code
stringlengths 2
1.05M
|
|---|
var winston = require('winston');
winston.loggers.add('http_access',{
file: {
filename: process.cwd()+'/logs/http_access.log'
}
});
winston.loggers.add('newUsers',{
file: {
filename: process.cwd()+'/logs/newUsers.log'
}
});
winston.loggers.add('notifies',{
file: {
filename: process.cwd()+'/logs/notifies.log'
}
});
winston.loggers.add('errors',{
file: {
filename: process.cwd()+'/logs/errors.log'
}
});
var httpLog = winston.loggers.get('http_access'),
newUserLog = winston.loggers.get('newUsers'),
notifyLog = winston.loggers.get('notifies'),
errorLog = winston.loggers.get('errors');
exports.name = 'kabamPluginLoggerFile';
exports.listeners = {
'http' : httpLog.info,
'error': errorLog.error, //logging errors
//logging new users
'users:signUp': newUserLog.info,
'users:signUpByEmailOnly': newUserLog.info,
'users:completeProfile': newUserLog.info,
'users:findOneByApiKeyAndVerify': newUserLog.info,
//logging roles managment - todo - create proper security logging for it
'users:revokeRole': function(){},
'users:grantRole': function(){},
//notifications
'notify:email': notifyLog.info,
'notify:sio': notifyLog.info
};
|
import { combineReducers } from 'redux';
import { routerReducer } from 'react-router-redux';
import auth from './auth';
export default combineReducers({
router: routerReducer,
auth,
});
|
import reducer from '../../src/reducers/NavigationReducer';
import * as types from '../../src/actions/types';
describe('navigation reducer', () => {
it('should return the initial state', () => {
expect(reducer(undefined, {})).toEqual(
{
leftClicked: false,
rightClicked: false,
currentView: '',
updateAchievementsView: false,
updateProfileView: false,
updateHighscoreView: false
}
);
});
it('should click left', () => {
expect(
reducer([], {
type: types.LEFT_CLICK,
payload: {
show: true,
view: 'view'
}
})
).toEqual(
{
leftClicked: true,
currentView: 'view'
}
);
});
it('should click right', () => {
expect(
reducer([], {
type: types.RIGHT_CLICK,
payload: {
show: true,
view: 'view'
}
})
).toEqual(
{
rightClicked: true,
currentView: 'view'
}
);
});
it('should update view highscore', () => {
expect(
reducer([], {
type: types.UPDATE_VIEW_HIGHSCORE,
payload: true
})
).toEqual(
{
updateHighscoreView: true
}
);
});
it('should update view achievements', () => {
expect(
reducer([], {
type: types.UPDATE_VIEW_ACHIEVEMENTS,
payload: true
})
).toEqual(
{
updateAchievementsView: true
}
);
});
it('should update ivew profile', () => {
expect(
reducer([], {
type: types.UPDATE_VIEW_PROFILE,
payload: true
})
).toEqual(
{
updateProfileView: true
}
);
});
});
|
// custom marker for selected restaurant
var plainMarker = L.icon({
iconUrl: './leaflet-0.8-dev/images/marker-icon.png',
iconSize: [18, 30],
iconAnchor: [9, 30],
});
var starMarker1 = L.icon({
iconUrl: './leaflet-0.8-dev/images/marker-star1.png',
iconSize: [18, 30],
iconAnchor: [9, 30],
});
var starMarker2 = L.icon({
iconUrl: './leaflet-0.8-dev/images/marker-star2.png',
iconSize: [18, 30],
iconAnchor: [9, 30],
});
var starMarker3 = L.icon({
iconUrl: './leaflet-0.8-dev/images/marker-star3.png',
iconSize: [18, 30],
iconAnchor: [9, 30],
});
var starMarker4 = L.icon({
iconUrl: './leaflet-0.8-dev/images/marker-star4.png',
iconSize: [18, 30],
iconAnchor: [9, 30],
});
var starMarker5 = L.icon({
iconUrl: './leaflet-0.8-dev/images/marker-star5.png',
iconSize: [18, 30],
iconAnchor: [9, 30],
});
function GetMarkerbyStar(star) {
var marker = L.Marker;
switch(Math.round(star)) {
case 1: marker = starMarker1; break;
case 2: marker = starMarker2; break;
case 3: marker = starMarker3; break;
case 4: marker = starMarker4; break;
case 5: marker = starMarker5; break;
}
return marker;
};
var map
var restaurant_data; //[business_id, name, lon, lat, average_rating]
// area selection
var markers = []
var SelectedMarkers = [];
var SelectedMarkerZIndex = [];
var selectedID = [];
var BrushedResID = []
var yScale = d3.scale.linear().domain([0, 5]).range([150, 50]);
var mindate = new Date("Janurary 1, 2011 00:00:00");
var maxdate = new Date("Janurary 1, 2015 00:00:00");
var yearFormat = d3.time.format("%Y");
var xScale = d3.time.scale().domain([mindate, maxdate]).range([50, 750]);
var allIDs; // restaurant ID for all the restaurants
var rating; // store the the json file after importing
// funtiont generate date object from database entry
var formatDate = d3.time.format("%Y-%m-%d");
function mainPlot(){
// ---------------------------------------------------------
// Draw the map
// ---------------------------------------------------------
// create a map in the "map" div, set the view to a given place and zoom
lon = restaurant_data[0][2]
lat = restaurant_data[0][3]
map = L.map('map').setView([lon, lat], 11);
map.scrollWheelZoom.disable();
// add an OpenStreetMap tile layer
L.tileLayer('http://{s}.www.toolserver.org/tiles/bw-mapnik/{z}/{x}/{y}.png', {
detectRetina: true,
styles: 'grayscale'
}).addTo(map);
// add reset button (using easyButton)
L.easyButton("fa-rotate-left",
function() {
map.setView([restaurant_data[0][2], restaurant_data[0][3]], 11)
// resume all markers
for (var i = 0; i < markers.length; i++) {
markers[i].setOpacity(1);
}
for (var i = 0; i < markers.length; i++) {
selectedID.push(markers[i]._leaflet_id);
SelectedMarkers.push(markers[i]);
SelectedMarkerZIndex.push(markers[i]._zIndex);
}
plotByID(selectedID);
},
"Reset",
map);
// ---------------------------------------------------------
// Draw the scatter plot of the ratings
// ---------------------------------------------------------
// draw the scatter plot (weighted rating vs average rating) axises
var xAxis = d3.svg.axis().ticks(5).scale(xaxisRange);
var yAxis = d3.svg.axis().ticks(5).scale(yaxisRange);
// color scale, Cynthia Brewer’s RdYlBu scale
var color01 = "#91bfdb"; //blue
var color02 = "#ffffbf"; //white
var color03 = "#fc8d59"; //red
var colorScale = d3.scale.linear().domain([0, 2.5, 5])
.range([color01, color02, color03]);
//axis of color scale map
var rateScale = d3.scale.linear().domain([5, 2.5, 0]).range([100, 200, 300]);
var rateAxis = d3.svg.axis().ticks(5).scale(rateScale);
rateAxis.orient("left");
var rateAxisSel = d3.select("#scatter") // or something else that selects the SVG element in your visualizations
.append("g") // create a group node
.attr("class", "axises")
.attr("transform", "translate(30, 0)")
.call(rateAxis); // call the axis generator
//plot the legend of scatter plot
gradientPlot = function (c1, c2, c3)
{
var gradientScale = d3.scale.linear()
.domain([0, 50, 100])
.range([c3, c2, c1]);
for (k=0; k<100; k++)
{
d3.select("#scatter")
.append("rect")
.attr("width", 20)
.attr("height", 2)
.attr("x", 30)
.attr("y", 100 + k*2)
.style("fill", gradientScale(k));
}
}
gradientPlot(color01, color02, color03);
// Add brush
var brush = d3.select("#scatter").append("g")
.attr("class", "brush")
.call(d3.svg.brush()
.x(xaxisRange)
.y(yaxisRange)
.on("brushstart", brushstart)
.on("brush", brushmove)
.on("brushend", brushend));
function clearDetail() {
// Clear table content
d3.select("body").select("#name").text("");
d3.select("body").select("#weiRating").text("");
d3.select("body").select("#aveRating").text("");
d3.select("body").select("#numRating").text("");
d3.select("body").select("#firRating").text("");
d3.select("body").select("#lasRating").text("");
// Clear review history
d3.select("#historyPlot").selectAll("circle").remove();
}
function brushstart() {
BrushedResID = [];
highlightInMap(BrushedResID);
clearDetail();
}
function brushmove() {
BrushedResID = [];
var extent = d3.event.target.extent();
d3.select("#scatter").selectAll("circle").classed("hidden", function(d, i) {
inBrush = (extent[0][0] <= weightedR[i] && weightedR[i] <= extent[1][0]
&& extent[0][1] <= d && d <= extent[1][1]);
if(inBrush) { BrushedResID.push(resID[i]);}
return !inBrush;
})
highlightInMap(BrushedResID);
}
function brushend() {
if (d3.event.target.empty()) {
d3.select("#scatter").selectAll("circle").classed("hidden", false)
for(var i = 0; i < SelectedMarkers.length; i ++) {
SelectedMarkers[i].setOpacity(1);
SelectedMarkers[i].setZIndexOffset(SelectedMarkerZIndex[i]);
}
plotByID(selectedID);
}
}
// the equal line in the scatter plot
d3.select("#scatter").append("line")
.attr("x1", 110)
.attr("y1", 370)
.attr("x2", 460)
.attr("y2", 20)
.attr("stroke", "blue")
.attr("stroke-width", 1);
// axis of the scatter plot
yAxis.orient("left");
d3.select("#scatter").append("g").attr("class", "axises")
.attr("transform", "translate(110, 0)")
.call(yAxis); // call the axis generator
d3.select("#scatter").append("g")
.attr("class", "axises")
.attr("transform", "translate(0, 370)")
.call(xAxis); // call the axis generator
// Click on scatterplot
d3.select("#scatter")
.on("mousedown", function()
{
var mouseC = d3.mouse(this);
for (var k=0; k<weightedR.length; k++){
if ((mouseC[0] + 5) > xaxisRange(weightedR[k]) && (mouseC[0] - 5) < xaxisRange(weightedR[k])) {
if ((mouseC[1] + 5) > yaxisRange(ratMean[k]) && (mouseC[1] - 5) < yaxisRange(ratMean[k])) {
clickOnScatter(k);
}
}
}
});
function clickOnScatter(resIndex) {
var k = resIndex;
d3.select("body").select("#name").text(resName[k]);
d3.select("body").select("#weiRating").text(weightedR[k]);
d3.select("body").select("#aveRating").text(ratMean[k]);
d3.select("body").select("#numRating").text(numR[k]);
d3.select("body").select("#firRating").text(firstDate[k]);
d3.select("body").select("#lasRating").text(lastDate[k]);
onCircle = true
highlightInMap([resID[k]]);
// plot single restaurant rating through the time
var revi1;
restaurantID1 = selectedID[k];
//console.log(restaurantID1);
function importRating1 (rid) // import the rating info of a selected restaurant
{
//console.log(rid);
var numRatings = rating[rid].length; // number of ratings for this restaurant
revi1 = new Array(numRatings); // import ratings
revit = new Array(numRatings); // import ratings date information
for (var h=0; h<numRatings; h++)
{
revi1[h] = rating[rid][h][0];
revit[h] = formatDate.parse(rating[rid][h][1]);
}
}
importRating1 (restaurantID1);
d3.select("body").select("#historyPlot").selectAll("circle").remove();
d3.select("body").select("#historyPlot").select("#rNm").remove();
d3.select("#historyPlot").append("text")
.attr("id", "rNm")
.attr("x", 50)
.attr("y", 20)
.text("Rating history");
d3.select("#historyPlot")
.selectAll("circle")
.data(revi1)
.enter()
.append("circle")
.attr("cx", function(d,i) { return xScale(revit[i]); })
.attr("cy", function(d) { return yScale(d); })
.attr("r", function(d,i) { if (yearFormat(revit[i]) > 2010 && yearFormat(revit[i]) < 2015) return 3; else return 0;})
// hide other circles when click on one
d3.select("#scatter").selectAll("circle").classed("hidden", function (d, j) {
// d is average, weightedR[j] is weighted
return !(k==j && ratMean[k]==d);
});
}
// ----------------------------------------------------------
// Draw the history of reviews
// ----------------------------------------------------------
// draw the axises
d3.select("#historyPlot").append("text")
.attr("id", "rNm")
.attr("x", 50)
.attr("y", 20)
.style("font-size", "16px")
.text("------");
var yAxis = d3.svg.axis()
.orient("left")
.ticks(5)
.scale(yScale);
var xAxis = d3.svg.axis()
.orient("bottom")
.ticks(6)
.scale(xScale);
d3.select("#historyPlot").append("g")
.attr("class", "axises")
.attr("transform", "translate(50,0)")
.call(yAxis);
d3.select("#historyPlot").append("g")
.attr("class", "axises") // give it a class so it can be used to select only xaxis labels below
.attr("transform", "translate(0,150)")
.call(xAxis);
// ---------------------------------------------------------
// Marker on map
// ---------------------------------------------------------
// Add markers to map
for (var i = 0; i < restaurant_data.length; i ++) {
var marker = L.marker([restaurant_data[i][2], restaurant_data[i][3]], {icon: GetMarkerbyStar(restaurant_data[i][4])} ).on('click', onClick);
marker._leaflet_id = restaurant_data[i][0];
marker.addTo(map);
markers[markers.length] = marker
}
map.on("boxzoomend", function(e) {
// reset
for (var i = 0; i < markers.length; i++) {
markers[i].setOpacity(1);
}
selectedID = [];
SelectedMarkers = [];
SelectedMarkerZIndex = [];
for (var i = 0; i < markers.length; i++) {
// Not in the boundary or not selected
if (! e.boxZoomBounds.contains(markers[i].getLatLng())) {
markers[i].setOpacity(0);
}
else {
selectedID.push(markers[i]._leaflet_id);
SelectedMarkers.push(markers[i]);
SelectedMarkerZIndex.push(markers[i]._zIndex);
}
}
plotByID(selectedID);
});
// Highlight the marker when click on corresponding scatterplot
function highlightInMap(resIDs) {
for(var i = 0; i < SelectedMarkers.length; i ++) {
flag = false;
for(var j = 0; j < resIDs.length; j ++) {
if(SelectedMarkers[i]._leaflet_id == resIDs[j]) {
flag = true;
break;
}
}
if(flag) {
SelectedMarkers[i].setOpacity(1);
SelectedMarkers[i].setZIndexOffset(10000);
}
else {
SelectedMarkers[i].setOpacity(0.2);
SelectedMarkers[i].setZIndexOffset(SelectedMarkerZIndex[i]);
}
}
}
// Click on a marker
function onClick(e) {
resIndex = 0;
for(var i = 0; i < resID.length; i ++) {
if(resID[i] == this._leaflet_id) {
resIndex = i;
break;
}
}
clickOnScatter(resIndex);
highlightInMap([this._leaflet_id]);
}
// --------------------------------------------
// Others
// --------------------------------------------
// plot all the restaurant at the begining;
for (var i = 0; i < markers.length; i++) {
selectedID.push(markers[i]._leaflet_id);
SelectedMarkers.push(markers[i]);
SelectedMarkerZIndex.push(markers[i]._zIndex);
}
plotByID(selectedID);
};
d3.json("./reviews.json", function(error, json) {
if (error) return console.warn(error);
rating = json;
d3.json("./az100.json", function(error, json) {
if (error) return console.warn(error);
restaurant_data= json;
mainPlot();
});
});
|
// pageObjectExample1.js
// This is a simple page object pattern example that does the following:
// open page
// verify copyright
// fill in search form and submit
// wait for results on results page
// verify results
// Page objects are used to provide another layer of abstraction between
// the page information and the actual tests.
// To Run:
// $ wdio wdio.conf-pObjEx1.js
// Updated to support version >4 of webdriverio
// required libraries
var webdriverio = require('webdriverio'),
should = require('should');
var WebPage = require('./pageobjects/web-page');
// a test script block or suite
describe('Page Object Example #1 for Web Driver IO - Tutorial Test Page Website', function() {
it('should open page using pageObjects', function () {
WebPage.open();
});
it('should verify copyright using pageObjects', function () {
var cr = WebPage.getCopyright();
(cr).should.equal("Tony Keith - tlkeith.com @ 2015-2017 - All rights reserved.");
});
it('should fill, submit the search form and verfiy results using pageObjects', function () {
WebPage.setFirstname("John");
var fn = WebPage.getFirstname();
(fn).should.be.equal("John");
console.log("First Name: " + fn);
WebPage.setLastname('Doe');
var ln = WebPage.getLastname();
(ln).should.be.equal("Doe");
WebPage.submit();
WebPage.waitForResults();
var rs = WebPage.getResults();
(rs).should.equal("Welcome " + "John" + " " + "Doe" + ".");
});
});
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import { fetchPost, deletePost } from '../actions';
class PostsShow extends Component {
componentDidMount() {
const { id } = this.props.match.params;
this.props.fetchPost(id);
}
onDeleteClick(){
const { id } = this.props.match.params;
this.props.deletePost(id, () => {
this.props.history.push('/');
});
}
render() {
const { post } = this.props;
if (!post) {
return <div>Loading...</div>;
}
return(
<div>
<Link to="/">Back to Index</Link>
<button
className="btn btn-danger pull-xs-right"
onClick={this.onDeleteClick.bind(this)}
>Delete Post
</button>
<h3>{post.title}</h3>
<h6>Categories: {post.categories}</h6>
<p>{post.content}</p>
</div>
);
}
}
function mapStateToProps({ posts }, ownProps) {
return { post: posts[ownProps.match.params.id] };
}
export default connect(mapStateToProps, { fetchPost, deletePost })(PostsShow);
|
'use strict';
/**
* Module dependencies.
*/
var passport = require('passport');
module.exports = function(app) {
// User Routes
var users = require('../controllers/users.server.controller');
// Setting up the users profile api
app.route('/api/users/me').get(users.me);
app.route('/api/users').put(users.update);
app.route('/api/users/initiatePayment').post(users.initiatePayment);
// Finish by binding the user middleware
app.param('userId', users.userByID);
};
|
const helpers = require('./helpers');
const webpackMerge = require('webpack-merge'); // used to merge webpack configs
const commonConfig = require('./webpack.common.js'); // the settings that are common to prod and dev
/**
* Webpack Plugins
*/
const AddAssetHtmlPlugin = require('add-asset-html-webpack-plugin');
const DefinePlugin = require('webpack/lib/DefinePlugin');
const NamedModulesPlugin = require('webpack/lib/NamedModulesPlugin');
const LoaderOptionsPlugin = require('webpack/lib/LoaderOptionsPlugin');
/**
* Webpack Constants
*/
const ENV = process.env.ENV = process.env.NODE_ENV = 'development';
const HOST = process.env.HOST || '0.0.0.0';
const PORT = process.env.PORT || 3000;
const HMR = helpers.hasProcessFlag('hot');
const METADATA = webpackMerge(commonConfig({env: ENV}).metadata, {
host: HOST,
port: PORT,
ENV: ENV,
HMR: HMR
});
module.exports = function (options) {
return webpackMerge(commonConfig({env: ENV}), {
devtool: 'cheap-module-source-map',
output: {
path: helpers.root('dist'),
filename: '[name].bundle.js',
sourceMapFilename: '[file].map',
chunkFilename: '[id].chunk.js',
library: 'ac_[name]',
libraryTarget: 'var',
},
module: {
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader'],
include: [helpers.root('src', 'styles')]
},
{
test: /\.scss$/,
use: ['style-loader', 'css-loader', 'sass-loader'],
include: [helpers.root('src', 'styles')]
},
]
},
plugins: [
/**
* Plugin: DefinePlugin
* Description: Define free variables.
* Useful for having development builds with debug logging or adding global constants.
**/
new DefinePlugin({
'ENV': JSON.stringify(METADATA.ENV),
'HMR': METADATA.HMR,
'process.env': {
'ENV': JSON.stringify(METADATA.ENV),
'NODE_ENV': JSON.stringify(METADATA.ENV),
'HMR': METADATA.HMR,
}
}),
new AddAssetHtmlPlugin([
{ filepath: helpers.root('src/assets/js', 'jquery-3.1.0.min.js'), includeSourcemap: false },
{ filepath: helpers.root('src/assets/js', 'bootstrap.min.js'), includeSourcemap: false },
{ filepath: helpers.root('src/assets/js', 'arrive.min.js'), includeSourcemap: false },
{ filepath: helpers.root('src/assets/js', 'material.min.js'), includeSourcemap: false },
{ filepath: helpers.root('src/assets/js', 'bootstrap-notify.js'), includeSourcemap: false },
{ filepath: helpers.root('src/assets/js', 'material-dashboard.js'), includeSourcemap: false },
{ filepath: helpers.root('src/assets/js', 'demo.js'), includeSourcemap: false },
{ filepath: helpers.root('node_modules/reflect-metadata', 'Reflect.js'), includeSourcemap: false }
]),
new LoaderOptionsPlugin({
debug: true,
options: {
}
}),
],
// webpack dev server configurations
devServer: {
port: METADATA.port,
host: METADATA.host,
historyApiFallback: true,
watchOptions: {
ignored: /node_modules/
},
setup: function(app) {
}
},
// Node configuration
node: {
global: true,
crypto: 'empty',
process: true,
module: false,
clearImmediate: false,
setImmediate: false
}
});
}
|
import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react/lib/ReactTestUtils';
import { Home } from './home';
describe('home', () => {
var props, result;
beforeEach(() => {
props = {
auth: {
authenticated: true
},
application: {
started: true
},
banks: [],
items: [],
settings: {
qBankHost: "qbankhost"
},
assessment_offered: {
bankId: "bankId",
id: "offeredId"
},
locales: ['en']
};
result = TestUtils.renderIntoDocument(<Home {...props}/>);
});
it('renders', () => {
expect(ReactDOM.findDOMNode(result).textContent).toContain("Filter Tree");
});
});
|
module.exports = {
data: {
badguys: []
},
methods: {
generate_badguys: function () {
var amount = 1000
// generate code here
this.badguys = null // replace null with an array of objects
// this will be the structure of the generated code
// this is temporary data (more like a story to me)
// entities: [
// {
// id: 1,
// sprite: '@', // goodguy greg yay :D ggg (aka gennady gennadyevich golovkin)
// bind: 'player'
// },
// {
// id: 2,
// sprite: 'w', // badguy bruce boo :C bbb
// location: {
// x: 2,
// y: 2,
// z: 0
// },
// health: 1000,
// stamina: 40
// }
// ],
},
behavior_badguys: function () {
// if player is within x radius move postition of badguy 1 block closer to player
// if touching player, attack player
// upon death of baguy remove badguy from badguys array
}
}
}
|
/**
* DocuSign REST API
* The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
*
* OpenAPI spec version: v2.1
* Contact: devcenter@docusign.com
*
* NOTE: This class is auto generated. Do not edit the class manually and submit a new issue instead.
*
*/
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['ApiClient', 'model/UserInformation'], factory);
} else if (typeof module === 'object' && module.exports) {
// CommonJS-like environments that support module.exports, like Node.
module.exports = factory(require('../ApiClient'), require('./UserInformation'));
} else {
// Browser globals (root is window)
if (!root.Docusign) {
root.Docusign = {};
}
root.Docusign.NewUsersDefinition = factory(root.Docusign.ApiClient, root.Docusign.UserInformation);
}
}(this, function(ApiClient, UserInformation) {
'use strict';
/**
* The NewUsersDefinition model module.
* @module model/NewUsersDefinition
*/
/**
* Constructs a new <code>NewUsersDefinition</code>.
* @alias module:model/NewUsersDefinition
* @class
*/
var exports = function() {
var _this = this;
};
/**
* Constructs a <code>NewUsersDefinition</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:model/NewUsersDefinition} obj Optional instance to populate.
* @return {module:model/NewUsersDefinition} The populated <code>NewUsersDefinition</code> instance.
*/
exports.constructFromObject = function(data, obj) {
if (data) {
obj = obj || new exports();
if (data.hasOwnProperty('newUsers')) {
obj['newUsers'] = ApiClient.convertToType(data['newUsers'], [UserInformation]);
}
}
return obj;
}
/**
*
* @member {Array.<module:model/UserInformation>} newUsers
*/
exports.prototype['newUsers'] = undefined;
return exports;
}));
|
module.exports = function(config){
config.set({
basePath : '../',
files : [
'app/lib/angular/angular.js',
'app/lib/angular/angular-*.js',
'app/js/**/*.js',
'test/unit/**/*.js'
],
exclude : [
'app/lib/angular/angular-loader.js',
'app/lib/angular/*.min.js',
'app/lib/angular/angular-scenario.js'
],
autoWatch : true,
frameworks: ['jasmine'],
browsers : ['Firefox'],
plugins : [
'karma-junit-reporter',
'karma-chrome-launcher',
'karma-firefox-launcher',
'karma-script-launcher',
'karma-jasmine'
],
junitReporter : {
outputFile: 'test_out/unit.xml',
suite: 'unit'
}
});
};
|
module.exports = function(grunt) {
require('load-grunt-tasks')(grunt);
var debug = grunt.option('env') !== 'production';
grunt.config('env.' + grunt.option('env'), true);
grunt.config('clean', ['./client/build']);
grunt.config('browserify', {
options: {
debug: debug,
watch: true
},
app: {
files: [
{ src: './client/src/index.js', dest: './client/build/assets/index.js' }
]
}
});
grunt.config('uglify', {
scripts: {
src: './client/build/assets/index.js',
dest: './client/build/assets/index.min.js',
options: {
mangle: false
}
}
});
grunt.config('copy', {
html: {
src: './client/src/index.html',
dest: './client/build/index.html',
options: {
process: function(content, srcpath) {
return grunt.template.process(content);
}
}
}
});
grunt.config('less', {
styles: {
src: './client/src/styles.less',
dest: './client/build/assets/styles.css',
options: {
dumpLineNumbers: debug ? 'all' : false,
sourceMap: debug,
outputSourceFiles: debug,
cleancss: !debug
}
}
});
grunt.config('concurrent', {
options: {
logConcurrentOutput: true
},
develop: {
tasks: ['watch', 'nodemon']
}
});
grunt.config('nodemon', {
develop: {
script: './server/app',
options: {
watch: ['./server'],
env: {
NODE_ENV: 'development',
NODE_CONFIG_DIR: './server/config'
}
}
}
});
grunt.config('jshint', {
options: {
jshintrc: true
},
all: ['./Gruntfile.js', './client/src/**/*.js']
});
grunt.config('watch', {
html: {
files: ['./client/src/index.html'],
tasks: ['copy:html']
},
less: {
files: ['./client/src/**/*.less'],
tasks: ['less']
},
jshint: {
files: ['./Gruntfile.js', './client/src/**/*.js'],
tasks: ['jshint']
}
});
grunt.registerTask('develop', ['build', 'concurrent:develop']);
grunt.registerTask('build', ['clean', 'jshint', 'browserify:app', 'uglify', 'copy', 'less']);
grunt.registerTask('default', ['build']);
};
|
/**
* Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
const mocks = require('./moduleMocker');
const MS_IN_A_YEAR = 31536000000;
class FakeTimers {
constructor(global, maxLoops) {
this._global = global;
this._uuidCounter = 1;
this._maxLoops = maxLoops || 100000;
this.reset();
// Store original timer APIs for future reference
this._originalTimerAPIs = {
setTimeout: global.setTimeout,
clearTimeout: global.clearTimeout,
setInterval: global.setInterval,
clearInterval: global.clearInterval,
};
this._fakeTimerAPIs = {
setTimeout: mocks.getMockFn().mockImpl(
this._fakeSetTimeout.bind(this)
),
clearTimeout: mocks.getMockFn().mockImpl(
this._fakeClearTimer.bind(this)
),
setInterval: mocks.getMockFn().mockImpl(
this._fakeSetInterval.bind(this)
),
clearInterval: mocks.getMockFn().mockImpl(
this._fakeClearTimer.bind(this)
),
};
// If there's a process.nextTick on the global, mock it out
// (only applicable to node/node-emulating environments)
if (typeof global.process === 'object'
&& typeof global.process.nextTick === 'function') {
this._originalTimerAPIs.nextTick = global.process.nextTick;
this._fakeTimerAPIs.nextTick = mocks.getMockFn().mockImpl(
this._fakeNextTick.bind(this)
);
}
// If there's a global.setImmediate, mock it out
if (typeof global.setImmediate === 'function') {
this._originalTimerAPIs.setImmediate = global.setImmediate;
this._fakeTimerAPIs.setImmediate = mocks.getMockFn().mockImpl(
this._fakeSetImmediate.bind(this)
);
this._originalTimerAPIs.clearImmediate = global.clearImmediate;
this._fakeTimerAPIs.clearImmediate = mocks.getMockFn().mockImpl(
this._fakeClearImmediate.bind(this)
);
}
this.useFakeTimers();
// These globally-accessible function are now deprecated!
// They will go away very soon, so do not use them!
// Instead, use the versions available on the `jest` object
global.mockRunTicksRepeatedly = this.runAllTicks.bind(this);
global.mockRunTimersOnce = this.runOnlyPendingTimers.bind(this);
global.mockRunTimersToTime = this.runTimersToTime.bind(this);
global.mockRunTimersRepeatedly = this.runAllTimers.bind(this);
global.mockClearTimers = this.clearAllTimers.bind(this);
global.mockGetTimersCount = () => Object.keys(this._timers).length;
}
clearAllTimers() {
this._immediates.forEach(function(immediate) {
this._fakeClearImmediate(immediate.uuid);
}, this);
for (const uuid in this._timers) {
delete this._timers[uuid];
}
}
reset() {
this._cancelledTicks = {};
this._cancelledImmediates = {};
this._now = 0;
this._ticks = [];
this._immediates = [];
this._timers = {};
}
// Used to be called runTicksRepeatedly
runAllTicks() {
// Only run a generous number of ticks and then bail.
// This is just to help avoid recursive loops
let i;
for (i = 0; i < this._maxLoops; i++) {
const tick = this._ticks.shift();
if (tick === undefined) {
break;
}
if (!this._cancelledTicks.hasOwnProperty(tick.uuid)) {
// Callback may throw, so update the map prior calling.
this._cancelledTicks[tick.uuid] = true;
tick.callback();
}
}
if (i === this._maxLoops) {
throw new Error(
'Ran ' + this._maxLoops + ' ticks, and there are still more! ' +
'Assuming we\'ve hit an infinite recursion and bailing out...'
);
}
}
runAllImmediates() {
// Only run a generous number of immediates and then bail.
let i;
for (i = 0; i < this._maxLoops; i++) {
const immediate = this._immediates.shift();
if (immediate === undefined) {
break;
}
this._runImmediate(immediate);
}
if (i === this._maxLoops) {
throw new Error(
'Ran ' + this._maxLoops +
' immediates, and there are still more! Assuming ' +
'we\'ve hit an infinite recursion and bailing out...'
);
}
}
_runImmediate(immediate) {
if (!this._cancelledImmediates.hasOwnProperty(immediate.uuid)) {
// Callback may throw, so update the map prior calling.
this._cancelledImmediates[immediate.uuid] = true;
immediate.callback();
}
}
// Used to be called runTimersRepeatedly
runAllTimers() {
this.runAllTicks();
this.runAllImmediates();
// Only run a generous number of timers and then bail.
// This is just to help avoid recursive loops
let i;
for (i = 0; i < this._maxLoops; i++) {
const nextTimerHandle = this._getNextTimerHandle();
// If there are no more timer handles, stop!
if (nextTimerHandle === null) {
break;
}
this._runTimerHandle(nextTimerHandle);
// Some of the immediate calls could be enqueued
// during the previous handling of the timers, we should
// run them as well.
if (this._immediates.length) {
this.runAllImmediates();
}
}
if (i === this._maxLoops) {
throw new Error(
'Ran ' + this._maxLoops + ' timers, and there are still more! ' +
'Assuming we\'ve hit an infinite recursion and bailing out...'
);
}
}
// Used to be called runTimersOnce
runOnlyPendingTimers() {
this._immediates.forEach(this._runImmediate, this);
const timers = this._timers;
Object.keys(timers)
.sort(function(left, right) {
return timers[left].expiry - timers[right].expiry;
})
.forEach(this._runTimerHandle, this);
}
// Use to be runTimersToTime
runTimersToTime(msToRun) {
// Only run a generous number of timers and then bail.
// This is jsut to help avoid recursive loops
let i;
for (i = 0; i < this._maxLoops; i++) {
const timerHandle = this._getNextTimerHandle();
// If there are no more timer handles, stop!
if (timerHandle === null) {
break;
}
const nextTimerExpiry = this._timers[timerHandle].expiry;
if (this._now + msToRun < nextTimerExpiry) {
// There are no timers between now and the target we're running to, so
// adjust our time cursor and quit
this._now += msToRun;
break;
} else {
msToRun -= (nextTimerExpiry - this._now);
this._now = nextTimerExpiry;
this._runTimerHandle(timerHandle);
}
}
if (i === this._maxLoops) {
throw new Error(
'Ran ' + this._maxLoops + ' timers, and there are still more! ' +
'Assuming we\'ve hit an infinite recursion and bailing out...'
);
}
}
runWithRealTimers(cb) {
const hasNextTick =
typeof this._global.process === 'object'
&& typeof this._global.process.nextTick === 'function';
const hasSetImmediate = typeof this._global.setImmediate === 'function';
const prevSetTimeout = this._global.setTimeout;
const prevSetInterval = this._global.setInterval;
const prevClearTimeout = this._global.clearTimeout;
const prevClearInterval = this._global.clearInterval;
let prevNextTick;
let prevSetImmediate;
let prevClearImmediate;
if (hasNextTick) {
prevNextTick = this._global.process.nextTick;
}
if (hasSetImmediate) {
prevSetImmediate = this._global.setImmediate;
prevClearImmediate = this._global.clearImmediate;
}
this.useRealTimers();
let cbErr = null;
let errThrown = false;
try {
cb();
} catch (e) {
errThrown = true;
cbErr = e;
}
this._global.setTimeout = prevSetTimeout;
this._global.setInterval = prevSetInterval;
this._global.clearTimeout = prevClearTimeout;
this._global.clearInterval = prevClearInterval;
if (hasNextTick) {
this._global.process.nextTick = prevNextTick;
}
if (hasSetImmediate) {
this._global.setImmediate = prevSetImmediate;
this._global.clearImmediate = prevClearImmediate;
}
if (errThrown) {
throw cbErr;
}
}
useRealTimers() {
const hasNextTick =
typeof this._global.process === 'object'
&& typeof this._global.process.nextTick === 'function';
const hasSetImmediate = typeof this._global.setImmediate === 'function';
this._global.setTimeout = this._originalTimerAPIs.setTimeout;
this._global.setInterval = this._originalTimerAPIs.setInterval;
this._global.clearTimeout = this._originalTimerAPIs.clearTimeout;
this._global.clearInterval = this._originalTimerAPIs.clearInterval;
if (hasNextTick) {
this._global.process.nextTick = this._originalTimerAPIs.nextTick;
}
if (hasSetImmediate) {
this._global.setImmediate = this._originalTimerAPIs.setImmediate;
this._global.clearImmediate = this._originalTimerAPIs.clearImmediate;
}
}
useFakeTimers() {
const hasNextTick =
typeof this._global.process === 'object'
&& typeof this._global.process.nextTick === 'function';
const hasSetImmediate = typeof this._global.setImmediate === 'function';
this._global.setTimeout = this._fakeTimerAPIs.setTimeout;
this._global.setInterval = this._fakeTimerAPIs.setInterval;
this._global.clearTimeout = this._fakeTimerAPIs.clearTimeout;
this._global.clearInterval = this._fakeTimerAPIs.clearInterval;
if (hasNextTick) {
this._global.process.nextTick = this._fakeTimerAPIs.nextTick;
}
if (hasSetImmediate) {
this._global.setImmediate = this._fakeTimerAPIs.setImmediate;
this._global.clearImmediate = this._fakeTimerAPIs.clearImmediate;
}
}
_fakeClearTimer(uuid) {
if (this._timers.hasOwnProperty(uuid)) {
delete this._timers[uuid];
}
}
_fakeClearImmediate(uuid) {
this._cancelledImmediates[uuid] = true;
}
_fakeNextTick(callback) {
const args = [];
for (let ii = 1, ll = arguments.length; ii < ll; ii++) {
args.push(arguments[ii]);
}
const uuid = this._uuidCounter++;
this._ticks.push({
uuid,
callback: function() {
return callback.apply(null, args);
},
});
const cancelledTicks = this._cancelledTicks;
this._originalTimerAPIs.nextTick(function() {
if (!cancelledTicks.hasOwnProperty(uuid)) {
// Callback may throw, so update the map prior calling.
cancelledTicks[uuid] = true;
callback.apply(null, args);
}
});
}
_fakeSetImmediate(callback) {
const args = [];
for (let ii = 1, ll = arguments.length; ii < ll; ii++) {
args.push(arguments[ii]);
}
const uuid = this._uuidCounter++;
this._immediates.push({
uuid,
callback: function() {
return callback.apply(null, args);
},
});
const cancelledImmediates = this._cancelledImmediates;
this._originalTimerAPIs.setImmediate(function() {
if (!cancelledImmediates.hasOwnProperty(uuid)) {
// Callback may throw, so update the map prior calling.
cancelledImmediates[uuid] = true;
callback.apply(null, args);
}
});
return uuid;
}
_fakeSetInterval(callback, intervalDelay) {
if (intervalDelay === undefined || intervalDelay === null) {
intervalDelay = 0;
}
const args = [];
for (let ii = 2, ll = arguments.length; ii < ll; ii++) {
args.push(arguments[ii]);
}
const uuid = this._uuidCounter++;
this._timers[uuid] = {
type: 'interval',
callback: function() {
return callback.apply(null, args);
},
expiry: this._now + intervalDelay,
interval: intervalDelay,
};
return uuid;
}
_fakeSetTimeout(callback, delay) {
if (delay === undefined || delay === null) {
delay = 0;
}
const args = [];
for (let ii = 2, ll = arguments.length; ii < ll; ii++) {
args.push(arguments[ii]);
}
const uuid = this._uuidCounter++;
this._timers[uuid] = {
type: 'timeout',
callback: function() {
return callback.apply(null, args);
},
expiry: this._now + delay,
interval: null,
};
return uuid;
}
_getNextTimerHandle() {
let nextTimerHandle = null;
let uuid;
let soonestTime = MS_IN_A_YEAR;
let timer;
for (uuid in this._timers) {
timer = this._timers[uuid];
if (timer.expiry < soonestTime) {
soonestTime = timer.expiry;
nextTimerHandle = uuid;
}
}
return nextTimerHandle;
}
_runTimerHandle(timerHandle) {
const timer = this._timers[timerHandle];
if (!timer) {
return;
}
switch (timer.type) {
case 'timeout':
const callback = timer.callback;
delete this._timers[timerHandle];
callback();
break;
case 'interval':
timer.expiry = this._now + timer.interval;
timer.callback();
break;
default:
throw new Error('Unexpected timer type: ' + timer.type);
}
}
}
module.exports = FakeTimers;
|
const { expect } = require('chai');
const path = require('path');
const output = require('./output');
describe('Webpack -> Output', () => {
it('Builds the output object', () => {
const BUILD = 'BUILD';
const BUNDLE = 'BUNDLE';
const ROOT = '../ROOT';
const VENDOR = false;
const configuration = {
build: { vendor: VENDOR },
output: { app: BUNDLE },
paths: { build: BUILD, root: ROOT },
};
const expected = {
filename: `./${BUNDLE}`,
library: '',
path: path.join(__dirname, ROOT, BUILD),
publicPath: '/',
};
expect(output(configuration)).to.deep.equal(expected);
});
it('Adds the vendor library when it is a vendor build', () => {
const BUILD = 'BUILD';
const BUNDLE = 'BUNDLE';
const ROOT = '../ROOT';
const VENDOR = true;
const configuration = {
build: { vendor: VENDOR },
output: { app: BUNDLE },
paths: { build: BUILD, root: ROOT },
};
const expected = {
filename: `./${BUNDLE}`,
library: 'vendor',
path: path.join(__dirname, ROOT, BUILD),
publicPath: '/',
};
expect(output(configuration)).to.deep.equal(expected);
});
});
|
import defprotocol from '../defprotocol'
import Function from '../types/Function'
const IPersistentStack = defprotocol({
peek: Function,
pop: Function,
push: Function
})
export default IPersistentStack
|
'use strict';
var path = require('path');
module.exports = function (config, storages) {
config.port = process.env.MEDIA_SERVICE_PORT || 80;
config.autoRestart = true;
config.progressive = true;
config.metadata = false;
config.quality = 90;
config.webp = true;
// access control
config.enableAccessControl = true;
config.accessControl = {
// [ '192.168.*.*', '127.0.0.1' ]
write: [ '127.0.0.1' ],
read: [ '127.0.0.1' ]
};
// log
config.logDir = process.env.MEDIA_SERVICE_LOG_DIR || path.join(__dirname, 'log');
config.logBackCopies = process.env.MEDIA_SERVICE_LOG_BACK_COPIES || 3;
// size
config.sizes = {
'small-avatar': '16x16:center',
'avatar': '120x120:center',
'big-avatar': '240x240:center'
};
// mobile detect
config.enableMobileDetect = true;
config.mobileSizes = {
phone: {
'avatar': 'small-avatar',
'big-avatar': 'avatar'
}
};
// storages
var localStorage = new storages.LocalStorage('local', {
baseUrl: 'http://localhost',
dir: path.join(__dirname, 'medias')
});
config.storages = [
localStorage
];
};
|
function EditWorksCtrl($scope, QuoteService) {
QuoteService.findOrCreateForWorks($scope);
$scope.remove = function(idx) {
$scope.utils.remove($scope.editing.works, idx);
$scope.qot.initRowNumbers($scope.editing.works);
$scope.qot.updateWorksTotal($scope, $scope.editing);
}
$scope.add = function(idx) {
idx = $scope.utils.add($scope.editing.works, $scope.qot.newWork(), idx);
$scope.qot.initRowNumbers($scope.editing.works);
$scope.loadWork(idx);
$scope.focus('work_' + idx);
}
$scope.down = function(idx) {
$scope.utils.down($scope.editing.works, idx);
$scope.qot.initRowNumbers($scope.editing.works);
}
$scope.up = function(idx) {
$scope.utils.up($scope.editing.works, idx);
$scope.qot.initRowNumbers($scope.editing.works);
}
$scope.loadWork = function(idx) {
$scope.$log.info("load Work edit works " + idx);
$scope.work = $scope.editing.works[idx];
}
}
EditWorksCtrl.$inject = ['$scope', 'QuoteService'];
|
var assert = require('chai').assert;
var user = require('../util/models/user');
var util = require('./rest-builder-util');
var putObj = {
key: 'value'
};
var putData = {
q: putObj
};
describe('RestBuilder', function() {
describe('definePut', function() {
util.setUp();
describe('no processors', function() {
it('should call db.del', function(done) {
this.rb.definePut('users', user, [], []);
this.client.put('/users/1', putData, function(err, req, res) {
assert.ifError(err);
util.mockDB.update.assertCalledOnceWithArgsIncluding(
['1', user, putObj]
);
done();
});
});
});
describe('with preprocessors', function () {
it('should call a single preprocessor', function(done) {
var mockPre = util.getMockPre();
this.rb.definePut('users', user, [mockPre], []);
this.client.put('/users/1', putData, function(err, req, res) {
mockPre.assertCalled('should call preprocessors');
assert.ifError(err);
util.mockDB.update.assertCalledOnceWithArgsIncluding(
['1', user, putObj]
);
done();
});
});
it('should call all the preprocessors', function (done) {
var mockPre = util.getMockPre();
var _mockPre = util.getMockPre();
this.rb.definePut('users', user, [mockPre, _mockPre], []);
this.client.put('/users/1', putData, function(err, req, res) {
mockPre.assertCalled('should call first preprocessor');
_mockPre.assertCalled('should call second preprocessor');
assert.ifError(err);
util.mockDB.update.assertCalledOnceWithArgsIncluding(
['1', user, putObj]
);
done();
});
});
});
});
});
|
'use strict';
angular.module('myApp.list-downloading', [
'ngRoute'
])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/list-downloading', {
templateUrl: 'list-downloading/list-downloading.html',
controller: 'ListDownloadingCtrl'
});
}])
.controller('ListDownloadingCtrl', ['$rootScope', '$scope', function($rootScope, $scope) {
$scope.files = $rootScope.listFiles.downloading;
}]);
|
$(document).ready(function(){
$('.page-add-gallery .form-colors [data-toggle="buttons"] .btn-color').click(function(){
if($(this).hasClass('active')) {
// alert('active');
}else {
if($('.page-add-gallery .form-colors [data-toggle="buttons"] .active').length >= 3) {
event.stopPropagation();
}
// alert('NOT active');
}
});
});
|
import Ember from 'ember';
import AuthenticatedRouteMixin from 'ember-simple-auth/mixins/authenticated-route-mixin';
export default Ember.Route.extend(AuthenticatedRouteMixin, {
model() {
return this.store.query('order', {
filter: { simple: { active: false } }
});
},
renderTemplate(controller, model) {
this.render('orders.index', { model });
}
});
|
import { combineReducers } from 'redux'
import {
FETCH_NEWS,
FETCH_NEWS_FULFILLED,
FETCH_NEWS_REJECTED
} from '../actions/news'
import {
FETCH_STORY,
FETCH_STORY_REJECTED,
FETCH_STORY_FULFILLED
} from '../actions/story'
import { CLOSE_DIALOG } from '../actions/dialog'
const isFetching = (state = false, action) => {
switch (action.type) {
case FETCH_NEWS:
case FETCH_STORY:
return true
case FETCH_NEWS_FULFILLED:
case FETCH_STORY_FULFILLED:
return false
default:
return state
}
}
const error = (state = false, action) => {
switch (action.type) {
case FETCH_NEWS_REJECTED:
case FETCH_STORY_REJECTED:
return true
case CLOSE_DIALOG:
return false
default:
return state
}
}
const msg = (state = '', action) => {
switch (action.type) {
case FETCH_NEWS_REJECTED:
case FETCH_STORY_REJECTED:
return action.payload || ''
default:
return state
}
}
const status = combineReducers({
isFetching,
error,
msg
})
export default status
|
"use strict";
/* globals AccountsAnonymous, AccountsMultiple, Hook */
Accounts.registerLoginHandler("anonymous", function(options) {
if (!options || !options.anonymous || Meteor.userId()) {
return undefined;
}
var newUserId = Accounts.insertUserDoc(options, {});
return {
userId: newUserId
};
});
AccountsAnonymous._onAbandonedHook = new Hook({
bindEnvironment: false,
debugPrintExceptions: "AccountsAnonymous.onAbandoned callback"
});
AccountsAnonymous.onAbandoned = function(func) {
var self = this;
return self._onAbandonedHook.register(func);
};
var callbackSet = {
onSwitch: function(attemptingUser /* , attempt (unused) */) {
if (isAnonymous(attemptingUser)) {
AccountsAnonymous._onAbandonedHook.each(function(callback) {
callback(attemptingUser);
return true;
});
}
}
};
AccountsAnonymous._init = function() {
AccountsMultiple.register(callbackSet);
};
AccountsAnonymous._init();
function isAnonymous(user) {
// A user is anonymous if they don't have any services other than "resume"
return (user.services && _.size(user.services) === 1 && user.services.resume);
}
|
import React, { Component } from 'react'
import BodySection1 from './BodySection1'
import BodySection2 from './BodySection2'
import BodySection3 from './BodySection3'
import { Link } from 'react-router'
import injectTapEventPlugin from 'react-tap-event-plugin';
import { Parallax } from 'react-parallax';
class Body extends Component {
render(){
return(
<Parallax bgImage="assets/1.jpg" width = {100} strength={400}>
<div className="generic-center dummy-height">
<BodySection1 />
<p></p>
<BodySection2 />
<p></p>
<BodySection3 />
</div>
</Parallax>
)
}
}
export default Body
|
'use strict';
var fs = require('fs');
var path = require('path');
function numFiles(dir, items, callback) {
var total = items.length;
var files = 0;
var completed = 0;
if (total === 0) {
callback(null, 0);
}
items.forEach(function(item) {
fs.stat(path.join(dir, item), function(err, stats) {
if (err) {
return callback(err);
}
if (stats && stats.isFile()) {
++files;
}
++completed;
if (completed === total) {
callback(null, files);
}
});
});
}
/**
* Count the number of files in a directory.
* @param {string} dir Path to directory.
* @param {function(Error, number)} callback Callback.
*/
module.exports = exports = function(dir, callback) {
fs.readdir(dir, function(err, items) {
if (err) {
return callback(err);
}
numFiles(dir, items, callback);
});
};
|
/**
* Created by intelligrape on 11/3/16.
*/
describe('Unit : MediaPlayerPluginWidget Home Controller', function () {
beforeEach(module('MediaPlayerPluginWidget'));
var $controller, $scope, WidgetHome, $routeParams, Buildfire,rootScope;
beforeEach(inject(function (_$controller_, _$rootScope_, _Buildfire_) {
$controller = _$controller_;
$scope = _$rootScope_.$new();
Buildfire = _Buildfire_;
rootScope=_$rootScope_;
WidgetHome = $controller('WidgetHomeCtrl', {
$scope: $scope,
$routeParams: $routeParams,
media: {id: '1', data: {topImage: "demo.png",audioUrl:"abc.mp3"}},
Buildfire: Buildfire
});
}));
describe('Unit : units should be Defined', function () {
it('it should pass if WidgetHome is defined', function () {
expect(WidgetHome).not.toBeUndefined();
});
it('it should pass if Buildfire is defined', function () {
expect(Buildfire).not.toBeUndefined();
});
});
describe('Unit : playTrack method should be Defined', function () {
it('it should pass if playTrack is defined', function () {
expect(WidgetHome.playTrack).not.toBeUndefined();
});
it('it should pass if playTrack method calling', function () {
WidgetHome.currentTrack={title:'track1',url:'track1.mp3'};
WidgetHome.playing=false;
WidgetHome.playTrack();
rootScope.$digest();
expect(WidgetHome.playing).toEqual(true);
});
it('it should pass if playTrack method calling if track is paused', function () {
WidgetHome.currentTrack={title:'track1',url:'track1.mp3'};
WidgetHome.playing=false;
WidgetHome.paused=true;
WidgetHome.playTrack();
rootScope.$digest();
expect(WidgetHome.playing).toEqual(true);
});
});
describe('Unit : playlistPlay method should be Defined', function () {
it('it should pass if playTrack is defined', function () {
expect(WidgetHome.playlistPlay).not.toBeUndefined();
});
it('it should pass if playlistPlay method calling', function () {
WidgetHome.currentTrack={title:'track1',url:'track1.mp3'};
WidgetHome.playing=false;
WidgetHome.playlistPlay({title:'track1',url:'track1.mp3'});
rootScope.$digest();
expect(WidgetHome.playing).toEqual(true);
});
});
describe('Unit : pauseTrack method should be Defined', function () {
it('it should pass if pauseTrack is defined', function () {
expect(WidgetHome.pauseTrack).not.toBeUndefined();
});
it('it should pass if pauseTrack method calling', function () {
WidgetHome.currentTrack={title:'track1',url:'track1.mp3'};
WidgetHome.playing=true;
WidgetHome.pauseTrack({title:'track1',url:'track1.mp3'});
rootScope.$digest();
expect(WidgetHome.playing).toEqual(false);
});
});
describe('Unit : playlistPause method should be Defined', function () {
it('it should pass if playlistPause is defined', function () {
expect(WidgetHome.playlistPause).not.toBeUndefined();
});
it('it should pass if playlistPause method calling', function () {
WidgetHome.currentTrack={title:'track1',url:'track1.mp3'};
WidgetHome.playing=true;
WidgetHome.playlistPause({title:'track1',url:'track1.mp3'});
rootScope.$digest();
expect(WidgetHome.playing).toEqual(false);
});
});
describe('Unit : forward method should be Defined', function () {
it('it should pass if forward is defined', function () {
expect(WidgetHome.forward).not.toBeUndefined();
});
it('it should pass if forward method calling', function () {
WidgetHome.currentTrack={title:'track1',url:'track1.mp3',duration:20};
WidgetHome.currentTime=5;
WidgetHome.forward();
rootScope.$digest();
expect(WidgetHome.currentTime).toEqual(5);
});
it('it should pass if forward method calling', function () {
WidgetHome.currentTrack={title:'track1',url:'track1.mp3',duration:5};
WidgetHome.currentTime=5;
WidgetHome.forward();
rootScope.$digest();
expect(WidgetHome.currentTime).toEqual(5);
});
});
describe('Unit : backward method should be Defined', function () {
it('it should pass if backward is defined', function () {
expect(WidgetHome.backward).not.toBeUndefined();
});
it('it should pass if forward method calling', function () {
WidgetHome.currentTrack={title:'track1',url:'track1.mp3',duration:20};
WidgetHome.currentTime=5;
WidgetHome.backward();
rootScope.$digest();
expect(WidgetHome.currentTime).toEqual(5);
});
it('it should pass if forward method calling', function () {
WidgetHome.currentTrack={title:'track1',url:'track1.mp3',duration:20};
WidgetHome.currentTime=7;
WidgetHome.backward();
rootScope.$digest();
expect(WidgetHome.currentTime).toEqual(7);
});
});
describe('Unit : addToPlaylist method should be Defined', function () {
it('it should pass if addToPlaylist is defined', function () {
expect(WidgetHome.addToPlaylist).not.toBeUndefined();
});
it('it should pass if addToPlaylist method calling', function () {
WidgetHome.currentTrack={title:'track1',url:'track1.mp3',duration:20};
WidgetHome.addToPlaylist();
rootScope.$digest();
});
});
describe('Unit : shufflePlaylist method should be Defined', function () {
it('it should pass if forward is defined', function () {
expect(WidgetHome.shufflePlaylist).not.toBeUndefined();
});
it('it should pass if shufflePlaylist method calling', function () {
WidgetHome.settings={shufflePlaylist:true};
WidgetHome.shufflePlaylist();
rootScope.$digest();
expect(WidgetHome.settings.shufflePlaylist).toEqual(false);
});
});
describe('Unit : loopPlaylist method should be Defined', function () {
it('it should pass if loopPlaylist is defined', function () {
expect(WidgetHome.loopPlaylist).not.toBeUndefined();
});
it('it should pass if loopPlaylist method calling', function () {
WidgetHome.settings={loopPlaylist:true};
WidgetHome.loopPlaylist();
rootScope.$digest();
expect(WidgetHome.settings.loopPlaylist).toEqual(false);
});
});
describe('Unit : changeVolume method should be Defined', function () {
it('it should pass if changeVolume is defined', function () {
expect(WidgetHome.changeVolume).not.toBeUndefined();
});
it('it should pass if changeVolume method calling', function () {
WidgetHome.changeVolume(50);
rootScope.$digest();
});
});
describe('Unit : changeTime method should be Defined', function () {
it('it should pass if changeTime is defined', function () {
expect(WidgetHome.changeTime).not.toBeUndefined();
});
it('it should pass if changeTime method calling', function () {
WidgetHome.changeTime(50);
rootScope.$digest();
});
});
describe('Unit : getSettings method should be Defined', function () {
it('it should pass if getSettings is defined', function () {
expect(WidgetHome.getSettings).not.toBeUndefined();
});
it('it should pass if getSettings method calling', function () {
WidgetHome.getSettings(false);
rootScope.$digest();
});
});
describe('Unit : removeTrackFromPlayList method should be Defined', function () {
it('it should pass if removeTrackFromPlayList is defined', function () {
expect(WidgetHome.removeTrackFromPlayList).not.toBeUndefined();
});
it('it should pass if removeTrackFromPlayList method calling', function () {
//WidgetHome.removeTrackFromPlayList(50);
rootScope.$digest();
});
});
describe('Unit : removeFromPlaylist method should be Defined', function () {
it('it should pass if removeFromPlaylist is defined', function () {
expect(WidgetHome.removeFromPlaylist).not.toBeUndefined();
});
it('it should pass if removeFromPlaylist method calling', function () {
WidgetHome.playList=[{title:'track1',url:'track1.mp3'}];
//WidgetHome.removeFromPlaylist({title:'track1',url:'track1.mp3'});
rootScope.$digest();
});
});
describe('Unit : setSettings method should be Defined', function () {
it('it should pass if setSettings is defined', function () {
expect(WidgetHome.setSettings).not.toBeUndefined();
});
it('it should pass if setSettings method calling', function () {
WidgetHome.setSettings({loopPlaylist:true, shufflePlaylist:true});
rootScope.$digest();
});
});
describe('Unit : addEvents method should be Defined', function () {
it('it should pass if addEvents is defined', function () {
expect(WidgetHome.addEvents).not.toBeUndefined();
});
it('it should pass if addEvents method calling', function () {
WidgetHome.addEvents({},{},true,{});
rootScope.$digest();
});
});
describe('Unit : playlistPlayPause method should be Defined', function () {
it('it should pass if playlistPlayPause is defined', function () {
expect(WidgetHome.playlistPlayPause).not.toBeUndefined();
});
it('it should pass if playlistPlayPause method calling', function () {
WidgetHome.playlistPlayPause({});
rootScope.$digest();
});
it('it should pass if playlistPlayPause method calling', function () {
WidgetHome.playlistPlayPause({playing:true});
rootScope.$digest();
});
});
describe('Unit : openMoreInfoOverlay method should be Defined', function () {
it('it should pass if addEvents method calling', function () {
WidgetHome.openMoreInfoOverlay();
WidgetHome.closeSettingsOverlay();
WidgetHome.closePlayListOverlay();
WidgetHome.closeMoreInfoOverlay();
rootScope.$digest();
});
});
});
|
module.exports = (Bluebird) => {
Bluebird.prototype.spread = function spread(fn) {
return this.all().then(results => fn(...results));
};
}
|
const types = require('./packages/mjml-core/lib/types/type.js')
const enumtype = types.initializeType('enum(top,left,center)')
const colortype = types.initializeType('color')
const booleantype = types.initializeType('boolean')
const unittype = types.initializeType('unit(px,%){1,3}')
const stringtype = types.initializeType('string')
console.log(stringtype)
const output = (t) => { console.log(`Type: ${t.constructor.name} — Value: ${t.value} — isValid: ${t.isValid()} ${t.getErrorMessage()}`) }
[new colortype('grey'),
new colortype('rgba(0,255,3,0.3)'),
new colortype('#DDF'),
new colortype('#DF'),
new booleantype('true'),
new booleantype('false'),
new booleantype('banana'),
new unittype('10 20px 20'),
new unittype('10px 20px 20px'),
new unittype('10px'),
new unittype('10%'),
new unittype('10px 10px'),
new unittype('0'),
new stringtype('hello world'),
].map(output)
|
Calendula.addLocale("it",{months:["gennaio","febbraio","marzo","aprile","maggio","giugno","luglio","agosto","settembre","ottobre","novembre","dicembre"],shortDayNames:["Do","Lu","Ma","Me","Gi","Ve","Sa"],dayNames:["Domenica","Lunedì","Martedì","Mercoledì","Giovedì","Venerdì","Sabato"],today:"Oggi",firstWeekday:1});
|
$(function () {
// There is a class name set on the nav-item that is the same as path
// else assume we are on startpage
currentpageclass = window.location.pathname.replace(/^\/|\/$/g, "");
// If no path then assume we are on startpage
if (currentpageclass == "") {
$('.startsida').addClass('active');
} else {
$('.' + currentpageclass).addClass('active');
}
});
|
define(['../string/typecast', '../lang/isString', '../lang/isArray', '../object/hasOwn'], function (typecast, isString, isArray, hasOwn) {
/**
* Decode query string into an object of keys => vals.
*/
function decode(queryStr, shouldTypecast) {
var queryArr = (queryStr || '').replace('?', '').split('&'),
count = -1,
length = queryArr.length,
obj = {},
item, pValue, pName, toSet;
while (++count < length) {
item = queryArr[count].split('=');
pName = item[0];
if (!pName || !pName.length){
continue;
}
pValue = shouldTypecast === false ? item[1] : typecast(item[1]);
toSet = isString(pValue) ? decodeURIComponent(pValue) : pValue;
if (hasOwn(obj,pName)){
if(isArray(obj[pName])){
obj[pName].push(toSet);
} else {
obj[pName] = [obj[pName],toSet];
}
} else {
obj[pName] = toSet;
}
}
return obj;
}
return decode;
});
|
"use strict";
module.exports = {
array: require('./array'),
debug: require("./debug"),
livereload: require("./livereload"),
log: require("./log"),
module: require("./module"),
regexp: require("./regexp")
};
|
var listen = require('./client/display.js').listen
var $ = require('jquery')
$(() => {
listen()
})
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = {
name: 'attribute-sets',
connection: 'default',
useAuth: true,
useACL: true,
useBuildInEndPoints: ['list', 'read', 'create', 'edit', 'delete'],
schema: {
title: {
type: 'string',
selectable: true,
changable: true,
sortable: true,
filters: ['substring'],
required: true,
unique: true
},
attributes: {
type: 'array',
required: true,
selectable: true,
changable: true,
connectWith: 'attributes',
items: {
type: 'id'
}
}
}
};
|
import * as CES from 'ces';
import * as BABYLON from '../lib/babylon';
import { c_light } from '../components/c_light';
/**
* ...
* @author Brendon Smith
* http://seacloud9.org
* LightWeight 3D System Design engine
*/
export class e_light{
constructor(_defaults = null){
this._defaults = _defaults == null ? this.defaults(): _defaults;
this.entity = new CES.Entity();
this.init();
}
static defaults(){
return{
_type:'Hemispheric',
e_type:'e_light',
name:'Hemispheric',
_position:'0,0,0',
_rotation:'0,0,0',
_material:{
_alpah:1.0,
_texture:null,
_uScale: 1.0,
_vScale: 1.0,
_backFaceCulling: true,
_vOffset: 0.0,
_uOffset: 0.0,
_hasAlpha:false,
_diffuseColor: '127, 0, 140',
},
_scene:{}
}
}
init(){
this.entity.addComponent(new c_light(this._defaults));
}
}
|
export function assertIsString(x, name) {
if (typeof x !== "string") {
throw new Error(`Expected ${name} to be a string, got ${x}.`);
}
}
export function assertIsNonEmptyString(x) {
if (typeof x !== "string" || x.length === 0) {
throw new Error(`Expected a non-empty string, got ${x}`);
}
}
export function assertIsValidHorizontalAlign(x) {
switch (x) {
case "left": return;
case "center": return;
case "right": return;
default: throw new Error(`Unexpected horizontalAlign (acceptable values are "left", "center", and "right"); got ${x}`);
}
}
export function assertIsValidVerticalAlign(x) {
switch (x) {
case "top": return;
case "middle": return;
case "bottom": return;
default: throw new Error(`Unexpected verticalAlign (acceptable values are "top", "middle", and "bottom"); got ${x}`);
}
}
export function assertIsNumber(x, name) {
if (typeof x !== "number") {
throw new Error(`Expected ${name} to be a number, got ${x}`);
}
}
export function assertIsBoolean(x, name) {
if (typeof x !== "boolean") {
throw new Error(`Expected ${name} to be a boolean, got ${x}`);
}
}
export function assertIsPositiveNumber(x, name) {
if (typeof x !== "number") {
throw new Error(`Expected ${name} to be a number, got ${x}`);
}
if (x <= 0) {
throw new Error(`Expected ${name} to be positive, got ${x}`);
}
}
export function assertIsNonNegativeNumber(x, name) {
if (typeof x !== "number") {
throw new Error(`Expected ${name} to be a number, got ${x}`);
}
if (x < 0) {
throw new Error(`Expected ${name} to be non-negative, got ${x}`);
}
}
|
{
("use strict");
var HTMLElement = scope.wrappers.HTMLElement;
var registerWrapper = scope.registerWrapper;
var unwrap = scope.unwrap;
var rewrap = scope.rewrap;
var OriginalHTMLImageElement = window.HTMLImageElement;
function HTMLImageElement(node) {
HTMLElement.call(this, node);
}
HTMLImageElement.prototype = Object.create(HTMLElement.prototype);
registerWrapper(
OriginalHTMLImageElement,
HTMLImageElement,
document.createElement("img")
);
function Image(width, height) {
if (!(this instanceof Image)) {
throw new TypeError(
"DOM object constructor cannot be called as a function."
);
}
var node = unwrap(document.createElement("img"));
HTMLElement.call(this, node);
rewrap(node, this);
if (width !== undefined) node.width = width;
if (height !== undefined) node.height = height;
}
Image.prototype = HTMLImageElement.prototype;
scope.wrappers.HTMLImageElement = HTMLImageElement;
scope.wrappers.Image = Image;
}
|
'use strict';
import Immutable from 'immutable';
export default {
DEFAULT_STATE: Immutable.fromJS({
channels: [],
activeChannel: null,
users: [],
user: null,
messages: []
})
/*
DEFAULT_STATE: Immutable.fromJS({
channels: [
{id: 1, name: 'channel 1'},
{id: 2, name: 'channel 2'},
{id: 3, name: 'channel 3'},
{id: 4, name: 'channel 4'}
],
activeChannel: 1,
users: [
{id: 1, name: 'Jiri Vopolka'},
{id: 2, name: 'Vladimir Gorej'},
{id: 3, name: 'Dmitry Druganov'}
],
user: 3,
messages: [
{
id: '6c84fb90-12c4-11e1-840d-7b25c5ee775a',
channel: 1,
user: 1,
body: 'message body 1, channel 1',
created: '2016-02-03T14:03:02.782Z'
},
{
id: 'cd278f50-cb8c-11e5-b5a4-f1075ef8465d',
channel: 1,
user: 2,
body: 'message body 2, channel 1',
created: '2016-02-03T14:03:02.782Z'
},
{
id: 'fee79d00-cb8c-11e5-b5a4-f1075ef8465d',
channel: 1,
user: 1,
body: 'message body 3, channel 1',
created: '2016-02-03T14:03:02.782Z'
},
{
id: 'dcfdaae0-cb8c-11e5-b5a4-f1075ef8465d',
channel: 2,
user: 2,
body: 'message body 4, channel 2',
created: '2016-02-03T14:03:02.782Z'
},
{
id: 'f4f9a6d0-cb8c-11e5-b5a4-f1075ef8465d',
channel: 2,
user: 3,
body: 'message body 5, channel 2',
created: '2016-02-03T14:03:02.782Z'
}
]
})
*/
};
|
var should = require('should')
var Store = require('../../../store/postgres')
describe('Postgres: UUID Key', function() {
var store
var database = 'uuid_key_test'
before(function(next) {
this.timeout(5000)
beforePG(
database,
[
'CREATE EXTENSION IF NOT EXISTS \\"uuid-ossp\\"',
'CREATE TABLE uuid_tests (id uuid not null primary key default uuid_generate_v1(), another_column varchar(255))'
],
next
)
})
before(function() {
store = new Store({
host: 'localhost',
type: 'postgres',
database: database,
user: 'postgres',
password: ''
})
store.Model('UuidTest', function() {})
})
after(function(next) {
afterPG(database, next)
})
it('attribute id is type uuid', function() {
return store.ready(function() {
var UuidTest = store.Model('UuidTest')
UuidTest.definition.attributes.id.type.name.should.be.equal('uuid')
})
})
it('new() returns a null id (uuid)', function() {
return store.ready(function() {
var UuidTest = store.Model('UuidTest')
var test = new UuidTest({ another_column: 'i am setting uuid' })
should.not.exist(test.id)
})
})
it('create() returns a new id (uuid)', function() {
return store.ready(function() {
var UuidTest = store.Model('UuidTest')
var test = new UuidTest({ another_column: 'i am setting uuid' })
return test.save().then(function() {
should.exist(test.id)
})
})
})
})
|
var searchData=
[
['root_279',['root',['../structbwRTree__t.html#ad4566d3fdd23ac4918104d23c77a7ddb',1,'bwRTree_t']]],
['rootoffset_280',['rootOffset',['../structbwRTree__t.html#aa3e57a494e0c45d56dca1de0939e8197',1,'bwRTree_t']]],
['runningwidthsum_281',['runningWidthSum',['../structbwWriteBuffer__t.html#a395634c6f60756abb87013a11f68b293',1,'bwWriteBuffer_t']]]
];
|
/**
* Extensions provide means of extending the page controllers with additional
* managed state and logic.
*
* An extension has access to the current route parameters, specify the
* resources to load when the page is loading or being updated, may intercept
* event bus events and modify the state of the page just like an ordinary
* controller, except that the modifications are restricted to the state fields
* which the extension explicitly specifies using its
* {@link Extension#getAllowedStateKeys} method.
*
* All extensions to be used on a page must be added to the current controller
* before the controller is initialized. After that, the extensions will go
* through the same lifecycle as the controller.
*
* @interface
*/
export default class Extension {
/**
* Callback for initializing the controller extension after the route
* parameters have been set on this extension.
*
* @return {(Promise<undefined>|undefined)}
*/
init() {}
/**
* Finalization callback, called when the controller is being discarded by
* the application. This usually happens when the user navigates to a
* different URL.
*
* This method is the lifecycle counterpart of the {@link Extension#init}
* method.
*
* The extension should release all resources obtained in the
* {@link Extension#init} method. The extension must release any resources
* that might not be released automatically when the extensions's instance
* is destroyed by the garbage collector.
*
* @return {(Promise<undefined>|undefined)}
*/
destroy() {}
/**
* Callback for activating the extension in the UI. This is the last
* method invoked during controller (and extensions) initialization, called
* after all the promises returned from the {@link Extension#load} method have
* been resolved and the controller has configured the meta manager.
*
* The extension may register any React and DOM event listeners in this
* method. The extension may start receiving event bus event after this
* method completes.
*
* @return {(Promise<undefined>|undefined)}
*/
activate() {}
/**
* Callback for deactivating the extension in the UI. This is the first
* method invoked during extension deinitialization. This usually happens
* when the user navigates to a different URL.
*
* This method is the lifecycle counterpart of the {@link Extension#activate}
* method.
*
* The extension should deregister listeners registered and release all
* resources obtained in the {@link Extension#activate} method.
*
* @return {(Promise<undefined>|undefined)}
*/
deactivate() {}
/**
* Callback the extension uses to request the resources it needs to render
* its related parts of the view. This method is invoked after the
* {@link Extension#init} method.
*
* The extension should request all resources it needs in this method, and
* represent each resource request as a promise that will resolve once the
* resource is ready for use (these can be data fetched over HTTP(S),
* database connections, etc).
*
* The method must return a plain flat object. The field names of the
* object identify the resources being fetched and prepared, each value
* must be either the resource (e.g. view configuration or a value
* retrieved synchronously) or a Promise that will resolve to the resource.
*
* The IMA will use the object to set the state of the controller.
*
* Any returned promise that gets rejected will redirect the application to
* the error page. The error page that will be used depends on the status
* code of the error.
*
* @return {(Promise<Object<string, (Promise|*)>>|Object<string, (Promise|*)>)}
* A map object of promises resolved when all resources the controller
* requires are ready. The resolved values will be pushed to the
* controller's state.
*/
load() {}
/**
* Callback for updating the extension after a route update. This method
* is invoked if the current route has the `onlyUpdate` flag set to `true` and
* the current controller and view match those used by the previously active
* route, or, the `onlyUpdate` option of the current route is a callback and
* returned `true`.
*
* The method must return an object with the same semantics as the result
* of the {@link Extension#load} method. The controller's state will then be
* patched by the returned object.
*
* The other extension lifecycle callbacks ({@link Extension#init},
* {@link Extension#load}, {@link Extension#activate},
* {@link Extension#deactivate}, {@link Extension#deinit}) are not call in
* case this method is used.
*
* @param {Object<string, string>=} [prevParams={}] Previous route
* parameters.
* @return {(Promise<Object<string, (Promise|*)>>|Object<string, (Promise|*)>)}
* A map object of promises resolved when all resources the controller
* requires are ready. The resolved values will be pushed to the
* controller's state.
*/
update() {}
/**
* Patches the state of the controller using this extension by using the
* provided object by copying the provided patch object fields to the
* controller's state object.
*
* Note that the state is not patched recursively but by replacing the
* values of the top-level fields of the state object.
*
* Note that the extension may modify only the fields of the state that it
* has specified by its {@link Extension#getAllowedStateKeys} method.
*
* @param {Object<string, *>} statePatch Patch of the controller's state to
* apply.
*/
setState() {}
/**
* Returns the current state of the controller using this extension.
*
* @return {Object<string, *>} The current state of the controller.
*/
getState() {}
/**
* Patches the partial state of the extension. The extension is able
* during its load and update phase receive state from active controller
* using this extension and from previously loaded/updated extensions.
*
* @param {Object<string, *>} partialStatePatch Patch of the controller's state to
* apply.
*/
setPartialState() {}
/**
* Returns the current partial state of the extension.
*
* @return {Object<string, *>} The current partial state of the extension.
*/
getPartialState() {}
/**
* Clears the current partial state of the extension and sets it value to empty object.
*/
clearPartialState() {}
/**
* Sets the state manager used to manage the controller's state..
*
* @param {?PageStateManager} pageStateManager The current state manager to
* use.
*/
setPageStateManager() {}
/**
* Enables using PageStateManager for getting state.
*/
switchToStateManager() {}
/**
* Disables using PageStateManager for getting state.
*/
switchToPartialState() {}
/**
* Sets the current route parameters. This method is invoked before the
* {@link Extension#init} method.
*
* @param {Object<string, string>} [params={}] The current route
* parameters.
*/
setRouteParams() {}
/**
* Returns the current route parameters.
*
* @return {Object<string, string>} The current route parameters.
*/
getRouteParams() {}
/**
* Returns the names of the state fields that may be manipulated by this
* extension. Manipulations of other fields of the state will be ignored.
*
* @return {string[]} The names of the state fields that may be manipulated
* by this extension.
*/
getAllowedStateKeys() {}
}
|
const fp = require('lodash/fp')
const { handleActions } = require('redux-fp')
module.exports = handleActions({
SET_SOCKET_CLIENT: ({ payload: { socket } }) =>
fp.set(['socketClients', socket.id], socket),
UNSET_SOCKET_CLIENT: ({ payload: { socket } }) =>
fp.unset(['socketClients', socket.id]),
SET_SOCKET_SESSION: ({ payload: { socket, session } }) =>
fp.set(['socketSessions', socket.id], session),
})
|
version https://git-lfs.github.com/spec/v1
oid sha256:ceb6c3cd7166befa772ac603351dea546ba4ae40384834f19111fac325627715
size 24214
|
(function(){
angular
.module('app.answer')
.controller('answerController', answerController);
answerController.$inject = ['$stateParams','$firebaseObject'];
function answerController($stateParams, $firebaseObject){
var vm = this;
vm.id = $stateParams.id;
vm.addVote = addVote;
vm.options = {
responsive: true,
maintainAspectRatio: true
};
var fireQuestions = new Firebase('https://quizpoll-d8e4a.firebaseio.com/question/' + vm.id);
vm.Answer = $firebaseObject(fireQuestions);
$firebaseObject(fireQuestions).$watch(function(){
vm.Answer.$loaded().then(function(){
vm.data = [vm.Answer.option1.vote, vm.Answer.option2.vote, vm.Answer.option3.vote, vm.Answer.option4.vote];
vm.labels = [vm.Answer.option1.option,vm.Answer.option2.option, vm.Answer.option3.option, vm.Answer.option4.option];
vm.sum = vm.Answer.option1.vote + vm.Answer.option2.vote + vm.Answer.option3.vote + vm.Answer.option4.vote;
});
});
function addVote(vote){
vote.vote++;
console.log(vote.vote);
vm.Answer.$save();
alert('Thank you for voting! Your vote has been added');
vm.Answer.$loaded().then(function(){
vm.data = [vm.Answer.option1.vote, vm.Answer.option2.vote, vm.Answer.option3.vote, vm.Answer.option4.vote];
vm.labels = [vm.Answer.option1.option,vm.Answer.option2.option, vm.Answer.option3.option, vm.Answer.option4.option];
});
vm.hide=true;
}
}
})();
|
/* ========================================================================
* Bootstrap: modal.js v3.1.0
* http://getbootstrap.com/javascript/#modals
* ========================================================================
* Copyright 2011-2014 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
* ======================================================================== */
+function ($) {
'use strict';
// MODAL CLASS DEFINITION
// ======================
var Modal = function (element, options) {
this.options = options
this.$element = $(element)
this.$backdrop =
this.isShown = null
if (this.options.remote) {
this.$element
.find('.modal-content')
.load(this.options.remote, $.proxy(function () {
this.$element.trigger('loaded.bs.modal')
}, this))
}
}
Modal.DEFAULTS = {
backdrop: true,
keyboard: true,
show: true
}
Modal.prototype.toggle = function (_relatedTarget) {
return this[!this.isShown ? 'show' : 'hide'](_relatedTarget)
}
Modal.prototype.show = function (_relatedTarget) {
var that = this
var e = $.Event('show.bs.modal', { relatedTarget: _relatedTarget })
this.$element.trigger(e)
if (this.isShown || e.isDefaultPrevented()) return
this.isShown = true
this.escape()
this.$element.on('click.dismiss.bs.modal', '[data-dismiss="modal"]', $.proxy(this.hide, this))
this.backdrop(function () {
var transition = $.support.transition && that.$element.hasClass('fade')
if (!that.$element.parent().length) {
that.$element.appendTo(document.body) // don't move modals dom position
}
that.$element
.show()
.scrollTop(0)
if (transition) {
that.$element[0].offsetWidth // force reflow
}
that.$element
.addClass('in')
.attr('aria-hidden', false)
that.enforceFocus()
var e = $.Event('shown.bs.modal', { relatedTarget: _relatedTarget })
transition ?
that.$element.find('.modal-dialog') // wait for modal to slide in
.one($.support.transition.end, function () {
that.$element.focus().trigger(e)
})
.emulateTransitionEnd(300) :
that.$element.focus().trigger(e)
})
}
Modal.prototype.hide = function (e) {
if (e) e.preventDefault()
e = $.Event('hide.bs.modal')
this.$element.trigger(e)
if (!this.isShown || e.isDefaultPrevented()) return
this.isShown = false
this.escape()
$(document).off('focusin.bs.modal')
this.$element
.removeClass('in')
.attr('aria-hidden', true)
.off('click.dismiss.bs.modal')
$.support.transition && this.$element.hasClass('fade') ?
this.$element
.one($.support.transition.end, $.proxy(this.hideModal, this))
.emulateTransitionEnd(300) :
this.hideModal()
}
Modal.prototype.enforceFocus = function () {
$(document)
.off('focusin.bs.modal') // guard against infinite focus loop
.on('focusin.bs.modal', $.proxy(function (e) {
if (this.$element[0] !== e.target && !this.$element.has(e.target).length) {
this.$element.focus()
}
}, this))
}
Modal.prototype.escape = function () {
if (this.isShown && this.options.keyboard) {
this.$element.on('keyup.dismiss.bs.modal', $.proxy(function (e) {
e.which == 27 && this.hide()
}, this))
} else if (!this.isShown) {
this.$element.off('keyup.dismiss.bs.modal')
}
}
Modal.prototype.hideModal = function () {
var that = this
this.$element.hide()
this.backdrop(function () {
that.removeBackdrop()
that.$element.trigger('hidden.bs.modal')
})
}
Modal.prototype.removeBackdrop = function () {
this.$backdrop && this.$backdrop.remove()
this.$backdrop = null
}
Modal.prototype.backdrop = function (callback) {
var animate = this.$element.hasClass('fade') ? 'fade' : ''
if (this.isShown && this.options.backdrop) {
var doAnimate = $.support.transition && animate
this.$backdrop = $('<div class="modal-backdrop ' + animate + '" />')
.appendTo(document.body)
this.$element.on('click.dismiss.bs.modal', $.proxy(function (e) {
if (e.target !== e.currentTarget) return
this.options.backdrop == 'static'
? this.$element[0].focus.call(this.$element[0])
: this.hide.call(this)
}, this))
if (doAnimate) this.$backdrop[0].offsetWidth // force reflow
this.$backdrop.addClass('in')
if (!callback) return
doAnimate ?
this.$backdrop
.one($.support.transition.end, callback)
.emulateTransitionEnd(150) :
callback()
} else if (!this.isShown && this.$backdrop) {
this.$backdrop.removeClass('in')
$.support.transition && this.$element.hasClass('fade') ?
this.$backdrop
.one($.support.transition.end, callback)
.emulateTransitionEnd(150) :
callback()
} else if (callback) {
callback()
}
}
// MODAL PLUGIN DEFINITION
// =======================
var old = $.fn.modal
$.fn.modal = function (option, _relatedTarget) {
return this.each(function () {
var $this = $(this)
var data = $this.data('bs.modal')
var options = $.extend({}, Modal.DEFAULTS, $this.data(), typeof option == 'object' && option)
if (!data) $this.data('bs.modal', (data = new Modal(this, options)))
if (typeof option == 'string') data[option](_relatedTarget)
else if (options.show) data.show(_relatedTarget)
})
}
$.fn.modal.Constructor = Modal
// MODAL NO CONFLICT
// =================
$.fn.modal.noConflict = function () {
$.fn.modal = old
return this
}
// MODAL DATA-API
// ==============
$(document).on('click.bs.modal.data-api', '[data-toggle="modal"]', function (e) {
var $this = $(this)
var href = $this.attr('href')
var $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) //strip for ie7
var option = $target.data('bs.modal') ? 'toggle' : $.extend({ remote: !/#/.test(href) && href }, $target.data(), $this.data())
if ($this.is('a')) e.preventDefault()
$target
.modal(option, this)
.one('hide', function () {
$this.is(':visible') && $this.focus()
})
})
$(document)
.on('show.bs.modal', '.modal', function () { $(document.body).addClass('modal-open') })
.on('hidden.bs.modal', '.modal', function () { $(document.body).removeClass('modal-open') })
}(jQuery);
|
var gulp = require('gulp');
var revOrig = require('./../index.js');
gulp.task('revOrig-default', function (argument) {
gulp.src('test.html')
.pipe(revOrig())
.pipe(gulp.dest('./dist'));
});
gulp.task('revOrig-withBase', function (argument) {
gulp.src('test.html')
.pipe(revOrig({
base: 'assets/'
}))
.pipe(gulp.dest('./dist'));
});
gulp.task('revOrig-byDate', function (argument) {
gulp.src('test.html')
.pipe(revOrig({
revType: 'date'
}))
.pipe(gulp.dest('./dist'));
});
gulp.task('revOrig-withDateFormat', function (argument) {
gulp.src('test.html')
.pipe(revOrig({
revType: 'date',
dateFormat: 'yymmddHHmm'
}))
.pipe(gulp.dest('./dist'));
});
gulp.task('revOrig-withHashLength', function (argument) {
gulp.src('test.html')
.pipe(revOrig({
revType: 'hash',
hashLength: 5
}))
.pipe(gulp.dest('./dist'));
});
gulp.task('revOrig-withHashKey', function (argument) {
gulp.src('test.html')
.pipe(revOrig({
suffix: 'hashkey'
}))
.pipe(gulp.dest('./dist'));
});
gulp.task('revOrig-withFileTypes', function (argument) {
gulp.src('test.html')
.pipe(revOrig({
fileTypes: ['js']
}))
.pipe(gulp.dest('./dist'));
});
gulp.task('revOrig-withElementAttributes', function (argument) {
gulp.src('test.html')
.pipe(revOrig({
fileTypes: ['img1'],
elementAttributes: {
img1: {
tagRegStr: '(<img [^>]+/?>)',
pathRegStr: '(?:(\\s+data-src=")([^"]+)("))'
}
}
}))
.pipe(gulp.dest('./dist'));
});
gulp.task('revOrig-withTransformPath', function (argument) {
gulp.src('test.html')
.pipe(revOrig({
transformPath: function (orgpath, ver) {
var newpath = 'http://s1.cdn.com/' + orgpath + (orgpath.indexOf('?') > -1 ? '&' : '?') + 'v=' + ver;
return newpath;
}
}))
.pipe(gulp.dest('./dist'));
});
gulp.task('revOrig-withDefaultAddElementRev', function (argument) {
gulp.src('test.html')
.pipe(revOrig({
defaultAddElementRev: function (segment, addSrcRev, elementSetting) {
elementSetting.pathReg.lastIndex = 0;
var match = elementSetting.pathReg.exec(segment);
if(match) {
var src = match[2];
var revSrc = addSrcRev(src);
if(revSrc !== src) {
var base = './xxx' + (revSrc[0] === '/' ? '' : '/');
return segment.replace(elementSetting.pathReg, '$1' + base + revSrc + '$3');
} else {
return segment;
}
} else {
return segment;
}
}
}))
.pipe(gulp.dest('./dist'));
});
gulp.task('revOrig-withAddElementRev', function (argument) {
gulp.src('test.html')
.pipe(revOrig({
fileTypes: ['js', 'img1'],
elementAttributes: {
js: {
tagRegStr: '(<script [^>]+/?>)',
pathRegStr: '(?:(\\s+src=")([^"]+)("))'
},
img1: {
tagRegStr: '(<img [^>]+/?>)',
pathRegStr: '(?:(\\s+data-src=")([^"]+)("))',
addElementRev: function (segment, addSrcRev, elementSetting) {
elementSetting.pathReg.lastIndex = 0;
var match = elementSetting.pathReg.exec(segment);
if(match) {
var src = match[2];
var revSrc = addSrcRev(src);
return segment.replace(elementSetting.pathReg, '$1[' + revSrc + ']$3');
} else {
return segment;
}
}
}
}
}))
.pipe(gulp.dest('./dist'));
});
gulp.task('revOrig-createDefaultOptions', function () {
var options = revOrig.createDefaultOptions();
options.elementAttributes.loadJs = {
tagRegStr: '(<js [^>]+/?>)',
pathRegStr: '(?:(\\s+src=")([^"]+)("))'
};
options.fileTypes.push('loadJs');
gulp.src('test.html')
.pipe(revOrig(options))
.pipe(gulp.dest('./dist'));
});
|
import React from 'react';
const ReactComponenta1 = () => <h2> Hello </h2>;
const ReactComponenta2 = () => <input />;
const ReactComponenta3 = () => <button>Add Me</button>;
const allBox = [
{
uid: 'a1',
title: 'Box-1',
content: "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.",
reactComponent: ReactComponenta1,
},
{
uid: 'a2',
title: 'Box-2',
content: "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.",
reactComponent: ReactComponenta2,
},
{
uid: 'a3',
title: 'Box-3',
content: "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.",
reactComponent: ReactComponenta3,
},
{
uid: 'a4',
title: 'Box-4',
content: "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.",
reactComponent: ReactComponenta3,
},
];
export default allBox;
/*
size: {
lg: {x: 0, y: 4, h: 2, w: 12, i: 'a3'},
md: {x: 0, y: 4, h: 2, w: 12, i: 'a3'},
sm: {x: 0, y: 4, h: 2, w: 12, i: 'a3'},
xs: {x: 0, y: 4, h: 2, w: 12, i: 'a3'},
xxs: {x: 0, y: 4, h: 2, w: 12,i: 'a3'},
},
*/
|
require("coffee-script/register");
module.exports = require("./machina.coffee");
|
import React, { Component, PropTypes } from 'react';
import styles from '../../build/styles';
import { getCallbacks } from '../helper/helper';
export default class Column extends Component {
static propTypes = {
children: PropTypes.any,
style: PropTypes.object,
className: PropTypes.string,
isMultiline: PropTypes.bool,
size: PropTypes.oneOf([
'is1',
'is2',
'is3',
'is4',
'is5',
'is6',
'is7',
'is8',
'is9',
'is10',
'is11',
'is12',
'isThreeQuarters',
'isTwoThirds',
'isHalf',
'isOneThird',
'isOneQuarter',
'isThreeQuartersMobile',
'isTwoThirdsMobile',
'isHalfMobile',
'isOneThirdMobile',
'isOneQuarterMobile',
'isThreeQuartersTablet',
'isTwoThirdsTablet',
'isHalfTablet',
'isOneThirdTablet',
'isOneQuarterTablet',
'isThreeQuartersDesktop',
'isTwoThirdsDesktop',
'isHalfDesktop',
'isOneThirdDesktop',
'isOneQuarterDesktop',
'isThreeQuartersWidescreen',
'isTwoThirdsWidescreen',
'isHalfWidescreen',
'isOneThirdWidescreen',
'isOneQuarterWidescreen',
'isNarrow',
'isNarrowMobile',
'isNarrowTablet',
'isNarrowDesktop',
'isNarrowWidescreen',
'isFull',
'isFullMobile',
'isFullTablet',
'isFullDesktop',
'isFullWidescreen',
]),
offset: PropTypes.oneOf([
'isOffsetThreeQuarters',
'isOffsetTwoThirds',
'isOffsetHalf',
'isOffsetOneThird',
'isOffsetOneQuarter',
'isOffset1',
'isOffset2',
'isOffset3',
'isOffset4',
'isOffset5',
'isOffset6',
'isOffset7',
'isOffset8',
'isOffset9',
'isOffset10',
'isOffset11',
'isOffset12',
'isOffset1Mobile',
'isOffset2Mobile',
'isOffset3Mobile',
'isOffset4Mobile',
'isOffset5Mobile',
'isOffset6Mobile',
'isOffset7Mobile',
'isOffset8Mobile',
'isOffset9Mobile',
'isOffset10Mobile',
'isOffset11Mobile',
'isOffset12Mobile',
'isOffset1Tablet',
'isOffset2Tablet',
'isOffset3Tablet',
'isOffset4Tablet',
'isOffset5Tablet',
'isOffset6Tablet',
'isOffset7Tablet',
'isOffset8Tablet',
'isOffset9Tablet',
'isOffset10Tablet',
'isOffset11Tablet',
'isOffset12Tablet',
'isOffset1Desktop',
'isOffset2Desktop',
'isOffset3Desktop',
'isOffset4Desktop',
'isOffset5Desktop',
'isOffset6Desktop',
'isOffset7Desktop',
'isOffset8Desktop',
'isOffset9Desktop',
'isOffset10Desktop',
'isOffset11Desktop',
'isOffset12Desktop',
'isOffset1Widescreen',
'isOffset2Widescreen',
'isOffset3Widescreen',
'isOffset4Widescreen',
'isOffset5Widescreen',
'isOffset6Widescreen',
'isOffset7Widescreen',
'isOffset8Widescreen',
'isOffset9Widescreen',
'isOffset10Widescreen',
'isOffset11Widescreen',
'isOffset12Widescreen',
]),
};
createClassName() {
return [
styles.column,
styles[this.props.size],
styles[this.props.offset],
this.props.className,
].join(' ').trim();
}
render() {
return (
<div
{...getCallbacks(this.props)}
className={this.createClassName()}
style={this.props.style}
>
{this.props.children}
</div>
);
}
}
|
import { createAction } from 'redux-actions'
import { NAME } from './constants'
import shop from 'api/shop'
const RECEIVE_PRODUCTS = `${NAME}/RECEIVE_PRODUCTS`
const receiveProducts = createAction(RECEIVE_PRODUCTS)
const getAllProductsAsync = () => (dispatch) =>
shop.getProducts(products => {
dispatch(receiveProducts(products))
})
export {
RECEIVE_PRODUCTS,
receiveProducts,
getAllProductsAsync,
}
|
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var WorkSchema = Schema({
name: {
type: String,
required: true
},
desc: {
type: String,
required: true
},
photo: [String],
tag: [String],
pubDate: {
type: Date,
default: Date.now,
required: true
},
id: Schema.Types.ObjectId
});
module.exports = mongoose.model('Work', WorkSchema);
|
class LocalstorageController {
/*@ngInject*/
constructor($location, persistenceService) {
this.$location = $location;
this.persistenceService = persistenceService;
this.initData();
}
initData() {
this.localStorageAsText = this.persistenceService.export();
}
import() {
if (!!importData) {
this.persistenceService.import(this.importData);
}
}
clear() {
localStorage.clear();
this.initData();
}
displayAsList() {
this.listDisplayed = true;
}
back() {
this.$location.url('/stack');
}
}
export default LocalstorageController;
|
/*
* (C) Copyright 2014-2017 Markus Moenig <markusm@visualgraphics.tv>.
*
* This file is part of Visual Graphics.
*
* Visual Graphics is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Visual Graphics is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Visual Graphics. If not, see <http://www.gnu.org/licenses/>.
*
*/
// ----------------------------------------------------------------- VG.Nodes.NodeGradient3D --- Generator.Gradient3D
VG.Nodes.NodeGradient3D=function()
{
if ( !(this instanceof VG.Nodes.NodeGradient3D ) ) return new VG.Nodes.NodeGradient3D();
this.name="Gradient Noise";
this.className="NodeGradient3D";
this.modifiesGlobals=true;
this.description = `<html><p>Gradient 3D noise. <a href=\"https://www.shadertoy.com/view/4dffRH">Based on a noise</a> by <a href=\"https://www.shadertoy.com/user/iq\">Inigo Quilez</a>. Released under the MIT license.</p>
<p>"normal" returns the analytic derivative of the gradient function. You can optionally supply an alternative hash function as input.</p></html>
`;
VG.Nodes.Node.call( this );
this.global=`
// return value noise (in x) and its derivatives (in yzw)
vec4 NodeGradient3D_noised_${this.token}( in vec3 x )
{
x *= <! SCALE VALUE !>;
// x += <! OFFSET VALUE !>;
// grid
vec3 p = floor(x);
vec3 w = fract(x);
#if 1
// quintic interpolant
vec3 u = w*w*w*(w*(w*6.0-15.0)+10.0);
vec3 du = 30.0*w*w*(w*(w-2.0)+1.0);
#else
// cubic interpolant
vec3 u = w*w*(3.0-2.0*w);
vec3 du = 6.0*w*(1.0-w);
#endif
// gradients
vec3 ga = <! HASH !>( p+vec3(0.0,0.0,0.0) )<! HASH DOMAIN !>;
vec3 gb = <! HASH !>( p+vec3(1.0,0.0,0.0) )<! HASH DOMAIN !>;
vec3 gc = <! HASH !>( p+vec3(0.0,1.0,0.0) )<! HASH DOMAIN !>;
vec3 gd = <! HASH !>( p+vec3(1.0,1.0,0.0) )<! HASH DOMAIN !>;
vec3 ge = <! HASH !>( p+vec3(0.0,0.0,1.0) )<! HASH DOMAIN !>;
vec3 gf = <! HASH !>( p+vec3(1.0,0.0,1.0) )<! HASH DOMAIN !>;
vec3 gg = <! HASH !>( p+vec3(0.0,1.0,1.0) )<! HASH DOMAIN !>;
vec3 gh = <! HASH !>( p+vec3(1.0,1.0,1.0) )<! HASH DOMAIN !>;
// projections
float va = dot( ga, w-vec3(0.0,0.0,0.0) );
float vb = dot( gb, w-vec3(1.0,0.0,0.0) );
float vc = dot( gc, w-vec3(0.0,1.0,0.0) );
float vd = dot( gd, w-vec3(1.0,1.0,0.0) );
float ve = dot( ge, w-vec3(0.0,0.0,1.0) );
float vf = dot( gf, w-vec3(1.0,0.0,1.0) );
float vg = dot( gg, w-vec3(0.0,1.0,1.0) );
float vh = dot( gh, w-vec3(1.0,1.0,1.0) );
// interpolations
return vec4( va + u.x*(vb-va) + u.y*(vc-va) + u.z*(ve-va) + u.x*u.y*(va-vb-vc+vd) + u.y*u.z*(va-vc-ve+vg) + u.z*u.x*(va-vb-ve+vf) + (-va+vb+vc-vd+ve-vf-vg+vh)*u.x*u.y*u.z, // value
ga + u.x*(gb-ga) + u.y*(gc-ga) + u.z*(ge-ga) + u.x*u.y*(ga-gb-gc+gd) + u.y*u.z*(ga-gc-ge+gg) + u.z*u.x*(ga-gb-ge+gf) + (-ga+gb+gc-gd+ge-gf-gg+gh)*u.x*u.y*u.z + // derivatives
du * (vec3(vb,vc,ve) - va + u.yzx*vec3(va-vb-vc+vd,va-vc-ve+vg,va-vb-ve+vf) + u.zxy*vec3(va-vb-ve+vf,va-vb-vc+vd,va-vc-ve+vg) + u.yzx*u.zxy*(-va+vb+vc-vd+ve-vf-vg+vh) ));
}
`;
this.hash = `
vec3 NodeGradient3D_hash_${this.token}(in vec3 p)
{
float time = 0.0;
p = vec3( dot(p,vec3(127.1, 311.7, 74.7)),
dot(p,vec3(269.5, 183.3, 246.1)),
dot(p,vec3(113.5, 271.9, 124.6)));
p = fract(sin(p)*43758.5453123)*2. - 1.;
float th = time * 2.;
vec2 a = sin(vec2(1.5707963, 0) + th);
mat2 m = mat2(a, -a.y, a.x); //in general use 3d rotation
p.xy = m * p.xy;//rotate gradient vector
//p.yz = m * p.yz;//rotate gradient vector
//p.zx = m * p.zx;//rotate gradient vector
return p;
}
`;
// --- Terminals
this.hashTerminal=this.addInput( VG.Nodes.Terminal( VG.Nodes.Terminal.Type.Function, "hash" ) );
this.addOutput( VG.Nodes.Terminal( VG.Nodes.Terminal.Type.Float, "noise", function( options ) {
let noiseVar = options.getVar( this, "", "vec4" );
if ( !noiseVar.exists || options.override )
options.code += " " + noiseVar.code + ` = NodeGradient3D_noised_${this.token}( pos );\n`;
let floatVar = options.getVar( this, "float", "float" );
if ( !floatVar.exists || options.override )
options.code += " " + floatVar.code + " = " + noiseVar.name + ".x;\n";
if ( !this.rt ) {
let prevCode = options.globalCode + options.code + " material.color = clamp( pow( vec3(" + floatVar.name + "), vec3( 0.4545 ) ), 0.0, 1.0 );\n}";
options.generatePreview( this, prevCode );
}
return floatVar.name;
}.bind( this ) ) );
this.addOutput( VG.Nodes.Terminal( VG.Nodes.Terminal.Type.Vector3, "normal", function( options ) {
let noiseVar = options.getVar( this, "", "vec4" );
if ( !noiseVar.exists )
options.code += " " + noiseVar.code + ` = NodeGradient3D_noised_${this.token}( pos );\n`;
let normalVar = options.getVar( this, "normal", "vec3" );
if ( !normalVar.exists )
options.code += " " + normalVar.code + " = " + noiseVar.name + ".yzw;\n";
if ( !this.rt ) {
let prevCode = options.globalCode + options.code;
let floatVar = options.getVar( this, "float", "float" );
if ( !floatVar.exists || options.override )
prevCode += " " + floatVar.code + " = " + noiseVar.name + ".x;\n";
prevCode += " material.color = clamp( pow( vec3(" + floatVar.name + "), vec3( 0.4545 ) ), 0.0, 1.0 );\n}";
options.generatePreview( this, prevCode );
}
return normalVar.name;
}.bind( this ) ) );
this.addOutput( VG.Nodes.Terminal( VG.Nodes.Terminal.Type.Function, "function", function( options ) {
if ( !this.rt && options.generatePreview ) {
let prevCode = options.globalCode + options.code + ` material.color = clamp( pow( vec3( NodeGradient3D_noised_${this.token}(pos).x ), vec3( 0.4545 ) ), 0.0, 1.0 );\n}`;
options.generatePreview( this, prevCode );
}
return `NodeGradient3D_noised_${this.token}`;
}.bind( this ) ) );
};
VG.Nodes.NodeGradient3D.prototype=VG.Nodes.Node();
VG.Nodes.NodeGradient3D.prototype.getGlobalCode=function( data )
{
let global = this.global;
let scale = this.container.getParamValue( "scaleGlobal" ).toFixed(2) + " * " + this.container.getParam( "scale" ).toString();
global = global.replace( /<! SCALE VALUE !>/g, scale );
if ( !this.hashTerminal.isConnected() ) {
global = global.replace( /<! HASH !>/g, `NodeGradient3D_hash_${this.token}` );
global = global.replace( /<! HASH DOMAIN !>/g, "" );
global = this.hash + global;
} else {
let funcName = this.hashTerminal.first().onCall( {} );
global = global.replace( /<! HASH !>/g, funcName );
global = global.replace( /<! HASH DOMAIN !>/g, ".xyz" );
}
return global;
};
VG.Nodes.NodeGradient3D.prototype.createProperties=function( data )
{
this.container=VG.Nodes.ParamContainer( this );
var group=this.container.addGroupByName( "basics", "Gradient 3D Noise" );
group.addParam( VG.Nodes.ParamSlider( data, "scaleGlobal", "Scale", 1, 0.001, 100.00, 0.5, 3, 3 ) );
group.addParam( VG.Nodes.ParamVector3( data, "scale", "Scale", 1.00, 1.00, 1.00, 0.001, 50.00 ) );
this.createDefaultProperties( data );
};
VG.Nodes.availableNodes.set( "Noise.Gradient Noise", "NodeGradient3D" );
// ----------------------------------------------------------------- VG.Nodes.NodeVoronoi3D --- Noise.NodeVoronoi3D
VG.Nodes.NodeVoronoi3D=function()
{
if ( !(this instanceof VG.Nodes.NodeVoronoi3D ) ) return new VG.Nodes.NodeVoronoi3D();
this.name="Voronoi Noise";
this.className="NodeVoronoi3D";
this.modifiesGlobals=true;
this.description = `<html><p>Voronoi 3D noise. <a href=\"https://www.shadertoy.com/view/ldl3Dl">Based on a noise</a> by <a href=\"https://www.shadertoy.com/user/iq\">Inigo Quilez</a>. Released under the MIT license.</p>
<p>"noise1" returns the closest distance to a cell, "noise2" the second closest and id the id of the cell. You can optionally supply an alternative hash function as input.</p> </html>
`;
VG.Nodes.Node.call( this );
this.global=`
// returns closest, second closest, and cell id
vec4 NodeVoronoi3D_${this.token}( in vec3 x )
{
x *= <! SCALE VALUE !>;
vec3 p = floor( x );
vec3 f = fract( x );
float id = 0.0;
vec2 res = vec2( 100.0 );
for( int k=-1; k<=1; k++ )
for( int j=-1; j<=1; j++ )
for( int i=-1; i<=1; i++ )
{
vec3 b = vec3( float(i), float(j), float(k) );
vec3 r = vec3( b ) - f + <! HASH !>( p + b )<! HASH DOMAIN !>;
float d = dot( r, r );
if( d < res.x )
{
id = dot( p+b, vec3(1.0,57.0,113.0 ) );
res = vec2( d, res.x );
}
else if( d < res.y )
{
res.y = d;
}
}
return vec4( sqrt( res ), abs(id), 0 );
}
`;
this.hash = `
vec3 NodeVoronoi3D_hash_${this.token}(in vec3 x)
{
x = vec3( dot(x,vec3(127.1,311.7, 74.7)),
dot(x,vec3(269.5,183.3,246.1)),
dot(x,vec3(113.5,271.9,124.6)));
return fract(sin(x)*43758.5453123);
}
`;
// --- Terminals
this.hashTerminal=this.addInput( VG.Nodes.Terminal( VG.Nodes.Terminal.Type.Function, "hash" ) );
this.addOutput( VG.Nodes.Terminal( VG.Nodes.Terminal.Type.Float, "noise 1", function( options ) {
let noiseVar = options.getVar( this, "", "vec4" );
if ( !noiseVar.exists || options.override )
options.code += " " + noiseVar.code + ` = NodeVoronoi3D_${this.token}( pos );\n`;
let floatVar = options.getVar( this, "float1", "float" );
if ( !floatVar.exists || options.override )
options.code += " " + floatVar.code + " = " + noiseVar.name + ".x;\n";
if ( !this.rt ) {
let prevCode = options.globalCode + options.code + " material.color = clamp( pow( vec3(" + floatVar.name + "), vec3( 0.4545 ) ), 0.0, 1.0 );\n}";
options.generatePreview( this, prevCode );
}
return floatVar.name;
}.bind( this ) ) );
this.addOutput( VG.Nodes.Terminal( VG.Nodes.Terminal.Type.Float, "noise 2", function( options ) {
let noiseVar = options.getVar( this, "", "vec4" );
if ( !noiseVar.exists || options.override )
options.code += " " + noiseVar.code + ` = NodeVoronoi3D_${this.token}( pos );\n`;
let floatVar = options.getVar( this, "float2", "float" );
if ( !floatVar.exists || options.override )
options.code += " " + floatVar.code + " = " + noiseVar.name + ".y;\n";
if ( !this.rt ) {
let prevCode = options.globalCode + options.code + " material.color = clamp( pow( vec3(" + floatVar.name + "), vec3( 0.4545 ) ), 0.0, 1.0 );\n}";
options.generatePreview( this, prevCode );
}
return floatVar.name;
}.bind( this ) ) );
this.addOutput( VG.Nodes.Terminal( VG.Nodes.Terminal.Type.Float, "id", function( options ) {
let noiseVar = options.getVar( this, "", "vec4" );
if ( !noiseVar.exists || options.override )
options.code += " " + noiseVar.code + ` = NodeVoronoi3D_${this.token}( pos );\n`;
let floatVar = options.getVar( this, "float2", "float" );
if ( !floatVar.exists || options.override )
options.code += " " + floatVar.code + " = " + noiseVar.name + ".z;\n";
if ( !this.rt ) {
let prevCode = options.globalCode + options.code + " material.color = clamp( pow( vec3(" + floatVar.name + "), vec3( 0.4545 ) ), 0.0, 1.0 );\n}";
options.generatePreview( this, prevCode );
}
return floatVar.name;
}.bind( this ) ) );
this.addOutput( VG.Nodes.Terminal( VG.Nodes.Terminal.Type.Function, "function", function( options ) {
if ( !this.rt && options.generatePreview ) {
let prevCode = options.globalCode + options.code + ` material.color = clamp( pow( vec3( NodeVoronoi3D_${this.token}(pos).x ), vec3( 0.4545 ) ), 0.0, 1.0 );\n}`;
options.generatePreview( this, prevCode );
}
return `NodeVoronoi3D_${this.token}`;
}.bind( this ) ) );
};
VG.Nodes.NodeVoronoi3D.prototype=VG.Nodes.Node();
VG.Nodes.NodeVoronoi3D.prototype.getGlobalCode=function( data )
{
let global = this.global;
let scale = this.container.getParamValue( "scaleGlobal" ).toFixed(2) + " * " + this.container.getParam( "scale" ).toString();
global = global.replace( /<! SCALE VALUE !>/g, scale );
if ( !this.hashTerminal.isConnected() ) {
global = global.replace( /<! HASH !>/g, `NodeVoronoi3D_hash_${this.token}` );
global = global.replace( /<! HASH DOMAIN !>/g, "" );
global = this.hash + global;
} else {
let funcName = this.hashTerminal.first().onCall( {} );
global = global.replace( /<! HASH !>/g, funcName );
global = global.replace( /<! HASH DOMAIN !>/g, ".xyz" );
}
// console.log( global );
return global;
};
VG.Nodes.NodeVoronoi3D.prototype.createProperties=function( data )
{
this.container=VG.Nodes.ParamContainer( this );
var group=this.container.addGroupByName( "basics", "Gradient 3D Noise" );
group.addParam( VG.Nodes.ParamSlider( data, "scaleGlobal", "Scale", 1, 0.001, 100.00, 0.5, 3, 3 ) );
group.addParam( VG.Nodes.ParamVector3( data, "scale", "Scale", 1.00, 1.00, 1.00, 0.001, 50.00 ) );
// group=this.container.addGroupByName( "about", "About" );
// group.addParam( VG.Nodes.ParamVector3( data, "scale", "Scale", 1.00, 1.00, 1.00, 0.001, 50.00 ) );
this.createDefaultProperties( data );
};
VG.Nodes.availableNodes.set( "Noise.Voronoi Noise", "NodeVoronoi3D" );
// ----------------------------------------------------------------- VG.Nodes.NodeTurbulence --- Operator.NodeTurbulence
VG.Nodes.NodeTurbulence=function()
{
if ( !(this instanceof VG.Nodes.NodeTurbulence ) ) return new VG.Nodes.NodeTurbulence();
this.name="Turbulence";
this.className="NodeTurbulence";
this.modifiesGlobals=true;
this.description = `<html><p>Turbulence or FBM.</p>
<p>Requires a noise function as input. The "normal" output will only be valid when the input noise has a "normal" output terminal.</p></html>
`;
VG.Nodes.Node.call( this );
this.global=`
/*
vec4 NodeTurbulence(in vec3 p)
{
// Three control factors. Lacunarity and gain are set to common defaults.
const int layers = 5; //Noise layers. Also called octaves.
const float lacunarity = 2.; // Frequency change factor. Controls the gaps.
const float gain = .5; // Amplitue change factor. Controls granularity.
float res = 0.; // Final result.
float amp = 1.; // Initial amplitude.
float tot = 0.; // Total amplitude. Used to normalize the final value.
// Adding the layers of noise with varying frequencies and amplitudes.
for(int i=0; i<layers; i++){
res += <! NOISE FUNC !>(p).x*amp; // Add noise layers at various amplitudes.
p *= lacunarity; // Change the layer frequency.
tot += amp; // Add the amplitude.
amp *= gain; // Change the amplitude.
}
return vec4( res/tot ); // Normalize and return. Range [0, 1]
}
*/
vec4 NodeTurbulence_${this.token}(in vec3 p)
{
const float scale = <! SCALE VALUE !>;
float a = 0.0;
float b = 0.5;
float f = 1.0;
vec3 d = vec3(0.0);
for( int i=0; i<8; i++ )
{
vec4 n = <! NOISE FUNC !>(f*p*scale);
a += b*n.x; // accumulate values
d += b*n.yzw*f*scale; // accumulate derivatives
b *= 0.5; // amplitude decrease
f *= 1.8; // frequency increase
}
return vec4( a, d );
}
`;
// --- Terminals
let noiseTerminal=VG.Nodes.Terminal( VG.Nodes.Terminal.Type.Function, "noise" );
this.noiseTerminal = noiseTerminal;
this.addInput( noiseTerminal );
this.addOutput( VG.Nodes.Terminal( VG.Nodes.Terminal.Type.Float, "turbulence", function( options ) {
if ( noiseTerminal.isConnected() ) {
let funcName = noiseTerminal.first().onCall( options );
let noiseVar = options.getVar( this, "", "vec4" );
if ( !noiseVar.exists || options.override )
options.code += " " + noiseVar.code + ` = NodeTurbulence_${this.token}( pos );\n`;
let floatVar = options.getVar( this, "float", "float" );
if ( !floatVar.exists || options.override )
options.code += " " + floatVar.code + " = " + noiseVar.name + ".x;\n";
if ( !this.rt ) {
let prevCode = options.globalCode + options.code + ` material.color = clamp( pow( vec3( NodeTurbulence_${this.token}(pos).x ), vec3( 0.4545 ) ), 0.0, 1.0 );\n}`;
options.generatePreview( this, prevCode );
}
return floatVar.name;
} else return "0.0";
}.bind( this ) ) );
this.addOutput( VG.Nodes.Terminal( VG.Nodes.Terminal.Type.Vector3, "normal", function( options ) {
if ( noiseTerminal.isConnected() ) {
let funcName = noiseTerminal.first().onCall( options );
let noiseVar = options.getVar( this, "", "vec4" );
if ( !noiseVar.exists || options.override )
options.code += " " + noiseVar.code + ` = NodeTurbulence_${this.token}( pos );\n`;
let normalVar = options.getVar( this, "normal", "vec3" );
if ( !normalVar.exists || options.override )
options.code += " " + normalVar.code + " = " + noiseVar.name + ".yzw;\n";
if ( !this.rt ) {
let prevCode = options.globalCode + options.code + ` material.color = clamp( pow( vec3( NodeTurbulence_${this.token}(pos).x ), vec3( 0.4545 ) ), 0.0, 1.0 );\n}`;
options.generatePreview( this, prevCode );
}
return normalVar.name;
} else return "vec3(0)";
}.bind( this ) ) );
this.addOutput( VG.Nodes.Terminal( VG.Nodes.Terminal.Type.Vector4, "t + n", function( options ) {
if ( noiseTerminal.isConnected() ) {
let funcName = noiseTerminal.first().onCall( options );
let noiseVar = options.getVar( this, "", "vec4" );
if ( !noiseVar.exists || options.override )
options.code += " " + noiseVar.code + ` = NodeTurbulence_${this.token}( pos );\n`;
let tnVar = options.getVar( this, "t_n", "vec4" );
if ( !tnVar.exists || options.override )
options.code += " " + tnVar.code + " = " + noiseVar.name + ";\n";
if ( !this.rt ) {
let prevCode = options.globalCode + options.code + ` material.color = clamp( pow( vec3( NodeTurbulence_${this.token}(pos).x ), vec3( 0.4545 ) ), 0.0, 1.0 );\n}`;
options.generatePreview( this, prevCode );
}
return tnVar.name;
} else return "vec4(0)";
}.bind( this ) ) );
/*
this.addOutput( VG.Nodes.Terminal( VG.Nodes.Terminal.Type.Function, "function", function( options ) {
return `NodeTurbulence_${this.token}`;
}.bind( this ) ) );
*/
};
VG.Nodes.NodeTurbulence.prototype=VG.Nodes.Node();
VG.Nodes.NodeTurbulence.prototype.getGlobalCode=function( data )
{
let funcName = "vec3";
if ( this.noiseTerminal.isConnected() ) {
funcName = this.noiseTerminal.first().onCall( {} );
} else return "";
let global = this.global;
global = global.replace( /<! NOISE FUNC !>/g, funcName );
let scaleGlobal = this.container.getParamValue( "scaleGlobal" );
global = global.replace( /<! SCALE VALUE !>/g, scaleGlobal.toFixed( 2 ) );
return global;
};
VG.Nodes.NodeTurbulence.prototype.createProperties=function( data )
{
this.container=VG.Nodes.ParamContainer( this );
let group=this.container.addGroupByName( "basics", "Turbulence" );
group.addParam( VG.Nodes.ParamSlider( data, "scaleGlobal", "Scale", 1, 0.001, 100.00, 0.5, 3, 3 ) );
/*
var group=this.container.addGroupByName( "basics", "Simplex3D - Basics" );
group.addParam( VG.Nodes.ParamList( data, "output", "Output", 1, ["RGB", "Grayscale"] ) );
group.addParam( VG.Nodes.ParamSlider( data, "amplitude", "Amplitude", 1, -50, 50, 0.5, 3 ) );
group.addParam( VG.Nodes.ParamSlider( data, "offset", "Offset", 0.5, -50, 50, 0.5, 3 ) );
group=this.container.addGroupByName( "scale", "Scale" );
group.addParam( VG.Nodes.ParamSlider( data, "scaleGlobal", "Scale", 1, 0.001, 50.00, 0.5, 3 ) );
group.addParam( VG.Nodes.ParamVector3( data, "scale", "Scale", 10.00, 10.00, 10.00, 0.001, 50.00 ) );
group=this.container.addGroupByName( "fractal", "Fractal" );
group.addParam( VG.Nodes.ParamBoolean( data, "fractal", "Enable", false ) );
group.addParam( VG.Nodes.ParamSlider( data, "octaves", "Octaves", 3.0, 1.00, 15.00, 0.5, 3 ) );
group.addParam( VG.Nodes.ParamSlider( data, "increment", "Increment", 0.5, 0.01, 2.00, 0.1, 3 ) );
group.addParam( VG.Nodes.ParamSlider( data, "lacunarity", "Lacunarity", 2.0, 0.01, 5.00, 0.5, 3 ) );
*/
this.createDefaultProperties( data );
};
VG.Nodes.availableNodes.set( "Noise.Turbulence", "NodeTurbulence" );
// ----------------------------------------------------------------- VG.Nodes.NodeHash1 --- Hash.NodeHash1
VG.Nodes.NodeHash1=function()
{
if ( !(this instanceof VG.Nodes.NodeHash1 ) ) return new VG.Nodes.NodeHash1();
this.name="Hash 1 - Simple";
this.className="NodeHash1";
VG.Nodes.Node.call( this );
this.global=`
vec4 NodeHash1( vec3 p )
{
p = vec3( dot(p,vec3(127.1,311.7, 74.7)),
dot(p,vec3(269.5,183.3,246.1)),
dot(p,vec3(113.5,271.9,124.6)));
return vec4( -1.0 + 2.0*fract(sin(p)*43758.5453123), 0 );
}
`;
// --- Terminals
this.addOutput( VG.Nodes.Terminal( VG.Nodes.Terminal.Type.Function, "function", function( options ) {
if ( !this.rt && options.generatePreview ) {
let prevCode = options.globalCode + options.code + ` material.color = clamp( pow( NodeHash1( pos ).xyz, vec3( 0.4545 ) ), 0.0, 1.0 );\n}`;
options.generatePreview( this, prevCode );
}
return "NodeHash1";
}.bind( this ) ) );
};
VG.Nodes.NodeHash1.prototype=VG.Nodes.Node();
VG.Nodes.NodeHash1.prototype.getGlobalCode=function( data )
{
let global = this.global;
return global;
};
VG.Nodes.NodeHash1.prototype.createProperties=function( data )
{
this.container=VG.Nodes.ParamContainer( this );
var group=this.container.addGroupByName( "basics", "Hash 1" );
this.createDefaultProperties( data );
};
VG.Nodes.availableNodes.set( "Noise.Hash 1 Simple", "NodeHash1" );
|
data = [{"t":0,"command":"create goroutine","name":"main"},
{"t":370879,"command":"create goroutine","name":"handler #6","parent":"main"},
{"t":375939,"command":"create goroutine","name":"handler #5","parent":"main"},
{"t":422330,"command":"create goroutine","name":"handler #11","parent":"main"},
{"t":478234,"command":"create goroutine","name":"handler #12","parent":"main"},
{"t":541790,"command":"create goroutine","name":"handler #26","parent":"main"},
{"t":549092,"command":"create goroutine","name":"handler #7","parent":"main"},
{"t":574948,"command":"create goroutine","name":"handler #27","parent":"main"},
{"t":574952,"command":"create goroutine","name":"handler #34","parent":"main"},
{"t":593659,"command":"create goroutine","name":"handler #13","parent":"main"},
{"t":624619,"command":"create goroutine","name":"handler #35","parent":"main"},
{"t":638308,"command":"create goroutine","name":"handler #14","parent":"main"},
{"t":638313,"command":"create goroutine","name":"handler #8","parent":"main"},
{"t":668524,"command":"create goroutine","name":"handler #36","parent":"main"},
{"t":674362,"command":"create goroutine","name":"handler #28","parent":"main"},
{"t":732302,"command":"create goroutine","name":"handler #9","parent":"main"},
{"t":751398,"command":"create goroutine","name":"handler #29","parent":"main"},
{"t":1166594,"command":"create goroutine","name":"handler #15","parent":"main"},
{"t":1176522,"command":"create goroutine","name":"handler #10","parent":"main"},
{"t":1203168,"command":"create goroutine","name":"handler #30","parent":"main"},
{"t":1215660,"command":"create goroutine","name":"handler #37","parent":"main"},
{"t":1218280,"command":"create goroutine","name":"handler #16","parent":"main"},
{"t":1223038,"command":"create goroutine","name":"handler #21","parent":"main"},
{"t":1261272,"command":"create goroutine","name":"handler #38","parent":"main"},
{"t":1261278,"command":"create goroutine","name":"handler #22","parent":"main"},
{"t":1273849,"command":"create goroutine","name":"handler #31","parent":"main"},
{"t":1295042,"command":"create goroutine","name":"handler #17","parent":"main"},
{"t":1322852,"command":"create goroutine","name":"handler #32","parent":"main"},
{"t":1327230,"command":"create goroutine","name":"handler #23","parent":"main"},
{"t":1329734,"command":"create goroutine","name":"handler #39","parent":"main"},
{"t":1369880,"command":"create goroutine","name":"handler #33","parent":"main"},
{"t":1374282,"command":"create goroutine","name":"handler #18","parent":"main"},
{"t":1386093,"command":"create goroutine","name":"handler #40","parent":"main"},
{"t":1433620,"command":"create goroutine","name":"handler #24","parent":"main"},
{"t":1436013,"command":"create goroutine","name":"handler #19","parent":"main"},
{"t":1477478,"command":"create goroutine","name":"handler #25","parent":"main"},
{"t":1477613,"command":"create goroutine","name":"handler #20","parent":"main"},
{"t":501484179,"command":"stop goroutine","name":"handler #33"},
{"t":501484219,"command":"stop goroutine","name":"handler #29"},
{"t":501540130,"command":"stop goroutine","name":"handler #6"},
{"t":501554109,"command":"stop goroutine","name":"handler #15"},
{"t":501554380,"command":"stop goroutine","name":"handler #12"},
{"t":501564330,"command":"stop goroutine","name":"handler #5"},
{"t":501566474,"command":"stop goroutine","name":"handler #10"},
{"t":501574210,"command":"stop goroutine","name":"handler #11"},
{"t":501576484,"command":"stop goroutine","name":"handler #30"},
{"t":501583774,"command":"stop goroutine","name":"handler #26"},
{"t":501586229,"command":"stop goroutine","name":"handler #16"},
{"t":501595729,"command":"stop goroutine","name":"handler #37"},
{"t":501595913,"command":"stop goroutine","name":"handler #27"},
{"t":501608294,"command":"stop goroutine","name":"handler #34"},
{"t":501616649,"command":"stop goroutine","name":"handler #14"},
{"t":501621831,"command":"stop goroutine","name":"handler #8"},
{"t":501631983,"command":"stop goroutine","name":"handler #36"},
{"t":501643003,"command":"stop goroutine","name":"handler #28"},
{"t":501644451,"command":"stop goroutine","name":"handler #7"},
{"t":501653480,"command":"stop goroutine","name":"handler #9"},
{"t":501655378,"command":"stop goroutine","name":"handler #13"},
{"t":501665160,"command":"stop goroutine","name":"handler #35"},
{"t":501673268,"command":"stop goroutine","name":"handler #21"},
{"t":501675529,"command":"stop goroutine","name":"handler #17"},
{"t":501681274,"command":"stop goroutine","name":"handler #22"},
{"t":501719030,"command":"stop goroutine","name":"handler #38"},
{"t":501719130,"command":"stop goroutine","name":"handler #39"},
{"t":501730414,"command":"stop goroutine","name":"handler #23"},
{"t":501734483,"command":"stop goroutine","name":"handler #32"},
{"t":501741540,"command":"stop goroutine","name":"handler #40"},
{"t":501750190,"command":"stop goroutine","name":"handler #20"},
{"t":501753854,"command":"stop goroutine","name":"handler #18"},
{"t":501758999,"command":"stop goroutine","name":"handler #31"},
{"t":501761693,"command":"stop goroutine","name":"handler #24"},
{"t":501766641,"command":"stop goroutine","name":"handler #19"},
{"t":501772894,"command":"stop goroutine","name":"handler #25"},
{"t":1004317730,"command":"create goroutine","name":"handler #51","parent":"main"},
{"t":1004317863,"command":"create goroutine","name":"handler #49","parent":"main"},
{"t":1004391984,"command":"create goroutine","name":"handler #50","parent":"main"},
{"t":1004412568,"command":"create goroutine","name":"handler #84","parent":"main"},
{"t":1004429210,"command":"create goroutine","name":"handler #67","parent":"main"},
{"t":1004441229,"command":"create goroutine","name":"handler #59","parent":"main"},
{"t":1004455874,"command":"create goroutine","name":"handler #68","parent":"main"},
{"t":1004474259,"command":"create goroutine","name":"handler #60","parent":"main"},
{"t":1004481171,"command":"create goroutine","name":"handler #52","parent":"main"},
{"t":1004496441,"command":"create goroutine","name":"handler #69","parent":"main"},
{"t":1004523673,"command":"create goroutine","name":"handler #53","parent":"main"},
{"t":1004536733,"command":"create goroutine","name":"handler #70","parent":"main"},
{"t":1004541610,"command":"create goroutine","name":"handler #64","parent":"main"},
{"t":1004562671,"command":"create goroutine","name":"handler #54","parent":"main"},
{"t":1004575993,"command":"create goroutine","name":"handler #71","parent":"main"},
{"t":1004591181,"command":"create goroutine","name":"handler #62","parent":"main"},
{"t":1004603233,"command":"create goroutine","name":"handler #55","parent":"main"},
{"t":1004616668,"command":"create goroutine","name":"handler #72","parent":"main"},
{"t":1004632971,"command":"create goroutine","name":"handler #63","parent":"main"},
{"t":1004642638,"command":"create goroutine","name":"handler #56","parent":"main"},
{"t":1004655563,"command":"create goroutine","name":"handler #73","parent":"main"},
{"t":1004674710,"command":"create goroutine","name":"handler #78","parent":"main"},
{"t":1004683100,"command":"create goroutine","name":"handler #57","parent":"main"},
{"t":1004697571,"command":"create goroutine","name":"handler #79","parent":"main"},
{"t":1004725228,"command":"create goroutine","name":"handler #58","parent":"main"},
{"t":1004736513,"command":"create goroutine","name":"handler #80","parent":"main"},
{"t":1004740601,"command":"create goroutine","name":"handler #61","parent":"main"},
{"t":1004764458,"command":"create goroutine","name":"handler #82","parent":"main"},
{"t":1004774814,"command":"create goroutine","name":"handler #83","parent":"main"},
{"t":1004782851,"command":"create goroutine","name":"handler #74","parent":"main"},
{"t":1004804359,"command":"create goroutine","name":"handler #81","parent":"main"},
{"t":1004816759,"command":"create goroutine","name":"handler #65","parent":"main"},
{"t":1004827114,"command":"create goroutine","name":"handler #75","parent":"main"},
{"t":1004843771,"command":"create goroutine","name":"handler #76","parent":"main"},
{"t":1004857800,"command":"create goroutine","name":"handler #66","parent":"main"},
{"t":1004908049,"command":"create goroutine","name":"handler #77","parent":"main"},
{"t":1504492048,"command":"stop goroutine","name":"handler #59"},
{"t":1504492348,"command":"stop goroutine","name":"handler #50"},
{"t":1504539034,"command":"stop goroutine","name":"handler #67"},
{"t":1504539160,"command":"stop goroutine","name":"handler #84"},
{"t":1504553250,"command":"stop goroutine","name":"handler #49"},
{"t":1504568228,"command":"stop goroutine","name":"handler #51"},
{"t":1504583100,"command":"stop goroutine","name":"handler #52"},
{"t":1504585440,"command":"stop goroutine","name":"handler #68"},
{"t":1504595660,"command":"stop goroutine","name":"handler #69"},
{"t":1504598964,"command":"stop goroutine","name":"handler #60"},
{"t":1504605340,"command":"stop goroutine","name":"handler #53"},
{"t":1504615568,"command":"stop goroutine","name":"handler #70"},
{"t":1504628684,"command":"stop goroutine","name":"handler #54"},
{"t":1504639948,"command":"stop goroutine","name":"handler #71"},
{"t":1504640498,"command":"stop goroutine","name":"handler #64"},
{"t":1504652361,"command":"stop goroutine","name":"handler #62"},
{"t":1504667634,"command":"stop goroutine","name":"handler #55"},
{"t":1504672984,"command":"stop goroutine","name":"handler #72"},
{"t":1504688692,"command":"stop goroutine","name":"handler #63"},
{"t":1504699588,"command":"stop goroutine","name":"handler #73"},
{"t":1504714182,"command":"stop goroutine","name":"handler #56"},
{"t":1504730830,"command":"stop goroutine","name":"handler #57"},
{"t":1504730969,"command":"stop goroutine","name":"handler #78"},
{"t":1504745592,"command":"stop goroutine","name":"handler #79"},
{"t":1504769652,"command":"stop goroutine","name":"handler #80"},
{"t":1504780649,"command":"stop goroutine","name":"handler #58"},
{"t":1504814710,"command":"stop goroutine","name":"handler #82"},
{"t":1504821830,"command":"stop goroutine","name":"handler #83"},
{"t":1504847374,"command":"stop goroutine","name":"handler #81"},
{"t":1504872402,"command":"stop goroutine","name":"handler #75"},
{"t":1504884702,"command":"stop goroutine","name":"handler #74"},
{"t":1504885962,"command":"stop goroutine","name":"handler #65"},
{"t":1504906540,"command":"stop goroutine","name":"handler #76"},
{"t":1504912812,"command":"stop goroutine","name":"handler #61"},
{"t":1504918229,"command":"stop goroutine","name":"handler #66"},
{"t":1504974028,"command":"stop goroutine","name":"handler #77"},
{"t":2005465638,"command":"create goroutine","name":"handler #85","parent":"main"},
{"t":2005465813,"command":"create goroutine","name":"handler #103","parent":"main"},
{"t":2005546063,"command":"create goroutine","name":"handler #100","parent":"main"},
{"t":2005553065,"command":"create goroutine","name":"handler #99","parent":"main"},
{"t":2005554786,"command":"create goroutine","name":"handler #117","parent":"main"},
{"t":2005595546,"command":"create goroutine","name":"handler #101","parent":"main"},
{"t":2005598513,"command":"create goroutine","name":"handler #104","parent":"main"},
{"t":2005620499,"command":"create goroutine","name":"handler #118","parent":"main"},
{"t":2005640453,"command":"create goroutine","name":"handler #102","parent":"main"},
{"t":2005671688,"command":"create goroutine","name":"handler #119","parent":"main"},
{"t":2005693771,"command":"create goroutine","name":"handler #97","parent":"main"},
{"t":2005720959,"command":"create goroutine","name":"handler #120","parent":"main"},
{"t":2005741066,"command":"create goroutine","name":"handler #126","parent":"main"},
{"t":2005742718,"command":"create goroutine","name":"handler #105","parent":"main"},
{"t":2005767670,"command":"create goroutine","name":"handler #127","parent":"main"},
{"t":2005790896,"command":"create goroutine","name":"handler #121","parent":"main"},
{"t":2005806283,"command":"create goroutine","name":"handler #98","parent":"main"},
{"t":2005817099,"command":"create goroutine","name":"handler #128","parent":"main"},
{"t":2005836862,"command":"create goroutine","name":"handler #122","parent":"main"},
{"t":2005854562,"command":"create goroutine","name":"handler #111","parent":"main"},
{"t":2005867445,"command":"create goroutine","name":"handler #129","parent":"main"},
{"t":2005881029,"command":"create goroutine","name":"handler #123","parent":"main"},
{"t":2005900831,"command":"create goroutine","name":"handler #106","parent":"main"},
{"t":2005915853,"command":"create goroutine","name":"handler #130","parent":"main"},
{"t":2005924623,"command":"create goroutine","name":"handler #124","parent":"main"},
{"t":2005942922,"command":"create goroutine","name":"handler #107","parent":"main"},
{"t":2005962281,"command":"create goroutine","name":"handler #131","parent":"main"},
{"t":2005984318,"command":"create goroutine","name":"handler #108","parent":"main"},
{"t":2005985291,"command":"create goroutine","name":"handler #125","parent":"main"},
{"t":2006007338,"command":"create goroutine","name":"handler #109","parent":"main"},
{"t":2006032229,"command":"create goroutine","name":"handler #110","parent":"main"},
{"t":2006046371,"command":"create goroutine","name":"handler #112","parent":"main"},
{"t":2006053412,"command":"create goroutine","name":"handler #114","parent":"main"},
{"t":2006092768,"command":"create goroutine","name":"handler #116","parent":"main"},
{"t":2006103608,"command":"create goroutine","name":"handler #113","parent":"main"},
{"t":2006121609,"command":"create goroutine","name":"handler #115","parent":"main"},
{"t":2506141679,"command":"stop goroutine","name":"handler #130"},
{"t":2506158191,"command":"stop goroutine","name":"handler #103"},
{"t":2506161251,"command":"stop goroutine","name":"handler #125"},
{"t":2506167327,"command":"stop goroutine","name":"handler #112"},
{"t":2506201720,"command":"stop goroutine","name":"handler #124"},
{"t":2506211779,"command":"stop goroutine","name":"handler #107"},
{"t":2506220723,"command":"stop goroutine","name":"handler #131"},
{"t":2506233751,"command":"stop goroutine","name":"handler #105"},
{"t":2506233763,"command":"stop goroutine","name":"handler #85"},
{"t":2506235447,"command":"stop goroutine","name":"handler #115"},
{"t":2506249277,"command":"stop goroutine","name":"handler #109"},
{"t":2506251737,"command":"stop goroutine","name":"handler #126"},
{"t":2506259989,"command":"stop goroutine","name":"handler #110"},
{"t":2506263230,"command":"stop goroutine","name":"handler #97"},
{"t":2506265710,"command":"stop goroutine","name":"handler #114"},
{"t":2506271293,"command":"stop goroutine","name":"handler #118"},
{"t":2506272557,"command":"stop goroutine","name":"handler #127"},
{"t":2506275477,"command":"stop goroutine","name":"handler #108"},
{"t":2506284321,"command":"stop goroutine","name":"handler #100"},
{"t":2506284981,"command":"stop goroutine","name":"handler #116"},
{"t":2506292530,"command":"stop goroutine","name":"handler #102"},
{"t":2506294097,"command":"stop goroutine","name":"handler #113"},
{"t":2506302872,"command":"stop goroutine","name":"handler #101"},
{"t":2506311083,"command":"stop goroutine","name":"handler #99"},
{"t":2506312892,"command":"stop goroutine","name":"handler #117"},
{"t":2506317150,"command":"stop goroutine","name":"handler #119"},
{"t":2506322233,"command":"stop goroutine","name":"handler #122"},
{"t":2506322541,"command":"stop goroutine","name":"handler #129"},
{"t":2506327247,"command":"stop goroutine","name":"handler #104"},
{"t":2506332830,"command":"stop goroutine","name":"handler #111"},
{"t":2506337140,"command":"stop goroutine","name":"handler #120"},
{"t":2506342933,"command":"stop goroutine","name":"handler #123"},
{"t":2506347123,"command":"stop goroutine","name":"handler #98"},
{"t":2506348833,"command":"stop goroutine","name":"handler #128"},
{"t":2506352753,"command":"stop goroutine","name":"handler #121"},
{"t":2506357753,"command":"stop goroutine","name":"handler #106"},
{"t":3005754847,"command":"stop goroutine","name":"main"}];
|
/**
* Property graph processing engine
*
* To use this processor engine, load the module, and call the `run()` function
* with the appropriate configuration setting like the following sample shows:
* var engine = require('proper');
* engine.run( getConfiguration() );
*
*/
(function() {
var verbose = false;
var engine = this;
var fs = require('fs');
var jsyaml = require('js-yaml');
var mmconv = require(__dirname + '/mmconv.js');
var mmToLatex = require(__dirname + '/mmToLatex.js');
/**
* Generic reader plugin for yaml format PGL files.
* @param {string} graphFileName The full pathname of the input file
* @return {Object} The content of the input file, that is a graph representation
*/
this.pglYamlReader = function( context ) {
var graphFileName = context.fileName;
// Load the YAML parser module
// Load the 'should' module for validation
require( 'should' );
// Load the YAML format graph file
var graphFile = require( graphFileName );
// TODO: Do validation
// graphFile.should.be.a( 'object' );
// TODO: Merge graphFile data with this.graph
for ( var property in graphFile ) {
if ( graphFile.hasOwnProperty(property) ) {
this.graph[property] = graphFile[property];
}
}
verbose && console.log(JSON.stringify(this, null, " "));
return this;
};
this.oladoTemplateWriter = function( context ) {
var graphFile = this.graph;
var template = fs.readFileSync(context.templateFile,'utf-8');
var doT = require('dot');
doT.templateSettings.strip = false;
console.log( doT.template(template)(graphFile) );
fs.writeFileSync( context.fileName, doT.template(template)(graphFile) );
return graphFile;
}
/**
* Generic writer plugin for dot format graphs
* @param {[type]} graphFile The graph representation with its `_config`
* @return {[type]} The original graph representation (`graphFile`)
*/
this.pglDotWriter = function( context ) {
var graphFile = this.graph;
var config = graphFile['_config'];
var graph = graphFile;
var template = fs.readFileSync(__dirname + '/templates/graphviz.dot','utf-8');
var doT = require('dot');
doT.templateSettings.strip = false;
var digraph = {
title: config._title,
nodes: [],
edges: []
};
for ( var node in graph ) {
if ( graph.hasOwnProperty(node) && node[0] !== '_' ) {
var domain = graph[node]['_domain'] || 'default';
var graphConfig = config['_domains'][domain] || config['_domains']['_default'];
var dnode = {
name: node,
shape: graphConfig['_shape'],
color: graphConfig['_color'],
label: graph[node]['_label'] || node || '',
properties: []
};
if ( graph[node]['_properties'] ) {
graph[node]['_properties'].forEach(function(property) {
dnode.properties.push(property);
});
}
digraph.nodes.push(dnode);
var relations = graph[node]['_relations'];
if ( relations ) {
for ( var relation in relations ) {
if ( relations.hasOwnProperty(relation) ) {
var edge = {
type: relations[relation].type || 'default',
from: node,
to: relations[relation]['_target'],
tailLabel: relations[relation]['_tail'] || '',
headLabel: relations[relation]['_head'] || '',
relLabel: relations[relation]['_label'] || relation || ''
};
if ( relations[relation]['_properties'] ) {
relations[relation]['_properties'].forEach(function(property) {
edge.properties.push(property);
});
}
digraph.edges.push(edge);
}
}
}
}
}
// console.log( doT.template(template)(digraph) );
fs.writeFileSync( context.fileName, doT.template(template)(digraph) );
return graphFile;
};
/**
* Generic writer plugin for markdown format outputs
* @param {[type]} graphFile The graph representation with its `_config`
* @return {[type]} The original graph representation (`graphFile`)
*/
this.pglMdWriter = function( context ) {
var graphFile = this.graph;
var config = graphFile['_config'];
var graph = graphFile;
var template = fs.readFileSync(__dirname + '/templates/markdown.md','utf-8');
var doT = require('dot');
doT.templateSettings.strip = false;
var digraph = {
title: config._title,
nodes: [],
edges: []
};
for ( var node in graph ) {
if ( graph.hasOwnProperty(node) && node[0] !== '_' ) {
var domain = graph[node]['_domain'] || 'default';
var graphConfig = config['_domains'][domain] || config['_domains']['_default'];
var dnode = {
name: node,
description: graph[node]['_description'] || ' ',
domain: graph[node]['_domain'] || 'default',
label: graph[node]['_label'] || node || '',
properties: []
};
if ( graph[node]['_properties'] ) {
graph[node]['_properties'].forEach(function(property) {
dnode.properties.push(property);
});
}
digraph.nodes.push(dnode);
var relations = graph[node]['_relations'];
if ( relations ) {
for ( var relation in relations ) {
if ( relations.hasOwnProperty(relation) ) {
var edge = {
type: relations[relation].type || 'default',
from: node,
to: relations[relation]['_target'],
tailLabel: relations[relation]['_tail'] || '',
headLabel: relations[relation]['_head'] || '',
relLabel: relations[relation]['_label'] || relation || ''
};
if ( relations[relation]['_properties'] ) {
relations[relation]['_properties'].forEach(function(property) {
edge.properties.push(property);
});
}
digraph.edges.push(edge);
}
}
}
}
}
// console.log( doT.template(template)(digraph) );
fs.writeFileSync( context.fileName, doT.template(template)(digraph) );
return graphFile;
};
this.freemindReader = function (context) {
var graphFileName = context.fileName;
// Load the YAML parser module
// Load the 'should' module for validation
require( 'should' );
// Load the freemind format graph file
var graphFile = mmconv.mmToJson( graphFileName, false );
// TODO: Do validation
// graphFile.should.be.a( 'object' );
// TODO: Merge graphFile data with this.graph
for ( var property in graphFile ) {
if ( graphFile.hasOwnProperty(property) ) {
this.graph[property] = graphFile[property];
}
}
verbose && console.log(JSON.stringify(this, null, " "));
return this;
};
this.latexWriter = function (context) {
return mmToLatex.latexWriter(this.graph.map, context.fileName);
};
/**
* Definition of processors to select one, based om `fileType`
* @type {Object}
*/
var processors = {
'preprocessor' : {
'/application/yaml' : this.pglYamlReader,
'/application/pgl-yaml' : this.pglYamlReader,
'/application/freemind' : this.freemindReader
},
'processor' : {
},
'postprocessor' : {
'/application/olado-dot' : this.oladoTemplateWriter,
'/application/pgl-dot' : this.pglDotWriter,
'/application/pgl-markdown' : this.pglMdWriter,
'/application/x-latex' : this.latexWriter
}
};
/**
* Runs a set of processors using their configurations
* @param {Array} processingQueue The processor set with their configuration data
* @return {Object} The result graph of processing
*/
var runProcessors = function(processingQueue, phase) {
var that = this;
verbose && console.log('phase is: ' + phase, processors);
processingQueue.forEach(function(context) {
var processor = processors[phase][context.fileType];
verbose && console.log('runProcessor with ', that, context );
context.graph = processor.apply(that, [context]);
});
return that;
};
/**
* Run the property graph processor engine
* @param {Object} config The configuration settings for the engine
*/
exports.run = function( config ) {
runProcessors.apply(
runProcessors.apply(
runProcessors.apply( {
graph: {}
},
[config.preprocessors, 'preprocessor'] ), // Run preprocessors
[config.processors, 'processor'] ), // Run processors
[config.postprocessors, 'postprocessor'] ); // Run postprocessors
};
})();
|
describe('Optimistic Cache', function () {
var $q = null;
var $rootScope = null;
var optimisticCache = null;
beforeEach(module('rt.optimisticcache'));
beforeEach(inject(function ($injector) {
$q = $injector.get('$q');
$rootScope = $injector.get('$rootScope');
optimisticCache = $injector.get('optimisticCache');
}));
it('Adds a toScope method', function () {
var deferred = $q.defer();
var promise = optimisticCache(deferred.promise, 'test');
assert.isFunction(promise.toScope);
});
it('Scope gets pre-filled if we already have a cached copy', function () {
// Fill cache
var deferred = $q.defer();
var promise = optimisticCache(deferred.promise, 'test');
deferred.resolve({
id: 123
});
$rootScope.$digest();
// Request it again somewhere else
deferred = $q.defer();
promise = optimisticCache(deferred.promise, 'test');
// Should be on scope now
var scope = {};
promise.toScope(scope, 'test');
assert.equal(scope.test.id, 123);
// Scope gets updated when results come in
deferred.resolve({
id: 124
});
$rootScope.$digest();
assert.equal(scope.test.id, 124);
});
it('Updates scope objects in place', function () {
var result = null;
var deferred = $q.defer();
var promise = optimisticCache(deferred.promise, 'test');
promise.then(function (obj) {
result = obj;
});
deferred.resolve({
id: 1,
name: 'Ruben'
});
var scope = {};
var result2 = null;
deferred = $q.defer();
promise = optimisticCache(deferred.promise, 'test');
promise.toScope(scope, 'person').then(function (obj) {
result2 = obj;
assert.equal(result2, result);
});
assert.equal(scope.person, result);
deferred.resolve({ id: 1, name: 'Ruben' });
assert.equal(result2, result);
assert.equal(scope.person, result);
});
it('Updates scope arrays in place', function () {
var result = null;
var deferred = $q.defer();
var promise = optimisticCache(deferred.promise, 'test');
promise.then(function (obj) {
result = obj;
});
deferred.resolve([
{ id: 1, name: 'Ruben' },
{ id: 2, name: 'Test' }
]);
var scope = {};
var result2 = null;
deferred = $q.defer();
promise = optimisticCache(deferred.promise, 'test');
promise.toScope(scope, 'people').then(function (obj) {
result2 = obj;
assert.equal(result2, result);
});
assert.equal(scope.people, result);
deferred.resolve([
{ id: 1, name: 'Test 2' },
{ id: 2, name: 'Test 3' }
]);
assert.equal(result2, result);
assert.equal(scope.people, result);
});
it('Uses results from getAll to pre-populate get', function () {
var deferred = $q.defer();
var promise = optimisticCache(deferred.promise, 'test');
deferred.resolve([
{ id: 1, name: 'Ruben' },
{ id: 2, name: 'Test' }
]);
$rootScope.$digest();
var scope = {};
var result = null;
deferred = $q.defer();
promise = optimisticCache(deferred.promise, 'test/1');
promise.toScope(scope, 'person').then(function (obj) {
result = obj;
});
assert.equal(scope.person.name, 'Ruben');
deferred.resolve({ id: 1, name: 'New' });
$rootScope.$digest();
assert.equal(result.name, 'New');
assert.equal(scope.person, result);
});
it('Can disable pre-populate', function () {
var deferred = $q.defer();
var promise = optimisticCache(deferred.promise, 'test', {
populateChildren: false
});
deferred.resolve([
{ id: 1, name: 'Ruben' },
{ id: 2, name: 'Test' }
]);
$rootScope.$digest();
var scope = {};
var result = null;
deferred = $q.defer();
promise = optimisticCache(deferred.promise, 'test/1');
promise.toScope(scope, 'person').then(function (obj) {
result = obj;
});
// Expect a cache miss
assert.equal(scope.person, undefined);
deferred.resolve({ id: 1, name: 'New' });
$rootScope.$digest();
assert.equal(result.name, 'New');
assert.equal(scope.person, result);
});
it('Can expire caches', function () {
// Fill cache
var deferred = $q.defer();
var promise = optimisticCache(deferred.promise, 'test');
deferred.resolve({
id: 123
});
$rootScope.$digest();
// Clear cache
optimisticCache.clear();
// Request it again somewhere else
deferred = $q.defer();
promise = optimisticCache(deferred.promise, 'test');
// Should not be on the scope, it's not cached anymore
var scope = {};
promise.toScope(scope, 'test');
assert.equal(scope.test, undefined);
// Scope gets updated when results come in
deferred.resolve({
id: 124
});
$rootScope.$digest();
assert.equal(scope.test.id, 124);
});
it('Can use different ID field');
});
|
const fs = require("fs");
const path = require("path");
const https = require("https");
const url = require("url");
const replace = require("replace-in-file");
module.exports = () => {
let cssPath = path.join(process.cwd(), "./node_modules/antd/dist/antd.css");
const options = {
files: ["node_modules/antd/dist/*.css"],
from: /https:\/\/at\.alicdn\.com\/t\//g,
to: "./"
};
console.log("download antd's font file...");
let cssContent = fs.readFileSync(cssPath, {
encoding: "utf8"
});
const distDir = path.join(process.cwd(), "./node_modules/antd/dist");
let urlRegex = /https:\/\/at\.alicdn\.com\/t\/font_[_a-zA-Z0-9]+\.(eot|woff|ttf|svg)\b/g;
let fonts = new Set(cssContent.match(urlRegex));
let downloadAll = [];
for (let f of fonts) {
downloadAll.push(
new Promise((resolve, reject) => {
download(
f,
path.join(distDir, path.parse(url.parse(f).path).base),
err => {
if (err) {
reject(err);
}
resolve();
}
);
})
);
}
return Promise.all(downloadAll)
.then(() => replace(options))
.then(changedfiles => {
console.log("modified files:", changedfiles.join(", "));
})
.catch(err => {
console.error(err);
throw err;
});
};
function download(url, dist, callback) {
let file = fs.createWriteStream(dist);
https
.get(url, function(response) {
response.pipe(file);
file.on("finish", function() {
file.close(); // close() is async, call cb after close completes.
callback();
});
})
.on("error", function(err) {
// Handle errors
fs.unlink(dist); // Delete the file async. (But we don't check the result)
if (callback) callback(err);
});
}
|
const webpack = require('webpack');
const SpriteLoaderPlugin = require('svg-sprite-loader/plugin');
module.exports = {
entry: {
app: './src/js/main.js'
},
module: {
rules: [
{
test: /\.js$/,
exclude: [/node_module/],
use: {
loader: 'babel-loader',
options: {
presets: ['env']
}
}
},
{
test: /\.svg$/,
use: [
{
loader: 'svg-sprite-loader',
options: {
extract: true,
spriteFilename: 'icons.svg'
}
},
'svgo-loader'
]
}
]
},
plugins: [
new webpack.EnvironmentPlugin([
'NODE_ENV'
]),
new SpriteLoaderPlugin()
]
};
|
module.exports = function(mongoose) {
var Comment = new mongoose.Schema({
userId: { type: String },
firstName: { type: String },
lastName: { type: String },
comment: { type: String },
date: { type: Date } // When the comment was added
});
var Like = new mongoose.Schema({
userId: { type: String },
firstName: { type: String },
lastName: { type: String },
date: { type: Date } // When the like was added
});
var PhotoSchema = new mongoose.Schema({
userId: { type: String },
firstName: { type: String }, //
lastName: { type: String }, //
photoUrl: { type: String },
caption: { type: String },
dateTaken: { type: Date },
removed: {type: String}, //0-not removed, 1-removed
photoWidth: { type: String },
photoHeight: { type: String },
comments: [Comment],
likes: [Like]
});
var Photo = mongoose.model('Photo', PhotoSchema);
//OK
var addPhoto = function(userId, firstName, lastName, photoUrl, caption,photoWidth,photoHeight, callback) {
var photo = new Photo({
userId: userId,
firstName: firstName,
lastName: lastName,
photoUrl: photoUrl,
caption: caption,
dateTaken: new Date(),
photoWidth: photoWidth,
photoHeight: photoHeight,
removed: 0
});
photo.save(function(err) {
if (err) {
callback(false);
console.log('Error adding the photo: ' + err);
}else{
callback(true);
console.log('Photo was added');
}
});
}
//OK (photo is not deleted from db.. only the flag 'removed' is set to '1' (1 means deleted)
var removePhoto = function(photo, callback) {
if ( null == photo ) return;
photo.removed ="1";
photo.save(function(err) {
if (err) {
callback(false);
console.log('Error deleting the photo: ' + err);
}else{
callback(true);
console.log('Photo was deleted');
}
});
}
//OK
var findById = function(photoId, callback) {
Photo.findOne({_id:photoId}, function(err,doc) {
callback(doc);
});
}
//OK
var getUserPhotos = function(userId, callback) {
Photo.find({userId:userId, removed: "0"}, {}, {sort: {dateTaken: -1}}, function(err,doc) { //check
callback(doc);
});
}
//returns:
/*
[
{
"_id": "53ff492d49aa9e681b000004",
"photoUrl": "urllllllllllllllll",
"caption": "captionnnnnnnnnn",
"dateTaken": "2014-08-28T15:22:21.220Z",
"removed": "0",
"__v": 0,
"likes": [],
"comments": []
},
...
]
*/
//OK
var getAllPhotos = function(callback) {
Photo.find({}, {}, {sort: {dateTaken: -1}}, function(err,doc) { //check
callback(doc);
});
}
//OK
var getPhotosByUsers = function(usersIdArray, callback) { //users = id1 id2 ...
Photo.find( {userId : {$in : usersIdArray }, removed: 0}, {} , {sort: {dateTaken: -1}} , function(err,result) {
callback(result);
});
}
//OK
var addComment = function( photo, userId, firstName, lastName, comment, callback ) {
var newComment = {
userId: userId,
firstName: firstName,
lastName: lastName,
comment: comment,
date: new Date()
};
photo.comments.push(newComment);
photo.save(function (err) {
if (err) {
console.log('Error adding a comment: ' + err);
callback(false);
}else{
console.log('Comment was added');
callback(true);
}
});
};
//OK
var addOrRemoveLike = function( photo, userId, firstName, lastName, callback ) {
var newLike = {
userId: userId,
firstName: firstName,
lastName: lastName,
date: new Date()
};
var hasLikeFromUser = false;
if ( null != photo.likes ){
photo.likes.forEach(function(like) {
if ( like.userId == userId ) {
hasLikeFromUser = true;
photo.likes.remove(like);
console.log('Like was removed');
photo.save();
}
});
}
if(!hasLikeFromUser){
photo.likes.push(newLike);
photo.save(function (err) {
if (err) {
console.log('Error adding like: ' + err);
callback(false);
}else{
console.log('Like was added');
callback(true);
}
});
}else{
callback(true);
}
};
return {
findById: findById,
addPhoto: addPhoto,
removePhoto: removePhoto,
getUserPhotos: getUserPhotos,
getPhotosByUsers: getPhotosByUsers,
addComment: addComment,
addOrRemoveLike: addOrRemoveLike,
getAllPhotos: getAllPhotos,
Photo: Photo
}
}
|
/**
* Gen 1 mechanics are fairly different to those we know on current gen.
* Therefor we need to make a lot of changes to the battle engine for this game simulation.
* This generation inherits all the changes from older generations, that must be taken into account when editing code.
*/
exports.BattleScripts = {
inherit: 'gen2',
gen: 1,
debug: function (activity) {
if (this.getFormat().debug) {
this.add('debug', activity);
}
},
// Gen 1 stores the last damage dealt by a move in the battle.
// This is used for the move Counter.
lastDamage: 0,
// BattleSide scripts.
// In gen 1, last move information is stored on the side rather than on the active Pokémon.
// This is because there was actually no side, just Battle and active Pokémon effects.
// Side's lastMove is used for Counter and Mirror Move.
side: {
lastMove: ''
},
// BattlePokemon scripts.
pokemon: {
getStat: function (statName, unboosted, unmodified, noscreens) {
statName = toId(statName);
if (statName === 'hp') return this.maxhp;
// base stat
var stat = this.stats[statName];
// stat boosts
if (!unboosted) {
var boost = this.boosts[statName];
if (boost > 6) boost = 6;
if (boost < -6) boost = -6;
if (boost >= 0) {
var boostTable = [1, 1.5, 2, 2.5, 3, 3.5, 4];
stat = Math.floor(stat * boostTable[boost]);
} else {
var numerators = [100, 66, 50, 40, 33, 28, 25];
stat = Math.floor(stat * numerators[-boost] / 100);
}
}
// Stat modifiers: burn, paralyse.
if (!unmodified) {
// Burn attack drop is checked when you get the attack stat upon switch in and used until switch out.
if (this.volatiles['brnattackdrop'] && statName === 'atk') {
stat = this.battle.clampIntRange(Math.floor(stat / 2), 1);
}
if (this.volatiles['parspeeddrop'] && statName === 'spe') {
stat = this.battle.clampIntRange(Math.floor(stat / 4), 1);
}
}
// Hard coded Reflect and Light Screen boosts
if (this.volatiles['reflect'] && statName === 'def' && !unboosted && !noscreens) {
this.battle.debug('Reflect doubles Defense');
stat *= 2;
stat = this.battle.clampIntRange(stat, 1, 1998);
} else if (this.volatiles['lightscreen'] && statName === 'spd' && !unboosted && !noscreens) {
this.battle.debug('Light Screen doubles Special Defense');
stat *= 2;
stat = this.battle.clampIntRange(stat, 1, 1998);
} else {
// Gen 1 normally caps stats at 999 and min is 1.
stat = this.battle.clampIntRange(stat, 1, 999);
}
return stat;
}
},
// Battle scripts.
// runMove can be found in scripts.js. This function is the main one when running a move.
// It deals with the beforeMove and AfterMoveSelf events.
// This leads with partial trapping moves shennanigans after the move has been used.
// It also deals with how PP reduction works on gen 1.
runMove: function (move, pokemon, target, sourceEffect) {
move = this.getMove(move);
if (!target) target = this.resolveTarget(pokemon, move);
if (target.subFainted) delete target.subFainted;
this.setActiveMove(move, pokemon, target);
if (pokemon.movedThisTurn || !this.runEvent('BeforeMove', pokemon, target, move)) {
// Prevent invulnerability from persisting until the turn ends.
pokemon.removeVolatile('twoturnmove');
this.clearActiveMove(true);
// This is only run for sleep.
this.runEvent('AfterMoveSelf', pokemon, target, move);
return;
}
if (move.beforeMoveCallback) {
if (move.beforeMoveCallback.call(this, pokemon, target, move)) {
this.clearActiveMove(true);
return;
}
}
pokemon.lastDamage = 0;
var lockedMove = this.runEvent('LockMove', pokemon);
if (lockedMove === true) lockedMove = false;
if (!lockedMove && (!pokemon.volatiles['partialtrappinglock'] || pokemon.volatiles['partialtrappinglock'].locked !== target)) {
pokemon.deductPP(move, null, target);
// On gen 1 moves are stored when they are chosen and a PP is deducted.
pokemon.side.lastMove = move;
pokemon.lastMove = move;
}
this.useMove(move, pokemon, target, sourceEffect);
this.runEvent('AfterMove', target, pokemon, move);
// If rival fainted
if (target.hp <= 0) {
// We remove recharge
if (pokemon.volatiles['mustrecharge']) pokemon.removeVolatile('mustrecharge');
delete pokemon.volatiles['partialtrappinglock'];
// We remove screens
target.side.removeSideCondition('reflect');
target.side.removeSideCondition('lightscreen');
pokemon.removeVolatile('twoturnmove');
} else {
this.runEvent('AfterMoveSelf', pokemon, target, move);
}
// For partial trapping moves, we are saving the target
if (move.volatileStatus === 'partiallytrapped' && target && target.hp > 0) {
// Let's check if the lock exists
if (pokemon.volatiles['partialtrappinglock'] && target.volatiles['partiallytrapped']) {
// Here the partialtrappinglock volatile has been already applied
if (!pokemon.volatiles['partialtrappinglock'].locked) {
// If it's the first hit, we save the target
pokemon.volatiles['partialtrappinglock'].locked = target;
} else {
if (pokemon.volatiles['partialtrappinglock'].locked !== target && target !== pokemon) {
// The target switched, therefor, we must re-roll the duration, damage, and accuracy.
var duration = [2, 2, 2, 3, 3, 3, 4, 5][this.random(8)];
pokemon.volatiles['partialtrappinglock'].duration = duration;
pokemon.volatiles['partialtrappinglock'].locked = target;
// Duration reset thus partially trapped at 2 always.
target.volatiles['partiallytrapped'].duration = 2;
// We deduct an additional PP that was not deducted earlier.
// Also get the move position for the PP change.
var usedMovePos = -1;
for (var m in pokemon.moveset) {
if (pokemon.moveset[m].id === move.id) usedMovePos = m;
}
if (usedMovePos > -1 && pokemon.moveset[usedMovePos].pp === 0) {
// If we were on the middle of the 0 PP sequence, the PPs get reset to 63.
pokemon.moveset[usedMovePos].pp = 63;
} else {
// Otherwise, plain reduct.
pokemon.deductPP(move, null, target);
}
}
}
} // If we move to here, the move failed and there's no partial trapping lock.
}
},
// useMove can be found on scripts.js
// It is the function that actually uses the move, running ModifyMove events.
// It uses the move and then deals with the effects after the move.
useMove: function (move, pokemon, target, sourceEffect) {
if (!sourceEffect && this.effect.id) sourceEffect = this.effect;
move = this.getMove(move);
var baseMove = move;
move = this.getMoveCopy(move);
if (!target) target = this.resolveTarget(pokemon, move);
if (move.target === 'self') {
target = pokemon;
}
if (sourceEffect) move.sourceEffect = sourceEffect.id;
this.setActiveMove(move, pokemon, target);
this.singleEvent('ModifyMove', move, null, pokemon, target, move, move);
if (baseMove.target !== move.target) {
// Target changed in ModifyMove, so we must adjust it here
target = this.resolveTarget(pokemon, move);
}
move = this.runEvent('ModifyMove', pokemon, target, move, move);
if (baseMove.target !== move.target) {
// Check again, this shouldn't ever happen on Gen 1.
target = this.resolveTarget(pokemon, move);
}
if (!move) return false;
var attrs = '';
var missed = false;
if (pokemon.fainted) {
// Removing screens upon faint.
pokemon.side.removeSideCondition('reflect');
pokemon.side.removeSideCondition('lightscreen');
return false;
}
if (move.isTwoTurnMove && !pokemon.volatiles[move.id]) {
attrs = '|[still]'; // Suppress the default move animation
}
if (sourceEffect) attrs += '|[from]' + this.getEffect(sourceEffect);
this.addMove('move', pokemon, move.name, target + attrs);
if (!this.singleEvent('Try', move, null, pokemon, target, move)) {
return true;
}
if (!this.runEvent('TryMove', pokemon, target, move)) {
return true;
}
if (typeof move.affectedByImmunities === 'undefined') {
move.affectedByImmunities = (move.category !== 'Status');
}
var damage = false;
if (target.fainted) {
this.attrLastMove('[notarget]');
this.add('-notarget');
return true;
}
damage = this.tryMoveHit(target, pokemon, move);
// Store 0 damage for last damage if move failed or dealt 0 damage.
// This only happens on moves that don't deal damage but call GetDamageVarsForPlayerAttack (disassembly).
if (!damage && (move.category !== 'Status' || (move.category === 'Status' && !(move.status in {'psn':1, 'tox':1, 'par':1}))) &&
!(move.id in {'conversion':1, 'haze':1, 'mist':1, 'focusenergy':1, 'confuseray':1, 'transform':1, 'lightscreen':1, 'reflect':1, 'substitute':1, 'mimic':1, 'leechseed':1, 'splash':1, 'softboiled':1, 'recover':1, 'rest':1})) {
pokemon.battle.lastDamage = 0;
}
// Go ahead with results of the used move.
if (!damage && damage !== 0) {
this.singleEvent('MoveFail', move, null, target, pokemon, move);
return true;
}
if (!move.negateSecondary) {
this.singleEvent('AfterMoveSecondarySelf', move, null, pokemon, target, move);
this.runEvent('AfterMoveSecondarySelf', pokemon, target, move);
}
return true;
},
// tryMoveHit can be found on scripts.js
// This function attempts a move hit and returns the attempt result before the actual hit happens.
// It deals with partial trapping weirdness and accuracy bugs as well.
tryMoveHit: function (target, pokemon, move, spreadHit) {
var boostTable = [1, 4 / 3, 5 / 3, 2, 7 / 3, 8 / 3, 3];
var doSelfDestruct = true;
var damage = 0;
// First, let's calculate the accuracy.
var accuracy = move.accuracy;
// Partial trapping moves: true accuracy while it lasts
if (move.volatileStatus === 'partiallytrapped' && pokemon.volatiles['partialtrappinglock'] && target === pokemon.volatiles['partialtrappinglock'].locked) {
accuracy = true;
}
// If a sleep inducing move is used while the user is recharging, the accuracy is true.
if (move.status === 'slp' && target && target.volatiles['mustrecharge']) {
accuracy = true;
}
// Calculate true accuracy for gen 1, which uses 0-255.
if (accuracy !== true) {
accuracy = Math.floor(accuracy * 255 / 100);
// Check also for accuracy modifiers.
if (!move.ignoreAccuracy) {
if (pokemon.boosts.accuracy > 0) {
accuracy *= boostTable[pokemon.boosts.accuracy];
} else {
accuracy = Math.floor(accuracy / boostTable[-pokemon.boosts.accuracy]);
}
}
if (!move.ignoreEvasion) {
if (target.boosts.evasion > 0 && !move.ignorePositiveEvasion) {
accuracy = Math.floor(accuracy / boostTable[target.boosts.evasion]);
} else if (target.boosts.evasion < 0) {
accuracy *= boostTable[-target.boosts.evasion];
}
}
}
accuracy = this.runEvent('Accuracy', target, pokemon, move, accuracy);
// Moves that target the user do not suffer from the 1/256 miss chance.
if (move.target === 'self' && accuracy !== true) accuracy++;
// 1/256 chance of missing always, no matter what. Besides the aforementioned exceptions.
if (accuracy !== true && this.random(256) >= accuracy) {
this.attrLastMove('[miss]');
this.add('-miss', pokemon);
damage = false;
}
// Check if the Pokémon is immune to this move.
if (move.affectedByImmunities && !target.runImmunity(move.type, true)) {
damage = false;
}
// If damage is 0 and not false it means it didn't miss, let's calc.
if (damage !== false) {
pokemon.lastDamage = 0;
if (move.multihit) {
var hits = move.multihit;
if (hits.length) {
// Yes, it's hardcoded... meh
if (hits[0] === 2 && hits[1] === 5) {
hits = [2, 2, 3, 3, 4, 5][this.random(6)];
} else {
hits = this.random(hits[0], hits[1] + 1);
}
}
hits = Math.floor(hits);
// In gen 1, all the hits have the same damage for multihits move
var moveDamage = 0;
var firstDamage;
var i;
for (i = 0; i < hits && target.hp && pokemon.hp; i++) {
if (i === 0) {
// First hit, we calculate
moveDamage = this.moveHit(target, pokemon, move);
firstDamage = moveDamage;
} else {
// We get the previous damage to make it fix damage
move.damage = firstDamage;
moveDamage = this.moveHit(target, pokemon, move);
}
if (moveDamage === false) break;
damage = (moveDamage || 0);
if (target.subFainted) {
i++;
break;
}
}
move.damage = null;
if (i === 0) return true;
this.add('-hitcount', target, i);
} else {
damage = this.moveHit(target, pokemon, move);
}
}
if (move.category !== 'Status') target.gotAttacked(move, damage, pokemon);
// Checking if substitute fainted
if (target.subFainted) doSelfDestruct = false;
if (move.selfdestruct && doSelfDestruct) {
this.faint(pokemon, pokemon, move);
}
// The move missed.
if (!damage && damage !== 0) {
// Delete the partial trap lock if necessary.
delete pokemon.volatiles['partialtrappinglock'];
return false;
}
if (!move.negateSecondary) {
this.singleEvent('AfterMoveSecondary', move, null, target, pokemon, move);
this.runEvent('AfterMoveSecondary', target, pokemon, move);
}
return damage;
},
// move Hit can be found on scripts.js
// It deals with the actual move hit, as the name indicates, dealing damage and/or effects.
// This function also deals with the Gen 1 Substitute behaviour on the hitting process.
moveHit: function (target, pokemon, move, moveData, isSecondary, isSelf) {
var damage = 0;
move = this.getMoveCopy(move);
if (!isSecondary && !isSelf) this.setActiveMove(move, pokemon, target);
var hitResult = true;
if (!moveData) moveData = move;
if (typeof move.affectedByImmunities === 'undefined') {
move.affectedByImmunities = (move.category !== 'Status');
}
// We get the sub to the target to see if it existed
var targetSub = (target) ? target.volatiles['substitute'] : false;
var targetHadSub = (targetSub !== null && targetSub !== false && (typeof targetSub !== 'undefined'));
if (target) {
hitResult = this.singleEvent('TryHit', moveData, {}, target, pokemon, move);
// Handle here the applying of partial trapping moves to Pokémon with Substitute
if (targetSub && moveData.volatileStatus && moveData.volatileStatus === 'partiallytrapped') {
target.addVolatile(moveData.volatileStatus, pokemon, move);
}
if (!hitResult) {
if (hitResult === false) this.add('-fail', target);
return false;
}
// Only run the hit events for the hit itself, not the secondary or self hits
if (!isSelf && !isSecondary) {
hitResult = this.runEvent('TryHit', target, pokemon, move);
if (!hitResult) {
if (hitResult === false) this.add('-fail', target);
// Special Substitute hit flag
if (hitResult !== 0) {
return false;
}
}
if (!this.runEvent('TryFieldHit', target, pokemon, move)) {
return false;
}
} else if (isSecondary && !moveData.self) {
hitResult = this.runEvent('TrySecondaryHit', target, pokemon, moveData);
}
if (hitResult === 0) {
target = null;
} else if (!hitResult) {
if (hitResult === false) this.add('-fail', target);
return false;
}
}
if (target) {
var didSomething = false;
damage = this.getDamage(pokemon, target, moveData);
// getDamage has several possible return values:
//
// a number:
// means that much damage is dealt (0 damage still counts as dealing
// damage for the purposes of things like Static)
// false:
// gives error message: "But it failed!" and move ends
// null:
// the move ends, with no message (usually, a custom fail message
// was already output by an event handler)
// undefined:
// means no damage is dealt and the move continues
//
// basically, these values have the same meanings as they do for event
// handlers.
if ((damage || damage === 0) && !target.fainted) {
if (move.noFaint && damage >= target.hp) {
damage = target.hp - 1;
}
damage = this.damage(damage, target, pokemon, move);
if (!(damage || damage === 0)) return false;
didSomething = true;
} else if (damage === false && typeof hitResult === 'undefined') {
this.add('-fail', target);
}
if (damage === false || damage === null) {
return false;
}
if (moveData.boosts && !target.fainted) {
this.boost(moveData.boosts, target, pokemon, move);
}
if (moveData.heal && !target.fainted) {
var d = target.heal(Math.floor(target.maxhp * moveData.heal[0] / moveData.heal[1]));
if (!d) {
this.add('-fail', target);
return false;
}
this.add('-heal', target, target.getHealth);
didSomething = true;
}
if (moveData.status) {
// Gen 1 bug: If the target has just used hyperbeam and must recharge, its status will be ignored and put to sleep.
// This does NOT revert the paralyse speed drop or the burn attack drop.
if (!target.status || moveData.status === 'slp' && target.volatiles['mustrecharge']) {
target.setStatus(moveData.status, pokemon, move);
} else if (!isSecondary) {
if (target.status === moveData.status) {
this.add('-fail', target, target.status);
} else {
this.add('-fail', target);
}
}
didSomething = true;
}
if (moveData.forceStatus) {
if (target.setStatus(moveData.forceStatus, pokemon, move)) {
didSomething = true;
}
}
if (moveData.volatileStatus) {
if (target.addVolatile(moveData.volatileStatus, pokemon, move)) {
didSomething = true;
}
}
if (moveData.sideCondition) {
if (target.side.addSideCondition(moveData.sideCondition, pokemon, move)) {
didSomething = true;
}
}
if (moveData.pseudoWeather) {
if (this.addPseudoWeather(moveData.pseudoWeather, pokemon, move)) {
didSomething = true;
}
}
// Hit events
hitResult = this.singleEvent('Hit', moveData, {}, target, pokemon, move);
if (!isSelf && !isSecondary) {
this.runEvent('Hit', target, pokemon, move);
}
if (!hitResult && !didSomething) {
if (hitResult === false) this.add('-fail', target);
return false;
}
}
var targetHasSub = false;
if (target) {
var targetSub = target.getVolatile('substitute');
if (targetSub !== null) {
targetHasSub = (targetSub.hp > 0);
}
}
// Here's where self effects are applied.
var doSelf = (targetHadSub && targetHasSub) || !targetHadSub;
if (moveData.self && (doSelf || moveData.self.volatileStatus === 'partialtrappinglock')) {
this.moveHit(pokemon, pokemon, move, moveData.self, isSecondary, true);
}
// Now we can save the partial trapping damage.
if (pokemon.volatiles['partialtrappinglock']) {
pokemon.volatiles['partialtrappinglock'].damage = pokemon.lastDamage;
}
// Apply move secondaries.
if (moveData.secondaries) {
for (var i = 0; i < moveData.secondaries.length; i++) {
// We check here whether to negate the probable secondary status if it's para, burn, or freeze.
// In the game, this is checked and if true, the random number generator is not called.
// That means that a move that does not share the type of the target can status it.
// If a move that was not fire-type would exist on Gen 1, it could burn a Pokémon.
if (!(moveData.secondaries[i].status && moveData.secondaries[i].status in {'par':1, 'brn':1, 'frz':1} && target && target.hasType(move.type))) {
var effectChance = Math.floor(moveData.secondaries[i].chance * 255 / 100);
if (typeof moveData.secondaries[i].chance === 'undefined' || this.random(256) < effectChance) {
this.moveHit(target, pokemon, move, moveData.secondaries[i], true, isSelf);
}
}
}
}
if (move.selfSwitch && pokemon.hp) {
pokemon.switchFlag = move.selfSwitch;
}
return damage;
},
// boost can be found on battle-engine.js on Battle object.
// It deals with Pokémon stat boosting, including Gen 1 buggy behaviour with burn and paralyse.
boost: function (boost, target, source, effect) {
if (this.event) {
if (!target) target = this.event.target;
if (!source) source = this.event.source;
if (!effect) effect = this.effect;
}
if (!target || !target.hp) return 0;
effect = this.getEffect(effect);
boost = this.runEvent('Boost', target, source, effect, Object.clone(boost));
for (var i in boost) {
var currentBoost = {};
currentBoost[i] = boost[i];
if (boost[i] !== 0 && target.boostBy(currentBoost)) {
var msg = '-boost';
if (boost[i] < 0) {
msg = '-unboost';
boost[i] = -boost[i];
// Re-add attack and speed drops if not present
if (i === 'atk' && target.status === 'brn' && !target.volatiles['brnattackdrop']) {
target.addVolatile('brnattackdrop');
}
if (i === 'spe' && target.status === 'par' && !target.volatiles['parspeeddrop']) {
target.addVolatile('parspeeddrop');
}
} else {
// Check for boost increases deleting attack or speed drops
if (i === 'atk' && target.status === 'brn' && target.volatiles['brnattackdrop']) {
target.removeVolatile('brnattackdrop');
}
if (i === 'spe' && target.status === 'par' && target.volatiles['parspeeddrop']) {
target.removeVolatile('parspeeddrop');
}
}
if (effect.effectType === 'Move') {
this.add(msg, target, i, boost[i]);
} else {
this.add(msg, target, i, boost[i], '[from] ' + effect.fullname);
}
this.runEvent('AfterEachBoost', target, source, effect, currentBoost);
}
}
this.runEvent('AfterBoost', target, source, effect, boost);
},
// damage can be found in battle-engine.js on the Battle object. Not to confuse with BattlePokemon.prototype.damage
// It calculates and executes the damage damage from source to target with effect.
// It also deals with recoil and drains.
damage: function (damage, target, source, effect) {
if (this.event) {
if (!target) target = this.event.target;
if (!source) source = this.event.source;
if (!effect) effect = this.effect;
}
if (!target || !target.hp) return 0;
effect = this.getEffect(effect);
if (!(damage || damage === 0)) return damage;
if (damage !== 0) damage = this.clampIntRange(damage, 1);
if (effect.id !== 'struggle-recoil') { // Struggle recoil is not affected by effects
damage = this.runEvent('Damage', target, source, effect, damage);
if (!(damage || damage === 0)) {
this.debug('damage event failed');
return damage;
}
}
if (damage !== 0) damage = this.clampIntRange(damage, 1);
if (!(effect.id in {'recoil':1, 'drain':1})) target.battle.lastDamage = damage;
damage = target.damage(damage, source, effect);
if (source) source.lastDamage = damage;
var name = effect.fullname;
if (name === 'tox') name = 'psn';
switch (effect.id) {
case 'partiallytrapped':
this.add('-damage', target, target.getHealth, '[from] ' + this.effectData.sourceEffect.fullname, '[partiallytrapped]');
break;
default:
if (effect.effectType === 'Move') {
this.add('-damage', target, target.getHealth);
} else if (source && source !== target) {
this.add('-damage', target, target.getHealth, '[from] ' + effect.fullname, '[of] ' + source);
} else {
this.add('-damage', target, target.getHealth, '[from] ' + name);
}
break;
}
if (effect.recoil && source) {
this.damage(this.clampIntRange(Math.floor(damage * effect.recoil[0] / effect.recoil[1]), 1), source, target, 'recoil');
}
if (effect.drain && source) {
this.heal(this.clampIntRange(Math.floor(damage * effect.drain[0] / effect.drain[1]), 1), source, target, 'drain');
}
if (target.fainted || target.hp <= 0) {
this.faint(target);
this.queue = [];
} else {
damage = this.runEvent('AfterDamage', target, source, effect, damage);
}
return damage;
},
// directDamage can be found on battle-engine.js in Battle object
// It deals direct damage damage from source to target with effect.
// It also deals with Gen 1 weird Substitute behaviour.
directDamage: function (damage, target, source, effect) {
if (this.event) {
if (!target) target = this.event.target;
if (!source) source = this.event.source;
if (!effect) effect = this.effect;
}
if (!target || !target.hp) return 0;
if (!damage) return 0;
damage = this.clampIntRange(damage, 1);
// Check here for Substitute on confusion since it's not exactly a move that causes the damage and thus it can't TryMoveHit.
// The hi jump kick recoil also hits the sub.
if (effect.id in {'confusion': 1, 'highjumpkick': 1} && target.volatiles['substitute']) {
target.volatiles['substitute'].hp -= damage;
if (target.volatiles['substitute'].hp <= 0) {
target.removeVolatile('substitute');
target.subFainted = true;
} else {
this.add('-activate', target, 'Substitute', '[damage]');
}
} else {
damage = target.damage(damage, source, effect);
// Now we sent the proper -damage.
switch (effect.id) {
case 'strugglerecoil':
this.add('-damage', target, target.getHealth, '[from] recoil');
break;
case 'confusion':
this.add('-damage', target, target.getHealth, '[from] confusion');
break;
default:
this.add('-damage', target, target.getHealth);
break;
}
if (target.fainted) this.faint(target);
}
return damage;
},
// getDamage can be found on battle-engine.js on the Battle object.
// It calculates the damage pokemon does to target with move.
getDamage: function (pokemon, target, move, suppressMessages) {
// First of all, we get the move.
if (typeof move === 'string') move = this.getMove(move);
if (typeof move === 'number') move = {
basePower: move,
type: '???',
category: 'Physical',
flags: {}
};
// Let's see if the target is immune to the move.
if (move.affectedByImmunities) {
if (!target.runImmunity(move.type, true)) {
return false;
}
}
// Is it an OHKO move?
if (move.ohko) {
// If it is, move hits if the Pokémon is faster.
if (target.speed > pokemon.speed) {
this.add('-failed', target);
return false;
}
return target.maxhp;
}
// We edit the damage through move's damage callback if necessary.
if (move.damageCallback) {
return move.damageCallback.call(this, pokemon, target);
}
// We take damage from damage=level moves (seismic toss).
if (move.damage === 'level') {
return pokemon.level;
}
// If there's a fix move damage, we return that.
if (move.damage) {
return move.damage;
}
// If it's the first hit on a Normal-type partially trap move, it hits Ghosts anyways but damage is 0.
if (move.volatileStatus === 'partiallytrapped' && move.type === 'Normal' && target.hasType('Ghost')) {
return 0;
}
// Let's check if we are in middle of a partial trap sequence to return the previous damage.
if (pokemon.volatiles['partialtrappinglock'] && (target === pokemon.volatiles['partialtrappinglock'].locked)) {
return pokemon.volatiles['partialtrappinglock'].damage;
}
// We check the category and typing to calculate later on the damage.
if (!move.category) move.category = 'Physical';
if (!move.defensiveCategory) move.defensiveCategory = move.category;
// '???' is typeless damage: used for Struggle and Confusion etc
if (!move.type) move.type = '???';
var type = move.type;
// We get the base power and apply basePowerCallback if necessary.
var basePower = move.basePower;
if (move.basePowerCallback) {
basePower = move.basePowerCallback.call(this, pokemon, target, move);
}
// We check if the base power is proper.
if (!basePower) {
if (basePower === 0) return; // Returning undefined means not dealing damage
return basePower;
}
basePower = this.clampIntRange(basePower, 1);
// Checking for the move's Critical Hit possibility. We check if it's a 100% crit move, otherwise we calculate the chance.
move.crit = move.willCrit || false;
if (!move.crit) {
// In gen 1, the critical chance is based on speed.
// First, we get the base speed, divide it by 2 and floor it. This is our current crit chance.
var critChance = Math.floor(pokemon.template.baseStats['spe'] / 2);
// Now we check for focus energy volatile.
if (pokemon.volatiles['focusenergy']) {
// If it exists, crit chance is divided by 2 again and floored.
critChance = Math.floor(critChance / 2);
} else {
// Normally, without focus energy, crit chance is multiplied by 2 and capped at 255 here.
critChance = this.clampIntRange(critChance * 2, 1, 255);
}
// Now we check for the move's critical hit ratio.
if (move.critRatio === 1) {
// Normal hit ratio, we divide the crit chance by 2 and floor the result again.
critChance = Math.floor(critChance / 2);
} else if (move.critRatio === 2) {
// High crit ratio, we multiply the result so far by 4 and cap it at 255.
critChance = this.clampIntRange(critChance * 4, 1, 255);
}
// Last, we check deppending on ratio if the move critical hits or not.
// We compare our critical hit chance against a random number between 0 and 255.
// If the random number is lower, we get a critical hit. This means there is always a 1/255 chance of not hitting critically.
if (critChance > 0) {
move.crit = (this.random(256) < critChance);
}
}
// Happens after crit calculation.
if (basePower) {
basePower = this.runEvent('BasePower', pokemon, target, move, basePower);
if (move.basePowerModifier) {
basePower *= move.basePowerModifier;
}
}
if (!basePower) return 0;
basePower = this.clampIntRange(basePower, 1);
// We now check attacker's and defender's stats.
var level = pokemon.level;
var attacker = pokemon;
var defender = target;
if (move.useTargetOffensive) attacker = target;
if (move.useSourceDefensive) defender = pokemon;
var atkType = (move.category === 'Physical') ? 'atk' : 'spa';
var defType = (move.defensiveCategory === 'Physical') ? 'def' : 'spd';
var attack = attacker.getStat(atkType);
var defense = defender.getStat(defType);
// In the event of a critical hit, the ofense and defense changes are ignored.
// This includes both boosts and screens.
// Also, level is doubled in damage calculation.
if (move.crit) {
move.ignoreOffensive = true;
move.ignoreDefensive = true;
level *= 2;
if (!suppressMessages) this.add('-crit', target);
}
if (move.ignoreOffensive) {
this.debug('Negating (sp)atk boost/penalty.');
attack = attacker.getStat(atkType, true, true);
}
if (move.ignoreDefensive) {
this.debug('Negating (sp)def boost/penalty.');
defense = target.getStat(defType, true);
}
// When either attack or defense are higher than 256, they are both divided by 4 and moded by 256.
// This is what cuases the roll over bugs.
if (attack >= 256 || defense >= 256) {
attack = this.clampIntRange(Math.floor(attack / 4) % 256, 1);
// Defense isn't checked on the cartridge, but we don't want those / 0 bugs on the sim.
defense = this.clampIntRange(Math.floor(defense / 4) % 256, 1);
}
// Self destruct moves halve defense at this point.
if (move.selfdestruct && defType === 'def') {
defense = this.clampIntRange(Math.floor(defense / 2), 1);
}
// Let's go with the calculation now that we have what we need.
// We do it step by step just like the game does.
var damage = level * 2;
damage = Math.floor(damage / 5);
damage += 2;
damage *= basePower;
damage *= attack;
damage = Math.floor(damage / defense);
damage = this.clampIntRange(Math.floor(damage / 50), 1, 997);
damage += 2;
// STAB damage bonus, the "???" type never gets STAB
if (type !== '???' && pokemon.hasType(type)) {
damage += Math.floor(damage / 2);
}
// Type effectiveness.
// The order here is not correct, must change to check the move versus each type.
var totalTypeMod = this.getEffectiveness(type, target);
// Super effective attack
if (totalTypeMod > 0) {
if (!suppressMessages) this.add('-supereffective', target);
damage *= 20;
damage = Math.floor(damage / 10);
if (totalTypeMod >= 2) {
damage *= 20;
damage = Math.floor(damage / 10);
}
}
if (totalTypeMod < 0) {
if (!suppressMessages) this.add('-resisted', target);
damage *= 5;
damage = Math.floor(damage / 10);
if (totalTypeMod <= -2) {
damage *= 5;
damage = Math.floor(damage / 10);
}
}
// If damage becomes 0, the move is made to miss.
// This occurs when damage was either 2 or 3 prior to applying STAB/Type matchup, and target is 4x resistant to the move.
if (damage === 0) return damage;
// Apply random factor is damage is greater than 1
if (damage > 1) {
damage *= this.random(217, 256);
damage = Math.floor(damage / 255);
if (damage > target.hp && !target.volatiles['substitute']) damage = target.hp;
if (target.volatiles['substitute'] && damage > target.volatiles['substitute'].hp) damage = target.volatiles['substitute'].hp;
}
// And we are done.
return Math.floor(damage);
},
// This is random teams making for gen 1.
// Challenge Cup or CC teams are basically fully random teams.
randomCCTeam: function (side) {
var teamdexno = [];
var team = [];
// Pick six random Pokémon, no repeats.
for (var i = 0; i < 6; i++) {
while (true) {
var x = Math.floor(Math.random() * 151) + 1;
if (teamdexno.indexOf(x) === -1) {
teamdexno.push(x);
break;
}
}
}
for (var i = 0; i < 6; i++) {
// Choose forme.
var formes = [];
for (var j in this.data.Pokedex) {
if (this.data.Pokedex[j].num === teamdexno[i] && this.getTemplate(this.data.Pokedex[j].species).learnset && this.data.Pokedex[j].species !== 'Pichu-Spiky-eared') {
formes.push(this.data.Pokedex[j].species);
}
}
var poke = formes.sample();
var template = this.getTemplate(poke);
// Level balance: calculate directly from stats rather than using some silly lookup table.
var mbstmin = 1307; // sunkern has the lowest modified base stat total, and that total is 807
var stats = template.baseStats;
// Modified base stat total assumes 30 IVs, 255 EVs in every stat
var mbst = (stats["hp"] * 2 + 30 + 63 + 100) + 10;
mbst += (stats["atk"] * 2 + 30 + 63 + 100) + 5;
mbst += (stats["def"] * 2 + 30 + 63 + 100) + 5;
mbst += (stats["spa"] * 2 + 30 + 63 + 100) + 5;
mbst += (stats["spd"] * 2 + 30 + 63 + 100) + 5;
mbst += (stats["spe"] * 2 + 30 + 63 + 100) + 5;
var level = Math.floor(100 * mbstmin / mbst); // Initial level guess will underestimate
while (level < 100) {
mbst = Math.floor((stats["hp"] * 2 + 30 + 63 + 100) * level / 100 + 10);
mbst += Math.floor(((stats["atk"] * 2 + 30 + 63 + 100) * level / 100 + 5) * level / 100); //since damage is roughly proportional to lvl
mbst += Math.floor((stats["def"] * 2 + 30 + 63 + 100) * level / 100 + 5);
mbst += Math.floor(((stats["spa"] * 2 + 30 + 63 + 100) * level / 100 + 5) * level / 100);
mbst += Math.floor((stats["spd"] * 2 + 30 + 63 + 100) * level / 100 + 5);
mbst += Math.floor((stats["spe"] * 2 + 30 + 63 + 100) * level / 100 + 5);
if (mbst >= mbstmin)
break;
level++;
}
// Random DVs
var ivs = {
hp: Math.floor(Math.random() * 30),
atk: Math.floor(Math.random() * 30),
def: Math.floor(Math.random() * 30),
spa: Math.floor(Math.random() * 30),
spd: Math.floor(Math.random() * 30),
spe: Math.floor(Math.random() * 30)
};
// ALl EVs
var evs = {
hp: 255,
atk: 255,
def: 255,
spa: 255,
spd: 255,
spe: 255
};
// Four random unique moves from movepool. don't worry about "attacking" or "viable".
var moves;
var pool = ['struggle'];
pool = Object.keys(template.learnset);
if (pool.length <= 4) {
moves = pool;
} else {
moves = pool.sample(4);
}
team.push({
name: poke,
moves: moves,
ability: 'None',
evs: evs,
ivs: ivs,
item: '',
level: level,
happiness: 0,
shiny: false,
nature: 'Serious'
});
}
return team;
},
// Random team generation for Gen 1 Random Battles.
randomTeam: function (side) {
var kagimarpSet = [
{
name: "Magikarp",
moves: ["boost", "freeze", "flinch", "damage"],
ability: 'None',
evs: { hp: 255, atk: 255, def: 255, spa: 255, spd: 255, spe: 255 },
ivs: { hp: 30, atk: 30, def: 30, spa: 30, spd: 30, spe: 30 },
item: '',
level: 666,
shiny: false,
gender: false }
]
// Get what we need ready.
var keys = [];
var pokemonLeft = 0;
var pokemon = [];
var i = 1;
// We need to check it's one of the first 151 because formats data are installed onto main format data, not replaced.
for (var n in this.data.FormatsData) {
if (this.data.FormatsData[n].randomBattleMoves && i < 152) {
keys.push(n);
}
i++;
}
keys = keys.randomize();
// Now let's store what we are getting.
var typeCount = {};
var weaknessCount = {'electric':0, 'psychic':0, 'water':0, 'ice':0};
var uberCount = 0;
var nuCount = 0;
var hasShitmon = false;
for (var i = 0; i < keys.length && pokemonLeft < 6; i++) {
var template = this.getTemplate(keys[i]);
if (!template || !template.name || !template.types) continue;
// Bias the tiers so you get less shitmons and only one of the two Ubers.
// If you have a shitmon, you're covered in OUs and Ubers if possible
var tier = template.tier;
if (tier === 'LC' && (nuCount > 1 || hasShitmon)) continue;
if ((tier === 'NFE' || tier === 'UU') && (hasShitmon || (nuCount > 2 && this.random(1)))) continue;
// Unless you have one of the worst mons, in that case we allow luck to give you both Mew and Mewtwo.
if (tier === 'Uber' && uberCount >= 1 && !hasShitmon) continue;
// We need a weakness count of spammable attacks to avoid being swept by those.
// Spammable attacks are: Thunderbolt, Psychic, Surf, Blizzard.
var skip = false;
Object.keys(weaknessCount).forEach(function (type) {
var notImmune = Tools.getImmunity(type, template);
if (notImmune && Tools.getEffectiveness(type, template) > 0) {
weaknessCount[type]++;
}
if (weaknessCount[type] > 2) skip = true;
});
if (skip) continue;
// Limit 2 of any type as well. Diversity and minor weakness count.
// The second of a same type has halved chance of being added.
var types = template.types;
for (var t = 0; t < types.length; t++) {
if (typeCount[types[t]] > 1 || (typeCount[types[t]] === 1 && this.random(1))) {
skip = true;
break;
}
}
if (skip) continue;
// The set passes the limitations.
var set = this.randomSet(template, i);
pokemon.push(set);
// Now let's increase the counters. First, the Pokémon left.
pokemonLeft++;
// Type counter.
for (var t = 0; t < types.length; t++) {
if (types[t] in typeCount) {
typeCount[types[t]]++;
} else {
typeCount[types[t]] = 1;
}
}
// Increment type bias counters.
if (tier === 'Uber') {
uberCount++;
} else if (tier === 'UU' || tier === 'NFE' || tier === 'LC') {
nuCount++;
}
if (keys[i] in {'magikarp':1}) {
return kagimarpSet
}
// Is it Magikarp?
if (keys[i] in {'magikarp':1, 'weedle':1, 'kakuna':1, 'caterpie':1, 'metapod':1, 'ditto':1}) {
hasShitmon = true;
}
}
return pokemon;
},
// Random set generation for Gen 1 Random Battles.
randomSet: function (template, i) {
if (i === undefined) i = 1;
template = this.getTemplate(template);
if (!template.exists) template = this.getTemplate('pikachu'); // Because Gen 1.
var moveKeys = template.randomBattleMoves;
moveKeys = moveKeys.randomize();
var moves = [];
var hasType = {};
hasType[template.types[0]] = true;
if (template.types[1]) hasType[template.types[1]] = true;
var hasMove = {};
var counter = {};
var setupType = '';
var j = 0;
do {
// Choose next 4 moves from learnset/viable moves and add them to moves list:
var howMany = (template.essentialMove) ? 3 : 4;
while (moves.length < howMany && j < moveKeys.length) {
var moveid = toId(moveKeys[j]);
j++;
moves.push(moveid);
}
// Add now the mandatory move
if (template.essentialMove) {
moves.unshift(template.essentialMove);
j++;
}
// Only do move choosing if we have more than four on the moveset...
if (moveKeys.length > howMany) {
hasMove = {};
counter = {Physical: 0, Special: 0, Status: 0, physicalsetup: 0, specialsetup: 0};
for (var k = 0; k < moves.length; k++) {
var move = this.getMove(moves[k]);
var moveid = move.id;
hasMove[moveid] = true;
if (!move.damage && !move.damageCallback) {
counter[move.category]++;
}
if ({swordsdance:1, sharpen:1}[moveid]) {
counter['physicalsetup']++;
}
if ({amnesia:1, growth:1}[moveid]) {
counter['specialsetup']++;
}
}
if (counter['specialsetup']) {
setupType = 'Special';
} else if (counter['physicalsetup']) {
setupType = 'Physical';
}
for (var k = 0; k < moves.length; k++) {
var moveid = moves[k];
var move = this.getMove(moveid);
var rejected = false;
if (hasMove[moveid]) rejected = true;
if (!template.essentialMove || moveid !== template.essentialMove) {
var isSetup = false;
switch (moveid) {
// bad after setup
case 'seismictoss': case 'nightshade':
if (setupType) rejected = true;
break;
// bit redundant to have both
case 'flamethrower':
if (hasMove['fireblast']) rejected = true;
break;
case 'fireblast':
if (hasMove['flamethrower']) rejected = true;
break;
case 'icebeam':
if (hasMove['blizzard']) rejected = true;
break;
// Hydropump and surf are both valid options, just avoid one with eachother.
case 'hydropump':
if (hasMove['surf']) rejected = true;
break;
case 'surf':
if (hasMove['hydropump']) rejected = true;
break;
case 'petaldance': case 'solarbeam':
if (hasMove['megadrain'] || hasMove['razorleaf']) rejected = true;
break;
case 'megadrain':
if (hasMove['razorleaf']) rejected = true;
break;
case 'thunder':
if (hasMove['thunderbolt']) rejected = true;
break;
case 'thunderbolt':
if (hasMove['thunder']) rejected = true;
break;
case 'bonemerang':
if (hasMove['earthquake']) rejected = true;
break;
case 'rest':
if (hasMove['recover'] || hasMove['softboiled']) rejected = true;
break;
case 'softboiled':
if (hasMove['recover']) rejected = true;
break;
case 'sharpen':
case 'swordsdance':
if (counter['Special'] > counter['Physical'] || hasMove['slash'] || !counter['Physical'] || hasMove['growth']) rejected = true;
break;
case 'growth':
if (counter['Special'] < counter['Physical'] || hasMove['swordsdance']) rejected = true;
break;
case 'doubleedge':
if (hasMove['bodyslam']) rejected = true;
break;
case 'mimic':
if (hasMove['mirrormove']) rejected = true;
break;
case 'superfang':
if (hasMove['bodyslam']) rejected = true;
break;
case 'rockslide':
if (hasMove['earthquake'] && hasMove['bodyslam'] && hasMove['hyperbeam']) rejected = true;
break;
case 'bodyslam':
if (hasMove['thunderwave']) rejected = true;
break;
case 'bubblebeam':
if (hasMove['blizzard']) rejected = true;
break;
case 'screech':
if (hasMove['slash']) rejected = true;
break;
case 'slash':
if (hasMove['swordsdance']) rejected = true;
break;
case 'megakick':
if (hasMove['bodyslam']) rejected = true;
break;
case 'eggbomb':
if (hasMove['hyperbeam']) rejected = true;
break;
case 'triattack':
if (hasMove['doubleedge']) rejected = true;
break;
case 'growth':
if (hasMove['amnesia']) rejected = true;
break;
case 'supersonic':
if (hasMove['confuseray']) rejected = true;
break;
case 'poisonpowder':
if (hasMove['toxic'] || counter['Status'] > 1) rejected = true;
break;
case 'stunspore':
if (hasMove['sleeppowder'] || counter['Status'] > 1) rejected = true;
break;
case 'sleeppowder':
if (hasMove['stunspore'] || counter['Status'] > 2) rejected = true;
break;
case 'toxic':
if (hasMove['sleeppowder'] || hasMove['stunspore'] || counter['Status'] > 1) rejected = true;
break;
} // End of switch for moveid
}
if (rejected && j < moveKeys.length) {
moves.splice(k, 1);
break;
}
counter[move.category]++;
} // End of for
} // End of the check for more than 4 moves on moveset.
} while (moves.length < 4 && j < moveKeys.length);
var levelScale = {
LC: 96,
NFE: 90,
UU: 85,
OU: 79,
Uber: 74
};
// Really bad Pokemon and jokemons, MEWTWO, Pokémon with higher tier in Wrap metas.
var customScale = {
Caterpie: 99, Kakuna: 99, Magikarp: 99, Metapod: 99, Weedle: 99,
Clefairy: 95, "Farfetch'd": 99, Jigglypuff: 99, Ditto: 99, Mewtwo: 70,
Dragonite: 85, Cloyster: 83, Staryu: 90
};
var level = levelScale[template.tier] || 90;
if (customScale[template.name]) level = customScale[template.name];
if (template.name === 'Mewtwo' && hasMove['amnesia']) level = 68;
return {
name: template.name,
moves: moves,
ability: 'None',
evs: {hp: 255, atk: 255, def: 255, spa: 255, spd: 255, spe: 255},
ivs: {hp: 30, atk: 30, def: 30, spa: 30, spd: 30, spe: 30},
item: '',
level: level,
shiny: false,
gender: false
};
}
};
|
"use strict";
let datafire = require('datafire');
let openapi = require('./openapi.json');
module.exports = datafire.Integration.fromOpenAPI(openapi, "keyserv_solutions");
|
"use strict";
(function (socket_path, thread_id) {
var socket = io(socket_path)
, thread_id = 6
, commentLists = []
, commentBox;
socket.emit('comment/list', {thread_id: thread_id});
socket.on('user', function (user) {
var comments = [];
var submitCallback = function (replyTo, body) {
socket.emit('comment/post', {body: body, thread_id: thread_id, replyTo: replyTo});
};
var likeCallback = function (id) {
socket.emit('comment/like', {comment_id: id});
};
/**
* @param integer commentId
* @param integer commentReplyId The replyId of commentId
*/
var getRepliesCallback = function (commentId, commentReplyId) {
var reset = false;
// If the trail is already open then we want to close it
if (commentLists[commentId] !== undefined) {
reset = true;
}
// Delete all list after the list matching commentReplyId
for (var id in commentLists) {
// If the id matches the commentReplyId then all loops going
// forward will delete the lists
if (id === commentReplyId) {
commentLists.length = parseInt(id) + 1;
break;
}
}
if (reset === false) {
socket.emit('comment/list', {commentId: commentId});
} else {
commentBox.setState({commentLists: commentLists});
}
};
var renderList = function (list) {
commentBox = React.renderComponent(
CommentBox({
key: 'CommentBox',
user: user,
getRepliesCallback: getRepliesCallback,
likeCallback: likeCallback,
submitCallback: submitCallback,
initialCommentLists: list
}),
document.getElementById('CommentListContainer')
);
};
socket.on('comment/list', function (data) {
commentLists[data.commentId] = data.comments;
renderList(commentLists);
});
socket.on('comment/replies', function (data) {
commentLists[data.commentId] = data.comments;
commentBox.setState({commentLists: commentLists});
});
socket.on('comment/post/confirmation', function (data) {
commentLists[data.replyTo].unshift(data.comment);
commentBox.setState({commentLists: commentLists});
});
});
window.socket;
})(socket_path, thread_id);
|
/**
* <http://stackoverflow.com/a/5158301>
*/
function getParameterByName(name) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
|
var path = require('path');
var webpack = require('webpack');
var writeStats = require('./utils/writeStats');
var notifyStats = require('./utils/notifyStats');
var assetsPath = path.resolve(__dirname, '../static/dist');
var host = 'localhost';
var port = parseInt(process.env.PORT) + 1 || 3001;
module.exports = {
devtool: 'eval-source-map',
context: path.resolve(__dirname, '..'),
entry: {
'main': [
'webpack-dev-server/client?http://' + host + ':' + port,
'webpack/hot/only-dev-server',
'./src/client.js'
]
},
output: {
path: assetsPath,
filename: '[name]-[hash].js',
chunkFilename: '[name]-[chunkhash].js',
publicPath: 'http://' + host + ':' + port + '/dist/'
},
module: {
loaders: [
{ test: /\.(jpe?g|png|gif|svg)$/, loader: 'url', query: {limit: 10240} },
{ test: /\.js$/, exclude: /node_modules/, loaders: ['react-hot', 'babel?stage=0&optional=runtime&plugins=typecheck']},
{ test: /\.json$/, loader: 'json-loader' },
{ test: /\.scss$/, loader: 'style!css?modules&importLoaders=2&localIdentName=[local]___[hash:base64:5]!autoprefixer?browsers=last 2 version!sass?outputStyle=expanded&sourceMap=true&sourceMapContents=true' }
]
},
progress: true,
resolve: {
modulesDirectories: [
'src',
'node_modules'
],
extensions: ['', '.json', '.js']
},
plugins: [
// hot reload
new webpack.HotModuleReplacementPlugin(),
new webpack.WatchIgnorePlugin([/\.json$/]),
new webpack.NoErrorsPlugin(),
new webpack.DefinePlugin({
__CLIENT__: true,
__SERVER__: false,
__DEVELOPMENT__: true,
__DEVTOOLS__: true // <-------- DISABLE redux-devtools HERE
}),
// stats
function () {
this.plugin('done', notifyStats);
},
function () {
this.plugin('done', function(stats) {
writeStats.call(this, stats, 'dev');
});
}
]
};
|
'use strict';
const _ = require('lodash');
const EntityHelper = require('../entity_helper');
const ExpenseClaim = require('../../entities/accounting/expenseclaim')
.ExpenseClaim;
const ExpenseClaims = EntityHelper.extend({
constructor: function(application, options) {
EntityHelper.call(
this,
application,
Object.assign({ entityPlural: 'ExpenseClaims' }, options)
);
},
newExpenseClaim: function(data, options) {
return new ExpenseClaim(this.application, data, options);
},
getExpenseClaims: function(options) {
return this.getEntities(this.setUpOptions(options));
},
getExpenseClaim: function(id) {
return this.getExpenseClaims({ id }).then(expenseClaims =>
_.first(expenseClaims)
);
},
saveExpenseClaims: function(expenseClaims, options) {
return this.saveEntities(expenseClaims, this.setUpOptions(options));
},
setUpOptions: function(options) {
const self = this;
const clonedOptions = _.clone(options || {});
clonedOptions.entityPath = 'ExpenseClaims';
clonedOptions.entityConstructor = data => self.newExpenseClaim(data);
return clonedOptions;
},
});
module.exports = ExpenseClaims;
|
// ==UserScript==
// @name SteamGifts GA input
// @description Adds input on top menu where you can enter 5characters of GA id and it will open the GA page for you.
// @author Bladito
// @version 1.0.0
// @homepageURL https://greasyfork.org/en/users/55159-bladito
// @match https://www.steamgifts.com/*
// @namespace Bladito/sg-ga-input
// @require http://code.jquery.com/jquery-latest.js
// @grant GM_addStyle
// ==/UserScript==
(function($) {
'use strict';
var $input = $('<input id="bsg-ga-input">');
$input.on('input', function(event) {
var value = event.target.value;
if (value.length === 5) {
var url = 'https://www.steamgifts.com/giveaway/' + value + '/';
$.get(url, function(data) {
if ($(data).find('.sidebar__navigation__item__name').text().indexOf('Entries') > -1) { // it is a giveaway page
window.open(url, '_blank');
$('#bsg-ga-input').removeClass('bsg-invalid');
} else {
$('#bsg-ga-input').addClass('bsg-invalid');
}
});
}
});
$('.nav__left-container').append($input);
addStyles();
//---------------------------------------------------------------------------------
function addStyles() {
GM_addStyle('#bsg-ga-input { ' +
'width: 100px;' +
'color: white;' +
'background-color: #3d434f;' +
'border: 1px solid #6e7788;' +
'}');
GM_addStyle('#bsg-ga-input:focus { ' +
'color: black;' +
'background-color: white;' +
'}');
GM_addStyle('#bsg-ga-input.bsg-invalid { ' +
'border: 1px solid red;' +
'}');
GM_addStyle('#bsg-ga-input.bsg-invalid:focus { ' +
'background-color: #ffd2d2;' +
'border: 1px solid red;' +
'}');
}
})(jQuery);
|
'use strict';
(function(module) {
function MyProject (proj) {
for (let keys in proj) {
this[keys] = proj[keys]
}
}
MyProject.allProjects = [];
MyProject.prototype.toHtml = function() {
var htmlTemplate = $('#template').html();
var template = Handlebars.compile(htmlTemplate);
return template(this);
};
MyProject.loadAll = function(project) {
project.forEach(function(ele) {
MyProject.allProjects.push(new MyProject(ele))
});
}
MyProject.getAll = function() {
if (localStorage.projects) {
var lStorageMyProjects = JSON.parse(localStorage.getItem('projects'));
MyProject.loadAll(lStorageMyProjects)
MyProject.showProjects(lStorageMyProjects)
} else {
$.getJSON('./data/projects.json').then(
function(data) {
localStorage.setItem('projects', JSON.stringify(data))
var lData = JSON.parse(localStorage.getItem('projects'));
MyProject.loadAll(lData);
MyProject.showProjects(lData)
}
);
}
};
MyProject.displayTheGroupProjects = function() {
return MyProject.allProjects.map(function(projects2) {
return projects2
})
.reduce(function(acc, curr) {
if (acc.indexOf(curr) === -1) {
acc.push(curr)
}
return acc;
}, []);
}
//MyProject.displayTheGroupProjects();
module.MyProject = MyProject;
})(window);
|
var dir_647e010a77631e7624f52ccf2ba3318e =
[
[ "html", "dir_04014538701d9c618e4a0af4f034e730.html", "dir_04014538701d9c618e4a0af4f034e730" ]
];
|
import React from 'react';
import Comment from './comment';
export default class CommentList extends React.Component {
render() {
var commentNodes = this.props.data.map(function(comment){
return (
<Comment author={comment.author} key={comment.id}>
{comment.text}
</Comment>
);
});
return (
<div className="commentList">
{commentNodes}
</div>
);
}
}
|
import HalAdapter from "ember-data-hal-9000/adapter";
import DS from "ember-data";
import Ember from "ember";
import config from "../config/environment";
let accessToken;
export function setAccessToken(token) {
accessToken = token;
}
export function getAccessToken() {
return accessToken;
}
export default HalAdapter.extend({
host: config.apiBaseUri,
headers: Ember.computed(function(){
if (!getAccessToken()) {
return {};
}
return {
'Authorization': 'Bearer ' + getAccessToken()
};
}).volatile(),
pathForType: function(type){
if (type === 'stack') {
type = 'account';
}
if(type === 'criterion') {
return 'criteria';
}
return this._super(type);
},
ajaxError: function(jqXHR){
var error = this._super(jqXHR);
if (jqXHR && jqXHR.status === 422) {
var payload = Ember.$.parseJSON(jqXHR.responseText);
return new DS.InvalidError({
message: payload.message
});
} else {
return error;
}
}
});
|
export default {
el: {
colorpicker: {
confirm: 'Qabul qilish',
clear: 'Tozalash'
},
datepicker: {
now: 'Hozir',
today: 'Bugun',
cancel: 'Bekor qilish',
clear: 'Tozalash',
confirm: 'Qabul qilish',
selectDate: 'Kunni tanlash',
selectTime: 'Soatni tanlash',
startDate: 'Boshlanish sanasi',
startTime: 'Boshlanish vaqti',
endDate: 'Tugash sanasi',
endTime: 'Tugash vaqti',
prevYear: 'Oʻtgan yil',
nextYear: 'Kelgusi yil',
prevMonth: 'Oʻtgan oy',
nextMonth: 'Kelgusi oy',
year: 'Yil',
month1: 'Yanvar',
month2: 'Fevral',
month3: 'Mart',
month4: 'Aprel',
month5: 'May',
month6: 'Iyun',
month7: 'Iyul',
month8: 'Avgust',
month9: 'Sentabr',
month10: 'Oktabr',
month11: 'Noyabr',
month12: 'Dekabr',
week: 'Hafta',
weeks: {
sun: 'Yak',
mon: 'Dush',
tue: 'Sesh',
wed: 'Chor',
thu: 'Pay',
fri: 'Jum',
sat: 'Shan'
},
months: {
jan: 'Yan',
feb: 'Fev',
mar: 'Mar',
apr: 'Apr',
may: 'May',
jun: 'Iyun',
jul: 'Iyul',
aug: 'Avg',
sep: 'Sen',
oct: 'Okt',
nov: 'Noy',
dec: 'Dek'
}
},
select: {
loading: 'Yuklanmoqda',
noMatch: 'Mos maʼlumot yoʻq',
noData: 'Maʼlumot yoʻq',
placeholder: 'Tanladizngiz'
},
cascader: {
noMatch: 'Mos maʼlumot topilmadi',
loading: 'Yuklanmoqda',
placeholder: 'Tanlash',
noData: 'Maʼlumot yoʻq'
},
pagination: {
goto: 'Oʻtish',
pagesize: '/sahifa',
total: 'Barchasi {total} ta',
pageClassifier: ''
},
messagebox: {
title: 'Xabar',
confirm: 'Qabul qilish',
cancel: 'Bekor qilish',
error: 'Xatolik'
},
upload: {
deleteTip: 'Oʻchirish tugmasini bosib oʻchiring',
delete: 'Oʻchirish',
preview: 'Oldin koʻrish',
continue: 'Davom qilish'
},
table: {
emptyText: 'Boʻsh',
confirmFilter: 'Qabul qilish',
resetFilter: 'Oldingi holatga qaytarish',
clearFilter: 'Jami',
sumText: 'Summasi'
},
tree: {
emptyText: 'Maʼlumot yoʻq'
},
transfer: {
noMatch: 'Mos maʼlumot topilmadi',
noData: 'Maʼlumot yoʻq',
titles: ['1-jadval', '2-jadval'],
filterPlaceholder: 'Kalit soʻzni kiriting',
noCheckedFormat: '{total} ta element',
hasCheckedFormat: '{checked}/{total} ta belgilandi'
},
image: {
error: 'Xatolik'
},
pageHeader: {
title: 'Orqaga'
},
popconfirm: {
confirmButtonText: 'Yes', // to be translated
cancelButtonText: 'No' // to be translated
},
empty: {
description: 'Boʻsh'
}
}
};
|
$(function() {
var widgets = [];
var currentWidget = 0;
function updateWidgets() {
$.ajax({
url: '/widgets.json',
}).success(function(result) {
widgets = result;
iterate();
}).always(function(result) {
setTimeout(updateWidgets, 2000);
});
}
updateWidgets();
function iterate() {
console.log("Currentwidget:", currentWidget)
var widget_name = widgets[currentWidget];
console.log("Name:", widget_name)
$.ajax({
url: '/widgets-' + widget_name + '.html',
}).success(function(result) {
var template = Handlebars.compile(result);
$.ajax({
url: '/widgets-' + widget_name + '.json',
}).success(function(result) {
context = result;
var html = template(context);
$(".view").empty().append(html);
}).always(function(result) {
// setTimeout(iterate, 2000);
});
});
// setTimeout(iterate, 2000);
currentWidget += 1;
if(currentWidget >= widgets.length) {
currentWidget = 0;
}
}
});
|
const path = require('path')
const execa = require('execa')
const logger = require('./lib/logger')
const { exampleAppsToRun } = require('./lib/paths')
const { createBundle } = require('./lib/bundle')
const bundle = createBundle()
const executeTest = (projectPath) => {
// we change current directory
process.chdir(projectPath)
// reading package.json
const projectPkg = require(path.join(projectPath, 'package.json'))
if (!projectPkg.name) projectPkg.name = 'unknown'
if (!projectPkg.version) projectPkg.version = 'unknown'
logger.log()
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
logger.log('='.repeat(20), `${projectPkg.name}@${projectPkg.version}`, 'in', projectPath, '='.repeat(20))
logger.log()
// then we install it in the repo
logger.log('ensuring all dependencies of target project are installed')
logger.log()
execa.sync('npm', ['ci'], { cwd: projectPath })
logger.log()
logger.log('installing bundled version of ts-jest')
logger.log()
execa.sync('npm', ['install', '--no-package-lock', '--no-shrinkwrap', '--no-save', bundle], { cwd: projectPath })
logger.log()
// then we can run the tests
const cmdLine = ['npm', 'run', 'test']
const cmdIsolatedLine = ['npm', 'run', 'test-isolated']
const cmdESMLine = ['npm', 'run', 'test-esm']
const cmdESMIsolatedLine = ['npm', 'run', 'test-esm-isolated']
logger.log('starting the CommonJS tests with `isolatedModules: false` using:', ...cmdLine)
logger.log()
execa.sync(cmdLine.shift(), cmdLine, {
cwd: projectPath,
stdio: 'inherit',
env: process.env,
})
logger.log()
logger.log('starting the CommonJS tests with `isolatedModules: true` using:', ...cmdIsolatedLine)
logger.log()
execa.sync(cmdIsolatedLine.shift(), cmdIsolatedLine, {
cwd: projectPath,
stdio: 'inherit',
env: process.env,
})
logger.log()
logger.log('starting the ESM tests with `isolatedModules: false` using:', ...cmdESMLine)
logger.log()
execa.sync(cmdESMLine.shift(), cmdESMLine, {
cwd: projectPath,
stdio: 'inherit',
env: process.env,
})
logger.log()
logger.log('starting the ESM tests with `isolatedModules: true` using:', ...cmdESMIsolatedLine)
logger.log()
execa.sync(cmdESMIsolatedLine.shift(), cmdESMIsolatedLine, {
cwd: projectPath,
stdio: 'inherit',
env: process.env,
})
logger.log()
}
exampleAppsToRun.forEach((projectPath) => {
executeTest(projectPath)
})
|
/* global phantom, exports, require, console */
(function () {
'use strict';
exports.resolveUrl = function (url, verbose) {
var fs = require('fs');
// assume http if no protocol is specified
// and we're not looking at a local file
if (!url.match(/:\/\//)) {
if (!fs.exists(url)) {
url = 'http://' + url;
if (verbose) {
console.log('Missing protocol, assuming http');
}
} else if (verbose) {
console.log('"' + url + '" exists locally, using that.');
console.log('Prepend a protocol (e.g. http:// or https://) to override this behavior');
}
}
return url;
};
exports.loadWithLibs = function (url, verbose, onload, width) {
var page = require('webpage').create();
if (width) {
page.viewportSize = { width: width, height: 800 };
}
page.open(url, function (status) {
if (status !== 'success' && verbose) {
console.log('Failed to load "' + url + '"');
phantom.exit();
} else {
if(page.evaluate(function () { return typeof jQuery; }) !== 'function') {
page.injectJs('vendor/jquery-1.8.2.js');
}
if(page.evaluate(function () { return typeof _; }) !== 'function') {
page.injectJs('vendor/underscore-1.4.2.js');
}
page.injectJs('lib/obj.js');
page.injectJs('lib/css.js');
page.onConsoleMessage = function (msg) {
console.log(msg);
};
page.evaluate(function () {
/* global $ */
if(window.fullyLoaded !== true) { // do not check twice
window.fullyLoaded = false;
$(function () { window.fullyLoaded = true; });
}
});
politelyWait(
function () {
return page.evaluate(function () { return window.fullyLoaded; }) === true;
},
function () { // aka _.partial(onload, page)
// Their page got to load so now blast the newest vanilla jquery in there
page.injectJs('vendor/jquery-1.8.2.js');
page.injectJs('vendor/underscore-1.4.2.js');
onload(page);
}
);
}
});
};
function politelyWait(testFx, onReady, timeOutMillis) {
var maxtimeOutMillis = timeOutMillis ? timeOutMillis : 3000, //< Default Max Timout is 3s
start = new Date().getTime(),
condition = false,
interval = setInterval(function() {
if ( (new Date().getTime() - start < maxtimeOutMillis) && !condition ) {
// If not time-out yet and condition not yet fulfilled
condition = testFx(); //< defensive code
} else {
if(!condition) {
// If condition still not fulfilled (timeout but condition is 'false')
// then just go ahead, we gave it some time
onReady(); //< Do what it's supposed to do once the condition is fulfilled
} else {
// Condition fulfilled (timeout and/or condition is 'true')
onReady(); //< Do what it's supposed to do once the condition is fulfilled
clearInterval(interval); //< Stop this interval
}
}
}, 250); //< repeat check every 250ms
}
}());
|
'use strict';
var gaModule = require('./gaModule'),
gaConfig = require('./gaConfig'),
gaSettingsConstant = require('./gaSettingsConstant'),
gaProvider = require('./gaProvider');
gaModule
.config(gaConfig)
.constant('$gaSettings', gaSettingsConstant)
.provider('$ga', gaProvider);
module.exports = gaModule;
|
/**
* Easy reference for key codes
*/
var KEYS = {
LEFT: 37,
UP: 38,
RIGHT: 39,
DOWN: 40,
W: 87,
A: 65,
S: 83,
D: 68,
R: 82
};
|
(function() {
'use strict';
/**
* [BetService Serves the application with resources data and calculate result]
*
*/
function BetService($http, betHelper) {
var _self = this;
/*
* Public function
* Gets resource file data.txt to be processed
* Returns promise
*/
_self.getResourceFile = function() {
return $http.get('/resources/data.txt').then(function(response) {
return response.data;
});
};
/*
* Public function
* Returns the result for the bets
*/
_self.calculateResult = function(formattedBets) {
return betHelper.buildResultOutput(formattedBets);
};
}
BetService.$inject = ['$http', 'betHelper'];
angular.module('bettingHost')
.service('betService', BetService);
})();
|
export default function($scope, Seasons, $state){
"ngInject";
$scope.Seasons = Seasons;
$scope.selectSeason = function(season){
Seasons.setSelectedSeason(season)
$state.reload();
}
}
|
/*
* The MIT License (MIT)
* Copyright (c) 2020 Karl STEIN
*/
import { ERROR_FIELD_FORMAT } from '../errors';
import FieldError from './FieldError';
class FieldFormatError extends FieldError {
constructor(field, format, path) {
super(field, path, ERROR_FIELD_FORMAT);
this.format = format;
this.message = `"${field}" does not matches format (${format}).`;
}
}
export default FieldFormatError;
|
/*global Raphael:true */
var impact = function (data) {
'use strict';
var COL_WIDTH = 100,
COL_SEP = 50,
UNIT_HEIGHT = 10,
PATH_SEP = 3,
colLblAttr = {font: '9px "Arial"', stroke: 'none', fill: '#aaa'},
pathLblAttr = {font: '9px "Arial"', stroke: 'none', fill: '#fff'},
handleAttr = {fill: 'r#fff-#ddd', stroke: '#ccc'},
paper = new Raphael('chart', 1000, 500),
legendColour = document.getElementById('legend-colour'),
legendText = document.getElementById('legend-text'),
paths = {},
labels = {},
handles = {},
currentDragging = null,
mouseOver = null;
function Bar(column, id, value) {
this.column = column;
this.id = String(id);
this.value = value;
}
Bar.prototype.getCoords = function() {
var column = this.column,
value = this.value,
numPrevious = data.columns[column].bars.indexOf(this),
previousValues = data.columns[column].bars.slice(0, numPrevious)
.reduce(function(acc, x) {
return acc + x.value;
}, 0);
var topLeft = [column * (COL_WIDTH + COL_SEP),
previousValues * UNIT_HEIGHT + numPrevious * PATH_SEP + 20],
topRight = [topLeft[0] + COL_WIDTH,
topLeft[1]],
bottomLeft = [topLeft[0],
topLeft[1] + value * UNIT_HEIGHT],
bottomRight = [topRight[0],
bottomLeft[1]],
center = [topLeft[0] + (COL_WIDTH / 2),
topLeft[1] + (value /2) * UNIT_HEIGHT],
bottom = [center[0],
bottomLeft[1]];
return [topLeft, topRight, bottomLeft, bottomRight, center, bottom];
};
Bar.prototype.toJSON = function() {
return {
id: this.id,
value: this.value
};
};
function applyMouseEvents(lbl) {
var mouseover = function (){
mouseOver = lbl;
},
mouseout = function () {
if (currentDragging === null){
mouseOver = null;
setTimeout(function(){
if(mouseOver !== lbl){
handles[lbl].hide();
}
},20);
}
};
paths[lbl].mouseover(function () {
if (currentDragging === null){
mouseOver = lbl;
paths[lbl].toFront();
labels[lbl].toFront();
handles[lbl].show().toFront();
legendText.innerHTML = data.labels[lbl];
legendColour.style.backgroundColor = paths[lbl].attr('fill');
}
}).mouseout(mouseout);
labels[lbl].mouseover(mouseover).mouseout(mouseout);
handles[lbl].mouseover(mouseover).mouseout(mouseout);
}
function findSeries(id){
var series = [],
filterFunc = function(bar) {return bar.id === id;};
for (var nCols = data.columns.length, col = 0; col < nCols; col++) {
var bars = data.columns[col].bars.filter(filterFunc);
if (bars.length > 1){
throw 'Duplicate data series in column ' + col;
}
if(bars.length > 0) {
series.push(bars[0]);
}
}
return series;
}
function handleDragMove(dx, dy){
/*jshint validthis:true */
if(Math.abs(dy - Math.round(dy / UNIT_HEIGHT) * UNIT_HEIGHT) < 5){
this.valueDiff = Math.max(this.data('origValue') * -1, Math.round(dy / UNIT_HEIGHT));
this.attr({cy: this.oy + this.valueDiff * UNIT_HEIGHT});
changeVal(this.data('col'), this.data('id'), this.data('origValue') + this.valueDiff);
this.toFront();
}
}
function handleDragStart(){
/*jshint validthis:true */
this.oy = this.attr('cy');
currentDragging = this.data('id');
handles[this.data('id')].exclude(this);
handles[this.data('id')].hide();
}
function handleDragEnd(){
/*jshint validthis:true */
this.data('origValue', this.data('origValue') + this.valueDiff);
this.valueDiff = 0;
handles[this.data('id')].push(this);
handles[this.data('id')].show().toFront();
currentDragging = null;
}
function setHandle(id, col, origValue, x, y){
if (currentDragging !== id){
handles[id].push(paper.circle(x, y, 5)
.attr(handleAttr)
.data({
id: id,
col:col,
origValue:origValue
})
.drag(handleDragMove,
handleDragStart,
handleDragEnd));
}
}
function drawSeries(id) {
var series = findSeries(id);
if(series.length < 1){
return;
}
var path = [],
prevPos = [],
nBlocks = series.length,
block;
if (labels.hasOwnProperty(id)){
labels[id].remove();
}
labels[id] = paper.set();
if (currentDragging !== id){
if (handles.hasOwnProperty(id)){
handles[id].remove();
}
handles[id] = paper.set();
}
for (var j = 0; j < nBlocks; j++) {
block = series[j].getCoords();
if(j===0){
path.push('M' + block[0].join());
}else{
path.push('C' +
[prevPos[0] + (COL_SEP / 2), prevPos[1]].join() + ',' +
[block[0][0] - (COL_SEP / 2), block[0][1]].join() + ',' +
block[0].join());
}
path.push('L' + block[1].join());
prevPos = block[1];
if(series[j].value > 0){
labels[id].push(paper.text(block[4][0], block[4][1], series[j].value).attr(pathLblAttr));
}
setHandle(id, j, series[j].value, block[5][0], block[5][1]);
}
path.push('L' + block[3].join());
path.push('L' + block[2].join());
prevPos = block[2];
for (j = nBlocks - 2; j >= 0; j--) {
block = series[j].getCoords();
path.push('C' +
[prevPos[0] - (COL_SEP / 2), prevPos[1]].join() + ',' +
[block[3][0] + (COL_SEP / 2), block[3][1]].join() + ',' +
block[3].join());
path.push('L' + block[2].join());
prevPos = block[2];
}
path.push('Z');
path = path.join('');
var clr;
if(paths.hasOwnProperty(id)) {
clr = paths[id].attrs.fill;
paths[id].remove();
}else{
clr = Raphael.getColor();
}
paths[id] = paper.path().attr({fill: clr, stroke: clr});
paths[id].attr({path: path});
labels[id].toFront();
handles[id].hide();
if(currentDragging !== null){
paths[currentDragging].toFront();
labels[currentDragging].toFront();
}
applyMouseEvents(id);
}
function changeVal(col, id, newVal) {
var bar = data.columns[col].bars.filter(function(b){return b.id === id;});
if(bar.length !== 1){
return;
}
bar = bar[0];
bar.value = newVal;
var barIdx = data.columns[col].bars.indexOf(bar),
afterBars = data.columns[col].bars.slice(barIdx);
afterBars.map(function(bar) {drawSeries(bar.id);});
}
// Init column labels and wrap data in classes
for (var nCols = data.columns.length, col = 0; col < nCols; col++) {
var lbl = data.columns[col].label,
column = data.columns[col];
paper.text(col * (COL_WIDTH + COL_SEP) + (COL_WIDTH / 2), 10, lbl).attr(colLblAttr);
for (var nBars = column.bars.length, b = 0; b < nBars; b++) {
var bar = column.bars[b];
column.bars[b] = new Bar(col, bar.id, bar.value);
}
}
// Draw all series
for (var l in data.labels) {
if (data.labels.hasOwnProperty(l)) {
drawSeries(l);
}
}
};
|
var Popover = ReactBootstrap.Popover;
var ButtonToolbar = ReactBootstrap.ButtonToolbar;
var OverlayTrigger = ReactBootstrap.OverlayTrigger;
var Button = ReactBootstrap.Button
var popoverInstance = (
<div style={{ height: 180 }}>
<ButtonToolbar>
<OverlayTrigger trigger="click" placement="left" overlay={<Popover title="Popover left"><strong>Holy guacamole!</strong> Check this info.</Popover>}>
<Button bsStyle="default">Holy guacamole!</Button>
</OverlayTrigger>
<OverlayTrigger trigger="click" placement="top" overlay={<Popover title="Popover top"><strong>Holy guacamole!</strong> Check this info.</Popover>}>
<Button bsStyle="default">Holy guacamole!</Button>
</OverlayTrigger>
<OverlayTrigger trigger="click" placement="bottom" overlay={<Popover title="Popover bottom"><strong>Holy guacamole!</strong> Check this info.</Popover>}>
<Button bsStyle="default">Holy guacamole!</Button>
</OverlayTrigger>
<OverlayTrigger trigger="click" placement="right" overlay={<Popover title="Popover right"><strong>Holy guacamole!</strong> Check this info.</Popover>}>
<Button bsStyle="default">Holy guacamole!</Button>
</OverlayTrigger>
</ButtonToolbar>
<Popover placement="right" positionLeft={200} positionTop={50} title="Popover right">
And here's some <strong>amazing</strong> content. It's very engaging. right?
</Popover>
</div>
);
ReactDOM.render(popoverInstance, mountNode);
|
/*
* Copyright (c) 2013 - present Adobe Systems Incorporated. All rights reserved.
*
* 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.
*
*/
/*jslint node: true */
module.exports = function (grunt) {
"use strict";
var common = require("./lib/common")(grunt),
build = require("./build")(grunt);
// task: write-config
grunt.registerTask("npm-install", "Install node_modules to the dist folder so it gets bundled with release", function () {
var packageJSON = grunt.file.readJSON("package.json");
delete packageJSON.devDependencies;
delete packageJSON.scripts; // we don't want to run post-install scripts in dist folder
common.writeJSON(grunt, "dist/package.json", packageJSON);
var exec = require('child_process').exec;
var done = this.async();
exec('npm install --production', { cwd: './dist' }, function(err, stdout, stderr) {
if (err) {
grunt.log.error(stderr);
done(false);
} else {
grunt.log.writeln(stdout);
done();
}
});
});
};
|
/* ========================================================================
* MZUI: doc.js
* https://github.com/easysoft/mzui
* ========================================================================
* Copyright (c) 2016 cnezsoft.com; Licensed MIT
* ======================================================================== */
$(function() {
var $fabNav = $('#fabNav'),
$partial = $('#partial'),
$tocList = $('#tocList'),
$navs = $('#navs'),
$modalHeading = $('#tocHeading'),
$headNav = $('#headNav'),
scrollTopOffset = $headNav.height() * 2 + 10;
$headNav.display({
selector: 'a:not(.brand-name)',
activeClass: 'active',
target: '#navs',
trigger: 'click',
name: 'headNav',
animate: false,
show: function() {
$partial.empty();
$('body').removeClass('has-index-content');
},
displayed: function(options) {
$('#navs > a[data-display-auto]').trigger('click');
}
});
$navs.display({
selector: 'a',
activeClass: 'active',
target: '#partial',
trigger: 'click',
targetZIndex: 'none',
name: 'navs',
show: function() {
$fabNav.addClass('disabled');
},
shown: function() {
$fabNav.removeClass('disabled');
$tocList.empty();
},
displayed: function(options) {
var $parent = $headNav.children('.active');
var parentName = $parent.data('pageName');
var parentTitle = $parent.text();
var $element = $(options.element);
var elementName = $element.attr('href').replace('doc/part/', '').replace('examples/', '');
var gaOptions = {
hitType: 'pageview',
page: window.location.pathname + '#' + parentName + '/' + elementName,
title: parentTitle + ' > ' + $element.text()
};
ga('send', gaOptions);
$fabNav.toggleClass('hidden', !$partial.find('.section').children('.heading').children('.title').length);
}
});
$('#tocBtn').display({
triggerMethod: 'toggle',
target: '#tocModal',
backdrop: true,
targetDismiss: true,
name: 'tocModal',
show: function() {
$fabNav.addClass('open').find('.btn').removeClass('primary');
if($tocList.children().length) return;
$partial.children('.section').each(function(idx) {
var $section = $(this);
var sectionId = 'section-' + idx;
$section.attr('id', sectionId);
$tocList.append('<a class="item" data-target="#' + sectionId + '">' + $section.children('.heading').find('.title').text() + '</a>')
});
$modalHeading.text($('#navs > .active').text());
},
hide: function() {
$fabNav.removeClass('open').find('.btn').addClass('primary');
}
});
$tocList.on('click', 'a', function(e) {
var $section = $($(this).data('target'));
$(window).scrollTop($section.offset().top - scrollTopOffset);
e.preventDefault();
});
$(document).on('display.displayed', function(e, display, $trigger, options) {
if(window.prettyPrint && options.$target && options.$target.find('.prettyprint').length) {
window.prettyPrint();
}
});
$('body').on($.TapName, '.btn-begin', function() {
$('#beginLink').trigger('click');
});
if(!window.localStorage.getItem('mzuiTip') && $(window).width() > 1200) {
$.messager.warning("MZUI 专为移动端设计,在移动设备上访问效果更佳。", {placement: 'top-center', targetZIndex: 3000});
window.localStorage.setItem('mzuiTip', new Date().toLocaleString());
}
});
|
export const error = (msg) => ({ error: msg })
export const success = (data) => ({ response: data })
|
/*********************************************
* app-src/js/ycalendar.js
* YeAPF 0.8.63-106 built on 2019-07-11 09:42 (-3 DST)
* Copyright (C) 2004-2019 Esteban Daniel Dortta - dortta@yahoo.com - MIT License
* 2018-05-30 11:21:04 (-3 DST)
* First Version (C) August 2013 - esteban daniel dortta - dortta@yahoo.com
**********************************************/
//# sourceURL=app-src/js/ycalendar.js
/*
* cfg elements
* view: 0 || 1 || 2
* orientation: 0 (landscape) || 1 (portrait)
* date: Date()
* dateScope { first: YYMMDDhhmmss, last: YYMMDDhhmmss}
* dayEntryDivision: 20 (minutes)
* cellSize { width: integer(px), height: integer (px) }
* divContainerName: string
*/
var yCalendar = function (cfg) {
var that = { };
that.cfg = cfg || { };
/*
0-month
1-week
2-day
*/
that.cfg.view = +(that.cfg.view || 0);
/*
* 0 - landscape
* 1 - portrait
*/
that.cfg.orientation = +(that.cfg.orientation || 0);
/*
* highlight date (or today as default)
*/
that.cfg.date = (that.cfg.date || new Date());
/*
* common division for day visualization (minutes)
*/
that.cfg.dayEntryDivision = that.cfg.dayEntryDivision || 20;
/*
* cell size in pixels
*/
if (that.cfg.cellSize) {
that.cfg.cellSize.width = that.cfg.cellSize.width || null;
that.cfg.cellSize.height = that.cfg.cellSize.height || null;
} else
that.cfg.cellSize = { width: null , height: null};
/*
* div container where to place the calendar
*/
that.cfg.divContainerName = that.cfg.divContainerName || '';
/*
* callback function to be called on different moments
*/
that.cfg.callback = that.cfg.callback || null;
that.context = { };
that.context.dateScope = { first: '', last: '' };
that.context.nCols = 0;
that.context.nRows = 0;
/*
* configuration functions
*/
/*
* set the container (div) to place the calendar
*/
that.setDivContainerName = function(aDivName) {
that.cfg.divContainerName = aDivName;
return that;
}
/*
* set cell size (width x height) in pixels
*/
that.setCellSize = function(aCellWidth, aCellHeight) {
that.cfg.cellSize.width = that.cfg.cellSize.width || aCellWidth;
that.cfg.cellSize.height = that.cfg.cellSize.height || aCellHeight;
return that;
}
that.setView = function(aView) {
that.cfg.view = +(aView) % 3;
return that;
}
that.setCallback = function(aCallback) {
that.cfg.callback = aCallback;
return that;
}
that.setDate = function(aDate) {
that.cfg.date = aDate || that.cfg.date;
return that;
}
that.getDate = function() {
return that.cfg.date;
}
/*
* set calendar orientation (0-landscape 1-portrait)
*/
that.setOrientation = function(aOrientation) {
that.cfg.orientation = (+(aOrientation) % 2);
return that;
}
/*
style that will be used
calBand,
calDayLCell, calWeekLCell, calMonthLCell
calDayPCell, calWeekPCell, calMonthPCell
calEmptyDayCel, calEmptyWeekCell, calEmptyMonthCell
*/
that.draw = function(aCaller) {
var orientationTag = ['L', 'P'];
var theDiv = y$(that.cfg.divContainerName);
if (theDiv) {
try {
/* status = 0. DOM BEING CREATED */
that.cfg.status = 0;
if (that.cfg.callback != null)
that.cfg.callback(that, 'DOMLocked', theDiv);
var aTag = null,
aCellID = null,
aTagClass = null,
aCellContent = null,
aAuxTag = null,
aDiv = null,
aSpan = null,
aText = null;
/* month ans week views increments in day chunks */
if (that.cfg.view<2)
var inc = 24 * 60 * 60 * 1000;
else
var inc = that.cfg.dayEntryDivision * 60 * 1000;
var colNumber = 0, rowNumber=0;
/*
* create a class base name to be used with all the elements
* that is: calDay followed by L(landscape) or P (portrait)
*/
var classBaseName = 'calDay'+orientationTag[that.cfg.view % 2];
/* remove all children nodes */
while (theDiv.hasChildNodes()) {
theDiv.removeChild(theDiv.lastChild);
}
/* create the calendar table */
that.context.oCalTable = document.createElement('table');
that.context.oCalTable.cellPadding=0;
that.context.oCalTable.cellSpacing=0;
var oTR = that.context.oCalTable.insertRow(-1);
var oTD = oTR.insertCell();
oTD.className = 'calBand';
var openRow = true;
var emptyCellCount = 0;
var extraStyle = { };
if (that.cfg.cellSize.height != null)
extraStyle.height = parseInt(that.cfg.cellSize.height) + 'px';
if (that.cfg.cellSize.width != null)
extraStyle.width = parseInt(that.cfg.cellSize.width) + 'px';
var d1 = that.context.dateScope.first;
var d2 = that.context.dateScope.last;
d1.setHours(12);
d2.setHours(12);
var createEmptyCell = function() {
/* create an unique ID for the empty day */
aCellID = that.cfg.divContainerName+"_empty_"+emptyCellCount;
/* create an empty day */
var aDiv = document.createElement('div');
mergeObject(extraStyle, aDiv.style);
aDiv.id = aCellID;
aDiv.className = classBaseName+"Cell "+classBaseName+"EmptyCell";
oTD.appendChild(aDiv);
if (that.cfg.orientation==0)
colNumber++;
emptyCellCount++;
/* call callback function */
if (that.cfg.callback!= null)
that.cfg.callback(that, 'getEmptyDayContent', aDiv);
}
var createFilledCell = function (aTagType) {
if (aTagType==0) {
aCellID = that.cfg.divContainerName+'_day_'+d.toUDate().substring(0,8);
aTag = d.getDate();
} else {
aTag = d.getHours()+':'+d.getMinutes();
aCellID = that.cfg.divContainerName+'_day_'+d.toUDate().substring(0, 12);
}
}
var d = new Date(d1);
var interactions = (d2 - d) / inc + 1;
if (that.cfg.view === 0) {
if (that.cfg.orientation==0) {
for(n = 0; n < d1.getDay(); n++) {
createEmptyCell();
}
} else {
d.setDate( d.getDate() - d1.getDay() );
var dOffset = [];
var dAux = new Date(d);
for(n = 0; n < that.context.nRows; n++) {
dOffset[n] = new Date(dAux);
dAux.setDate(dAux.getDate()+1);
}
}
}
while (interactions>0) {
if (!openRow) {
oTR = that.context.oCalTable.insertRow(-1);
oTD = oTR.insertCell();
oTD.className = 'calBand';
openRow = true;
}
aTag = '';
if (that.cfg.orientation==1) {
if ((d<d1) || (d>d2))
createEmptyCell();
else {
if ((that.cfg.view === 0) || (that.cfg.view === 1)) {
createFilledCell(0);
} else if (that.cfg.view === 2){
createFilledCell(1);
} else
_dumpy(8,1,"Not implemented");
}
} else if (that.cfg.orientation==0) {
if ((that.cfg.view === 0) || (that.cfg.view === 1)) {
createFilledCell(0);
} else if (that.cfg.view === 2) {
createFilledCell(1);
} else
_dumpy(8,1,"Not implemented");
}
if (aTag>'') {
aTagClass = classBaseName+'Cell';
if (d.getDay() === 0)
aTagClass += ' '+classBaseName+'FreeCell';
if (d.getDate()==that.cfg.date.getDate())
aTagClass += ' '+classBaseName+'Highlight';
/* create a day container */
aDiv = document.createElement('div');
mergeObject(extraStyle, aDiv.style);
aDiv.id = aCellID;
aDiv.className = aTagClass;
mergeObject(extraStyle, aDiv.style);
aDiv.date = d;
/* create a day tag */
aSpan = document.createElement('span');
aSpan.id = aCellID+"_tag";
aSpan.className = 'calTag';
if (that.cfg.callback!= null) {
aAuxTag = that.cfg.callback(that, 'getTagContent', aSpan) || '';
if (aAuxTag>'')
aTag = aAuxTag;
}
aSpan.innerHTML = aTag;
aDiv.appendChild(aSpan);
if (that.cfg.callback!= null) {
aText = that.cfg.callback(that, 'getCellContent', aDiv) || '';
if (aText>'') {
aDiv.innerHTML += aText;
}
}
oTD.appendChild(aDiv);
}
if (that.cfg.orientation==1) {
d.setTime(d.getTime()+inc * that.context.nRows);
} else
d.setTime(d.getTime()+inc);
colNumber++;
if(colNumber>=that.context.nCols) {
colNumber = 0;
rowNumber++;
openRow = false;
if (that.cfg.orientation==1)
d=dOffset[rowNumber];
}
interactions--;
}
if (openRow) {
while (colNumber<that.context.nCols) {
createEmptyCell();
}
colNumber = 0;
openRow = false;
}
theDiv.appendChild(that.context.oCalTable);
} catch(err) {
_dumpy(8,1,'ERROR: '+err.message);
}
// status = 1. DOM READY
that.cfg.status = 1;
if (that.cfg.callback!= null)
that.cfg.callback(that, 'DOMReleased', theDiv);
}
return that;
}
that.build = function(aDate, aView, aOrientation) {
that.cfg.orientation = aOrientation || that.cfg.orientation;
that.cfg.view = aView || that.cfg.view;
that.cfg.date = aDate || that.cfg.date;
var theDiv = y$(that.cfg.divContainerName);
if (theDiv) {
var d1 = new Date(that.cfg.date),
d2 = null,
secondsPerDay = 24 * 60 * 60 * 1000,
nCols = 0,
nRows = 0;
switch (that.cfg.view) {
case 0:
// month view.
nCols = 7;
nRows = 5;
// Recalculate dateScope
d1.setDate(1);
var d2 = new Date(d1);
d2.setDate(d1.daysInMonth());
break;
case 1:
// week view.
nCols = 1;
nRows = 7;
// Recalculate dateScope
var d1 = new Date(that.cfg.date);
while (d1.getDay()>0)
d1.setTime(d1.getTime()-secondsPerDay)
var d2 = new Date(d1);
d2.setTime(d1.getTime()+secondsPerDay * 6);
break;
case 2:
// day view
nCols = 1;
nRows = Math.round(24 * 60 / that.cfg.dayEntryDivision);
// Recalculate dateScope
d1.setHours(6); // <--- Need more config there
d1.setMinutes(0); // <--- Need more config there
var d2 = new Date(d1);
d2.setHours(21); // <--- Need more config there
d2.setMinutes(60-that.cfg.dayEntryDivision);
break;
default:
_dumpy(8,1,"Not implemented");
}
that.context.dateScope.first = d1;
that.context.dateScope.last = d2;
if (that.cfg.orientation === 1) {
that.context.nCols = nRows;
that.context.nRows = nCols;
} else {
that.context.nCols = nCols;
that.context.nRows = nRows;
}
that.draw(that);
_dumpy(8,1,"Build calendar on "+that.cfg.date.toUDate()+" View: "+that.cfg.view+" Orientation: "+that.cfg.orientation+" cols: "+nCols+" rows: "+nRows);
} else
_dumpy(8,1,"ERROR: "+that.cfg.divContainerName+" not found on that page");
return that;
}
that.each = function(aFunction) {
if (typeof aFunction == 'function') {
if (that.context.oCalTable) {
var idSeed = that.cfg.divContainerName+"_day_";
var processElement = function (aTagSpec) {
var elements = that.context.oCalTable.getElementsByTagName(aTagSpec);
for (var i=0; i<elements.length; i++)
if (elements[i].id.substr(0,idSeed.length)==idSeed)
aFunction(elements[i]);
}
processElement('div');
processElement('span');
}
}
return that;
};
return that;
};
|
define([
'./script/dbpediaQuery',
'./script/dbpediaQueryArea',
'./script/dbpediaQueryDump',
'./script/dbpediaSvc',
'./script/dbpImgHistory',
'./script/dbpImgSearch',
'./script/dbpKey',
'./script/dbpSpecies',
'./script/dbpFungi'
],
function(){})
|
import React from 'react';
import { Link } from 'react-router';
import Breadcrumbs from 'components/Breadcrumbs';
class FilesPage extends React.Component {
constructor(props) {
super(props);
}
renderBreadcrumbs(breadcrumbs) {
//console.log(breadcrumbs);
if (Array.isArray(breadcrumbs)) {
return <div style={{'paddingTop': '20px', 'paddingBottom': '20px'}}>
{breadcrumbs.map((el, i) => (
<span key={i}>{el}</span>
))}
</div>
} else {
return <div></div>;
}
}
render() {
const breadcrumbs = [
<Link to='/files'>Файловый архив</Link>,
'123'
];
return (
<div>
<Breadcrumbs items={breadcrumbs} />
<span>тут будет страница файлов</span>
</div>
);
}
}
//LoginPage.propTypes = { initialCount: React.PropTypes.number };
//LoginPage.defaultProps = { initialCount: 0 };
export default FilesPage;
|
const mongoose = require('mongoose');
const childSchema = new mongoose.Schema({ subName: String });
module.exports = childSchema;
|
// @flow
import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { Redirect } from 'react-router';
import { connect } from 'react-redux';
import { Button, Header, Icon, Menu, Modal, Segment, Table } from 'semantic-ui-react';
import AccountsCustomJson from '../components/Accounts/CustomJSON.js';
import * as AccountActions from '../actions/account';
import * as KeyActions from '../actions/keys';
import * as ProcessingActions from '../actions/processing';
import MenuBar from './MenuBar';
import ContentBar from '../components/ContentBar';
class AccountsPage extends Component {
state = {
activeItem: 'custom_json'
};
handleItemClick = (e, { name }) => this.setState({ activeItem: name })
render() {
if (!this.props.keys.isUser) {
return <Redirect to="/" />;
}
const { activeItem } = this.state;
let activeTab = <AccountsCustomJson {...this.props} />;
switch (activeItem) {
default: {
activeTab = <AccountsCustomJson {...this.props} />;
break;
}
}
return (
<ContentBar>
<Segment basic padded attached secondary>
<Header>
<Icon name="lab" />
<Header.Content>
Advanced Operations
<Header.Subheader>
This section can be used to perform more advanced operations using the loaded accounts.
</Header.Subheader>
</Header.Content>
</Header>
</Segment>
<Menu tabular attached>
<Menu.Item
name="custom_json"
icon="lock"
content="Custom JSON"
active={activeItem === 'custom_json'}
onClick={this.handleItemClick}
/>
</Menu>
{activeTab}
<MenuBar />
</ContentBar>
);
}
}
function mapStateToProps(state) {
return {
account: state.account,
keys: state.keys,
processing: state.processing,
hive: state.hive
};
}
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators({
...AccountActions,
...KeyActions,
...ProcessingActions,
}, dispatch)
};
}
export default connect(mapStateToProps, mapDispatchToProps)(AccountsPage);
|
const gulp = require('gulp');
const browserify = require('browserify');
const babelify = require('babelify');
const source = require('vinyl-source-stream');
const watchify = require('watchify');
const webserver = require('gulp-webserver');
const uglify = require('gulp-uglify');
const rename = require('gulp-rename');
const msx = require('gulp-msx');
const br = watchify(
browserify({
entries: './src/Solufa.ts'
})
.plugin('tsify', {target: 'es6'})
.transform("babelify")
);
br.on( "update", bundle );
function bundle() {
return br.bundle()
.pipe(source('Solufa.js'))
.pipe(gulp.dest('./static/js'));
}
gulp.task( "msx", function() {
gulp.src('./components/*.js')
.pipe(msx({harmony: true}))
.pipe(gulp.dest('./static/components'));
});
gulp.task( "default", function() {
gulp.src('./static')
.pipe(webserver({
host: '0.0.0.0',//スマホからIPアドレスでアクセスできる
livereload: true,
open: "http://0.0.0.0:8000/samples/1000box.html"
}));
bundle();
gulp.watch('./components/*.js', ['msx']);
});
gulp.task('compress', function() {
return gulp.src('static/js/Solufa.js')
.pipe(uglify({
preserveComments: 'some' // ! から始まるコメントを残すオプションを追加
}))
.pipe(rename('Solufa.min.js'))
.pipe(gulp.dest('static/js'));
});
|
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
define([], factory);
} else if (typeof exports === 'object') {
module.exports = factory();
} else {
var lastName = root,
namespace = 'allColors.ideaColorThemes.netbeans8'.split('.');
for (var i = 0; i < namespace.length; i++) {
if (lastName[namespace[i]] === undefined) {
lastName = lastName[namespace[i]] = {};
}
}
root.allColors.ideaColorThemes.netbeans8 = factory();
}
}(this, function() {
return [
'#a1f2ac',
'#eeeeee',
'#ffffff',
'#cccccc',
'#a0a9f9',
'#ffc8c8',
'#b7b7b7',
'#ce7b00',
'#d25252',
'#868686',
'#808080',
'#ffded8',
'#ffc8bd',
'#d6d6d6',
'#cbcbcb',
'#c8f2c8',
'#baeeba',
'#bccff9',
'#f5f7f0',
'#ff0000',
'#e9e9e9',
'#f4e803',
'#eceba3',
'#ffffcc',
'#660e7a',
'#ccffcc',
'#ffcccc',
'#99ccff',
'#f49810',
'#d8d8d8',
'#ffdcdc',
'#f6ebbc',
'#ffff00'
];
}));
|
var searchData=
[
['paperfigures',['PaperFigures',['../class_paper_figures.html',1,'']]],
['parameter',['Parameter',['../class_parameter.html',1,'']]],
['pathway',['Pathway',['../class_pathway.html',1,'']]],
['pdfutil',['PdfUtil',['../class_pdf_util.html',1,'']]],
['physicalobject',['PhysicalObject',['../class_physical_object.html',1,'']]],
['polymer',['Polymer',['../class_polymer.html',1,'']]],
['population',['Population',['../class_population.html',1,'']]],
['posterfigures',['PosterFigures',['../class_poster_figures.html',1,'']]],
['process',['Process',['../class_process.html',1,'']]],
['processmetaboliteusage',['ProcessMetaboliteUsage',['../class_process_metabolite_usage.html',1,'']]],
['protein',['Protein',['../class_protein.html',1,'']]],
['proteincomplex',['ProteinComplex',['../class_protein_complex.html',1,'']]],
['proteinmonomer',['ProteinMonomer',['../class_protein_monomer.html',1,'']]]
];
|
(function() {
window.Glow = {
flash: function(type, message) {
return $(document).trigger('glow:flash', {
type: type,
message: message
});
}
};
$(document).ajaxComplete(function(evt, xhr, options) {
var message, type;
type = xhr.getResponseHeader('X-Message-Type');
message = xhr.getResponseHeader('X-Message');
if (type && message) {
return Glow.flash(type, $('<div/>').html(message).text());
}
});
window.Flash = {
fire: Glow.flash,
// convenience methods
success: function(message) {
return Glow.flash('success', message);
},
notice: function(message) {
return Glow.flash('notice', message);
},
error: function(message) {
return Glow.flash('error', message);
}
};
}).call(this);
|
export default {
uiv: {
datePicker: {
clear: 'Törlés',
today: 'Ma',
month: 'Hónap',
month1: 'január',
month2: 'február',
month3: 'március',
month4: 'április',
month5: 'május',
month6: 'június',
month7: 'július',
month8: 'augusztus',
month9: 'szeptember',
month10: 'október',
month11: 'november',
month12: 'december',
year: 'Év',
week1: 'H.',
week2: 'K.',
week3: 'Sze.',
week4: 'Cs.',
week5: 'P.',
week6: 'Szo.',
week7: 'V.'
},
timePicker: {
am: 'AM',
pm: 'PM'
},
modal: {
cancel: 'Mégse',
ok: 'OK'
},
multiSelect: {
placeholder: 'Válassz...',
filterPlaceholder: 'Keresés...'
}
}
}
|
// @flow
export default ( siteInformation: Object ) => '/graphql'
|
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var app = express();
//Añadir el módulo de MongoDB
var mongodb = require('mongodb');
var database;
//Crea la conexión a la base de datos ColScript mediante el puerto por defecto.
var connection = mongodb.MongoClient.connect('mongodb://127.0.0.1:27017/colscript', function(err, db){
database = db; //Almacena la información de la base de datos.
});
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
//Con este código podemos acceder a la base de datos desde cualquier objeto req de las rutas.
app.use(function(req,res,next){
req.db = database;
next();
});
app.use('/', routes);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
app.listen(3000);
console.log("Listening on port 3000.");
module.exports = app;
|
var ConfigManager = require('./components/config_manager');
var RenderEngine = require('./components/render_engine');
var OrientationManager = require('./components/orientation_manager');
var Network = require('./components/network');
var LocalStream = require('./components/local_stream');
var DepthRender = require('./components/depth_render');
var ForwardStream = require('./components/forward_stream');
var RemoteStream = require('./components/remote_stream');
var Utils = require('./components/utils');
var Logger = require('./components/logger');
var REDUCE = 4;
var SKIP = 60;
var cm = new ConfigManager();
var re = new RenderEngine(cm);
var om = new OrientationManager();
var n = new Network(cm);
var ls = new LocalStream('ws://0.0.0.0:9090');
new DepthRender(ls, REDUCE, re, om.obtain(ls), 0);
new ForwardStream(ls, n, SKIP);
var l = new Logger(n, re, cm);
n.on('found', function(node){
node.render = new DepthRender(new RemoteStream(node), REDUCE, re, om.obtain(node), RenderEngine.SENSOR_DISTANCE);
});
n.on('lost', function(node){
node.render.stop();
om.free(node);
});
cm.initialize();
Utils.hideInactiveCursor();
n.connect();
re.start();
|
'use strict';
/* The following tests are copied from WPT. Modifications to them should be
upstreamed first. Refs:
https://github.com/w3c/web-platform-tests/blob/ed4bb727ed/url/urltestdata.json
License: http://www.w3.org/Consortium/Legal/2008/04-testsuite-copyright.html
*/
module.exports =
[
"# Based on http://trac.webkit.org/browser/trunk/LayoutTests/fast/url/script-tests/segments.js",
{
"input": "http://example\t.\norg",
"base": "http://example.org/foo/bar",
"href": "http://example.org/",
"origin": "http://example.org",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.org",
"hostname": "example.org",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "http://user:pass@foo:21/bar;par?b#c",
"base": "http://example.org/foo/bar",
"href": "http://user:pass@foo:21/bar;par?b#c",
"origin": "http://foo:21",
"protocol": "http:",
"username": "user",
"password": "pass",
"host": "foo:21",
"hostname": "foo",
"port": "21",
"pathname": "/bar;par",
"search": "?b",
"hash": "#c"
},
{
"input": "https://test:@test",
"base": "about:blank",
"href": "https://test@test/",
"origin": "https://test",
"protocol": "https:",
"username": "test",
"password": "",
"host": "test",
"hostname": "test",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "https://:@test",
"base": "about:blank",
"href": "https://test/",
"origin": "https://test",
"protocol": "https:",
"username": "",
"password": "",
"host": "test",
"hostname": "test",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "non-special://test:@test/x",
"base": "about:blank",
"href": "non-special://test@test/x",
"origin": "null",
"protocol": "non-special:",
"username": "test",
"password": "",
"host": "test",
"hostname": "test",
"port": "",
"pathname": "/x",
"search": "",
"hash": ""
},
{
"input": "non-special://:@test/x",
"base": "about:blank",
"href": "non-special://test/x",
"origin": "null",
"protocol": "non-special:",
"username": "",
"password": "",
"host": "test",
"hostname": "test",
"port": "",
"pathname": "/x",
"search": "",
"hash": ""
},
{
"input": "http:foo.com",
"base": "http://example.org/foo/bar",
"href": "http://example.org/foo/foo.com",
"origin": "http://example.org",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.org",
"hostname": "example.org",
"port": "",
"pathname": "/foo/foo.com",
"search": "",
"hash": ""
},
{
"input": "\t :foo.com \n",
"base": "http://example.org/foo/bar",
"href": "http://example.org/foo/:foo.com",
"origin": "http://example.org",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.org",
"hostname": "example.org",
"port": "",
"pathname": "/foo/:foo.com",
"search": "",
"hash": ""
},
{
"input": " foo.com ",
"base": "http://example.org/foo/bar",
"href": "http://example.org/foo/foo.com",
"origin": "http://example.org",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.org",
"hostname": "example.org",
"port": "",
"pathname": "/foo/foo.com",
"search": "",
"hash": ""
},
{
"input": "a:\t foo.com",
"base": "http://example.org/foo/bar",
"href": "a: foo.com",
"origin": "null",
"protocol": "a:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": " foo.com",
"search": "",
"hash": ""
},
{
"input": "http://f:21/ b ? d # e ",
"base": "http://example.org/foo/bar",
"href": "http://f:21/%20b%20?%20d%20#%20e",
"origin": "http://f:21",
"protocol": "http:",
"username": "",
"password": "",
"host": "f:21",
"hostname": "f",
"port": "21",
"pathname": "/%20b%20",
"search": "?%20d%20",
"hash": "#%20e"
},
{
"input": "lolscheme:x x#x x",
"base": "about:blank",
"href": "lolscheme:x x#x%20x",
"protocol": "lolscheme:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "x x",
"search": "",
"hash": "#x%20x"
},
{
"input": "http://f:/c",
"base": "http://example.org/foo/bar",
"href": "http://f/c",
"origin": "http://f",
"protocol": "http:",
"username": "",
"password": "",
"host": "f",
"hostname": "f",
"port": "",
"pathname": "/c",
"search": "",
"hash": ""
},
{
"input": "http://f:0/c",
"base": "http://example.org/foo/bar",
"href": "http://f:0/c",
"origin": "http://f:0",
"protocol": "http:",
"username": "",
"password": "",
"host": "f:0",
"hostname": "f",
"port": "0",
"pathname": "/c",
"search": "",
"hash": ""
},
{
"input": "http://f:00000000000000/c",
"base": "http://example.org/foo/bar",
"href": "http://f:0/c",
"origin": "http://f:0",
"protocol": "http:",
"username": "",
"password": "",
"host": "f:0",
"hostname": "f",
"port": "0",
"pathname": "/c",
"search": "",
"hash": ""
},
{
"input": "http://f:00000000000000000000080/c",
"base": "http://example.org/foo/bar",
"href": "http://f/c",
"origin": "http://f",
"protocol": "http:",
"username": "",
"password": "",
"host": "f",
"hostname": "f",
"port": "",
"pathname": "/c",
"search": "",
"hash": ""
},
{
"input": "http://f:b/c",
"base": "http://example.org/foo/bar",
"failure": true
},
{
"input": "http://f: /c",
"base": "http://example.org/foo/bar",
"failure": true
},
{
"input": "http://f:\n/c",
"base": "http://example.org/foo/bar",
"href": "http://f/c",
"origin": "http://f",
"protocol": "http:",
"username": "",
"password": "",
"host": "f",
"hostname": "f",
"port": "",
"pathname": "/c",
"search": "",
"hash": ""
},
{
"input": "http://f:fifty-two/c",
"base": "http://example.org/foo/bar",
"failure": true
},
{
"input": "http://f:999999/c",
"base": "http://example.org/foo/bar",
"failure": true
},
{
"input": "non-special://f:999999/c",
"base": "http://example.org/foo/bar",
"failure": true
},
{
"input": "http://f: 21 / b ? d # e ",
"base": "http://example.org/foo/bar",
"failure": true
},
{
"input": "",
"base": "http://example.org/foo/bar",
"href": "http://example.org/foo/bar",
"origin": "http://example.org",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.org",
"hostname": "example.org",
"port": "",
"pathname": "/foo/bar",
"search": "",
"hash": ""
},
{
"input": " \t",
"base": "http://example.org/foo/bar",
"href": "http://example.org/foo/bar",
"origin": "http://example.org",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.org",
"hostname": "example.org",
"port": "",
"pathname": "/foo/bar",
"search": "",
"hash": ""
},
{
"input": ":foo.com/",
"base": "http://example.org/foo/bar",
"href": "http://example.org/foo/:foo.com/",
"origin": "http://example.org",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.org",
"hostname": "example.org",
"port": "",
"pathname": "/foo/:foo.com/",
"search": "",
"hash": ""
},
{
"input": ":foo.com\\",
"base": "http://example.org/foo/bar",
"href": "http://example.org/foo/:foo.com/",
"origin": "http://example.org",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.org",
"hostname": "example.org",
"port": "",
"pathname": "/foo/:foo.com/",
"search": "",
"hash": ""
},
{
"input": ":",
"base": "http://example.org/foo/bar",
"href": "http://example.org/foo/:",
"origin": "http://example.org",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.org",
"hostname": "example.org",
"port": "",
"pathname": "/foo/:",
"search": "",
"hash": ""
},
{
"input": ":a",
"base": "http://example.org/foo/bar",
"href": "http://example.org/foo/:a",
"origin": "http://example.org",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.org",
"hostname": "example.org",
"port": "",
"pathname": "/foo/:a",
"search": "",
"hash": ""
},
{
"input": ":/",
"base": "http://example.org/foo/bar",
"href": "http://example.org/foo/:/",
"origin": "http://example.org",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.org",
"hostname": "example.org",
"port": "",
"pathname": "/foo/:/",
"search": "",
"hash": ""
},
{
"input": ":\\",
"base": "http://example.org/foo/bar",
"href": "http://example.org/foo/:/",
"origin": "http://example.org",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.org",
"hostname": "example.org",
"port": "",
"pathname": "/foo/:/",
"search": "",
"hash": ""
},
{
"input": ":#",
"base": "http://example.org/foo/bar",
"href": "http://example.org/foo/:#",
"origin": "http://example.org",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.org",
"hostname": "example.org",
"port": "",
"pathname": "/foo/:",
"search": "",
"hash": ""
},
{
"input": "#",
"base": "http://example.org/foo/bar",
"href": "http://example.org/foo/bar#",
"origin": "http://example.org",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.org",
"hostname": "example.org",
"port": "",
"pathname": "/foo/bar",
"search": "",
"hash": ""
},
{
"input": "#/",
"base": "http://example.org/foo/bar",
"href": "http://example.org/foo/bar#/",
"origin": "http://example.org",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.org",
"hostname": "example.org",
"port": "",
"pathname": "/foo/bar",
"search": "",
"hash": "#/"
},
{
"input": "#\\",
"base": "http://example.org/foo/bar",
"href": "http://example.org/foo/bar#\\",
"origin": "http://example.org",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.org",
"hostname": "example.org",
"port": "",
"pathname": "/foo/bar",
"search": "",
"hash": "#\\"
},
{
"input": "#;?",
"base": "http://example.org/foo/bar",
"href": "http://example.org/foo/bar#;?",
"origin": "http://example.org",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.org",
"hostname": "example.org",
"port": "",
"pathname": "/foo/bar",
"search": "",
"hash": "#;?"
},
{
"input": "?",
"base": "http://example.org/foo/bar",
"href": "http://example.org/foo/bar?",
"origin": "http://example.org",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.org",
"hostname": "example.org",
"port": "",
"pathname": "/foo/bar",
"search": "",
"hash": ""
},
{
"input": "/",
"base": "http://example.org/foo/bar",
"href": "http://example.org/",
"origin": "http://example.org",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.org",
"hostname": "example.org",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": ":23",
"base": "http://example.org/foo/bar",
"href": "http://example.org/foo/:23",
"origin": "http://example.org",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.org",
"hostname": "example.org",
"port": "",
"pathname": "/foo/:23",
"search": "",
"hash": ""
},
{
"input": "/:23",
"base": "http://example.org/foo/bar",
"href": "http://example.org/:23",
"origin": "http://example.org",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.org",
"hostname": "example.org",
"port": "",
"pathname": "/:23",
"search": "",
"hash": ""
},
{
"input": "::",
"base": "http://example.org/foo/bar",
"href": "http://example.org/foo/::",
"origin": "http://example.org",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.org",
"hostname": "example.org",
"port": "",
"pathname": "/foo/::",
"search": "",
"hash": ""
},
{
"input": "::23",
"base": "http://example.org/foo/bar",
"href": "http://example.org/foo/::23",
"origin": "http://example.org",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.org",
"hostname": "example.org",
"port": "",
"pathname": "/foo/::23",
"search": "",
"hash": ""
},
{
"input": "foo://",
"base": "http://example.org/foo/bar",
"href": "foo://",
"origin": "null",
"protocol": "foo:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "",
"search": "",
"hash": ""
},
{
"input": "http://a:b@c:29/d",
"base": "http://example.org/foo/bar",
"href": "http://a:b@c:29/d",
"origin": "http://c:29",
"protocol": "http:",
"username": "a",
"password": "b",
"host": "c:29",
"hostname": "c",
"port": "29",
"pathname": "/d",
"search": "",
"hash": ""
},
{
"input": "http::@c:29",
"base": "http://example.org/foo/bar",
"href": "http://example.org/foo/:@c:29",
"origin": "http://example.org",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.org",
"hostname": "example.org",
"port": "",
"pathname": "/foo/:@c:29",
"search": "",
"hash": ""
},
{
"input": "http://&a:foo(b]c@d:2/",
"base": "http://example.org/foo/bar",
"href": "http://&a:foo(b%5Dc@d:2/",
"origin": "http://d:2",
"protocol": "http:",
"username": "&a",
"password": "foo(b%5Dc",
"host": "d:2",
"hostname": "d",
"port": "2",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "http://::@c@d:2",
"base": "http://example.org/foo/bar",
"href": "http://:%3A%40c@d:2/",
"origin": "http://d:2",
"protocol": "http:",
"username": "",
"password": "%3A%40c",
"host": "d:2",
"hostname": "d",
"port": "2",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "http://foo.com:b@d/",
"base": "http://example.org/foo/bar",
"href": "http://foo.com:b@d/",
"origin": "http://d",
"protocol": "http:",
"username": "foo.com",
"password": "b",
"host": "d",
"hostname": "d",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "http://foo.com/\\@",
"base": "http://example.org/foo/bar",
"href": "http://foo.com//@",
"origin": "http://foo.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "foo.com",
"hostname": "foo.com",
"port": "",
"pathname": "//@",
"search": "",
"hash": ""
},
{
"input": "http:\\\\foo.com\\",
"base": "http://example.org/foo/bar",
"href": "http://foo.com/",
"origin": "http://foo.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "foo.com",
"hostname": "foo.com",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "http:\\\\a\\b:c\\d@foo.com\\",
"base": "http://example.org/foo/bar",
"href": "http://a/b:c/d@foo.com/",
"origin": "http://a",
"protocol": "http:",
"username": "",
"password": "",
"host": "a",
"hostname": "a",
"port": "",
"pathname": "/b:c/d@foo.com/",
"search": "",
"hash": ""
},
{
"input": "foo:/",
"base": "http://example.org/foo/bar",
"href": "foo:/",
"origin": "null",
"protocol": "foo:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "foo:/bar.com/",
"base": "http://example.org/foo/bar",
"href": "foo:/bar.com/",
"origin": "null",
"protocol": "foo:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/bar.com/",
"search": "",
"hash": ""
},
{
"input": "foo://///////",
"base": "http://example.org/foo/bar",
"href": "foo://///////",
"origin": "null",
"protocol": "foo:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "///////",
"search": "",
"hash": ""
},
{
"input": "foo://///////bar.com/",
"base": "http://example.org/foo/bar",
"href": "foo://///////bar.com/",
"origin": "null",
"protocol": "foo:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "///////bar.com/",
"search": "",
"hash": ""
},
{
"input": "foo:////://///",
"base": "http://example.org/foo/bar",
"href": "foo:////://///",
"origin": "null",
"protocol": "foo:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "//://///",
"search": "",
"hash": ""
},
{
"input": "c:/foo",
"base": "http://example.org/foo/bar",
"href": "c:/foo",
"origin": "null",
"protocol": "c:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/foo",
"search": "",
"hash": ""
},
{
"input": "//foo/bar",
"base": "http://example.org/foo/bar",
"href": "http://foo/bar",
"origin": "http://foo",
"protocol": "http:",
"username": "",
"password": "",
"host": "foo",
"hostname": "foo",
"port": "",
"pathname": "/bar",
"search": "",
"hash": ""
},
{
"input": "http://foo/path;a??e#f#g",
"base": "http://example.org/foo/bar",
"href": "http://foo/path;a??e#f#g",
"origin": "http://foo",
"protocol": "http:",
"username": "",
"password": "",
"host": "foo",
"hostname": "foo",
"port": "",
"pathname": "/path;a",
"search": "??e",
"hash": "#f#g"
},
{
"input": "http://foo/abcd?efgh?ijkl",
"base": "http://example.org/foo/bar",
"href": "http://foo/abcd?efgh?ijkl",
"origin": "http://foo",
"protocol": "http:",
"username": "",
"password": "",
"host": "foo",
"hostname": "foo",
"port": "",
"pathname": "/abcd",
"search": "?efgh?ijkl",
"hash": ""
},
{
"input": "http://foo/abcd#foo?bar",
"base": "http://example.org/foo/bar",
"href": "http://foo/abcd#foo?bar",
"origin": "http://foo",
"protocol": "http:",
"username": "",
"password": "",
"host": "foo",
"hostname": "foo",
"port": "",
"pathname": "/abcd",
"search": "",
"hash": "#foo?bar"
},
{
"input": "[61:24:74]:98",
"base": "http://example.org/foo/bar",
"href": "http://example.org/foo/[61:24:74]:98",
"origin": "http://example.org",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.org",
"hostname": "example.org",
"port": "",
"pathname": "/foo/[61:24:74]:98",
"search": "",
"hash": ""
},
{
"input": "http:[61:27]/:foo",
"base": "http://example.org/foo/bar",
"href": "http://example.org/foo/[61:27]/:foo",
"origin": "http://example.org",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.org",
"hostname": "example.org",
"port": "",
"pathname": "/foo/[61:27]/:foo",
"search": "",
"hash": ""
},
{
"input": "http://[1::2]:3:4",
"base": "http://example.org/foo/bar",
"failure": true
},
{
"input": "http://2001::1",
"base": "http://example.org/foo/bar",
"failure": true
},
{
"input": "http://2001::1]",
"base": "http://example.org/foo/bar",
"failure": true
},
{
"input": "http://2001::1]:80",
"base": "http://example.org/foo/bar",
"failure": true
},
{
"input": "http://[2001::1]",
"base": "http://example.org/foo/bar",
"href": "http://[2001::1]/",
"origin": "http://[2001::1]",
"protocol": "http:",
"username": "",
"password": "",
"host": "[2001::1]",
"hostname": "[2001::1]",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "http://[::127.0.0.1]",
"base": "http://example.org/foo/bar",
"href": "http://[::7f00:1]/",
"origin": "http://[::7f00:1]",
"protocol": "http:",
"username": "",
"password": "",
"host": "[::7f00:1]",
"hostname": "[::7f00:1]",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "http://[0:0:0:0:0:0:13.1.68.3]",
"base": "http://example.org/foo/bar",
"href": "http://[::d01:4403]/",
"origin": "http://[::d01:4403]",
"protocol": "http:",
"username": "",
"password": "",
"host": "[::d01:4403]",
"hostname": "[::d01:4403]",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "http://[2001::1]:80",
"base": "http://example.org/foo/bar",
"href": "http://[2001::1]/",
"origin": "http://[2001::1]",
"protocol": "http:",
"username": "",
"password": "",
"host": "[2001::1]",
"hostname": "[2001::1]",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "http:/example.com/",
"base": "http://example.org/foo/bar",
"href": "http://example.org/example.com/",
"origin": "http://example.org",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.org",
"hostname": "example.org",
"port": "",
"pathname": "/example.com/",
"search": "",
"hash": ""
},
{
"input": "ftp:/example.com/",
"base": "http://example.org/foo/bar",
"href": "ftp://example.com/",
"origin": "ftp://example.com",
"protocol": "ftp:",
"username": "",
"password": "",
"host": "example.com",
"hostname": "example.com",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "https:/example.com/",
"base": "http://example.org/foo/bar",
"href": "https://example.com/",
"origin": "https://example.com",
"protocol": "https:",
"username": "",
"password": "",
"host": "example.com",
"hostname": "example.com",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "madeupscheme:/example.com/",
"base": "http://example.org/foo/bar",
"href": "madeupscheme:/example.com/",
"origin": "null",
"protocol": "madeupscheme:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/example.com/",
"search": "",
"hash": ""
},
{
"input": "file:/example.com/",
"base": "http://example.org/foo/bar",
"href": "file:///example.com/",
"protocol": "file:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/example.com/",
"search": "",
"hash": ""
},
{
"input": "file://example:1/",
"base": "about:blank",
"failure": true
},
{
"input": "file://example:test/",
"base": "about:blank",
"failure": true
},
{
"input": "file://example%/",
"base": "about:blank",
"failure": true
},
{
"input": "file://[example]/",
"base": "about:blank",
"failure": true
},
{
"input": "ftps:/example.com/",
"base": "http://example.org/foo/bar",
"href": "ftps:/example.com/",
"origin": "null",
"protocol": "ftps:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/example.com/",
"search": "",
"hash": ""
},
{
"input": "gopher:/example.com/",
"base": "http://example.org/foo/bar",
"href": "gopher://example.com/",
"origin": "gopher://example.com",
"protocol": "gopher:",
"username": "",
"password": "",
"host": "example.com",
"hostname": "example.com",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "ws:/example.com/",
"base": "http://example.org/foo/bar",
"href": "ws://example.com/",
"origin": "ws://example.com",
"protocol": "ws:",
"username": "",
"password": "",
"host": "example.com",
"hostname": "example.com",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "wss:/example.com/",
"base": "http://example.org/foo/bar",
"href": "wss://example.com/",
"origin": "wss://example.com",
"protocol": "wss:",
"username": "",
"password": "",
"host": "example.com",
"hostname": "example.com",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "data:/example.com/",
"base": "http://example.org/foo/bar",
"href": "data:/example.com/",
"origin": "null",
"protocol": "data:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/example.com/",
"search": "",
"hash": ""
},
{
"input": "javascript:/example.com/",
"base": "http://example.org/foo/bar",
"href": "javascript:/example.com/",
"origin": "null",
"protocol": "javascript:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/example.com/",
"search": "",
"hash": ""
},
{
"input": "mailto:/example.com/",
"base": "http://example.org/foo/bar",
"href": "mailto:/example.com/",
"origin": "null",
"protocol": "mailto:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/example.com/",
"search": "",
"hash": ""
},
{
"input": "http:example.com/",
"base": "http://example.org/foo/bar",
"href": "http://example.org/foo/example.com/",
"origin": "http://example.org",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.org",
"hostname": "example.org",
"port": "",
"pathname": "/foo/example.com/",
"search": "",
"hash": ""
},
{
"input": "ftp:example.com/",
"base": "http://example.org/foo/bar",
"href": "ftp://example.com/",
"origin": "ftp://example.com",
"protocol": "ftp:",
"username": "",
"password": "",
"host": "example.com",
"hostname": "example.com",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "https:example.com/",
"base": "http://example.org/foo/bar",
"href": "https://example.com/",
"origin": "https://example.com",
"protocol": "https:",
"username": "",
"password": "",
"host": "example.com",
"hostname": "example.com",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "madeupscheme:example.com/",
"base": "http://example.org/foo/bar",
"href": "madeupscheme:example.com/",
"origin": "null",
"protocol": "madeupscheme:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "example.com/",
"search": "",
"hash": ""
},
{
"input": "ftps:example.com/",
"base": "http://example.org/foo/bar",
"href": "ftps:example.com/",
"origin": "null",
"protocol": "ftps:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "example.com/",
"search": "",
"hash": ""
},
{
"input": "gopher:example.com/",
"base": "http://example.org/foo/bar",
"href": "gopher://example.com/",
"origin": "gopher://example.com",
"protocol": "gopher:",
"username": "",
"password": "",
"host": "example.com",
"hostname": "example.com",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "ws:example.com/",
"base": "http://example.org/foo/bar",
"href": "ws://example.com/",
"origin": "ws://example.com",
"protocol": "ws:",
"username": "",
"password": "",
"host": "example.com",
"hostname": "example.com",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "wss:example.com/",
"base": "http://example.org/foo/bar",
"href": "wss://example.com/",
"origin": "wss://example.com",
"protocol": "wss:",
"username": "",
"password": "",
"host": "example.com",
"hostname": "example.com",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "data:example.com/",
"base": "http://example.org/foo/bar",
"href": "data:example.com/",
"origin": "null",
"protocol": "data:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "example.com/",
"search": "",
"hash": ""
},
{
"input": "javascript:example.com/",
"base": "http://example.org/foo/bar",
"href": "javascript:example.com/",
"origin": "null",
"protocol": "javascript:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "example.com/",
"search": "",
"hash": ""
},
{
"input": "mailto:example.com/",
"base": "http://example.org/foo/bar",
"href": "mailto:example.com/",
"origin": "null",
"protocol": "mailto:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "example.com/",
"search": "",
"hash": ""
},
{
"input": "/a/b/c",
"base": "http://example.org/foo/bar",
"href": "http://example.org/a/b/c",
"origin": "http://example.org",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.org",
"hostname": "example.org",
"port": "",
"pathname": "/a/b/c",
"search": "",
"hash": ""
},
{
"input": "/a/ /c",
"base": "http://example.org/foo/bar",
"href": "http://example.org/a/%20/c",
"origin": "http://example.org",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.org",
"hostname": "example.org",
"port": "",
"pathname": "/a/%20/c",
"search": "",
"hash": ""
},
{
"input": "/a%2fc",
"base": "http://example.org/foo/bar",
"href": "http://example.org/a%2fc",
"origin": "http://example.org",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.org",
"hostname": "example.org",
"port": "",
"pathname": "/a%2fc",
"search": "",
"hash": ""
},
{
"input": "/a/%2f/c",
"base": "http://example.org/foo/bar",
"href": "http://example.org/a/%2f/c",
"origin": "http://example.org",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.org",
"hostname": "example.org",
"port": "",
"pathname": "/a/%2f/c",
"search": "",
"hash": ""
},
{
"input": "#β",
"base": "http://example.org/foo/bar",
"href": "http://example.org/foo/bar#%CE%B2",
"origin": "http://example.org",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.org",
"hostname": "example.org",
"port": "",
"pathname": "/foo/bar",
"search": "",
"hash": "#%CE%B2"
},
{
"input": "data:text/html,test#test",
"base": "http://example.org/foo/bar",
"href": "data:text/html,test#test",
"origin": "null",
"protocol": "data:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "text/html,test",
"search": "",
"hash": "#test"
},
{
"input": "tel:1234567890",
"base": "http://example.org/foo/bar",
"href": "tel:1234567890",
"origin": "null",
"protocol": "tel:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "1234567890",
"search": "",
"hash": ""
},
"# Based on http://trac.webkit.org/browser/trunk/LayoutTests/fast/url/file.html",
{
"input": "file:c:\\foo\\bar.html",
"base": "file:///tmp/mock/path",
"href": "file:///c:/foo/bar.html",
"protocol": "file:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/c:/foo/bar.html",
"search": "",
"hash": ""
},
{
"input": " File:c|////foo\\bar.html",
"base": "file:///tmp/mock/path",
"href": "file:///c:////foo/bar.html",
"protocol": "file:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/c:////foo/bar.html",
"search": "",
"hash": ""
},
{
"input": "C|/foo/bar",
"base": "file:///tmp/mock/path",
"href": "file:///C:/foo/bar",
"protocol": "file:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/C:/foo/bar",
"search": "",
"hash": ""
},
{
"input": "/C|\\foo\\bar",
"base": "file:///tmp/mock/path",
"href": "file:///C:/foo/bar",
"protocol": "file:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/C:/foo/bar",
"search": "",
"hash": ""
},
{
"input": "//C|/foo/bar",
"base": "file:///tmp/mock/path",
"href": "file:///C:/foo/bar",
"protocol": "file:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/C:/foo/bar",
"search": "",
"hash": ""
},
{
"input": "//server/file",
"base": "file:///tmp/mock/path",
"href": "file://server/file",
"protocol": "file:",
"username": "",
"password": "",
"host": "server",
"hostname": "server",
"port": "",
"pathname": "/file",
"search": "",
"hash": ""
},
{
"input": "\\\\server\\file",
"base": "file:///tmp/mock/path",
"href": "file://server/file",
"protocol": "file:",
"username": "",
"password": "",
"host": "server",
"hostname": "server",
"port": "",
"pathname": "/file",
"search": "",
"hash": ""
},
{
"input": "/\\server/file",
"base": "file:///tmp/mock/path",
"href": "file://server/file",
"protocol": "file:",
"username": "",
"password": "",
"host": "server",
"hostname": "server",
"port": "",
"pathname": "/file",
"search": "",
"hash": ""
},
{
"input": "file:///foo/bar.txt",
"base": "file:///tmp/mock/path",
"href": "file:///foo/bar.txt",
"protocol": "file:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/foo/bar.txt",
"search": "",
"hash": ""
},
{
"input": "file:///home/me",
"base": "file:///tmp/mock/path",
"href": "file:///home/me",
"protocol": "file:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/home/me",
"search": "",
"hash": ""
},
{
"input": "//",
"base": "file:///tmp/mock/path",
"href": "file:///",
"protocol": "file:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "///",
"base": "file:///tmp/mock/path",
"href": "file:///",
"protocol": "file:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "///test",
"base": "file:///tmp/mock/path",
"href": "file:///test",
"protocol": "file:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/test",
"search": "",
"hash": ""
},
{
"input": "file://test",
"base": "file:///tmp/mock/path",
"href": "file://test/",
"protocol": "file:",
"username": "",
"password": "",
"host": "test",
"hostname": "test",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "file://localhost",
"base": "file:///tmp/mock/path",
"href": "file:///",
"protocol": "file:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "file://localhost/",
"base": "file:///tmp/mock/path",
"href": "file:///",
"protocol": "file:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "file://localhost/test",
"base": "file:///tmp/mock/path",
"href": "file:///test",
"protocol": "file:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/test",
"search": "",
"hash": ""
},
{
"input": "test",
"base": "file:///tmp/mock/path",
"href": "file:///tmp/mock/test",
"protocol": "file:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/tmp/mock/test",
"search": "",
"hash": ""
},
{
"input": "file:test",
"base": "file:///tmp/mock/path",
"href": "file:///tmp/mock/test",
"protocol": "file:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/tmp/mock/test",
"search": "",
"hash": ""
},
"# Based on http://trac.webkit.org/browser/trunk/LayoutTests/fast/url/script-tests/path.js",
{
"input": "http://example.com/././foo",
"base": "about:blank",
"href": "http://example.com/foo",
"origin": "http://example.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.com",
"hostname": "example.com",
"port": "",
"pathname": "/foo",
"search": "",
"hash": ""
},
{
"input": "http://example.com/./.foo",
"base": "about:blank",
"href": "http://example.com/.foo",
"origin": "http://example.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.com",
"hostname": "example.com",
"port": "",
"pathname": "/.foo",
"search": "",
"hash": ""
},
{
"input": "http://example.com/foo/.",
"base": "about:blank",
"href": "http://example.com/foo/",
"origin": "http://example.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.com",
"hostname": "example.com",
"port": "",
"pathname": "/foo/",
"search": "",
"hash": ""
},
{
"input": "http://example.com/foo/./",
"base": "about:blank",
"href": "http://example.com/foo/",
"origin": "http://example.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.com",
"hostname": "example.com",
"port": "",
"pathname": "/foo/",
"search": "",
"hash": ""
},
{
"input": "http://example.com/foo/bar/..",
"base": "about:blank",
"href": "http://example.com/foo/",
"origin": "http://example.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.com",
"hostname": "example.com",
"port": "",
"pathname": "/foo/",
"search": "",
"hash": ""
},
{
"input": "http://example.com/foo/bar/../",
"base": "about:blank",
"href": "http://example.com/foo/",
"origin": "http://example.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.com",
"hostname": "example.com",
"port": "",
"pathname": "/foo/",
"search": "",
"hash": ""
},
{
"input": "http://example.com/foo/..bar",
"base": "about:blank",
"href": "http://example.com/foo/..bar",
"origin": "http://example.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.com",
"hostname": "example.com",
"port": "",
"pathname": "/foo/..bar",
"search": "",
"hash": ""
},
{
"input": "http://example.com/foo/bar/../ton",
"base": "about:blank",
"href": "http://example.com/foo/ton",
"origin": "http://example.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.com",
"hostname": "example.com",
"port": "",
"pathname": "/foo/ton",
"search": "",
"hash": ""
},
{
"input": "http://example.com/foo/bar/../ton/../../a",
"base": "about:blank",
"href": "http://example.com/a",
"origin": "http://example.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.com",
"hostname": "example.com",
"port": "",
"pathname": "/a",
"search": "",
"hash": ""
},
{
"input": "http://example.com/foo/../../..",
"base": "about:blank",
"href": "http://example.com/",
"origin": "http://example.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.com",
"hostname": "example.com",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "http://example.com/foo/../../../ton",
"base": "about:blank",
"href": "http://example.com/ton",
"origin": "http://example.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.com",
"hostname": "example.com",
"port": "",
"pathname": "/ton",
"search": "",
"hash": ""
},
{
"input": "http://example.com/foo/%2e",
"base": "about:blank",
"href": "http://example.com/foo/",
"origin": "http://example.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.com",
"hostname": "example.com",
"port": "",
"pathname": "/foo/",
"search": "",
"hash": ""
},
{
"input": "http://example.com/foo/%2e%2",
"base": "about:blank",
"href": "http://example.com/foo/%2e%2",
"origin": "http://example.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.com",
"hostname": "example.com",
"port": "",
"pathname": "/foo/%2e%2",
"search": "",
"hash": ""
},
{
"input": "http://example.com/foo/%2e./%2e%2e/.%2e/%2e.bar",
"base": "about:blank",
"href": "http://example.com/%2e.bar",
"origin": "http://example.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.com",
"hostname": "example.com",
"port": "",
"pathname": "/%2e.bar",
"search": "",
"hash": ""
},
{
"input": "http://example.com////../..",
"base": "about:blank",
"href": "http://example.com//",
"origin": "http://example.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.com",
"hostname": "example.com",
"port": "",
"pathname": "//",
"search": "",
"hash": ""
},
{
"input": "http://example.com/foo/bar//../..",
"base": "about:blank",
"href": "http://example.com/foo/",
"origin": "http://example.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.com",
"hostname": "example.com",
"port": "",
"pathname": "/foo/",
"search": "",
"hash": ""
},
{
"input": "http://example.com/foo/bar//..",
"base": "about:blank",
"href": "http://example.com/foo/bar/",
"origin": "http://example.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.com",
"hostname": "example.com",
"port": "",
"pathname": "/foo/bar/",
"search": "",
"hash": ""
},
{
"input": "http://example.com/foo",
"base": "about:blank",
"href": "http://example.com/foo",
"origin": "http://example.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.com",
"hostname": "example.com",
"port": "",
"pathname": "/foo",
"search": "",
"hash": ""
},
{
"input": "http://example.com/%20foo",
"base": "about:blank",
"href": "http://example.com/%20foo",
"origin": "http://example.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.com",
"hostname": "example.com",
"port": "",
"pathname": "/%20foo",
"search": "",
"hash": ""
},
{
"input": "http://example.com/foo%",
"base": "about:blank",
"href": "http://example.com/foo%",
"origin": "http://example.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.com",
"hostname": "example.com",
"port": "",
"pathname": "/foo%",
"search": "",
"hash": ""
},
{
"input": "http://example.com/foo%2",
"base": "about:blank",
"href": "http://example.com/foo%2",
"origin": "http://example.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.com",
"hostname": "example.com",
"port": "",
"pathname": "/foo%2",
"search": "",
"hash": ""
},
{
"input": "http://example.com/foo%2zbar",
"base": "about:blank",
"href": "http://example.com/foo%2zbar",
"origin": "http://example.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.com",
"hostname": "example.com",
"port": "",
"pathname": "/foo%2zbar",
"search": "",
"hash": ""
},
{
"input": "http://example.com/foo%2©zbar",
"base": "about:blank",
"href": "http://example.com/foo%2%C3%82%C2%A9zbar",
"origin": "http://example.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.com",
"hostname": "example.com",
"port": "",
"pathname": "/foo%2%C3%82%C2%A9zbar",
"search": "",
"hash": ""
},
{
"input": "http://example.com/foo%41%7a",
"base": "about:blank",
"href": "http://example.com/foo%41%7a",
"origin": "http://example.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.com",
"hostname": "example.com",
"port": "",
"pathname": "/foo%41%7a",
"search": "",
"hash": ""
},
{
"input": "http://example.com/foo\t\u0091%91",
"base": "about:blank",
"href": "http://example.com/foo%C2%91%91",
"origin": "http://example.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.com",
"hostname": "example.com",
"port": "",
"pathname": "/foo%C2%91%91",
"search": "",
"hash": ""
},
{
"input": "http://example.com/foo%00%51",
"base": "about:blank",
"href": "http://example.com/foo%00%51",
"origin": "http://example.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.com",
"hostname": "example.com",
"port": "",
"pathname": "/foo%00%51",
"search": "",
"hash": ""
},
{
"input": "http://example.com/(%28:%3A%29)",
"base": "about:blank",
"href": "http://example.com/(%28:%3A%29)",
"origin": "http://example.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.com",
"hostname": "example.com",
"port": "",
"pathname": "/(%28:%3A%29)",
"search": "",
"hash": ""
},
{
"input": "http://example.com/%3A%3a%3C%3c",
"base": "about:blank",
"href": "http://example.com/%3A%3a%3C%3c",
"origin": "http://example.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.com",
"hostname": "example.com",
"port": "",
"pathname": "/%3A%3a%3C%3c",
"search": "",
"hash": ""
},
{
"input": "http://example.com/foo\tbar",
"base": "about:blank",
"href": "http://example.com/foobar",
"origin": "http://example.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.com",
"hostname": "example.com",
"port": "",
"pathname": "/foobar",
"search": "",
"hash": ""
},
{
"input": "http://example.com\\\\foo\\\\bar",
"base": "about:blank",
"href": "http://example.com//foo//bar",
"origin": "http://example.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.com",
"hostname": "example.com",
"port": "",
"pathname": "//foo//bar",
"search": "",
"hash": ""
},
{
"input": "http://example.com/%7Ffp3%3Eju%3Dduvgw%3Dd",
"base": "about:blank",
"href": "http://example.com/%7Ffp3%3Eju%3Dduvgw%3Dd",
"origin": "http://example.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.com",
"hostname": "example.com",
"port": "",
"pathname": "/%7Ffp3%3Eju%3Dduvgw%3Dd",
"search": "",
"hash": ""
},
{
"input": "http://example.com/@asdf%40",
"base": "about:blank",
"href": "http://example.com/@asdf%40",
"origin": "http://example.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.com",
"hostname": "example.com",
"port": "",
"pathname": "/@asdf%40",
"search": "",
"hash": ""
},
{
"input": "http://example.com/你好你好",
"base": "about:blank",
"href": "http://example.com/%E4%BD%A0%E5%A5%BD%E4%BD%A0%E5%A5%BD",
"origin": "http://example.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.com",
"hostname": "example.com",
"port": "",
"pathname": "/%E4%BD%A0%E5%A5%BD%E4%BD%A0%E5%A5%BD",
"search": "",
"hash": ""
},
{
"input": "http://example.com/‥/foo",
"base": "about:blank",
"href": "http://example.com/%E2%80%A5/foo",
"origin": "http://example.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.com",
"hostname": "example.com",
"port": "",
"pathname": "/%E2%80%A5/foo",
"search": "",
"hash": ""
},
{
"input": "http://example.com//foo",
"base": "about:blank",
"href": "http://example.com/%EF%BB%BF/foo",
"origin": "http://example.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.com",
"hostname": "example.com",
"port": "",
"pathname": "/%EF%BB%BF/foo",
"search": "",
"hash": ""
},
{
"input": "http://example.com//foo//bar",
"base": "about:blank",
"href": "http://example.com/%E2%80%AE/foo/%E2%80%AD/bar",
"origin": "http://example.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.com",
"hostname": "example.com",
"port": "",
"pathname": "/%E2%80%AE/foo/%E2%80%AD/bar",
"search": "",
"hash": ""
},
"# Based on http://trac.webkit.org/browser/trunk/LayoutTests/fast/url/script-tests/relative.js",
{
"input": "http://www.google.com/foo?bar=baz#",
"base": "about:blank",
"href": "http://www.google.com/foo?bar=baz#",
"origin": "http://www.google.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "www.google.com",
"hostname": "www.google.com",
"port": "",
"pathname": "/foo",
"search": "?bar=baz",
"hash": ""
},
{
"input": "http://www.google.com/foo?bar=baz# »",
"base": "about:blank",
"href": "http://www.google.com/foo?bar=baz#%20%C2%BB",
"origin": "http://www.google.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "www.google.com",
"hostname": "www.google.com",
"port": "",
"pathname": "/foo",
"search": "?bar=baz",
"hash": "#%20%C2%BB"
},
{
"input": "data:test# »",
"base": "about:blank",
"href": "data:test#%20%C2%BB",
"origin": "null",
"protocol": "data:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "test",
"search": "",
"hash": "#%20%C2%BB"
},
{
"input": "http://www.google.com",
"base": "about:blank",
"href": "http://www.google.com/",
"origin": "http://www.google.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "www.google.com",
"hostname": "www.google.com",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "http://192.0x00A80001",
"base": "about:blank",
"href": "http://192.168.0.1/",
"origin": "http://192.168.0.1",
"protocol": "http:",
"username": "",
"password": "",
"host": "192.168.0.1",
"hostname": "192.168.0.1",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "http://www/foo%2Ehtml",
"base": "about:blank",
"href": "http://www/foo%2Ehtml",
"origin": "http://www",
"protocol": "http:",
"username": "",
"password": "",
"host": "www",
"hostname": "www",
"port": "",
"pathname": "/foo%2Ehtml",
"search": "",
"hash": ""
},
{
"input": "http://www/foo/%2E/html",
"base": "about:blank",
"href": "http://www/foo/html",
"origin": "http://www",
"protocol": "http:",
"username": "",
"password": "",
"host": "www",
"hostname": "www",
"port": "",
"pathname": "/foo/html",
"search": "",
"hash": ""
},
{
"input": "http://user:pass@/",
"base": "about:blank",
"failure": true
},
{
"input": "http://%25DOMAIN:foobar@foodomain.com/",
"base": "about:blank",
"href": "http://%25DOMAIN:foobar@foodomain.com/",
"origin": "http://foodomain.com",
"protocol": "http:",
"username": "%25DOMAIN",
"password": "foobar",
"host": "foodomain.com",
"hostname": "foodomain.com",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "http:\\\\www.google.com\\foo",
"base": "about:blank",
"href": "http://www.google.com/foo",
"origin": "http://www.google.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "www.google.com",
"hostname": "www.google.com",
"port": "",
"pathname": "/foo",
"search": "",
"hash": ""
},
{
"input": "http://foo:80/",
"base": "about:blank",
"href": "http://foo/",
"origin": "http://foo",
"protocol": "http:",
"username": "",
"password": "",
"host": "foo",
"hostname": "foo",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "http://foo:81/",
"base": "about:blank",
"href": "http://foo:81/",
"origin": "http://foo:81",
"protocol": "http:",
"username": "",
"password": "",
"host": "foo:81",
"hostname": "foo",
"port": "81",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "httpa://foo:80/",
"base": "about:blank",
"href": "httpa://foo:80/",
"origin": "null",
"protocol": "httpa:",
"username": "",
"password": "",
"host": "foo:80",
"hostname": "foo",
"port": "80",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "http://foo:-80/",
"base": "about:blank",
"failure": true
},
{
"input": "https://foo:443/",
"base": "about:blank",
"href": "https://foo/",
"origin": "https://foo",
"protocol": "https:",
"username": "",
"password": "",
"host": "foo",
"hostname": "foo",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "https://foo:80/",
"base": "about:blank",
"href": "https://foo:80/",
"origin": "https://foo:80",
"protocol": "https:",
"username": "",
"password": "",
"host": "foo:80",
"hostname": "foo",
"port": "80",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "ftp://foo:21/",
"base": "about:blank",
"href": "ftp://foo/",
"origin": "ftp://foo",
"protocol": "ftp:",
"username": "",
"password": "",
"host": "foo",
"hostname": "foo",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "ftp://foo:80/",
"base": "about:blank",
"href": "ftp://foo:80/",
"origin": "ftp://foo:80",
"protocol": "ftp:",
"username": "",
"password": "",
"host": "foo:80",
"hostname": "foo",
"port": "80",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "gopher://foo:70/",
"base": "about:blank",
"href": "gopher://foo/",
"origin": "gopher://foo",
"protocol": "gopher:",
"username": "",
"password": "",
"host": "foo",
"hostname": "foo",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "gopher://foo:443/",
"base": "about:blank",
"href": "gopher://foo:443/",
"origin": "gopher://foo:443",
"protocol": "gopher:",
"username": "",
"password": "",
"host": "foo:443",
"hostname": "foo",
"port": "443",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "ws://foo:80/",
"base": "about:blank",
"href": "ws://foo/",
"origin": "ws://foo",
"protocol": "ws:",
"username": "",
"password": "",
"host": "foo",
"hostname": "foo",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "ws://foo:81/",
"base": "about:blank",
"href": "ws://foo:81/",
"origin": "ws://foo:81",
"protocol": "ws:",
"username": "",
"password": "",
"host": "foo:81",
"hostname": "foo",
"port": "81",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "ws://foo:443/",
"base": "about:blank",
"href": "ws://foo:443/",
"origin": "ws://foo:443",
"protocol": "ws:",
"username": "",
"password": "",
"host": "foo:443",
"hostname": "foo",
"port": "443",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "ws://foo:815/",
"base": "about:blank",
"href": "ws://foo:815/",
"origin": "ws://foo:815",
"protocol": "ws:",
"username": "",
"password": "",
"host": "foo:815",
"hostname": "foo",
"port": "815",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "wss://foo:80/",
"base": "about:blank",
"href": "wss://foo:80/",
"origin": "wss://foo:80",
"protocol": "wss:",
"username": "",
"password": "",
"host": "foo:80",
"hostname": "foo",
"port": "80",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "wss://foo:81/",
"base": "about:blank",
"href": "wss://foo:81/",
"origin": "wss://foo:81",
"protocol": "wss:",
"username": "",
"password": "",
"host": "foo:81",
"hostname": "foo",
"port": "81",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "wss://foo:443/",
"base": "about:blank",
"href": "wss://foo/",
"origin": "wss://foo",
"protocol": "wss:",
"username": "",
"password": "",
"host": "foo",
"hostname": "foo",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "wss://foo:815/",
"base": "about:blank",
"href": "wss://foo:815/",
"origin": "wss://foo:815",
"protocol": "wss:",
"username": "",
"password": "",
"host": "foo:815",
"hostname": "foo",
"port": "815",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "http:/example.com/",
"base": "about:blank",
"href": "http://example.com/",
"origin": "http://example.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.com",
"hostname": "example.com",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "ftp:/example.com/",
"base": "about:blank",
"href": "ftp://example.com/",
"origin": "ftp://example.com",
"protocol": "ftp:",
"username": "",
"password": "",
"host": "example.com",
"hostname": "example.com",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "https:/example.com/",
"base": "about:blank",
"href": "https://example.com/",
"origin": "https://example.com",
"protocol": "https:",
"username": "",
"password": "",
"host": "example.com",
"hostname": "example.com",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "madeupscheme:/example.com/",
"base": "about:blank",
"href": "madeupscheme:/example.com/",
"origin": "null",
"protocol": "madeupscheme:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/example.com/",
"search": "",
"hash": ""
},
{
"input": "file:/example.com/",
"base": "about:blank",
"href": "file:///example.com/",
"protocol": "file:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/example.com/",
"search": "",
"hash": ""
},
{
"input": "ftps:/example.com/",
"base": "about:blank",
"href": "ftps:/example.com/",
"origin": "null",
"protocol": "ftps:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/example.com/",
"search": "",
"hash": ""
},
{
"input": "gopher:/example.com/",
"base": "about:blank",
"href": "gopher://example.com/",
"origin": "gopher://example.com",
"protocol": "gopher:",
"username": "",
"password": "",
"host": "example.com",
"hostname": "example.com",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "ws:/example.com/",
"base": "about:blank",
"href": "ws://example.com/",
"origin": "ws://example.com",
"protocol": "ws:",
"username": "",
"password": "",
"host": "example.com",
"hostname": "example.com",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "wss:/example.com/",
"base": "about:blank",
"href": "wss://example.com/",
"origin": "wss://example.com",
"protocol": "wss:",
"username": "",
"password": "",
"host": "example.com",
"hostname": "example.com",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "data:/example.com/",
"base": "about:blank",
"href": "data:/example.com/",
"origin": "null",
"protocol": "data:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/example.com/",
"search": "",
"hash": ""
},
{
"input": "javascript:/example.com/",
"base": "about:blank",
"href": "javascript:/example.com/",
"origin": "null",
"protocol": "javascript:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/example.com/",
"search": "",
"hash": ""
},
{
"input": "mailto:/example.com/",
"base": "about:blank",
"href": "mailto:/example.com/",
"origin": "null",
"protocol": "mailto:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/example.com/",
"search": "",
"hash": ""
},
{
"input": "http:example.com/",
"base": "about:blank",
"href": "http://example.com/",
"origin": "http://example.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.com",
"hostname": "example.com",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "ftp:example.com/",
"base": "about:blank",
"href": "ftp://example.com/",
"origin": "ftp://example.com",
"protocol": "ftp:",
"username": "",
"password": "",
"host": "example.com",
"hostname": "example.com",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "https:example.com/",
"base": "about:blank",
"href": "https://example.com/",
"origin": "https://example.com",
"protocol": "https:",
"username": "",
"password": "",
"host": "example.com",
"hostname": "example.com",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "madeupscheme:example.com/",
"base": "about:blank",
"href": "madeupscheme:example.com/",
"origin": "null",
"protocol": "madeupscheme:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "example.com/",
"search": "",
"hash": ""
},
{
"input": "ftps:example.com/",
"base": "about:blank",
"href": "ftps:example.com/",
"origin": "null",
"protocol": "ftps:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "example.com/",
"search": "",
"hash": ""
},
{
"input": "gopher:example.com/",
"base": "about:blank",
"href": "gopher://example.com/",
"origin": "gopher://example.com",
"protocol": "gopher:",
"username": "",
"password": "",
"host": "example.com",
"hostname": "example.com",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "ws:example.com/",
"base": "about:blank",
"href": "ws://example.com/",
"origin": "ws://example.com",
"protocol": "ws:",
"username": "",
"password": "",
"host": "example.com",
"hostname": "example.com",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "wss:example.com/",
"base": "about:blank",
"href": "wss://example.com/",
"origin": "wss://example.com",
"protocol": "wss:",
"username": "",
"password": "",
"host": "example.com",
"hostname": "example.com",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "data:example.com/",
"base": "about:blank",
"href": "data:example.com/",
"origin": "null",
"protocol": "data:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "example.com/",
"search": "",
"hash": ""
},
{
"input": "javascript:example.com/",
"base": "about:blank",
"href": "javascript:example.com/",
"origin": "null",
"protocol": "javascript:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "example.com/",
"search": "",
"hash": ""
},
{
"input": "mailto:example.com/",
"base": "about:blank",
"href": "mailto:example.com/",
"origin": "null",
"protocol": "mailto:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "example.com/",
"search": "",
"hash": ""
},
"# Based on http://trac.webkit.org/browser/trunk/LayoutTests/fast/url/segments-userinfo-vs-host.html",
{
"input": "http:@www.example.com",
"base": "about:blank",
"href": "http://www.example.com/",
"origin": "http://www.example.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "www.example.com",
"hostname": "www.example.com",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "http:/@www.example.com",
"base": "about:blank",
"href": "http://www.example.com/",
"origin": "http://www.example.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "www.example.com",
"hostname": "www.example.com",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "http://@www.example.com",
"base": "about:blank",
"href": "http://www.example.com/",
"origin": "http://www.example.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "www.example.com",
"hostname": "www.example.com",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "http:a:b@www.example.com",
"base": "about:blank",
"href": "http://a:b@www.example.com/",
"origin": "http://www.example.com",
"protocol": "http:",
"username": "a",
"password": "b",
"host": "www.example.com",
"hostname": "www.example.com",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "http:/a:b@www.example.com",
"base": "about:blank",
"href": "http://a:b@www.example.com/",
"origin": "http://www.example.com",
"protocol": "http:",
"username": "a",
"password": "b",
"host": "www.example.com",
"hostname": "www.example.com",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "http://a:b@www.example.com",
"base": "about:blank",
"href": "http://a:b@www.example.com/",
"origin": "http://www.example.com",
"protocol": "http:",
"username": "a",
"password": "b",
"host": "www.example.com",
"hostname": "www.example.com",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "http://@pple.com",
"base": "about:blank",
"href": "http://pple.com/",
"origin": "http://pple.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "pple.com",
"hostname": "pple.com",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "http::b@www.example.com",
"base": "about:blank",
"href": "http://:b@www.example.com/",
"origin": "http://www.example.com",
"protocol": "http:",
"username": "",
"password": "b",
"host": "www.example.com",
"hostname": "www.example.com",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "http:/:b@www.example.com",
"base": "about:blank",
"href": "http://:b@www.example.com/",
"origin": "http://www.example.com",
"protocol": "http:",
"username": "",
"password": "b",
"host": "www.example.com",
"hostname": "www.example.com",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "http://:b@www.example.com",
"base": "about:blank",
"href": "http://:b@www.example.com/",
"origin": "http://www.example.com",
"protocol": "http:",
"username": "",
"password": "b",
"host": "www.example.com",
"hostname": "www.example.com",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "http:/:@/www.example.com",
"base": "about:blank",
"failure": true
},
{
"input": "http://user@/www.example.com",
"base": "about:blank",
"failure": true
},
{
"input": "http:@/www.example.com",
"base": "about:blank",
"failure": true
},
{
"input": "http:/@/www.example.com",
"base": "about:blank",
"failure": true
},
{
"input": "http://@/www.example.com",
"base": "about:blank",
"failure": true
},
{
"input": "https:@/www.example.com",
"base": "about:blank",
"failure": true
},
{
"input": "http:a:b@/www.example.com",
"base": "about:blank",
"failure": true
},
{
"input": "http:/a:b@/www.example.com",
"base": "about:blank",
"failure": true
},
{
"input": "http://a:b@/www.example.com",
"base": "about:blank",
"failure": true
},
{
"input": "http::@/www.example.com",
"base": "about:blank",
"failure": true
},
{
"input": "http:a:@www.example.com",
"base": "about:blank",
"href": "http://a@www.example.com/",
"origin": "http://www.example.com",
"protocol": "http:",
"username": "a",
"password": "",
"host": "www.example.com",
"hostname": "www.example.com",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "http:/a:@www.example.com",
"base": "about:blank",
"href": "http://a@www.example.com/",
"origin": "http://www.example.com",
"protocol": "http:",
"username": "a",
"password": "",
"host": "www.example.com",
"hostname": "www.example.com",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "http://a:@www.example.com",
"base": "about:blank",
"href": "http://a@www.example.com/",
"origin": "http://www.example.com",
"protocol": "http:",
"username": "a",
"password": "",
"host": "www.example.com",
"hostname": "www.example.com",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "http://www.@pple.com",
"base": "about:blank",
"href": "http://www.@pple.com/",
"origin": "http://pple.com",
"protocol": "http:",
"username": "www.",
"password": "",
"host": "pple.com",
"hostname": "pple.com",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "http:@:www.example.com",
"base": "about:blank",
"failure": true
},
{
"input": "http:/@:www.example.com",
"base": "about:blank",
"failure": true
},
{
"input": "http://@:www.example.com",
"base": "about:blank",
"failure": true
},
{
"input": "http://:@www.example.com",
"base": "about:blank",
"href": "http://www.example.com/",
"origin": "http://www.example.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "www.example.com",
"hostname": "www.example.com",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
"# Others",
{
"input": "/",
"base": "http://www.example.com/test",
"href": "http://www.example.com/",
"origin": "http://www.example.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "www.example.com",
"hostname": "www.example.com",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "/test.txt",
"base": "http://www.example.com/test",
"href": "http://www.example.com/test.txt",
"origin": "http://www.example.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "www.example.com",
"hostname": "www.example.com",
"port": "",
"pathname": "/test.txt",
"search": "",
"hash": ""
},
{
"input": ".",
"base": "http://www.example.com/test",
"href": "http://www.example.com/",
"origin": "http://www.example.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "www.example.com",
"hostname": "www.example.com",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "..",
"base": "http://www.example.com/test",
"href": "http://www.example.com/",
"origin": "http://www.example.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "www.example.com",
"hostname": "www.example.com",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "test.txt",
"base": "http://www.example.com/test",
"href": "http://www.example.com/test.txt",
"origin": "http://www.example.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "www.example.com",
"hostname": "www.example.com",
"port": "",
"pathname": "/test.txt",
"search": "",
"hash": ""
},
{
"input": "./test.txt",
"base": "http://www.example.com/test",
"href": "http://www.example.com/test.txt",
"origin": "http://www.example.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "www.example.com",
"hostname": "www.example.com",
"port": "",
"pathname": "/test.txt",
"search": "",
"hash": ""
},
{
"input": "../test.txt",
"base": "http://www.example.com/test",
"href": "http://www.example.com/test.txt",
"origin": "http://www.example.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "www.example.com",
"hostname": "www.example.com",
"port": "",
"pathname": "/test.txt",
"search": "",
"hash": ""
},
{
"input": "../aaa/test.txt",
"base": "http://www.example.com/test",
"href": "http://www.example.com/aaa/test.txt",
"origin": "http://www.example.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "www.example.com",
"hostname": "www.example.com",
"port": "",
"pathname": "/aaa/test.txt",
"search": "",
"hash": ""
},
{
"input": "../../test.txt",
"base": "http://www.example.com/test",
"href": "http://www.example.com/test.txt",
"origin": "http://www.example.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "www.example.com",
"hostname": "www.example.com",
"port": "",
"pathname": "/test.txt",
"search": "",
"hash": ""
},
{
"input": "中/test.txt",
"base": "http://www.example.com/test",
"href": "http://www.example.com/%E4%B8%AD/test.txt",
"origin": "http://www.example.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "www.example.com",
"hostname": "www.example.com",
"port": "",
"pathname": "/%E4%B8%AD/test.txt",
"search": "",
"hash": ""
},
{
"input": "http://www.example2.com",
"base": "http://www.example.com/test",
"href": "http://www.example2.com/",
"origin": "http://www.example2.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "www.example2.com",
"hostname": "www.example2.com",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "//www.example2.com",
"base": "http://www.example.com/test",
"href": "http://www.example2.com/",
"origin": "http://www.example2.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "www.example2.com",
"hostname": "www.example2.com",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "file:...",
"base": "http://www.example.com/test",
"href": "file:///...",
"protocol": "file:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/...",
"search": "",
"hash": ""
},
{
"input": "file:..",
"base": "http://www.example.com/test",
"href": "file:///",
"protocol": "file:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "file:a",
"base": "http://www.example.com/test",
"href": "file:///a",
"protocol": "file:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/a",
"search": "",
"hash": ""
},
"# Based on http://trac.webkit.org/browser/trunk/LayoutTests/fast/url/host.html",
"Basic canonicalization, uppercase should be converted to lowercase",
{
"input": "http://ExAmPlE.CoM",
"base": "http://other.com/",
"href": "http://example.com/",
"origin": "http://example.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.com",
"hostname": "example.com",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "http://example example.com",
"base": "http://other.com/",
"failure": true
},
{
"input": "http://Goo%20 goo%7C|.com",
"base": "http://other.com/",
"failure": true
},
{
"input": "http://[]",
"base": "http://other.com/",
"failure": true
},
{
"input": "http://[:]",
"base": "http://other.com/",
"failure": true
},
"U+3000 is mapped to U+0020 (space) which is disallowed",
{
"input": "http://GOO\u00a0\u3000goo.com",
"base": "http://other.com/",
"failure": true
},
"Other types of space (no-break, zero-width, zero-width-no-break) are name-prepped away to nothing. U+200B, U+2060, and U+FEFF, are ignored",
{
"input": "http://GOO\u200b\u2060\ufeffgoo.com",
"base": "http://other.com/",
"href": "http://googoo.com/",
"origin": "http://googoo.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "googoo.com",
"hostname": "googoo.com",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
"Leading and trailing C0 control or space",
{
"input": "\u0000\u001b\u0004\u0012 http://example.com/\u001f \u000d ",
"base": "about:blank",
"href": "http://example.com/",
"origin": "http://example.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.com",
"hostname": "example.com",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
"Ideographic full stop (full-width period for Chinese, etc.) should be treated as a dot. U+3002 is mapped to U+002E (dot)",
{
"input": "http://www.foo。bar.com",
"base": "http://other.com/",
"href": "http://www.foo.bar.com/",
"origin": "http://www.foo.bar.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "www.foo.bar.com",
"hostname": "www.foo.bar.com",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
"Invalid unicode characters should fail... U+FDD0 is disallowed; %ef%b7%90 is U+FDD0",
{
"input": "http://\ufdd0zyx.com",
"base": "http://other.com/",
"failure": true
},
"This is the same as previous but escaped",
{
"input": "http://%ef%b7%90zyx.com",
"base": "http://other.com/",
"failure": true
},
"U+FFFD",
{
"input": "https://\ufffd",
"base": "about:blank",
"failure": true
},
{
"input": "https://%EF%BF%BD",
"base": "about:blank",
"failure": true
},
{
"input": "https://x/\ufffd?\ufffd#\ufffd",
"base": "about:blank",
"href": "https://x/%EF%BF%BD?%EF%BF%BD#%EF%BF%BD",
"origin": "https://x",
"protocol": "https:",
"username": "",
"password": "",
"host": "x",
"hostname": "x",
"port": "",
"pathname": "/%EF%BF%BD",
"search": "?%EF%BF%BD",
"hash": "#%EF%BF%BD"
},
"Test name prepping, fullwidth input should be converted to ASCII and NOT IDN-ized. This is 'Go' in fullwidth UTF-8/UTF-16.",
{
"input": "http://Go.com",
"base": "http://other.com/",
"href": "http://go.com/",
"origin": "http://go.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "go.com",
"hostname": "go.com",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
"URL spec forbids the following. https://www.w3.org/Bugs/Public/show_bug.cgi?id=24257",
{
"input": "http://%41.com",
"base": "http://other.com/",
"failure": true
},
{
"input": "http://%ef%bc%85%ef%bc%94%ef%bc%91.com",
"base": "http://other.com/",
"failure": true
},
"...%00 in fullwidth should fail (also as escaped UTF-8 input)",
{
"input": "http://%00.com",
"base": "http://other.com/",
"failure": true
},
{
"input": "http://%ef%bc%85%ef%bc%90%ef%bc%90.com",
"base": "http://other.com/",
"failure": true
},
"Basic IDN support, UTF-8 and UTF-16 input should be converted to IDN",
{
"input": "http://你好你好",
"base": "http://other.com/",
"href": "http://xn--6qqa088eba/",
"origin": "http://xn--6qqa088eba",
"protocol": "http:",
"username": "",
"password": "",
"host": "xn--6qqa088eba",
"hostname": "xn--6qqa088eba",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "https://faß.ExAmPlE/",
"base": "about:blank",
"href": "https://xn--fa-hia.example/",
"origin": "https://xn--fa-hia.example",
"protocol": "https:",
"username": "",
"password": "",
"host": "xn--fa-hia.example",
"hostname": "xn--fa-hia.example",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "sc://faß.ExAmPlE/",
"base": "about:blank",
"href": "sc://fa%C3%9F.ExAmPlE/",
"origin": "null",
"protocol": "sc:",
"username": "",
"password": "",
"host": "fa%C3%9F.ExAmPlE",
"hostname": "fa%C3%9F.ExAmPlE",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
"Invalid escaped characters should fail and the percents should be escaped. https://www.w3.org/Bugs/Public/show_bug.cgi?id=24191",
{
"input": "http://%zz%66%a.com",
"base": "http://other.com/",
"failure": true
},
"If we get an invalid character that has been escaped.",
{
"input": "http://%25",
"base": "http://other.com/",
"failure": true
},
{
"input": "http://hello%00",
"base": "http://other.com/",
"failure": true
},
"Escaped numbers should be treated like IP addresses if they are.",
{
"input": "http://%30%78%63%30%2e%30%32%35%30.01",
"base": "http://other.com/",
"href": "http://192.168.0.1/",
"origin": "http://192.168.0.1",
"protocol": "http:",
"username": "",
"password": "",
"host": "192.168.0.1",
"hostname": "192.168.0.1",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "http://%30%78%63%30%2e%30%32%35%30.01%2e",
"base": "http://other.com/",
"href": "http://192.168.0.1/",
"origin": "http://192.168.0.1",
"protocol": "http:",
"username": "",
"password": "",
"host": "192.168.0.1",
"hostname": "192.168.0.1",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "http://192.168.0.257",
"base": "http://other.com/",
"failure": true
},
"Invalid escaping in hosts causes failure",
{
"input": "http://%3g%78%63%30%2e%30%32%35%30%2E.01",
"base": "http://other.com/",
"failure": true
},
"A space in a host causes failure",
{
"input": "http://192.168.0.1 hello",
"base": "http://other.com/",
"failure": true
},
{
"input": "https://x x:12",
"base": "about:blank",
"failure": true
},
"Fullwidth and escaped UTF-8 fullwidth should still be treated as IP",
{
"input": "http://0Xc0.0250.01",
"base": "http://other.com/",
"href": "http://192.168.0.1/",
"origin": "http://192.168.0.1",
"protocol": "http:",
"username": "",
"password": "",
"host": "192.168.0.1",
"hostname": "192.168.0.1",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
"Domains with empty labels",
{
"input": "http://./",
"base": "about:blank",
"href": "http://./",
"origin": "http://.",
"protocol": "http:",
"username": "",
"password": "",
"host": ".",
"hostname": ".",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "http://../",
"base": "about:blank",
"href": "http://../",
"origin": "http://..",
"protocol": "http:",
"username": "",
"password": "",
"host": "..",
"hostname": "..",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "http://0..0x300/",
"base": "about:blank",
"href": "http://0..0x300/",
"origin": "http://0..0x300",
"protocol": "http:",
"username": "",
"password": "",
"host": "0..0x300",
"hostname": "0..0x300",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
"Broken IPv6",
{
"input": "http://[www.google.com]/",
"base": "about:blank",
"failure": true
},
{
"input": "http://[google.com]",
"base": "http://other.com/",
"failure": true
},
{
"input": "http://[::1.2.3.4x]",
"base": "http://other.com/",
"failure": true
},
{
"input": "http://[::1.2.3.]",
"base": "http://other.com/",
"failure": true
},
{
"input": "http://[::1.2.]",
"base": "http://other.com/",
"failure": true
},
{
"input": "http://[::1.]",
"base": "http://other.com/",
"failure": true
},
"Misc Unicode",
{
"input": "http://foo:💩@example.com/bar",
"base": "http://other.com/",
"href": "http://foo:%F0%9F%92%A9@example.com/bar",
"origin": "http://example.com",
"protocol": "http:",
"username": "foo",
"password": "%F0%9F%92%A9",
"host": "example.com",
"hostname": "example.com",
"port": "",
"pathname": "/bar",
"search": "",
"hash": ""
},
"# resolving a fragment against any scheme succeeds",
{
"input": "#",
"base": "test:test",
"href": "test:test#",
"origin": "null",
"protocol": "test:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "test",
"search": "",
"hash": ""
},
{
"input": "#x",
"base": "mailto:x@x.com",
"href": "mailto:x@x.com#x",
"origin": "null",
"protocol": "mailto:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "x@x.com",
"search": "",
"hash": "#x"
},
{
"input": "#x",
"base": "data:,",
"href": "data:,#x",
"origin": "null",
"protocol": "data:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": ",",
"search": "",
"hash": "#x"
},
{
"input": "#x",
"base": "about:blank",
"href": "about:blank#x",
"origin": "null",
"protocol": "about:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "blank",
"search": "",
"hash": "#x"
},
{
"input": "#",
"base": "test:test?test",
"href": "test:test?test#",
"origin": "null",
"protocol": "test:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "test",
"search": "?test",
"hash": ""
},
"# multiple @ in authority state",
{
"input": "https://@test@test@example:800/",
"base": "http://doesnotmatter/",
"href": "https://%40test%40test@example:800/",
"origin": "https://example:800",
"protocol": "https:",
"username": "%40test%40test",
"password": "",
"host": "example:800",
"hostname": "example",
"port": "800",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "https://@@@example",
"base": "http://doesnotmatter/",
"href": "https://%40%40@example/",
"origin": "https://example",
"protocol": "https:",
"username": "%40%40",
"password": "",
"host": "example",
"hostname": "example",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
"non-az-09 characters",
{
"input": "http://`{}:`{}@h/`{}?`{}",
"base": "http://doesnotmatter/",
"href": "http://%60%7B%7D:%60%7B%7D@h/%60%7B%7D?`{}",
"origin": "http://h",
"protocol": "http:",
"username": "%60%7B%7D",
"password": "%60%7B%7D",
"host": "h",
"hostname": "h",
"port": "",
"pathname": "/%60%7B%7D",
"search": "?`{}",
"hash": ""
},
"# Credentials in base",
{
"input": "/some/path",
"base": "http://user@example.org/smth",
"href": "http://user@example.org/some/path",
"origin": "http://example.org",
"protocol": "http:",
"username": "user",
"password": "",
"host": "example.org",
"hostname": "example.org",
"port": "",
"pathname": "/some/path",
"search": "",
"hash": ""
},
{
"input": "",
"base": "http://user:pass@example.org:21/smth",
"href": "http://user:pass@example.org:21/smth",
"origin": "http://example.org:21",
"protocol": "http:",
"username": "user",
"password": "pass",
"host": "example.org:21",
"hostname": "example.org",
"port": "21",
"pathname": "/smth",
"search": "",
"hash": ""
},
{
"input": "/some/path",
"base": "http://user:pass@example.org:21/smth",
"href": "http://user:pass@example.org:21/some/path",
"origin": "http://example.org:21",
"protocol": "http:",
"username": "user",
"password": "pass",
"host": "example.org:21",
"hostname": "example.org",
"port": "21",
"pathname": "/some/path",
"search": "",
"hash": ""
},
"# a set of tests designed by zcorpan for relative URLs with unknown schemes",
{
"input": "i",
"base": "sc:sd",
"failure": true
},
{
"input": "i",
"base": "sc:sd/sd",
"failure": true
},
{
"input": "i",
"base": "sc:/pa/pa",
"href": "sc:/pa/i",
"origin": "null",
"protocol": "sc:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/pa/i",
"search": "",
"hash": ""
},
{
"input": "i",
"base": "sc://ho/pa",
"href": "sc://ho/i",
"origin": "null",
"protocol": "sc:",
"username": "",
"password": "",
"host": "ho",
"hostname": "ho",
"port": "",
"pathname": "/i",
"search": "",
"hash": ""
},
{
"input": "i",
"base": "sc:///pa/pa",
"href": "sc:///pa/i",
"origin": "null",
"protocol": "sc:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/pa/i",
"search": "",
"hash": ""
},
{
"input": "../i",
"base": "sc:sd",
"failure": true
},
{
"input": "../i",
"base": "sc:sd/sd",
"failure": true
},
{
"input": "../i",
"base": "sc:/pa/pa",
"href": "sc:/i",
"origin": "null",
"protocol": "sc:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/i",
"search": "",
"hash": ""
},
{
"input": "../i",
"base": "sc://ho/pa",
"href": "sc://ho/i",
"origin": "null",
"protocol": "sc:",
"username": "",
"password": "",
"host": "ho",
"hostname": "ho",
"port": "",
"pathname": "/i",
"search": "",
"hash": ""
},
{
"input": "../i",
"base": "sc:///pa/pa",
"href": "sc:///i",
"origin": "null",
"protocol": "sc:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/i",
"search": "",
"hash": ""
},
{
"input": "/i",
"base": "sc:sd",
"failure": true
},
{
"input": "/i",
"base": "sc:sd/sd",
"failure": true
},
{
"input": "/i",
"base": "sc:/pa/pa",
"href": "sc:/i",
"origin": "null",
"protocol": "sc:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/i",
"search": "",
"hash": ""
},
{
"input": "/i",
"base": "sc://ho/pa",
"href": "sc://ho/i",
"origin": "null",
"protocol": "sc:",
"username": "",
"password": "",
"host": "ho",
"hostname": "ho",
"port": "",
"pathname": "/i",
"search": "",
"hash": ""
},
{
"input": "/i",
"base": "sc:///pa/pa",
"href": "sc:///i",
"origin": "null",
"protocol": "sc:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/i",
"search": "",
"hash": ""
},
{
"input": "?i",
"base": "sc:sd",
"failure": true
},
{
"input": "?i",
"base": "sc:sd/sd",
"failure": true
},
{
"input": "?i",
"base": "sc:/pa/pa",
"href": "sc:/pa/pa?i",
"origin": "null",
"protocol": "sc:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/pa/pa",
"search": "?i",
"hash": ""
},
{
"input": "?i",
"base": "sc://ho/pa",
"href": "sc://ho/pa?i",
"origin": "null",
"protocol": "sc:",
"username": "",
"password": "",
"host": "ho",
"hostname": "ho",
"port": "",
"pathname": "/pa",
"search": "?i",
"hash": ""
},
{
"input": "?i",
"base": "sc:///pa/pa",
"href": "sc:///pa/pa?i",
"origin": "null",
"protocol": "sc:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/pa/pa",
"search": "?i",
"hash": ""
},
{
"input": "#i",
"base": "sc:sd",
"href": "sc:sd#i",
"origin": "null",
"protocol": "sc:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "sd",
"search": "",
"hash": "#i"
},
{
"input": "#i",
"base": "sc:sd/sd",
"href": "sc:sd/sd#i",
"origin": "null",
"protocol": "sc:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "sd/sd",
"search": "",
"hash": "#i"
},
{
"input": "#i",
"base": "sc:/pa/pa",
"href": "sc:/pa/pa#i",
"origin": "null",
"protocol": "sc:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/pa/pa",
"search": "",
"hash": "#i"
},
{
"input": "#i",
"base": "sc://ho/pa",
"href": "sc://ho/pa#i",
"origin": "null",
"protocol": "sc:",
"username": "",
"password": "",
"host": "ho",
"hostname": "ho",
"port": "",
"pathname": "/pa",
"search": "",
"hash": "#i"
},
{
"input": "#i",
"base": "sc:///pa/pa",
"href": "sc:///pa/pa#i",
"origin": "null",
"protocol": "sc:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/pa/pa",
"search": "",
"hash": "#i"
},
"# make sure that relative URL logic works on known typically non-relative schemes too",
{
"input": "about:/../",
"base": "about:blank",
"href": "about:/",
"origin": "null",
"protocol": "about:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "data:/../",
"base": "about:blank",
"href": "data:/",
"origin": "null",
"protocol": "data:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "javascript:/../",
"base": "about:blank",
"href": "javascript:/",
"origin": "null",
"protocol": "javascript:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "mailto:/../",
"base": "about:blank",
"href": "mailto:/",
"origin": "null",
"protocol": "mailto:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
"# unknown schemes and their hosts",
{
"input": "sc://ñ.test/",
"base": "about:blank",
"href": "sc://%C3%B1.test/",
"origin": "null",
"protocol": "sc:",
"username": "",
"password": "",
"host": "%C3%B1.test",
"hostname": "%C3%B1.test",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "sc://\u001F!\"$&'()*+,-.;<=>^_`{|}~/",
"base": "about:blank",
"href": "sc://%1F!\"$&'()*+,-.;<=>^_`{|}~/",
"origin": "null",
"protocol": "sc:",
"username": "",
"password": "",
"host": "%1F!\"$&'()*+,-.;<=>^_`{|}~",
"hostname": "%1F!\"$&'()*+,-.;<=>^_`{|}~",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "sc://\u0000/",
"base": "about:blank",
"failure": true
},
{
"input": "sc:// /",
"base": "about:blank",
"failure": true
},
{
"input": "sc://%/",
"base": "about:blank",
"href": "sc://%/",
"protocol": "sc:",
"username": "",
"password": "",
"host": "%",
"hostname": "%",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "sc://@/",
"base": "about:blank",
"failure": true
},
{
"input": "sc://te@s:t@/",
"base": "about:blank",
"failure": true
},
{
"input": "sc://:/",
"base": "about:blank",
"failure": true
},
{
"input": "sc://:12/",
"base": "about:blank",
"failure": true
},
{
"input": "sc://[/",
"base": "about:blank",
"failure": true
},
{
"input": "sc://\\/",
"base": "about:blank",
"failure": true
},
{
"input": "sc://]/",
"base": "about:blank",
"failure": true
},
{
"input": "x",
"base": "sc://ñ",
"href": "sc://%C3%B1/x",
"origin": "null",
"protocol": "sc:",
"username": "",
"password": "",
"host": "%C3%B1",
"hostname": "%C3%B1",
"port": "",
"pathname": "/x",
"search": "",
"hash": ""
},
"# unknown schemes and backslashes",
{
"input": "sc:\\../",
"base": "about:blank",
"href": "sc:\\../",
"origin": "null",
"protocol": "sc:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "\\../",
"search": "",
"hash": ""
},
"# unknown scheme with path looking like a password",
{
"input": "sc::a@example.net",
"base": "about:blank",
"href": "sc::a@example.net",
"origin": "null",
"protocol": "sc:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": ":a@example.net",
"search": "",
"hash": ""
},
"# unknown scheme with bogus percent-encoding",
{
"input": "wow:%NBD",
"base": "about:blank",
"href": "wow:%NBD",
"origin": "null",
"protocol": "wow:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "%NBD",
"search": "",
"hash": ""
},
{
"input": "wow:%1G",
"base": "about:blank",
"href": "wow:%1G",
"origin": "null",
"protocol": "wow:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "%1G",
"search": "",
"hash": ""
},
"# Hosts and percent-encoding",
{
"input": "ftp://example.com%80/",
"base": "about:blank",
"failure": true
},
{
"input": "ftp://example.com%A0/",
"base": "about:blank",
"failure": true
},
{
"input": "https://example.com%80/",
"base": "about:blank",
"failure": true
},
{
"input": "https://example.com%A0/",
"base": "about:blank",
"failure": true
},
{
"input": "ftp://%e2%98%83",
"base": "about:blank",
"href": "ftp://xn--n3h/",
"origin": "ftp://xn--n3h",
"protocol": "ftp:",
"username": "",
"password": "",
"host": "xn--n3h",
"hostname": "xn--n3h",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "https://%e2%98%83",
"base": "about:blank",
"href": "https://xn--n3h/",
"origin": "https://xn--n3h",
"protocol": "https:",
"username": "",
"password": "",
"host": "xn--n3h",
"hostname": "xn--n3h",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
"# tests from jsdom/whatwg-url designed for code coverage",
{
"input": "http://127.0.0.1:10100/relative_import.html",
"base": "about:blank",
"href": "http://127.0.0.1:10100/relative_import.html",
"origin": "http://127.0.0.1:10100",
"protocol": "http:",
"username": "",
"password": "",
"host": "127.0.0.1:10100",
"hostname": "127.0.0.1",
"port": "10100",
"pathname": "/relative_import.html",
"search": "",
"hash": ""
},
{
"input": "http://facebook.com/?foo=%7B%22abc%22",
"base": "about:blank",
"href": "http://facebook.com/?foo=%7B%22abc%22",
"origin": "http://facebook.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "facebook.com",
"hostname": "facebook.com",
"port": "",
"pathname": "/",
"search": "?foo=%7B%22abc%22",
"hash": ""
},
{
"input": "https://localhost:3000/jqueryui@1.2.3",
"base": "about:blank",
"href": "https://localhost:3000/jqueryui@1.2.3",
"origin": "https://localhost:3000",
"protocol": "https:",
"username": "",
"password": "",
"host": "localhost:3000",
"hostname": "localhost",
"port": "3000",
"pathname": "/jqueryui@1.2.3",
"search": "",
"hash": ""
},
"# tab/LF/CR",
{
"input": "h\tt\nt\rp://h\to\ns\rt:9\t0\n0\r0/p\ta\nt\rh?q\tu\ne\rry#f\tr\na\rg",
"base": "about:blank",
"href": "http://host:9000/path?query#frag",
"origin": "http://host:9000",
"protocol": "http:",
"username": "",
"password": "",
"host": "host:9000",
"hostname": "host",
"port": "9000",
"pathname": "/path",
"search": "?query",
"hash": "#frag"
},
"# Stringification of URL.searchParams",
{
"input": "?a=b&c=d",
"base": "http://example.org/foo/bar",
"href": "http://example.org/foo/bar?a=b&c=d",
"origin": "http://example.org",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.org",
"hostname": "example.org",
"port": "",
"pathname": "/foo/bar",
"search": "?a=b&c=d",
"searchParams": "a=b&c=d",
"hash": ""
},
{
"input": "??a=b&c=d",
"base": "http://example.org/foo/bar",
"href": "http://example.org/foo/bar??a=b&c=d",
"origin": "http://example.org",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.org",
"hostname": "example.org",
"port": "",
"pathname": "/foo/bar",
"search": "??a=b&c=d",
"searchParams": "%3Fa=b&c=d",
"hash": ""
},
"# Scheme only",
{
"input": "http:",
"base": "http://example.org/foo/bar",
"href": "http://example.org/foo/bar",
"origin": "http://example.org",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.org",
"hostname": "example.org",
"port": "",
"pathname": "/foo/bar",
"search": "",
"searchParams": "",
"hash": ""
},
{
"input": "http:",
"base": "https://example.org/foo/bar",
"failure": true
},
{
"input": "sc:",
"base": "https://example.org/foo/bar",
"href": "sc:",
"origin": "null",
"protocol": "sc:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "",
"search": "",
"searchParams": "",
"hash": ""
},
"# Percent encoding of fragments",
{
"input": "http://foo.bar/baz?qux#foo\bbar",
"base": "about:blank",
"href": "http://foo.bar/baz?qux#foo%08bar",
"origin": "http://foo.bar",
"protocol": "http:",
"username": "",
"password": "",
"host": "foo.bar",
"hostname": "foo.bar",
"port": "",
"pathname": "/baz",
"search": "?qux",
"searchParams": "qux=",
"hash": "#foo%08bar"
},
{
"input": "http://foo.bar/baz?qux#foo\"bar",
"base": "about:blank",
"href": "http://foo.bar/baz?qux#foo%22bar",
"origin": "http://foo.bar",
"protocol": "http:",
"username": "",
"password": "",
"host": "foo.bar",
"hostname": "foo.bar",
"port": "",
"pathname": "/baz",
"search": "?qux",
"searchParams": "qux=",
"hash": "#foo%22bar"
},
{
"input": "http://foo.bar/baz?qux#foo<bar",
"base": "about:blank",
"href": "http://foo.bar/baz?qux#foo%3Cbar",
"origin": "http://foo.bar",
"protocol": "http:",
"username": "",
"password": "",
"host": "foo.bar",
"hostname": "foo.bar",
"port": "",
"pathname": "/baz",
"search": "?qux",
"searchParams": "qux=",
"hash": "#foo%3Cbar"
},
{
"input": "http://foo.bar/baz?qux#foo>bar",
"base": "about:blank",
"href": "http://foo.bar/baz?qux#foo%3Ebar",
"origin": "http://foo.bar",
"protocol": "http:",
"username": "",
"password": "",
"host": "foo.bar",
"hostname": "foo.bar",
"port": "",
"pathname": "/baz",
"search": "?qux",
"searchParams": "qux=",
"hash": "#foo%3Ebar"
},
{
"input": "http://foo.bar/baz?qux#foo`bar",
"base": "about:blank",
"href": "http://foo.bar/baz?qux#foo%60bar",
"origin": "http://foo.bar",
"protocol": "http:",
"username": "",
"password": "",
"host": "foo.bar",
"hostname": "foo.bar",
"port": "",
"pathname": "/baz",
"search": "?qux",
"searchParams": "qux=",
"hash": "#foo%60bar"
},
"# IPv4 parsing (via https://github.com/nodejs/node/pull/10317)",
{
"input": "http://192.168.257",
"base": "http://other.com/",
"href": "http://192.168.1.1/",
"origin": "http://192.168.1.1",
"protocol": "http:",
"username": "",
"password": "",
"host": "192.168.1.1",
"hostname": "192.168.1.1",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "http://192.168.257.com",
"base": "http://other.com/",
"href": "http://192.168.257.com/",
"origin": "http://192.168.257.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "192.168.257.com",
"hostname": "192.168.257.com",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "http://256",
"base": "http://other.com/",
"href": "http://0.0.1.0/",
"origin": "http://0.0.1.0",
"protocol": "http:",
"username": "",
"password": "",
"host": "0.0.1.0",
"hostname": "0.0.1.0",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "http://256.com",
"base": "http://other.com/",
"href": "http://256.com/",
"origin": "http://256.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "256.com",
"hostname": "256.com",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "http://999999999",
"base": "http://other.com/",
"href": "http://59.154.201.255/",
"origin": "http://59.154.201.255",
"protocol": "http:",
"username": "",
"password": "",
"host": "59.154.201.255",
"hostname": "59.154.201.255",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "http://999999999.com",
"base": "http://other.com/",
"href": "http://999999999.com/",
"origin": "http://999999999.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "999999999.com",
"hostname": "999999999.com",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "http://10000000000",
"base": "http://other.com/",
"failure": true
},
{
"input": "http://10000000000.com",
"base": "http://other.com/",
"href": "http://10000000000.com/",
"origin": "http://10000000000.com",
"protocol": "http:",
"username": "",
"password": "",
"host": "10000000000.com",
"hostname": "10000000000.com",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "http://4294967295",
"base": "http://other.com/",
"href": "http://255.255.255.255/",
"origin": "http://255.255.255.255",
"protocol": "http:",
"username": "",
"password": "",
"host": "255.255.255.255",
"hostname": "255.255.255.255",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "http://4294967296",
"base": "http://other.com/",
"failure": true
},
{
"input": "http://0xffffffff",
"base": "http://other.com/",
"href": "http://255.255.255.255/",
"origin": "http://255.255.255.255",
"protocol": "http:",
"username": "",
"password": "",
"host": "255.255.255.255",
"hostname": "255.255.255.255",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "http://0xffffffff1",
"base": "http://other.com/",
"failure": true
},
{
"input": "http://256.256.256.256",
"base": "http://other.com/",
"failure": true
},
{
"input": "http://256.256.256.256.256",
"base": "http://other.com/",
"href": "http://256.256.256.256.256/",
"origin": "http://256.256.256.256.256",
"protocol": "http:",
"username": "",
"password": "",
"host": "256.256.256.256.256",
"hostname": "256.256.256.256.256",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "https://0x.0x.0",
"base": "about:blank",
"href": "https://0.0.0.0/",
"origin": "https://0.0.0.0",
"protocol": "https:",
"username": "",
"password": "",
"host": "0.0.0.0",
"hostname": "0.0.0.0",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
"More IPv4 parsing (via https://github.com/jsdom/whatwg-url/issues/92)",
{
"input": "https://0x100000000/test",
"base": "about:blank",
"failure": true
},
{
"input": "https://256.0.0.1/test",
"base": "about:blank",
"failure": true
},
"# file URLs containing percent-encoded Windows drive letters (shouldn't work)",
{
"input": "file:///C%3A/",
"base": "about:blank",
"href": "file:///C%3A/",
"protocol": "file:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/C%3A/",
"search": "",
"hash": ""
},
{
"input": "file:///C%7C/",
"base": "about:blank",
"href": "file:///C%7C/",
"protocol": "file:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/C%7C/",
"search": "",
"hash": ""
},
"# file URLs relative to other file URLs (via https://github.com/jsdom/whatwg-url/pull/60)",
{
"input": "pix/submit.gif",
"base": "file:///C:/Users/Domenic/Dropbox/GitHub/tmpvar/jsdom/test/level2/html/files/anchor.html",
"href": "file:///C:/Users/Domenic/Dropbox/GitHub/tmpvar/jsdom/test/level2/html/files/pix/submit.gif",
"protocol": "file:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/C:/Users/Domenic/Dropbox/GitHub/tmpvar/jsdom/test/level2/html/files/pix/submit.gif",
"search": "",
"hash": ""
},
{
"input": "..",
"base": "file:///C:/",
"href": "file:///C:/",
"protocol": "file:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/C:/",
"search": "",
"hash": ""
},
{
"input": "..",
"base": "file:///",
"href": "file:///",
"protocol": "file:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
"# More file URL tests by zcorpan and annevk",
{
"input": "/",
"base": "file:///C:/a/b",
"href": "file:///C:/",
"protocol": "file:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/C:/",
"search": "",
"hash": ""
},
{
"input": "//d:",
"base": "file:///C:/a/b",
"href": "file:///d:",
"protocol": "file:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/d:",
"search": "",
"hash": ""
},
{
"input": "//d:/..",
"base": "file:///C:/a/b",
"href": "file:///d:/",
"protocol": "file:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/d:/",
"search": "",
"hash": ""
},
{
"input": "..",
"base": "file:///ab:/",
"href": "file:///",
"protocol": "file:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "..",
"base": "file:///1:/",
"href": "file:///",
"protocol": "file:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "",
"base": "file:///test?test#test",
"href": "file:///test?test",
"protocol": "file:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/test",
"search": "?test",
"hash": ""
},
{
"input": "file:",
"base": "file:///test?test#test",
"href": "file:///test?test",
"protocol": "file:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/test",
"search": "?test",
"hash": ""
},
{
"input": "?x",
"base": "file:///test?test#test",
"href": "file:///test?x",
"protocol": "file:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/test",
"search": "?x",
"hash": ""
},
{
"input": "file:?x",
"base": "file:///test?test#test",
"href": "file:///test?x",
"protocol": "file:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/test",
"search": "?x",
"hash": ""
},
{
"input": "#x",
"base": "file:///test?test#test",
"href": "file:///test?test#x",
"protocol": "file:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/test",
"search": "?test",
"hash": "#x"
},
{
"input": "file:#x",
"base": "file:///test?test#test",
"href": "file:///test?test#x",
"protocol": "file:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/test",
"search": "?test",
"hash": "#x"
},
"# File URLs and many (back)slashes",
{
"input": "file:\\\\//",
"base": "about:blank",
"href": "file:///",
"protocol": "file:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "file:\\\\\\\\",
"base": "about:blank",
"href": "file:///",
"protocol": "file:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "file:\\\\\\\\?fox",
"base": "about:blank",
"href": "file:///?fox",
"protocol": "file:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/",
"search": "?fox",
"hash": ""
},
{
"input": "file:\\\\\\\\#guppy",
"base": "about:blank",
"href": "file:///#guppy",
"protocol": "file:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/",
"search": "",
"hash": "#guppy"
},
{
"input": "file://spider///",
"base": "about:blank",
"href": "file://spider/",
"protocol": "file:",
"username": "",
"password": "",
"host": "spider",
"hostname": "spider",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "file:\\\\localhost//",
"base": "about:blank",
"href": "file:///",
"protocol": "file:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "file:///localhost//cat",
"base": "about:blank",
"href": "file:///localhost//cat",
"protocol": "file:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/localhost//cat",
"search": "",
"hash": ""
},
{
"input": "file://\\/localhost//cat",
"base": "about:blank",
"href": "file:///localhost//cat",
"protocol": "file:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/localhost//cat",
"search": "",
"hash": ""
},
{
"input": "file://localhost//a//../..//",
"base": "about:blank",
"href": "file:///",
"protocol": "file:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "/////mouse",
"base": "file:///elephant",
"href": "file:///mouse",
"protocol": "file:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/mouse",
"search": "",
"hash": ""
},
{
"input": "\\//pig",
"base": "file://lion/",
"href": "file:///pig",
"protocol": "file:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/pig",
"search": "",
"hash": ""
},
{
"input": "\\/localhost//pig",
"base": "file://lion/",
"href": "file:///pig",
"protocol": "file:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/pig",
"search": "",
"hash": ""
},
{
"input": "//localhost//pig",
"base": "file://lion/",
"href": "file:///pig",
"protocol": "file:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/pig",
"search": "",
"hash": ""
},
{
"input": "/..//localhost//pig",
"base": "file://lion/",
"href": "file://lion/localhost//pig",
"protocol": "file:",
"username": "",
"password": "",
"host": "lion",
"hostname": "lion",
"port": "",
"pathname": "/localhost//pig",
"search": "",
"hash": ""
},
{
"input": "file://",
"base": "file://ape/",
"href": "file:///",
"protocol": "file:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
"# File URLs with non-empty hosts",
{
"input": "/rooibos",
"base": "file://tea/",
"href": "file://tea/rooibos",
"protocol": "file:",
"username": "",
"password": "",
"host": "tea",
"hostname": "tea",
"port": "",
"pathname": "/rooibos",
"search": "",
"hash": ""
},
{
"input": "/?chai",
"base": "file://tea/",
"href": "file://tea/?chai",
"protocol": "file:",
"username": "",
"password": "",
"host": "tea",
"hostname": "tea",
"port": "",
"pathname": "/",
"search": "?chai",
"hash": ""
},
"# Windows drive letter handling with the 'file:' base URL",
{
"input": "C|",
"base": "file://host/dir/file",
"href": "file:///C:",
"protocol": "file:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/C:",
"search": "",
"hash": ""
},
{
"input": "C|#",
"base": "file://host/dir/file",
"href": "file:///C:#",
"protocol": "file:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/C:",
"search": "",
"hash": ""
},
{
"input": "C|?",
"base": "file://host/dir/file",
"href": "file:///C:?",
"protocol": "file:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/C:",
"search": "",
"hash": ""
},
{
"input": "C|/",
"base": "file://host/dir/file",
"href": "file:///C:/",
"protocol": "file:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/C:/",
"search": "",
"hash": ""
},
{
"input": "C|\n/",
"base": "file://host/dir/file",
"href": "file:///C:/",
"protocol": "file:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/C:/",
"search": "",
"hash": ""
},
{
"input": "C|\\",
"base": "file://host/dir/file",
"href": "file:///C:/",
"protocol": "file:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/C:/",
"search": "",
"hash": ""
},
{
"input": "C",
"base": "file://host/dir/file",
"href": "file://host/dir/C",
"protocol": "file:",
"username": "",
"password": "",
"host": "host",
"hostname": "host",
"port": "",
"pathname": "/dir/C",
"search": "",
"hash": ""
},
{
"input": "C|a",
"base": "file://host/dir/file",
"href": "file://host/dir/C|a",
"protocol": "file:",
"username": "",
"password": "",
"host": "host",
"hostname": "host",
"port": "",
"pathname": "/dir/C|a",
"search": "",
"hash": ""
},
"# Windows drive letter quirk in the file slash state",
{
"input": "/c:/foo/bar",
"base": "file:///c:/baz/qux",
"href": "file:///c:/foo/bar",
"protocol": "file:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/c:/foo/bar",
"search": "",
"hash": ""
},
{
"input": "/c|/foo/bar",
"base": "file:///c:/baz/qux",
"href": "file:///c:/foo/bar",
"protocol": "file:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/c:/foo/bar",
"search": "",
"hash": ""
},
{
"input": "file:\\c:\\foo\\bar",
"base": "file:///c:/baz/qux",
"href": "file:///c:/foo/bar",
"protocol": "file:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/c:/foo/bar",
"search": "",
"hash": ""
},
{
"input": "/c:/foo/bar",
"base": "file://host/path",
"href": "file:///c:/foo/bar",
"protocol": "file:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/c:/foo/bar",
"search": "",
"hash": ""
},
"# Windows drive letter quirk with not empty host",
{
"input": "file://example.net/C:/",
"base": "about:blank",
"href": "file:///C:/",
"protocol": "file:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/C:/",
"search": "",
"hash": ""
},
{
"input": "file://1.2.3.4/C:/",
"base": "about:blank",
"href": "file:///C:/",
"protocol": "file:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/C:/",
"search": "",
"hash": ""
},
{
"input": "file://[1::8]/C:/",
"base": "about:blank",
"href": "file:///C:/",
"protocol": "file:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/C:/",
"search": "",
"hash": ""
},
"# Windows drive letter quirk (no host)",
{
"input": "file:/C|/",
"base": "about:blank",
"href": "file:///C:/",
"protocol": "file:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/C:/",
"search": "",
"hash": ""
},
{
"input": "file://C|/",
"base": "about:blank",
"href": "file:///C:/",
"protocol": "file:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/C:/",
"search": "",
"hash": ""
},
"# file URLs without base URL by Rimas Misevičius",
{
"input": "file:",
"base": "about:blank",
"href": "file:///",
"protocol": "file:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "file:?q=v",
"base": "about:blank",
"href": "file:///?q=v",
"protocol": "file:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/",
"search": "?q=v",
"hash": ""
},
{
"input": "file:#frag",
"base": "about:blank",
"href": "file:///#frag",
"protocol": "file:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/",
"search": "",
"hash": "#frag"
},
"# IPv6 tests",
{
"input": "http://[1:0::]",
"base": "http://example.net/",
"href": "http://[1::]/",
"origin": "http://[1::]",
"protocol": "http:",
"username": "",
"password": "",
"host": "[1::]",
"hostname": "[1::]",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "http://[0:1:2:3:4:5:6:7:8]",
"base": "http://example.net/",
"failure": true
},
{
"input": "https://[0::0::0]",
"base": "about:blank",
"failure": true
},
{
"input": "https://[0:.0]",
"base": "about:blank",
"failure": true
},
{
"input": "https://[0:0:]",
"base": "about:blank",
"failure": true
},
{
"input": "https://[0:1:2:3:4:5:6:7.0.0.0.1]",
"base": "about:blank",
"failure": true
},
{
"input": "https://[0:1.00.0.0.0]",
"base": "about:blank",
"failure": true
},
{
"input": "https://[0:1.290.0.0.0]",
"base": "about:blank",
"failure": true
},
{
"input": "https://[0:1.23.23]",
"base": "about:blank",
"failure": true
},
"# Empty host",
{
"input": "http://?",
"base": "about:blank",
"failure": true
},
{
"input": "http://#",
"base": "about:blank",
"failure": true
},
"Port overflow (2^32 + 81)",
{
"input": "http://f:4294967377/c",
"base": "http://example.org/",
"failure": true
},
"Port overflow (2^64 + 81)",
{
"input": "http://f:18446744073709551697/c",
"base": "http://example.org/",
"failure": true
},
"Port overflow (2^128 + 81)",
{
"input": "http://f:340282366920938463463374607431768211537/c",
"base": "http://example.org/",
"failure": true
},
"# Non-special-URL path tests",
{
"input": "sc://ñ",
"base": "about:blank",
"href": "sc://%C3%B1",
"origin": "null",
"protocol": "sc:",
"username": "",
"password": "",
"host": "%C3%B1",
"hostname": "%C3%B1",
"port": "",
"pathname": "",
"search": "",
"hash": ""
},
{
"input": "sc://ñ?x",
"base": "about:blank",
"href": "sc://%C3%B1?x",
"origin": "null",
"protocol": "sc:",
"username": "",
"password": "",
"host": "%C3%B1",
"hostname": "%C3%B1",
"port": "",
"pathname": "",
"search": "?x",
"hash": ""
},
{
"input": "sc://ñ#x",
"base": "about:blank",
"href": "sc://%C3%B1#x",
"origin": "null",
"protocol": "sc:",
"username": "",
"password": "",
"host": "%C3%B1",
"hostname": "%C3%B1",
"port": "",
"pathname": "",
"search": "",
"hash": "#x"
},
{
"input": "#x",
"base": "sc://ñ",
"href": "sc://%C3%B1#x",
"origin": "null",
"protocol": "sc:",
"username": "",
"password": "",
"host": "%C3%B1",
"hostname": "%C3%B1",
"port": "",
"pathname": "",
"search": "",
"hash": "#x"
},
{
"input": "?x",
"base": "sc://ñ",
"href": "sc://%C3%B1?x",
"origin": "null",
"protocol": "sc:",
"username": "",
"password": "",
"host": "%C3%B1",
"hostname": "%C3%B1",
"port": "",
"pathname": "",
"search": "?x",
"hash": ""
},
{
"input": "sc://?",
"base": "about:blank",
"href": "sc://?",
"protocol": "sc:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "",
"search": "",
"hash": ""
},
{
"input": "sc://#",
"base": "about:blank",
"href": "sc://#",
"protocol": "sc:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "",
"search": "",
"hash": ""
},
{
"input": "///",
"base": "sc://x/",
"href": "sc:///",
"protocol": "sc:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "////",
"base": "sc://x/",
"href": "sc:////",
"protocol": "sc:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "//",
"search": "",
"hash": ""
},
{
"input": "////x/",
"base": "sc://x/",
"href": "sc:////x/",
"protocol": "sc:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "//x/",
"search": "",
"hash": ""
},
{
"input": "tftp://foobar.com/someconfig;mode=netascii",
"base": "about:blank",
"href": "tftp://foobar.com/someconfig;mode=netascii",
"origin": "null",
"protocol": "tftp:",
"username": "",
"password": "",
"host": "foobar.com",
"hostname": "foobar.com",
"port": "",
"pathname": "/someconfig;mode=netascii",
"search": "",
"hash": ""
},
{
"input": "telnet://user:pass@foobar.com:23/",
"base": "about:blank",
"href": "telnet://user:pass@foobar.com:23/",
"origin": "null",
"protocol": "telnet:",
"username": "user",
"password": "pass",
"host": "foobar.com:23",
"hostname": "foobar.com",
"port": "23",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "ut2004://10.10.10.10:7777/Index.ut2",
"base": "about:blank",
"href": "ut2004://10.10.10.10:7777/Index.ut2",
"origin": "null",
"protocol": "ut2004:",
"username": "",
"password": "",
"host": "10.10.10.10:7777",
"hostname": "10.10.10.10",
"port": "7777",
"pathname": "/Index.ut2",
"search": "",
"hash": ""
},
{
"input": "redis://foo:bar@somehost:6379/0?baz=bam&qux=baz",
"base": "about:blank",
"href": "redis://foo:bar@somehost:6379/0?baz=bam&qux=baz",
"origin": "null",
"protocol": "redis:",
"username": "foo",
"password": "bar",
"host": "somehost:6379",
"hostname": "somehost",
"port": "6379",
"pathname": "/0",
"search": "?baz=bam&qux=baz",
"hash": ""
},
{
"input": "rsync://foo@host:911/sup",
"base": "about:blank",
"href": "rsync://foo@host:911/sup",
"origin": "null",
"protocol": "rsync:",
"username": "foo",
"password": "",
"host": "host:911",
"hostname": "host",
"port": "911",
"pathname": "/sup",
"search": "",
"hash": ""
},
{
"input": "git://github.com/foo/bar.git",
"base": "about:blank",
"href": "git://github.com/foo/bar.git",
"origin": "null",
"protocol": "git:",
"username": "",
"password": "",
"host": "github.com",
"hostname": "github.com",
"port": "",
"pathname": "/foo/bar.git",
"search": "",
"hash": ""
},
{
"input": "irc://myserver.com:6999/channel?passwd",
"base": "about:blank",
"href": "irc://myserver.com:6999/channel?passwd",
"origin": "null",
"protocol": "irc:",
"username": "",
"password": "",
"host": "myserver.com:6999",
"hostname": "myserver.com",
"port": "6999",
"pathname": "/channel",
"search": "?passwd",
"hash": ""
},
{
"input": "dns://fw.example.org:9999/foo.bar.org?type=TXT",
"base": "about:blank",
"href": "dns://fw.example.org:9999/foo.bar.org?type=TXT",
"origin": "null",
"protocol": "dns:",
"username": "",
"password": "",
"host": "fw.example.org:9999",
"hostname": "fw.example.org",
"port": "9999",
"pathname": "/foo.bar.org",
"search": "?type=TXT",
"hash": ""
},
{
"input": "ldap://localhost:389/ou=People,o=JNDITutorial",
"base": "about:blank",
"href": "ldap://localhost:389/ou=People,o=JNDITutorial",
"origin": "null",
"protocol": "ldap:",
"username": "",
"password": "",
"host": "localhost:389",
"hostname": "localhost",
"port": "389",
"pathname": "/ou=People,o=JNDITutorial",
"search": "",
"hash": ""
},
{
"input": "git+https://github.com/foo/bar",
"base": "about:blank",
"href": "git+https://github.com/foo/bar",
"origin": "null",
"protocol": "git+https:",
"username": "",
"password": "",
"host": "github.com",
"hostname": "github.com",
"port": "",
"pathname": "/foo/bar",
"search": "",
"hash": ""
},
{
"input": "urn:ietf:rfc:2648",
"base": "about:blank",
"href": "urn:ietf:rfc:2648",
"origin": "null",
"protocol": "urn:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "ietf:rfc:2648",
"search": "",
"hash": ""
},
{
"input": "tag:joe@example.org,2001:foo/bar",
"base": "about:blank",
"href": "tag:joe@example.org,2001:foo/bar",
"origin": "null",
"protocol": "tag:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "joe@example.org,2001:foo/bar",
"search": "",
"hash": ""
},
"# percent encoded hosts in non-special-URLs",
{
"input": "non-special://%E2%80%A0/",
"base": "about:blank",
"href": "non-special://%E2%80%A0/",
"protocol": "non-special:",
"username": "",
"password": "",
"host": "%E2%80%A0",
"hostname": "%E2%80%A0",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "non-special://H%4fSt/path",
"base": "about:blank",
"href": "non-special://H%4fSt/path",
"protocol": "non-special:",
"username": "",
"password": "",
"host": "H%4fSt",
"hostname": "H%4fSt",
"port": "",
"pathname": "/path",
"search": "",
"hash": ""
},
"# IPv6 in non-special-URLs",
{
"input": "non-special://[1:2:0:0:5:0:0:0]/",
"base": "about:blank",
"href": "non-special://[1:2:0:0:5::]/",
"protocol": "non-special:",
"username": "",
"password": "",
"host": "[1:2:0:0:5::]",
"hostname": "[1:2:0:0:5::]",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "non-special://[1:2:0:0:0:0:0:3]/",
"base": "about:blank",
"href": "non-special://[1:2::3]/",
"protocol": "non-special:",
"username": "",
"password": "",
"host": "[1:2::3]",
"hostname": "[1:2::3]",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "non-special://[1:2::3]:80/",
"base": "about:blank",
"href": "non-special://[1:2::3]:80/",
"protocol": "non-special:",
"username": "",
"password": "",
"host": "[1:2::3]:80",
"hostname": "[1:2::3]",
"port": "80",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "non-special://[:80/",
"base": "about:blank",
"failure": true
},
{
"input": "blob:https://example.com:443/",
"base": "about:blank",
"href": "blob:https://example.com:443/",
"protocol": "blob:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "https://example.com:443/",
"search": "",
"hash": ""
},
{
"input": "blob:d3958f5c-0777-0845-9dcf-2cb28783acaf",
"base": "about:blank",
"href": "blob:d3958f5c-0777-0845-9dcf-2cb28783acaf",
"protocol": "blob:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "d3958f5c-0777-0845-9dcf-2cb28783acaf",
"search": "",
"hash": ""
},
"Invalid IPv4 radix digits",
{
"input": "http://0177.0.0.0189",
"base": "about:blank",
"href": "http://0177.0.0.0189/",
"protocol": "http:",
"username": "",
"password": "",
"host": "0177.0.0.0189",
"hostname": "0177.0.0.0189",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "http://0x7f.0.0.0x7g",
"base": "about:blank",
"href": "http://0x7f.0.0.0x7g/",
"protocol": "http:",
"username": "",
"password": "",
"host": "0x7f.0.0.0x7g",
"hostname": "0x7f.0.0.0x7g",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "http://0X7F.0.0.0X7G",
"base": "about:blank",
"href": "http://0x7f.0.0.0x7g/",
"protocol": "http:",
"username": "",
"password": "",
"host": "0x7f.0.0.0x7g",
"hostname": "0x7f.0.0.0x7g",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
"Invalid IPv4 portion of IPv6 address",
{
"input": "http://[::127.0.0.0.1]",
"base": "about:blank",
"failure": true
},
"Uncompressed IPv6 addresses with 0",
{
"input": "http://[0:1:0:1:0:1:0:1]",
"base": "about:blank",
"href": "http://[0:1:0:1:0:1:0:1]/",
"protocol": "http:",
"username": "",
"password": "",
"host": "[0:1:0:1:0:1:0:1]",
"hostname": "[0:1:0:1:0:1:0:1]",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
{
"input": "http://[1:0:1:0:1:0:1:0]",
"base": "about:blank",
"href": "http://[1:0:1:0:1:0:1:0]/",
"protocol": "http:",
"username": "",
"password": "",
"host": "[1:0:1:0:1:0:1:0]",
"hostname": "[1:0:1:0:1:0:1:0]",
"port": "",
"pathname": "/",
"search": "",
"hash": ""
},
"Percent-encoded query and fragment",
{
"input": "http://example.org/test?\u0022",
"base": "about:blank",
"href": "http://example.org/test?%22",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.org",
"hostname": "example.org",
"port": "",
"pathname": "/test",
"search": "?%22",
"hash": ""
},
{
"input": "http://example.org/test?\u0023",
"base": "about:blank",
"href": "http://example.org/test?#",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.org",
"hostname": "example.org",
"port": "",
"pathname": "/test",
"search": "",
"hash": ""
},
{
"input": "http://example.org/test?\u003C",
"base": "about:blank",
"href": "http://example.org/test?%3C",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.org",
"hostname": "example.org",
"port": "",
"pathname": "/test",
"search": "?%3C",
"hash": ""
},
{
"input": "http://example.org/test?\u003E",
"base": "about:blank",
"href": "http://example.org/test?%3E",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.org",
"hostname": "example.org",
"port": "",
"pathname": "/test",
"search": "?%3E",
"hash": ""
},
{
"input": "http://example.org/test?\u2323",
"base": "about:blank",
"href": "http://example.org/test?%E2%8C%A3",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.org",
"hostname": "example.org",
"port": "",
"pathname": "/test",
"search": "?%E2%8C%A3",
"hash": ""
},
{
"input": "http://example.org/test?%23%23",
"base": "about:blank",
"href": "http://example.org/test?%23%23",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.org",
"hostname": "example.org",
"port": "",
"pathname": "/test",
"search": "?%23%23",
"hash": ""
},
{
"input": "http://example.org/test?%GH",
"base": "about:blank",
"href": "http://example.org/test?%GH",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.org",
"hostname": "example.org",
"port": "",
"pathname": "/test",
"search": "?%GH",
"hash": ""
},
{
"input": "http://example.org/test?a#%EF",
"base": "about:blank",
"href": "http://example.org/test?a#%EF",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.org",
"hostname": "example.org",
"port": "",
"pathname": "/test",
"search": "?a",
"hash": "#%EF"
},
{
"input": "http://example.org/test?a#%GH",
"base": "about:blank",
"href": "http://example.org/test?a#%GH",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.org",
"hostname": "example.org",
"port": "",
"pathname": "/test",
"search": "?a",
"hash": "#%GH"
},
"Bad bases",
{
"input": "test-a.html",
"base": "a",
"failure": true
},
{
"input": "test-a-slash.html",
"base": "a/",
"failure": true
},
{
"input": "test-a-slash-slash.html",
"base": "a//",
"failure": true
},
{
"input": "test-a-colon.html",
"base": "a:",
"failure": true
},
{
"input": "test-a-colon-slash.html",
"base": "a:/",
"href": "a:/test-a-colon-slash.html",
"protocol": "a:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/test-a-colon-slash.html",
"search": "",
"hash": ""
},
{
"input": "test-a-colon-slash-slash.html",
"base": "a://",
"href": "a:///test-a-colon-slash-slash.html",
"protocol": "a:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/test-a-colon-slash-slash.html",
"search": "",
"hash": ""
},
{
"input": "test-a-colon-b.html",
"base": "a:b",
"failure": true
},
{
"input": "test-a-colon-slash-b.html",
"base": "a:/b",
"href": "a:/test-a-colon-slash-b.html",
"protocol": "a:",
"username": "",
"password": "",
"host": "",
"hostname": "",
"port": "",
"pathname": "/test-a-colon-slash-b.html",
"search": "",
"hash": ""
},
{
"input": "test-a-colon-slash-slash-b.html",
"base": "a://b",
"href": "a://b/test-a-colon-slash-slash-b.html",
"protocol": "a:",
"username": "",
"password": "",
"host": "b",
"hostname": "b",
"port": "",
"pathname": "/test-a-colon-slash-slash-b.html",
"search": "",
"hash": ""
},
"Null code point in fragment",
{
"input": "http://example.org/test?a#b\u0000c",
"base": "about:blank",
"href": "http://example.org/test?a#bc",
"protocol": "http:",
"username": "",
"password": "",
"host": "example.org",
"hostname": "example.org",
"port": "",
"pathname": "/test",
"search": "?a",
"hash": "#bc"
}
]
|
const util = require('util');
const moment = require('moment');
const mysql = require('mysql2');
const Base = require('db-migrate-base');
const Promise = require('bluebird');
let log;
let type;
let internals = {};
const MysqlDriver = Base.extend({
init: function (connection) {
this._escapeDDL = '`';
this._escapeString = "'";
this._super(internals);
this.connection = connection;
},
startMigration: function (cb) {
const self = this;
if (!internals.notransactions) {
return this.runSql('SET AUTOCOMMIT=0;')
.then(function () {
return self.runSql('START TRANSACTION;');
})
.nodeify(cb);
} else return Promise.resolve().nodeify(cb);
},
endMigration: function (cb) {
if (!internals.notransactions) {
return this.runSql('COMMIT;').nodeify(cb);
} else return Promise.resolve(null).nodeify(cb);
},
mapDataType: function (spec) {
let len;
switch (spec.type) {
case type.TEXT:
len = parseInt(spec.length, 10) || 1000;
if (len > 16777216) {
return 'LONGTEXT';
}
if (len > 65536) {
return 'MEDIUMTEXT';
}
if (len > 256) {
return 'TEXT';
}
return 'TINYTEXT';
case type.DATE_TIME:
return 'DATETIME';
case type.BLOB:
len = parseInt(spec.length, 10) || 1000;
if (len > 16777216) {
return 'LONGBLOB';
}
if (len > 65536) {
return 'MEDIUMBLOB';
}
if (len > 256) {
return 'BLOB';
}
return 'TINYBLOB';
case type.BOOLEAN:
return 'TINYINT(1)';
case 'json':
return 'JSON';
}
return this._super(spec.type);
},
createColumnDef: function (name, spec, options, tableName) {
const escapedName = util.format('`%s`', name);
const t = this.mapDataType(spec);
let len;
if (spec.type === type.DECIMAL) {
if (spec.precision && spec.scale) {
len = '(' + spec.precision + ',' + spec.scale + ')';
}
} else if (spec.type !== type.TEXT && spec.type !== type.BLOB) {
len = spec.length ? util.format('(%s)', spec.length) : '';
if (t === 'VARCHAR' && len === '') {
len = '(255)';
}
}
const constraint = this.createColumnConstraint(
spec,
options,
tableName,
name
);
return {
foreignKey: constraint.foreignKey,
constraints: [escapedName, t, len, constraint.constraints].join(' ')
};
},
createColumnConstraint: function (spec, options, tableName, columnName) {
const constraint = [];
let cb;
if (spec.unsigned) {
constraint.push('UNSIGNED');
}
if (spec.primaryKey) {
if (!options || options.emitPrimaryKey) {
constraint.push('PRIMARY KEY');
}
}
if (spec.autoIncrement) {
constraint.push('AUTO_INCREMENT');
}
if (spec.notNull === true) {
constraint.push('NOT NULL');
}
if (spec.unique) {
constraint.push('UNIQUE');
}
if (spec.onUpdate && spec.onUpdate.startsWith('CURRENT_TIMESTAMP')) {
constraint.push('ON UPDATE ' + spec.onUpdate);
}
if (spec.null || spec.notNull === false) {
constraint.push('NULL');
}
if (spec.defaultValue !== undefined) {
constraint.push('DEFAULT');
if (typeof spec.defaultValue === 'string') {
if (spec.defaultValue.startsWith('CURRENT_TIMESTAMP')) {
constraint.push(spec.defaultValue);
} else {
constraint.push("'" + spec.defaultValue + "'");
}
} else if (spec.defaultValue === null) {
constraint.push('NULL');
} else {
constraint.push(spec.defaultValue);
}
}
if (spec.after !== undefined) {
constraint.push('AFTER ' + spec.after);
}
if (spec.comment) {
constraint.push(`COMMENT '${spec.comment}'`);
}
if (spec.foreignKey) {
cb = this.bindForeignKey(tableName, columnName, spec.foreignKey);
}
return { foreignKey: cb, constraints: constraint.join(' ') };
},
renameTable: function (tableName, newTableName, callback) {
const sql = util.format(
'RENAME TABLE `%s` TO `%s`',
tableName,
newTableName
);
return this.runSql(sql).nodeify(callback);
},
_applyTableOptions: function (spec, tableName) {
const tableOpts = [];
// if there is no columns in the options object
// it means it was a default payload without table options
if (!spec.columns) return '';
if (spec.engine && typeof spec.engine === 'string') {
tableOpts.push(`ENGINE ${spec.engine}`);
}
if (spec.rowFormat && typeof spec.rowFormat === 'string') {
tableOpts.push(`ROW_FORMAT ${spec.rowFormat}`);
}
if (spec.collate && typeof spec.collate === 'string') {
tableOpts.push(`COLLATE '${spec.collate}'`);
}
if (spec.charset && typeof spec.charset === 'string') {
tableOpts.push(`CHARACTER SET ${spec.charset}`);
}
return tableOpts.join(' ');
},
createDatabase: function (dbName, options, callback) {
const spec = '';
let ifNotExists = '';
if (typeof options === 'function') callback = options;
else {
ifNotExists = options.ifNotExists === true ? 'IF NOT EXISTS' : '';
}
this.runSql(
util.format('CREATE DATABASE %s `%s` %s', ifNotExists, dbName, spec),
callback
);
},
switchDatabase: function (options, callback) {
if (typeof options === 'object') {
if (typeof options.database === 'string') {
this.all(util.format('USE `%s`', options.database), callback);
}
} else if (typeof options === 'string') {
this.all(util.format('USE `%s`', options), callback);
} else callback(null);
},
dropDatabase: function (dbName, options, callback) {
let ifExists = '';
if (typeof options === 'function') callback = options;
else {
ifExists = options.ifExists === true ? 'IF EXISTS' : '';
}
this.runSql(
util.format('DROP DATABASE %s `%s`', ifExists, dbName),
callback
);
},
removeColumn: function (tableName, columnName, callback) {
const sql = util.format(
'ALTER TABLE `%s` DROP COLUMN `%s`',
tableName,
columnName
);
return this.runSql(sql).nodeify(callback);
},
addIndex: function (tableName, indexName, columns, unique, callback) {
if (typeof unique === 'function') {
callback = unique;
unique = false;
}
if (!Array.isArray(columns)) {
columns = [columns];
}
const columnsList = [];
for (const columnIndex in columns) {
const column = columns[columnIndex];
let columnSpec = '';
if (typeof column === 'object' && column.name) {
columnSpec = util.format(
'`%s`%s',
column.name,
column.length ? util.format('(%s)', parseInt(column.length)) : ''
);
} else if (typeof column === 'string') {
columnSpec = util.format('`%s`', column);
} else return callback(new Error('Invalid column specification'));
columnsList.push(columnSpec);
}
const sql = util.format(
'ALTER TABLE `%s` ADD %s INDEX `%s` (%s)',
tableName,
unique ? 'UNIQUE ' : '',
indexName,
columnsList.join(', ')
);
return this.runSql(sql).nodeify(callback);
},
removeIndex: function (tableName, indexName, callback) {
// tableName is optional for other drivers, but required for mySql.
// So, check the args to ensure they are valid
if (
arguments.length === 1 ||
(arguments.length === 2 && typeof indexName === 'function')
) {
callback = indexName;
const err = new Error(
'Illegal arguments, must provide "tableName" and "indexName"'
);
if (typeof indexName === 'function') {
process.nextTick(function () {
callback(err);
});
}
return Promise.reject(err);
}
const sql = util.format('DROP INDEX `%s` ON `%s`', indexName, tableName);
return this.runSql(sql).nodeify(callback);
},
renameColumn: function (tableName, oldColumnName, newColumnName, callback) {
const self = this;
const columnTypeSql = util.format(
"SELECT COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '%s' AND COLUMN_NAME = '%s'",
tableName,
oldColumnName
);
return this.runSql(columnTypeSql)
.then(function (result) {
const columnType = result[0].COLUMN_TYPE;
const alterSql = util.format(
'ALTER TABLE `%s` CHANGE `%s` `%s` %s',
tableName,
oldColumnName,
newColumnName,
columnType
);
return self.runSql(alterSql);
})
.nodeify(callback);
},
changeColumn: function (tableName, columnName, columnSpec, callback) {
const constraint = this.createColumnDef(columnName, columnSpec);
const sql = util.format(
'ALTER TABLE `%s` CHANGE COLUMN `%s` %s',
tableName,
columnName,
constraint.constraints
);
const exec = function () {
return this.runSql(sql).then(function () {
if (constraint.foreignKey) return constraint.foreignKey();
else return Promise.resolve();
});
}.bind(this);
if (columnSpec.unique === false) {
return this.removeIndex(tableName, columnName)
.then(function () {
return exec();
})
.nodeify(callback);
} else return exec().nodeify(callback);
},
addMigrationRecord: function (name, callback) {
const formattedDate = moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
this.runSql(
'INSERT INTO `' +
internals.migrationTable +
'` (`name`, `run_on`) VALUES (?, ?)',
[name, formattedDate],
callback
);
},
addSeedRecord: function (name, callback) {
const formattedDate = moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
this.runSql(
'INSERT INTO `' +
internals.seedTable +
'` (`name`, `run_on`) VALUES (?, ?)',
[name, formattedDate],
callback
);
},
addForeignKey: function (
tableName,
referencedTableName,
keyName,
fieldMapping,
rules,
callback
) {
if (arguments.length === 5 && typeof rules === 'function') {
callback = rules;
rules = {};
}
const columns = Object.keys(fieldMapping);
const referencedColumns = columns.map(function (key) {
return fieldMapping[key];
});
const sql = util.format(
'ALTER TABLE `%s` ADD CONSTRAINT `%s` FOREIGN KEY (%s) REFERENCES `%s` (%s) ON DELETE %s ON UPDATE %s',
tableName,
keyName,
this.quoteDDLArr(columns).join(', '),
referencedTableName,
this.quoteDDLArr(referencedColumns).join(', '),
rules.onDelete || 'NO ACTION',
rules.onUpdate || 'NO ACTION'
);
return this.runSql(sql).nodeify(callback);
},
removeForeignKey: function (tableName, keyName, options, callback) {
let sql = util.format(
'ALTER TABLE `%s` DROP FOREIGN KEY `%s`',
tableName,
keyName
);
if (typeof options === 'function') {
callback = options;
}
return this.runSql(sql)
.then(
function () {
if (options && options.dropIndex === true) {
sql = util.format(
'ALTER TABLE `%s` DROP INDEX `%s`',
tableName,
keyName
);
return this.runSql(sql);
} else {
return Promise.resolve();
}
}.bind(this)
)
.nodeify(callback);
},
runSql: function () {
const self = this;
const args = this._makeParamArgs(arguments);
const callback = args.pop();
log.sql.apply(null, arguments);
if (internals.dryRun) {
return Promise.resolve().nodeify(callback);
}
return new Promise(function (resolve, reject) {
args.push(function (err, data) {
return err ? reject(err) : resolve(data);
});
self.connection.query.apply(self.connection, args);
}).nodeify(callback);
},
_makeParamArgs: function (args) {
let params = Array.prototype.slice.call(args);
const sql = params.shift();
const callback =
typeof params[params.length - 1] === 'function' ? params.pop() : null;
if (params.length > 0 && Array.isArray(params[0])) {
params = params[0];
}
return [sql, params, callback];
},
all: function () {
const args = this._makeParamArgs(arguments);
log.sql.apply(null, arguments);
return this.connection.query.apply(this.connection, args);
},
close: function (callback) {
return new Promise(
function (resolve, reject) {
const cb = function (err, data) {
return err ? reject(err) : resolve(data);
};
this.connection.end(cb);
}.bind(this)
).nodeify(callback);
}
});
Promise.promisifyAll(MysqlDriver);
function dummy () {
arguments[arguments.length - 1]('not implemented');
}
exports.connect = function (config, intern, callback) {
let db;
internals = intern;
log = internals.mod.log;
type = internals.mod.type;
internals.interfaces.SeederInterface._makeParamArgs = dummy;
if (typeof mysql.createConnection === 'undefined') {
db = config.db || mysql.createClient(config);
} else {
db = config.db || mysql.createConnection(config);
}
db.connect(function (err) {
if (err) {
return callback(err);
}
callback(null, new MysqlDriver(db));
});
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.