text
stringlengths 2
6.14k
|
|---|
import 'normalize.css';
import 'babel-polyfill';
import sizeHelper from '../../../../Common/Misc/SizeHelper';
import MutualInformationDiagram from '../../../Native/MutualInformationDiagram';
import FieldSelector from '../../../Native/FieldSelector';
import CompositeClosureHelper from '../../../../../src/Common/Core/CompositeClosureHelper';
import FieldProvider from '../../../../../src/InfoViz/Core/FieldProvider';
import Histogram1DProvider from '../../../../../src/InfoViz/Core/Histogram1DProvider';
import Histogram2DProvider from '../../../../../src/InfoViz/Core/Histogram2DProvider';
import LegendProvider from '../../../../../src/InfoViz/Core/LegendProvider';
import MutualInformationProvider from '../../../../../src/InfoViz/Core/MutualInformationProvider';
import HistogramBinHoverProvider from '../../../../../src/InfoViz/Core/HistogramBinHoverProvider';
import dataModel from './state.json';
const bodyElt = document.querySelector('body');
const container = document.createElement('div');
container.style.position = 'relative';
container.style.width = '500px';
container.style.height = '500px';
container.style.float = 'left';
bodyElt.appendChild(container);
const fieldSelectorContainer = document.createElement('div');
fieldSelectorContainer.style.position = 'relative';
fieldSelectorContainer.style.width = '40%';
fieldSelectorContainer.style.height = '250px';
fieldSelectorContainer.style.float = 'left';
bodyElt.appendChild(fieldSelectorContainer);
const provider = CompositeClosureHelper.newInstance((publicAPI, model, initialValues = {}) => {
Object.assign(model, initialValues);
FieldProvider.extend(publicAPI, model, initialValues);
Histogram1DProvider.extend(publicAPI, model, initialValues);
Histogram2DProvider.extend(publicAPI, model, initialValues);
HistogramBinHoverProvider.extend(publicAPI, model);
LegendProvider.extend(publicAPI, model, initialValues);
MutualInformationProvider.extend(publicAPI, model, initialValues);
})(dataModel);
// Init Mutual information
// provider.setMutualInformationParameterNames([]);
provider.setHistogram2dProvider(provider);
// provider.setMutualInformationParameterNames(provider.getFieldNames());
// Create parallel coordinates
const diag = MutualInformationDiagram.newInstance({ provider, container });
// Create field selector
const fieldSelector = FieldSelector.newInstance({ provider, container: fieldSelectorContainer });
// Listen to window resize
sizeHelper.onSizeChange(() => {
diag.resize();
fieldSelector.resize();
});
sizeHelper.startListening();
sizeHelper.triggerChange();
|
/**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
export default class AnimatedSpriteExample extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
<Text style={styles.instructions}>
To get started, edit index.ios.js
</Text>
<Text style={styles.instructions}>
Press Cmd+R to reload,{'\n'}
Cmd+D or shake for dev menu
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
AppRegistry.registerComponent('AnimatedSpriteExample', () => AnimatedSpriteExample);
|
import test from 'tape';
test('translate', assert => {
System.import('./test/config.js')
.then(() => System.import('test/styles/test.scss!'))
.then((module) => {
assert.equal(typeof module.default, 'string', 'exports css string as a default');
})
.catch(e => {
assert.fail(e);
})
.then(() => {
assert.end();
});
});
|
pg.text = function() {
var importedFonts = [];
var setup = function() {
jQuery.getJSON('fonts/fonts.json', function(data){
jQuery.each(data.fonts, function(index, fontName) {
opentype.load('fonts/'+fontName, function (err, font) {
if (err) {
console.error(err);
} else {
importFontLoaded(font);
}
});
});
});
};
var addImportedFont = function(fontName, fontStyle, fontToAdd) {
// check if font with the same name already exists. if it does, just
// add the style (or overwrite it, if the style already exists)
for(var i=0; i<importedFonts.length; i++) {
var font = importedFonts[i];
if(font.name == fontName) {
for(var j=0; j<font.styles.length; j++) {
var fStyle = font.styles[j];
if(fStyle.style == fontStyle) {
fStyle.font = fontToAdd;
return true;
}
}
// if the style wasn't found, add it
font.styles.push({
'style': fontStyle,
'font' : fontToAdd
});
return true;
}
}
// if no font with that name existed, add it as new
importedFonts.push({
'name': fontName,
'styles': [{
'style': fontStyle,
'font': fontToAdd
}]
});
return true;
};
var getImportedFonts = function() {
return importedFonts;
};
var getImportedFont = function(fontName, fontStyle) {
for (var i=0; i<importedFonts.length; i++) {
var font = importedFonts[i];
if(font.name == fontName) {
for(var j=0; j<font.styles.length; j++) {
var style = font.styles[j];
if(style.style == fontStyle) {
return style.font;
}
}
}
}
};
var readFontFilesFromInput = function(e, doneCallback) {
var files = e.target.files;
for (var i = 0; i < files.length; i++) {
var reader = new FileReader();
reader.readAsArrayBuffer(files[i]);
reader.onload = function (e) {
try {
var font = opentype.parse(e.target.result);
importFontLoaded(font);
doneCallback(font);
} catch (err) {
console.error(err.toString());
}
};
reader.onerror = function (err) {
console.error(err.toString());
};
}
};
var importFontLoaded = function(font) {
var info = getShortInfoFromFont(font);
addImportedFont(info.fontFamily, info.fontStyle, font);
};
var getShortInfoFromFont = function(font) {
var info = {};
if(font.names.preferredFamily) {
info.fontFamily = font.names.preferredFamily.en;
} else {
info.fontFamily = font.names.fontFamily.en;
}
if(font.names.preferredSubfamily) {
info.fontStyle = font.names.preferredSubfamily.en;
} else {
info.fontStyle = font.names.fontSubfamily.en;
}
return info;
};
var createPGTextItem = function(text, options, pos) {
var font = getImportedFont(options.fontFamily, options.fontStyle);
var scaleFactor = options.fontSize/font.unitsPerEm;
var asc = font.ascender;
var desc = font.descender;
var glyphs = font.stringToGlyphs(text);
var offsetX = 0;
var textGroup = new paper.Group();
var lastGlyphIndex = -1;
jQuery.each(glyphs, function (index, glyph) {
var kerningPairValue = 0;
if(lastGlyphIndex >= 0) {
var kerning = font.kerningPairs[lastGlyphIndex+','+glyph.index];
if(kerning != undefined) {
kerningPairValue = kerning;
}
}
var glyphGroup = new paper.Group();
var glyphRect = new paper.Rectangle(new paper.Point(0, -asc), new paper.Point(glyph.advanceWidth, desc * -1));
var glyphRectPaperPath = new paper.Path.Rectangle(glyphRect);
glyphRectPaperPath.data.isPGGlyphRect = true;
glyphRectPaperPath.fillColor = 'rgba(0,0,0,0.00001)'; //hack to make finrect fill
glyphGroup.addChild(glyphRectPaperPath);
glyphGroup.data.isPGGlyphGroup = true;
var glyphPath = glyph.getPath(0, 0, font.unitsPerEm);
var glyphPaperPath = new paper.CompoundPath(glyphPath.toPathData());
pg.stylebar.applyActiveToolbarStyle(glyphPaperPath);
glyphPaperPath.opacity = 1;
glyphPaperPath.blendMode = 'normal';
glyphGroup.addChild(glyphPaperPath);
glyphGroup.pivot = glyphRectPaperPath.bounds.topLeft;
glyphGroup.position.x = offsetX + kerningPairValue + options.letterSpacing * 10;
textGroup.addChild(glyphGroup);
offsetX += glyphRectPaperPath.bounds.width - (kerningPairValue*-1) - (options.letterSpacing * 10 *-1);
lastGlyphIndex = glyph.index;
});
textGroup.scale(scaleFactor);
textGroup.position = new paper.Point(pos.x, pos.y);
textGroup.data.isPGTextItem = true;
textGroup.data.text = text;
textGroup.data.fontFamily = options.fontFamily;
textGroup.data.fontStyle = options.fontStyle;
textGroup.data.fontSize = options.fontSize;
textGroup.data.letterSpacing = options.letterSpacing;
return textGroup;
};
var convertSelectionToOutlines = function() {
var items = pg.selection.getSelectedItems();
for(var i=0; i<items.length; i++) {
var outlines = [];
var item = items[i];
var opacity = item.opacity;
var blendMode = item.blendMode;
if(pg.item.isPGTextItem(item)) {
for(var j=0; j<item.children.length; j++) {
var child = item.children[j];
if(child.data.isPGGlyphGroup) {
for(var k=0; k<child.children.length; k++) {
if(!child.children[k].data.isPGGlyphRect) {
outlines.push(child.children[k]);
}
}
}
}
item.remove();
var group = new paper.Group();
pg.layer.getActiveLayer().addChild(group);
group.addChildren(outlines);
group.opacity = opacity;
group.blendMode = blendMode;
pg.selection.setItemSelection(group, true);
}
}
};
return {
setup: setup,
addImportedFont: addImportedFont,
getImportedFonts: getImportedFonts,
getImportedFont: getImportedFont,
getShortInfoFromFont: getShortInfoFromFont,
createPGTextItem: createPGTextItem,
convertSelectionToOutlines: convertSelectionToOutlines,
readFontFilesFromInput: readFontFilesFromInput
};
}();
|
var Collection = require('./collection').Collection,
Model = require('../model/main').Model,
Snitch = require('../../mixins/snitch').Snitch;
var validateFnc = function(val, prop){
return this.parent(prop, val);
};
Collection.implement(new Snitch);
exports.Collection = new Class({
Extends: Collection,
setup: function(models, options){
this.setupValidators(this.options.validators);
this.parent(models, options);
return this;
},
_add: function(model, at){
/**
* Validate data, not a model instance.
*/
if (!this.validate(model)) {
this.signalError(model, at);
} else {
this.parent(model, at)
}
return this
},
/**
* Validate every property in a model
* @param {Object | Model | Array} models An object, a model instance, or an array mix of both to be validated
* @return {Boolean} True if all properties in the models validate
*/
validate: function(models){
var globalValidateFnc = this.getValidator('*');
models = Array.from(models);
return models.every(function(model){
var isInstance = instanceOf(model, Model);
// If the global validator exists, then all validation pipes through it
// Otherwise, use the prop referenced validator
return globalValidateFnc
? globalValidateFnc(isInstance ? model.getData() : model)
: (isInstance ? model.every(validateFnc, this) : Object.every(model, validateFnc, this));
}, this);
},
/**
* Proof every property in the models. Every validator property needs to exist in the model
*
* @param {Object | Model | Array} models An object, a model instance, or an array mix of both to be proofed
* @return {Boolean} True if all properties in the models proof, false otherwise.
*/
proofModel: function(models){
models = Array.from(models);
return models.every(function(model){
return Snitch.proof(
instanceOf(model, Model)
? model.getData()
: model,
this._validators
);
}, this);
},
/**
* Proof every model in the collection
* @return {Boolean} True if all properties in the collection's models proof, false otherwise.
*/
proof: function(){
return this.proofModel(this._models);
},
signalError: function(model, at){
!this.isSilent() && this.fireEvent('error', [this, model, at]);
}
});
|
// Karma configuration
// Generated on Wed Aug 10 2016 21:21:42 GMT+0200 (Közép-európai nyári idő )
module.exports = function (config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// list of files / patterns to load in the browser
files: [],
//.concat(
//["node_modules/lodash/lodash.js"],
//["node_modules/jquery/dist/jquery.js"],
//["src/*.ts"],
//['tests/**/*.ts']//, 'templates/**/*.html'
//),
proxies: {
'/src/': '/base/src/',
'/config.js': '/base/config',
'/jspm_packages/': '/base/jspm_packages/'
},
jspm: {
config: "./config.js",
serveFiles: [
"src/**/*.ts",
"jspm_packages/**/*.js"
//"/node_modules/babel-core/browser.js"
],
loadFiles: [
"tests/**/*.ts"
]
},
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jspm', 'jasmine'],
// list of files to exclude
exclude: [
],
plugins: [
"karma-jspm",
'karma-chrome-launcher',
'karma-jasmine',
"karma-junit-reporter"
//"karma-firefox-launcher",
//'karma-typescript-preprocessor'
//'karma-ng-html2js-preprocessor'
],
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['Chrome'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false,
// Concurrency level
// how many browser should be started simultaneous
concurrency: Infinity,
junitReporters: {
outputFile: 'test_out.xml',
suite: 'unit'
}
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
//preprocessors: {
// '**/*.ts': ['typescript']
//,'**/*.html': ['ng-html2js']
//},
/*typescriptPreprocessor: {
// options passed to the typescript compiler
options: {
sourceMap: true, // (optional) Generates corresponding .map file.
target: 'ES5', // (optional) Specify ECMAScript target version: 'ES3' (default), or 'ES5'
module: 'ES2015', // (optional) Specify module code generation: 'commonjs' or 'amd'
noImplicitAny: true, // (optional) Warn on expressions and declarations with an implied 'any' type.
noResolve: false, // (optional) Skip resolution and preprocessing.
removeComments: true, // (optional) Do not emit comments to output.
concatenateOutput: true, // (optional) Concatenate and emit output to single file. By default true if module option is omited, otherwise false.
diagnostics: true,
inlineSourceMap: true,
inlineSources: true
},
// transforming the filenames
transformPath: function (path) {
return path.replace(/\.ts$/, '.js');
}
},*/
/*ngHtml2JsPreprocessor: {
prependPrefix: '/'
},*/
});
}
|
'use strict';
/**
* @ngdoc function
* @name dormManagementToolApp.controller:MainCtrl
* @description
* # MainCtrl
* Controller of the dormManagementToolApp
*/
angular.module('dormManagementToolApp')
.controller('MainCtrl', function () {
this.awesomeThings = [
'HTML5 Boilerplate',
'AngularJS',
'Karma'
];
});
|
describe("The hyperHTML extension should", function() {
it("render its content when loaded", function() {
var count = 0;
var component = xtag.create(class extends XTagElement.extensions('hyper') {
'::hyper(true)'(render){
render`<h1>${this.foo}</h1><input value="${this.bar()}" />`;
}
get foo (){
return 'foo ' + count++;
}
bar (){
return 'bar ' + count++;
}
});
defineTestElement(component);
var node = new component();
var first = node.firstElementChild;
var last = node.lastElementChild;
expect(node.firstElementChild.textContent).toBe('foo 0');
expect(node.lastElementChild.value).toBe('bar 1');
node.render();
expect(node.firstElementChild.textContent).toBe('foo 2');
expect(node.lastElementChild.value).toBe('bar 3');
expect(node.firstElementChild === first).toBe(true);
expect(node.lastElementChild === last).toBe(true);
});
it("flush old nodes when rendering a new template", function() {
var count = 0;
var component = xtag.create(class extends XTagElement.extensions('hyper') {
'::hyper(true)'(render){
render`<h1>${this.foo}</h1><input value="${this.bar()}" />`;
}
'second::hyper'(render){
render`<h2>${this.foo}</h2><input value="${this.bar()}" />`;
}
get foo (){
return 'foo ' + count++;
}
bar (){
return 'bar ' + count++;
}
});
defineTestElement(component);
var node = new component();
var first = node.firstElementChild;
var last = node.lastElementChild;
expect(node.firstElementChild.innerHTML).toBe('foo 0');
expect(node.lastElementChild.value).toBe('bar 1');
node.render('second');
expect(node.firstElementChild.innerHTML).toBe('foo 2');
expect(node.lastElementChild.value).toBe('bar 3');
expect(node.firstElementChild === first).toBe(false);
expect(node.lastElementChild === last).toBe(false);
});
});
|
/* TODO
Handle multiline code after tag
%foo= some |
multiline |
code |
*/
(function(Prism) {
Prism.languages.haml = {
// Multiline stuff should appear before the rest
'multiline-comment': [
{
pattern: /((?:^|\n)([\t ]*))\/.*(\n\2[\t ]+.+)*/,
lookbehind: true,
alias: 'comment'
},
{
pattern: /((?:^|\n)([\t ]*))-#.*(\n\2[\t ]+.+)*/,
lookbehind: true,
alias: 'comment'
}
],
'multiline-code': [
{
pattern: /((?:^|\n)([\t ]*)(?:[~-]|[&!]?=)).*,[\t ]*(\n\2[\t ]+.*,[\t ]*)*(\n\2[\t ]+.+)/,
lookbehind: true,
inside: {
rest: Prism.languages.ruby
}
},
{
pattern: /((?:^|\n)([\t ]*)(?:[~-]|[&!]?=)).*\|[\t ]*(\n\2[\t ]+.*\|[\t ]*)*/,
lookbehind: true,
inside: {
rest: Prism.languages.ruby
}
}
],
// See at the end of the file for known filters
'filter': {
pattern: /((?:^|\n)([\t ]*)):[\w-]+(\n(?:\2[\t ]+.+|\s*?(?=\n)))+/,
lookbehind: true,
inside: {
'filter-name': {
pattern: /^:[\w-]+/,
alias: 'variable'
}
}
},
'markup': {
pattern: /((?:^|\n)[\t ]*)<.+/,
lookbehind: true,
inside: {
rest: Prism.languages.markup
}
},
'doctype': {
pattern: /((?:^|\n)[\t ]*)!!!(?: .+)?/,
lookbehind: true
},
'tag': {
// Allows for one nested group of braces
pattern: /((?:^|\n)[\t ]*)[%.#][\w\-#.]*[\w\-](?:\([^)]+\)|\{(?:\{[^}]+\}|[^}])+\}|\[[^\]]+\])*[\/<>]*/,
lookbehind: true,
inside: {
'attributes': [
{
// Lookbehind tries to prevent interpolations for breaking it all
// Allows for one nested group of braces
pattern: /(^|[^#])\{(?:\{[^}]+\}|[^}])+\}/,
lookbehind: true,
inside: {
rest: Prism.languages.ruby
}
},
{
pattern: /\([^)]+\)/,
inside: {
'attr-value': {
pattern: /(=\s*)(?:"(?:\\?.)*?"|[^)\s]+)/,
lookbehind: true
},
'attr-name': /[\w:-]+(?=\s*!?=|\s*[,)])/,
'punctuation': /[=(),]/
}
},
{
pattern: /\[[^\]]+\]/,
inside: {
rest: Prism.languages.ruby
}
}
],
'punctuation': /[<>]/
}
},
'code': {
pattern: /((?:^|\n)[\t ]*(?:[~-]|[&!]?=)).+/,
lookbehind: true,
inside: {
rest: Prism.languages.ruby
}
},
// Interpolations in plain text
'interpolation': {
pattern: /#\{[^}]+\}/,
inside: {
'delimiter': {
pattern: /^#\{|\}$/,
alias: 'punctuation'
},
rest: Prism.languages.ruby
}
},
'punctuation': {
pattern: /((?:^|\n)[\t ]*)[~=\-&!]/,
lookbehind: true
}
};
var filter_pattern = '((?:^|\\n)([\\t ]*)):{{filter_name}}(\\n(?:\\2[\\t ]+.+|\\s*?(?=\\n)))+';
// Non exhaustive list of available filters and associated languages
var filters = [
'css',
{filter:'coffee',language:'coffeescript'},
'erb',
'javascript',
'less',
'markdown',
'ruby',
'scss',
'textile'
];
var all_filters = {};
for (var i = 0, l = filters.length; i < l; i++) {
var filter = filters[i];
filter = typeof filter === 'string' ? {filter: filter, language: filter} : filter;
if (Prism.languages[filter.language]) {
all_filters['filter-' + filter.filter] = {
pattern: RegExp(filter_pattern.replace('{{filter_name}}', filter.filter)),
lookbehind: true,
inside: {
'filter-name': {
pattern: /^:[\w-]+/,
alias: 'variable'
},
rest: Prism.languages[filter.language]
}
}
}
}
Prism.languages.insertBefore('haml', 'filter', all_filters);
}(Prism));
|
'use strict';
/**
* @ngdoc overview
* @name baseAngular.core
* @description
* # baseAngular.core
*
* Core modules of the application.
*/
angular
.module('baseAngular.core', [
'ngRoute',
'ngSanitize'
]);
|
const fs = require('fs');
const assert = require('assert');
const depre = require('../../de-pre.js');
describe('de-pre.js', function () {
it('Testing removal of spaces.', function (done) {
fs.readFile('test/fixtures/a-spaces.html', 'utf8', function (err, data) {
document.body.innerHTML = data;
depre('pre');
assert.equal(document.querySelector('pre').textContent.match(/\s*\{/)[0], '{');
done();
});
});
it('Testing removal of spaces without specifying tag.', function (done) {
fs.readFile('test/fixtures/a-spaces.html', 'utf8', function (err, data) {
document.body.innerHTML = data;
depre();
assert.equal(document.querySelector('pre').textContent.match(/\s*\{/)[0], '{');
done();
});
});
it('Testing removal of tabs.', function (done) {
fs.readFile('test/fixtures/a-tabs.html', 'utf8', function (err, data) {
document.body.innerHTML = data;
depre('pre');
assert.equal(document.querySelector('pre').textContent.match(/\s*\{/)[0], '{');
done();
});
});
it('Testing removal of mixed whitespace.', function (done) {
fs.readFile('test/fixtures/a-mixed.html', 'utf8', function (err, data) {
document.body.innerHTML = data;
depre('pre');
assert.equal(document.querySelector('pre').textContent.match(/\s*\{/)[0], '{');
done();
});
});
});
|
/*
* Delete widget'as
* Ištrina Komentarus, paveiksliukus, albumus.
* Paveiksliukams ir albumams parodoma patvirtinimo lentelė
* Trinant paveiksliukus galima pasirinkti, ar trinsim tik iš šio albumo ar iš visų
* Option aID reikšmė nurodo, kuriame albume esame. Jei aID lygi nuliui, vadinasi albumas yra
* sugeneruotas dinamiškai (pvz.: visos vartotojo nuotraukos) ir jį galima ištrinti tik iš visų albumų.
*/
(function ($) {
function Delete() {
}
Delete.prototype.options = {
aID: 0,
type: 'image',
route: 'galerija_image_delete'
};
Delete.prototype._create = function () {
this.inProgress = false;
this._on(this.element, {
"click": "_prompt"
});
this.deleteAll = $.globals.bind(this.deleteAll, this);
this.deleteSingle = $.globals.bind(this.deleteSingle, this);
this.start = $.globals.bind(this.start, this);
this.srcPath = this.element.attr("src").replace(/[^\/]*$/,"");
this.csrf_token = this.element.attr("data-csrf_token");
};
Delete.prototype._prompt = function () {
if (this.inProgress)
return;
if(this.options.type == 'comment')
{
this.start(null);
return;
}
var delete_dialog = $("#delete-dialog" );
if(this.options.type == 'album')
{
delete_dialog.dialog(
{
modal:true,
width: '25em',
resizable: false,
context: this,
buttons:{
'Patvirtinti': this.start
}
}
);
return;
}
delete_dialog.dialog(
{
modal:true,
width: '25em',
resizable: false,
context: this,
buttons:{
'Iš visų albumų': this.deleteAll,
'Tik iš šio albumo':this.deleteSingle
}
}
);
if(this.options.aID == 0)
{
$(".ui-dialog-buttonpane button:contains('Tik iš šio albumo')").attr("disabled", true).addClass("ui-state-disabled");
}
};
Delete.prototype.deleteAll = function ()
{
this.start(null, 0);
};
Delete.prototype.deleteSingle = function ()
{
this.start(null, this.options.aID);
};
Delete.prototype._initiate = function () {
this.inProgress = true;
this.element.removeClass("disappear");
this.element.attr("src", this.srcPath + "loading.gif");
};
Delete.prototype._result = function (data) {
if (data.success) {
$.globals.container.isotope('remove', this.element.parent().parent(),
function(){
$(window).smartresize();
});
}
else {
this._failure();
}
$.globals.showStatus(data.success, data.message);
this.inProgress = false;
};
Delete.prototype._failure = function () {
this.element.attr("src", this.srcPath + "delete.png");
this.element.addClass("disappear");
};
Delete.prototype.start = function (event, extraData) {
var dialog_container = $("#delete-dialog");
if( dialog_container.hasClass('ui-dialog-content'))
dialog_container.dialog( "close" );
extraData = extraData || 0;
$.ajax({
url: Routing.generate(this.options.route),
type: "POST",
data: {
"ID": this.element.attr('data-id'),
"aID": extraData,
"csrf_token": this.csrf_token
},
context: this,
beforeSend: this._initiate,
error: function (xhr, ajaxOptions, thrownError) {
$.globals.showStatus(0, 'Ištrinti nepavyko');
this._failure();
},
success: this._result
});
};
$.widget("custom.Delete", Delete.prototype);
})(jQuery);
|
ccNotifications.config = {};
ccNotifications.config.save = function (key, value) {
localStorage.setItem('ccNotifications_' + key, JSON.stringify(value));
};
ccNotifications.config.load = function (key) {
return JSON.parse(localStorage.getItem('ccNotifications_' + key));
};
ccNotifications.menu = {};
ccNotifications.menu.add = function () {
var heading = function () {
var div = document.createElement('div');
div.className = 'title';
div.textContent = 'Cookie Crate Notifications';
return div;
};
var check = function (name, labelText, listener, toggleFunction) {
var div = document.createElement('div');
var input = document.createElement('input');
input.type = 'checkbox';
input.name = name;
var label = document.createElement('label');
label.textContent = labelText;
div.appendChild(input);
div.appendChild(label);
input.checked = ccNotifications.config.load(name);
input.listener = listener;
input.onclick = function () {
var state = input.checked;
ccNotifications.config.save(name, state);
toggleFunction(input.listener, state);
};
return div;
};
var frag = document.createDocumentFragment();
frag.appendChild(heading());
for (var key in ccNotifications.listeners) {
if (ccNotifications.listeners.hasOwnProperty(key)) {
var listener = ccNotifications.listeners[key];
var checkBox = check(listener.myname, listener.label, listener, function (listener, state) {
if (state === true) {
ccNotifications.addListener(listener);
} else {
ccNotifications.removeListener(listener);
}
});
frag.appendChild(checkBox);
}
}
var subSection = l('menu').childNodes[2];
var lastMenuIndex = subSection.childNodes.length;
var lastMenu = subSection.childNodes[lastMenuIndex - 1];
subSection.insertBefore(frag, lastMenu);
};
ccNotifications.initialize = function () {
for (var key in ccNotifications.listeners) {
if (ccNotifications.listeners.hasOwnProperty(key)) {
var listener = ccNotifications.listeners[key];
var name = listener.myname;
var configValue = ccNotifications.config.load(name);
if (configValue === null) {
ccNotifications.config.save(name, true);
configValue = true;
}
if (configValue === true) {
ccNotifications.addListener(listener);
}
}
}
};
ccNotifications.updateMenu = function () {
if (Game.onMenu === 'prefs') {
ccNotifications.menu.add();
}
};
ccNotifications.existingUpdateMenu = Game.UpdateMenu;
ccNotifications.initialize();
Game.UpdateMenu = function () {
ccNotifications.existingUpdateMenu();
ccNotifications.updateMenu();
};
|
var txtarea = document.activeElement
var text = '#!tag/';
var temp = "";
if(txtarea.selectionStart ===txtarea.selectionEnd)
{
var temp = prompt("Tag Value:","");
}
else
{
temp = (txtarea.value).substring(txtarea.selectionStart ,txtarea.selectionEnd);
}
temp = temp.trim();
if(temp==="")throw 'Error: Empty string or all spaces.'
temp = temp.split(" ");
for(i=1; i < temp.length ; i++)
{
if(temp[i]!=="")
temp[0]+="_" +temp[i];
}
text+=temp[0];
var nextpos = parseInt(txtarea.selectionStart,10) + text.length;
strPos = txtarea.selectionStart;
var front = (txtarea.value).substring(0,strPos);
var end = (txtarea.value).substring(txtarea.selectionEnd,txtarea.value.length);
txtarea.value = front+text+end;
txtarea.selectionStart = nextpos;
txtarea.selectionEnd = nextpos;
/*
if( isEnglish(temp) )
{
alert('here');
temp = temp.split(" ");
i=0;
while(i< temp.length && temp[i]==="")i++;
temp[0] = temp[i];
i++;
for(; i < temp.length ; i++)
{
if(temp[i]!=="")
temp[0]+="_" +temp[i];
}
alert(temp);
}
else if(isPersian(temp))
{
}
else
{
}
if(!isNaN(temp))
{
text+=temp;
}
else
throw 'Error: selection or input is not a number';
var nextpos = parseInt(txtarea.selectionStart,10) + text.length;
strPos = txtarea.selectionStart;
var front = (txtarea.value).substring(0,strPos);
var end = (txtarea.value).substring(txtarea.selectionEnd,txtarea.value.length);
txtarea.value = front+text+end;
txtarea.selectionStart = nextpos;
txtarea.selectionEnd = nextpos;
function isEnglish(str)
{
//alert(str.match("[0-9a-zA-Z_\\- ]*").toString().length + " \n" +str.length);
if(str.match("[0-9a-zA-Z_\\-]*").toString().length===str.length)
return true;
return false;
}
function isPersian(str)
{
}
*/
|
/* global Vue, Flash, gl */
/* eslint-disable no-param-reassign */
import canceledSvg from 'icons/_icon_status_canceled_borderless.svg';
import createdSvg from 'icons/_icon_status_created_borderless.svg';
import failedSvg from 'icons/_icon_status_failed_borderless.svg';
import manualSvg from 'icons/_icon_status_manual_borderless.svg';
import pendingSvg from 'icons/_icon_status_pending_borderless.svg';
import runningSvg from 'icons/_icon_status_running_borderless.svg';
import skippedSvg from 'icons/_icon_status_skipped_borderless.svg';
import successSvg from 'icons/_icon_status_success_borderless.svg';
import warningSvg from 'icons/_icon_status_warning_borderless.svg';
((gl) => {
gl.VueStage = Vue.extend({
data() {
const svgsDictionary = {
icon_status_canceled: canceledSvg,
icon_status_created: createdSvg,
icon_status_failed: failedSvg,
icon_status_manual: manualSvg,
icon_status_pending: pendingSvg,
icon_status_running: runningSvg,
icon_status_skipped: skippedSvg,
icon_status_success: successSvg,
icon_status_warning: warningSvg,
};
return {
builds: '',
spinner: '<span class="fa fa-spinner fa-spin"></span>',
svg: svgsDictionary[this.stage.status.icon],
};
},
props: {
stage: {
type: Object,
required: true,
},
},
updated() {
if (this.builds) {
this.stopDropdownClickPropagation();
}
},
methods: {
fetchBuilds(e) {
const areaExpanded = e.currentTarget.attributes['aria-expanded'];
if (areaExpanded && (areaExpanded.textContent === 'true')) return null;
return this.$http.get(this.stage.dropdown_path)
.then((response) => {
this.builds = JSON.parse(response.body).html;
}, () => {
const flash = new Flash('Something went wrong on our end.');
return flash;
});
},
/**
* When the user right clicks or cmd/ctrl + click in the job name
* the dropdown should not be closed and the link should open in another tab,
* so we stop propagation of the click event inside the dropdown.
*
* Since this component is rendered multiple times per page we need to guarantee we only
* target the click event of this component.
*/
stopDropdownClickPropagation() {
$(this.$el.querySelectorAll('.js-builds-dropdown-list a.mini-pipeline-graph-dropdown-item')).on('click', (e) => {
e.stopPropagation();
});
},
},
computed: {
buildsOrSpinner() {
return this.builds ? this.builds : this.spinner;
},
dropdownClass() {
if (this.builds) return 'js-builds-dropdown-container';
return 'js-builds-dropdown-loading builds-dropdown-loading';
},
buildStatus() {
return `Build: ${this.stage.status.label}`;
},
tooltip() {
return `has-tooltip ci-status-icon ci-status-icon-${this.stage.status.group}`;
},
triggerButtonClass() {
return `mini-pipeline-graph-dropdown-toggle has-tooltip js-builds-dropdown-button ci-status-icon-${this.stage.status.group}`;
},
},
template: `
<div>
<button
@click="fetchBuilds($event)"
:class="triggerButtonClass"
:title="stage.title"
data-placement="top"
data-toggle="dropdown"
type="button"
:aria-label="stage.title">
<span v-html="svg" aria-hidden="true"></span>
<i class="fa fa-caret-down" aria-hidden="true"></i>
</button>
<ul class="dropdown-menu mini-pipeline-graph-dropdown-menu js-builds-dropdown-container">
<div class="arrow-up" aria-hidden="true"></div>
<div
:class="dropdownClass"
class="js-builds-dropdown-list scrollable-menu"
v-html="buildsOrSpinner">
</div>
</ul>
</div>
`,
});
})(window.gl || (window.gl = {}));
|
// @flow
export function errUnknownOpt(name: string): string[] {
return [`Unknown option ${name}`];
}
export function errInvalidTimer(): string[] {
return ['Invalid "timer" option value'];
}
export function errInvalidLog(): string[] {
return ['"log" option must be function'];
}
export function errInvalidWarn(): string[] {
return ['"warn" option must be function'];
}
export function errInvalidClone(): string[] {
return ['"clone" option must be boolean or "auto"'];
}
export function errInvalidErrorHandling(): string[] {
return ['"errorHandling" option must be "warn" or "throw"'];
}
export function errInvalidDevTools(): string[] {
return ['"devTools" option must be boolean or "auto"'];
}
export function errInvalidDev(): string[] {
return ['"dev" option must be boolean'];
}
// StackTrace
// ----------
export function errInvalidStackTrace(): string[] {
return ['Invalid "stackTrace" option value'];
}
export function errInvalidStackTraceAsync(): string[] {
return ['"stackTraceAsync" option must be boolean or "auto"'];
}
export function errInvalidStackTraceShift(): string[] {
return ['"stackTraceShift" option must be a number'];
}
// Formatting
// ----------
export function errInvalidFormat(): string[] {
return ['"format" option must be boolean or "auto"'];
}
export function errInvalidFormatErrors(): string[] {
return ['"formatErrors" option must be boolean or "auto"'];
}
export function errInvalidHighlight(): string[] {
return ['"highlight" option must be boolean'];
}
export function errInvalidInspectOptions(): string[] {
return ['"inspectOptions" option must be object'];
}
export function errInvalidPrecision(): string[] {
return ['"precision" option must be number >=0'];
}
// In-Place Options
// ----------------
export function errInvalidGuard(): string[] {
return ['"guard" option must be number'];
}
export function errInvalidRepeat(): string[] {
return ['"repeat" option must be string or number >= 0'];
}
|
$(function () {
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
defaultSeriesType: 'pie',
},
title: {
text: '食べたリンゴたち'
},
tooltip: {
formatter: function () {
return '<b>' + this.point.name + '</b>: ' + this.point.y + '個';
}
},
plotOptions: {
pie: {
allowPointSelect: true,
showInLegend: true
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: 0,
y: 100
},
series: [{
data: [
]
}]
});
$.getJSON('https://ringo-tabetter-api.herokuapp.com/api/v1/total?callback=?', function (res) {
$.each(res, function (i, json) {
chart.series[0].addPoint({
name: json['name'],
y: json['quantity'],
color: json['color']
});
});
});
});
|
// Register a 'rendered' callback on the submit button
// to attach _uihooks to the atPwdForm
// this way, every time the atPwdForm content changed
// the container fview is asked to recompute its height
Template.atPwdFormBtn.rendered = function(){
var fview = FView.from(this);
this.firstNode.parentNode._uihooks = {
// everytime something is inserted...
insertElement: function (node, next) {
// ...asks to recompute the height
fview.autoHeight();
// then simply insert the element as required
$(node).insertBefore(next);
},
// everytime something is removed...
removeElement: function(node) {
// ...asks to recompute the height
fview.autoHeight();
// then simply remove the element as required
$(node).remove();
}
};
};
|
import axios from 'axios';
import config from './../../config.json';
const api = axios.create({
baseURL: config.api.url,
timeout: 2000,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'token': ''
}
});
export default api;
|
/* Javascript for users Bundle */
jQuery(document).ready(function(){
});
|
define(function(require) {
var Backbone = require('backbone'),
Handlebars = require('handlebars'),
template = require('text!templates/Footer.html');
return Backbone.View.extend({
template : Handlebars.compile(template),
className : 'footer',
id : 'footer',
render : function() {
this.$el.html(this.template(this));
return this;
},
author : function() {
return 'Simon Jonsson';
},
year : function() {
return 2013;
}
});
});
|
var bookminder = {
getTitle: function(url){
var addrField = document.getElementById("addr");
addrField.value = url;
},
setup: function(){
chrome.tabs.query({active: true, lastFocusedWindow: true}, function(tabs) {
var url = tabs[0].url;
bookminder.getTitle(url);
});
}
};
document.addEventListener('DOMContentLoaded', function () {
bookminder.setup();
});
|
var Model = require('../Model');
var DocumentPageConsult = Model.extend({
defaults: {
/**
* URL where this document page can be viewed.
*/
Url: null,
/**
* Time in millis when the page consult will expire.
*/
ExpirationDate: null
}
});
module.exports = DocumentPageConsult;
|
/*global extend*/
goog.require('Odyssey.Generics.extend');
goog.require('Odyssey.Events.Event');
goog.provide('Odyssey.Events.MapRenderCompleteEvent');
Odyssey.Events.MapRenderCompleteEvent = (function () {
"use strict";
/**
* @constructor
*/
function OdysseyMapRenderCompleteEvent() {}
// Extends OdysseyEvent
extend(OdysseyMapRenderCompleteEvent.prototype, new Odyssey.Events.Event('OdysseyMapRenderComplete'));
return OdysseyMapRenderCompleteEvent;
}());
|
module.exports = {
key: 'secret'
};
|
'use strict'
const t = require('tap')
const test = t.test
const Fastify = require('../..')
const h2url = require('h2url')
const msg = { hello: 'world' }
var fastify
try {
fastify = Fastify({
http2: true
})
t.pass('http2 successfully loaded')
} catch (e) {
t.fail('http2 loading failed', e)
}
fastify.get('/', function (req, reply) {
reply.code(200).send(msg)
})
fastify.listen(0, err => {
t.error(err)
fastify.server.unref()
test('http UNKNOWN_METHOD request', async (t) => {
t.plan(2)
const url = `http://localhost:${fastify.server.address().port}`
const res = await h2url.concat({ url, method: 'UNKNOWN_METHOD' })
t.strictEqual(res.headers[':status'], 404)
t.deepEqual(JSON.parse(res.body), {
statusCode: 404,
error: 'Not Found',
message: 'Not Found'
})
})
})
|
'use strict';
angular.module('admin.user', ['ngTable'])
.config([
'$stateProvider',
'$urlRouterProvider',
'RestangularProvider',
function($stateProvider, $urlRouterProvider, RestangularProvider) {
var viewPath = 'gzero/admin/views/user/';
// Now set up the states
$stateProvider
.state('user', {
url: '/user',
templateUrl: viewPath + 'index.html'
})
.state('user.show', {
url: '/{userId}/show',
views: {
'content': {
templateUrl: viewPath + 'show.html',
controller: 'UserDetailsCtrl'
}
}
}).state('user.edit', {
url: '/{userId}/edit',
views: {
'content': {
templateUrl: viewPath + 'edit.html',
controller: 'UserEditCtrl'
}
}
})
.state('user.list', {
url: '/list?page&perPage',
views: {
'content': {
templateUrl: viewPath + 'list.html'
}
}
});
}
])
.controller('UserListCtrl', require('./controllers/UserListCtrl'))
.controller('UserDeleteCtrl', require('./controllers/directives/UserDeleteCtrl'))
.controller('UserEditCtrl', require('./controllers/UserEditCtrl'))
.controller('UserDetailsCtrl', require('./controllers/UserDetailsCtrl'))
.factory('UserRepository', require('./services/UserRepository.js'))
.directive('userDeleteButton', require('./directives/UserDeleteButton.js'))
.directive('userActionsDropdown', ['$dropdown', require('./directives/UserActionsDropdown.js')])
.run([
'NavBar',
function(NavBar) {
NavBar.add({
title: 'USERS', action: 'user.list', icon: 'fa fa-user'
//children: [
// {
// title: 'USER_LIST',
// action: 'user.list',
// icon: 'fa fa-th'
// }
//]
});
}
]);
|
/**
* Created by dd on 12/15/14.
*/
Meteor.publish("patientDiagnoses", function (patientId) {
return getPatientDiagnoses(patientId);
});
Meteor.publish("patientFlags", function (patientId) {
return getPatientFlags(patientId);
});
Meteor.publish("patientQuestions", function (flags) {
return getPatientQuestions(flags);
});
Meteor.publish("patientMeds", function (patientId) {
return getPatientMeds(patientId);
});
//Meteor.publish("patientChecklist", function (patientId) {
// return getPatientChecklist(patientId);
//});
//Meteor.publish("mostUsedConditions", function (count) {
// return Entities.find({etypes: "health-condition" }, {sort: [["used","desc"]]}, {limit: 20});
//});
//Meteor.publish("allFacts", function () {
// return Facts.find();
//});
//Meteor.publish("currentPatient"), function() {
// return Entities.find({etypes: "patient" }, {sort: [["used","desc"]]}, {limit: 20});
//});
EasySearch.config({
'host' : 'localhost:9200'
});
appConfig = function() {
var config = Assets.getText("config/config.json");
return JSON.parse(config);
};
|
'use strict'
/**
* If expose is `true` the event will also be send out using an output port
* In such a case the port/event name is prefixed with a ':'
*/
module.exports = {
/**
* Started event.
*
* @event Node#started
* @type {object}
* @property {node} node - Node being stopped
*/
STARTED: {name: 'started'},
/**
* Complete event.
*
* @event Node#complete
* @type {object}
* @property {node} node - Node being stopped
*/
COMPLETE: {name: 'complete', expose: true},
/**
* Shutdown event.
*
* @event Node#shutdown
* @type {object}
* @property {node} node - Node being stopped
*/
SHUTDOWN: {name: 'shutdown', expose: true},
/**
* Start event.
*
* @event Node#start
* @type {object}
* @property {node} node - Node being stopped
*/
START: {name: 'start', expose: true},
/**
* Stop event.
*
* @event Node#stop
* @type {object}
* @property {node} node - Node being stopped
*/
STOP: {name: 'stop', expose: true},
/**
* Status Update event.
*
* @event Node#stop
* @type {object}
* @property {node} node - Node being stopped
*/
STATUSUPDATE: {name: 'statusUpdate', expose: true},
/**
* Execute event.
*
* @event Node#execute
* @type {object}
* @property {node} node - Node being stopped
*/
EXECUTE: {name: 'execute'},
/**
* Executed event.
*
* @event Node#executed
* @type {object}
* @property {node} node - Node being stopped
*/
EXECUTED: {name: 'executed'},
/**
* Portfill event.
*
* @event Node#portfill
* @type {object}
* @property {node} node - Node being stopped
*/
PORTFILL: {name: 'portFill'},
/**
* Error event.
*
* @event Node#error
* @type {object}
* @property {node} node - Node being stopped
*/
ERROR: {name: 'error', expose: true},
/**
* Output event.
*
* @event Node#output
* @type {object}
* @property {node} node - Node being stopped
*/
OUTPUT: {name: 'output'},
/**
* Context update event.
*
* @event Node#contextUpdate
* @type {object}
* @property {node} node - Node being stopped
*/
CONTEXTUPDATE: {name: 'contextUpdate', expose: true},
/**
* Context clear event.
*
* @event Node#contextClear
* @type {object}
* @property {node} node - Node being stopped
*/
CONTEXTCLEAR: {name: 'contextClear', expose: true},
/**
* Timeout event.
*
* @event Node#nodeTimeout
* @type {object}
* @property {node} node - Node being stopped
*/
TIMEOUT: {name: 'nodeTimeout', expose: true}
}
|
#!/usr/bin/env nodejs
'use strict';
/*
* ytcompile
* https://github.com/earnubs/ytcompile
*
* Copyright (c) 2013 Stephen Stewart
* Licensed under the MIT license.
*/
/**
* Take template files and build out their equivalents as precompiled template
* functions, ready to be squished and packaged by shifter or whatever.
*
* Template files contain a <script> node per template, eg.
* <script id=foo type=x-template>
* Hello {{planet}}!
* </script>
*
* The template file extension should be one of handlebars|hbs, micro|mu which
* will determine which compilation step we take
*
* In the template file, each <script> nodes id attribute will be used to set
* the namespace on Y.U1.Template for that template
*
* ./precompile -d /path/to/output file1 file2 file3
*
* -d output directory, optional, defaults to ./js/templates/ (add this path to
* your build.json for shifter to pick up)
*
* TODO build caching
*
*/
var ArgumentParser = require('argparse').ArgumentParser,
fs = require('fs'),
path = require('path'),
htmlparser = require('htmlparser'),
Handlebars = require('yui/handlebars').Handlebars,
Micro = require('yui/template-micro').Template.Micro,
FILE_EXTS = ['.hbs', '.mu', '.micro', '.handlebars'],
parser = new ArgumentParser({
version: '0.0.1',
addHelp: true,
description: 'Precompile Y.Templates'
}),
args,
src, dest;
// --- setup command line options ----//
parser.addArgument(
[ '-o', '--output-dir' ],
{
help: 'directory to write precompiled template files',
required: true
}
);
parser.addArgument(
[ '-i', '--input-dir' ],
{
help: 'source template file directory',
required: true
}
);
/**
* write out the precompiled templates file
* @param {String} output
* @param {String} file the name of the file we're writing to, mirrors the
* name of the file templates read from
*/
function writeFile(output, file) {
file = path.resolve(dest + '/' + path.basename(file));
fs.writeFile(file + '.js', output, function(err) {
if(err) {
console.log('Uh, oh...');
console.log(err);
} else {
console.log("Templates precompiled to: " + file + ".js");
}
});
}
/**
* handle the parsed dom
* @param {Object} dom
* @param {String} type Y.Template.Micro or Y.Template.Handlebars
*/
function parsedFileDomHandler( dom, type ) {
var i, l, node, html, namespace,
// we're at the mercy of the engines' precompile function, so make jshint relax
output = '/*jshint trailing: false, asi: true, shadow: true, onevar: false */\n';
for (i = 0, l = dom.length; i < l; i++ ) {
node = dom[i];
if ( node.type === 'script' ) {
if (
( node.attribs.type === 'x-template' ||
node.attribs.type === 'text/x-handlebars-template' ) &&
node.children &&
node.children[0].type === 'text'
) {
html = node.children[0].raw;
namespace = node.attribs.id;
output += 'var engine, tmpl = ';
if (type && (type === 'hbs' || type === 'handlebars')) {
output += Handlebars.precompile(html) + ';\n';
output += 'engine = Y.Template.Handlebars;';
}
if (type && (type === 'mu' || type === 'micro')) {
output += Micro.precompile(html) + ';\n';
output += 'engine = Y.Template.Micro;';
}
output += '\nY.Template.register("'+namespace+'", engine.revive(tmpl));\n\n';
} else {
console.log('<script> element empty or has irrelevant type attribute, skipping');
}
}
}
output += '\n\n';
return output;
}
/**
* parse the file as html
* @param {String} html the file contents
* @param {String} ext file extension, decides if the precompiler to use
* @param {String} filename so we can write a new file in $dest of the sam name
**/
function parseHTML(html, ext, filename) {
var handler = new htmlparser.DefaultHandler(function(err, dom) {
if (err) {
throw err;
}
// write output to file
writeFile(parsedFileDomHandler(dom, ext), filename);
});
parser = new htmlparser.Parser(handler);
parser.parseComplete(html);
}
function getExtension(filename) {
var ext = path.extname(filename||'').split('.');
return ext[ext.length - 1];
}
/**
* Is this a valid Directory, if not bail out
* @param {String} path
* @return {Boolean}
*/
function isDirectory(dir) {
try {
var stat = fs.statSync(dir);
if (stat.isDirectory()) {
return path.normalize(dir);
} else {
console.error('Error: "' + dir + '" is not a directory.');
process.exit();
}
} catch (e) {
console.error('Error: "' + e.dir + '" is not a directory.');
process.exit();
}
}
args = parser.parseArgs(process.argv.slice(2));
src = isDirectory(args.input_dir);
dest = isDirectory(args.output_dir);
var templates = fs.readdirSync(src).filter(function(file) {
var ext = path.extname(file), isMatch = false;
FILE_EXTS.forEach(function(x) {
if (x == ext) {
isMatch = true;
}
});
return isMatch;
})
templates.forEach(function(file) {
file = path.resolve(src + '/' + file);
fs.stat(file, function(err, stats) {
if (stats.isFile()) {
fs.readFile(file, 'utf8', function (err, data) {
if (err) { throw err; }
parseHTML(data, getExtension(file), file);
});
}
});
});
|
var kSelSlider = new Slider(document.getElementById("kanji_selector_slider"), document.getElementById("kanji_selector_slider_input"), "vertical");
kSelSlider.setMinimum(100);
kSelSlider.setMaximum(2500);
kSelSlider.setBlockIncrement(50);
kSelSlider.onchange = function () {
var new_val = 20 * Math.round(kSelSlider.getValue()/20);
document.getElementById("kanji_count_div").innerHTML = new_val;
if (new_val != lastSliderVal) {
lastSliderVal = new_val;
setVisibleRTLevel(new_val);
}
};
lastSliderVal = 500; //Default value
setVisibleRTLevel(lastSliderVal);
kSelSlider.setValue(lastSliderVal);
window.onresize = function () {
kSelSlider.recalculate();
};
|
var postcss = require("postcss");
var extend = require("extend");
var csscolors = require('css-color-names');
module.exports = postcss.plugin("postcss-spine", function (opts) {
var defaultOpts = {
fallback: false,
complementary: false,
};
var opts = extend({}, defaultOpts, opts || {});
var paintProperties = [
"background-attachment",
"background-blend-mode",
"background-clip",
"background-color",
"background-image",
"background-origin",
"background-position",
"background-position-x",
"background-position-y",
"background-repeat",
"background-repeat-x",
"background-repeat-y",
"background-size",
"background",
"border-bottom-left-radius",
"border-bottom-right-radius",
"border-top-left-radius",
"border-top-right-radius",
"border-radius",
"border-bottom-color",
"border-left-color",
"border-right-color",
"border-top-color",
"border-color",
"border-bottom-style",
"border-left-style",
"border-right-style",
"border-top-style",
"border-style",
"border-image-outset",
"border-image-repeat",
"border-image-slice",
"border-image-source",
"border-image-width",
"border",
"box-shadow",
"color",
"outline-offset",
"text-shadow"
];
var visibilityProperties = [
"clip",
"backface-visibility",
"transform",
"transform-origin",
"transform-style",
"z-index",
"opacity",
"perspective",
"perspective-origin"
];
var returnFunctions = {
"border": function(decl) {
decl.value = decl.value.match(/[^\s]+\([^\)]*\)|[^\s]+/g).filter(function(v){
if (v.indexOf("#") == 0 || v.indexOf("rgb") == 0 || v.indexOf("hsl") == 0 || v.indexOf("rbga") == 0) {
return false;
}
if (typeof csscolors[v.toLowerCase()] !== 'undefined') {
return false;
}
return true;
}).join(" ");
},
"background": function(decl) {
if(opts.fallback === true) {
decl.value = "#fff";
} else {
decl.removeSelf();
}
},
"background-color": function(decl) {
if(opts.fallback === true) {
decl.value = "#fff";
} else {
decl.removeSelf();
}
},
"animation": function(decl) {
decl.removeSelf();
},
"transition": function(decl) {
decl.removeSelf();
}
};
var complementaryReturnFunctions = {
"border": function(decl) {
decl.value = decl.value.match(/[^\s]+\([^\)]*\)|[^\s]+/g).filter(function(v){
if (v.indexOf("#") == 0 || v.indexOf("rgb") == 0 || v.indexOf("hsl") == 0 || v.indexOf("rgba") == 0) {
return true;
}
if (typeof csscolors[v.toLowerCase()] !== 'undefined') {
return true;
}
return false;
}).join(" ");
decl.prop = "border-color";
},
"background": function(decl) {
},
"background-color": function(decl) {
},
"animation": function(decl) {
},
"transition": function(decl) {
}
};
if(opts.complementary === true) {
return function (css) {
css.eachDecl(function (decl) {
var unprefixedProp = postcss.vendor.unprefixed(decl.prop);
if(/animation/.test(unprefixedProp)) {
complementaryReturnFunctions['animation'](decl);
}
if(/transition/.test(unprefixedProp)) {
complementaryReturnFunctions['transition'](decl);
}
if (typeof(complementaryReturnFunctions[unprefixedProp]) === 'function') {
complementaryReturnFunctions[unprefixedProp](decl);
} else if (visibilityProperties.indexOf(unprefixedProp) != -1) {
if(opts.fallback === true) {
decl.removeSelf();
}
} else if (paintProperties.indexOf(unprefixedProp) == -1) {
decl.removeSelf();
}
});
};
} else {
return function (css) {
css.eachDecl(function (decl) {
var unprefixedProp = postcss.vendor.unprefixed(decl.prop);
if(/animation/.test(unprefixedProp)) {
returnFunctions['animation'](decl);
}
if(/transition/.test(unprefixedProp)) {
returnFunctions['transition'](decl);
}
if (typeof(returnFunctions[unprefixedProp]) === 'function') {
returnFunctions[unprefixedProp](decl);
} else if (visibilityProperties.indexOf(unprefixedProp) != -1) {
if(opts.fallback !== true) {
decl.removeSelf();
}
} else if (paintProperties.indexOf(unprefixedProp) != -1) {
decl.removeSelf();
}
});
css.eachAtRule(/(keyframes)$/, function(rule) {
rule.removeSelf();
});
};
}
});
|
/**
*
* @author Simon Boudrias
*
* Backbone like `Class.extend` for NodeJS (Adobe Brackets)
* @see https://github.com/SBoudrias/class-extend
*
* Adapter for adobe Brackets
* @author Matthieu Lassalvy
*
*/
/**
Copyright (c) 2013 Simon Boudrias
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.
*/
/*global Object */
var objectAssign = require('./object-assign'),
hasOwnProp = Object.prototype.hasOwnProperty;
/**
* Extend this Class to create a new one inherithing this one.
* Also add a helper __super__ object poiting to the parent prototypes methods
* @param {Object} protoProps Prototype properties (available on the instances)
* @param {Object} staticProps Static properties (available on the contructor)
* @return {Object} New sub class
*/
function extend(protoProps, staticProps) {
var child,
parent = this; // jshint ignore:line
// The constructor function for the new subclass is either defined by you
// (the "constructor" property in your `extend` definition), or defaulted
// by us to simply call the parent's constructor.
if (protoProps && hasOwnProp.call(protoProps, 'constructor')) {
child = protoProps.constructor;
} else {
child = function () {
return parent.apply(this, arguments);
};
}
// Add static properties to the constructor function, if supplied.
objectAssign(child, parent, staticProps);
// Set the prototype chain to inherit from `parent`
child.prototype = Object.create(parent.prototype, {
constructor: {
value: child,
enumerable: false,
writable: true,
configurable: true
}
});
// Add prototype properties (instance properties) to the subclass,
// if supplied.
if (protoProps) {
objectAssign(child.prototype, protoProps);
}
// Set a convenience property in case the parent's prototype is needed
// later.
child.__super__ = parent.prototype;
return child;
}
var Base = module.exports = function () {};
Base.extend = extend;
|
/**
* Preference
*
* @module :: Cyclopedia (Sails)
* @description :: Preference storage for user to specify what content they want to see/what content they want to have hidden.
* @todo :: When Waterline is updated with associations, this User has a one-to-many relationship with this model.
*/
module.exports = {
attributes: {
preferenceName: {
type: 'STRING',
},
exclusionValues: {
type: 'array'
},
inclusionValues: {
type: 'array'
}
}
};
|
"use strict";
/*
GroundStorage is a thin layer providing Meteor offline storage
Uses minimax and handles objects via EJSON
Regz. RaiX
*/
// Main scope
GroundStore = {};
// Test scope
_groundstore = {};
|
import React from "react";
import test from "ava";
import { mount } from "enzyme";
import createMemoryHistory from "history/createMemoryHistory";
import RouteMatcher from "../../../src/lib/RouteMatcher";
import HistoryManager from "../../../src/lib/HistoryManager";
import Connector from "../../../src/lib/Connector";
import LoadRunner from "../../../src/lib/runner/LoadRunner";
import InitialPropsRunner from "../../../src/lib/runner/InitialPropsRunner";
test.beforeEach((t) => {
const routeMatcher = new RouteMatcher();
const historyManager = new HistoryManager();
const connector = new Connector(historyManager, routeMatcher);
t.context.connector = connector;
});
test.cb("Rendering", (t) => {
// Page Settings
class IndexPage extends React.Component {
static initialPropsWillGet(props) {
t.is(props.pathname, "/");
}
static async getInitialProps(props) {
t.is(props.pathname, "/");
return {
message: "world"
};
}
static initialPropsDidGet(componentProps) {
t.is(componentProps.pathname, "/");
}
render() {
return <div>Hello, {this.props.message}</div>;
}
}
const initializedConnector = t.context.connector.newInitializedInstance(
createMemoryHistory()
);
initializedConnector.routeMatcher.addRoute("/", IndexPage);
const runner = new LoadRunner(initializedConnector);
runner.run(async (RootComponent) => {
const mountedActual = mount(React.createElement(RootComponent));
const expected = mount(
React.createElement(IndexPage, { message: "world" })
);
t.is(mountedActual.html(), expected.html());
t.plan(4);
t.end();
});
});
test("No match route", (t) => {
const initializedConnector = t.context.connector.newInitializedInstance(
createMemoryHistory()
);
const runner = new LoadRunner(initializedConnector);
runner.run(async (RootComponent) => {
t.fail();
});
t.pass();
});
test.cb("Not found page", (t) => {
// Page Settings
class IndexPage extends React.Component {
render() {
return (
<div>
<h1>Index</h1>
</div>
);
}
}
// Page Settings
class NotFoundPage extends React.Component {
render() {
return (
<div>
<h1>NotFound</h1>
</div>
);
}
}
const initializedConnector = t.context.connector.newInitializedInstance(
createMemoryHistory({
initialEntries: ["/not-found"]
})
);
initializedConnector.routeMatcher.addRoute("/", IndexPage);
initializedConnector.routeMatcher.addRoute("(.*)", NotFoundPage);
const runner = new InitialPropsRunner(initializedConnector, {});
runner.run(async (RootComponent) => {
const actual = mount(React.createElement(RootComponent));
const expected = mount(React.createElement(NotFoundPage));
t.is(actual.html(), expected.html());
t.end();
});
});
|
const url = require('url')
const Strategy = require('./strategy')
const execSync = require('child_process').execSync || require('exec-sync')
const Buffer = require('buffer').Buffer
function get_ports () {
// Use execSync if it exist (Node 0.12 and later) or exec-sync
const ports = execSync('spurious ports --json')
if (typeof ports === 'string') {
return ports
}
if (Buffer.isBuffer(ports)) {
return ports.toString()
}
throw new Error(ports)
}
function port_config () {
const ports = get_ports()
if (ports === '[error] Spurious services haven\'t been started, please run \'spurious start\'') {
throw new Error(ports)
}
return JSON.parse(ports)
}
function docker_config () {
return {
'spurious-dynamo': [
{
Host: process.env['DYNAMODB.SPURIOUS.LOCALHOST_NAME'].split('/').pop(),
HostPort: url.parse(process.env['DYNAMODB.SPURIOUS.LOCALHOST_PORT']).port
}
],
'spurious-sqs': [
{
Host: process.env['SQS.SPURIOUS.LOCALHOST_NAME'].split('/').pop(),
HostPort: url.parse(process.env['SQS.SPURIOUS.LOCALHOST_PORT']).port
}
],
'spurious-s3': [
{
Host: process.env['S3.SPURIOUS.LOCALHOST_NAME'].split('/').pop(),
HostPort: url.parse(process.env['S3.SPURIOUS.LOCALHOST_PORT']).port
}
]
}
}
function config (type) {
switch (type) {
case 'docker':
return docker_config()
default:
return port_config()
}
}
function configure (type, strategy) {
strategy = strategy || new Strategy(true)
strategy.apply(config(type))
}
module.exports = configure
|
import { h, Component } from 'preact';
import { Router } from 'preact-router';
import Home from './routes/home';
import Route66 from './routes/route66';
import Custom from './routes/custom';
import './style.css';
export default class App extends Component {
handleRoute = e => {
this.currentUrl = e.url;
};
render(props) {
return (
<div id="app">
<Router url={props.url} onChange={this.handleRoute} {...props}>
<Home path="/" />
<Route66 path="/route66" />
<Custom path="/custom" {...props} />
</Router>
</div>
);
}
}
|
import Ember from 'ember';
import Resolver from 'ember/resolver';
import loadInitializers from 'ember/load-initializers';
import config from './config/environment';
import inheritance from './inheritance';
import numericBox from './numberic_box';
import user from './user';
import timeManager from './time_manager'
import father from './father'
import child from './child'
import prototype from './prototype';
var myTimeManager = timeManager.create({
time: 12
});
myTimeManager.set("time",22);
myUser = user.create({
firstName: "Andrew",
lastName: "Scott"
});
console.log(myUser.get('fullName')); // Andrew Scott
myUser.set("firstName","Tony");
myUser.set("lastName","Stark");
console.log(myUser.get('fullName'));
var textbox = numericBox.create();
console.log(textbox.valid("12")); //true
textbox.onFocus();
var darren = father.create({
name:'Darren',
age:40,
address:'Brisbane'
});
var dan = child.create({
school:'Brisbane State High School',
father: darren
});
console.log(dan.get('address'));
darren.set('address','sydney');
console.log(dan.get('address'));
//Output
//Brisbane
//sydney
var App;
Ember.MODEL_FACTORY_INJECTIONS = true;
App = Ember.Application.extend({
modulePrefix: config.modulePrefix,
podModulePrefix: config.podModulePrefix,
Resolver: Resolver
});
loadInitializers(App, config.modulePrefix);
inheritance();
prototype();
export default App;
|
'use strict';
/**
* Module dependencies
*/
var carsPolicy = require('../policies/cars.server.policy'),
cars = require('../controllers/cars.server.controller');
module.exports = function (app) {
// Cars collection routes
app.route('/api/cars').all(carsPolicy.isAllowed)
.get(cars.list)
.post(cars.create);
// Single car routes
app.route('/api/cars/:carId').all(carsPolicy.isAllowed)
.get(cars.read)
.put(cars.update)
.delete(cars.delete);
// Finish by binding the car middleware
app.param('carId', cars.carByID);
};
|
'use strict';
var dbm;
var type;
var seed;
var fs = require('fs');
var path = require('path');
var Promise;
/**
* We receive the dbmigrate dependency from dbmigrate initially.
* This enables us to not have to rely on NODE_PATH.
*/
exports.setup = function(options, seedLink) {
dbm = options.dbmigrate;
type = dbm.dataType;
seed = seedLink;
Promise = options.Promise;
};
exports.up = function(db) {
var filePath = path.join(__dirname + '/sqls/20160302070050-initial-schema-up.sql');
return new Promise( function( resolve, reject ) {
fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){
if (err) return reject(err);
console.log('received data: ' + data);
resolve(data);
});
})
.then(function(data) {
return db.runSql(data);
});
};
exports.down = function(db) {
var filePath = path.join(__dirname + '/sqls/20160302070050-initial-schema-down.sql');
return new Promise( function( resolve, reject ) {
fs.readFile(filePath, {encoding: 'utf-8'}, function(err,data){
if (err) return reject(err);
console.log('received data: ' + data);
resolve(data);
});
})
.then(function(data) {
return db.runSql(data);
});
};
|
/*!
* qoo.legacy.js
*
* qoo.js is a small, simple, and clean javascript oop library.
*
* @version 1.0.1
* @author Hiroyuki OHARA <Hiroyuki.no22@gmail.com>
* @copyright (c) 2014 Hiroyuki OHARA
* @see https://github.com/no22/qoo
* @license MIT
*/(function(e,t,n,r){if(typeof define=="function"&&define.amd)define([],r);else if(typeof exports=="object")module.exports=r();else{var i=e[n],s=r();if(i)return i.extend(i,s);e[t]=s}})(this,"qooLegacy","qoo",function(e){return{_inherit:function(e,t){function n(){}n.prototype=t,e.prototype=new n,e.prototype.constructor=e}}});
|
'use strict';
module.exports = {
app: {
title: 'One Step',
description: 'One step is an application to provide the convinience for salarymen who are busy with working but prefer to cook themselves. With the help of one step, you only need one click to order the dish and receive the ingrediants at any time you want.',
keywords: 'mongodb, express, angularjs, node.js, mongoose, passport',
googleAnalyticsTrackingID: process.env.GOOGLE_ANALYTICS_TRACKING_ID || 'GOOGLE_ANALYTICS_TRACKING_ID'
},
port: process.env.PORT || 3000,
templateEngine: 'swig',
// Session Cookie settings
sessionCookie: {
// session expiration is set by default to 24 hours
maxAge: 24 * (60 * 60 * 1000),
// httpOnly flag makes sure the cookie is only accessed
// through the HTTP protocol and not JS/browser
httpOnly: true,
// secure cookie should be turned to true to provide additional
// layer of security so that the cookie is set only when working
// in HTTPS mode.
secure: false
},
// sessionSecret should be changed for security measures and concerns
sessionSecret: process.env.SESSION_SECRET || 'MEAN',
// sessionKey is set to the generic sessionId key used by PHP applications
// for obsecurity reasons
sessionKey: 'sessionId',
sessionCollection: 'sessions',
logo: 'modules/core/client/img/brand/logo.png',
favicon: 'modules/core/client/img/brand/favicon.ico',
uploads: {
profileUpload: {
dest: './modules/users/client/img/profile/uploads/', // Profile upload destination path
limits: {
fileSize: 1*1024*1024 // Max file size in bytes (1 MB)
}
}
}
};
|
import React, { Component, PropTypes } from 'react'
import './Loading.css'
class Loading extends Component {
render() {
if (this.props.mode === 'loading') {
return (
<div id="container">
<div id="content">
<div className="loader" />
</div>
</div>
)
} else if (this.props.mode === 'success') {
return (
<div id="container">
<div id="content">
Success
</div>
</div>
)
} else if (this.props.mode === 'fail') {
return (
<div id="container">
<div id="content">
Fail
</div>
</div>
)
} else {
return (<span />)
}
}
}
Loading.propTypes = {
mode: PropTypes.string,
}
export default Loading
|
var path = require('path');
var at = require('basisjs-tools-ast').js;
var l10nContext = require('../l10n/context.js');
function unixpath(filename){
return path.normalize(filename).replace(/^[a-z]+:/i, '').replace(/\\/g, '/');
}
function resolveToBase(flow, filename, baseURI){
return unixpath(path.resolve(baseURI || '', filename));
}
//
// NEW API
//
module.exports = function(file, flow, defineHandler, globalScope){
var fconsole = flow.console;
var basisResolveURI = flow.js.basis.resource.resolveURI;
flow.l10n = l10nContext.create(flow, file);
var resolveL10nToken = function(key, dictPath){
var id = key + '@' + dictPath;
var tokenDescriptor = flow.l10n.getToken(id);
if (!tokenDescriptor.jsToken)
{
var token = {
type: 'ObjectExpression',
properties: []
};
token.obj = {
compute: at.createRunner(function(token_){
var id = key + '.{?}' + '@' + dictPath;
fconsole.log('[basis.l10n] basis.l10n.Dictionary#token.compute ' + id);
token_.obj = resolveL10nToken(key + '.{?}', dictPath).jsToken.obj;
})
};
tokenDescriptor.jsToken = token;
}
return tokenDescriptor;
};
var resolveDictionary = function(filename){
var dict = flow.l10n.getDictionary(filename);
if (!dict.jsToken)
{
var file = dict.file;
var token = {
type: 'ObjectExpression',
properties: []
};
token.file = file;
token.obj = {
token: at.createRunner(function(token_, this_, args, scope){
var key = scope.simpleExpression(args[0]);
if (key && key.type == 'Literal')
{
var id = key.value + '@' + file.filename;
fconsole.log('[basis.l10n] basis.l10n.Dictionary#token ' + id);
var l10nToken = resolveL10nToken(key.value, file.filename);
l10nToken.addRef(this.file, token_);
token_.obj = l10nToken.jsToken.obj;
}
else
{
flow.warn({
file: this.file.relpath,
message: 'First argument of basis.l10n.dictionary#token() is not resolved: ' + at.translate(token_),
loc: this.file.location(token_.loc)
});
}
})
};
dict.jsToken = token;
}
return dict;
};
// TODO: fetch culture list from basis.l10n
defineHandler(globalScope, 'basis.l10n.setCultureList', function(token, this_, args, scope){
flow.l10n.cultures = {};
var list = scope.simpleExpression(args[0]);
if (!list)
{
flow.warn({
file: this.file.relpath,
message: 'First argument of basis.l10n.setCulture() is not resolved: ' + at.translate(token),
loc: this.file.location(token.loc)
});
return;
}
switch (list.type)
{
case 'Literal':
list = list.value;
break;
case 'ArrayExpression':
list = list.elements.map(function(val){
return val && val.type == 'Literal' ? val.value : undefined;
});
if (list.every(function(val){
return typeof val == 'string';
}))
break;
default:
flow.warn({
file: this.file.relpath,
message: 'First argument of basis.l10n.setCulture() should be string or array of string: ' + at.translate(token),
loc: this.file.location(token.loc)
});
return;
}
fconsole.start('[basis.l10n] ' + at.translate(token) + ' in ' + this.file.relpath);
if (typeof list == 'string')
list = list.trim().split(/\s+/);
if (Array.isArray(list))
{
for (var i = 0, cultureDef; cultureDef = list[i]; i++)
{
var clist = cultureDef.split(/\//);
list[i] = clist[0];
flow.l10n.cultures[clist[0]] = clist;
}
fconsole.log('[OK] Set culture list ' + JSON.stringify(Object.keys(flow.l10n.cultures)));
}
else
{
flow.warn({
file: this.file.relpath,
message: 'basis.l10n.setCultureList is not resolved (can\'t convert into array): ' + at.translate(token)
});
}
fconsole.end();
});
defineHandler(file.jsScope, 'basis.l10n.dictionary', function(token, this_, args, scope){
var filename = scope.simpleExpression(args[0]);
if (filename && filename.type == 'Literal')
{
//filename = this.file.resolve(filename[1]);
filename = basisResolveURI
? basisResolveURI(filename.value, flow.indexFile.baseURI)
: resolveToBase(flow, filename.value, flow.indexFile.baseURI);
var dict = resolveDictionary(filename);
dict.addRef(this.file, token);
dict.file.jsRefCount++;
fconsole.log('[basis.l10n] dictionary ' + at.translate(args[0]) + ' -> ' + filename + ' -> ' + dict.file.relpath);
token.obj = dict.jsToken.obj;
this.file.link(dict.file);
}
else
{
return flow.warn({
//fatal: true,
file: this.file.relpath,
message: 'basis.l10n.dictionary: first argument is not resolved, token: ' + at.translate(token)
});
}
});
};
|
/**
* Created by zhangrz on 2017/9/26.
* Copyright© 2015-2020 codingview (https://github.com/codingview)
* @version 0.0.1 created 图片处理相关
*/
'use strict';
const _ = {
// 上传图片
ajax: ()=>new Promise((resolve, reject)=>
$.ajax({
url: '/admin/example/image'
, type: 'put'
, data: _.getForm()
, dataType: 'json'
, processData: false // 告诉JSLite不要去处理发送的数据
, contentType: false // 告诉JSLite不要去设置Content-Type请求头
, success: json=> {
if (json && 'status' in json && json.status > 0) {
resolve(json.data);
} else {
reject('message' in json ? json.message : '上传图片出错');
}
}, error: e=> {
console.error(e);
reject('上传图片超时');
}
})
)
// 获取图片
, getForm: ()=> {
let formData = new FormData();
formData.append('img', $('#e_icon').get(0).files[0]);
return formData;
}
// 监听
, init: ()=> {
$('#e_icon').on('change', function () {
_
.ajax()
.then(()=> {
$('#e_icon_val').val(1); // 设置临时图片有值
})
.catch(e=>alert(e));
});
}
};
module.exports = _.init;
|
const { resolve } = require('path');
const webpackValidator = require('webpack-validator');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ProgressBarPlugin = require('progress-bar-webpack-plugin');
const { getIfUtils, removeEmpty } = require('webpack-config-utils');
const webpack = require('webpack');
const nodeExternals = require('webpack-node-externals');
const InlineManifestWebpackPlugin = require('inline-manifest-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const OfflinePlugin = require('offline-plugin');
module.exports = (env) => {
const { ifProd, ifNotProd, ifProduction } = getIfUtils(env);
const config = webpackValidator({
context: resolve('src'),
entry: {
app: ['babel-polyfill', 'whatwg-fetch', './app.js'],
vendor: ['./vendor/lib.js'],
},
output: {
path: resolve('dist'),
filename: ifProd('bundle.[name].[chunkhash].js', 'bundle.[name].js'),
pathinfo: ifNotProd(),
},
devtool: ifProd('source-map', 'eval'),
performance: {
hints: ifProd(true, false),
},
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
babelrc: ifProd(false, true),
presets: [
['es2015', { modules: false }],
],
plugins: ['transform-runtime', 'transform-object-rest-spread'],
},
},
{
test: /\.css$/,
include: resolve('src/css'),
loader: ExtractTextPlugin.extract({
fallbackLoader: 'style-loader',
loader: ifProd('css-loader', 'css-loader?sourceMap'),
}),
},
],
},
plugins: removeEmpty([
new ProgressBarPlugin(),
ifProd(new OfflinePlugin()),
new webpack.DefinePlugin({
'process.env': {
BROWSER: JSON.stringify(true),
NODE_ENV: ifProd('"production"', '"development"'),
},
}),
new ExtractTextPlugin(ifProd('styles.[name].[chunkhash].css', 'styles.[name].css')),
ifProd(new InlineManifestWebpackPlugin()),
ifProd(new webpack.optimize.CommonsChunkPlugin({
names: ['vendor', 'manifest'],
})),
new HtmlWebpackPlugin({
template: './index.html',
}),
]),
externals: ifProduction([nodeExternals()]),
node: {
fs: 'empty',
},
});
if (env.debug) {
console.log(config);
}
return config;
};
|
version https://git-lfs.github.com/spec/v1
oid sha256:ba5708628a7e468b03091e40a0f4a6b2812a2ccb17a72a38ff29eef72f7b4492
size 3736
|
var express = require('express');
var router = express.Router();
let checknew = require('../lib/checknew')
let jsonresult = require('../models/jsonresult')
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('home/index', { title: '首页', config: global.config });
});
router.get('/index2', function(req, res, next) {
res.render('home/index2', { layout: null });
});
router.get('/home/newver', function(req, res, next) {
checknew.hasNew().then(isnew=>{
let resultjson = new jsonresult(true, '', isnew)
res.json(resultjson)
}).catch(error=>{
let resultjson = new jsonresult(false, error.message, null)
res.json(resultjson)
})
});
module.exports = router;
|
'use strict';
var split = require('split');
var CombinedStream = require('combined-stream');
var through = require('through2');
module.exports = function create(winStream, posixStream)
{
var posixTransformStream = through.obj(function(line, encoding, callback) {
if (line.substr(0,2) === '#!') // Strip shebang, as it will be ignored
{
callback(null, '');
}
else
{
callback(null, ':; ' + line + '\n');
}
}, function(callback) {
this.push(':; exit\n');
callback(null);
});
var winTransformStream = through.obj(function(line, encoding, callback) {
callback(null, line + '\r\n');
}, function(callback) {
this.push('exit /B\r\n');
callback(null);
});
var combinedStream = CombinedStream.create();
combinedStream.append( posixStream.pipe(split()).pipe(posixTransformStream) );
combinedStream.append( winStream.pipe(split()).pipe(winTransformStream) );
return combinedStream;
};
|
require.paths.unshift('./../Source/');
var Deck = require('deck').setup(global, 'ringo');
var http = require('ringo/httpserver');
/* App */
var Application = function(request, response){
response.setStatus(200);
response.setHeader('content-type', 'text/html');
if (request.params.name) response.write(['Hello ', request.params.name, '!\n'].join(''));
if (request.params.age) response.write(['You are', request.params.age, 'years old.\n'].join(' '));
response.write('Have a nice Day!');
response.finish();
};
/* Deck Instance */
var Serv = new Deck();
Serv.addRoute('/{:name{/:age}}', Application);
var httpserv = new http.Server();
httpserv.addApplication('/', null, function(env){
return Serv.dispatch(env);
});
httpserv.start();
|
var gulp = require('gulp'),
sass = require('gulp-sass');
gulp.task('sass', function () {
gulp.src('./assets/css/*.scss')
.pipe(sass())
.pipe(gulp.dest('./assets/css'));
});
|
/**
* @file 图像处理模块
* @author mengke01(kekee000@gmail.com)
*/
import cloneImage from './util/cloneImage';
import grayImage from './filter/gray';
import binarizeImage from './filter/binarize';
import brightnessImage from './filter/brightness';
import sharpImage from './filter/sharp';
import gaussBlurImage from './filter/gaussBlur';
import blurImage from './filter/blur';
import reverseImage from './filter/reverse';
import closeImage from './filter/close';
import openImage from './filter/open';
import dilateImage from './filter/dilate';
import erodeImage from './filter/erode';
import getHistogram from './util/getHistogram';
import getThreshold from './util/getThreshold';
export default class ImageProcessor {
/**
* 灰度图像处理子程序,处理灰度图像和二值图像
*
* @param {Object} imageData 图像数据
*/
constructor(imageData) {
imageData && this.set(imageData);
}
/**
* 设置一个图像数据
*
* @param {Object} imageData 原始图像数据
* @return {this}
*/
set(imageData) {
if (!imageData.gray) {
imageData = grayImage(imageData);
}
this.imageData = imageData;
this.originData = null;
return this;
}
/**
* 获取当前编辑
*
* @return {Object} 图像数据
*/
get() {
return this.imageData;
}
/**
* 获取上一个保存点
*
* @return {Object} 图像数据
*/
getOrigin() {
return this.originData;
}
/**
* 备份当前编辑
*
* @return {this}
*/
save() {
this.originData = cloneImage(this.imageData);
return this;
}
/**
* 克隆当前处理器
*
* @return {this}
*/
clone() {
return new ImageProcessor(cloneImage(this.imageData));
}
/**
* 恢复备份
*
* @return {this}
*/
restore() {
if (this.originData) {
this.imageData = cloneImage(this.originData);
}
return this;
}
/**
* 获取当前图像的直方图信息
*
* @return {Array} 灰度直方图信息
*/
getHistogram() {
return getHistogram(this.imageData);
}
/**
* 根据直方图获取阈值
*
* @param {string} thresholdType 阈值类型
* @return {number} 阈值
*/
getThreshold(thresholdType) {
return getThreshold(this.getHistogram(), thresholdType);
}
/**
* 对当前图像进行二值化处理
*
* @param {number} threshold 阈值
* @return {this}
*/
binarize(threshold) {
this.imageData = binarizeImage(this.imageData, threshold);
return this;
}
/**
* 反转图像
*
* @return {this}
*/
reverse() {
this.imageData = reverseImage(this.imageData);
return this;
}
/**
* 二值图像开运算
*
* @param {string} mode 模板,'square', 'circle', 'rhomb'
* @param {number} radius 半径
* @return {this}
*/
close(mode, radius) {
if (!this.imageData.binarize) {
this.binarize();
}
this.imageData = closeImage(this.imageData, mode, radius);
return this;
}
/**
* 二值图像闭运算
*
* @param {string} mode 模板,'square', 'circle', 'rhomb'
* @param {number} radius 半径
* @return {this}
*/
open(mode, radius) {
if (!this.imageData.binarize) {
this.binarize();
}
this.imageData = openImage(this.imageData, mode, radius);
return this;
}
/**
* 二值图像膨胀
*
* @param {string} mode 模板,'square', 'circle', 'rhomb'
* @param {number} radius 半径
* @return {this}
*/
dilate(mode, radius) {
if (!this.imageData.binarize) {
this.binarize();
}
this.imageData = dilateImage(this.imageData, mode, radius);
return this;
}
/**
* 二值图像腐蚀
*
* @param {string} mode 模板
* @param {number} radius 半径
* @return {this}
*/
erode(mode, radius) {
if (!this.imageData.binarize) {
this.binarize();
}
this.imageData = erodeImage(this.imageData, mode, radius);
return this;
}
/**
* 图像高斯模糊
*
* @param {number} radius 取样区域半径
* @param {number} sigma 标准方差, 可选, 默认取值为 1.5
* @return {this}
*/
gaussBlur(radius, sigma) {
this.imageData = gaussBlurImage(this.imageData, radius, sigma);
return this;
}
/**
* 图像均值模糊
*
* @param {number} radius 取样区域半径
* @return {this}
*/
blur(radius) {
this.imageData = blurImage(this.imageData, radius);
return this;
}
/**
* 图像锐化
*
* @param {number} lamta 锐化参数
* @return {this}
*/
sharp(lamta) {
this.imageData = sharpImage(this.imageData, lamta);
return this;
}
/**
* 调节图像亮度对比度
*
* @param {string} brightness 亮度 -50 ~ 50
* @param {number} contrast 对比度 -50 ~ 50
* @return {this}
*/
brightness(brightness, contrast) {
this.imageData = brightnessImage(this.imageData, brightness, contrast);
return this;
}
/**
* 注销
*/
dispose() {
this.imageData = this.originData = null;
}
}
|
const gulp = require('gulp');
const gulpWebpack = require('webpack-stream');
const webpackConfig = require('./webpack.config');
const DESTINATION_FOLDER = 'build';
gulp.task('webpack', () =>
gulp.src('src/app.js')
.pipe(gulpWebpack(webpackConfig))
.pipe(gulp.dest(DESTINATION_FOLDER))
);
// TODO: Add electron pack and build tasks
gulp.task('default', ['webpack']);
|
module.exports = {
apps: [{
name: 'Hapiness',
script: 'server.js',
instances: 1,
exec_mode: 'cluster',
max_memory_restart: '500M',
restart_delay: 3000
}]
}
|
import AnalyzerResult from '../analyzer-result';
export default class MatchWordListAnalyzer {
constructor(messageType, words) {
this.messageType = messageType;
this.words = words;
}
analyze(str) {
const result = new AnalyzerResult();
const usages = [];
// Populate usages object with counts of usages
this.words.forEach(x => {
const regExp = new RegExp(x, 'gi');
const matches = str.match(regExp);
if (matches && matches.length > 0) {
const prop = matches[0].toLowerCase();
usages.push({
word: prop,
count: matches.length
});
}
});
usages.sort((a, b) => b.count - a.count);
const messageItems = usages.map(usage => `${usage.word}: ${usage.count}`);
if (messageItems.length > 0) {
result.addMessage(this.messageType, messageItems.join(', '));
}
return result;
}
}
|
import React from 'react'
import PropTypes from 'prop-types'
import CountUp from 'react-countup'
import { LineChart, Line, XAxis, YAxis, CartesianGrid, ResponsiveContainer } from 'recharts'
import styles from './cpu.less'
import { color } from '../../../utils'
const countUpProps = {
start: 0,
duration: 2.75,
useEasing: true,
useGrouping: true,
separator: ',',
}
function Cpu ({ usage, space, cpu, data }) {
return (<div className={styles.cpu}>
<div className={styles.number}>
<div className={styles.item}>
<p>usage</p>
<p><CountUp
end={usage}
suffix="GB"
{...countUpProps}
/></p>
</div>
<div className={styles.item}>
<p>space</p>
<p><CountUp
end={space}
suffix="GB"
{...countUpProps}
/></p>
</div>
<div className={styles.item}>
<p>cpu</p>
<p><CountUp
end={cpu}
suffix="%"
{...countUpProps}
/></p>
</div>
</div>
<ResponsiveContainer minHeight={300}>
<LineChart data={data} margin={{ left: -40 }}>
<XAxis dataKey="name" axisLine={{ stroke: color.borderBase, strokeWidth: 1 }} tickLine={false} />
<YAxis axisLine={false} tickLine={false} />
<CartesianGrid vertical={false} stroke={color.borderBase} strokeDasharray="3 3" />
<Line type="monotone" connectNulls dataKey="cpu" stroke={color.blue} fill={color.blue} />
</LineChart>
</ResponsiveContainer>
</div>)
}
Cpu.propTypes = {
data: PropTypes.array,
usage: PropTypes.number,
space: PropTypes.number,
cpu: PropTypes.number,
}
export default Cpu
|
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var core_1 = require("@angular/core");
var platform_browser_1 = require("@angular/platform-browser");
var common_1 = require("@angular/common");
var http_1 = require("@angular/http");
var material_1 = require("@angular/material");
var router_1 = require("@angular/router");
var ng2_redux_1 = require("ng2-redux");
var ng2_hearthstone_app_1 = require("./store/ng2-hearthstone.app");
var createLogger = require("redux-logger");
var redux_thunk_1 = require("redux-thunk");
var cards_module_1 = require("./cards/cards.module");
var app_component_1 = require("./app.component");
var app_routing_1 = require("./app.routing");
var AppModule = (function () {
function AppModule(ngRedux) {
ngRedux.configureStore(ng2_hearthstone_app_1.ng2HearthstoneApp, {
searchCards: {
searching: false,
keyword: '',
items: []
}
}, [redux_thunk_1.default, createLogger()]);
}
return AppModule;
}());
AppModule = __decorate([
core_1.NgModule({
imports: [
platform_browser_1.BrowserModule,
common_1.CommonModule,
http_1.HttpModule,
material_1.MaterialModule.forRoot(),
router_1.RouterModule.forRoot(app_routing_1.appRoutes),
//
ng2_redux_1.NgReduxModule,
//
cards_module_1.CardsModule
],
declarations: [
app_component_1.AppComponent
],
bootstrap: [app_component_1.AppComponent]
}),
__metadata("design:paramtypes", [ng2_redux_1.NgRedux])
], AppModule);
exports.AppModule = AppModule;
//# sourceMappingURL=app.module.js.map
|
import _extends from "@babel/runtime/helpers/builtin/extends";
import _jsx from "@babel/runtime/helpers/builtin/jsx";
import _objectWithoutProperties from "@babel/runtime/helpers/builtin/objectWithoutProperties";
import _assertThisInitialized from "@babel/runtime/helpers/builtin/assertThisInitialized";
import _inheritsLoose from "@babel/runtime/helpers/builtin/inheritsLoose";
import cx from 'classnames';
import React from 'react';
import PropTypes from 'prop-types';
import { translate } from 'react-i18next';
import OverlayHeader from '../Overlay/Header';
import OverlayContent from '../Overlay/Content';
import SettingsPanel from './SettingsPanel';
var enhance = translate();
var SettingsManager =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(SettingsManager, _React$Component);
function SettingsManager() {
var _temp, _this;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return (_temp = _this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this, _this.handleLogout = function () {
_this.props.onCloseOverlay();
_this.props.onLogout();
}, _temp) || _assertThisInitialized(_this);
}
var _proto = SettingsManager.prototype;
_proto.render = function render() {
var _this$props = this.props,
t = _this$props.t,
className = _this$props.className,
onCloseOverlay = _this$props.onCloseOverlay,
props = _objectWithoutProperties(_this$props, ["t", "className", "onCloseOverlay"]);
return _jsx("div", {
className: cx('SettingsManager', className)
}, void 0, _jsx(OverlayHeader, {
title: t('settings.title'),
onCloseOverlay: onCloseOverlay
}), _jsx(OverlayContent, {
className: "SettingsManager-body"
}, void 0, React.createElement(SettingsPanel, _extends({}, props, {
onLogout: this.handleLogout
}))));
};
return SettingsManager;
}(React.Component);
SettingsManager.propTypes = process.env.NODE_ENV !== "production" ? {
t: PropTypes.func.isRequired,
className: PropTypes.string,
onCloseOverlay: PropTypes.func.isRequired,
onLogout: PropTypes.func.isRequired
} : {};
export default enhance(SettingsManager);
//# sourceMappingURL=index.js.map
|
var model = require('../models');
exports.authUser = function(req, res, next) {
if (!req.session.loggedIn) {
return res.redirect('/login');
}
next();
}
exports.authLink = function(req, res, next) {
var id = req.params.linkId || -1;
model.userCanAccessLink(req.db, req.user, id, function(err, authorized) {
if (authorized) {
next();
} else if (!authorized) {
return res.redirect('/');
} else if (err) {
return next(err);
}
});
}
|
#!/usr/bin/env node --harmony
var nejs = require('../nejs'),
fs = require('fs');
var program = require('commander'),
defs = require('defs');
program
.version(nejs.VERSION.join('.'))
.usage('[options] [dir|file ...]')
.option('-s, --source [src]')
.option('-o, --output [src]')
.parse(process.argv);
var args = program['args'],
input;
var file = program['source'],
newFile = program['output'];
if (!file && args.length) {
input = args.join(' ');
if (fs.existsSync(input)) {
file = input;
input = false;
}
}
function action(data) {
var toConsole = input && !program['output'] ||
!newFile;
var ShaBang = '';
data = data.replace(/^(#!\/.*\s+)/, function (sstr, $1) {
ShaBang = $1;
return '';
});
var res = defs(nejs.compile(data), {
'environments': ['node', 'browser'],
'disallowVars': false,
'disallowDuplicated': false,
'disallowUnknownReferences': false
});
if (res.errors) {
console.error(res.errors.join('\n'));
console.error('\n');
process.exit(1);
}
if (res.ast) {
console.log(JSON.stringify(res.ast, null, 4));
}
res.src = ShaBang + res.src;
if (toConsole) {
console.log(res.src);
} else {
fs.writeFileSync(newFile, res.src);
console.log('File "' + file + '" was successfully compiled -> "' + newFile + '"');
}
process.exit(0);
}
if (!file && input == null) {
var buf = '';
var stdin = process.stdin,
stdout = process.stdout;
stdin.setEncoding('utf8');
stdin.on('data', function (chunk) {
buf += chunk;
});
stdin.on('end', function () {
action(buf);
}).resume();
process.on('SIGINT', function () {
stdout.write('\n');
stdin.emit('end');
stdout.write('\n');
process.exit();
});
} else {
action(file ? fs.readFileSync(file).toString() : input);
}
|
/* eslint no-undef: 0 */
// Note: This is to stop XO from complaining about {navigator}
import React from 'react'
import Component from 'hyper/component'
import leftPad from 'left-pad'
import BatteryIcon from './battery/battery-icon'
export default class Battery extends Component {
static displayName() {
return 'battery'
}
constructor(props) {
super(props)
this.state = {
charging: false,
percentage: '--'
}
this.batteryEvents = [ 'chargingchange', 'chargingtimechange', 'dischargingtimechange', 'levelchange' ]
this.handleEvent = this.handleEvent.bind(this)
}
setBatteryStatus(battery) {
this.setState({
charging: battery.charging,
percentage: Math.floor(battery.level * 100)
})
}
handleEvent(event) {
this.setBatteryStatus(event.target)
}
componentDidMount() {
navigator.getBattery().then(battery => {
this.setBatteryStatus(battery)
this.batteryEvents.forEach(event => {
battery.addEventListener(event, this.handleEvent, false)
})
})
}
componentWillUnmount() {
navigator.getBattery().then(battery => {
this.batteryEvents.forEach(event => {
battery.removeEventListener(event, this.handleEvent)
})
})
}
render() {
const { charging, percentage } = this.state
return (
<div className='wrapper'>
<BatteryIcon charging={charging} percentage={Number(percentage)} /> {leftPad(percentage, 2, 0)}%
<style jsx>{`
.wrapper {
display: flex;
align-items: center;
}
`}</style>
</div>
)
}
}
|
import test from 'ava'
import parse from '../../lib/parse'
let networkBus = [{
handler: 'network',
command: 'push',
}]
let networkPropsBus = [{
handler: 'network',
command: 'push',
props: {
timeout: 4,
},
}]
let networkParamsBus = [{
handler: 'network',
command: 'push',
params: [4],
}]
let holdBus = [{
handler: 'hold',
command: 'popall',
}]
let doubleBus = [...networkBus, ...holdBus]
test('simple parse', t => {
t.deepEqual(parse('network push'), networkBus)
t.deepEqual(parse('network push'), networkBus)
t.deepEqual(parse('network push '), networkBus)
t.notDeepEqual(parse('network1 push '), networkBus)
})
test('double parse', t => {
t.deepEqual(parse('network push | hold popall'), doubleBus)
t.deepEqual(parse('network push || hold popall'), doubleBus)
})
test('double parse with props', t => {
t.deepEqual(parse('network push timeout:4'), networkPropsBus)
})
test('double parse with params', t => {
t.deepEqual(parse('network push 4'), networkParamsBus )
})
test('parse with empty bus', t => {
t.deepEqual(parse('network push '), networkBus )
})
test('parse with empty object', t => {
t.deepEqual(parse({}), undefined )
})
test('parse with array with empty', t => {
t.deepEqual(parse([{}]), [{}] )
})
test('parse with object to array', t => {
t.deepEqual(parse({handler: 'test'}), [{handler: 'test'}] )
})
test('parse with object to array', t => {
t.deepEqual(parse([{handler: 'test'}]), [{handler: 'test'}] )
})
|
var express = require('express'),
auction = require('./routes/auction.js'),
exphbs = require('express-handlebars'),
cookieParser = require('cookie-parser'),
session = require('express-session'),
oa_controller = require('./middlewares/oauth'),
auctionlist = require('./middlewares/auctionlist');
var app = express();
if (process.env.PORT) {
//Not working right now.
app.set('oauth consumer key', process.env.oauthkey);
app.set('oauth consumer secret', process.env.oauthsecret);
app.set('app domain', 'http://steelme.heroku.com');
app.set('api domain', process.env.apidomain || 'tmsandbox.co.nz');
console.log('windows azure/production');
} else {
//dev is working
var config = require('./config.json');
app.set('oauth consumer key', config.key);
app.set('oauth consumer secret', config.secret);
app.set('app domain', 'http://localhost:3000');
app.set('api domain', 'tmsandbox.co.nz');
console.log('dev');
}
app.set('views', './views');
app.set('view engine', 'handlebars');
app.set('oauth callback', '/callback');
app.engine('handlebars', exphbs({defaultLayout: 'main'}));
app.use(cookieParser());
app.use(session({
key: 'trademe-demo.sid',
secret: 'a really great secret message that is neat'
}));
app.use(express.static(__dirname + '/public'));
oa_controller.initialize(
app.set('oauth consumer key'),
app.set('oauth consumer secret'),
app.set('app domain') + app.set('oauth callback'),
app.set('api domain'));
// ## Routes
// ### Main (and only) route
app.get('/', oa_controller.auth, auctionlist.auctionlist, auction.index);
// ### Watchlist route
app.get('/auctionlist', oa_controller.auth, auctionlist.auctionlist, auction.index);
// ### Callback route
// Will only be used after OAuth login.
app.get('/callback', oa_controller.callback('/'));
// ### Middleware to handle 404
var notFound = function(req,res,next){
res.statusCode = 404;
res.description = 'Not found';
res.render('404');
};
// ### Middleware to internal server errors
var errorHandler = function(err,req,res,next){
res.render('error',{description:'Please check the URL.'});
};
app.use(notFound);
app.use(errorHandler);
// ### Start Express
var start = function(port){
return app.listen(port, function() {
console.log('Express server listening on port %d in %s mode', port, app.settings.env);
});
};
var server = start(process.env.PORT || 3000);
|
import React, { Component, PropTypes as type } from 'react'
import stateful from 'ui/util/stateful'
import { Link } from 'react-router'
const categoryFolder = 'themes'
export class BrowseThemes extends Component {
static displayName = 'BrowseThemes';
static propTypes = {
filters: type.shape({
categoryFolder: type.string
})
};
static defaultProps = {
filters: { }
};
get themes() {
let { project } = this.context
let { filters, copy } = this.props
return project.scripts.query({ ...filters, categoryFolder })
}
render() {
const copy = this.props.copy
return (
<div>Browse Themes</div>
)
}
}
export default stateful(BrowseThemes, 'settings', 'themes.filters', 'copy')
|
var extend = require('../../extend'),
_ = require('lodash'),
config = hexo.config;
extend.helper.register('paginator', function(options){
var defaults = {
base: '/',
format: config.pagination_dir + '/%d/',
total: 1,
current: 0,
prev_text: 'Prev',
next_text: 'Next',
space: '…',
prev_next: true,
end_size: 1,
mid_size: 2,
show_all: false
};
var options = _.extend(defaults, options),
current = options.current,
total = options.total,
end_size = options.end_size,
mid_size = options.mid_size,
space = options.space,
base = options.base,
format = options.format,
front = '',
back = '';
var link = function(i){
return i == 1 ? base : base + format.replace('%d', i);
};
var pageNum = function(i){
return '<a class="page-number" href="' + link(i) + '">' + i + '</a>';
};
if (options.prev_next){
if (current !== 1) front = '<a class="extend prev" href="' + link(current - 1) + '">' + options.prev_text + '</a>';
if (current !== total) back = '<a class="extend next" href="' + link(current + 1) + '">' + options.next_text + '</a>';
}
if (options.show_all){
for (var i=1; i<=total; i++){
if (i == current){
front += '<span class="page-number current">' + i + '</span>';
} else {
front += pageNum(i);
}
}
} else {
if (end_size){
var endmax = current <= end_size ? current - 1 : end_size;
for (var i=1; i<=endmax; i++){
front += pageNum(i);
}
var endmin = total - current <= end_size ? current + 1 : total - end_size + 1;
for (var i=total; i>=endmin; i--){
back = pageNum(i) + back;
}
if (space){
var space_html = '<span class="space">' + space + '</span>';
if (current - end_size - mid_size > 1) front += space_html;
if (total - end_size - mid_size > current) back = space_html + back;
}
}
if (mid_size){
var midmin = current - mid_size <= end_size ? current - mid_size + end_size : current - mid_size;
if (midmin > 1){
for (var i=midmin; i<=current-1; i++){
front += pageNum(i);
}
}
var midmax = current + mid_size + end_size > total ? current + mid_size - end_size : current + mid_size;
if (midmax < total){
for (var i=midmax; i>=current+1; i--){
back = pageNum(i) + back;
}
}
}
front += '<span class="page-number current">' + current + '</span>';
}
return front + back;
});
|
import fetch from 'isomorphic-fetch'
export default function fetchData(url, opt={}) {
return fetch(opt.query ? makeUrl(url, opt.query) : url, {
...opt,
// 'same-origin' or 'include'
credentials: 'same-origin'
}).then(res => {
const contentType = res.headers.get('Content-Type')
const isJson = contentType.indexOf('json') >= 0
const dataPromise = isJson ? res.json() : res.text()
return res.status >= 400 ? dataPromise.then(data => Promise.reject({status: res.status, data: data})) : dataPromise
})
}
export function postJson(url, json, method='post') {
return fetchData(url, {
method: method,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(json)
})
}
export const makeUrl = (url, params) =>
url + (params && Object.keys(params).length ? '?' + queryStringify(params) : '')
export const queryStringify = (params) => Object.keys(params)
.map((key) => encodeURIComponent(key) + '=' + encodeURIComponent(params[key]))
.join('&')
.replace(/%20/g, '+')
|
import create from './index.tpl'
import createDemo from './demo.tpl'
import htmlSource from './source.txt'
const demoSource = {
html: htmlSource
}
const Demo = createDemo({
data() {
return {
source: demoSource
}
}
})
export default create({
components: {
demo: Demo
}
})
|
// @flow
import React from 'react';
import { Route, Switch } from 'react-router';
import { Home, Avatar } from './pages';
const routes = () => (
<Switch>
<Route exact path="/" component={Home} />
<Route path="/avatar" component={Avatar} />
</Switch>
);
export default routes;
|
const url = require('url');
const should = require('should');
const supertest = require('supertest');
const testUtils = require('../../../utils');
const localUtils = require('./utils');
const configUtils = require('../../../utils/configUtils');
const config = require('../../../../server/config');
const ghost = testUtils.startGhost;
let request;
describe('Pages Content API', function () {
before(function () {
return ghost()
.then(function () {
request = supertest.agent(config.get('url'));
})
.then(function () {
return testUtils.initFixtures('users:no-owner', 'user:inactive', 'posts', 'tags:extra', 'api_keys');
});
});
afterEach(function () {
configUtils.restore();
});
it('Can request pages', function () {
const key = localUtils.getValidKey();
return request.get(localUtils.API.getApiQuery(`pages/?key=${key}`))
.set('Origin', testUtils.API.getURL())
.expect('Content-Type', /json/)
.expect('Cache-Control', testUtils.cacheRules.private)
.expect(200)
.then((res) => {
res.headers.vary.should.eql('Accept-Encoding');
should.exist(res.headers['access-control-allow-origin']);
should.not.exist(res.headers['x-cache-invalidate']);
const jsonResponse = res.body;
should.exist(jsonResponse.pages);
should.exist(jsonResponse.meta);
jsonResponse.pages.should.have.length(1);
res.body.pages[0].slug.should.eql(testUtils.DataGenerator.Content.posts[5].slug);
const urlParts = url.parse(res.body.pages[0].url);
should.exist(urlParts.protocol);
should.exist(urlParts.host);
});
});
it('Can request page', function () {
const key = localUtils.getValidKey();
return request.get(localUtils.API.getApiQuery(`pages/${testUtils.DataGenerator.Content.posts[5].id}/?key=${key}`))
.set('Origin', testUtils.API.getURL())
.expect('Content-Type', /json/)
.expect('Cache-Control', testUtils.cacheRules.private)
.expect(200)
.then((res) => {
res.headers.vary.should.eql('Accept-Encoding');
should.exist(res.headers['access-control-allow-origin']);
should.not.exist(res.headers['x-cache-invalidate']);
const jsonResponse = res.body;
should.exist(jsonResponse.pages);
jsonResponse.pages.should.have.length(1);
res.body.pages[0].slug.should.eql(testUtils.DataGenerator.Content.posts[5].slug);
const urlParts = url.parse(res.body.pages[0].url);
should.exist(urlParts.protocol);
should.exist(urlParts.host);
});
});
});
|
/*
gulpfile.js
===========
Rather than manage one giant configuration file responsible
for creating multiple tasks, each task has been broken out into
its own file in `/gulp`. Any files in that directory
get automatically required below.
To add a new task, simply add a new task file that directory.
*/
const gulp = require('gulp')
const requireDir = require('require-dir')
// Require all tasks in gulp/tasks, including subfolders
requireDir('./gulp', { recurse: true })
// gulp 4 requires dependency tasks to be defined before they are called.
// We'll keep our top-level tasks in this file so that they are defined at the end of the chain, after their dependencies.
gulp.task('generate-assets', gulp.series(
'clean',
'version',
'sass-extensions',
gulp.parallel(
'sass',
'copy-assets',
'sass-documentation',
'copy-assets-documentation',
'sass-v6',
'copy-assets-v6'
)
))
gulp.task('watch', gulp.parallel(
'watch-sass',
'watch-assets',
'watch-sass-v6',
'watch-assets-v6'
))
gulp.task('default', gulp.series(
'generate-assets',
gulp.parallel(
'watch',
'server'
)
))
|
import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
moduleForComponent('ui-shape', 'Integration | Component | ui shape', {
integration: true
});
test('it renders', function(assert) {
assert.expect(1);
this.render(hbs`
{{#ui-shape}}
<p>Content</p>
{{/ui-shape}}
`);
assert.equal(this.$('.ui.shape').length, 1);
});
|
up.Layer.Cover = class Cover extends up.Layer.OverlayWithViewport {
static mode = 'cover'
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.