text
stringlengths 2
6.14k
|
|---|
import React, {Component} from 'react';
import {connect} from 'react-redux';
import Button from "../../../../../components/buttons/button";
import {Link} from "react-router-dom";
import {firebaseResetPasswordRequest} from "../../../../../redux/firebase/actions/reset-password.action";
class ResetPasswordForm extends Component{
componentDidMount(){
document.title = "Restore Password";
}
handleResetPassword = (e) =>{
e.preventDefault();
const {resetPassword, resetPass_email} = this.props;
resetPassword(resetPass_email);
};
render() {
const {handleInputChange, resetPass_email} = this.props;
return (
<form action="">
<div className="input-wrapper">
<label htmlFor="resetPass_email">E-mail:</label>
<input id="resetPass_email"
type="text"
onChange={handleInputChange}
value={resetPass_email}/>
</div>
<div className="button-wrapper">
<Button text="Reset password"
handleClick={(e) => this.handleResetPassword(e, resetPass_email)}
requiresAuth={false}
type="submit--light"/>
<Link to="/sign-in">Cancel</Link>
</div>
</form>
)
}
}
const mapStateToProps = state => {
const {resetPass_email} = state.entry;
return {resetPass_email};
};
const mapDispatchToProps = dispatch => {
return {
resetPassword: payload => dispatch(firebaseResetPasswordRequest(payload))
}
};
export default connect(mapStateToProps, mapDispatchToProps)(ResetPasswordForm);
|
function ReportRowProvider()
{
var that = this;
var mXHR = new XHR();
var mFetchListeners = [];
var mReportId = "";
var mCriteriaText = "";
this.addFetchListener = function(address) { mFetchListeners.push(address); };
this.getReportId = function() { return mReportId; };
this.setReportId = function(value) { mReportId = value; };
this.getCriteriaText = function() { return mCriteriaText; };
this.setCriteriaText = function(value) { mCriteriaText = value; };
function getAddress()
{
var timeNow = new Date();
var result = "ReportRows.json?rep=" + mReportId; // time parameter no longer required, server now sends cache-control header
if(mCriteriaText !== null && mCriteriaText.length > 0) result += mCriteriaText;
return result;
};
this.startFetchingRows = function()
{
mXHR.beginSend("get", getAddress(), null, null, 60000, fetchHandler);
};
function fetchHandler(status, responseText)
{
var response = null;
if (status !== 200) response = { errorText: "ADS-B Radar Server 返回状态 " + status };
else {
responseText = replaceDateConstructors(responseText);
response = eval('(' + responseText + ')');
}
for(var i = 0;i < mFetchListeners.length;++i) mFetchListeners[i](response);
};
}
|
/**
* Objects implementing the NamedNodeMap interface are used to represent collections of nodes that can be accessed by name. Note that NamedNodeMap does not inherit from NodeList; NamedNodeMaps are not maintained in any particular order. Objects contained in an object implementing NamedNodeMap may also be accessed by an ordinal index, but this is simply to allow convenient enumeration of the contents of a NamedNodeMap, and does not imply that the DOM specifies an order to these Nodes.
* NamedNodeMap objects in the DOM are live.
* used for attributes or DocumentType entities
*
* @class tesla.xml.NamedNodeMap
* @extends tesla.xml.NodeList
* @createTime 2012-01-18
* @author louis.tru <louis.tru@gmail.com>
* @copyright (C) 2011 louis.tru, http://mooogame.com
* Released under MIT license, http://license.mooogame.com
* @version 1.0
*/
include('tesla/xml/DOMException.js');
var DOMException = tesla.xml.DOMException;
var NodeList = tesla.xml.NodeList;
function findNodeIndex(_this, node) {
var i = _this.length;
while (i--) {
if (_this[i] == node) { return i }
}
}
function add(_this, node, old) {
if (old) {
_this[findNodeIndex(_this, old)] = node;
} else {
_this[_this.length++] = node;
}
var el = _this._ownerElement;
var doc = el && el.ownerDocument;
if (doc)
node.ownerElement = el;
return old || null;
}
Class('tesla.xml.NamedNodeMap', NodeList, {
getNamedItem: function(key) {
var i = this.length;
while (i--) {
var node = this[i];
if (node.nodeName == key)
return node;
}
},
setNamedItem: function(node) {
var old = this.getNamedItem(node.nodeName);
return add(this, node, old);
},
/* returns Node */
setNamedItemNS: function(node) {// raises: WRONG_DOCUMENT_ERR,NO_MODIFICATION_ALLOWED_ERR,INUSE_ATTRIBUTE_ERR
var old = this.getNamedItemNS(node.namespaceURI, node.localName);
return add(_this, node, old);
},
_removeItem: function(node) {
var i = this.length;
var lastIndex = i - 1;
while (i--) {
var c = this[i];
if (node === c) {
var old = c;
while (i < lastIndex) {
this[i] = this[++i]
}
this.length = lastIndex;
node.ownerElement = null;
var el = this._ownerElement;
var doc = el && el.ownerDocument;
return old;
}
}
},
/* returns Node */
removeNamedItem: function(key) {
var node = this.getNamedItem(key);
if (node) {
this._removeItem(node);
} else {
throw DOMException(DOMException.NOT_FOUND_ERR, new Error())
}
}, // raises: NOT_FOUND_ERR,NO_MODIFICATION_ALLOWED_ERR
//for level2
getNamedItemNS: function(namespaceURI, localName) {
var i = this.length;
while (i--) {
var node = this[i];
if (node.localName == localName && node.namespaceURI == namespaceURI) {
return node;
}
}
return null;
},
removeNamedItemNS: function(namespaceURI, localName) {
var node = this.getNamedItemNS(namespaceURI, localName);
if (node) {
this._removeItem(node);
} else {
throw DOMException(DOMException.NOT_FOUND_ERR, new Error())
}
}
});
|
import NativeObject from '../NativeObject';
import Widget from '../Widget';
import {JSX} from '../JsxProcessor';
export default class RadioButton extends Widget {
get _nativeType() {
return 'tabris.RadioButton';
}
_getXMLAttributes() {
return super._getXMLAttributes().concat([
['text', this.text],
['checked', this.checked]
]);
}
/** @this {import("../JsxProcessor").default} */
[JSX.jsxFactory](Type, attributes) {
const children = this.getChildren(attributes);
const normalAttributes = this.withoutChildren(attributes);
return super[JSX.jsxFactory](Type, this.withContentText(
normalAttributes,
children,
'text'
));
}
}
NativeObject.defineProperties(RadioButton.prototype, {
text: {type: 'string', default: ''},
checked: {type: 'boolean', nocache: true},
textColor: {type: 'ColorValue', default: 'initial'},
tintColor: {type: 'ColorValue', default: 'initial'},
checkedTintColor: {type: 'ColorValue', default: 'initial'},
font: {type: 'FontValue', default: 'initial'}
});
NativeObject.defineEvents(RadioButton.prototype, {
select: {native: true, changes: 'checked'}
});
|
/*
Language: Go
Author: Stephan Kountso aka StepLg <steplg@gmail.com>
Contributors: Evgeny Stepanischev <imbolk@gmail.com>
Description: Google go language (golang). For info about language
Website: http://golang.org/
Category: common, system
*/
function(hljs) {
var GO_KEYWORDS = {
keyword:
'break default func interface select case map struct chan else goto package switch ' +
'const fallthrough if range type continue for import return var go defer ' +
'bool byte complex64 complex128 float32 float64 int8 int16 int32 int64 string uint8 ' +
'uint16 uint32 uint64 int uint uintptr rune',
literal:
'true false iota nil',
built_in:
'append cap close complex copy imag len make new panic print println real recover delete'
};
return {
aliases: ['golang'],
keywords: GO_KEYWORDS,
illegal: '</',
contains: [
hljs.C_LINE_COMMENT_MODE,
hljs.C_BLOCK_COMMENT_MODE,
{
className: 'string',
variants: [
hljs.QUOTE_STRING_MODE,
{begin: '\'', end: '[^\\\\]\''},
{begin: '`', end: '`'},
]
},
{
className: 'number',
variants: [
{begin: hljs.C_NUMBER_RE + '[i]', relevance: 1},
hljs.C_NUMBER_MODE
]
},
{
begin: /:=/ // relevance booster
},
{
className: 'function',
beginKeywords: 'func', end: '\\s*(\\{|$)', excludeEnd: true,
contains: [
hljs.TITLE_MODE,
{
className: 'params',
begin: /\(/, end: /\)/,
keywords: GO_KEYWORDS,
illegal: /["']/
}
]
}
]
};
}
|
define(['App', 'underscore', 'backbone', 'jquery'], function(App, _, Backbone, $) {
return Backbone.Model.extend({
parseAsCommentMoreLink: function(data) {
if (data.children.length === 0) return null
data.childrenCount = data.children.length
if (data.childrenCount == 1) {
data.replyVerb = 'reply'
} else {
data.replyVerb = 'replies'
}
return data
},
parse: function(data) {
if (!data) {
return
}
if (typeof data.data !== 'undefined') {
//the data from getmorechildren comes in this format
data.data.kind = data.kind
data = data.data
}
if (data.kind === 'more') {
return this.parseAsCommentMoreLink(data)
}
var timeAgo = moment.unix(data.created_utc).fromNow(true) //"true" removes the "ago"
timeAgo = timeAgo.replace("in ", ''); //why would it add the word "in"
data.timeAgo = timeAgo
data.timeUgly = moment.unix(data.created_utc).format()
data.timePretty = moment.unix(data.created_utc).format("ddd MMM DD HH:mm:ss YYYY") + " UTC" //format Sun Aug 18 12:51:06 2013 UTC
//if the comment is edited format its last edited time
if (typeof data.edited !== 'undefined' && data.edited !== false) {
timeAgo = moment.unix(data.edited).fromNow(true) //"true" removes the "ago"
timeAgo = timeAgo.replace("in ", ''); //why would it add the word "in"
data.editedTimeAgo = timeAgo
}
data.score = +data.ups - parseInt(data.downs, 10)
data.scoreUp = +data.score + 1
data.scoreDown = +data.score - 1
if (data.likes === null) {
data.voted = 'unvoted'
data.downmod = 'down'
data.upmod = 'up'
} else if (data.likes === true) {
data.voted = "likes"
data.downmod = 'down'
data.upmod = 'upmod'
} else {
data.voted = "dislikes"
data.downmod = 'downmod'
data.upmod = 'up'
}
//for the user view we can have comments
if (typeof data.thumbnail !== 'undefined' && data.thumbnail == 'self') {
data.thumbnail = 'img/self.png'
} else if (data.thumbnail == 'nsfw') {
data.thumbnail = 'img/nsfw.png'
} else if (data.thumbnail === '' || data.thumbnail == 'default') {
data.thumbnail = 'img/notsure.png'
}
data.body_html = (typeof data.body_html === 'undefined') ? '' : $('<div/>').html(data.body_html).text();
var linkName = data.link_id.replace('t3_', '')
data.permalink = '/r/' + data.subreddit + '/comments/' + linkName + "/L/" + data.id
if (typeof data.replies !== "undefined" && data.replies !== null && typeof data.replies.data !== "undefined") {
// data.replies = parseComments(data.replies.data, data.link_id)
data.childrenCount = data.replies.data.length
if (data.replies.length == 1) {
data.childOrChildren = 'child'
} else {
data.childOrChildren = 'children'
}
} else {
data.childOrChildren = 'children'
data.childrenCount = 0
}
return data
}
});
});
|
BaseExporter = function () {};
BaseExporter.prototype = {};
function niceWrite (writeStream, toWrite) {
// NOTE: might need to break toWrite into multiple strings
if (toWrite.length > 10000) {
console.log("break toWrite into multiple strings");
}
var keepWriting = writeStream.write(toWrite);
if (keepWriting) {
// return a promise that has already been resolved
// any .then()s connected to this will fire immidiately
return Q();
}
// waits until the stream has drained, then resolves
return new Q.Promise(function (resolve) {
writeStream.once("drain", resolve);
});
}
BaseExporter.prototype.run = function (destination, options) {
var self = this;
return new Q.Promise(function (resolve, reject) {
// make sure it's being called with new keyword
if (!self.init) {
console.log("not called with new keyword");
throw new Error("not called with new keyword");
}
self.init.call(self, options);
self.writeStream = createWriteStream(destination);
var lineNumber = 1; // careful: starts at 1
function writeNextLine () {
var chunks = [];
var lineMaybePromise = self.getLine.call(self, function (chunk) {
chunks.push(chunk);
}, lineNumber);
Q(lineMaybePromise)
.then(function () {
if (chunks.length) {
lineNumber++;
// write all chunks, wait for drain (if necessary), call itself
niceWrite(self.writeStream, chunks.join("") + "\n")
.then(writeNextLine)
.catch(reject);
} else {
// end the write stream, close the file
self.writeStream.end(resolve);
}
});
}
writeNextLine(); // kick off the writing
});
};
BaseExporter.prototype.init = function (write, lineNumber) {
throw new Error("init not overridden");
};
BaseExporter.prototype.getLine = function (write, lineNumber) {
throw new Error("getLine not overridden");
};
|
import { put, select, takeEvery } from 'redux-saga/effects'
import { getQuotes } from './quotes'
import { has, toArray } from 'lodash'
import { createAuthor, removeAuthor, updateAuthor } from "./authors";
import { createCategory, removeCategory, updateCategory } from "./categories";
import { createTag, removeTag, updateTag } from "./tags";
const FILTER_CHANGED = 'FILTER_CHANGED'
const SEARCH_CHANGED = 'SEARCH_CHANGED'
const initialState = {
categories: new Set(),
authors: new Set(),
tags: new Set(),
search: null,
snapshot: {
categories: new Set(),
authors: new Set(),
tags: new Set(),
search: null,
}
}
export function reducer(state = initialState, action = {}) {
switch (action.type) {
case FILTER_CHANGED:
const id = action.payload.value
const field = action.payload.field
const checked = action.payload.checked
let newState
if (checked) {
const newSet = new Set(state[field])
newSet.add(id)
newState = newSet
} else {
const newSet = new Set(state[field])
newSet.delete(id)
newState = newSet
}
return {
...state,
[field]: newState
}
case SEARCH_CHANGED:
return {
...state,
search: action.payload.value
}
case 'SET_FILTERS':
return {
...state,
...action.payload
}
default:
return state
}
}
export function* handleFilterChange() {
const filters = yield select((state) => state.filters)
const routing = yield select((state) => state.routing)
const params = {
category: toArray(filters.categories),
author: toArray(filters.authors),
tags: toArray(filters.tags),
search: filters.search,
user__username: has(routing.match.params, 'username') ? routing.match.params.username : null
}
yield put(getQuotes(params))
}
export function* saga() {
yield takeEvery(FILTER_CHANGED, handleFilterChange)
yield takeEvery(SEARCH_CHANGED, handleFilterChange)
}
export const changeFilter = (field, value, checked) => ({
type: FILTER_CHANGED,
payload: {field, value, checked}
})
export const changeSearch = (value) => ({
type: SEARCH_CHANGED,
payload: {value}
})
export const createFilter = (type, data) => {
switch (type) {
case 'authors':
return createAuthor(data)
case 'categories':
return createCategory(data)
case 'tags':
return createTag(data)
default:
return null
}
}
export const updateFilter = (type, data) => {
switch (type) {
case 'authors':
return updateAuthor(data)
case 'categories':
return updateCategory(data)
case 'tags':
return updateTag(data)
default:
return null
}
}
export const removeFilter = (type, data) => {
switch (type) {
case 'authors':
return removeAuthor(data)
case 'categories':
return removeCategory(data)
case 'tags':
return removeTag(data)
default:
return null
}
}
|
var RecipeReport = (function () {
"use strict";
var standartThaaliCount = 100;
var sum = function(array, prop) {
return array.reduce( function(a, b){
return a + b[prop];
}, 0);
};
var recipeReport = function (data, fromDate, toDate, recipe) {
this.data = data;
this.fromDate = fromDate;
this.toDate = toDate;
this.recipe = recipe;
};
recipeReport.prototype.run = function() {
var d = {};
d.dateWiseReport = this.getDateWiseReport();
d.ingredientWiseAverage = this.getIngredientWiseAverage();
return d;
};
recipeReport.prototype.matchCriteria = function(meal) {
return meal.recipe === this.recipe
&& meal.date<=this.toDate
&& meal.date>=this.fromDate;
};
recipeReport.prototype.getDateWiseReport = function() {
var report = [];
for (var i = this.data.length - 1; i >= 0; i--) {
var meal = this.data[i];
if(this.matchCriteria(meal)) {
var cost = sum(meal.ingredients, 'amount');
report.push({
date: meal.date,
noOfThaalis: meal.noOfThaalis,
//total cost of recipe made on this date
perThaaliCost: (cost/meal.noOfThaalis) * standartThaaliCount,
totalCost: cost
});
}
}
return report;
};
recipeReport.prototype.getIngredientWiseAverage = function() {
var report = {};
var faulty = {};
var isFaulty = false;
for (var i = this.data.length - 1; i >= 0; i--) {
var meal = this.data[i];
if(this.matchCriteria(meal)) {
for (var k = meal.ingredients.length - 1; k >= 0; k--) {
var ingredient = meal.ingredients[k];
var name = ingredient.item.toLowerCase();
report[name] = report[name] || {};
report[name].qty = report[name].qty || 0;
report[name].qty+= ingredient.qty;
if((report[name].unit !== undefined && report[name].unit !== ingredient.unit)) {
fault[ingredient.item.toLowerCase() + '-' + meal.date] = fault[ingredient.item.toLowerCase() + '-' + meal.date] || 0;
fault[ingredient.item.toLowerCase() + '-' + meal.date] += 1;
isFaulty = true;
}
report[name].unit = ingredient.unit;
report[name].amount = report[name].amount || 0;
report[name].amount += ingredient.amount;
report[name].count = report[name].count || 0;
report[name].count++;
}
}
}
var finalReport = [];
for (var prop in report) {
finalReport.push({
"IngredientName": prop,
"Quantity": report[prop].qty/report[prop].count,
"Unit": report[prop].unit,
"PerUnitCost": report[prop].amount/report[prop].qty,
"Amount": report[prop].amount/report[prop].count
});
}
if(isFaulty) {
console.log(faulty);
//TODO add details for faulty items
alert('Different units specified for same ingredient on saperate days. Invalid data. Please see what\'s wrong. Or contact maker of this application');
}
return finalReport;
};
return recipeReport;
})();
|
var fs = require("fs");
var express = require("express"),
optimist = require("optimist"),
gitstatic = require("../");
var argv = optimist.usage("Usage: $0")
.options("h", {
alias: "help",
describe: "display this help text"
})
.options("repository", {
default: ".git",
describe: "path to bare git repository"
})
.options("port", {
default: 3000,
describe: "http port"
})
.check(function(argv) {
if (argv.help) throw "";
try { var stats = fs.statSync(argv.repository); } catch (e) { throw "Error: " + e.message; }
if (!stats.isDirectory()) throw "Error: invalid --repository directory.";
})
.argv;
var server = express();
server.get(/^\/.*/, gitstatic.route()
.repository(argv.repository));
server.listen(argv.port);
|
$(document).ready(function() {
$.viewMap = {
'install' : $('#coordinator_row'),
'repair' : $('#barcode_row, #equipment_row')
};
$('#coordinator_row').hide();
$('#id_work_type').change(function() {
// hide all
$.each($.viewMap, function() { this.hide(); });
// show current
$.viewMap[$(this).val()].show();
});
});
|
jQuery(document).ready(function(){
var numSaves, _autoSaveChanges;
module("TiddlyWiki options", {
setup: function() {
config.options.chkAutoSave = true;
systemSettingSave = 0;
_autoSaveChanges = autoSaveChanges;
numSaves = 0;
autoSaveChanges = function() {
numSaves += 1;
return _autoSaveChanges.apply(this, arguments);
}
},
teardown: function() {
numSaves = null;
config.options.chkAutoSave = false;
autoSaveChanges = _autoSaveChanges;
}
});
test("save multiple system settings", function() {
saveSystemSetting("foo", true);
saveSystemSetting("foo", false);
saveSystemSetting("foo", true);
strictEqual(numSaves, 0, "The save is asynchronous so no saves have yet been made");
strictEqual(systemSettingSave > 0, true, "However there should be a timeout in progress");
});
});
|
import React from 'react';
import { compose } from 'react-apollo';
import autoBind from 'react-autobind';
// graphql
import textNodesQuery from '../../../textNodes/graphql/queries/textNodesQuery';
// components
import CommentLemma from '../../components/CommentLemma';
import LoadingLemma from '../../../../components/loading/LoadingLemma';
// lib
import Utils from '../../../../lib/utils';
import getCurrentSubdomain from '../../../../lib/getCurrentSubdomain';
import defaultWorksEditions from '../../lib/defaultWorksEditions';
class CommentLemmaContainer extends React.Component {
constructor(props) {
super(props);
this.state = {
selectedLemmaVersionIndex: null,
selectedTranslationVersionIndex: null,
};
autoBind(this);
}
toggleVersion(versionId) {
const { selectedLemmaVersionIndex } = this.state;
let textNodes = [];
let versions = [];
if (
this.props.textNodesQuery
&& this.props.textNodesQuery.textNodes
) {
textNodes = this.props.textNodesQuery.textNodes;
}
if (textNodes && textNodes.length) {
const allVersions = Utils.textFromTextNodesGroupedByVersion(textNodes);
versions = allVersions.versions;
}
if (versions && versions.length) {
if (
selectedLemmaVersionIndex === null
|| versions[selectedLemmaVersionIndex].id !== versionId
) {
let newSelectedVersionIndex = 0;
versions.forEach((version, index) => {
if (version.id === versionId) {
newSelectedVersionIndex = index;
}
});
this.setState({
selectedLemmaVersionIndex: newSelectedVersionIndex,
});
}
}
}
render() {
const { commentGroup, multiline } = this.props;
const { selectedLemmaVersionIndex } = this.state;
const subdomain = getCurrentSubdomain();
let textNodes = [];
let versionsWithText = [];
let translationsWithText = [];
let selectedLemmaVersion = { textNodes: [] };
let selectedTranslationVersion = { textNodes: [] };
if (this.props.textNodesQuery.loading) {
return <LoadingLemma />
}
// text nodes data
if (
this.props.textNodesQuery
&& this.props.textNodesQuery.textNodes
) {
textNodes = this.props.textNodesQuery.textNodes;
}
// TODO: potentially structure data from backend to prevent this transformation
// in the future
// set versions from textnodes data
if (textNodes && textNodes.length) {
const allVersions = Utils.textFromTextNodesGroupedByVersion(textNodes);
versionsWithText = allVersions.versions;
translationsWithText = allVersions.translations;
}
// if necessary, parse versions into multiline data
versionsWithText = multiline ?
Utils.parseMultilineVersion(versionsWithText, multiline)
:
versionsWithText;
// set selected version
if (versionsWithText.length) {
if (
selectedLemmaVersionIndex !== null
&& versionsWithText[selectedLemmaVersionIndex]
) {
selectedLemmaVersion = versionsWithText[selectedLemmaVersionIndex];
} else {
selectedLemmaVersion = versionsWithText.find(version => (version.urn === defaultWorksEditions[subdomain].defaultVersionUrn));
}
}
return (
<CommentLemma
commentGroup={commentGroup}
versions={versionsWithText}
translations={translationsWithText}
selectedLemmaVersion={selectedLemmaVersion}
selectedTranslationVersion={selectedTranslationVersion}
showContextPanel={this.props.showContextPanel}
index={this.props.index}
setScrollPosition={this.props.setScrollPosition}
hideLemma={this.props.hideLemma}
selectMultiLine={this.props.selectMultiLine}
multiline={this.props.multiline}
toggleVersion={this.toggleVersion}
lemmaCitation={this.props.lemmaCitation}
/>
);
}
}
export default compose(
textNodesQuery,
)(CommentLemmaContainer);
|
version https://git-lfs.github.com/spec/v1
oid sha256:eb830b3ada371c6f6af6bd512f864699a8123c5922f0376292ece99b8fc9e602
size 105460
|
import _ from 'lodash'
import URLJoin from 'url-join'
import request from 'request'
import bitcore from 'bitcore-lib'
import config from './config'
import logger from './logger'
/**
* @typedef {Object} Insight~UnspentObject
* @property {string} address
* @property {string} txId
* @property {number} outputIndex
* @property {string} script
* @property {number} satoshis
*/
/**
* @class Insight
*/
export default class Insight {
/**
* @constructor
*/
constructor () {
this._insightURL = config.get('insight.url')
this._requestTimeout = config.get('insight.timeout')
}
/**
* @private
* @param {Object} opts
* @return {Promise<Object>}
*/
async _request (opts) {
return new Promise((resolve, reject) => {
opts = _.extend({
method: 'GET',
timeout: this._requestTimeout,
json: true,
zip: true
}, opts)
logger.verbose(`Make request: ${opts.uri}`)
request(opts, (err, response) => {
if (err === null) {
if (response.statusCode === 200) {
return resolve(response)
}
err = new Error(`Expected statusCode is 200, got ${response.statusCode} (body: ${response.body})`)
}
reject(err)
})
})
}
/**
* @return {string}
*/
getURL () {
return this._insightURL
}
/**
* @param {string[]} addresses
* @return {Promise<Insight~UnspentObject[]>}
*/
async getUnspent (addresses) {
logger.verbose(`getUnspent for addresses: ${addresses}`)
let response = await this._request({
uri: URLJoin(this._insightURL, 'addrs', addresses.join(','), 'utxo')
})
return response.body.map((item) => {
return {
address: item.address,
txId: item.txid,
outputIndex: item.vout,
script: item.scriptPubKey,
satoshis: bitcore.Unit.fromBTC(item.amount).toSatoshis()
}
})
}
/**
* @param {bitcore.Transaction} tx
* @return {Promise}
*/
async sendTx (tx) {
let rawTx = tx.serialize()
logger.verbose(`sendTx ${tx.id} (size: ${rawTx.length / 2})`)
await this._request({
method: 'POST',
uri: URLJoin(this._insightURL, '/tx/send'),
json: {rawtx: rawTx}
})
}
}
|
(function(exports) {
"use strict";
exports.dontIgnoreComposerLockFile = function(grunt, init, done) {
grunt.verbose.write("Removing composer.lock from .gitignore.");
var content = grunt.file.read('build/.gitignore').replace(/composer.lock[\r\n]/m, '');
grunt.file.write('build/.gitignore', content);
grunt.verbose.ok();
done();
};
})(typeof exports === 'object' && exports || this);
|
import core from 'core-js';
import * as LogManager from 'aurelia-logging';
import {Metadata} from 'aurelia-metadata';
var logger = LogManager.getLogger('aurelia');
function loadPlugin(aurelia, loader, info){
logger.debug(`Loading plugin ${info.moduleId}.`);
aurelia.currentPluginId = info.moduleId;
return loader.loadModule(info.moduleId).then(m => {
if('configure' in m){
return Promise.resolve(m.configure(aurelia, info.config || {})).then(() => {
aurelia.currentPluginId = null;
logger.debug(`Configured plugin ${info.moduleId}.`);
});
}else{
aurelia.currentPluginId = null;
logger.debug(`Loaded plugin ${info.moduleId}.`);
}
});
}
/**
* Manages loading and configuring plugins.
*
* @class Plugins
* @constructor
* @param {Aurelia} aurelia An instance of Aurelia.
*/
export class Plugins {
constructor(aurelia){
this.aurelia = aurelia;
this.info = [];
this.processed = false;
}
/**
* Configures a plugin before Aurelia starts.
*
* @method plugin
* @param {moduleId} moduleId The ID of the module to configure.
* @param {config} config The configuration for the specified module.
* @return {Plugins} Returns the current Plugins instance.
*/
plugin(moduleId, config){
var plugin = {moduleId:moduleId, config:config || {}};
if(this.processed){
loadPlugin(this.aurelia, this.aurelia.loader, plugin);
}else{
this.info.push(plugin);
}
return this;
}
_process(){
var aurelia = this.aurelia,
loader = aurelia.loader,
info = this.info,
current;
if(this.processed){
return;
}
var next = () => {
if(current = info.shift()){
return loadPlugin(aurelia, loader, current).then(next);
}
this.processed = true;
return Promise.resolve();
};
return next();
}
}
|
var searchData=
[
['uniquecount',['UniqueCount',['../class_standard_trie_1_1cs_1_1_prefix_trie.html#a82986e28b3191486a98cf874a1ae1b06',1,'StandardTrie::cs::PrefixTrie']]]
];
|
/*
* RegExp instance properties.
*
* RegExp instance 'source' property must behave as specified in E5 Section
* 15.10.4.1 paragraphcs 5 and 6. Note: there is no one required form of source.
* Tests are for the source form that we want.
*/
/*
* FIXME: when does '\' in source need to be escaped?
*/
/*
* FIXME: add property attribute checks
*/
function getflags(r) {
var res = ''
if (r.global) {
res += 'g';
}
if (r.ignoreCase) {
res += 'i';
}
if (r.multiline) {
res += 'm';
}
return res;
}
/*
* Empty string
*/
/*===
(?:)
===*/
try {
t = new RegExp('');
print(t.source);
t = eval('/' + t.source + '/' + getflags(t));
t = t.exec('');
print(t[0]);
} catch (e) {
print(e.name);
}
/*
* Forward slash
*/
/*===
\/
/
===*/
try {
t = new RegExp('/'); /* matches one forward slash (only) */
print(t.source);
t = eval('/' + t.source + '/' + getflags(t));
t = t.exec('/');
print(t[0]);
} catch (e) {
print(e.name);
}
/*
* Backslash
*/
/*===
\d
9
===*/
try {
t = new RegExp('\\d'); /* matches a digit */
print(t.source);
t = eval('/' + t.source + '/' + getflags(t));
t = t.exec('9');
print(t[0]);
} catch (e) {
print(e.name);
}
/*
* Flags
*/
/*===
foo false true false
foo false true false
Foo
foo true false false
foo true false false
foo false false true
foo false false true
===*/
try {
t = new RegExp('foo', 'i');
print(t.source, t.global, t.ignoreCase, t.multiline);
t = eval('/' + t.source + '/' + getflags(t));
print(t.source, t.global, t.ignoreCase, t.multiline);
t = t.exec('Foo');
print(t[0]);
} catch (e) {
print(e.name);
}
try {
t = new RegExp('foo', 'g');
print(t.source, t.global, t.ignoreCase, t.multiline);
t = eval('/' + t.source + '/' + getflags(t));
print(t.source, t.global, t.ignoreCase, t.multiline);
} catch (e) {
print(e.name);
}
try {
t = new RegExp('foo', 'm');
print(t.source, t.global, t.ignoreCase, t.multiline);
t = eval('/' + t.source + '/' + getflags(t));
print(t.source, t.global, t.ignoreCase, t.multiline);
} catch (e) {
print(e.name);
}
/*
* lastIndex
*/
/*===
0
===*/
try {
t = new RegExp('foo', 'i');
print(t.lastIndex);
} catch (e) {
print(e.name);
}
|
version https://git-lfs.github.com/spec/v1
oid sha256:ac9e4d0cf97f46d8fcb1545ff017272b57a2c9a45f74cc1e57792311dd060f6e
size 603
|
import {HttpClientConfiguration} from './http-client-configuration';
import {RequestInit, Interceptor} from './interfaces';
import 'core-js';
/**
* An HTTP client based on the Fetch API.
*
* @constructor
*/
export class HttpClient {
activeRequestCount: number = 0;
isRequesting: boolean = false;
interceptors: Interceptor[] = [];
isConfigured: boolean = false;
baseUrl: string = '';
defaults: RequestInit = null;
/**
* Configure this client with default settings to be used by all requests.
*
* @param config - A function that takes a config argument,
* or a config object, or a string to use as the client's baseUrl.
* @chainable
*/
configure(config: string|RequestInit|(config: HttpClientConfiguration) => void): HttpClient {
let normalizedConfig;
if (typeof config === 'string') {
normalizedConfig = { baseUrl: config };
} else if (typeof config === 'object') {
normalizedConfig = { defaults: config };
} else if (typeof config === 'function') {
normalizedConfig = new HttpClientConfiguration();
config(normalizedConfig);
} else {
throw new Error('invalid config');
}
let defaults = normalizedConfig.defaults;
if (defaults && defaults.headers instanceof Headers) {
// Headers instances are not iterable in all browsers. Require a plain
// object here to allow default headers to be merged into request headers.
throw new Error('Default headers must be a plain object.');
}
this.baseUrl = normalizedConfig.baseUrl;
this.defaults = defaults;
this.interceptors.push(...normalizedConfig.interceptors || []);
this.isConfigured = true;
return this;
}
/**
* Starts the process of fetching a resource. Default configuration parameters
* will be applied to the Request. The constructed Request will be passed to
* registered request interceptors before being sent. The Response will be passed
* to registered Response interceptors before it is returned.
*
* See also https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
*
* @param input - The resource that you wish to fetch. Either a
* Request object, or a string containing the URL of the resource.
* @param - An options object containing settings to be applied to
* the Request.
*/
fetch(input: Request|string, init?: RequestInit): Promise<Response> {
this::trackRequestStart();
let request = Promise.resolve().then(() => this::buildRequest(input, init, this.defaults));
let promise = processRequest(request, this.interceptors)
.then(result => {
let response = null;
if (result instanceof Response) {
response = result;
} else if (result instanceof Request) {
response = fetch(result);
} else {
throw new Error(`An invalid result was returned by the interceptor chain. Expected a Request or Response instance, but got [${result}]`);
}
return processResponse(response, this.interceptors);
});
return this::trackRequestEndWith(promise);
}
}
function trackRequestStart() {
this.isRequesting = !!(++this.activeRequestCount);
}
function trackRequestEnd() {
this.isRequesting = !!(--this.activeRequestCount);
}
function trackRequestEndWith(promise) {
let handle = this::trackRequestEnd;
promise.then(handle, handle);
return promise;
}
function buildRequest(input, init = {}) {
let defaults = this.defaults || {};
let source;
let url;
let body;
if (input instanceof Request) {
if (!this.isConfigured) {
// don't copy the request if there are no defaults configured
return input;
}
source = input;
url = input.url;
body = input.blob();
} else {
source = init;
url = input;
body = init.body;
}
let requestInit = Object.assign({}, defaults, source, { body });
let request = new Request((this.baseUrl || '') + url, requestInit);
setDefaultHeaders(request.headers, defaults.headers);
return request;
}
function setDefaultHeaders(headers, defaultHeaders) {
for (let name in defaultHeaders || {}) {
if (defaultHeaders.hasOwnProperty(name) && !headers.has(name)) {
headers.set(name, defaultHeaders[name]);
}
}
}
function processRequest(request, interceptors) {
return applyInterceptors(request, interceptors, 'request', 'requestError');
}
function processResponse(response, interceptors) {
return applyInterceptors(response, interceptors, 'response', 'responseError');
}
function applyInterceptors(input, interceptors, successName, errorName) {
return (interceptors || [])
.reduce((chain, interceptor) => {
let successHandler = interceptor[successName];
let errorHandler = interceptor[errorName];
return chain.then(
successHandler && interceptor::successHandler,
errorHandler && interceptor::errorHandler);
}, Promise.resolve(input));
}
|
export * from './aurelia-pal-worker';
|
const validate = (value, options) => {
if (Array.isArray(value)) {
return value.every(val => validate(val, options));
}
// eslint-disable-next-line
return ! options.filter(option => option == value).length;
};
export default validate;
|
version https://git-lfs.github.com/spec/v1
oid sha256:8b057c8d60d76759e6a75285bd1fcea8ba4acea65ffe3b8e5ff4a1937cb3dacd
size 2530
|
import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";
export default createSvgIcon([/*#__PURE__*/_jsx("path", {
d: "m8 6.83-4 4V18h3v-3h2v3h3v-7.17l-4-4zM9 13H7v-2h2v2z",
opacity: ".3"
}, "0"), /*#__PURE__*/_jsx("path", {
d: "m8 4-6 6v10h12V10L8 4zm4 14H9v-3H7v3H4v-7.17l4-4 4 4V18zm-3-5H7v-2h2v2zm9 7V8.35L13.65 4h-2.83L16 9.18V20h2zm4 0V6.69L19.31 4h-2.83L20 7.52V20h2z"
}, "1")], 'HolidayVillageTwoTone');
|
import Binding from 'virtualdom/items/Element/Binding/Binding';
import handleDomEvent from 'virtualdom/items/Element/Binding/shared/handleDomEvent';
var CheckboxBinding = Binding.extend({
name: 'checked',
render: function () {
var node = this.element.node;
node.addEventListener( 'change', handleDomEvent, false );
if ( node.attachEvent ) {
node.addEventListener( 'click', handleDomEvent, false );
}
},
unrender: function () {
var node = this.element.node;
node.removeEventListener( 'change', handleDomEvent, false );
node.removeEventListener( 'click', handleDomEvent, false );
},
getValue: function () {
return this.element.node.checked;
}
});
export default CheckboxBinding;
|
var fs = require('fs');
var path = require('path');
var md_parser = require('./md_parser');
var $ = require('./helper');
var rootDir = path.join(__dirname, '../') + path.sep;
var assetsDir = path.join(rootDir, 'assets') + path.sep;
var templateDir = path.join(rootDir, 'template') + path.sep;
//1. 只导出文件nodeppt generate file.md
//2. 导出文件+目录 nodeppt generate ./ --all -o publish
module.exports = function(filepath, outputDir, isAll) {
filepath = fs.realpathSync(filepath);
outputDir = outputDir ? $.getDirPath(outputDir) : $.getDirPath(path.join(process.cwd(), './publish'));
isAll = !!isAll;
if (isAll) {
//1.导出assets
$.copy(assetsDir, outputDir, function(filename, dir, subdir) {
if (!subdir || subdir === 'scss') {
//不复制scss
return false;
}
return true;
});
}
//2.导出复制filepath除根目录下img、css和js等到assets,遇见/*.md就解析
generate(filepath, outputDir);
console.log('生成结束!'.bold.green + require('path').relative('b:/', outputDir).yellow);
};
function parser(content, template) {
try {
var html = md_parser(content, null, null, null, {
generate: true
});
return html;
} catch (e) {
console.log('ERROR: '.bold.red + e.toString());
}
return false;
}
/**
* 生成
* @param {[type]} filepath [description]
* @param {[type]} outputDir [description]
* @return {[type]} [description]
*/
function generate(filepath, outputDir) {
var filename = '';
var templateMd = $.readFile(templateDir + 'markdown.ejs');
var templateList = $.readFile(templateDir + 'list.ejs');
if ($.isDir(filepath, true)) {
//遍历目录生成htm
var indexList = '';
$.copy(filepath, outputDir, function(filename, dir, subdir) {
if (!subdir && /\.(?:md|markdown)$/i.test(filename)) {
var content = $.readFile(path.join(filepath, filename));
var html = parser(content);
if (html) {
var title = html.match(/<title>(.*?)<\/title>/);
if (title[1]) {
title = title[1];
} else {
title = filename;
}
var url = filename.replace(/\.(?:md|markdown)$/i, '.htm');
indexList += '<li><a class="star" href="' + url + '" target="_blank">' + title + '</a> [<a href="' + url + '?_multiscreen=1" target="_blank" title="多窗口打开">多窗口</a>]</li>';
copyLinkToOutput(content, filepath, outputDir);
html = handlerHTML(html);
$.writeFile(path.join(outputDir, filename.replace(/\.(?:md|markdown)$/i, '.htm')), html);
}
return false;
}
return true;
});
//输出index文件
var packageJson = require(rootDir + 'package.json');
var data = {
version: packageJson.version,
site: packageJson.site,
date: Date.now(),
list: indexList,
dir: '/'
};
indexList = $.renderStr(templateList, data);
$.writeFile(path.join(outputDir, 'index.html'), indexList);
} else {
var content;
if ($.exists(filepath)) {
content = $.readFile(filepath);
} else {
return console.log('ERROR: '.bold.red + filepath + ' is not exists!');
}
filename = path.basename(filepath);
copyLinkToOutput(content, filepath, outputDir);
var html = parser(content);
if (html) {
html = handlerHTML(html);
$.writeFile(path.join(outputDir, filename.replace(/\.(?:md|markdown)$/i, '.htm')), html);
}
}
}
//处理绝对路径的url
function handlerHTML(html) {
html = html.replace(/([src|href])=["']\//gi, '$1="./')
.replace("loadJS('/js", "loadJS('./js").replace("dir: '/js/',", "dir: './js/',");
return html;
}
//处理页面相对url,到目标文件夹
function copyLinkToOutput(content, filepath, outputDir) {
//[inline模式](/assets/box-fe-road/img/inline-mode.png)
var files = [];
content.replace(/\[.+?\]\(\s?(.*?)\s?\)/g, function(i, file) {
files.push(file);
}).replace(/href=(['"])(.+?)\1/g, function(i, q, file) {
files.push(file);
});
//解析cover
var json = md_parser.parseCover(content.split(/\[slide.*\]/i)[0]);
if (json.files) {
files = files.concat(json.files.split(/\s?,\s?/));
}
files.filter(function(f) {
return !/^http[s]?:\/\//.test(f);
}).forEach(function(f) {
var topath = path.join(outputDir, f);
var realpath = path.join(path.dirname(filepath), f);
if ($.exists(realpath)) {
var data = fs.readFileSync(String(realpath));
$.writeFile(topath, data);
}
});
}
|
/**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import { AppRegistry } from 'react-native';
import Navigation from './app/config/entry';
export default class RNJueJin extends Component {
render() {
return (
<Navigation />
);
}
}
AppRegistry.registerComponent('RNJueJin', () => RNJueJin);
|
'use strict';
module.exports = ({ strapi }) => ({
getWelcomeMessage() {
return 'Welcome to Strapi 🚀';
},
});
|
/* */
(function(Buffer) {
var crypto = require("crypto");
var sign = require("./sign");
var m = new Buffer('AF2BDBE1AA9B6EC1E2ADE1D694F41FC71A831D0268E9891562113D8A62ADD1BF', 'hex');
var xbuf = new Buffer('009A4D6792295A7F730FC3F2B49CBC0F62E862272F', 'hex');
var bn = require("bn.js");
var x = new bn(xbuf);
var q = new Buffer('04000000000000000000020108A2E0CC0D99F8A5EF', 'hex');
var qbuf = new Buffer('04000000000000000000020108A2E0CC0D99F8A5EF', 'hex');
var q = new bn(qbuf);
var kv = sign.getKay(x, q, m, 'sha256', crypto);
var k = sign.makeKey(q, kv, 'sha256', crypto);
console.log('k', k);
})(require("buffer").Buffer);
|
;(function () {
var defaults = {
"wrap": "this",//下拉列表用什么包裹,"this"为按钮自身,主流的插件放在"body"中
"data": null,
"formName": "",
"zIndex": 999
};
function Dropdown(opt) {
var $this = $(this),
id = $this.attr("id"),
height = $this.outerHeight(),
name = !!opt.formName ? opt.formName : id,
liArray = [],
aTop = height / 2 - 3;
$this.css("position", "relative").append("<i class='dropdown_arrow' style='top:" + aTop + "px; right:10px'></i>");
if ($this.find("span").length < 1) {
$this.append("<span></span>");
}
$this.append("<input type='hidden' name='" + name + "'>");
if ($(".dropdown_menu[data-target='#" + id + "']").length < 1 && !!opt.data) {
var wrap;
if (opt.wrap == "this") {
wrap = $this
} else {
wrap = $(opt.wrap)
}
wrap.append("<ul class='dropdown_menu' data-target='#" + id + "'></ul>")
}
var $menu = $(".dropdown_menu[data-target='#" + id + "']").hide().css({"position": "absolute", "zIndex": opt.zIndex});
if (!!opt.data) {
for (var i = 0; i < opt.data.length; i++) {
liArray.push("<li data-text='" + opt.data[i].text + "' data-value='" + opt.data[i].value + "' >" + opt.data[i].text + "</li>");
}
$menu.html(liArray.join(""));
}
BindEvents($this, $menu, true);
}
function Reload(data) {
var $this = $(this),
id = $this.attr("id"),
$menu = $(".dropdown_menu[data-target='#" + id + "']"),
liArray = [];
if (typeof data != "object") {
return
}
for (var i = 0; i < data.length; i++) {
liArray.push("<li data-text='" + data[i].text + "' data-value='" + data[i].value + "' >" + data[i].text + "</li>");
}
$menu.html(liArray.join(""));
BindEvents($this, $menu, false);
}
function setValue(text, value) {
var $this = $(this);
$this.data("value", value).find("span:eq(0)").html(text).end().find("input:hidden").val(value);
}
function setDisable (val){
}
function BindEvents($this, $menu, init) {
if(init){
$("body").on("click",function(){
$menu.hide();
});
}
$this.off("click").on("click", function () {
var width = $this.outerWidth(),
height = $this.outerHeight(),
offset = $this.offset();
var border = parseInt($menu.css("borderLeftWidth")) + parseInt($menu.css("borderRightWidth"));
var padding = parseInt($menu.css("paddingLeft")) + parseInt($menu.css("paddingRight"));
$menu.css({"width": (width - border - padding), "top": offset.top + height, "left": offset.left}).show();
$this.trigger("dropdown.show");
return false;
});
$menu.delegate("li", "click", function () {
var text = $(this).data("text");
var value = $(this).data("value");
setValue.call($this[0], text, value);
$this.trigger("dropdown.set", [text, value]);
$menu.hide();
}).delegate("li", "mouseenter", function () {
$(this).addClass("cursor").siblings("li").removeClass("cursor");
}).mouseleave(function () {
$menu.hide();
});
}
//初始化下拉组件的方法
$.fn.dropdown = function (opt) {
var opts = defaults;
$.extend(true, opts, opt);
return this.each(function () {
Dropdown.call(this, opts);
});
};
//重载下拉框数据的方法
$.fn.menuReload = function (data) {
return this.each(function () {
Reload.call(this, data);
});
};
//设置下拉框的值
$.fn.setValue = function (data) {
return this.each(function () {
setValue.call(this, data.text, data.value);
});
};
$.fn.setDisable = function (val) {
return this.each(function () {
setDisable.call(this, val);
});
};
})();
|
const findIndex = require('lodash/findIndex');
module.exports = (req, res, next) => {
const pageData = req.pageData || {};
const siblings = pageData.meta ? pageData.meta.siblings : [];
const pagination = pageData.pagination || {};
if (pageData && pageData.guide && siblings) {
const currentIndex = findIndex(siblings, (p) => {
return pageData.slug.indexOf(p.slug) !== -1;
});
if (currentIndex > 0) {
pagination.previous = siblings[currentIndex - 1];
}
if (siblings && currentIndex < siblings.length) {
pagination.next = siblings[currentIndex + 1];
}
pageData.pagination = pagination;
}
// eslint-disable-next-line no-param-reassign
req.pageData = pageData;
next();
};
|
var cheerio = require('cheerio')
, request = require('request')
, url = 'http://theroyalamerican.com/schedule/'
, shows = []
, months = ['January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December']
function royalamerican (done) {
request(url, function(err, response, body) {
var $ = cheerio.load(body)
$('.gig').each(function(i, elem) {
var price, time
var $$ = cheerio.load(elem)
var title = $$('.title').text().trim()
if($$('.with').text().trim()) title += $$('.with').text().trim()
var date = $$('.date').text().trim()
var timePrice = $$('.details').text().trim().split('Show: ').join('').split('|')
if(timePrice[0]) time = timePrice[0].trim()
if(timePrice[1] && timePrice[1].trim().slice(0,1) === '$') price = timePrice[1].split('Cover')[0].trim()
else price = ''
var year = $('#gigs_left').children().attr('name')
date = normalizeDate(date, year)
var show = {
venue: 'The Royal American',
venueUrl: 'http://theroyalamerican.com/',
title: title,
time: time.slice(0,5).trim(),
price: price,
url: $$('.details').first().find('a').attr('href'),
date: date
}
shows.push(show)
})
done(null, shows)
})
}
module.exports = royalamerican
function normalizeDate(date, year) {
var newDate = []
date = date.split(' ')
var day = date.pop()
if(day.length < 2) day = '0'+day
var month = date.pop()
month = (months.indexOf(month)+1).toString()
if(month.length < 2) month = '0'+month
year = year.split('_')[1]
newDate.push(year)
newDate.push(month)
newDate.push(day)
return newDate.join('-')
}
|
<div ng-include="'components/navbar/navbar.html'"></div>
<div class="container">
<div class="row">
<div class="col-lg-12">
<h1 class="page-header">Delete A ${model["name"]} :</h1>
</div>
</div>
</div>
|
var vows = require('vows'),
assert = require('assert'),
fs = require('fs'),
jscheckstyle = require('../lib/jscheckstyle');
function given(inputFile, expectedOutput) {
var context = {};
context['(' + inputFile + ') '] = {
topic: function() {
return jscheckstyle.analyse('/pants/file1.js', fs.readFileSync(__dirname + '/fixtures/' + inputFile, 'utf8'));
}
};
context['(' + inputFile + ') ']['passed to the renderer'] = expectedOutput;
return context;
}
function expect(outputFile) {
var context = {
topic: function(results) {
return jscheckstyle.renderers.checkstyle(results);
}
};
context['the output should match ' + outputFile] = function(output) {
assert.equal(output, fs.readFileSync(__dirname + '/fixtures/' + outputFile, 'utf8'));
};
return context;
}
vows.describe("checkstyle renderer").addBatch({
'should be exported as a command line option': function() {
assert.equal(jscheckstyle.renderers.checkstyle, jscheckstyle.renderers['--checkstyle']);
},
'with simple input': given('simple.js', expect('no-errors.xml')),
'with a cyclomatic complexity violation': given('complex-function.js', expect('complex-output.xml')),
'with a function length violation': given('long-function.js', expect('long-output.xml')),
'with a configured function length violation': given('configured-long-function.js', expect('configured-long-output.xml')),
'with a number of arguments violation': given('too-many-arguments.js', expect('too-many-arguments-output.xml')),
'with multiple violations in a single function': given('lots-of-args-and-long.js', expect('lots-of-args-and-long-output.xml')),
'module.exports should not trigger function length violation': given('a-long-module.js', expect('no-errors.xml')),
'module.exports should trigger number of arguments violation': given('a-module-function.js', expect('module-arguments.xml')),
'violations only': {
'when no rules are broken': {
topic: jscheckstyle.violationsOnly([{
filename: "file1.js",
results: [
{ lineStart: 1, shortName: "cheese", lines: 5, complexity: 1, ins: 1 },
{ lineStart: 10, shortName: "biscuits", lines: 2, complexity: 5, ins: 0 }
]
}]),
'should return an empty array': function(results) {
assert.lengthOf(results, 0);
}
},
'when one rule is broken': {
topic: jscheckstyle.violationsOnly([{
filename: "file1.js",
results: [
{ lineStart: 1, shortName: "cheese", lines:5, complexity:15, ins: 1 },
{ lineStart: 10, shortName: "biscuits", lines: 2, complexity: 5, ins: 0 }
]
}]),
'should return an array with one result': function(results) {
assert.deepEqual(results, [{
filename: "file1.js",
results: [
{ lineStart:1,
shortName: "cheese",
lines: 5,
complexity: 15,
ins: 1,
violations: [{
source: "CyclomaticComplexity",
message: "cheese has a cyclomatic complexity of 15, maximum should be 10"
}]
}
]
}]);
}
},
'when one rule is broken in two functions': {
topic: jscheckstyle.violationsOnly([{
filename: "file1.js",
results: [
{ lineStart: 1, shortName: "cheese", lines:5, complexity:15, ins: 1 },
{ lineStart: 10, shortName: "biscuits", lines: 2, complexity: 15, ins: 0 }
]
}]),
'should return an array with two results': function(results) {
assert.deepEqual(
results,
[{ filename: "file1.js", results: [
{ lineStart:1, shortName: "cheese", lines: 5, complexity: 15, ins: 1, violations: [{
source: "CyclomaticComplexity",
message: "cheese has a cyclomatic complexity of 15, maximum should be 10"
}] },
{ lineStart:10, shortName: "biscuits", lines: 2, complexity: 15, ins: 0, violations: [{
source: "CyclomaticComplexity",
message: "biscuits has a cyclomatic complexity of 15, maximum should be 10"
}] }
] }]
);
}
},
'when two rules are broken in one function': {
topic: jscheckstyle.violationsOnly([{
filename: "file1.js",
results: [
{ lineStart: 1, shortName: "cheese", lines:5, complexity:15, ins: 8 },
{ lineStart: 10, shortName: "biscuits", lines: 2, complexity: 1, ins: 0 }
]
}]),
'should return an array with one result and two violations': function(results) {
assert.deepEqual(
results,
[{ filename: "file1.js", results: [
{ lineStart:1, shortName: "cheese", lines: 5, complexity: 15, ins: 8, violations: [
{ source: "CyclomaticComplexity",
message: "cheese has a cyclomatic complexity of 15, maximum should be 10"
},
{ source: "NumberOfArguments",
message: "cheese has 8 arguments, maximum allowed is 5"
}
]}
] }]
);
}
}
}
}).exportTo(module);
|
version https://git-lfs.github.com/spec/v1
oid sha256:5b06c8bb34dea0d08a98bb98d8fc80c43e4c6e36f6051a72b41fd447afd37cfc
size 1253
|
Hilary.scope('node-example').register({
name: 'breweriesController',
dependencies: ['newGidgetModule', 'GidgetRoute', 'viewEngine'],
factory: function (self, GidgetRoute, viewEngine) {
'use strict';
self.get['/breweries/:brewery'] = new GidgetRoute({
routeHandler: function (err, req, next) {
req.title = req.params.brewery;
viewEngine.setVM({
template: 't-brewery',
data: {
heading: '/breweries/:brewery',
param0: req.params.splat[0],
brewery: req.params.brewery
}
});
next(err, req);
},
before: function (err, req, next) {
console.log('before breweries route', req);
next(err, req);
},
after: function (err, req, next) {
console.log('after breweries route', req);
next(err, req);
}
});
self.get['/breweries/:brewery/beers/:beer'] = function (err, req, next) {
req.title = req.params.brewery.concat(' ', req.params.beer);
viewEngine.setVM({
template: 't-beer',
data: {
heading: '/breweries/:brewery/beers/:beer',
param0: req.params.splat[0],
param1: req.params.splat[1],
brewery: req.params.brewery,
beer: req.params.beer
}
});
next(err, req);
};
return self;
}
});
|
/**
* Created by OTHREE on 7/17/2016.
*/
function my_special_notification_callback(data) {
var badge = document.getElementById('live_notify_badge2');
if (badge) {
badge.innerHTML = data.unread_count;
}
var template = "<li> <a href='/user/dashboard/notifications/' id='{{id}}'> <i class='fa fa-info text-aqua'></i> {{level}} "+
"<br><small> {{ description }} </small></a></li>";
var menu = document.getElementById('live_notify_list');
if (menu) {
menu.innerHTML = "";
for (var i=0; i < data.unread_list.length; i++) {
var item = data.unread_list[i];
var message = "";
if(typeof item.actor !== 'undefined'){
message = item.actor;
}
if(typeof item.verb !== 'undefined'){
message = message + " " + item.verb;
}
if(typeof item.target !== 'undefined'){
message = message + " " + item.target;
}
if(typeof item.timestamp !== 'undefined'){
message = message + " " + item.timestamp;
}
menu.innerHTML = menu.innerHTML + Mustache.render(template,item)
}
}
}
|
var crypto = require('crypto')
var multimatch = require('multimatch')
var path = require('path')
var KEY = 'metalsmith'
module.exports = plugin
function plugin(options) {
return function (files, metalsmith, done) {
var metadata = metalsmith.metadata()
metadata.fingerprint = (metadata.fingerprint || {})
Object.keys(files)
.filter(function (p) {
return multimatch(p, options.pattern).length > 0
})
.forEach(function (p) {
var hash = crypto.createHmac('md5', KEY).update(files[p].contents).digest('hex')
var ext = path.extname(p)
var fingerprint = [p.substring(0, p.lastIndexOf(ext)), '-', hash, ext].join('').replace(/\\/g, '/')
files[fingerprint] = files[p]
metadata.fingerprint[p] = fingerprint
})
return process.nextTick(done)
}
}
|
import {
ActionHandler,
Evented,
FrameworkObject,
deprecateUnderscoreActions
} from 'ember-runtime';
import { initViewElement } from '../system/utils';
import { cloneStates, states } from './states';
/**
`Ember.CoreView` is an abstract class that exists to give view-like behavior
to both Ember's main view class `Ember.Component` and other classes that don't need
the full functionality of `Ember.Component`.
Unless you have specific needs for `CoreView`, you will use `Ember.Component`
in your applications.
@class CoreView
@namespace Ember
@extends Ember.Object
@deprecated Use `Ember.Component` instead.
@uses Ember.Evented
@uses Ember.ActionHandler
@private
*/
const CoreView = FrameworkObject.extend(Evented, ActionHandler, {
isView: true,
_states: cloneStates(states),
init() {
this._super(...arguments);
this._state = 'preRender';
this._currentState = this._states.preRender;
initViewElement(this);
if (!this.renderer) {
throw new Error(`Cannot instantiate a component without a renderer. Please ensure that you are creating ${this} with a proper container/registry.`);
}
},
/**
If the view is currently inserted into the DOM of a parent view, this
property will point to the parent of the view.
@property parentView
@type Ember.View
@default null
@private
*/
parentView: null,
instrumentDetails(hash) {
hash.object = this.toString();
hash.containerKey = this._debugContainerKey;
hash.view = this;
return hash;
},
/**
Override the default event firing from `Ember.Evented` to
also call methods with the given name.
@method trigger
@param name {String}
@private
*/
trigger(name, ...args) {
this._super(...arguments);
let method = this[name];
if (typeof method === 'function') {
return method.apply(this, args);
}
},
has(name) {
return typeof this[name] === 'function' || this._super(name);
}
});
deprecateUnderscoreActions(CoreView);
CoreView.reopenClass({
isViewFactory: true
});
export default CoreView;
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M7.77 6.76 6.23 5.48.82 12l5.41 6.52 1.54-1.28L3.42 12l4.35-5.24zM7 13h2v-2H7v2zm10-2h-2v2h2v-2zm-6 2h2v-2h-2v2zm6.77-7.52-1.54 1.28L20.58 12l-4.35 5.24 1.54 1.28L23.18 12l-5.41-6.52z"
}), 'SettingsEthernet');
exports.default = _default;
|
import m from 'mithril';
import _ from 'underscore';
import h from '../h';
const adminItem = {
oninit: function(vnode) {
vnode.state = {
displayDetailBox: h.toggleProp(false, true)
};
},
view: function({state, attrs}) {
const item = attrs.item,
listWrapper = attrs.listWrapper || {},
selectedItem = (_.isFunction(listWrapper.isSelected) ?
listWrapper.isSelected(item.id) : false);
return m('.w-clearfix.card.u-radius.u-marginbottom-20.results-admin-items', {
class: (selectedItem ? 'card-alert' : '')
}, [
m(attrs.listItem, {
item,
listWrapper: attrs.listWrapper,
}),
m('button.w-inline-block.arrow-admin.fa.fa-chevron-down.fontcolor-secondary', {
onclick: state.displayDetailBox.toggle
}),
(
state.displayDetailBox() ?
m(attrs.listDetail, {
item,
})
:
''
)
]);
}
};
export default adminItem;
|
'use strict';
var React = require('react');
var SvgIcon = require('../../svg-icon');
var NavigationChevronRight = React.createClass({
displayName: 'NavigationChevronRight',
render: function render() {
return React.createElement(
SvgIcon,
this.props,
React.createElement('path', { d: 'M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z' })
);
}
});
module.exports = NavigationChevronRight;
|
version https://git-lfs.github.com/spec/v1
oid sha256:7191d4054034f882d0333e067f484abf20e9d176d5c0297c8824f5e0cafc8e12
size 2389
|
/* Chinese initialisation for the jQuery UI date picker plugin. */
/* Written by Ressol (ressol@gmail.com). */
(function (factory) {
// AMD. Register as an anonymous module.
module.exports = factory(require('../datepicker'));;
}(function (datepicker) {
datepicker.regional['zh-TW'] = {
closeText: '\u95DC\u9589',
prevText: '<\u4E0A\u6708',
nextText: '\u4E0B\u6708>',
currentText: '\u4ECA\u5929',
monthNames: [
'\u4E00\u6708',
'\u4E8C\u6708',
'\u4E09\u6708',
'\u56DB\u6708',
'\u4E94\u6708',
'\u516D\u6708',
'\u4E03\u6708',
'\u516B\u6708',
'\u4E5D\u6708',
'\u5341\u6708',
'\u5341\u4E00\u6708',
'\u5341\u4E8C\u6708'
],
monthNamesShort: [
'\u4E00\u6708',
'\u4E8C\u6708',
'\u4E09\u6708',
'\u56DB\u6708',
'\u4E94\u6708',
'\u516D\u6708',
'\u4E03\u6708',
'\u516B\u6708',
'\u4E5D\u6708',
'\u5341\u6708',
'\u5341\u4E00\u6708',
'\u5341\u4E8C\u6708'
],
dayNames: [
'\u661F\u671F\u65E5',
'\u661F\u671F\u4E00',
'\u661F\u671F\u4E8C',
'\u661F\u671F\u4E09',
'\u661F\u671F\u56DB',
'\u661F\u671F\u4E94',
'\u661F\u671F\u516D'
],
dayNamesShort: [
'\u5468\u65E5',
'\u5468\u4E00',
'\u5468\u4E8C',
'\u5468\u4E09',
'\u5468\u56DB',
'\u5468\u4E94',
'\u5468\u516D'
],
dayNamesMin: [
'\u65E5',
'\u4E00',
'\u4E8C',
'\u4E09',
'\u56DB',
'\u4E94',
'\u516D'
],
weekHeader: '\u5468',
dateFormat: 'yy/mm/dd',
firstDay: 1,
isRTL: false,
showMonthAfterYear: true,
yearSuffix: '\u5E74'
};
datepicker.setDefaults(datepicker.regional['zh-TW']);
return datepicker.regional['zh-TW'];
}));
|
/**
* Copyright 2015 Telerik AD
*
* 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(f, define){
define([], f);
})(function(){
(function( window, undefined ) {
var kendo = window.kendo || (window.kendo = { cultures: {} });
kendo.cultures["nso-ZA"] = {
name: "nso-ZA",
numberFormat: {
pattern: ["-n"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3],
percent: {
pattern: ["-%n","%n"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3],
symbol: "%"
},
currency: {
pattern: ["$-n","$ n"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3],
symbol: "R"
}
},
calendars: {
standard: {
days: {
names: ["Lamorena","Mošupologo","Labobedi","Laboraro","Labone","Labohlano","Mokibelo"],
namesAbbr: ["Lam","Moš","Lbb","Lbr","Lbn","Lbh","Mok"],
namesShort: ["L","M","L","L","L","L","M"]
},
months: {
names: ["Pherekgong","Hlakola","Mopitlo","Moranang","Mosegamanye","Ngoatobošego","Phuphu","Phato","Lewedi","Diphalana","Dibatsela","Manthole",""],
namesAbbr: ["Pher","Hlak","Mop","Mor","Mos","Ngwat","Phup","Phat","Lew","Dip","Dib","Man",""]
},
AM: ["AM","am","AM"],
PM: ["PM","pm","PM"],
patterns: {
d: "yyyy/MM/dd",
D: "dd MMMM yyyy",
F: "dd MMMM yyyy hh:mm:ss tt",
g: "yyyy/MM/dd hh:mm tt",
G: "yyyy/MM/dd hh:mm:ss tt",
m: "dd MMMM",
M: "dd MMMM",
s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss",
t: "hh:mm tt",
T: "hh:mm:ss tt",
u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'",
y: "MMMM yyyy",
Y: "MMMM yyyy"
},
"/": "/",
":": ":",
firstDay: 0
}
}
}
})(this);
return window.kendo;
}, typeof define == 'function' && define.amd ? define : function(_, f){ f(); });
|
'use strict';
exports = module.exports = function(service) {
return {
message: function(user) {
return '<p>' + 'Welcome to ' + service + ' ' + user.fullname + '!' + '</p>' +
'<p>' + 'You have now linked your Google+ account to this service' + '</p>';
},
title: function() {
return 'You linked your Google+ account to our service';
}
};
};
|
/**
* @typedef {object} SalesAPI
* @property {Activities} Activities
**/
function SalesAPI(options) {
const _Activities = require('./Activities');
return {
Activities: new _Activities(options),
};
}
module.exports = SalesAPI;
|
(function () {
function RunningInNode () {
return(
(typeof require) == "function"
&&
(typeof exports) == "object"
&&
(typeof module) == "object"
&&
(typeof __filename) == "string"
&&
(typeof __dirname) == "string"
);
}
if (!RunningInNode()) {
if (!this.Tautologistics)
this.Tautologistics = {};
if (!this.Tautologistics.NodeHtmlParser)
this.Tautologistics.NodeHtmlParser = {};
if (!this.Tautologistics.NodeHtmlParser.Tests)
this.Tautologistics.NodeHtmlParser.Tests = [];
exports = {};
this.Tautologistics.NodeHtmlParser.Tests.push(exports);
}
exports.name = "XML Namespace";
exports.options = {
handler: {}
, parser: {}
};
exports.html = "<ns:tag>text</ns:tag>";
exports.expected =
[ { raw: 'ns:tag', data: 'ns:tag', type: 'tag', name: 'ns:tag', children: [ { raw: 'text', data: 'text', type: 'text' } ] }
];
})();
|
import Ember from 'ember';
import DS from 'ember-data';
const secondsInDay = 86400;
const days = [
'monday',
'tuesday',
'wednesday',
'thursday',
'friday',
'saturday',
'sunday',
];
export default DS.Model.extend(Ember.Copyable, {
temp: DS.attr('number', {
defaultValue: 18,
}),
// Seconds since 00:00 Monday.
seconds: DS.attr('number', {
defaultValue: 0,
}),
day: Ember.computed('seconds', {
get() {
return Math.floor(this.get('seconds') / secondsInDay);
},
set(key, day) {
day = day % days.length;
if (day < 0) {
day += days.length;
}
const newDayOffset = day * secondsInDay;
const oldDayOffset = this.get('day') * secondsInDay;
const secondsRemaining = this.get('seconds') - oldDayOffset;
this.set('seconds', newDayOffset + secondsRemaining);
return day;
},
}),
dayLabel: Ember.computed('day', {
get() {
return days[this.get('day')];
},
set(key, dayLabel) {
this.set('day', days.indexOf(dayLabel));
return dayLabel;
},
}),
secondsToday: Ember.computed('seconds', 'day', {
get() {
const dayOffset = this.get('day') * secondsInDay;
const secondsToday = this.get('seconds') - dayOffset;
return secondsToday;
},
set(key, secondsToday) {
const dayOffset = this.get('day') * secondsInDay;
const seconds = secondsToday + dayOffset;
this.set('seconds', seconds);
return secondsToday;
},
}),
time: Ember.computed('secondsToday', {
get() {
const time = moment({ hours: 0 }).seconds(this.get('secondsToday'));
return time.format('HH:mm');
},
set(key, time) {
const duration = moment.duration(time);
this.set('secondsToday', duration.asSeconds());
return time;
},
}),
copy() {
return this.store.createRecord('event', {
temp: this.get('temp'),
seconds: this.get('seconds'),
});
}
});
|
var sheet = cssx();
(function () {
var _1 = {},
_2 = {},
_3 = {};
_2['color'] = '#000';
_3['color'] = '#F00';
_1['body'] = _2;
_1['body.error'] = _3;
return _1;
}.apply(this))
;
sheet.add((function () {
var _5 = {},
_6 = {},
_7 = {};
_6['font-size'] = '10px';
_6['line-height'] = '12px';
_7['margin'] = 0;
_7['padding'] = '2em';
_5['p'] = _6;
_5['ul > foo'] = _7;
return _5;
}.apply(this)));
var test = (function () {
var _9 = {};
_9['border'] = 'solid 1px #000';
_9['background'] = '#F00';
return _9;
}.apply(this));
|
"use strict";
var Cylon = require("cylon");
Cylon
.robot()
.connection("arduino", { adaptor: "firmata", port: "/dev/ttyACM0" })
.device("bmp180", { driver: "bmp180" })
.on("ready", function(bot) {
bot.bmp180.getTemperature(function(err, val) {
if (err) {
console.log(err);
} else {
console.log("getTemperature call:");
console.log("\tTemp: " + val.temp + " C");
}
});
setTimeout(function() {
bot.bmp180.getPressure(1, function(err, val) {
if (err) {
console.log(err);
} else {
console.log("getPressure call:");
console.log("\tTemperature: " + val.temp + " C");
console.log("\tPressure: " + val.press + " Pa");
}
});
}, 1000);
setTimeout(function() {
bot.bmp180.getAltitude(1, null, function(err, val) {
if (err) {
console.log(err);
} else {
console.log("getAltitude call:");
console.log("\tTemperature: " + val.temp + " C");
console.log("\tPressure: " + val.press + " Pa");
console.log("\tAltitude: " + val.alt + " m");
}
});
}, 2000);
});
Cylon.start();
|
'use strict';
var _Object$assign = require('babel-runtime/core-js/object/assign')['default'];
var _getIterator = require('babel-runtime/core-js/get-iterator')['default'];
var fs = require('fs'),
path = require('path'),
resolve = require('resolve');
var CASE_INSENSITIVE = fs.existsSync(path.join(__dirname, 'reSOLVE.js'));
// http://stackoverflow.com/a/27382838
function fileExistsWithCaseSync(_x) {
var _again = true;
_function: while (_again) {
var filepath = _x;
dir = filenames = undefined;
_again = false;
// shortcut exit
if (!fs.existsSync(filepath)) return false;
var dir = path.dirname(filepath);
if (dir === '/' || dir === '.' || /^[A-Z]:\\$/.test(dir)) return true;
var filenames = fs.readdirSync(dir);
if (filenames.indexOf(path.basename(filepath)) === -1) {
return false;
}
_x = dir;
_again = true;
continue _function;
}
}
function fileExists(filepath) {
if (CASE_INSENSITIVE) {
return fileExistsWithCaseSync(filepath);
} else {
return fs.existsSync(filepath);
}
}
function opts(basedir, settings) {
// pulls all items from 'import/resolve'
return _Object$assign({}, settings['import/resolve'], { basedir: basedir });
}
/**
* wrapper around resolve
* @param {string} p - module path
* @param {object} context - ESLint context
* @return {string} - the full module filesystem path
*/
module.exports = function (p, context) {
function withResolver(resolver) {
// resolve just returns the core module id, which won't appear to exist
if (resolver.isCore(p)) return p;
try {
var file = resolver.sync(p, opts(path.dirname(context.getFilename()), context.settings));
if (!fileExists(file)) return null;
return file;
} catch (err) {
// probably want something more general here
if (err.message.indexOf('Cannot find module') === 0) {
return null;
}
throw err;
}
}
var resolvers = (context.settings['import/resolvers'] || ['resolve']).map(require);
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = _getIterator(resolvers), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var resolver = _step.value;
var file = withResolver(resolver);
if (file) return file;
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator['return']) {
_iterator['return']();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
return null;
};
module.exports.relative = function (p, r, settings) {
try {
var file = resolve.sync(p, opts(path.dirname(r), settings));
if (!fileExists(file)) return null;
return file;
} catch (err) {
if (err.message.indexOf('Cannot find module') === 0) return null;
throw err; // else
}
};
|
(function(){
<?php
print (new \tomk79\pickles2\px2dthelper\main($px))->document_modules()->build_js();
?>
})();
|
//jshint strict: false
module.exports = function(config) {
config.set({
basePath: './app',
files: [
'bower_components/angular/angular.js',
'bower_components/angular-route/angular-route.js',
'bower_components/angular-mocks/angular-mocks.js',
'*.js'
],
autoWatch: true,
frameworks: ['jasmine'],
browsers: ['Chrome'],
plugins: [
'karma-chrome-launcher',
'karma-firefox-launcher',
'karma-jasmine',
'karma-junit-reporter'
],
junitReporter: {
outputFile: 'test_out/unit.xml',
suite: 'unit'
}
});
};
|
angular.module('umbraco').directive('maxlen', function () {
return {
require: 'ngModel',
link: function (scope, el, attrs, ctrl) {
var validate = false;
var length = 999999;
if (attrs.name === 'title') {
validate = scope.model.config.allowLongTitles !== '1';
length = scope.serpTitleLength;
} else if (attrs.name === 'description') {
validate = scope.model.config.allowLongDescriptions !== '1';
length = scope.serpDescriptionLength;
}
ctrl.$parsers.unshift(function (viewValue) {
if (validate && viewValue.length > length) {
ctrl.$setValidity('maxlen', false);
} else {
ctrl.$setValidity('maxlen', true);
}
return viewValue;
});
}
};
});
|
var nock = require('nock');
var Mockaroo = require('../lib/mockaroo');
require('chai').should();
describe('Client', function() {
describe('constructor', function() {
it('should require an api key', function() {
(function() {
new Mockaroo.Client({});
}).should.throw('apiKey is required');
});
});
describe('convertError', function() {
var client = new Mockaroo.Client({
apiKey: 'xxx'
});
it('should convert Invalid API Key to InvalidApiKeyError', function() {
client.convertError({ data: { error: 'Invalid API Key' }}).should.be.a.instanceOf(Mockaroo.errors.InvalidApiKeyError)
});
it('should convert errors containing "limited" to UsageLimitExceededError', function() {
client.convertError({ data: { error: 'Silver plans are limited to 1,000,000 records per day.' }}).should.be.a.instanceOf(Mockaroo.errors.UsageLimitExceededError)
});
});
describe('getUrl', function() {
it('should default to https://mockaroo.com', function() {
var client = new Mockaroo.Client({
apiKey: 'xxx'
});
client.getUrl().should.equal('https://mockaroo.com/api/generate.json?client=node&key=xxx&count=1')
});
it('should allow you to change the port', function() {
var client = new Mockaroo.Client({
apiKey: 'xxx',
secure: false,
port: 3000
});
client.getUrl().should.equal('http://mockaroo.com:3000/api/generate.json?client=node&key=xxx&count=1');
});
it('should use http when secure:false', function() {
var client = new Mockaroo.Client({
apiKey: 'xxx',
secure: false
});
client.getUrl().should.equal('http://mockaroo.com/api/generate.json?client=node&key=xxx&count=1');
});
it('should allow you to set a count > 1', function() {
var client = new Mockaroo.Client({
apiKey: 'xxx',
});
client.getUrl({count: 10}).should.equal('https://mockaroo.com/api/generate.json?client=node&key=xxx&count=10');
});
it('should allow you to customize the host', function() {
var client = new Mockaroo.Client({
apiKey: 'xxx',
host: 'foo'
});
client.getUrl().should.equal('https://foo/api/generate.json?client=node&key=xxx&count=1');
});
it('should include schema', function() {
var client = new Mockaroo.Client({
apiKey: 'xxx'
});
client.getUrl({schema: 'MySchema'}).should.equal('https://mockaroo.com/api/generate.json?client=node&key=xxx&count=1&schema=MySchema');
});
it('should allow you to generate csv', function() {
var client = new Mockaroo.Client({
apiKey: 'xxx'
});
client.getUrl({format: 'csv'}).should.equal('https://mockaroo.com/api/generate.csv?client=node&key=xxx&count=1');
});
it('should allow you to remove the header from csv', function() {
var client = new Mockaroo.Client({
apiKey: 'xxx'
});
client.getUrl({format: 'csv', header: false}).should.equal('https://mockaroo.com/api/generate.csv?client=node&key=xxx&count=1&header=false');
})
});
describe('generate', function() {
var client = new Mockaroo.Client({
secure: false,
apiKey: 'xxx'
});
it('should require fields or schema', function() {
(function() {
client.generate()
}).should.throw('Either fields or schema option must be specified');
});
describe('when successful', function() {
var api = nock('http://mockaroo.com')
.post('/api/generate.json?client=node&key=xxx&count=1')
.reply(200, JSON.stringify([{ foo: 'bar' }]))
it('should resolve', function() {
return client.generate({
fields: [{
name: 'foo',
type: 'Custom List',
values: ['bar']
}]
}).then(function(records) {
records.should.deep.equal([{ foo: 'bar' }]);
})
});
})
describe('when unsuccessful', function() {
var api = nock('http://mockaroo.com')
.post('/api/generate.json?client=node&key=xxx&count=1')
.reply(500, JSON.stringify({ error: 'Invalid API Key' }))
it('should handle errors', function() {
return client.generate({
fields: []
}).catch(function(error) {
error.should.be.instanceOf(Mockaroo.errors.InvalidApiKeyError)
})
});
});
it('should required fields to be an array', function() {
(function() {
client.generate({ fields: 'foo' })
}).should.throw('fields must be an array');
});
it('should required a name for each field', function() {
(function() {
client.generate({ fields: [{ type: 'Row Number' }] })
}).should.throw('each field must have a name');
});
it('should required a type for each field', function() {
(function() {
client.generate({ fields: [{ name: 'ID' }] })
}).should.throw('each field must have a type');
});
});
});
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M4 15h16v-2H4v2zm0 4h16v-2H4v2zm0-8h16V9H4v2zm0-6v2h16V5H4z"
}), 'ViewHeadlineSharp');
exports.default = _default;
|
import React from 'react'
import Icon from 'react-icon-base'
const GoColorMode = props => (
<Icon viewBox="0 0 40 40" {...props}>
<g><path d="m5 5v30h30v-30h-30z m2.5 27.5v-25h25l-25 25z"/></g>
</Icon>
)
export default GoColorMode
|
/*
* Copyright (c) 2015 by Rafael Angel Aznar Aparici (rafaaznar at gmail dot com)
*
* openAUSIAS: The stunning micro-library that helps you to develop easily
* AJAX web applications by using Java and jQuery
* openAUSIAS is distributed under the MIT License (MIT)
* Sources at https://github.com/rafaelaznar/
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
'use strict';
moduloTipocompeticion.controller('TipocompeticionRemoveController', ['$scope', '$routeParams', 'serverService',
function ($scope, $routeParams, serverService) {
$scope.result = "";
$scope.back = function () {
window.history.back();
};
$scope.ob = 'tipocompeticion';
$scope.id = $routeParams.id;
$scope.title = "Borrado de un Tipo de Competicion";
$scope.icon = "fa-futbol-o";
serverService.getDataFromPromise(serverService.promise_getOne($scope.ob, $scope.id)).then(function (data) {
$scope.bean = data.message;
});
$scope.remove = function () {
serverService.getDataFromPromise(serverService.promise_removeOne($scope.ob, $scope.id)).then(function (data) {
$scope.result = data;
});
}
;
}]);
|
/*
基本测试,ejs 模版 测试 例子
*/
var should = require('should');
var request = require('request');
var path = require('path');
var testconf = require('./testconf.js');
module.exports.rrestjsconfig = {
listenPort:3000,
tempSet:'ejs',
tempFolder :'/static',
baseDir: path.join(__dirname),
};
var chtml='';
var dhtml = '';
var fhtml = '';
var http = require('http'),
rrest = require('../'),
i=0,
server = http.createServer(function (req, res) {
var pname = req.pathname;
if(pname === '/a'){
res.render('/ejs');
}
else if(pname === '/b'){
res.render('/ejs.ejs', {"name":'hello world'});
}
else if(pname === '/c'){
res.render('/ejs',function(err, html){//测试不加后缀名是否可以render成功
chtml = html;
});
}
else if(pname === '/d'){
res.render('/ejs.ejs', {"name":'hello world'}, function(err, html){
dhtml = html;
});
}
else if(pname === '/e'){
res.render('/ejs.ejs', 1, {"usersex":'hello world'});
}
else if(pname === '/f'){
res.render('/ejs', 2, {}, function(err, html){
fhtml = html;
});
}
else if(pname === '/g'){
res.compiletemp('/ejs.ejs', function(err, html){
res.sendjson({'data':html});
});
}
else if(pname === '/h'){
res.compiletemp('/ejs.ejs', 3, {"name":'hello world'}, function(err, html){
res.sendjson({'data':html});
});
}
else if(pname === '/i'){
res.compiletemp('/ejs2', 3, {"name":'hello world'}, function(err, html){
res.sendjson({'data':html});
});
}
}).listen(rrest.config.listenPort);
//设置全局的模版option
rrest.tploption.userid = function(req,res){return req.ip};
rrest.tploption.name = 'rrestjs default';
rrest.tploption.usersex = 'male';
http.globalAgent.maxSockets = 10;
var i = 9;
var r = 0
var result = function(name){
var num = ++r;
console.log('%s test done, receive %d/%d', name, num, i);
if(num>=i){
console.log('ejs.js test done.')
process.exit();
}
}
request({
method:'get',
uri:'http://'+testconf.hostname+':3000/a',
}, function(error, res, body){
should.strictEqual(res.statusCode, 200);
should.strictEqual(body, '<li>rrestjs default</li><li>'+testconf.hostname+'</li><li>male</li><form></form>')
result('/a request')
});
request({
method:'get',
uri:'http://'+testconf.hostname+':3000/b',
}, function(error, res, body){
should.strictEqual(res.statusCode, 200);
should.strictEqual(body, '<li>hello world</li><li>'+testconf.hostname+'</li><li>male</li><form></form>')
result('/b request')
});
request({
method:'get',
uri:'http://'+testconf.hostname+':3000/c',
}, function(error, res, body){
should.strictEqual(res.statusCode, 200);
should.strictEqual(body, '<li>rrestjs default</li><li>'+testconf.hostname+'</li><li>male</li><form></form>');
setTimeout(function(){
should.strictEqual(chtml, '<li>rrestjs default</li><li>'+testconf.hostname+'</li><li>male</li><form></form>');
result('/c request')
},100)
});
request({
method:'get',
uri:'http://'+testconf.hostname+':3000/d',
}, function(error, res, body){
should.strictEqual(res.statusCode, 200);
should.strictEqual(body, '<li>hello world</li><li>'+testconf.hostname+'</li><li>male</li><form></form>');
setTimeout(function(){
should.strictEqual(dhtml, '<li>hello world</li><li>'+testconf.hostname+'</li><li>male</li><form></form>');
result('/d request')
},100)
});
request({
method:'get',
uri:'http://'+testconf.hostname+':3000/e',
}, function(error, res, body){
should.strictEqual(res.statusCode, 200);
should.strictEqual(body, '<li>rrestjs default</li><li>'+testconf.hostname+'</li><li>hello world</li><form></form>');
result('/e request')
});
request({
method:'get',
uri:'http://'+testconf.hostname+':3000/f',
}, function(error, res, body){
should.strictEqual(res.statusCode, 200);
should.strictEqual(body, '<li>rrestjs default</li><li>'+testconf.hostname+'</li><li>male</li><form></form>');
setTimeout(function(){
should.strictEqual(fhtml, '<li>rrestjs default</li><li>'+testconf.hostname+'</li><li>male</li><form></form>');
result('/f request')
},100)
});
request({
method:'get',
uri:'http://'+testconf.hostname+':3000/g',
}, function(error, res, body){
should.strictEqual(res.statusCode, 200);
should.strictEqual(body, '{\"data\":\"<li>rrestjs default</li><li>'+testconf.hostname+'</li><li>male</li><form></form>\"}');
result('/g request')
});
request({
method:'get',
uri:'http://'+testconf.hostname+':3000/h',
}, function(error, res, body){
should.strictEqual(res.statusCode, 200);
should.strictEqual(body, '{\"data\":\"<li>hello world</li><li>'+testconf.hostname+'</li><li>male</li><form></form>\"}');
result('/h request')
});
setTimeout(function(){
rrest.ejs.open ='{{'
rrest.ejs.close ='}}'
request({
method:'get',
uri:'http://'+testconf.hostname+':3000/i',
}, function(error, res, body){
should.strictEqual(res.statusCode, 200);
should.strictEqual(body, '{\"data\":\"<li>hello world</li><li>'+testconf.hostname+'</li><li>male</li><form></form>\"}');
result('/h request')
});
},1000)
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)([/*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M5 18h14V8H5v10zm3.82-6.42 2.12 2.12 4.24-4.24 1.41 1.41-5.66 5.66L7.4 13l1.42-1.42z",
opacity: ".3"
}, "0"), /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "m16.6 10.88-1.42-1.42-4.24 4.25-2.12-2.13L7.4 13l3.54 3.54z"
}, "1"), /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M19 4H5c-1.11 0-2 .9-2 2v12c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V6c0-1.1-.89-2-2-2zm0 14H5V8h14v10z"
}, "2")], 'DomainVerificationTwoTone');
exports.default = _default;
|
var _ = require('lodash'),
Promise = require('bluebird'),
IndexMapGenerator = require('./index-generator'),
PagesMapGenerator = require('./page-generator'),
PostsMapGenerator = require('./post-generator'),
UsersMapGenerator = require('./user-generator'),
TagsMapGenerator = require('./tag-generator'),
SiteMapManager;
SiteMapManager = function (opts) {
opts = opts || {};
this.initialized = false;
this.pages = opts.pages || this.createPagesGenerator(opts);
this.posts = opts.posts || this.createPostsGenerator(opts);
this.authors = opts.authors || this.createUsersGenerator(opts);
this.tags = opts.tags || this.createTagsGenerator(opts);
this.index = opts.index || this.createIndexGenerator(opts);
};
_.extend(SiteMapManager.prototype, {
createIndexGenerator: function () {
return new IndexMapGenerator(_.pick(this, 'pages', 'posts', 'authors', 'tags'));
},
createPagesGenerator: function (opts) {
return new PagesMapGenerator(opts);
},
createPostsGenerator: function (opts) {
return new PostsMapGenerator(opts);
},
createUsersGenerator: function (opts) {
return new UsersMapGenerator(opts);
},
createTagsGenerator: function (opts) {
return new TagsMapGenerator(opts);
},
init: function () {
var self = this,
initOps = [
this.pages.init(),
this.posts.init(),
this.authors.init(),
this.tags.init()
];
return Promise.all(initOps).then(function () {
self.initialized = true;
});
},
getIndexXml: function () {
if (!this.initialized) {
return '';
}
return this.index.getIndexXml();
},
getSiteMapXml: function (type) {
if (!this.initialized || !this[type]) {
return null;
}
return this[type].siteMapContent;
},
pageAdded: function (page) {
if (!this.initialized) {
return;
}
if (page.get('status') !== 'published') {
return;
}
this.pages.addUrl(page.toJSON());
},
pageEdited: function (page) {
if (!this.initialized) {
return;
}
var pageData = page.toJSON(),
wasPublished = page.updated('status') === 'published',
isPublished = pageData.status === 'published';
// Published status hasn't changed and it's published
if (isPublished === wasPublished && isPublished) {
this.pages.updateUrl(pageData);
} else if (!isPublished && wasPublished) {
// Handle page going from published to draft
this.pageDeleted(page);
} else if (isPublished && !wasPublished) {
// ... and draft to published
this.pageAdded(page);
}
},
pageDeleted: function (page) {
if (!this.initialized) {
return;
}
this.pages.removeUrl(page.toJSON());
},
postAdded: function (post) {
if (!this.initialized) {
return;
}
if (post.get('status') !== 'published') {
return;
}
this.posts.addUrl(post.toJSON());
},
postEdited: function (post) {
if (!this.initialized) {
return;
}
var postData = post.toJSON(),
wasPublished = post.updated('status') === 'published',
isPublished = postData.status === 'published';
// Published status hasn't changed and it's published
if (isPublished === wasPublished && isPublished) {
this.posts.updateUrl(postData);
} else if (!isPublished && wasPublished) {
// Handle post going from published to draft
this.postDeleted(post);
} else if (isPublished && !wasPublished) {
// ... and draft to published
this.postAdded(post);
}
},
postDeleted: function (post) {
if (!this.initialized) {
return;
}
this.posts.removeUrl(post.toJSON());
},
userAdded: function (user) {
if (!this.initialized) {
return;
}
this.authors.addUrl(user.toJSON());
},
userEdited: function (user) {
if (!this.initialized) {
return;
}
var userData = user.toJSON();
this.authors.updateUrl(userData);
},
userDeleted: function (user) {
if (!this.initialized) {
return;
}
this.authors.removeUrl(user.toJSON());
},
tagAdded: function (tag) {
if (!this.initialized) {
return;
}
this.tags.addUrl(tag.toJSON());
},
tagEdited: function (tag) {
if (!this.initialized) {
return;
}
this.tags.updateUrl(tag.toJSON());
},
tagDeleted: function (tag) {
if (!this.initialized) {
return;
}
this.tags.removeUrl(tag.toJSON());
},
// TODO: Call this from settings model when it's changed
permalinksUpdated: function (permalinks) {
if (!this.initialized) {
return;
}
this.posts.updatePermalinksValue(permalinks.toJSON ? permalinks.toJSON() : permalinks);
},
_refreshAllPosts: _.throttle(function () {
this.posts.refreshAllPosts();
}, 3000, {
leading: false,
trailing: true
})
});
module.exports = SiteMapManager;
|
/**
* Draws rectangles
*/
Y.Rect = Y.Base.create("rect", Y.Shape, [], {
/**
* Indicates the type of shape
*
* @property _type
* @readOnly
* @type String
*/
_type: "rect",
/**
* @private
*/
_draw: function()
{
var x = this.get("x"),
y = this.get("y"),
w = this.get("width"),
h = this.get("height"),
fill = this.get("fill"),
stroke = this.get("stroke");
this.drawRect(x, y, w, h);
this._paint();
}
});
|
/**
* Test helpers for the tap tests that use material-ui as a front end
*/
import {saveToken, elements} from '../demo';
/**
*
* @param {object} aBrowser
* @param {string} accessToken
* @param {boolean} isOneOnOne
* @param {string} to
*/
export default function loginAndOpenWidget(aBrowser, accessToken, isOneOnOne, to) {
saveToken(aBrowser, accessToken);
if (isOneOnOne) {
aBrowser.element(elements.toPersonRadioButton).click();
aBrowser.element(elements.toPersonInput).setValue(to);
}
else {
aBrowser.element(elements.toSpaceRadioButton).click();
aBrowser.element(elements.toSpaceInput).setValue(to);
}
aBrowser.element(elements.openSpaceWidgetButton).click();
aBrowser.waitUntil(() => aBrowser.element(elements.spaceWidgetContainer).isVisible(), 3500, 'widget failed to open');
}
|
import browserColor from 'tap-browser-color';
browserColor();
import test from 'tape';
import React from 'react';
import universal from '../../client';
import routes from '../fixtures/routes';
import reducers from '../fixtures/reducers';
const app = universal({ React, routes, reducers });
const store = app();
test('Client app', nest => {
nest.test('...without Express instance', assert => {
const msg = 'should not return an Express instance';
const actual = typeof app.use;
const expected = 'undefined';
assert.equal(actual, expected, msg);
assert.end();
});
nest.test('...initalState', assert => {
const msg = 'should render initialState';
const text = 'Untitled';
const actual = document.querySelectorAll('.title')[0].innerHTML;
const expected = text;
assert.equal(actual, expected, msg);
assert.end();
});
nest.test('...client call', assert => {
const msg = 'should return store instance';
const actual = typeof store.dispatch;
const expected = 'function';
assert.equal(actual, expected, msg);
assert.end();
});
nest.test('...with dispatch', assert => {
const msg = 'should render new output';
const text = 'Client render';
store.dispatch({
type: 'SET_TITLE',
title: text
});
setTimeout(() => {
const actual = document.querySelectorAll('.title')[0].innerHTML;
const expected = text;
assert.equal(actual, expected, msg);
assert.end();
}, 100);
});
nest.test('...with second dispatch', assert => {
const msg = 'should render new output';
const text = 'Client render 2';
store.dispatch({
type: 'SET_TITLE',
title: text
});
setTimeout(() => {
const actual = document.querySelectorAll('.title')[0].innerHTML;
const expected = text;
assert.equal(actual, expected, msg);
assert.end();
}, 100);
});
});
|
import fs from "fs";
import { parse } from "babylon";
import CodeGenerator from "../CodeGenerator";
import processTokens from "../process-tokens";
import {timeLogStart, timeLog} from "../utils";
function parseText(text) {
timeLogStart("started parsing text");
let ast = parse(text, {
preserveParens: true,
sourceType: "module",
plugins: [ "*" ]
});
timeLog("parsed input");
let tokens = ast.tokens;
let semicolons = ast.tokens.filter(token => token.type.label === ";");
timeLogStart();
const modifiedTokens = processTokens(text, tokens, semicolons);
timeLog(`processed ${tokens.length} -> ${modifiedTokens.length} tokens`);
return { ast: ast.program, tokens: modifiedTokens, semicolons };
}
export function formatText(text) {
const { ast, tokens, semicolons } = parseText(text);
let generator = new CodeGenerator(ast, text, tokens, semicolons);
return generator.generate();
}
export function formatFile(filename) {
try {
timeLogStart();
const text = fs.readFileSync(filename).toString();
timeLog("finished reading file");
return formatText(text);
} catch (error) {
error.message = `${filename}: ${error.message}`;
throw error;
}
}
|
var Thoonk = require('../thoonk').Thoonk;
var thoonk = new Thoonk();
var jobs = {};
var stats = thoonk.feed('thoonk_job_stats');
thoonk.mredis.smembers('feeds', function(err, feeds) {
feeds.forEach(function(name) {
thoonk.mredis.hget('feed.config:' + name, 'type', function(err, reply) {
if(reply == 'job') {
jobs[name] = thoonk.job(name);
}
});
});
});
thoonk.on('create', function(name, instance) {
thoonk.mredis.hget('feed.config:' + name, 'type', function(err, reply) {
if(reply == 'job') {
jobs[name] = thoonk.job(name);
}
});
});
thoonk.on('delete', function(name, instance) {
if(jobs.hasOwnProperty(name)) {
jobs[name].quit();
delete jobs[name];
};
});
var update = function() {
for(key in jobs) { //function(job, key) {
(function(key, jobs) {
var multi = thoonk.mredis.multi();
multi.llen('feed.ids:' + key);
multi.getset('feed.publishes:' + key, '0');
multi.getset('feed.finishes:' + key, '0');
multi.zcount('feed.claimed:' + key,'0', '999999999999999');
multi.hlen('feed.items:' + key);
multi.exec(function(err, reply) {
console.log('----' + key + '----');
console.log('available:', reply[0]);
console.log('publishes:', reply[1]);
console.log('finishes:', reply[1]);
console.log('claimed:', reply[3]);
console.log('total:', reply[4]);
stats.publish(JSON.stringify({available: reply[0], publishes: reply[1], finishes: reply[2], claimed: reply[3], total:reply[4]}), key)
});
})(key, jobs);
}
setTimeout(update, 1000);
};
update();
var http = require('http');
var static = require('node-static');
var fileServer = new(static.Server)('./monitor-html');
var server = http.createServer(function(request, response) {
request.addListener('end', function () {
fileServer.serve(request, response);
});
});
server.listen(8000);
var io = require('socket.io').listen(8001);
io.sockets.on('connection', function (socket) {
var thissocket = socket;
var statupdate = function(feed, id, item) {
var uitem = JSON.parse(item);
uitem.id = id;
console.log('msg', feed, item, id);
socket.emit('message', uitem);
};
stats.subscribe({
edit: statupdate,
publish: statupdate
});
socket.once('disconnect', function() {
stats.unsubscribe({edit: statupdate, publish: statupdate});
});
});
|
import {writeArray} from 'event-stream';
import gulp from 'gulp';
import license from '../../tasks/helpers/license-helper';
describe('license', () => {
let result;
beforeEach(done => {
const licenseStream = gulp.src('src/pivotal-ui/components/alerts')
.pipe(license());
licenseStream.on('error', (error) => {
console.error(error);
callback();
});
licenseStream.pipe(writeArray((error, data) => {
result = data;
done();
}));
});
it('creates an MIT license for the component', () => {
expect(result[0].path).toEqual('alerts/LICENSE');
expect(result[0].contents.toString()).toContain('The MIT License');
});
});
|
/*globals define, _*/
/*jshint browser: true*/
/**
* @author rkereskenyi / https://github.com/rkereskenyi
*/
define(['js/KeyboardManager/IKeyTarget'], function (IKeyTarget) {
'use strict';
var DiagramDesignerWidgetKeyboard;
DiagramDesignerWidgetKeyboard = function () {
};
_.extend(DiagramDesignerWidgetKeyboard.prototype, IKeyTarget.prototype);
DiagramDesignerWidgetKeyboard.prototype.onKeyDown = function (eventArgs) {
var ret = true;
switch (eventArgs.combo) {
case 'del':
this.onSelectionDelete(this.selectionManager.getSelectedElements());
ret = false;
break;
case 'ctrl+a':
this.selectAll();
ret = false;
break;
case 'ctrl+q':
this.selectNone();
ret = false;
break;
case 'ctrl+i':
this.selectItems();
ret = false;
break;
case 'ctrl+u':
this.selectConnections();
ret = false;
break;
case 'ctrl+l':
this.selectInvert();
ret = false;
break;
case 'up':
this._moveSelection(0, -this.gridSize);
ret = false;
break;
case 'down':
this._moveSelection(0, this.gridSize);
ret = false;
break;
case 'left':
this._moveSelection(-this.gridSize, 0);
ret = false;
break;
case 'right':
this._moveSelection(this.gridSize, 0);
ret = false;
break;
case this.CONSTANTS.KEY_SHORT_CUT_MOVE_TO_TOP:
this.onAlignSelection(this.selectionManager.getSelectedElements(), this.CONSTANTS.MOVE_TO_TOP);
ret = false;
break;
case this.CONSTANTS.KEY_SHORT_CUT_MOVE_TO_BOTTOM:
this.onAlignSelection(this.selectionManager.getSelectedElements(), this.CONSTANTS.MOVE_TO_BOTTOM);
ret = false;
break;
case this.CONSTANTS.KEY_SHORT_CUT_MOVE_TO_LEFT:
this.onAlignSelection(this.selectionManager.getSelectedElements(), this.CONSTANTS.MOVE_TO_LEFT);
ret = false;
break;
case this.CONSTANTS.KEY_SHORT_CUT_MOVE_TO_RIGHT:
this.onAlignSelection(this.selectionManager.getSelectedElements(), this.CONSTANTS.MOVE_TO_RIGHT);
ret = false;
break;
default:
break;
/*case 'ctrl+c':
this.onClipboardCopy(this.selectionManager.getSelectedElements());
ret = false;
break;
case 'ctrl+v':
this.onClipboardPaste();
ret = false;
break;*/
}
return ret;
};
DiagramDesignerWidgetKeyboard.prototype.onKeyUp = function (eventArgs) {
var ret = true;
switch (eventArgs.combo) {
case 'up':
this._endMoveSelection();
ret = false;
break;
case 'down':
this._endMoveSelection();
ret = false;
break;
case 'left':
this._endMoveSelection();
ret = false;
break;
case 'right':
this._endMoveSelection();
ret = false;
break;
}
return ret;
};
DiagramDesignerWidgetKeyboard.prototype._moveSelection = function (dX, dY) {
if (!this._keyMoveDelta) {
this._keyMoveDelta = {x: 0, y: 0};
this.dragManager._initDrag(0, 0);
this.dragManager._startDrag(undefined);
}
this._keyMoveDelta.x += dX;
this._keyMoveDelta.y += dY;
this.dragManager._updateDraggedItemPositions(this._keyMoveDelta.x, this._keyMoveDelta.y);
};
DiagramDesignerWidgetKeyboard.prototype._endMoveSelection = function () {
if (this._keyMoveDelta) {
// reinitialize keyMove data
this._keyMoveDelta = undefined;
this.dragManager._endDragAction();
}
};
return DiagramDesignerWidgetKeyboard;
});
|
import "core-js/modules/web.dom.iterable";
import "core-js/modules/es6.promise";
var p = Promise.resolve(0);
Promise.all([p]).then(function (outcome) {
alert("OK");
});
|
fn() => x
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon"));
var _jsxRuntime = require("react/jsx-runtime");
var _default = (0, _createSvgIcon.default)([/*#__PURE__*/(0, _jsxRuntime.jsx)("circle", {
cx: "12",
cy: "23",
r: "1"
}, "0"), /*#__PURE__*/(0, _jsxRuntime.jsx)("circle", {
cx: "8",
cy: "23",
r: "1"
}, "1"), /*#__PURE__*/(0, _jsxRuntime.jsx)("circle", {
cx: "16",
cy: "23",
r: "1"
}, "2"), /*#__PURE__*/(0, _jsxRuntime.jsx)("path", {
d: "M13.41 10 17 6.42c.39-.39.39-1.02 0-1.42L12.21.21c-.14-.14-.32-.21-.5-.21-.39 0-.71.32-.71.71v6.88L7.11 3.71a.9959.9959 0 0 0-1.41 0c-.39.39-.39 1.02 0 1.41L10.59 10 5.7 14.89c-.39.39-.39 1.02 0 1.41.39.39 1.02.39 1.41 0L11 12.41v6.88c0 .39.32.71.71.71.19 0 .37-.07.5-.21L17 15c.39-.39.39-1.02 0-1.42L13.41 10zM13 3.83l1.88 1.88L13 7.59V3.83zm0 12.34v-3.76l1.88 1.88L13 16.17z"
}, "3")], 'SettingsBluetoothRounded');
exports.default = _default;
|
'use strict';
module.exports = {
db: {
dbName:'sean-dev',
username : 'SeanDB',
password : 'HU7XQQBNWq',
dialect: "postgres", // 'sqlite', 'postgres', 'mariadb','mysql'
port : 5432 // 5432 for postgres, 3306 for mysql and mariaDB ,
},
app: {
title: 'SEAN - Development Environment'
},
facebook: {
clientID: process.env.FACEBOOK_ID || 'APP_ID',
clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET',
callbackURL: 'http://localhost:3000/auth/facebook/callback'
},
twitter: {
clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY',
clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET',
callbackURL: 'http://localhost:3000/auth/twitter/callback'
},
google: {
clientID: process.env.GOOGLE_ID || 'APP_ID',
clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET',
callbackURL: 'http://localhost:3000/auth/google/callback'
},
linkedin: {
clientID: process.env.LINKEDIN_ID || 'APP_ID',
clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET',
callbackURL: 'http://localhost:3000/auth/linkedin/callback'
},
github: {
clientID: process.env.GITHUB_ID || 'APP_ID',
clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET',
callbackURL: 'http://localhost:3000/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'
}
}
}
};
|
(function () {
'use strict';
angular
.module('nama.common')
.directive('namaNav', namaNav);
namaNav.$inject = [];
function namaNav() {
return {
restrict: 'E',
templateUrl: '/nama-framework/common/nav/nav.html',
controller: 'NavController',
controllerAs: 'vm',
bindToController: true,
scope: {
brand: '@'
}
};
}
}());
|
var module = angular.module("example", ["agGrid"]);
module.controller("exampleCtrl", function($scope, $http) {
var columnDefs = [
{headerName: "Gold", field: "gold", width: 100},
{headerName: "Silver", field: "silver", width: 100},
{headerName: "Bronze", field: "bronze", width: 100},
{headerName: "Total", field: "total", width: 100},
{headerName: "Age", field: "age", width: 90, checkboxSelection: true},
{headerName: "Country", field: "country", width: 120, rowGroupIndex: 0},
{headerName: "Year", field: "year", width: 90},
{headerName: "Date", field: "date", width: 110},
{headerName: "Sport", field: "sport", width: 110, rowGroupIndex: 1}
];
$scope.gridOptions = {
columnDefs: columnDefs,
rowData: null,
rowSelection: 'multiple',
groupAggFunction: groupAggFunction,
groupSelectsChildren: true,
suppressRowClickSelection: true,
groupColumnDef: {headerName: "Athlete", field: "athlete", width: 200,
cellRenderer: {
renderer: "group",
checkbox: true
}}
};
function groupAggFunction(rows) {
var sums = {
gold: 0,
silver: 0,
bronze: 0,
total: 0
};
rows.forEach(function(row) {
var data = row.data;
sums.gold += data.gold;
sums.silver += data.silver;
sums.bronze += data.bronze;
sums.total += data.total;
});
return sums;
}
$http.get("../olympicWinners.json")
.then(function(res){
$scope.gridOptions.api.setRowData(res.data);
});
});
|
import CalendarDayNamesHeader from "../base/CalendarDayNamesHeader.js";
import { template } from "../base/internal.js";
import { fragmentFrom } from "../core/htmlLiterals.js";
/**
* CalendarDayNamesHeader component in the Plain reference design system
*
* @inherits CalendarDayNamesHeader
*/
class PlainCalendarDayNamesHeader extends CalendarDayNamesHeader {
get [template]() {
const result = super[template];
result.content.append(
fragmentFrom.html`
<style>
:host {
font-size: smaller;
}
[part~="day-name"] {
padding: 0.3em;
text-align: center;
white-space: nowrap;
}
[weekend] {
color: gray;
}
</style>
`
);
return result;
}
}
export default PlainCalendarDayNamesHeader;
|
/*global describe, beforeEach, it*/
'use strict';
var assert = require('assert');
describe('video generator', function () {
it('can be imported without blowing up', function () {
var app = require('../app');
assert(app !== undefined);
});
});
|
'use strict';
module.exports = function modify(config) {
console.log('Razzle comes with React! This package is a stub.');
return config;
};
|
var path = require("path");
var webpack = require("webpack");
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var pkg = require(path.join(process.cwd(), 'package.json'));
var assetsPath = path.join(__dirname, "public","js");
var publicPath = "/public/";
var commonLoaders = [
{
test: /\.js$|\.jsx$/,
loaders: ["babel"],
include: path.join(__dirname, "app")
},
{
test: /\.css$/,
loader: ExtractTextPlugin.extract(
'css?sourceMap&-restructuring!' +
'autoprefixer-loader'
)
},
{
test: /\.less$/,
loader: ExtractTextPlugin.extract(
'css?sourceMap!' +
'autoprefixer-loader!' +
'less?{"sourceMap":true,"modifyVars":' + JSON.stringify(pkg.theme || {})+'}'
)
}
];
module.exports = {
// The configuration for the client
name: "browser",
/* The entry point of the bundle
* Entry points for multi page app could be more complex
* A good example of entry points would be:
* entry: {
* pageA: "./pageA",
* pageB: "./pageB",
* pageC: "./pageC",
* adminPageA: "./adminPageA",
* adminPageB: "./adminPageB",
* adminPageC: "./adminPageC"
* }
*
* We can then proceed to optimize what are the common chunks
* plugins: [
* new CommonsChunkPlugin("admin-commons.js", ["adminPageA", "adminPageB"]),
* new CommonsChunkPlugin("common.js", ["pageA", "pageB", "admin-commons.js"], 2),
* new CommonsChunkPlugin("c-commons.js", ["pageC", "adminPageC"]);
* ]
*/
context: path.join(__dirname, "app"),
entry: {
app: "./app.js"
},
output: {
// The output directory as absolute path
path: assetsPath,
// The filename of the entry chunk as relative path inside the output.path directory
filename: "bundle.js",
// The output path from the view of the Javascript
publicPath: publicPath
},
module: {
loaders: commonLoaders
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
new ExtractTextPlugin('ant.css', {
disable: false,
allChunks: true
}),
]
};
|
<Card>
<Card.Header>
<Nav variant="tabs" defaultActiveKey="#first">
<Nav.Item>
<Nav.Link href="#first">Active</Nav.Link>
</Nav.Item>
<Nav.Item>
<Nav.Link href="#link">Link</Nav.Link>
</Nav.Item>
<Nav.Item>
<Nav.Link href="#disabled" disabled>
Disabled
</Nav.Link>
</Nav.Item>
</Nav>
</Card.Header>
<Card.Body>
<Card.Title>Special title treatment</Card.Title>
<Card.Text>
With supporting text below as a natural lead-in to additional content.
</Card.Text>
<Button variant="primary">Go somewhere</Button>
</Card.Body>
</Card>;
|
import markdownIt from 'markdown-it';
import _ from 'lodash';
import footnotes from 'markdown-it-footnote';
export default function (opts) {
const mergedOpts = _.assign({}, opts, { html: true, linkify: true });
const md = markdownIt(mergedOpts).use(footnotes);
if (mergedOpts.openLinksExternally) {
// Remember old renderer, if overriden, or proxy to default renderer
const defaultRender = md.renderer.rules.link_open || function (tokens, idx, options, env, self) {
return self.renderToken(tokens, idx, options);
};
md.renderer.rules.link_open = function (tokens, idx, options, env, self) {
const aIndex = tokens[idx].attrIndex('target');
if (aIndex < 0) {
tokens[idx].attrPush(['target', '_blank']); // add new attribute
} else {
tokens[idx].attrs[aIndex][1] = '_blank'; // replace value of existing attr
}
// pass token to default renderer.
return defaultRender(tokens, idx, options, env, self);
};
}
return md;
}
|
angular.module('app', [])
.controller('Controller', function($scope) {
$scope.hi = 'world';
});
|
'use strict';
var setPrototypeOf = require('es5-ext/object/set-prototype-of')
, mixin = require('es5-ext/object/mixin-prototypes')
, iterator = require('es6-iterator/valid-iterable')
, forOf = require('es6-iterator/for-of')
, toArray = require('es5-ext/array/to-array')
, Set = require('es6-set')
, d = require('d')
, validObservableSet = require('observable-set/valid-observable-set')
, defineProperty = Object.defineProperty, getPrototypeOf = Object.getPrototypeOf
, add = Set.prototype.add, clear = Set.prototype.clear, del = Set.prototype.delete
, SetsSet;
module.exports = SetsSet = function (multiSet, iterable) {
var sets, set;
if (!(this instanceof SetsSet)) throw new TypeError('Constructor requires \'new\'');
if (iterable != null) {
iterator(iterable);
sets = [];
forOf(iterable, function (value) {
sets.push(validObservableSet(value));
});
}
set = new Set(sets);
if (setPrototypeOf) setPrototypeOf(set, getPrototypeOf(this));
else mixin(set, getPrototypeOf(this));
defineProperty(set, '__master__', d('', multiSet));
return set;
};
if (setPrototypeOf) setPrototypeOf(SetsSet, Set);
SetsSet.prototype = Object.create(Set.prototype, {
constructor: d(SetsSet),
add: d(function (set) {
if (this.has(validObservableSet(set))) return this;
add.call(this, set);
this.__master__._onSetAdd(set);
return this;
}),
clear: d(function () {
var sets;
if (!this.size) return;
sets = toArray(this);
clear.call(this);
this.__master__._onSetsClear(sets);
}),
delete: d(function (set) {
if (!this.has(set)) return false;
del.call(this, set);
this.__master__._onSetDelete(set);
return true;
})
});
|
var gulp = require('gulp');
var argv = require('yargs').argv;
var config = require('../config.js');
var dist = config.release = !!argv.dist;
console.log('_________________________________________');
console.log('');
console.log(' Building for distribution: ' + dist);
console.log('');
gulp.task('default', ['images', 'lib', 'sass', 'watch', 'code', 'html']);
|
var routes = {
"index" : {
title : "",
url : "/",
controller : main
},
"404" : {
title : "404",
url : "/404",
controller : fourohfour
}
};
|
var searchData=
[
['rgb',['Rgb',['../structarctic_1_1_rgb.html',1,'arctic']]],
['rgba',['Rgba',['../structarctic_1_1easy_1_1_rgba.html',1,'arctic::easy']]]
];
|
var lightstep = require("../../../..");
var FileTransport = require("../../../util/file_transport");
var path = require('path');
var reportFilename = path.join(__dirname, "../../../results/on_exit_child.json");
Tracer = new lightstep.Tracer({
access_token : "{your_access_token}",
component_name : "lightstep-tracer/unit-test/on_exit",
override_transport : new FileTransport(reportFilename),
});
for (var i = 0; i < 10; i++) {
var span = Tracer.startSpan("test_span_" + i);
span.log({"log_index" : i});
span.finish();
}
|
/* RequireJS Module Dependency Definitions */
define([
'app',
'jquery',
'marionette',
'handlebars',
'collections/TopBarMessagesCollection',
'text!templates/main_topbar.html',
'foundation-reveal',
'foundation-topbar'
], function (App, $, Marionette, Handlebars, TopBarMessagesCollection, template){
"use strict";
return Marionette.ItemView.extend({
//Template HTML string
template: Handlebars.compile(template),
collection: new TopBarMessagesCollection(),
initialize: function(options){
this.options = options;
},
events: {
"click #logoutButton": "logout",
"click #topbar_settingsButton": "settingsShow",
"click #topbar_profileButton": "myprofileShow",
"click #topbar_message-seeall": "messageSeeall",
"click #topbar_forumsButton": "forumsShow",
"click #topbar_leaderboardsButton": "leaderboardsShow",
"click #topbar_announcementsButton": "announcementsShow",
"click #topbar_adminButton": "adminShow",
"mouseenter #topbar_messageButton,#topbar_messageContainer": "messagesShow",
"mouseleave #topbar_messageButton,#topbar_messageContainer": "messagesHide",
"click li.name": "getMessages"
},
onRender: function(){
this.getMessages();
},
onBeforeDestroy: function() {
this.unbind();
},
getMessages: function(event){
if(event){
event.stopPropagation();
event.preventDefault();
}
var self = this;
$.ajax({
url: '/api/messages/chat/?username='+App.session.user.get('username'),
type: 'GET',
contentType: 'application/json',
dataType: 'json',
crossDomain: true,
xhrFields: {
withCredentials: true
},
success: function(data){
self.collection.reset();
self.collection.add(data, {merge: true});
var html = self.template(self.collection.toJSON());
html += self.template({messageCount:self.collection.length});
html += self.template($.extend({messageCount:self.collection.length},App.session.user.toJSON()));
self.$el.html(html);
$(document).foundation('reflow');
},
error: function(data){
console.log(data);
}
});
},
messagesShow: function() {
this.$("#topbar_messageContainer").show();
},
messagesHide: function() {
this.$("#topbar_messageContainer").hide();
},
messageSeeall: function(){
this.triggerMethod("click:messages:show");
},
detectUserAgent: function() {
var userAgent;
var fileType;
if(navigator.userAgent.match(/Android/g)) {
userAgent = "You are using an Android";
fileType = ".apk";
} else if(navigator.userAgent.match(/iPhone/g)){
userAgent = "iPhone";
fileType = ".ipa";
} else if(navigator.userAgent.match(/Windows/g)){
userAgent = "Windows";
fileType = ".exe";
} else if(navigator.userAgent.match(/Mac/g)){
userAgent = "Mac";
fileType = ".dmg";
} else if(navigator.userAgent.match(/Linux/g)){
userAgent = "Linux";
fileType = ".deb";
}
this.$el.find("#modalPlatform").html("You have the following OS: "+userAgent);
this.$el.find("#modalDownload").html("Download the "+fileType+" on the right to begin playing the game! -->");
this.$el.find("#myModal").foundation('reveal','open');
},
settingsShow: function(){
this.triggerMethod("click:settings:show");
},
myprofileShow: function(){
this.triggerMethod("click:myprofile:show");
},
forumsShow: function(){
this.triggerMethod("click:forums:show");
},
leaderboardsShow: function(){
this.triggerMethod("click:leaderboards:show");
},
announcementsShow: function(){
this.triggerMethod("click:announcements:show");
},
adminShow: function() {
this.triggerMethod("click:admin:show");
},
logout: function(event) {
if(event){
event.stopPropagation();
event.preventDefault();
}
App.session.logout({
},{
success: function(){
console.log("Logged out");
Backbone.history.navigate('home', {trigger: true});
},
error: function() {
console.log("Logged out failed");
}
});
}
});
});
|
/*jshint node: true*/
'use strict';
// Defaults derived from: https://github.com/dequelabs/axe-core
const defaults = {
rules: {
'area-alt': { 'enabled': true },
'audio-caption': { 'enabled': true },
'button-name': { 'enabled': true },
'document-title': { 'enabled': true },
'empty-heading': { 'enabled': true },
'frame-title': { 'enabled': true },
'frame-title-unique': { 'enabled': true },
'image-alt': { 'enabled': true },
'image-redundant-alt': { 'enabled': true },
'input-image-alt': { 'enabled': true },
'link-name': { 'enabled': true },
'object-alt': { 'enabled': true },
'server-side-image-map': { 'enabled': true },
'video-caption': { 'enabled': true },
'video-description': { 'enabled': true },
'definition-list': { 'enabled': true },
'dlitem': { 'enabled': true },
'heading-order': { 'enabled': true },
'href-no-hash': { 'enabled': true },
'layout-table': { 'enabled': true },
'list': { 'enabled': true },
'listitem': { 'enabled': true },
'p-as-heading': { 'enabled': true },
'scope-attr-valid': { 'enabled': true },
'table-duplicate-name': { 'enabled': true },
'table-fake-caption': { 'enabled': true },
'td-has-header': { 'enabled': true },
'td-headers-attr': { 'enabled': true },
'th-has-data-cells': { 'enabled': true },
'duplicate-id': { 'enabled': true },
'html-has-lang': { 'enabled': true },
'html-lang-valid': { 'enabled': true },
'meta-refresh': { 'enabled': true },
'valid-lang': { 'enabled': true },
'checkboxgroup': { 'enabled': true },
'label': { 'enabled': true },
'radiogroup': { 'enabled': true },
'accesskeys': { 'enabled': true },
'bypass': { 'enabled': true },
'tabindex': { 'enabled': true },
// TODO: this should be re-enabled when we upgrade to axe-core ^3.1.1 (https://github.com/dequelabs/axe-core/issues/961)
'aria-allowed-attr': { 'enabled': false },
'aria-required-attr': { 'enabled': true },
'aria-required-children': { 'enabled': true },
'aria-required-parent': { 'enabled': true },
'aria-roles': { 'enabled': true },
'aria-valid-attr': { 'enabled': true },
'aria-valid-attr-value': { 'enabled': true },
'blink': { 'enabled': true },
'color-contrast': { 'enabled': true },
'link-in-text-block': { 'enabled': true },
'marquee': { 'enabled': true },
'meta-viewport': { 'enabled': true },
'meta-viewport-large': { 'enabled': true }
}
};
module.exports = {
getConfig: () => {
const skyPagesConfigUtil = require('../sky-pages/sky-pages.config');
const skyPagesConfig = skyPagesConfigUtil.getSkyPagesConfig();
let config = {};
// Merge rules from skyux config.
if (skyPagesConfig.skyux.a11y && skyPagesConfig.skyux.a11y.rules) {
config.rules = Object.assign({}, defaults.rules, skyPagesConfig.skyux.a11y.rules);
}
// The consuming SPA wishes to disable all rules.
if (skyPagesConfig.skyux.a11y === false) {
config.rules = Object.assign({}, defaults.rules);
Object.keys(config.rules).forEach((key) => {
config.rules[key].enabled = false;
});
}
if (!config.rules) {
return defaults;
}
return config;
}
};
|
import Instruction from './Instruction';
function arcTo(x1, y1, x2, y2, r) {
return new Instruction('call', {
name: 'arcTo',
args: [x1, y1, x2, y2, r],
count: 5,
});
}
export default arcTo;
|
'use strict';
exports.fixShould = function fixShould(str) {
var segs = str.split('var should = require(\'should\');');
return segs.join('require(\'should\');');
};
|
//// config/database.js
module.exports = {
url: 'mongodb://gaurav:gaurav@dogen.mongohq.com:10056/cmpe275'
};
|
/* jslint node: true */
/*!
* rinco - include templates
* Copyright(c) 2014 Allan Esquina
* MIT Licensed
*/
'use strict';
var rinco = require('../rinco');
var it = require('../interpreter');
var Markdown = require('markdown').markdown;
var md = require('markdown-it')({
html: true,
linkify: true,
typographer: true
});
var config = require('../constants');
// Parse templates files
rinco.render.middleware.register(function rinco_template(next, content) {
[{ start:'<r-include', end:'/>'}].map(function (tag) {
function r(content) {
var has = false;
content = it.parse(content, tag, function (prc) {
var filename = prc.trim();
var tpl = rinco.fs.file.read(rinco.fs.path.join(config.INCLUDE_DIR, filename));
has = true;
if(tpl) {
if (rinco.fs.path.extname(filename) === ".md") {
tpl = md.render(tpl.toString());
}
return tpl;
}
else {
return "File: " + rinco.fs.path.join(config.INCLUDE_DIR, filename);
}
});
return has ? r(content) : content;
}
content = r(content.toString());
});
next(content);
});
|
BASE.require(["Object"], function () {
BASE.namespace("LG.core.dataModel.core");
var _globalObject = this;
LG.core.dataModel.core.Credential = (function (Super) {
var Credential = function () {
var self = this;
if (self === _globalObject) {
throw new Error("Credential constructor invoked with global context. Say new.");
}
Super.call(self);
self["authenticationFactors"] = [];
self["authentications"] = [];
self["personId"] = null;
self["person"] = null;
self["startDate"] = null;
self["endDate"] = null;
self["id"] = null;
return self;
};
BASE.extend(Credential, Super);
return Credential;
}(Object));
});
|
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule dangerousStyleValue
*/
import CSSProperty from './CSSProperty'
import warning from 'fbjs/lib/warning'
let isUnitlessNumber = CSSProperty.isUnitlessNumber
let styleWarnings = {}
/**
* Convert a value into the proper css writable value. The style name `name`
* should be logical (no hyphens), as specified
* in `CSSProperty.isUnitlessNumber`.
*
* @param {string} name CSS property name such as `topMargin`.
* @param {*} value CSS property value such as `10px`.
* @param {ReactDOMComponent} component
* @return {string} Normalized style value with dimensions applied.
*/
function dangerousStyleValue(name, value, component) {
// Note that we've removed escapeTextForBrowser() calls here since the
// whole string will be escaped when the attribute is injected into
// the markup. If you provide unsafe user data here they can inject
// arbitrary CSS which may be problematic (I couldn't repro this):
// https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet
// http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/
// This is not an XSS hole but instead a potential CSS injection issue
// which has lead to a greater discussion about how we're going to
// trust URLs moving forward. See #2115901
let isEmpty = value == null || typeof value === 'boolean' || value === ''
if (isEmpty) {
return ''
}
let isNonNumeric = isNaN(value)
if (isNonNumeric || value === 0 || isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name]) {
return '' + value // cast to string
}
if (typeof value === 'string') {
if (process.env.NODE_ENV !== 'production') {
// Allow '0' to pass through without warning. 0 is already special and
// doesn't require units, so we don't need to warn about it.
if (component && value !== '0') {
let owner = component._currentElement._owner
let ownerName = owner ? owner.getName() : null
if (ownerName && !styleWarnings[ownerName]) {
styleWarnings[ownerName] = {}
}
let warned = false
if (ownerName) {
let warnings = styleWarnings[ownerName]
warned = warnings[name]
if (!warned) {
warnings[name] = true
}
}
if (!warned) {
process.env.NODE_ENV !== 'production' ? warning(false, 'a `%s` tag (owner: `%s`) was passed a numeric string value ' + 'for CSS property `%s` (value: `%s`) which will be treated ' + 'as a unitless number in a future version of React.', component._currentElement.type, ownerName || 'unknown', name, value) : void 0
}
}
}
value = value.trim()
}
return value + 'px'
}
export default dangerousStyleValue
|
function CScrollingBg(oSprite){
var _iLastObjIndex;
var _aTiles;
var _oSpriteTile;
this._init = function(oSprite){
_oSpriteTile = oSprite;
_aTiles = new Array();
var iYPos = -oSprite.height;
while( iYPos < CANVAS_HEIGHT){
var oTile = new createjs.Bitmap(oSprite);
oTile.y=iYPos;
iYPos += oSprite.height;
_aTiles.push(oTile);
s_oStage.addChild(oTile);
}
_iLastObjIndex = 0;
};
this.update = function(iSpeed){
for(var i=0;i<_aTiles.length;i++){
if(_aTiles[i].y > CANVAS_HEIGHT){
_aTiles[i].y = _aTiles[_iLastObjIndex].y - (_oSpriteTile.height);
_iLastObjIndex = i;
}
_aTiles[i].y += iSpeed;
}
};
this._init(oSprite);
}
|
// generate a hash from string
var crypto = require('crypto'),
text = 'hello bob',
key = 'mysecret key'
// create hahs
var hash = crypto.createHmac('sha512', key)
hash.update(text)
var value = hash.digest('hex')
// print result
console.log(value);
|
module.exports = function ({ serializers, $lookup }) {
serializers.inc.object = function () {
return function (object, $step = 0) {
let $_, $bite
return function $serialize ($buffer, $start, $end) {
switch ($step) {
case 0:
$step = 1
$bite = 7n
$_ = object.value
case 1:
while ($bite != -1n) {
if ($start == $end) {
return { start: $start, serialize: $serialize }
}
$buffer[$start++] = Number($_ >> $bite * 8n & 0xffn)
$bite--
}
$step = 2
case 2:
break
}
return { start: $start, serialize: null }
}
}
} ()
}
|
import applicationActions from '../../constants/application';
import productActions from '../../constants/products';
export default function fetchProductAndCheckIfFound(context, payload, done) {
context.dispatch(productActions.PRODUCTS_ITEM);
context.api.products.get(payload).then(function successFn(result) {
context.dispatch(productActions.PRODUCTS_ITEM_SUCCESS, result);
done && done();
}, function errorFn(err) {
context.dispatch(productActions.PRODUCTS_ITEM_ERROR, err.result);
context.dispatch(applicationActions.APPLICATION_ROUTE_ERROR, err.status);
done && done();
});
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.