text
stringlengths 2
6.14k
|
|---|
//
// nodemavens
// Copyright(c) 2014 Matt Hernandez <matt@modulus.io>
// MIT Licensed
//
var express = require('express')
, MongoStore = require('connect-mongo')(express)
, http = require('http')
, path = require('path');
var app = express();
app.use(express.cookieParser(process.env.SECRET || 'cats'));
app.configure('production', function() {
app.use(express.session({
secret: process.env.SECRET || 'cats'
, cookie: { maxAge: 24 * 60 * 60 * 1000 }
, store: new MongoStore({
url: process.env.MONGO_URL || 'mongodb://localhost/test'
})
}));
});
app.configure('development', function() {
app.use(express.errorHandler());
app.use(express.session());
});
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'server/views'));
app.disable('x-powered-by');
app.use(express.favicon(path.join(__dirname, 'public/images/favicon.ico')));
app.use(express.json());
app.use(express.urlencoded());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// Bootstrap the models and controllers.
var models = require('./server/models')()
, controllers = require('./server/controllers')(models);
require('./server/routes')(app, controllers);
http.createServer(app).listen(app.get('port'));
|
$(document).ready(function() {
$("#contact-form [type='submit']").click(function(e) {
e.preventDefault();
// Get input field values of the contact form
var user_email = $('input[name=email-address]').val();
var user_message = $('textarea[name=message]').val();
// Datadata to be sent to server
post_data = {'userEmail':user_email, 'userMessage':user_message};
// Ajax post data to server
$.post('php/contact-me.php', post_data, function(response){
// Load json data from server and output message
if(response.type == 'error') {
output = '<div class="error-message"><p>'+response.text+'</p></div>';
} else {
output = '<div class="success-message"><p>'+response.text+'</p></div>';
// After, all the fields are reseted
$('#contact-form input').val('');
$('#contact-form textarea').val('');
}
$("#answer").hide().html(output).fadeIn();
}, 'json');
});
// Reset and hide all messages on .keyup()
$("#contact-form input, #contact-form textarea").keyup(function() {
$("#answer").fadeOut();
});
});
|
function displayCalendar() {
var htmlContent ="";
var FebNumberOfDays ="";
var counter = 1;
var dateNow = new Date();
var month = dateNow.getMonth();
var nextMonth = month+1; //+1; //Used to match up the current month with the correct start date.
var prevMonth = month -1;
var day = dateNow.getDate();
var year = dateNow.getFullYear();
//Determing if February (28,or 29)
if (month == 1){
if ( ( year % 100 != 0 ) && ( year % 4 == 0 ) || ( year % 400 == 0 ) ) {
FebNumberOfDays = 29;
}else{
FebNumberOfDays = 28;
}
}
// names of months and week days.
var monthNames = ["January","February","March","April","May","June","July","August","September","October","November", "December"];
var dayNames = ["Sunday","Monday","Tuesday","Wednesday","Thrusday","Friday", "Saturday"];
var dayPerMonth = ["31", "" + FebNumberOfDays + "" , "31", "30", "31", "30", "31", "31", "30", "31", "30", "31"]
// days in previous month and next month and day of week.
var nextDate = new Date( nextMonth +' 1 ,' + year);
var weekdays= nextDate.getDay();
var weekdays2 = weekdays
var numOfDays = dayPerMonth[month];
// white space for days of pervious month.
while ( weekdays > 0 ) {
htmlContent += "<td class='monthPre'></td>";
weekdays--;
}
// calander body.
while (counter <= numOfDays){
// When to start new line.
if (weekdays2 > 6) {
weekdays2 = 0;
htmlContent += "</tr><tr>";
}
// if counter is current day.
// highlight current day.
if (counter == day){
htmlContent +="<td class='dayNow' onMouseOver='this.style.background=\"#FF0000\"; this.style.color=\"#FFFFFF\"' "+
"onMouseOut='this.style.background=\"#FFFFFF\"; this.style.color=\"#333\"'>"+counter+"</td>";
}else{
htmlContent +="<td class='monthNow' onMouseOver='this.style.background=\"#FF0000\"'"+
" onMouseOut='this.style.background=\"#FFFFFF\"'>"+counter+"</td>";
}
weekdays2++;
counter++;
}
// calendar html body.
var calendarBody = "<table class='table table-condensed calendar'> <tr class='monthNow'><th colspan='7'>"
+monthNames[month]+" "+ year +"</th></tr>";
calendarBody +="<tr class='dayNames'> <td>Sun</td> <td>Mon</td> <td>Tues</td>"+
"<td>Wed</td> <td>Thurs</td> <td>Fri</td> <td>Sat</td> </tr>";
calendarBody += "<tr>";
calendarBody += htmlContent;
calendarBody += "</tr></table>";
// set the content of div .
document.getElementById("calendar").innerHTML=calendarBody;
};
displayCalendar();
|
/*
* Translated default messages for bootstrap-select.
* Locale: IT (Italian; italiano)
* Region: IT (Italy; Italia)
* Author: Michele Beltrame <mb@cattlegrid.info>
*/
(function ($) {
$.fn.selectpicker.defaults = {
noneSelectedText: 'Nessuna selezione',
noneResultsText: 'Nessun risultato per {0}',
countSelectedText: function (numSelected, numTotal) {
return (numSelected == 1) ? 'Selezionato {0} di {1}' : 'Selezionati {0} di {1}';
},
maxOptionsText: ['Limite raggiunto ({n} {var} max)', 'Limite del gruppo raggiunto ({n} {var} max)', ['elementi', 'elemento']],
multipleSeparator: ', ',
selectAllText: 'Seleziona Tutto',
deselectAllText: 'Deseleziona Tutto'
};
})(jQuery);
|
var searchData=
[
['errorstring',['errorString',['../classqe_1_1render_1_1vulkan_1_1_vulkan_tools.html#a4eca1f90bf6fb0f99286fec0380b1724',1,'qe::render::vulkan::VulkanTools']]],
['exitfatal',['exitFatal',['../classqe_1_1render_1_1vulkan_1_1_vulkan_tools.html#a309a805fcdcb68d862ca161369cc4109',1,'qe::render::vulkan::VulkanTools']]],
['extensionsupported',['ExtensionSupported',['../classqe_1_1render_1_1vulkan_1_1_vulkan_device.html#a5ba121615d7663ea201ab6f5d842b558',1,'qe::render::vulkan::VulkanDevice']]]
];
|
// file path: root/static/person/person.js
var _ = require("../utils/underscore");
function Person(details) {
// Make sure we instantiate this object
if (!(this instanceof Person)) {
return new Person(details);
}
var id;
this.getId = function () {
return id;
}
this.setId = function (val) {
if (val == "")
throw "Id cannot be blank";
id = val;
}
// End Id
var name;
this.getName = function () {
return name;
}
this.setName = function (val) {
if (val == "")
throw "Name cannot be blank";
name = val;
}
// End Name
var color = "#FFFFFF";
this.getColor = function () {
return color;
}
this.setColor = function(val) {
if (typeof val !== "undefined" && /^#([0-9A-Fa-f]{3}|[0-9A-Fa-f]{6})$/.test(val) ) {
color = val;
} else if (typeof val !== "undefined") {
throw "Bad Color";
}
}
// End Color
var score = 0;
this.getScore = function() {
return score;
}
this.incrementScore = function(inc) {
if (typeof inc === "number") {
score += inc;
} else if (typeof inc === "undefined") {
score++;
} else {
throw "Bad Score";
}
}
// End Score
// Make it flat
this.flattify = function() {
return { id: id, name: name, color: color }
}
// Check to see if we got this passed
if (details) {
this.setId( details["id"] );
this.setName( details["name"] );
this.setColor( details["color"] );
}
}
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = Person;
}
}
|
version https://git-lfs.github.com/spec/v1
oid sha256:06805899b7a1357eaa8ec73ec08c59e47089c3330877162bd9c27aa5d0c59aff
size 2717
|
// Generated by CoffeeScript 1.6.3
(function() {
var UserProfileSchema, mongoose;
mongoose = require('mongoose');
module.exports = UserProfileSchema = new mongoose.Schema({
linkUrl: {
type: String
},
linkIdentifier: {
type: String
},
provider: {
type: String
},
linkType: {
type: String
},
linkSubType: {
type: String
},
caption: {
type: String
},
isPublic: {
type: Boolean,
"default": false
}
});
}).call(this);
|
var fs=require("fs");
exports.watch=function(){
fs.watchFile(__dirname+'/config.json', function (curr, prev) {
reload_config();
});
};
exports.unwatch=function(){
fs.unwatchFile(__dirname+'/config.json');
};
function reload_config(){
var config_json=fs.readFileSync(__dirname+"/config.json",{encoding:'utf-8'});
try{
var config=(eval(config_json));
}catch(e){
log.error(e);
return;
}
for(var c in config){
exports[c]=config[c];
}
config.hosts.forEach(function(host){
exports.DNSCache[host[0]]={addresses:[host[1]]};
});
}
exports.addDNSCache=function(host,ip){
exports.DNSCache[hosts]={addresses:[ip]};
};
exports.delDNSCache=function(host){
delete exports.DNSCache[hosts];
};
exports.DNSCache={};
reload_config();
|
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
info: The Date.prototype property "valueOf" has { DontEnum } attributes
es5id: 15.9.5.8_A1_T1
description: Checking absence of ReadOnly attribute
---*/
x = Date.prototype.valueOf;
if(x === 1)
Date.prototype.valueOf = 2;
else
Date.prototype.valueOf = 1;
if (Date.prototype.valueOf === x) {
$ERROR('#1: The Date.prototype.valueOf has not the attribute ReadOnly');
}
|
var Q = require('q');
var fs = require('q-io/fs');
var express = require('express');
var analyzer = require('./lib/sourcetreemap/analyzer.js');
Q.longStackSupport = true;
var app = express();
app.use(express.static('public'));
app.get('/analyze', function(req, res) {
analyzer.analyze(req.query.url).then(function(analyzer) {
res.send({ files: analyzer.files, treeRoot: analyzer.treeRoot });
res.end();
}).catch(function(error) {
console.error(error.stack);
res.send(error);
res.end(500);
});
});
var server = app.listen(process.env.PORT || 8888, function() {
console.log('Listening on port %d', server.address().port);
});
|
import React from 'react';
import ReactDOM from 'react-dom';
import {Provider} from 'react-redux';
import injectTapEventPlugin from 'react-tap-event-plugin';
injectTapEventPlugin();
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import store from './data/root/store';
import App from './container/App';
ReactDOM.render(
<Provider store={store}>
<MuiThemeProvider>
<App />
</MuiThemeProvider>
</Provider>,
document.getElementById("app")
);
if (module.hot) {
module.hot.accept('./container/App', () => {
const NextApp = require("./container/App").default;
ReactDOM.render(
<Provider store={store}>
<NextApp/>
</Provider>, document.getElementById('app')
);
});
}
|
var express = require('express')
//, routes = require('./routes')
, bodyParser = require('body-parser')
, cookieParser = require('cookie-parser')
, logger = require('morgan')
, http = require('http')
, path = require('path')
, ejs = require('ejs')
, URL = require('url')
, session = require("express-session");;
var app = express();
//设置默认端口, 启动views
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, ''));
app.engine('.html', ejs.__express);
app.set('view engine', 'html');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(cookieParser());
app.use(session({
secret: 'ATUi'
}))
app.use(express.static(path.join(__dirname, 'dist')));
app.use(function (req, res, next) {
var url = req.originalUrl.substr(1, req.originalUrl.length - 1)
var arg = URL.parse(req.url, true).query;
//多语言控制加载方式 xx
if(arg.lang) {
req.session.lang = arg.lang;
url = "";
}
if(!req.session.lang){
req.session.lang = "CH";
}
var lang = require('./lang/lang_' + req.session.lang);
res.render(url, lang);
});
// catch 404 and forward to error handler
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
//socket 服务
var server = http.createServer(app);
//启动server
server.listen(app.get('port'), function () {
console.log('Express server listening on port ' + app.get('port'));
});
|
'use strict';
(function() {
// Builds Controller Spec
describe('Builds Controller Tests', function() {
// Initialize global variables
var BuildsController,
scope,
$httpBackend,
$stateParams,
$location;
// The $resource service augments the response object with methods for updating and deleting the resource.
// If we were to use the standard toEqual matcher, our tests would fail because the test values would not match
// the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher.
// When the toEqualData matcher compares two objects, it takes only object properties into
// account and ignores methods.
beforeEach(function() {
jasmine.addMatchers({
toEqualData: function(util, customEqualityTesters) {
return {
compare: function(actual, expected) {
return {
pass: angular.equals(actual, expected)
};
}
};
}
});
});
// Then we can start by loading the main application module
beforeEach(module(ApplicationConfiguration.applicationModuleName));
// The injector ignores leading and trailing underscores here (i.e. _$httpBackend_).
// This allows us to inject a service but then attach it to a variable
// with the same name as the service.
beforeEach(inject(function($controller, $rootScope, _$location_, _$stateParams_, _$httpBackend_) {
// Set a new global scope
scope = $rootScope.$new();
// Point global variables to injected services
$stateParams = _$stateParams_;
$httpBackend = _$httpBackend_;
$location = _$location_;
// Initialize the Builds controller.
BuildsController = $controller('BuildsController', {
$scope: scope
});
}));
it('$scope.find() should create an array with at least one Build object fetched from XHR', inject(function(Builds) {
// Create sample Build using the Builds service
var sampleBuild = new Builds({
name: 'New Build'
});
// Create a sample Builds array that includes the new Build
var sampleBuilds = [sampleBuild];
// Set GET response
$httpBackend.expectGET('builds').respond(sampleBuilds);
// Run controller functionality
scope.find();
$httpBackend.flush();
// Test scope value
expect(scope.builds).toEqualData(sampleBuilds);
}));
it('$scope.findOne() should create an array with one Build object fetched from XHR using a buildId URL parameter', inject(function(Builds) {
// Define a sample Build object
var sampleBuild = new Builds({
name: 'New Build'
});
// Set the URL parameter
$stateParams.buildId = '525a8422f6d0f87f0e407a33';
// Set GET response
$httpBackend.expectGET(/builds\/([0-9a-fA-F]{24})$/).respond(sampleBuild);
// Run controller functionality
scope.findOne();
$httpBackend.flush();
// Test scope value
expect(scope.build).toEqualData(sampleBuild);
}));
it('$scope.create() with valid form data should send a POST request with the form input values and then locate to new object URL', inject(function(Builds) {
// Create a sample Build object
var sampleBuildPostData = new Builds({
name: 'New Build'
});
// Create a sample Build response
var sampleBuildResponse = new Builds({
_id: '525cf20451979dea2c000001',
name: 'New Build'
});
// Fixture mock form input values
scope.name = 'New Build';
// Set POST response
$httpBackend.expectPOST('builds', sampleBuildPostData).respond(sampleBuildResponse);
// Run controller functionality
scope.create();
$httpBackend.flush();
// Test form inputs are reset
expect(scope.name).toEqual('');
// Test URL redirection after the Build was created
expect($location.path()).toBe('/builds/' + sampleBuildResponse._id);
}));
it('$scope.update() should update a valid Build', inject(function(Builds) {
// Define a sample Build put data
var sampleBuildPutData = new Builds({
_id: '525cf20451979dea2c000001',
name: 'New Build'
});
// Mock Build in scope
scope.build = sampleBuildPutData;
// Set PUT response
$httpBackend.expectPUT(/builds\/([0-9a-fA-F]{24})$/).respond();
// Run controller functionality
scope.update();
$httpBackend.flush();
// Test URL location to new object
expect($location.path()).toBe('/builds/' + sampleBuildPutData._id);
}));
it('$scope.remove() should send a DELETE request with a valid buildId and remove the Build from the scope', inject(function(Builds) {
// Create new Build object
var sampleBuild = new Builds({
_id: '525a8422f6d0f87f0e407a33'
});
// Create new Builds array and include the Build
scope.builds = [sampleBuild];
// Set expected DELETE response
$httpBackend.expectDELETE(/builds\/([0-9a-fA-F]{24})$/).respond(204);
// Run controller functionality
scope.remove(sampleBuild);
$httpBackend.flush();
// Test array after successful delete
expect(scope.builds.length).toBe(0);
}));
});
}());
|
var _ = {
isUndefined: require('lodash/isUndefined'),
isFunction: require('lodash/isFunction'),
isString: require('lodash/isString'),
isObject: require('lodash/isObject'),
};
module.exports = function (key, map) {
var action = map[key];
var def = map.default;
if (!_.isString(key)) {
throw new TypeError('`key` parameter should be a string.');
}
if (!_.isObject(map)) {
throw new TypeError('`map` parameter should be an object.');
}
if (_.isFunction(action)) {
return action.call(this);
}
if (!_.isUndefined(action)) {
return action;
}
if (_.isFunction(def)) {
return def.call(this);
}
return def;
};
|
import React, { Component, PropTypes } from 'react'
import { connect } from 'react-redux'
import { resource } from '../../actions'
//headline basic structure
export const Headline = ({user,dispatch}) => {
let status;
return(
<div>
<img src={user.avatar}/>
<div>{user.name}</div>
<div><b>{user.headline}</b></div>
<br/>
<input className="inputmsg2" type="text"ref={(node)=>status = node}/>
<br/><br/>
<input id="changeHl" className="btn" type="submit"
value="Change Headline" onClick={(event) =>
{event.preventDefault();
changeHeadline(status, dispatch)}
}/>
<br/>
</div>
)
}
//change the headline
const changeHeadline=(status,dispatch)=>{
if(status.value != '') {
resource('PUT', 'headline', { headline: status.value })
.then((response) => {
dispatch({type: 'UPDATE_HEADLINE', username: response.username, headline: response.headline})
})
status.value = ''
}
}
//check the type
Headline.propTypes = {
user: PropTypes.object.isRequired
}
export default connect(
(state) => {
return {
user: state.user
}
},null
)(Headline)
|
/**
* 装备额外属性收益
* 283. **533mm 三連装魚雷**
*
* @module
*/
// https://wikiwiki.jp/kancolle/533mm%20%E4%B8%89%E9%80%A3%E8%A3%85%E9%AD%9A%E9%9B%B7
const { vmf_DD } = require('../../ships')
module.exports = [
{
equipment: 283,
ship: {
isID: vmf_DD,
},
bonus: {
fire: 1,
torpedo: 3,
armor: 1,
}
},
// ------------------------------------------------------------------------
]
|
System.register(['angular2/core', './movies/movie-list.component'], function(exports_1, context_1) {
"use strict";
var __moduleName = context_1 && context_1.id;
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, movie_list_component_1;
var AppComponent;
return {
setters:[
function (core_1_1) {
core_1 = core_1_1;
},
function (movie_list_component_1_1) {
movie_list_component_1 = movie_list_component_1_1;
}],
execute: function() {
AppComponent = (function () {
function AppComponent() {
this.pageTitle = "InStep Movie Hunter";
}
AppComponent = __decorate([
core_1.Component({
selector: 'mh-app',
template: "\n <div class=\"container\">\n <h1>{{pageTitle}}</h1>\n <div>\n <mh-movies></mh-movies>\n </div>\n </div>\n ",
directives: [movie_list_component_1.MovieListComponent]
}),
__metadata('design:paramtypes', [])
], AppComponent);
return AppComponent;
}());
exports_1("AppComponent", AppComponent);
}
}
});
//# sourceMappingURL=app.component.js.map
|
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }
var _Calendar = require('./Calendar');
var _Calendar2 = _interopRequireDefault(_Calendar);
exports['default'] = _Calendar2['default'];
module.exports = exports['default'];
|
"use strict"
const messages = require("..").messages
const ruleName = require("..").ruleName
const rules = require("../../../rules")
const rule = rules[ruleName]
testRule(rule, {
ruleName,
config: [0],
accept: [ {
code: "a { padding: 10px 10px 10px 10px }",
}, {
code: "a { padding:\n10px 10px 10px 10px }",
}, {
code: "a { padding:\n\n10px 10px 10px 10px }",
}, {
code: "a { padding:\r\n10px 10px 10px 10px }",
}, {
code: "a { padding:\r\n\r\n10px 10px 10px 10px }",
}, {
code: "a { padding: 10px 10px 10px 10px\n }",
}, {
code: "a { padding: 10px 10px 10px 10px\r\n }",
}, {
code: "a { padding: 10px 10px 10px 10px\n\n }",
}, {
code: "a { padding: 10px 10px 10px 10px\r\n\r\n }",
}, {
code: "a { padding: 10px\n10px\n10px\n10px }",
}, {
code: "a { padding: 10px\r\n10px\r\n10px\r\n10px }",
}, {
code: "a { box-shadow: inset 0 2px 0 #dcffa6, 0 2px 5px #000; }",
}, {
code: "a { box-shadow: inset 0 2px 0 #dcffa6,\n0 2px 5px #000; }",
}, {
code: "a { box-shadow: inset 0 2px 0 #dcffa6,\r\n0 2px 5px #000; }",
} ],
reject: [ {
code: "a { padding: 10px\n\n10px 10px 10px }",
message: messages.expected(0),
line: 1,
column: 9,
}, {
code: "a { padding: 10px\r\n\r\n10px 10px 10px }",
message: messages.expected(0),
line: 1,
column: 9,
}, {
code: "a { padding: 10px 10px 10px\n\n10px }",
message: messages.expected(0),
line: 1,
column: 19,
}, {
code: "a { padding: 10px 10px 10px\r\n\r\n10px }",
message: messages.expected(0),
line: 1,
column: 19,
}, {
code: "a { box-shadow: inset 0 2px 0 #dcffa6,\n\n0 2px 5px #000; }",
message: messages.expected(0),
line: 1,
column: 27,
}, {
code: "a { box-shadow: inset 0 2px 0 #dcffa6,\r\n\r\n0 2px 5px #000; }",
message: messages.expected(0),
line: 1,
column: 27,
} ],
})
testRule(rule, {
ruleName,
config: [1],
accept: [ {
code: "a { padding: 10px\n10px\n10px\n10px }",
}, {
code: "a { padding: 10px\r\n10px\r\n10px\r\n10px }",
}, {
code: "a { padding: 10px\n\n10px\n\n10px\n\n10px }",
}, {
code: "a { padding: 10px\r\n\r\n10px\r\n\r\n10px\r\n\r\n10px }",
}, {
code: "a { box-shadow: inset 0 2px 0 #dcffa6, 0 2px 5px #000; }",
}, {
code: "a { box-shadow: inset 0 2px 0 #dcffa6,\n\n0 2px 5px #000; }",
}, {
code: "a { box-shadow: inset 0 2px 0 #dcffa6,\r\n\r\n0 2px 5px #000; }",
} ],
reject: [ {
code: "a { padding: 10px\n\n\n10px 10px 10px }",
message: messages.expected(1),
line: 1,
column: 9,
}, {
code: "a { padding: 10px\r\n\r\n\r\n10px 10px 10px }",
message: messages.expected(1),
line: 1,
column: 9,
}, {
code: "a { padding: 10px 10px 10px\n\n\n10px }",
message: messages.expected(1),
line: 1,
column: 19,
}, {
code: "a { padding: 10px 10px 10px\r\n\r\n\r\n10px }",
message: messages.expected(1),
line: 1,
column: 19,
}, {
code: "a { box-shadow: inset 0 2px 0 #dcffa6,\n\n\n0 2px 5px #000; }",
message: messages.expected(1),
line: 1,
column: 27,
}, {
code: "a { box-shadow: inset 0 2px 0 #dcffa6,\r\n\r\n\r\n0 2px 5px #000; }",
message: messages.expected(1),
line: 1,
column: 27,
} ],
})
|
define('parsley/form', [
'parsley/abstract',
'parsley/utils'
], function (ParsleyAbstract, ParsleyUtils) {
var ParsleyForm = function (element, domOptions, options) {
this.__class__ = 'ParsleyForm';
this.__id__ = ParsleyUtils.generateID();
this.$element = $(element);
this.domOptions = domOptions;
this.options = options;
this.parent = window.Parsley;
this.fields = [];
this.validationResult = null;
};
ParsleyForm.prototype = {
onSubmitValidate: function (event) {
this.validate(undefined, undefined, event);
// prevent form submission if validation fails
if ((false === this.validationResult || !this._trigger('submit')) && event instanceof $.Event) {
event.stopImmediatePropagation();
event.preventDefault();
}
return this;
},
// @returns boolean
validate: function (group, force, event) {
this.submitEvent = event;
this.validationResult = true;
var fieldValidationResult = [];
// fire validate event to eventually modify things before very validation
this._trigger('validate');
// Refresh form DOM options and form's fields that could have changed
this._refreshFields();
this._withoutReactualizingFormOptions(function(){
// loop through fields to validate them one by one
for (var i = 0; i < this.fields.length; i++) {
// do not validate a field if not the same as given validation group
if (group && !this._isFieldInGroup(this.fields[i], group))
continue;
fieldValidationResult = this.fields[i].validate(force);
if (true !== fieldValidationResult && fieldValidationResult.length > 0 && this.validationResult)
this.validationResult = false;
}
});
this._trigger(this.validationResult ? 'success' : 'error');
this._trigger('validated');
return this.validationResult;
},
// Iterate over refreshed fields, and stop on first failure
isValid: function (group, force) {
this._refreshFields();
return this._withoutReactualizingFormOptions(function(){
for (var i = 0; i < this.fields.length; i++) {
// do not validate a field if not the same as given validation group
if (group && !this._isFieldInGroup(this.fields[i], group))
continue;
if (false === this.fields[i].isValid(force))
return false;
}
return true;
});
},
_isFieldInGroup: function (field, group) {
if($.isArray(field.options.group))
return -1 !== $.inArray(group, field.options.group);
return field.options.group === group;
},
_refreshFields: function () {
return this.actualizeOptions()._bindFields();
},
_bindFields: function () {
var self = this,
oldFields = this.fields;
this.fields = [];
this.fieldsMappedById = {};
this._withoutReactualizingFormOptions(function(){
this.$element
.find(this.options.inputs)
.not(this.options.excluded)
.each(function () {
var fieldInstance = new Parsley.Factory(this, {}, self);
// Only add valid and not excluded `ParsleyField` and `ParsleyFieldMultiple` children
if (('ParsleyField' === fieldInstance.__class__ || 'ParsleyFieldMultiple' === fieldInstance.__class__) && (true !== fieldInstance.options.excluded))
if ('undefined' === typeof self.fieldsMappedById[fieldInstance.__class__ + '-' + fieldInstance.__id__]) {
self.fieldsMappedById[fieldInstance.__class__ + '-' + fieldInstance.__id__] = fieldInstance;
self.fields.push(fieldInstance);
}
});
$(oldFields).not(self.fields).each(function () {
this._trigger('reset');
});
});
return this;
},
// Internal only.
// Looping on a form's fields to do validation or similar
// will trigger reactualizing options on all of them, which
// in turn will reactualize the form's options.
// To avoid calling actualizeOptions so many times on the form
// for nothing, _withoutReactualizingFormOptions temporarily disables
// the method actualizeOptions on this form while `fn` is called.
_withoutReactualizingFormOptions: function (fn) {
var oldActualizeOptions = this.actualizeOptions;
this.actualizeOptions = $.noop;
var result = fn.call(this); // Keep the current `this`.
this.actualizeOptions = oldActualizeOptions;
return result;
},
// Internal only.
// Shortcut to trigger an event
// Returns true iff event is not interrupted and default not prevented.
_trigger: function (eventName) {
eventName = 'form:' + eventName;
return this.trigger.apply(this, arguments);
}
};
return ParsleyForm;
});
|
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
/* jshint latedef:false */
/* jshint forin:false */
/* jshint noempty:false */
'use strict';
exports.IntModel = require('./intModel');
|
const webpack = require('webpack');
module.exports = {
entry: './src/index',
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel',
exclude: /node_modules/,
query: {
presets: ['es2015', 'react'],
},
},
],
},
externals: [{
react: {
root: 'React',
commonjs2: 'react',
commonjs: 'react',
amd: 'react',
},
}],
output: {
filename: 'dist/react-input-suggest.min.js',
libraryTarget: 'umd',
library: 'react-input-suggest',
},
plugins: [
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production'),
},
}),
],
};
|
'use strict';
// Parent constructor
function CarMaker() {};
// A method of the parent
CarMaker.prototype.drive = function() {
return 'I have ' + this.doors + ' doors';
};
// the static factory method
CarMaker.factory = function(type) {
let constr = type;
let newCar;
// error if the constructor doesn't exists
if (typeof CarMaker[constr] !== 'function') {
throw {
name: 'Error',
message: constr + 'doesn\'t exists',
};
}
// inherit the parent but only once
if (typeof CarMaker[constr].prototype.drive !== 'function') {
CarMaker[constr].prototype = new CarMaker();
}
// create new instance
newCar = new CarMaker[constr]();
return newCar;
};
// define specific car makers
CarMaker.Compact = function() {
this.doors = 4;
};
CarMaker.Convertible = function() {
this.doors = 2;
};
CarMaker.SUV = function() {
this.doors = 24;
};
let corolla = CarMaker.factory('Compact');
let solstice = CarMaker.factory('Convertible');
let cherokee = CarMaker.factory('SUV');
let jsFC = document.getElementById('js-factory-corolla');
jsFC.innerHTML = corolla.drive(); // "I have 4 doors"
let jsFS = document.getElementById('js-factory-solstice');
jsFS.innerHTML = solstice.drive(); // "I have 2 doors"
let jsFCh = document.getElementById('js-factory-cherokee');
jsFCh.innerHTML = cherokee.drive(); // "I have 17 doors"
|
API.LayoutViews.Home = Marionette.LayoutView.extend({
template: "#app-skeleton",
className: "app-layout",
regions: {
header: "#header-container"
}
});
|
var globID;
function zobraz(id) {
globID = id;
turnLayer(1);
document.getElementById("vrstva").style.backgroundImage = "url(" + a.photos[id].src + ")";
document.getElementById("vrstva").style.visibility = "visible";
document.getElementById("text").innerHTML = a.photos[id].title;
document.getElementById("desc").innerHTML = a.photos[id].desc;
}
var x = true;
function left() {
if (globID == 0) {
globID = 4;
zobraz(globID);
}
else {
globID--;
zobraz(globID);
}
}
function right() {
if (globID == 4) {
globID = 0;
zobraz(globID);
}
else {
globID++;
zobraz(globID);
}
}
function pohyb() {
if (x == true) {
if (globID == 4) {
zobraz(globID);
globID = 0;
}
else {
zobraz(globID);
globID++;
}
}
}
function exit() {
document.getElementById("vrstva").style.visibility = "hidden";
turnLayer(0);
x = false;
}
function play() {
x = true;
setInterval(pohyb, 2000);
}
function turnLayer(on) {
var d = document.getElementById("layer");
if (on) {
d.className = 'layer';
} else {
d.className = 'layer hidden';
}
}
|
var concat = require('..');
var equal = require('assert-dir-equal');
var rimraf = require('rimraf');
var vfs = require('vinyl-fs');
describe('gulp-multi-concat', function() {
before(function() {
process.chdir('test/fixtures');
});
after(function(done) {
rimraf('_build', done)
});
it('performs multiple sets of file concatenations', function(done) {
concat({
'test1.html': [
'src/test1-1.html',
'src/test1-2.html'
],
'test2.html': [
'src/test2-1.html',
'src/test2-2.html'
]
})
.pipe(vfs.dest('_build'))
.on('finish', function() {
equal('expected', '_build');
done();
});
});
});
|
import Deal from 'scripts'
import {
ADMIN_GET_REFINEMENTS
} from './const'
export function getRefinements () {
return (dispatch) => {
return Deal.Category.getAllRefinements().then((json) => {
dispatch({
payload: json,
type: ADMIN_GET_REFINEMENTS
})
}).catch((error) => {
//@TODO log the error message.
})
}
}
|
var fs = require('fs')
var path = require('path')
var appDir = path.dirname(require.main.filename)
var familyDao = require(appDir + '/data/family-dao.js')
const locationsFile = "locations.json"
const locationsPath = (appDir + '/data/' + locationsFile)
module.exports = {
getAllLocations: function(callback) {
readLocations(null, callback);
},
getLocationById: function(locationId, callback) {
readLocations(locationId, callback);
},
getLocationByFamilyMemberId: function(familyMemberId, callback) {
readLocationByFamilyMemberId(familyMemberId, callback);
}
};
function readLocationsJson(callback) {
fs.readFile(locationsPath, 'utf8', function readFileCallback(err, data){
if (err){
console.log(err)
throw new Error("can't read file")
} else {
locationsObj = JSON.parse(data)
callback(locationsObj)
}
});
}
function readLocations(locationId, callback) {
readLocationsJson(function(locationsObj) {
if (locationsObj) {
if (!locationId) {
console.log(locationsObj)
callback(locationsObj)
} else {
if (locationsObj.locations && locationsObj.locations.length && locationsObj.locations.length > 0) {
var locations = locationsObj.locations
for (index = 0; index < locations.length; ++index) {
var location = locations[index]
if (location.id === locationId) {
console.log(location)
callback(location)
return;
}
}
}
throw new Error("can't find location")
return;
}
} else {
console.log("locations obj was null")
throw new Error("can't get locations")
}
});
}
function readLocationByFamilyMemberId(familyMemberId, callback) {
if (familyMemberId) {
familyDao.getFamilyById(familyMemberId, function(familyMember){
if (familyMember) {
var locationId = familyMember.location;
readLocationsJson(function(locationsObj) {
if (locationsObj) {
if (locationsObj.locations && locationsObj.locations.length && locationsObj.locations.length > 0) {
var locations = locationsObj.locations
for (index = 0; index < locations.length; ++index) {
var location = locations[index]
if (location.id === locationId) {
console.log(location)
callback(location)
return;
}
}
throw new Error("can't find location member")
return;
}
} else {
console.log("locations obj was null")
throw new Error("can't get locations")
}
});
}
})
}
}
|
var md_tpl = '[{title}]({link})';
function markdown(arr) {
return md_tpl.replace('{title}',arr[0]).replace('{link}', arr[1]);
}
function txt(arr) {
return arr.join('\n');
}
exports.generate = function generate(arr, ext) {
switch (ext) {
case 'txt':
return txt(arr);
break;
case 'md':
return markdown(arr);
break;
}
};
|
const HelpBlock = require('../../app/examples/HelpBlock.react');
const expect = global.expect,
it = global.it,
describe = global.describe,
shallow = global.shallow,
beforeEach = global.beforeEach,
context = global.context;
describe('A HelpBlock component,', function() {
it('renders without exploding', function() {
expect(shallow(<HelpBlock />)).to.exist;
});
context('should display nothing when there\'s no error message,', function() {
it('like null', function() {
const wrapper = shallow(<HelpBlock errorMessage={null} />);
expect(wrapper.find('span')).to.be.empty;
});
it('like an empty string', function() {
const wrapper = shallow(<HelpBlock errorMessage={''} />);
expect(wrapper.find('span')).to.be.empty;
});
});
context('when threre\'s an error, should display', function() {
let wrapper;
let errorMessage;
beforeEach(function() {
errorMessage = 'É uma cilada Bino!';
wrapper = shallow(<HelpBlock errorMessage={errorMessage} />);
});
it('the right error message', function() {
expect(wrapper.find('span')).to.contain(errorMessage);
});
it('and not the wrong error message', function() {
const wrongMessage = 'this should not appear';
expect(wrapper.find('span')).to.not.contain(wrongMessage);
});
});
context('should have the classes', function() {
let wrapper;
beforeEach(function() {
wrapper = shallow(<HelpBlock />);
});
it('help-block', function() {
expect(wrapper.find('span')).to.have.className('help-block');
});
it('and not some other random classes', function() {
expect(wrapper.find('span')).to.not.have.className('DUMMYCLASS');
});
});
});
|
var path = require("path");
var webpack = require("webpack");
var autoprefixer = require("autoprefixer");
var HtmlWebpackPlugin = require("html-webpack-plugin");
var ExtractTextPlugin = require("extract-text-webpack-plugin");
/**
* Check if currently in development environment.
*/
var isDev = process.env.NODE_ENV !== "production";
/**
* Get loader for specific type.
*
* @param {String} type
* @returns {String}
*/
function getLoader(type) {
return "css?modules&importLoaders=2&sourceMap&localIdentName=[local]_[hash:base64:5]!" +
type +
"?outputStyle=expanded&sourceMap";
}
/**
* Webpack configuration.
*/
var config = {
/**
* Context to resolve relative paths.
*/
context: __dirname,
/**
* Entry point for the application.
*/
entry: {
src: "./src/scripts/main"
},
/**
* Output settings.
*/
output: {
path: path.resolve("./build"),
filename: "assets/[name]-[hash].js",
publicPath: "/"
},
/**
* Common plugins for production and development.
*/
commonPlugins: [
new HtmlWebpackPlugin({
title: "2048 - implemented with React and Redux",
template: "src/index.html"
}),
new webpack.ProvidePlugin({
React: "react"
})
],
module: {
/**
* Loaders to be executed ahead of the others.
*
* Example:
* - Eslint checks should be made before the code is transformed.
*/
preLoaders: [
/**
* Eslint loader.
*/
{
test: /\.js$/,
exclude: /node_modules/,
loader: "eslint"
}
],
/**
* Loaders to be used for code transformation.
*/
loaders: [
/**
* Implement Hot Module Replacement and Babel transpiler.
*/
{
test: /\.js?$/,
exclude: /node_modules/,
loaders: ["react-hot", "babel"]
},
/**
* Load .json files.
*/
{
test: /\.json$/,
loader: "json-loader"
},
/**
* Load .less files.
*
* If the environment is different than `development` extract the css, should not
* be used otherwise, because HMR won't work.
*/
{
test: /\.less$/,
loader: isDev ?
"style!".concat(getLoader("less")) :
ExtractTextPlugin.extract("style", getLoader("less"))
},
/**
* Load .sass files.
*
* If the environment is different than `development` extract the css, should not
* be used otherwise, because HMR won't work.
*/
{
test: /\.scss$/,
loader: isDev ?
"style!".concat(getLoader("sass")) :
ExtractTextPlugin.extract("style", getLoader("sass"))
},
/**
* Load .jpg pictures.
*/
{
test: /\.(jpg)$/,
loader: "url?limit=25000"
},
/**
* Load .png, .gif, .svg pictures.
*/
{
test: /\.(png|gif|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: "file-loader?hash=sha512&digest=hex&name=assets/[name].[ext]"
},
/**
* Load .woff, .woff2 fonts.
*/
{
test: /\.(woff|woff2)(\?v=\d+\.\d+\.\d+)?$/,
loader: "url?limit=10000&mimetype=application/font-woff"
},
/**
* Load .ttf, .eot fonts.
*/
{
test: /\.(ttf|eot)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
loader: "file-loader?name=assets/[hash].[ext]"
}
]
},
/**
* Post css.
*/
postcss: [autoprefixer],
/**
* Resolve modules.
*/
resolve: {
/**
* Alias for resolving modules names.
*/
alias: {
js: path.join(__dirname, "src", "scripts"),
img: path.join(__dirname, "src", "images"),
css: path.join(__dirname, "src", "styles")
},
/**
* Directories to be resolved.
*/
modulesDirectories: [
"src",
"node_modules",
"bower_components"
],
/**
* Files with the following extensions should be resolved.
*/
extensions: ["", ".json", ".js"]
}
};
/**
* Export the configuration object.
*/
module.exports = config;
|
/*global define */
// Spanish - strings
define({
'COMMAND_NAME' : 'JSLint Configurador',
/* DIALOG HEADER */
'DIALOG_TITLE' : 'JSLint Configurador',
'CLEAR_OPTIONS' : 'opciones claras',
/* DIALOG BODY */
'ASSUME' : 'Supongamos',
'TOLERATE' : 'Tolerar',
/* JSLINT OPTIONS */
'BROWSER' : 'un navegador',
'COUCH' : 'CouchDB',
'DEVEL' : 'console, alert, ...',
'NODE' : 'Node.js',
'RHINO' : 'Rhino',
'PASSFAIL' : 'Pare el primer error',
'ASS' : 'expresiones de asignación',
'BITWISE' : 'operadores bit a bit',
'CLOSURE' : 'Google Closure',
'CONTINUE' : 'continue',
'DEBUG' : 'declaraciones del depurador',
'EQEQ' : '== y !=',
'EVIL' : 'eval',
'FORIN' : 'sin filtrar for in',
'NEWCAP' : 'constructores sin mayúsculas',
'NOMEN' : '_ colgando en los identificadores',
'PLUSPLUS' : '++ y --',
'REGEXP' : '. y [^...] en /RegExp/',
'UNPARAM' : 'parámetros no utilizados',
'SLOPPY' : 'desaparecidos \'use strict\' pragma',
'STUPID' : 'estupidez',
'SUB' : 'subscripting ineficiente',
'TODO' : 'comentarios TODO',
'VARS' : 'muchas declaraciones var por función',
'WHITE' : 'espacio en blanco sucio',
'INDENT' : 'Margen',
'MAXLEN' : 'Longitud máxima de la línea',
'MAXERR' : 'Número máximo de errores',
/* DIRECTIVE AREA */
'DIRECTIVE_TITLE' : 'JSLint Directiva',
'HINT' : '<span style="font-weight:bold;">Nota:</span> Inserte siempre la directiva JSLint en la primera línea del documento.',
'SELECT' : 'Seleccione',
'EXTRACT' : 'Exportar a archivo',
'JSON_CONVERT' : 'Convertir a JSON',
/* DIALOG FOOTER */
'JSLINT_INFO' : 'Documentación opciones JSLint',
'DIALOG_OK' : 'Inserte directiva para documentar',
'DIALOG_CANCEL' : 'Cancelar'
});
|
BASE.require([
"app.Entity",
"app.properties.Position",
"app.properties.Size",
"app.properties.Collidable"
], function () {
BASE.namespace("app.systems");
var Entity = app.Entity;
var Position = app.properties.Position;
var Size = app.properties.Size;
var Collision = app.properties.Collidable;
var emptyFn = function () { };
app.systems.RigidBodyDrawerSystem = function (canvas, camera) {
var self = this;
this.isReady = true;
this.game = null;
this.canvas = canvas;
this.camera = camera;
this.context = canvas.getContext("2d");
this.entities = [];
var cameraPosition = this.cameraPosition = camera.getProperty("position");
};
app.systems.RigidBodyDrawerSystem.prototype.activated = function (game) {
var self = this;
this.game = game;
game.stage.filter().forEach(function (entity) {
self.entityAdded(entity);
});
};
app.systems.RigidBodyDrawerSystem.prototype.drawJoiningVector = function (entityA, entityB) {
var context = this.context;
var offset = this.cameraPosition;
var positionA = entityA.getProperty("position");
var rigidBodyA = entityA.getProperty("rigid-body");
var positionB = entityB.getProperty("position");
var rigidBodyB = entityB.getProperty("rigid-body");
context.beginPath();
context.lineWidth = 1;
context.lineCap = "round";
context.strokeStyle = '#0094ff';
context.moveTo(positionA.x - offset.x + rigidBodyA.origin.x, positionA.y + rigidBodyA.origin.y - offset.y);
context.lineTo(positionB.x - offset.x + rigidBodyB.origin.x, positionB.y + rigidBodyB.origin.y - offset.y);
context.closePath();
context.stroke();
};
app.systems.RigidBodyDrawerSystem.prototype.drawRigidBody = function (entity) {
var context = this.context;
var offset = this.cameraPosition;
var position = entity.getProperty("position");
var rigidBody = entity.getProperty("rigid-body");
context.beginPath();
context.lineWidth = 1;
context.lineCap = "round";
context.strokeStyle = '#99ff00';
rigidBody.points.forEach(function (point) {
context.lineTo(position.x - offset.x + point.x, position.y + point.y - offset.y);
});
context.lineTo(position.x - offset.x + rigidBody.points[0].x, position.y + rigidBody.points[0].y - offset.y);
context.closePath();
context.stroke();
};
app.systems.RigidBodyDrawerSystem.prototype.update = function () {
var self = this;
this.entities.forEach(function (entity) {
var collision = entity.getProperty("collidable");
var rigidBody = entity.getProperty("rigid-body");
var activeCollisions = collision.activeCollisions;
var collisions = Object.keys(activeCollisions).map(function (key) {
return activeCollisions[key];
}).filter(function (collision) {
return collision.entity.hasProperties(["rigid-body"]) && collision.endTimestamp == null;
});
if (collisions.length > 0) {
self.drawRigidBody(entity);
collisions.forEach(function (collision) {
self.drawRigidBody(collision.entity);
self.drawJoiningVector(entity, collision.entity);
});
}
});
};
app.systems.RigidBodyDrawerSystem.prototype.entityAdded = function (entity) {
if (entity.hasProperties(["collidable", "rigid-body"])) {
this.entities.push(entity);
}
};
app.systems.RigidBodyDrawerSystem.prototype.entityRemoved = function (entity) {
if (entity.hasProperties(["collidable", "rigid-body"])) {
var index = this.entities.indexOf(entity);
if (index > -1) {
this.entities.splice(index, 1);
}
}
};
app.systems.RigidBodyDrawerSystem.prototype.deactivated = function () {
};
});
|
// Do this as the first thing so that any code reading it knows the right env.
process.env.NODE_ENV = 'production';
// Load environment variables from .env file. Suppress warnings using silent
// if this file is missing. dotenv will never modify any environment variables
// that have already been set.
// https://github.com/motdotla/dotenv
require('dotenv').config({silent: true});
var chalk = require('chalk');
var fs = require('fs-extra');
var path = require('path');
var filesize = require('filesize');
var gzipSize = require('gzip-size').sync;
var webpack = require('webpack');
var config = require('../config/webpack.config.prod');
var paths = require('../config/paths');
var checkRequiredFiles = require('react-dev-utils/checkRequiredFiles');
var recursive = require('recursive-readdir');
var stripAnsi = require('strip-ansi');
// Warn and crash if required files are missing
if (!checkRequiredFiles([paths.appHtml, paths.appIndexJs])) {
process.exit(1);
}
// Input: /User/dan/app/build/static/js/main.82be8.js
// Output: /static/js/main.js
function removeFileNameHash(fileName) {
return fileName
.replace(paths.appBuildTemp, '')
.replace(/\/?(.*)(\.\w+)(\.js|\.css)/, (match, p1, p2, p3) => p1 + p3);
}
// Input: 1024, 2048
// Output: "(+1 KB)"
function getDifferenceLabel(currentSize, previousSize) {
var FIFTY_KILOBYTES = 1024 * 50;
var difference = currentSize - previousSize;
var fileSize = !Number.isNaN(difference) ? filesize(difference) : 0;
if (difference >= FIFTY_KILOBYTES) {
return chalk.red('+' + fileSize);
} else if (difference < FIFTY_KILOBYTES && difference > 0) {
return chalk.yellow('+' + fileSize);
} else if (difference < 0) {
return chalk.green(fileSize);
} else {
return '';
}
}
// First, read the current file sizes in build directory.
// This lets us display how much they changed later.
recursive(paths.appBuild, (err, fileNames) => {
var previousSizeMap = (fileNames || [])
.filter(fileName => /\.(js|css)$/.test(fileName))
.reduce((memo, fileName) => {
var contents = fs.readFileSync(fileName);
var key = removeFileNameHash(fileName);
memo[key] = gzipSize(contents);
return memo;
}, {});
// Remove all content but keep the directory so that
// if you're in it, you don't end up in Trash
fs.emptyDirSync(paths.appBuildTemp);
// Start the webpack build
build(previousSizeMap);
});
// Print a detailed summary of build files.
function printFileSizes(stats, previousSizeMap) {
var assets = stats.toJson().assets
.filter(asset => /\.(js|css)$/.test(asset.name))
.map(asset => {
var fileContents = fs.readFileSync(paths.appBuildTemp + '/' + asset.name);
var size = gzipSize(fileContents);
var previousSize = previousSizeMap[removeFileNameHash(asset.name)];
var difference = getDifferenceLabel(size, previousSize);
return {
folder: path.join('build', path.dirname(asset.name)),
name: path.basename(asset.name),
size: size,
sizeLabel: filesize(size) + (difference ? ' (' + difference + ')' : '')
};
});
assets.sort((a, b) => b.size - a.size);
var longestSizeLabelLength = Math.max.apply(null,
assets.map(a => stripAnsi(a.sizeLabel).length)
);
assets.forEach(asset => {
var sizeLabel = asset.sizeLabel;
var sizeLength = stripAnsi(sizeLabel).length;
if (sizeLength < longestSizeLabelLength) {
var rightPadding = ' '.repeat(longestSizeLabelLength - sizeLength);
sizeLabel += rightPadding;
}
console.log(
' ' + sizeLabel +
' ' + chalk.dim(asset.folder + path.sep) + chalk.cyan(asset.name)
);
});
}
// Print out errors
function printErrors(summary, errors) {
console.log(chalk.red(summary));
console.log();
errors.forEach(err => {
console.log(err.message || err);
console.log();
});
}
// Create the production build and print the deployment instructions.
function build(previousSizeMap) {
console.log('Creating an optimized production build...');
webpack(config).run((err, stats) => {
if (err) {
printErrors('Failed to compile.', [err]);
process.exit(1);
}
if (stats.compilation.errors.length) {
printErrors('Failed to compile.', stats.compilation.errors);
process.exit(1);
}
if (process.env.CI && stats.compilation.warnings.length) {
printErrors('Failed to compile.', stats.compilation.warnings);
process.exit(1);
}
console.log(chalk.green('Compiled successfully.'));
console.log();
console.log('File sizes after gzip:');
console.log();
printFileSizes(stats, previousSizeMap);
console.log();
console.log('Moving temporary build to actual build folder...');
fs.moveSync(paths.appBuildTemp, paths.appBuild, { overwrite: true });
console.log('Merging build with the public folder...');
copyPublicFolder();
});
}
function copyPublicFolder() {
fs.copySync(paths.appPublic, paths.appBuild, {
dereference: true,
filter: file => file !== paths.appHtml
});
}
|
/**
* Copyright 2016 IBM Corp. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
// error catching to prevent gulp from crashing
module.exports = function(error) {
// details of the error in console
console.log(error);
this.emit('end');
};
|
export class ProxyFactory {
static create (objeto, props, acao) {
return new Proxy(objeto, {
get (target, prop, receiver) {
if (props.includes(prop) && ProxyFactory._ehFuncao(target[prop])) {
return function () {
let retorno = Reflect.apply(target[prop], target, arguments)
acao(target)
return retorno
}
}
return Reflect.get(target, prop, receiver)
},
set (target, prop, value, receiver) {
let retorno = Reflect.set(target, prop, value, receiver)
if (props.includes(prop)) acao(target) // só executa acao(target) se for uma propriedade monitorada
return retorno
}
})
}
static _ehFuncao (func) {
return typeof (func) === typeof (Function)
}
}
|
import * as typeMapper from './typeMapper';
import { GraphQLNonNull, GraphQLEnumType } from 'graphql';
module.exports = function (Model, options) {
options = options || {};
var result = Object.keys(Model.rawAttributes).reduce(function (memo, key) {
if (options.exclude && ~options.exclude.indexOf(key)) return memo;
var attribute = Model.rawAttributes[key]
, type = attribute.type;
memo[key] = {
type: typeMapper.toGraphQL(type, Model.sequelize.constructor)
};
if ( memo[key].type instanceof GraphQLEnumType ) {
memo[key].type.name = `${Model.name}${key}EnumType`;
}
if (attribute.allowNull === false || attribute.primaryKey === true) {
memo[key].type = new GraphQLNonNull(memo[key].type);
}
return memo;
}, {});
return result;
};
|
app.controller("MainController", function($http, $location, AuthUser) {
var ctrl = this;
ctrl.loggedin = AuthUser.isLoggedin();
ctrl.logout = function(){
if(AuthUser.isLoggedin()) {
AuthUser.logout().then(function (data) {
var loggedout = !data.isSet;
if (loggedout) {
ctrl.loggedin = false;
}
});
}
};
ctrl.userInfo = {};
if (AuthUser.isLoggedin()) {
$http.get("/api/me").then(function (data) {
var rawData = data.data;
if (rawData.success) {
ctrl.userInfo.name = rawData.user.name;
ctrl.userInfo.username = rawData.user.username;
ctrl.userInfo.chat_name = rawData.user.chat_name;
console.log(angular.toJson(ctrl.userInfo));
}
});
}
});
|
Namespace('Enpowi.Test').
Class('Utilities', {
Static: {
open: function(url, callback) {
var w = window.open(url),
d;
//popup blockers
if (w !== undefined) {
d = w.document;
callback.document = d;
var interval = setInterval(function() {
if (w.app !== undefined) {
window.clearInterval(interval);
callback(w.app, w.jQuery, w, d);
}
}, 20)
}
},
crawl: function(steps) {
return function() {
var step = steps.pop();
if (step) {
step();
}
};
}
}
});
|
if ( 'undefined' === typeof window.fakerpress ){
window.fakerpress = {};
}
( function( $, _ ){
'use strict';
// Creates a Shortcut
var fp = window.fakerpress;
// Setup the Selectors
fp._module_generator = '.fp-module-generator';
fp.log = function ( $element, html, data, attrClass ){
if ( 'undefined' === typeof attrClass ){
attrClass = 'notice is-dismissible';
} else {
attrClass = 'notice is-dismissible ' + attrClass;
}
var noticeContent = _.template( html )( data ),
templateVars = {
'attrClass': attrClass,
'html': noticeContent
},
noticeHtml = _.template( '<div class="<%= attrClass %>"><p><%= html %></p><button type="button" class="notice-dismiss"></button></div>' )( templateVars ),
$notice = $( noticeHtml );
$notice.on( 'click.wp-dismiss-notice', '.notice-dismiss', function( event ) {
event.preventDefault();
$notice.fadeTo( 100 , 0, function() {
$(this).slideUp( 100, function() {
$(this).remove();
});
});
});
return $element.append( $notice );
};
fp.moduleGenerate = function ( $form, _POST ){
if ( 'undefined' === typeof _POST ){
_POST = Qs.parse( $form.serialize() );
}
// Always Hard set the Action
_POST.action = 'fakerpress.module_generate';
var $submit_container = $form.find( '.fp-submit' ),
$spinner = $submit_container.find( '.spinner' ),
$button = $submit_container.find( '.button-primary' ),
$response = $submit_container.find( '.fp-response' );
if ( $spinner.hasClass( 'is-active' ) ){
return;
}
$spinner.addClass( 'is-active' );
$button.prop( 'disabled', true );
$.ajax({
dataType: 'json',
type: 'POST',
url: window.ajaxurl,
data: _POST,
complete: function( jqXHR, status ){
if ( 'success' !== status ){
$spinner.removeClass( 'is-active' );
$button.prop( 'disabled', false );
fp.log( $response, '<%= message %>', { message: jqXHR.responseText }, 'notice-error' );
}
},
success: function( data, textStatus, jqXHR ) {
$spinner.removeClass( 'is-active' );
if ( null === data ) {
$button.prop( 'disabled', false );
fp.log( $response, '<%= message %>', { message: jqXHR.responseText }, 'notice-error' );
} else if ( data.status ){
if ( data.is_capped && data.offset < data.total ){
_POST.offset = data.offset;
_POST.total = data.total;
fp.moduleGenerate( $form, _POST );
} else {
$button.prop( 'disabled', false );
}
fp.log( $response, 'Faked <%= total %>: <%= message %>', { message: data.message, total: data.results.length }, 'notice-success' );
} else {
$button.prop( 'disabled', false );
fp.log( $response, '<%= message %>', data, 'notice-error' );
}
}
});
};
// Document Ready Actions
$( document ).ready( function(){
var $forms = $( fp._module_generator ).each( function() {
var $form = $( this );
$form.on( 'submit', function ( event ) {
fp.moduleGenerate( $form );
event.preventDefault();
return;
} );
} );
} );
}( jQuery, _ ) );
|
version https://git-lfs.github.com/spec/v1
oid sha256:8bf150f6b29d6c9337de6c945a8f63c929b203442040688878bc2753fe13e007
size 93057
|
var u = new UnityObject2(config);
jQuery(function() {
var $missingScreen = jQuery("#unityPlayer").find(".missing");
var $brokenScreen = jQuery("#unityPlayer").find(".broken");
$missingScreen.hide();
$brokenScreen.hide();
u.observeProgress(function (progress) {
switch(progress.pluginStatus) {
case "broken":
$brokenScreen.find("a").click(function (e) {
e.stopPropagation();
e.preventDefault();
u.installPlugin();
return false;
});
$brokenScreen.show();
break;
case "missing":
$missingScreen.find("a").click(function (e) {
e.stopPropagation();
e.preventDefault();
u.installPlugin();
return false;
});
$missingScreen.show();
break;
case "installed":
$missingScreen.remove();
break;
case "first":
break;
}
});
u.initPlugin(jQuery("#unityPlayer")[0], "/assets/projects/space-luddites/SpaceLuddites-Web.unity3d");
});
|
"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);
};
Object.defineProperty(exports, "__esModule", { value: true });
var core_1 = require("@angular/core");
var BannerComponent = (function () {
function BannerComponent() {
this.title = 'The joy of test';
}
;
return BannerComponent;
}());
BannerComponent = __decorate([
core_1.Component({
selector: 'banner-comp',
templateUrl: './banner.component.html',
styleUrls: [
'./banner.component.css'
]
}),
__metadata("design:paramtypes", [])
], BannerComponent);
exports.BannerComponent = BannerComponent;
//# sourceMappingURL=banner.component.js.map
|
import { Path } from 'slate'
export const input = {
path: [0, 1, 2],
another: [0, 1, 2],
}
export const test = ({ path, another }) => {
return Path.endsAfter(path, another)
}
export const output = false
|
class CanvasSequence {
constructor(canvas, sequencePath, sequenceStart, sequenceEnd, fileType, loadCallback) {
this.sequence = [];
this.canvas = document.getElementById(canvas);
if(this.canvas !== null) {
this.context = this.canvas.getContext('2d');
} else {
console.log("Please ensure the lib is loaded when DOM is loaded.")
}
this.canvas.width = window.innerWidth;
this.canvas.height = window.innerHeight;
this.sequencePath = sequencePath;
this.sequenceStart = sequenceStart;
this.sequenceEnd = sequenceEnd;
this.sequenceLength = this.sequenceEnd - this.sequenceStart;
this.fileType = fileType || '.png';
this.scrollHeight = document.body.scrollHeight;
this.scrollOffset = document.body.scrollTop;
this.clientHeight = window.innerHeight;
this.loadCallback = loadCallback || function() {};
this.loadSequence();
}
addLeadingZeros(n) {
var length = this.sequenceEnd.toString().length;
var str = (n > 0 ? n : -n) + "";
var zeros = "";
for (var i = length - str.length; i > 0; i--)
zeros += "0";
zeros += str;
return n >= 0 ? zeros : "-" + zeros;
}
loadSequence() {
var promises = [];
for(var i = this.sequenceStart; i <= this.sequenceEnd; i++) {
var frameNumber = this.addLeadingZeros(i);
var filename = this.sequencePath + frameNumber + this.fileType;
var img = new Image;
img.src = filename;
var promise = new Promise(function(resolve, reject) {
img.onload = resolve;
img.onerror = reject;
});
promises.push(promise);
this.sequence.push(img);
}
Promise.all(promises).then(() => {
this.renderFrame();
this.loadCallback();
}).catch((e) => {
console.log(e);
});
}
getNextFrameNumber() {
var scrollPercentage = (this.scrollOffset/(this.scrollHeight-this.clientHeight))*100;
var currentFrameNumber = Math.round(scrollPercentage*this.sequenceLength/100);
return currentFrameNumber;
}
syncScrollPosition() {
this.scrollOffset = document.body.scrollTop;
}
drawImage(frame) {
if(frame >= 0 && frame < this.sequence.length) {
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
if(this.sequence[frame].complete) {
this.context.drawImage(this.sequence[frame], 0, 0, this.canvas.width, this.canvas.height);
} else {
console.log("The current frame has not been loaded. Please ensure all images are loaded before updating the canvas.")
}
}
}
renderFrame() {
this.syncScrollPosition();
requestAnimationFrame(() => {
this.renderFrame();
});
this.previousFrame = this.currentFrame;
this.currentFrame = this.getNextFrameNumber();
if( (this.currentFrame != this.previousFrame) || this.firstLoad) {
this.drawImage(this.currentFrame);
}
this.firstLoad = false;
}
}
if (!window.requestAnimationFrame) {
window.requestAnimationFrame = (function() {
return window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame || // comment out if FF4 is slow (it caps framerate at ~30fps: https://bugzilla.mozilla.org/show_bug.cgi?id=630127)
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function( /* function FrameRequestCallback */ callback, /* DOMElement Element */ element) {
window.setTimeout(callback, 1000 / 60);
};
})();
}
if (typeof define === 'function' && define.amd) {
define('CanvasSequence', CanvasSequence);
} else if (typeof module !== 'undefined' && module.exports) {
module.exports = CanvasSequence;
} else {
window.CanvasSequence = CanvasSequence;
}
|
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import Style from 'style-it';
class Button extends Component {
render() {
return Style.it(`
.container {
text-align: center;
}
.button {
background-color: #ff0000;
width: 320px;
padding: 20px;
border-radius: 5px;
border: none;
outline: none;
}
.button:hover {
color: #fff;
}
.button:active {
position: relative;
top: 2px;
}
@media (max-width: 480px) {
.button {
width: 160px;
}
}
`,
<div className="container">
<button className="button">Click me!</button>
</div>
);
}
}
ReactDOM.render(<Button />, document.getElementById('content'));
|
'use strict';
/**
* Module dependencies.
*/
var express = require('express');
var cookieParser = require('cookie-parser');
var compress = require('compression');
var session = require('express-session');
var bodyParser = require('body-parser');
var logger = require('morgan');
var errorHandler = require('errorhandler');
var csrf = require('lusca').csrf();
var methodOverride = require('method-override');
var _ = require('lodash');
var MongoStore = require('connect-mongo')({
session: session
});
var flash = require('express-flash');
var path = require('path');
var mongoose = require('mongoose');
var passport = require('passport');
var expressValidator = require('express-validator');
var connectAssets = require('connect-assets');
var hbs = require('hbs');
var glob = require('glob');
var fs = require('fs');
/**
* Handlebars helpers
*/
var helpers = require('./app/lib/helpers.js');
/**
* API keys and Passport configuration.
*/
var dotenv = require('dotenv');
dotenv.load();
var secrets = require('./app/config/secrets');
var passportConf = require('./app/config/passport');
/**
* Create Express server.
*/
var app = express();
/**
* Connect to MongoDB.
*/
mongoose.connect(secrets.db);
mongoose.connection.on('error', function() {
console.error('MongoDB Connection Error. Make sure MongoDB is running.');
});
var hour = 3600000;
var day = hour * 24;
var week = day * 7;
/**
* CSRF whitelist.
*/
var csrfExclude = ['/url1', '/url2'];
/**
* Express configuration.
*/
app.set('port', process.env.PORT || 8080);
app.set('views', path.join(__dirname, '/app/views'));
app.set('view engine', 'hbs');
/**
* Dev settings
*/
if (process.env.NODE_ENV === 'dev') {
/**
* Get Local IP for browserify
*/
var os = require('os');
var ifaces = os.networkInterfaces();
var localIpAddress = null;
for (var dev in ifaces) {
if (dev !== "en1" && dev !== "en0") {
continue;
}
ifaces[dev].forEach(function(details) {
if (details.family === 'IPv4') {
localIpAddress = details.address;
}
});
}
var dev = {
livereload: process.env.livereload ? process.env.livereload : true,
browsersync: process.env.browsersync ? process.env.browsersync : true,
localIpAddress: localIpAddress
};
}
app.use(compress());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(expressValidator());
app.use(methodOverride());
app.use(cookieParser());
app.use(session({
resave: true,
saveUninitialized: true,
secret: secrets.sessionSecret,
store: new MongoStore({
mongooseConnection: mongoose.connection
})
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use(function(req, res, next) {
// CSRF protection.
if (_.contains(csrfExclude, req.path)) {
return next();
}
csrf(req, res, next);
});
app.use(function(req, res, next) {
// Make user object available in templates.
res.locals.user = req.user;
res.locals.dev = dev;
next();
});
app.use(function(req, res, next) {
// Remember original destination before login.
var path = req.path.split('/')[1];
if (/auth|login|logout|signup|img|fonts|favicon/i.test(path)) {
return next();
}
req.session.returnTo = req.path;
next();
});
app.use(express.static(path.join(__dirname, 'app/public'), {
maxAge: week
}));
/**
* Routes.
*/
require('./app/config/routes')(app, passport, passportConf);
/**
* 500 Error Handler.
*/
app.use(errorHandler());
/**
* Find all the patterns in our patterns directory and register with Handlebars
*/
var files = glob.sync("./app/patterns/**/*.hbs"),
partials = {};
files.forEach(function(filename) {
var name = filename.match(/[^\/]+[.+\.].*$/, '');
name = name[0].replace(/\.hbs$/, '');
//console.log('Registering: '+name);
hbs.registerPartial(name, fs.readFileSync(filename, 'utf8'));
});
/**
* Register Handlebars helpers
*/
helpers.register();
/**
* Start Express server.
*/
app.listen(app.get('port'), function() {
console.log('Express server listening on port %d in %s mode', app.get('port'), app.get('env'));
//process.send('online');
});
process.on('message', function(message) {
if (message === 'shutdown') {
process.exit(0);
}
});
module.exports = app;
|
/**
* @author Aravind Buddha
* @desc To set a video background to the application
*
*
*/
(function ( define ){
"use strict";
define([],function(){
var videoBgDirective=function(){
return {
templateUrl: './js/app/modules/app/views/partials/video-bg.html',
compile: function(scope,element,attrs){
return {
post:function(){
// $(".player").mb_YTPlayer();
}
}
}
};
};
return videoBgDirective;
});
}(define));
|
/**
* Created by ben on 01/02/16.
*/
angular.module('graph')
.factory('preloader', ['$q', '$http', function($q, $http) {
preloaderFunctions = {};
preloaderFunctions.getGraph = function (graphId) {
return $http.get('/api/graphs/' + graphId).then(function (response) {
return response.data;
}, function (error) {
if (error.status == 404) {
console.log("requested graph does not exist, creating a new one");
var newGraph = {
id: graphId,
name: "My New Graph",
specification: {
properties: {},
processes: {},
connections: []
}
};
return $http.put('/api/graphs/' + graphId, newGraph).then(function (response) {
console.log("created new graph with id " + graphId);
return response.data;
}, function (error) {
console.log("could not create a new graph with id " + graphId + " because " + error.statusText);
console.log(error);
return undefined;
});
}
});
};
preloaderFunctions.getProcessConfig = function () {
return $http.get('/api/library/processes').then(function (response) {
return response.data;
});
};
preloaderFunctions.getGraphConfig = function () {
return $http.get('/api/library/graphs').then(function (response) {
return response.data;
});
};
preloaderFunctions.loadData = function (path) {
return $q.all([
preloaderFunctions.getGraph(path.params.graphId),
preloaderFunctions.getProcessConfig(),
preloaderFunctions.getGraphConfig()
]).then(function (results) {
return {
graph: results[0],
processConfig: results[1],
graphConfig: results[2]
};
});
};
return preloaderFunctions;
}]);
|
/*
* Basic Weighted Graph Algorithms
*/
(function(exports) {
'use strict';
/*
* MinSpanningTree: Wrapper object containing the Minimum Spanning Tree (MST)
* results for a graph: predecessor array and edge weights array.
*
* @constructor
* @param {Array} pred, the predecessor array of vertices
* @param {Array} key, the final array of edge weights keyed by vertex logical id
*/
exports.MinSpanningTree = function(pred, key) {
this.predecessors = pred;
this.weights = key;
};
/*
* weightedMST: Finds the Minimum Spanning Tree for a weighted graph.
*
* Amazon link to "Algorithms in a Nutshell", an O'Reilly book
* http://www.amazon.com/Algorithms-Nutshell-In-OReilly/dp/059651624X/ref=tmm_pap_title_0?ie=UTF8&qid=1428939214&sr=1-1
*
* YouTube video with example of algorithm used:
* https://www.youtube.com/watch?v=z1L3rMzG1_A
*
* @param {Array} pred, the predecessor array of vertices
* @param {Array} key, the final array of edge weights keyed by vertex logical id
* @return {MinSpanningTree} a wrapper object around the predecessor and edge weight arrays
*/
exports.weightedMST = function(graph, startVertexIndex) {
validate(graph, startVertexIndex);
var key = [];
var pred = [];
var queue = [];
for (var i = 0; i < graph.getNumberVertices(); i++) {
key[i] = Number.POSITIVE_INFINITY;
pred[i] = -1;
queue.push(i);
}
key[startVertexIndex] = 0;
while (queue.length > 0) {
var u = getMin(queue, key);
var adjList = graph.getAdjList(u);
var v = -1;
var w = -1;
for (i = 0; i < adjList.length; i++) {
v = adjList[i].to;
if (queue.indexOf(v) > -1) {
w = adjList[i].weight;
if (w < key[v]) {
pred[v] = u;
key[v] = w;
}
}
}
}
var mst = new exports.MinSpanningTree(pred, key);
return mst;
};
/*
* Find and remove the vertex having the minimum key (edge weight) value
* in the vertex queue
*
* WARNING: as-is, the search for min is O(n) where n = number elements
* in the queue.
*
* TODO: replace simple array queue with a heap-based one
*
* @param {Array} queue, a queue have vertices eligible for MST inclusion
* @param {Array} key, an array of edge weights indexed by vertix logical id
* @return {Number}: the vertix with the minimum key (edge weight)
*/
function getMin(queue, key) {
var minIdx = 0;
var u = queue[minIdx];
var min = key[u];
for (var i = 1; i < queue.length; i++) {
if (key[queue[i]] < min) {
min = key[queue[i]];
minIdx = i;
}
}
u = queue.splice(minIdx, 1)[0];
return u;
}
function validate(graph, startVertexIndex) {
if (startVertexIndex === undefined || startVertexIndex < 0) {
throw Error('Graph Search Error: start vertex index < 0 or undefined');
} else if (graph.getNumberVertices() <= 0) {
throw Error('Graph Search Error: Graph has no vertices');
}
}
})(typeof window === 'undefined' ? module.exports : window);
|
'use strict';
describe('Service: weatherService', function () {
// load the service's module
beforeEach(module('wavesApp'));
// instantiate service
var weatherService;
beforeEach(inject(function (_weatherService_) {
weatherService = _weatherService_;
}));
it('should do something', function () {
expect(!!weatherService).toBe(true);
});
});
|
define(['tag-parser'], function(tagParser) {
return function() {
var body = document.body;
body.appendChild(document.createComment('PoleTemplateTag name="a" action="1" /EndTag'));
body.appendChild(document.createComment(' PoleTemplateTag name="b" action="1" /EndTag '));
body.appendChild(document.createComment(' PoleTemplateTag name="c" action="1" /EndTag'));
body.appendChild(document.createComment(' PoleTemplateTag name="d" action="" /'));
body.appendChild(document.createComment(' PoleTemplateTag name="e" action=""'));
body.appendChild(document.createComment('name="f" action="1" /EndTag'));
body.appendChild(document.createComment('name="g" action="1" '));
body.appendChild(document.createComment('PoleTemplateTag name="h" /EndTag'));
body.appendChild(document.createComment('PoleFragmentTag name="i" /EndTag'));
body.appendChild(document.createComment('PoleFragmentTag /EndTag'));
module('Test TagParser');
test('parseParams', function() {
deepEqual(tagParser.parseParams('name="a" action="xxx"'), { name: 'a', action: 'xxx' }, '');
deepEqual(tagParser.parseParams(' name="a" action="xxx"'), { name: 'a', action: 'xxx' }, '');
deepEqual(tagParser.parseParams(' name="a" action '), { name: 'a' }, '');
deepEqual(tagParser.parseParams(' name="a" action='), { name: 'a' }, '');
deepEqual(tagParser.parseParams('name="a" action="" '), { name: 'a', action: '' }, '');
});
test('getChildTags', function() {
equal(tagParser.getChildTags('template', document.documentElement).length, 5, '解析PoleTemplateTag数量');
equal(tagParser.getChildTags('fragment', document.documentElement).length, 2, '解析PoleFragmentTag数量');
});
};
});
|
if (typeof exports === 'object') {
var assert = require('assert');
var alasql = require('..');
} else {
__dirname = '.';
}
describe('Test 350 SERIAL data type', function () {
it('1. CREATE DATABASE', function (done) {
alasql('CREATE DATABASE test350;USE test350');
done();
});
it('2. CREATE TABLE', function (done) {
var res = alasql('CREATE TABLE one (id SERIAL, name STRING)');
assert.deepEqual(res, 1);
done();
});
it('3. INSERT', function (done) {
var res = alasql('INSERT INTO one (name) VALUES ("One"), ("Two"), ("Three")');
assert.deepEqual(res, 3);
done();
});
it('4. SELECT', function (done) {
var res = alasql('SELECT * FROM one');
assert.deepEqual(res, [
{id: 1, name: 'One'},
{id: 2, name: 'Two'},
{id: 3, name: 'Three'},
]);
done();
});
it('99. DROP DATABASE', function (done) {
alasql.options.modifier = undefined;
alasql('DROP DATABASE test350');
done();
});
});
|
import { MF } from '../Form';
MF('.mf-input-field,.mf-textarea-field').input();
MF('.mf-select-field').dropdown();
|
/**
* React Static Boilerplate
* https://github.com/kriasoft/react-static-boilerplate
*
* Copyright © 2015-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React, {PropTypes} from 'react';
import s from './styles.css';
import {title, html} from './index.md';
import axios from 'axios';
/*----------------------------------------------------------------
IMPORTED COMPONENTS
---------------------------------------------------------------*/
import GiphyFrame from '../../components/onederful-ui/giphy/giphy-frame'
import WatsonVisualRecognition from '../../components/onederful-ui/watson-visual-recognition/watson-tags'
/*-------------------------------------------------
This function doesn't change
It makes a RESTful call to onederful and returns a promise
-------------------------------------------------*/
function callOnederful(query) {
const ONEDERFUL_API = 'https://api.onederful.co/graphql';
const OPEN_BETA_KEY = 'DsvIiZ1oBO9OwjU0Kn1sAukaVNwpRjT29zWV6T53';
const axiosInstance = axios.create({headers: {'x-api-key': OPEN_BETA_KEY}});
return axiosInstance.post(ONEDERFUL_API, {query})
}
class ExamplePage extends React.Component {
constructor(props) {
super(props);
this.state = {
q: 'bears',
limit: 3,
giphyList: []
}
}
componentDidMount() {
document.title = title;
}
getGiphyWatson() {
const {q, limit} = this.state;
const query =
`
query GIPHY {
giphy_search_api
#This is where you change inputs
(
q: "${q}",
limit: "${limit}"
)
#Below is the exact json shape of the response
{
data {
embed_url
rating
bitly_url
bitly_gif_url
images {
downsized_still {
url
}
stillImage {
url
}
}
watsonVisualRecognition {
images {
classifiers {
classes {
class
score
}
}
}
}
}
}
}
`;
/*-------------------------------------------------
Example Call:
-------------------------------------------------*/
callOnederful(query)
.then(({data})=> {
console.log(data)
this.setState({giphyList: data.data.giphy_search_api.data})
})
.catch(e=>console.log('handle error', e))
}
render() {
return (
<div className={s.container}>
<input value={this.state.q} onChange={(e)=>{this.setState({q:e.target.value})}}/>
<button onClick={()=>{this.getGiphyWatson()}}>Get Giphy's that have watson in it</button>
{this.state.giphyList.map(giphy=> {
return (
<div className = {s.content}>
<GiphyFrame {...giphy}/>
<WatsonVisualRecognition {...giphy.watsonVisualRecognition}/>
</div>
)
})}
</div>
);
}
}
export default ExamplePage;
|
module.exports = {
message: `Invalid database expression. Should look like: myDb.todos = myDb.todos.filter(todo => !(todo.key === "Task"))`
};
|
//Array of our earthquakes, actually we just use this to center our map over the earthquake
var quakes = [
["PAK-ASC", "up2013ueba", "2013-10-15 00:12:35", 9.786595, 124.075],
["PAK", "up2013ssol", "2013-09-24 11:29:48", 26.9424, 65.4466],
["PAKISTAN", "up2013ueba", "2013-10-15 00:12:35", 9.786595, 124.075],
["SEA-OF-OKHOTSK", "up2013kbnw", "2013-05-24 05:44:45", 54.893, 153.136],
["SOUTH-IRAN-2", "up2013hknw", "2013-04-16 10:44:11", 27.9611, 62.0207],
["SOUTH-OF-FIJI-ISLANDS", "up2013kapj", "2013-05-23 17:19:03", -23.0366, -177.259]
];
//which quake frome the array above do we want to show
var quake_id = 1;
//global animation state
var animated = false;
//counter for frame loading
var time = 0;
//counter for frame playback
var atime = 0;
//global variable for our map, the layer holding the visualization and the load request
var map, layer, request;
//global container holding the data for our animation
var frames = [];
//variables required for calculation the estimated time for loading all frames
var timestamp;
var avrg_speed = 0;
var avrg_size = 0;
var d = new Date();
var start = d.getTime();
//number of frames the system should load before allowing the auto play feature
var min_frame_load = 10;
//number of frames of the animation
var max_frame_load = 139;
//the miliseconds between each visualizations step/frame
var animation_speed = 100;
//The maximum spread of our coordinate system, required for calculations
var max = 20037508;
var myPlaybar;
var data_size = 0;
var interval;
var global_data;
var loadInit = false;
var maxSets = 0;
$(document).ready(function() {
map = L.map('map', { worldCopyJump: true }).setView([quakes[quake_id][3], quakes[quake_id][4]], 6);
L.tileLayer('http://a.tiles.mapbox.com/v3/juli84.gdc638hh/{z}/{x}/{y}.png').addTo(map);
layer = L.layerGroup();
layer.addTo(map);
Proj4js.defs["SR-ORG:7483"] = "+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +wktext +no_defs";
//Initiate Playbar
myPlaybar = playbar({repeat:true,x_name:'time',y_name:'value',x_type:'linear'});
//Add listeners to the change event - call for every change of the playhead position
myPlaybar.on("change", function(status){
if(status < frames.length){
layer.clearLayers();
for(var i = 0; i<frames[status].length; i++){
//Here we loop through the layers and add them to the map
if(frames[status][i].geometry.coordinates[0].length >= 1){
geo = L.Proj.geoJson(frames[status][i], { style: function(feature){ return feature.properties && feature.properties.style; }}).on('dblclick', function(event){map.panTo(event.latlng);map.zoomIn();});
geo.addTo(layer);
}
}
}
});
//Add listeners to the status event - call for every change on loading/playing/pause
myPlaybar.on("status", function(status){
if(status=="loading" && !loadInit){
loadInit = true;
setHeatmap();
}else{
//animated=true;
//animate();
//console.log(status);
}
});
//Apply playbar to an svg-container
d3.select('#playbar').append("svg").call(myPlaybar);
d3.csv("../provider/meta.php?ref_id="+quake_id, function(error, data) {
if(error){
//In case of Data-Error -> Abort!
console.log(error);
}else{
//Load Data and send it to the playbar, to generate the preview graph
maxSets = data.length;
myPlaybar.data(data);
}
});
});
/*
optimizeCoords([longitude, latitude]){
Due to leaflet using a continous world,
which makes the tiles contine on the right
and left end of the map, we sometimes
receive longitude and latitude values
that are "off the grid". As most GIS
function will throw an error for "off
the grid" numbers we need to make sure
the numbers are converted to save
coordinates.
}
*/
function optimizeCoords(coordArray){
//Longitude Correction
if(coordArray[0]<-180){
coordArray[0]=360+coordArray[0];
}else if(coordArray[0]>180){
coordArray[0]=(-360+coordArray[0]);
}
//Latitude Correction
if(coordArray[1]<-90){
coordArray[1]=180+coordArray[1];
}else if(coordArray[1]>90){
coordArray[1]=(-180+coordArray[1]);
}
return coordArray;
}
/*
setHeatmap(){
Due to leaflet using a continous world,
which makes the tiles contine on the right
and left end of the map, we sometimes
receive longitude and latitude values
that are "off the grid". As most GIS
function will throw an error for "off
the grid" numbers we need to make sure
the numbers are converted to save
coordinates.
}
*/
function setHeatmap(){
//Get the boundaries of the current map. We will use this square for our query to the database.
var bounds = map.getBounds();
//The boundaries are converted to our coordinate system
var neA = optimizeCoords([bounds.getNorthEast().lng, bounds.getNorthEast().lat]);
var ne = ToWebMercator(neA[0], neA[1]);
var swA = optimizeCoords([bounds.getSouthWest().lng, bounds.getSouthWest().lat]);
var sw = ToWebMercator(swA[0], swA[1]);
//For faster queries we using a positive only coordinate system
ne[0]+=20037508;
ne[1]+=20037508;
sw[0]+=20037508;
sw[1]+=20037508;
//Just for readability we store the variables in x/y min/max variables
min_x = sw[0];
max_x = ne[0];
min_y = sw[1];
max_y = ne[1];
//based on the dataset you want to visualize, the zoom level and the boundaries we will request a heatmap
var trequest = "../provider/deliver.php?zoom="+map.getZoom()+"&min_y="+min_y+"&max_y="+max_y+"&min_x="+min_x+"&max_x="+max_x+"&vis=square&vis_type=value_max&time=all&ref_id="+(quake_id+1);
var eventSource = new EventSource(trequest);
eventSource.onmessage = function(event){
myPlaybar.loading(event.lastEventId, event.data.length);
frames.push(jQuery.parseJSON(event.data));
if(event.lastEventId>=maxSets-1){
console.log("done");
eventSource.close();
}
};
}
/*
function animate(){
as soon as enough frames are loaded the user can "play" the visualization
}
*/
|
tripExchange.factory('notifier', ['toastr', function (toastr) {
return {
success: function(msg) {
toastr.success(msg);
},
error: function(msg) {
toastr.error(msg);
}
}
}])
|
import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
moduleForComponent('table-pagination', 'Integration | Component | table pagination', {
integration: true
});
test('it renders', function(assert) {
// Set any properties with this.set('myProperty', 'value');
// Handle any actions with this.on('myAction', function(val) { ... });"
this.render(hbs`{{table-pagination}}`);
assert.equal(this.$().text().trim(), '');
// Template block usage:"
this.render(hbs`
{{#table-pagination}}
template block text
{{/table-pagination}}
`);
assert.equal(this.$().text().trim(), 'template block text');
});
|
import React, { Component, PropTypes } from 'react';
// import Navigation from './../ComposedComponent/Navigation/Navigation'
// import BaseButton from './../BaseComponent/BaseButton/BaseButton'
import withStyles from 'isomorphic-style-loader/lib/withStyles'
import s from './Carousel.css'
import { observer } from 'mobx-react'
import { observable, computed } from 'mobx'
import cx from 'classnames'
@observer
class Carousel extends Component {
static propTypes = {
children: PropTypes.oneOfType(
[
PropTypes.element,
PropTypes.array,
]).isRequired,
};
componentDidMount() {
this.contentDimension.width = this.refs.content0.getBoundingClientRect().width
this.contentDimension.height = this.refs.content0.getBoundingClientRect().height
this.startPlay();
}
componentWillUnmount() {
this.destroyTimer()
}
@observable currentIndex = 0;
@observable contentDimension = { width: 0, height: 0 }
@computed get leftValue() {
// 400 is the width of the visible area
return (-this.currentIndex * this.contentDimension.width)
}
cloneWithState(element, index) {
return React.cloneElement(
element,
{ key: index, ref: `content${index}`, style: { float: 'left' } }
);
}
startPlay() {
this.handler = setInterval(() => {
if (this.currentIndex >= (React.Children.count(this.props.children) - 1)) {
this.currentIndex = 0
} else {
this.currentIndex++
}
}, 3000)
}
destroyTimer() {
window.clearInterval(this.handler)
}
changeImage(index) {
this.currentIndex = index;
this.destroyTimer();
this.startPlay()
}
dotRender() {
return React.Children.map(this.props.children,
(item, index) => (
<li
key={index}
onClick={() => this.changeIndex(index) }
className={index === this.currentIndex ? cx(s.dot, s.active) : s.dot}>
</li>
))
}
contentRender() {
return this.props.children && React.Children.map(this.props.children, this.cloneWithState);
}
render() {
const { children } = this.props
return (
<div
style={{ width: this.contentDimension.width, height: this.contentDimension.height }}
className={s.wrapper}>
<div
style={{
width: this.contentDimension.width * React.Children.count(children),
height: this.contentDimension.height, marginLeft: this.leftValue,
}}
className={s.content}>
{this.contentRender() }
</div>
<div className={s.dotSection}>
{this.dotRender() }
</div>
</div >
)
}
}
export default withStyles(s)(Carousel)
|
"use strict";
angular.module("ehelseEditor").factory("DocumentType", ["$rootScope", "StorageHandler", function($rootScope, StorageHandler) {
var document_types = [];
var document_types_dict = {};
var document_types_option_list = [];
init();
function init(){
try{
Array.prototype.push.apply(document_types, StorageHandler.getDocumentTypes().documentTypes);
Array.prototype.push.apply(document_types_option_list, generateDocumentTypesOptionList(document_types));
generateDocumentTypeDict(document_types);
}
catch(error){
console.log("Document types could not be loaded: " + error);
$rootScope.notifyError("Dokumenttyper kunne ikke lastes: " + error, 6000);
}
}
/**
* Function used to clear document type lists and dicts.
*/
function clear(){
document_types.length = 0;
document_types_dict = {};
document_types_option_list.length = 0;
}
/**
* Function that generates DocumentType dict
*
* The document ype dict is used were only the id is available.
* @param document_types
*/
function generateDocumentTypeDict(document_types){
for(var i = 0; i < document_types.length; i++){
document_types_dict[document_types[i].id] = document_types[i];
}
}
/**
* Function generating document types option list.
*
* Used to generate option lists in the view.
* @param document_types
* @returns Document type options list
*/
function generateDocumentTypesOptionList(document_types){
var tuples = [];
for (var i = 0; i < document_types.length; i++) {
var document_type = document_types[i];
tuples.push({
value: document_type.id,
name: document_type.name
})
}
return tuples;
}
function getAll(){
return document_types;
}
function getById(id){
return document_types_dict[id];
}
function getDocumentTypesOptionList(){
return document_types_option_list;
}
return {
getById: getById,
getDocumentTypesOptionList: getDocumentTypesOptionList,
clear: clear,
init: init,
getAll: getAll,
document_types: document_types,
document_types_dict: document_types_dict,
document_types_option_list: document_types_option_list
};
}]);
|
import bcrypt from "bcrypt";
module.exports = (sequelize, DataType) => {
const Users = sequelize.define("Users", {
id: {
type: DataType.INTEGER,
primaryKey: true,
autoIncrement: true
},
first: {
type: DataType.STRING,
allowNull: false,
validate: {
notEmpty: true
}
},
last: {
type: DataType.STRING,
allowNull: false,
validate: {
notEmpty: true
}
},
password: {
type: DataType.STRING,
allowNull: false,
validate: {
notEmpty: true
}
},
email: {
type: DataType.STRING,
unique: true,
allowNull: false,
validate: {
notEmpty: true
}
}
}, {
hooks: {
beforeCreate: user => {
const salt = bcrypt.genSaltSync();
user.password = bcrypt.hashSync(user.password, salt);
}
},
classMethods: {
associate: models => {
Users.hasMany(models.Clients);
},
isPassword: (encodedPassword, password) => {
return bcrypt.compareSync(password, encodedPassword);
}
}
});
return Users;
};
|
"use strict";
define(function(require) {
var SearchView = require('views/searches/search'),
Templates = require('templates'),
Util = require('util');
require('views/searches/syntax/ecl');
/**
* Elasticsearch search View.
*/
var ECLSearchView = SearchView.SearchView.extend({
__render: function() {
Util.initCodeMirror(this.registerElement('[name=query]'), {'mode': 'ecl'});
}
});
return ECLSearchView;
});
|
/* globals window */
define(function() {
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
window.clearTimeout(timeout);
timeout = window.setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
}
return debounce;
});
|
var Server = require('http-route-proxy');
Server.proxy([
{
from: 'localhost:3001',
to: 'github.io',
route: ['!/']
}
]);
|
// ItemTypesStore.js
'use strict';
var AuthoringConstants = require('../constants/AuthoringConstants');
var EventEmitter = require('events').EventEmitter;
var MiddlewareService = require('../services/middleware.service.js');
var _ = require('lodash');
var ActionTypes = AuthoringConstants.ActionTypes;
var CHANGE_EVENT = ActionTypes.CHANGE_EVENT;
var _itemTypes = [];
var ItemTypesStore = _.assign({}, EventEmitter.prototype, {
emitChange: function () {
this.emit(CHANGE_EVENT, _itemTypes);
},
addChangeListener: function (callback) {
this.on(CHANGE_EVENT, callback);
},
removeChangeListener: function (callback) {
this.removeListener(CHANGE_EVENT, callback);
},
getSupportedItemTypes: function (libraryId) {
var url = this.url() + libraryId + '/items/types',
_this = this;
fetch(url, {
cache: "no-store",
credentials: "same-origin"
}).then(function (response) {
if (response.ok) {
response.json().then(function (data) {
_itemTypes = data;
_this.emitChange();
});
} else {
response.text().then(function (data) {
alert(response.statusText + ': ' + data);
});
}
}).catch(function (error) {
console.log('Problem with getting item types: ' + error.message);
});
},
url: function () {
if (MiddlewareService.shouldReturnStatic()) return '/raw_data/libraries.json';
return MiddlewareService.host() + '/assessment/libraries/';
}
});
module.exports = ItemTypesStore;
|
import { WINDOW, JSCRIPT_VERSION } from "../const";
import { $Document, $Element, $NullElement } from "../types";
var arrayProto = Array.prototype;
export const every = arrayProto.every;
export const each = arrayProto.forEach;
export const filter = arrayProto.filter;
export const map = arrayProto.map;
export const slice = arrayProto.slice;
export const isArray = Array.isArray;
export const keys = Object.keys;
export function computeStyle(node) {
/* istanbul ignore if */
if (JSCRIPT_VERSION < 9) {
return node.currentStyle;
} else {
return node.ownerDocument.defaultView.getComputedStyle(node);
}
}
export function injectElement(node) {
if (node && node.nodeType === 1) {
return node.ownerDocument.getElementsByTagName("head")[0].appendChild(node);
}
}
export function safeCall(context, fn, arg1, arg2) {
if (typeof fn === "string") fn = context[fn];
try {
return fn.call(context, arg1, arg2);
} catch (err) {
/* istanbul ignore next */
WINDOW.setTimeout(() => { throw err }, 1);
return false;
}
}
export function register(mixins, factory, defaultFactory) {
var proto = defaultFactory ? $Element.prototype : $Document.prototype;
if (factory == null) {
factory = (methodName, strategy) => strategy;
}
keys(mixins).forEach((methodName) => {
var args = [methodName].concat(mixins[methodName]);
proto[methodName] = factory.apply(null, args);
if (defaultFactory) {
$NullElement.prototype[methodName] = defaultFactory.apply(null, args);
}
});
}
|
import React from 'react';
import classnames from 'classnames';
import PropTypes from 'prop-types';
export class ListItem extends React.PureComponent {
render() {
return <li {...this.props}/>;
}
}
const defList = (tagName, classNames, childClassNames) => {
return class extends React.Component {
static propTypes = {
className: PropTypes.string,
unstyled: PropTypes.bool,
divider: PropTypes.bool
};
componentDidMount() {
require('../../css/lists');
}
render() {
let {className, children, unstyled, divider, ...others} = this.props;
const classes = classnames(classNames(this.props), className);
if(childClassNames) {
children = React.Children.map(children, child => React.cloneElement(child, {className: childClassNames}));
}
return tagName === 'ul' ? <ul className={classes} {...others}>{children}</ul>
: tagName === 'ol' ? <ol className={classes} {...others}>{children}</ol>
: null;
}
};
};
export const UnorderedList = defList('ul', ({unstyled, divider}) => classnames({'list-unordered': !unstyled, 'list-unstyled': unstyled, 'list-divider': divider}));
export const OrderedList = defList('ol', ({unstyled, divider}) => classnames({'list-unstyled': unstyled, 'list-divider': divider}));
export const InlineList = defList('ul', ({divider}) => classnames('list-inline', {'list-inline-divider': divider}));
export const BreadcrumbList = defList('ul', () => classnames('list-breadcrumb'));
|
var fs = require('fs');
var path = require('path');
var split = require('split');
var countries = module.exports = {
raw:function(){
return require('./countries.json');
},
stream:function(){
return countries
.filestream()
.pipe(split(function(line){
if(line.charAt(0)=='['){
line = line.replace(/^\[/, '');
}
if(line.charAt(line.length-1)==']'){
line = line.replace(/\]$/, '');
}
line = line.replace(/,$/, '');
if(line){
return JSON.parse(line);
}
}))
},
filepath:function(){
return path.normalize(__dirname + '/countries.json');
},
filestream:function(){
return fs.createReadStream(countries.filepath(), 'utf8');
}
}
|
'use strict';
angular
.module( 'app.controller.share', [
'ngMaterial',
'ngMessages'
] )
// constants
.constant('MODULE_VERSION', '0.0.1')
// // // // // // // // // // // // // // // // // // // // // // // // //
// Share
.controller('ShareController', function($scope, $log) {
$scope.currentPage = 'Share';
$log.debug("ShareController");
});
|
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
/* eslint-disable global-require */
// The top-level (parent) route
const routes = {
path: '/',
// Keep in mind, routes are evaluated in order
children: [
{
path: '/',
load: () => import(/* webpackChunkName: 'home' */ './home'),
},
{
path: '/contact',
load: () => import(/* webpackChunkName: 'contact' */ './contact'),
},
{
path: '/login',
load: () => import(/* webpackChunkName: 'login' */ './login'),
},
{
path: '/register',
load: () => import(/* webpackChunkName: 'register' */ './register'),
},
{
path: '/about',
load: () => import(/* webpackChunkName: 'about' */ './about'),
},
{
path: '/privacy',
load: () => import(/* webpackChunkName: 'privacy' */ './privacy'),
},
{
path: '/import',
load: () => import(/* webpackChunkName: 'import' */ './import'),
},
{
path: '/runners',
load: () => import(/* webpackChunkName: 'runners' */ './runners'),
},
{
path: '/runners/create',
load: () => import(/* webpackChunkName: 'runners-create' */ './runners/create'),
},
{
path: '/runners/:id',
load: () => import(/* webpackChunkName: 'runners-update' */ './runners/update'),
},
{
path: '/sponsors',
load: () => import(/* webpackChunkName: 'sponsors' */ './sponsors'),
},
{
path: '/sponsors/create',
load: () => import(/* webpackChunkName: 'sponsors-create' */ './sponsors/create'),
},
// Wildcard routes, e.g. { path: '*', ... } (must go last)
{
path: '*',
load: () => import(/* webpackChunkName: 'not-found' */ './not-found'),
},
],
async action({ next }) {
// Execute each child route until one of them return the result
const route = await next();
// Provide default values for title, description etc.
route.title = `${route.title || 'Untitled Page'} - www.reactstarterkit.com`;
route.description = route.description || '';
return route;
},
};
// The error page is available by permanent url for development mode
if (__DEV__) {
routes.children.unshift({
path: '/error',
action: require('./error').default,
});
}
export default routes;
|
function True () { console.log("true" ); return true ; }
function False() { console.log("false"); return false; }
function Run () { console.log("run" ); return true ; }
True();
False();
console.log("True () || Run()", True () || Run());
console.log("False() || Run()", False() || Run());
console.log("True () && Run()", True () && Run());
console.log("False() && Run()", False() && Run());
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var index_1 = require("./index");
var index_2 = require("../shared/index");
exports.sellerRoutes = [
{ path: "vendor-profile", component: index_1.SellerProfileComponent, canActivate: [index_2.VendorProfileActivator] },
{ path: "sellers-list/:id", component: index_1.SellerDetailsComponent, canActivate: [index_2.JewelleryAndSellerDetailsActivator] },
{ path: '', redirectTo: "/home", pathMatch: "prefix" }
];
//# sourceMappingURL=seller.routes.js.map
|
/*globals define, WebGMEGlobal, $ */
define([
'./jquery.layout',
'js/logger',
'js/Utils/ComponentSettings',
'text!./templates/CHFLayout.html',
'text!./CHFLayoutConfig.json'
], function(
_jQueryLayout,
Logger,
ComponentSettings,
defaultLayoutTemplate,
LayoutConfigJSON
) {
'use strict';
var DEFAULT_CONFIG = JSON.parse(LayoutConfigJSON);
var CHFLayout = function(params) {
this._logger = (params && params.logger) || Logger.create('gme:Layouts:CHFLayout',
WebGMEGlobal.gmeConfig.client.log);
this.config = this.config ||
WebGMEGlobal.componentSettings[this.getComponentId()] ||
DEFAULT_CONFIG;
this.panels = this.config.panels;
this._template = (params && params.template) || defaultLayoutTemplate;
this._body = null;
this._panelToContainer = {};
};
/**
* Initialize the html page. This example is using the jQuery Layout plugin.
*
* @return {undefined}
*/
CHFLayout.prototype.init = function() {
var self = this;
this._body = $('body');
this._body.html(this._template);
this._centerPanel = this._body.find('div.center');
this._floatContainer = this._body.find('div.float');
this._headerPanel = this._body.find('div.ui-layout-north');
this._footerPanel = this._body.find('div.ui-layout-south');
this._canvas = null;
this._body.layout({
north: {
closable: false,
resizable: false,
slidable: false,
spacing_open: 0, //jshint ignore: line
size: 64
},
south: {
closable: false,
resizable: false,
slidable: false,
spacing_open: 0, //jshint ignore: line
size: 27 //has to match footer CSS settings (height + border)
},
center: {
onresize: function (/*paneName, paneElement, paneState, paneOptions, layoutName*/) {
self._onCenterResize();
}
}
});
};
CHFLayout.prototype.getComponentId = function() {
return 'CHFLayout';
};
/**
* Add a panel to a given container. This is defined in the corresponding
* layout config JSON file.
*
* @param {Panel} panel
* @param {String} container
* @return {undefined}
*/
CHFLayout.prototype.addToContainer = function(panel, container) {
if (container === 'header') {
this._headerPanel.append(panel.$pEl);
} else if (container === 'footer') {
this._footerPanel.append(panel.$pEl);
} else if (container === 'float') {
this._floatContainer.append(panel.$pEl);
} else if (container === 'center') {
this._centerPanel.append(panel.$pEl);
this._canvas = panel;
this._onCenterResize();
return this._onCenterResize;
}
};
/**
* Remove the given panel from the views
*
* @param {Panel} panel
* @return {undefined}
*/
CHFLayout.prototype.remove = function(panel) {
if (this._canvas === panel) {
this._centerPanel.empty();
}
};
/**
* Remove the current layout
*
* @return {undefined}
*/
CHFLayout.prototype.destroy = function() {
this._body.empty();
};
// Resize handlers
//
// These are internally called and used by the example to provide a responsive
// UI (even if it is simply scaling linearly here)
CHFLayout.prototype._onCenterResize = function() {
if (this._canvas) {
this._canvas.setSize(this._centerPanel.width(), this._centerPanel.height());
}
};
return CHFLayout;
});
|
define([
'nbd/util/async',
'nbd/util/extend',
'../View',
'../ux/keyboard',
'hgn!../template/dialog'
], function(async, extend, View, keyboard, dialogTemplate) {
'use strict';
var constructor = View.extend({
init: function(model) {
this._super(model);
this
.on('postrender', this._bindButtons)
.on('postrender', function() {
async(this.position.bind(this));
});
},
_bindButtons: function($view) {
$view
.on('click', '.js-confirm', this.trigger.bind(this, 'confirm'))
.on('click', '.js-close', this.hide.bind(this))
.on('click', '.js-disabled', false);
},
dialogTemplate: dialogTemplate,
template: function(data) {
return this.dialogTemplate(extend({
content: this._super(data)
}, this.dialogData, data));
},
position: function() {},
show: function() {
keyboard.on({
escape: this.hide.bind(this)
});
return this.trigger('show', this.$view);
},
hide: function() {
keyboard.off();
return this.trigger('hide', this.$view);
},
toggle: function() {
var state = this.$view.is(':visible');
return this[state ? 'hide': 'show']();
}
});
return constructor;
});
|
describe("Object.isEmpty", function(){
describeIsXFunction(Object.isEmpty, 'empty');
});
|
import createFetchSaga from '../../sagas/createFetchSaga'
import { roomLeave } from '../actions'
import { getRoomSelection } from '../selectors'
export default createFetchSaga(roomLeave, {
payloadSelector: getRoomSelection,
payloadReducer: roomId => ({ roomId })
})
|
/* @noflow */
import React from 'react';
import {
View,
} from 'react-native';
import {
Header,
} from 'react-router-native';
import styles from './styles';
export const component = (backgroundColor) => (props) => (
<View style={[styles.component, { backgroundColor }]}>
{props.children}
</View>
);
export const stackHeaderComponent = (backgroundColor) => (props) => {
const { scene } = props;
const title = String(scene.route.key || '');
return (
<Header
{...props}
title={title}
leftButtonText="Back"
style={{ backgroundColor }}
/>
);
};
export const tabHeaderComponent = (backgroundColor) => (props) => {
const { scene } = props;
const title = String(scene.route.key || '');
return (
<Header
{...props}
title={title}
style={{ backgroundColor }}
/>
);
};
|
$(function(){
$(".intelligent_ensemble_matches").hide();
$(".instrument_options_for_alternate_group").hide();
$(".wrapper").on("click", ".intelligent_ensemble_toggle", function(e){
e.preventDefault();
$(".intelligent_matches").toggle();
$(".all_ensemble_matches").toggle();
$(this).text(function(){
if($(this).text() == "Show All Ensembles") {
return "Show Intelligent Matches"
} else {
return "Show All Ensembles"
}
});
});
$(".show_parts").hide();
$(".group_parts").on("click", ".show_parts_button", function(e){
e.preventDefault();
$(".show_parts").slideToggle();
})
$(".all_ensemble_matches").on("click", ".search_button", function(e){
e.preventDefault();
$(".group_complete").parent().show();
var instrumentation = $("#group_instrumentation_id").val();
var instruments = $("#group_instruments").val();
var complete = $("#group_complete").val();
if(instrumentation.length > 0){
$.each($(".group_instrumentation"), function(i, value){
if($(value).text() !== instrumentation){
$(value).parent().hide();
}
});
}
if(complete.length > 0){
$.each($(".group_complete"), function(i, value){
if($(value).text() !== complete){
$(value).parent().hide();
}
});
}
var ensembleMatches;
function ajax1(){
return $.ajax({
url: 'search/get_instruments_for_group',
type: 'POST',
data: {instrument: $("#group_instruments").val()},
success: function(data){
ensembleMatches = data.join(",");
}
});
}
$.when(ajax1()).done(function(){
if(instruments.length > 0){
$.each($(".group_instrumentation"), function(i, value){
if(ensembleMatches.indexOf($(value).text())===-1){
$(value).parent().hide();
}
});
}
});
});
$(".wrapper").on("click", ".clear_fields", function(e){
e.preventDefault();
$(".chosen-container-single span").text("Select an Option");
$("#group_instrumentation_id").val("");
$("#group_instruments").val("");
$("#group_complete").val("");
});
$("#alternate_instrumentation").on("change", function(){
if ($(this).val() === "16"){
$(".instrument_options_for_alternate_group").show();
}
})
$(".row").on("hover", "li", function(){
$(this).find(".delete_piece_x").toggle();
});
$(".row").on("click", ".delete_piece_x", function(e){
e.preventDefault();
$id = $(this).parent().attr("id")
$row = $(this).parent()
if (confirm("Delete "+$row.text()+"...for real??") == true) {
$.ajax({
url: "/group_pieces/"+$id,
type: "delete",
success: function (){
$row.css({"color":"red","text-decoration":"line-through"});
$row.text("successfully removed");
$row.fadeOut(1500, function(){
$row.remove();
});
}
})
}
});
});
|
import React from 'react'
import Autocomplete from 'common/components/Autocomplete'
import { debounce } from 'throttle-debounce'
import ServiceFactory from 'services/ServiceFactory'
import { TaxonAttributeDefinition } from 'model/Survey'
import Arrays from 'utils/Arrays'
import Objects from 'utils/Objects'
import TaxonAutoCompleteDialogItem from './TaxonAutoCompleteDialogItem'
import * as FieldsSizes from '../FieldsSizes'
const fetchTaxa = ({ surveyId, fieldDef, queryField }) => ({ searchString, onComplete }) => {
return debounce(1000, false, async () => {
const { attributeDefinition } = fieldDef
const { allowUnlisted, highestRank, includeUniqueVernacularName, showFamily, taxonomyName } = attributeDefinition
const query = {
field: queryField,
searchString,
parameters: { highestRank, includeUniqueVernacularName, includeAncestorTaxons: showFamily },
}
const taxa = await ServiceFactory.speciesService.findTaxa({ surveyId, taxonomyName, query })
if (taxa.length === 0 && allowUnlisted) {
taxa.push(
{
[TaxonAttributeDefinition.ValueFields.CODE]: 'UNK',
[TaxonAttributeDefinition.ValueFields.SCIENTIFIC_NAME]: 'Unknown',
},
{
[TaxonAttributeDefinition.ValueFields.CODE]: 'UNL',
[TaxonAttributeDefinition.ValueFields.SCIENTIFIC_NAME]: 'Unlisted',
}
)
}
onComplete(taxa)
})
}
const TaxonAutoCompleteField = (props) => {
const { parentEntity, fieldDef, field, valueByFields, onInputChange, onSelect, onDismiss, readOnly } = props
const { attributeDefinition } = fieldDef
const queryField = TaxonAttributeDefinition.QueryFieldByField[field]
const surveyId = parentEntity.survey.id
const valueField = TaxonAttributeDefinition.ValueFieldByField[field]
const initialInputValue = Objects.getProp(field, '')(valueByFields)
const selectedTaxonOccurrence = Objects.mapKeys({
obj: valueByFields,
keysMapping: TaxonAttributeDefinition.ValueFieldByField,
})
const onTaxonSelected = (taxonOccurrence, inputValue) => {
const taxonOccurrenceUpdated = taxonOccurrence
if (
taxonOccurrence &&
[
TaxonAttributeDefinition.Fields.SCIENTIFIC_NAME,
TaxonAttributeDefinition.Fields.VERNACULAR_NAME,
TaxonAttributeDefinition.Fields.FAMILY_SCIENTIFIC_NAME,
].includes(field) &&
['UNK', 'UNL'].includes(taxonOccurrence.code)
) {
taxonOccurrenceUpdated[valueField] = inputValue.trim()
}
onSelect(taxonOccurrenceUpdated)
}
return (
<Autocomplete
asynchronous
inputValue={initialInputValue}
inputFieldWidth={FieldsSizes.TaxonFieldWidths[field]}
selectedItems={Arrays.singleton(selectedTaxonOccurrence)}
fetchFunction={fetchTaxa({ surveyId, fieldDef, queryField })}
itemLabelFunction={Objects.getProp(valueField, '')}
itemSelectedFunction={(item, value) => item.code === value.code}
itemRenderFunction={(taxonOccurrence) => (
<TaxonAutoCompleteDialogItem attributeDefinition={attributeDefinition} taxonOccurrence={taxonOccurrence} />
)}
onInputChange={onInputChange}
onSelect={onTaxonSelected}
onDismiss={onDismiss}
readOnly={readOnly}
popUpWidthContentBased
/>
)
}
export default TaxonAutoCompleteField
|
import bookmarksHelper from './bookmarks';
import tabsSync from '../background/tabs-sync';
export default {
get(tabId) {
return browser.tabs.get(tabId);
},
getOfWindow(windowId, filter = { pinned: false }) {
return new Promise((resolve) => {
browser.tabs.query(Object.assign({ windowId }, filter), resolve);
});
},
getRelevantOfWindow(windowId) {
return this.getOfWindow(windowId).then(tabs => tabs.filter(t => t.url.indexOf('about:') !== 0));
},
transformIndex(indexOrIndices, windowId) {
// The tab.index contains pinned and priviledged tabs,
// exclude them to be able to compare with bookmark indices
return this.getOfWindow(windowId, {})
.then(tabs => tabs.filter(t => t.pinned || t.url.indexOf('about:') === 0))
.then(ignoredTabs => ignoredTabs.map(t => t.index))
.then((ignoredIndices) => {
if (Array.isArray(indexOrIndices)) {
return indexOrIndices.map(i => this.adjustIndexForIgnored(i, ignoredIndices));
}
return this.adjustIndexForIgnored(indexOrIndices, ignoredIndices);
});
},
adjustIndexForIgnored(index, ignoredIndices) {
if (ignoredIndices.includes(index)) return null;
let offset = ignoredIndices.findIndex(i => i > index);
if (offset === -1) {
offset = ignoredIndices.length;
}
return index - offset;
},
openGroup(windowId, groupId) {
return this.getOfWindow(windowId)
.then(tabs => tabs.map(t => t.id))
.then(previousTabIds =>
bookmarksHelper.getChildren(groupId)
.then(bookmarks => this.withTabSyncDisabled(() => {
let promise;
if (bookmarks.length === 0) {
// For empty groups, make sure at least one tab is open,
// to not accidentially close the window
promise = this.open(null, true);
}
promise = Promise.all(bookmarks.map((bookmark, i) => this.open(bookmark, i === 0)));
return promise.then(() => this.close(previousTabIds), () => this.close(previousTabIds));
})));
},
openEmptyGroup(windowId) {
return this.getOfWindow(windowId)
.then(tabs => tabs.map(t => t.id))
.then(previousTabIds => this.withTabSyncDisabled(() =>
this.open(null, true)
.then(() => this.close(previousTabIds))));
},
open(bookmark, active) {
return browser.tabs.create({
url: bookmark ? bookmark.url : 'about:blank',
active,
});
},
close(tabIds) {
return browser.tabs.remove(tabIds);
},
withTabSyncDisabled(promiseCallback) {
tabsSync.disabled = true;
return promiseCallback().then(
(result) => {
setTimeout(() => {
tabsSync.disabled = false;
});
return result;
},
(error) => {
setTimeout(() => {
tabsSync.disabled = false;
});
return Promise.reject(error);
});
},
};
|
const INITIAL_STATE = { image: null };
export default (state = INITIAL_STATE, action) => {
switch (action.type) {
case 'SELECTED_IMAGE':
const img = action.payload.image;
return { image: img };
default:
return state;
}
};
|
import React from 'react';
import IconBase from '@suitejs/icon-base';
function MdExposureNeg2(props) {
return (
<IconBase viewBox="0 0 48 48" {...props}>
<path d="M31.09 33.58l5.73-6.13c.75-.79 1.44-1.57 2.08-2.35.63-.78 1.18-1.56 1.64-2.33.46-.78.82-1.55 1.07-2.33.26-.78.39-1.57.39-2.37 0-1.07-.18-2.04-.54-2.92-.36-.87-.88-1.62-1.57-2.23-.69-.61-1.53-1.08-2.53-1.42-1-.33-2.14-.5-3.42-.5-1.38 0-2.62.21-3.7.64-1.08.43-1.99 1.01-2.73 1.75s-1.3 1.61-1.68 2.6c-.36.94-.54 1.95-.56 3.01h4.28c.01-.62.09-1.21.26-1.74.18-.58.45-1.08.81-1.5.36-.42.81-.74 1.35-.98.55-.23 1.19-.35 1.93-.35.61 0 1.15.1 1.62.31.47.21.87.49 1.19.85.32.36.57.8.74 1.29.17.5.25 1.04.25 1.63 0 .43-.06.87-.17 1.3-.11.43-.3.9-.58 1.4-.28.5-.65 1.05-1.11 1.66-.46.6-1.05 1.29-1.75 2.07l-8.35 9.11V37H43v-3.42H31.09zM5 23v4h16v-4H5z" />
</IconBase>
);
}
export default MdExposureNeg2;
|
// @flow
import { describe, it } from 'flow-typed-test';
import type { PasswordPolicySchema } from 'password-validator';
import PasswordValidator from 'password-validator';
describe('password-validator', () => {
it('should work with valid arguments', () => {
const schema: PasswordPolicySchema = new PasswordValidator();
// prettier-ignore
schema
.is().min(8)
.is().max(100)
.has().uppercase()
.has().lowercase()
.has().digits()
.has().symbols()
.has().not().spaces()
.has(/(.*[A-Z]){2,}/);
schema.validate('3L}Ls4[4}qQB>UgN');
});
it('should fail with incorrect arguments', () => {
const schema = new PasswordValidator();
// $FlowExpectedError[extra-arg]
new PasswordValidator('extra-arg');
// $FlowExpectedError[extra-arg]
schema.is('foo');
// $FlowExpectedError[incompatible-call]
schema.has('foo');
// $FlowExpectedError[extra-arg]
schema.has(/.*/, 'foo');
// $FlowExpectedError[incompatible-call]
schema.not('foo');
// $FlowExpectedError[extra-arg]
schema.not(/.*/, 'bar');
// $FlowExpectedError[incompatible-call]
schema.is().min();
// $FlowExpectedError[incompatible-call]
schema.is().min('1');
// $FlowExpectedError[extra-arg]
schema.is().min(1, 'foo');
// $FlowExpectedError[incompatible-call]
schema.is().max();
// $FlowExpectedError[incompatible-call]
schema.is().max('1');
// $FlowExpectedError[extra-arg]
schema.is().max(1, 'foo');
// $FlowExpectedError[incompatible-call]
schema.has().spaces('1');
// $FlowExpectedError[extra-arg]
schema.has().spaces(1, 'foo');
// $FlowExpectedError[incompatible-call]
schema.has().symbols('1');
// $FlowExpectedError[extra-arg]
schema.has().symbols(1, 'foo');
// $FlowExpectedError[incompatible-call]
schema.has().uppercase('1');
// $FlowExpectedError[extra-arg]
schema.has().uppercase(1, 'foo');
// $FlowExpectedError[incompatible-call]
schema.has().letters('1');
// $FlowExpectedError[extra-arg]
schema.has().letters(1, 'foo');
// $FlowExpectedError[incompatible-call]
schema.has().digits('1');
// $FlowExpectedError[extra-arg]
schema.has().digits(1, 'foo');
// $FlowExpectedError[incompatible-call]
schema.has().oneOf([1, 2, 3]);
// $FlowExpectedError[extra-arg]
schema.has().oneOf(['foo', 'bar', 'baz'], 'foo');
});
});
|
var request = require("request");
exports.builder = function(url) {
return {
name: "Fetch HTML page",
weight: 3,
handler: function(item, args, context, cb) {
try {
request(url, response_available);
} catch(err) { return cb(err); }
function response_available(err, response, body) {
try {
if(err) return cb(err, null);
if(response.statusCode != 200) return cb("HTTP status code " + response.statusCode + " received.", null);
cb(null, { html: body });
} catch(err) { return cb(err); }
}
}
};
};
|
version https://git-lfs.github.com/spec/v1
oid sha256:60d28105148b198a94a403c96020096b04efc18e8495e5f733a0e07df3445a4b
size 1366
|
/**
* PostController
*
* @description :: Server-side logic for managing posts
* @help :: See http://links.sailsjs.org/docs/controllers
*/
module.exports = {
index: function (request, response, next) {
response.view('main');
},
form: function (request, response) {
response.view();
},
add: function (request, response, next) {
var title = request.param('title');
var description = request.param('description');
var body = request.param('body');
if (!title || !body) {
return response.redirect('post/form');
}
Post.create({
title: title,
description: description,
body: body
}, function (error, created) {
if (error) return next(error);
Post.publishCreate(created);
response.redirect('post/' + created.id);
});
},
subscribe: function (request, response, next) {
Post.find().limit(10).sort('createdAt desc').exec(function(err, posts) {
if (err) {
return next(err);
}
Post.watch(request);
response.json(posts);
});
}
};
|
$(document).ready(function(){
$("a[rel^='prettyPhoto']").prettyPhoto();
});
|
/*jslint sub: true */
var url = require('url');
var util = require('../util');
var EventEmitter = require('events').EventEmitter;
/**
* Endpoint represents an a collection of functions that can be executed by POSTing parameters to an
* HTTP server.
*
* When Endpoint is started it adds the a unique route, /remote/{uid}/{method}, to server.
* When a POST request is received, it calls method() with the request body as it's parameters.
*
* The available methods for this endpoint are defined by calling defineMethod(...).
*
* Endpoint emits the following events:
* - 'start': A route has been installed on the HTTP server and setup(), if defined through defineMethod(),
* has been called
* - 'end': The route has been removed. No more defined methods will be called.
*
* Endpoint.state can be:
* - 'initialized': This endpoint is ready to be started.
* - 'started': This endpoint is listening for POST requests to dispatching to the corresponding methods
*/
var Endpoint = exports.Endpoint = function Endpoint(server, hostAndPort) {
EventEmitter.call(this);
var self = this,
parts = hostAndPort ? hostAndPort.split(':') : [];
self.id = util.uid();
self.server = server;
self.methodNames = [];
self.methods = {};
self.setStaticParams([]);
self.state = 'initialized';
self.__defineGetter__('url', function() { return self.url_; });
self.hostname_ = parts[0];
self.port_ = parts[1];
self.basepath_ = '/remote/' + self.id;
self.handler_ = self.handle.bind(self);
};
Endpoint.prototype.__proto__ = EventEmitter.prototype;
/**
Set values that are passed as the initial arguments to every handler method. For example, if you:
var id = 123, name = 'myobject';
endpoint.setStaticParams([id, name]);
You should define methods:
endpoint.defineMethod('method_1', function(id, name, arg1, arg2...) {...});
which are called by:
endpoint.method_1(arg1, arg2...)
*/
Endpoint.prototype.setStaticParams = function(params) {
this.staticParams_ = params instanceof Array ? params : [params];
};
/**
Define a method that can be executed by POSTing to /basepath/method-name. For example:
endpoint.defineMethod('method_1', function(data) { return data; });
then POSTing '[123]' to /{basepath}/method_1 will respond with a message with body 123.
*/
Endpoint.prototype.defineMethod = function(name, fun) {
this.methodNames.push(name);
this.methods[name] = fun;
};
/**
* Start responding to requests to this endpoint by adding the proper route to the HTTP server
*/
Endpoint.prototype.start = function() {
if (this.state !== 'initialized') { return; }
this.url_ = url.format({
protocol: 'http',
hostname: this.hostname_ || this.server.hostname,
port: this.port_ || this.server.port,
pathname: this.basepath_
});
this.route_ = '^' + this.basepath_ + '/?';
this.server.addRoute(this.route_, this.handler_);
this.context = {};
if (this.methods['setup']) {
this.methods['setup'].apply(this.context, this.staticParams_);
}
this.state = 'started';
this.emit('start');
};
/**
* Remove the HTTP server route and stop responding to requests
*/
Endpoint.prototype.end = function() {
if (this.state !== 'started') { return; }
this.server.removeRoute(this.route_, this.handler_);
this.state = 'initialized';
this.emit('end');
};
/**
* The main HTTP request handler. On DELETE /{basepath}, it will self-destruct this endpoint. POST
* requests are routed to the function set by defineMethod(), applying the HTTP request body as parameters,
* and sending return value back in the HTTP response.
*/
Endpoint.prototype.handle = function(path, req, res) {
var self = this;
if (path === self.basepath_) {
if (req.method === 'DELETE') {
self.end();
res.writeHead(204, {'Content-Length': 0});
res.end();
} else {
res.writeHead(405);
res.end();
}
} else if (req.method === 'POST') {
var method = path.slice(this.basepath_.length+1);
if (self.methods[method]) {
util.readStream(req, function(params) {
var status = 200, ret;
try {
params = JSON.parse(params);
} catch(e1) {
res.writeHead(400);
res.end();
return;
}
params = (params instanceof Array) ? params : [params];
ret = self.methods[method].apply(self.context, self.staticParams_.concat(params));
try {
ret = (ret === undefined) ? '' : JSON.stringify(ret);
} catch(e2) {
ret = e2.toString();
status = 500;
}
res.writeHead(status, {'Content-Length': ret.length, 'Content-Type': 'application/json'});
res.end(ret);
});
} else {
res.writeHead(404);
res.end();
}
} else {
res.writeHead(405);
res.end();
}
};
|
// Copyright (c) 2015 - 2017 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import test from 'tape-catch';
import Effect from '@deck.gl/core/lib/effect';
test('Effect#constructor', t => {
const effect = new Effect();
t.ok(effect, 'Effect created');
t.end();
});
|
'use strict';
angular.module('HeyBusApp')
.filter('isActive', function () {
return function (input) {
return input.filter(function (item) {
return item.active === true;
});
};
});
|
/**
* Toggles
* jquery.toggles wrapper
*/
"use strict";
(
function(){
var dependencies = ['angular',"./UIModule",'toggles'];
define(dependencies,function(angular,UIModule) {
console.log("directives.ui.Toggles");
// camelCase get converted to snake-case when applied to dom element
UIModule.directive("uiToggles",function($document){
return function(scope,element,attr){
console.log("Toggles");
element.toggles({
//width:40,
height:30,
drag:false,
text: {
on:"",
off:""
}
});
}
});
});
}()
);
|
function setup() {
// createCanvas( windowWidth, windowHeight );
createCanvas( windowWidth, 600 );
}
function draw() {
background( 'rgb(0, 6, 87)' );
textSize(36);
noStroke();
fill('white');
text("'mouseX': " + floor(mouseX), 10, 40 );
text("'mouseY': " + floor(mouseY), 10, 80 );
}
|
import React from 'react';
import { Switch, BrowserRouter as Router, Route } from 'react-router-dom';
import ImportedComponent from 'react-imported-component';
import Loading from '../components/Loading';
const AsyncUpdaterForm = ImportedComponent(
() =>
import(/* webpackChunkName:'UpdaterForm' */ '../components/UpdaterForm'),
{
LoadingComponent: Loading
}
);
const AsyncLogin = ImportedComponent(
() => import(/* webpackChunkName:'Login' */ '../components/Login'),
{
LoadingComponent: Loading
}
);
const AsyncNoMatch = ImportedComponent(
() => import(/* webpackChunkName:'NoMatch' */ '../components/NoMatch'),
{
LoadingComponent: Loading
}
);
const App = () => {
return (
<Router>
<div>
<Switch>
<Route path="/updater" component={AsyncUpdaterForm} />
<Route exact path="/" component={AsyncLogin} />
<Route component={AsyncNoMatch} />
</Switch>
</div>
</Router>
);
};
export default App;
|
import extname from './extname'
import ValidatorErrors from './validator-errors'
export default class FileExtensionValidator {
constructor (validatable) {
if (validatable.type === 'browser') {
this.extension = validatable
} else {
this.extension = extname(validatable.fileToParse.fileName)
}
}
validate () {
if (this._validateFileExtension()) return { error: null }
return this._fileExtensionError()
}
_validateFileExtension () {
return this.extension === '.xlsx'
}
_fileExtensionError () {
let msg = `El archivo no tiene una extensión permitida '${this.extension}'`
return new ValidatorErrors('FileExtensionValidatorError', msg, 'ValidFileExtension')
}
}
|
'use strict';
//region Imports
import Argument from '../system/argument-check.js';
import ConstructorError from '../system/constructor-error.js';
import NotImplementedError from '../system/not-implemented-error.js';
//endregion
/**
* Serves as the base class for rules.
*
* @memberof bo.rules
*/
class RuleBase {
/**
* Creates a new rule object.
* The rule instances should be frozen.
*
* @param {string} ruleName - The name of the rule.
*
* @throws {@link bo.system.ArgumentError Argument error}: The rule name must be a non-empty string.
*/
constructor( ruleName ) {
ruleName = Argument.inConstructor( this.constructor.name )
.check( ruleName ).forMandatory( 'ruleName' ).asString();
/**
* The name of the rule type.
* The default value usually the name of the constructor, without the Rule suffix.
* @member {string} bo.rules.RuleBase#ruleName
* @readonly
*/
Object.defineProperty( this, 'ruleName', {
get: function () {
return ruleName;
},
enumeration: true
} );
/**
* Human-readable description of the rule failure.
* @member {string} bo.rules.RuleBase#message
* @readonly
*/
this.message = null;
/**
* The priority of the rule. Higher number means higher priority.
* @member {number} bo.rules.RuleBase#priority
* @default
* @readonly
*/
this.priority = 10;
/**
* Indicates whether processing of the rules for a property stops when the rule fails.
* @member {boolean} bo.rules.RuleBase#stopsProcessing
* @default
* @readonly
*/
this.stopsProcessing = false;
}
/**
* Sets the properties of the rule.
*
* @function bo.rules.RuleBase#initialize
* @param {string} message - Human-readable description of the rule failure.
* @param {number} [priority=10] - The priority of the rule.
* @param {boolean} [stopsProcessing=false] - Indicates the rule behavior in case of failure.
*
* @throws {@link bo.system.ArgumentError Argument error}: The message must be a non-empty string.
* @throws {@link bo.system.ArgumentError Argument error}: The last 3 arguments can be:
* a string as the message, an integer as the priority and a Boolean as the stopsProcessing argument.
*/
initialize( message, priority, stopsProcessing ) {
// Remove null and undefined arguments.
const args = Array.prototype.slice.call( arguments ).filter( function ( arg ) {
return arg !== null && arg !== undefined;
} );
if (args.length) {
for (let i = 0; i < args.length; i++) {
switch (typeof args[ i ]) {
case 'string':
this.message = args[ i ];
break;
case 'number':
this.priority = Math.round( args[ i ] );
break;
case 'boolean':
this.stopsProcessing = args[ i ];
break;
default:
throw new ConstructorError( 'rule', this.constructor.name );
}
}
}
Argument.inConstructor( this.constructor.name ).check( this.message ).forMandatory( 'message' ).asString();
}
/**
* Abstract method to check if the rule is valid for the property.
*
* @abstract
* @function bo.rules.RuleBase#execute
* @param {Array.<*>} inputs - An array of the values of the required properties.
*
* @throws {@link bo.system.NotImplementedError Not implemented error}: The Rule.execute method is not implemented.
*/
execute( inputs ) {
throw new NotImplementedError( 'method', this.constructor.name, 'execute' );
}
/**
* Abstract method that returns the result of the rule checking.
*
* @abstract
* @function bo.rules.RuleBase#result
* @param {string} [message] - Human-readable description of the rule failure.
* @param {bo.rules.RuleSeverity} [severity] - The severity of the rule failure.
* @returns {object} An object that describes the result of the rule checking.
*
* @throws {@link bo.system.NotImplementedError Not implemented error}: The Rule.result method is not implemented.
*/
result( message, severity ) {
throw new NotImplementedError( 'method', this.constructor.name, 'result' );
}
}
export default RuleBase;
|
define('MAF.system.SnippetView', function () {
return new MAF.Class({
ClassName: 'SnippetView',
Extends: MAF.system.BaseView,
viewType: 'SNIPPET'
});
}, {
SnippetView: {
styles: {
width: '470px',
height: '166px'
}
}
});
|
// @flow
export type StubsType = {
[path: string]: any,
};
|
module.exports = {
root: true,
env: {
browser: true,
es6: true,
node: true,
},
parser: 'babel-eslint',
parserOptions: {
ecmaVersion: 6,
sourceType: 'module',
ecmaFeatures: {
jsx: true,
experimentalObjectRestSpread: true,
},
},
'rules': {
'no-constant-condition': 'error',
'no-cond-assign': 'error',
'no-console': 'warn',
'no-constant-condition': 'error',
'no-control-regex': 'error',
'no-debugger': 'warn',
'no-dupe-args': 'error',
'no-dupe-keys': 'error',
'no-duplicate-case': 'error',
'no-empty': 'warn',
'no-empty-character-class': 'error',
'no-ex-assign': 'error',
'no-extra-boolean-cast': 'error',
'no-extra-semi': 'error',
'no-func-assign': 'error',
'no-inner-declarations': 'error',
'no-invalid-regexp': 'error',
'no-irregular-whitespace': 'error',
'no-obj-calls': 'error',
'no-regex-spaces': 'error',
'no-sparse-arrays': 'error',
'no-template-curly-in-string': 'error',
'no-unexpected-multiline': 'error',
'no-unreachable': 'error',
'no-unsafe-finally': 'error',
'no-unsafe-negation': 'error',
'use-isnan': 'error',
'valid-typeof': 'error',
'block-scoped-var': 'error',
'curly': 'error',
'default-case': 'error',
'dot-location': ['error', 'property'],
'dot-notation': 'error',
'eqeqeq': 'error',
'no-case-declarations': 'error',
'no-else-return': 'error',
'no-empty-pattern': 'error',
'no-eq-null': 'error',
'no-eval': 'error',
'no-extend-native': 'error',
'no-extra-bind': 'error',
'no-extra-label': 'error',
'no-fallthrough': 'error',
'no-floating-decimal': 'error',
'no-global-assign': 'error',
'no-implicit-coercion': 'error',
'no-multi-spaces': 'error',
'no-octal': 'error',
'no-redeclare': 'error',
'no-self-assign': 'error',
'no-unused-labels': 'error',
'no-useless-call': 'error',
'no-useless-concat': 'error',
'no-useless-escape': 'error',
'no-useless-return': 'error',
'no-void': 'error',
'no-catch-shadow': 'error',
'no-delete-var': 'error',
'no-label-var': 'error',
'no-restricted-globals': 'error',
'no-shadow': 'error',
'no-shadow-restricted-names': 'error',
'no-undef': 'error',
'no-undef-init': 'error',
'no-unused-vars': 'error',
'array-bracket-spacing': ['error', 'always'],
'block-spacing': 'warn',
'brace-style': ['warn', 'stroustrup', { 'allowSingleLine': true }],
'camelcase': 'error',
'comma-dangle': ['warn', 'always'],
'comma-spacing': ['warn', { 'before': false, 'after': true }],
'array-bracket-spacing': ['warn', 'always'],
'computed-property-spacing': ['warn', 'always'],
'eol-last': ['warn', 'always'],
'func-call-spacing': ['warn', 'never'],
'func-name-matching': ['error', 'always'],
'indent': 'warn',
'key-spacing': 'warn',
'keyword-spacing': 'warn',
'no-bitwise': 'error',
'no-lonely-if': 'error',
'no-mixed-operators': 'error',
'no-mixed-spaces-and-tabs': 'warn',
'no-multi-assign': 'error',
'no-multiple-empty-lines': 'warn',
'no-tabs': 'warn',
'no-trailing-spaces': 'warn',
'no-unneeded-ternary': 'error',
'no-whitespace-before-property': 'warn',
'object-curly-newline': ['warn', { 'multiline': true }],
'object-curly-spacing': ['warn', 'always'],
'object-property-newline': 'error',
'one-var': ['error', 'never'],
'operator-linebreak': ['error', 'before'],
'quotes': ['error', 'single'],
'semi': 'error',
'space-before-blocks': 'warn',
'space-before-function-paren': ['warn', 'never'],
'space-infix-ops': 'warn',
'space-unary-ops': 'warn',
'spaced-comment': ['warn', 'always'],
'wrap-regex': 'error',
'arrow-body-style': ['error', 'always'],
'arrow-parens': ['error', 'always'],
'arrow-spacing': 'warn',
'no-confusing-arrow': 'error',
'no-const-assign': 'error',
'no-dupe-class-members': 'error',
'no-duplicate-imports': 'error',
'no-this-before-super': 'error',
'no-var': 'error',
'prefer-arrow-callback': 'error',
'prefer-const': 'warn',
'prefer-rest-params': 'warn',
'prefer-spread': 'warn',
'prefer-template': 'error',
'require-yield': 'error',
'rest-spread-spacing': ['warn', 'never'],
'template-curly-spacing': 'warn'
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.