text
stringlengths 3
1.05M
|
|---|
import store from '@/store'
import storage from 'store'
import {
ACCESS_TOKEN,
APP_LANGUAGE,
TOGGLE_CONTENT_WIDTH,
TOGGLE_FIXED_HEADER,
TOGGLE_FIXED_SIDEBAR, TOGGLE_HIDE_HEADER,
TOGGLE_LAYOUT, TOGGLE_NAV_THEME, TOGGLE_WEAK,
TOGGLE_COLOR, TOGGLE_MULTI_TAB
} from '@/appCore/store/mutation-types'
import defaultSettings from '@/appCore/config/defaultSettings'
export default function Initializer () {
store.commit(TOGGLE_LAYOUT, storage.get(TOGGLE_LAYOUT, defaultSettings.layout))
store.commit(TOGGLE_FIXED_HEADER, storage.get(TOGGLE_FIXED_HEADER, defaultSettings.fixedHeader))
store.commit(TOGGLE_FIXED_SIDEBAR, storage.get(TOGGLE_FIXED_SIDEBAR, defaultSettings.fixSiderbar))
store.commit(TOGGLE_CONTENT_WIDTH, storage.get(TOGGLE_CONTENT_WIDTH, defaultSettings.contentWidth))
store.commit(TOGGLE_HIDE_HEADER, storage.get(TOGGLE_HIDE_HEADER, defaultSettings.autoHideHeader))
store.commit(TOGGLE_NAV_THEME, storage.get(TOGGLE_NAV_THEME, defaultSettings.navTheme))
store.commit(TOGGLE_WEAK, storage.get(TOGGLE_WEAK, defaultSettings.colorWeak))
store.commit(TOGGLE_COLOR, storage.get(TOGGLE_COLOR, defaultSettings.primaryColor))
store.commit(TOGGLE_MULTI_TAB, storage.get(TOGGLE_MULTI_TAB, defaultSettings.multiTab))
store.commit('SET_TOKEN', storage.get(ACCESS_TOKEN))
store.dispatch('setLang', storage.get(APP_LANGUAGE, 'zh-CN'))
// last step
}
|
'use strict';
/* Controllers */
//an app controller is useful for providing default - e.g. AppName, Page Titles?
// function AppCtrl($scope, $http) {
// $http.get('/api/name')
// .success(function(data, status, headers, config) {
// $scope.name = data.name;
// })
// .error(function(data, status, headers, config) {
// $scope.name = 'Error!';
// });
// }
function RegisterCtrl($scope, $location, $http) {
$scope.form = {};
$scope.registerUser = function () {
$http.post('/account/register', $scope.form)
.success(function(data) {
$location.path('/activationSent');
})
.error(function(data, status, headers, config) {
$scope.error = data.error.message;
});
};
$scope.resendActivation = function () {
$http.post('/account/resendActivation', $scope.form)
.success(function(data) {
$location.path('/activationResent');
})
.error(function(data, status, headers, config) {
$scope.error = data.error.message;
});
};
// $scope.terms = function() {
// $http.get('/modals/terms')
// .success(function(data, status, headers, config) {
// $scope.data = data;
// });
// };
}
// RegisterCtrl.$inject = [];
function LoginCtrl($scope, $location, $http) {
$scope.form = {};
$scope.loginUser = function () {
$http.post('/account/login', $scope.form)
.success(function(data) {
$location.path('/');
})
.error(function(data, status, headers, config) {
$scope.error = data.error.message;
console.log(data.error.message);
});
};
}
// RegisterCtrl.$inject = [];
function ModalCtrl($scope) {
this.setModel = function(data) {
$scope.$apply( function() {
$scope.data = data;
});
};
$scope.setModel = this.setModel;
}
// function IndexCtrl($scope, $http) {
// $http.get('/api/posts').
// success(function(data, status, headers, config) {
// $scope.posts = data.posts;
// });
// }
// function AddPostCtrl($scope, $http, $location) {
// $scope.form = {};
// $scope.submitPost = function () {
// $http.post('/api/post', $scope.form).
// success(function(data) {
// $location.path('/');
// });
// };
// }
// function ReadPostCtrl($scope, $http, $routeParams) {
// $http.get('/api/post/' + $routeParams.id).
// success(function(data) {
// $scope.post = data.post;
// });
// }
// function EditPostCtrl($scope, $http, $location, $routeParams) {
// $scope.form = {};
// $http.get('/api/post/' + $routeParams.id).
// success(function(data) {
// $scope.form = data.post;
// });
// $scope.editPost = function () {
// $http.put('/api/post/' + $routeParams.id, $scope.form).
// success(function(data) {
// $location.url('/readPost/' + $routeParams.id);
// });
// };
// }
// function DeletePostCtrl($scope, $http, $location, $routeParams) {
// $http.get('/api/post/' + $routeParams.id).
// success(function(data) {
// $scope.post = data.post;
// });
// $scope.deletePost = function () {
// $http.delete('/api/post/' + $routeParams.id).
// success(function(data) {
// $location.url('/');
// });
// };
// $scope.home = function () {
// $location.url('/');
// };
// }
|
/**
* @author : weiwzhang@Ctrip.com
* @editor : Sublime Text
* @updated : 2016.11.30
* @description : Cute ui
*
*/
;
(function ($, global) {
var docs = (function () {
var $side = $(".side-area"),
$mask = $("#mask"),
$tips = $("#tips"),
$tab = $("#tab"),
lastTag = 'mask';
return {
// sidebar
sidebar: function () {
var scrollTop = $(window).scrollTop(),
scrollLeft = $(window).scrollLeft(),
sideLeft = $side.parent().offset().left - scrollLeft + 10 + "px";
if (scrollTop >= 281) {
$side.css({
"position": "fixed",
"top": 20 + "px",
"left": sideLeft,
"z-index": 10
});
} else {
$side.css({
"position": "absolute",
"top": "auto",
"left": "auto",
"z-index": "auto"
});
}
},
// scrool
windowScroll: function () {
var _this = this;
$(window).scroll(function () {
_this.sidebar();
var scrollTop = $(window).scrollTop() + 0;
var tag = 'mask';
if (scrollTop >= $tips.offset().top) {
tag = 'tips';
}
if (scrollTop >= $tab.offset().top) {
tag = 'tab';
}
if (lastTag !== tag) {
lastTag = tag;
$side.find('a.avtive').removeClass('avtive');
$side.find('[href="#' + tag + '"]').addClass('avtive');
}
});
},
// resize
windowResize: function () {
var _this = this;
$(window).resize(function () {
_this.sidebar();
});
},
// 统一执行
init: function () {
this.sidebar();
this.windowScroll();
this.windowResize();
}
};
})();
$(function () {
docs.init();
});
})(jQuery, this);
|
'use strict';
import { quizData } from '../data.js';
import createDOMElement from '../utils/createDOMElement.js';
import getDOMElement from '../utils/getDOMElement.js';
const score = createDOMElement('h3', { id: 'user-score' });
export const createQuestionElement = (question) => {
const container = createDOMElement('div');
const title = createDOMElement('h1');
title.innerText = question.text;
container.appendChild(title);
const answerContainer = createDOMElement('ol');
let clickCounter = 0;
score.innerText = `${quizData.correctAnswers.length} correct of ${quizData.questions.length}`;
for (const answerKey in question.answers) {
const answer = createAnswerElement(answerKey, question.answers[answerKey]);
answer.addEventListener('click', (e) => {
score.innerText = '';
score.innerText = `${quizData.correctAnswers.length} correct of ${quizData.questions.length}`;
clickCounter++;
// question.selected = e.target.dataset.answerItemKey; discuss this line with the group
if (
e.target.dataset.answerItemKey == question.correct &&
clickCounter == 1
) {
e.target.classList.add('correct');
quizData.correctAnswers.push(question);
} else if (
e.target.dataset.answerItemKey != question.correct &&
clickCounter == 1
) {
quizData.wrongAnswers.push(question);
e.target.parentElement.childNodes.forEach((item) => {
if (item.dataset.answerItemKey == question.correct) {
item.classList.add('correct');
} else {
e.target.classList.add('wrong');
}
});
} else {
title.innerText = 'Click next Button';
title.style.color = 'red';
title.style.width = '800px';
}
// score.innerText = `${quizData.correctAnswers.length} correct of ${quizData.questions.length}`;
});
answerContainer.appendChild(answer);
document.body.appendChild(score);
}
container.appendChild(answerContainer);
return container;
};
export const createAnswerElement = (answerKey, answerText) => {
const answerElement = createDOMElement('li', { className: 'btn' });
answerElement.innerText = answerText;
answerElement.dataset.answerItemKey = answerKey;
answerElement.classList.add('answersStyle');
return answerElement;
};
export default createQuestionElement;
|
'use strict';
module.exports = {
classesContainer: {
methods: {
/**
* Set the definition of a class.
*
* @param {string} id The id of the class.
* @param {function} class The class.
*/
setDefinition: {
arguments: ['string/id', 'function/class']
},
/**
* Get the definition of a class.
*
* @param {string} id The id of the class.
* @return {object} The class.
*/
getDefinition: {
arguments: ['string/id'],
returns: 'object'
},
/**
* Whether or not a class is defined.
*
* @param {string} id The id of the class.
* @return {boolean} True if the class is defined, false otherwise.
*/
hasDefinition: {
arguments: ['string/id'],
returns: 'boolean'
},
/**
* Build the definitions of the classes applying the class processors.
*/
build: {
arguments: []
},
/**
* Get a processed class.
*
* @param {string} id The id of the class.
* @return {function} The class.
*/
get: {
arguments: ['string/id'],
returns: 'function'
},
/**
* Whether or not a class has been processed.
*
* @param {string} id The id of the class.
* @return {boolean} True if the class has been processed, false otherwise.
*/
has: {
arguments: ['string/id'],
returns: 'boolean'
}
}
},
interfacesContainer: {
methods: {
/**
* Set the definition of an interface.
*
* @param {string} id The id of the interface.
* @param {object} definition The definition of the interface.
*/
setDefinition: {
arguments: ['string/id', 'object/definition']
},
/**
* Get the definition of an interface.
*
* @param {string} id The id of the interface.
* @return {object} The definition of the interface.
*/
getDefinition: {
arguments: ['string/id'],
returns: 'object'
},
/**
* Whether or not an interface is defined.
*
* @param {string} id The id of the interface.
* @return {boolean} True if the interface is defined, false otherwise.
*/
hasDefinition: {
arguments: ['string/id'],
returns: 'boolean'
},
/**
* Build the definitions of the interfaces.
*/
build: {
arguments: []
},
/**
* Get an interface.
*
* @param {string} id The id of the interface.
* @return {danf:object.interface} The interface.
*/
get: {
arguments: ['string/id'],
returns: 'danf:object.interface'
},
/**
* Whether or not an interface has been processed.
*
* @param {string} id The id of the interface.
* @return {boolean} True if the interface exists, false otherwise.
*/
has: {
arguments: ['string/id'],
returns: 'boolean'
}
}
},
'interface': {
methods: {
/**
* Whether or not the interface define a method.
*
* @param {string} methodName The name of the method.
* @return {boolean} True if the interface define the method, false otherwise.
* @throw {error} If the interface is not defined.
*/
hasMethod: {
arguments: ['string/name', 'string/methodName'],
returns: 'boolean'
},
/**
* Get a method of the interface.
*
* @param {string} methodName The name of the method.
* @return {object} The method.
* @throw {error} If the method of the interface is not defined.
*/
getMethod: {
arguments: ['string/name', 'string/methodName'],
returns: 'object'
},
/**
* Whether or not the interface define a getter.
*
* @param {string} getterName The name of the getter.
* @return {boolean} True if the interface define the getter, false otherwise.
* @throw {error} If the interface is not defined.
*/
hasGetter: {
arguments: ['string/name', 'string/getterName'],
returns: 'boolean'
},
/**
* Get a getter of the interface.
*
* @param {string} getterName The name of the getter.
* @return {object} The getter.
* @throw {error} If the getter of the interface is not defined.
*/
getGetter: {
arguments: ['string/name', 'string/getterName'],
returns: 'string'
},
/**
* Whether or not the interface define a setter.
*
* @param {string} setterName The name of the setter.
* @return {boolean} True if the interface define the setter, false otherwise.
* @throw {error} If the interface is not defined.
*/
hasSetter: {
arguments: ['string/name', 'string/setterName'],
returns: 'boolean'
},
/**
* Get a setter of the interface.
*
* @param {string} setterName The name of the setter.
* @return {object} The setter.
* @throw {error} If the setter of the interface is not defined.
*/
getSetter: {
arguments: ['string/name', 'string/setterName'],
returns: 'string'
}
},
getters: {
/**
* Name.
*
* @return {string}
*/
name: 'string',
/**
* Name of the extended interface.
*
* @return {string}
*/
'extends': 'string',
/**
* Methods.
*
* @return {mixed_object_object}
*/
methods: 'mixed_object_object',
/**
* Getters.
*
* @return {string_object}
*/
getters: 'string_object',
/**
* Setters.
*
* @return {string_object}
*/
setters: 'string_object'
}
},
interfacer: {
methods: {
/**
* Add a proxy on an object to ensure the respect of an interface.
*
* @param {object} object The object.
* @param {string} interfaceName The name of the interface.
*/
addProxy: {
arguments: ['object/object', 'string/interfaceName']
}
}
},
classProcessor: {
methods: {
/**
* Process a class.
*
* @param {function}
*/
process: {
arguments: ['function/class']
}
},
getters: {
/**
* Order of execution.
*
* @return {number}
*/
order: 'number'
},
setters: {
/**
* Classes container.
*
* @param {danf:object.classesContainer}
*/
classesContainer: 'danf:object.classesContainer'
}
}
};
|
from matplotlib.ticker import MaxNLocator
import matplotlib.pyplot as plt
import os
import statistics
import matplotlib
import numpy as np
matplotlib.rcParams['text.usetex'] = True
# Path for criterion
main_path = './compile_time'
# Get all directories in main_path
directories = os.listdir(main_path)
# Lists for plots
average_mpst = []
average_binary = []
average_crossbeam = []
average_cancel = []
average_cancel_broadcast = []
nb_participants_mpst = []
nb_participants_binary = []
nb_participants_crossbeam = []
nb_participants_cancel = []
nb_participants_cancel_broadcast = []
# Dictionary for converting from string to int
str_to_int = {'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6, 'seven': 7,
'eight': 8, 'nine': 9, 'ten': 10, 'eleven': 11, 'twenty': 20, 'empty': 0}
# For each folder in main_path
for d in directories:
if ".txt" in d and 'mesh' in d:
file = open(main_path + '/' + d, "r")
name = d.split('.txt')[0].split('mesh_')[1].split('_')[0]
build_time = []
try:
for line in file:
if 'build' in line:
build_time.append(
int(line.split('build; ')[1].split('\n')[0]))
# If MPST of binary, append to related lists
if 'mpst' in d:
average_mpst.append(statistics.mean(build_time)/10**6)
nb_participants_mpst.append(str_to_int[name])
elif 'binary' in d:
average_binary.append(statistics.mean(build_time)/10**6)
nb_participants_binary.append(str_to_int[name])
elif 'cancel' in d:
if 'broadcast' in d:
average_cancel_broadcast.append(
statistics.mean(build_time)/10**6)
nb_participants_cancel_broadcast.append(str_to_int[name])
else:
average_cancel.append(statistics.mean(build_time)/10**6)
nb_participants_cancel.append(str_to_int[name])
elif 'crossbeam' in d:
average_crossbeam.append(statistics.mean(build_time)/10**6)
nb_participants_crossbeam.append(str_to_int[name])
except:
print('Issue with ', d)
file.close()
# Sort the lists in pair
nb_participants_mpst, average_mpst = (list(t) for t in zip(
*sorted(zip(nb_participants_mpst, average_mpst))))
nb_participants_binary, average_binary = (list(t)
for t in zip(*sorted(zip(nb_participants_binary, average_binary))))
nb_participants_crossbeam, average_crossbeam = (list(t)
for t in zip(*sorted(zip(nb_participants_crossbeam, average_crossbeam))))
nb_participants_cancel, average_cancel = (list(t)
for t in zip(*sorted(zip(nb_participants_cancel, average_cancel))))
nb_participants_cancel_broadcast, average_cancel_broadcast = (list(t)
for t in zip(*sorted(zip(nb_participants_cancel_broadcast, average_cancel_broadcast))))
# Change size
fig, ax = plt.subplots(figsize=(60, 60))
plt.gcf().subplots_adjust(bottom=0.27, left=0.13)
ax.xaxis.set_major_locator(MaxNLocator(integer=True))
ax.yaxis.set_major_locator(MaxNLocator(integer=True))
# Plot the MPST graph
ax.plot(nb_participants_mpst, average_mpst, label='MPST',
linestyle='solid', linewidth=20, marker='>', markersize=150)
# Plot the binary graph
ax.plot(nb_participants_binary, average_binary, label='Binary',
linestyle='solid', linewidth=20, marker='o', markersize=150)
# Plot the crossbeam graph
ax.plot(nb_participants_crossbeam, average_crossbeam, label='Crossbeam',
linestyle='solid', linewidth=20, marker='d', markersize=150)
if len(average_cancel) > 0:
# Plot the cancel graph
ax.plot(nb_participants_cancel, average_cancel, label='Cancel',
linestyle='solid', linewidth=20, marker='*', markersize=150)
# ax.plot(nb_participants_cancel_broadcast, average_cancel_broadcast,
# label="Broadcast cancel", linestyle='dotted', linewidth=5)
# Label X and Y axis
ax.set_xlabel('\# roles', fontsize=600)
# ax.set_ylabel('Time (s)', fontsize=600)
ax.tick_params(axis='both', which='major', labelsize=500)
ax.xaxis.set_ticks(np.arange(2, 11, 2))
ax.yaxis.set_ticks(np.arange(50, 73, 10))
ax.set_xlim(2, 10)
ax.set_ylim(50, 73)
# ax.tick_params(axis='both', which='minor', labelsize=30)
offset_x = matplotlib.transforms.ScaledTranslation(0, -2, fig.dpi_scale_trans)
# apply offset transform to all x ticklabels.
for label in ax.xaxis.get_majorticklabels():
label.set_transform(label.get_transform() + offset_x)
offset_y = matplotlib.transforms.ScaledTranslation(-1, 0, fig.dpi_scale_trans)
for label in ax.yaxis.get_majorticklabels():
label.set_transform(label.get_transform() + offset_y)
# Add grid
# ax.grid(True)
# # giving a title to my graph
# plt.title('Compile time needed')
# show a legend on the plot
# ax.legend(bbox_to_anchor=(0.5, 1), loc="lower center", prop={'size': 20})
# Save fig
plt.savefig(main_path + '/graphAverageCompileMesh.pdf')
# # function to show the plot
# plt.show()
|
import "foo" \u{61}ssert { type: "json" };
|
import Ember from 'ember';
export default Ember.Controller.extend({
// -------------------------------------------------------------------------
// Dependencies
queryParams: ['unitId', 'lessonId'],
// -------------------------------------------------------------------------
// Actions
actions: {
/**
* Sets the current course builder location
* @param unitId
* @param lessonId
*/
setLocation: function(unitId, lessonId = undefined) {
this.set('unitId', unitId || null);
this.set('lessonId', lessonId || null);
}
},
// -------------------------------------------------------------------------
// Properties
/**
* @property {string}
*/
unitId: null,
/**
* @property {string}
*/
lessonId: null,
/**
* @property {string}
*/
classId: null,
/**
* @property {string}
*/
userId: null,
// -------------------------------------------------------------------------
// Methods
resetValues: function() {
this.set('unitId', null);
this.set('lessonId', null);
}
});
|
"""
Tooling to quickly discover datasets in a given blob store.
"""
import logging
from typing import Callable, Dict, Iterable, Optional, Set, Tuple, Union
from simplekv import KeyValueStore
from kartothek.api.consistency import check_datasets
from kartothek.core.cube.constants import (
KTK_CUBE_METADATA_DIMENSION_COLUMNS,
KTK_CUBE_METADATA_KEY_IS_SEED,
KTK_CUBE_METADATA_PARTITION_COLUMNS,
KTK_CUBE_UUID_SEPERATOR,
)
from kartothek.core.cube.cube import Cube
from kartothek.core.dataset import DatasetMetadata
from kartothek.core.naming import (
METADATA_BASE_SUFFIX,
METADATA_FORMAT_JSON,
METADATA_FORMAT_MSGPACK,
)
from kartothek.utils.converters import converter_str_set_optional
__all__ = (
"discover_cube",
"discover_datasets",
"discover_datasets_unchecked",
"discover_ktk_cube_dataset_ids",
)
_logger = logging.getLogger(__name__)
def _discover_dataset_meta_files(
prefix: str, store: Union[Callable[[], KeyValueStore], KeyValueStore]
) -> Set[str]:
"""
Get meta file names for all datasets.
Parameters
----------
prefix
the prefix.
store
KV store.
Returns
-------
names: Set[str]
The meta file names
"""
if callable(store):
store = store()
names = {
name[: -len(METADATA_BASE_SUFFIX + suffix)]
for name in store.iter_prefixes(delimiter="/", prefix=prefix)
for suffix in [METADATA_FORMAT_JSON, METADATA_FORMAT_MSGPACK]
if name.endswith(METADATA_BASE_SUFFIX + suffix)
}
return names
def discover_ktk_cube_dataset_ids(
uuid_prefix: str, store: Union[Callable[[], KeyValueStore], KeyValueStore]
) -> Set[str]:
"""
Get ktk_cube dataset ids for all datasets.
Parameters
----------
uuid_prefix
Dataset UUID prefix.
store
KV store.
Returns
-------
names: Set[str]
The ktk_cube dataset ids
"""
prefix = uuid_prefix + KTK_CUBE_UUID_SEPERATOR
names = _discover_dataset_meta_files(prefix, store)
return set([name[len(prefix) :] for name in names])
def discover_datasets_unchecked(
uuid_prefix: str,
store: Union[Callable[[], KeyValueStore], KeyValueStore],
filter_ktk_cube_dataset_ids: Optional[Union[str, Iterable[str]]] = None,
) -> Dict[str, DatasetMetadata]:
"""
Get all known datasets that may belong to a give cube w/o applying any checks.
.. warning::
The results are not checked for validity. Found datasets may be incompatible w/ the given cube. Use
:meth:`check_datasets` to check the results, or go for :meth:`discover_datasets` in the first place.
Parameters
----------
uuid_prefix
Dataset UUID prefix.
store
KV store.
filter_ktk_cube_dataset_ids
Optional selection of datasets to include.
Returns
-------
datasets: Dict[str, DatasetMetadata]
All discovered datasets. Empty Dict if no dataset is found
"""
if callable(store):
store = store()
filter_ktk_cube_dataset_ids = converter_str_set_optional(
filter_ktk_cube_dataset_ids
)
prefix = uuid_prefix + KTK_CUBE_UUID_SEPERATOR
names = _discover_dataset_meta_files(prefix, store)
if filter_ktk_cube_dataset_ids is not None:
names = {
name for name in names if name[len(prefix) :] in filter_ktk_cube_dataset_ids
}
result = {}
# sorted iteration for determistic error messages in case DatasetMetadata.load_from_store fails
for name in sorted(names):
try:
result[name[len(prefix) :]] = DatasetMetadata.load_from_store(
uuid=name, store=store, load_schema=True, load_all_indices=False
)
except KeyError as e:
_logger.warning(
'Ignore dataset "{name}" due to KeyError: {e}'.format(name=name, e=e)
)
return result
def discover_datasets(
cube: Cube,
store: Union[Callable[[], KeyValueStore], KeyValueStore],
filter_ktk_cube_dataset_ids: Optional[Union[str, Iterable[str]]] = None,
) -> Dict[str, DatasetMetadata]:
"""
Get all known datasets that belong to a give cube.
Parameters
----------
cube
Cube specification.
store
KV store.
filter_ktk_cube_dataset_ids
Optional selection of datasets to include.
Returns
-------
datasets: Dict[str, DatasetMetadata]
All discovered datasets.
Raises
------
ValueError
In case no valid cube could be discovered.
"""
filter_ktk_cube_dataset_ids = converter_str_set_optional(
filter_ktk_cube_dataset_ids
)
result = discover_datasets_unchecked(
cube.uuid_prefix, store, filter_ktk_cube_dataset_ids
)
if filter_ktk_cube_dataset_ids is not None:
if isinstance(filter_ktk_cube_dataset_ids, str):
filter_ktk_cube_dataset_ids = {filter_ktk_cube_dataset_ids}
else:
filter_ktk_cube_dataset_ids = set(filter_ktk_cube_dataset_ids)
missing = filter_ktk_cube_dataset_ids - set(result.keys())
if missing:
raise ValueError(
"Could not find the following requested datasets: {missing}".format(
missing=", ".join(sorted(missing))
)
)
check_datasets(result, cube)
return result
def discover_cube(
uuid_prefix: str,
store: Union[Callable[[], KeyValueStore]],
filter_ktk_cube_dataset_ids: Optional[Union[str, Iterable[str]]] = None,
) -> Tuple[Cube, Dict[str, DatasetMetadata]]:
"""
Recover cube information from store.
Parameters
----------
uuid_prefix
Dataset UUID prefix.
store
KV store.
filter_ktk_cube_dataset_ids
Optional selection of datasets to include.
Returns
-------
cube: Cube
Cube specification.
datasets: Dict[str, DatasetMetadata]
All discovered datasets.
"""
datasets = discover_datasets_unchecked(
uuid_prefix, store, filter_ktk_cube_dataset_ids
)
seed_candidates = {
ktk_cube_dataset_id
for ktk_cube_dataset_id, ds in datasets.items()
if ds.metadata.get(
KTK_CUBE_METADATA_KEY_IS_SEED, ds.metadata.get("klee_is_seed", False)
)
}
if len(seed_candidates) == 0:
raise ValueError(
'Could not find seed dataset for cube "{uuid_prefix}".'.format(
uuid_prefix=uuid_prefix
)
)
elif len(seed_candidates) > 1:
raise ValueError(
'Found multiple possible seed datasets for cube "{uuid_prefix}": {seed_candidates}'.format(
uuid_prefix=uuid_prefix,
seed_candidates=", ".join(sorted(seed_candidates)),
)
)
seed_dataset = list(seed_candidates)[0]
seed_ds = datasets[seed_dataset]
dimension_columns = seed_ds.metadata.get(
KTK_CUBE_METADATA_DIMENSION_COLUMNS,
seed_ds.metadata.get("klee_dimension_columns"),
)
if dimension_columns is None:
raise ValueError(
'Could not recover dimension columns from seed dataset ("{seed_dataset}") of cube "{uuid_prefix}".'.format(
seed_dataset=seed_dataset, uuid_prefix=uuid_prefix
)
)
# datasets written with new kartothek versions (after merge of PR#7747)
# always set KTK_CUBE_METADATA_PARTITION_COLUMNS and "klee_timestamp_column" in the metadata.
# Older versions of ktk_cube do not write these; instead, these columns are inferred from
# the actual partitioning: partition_columns are all but the last partition key
#
# TODO: once we're sure we have re-written all kartothek cubes, the code
# in the branch `if partition_columns is None` below can be removed.
#
# read the now unused timestamp column just to make sure we can still read older cubes.
#
# TODO: once all cubes are re-created and don't use timestamp column anymore, remove the timestamp column handling
# entirely
partition_columns = seed_ds.metadata.get(
KTK_CUBE_METADATA_PARTITION_COLUMNS,
seed_ds.metadata.get("klee_partition_columns"),
)
timestamp_column = seed_ds.metadata.get("klee_timestamp_column")
if partition_columns is None:
# infer the partition columns and timestamp column from the actual partitioning:
partition_keys = seed_ds.partition_keys
if len(partition_keys) == 0:
raise ValueError(
'Seed dataset ("{seed_dataset}") has no partition keys.'.format( # type: ignore # noqa
seed_dataset=seed_dataset, partition_keys=", ".join(partition_keys),
)
)
elif len(partition_keys) < 2:
raise ValueError(
(
'Seed dataset ("{seed_dataset}") has only a single partition key ({partition_key}) '
"but should have at least 2."
).format(seed_dataset=seed_dataset, partition_key=partition_keys[0])
)
partition_columns = partition_keys[:-1]
timestamp_column = partition_keys[-1]
index_columns = set()
for ds in datasets.values():
index_columns |= set(ds.indices.keys()) - (
set(dimension_columns) | set(partition_columns) | {timestamp_column}
)
# we only support the default timestamp column in the compat code
if (timestamp_column is not None) and (timestamp_column != "KLEE_TS"):
raise NotImplementedError(
f"Can only read old cubes if the timestamp column is 'KLEE_TS', but '{timestamp_column}' was detected."
)
cube = Cube(
uuid_prefix=uuid_prefix,
dimension_columns=dimension_columns,
partition_columns=partition_columns,
index_columns=index_columns,
seed_dataset=seed_dataset,
)
datasets = check_datasets(datasets, cube)
return cube, datasets
|
const db = require('./db');
exports.getLastsArticles = (limit) => {
return new Promise((resolve, reject) => {
db.query('SELECT * FROM articles WHERE status = 1 ORDER BY date_insert DESC LIMIT ?', [limit], (err, result) => {
if (err) return reject(err.message)
else {
resolve(result)
}
})
})
}
exports.getAllArticles = (skip) => {
return new Promise((resolve, reject) => {
if (skip < 0) return reject('Skip ne peux pas etre inferieur a 0.')
db.query('SELECT * FROM articles ORDER BY date_insert DESC LIMIT 5 OFFSET ?', [skip], (err, result) => {
if (err) return reject(err.message)
else {
resolve(result)
}
})
})
}
exports.searchArticles = (search) => {
return new Promise((resolve, reject) => {
db.query('SELECT * FROM articles WHERE title LIKE ? ORDER BY date_insert DESC LIMIT 10', ['%' + search + '%'], (err, result) => {
if (err) return reject(err.message)
else {
resolve(result)
}
})
})
}
exports.getAllByMemberId = (id) => {
return new Promise((resolve, reject) => {
db.query('SELECT * FROM articles WHERE author_id = ?', [id], (err, result) => {
if (err) return reject(err.message)
else {
resolve(result)
}
})
})
}
exports.getArticle = (articleId) => {
return new Promise((resolve, reject) => {
db.query('SELECT * FROM `articles` LEFT JOIN `members` ON articles.author_id = members.member_id WHERE id = ?', [articleId], (err, result) => {
if (err) return reject(err.message)
else {
resolve(result[0])
}
})
})
}
exports.isUniqueTitle = (title) => {
return new Promise((resolve, reject) => {
db.query('SELECT * FROM articles WHERE title = ?', [title], (err, result) => {
if (err) return reject(err.message)
else {
if (result[0]) return resolve(false)
else return resolve(true)
}
})
})
}
exports.addArticle = (article) => {
return new Promise((resolve, reject) => {
if (!article) return reject('Aucun paramètres')
else {
db.query('INSERT INTO `articles` (`author_id`, `title`, `categorie`, `intro`, `content`, `lien_miniature`, `status`, `date_insert`) VALUES (?,?,?,?,?,?,?,?)', [article.authorId, article.title, article.categorie, article.intro, article.content, article.miniature, article.status, article.timestamp], (err, result) => {
if (err) reject(err.message)
else resolve(result)
})
}
})
}
exports.updateArticle = (id, newParams) => {
return new Promise((resolve, reject) => {
if (!id) return reject('Missing id');
if (!newParams) return reject('Missing new params');
db.query('UPDATE articles SET title=?,categorie=?,intro=?,content=?,lien_miniature=?,status=? WHERE id = ?', [newParams.title, newParams.categorie, newParams.intro, newParams.content, newParams.miniature, newParams.status, id], (err, result) => {
if (err) return reject(err.message)
else {
resolve(result)
}
})
})
}
exports.deleteArticle = (id) => {
return new Promise((resolve, reject) => {
if (!id) return reject("Missing id")
db.query('DELETE FROM articles WHERE id = ?', [id], (err, result) => {
if (err) return reject(err.message)
else {
resolve(result)
}
})
})
}
|
// Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular-devkit/build-angular'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage'),
require('@angular-devkit/build-angular/plugins/karma')
],
client: {
jasmine: {
// you can add configuration options for Jasmine here
// the possible options are listed at https://jasmine.github.io/api/edge/Configuration.html
// for example, you can disable the random execution with `random: false`
// or set a specific seed with `seed: 4321`
},
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
jasmineHtmlReporter: {
suppressAll: true // removes the duplicated traces
},
coverageReporter: {
dir: require('path').join(__dirname, './coverage/SpaceXProgram'),
subdir: '.',
reporters: [
{ type: 'html' },
{ type: 'text-summary' }
]
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
restartOnFileChange: true
});
};
|
/* eslint-disable react/no-array-index-key */
import React from 'react';
import { Row, Card, CardBody, CardTitle } from 'reactstrap';
import IntlMessages from '../../../../helpers/IntlMessages';
import {
Colxx,
Separator,
} from '../../../../components/common/CustomBootstrap';
import Breadcrumb from '../../../../containers/navs/Breadcrumb';
import PopoverItem from '../../../../components/common/PopoverItem';
import TooltipItem from '../../../../components/common/TooltipItem';
const popovers = [
{
placement: 'top',
text: 'Popover on top',
body: 'Augue laoreet rutrum faucibus vivamus sagittis lacus vel .',
},
{
placement: 'bottom',
text: 'Popover on bottom',
body: 'Vel augue laoreet rutrum Vivamus sagittis lacus faucibus.',
},
{
placement: 'left',
text: 'Popover on left',
body: 'Lacus vel augue Vivamus sagittis laoreet rutrum faucibus.',
},
{
placement: 'right',
text: 'Popover on right',
body: 'Laoreet rutrum faucibus vivamus sagittis lacus vel augue.',
},
];
const tooltips = [
{
placement: 'top',
text: 'Tooltip on top',
body: 'Vivamus sagittis lacus',
},
{
placement: 'bottom',
text: 'Tooltip on bottom',
body: 'Lacus vel augue',
},
{
placement: 'left',
text: 'Tooltip on left',
body: 'Laoreet rutrum faucibus',
},
{
placement: 'right',
text: 'Tooltip on right',
body: 'Augue rutrum vel',
},
];
const PopoverTooltipUi = ({ match }) => {
return (
<>
<Row>
<Colxx xxs="12">
<Breadcrumb heading="menu.popover-tooltip" match={match} />
<Separator className="mb-5" />
</Colxx>
</Row>
<Row>
<Colxx xxs="12">
<Card className="mb-4">
<CardBody>
<CardTitle>
<IntlMessages id="popover-tooltip.popover" />
</CardTitle>
{popovers.map((popover, i) => {
return (
<PopoverItem key={`popover_${i}`} item={popover} id={i} />
);
})}
</CardBody>
</Card>
</Colxx>
</Row>
<Row>
<Colxx xxs="12">
<Card className="mb-4">
<CardBody>
<CardTitle>
<IntlMessages id="popover-tooltip.tooltip" />
</CardTitle>
{tooltips.map((tooltip, i) => {
return (
<TooltipItem key={`tooltip_${i}`} item={tooltip} id={i} />
);
})}
</CardBody>
</Card>
</Colxx>
</Row>
</>
);
};
export default PopoverTooltipUi;
|
from rest_framework.generics import RetrieveAPIView, RetrieveUpdateDestroyAPIView, ListCreateAPIView
from rest_framework import permissions
from api.models import PDUser, Scenario
from api.serializers import LevelSerializer, PDUserSerializer
from api.permissions import IsOwnerOrReadOnly
class UserList(ListCreateAPIView):
queryset = PDUser.objects.all()
serializer_class = PDUserSerializer
class UserDetail(RetrieveAPIView):
queryset = PDUser.objects.all()
serializer_class = PDUserSerializer
class LevelList(ListCreateAPIView):
queryset = Scenario.objects.all()
serializer_class = LevelSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
def perform_create(self, serializer):
owner = PDUser.objects.get(user_id=self.request.user.id)
serializer.save(owner=owner)
class LevelDetail(RetrieveUpdateDestroyAPIView):
queryset = Scenario.objects.all()
serializer_class = LevelSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrReadOnly)
'''class LevelList(APIView):
permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
def get(self, request, format=None):
levels = Level.objects.all()
serializer = LevelSerializer(levels, many=True)
return Response(serializer.data)
def post(self, request, format=None):
serializer = LevelSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
class LevelDetail(APIView):
permission_classes = (permissions.IsAuthenticatedOrReadOnly,)
def get_object(self, pk):
try:
return Level.objects.get(pk=pk)
except Level.DoesNotExist:
raise Http404
def get(self, request, pk, format=None):
level = self.get_object(pk)
serializer = LevelSerializer(level)
return Response(serializer.data)
def put(self, request, pk, format=None):
snippet = self.get_object(pk)
level = LevelSerializer(snippet, data=request.data)
if level.is_valid():
level.save()
return Response(level.data)
return Response(level.errors, status=status.HTTP_400_BAD_REQUEST)
def delete(self, request, pk, format=None):
level = self.get_object(pk)
level.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
'''
|
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.rexloadingprogressplugin = factory());
})(this, (function () { 'use strict';
function _regeneratorRuntime() {
/*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */
_regeneratorRuntime = function () {
return exports;
};
var exports = {},
Op = Object.prototype,
hasOwn = Op.hasOwnProperty,
$Symbol = "function" == typeof Symbol ? Symbol : {},
iteratorSymbol = $Symbol.iterator || "@@iterator",
asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator",
toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
function define(obj, key, value) {
return Object.defineProperty(obj, key, {
value: value,
enumerable: !0,
configurable: !0,
writable: !0
}), obj[key];
}
try {
define({}, "");
} catch (err) {
define = function (obj, key, value) {
return obj[key] = value;
};
}
function wrap(innerFn, outerFn, self, tryLocsList) {
var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator,
generator = Object.create(protoGenerator.prototype),
context = new Context(tryLocsList || []);
return generator._invoke = function (innerFn, self, context) {
var state = "suspendedStart";
return function (method, arg) {
if ("executing" === state) throw new Error("Generator is already running");
if ("completed" === state) {
if ("throw" === method) throw arg;
return doneResult();
}
for (context.method = method, context.arg = arg;;) {
var delegate = context.delegate;
if (delegate) {
var delegateResult = maybeInvokeDelegate(delegate, context);
if (delegateResult) {
if (delegateResult === ContinueSentinel) continue;
return delegateResult;
}
}
if ("next" === context.method) context.sent = context._sent = context.arg;else if ("throw" === context.method) {
if ("suspendedStart" === state) throw state = "completed", context.arg;
context.dispatchException(context.arg);
} else "return" === context.method && context.abrupt("return", context.arg);
state = "executing";
var record = tryCatch(innerFn, self, context);
if ("normal" === record.type) {
if (state = context.done ? "completed" : "suspendedYield", record.arg === ContinueSentinel) continue;
return {
value: record.arg,
done: context.done
};
}
"throw" === record.type && (state = "completed", context.method = "throw", context.arg = record.arg);
}
};
}(innerFn, self, context), generator;
}
function tryCatch(fn, obj, arg) {
try {
return {
type: "normal",
arg: fn.call(obj, arg)
};
} catch (err) {
return {
type: "throw",
arg: err
};
}
}
exports.wrap = wrap;
var ContinueSentinel = {};
function Generator() {}
function GeneratorFunction() {}
function GeneratorFunctionPrototype() {}
var IteratorPrototype = {};
define(IteratorPrototype, iteratorSymbol, function () {
return this;
});
var getProto = Object.getPrototypeOf,
NativeIteratorPrototype = getProto && getProto(getProto(values([])));
NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol) && (IteratorPrototype = NativeIteratorPrototype);
var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype);
function defineIteratorMethods(prototype) {
["next", "throw", "return"].forEach(function (method) {
define(prototype, method, function (arg) {
return this._invoke(method, arg);
});
});
}
function AsyncIterator(generator, PromiseImpl) {
function invoke(method, arg, resolve, reject) {
var record = tryCatch(generator[method], generator, arg);
if ("throw" !== record.type) {
var result = record.arg,
value = result.value;
return value && "object" == typeof value && hasOwn.call(value, "__await") ? PromiseImpl.resolve(value.__await).then(function (value) {
invoke("next", value, resolve, reject);
}, function (err) {
invoke("throw", err, resolve, reject);
}) : PromiseImpl.resolve(value).then(function (unwrapped) {
result.value = unwrapped, resolve(result);
}, function (error) {
return invoke("throw", error, resolve, reject);
});
}
reject(record.arg);
}
var previousPromise;
this._invoke = function (method, arg) {
function callInvokeWithMethodAndArg() {
return new PromiseImpl(function (resolve, reject) {
invoke(method, arg, resolve, reject);
});
}
return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
};
}
function maybeInvokeDelegate(delegate, context) {
var method = delegate.iterator[context.method];
if (undefined === method) {
if (context.delegate = null, "throw" === context.method) {
if (delegate.iterator.return && (context.method = "return", context.arg = undefined, maybeInvokeDelegate(delegate, context), "throw" === context.method)) return ContinueSentinel;
context.method = "throw", context.arg = new TypeError("The iterator does not provide a 'throw' method");
}
return ContinueSentinel;
}
var record = tryCatch(method, delegate.iterator, context.arg);
if ("throw" === record.type) return context.method = "throw", context.arg = record.arg, context.delegate = null, ContinueSentinel;
var info = record.arg;
return info ? info.done ? (context[delegate.resultName] = info.value, context.next = delegate.nextLoc, "return" !== context.method && (context.method = "next", context.arg = undefined), context.delegate = null, ContinueSentinel) : info : (context.method = "throw", context.arg = new TypeError("iterator result is not an object"), context.delegate = null, ContinueSentinel);
}
function pushTryEntry(locs) {
var entry = {
tryLoc: locs[0]
};
1 in locs && (entry.catchLoc = locs[1]), 2 in locs && (entry.finallyLoc = locs[2], entry.afterLoc = locs[3]), this.tryEntries.push(entry);
}
function resetTryEntry(entry) {
var record = entry.completion || {};
record.type = "normal", delete record.arg, entry.completion = record;
}
function Context(tryLocsList) {
this.tryEntries = [{
tryLoc: "root"
}], tryLocsList.forEach(pushTryEntry, this), this.reset(!0);
}
function values(iterable) {
if (iterable) {
var iteratorMethod = iterable[iteratorSymbol];
if (iteratorMethod) return iteratorMethod.call(iterable);
if ("function" == typeof iterable.next) return iterable;
if (!isNaN(iterable.length)) {
var i = -1,
next = function next() {
for (; ++i < iterable.length;) if (hasOwn.call(iterable, i)) return next.value = iterable[i], next.done = !1, next;
return next.value = undefined, next.done = !0, next;
};
return next.next = next;
}
}
return {
next: doneResult
};
}
function doneResult() {
return {
value: undefined,
done: !0
};
}
return GeneratorFunction.prototype = GeneratorFunctionPrototype, define(Gp, "constructor", GeneratorFunctionPrototype), define(GeneratorFunctionPrototype, "constructor", GeneratorFunction), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"), exports.isGeneratorFunction = function (genFun) {
var ctor = "function" == typeof genFun && genFun.constructor;
return !!ctor && (ctor === GeneratorFunction || "GeneratorFunction" === (ctor.displayName || ctor.name));
}, exports.mark = function (genFun) {
return Object.setPrototypeOf ? Object.setPrototypeOf(genFun, GeneratorFunctionPrototype) : (genFun.__proto__ = GeneratorFunctionPrototype, define(genFun, toStringTagSymbol, "GeneratorFunction")), genFun.prototype = Object.create(Gp), genFun;
}, exports.awrap = function (arg) {
return {
__await: arg
};
}, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, asyncIteratorSymbol, function () {
return this;
}), exports.AsyncIterator = AsyncIterator, exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) {
void 0 === PromiseImpl && (PromiseImpl = Promise);
var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl);
return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) {
return result.done ? result.value : iter.next();
});
}, defineIteratorMethods(Gp), define(Gp, toStringTagSymbol, "Generator"), define(Gp, iteratorSymbol, function () {
return this;
}), define(Gp, "toString", function () {
return "[object Generator]";
}), exports.keys = function (object) {
var keys = [];
for (var key in object) keys.push(key);
return keys.reverse(), function next() {
for (; keys.length;) {
var key = keys.pop();
if (key in object) return next.value = key, next.done = !1, next;
}
return next.done = !0, next;
};
}, exports.values = values, Context.prototype = {
constructor: Context,
reset: function (skipTempReset) {
if (this.prev = 0, this.next = 0, this.sent = this._sent = undefined, this.done = !1, this.delegate = null, this.method = "next", this.arg = undefined, this.tryEntries.forEach(resetTryEntry), !skipTempReset) for (var name in this) "t" === name.charAt(0) && hasOwn.call(this, name) && !isNaN(+name.slice(1)) && (this[name] = undefined);
},
stop: function () {
this.done = !0;
var rootRecord = this.tryEntries[0].completion;
if ("throw" === rootRecord.type) throw rootRecord.arg;
return this.rval;
},
dispatchException: function (exception) {
if (this.done) throw exception;
var context = this;
function handle(loc, caught) {
return record.type = "throw", record.arg = exception, context.next = loc, caught && (context.method = "next", context.arg = undefined), !!caught;
}
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i],
record = entry.completion;
if ("root" === entry.tryLoc) return handle("end");
if (entry.tryLoc <= this.prev) {
var hasCatch = hasOwn.call(entry, "catchLoc"),
hasFinally = hasOwn.call(entry, "finallyLoc");
if (hasCatch && hasFinally) {
if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
} else if (hasCatch) {
if (this.prev < entry.catchLoc) return handle(entry.catchLoc, !0);
} else {
if (!hasFinally) throw new Error("try statement without catch or finally");
if (this.prev < entry.finallyLoc) return handle(entry.finallyLoc);
}
}
}
},
abrupt: function (type, arg) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) {
var finallyEntry = entry;
break;
}
}
finallyEntry && ("break" === type || "continue" === type) && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc && (finallyEntry = null);
var record = finallyEntry ? finallyEntry.completion : {};
return record.type = type, record.arg = arg, finallyEntry ? (this.method = "next", this.next = finallyEntry.finallyLoc, ContinueSentinel) : this.complete(record);
},
complete: function (record, afterLoc) {
if ("throw" === record.type) throw record.arg;
return "break" === record.type || "continue" === record.type ? this.next = record.arg : "return" === record.type ? (this.rval = this.arg = record.arg, this.method = "return", this.next = "end") : "normal" === record.type && afterLoc && (this.next = afterLoc), ContinueSentinel;
},
finish: function (finallyLoc) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.finallyLoc === finallyLoc) return this.complete(entry.completion, entry.afterLoc), resetTryEntry(entry), ContinueSentinel;
}
},
catch: function (tryLoc) {
for (var i = this.tryEntries.length - 1; i >= 0; --i) {
var entry = this.tryEntries[i];
if (entry.tryLoc === tryLoc) {
var record = entry.completion;
if ("throw" === record.type) {
var thrown = record.arg;
resetTryEntry(entry);
}
return thrown;
}
}
throw new Error("illegal catch attempt");
},
delegateYield: function (iterable, resultName, nextLoc) {
return this.delegate = {
iterator: values(iterable),
resultName: resultName,
nextLoc: nextLoc
}, "next" === this.method && (this.arg = undefined), ContinueSentinel;
}
}, exports;
}
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
function _asyncToGenerator(fn) {
return function () {
var self = this,
args = arguments;
return new Promise(function (resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
Object.defineProperty(Constructor, "prototype", {
writable: false
});
return Constructor;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
Object.defineProperty(subClass, "prototype", {
writable: false
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _isNativeReflectConstruct() {
if (typeof Reflect === "undefined" || !Reflect.construct) return false;
if (Reflect.construct.sham) return false;
if (typeof Proxy === "function") return true;
try {
Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
return true;
} catch (e) {
return false;
}
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _possibleConstructorReturn(self, call) {
if (call && (typeof call === "object" || typeof call === "function")) {
return call;
} else if (call !== void 0) {
throw new TypeError("Derived constructors may only return object or undefined");
}
return _assertThisInitialized(self);
}
function _createSuper(Derived) {
var hasNativeReflectConstruct = _isNativeReflectConstruct();
return function _createSuperInternal() {
var Super = _getPrototypeOf(Derived),
result;
if (hasNativeReflectConstruct) {
var NewTarget = _getPrototypeOf(this).constructor;
result = Reflect.construct(Super, arguments, NewTarget);
} else {
result = Super.apply(this, arguments);
}
return _possibleConstructorReturn(this, result);
};
}
var FILE_POPULATED = Phaser.Loader.FILE_POPULATED;
var UUID = Phaser.Utils.String.UUID;
var AwaitFile = /*#__PURE__*/function (_Phaser$Loader$File) {
_inherits(AwaitFile, _Phaser$Loader$File);
var _super = _createSuper(AwaitFile);
function AwaitFile(loader, fileConfig) {
_classCallCheck(this, AwaitFile);
if (!fileConfig.hasOwnProperty('type')) {
fileConfig.type = 'await';
}
if (!fileConfig.hasOwnProperty('url')) {
fileConfig.url = '';
}
if (!fileConfig.hasOwnProperty('key')) {
fileConfig.key = UUID();
}
return _super.call(this, loader, fileConfig);
}
_createClass(AwaitFile, [{
key: "load",
value: function load() {
if (this.state === FILE_POPULATED) {
// Can happen for example in a JSONFile if they've provided a JSON object instead of a URL
this.loader.nextFile(this, true);
} else {
// start loading task
var config = this.config;
var callback = config.callback;
var scope = config.scope;
var successCallback = this.onLoad.bind(this);
var failureCallback = this.onError.bind(this);
if (callback) {
if (scope) {
callback.call(scope, successCallback, failureCallback);
} else {
callback(successCallback, failureCallback);
}
} else {
this.onLoad();
}
}
}
}, {
key: "onLoad",
value: function onLoad() {
this.loader.nextFile(this, true);
}
}, {
key: "onError",
value: function onError() {
this.loader.nextFile(this, false);
}
}]);
return AwaitFile;
}(Phaser.Loader.File);
var IsFunction = function IsFunction(obj) {
return obj && typeof obj === 'function';
};
var IsPlainObject = Phaser.Utils.Objects.IsPlainObject;
var loaderCallback = function loaderCallback(key, config) {
if (IsFunction(key)) {
var callback = key;
var scope = config;
config = {
config: {
callback: callback,
scope: scope
}
};
} else if (IsPlainObject(key)) {
config = key;
if (!config.hasOwnProperty('config')) {
config = {
config: config
};
}
} else {
config = {
key: key,
config: config
};
}
this.addFile(new AwaitFile(this, config));
return this;
};
var WaitEvent = function WaitEvent(eventEmitter, eventName) {
return new Promise(function (resolve, reject) {
eventEmitter.once(eventName, function () {
resolve();
});
});
};
var NOOP = function NOOP() {// NOOP
};
var GetValue = Phaser.Utils.Objects.GetValue;
var LoadingProgress = function LoadingProgress(gameObject, config) {
var TransitionInCallback = GetValue(config, 'transitIn', NOOP);
var ProgressCallback = GetValue(config, 'progress', NOOP);
var TransitionOutCallback = GetValue(config, 'transitionOut', NOOP);
var scene = gameObject.scene; // Register AwaitLoader
if (!scene.sys.load.rexAwait) {
Phaser.Loader.FileTypesManager.register('rexAwait', loaderCallback);
scene.sys.load.rexAwait = loaderCallback;
} // Add await-task
scene.load.rexAwait( /*#__PURE__*/function () {
var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(successCallback, failureCallback) {
var progress;
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
_context.next = 2;
return TransitionInCallback(gameObject);
case 2:
progress = GetProgress(scene);
if (!(progress < 1)) {
_context.next = 13;
break;
}
case 4:
if (!(progress < 1)) {
_context.next = 11;
break;
}
_context.next = 7;
return WaitEvent(scene.load, 'progress');
case 7:
progress = GetProgress(scene);
ProgressCallback(gameObject, progress);
_context.next = 4;
break;
case 11:
_context.next = 14;
break;
case 13:
// Progress is 1 already
ProgressCallback(gameObject, progress);
case 14:
_context.next = 16;
return TransitionOutCallback(gameObject);
case 16:
gameObject.destroy(); // Finish this loading task, goto create stage
successCallback();
case 18:
case "end":
return _context.stop();
}
}
}, _callee);
}));
return function (_x, _x2) {
return _ref.apply(this, arguments);
};
}());
};
var GetProgress = function GetProgress(scene) {
var loader = scene.load;
var total = loader.totalToLoad - 1;
var remainder = loader.list.size + loader.inflight.size - 1;
var progress = 1 - remainder / total;
return progress;
};
var Delay = function Delay(time, result) {
if (time === undefined) {
time = 0;
}
return new Promise(function (resolve, reject) {
setTimeout(function () {
resolve(result);
}, time);
});
};
var LoadingProgressPlugin = /*#__PURE__*/function (_Phaser$Plugins$BaseP) {
_inherits(LoadingProgressPlugin, _Phaser$Plugins$BaseP);
var _super = _createSuper(LoadingProgressPlugin);
function LoadingProgressPlugin(pluginManager) {
_classCallCheck(this, LoadingProgressPlugin);
return _super.call(this, pluginManager);
}
_createClass(LoadingProgressPlugin, [{
key: "add",
value: function add(gameObject, config) {
LoadingProgress(gameObject, config);
}
}, {
key: "addDelayPromise",
value: function addDelayPromise(time) {
return Delay(time);
}
}]);
return LoadingProgressPlugin;
}(Phaser.Plugins.BasePlugin);
return LoadingProgressPlugin;
}));
|
import { FormGroup, withStyles } from '@material-ui/core';
export default withStyles({
root: {}
})(FormGroup);
|
from glob import glob
import numpy as np
import scipy
import keras
import os
import Network
import utls
import time
import cv2
import argparse
from tqdm import tqdm
from keras.backend.tensorflow_backend import set_session
import tensorflow as tf
config = tf.ConfigProto()
config.gpu_options.allow_growth = True # dynamically grow the memory used on the GPU
sess = tf.Session(config=config)
set_session(sess) # set this TensorFlow session as the default session for Keras
import skimage.transform
def Resizer(image, min_side=608, max_side=1024):
rows, cols, cns = image.shape
smallest_side = min(rows, cols)
# rescale the image so the smallest side is min_side
scale = min_side / smallest_side
# check if the largest side is now greater than max_side, which can happen
# when images have a large aspect ratio
largest_side = max(rows, cols)
if largest_side * scale > max_side:
scale = max_side / largest_side
# resize the image with the computed scale
image = skimage.transform.resize(image, (int(round(rows*scale)), int(round((cols*scale)))))
rows, cols, cns = image.shape
pad_w = 32 - rows%32
pad_h = 32 - cols%32
new_image = np.zeros((rows + pad_w, cols + pad_h, cns)).astype(np.float32)
new_image[:rows, :cols, :] = image.astype(np.float32)
return new_image
parser = argparse.ArgumentParser()
parser.add_argument("--input", "-i", type=str, default='../input', help='test image folder')
parser.add_argument("--result", "-r", type=str, default='../result', help='result folder')
parser.add_argument("--model", "-m", type=str, default='Syn_img_lowlight_withnoise', help='model name')
parser.add_argument("--com", "-c", type=int, default=0, help='output with/without origional image and mid result')
parser.add_argument("--highpercent", "-hp", type=int, default=95, help='should be in [85,100], linear amplification')
parser.add_argument("--lowpercent", "-lp", type=int, default=5, help='should be in [0,15], rescale the range [p%,1] to [0, 1]')
parser.add_argument("--gamma", "-g", type=int, default=8, help='should be in [6,10], increase the saturability')
parser.add_argument("--maxrange", "-mr", type=int, default=8, help='linear amplification range')
arg = parser.parse_args()
result_folder = arg.result
if not os.path.isdir(result_folder):
os.makedirs(result_folder)
input_folder = arg.input
path = glob(input_folder+'/*.*')
model_name = arg.model
mbllen = Network.build_mbllen((None, None, 3))
mbllen.load_weights('../models/'+model_name+'.h5')
opt = keras.optimizers.Adam(lr=2 * 1e-04, beta_1=0.9, beta_2=0.999, epsilon=1e-08)
mbllen.compile(loss='mse', optimizer=opt)
flag = arg.com
lowpercent = arg.lowpercent
highpercent = arg.highpercent
maxrange = arg.maxrange/10.
hsvgamma = arg.gamma/10.
for i in tqdm(range(len(path))):
img_A_path = path[i]
img_A = utls.imread_color(img_A_path)
# add resize
img_A = Resizer(img_A)
img_A = img_A[np.newaxis, :]
starttime = time.clock()
out_pred = mbllen.predict(img_A)
endtime = time.clock()
print('The ' + str(i+1)+'th image\'s Time:' +str(endtime-starttime)+'s.')
fake_B = out_pred[0, :, :, :3]
fake_B_o = fake_B
gray_fake_B = fake_B[:, :, 0] * 0.299 + fake_B[:, :, 1] * 0.587 + fake_B[:, :, 1] * 0.114
percent_max = sum(sum(gray_fake_B >= maxrange))/sum(sum(gray_fake_B <= 1.0))
# print(percent_max)
max_value = np.percentile(gray_fake_B[:], highpercent)
if percent_max < (100-highpercent)/100.:
scale = maxrange / max_value
fake_B = fake_B * scale
fake_B = np.minimum(fake_B, 1.0)
gray_fake_B = fake_B[:,:,0]*0.299 + fake_B[:,:,1]*0.587 + fake_B[:,:,1]*0.114
sub_value = np.percentile(gray_fake_B[:], lowpercent)
fake_B = (fake_B - sub_value)*(1./(1-sub_value))
imgHSV = cv2.cvtColor(fake_B, cv2.COLOR_RGB2HSV)
H, S, V = cv2.split(imgHSV)
S = np.power(S, hsvgamma)
imgHSV = cv2.merge([H, S, V])
fake_B = cv2.cvtColor(imgHSV, cv2.COLOR_HSV2RGB)
fake_B = np.minimum(fake_B, 1.0)
if flag:
outputs = np.concatenate([img_A[0,:,:,:], fake_B_o, fake_B], axis=1)
else:
outputs = fake_B
filename = os.path.basename(path[i])
img_name = result_folder+'/' + filename
# scipy.misc.toimage(outputs * 255, high=255, low=0, cmin=0, cmax=255).save(img_name)
outputs = np.minimum(outputs, 1.0)
outputs = np.maximum(outputs, 0.0)
utls.imwrite(img_name, outputs)
|
!function(r){const e=r["pt-br"]=r["pt-br"]||{};e.dictionary=Object.assign(e.dictionary||{},{"%0 of %1":"%0 de %1",Aquamarine:"Água-marinha",Black:"Preto",Blue:"Azul",Cancel:"Cancelar","Cannot upload file:":"Não foi possível enviar o arquivo:","Dim grey":"Cinza escuro","Dropdown toolbar":"Barra de Ferramentas da Lista Suspensa","Edit block":"Editor de bloco","Editor toolbar":"Ferramentas do Editor",Green:"Verde",Grey:"Cinza","Insert paragraph after block":"Inserir parágrafo após o bloco","Insert paragraph before block":"Inserir parágrafo antes do bloco","Light blue":"Azul claro","Light green":"Verde claro","Light grey":"Cinza claro",Next:"Próximo",Orange:"Laranja",Previous:"Anterior",Purple:"Púrpura",Red:"Vermelho",Redo:"Refazer","Remove color":"Remover cor","Restore default":"Restaurar padrão","Rich Text Editor":"Editor de Formatação","Rich Text Editor, %0":"Editor de Formatação, %0",Save:"Salvar","Select all":"Selecionar tudo","Show more items":"Exibir mais itens",Turquoise:"Turquesa",Undo:"Desfazer","Upload in progress":"Enviando dados",White:"Branco","Widget toolbar":"Ferramentas de Widgets",Yellow:"Amarelo"}),e.getPluralForm=function(r){return r>1}}(window.CKEDITOR_TRANSLATIONS||(window.CKEDITOR_TRANSLATIONS={}));
|
/* eslint-disable no-console */
/* eslint-disable no-unused-vars */
/* eslint-disable react/prop-types */
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import Button from '../Button';
import Main from '../Main';
import { cepMask } from '../Form/mask';
import './help.css';
export default function RequestHelp() {
const [volunteers, setVolunteers] = useState([{}]);
const [check, setCheck] = useState(true);
const [cidade, setCidade] = useState('');
const [cep, setCep] = useState('');
async function validadeCep() {
if (cep && cep.length >= 8) {
const response = await axios.get(`https://viacep.com.br/ws/${cep}/json/`);
setCidade(response.data.localidade);
setCheck(true);
} else {
setCidade('');
setCheck(false);
}
}
async function loadVoluntaresCep(event) {
event.preventDefault();
const response = await axios.get(
`https://apirest-covol19.herokuapp.com//voluntariarse/voluntarios/localidade/${cidade}`
);
setVolunteers(response.data);
// console.log(response.data.length);
setCep('');
setCidade('');
}
function localization() {
const options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0,
};
async function success(pos) {
const crd = pos.coords;
try {
const response = await axios.get(
`https://nominatim.openstreetmap.org/reverse?format=json&lat=${crd.latitude}&lon=${crd.longitude}`
);
// console.log(response.data) descomenta pra "Debugar" e entender se o fluxo ta seguindo
try {
const responseVol = await axios.get(
`https://apirest-covol19.herokuapp.com//voluntariarse/voluntarios/localidade/${response.data.address.city_district}`
);
setVolunteers(responseVol.data);
// console.log(responseVol) descomenta pra "Debugar" e entender se o fluxo ta seguindo
} catch (errApi) {
console.error('Erro na API', errApi);
}
} catch (errLoc) {
console.error('Erro na localização', errLoc);
}
}
function error(err) {
console.warn(`ERROR(${err.code}): ${err.message}`);
}
navigator.geolocation.getCurrentPosition(success, error, options);
}
useEffect(() => {
localization();
}, []);
return (
<>
<div>
<section className="formA hideA" data-netlify="true" name="filtragem">
<h2>Preciso de Ajuda</h2>
<form onSubmit={loadVoluntaresCep}>
<div>
<div className="cep-container">
{!check ? <p>Cep Inválido</p> : <p />}
<input
type="text"
required
maxLength="8"
name="cep"
value={cep}
onChange={event => setCep(cepMask(event.target.value))}
placeholder="Cep"
/>
</div>
<input
type="text"
required
name="cidade"
value={cidade}
onChange={event => setCidade(event.target.value)}
onFocus={validadeCep}
placeholder="Cidade"
/>
</div>
<Button type="submit">Listar voluntários</Button>
</form>
</section>
</div>
<Main volunteers={volunteers} />
</>
);
}
|
# coding: utf-8
import pandas as pd
import matplotlib.pyplot as plt
from mlxtend.plotting import scatterplotmatrix
import numpy as np
from mlxtend.plotting import heatmap
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LinearRegression
from sklearn.linear_model import RANSACRegressor
from sklearn.model_selection import train_test_split
import scipy as sp
from sklearn.metrics import r2_score
from sklearn.metrics import mean_squared_error
from sklearn.linear_model import Lasso
from sklearn.linear_model import Ridge
from sklearn.linear_model import ElasticNet
from sklearn.preprocessing import PolynomialFeatures
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import RandomForestRegressor
# *Python Machine Learning 3rd Edition* by [Sebastian Raschka](https://sebastianraschka.com), Packt Publishing Ltd. 2019
#
# Code Repository: https://github.com/rasbt/python-machine-learning-book-3rd-edition
#
# Code License: [MIT License](https://github.com/rasbt/python-machine-learning-book-3rd-edition/blob/master/LICENSE.txt)
# # Python Machine Learning - Code Examples
# # Chapter 10 - Predicting Continuous Target Variables with Regression Analysis
# Note that the optional watermark extension is a small IPython notebook plugin that I developed to make the code reproducible. You can just skip the following line(s).
# *The use of `watermark` is optional. You can install this IPython extension via "`pip install watermark`". For more information, please see: https://github.com/rasbt/watermark.*
# The mlxtend package (http://rasbt.github.io/mlxtend/), which contains a few useful functions on top of scikit-learn and matplotloib, can be installed via
#
# conda install mlxtend
#
# or
#
# pip install mlxtend
# ### Overview
# - [Introducing regression](#Introducing-linear-regression)
# - [Simple linear regression](#Simple-linear-regression)
# - [Exploring the Housing Dataset](#Exploring-the-Housing-Dataset)
# - [Loading the Housing dataset into a data frame](Loading-the-Housing-dataset-into-a-data-frame)
# - [Visualizing the important characteristics of a dataset](#Visualizing-the-important-characteristics-of-a-dataset)
# - [Implementing an ordinary least squares linear regression model](#Implementing-an-ordinary-least-squares-linear-regression-model)
# - [Solving regression for regression parameters with gradient descent](#Solving-regression-for-regression-parameters-with-gradient-descent)
# - [Estimating the coefficient of a regression model via scikit-learn](#Estimating-the-coefficient-of-a-regression-model-via-scikit-learn)
# - [Fitting a robust regression model using RANSAC](#Fitting-a-robust-regression-model-using-RANSAC)
# - [Evaluating the performance of linear regression models](#Evaluating-the-performance-of-linear-regression-models)
# - [Using regularized methods for regression](#Using-regularized-methods-for-regression)
# - [Turning a linear regression model into a curve - polynomial regression](#Turning-a-linear-regression-model-into-a-curve---polynomial-regression)
# - [Modeling nonlinear relationships in the Housing Dataset](#Modeling-nonlinear-relationships-in-the-Housing-Dataset)
# - [Dealing with nonlinear relationships using random forests](#Dealing-with-nonlinear-relationships-using-random-forests)
# - [Decision tree regression](#Decision-tree-regression)
# - [Random forest regression](#Random-forest-regression)
# - [Summary](#Summary)
# # Introducing linear regression
# ## Simple linear regression
# ## Multiple linear regression
# # Exploring the Housing dataset
# ## Loading the Housing dataset into a data frame
# Description, which was previously available at: [https://archive.ics.uci.edu/ml/datasets/Housing](https://archive.ics.uci.edu/ml/datasets/Housing)
#
# Attributes:
#
# <pre>
# 1. CRIM per capita crime rate by town
# 2. ZN proportion of residential land zoned for lots over
# 25,000 sq.ft.
# 3. INDUS proportion of non-retail business acres per town
# 4. CHAS Charles River dummy variable (= 1 if tract bounds
# river; 0 otherwise)
# 5. NOX nitric oxides concentration (parts per 10 million)
# 6. RM average number of rooms per dwelling
# 7. AGE proportion of owner-occupied units built prior to 1940
# 8. DIS weighted distances to five Boston employment centres
# 9. RAD index of accessibility to radial highways
# 10. TAX full-value property-tax rate per $10,000
# 11. PTRATIO pupil-teacher ratio by town
# 12. B 1000(Bk - 0.63)^2 where Bk is the proportion of blacks
# by town
# 13. LSTAT % lower status of the population
# 14. MEDV Median value of owner-occupied homes in $1000s
# </pre>
df = pd.read_csv('https://raw.githubusercontent.com/rasbt/'
'python-machine-learning-book-3rd-edition/'
'master/ch10/housing.data.txt',
header=None,
sep='\s+')
df.columns = ['CRIM', 'ZN', 'INDUS', 'CHAS',
'NOX', 'RM', 'AGE', 'DIS', 'RAD',
'TAX', 'PTRATIO', 'B', 'LSTAT', 'MEDV']
df.head()
#
# ### Note:
#
#
# You can find a copy of the housing dataset (and all other datasets used in this book) in the code bundle of this book, which you can use if you are working offline or the UCI server at https://archive.ics.uci.edu/ml/machine-learning-databases/housing/housing.data is temporarily unavailable. For instance, to load the housing dataset from a local directory, you can replace the lines
# df = pd.read_csv('https://archive.ics.uci.edu/ml/'
# 'machine-learning-databases'
# '/housing/housing.data',
# sep='\s+')
# in the following code example by
# df = pd.read_csv('./housing.data',
# sep='\s+')
# ## Visualizing the important characteristics of a dataset
cols = ['LSTAT', 'INDUS', 'NOX', 'RM', 'MEDV']
scatterplotmatrix(df[cols].values, figsize=(10, 8),
names=cols, alpha=0.5)
plt.tight_layout()
#plt.savefig('images/10_03.png', dpi=300)
plt.show()
cm = np.corrcoef(df[cols].values.T)
hm = heatmap(cm, row_names=cols, column_names=cols)
# plt.savefig('images/10_04.png', dpi=300)
plt.show()
# # Implementing an ordinary least squares linear regression model
# ...
# ## Solving regression for regression parameters with gradient descent
class LinearRegressionGD(object):
def __init__(self, eta=0.001, n_iter=20):
self.eta = eta
self.n_iter = n_iter
def fit(self, X, y):
self.w_ = np.zeros(1 + X.shape[1])
self.cost_ = []
for _ in range(self.n_iter):
output = self.net_input(X)
errors = (y - output)
self.w_[1:] += self.eta * X.T.dot(errors)
self.w_[0] += self.eta * errors.sum()
cost = (errors**2).sum() / 2.0
self.cost_.append(cost)
return self
def net_input(self, X):
return np.dot(X, self.w_[1:]) + self.w_[0]
def predict(self, X):
return self.net_input(X)
X = df[['RM']].values
y = df['MEDV'].values
sc_x = StandardScaler()
sc_y = StandardScaler()
X_std = sc_x.fit_transform(X)
y_std = sc_y.fit_transform(y[:, np.newaxis]).flatten()
lr = LinearRegressionGD()
lr.fit(X_std, y_std)
plt.plot(range(1, lr.n_iter+1), lr.cost_)
plt.ylabel('SSE')
plt.xlabel('Epoch')
#plt.tight_layout()
#plt.savefig('images/10_05.png', dpi=300)
plt.show()
def lin_regplot(X, y, model):
plt.scatter(X, y, c='steelblue', edgecolor='white', s=70)
plt.plot(X, model.predict(X), color='black', lw=2)
return
lin_regplot(X_std, y_std, lr)
plt.xlabel('Average number of rooms [RM] (standardized)')
plt.ylabel('Price in $1000s [MEDV] (standardized)')
#plt.savefig('images/10_06.png', dpi=300)
plt.show()
print('Slope: %.3f' % lr.w_[1])
print('Intercept: %.3f' % lr.w_[0])
num_rooms_std = sc_x.transform(np.array([[5.0]]))
price_std = lr.predict(num_rooms_std)
print("Price in $1000s: %.3f" % sc_y.inverse_transform(price_std))
# ## Estimating the coefficient of a regression model via scikit-learn
slr = LinearRegression()
slr.fit(X, y)
y_pred = slr.predict(X)
print('Slope: %.3f' % slr.coef_[0])
print('Intercept: %.3f' % slr.intercept_)
lin_regplot(X, y, slr)
plt.xlabel('Average number of rooms [RM]')
plt.ylabel('Price in $1000s [MEDV]')
#plt.savefig('images/10_07.png', dpi=300)
plt.show()
# **Normal Equations** alternative:
# adding a column vector of "ones"
Xb = np.hstack((np.ones((X.shape[0], 1)), X))
w = np.zeros(X.shape[1])
z = np.linalg.inv(np.dot(Xb.T, Xb))
w = np.dot(z, np.dot(Xb.T, y))
print('Slope: %.3f' % w[1])
print('Intercept: %.3f' % w[0])
# # Fitting a robust regression model using RANSAC
ransac = RANSACRegressor(LinearRegression(),
max_trials=100,
min_samples=50,
loss='absolute_loss',
residual_threshold=5.0,
random_state=0)
ransac.fit(X, y)
inlier_mask = ransac.inlier_mask_
outlier_mask = np.logical_not(inlier_mask)
line_X = np.arange(3, 10, 1)
line_y_ransac = ransac.predict(line_X[:, np.newaxis])
plt.scatter(X[inlier_mask], y[inlier_mask],
c='steelblue', edgecolor='white',
marker='o', label='Inliers')
plt.scatter(X[outlier_mask], y[outlier_mask],
c='limegreen', edgecolor='white',
marker='s', label='Outliers')
plt.plot(line_X, line_y_ransac, color='black', lw=2)
plt.xlabel('Average number of rooms [RM]')
plt.ylabel('Price in $1000s [MEDV]')
plt.legend(loc='upper left')
#plt.savefig('images/10_08.png', dpi=300)
plt.show()
print('Slope: %.3f' % ransac.estimator_.coef_[0])
print('Intercept: %.3f' % ransac.estimator_.intercept_)
# # Evaluating the performance of linear regression models
X = df.iloc[:, :-1].values
y = df['MEDV'].values
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, random_state=0)
slr = LinearRegression()
slr.fit(X_train, y_train)
y_train_pred = slr.predict(X_train)
y_test_pred = slr.predict(X_test)
ary = np.array(range(100000))
plt.scatter(y_train_pred, y_train_pred - y_train,
c='steelblue', marker='o', edgecolor='white',
label='Training data')
plt.scatter(y_test_pred, y_test_pred - y_test,
c='limegreen', marker='s', edgecolor='white',
label='Test data')
plt.xlabel('Predicted values')
plt.ylabel('Residuals')
plt.legend(loc='upper left')
plt.hlines(y=0, xmin=-10, xmax=50, color='black', lw=2)
plt.xlim([-10, 50])
plt.tight_layout()
# plt.savefig('images/10_09.png', dpi=300)
plt.show()
print('MSE train: %.3f, test: %.3f' % (
mean_squared_error(y_train, y_train_pred),
mean_squared_error(y_test, y_test_pred)))
print('R^2 train: %.3f, test: %.3f' % (
r2_score(y_train, y_train_pred),
r2_score(y_test, y_test_pred)))
# # Using regularized methods for regression
lasso = Lasso(alpha=0.1)
lasso.fit(X_train, y_train)
y_train_pred = lasso.predict(X_train)
y_test_pred = lasso.predict(X_test)
print(lasso.coef_)
print('MSE train: %.3f, test: %.3f' % (
mean_squared_error(y_train, y_train_pred),
mean_squared_error(y_test, y_test_pred)))
print('R^2 train: %.3f, test: %.3f' % (
r2_score(y_train, y_train_pred),
r2_score(y_test, y_test_pred)))
# Ridge regression:
ridge = Ridge(alpha=1.0)
# LASSO regression:
lasso = Lasso(alpha=1.0)
# Elastic Net regression:
elanet = ElasticNet(alpha=1.0, l1_ratio=0.5)
# # Turning a linear regression model into a curve - polynomial regression
X = np.array([258.0, 270.0, 294.0,
320.0, 342.0, 368.0,
396.0, 446.0, 480.0, 586.0])\
[:, np.newaxis]
y = np.array([236.4, 234.4, 252.8,
298.6, 314.2, 342.2,
360.8, 368.0, 391.2,
390.8])
lr = LinearRegression()
pr = LinearRegression()
quadratic = PolynomialFeatures(degree=2)
X_quad = quadratic.fit_transform(X)
# fit linear features
lr.fit(X, y)
X_fit = np.arange(250, 600, 10)[:, np.newaxis]
y_lin_fit = lr.predict(X_fit)
# fit quadratic features
pr.fit(X_quad, y)
y_quad_fit = pr.predict(quadratic.fit_transform(X_fit))
# plot results
plt.scatter(X, y, label='Training points')
plt.plot(X_fit, y_lin_fit, label='Linear fit', linestyle='--')
plt.plot(X_fit, y_quad_fit, label='Quadratic fit')
plt.xlabel('Explanatory variable')
plt.ylabel('Predicted or known target values')
plt.legend(loc='upper left')
plt.tight_layout()
#plt.savefig('images/10_11.png', dpi=300)
plt.show()
y_lin_pred = lr.predict(X)
y_quad_pred = pr.predict(X_quad)
print('Training MSE linear: %.3f, quadratic: %.3f' % (
mean_squared_error(y, y_lin_pred),
mean_squared_error(y, y_quad_pred)))
print('Training R^2 linear: %.3f, quadratic: %.3f' % (
r2_score(y, y_lin_pred),
r2_score(y, y_quad_pred)))
# ## Modeling nonlinear relationships in the Housing Dataset
X = df[['LSTAT']].values
y = df['MEDV'].values
regr = LinearRegression()
# create quadratic features
quadratic = PolynomialFeatures(degree=2)
cubic = PolynomialFeatures(degree=3)
X_quad = quadratic.fit_transform(X)
X_cubic = cubic.fit_transform(X)
# fit features
X_fit = np.arange(X.min(), X.max(), 1)[:, np.newaxis]
regr = regr.fit(X, y)
y_lin_fit = regr.predict(X_fit)
linear_r2 = r2_score(y, regr.predict(X))
regr = regr.fit(X_quad, y)
y_quad_fit = regr.predict(quadratic.fit_transform(X_fit))
quadratic_r2 = r2_score(y, regr.predict(X_quad))
regr = regr.fit(X_cubic, y)
y_cubic_fit = regr.predict(cubic.fit_transform(X_fit))
cubic_r2 = r2_score(y, regr.predict(X_cubic))
# plot results
plt.scatter(X, y, label='Training points', color='lightgray')
plt.plot(X_fit, y_lin_fit,
label='Linear (d=1), $R^2=%.2f$' % linear_r2,
color='blue',
lw=2,
linestyle=':')
plt.plot(X_fit, y_quad_fit,
label='Quadratic (d=2), $R^2=%.2f$' % quadratic_r2,
color='red',
lw=2,
linestyle='-')
plt.plot(X_fit, y_cubic_fit,
label='Cubic (d=3), $R^2=%.2f$' % cubic_r2,
color='green',
lw=2,
linestyle='--')
plt.xlabel('% lower status of the population [LSTAT]')
plt.ylabel('Price in $1000s [MEDV]')
plt.legend(loc='upper right')
#plt.savefig('images/10_12.png', dpi=300)
plt.show()
# Transforming the dataset:
X = df[['LSTAT']].values
y = df['MEDV'].values
# transform features
X_log = np.log(X)
y_sqrt = np.sqrt(y)
# fit features
X_fit = np.arange(X_log.min()-1, X_log.max()+1, 1)[:, np.newaxis]
regr = regr.fit(X_log, y_sqrt)
y_lin_fit = regr.predict(X_fit)
linear_r2 = r2_score(y_sqrt, regr.predict(X_log))
# plot results
plt.scatter(X_log, y_sqrt, label='Training points', color='lightgray')
plt.plot(X_fit, y_lin_fit,
label='Linear (d=1), $R^2=%.2f$' % linear_r2,
color='blue',
lw=2)
plt.xlabel('log(% lower status of the population [LSTAT])')
plt.ylabel('$\sqrt{Price \; in \; \$1000s \; [MEDV]}$')
plt.legend(loc='lower left')
plt.tight_layout()
#plt.savefig('images/10_13.png', dpi=300)
plt.show()
# # Dealing with nonlinear relationships using random forests
# ...
# ## Decision tree regression
X = df[['LSTAT']].values
y = df['MEDV'].values
tree = DecisionTreeRegressor(max_depth=3)
tree.fit(X, y)
sort_idx = X.flatten().argsort()
lin_regplot(X[sort_idx], y[sort_idx], tree)
plt.xlabel('% lower status of the population [LSTAT]')
plt.ylabel('Price in $1000s [MEDV]')
#plt.savefig('images/10_14.png', dpi=300)
plt.show()
# ## Random forest regression
X = df.iloc[:, :-1].values
y = df['MEDV'].values
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.4, random_state=1)
forest = RandomForestRegressor(n_estimators=1000,
criterion='mse',
random_state=1,
n_jobs=-1)
forest.fit(X_train, y_train)
y_train_pred = forest.predict(X_train)
y_test_pred = forest.predict(X_test)
print('MSE train: %.3f, test: %.3f' % (
mean_squared_error(y_train, y_train_pred),
mean_squared_error(y_test, y_test_pred)))
print('R^2 train: %.3f, test: %.3f' % (
r2_score(y_train, y_train_pred),
r2_score(y_test, y_test_pred)))
plt.scatter(y_train_pred,
y_train_pred - y_train,
c='steelblue',
edgecolor='white',
marker='o',
s=35,
alpha=0.9,
label='Training data')
plt.scatter(y_test_pred,
y_test_pred - y_test,
c='limegreen',
edgecolor='white',
marker='s',
s=35,
alpha=0.9,
label='Test data')
plt.xlabel('Predicted values')
plt.ylabel('Residuals')
plt.legend(loc='upper left')
plt.hlines(y=0, xmin=-10, xmax=50, lw=2, color='black')
plt.xlim([-10, 50])
plt.tight_layout()
#plt.savefig('images/10_15.png', dpi=300)
plt.show()
# # Summary
# ...
# ---
#
# Readers may ignore the next cell.
|
module.exports = {
"extends": [
"@commitlint/config-conventional"
],
"rules": {
"body-max-line-length": [
0,
"always",
100
],
"type-enum": [
0,
"always",
[
"content",
"docs",
"feat",
"fix",
"layouts",
"refactor",
"test",
"chore",
"wip"
]
]
}
};
|
'use strict';
const {join} = require('path');
const {lstat} = require('fs').promises;
const getCacacheInfo = require('cacache').get.info;
const npmCachePath = require('.');
const test = require('tape');
test('npmCachePath()', async t => {
const path = await npmCachePath();
t.ok(
(await lstat(path)).isDirectory(),
'should get a path to the directory.'
);
t.ok(Number.isSafeInteger((await getCacacheInfo(
join(path, '_cacache'),
`make-fetch-happen:request-cache:https://registry.npmjs.org/eslint/-/eslint-${
require('eslint/package.json').version
}.tgz`
)).size), 'should get a path where packages are cached.');
try {
await npmCachePath('Hi');
t.fail('Unexpectedlt succeeded.');
} catch (err) {
t.equal(
err.toString(),
'RangeError: Expected no arguments, but received 1 arguments.',
'should fail when it takes arguments.'
);
}
t.end();
});
test('npmCachePath() in a non-npm environment', async t => {
delete process.env.npm_lifecycle_event;
delete process.env.npm_config_cache;
const path = await npmCachePath();
t.ok(
(await lstat(path)).isDirectory(),
'should get a path to the directory.'
);
t.ok(Number.isSafeInteger((await getCacacheInfo(
join(path, '_cacache'),
`make-fetch-happen:request-cache:https://registry.npmjs.org/cacache/-/cacache-${
require('cacache/package.json').version
}.tgz`
)).size), 'should get a path where packages are cached.');
t.end();
});
|
# coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..compat import compat_str
from ..utils import (
determine_ext,
ExtractorError,
int_or_none,
)
class HotStarBaseIE(InfoExtractor):
_GEO_COUNTRIES = ['IN']
def _download_json(self, *args, **kwargs):
response = super(HotStarBaseIE, self)._download_json(*args, **kwargs)
if response['resultCode'] != 'OK':
if kwargs.get('fatal'):
raise ExtractorError(
response['errorDescription'], expected=True)
return None
return response['resultObj']
def _download_content_info(self, content_id):
return self._download_json(
'https://account.hotstar.com/AVS/besc', content_id, query={
'action': 'GetAggregatedContentDetails',
'appVersion': '5.0.40',
'channel': 'PCTV',
'contentId': content_id,
})['contentInfo'][0]
class HotStarIE(HotStarBaseIE):
_VALID_URL = r'https?://(?:www\.)?hotstar\.com/(?:.+?[/-])?(?P<id>\d{10})'
_TESTS = [{
'url': 'http://www.hotstar.com/on-air-with-aib--english-1000076273',
'info_dict': {
'id': '1000076273',
'ext': 'mp4',
'title': 'On Air With AIB',
'description': 'md5:c957d8868e9bc793ccb813691cc4c434',
'timestamp': 1447227000,
'upload_date': '20151111',
'duration': 381,
},
'params': {
# m3u8 download
'skip_download': True,
}
}, {
'url': 'http://www.hotstar.com/sports/cricket/rajitha-sizzles-on-debut-with-329/2001477583',
'only_matching': True,
}, {
'url': 'http://www.hotstar.com/1000000515',
'only_matching': True,
}]
def _real_extract(self, url):
video_id = self._match_id(url)
video_data = self._download_content_info(video_id)
title = video_data['episodeTitle']
if video_data.get('encrypted') == 'Y':
raise ExtractorError('This video is DRM protected.', expected=True)
formats = []
for f in ('JIO',):
format_data = self._download_json(
'http://getcdn.hotstar.com/AVS/besc',
video_id, 'Downloading %s JSON metadata' % f,
fatal=False, query={
'action': 'GetCDN',
'asJson': 'Y',
'channel': f,
'id': video_id,
'type': 'VOD',
})
if format_data:
format_url = format_data.get('src')
if not format_url:
continue
ext = determine_ext(format_url)
if ext == 'm3u8':
formats.extend(self._extract_m3u8_formats(
format_url, video_id, 'mp4',
m3u8_id='hls', fatal=False))
elif ext == 'f4m':
# produce broken files
continue
else:
formats.append({
'url': format_url,
'width': int_or_none(format_data.get('width')),
'height': int_or_none(format_data.get('height')),
})
self._sort_formats(formats)
return {
'id': video_id,
'title': title,
'description': video_data.get('description'),
'duration': int_or_none(video_data.get('duration')),
'timestamp': int_or_none(video_data.get('broadcastDate')),
'formats': formats,
'episode': title,
'episode_number': int_or_none(video_data.get('episodeNumber')),
'series': video_data.get('contentTitle'),
}
class HotStarPlaylistIE(HotStarBaseIE):
IE_NAME = 'hotstar:playlist'
_VALID_URL = r'(?P<url>https?://(?:www\.)?hotstar\.com/tv/[^/]+/(?P<content_id>\d+))/(?P<type>[^/]+)/(?P<id>\d+)'
_TESTS = [{
'url': 'http://www.hotstar.com/tv/pratidaan/14982/episodes/14812/9993',
'info_dict': {
'id': '14812',
},
'playlist_mincount': 75,
}, {
'url': 'http://www.hotstar.com/tv/pratidaan/14982/popular-clips/9998/9998',
'only_matching': True,
}]
_ITEM_TYPES = {
'episodes': 'EPISODE',
'popular-clips': 'CLIPS',
}
def _real_extract(self, url):
mobj = re.match(self._VALID_URL, url)
base_url = mobj.group('url')
content_id = mobj.group('content_id')
playlist_type = mobj.group('type')
content_info = self._download_content_info(content_id)
playlist_id = compat_str(content_info['categoryId'])
collection = self._download_json(
'https://search.hotstar.com/AVS/besc', playlist_id, query={
'action': 'SearchContents',
'appVersion': '5.0.40',
'channel': 'PCTV',
'moreFilters': 'series:%s;' % playlist_id,
'query': '*',
'searchOrder': 'last_broadcast_date desc,year desc,title asc',
'type': self._ITEM_TYPES.get(playlist_type, 'EPISODE'),
})
entries = [
self.url_result(
'%s/_/%s' % (base_url, video['contentId']),
ie=HotStarIE.ie_key(), video_id=video['contentId'])
for video in collection['response']['docs']
if video.get('contentId')]
return self.playlist_result(entries, playlist_id)
|
// here database is attaining connection and also create a schema
// for mongodb
const mongoose = require("mongoose");
module.exports = {
// connect database
connectDatabase: (connectUrl) => {
return new Promise((resolve, reject) => {
mongoose.connect(
connectUrl,
{ useNewUrlParser: true, useUnifiedTopology: true },
() => {
console.log(`[INFO] Database connected to ${connectUrl}`);
resolve();
}
);
});
},
// get all deatils about database schema
getDatabaseSchema: (databaseItems) => {
return new Promise((resolve, reject) => {
const databaseSchema = new mongoose.Schema(databaseItems);
resolve(databaseSchema); // exporting database schema
});
},
// create database model
createDatabaseModel: (databaseSchema, collectionName) => {
return new Promise(async (resolve, reject) => {
const databaseModel = await new mongoose.model(
collectionName,
databaseSchema
);
resolve(databaseModel);
});
},
};
|
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import React, {PureComponent} from 'react';
import PropTypes from 'prop-types';
import {
Platform,
Text,
TouchableOpacity,
View,
} from 'react-native';
import {getFullName} from 'mattermost-redux/utils/user_utils';
import {General} from 'mattermost-redux/constants';
import {injectIntl, intlShape} from 'react-intl';
import Loading from 'app/components/loading';
import ProfilePicture from 'app/components/profile_picture';
import {preventDoubleTap} from 'app/utils/tap';
import {changeOpacity, makeStyleSheetFromTheme} from 'app/utils/theme';
class ChannelIntro extends PureComponent {
static propTypes = {
creator: PropTypes.object,
currentChannel: PropTypes.object.isRequired,
currentChannelMembers: PropTypes.array.isRequired,
intl: intlShape.isRequired,
isLoadingPosts: PropTypes.bool,
navigator: PropTypes.object.isRequired,
theme: PropTypes.object.isRequired,
};
goToUserProfile = (userId) => {
const {intl, navigator, theme} = this.props;
const options = {
screen: 'UserProfile',
title: intl.formatMessage({id: 'mobile.routes.user_profile', defaultMessage: 'Profile'}),
animated: true,
backButtonTitle: '',
passProps: {
userId,
},
navigatorStyle: {
navBarTextColor: theme.sidebarHeaderTextColor,
navBarBackgroundColor: theme.sidebarHeaderBg,
navBarButtonColor: theme.sidebarHeaderTextColor,
screenBackgroundColor: theme.centerChannelBg,
},
};
if (Platform.OS === 'ios') {
navigator.push(options);
} else {
navigator.showModal(options);
}
};
getDisplayName = (member) => {
if (!member) {
return null;
}
const displayName = getFullName(member);
if (!displayName) {
return member.username;
}
return displayName;
};
buildProfiles = () => {
const {currentChannelMembers, theme} = this.props;
const style = getStyleSheet(theme);
return currentChannelMembers.map((member) => (
<TouchableOpacity
key={member.id}
onPress={preventDoubleTap(() => this.goToUserProfile(member.id))}
style={style.profile}
>
<ProfilePicture
userId={member.id}
size={64}
statusBorderWidth={2}
statusSize={25}
/>
</TouchableOpacity>
));
};
buildNames = () => {
const {currentChannelMembers, theme} = this.props;
const style = getStyleSheet(theme);
return currentChannelMembers.map((member, index) => (
<TouchableOpacity
key={member.id}
onPress={preventDoubleTap(() => this.goToUserProfile(member.id))}
>
<Text style={style.displayName}>
{index === currentChannelMembers.length - 1 ? this.getDisplayName(member) : `${this.getDisplayName(member)}, `}
</Text>
</TouchableOpacity>
));
};
buildDMContent = () => {
const {currentChannelMembers, intl, theme} = this.props;
const style = getStyleSheet(theme);
if (currentChannelMembers.length) {
const teammate = this.getDisplayName(currentChannelMembers[0]);
return (
<Text style={style.message}>
{intl.formatMessage({
id: 'mobile.intro_messages.DM',
defaultMessage: 'This is the start of your direct message history with {teammate}. Direct messages and files shared here are not shown to people outside this area.',
}, {
teammate,
})}
</Text>
);
}
return null;
};
buildGMContent = () => {
const {intl, theme} = this.props;
const style = getStyleSheet(theme);
return (
<Text style={style.message}>
{intl.formatMessage({
id: 'intro_messages.group_message',
defaultMessage: 'This is the start of your group message history with these teammates. Messages and files shared here are not shown to people outside this area.',
})}
</Text>
);
};
buildOpenChannelContent = () => {
const {creator, currentChannel, intl, theme} = this.props;
const style = getStyleSheet(theme);
const date = intl.formatDate(currentChannel.create_at, {
year: 'numeric',
month: 'long',
day: 'numeric',
});
let mainMessageIntl;
if (creator) {
const creatorName = this.getDisplayName(creator);
mainMessageIntl = {
id: 'intro_messages.creator',
defaultMessage: 'This is the start of the {name} {type}, created by {creator} on {date}.',
values: {
name: currentChannel.display_name,
creator: creatorName,
date,
type: intl.formatMessage({
id: 'intro_messages.channel',
defaultMessage: 'channel',
}),
},
};
} else {
mainMessageIntl = {
id: 'intro_messages.noCreator',
defaultMessage: 'This is the start of the {name} {type}, created on {date}.',
values: {
name: currentChannel.display_name,
date,
type: intl.formatMessage({
id: 'intro_messages.channel',
defaultMessage: 'channel',
}),
},
};
}
const mainMessage = intl.formatMessage({
id: mainMessageIntl.id,
defaultMessage: mainMessageIntl.defaultMessage,
}, mainMessageIntl.values);
const anyMemberMessage = intl.formatMessage({
id: 'intro_messages.anyMember',
defaultMessage: ' Any member can join and read this channel.',
});
return (
<View>
<Text style={style.channelTitle}>
{intl.formatMessage({
id: 'intro_messages.beginning',
defaultMessage: 'Beginning of {name}',
}, {
name: currentChannel.display_name,
})}
</Text>
<Text style={style.message}>
{`${mainMessage} ${anyMemberMessage}`}
</Text>
</View>
);
};
buildPrivateChannelContent = () => {
const {creator, currentChannel, intl, theme} = this.props;
const style = getStyleSheet(theme);
const creatorName = this.getDisplayName(creator);
const date = intl.formatDate(currentChannel.create_at, {
year: 'numeric',
month: 'long',
day: 'numeric',
});
const mainMessage = intl.formatMessage({
id: 'intro_messages.creator',
defaultMessage: 'This is the start of the {name} {type}, created by {creator} on {date}.',
}, {
name: currentChannel.display_name,
creator: creatorName,
date,
type: intl.formatMessage({
id: 'intro_messages.group',
defaultMessage: 'private channel',
}),
});
const onlyInvitedMessage = intl.formatMessage({
id: 'intro_messages.onlyInvited',
defaultMessage: ' Only invited members can see this private channel.',
});
return (
<View>
<Text style={style.channelTitle}>
{intl.formatMessage({
id: 'intro_messages.beginning',
defaultMessage: 'Beginning of {name}',
}, {
name: currentChannel.display_name,
})}
</Text>
<Text style={style.message}>
{`${mainMessage} ${onlyInvitedMessage}`}
</Text>
</View>
);
};
buildTownSquareContent = () => {
const {currentChannel, intl, theme} = this.props;
const style = getStyleSheet(theme);
return (
<View>
<Text style={style.channelTitle}>
{intl.formatMessage({
id: 'intro_messages.beginning',
defaultMessage: 'Beginning of {name}',
}, {
name: currentChannel.display_name,
})}
</Text>
<Text style={style.channelWelcome}>
{intl.formatMessage({
id: 'mobile.intro_messages.default_welcome',
defaultMessage: 'Welcome to {name}!',
}, {
name: currentChannel.display_name,
})}
</Text>
<Text style={style.message}>
{intl.formatMessage({
id: 'mobile.intro_messages.default_message',
defaultMessage: 'This is the first channel teammates see when they sign up - use it for posting updates everyone needs to know.',
})}
</Text>
</View>
);
};
buildContent = () => {
const {currentChannel} = this.props;
switch (currentChannel.type) {
default:
case General.DM_CHANNEL:
return this.buildDMContent();
case General.GM_CHANNEL:
return this.buildGMContent();
case General.OPEN_CHANNEL: {
if (currentChannel.name === General.DEFAULT_CHANNEL) {
return this.buildTownSquareContent();
}
return this.buildOpenChannelContent();
}
case General.PRIVATE_CHANNEL:
return this.buildPrivateChannelContent();
}
};
render() {
const {currentChannel, isLoadingPosts, theme} = this.props;
const style = getStyleSheet(theme);
const channelType = currentChannel.type;
if (isLoadingPosts) {
return (
<View style={style.container}>
<Loading/>
</View>
);
}
let profiles;
if (channelType === General.DM_CHANNEL || channelType === General.GM_CHANNEL) {
profiles = (
<View>
<View style={style.profilesContainer}>
{this.buildProfiles()}
</View>
<View style={style.namesContainer}>
{this.buildNames()}
</View>
</View>
);
}
return (
<View style={style.container}>
{profiles}
<View style={style.contentContainer}>
{this.buildContent()}
</View>
</View>
);
}
}
const getStyleSheet = makeStyleSheetFromTheme((theme) => {
return {
channelTitle: {
color: theme.centerChannelColor,
fontSize: 19,
fontWeight: '600',
marginBottom: 12,
},
channelWelcome: {
color: theme.centerChannelColor,
marginBottom: 12,
},
container: {
marginTop: 60,
marginHorizontal: 12,
marginBottom: 12,
},
displayName: {
color: theme.centerChannelColor,
fontSize: 15,
fontWeight: '600',
},
message: {
color: changeOpacity(theme.centerChannelColor, 0.8),
fontSize: 15,
lineHeight: 22,
},
namesContainer: {
flexDirection: 'row',
flexWrap: 'wrap',
marginBottom: 12,
},
profile: {
height: 67,
marginBottom: 12,
marginRight: 12,
},
profilesContainer: {
flexDirection: 'row',
flexWrap: 'wrap',
justifyContent: 'flex-start',
},
};
});
export default injectIntl(ChannelIntro);
|
const { MessageType } = require('@adiwajshing/baileys')
const PhoneNumber = require('awesome-phonenumber')
async function handler(m) {
let name = 'NO KE 2 GW'
number = owner[0].replace(/[^0-9]/g, '')
let njid = number + '@s.whatsapp.net'
let onW = await this.isOnWhatsApp(njid) || { isBusiness: false }
let name2 = 'Rizki'
number2 = owner[1].replace(/[^0-9]/g, '')
let njid2 = number2 + '@s.whatsapp.net'
let onW2 = await this.isOnWhatsApp(njid2) || { isBusiness: false }
let name3 = 'Kayy botz'
number3 = owner[2].replace(/[^0-9]/g, '')
let njid3 = number3 + '@s.whatsapp.net'
let onW3 = await this.isOnWhatsApp(njid3) || { isBusiness: false }
let name4 = 'Rizki'
number4 = owner[3].replace(/[^0-9]/g, '')
let njid4 = number4 + '@s.whatsapp.net'
let onW4 = await this.isOnWhatsApp(njid4) || { isBusiness: false }
m.reply(`Nomer owner itu *bukan bot*, tapi nomor _*pemilik bot*_\n\nSilahan chat jika ada keperluan.\nChat "P" atau minta save kemungkinan tidak akan di balas, dan -9999 social credit.`)
this.sendMessage(m.chat, {
contacts: [{
displayname: name, vcard: `
BEGIN:VCARD
VERSION:3.0
N:;${name.replace(/\n/g, '\\n')};;;
FN:${name.replace(/\n/g, '\\n')}
TEL;type=CELL;type=VOICE;waid=${number}:${PhoneNumber('+' + number).getNumber('international')}${onW.isBusiness ? `
X-WA-BIZ-NAME:${(this.contacts[njid].vname || this.getName(njid)).replace(/\n/, '\\n')}
X-WA-BIZ-DESCRIPTION:${((await this.getBusinessProfile(njid)).description || '').replace(/\n/g, '\\n')}
` : ''}
END:VCARD
`.trim()
}, {
displayname: name2, vcard: `
BEGIN:VCARD
VERSION:3.0
N:;${name2.replace(/\n/g, '\\n')};;;
FN:${name2.replace(/\n/g, '\\n')}
TEL;type=CELL;type=VOICE;waid=${number2}:${PhoneNumber('+' + number2).getNumber('international')}${onW2.isBusiness ? `
X-WA-BIZ-NAME:${(this.contacts[njid2].vname || this.getName(njid2)).replace(/\n/, '\\n')}
X-WA-BIZ-DESCRIPTION:${((await this.getBusinessProfile(njid2)).description || '').replace(/\n/g, '\\n')}
` : ''}
END:VCARD
`.trim()
}, {displayname: name3, vcard: `
BEGIN:VCARD
VERSION:3.0
N:;${name3.replace(/\n/g, '\\n')};;;
FN:${name3.replace(/\n/g, '\\n')}
TEL;type=CELL;type=VOICE;waid=${number3}:${PhoneNumber('+' + number3).getNumber('international')}${onW3.isBusiness ? `
X-WA-BIZ-NAME:${(this.contacts[njid3].vname || this.getName(njid3)).replace(/\n/, '\\n')}
X-WA-BIZ-DESCRIPTION:${((await this.getBusinessProfile(njid3)).description || '').replace(/\n/g, '\\n')}
` : ''}
END:VCARD
`.trim()
}, {
displayname: name4, vcard: `
BEGIN:VCARD
VERSION:3.0
N:;${name4.replace(/\n/g, '\\n')};;;
FN:${name4.replace(/\n/g, '\\n')}
TEL;type=CELL;type=VOICE;waid=${number4}:${PhoneNumber('+' + number4).getNumber('international')}${onW4.isBusiness ? `
X-WA-BIZ-NAME:${(this.contacts[njid4].vname || this.getName(njid4)).replace(/\n/, '\\n')}
X-WA-BIZ-DESCRIPTION:${((await this.getBusinessProfile(njid4)).description || '').replace(/\n/g, '\\n')}
` : ''}
END:VCARD
`.trim()
}]
}, MessageType.contactsArray, { quoted: m })
}
handler.help = ['owner', 'creator']
handler.tags = ['info']
handler.command = /^(owner|creator)$/i
module.exports = handler
|
/**
* Bootstrap based calendar full view.
*
* https://github.com/Serhioromano/bootstrap-calendar
*
* User: Sergey Romanov <serg4172@mail.ru>
*/
"use strict";
Date.prototype.getWeek = function() {
var onejan = new Date(this.getFullYear(), 0, 1);
return Math.ceil((((this.getTime() - onejan.getTime()) / 86400000) + onejan.getDay() + 1) / 7);
};
Date.prototype.getMonthFormatted = function() {
var month = this.getMonth() + 1;
return month < 10 ? '0' + month : month;
};
Date.prototype.getDateFormatted = function() {
var date = this.getDate();
return date < 10 ? '0' + date : date;
};
if(!String.prototype.format) {
String.prototype.format = function() {
var args = arguments;
return this.replace(/{(\d+)}/g, function(match, number) {
return typeof args[number] != 'undefined' ? args[number] : match;
});
};
}
if(!String.prototype.formatNum) {
String.prototype.formatNum = function(decimal) {
var r = "" + this;
while(r.length < decimal)
r = "0" + r;
return r;
};
}
(function($) {
var defaults = {
// Width of the calendar
width: '100%',
// Initial view (can be 'month', 'week', 'day')
view: 'month',
// Initial date. No matter month, week or day this will be a starting point. Can be 'now' or a date in format 'yyyy-mm-dd'
day: 'now',
// Day Start time and end time with time intervals. Time split 10, 15 or 30.
time_start: '06:00',
time_end: '22:00',
time_split: '30',
// Source of events data. It can be one of the following:
// - URL to return JSON list of events in special format.
// {success:1, result: [....]} or for error {success:0, error:'Something terrible happened'}
// events: [...] as described in events property description
// The start and end variables will be sent to this url
// - A function that received the start and end date, and that
// returns an array of events (as described in events property description)
// - An array containing the events
events_source: '',
// Set format12 to true if you want to use 12 Hour format instead of 24 Hour
format12: false,
am_suffix: "AM",
pm_suffix: "PM",
// Path to templates should end with slash /. It can be as relative
// /component/bootstrap-calendar/tmpls/
// or absolute
// http://localhost/component/bootstrap-calendar/tmpls/
tmpl_path: 'tmpls/',
tmpl_cache: true,
classes: {
months: {
inmonth: 'cal-day-inmonth',
outmonth: 'cal-day-outmonth',
saturday: 'cal-day-weekend',
sunday: 'cal-day-weekend',
holidays: 'cal-day-holiday',
today: 'cal-day-today'
},
week: {
workday: 'cal-day-workday',
saturday: 'cal-day-weekend',
sunday: 'cal-day-weekend',
holidays: 'cal-day-holiday',
today: 'cal-day-today'
}
},
// ID of the element of modal window. If set, events URLs will be opened in modal windows.
modal: null,
// modal handling setting, one of "iframe", "ajax" or "template"
modal_type: "iframe",
// function to set modal title, will be passed the event as a parameter
modal_title: null,
views: {
year: {
slide_events: 1,
enable: 1
},
month: {
slide_events: 1,
enable: 1
},
week: {
enable: 1
},
day: {
enable: 1
}
},
merge_holidays: false,
display_week_numbers: true,
weekbox: true,
// ------------------------------------------------------------
// CALLBACKS. Events triggered by calendar class. You can use
// those to affect you UI
// ------------------------------------------------------------
onAfterEventsLoad: function(events) {
// Inside this function 'this' is the calendar instance
},
onBeforeEventsLoad: function(next) {
// Inside this function 'this' is the calendar instance
next();
},
onAfterViewLoad: function(view) {
// Inside this function 'this' is the calendar instance
},
onAfterModalShown: function(events) {
// Inside this function 'this' is the calendar instance
},
onAfterModalHidden: function(events) {
// Inside this function 'this' is the calendar instance
},
// -------------------------------------------------------------
// INTERNAL USE ONLY. DO NOT ASSIGN IT WILL BE OVERRIDDEN ANYWAY
// -------------------------------------------------------------
events: [],
templates: {
year: '',
month: '',
week: '',
day: ''
},
stop_cycling: false
};
var defaults_extended = {
first_day: 1,
holidays: {
// January 1
'01-01': "New Year's Day",
// Third (+3*) Monday (1) in January (01)
'01+3*1': "Birthday of Dr. Martin Luther King, Jr.",
// Third (+3*) Monday (1) in February (02)
'02+3*1': "Washington's Birthday",
// Last (-1*) Monday (1) in May (05)
'05-1*1': "Memorial Day",
// July 4
'04-07': "Independence Day",
// First (+1*) Monday (1) in September (09)
'09+1*1': "Labor Day",
// Second (+2*) Monday (1) in October (10)
'10+2*1': "Columbus Day",
// November 11
'11-11': "Veterans Day",
// Fourth (+4*) Thursday (4) in November (11)
'11+4*4': "Thanksgiving Day",
// December 25
'25-12': "Christmas"
}
};
var strings = {
error_noview: 'Calendar: View {0} not found',
error_dateformat: 'Calendar: Wrong date format {0}. Should be either "now" or "yyyy-mm-dd"',
error_loadurl: 'Calendar: Event URL is not set',
error_where: 'Calendar: Wrong navigation direction {0}. Can be only "next" or "prev" or "today"',
error_timedevide: 'Calendar: Time split parameter should divide 60 without decimals. Something like 10, 15, 30',
no_events_in_day: 'No events in this day.',
title_year: '{0}',
title_month: '{0} {1}',
title_week: 'week {0} of {1}',
title_day: '{0} {1} {2}, {3}',
week: 'Week {0}',
all_day: 'All day',
time: 'Time',
events: 'Events',
before_time: 'Ends before timeline',
after_time: 'Starts after timeline',
m0: 'January',
m1: 'February',
m2: 'March',
m3: 'April',
m4: 'May',
m5: 'June',
m6: 'July',
m7: 'August',
m8: 'September',
m9: 'October',
m10: 'November',
m11: 'December',
ms0: 'Jan',
ms1: 'Feb',
ms2: 'Mar',
ms3: 'Apr',
ms4: 'May',
ms5: 'Jun',
ms6: 'Jul',
ms7: 'Aug',
ms8: 'Sep',
ms9: 'Oct',
ms10: 'Nov',
ms11: 'Dec',
d0: 'Sunday',
d1: 'Monday',
d2: 'Tuesday',
d3: 'Wednesday',
d4: 'Thursday',
d5: 'Friday',
d6: 'Saturday'
};
var browser_timezone = '';
try {
if($.type(window.jstz) == 'object' && $.type(jstz.determine) == 'function') {
browser_timezone = jstz.determine().name();
if($.type(browser_timezone) !== 'string') {
browser_timezone = '';
}
}
}
catch(e) {
}
function buildEventsUrl(events_url, data) {
var separator, key, url;
url = events_url;
separator = (events_url.indexOf('?') < 0) ? '?' : '&';
for(key in data) {
url += separator + key + '=' + encodeURIComponent(data[key]);
separator = '&';
}
return url;
}
function getExtentedOption(cal, option_name) {
var fromOptions = (cal.options[option_name] != null) ? cal.options[option_name] : null;
var fromLanguage = (cal.locale[option_name] != null) ? cal.locale[option_name] : null;
if((option_name == 'holidays') && cal.options.merge_holidays) {
var holidays = {};
$.extend(true, holidays, fromLanguage ? fromLanguage : defaults_extended.holidays);
if(fromOptions) {
$.extend(true, holidays, fromOptions);
}
return holidays;
}
else {
if(fromOptions != null) {
return fromOptions;
}
if(fromLanguage != null) {
return fromLanguage;
}
return defaults_extended[option_name];
}
}
function getHolidays(cal, year) {
var hash = [];
var holidays_def = getExtentedOption(cal, 'holidays');
for(var k in holidays_def) {
hash.push(k + ':' + holidays_def[k]);
}
hash.push(year);
hash = hash.join('|');
if(hash in getHolidays.cache) {
return getHolidays.cache[hash];
}
var holidays = [];
$.each(holidays_def, function(key, name) {
var firstDay = null, lastDay = null, failed = false;
$.each(key.split('>'), function(i, chunk) {
var m, date = null;
if(m = /^(\d\d)-(\d\d)$/.exec(chunk)) {
date = new Date(year, parseInt(m[2], 10) - 1, parseInt(m[1], 10));
}
else if(m = /^(\d\d)-(\d\d)-(\d\d\d\d)$/.exec(chunk)) {
if(parseInt(m[3], 10) == year) {
date = new Date(year, parseInt(m[2], 10) - 1, parseInt(m[1], 10));
}
}
else if(m = /^easter(([+\-])(\d+))?$/.exec(chunk)) {
date = getEasterDate(year, m[1] ? parseInt(m[1], 10) : 0);
}
else if(m = /^(\d\d)([+\-])([1-5])\*([0-6])$/.exec(chunk)) {
var month = parseInt(m[1], 10) - 1;
var direction = m[2];
var offset = parseInt(m[3]);
var weekday = parseInt(m[4]);
switch(direction) {
case '+':
var d = new Date(year, month, 1 - 7);
while(d.getDay() != weekday) {
d = new Date(d.getFullYear(), d.getMonth(), d.getDate() + 1);
}
date = new Date(d.getFullYear(), d.getMonth(), d.getDate() + 7 * offset);
break;
case '-':
var d = new Date(year, month + 1, 0 + 7);
while(d.getDay() != weekday) {
d = new Date(d.getFullYear(), d.getMonth(), d.getDate() - 1);
}
date = new Date(d.getFullYear(), d.getMonth(), d.getDate() - 7 * offset);
break;
}
}
if(!date) {
warn('Unknown holiday: ' + key);
failed = true;
return false;
}
switch(i) {
case 0:
firstDay = date;
break;
case 1:
if(date.getTime() <= firstDay.getTime()) {
warn('Unknown holiday: ' + key);
failed = true;
return false;
}
lastDay = date;
break;
default:
warn('Unknown holiday: ' + key);
failed = true;
return false;
}
});
if(!failed) {
var days = [];
if(lastDay) {
for(var date = new Date(firstDay.getTime()); date.getTime() <= lastDay.getTime(); date.setDate(date.getDate() + 1)) {
days.push(new Date(date.getTime()));
}
}
else {
days.push(firstDay);
}
holidays.push({name: name, days: days});
}
});
getHolidays.cache[hash] = holidays;
return getHolidays.cache[hash];
}
getHolidays.cache = {};
function warn(message) {
if($.type(window.console) == 'object' && $.type(window.console.warn) == 'function') {
window.console.warn('[Bootstrap-Calendar] ' + message);
}
}
function Calendar(params, context) {
this.options = $.extend(true, {position: {start: new Date(), end: new Date()}}, defaults, params);
this.setLanguage(this.options.language);
this.context = context;
context.css('width', this.options.width).addClass('cal-context');
this.view();
return this;
}
Calendar.prototype.setOptions = function(object) {
$.extend(this.options, object);
if('language' in object) {
this.setLanguage(object.language);
}
if('modal' in object) {
this._update_modal();
}
}
Calendar.prototype.setLanguage = function(lang) {
if(window.calendar_languages && (lang in window.calendar_languages)) {
this.locale = $.extend(true, {}, strings, calendar_languages[lang]);
this.options.language = lang;
} else {
this.locale = strings;
delete this.options.language;
}
}
Calendar.prototype._render = function() {
this.context.html('');
this._loadTemplate(this.options.view);
this.stop_cycling = false;
var data = {};
data.cal = this;
data.day = 1;
// Getting list of days in a week in correct order. Works for month and week views
if(getExtentedOption(this, 'first_day') == 1) {
data.days_name = [this.locale.d1, this.locale.d2, this.locale.d3, this.locale.d4, this.locale.d5, this.locale.d6, this.locale.d0]
} else {
data.days_name = [this.locale.d0, this.locale.d1, this.locale.d2, this.locale.d3, this.locale.d4, this.locale.d5, this.locale.d6]
}
// Get all events between start and end
var start = parseInt(this.options.position.start.getTime());
var end = parseInt(this.options.position.end.getTime());
data.events = this.getEventsBetween(start, end);
switch(this.options.view) {
case 'month':
break;
case 'week':
this._calculate_hour_minutes(data);
break;
case 'day':
this._calculate_hour_minutes(data);
break;
}
data.start = new Date(this.options.position.start.getTime());
data.lang = this.locale;
this.context.append(this.options.templates[this.options.view](data));
this._update();
};
Calendar.prototype._format_hour = function(str_hour) {
var hour_split = str_hour.split(":");
var hour = parseInt(hour_split[0]);
var minutes = parseInt(hour_split[1]);
var suffix = '';
if(this.options.format12) {
if(hour < 12) {
suffix = this.options.am_suffix;
}
else {
suffix = this.options.pm_suffix;
}
hour = hour % 12;
if(hour == 0) {
hour = 12;
}
}
return hour.toString().formatNum(2) + ':' + minutes.toString().formatNum(2) + suffix;
};
Calendar.prototype._format_time = function(datetime) {
return this._format_hour(datetime.getHours() + ':' + datetime.getMinutes());
};
Calendar.prototype._calculate_hour_minutes = function(data) {
var $self = this;
var time_split = parseInt(this.options.time_split);
var time_split_count = 60 / time_split;
var time_split_hour = Math.min(time_split_count, 1);
if(((time_split_count >= 1) && (time_split_count % 1 != 0)) || ((time_split_count < 1) && (1440 / time_split % 1 != 0))) {
$.error(this.locale.error_timedevide);
}
var time_start = this.options.time_start.split(":");
var time_end = this.options.time_end.split(":");
data.hours = (parseInt(time_end[0]) - parseInt(time_start[0])) * time_split_hour;
var lines = data.hours * time_split_count - parseInt(time_start[1]) / time_split;
var ms_per_line = (60000 * time_split);
var start = new Date(this.options.position.start.getTime());
start.setHours(time_start[0]);
start.setMinutes(time_start[1]);
var end = new Date(this.options.position.end.getTime());
end.setHours(time_end[0]);
end.setMinutes(time_end[1]);
data.all_day = [];
data.by_hour = [];
data.after_time = [];
data.before_time = [];
$.each(data.events, function(k, e) {
var s = new Date(parseInt(e.start));
var f = new Date(parseInt(e.end));
e.start_hour = $self._format_time(s);
e.end_hour = $self._format_time(f);
if(e.start < start.getTime()) {
warn(1);
e.start_hour = s.getDate() + ' ' + $self.locale['ms' + s.getMonth()] + ' ' + e.start_hour;
}
if(e.end > end.getTime()) {
warn(1);
e.end_hour = f.getDate() + ' ' + $self.locale['ms' + f.getMonth()] + ' ' + e.end_hour;
}
if(e.start < start.getTime() && e.end > end.getTime()) {
data.all_day.push(e);
return;
}
if(e.end < start.getTime()) {
data.before_time.push(e);
return;
}
if(e.start > end.getTime()) {
data.after_time.push(e);
return;
}
var event_start = start.getTime() - e.start;
if(event_start >= 0) {
e.top = 0;
} else {
e.top = Math.abs(event_start) / ms_per_line;
}
var lines_left = Math.abs(lines - e.top);
var lines_in_event = (e.end - e.start) / ms_per_line;
if(event_start >= 0) {
lines_in_event = (e.end - start.getTime()) / ms_per_line;
}
e.lines = lines_in_event;
if(lines_in_event > lines_left) {
e.lines = lines_left;
}
data.by_hour.push(e);
});
//var d = new Date('2013-03-14 13:20:00');
//warn(d.getTime());
};
Calendar.prototype._hour_min = function(hour) {
var time_start = this.options.time_start.split(":");
var time_split = parseInt(this.options.time_split);
var in_hour = 60 / time_split;
return (hour == 0) ? (in_hour - (parseInt(time_start[1]) / time_split)) : in_hour;
};
Calendar.prototype._hour = function(hour, part) {
var time_start = this.options.time_start.split(":");
var time_split = parseInt(this.options.time_split);
var h = "" + (parseInt(time_start[0]) + hour * Math.max(time_split / 60, 1));
var m = "" + time_split * part;
return this._format_hour(h.formatNum(2) + ":" + m.formatNum(2));
};
Calendar.prototype._week = function(event) {
this._loadTemplate('week-days');
var t = {};
var start = parseInt(this.options.position.start.getTime());
var end = parseInt(this.options.position.end.getTime());
var events = [];
var self = this;
var first_day = getExtentedOption(this, 'first_day');
$.each(this.getEventsBetween(start, end), function(k, event) {
event.start_day = new Date(parseInt(event.start)).getDay();
if(first_day == 1) {
event.start_day = (event.start_day + 6) % 7;
}
if((event.end - event.start) <= 86400000) {
event.days = 1;
} else {
event.days = ((event.end - event.start) / 86400000);
}
if(event.start < start) {
event.days = event.days - ((start - event.start) / 86400000);
event.start_day = 0;
}
event.days = Math.ceil(event.days);
if(event.start_day + event.days > 7) {
event.days = 7 - (event.start_day);
}
events.push(event);
});
t.events = events;
t.cal = this;
return self.options.templates['week-days'](t);
}
Calendar.prototype._month = function(month) {
this._loadTemplate('year-month');
var t = {cal: this};
var newmonth = month + 1;
t.data_day = this.options.position.start.getFullYear() + '-' + (newmonth < 10 ? '0' + newmonth : newmonth) + '-' + '01';
t.month_name = this.locale['m' + month];
var curdate = new Date(this.options.position.start.getFullYear(), month, 1, 0, 0, 0);
t.start = parseInt(curdate.getTime());
t.end = parseInt(new Date(this.options.position.start.getFullYear(), month + 1, 1, 0, 0, 0).getTime());
t.events = this.getEventsBetween(t.start, t.end);
return this.options.templates['year-month'](t);
}
Calendar.prototype._day = function(week, day) {
this._loadTemplate('month-day');
var t = {tooltip: '', cal: this};
var cls = this.options.classes.months.outmonth;
var firstday = this.options.position.start.getDay();
if(getExtentedOption(this, 'first_day') == 2) {
firstday++;
} else {
firstday = (firstday == 0 ? 7 : firstday);
}
day = (day - firstday) + 1;
var curdate = new Date(this.options.position.start.getFullYear(), this.options.position.start.getMonth(), day, 0, 0, 0);
// if day of the current month
if(day > 0) {
cls = this.options.classes.months.inmonth;
}
// stop cycling table rows;
var daysinmonth = (new Date(this.options.position.end.getTime() - 1)).getDate();
if((day + 1) > daysinmonth) {
this.stop_cycling = true;
}
// if day of the next month
if(day > daysinmonth) {
day = day - daysinmonth;
cls = this.options.classes.months.outmonth;
}
cls = $.trim(cls + " " + this._getDayClass("months", curdate));
if(day <= 0) {
var daysinprevmonth = (new Date(this.options.position.start.getFullYear(), this.options.position.start.getMonth(), 0)).getDate();
day = daysinprevmonth - Math.abs(day);
cls += ' cal-month-first-row';
}
var holiday = this._getHoliday(curdate);
if(holiday !== false) {
t.tooltip = holiday;
}
t.data_day = curdate.getFullYear() + '-' + curdate.getMonthFormatted() + '-' + (day < 10 ? '0' + day : day);
t.cls = cls;
t.day = day;
t.start = parseInt(curdate.getTime());
t.end = parseInt(t.start + 86400000);
t.events = this.getEventsBetween(t.start, t.end);
return this.options.templates['month-day'](t);
}
Calendar.prototype._getHoliday = function(date) {
var result = false;
$.each(getHolidays(this, date.getFullYear()), function() {
var found = false;
$.each(this.days, function() {
if(this.toDateString() == date.toDateString()) {
found = true;
return false;
}
});
if(found) {
result = this.name;
return false;
}
});
return result;
};
Calendar.prototype._getHolidayName = function(date) {
var holiday = this._getHoliday(date);
return (holiday === false) ? "" : holiday;
};
Calendar.prototype._getDayClass = function(class_group, date) {
var self = this;
var addClass = function(which, to) {
var cls;
cls = (self.options.classes && (class_group in self.options.classes) && (which in self.options.classes[class_group])) ? self.options.classes[class_group][which] : "";
if((typeof(cls) == "string") && cls.length) {
to.push(cls);
}
};
var classes = [];
if(date.toDateString() == (new Date()).toDateString()) {
addClass("today", classes);
}
var holiday = this._getHoliday(date);
if(holiday !== false) {
addClass("holidays", classes);
}
switch(date.getDay()) {
case 0:
addClass("sunday", classes);
break;
case 6:
addClass("saturday", classes);
break;
}
addClass(date.toDateString(), classes);
return classes.join(" ");
};
Calendar.prototype.view = function(view) {
if(view) {
if(!this.options.views[view].enable) {
return;
}
this.options.view = view;
}
this._init_position();
this._loadEvents();
this._render();
this.options.onAfterViewLoad.call(this, this.options.view);
};
Calendar.prototype.navigate = function(where, next) {
var to = $.extend({}, this.options.position);
if(where == 'next') {
switch(this.options.view) {
case 'year':
to.start.setFullYear(this.options.position.start.getFullYear() + 1);
break;
case 'month':
to.start.setMonth(this.options.position.start.getMonth() + 1);
break;
case 'week':
to.start.setDate(this.options.position.start.getDate() + 7);
break;
case 'day':
to.start.setDate(this.options.position.start.getDate() + 1);
break;
}
} else if(where == 'prev') {
switch(this.options.view) {
case 'year':
to.start.setFullYear(this.options.position.start.getFullYear() - 1);
break;
case 'month':
to.start.setMonth(this.options.position.start.getMonth() - 1);
break;
case 'week':
to.start.setDate(this.options.position.start.getDate() - 7);
break;
case 'day':
to.start.setDate(this.options.position.start.getDate() - 1);
break;
}
} else if(where == 'today') {
to.start.setTime(new Date().getTime());
}
else {
$.error(this.locale.error_where.format(where))
}
this.options.day = to.start.getFullYear() + '-' + to.start.getMonthFormatted() + '-' + to.start.getDateFormatted();
this.view();
if(_.isFunction(next)) {
next();
}
};
Calendar.prototype._init_position = function() {
var year, month, day;
if(this.options.day == 'now') {
var date = new Date();
year = date.getFullYear();
month = date.getMonth();
day = date.getDate();
} else if(this.options.day.match(/^\d{4}-\d{2}-\d{2}$/g)) {
var list = this.options.day.split('-');
year = parseInt(list[0], 10);
month = parseInt(list[1], 10) - 1;
day = parseInt(list[2], 10);
}
else {
$.error(this.locale.error_dateformat.format(this.options.day));
}
switch(this.options.view) {
case 'year':
this.options.position.start.setTime(new Date(year, 0, 1).getTime());
this.options.position.end.setTime(new Date(year + 1, 0, 1).getTime());
break;
case 'month':
this.options.position.start.setTime(new Date(year, month, 1).getTime());
this.options.position.end.setTime(new Date(year, month + 1, 1).getTime());
break;
case 'day':
this.options.position.start.setTime(new Date(year, month, day).getTime());
this.options.position.end.setTime(new Date(year, month, day + 1).getTime());
break;
case 'week':
var curr = new Date(year, month, day);
var first;
if(getExtentedOption(this, 'first_day') == 1) {
first = curr.getDate() - ((curr.getDay() + 6) % 7);
}
else {
first = curr.getDate() - curr.getDay();
}
this.options.position.start.setTime(new Date(year, month, first).getTime());
this.options.position.end.setTime(new Date(year, month, first + 7).getTime());
break;
default:
$.error(this.locale.error_noview.format(this.options.view))
}
return this;
};
Calendar.prototype.getTitle = function() {
var p = this.options.position.start;
switch(this.options.view) {
case 'year':
return this.locale.title_year.format(p.getFullYear());
break;
case 'month':
return this.locale.title_month.format(this.locale['m' + p.getMonth()], p.getFullYear());
break;
case 'week':
return this.locale.title_week.format(p.getWeek(), p.getFullYear());
break;
case 'day':
return this.locale.title_day.format(this.locale['d' + p.getDay()], p.getDate(), this.locale['m' + p.getMonth()], p.getFullYear());
break;
}
return;
};
Calendar.prototype.isToday = function() {
var now = new Date().getTime();
return ((now > this.options.position.start) && (now < this.options.position.end));
}
Calendar.prototype.getStartDate = function() {
return this.options.position.start;
}
Calendar.prototype.getEndDate = function() {
return this.options.position.end;
}
Calendar.prototype._loadEvents = function() {
var self = this;
var source = null;
if('events_source' in this.options && this.options.events_source !== '') {
source = this.options.events_source;
}
else if('events_url' in this.options) {
source = this.options.events_url;
warn('The events_url option is DEPRECATED and it will be REMOVED in near future. Please use events_source instead.');
}
var loader;
switch($.type(source)) {
case 'function':
loader = function() {
return source(self.options.position.start, self.options.position.end, browser_timezone);
};
break;
case 'array':
loader = function() {
return [].concat(source);
};
break;
case 'string':
if(source.length) {
loader = function() {
var events = [];
var d = new Date();
var utc_offset = d.getTimezoneOffset();
var params = {from: self.options.position.start.getTime(), to: self.options.position.end.getTime(), utc_offset: utc_offset};
if(browser_timezone.length) {
params.browser_timezone = browser_timezone;
}
$.ajax({
url: buildEventsUrl(source, params),
dataType: 'json',
type: 'GET',
async: false
}).done(function(json) {
if(!json.success) {
$.error(json.error);
}
if(json.result) {
events = json.result;
}
});
return events;
};
}
break;
}
if(!loader) {
$.error(this.locale.error_loadurl);
}
this.options.onBeforeEventsLoad.call(this, function() {
self.options.events = loader();
self.options.events.sort(function(a, b) {
var delta;
delta = a.start - b.start;
if(delta == 0) {
delta = a.end - b.end;
}
return delta;
});
self.options.onAfterEventsLoad.call(self, self.options.events);
});
};
Calendar.prototype._templatePath = function(name) {
if(typeof this.options.tmpl_path == 'function') {
return this.options.tmpl_path(name)
}
else {
return this.options.tmpl_path + name + '.html';
}
};
Calendar.prototype._loadTemplate = function(name) {
if(this.options.templates[name]) {
return;
}
var self = this;
$.ajax({
url: self._templatePath(name),
dataType: 'html',
type: 'GET',
async: false,
cache: this.options.tmpl_cache
}).done(function(html) {
self.options.templates[name] = _.template(html);
});
};
Calendar.prototype._update = function() {
var self = this;
$('*[data-toggle="tooltip"]').tooltip({container: 'body'});
$('*[data-cal-date]').click(function() {
var view = $(this).data('cal-view');
self.options.day = $(this).data('cal-date');
self.view(view);
});
$('.cal-cell').dblclick(function() {
var view = $('[data-cal-date]', this).data('cal-view');
self.options.day = $('[data-cal-date]', this).data('cal-date');
self.view(view);
});
this['_update_' + this.options.view]();
this._update_modal();
};
Calendar.prototype._update_modal = function() {
var self = this;
$('a[data-event-id]', this.context).unbind('click');
if(!self.options.modal) {
return;
}
var modal = $(self.options.modal);
if(!modal.length) {
return;
}
var ifrm = null;
if(self.options.modal_type == "iframe") {
ifrm = $(document.createElement("iframe"))
.attr({
width: "100%",
frameborder: "0"
});
}
$('a[data-event-id]', this.context).on('click', function(event) {
event.preventDefault();
event.stopPropagation();
var url = $(this).attr('href');
var id = $(this).data("event-id");
var event = _.find(self.options.events, function(event) {
return event.id == id
});
if(self.options.modal_type == "iframe") {
ifrm.attr('src', url);
$('.modal-body', modal).html(ifrm);
}
if(!modal.data('handled.bootstrap-calendar') || (modal.data('handled.bootstrap-calendar') && modal.data('handled.event-id') != event.id)) {
modal.off('show.bs.modal')
.off('shown.bs.modal')
.off('hidden.bs.modal')
.on('show.bs.modal', function() {
var modal_body = $(this).find('.modal-body');
switch(self.options.modal_type) {
case "iframe" :
var height = modal_body.height() - parseInt(modal_body.css('padding-top'), 10) - parseInt(modal_body.css('padding-bottom'), 10);
$(this).find('iframe').height(Math.max(height, 50));
break;
case "ajax":
$.ajax({
url: url, dataType: "html", async: false, success: function(data) {
modal_body.html(data);
}
});
break;
case "template":
self._loadTemplate("modal");
// also serve calendar instance to underscore template to be able to access current language strings
modal_body.html(self.options.templates["modal"]({"event": event, "calendar": self}))
break;
}
// set the title of the bootstrap modal
if(_.isFunction(self.options.modal_title)) {
modal.find(".modal-title").html(self.options.modal_title(event));
}
})
.on('shown.bs.modal', function() {
self.options.onAfterModalShown.call(self, self.options.events);
})
.on('hidden.bs.modal', function() {
self.options.onAfterModalHidden.call(self, self.options.events);
})
.data('handled.bootstrap-calendar', true).data('handled.event-id', event.id);
}
modal.modal('show');
});
};
Calendar.prototype._update_day = function() {
$('#cal-day-panel').height($('#cal-day-panel-hour').height());
};
Calendar.prototype._update_week = function() {
};
Calendar.prototype._update_year = function() {
this._update_month_year();
};
Calendar.prototype._update_month = function() {
this._update_month_year();
var self = this;
if(this.options.weekbox == true) {
var week = $(document.createElement('div')).attr('id', 'cal-week-box');
var start = this.options.position.start.getFullYear() + '-' + this.options.position.start.getMonthFormatted() + '-';
self.context.find('.cal-month-box .cal-row-fluid')
.on('mouseenter', function() {
var p = new Date(self.options.position.start);
var child = $('.cal-cell1:first-child .cal-month-day', this);
var day = (child.hasClass('cal-month-first-row') ? 1 : $('[data-cal-date]', child).text());
p.setDate(parseInt(day));
day = (day < 10 ? '0' + day : day);
week.html(self.locale.week.format(self.options.display_week_numbers == true ? p.getWeek() : ''));
week.attr('data-cal-week', start + day).show().appendTo(child);
})
.on('mouseleave', function() {
week.hide();
});
week.click(function() {
self.options.day = $(this).data('cal-week');
self.view('week');
});
}
self.context.find('a.event').mouseenter(function() {
$('a[data-event-id="' + $(this).data('event-id') + '"]').closest('.cal-cell1').addClass('day-highlight dh-' + $(this).data('event-class'));
});
self.context.find('a.event').mouseleave(function() {
$('div.cal-cell1').removeClass('day-highlight dh-' + $(this).data('event-class'));
});
};
Calendar.prototype._update_month_year = function() {
if(!this.options.views[this.options.view].slide_events) {
return;
}
var self = this;
var activecell = 0;
var downbox = $(document.createElement('div')).attr('id', 'cal-day-tick').html('<i class="icon-chevron-down glyphicon glyphicon-chevron-down"></i>');
self.context.find('.cal-month-day, .cal-year-box .span3')
.on('mouseenter', function() {
if($('.events-list', this).length == 0) {
return;
}
if($(this).children('[data-cal-date]').text() == self.activecell) {
return;
}
downbox.show().appendTo(this);
})
.on('mouseleave', function() {
downbox.hide();
})
.on('click', function(event) {
if($('.events-list', this).length == 0) {
return;
}
if($(this).children('[data-cal-date]').text() == self.activecell) {
return;
}
showEventsList(event, downbox, slider, self);
})
;
var slider = $(document.createElement('div')).attr('id', 'cal-slide-box');
slider.hide().click(function(event) {
event.stopPropagation();
});
this._loadTemplate('events-list');
downbox.click(function(event) {
showEventsList(event, $(this), slider, self);
});
};
Calendar.prototype.getEventsBetween = function(start, end) {
var events = [];
$.each(this.options.events, function() {
if(this.start == null) {
return true;
}
var event_end = this.end || this.start;
if((parseInt(this.start) < end) && (parseInt(event_end) >= start)) {
events.push(this);
}
});
return events;
};
function showEventsList(event, that, slider, self) {
event.stopPropagation();
var that = $(that);
var cell = that.closest('.cal-cell');
var row = cell.closest('.cal-before-eventlist');
var tick_position = cell.data('cal-row');
that.fadeOut('fast');
slider.slideUp('fast', function() {
var event_list = $('.events-list', cell);
slider.html(self.options.templates['events-list']({
cal: self,
events: self.getEventsBetween(parseInt(event_list.data('cal-start')), parseInt(event_list.data('cal-end')))
}));
row.after(slider);
self.activecell = $('[data-cal-date]', cell).text();
$('#cal-slide-tick').addClass('tick' + tick_position).show();
slider.slideDown('fast', function() {
$('body').one('click', function() {
slider.slideUp('fast');
self.activecell = 0;
});
});
});
// Wait 400ms before updating the modal & attach the mouseenter&mouseleave(400ms is the time for the slider to fade out and slide up)
setTimeout(function() {
$('a.event-item').mouseenter(function() {
$('a[data-event-id="' + $(this).data('event-id') + '"]').closest('.cal-cell1').addClass('day-highlight dh-' + $(this).data('event-class'));
});
$('a.event-item').mouseleave(function() {
$('div.cal-cell1').removeClass('day-highlight dh-' + $(this).data('event-class'));
});
self._update_modal();
}, 400);
}
function getEasterDate(year, offsetDays) {
var a = year % 19;
var b = Math.floor(year / 100);
var c = year % 100;
var d = Math.floor(b / 4);
var e = b % 4;
var f = Math.floor((b + 8) / 25);
var g = Math.floor((b - f + 1) / 3);
var h = (19 * a + b - d - g + 15) % 30;
var i = Math.floor(c / 4);
var k = c % 4;
var l = (32 + 2 * e + 2 * i - h - k) % 7;
var m = Math.floor((a + 11 * h + 22 * l) / 451);
var n0 = (h + l + 7 * m + 114)
var n = Math.floor(n0 / 31) - 1;
var p = n0 % 31 + 1;
return new Date(year, n, p + (offsetDays ? offsetDays : 0), 0, 0, 0);
}
$.fn.calendar = function(params) {
return new Calendar(params, this);
}
}(jQuery));
|
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from vaxrank.manufacturability import ManufacturabilityScores
def test_c_terminal_proline():
scores = ManufacturabilityScores.from_amino_acids("A" * 6 + "P")
assert scores.c_terminal_proline
scores = ManufacturabilityScores.from_amino_acids("A" * 7)
assert not scores.c_terminal_proline
def test_n_terminal_cysteine():
scores = ManufacturabilityScores.from_amino_acids("C" + 6 * "A")
assert scores.difficult_n_terminal_residue
scores = ManufacturabilityScores.from_amino_acids(7 * "A")
assert not scores.difficult_n_terminal_residue
def test_n_terminal_glutamic_acid():
scores = ManufacturabilityScores.from_amino_acids("E" + 6 * "A")
assert scores.difficult_n_terminal_residue
scores = ManufacturabilityScores.from_amino_acids(7 * "A")
assert not scores.difficult_n_terminal_residue
def test_n_terminal_glutamine():
scores = ManufacturabilityScores.from_amino_acids("Q" + 6 * "A")
assert scores.difficult_n_terminal_residue
scores = ManufacturabilityScores.from_amino_acids(7 * "A")
assert not scores.difficult_n_terminal_residue
def test_asp_pro_bond_count():
scores = ManufacturabilityScores.from_amino_acids("A" * 7)
assert scores.asparagine_proline_bond_count == 0
scores = ManufacturabilityScores.from_amino_acids("NP" + "A" * 7 + "NP")
assert scores.asparagine_proline_bond_count == 2
def test_cysteine_count():
scores = ManufacturabilityScores.from_amino_acids("C" * 7)
assert scores.cysteine_count == 7
def cterm_7mer_gravy_score():
scores = ManufacturabilityScores.from_amino_acids("QLFY" + "A" * 7)
# hydropathy of alanine is 1.8 from Kyte & Doolittle 1982
assert scores.cterm_7mer_gravy_score == 1.8
def max_7mer_gravy_score():
scores = ManufacturabilityScores.from_amino_acids("H" * 3 + "A" * 7)
# hydropathy of alanine is 1.8, histidine is -3.2
# from Kyte & Doolittle 1982
assert scores.max_7mer_gravy_score == 1.8
|
/* eslint no-console: [2, { allow: ["log", "warn", "error", "assert"] }] */
import amqp from 'amqplib';
import async from 'async';
import _ from 'underscore';
import { getTaskId } from '../common/task';
// class for sending messages to rabbit exchange
// the class contains an internal queue
// where messages are stored in case the rabbit connection
// is not online. The class will attempt to recconect
// and resend message
export default class Rabbit {
constructor(address, workerExchangeName, resultExchangeName, routingKeys, debug) {
this.address = address;
this.channel = null;
// global var for storing items
// that have been sent but not acked
// if some error occures while in transit
// than place the item back into queue
this.itemInTransit = null;
this.sendItemToRabbit = (item, callback) => {
if (this.channel) {
// debug(`[INF] sending ${getTaskId(item)}`);
if (this.itemInTransit !== null) {
const error = new Error('should never send while something in transit');
debug('[ERROR] send while something in transit', error);
console.error('[ERROR] send while something in transit', error);
throw error;
}
this.itemInTransit = [item, callback];
const payload = new Buffer(JSON.stringify(item.payload));
const routingKey = item.routingKey
? `${workerExchangeName}.${item.routingKey}`
: workerExchangeName;
const fullRoutingKeyBase = `SUMMA-RESULTS.${resultExchangeName}`;
// console.log(`!!! publishing to '${exchangeName}' under '${routingKey}'`);
const resultRoutingKeys = {
// FIXME for now using the same for all
finalResult: `${fullRoutingKeyBase}.finalResult`,
partialResult: `${fullRoutingKeyBase}.partialResult`,
processingError: `${fullRoutingKeyBase}.processingError`,
};
this.channel.publish(workerExchangeName, routingKey, payload,
{
headers: {
replyToExchange: 'SUMMA-RESULTS',
replyToRoutingKeys: resultRoutingKeys,
},
},
(err) => {
if (err !== null) {
debug(`[WARN] send failed; placing ${getTaskId(item)} back into queue`, err); // Message nacked!
callback(err);
} else {
debug(`[INF] done sending ${getTaskId(item)}`); // Message acked!
callback(err);
}
},
);
} else {
debug(`[WARN] channel not ready; place back ${getTaskId(item)}`);
callback(new Error('channel not ready'));
}
};
const maximumConcurency = 1;
this.sendToRabbitExchange = async.queue(this.sendItemToRabbit, maximumConcurency);
this.sendToRabbitExchange.pause();
const channelReady = (ch) => {
debug('[INF] channelReady');
this.channel = ch;
this.sendToRabbitExchange.resume();
};
let connect;
const tryReconnect = (err) => {
this.channel = null;
this.sendToRabbitExchange.pause();
if (this.itemInTransit !== null) {
debug('[WARN] connection failure; placing item back into local queue', this.itemInTransit[0]);
const [, callback] = this.itemInTransit;
callback(new Error('connection failure'));
}
debug('[INF] tryReconnect in 3s; recovery from error', err);
setTimeout(connect, 3000);
};
const connectionEstablishedCallback = async (connection) => {
debug('[INF] connection established');
connection.on('error', tryReconnect);
const ch = await connection.createConfirmChannel();
debug('[INF] channel open');
await ch.assertExchange(workerExchangeName, 'topic', { durable: false });
debug('[INF] exchange asserted');
if (_.isEmpty(routingKeys)) {
// create default queue => exchangeName
const route = workerExchangeName;
const queueName = route;
const queue = await ch.assertQueue(queueName, { durable: false });
console.log('binding queue', queueName);
await ch.bindQueue(queue.queue, workerExchangeName, route);
} else {
// create queues for each routingKey => exchangeName.routingKey
for (let routingKey of routingKeys) {
const route = `${workerExchangeName}.${routingKey}`;
const queueName = route;
const queue = await ch.assertQueue(queueName, { durable: false });
console.log('binding queue', queueName);
await ch.bindQueue(queue.queue, workerExchangeName, route);
}
}
channelReady(ch);
return ch;
};
connect = () => {
amqp.connect(this.address)
.then(connectionEstablishedCallback, tryReconnect)
.catch((error) => {
// all exceptions should have been caught and handle above
debug('[ERROR] unexpected connection error', error);
console.error('[ERROR] unexpected connection error', error);
const err = new Error(`should have never been here ${error}`);
throw err;
});
};
connect();
}
push(item, sendDone) {
const handleError = (err) => {
this.itemInTransit = null; // clean up
if (err) {
this.sendToRabbitExchange.unshift(item, handleError);
} else if (sendDone) {
sendDone();
}
};
this.sendToRabbitExchange.push(item, handleError);
}
}
|
import React from 'react';
import { View , Text, StyleSheet, Button } from 'react-native';
import { useSelector, useDispatch } from 'react-redux';
import { addition , subtraction , reset} from './store/actions';
const Counter = (props) => {
const data = useSelector((state) => state.counter);
const dispatch = useDispatch();
return (
<View style={styles.container}>
<Button title='INCREMENT' onPress={() => dispatch(addition())} />
<Text>{data}</Text>
<Button title='DECREMENT' onPress={() => dispatch(subtraction())} />
</View>
);
};
export default Counter;
const styles = StyleSheet.create({
container: { flex: 1, justifyContent: 'center', alignItems: 'center' }});
|
it('testa a página da política de privavidade de forma independente', function(){
cy.visit("./src/privacy.html");
cy.contains('Talking About Testing').should('be.visible')
})
|
from rest_framework import serializers
from profiles_api import models
class HelloSerializer(serializers.Serializer): # converts data input into Python obj and vice versa
"""
Serializes a name field to test POST functionality of APIView
"""
name = serializers.CharField(max_length=10)
class UserProfileSerializer(serializers.ModelSerializer):
"""
Serializes fields for User Profile model
"""
class Meta:
model = models.UserProfile
fields = ('id', 'email', 'name', 'password')
extra_kwargs = {
'password': {
'write_only': True,
'style': {'input_type': 'password'}
}}
def create(self, validated_data):
"""
Create and return new user
"""
user = models.UserProfile.objects.create_user(
email=validated_data['email'],
name=validated_data['name'],
password=validated_data['password']
)
return user
def update(self, instance, validated_data):
"""
Update user account
"""
if 'password' in validated_data:
password = validated_data.pop('password')
instance.set_password(password)
return super().update(instance, validated_data)
class ProfileFeedItemSerializer(serializers.ModelSerializer):
"""
Serializes profile feed item model
"""
class Meta:
model = models.ProfileFeedItem
fields = ('id', 'user_profile', 'status_text', 'created_on')
extra_kwargs = {'user_profile': {'read_only': True}}
class BlogPost(serializers.ModelSerializer):
class Meta:
model = models.BlogPost
fields = ['pk', 'user_profile', 'title', 'content', 'timestamp']
extra_kwargs = {'user_profile': {'read_only': True}}
|
// Copyright 2017 the V8 project authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
description: Basic matching cases with Unicode groups
esid: prod-GroupSpecifier
features: [regexp-named-groups]
includes: [compareArray.js]
---*/
assert.compareArray(
"bab".match(/(?<a>a)/u),
["a", "a"],
'"bab".match(""bab".match(/(?<a>.(?<b>.(?<c>.)))/u).groups") must return ["a", "a"]'
);
assert.compareArray(
"bab".match(/(?<a42>a)/u),
["a", "a"],
'"bab".match(""bab".match(/(?<a>.(?<b>.(?<c>.)))/u).groups") must return ["a", "a"]'
);
assert.compareArray(
"bab".match(/(?<_>a)/u),
["a", "a"],
'"bab".match(""bab".match(/(?<a>.(?<b>.(?<c>.)))/u).groups") must return ["a", "a"]'
);
assert.compareArray(
"bab".match(/(?<$>a)/u),
["a", "a"],
'"bab".match(""bab".match(/(?<a>.(?<b>.(?<c>.)))/u).groups") must return ["a", "a"]'
);
assert.compareArray(
"bab".match(/.(?<$>a)./u),
["bab", "a"],
'"bab".match(""bab".match(/(?<a>.(?<b>.(?<c>.)))/u).groups") must return ["bab", "a"]'
);
assert.compareArray(
"bab".match(/.(?<a>a)(.)/u),
["bab", "a", "b"],
'"bab".match(""bab".match(/(?<a>.(?<b>.(?<c>.)))/u).groups") must return ["bab", "a", "b"]'
);
assert.compareArray(
"bab".match(/.(?<a>a)(?<b>.)/u),
["bab", "a", "b"],
'"bab".match(""bab".match(/(?<a>.(?<b>.(?<c>.)))/u).groups") must return ["bab", "a", "b"]'
);
assert.compareArray(
"bab".match(/.(?<a>\w\w)/u),
["bab", "ab"],
'"bab".match(""bab".match(/(?<a>.(?<b>.(?<c>.)))/u).groups") must return ["bab", "ab"]'
);
assert.compareArray(
"bab".match(/(?<a>\w\w\w)/u),
["bab", "bab"],
'"bab".match(""bab".match(/(?<a>.(?<b>.(?<c>.)))/u).groups") must return ["bab", "bab"]'
);
assert.compareArray(
"bab".match(/(?<a>\w\w)(?<b>\w)/u),
["bab", "ba", "b"],
'"bab".match(""bab".match(/(?<a>.(?<b>.(?<c>.)))/u).groups") must return ["bab", "ba", "b"]'
);
let {a, b, c} = /(?<a>.)(?<b>.)(?<c>.)\k<c>\k<b>\k<a>/u.exec("abccba").groups;
assert.sameValue(a, "a", 'The value of a is expected to be "a"');
assert.sameValue(b, "b", 'The value of b is expected to be "b"');
assert.sameValue(c, "c", 'The value of c is expected to be "c"');
assert.compareArray(
"bab".match(/(?<a>a)/u),
"bab".match(/(a)/u),
'"bab".match("/(?<a>.)(?<b>.)(?<c>.)k<c>k<b>k<a>/u.exec("abccba").groups") must return the same value returned by "bab".match(/(a)/u)'
);
assert.compareArray(
"bab".match(/(?<a42>a)/u),
"bab".match(/(a)/u),
'"bab".match("/(?<a>.)(?<b>.)(?<c>.)k<c>k<b>k<a>/u.exec("abccba").groups") must return the same value returned by "bab".match(/(a)/u)'
);
assert.compareArray(
"bab".match(/(?<_>a)/u),
"bab".match(/(a)/u),
'"bab".match("/(?<a>.)(?<b>.)(?<c>.)k<c>k<b>k<a>/u.exec("abccba").groups") must return the same value returned by "bab".match(/(a)/u)'
);
assert.compareArray(
"bab".match(/(?<$>a)/u),
"bab".match(/(a)/u),
'"bab".match("/(?<a>.)(?<b>.)(?<c>.)k<c>k<b>k<a>/u.exec("abccba").groups") must return the same value returned by "bab".match(/(a)/u)'
);
assert.compareArray(
"bab".match(/.(?<$>a)./u),
"bab".match(/.(a)./u),
'"bab".match("/(?<a>.)(?<b>.)(?<c>.)k<c>k<b>k<a>/u.exec("abccba").groups") must return the same value returned by "bab".match(/.(a)./u)'
);
assert.compareArray(
"bab".match(/.(?<a>a)(.)/u),
"bab".match(/.(a)(.)/u),
'"bab".match("/(?<a>.)(?<b>.)(?<c>.)k<c>k<b>k<a>/u.exec("abccba").groups") must return the same value returned by "bab".match(/.(a)(.)/u)'
);
assert.compareArray(
"bab".match(/.(?<a>a)(?<b>.)/u),
"bab".match(/.(a)(.)/u),
'"bab".match("/(?<a>.)(?<b>.)(?<c>.)k<c>k<b>k<a>/u.exec("abccba").groups") must return the same value returned by "bab".match(/.(a)(.)/u)'
);
assert.compareArray(
"bab".match(/.(?<a>\w\w)/u),
"bab".match(/.(\w\w)/u),
'"bab".match("/(?<a>.)(?<b>.)(?<c>.)k<c>k<b>k<a>/u.exec("abccba").groups") must return the same value returned by "bab".match(/.(ww)/u)'
);
assert.compareArray(
"bab".match(/(?<a>\w\w\w)/u),
"bab".match(/(\w\w\w)/u),
'"bab".match("/(?<a>.)(?<b>.)(?<c>.)k<c>k<b>k<a>/u.exec("abccba").groups") must return the same value returned by "bab".match(/(www)/u)'
);
assert.compareArray(
"bab".match(/(?<a>\w\w)(?<b>\w)/u),
"bab".match(/(\w\w)(\w)/u),
'"bab".match("/(?<a>.)(?<b>.)(?<c>.)k<c>k<b>k<a>/u.exec("abccba").groups") must return the same value returned by "bab".match(/(ww)(w)/u)'
);
assert.compareArray(
"bab".match(/(?<b>b).\1/u),
["bab", "b"],
'"bab".match("/(?<a>.)(?<b>.)(?<c>.)k<c>k<b>k<a>/u.exec("abccba").groups") must return ["bab", "b"]'
);
assert.compareArray(
"baba".match(/(.)(?<a>a)\1\2/u),
["baba", "b", "a"],
'"baba".match("/(?<a>.)(?<b>.)(?<c>.)k<c>k<b>k<a>/u.exec("abccba").groups") must return ["baba", "b", "a"]'
);
assert.compareArray(
"baba".match(/(.)(?<a>a)(?<b>\1)(\2)/u),
["baba", "b", "a", "b", "a"],
'"baba".match("/(?<a>.)(?<b>.)(?<c>.)k<c>k<b>k<a>/u.exec("abccba").groups") must return ["baba", "b", "a", "b", "a"]'
);
assert.compareArray(
"<a".match(/(?<lt><)a/u),
["<a", "<"],
'"<a".match("/(?<a>.)(?<b>.)(?<c>.)k<c>k<b>k<a>/u.exec("abccba").groups") must return ["<a", "<"]'
);
assert.compareArray(
">a".match(/(?<gt>>)a/u),
[">a", ">"],
'">a".match("/(?<a>.)(?<b>.)(?<c>.)k<c>k<b>k<a>/u.exec("abccba").groups") must return [">a", ">"]'
);
// Nested groups.
assert.compareArray(
"bab".match(/(?<a>.(?<b>.(?<c>.)))/u),
["bab", "bab", "ab", "b"],
'"bab".match("/(?<a>.)(?<b>.)(?<c>.)k<c>k<b>k<a>/u.exec("abccba").groups") must return ["bab", "bab", "ab", "b"]'
);
{
let {a, b, c} = "bab".match(/(?<a>.(?<b>.(?<c>.)))/u).groups
assert.sameValue(a, "bab", 'The value of a is expected to be "bab"');
assert.sameValue(b, "ab", 'The value of b is expected to be "ab"');
assert.sameValue(c, "b", 'The value of c is expected to be "b"');
}
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-05-15 16:15
from django.db import migrations
def ensure_slugs(apps, schema_editor):
ProductCategory = apps.get_model('shop', 'ProductCategory')
Product = apps.get_model('shop', 'Product')
for category in ProductCategory.objects.all():
category.save()
for product in Product.objects.all():
product.save()
class Migration(migrations.Migration):
dependencies = [
('shop', '0005_product_slug'),
]
operations = [
migrations.RunPython(ensure_slugs, migrations.RunPython.noop)
]
|
import React from "react";
export function clamp(number, lowerBound, upperBound) {
return Math.max(lowerBound, Math.min(number, upperBound));
}
export const getOnDemandLazySlides = spec => {
let onDemandSlides = [];
let startIndex = lazyStartIndex(spec);
let endIndex = lazyEndIndex(spec);
for (let slideIndex = startIndex; slideIndex < endIndex; slideIndex++) {
if (spec.lazyLoadedList.indexOf(slideIndex) < 0) {
onDemandSlides.push(slideIndex);
}
}
return onDemandSlides;
};
// return list of slides that need to be present
export const getRequiredLazySlides = spec => {
let requiredSlides = [];
let startIndex = lazyStartIndex(spec);
let endIndex = lazyEndIndex(spec);
for (let slideIndex = startIndex; slideIndex < endIndex; slideIndex++) {
requiredSlides.push(slideIndex);
}
return requiredSlides;
};
// startIndex that needs to be present
export const lazyStartIndex = spec =>
spec.currentSlide - lazySlidesOnLeft(spec);
export const lazyEndIndex = spec => spec.currentSlide + lazySlidesOnRight(spec);
export const lazySlidesOnLeft = spec =>
spec.centerMode
? Math.floor(spec.slidesToShow / 2) +
(parseInt(spec.centerPadding) > 0 ? 1 : 0)
: 0;
export const lazySlidesOnRight = spec =>
spec.centerMode
? Math.floor((spec.slidesToShow - 1) / 2) +
1 +
(parseInt(spec.centerPadding) > 0 ? 1 : 0)
: spec.slidesToShow;
// get width of an element
export const getWidth = elem => (elem && elem.offsetWidth) || 0;
export const getHeight = elem => (elem && elem.offsetHeight) || 0;
export const getSwipeDirection = (touchObject, verticalSwiping = false) => {
var xDist, yDist, r, swipeAngle;
xDist = touchObject.startX - touchObject.curX;
yDist = touchObject.startY - touchObject.curY;
r = Math.atan2(yDist, xDist);
swipeAngle = Math.round((r * 180) / Math.PI);
if (swipeAngle < 0) {
swipeAngle = 360 - Math.abs(swipeAngle);
}
if (
(swipeAngle <= 45 && swipeAngle >= 0) ||
(swipeAngle <= 360 && swipeAngle >= 315)
) {
return "left";
}
if (swipeAngle >= 135 && swipeAngle <= 225) {
return "right";
}
if (verticalSwiping === true) {
if (swipeAngle >= 35 && swipeAngle <= 135) {
return "up";
} else {
return "down";
}
}
return "vertical";
};
// whether or not we can go next
export const canGoNext = spec => {
let canGo = true;
if (!spec.infinite) {
if (spec.centerMode && spec.currentSlide >= spec.slideCount - 1) {
canGo = false;
} else if (
spec.slideCount <= spec.slidesToShow ||
spec.currentSlide >= spec.slideCount - spec.slidesToShow
) {
canGo = false;
}
}
return canGo;
};
// given an object and a list of keys, return new object with given keys
export const extractObject = (spec, keys) => {
let newObject = {};
keys.forEach(key => (newObject[key] = spec[key]));
return newObject;
};
// get initialized state
export const initializedState = spec => {
// spec also contains listRef, trackRef
let slideCount = React.Children.count(spec.children);
const listNode = spec.listRef;
let listWidth = Math.ceil(getWidth(listNode));
const trackNode = spec.trackRef && spec.trackRef.node;
let trackWidth = Math.ceil(getWidth(trackNode));
let slideWidth;
if (!spec.vertical) {
let centerPaddingAdj = spec.centerMode && parseInt(spec.centerPadding) * 2;
if (
typeof spec.centerPadding === "string" &&
spec.centerPadding.slice(-1) === "%"
) {
centerPaddingAdj *= listWidth / 100;
}
slideWidth = Math.ceil((listWidth - centerPaddingAdj) / spec.slidesToShow);
} else {
slideWidth = listWidth;
}
let slideHeight =
listNode && getHeight(listNode.querySelector('[data-index="0"]'));
let listHeight = slideHeight * spec.slidesToShow;
let currentSlide =
spec.currentSlide === undefined ? spec.initialSlide : spec.currentSlide;
if (spec.rtl && spec.currentSlide === undefined) {
currentSlide = slideCount - 1 - spec.initialSlide;
}
let lazyLoadedList = spec.lazyLoadedList || [];
let slidesToLoad = getOnDemandLazySlides({
...spec,
currentSlide,
lazyLoadedList
});
lazyLoadedList.concat(slidesToLoad);
let state = {
slideCount,
slideWidth,
listWidth,
trackWidth,
currentSlide,
slideHeight,
listHeight,
lazyLoadedList
};
if (spec.autoplaying === null && spec.autoplay) {
state["autoplaying"] = "playing";
}
return state;
};
export const slideHandler = spec => {
const {
waitForAnimate,
animating,
fade,
infinite,
index,
slideCount,
lazyLoadedList,
lazyLoad,
currentSlide,
centerMode,
slidesToScroll,
slidesToShow,
useCSS
} = spec;
if (waitForAnimate && animating) return {};
let animationSlide = index,
finalSlide,
animationLeft,
finalLeft;
let state = {},
nextState = {};
const targetSlide = infinite ? index : clamp(index, 0, slideCount - 1);
if (fade) {
if (!infinite && (index < 0 || index >= slideCount)) return {};
if (index < 0) {
animationSlide = index + slideCount;
} else if (index >= slideCount) {
animationSlide = index - slideCount;
}
if (lazyLoad && lazyLoadedList.indexOf(animationSlide) < 0) {
lazyLoadedList.push(animationSlide);
}
state = {
animating: true,
currentSlide: animationSlide,
lazyLoadedList,
targetSlide: animationSlide
};
nextState = { animating: false, targetSlide: animationSlide };
} else {
finalSlide = animationSlide;
if (animationSlide < 0) {
finalSlide = animationSlide + slideCount;
if (!infinite) finalSlide = 0;
else if (slideCount % slidesToScroll !== 0)
finalSlide = slideCount - (slideCount % slidesToScroll);
} else if (!canGoNext(spec) && animationSlide > currentSlide) {
animationSlide = finalSlide = currentSlide;
} else if (centerMode && animationSlide >= slideCount) {
animationSlide = infinite ? slideCount : slideCount - 1;
finalSlide = infinite ? 0 : slideCount - 1;
} else if (animationSlide >= slideCount) {
finalSlide = animationSlide - slideCount;
if (!infinite) finalSlide = slideCount - slidesToShow;
else if (slideCount % slidesToScroll !== 0) finalSlide = 0;
}
if (!infinite && animationSlide + slidesToShow >= slideCount) {
finalSlide = slideCount - slidesToShow;
}
animationLeft = getTrackLeft({ ...spec, slideIndex: animationSlide });
finalLeft = getTrackLeft({ ...spec, slideIndex: finalSlide });
if (!infinite) {
if (animationLeft === finalLeft) animationSlide = finalSlide;
animationLeft = finalLeft;
}
lazyLoad &&
lazyLoadedList.concat(
getOnDemandLazySlides({ ...spec, currentSlide: animationSlide })
);
if (!useCSS) {
state = {
currentSlide: finalSlide,
trackStyle: getTrackCSS({ ...spec, left: finalLeft }),
lazyLoadedList,
targetSlide
};
} else {
state = {
animating: true,
currentSlide: finalSlide,
trackStyle: getTrackAnimateCSS({ ...spec, left: animationLeft }),
lazyLoadedList,
targetSlide
};
nextState = {
animating: false,
currentSlide: finalSlide,
trackStyle: getTrackCSS({ ...spec, left: finalLeft }),
swipeLeft: null,
targetSlide
};
}
}
return { state, nextState };
};
export const changeSlide = (spec, options) => {
var indexOffset, previousInt, slideOffset, unevenOffset, targetSlide;
const {
slidesToScroll,
slidesToShow,
slideCount,
currentSlide,
targetSlide: previousTargetSlide,
lazyLoad,
infinite
} = spec;
unevenOffset = slideCount % slidesToScroll !== 0;
indexOffset = unevenOffset ? 0 : (slideCount - currentSlide) % slidesToScroll;
if (options.message === "previous") {
slideOffset =
indexOffset === 0 ? slidesToScroll : slidesToShow - indexOffset;
targetSlide = currentSlide - slideOffset;
if (lazyLoad && !infinite) {
previousInt = currentSlide - slideOffset;
targetSlide = previousInt === -1 ? slideCount - 1 : previousInt;
}
if (!infinite) {
targetSlide = previousTargetSlide - slidesToScroll;
}
} else if (options.message === "next") {
slideOffset = indexOffset === 0 ? slidesToScroll : indexOffset;
targetSlide = currentSlide + slideOffset;
if (lazyLoad && !infinite) {
targetSlide =
((currentSlide + slidesToScroll) % slideCount) + indexOffset;
}
if (!infinite) {
targetSlide = previousTargetSlide + slidesToScroll;
}
} else if (options.message === "dots") {
// Click on dots
targetSlide = options.index * options.slidesToScroll;
} else if (options.message === "children") {
// Click on the slides
targetSlide = options.index;
if (infinite) {
let direction = siblingDirection({ ...spec, targetSlide });
if (targetSlide > options.currentSlide && direction === "left") {
targetSlide = targetSlide - slideCount;
} else if (targetSlide < options.currentSlide && direction === "right") {
targetSlide = targetSlide + slideCount;
}
}
} else if (options.message === "index") {
targetSlide = Number(options.index);
}
return targetSlide;
};
export const keyHandler = (e, accessibility, rtl) => {
if (e.target.tagName.match("TEXTAREA|INPUT|SELECT") || !accessibility)
return "";
if (e.keyCode === 37) return rtl ? "next" : "previous";
if (e.keyCode === 39) return rtl ? "previous" : "next";
return "";
};
export const swipeStart = (e, swipe, draggable) => {
e.target.tagName === "IMG" && e.preventDefault();
if (!swipe || (!draggable && e.type.indexOf("mouse") !== -1)) return "";
return {
dragging: true,
touchObject: {
startX: e.touches ? e.touches[0].pageX : e.clientX,
startY: e.touches ? e.touches[0].pageY : e.clientY,
curX: e.touches ? e.touches[0].pageX : e.clientX,
curY: e.touches ? e.touches[0].pageY : e.clientY
}
};
};
export const swipeMove = (e, spec) => {
// spec also contains, trackRef and slideIndex
const {
scrolling,
animating,
vertical,
swipeToSlide,
verticalSwiping,
rtl,
currentSlide,
edgeFriction,
edgeDragged,
onEdge,
swiped,
swiping,
slideCount,
slidesToScroll,
infinite,
touchObject,
swipeEvent,
listHeight,
listWidth
} = spec;
if (scrolling) return;
if (animating) return e.preventDefault();
if (vertical && swipeToSlide && verticalSwiping) e.preventDefault();
let swipeLeft,
state = {};
let curLeft = getTrackLeft(spec);
touchObject.curX = e.touches ? e.touches[0].pageX : e.clientX;
touchObject.curY = e.touches ? e.touches[0].pageY : e.clientY;
touchObject.swipeLength = Math.round(
Math.sqrt(Math.pow(touchObject.curX - touchObject.startX, 2))
);
let verticalSwipeLength = Math.round(
Math.sqrt(Math.pow(touchObject.curY - touchObject.startY, 2))
);
if (!verticalSwiping && !swiping && verticalSwipeLength > 10) {
return { scrolling: true };
}
if (verticalSwiping) touchObject.swipeLength = verticalSwipeLength;
let positionOffset =
(!rtl ? 1 : -1) * (touchObject.curX > touchObject.startX ? 1 : -1);
if (verticalSwiping)
positionOffset = touchObject.curY > touchObject.startY ? 1 : -1;
let dotCount = Math.ceil(slideCount / slidesToScroll);
let swipeDirection = getSwipeDirection(spec.touchObject, verticalSwiping);
let touchSwipeLength = touchObject.swipeLength;
if (!infinite) {
if (
(currentSlide === 0 && swipeDirection === "right") ||
(currentSlide + 1 >= dotCount && swipeDirection === "left") ||
(!canGoNext(spec) && swipeDirection === "left")
) {
touchSwipeLength = touchObject.swipeLength * edgeFriction;
if (edgeDragged === false && onEdge) {
onEdge(swipeDirection);
state["edgeDragged"] = true;
}
}
}
if (!swiped && swipeEvent) {
swipeEvent(swipeDirection);
state["swiped"] = true;
}
if (!vertical) {
if (!rtl) {
swipeLeft = curLeft + touchSwipeLength * positionOffset;
} else {
swipeLeft = curLeft - touchSwipeLength * positionOffset;
}
} else {
swipeLeft =
curLeft + touchSwipeLength * (listHeight / listWidth) * positionOffset;
}
if (verticalSwiping) {
swipeLeft = curLeft + touchSwipeLength * positionOffset;
}
state = {
...state,
touchObject,
swipeLeft,
trackStyle: getTrackCSS({ ...spec, left: swipeLeft })
};
if (
Math.abs(touchObject.curX - touchObject.startX) <
Math.abs(touchObject.curY - touchObject.startY) * 0.8
) {
return state;
}
if (touchObject.swipeLength > 10) {
state["swiping"] = true;
e.preventDefault();
}
return state;
};
export const swipeEnd = (e, spec) => {
const {
dragging,
swipe,
touchObject,
listWidth,
touchThreshold,
verticalSwiping,
listHeight,
swipeToSlide,
scrolling,
onSwipe,
targetSlide,
currentSlide,
infinite
} = spec;
if (!dragging) {
if (swipe) e.preventDefault();
return {};
}
let minSwipe = verticalSwiping
? listHeight / touchThreshold
: listWidth / touchThreshold;
let swipeDirection = getSwipeDirection(touchObject, verticalSwiping);
// reset the state of touch related state variables.
let state = {
dragging: false,
edgeDragged: false,
scrolling: false,
swiping: false,
swiped: false,
swipeLeft: null,
touchObject: {}
};
if (scrolling) {
return state;
}
if (!touchObject.swipeLength) {
return state;
}
if (touchObject.swipeLength > minSwipe) {
e.preventDefault();
if (onSwipe) {
onSwipe(swipeDirection);
}
let slideCount, newSlide;
let activeSlide = infinite ? currentSlide : targetSlide;
switch (swipeDirection) {
case "left":
case "up":
newSlide = activeSlide + getSlideCount(spec);
slideCount = swipeToSlide ? checkNavigable(spec, newSlide) : newSlide;
state["currentDirection"] = 0;
break;
case "right":
case "down":
newSlide = activeSlide - getSlideCount(spec);
slideCount = swipeToSlide ? checkNavigable(spec, newSlide) : newSlide;
state["currentDirection"] = 1;
break;
default:
slideCount = activeSlide;
}
state["triggerSlideHandler"] = slideCount;
} else {
// Adjust the track back to it's original position.
let currentLeft = getTrackLeft(spec);
state["trackStyle"] = getTrackAnimateCSS({ ...spec, left: currentLeft });
}
return state;
};
export const getNavigableIndexes = spec => {
let max = spec.infinite ? spec.slideCount * 2 : spec.slideCount;
let breakpoint = spec.infinite ? spec.slidesToShow * -1 : 0;
let counter = spec.infinite ? spec.slidesToShow * -1 : 0;
let indexes = [];
while (breakpoint < max) {
indexes.push(breakpoint);
breakpoint = counter + spec.slidesToScroll;
counter += Math.min(spec.slidesToScroll, spec.slidesToShow);
}
return indexes;
};
export const checkNavigable = (spec, index) => {
const navigables = getNavigableIndexes(spec);
let prevNavigable = 0;
if (index > navigables[navigables.length - 1]) {
index = navigables[navigables.length - 1];
} else {
for (let n in navigables) {
if (index < navigables[n]) {
index = prevNavigable;
break;
}
prevNavigable = navigables[n];
}
}
return index;
};
export const getSlideCount = spec => {
const centerOffset = spec.centerMode
? spec.slideWidth * Math.floor(spec.slidesToShow / 2)
: 0;
if (spec.swipeToSlide) {
let swipedSlide;
const slickList = spec.listRef;
const slides = slickList.querySelectorAll(".slick-slide");
Array.from(slides).every(slide => {
if (!spec.vertical) {
if (
slide.offsetLeft - centerOffset + getWidth(slide) / 2 >
spec.swipeLeft * -1
) {
swipedSlide = slide;
return false;
}
} else {
if (slide.offsetTop + getHeight(slide) / 2 > spec.swipeLeft * -1) {
swipedSlide = slide;
return false;
}
}
return true;
});
if (!swipedSlide) {
return 0;
}
const currentIndex =
spec.rtl === true
? spec.slideCount - spec.currentSlide
: spec.currentSlide;
const slidesTraversed =
Math.abs(swipedSlide.dataset.index - currentIndex) || 1;
return slidesTraversed;
} else {
return spec.slidesToScroll;
}
};
export const checkSpecKeys = (spec, keysArray) =>
keysArray.reduce((value, key) => value && spec.hasOwnProperty(key), true)
? null
: console.error("Keys Missing:", spec);
export const getTrackCSS = spec => {
checkSpecKeys(spec, [
"left",
"variableWidth",
"slideCount",
"slidesToShow",
"slideWidth"
]);
let trackWidth, trackHeight;
const trackChildren = spec.slideCount + 2 * spec.slidesToShow;
if (!spec.vertical) {
trackWidth = getTotalSlides(spec) * spec.slideWidth;
} else {
trackHeight = trackChildren * spec.slideHeight;
}
let style = {
opacity: 1,
transition: "",
WebkitTransition: ""
};
if (spec.useTransform) {
let WebkitTransform = !spec.vertical
? "translate3d(" + spec.left + "px, 0px, 0px)"
: "translate3d(0px, " + spec.left + "px, 0px)";
let transform = !spec.vertical
? "translate3d(" + spec.left + "px, 0px, 0px)"
: "translate3d(0px, " + spec.left + "px, 0px)";
let msTransform = !spec.vertical
? "translateX(" + spec.left + "px)"
: "translateY(" + spec.left + "px)";
style = {
...style,
WebkitTransform,
transform,
msTransform
};
} else {
if (spec.vertical) {
style["top"] = spec.left;
} else {
style["left"] = spec.left;
}
}
if (spec.fade) style = { opacity: 1 };
if (trackWidth) style.width = trackWidth;
if (trackHeight) style.height = trackHeight;
// Fallback for IE8
if (window && !window.addEventListener && window.attachEvent) {
if (!spec.vertical) {
style.marginLeft = spec.left + "px";
} else {
style.marginTop = spec.left + "px";
}
}
return style;
};
export const getTrackAnimateCSS = spec => {
checkSpecKeys(spec, [
"left",
"variableWidth",
"slideCount",
"slidesToShow",
"slideWidth",
"speed",
"cssEase"
]);
let style = getTrackCSS(spec);
// useCSS is true by default so it can be undefined
if (spec.useTransform) {
style.WebkitTransition =
"-webkit-transform " + spec.speed + "ms " + spec.cssEase;
style.transition = "transform " + spec.speed + "ms " + spec.cssEase;
} else {
if (spec.vertical) {
style.transition = "top " + spec.speed + "ms " + spec.cssEase;
} else {
style.transition = "left " + spec.speed + "ms " + spec.cssEase;
}
}
return style;
};
export const getTrackLeft = spec => {
if (spec.unslick) {
return 0;
}
checkSpecKeys(spec, [
"slideIndex",
"trackRef",
"infinite",
"centerMode",
"slideCount",
"slidesToShow",
"slidesToScroll",
"slideWidth",
"listWidth",
"variableWidth",
"slideHeight"
]);
const {
slideIndex,
trackRef,
infinite,
centerMode,
slideCount,
slidesToShow,
slidesToScroll,
slideWidth,
listWidth,
variableWidth,
slideHeight,
fade,
vertical
} = spec;
var slideOffset = 0;
var targetLeft;
var targetSlide;
var verticalOffset = 0;
if (fade || spec.slideCount === 1) {
return 0;
}
let slidesToOffset = 0;
if (infinite) {
slidesToOffset = -getPreClones(spec); // bring active slide to the beginning of visual area
// if next scroll doesn't have enough children, just reach till the end of original slides instead of shifting slidesToScroll children
if (
slideCount % slidesToScroll !== 0 &&
slideIndex + slidesToScroll > slideCount
) {
slidesToOffset = -(slideIndex > slideCount
? slidesToShow - (slideIndex - slideCount)
: slideCount % slidesToScroll);
}
// shift current slide to center of the frame
if (centerMode) {
slidesToOffset += parseInt(slidesToShow / 2);
}
} else {
if (
slideCount % slidesToScroll !== 0 &&
slideIndex + slidesToScroll > slideCount
) {
slidesToOffset = slidesToShow - (slideCount % slidesToScroll);
}
if (centerMode) {
slidesToOffset = parseInt(slidesToShow / 2);
}
}
slideOffset = slidesToOffset * slideWidth;
verticalOffset = slidesToOffset * slideHeight;
if (!vertical) {
targetLeft = slideIndex * slideWidth * -1 + slideOffset;
} else {
targetLeft = slideIndex * slideHeight * -1 + verticalOffset;
}
if (variableWidth === true) {
var targetSlideIndex;
const trackElem = trackRef && trackRef.node;
targetSlideIndex = slideIndex + getPreClones(spec);
targetSlide = trackElem && trackElem.childNodes[targetSlideIndex];
targetLeft = targetSlide ? targetSlide.offsetLeft * -1 : 0;
if (centerMode === true) {
targetSlideIndex = infinite
? slideIndex + getPreClones(spec)
: slideIndex;
targetSlide = trackElem && trackElem.children[targetSlideIndex];
targetLeft = 0;
for (let slide = 0; slide < targetSlideIndex; slide++) {
targetLeft -=
trackElem &&
trackElem.children[slide] &&
trackElem.children[slide].offsetWidth;
}
targetLeft -= parseInt(spec.centerPadding);
targetLeft += targetSlide && (listWidth - targetSlide.offsetWidth) / 2;
}
}
return targetLeft;
};
export const getPreClones = spec => {
if (spec.unslick || !spec.infinite) {
return 0;
}
if (spec.variableWidth) {
return spec.slideCount;
}
return spec.slidesToShow + (spec.centerMode ? 1 : 0);
};
export const getPostClones = spec => {
if (spec.unslick || !spec.infinite) {
return 0;
}
return spec.slideCount;
};
export const getTotalSlides = spec =>
spec.slideCount === 1
? 1
: getPreClones(spec) + spec.slideCount + getPostClones(spec);
export const siblingDirection = spec => {
if (spec.targetSlide > spec.currentSlide) {
if (spec.targetSlide > spec.currentSlide + slidesOnRight(spec)) {
return "left";
}
return "right";
} else {
if (spec.targetSlide < spec.currentSlide - slidesOnLeft(spec)) {
return "right";
}
return "left";
}
};
export const slidesOnRight = ({
slidesToShow,
centerMode,
rtl,
centerPadding
}) => {
// returns no of slides on the right of active slide
if (centerMode) {
let right = (slidesToShow - 1) / 2 + 1;
if (parseInt(centerPadding) > 0) right += 1;
if (rtl && slidesToShow % 2 === 0) right += 1;
return right;
}
if (rtl) {
return 0;
}
return slidesToShow - 1;
};
export const slidesOnLeft = ({
slidesToShow,
centerMode,
rtl,
centerPadding
}) => {
// returns no of slides on the left of active slide
if (centerMode) {
let left = (slidesToShow - 1) / 2 + 1;
if (parseInt(centerPadding) > 0) left += 1;
if (!rtl && slidesToShow % 2 === 0) left += 1;
return left;
}
if (rtl) {
return slidesToShow - 1;
}
return 0;
};
export const canUseDOM = () =>
!!(
typeof window !== "undefined" &&
window.document &&
window.document.createElement
);
|
#!/usr/bin/env python
# Copyright 2012 - 2017, New York University and the TUF contributors
# SPDX-License-Identifier: MIT OR Apache-2.0
"""
<Program Name>
formats.py
<Author>
Geremy Condra
Vladimir Diaz <vladimir.v.diaz@gmail.com>
<Started>
Refactored April 30, 2012. -vladimir.v.diaz
<Copyright>
See LICENSE-MIT OR LICENSE for licensing information.
<Purpose>
A central location for all format-related checking of TUF objects.
Some crypto-related formats may also be defined in securesystemslib.
Note: 'formats.py' depends heavily on 'schema.py', so the 'schema.py'
module should be read and understood before tackling this module.
'formats.py' can be broken down into two sections. (1) Schemas and object
matching. (2) Functions that help produce or verify TUF objects.
The first section deals with schemas and object matching based on format.
There are two ways of checking the format of objects. The first method
raises a 'securesystemslib.exceptions.FormatError' exception if the match
fails and the other returns a Boolean result.
tuf.formats.<SCHEMA>.check_match(object)
tuf.formats.<SCHEMA>.matches(object)
Example:
rsa_key = {'keytype': 'rsa'
'keyid': 34892fc465ac76bc3232fab
'keyval': {'public': 'public_key',
'private': 'private_key'}
securesystemslib.formats.RSAKEY_SCHEMA.check_match(rsa_key)
securesystemslib.formats.RSAKEY_SCHEMA.matches(rsa_key)
In this example, if a dict key or dict value is missing or incorrect,
the match fails. There are numerous variations of object checking
provided by 'formats.py' and 'schema.py'.
The second section contains miscellaneous functions related to the format of
TUF objects.
Example:
signable_object = make_signable(unsigned_object)
"""
# Help with Python 3 compatibility, where the print statement is a function, an
# implicit relative import is invalid, and the '/' operator performs true
# division. Example: print 'hello world' raises a 'SyntaxError' exception.
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import binascii
import calendar
import datetime
import time
import copy
import securesystemslib.formats
import securesystemslib.schema as SCHEMA
import tuf
import six
# As per TUF spec 1.0.0 the spec version field must follow the Semantic
# Versioning 2.0.0 (semver) format. The regex pattern is provided by semver.
# https://semver.org/spec/v2.0.0.html#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string
SEMVER_2_0_0_SCHEMA = SCHEMA.RegularExpression(
r'(?P<major>0|[1-9]\d*)\.(?P<minor>0|[1-9]\d*)\.(?P<patch>0|[1-9]\d*)'
r'(?:-(?P<prerelease>(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)'
r'(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?'
r'(?:\+(?P<buildmetadata>[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?'
)
SPECIFICATION_VERSION_SCHEMA = SCHEMA.OneOf([
# However, temporarily allow "1.0" for backwards-compatibility in tuf-0.12.PATCH.
SCHEMA.String("1.0"),
SEMVER_2_0_0_SCHEMA
])
# A datetime in 'YYYY-MM-DDTHH:MM:SSZ' ISO 8601 format. The "Z" zone designator
# for the zero UTC offset is always used (i.e., a numerical offset is not
# supported.) Example: '2015-10-21T13:20:00Z'. Note: This is a simple format
# check, and an ISO8601 string should be fully verified when it is parsed.
ISO8601_DATETIME_SCHEMA = SCHEMA.RegularExpression(r'\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z')
# An integer representing the numbered version of a metadata file.
# Must be 1, or greater.
METADATAVERSION_SCHEMA = SCHEMA.Integer(lo=0)
# A relative file path (e.g., 'metadata/root/').
RELPATH_SCHEMA = SCHEMA.AnyString()
RELPATHS_SCHEMA = SCHEMA.ListOf(RELPATH_SCHEMA)
VERSIONINFO_SCHEMA = SCHEMA.Object(
object_name = 'VERSIONINFO_SCHEMA',
version = METADATAVERSION_SCHEMA)
# A string representing a role's name.
ROLENAME_SCHEMA = SCHEMA.AnyString()
# A role's threshold value (i.e., the minimum number
# of signatures required to sign a metadata file).
# Must be 1 and greater.
THRESHOLD_SCHEMA = SCHEMA.Integer(lo=1)
# A hexadecimal value in '23432df87ab..' format.
HEX_SCHEMA = SCHEMA.RegularExpression(r'[a-fA-F0-9]+')
# A path hash prefix is a hexadecimal string.
PATH_HASH_PREFIX_SCHEMA = HEX_SCHEMA
# A list of path hash prefixes.
PATH_HASH_PREFIXES_SCHEMA = SCHEMA.ListOf(PATH_HASH_PREFIX_SCHEMA)
# Role object in {'keyids': [keydids..], 'name': 'ABC', 'threshold': 1,
# 'paths':[filepaths..]} format.
# TODO: This is not a role. In further #660-related PRs, fix it, similar to
# the way I did in Uptane's TUF fork.
ROLE_SCHEMA = SCHEMA.Object(
object_name = 'ROLE_SCHEMA',
name = SCHEMA.Optional(ROLENAME_SCHEMA),
keyids = securesystemslib.formats.KEYIDS_SCHEMA,
threshold = THRESHOLD_SCHEMA,
terminating = SCHEMA.Optional(securesystemslib.formats.BOOLEAN_SCHEMA),
paths = SCHEMA.Optional(RELPATHS_SCHEMA),
path_hash_prefixes = SCHEMA.Optional(PATH_HASH_PREFIXES_SCHEMA))
# A dict of roles where the dict keys are role names and the dict values holding
# the role data/information.
ROLEDICT_SCHEMA = SCHEMA.DictOf(
key_schema = ROLENAME_SCHEMA,
value_schema = ROLE_SCHEMA)
# A dictionary of ROLEDICT, where dictionary keys can be repository names, and
# dictionary values containing information for each role available on the
# repository (corresponding to the repository belonging to named repository in
# the dictionary key)
ROLEDICTDB_SCHEMA = SCHEMA.DictOf(
key_schema = securesystemslib.formats.NAME_SCHEMA,
value_schema = ROLEDICT_SCHEMA)
# Command argument list, as used by the CLI tool.
# Example: {'keytype': ed25519, 'expires': 365,}
COMMAND_SCHEMA = SCHEMA.DictOf(
key_schema = securesystemslib.formats.NAME_SCHEMA,
value_schema = SCHEMA.Any())
# A dictionary holding version information.
VERSION_SCHEMA = SCHEMA.Object(
object_name = 'VERSION_SCHEMA',
major = SCHEMA.Integer(lo=0),
minor = SCHEMA.Integer(lo=0),
fix = SCHEMA.Integer(lo=0))
# A value that is either True or False, on or off, etc.
BOOLEAN_SCHEMA = SCHEMA.Boolean()
# A hexadecimal value in '23432df87ab..' format.
HASH_SCHEMA = SCHEMA.RegularExpression(r'[a-fA-F0-9]+')
# A key identifier (e.g., a hexadecimal value identifying an RSA key).
KEYID_SCHEMA = HASH_SCHEMA
# A list of KEYID_SCHEMA.
KEYIDS_SCHEMA = SCHEMA.ListOf(KEYID_SCHEMA)
# The actual values of a key, as opposed to meta data such as a key type and
# key identifier ('rsa', 233df889cb). For RSA keys, the key value is a pair of
# public and private keys in PEM Format stored as strings.
KEYVAL_SCHEMA = SCHEMA.Object(
object_name = 'KEYVAL_SCHEMA',
public = SCHEMA.AnyString(),
private = SCHEMA.Optional(SCHEMA.AnyString()))
# A generic TUF key. All TUF keys should be saved to metadata files in this
# format.
KEY_SCHEMA = SCHEMA.Object(
object_name = 'KEY_SCHEMA',
keytype = SCHEMA.AnyString(),
keyval = KEYVAL_SCHEMA,
expires = SCHEMA.Optional(ISO8601_DATETIME_SCHEMA))
# A dict where the dict keys hold a keyid and the dict values a key object.
KEYDICT_SCHEMA = SCHEMA.DictOf(
key_schema = KEYID_SCHEMA,
value_schema = KEY_SCHEMA)
# The format used by the key database to store keys. The dict keys hold a key
# identifier and the dict values any object. The key database should store
# key objects in the values (e.g., 'RSAKEY_SCHEMA', 'DSAKEY_SCHEMA').
KEYDB_SCHEMA = SCHEMA.DictOf(
key_schema = KEYID_SCHEMA,
value_schema = SCHEMA.Any())
# A schema holding the result of checking the signatures of a particular
# 'SIGNABLE_SCHEMA' role.
# For example, how many of the signatures for the 'Target' role are
# valid? This SCHEMA holds this information. See 'sig.py' for
# more information.
SIGNATURESTATUS_SCHEMA = SCHEMA.Object(
object_name = 'SIGNATURESTATUS_SCHEMA',
threshold = SCHEMA.Integer(),
good_sigs = KEYIDS_SCHEMA,
bad_sigs = KEYIDS_SCHEMA,
unknown_sigs = KEYIDS_SCHEMA,
untrusted_sigs = KEYIDS_SCHEMA)
# An integer representing length. Must be 0, or greater.
LENGTH_SCHEMA = SCHEMA.Integer(lo=0)
# A dict in {'sha256': '23432df87ab..', 'sha512': '34324abc34df..', ...} format.
HASHDICT_SCHEMA = SCHEMA.DictOf(
key_schema = SCHEMA.AnyString(),
value_schema = HASH_SCHEMA)
# Information about target files, like file length and file hash(es). This
# schema allows the storage of multiple hashes for the same file (e.g., sha256
# and sha512 may be computed for the same file and stored).
TARGETS_FILEINFO_SCHEMA = SCHEMA.Object(
object_name = 'TARGETS_FILEINFO_SCHEMA',
length = LENGTH_SCHEMA,
hashes = HASHDICT_SCHEMA,
custom = SCHEMA.Optional(SCHEMA.Object()))
# Information about snapshot and timestamp files. This schema allows for optional
# length and hashes, but version is mandatory.
METADATA_FILEINFO_SCHEMA = SCHEMA.Object(
object_name = 'METADATA_FILEINFO_SCHEMA',
length = SCHEMA.Optional(LENGTH_SCHEMA),
hashes = SCHEMA.Optional(HASHDICT_SCHEMA),
version = METADATAVERSION_SCHEMA)
# A dict holding the version or file information for a particular metadata
# role. The dict keys hold the relative file paths, and the dict values the
# corresponding version numbers and/or file information.
FILEINFODICT_SCHEMA = SCHEMA.DictOf(
key_schema = RELPATH_SCHEMA,
value_schema = SCHEMA.OneOf([VERSIONINFO_SCHEMA,
METADATA_FILEINFO_SCHEMA]))
# A dict holding the information for a particular target / file. The dict keys
# hold the relative file paths, and the dict values the corresponding file
# information.
FILEDICT_SCHEMA = SCHEMA.DictOf(
key_schema = RELPATH_SCHEMA,
value_schema = TARGETS_FILEINFO_SCHEMA)
# A dict holding a target info.
TARGETINFO_SCHEMA = SCHEMA.Object(
object_name = 'TARGETINFO_SCHEMA',
filepath = RELPATH_SCHEMA,
fileinfo = TARGETS_FILEINFO_SCHEMA)
# A list of TARGETINFO_SCHEMA.
TARGETINFOS_SCHEMA = SCHEMA.ListOf(TARGETINFO_SCHEMA)
# A string representing a named oject.
NAME_SCHEMA = SCHEMA.AnyString()
# A dict of repository names to mirrors.
REPO_NAMES_TO_MIRRORS_SCHEMA = SCHEMA.DictOf(
key_schema = NAME_SCHEMA,
value_schema = SCHEMA.ListOf(securesystemslib.formats.URL_SCHEMA))
# An object containing the map file's "mapping" attribute.
MAPPING_SCHEMA = SCHEMA.ListOf(SCHEMA.Object(
paths = RELPATHS_SCHEMA,
repositories = SCHEMA.ListOf(NAME_SCHEMA),
terminating = BOOLEAN_SCHEMA,
threshold = THRESHOLD_SCHEMA))
# A dict containing the map file (named 'map.json', by default). The format of
# the map file is covered in TAP 4: Multiple repository consensus on entrusted
# targets.
MAPFILE_SCHEMA = SCHEMA.Object(
repositories = REPO_NAMES_TO_MIRRORS_SCHEMA,
mapping = MAPPING_SCHEMA)
# Like ROLEDICT_SCHEMA, except that ROLE_SCHEMA instances are stored in order.
ROLELIST_SCHEMA = SCHEMA.ListOf(ROLE_SCHEMA)
# The delegated roles of a Targets role (a parent).
DELEGATIONS_SCHEMA = SCHEMA.Object(
keys = KEYDICT_SCHEMA,
roles = ROLELIST_SCHEMA)
# The number of hashed bins, or the number of delegated roles. See
# delegate_hashed_bins() in 'repository_tool.py' for an example. Note:
# Tools may require further restrictions on the number of bins, such
# as requiring them to be a power of 2.
NUMBINS_SCHEMA = SCHEMA.Integer(lo=1)
# The fileinfo format of targets specified in the repository and
# developer tools. The fields match that of TARGETS_FILEINFO_SCHEMA, only all
# fields are optional.
CUSTOM_SCHEMA = SCHEMA.DictOf(
key_schema = SCHEMA.AnyString(),
value_schema = SCHEMA.Any()
)
LOOSE_TARGETS_FILEINFO_SCHEMA = SCHEMA.Object(
object_name = "LOOSE_TARGETS_FILEINFO_SCHEMA",
length = SCHEMA.Optional(LENGTH_SCHEMA),
hashes = SCHEMA.Optional(HASHDICT_SCHEMA),
version = SCHEMA.Optional(METADATAVERSION_SCHEMA),
custom = SCHEMA.Optional(SCHEMA.Object())
)
PATH_FILEINFO_SCHEMA = SCHEMA.DictOf(
key_schema = RELPATH_SCHEMA,
value_schema = LOOSE_TARGETS_FILEINFO_SCHEMA)
# TUF roledb
ROLEDB_SCHEMA = SCHEMA.Object(
object_name = 'ROLEDB_SCHEMA',
keyids = SCHEMA.Optional(KEYIDS_SCHEMA),
signing_keyids = SCHEMA.Optional(KEYIDS_SCHEMA),
previous_keyids = SCHEMA.Optional(KEYIDS_SCHEMA),
threshold = SCHEMA.Optional(THRESHOLD_SCHEMA),
previous_threshold = SCHEMA.Optional(THRESHOLD_SCHEMA),
version = SCHEMA.Optional(METADATAVERSION_SCHEMA),
expires = SCHEMA.Optional(ISO8601_DATETIME_SCHEMA),
signatures = SCHEMA.Optional(securesystemslib.formats.SIGNATURES_SCHEMA),
paths = SCHEMA.Optional(SCHEMA.OneOf([RELPATHS_SCHEMA, PATH_FILEINFO_SCHEMA])),
path_hash_prefixes = SCHEMA.Optional(PATH_HASH_PREFIXES_SCHEMA),
delegations = SCHEMA.Optional(DELEGATIONS_SCHEMA),
partial_loaded = SCHEMA.Optional(BOOLEAN_SCHEMA))
# A signable object. Holds the signing role and its associated signatures.
SIGNABLE_SCHEMA = SCHEMA.Object(
object_name = 'SIGNABLE_SCHEMA',
signed = SCHEMA.Any(),
signatures = SCHEMA.ListOf(securesystemslib.formats.SIGNATURE_SCHEMA))
# Root role: indicates root keys and top-level roles.
ROOT_SCHEMA = SCHEMA.Object(
object_name = 'ROOT_SCHEMA',
_type = SCHEMA.String('root'),
spec_version = SPECIFICATION_VERSION_SCHEMA,
version = METADATAVERSION_SCHEMA,
consistent_snapshot = BOOLEAN_SCHEMA,
expires = ISO8601_DATETIME_SCHEMA,
keys = KEYDICT_SCHEMA,
roles = ROLEDICT_SCHEMA)
# Targets role: Indicates targets and delegates target paths to other roles.
TARGETS_SCHEMA = SCHEMA.Object(
object_name = 'TARGETS_SCHEMA',
_type = SCHEMA.String('targets'),
spec_version = SPECIFICATION_VERSION_SCHEMA,
version = METADATAVERSION_SCHEMA,
expires = ISO8601_DATETIME_SCHEMA,
targets = FILEDICT_SCHEMA,
delegations = SCHEMA.Optional(DELEGATIONS_SCHEMA))
# Snapshot role: indicates the latest versions of all metadata (except
# timestamp).
SNAPSHOT_SCHEMA = SCHEMA.Object(
object_name = 'SNAPSHOT_SCHEMA',
_type = SCHEMA.String('snapshot'),
version = METADATAVERSION_SCHEMA,
expires = securesystemslib.formats.ISO8601_DATETIME_SCHEMA,
spec_version = SPECIFICATION_VERSION_SCHEMA,
meta = FILEINFODICT_SCHEMA)
# Timestamp role: indicates the latest version of the snapshot file.
TIMESTAMP_SCHEMA = SCHEMA.Object(
object_name = 'TIMESTAMP_SCHEMA',
_type = SCHEMA.String('timestamp'),
spec_version = SPECIFICATION_VERSION_SCHEMA,
version = METADATAVERSION_SCHEMA,
expires = securesystemslib.formats.ISO8601_DATETIME_SCHEMA,
meta = FILEINFODICT_SCHEMA)
# project.cfg file: stores information about the project in a json dictionary
PROJECT_CFG_SCHEMA = SCHEMA.Object(
object_name = 'PROJECT_CFG_SCHEMA',
project_name = SCHEMA.AnyString(),
layout_type = SCHEMA.OneOf([SCHEMA.String('repo-like'), SCHEMA.String('flat')]),
targets_location = securesystemslib.formats.PATH_SCHEMA,
metadata_location = securesystemslib.formats.PATH_SCHEMA,
prefix = securesystemslib.formats.PATH_SCHEMA,
public_keys = securesystemslib.formats.KEYDICT_SCHEMA,
threshold = SCHEMA.Integer(lo = 0, hi = 2)
)
# A schema containing information a repository mirror may require,
# such as a url, the path of the directory metadata files, etc.
MIRROR_SCHEMA = SCHEMA.Object(
object_name = 'MIRROR_SCHEMA',
url_prefix = securesystemslib.formats.URL_SCHEMA,
metadata_path = RELPATH_SCHEMA,
targets_path = RELPATH_SCHEMA,
confined_target_dirs = RELPATHS_SCHEMA,
custom = SCHEMA.Optional(SCHEMA.Object()))
# A dictionary of mirrors where the dict keys hold the mirror's name and
# and the dict values the mirror's data (i.e., 'MIRROR_SCHEMA').
# The repository class of 'updater.py' accepts dictionaries
# of this type provided by the TUF client.
MIRRORDICT_SCHEMA = SCHEMA.DictOf(
key_schema = SCHEMA.AnyString(),
value_schema = MIRROR_SCHEMA)
# A Mirrorlist: indicates all the live mirrors, and what documents they
# serve.
MIRRORLIST_SCHEMA = SCHEMA.Object(
object_name = 'MIRRORLIST_SCHEMA',
_type = SCHEMA.String('mirrors'),
version = METADATAVERSION_SCHEMA,
expires = securesystemslib.formats.ISO8601_DATETIME_SCHEMA,
mirrors = SCHEMA.ListOf(MIRROR_SCHEMA))
# Any of the role schemas (e.g., TIMESTAMP_SCHEMA, SNAPSHOT_SCHEMA, etc.)
ANYROLE_SCHEMA = SCHEMA.OneOf([ROOT_SCHEMA, TARGETS_SCHEMA, SNAPSHOT_SCHEMA,
TIMESTAMP_SCHEMA, MIRROR_SCHEMA])
# The format of the resulting "scp config dict" after extraction from the
# push configuration file (i.e., push.cfg). In the case of a config file
# utilizing the scp transfer module, it must contain the 'general' and 'scp'
# sections, where 'general' must contain a 'transfer_module' and
# 'metadata_path' entry, and 'scp' the 'host', 'user', 'identity_file', and
# 'remote_directory' entries.
SCPCONFIG_SCHEMA = SCHEMA.Object(
object_name = 'SCPCONFIG_SCHEMA',
general = SCHEMA.Object(
object_name = '[general]',
transfer_module = SCHEMA.String('scp'),
metadata_path = securesystemslib.formats.PATH_SCHEMA,
targets_directory = securesystemslib.formats.PATH_SCHEMA),
scp=SCHEMA.Object(
object_name = '[scp]',
host = securesystemslib.formats.URL_SCHEMA,
user = securesystemslib.formats.NAME_SCHEMA,
identity_file = securesystemslib.formats.PATH_SCHEMA,
remote_directory = securesystemslib.formats.PATH_SCHEMA))
# The format of the resulting "receive config dict" after extraction from the
# receive configuration file (i.e., receive.cfg). The receive config file
# must contain a 'general' section, and this section the 'pushroots',
# 'repository_directory', 'metadata_directory', 'targets_directory', and
# 'backup_directory' entries.
RECEIVECONFIG_SCHEMA = SCHEMA.Object(
object_name = 'RECEIVECONFIG_SCHEMA', general=SCHEMA.Object(
object_name = '[general]',
pushroots = SCHEMA.ListOf(securesystemslib.formats.PATH_SCHEMA),
repository_directory = securesystemslib.formats.PATH_SCHEMA,
metadata_directory = securesystemslib.formats.PATH_SCHEMA,
targets_directory = securesystemslib.formats.PATH_SCHEMA,
backup_directory = securesystemslib.formats.PATH_SCHEMA))
def make_signable(role_schema):
"""
<Purpose>
Return the role metadata 'role_schema' in 'SIGNABLE_SCHEMA' format.
'role_schema' is added to the 'signed' key, and an empty list
initialized to the 'signatures' key. The caller adds signatures
to this second field.
Note: check_signable_object_format() should be called after
make_signable() and signatures added to ensure the final
signable object has a valid format (i.e., a signable containing
a supported role metadata).
<Arguments>
role_schema:
A role schema dict (e.g., 'ROOT_SCHEMA', 'SNAPSHOT_SCHEMA').
<Exceptions>
None.
<Side Effects>
None.
<Returns>
A dict in 'SIGNABLE_SCHEMA' format.
"""
if not isinstance(role_schema, dict) or 'signed' not in role_schema:
return { 'signed' : role_schema, 'signatures' : [] }
else:
return role_schema
def build_dict_conforming_to_schema(schema, **kwargs):
"""
<Purpose>
Given a schema.Object object (for example, TIMESTAMP_SCHEMA from this
module) and a set of keyword arguments, create a dictionary that conforms
to the given schema, using the keyword arguments to define the elements of
the new dict.
Checks the result to make sure that it conforms to the given schema, raising
an error if not.
<Arguments>
schema
A schema.Object, like TIMESTAMP_SCHEMA, TARGETS_FILEINFO_SCHEMA,
securesystemslib.formats.SIGNATURE_SCHEMA, etc.
**kwargs
A keyword argument for each element of the schema. Optional arguments
may be included or skipped, but all required arguments must be included.
For example, for TIMESTAMP_SCHEMA, a call might look like:
build_dict_conforming_to_schema(
TIMESTAMP_SCHEMA,
_type='timestamp',
spec_version='1.0.0',
version=1,
expires='2020-01-01T00:00:00Z',
meta={...})
Some arguments will be filled in if excluded: _type, spec_version
<Returns>
A dictionary conforming to the given schema. Adds certain required fields
if they are missing and can be deduced from the schema. The data returned
is a deep copy.
<Exceptions>
securesystemslib.exceptions.FormatError
if the provided data does not match the schema when assembled.
<Side Effects>
None. In particular, the provided values are not modified, and the
returned dictionary does not include references to them.
"""
# Check the schema argument type (must provide check_match and _required).
if not isinstance(schema, SCHEMA.Object):
raise ValueError(
'The first argument must be a schema.Object instance, but is not. '
'Given schema: ' + repr(schema))
# Make a copy of the provided fields so that the caller's provided values
# do not change when the returned values are changed.
dictionary = copy.deepcopy(kwargs)
# Automatically provide certain schema properties if they are not already
# provided and are required in objects of class <schema>.
# This includes:
# _type: <securesystemslib.schema.String object>
# spec_version: SPECIFICATION_VERSION_SCHEMA
#
# (Please note that _required is slightly misleading, as it includes both
# required and optional elements. It should probably be called _components.)
#
for key, element_type in schema._required: #pylint: disable=protected-access
if key in dictionary:
# If the field has been provided, proceed normally.
continue
elif isinstance(element_type, SCHEMA.Optional):
# If the field has NOT been provided but IS optional, proceed without it.
continue
else:
# If the field has not been provided and is required, check to see if
# the field is one of the fields we automatically fill.
# Currently, the list is limited to ['_type', 'spec_version'].
if key == '_type' and isinstance(element_type, SCHEMA.String):
# A SCHEMA.String stores its expected value in _string, so use that.
dictionary[key] = element_type._string #pylint: disable=protected-access
elif (key == 'spec_version' and
element_type == SPECIFICATION_VERSION_SCHEMA):
# If not provided, use the specification version in tuf/__init__.py
dictionary[key] = tuf.SPECIFICATION_VERSION
# If what we produce does not match the provided schema, raise a FormatError.
schema.check_match(dictionary)
return dictionary
# A dict holding the recognized schemas for the top-level roles.
SCHEMAS_BY_TYPE = {
'root' : ROOT_SCHEMA,
'targets' : TARGETS_SCHEMA,
'snapshot' : SNAPSHOT_SCHEMA,
'timestamp' : TIMESTAMP_SCHEMA,
'mirrors' : MIRRORLIST_SCHEMA}
def datetime_to_unix_timestamp(datetime_object):
"""
<Purpose>
Convert 'datetime_object' (in datetime.datetime()) format) to a Unix/POSIX
timestamp. For example, Python's time.time() returns a Unix timestamp, and
includes the number of microseconds. 'datetime_object' is converted to UTC.
>>> datetime_object = datetime.datetime(1985, 10, 26, 1, 22)
>>> timestamp = datetime_to_unix_timestamp(datetime_object)
>>> timestamp
499137720
<Arguments>
datetime_object:
The datetime.datetime() object to convert to a Unix timestamp.
<Exceptions>
securesystemslib.exceptions.FormatError, if 'datetime_object' is not a
datetime.datetime() object.
<Side Effects>
None.
<Returns>
A unix (posix) timestamp (e.g., 499137660).
"""
# Is 'datetime_object' a datetime.datetime() object?
# Raise 'securesystemslib.exceptions.FormatError' if not.
if not isinstance(datetime_object, datetime.datetime):
message = repr(datetime_object) + ' is not a datetime.datetime() object.'
raise securesystemslib.exceptions.FormatError(message)
unix_timestamp = calendar.timegm(datetime_object.timetuple())
return unix_timestamp
def unix_timestamp_to_datetime(unix_timestamp):
"""
<Purpose>
Convert 'unix_timestamp' (i.e., POSIX time, in UNIX_TIMESTAMP_SCHEMA format)
to a datetime.datetime() object. 'unix_timestamp' is the number of seconds
since the epoch (January 1, 1970.)
>>> datetime_object = unix_timestamp_to_datetime(1445455680)
>>> datetime_object
datetime.datetime(2015, 10, 21, 19, 28)
<Arguments>
unix_timestamp:
An integer representing the time (e.g., 1445455680). Conformant to
'securesystemslib.formats.UNIX_TIMESTAMP_SCHEMA'.
<Exceptions>
securesystemslib.exceptions.FormatError, if 'unix_timestamp' is improperly
formatted.
<Side Effects>
None.
<Returns>
A datetime.datetime() object corresponding to 'unix_timestamp'.
"""
# Is 'unix_timestamp' properly formatted?
# Raise 'securesystemslib.exceptions.FormatError' if there is a mismatch.
securesystemslib.formats.UNIX_TIMESTAMP_SCHEMA.check_match(unix_timestamp)
# Convert 'unix_timestamp' to a 'time.struct_time', in UTC. The Daylight
# Savings Time (DST) flag is set to zero. datetime.fromtimestamp() is not
# used because it returns a local datetime.
struct_time = time.gmtime(unix_timestamp)
# Extract the (year, month, day, hour, minutes, seconds) arguments for the
# datetime object to be returned.
datetime_object = datetime.datetime(*struct_time[:6])
return datetime_object
def format_base64(data):
"""
<Purpose>
Return the base64 encoding of 'data' with whitespace and '=' signs omitted.
<Arguments>
data:
Binary or buffer of data to convert.
<Exceptions>
securesystemslib.exceptions.FormatError, if the base64 encoding fails or the
argument is invalid.
<Side Effects>
None.
<Returns>
A base64-encoded string.
"""
try:
return binascii.b2a_base64(data).decode('utf-8').rstrip('=\n ')
except (TypeError, binascii.Error) as e:
raise securesystemslib.exceptions.FormatError('Invalid base64'
' encoding: ' + str(e))
def parse_base64(base64_string):
"""
<Purpose>
Parse a base64 encoding with whitespace and '=' signs omitted.
<Arguments>
base64_string:
A string holding a base64 value.
<Exceptions>
securesystemslib.exceptions.FormatError, if 'base64_string' cannot be parsed
due to an invalid base64 encoding.
<Side Effects>
None.
<Returns>
A byte string representing the parsed based64 encoding of
'base64_string'.
"""
if not isinstance(base64_string, six.string_types):
message = 'Invalid argument: '+repr(base64_string)
raise securesystemslib.exceptions.FormatError(message)
extra = len(base64_string) % 4
if extra:
padding = '=' * (4 - extra)
base64_string = base64_string + padding
try:
return binascii.a2b_base64(base64_string.encode('utf-8'))
except (TypeError, binascii.Error) as e:
raise securesystemslib.exceptions.FormatError('Invalid base64'
' encoding: ' + str(e))
def make_targets_fileinfo(length, hashes, custom=None):
"""
<Purpose>
Create a dictionary conformant to 'TARGETS_FILEINFO_SCHEMA'.
This dict describes a target file.
<Arguments>
length:
An integer representing the size of the file.
hashes:
A dict of hashes in 'HASHDICT_SCHEMA' format, which has the form:
{'sha256': 123df8a9b12, 'sha512': 324324dfc121, ...}
custom:
An optional object providing additional information about the file.
<Exceptions>
securesystemslib.exceptions.FormatError, if the 'TARGETS_FILEINFO_SCHEMA' to be
returned does not have the correct format.
<Returns>
A dictionary conformant to 'TARGETS_FILEINFO_SCHEMA', representing the file
information of a target file.
"""
fileinfo = {'length' : length, 'hashes' : hashes}
if custom is not None:
fileinfo['custom'] = custom
# Raise 'securesystemslib.exceptions.FormatError' if the check fails.
TARGETS_FILEINFO_SCHEMA.check_match(fileinfo)
return fileinfo
def make_metadata_fileinfo(version, length=None, hashes=None):
"""
<Purpose>
Create a dictionary conformant to 'METADATA_FILEINFO_SCHEMA'.
This dict describes one of the metadata files used for timestamp and
snapshot roles.
<Arguments>
version:
An integer representing the version of the file.
length:
An optional integer representing the size of the file.
hashes:
An optional dict of hashes in 'HASHDICT_SCHEMA' format, which has the form:
{'sha256': 123df8a9b12, 'sha512': 324324dfc121, ...}
<Exceptions>
securesystemslib.exceptions.FormatError, if the 'METADATA_FILEINFO_SCHEMA' to be
returned does not have the correct format.
<Returns>
A dictionary conformant to 'METADATA_FILEINFO_SCHEMA', representing the file
information of a metadata file.
"""
fileinfo = {'version' : version}
if length:
fileinfo['length'] = length
if hashes:
fileinfo['hashes'] = hashes
# Raise 'securesystemslib.exceptions.FormatError' if the check fails.
METADATA_FILEINFO_SCHEMA.check_match(fileinfo)
return fileinfo
def make_versioninfo(version_number):
"""
<Purpose>
Create a dictionary conformant to 'VERSIONINFO_SCHEMA'. This dict
describes both metadata and target files.
<Arguments>
version_number:
An integer representing the version of a particular metadata role.
The dictionary returned by this function is expected to be included
in Snapshot metadata.
<Exceptions>
securesystemslib.exceptions.FormatError, if the dict to be returned does not
have the correct format (i.e., VERSIONINFO_SCHEMA).
<Side Effects>
None.
<Returns>
A dictionary conformant to 'VERSIONINFO_SCHEMA', containing the version
information of a metadata role.
"""
versioninfo = {'version': version_number}
# Raise 'securesystemslib.exceptions.FormatError' if 'versioninfo' is
# improperly formatted.
VERSIONINFO_SCHEMA.check_match(versioninfo)
return versioninfo
def expected_meta_rolename(meta_rolename):
"""
<Purpose>
Ensure 'meta_rolename' is properly formatted.
'targets' is returned as 'Targets'.
'targets role1' is returned as 'Targets Role1'.
The words in the string (i.e., separated by whitespace)
are capitalized.
<Arguments>
meta_rolename:
A string representing the rolename.
E.g., 'root', 'targets'.
<Exceptions>
securesystemslib.exceptions.FormatError, if 'meta_rolename' is improperly
formatted.
<Side Effects>
None.
<Returns>
A string (e.g., 'Root', 'Targets').
"""
# Does 'meta_rolename' have the correct type?
# This check ensures 'meta_rolename' conforms to
# 'securesystemslib.formats.NAME_SCHEMA'.
# Raise 'securesystemslib.exceptions.FormatError' if there is a mismatch.
securesystemslib.formats.NAME_SCHEMA.check_match(meta_rolename)
return meta_rolename.lower()
def check_signable_object_format(signable):
"""
<Purpose>
Ensure 'signable' is properly formatted, conformant to
'SIGNABLE_SCHEMA'. Return the signing role on
success. Note: The 'signed' field of a 'SIGNABLE_SCHEMA' is checked
against securesystemslib.schema.Any(). The 'signed' field, however, should
actually hold one of the supported role schemas (e.g., 'ROOT_SCHEMA',
'TARGETS_SCHEMA'). The role schemas all differ in their format, so this
function determines exactly which schema is listed in the 'signed' field.
<Arguments>
signable:
The signable object compared against 'SIGNABLE.SCHEMA'.
<Exceptions>
securesystemslib.exceptions.FormatError, if 'signable' does not have the
correct format.
<Side Effects>
None.
<Returns>
A string representing the signing role (e.g., 'root', 'targets').
The role string is returned with characters all lower case.
"""
# Does 'signable' have the correct type?
# This check ensures 'signable' conforms to
# 'SIGNABLE_SCHEMA'.
SIGNABLE_SCHEMA.check_match(signable)
try:
role_type = signable['signed']['_type']
except (KeyError, TypeError) as error:
six.raise_from(securesystemslib.exceptions.FormatError(
'Untyped signable object.'), error)
try:
schema = SCHEMAS_BY_TYPE[role_type]
except KeyError as error:
six.raise_from(securesystemslib.exceptions.FormatError(
'Unrecognized type ' + repr(role_type)), error)
# 'securesystemslib.exceptions.FormatError' raised if 'signable' does not
# have a properly formatted role schema.
schema.check_match(signable['signed'])
return role_type.lower()
if __name__ == '__main__':
# The interactive sessions of the documentation strings can
# be tested by running formats.py as a standalone module.
# python -B formats.py
import doctest
doctest.testmod()
|
'use strict';
// Declare app level module which depends on views, and components
angular.module('rx-angular-example', [
'ngRoute',
'rx',
'rx-angular-example.wikipedia',
'infra.wikipedia'
]).
config(['$routeProvider', $routeProvider =>
$routeProvider.otherwise({redirectTo: '/wikipedia'})
]);
|
# -*- coding: utf-8 -*-
# cython: language_level=3
# Copyright (c) 2020 Nekokatt
# Copyright (c) 2021-present davfsa
#
# 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.
"""Reflection utilities."""
from __future__ import annotations
__all__: typing.Sequence[str] = ("resolve_signature",)
import functools
import inspect
import sys
import typing
if typing.TYPE_CHECKING:
_T = typing.TypeVar("_T")
EMPTY: typing.Final[typing.Any] = inspect.Parameter.empty
"""A singleton that empty annotations will be set to in `resolve_signature`."""
def resolve_signature(func: typing.Callable[..., typing.Any]) -> inspect.Signature:
"""Get the `inspect.Signature` of `func` with resolved forward annotations.
Parameters
----------
func : typing.Callable[..., typing.Any]
The function to get the resolved annotations from.
!!! warning
This will use `builtins.eval` to resolve string type-hints and forward
references. This has a slight performance overhead, so attempt to cache
this info as much as possible.
Returns
-------
inspect.Signature
A `inspect.Signature` object with all forward reference annotations
resolved.
"""
if sys.version_info >= (3, 10):
return inspect.signature(func, eval_str=True)
signature = inspect.signature(func)
resolved_typehints = typing.get_type_hints(func)
params = []
none_type = type(None)
for name, param in signature.parameters.items():
if isinstance(param.annotation, str):
param = param.replace(annotation=resolved_typehints[name] if name in resolved_typehints else EMPTY)
if param.annotation is none_type:
param = param.replace(annotation=None)
params.append(param)
return_annotation = resolved_typehints.get("return", EMPTY)
if return_annotation is none_type:
return_annotation = None
return signature.replace(parameters=params, return_annotation=return_annotation)
def profiled(call: typing.Callable[..., _T]) -> typing.Callable[..., _T]: # pragma: no cover
"""Decorate a callable and profile each invocation of it.
Profile results are dumped to stdout.
!!! warning
This is NOT part of the public API. It should be considered to be
internal detail and will likely be removed without prior warning in
the future. You have been warned!
"""
import cProfile
if inspect.iscoroutinefunction(call):
raise TypeError("cannot profile async calls")
invoker = compile("result = call(*args, **kwargs)", filename=call.__module__, mode="exec", optimize=1)
@functools.wraps(call)
def wrapped(*args: typing.Any, **kwargs: typing.Any) -> typing.Any:
print("Profiling", call.__module__ + "." + call.__qualname__) # noqa: T001 print disallowed.
cProfile.runctx(invoker, globals=globals(), locals=locals(), filename=None, sort=1)
return locals()["result"]
return wrapped
|
export * from './casing'
|
var searchData=
[
['varying_5fparams_2ecpp_303',['varying_params.cpp',['../varying__params_8cpp.html',1,'']]]
];
|
import babelJest from 'babel-jest';
export default babelJest.createTransformer({
presets: [
[
require.resolve('babel-preset-umi'),
{
commonjs: true,
disableTransform: true,
},
],
],
plugins: [
[
require.resolve('babel-plugin-module-resolver'),
{
alias: {
'ts-jest-babel-7': require.resolve('ts-jest-babel-7'),
react: require.resolve('react'),
'react-dom': require.resolve('react-dom'),
enzyme: require.resolve('enzyme'),
},
},
'module-resolver-in-umi-test',
],
],
});
|
// First, we must import the schema creator
import createSchema from 'part:@sanity/base/schema-creator'
// Then import schema types from any plugins that might expose them
import schemaTypes from 'all:part:@sanity/base/schema-type'
// We import object and document schemas
import blockContent from './blockContent'
import crewMember from './crewMember'
import castMember from './castMember'
import movie from './movie'
import person from './person'
import screening from './screening'
import plotSummary from './plotSummary'
import plotSummaries from './plotSummaries'
// Then we give our schema to the builder and provide the result to Sanity
export default createSchema({
// We name our schema
name: 'default',
// Then proceed to concatenate our our document type
// to the ones provided by any plugins that are installed
types: schemaTypes.concat([
// The following are document types which will appear
// in the studio.
movie,
person,
screening,
// When added to this list, object types can be used as
// { type: 'typename' } in other document schemas
blockContent,
plotSummary,
plotSummaries,
castMember,
crewMember
])
})
|
const fs = require('fs');
const { google } = require('googleapis');
const { authenticate } = require('./auth');
/**
* Call the "testRunner" to test function on the deployed script.
* @param {google.auth.OAuth2} auth An authorized OAuth2 client.
* @return [Number] Exit with the number of failed tests
*/
function callAppsScript(auth) {
const script = google.script({ version: 'v1' });
const { scriptId } = JSON.parse(fs.readFileSync('../.clasp.json'));
const { url: testSheetURL } = JSON.parse(fs.readFileSync('../.testSheet.json'));
if (!testSheetURL) {
console.error('error: no test sheet url');
process.exit(1);
}
const request = {
function: 'testRunner',
parameters: [testSheetURL],
devMode: true, // Sue always the latest pushed codes
};
script.scripts.run({ auth, scriptId, resource: request }, (err, resp) => {
if (err) {
// The API encountered a problem before the script started executing.
console.error(`error: api returned an error: ${err}`);
process.exit(1);
}
if (resp.data.error) {
// The API executed, but the script returned an error.
// Extract the first (and only) set of error details. The values of this
// object are the script's 'errorMessage' and 'errorType', and an array
// of stack trace elements.
const [errorDetail] = resp.data.error.details;
console.error(`error: script error message: ${errorDetail.errorMessage}`);
console.error('error: script error stacktrace:');
if (errorDetail.scriptStackTraceElements) {
// There may not be a stacktrace if the script didn't start executing.
for (let i = 0; i < errorDetail.scriptStackTraceElements.length; i += 1) {
const trace = errorDetail.scriptStackTraceElements[i];
console.error('\t%s: %s', trace.function, trace.lineNumber);
}
}
process.exit(1);
} else {
console.log(resp.data);
if (resp.data.response) {
// script.scripts.run prints the result so no need double prints
const { /* log, */ failures } = resp.data.response.result;
// console.log(log);
process.exit(failures);
} else {
process.exit(1);
}
}
});
}
authenticate().then((auth) => callAppsScript(auth));
|
"use strict";
class Scrambler {
constructor() {
this.leet = [
{k: 'A', u: '4', l: '@'},
{k: 'B', u: '8', l: '6'},
{k: 'C', u: '(', l: '<'},
{k: 'D', u: 'l)', l: 'ol'},
{k: 'E', u: '3', l: '3'},
{k: 'F', u: 'l"', l: 'l"'},
{k: 'G', u: '(,', l: '(,'},
{k: 'H', u: '4', l: '4'},
{k: 'I', u: '1', l: '1'},
{k: 'J', u: '_)', l: '_)'},
{k: 'K', u: '|<', l: '|<'},
{k: 'L', u: '[', l: '['},
{k: 'M', u: '/\\/\\', l: '^^'},
{k: 'N', u: '/\\/', l: '/\\/'},
{k: 'O', u: '0', l: '0'},
{k: 'P', u: '|o', l: '/o'},
{k: 'Q', u: '(,)', l: '9'},
{k: 'R', u: '|2', l: 'r'},
{k: 'S', u: '$', l: '$'},
{k: 'T', u: '7', l: '7'},
{k: 'U', u: '|_|', l: '|_|'},
{k: 'V', u: '\\/', l: '\\/'},
{k: 'W', u: '\\/\\/', l: '\\/\\/'},
{k: 'X', u: '}{', l: '><'},
{k: 'Y', u: '¥', l: '¥'},
{k: 'Z', u: 'Z', l: 'z'},
];
}
/**
* Scramble all words in a string, re-arrange the letters
* in between first and last letter
*
* @param string text
*
* @return string result
*
*/
innerScramble(text) {
var result = '';
var words = text.split(' ');
if(text.length > 0) {
$.each(words, function(k, v){
var newWord = '';
if(v.length > 2) {
var added = Array();
var letters = v.split('');
newWord = newWord + letters[0];
while(letters.length - 1 != newWord.length) {
var key = randNum(1, letters.length - 2);
var exist = $.inArray(key, added);
if(exist < 0) {
newWord = newWord + letters[key];
added.push(key);
}
}
newWord = newWord + letters[letters.length - 1];
}
else {
newWord = v;
}
result = result + ' ' + newWord;
});
result = result.trim();
}
return result;
}
/**
* Maintains vowels
*
* @param string text
*
* @return string result
*/
maintainVowels(text) {
var result = '';
var words = text.split(' ');
var vowels = ['a', 'e', 'i', 'o', 'u'];
if(text.length > 0) {
$.each(words, function(k, v){
var newWord = '';
if(v.length > 2) {
var letters = v.split('');
var lettersToChange = Array();
$.each(letters, function(k, v){
var isVowel = $.inArray(v.toLowerCase(), vowels);
if(isVowel < 0) {
lettersToChange.push(k);
}
});
lettersToChange = shuffleArray(lettersToChange);
$.each(letters, function(k, v){
var isVowel = $.inArray(v.toLowerCase(), vowels);
if(isVowel < 0) {
if(lettersToChange.length > 0) {
newWord = newWord + letters[lettersToChange[0]];
lettersToChange.splice(0, 1);
}
}
else {
newWord = newWord + v;
}
});
}
else {
newWord = v;
}
result = result + ' ' + newWord;
});
result = result.trim();
}
return result;
}
/**
* Leet letter conversion
*
* @param string text
*
* @return string result
*
*/
leetConversion(text) {
var result = '';
var words = text.split(' ');
var leet = this.leet;
$.each(words, function(k, word) {
var newWord = '';
var letters = word.split('');
$.each(letters, function(k, v) {
var l = letterToLeet(leet, v);
if(l != null) {
newWord = newWord + l;
}
else {
newWord = newWord + v;
}
});
result = result + ' ' + newWord;
});
result = result.trim();
return result;
}
}
/**
* Generates a random number
*
* @param number min max
*
* @return number
*
*/
function randNum(min,max) {
return Math.floor(Math.random()*(max-min+1)+min);
}
/**
* Shuffles array
*
* @param array a
*
* @return array a
*
*/
function shuffleArray(a) {
var j, x, i;
for (i = a.length - 1; i > 0; i--) {
j = Math.floor(Math.random() * (i + 1));
x = a[i];
a[i] = a[j];
a[j] = x;
}
return a;
}
/**
* Get the leet value
*
* @param array leet
*
* @return letter r
*
*/
function letterToLeet(leet, letter) {
var r = null;
$.each(leet, function(key, value){
if(value.k === letter.toUpperCase()) {
if(letter === letter.toUpperCase()) {
r = value.u;
}
else {
r = value.l;
}
}
});
return r;
}
|
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: path.resolve(__dirname, 'src/index.js'),
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ['babel-loader'],
},
],
},
resolve: {
extensions: ['*', '.js'],
},
output: {
path: path.resolve(__dirname, './dist'),
filename: 'bundle.js',
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new HtmlWebpackPlugin({
title: 'React App',
template: path.resolve(__dirname, 'src/index.html'),
}),
],
devServer: {
contentBase: path.resolve(__dirname, './dist'),
hot: true,
},
};
|
/**
* @fileoverview Tests for no-confusing-arrow rule.
* @author Jxck <https://github.com/Jxck>
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const rule = require("../../../lib/rules/no-confusing-arrow"),
RuleTester = require("../../../lib/testers/rule-tester");
//------------------------------------------------------------------------------
// Tests
//------------------------------------------------------------------------------
const ruleTester = new RuleTester({ parserOptions: { ecmaVersion: 6 } });
ruleTester.run("no-confusing-arrow", rule, {
valid: [
"a => { return 1 ? 2 : 3; }",
"var x = a => { return 1 ? 2 : 3; }",
"var x = (a) => { return 1 ? 2 : 3; }",
{ code: "var x = a => (1 ? 2 : 3)", options: [{ allowParens: true }] }
],
invalid: [
{
code: "a => 1 ? 2 : 3",
output: null,
errors: [{ message: "Arrow function used ambiguously with a conditional expression." }]
},
{
code: "var x = a => 1 ? 2 : 3",
output: null,
errors: [{ message: "Arrow function used ambiguously with a conditional expression." }]
},
{
code: "var x = (a) => 1 ? 2 : 3",
output: null,
errors: [{ message: "Arrow function used ambiguously with a conditional expression." }]
},
{
code: "var x = a => (1 ? 2 : 3)",
output: null,
errors: [{ message: "Arrow function used ambiguously with a conditional expression." }]
},
{
code: "a => 1 ? 2 : 3",
output: "a => (1 ? 2 : 3)",
options: [{ allowParens: true }],
errors: [{ message: "Arrow function used ambiguously with a conditional expression." }]
},
{
code: "var x = a => 1 ? 2 : 3",
output: "var x = a => (1 ? 2 : 3)",
options: [{ allowParens: true }],
errors: [{ message: "Arrow function used ambiguously with a conditional expression." }]
},
{
code: "var x = (a) => 1 ? 2 : 3",
output: "var x = (a) => (1 ? 2 : 3)",
options: [{ allowParens: true }],
errors: [{ message: "Arrow function used ambiguously with a conditional expression." }]
}
]
});
|
import sys
from bin.corona_esmda import get_calibration_modes
from src.io_func import load_config, load_data, hospital_forecast_to_txt, save_input_data
from src.parse import parse_config, reshape_prior
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
import os
from vis.general import plot_posterior
from tqdm import tqdm
from src.tools import generate_hos_actual, generate_zero_columns, calc_axis_interval
import datetime
import matplotlib.dates as mdates
from src import coronaSEIR
I_TIME = 0
I_INF = 1
I_DEAD = 2
I_REC = 3
I_HOSCUM = 4
I_ICU = 5
I_HOS = 6
O_TIME = 0
O_SUS = 1
O_EXP = 2
O_INF = 3
O_REM = 4
O_HOS = 5
O_HOSCUM = 6
O_ICU = 7
O_ICUCUM = 8
O_REC = 9
O_DEAD = 10
O_CUMINF = 11
def run_prior(config, ndata):
"""
Create a prior ensemble of model runs.
:param config: The entire model configuration in dict-form
:return: Forward model results, the parameter sets used to create them, and an array of timesteps
"""
np.random.seed(1)
# Parse parameters
m_prior, fwd_args = parse_config(config, ndata)
m_prior = reshape_prior(m_prior)
# Run simulation
results = np.zeros((len(m_prior), 13, len(fwd_args['time'])))
for i in tqdm(range(len(m_prior)), desc='Running prior ensemble'):
param = m_prior[i]
results[i] = coronaSEIR.base_seir_model(param,fwd_args)
tnew = fwd_args['time'] - fwd_args['time_delay']
return results, tnew, m_prior, fwd_args
def calibrate_with_data(prior, t, data,data_index, output_index):
"""
Use the observed cases ('hospitalized' or 'dead') to assign each prior member a probability
:param prior: The prior ensemble
:param t: The time definition
:param data: The observed data
:param model_conf: The model configuration for each prior member
:param mode: Calibration mode ('hospitalized' or 'dead')
:return: Probability of each prior member (sums to 1.0)
"""
# Find the timesteps in the model corresponding to the data
t_ind = [np.where(t == a)[0][0] for a in data[:, I_TIME]]
forecasted_cases = prior[:, output_index, t_ind]
observed_cases = data[:, data_index]
total_cases_forecasted = forecasted_cases[:, -1] - forecasted_cases[:,0];
forecasted_rate = np.diff(forecasted_cases, axis=-1)
forecasted_rate = np.clip(forecasted_rate, a_min=1e-05, a_max=None)
observed_rate = np.diff(observed_cases)
ll = np.sum(observed_rate[None, :] * np.log(forecasted_rate), axis=-1) - total_cases_forecasted
ll = ll.astype(float)
llmax = ll.max()
p = np.exp(ll - llmax) / np.sum(np.exp(ll - llmax))
return p
def integrate_calibration(results, p):
# Multiply each prior member with its probability. Sum to obtain mean posterior
integrated_result = np.einsum('ijk,i', results, p)
return integrated_result
def rerun_model_with_alpha_uncertainty(model_conf, p, config,fwd_args):
"""
Sample from the posterior distribution, and add extra samples to sufficiently account for (prior) uncertainty in
alpha
:param model_conf: Model configuration of the prior members
:param p: Probality of the prior members
:param config: Dict with model configuration
:return: Forward models, sampled from posterior, with added alpha uncertainty
"""
model_conf = np.array(model_conf)
nr_samples = config['nr_forecast_samples']
sample_indices = np.random.choice(np.arange(len(p)), size=nr_samples, p=p)
# Sample from posterior
post = model_conf[sample_indices]
# Replace alpha uncertainty with prior uncertainty
alpha_sample_indices = np.random.choice(np.arange(len(p)), size=nr_samples)
for i, param in enumerate(fwd_args['free_param']):
if param =='alpha':
post[:,i] = model_conf[alpha_sample_indices,i]
# Run simulation
results = np.zeros((post.shape[0], 13, len(fwd_args['time'])))
for i in tqdm(range(post.shape[0]), desc='Running posterior ensemble'):
param = post[i]
results[i] = coronaSEIR.base_seir_model(param, fwd_args)
return results
def plot_results(results, time, configpath, config, data, integrated_result=None, cal_mode=None, prior=True, plot_plume= True):
base = (os.path.split(configpath)[-1]).split('.')[0]
outpath = os.path.join(os.path.split(os.getcwd())[0], 'output', base)
date_1 = datetime.datetime.strptime(config['startdate'], "%m/%d/%y")
t = [date_1 + datetime.timedelta(days=a - 1) for a in time]
t_obs = [date_1 + datetime.timedelta(days=a - 1) for a in data[:,0]]
fig_base = configpath.split('/')[-1][0:-5]
fig, ax = plt.subplots()
nr_samples = results.shape[0]
transparancy = max(min(5.0 / nr_samples, 1),0.01)
alphaday = config["dayalpha"]
for i in alphaday:
ax.axvline(x=i, color='silver')
if (plot_plume):
ax.plot(t, np.full_like(t, fill_value=np.nan), color='magenta', label='exposed')
ax.plot(t, np.full_like(t, fill_value=np.nan), color='red', label='infected')
ax.plot(t, np.full_like(t, fill_value=np.nan), color='green', label='hospitalized')
ax.plot(t, np.full_like(t, fill_value=np.nan), color='blue', label='deceased')
ax.plot(t, np.full_like(t, fill_value=np.nan), color='black', label='recovered')
ax.plot(t, results[0:, O_EXP, :].T, color='magenta', alpha=transparancy)
# ax.plot(t, results[0:, O_INF, :].T + results[0:, O_REM, :].T, color='red', alpha=transparancy)
ax.plot(t, results[0:, O_CUMINF, :].T , color='red', alpha=transparancy)
ax.plot(t, results[0:, O_HOSCUM, :].T, color='green', alpha=transparancy)
ax.plot(t, results[0:, O_DEAD, :].T, color='blue', alpha=transparancy)
ax.plot(t, results[0:, O_REC, :].T, color='black', alpha=transparancy)
plt.xlabel('Time [days]')
plt.ylabel('Number')
y_lim = config['YMAX']
x_lim = config['XMAX']
plt.ylim(1, y_lim)
plt.xlim(date_1, t[x_lim])
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%d %b'))
day_interval = calc_axis_interval((t[x_lim] - date_1).days)
plt.gca().xaxis.set_major_locator(mdates.DayLocator(interval=day_interval))
plt.gcf().autofmt_xdate()
if config['plot']['y_axis_log']:
plt.semilogy()
plt.grid(True)
ax.legend(loc=config['plot']['legendloc'], fontsize=config['plot']['legendfont'])
plt.savefig('{}_priors_MC_{}.png'.format(outpath, cal_mode), dpi=300)
if not config['worldfile']:
plt.plot(t_obs, data[:, I_HOSCUM], "go", markersize=2, markeredgecolor='k', alpha=1, label='hospitalized cum (data)')
plt.plot(t_obs, data[:, I_INF], "r<", markersize=2, markeredgecolor='k', alpha=1, label='infected cum (data)')
plt.plot(t_obs, data[:, I_DEAD], "bx", markersize=2, markeredgecolor='k', alpha=1, label='deceased(data)')
plt.plot(t_obs, data[:, I_REC], ">", markersize=2, markeredgecolor='k', alpha=1, label='recovered(data)')
if type(integrated_result) == np.ndarray:
#cuminfected = integrated_result[O_INF] + integrated_result[O_REM]
cuminfected = integrated_result[O_CUMINF]
if plot_plume:
if not config['worldfile']:
ax.plot(t, integrated_result[O_HOSCUM], color='green')
ax.plot(t, cuminfected, color='red')
ax.plot(t, integrated_result[O_DEAD], color='blue')
ax.plot(t, integrated_result[O_EXP], color='magenta')
ax.plot(t, integrated_result[O_REC], color='black')
else:
ax.plot(t, integrated_result[O_EXP], color='magenta', label='exposed')
ax.plot(t, cuminfected, color='red', label='infected')
if not config['worldfile']:
ax.plot(t, integrated_result[O_HOSCUM], color='green', label='hospitalized')
ax.plot(t, integrated_result[O_DEAD], color='blue',label='deceased' )
ax.plot(t, integrated_result[O_REC], color='black',label='recovered' )
ax.legend(loc=config['plot']['legendloc'], fontsize=config['plot']['legendfont'])
plt.title('Calibrated on {}'.format(cal_mode))
plottype = '{}_forecast_MC_{}'
if prior:
plottype = '{}_hindcast_MC_{}.png'
plt.savefig(plottype.format(outpath, cal_mode), dpi=300)
plt.close()
def sample_from_prior(prior,p,config):
nr_samples = config['nr_forecast_samples']
sample_indices = np.random.choice(np.arange(len(p)), size=nr_samples, p=p)
return prior[sample_indices]
def main(configpath):
# Load the model configuration file and the data (observed cases)
config = load_config(configpath)
data = load_data(config)
base_filename = (os.path.split(configpath)[-1]).split('.')[0]
useworldfile = config['worldfile']
if (not useworldfile):
data = generate_hos_actual(data, config)
else:
data = generate_zero_columns(data, config)
# Run the forward model to obtain a prior ensemble of models
save_input_data(base_filename, data)
ndata = np.size(data[:, 0])
prior, time, prior_param, fwd_args = run_prior(config,ndata)
# Calibrate the model (as calibration data, we either use 'hospitalized' or 'dead')
calibration_mode = get_calibration_modes(config['calibration_mode'])[0]
if calibration_mode == 'dead':
data_index = I_DEAD
output_index = O_DEAD
elif calibration_mode == 'hospitalized':
data_index = I_HOS
output_index = O_HOS
elif calibration_mode == 'hospitalizedcum':
data_index = I_HOSCUM
output_index = O_HOSCUM
elif calibration_mode == 'ICU':
data_index = I_ICU
output_index = O_ICU
else:
raise NotImplementedError
plotplume = config['plot']['hindcast_plume']
p = calibrate_with_data(prior, time, data, data_index, output_index) # Posterior probability for each ensemble member
integrated_results = integrate_calibration(prior, p) # Mean posterior model
# Create output of the calibration phase
plot_results(prior, time, configpath, config, data, integrated_results, calibration_mode, prior=True, plot_plume= plotplume )
# Based on the model performance in the past, run models again, forecasting the future
forecast = rerun_model_with_alpha_uncertainty(prior_param, p, config, fwd_args)
base = (os.path.split(configpath)[-1]).split('.')[0]
outbase = os.path.join(os.path.split(os.getcwd())[0], 'output', base)
plot_results(forecast, time, configpath, config, data, cal_mode= config['calibration_mode'], prior=False,
plot_plume=True)
plot_posterior(forecast, config,outbase,data,['time'])
try:
hospital_forecast_to_txt(forecast, time, configpath, config, data)
except:
pass
if __name__ == '__main__':
# This script only accepts one input argument: the path to the configuration .json file
main(sys.argv[1])
|
from surrortg import Game # First we need import the Game
from surrortg.inputs import Joystick, Directions # and our preferred input(s)
# Create a custom Joystick, it really can do what ever you want.
class MyJoystick(Joystick):
"""
Advanced game documentation
"""
def __init__(self, io):
self.io = io # save io for sending updates to the game engine
self.progress = 0.0 # initialize progress with 0.0
# do things based on Joystick directions
async def handle_coordinates(self, x, y, seat=0):
direction = self.get_direction_4(x, y)
if direction == Directions.TOP:
self.progress += 0.01 # increase the progress with each TOP event
self.io.send_progress(self.progress) # and update the game engine
# implement the required reset method
async def reset(self, seat=0):
pass
class AdvancedGame(Game):
"""
Advanced game documentation2
"""
async def on_init(self):
# During the Game initialization callback register your joystick so
# the Game Engine knows where to send the user input during the
# games. Make sure that the name matches with the admin panel one.
self.io.register_inputs({"joystick": MyJoystick(self.io)})
async def on_config(self):
# Do things before the game engine starts fetching new players
pass
async def on_prepare(self):
# Do some preparations before the players connect
pass
async def on_pre_game(self):
# Do some preparations after the players connect
pass
async def on_countdown(self):
# Do things during the game countdown
pass
async def on_start(self):
# Inputs are now enabled. Scores, laps and progress are counted
if True: # TODO create a score increasing condition
self.io.send_score(100)
pass
async def on_finish(self):
# Do something when the robot finishes the game
pass
async def on_exit(self, reason, exception):
# This method is called just before the program exits
pass
# And now you are ready to play!
if __name__ == "__main__":
AdvancedGame().run()
# More info about:
# Game: <url>
# Joystick: <url>
# Inputs: <url>
# More examples and the full documentation: <url>
|
import Myr from "../myr/Myr";
const myr = new Myr();
let colorRegEx = new RegExp("#([0-9]|[A-F]|[a-f]){6}");
const defaultCursor = {
color: "red",
texture: "",
transparency: 0,
position: {
x: 0,
y: 0,
z: 0
},
scale: {
x: 1,
y: 1,
z: 1
},
rotation: {
x: 0,
y: 0,
z: 0
},
radius: "1",
phiLength: 360,
loop: true,
textureColoring: false,
textureRepeatWidth: 1,
textureRepeatHeight: 1,
duration: 1000,
magnitude: {
spin: 360,
fadeOut: 0,
general: 1
},
light: {
intensity: 1.0,
beamAngle: 60,
diffusion: 0.0,
decay: 1,
distance: 0.0,
target: null
}
};
describe("Updates to Myr's Model", () => {
it("should set the color", () => {
myr.setColor("red");
expect(myr.cursor.color).toEqual("red");
});
it("should set the texture by using a title and getTexture() should return that title", () => {
myr.setTexture("bricks", 2, 2);
expect(myr.cursor.texture).toEqual("/img/textures/bricks.jpg");
expect(myr.cursor.textureRepeatWidth).toEqual(2);
expect(myr.cursor.textureRepeatHeight).toEqual(2);
let getTest = myr.getTexture();
expect(getTest).toEqual("bricks");
});
it("should set the texture by using a url and getTexture() should return that url", () => {
myr.setTexture("https://learnmyr.org/img/MYR-Logo.png");
expect(myr.cursor.texture).toEqual("https://learnmyr.org/img/MYR-Logo.png");
});
it("improper texture should throw an error", () => {
try {
myr.setTexture("asdfghjkl");
}
catch(err) {
expect(err).toEqual(Error("Not a usable texture or URL."));
}
});
it("setTextureColoring(true) should allow a textured object to have a color other than white", () => {
myr.setTextureColoring(true);
myr.setColor("blue");
myr.setTexture("bricks");
myr.els = [];
let id = myr.box();
let box = myr.els[id];
expect(myr.getColor()).toMatch("blue");
expect(box.material).toMatch(/color: blue;/);
});
it("setTextureColoring(false) should not affect an untextures objects color", () => {
myr.setTextureColoring(false);
myr.setTexture();
myr.setColor("blue");
myr.els = [];
let id = myr.box();
let box = myr.els[id];
expect(myr.getColor()).toMatch("blue");
expect(box.material).toMatch(/color: blue;/);
});
it("setTextureColoring(false) should change the color of a textured object to white", () => {
myr.setTextureColoring(false);
myr.setTexture("bricks");
myr.setColor("blue");
myr.els = [];
let id = myr.box();
let box = myr.els[id];
expect(myr.getColor()).toMatch("blue");
expect(myr.getTexture()).toMatch("bricks");
expect(box.material).toMatch(/color: white;/);
myr.setTexture();
});
it("to SetPosition", () => {
myr.setPosition(1, 2, 3);
expect(myr.cursor.position).toEqual({ x: 1, y: 2, z: 3 });
});
it("to SetScale", () => {
myr.setScale(1, 2, 3);
expect(myr.cursor.scale).toEqual({ x: 1, y: 2, z: 3 });
});
it("to SetRotation", () => {
myr.setRotation(1, 2, 3);
expect(myr.cursor.rotation).toEqual({ x: 1, y: 2, z: 3 });
});
it("to SetRadius", () => {
myr.setRadius(10);
expect(myr.cursor.radius).toEqual("10");
myr.setRadius("a");
expect(myr.cursor.radius).toEqual("10");
myr.setRadius({});
expect(myr.cursor.radius).toEqual("10");
});
it("to makes Random Color", () => {
let color = myr.getRandomColor();
expect(color).not.toBeUndefined();
expect(colorRegEx.test(color)).toBeTruthy();
});
it("pick Random Color out of a list of colors", () => {
let colors = ["blue", "green", "red", "hotpink", "FF00FF", "rgb(100,33,93)"];
let color = myr.getRandomColor(colors);
expect(color).not.toBeUndefined();
expect(colors.includes(color)).toBeTruthy();
});
});
describe("Component Renders", () => {
it("Box", () => {
let id = myr.box({ material: "color: blue; texture: bricks", position: { x: 1, y: 1, z: 1 } });
let box = myr.els[id];
expect(box).toBeDefined();
expect(box.geometry).toMatch(/box/);
expect(box.material).toMatch(/color: blue;/);
expect(box.material).toMatch(/texture: bricks/);
expect(box.position).toEqual({ x: 1, y: 1, z: 1 });
});
it("Sphere", () => {
myr.els = [];
let id = myr.sphere({ material: "color: blue; texture: bricks", position: { x: 1, y: 1, z: 1 } });
let sphere = myr.els[id];
expect(sphere).toBeDefined();
expect(sphere.geometry).toMatch(/sphere/);
expect(sphere.material).toMatch(/color: blue;/);
expect(sphere.material).toMatch(/texture: bricks/);
expect(sphere.position).toEqual({ x: 1, y: 1, z: 1 });
});
it("Circle", () => {
myr.els = [];
let id = myr.circle({ material: "color: blue; texture: bricks", position: { x: 1, y: 1, z: 1 } });
let circle = myr.els[id];
expect(circle).toBeDefined();
expect(circle.geometry).toMatch(/circle/);
expect(circle.material).toMatch(/color: blue;/);
expect(circle.material).toMatch(/texture: bricks/);
expect(circle.position).toEqual({ x: 1, y: 1, z: 1 });
});
it("Cone", () => {
myr.els = [];
let id = myr.cone({ material: "color: blue; texture: bricks", position: { x: 1, y: 1, z: 1 } });
let cone = myr.els[id];
expect(cone).toBeDefined();
expect(cone.geometry).toMatch(/cone/);
expect(cone.material).toMatch(/color: blue;/);
expect(cone.material).toMatch(/texture: bricks/);
expect(cone.position).toEqual({ x: 1, y: 1, z: 1 });
});
it("Cylinder", () => {
myr.els = [];
let id = myr.cylinder({ material: "color: blue; texture: bricks;", position: { x: 1, y: 1, z: 1 } });
let cylinder = myr.els[id];
expect(cylinder).toBeDefined();
expect(cylinder.geometry).toMatch(/cylinder/);
expect(cylinder.material).toMatch(/color: blue;/);
expect(cylinder.material).toMatch(/texture: bricks/);
expect(cylinder.position).toEqual({ x: 1, y: 1, z: 1 });
});
it("Ring", () => {
myr.reset();
let id = myr.ring({ material: "color: red; texture: bricks; side: double;" });
let ring = myr.els[id];
expect(ring).toBeDefined();
expect(ring.geometry).toMatch(/ring/);
expect(ring.material).toMatch(/color: red;/);
expect(ring.material).toMatch(/texture: bricks/);
expect(ring.material).toMatch(/side: double;/);
expect(ring.position).toEqual({ x: 0, y: 0, z: 0 });
});
it("Plane", () => {
myr.reset();
myr.els = [];
myr.setTexture("bricks");
let id = myr.plane();
let plane = myr.els[id];
expect(plane).toBeDefined();
expect(plane.geometry).toMatch(/plane/);
expect(plane.material).toMatch(/color: white;/);
expect(plane.material).toMatch("img/textures/bricks.jpg");
expect(plane.material).toMatch(/side: double;/);
expect(plane.position).toEqual({ x: 0, y: 0, z: 0 });
});
it("Tetrahedron", () => {
myr.reset();
let id = myr.tetrahedron({ material: "color: red; texture: bricks; side: double;" });
let tetrahedron = myr.els[id];
expect(tetrahedron).toBeDefined();
expect(tetrahedron.geometry).toMatch(/tetrahedron/);
expect(tetrahedron.material).toMatch(/color: red;/);
expect(tetrahedron.material).toMatch(/texture: bricks/);
expect(tetrahedron.material).toMatch(/side: double;/);
expect(tetrahedron.position).toEqual({ x: 0, y: 0, z: 0 });
});
it("Triangle", () => {
myr.els = [];
myr.setTextureColoring(true);
let id = myr.triangle({ material: "color: blue; texture: bricks", position: { x: 1, y: 1, z: 1 } });
let triangle = myr.els[id];
expect(triangle).toBeDefined();
expect(triangle.geometry).toMatch(/triangle/);
expect(triangle.material).toMatch(/texture: bricks/);
expect(triangle.material).toMatch(/color: blue;/);
expect(triangle.position).toEqual({ x: 1, y: 1, z: 1 });
});
it("Text", () => {
myr.els = [];
myr.setPosition(0, 0, 0);
let id = myr.text("Hello World!");
let text = myr.els[id];
expect(text).toBeDefined();
expect(text.position).toEqual({ x: 0, y: 0, z: 0 });
expect(text.value).toEqual("Hello World!");
expect(text.text).toBeTruthy();
//passing no argument should give default value
myr.els = [];
myr.setPosition(0, 0, 0);
id = myr.text();
text = myr.els[id];
expect(text).toBeDefined();
expect(text.position).toEqual({ x: 0, y: 0, z: 0 });
expect(text.value).toEqual("Default");
expect(text.text).toBeTruthy();
//should reject the value and give default value
myr.els = [];
myr.setPosition(0, 0, 0);
id = myr.text(1);
text = myr.els[id];
expect(text).toBeDefined();
expect(text.position).toEqual({ x: 0, y: 0, z: 0 });
expect(text.value).toEqual("Default");
expect(text.text).toBeTruthy();
});
it("Tube", () => {
myr.els = [];
myr.setColor("blue");
let id = myr.tube({ position: { x: 1, y: 1, z: 1 } });
let tube = myr.els[id];
expect(tube).toBeDefined();
expect(tube.material).toMatch(/color: blue;/);
expect(tube).toHaveProperty("tube");
});
it("Line", () => {
myr.els = [];
myr.setColor("blue");
let id = myr.line("1 0 0, 2 0 0", { position: { x: 1, y: 1, z: 1 } });
let line = myr.els[id];
expect(line).toBeDefined();
expect(line.material).toMatch(/color: blue;/);
expect(line.path).toEqual("1 0 0, 2 0 0");
expect(line.position).toEqual({ x: 1, y: 1, z: 1 });
});
it("Torus", () => {
myr.els = [];
myr.setTextureColoring(false);
myr.setColor("blue");
myr.setTexture("bricks");
let id = myr.torus({ position: { x: 1, y: 1, z: 1 } });
let torus = myr.els[id];
expect(torus).toBeDefined();
expect(torus.geometry).toMatch(/torus/);
expect(torus.material).toMatch(/color: white;/);
expect(myr.getTexture()).toMatch("bricks");
expect(torus.position).toEqual({ x: 1, y: 1, z: 1 });
});
it("torusknot", () => {
myr.els = [];
myr.setColor("blue");
myr.setTexture("bricks");
myr.setTextureColoring(true);
let id = myr.torusknot({ position: { x: 1, y: 1, z: 1 } });
let torusknot = myr.els[id];
expect(torusknot).toBeDefined();
expect(torusknot.geometry).toMatch(/torus/);
expect(torusknot.material).toMatch(/color: blue;/);
expect(torusknot.material).toMatch("img/textures/bricks.jpg");
expect(myr.getTexture()).toMatch("bricks");
expect(torusknot.position).toEqual({ x: 1, y: 1, z: 1 });
});
it("polyhedron", () => {
myr.els = [];
let id = myr.polyhedron({
position: { x: 1, y: 1, z: 1 },
rotation: { x: 1, y: 1, z: 1 },
scale: { x: 1, y: 1, z: 1 }
});
let polyhedron = myr.els[id];
expect(polyhedron).toBeDefined();
expect(polyhedron.position).toEqual({ x: 1, y: 1, z: 1 });
expect(polyhedron.rotation).toEqual({ x: 1, y: 1, z: 1 });
expect(polyhedron.scale).toEqual({ x: 1, y: 1, z: 1 });
});
it("dodecahedron", () => {
myr.els = [];
let id = myr.dodecahedron({ material: "color: blue; texture: bricks;", position: { x: 1, y: 1, z: 1 } });
let dodecahedron = myr.els[id];
expect(dodecahedron).toBeDefined();
expect(dodecahedron.geometry).toMatch(/dodecahedron/);
expect(dodecahedron.material).toMatch(/color: blue;/);
expect(dodecahedron.material).toMatch(/texture: bricks/);
expect(dodecahedron.position).toEqual({ x: 1, y: 1, z: 1 });
});
it("icosahedron", () => {
myr.els = [];
let id = myr.icosahedron({ material: "color: blue; texture: bricks", position: { x: 1, y: 1, z: 1 } });
let icosahedron = myr.els[id];
expect(icosahedron).toBeDefined();
expect(icosahedron.geometry).toMatch(/icosahedron/);
expect(icosahedron.material).toMatch(/color: blue;/);
expect(icosahedron.material).toMatch(/texture: bricks/);
expect(icosahedron.position).toEqual({ x: 1, y: 1, z: 1 });
});
it("octahedron", () => {
myr.els = [];
let id = myr.octahedron({ material: "color: blue; texture: bricks", position: { x: 1, y: 1, z: 1 } });
let octahedron = myr.els[id];
expect(octahedron).toBeDefined();
expect(octahedron.geometry).toMatch(/octahedron/);
expect(octahedron.material).toMatch(/color: blue;/);
expect(octahedron.material).toMatch(/texture: bricks/);
expect(octahedron.position).toEqual({ x: 1, y: 1, z: 1 });
});
});
describe("MYR light functionality", () => {
it("ambientLight", ()=>{
myr.reset();
myr.els = [];
let id = myr.ambientLight({position: {x:1,y:1,z:1}});
let ambientLight = myr.els[id];
expect(ambientLight).toBeDefined();
expect(ambientLight.light.state).toEqual(`
type: ambient;
color: red;
intensity: 1;`);
expect(ambientLight.position).toEqual({x:1,y:1,z:1});
//light's scale sohuld not change
expect(ambientLight.scale).toEqual({x:1,y:1,z:1});
});
it("directionalLight", ()=>{
myr.els = [];
let id = myr.directionalLight({position: {x:1,y:1,z:1}});
let directionalLight = myr.els[id];
expect(directionalLight).toBeDefined();
expect(directionalLight.light.state).toEqual(`
type: directional;
color: red;
intensity: 1;`);
expect(directionalLight.position).toEqual({x:1,y:1,z:1});
expect(directionalLight.scale).toEqual({x:1,y:1,z:1});
});
it("spotLight", ()=>{
myr.els = [];
let id = myr.spotLight({position: {x:1,y:1,z:1}});
let spotLight = myr.els[id];
expect(spotLight).toBeDefined();
expect(spotLight.light.state).toEqual(`
type: spot;
angle: 60;
decay: 1;
distance: 0;
intensity: 1;
penumbra: 0;
color: red;`);
expect(spotLight.position).toEqual({x:1,y:1,z:1});
//light's scale sohuld not change
expect(spotLight.scale).toEqual({x:1,y:1,z:1});
});
it("pointLight", ()=>{
myr.els = [];
let id = myr.pointLight({position: {x:1,y:1,z:1}});
let pointLight = myr.els[id];
expect(pointLight).toBeDefined();
expect(pointLight.light.state).toEqual(`
type: point;
angle: 60;
decay: 1;
distance: 0;
intensity: 1;
penumbra: 0;
color: red;`);
expect(pointLight.position).toEqual({x:1,y:1,z:1});
//light's scale should not change
expect(pointLight.scale).toEqual({x:1,y:1,z:1});
});
it("hemisphereLight", ()=>{
myr.els = [];
let id = myr.hemisphereLight("blue",{position: {x:1,y:1,z:1}});
let hemisphereLight = myr.els[id];
expect(hemisphereLight).toBeDefined();
expect(hemisphereLight.light.state).toEqual(`
type: hemisphere;
intensity: 1;
color: red;
groundColor: blue;`);
expect(hemisphereLight.position).toEqual({x:1,y:1,z:1});
//light's scale should not change
expect(hemisphereLight.scale).toEqual({x:1,y:1,z:1});
});
it("to Set Intensity", () => {
myr.setIntensity(5);
expect(myr.cursor.light.intensity).toEqual(5);
});
it("to Set BeamAngle", () => {
myr.setBeamAngle(30);
expect(myr.cursor.light.beamAngle).toEqual(30);
});
it("to Set Diffusion", () => {
myr.setDiffusion(1.25);
expect(myr.cursor.light.diffusion).toEqual(1.25);
});
it("to Set decay", () => {
myr.setDecay(1.87);
expect(myr.cursor.light.decay).toEqual(1.87);
});
it("to Set Distance", () => {
myr.setDistance(50);
expect(myr.cursor.light.distance).toEqual(50);
});
it("to Set Light Target", () => {
myr.setLightTarget(4,5,10);
expect(myr.cursor.light.target).toEqual({x:4, y: 5, z: 10});
});
});
describe("Component Animations", () => {
it("should add the animate animation", () => {
myr.reset();
let bId = myr.box();
myr.animate(bId);
let el = myr.getEl(bId);
expect(el.animation).toEqual(`
property: rotation;
dir: alternate;
to: 0 360 0;
dur: 1000;
loop: true;
`);
myr.animate(bId, 720, false, 2000);
expect(el.animation).toEqual(`
property: rotation;
dir: alternate;
to: 0 720 0;
dur: 2000;
loop: false;
`);
});
it("should add the spin animation", () => {
myr.reset();
let bId = myr.box();
myr.spin(bId);
let el = myr.getEl(bId);
expect(el.animation__spin).toEqual(`
property: rotation;
dir: alternate;
dur: 1000;
loop: true;
easing: linear;
to: 0 360 0;
`);
myr.spin(bId, 720, false, 2000);
expect(el.animation__spin).toEqual(`
property: rotation;
dir: alternate;
dur: 2000;
loop: false;
easing: linear;
to: 0 720 0;
`);
});
it("should add the yoyo animiation", () => {
myr.reset();
let id = myr.box();
myr.yoyo(id);
let el = myr.getEl(id);
expect(el).toHaveProperty("animation__yoyo");
});
it("should add the sideToSide animiation", () => {
myr.reset();
let id = myr.box();
myr.sideToSide(id);
let el = myr.getEl(id);
expect(el).toHaveProperty("animation__sidetoside");
});
it("should add the goUp animiation", () => {
myr.reset();
let id = myr.box();
myr.goUp(id);
let el = myr.getEl(id);
expect(el).toHaveProperty("animation__goup");
});
it("should add the goDown animiation", () => {
myr.reset();
let id = myr.box();
myr.goDown(id);
let el = myr.getEl(id);
expect(el).toHaveProperty("animation__godown");
});
it("should add the goLeft animiation", () => {
myr.reset();
let id = myr.box();
myr.goLeft(id);
let el = myr.getEl(id);
expect(el).toHaveProperty("animation__goleft");
});
it("should add the goRight animiation", () => {
myr.reset();
let id = myr.box();
myr.goRight(id);
let el = myr.getEl(id);
expect(el).toHaveProperty("animation__goright");
});
it("should add the goTowards animiation", () => {
myr.reset();
let id = myr.box();
myr.goTowards(id);
let el = myr.getEl(id);
expect(el).toHaveProperty("animation__goleft");
});
it("should add the goAway animiation", () => {
myr.reset();
let id = myr.box();
myr.goAway(id);
let el = myr.getEl(id);
expect(el).toHaveProperty("animation__goaway");
});
it("should add the grow animiation", () => {
myr.reset();
let id = myr.box();
myr.grow(id);
let el = myr.getEl(id);
expect(el).toHaveProperty("animation__grow");
});
it("should add the shrink animiation", () => {
myr.reset();
let id = myr.box();
myr.shrink(id);
let el = myr.getEl(id);
expect(el).toHaveProperty("animation__shrink");
});
it("should add the fadeOut animiation", () => {
myr.reset();
let id = myr.box();
myr.fadeOut(id);
let el = myr.getEl(id);
expect(el).toHaveProperty("animation__fadeout");
expect(el.material).toMatch(/transparent: true;/);
});
it("should add the fadeIn animiation", () => {
myr.reset();
let id = myr.box();
myr.fadeIn(id);
let el = myr.getEl(id);
expect(el).toHaveProperty("animation__fadein");
expect(el.material).toMatch(/transparent: true;/);
});
it("should add the shrink animiation", () => {
myr.reset();
let id = myr.box();
myr.shrink(id);
let el = myr.getEl(id);
expect(el).toHaveProperty("animation__shrink");
});
it("should add the shrink animiation", () => {
myr.reset();
let id = myr.box();
myr.shrink(id);
let el = myr.getEl(id);
expect(el).toHaveProperty("animation__shrink");
});
it("should add the shrink animiation", () => {
myr.reset();
let id = myr.box();
myr.shrink(id);
let el = myr.getEl(id);
expect(el).toHaveProperty("animation__shrink");
});
it("should add the shrink animiation", () => {
myr.reset();
let id = myr.box();
myr.shrink(id);
let el = myr.getEl(id);
expect(el).toHaveProperty("animation__shrink");
});
it("should add the color_shift animation",()=>{
myr.reset();
let id = myr.box();
myr.colorShift(id,"blue");
let el = myr.getEl(id);
expect(el).toHaveProperty("animation__color");
expect(el.animation__color).toEqual(`property: components.material.material.color;
from: ${defaultCursor.color};
to: blue;
dur: ${defaultCursor.duration};
dir: alternate;
loop: ${defaultCursor.loop};
isRawProperty: true;
type: color;`);
});
it("should add the color_shift animation to the light",()=>{
myr.reset();
let id = myr.directionalLight();
myr.colorShift(id,"green");
let el = myr.getEl(id);
expect(el).toHaveProperty("animation__color");
expect(el.animation__color).toEqual(`property: light.color;
from: #ff0000;
to: #008000;
dur: ${defaultCursor.duration};
dir: alternate;
loop: ${defaultCursor.loop};
type: color;`);
});
it("should add the color_shift animation to the group",()=>{
myr.reset();
let id = myr.group();
id.add(myr.box());
id.add(myr.box());
id.add(myr.box());
myr.colorShift(id,"purple");
let el = myr.getEl(id);
el.els.forEach(e=>{
expect(e).toHaveProperty("animation__color");
expect(e.animation__color).toEqual(`property: components.material.material.color;
from: ${defaultCursor.color};
to: purple;
dur: ${defaultCursor.duration};
dir: alternate;
loop: ${Boolean(defaultCursor.loop)};
isRawProperty: true;
type: color;`);
});
});
});
describe("Other Myr functionality", () => {
it("should add a model", () => {
myr.reset();
myr.assets = [];
myr.addCModel();
expect(myr.assets).toContainEqual({ id: "c-obj", src: "/img/c.obj" });
});
it("should drop", () => {
myr.reset();
let el = myr.box({ material: "color: blue;", position: { x: 1, y: 1, z: 1 } });
myr.drop(el);
let thisEl = myr.els[el];
expect(thisEl).toHaveProperty("dynamic-body");
});
it("should get the right element", () => {
myr.reset();
let id = myr.box();
expect(myr.getEl(id)).toBeDefined();
expect(myr.getEl(id).geometry).toEqual("primitive: box;");
});
it("should get the right index", () => {
myr.reset();
let id = myr.box();
expect(myr.els[id]).toBeDefined();
});
it("should initialize Myr", () => {
let obj = [{ name: "test" }];
let m = new Myr(obj);
expect(m.els.length).toEqual(1);
expect(m.baseEls.length).toEqual(1);
});
// it('should reset Myr', () => {
// myr.reset();
// expect(myr.els.length).toEqual(0);
// let m = new Myr([{ id: "item" }])
// m.reset();
// expect(m.els.length).toEqual(1);
// });
it("should reset cursor", () => {
myr.resetCursor();
expect(myr.cursor).toEqual(defaultCursor);
});
it("should only reset cursor with transformation property", () => {
myr.setPosition(5,4,3);
myr.setMagnitude(512);
myr.setIntensity(2.15);
myr.resetTransformationCursor();
expect(myr.cursor.position).toEqual({ x: 0, y: 0, z: 0});
expect(myr.cursor.magnitude).toEqual({ spin: 512, fadeOut: 512, general: 512 });
expect(myr.cursor.light.intensity).toEqual(2.15);
});
it("should only reset cursor with animation property", () => {
myr.setPosition(5,4,3);
myr.setMagnitude(512);
myr.setIntensity(2.15);
myr.resetAnimationCursor();
expect(myr.cursor.position).toEqual({ x: 5, y: 4, z: 3});
expect(myr.cursor.magnitude).toEqual({ spin: 360, fadeOut: 0, general: 1 });
expect(myr.cursor.light.intensity).toEqual(2.15);
});
it("should only reset cursor with light property", () => {
myr.setPosition(5,4,3);
myr.setMagnitude(512);
myr.setIntensity(2.15);
myr.resetLightCursor();
expect(myr.cursor.position).toEqual({ x: 5, y: 4, z: 3});
expect(myr.cursor.magnitude).toEqual({ spin: 512, fadeOut: 512, general: 512 });
expect(myr.cursor.light).toEqual(defaultCursor.light);
});
it("should set the position in Myr", () => {
myr.reset();
myr.setPosition(1);
expect(myr.cursor.position).toEqual({ x: 1, y: 1, z: 0 });
myr.setPosition(1, 2);
expect(myr.cursor.position).toEqual({ x: 1, y: 2, z: 0 });
myr.setPosition(1, 2, 3);
expect(myr.cursor.position).toEqual({ x: 1, y: 2, z: 3 });
myr.setPosition(-1, -2, -3);
expect(myr.cursor.position).toEqual({ x: -1, y: -2, z: -3 });
// Should reject these values
myr.setPosition("a", -2, -3);
expect(myr.cursor.position).toEqual({ x: -1, y: -2, z: -3 });
myr.setPosition({}, -2, -3);
expect(myr.cursor.position).toEqual({ x: -1, y: -2, z: -3 });
myr.setPosition([], -2, -3);
expect(myr.cursor.position).toEqual({ x: -1, y: -2, z: -3 });
});
it("should set the X-position in Myr", () => {
myr.reset();
myr.setXPos(5);
expect(myr.cursor.position.x).toEqual(5);
myr.setXPos(-5);
expect(myr.cursor.position.x).toEqual(-5);
// Check for stable model with bad values
myr.setXPos({});
expect(myr.cursor.position.x).toEqual(-5);
myr.setXPos("a");
expect(myr.cursor.position.x).toEqual(-5);
myr.setXPos(() => { });
expect(myr.cursor.position.x).toEqual(-5);
expect(myr.cursor.position).toEqual({ x: -5, y: 0, z: 0 });
});
it("should set the Y-position in Myr", () => {
myr.reset();
myr.setYPos(5);
expect(myr.cursor.position.y).toEqual(5);
myr.setYPos(-5);
expect(myr.cursor.position.y).toEqual(-5);
// Check for stable model with bad values
myr.setYPos({});
expect(myr.cursor.position.y).toEqual(-5);
myr.setYPos("a");
expect(myr.cursor.position.y).toEqual(-5);
myr.setYPos(() => { });
expect(myr.cursor.position.y).toEqual(-5);
expect(myr.cursor.position).toEqual({ x: 0, y: -5, z: 0 });
});
it("should set the Z-position in Myr", () => {
myr.reset();
myr.setZPos(5);
expect(myr.cursor.position.z).toEqual(5);
myr.setZPos(-5);
expect(myr.cursor.position.z).toEqual(-5);
// Check for stable model with bad values
myr.setZPos({});
expect(myr.cursor.position.z).toEqual(-5);
myr.setZPos("a");
expect(myr.cursor.position.z).toEqual(-5);
myr.setZPos(() => { });
expect(myr.cursor.position.z).toEqual(-5);
expect(myr.cursor.position).toEqual({ x: 0, y: 0, z: -5 });
});
it("shoud increase the position relative to cursor position in MYR", () => {
myr.reset();
myr.increasePosition(1);
expect(myr.cursor.position).toEqual({ x: 1, y: 0, z: 0 });
myr.increasePosition(1, 1);
expect(myr.cursor.position).toEqual({ x: 2, y: 1, z: 0 });
myr.increasePosition(1, 1, 1);
expect(myr.cursor.position).toEqual({ x: 3, y: 2, z: 1 });
myr.increasePosition(-3, -2, -1);
expect(myr.cursor.position).toEqual({ x: 0, y: 0, z: 0 });
// Check for stable model with bad values
myr.increasePosition("a", 2, 3);
expect(myr.cursor.position).toEqual({ x: 0, y: 0, z: 0 });
myr.increasePosition({}, 2, 3);
expect(myr.cursor.position).toEqual({ x: 0, y: 0, z: 0 });
myr.increasePosition([], 2, 3);
expect(myr.cursor.position).toEqual({ x: 0, y: 0, z: 0 });
});
it("should increase the X-position relative to the cursor position", () => {
myr.reset();
myr.increaseXPos(5);
expect(myr.cursor.position.x).toEqual(5);
myr.increaseXPos();
expect(myr.cursor.position.x).toEqual(6);
myr.increaseXPos(-6);
expect(myr.cursor.position.x).toEqual(0);
//check for stable model with bad values
myr.increaseXPos("a");
expect(myr.cursor.position.x).toEqual(0);
myr.increaseXPos({});
expect(myr.cursor.position.x).toEqual(0);
myr.increaseXPos([]);
expect(myr.cursor.position.x).toEqual(0);
expect(myr.cursor.position).toEqual({ x: 0, y: 0, z: 0 });
});
it("should increase the Y-position relative to the cursor position", () => {
myr.reset();
myr.increaseYPos(5);
expect(myr.cursor.position.y).toEqual(5);
myr.increaseYPos();
expect(myr.cursor.position.y).toEqual(6);
myr.increaseYPos(-6);
expect(myr.cursor.position.y).toEqual(0);
//check for stable model with bad values
myr.increaseYPos("a");
expect(myr.cursor.position.y).toEqual(0);
myr.increaseYPos({});
expect(myr.cursor.position.y).toEqual(0);
myr.increaseYPos([]);
expect(myr.cursor.position.y).toEqual(0);
expect(myr.cursor.position).toEqual({ x: 0, y: 0, z: 0 });
});
it("should increase the Z-position relative to the cursor position", () => {
myr.reset();
myr.increaseZPos(5);
expect(myr.cursor.position.z).toEqual(5);
myr.increaseZPos();
expect(myr.cursor.position.z).toEqual(6);
myr.increaseZPos(-6);
expect(myr.cursor.position.z).toEqual(0);
//check for stable model with bad values
myr.increaseZPos("a");
expect(myr.cursor.position.z).toEqual(0);
myr.increaseZPos({});
expect(myr.cursor.position.z).toEqual(0);
myr.increaseZPos([]);
expect(myr.cursor.position.z).toEqual(0);
expect(myr.cursor.position).toEqual({ x: 0, y: 0, z: 0 });
});
it("should set the scale in Myr", () => {
myr.reset();
myr.setScale(4);
expect(myr.cursor.scale).toEqual({ x: 4, y: 1, z: 1 });
myr.setScale(4, 5);
expect(myr.cursor.scale).toEqual({ x: 4, y: 5, z: 1 });
myr.setScale(1, 2, 3);
expect(myr.cursor.scale).toEqual({ x: 1, y: 2, z: 3 });
myr.setScale(-1, -2, -3);
expect(myr.cursor.scale).toEqual({ x: -1, y: -2, z: -3 });
// Should reject these values
myr.setScale("a", -2, -3);
expect(myr.cursor.scale).toEqual({ x: -1, y: -2, z: -3 });
myr.setScale({}, -2, -3);
expect(myr.cursor.scale).toEqual({ x: -1, y: -2, z: -3 });
myr.setScale([], -2, -3);
expect(myr.cursor.scale).toEqual({ x: -1, y: -2, z: -3 });
});
it("should set the X-scale in Myr", () => {
myr.reset();
myr.setXScale(5);
expect(myr.cursor.scale.x).toEqual(5);
myr.setXScale(-5);
expect(myr.cursor.scale.x).toEqual(-5);
// Check for stable model with bad values
myr.setXScale({});
expect(myr.cursor.scale.x).toEqual(-5);
myr.setXScale("a");
expect(myr.cursor.scale.x).toEqual(-5);
myr.setXScale(() => { });
expect(myr.cursor.scale.x).toEqual(-5);
expect(myr.cursor.scale).toEqual({ x: -5, y: 1, z: 1 });
});
it("should set the Y-scale in Myr", () => {
myr.reset();
myr.setYScale(5);
expect(myr.cursor.scale.y).toEqual(5);
myr.setYScale(-5);
expect(myr.cursor.scale.y).toEqual(-5);
// Check for stable model with bad values
myr.setYScale({});
expect(myr.cursor.scale.y).toEqual(-5);
myr.setYScale("a");
expect(myr.cursor.scale.y).toEqual(-5);
myr.setYScale(() => { });
expect(myr.cursor.scale.y).toEqual(-5);
expect(myr.cursor.scale).toEqual({ x: 1, y: -5, z: 1 });
});
it("should set the Z-scale in Myr", () => {
myr.reset();
myr.setZScale(5);
expect(myr.cursor.scale.z).toEqual(5);
myr.setZScale(-5);
expect(myr.cursor.scale.z).toEqual(-5);
// Check for stable model with bad values
myr.setZScale({});
expect(myr.cursor.scale.z).toEqual(-5);
myr.setZScale("a");
expect(myr.cursor.scale.z).toEqual(-5);
myr.setZScale(() => { });
expect(myr.cursor.scale.z).toEqual(-5);
expect(myr.cursor.scale).toEqual({ x: 1, y: 1, z: -5 });
});
it("should set the rotation in Myr", () => {
myr.reset();
myr.setRotation(1);
expect(myr.cursor.rotation).toEqual({ x: 1, y: 0, z: 0 });
myr.setRotation(1, 2);
expect(myr.cursor.rotation).toEqual({ x: 1, y: 2, z: 0 });
myr.setRotation(1, 2, 3);
expect(myr.cursor.rotation).toEqual({ x: 1, y: 2, z: 3 });
myr.setRotation(-1, -2, -3);
expect(myr.cursor.rotation).toEqual({ x: -1, y: -2, z: -3 });
// Should reject these values
myr.setRotation("a", -2, -3);
expect(myr.cursor.rotation).toEqual({ x: -1, y: -2, z: -3 });
myr.setRotation({}, -2, -3);
expect(myr.cursor.rotation).toEqual({ x: -1, y: -2, z: -3 });
myr.setRotation([], -2, -3);
expect(myr.cursor.rotation).toEqual({ x: -1, y: -2, z: -3 });
});
it("should set the Pitch/X-rotation in Myr", () => {
myr.reset();
myr.pitchX(5);
expect(myr.cursor.rotation.x).toEqual(5);
myr.pitchX(-5);
expect(myr.cursor.rotation.x).toEqual(-5);
// Check for stable model with bad values
myr.pitchX({});
expect(myr.cursor.rotation.x).toEqual(-5);
myr.pitchX("a");
expect(myr.cursor.rotation.x).toEqual(-5);
myr.pitchX(() => { });
expect(myr.cursor.rotation.x).toEqual(-5);
expect(myr.cursor.rotation).toEqual({ x: -5, y: 0, z: 0 });
});
it("should set the Yaw/Y-rotation in Myr", () => {
myr.reset();
myr.yawY(5);
expect(myr.cursor.rotation.y).toEqual(5);
myr.yawY(-5);
expect(myr.cursor.rotation.y).toEqual(-5);
// Check for stable model with bad values
myr.yawY({});
expect(myr.cursor.rotation.y).toEqual(-5);
myr.yawY("a");
expect(myr.cursor.rotation.y).toEqual(-5);
myr.yawY(() => { });
expect(myr.cursor.rotation.y).toEqual(-5);
expect(myr.cursor.rotation).toEqual({ x: 0, y: -5, z: 0 });
});
it("should set the Roll/Z-rotation in Myr", () => {
myr.reset();
myr.rollZ(5);
expect(myr.cursor.rotation.z).toEqual(5);
myr.rollZ(-5);
expect(myr.cursor.rotation.z).toEqual(-5);
// Check for stable model with bad values
myr.rollZ({});
expect(myr.cursor.rotation.z).toEqual(-5);
myr.rollZ("a");
expect(myr.cursor.rotation.z).toEqual(-5);
myr.rollZ(() => { });
expect(myr.cursor.rotation.z).toEqual(-5);
expect(myr.cursor.rotation).toEqual({ x: 0, y: 0, z: -5 });
});
it("should set phi-length", () => {
myr.reset();
myr.setPhiLength(45);
expect(myr.cursor.phiLength).toBe("45");
});
it("should set custom cursor attributes", () => {
myr.reset();
myr.setCursorAttribute("size", "large");
let response = myr.getCursorAttribute("size");
expect(response).toBe("large");
response = myr.getCursorAttribute("");
expect(response).toBe(undefined);
myr.setCursorAttribute(7, 8);
response = myr.getCursorAttribute(7);
expect(response).toBe(undefined);
myr.setCursorAttribute("position", { x: 1, y: 2, z: 3 });
expect(myr.cursor).toEqual({ ...defaultCursor, ...{ "position": { x: 1, y: 2, z: 3 }, "size": "large" } });
myr.setCursorAttribute("test", 8);
response = myr.getCursorAttribute("test");
expect(response).toBe(8);
myr.setCursorAttribute("test", { "test1": 1, "test2": 3 });
response = myr.getCursorAttribute("test");
expect(response).toEqual({ "test1": 1, "test2": 3 });
});
it("should accept hex colors entered for setColor function", () => {
myr.setColor("#ff0000");
expect(myr.cursor.color).toEqual("#ff0000");
myr.setColor("#FF0000");
expect(myr.cursor.color).toEqual("#ff0000");
myr.setColor("#0000fF");
expect(myr.cursor.color).toEqual("#0000ff");
myr.setColor("#008000");
expect(myr.cursor.color).toEqual("#008000");
});
// This is will test different variations of color
it("should accept any caps or lowercase letters", () => {
myr.setColor("Blue");
expect(myr.cursor.color).toEqual("blue");
myr.setColor("pURPle");
expect(myr.cursor.color).toEqual("purple");
myr.setColor("OrAnGe");
expect(myr.cursor.color).toEqual("orange");
myr.setColor("Red");
expect(myr.cursor.color).toEqual("red");
myr.setColor("rED");
expect(myr.cursor.color).toEqual("red");
myr.setColor("ReD");
expect(myr.cursor.color).toEqual("red");
});
it("setTransparency should set the appropriate cursor attribute correctly", () => {
myr.setTransparency(0);
expect(myr.cursor.transparency).toEqual(0);
myr.setTransparency(100);
expect(myr.cursor.transparency).toEqual(1);
myr.setTransparency(50);
expect(myr.cursor.transparency).toEqual(0.5);
myr.setTransparency(40);
expect(myr.cursor.transparency).toEqual(0.4);
});
it("setTransparency should not change opacity if it received an invalid argument", () => {
myr.reset();
myr.setTransparency(-100);
expect(myr.cursor.transparency).toEqual(0);
myr.setTransparency(-50);
expect(myr.cursor.transparency).toEqual(0);
myr.setTransparency(-1);
expect(myr.cursor.transparency).toEqual(0);
myr.setTransparency("50");
expect(myr.cursor.transparency).toEqual(0);
myr.setTransparency("1");
expect(myr.cursor.transparency).toEqual(0);
myr.setTransparency([1, 2, 3]);
expect(myr.cursor.transparency).toEqual(0);
myr.setTransparency({
test: true,
valid: "false",
value: 1
});
expect(myr.cursor.transparency).toEqual(0);
});
});
|
# Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
# Example:
# Input: 38
# Output: 2
# Explanation: The process is like: 3 + 8 = 11, 1 + 1 = 2.
# Since 2 has only one digit, return it.
class Solution(object):
def addDigits(self, num):
"""
:type num: int
:rtype: int
"""
return 0 if num == 0 else num % 9 or 9
# Time: O(1)
# Space: O(1)
# Difficulty: easy
|
const { SlashCommandBuilder } = require('@discordjs/builders');
const Discord = require("discord.js")
const db = require("quick.db")
const Canvas = require('canvas');
Canvas.registerFont('./data/font/OpenSans-SemiBoldItalic.ttf', { family: 'OpenSans-SemiBoldItalic' })
const { OWNER } = require('../data/config.json')
module.exports = {
data: new SlashCommandBuilder()
.setName('set')
.setDescription('Set Guild Limitation Config')
.addStringOption(option =>
option.setName('config')
.setDescription('Type Of Config')
.setRequired(true)
.addChoice('Set Role Create Limit', 'setrolecreatelimit')
.addChoice('Set Role Delete Limit', 'setroledeletelimit')
.addChoice('Set Channel Create Limit', 'setchannelcreatelimit')
.addChoice('Set Channel Delete Limit', 'setchanneldeletelimit')
.addChoice('Set Ban Limit', 'setbanlimit')
.addChoice('Set Kick Limit', 'setkicklimit'))
.addNumberOption(option =>
option.setName('num')
.setDescription('Number Of Limit')
.setRequired(true)),
async execute(interaction, client) {
var config = interaction.options.get('config').value
var num = interaction.options.get('num').value
let extraowners = db.get(`extraowners_${interaction.guild.id}`)
var log = db.get(`acitonslogs_${interaction.guild.id}`)
if (extraowners && extraowners.find(find => find.user == interaction.user.id)) {
if (config === 'setrolecreatelimit') {
db.set(`rolecreatelimt_${interaction.guild.id}`, num)
let done = new Discord.MessageEmbed()
.setColor('#85db61')
.setDescription(`<:check:923151545401479179> RoleCreation limits Has Been Set To ${num}`)
const canvas = Canvas.createCanvas(1242, 703);
const context = canvas.getContext('2d');
const background = await Canvas.loadImage(`./data/bg.png`);
context.drawImage(background, 0, 0, canvas.width, canvas.height);
context.font = '100px OpenSans-SemiBoldItalic';
context.fillStyle = 'black';
context.fillText(interaction.user.tag, 720, 270, 300, 250);
context.fillText(`Changes ${config} Limits To ${num}`, 470, 640, 700, 250);
context.beginPath();
context.arc(250, 250, 200, 0, 2 * Math.PI);
context.clip();
const profile = await Canvas.loadImage(interaction.user.displayAvatarURL({ format: 'png', size: 2048 }));
context.drawImage(profile, 50, 50, 400, 400);
const wladdedimg = new Discord.MessageAttachment(canvas.toBuffer(), "set.png");
let setted = new Discord.MessageEmbed()
.setColor('#85db61')
.setDescription(`<:check:923151545401479179> **${config}** Has Been Edited To **${num}** By **${interaction.user.tag}**`)
.setImage('attachment://set.png');
if (log) client.channels.cache.get(log).send({ embeds: [setted], files: [wladdedimg] });
return interaction.reply({
embeds: [done]
});
}
if (config === 'setroledeletelimit') {
db.set(`roledeletelimts_${interaction.guild.id}`, num)
let done = new Discord.MessageEmbed()
.setColor('#85db61')
.setDescription(`<:check:923151545401479179> RoleDelete limits Has Been Set To ${num}`)
const canvas = Canvas.createCanvas(1242, 703);
const context = canvas.getContext('2d');
const background = await Canvas.loadImage(`./data/bg.png`);
context.drawImage(background, 0, 0, canvas.width, canvas.height);
context.font = '100px OpenSans-SemiBoldItalic';
context.fillStyle = 'black';
context.fillText(interaction.user.tag, 720, 270, 300, 250);
context.fillText(`Changes ${config} Limits To ${num}`, 470, 640, 700, 250);
context.beginPath();
context.arc(250, 250, 200, 0, 2 * Math.PI);
context.clip();
const profile = await Canvas.loadImage(interaction.user.displayAvatarURL({ format: 'png', size: 2048 }));
context.drawImage(profile, 50, 50, 400, 400);
const wladdedimg = new Discord.MessageAttachment(canvas.toBuffer(), "set.png");
let setted = new Discord.MessageEmbed()
.setColor('#85db61')
.setDescription(`<:check:923151545401479179> **${config}** Has Been Edited To **${num}** By **${interaction.user.tag}**`)
.setImage('attachment://set.png');
if (log) client.channels.cache.get(log).send({ embeds: [setted], files: [wladdedimg] });
return interaction.reply({
embeds: [done]
});
}
if (config === 'setchannelcreatelimit') {
db.set(`channelcreatelimts_${interaction.guild.id}`, num)
let done = new Discord.MessageEmbed()
.setColor('#85db61')
.setDescription(`<:check:923151545401479179> ChannelCreation limits Has Been Set To ${num}`)
const canvas = Canvas.createCanvas(1242, 703);
const context = canvas.getContext('2d');
const background = await Canvas.loadImage(`./data/bg.png`);
context.drawImage(background, 0, 0, canvas.width, canvas.height);
context.font = '100px OpenSans-SemiBoldItalic';
context.fillStyle = 'black';
context.fillText(interaction.user.tag, 720, 270, 300, 250);
context.fillText(`Changes ${config} Limits To ${num}`, 470, 640, 700, 250);
context.beginPath();
context.arc(250, 250, 200, 0, 2 * Math.PI);
context.clip();
const profile = await Canvas.loadImage(interaction.user.displayAvatarURL({ format: 'png', size: 2048 }));
context.drawImage(profile, 50, 50, 400, 400);
const wladdedimg = new Discord.MessageAttachment(canvas.toBuffer(), "set.png");
let setted = new Discord.MessageEmbed()
.setColor('#85db61')
.setDescription(`<:check:923151545401479179> **${config}** Has Been Edited To **${num}** By **${interaction.user.tag}**`)
.setImage('attachment://set.png');
if (log) client.channels.cache.get(log).send({ embeds: [setted], files: [wladdedimg] });
return interaction.reply({
embeds: [done]
});
}
if (config === 'setchanneldeletelimit') {
db.set(`channeldeletelimts_${interaction.guild.id}`, num)
let done = new Discord.MessageEmbed()
.setColor('#85db61')
.setDescription(`<:check:923151545401479179> ChannelDelete limits Has Been Set To ${num}`)
const canvas = Canvas.createCanvas(1242, 703);
const context = canvas.getContext('2d');
const background = await Canvas.loadImage(`./data/bg.png`);
context.drawImage(background, 0, 0, canvas.width, canvas.height);
context.font = '100px OpenSans-SemiBoldItalic';
context.fillStyle = 'black';
context.fillText(interaction.user.tag, 720, 270, 300, 250);
context.fillText(`Changes ${config} Limits To ${num}`, 470, 640, 700, 250);
context.beginPath();
context.arc(250, 250, 200, 0, 2 * Math.PI);
context.clip();
const profile = await Canvas.loadImage(interaction.user.displayAvatarURL({ format: 'png', size: 2048 }));
context.drawImage(profile, 50, 50, 400, 400);
const wladdedimg = new Discord.MessageAttachment(canvas.toBuffer(), "set.png");
let setted = new Discord.MessageEmbed()
.setColor('#85db61')
.setDescription(`<:check:923151545401479179> **${config}** Has Been Edited To **${num}** By **${interaction.user.tag}**`)
.setImage('attachment://set.png');
if (log) client.channels.cache.get(log).send({ embeds: [setted], files: [wladdedimg] });
return interaction.reply({
embeds: [done]
});
}
if (config === 'setbanlimit') {
db.set(`banlimts_${interaction.guild.id}`, num)
let done = new Discord.MessageEmbed()
.setColor('#85db61')
.setDescription(`<:check:923151545401479179> Ban limits Has Been Set To ${num}`)
const canvas = Canvas.createCanvas(1242, 703);
const context = canvas.getContext('2d');
const background = await Canvas.loadImage(`./data/bg.png`);
context.drawImage(background, 0, 0, canvas.width, canvas.height);
context.font = '100px OpenSans-SemiBoldItalic';
context.fillStyle = 'black';
context.fillText(interaction.user.tag, 720, 270, 300, 250);
context.fillText(`Changes ${config} Limits To ${num}`, 470, 640, 700, 250);
context.beginPath();
context.arc(250, 250, 200, 0, 2 * Math.PI);
context.clip();
const profile = await Canvas.loadImage(interaction.user.displayAvatarURL({ format: 'png', size: 2048 }));
context.drawImage(profile, 50, 50, 400, 400);
const wladdedimg = new Discord.MessageAttachment(canvas.toBuffer(), "set.png");
let setted = new Discord.MessageEmbed()
.setColor('#85db61')
.setDescription(`<:check:923151545401479179> **${config}** Has Been Edited To **${num}** By **${interaction.user.tag}**`)
.setImage('attachment://set.png');
if (log) client.channels.cache.get(log).send({ embeds: [setted], files: [wladdedimg] });
return interaction.reply({
embeds: [done]
});
}
if (config === 'setkicklimit') {
db.set(`kicklimts_${interaction.guild.id}`, num)
let done = new Discord.MessageEmbed()
.setColor('#85db61')
.setDescription(`<:check:923151545401479179> Kick limits Has Been Set To ${num}`)
const canvas = Canvas.createCanvas(1242, 703);
const context = canvas.getContext('2d');
const background = await Canvas.loadImage(`./data/bg.png`);
context.drawImage(background, 0, 0, canvas.width, canvas.height);
context.font = '100px OpenSans-SemiBoldItalic';
context.fillStyle = 'black';
context.fillText(interaction.user.tag, 720, 270, 300, 250);
context.fillText(`Changes ${config} Limits To ${num}`, 470, 640, 700, 250);
context.beginPath();
context.arc(250, 250, 200, 0, 2 * Math.PI);
context.clip();
const profile = await Canvas.loadImage(interaction.user.displayAvatarURL({ format: 'png', size: 2048 }));
context.drawImage(profile, 50, 50, 400, 400);
const wladdedimg = new Discord.MessageAttachment(canvas.toBuffer(), "set.png");
let setted = new Discord.MessageEmbed()
.setColor('#85db61')
.setDescription(`<:check:923151545401479179> **${config}** Has Been Edited To **${num}** By **${interaction.user.tag}**`)
.setImage('attachment://set.png');
if (log) client.channels.cache.get(log).send({ embeds: [setted], files: [wladdedimg] });
return interaction.reply({
embeds: [done]
});
}
let setted = new Discord.MessageEmbed()
.setColor('#85db61')
.setDescription(`<:check:923151545401479179> **${config}** Has Been Edited To **${num}** By **${interaction.user.tag}**`)
if (log) client.channels.cache.get(log).send({ embeds: [setted] });
} else if (interaction.user.id === interaction.guild.ownerId || interaction.user.id === OWNER) {
if (config === 'setrolecreatelimit') {
db.set(`rolecreatelimt_${interaction.guild.id}`, num)
let done = new Discord.MessageEmbed()
.setColor('#85db61')
.setDescription(`<:check:923151545401479179> RoleCreation limits Has Been Set To ${num}`)
const canvas = Canvas.createCanvas(1242, 703);
const context = canvas.getContext('2d');
const background = await Canvas.loadImage(`./data/bg.png`);
context.drawImage(background, 0, 0, canvas.width, canvas.height);
context.font = '100px OpenSans-SemiBoldItalic';
context.fillStyle = 'black';
context.fillText(interaction.user.tag, 720, 270, 300, 250);
context.fillText(`Changes ${config} Limits To ${num}`, 470, 640, 700, 250);
context.beginPath();
context.arc(250, 250, 200, 0, 2 * Math.PI);
context.clip();
const profile = await Canvas.loadImage(interaction.user.displayAvatarURL({ format: 'png', size: 2048 }));
context.drawImage(profile, 50, 50, 400, 400);
const wladdedimg = new Discord.MessageAttachment(canvas.toBuffer(), "set.png");
let setted = new Discord.MessageEmbed()
.setColor('#85db61')
.setDescription(`<:check:923151545401479179> **${config}** Has Been Edited To **${num}** By **${interaction.user.tag}**`)
.setImage('attachment://set.png');
if (log) client.channels.cache.get(log).send({ embeds: [setted], files: [wladdedimg] });
return interaction.reply({
embeds: [done]
});
}
if (config === 'setroledeletelimit') {
db.set(`roledeletelimts_${interaction.guild.id}`, num)
let done = new Discord.MessageEmbed()
.setColor('#85db61')
.setDescription(`<:check:923151545401479179> RoleDelete limits Has Been Set To ${num}`)
const canvas = Canvas.createCanvas(1242, 703);
const context = canvas.getContext('2d');
const background = await Canvas.loadImage(`./data/bg.png`);
context.drawImage(background, 0, 0, canvas.width, canvas.height);
context.font = '100px OpenSans-SemiBoldItalic';
context.fillStyle = 'black';
context.fillText(interaction.user.tag, 720, 270, 300, 250);
context.fillText(`Changes ${config} Limits To ${num}`, 470, 640, 700, 250);
context.beginPath();
context.arc(250, 250, 200, 0, 2 * Math.PI);
context.clip();
const profile = await Canvas.loadImage(interaction.user.displayAvatarURL({ format: 'png', size: 2048 }));
context.drawImage(profile, 50, 50, 400, 400);
const wladdedimg = new Discord.MessageAttachment(canvas.toBuffer(), "set.png");
let setted = new Discord.MessageEmbed()
.setColor('#85db61')
.setDescription(`<:check:923151545401479179> **${config}** Has Been Edited To **${num}** By **${interaction.user.tag}**`)
.setImage('attachment://set.png');
if (log) client.channels.cache.get(log).send({ embeds: [setted], files: [wladdedimg] });
return interaction.reply({
embeds: [done]
});
}
if (config === 'setchannelcreatelimit') {
db.set(`channelcreatelimts_${interaction.guild.id}`, num)
let done = new Discord.MessageEmbed()
.setColor('#85db61')
.setDescription(`<:check:923151545401479179> ChannelCreation limits Has Been Set To ${num}`)
const canvas = Canvas.createCanvas(1242, 703);
const context = canvas.getContext('2d');
const background = await Canvas.loadImage(`./data/bg.png`);
context.drawImage(background, 0, 0, canvas.width, canvas.height);
context.font = '100px OpenSans-SemiBoldItalic';
context.fillStyle = 'black';
context.fillText(interaction.user.tag, 720, 270, 300, 250);
context.fillText(`Changes ${config} Limits To ${num}`, 470, 640, 700, 250);
context.beginPath();
context.arc(250, 250, 200, 0, 2 * Math.PI);
context.clip();
const profile = await Canvas.loadImage(interaction.user.displayAvatarURL({ format: 'png', size: 2048 }));
context.drawImage(profile, 50, 50, 400, 400);
const wladdedimg = new Discord.MessageAttachment(canvas.toBuffer(), "set.png");
let setted = new Discord.MessageEmbed()
.setColor('#85db61')
.setDescription(`<:check:923151545401479179> **${config}** Has Been Edited To **${num}** By **${interaction.user.tag}**`)
.setImage('attachment://set.png');
if (log) client.channels.cache.get(log).send({ embeds: [setted], files: [wladdedimg] });
return interaction.reply({
embeds: [done]
});
}
if (config === 'setchanneldeletelimit') {
db.set(`channeldeletelimts_${interaction.guild.id}`, num)
let done = new Discord.MessageEmbed()
.setColor('#85db61')
.setDescription(`<:check:923151545401479179> ChannelDelete limits Has Been Set To ${num}`)
const canvas = Canvas.createCanvas(1242, 703);
const context = canvas.getContext('2d');
const background = await Canvas.loadImage(`./data/bg.png`);
context.drawImage(background, 0, 0, canvas.width, canvas.height);
context.font = '100px OpenSans-SemiBoldItalic';
context.fillStyle = 'black';
context.fillText(interaction.user.tag, 720, 270, 300, 250);
context.fillText(`Changes ${config} Limits To ${num}`, 470, 640, 700, 250);
context.beginPath();
context.arc(250, 250, 200, 0, 2 * Math.PI);
context.clip();
const profile = await Canvas.loadImage(interaction.user.displayAvatarURL({ format: 'png', size: 2048 }));
context.drawImage(profile, 50, 50, 400, 400);
const wladdedimg = new Discord.MessageAttachment(canvas.toBuffer(), "set.png");
let setted = new Discord.MessageEmbed()
.setColor('#85db61')
.setDescription(`<:check:923151545401479179> **${config}** Has Been Edited To **${num}** By **${interaction.user.tag}**`)
.setImage('attachment://set.png');
if (log) client.channels.cache.get(log).send({ embeds: [setted], files: [wladdedimg] });
return interaction.reply({
embeds: [done]
});
}
if (config === 'setbanlimit') {
db.set(`banlimts_${interaction.guild.id}`, num)
let done = new Discord.MessageEmbed()
.setColor('#85db61')
.setDescription(`<:check:923151545401479179> Ban limits Has Been Set To ${num}`)
const canvas = Canvas.createCanvas(1242, 703);
const context = canvas.getContext('2d');
const background = await Canvas.loadImage(`./data/bg.png`);
context.drawImage(background, 0, 0, canvas.width, canvas.height);
context.font = '100px OpenSans-SemiBoldItalic';
context.fillStyle = 'black';
context.fillText(interaction.user.tag, 720, 270, 300, 250);
context.fillText(`Changes ${config} Limits To ${num}`, 470, 640, 700, 250);
context.beginPath();
context.arc(250, 250, 200, 0, 2 * Math.PI);
context.clip();
const profile = await Canvas.loadImage(interaction.user.displayAvatarURL({ format: 'png', size: 2048 }));
context.drawImage(profile, 50, 50, 400, 400);
const wladdedimg = new Discord.MessageAttachment(canvas.toBuffer(), "set.png");
let setted = new Discord.MessageEmbed()
.setColor('#85db61')
.setDescription(`<:check:923151545401479179> **${config}** Has Been Edited To **${num}** By **${interaction.user.tag}**`)
.setImage('attachment://set.png');
if (log) client.channels.cache.get(log).send({ embeds: [setted], files: [wladdedimg] });
return interaction.reply({
embeds: [done]
});
}
if (config === 'setkicklimit') {
db.set(`kicklimts_${interaction.guild.id}`, num)
let done = new Discord.MessageEmbed()
.setColor('#85db61')
.setDescription(`<:check:923151545401479179> Kick limits Has Been Set To ${num}`)
const canvas = Canvas.createCanvas(1242, 703);
const context = canvas.getContext('2d');
const background = await Canvas.loadImage(`./data/bg.png`);
context.drawImage(background, 0, 0, canvas.width, canvas.height);
context.font = '100px OpenSans-SemiBoldItalic';
context.fillStyle = 'black';
context.fillText(interaction.user.tag, 720, 270, 300, 250);
context.fillText(`Changes ${config} Limits To ${num}`, 470, 640, 700, 250);
context.beginPath();
context.arc(250, 250, 200, 0, 2 * Math.PI);
context.clip();
const profile = await Canvas.loadImage(interaction.user.displayAvatarURL({ format: 'png', size: 2048 }));
context.drawImage(profile, 50, 50, 400, 400);
const wladdedimg = new Discord.MessageAttachment(canvas.toBuffer(), "set.png");
let setted = new Discord.MessageEmbed()
.setColor('#85db61')
.setDescription(`<:check:923151545401479179> **${config}** Has Been Edited To **${num}** By **${interaction.user.tag}**`)
.setImage('attachment://set.png');
if (log) client.channels.cache.get(log).send({ embeds: [setted], files: [wladdedimg] });
return interaction.reply({
embeds: [done]
});
}
}
let owneronly = new Discord.MessageEmbed()
.setColor('#f67975')
.setTitle(`You Can't Use This Command!`)
.setDescription('<:ignore:923151545569267752> Only **Server Owner** & **Extra Owners** Can Use This Command!')
return interaction.reply({
embeds: [owneronly]
});
},
};
|
/* *
* (c) 2010-2019 Torstein Honsi
*
* License: www.highcharts.com/license
*/
'use strict';
import H from './Globals.js';
import './Utilities.js';
import './Color.js';
import './Legend.js';
import './Series.js';
import './Options.js';
var color = H.color,
LegendSymbolMixin = H.LegendSymbolMixin,
pick = H.pick,
Series = H.Series,
seriesType = H.seriesType;
/**
* Area series type.
*
* @private
* @class
* @name Highcharts.seriesTypes.area
*
* @augments Highcharts.Series
*/
seriesType(
'area',
'line',
/**
* The area series type.
*
* @sample {highcharts} highcharts/demo/area-basic/
* Area chart
* @sample {highstock} stock/demo/area/
* Area chart
*
* @extends plotOptions.line
* @excluding useOhlcData
* @product highcharts highstock
* @optionparent plotOptions.area
*/
{
/**
* Fill color or gradient for the area. When `null`, the series' `color`
* is used with the series' `fillOpacity`.
*
* In styled mode, the fill color can be set with the `.highcharts-area`
* class name.
*
* @sample {highcharts} highcharts/plotoptions/area-fillcolor-default/
* Null by default
* @sample {highcharts} highcharts/plotoptions/area-fillcolor-gradient/
* Gradient
*
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
* @product highcharts highstock
* @apioption plotOptions.area.fillColor
*/
/**
* Fill opacity for the area. When you set an explicit `fillColor`,
* the `fillOpacity` is not applied. Instead, you should define the
* opacity in the `fillColor` with an rgba color definition. The
* `fillOpacity` setting, also the default setting, overrides the alpha
* component of the `color` setting.
*
* In styled mode, the fill opacity can be set with the
* `.highcharts-area` class name.
*
* @sample {highcharts} highcharts/plotoptions/area-fillopacity/
* Automatic fill color and fill opacity of 0.1
*
* @type {number}
* @default {highcharts} 0.75
* @default {highstock} 0.75
* @product highcharts highstock
* @apioption plotOptions.area.fillOpacity
*/
/**
* A separate color for the graph line. By default the line takes the
* `color` of the series, but the lineColor setting allows setting a
* separate color for the line without altering the `fillColor`.
*
* In styled mode, the line stroke can be set with the
* `.highcharts-graph` class name.
*
* @sample {highcharts} highcharts/plotoptions/area-linecolor/
* Dark gray line
*
* @type {Highcharts.ColorString}
* @product highcharts highstock
* @apioption plotOptions.area.lineColor
*/
/**
* A separate color for the negative part of the area.
*
* In styled mode, a negative color is set with the
* `.highcharts-negative` class name.
*
* @see [negativeColor](#plotOptions.area.negativeColor)
*
* @sample {highcharts} highcharts/css/series-negative-color/
* Negative color in styled mode
*
* @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject}
* @since 3.0
* @product highcharts
* @apioption plotOptions.area.negativeFillColor
*/
/**
* Whether the whole area or just the line should respond to mouseover
* tooltips and other mouse or touch events.
*
* @sample {highcharts|highstock} highcharts/plotoptions/area-trackbyarea/
* Display the tooltip when the area is hovered
*
* @type {boolean}
* @default false
* @since 1.1.6
* @product highcharts highstock
* @apioption plotOptions.area.trackByArea
*/
/**
* When this is true, the series will not cause the Y axis to cross
* the zero plane (or [threshold](#plotOptions.series.threshold) option)
* unless the data actually crosses the plane.
*
* For example, if `softThreshold` is `false`, a series of 0, 1, 2,
* 3 will make the Y axis show negative values according to the
* `minPadding` option. If `softThreshold` is `true`, the Y axis starts
* at 0.
*
* @since 4.1.9
* @product highcharts highstock
*/
softThreshold: false,
/**
* The Y axis value to serve as the base for the area, for
* distinguishing between values above and below a threshold. The area
* between the graph and the threshold is filled.
*
* * If a number is given, the Y axis will scale to the threshold.
* * If `null`, the scaling behaves like a line series with fill between
* the graph and the Y axis minimum.
* * If `Infinity` or `-Infinity`, the area between the graph and the
* corresponing Y axis extreme is filled (since v6.1.0).
*
* @sample {highcharts} highcharts/plotoptions/area-threshold/
* A threshold of 100
* @sample {highcharts} highcharts/plotoptions/area-threshold-infinity/
* A threshold of Infinity
*
* @since 2.0
* @product highcharts highstock
*/
threshold: 0
},
/**
* @lends seriesTypes.area.prototype
*/
{
singleStacks: false,
// Return an array of stacked points, where null and missing points are
// replaced by dummy points in order for gaps to be drawn correctly in
// stacks.
getStackPoints: function (points) {
var series = this,
segment = [],
keys = [],
xAxis = this.xAxis,
yAxis = this.yAxis,
stack = yAxis.stacks[this.stackKey],
pointMap = {},
seriesIndex = series.index,
yAxisSeries = yAxis.series,
seriesLength = yAxisSeries.length,
visibleSeries,
upOrDown = pick(yAxis.options.reversedStacks, true) ? 1 : -1,
i;
points = points || this.points;
if (this.options.stacking) {
for (i = 0; i < points.length; i++) {
// Reset after point update (#7326)
points[i].leftNull = points[i].rightNull = null;
// Create a map where we can quickly look up the points by
// their X values.
pointMap[points[i].x] = points[i];
}
// Sort the keys (#1651)
H.objectEach(stack, function (stackX, x) {
// nulled after switching between
// grouping and not (#1651, #2336)
if (stackX.total !== null) {
keys.push(x);
}
});
keys.sort(function (a, b) {
return a - b;
});
visibleSeries = yAxisSeries.map(function (s) {
return s.visible;
});
keys.forEach(function (x, idx) {
var y = 0,
stackPoint,
stackedValues;
if (pointMap[x] && !pointMap[x].isNull) {
segment.push(pointMap[x]);
// Find left and right cliff. -1 goes left, 1 goes
// right.
[-1, 1].forEach(function (direction) {
var nullName = direction === 1 ?
'rightNull' :
'leftNull',
cliffName = direction === 1 ?
'rightCliff' :
'leftCliff',
cliff = 0,
otherStack = stack[keys[idx + direction]];
// If there is a stack next to this one,
// to the left or to the right...
if (otherStack) {
i = seriesIndex;
// Can go either up or down,
// depending on reversedStacks
while (i >= 0 && i < seriesLength) {
stackPoint = otherStack.points[i];
if (!stackPoint) {
// If the next point in this series
// is missing, mark the point
// with point.leftNull or
// point.rightNull = true.
if (i === seriesIndex) {
pointMap[x][nullName] = true;
// If there are missing points in
// the next stack in any of the
// series below this one, we need
// to substract the missing values
// and add a hiatus to the left or
// right.
} else if (visibleSeries[i]) {
stackedValues = stack[x].points[i];
if (stackedValues) {
cliff -= stackedValues[1] -
stackedValues[0];
}
}
}
// When reversedStacks is true, loop up,
// else loop down
i += upOrDown;
}
}
pointMap[x][cliffName] = cliff;
});
// There is no point for this X value in this series, so we
// insert a dummy point in order for the areas to be drawn
// correctly.
} else {
// Loop down the stack to find the series below this
// one that has a value (#1991)
i = seriesIndex;
while (i >= 0 && i < seriesLength) {
stackPoint = stack[x].points[i];
if (stackPoint) {
y = stackPoint[1];
break;
}
// When reversedStacks is true, loop up, else loop
// down
i += upOrDown;
}
y = yAxis.translate(y, 0, 1, 0, 1); // #6272
segment.push({
isNull: true,
plotX: xAxis.translate(x, 0, 0, 0, 1), // #6272
x: x,
plotY: y,
yBottom: y
});
}
});
}
return segment;
},
getGraphPath: function (points) {
var getGraphPath = Series.prototype.getGraphPath,
graphPath,
options = this.options,
stacking = options.stacking,
yAxis = this.yAxis,
topPath,
bottomPath,
bottomPoints = [],
graphPoints = [],
seriesIndex = this.index,
i,
areaPath,
plotX,
stacks = yAxis.stacks[this.stackKey],
threshold = options.threshold,
translatedThreshold = yAxis.getThreshold(options.threshold),
isNull,
yBottom,
connectNulls = H.pick( // #10574
options.connectNulls,
stacking === 'percent'
),
// To display null points in underlying stacked series, this
// series graph must be broken, and the area also fall down to
// fill the gap left by the null point. #2069
addDummyPoints = function (i, otherI, side) {
var point = points[i],
stackedValues = stacking &&
stacks[point.x].points[seriesIndex],
nullVal = point[side + 'Null'] || 0,
cliffVal = point[side + 'Cliff'] || 0,
top,
bottom,
isNull = true;
if (cliffVal || nullVal) {
top = (nullVal ? stackedValues[0] : stackedValues[1]) +
cliffVal;
bottom = stackedValues[0] + cliffVal;
isNull = !!nullVal;
} else if (
!stacking &&
points[otherI] &&
points[otherI].isNull
) {
top = bottom = threshold;
}
// Add to the top and bottom line of the area
if (top !== undefined) {
graphPoints.push({
plotX: plotX,
plotY: top === null ?
translatedThreshold :
yAxis.getThreshold(top),
isNull: isNull,
isCliff: true
});
bottomPoints.push({
plotX: plotX,
plotY: bottom === null ?
translatedThreshold :
yAxis.getThreshold(bottom),
doCurve: false // #1041, gaps in areaspline areas
});
}
};
// Find what points to use
points = points || this.points;
// Fill in missing points
if (stacking) {
points = this.getStackPoints(points);
}
for (i = 0; i < points.length; i++) {
isNull = points[i].isNull;
plotX = pick(points[i].rectPlotX, points[i].plotX);
yBottom = pick(points[i].yBottom, translatedThreshold);
if (!isNull || connectNulls) {
if (!connectNulls) {
addDummyPoints(i, i - 1, 'left');
}
// Skip null point when stacking is false and connectNulls
// true
if (!(isNull && !stacking && connectNulls)) {
graphPoints.push(points[i]);
bottomPoints.push({
x: i,
plotX: plotX,
plotY: yBottom
});
}
if (!connectNulls) {
addDummyPoints(i, i + 1, 'right');
}
}
}
topPath = getGraphPath.call(this, graphPoints, true, true);
bottomPoints.reversed = true;
bottomPath = getGraphPath.call(this, bottomPoints, true, true);
if (bottomPath.length) {
bottomPath[0] = 'L';
}
areaPath = topPath.concat(bottomPath);
// TODO: don't set leftCliff and rightCliff when connectNulls?
graphPath = getGraphPath
.call(this, graphPoints, false, connectNulls);
areaPath.xMap = topPath.xMap;
this.areaPath = areaPath;
return graphPath;
},
// Draw the graph and the underlying area. This method calls the Series
// base function and adds the area. The areaPath is calculated in the
// getSegmentPath method called from Series.prototype.drawGraph.
drawGraph: function () {
// Define or reset areaPath
this.areaPath = [];
// Call the base method
Series.prototype.drawGraph.apply(this);
// Define local variables
var series = this,
areaPath = this.areaPath,
options = this.options,
zones = this.zones,
props = [[
'area',
'highcharts-area',
this.color,
options.fillColor
]]; // area name, main color, fill color
zones.forEach(function (zone, i) {
props.push([
'zone-area-' + i,
'highcharts-area highcharts-zone-area-' + i + ' ' +
zone.className,
zone.color || series.color,
zone.fillColor || options.fillColor
]);
});
props.forEach(function (prop) {
var areaKey = prop[0],
area = series[areaKey],
verb = area ? 'animate' : 'attr',
attribs = {};
// Create or update the area
if (area) { // update
area.endX = series.preventGraphAnimation ?
null :
areaPath.xMap;
area.animate({ d: areaPath });
} else { // create
attribs.zIndex = 0; // #1069
area = series[areaKey] = series.chart.renderer
.path(areaPath)
.addClass(prop[1])
.add(series.group);
area.isArea = true;
}
if (!series.chart.styledMode) {
attribs.fill = pick(
prop[3],
color(prop[2])
.setOpacity(pick(options.fillOpacity, 0.75))
.get()
);
}
area[verb](attribs);
area.startX = areaPath.xMap;
area.shiftUnit = options.step ? 2 : 1;
});
},
drawLegendSymbol: LegendSymbolMixin.drawRectangle
}
);
/**
* A `area` series. If the [type](#series.area.type) option is not
* specified, it is inherited from [chart.type](#chart.type).
*
* @extends series,plotOptions.area
* @excluding dataParser, dataURL, useOhlcData
* @product highcharts highstock
* @apioption series.area
*/
/**
* An array of data points for the series. For the `area` series type,
* points can be given in the following ways:
*
* 1. An array of numerical values. In this case, the numerical values will be
* interpreted as `y` options. The `x` values will be automatically
* calculated, either starting at 0 and incremented by 1, or from
* `pointStart` * and `pointInterval` given in the series options. If the
* axis has categories, these will be used. Example:
* ```js
* data: [0, 5, 3, 5]
* ```
*
* 2. An array of arrays with 2 values. In this case, the values correspond to
* `x,y`. If the first value is a string, it is applied as the name of the
* point, and the `x` value is inferred.
* ```js
* data: [
* [0, 9],
* [1, 7],
* [2, 6]
* ]
* ```
*
* 3. An array of objects with named values. The following snippet shows only a
* few settings, see the complete options set below. If the total number of
* data points exceeds the series'
* [turboThreshold](#series.area.turboThreshold), this option is not
* available.
* ```js
* data: [{
* x: 1,
* y: 9,
* name: "Point2",
* color: "#00FF00"
* }, {
* x: 1,
* y: 6,
* name: "Point1",
* color: "#FF00FF"
* }]
* ```
*
* @sample {highcharts} highcharts/chart/reflow-true/
* Numerical values
* @sample {highcharts} highcharts/series/data-array-of-arrays/
* Arrays of numeric x and y
* @sample {highcharts} highcharts/series/data-array-of-arrays-datetime/
* Arrays of datetime x and y
* @sample {highcharts} highcharts/series/data-array-of-name-value/
* Arrays of point.name and y
* @sample {highcharts} highcharts/series/data-array-of-objects/
* Config objects
*
* @type {Array<number|Array<(number|string),(number|null)>|null|*>}
* @extends series.line.data
* @product highcharts highstock
* @apioption series.area.data
*/
|
import React, { useEffect, useState } from "react";
import { useMoralis } from "react-moralis";
import MoralisDappContext from "./context";
function MoralisDappProvider({ children }) {
const { web3, Moralis, user } = useMoralis();
const [walletAddress, setWalletAddress] = useState();
const [chainId, setChainId] = useState();
const [contractABI, setContractABI] = useState('[ { "inputs": [], "stateMutability": "nonpayable", "type": "constructor" }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "uint256", "name": "itemId", "type": "uint256" }, { "indexed": true, "internalType": "address", "name": "nftContract", "type": "address" }, { "indexed": true, "internalType": "uint256", "name": "tokenId", "type": "uint256" }, { "indexed": false, "internalType": "address", "name": "seller", "type": "address" }, { "indexed": false, "internalType": "address", "name": "owner", "type": "address" }, { "indexed": false, "internalType": "uint256", "name": "price", "type": "uint256" }, { "indexed": false, "internalType": "bool", "name": "sold", "type": "bool" } ], "name": "MarketItemCreated", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": true, "internalType": "uint256", "name": "itemId", "type": "uint256" }, { "indexed": false, "internalType": "address", "name": "owner", "type": "address" } ], "name": "MarketItemSold", "type": "event" }, { "inputs": [ { "internalType": "address", "name": "nftContract", "type": "address" }, { "internalType": "uint256", "name": "tokenId", "type": "uint256" }, { "internalType": "uint256", "name": "price", "type": "uint256" } ], "name": "createMarketItem", "outputs": [], "stateMutability": "payable", "type": "function" }, { "inputs": [ { "internalType": "address", "name": "nftContract", "type": "address" }, { "internalType": "uint256", "name": "itemId", "type": "uint256" } ], "name": "createMarketSale", "outputs": [], "stateMutability": "payable", "type": "function" }, { "inputs": [], "name": "fetchMarketItems", "outputs": [ { "components": [ { "internalType": "uint256", "name": "itemId", "type": "uint256" }, { "internalType": "address", "name": "nftContract", "type": "address" }, { "internalType": "uint256", "name": "tokenId", "type": "uint256" }, { "internalType": "address payable", "name": "seller", "type": "address" }, { "internalType": "address payable", "name": "owner", "type": "address" }, { "internalType": "uint256", "name": "price", "type": "uint256" }, { "internalType": "bool", "name": "sold", "type": "bool" } ], "internalType": "struct marketPlaceBoilerPlate.MarketItem[]", "name": "", "type": "tuple[]" } ], "stateMutability": "view", "type": "function" }, { "inputs": [], "name": "owner", "outputs": [ { "internalType": "address", "name": "", "type": "address" } ], "stateMutability": "view", "type": "function"}]')
const [marketAddress, setMarketAddress] = useState("0xa3dDf4B68CCda6c9CB35AE1962c60aA5cb226E90")
useEffect(() => {
Moralis.onChainChanged(function (chain) {
setChainId(chain);
});
Moralis.onAccountsChanged(function (address) {
setWalletAddress(address[0]);
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
// eslint-disable-next-line react-hooks/exhaustive-deps
useEffect(() => setChainId(web3.givenProvider?.chainId));
useEffect(
() => setWalletAddress(web3.givenProvider?.selectedAddress || user?.get("ethAddress")),
[web3, user]
);
return (
<MoralisDappContext.Provider value={{ walletAddress, chainId, marketAddress, setMarketAddress, contractABI, setContractABI }}>
{children}
</MoralisDappContext.Provider>
);
}
function useMoralisDapp() {
const context = React.useContext(MoralisDappContext);
if (context === undefined) {
throw new Error("useMoralisDapp must be used within a MoralisDappProvider");
}
return context;
}
export { MoralisDappProvider, useMoralisDapp };
|
(function() {
VimeoVideo = function(domObject, url) {
this.domObject = domObject;
this.url = url;
};
VimeoVideo.vimeoRegEx = new RegExp('^http://(?:www\\.)?vimeo\\.com/.+clip_id=(\\d+)');
VimeoVideo.prototype.canHandle = function() {
console.log('url: ' + this.url);
console.log('result: ' + VimeoVideo.vimeoRegEx.test(this.url));
return VimeoVideo.vimeoRegEx.test(this.url);
};
VimeoVideo.prototype.start = function() {
var match = VimeoVideo.vimeoRegEx.exec(this.url);
if (match) {
this.clipId = match[1];
this.watchUrl = 'http://vimeo.com/' + this.clipId;
var videoUrl = 'http://vimeo.com/play_redirect?clip_id=' + this.clipId;
VideoHandlers.replaceFlashObjectWithVideo(this.domObject,
videoUrl,
{ watchURL: this.watchUrl });
}
};
return VimeoVideo;
})
|
const data = {
name: "fr-BI",
identity: {
language: "fr",
territory: "BI"
},
territory: "BI",
numbers: {
symbols: {
decimal: ",",
group: " ",
list: ";",
percentSign: "%",
plusSign: "+",
minusSign: "-",
exponential: "E",
superscriptingExponent: "×",
perMille: "‰",
infinity: "∞",
nan: "NaN",
timeSeparator: ":"
},
decimal: {
patterns: [
"n"
],
groupSize: [
3
]
},
scientific: {
patterns: [
"nEn"
],
groupSize: []
},
percent: {
patterns: [
"n %"
],
groupSize: [
3
]
},
currency: {
patterns: [
"n $"
],
groupSize: [
3
],
"unitPattern-count-one": "n $",
"unitPattern-count-other": "n $"
},
accounting: {
patterns: [
"n $",
"(n $)"
],
groupSize: [
3
]
},
currencies: {
ADP: {
displayName: "peseta andorrane",
"displayName-count-one": "peseta andorrane",
"displayName-count-other": "pesetas andorranes",
symbol: "ADP"
},
AED: {
displayName: "dirham des Émirats arabes unis",
"displayName-count-one": "dirham des Émirats arabes unis",
"displayName-count-other": "dirhams des Émirats arabes unis",
symbol: "AED"
},
AFA: {
displayName: "afghani (1927–2002)",
"displayName-count-one": "afghani (1927–2002)",
"displayName-count-other": "afghanis (1927–2002)",
symbol: "AFA"
},
AFN: {
displayName: "afghani afghan",
"displayName-count-one": "afghani afghan",
"displayName-count-other": "afghanis afghan",
symbol: "AFN"
},
ALK: {
displayName: "lek albanais (1947–1961)",
"displayName-count-one": "lek albanais (1947–1961)",
"displayName-count-other": "leks albanais (1947–1961)",
symbol: "ALK"
},
ALL: {
displayName: "lek albanais",
"displayName-count-one": "lek albanais",
"displayName-count-other": "leks albanais",
symbol: "ALL"
},
AMD: {
displayName: "dram arménien",
"displayName-count-one": "dram arménien",
"displayName-count-other": "drams arméniens",
symbol: "AMD"
},
ANG: {
displayName: "florin antillais",
"displayName-count-one": "florin antillais",
"displayName-count-other": "florins antillais",
symbol: "ANG"
},
AOA: {
displayName: "kwanza angolais",
"displayName-count-one": "kwanza angolais",
"displayName-count-other": "kwanzas angolais",
symbol: "AOA",
"symbol-alt-narrow": "Kz"
},
AOK: {
displayName: "kwanza angolais (1977–1990)",
"displayName-count-one": "kwanza angolais (1977–1990)",
"displayName-count-other": "kwanzas angolais (1977–1990)",
symbol: "AOK"
},
AON: {
displayName: "nouveau kwanza angolais (1990–2000)",
"displayName-count-one": "nouveau kwanza angolais (1990–2000)",
"displayName-count-other": "nouveaux kwanzas angolais (1990–2000)",
symbol: "AON"
},
AOR: {
displayName: "kwanza angolais réajusté (1995–1999)",
"displayName-count-one": "kwanza angolais réajusté (1995–1999)",
"displayName-count-other": "kwanzas angolais réajustés (1995–1999)",
symbol: "AOR"
},
ARA: {
displayName: "austral argentin",
"displayName-count-one": "austral argentin",
"displayName-count-other": "australs argentins",
symbol: "ARA"
},
ARL: {
displayName: "ARL",
symbol: "ARL"
},
ARM: {
displayName: "ARM",
symbol: "ARM"
},
ARP: {
displayName: "peso argentin (1983–1985)",
"displayName-count-one": "peso argentin (1983–1985)",
"displayName-count-other": "pesos argentins (1983–1985)",
symbol: "ARP"
},
ARS: {
displayName: "peso argentin",
"displayName-count-one": "peso argentin",
"displayName-count-other": "pesos argentins",
symbol: "$AR",
"symbol-alt-narrow": "$"
},
ATS: {
displayName: "schilling autrichien",
"displayName-count-one": "schilling autrichien",
"displayName-count-other": "schillings autrichiens",
symbol: "ATS"
},
AUD: {
displayName: "dollar australien",
"displayName-count-one": "dollar australien",
"displayName-count-other": "dollars australiens",
symbol: "$AU",
"symbol-alt-narrow": "$"
},
AWG: {
displayName: "florin arubais",
"displayName-count-one": "florin arubais",
"displayName-count-other": "florins arubais",
symbol: "AWG"
},
AZM: {
displayName: "manat azéri (1993–2006)",
"displayName-count-one": "manat azéri (1993–2006)",
"displayName-count-other": "manats azéris (1993–2006)",
symbol: "AZM"
},
AZN: {
displayName: "manat azéri",
"displayName-count-one": "manat azéri",
"displayName-count-other": "manats azéris",
symbol: "AZN"
},
BAD: {
displayName: "dinar bosniaque",
"displayName-count-one": "dinar bosniaque",
"displayName-count-other": "dinars bosniaques",
symbol: "BAD"
},
BAM: {
displayName: "mark convertible bosniaque",
"displayName-count-one": "mark convertible bosniaque",
"displayName-count-other": "marks convertibles bosniaques",
symbol: "BAM",
"symbol-alt-narrow": "KM"
},
BAN: {
displayName: "BAN",
symbol: "BAN"
},
BBD: {
displayName: "dollar barbadien",
"displayName-count-one": "dollar barbadien",
"displayName-count-other": "dollars barbadiens",
symbol: "BBD",
"symbol-alt-narrow": "$"
},
BDT: {
displayName: "taka bangladeshi",
"displayName-count-one": "taka bangladeshi",
"displayName-count-other": "takas bangladeshis",
symbol: "BDT",
"symbol-alt-narrow": "৳"
},
BEC: {
displayName: "franc belge (convertible)",
"displayName-count-one": "franc belge (convertible)",
"displayName-count-other": "francs belges (convertibles)",
symbol: "BEC"
},
BEF: {
displayName: "franc belge",
"displayName-count-one": "franc belge",
"displayName-count-other": "francs belges",
symbol: "FB"
},
BEL: {
displayName: "franc belge (financier)",
"displayName-count-one": "franc belge (financier)",
"displayName-count-other": "francs belges (financiers)",
symbol: "BEL"
},
BGL: {
displayName: "lev bulgare (1962–1999)",
"displayName-count-one": "lev bulgare (1962–1999)",
"displayName-count-other": "levs bulgares (1962–1999)",
symbol: "BGL"
},
BGM: {
displayName: "BGM",
symbol: "BGM"
},
BGN: {
displayName: "lev bulgare",
"displayName-count-one": "lev bulgare",
"displayName-count-other": "levs bulgares",
symbol: "BGN"
},
BGO: {
displayName: "BGO",
symbol: "BGO"
},
BHD: {
displayName: "dinar bahreïni",
"displayName-count-one": "dinar bahreïni",
"displayName-count-other": "dinars bahreïnis",
symbol: "BHD"
},
BIF: {
displayName: "franc burundais",
"displayName-count-one": "franc burundais",
"displayName-count-other": "francs burundais",
symbol: "FBu"
},
BMD: {
displayName: "dollar bermudien",
"displayName-count-one": "dollar bermudien",
"displayName-count-other": "dollars bermudiens",
symbol: "$BM",
"symbol-alt-narrow": "$"
},
BND: {
displayName: "dollar brunéien",
"displayName-count-one": "dollar brunéien",
"displayName-count-other": "dollars brunéiens",
symbol: "$BN",
"symbol-alt-narrow": "$"
},
BOB: {
displayName: "boliviano bolivien",
"displayName-count-one": "boliviano bolivien",
"displayName-count-other": "bolivianos boliviens",
symbol: "BOB",
"symbol-alt-narrow": "Bs"
},
BOL: {
displayName: "BOL",
symbol: "BOL"
},
BOP: {
displayName: "peso bolivien",
"displayName-count-one": "peso bolivien",
"displayName-count-other": "pesos boliviens",
symbol: "BOP"
},
BOV: {
displayName: "mvdol bolivien",
"displayName-count-one": "mvdol bolivien",
"displayName-count-other": "mvdols boliviens",
symbol: "BOV"
},
BRB: {
displayName: "nouveau cruzeiro brésilien (1967–1986)",
"displayName-count-one": "nouveau cruzeiro brésilien (1967–1986)",
"displayName-count-other": "nouveaux cruzeiros brésiliens (1967–1986)",
symbol: "BRB"
},
BRC: {
displayName: "cruzado brésilien (1986–1989)",
"displayName-count-one": "cruzado brésilien (1986–1989)",
"displayName-count-other": "cruzados brésiliens (1986–1989)",
symbol: "BRC"
},
BRE: {
displayName: "cruzeiro brésilien (1990–1993)",
"displayName-count-one": "cruzeiro brésilien (1990–1993)",
"displayName-count-other": "cruzeiros brésiliens (1990–1993)",
symbol: "BRE"
},
BRL: {
displayName: "réal brésilien",
"displayName-count-one": "réal brésilien",
"displayName-count-other": "réals brésiliens",
symbol: "R$",
"symbol-alt-narrow": "R$"
},
BRN: {
displayName: "nouveau cruzado",
"displayName-count-one": "nouveau cruzado brésilien (1989–1990)",
"displayName-count-other": "nouveaux cruzados brésiliens (1989–1990)",
symbol: "BRN"
},
BRR: {
displayName: "cruzeiro",
"displayName-count-one": "cruzeiro réal brésilien (1993–1994)",
"displayName-count-other": "cruzeiros réals brésiliens (1993–1994)",
symbol: "BRR"
},
BRZ: {
displayName: "BRZ",
symbol: "BRZ"
},
BSD: {
displayName: "dollar bahaméen",
"displayName-count-one": "dollar bahaméen",
"displayName-count-other": "dollars bahaméens",
symbol: "BSD",
"symbol-alt-narrow": "$"
},
BTN: {
displayName: "ngultrum bouthanais",
"displayName-count-one": "ngultrum bouthanais",
"displayName-count-other": "ngultrums bouthanais",
symbol: "BTN"
},
BUK: {
displayName: "kyat birman",
"displayName-count-one": "kyat birman",
"displayName-count-other": "kyats birmans",
symbol: "BUK"
},
BWP: {
displayName: "pula botswanais",
"displayName-count-one": "pula botswanais",
"displayName-count-other": "pulas botswanais",
symbol: "BWP",
"symbol-alt-narrow": "P"
},
BYB: {
displayName: "nouveau rouble biélorusse (1994–1999)",
"displayName-count-one": "nouveau rouble biélorusse (1994–1999)",
"displayName-count-other": "nouveaux roubles biélorusses (1994–1999)",
symbol: "BYB"
},
BYN: {
displayName: "rouble biélorusse",
"displayName-count-one": "rouble biélorusse",
"displayName-count-other": "roubles biélorusses",
symbol: "BYN",
"symbol-alt-narrow": "р."
},
BYR: {
displayName: "rouble biélorusse (2000–2016)",
"displayName-count-one": "rouble biélorusse (2000–2016)",
"displayName-count-other": "roubles biélorusses (2000–2016)",
symbol: "BYR"
},
BZD: {
displayName: "dollar bélizéen",
"displayName-count-one": "dollar bélizéen",
"displayName-count-other": "dollars bélizéens",
symbol: "$BZ",
"symbol-alt-narrow": "$"
},
CAD: {
displayName: "dollar canadien",
"displayName-count-one": "dollar canadien",
"displayName-count-other": "dollars canadiens",
symbol: "$CA",
"symbol-alt-narrow": "$"
},
CDF: {
displayName: "franc congolais",
"displayName-count-one": "franc congolais",
"displayName-count-other": "francs congolais",
symbol: "CDF"
},
CHE: {
displayName: "euro WIR",
"displayName-count-one": "euro WIR",
"displayName-count-other": "euros WIR",
symbol: "CHE"
},
CHF: {
displayName: "franc suisse",
"displayName-count-one": "franc suisse",
"displayName-count-other": "francs suisses",
symbol: "CHF"
},
CHW: {
displayName: "franc WIR",
"displayName-count-one": "franc WIR",
"displayName-count-other": "francs WIR",
symbol: "CHW"
},
CLE: {
displayName: "CLE",
symbol: "CLE"
},
CLF: {
displayName: "unité d’investissement chilienne",
"displayName-count-one": "unité d’investissement chilienne",
"displayName-count-other": "unités d’investissement chiliennes",
symbol: "CLF"
},
CLP: {
displayName: "peso chilien",
"displayName-count-one": "peso chilien",
"displayName-count-other": "pesos chiliens",
symbol: "$CL",
"symbol-alt-narrow": "$"
},
CNH: {
displayName: "yuan chinois (zone extracôtière)",
"displayName-count-one": "yuan chinois (zone extracôtière)",
"displayName-count-other": "yuans chinois (zone extracôtière)",
symbol: "CNH"
},
CNX: {
displayName: "CNX",
symbol: "CNX"
},
CNY: {
displayName: "yuan renminbi chinois",
"displayName-count-one": "yuan renminbi chinois",
"displayName-count-other": "yuans renminbi chinois",
symbol: "CNY",
"symbol-alt-narrow": "¥"
},
COP: {
displayName: "peso colombien",
"displayName-count-one": "peso colombien",
"displayName-count-other": "pesos colombiens",
symbol: "$CO",
"symbol-alt-narrow": "$"
},
COU: {
displayName: "unité de valeur réelle colombienne",
"displayName-count-one": "unité de valeur réelle colombienne",
"displayName-count-other": "unités de valeur réelle colombiennes",
symbol: "COU"
},
CRC: {
displayName: "colón costaricain",
"displayName-count-one": "colón costaricain",
"displayName-count-other": "colóns costaricains",
symbol: "CRC",
"symbol-alt-narrow": "₡"
},
CSD: {
displayName: "dinar serbo-monténégrin",
"displayName-count-one": "dinar serbo-monténégrin",
"displayName-count-other": "dinars serbo-monténégrins",
symbol: "CSD"
},
CSK: {
displayName: "couronne forte tchécoslovaque",
"displayName-count-one": "couronne forte tchécoslovaque",
"displayName-count-other": "couronnes fortes tchécoslovaques",
symbol: "CSK"
},
CUC: {
displayName: "peso cubain convertible",
"displayName-count-one": "peso cubain convertible",
"displayName-count-other": "pesos cubains convertibles",
symbol: "CUC",
"symbol-alt-narrow": "$"
},
CUP: {
displayName: "peso cubain",
"displayName-count-one": "peso cubain",
"displayName-count-other": "pesos cubains",
symbol: "CUP",
"symbol-alt-narrow": "$"
},
CVE: {
displayName: "escudo capverdien",
"displayName-count-one": "escudo capverdien",
"displayName-count-other": "escudos capverdiens",
symbol: "CVE"
},
CYP: {
displayName: "livre chypriote",
"displayName-count-one": "livre chypriote",
"displayName-count-other": "livres chypriotes",
symbol: "£CY"
},
CZK: {
displayName: "couronne tchèque",
"displayName-count-one": "couronne tchèque",
"displayName-count-other": "couronnes tchèques",
symbol: "CZK",
"symbol-alt-narrow": "Kč"
},
DDM: {
displayName: "mark est-allemand",
"displayName-count-one": "mark est-allemand",
"displayName-count-other": "marks est-allemands",
symbol: "DDM"
},
DEM: {
displayName: "mark allemand",
"displayName-count-one": "mark allemand",
"displayName-count-other": "marks allemands",
symbol: "DEM"
},
DJF: {
displayName: "franc djiboutien",
"displayName-count-one": "franc djiboutien",
"displayName-count-other": "francs djiboutiens",
symbol: "DJF"
},
DKK: {
displayName: "couronne danoise",
"displayName-count-one": "couronne danoise",
"displayName-count-other": "couronnes danoises",
symbol: "DKK",
"symbol-alt-narrow": "kr"
},
DOP: {
displayName: "peso dominicain",
"displayName-count-one": "peso dominicain",
"displayName-count-other": "pesos dominicains",
symbol: "DOP",
"symbol-alt-narrow": "$"
},
DZD: {
displayName: "dinar algérien",
"displayName-count-one": "dinar algérien",
"displayName-count-other": "dinars algériens",
symbol: "DZD"
},
ECS: {
displayName: "sucre équatorien",
"displayName-count-one": "sucre équatorien",
"displayName-count-other": "sucres équatoriens",
symbol: "ECS"
},
ECV: {
displayName: "unité de valeur constante équatoriale (UVC)",
"displayName-count-one": "unité de valeur constante équatorienne (UVC)",
"displayName-count-other": "unités de valeur constante équatoriennes (UVC)",
symbol: "ECV"
},
EEK: {
displayName: "couronne estonienne",
"displayName-count-one": "couronne estonienne",
"displayName-count-other": "couronnes estoniennes",
symbol: "EEK"
},
EGP: {
displayName: "livre égyptienne",
"displayName-count-one": "livre égyptienne",
"displayName-count-other": "livres égyptiennes",
symbol: "EGP",
"symbol-alt-narrow": "£E"
},
ERN: {
displayName: "nafka érythréen",
"displayName-count-one": "nafka érythréen",
"displayName-count-other": "nafkas érythréens",
symbol: "ERN"
},
ESA: {
displayName: "peseta espagnole (compte A)",
"displayName-count-one": "peseta espagnole (compte A)",
"displayName-count-other": "pesetas espagnoles (compte A)",
symbol: "ESA"
},
ESB: {
displayName: "peseta espagnole (compte convertible)",
"displayName-count-one": "peseta espagnole (compte convertible)",
"displayName-count-other": "pesetas espagnoles (compte convertible)",
symbol: "ESB"
},
ESP: {
displayName: "peseta espagnole",
"displayName-count-one": "peseta espagnole",
"displayName-count-other": "pesetas espagnoles",
symbol: "ESP",
"symbol-alt-narrow": "₧"
},
ETB: {
displayName: "birr éthiopien",
"displayName-count-one": "birr éthiopien",
"displayName-count-other": "birrs éthiopiens",
symbol: "ETB"
},
EUR: {
displayName: "euro",
"displayName-count-one": "euro",
"displayName-count-other": "euros",
symbol: "€",
"symbol-alt-narrow": "€"
},
FIM: {
displayName: "mark finlandais",
"displayName-count-one": "mark finlandais",
"displayName-count-other": "marks finlandais",
symbol: "FIM"
},
FJD: {
displayName: "dollar fidjien",
"displayName-count-one": "dollar fidjien",
"displayName-count-other": "dollars fidjiens",
symbol: "$FJ",
"symbol-alt-narrow": "$"
},
FKP: {
displayName: "livre des îles Malouines",
"displayName-count-one": "livre des îles Malouines",
"displayName-count-other": "livres des îles Malouines",
symbol: "£FK",
"symbol-alt-narrow": "£"
},
FRF: {
displayName: "franc français",
"displayName-count-one": "franc français",
"displayName-count-other": "francs français",
symbol: "F"
},
GBP: {
displayName: "livre sterling",
"displayName-count-one": "livre sterling",
"displayName-count-other": "livres sterling",
symbol: "£GB",
"symbol-alt-narrow": "£"
},
GEK: {
displayName: "coupon de lari géorgien",
"displayName-count-one": "coupon de lari géorgien",
"displayName-count-other": "coupons de lari géorgiens",
symbol: "GEK"
},
GEL: {
displayName: "lari géorgien",
"displayName-count-one": "lari géorgien",
"displayName-count-other": "lari géorgiens",
symbol: "GEL",
"symbol-alt-narrow": "₾",
"symbol-alt-variant": "₾"
},
GHC: {
displayName: "cédi",
"displayName-count-one": "cédi ghanéen (1967–2007)",
"displayName-count-other": "cédis ghanéens (1967–2007)",
symbol: "GHC"
},
GHS: {
displayName: "cédi ghanéen",
"displayName-count-one": "cédi ghanéen",
"displayName-count-other": "cédis ghanéens",
symbol: "GHS"
},
GIP: {
displayName: "livre de Gibraltar",
"displayName-count-one": "livre de Gibraltar",
"displayName-count-other": "livres de Gibraltar",
symbol: "£GI",
"symbol-alt-narrow": "£"
},
GMD: {
displayName: "dalasi gambien",
"displayName-count-one": "dalasi gambien",
"displayName-count-other": "dalasis gambiens",
symbol: "GMD"
},
GNF: {
displayName: "franc guinéen",
"displayName-count-one": "franc guinéen",
"displayName-count-other": "francs guinéens",
symbol: "GNF",
"symbol-alt-narrow": "FG"
},
GNS: {
displayName: "syli guinéen",
"displayName-count-one": "syli guinéen",
"displayName-count-other": "sylis guinéens",
symbol: "GNS"
},
GQE: {
displayName: "ekwélé équatoguinéen",
"displayName-count-one": "ekwélé équatoguinéen",
"displayName-count-other": "ekwélés équatoguinéens",
symbol: "GQE"
},
GRD: {
displayName: "drachme grecque",
"displayName-count-one": "drachme grecque",
"displayName-count-other": "drachmes grecques",
symbol: "GRD"
},
GTQ: {
displayName: "quetzal guatémaltèque",
"displayName-count-one": "quetzal guatémaltèque",
"displayName-count-other": "quetzals guatémaltèques",
symbol: "GTQ",
"symbol-alt-narrow": "Q"
},
GWE: {
displayName: "escudo de Guinée portugaise",
"displayName-count-one": "escudo de Guinée portugaise",
"displayName-count-other": "escudos de Guinée portugaise",
symbol: "GWE"
},
GWP: {
displayName: "peso bissau-guinéen",
"displayName-count-one": "peso bissau-guinéen",
"displayName-count-other": "pesos bissau-guinéens",
symbol: "GWP"
},
GYD: {
displayName: "dollar du Guyana",
"displayName-count-one": "dollar du Guyana",
"displayName-count-other": "dollars du Guyana",
symbol: "GYD",
"symbol-alt-narrow": "$"
},
HKD: {
displayName: "dollar de Hong Kong",
"displayName-count-one": "dollar de Hong Kong",
"displayName-count-other": "dollars de Hong Kong",
symbol: "HKD",
"symbol-alt-narrow": "$"
},
HNL: {
displayName: "lempira hondurien",
"displayName-count-one": "lempira hondurien",
"displayName-count-other": "lempiras honduriens",
symbol: "HNL",
"symbol-alt-narrow": "L"
},
HRD: {
displayName: "dinar croate",
"displayName-count-one": "dinar croate",
"displayName-count-other": "dinars croates",
symbol: "HRD"
},
HRK: {
displayName: "kuna croate",
"displayName-count-one": "kuna croate",
"displayName-count-other": "kunas croates",
symbol: "HRK",
"symbol-alt-narrow": "kn"
},
HTG: {
displayName: "gourde haïtienne",
"displayName-count-one": "gourde haïtienne",
"displayName-count-other": "gourdes haïtiennes",
symbol: "HTG"
},
HUF: {
displayName: "forint hongrois",
"displayName-count-one": "forint hongrois",
"displayName-count-other": "forints hongrois",
symbol: "HUF",
"symbol-alt-narrow": "Ft"
},
IDR: {
displayName: "roupie indonésienne",
"displayName-count-one": "roupie indonésienne",
"displayName-count-other": "roupies indonésiennes",
symbol: "IDR",
"symbol-alt-narrow": "Rp"
},
IEP: {
displayName: "livre irlandaise",
"displayName-count-one": "livre irlandaise",
"displayName-count-other": "livres irlandaises",
symbol: "£IE"
},
ILP: {
displayName: "livre israélienne",
"displayName-count-one": "livre israélienne",
"displayName-count-other": "livres israéliennes",
symbol: "£IL"
},
ILR: {
displayName: "ILR",
symbol: "ILR"
},
ILS: {
displayName: "nouveau shekel israélien",
"displayName-count-one": "nouveau shekel israélien",
"displayName-count-other": "nouveaux shekels israéliens",
symbol: "₪",
"symbol-alt-narrow": "₪"
},
INR: {
displayName: "roupie indienne",
"displayName-count-one": "roupie indienne",
"displayName-count-other": "roupies indiennes",
symbol: "₹",
"symbol-alt-narrow": "₹"
},
IQD: {
displayName: "dinar irakien",
"displayName-count-one": "dinar irakien",
"displayName-count-other": "dinars irakiens",
symbol: "IQD"
},
IRR: {
displayName: "riyal iranien",
"displayName-count-one": "riyal iranien",
"displayName-count-other": "riyals iraniens",
symbol: "IRR"
},
ISJ: {
displayName: "ISJ",
symbol: "ISJ"
},
ISK: {
displayName: "couronne islandaise",
"displayName-count-one": "couronne islandaise",
"displayName-count-other": "couronnes islandaises",
symbol: "ISK",
"symbol-alt-narrow": "kr"
},
ITL: {
displayName: "lire italienne",
"displayName-count-one": "lire italienne",
"displayName-count-other": "lires italiennes",
symbol: "₤IT"
},
JMD: {
displayName: "dollar jamaïcain",
"displayName-count-one": "dollar jamaïcain",
"displayName-count-other": "dollars jamaïcains",
symbol: "JMD",
"symbol-alt-narrow": "$"
},
JOD: {
displayName: "dinar jordanien",
"displayName-count-one": "dinar jordanien",
"displayName-count-other": "dinars jordaniens",
symbol: "JOD"
},
JPY: {
displayName: "yen japonais",
"displayName-count-one": "yen japonais",
"displayName-count-other": "yens japonais",
symbol: "JPY",
"symbol-alt-narrow": "¥"
},
KES: {
displayName: "shilling kényan",
"displayName-count-one": "shilling kényan",
"displayName-count-other": "shillings kényans",
symbol: "KES"
},
KGS: {
displayName: "som kirghize",
"displayName-count-one": "som kirghize",
"displayName-count-other": "soms kirghizes",
symbol: "KGS"
},
KHR: {
displayName: "riel cambodgien",
"displayName-count-one": "riel cambodgien",
"displayName-count-other": "riels cambodgiens",
symbol: "KHR",
"symbol-alt-narrow": "៛"
},
KMF: {
displayName: "franc comorien",
"displayName-count-one": "franc comorien",
"displayName-count-other": "francs comoriens",
symbol: "KMF",
"symbol-alt-narrow": "FC"
},
KPW: {
displayName: "won nord-coréen",
"displayName-count-one": "won nord-coréen",
"displayName-count-other": "wons nord-coréens",
symbol: "KPW",
"symbol-alt-narrow": "₩"
},
KRH: {
displayName: "KRH",
symbol: "KRH"
},
KRO: {
displayName: "KRO",
symbol: "KRO"
},
KRW: {
displayName: "won sud-coréen",
"displayName-count-one": "won sud-coréen",
"displayName-count-other": "wons sud-coréens",
symbol: "₩",
"symbol-alt-narrow": "₩"
},
KWD: {
displayName: "dinar koweïtien",
"displayName-count-one": "dinar koweïtien",
"displayName-count-other": "dinar koweïtiens",
symbol: "KWD"
},
KYD: {
displayName: "dollar des îles Caïmans",
"displayName-count-one": "dollar des îles Caïmans",
"displayName-count-other": "dollars des îles Caïmans",
symbol: "KYD",
"symbol-alt-narrow": "$"
},
KZT: {
displayName: "tenge kazakh",
"displayName-count-one": "tenge kazakh",
"displayName-count-other": "tenges kazakhs",
symbol: "KZT",
"symbol-alt-narrow": "₸"
},
LAK: {
displayName: "kip loatien",
"displayName-count-one": "kip loatien",
"displayName-count-other": "kips loatiens",
symbol: "LAK",
"symbol-alt-narrow": "₭"
},
LBP: {
displayName: "livre libanaise",
"displayName-count-one": "livre libanaise",
"displayName-count-other": "livres libanaises",
symbol: "£LB",
"symbol-alt-narrow": "£L"
},
LKR: {
displayName: "roupie srilankaise",
"displayName-count-one": "roupie srilankaise",
"displayName-count-other": "roupies srilankaises",
symbol: "LKR",
"symbol-alt-narrow": "Rs"
},
LRD: {
displayName: "dollar libérien",
"displayName-count-one": "dollar libérien",
"displayName-count-other": "dollars libériens",
symbol: "LRD",
"symbol-alt-narrow": "$"
},
LSL: {
displayName: "loti lesothan",
"displayName-count-one": "loti lesothan",
"displayName-count-other": "maloti lesothans",
symbol: "LSL"
},
LTL: {
displayName: "litas lituanien",
"displayName-count-one": "litas lituanien",
"displayName-count-other": "litas lituaniens",
symbol: "LTL",
"symbol-alt-narrow": "Lt"
},
LTT: {
displayName: "talonas lituanien",
"displayName-count-one": "talonas lituanien",
"displayName-count-other": "talonas lituaniens",
symbol: "LTT"
},
LUC: {
displayName: "franc convertible luxembourgeois",
"displayName-count-one": "franc convertible luxembourgeois",
"displayName-count-other": "francs convertibles luxembourgeois",
symbol: "LUC"
},
LUF: {
displayName: "franc luxembourgeois",
"displayName-count-one": "franc luxembourgeois",
"displayName-count-other": "francs luxembourgeois",
symbol: "LUF"
},
LUL: {
displayName: "franc financier luxembourgeois",
"displayName-count-one": "franc financier luxembourgeois",
"displayName-count-other": "francs financiers luxembourgeois",
symbol: "LUL"
},
LVL: {
displayName: "lats letton",
"displayName-count-one": "lats letton",
"displayName-count-other": "lats lettons",
symbol: "LVL",
"symbol-alt-narrow": "Ls"
},
LVR: {
displayName: "rouble letton",
"displayName-count-one": "rouble letton",
"displayName-count-other": "roubles lettons",
symbol: "LVR"
},
LYD: {
displayName: "dinar libyen",
"displayName-count-one": "dinar libyen",
"displayName-count-other": "dinars libyens",
symbol: "LYD"
},
MAD: {
displayName: "dirham marocain",
"displayName-count-one": "dirham marocain",
"displayName-count-other": "dirhams marocains",
symbol: "MAD"
},
MAF: {
displayName: "franc marocain",
"displayName-count-one": "franc marocain",
"displayName-count-other": "francs marocains",
symbol: "MAF"
},
MCF: {
displayName: "MCF",
symbol: "MCF"
},
MDC: {
displayName: "MDC",
symbol: "MDC"
},
MDL: {
displayName: "leu moldave",
"displayName-count-one": "leu moldave",
"displayName-count-other": "leus moldaves",
symbol: "MDL"
},
MGA: {
displayName: "ariary malgache",
"displayName-count-one": "ariary malgache",
"displayName-count-other": "ariarys malgaches",
symbol: "MGA",
"symbol-alt-narrow": "Ar"
},
MGF: {
displayName: "franc malgache",
"displayName-count-one": "franc malgache",
"displayName-count-other": "francs malgaches",
symbol: "MGF"
},
MKD: {
displayName: "denar macédonien",
"displayName-count-one": "denar macédonien",
"displayName-count-other": "denars macédoniens",
symbol: "MKD"
},
MKN: {
displayName: "MKN",
symbol: "MKN"
},
MLF: {
displayName: "franc malien",
"displayName-count-one": "franc malien",
"displayName-count-other": "francs maliens",
symbol: "MLF"
},
MMK: {
displayName: "kyat myanmarais",
"displayName-count-one": "kyat myanmarais",
"displayName-count-other": "kyats myanmarais",
symbol: "MMK",
"symbol-alt-narrow": "K"
},
MNT: {
displayName: "tugrik mongol",
"displayName-count-one": "tugrik mongol",
"displayName-count-other": "tugriks mongols",
symbol: "MNT",
"symbol-alt-narrow": "₮"
},
MOP: {
displayName: "pataca macanaise",
"displayName-count-one": "pataca macanaise",
"displayName-count-other": "patacas macanaises",
symbol: "MOP"
},
MRO: {
displayName: "ouguiya mauritanien (1973–2017)",
"displayName-count-one": "ouguiya mauritanien (1973–2017)",
"displayName-count-other": "ouguiyas mauritaniens (1973–2017)",
symbol: "MRO"
},
MRU: {
displayName: "ouguiya mauritanien",
"displayName-count-one": "ouguiya mauritanien",
"displayName-count-other": "ouguiyas mauritaniens",
symbol: "MRU"
},
MTL: {
displayName: "lire maltaise",
"displayName-count-one": "lire maltaise",
"displayName-count-other": "lires maltaises",
symbol: "MTL"
},
MTP: {
displayName: "livre maltaise",
"displayName-count-one": "livre maltaise",
"displayName-count-other": "livres maltaises",
symbol: "£MT"
},
MUR: {
displayName: "roupie mauricienne",
"displayName-count-one": "roupie mauricienne",
"displayName-count-other": "roupies mauriciennes",
symbol: "MUR",
"symbol-alt-narrow": "Rs"
},
MVP: {
displayName: "MVP",
symbol: "MVP"
},
MVR: {
displayName: "rufiyaa maldivien",
"displayName-count-one": "rufiyaa maldivienne",
"displayName-count-other": "rufiyaas maldiviennes",
symbol: "MVR"
},
MWK: {
displayName: "kwacha malawite",
"displayName-count-one": "kwacha malawite",
"displayName-count-other": "kwachas malawites",
symbol: "MWK"
},
MXN: {
displayName: "peso mexicain",
"displayName-count-one": "peso mexicain",
"displayName-count-other": "pesos mexicains",
symbol: "$MX",
"symbol-alt-narrow": "$"
},
MXP: {
displayName: "peso d’argent mexicain (1861–1992)",
"displayName-count-one": "peso d’argent mexicain (1861–1992)",
"displayName-count-other": "pesos d’argent mexicains (1861–1992)",
symbol: "MXP"
},
MXV: {
displayName: "unité de conversion mexicaine (UDI)",
"displayName-count-one": "unité de conversion mexicaine (UDI)",
"displayName-count-other": "unités de conversion mexicaines (UDI)",
symbol: "MXV"
},
MYR: {
displayName: "ringgit malais",
"displayName-count-one": "ringgit malais",
"displayName-count-other": "ringgits malais",
symbol: "MYR",
"symbol-alt-narrow": "RM"
},
MZE: {
displayName: "escudo mozambicain",
"displayName-count-one": "escudo mozambicain",
"displayName-count-other": "escudos mozambicains",
symbol: "MZE"
},
MZM: {
displayName: "métical",
"displayName-count-one": "metical mozambicain (1980–2006)",
"displayName-count-other": "meticais mozambicains (1980–2006)",
symbol: "MZM"
},
MZN: {
displayName: "metical mozambicain",
"displayName-count-one": "metical mozambicain",
"displayName-count-other": "meticais mozambicains",
symbol: "MZN"
},
NAD: {
displayName: "dollar namibien",
"displayName-count-one": "dollar namibien",
"displayName-count-other": "dollars namibiens",
symbol: "$NA",
"symbol-alt-narrow": "$"
},
NGN: {
displayName: "naira nigérian",
"displayName-count-one": "naira nigérian",
"displayName-count-other": "nairas nigérians",
symbol: "NGN",
"symbol-alt-narrow": "₦"
},
NIC: {
displayName: "cordoba",
"displayName-count-one": "córdoba nicaraguayen (1912–1988)",
"displayName-count-other": "córdobas nicaraguayens (1912–1988)",
symbol: "NIC"
},
NIO: {
displayName: "córdoba oro nicaraguayen",
"displayName-count-one": "córdoba oro nicaraguayen",
"displayName-count-other": "córdobas oro nicaraguayens",
symbol: "NIO",
"symbol-alt-narrow": "$C"
},
NLG: {
displayName: "florin néerlandais",
"displayName-count-one": "florin néerlandais",
"displayName-count-other": "florins néerlandais",
symbol: "NLG"
},
NOK: {
displayName: "couronne norvégienne",
"displayName-count-one": "couronne norvégienne",
"displayName-count-other": "couronnes norvégiennes",
symbol: "NOK",
"symbol-alt-narrow": "kr"
},
NPR: {
displayName: "roupie népalaise",
"displayName-count-one": "roupie népalaise",
"displayName-count-other": "roupies népalaises",
symbol: "NPR",
"symbol-alt-narrow": "Rs"
},
NZD: {
displayName: "dollar néo-zélandais",
"displayName-count-one": "dollar néo-zélandais",
"displayName-count-other": "dollars néo-zélandais",
symbol: "$NZ",
"symbol-alt-narrow": "$"
},
OMR: {
displayName: "riyal omanais",
"displayName-count-one": "riyal omanais",
"displayName-count-other": "riyals omanis",
symbol: "OMR"
},
PAB: {
displayName: "balboa panaméen",
"displayName-count-one": "balboa panaméen",
"displayName-count-other": "balboas panaméens",
symbol: "PAB"
},
PEI: {
displayName: "inti péruvien",
"displayName-count-one": "inti péruvien",
"displayName-count-other": "intis péruviens",
symbol: "PEI"
},
PEN: {
displayName: "sol péruvien",
"displayName-count-one": "sol péruvien",
"displayName-count-other": "sols péruviens",
symbol: "PEN"
},
PES: {
displayName: "sol péruvien (1863–1985)",
"displayName-count-one": "sol péruvien (1863–1985)",
"displayName-count-other": "sols péruviens (1863–1985)",
symbol: "PES"
},
PGK: {
displayName: "kina papouan-néo-guinéen",
"displayName-count-one": "kina papouan-néo-guinéen",
"displayName-count-other": "kinas papouan-néo-guinéens",
symbol: "PGK"
},
PHP: {
displayName: "peso philippin",
"displayName-count-one": "peso philippin",
"displayName-count-other": "pesos philippins",
symbol: "PHP",
"symbol-alt-narrow": "₱"
},
PKR: {
displayName: "roupie pakistanaise",
"displayName-count-one": "roupie pakistanaise",
"displayName-count-other": "roupies pakistanaises",
symbol: "PKR",
"symbol-alt-narrow": "Rs"
},
PLN: {
displayName: "zloty polonais",
"displayName-count-one": "zloty polonais",
"displayName-count-other": "zlotys polonais",
symbol: "PLN",
"symbol-alt-narrow": "zł"
},
PLZ: {
displayName: "zloty (1950–1995)",
"displayName-count-one": "zloty polonais (1950–1995)",
"displayName-count-other": "zlotys polonais (1950–1995)",
symbol: "PLZ"
},
PTE: {
displayName: "escudo portugais",
"displayName-count-one": "escudo portugais",
"displayName-count-other": "escudos portugais",
symbol: "PTE"
},
PYG: {
displayName: "guaraní paraguayen",
"displayName-count-one": "guaraní paraguayen",
"displayName-count-other": "guaranís paraguayens",
symbol: "PYG",
"symbol-alt-narrow": "₲"
},
QAR: {
displayName: "riyal qatari",
"displayName-count-one": "riyal qatari",
"displayName-count-other": "riyals qataris",
symbol: "QAR"
},
RHD: {
displayName: "dollar rhodésien",
"displayName-count-one": "dollar rhodésien",
"displayName-count-other": "dollars rhodésiens",
symbol: "$RH"
},
ROL: {
displayName: "ancien leu roumain",
"displayName-count-one": "leu roumain (1952–2005)",
"displayName-count-other": "lei roumains (1952–2005)",
symbol: "ROL"
},
RON: {
displayName: "leu roumain",
"displayName-count-one": "leu roumain",
"displayName-count-other": "lei roumains",
symbol: "RON",
"symbol-alt-narrow": "L"
},
RSD: {
displayName: "dinar serbe",
"displayName-count-one": "dinar serbe",
"displayName-count-other": "dinars serbes",
symbol: "RSD"
},
RUB: {
displayName: "rouble russe",
"displayName-count-one": "rouble russe",
"displayName-count-other": "roubles russes",
symbol: "RUB",
"symbol-alt-narrow": "₽"
},
RUR: {
displayName: "rouble russe (1991–1998)",
"displayName-count-one": "rouble russe (1991–1998)",
"displayName-count-other": "roubles russes (1991–1998)",
symbol: "RUR",
"symbol-alt-narrow": "р."
},
RWF: {
displayName: "franc rwandais",
"displayName-count-one": "franc rwandais",
"displayName-count-other": "francs rwandais",
symbol: "RWF",
"symbol-alt-narrow": "FR"
},
SAR: {
displayName: "riyal saoudien",
"displayName-count-one": "riyal saoudien",
"displayName-count-other": "riyals saoudiens",
symbol: "SAR"
},
SBD: {
displayName: "dollar des îles Salomon",
"displayName-count-one": "dollar des îles Salomon",
"displayName-count-other": "dollars des îles Salomon",
symbol: "$SB",
"symbol-alt-narrow": "$"
},
SCR: {
displayName: "roupie des Seychelles",
"displayName-count-one": "roupie des Seychelles",
"displayName-count-other": "roupies des Seychelles",
symbol: "SCR"
},
SDD: {
displayName: "dinar soudanais",
"displayName-count-one": "dinar soudanais (1992–2007)",
"displayName-count-other": "dinars soudanais (1992–2007)",
symbol: "SDD"
},
SDG: {
displayName: "livre soudanaise",
"displayName-count-one": "livre soudanaise",
"displayName-count-other": "livres soudanaises",
symbol: "SDG"
},
SDP: {
displayName: "livre soudanaise (1956–2007)",
"displayName-count-one": "livre soudanaise (1956–2007)",
"displayName-count-other": "livres soudanaises (1956–2007)",
symbol: "SDP"
},
SEK: {
displayName: "couronne suédoise",
"displayName-count-one": "couronne suédoise",
"displayName-count-other": "couronnes suédoises",
symbol: "SEK",
"symbol-alt-narrow": "kr"
},
SGD: {
displayName: "dollar de Singapour",
"displayName-count-one": "dollar de Singapour",
"displayName-count-other": "dollars de Singapour",
symbol: "$SG",
"symbol-alt-narrow": "$"
},
SHP: {
displayName: "livre de Sainte-Hélène",
"displayName-count-one": "livre de Sainte-Hélène",
"displayName-count-other": "livres de Sainte-Hélène",
symbol: "SHP",
"symbol-alt-narrow": "£"
},
SIT: {
displayName: "tolar slovène",
"displayName-count-one": "tolar slovène",
"displayName-count-other": "tolars slovènes",
symbol: "SIT"
},
SKK: {
displayName: "couronne slovaque",
"displayName-count-one": "couronne slovaque",
"displayName-count-other": "couronnes slovaques",
symbol: "SKK"
},
SLL: {
displayName: "leone sierra-léonais",
"displayName-count-one": "leone sierra-léonais",
"displayName-count-other": "leones sierra-léonais",
symbol: "SLL"
},
SOS: {
displayName: "shilling somalien",
"displayName-count-one": "shilling somalien",
"displayName-count-other": "shillings somaliens",
symbol: "SOS"
},
SRD: {
displayName: "dollar surinamais",
"displayName-count-one": "dollar surinamais",
"displayName-count-other": "dollars surinamais",
symbol: "$SR",
"symbol-alt-narrow": "$"
},
SRG: {
displayName: "florin surinamais",
"displayName-count-one": "florin surinamais",
"displayName-count-other": "florins surinamais",
symbol: "SRG"
},
SSP: {
displayName: "livre sud-soudanaise",
"displayName-count-one": "livre sud-soudanaise",
"displayName-count-other": "livres sud-soudanaises",
symbol: "SSP",
"symbol-alt-narrow": "£"
},
STD: {
displayName: "dobra santoméen (1977–2017)",
"displayName-count-one": "dobra santoméen (1977–2017)",
"displayName-count-other": "dobras santoméens (1977–2017)",
symbol: "STD"
},
STN: {
displayName: "dobra santoméen",
"displayName-count-one": "dobra santoméen",
"displayName-count-other": "dobras santoméens",
symbol: "STN",
"symbol-alt-narrow": "Db"
},
SUR: {
displayName: "rouble soviétique",
"displayName-count-one": "rouble soviétique",
"displayName-count-other": "roubles soviétiques",
symbol: "SUR"
},
SVC: {
displayName: "colón salvadorien",
"displayName-count-one": "colón salvadorien",
"displayName-count-other": "colóns salvadoriens",
symbol: "SVC"
},
SYP: {
displayName: "livre syrienne",
"displayName-count-one": "livre syrienne",
"displayName-count-other": "livres syriennes",
symbol: "SYP",
"symbol-alt-narrow": "£"
},
SZL: {
displayName: "lilangeni swazi",
"displayName-count-one": "lilangeni swazi",
"displayName-count-other": "lilangenis swazis",
symbol: "SZL"
},
THB: {
displayName: "baht thaïlandais",
"displayName-count-one": "baht thaïlandais",
"displayName-count-other": "bahts thaïlandais",
symbol: "THB",
"symbol-alt-narrow": "฿"
},
TJR: {
displayName: "rouble tadjik",
"displayName-count-one": "rouble tadjik",
"displayName-count-other": "roubles tadjiks",
symbol: "TJR"
},
TJS: {
displayName: "somoni tadjik",
"displayName-count-one": "somoni tadjik",
"displayName-count-other": "somonis tadjiks",
symbol: "TJS"
},
TMM: {
displayName: "manat turkmène",
"displayName-count-one": "manat turkmène",
"displayName-count-other": "manats turkmènes",
symbol: "TMM"
},
TMT: {
displayName: "nouveau manat turkmène",
"displayName-count-one": "nouveau manat turkmène",
"displayName-count-other": "nouveaux manats turkmènes",
symbol: "TMT"
},
TND: {
displayName: "dinar tunisien",
"displayName-count-one": "dinar tunisien",
"displayName-count-other": "dinars tunisiens",
symbol: "TND"
},
TOP: {
displayName: "pa’anga tongan",
"displayName-count-one": "pa’anga tongan",
"displayName-count-other": "pa’angas tongans",
symbol: "TOP",
"symbol-alt-narrow": "$T"
},
TPE: {
displayName: "escudo timorais",
"displayName-count-one": "escudo timorais",
"displayName-count-other": "escudos timorais",
symbol: "TPE"
},
TRL: {
displayName: "livre turque (1844–2005)",
"displayName-count-one": "livre turque (1844–2005)",
"displayName-count-other": "livres turques (1844–2005)",
symbol: "TRL"
},
TRY: {
displayName: "livre turque",
"displayName-count-one": "livre turque",
"displayName-count-other": "livres turques",
symbol: "TRY",
"symbol-alt-narrow": "₺",
"symbol-alt-variant": "LT"
},
TTD: {
displayName: "dollar trinidadien",
"displayName-count-one": "dollar de Trinité-et-Tobago",
"displayName-count-other": "dollars de Trinité-et-Tobago",
symbol: "$TT",
"symbol-alt-narrow": "$"
},
TWD: {
displayName: "nouveau dollar taïwanais",
"displayName-count-one": "nouveau dollar taïwanais",
"displayName-count-other": "nouveaux dollars taïwanais",
symbol: "TWD",
"symbol-alt-narrow": "NT$"
},
TZS: {
displayName: "shilling tanzanien",
"displayName-count-one": "shilling tanzanien",
"displayName-count-other": "shillings tanzaniens",
symbol: "TZS"
},
UAH: {
displayName: "hryvnia ukrainienne",
"displayName-count-one": "hryvnia ukrainienne",
"displayName-count-other": "hryvnias ukrainiennes",
symbol: "UAH",
"symbol-alt-narrow": "₴"
},
UAK: {
displayName: "karbovanetz",
"displayName-count-one": "karbovanets ukrainien (1992–1996)",
"displayName-count-other": "karbovanets ukrainiens (1992–1996)",
symbol: "UAK"
},
UGS: {
displayName: "shilling ougandais (1966–1987)",
"displayName-count-one": "shilling ougandais (1966–1987)",
"displayName-count-other": "shillings ougandais (1966–1987)",
symbol: "UGS"
},
UGX: {
displayName: "shilling ougandais",
"displayName-count-one": "shilling ougandais",
"displayName-count-other": "shillings ougandais",
symbol: "UGX"
},
USD: {
displayName: "dollar des États-Unis",
"displayName-count-one": "dollar des États-Unis",
"displayName-count-other": "dollars des États-Unis",
symbol: "$US",
"symbol-alt-narrow": "$"
},
USN: {
displayName: "dollar des Etats-Unis (jour suivant)",
"displayName-count-one": "dollar des États-Unis (jour suivant)",
"displayName-count-other": "dollars des États-Unis (jour suivant)",
symbol: "USN"
},
USS: {
displayName: "dollar des Etats-Unis (jour même)",
"displayName-count-one": "dollar des États-Unis (jour même)",
"displayName-count-other": "dollars des États-Unis (jour même)",
symbol: "USS"
},
UYI: {
displayName: "peso uruguayen (unités indexées)",
"displayName-count-one": "peso uruguayen (unités indexées)",
"displayName-count-other": "pesos uruguayen (unités indexées)",
symbol: "UYI"
},
UYP: {
displayName: "peso uruguayen (1975–1993)",
"displayName-count-one": "peso uruguayen (1975–1993)",
"displayName-count-other": "pesos uruguayens (1975–1993)",
symbol: "UYP"
},
UYU: {
displayName: "peso uruguayen",
"displayName-count-one": "peso uruguayen",
"displayName-count-other": "pesos uruguayens",
symbol: "$UY",
"symbol-alt-narrow": "$"
},
UYW: {
displayName: "UYW",
symbol: "UYW"
},
UZS: {
displayName: "sum ouzbek",
"displayName-count-one": "sum ouzbek",
"displayName-count-other": "sums ouzbeks",
symbol: "UZS"
},
VEB: {
displayName: "bolivar vénézuélien (1871–2008)",
"displayName-count-one": "bolivar vénézuélien (1871–2008)",
"displayName-count-other": "bolivar vénézuélien (1871–2008)",
symbol: "VEB"
},
VEF: {
displayName: "bolivar vénézuélien (2008–2018)",
"displayName-count-one": "bolivar vénézuélien (2008–2018)",
"displayName-count-other": "bolivars vénézuéliens (2008–2018)",
symbol: "VEF",
"symbol-alt-narrow": "Bs"
},
VES: {
displayName: "bolivar vénézuélien",
"displayName-count-one": "bolivar vénézuélien",
"displayName-count-other": "bolivars vénézuéliens",
symbol: "VES"
},
VND: {
displayName: "dông vietnamien",
"displayName-count-one": "dông vietnamien",
"displayName-count-other": "dôngs vietnamiens",
symbol: "₫",
"symbol-alt-narrow": "₫"
},
VNN: {
displayName: "VNN",
symbol: "VNN"
},
VUV: {
displayName: "vatu vanuatuan",
"displayName-count-one": "vatu vanuatuan",
"displayName-count-other": "vatus vanuatuans",
symbol: "VUV"
},
WST: {
displayName: "tala samoan",
"displayName-count-one": "tala samoan",
"displayName-count-other": "talas samoans",
symbol: "$WS"
},
XAF: {
displayName: "franc CFA (BEAC)",
"displayName-count-one": "franc CFA (BEAC)",
"displayName-count-other": "francs CFA (BEAC)",
symbol: "FCFA"
},
XAG: {
displayName: "argent",
"displayName-count-one": "once troy d’argent",
"displayName-count-other": "onces troy d’argent",
symbol: "XAG"
},
XAU: {
displayName: "or",
"displayName-count-one": "once troy d’or",
"displayName-count-other": "onces troy d’or",
symbol: "XAU"
},
XBA: {
displayName: "unité européenne composée",
"displayName-count-one": "unité composée européenne (EURCO)",
"displayName-count-other": "unités composées européennes (EURCO)",
symbol: "XBA"
},
XBB: {
displayName: "unité monétaire européenne",
"displayName-count-one": "unité monétaire européenne (UME–6)",
"displayName-count-other": "unités monétaires européennes (UME–6)",
symbol: "XBB"
},
XBC: {
displayName: "unité de compte européenne (XBC)",
"displayName-count-one": "unité de compte 9 européenne (UEC–9)",
"displayName-count-other": "unités de compte 9 européennes (UEC–9)",
symbol: "XBC"
},
XBD: {
displayName: "unité de compte européenne (XBD)",
"displayName-count-one": "unité de compte 17 européenne (UEC–17)",
"displayName-count-other": "unités de compte 17 européennes (UEC–17)",
symbol: "XBD"
},
XCD: {
displayName: "dollar des Caraïbes orientales",
"displayName-count-one": "dollar des Caraïbes orientales",
"displayName-count-other": "dollars des Caraïbes orientales",
symbol: "XCD",
"symbol-alt-narrow": "$"
},
XDR: {
displayName: "droit de tirage spécial",
"displayName-count-one": "droit de tirage spécial",
"displayName-count-other": "droits de tirage spéciaux",
symbol: "XDR"
},
XEU: {
displayName: "unité de compte européenne (ECU)",
symbol: "XEU"
},
XFO: {
displayName: "franc or",
"displayName-count-one": "franc or",
"displayName-count-other": "francs or",
symbol: "XFO"
},
XFU: {
displayName: "franc UIC",
"displayName-count-one": "franc UIC",
"displayName-count-other": "francs UIC",
symbol: "XFU"
},
XOF: {
displayName: "franc CFA (BCEAO)",
"displayName-count-one": "franc CFA (BCEAO)",
"displayName-count-other": "francs CFA (BCEAO)",
symbol: "CFA"
},
XPD: {
displayName: "palladium",
"displayName-count-one": "once troy de palladium",
"displayName-count-other": "onces troy de palladium",
symbol: "XPD"
},
XPF: {
displayName: "franc CFP",
"displayName-count-one": "franc CFP",
"displayName-count-other": "francs CFP",
symbol: "FCFP"
},
XPT: {
displayName: "platine",
"displayName-count-one": "once troy de platine",
"displayName-count-other": "onces troy de platine",
symbol: "XPT"
},
XRE: {
displayName: "type de fonds RINET",
"displayName-count-one": "unité de fonds RINET",
"displayName-count-other": "unités de fonds RINET",
symbol: "XRE"
},
XSU: {
displayName: "XSU",
symbol: "XSU"
},
XTS: {
displayName: "(devise de test)",
"displayName-count-one": "(devise de test)",
"displayName-count-other": "(devises de test)",
symbol: "XTS"
},
XUA: {
displayName: "XUA",
symbol: "XUA"
},
XXX: {
displayName: "devise inconnue ou non valide",
"displayName-count-one": "devise inconnue",
"displayName-count-other": "devises inconnues",
symbol: "¤"
},
YDD: {
displayName: "dinar du Yémen",
"displayName-count-one": "dinar nord-yéménite",
"displayName-count-other": "dinars nord-yéménites",
symbol: "YDD"
},
YER: {
displayName: "riyal yéménite",
"displayName-count-one": "riyal yéménite",
"displayName-count-other": "riyals yéménites",
symbol: "YER"
},
YUD: {
displayName: "nouveau dinar yougoslave",
"displayName-count-one": "dinar fort yougoslave (1966–1989)",
"displayName-count-other": "dinars forts yougoslaves (1966–1989)",
symbol: "YUD"
},
YUM: {
displayName: "dinar yougoslave Noviy",
"displayName-count-one": "nouveau dinar yougoslave (1994–2003)",
"displayName-count-other": "nouveaux dinars yougoslaves (1994–2003)",
symbol: "YUM"
},
YUN: {
displayName: "dinar yougoslave convertible",
"displayName-count-one": "dinar convertible yougoslave (1990–1992)",
"displayName-count-other": "dinars convertibles yougoslaves (1990–1992)",
symbol: "YUN"
},
YUR: {
displayName: "YUR",
symbol: "YUR"
},
ZAL: {
displayName: "rand sud-africain (financier)",
"displayName-count-one": "rand sud-africain (financier)",
"displayName-count-other": "rands sud-africains (financiers)",
symbol: "ZAL"
},
ZAR: {
displayName: "rand sud-africain",
"displayName-count-one": "rand sud-africain",
"displayName-count-other": "rands sud-africains",
symbol: "ZAR",
"symbol-alt-narrow": "R"
},
ZMK: {
displayName: "kwacha zambien (1968–2012)",
"displayName-count-one": "kwacha zambien (1968–2012)",
"displayName-count-other": "kwachas zambiens (1968–2012)",
symbol: "ZMK"
},
ZMW: {
displayName: "kwacha zambien",
"displayName-count-one": "kwacha zambien",
"displayName-count-other": "kwachas zambiens",
symbol: "ZMW",
"symbol-alt-narrow": "Kw"
},
ZRN: {
displayName: "nouveau zaïre zaïrien",
"displayName-count-one": "nouveau zaïre zaïrien",
"displayName-count-other": "nouveaux zaïres zaïriens",
symbol: "ZRN"
},
ZRZ: {
displayName: "zaïre zaïrois",
"displayName-count-one": "zaïre zaïrois",
"displayName-count-other": "zaïres zaïrois",
symbol: "ZRZ"
},
ZWD: {
displayName: "dollar zimbabwéen",
"displayName-count-one": "dollar zimbabwéen",
"displayName-count-other": "dollars zimbabwéens",
symbol: "ZWD"
},
ZWL: {
displayName: "dollar zimbabwéen (2009)",
"displayName-count-one": "dollar zimbabwéen (2009)",
"displayName-count-other": "dollars zimbabwéens (2009)",
symbol: "ZWL"
},
ZWR: {
displayName: "dollar zimbabwéen (2008)",
"displayName-count-one": "dollar zimbabwéen (2008)",
"displayName-count-other": "dollars zimbabwéens (2008)",
symbol: "ZWR"
}
},
localeCurrency: "BIF"
},
calendar: {
patterns: {
d: "dd/MM/y",
D: "EEEE d MMMM y",
m: "d MMM",
M: "d MMMM",
y: "MMM y",
Y: "MMMM y",
F: "EEEE d MMMM y HH:mm:ss",
g: "dd/MM/y HH:mm",
G: "dd/MM/y HH:mm:ss",
t: "HH:mm",
T: "HH:mm:ss",
s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss",
u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'"
},
dateTimeFormats: {
full: "{1} 'à' {0}",
long: "{1} 'à' {0}",
medium: "{1} 'à' {0}",
short: "{1} {0}",
availableFormats: {
Bh: "h B",
Bhm: "h:mm B",
Bhms: "h:mm:ss B",
d: "d",
E: "E",
EBhm: "E h:mm B",
EBhms: "E h:mm:ss B",
Ed: "E d",
Ehm: "E h:mm a",
EHm: "E HH:mm",
Ehms: "E h:mm:ss a",
EHms: "E HH:mm:ss",
Gy: "y G",
GyMMM: "MMM y G",
GyMMMd: "d MMM y G",
GyMMMEd: "E d MMM y G",
h: "h a",
H: "HH 'h'",
hm: "h:mm a",
Hm: "HH:mm",
hms: "h:mm:ss a",
Hms: "HH:mm:ss",
hmsv: "h:mm:ss a v",
Hmsv: "HH:mm:ss v",
hmv: "h:mm a v",
Hmv: "HH:mm v",
M: "L",
Md: "dd/MM",
MEd: "E dd/MM",
MMM: "LLL",
MMMd: "d MMM",
MMMEd: "E d MMM",
MMMMd: "d MMMM",
"MMMMW-count-one": "'semaine' W (MMMM)",
"MMMMW-count-other": "'semaine' W (MMMM)",
ms: "mm:ss",
y: "y",
yM: "MM/y",
yMd: "dd/MM/y",
yMEd: "E dd/MM/y",
yMMM: "MMM y",
yMMMd: "d MMM y",
yMMMEd: "E d MMM y",
yMMMM: "MMMM y",
yQQQ: "QQQ y",
yQQQQ: "QQQQ y",
"yw-count-one": "'semaine' w 'de' Y",
"yw-count-other": "'semaine' w 'de' Y"
}
},
timeFormats: {
full: "HH:mm:ss zzzz",
long: "HH:mm:ss z",
medium: "HH:mm:ss",
short: "HH:mm"
},
dateFormats: {
full: "EEEE d MMMM y",
long: "d MMMM y",
medium: "d MMM y",
short: "dd/MM/y"
},
days: {
format: {
abbreviated: [
"dim.",
"lun.",
"mar.",
"mer.",
"jeu.",
"ven.",
"sam."
],
narrow: [
"D",
"L",
"M",
"M",
"J",
"V",
"S"
],
short: [
"di",
"lu",
"ma",
"me",
"je",
"ve",
"sa"
],
wide: [
"dimanche",
"lundi",
"mardi",
"mercredi",
"jeudi",
"vendredi",
"samedi"
]
},
"stand-alone": {
abbreviated: [
"dim.",
"lun.",
"mar.",
"mer.",
"jeu.",
"ven.",
"sam."
],
narrow: [
"D",
"L",
"M",
"M",
"J",
"V",
"S"
],
short: [
"di",
"lu",
"ma",
"me",
"je",
"ve",
"sa"
],
wide: [
"dimanche",
"lundi",
"mardi",
"mercredi",
"jeudi",
"vendredi",
"samedi"
]
}
},
months: {
format: {
abbreviated: [
"janv.",
"févr.",
"mars",
"avr.",
"mai",
"juin",
"juil.",
"août",
"sept.",
"oct.",
"nov.",
"déc."
],
narrow: [
"J",
"F",
"M",
"A",
"M",
"J",
"J",
"A",
"S",
"O",
"N",
"D"
],
wide: [
"janvier",
"février",
"mars",
"avril",
"mai",
"juin",
"juillet",
"août",
"septembre",
"octobre",
"novembre",
"décembre"
]
},
"stand-alone": {
abbreviated: [
"janv.",
"févr.",
"mars",
"avr.",
"mai",
"juin",
"juil.",
"août",
"sept.",
"oct.",
"nov.",
"déc."
],
narrow: [
"J",
"F",
"M",
"A",
"M",
"J",
"J",
"A",
"S",
"O",
"N",
"D"
],
wide: [
"janvier",
"février",
"mars",
"avril",
"mai",
"juin",
"juillet",
"août",
"septembre",
"octobre",
"novembre",
"décembre"
]
}
},
quarters: {
format: {
abbreviated: [
"T1",
"T2",
"T3",
"T4"
],
narrow: [
"1",
"2",
"3",
"4"
],
wide: [
"1er trimestre",
"2e trimestre",
"3e trimestre",
"4e trimestre"
]
},
"stand-alone": {
abbreviated: [
"T1",
"T2",
"T3",
"T4"
],
narrow: [
"1",
"2",
"3",
"4"
],
wide: [
"1er trimestre",
"2e trimestre",
"3e trimestre",
"4e trimestre"
]
}
},
dayPeriods: {
format: {
abbreviated: {
midnight: "minuit",
am: "AM",
noon: "midi",
pm: "PM",
morning1: "mat.",
afternoon1: "ap.m.",
evening1: "soir",
night1: "nuit"
},
narrow: {
midnight: "minuit",
am: "AM",
noon: "midi",
pm: "PM",
morning1: "mat.",
afternoon1: "ap.m.",
evening1: "soir",
night1: "nuit"
},
wide: {
midnight: "minuit",
am: "AM",
noon: "midi",
pm: "PM",
morning1: "du matin",
afternoon1: "de l’après-midi",
evening1: "du soir",
night1: "du matin"
}
},
"stand-alone": {
abbreviated: {
midnight: "minuit",
am: "AM",
noon: "midi",
pm: "PM",
morning1: "mat.",
afternoon1: "ap.m.",
evening1: "soir",
night1: "nuit"
},
narrow: {
midnight: "minuit",
am: "AM",
noon: "midi",
pm: "PM",
morning1: "mat.",
afternoon1: "ap.m.",
evening1: "soir",
night1: "nuit"
},
wide: {
midnight: "minuit",
am: "AM",
noon: "midi",
pm: "PM",
morning1: "matin",
afternoon1: "après-midi",
evening1: "soir",
night1: "nuit"
}
}
},
eras: {
format: {
wide: {
"0": "avant Jésus-Christ",
"1": "après Jésus-Christ",
"0-alt-variant": "avant l’ère commune",
"1-alt-variant": "de l’ère commune"
},
abbreviated: {
"0": "av. J.-C.",
"1": "ap. J.-C.",
"0-alt-variant": "AEC",
"1-alt-variant": "EC"
},
narrow: {
"0": "av. J.-C.",
"1": "ap. J.-C.",
"0-alt-variant": "AEC",
"1-alt-variant": "EC"
}
}
},
gmtFormat: "UTC{0}",
gmtZeroFormat: "UTC",
dateFields: {
era: {
wide: "ère",
short: "ère",
narrow: "ère"
},
year: {
wide: "année",
short: "an",
narrow: "a"
},
quarter: {
wide: "trimestre",
short: "trim.",
narrow: "trim."
},
month: {
wide: "mois",
short: "m.",
narrow: "m."
},
week: {
wide: "semaine",
short: "sem.",
narrow: "sem."
},
weekOfMonth: {
wide: "semaine (mois)",
short: "sem. (m.)",
narrow: "sem. (m.)"
},
day: {
wide: "jour",
short: "j",
narrow: "j"
},
dayOfYear: {
wide: "jour (année)",
short: "j (an)",
narrow: "j (an)"
},
weekday: {
wide: "jour de la semaine",
short: "j (sem.)",
narrow: "j (sem.)"
},
weekdayOfMonth: {
wide: "jour (mois)",
short: "jour (mois)",
narrow: "jour (mois)"
},
dayperiod: {
short: "cadran",
wide: "cadran",
narrow: "cadran"
},
hour: {
wide: "heure",
short: "h",
narrow: "h"
},
minute: {
wide: "minute",
short: "min",
narrow: "min"
},
second: {
wide: "seconde",
short: "s",
narrow: "s"
},
zone: {
wide: "fuseau horaire",
short: "fuseau horaire",
narrow: "fuseau horaire"
}
}
},
firstDay: 1,
weekendRange: {
start: 6,
end: 0
},
likelySubtags: {
fr: "fr-Latn-FR"
},
currencyData: {
BIF: {
_rounding: "0",
_digits: "0"
}
}
};
export default data;
|
import React, { useContext, useState, useEffect } from "react";
import { ChartContext } from "../../../../context/chartContext";
import Dropdown from "../../TabGeral/components/dropdown/dropdown";
import OverlapWrapper from "../../../../components/chartWrapper/overlapWrapper";
function LapDivision() {
const chartValues = useContext(ChartContext);
const [dataX, setDataX] = useState([]);
const [dataY, setDataY] = useState([]);
const [dataLap, setDataLap] = useState(null);
const [lapSelected, setLapSelected] = useState([]);
useEffect(() => {
setDataX(chartValues.data.map((d) => +d[chartValues.axisX.value]));
}, [chartValues.data, chartValues.axisX]);
useEffect(() => {
if (chartValues.axisY[0])
setDataY(chartValues.data.map((d) => +d[chartValues.axisY[0].column]));
}, [chartValues.data, chartValues.axisY]);
useEffect(() => {
let lapFlag = 0;
let contador = 0;
let index = [];
chartValues.data.map((d) => {
if (d.beacon === "1") {
if (!lapFlag) index.push(contador);
lapFlag = 1;
} else lapFlag = 0;
contador = contador + 1;
return 0;
});
setDataLap(index);
}, [chartValues.data]);
const getCheck = () => {
const laps = [];
for (let i = 0; i < dataLap.length - 1; i++) {
const id = `lap-${i+1}`;
const check = document.getElementById(id);
if (check.checked === true) {
laps.push(i);
}
}
setLapSelected(laps);
};
let cont = 0
const renderCheckboxVoltas = () => {
if (dataLap) {
return (
dataLap.map((laps, i) => {
if (i*3 < dataLap.length - 1) {
return (
<div className="checkbox-wrapper" key={`lap ${i}`}>
{dataLap.map((lap, index) => {
if (index < 3 && cont < dataLap.length - 1) {
cont++;
return (
<div key={`${i} lap`}>
<input type="checkbox"
className="laps-checkbox"
name="laps"
id={"lap-" + cont}
value={"lap-" + cont}
onClick={getCheck}
/>
<label className="label-lap" htmlFor={"lap-" + cont}>Volta {cont}</label>
</div>
);
}
else return 0;
})}
</div>
);
}
else return 0;
})
);
}
else return 0;
};
const renderOverLapChart = () => {
if (dataX && chartValues.axisY && dataLap) {
return (
<OverlapWrapper
dataX={dataX}
dataY={dataY}
lapSelected={lapSelected}
lapIndex={dataLap}
/>
);
}
};
return (
<div key="lap Division">
<form>
<Dropdown
data={chartValues.data}
label="Eixo X"
name="axis-X"
selectedAxis={(value) => chartValues.setAxisX(value)}
defaultValue={{ value: "timer", label: "Timer" }}
/>
<Dropdown
data={chartValues.data}
label="Eixo Y"
name="axis-Y"
selectedAxis={(value) => chartValues.setAxisY(value)}
defaultValue={chartValues.axisY.map((axis) => {
return { value: axis.column, label: axis.column };
})}
/>
</form>
<div className="inputs-container">{renderCheckboxVoltas()}</div>
<div className="overlap-area">{renderOverLapChart()}</div>
</div>
);
}
export default LapDivision;
|
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
(function (process,global){
'use strict';
/* eslint no-unused-vars: off */
/* eslint-env commonjs */
/**
* Shim process.stdout.
*/
process.stdout = require('browser-stdout')();
var Mocha = require('./lib/mocha');
/**
* Create a Mocha instance.
*
* @return {undefined}
*/
var mocha = new Mocha({ reporter: 'html' });
/**
* Save timer references to avoid Sinon interfering (see GH-237).
*/
var Date = global.Date;
var setTimeout = global.setTimeout;
var setInterval = global.setInterval;
var clearTimeout = global.clearTimeout;
var clearInterval = global.clearInterval;
var uncaughtExceptionHandlers = [];
var originalOnerrorHandler = global.onerror;
/**
* Remove uncaughtException listener.
* Revert to original onerror handler if previously defined.
*/
process.removeListener = function (e, fn) {
if (e === 'uncaughtException') {
if (originalOnerrorHandler) {
global.onerror = originalOnerrorHandler;
} else {
global.onerror = function () {};
}
var i = Mocha.utils.indexOf(uncaughtExceptionHandlers, fn);
if (i !== -1) {
uncaughtExceptionHandlers.splice(i, 1);
}
}
};
/**
* Implements uncaughtException listener.
*/
process.on = function (e, fn) {
if (e === 'uncaughtException') {
global.onerror = function (err, url, line) {
fn(new Error(err + ' (' + url + ':' + line + ')'));
return !mocha.allowUncaught;
};
uncaughtExceptionHandlers.push(fn);
}
};
// The BDD UI is registered by default, but no UI will be functional in the
// browser without an explicit call to the overridden `mocha.ui` (see below).
// Ensure that this default UI does not expose its methods to the global scope.
mocha.suite.removeAllListeners('pre-require');
var immediateQueue = [];
var immediateTimeout;
function timeslice () {
var immediateStart = new Date().getTime();
while (immediateQueue.length && (new Date().getTime() - immediateStart) < 100) {
immediateQueue.shift()();
}
if (immediateQueue.length) {
immediateTimeout = setTimeout(timeslice, 0);
} else {
immediateTimeout = null;
}
}
/**
* High-performance override of Runner.immediately.
*/
Mocha.Runner.immediately = function (callback) {
immediateQueue.push(callback);
if (!immediateTimeout) {
immediateTimeout = setTimeout(timeslice, 0);
}
};
/**
* Function to allow assertion libraries to throw errors directly into mocha.
* This is useful when running tests in a browser because window.onerror will
* only receive the 'message' attribute of the Error.
*/
mocha.throwError = function (err) {
Mocha.utils.forEach(uncaughtExceptionHandlers, function (fn) {
fn(err);
});
throw err;
};
/**
* Override ui to ensure that the ui functions are initialized.
* Normally this would happen in Mocha.prototype.loadFiles.
*/
mocha.ui = function (ui) {
Mocha.prototype.ui.call(this, ui);
this.suite.emit('pre-require', global, null, this);
return this;
};
/**
* Setup mocha with the given setting options.
*/
mocha.setup = function (opts) {
if (typeof opts === 'string') {
opts = { ui: opts };
}
for (var opt in opts) {
if (opts.hasOwnProperty(opt)) {
this[opt](opts[opt]);
}
}
return this;
};
/**
* Run mocha, returning the Runner.
*/
mocha.run = function (fn) {
var options = mocha.options;
mocha.globals('location');
var query = Mocha.utils.parseQuery(global.location.search || '');
if (query.grep) {
mocha.grep(query.grep);
}
if (query.fgrep) {
mocha.fgrep(query.fgrep);
}
if (query.invert) {
mocha.invert();
}
return Mocha.prototype.run.call(mocha, function (err) {
// The DOM Document is not available in Web Workers.
var document = global.document;
if (document && document.getElementById('mocha') && options.noHighlighting !== true) {
Mocha.utils.highlightTags('code');
}
if (fn) {
fn(err);
}
});
};
/**
* Expose the process shim.
* https://github.com/mochajs/mocha/pull/916
*/
Mocha.process = process;
/**
* Expose mocha.
*/
global.Mocha = Mocha;
global.mocha = mocha;
// this allows test/acceptance/required-tokens.js to pass; thus,
// you can now do `const describe = require('mocha').describe` in a
// browser context (assuming browserification). should fix #880
module.exports = global;
}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./lib/mocha":14,"_process":67,"browser-stdout":41}],2:[function(require,module,exports){
'use strict';
function noop () {}
module.exports = function () {
return noop;
};
},{}],3:[function(require,module,exports){
'use strict';
/**
* Module exports.
*/
exports.EventEmitter = EventEmitter;
/**
* Object#toString reference.
*/
var objToString = Object.prototype.toString;
/**
* Check if a value is an array.
*
* @api private
* @param {*} val The value to test.
* @return {boolean} true if the value is an array, otherwise false.
*/
function isArray (val) {
return objToString.call(val) === '[object Array]';
}
/**
* Event emitter constructor.
*
* @api public
*/
function EventEmitter () {}
/**
* Add a listener.
*
* @api public
* @param {string} name Event name.
* @param {Function} fn Event handler.
* @return {EventEmitter} Emitter instance.
*/
EventEmitter.prototype.on = function (name, fn) {
if (!this.$events) {
this.$events = {};
}
if (!this.$events[name]) {
this.$events[name] = fn;
} else if (isArray(this.$events[name])) {
this.$events[name].push(fn);
} else {
this.$events[name] = [this.$events[name], fn];
}
return this;
};
EventEmitter.prototype.addListener = EventEmitter.prototype.on;
/**
* Adds a volatile listener.
*
* @api public
* @param {string} name Event name.
* @param {Function} fn Event handler.
* @return {EventEmitter} Emitter instance.
*/
EventEmitter.prototype.once = function (name, fn) {
var self = this;
function on () {
self.removeListener(name, on);
fn.apply(this, arguments);
}
on.listener = fn;
this.on(name, on);
return this;
};
/**
* Remove a listener.
*
* @api public
* @param {string} name Event name.
* @param {Function} fn Event handler.
* @return {EventEmitter} Emitter instance.
*/
EventEmitter.prototype.removeListener = function (name, fn) {
if (this.$events && this.$events[name]) {
var list = this.$events[name];
if (isArray(list)) {
var pos = -1;
for (var i = 0, l = list.length; i < l; i++) {
if (list[i] === fn || (list[i].listener && list[i].listener === fn)) {
pos = i;
break;
}
}
if (pos < 0) {
return this;
}
list.splice(pos, 1);
if (!list.length) {
delete this.$events[name];
}
} else if (list === fn || (list.listener && list.listener === fn)) {
delete this.$events[name];
}
}
return this;
};
/**
* Remove all listeners for an event.
*
* @api public
* @param {string} name Event name.
* @return {EventEmitter} Emitter instance.
*/
EventEmitter.prototype.removeAllListeners = function (name) {
if (name === undefined) {
this.$events = {};
return this;
}
if (this.$events && this.$events[name]) {
this.$events[name] = null;
}
return this;
};
/**
* Get all listeners for a given event.
*
* @api public
* @param {string} name Event name.
* @return {EventEmitter} Emitter instance.
*/
EventEmitter.prototype.listeners = function (name) {
if (!this.$events) {
this.$events = {};
}
if (!this.$events[name]) {
this.$events[name] = [];
}
if (!isArray(this.$events[name])) {
this.$events[name] = [this.$events[name]];
}
return this.$events[name];
};
/**
* Emit an event.
*
* @api public
* @param {string} name Event name.
* @return {boolean} true if at least one handler was invoked, else false.
*/
EventEmitter.prototype.emit = function (name) {
if (!this.$events) {
return false;
}
var handler = this.$events[name];
if (!handler) {
return false;
}
var args = Array.prototype.slice.call(arguments, 1);
if (typeof handler === 'function') {
handler.apply(this, args);
} else if (isArray(handler)) {
var listeners = handler.slice();
for (var i = 0, l = listeners.length; i < l; i++) {
listeners[i].apply(this, args);
}
} else {
return false;
}
return true;
};
},{}],4:[function(require,module,exports){
'use strict';
/**
* Expose `Progress`.
*/
module.exports = Progress;
/**
* Initialize a new `Progress` indicator.
*/
function Progress () {
this.percent = 0;
this.size(0);
this.fontSize(11);
this.font('helvetica, arial, sans-serif');
}
/**
* Set progress size to `size`.
*
* @api public
* @param {number} size
* @return {Progress} Progress instance.
*/
Progress.prototype.size = function (size) {
this._size = size;
return this;
};
/**
* Set text to `text`.
*
* @api public
* @param {string} text
* @return {Progress} Progress instance.
*/
Progress.prototype.text = function (text) {
this._text = text;
return this;
};
/**
* Set font size to `size`.
*
* @api public
* @param {number} size
* @return {Progress} Progress instance.
*/
Progress.prototype.fontSize = function (size) {
this._fontSize = size;
return this;
};
/**
* Set font to `family`.
*
* @param {string} family
* @return {Progress} Progress instance.
*/
Progress.prototype.font = function (family) {
this._font = family;
return this;
};
/**
* Update percentage to `n`.
*
* @param {number} n
* @return {Progress} Progress instance.
*/
Progress.prototype.update = function (n) {
this.percent = n;
return this;
};
/**
* Draw on `ctx`.
*
* @param {CanvasRenderingContext2d} ctx
* @return {Progress} Progress instance.
*/
Progress.prototype.draw = function (ctx) {
try {
var percent = Math.min(this.percent, 100);
var size = this._size;
var half = size / 2;
var x = half;
var y = half;
var rad = half - 1;
var fontSize = this._fontSize;
ctx.font = fontSize + 'px ' + this._font;
var angle = Math.PI * 2 * (percent / 100);
ctx.clearRect(0, 0, size, size);
// outer circle
ctx.strokeStyle = '#9f9f9f';
ctx.beginPath();
ctx.arc(x, y, rad, 0, angle, false);
ctx.stroke();
// inner circle
ctx.strokeStyle = '#eee';
ctx.beginPath();
ctx.arc(x, y, rad - 1, 0, angle, true);
ctx.stroke();
// text
var text = this._text || (percent | 0) + '%';
var w = ctx.measureText(text).width;
ctx.fillText(text, x - w / 2 + 1, y + fontSize / 2 - 1);
} catch (err) {
// don't fail if we can't render progress
}
return this;
};
},{}],5:[function(require,module,exports){
(function (global){
'use strict';
exports.isatty = function isatty () {
return true;
};
exports.getWindowSize = function getWindowSize () {
if ('innerHeight' in global) {
return [global.innerHeight, global.innerWidth];
}
// In a Web Worker, the DOM Window is not available.
return [640, 480];
};
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],6:[function(require,module,exports){
'use strict';
/**
* Module dependencies.
*/
var JSON = require('json3');
/**
* Expose `Context`.
*/
module.exports = Context;
/**
* Initialize a new `Context`.
*
* @api private
*/
function Context () {}
/**
* Set or get the context `Runnable` to `runnable`.
*
* @api private
* @param {Runnable} runnable
* @return {Context}
*/
Context.prototype.runnable = function (runnable) {
if (!arguments.length) {
return this._runnable;
}
this.test = this._runnable = runnable;
return this;
};
/**
* Set test timeout `ms`.
*
* @api private
* @param {number} ms
* @return {Context} self
*/
Context.prototype.timeout = function (ms) {
if (!arguments.length) {
return this.runnable().timeout();
}
this.runnable().timeout(ms);
return this;
};
/**
* Set test timeout `enabled`.
*
* @api private
* @param {boolean} enabled
* @return {Context} self
*/
Context.prototype.enableTimeouts = function (enabled) {
this.runnable().enableTimeouts(enabled);
return this;
};
/**
* Set test slowness threshold `ms`.
*
* @api private
* @param {number} ms
* @return {Context} self
*/
Context.prototype.slow = function (ms) {
this.runnable().slow(ms);
return this;
};
/**
* Mark a test as skipped.
*
* @api private
* @return {Context} self
*/
Context.prototype.skip = function () {
this.runnable().skip();
return this;
};
/**
* Allow a number of retries on failed tests
*
* @api private
* @param {number} n
* @return {Context} self
*/
Context.prototype.retries = function (n) {
if (!arguments.length) {
return this.runnable().retries();
}
this.runnable().retries(n);
return this;
};
/**
* Inspect the context void of `._runnable`.
*
* @api private
* @return {string}
*/
Context.prototype.inspect = function () {
return JSON.stringify(this, function (key, val) {
return key === 'runnable' || key === 'test' ? undefined : val;
}, 2);
};
},{"json3":54}],7:[function(require,module,exports){
'use strict';
/**
* Module dependencies.
*/
var Runnable = require('./runnable');
var inherits = require('./utils').inherits;
/**
* Expose `Hook`.
*/
module.exports = Hook;
/**
* Initialize a new `Hook` with the given `title` and callback `fn`.
*
* @param {String} title
* @param {Function} fn
* @api private
*/
function Hook (title, fn) {
Runnable.call(this, title, fn);
this.type = 'hook';
}
/**
* Inherit from `Runnable.prototype`.
*/
inherits(Hook, Runnable);
/**
* Get or set the test `err`.
*
* @param {Error} err
* @return {Error}
* @api public
*/
Hook.prototype.error = function (err) {
if (!arguments.length) {
err = this._error;
this._error = null;
return err;
}
this._error = err;
};
},{"./runnable":33,"./utils":38}],8:[function(require,module,exports){
'use strict';
/**
* Module dependencies.
*/
var Test = require('../test');
/**
* BDD-style interface:
*
* describe('Array', function() {
* describe('#indexOf()', function() {
* it('should return -1 when not present', function() {
* // ...
* });
*
* it('should return the index when present', function() {
* // ...
* });
* });
* });
*
* @param {Suite} suite Root suite.
*/
module.exports = function (suite) {
var suites = [suite];
suite.on('pre-require', function (context, file, mocha) {
var common = require('./common')(suites, context, mocha);
context.before = common.before;
context.after = common.after;
context.beforeEach = common.beforeEach;
context.afterEach = common.afterEach;
context.run = mocha.options.delay && common.runWithSuite(suite);
/**
* Describe a "suite" with the given `title`
* and callback `fn` containing nested suites
* and/or tests.
*/
context.describe = context.context = function (title, fn) {
return common.suite.create({
title: title,
file: file,
fn: fn
});
};
/**
* Pending describe.
*/
context.xdescribe = context.xcontext = context.describe.skip = function (title, fn) {
return common.suite.skip({
title: title,
file: file,
fn: fn
});
};
/**
* Exclusive suite.
*/
context.describe.only = function (title, fn) {
return common.suite.only({
title: title,
file: file,
fn: fn
});
};
/**
* Describe a specification or test-case
* with the given `title` and callback `fn`
* acting as a thunk.
*/
context.it = context.specify = function (title, fn) {
var suite = suites[0];
if (suite.isPending()) {
fn = null;
}
var test = new Test(title, fn);
test.file = file;
suite.addTest(test);
return test;
};
/**
* Exclusive test-case.
*/
context.it.only = function (title, fn) {
return common.test.only(mocha, context.it(title, fn));
};
/**
* Pending test case.
*/
context.xit = context.xspecify = context.it.skip = function (title) {
context.it(title);
};
/**
* Number of attempts to retry.
*/
context.it.retries = function (n) {
context.retries(n);
};
});
};
},{"../test":36,"./common":9}],9:[function(require,module,exports){
'use strict';
var Suite = require('../suite');
/**
* Functions common to more than one interface.
*
* @param {Suite[]} suites
* @param {Context} context
* @param {Mocha} mocha
* @return {Object} An object containing common functions.
*/
module.exports = function (suites, context, mocha) {
return {
/**
* This is only present if flag --delay is passed into Mocha. It triggers
* root suite execution.
*
* @param {Suite} suite The root suite.
* @return {Function} A function which runs the root suite
*/
runWithSuite: function runWithSuite (suite) {
return function run () {
suite.run();
};
},
/**
* Execute before running tests.
*
* @param {string} name
* @param {Function} fn
*/
before: function (name, fn) {
suites[0].beforeAll(name, fn);
},
/**
* Execute after running tests.
*
* @param {string} name
* @param {Function} fn
*/
after: function (name, fn) {
suites[0].afterAll(name, fn);
},
/**
* Execute before each test case.
*
* @param {string} name
* @param {Function} fn
*/
beforeEach: function (name, fn) {
suites[0].beforeEach(name, fn);
},
/**
* Execute after each test case.
*
* @param {string} name
* @param {Function} fn
*/
afterEach: function (name, fn) {
suites[0].afterEach(name, fn);
},
suite: {
/**
* Create an exclusive Suite; convenience function
* See docstring for create() below.
*
* @param {Object} opts
* @returns {Suite}
*/
only: function only (opts) {
mocha.options.hasOnly = true;
opts.isOnly = true;
return this.create(opts);
},
/**
* Create a Suite, but skip it; convenience function
* See docstring for create() below.
*
* @param {Object} opts
* @returns {Suite}
*/
skip: function skip (opts) {
opts.pending = true;
return this.create(opts);
},
/**
* Creates a suite.
* @param {Object} opts Options
* @param {string} opts.title Title of Suite
* @param {Function} [opts.fn] Suite Function (not always applicable)
* @param {boolean} [opts.pending] Is Suite pending?
* @param {string} [opts.file] Filepath where this Suite resides
* @param {boolean} [opts.isOnly] Is Suite exclusive?
* @returns {Suite}
*/
create: function create (opts) {
var suite = Suite.create(suites[0], opts.title);
suite.pending = Boolean(opts.pending);
suite.file = opts.file;
suites.unshift(suite);
if (opts.isOnly) {
suite.parent._onlySuites = suite.parent._onlySuites.concat(suite);
mocha.options.hasOnly = true;
}
if (typeof opts.fn === 'function') {
opts.fn.call(suite);
suites.shift();
} else if (typeof opts.fn === 'undefined' && !suite.pending) {
throw new Error('Suite "' + suite.fullTitle() + '" was defined but no callback was supplied. Supply a callback or explicitly skip the suite.');
}
return suite;
}
},
test: {
/**
* Exclusive test-case.
*
* @param {Object} mocha
* @param {Function} test
* @returns {*}
*/
only: function (mocha, test) {
test.parent._onlyTests = test.parent._onlyTests.concat(test);
mocha.options.hasOnly = true;
return test;
},
/**
* Pending test case.
*
* @param {string} title
*/
skip: function (title) {
context.test(title);
},
/**
* Number of retry attempts
*
* @param {number} n
*/
retries: function (n) {
context.retries(n);
}
}
};
};
},{"../suite":35}],10:[function(require,module,exports){
'use strict';
/**
* Module dependencies.
*/
var Suite = require('../suite');
var Test = require('../test');
/**
* Exports-style (as Node.js module) interface:
*
* exports.Array = {
* '#indexOf()': {
* 'should return -1 when the value is not present': function() {
*
* },
*
* 'should return the correct index when the value is present': function() {
*
* }
* }
* };
*
* @param {Suite} suite Root suite.
*/
module.exports = function (suite) {
var suites = [suite];
suite.on('require', visit);
function visit (obj, file) {
var suite;
for (var key in obj) {
if (typeof obj[key] === 'function') {
var fn = obj[key];
switch (key) {
case 'before':
suites[0].beforeAll(fn);
break;
case 'after':
suites[0].afterAll(fn);
break;
case 'beforeEach':
suites[0].beforeEach(fn);
break;
case 'afterEach':
suites[0].afterEach(fn);
break;
default:
var test = new Test(key, fn);
test.file = file;
suites[0].addTest(test);
}
} else {
suite = Suite.create(suites[0], key);
suites.unshift(suite);
visit(obj[key], file);
suites.shift();
}
}
}
};
},{"../suite":35,"../test":36}],11:[function(require,module,exports){
'use strict';
exports.bdd = require('./bdd');
exports.tdd = require('./tdd');
exports.qunit = require('./qunit');
exports.exports = require('./exports');
},{"./bdd":8,"./exports":10,"./qunit":12,"./tdd":13}],12:[function(require,module,exports){
'use strict';
/**
* Module dependencies.
*/
var Test = require('../test');
/**
* QUnit-style interface:
*
* suite('Array');
*
* test('#length', function() {
* var arr = [1,2,3];
* ok(arr.length == 3);
* });
*
* test('#indexOf()', function() {
* var arr = [1,2,3];
* ok(arr.indexOf(1) == 0);
* ok(arr.indexOf(2) == 1);
* ok(arr.indexOf(3) == 2);
* });
*
* suite('String');
*
* test('#length', function() {
* ok('foo'.length == 3);
* });
*
* @param {Suite} suite Root suite.
*/
module.exports = function (suite) {
var suites = [suite];
suite.on('pre-require', function (context, file, mocha) {
var common = require('./common')(suites, context, mocha);
context.before = common.before;
context.after = common.after;
context.beforeEach = common.beforeEach;
context.afterEach = common.afterEach;
context.run = mocha.options.delay && common.runWithSuite(suite);
/**
* Describe a "suite" with the given `title`.
*/
context.suite = function (title) {
if (suites.length > 1) {
suites.shift();
}
return common.suite.create({
title: title,
file: file,
fn: false
});
};
/**
* Exclusive Suite.
*/
context.suite.only = function (title) {
if (suites.length > 1) {
suites.shift();
}
return common.suite.only({
title: title,
file: file,
fn: false
});
};
/**
* Describe a specification or test-case
* with the given `title` and callback `fn`
* acting as a thunk.
*/
context.test = function (title, fn) {
var test = new Test(title, fn);
test.file = file;
suites[0].addTest(test);
return test;
};
/**
* Exclusive test-case.
*/
context.test.only = function (title, fn) {
return common.test.only(mocha, context.test(title, fn));
};
context.test.skip = common.test.skip;
context.test.retries = common.test.retries;
});
};
},{"../test":36,"./common":9}],13:[function(require,module,exports){
'use strict';
/**
* Module dependencies.
*/
var Test = require('../test');
/**
* TDD-style interface:
*
* suite('Array', function() {
* suite('#indexOf()', function() {
* suiteSetup(function() {
*
* });
*
* test('should return -1 when not present', function() {
*
* });
*
* test('should return the index when present', function() {
*
* });
*
* suiteTeardown(function() {
*
* });
* });
* });
*
* @param {Suite} suite Root suite.
*/
module.exports = function (suite) {
var suites = [suite];
suite.on('pre-require', function (context, file, mocha) {
var common = require('./common')(suites, context, mocha);
context.setup = common.beforeEach;
context.teardown = common.afterEach;
context.suiteSetup = common.before;
context.suiteTeardown = common.after;
context.run = mocha.options.delay && common.runWithSuite(suite);
/**
* Describe a "suite" with the given `title` and callback `fn` containing
* nested suites and/or tests.
*/
context.suite = function (title, fn) {
return common.suite.create({
title: title,
file: file,
fn: fn
});
};
/**
* Pending suite.
*/
context.suite.skip = function (title, fn) {
return common.suite.skip({
title: title,
file: file,
fn: fn
});
};
/**
* Exclusive test-case.
*/
context.suite.only = function (title, fn) {
return common.suite.only({
title: title,
file: file,
fn: fn
});
};
/**
* Describe a specification or test-case with the given `title` and
* callback `fn` acting as a thunk.
*/
context.test = function (title, fn) {
var suite = suites[0];
if (suite.isPending()) {
fn = null;
}
var test = new Test(title, fn);
test.file = file;
suite.addTest(test);
return test;
};
/**
* Exclusive test-case.
*/
context.test.only = function (title, fn) {
return common.test.only(mocha, context.test(title, fn));
};
context.test.skip = common.test.skip;
context.test.retries = common.test.retries;
});
};
},{"../test":36,"./common":9}],14:[function(require,module,exports){
(function (process,global,__dirname){
'use strict';
/*!
* mocha
* Copyright(c) 2011 TJ Holowaychuk <tj@vision-media.ca>
* MIT Licensed
*/
/**
* Module dependencies.
*/
var escapeRe = require('escape-string-regexp');
var path = require('path');
var reporters = require('./reporters');
var utils = require('./utils');
/**
* Expose `Mocha`.
*/
exports = module.exports = Mocha;
/**
* To require local UIs and reporters when running in node.
*/
if (!process.browser) {
var cwd = process.cwd();
module.paths.push(cwd, path.join(cwd, 'node_modules'));
}
/**
* Expose internals.
*/
exports.utils = utils;
exports.interfaces = require('./interfaces');
exports.reporters = reporters;
exports.Runnable = require('./runnable');
exports.Context = require('./context');
exports.Runner = require('./runner');
exports.Suite = require('./suite');
exports.Hook = require('./hook');
exports.Test = require('./test');
/**
* Return image `name` path.
*
* @api private
* @param {string} name
* @return {string}
*/
function image (name) {
return path.join(__dirname, '../images', name + '.png');
}
/**
* Set up mocha with `options`.
*
* Options:
*
* - `ui` name "bdd", "tdd", "exports" etc
* - `reporter` reporter instance, defaults to `mocha.reporters.spec`
* - `globals` array of accepted globals
* - `timeout` timeout in milliseconds
* - `retries` number of times to retry failed tests
* - `bail` bail on the first test failure
* - `slow` milliseconds to wait before considering a test slow
* - `ignoreLeaks` ignore global leaks
* - `fullTrace` display the full stack-trace on failing
* - `grep` string or regexp to filter tests with
*
* @param {Object} options
* @api public
*/
function Mocha (options) {
options = options || {};
this.files = [];
this.options = options;
if (options.grep) {
this.grep(new RegExp(options.grep));
}
if (options.fgrep) {
this.fgrep(options.fgrep);
}
this.suite = new exports.Suite('', new exports.Context());
this.ui(options.ui);
this.bail(options.bail);
this.reporter(options.reporter, options.reporterOptions);
if (typeof options.timeout !== 'undefined' && options.timeout !== null) {
this.timeout(options.timeout);
}
if (typeof options.retries !== 'undefined' && options.retries !== null) {
this.retries(options.retries);
}
this.useColors(options.useColors);
if (options.enableTimeouts !== null) {
this.enableTimeouts(options.enableTimeouts);
}
if (options.slow) {
this.slow(options.slow);
}
}
/**
* Enable or disable bailing on the first failure.
*
* @api public
* @param {boolean} [bail]
*/
Mocha.prototype.bail = function (bail) {
if (!arguments.length) {
bail = true;
}
this.suite.bail(bail);
return this;
};
/**
* Add test `file`.
*
* @api public
* @param {string} file
*/
Mocha.prototype.addFile = function (file) {
this.files.push(file);
return this;
};
/**
* Set reporter to `reporter`, defaults to "spec".
*
* @param {String|Function} reporter name or constructor
* @param {Object} reporterOptions optional options
* @api public
* @param {string|Function} reporter name or constructor
* @param {Object} reporterOptions optional options
*/
Mocha.prototype.reporter = function (reporter, reporterOptions) {
if (typeof reporter === 'function') {
this._reporter = reporter;
} else {
reporter = reporter || 'spec';
var _reporter;
// Try to load a built-in reporter.
if (reporters[reporter]) {
_reporter = reporters[reporter];
}
// Try to load reporters from process.cwd() and node_modules
if (!_reporter) {
try {
_reporter = require(reporter);
} catch (err) {
err.message.indexOf('Cannot find module') !== -1
? console.warn('"' + reporter + '" reporter not found')
: console.warn('"' + reporter + '" reporter blew up with error:\n' + err.stack);
}
}
if (!_reporter && reporter === 'teamcity') {
console.warn('The Teamcity reporter was moved to a package named ' +
'mocha-teamcity-reporter ' +
'(https://npmjs.org/package/mocha-teamcity-reporter).');
}
if (!_reporter) {
throw new Error('invalid reporter "' + reporter + '"');
}
this._reporter = _reporter;
}
this.options.reporterOptions = reporterOptions;
return this;
};
/**
* Set test UI `name`, defaults to "bdd".
*
* @api public
* @param {string} bdd
*/
Mocha.prototype.ui = function (name) {
name = name || 'bdd';
this._ui = exports.interfaces[name];
if (!this._ui) {
try {
this._ui = require(name);
} catch (err) {
throw new Error('invalid interface "' + name + '"');
}
}
this._ui = this._ui(this.suite);
this.suite.on('pre-require', function (context) {
exports.afterEach = context.afterEach || context.teardown;
exports.after = context.after || context.suiteTeardown;
exports.beforeEach = context.beforeEach || context.setup;
exports.before = context.before || context.suiteSetup;
exports.describe = context.describe || context.suite;
exports.it = context.it || context.test;
exports.setup = context.setup || context.beforeEach;
exports.suiteSetup = context.suiteSetup || context.before;
exports.suiteTeardown = context.suiteTeardown || context.after;
exports.suite = context.suite || context.describe;
exports.teardown = context.teardown || context.afterEach;
exports.test = context.test || context.it;
exports.run = context.run;
});
return this;
};
/**
* Load registered files.
*
* @api private
*/
Mocha.prototype.loadFiles = function (fn) {
var self = this;
var suite = this.suite;
this.files.forEach(function (file) {
file = path.resolve(file);
suite.emit('pre-require', global, file, self);
suite.emit('require', require(file), file, self);
suite.emit('post-require', global, file, self);
});
fn && fn();
};
/**
* Enable growl support.
*
* @api private
*/
Mocha.prototype._growl = function (runner, reporter) {
var notify = require('growl');
runner.on('end', function () {
var stats = reporter.stats;
if (stats.failures) {
var msg = stats.failures + ' of ' + runner.total + ' tests failed';
notify(msg, { name: 'mocha', title: 'Failed', image: image('error') });
} else {
notify(stats.passes + ' tests passed in ' + stats.duration + 'ms', {
name: 'mocha',
title: 'Passed',
image: image('ok')
});
}
});
};
/**
* Escape string and add it to grep as a regexp.
*
* @api public
* @param str
* @returns {Mocha}
*/
Mocha.prototype.fgrep = function (str) {
return this.grep(new RegExp(escapeRe(str)));
};
/**
* Add regexp to grep, if `re` is a string it is escaped.
*
* @param {RegExp|String} re
* @return {Mocha}
* @api public
* @param {RegExp|string} re
* @return {Mocha}
*/
Mocha.prototype.grep = function (re) {
if (utils.isString(re)) {
// extract args if it's regex-like, i.e: [string, pattern, flag]
var arg = re.match(/^\/(.*)\/(g|i|)$|.*/);
this.options.grep = new RegExp(arg[1] || arg[0], arg[2]);
} else {
this.options.grep = re;
}
return this;
};
/**
* Invert `.grep()` matches.
*
* @return {Mocha}
* @api public
*/
Mocha.prototype.invert = function () {
this.options.invert = true;
return this;
};
/**
* Ignore global leaks.
*
* @param {Boolean} ignore
* @return {Mocha}
* @api public
* @param {boolean} ignore
* @return {Mocha}
*/
Mocha.prototype.ignoreLeaks = function (ignore) {
this.options.ignoreLeaks = Boolean(ignore);
return this;
};
/**
* Enable global leak checking.
*
* @return {Mocha}
* @api public
*/
Mocha.prototype.checkLeaks = function () {
this.options.ignoreLeaks = false;
return this;
};
/**
* Display long stack-trace on failing
*
* @return {Mocha}
* @api public
*/
Mocha.prototype.fullTrace = function () {
this.options.fullStackTrace = true;
return this;
};
/**
* Enable growl support.
*
* @return {Mocha}
* @api public
*/
Mocha.prototype.growl = function () {
this.options.growl = true;
return this;
};
/**
* Ignore `globals` array or string.
*
* @param {Array|String} globals
* @return {Mocha}
* @api public
* @param {Array|string} globals
* @return {Mocha}
*/
Mocha.prototype.globals = function (globals) {
this.options.globals = (this.options.globals || []).concat(globals);
return this;
};
/**
* Emit color output.
*
* @param {Boolean} colors
* @return {Mocha}
* @api public
* @param {boolean} colors
* @return {Mocha}
*/
Mocha.prototype.useColors = function (colors) {
if (colors !== undefined) {
this.options.useColors = colors;
}
return this;
};
/**
* Use inline diffs rather than +/-.
*
* @param {Boolean} inlineDiffs
* @return {Mocha}
* @api public
* @param {boolean} inlineDiffs
* @return {Mocha}
*/
Mocha.prototype.useInlineDiffs = function (inlineDiffs) {
this.options.useInlineDiffs = inlineDiffs !== undefined && inlineDiffs;
return this;
};
/**
* Set the timeout in milliseconds.
*
* @param {Number} timeout
* @return {Mocha}
* @api public
* @param {number} timeout
* @return {Mocha}
*/
Mocha.prototype.timeout = function (timeout) {
this.suite.timeout(timeout);
return this;
};
/**
* Set the number of times to retry failed tests.
*
* @param {Number} retry times
* @return {Mocha}
* @api public
*/
Mocha.prototype.retries = function (n) {
this.suite.retries(n);
return this;
};
/**
* Set slowness threshold in milliseconds.
*
* @param {Number} slow
* @return {Mocha}
* @api public
* @param {number} slow
* @return {Mocha}
*/
Mocha.prototype.slow = function (slow) {
this.suite.slow(slow);
return this;
};
/**
* Enable timeouts.
*
* @param {Boolean} enabled
* @return {Mocha}
* @api public
* @param {boolean} enabled
* @return {Mocha}
*/
Mocha.prototype.enableTimeouts = function (enabled) {
this.suite.enableTimeouts(arguments.length && enabled !== undefined ? enabled : true);
return this;
};
/**
* Makes all tests async (accepting a callback)
*
* @return {Mocha}
* @api public
*/
Mocha.prototype.asyncOnly = function () {
this.options.asyncOnly = true;
return this;
};
/**
* Disable syntax highlighting (in browser).
*
* @api public
*/
Mocha.prototype.noHighlighting = function () {
this.options.noHighlighting = true;
return this;
};
/**
* Enable uncaught errors to propagate (in browser).
*
* @return {Mocha}
* @api public
*/
Mocha.prototype.allowUncaught = function () {
this.options.allowUncaught = true;
return this;
};
/**
* Delay root suite execution.
* @returns {Mocha}
*/
Mocha.prototype.delay = function delay () {
this.options.delay = true;
return this;
};
/**
* Run tests and invoke `fn()` when complete.
*
* @api public
* @param {Function} fn
* @return {Runner}
*/
Mocha.prototype.run = function (fn) {
if (this.files.length) {
this.loadFiles();
}
var suite = this.suite;
var options = this.options;
options.files = this.files;
var runner = new exports.Runner(suite, options.delay);
var reporter = new this._reporter(runner, options);
runner.ignoreLeaks = options.ignoreLeaks !== false;
runner.fullStackTrace = options.fullStackTrace;
runner.hasOnly = options.hasOnly;
runner.asyncOnly = options.asyncOnly;
runner.allowUncaught = options.allowUncaught;
if (options.grep) {
runner.grep(options.grep, options.invert);
}
if (options.globals) {
runner.globals(options.globals);
}
if (options.growl) {
this._growl(runner, reporter);
}
if (options.useColors !== undefined) {
exports.reporters.Base.useColors = options.useColors;
}
exports.reporters.Base.inlineDiffs = options.useInlineDiffs;
function done (failures) {
if (reporter.done) {
reporter.done(failures, fn);
} else {
fn && fn(failures);
}
}
return runner.run(done);
};
}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},"/lib")
},{"./context":6,"./hook":7,"./interfaces":11,"./reporters":21,"./runnable":33,"./runner":34,"./suite":35,"./test":36,"./utils":38,"_process":67,"escape-string-regexp":47,"growl":49,"path":42}],15:[function(require,module,exports){
'use strict';
/**
* Helpers.
*/
var s = 1000;
var m = s * 60;
var h = m * 60;
var d = h * 24;
var y = d * 365.25;
/**
* Parse or format the given `val`.
*
* Options:
*
* - `long` verbose formatting [false]
*
* @api public
* @param {string|number} val
* @param {Object} options
* @return {string|number}
*/
module.exports = function (val, options) {
options = options || {};
if (typeof val === 'string') {
return parse(val);
}
// https://github.com/mochajs/mocha/pull/1035
return options['long'] ? longFormat(val) : shortFormat(val);
};
/**
* Parse the given `str` and return milliseconds.
*
* @api private
* @param {string} str
* @return {number}
*/
function parse (str) {
var match = (/^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i).exec(str);
if (!match) {
return;
}
var n = parseFloat(match[1]);
var type = (match[2] || 'ms').toLowerCase();
switch (type) {
case 'years':
case 'year':
case 'y':
return n * y;
case 'days':
case 'day':
case 'd':
return n * d;
case 'hours':
case 'hour':
case 'h':
return n * h;
case 'minutes':
case 'minute':
case 'm':
return n * m;
case 'seconds':
case 'second':
case 's':
return n * s;
case 'ms':
return n;
default:
// No default case
}
}
/**
* Short format for `ms`.
*
* @api private
* @param {number} ms
* @return {string}
*/
function shortFormat (ms) {
if (ms >= d) {
return Math.round(ms / d) + 'd';
}
if (ms >= h) {
return Math.round(ms / h) + 'h';
}
if (ms >= m) {
return Math.round(ms / m) + 'm';
}
if (ms >= s) {
return Math.round(ms / s) + 's';
}
return ms + 'ms';
}
/**
* Long format for `ms`.
*
* @api private
* @param {number} ms
* @return {string}
*/
function longFormat (ms) {
return plural(ms, d, 'day') ||
plural(ms, h, 'hour') ||
plural(ms, m, 'minute') ||
plural(ms, s, 'second') ||
ms + ' ms';
}
/**
* Pluralization helper.
*
* @api private
* @param {number} ms
* @param {number} n
* @param {string} name
*/
function plural (ms, n, name) {
if (ms < n) {
return;
}
if (ms < n * 1.5) {
return Math.floor(ms / n) + ' ' + name;
}
return Math.ceil(ms / n) + ' ' + name + 's';
}
},{}],16:[function(require,module,exports){
'use strict';
/**
* Expose `Pending`.
*/
module.exports = Pending;
/**
* Initialize a new `Pending` error with the given message.
*
* @param {string} message
*/
function Pending (message) {
this.message = message;
}
},{}],17:[function(require,module,exports){
(function (process,global){
'use strict';
/**
* Module dependencies.
*/
var tty = require('tty');
var diff = require('diff');
var ms = require('../ms');
var utils = require('../utils');
var supportsColor = process.browser ? null : require('supports-color');
/**
* Expose `Base`.
*/
exports = module.exports = Base;
/**
* Save timer references to avoid Sinon interfering.
* See: https://github.com/mochajs/mocha/issues/237
*/
/* eslint-disable no-unused-vars, no-native-reassign */
var Date = global.Date;
var setTimeout = global.setTimeout;
var setInterval = global.setInterval;
var clearTimeout = global.clearTimeout;
var clearInterval = global.clearInterval;
/* eslint-enable no-unused-vars, no-native-reassign */
/**
* Check if both stdio streams are associated with a tty.
*/
var isatty = tty.isatty(1) && tty.isatty(2);
/**
* Enable coloring by default, except in the browser interface.
*/
exports.useColors = !process.browser && (supportsColor || (process.env.MOCHA_COLORS !== undefined));
/**
* Inline diffs instead of +/-
*/
exports.inlineDiffs = false;
/**
* Default color map.
*/
exports.colors = {
pass: 90,
fail: 31,
'bright pass': 92,
'bright fail': 91,
'bright yellow': 93,
pending: 36,
suite: 0,
'error title': 0,
'error message': 31,
'error stack': 90,
checkmark: 32,
fast: 90,
medium: 33,
slow: 31,
green: 32,
light: 90,
'diff gutter': 90,
'diff added': 32,
'diff removed': 31
};
/**
* Default symbol map.
*/
exports.symbols = {
ok: '✓',
err: '✖',
dot: '․',
comma: ',',
bang: '!'
};
// With node.js on Windows: use symbols available in terminal default fonts
if (process.platform === 'win32') {
exports.symbols.ok = '\u221A';
exports.symbols.err = '\u00D7';
exports.symbols.dot = '.';
}
/**
* Color `str` with the given `type`,
* allowing colors to be disabled,
* as well as user-defined color
* schemes.
*
* @param {string} type
* @param {string} str
* @return {string}
* @api private
*/
var color = exports.color = function (type, str) {
if (!exports.useColors) {
return String(str);
}
return '\u001b[' + exports.colors[type] + 'm' + str + '\u001b[0m';
};
/**
* Expose term window size, with some defaults for when stderr is not a tty.
*/
exports.window = {
width: 75
};
if (isatty) {
exports.window.width = process.stdout.getWindowSize
? process.stdout.getWindowSize(1)[0]
: tty.getWindowSize()[1];
}
/**
* Expose some basic cursor interactions that are common among reporters.
*/
exports.cursor = {
hide: function () {
isatty && process.stdout.write('\u001b[?25l');
},
show: function () {
isatty && process.stdout.write('\u001b[?25h');
},
deleteLine: function () {
isatty && process.stdout.write('\u001b[2K');
},
beginningOfLine: function () {
isatty && process.stdout.write('\u001b[0G');
},
CR: function () {
if (isatty) {
exports.cursor.deleteLine();
exports.cursor.beginningOfLine();
} else {
process.stdout.write('\r');
}
}
};
/**
* Outut the given `failures` as a list.
*
* @param {Array} failures
* @api public
*/
exports.list = function (failures) {
console.log();
failures.forEach(function (test, i) {
// format
var fmt = color('error title', ' %s) %s:\n') +
color('error message', ' %s') +
color('error stack', '\n%s\n');
// msg
var msg;
var err = test.err;
var message;
if (err.message && typeof err.message.toString === 'function') {
message = err.message + '';
} else if (typeof err.inspect === 'function') {
message = err.inspect() + '';
} else {
message = '';
}
var stack = err.stack || message;
var index = message ? stack.indexOf(message) : -1;
var actual = err.actual;
var expected = err.expected;
var escape = true;
if (index === -1) {
msg = message;
} else {
index += message.length;
msg = stack.slice(0, index);
// remove msg from stack
stack = stack.slice(index + 1);
}
// uncaught
if (err.uncaught) {
msg = 'Uncaught ' + msg;
}
// explicitly show diff
if (err.showDiff !== false && sameType(actual, expected) && expected !== undefined) {
escape = false;
if (!(utils.isString(actual) && utils.isString(expected))) {
err.actual = actual = utils.stringify(actual);
err.expected = expected = utils.stringify(expected);
}
fmt = color('error title', ' %s) %s:\n%s') + color('error stack', '\n%s\n');
var match = message.match(/^([^:]+): expected/);
msg = '\n ' + color('error message', match ? match[1] : msg);
if (exports.inlineDiffs) {
msg += inlineDiff(err, escape);
} else {
msg += unifiedDiff(err, escape);
}
}
// indent stack trace
stack = stack.replace(/^/gm, ' ');
console.log(fmt, (i + 1), test.fullTitle(), msg, stack);
});
};
/**
* Initialize a new `Base` reporter.
*
* All other reporters generally
* inherit from this reporter, providing
* stats such as test duration, number
* of tests passed / failed etc.
*
* @param {Runner} runner
* @api public
*/
function Base (runner) {
var stats = this.stats = { suites: 0, tests: 0, passes: 0, pending: 0, failures: 0 };
var failures = this.failures = [];
if (!runner) {
return;
}
this.runner = runner;
runner.stats = stats;
runner.on('start', function () {
stats.start = new Date();
});
runner.on('suite', function (suite) {
stats.suites = stats.suites || 0;
suite.root || stats.suites++;
});
runner.on('test end', function () {
stats.tests = stats.tests || 0;
stats.tests++;
});
runner.on('pass', function (test) {
stats.passes = stats.passes || 0;
if (test.duration > test.slow()) {
test.speed = 'slow';
} else if (test.duration > test.slow() / 2) {
test.speed = 'medium';
} else {
test.speed = 'fast';
}
stats.passes++;
});
runner.on('fail', function (test, err) {
stats.failures = stats.failures || 0;
stats.failures++;
test.err = err;
failures.push(test);
});
runner.on('end', function () {
stats.end = new Date();
stats.duration = new Date() - stats.start;
});
runner.on('pending', function () {
stats.pending++;
});
}
/**
* Output common epilogue used by many of
* the bundled reporters.
*
* @api public
*/
Base.prototype.epilogue = function () {
var stats = this.stats;
var fmt;
console.log();
// passes
fmt = color('bright pass', ' ') +
color('green', ' %d passing') +
color('light', ' (%s)');
console.log(fmt,
stats.passes || 0,
ms(stats.duration));
// pending
if (stats.pending) {
fmt = color('pending', ' ') +
color('pending', ' %d pending');
console.log(fmt, stats.pending);
}
// failures
if (stats.failures) {
fmt = color('fail', ' %d failing');
console.log(fmt, stats.failures);
Base.list(this.failures);
console.log();
}
console.log();
};
/**
* Pad the given `str` to `len`.
*
* @api private
* @param {string} str
* @param {string} len
* @return {string}
*/
function pad (str, len) {
str = String(str);
return Array(len - str.length + 1).join(' ') + str;
}
/**
* Returns an inline diff between 2 strings with coloured ANSI output
*
* @api private
* @param {Error} err with actual/expected
* @param {boolean} escape
* @return {string} Diff
*/
function inlineDiff (err, escape) {
var msg = errorDiff(err, 'WordsWithSpace', escape);
// linenos
var lines = msg.split('\n');
if (lines.length > 4) {
var width = String(lines.length).length;
msg = lines.map(function (str, i) {
return pad(++i, width) + ' |' + ' ' + str;
}).join('\n');
}
// legend
msg = '\n' +
color('diff removed', 'actual') +
' ' +
color('diff added', 'expected') +
'\n\n' +
msg +
'\n';
// indent
msg = msg.replace(/^/gm, ' ');
return msg;
}
/**
* Returns a unified diff between two strings.
*
* @api private
* @param {Error} err with actual/expected
* @param {boolean} escape
* @return {string} The diff.
*/
function unifiedDiff (err, escape) {
var indent = ' ';
function cleanUp (line) {
if (escape) {
line = escapeInvisibles(line);
}
if (line[0] === '+') {
return indent + colorLines('diff added', line);
}
if (line[0] === '-') {
return indent + colorLines('diff removed', line);
}
if (line.match(/@@/)) {
return null;
}
if (line.match(/\\ No newline/)) {
return null;
}
return indent + line;
}
function notBlank (line) {
return typeof line !== 'undefined' && line !== null;
}
var msg = diff.createPatch('string', err.actual, err.expected);
var lines = msg.split('\n').splice(4);
return '\n ' +
colorLines('diff added', '+ expected') + ' ' +
colorLines('diff removed', '- actual') +
'\n\n' +
lines.map(cleanUp).filter(notBlank).join('\n');
}
/**
* Return a character diff for `err`.
*
* @api private
* @param {Error} err
* @param {string} type
* @param {boolean} escape
* @return {string}
*/
function errorDiff (err, type, escape) {
var actual = escape ? escapeInvisibles(err.actual) : err.actual;
var expected = escape ? escapeInvisibles(err.expected) : err.expected;
return diff['diff' + type](actual, expected).map(function (str) {
if (str.added) {
return colorLines('diff added', str.value);
}
if (str.removed) {
return colorLines('diff removed', str.value);
}
return str.value;
}).join('');
}
/**
* Returns a string with all invisible characters in plain text
*
* @api private
* @param {string} line
* @return {string}
*/
function escapeInvisibles (line) {
return line.replace(/\t/g, '<tab>')
.replace(/\r/g, '<CR>')
.replace(/\n/g, '<LF>\n');
}
/**
* Color lines for `str`, using the color `name`.
*
* @api private
* @param {string} name
* @param {string} str
* @return {string}
*/
function colorLines (name, str) {
return str.split('\n').map(function (str) {
return color(name, str);
}).join('\n');
}
/**
* Object#toString reference.
*/
var objToString = Object.prototype.toString;
/**
* Check that a / b have the same type.
*
* @api private
* @param {Object} a
* @param {Object} b
* @return {boolean}
*/
function sameType (a, b) {
return objToString.call(a) === objToString.call(b);
}
}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"../ms":15,"../utils":38,"_process":67,"diff":46,"supports-color":42,"tty":5}],18:[function(require,module,exports){
'use strict';
/**
* Module dependencies.
*/
var Base = require('./base');
var utils = require('../utils');
/**
* Expose `Doc`.
*/
exports = module.exports = Doc;
/**
* Initialize a new `Doc` reporter.
*
* @param {Runner} runner
* @api public
*/
function Doc (runner) {
Base.call(this, runner);
var indents = 2;
function indent () {
return Array(indents).join(' ');
}
runner.on('suite', function (suite) {
if (suite.root) {
return;
}
++indents;
console.log('%s<section class="suite">', indent());
++indents;
console.log('%s<h1>%s</h1>', indent(), utils.escape(suite.title));
console.log('%s<dl>', indent());
});
runner.on('suite end', function (suite) {
if (suite.root) {
return;
}
console.log('%s</dl>', indent());
--indents;
console.log('%s</section>', indent());
--indents;
});
runner.on('pass', function (test) {
console.log('%s <dt>%s</dt>', indent(), utils.escape(test.title));
var code = utils.escape(utils.clean(test.body));
console.log('%s <dd><pre><code>%s</code></pre></dd>', indent(), code);
});
runner.on('fail', function (test, err) {
console.log('%s <dt class="error">%s</dt>', indent(), utils.escape(test.title));
var code = utils.escape(utils.clean(test.body));
console.log('%s <dd class="error"><pre><code>%s</code></pre></dd>', indent(), code);
console.log('%s <dd class="error">%s</dd>', indent(), utils.escape(err));
});
}
},{"../utils":38,"./base":17}],19:[function(require,module,exports){
(function (process){
'use strict';
/**
* Module dependencies.
*/
var Base = require('./base');
var inherits = require('../utils').inherits;
var color = Base.color;
/**
* Expose `Dot`.
*/
exports = module.exports = Dot;
/**
* Initialize a new `Dot` matrix test reporter.
*
* @api public
* @param {Runner} runner
*/
function Dot (runner) {
Base.call(this, runner);
var self = this;
var width = Base.window.width * 0.75 | 0;
var n = -1;
runner.on('start', function () {
process.stdout.write('\n');
});
runner.on('pending', function () {
if (++n % width === 0) {
process.stdout.write('\n ');
}
process.stdout.write(color('pending', Base.symbols.comma));
});
runner.on('pass', function (test) {
if (++n % width === 0) {
process.stdout.write('\n ');
}
if (test.speed === 'slow') {
process.stdout.write(color('bright yellow', Base.symbols.dot));
} else {
process.stdout.write(color(test.speed, Base.symbols.dot));
}
});
runner.on('fail', function () {
if (++n % width === 0) {
process.stdout.write('\n ');
}
process.stdout.write(color('fail', Base.symbols.bang));
});
runner.on('end', function () {
console.log();
self.epilogue();
});
}
/**
* Inherit from `Base.prototype`.
*/
inherits(Dot, Base);
}).call(this,require('_process'))
},{"../utils":38,"./base":17,"_process":67}],20:[function(require,module,exports){
(function (global){
'use strict';
/* eslint-env browser */
/**
* Module dependencies.
*/
var Base = require('./base');
var utils = require('../utils');
var Progress = require('../browser/progress');
var escapeRe = require('escape-string-regexp');
var escape = utils.escape;
/**
* Save timer references to avoid Sinon interfering (see GH-237).
*/
/* eslint-disable no-unused-vars, no-native-reassign */
var Date = global.Date;
var setTimeout = global.setTimeout;
var setInterval = global.setInterval;
var clearTimeout = global.clearTimeout;
var clearInterval = global.clearInterval;
/* eslint-enable no-unused-vars, no-native-reassign */
/**
* Expose `HTML`.
*/
exports = module.exports = HTML;
/**
* Stats template.
*/
var statsTemplate = '<ul id="mocha-stats">' +
'<li class="progress"><canvas width="40" height="40"></canvas></li>' +
'<li class="passes"><a href="javascript:void(0);">passes:</a> <em>0</em></li>' +
'<li class="failures"><a href="javascript:void(0);">failures:</a> <em>0</em></li>' +
'<li class="duration">duration: <em>0</em>s</li>' +
'</ul>';
/**
* Initialize a new `HTML` reporter.
*
* @api public
* @param {Runner} runner
*/
function HTML (runner) {
Base.call(this, runner);
var self = this;
var stats = this.stats;
var stat = fragment(statsTemplate);
var items = stat.getElementsByTagName('li');
var passes = items[1].getElementsByTagName('em')[0];
var passesLink = items[1].getElementsByTagName('a')[0];
var failures = items[2].getElementsByTagName('em')[0];
var failuresLink = items[2].getElementsByTagName('a')[0];
var duration = items[3].getElementsByTagName('em')[0];
var canvas = stat.getElementsByTagName('canvas')[0];
var report = fragment('<ul id="mocha-report"></ul>');
var stack = [report];
var progress;
var ctx;
var root = document.getElementById('mocha');
if (canvas.getContext) {
var ratio = window.devicePixelRatio || 1;
canvas.style.width = canvas.width;
canvas.style.height = canvas.height;
canvas.width *= ratio;
canvas.height *= ratio;
ctx = canvas.getContext('2d');
ctx.scale(ratio, ratio);
progress = new Progress();
}
if (!root) {
return error('#mocha div missing, add it to your document');
}
// pass toggle
on(passesLink, 'click', function (evt) {
evt.preventDefault();
unhide();
var name = (/pass/).test(report.className) ? '' : ' pass';
report.className = report.className.replace(/fail|pass/g, '') + name;
if (report.className.trim()) {
hideSuitesWithout('test pass');
}
});
// failure toggle
on(failuresLink, 'click', function (evt) {
evt.preventDefault();
unhide();
var name = (/fail/).test(report.className) ? '' : ' fail';
report.className = report.className.replace(/fail|pass/g, '') + name;
if (report.className.trim()) {
hideSuitesWithout('test fail');
}
});
root.appendChild(stat);
root.appendChild(report);
if (progress) {
progress.size(40);
}
runner.on('suite', function (suite) {
if (suite.root) {
return;
}
// suite
var url = self.suiteURL(suite);
var el = fragment('<li class="suite"><h1><a href="%s">%s</a></h1></li>', url, escape(suite.title));
// container
stack[0].appendChild(el);
stack.unshift(document.createElement('ul'));
el.appendChild(stack[0]);
});
runner.on('suite end', function (suite) {
if (suite.root) {
updateStats();
return;
}
stack.shift();
});
runner.on('pass', function (test) {
var url = self.testURL(test);
var markup = '<li class="test pass %e"><h2>%e<span class="duration">%ems</span> ' +
'<a href="%s" class="replay">‣</a></h2></li>';
var el = fragment(markup, test.speed, test.title, test.duration, url);
self.addCodeToggle(el, test.body);
appendToStack(el);
updateStats();
});
runner.on('fail', function (test) {
var el = fragment('<li class="test fail"><h2>%e <a href="%e" class="replay">‣</a></h2></li>',
test.title, self.testURL(test));
var stackString; // Note: Includes leading newline
var message = test.err.toString();
// <=IE7 stringifies to [Object Error]. Since it can be overloaded, we
// check for the result of the stringifying.
if (message === '[object Error]') {
message = test.err.message;
}
if (test.err.stack) {
var indexOfMessage = test.err.stack.indexOf(test.err.message);
if (indexOfMessage === -1) {
stackString = test.err.stack;
} else {
stackString = test.err.stack.substr(test.err.message.length + indexOfMessage);
}
} else if (test.err.sourceURL && test.err.line !== undefined) {
// Safari doesn't give you a stack. Let's at least provide a source line.
stackString = '\n(' + test.err.sourceURL + ':' + test.err.line + ')';
}
stackString = stackString || '';
if (test.err.htmlMessage && stackString) {
el.appendChild(fragment('<div class="html-error">%s\n<pre class="error">%e</pre></div>',
test.err.htmlMessage, stackString));
} else if (test.err.htmlMessage) {
el.appendChild(fragment('<div class="html-error">%s</div>', test.err.htmlMessage));
} else {
el.appendChild(fragment('<pre class="error">%e%e</pre>', message, stackString));
}
self.addCodeToggle(el, test.body);
appendToStack(el);
updateStats();
});
runner.on('pending', function (test) {
var el = fragment('<li class="test pass pending"><h2>%e</h2></li>', test.title);
appendToStack(el);
updateStats();
});
function appendToStack (el) {
// Don't call .appendChild if #mocha-report was already .shift()'ed off the stack.
if (stack[0]) {
stack[0].appendChild(el);
}
}
function updateStats () {
// TODO: add to stats
var percent = stats.tests / runner.total * 100 | 0;
if (progress) {
progress.update(percent).draw(ctx);
}
// update stats
var ms = new Date() - stats.start;
text(passes, stats.passes);
text(failures, stats.failures);
text(duration, (ms / 1000).toFixed(2));
}
}
/**
* Makes a URL, preserving querystring ("search") parameters.
*
* @param {string} s
* @return {string} A new URL.
*/
function makeUrl (s) {
var search = window.location.search;
// Remove previous grep query parameter if present
if (search) {
search = search.replace(/[?&]grep=[^&\s]*/g, '').replace(/^&/, '?');
}
return window.location.pathname + (search ? search + '&' : '?') + 'grep=' + encodeURIComponent(escapeRe(s));
}
/**
* Provide suite URL.
*
* @param {Object} [suite]
*/
HTML.prototype.suiteURL = function (suite) {
return makeUrl(suite.fullTitle());
};
/**
* Provide test URL.
*
* @param {Object} [test]
*/
HTML.prototype.testURL = function (test) {
return makeUrl(test.fullTitle());
};
/**
* Adds code toggle functionality for the provided test's list element.
*
* @param {HTMLLIElement} el
* @param {string} contents
*/
HTML.prototype.addCodeToggle = function (el, contents) {
var h2 = el.getElementsByTagName('h2')[0];
on(h2, 'click', function () {
pre.style.display = pre.style.display === 'none' ? 'block' : 'none';
});
var pre = fragment('<pre><code>%e</code></pre>', utils.clean(contents));
el.appendChild(pre);
pre.style.display = 'none';
};
/**
* Display error `msg`.
*
* @param {string} msg
*/
function error (msg) {
document.body.appendChild(fragment('<div id="mocha-error">%s</div>', msg));
}
/**
* Return a DOM fragment from `html`.
*
* @param {string} html
*/
function fragment (html) {
var args = arguments;
var div = document.createElement('div');
var i = 1;
div.innerHTML = html.replace(/%([se])/g, function (_, type) {
switch (type) {
case 's': return String(args[i++]);
case 'e': return escape(args[i++]);
// no default
}
});
return div.firstChild;
}
/**
* Check for suites that do not have elements
* with `classname`, and hide them.
*
* @param {text} classname
*/
function hideSuitesWithout (classname) {
var suites = document.getElementsByClassName('suite');
for (var i = 0; i < suites.length; i++) {
var els = suites[i].getElementsByClassName(classname);
if (!els.length) {
suites[i].className += ' hidden';
}
}
}
/**
* Unhide .hidden suites.
*/
function unhide () {
var els = document.getElementsByClassName('suite hidden');
for (var i = 0; i < els.length; ++i) {
els[i].className = els[i].className.replace('suite hidden', 'suite');
}
}
/**
* Set an element's text contents.
*
* @param {HTMLElement} el
* @param {string} contents
*/
function text (el, contents) {
if (el.textContent) {
el.textContent = contents;
} else {
el.innerText = contents;
}
}
/**
* Listen on `event` with callback `fn`.
*/
function on (el, event, fn) {
if (el.addEventListener) {
el.addEventListener(event, fn, false);
} else {
el.attachEvent('on' + event, fn);
}
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"../browser/progress":4,"../utils":38,"./base":17,"escape-string-regexp":47}],21:[function(require,module,exports){
'use strict';
// Alias exports to a their normalized format Mocha#reporter to prevent a need
// for dynamic (try/catch) requires, which Browserify doesn't handle.
exports.Base = exports.base = require('./base');
exports.Dot = exports.dot = require('./dot');
exports.Doc = exports.doc = require('./doc');
exports.TAP = exports.tap = require('./tap');
exports.JSON = exports.json = require('./json');
exports.HTML = exports.html = require('./html');
exports.List = exports.list = require('./list');
exports.Min = exports.min = require('./min');
exports.Spec = exports.spec = require('./spec');
exports.Nyan = exports.nyan = require('./nyan');
exports.XUnit = exports.xunit = require('./xunit');
exports.Markdown = exports.markdown = require('./markdown');
exports.Progress = exports.progress = require('./progress');
exports.Landing = exports.landing = require('./landing');
exports.JSONStream = exports['json-stream'] = require('./json-stream');
},{"./base":17,"./doc":18,"./dot":19,"./html":20,"./json":23,"./json-stream":22,"./landing":24,"./list":25,"./markdown":26,"./min":27,"./nyan":28,"./progress":29,"./spec":30,"./tap":31,"./xunit":32}],22:[function(require,module,exports){
(function (process){
'use strict';
/**
* Module dependencies.
*/
var Base = require('./base');
var JSON = require('json3');
/**
* Expose `List`.
*/
exports = module.exports = List;
/**
* Initialize a new `List` test reporter.
*
* @api public
* @param {Runner} runner
*/
function List (runner) {
Base.call(this, runner);
var self = this;
var total = runner.total;
runner.on('start', function () {
console.log(JSON.stringify(['start', { total: total }]));
});
runner.on('pass', function (test) {
console.log(JSON.stringify(['pass', clean(test)]));
});
runner.on('fail', function (test, err) {
test = clean(test);
test.err = err.message;
test.stack = err.stack || null;
console.log(JSON.stringify(['fail', test]));
});
runner.on('end', function () {
process.stdout.write(JSON.stringify(['end', self.stats]));
});
}
/**
* Return a plain-object representation of `test`
* free of cyclic properties etc.
*
* @api private
* @param {Object} test
* @return {Object}
*/
function clean (test) {
return {
title: test.title,
fullTitle: test.fullTitle(),
duration: test.duration,
currentRetry: test.currentRetry()
};
}
}).call(this,require('_process'))
},{"./base":17,"_process":67,"json3":54}],23:[function(require,module,exports){
(function (process){
'use strict';
/**
* Module dependencies.
*/
var Base = require('./base');
/**
* Expose `JSON`.
*/
exports = module.exports = JSONReporter;
/**
* Initialize a new `JSON` reporter.
*
* @api public
* @param {Runner} runner
*/
function JSONReporter (runner) {
Base.call(this, runner);
var self = this;
var tests = [];
var pending = [];
var failures = [];
var passes = [];
runner.on('test end', function (test) {
tests.push(test);
});
runner.on('pass', function (test) {
passes.push(test);
});
runner.on('fail', function (test) {
failures.push(test);
});
runner.on('pending', function (test) {
pending.push(test);
});
runner.on('end', function () {
var obj = {
stats: self.stats,
tests: tests.map(clean),
pending: pending.map(clean),
failures: failures.map(clean),
passes: passes.map(clean)
};
runner.testResults = obj;
process.stdout.write(JSON.stringify(obj, null, 2));
});
}
/**
* Return a plain-object representation of `test`
* free of cyclic properties etc.
*
* @api private
* @param {Object} test
* @return {Object}
*/
function clean (test) {
return {
title: test.title,
fullTitle: test.fullTitle(),
duration: test.duration,
currentRetry: test.currentRetry(),
err: errorJSON(test.err || {})
};
}
/**
* Transform `error` into a JSON object.
*
* @api private
* @param {Error} err
* @return {Object}
*/
function errorJSON (err) {
var res = {};
Object.getOwnPropertyNames(err).forEach(function (key) {
res[key] = err[key];
}, err);
return res;
}
}).call(this,require('_process'))
},{"./base":17,"_process":67}],24:[function(require,module,exports){
(function (process){
'use strict';
/**
* Module dependencies.
*/
var Base = require('./base');
var inherits = require('../utils').inherits;
var cursor = Base.cursor;
var color = Base.color;
/**
* Expose `Landing`.
*/
exports = module.exports = Landing;
/**
* Airplane color.
*/
Base.colors.plane = 0;
/**
* Airplane crash color.
*/
Base.colors['plane crash'] = 31;
/**
* Runway color.
*/
Base.colors.runway = 90;
/**
* Initialize a new `Landing` reporter.
*
* @api public
* @param {Runner} runner
*/
function Landing (runner) {
Base.call(this, runner);
var self = this;
var width = Base.window.width * 0.75 | 0;
var total = runner.total;
var stream = process.stdout;
var plane = color('plane', '✈');
var crashed = -1;
var n = 0;
function runway () {
var buf = Array(width).join('-');
return ' ' + color('runway', buf);
}
runner.on('start', function () {
stream.write('\n\n\n ');
cursor.hide();
});
runner.on('test end', function (test) {
// check if the plane crashed
var col = crashed === -1 ? width * ++n / total | 0 : crashed;
// show the crash
if (test.state === 'failed') {
plane = color('plane crash', '✈');
crashed = col;
}
// render landing strip
stream.write('\u001b[' + (width + 1) + 'D\u001b[2A');
stream.write(runway());
stream.write('\n ');
stream.write(color('runway', Array(col).join('⋅')));
stream.write(plane);
stream.write(color('runway', Array(width - col).join('⋅') + '\n'));
stream.write(runway());
stream.write('\u001b[0m');
});
runner.on('end', function () {
cursor.show();
console.log();
self.epilogue();
});
}
/**
* Inherit from `Base.prototype`.
*/
inherits(Landing, Base);
}).call(this,require('_process'))
},{"../utils":38,"./base":17,"_process":67}],25:[function(require,module,exports){
(function (process){
'use strict';
/**
* Module dependencies.
*/
var Base = require('./base');
var inherits = require('../utils').inherits;
var color = Base.color;
var cursor = Base.cursor;
/**
* Expose `List`.
*/
exports = module.exports = List;
/**
* Initialize a new `List` test reporter.
*
* @api public
* @param {Runner} runner
*/
function List (runner) {
Base.call(this, runner);
var self = this;
var n = 0;
runner.on('start', function () {
console.log();
});
runner.on('test', function (test) {
process.stdout.write(color('pass', ' ' + test.fullTitle() + ': '));
});
runner.on('pending', function (test) {
var fmt = color('checkmark', ' -') +
color('pending', ' %s');
console.log(fmt, test.fullTitle());
});
runner.on('pass', function (test) {
var fmt = color('checkmark', ' ' + Base.symbols.ok) +
color('pass', ' %s: ') +
color(test.speed, '%dms');
cursor.CR();
console.log(fmt, test.fullTitle(), test.duration);
});
runner.on('fail', function (test) {
cursor.CR();
console.log(color('fail', ' %d) %s'), ++n, test.fullTitle());
});
runner.on('end', self.epilogue.bind(self));
}
/**
* Inherit from `Base.prototype`.
*/
inherits(List, Base);
}).call(this,require('_process'))
},{"../utils":38,"./base":17,"_process":67}],26:[function(require,module,exports){
(function (process){
'use strict';
/**
* Module dependencies.
*/
var Base = require('./base');
var utils = require('../utils');
/**
* Constants
*/
var SUITE_PREFIX = '$';
/**
* Expose `Markdown`.
*/
exports = module.exports = Markdown;
/**
* Initialize a new `Markdown` reporter.
*
* @api public
* @param {Runner} runner
*/
function Markdown (runner) {
Base.call(this, runner);
var level = 0;
var buf = '';
function title (str) {
return Array(level).join('#') + ' ' + str;
}
function mapTOC (suite, obj) {
var ret = obj;
var key = SUITE_PREFIX + suite.title;
obj = obj[key] = obj[key] || { suite: suite };
suite.suites.forEach(function (suite) {
mapTOC(suite, obj);
});
return ret;
}
function stringifyTOC (obj, level) {
++level;
var buf = '';
var link;
for (var key in obj) {
if (key === 'suite') {
continue;
}
if (key !== SUITE_PREFIX) {
link = ' - [' + key.substring(1) + ']';
link += '(#' + utils.slug(obj[key].suite.fullTitle()) + ')\n';
buf += Array(level).join(' ') + link;
}
buf += stringifyTOC(obj[key], level);
}
return buf;
}
function generateTOC (suite) {
var obj = mapTOC(suite, {});
return stringifyTOC(obj, 0);
}
generateTOC(runner.suite);
runner.on('suite', function (suite) {
++level;
var slug = utils.slug(suite.fullTitle());
buf += '<a name="' + slug + '"></a>' + '\n';
buf += title(suite.title) + '\n';
});
runner.on('suite end', function () {
--level;
});
runner.on('pass', function (test) {
var code = utils.clean(test.body);
buf += test.title + '.\n';
buf += '\n```js\n';
buf += code + '\n';
buf += '```\n\n';
});
runner.on('end', function () {
process.stdout.write('# TOC\n');
process.stdout.write(generateTOC(runner.suite));
process.stdout.write(buf);
});
}
}).call(this,require('_process'))
},{"../utils":38,"./base":17,"_process":67}],27:[function(require,module,exports){
(function (process){
'use strict';
/**
* Module dependencies.
*/
var Base = require('./base');
var inherits = require('../utils').inherits;
/**
* Expose `Min`.
*/
exports = module.exports = Min;
/**
* Initialize a new `Min` minimal test reporter (best used with --watch).
*
* @api public
* @param {Runner} runner
*/
function Min (runner) {
Base.call(this, runner);
runner.on('start', function () {
// clear screen
process.stdout.write('\u001b[2J');
// set cursor position
process.stdout.write('\u001b[1;3H');
});
runner.on('end', this.epilogue.bind(this));
}
/**
* Inherit from `Base.prototype`.
*/
inherits(Min, Base);
}).call(this,require('_process'))
},{"../utils":38,"./base":17,"_process":67}],28:[function(require,module,exports){
(function (process){
'use strict';
/**
* Module dependencies.
*/
var Base = require('./base');
var inherits = require('../utils').inherits;
/**
* Expose `Dot`.
*/
exports = module.exports = NyanCat;
/**
* Initialize a new `Dot` matrix test reporter.
*
* @param {Runner} runner
* @api public
*/
function NyanCat (runner) {
Base.call(this, runner);
var self = this;
var width = Base.window.width * 0.75 | 0;
var nyanCatWidth = this.nyanCatWidth = 11;
this.colorIndex = 0;
this.numberOfLines = 4;
this.rainbowColors = self.generateColors();
this.scoreboardWidth = 5;
this.tick = 0;
this.trajectories = [[], [], [], []];
this.trajectoryWidthMax = (width - nyanCatWidth);
runner.on('start', function () {
Base.cursor.hide();
self.draw();
});
runner.on('pending', function () {
self.draw();
});
runner.on('pass', function () {
self.draw();
});
runner.on('fail', function () {
self.draw();
});
runner.on('end', function () {
Base.cursor.show();
for (var i = 0; i < self.numberOfLines; i++) {
write('\n');
}
self.epilogue();
});
}
/**
* Inherit from `Base.prototype`.
*/
inherits(NyanCat, Base);
/**
* Draw the nyan cat
*
* @api private
*/
NyanCat.prototype.draw = function () {
this.appendRainbow();
this.drawScoreboard();
this.drawRainbow();
this.drawNyanCat();
this.tick = !this.tick;
};
/**
* Draw the "scoreboard" showing the number
* of passes, failures and pending tests.
*
* @api private
*/
NyanCat.prototype.drawScoreboard = function () {
var stats = this.stats;
function draw (type, n) {
write(' ');
write(Base.color(type, n));
write('\n');
}
draw('green', stats.passes);
draw('fail', stats.failures);
draw('pending', stats.pending);
write('\n');
this.cursorUp(this.numberOfLines);
};
/**
* Append the rainbow.
*
* @api private
*/
NyanCat.prototype.appendRainbow = function () {
var segment = this.tick ? '_' : '-';
var rainbowified = this.rainbowify(segment);
for (var index = 0; index < this.numberOfLines; index++) {
var trajectory = this.trajectories[index];
if (trajectory.length >= this.trajectoryWidthMax) {
trajectory.shift();
}
trajectory.push(rainbowified);
}
};
/**
* Draw the rainbow.
*
* @api private
*/
NyanCat.prototype.drawRainbow = function () {
var self = this;
this.trajectories.forEach(function (line) {
write('\u001b[' + self.scoreboardWidth + 'C');
write(line.join(''));
write('\n');
});
this.cursorUp(this.numberOfLines);
};
/**
* Draw the nyan cat
*
* @api private
*/
NyanCat.prototype.drawNyanCat = function () {
var self = this;
var startWidth = this.scoreboardWidth + this.trajectories[0].length;
var dist = '\u001b[' + startWidth + 'C';
var padding = '';
write(dist);
write('_,------,');
write('\n');
write(dist);
padding = self.tick ? ' ' : ' ';
write('_|' + padding + '/\\_/\\ ');
write('\n');
write(dist);
padding = self.tick ? '_' : '__';
var tail = self.tick ? '~' : '^';
write(tail + '|' + padding + this.face() + ' ');
write('\n');
write(dist);
padding = self.tick ? ' ' : ' ';
write(padding + '"" "" ');
write('\n');
this.cursorUp(this.numberOfLines);
};
/**
* Draw nyan cat face.
*
* @api private
* @return {string}
*/
NyanCat.prototype.face = function () {
var stats = this.stats;
if (stats.failures) {
return '( x .x)';
} else if (stats.pending) {
return '( o .o)';
} else if (stats.passes) {
return '( ^ .^)';
}
return '( - .-)';
};
/**
* Move cursor up `n`.
*
* @api private
* @param {number} n
*/
NyanCat.prototype.cursorUp = function (n) {
write('\u001b[' + n + 'A');
};
/**
* Move cursor down `n`.
*
* @api private
* @param {number} n
*/
NyanCat.prototype.cursorDown = function (n) {
write('\u001b[' + n + 'B');
};
/**
* Generate rainbow colors.
*
* @api private
* @return {Array}
*/
NyanCat.prototype.generateColors = function () {
var colors = [];
for (var i = 0; i < (6 * 7); i++) {
var pi3 = Math.floor(Math.PI / 3);
var n = (i * (1.0 / 6));
var r = Math.floor(3 * Math.sin(n) + 3);
var g = Math.floor(3 * Math.sin(n + 2 * pi3) + 3);
var b = Math.floor(3 * Math.sin(n + 4 * pi3) + 3);
colors.push(36 * r + 6 * g + b + 16);
}
return colors;
};
/**
* Apply rainbow to the given `str`.
*
* @api private
* @param {string} str
* @return {string}
*/
NyanCat.prototype.rainbowify = function (str) {
if (!Base.useColors) {
return str;
}
var color = this.rainbowColors[this.colorIndex % this.rainbowColors.length];
this.colorIndex += 1;
return '\u001b[38;5;' + color + 'm' + str + '\u001b[0m';
};
/**
* Stdout helper.
*
* @param {string} string A message to write to stdout.
*/
function write (string) {
process.stdout.write(string);
}
}).call(this,require('_process'))
},{"../utils":38,"./base":17,"_process":67}],29:[function(require,module,exports){
(function (process){
'use strict';
/**
* Module dependencies.
*/
var Base = require('./base');
var inherits = require('../utils').inherits;
var color = Base.color;
var cursor = Base.cursor;
/**
* Expose `Progress`.
*/
exports = module.exports = Progress;
/**
* General progress bar color.
*/
Base.colors.progress = 90;
/**
* Initialize a new `Progress` bar test reporter.
*
* @api public
* @param {Runner} runner
* @param {Object} options
*/
function Progress (runner, options) {
Base.call(this, runner);
var self = this;
var width = Base.window.width * 0.50 | 0;
var total = runner.total;
var complete = 0;
var lastN = -1;
// default chars
options = options || {};
options.open = options.open || '[';
options.complete = options.complete || '▬';
options.incomplete = options.incomplete || Base.symbols.dot;
options.close = options.close || ']';
options.verbose = false;
// tests started
runner.on('start', function () {
console.log();
cursor.hide();
});
// tests complete
runner.on('test end', function () {
complete++;
var percent = complete / total;
var n = width * percent | 0;
var i = width - n;
if (n === lastN && !options.verbose) {
// Don't re-render the line if it hasn't changed
return;
}
lastN = n;
cursor.CR();
process.stdout.write('\u001b[J');
process.stdout.write(color('progress', ' ' + options.open));
process.stdout.write(Array(n).join(options.complete));
process.stdout.write(Array(i).join(options.incomplete));
process.stdout.write(color('progress', options.close));
if (options.verbose) {
process.stdout.write(color('progress', ' ' + complete + ' of ' + total));
}
});
// tests are complete, output some stats
// and the failures if any
runner.on('end', function () {
cursor.show();
console.log();
self.epilogue();
});
}
/**
* Inherit from `Base.prototype`.
*/
inherits(Progress, Base);
}).call(this,require('_process'))
},{"../utils":38,"./base":17,"_process":67}],30:[function(require,module,exports){
'use strict';
/**
* Module dependencies.
*/
var Base = require('./base');
var inherits = require('../utils').inherits;
var color = Base.color;
/**
* Expose `Spec`.
*/
exports = module.exports = Spec;
/**
* Initialize a new `Spec` test reporter.
*
* @api public
* @param {Runner} runner
*/
function Spec (runner) {
Base.call(this, runner);
var self = this;
var indents = 0;
var n = 0;
function indent () {
return Array(indents).join(' ');
}
runner.on('start', function () {
console.log();
});
runner.on('suite', function (suite) {
++indents;
console.log(color('suite', '%s%s'), indent(), suite.title);
});
runner.on('suite end', function () {
--indents;
if (indents === 1) {
console.log();
}
});
runner.on('pending', function (test) {
var fmt = indent() + color('pending', ' - %s');
console.log(fmt, test.title);
});
runner.on('pass', function (test) {
var fmt;
if (test.speed === 'fast') {
fmt = indent() +
color('checkmark', ' ' + Base.symbols.ok) +
color('pass', ' %s');
console.log(fmt, test.title);
} else {
fmt = indent() +
color('checkmark', ' ' + Base.symbols.ok) +
color('pass', ' %s') +
color(test.speed, ' (%dms)');
console.log(fmt, test.title, test.duration);
}
});
runner.on('fail', function (test) {
console.log(indent() + color('fail', ' %d) %s'), ++n, test.title);
});
runner.on('end', self.epilogue.bind(self));
}
/**
* Inherit from `Base.prototype`.
*/
inherits(Spec, Base);
},{"../utils":38,"./base":17}],31:[function(require,module,exports){
'use strict';
/**
* Module dependencies.
*/
var Base = require('./base');
/**
* Expose `TAP`.
*/
exports = module.exports = TAP;
/**
* Initialize a new `TAP` reporter.
*
* @api public
* @param {Runner} runner
*/
function TAP (runner) {
Base.call(this, runner);
var n = 1;
var passes = 0;
var failures = 0;
runner.on('start', function () {
var total = runner.grepTotal(runner.suite);
console.log('%d..%d', 1, total);
});
runner.on('test end', function () {
++n;
});
runner.on('pending', function (test) {
console.log('ok %d %s # SKIP -', n, title(test));
});
runner.on('pass', function (test) {
passes++;
console.log('ok %d %s', n, title(test));
});
runner.on('fail', function (test, err) {
failures++;
console.log('not ok %d %s', n, title(test));
if (err.stack) {
console.log(err.stack.replace(/^/gm, ' '));
}
});
runner.on('end', function () {
console.log('# tests ' + (passes + failures));
console.log('# pass ' + passes);
console.log('# fail ' + failures);
});
}
/**
* Return a TAP-safe title of `test`
*
* @api private
* @param {Object} test
* @return {String}
*/
function title (test) {
return test.fullTitle().replace(/#/g, '');
}
},{"./base":17}],32:[function(require,module,exports){
(function (process,global){
'use strict';
/**
* Module dependencies.
*/
var Base = require('./base');
var utils = require('../utils');
var inherits = utils.inherits;
var fs = require('fs');
var escape = utils.escape;
var mkdirp = require('mkdirp');
var path = require('path');
/**
* Save timer references to avoid Sinon interfering (see GH-237).
*/
/* eslint-disable no-unused-vars, no-native-reassign */
var Date = global.Date;
var setTimeout = global.setTimeout;
var setInterval = global.setInterval;
var clearTimeout = global.clearTimeout;
var clearInterval = global.clearInterval;
/* eslint-enable no-unused-vars, no-native-reassign */
/**
* Expose `XUnit`.
*/
exports = module.exports = XUnit;
/**
* Initialize a new `XUnit` reporter.
*
* @api public
* @param {Runner} runner
*/
function XUnit (runner, options) {
Base.call(this, runner);
var stats = this.stats;
var tests = [];
var self = this;
if (options && options.reporterOptions && options.reporterOptions.output) {
if (!fs.createWriteStream) {
throw new Error('file output not supported in browser');
}
mkdirp.sync(path.dirname(options.reporterOptions.output));
self.fileStream = fs.createWriteStream(options.reporterOptions.output);
}
runner.on('pending', function (test) {
tests.push(test);
});
runner.on('pass', function (test) {
tests.push(test);
});
runner.on('fail', function (test) {
tests.push(test);
});
runner.on('end', function () {
self.write(tag('testsuite', {
name: 'Mocha Tests',
tests: stats.tests,
failures: stats.failures,
errors: stats.failures,
skipped: stats.tests - stats.failures - stats.passes,
timestamp: (new Date()).toUTCString(),
time: (stats.duration / 1000) || 0
}, false));
tests.forEach(function (t) {
self.test(t);
});
self.write('</testsuite>');
});
}
/**
* Inherit from `Base.prototype`.
*/
inherits(XUnit, Base);
/**
* Override done to close the stream (if it's a file).
*
* @param failures
* @param {Function} fn
*/
XUnit.prototype.done = function (failures, fn) {
if (this.fileStream) {
this.fileStream.end(function () {
fn(failures);
});
} else {
fn(failures);
}
};
/**
* Write out the given line.
*
* @param {string} line
*/
XUnit.prototype.write = function (line) {
if (this.fileStream) {
this.fileStream.write(line + '\n');
} else if (typeof process === 'object' && process.stdout) {
process.stdout.write(line + '\n');
} else {
console.log(line);
}
};
/**
* Output tag for the given `test.`
*
* @param {Test} test
*/
XUnit.prototype.test = function (test) {
var attrs = {
classname: test.parent.fullTitle(),
name: test.title,
time: (test.duration / 1000) || 0
};
if (test.state === 'failed') {
var err = test.err;
this.write(tag('testcase', attrs, false, tag('failure', {}, false, escape(err.message) + '\n' + escape(err.stack))));
} else if (test.isPending()) {
this.write(tag('testcase', attrs, false, tag('skipped', {}, true)));
} else {
this.write(tag('testcase', attrs, true));
}
};
/**
* HTML tag helper.
*
* @param name
* @param attrs
* @param close
* @param content
* @return {string}
*/
function tag (name, attrs, close, content) {
var end = close ? '/>' : '>';
var pairs = [];
var tag;
for (var key in attrs) {
if (Object.prototype.hasOwnProperty.call(attrs, key)) {
pairs.push(key + '="' + escape(attrs[key]) + '"');
}
}
tag = '<' + name + (pairs.length ? ' ' + pairs.join(' ') : '') + end;
if (content) {
tag += content + '</' + name + end;
}
return tag;
}
}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"../utils":38,"./base":17,"_process":67,"fs":42,"mkdirp":64,"path":42}],33:[function(require,module,exports){
(function (global){
'use strict';
/**
* Module dependencies.
*/
var EventEmitter = require('events').EventEmitter;
var JSON = require('json3');
var Pending = require('./pending');
var debug = require('debug')('mocha:runnable');
var milliseconds = require('./ms');
var utils = require('./utils');
var create = require('lodash.create');
/**
* Save timer references to avoid Sinon interfering (see GH-237).
*/
/* eslint-disable no-unused-vars, no-native-reassign */
var Date = global.Date;
var setTimeout = global.setTimeout;
var setInterval = global.setInterval;
var clearTimeout = global.clearTimeout;
var clearInterval = global.clearInterval;
/* eslint-enable no-unused-vars, no-native-reassign */
/**
* Object#toString().
*/
var toString = Object.prototype.toString;
/**
* Expose `Runnable`.
*/
module.exports = Runnable;
/**
* Initialize a new `Runnable` with the given `title` and callback `fn`.
*
* @param {String} title
* @param {Function} fn
* @api private
* @param {string} title
* @param {Function} fn
*/
function Runnable (title, fn) {
this.title = title;
this.fn = fn;
this.body = (fn || '').toString();
this.async = fn && fn.length;
this.sync = !this.async;
this._timeout = 2000;
this._slow = 75;
this._enableTimeouts = true;
this.timedOut = false;
this._trace = new Error('done() called multiple times');
this._retries = -1;
this._currentRetry = 0;
this.pending = false;
}
/**
* Inherit from `EventEmitter.prototype`.
*/
Runnable.prototype = create(EventEmitter.prototype, {
constructor: Runnable
});
/**
* Set & get timeout `ms`.
*
* @api private
* @param {number|string} ms
* @return {Runnable|number} ms or Runnable instance.
*/
Runnable.prototype.timeout = function (ms) {
if (!arguments.length) {
return this._timeout;
}
// see #1652 for reasoning
if (ms === 0 || ms > Math.pow(2, 31)) {
this._enableTimeouts = false;
}
if (typeof ms === 'string') {
ms = milliseconds(ms);
}
debug('timeout %d', ms);
this._timeout = ms;
if (this.timer) {
this.resetTimeout();
}
return this;
};
/**
* Set & get slow `ms`.
*
* @api private
* @param {number|string} ms
* @return {Runnable|number} ms or Runnable instance.
*/
Runnable.prototype.slow = function (ms) {
if (typeof ms === 'undefined') {
return this._slow;
}
if (typeof ms === 'string') {
ms = milliseconds(ms);
}
debug('timeout %d', ms);
this._slow = ms;
return this;
};
/**
* Set and get whether timeout is `enabled`.
*
* @api private
* @param {boolean} enabled
* @return {Runnable|boolean} enabled or Runnable instance.
*/
Runnable.prototype.enableTimeouts = function (enabled) {
if (!arguments.length) {
return this._enableTimeouts;
}
debug('enableTimeouts %s', enabled);
this._enableTimeouts = enabled;
return this;
};
/**
* Halt and mark as pending.
*
* @api public
*/
Runnable.prototype.skip = function () {
throw new Pending('sync skip');
};
/**
* Check if this runnable or its parent suite is marked as pending.
*
* @api private
*/
Runnable.prototype.isPending = function () {
return this.pending || (this.parent && this.parent.isPending());
};
/**
* Set number of retries.
*
* @api private
*/
Runnable.prototype.retries = function (n) {
if (!arguments.length) {
return this._retries;
}
this._retries = n;
};
/**
* Get current retry
*
* @api private
*/
Runnable.prototype.currentRetry = function (n) {
if (!arguments.length) {
return this._currentRetry;
}
this._currentRetry = n;
};
/**
* Return the full title generated by recursively concatenating the parent's
* full title.
*
* @api public
* @return {string}
*/
Runnable.prototype.fullTitle = function () {
return this.parent.fullTitle() + ' ' + this.title;
};
/**
* Clear the timeout.
*
* @api private
*/
Runnable.prototype.clearTimeout = function () {
clearTimeout(this.timer);
};
/**
* Inspect the runnable void of private properties.
*
* @api private
* @return {string}
*/
Runnable.prototype.inspect = function () {
return JSON.stringify(this, function (key, val) {
if (key[0] === '_') {
return;
}
if (key === 'parent') {
return '#<Suite>';
}
if (key === 'ctx') {
return '#<Context>';
}
return val;
}, 2);
};
/**
* Reset the timeout.
*
* @api private
*/
Runnable.prototype.resetTimeout = function () {
var self = this;
var ms = this.timeout() || 1e9;
if (!this._enableTimeouts) {
return;
}
this.clearTimeout();
this.timer = setTimeout(function () {
if (!self._enableTimeouts) {
return;
}
self.callback(new Error('Timeout of ' + ms +
'ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.'));
self.timedOut = true;
}, ms);
};
/**
* Whitelist a list of globals for this test run.
*
* @api private
* @param {string[]} globals
*/
Runnable.prototype.globals = function (globals) {
if (!arguments.length) {
return this._allowedGlobals;
}
this._allowedGlobals = globals;
};
/**
* Run the test and invoke `fn(err)`.
*
* @param {Function} fn
* @api private
*/
Runnable.prototype.run = function (fn) {
var self = this;
var start = new Date();
var ctx = this.ctx;
var finished;
var emitted;
// Sometimes the ctx exists, but it is not runnable
if (ctx && ctx.runnable) {
ctx.runnable(this);
}
// called multiple times
function multiple (err) {
if (emitted) {
return;
}
emitted = true;
self.emit('error', err || new Error('done() called multiple times; stacktrace may be inaccurate'));
}
// finished
function done (err) {
var ms = self.timeout();
if (self.timedOut) {
return;
}
if (finished) {
return multiple(err || self._trace);
}
self.clearTimeout();
self.duration = new Date() - start;
finished = true;
if (!err && self.duration > ms && self._enableTimeouts) {
err = new Error('Timeout of ' + ms +
'ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.');
}
fn(err);
}
// for .resetTimeout()
this.callback = done;
// explicit async with `done` argument
if (this.async) {
this.resetTimeout();
// allows skip() to be used in an explicit async context
this.skip = function asyncSkip () {
done(new Pending('async skip call'));
// halt execution. the Runnable will be marked pending
// by the previous call, and the uncaught handler will ignore
// the failure.
throw new Pending('async skip; aborting execution');
};
if (this.allowUncaught) {
return callFnAsync(this.fn);
}
try {
callFnAsync(this.fn);
} catch (err) {
emitted = true;
done(utils.getError(err));
}
return;
}
if (this.allowUncaught) {
callFn(this.fn);
done();
return;
}
// sync or promise-returning
try {
if (this.isPending()) {
done();
} else {
callFn(this.fn);
}
} catch (err) {
emitted = true;
done(utils.getError(err));
}
function callFn (fn) {
var result = fn.call(ctx);
if (result && typeof result.then === 'function') {
self.resetTimeout();
result
.then(function () {
done();
// Return null so libraries like bluebird do not warn about
// subsequently constructed Promises.
return null;
},
function (reason) {
done(reason || new Error('Promise rejected with no or falsy reason'));
});
} else {
if (self.asyncOnly) {
return done(new Error('--async-only option in use without declaring `done()` or returning a promise'));
}
done();
}
}
function callFnAsync (fn) {
var result = fn.call(ctx, function (err) {
if (err instanceof Error || toString.call(err) === '[object Error]') {
return done(err);
}
if (err) {
if (Object.prototype.toString.call(err) === '[object Object]') {
return done(new Error('done() invoked with non-Error: ' +
JSON.stringify(err)));
}
return done(new Error('done() invoked with non-Error: ' + err));
}
if (result && utils.isPromise(result)) {
return done(new Error('Resolution method is overspecified. Specify a callback *or* return a Promise; not both.'));
}
done();
});
}
};
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./ms":15,"./pending":16,"./utils":38,"debug":2,"events":3,"json3":54,"lodash.create":60}],34:[function(require,module,exports){
(function (process,global){
'use strict';
/**
* Module dependencies.
*/
var EventEmitter = require('events').EventEmitter;
var Pending = require('./pending');
var utils = require('./utils');
var inherits = utils.inherits;
var debug = require('debug')('mocha:runner');
var Runnable = require('./runnable');
var filter = utils.filter;
var indexOf = utils.indexOf;
var some = utils.some;
var keys = utils.keys;
var stackFilter = utils.stackTraceFilter();
var stringify = utils.stringify;
var type = utils.type;
var undefinedError = utils.undefinedError;
var isArray = utils.isArray;
/**
* Non-enumerable globals.
*/
var globals = [
'setTimeout',
'clearTimeout',
'setInterval',
'clearInterval',
'XMLHttpRequest',
'Date',
'setImmediate',
'clearImmediate'
];
/**
* Expose `Runner`.
*/
module.exports = Runner;
/**
* Initialize a `Runner` for the given `suite`.
*
* Events:
*
* - `start` execution started
* - `end` execution complete
* - `suite` (suite) test suite execution started
* - `suite end` (suite) all tests (and sub-suites) have finished
* - `test` (test) test execution started
* - `test end` (test) test completed
* - `hook` (hook) hook execution started
* - `hook end` (hook) hook complete
* - `pass` (test) test passed
* - `fail` (test, err) test failed
* - `pending` (test) test pending
*
* @api public
* @param {Suite} suite Root suite
* @param {boolean} [delay] Whether or not to delay execution of root suite
* until ready.
*/
function Runner (suite, delay) {
var self = this;
this._globals = [];
this._abort = false;
this._delay = delay;
this.suite = suite;
this.started = false;
this.total = suite.total();
this.failures = 0;
this.on('test end', function (test) {
self.checkGlobals(test);
});
this.on('hook end', function (hook) {
self.checkGlobals(hook);
});
this._defaultGrep = /.*/;
this.grep(this._defaultGrep);
this.globals(this.globalProps().concat(extraGlobals()));
}
/**
* Wrapper for setImmediate, process.nextTick, or browser polyfill.
*
* @param {Function} fn
* @api private
*/
Runner.immediately = global.setImmediate || process.nextTick;
/**
* Inherit from `EventEmitter.prototype`.
*/
inherits(Runner, EventEmitter);
/**
* Run tests with full titles matching `re`. Updates runner.total
* with number of tests matched.
*
* @param {RegExp} re
* @param {Boolean} invert
* @return {Runner} for chaining
* @api public
* @param {RegExp} re
* @param {boolean} invert
* @return {Runner} Runner instance.
*/
Runner.prototype.grep = function (re, invert) {
debug('grep %s', re);
this._grep = re;
this._invert = invert;
this.total = this.grepTotal(this.suite);
return this;
};
/**
* Returns the number of tests matching the grep search for the
* given suite.
*
* @param {Suite} suite
* @return {Number}
* @api public
* @param {Suite} suite
* @return {number}
*/
Runner.prototype.grepTotal = function (suite) {
var self = this;
var total = 0;
suite.eachTest(function (test) {
var match = self._grep.test(test.fullTitle());
if (self._invert) {
match = !match;
}
if (match) {
total++;
}
});
return total;
};
/**
* Return a list of global properties.
*
* @return {Array}
* @api private
*/
Runner.prototype.globalProps = function () {
var props = keys(global);
// non-enumerables
for (var i = 0; i < globals.length; ++i) {
if (~indexOf(props, globals[i])) {
continue;
}
props.push(globals[i]);
}
return props;
};
/**
* Allow the given `arr` of globals.
*
* @param {Array} arr
* @return {Runner} for chaining
* @api public
* @param {Array} arr
* @return {Runner} Runner instance.
*/
Runner.prototype.globals = function (arr) {
if (!arguments.length) {
return this._globals;
}
debug('globals %j', arr);
this._globals = this._globals.concat(arr);
return this;
};
/**
* Check for global variable leaks.
*
* @api private
*/
Runner.prototype.checkGlobals = function (test) {
if (this.ignoreLeaks) {
return;
}
var ok = this._globals;
var globals = this.globalProps();
var leaks;
if (test) {
ok = ok.concat(test._allowedGlobals || []);
}
if (this.prevGlobalsLength === globals.length) {
return;
}
this.prevGlobalsLength = globals.length;
leaks = filterLeaks(ok, globals);
this._globals = this._globals.concat(leaks);
if (leaks.length > 1) {
this.fail(test, new Error('global leaks detected: ' + leaks.join(', ') + ''));
} else if (leaks.length) {
this.fail(test, new Error('global leak detected: ' + leaks[0]));
}
};
/**
* Fail the given `test`.
*
* @api private
* @param {Test} test
* @param {Error} err
*/
Runner.prototype.fail = function (test, err) {
if (test.isPending()) {
return;
}
++this.failures;
test.state = 'failed';
if (!(err instanceof Error || err && typeof err.message === 'string')) {
err = new Error('the ' + type(err) + ' ' + stringify(err) + ' was thrown, throw an Error :)');
}
try {
err.stack = (this.fullStackTrace || !err.stack)
? err.stack
: stackFilter(err.stack);
} catch (ignored) {
// some environments do not take kindly to monkeying with the stack
}
this.emit('fail', test, err);
};
/**
* Fail the given `hook` with `err`.
*
* Hook failures work in the following pattern:
* - If bail, then exit
* - Failed `before` hook skips all tests in a suite and subsuites,
* but jumps to corresponding `after` hook
* - Failed `before each` hook skips remaining tests in a
* suite and jumps to corresponding `after each` hook,
* which is run only once
* - Failed `after` hook does not alter
* execution order
* - Failed `after each` hook skips remaining tests in a
* suite and subsuites, but executes other `after each`
* hooks
*
* @api private
* @param {Hook} hook
* @param {Error} err
*/
Runner.prototype.failHook = function (hook, err) {
if (hook.ctx && hook.ctx.currentTest) {
hook.originalTitle = hook.originalTitle || hook.title;
hook.title = hook.originalTitle + ' for "' + hook.ctx.currentTest.title + '"';
}
this.fail(hook, err);
if (this.suite.bail()) {
this.emit('end');
}
};
/**
* Run hook `name` callbacks and then invoke `fn()`.
*
* @api private
* @param {string} name
* @param {Function} fn
*/
Runner.prototype.hook = function (name, fn) {
var suite = this.suite;
var hooks = suite['_' + name];
var self = this;
function next (i) {
var hook = hooks[i];
if (!hook) {
return fn();
}
self.currentRunnable = hook;
hook.ctx.currentTest = self.test;
self.emit('hook', hook);
if (!hook.listeners('error').length) {
hook.on('error', function (err) {
self.failHook(hook, err);
});
}
hook.run(function (err) {
var testError = hook.error();
if (testError) {
self.fail(self.test, testError);
}
if (err) {
if (err instanceof Pending) {
if (name === 'beforeEach' || name === 'afterEach') {
self.test.pending = true;
} else {
utils.forEach(suite.tests, function (test) {
test.pending = true;
});
// a pending hook won't be executed twice.
hook.pending = true;
}
} else {
self.failHook(hook, err);
// stop executing hooks, notify callee of hook err
return fn(err);
}
}
self.emit('hook end', hook);
delete hook.ctx.currentTest;
next(++i);
});
}
Runner.immediately(function () {
next(0);
});
};
/**
* Run hook `name` for the given array of `suites`
* in order, and callback `fn(err, errSuite)`.
*
* @api private
* @param {string} name
* @param {Array} suites
* @param {Function} fn
*/
Runner.prototype.hooks = function (name, suites, fn) {
var self = this;
var orig = this.suite;
function next (suite) {
self.suite = suite;
if (!suite) {
self.suite = orig;
return fn();
}
self.hook(name, function (err) {
if (err) {
var errSuite = self.suite;
self.suite = orig;
return fn(err, errSuite);
}
next(suites.pop());
});
}
next(suites.pop());
};
/**
* Run hooks from the top level down.
*
* @param {String} name
* @param {Function} fn
* @api private
*/
Runner.prototype.hookUp = function (name, fn) {
var suites = [this.suite].concat(this.parents()).reverse();
this.hooks(name, suites, fn);
};
/**
* Run hooks from the bottom up.
*
* @param {String} name
* @param {Function} fn
* @api private
*/
Runner.prototype.hookDown = function (name, fn) {
var suites = [this.suite].concat(this.parents());
this.hooks(name, suites, fn);
};
/**
* Return an array of parent Suites from
* closest to furthest.
*
* @return {Array}
* @api private
*/
Runner.prototype.parents = function () {
var suite = this.suite;
var suites = [];
while (suite.parent) {
suite = suite.parent;
suites.push(suite);
}
return suites;
};
/**
* Run the current test and callback `fn(err)`.
*
* @param {Function} fn
* @api private
*/
Runner.prototype.runTest = function (fn) {
var self = this;
var test = this.test;
if (!test) {
return;
}
if (this.asyncOnly) {
test.asyncOnly = true;
}
if (this.allowUncaught) {
test.allowUncaught = true;
return test.run(fn);
}
try {
test.on('error', function (err) {
self.fail(test, err);
});
test.run(fn);
} catch (err) {
fn(err);
}
};
/**
* Run tests in the given `suite` and invoke the callback `fn()` when complete.
*
* @api private
* @param {Suite} suite
* @param {Function} fn
*/
Runner.prototype.runTests = function (suite, fn) {
var self = this;
var tests = suite.tests.slice();
var test;
function hookErr (_, errSuite, after) {
// before/after Each hook for errSuite failed:
var orig = self.suite;
// for failed 'after each' hook start from errSuite parent,
// otherwise start from errSuite itself
self.suite = after ? errSuite.parent : errSuite;
if (self.suite) {
// call hookUp afterEach
self.hookUp('afterEach', function (err2, errSuite2) {
self.suite = orig;
// some hooks may fail even now
if (err2) {
return hookErr(err2, errSuite2, true);
}
// report error suite
fn(errSuite);
});
} else {
// there is no need calling other 'after each' hooks
self.suite = orig;
fn(errSuite);
}
}
function next (err, errSuite) {
// if we bail after first err
if (self.failures && suite._bail) {
return fn();
}
if (self._abort) {
return fn();
}
if (err) {
return hookErr(err, errSuite, true);
}
// next test
test = tests.shift();
// all done
if (!test) {
return fn();
}
// grep
var match = self._grep.test(test.fullTitle());
if (self._invert) {
match = !match;
}
if (!match) {
// Run immediately only if we have defined a grep. When we
// define a grep — It can cause maximum callstack error if
// the grep is doing a large recursive loop by neglecting
// all tests. The run immediately function also comes with
// a performance cost. So we don't want to run immediately
// if we run the whole test suite, because running the whole
// test suite don't do any immediate recursive loops. Thus,
// allowing a JS runtime to breathe.
if (self._grep !== self._defaultGrep) {
Runner.immediately(next);
} else {
next();
}
return;
}
if (test.isPending()) {
self.emit('pending', test);
self.emit('test end', test);
return next();
}
// execute test and hook(s)
self.emit('test', self.test = test);
self.hookDown('beforeEach', function (err, errSuite) {
if (test.isPending()) {
self.emit('pending', test);
self.emit('test end', test);
return next();
}
if (err) {
return hookErr(err, errSuite, false);
}
self.currentRunnable = self.test;
self.runTest(function (err) {
test = self.test;
if (err) {
var retry = test.currentRetry();
if (err instanceof Pending) {
test.pending = true;
self.emit('pending', test);
} else if (retry < test.retries()) {
var clonedTest = test.clone();
clonedTest.currentRetry(retry + 1);
tests.unshift(clonedTest);
// Early return + hook trigger so that it doesn't
// increment the count wrong
return self.hookUp('afterEach', next);
} else {
self.fail(test, err);
}
self.emit('test end', test);
if (err instanceof Pending) {
return next();
}
return self.hookUp('afterEach', next);
}
test.state = 'passed';
self.emit('pass', test);
self.emit('test end', test);
self.hookUp('afterEach', next);
});
});
}
this.next = next;
this.hookErr = hookErr;
next();
};
/**
* Run the given `suite` and invoke the callback `fn()` when complete.
*
* @api private
* @param {Suite} suite
* @param {Function} fn
*/
Runner.prototype.runSuite = function (suite, fn) {
var i = 0;
var self = this;
var total = this.grepTotal(suite);
var afterAllHookCalled = false;
debug('run suite %s', suite.fullTitle());
if (!total || (self.failures && suite._bail)) {
return fn();
}
this.emit('suite', this.suite = suite);
function next (errSuite) {
if (errSuite) {
// current suite failed on a hook from errSuite
if (errSuite === suite) {
// if errSuite is current suite
// continue to the next sibling suite
return done();
}
// errSuite is among the parents of current suite
// stop execution of errSuite and all sub-suites
return done(errSuite);
}
if (self._abort) {
return done();
}
var curr = suite.suites[i++];
if (!curr) {
return done();
}
// Avoid grep neglecting large number of tests causing a
// huge recursive loop and thus a maximum call stack error.
// See comment in `this.runTests()` for more information.
if (self._grep !== self._defaultGrep) {
Runner.immediately(function () {
self.runSuite(curr, next);
});
} else {
self.runSuite(curr, next);
}
}
function done (errSuite) {
self.suite = suite;
self.nextSuite = next;
if (afterAllHookCalled) {
fn(errSuite);
} else {
// mark that the afterAll block has been called once
// and so can be skipped if there is an error in it.
afterAllHookCalled = true;
// remove reference to test
delete self.test;
self.hook('afterAll', function () {
self.emit('suite end', suite);
fn(errSuite);
});
}
}
this.nextSuite = next;
this.hook('beforeAll', function (err) {
if (err) {
return done();
}
self.runTests(suite, next);
});
};
/**
* Handle uncaught exceptions.
*
* @param {Error} err
* @api private
*/
Runner.prototype.uncaught = function (err) {
if (err) {
debug('uncaught exception %s', err !== function () {
return this;
}.call(err) ? err : (err.message || err));
} else {
debug('uncaught undefined exception');
err = undefinedError();
}
err.uncaught = true;
var runnable = this.currentRunnable;
if (!runnable) {
runnable = new Runnable('Uncaught error outside test suite');
runnable.parent = this.suite;
if (this.started) {
this.fail(runnable, err);
} else {
// Can't recover from this failure
this.emit('start');
this.fail(runnable, err);
this.emit('end');
}
return;
}
runnable.clearTimeout();
// Ignore errors if complete or pending
if (runnable.state || runnable.isPending()) {
return;
}
this.fail(runnable, err);
// recover from test
if (runnable.type === 'test') {
this.emit('test end', runnable);
this.hookUp('afterEach', this.next);
return;
}
// recover from hooks
if (runnable.type === 'hook') {
var errSuite = this.suite;
// if hook failure is in afterEach block
if (runnable.fullTitle().indexOf('after each') > -1) {
return this.hookErr(err, errSuite, true);
}
// if hook failure is in beforeEach block
if (runnable.fullTitle().indexOf('before each') > -1) {
return this.hookErr(err, errSuite, false);
}
// if hook failure is in after or before blocks
return this.nextSuite(errSuite);
}
// bail
this.emit('end');
};
/**
* Cleans up the references to all the deferred functions
* (before/after/beforeEach/afterEach) and tests of a Suite.
* These must be deleted otherwise a memory leak can happen,
* as those functions may reference variables from closures,
* thus those variables can never be garbage collected as long
* as the deferred functions exist.
*
* @param {Suite} suite
*/
function cleanSuiteReferences (suite) {
function cleanArrReferences (arr) {
for (var i = 0; i < arr.length; i++) {
delete arr[i].fn;
}
}
if (isArray(suite._beforeAll)) {
cleanArrReferences(suite._beforeAll);
}
if (isArray(suite._beforeEach)) {
cleanArrReferences(suite._beforeEach);
}
if (isArray(suite._afterAll)) {
cleanArrReferences(suite._afterAll);
}
if (isArray(suite._afterEach)) {
cleanArrReferences(suite._afterEach);
}
for (var i = 0; i < suite.tests.length; i++) {
delete suite.tests[i].fn;
}
}
/**
* Run the root suite and invoke `fn(failures)`
* on completion.
*
* @param {Function} fn
* @return {Runner} for chaining
* @api public
* @param {Function} fn
* @return {Runner} Runner instance.
*/
Runner.prototype.run = function (fn) {
var self = this;
var rootSuite = this.suite;
// If there is an `only` filter
if (this.hasOnly) {
filterOnly(rootSuite);
}
fn = fn || function () {};
function uncaught (err) {
self.uncaught(err);
}
function start () {
self.started = true;
self.emit('start');
self.runSuite(rootSuite, function () {
debug('finished running');
self.emit('end');
});
}
debug('start');
// references cleanup to avoid memory leaks
this.on('suite end', cleanSuiteReferences);
// callback
this.on('end', function () {
debug('end');
process.removeListener('uncaughtException', uncaught);
fn(self.failures);
});
// uncaught exception
process.on('uncaughtException', uncaught);
if (this._delay) {
// for reporters, I guess.
// might be nice to debounce some dots while we wait.
this.emit('waiting', rootSuite);
rootSuite.once('run', start);
} else {
start();
}
return this;
};
/**
* Cleanly abort execution.
*
* @api public
* @return {Runner} Runner instance.
*/
Runner.prototype.abort = function () {
debug('aborting');
this._abort = true;
return this;
};
/**
* Filter suites based on `isOnly` logic.
*
* @param {Array} suite
* @returns {Boolean}
* @api private
*/
function filterOnly (suite) {
if (suite._onlyTests.length) {
// If the suite contains `only` tests, run those and ignore any nested suites.
suite.tests = suite._onlyTests;
suite.suites = [];
} else {
// Otherwise, do not run any of the tests in this suite.
suite.tests = [];
utils.forEach(suite._onlySuites, function (onlySuite) {
// If there are other `only` tests/suites nested in the current `only` suite, then filter that `only` suite.
// Otherwise, all of the tests on this `only` suite should be run, so don't filter it.
if (hasOnly(onlySuite)) {
filterOnly(onlySuite);
}
});
// Run the `only` suites, as well as any other suites that have `only` tests/suites as descendants.
suite.suites = filter(suite.suites, function (childSuite) {
return indexOf(suite._onlySuites, childSuite) !== -1 || filterOnly(childSuite);
});
}
// Keep the suite only if there is something to run
return suite.tests.length || suite.suites.length;
}
/**
* Determines whether a suite has an `only` test or suite as a descendant.
*
* @param {Array} suite
* @returns {Boolean}
* @api private
*/
function hasOnly (suite) {
return suite._onlyTests.length || suite._onlySuites.length || some(suite.suites, hasOnly);
}
/**
* Filter leaks with the given globals flagged as `ok`.
*
* @api private
* @param {Array} ok
* @param {Array} globals
* @return {Array}
*/
function filterLeaks (ok, globals) {
return filter(globals, function (key) {
// Firefox and Chrome exposes iframes as index inside the window object
if (/^\d+/.test(key)) {
return false;
}
// in firefox
// if runner runs in an iframe, this iframe's window.getInterface method
// not init at first it is assigned in some seconds
if (global.navigator && (/^getInterface/).test(key)) {
return false;
}
// an iframe could be approached by window[iframeIndex]
// in ie6,7,8 and opera, iframeIndex is enumerable, this could cause leak
if (global.navigator && (/^\d+/).test(key)) {
return false;
}
// Opera and IE expose global variables for HTML element IDs (issue #243)
if (/^mocha-/.test(key)) {
return false;
}
var matched = filter(ok, function (ok) {
if (~ok.indexOf('*')) {
return key.indexOf(ok.split('*')[0]) === 0;
}
return key === ok;
});
return !matched.length && (!global.navigator || key !== 'onerror');
});
}
/**
* Array of globals dependent on the environment.
*
* @return {Array}
* @api private
*/
function extraGlobals () {
if (typeof process === 'object' && typeof process.version === 'string') {
var parts = process.version.split('.');
var nodeVersion = utils.reduce(parts, function (a, v) {
return a << 8 | v;
});
// 'errno' was renamed to process._errno in v0.9.11.
if (nodeVersion < 0x00090B) {
return ['errno'];
}
}
return [];
}
}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./pending":16,"./runnable":33,"./utils":38,"_process":67,"debug":2,"events":3}],35:[function(require,module,exports){
'use strict';
/**
* Module dependencies.
*/
var EventEmitter = require('events').EventEmitter;
var Hook = require('./hook');
var utils = require('./utils');
var inherits = utils.inherits;
var debug = require('debug')('mocha:suite');
var milliseconds = require('./ms');
/**
* Expose `Suite`.
*/
exports = module.exports = Suite;
/**
* Create a new `Suite` with the given `title` and parent `Suite`. When a suite
* with the same title is already present, that suite is returned to provide
* nicer reporter and more flexible meta-testing.
*
* @api public
* @param {Suite} parent
* @param {string} title
* @return {Suite}
*/
exports.create = function (parent, title) {
var suite = new Suite(title, parent.ctx);
suite.parent = parent;
title = suite.fullTitle();
parent.addSuite(suite);
return suite;
};
/**
* Initialize a new `Suite` with the given `title` and `ctx`.
*
* @api private
* @param {string} title
* @param {Context} parentContext
*/
function Suite (title, parentContext) {
if (!utils.isString(title)) {
throw new Error('Suite `title` should be a "string" but "' + typeof title + '" was given instead.');
}
this.title = title;
function Context () {}
Context.prototype = parentContext;
this.ctx = new Context();
this.suites = [];
this.tests = [];
this.pending = false;
this._beforeEach = [];
this._beforeAll = [];
this._afterEach = [];
this._afterAll = [];
this.root = !title;
this._timeout = 2000;
this._enableTimeouts = true;
this._slow = 75;
this._bail = false;
this._retries = -1;
this._onlyTests = [];
this._onlySuites = [];
this.delayed = false;
}
/**
* Inherit from `EventEmitter.prototype`.
*/
inherits(Suite, EventEmitter);
/**
* Return a clone of this `Suite`.
*
* @api private
* @return {Suite}
*/
Suite.prototype.clone = function () {
var suite = new Suite(this.title);
debug('clone');
suite.ctx = this.ctx;
suite.timeout(this.timeout());
suite.retries(this.retries());
suite.enableTimeouts(this.enableTimeouts());
suite.slow(this.slow());
suite.bail(this.bail());
return suite;
};
/**
* Set timeout `ms` or short-hand such as "2s".
*
* @api private
* @param {number|string} ms
* @return {Suite|number} for chaining
*/
Suite.prototype.timeout = function (ms) {
if (!arguments.length) {
return this._timeout;
}
if (ms.toString() === '0') {
this._enableTimeouts = false;
}
if (typeof ms === 'string') {
ms = milliseconds(ms);
}
debug('timeout %d', ms);
this._timeout = parseInt(ms, 10);
return this;
};
/**
* Set number of times to retry a failed test.
*
* @api private
* @param {number|string} n
* @return {Suite|number} for chaining
*/
Suite.prototype.retries = function (n) {
if (!arguments.length) {
return this._retries;
}
debug('retries %d', n);
this._retries = parseInt(n, 10) || 0;
return this;
};
/**
* Set timeout to `enabled`.
*
* @api private
* @param {boolean} enabled
* @return {Suite|boolean} self or enabled
*/
Suite.prototype.enableTimeouts = function (enabled) {
if (!arguments.length) {
return this._enableTimeouts;
}
debug('enableTimeouts %s', enabled);
this._enableTimeouts = enabled;
return this;
};
/**
* Set slow `ms` or short-hand such as "2s".
*
* @api private
* @param {number|string} ms
* @return {Suite|number} for chaining
*/
Suite.prototype.slow = function (ms) {
if (!arguments.length) {
return this._slow;
}
if (typeof ms === 'string') {
ms = milliseconds(ms);
}
debug('slow %d', ms);
this._slow = ms;
return this;
};
/**
* Sets whether to bail after first error.
*
* @api private
* @param {boolean} bail
* @return {Suite|number} for chaining
*/
Suite.prototype.bail = function (bail) {
if (!arguments.length) {
return this._bail;
}
debug('bail %s', bail);
this._bail = bail;
return this;
};
/**
* Check if this suite or its parent suite is marked as pending.
*
* @api private
*/
Suite.prototype.isPending = function () {
return this.pending || (this.parent && this.parent.isPending());
};
/**
* Run `fn(test[, done])` before running tests.
*
* @api private
* @param {string} title
* @param {Function} fn
* @return {Suite} for chaining
*/
Suite.prototype.beforeAll = function (title, fn) {
if (this.isPending()) {
return this;
}
if (typeof title === 'function') {
fn = title;
title = fn.name;
}
title = '"before all" hook' + (title ? ': ' + title : '');
var hook = new Hook(title, fn);
hook.parent = this;
hook.timeout(this.timeout());
hook.retries(this.retries());
hook.enableTimeouts(this.enableTimeouts());
hook.slow(this.slow());
hook.ctx = this.ctx;
this._beforeAll.push(hook);
this.emit('beforeAll', hook);
return this;
};
/**
* Run `fn(test[, done])` after running tests.
*
* @api private
* @param {string} title
* @param {Function} fn
* @return {Suite} for chaining
*/
Suite.prototype.afterAll = function (title, fn) {
if (this.isPending()) {
return this;
}
if (typeof title === 'function') {
fn = title;
title = fn.name;
}
title = '"after all" hook' + (title ? ': ' + title : '');
var hook = new Hook(title, fn);
hook.parent = this;
hook.timeout(this.timeout());
hook.retries(this.retries());
hook.enableTimeouts(this.enableTimeouts());
hook.slow(this.slow());
hook.ctx = this.ctx;
this._afterAll.push(hook);
this.emit('afterAll', hook);
return this;
};
/**
* Run `fn(test[, done])` before each test case.
*
* @api private
* @param {string} title
* @param {Function} fn
* @return {Suite} for chaining
*/
Suite.prototype.beforeEach = function (title, fn) {
if (this.isPending()) {
return this;
}
if (typeof title === 'function') {
fn = title;
title = fn.name;
}
title = '"before each" hook' + (title ? ': ' + title : '');
var hook = new Hook(title, fn);
hook.parent = this;
hook.timeout(this.timeout());
hook.retries(this.retries());
hook.enableTimeouts(this.enableTimeouts());
hook.slow(this.slow());
hook.ctx = this.ctx;
this._beforeEach.push(hook);
this.emit('beforeEach', hook);
return this;
};
/**
* Run `fn(test[, done])` after each test case.
*
* @api private
* @param {string} title
* @param {Function} fn
* @return {Suite} for chaining
*/
Suite.prototype.afterEach = function (title, fn) {
if (this.isPending()) {
return this;
}
if (typeof title === 'function') {
fn = title;
title = fn.name;
}
title = '"after each" hook' + (title ? ': ' + title : '');
var hook = new Hook(title, fn);
hook.parent = this;
hook.timeout(this.timeout());
hook.retries(this.retries());
hook.enableTimeouts(this.enableTimeouts());
hook.slow(this.slow());
hook.ctx = this.ctx;
this._afterEach.push(hook);
this.emit('afterEach', hook);
return this;
};
/**
* Add a test `suite`.
*
* @api private
* @param {Suite} suite
* @return {Suite} for chaining
*/
Suite.prototype.addSuite = function (suite) {
suite.parent = this;
suite.timeout(this.timeout());
suite.retries(this.retries());
suite.enableTimeouts(this.enableTimeouts());
suite.slow(this.slow());
suite.bail(this.bail());
this.suites.push(suite);
this.emit('suite', suite);
return this;
};
/**
* Add a `test` to this suite.
*
* @api private
* @param {Test} test
* @return {Suite} for chaining
*/
Suite.prototype.addTest = function (test) {
test.parent = this;
test.timeout(this.timeout());
test.retries(this.retries());
test.enableTimeouts(this.enableTimeouts());
test.slow(this.slow());
test.ctx = this.ctx;
this.tests.push(test);
this.emit('test', test);
return this;
};
/**
* Return the full title generated by recursively concatenating the parent's
* full title.
*
* @api public
* @return {string}
*/
Suite.prototype.fullTitle = function () {
if (this.parent) {
var full = this.parent.fullTitle();
if (full) {
return full + ' ' + this.title;
}
}
return this.title;
};
/**
* Return the total number of tests.
*
* @api public
* @return {number}
*/
Suite.prototype.total = function () {
return utils.reduce(this.suites, function (sum, suite) {
return sum + suite.total();
}, 0) + this.tests.length;
};
/**
* Iterates through each suite recursively to find all tests. Applies a
* function in the format `fn(test)`.
*
* @api private
* @param {Function} fn
* @return {Suite}
*/
Suite.prototype.eachTest = function (fn) {
utils.forEach(this.tests, fn);
utils.forEach(this.suites, function (suite) {
suite.eachTest(fn);
});
return this;
};
/**
* This will run the root suite if we happen to be running in delayed mode.
*/
Suite.prototype.run = function run () {
if (this.root) {
this.emit('run');
}
};
},{"./hook":7,"./ms":15,"./utils":38,"debug":2,"events":3}],36:[function(require,module,exports){
'use strict';
/**
* Module dependencies.
*/
var Runnable = require('./runnable');
var create = require('lodash.create');
var isString = require('./utils').isString;
/**
* Expose `Test`.
*/
module.exports = Test;
/**
* Initialize a new `Test` with the given `title` and callback `fn`.
*
* @api private
* @param {String} title
* @param {Function} fn
*/
function Test (title, fn) {
if (!isString(title)) {
throw new Error('Test `title` should be a "string" but "' + typeof title + '" was given instead.');
}
Runnable.call(this, title, fn);
this.pending = !fn;
this.type = 'test';
}
/**
* Inherit from `Runnable.prototype`.
*/
Test.prototype = create(Runnable.prototype, {
constructor: Test
});
Test.prototype.clone = function () {
var test = new Test(this.title, this.fn);
test.timeout(this.timeout());
test.slow(this.slow());
test.enableTimeouts(this.enableTimeouts());
test.retries(this.retries());
test.currentRetry(this.currentRetry());
test.globals(this.globals());
test.parent = this.parent;
test.file = this.file;
test.ctx = this.ctx;
return test;
};
},{"./runnable":33,"./utils":38,"lodash.create":60}],37:[function(require,module,exports){
'use strict';
/**
* Pad a `number` with a ten's place zero.
*
* @param {number} number
* @return {string}
*/
function pad(number) {
var n = number.toString();
return n.length === 1 ? '0' + n : n;
}
/**
* Turn a `date` into an ISO string.
*
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString
*
* @param {Date} date
* @return {string}
*/
function toISOString(date) {
return date.getUTCFullYear()
+ '-' + pad(date.getUTCMonth() + 1)
+ '-' + pad(date.getUTCDate())
+ 'T' + pad(date.getUTCHours())
+ ':' + pad(date.getUTCMinutes())
+ ':' + pad(date.getUTCSeconds())
+ '.' + String((date.getUTCMilliseconds()/1000).toFixed(3)).slice(2, 5)
+ 'Z';
}
/*
* Exports.
*/
module.exports = toISOString;
},{}],38:[function(require,module,exports){
(function (process,Buffer){
'use strict';
/* eslint-env browser */
/**
* Module dependencies.
*/
var JSON = require('json3');
var basename = require('path').basename;
var debug = require('debug')('mocha:watch');
var exists = require('fs').existsSync || require('path').existsSync;
var glob = require('glob');
var path = require('path');
var join = path.join;
var readdirSync = require('fs').readdirSync;
var statSync = require('fs').statSync;
var watchFile = require('fs').watchFile;
var lstatSync = require('fs').lstatSync;
var toISOString = require('./to-iso-string');
/**
* Ignored directories.
*/
var ignore = ['node_modules', '.git'];
exports.inherits = require('util').inherits;
/**
* Escape special characters in the given string of html.
*
* @api private
* @param {string} html
* @return {string}
*/
exports.escape = function (html) {
return String(html)
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/</g, '<')
.replace(/>/g, '>');
};
/**
* Array#forEach (<=IE8)
*
* @api private
* @param {Array} arr
* @param {Function} fn
* @param {Object} scope
*/
exports.forEach = function (arr, fn, scope) {
for (var i = 0, l = arr.length; i < l; i++) {
fn.call(scope, arr[i], i);
}
};
/**
* Test if the given obj is type of string.
*
* @api private
* @param {Object} obj
* @return {boolean}
*/
exports.isString = function (obj) {
return typeof obj === 'string';
};
/**
* Array#map (<=IE8)
*
* @api private
* @param {Array} arr
* @param {Function} fn
* @param {Object} scope
* @return {Array}
*/
exports.map = function (arr, fn, scope) {
var result = [];
for (var i = 0, l = arr.length; i < l; i++) {
result.push(fn.call(scope, arr[i], i, arr));
}
return result;
};
/**
* Array#indexOf (<=IE8)
*
* @api private
* @param {Array} arr
* @param {Object} obj to find index of
* @param {number} start
* @return {number}
*/
var indexOf = exports.indexOf = function (arr, obj, start) {
for (var i = start || 0, l = arr.length; i < l; i++) {
if (arr[i] === obj) {
return i;
}
}
return -1;
};
/**
* Array#reduce (<=IE8)
*
* @api private
* @param {Array} arr
* @param {Function} fn
* @param {Object} val Initial value.
* @return {*}
*/
var reduce = exports.reduce = function (arr, fn, val) {
var rval = val;
for (var i = 0, l = arr.length; i < l; i++) {
rval = fn(rval, arr[i], i, arr);
}
return rval;
};
/**
* Array#filter (<=IE8)
*
* @api private
* @param {Array} arr
* @param {Function} fn
* @return {Array}
*/
exports.filter = function (arr, fn) {
var ret = [];
for (var i = 0, l = arr.length; i < l; i++) {
var val = arr[i];
if (fn(val, i, arr)) {
ret.push(val);
}
}
return ret;
};
/**
* Array#some (<=IE8)
*
* @api private
* @param {Array} arr
* @param {Function} fn
* @return {Array}
*/
exports.some = function (arr, fn) {
for (var i = 0, l = arr.length; i < l; i++) {
if (fn(arr[i])) {
return true;
}
}
return false;
};
/**
* Object.keys (<=IE8)
*
* @api private
* @param {Object} obj
* @return {Array} keys
*/
exports.keys = typeof Object.keys === 'function' ? Object.keys : function (obj) {
var keys = [];
var has = Object.prototype.hasOwnProperty; // for `window` on <=IE8
for (var key in obj) {
if (has.call(obj, key)) {
keys.push(key);
}
}
return keys;
};
/**
* Watch the given `files` for changes
* and invoke `fn(file)` on modification.
*
* @api private
* @param {Array} files
* @param {Function} fn
*/
exports.watch = function (files, fn) {
var options = { interval: 100 };
files.forEach(function (file) {
debug('file %s', file);
watchFile(file, options, function (curr, prev) {
if (prev.mtime < curr.mtime) {
fn(file);
}
});
});
};
/**
* Array.isArray (<=IE8)
*
* @api private
* @param {Object} obj
* @return {Boolean}
*/
var isArray = typeof Array.isArray === 'function' ? Array.isArray : function (obj) {
return Object.prototype.toString.call(obj) === '[object Array]';
};
exports.isArray = isArray;
/**
* Buffer.prototype.toJSON polyfill.
*
* @type {Function}
*/
if (typeof Buffer !== 'undefined' && Buffer.prototype) {
Buffer.prototype.toJSON = Buffer.prototype.toJSON || function () {
return Array.prototype.slice.call(this, 0);
};
}
/**
* Ignored files.
*
* @api private
* @param {string} path
* @return {boolean}
*/
function ignored (path) {
return !~ignore.indexOf(path);
}
/**
* Lookup files in the given `dir`.
*
* @api private
* @param {string} dir
* @param {string[]} [ext=['.js']]
* @param {Array} [ret=[]]
* @return {Array}
*/
exports.files = function (dir, ext, ret) {
ret = ret || [];
ext = ext || ['js'];
var re = new RegExp('\\.(' + ext.join('|') + ')$');
readdirSync(dir)
.filter(ignored)
.forEach(function (path) {
path = join(dir, path);
if (lstatSync(path).isDirectory()) {
exports.files(path, ext, ret);
} else if (path.match(re)) {
ret.push(path);
}
});
return ret;
};
/**
* Compute a slug from the given `str`.
*
* @api private
* @param {string} str
* @return {string}
*/
exports.slug = function (str) {
return str
.toLowerCase()
.replace(/ +/g, '-')
.replace(/[^-\w]/g, '');
};
/**
* Strip the function definition from `str`, and re-indent for pre whitespace.
*
* @param {string} str
* @return {string}
*/
exports.clean = function (str) {
str = str
.replace(/\r\n?|[\n\u2028\u2029]/g, '\n').replace(/^\uFEFF/, '')
// (traditional)-> space/name parameters body (lambda)-> parameters body multi-statement/single keep body content
.replace(/^function(?:\s*|\s+[^(]*)\([^)]*\)\s*\{((?:.|\n)*?)\s*\}$|^\([^)]*\)\s*=>\s*(?:\{((?:.|\n)*?)\s*\}|((?:.|\n)*))$/, '$1$2$3');
var spaces = str.match(/^\n?( *)/)[1].length;
var tabs = str.match(/^\n?(\t*)/)[1].length;
var re = new RegExp('^\n?' + (tabs ? '\t' : ' ') + '{' + (tabs || spaces) + '}', 'gm');
str = str.replace(re, '');
return exports.trim(str);
};
/**
* Trim the given `str`.
*
* @api private
* @param {string} str
* @return {string}
*/
exports.trim = function (str) {
return str.replace(/^\s+|\s+$/g, '');
};
/**
* Parse the given `qs`.
*
* @api private
* @param {string} qs
* @return {Object}
*/
exports.parseQuery = function (qs) {
return reduce(qs.replace('?', '').split('&'), function (obj, pair) {
var i = pair.indexOf('=');
var key = pair.slice(0, i);
var val = pair.slice(++i);
obj[key] = decodeURIComponent(val);
return obj;
}, {});
};
/**
* Highlight the given string of `js`.
*
* @api private
* @param {string} js
* @return {string}
*/
function highlight (js) {
return js
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/\/\/(.*)/gm, '<span class="comment">//$1</span>')
.replace(/('.*?')/gm, '<span class="string">$1</span>')
.replace(/(\d+\.\d+)/gm, '<span class="number">$1</span>')
.replace(/(\d+)/gm, '<span class="number">$1</span>')
.replace(/\bnew[ \t]+(\w+)/gm, '<span class="keyword">new</span> <span class="init">$1</span>')
.replace(/\b(function|new|throw|return|var|if|else)\b/gm, '<span class="keyword">$1</span>');
}
/**
* Highlight the contents of tag `name`.
*
* @api private
* @param {string} name
*/
exports.highlightTags = function (name) {
var code = document.getElementById('mocha').getElementsByTagName(name);
for (var i = 0, len = code.length; i < len; ++i) {
code[i].innerHTML = highlight(code[i].innerHTML);
}
};
/**
* If a value could have properties, and has none, this function is called,
* which returns a string representation of the empty value.
*
* Functions w/ no properties return `'[Function]'`
* Arrays w/ length === 0 return `'[]'`
* Objects w/ no properties return `'{}'`
* All else: return result of `value.toString()`
*
* @api private
* @param {*} value The value to inspect.
* @param {string} typeHint The type of the value
* @returns {string}
*/
function emptyRepresentation (value, typeHint) {
switch (typeHint) {
case 'function':
return '[Function]';
case 'object':
return '{}';
case 'array':
return '[]';
default:
return value.toString();
}
}
/**
* Takes some variable and asks `Object.prototype.toString()` what it thinks it
* is.
*
* @api private
* @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString
* @param {*} value The value to test.
* @returns {string} Computed type
* @example
* type({}) // 'object'
* type([]) // 'array'
* type(1) // 'number'
* type(false) // 'boolean'
* type(Infinity) // 'number'
* type(null) // 'null'
* type(new Date()) // 'date'
* type(/foo/) // 'regexp'
* type('type') // 'string'
* type(global) // 'global'
* type(new String('foo') // 'object'
*/
var type = exports.type = function type (value) {
if (value === undefined) {
return 'undefined';
} else if (value === null) {
return 'null';
} else if (typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) {
return 'buffer';
}
return Object.prototype.toString.call(value)
.replace(/^\[.+\s(.+?)\]$/, '$1')
.toLowerCase();
};
/**
* Stringify `value`. Different behavior depending on type of value:
*
* - If `value` is undefined or null, return `'[undefined]'` or `'[null]'`, respectively.
* - If `value` is not an object, function or array, return result of `value.toString()` wrapped in double-quotes.
* - If `value` is an *empty* object, function, or array, return result of function
* {@link emptyRepresentation}.
* - If `value` has properties, call {@link exports.canonicalize} on it, then return result of
* JSON.stringify().
*
* @api private
* @see exports.type
* @param {*} value
* @return {string}
*/
exports.stringify = function (value) {
var typeHint = type(value);
if (!~indexOf(['object', 'array', 'function'], typeHint)) {
if (typeHint === 'buffer') {
var json = value.toJSON();
// Based on the toJSON result
return jsonStringify(json.data && json.type ? json.data : json, 2)
.replace(/,(\n|$)/g, '$1');
}
// IE7/IE8 has a bizarre String constructor; needs to be coerced
// into an array and back to obj.
if (typeHint === 'string' && typeof value === 'object') {
value = reduce(value.split(''), function (acc, char, idx) {
acc[idx] = char;
return acc;
}, {});
typeHint = 'object';
} else {
return jsonStringify(value);
}
}
for (var prop in value) {
if (Object.prototype.hasOwnProperty.call(value, prop)) {
return jsonStringify(exports.canonicalize(value, null, typeHint), 2).replace(/,(\n|$)/g, '$1');
}
}
return emptyRepresentation(value, typeHint);
};
/**
* like JSON.stringify but more sense.
*
* @api private
* @param {Object} object
* @param {number=} spaces
* @param {number=} depth
* @returns {*}
*/
function jsonStringify (object, spaces, depth) {
if (typeof spaces === 'undefined') {
// primitive types
return _stringify(object);
}
depth = depth || 1;
var space = spaces * depth;
var str = isArray(object) ? '[' : '{';
var end = isArray(object) ? ']' : '}';
var length = typeof object.length === 'number' ? object.length : exports.keys(object).length;
// `.repeat()` polyfill
function repeat (s, n) {
return new Array(n).join(s);
}
function _stringify (val) {
switch (type(val)) {
case 'null':
case 'undefined':
val = '[' + val + ']';
break;
case 'array':
case 'object':
val = jsonStringify(val, spaces, depth + 1);
break;
case 'boolean':
case 'regexp':
case 'symbol':
case 'number':
val = val === 0 && (1 / val) === -Infinity // `-0`
? '-0'
: val.toString();
break;
case 'date':
var sDate;
if (isNaN(val.getTime())) { // Invalid date
sDate = val.toString();
} else {
sDate = val.toISOString ? val.toISOString() : toISOString(val);
}
val = '[Date: ' + sDate + ']';
break;
case 'buffer':
var json = val.toJSON();
// Based on the toJSON result
json = json.data && json.type ? json.data : json;
val = '[Buffer: ' + jsonStringify(json, 2, depth + 1) + ']';
break;
default:
val = (val === '[Function]' || val === '[Circular]')
? val
: JSON.stringify(val); // string
}
return val;
}
for (var i in object) {
if (!Object.prototype.hasOwnProperty.call(object, i)) {
continue; // not my business
}
--length;
str += '\n ' + repeat(' ', space) +
(isArray(object) ? '' : '"' + i + '": ') + // key
_stringify(object[i]) + // value
(length ? ',' : ''); // comma
}
return str +
// [], {}
(str.length !== 1 ? '\n' + repeat(' ', --space) + end : end);
}
/**
* Test if a value is a buffer.
*
* @api private
* @param {*} value The value to test.
* @return {boolean} True if `value` is a buffer, otherwise false
*/
exports.isBuffer = function (value) {
return typeof Buffer !== 'undefined' && Buffer.isBuffer(value);
};
/**
* Return a new Thing that has the keys in sorted order. Recursive.
*
* If the Thing...
* - has already been seen, return string `'[Circular]'`
* - is `undefined`, return string `'[undefined]'`
* - is `null`, return value `null`
* - is some other primitive, return the value
* - is not a primitive or an `Array`, `Object`, or `Function`, return the value of the Thing's `toString()` method
* - is a non-empty `Array`, `Object`, or `Function`, return the result of calling this function again.
* - is an empty `Array`, `Object`, or `Function`, return the result of calling `emptyRepresentation()`
*
* @api private
* @see {@link exports.stringify}
* @param {*} value Thing to inspect. May or may not have properties.
* @param {Array} [stack=[]] Stack of seen values
* @param {string} [typeHint] Type hint
* @return {(Object|Array|Function|string|undefined)}
*/
exports.canonicalize = function canonicalize (value, stack, typeHint) {
var canonicalizedObj;
/* eslint-disable no-unused-vars */
var prop;
/* eslint-enable no-unused-vars */
typeHint = typeHint || type(value);
function withStack (value, fn) {
stack.push(value);
fn();
stack.pop();
}
stack = stack || [];
if (indexOf(stack, value) !== -1) {
return '[Circular]';
}
switch (typeHint) {
case 'undefined':
case 'buffer':
case 'null':
canonicalizedObj = value;
break;
case 'array':
withStack(value, function () {
canonicalizedObj = exports.map(value, function (item) {
return exports.canonicalize(item, stack);
});
});
break;
case 'function':
/* eslint-disable guard-for-in */
for (prop in value) {
canonicalizedObj = {};
break;
}
/* eslint-enable guard-for-in */
if (!canonicalizedObj) {
canonicalizedObj = emptyRepresentation(value, typeHint);
break;
}
/* falls through */
case 'object':
canonicalizedObj = canonicalizedObj || {};
withStack(value, function () {
exports.forEach(exports.keys(value).sort(), function (key) {
canonicalizedObj[key] = exports.canonicalize(value[key], stack);
});
});
break;
case 'date':
case 'number':
case 'regexp':
case 'boolean':
case 'symbol':
canonicalizedObj = value;
break;
default:
canonicalizedObj = value + '';
}
return canonicalizedObj;
};
/**
* Lookup file names at the given `path`.
*
* @api public
* @param {string} path Base path to start searching from.
* @param {string[]} extensions File extensions to look for.
* @param {boolean} recursive Whether or not to recurse into subdirectories.
* @return {string[]} An array of paths.
*/
exports.lookupFiles = function lookupFiles (path, extensions, recursive) {
var files = [];
var re = new RegExp('\\.(' + extensions.join('|') + ')$');
if (!exists(path)) {
if (exists(path + '.js')) {
path += '.js';
} else {
files = glob.sync(path);
if (!files.length) {
throw new Error("cannot resolve path (or pattern) '" + path + "'");
}
return files;
}
}
try {
var stat = statSync(path);
if (stat.isFile()) {
return path;
}
} catch (err) {
// ignore error
return;
}
readdirSync(path).forEach(function (file) {
file = join(path, file);
try {
var stat = statSync(file);
if (stat.isDirectory()) {
if (recursive) {
files = files.concat(lookupFiles(file, extensions, recursive));
}
return;
}
} catch (err) {
// ignore error
return;
}
if (!stat.isFile() || !re.test(file) || basename(file)[0] === '.') {
return;
}
files.push(file);
});
return files;
};
/**
* Generate an undefined error with a message warning the user.
*
* @return {Error}
*/
exports.undefinedError = function () {
return new Error('Caught undefined error, did you throw without specifying what?');
};
/**
* Generate an undefined error if `err` is not defined.
*
* @param {Error} err
* @return {Error}
*/
exports.getError = function (err) {
return err || exports.undefinedError();
};
/**
* @summary
* This Filter based on `mocha-clean` module.(see: `github.com/rstacruz/mocha-clean`)
* @description
* When invoking this function you get a filter function that get the Error.stack as an input,
* and return a prettify output.
* (i.e: strip Mocha and internal node functions from stack trace).
* @returns {Function}
*/
exports.stackTraceFilter = function () {
// TODO: Replace with `process.browser`
var is = typeof document === 'undefined' ? { node: true } : { browser: true };
var slash = path.sep;
var cwd;
if (is.node) {
cwd = process.cwd() + slash;
} else {
cwd = (typeof location === 'undefined' ? window.location : location).href.replace(/\/[^\/]*$/, '/');
slash = '/';
}
function isMochaInternal (line) {
return (~line.indexOf('node_modules' + slash + 'mocha' + slash)) ||
(~line.indexOf('node_modules' + slash + 'mocha.js')) ||
(~line.indexOf('bower_components' + slash + 'mocha.js')) ||
(~line.indexOf(slash + 'mocha.js'));
}
function isNodeInternal (line) {
return (~line.indexOf('(timers.js:')) ||
(~line.indexOf('(events.js:')) ||
(~line.indexOf('(node.js:')) ||
(~line.indexOf('(module.js:')) ||
(~line.indexOf('GeneratorFunctionPrototype.next (native)')) ||
false;
}
return function (stack) {
stack = stack.split('\n');
stack = reduce(stack, function (list, line) {
if (isMochaInternal(line)) {
return list;
}
if (is.node && isNodeInternal(line)) {
return list;
}
// Clean up cwd(absolute)
if (/\(?.+:\d+:\d+\)?$/.test(line)) {
line = line.replace(cwd, '');
}
list.push(line);
return list;
}, []);
return stack.join('\n');
};
};
/**
* Crude, but effective.
* @api
* @param {*} value
* @returns {boolean} Whether or not `value` is a Promise
*/
exports.isPromise = function isPromise (value) {
return typeof value === 'object' && typeof value.then === 'function';
};
/**
* It's a noop.
* @api
*/
exports.noop = function () {};
}).call(this,require('_process'),require("buffer").Buffer)
},{"./to-iso-string":37,"_process":67,"buffer":44,"debug":2,"fs":42,"glob":42,"json3":54,"path":42,"util":84}],39:[function(require,module,exports){
'use strict'
exports.byteLength = byteLength
exports.toByteArray = toByteArray
exports.fromByteArray = fromByteArray
var lookup = []
var revLookup = []
var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
for (var i = 0, len = code.length; i < len; ++i) {
lookup[i] = code[i]
revLookup[code.charCodeAt(i)] = i
}
revLookup['-'.charCodeAt(0)] = 62
revLookup['_'.charCodeAt(0)] = 63
function placeHoldersCount (b64) {
var len = b64.length
if (len % 4 > 0) {
throw new Error('Invalid string. Length must be a multiple of 4')
}
// the number of equal signs (place holders)
// if there are two placeholders, than the two characters before it
// represent one byte
// if there is only one, then the three characters before it represent 2 bytes
// this is just a cheap hack to not do indexOf twice
return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0
}
function byteLength (b64) {
// base64 is 4/3 + up to two characters of the original data
return b64.length * 3 / 4 - placeHoldersCount(b64)
}
function toByteArray (b64) {
var i, j, l, tmp, placeHolders, arr
var len = b64.length
placeHolders = placeHoldersCount(b64)
arr = new Arr(len * 3 / 4 - placeHolders)
// if there are placeholders, only get up to the last complete 4 chars
l = placeHolders > 0 ? len - 4 : len
var L = 0
for (i = 0, j = 0; i < l; i += 4, j += 3) {
tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]
arr[L++] = (tmp >> 16) & 0xFF
arr[L++] = (tmp >> 8) & 0xFF
arr[L++] = tmp & 0xFF
}
if (placeHolders === 2) {
tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4)
arr[L++] = tmp & 0xFF
} else if (placeHolders === 1) {
tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2)
arr[L++] = (tmp >> 8) & 0xFF
arr[L++] = tmp & 0xFF
}
return arr
}
function tripletToBase64 (num) {
return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
}
function encodeChunk (uint8, start, end) {
var tmp
var output = []
for (var i = start; i < end; i += 3) {
tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
output.push(tripletToBase64(tmp))
}
return output.join('')
}
function fromByteArray (uint8) {
var tmp
var len = uint8.length
var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
var output = ''
var parts = []
var maxChunkLength = 16383 // must be multiple of 3
// go through the array every three bytes, we'll deal with trailing stuff later
for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
}
// pad the end with zeros, but make sure to not forget the extra bytes
if (extraBytes === 1) {
tmp = uint8[len - 1]
output += lookup[tmp >> 2]
output += lookup[(tmp << 4) & 0x3F]
output += '=='
} else if (extraBytes === 2) {
tmp = (uint8[len - 2] << 8) + (uint8[len - 1])
output += lookup[tmp >> 10]
output += lookup[(tmp >> 4) & 0x3F]
output += lookup[(tmp << 2) & 0x3F]
output += '='
}
parts.push(output)
return parts.join('')
}
},{}],40:[function(require,module,exports){
},{}],41:[function(require,module,exports){
(function (process){
var WritableStream = require('stream').Writable
var inherits = require('util').inherits
module.exports = BrowserStdout
inherits(BrowserStdout, WritableStream)
function BrowserStdout(opts) {
if (!(this instanceof BrowserStdout)) return new BrowserStdout(opts)
opts = opts || {}
WritableStream.call(this, opts)
this.label = (opts.label !== undefined) ? opts.label : 'stdout'
}
BrowserStdout.prototype._write = function(chunks, encoding, cb) {
var output = chunks.toString ? chunks.toString() : chunks
if (this.label === false) {
console.log(output)
} else {
console.log(this.label+':', output)
}
process.nextTick(cb)
}
}).call(this,require('_process'))
},{"_process":67,"stream":79,"util":84}],42:[function(require,module,exports){
arguments[4][40][0].apply(exports,arguments)
},{"dup":40}],43:[function(require,module,exports){
(function (global){
'use strict';
var buffer = require('buffer');
var Buffer = buffer.Buffer;
var SlowBuffer = buffer.SlowBuffer;
var MAX_LEN = buffer.kMaxLength || 2147483647;
exports.alloc = function alloc(size, fill, encoding) {
if (typeof Buffer.alloc === 'function') {
return Buffer.alloc(size, fill, encoding);
}
if (typeof encoding === 'number') {
throw new TypeError('encoding must not be number');
}
if (typeof size !== 'number') {
throw new TypeError('size must be a number');
}
if (size > MAX_LEN) {
throw new RangeError('size is too large');
}
var enc = encoding;
var _fill = fill;
if (_fill === undefined) {
enc = undefined;
_fill = 0;
}
var buf = new Buffer(size);
if (typeof _fill === 'string') {
var fillBuf = new Buffer(_fill, enc);
var flen = fillBuf.length;
var i = -1;
while (++i < size) {
buf[i] = fillBuf[i % flen];
}
} else {
buf.fill(_fill);
}
return buf;
}
exports.allocUnsafe = function allocUnsafe(size) {
if (typeof Buffer.allocUnsafe === 'function') {
return Buffer.allocUnsafe(size);
}
if (typeof size !== 'number') {
throw new TypeError('size must be a number');
}
if (size > MAX_LEN) {
throw new RangeError('size is too large');
}
return new Buffer(size);
}
exports.from = function from(value, encodingOrOffset, length) {
if (typeof Buffer.from === 'function' && (!global.Uint8Array || Uint8Array.from !== Buffer.from)) {
return Buffer.from(value, encodingOrOffset, length);
}
if (typeof value === 'number') {
throw new TypeError('"value" argument must not be a number');
}
if (typeof value === 'string') {
return new Buffer(value, encodingOrOffset);
}
if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
var offset = encodingOrOffset;
if (arguments.length === 1) {
return new Buffer(value);
}
if (typeof offset === 'undefined') {
offset = 0;
}
var len = length;
if (typeof len === 'undefined') {
len = value.byteLength - offset;
}
if (offset >= value.byteLength) {
throw new RangeError('\'offset\' is out of bounds');
}
if (len > value.byteLength - offset) {
throw new RangeError('\'length\' is out of bounds');
}
return new Buffer(value.slice(offset, offset + len));
}
if (Buffer.isBuffer(value)) {
var out = new Buffer(value.length);
value.copy(out, 0, 0, value.length);
return out;
}
if (value) {
if (Array.isArray(value) || (typeof ArrayBuffer !== 'undefined' && value.buffer instanceof ArrayBuffer) || 'length' in value) {
return new Buffer(value);
}
if (value.type === 'Buffer' && Array.isArray(value.data)) {
return new Buffer(value.data);
}
}
throw new TypeError('First argument must be a string, Buffer, ' + 'ArrayBuffer, Array, or array-like object.');
}
exports.allocUnsafeSlow = function allocUnsafeSlow(size) {
if (typeof Buffer.allocUnsafeSlow === 'function') {
return Buffer.allocUnsafeSlow(size);
}
if (typeof size !== 'number') {
throw new TypeError('size must be a number');
}
if (size >= MAX_LEN) {
throw new RangeError('size is too large');
}
return new SlowBuffer(size);
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"buffer":44}],44:[function(require,module,exports){
(function (global){
/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
* @license MIT
*/
/* eslint-disable no-proto */
'use strict'
var base64 = require('base64-js')
var ieee754 = require('ieee754')
var isArray = require('isarray')
exports.Buffer = Buffer
exports.SlowBuffer = SlowBuffer
exports.INSPECT_MAX_BYTES = 50
/**
* If `Buffer.TYPED_ARRAY_SUPPORT`:
* === true Use Uint8Array implementation (fastest)
* === false Use Object implementation (most compatible, even IE6)
*
* Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
* Opera 11.6+, iOS 4.2+.
*
* Due to various browser bugs, sometimes the Object implementation will be used even
* when the browser supports typed arrays.
*
* Note:
*
* - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
* See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
*
* - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
*
* - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
* incorrect length in some situations.
* We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
* get the Object implementation, which is slower but behaves correctly.
*/
Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
? global.TYPED_ARRAY_SUPPORT
: typedArraySupport()
/*
* Export kMaxLength after typed array support is determined.
*/
exports.kMaxLength = kMaxLength()
function typedArraySupport () {
try {
var arr = new Uint8Array(1)
arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
return arr.foo() === 42 && // typed array instances can be augmented
typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
} catch (e) {
return false
}
}
function kMaxLength () {
return Buffer.TYPED_ARRAY_SUPPORT
? 0x7fffffff
: 0x3fffffff
}
function createBuffer (that, length) {
if (kMaxLength() < length) {
throw new RangeError('Invalid typed array length')
}
if (Buffer.TYPED_ARRAY_SUPPORT) {
// Return an augmented `Uint8Array` instance, for best performance
that = new Uint8Array(length)
that.__proto__ = Buffer.prototype
} else {
// Fallback: Return an object instance of the Buffer class
if (that === null) {
that = new Buffer(length)
}
that.length = length
}
return that
}
/**
* The Buffer constructor returns instances of `Uint8Array` that have their
* prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
* `Uint8Array`, so the returned instances will have all the node `Buffer` methods
* and the `Uint8Array` methods. Square bracket notation works as expected -- it
* returns a single octet.
*
* The `Uint8Array` prototype remains unmodified.
*/
function Buffer (arg, encodingOrOffset, length) {
if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
return new Buffer(arg, encodingOrOffset, length)
}
// Common case.
if (typeof arg === 'number') {
if (typeof encodingOrOffset === 'string') {
throw new Error(
'If encoding is specified then the first argument must be a string'
)
}
return allocUnsafe(this, arg)
}
return from(this, arg, encodingOrOffset, length)
}
Buffer.poolSize = 8192 // not used by this implementation
// TODO: Legacy, not needed anymore. Remove in next major version.
Buffer._augment = function (arr) {
arr.__proto__ = Buffer.prototype
return arr
}
function from (that, value, encodingOrOffset, length) {
if (typeof value === 'number') {
throw new TypeError('"value" argument must not be a number')
}
if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
return fromArrayBuffer(that, value, encodingOrOffset, length)
}
if (typeof value === 'string') {
return fromString(that, value, encodingOrOffset)
}
return fromObject(that, value)
}
/**
* Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
* if value is a number.
* Buffer.from(str[, encoding])
* Buffer.from(array)
* Buffer.from(buffer)
* Buffer.from(arrayBuffer[, byteOffset[, length]])
**/
Buffer.from = function (value, encodingOrOffset, length) {
return from(null, value, encodingOrOffset, length)
}
if (Buffer.TYPED_ARRAY_SUPPORT) {
Buffer.prototype.__proto__ = Uint8Array.prototype
Buffer.__proto__ = Uint8Array
if (typeof Symbol !== 'undefined' && Symbol.species &&
Buffer[Symbol.species] === Buffer) {
// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
Object.defineProperty(Buffer, Symbol.species, {
value: null,
configurable: true
})
}
}
function assertSize (size) {
if (typeof size !== 'number') {
throw new TypeError('"size" argument must be a number')
} else if (size < 0) {
throw new RangeError('"size" argument must not be negative')
}
}
function alloc (that, size, fill, encoding) {
assertSize(size)
if (size <= 0) {
return createBuffer(that, size)
}
if (fill !== undefined) {
// Only pay attention to encoding if it's a string. This
// prevents accidentally sending in a number that would
// be interpretted as a start offset.
return typeof encoding === 'string'
? createBuffer(that, size).fill(fill, encoding)
: createBuffer(that, size).fill(fill)
}
return createBuffer(that, size)
}
/**
* Creates a new filled Buffer instance.
* alloc(size[, fill[, encoding]])
**/
Buffer.alloc = function (size, fill, encoding) {
return alloc(null, size, fill, encoding)
}
function allocUnsafe (that, size) {
assertSize(size)
that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)
if (!Buffer.TYPED_ARRAY_SUPPORT) {
for (var i = 0; i < size; ++i) {
that[i] = 0
}
}
return that
}
/**
* Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
* */
Buffer.allocUnsafe = function (size) {
return allocUnsafe(null, size)
}
/**
* Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
*/
Buffer.allocUnsafeSlow = function (size) {
return allocUnsafe(null, size)
}
function fromString (that, string, encoding) {
if (typeof encoding !== 'string' || encoding === '') {
encoding = 'utf8'
}
if (!Buffer.isEncoding(encoding)) {
throw new TypeError('"encoding" must be a valid string encoding')
}
var length = byteLength(string, encoding) | 0
that = createBuffer(that, length)
var actual = that.write(string, encoding)
if (actual !== length) {
// Writing a hex string, for example, that contains invalid characters will
// cause everything after the first invalid character to be ignored. (e.g.
// 'abxxcd' will be treated as 'ab')
that = that.slice(0, actual)
}
return that
}
function fromArrayLike (that, array) {
var length = array.length < 0 ? 0 : checked(array.length) | 0
that = createBuffer(that, length)
for (var i = 0; i < length; i += 1) {
that[i] = array[i] & 255
}
return that
}
function fromArrayBuffer (that, array, byteOffset, length) {
array.byteLength // this throws if `array` is not a valid ArrayBuffer
if (byteOffset < 0 || array.byteLength < byteOffset) {
throw new RangeError('\'offset\' is out of bounds')
}
if (array.byteLength < byteOffset + (length || 0)) {
throw new RangeError('\'length\' is out of bounds')
}
if (byteOffset === undefined && length === undefined) {
array = new Uint8Array(array)
} else if (length === undefined) {
array = new Uint8Array(array, byteOffset)
} else {
array = new Uint8Array(array, byteOffset, length)
}
if (Buffer.TYPED_ARRAY_SUPPORT) {
// Return an augmented `Uint8Array` instance, for best performance
that = array
that.__proto__ = Buffer.prototype
} else {
// Fallback: Return an object instance of the Buffer class
that = fromArrayLike(that, array)
}
return that
}
function fromObject (that, obj) {
if (Buffer.isBuffer(obj)) {
var len = checked(obj.length) | 0
that = createBuffer(that, len)
if (that.length === 0) {
return that
}
obj.copy(that, 0, 0, len)
return that
}
if (obj) {
if ((typeof ArrayBuffer !== 'undefined' &&
obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
if (typeof obj.length !== 'number' || isnan(obj.length)) {
return createBuffer(that, 0)
}
return fromArrayLike(that, obj)
}
if (obj.type === 'Buffer' && isArray(obj.data)) {
return fromArrayLike(that, obj.data)
}
}
throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
}
function checked (length) {
// Note: cannot use `length < kMaxLength()` here because that fails when
// length is NaN (which is otherwise coerced to zero.)
if (length >= kMaxLength()) {
throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
'size: 0x' + kMaxLength().toString(16) + ' bytes')
}
return length | 0
}
function SlowBuffer (length) {
if (+length != length) { // eslint-disable-line eqeqeq
length = 0
}
return Buffer.alloc(+length)
}
Buffer.isBuffer = function isBuffer (b) {
return !!(b != null && b._isBuffer)
}
Buffer.compare = function compare (a, b) {
if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
throw new TypeError('Arguments must be Buffers')
}
if (a === b) return 0
var x = a.length
var y = b.length
for (var i = 0, len = Math.min(x, y); i < len; ++i) {
if (a[i] !== b[i]) {
x = a[i]
y = b[i]
break
}
}
if (x < y) return -1
if (y < x) return 1
return 0
}
Buffer.isEncoding = function isEncoding (encoding) {
switch (String(encoding).toLowerCase()) {
case 'hex':
case 'utf8':
case 'utf-8':
case 'ascii':
case 'latin1':
case 'binary':
case 'base64':
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return true
default:
return false
}
}
Buffer.concat = function concat (list, length) {
if (!isArray(list)) {
throw new TypeError('"list" argument must be an Array of Buffers')
}
if (list.length === 0) {
return Buffer.alloc(0)
}
var i
if (length === undefined) {
length = 0
for (i = 0; i < list.length; ++i) {
length += list[i].length
}
}
var buffer = Buffer.allocUnsafe(length)
var pos = 0
for (i = 0; i < list.length; ++i) {
var buf = list[i]
if (!Buffer.isBuffer(buf)) {
throw new TypeError('"list" argument must be an Array of Buffers')
}
buf.copy(buffer, pos)
pos += buf.length
}
return buffer
}
function byteLength (string, encoding) {
if (Buffer.isBuffer(string)) {
return string.length
}
if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
(ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
return string.byteLength
}
if (typeof string !== 'string') {
string = '' + string
}
var len = string.length
if (len === 0) return 0
// Use a for loop to avoid recursion
var loweredCase = false
for (;;) {
switch (encoding) {
case 'ascii':
case 'latin1':
case 'binary':
return len
case 'utf8':
case 'utf-8':
case undefined:
return utf8ToBytes(string).length
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return len * 2
case 'hex':
return len >>> 1
case 'base64':
return base64ToBytes(string).length
default:
if (loweredCase) return utf8ToBytes(string).length // assume utf8
encoding = ('' + encoding).toLowerCase()
loweredCase = true
}
}
}
Buffer.byteLength = byteLength
function slowToString (encoding, start, end) {
var loweredCase = false
// No need to verify that "this.length <= MAX_UINT32" since it's a read-only
// property of a typed array.
// This behaves neither like String nor Uint8Array in that we set start/end
// to their upper/lower bounds if the value passed is out of range.
// undefined is handled specially as per ECMA-262 6th Edition,
// Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
if (start === undefined || start < 0) {
start = 0
}
// Return early if start > this.length. Done here to prevent potential uint32
// coercion fail below.
if (start > this.length) {
return ''
}
if (end === undefined || end > this.length) {
end = this.length
}
if (end <= 0) {
return ''
}
// Force coersion to uint32. This will also coerce falsey/NaN values to 0.
end >>>= 0
start >>>= 0
if (end <= start) {
return ''
}
if (!encoding) encoding = 'utf8'
while (true) {
switch (encoding) {
case 'hex':
return hexSlice(this, start, end)
case 'utf8':
case 'utf-8':
return utf8Slice(this, start, end)
case 'ascii':
return asciiSlice(this, start, end)
case 'latin1':
case 'binary':
return latin1Slice(this, start, end)
case 'base64':
return base64Slice(this, start, end)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return utf16leSlice(this, start, end)
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = (encoding + '').toLowerCase()
loweredCase = true
}
}
}
// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
// Buffer instances.
Buffer.prototype._isBuffer = true
function swap (b, n, m) {
var i = b[n]
b[n] = b[m]
b[m] = i
}
Buffer.prototype.swap16 = function swap16 () {
var len = this.length
if (len % 2 !== 0) {
throw new RangeError('Buffer size must be a multiple of 16-bits')
}
for (var i = 0; i < len; i += 2) {
swap(this, i, i + 1)
}
return this
}
Buffer.prototype.swap32 = function swap32 () {
var len = this.length
if (len % 4 !== 0) {
throw new RangeError('Buffer size must be a multiple of 32-bits')
}
for (var i = 0; i < len; i += 4) {
swap(this, i, i + 3)
swap(this, i + 1, i + 2)
}
return this
}
Buffer.prototype.swap64 = function swap64 () {
var len = this.length
if (len % 8 !== 0) {
throw new RangeError('Buffer size must be a multiple of 64-bits')
}
for (var i = 0; i < len; i += 8) {
swap(this, i, i + 7)
swap(this, i + 1, i + 6)
swap(this, i + 2, i + 5)
swap(this, i + 3, i + 4)
}
return this
}
Buffer.prototype.toString = function toString () {
var length = this.length | 0
if (length === 0) return ''
if (arguments.length === 0) return utf8Slice(this, 0, length)
return slowToString.apply(this, arguments)
}
Buffer.prototype.equals = function equals (b) {
if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
if (this === b) return true
return Buffer.compare(this, b) === 0
}
Buffer.prototype.inspect = function inspect () {
var str = ''
var max = exports.INSPECT_MAX_BYTES
if (this.length > 0) {
str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
if (this.length > max) str += ' ... '
}
return '<Buffer ' + str + '>'
}
Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
if (!Buffer.isBuffer(target)) {
throw new TypeError('Argument must be a Buffer')
}
if (start === undefined) {
start = 0
}
if (end === undefined) {
end = target ? target.length : 0
}
if (thisStart === undefined) {
thisStart = 0
}
if (thisEnd === undefined) {
thisEnd = this.length
}
if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
throw new RangeError('out of range index')
}
if (thisStart >= thisEnd && start >= end) {
return 0
}
if (thisStart >= thisEnd) {
return -1
}
if (start >= end) {
return 1
}
start >>>= 0
end >>>= 0
thisStart >>>= 0
thisEnd >>>= 0
if (this === target) return 0
var x = thisEnd - thisStart
var y = end - start
var len = Math.min(x, y)
var thisCopy = this.slice(thisStart, thisEnd)
var targetCopy = target.slice(start, end)
for (var i = 0; i < len; ++i) {
if (thisCopy[i] !== targetCopy[i]) {
x = thisCopy[i]
y = targetCopy[i]
break
}
}
if (x < y) return -1
if (y < x) return 1
return 0
}
// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
//
// Arguments:
// - buffer - a Buffer to search
// - val - a string, Buffer, or number
// - byteOffset - an index into `buffer`; will be clamped to an int32
// - encoding - an optional encoding, relevant is val is a string
// - dir - true for indexOf, false for lastIndexOf
function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
// Empty buffer means no match
if (buffer.length === 0) return -1
// Normalize byteOffset
if (typeof byteOffset === 'string') {
encoding = byteOffset
byteOffset = 0
} else if (byteOffset > 0x7fffffff) {
byteOffset = 0x7fffffff
} else if (byteOffset < -0x80000000) {
byteOffset = -0x80000000
}
byteOffset = +byteOffset // Coerce to Number.
if (isNaN(byteOffset)) {
// byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
byteOffset = dir ? 0 : (buffer.length - 1)
}
// Normalize byteOffset: negative offsets start from the end of the buffer
if (byteOffset < 0) byteOffset = buffer.length + byteOffset
if (byteOffset >= buffer.length) {
if (dir) return -1
else byteOffset = buffer.length - 1
} else if (byteOffset < 0) {
if (dir) byteOffset = 0
else return -1
}
// Normalize val
if (typeof val === 'string') {
val = Buffer.from(val, encoding)
}
// Finally, search either indexOf (if dir is true) or lastIndexOf
if (Buffer.isBuffer(val)) {
// Special case: looking for empty string/buffer always fails
if (val.length === 0) {
return -1
}
return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
} else if (typeof val === 'number') {
val = val & 0xFF // Search for a byte value [0-255]
if (Buffer.TYPED_ARRAY_SUPPORT &&
typeof Uint8Array.prototype.indexOf === 'function') {
if (dir) {
return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
} else {
return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
}
}
return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
}
throw new TypeError('val must be string, number or Buffer')
}
function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
var indexSize = 1
var arrLength = arr.length
var valLength = val.length
if (encoding !== undefined) {
encoding = String(encoding).toLowerCase()
if (encoding === 'ucs2' || encoding === 'ucs-2' ||
encoding === 'utf16le' || encoding === 'utf-16le') {
if (arr.length < 2 || val.length < 2) {
return -1
}
indexSize = 2
arrLength /= 2
valLength /= 2
byteOffset /= 2
}
}
function read (buf, i) {
if (indexSize === 1) {
return buf[i]
} else {
return buf.readUInt16BE(i * indexSize)
}
}
var i
if (dir) {
var foundIndex = -1
for (i = byteOffset; i < arrLength; i++) {
if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
if (foundIndex === -1) foundIndex = i
if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
} else {
if (foundIndex !== -1) i -= i - foundIndex
foundIndex = -1
}
}
} else {
if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
for (i = byteOffset; i >= 0; i--) {
var found = true
for (var j = 0; j < valLength; j++) {
if (read(arr, i + j) !== read(val, j)) {
found = false
break
}
}
if (found) return i
}
}
return -1
}
Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
return this.indexOf(val, byteOffset, encoding) !== -1
}
Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
}
Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
}
function hexWrite (buf, string, offset, length) {
offset = Number(offset) || 0
var remaining = buf.length - offset
if (!length) {
length = remaining
} else {
length = Number(length)
if (length > remaining) {
length = remaining
}
}
// must be an even number of digits
var strLen = string.length
if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
if (length > strLen / 2) {
length = strLen / 2
}
for (var i = 0; i < length; ++i) {
var parsed = parseInt(string.substr(i * 2, 2), 16)
if (isNaN(parsed)) return i
buf[offset + i] = parsed
}
return i
}
function utf8Write (buf, string, offset, length) {
return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
}
function asciiWrite (buf, string, offset, length) {
return blitBuffer(asciiToBytes(string), buf, offset, length)
}
function latin1Write (buf, string, offset, length) {
return asciiWrite(buf, string, offset, length)
}
function base64Write (buf, string, offset, length) {
return blitBuffer(base64ToBytes(string), buf, offset, length)
}
function ucs2Write (buf, string, offset, length) {
return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
}
Buffer.prototype.write = function write (string, offset, length, encoding) {
// Buffer#write(string)
if (offset === undefined) {
encoding = 'utf8'
length = this.length
offset = 0
// Buffer#write(string, encoding)
} else if (length === undefined && typeof offset === 'string') {
encoding = offset
length = this.length
offset = 0
// Buffer#write(string, offset[, length][, encoding])
} else if (isFinite(offset)) {
offset = offset | 0
if (isFinite(length)) {
length = length | 0
if (encoding === undefined) encoding = 'utf8'
} else {
encoding = length
length = undefined
}
// legacy write(string, encoding, offset, length) - remove in v0.13
} else {
throw new Error(
'Buffer.write(string, encoding, offset[, length]) is no longer supported'
)
}
var remaining = this.length - offset
if (length === undefined || length > remaining) length = remaining
if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
throw new RangeError('Attempt to write outside buffer bounds')
}
if (!encoding) encoding = 'utf8'
var loweredCase = false
for (;;) {
switch (encoding) {
case 'hex':
return hexWrite(this, string, offset, length)
case 'utf8':
case 'utf-8':
return utf8Write(this, string, offset, length)
case 'ascii':
return asciiWrite(this, string, offset, length)
case 'latin1':
case 'binary':
return latin1Write(this, string, offset, length)
case 'base64':
// Warning: maxLength not taken into account in base64Write
return base64Write(this, string, offset, length)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return ucs2Write(this, string, offset, length)
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = ('' + encoding).toLowerCase()
loweredCase = true
}
}
}
Buffer.prototype.toJSON = function toJSON () {
return {
type: 'Buffer',
data: Array.prototype.slice.call(this._arr || this, 0)
}
}
function base64Slice (buf, start, end) {
if (start === 0 && end === buf.length) {
return base64.fromByteArray(buf)
} else {
return base64.fromByteArray(buf.slice(start, end))
}
}
function utf8Slice (buf, start, end) {
end = Math.min(buf.length, end)
var res = []
var i = start
while (i < end) {
var firstByte = buf[i]
var codePoint = null
var bytesPerSequence = (firstByte > 0xEF) ? 4
: (firstByte > 0xDF) ? 3
: (firstByte > 0xBF) ? 2
: 1
if (i + bytesPerSequence <= end) {
var secondByte, thirdByte, fourthByte, tempCodePoint
switch (bytesPerSequence) {
case 1:
if (firstByte < 0x80) {
codePoint = firstByte
}
break
case 2:
secondByte = buf[i + 1]
if ((secondByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
if (tempCodePoint > 0x7F) {
codePoint = tempCodePoint
}
}
break
case 3:
secondByte = buf[i + 1]
thirdByte = buf[i + 2]
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
codePoint = tempCodePoint
}
}
break
case 4:
secondByte = buf[i + 1]
thirdByte = buf[i + 2]
fourthByte = buf[i + 3]
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
codePoint = tempCodePoint
}
}
}
}
if (codePoint === null) {
// we did not generate a valid codePoint so insert a
// replacement char (U+FFFD) and advance only 1 byte
codePoint = 0xFFFD
bytesPerSequence = 1
} else if (codePoint > 0xFFFF) {
// encode to utf16 (surrogate pair dance)
codePoint -= 0x10000
res.push(codePoint >>> 10 & 0x3FF | 0xD800)
codePoint = 0xDC00 | codePoint & 0x3FF
}
res.push(codePoint)
i += bytesPerSequence
}
return decodeCodePointsArray(res)
}
// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
var MAX_ARGUMENTS_LENGTH = 0x1000
function decodeCodePointsArray (codePoints) {
var len = codePoints.length
if (len <= MAX_ARGUMENTS_LENGTH) {
return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
}
// Decode in chunks to avoid "call stack size exceeded".
var res = ''
var i = 0
while (i < len) {
res += String.fromCharCode.apply(
String,
codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
)
}
return res
}
function asciiSlice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i] & 0x7F)
}
return ret
}
function latin1Slice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i])
}
return ret
}
function hexSlice (buf, start, end) {
var len = buf.length
if (!start || start < 0) start = 0
if (!end || end < 0 || end > len) end = len
var out = ''
for (var i = start; i < end; ++i) {
out += toHex(buf[i])
}
return out
}
function utf16leSlice (buf, start, end) {
var bytes = buf.slice(start, end)
var res = ''
for (var i = 0; i < bytes.length; i += 2) {
res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
}
return res
}
Buffer.prototype.slice = function slice (start, end) {
var len = this.length
start = ~~start
end = end === undefined ? len : ~~end
if (start < 0) {
start += len
if (start < 0) start = 0
} else if (start > len) {
start = len
}
if (end < 0) {
end += len
if (end < 0) end = 0
} else if (end > len) {
end = len
}
if (end < start) end = start
var newBuf
if (Buffer.TYPED_ARRAY_SUPPORT) {
newBuf = this.subarray(start, end)
newBuf.__proto__ = Buffer.prototype
} else {
var sliceLen = end - start
newBuf = new Buffer(sliceLen, undefined)
for (var i = 0; i < sliceLen; ++i) {
newBuf[i] = this[i + start]
}
}
return newBuf
}
/*
* Need to make sure that buffer isn't trying to write out of bounds.
*/
function checkOffset (offset, ext, length) {
if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
}
Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var val = this[offset]
var mul = 1
var i = 0
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul
}
return val
}
Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) {
checkOffset(offset, byteLength, this.length)
}
var val = this[offset + --byteLength]
var mul = 1
while (byteLength > 0 && (mul *= 0x100)) {
val += this[offset + --byteLength] * mul
}
return val
}
Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
if (!noAssert) checkOffset(offset, 1, this.length)
return this[offset]
}
Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
return this[offset] | (this[offset + 1] << 8)
}
Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
return (this[offset] << 8) | this[offset + 1]
}
Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return ((this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16)) +
(this[offset + 3] * 0x1000000)
}
Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] * 0x1000000) +
((this[offset + 1] << 16) |
(this[offset + 2] << 8) |
this[offset + 3])
}
Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var val = this[offset]
var mul = 1
var i = 0
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul
}
mul *= 0x80
if (val >= mul) val -= Math.pow(2, 8 * byteLength)
return val
}
Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var i = byteLength
var mul = 1
var val = this[offset + --i]
while (i > 0 && (mul *= 0x100)) {
val += this[offset + --i] * mul
}
mul *= 0x80
if (val >= mul) val -= Math.pow(2, 8 * byteLength)
return val
}
Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
if (!noAssert) checkOffset(offset, 1, this.length)
if (!(this[offset] & 0x80)) return (this[offset])
return ((0xff - this[offset] + 1) * -1)
}
Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset] | (this[offset + 1] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset + 1] | (this[offset] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16) |
(this[offset + 3] << 24)
}
Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] << 24) |
(this[offset + 1] << 16) |
(this[offset + 2] << 8) |
(this[offset + 3])
}
Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, true, 23, 4)
}
Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, false, 23, 4)
}
Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, true, 52, 8)
}
Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, false, 52, 8)
}
function checkInt (buf, value, offset, ext, max, min) {
if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
if (offset + ext > buf.length) throw new RangeError('Index out of range')
}
Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) {
var maxBytes = Math.pow(2, 8 * byteLength) - 1
checkInt(this, value, offset, byteLength, maxBytes, 0)
}
var mul = 1
var i = 0
this[offset] = value & 0xFF
while (++i < byteLength && (mul *= 0x100)) {
this[offset + i] = (value / mul) & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
value = +value
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) {
var maxBytes = Math.pow(2, 8 * byteLength) - 1
checkInt(this, value, offset, byteLength, maxBytes, 0)
}
var i = byteLength - 1
var mul = 1
this[offset + i] = value & 0xFF
while (--i >= 0 && (mul *= 0x100)) {
this[offset + i] = (value / mul) & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
this[offset] = (value & 0xff)
return offset + 1
}
function objectWriteUInt16 (buf, value, offset, littleEndian) {
if (value < 0) value = 0xffff + value + 1
for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
(littleEndian ? i : 1 - i) * 8
}
}
Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
} else {
objectWriteUInt16(this, value, offset, true)
}
return offset + 2
}
Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 8)
this[offset + 1] = (value & 0xff)
} else {
objectWriteUInt16(this, value, offset, false)
}
return offset + 2
}
function objectWriteUInt32 (buf, value, offset, littleEndian) {
if (value < 0) value = 0xffffffff + value + 1
for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
}
}
Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset + 3] = (value >>> 24)
this[offset + 2] = (value >>> 16)
this[offset + 1] = (value >>> 8)
this[offset] = (value & 0xff)
} else {
objectWriteUInt32(this, value, offset, true)
}
return offset + 4
}
Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = (value & 0xff)
} else {
objectWriteUInt32(this, value, offset, false)
}
return offset + 4
}
Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) {
var limit = Math.pow(2, 8 * byteLength - 1)
checkInt(this, value, offset, byteLength, limit - 1, -limit)
}
var i = 0
var mul = 1
var sub = 0
this[offset] = value & 0xFF
while (++i < byteLength && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
sub = 1
}
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) {
var limit = Math.pow(2, 8 * byteLength - 1)
checkInt(this, value, offset, byteLength, limit - 1, -limit)
}
var i = byteLength - 1
var mul = 1
var sub = 0
this[offset + i] = value & 0xFF
while (--i >= 0 && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
sub = 1
}
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
if (value < 0) value = 0xff + value + 1
this[offset] = (value & 0xff)
return offset + 1
}
Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
} else {
objectWriteUInt16(this, value, offset, true)
}
return offset + 2
}
Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 8)
this[offset + 1] = (value & 0xff)
} else {
objectWriteUInt16(this, value, offset, false)
}
return offset + 2
}
Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
this[offset + 2] = (value >>> 16)
this[offset + 3] = (value >>> 24)
} else {
objectWriteUInt32(this, value, offset, true)
}
return offset + 4
}
Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
if (value < 0) value = 0xffffffff + value + 1
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = (value & 0xff)
} else {
objectWriteUInt32(this, value, offset, false)
}
return offset + 4
}
function checkIEEE754 (buf, value, offset, ext, max, min) {
if (offset + ext > buf.length) throw new RangeError('Index out of range')
if (offset < 0) throw new RangeError('Index out of range')
}
function writeFloat (buf, value, offset, littleEndian, noAssert) {
if (!noAssert) {
checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
}
ieee754.write(buf, value, offset, littleEndian, 23, 4)
return offset + 4
}
Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
return writeFloat(this, value, offset, true, noAssert)
}
Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
return writeFloat(this, value, offset, false, noAssert)
}
function writeDouble (buf, value, offset, littleEndian, noAssert) {
if (!noAssert) {
checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
}
ieee754.write(buf, value, offset, littleEndian, 52, 8)
return offset + 8
}
Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
return writeDouble(this, value, offset, true, noAssert)
}
Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
return writeDouble(this, value, offset, false, noAssert)
}
// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
Buffer.prototype.copy = function copy (target, targetStart, start, end) {
if (!start) start = 0
if (!end && end !== 0) end = this.length
if (targetStart >= target.length) targetStart = target.length
if (!targetStart) targetStart = 0
if (end > 0 && end < start) end = start
// Copy 0 bytes; we're done
if (end === start) return 0
if (target.length === 0 || this.length === 0) return 0
// Fatal error conditions
if (targetStart < 0) {
throw new RangeError('targetStart out of bounds')
}
if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
if (end < 0) throw new RangeError('sourceEnd out of bounds')
// Are we oob?
if (end > this.length) end = this.length
if (target.length - targetStart < end - start) {
end = target.length - targetStart + start
}
var len = end - start
var i
if (this === target && start < targetStart && targetStart < end) {
// descending copy from end
for (i = len - 1; i >= 0; --i) {
target[i + targetStart] = this[i + start]
}
} else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
// ascending copy from start
for (i = 0; i < len; ++i) {
target[i + targetStart] = this[i + start]
}
} else {
Uint8Array.prototype.set.call(
target,
this.subarray(start, start + len),
targetStart
)
}
return len
}
// Usage:
// buffer.fill(number[, offset[, end]])
// buffer.fill(buffer[, offset[, end]])
// buffer.fill(string[, offset[, end]][, encoding])
Buffer.prototype.fill = function fill (val, start, end, encoding) {
// Handle string cases:
if (typeof val === 'string') {
if (typeof start === 'string') {
encoding = start
start = 0
end = this.length
} else if (typeof end === 'string') {
encoding = end
end = this.length
}
if (val.length === 1) {
var code = val.charCodeAt(0)
if (code < 256) {
val = code
}
}
if (encoding !== undefined && typeof encoding !== 'string') {
throw new TypeError('encoding must be a string')
}
if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
throw new TypeError('Unknown encoding: ' + encoding)
}
} else if (typeof val === 'number') {
val = val & 255
}
// Invalid ranges are not set to a default, so can range check early.
if (start < 0 || this.length < start || this.length < end) {
throw new RangeError('Out of range index')
}
if (end <= start) {
return this
}
start = start >>> 0
end = end === undefined ? this.length : end >>> 0
if (!val) val = 0
var i
if (typeof val === 'number') {
for (i = start; i < end; ++i) {
this[i] = val
}
} else {
var bytes = Buffer.isBuffer(val)
? val
: utf8ToBytes(new Buffer(val, encoding).toString())
var len = bytes.length
for (i = 0; i < end - start; ++i) {
this[i + start] = bytes[i % len]
}
}
return this
}
// HELPER FUNCTIONS
// ================
var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g
function base64clean (str) {
// Node strips out invalid characters like \n and \t from the string, base64-js does not
str = stringtrim(str).replace(INVALID_BASE64_RE, '')
// Node converts strings with length < 2 to ''
if (str.length < 2) return ''
// Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
while (str.length % 4 !== 0) {
str = str + '='
}
return str
}
function stringtrim (str) {
if (str.trim) return str.trim()
return str.replace(/^\s+|\s+$/g, '')
}
function toHex (n) {
if (n < 16) return '0' + n.toString(16)
return n.toString(16)
}
function utf8ToBytes (string, units) {
units = units || Infinity
var codePoint
var length = string.length
var leadSurrogate = null
var bytes = []
for (var i = 0; i < length; ++i) {
codePoint = string.charCodeAt(i)
// is surrogate component
if (codePoint > 0xD7FF && codePoint < 0xE000) {
// last char was a lead
if (!leadSurrogate) {
// no lead yet
if (codePoint > 0xDBFF) {
// unexpected trail
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
} else if (i + 1 === length) {
// unpaired lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
}
// valid lead
leadSurrogate = codePoint
continue
}
// 2 leads in a row
if (codePoint < 0xDC00) {
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
leadSurrogate = codePoint
continue
}
// valid surrogate pair
codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
} else if (leadSurrogate) {
// valid bmp char, but last char was a lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
}
leadSurrogate = null
// encode utf8
if (codePoint < 0x80) {
if ((units -= 1) < 0) break
bytes.push(codePoint)
} else if (codePoint < 0x800) {
if ((units -= 2) < 0) break
bytes.push(
codePoint >> 0x6 | 0xC0,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x10000) {
if ((units -= 3) < 0) break
bytes.push(
codePoint >> 0xC | 0xE0,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x110000) {
if ((units -= 4) < 0) break
bytes.push(
codePoint >> 0x12 | 0xF0,
codePoint >> 0xC & 0x3F | 0x80,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else {
throw new Error('Invalid code point')
}
}
return bytes
}
function asciiToBytes (str) {
var byteArray = []
for (var i = 0; i < str.length; ++i) {
// Node's code seems to be doing this and not & 0x7F..
byteArray.push(str.charCodeAt(i) & 0xFF)
}
return byteArray
}
function utf16leToBytes (str, units) {
var c, hi, lo
var byteArray = []
for (var i = 0; i < str.length; ++i) {
if ((units -= 2) < 0) break
c = str.charCodeAt(i)
hi = c >> 8
lo = c % 256
byteArray.push(lo)
byteArray.push(hi)
}
return byteArray
}
function base64ToBytes (str) {
return base64.toByteArray(base64clean(str))
}
function blitBuffer (src, dst, offset, length) {
for (var i = 0; i < length; ++i) {
if ((i + offset >= dst.length) || (i >= src.length)) break
dst[i + offset] = src[i]
}
return i
}
function isnan (val) {
return val !== val // eslint-disable-line no-self-compare
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"base64-js":39,"ieee754":50,"isarray":53}],45:[function(require,module,exports){
(function (Buffer){
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(arg) {
if (Array.isArray) {
return Array.isArray(arg);
}
return objectToString(arg) === '[object Array]';
}
exports.isArray = isArray;
function isBoolean(arg) {
return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;
function isNull(arg) {
return arg === null;
}
exports.isNull = isNull;
function isNullOrUndefined(arg) {
return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;
function isNumber(arg) {
return typeof arg === 'number';
}
exports.isNumber = isNumber;
function isString(arg) {
return typeof arg === 'string';
}
exports.isString = isString;
function isSymbol(arg) {
return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;
function isUndefined(arg) {
return arg === void 0;
}
exports.isUndefined = isUndefined;
function isRegExp(re) {
return objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;
function isDate(d) {
return objectToString(d) === '[object Date]';
}
exports.isDate = isDate;
function isError(e) {
return (objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;
function isFunction(arg) {
return typeof arg === 'function';
}
exports.isFunction = isFunction;
function isPrimitive(arg) {
return arg === null ||
typeof arg === 'boolean' ||
typeof arg === 'number' ||
typeof arg === 'string' ||
typeof arg === 'symbol' || // ES6 symbol
typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;
exports.isBuffer = Buffer.isBuffer;
function objectToString(o) {
return Object.prototype.toString.call(o);
}
}).call(this,{"isBuffer":require("../../is-buffer/index.js")})
},{"../../is-buffer/index.js":52}],46:[function(require,module,exports){
/* See LICENSE file for terms of use */
/*
* Text diff implementation.
*
* This library supports the following APIS:
* JsDiff.diffChars: Character by character diff
* JsDiff.diffWords: Word (as defined by \b regex) diff which ignores whitespace
* JsDiff.diffLines: Line based diff
*
* JsDiff.diffCss: Diff targeted at CSS content
*
* These methods are based on the implementation proposed in
* "An O(ND) Difference Algorithm and its Variations" (Myers, 1986).
* http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927
*/
(function(global, undefined) {
var objectPrototypeToString = Object.prototype.toString;
/*istanbul ignore next*/
function map(arr, mapper, that) {
if (Array.prototype.map) {
return Array.prototype.map.call(arr, mapper, that);
}
var other = new Array(arr.length);
for (var i = 0, n = arr.length; i < n; i++) {
other[i] = mapper.call(that, arr[i], i, arr);
}
return other;
}
function clonePath(path) {
return { newPos: path.newPos, components: path.components.slice(0) };
}
function removeEmpty(array) {
var ret = [];
for (var i = 0; i < array.length; i++) {
if (array[i]) {
ret.push(array[i]);
}
}
return ret;
}
function escapeHTML(s) {
var n = s;
n = n.replace(/&/g, '&');
n = n.replace(/</g, '<');
n = n.replace(/>/g, '>');
n = n.replace(/"/g, '"');
return n;
}
// This function handles the presence of circular references by bailing out when encountering an
// object that is already on the "stack" of items being processed.
function canonicalize(obj, stack, replacementStack) {
stack = stack || [];
replacementStack = replacementStack || [];
var i;
for (i = 0; i < stack.length; i += 1) {
if (stack[i] === obj) {
return replacementStack[i];
}
}
var canonicalizedObj;
if ('[object Array]' === objectPrototypeToString.call(obj)) {
stack.push(obj);
canonicalizedObj = new Array(obj.length);
replacementStack.push(canonicalizedObj);
for (i = 0; i < obj.length; i += 1) {
canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack);
}
stack.pop();
replacementStack.pop();
} else if (typeof obj === 'object' && obj !== null) {
stack.push(obj);
canonicalizedObj = {};
replacementStack.push(canonicalizedObj);
var sortedKeys = [],
key;
for (key in obj) {
sortedKeys.push(key);
}
sortedKeys.sort();
for (i = 0; i < sortedKeys.length; i += 1) {
key = sortedKeys[i];
canonicalizedObj[key] = canonicalize(obj[key], stack, replacementStack);
}
stack.pop();
replacementStack.pop();
} else {
canonicalizedObj = obj;
}
return canonicalizedObj;
}
function buildValues(components, newString, oldString, useLongestToken) {
var componentPos = 0,
componentLen = components.length,
newPos = 0,
oldPos = 0;
for (; componentPos < componentLen; componentPos++) {
var component = components[componentPos];
if (!component.removed) {
if (!component.added && useLongestToken) {
var value = newString.slice(newPos, newPos + component.count);
value = map(value, function(value, i) {
var oldValue = oldString[oldPos + i];
return oldValue.length > value.length ? oldValue : value;
});
component.value = value.join('');
} else {
component.value = newString.slice(newPos, newPos + component.count).join('');
}
newPos += component.count;
// Common case
if (!component.added) {
oldPos += component.count;
}
} else {
component.value = oldString.slice(oldPos, oldPos + component.count).join('');
oldPos += component.count;
// Reverse add and remove so removes are output first to match common convention
// The diffing algorithm is tied to add then remove output and this is the simplest
// route to get the desired output with minimal overhead.
if (componentPos && components[componentPos - 1].added) {
var tmp = components[componentPos - 1];
components[componentPos - 1] = components[componentPos];
components[componentPos] = tmp;
}
}
}
return components;
}
function Diff(ignoreWhitespace) {
this.ignoreWhitespace = ignoreWhitespace;
}
Diff.prototype = {
diff: function(oldString, newString, callback) {
var self = this;
function done(value) {
if (callback) {
setTimeout(function() { callback(undefined, value); }, 0);
return true;
} else {
return value;
}
}
// Handle the identity case (this is due to unrolling editLength == 0
if (newString === oldString) {
return done([{ value: newString }]);
}
if (!newString) {
return done([{ value: oldString, removed: true }]);
}
if (!oldString) {
return done([{ value: newString, added: true }]);
}
newString = this.tokenize(newString);
oldString = this.tokenize(oldString);
var newLen = newString.length, oldLen = oldString.length;
var editLength = 1;
var maxEditLength = newLen + oldLen;
var bestPath = [{ newPos: -1, components: [] }];
// Seed editLength = 0, i.e. the content starts with the same values
var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0);
if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
// Identity per the equality and tokenizer
return done([{value: newString.join('')}]);
}
// Main worker method. checks all permutations of a given edit length for acceptance.
function execEditLength() {
for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {
var basePath;
var addPath = bestPath[diagonalPath - 1],
removePath = bestPath[diagonalPath + 1],
oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
if (addPath) {
// No one else is going to attempt to use this value, clear it
bestPath[diagonalPath - 1] = undefined;
}
var canAdd = addPath && addPath.newPos + 1 < newLen,
canRemove = removePath && 0 <= oldPos && oldPos < oldLen;
if (!canAdd && !canRemove) {
// If this path is a terminal then prune
bestPath[diagonalPath] = undefined;
continue;
}
// Select the diagonal that we want to branch from. We select the prior
// path whose position in the new string is the farthest from the origin
// and does not pass the bounds of the diff graph
if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) {
basePath = clonePath(removePath);
self.pushComponent(basePath.components, undefined, true);
} else {
basePath = addPath; // No need to clone, we've pulled it from the list
basePath.newPos++;
self.pushComponent(basePath.components, true, undefined);
}
oldPos = self.extractCommon(basePath, newString, oldString, diagonalPath);
// If we have hit the end of both strings, then we are done
if (basePath.newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
return done(buildValues(basePath.components, newString, oldString, self.useLongestToken));
} else {
// Otherwise track this path as a potential candidate and continue.
bestPath[diagonalPath] = basePath;
}
}
editLength++;
}
// Performs the length of edit iteration. Is a bit fugly as this has to support the
// sync and async mode which is never fun. Loops over execEditLength until a value
// is produced.
if (callback) {
(function exec() {
setTimeout(function() {
// This should not happen, but we want to be safe.
/*istanbul ignore next */
if (editLength > maxEditLength) {
return callback();
}
if (!execEditLength()) {
exec();
}
}, 0);
}());
} else {
while (editLength <= maxEditLength) {
var ret = execEditLength();
if (ret) {
return ret;
}
}
}
},
pushComponent: function(components, added, removed) {
var last = components[components.length - 1];
if (last && last.added === added && last.removed === removed) {
// We need to clone here as the component clone operation is just
// as shallow array clone
components[components.length - 1] = {count: last.count + 1, added: added, removed: removed };
} else {
components.push({count: 1, added: added, removed: removed });
}
},
extractCommon: function(basePath, newString, oldString, diagonalPath) {
var newLen = newString.length,
oldLen = oldString.length,
newPos = basePath.newPos,
oldPos = newPos - diagonalPath,
commonCount = 0;
while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) {
newPos++;
oldPos++;
commonCount++;
}
if (commonCount) {
basePath.components.push({count: commonCount});
}
basePath.newPos = newPos;
return oldPos;
},
equals: function(left, right) {
var reWhitespace = /\S/;
return left === right || (this.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right));
},
tokenize: function(value) {
return value.split('');
}
};
var CharDiff = new Diff();
var WordDiff = new Diff(true);
var WordWithSpaceDiff = new Diff();
WordDiff.tokenize = WordWithSpaceDiff.tokenize = function(value) {
return removeEmpty(value.split(/(\s+|\b)/));
};
var CssDiff = new Diff(true);
CssDiff.tokenize = function(value) {
return removeEmpty(value.split(/([{}:;,]|\s+)/));
};
var LineDiff = new Diff();
var TrimmedLineDiff = new Diff();
TrimmedLineDiff.ignoreTrim = true;
LineDiff.tokenize = TrimmedLineDiff.tokenize = function(value) {
var retLines = [],
lines = value.split(/^/m);
for (var i = 0; i < lines.length; i++) {
var line = lines[i],
lastLine = lines[i - 1],
lastLineLastChar = lastLine && lastLine[lastLine.length - 1];
// Merge lines that may contain windows new lines
if (line === '\n' && lastLineLastChar === '\r') {
retLines[retLines.length - 1] = retLines[retLines.length - 1].slice(0, -1) + '\r\n';
} else {
if (this.ignoreTrim) {
line = line.trim();
// add a newline unless this is the last line.
if (i < lines.length - 1) {
line += '\n';
}
}
retLines.push(line);
}
}
return retLines;
};
var PatchDiff = new Diff();
PatchDiff.tokenize = function(value) {
var ret = [],
linesAndNewlines = value.split(/(\n|\r\n)/);
// Ignore the final empty token that occurs if the string ends with a new line
if (!linesAndNewlines[linesAndNewlines.length - 1]) {
linesAndNewlines.pop();
}
// Merge the content and line separators into single tokens
for (var i = 0; i < linesAndNewlines.length; i++) {
var line = linesAndNewlines[i];
if (i % 2) {
ret[ret.length - 1] += line;
} else {
ret.push(line);
}
}
return ret;
};
var SentenceDiff = new Diff();
SentenceDiff.tokenize = function(value) {
return removeEmpty(value.split(/(\S.+?[.!?])(?=\s+|$)/));
};
var JsonDiff = new Diff();
// Discriminate between two lines of pretty-printed, serialized JSON where one of them has a
// dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output:
JsonDiff.useLongestToken = true;
JsonDiff.tokenize = LineDiff.tokenize;
JsonDiff.equals = function(left, right) {
return LineDiff.equals(left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1'));
};
var JsDiff = {
Diff: Diff,
diffChars: function(oldStr, newStr, callback) { return CharDiff.diff(oldStr, newStr, callback); },
diffWords: function(oldStr, newStr, callback) { return WordDiff.diff(oldStr, newStr, callback); },
diffWordsWithSpace: function(oldStr, newStr, callback) { return WordWithSpaceDiff.diff(oldStr, newStr, callback); },
diffLines: function(oldStr, newStr, callback) { return LineDiff.diff(oldStr, newStr, callback); },
diffTrimmedLines: function(oldStr, newStr, callback) { return TrimmedLineDiff.diff(oldStr, newStr, callback); },
diffSentences: function(oldStr, newStr, callback) { return SentenceDiff.diff(oldStr, newStr, callback); },
diffCss: function(oldStr, newStr, callback) { return CssDiff.diff(oldStr, newStr, callback); },
diffJson: function(oldObj, newObj, callback) {
return JsonDiff.diff(
typeof oldObj === 'string' ? oldObj : JSON.stringify(canonicalize(oldObj), undefined, ' '),
typeof newObj === 'string' ? newObj : JSON.stringify(canonicalize(newObj), undefined, ' '),
callback
);
},
createTwoFilesPatch: function(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader) {
var ret = [];
if (oldFileName == newFileName) {
ret.push('Index: ' + oldFileName);
}
ret.push('===================================================================');
ret.push('--- ' + oldFileName + (typeof oldHeader === 'undefined' ? '' : '\t' + oldHeader));
ret.push('+++ ' + newFileName + (typeof newHeader === 'undefined' ? '' : '\t' + newHeader));
var diff = PatchDiff.diff(oldStr, newStr);
diff.push({value: '', lines: []}); // Append an empty value to make cleanup easier
// Formats a given set of lines for printing as context lines in a patch
function contextLines(lines) {
return map(lines, function(entry) { return ' ' + entry; });
}
// Outputs the no newline at end of file warning if needed
function eofNL(curRange, i, current) {
var last = diff[diff.length - 2],
isLast = i === diff.length - 2,
isLastOfType = i === diff.length - 3 && current.added !== last.added;
// Figure out if this is the last line for the given file and missing NL
if (!(/\n$/.test(current.value)) && (isLast || isLastOfType)) {
curRange.push('\\ No newline at end of file');
}
}
var oldRangeStart = 0, newRangeStart = 0, curRange = [],
oldLine = 1, newLine = 1;
for (var i = 0; i < diff.length; i++) {
var current = diff[i],
lines = current.lines || current.value.replace(/\n$/, '').split('\n');
current.lines = lines;
if (current.added || current.removed) {
// If we have previous context, start with that
if (!oldRangeStart) {
var prev = diff[i - 1];
oldRangeStart = oldLine;
newRangeStart = newLine;
if (prev) {
curRange = contextLines(prev.lines.slice(-4));
oldRangeStart -= curRange.length;
newRangeStart -= curRange.length;
}
}
// Output our changes
curRange.push.apply(curRange, map(lines, function(entry) {
return (current.added ? '+' : '-') + entry;
}));
eofNL(curRange, i, current);
// Track the updated file position
if (current.added) {
newLine += lines.length;
} else {
oldLine += lines.length;
}
} else {
// Identical context lines. Track line changes
if (oldRangeStart) {
// Close out any changes that have been output (or join overlapping)
if (lines.length <= 8 && i < diff.length - 2) {
// Overlapping
curRange.push.apply(curRange, contextLines(lines));
} else {
// end the range and output
var contextSize = Math.min(lines.length, 4);
ret.push(
'@@ -' + oldRangeStart + ',' + (oldLine - oldRangeStart + contextSize)
+ ' +' + newRangeStart + ',' + (newLine - newRangeStart + contextSize)
+ ' @@');
ret.push.apply(ret, curRange);
ret.push.apply(ret, contextLines(lines.slice(0, contextSize)));
if (lines.length <= 4) {
eofNL(ret, i, current);
}
oldRangeStart = 0;
newRangeStart = 0;
curRange = [];
}
}
oldLine += lines.length;
newLine += lines.length;
}
}
return ret.join('\n') + '\n';
},
createPatch: function(fileName, oldStr, newStr, oldHeader, newHeader) {
return JsDiff.createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader);
},
applyPatch: function(oldStr, uniDiff) {
var diffstr = uniDiff.split('\n'),
hunks = [],
i = 0,
remEOFNL = false,
addEOFNL = false;
// Skip to the first change hunk
while (i < diffstr.length && !(/^@@/.test(diffstr[i]))) {
i++;
}
// Parse the unified diff
for (; i < diffstr.length; i++) {
if (diffstr[i][0] === '@') {
var chnukHeader = diffstr[i].split(/@@ -(\d+),(\d+) \+(\d+),(\d+) @@/);
hunks.unshift({
start: chnukHeader[3],
oldlength: +chnukHeader[2],
removed: [],
newlength: chnukHeader[4],
added: []
});
} else if (diffstr[i][0] === '+') {
hunks[0].added.push(diffstr[i].substr(1));
} else if (diffstr[i][0] === '-') {
hunks[0].removed.push(diffstr[i].substr(1));
} else if (diffstr[i][0] === ' ') {
hunks[0].added.push(diffstr[i].substr(1));
hunks[0].removed.push(diffstr[i].substr(1));
} else if (diffstr[i][0] === '\\') {
if (diffstr[i - 1][0] === '+') {
remEOFNL = true;
} else if (diffstr[i - 1][0] === '-') {
addEOFNL = true;
}
}
}
// Apply the diff to the input
var lines = oldStr.split('\n');
for (i = hunks.length - 1; i >= 0; i--) {
var hunk = hunks[i];
// Sanity check the input string. Bail if we don't match.
for (var j = 0; j < hunk.oldlength; j++) {
if (lines[hunk.start - 1 + j] !== hunk.removed[j]) {
return false;
}
}
Array.prototype.splice.apply(lines, [hunk.start - 1, hunk.oldlength].concat(hunk.added));
}
// Handle EOFNL insertion/removal
if (remEOFNL) {
while (!lines[lines.length - 1]) {
lines.pop();
}
} else if (addEOFNL) {
lines.push('');
}
return lines.join('\n');
},
convertChangesToXML: function(changes) {
var ret = [];
for (var i = 0; i < changes.length; i++) {
var change = changes[i];
if (change.added) {
ret.push('<ins>');
} else if (change.removed) {
ret.push('<del>');
}
ret.push(escapeHTML(change.value));
if (change.added) {
ret.push('</ins>');
} else if (change.removed) {
ret.push('</del>');
}
}
return ret.join('');
},
// See: http://code.google.com/p/google-diff-match-patch/wiki/API
convertChangesToDMP: function(changes) {
var ret = [],
change,
operation;
for (var i = 0; i < changes.length; i++) {
change = changes[i];
if (change.added) {
operation = 1;
} else if (change.removed) {
operation = -1;
} else {
operation = 0;
}
ret.push([operation, change.value]);
}
return ret;
},
canonicalize: canonicalize
};
/*istanbul ignore next */
/*global module */
if (typeof module !== 'undefined' && module.exports) {
module.exports = JsDiff;
} else if (false) {
/*global define */
define([], function() { return JsDiff; });
} else if (typeof global.JsDiff === 'undefined') {
global.JsDiff = JsDiff;
}
}(this));
},{}],47:[function(require,module,exports){
'use strict';
var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g;
module.exports = function (str) {
if (typeof str !== 'string') {
throw new TypeError('Expected a string');
}
return str.replace(matchOperatorsRe, '\\$&');
};
},{}],48:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
function EventEmitter() {
this._events = this._events || {};
this._maxListeners = this._maxListeners || undefined;
}
module.exports = EventEmitter;
// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._maxListeners = undefined;
// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
EventEmitter.defaultMaxListeners = 10;
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function(n) {
if (!isNumber(n) || n < 0 || isNaN(n))
throw TypeError('n must be a positive number');
this._maxListeners = n;
return this;
};
EventEmitter.prototype.emit = function(type) {
var er, handler, len, args, i, listeners;
if (!this._events)
this._events = {};
// If there is no 'error' event listener then throw.
if (type === 'error') {
if (!this._events.error ||
(isObject(this._events.error) && !this._events.error.length)) {
er = arguments[1];
if (er instanceof Error) {
throw er; // Unhandled 'error' event
} else {
// At least give some kind of context to the user
var err = new Error('Uncaught, unspecified "error" event. (' + er + ')');
err.context = er;
throw err;
}
}
}
handler = this._events[type];
if (isUndefined(handler))
return false;
if (isFunction(handler)) {
switch (arguments.length) {
// fast cases
case 1:
handler.call(this);
break;
case 2:
handler.call(this, arguments[1]);
break;
case 3:
handler.call(this, arguments[1], arguments[2]);
break;
// slower
default:
args = Array.prototype.slice.call(arguments, 1);
handler.apply(this, args);
}
} else if (isObject(handler)) {
args = Array.prototype.slice.call(arguments, 1);
listeners = handler.slice();
len = listeners.length;
for (i = 0; i < len; i++)
listeners[i].apply(this, args);
}
return true;
};
EventEmitter.prototype.addListener = function(type, listener) {
var m;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events)
this._events = {};
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (this._events.newListener)
this.emit('newListener', type,
isFunction(listener.listener) ?
listener.listener : listener);
if (!this._events[type])
// Optimize the case of one listener. Don't need the extra array object.
this._events[type] = listener;
else if (isObject(this._events[type]))
// If we've already got an array, just append.
this._events[type].push(listener);
else
// Adding the second element, need to change to array.
this._events[type] = [this._events[type], listener];
// Check for listener leak
if (isObject(this._events[type]) && !this._events[type].warned) {
if (!isUndefined(this._maxListeners)) {
m = this._maxListeners;
} else {
m = EventEmitter.defaultMaxListeners;
}
if (m && m > 0 && this._events[type].length > m) {
this._events[type].warned = true;
console.error('(node) warning: possible EventEmitter memory ' +
'leak detected. %d listeners added. ' +
'Use emitter.setMaxListeners() to increase limit.',
this._events[type].length);
if (typeof console.trace === 'function') {
// not supported in IE 10
console.trace();
}
}
}
return this;
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.once = function(type, listener) {
if (!isFunction(listener))
throw TypeError('listener must be a function');
var fired = false;
function g() {
this.removeListener(type, g);
if (!fired) {
fired = true;
listener.apply(this, arguments);
}
}
g.listener = listener;
this.on(type, g);
return this;
};
// emits a 'removeListener' event iff the listener was removed
EventEmitter.prototype.removeListener = function(type, listener) {
var list, position, length, i;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events || !this._events[type])
return this;
list = this._events[type];
length = list.length;
position = -1;
if (list === listener ||
(isFunction(list.listener) && list.listener === listener)) {
delete this._events[type];
if (this._events.removeListener)
this.emit('removeListener', type, listener);
} else if (isObject(list)) {
for (i = length; i-- > 0;) {
if (list[i] === listener ||
(list[i].listener && list[i].listener === listener)) {
position = i;
break;
}
}
if (position < 0)
return this;
if (list.length === 1) {
list.length = 0;
delete this._events[type];
} else {
list.splice(position, 1);
}
if (this._events.removeListener)
this.emit('removeListener', type, listener);
}
return this;
};
EventEmitter.prototype.removeAllListeners = function(type) {
var key, listeners;
if (!this._events)
return this;
// not listening for removeListener, no need to emit
if (!this._events.removeListener) {
if (arguments.length === 0)
this._events = {};
else if (this._events[type])
delete this._events[type];
return this;
}
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
for (key in this._events) {
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = {};
return this;
}
listeners = this._events[type];
if (isFunction(listeners)) {
this.removeListener(type, listeners);
} else if (listeners) {
// LIFO order
while (listeners.length)
this.removeListener(type, listeners[listeners.length - 1]);
}
delete this._events[type];
return this;
};
EventEmitter.prototype.listeners = function(type) {
var ret;
if (!this._events || !this._events[type])
ret = [];
else if (isFunction(this._events[type]))
ret = [this._events[type]];
else
ret = this._events[type].slice();
return ret;
};
EventEmitter.prototype.listenerCount = function(type) {
if (this._events) {
var evlistener = this._events[type];
if (isFunction(evlistener))
return 1;
else if (evlistener)
return evlistener.length;
}
return 0;
};
EventEmitter.listenerCount = function(emitter, type) {
return emitter.listenerCount(type);
};
function isFunction(arg) {
return typeof arg === 'function';
}
function isNumber(arg) {
return typeof arg === 'number';
}
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
function isUndefined(arg) {
return arg === void 0;
}
},{}],49:[function(require,module,exports){
(function (process){
// Growl - Copyright TJ Holowaychuk <tj@vision-media.ca> (MIT Licensed)
/**
* Module dependencies.
*/
var exec = require('child_process').exec
, fs = require('fs')
, path = require('path')
, exists = fs.existsSync || path.existsSync
, os = require('os')
, quote = JSON.stringify
, cmd;
function which(name) {
var paths = process.env.PATH.split(':');
var loc;
for (var i = 0, len = paths.length; i < len; ++i) {
loc = path.join(paths[i], name);
if (exists(loc)) return loc;
}
}
switch(os.type()) {
case 'Darwin':
if (which('terminal-notifier')) {
cmd = {
type: "Darwin-NotificationCenter"
, pkg: "terminal-notifier"
, msg: '-message'
, title: '-title'
, subtitle: '-subtitle'
, icon: '-appIcon'
, sound: '-sound'
, url: '-open'
, priority: {
cmd: '-execute'
, range: []
}
};
} else {
cmd = {
type: "Darwin-Growl"
, pkg: "growlnotify"
, msg: '-m'
, sticky: '--sticky'
, priority: {
cmd: '--priority'
, range: [
-2
, -1
, 0
, 1
, 2
, "Very Low"
, "Moderate"
, "Normal"
, "High"
, "Emergency"
]
}
};
}
break;
case 'Linux':
if (which('growl')) {
cmd = {
type: "Linux-Growl"
, pkg: "growl"
, msg: '-m'
, title: '-title'
, subtitle: '-subtitle'
, host: {
cmd: '-H'
, hostname: '192.168.33.1'
}
};
} else {
cmd = {
type: "Linux"
, pkg: "notify-send"
, msg: ''
, sticky: '-t 0'
, icon: '-i'
, priority: {
cmd: '-u'
, range: [
"low"
, "normal"
, "critical"
]
}
};
}
break;
case 'Windows_NT':
cmd = {
type: "Windows"
, pkg: "growlnotify"
, msg: ''
, sticky: '/s:true'
, title: '/t:'
, icon: '/i:'
, url: '/cu:'
, priority: {
cmd: '/p:'
, range: [
-2
, -1
, 0
, 1
, 2
]
}
};
break;
}
/**
* Expose `growl`.
*/
exports = module.exports = growl;
/**
* Node-growl version.
*/
exports.version = '1.4.1'
/**
* Send growl notification _msg_ with _options_.
*
* Options:
*
* - title Notification title
* - sticky Make the notification stick (defaults to false)
* - priority Specify an int or named key (default is 0)
* - name Application name (defaults to growlnotify)
* - sound Sound efect ( in OSx defined in preferences -> sound -> effects) * works only in OSX > 10.8x
* - image
* - path to an icon sets --iconpath
* - path to an image sets --image
* - capitalized word sets --appIcon
* - filename uses extname as --icon
* - otherwise treated as --icon
*
* Examples:
*
* growl('New email')
* growl('5 new emails', { title: 'Thunderbird' })
* growl('5 new emails', { title: 'Thunderbird', sound: 'Purr' })
* growl('Email sent', function(){
* // ... notification sent
* })
*
* @param {string} msg
* @param {object} options
* @param {function} fn
* @api public
*/
function growl(msg, options, fn) {
var image
, args
, options = options || {}
, fn = fn || function(){};
if (options.exec) {
cmd = {
type: "Custom"
, pkg: options.exec
, range: []
};
}
// noop
if (!cmd) return fn(new Error('growl not supported on this platform'));
args = [cmd.pkg];
// image
if (image = options.image) {
switch(cmd.type) {
case 'Darwin-Growl':
var flag, ext = path.extname(image).substr(1)
flag = flag || ext == 'icns' && 'iconpath'
flag = flag || /^[A-Z]/.test(image) && 'appIcon'
flag = flag || /^png|gif|jpe?g$/.test(ext) && 'image'
flag = flag || ext && (image = ext) && 'icon'
flag = flag || 'icon'
args.push('--' + flag, quote(image))
break;
case 'Darwin-NotificationCenter':
args.push(cmd.icon, quote(image));
break;
case 'Linux':
args.push(cmd.icon, quote(image));
// libnotify defaults to sticky, set a hint for transient notifications
if (!options.sticky) args.push('--hint=int:transient:1');
break;
case 'Windows':
args.push(cmd.icon + quote(image));
break;
}
}
// sticky
if (options.sticky) args.push(cmd.sticky);
// priority
if (options.priority) {
var priority = options.priority + '';
var checkindexOf = cmd.priority.range.indexOf(priority);
if (~cmd.priority.range.indexOf(priority)) {
args.push(cmd.priority, options.priority);
}
}
//sound
if(options.sound && cmd.type === 'Darwin-NotificationCenter'){
args.push(cmd.sound, options.sound)
}
// name
if (options.name && cmd.type === "Darwin-Growl") {
args.push('--name', options.name);
}
switch(cmd.type) {
case 'Darwin-Growl':
args.push(cmd.msg);
args.push(quote(msg).replace(/\\n/g, '\n'));
if (options.title) args.push(quote(options.title));
break;
case 'Darwin-NotificationCenter':
args.push(cmd.msg);
var stringifiedMsg = quote(msg);
var escapedMsg = stringifiedMsg.replace(/\\n/g, '\n');
args.push(escapedMsg);
if (options.title) {
args.push(cmd.title);
args.push(quote(options.title));
}
if (options.subtitle) {
args.push(cmd.subtitle);
args.push(quote(options.subtitle));
}
if (options.url) {
args.push(cmd.url);
args.push(quote(options.url));
}
break;
case 'Linux-Growl':
args.push(cmd.msg);
args.push(quote(msg).replace(/\\n/g, '\n'));
if (options.title) args.push(quote(options.title));
if (cmd.host) {
args.push(cmd.host.cmd, cmd.host.hostname)
}
break;
case 'Linux':
if (options.title) {
args.push(quote(options.title));
args.push(cmd.msg);
args.push(quote(msg).replace(/\\n/g, '\n'));
} else {
args.push(quote(msg).replace(/\\n/g, '\n'));
}
break;
case 'Windows':
args.push(quote(msg).replace(/\\n/g, '\n'));
if (options.title) args.push(cmd.title + quote(options.title));
if (options.url) args.push(cmd.url + quote(options.url));
break;
case 'Custom':
args[0] = (function(origCommand) {
var message = options.title
? options.title + ': ' + msg
: msg;
var command = origCommand.replace(/(^|[^%])%s/g, '$1' + quote(message));
if (command === origCommand) args.push(quote(message));
return command;
})(args[0]);
break;
}
// execute
exec(args.join(' '), fn);
};
}).call(this,require('_process'))
},{"_process":67,"child_process":42,"fs":42,"os":65,"path":42}],50:[function(require,module,exports){
exports.read = function (buffer, offset, isLE, mLen, nBytes) {
var e, m
var eLen = nBytes * 8 - mLen - 1
var eMax = (1 << eLen) - 1
var eBias = eMax >> 1
var nBits = -7
var i = isLE ? (nBytes - 1) : 0
var d = isLE ? -1 : 1
var s = buffer[offset + i]
i += d
e = s & ((1 << (-nBits)) - 1)
s >>= (-nBits)
nBits += eLen
for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
m = e & ((1 << (-nBits)) - 1)
e >>= (-nBits)
nBits += mLen
for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
if (e === 0) {
e = 1 - eBias
} else if (e === eMax) {
return m ? NaN : ((s ? -1 : 1) * Infinity)
} else {
m = m + Math.pow(2, mLen)
e = e - eBias
}
return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
}
exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
var e, m, c
var eLen = nBytes * 8 - mLen - 1
var eMax = (1 << eLen) - 1
var eBias = eMax >> 1
var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
var i = isLE ? 0 : (nBytes - 1)
var d = isLE ? 1 : -1
var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
value = Math.abs(value)
if (isNaN(value) || value === Infinity) {
m = isNaN(value) ? 1 : 0
e = eMax
} else {
e = Math.floor(Math.log(value) / Math.LN2)
if (value * (c = Math.pow(2, -e)) < 1) {
e--
c *= 2
}
if (e + eBias >= 1) {
value += rt / c
} else {
value += rt * Math.pow(2, 1 - eBias)
}
if (value * c >= 2) {
e++
c /= 2
}
if (e + eBias >= eMax) {
m = 0
e = eMax
} else if (e + eBias >= 1) {
m = (value * c - 1) * Math.pow(2, mLen)
e = e + eBias
} else {
m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
e = 0
}
}
for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
e = (e << mLen) | m
eLen += mLen
for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
buffer[offset + i - d] |= s * 128
}
},{}],51:[function(require,module,exports){
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
},{}],52:[function(require,module,exports){
/*!
* Determine if an object is a Buffer
*
* @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
* @license MIT
*/
// The _isBuffer check is for Safari 5-7 support, because it's missing
// Object.prototype.constructor. Remove this eventually
module.exports = function (obj) {
return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
}
function isBuffer (obj) {
return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
}
// For Node v0.10 support. Remove this eventually.
function isSlowBuffer (obj) {
return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
}
},{}],53:[function(require,module,exports){
var toString = {}.toString;
module.exports = Array.isArray || function (arr) {
return toString.call(arr) == '[object Array]';
};
},{}],54:[function(require,module,exports){
(function (global){
/*! JSON v3.3.2 | http://bestiejs.github.io/json3 | Copyright 2012-2014, Kit Cambridge | http://kit.mit-license.org */
;(function () {
// Detect the `define` function exposed by asynchronous module loaders. The
// strict `define` check is necessary for compatibility with `r.js`.
var isLoader = false;
// A set of types used to distinguish objects from primitives.
var objectTypes = {
"function": true,
"object": true
};
// Detect the `exports` object exposed by CommonJS implementations.
var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports;
// Use the `global` object exposed by Node (including Browserify via
// `insert-module-globals`), Narwhal, and Ringo as the default context,
// and the `window` object in browsers. Rhino exports a `global` function
// instead.
var root = objectTypes[typeof window] && window || this,
freeGlobal = freeExports && objectTypes[typeof module] && module && !module.nodeType && typeof global == "object" && global;
if (freeGlobal && (freeGlobal["global"] === freeGlobal || freeGlobal["window"] === freeGlobal || freeGlobal["self"] === freeGlobal)) {
root = freeGlobal;
}
// Public: Initializes JSON 3 using the given `context` object, attaching the
// `stringify` and `parse` functions to the specified `exports` object.
function runInContext(context, exports) {
context || (context = root["Object"]());
exports || (exports = root["Object"]());
// Native constructor aliases.
var Number = context["Number"] || root["Number"],
String = context["String"] || root["String"],
Object = context["Object"] || root["Object"],
Date = context["Date"] || root["Date"],
SyntaxError = context["SyntaxError"] || root["SyntaxError"],
TypeError = context["TypeError"] || root["TypeError"],
Math = context["Math"] || root["Math"],
nativeJSON = context["JSON"] || root["JSON"];
// Delegate to the native `stringify` and `parse` implementations.
if (typeof nativeJSON == "object" && nativeJSON) {
exports.stringify = nativeJSON.stringify;
exports.parse = nativeJSON.parse;
}
// Convenience aliases.
var objectProto = Object.prototype,
getClass = objectProto.toString,
isProperty, forEach, undef;
// Test the `Date#getUTC*` methods. Based on work by @Yaffle.
var isExtended = new Date(-3509827334573292);
try {
// The `getUTCFullYear`, `Month`, and `Date` methods return nonsensical
// results for certain dates in Opera >= 10.53.
isExtended = isExtended.getUTCFullYear() == -109252 && isExtended.getUTCMonth() === 0 && isExtended.getUTCDate() === 1 &&
// Safari < 2.0.2 stores the internal millisecond time value correctly,
// but clips the values returned by the date methods to the range of
// signed 32-bit integers ([-2 ** 31, 2 ** 31 - 1]).
isExtended.getUTCHours() == 10 && isExtended.getUTCMinutes() == 37 && isExtended.getUTCSeconds() == 6 && isExtended.getUTCMilliseconds() == 708;
} catch (exception) {}
// Internal: Determines whether the native `JSON.stringify` and `parse`
// implementations are spec-compliant. Based on work by Ken Snyder.
function has(name) {
if (has[name] !== undef) {
// Return cached feature test result.
return has[name];
}
var isSupported;
if (name == "bug-string-char-index") {
// IE <= 7 doesn't support accessing string characters using square
// bracket notation. IE 8 only supports this for primitives.
isSupported = "a"[0] != "a";
} else if (name == "json") {
// Indicates whether both `JSON.stringify` and `JSON.parse` are
// supported.
isSupported = has("json-stringify") && has("json-parse");
} else {
var value, serialized = '{"a":[1,true,false,null,"\\u0000\\b\\n\\f\\r\\t"]}';
// Test `JSON.stringify`.
if (name == "json-stringify") {
var stringify = exports.stringify, stringifySupported = typeof stringify == "function" && isExtended;
if (stringifySupported) {
// A test function object with a custom `toJSON` method.
(value = function () {
return 1;
}).toJSON = value;
try {
stringifySupported =
// Firefox 3.1b1 and b2 serialize string, number, and boolean
// primitives as object literals.
stringify(0) === "0" &&
// FF 3.1b1, b2, and JSON 2 serialize wrapped primitives as object
// literals.
stringify(new Number()) === "0" &&
stringify(new String()) == '""' &&
// FF 3.1b1, 2 throw an error if the value is `null`, `undefined`, or
// does not define a canonical JSON representation (this applies to
// objects with `toJSON` properties as well, *unless* they are nested
// within an object or array).
stringify(getClass) === undef &&
// IE 8 serializes `undefined` as `"undefined"`. Safari <= 5.1.7 and
// FF 3.1b3 pass this test.
stringify(undef) === undef &&
// Safari <= 5.1.7 and FF 3.1b3 throw `Error`s and `TypeError`s,
// respectively, if the value is omitted entirely.
stringify() === undef &&
// FF 3.1b1, 2 throw an error if the given value is not a number,
// string, array, object, Boolean, or `null` literal. This applies to
// objects with custom `toJSON` methods as well, unless they are nested
// inside object or array literals. YUI 3.0.0b1 ignores custom `toJSON`
// methods entirely.
stringify(value) === "1" &&
stringify([value]) == "[1]" &&
// Prototype <= 1.6.1 serializes `[undefined]` as `"[]"` instead of
// `"[null]"`.
stringify([undef]) == "[null]" &&
// YUI 3.0.0b1 fails to serialize `null` literals.
stringify(null) == "null" &&
// FF 3.1b1, 2 halts serialization if an array contains a function:
// `[1, true, getClass, 1]` serializes as "[1,true,],". FF 3.1b3
// elides non-JSON values from objects and arrays, unless they
// define custom `toJSON` methods.
stringify([undef, getClass, null]) == "[null,null,null]" &&
// Simple serialization test. FF 3.1b1 uses Unicode escape sequences
// where character escape codes are expected (e.g., `\b` => `\u0008`).
stringify({ "a": [value, true, false, null, "\x00\b\n\f\r\t"] }) == serialized &&
// FF 3.1b1 and b2 ignore the `filter` and `width` arguments.
stringify(null, value) === "1" &&
stringify([1, 2], null, 1) == "[\n 1,\n 2\n]" &&
// JSON 2, Prototype <= 1.7, and older WebKit builds incorrectly
// serialize extended years.
stringify(new Date(-8.64e15)) == '"-271821-04-20T00:00:00.000Z"' &&
// The milliseconds are optional in ES 5, but required in 5.1.
stringify(new Date(8.64e15)) == '"+275760-09-13T00:00:00.000Z"' &&
// Firefox <= 11.0 incorrectly serializes years prior to 0 as negative
// four-digit years instead of six-digit years. Credits: @Yaffle.
stringify(new Date(-621987552e5)) == '"-000001-01-01T00:00:00.000Z"' &&
// Safari <= 5.1.5 and Opera >= 10.53 incorrectly serialize millisecond
// values less than 1000. Credits: @Yaffle.
stringify(new Date(-1)) == '"1969-12-31T23:59:59.999Z"';
} catch (exception) {
stringifySupported = false;
}
}
isSupported = stringifySupported;
}
// Test `JSON.parse`.
if (name == "json-parse") {
var parse = exports.parse;
if (typeof parse == "function") {
try {
// FF 3.1b1, b2 will throw an exception if a bare literal is provided.
// Conforming implementations should also coerce the initial argument to
// a string prior to parsing.
if (parse("0") === 0 && !parse(false)) {
// Simple parsing test.
value = parse(serialized);
var parseSupported = value["a"].length == 5 && value["a"][0] === 1;
if (parseSupported) {
try {
// Safari <= 5.1.2 and FF 3.1b1 allow unescaped tabs in strings.
parseSupported = !parse('"\t"');
} catch (exception) {}
if (parseSupported) {
try {
// FF 4.0 and 4.0.1 allow leading `+` signs and leading
// decimal points. FF 4.0, 4.0.1, and IE 9-10 also allow
// certain octal literals.
parseSupported = parse("01") !== 1;
} catch (exception) {}
}
if (parseSupported) {
try {
// FF 4.0, 4.0.1, and Rhino 1.7R3-R4 allow trailing decimal
// points. These environments, along with FF 3.1b1 and 2,
// also allow trailing commas in JSON objects and arrays.
parseSupported = parse("1.") !== 1;
} catch (exception) {}
}
}
}
} catch (exception) {
parseSupported = false;
}
}
isSupported = parseSupported;
}
}
return has[name] = !!isSupported;
}
if (!has("json")) {
// Common `[[Class]]` name aliases.
var functionClass = "[object Function]",
dateClass = "[object Date]",
numberClass = "[object Number]",
stringClass = "[object String]",
arrayClass = "[object Array]",
booleanClass = "[object Boolean]";
// Detect incomplete support for accessing string characters by index.
var charIndexBuggy = has("bug-string-char-index");
// Define additional utility methods if the `Date` methods are buggy.
if (!isExtended) {
var floor = Math.floor;
// A mapping between the months of the year and the number of days between
// January 1st and the first of the respective month.
var Months = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
// Internal: Calculates the number of days between the Unix epoch and the
// first day of the given month.
var getDay = function (year, month) {
return Months[month] + 365 * (year - 1970) + floor((year - 1969 + (month = +(month > 1))) / 4) - floor((year - 1901 + month) / 100) + floor((year - 1601 + month) / 400);
};
}
// Internal: Determines if a property is a direct property of the given
// object. Delegates to the native `Object#hasOwnProperty` method.
if (!(isProperty = objectProto.hasOwnProperty)) {
isProperty = function (property) {
var members = {}, constructor;
if ((members.__proto__ = null, members.__proto__ = {
// The *proto* property cannot be set multiple times in recent
// versions of Firefox and SeaMonkey.
"toString": 1
}, members).toString != getClass) {
// Safari <= 2.0.3 doesn't implement `Object#hasOwnProperty`, but
// supports the mutable *proto* property.
isProperty = function (property) {
// Capture and break the object's prototype chain (see section 8.6.2
// of the ES 5.1 spec). The parenthesized expression prevents an
// unsafe transformation by the Closure Compiler.
var original = this.__proto__, result = property in (this.__proto__ = null, this);
// Restore the original prototype chain.
this.__proto__ = original;
return result;
};
} else {
// Capture a reference to the top-level `Object` constructor.
constructor = members.constructor;
// Use the `constructor` property to simulate `Object#hasOwnProperty` in
// other environments.
isProperty = function (property) {
var parent = (this.constructor || constructor).prototype;
return property in this && !(property in parent && this[property] === parent[property]);
};
}
members = null;
return isProperty.call(this, property);
};
}
// Internal: Normalizes the `for...in` iteration algorithm across
// environments. Each enumerated key is yielded to a `callback` function.
forEach = function (object, callback) {
var size = 0, Properties, members, property;
// Tests for bugs in the current environment's `for...in` algorithm. The
// `valueOf` property inherits the non-enumerable flag from
// `Object.prototype` in older versions of IE, Netscape, and Mozilla.
(Properties = function () {
this.valueOf = 0;
}).prototype.valueOf = 0;
// Iterate over a new instance of the `Properties` class.
members = new Properties();
for (property in members) {
// Ignore all properties inherited from `Object.prototype`.
if (isProperty.call(members, property)) {
size++;
}
}
Properties = members = null;
// Normalize the iteration algorithm.
if (!size) {
// A list of non-enumerable properties inherited from `Object.prototype`.
members = ["valueOf", "toString", "toLocaleString", "propertyIsEnumerable", "isPrototypeOf", "hasOwnProperty", "constructor"];
// IE <= 8, Mozilla 1.0, and Netscape 6.2 ignore shadowed non-enumerable
// properties.
forEach = function (object, callback) {
var isFunction = getClass.call(object) == functionClass, property, length;
var hasProperty = !isFunction && typeof object.constructor != "function" && objectTypes[typeof object.hasOwnProperty] && object.hasOwnProperty || isProperty;
for (property in object) {
// Gecko <= 1.0 enumerates the `prototype` property of functions under
// certain conditions; IE does not.
if (!(isFunction && property == "prototype") && hasProperty.call(object, property)) {
callback(property);
}
}
// Manually invoke the callback for each non-enumerable property.
for (length = members.length; property = members[--length]; hasProperty.call(object, property) && callback(property));
};
} else if (size == 2) {
// Safari <= 2.0.4 enumerates shadowed properties twice.
forEach = function (object, callback) {
// Create a set of iterated properties.
var members = {}, isFunction = getClass.call(object) == functionClass, property;
for (property in object) {
// Store each property name to prevent double enumeration. The
// `prototype` property of functions is not enumerated due to cross-
// environment inconsistencies.
if (!(isFunction && property == "prototype") && !isProperty.call(members, property) && (members[property] = 1) && isProperty.call(object, property)) {
callback(property);
}
}
};
} else {
// No bugs detected; use the standard `for...in` algorithm.
forEach = function (object, callback) {
var isFunction = getClass.call(object) == functionClass, property, isConstructor;
for (property in object) {
if (!(isFunction && property == "prototype") && isProperty.call(object, property) && !(isConstructor = property === "constructor")) {
callback(property);
}
}
// Manually invoke the callback for the `constructor` property due to
// cross-environment inconsistencies.
if (isConstructor || isProperty.call(object, (property = "constructor"))) {
callback(property);
}
};
}
return forEach(object, callback);
};
// Public: Serializes a JavaScript `value` as a JSON string. The optional
// `filter` argument may specify either a function that alters how object and
// array members are serialized, or an array of strings and numbers that
// indicates which properties should be serialized. The optional `width`
// argument may be either a string or number that specifies the indentation
// level of the output.
if (!has("json-stringify")) {
// Internal: A map of control characters and their escaped equivalents.
var Escapes = {
92: "\\\\",
34: '\\"',
8: "\\b",
12: "\\f",
10: "\\n",
13: "\\r",
9: "\\t"
};
// Internal: Converts `value` into a zero-padded string such that its
// length is at least equal to `width`. The `width` must be <= 6.
var leadingZeroes = "000000";
var toPaddedString = function (width, value) {
// The `|| 0` expression is necessary to work around a bug in
// Opera <= 7.54u2 where `0 == -0`, but `String(-0) !== "0"`.
return (leadingZeroes + (value || 0)).slice(-width);
};
// Internal: Double-quotes a string `value`, replacing all ASCII control
// characters (characters with code unit values between 0 and 31) with
// their escaped equivalents. This is an implementation of the
// `Quote(value)` operation defined in ES 5.1 section 15.12.3.
var unicodePrefix = "\\u00";
var quote = function (value) {
var result = '"', index = 0, length = value.length, useCharIndex = !charIndexBuggy || length > 10;
var symbols = useCharIndex && (charIndexBuggy ? value.split("") : value);
for (; index < length; index++) {
var charCode = value.charCodeAt(index);
// If the character is a control character, append its Unicode or
// shorthand escape sequence; otherwise, append the character as-is.
switch (charCode) {
case 8: case 9: case 10: case 12: case 13: case 34: case 92:
result += Escapes[charCode];
break;
default:
if (charCode < 32) {
result += unicodePrefix + toPaddedString(2, charCode.toString(16));
break;
}
result += useCharIndex ? symbols[index] : value.charAt(index);
}
}
return result + '"';
};
// Internal: Recursively serializes an object. Implements the
// `Str(key, holder)`, `JO(value)`, and `JA(value)` operations.
var serialize = function (property, object, callback, properties, whitespace, indentation, stack) {
var value, className, year, month, date, time, hours, minutes, seconds, milliseconds, results, element, index, length, prefix, result;
try {
// Necessary for host object support.
value = object[property];
} catch (exception) {}
if (typeof value == "object" && value) {
className = getClass.call(value);
if (className == dateClass && !isProperty.call(value, "toJSON")) {
if (value > -1 / 0 && value < 1 / 0) {
// Dates are serialized according to the `Date#toJSON` method
// specified in ES 5.1 section 15.9.5.44. See section 15.9.1.15
// for the ISO 8601 date time string format.
if (getDay) {
// Manually compute the year, month, date, hours, minutes,
// seconds, and milliseconds if the `getUTC*` methods are
// buggy. Adapted from @Yaffle's `date-shim` project.
date = floor(value / 864e5);
for (year = floor(date / 365.2425) + 1970 - 1; getDay(year + 1, 0) <= date; year++);
for (month = floor((date - getDay(year, 0)) / 30.42); getDay(year, month + 1) <= date; month++);
date = 1 + date - getDay(year, month);
// The `time` value specifies the time within the day (see ES
// 5.1 section 15.9.1.2). The formula `(A % B + B) % B` is used
// to compute `A modulo B`, as the `%` operator does not
// correspond to the `modulo` operation for negative numbers.
time = (value % 864e5 + 864e5) % 864e5;
// The hours, minutes, seconds, and milliseconds are obtained by
// decomposing the time within the day. See section 15.9.1.10.
hours = floor(time / 36e5) % 24;
minutes = floor(time / 6e4) % 60;
seconds = floor(time / 1e3) % 60;
milliseconds = time % 1e3;
} else {
year = value.getUTCFullYear();
month = value.getUTCMonth();
date = value.getUTCDate();
hours = value.getUTCHours();
minutes = value.getUTCMinutes();
seconds = value.getUTCSeconds();
milliseconds = value.getUTCMilliseconds();
}
// Serialize extended years correctly.
value = (year <= 0 || year >= 1e4 ? (year < 0 ? "-" : "+") + toPaddedString(6, year < 0 ? -year : year) : toPaddedString(4, year)) +
"-" + toPaddedString(2, month + 1) + "-" + toPaddedString(2, date) +
// Months, dates, hours, minutes, and seconds should have two
// digits; milliseconds should have three.
"T" + toPaddedString(2, hours) + ":" + toPaddedString(2, minutes) + ":" + toPaddedString(2, seconds) +
// Milliseconds are optional in ES 5.0, but required in 5.1.
"." + toPaddedString(3, milliseconds) + "Z";
} else {
value = null;
}
} else if (typeof value.toJSON == "function" && ((className != numberClass && className != stringClass && className != arrayClass) || isProperty.call(value, "toJSON"))) {
// Prototype <= 1.6.1 adds non-standard `toJSON` methods to the
// `Number`, `String`, `Date`, and `Array` prototypes. JSON 3
// ignores all `toJSON` methods on these objects unless they are
// defined directly on an instance.
value = value.toJSON(property);
}
}
if (callback) {
// If a replacement function was provided, call it to obtain the value
// for serialization.
value = callback.call(object, property, value);
}
if (value === null) {
return "null";
}
className = getClass.call(value);
if (className == booleanClass) {
// Booleans are represented literally.
return "" + value;
} else if (className == numberClass) {
// JSON numbers must be finite. `Infinity` and `NaN` are serialized as
// `"null"`.
return value > -1 / 0 && value < 1 / 0 ? "" + value : "null";
} else if (className == stringClass) {
// Strings are double-quoted and escaped.
return quote("" + value);
}
// Recursively serialize objects and arrays.
if (typeof value == "object") {
// Check for cyclic structures. This is a linear search; performance
// is inversely proportional to the number of unique nested objects.
for (length = stack.length; length--;) {
if (stack[length] === value) {
// Cyclic structures cannot be serialized by `JSON.stringify`.
throw TypeError();
}
}
// Add the object to the stack of traversed objects.
stack.push(value);
results = [];
// Save the current indentation level and indent one additional level.
prefix = indentation;
indentation += whitespace;
if (className == arrayClass) {
// Recursively serialize array elements.
for (index = 0, length = value.length; index < length; index++) {
element = serialize(index, value, callback, properties, whitespace, indentation, stack);
results.push(element === undef ? "null" : element);
}
result = results.length ? (whitespace ? "[\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "]" : ("[" + results.join(",") + "]")) : "[]";
} else {
// Recursively serialize object members. Members are selected from
// either a user-specified list of property names, or the object
// itself.
forEach(properties || value, function (property) {
var element = serialize(property, value, callback, properties, whitespace, indentation, stack);
if (element !== undef) {
// According to ES 5.1 section 15.12.3: "If `gap` {whitespace}
// is not the empty string, let `member` {quote(property) + ":"}
// be the concatenation of `member` and the `space` character."
// The "`space` character" refers to the literal space
// character, not the `space` {width} argument provided to
// `JSON.stringify`.
results.push(quote(property) + ":" + (whitespace ? " " : "") + element);
}
});
result = results.length ? (whitespace ? "{\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "}" : ("{" + results.join(",") + "}")) : "{}";
}
// Remove the object from the traversed object stack.
stack.pop();
return result;
}
};
// Public: `JSON.stringify`. See ES 5.1 section 15.12.3.
exports.stringify = function (source, filter, width) {
var whitespace, callback, properties, className;
if (objectTypes[typeof filter] && filter) {
if ((className = getClass.call(filter)) == functionClass) {
callback = filter;
} else if (className == arrayClass) {
// Convert the property names array into a makeshift set.
properties = {};
for (var index = 0, length = filter.length, value; index < length; value = filter[index++], ((className = getClass.call(value)), className == stringClass || className == numberClass) && (properties[value] = 1));
}
}
if (width) {
if ((className = getClass.call(width)) == numberClass) {
// Convert the `width` to an integer and create a string containing
// `width` number of space characters.
if ((width -= width % 1) > 0) {
for (whitespace = "", width > 10 && (width = 10); whitespace.length < width; whitespace += " ");
}
} else if (className == stringClass) {
whitespace = width.length <= 10 ? width : width.slice(0, 10);
}
}
// Opera <= 7.54u2 discards the values associated with empty string keys
// (`""`) only if they are used directly within an object member list
// (e.g., `!("" in { "": 1})`).
return serialize("", (value = {}, value[""] = source, value), callback, properties, whitespace, "", []);
};
}
// Public: Parses a JSON source string.
if (!has("json-parse")) {
var fromCharCode = String.fromCharCode;
// Internal: A map of escaped control characters and their unescaped
// equivalents.
var Unescapes = {
92: "\\",
34: '"',
47: "/",
98: "\b",
116: "\t",
110: "\n",
102: "\f",
114: "\r"
};
// Internal: Stores the parser state.
var Index, Source;
// Internal: Resets the parser state and throws a `SyntaxError`.
var abort = function () {
Index = Source = null;
throw SyntaxError();
};
// Internal: Returns the next token, or `"$"` if the parser has reached
// the end of the source string. A token may be a string, number, `null`
// literal, or Boolean literal.
var lex = function () {
var source = Source, length = source.length, value, begin, position, isSigned, charCode;
while (Index < length) {
charCode = source.charCodeAt(Index);
switch (charCode) {
case 9: case 10: case 13: case 32:
// Skip whitespace tokens, including tabs, carriage returns, line
// feeds, and space characters.
Index++;
break;
case 123: case 125: case 91: case 93: case 58: case 44:
// Parse a punctuator token (`{`, `}`, `[`, `]`, `:`, or `,`) at
// the current position.
value = charIndexBuggy ? source.charAt(Index) : source[Index];
Index++;
return value;
case 34:
// `"` delimits a JSON string; advance to the next character and
// begin parsing the string. String tokens are prefixed with the
// sentinel `@` character to distinguish them from punctuators and
// end-of-string tokens.
for (value = "@", Index++; Index < length;) {
charCode = source.charCodeAt(Index);
if (charCode < 32) {
// Unescaped ASCII control characters (those with a code unit
// less than the space character) are not permitted.
abort();
} else if (charCode == 92) {
// A reverse solidus (`\`) marks the beginning of an escaped
// control character (including `"`, `\`, and `/`) or Unicode
// escape sequence.
charCode = source.charCodeAt(++Index);
switch (charCode) {
case 92: case 34: case 47: case 98: case 116: case 110: case 102: case 114:
// Revive escaped control characters.
value += Unescapes[charCode];
Index++;
break;
case 117:
// `\u` marks the beginning of a Unicode escape sequence.
// Advance to the first character and validate the
// four-digit code point.
begin = ++Index;
for (position = Index + 4; Index < position; Index++) {
charCode = source.charCodeAt(Index);
// A valid sequence comprises four hexdigits (case-
// insensitive) that form a single hexadecimal value.
if (!(charCode >= 48 && charCode <= 57 || charCode >= 97 && charCode <= 102 || charCode >= 65 && charCode <= 70)) {
// Invalid Unicode escape sequence.
abort();
}
}
// Revive the escaped character.
value += fromCharCode("0x" + source.slice(begin, Index));
break;
default:
// Invalid escape sequence.
abort();
}
} else {
if (charCode == 34) {
// An unescaped double-quote character marks the end of the
// string.
break;
}
charCode = source.charCodeAt(Index);
begin = Index;
// Optimize for the common case where a string is valid.
while (charCode >= 32 && charCode != 92 && charCode != 34) {
charCode = source.charCodeAt(++Index);
}
// Append the string as-is.
value += source.slice(begin, Index);
}
}
if (source.charCodeAt(Index) == 34) {
// Advance to the next character and return the revived string.
Index++;
return value;
}
// Unterminated string.
abort();
default:
// Parse numbers and literals.
begin = Index;
// Advance past the negative sign, if one is specified.
if (charCode == 45) {
isSigned = true;
charCode = source.charCodeAt(++Index);
}
// Parse an integer or floating-point value.
if (charCode >= 48 && charCode <= 57) {
// Leading zeroes are interpreted as octal literals.
if (charCode == 48 && ((charCode = source.charCodeAt(Index + 1)), charCode >= 48 && charCode <= 57)) {
// Illegal octal literal.
abort();
}
isSigned = false;
// Parse the integer component.
for (; Index < length && ((charCode = source.charCodeAt(Index)), charCode >= 48 && charCode <= 57); Index++);
// Floats cannot contain a leading decimal point; however, this
// case is already accounted for by the parser.
if (source.charCodeAt(Index) == 46) {
position = ++Index;
// Parse the decimal component.
for (; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);
if (position == Index) {
// Illegal trailing decimal.
abort();
}
Index = position;
}
// Parse exponents. The `e` denoting the exponent is
// case-insensitive.
charCode = source.charCodeAt(Index);
if (charCode == 101 || charCode == 69) {
charCode = source.charCodeAt(++Index);
// Skip past the sign following the exponent, if one is
// specified.
if (charCode == 43 || charCode == 45) {
Index++;
}
// Parse the exponential component.
for (position = Index; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);
if (position == Index) {
// Illegal empty exponent.
abort();
}
Index = position;
}
// Coerce the parsed value to a JavaScript number.
return +source.slice(begin, Index);
}
// A negative sign may only precede numbers.
if (isSigned) {
abort();
}
// `true`, `false`, and `null` literals.
if (source.slice(Index, Index + 4) == "true") {
Index += 4;
return true;
} else if (source.slice(Index, Index + 5) == "false") {
Index += 5;
return false;
} else if (source.slice(Index, Index + 4) == "null") {
Index += 4;
return null;
}
// Unrecognized token.
abort();
}
}
// Return the sentinel `$` character if the parser has reached the end
// of the source string.
return "$";
};
// Internal: Parses a JSON `value` token.
var get = function (value) {
var results, hasMembers;
if (value == "$") {
// Unexpected end of input.
abort();
}
if (typeof value == "string") {
if ((charIndexBuggy ? value.charAt(0) : value[0]) == "@") {
// Remove the sentinel `@` character.
return value.slice(1);
}
// Parse object and array literals.
if (value == "[") {
// Parses a JSON array, returning a new JavaScript array.
results = [];
for (;; hasMembers || (hasMembers = true)) {
value = lex();
// A closing square bracket marks the end of the array literal.
if (value == "]") {
break;
}
// If the array literal contains elements, the current token
// should be a comma separating the previous element from the
// next.
if (hasMembers) {
if (value == ",") {
value = lex();
if (value == "]") {
// Unexpected trailing `,` in array literal.
abort();
}
} else {
// A `,` must separate each array element.
abort();
}
}
// Elisions and leading commas are not permitted.
if (value == ",") {
abort();
}
results.push(get(value));
}
return results;
} else if (value == "{") {
// Parses a JSON object, returning a new JavaScript object.
results = {};
for (;; hasMembers || (hasMembers = true)) {
value = lex();
// A closing curly brace marks the end of the object literal.
if (value == "}") {
break;
}
// If the object literal contains members, the current token
// should be a comma separator.
if (hasMembers) {
if (value == ",") {
value = lex();
if (value == "}") {
// Unexpected trailing `,` in object literal.
abort();
}
} else {
// A `,` must separate each object member.
abort();
}
}
// Leading commas are not permitted, object property names must be
// double-quoted strings, and a `:` must separate each property
// name and value.
if (value == "," || typeof value != "string" || (charIndexBuggy ? value.charAt(0) : value[0]) != "@" || lex() != ":") {
abort();
}
results[value.slice(1)] = get(lex());
}
return results;
}
// Unexpected token encountered.
abort();
}
return value;
};
// Internal: Updates a traversed object member.
var update = function (source, property, callback) {
var element = walk(source, property, callback);
if (element === undef) {
delete source[property];
} else {
source[property] = element;
}
};
// Internal: Recursively traverses a parsed JSON object, invoking the
// `callback` function for each value. This is an implementation of the
// `Walk(holder, name)` operation defined in ES 5.1 section 15.12.2.
var walk = function (source, property, callback) {
var value = source[property], length;
if (typeof value == "object" && value) {
// `forEach` can't be used to traverse an array in Opera <= 8.54
// because its `Object#hasOwnProperty` implementation returns `false`
// for array indices (e.g., `![1, 2, 3].hasOwnProperty("0")`).
if (getClass.call(value) == arrayClass) {
for (length = value.length; length--;) {
update(value, length, callback);
}
} else {
forEach(value, function (property) {
update(value, property, callback);
});
}
}
return callback.call(source, property, value);
};
// Public: `JSON.parse`. See ES 5.1 section 15.12.2.
exports.parse = function (source, callback) {
var result, value;
Index = 0;
Source = "" + source;
result = get(lex());
// If a JSON string contains multiple tokens, it is invalid.
if (lex() != "$") {
abort();
}
// Reset the parser state.
Index = Source = null;
return callback && getClass.call(callback) == functionClass ? walk((value = {}, value[""] = result, value), "", callback) : result;
};
}
}
exports["runInContext"] = runInContext;
return exports;
}
if (freeExports && !isLoader) {
// Export for CommonJS environments.
runInContext(root, freeExports);
} else {
// Export for web browsers and JavaScript engines.
var nativeJSON = root.JSON,
previousJSON = root["JSON3"],
isRestored = false;
var JSON3 = runInContext(root, (root["JSON3"] = {
// Public: Restores the original value of the global `JSON` object and
// returns a reference to the `JSON3` object.
"noConflict": function () {
if (!isRestored) {
isRestored = true;
root.JSON = nativeJSON;
root["JSON3"] = previousJSON;
nativeJSON = previousJSON = null;
}
return JSON3;
}
}));
root.JSON = {
"parse": JSON3.parse,
"stringify": JSON3.stringify
};
}
// Export for asynchronous module loaders.
if (isLoader) {
define(function () {
return JSON3;
});
}
}).call(this);
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],55:[function(require,module,exports){
/**
* lodash 3.2.0 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
var baseCopy = require('lodash._basecopy'),
keys = require('lodash.keys');
/**
* The base implementation of `_.assign` without support for argument juggling,
* multiple sources, and `customizer` functions.
*
* @private
* @param {Object} object The destination object.
* @param {Object} source The source object.
* @returns {Object} Returns `object`.
*/
function baseAssign(object, source) {
return source == null
? object
: baseCopy(source, keys(source), object);
}
module.exports = baseAssign;
},{"lodash._basecopy":56,"lodash.keys":63}],56:[function(require,module,exports){
/**
* lodash 3.0.1 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
/**
* Copies properties of `source` to `object`.
*
* @private
* @param {Object} source The object to copy properties from.
* @param {Array} props The property names to copy.
* @param {Object} [object={}] The object to copy properties to.
* @returns {Object} Returns `object`.
*/
function baseCopy(source, props, object) {
object || (object = {});
var index = -1,
length = props.length;
while (++index < length) {
var key = props[index];
object[key] = source[key];
}
return object;
}
module.exports = baseCopy;
},{}],57:[function(require,module,exports){
/**
* lodash 3.0.3 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
/**
* The base implementation of `_.create` without support for assigning
* properties to the created object.
*
* @private
* @param {Object} prototype The object to inherit from.
* @returns {Object} Returns the new object.
*/
var baseCreate = (function() {
function object() {}
return function(prototype) {
if (isObject(prototype)) {
object.prototype = prototype;
var result = new object;
object.prototype = undefined;
}
return result || {};
};
}());
/**
* Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
* (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(1);
* // => false
*/
function isObject(value) {
// Avoid a V8 JIT bug in Chrome 19-20.
// See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
var type = typeof value;
return !!value && (type == 'object' || type == 'function');
}
module.exports = baseCreate;
},{}],58:[function(require,module,exports){
/**
* lodash 3.9.1 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
/** `Object#toString` result references. */
var funcTag = '[object Function]';
/** Used to detect host constructors (Safari > 5). */
var reIsHostCtor = /^\[object .+?Constructor\]$/;
/**
* Checks if `value` is object-like.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
*/
function isObjectLike(value) {
return !!value && typeof value == 'object';
}
/** Used for native method references. */
var objectProto = Object.prototype;
/** Used to resolve the decompiled source of functions. */
var fnToString = Function.prototype.toString;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
* of values.
*/
var objToString = objectProto.toString;
/** Used to detect if a method is native. */
var reIsNative = RegExp('^' +
fnToString.call(hasOwnProperty).replace(/[\\^$.*+?()[\]{}|]/g, '\\$&')
.replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
);
/**
* Gets the native function at `key` of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {string} key The key of the method to get.
* @returns {*} Returns the function if it's native, else `undefined`.
*/
function getNative(object, key) {
var value = object == null ? undefined : object[key];
return isNative(value) ? value : undefined;
}
/**
* Checks if `value` is classified as a `Function` object.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isFunction(_);
* // => true
*
* _.isFunction(/abc/);
* // => false
*/
function isFunction(value) {
// The use of `Object#toString` avoids issues with the `typeof` operator
// in older versions of Chrome and Safari which return 'function' for regexes
// and Safari 8 equivalents which return 'object' for typed array constructors.
return isObject(value) && objToString.call(value) == funcTag;
}
/**
* Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
* (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(1);
* // => false
*/
function isObject(value) {
// Avoid a V8 JIT bug in Chrome 19-20.
// See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
var type = typeof value;
return !!value && (type == 'object' || type == 'function');
}
/**
* Checks if `value` is a native function.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a native function, else `false`.
* @example
*
* _.isNative(Array.prototype.push);
* // => true
*
* _.isNative(_);
* // => false
*/
function isNative(value) {
if (value == null) {
return false;
}
if (isFunction(value)) {
return reIsNative.test(fnToString.call(value));
}
return isObjectLike(value) && reIsHostCtor.test(value);
}
module.exports = getNative;
},{}],59:[function(require,module,exports){
/**
* lodash 3.0.9 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
/** Used to detect unsigned integer values. */
var reIsUint = /^\d+$/;
/**
* Used as the [maximum length](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.max_safe_integer)
* of an array-like value.
*/
var MAX_SAFE_INTEGER = 9007199254740991;
/**
* The base implementation of `_.property` without support for deep paths.
*
* @private
* @param {string} key The key of the property to get.
* @returns {Function} Returns the new function.
*/
function baseProperty(key) {
return function(object) {
return object == null ? undefined : object[key];
};
}
/**
* Gets the "length" property value of `object`.
*
* **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792)
* that affects Safari on at least iOS 8.1-8.3 ARM64.
*
* @private
* @param {Object} object The object to query.
* @returns {*} Returns the "length" value.
*/
var getLength = baseProperty('length');
/**
* Checks if `value` is array-like.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is array-like, else `false`.
*/
function isArrayLike(value) {
return value != null && isLength(getLength(value));
}
/**
* Checks if `value` is a valid array-like index.
*
* @private
* @param {*} value The value to check.
* @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
* @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
*/
function isIndex(value, length) {
value = (typeof value == 'number' || reIsUint.test(value)) ? +value : -1;
length = length == null ? MAX_SAFE_INTEGER : length;
return value > -1 && value % 1 == 0 && value < length;
}
/**
* Checks if the provided arguments are from an iteratee call.
*
* @private
* @param {*} value The potential iteratee value argument.
* @param {*} index The potential iteratee index or key argument.
* @param {*} object The potential iteratee object argument.
* @returns {boolean} Returns `true` if the arguments are from an iteratee call, else `false`.
*/
function isIterateeCall(value, index, object) {
if (!isObject(object)) {
return false;
}
var type = typeof index;
if (type == 'number'
? (isArrayLike(object) && isIndex(index, object.length))
: (type == 'string' && index in object)) {
var other = object[index];
return value === value ? (value === other) : (other !== other);
}
return false;
}
/**
* Checks if `value` is a valid array-like length.
*
* **Note:** This function is based on [`ToLength`](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength).
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
*/
function isLength(value) {
return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
/**
* Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
* (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(1);
* // => false
*/
function isObject(value) {
// Avoid a V8 JIT bug in Chrome 19-20.
// See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
var type = typeof value;
return !!value && (type == 'object' || type == 'function');
}
module.exports = isIterateeCall;
},{}],60:[function(require,module,exports){
/**
* lodash 3.1.1 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
var baseAssign = require('lodash._baseassign'),
baseCreate = require('lodash._basecreate'),
isIterateeCall = require('lodash._isiterateecall');
/**
* Creates an object that inherits from the given `prototype` object. If a
* `properties` object is provided its own enumerable properties are assigned
* to the created object.
*
* @static
* @memberOf _
* @category Object
* @param {Object} prototype The object to inherit from.
* @param {Object} [properties] The properties to assign to the object.
* @param- {Object} [guard] Enables use as a callback for functions like `_.map`.
* @returns {Object} Returns the new object.
* @example
*
* function Shape() {
* this.x = 0;
* this.y = 0;
* }
*
* function Circle() {
* Shape.call(this);
* }
*
* Circle.prototype = _.create(Shape.prototype, {
* 'constructor': Circle
* });
*
* var circle = new Circle;
* circle instanceof Circle;
* // => true
*
* circle instanceof Shape;
* // => true
*/
function create(prototype, properties, guard) {
var result = baseCreate(prototype);
if (guard && isIterateeCall(prototype, properties, guard)) {
properties = undefined;
}
return properties ? baseAssign(result, properties) : result;
}
module.exports = create;
},{"lodash._baseassign":55,"lodash._basecreate":57,"lodash._isiterateecall":59}],61:[function(require,module,exports){
/**
* lodash (Custom Build) <https://lodash.com/>
* Build: `lodash modularize exports="npm" -o ./`
* Copyright jQuery Foundation and other contributors <https://jquery.org/>
* Released under MIT license <https://lodash.com/license>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
*/
/** Used as references for various `Number` constants. */
var MAX_SAFE_INTEGER = 9007199254740991;
/** `Object#toString` result references. */
var argsTag = '[object Arguments]',
funcTag = '[object Function]',
genTag = '[object GeneratorFunction]';
/** Used for built-in method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Used to resolve the
* [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
* of values.
*/
var objectToString = objectProto.toString;
/** Built-in value references. */
var propertyIsEnumerable = objectProto.propertyIsEnumerable;
/**
* Checks if `value` is likely an `arguments` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an `arguments` object,
* else `false`.
* @example
*
* _.isArguments(function() { return arguments; }());
* // => true
*
* _.isArguments([1, 2, 3]);
* // => false
*/
function isArguments(value) {
// Safari 8.1 makes `arguments.callee` enumerable in strict mode.
return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') &&
(!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag);
}
/**
* Checks if `value` is array-like. A value is considered array-like if it's
* not a function and has a `value.length` that's an integer greater than or
* equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is array-like, else `false`.
* @example
*
* _.isArrayLike([1, 2, 3]);
* // => true
*
* _.isArrayLike(document.body.children);
* // => true
*
* _.isArrayLike('abc');
* // => true
*
* _.isArrayLike(_.noop);
* // => false
*/
function isArrayLike(value) {
return value != null && isLength(value.length) && !isFunction(value);
}
/**
* This method is like `_.isArrayLike` except that it also checks if `value`
* is an object.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an array-like object,
* else `false`.
* @example
*
* _.isArrayLikeObject([1, 2, 3]);
* // => true
*
* _.isArrayLikeObject(document.body.children);
* // => true
*
* _.isArrayLikeObject('abc');
* // => false
*
* _.isArrayLikeObject(_.noop);
* // => false
*/
function isArrayLikeObject(value) {
return isObjectLike(value) && isArrayLike(value);
}
/**
* Checks if `value` is classified as a `Function` object.
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a function, else `false`.
* @example
*
* _.isFunction(_);
* // => true
*
* _.isFunction(/abc/);
* // => false
*/
function isFunction(value) {
// The use of `Object#toString` avoids issues with the `typeof` operator
// in Safari 8-9 which returns 'object' for typed array and other constructors.
var tag = isObject(value) ? objectToString.call(value) : '';
return tag == funcTag || tag == genTag;
}
/**
* Checks if `value` is a valid array-like length.
*
* **Note:** This method is loosely based on
* [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
* @example
*
* _.isLength(3);
* // => true
*
* _.isLength(Number.MIN_VALUE);
* // => false
*
* _.isLength(Infinity);
* // => false
*
* _.isLength('3');
* // => false
*/
function isLength(value) {
return typeof value == 'number' &&
value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
/**
* Checks if `value` is the
* [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
* of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @since 0.1.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(_.noop);
* // => true
*
* _.isObject(null);
* // => false
*/
function isObject(value) {
var type = typeof value;
return !!value && (type == 'object' || type == 'function');
}
/**
* Checks if `value` is object-like. A value is object-like if it's not `null`
* and has a `typeof` result of "object".
*
* @static
* @memberOf _
* @since 4.0.0
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
* @example
*
* _.isObjectLike({});
* // => true
*
* _.isObjectLike([1, 2, 3]);
* // => true
*
* _.isObjectLike(_.noop);
* // => false
*
* _.isObjectLike(null);
* // => false
*/
function isObjectLike(value) {
return !!value && typeof value == 'object';
}
module.exports = isArguments;
},{}],62:[function(require,module,exports){
/**
* lodash 3.0.4 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
/** `Object#toString` result references. */
var arrayTag = '[object Array]',
funcTag = '[object Function]';
/** Used to detect host constructors (Safari > 5). */
var reIsHostCtor = /^\[object .+?Constructor\]$/;
/**
* Checks if `value` is object-like.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is object-like, else `false`.
*/
function isObjectLike(value) {
return !!value && typeof value == 'object';
}
/** Used for native method references. */
var objectProto = Object.prototype;
/** Used to resolve the decompiled source of functions. */
var fnToString = Function.prototype.toString;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/**
* Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring)
* of values.
*/
var objToString = objectProto.toString;
/** Used to detect if a method is native. */
var reIsNative = RegExp('^' +
fnToString.call(hasOwnProperty).replace(/[\\^$.*+?()[\]{}|]/g, '\\$&')
.replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
);
/* Native method references for those with the same name as other `lodash` methods. */
var nativeIsArray = getNative(Array, 'isArray');
/**
* Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer)
* of an array-like value.
*/
var MAX_SAFE_INTEGER = 9007199254740991;
/**
* Gets the native function at `key` of `object`.
*
* @private
* @param {Object} object The object to query.
* @param {string} key The key of the method to get.
* @returns {*} Returns the function if it's native, else `undefined`.
*/
function getNative(object, key) {
var value = object == null ? undefined : object[key];
return isNative(value) ? value : undefined;
}
/**
* Checks if `value` is a valid array-like length.
*
* **Note:** This function is based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength).
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
*/
function isLength(value) {
return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
/**
* Checks if `value` is classified as an `Array` object.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isArray([1, 2, 3]);
* // => true
*
* _.isArray(function() { return arguments; }());
* // => false
*/
var isArray = nativeIsArray || function(value) {
return isObjectLike(value) && isLength(value.length) && objToString.call(value) == arrayTag;
};
/**
* Checks if `value` is classified as a `Function` object.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isFunction(_);
* // => true
*
* _.isFunction(/abc/);
* // => false
*/
function isFunction(value) {
// The use of `Object#toString` avoids issues with the `typeof` operator
// in older versions of Chrome and Safari which return 'function' for regexes
// and Safari 8 equivalents which return 'object' for typed array constructors.
return isObject(value) && objToString.call(value) == funcTag;
}
/**
* Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
* (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(1);
* // => false
*/
function isObject(value) {
// Avoid a V8 JIT bug in Chrome 19-20.
// See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
var type = typeof value;
return !!value && (type == 'object' || type == 'function');
}
/**
* Checks if `value` is a native function.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a native function, else `false`.
* @example
*
* _.isNative(Array.prototype.push);
* // => true
*
* _.isNative(_);
* // => false
*/
function isNative(value) {
if (value == null) {
return false;
}
if (isFunction(value)) {
return reIsNative.test(fnToString.call(value));
}
return isObjectLike(value) && reIsHostCtor.test(value);
}
module.exports = isArray;
},{}],63:[function(require,module,exports){
/**
* lodash 3.1.2 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
var getNative = require('lodash._getnative'),
isArguments = require('lodash.isarguments'),
isArray = require('lodash.isarray');
/** Used to detect unsigned integer values. */
var reIsUint = /^\d+$/;
/** Used for native method references. */
var objectProto = Object.prototype;
/** Used to check objects for own properties. */
var hasOwnProperty = objectProto.hasOwnProperty;
/* Native method references for those with the same name as other `lodash` methods. */
var nativeKeys = getNative(Object, 'keys');
/**
* Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer)
* of an array-like value.
*/
var MAX_SAFE_INTEGER = 9007199254740991;
/**
* The base implementation of `_.property` without support for deep paths.
*
* @private
* @param {string} key The key of the property to get.
* @returns {Function} Returns the new function.
*/
function baseProperty(key) {
return function(object) {
return object == null ? undefined : object[key];
};
}
/**
* Gets the "length" property value of `object`.
*
* **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792)
* that affects Safari on at least iOS 8.1-8.3 ARM64.
*
* @private
* @param {Object} object The object to query.
* @returns {*} Returns the "length" value.
*/
var getLength = baseProperty('length');
/**
* Checks if `value` is array-like.
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is array-like, else `false`.
*/
function isArrayLike(value) {
return value != null && isLength(getLength(value));
}
/**
* Checks if `value` is a valid array-like index.
*
* @private
* @param {*} value The value to check.
* @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
* @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
*/
function isIndex(value, length) {
value = (typeof value == 'number' || reIsUint.test(value)) ? +value : -1;
length = length == null ? MAX_SAFE_INTEGER : length;
return value > -1 && value % 1 == 0 && value < length;
}
/**
* Checks if `value` is a valid array-like length.
*
* **Note:** This function is based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength).
*
* @private
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
*/
function isLength(value) {
return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
}
/**
* A fallback implementation of `Object.keys` which creates an array of the
* own enumerable property names of `object`.
*
* @private
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
*/
function shimKeys(object) {
var props = keysIn(object),
propsLength = props.length,
length = propsLength && object.length;
var allowIndexes = !!length && isLength(length) &&
(isArray(object) || isArguments(object));
var index = -1,
result = [];
while (++index < propsLength) {
var key = props[index];
if ((allowIndexes && isIndex(key, length)) || hasOwnProperty.call(object, key)) {
result.push(key);
}
}
return result;
}
/**
* Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`.
* (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is an object, else `false`.
* @example
*
* _.isObject({});
* // => true
*
* _.isObject([1, 2, 3]);
* // => true
*
* _.isObject(1);
* // => false
*/
function isObject(value) {
// Avoid a V8 JIT bug in Chrome 19-20.
// See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
var type = typeof value;
return !!value && (type == 'object' || type == 'function');
}
/**
* Creates an array of the own enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects. See the
* [ES spec](http://ecma-international.org/ecma-262/6.0/#sec-object.keys)
* for more details.
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keys(new Foo);
* // => ['a', 'b'] (iteration order is not guaranteed)
*
* _.keys('hi');
* // => ['0', '1']
*/
var keys = !nativeKeys ? shimKeys : function(object) {
var Ctor = object == null ? undefined : object.constructor;
if ((typeof Ctor == 'function' && Ctor.prototype === object) ||
(typeof object != 'function' && isArrayLike(object))) {
return shimKeys(object);
}
return isObject(object) ? nativeKeys(object) : [];
};
/**
* Creates an array of the own and inherited enumerable property names of `object`.
*
* **Note:** Non-object values are coerced to objects.
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @returns {Array} Returns the array of property names.
* @example
*
* function Foo() {
* this.a = 1;
* this.b = 2;
* }
*
* Foo.prototype.c = 3;
*
* _.keysIn(new Foo);
* // => ['a', 'b', 'c'] (iteration order is not guaranteed)
*/
function keysIn(object) {
if (object == null) {
return [];
}
if (!isObject(object)) {
object = Object(object);
}
var length = object.length;
length = (length && isLength(length) &&
(isArray(object) || isArguments(object)) && length) || 0;
var Ctor = object.constructor,
index = -1,
isProto = typeof Ctor == 'function' && Ctor.prototype === object,
result = Array(length),
skipIndexes = length > 0;
while (++index < length) {
result[index] = (index + '');
}
for (var key in object) {
if (!(skipIndexes && isIndex(key, length)) &&
!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {
result.push(key);
}
}
return result;
}
module.exports = keys;
},{"lodash._getnative":58,"lodash.isarguments":61,"lodash.isarray":62}],64:[function(require,module,exports){
(function (process){
var path = require('path');
var fs = require('fs');
var _0777 = parseInt('0777', 8);
module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP;
function mkdirP (p, opts, f, made) {
if (typeof opts === 'function') {
f = opts;
opts = {};
}
else if (!opts || typeof opts !== 'object') {
opts = { mode: opts };
}
var mode = opts.mode;
var xfs = opts.fs || fs;
if (mode === undefined) {
mode = _0777 & (~process.umask());
}
if (!made) made = null;
var cb = f || function () {};
p = path.resolve(p);
xfs.mkdir(p, mode, function (er) {
if (!er) {
made = made || p;
return cb(null, made);
}
switch (er.code) {
case 'ENOENT':
mkdirP(path.dirname(p), opts, function (er, made) {
if (er) cb(er, made);
else mkdirP(p, opts, cb, made);
});
break;
// In the case of any other error, just see if there's a dir
// there already. If so, then hooray! If not, then something
// is borked.
default:
xfs.stat(p, function (er2, stat) {
// if the stat fails, then that's super weird.
// let the original error be the failure reason.
if (er2 || !stat.isDirectory()) cb(er, made)
else cb(null, made);
});
break;
}
});
}
mkdirP.sync = function sync (p, opts, made) {
if (!opts || typeof opts !== 'object') {
opts = { mode: opts };
}
var mode = opts.mode;
var xfs = opts.fs || fs;
if (mode === undefined) {
mode = _0777 & (~process.umask());
}
if (!made) made = null;
p = path.resolve(p);
try {
xfs.mkdirSync(p, mode);
made = made || p;
}
catch (err0) {
switch (err0.code) {
case 'ENOENT' :
made = sync(path.dirname(p), opts, made);
sync(p, opts, made);
break;
// In the case of any other error, just see if there's a dir
// there already. If so, then hooray! If not, then something
// is borked.
default:
var stat;
try {
stat = xfs.statSync(p);
}
catch (err1) {
throw err0;
}
if (!stat.isDirectory()) throw err0;
break;
}
}
return made;
};
}).call(this,require('_process'))
},{"_process":67,"fs":42,"path":42}],65:[function(require,module,exports){
exports.endianness = function () { return 'LE' };
exports.hostname = function () {
if (typeof location !== 'undefined') {
return location.hostname
}
else return '';
};
exports.loadavg = function () { return [] };
exports.uptime = function () { return 0 };
exports.freemem = function () {
return Number.MAX_VALUE;
};
exports.totalmem = function () {
return Number.MAX_VALUE;
};
exports.cpus = function () { return [] };
exports.type = function () { return 'Browser' };
exports.release = function () {
if (typeof navigator !== 'undefined') {
return navigator.appVersion;
}
return '';
};
exports.networkInterfaces
= exports.getNetworkInterfaces
= function () { return {} };
exports.arch = function () { return 'javascript' };
exports.platform = function () { return 'browser' };
exports.tmpdir = exports.tmpDir = function () {
return '/tmp';
};
exports.EOL = '\n';
},{}],66:[function(require,module,exports){
(function (process){
'use strict';
if (!process.version ||
process.version.indexOf('v0.') === 0 ||
process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
module.exports = nextTick;
} else {
module.exports = process.nextTick;
}
function nextTick(fn, arg1, arg2, arg3) {
if (typeof fn !== 'function') {
throw new TypeError('"callback" argument must be a function');
}
var len = arguments.length;
var args, i;
switch (len) {
case 0:
case 1:
return process.nextTick(fn);
case 2:
return process.nextTick(function afterTickOne() {
fn.call(null, arg1);
});
case 3:
return process.nextTick(function afterTickTwo() {
fn.call(null, arg1, arg2);
});
case 4:
return process.nextTick(function afterTickThree() {
fn.call(null, arg1, arg2, arg3);
});
default:
args = new Array(len - 1);
i = 0;
while (i < args.length) {
args[i++] = arguments[i];
}
return process.nextTick(function afterTick() {
fn.apply(null, args);
});
}
}
}).call(this,require('_process'))
},{"_process":67}],67:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
function defaultSetTimout() {
throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
throw new Error('clearTimeout has not been defined');
}
(function () {
try {
if (typeof setTimeout === 'function') {
cachedSetTimeout = setTimeout;
} else {
cachedSetTimeout = defaultSetTimout;
}
} catch (e) {
cachedSetTimeout = defaultSetTimout;
}
try {
if (typeof clearTimeout === 'function') {
cachedClearTimeout = clearTimeout;
} else {
cachedClearTimeout = defaultClearTimeout;
}
} catch (e) {
cachedClearTimeout = defaultClearTimeout;
}
} ())
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
}
// if setTimeout wasn't available but was latter defined
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch(e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch(e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
}
// if clearTimeout wasn't available but was latter defined
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
runTimeout(drainQueue);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
},{}],68:[function(require,module,exports){
module.exports = require("./lib/_stream_duplex.js")
},{"./lib/_stream_duplex.js":69}],69:[function(require,module,exports){
// a duplex stream is just a stream that is both readable and writable.
// Since JS doesn't have multiple prototypal inheritance, this class
// prototypally inherits from Readable, and then parasitically from
// Writable.
'use strict';
/*<replacement>*/
var objectKeys = Object.keys || function (obj) {
var keys = [];
for (var key in obj) {
keys.push(key);
}return keys;
};
/*</replacement>*/
module.exports = Duplex;
/*<replacement>*/
var processNextTick = require('process-nextick-args');
/*</replacement>*/
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
var Readable = require('./_stream_readable');
var Writable = require('./_stream_writable');
util.inherits(Duplex, Readable);
var keys = objectKeys(Writable.prototype);
for (var v = 0; v < keys.length; v++) {
var method = keys[v];
if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
}
function Duplex(options) {
if (!(this instanceof Duplex)) return new Duplex(options);
Readable.call(this, options);
Writable.call(this, options);
if (options && options.readable === false) this.readable = false;
if (options && options.writable === false) this.writable = false;
this.allowHalfOpen = true;
if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
this.once('end', onend);
}
// the no-half-open enforcer
function onend() {
// if we allow half-open state, or if the writable side ended,
// then we're ok.
if (this.allowHalfOpen || this._writableState.ended) return;
// no more data can be written.
// But allow more writes to happen in this tick.
processNextTick(onEndNT, this);
}
function onEndNT(self) {
self.end();
}
function forEach(xs, f) {
for (var i = 0, l = xs.length; i < l; i++) {
f(xs[i], i);
}
}
},{"./_stream_readable":71,"./_stream_writable":73,"core-util-is":45,"inherits":51,"process-nextick-args":66}],70:[function(require,module,exports){
// a passthrough stream.
// basically just the most minimal sort of Transform stream.
// Every written chunk gets output as-is.
'use strict';
module.exports = PassThrough;
var Transform = require('./_stream_transform');
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
util.inherits(PassThrough, Transform);
function PassThrough(options) {
if (!(this instanceof PassThrough)) return new PassThrough(options);
Transform.call(this, options);
}
PassThrough.prototype._transform = function (chunk, encoding, cb) {
cb(null, chunk);
};
},{"./_stream_transform":72,"core-util-is":45,"inherits":51}],71:[function(require,module,exports){
(function (process){
'use strict';
module.exports = Readable;
/*<replacement>*/
var processNextTick = require('process-nextick-args');
/*</replacement>*/
/*<replacement>*/
var isArray = require('isarray');
/*</replacement>*/
Readable.ReadableState = ReadableState;
/*<replacement>*/
var EE = require('events').EventEmitter;
var EElistenerCount = function (emitter, type) {
return emitter.listeners(type).length;
};
/*</replacement>*/
/*<replacement>*/
var Stream;
(function () {
try {
Stream = require('st' + 'ream');
} catch (_) {} finally {
if (!Stream) Stream = require('events').EventEmitter;
}
})();
/*</replacement>*/
var Buffer = require('buffer').Buffer;
/*<replacement>*/
var bufferShim = require('buffer-shims');
/*</replacement>*/
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
/*<replacement>*/
var debugUtil = require('util');
var debug = void 0;
if (debugUtil && debugUtil.debuglog) {
debug = debugUtil.debuglog('stream');
} else {
debug = function () {};
}
/*</replacement>*/
var BufferList = require('./internal/streams/BufferList');
var StringDecoder;
util.inherits(Readable, Stream);
function prependListener(emitter, event, fn) {
if (typeof emitter.prependListener === 'function') {
return emitter.prependListener(event, fn);
} else {
// This is a hack to make sure that our error handler is attached before any
// userland ones. NEVER DO THIS. This is here only because this code needs
// to continue to work with older versions of Node.js that do not include
// the prependListener() method. The goal is to eventually remove this hack.
if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
}
}
var Duplex;
function ReadableState(options, stream) {
Duplex = Duplex || require('./_stream_duplex');
options = options || {};
// object stream flag. Used to make read(n) ignore n and to
// make all the buffer merging and length checks go away
this.objectMode = !!options.objectMode;
if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
// the point at which it stops calling _read() to fill the buffer
// Note: 0 is a valid value, means "don't call _read preemptively ever"
var hwm = options.highWaterMark;
var defaultHwm = this.objectMode ? 16 : 16 * 1024;
this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
// cast to ints.
this.highWaterMark = ~ ~this.highWaterMark;
// A linked list is used to store data chunks instead of an array because the
// linked list can remove elements from the beginning faster than
// array.shift()
this.buffer = new BufferList();
this.length = 0;
this.pipes = null;
this.pipesCount = 0;
this.flowing = null;
this.ended = false;
this.endEmitted = false;
this.reading = false;
// a flag to be able to tell if the onwrite cb is called immediately,
// or on a later tick. We set this to true at first, because any
// actions that shouldn't happen until "later" should generally also
// not happen before the first write call.
this.sync = true;
// whenever we return null, then we set a flag to say
// that we're awaiting a 'readable' event emission.
this.needReadable = false;
this.emittedReadable = false;
this.readableListening = false;
this.resumeScheduled = false;
// Crypto is kind of old and crusty. Historically, its default string
// encoding is 'binary' so we have to make this configurable.
// Everything else in the universe uses 'utf8', though.
this.defaultEncoding = options.defaultEncoding || 'utf8';
// when piping, we only care about 'readable' events that happen
// after read()ing all the bytes and not getting any pushback.
this.ranOut = false;
// the number of writers that are awaiting a drain event in .pipe()s
this.awaitDrain = 0;
// if true, a maybeReadMore has been scheduled
this.readingMore = false;
this.decoder = null;
this.encoding = null;
if (options.encoding) {
if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
this.decoder = new StringDecoder(options.encoding);
this.encoding = options.encoding;
}
}
var Duplex;
function Readable(options) {
Duplex = Duplex || require('./_stream_duplex');
if (!(this instanceof Readable)) return new Readable(options);
this._readableState = new ReadableState(options, this);
// legacy
this.readable = true;
if (options && typeof options.read === 'function') this._read = options.read;
Stream.call(this);
}
// Manually shove something into the read() buffer.
// This returns true if the highWaterMark has not been hit yet,
// similar to how Writable.write() returns true if you should
// write() some more.
Readable.prototype.push = function (chunk, encoding) {
var state = this._readableState;
if (!state.objectMode && typeof chunk === 'string') {
encoding = encoding || state.defaultEncoding;
if (encoding !== state.encoding) {
chunk = bufferShim.from(chunk, encoding);
encoding = '';
}
}
return readableAddChunk(this, state, chunk, encoding, false);
};
// Unshift should *always* be something directly out of read()
Readable.prototype.unshift = function (chunk) {
var state = this._readableState;
return readableAddChunk(this, state, chunk, '', true);
};
Readable.prototype.isPaused = function () {
return this._readableState.flowing === false;
};
function readableAddChunk(stream, state, chunk, encoding, addToFront) {
var er = chunkInvalid(state, chunk);
if (er) {
stream.emit('error', er);
} else if (chunk === null) {
state.reading = false;
onEofChunk(stream, state);
} else if (state.objectMode || chunk && chunk.length > 0) {
if (state.ended && !addToFront) {
var e = new Error('stream.push() after EOF');
stream.emit('error', e);
} else if (state.endEmitted && addToFront) {
var _e = new Error('stream.unshift() after end event');
stream.emit('error', _e);
} else {
var skipAdd;
if (state.decoder && !addToFront && !encoding) {
chunk = state.decoder.write(chunk);
skipAdd = !state.objectMode && chunk.length === 0;
}
if (!addToFront) state.reading = false;
// Don't add to the buffer if we've decoded to an empty string chunk and
// we're not in object mode
if (!skipAdd) {
// if we want the data now, just emit it.
if (state.flowing && state.length === 0 && !state.sync) {
stream.emit('data', chunk);
stream.read(0);
} else {
// update the buffer info.
state.length += state.objectMode ? 1 : chunk.length;
if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
if (state.needReadable) emitReadable(stream);
}
}
maybeReadMore(stream, state);
}
} else if (!addToFront) {
state.reading = false;
}
return needMoreData(state);
}
// if it's past the high water mark, we can push in some more.
// Also, if we have no data yet, we can stand some
// more bytes. This is to work around cases where hwm=0,
// such as the repl. Also, if the push() triggered a
// readable event, and the user called read(largeNumber) such that
// needReadable was set, then we ought to push more, so that another
// 'readable' event will be triggered.
function needMoreData(state) {
return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
}
// backwards compatibility.
Readable.prototype.setEncoding = function (enc) {
if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
this._readableState.decoder = new StringDecoder(enc);
this._readableState.encoding = enc;
return this;
};
// Don't raise the hwm > 8MB
var MAX_HWM = 0x800000;
function computeNewHighWaterMark(n) {
if (n >= MAX_HWM) {
n = MAX_HWM;
} else {
// Get the next highest power of 2 to prevent increasing hwm excessively in
// tiny amounts
n--;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
n++;
}
return n;
}
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function howMuchToRead(n, state) {
if (n <= 0 || state.length === 0 && state.ended) return 0;
if (state.objectMode) return 1;
if (n !== n) {
// Only flow one buffer at a time
if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
}
// If we're asking for more than the current hwm, then raise the hwm.
if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
if (n <= state.length) return n;
// Don't have enough
if (!state.ended) {
state.needReadable = true;
return 0;
}
return state.length;
}
// you can override either this method, or the async _read(n) below.
Readable.prototype.read = function (n) {
debug('read', n);
n = parseInt(n, 10);
var state = this._readableState;
var nOrig = n;
if (n !== 0) state.emittedReadable = false;
// if we're doing read(0) to trigger a readable event, but we
// already have a bunch of data in the buffer, then just trigger
// the 'readable' event and move on.
if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
debug('read: emitReadable', state.length, state.ended);
if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
return null;
}
n = howMuchToRead(n, state);
// if we've ended, and we're now clear, then finish it up.
if (n === 0 && state.ended) {
if (state.length === 0) endReadable(this);
return null;
}
// All the actual chunk generation logic needs to be
// *below* the call to _read. The reason is that in certain
// synthetic stream cases, such as passthrough streams, _read
// may be a completely synchronous operation which may change
// the state of the read buffer, providing enough data when
// before there was *not* enough.
//
// So, the steps are:
// 1. Figure out what the state of things will be after we do
// a read from the buffer.
//
// 2. If that resulting state will trigger a _read, then call _read.
// Note that this may be asynchronous, or synchronous. Yes, it is
// deeply ugly to write APIs this way, but that still doesn't mean
// that the Readable class should behave improperly, as streams are
// designed to be sync/async agnostic.
// Take note if the _read call is sync or async (ie, if the read call
// has returned yet), so that we know whether or not it's safe to emit
// 'readable' etc.
//
// 3. Actually pull the requested chunks out of the buffer and return.
// if we need a readable event, then we need to do some reading.
var doRead = state.needReadable;
debug('need readable', doRead);
// if we currently have less than the highWaterMark, then also read some
if (state.length === 0 || state.length - n < state.highWaterMark) {
doRead = true;
debug('length less than watermark', doRead);
}
// however, if we've ended, then there's no point, and if we're already
// reading, then it's unnecessary.
if (state.ended || state.reading) {
doRead = false;
debug('reading or ended', doRead);
} else if (doRead) {
debug('do read');
state.reading = true;
state.sync = true;
// if the length is currently zero, then we *need* a readable event.
if (state.length === 0) state.needReadable = true;
// call internal read method
this._read(state.highWaterMark);
state.sync = false;
// If _read pushed data synchronously, then `reading` will be false,
// and we need to re-evaluate how much data we can return to the user.
if (!state.reading) n = howMuchToRead(nOrig, state);
}
var ret;
if (n > 0) ret = fromList(n, state);else ret = null;
if (ret === null) {
state.needReadable = true;
n = 0;
} else {
state.length -= n;
}
if (state.length === 0) {
// If we have nothing in the buffer, then we want to know
// as soon as we *do* get something into the buffer.
if (!state.ended) state.needReadable = true;
// If we tried to read() past the EOF, then emit end on the next tick.
if (nOrig !== n && state.ended) endReadable(this);
}
if (ret !== null) this.emit('data', ret);
return ret;
};
function chunkInvalid(state, chunk) {
var er = null;
if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) {
er = new TypeError('Invalid non-string/buffer chunk');
}
return er;
}
function onEofChunk(stream, state) {
if (state.ended) return;
if (state.decoder) {
var chunk = state.decoder.end();
if (chunk && chunk.length) {
state.buffer.push(chunk);
state.length += state.objectMode ? 1 : chunk.length;
}
}
state.ended = true;
// emit 'readable' now to make sure it gets picked up.
emitReadable(stream);
}
// Don't emit readable right away in sync mode, because this can trigger
// another read() call => stack overflow. This way, it might trigger
// a nextTick recursion warning, but that's not so bad.
function emitReadable(stream) {
var state = stream._readableState;
state.needReadable = false;
if (!state.emittedReadable) {
debug('emitReadable', state.flowing);
state.emittedReadable = true;
if (state.sync) processNextTick(emitReadable_, stream);else emitReadable_(stream);
}
}
function emitReadable_(stream) {
debug('emit readable');
stream.emit('readable');
flow(stream);
}
// at this point, the user has presumably seen the 'readable' event,
// and called read() to consume some data. that may have triggered
// in turn another _read(n) call, in which case reading = true if
// it's in progress.
// However, if we're not ended, or reading, and the length < hwm,
// then go ahead and try to read some more preemptively.
function maybeReadMore(stream, state) {
if (!state.readingMore) {
state.readingMore = true;
processNextTick(maybeReadMore_, stream, state);
}
}
function maybeReadMore_(stream, state) {
var len = state.length;
while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
debug('maybeReadMore read 0');
stream.read(0);
if (len === state.length)
// didn't get any data, stop spinning.
break;else len = state.length;
}
state.readingMore = false;
}
// abstract method. to be overridden in specific implementation classes.
// call cb(er, data) where data is <= n in length.
// for virtual (non-string, non-buffer) streams, "length" is somewhat
// arbitrary, and perhaps not very meaningful.
Readable.prototype._read = function (n) {
this.emit('error', new Error('not implemented'));
};
Readable.prototype.pipe = function (dest, pipeOpts) {
var src = this;
var state = this._readableState;
switch (state.pipesCount) {
case 0:
state.pipes = dest;
break;
case 1:
state.pipes = [state.pipes, dest];
break;
default:
state.pipes.push(dest);
break;
}
state.pipesCount += 1;
debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
var endFn = doEnd ? onend : cleanup;
if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn);
dest.on('unpipe', onunpipe);
function onunpipe(readable) {
debug('onunpipe');
if (readable === src) {
cleanup();
}
}
function onend() {
debug('onend');
dest.end();
}
// when the dest drains, it reduces the awaitDrain counter
// on the source. This would be more elegant with a .once()
// handler in flow(), but adding and removing repeatedly is
// too slow.
var ondrain = pipeOnDrain(src);
dest.on('drain', ondrain);
var cleanedUp = false;
function cleanup() {
debug('cleanup');
// cleanup event handlers once the pipe is broken
dest.removeListener('close', onclose);
dest.removeListener('finish', onfinish);
dest.removeListener('drain', ondrain);
dest.removeListener('error', onerror);
dest.removeListener('unpipe', onunpipe);
src.removeListener('end', onend);
src.removeListener('end', cleanup);
src.removeListener('data', ondata);
cleanedUp = true;
// if the reader is waiting for a drain event from this
// specific writer, then it would cause it to never start
// flowing again.
// So, if this is awaiting a drain, then we just call it now.
// If we don't know, then assume that we are waiting for one.
if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
}
// If the user pushes more data while we're writing to dest then we'll end up
// in ondata again. However, we only want to increase awaitDrain once because
// dest will only emit one 'drain' event for the multiple writes.
// => Introduce a guard on increasing awaitDrain.
var increasedAwaitDrain = false;
src.on('data', ondata);
function ondata(chunk) {
debug('ondata');
increasedAwaitDrain = false;
var ret = dest.write(chunk);
if (false === ret && !increasedAwaitDrain) {
// If the user unpiped during `dest.write()`, it is possible
// to get stuck in a permanently paused state if that write
// also returned false.
// => Check whether `dest` is still a piping destination.
if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
debug('false write response, pause', src._readableState.awaitDrain);
src._readableState.awaitDrain++;
increasedAwaitDrain = true;
}
src.pause();
}
}
// if the dest has an error, then stop piping into it.
// however, don't suppress the throwing behavior for this.
function onerror(er) {
debug('onerror', er);
unpipe();
dest.removeListener('error', onerror);
if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
}
// Make sure our error handler is attached before userland ones.
prependListener(dest, 'error', onerror);
// Both close and finish should trigger unpipe, but only once.
function onclose() {
dest.removeListener('finish', onfinish);
unpipe();
}
dest.once('close', onclose);
function onfinish() {
debug('onfinish');
dest.removeListener('close', onclose);
unpipe();
}
dest.once('finish', onfinish);
function unpipe() {
debug('unpipe');
src.unpipe(dest);
}
// tell the dest that it's being piped to
dest.emit('pipe', src);
// start the flow if it hasn't been started already.
if (!state.flowing) {
debug('pipe resume');
src.resume();
}
return dest;
};
function pipeOnDrain(src) {
return function () {
var state = src._readableState;
debug('pipeOnDrain', state.awaitDrain);
if (state.awaitDrain) state.awaitDrain--;
if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
state.flowing = true;
flow(src);
}
};
}
Readable.prototype.unpipe = function (dest) {
var state = this._readableState;
// if we're not piping anywhere, then do nothing.
if (state.pipesCount === 0) return this;
// just one destination. most common case.
if (state.pipesCount === 1) {
// passed in one, but it's not the right one.
if (dest && dest !== state.pipes) return this;
if (!dest) dest = state.pipes;
// got a match.
state.pipes = null;
state.pipesCount = 0;
state.flowing = false;
if (dest) dest.emit('unpipe', this);
return this;
}
// slow case. multiple pipe destinations.
if (!dest) {
// remove all.
var dests = state.pipes;
var len = state.pipesCount;
state.pipes = null;
state.pipesCount = 0;
state.flowing = false;
for (var _i = 0; _i < len; _i++) {
dests[_i].emit('unpipe', this);
}return this;
}
// try to find the right one.
var i = indexOf(state.pipes, dest);
if (i === -1) return this;
state.pipes.splice(i, 1);
state.pipesCount -= 1;
if (state.pipesCount === 1) state.pipes = state.pipes[0];
dest.emit('unpipe', this);
return this;
};
// set up data events if they are asked for
// Ensure readable listeners eventually get something
Readable.prototype.on = function (ev, fn) {
var res = Stream.prototype.on.call(this, ev, fn);
if (ev === 'data') {
// Start flowing on next tick if stream isn't explicitly paused
if (this._readableState.flowing !== false) this.resume();
} else if (ev === 'readable') {
var state = this._readableState;
if (!state.endEmitted && !state.readableListening) {
state.readableListening = state.needReadable = true;
state.emittedReadable = false;
if (!state.reading) {
processNextTick(nReadingNextTick, this);
} else if (state.length) {
emitReadable(this, state);
}
}
}
return res;
};
Readable.prototype.addListener = Readable.prototype.on;
function nReadingNextTick(self) {
debug('readable nexttick read 0');
self.read(0);
}
// pause() and resume() are remnants of the legacy readable stream API
// If the user uses them, then switch into old mode.
Readable.prototype.resume = function () {
var state = this._readableState;
if (!state.flowing) {
debug('resume');
state.flowing = true;
resume(this, state);
}
return this;
};
function resume(stream, state) {
if (!state.resumeScheduled) {
state.resumeScheduled = true;
processNextTick(resume_, stream, state);
}
}
function resume_(stream, state) {
if (!state.reading) {
debug('resume read 0');
stream.read(0);
}
state.resumeScheduled = false;
state.awaitDrain = 0;
stream.emit('resume');
flow(stream);
if (state.flowing && !state.reading) stream.read(0);
}
Readable.prototype.pause = function () {
debug('call pause flowing=%j', this._readableState.flowing);
if (false !== this._readableState.flowing) {
debug('pause');
this._readableState.flowing = false;
this.emit('pause');
}
return this;
};
function flow(stream) {
var state = stream._readableState;
debug('flow', state.flowing);
while (state.flowing && stream.read() !== null) {}
}
// wrap an old-style stream as the async data source.
// This is *not* part of the readable stream interface.
// It is an ugly unfortunate mess of history.
Readable.prototype.wrap = function (stream) {
var state = this._readableState;
var paused = false;
var self = this;
stream.on('end', function () {
debug('wrapped end');
if (state.decoder && !state.ended) {
var chunk = state.decoder.end();
if (chunk && chunk.length) self.push(chunk);
}
self.push(null);
});
stream.on('data', function (chunk) {
debug('wrapped data');
if (state.decoder) chunk = state.decoder.write(chunk);
// don't skip over falsy values in objectMode
if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
var ret = self.push(chunk);
if (!ret) {
paused = true;
stream.pause();
}
});
// proxy all the other methods.
// important when wrapping filters and duplexes.
for (var i in stream) {
if (this[i] === undefined && typeof stream[i] === 'function') {
this[i] = function (method) {
return function () {
return stream[method].apply(stream, arguments);
};
}(i);
}
}
// proxy certain important events.
var events = ['error', 'close', 'destroy', 'pause', 'resume'];
forEach(events, function (ev) {
stream.on(ev, self.emit.bind(self, ev));
});
// when we try to consume some more bytes, simply unpause the
// underlying stream.
self._read = function (n) {
debug('wrapped _read', n);
if (paused) {
paused = false;
stream.resume();
}
};
return self;
};
// exposed for testing purposes only.
Readable._fromList = fromList;
// Pluck off n bytes from an array of buffers.
// Length is the combined lengths of all the buffers in the list.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function fromList(n, state) {
// nothing buffered
if (state.length === 0) return null;
var ret;
if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
// read it all, truncate the list
if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length);
state.buffer.clear();
} else {
// read part of list
ret = fromListPartial(n, state.buffer, state.decoder);
}
return ret;
}
// Extracts only enough buffered data to satisfy the amount requested.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function fromListPartial(n, list, hasStrings) {
var ret;
if (n < list.head.data.length) {
// slice is the same for buffers and strings
ret = list.head.data.slice(0, n);
list.head.data = list.head.data.slice(n);
} else if (n === list.head.data.length) {
// first chunk is a perfect match
ret = list.shift();
} else {
// result spans more than one buffer
ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
}
return ret;
}
// Copies a specified amount of characters from the list of buffered data
// chunks.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function copyFromBufferString(n, list) {
var p = list.head;
var c = 1;
var ret = p.data;
n -= ret.length;
while (p = p.next) {
var str = p.data;
var nb = n > str.length ? str.length : n;
if (nb === str.length) ret += str;else ret += str.slice(0, n);
n -= nb;
if (n === 0) {
if (nb === str.length) {
++c;
if (p.next) list.head = p.next;else list.head = list.tail = null;
} else {
list.head = p;
p.data = str.slice(nb);
}
break;
}
++c;
}
list.length -= c;
return ret;
}
// Copies a specified amount of bytes from the list of buffered data chunks.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function copyFromBuffer(n, list) {
var ret = bufferShim.allocUnsafe(n);
var p = list.head;
var c = 1;
p.data.copy(ret);
n -= p.data.length;
while (p = p.next) {
var buf = p.data;
var nb = n > buf.length ? buf.length : n;
buf.copy(ret, ret.length - n, 0, nb);
n -= nb;
if (n === 0) {
if (nb === buf.length) {
++c;
if (p.next) list.head = p.next;else list.head = list.tail = null;
} else {
list.head = p;
p.data = buf.slice(nb);
}
break;
}
++c;
}
list.length -= c;
return ret;
}
function endReadable(stream) {
var state = stream._readableState;
// If we get here before consuming all the bytes, then that is a
// bug in node. Should never happen.
if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
if (!state.endEmitted) {
state.ended = true;
processNextTick(endReadableNT, state, stream);
}
}
function endReadableNT(state, stream) {
// Check that we didn't get one last unshift.
if (!state.endEmitted && state.length === 0) {
state.endEmitted = true;
stream.readable = false;
stream.emit('end');
}
}
function forEach(xs, f) {
for (var i = 0, l = xs.length; i < l; i++) {
f(xs[i], i);
}
}
function indexOf(xs, x) {
for (var i = 0, l = xs.length; i < l; i++) {
if (xs[i] === x) return i;
}
return -1;
}
}).call(this,require('_process'))
},{"./_stream_duplex":69,"./internal/streams/BufferList":74,"_process":67,"buffer":44,"buffer-shims":43,"core-util-is":45,"events":48,"inherits":51,"isarray":53,"process-nextick-args":66,"string_decoder/":80,"util":40}],72:[function(require,module,exports){
// a transform stream is a readable/writable stream where you do
// something with the data. Sometimes it's called a "filter",
// but that's not a great name for it, since that implies a thing where
// some bits pass through, and others are simply ignored. (That would
// be a valid example of a transform, of course.)
//
// While the output is causally related to the input, it's not a
// necessarily symmetric or synchronous transformation. For example,
// a zlib stream might take multiple plain-text writes(), and then
// emit a single compressed chunk some time in the future.
//
// Here's how this works:
//
// The Transform stream has all the aspects of the readable and writable
// stream classes. When you write(chunk), that calls _write(chunk,cb)
// internally, and returns false if there's a lot of pending writes
// buffered up. When you call read(), that calls _read(n) until
// there's enough pending readable data buffered up.
//
// In a transform stream, the written data is placed in a buffer. When
// _read(n) is called, it transforms the queued up data, calling the
// buffered _write cb's as it consumes chunks. If consuming a single
// written chunk would result in multiple output chunks, then the first
// outputted bit calls the readcb, and subsequent chunks just go into
// the read buffer, and will cause it to emit 'readable' if necessary.
//
// This way, back-pressure is actually determined by the reading side,
// since _read has to be called to start processing a new chunk. However,
// a pathological inflate type of transform can cause excessive buffering
// here. For example, imagine a stream where every byte of input is
// interpreted as an integer from 0-255, and then results in that many
// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
// 1kb of data being output. In this case, you could write a very small
// amount of input, and end up with a very large amount of output. In
// such a pathological inflating mechanism, there'd be no way to tell
// the system to stop doing the transform. A single 4MB write could
// cause the system to run out of memory.
//
// However, even in such a pathological case, only a single written chunk
// would be consumed, and then the rest would wait (un-transformed) until
// the results of the previous transformed chunk were consumed.
'use strict';
module.exports = Transform;
var Duplex = require('./_stream_duplex');
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
util.inherits(Transform, Duplex);
function TransformState(stream) {
this.afterTransform = function (er, data) {
return afterTransform(stream, er, data);
};
this.needTransform = false;
this.transforming = false;
this.writecb = null;
this.writechunk = null;
this.writeencoding = null;
}
function afterTransform(stream, er, data) {
var ts = stream._transformState;
ts.transforming = false;
var cb = ts.writecb;
if (!cb) return stream.emit('error', new Error('no writecb in Transform class'));
ts.writechunk = null;
ts.writecb = null;
if (data !== null && data !== undefined) stream.push(data);
cb(er);
var rs = stream._readableState;
rs.reading = false;
if (rs.needReadable || rs.length < rs.highWaterMark) {
stream._read(rs.highWaterMark);
}
}
function Transform(options) {
if (!(this instanceof Transform)) return new Transform(options);
Duplex.call(this, options);
this._transformState = new TransformState(this);
// when the writable side finishes, then flush out anything remaining.
var stream = this;
// start out asking for a readable event once data is transformed.
this._readableState.needReadable = true;
// we have implemented the _read method, and done the other things
// that Readable wants before the first _read call, so unset the
// sync guard flag.
this._readableState.sync = false;
if (options) {
if (typeof options.transform === 'function') this._transform = options.transform;
if (typeof options.flush === 'function') this._flush = options.flush;
}
this.once('prefinish', function () {
if (typeof this._flush === 'function') this._flush(function (er) {
done(stream, er);
});else done(stream);
});
}
Transform.prototype.push = function (chunk, encoding) {
this._transformState.needTransform = false;
return Duplex.prototype.push.call(this, chunk, encoding);
};
// This is the part where you do stuff!
// override this function in implementation classes.
// 'chunk' is an input chunk.
//
// Call `push(newChunk)` to pass along transformed output
// to the readable side. You may call 'push' zero or more times.
//
// Call `cb(err)` when you are done with this chunk. If you pass
// an error, then that'll put the hurt on the whole operation. If you
// never call cb(), then you'll never get another chunk.
Transform.prototype._transform = function (chunk, encoding, cb) {
throw new Error('Not implemented');
};
Transform.prototype._write = function (chunk, encoding, cb) {
var ts = this._transformState;
ts.writecb = cb;
ts.writechunk = chunk;
ts.writeencoding = encoding;
if (!ts.transforming) {
var rs = this._readableState;
if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
}
};
// Doesn't matter what the args are here.
// _transform does all the work.
// That we got here means that the readable side wants more data.
Transform.prototype._read = function (n) {
var ts = this._transformState;
if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
ts.transforming = true;
this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
} else {
// mark that we need a transform, so that any data that comes in
// will get processed, now that we've asked for it.
ts.needTransform = true;
}
};
function done(stream, er) {
if (er) return stream.emit('error', er);
// if there's nothing in the write buffer, then that means
// that nothing more will ever be provided
var ws = stream._writableState;
var ts = stream._transformState;
if (ws.length) throw new Error('Calling transform done when ws.length != 0');
if (ts.transforming) throw new Error('Calling transform done when still transforming');
return stream.push(null);
}
},{"./_stream_duplex":69,"core-util-is":45,"inherits":51}],73:[function(require,module,exports){
(function (process){
// A bit simpler than readable streams.
// Implement an async ._write(chunk, encoding, cb), and it'll handle all
// the drain event emission and buffering.
'use strict';
module.exports = Writable;
/*<replacement>*/
var processNextTick = require('process-nextick-args');
/*</replacement>*/
/*<replacement>*/
var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : processNextTick;
/*</replacement>*/
Writable.WritableState = WritableState;
/*<replacement>*/
var util = require('core-util-is');
util.inherits = require('inherits');
/*</replacement>*/
/*<replacement>*/
var internalUtil = {
deprecate: require('util-deprecate')
};
/*</replacement>*/
/*<replacement>*/
var Stream;
(function () {
try {
Stream = require('st' + 'ream');
} catch (_) {} finally {
if (!Stream) Stream = require('events').EventEmitter;
}
})();
/*</replacement>*/
var Buffer = require('buffer').Buffer;
/*<replacement>*/
var bufferShim = require('buffer-shims');
/*</replacement>*/
util.inherits(Writable, Stream);
function nop() {}
function WriteReq(chunk, encoding, cb) {
this.chunk = chunk;
this.encoding = encoding;
this.callback = cb;
this.next = null;
}
var Duplex;
function WritableState(options, stream) {
Duplex = Duplex || require('./_stream_duplex');
options = options || {};
// object stream flag to indicate whether or not this stream
// contains buffers or objects.
this.objectMode = !!options.objectMode;
if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
// the point at which write() starts returning false
// Note: 0 is a valid value, means that we always return false if
// the entire buffer is not flushed immediately on write()
var hwm = options.highWaterMark;
var defaultHwm = this.objectMode ? 16 : 16 * 1024;
this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
// cast to ints.
this.highWaterMark = ~ ~this.highWaterMark;
this.needDrain = false;
// at the start of calling end()
this.ending = false;
// when end() has been called, and returned
this.ended = false;
// when 'finish' is emitted
this.finished = false;
// should we decode strings into buffers before passing to _write?
// this is here so that some node-core streams can optimize string
// handling at a lower level.
var noDecode = options.decodeStrings === false;
this.decodeStrings = !noDecode;
// Crypto is kind of old and crusty. Historically, its default string
// encoding is 'binary' so we have to make this configurable.
// Everything else in the universe uses 'utf8', though.
this.defaultEncoding = options.defaultEncoding || 'utf8';
// not an actual buffer we keep track of, but a measurement
// of how much we're waiting to get pushed to some underlying
// socket or file.
this.length = 0;
// a flag to see when we're in the middle of a write.
this.writing = false;
// when true all writes will be buffered until .uncork() call
this.corked = 0;
// a flag to be able to tell if the onwrite cb is called immediately,
// or on a later tick. We set this to true at first, because any
// actions that shouldn't happen until "later" should generally also
// not happen before the first write call.
this.sync = true;
// a flag to know if we're processing previously buffered items, which
// may call the _write() callback in the same tick, so that we don't
// end up in an overlapped onwrite situation.
this.bufferProcessing = false;
// the callback that's passed to _write(chunk,cb)
this.onwrite = function (er) {
onwrite(stream, er);
};
// the callback that the user supplies to write(chunk,encoding,cb)
this.writecb = null;
// the amount that is being written when _write is called.
this.writelen = 0;
this.bufferedRequest = null;
this.lastBufferedRequest = null;
// number of pending user-supplied write callbacks
// this must be 0 before 'finish' can be emitted
this.pendingcb = 0;
// emit prefinish if the only thing we're waiting for is _write cbs
// This is relevant for synchronous Transform streams
this.prefinished = false;
// True if the error was already emitted and should not be thrown again
this.errorEmitted = false;
// count buffered requests
this.bufferedRequestCount = 0;
// allocate the first CorkedRequest, there is always
// one allocated and free to use, and we maintain at most two
this.corkedRequestsFree = new CorkedRequest(this);
}
WritableState.prototype.getBuffer = function writableStateGetBuffer() {
var current = this.bufferedRequest;
var out = [];
while (current) {
out.push(current);
current = current.next;
}
return out;
};
(function () {
try {
Object.defineProperty(WritableState.prototype, 'buffer', {
get: internalUtil.deprecate(function () {
return this.getBuffer();
}, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.')
});
} catch (_) {}
})();
var Duplex;
function Writable(options) {
Duplex = Duplex || require('./_stream_duplex');
// Writable ctor is applied to Duplexes, though they're not
// instanceof Writable, they're instanceof Readable.
if (!(this instanceof Writable) && !(this instanceof Duplex)) return new Writable(options);
this._writableState = new WritableState(options, this);
// legacy.
this.writable = true;
if (options) {
if (typeof options.write === 'function') this._write = options.write;
if (typeof options.writev === 'function') this._writev = options.writev;
}
Stream.call(this);
}
// Otherwise people can pipe Writable streams, which is just wrong.
Writable.prototype.pipe = function () {
this.emit('error', new Error('Cannot pipe, not readable'));
};
function writeAfterEnd(stream, cb) {
var er = new Error('write after end');
// TODO: defer error events consistently everywhere, not just the cb
stream.emit('error', er);
processNextTick(cb, er);
}
// If we get something that is not a buffer, string, null, or undefined,
// and we're not in objectMode, then that's an error.
// Otherwise stream chunks are all considered to be of length=1, and the
// watermarks determine how many objects to keep in the buffer, rather than
// how many bytes or characters.
function validChunk(stream, state, chunk, cb) {
var valid = true;
var er = false;
// Always throw error if a null is written
// if we are not in object mode then throw
// if it is not a buffer, string, or undefined.
if (chunk === null) {
er = new TypeError('May not write null values to stream');
} else if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
er = new TypeError('Invalid non-string/buffer chunk');
}
if (er) {
stream.emit('error', er);
processNextTick(cb, er);
valid = false;
}
return valid;
}
Writable.prototype.write = function (chunk, encoding, cb) {
var state = this._writableState;
var ret = false;
if (typeof encoding === 'function') {
cb = encoding;
encoding = null;
}
if (Buffer.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
if (typeof cb !== 'function') cb = nop;
if (state.ended) writeAfterEnd(this, cb);else if (validChunk(this, state, chunk, cb)) {
state.pendingcb++;
ret = writeOrBuffer(this, state, chunk, encoding, cb);
}
return ret;
};
Writable.prototype.cork = function () {
var state = this._writableState;
state.corked++;
};
Writable.prototype.uncork = function () {
var state = this._writableState;
if (state.corked) {
state.corked--;
if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
}
};
Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
// node::ParseEncoding() requires lower case.
if (typeof encoding === 'string') encoding = encoding.toLowerCase();
if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding);
this._writableState.defaultEncoding = encoding;
return this;
};
function decodeChunk(state, chunk, encoding) {
if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
chunk = bufferShim.from(chunk, encoding);
}
return chunk;
}
// if we're already writing something, then just put this
// in the queue, and wait our turn. Otherwise, call _write
// If we return false, then we need a drain event, so set that flag.
function writeOrBuffer(stream, state, chunk, encoding, cb) {
chunk = decodeChunk(state, chunk, encoding);
if (Buffer.isBuffer(chunk)) encoding = 'buffer';
var len = state.objectMode ? 1 : chunk.length;
state.length += len;
var ret = state.length < state.highWaterMark;
// we must ensure that previous needDrain will not be reset to false.
if (!ret) state.needDrain = true;
if (state.writing || state.corked) {
var last = state.lastBufferedRequest;
state.lastBufferedRequest = new WriteReq(chunk, encoding, cb);
if (last) {
last.next = state.lastBufferedRequest;
} else {
state.bufferedRequest = state.lastBufferedRequest;
}
state.bufferedRequestCount += 1;
} else {
doWrite(stream, state, false, len, chunk, encoding, cb);
}
return ret;
}
function doWrite(stream, state, writev, len, chunk, encoding, cb) {
state.writelen = len;
state.writecb = cb;
state.writing = true;
state.sync = true;
if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
state.sync = false;
}
function onwriteError(stream, state, sync, er, cb) {
--state.pendingcb;
if (sync) processNextTick(cb, er);else cb(er);
stream._writableState.errorEmitted = true;
stream.emit('error', er);
}
function onwriteStateUpdate(state) {
state.writing = false;
state.writecb = null;
state.length -= state.writelen;
state.writelen = 0;
}
function onwrite(stream, er) {
var state = stream._writableState;
var sync = state.sync;
var cb = state.writecb;
onwriteStateUpdate(state);
if (er) onwriteError(stream, state, sync, er, cb);else {
// Check if we're actually ready to finish, but don't emit yet
var finished = needFinish(state);
if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
clearBuffer(stream, state);
}
if (sync) {
/*<replacement>*/
asyncWrite(afterWrite, stream, state, finished, cb);
/*</replacement>*/
} else {
afterWrite(stream, state, finished, cb);
}
}
}
function afterWrite(stream, state, finished, cb) {
if (!finished) onwriteDrain(stream, state);
state.pendingcb--;
cb();
finishMaybe(stream, state);
}
// Must force callback to be called on nextTick, so that we don't
// emit 'drain' before the write() consumer gets the 'false' return
// value, and has a chance to attach a 'drain' listener.
function onwriteDrain(stream, state) {
if (state.length === 0 && state.needDrain) {
state.needDrain = false;
stream.emit('drain');
}
}
// if there's something in the buffer waiting, then process it
function clearBuffer(stream, state) {
state.bufferProcessing = true;
var entry = state.bufferedRequest;
if (stream._writev && entry && entry.next) {
// Fast case, write everything using _writev()
var l = state.bufferedRequestCount;
var buffer = new Array(l);
var holder = state.corkedRequestsFree;
holder.entry = entry;
var count = 0;
while (entry) {
buffer[count] = entry;
entry = entry.next;
count += 1;
}
doWrite(stream, state, true, state.length, buffer, '', holder.finish);
// doWrite is almost always async, defer these to save a bit of time
// as the hot path ends with doWrite
state.pendingcb++;
state.lastBufferedRequest = null;
if (holder.next) {
state.corkedRequestsFree = holder.next;
holder.next = null;
} else {
state.corkedRequestsFree = new CorkedRequest(state);
}
} else {
// Slow case, write chunks one-by-one
while (entry) {
var chunk = entry.chunk;
var encoding = entry.encoding;
var cb = entry.callback;
var len = state.objectMode ? 1 : chunk.length;
doWrite(stream, state, false, len, chunk, encoding, cb);
entry = entry.next;
// if we didn't call the onwrite immediately, then
// it means that we need to wait until it does.
// also, that means that the chunk and cb are currently
// being processed, so move the buffer counter past them.
if (state.writing) {
break;
}
}
if (entry === null) state.lastBufferedRequest = null;
}
state.bufferedRequestCount = 0;
state.bufferedRequest = entry;
state.bufferProcessing = false;
}
Writable.prototype._write = function (chunk, encoding, cb) {
cb(new Error('not implemented'));
};
Writable.prototype._writev = null;
Writable.prototype.end = function (chunk, encoding, cb) {
var state = this._writableState;
if (typeof chunk === 'function') {
cb = chunk;
chunk = null;
encoding = null;
} else if (typeof encoding === 'function') {
cb = encoding;
encoding = null;
}
if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
// .end() fully uncorks
if (state.corked) {
state.corked = 1;
this.uncork();
}
// ignore unnecessary end() calls.
if (!state.ending && !state.finished) endWritable(this, state, cb);
};
function needFinish(state) {
return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
}
function prefinish(stream, state) {
if (!state.prefinished) {
state.prefinished = true;
stream.emit('prefinish');
}
}
function finishMaybe(stream, state) {
var need = needFinish(state);
if (need) {
if (state.pendingcb === 0) {
prefinish(stream, state);
state.finished = true;
stream.emit('finish');
} else {
prefinish(stream, state);
}
}
return need;
}
function endWritable(stream, state, cb) {
state.ending = true;
finishMaybe(stream, state);
if (cb) {
if (state.finished) processNextTick(cb);else stream.once('finish', cb);
}
state.ended = true;
stream.writable = false;
}
// It seems a linked list but it is not
// there will be only 2 of these for each stream
function CorkedRequest(state) {
var _this = this;
this.next = null;
this.entry = null;
this.finish = function (err) {
var entry = _this.entry;
_this.entry = null;
while (entry) {
var cb = entry.callback;
state.pendingcb--;
cb(err);
entry = entry.next;
}
if (state.corkedRequestsFree) {
state.corkedRequestsFree.next = _this;
} else {
state.corkedRequestsFree = _this;
}
};
}
}).call(this,require('_process'))
},{"./_stream_duplex":69,"_process":67,"buffer":44,"buffer-shims":43,"core-util-is":45,"events":48,"inherits":51,"process-nextick-args":66,"util-deprecate":81}],74:[function(require,module,exports){
'use strict';
var Buffer = require('buffer').Buffer;
/*<replacement>*/
var bufferShim = require('buffer-shims');
/*</replacement>*/
module.exports = BufferList;
function BufferList() {
this.head = null;
this.tail = null;
this.length = 0;
}
BufferList.prototype.push = function (v) {
var entry = { data: v, next: null };
if (this.length > 0) this.tail.next = entry;else this.head = entry;
this.tail = entry;
++this.length;
};
BufferList.prototype.unshift = function (v) {
var entry = { data: v, next: this.head };
if (this.length === 0) this.tail = entry;
this.head = entry;
++this.length;
};
BufferList.prototype.shift = function () {
if (this.length === 0) return;
var ret = this.head.data;
if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
--this.length;
return ret;
};
BufferList.prototype.clear = function () {
this.head = this.tail = null;
this.length = 0;
};
BufferList.prototype.join = function (s) {
if (this.length === 0) return '';
var p = this.head;
var ret = '' + p.data;
while (p = p.next) {
ret += s + p.data;
}return ret;
};
BufferList.prototype.concat = function (n) {
if (this.length === 0) return bufferShim.alloc(0);
if (this.length === 1) return this.head.data;
var ret = bufferShim.allocUnsafe(n >>> 0);
var p = this.head;
var i = 0;
while (p) {
p.data.copy(ret, i);
i += p.data.length;
p = p.next;
}
return ret;
};
},{"buffer":44,"buffer-shims":43}],75:[function(require,module,exports){
module.exports = require("./lib/_stream_passthrough.js")
},{"./lib/_stream_passthrough.js":70}],76:[function(require,module,exports){
(function (process){
var Stream = (function (){
try {
return require('st' + 'ream'); // hack to fix a circular dependency issue when used with browserify
} catch(_){}
}());
exports = module.exports = require('./lib/_stream_readable.js');
exports.Stream = Stream || exports;
exports.Readable = exports;
exports.Writable = require('./lib/_stream_writable.js');
exports.Duplex = require('./lib/_stream_duplex.js');
exports.Transform = require('./lib/_stream_transform.js');
exports.PassThrough = require('./lib/_stream_passthrough.js');
if (!process.browser && process.env.READABLE_STREAM === 'disable' && Stream) {
module.exports = Stream;
}
}).call(this,require('_process'))
},{"./lib/_stream_duplex.js":69,"./lib/_stream_passthrough.js":70,"./lib/_stream_readable.js":71,"./lib/_stream_transform.js":72,"./lib/_stream_writable.js":73,"_process":67}],77:[function(require,module,exports){
module.exports = require("./lib/_stream_transform.js")
},{"./lib/_stream_transform.js":72}],78:[function(require,module,exports){
module.exports = require("./lib/_stream_writable.js")
},{"./lib/_stream_writable.js":73}],79:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
module.exports = Stream;
var EE = require('events').EventEmitter;
var inherits = require('inherits');
inherits(Stream, EE);
Stream.Readable = require('readable-stream/readable.js');
Stream.Writable = require('readable-stream/writable.js');
Stream.Duplex = require('readable-stream/duplex.js');
Stream.Transform = require('readable-stream/transform.js');
Stream.PassThrough = require('readable-stream/passthrough.js');
// Backwards-compat with node 0.4.x
Stream.Stream = Stream;
// old-style streams. Note that the pipe method (the only relevant
// part of this class) is overridden in the Readable class.
function Stream() {
EE.call(this);
}
Stream.prototype.pipe = function(dest, options) {
var source = this;
function ondata(chunk) {
if (dest.writable) {
if (false === dest.write(chunk) && source.pause) {
source.pause();
}
}
}
source.on('data', ondata);
function ondrain() {
if (source.readable && source.resume) {
source.resume();
}
}
dest.on('drain', ondrain);
// If the 'end' option is not supplied, dest.end() will be called when
// source gets the 'end' or 'close' events. Only dest.end() once.
if (!dest._isStdio && (!options || options.end !== false)) {
source.on('end', onend);
source.on('close', onclose);
}
var didOnEnd = false;
function onend() {
if (didOnEnd) return;
didOnEnd = true;
dest.end();
}
function onclose() {
if (didOnEnd) return;
didOnEnd = true;
if (typeof dest.destroy === 'function') dest.destroy();
}
// don't leave dangling pipes when there are errors.
function onerror(er) {
cleanup();
if (EE.listenerCount(this, 'error') === 0) {
throw er; // Unhandled stream error in pipe.
}
}
source.on('error', onerror);
dest.on('error', onerror);
// remove all the event listeners that were added.
function cleanup() {
source.removeListener('data', ondata);
dest.removeListener('drain', ondrain);
source.removeListener('end', onend);
source.removeListener('close', onclose);
source.removeListener('error', onerror);
dest.removeListener('error', onerror);
source.removeListener('end', cleanup);
source.removeListener('close', cleanup);
dest.removeListener('close', cleanup);
}
source.on('end', cleanup);
source.on('close', cleanup);
dest.on('close', cleanup);
dest.emit('pipe', source);
// Allow for unix-like usage: A.pipe(B).pipe(C)
return dest;
};
},{"events":48,"inherits":51,"readable-stream/duplex.js":68,"readable-stream/passthrough.js":75,"readable-stream/readable.js":76,"readable-stream/transform.js":77,"readable-stream/writable.js":78}],80:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
var Buffer = require('buffer').Buffer;
var isBufferEncoding = Buffer.isEncoding
|| function(encoding) {
switch (encoding && encoding.toLowerCase()) {
case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true;
default: return false;
}
}
function assertEncoding(encoding) {
if (encoding && !isBufferEncoding(encoding)) {
throw new Error('Unknown encoding: ' + encoding);
}
}
// StringDecoder provides an interface for efficiently splitting a series of
// buffers into a series of JS strings without breaking apart multi-byte
// characters. CESU-8 is handled as part of the UTF-8 encoding.
//
// @TODO Handling all encodings inside a single object makes it very difficult
// to reason about this code, so it should be split up in the future.
// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code
// points as used by CESU-8.
var StringDecoder = exports.StringDecoder = function(encoding) {
this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, '');
assertEncoding(encoding);
switch (this.encoding) {
case 'utf8':
// CESU-8 represents each of Surrogate Pair by 3-bytes
this.surrogateSize = 3;
break;
case 'ucs2':
case 'utf16le':
// UTF-16 represents each of Surrogate Pair by 2-bytes
this.surrogateSize = 2;
this.detectIncompleteChar = utf16DetectIncompleteChar;
break;
case 'base64':
// Base-64 stores 3 bytes in 4 chars, and pads the remainder.
this.surrogateSize = 3;
this.detectIncompleteChar = base64DetectIncompleteChar;
break;
default:
this.write = passThroughWrite;
return;
}
// Enough space to store all bytes of a single character. UTF-8 needs 4
// bytes, but CESU-8 may require up to 6 (3 bytes per surrogate).
this.charBuffer = new Buffer(6);
// Number of bytes received for the current incomplete multi-byte character.
this.charReceived = 0;
// Number of bytes expected for the current incomplete multi-byte character.
this.charLength = 0;
};
// write decodes the given buffer and returns it as JS string that is
// guaranteed to not contain any partial multi-byte characters. Any partial
// character found at the end of the buffer is buffered up, and will be
// returned when calling write again with the remaining bytes.
//
// Note: Converting a Buffer containing an orphan surrogate to a String
// currently works, but converting a String to a Buffer (via `new Buffer`, or
// Buffer#write) will replace incomplete surrogates with the unicode
// replacement character. See https://codereview.chromium.org/121173009/ .
StringDecoder.prototype.write = function(buffer) {
var charStr = '';
// if our last write ended with an incomplete multibyte character
while (this.charLength) {
// determine how many remaining bytes this buffer has to offer for this char
var available = (buffer.length >= this.charLength - this.charReceived) ?
this.charLength - this.charReceived :
buffer.length;
// add the new bytes to the char buffer
buffer.copy(this.charBuffer, this.charReceived, 0, available);
this.charReceived += available;
if (this.charReceived < this.charLength) {
// still not enough chars in this buffer? wait for more ...
return '';
}
// remove bytes belonging to the current character from the buffer
buffer = buffer.slice(available, buffer.length);
// get the character that was split
charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding);
// CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
var charCode = charStr.charCodeAt(charStr.length - 1);
if (charCode >= 0xD800 && charCode <= 0xDBFF) {
this.charLength += this.surrogateSize;
charStr = '';
continue;
}
this.charReceived = this.charLength = 0;
// if there are no more bytes in this buffer, just emit our char
if (buffer.length === 0) {
return charStr;
}
break;
}
// determine and set charLength / charReceived
this.detectIncompleteChar(buffer);
var end = buffer.length;
if (this.charLength) {
// buffer the incomplete character bytes we got
buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end);
end -= this.charReceived;
}
charStr += buffer.toString(this.encoding, 0, end);
var end = charStr.length - 1;
var charCode = charStr.charCodeAt(end);
// CESU-8: lead surrogate (D800-DBFF) is also the incomplete character
if (charCode >= 0xD800 && charCode <= 0xDBFF) {
var size = this.surrogateSize;
this.charLength += size;
this.charReceived += size;
this.charBuffer.copy(this.charBuffer, size, 0, size);
buffer.copy(this.charBuffer, 0, 0, size);
return charStr.substring(0, end);
}
// or just emit the charStr
return charStr;
};
// detectIncompleteChar determines if there is an incomplete UTF-8 character at
// the end of the given buffer. If so, it sets this.charLength to the byte
// length that character, and sets this.charReceived to the number of bytes
// that are available for this character.
StringDecoder.prototype.detectIncompleteChar = function(buffer) {
// determine how many bytes we have to check at the end of this buffer
var i = (buffer.length >= 3) ? 3 : buffer.length;
// Figure out if one of the last i bytes of our buffer announces an
// incomplete char.
for (; i > 0; i--) {
var c = buffer[buffer.length - i];
// See http://en.wikipedia.org/wiki/UTF-8#Description
// 110XXXXX
if (i == 1 && c >> 5 == 0x06) {
this.charLength = 2;
break;
}
// 1110XXXX
if (i <= 2 && c >> 4 == 0x0E) {
this.charLength = 3;
break;
}
// 11110XXX
if (i <= 3 && c >> 3 == 0x1E) {
this.charLength = 4;
break;
}
}
this.charReceived = i;
};
StringDecoder.prototype.end = function(buffer) {
var res = '';
if (buffer && buffer.length)
res = this.write(buffer);
if (this.charReceived) {
var cr = this.charReceived;
var buf = this.charBuffer;
var enc = this.encoding;
res += buf.slice(0, cr).toString(enc);
}
return res;
};
function passThroughWrite(buffer) {
return buffer.toString(this.encoding);
}
function utf16DetectIncompleteChar(buffer) {
this.charReceived = buffer.length % 2;
this.charLength = this.charReceived ? 2 : 0;
}
function base64DetectIncompleteChar(buffer) {
this.charReceived = buffer.length % 3;
this.charLength = this.charReceived ? 3 : 0;
}
},{"buffer":44}],81:[function(require,module,exports){
(function (global){
/**
* Module exports.
*/
module.exports = deprecate;
/**
* Mark that a method should not be used.
* Returns a modified function which warns once by default.
*
* If `localStorage.noDeprecation = true` is set, then it is a no-op.
*
* If `localStorage.throwDeprecation = true` is set, then deprecated functions
* will throw an Error when invoked.
*
* If `localStorage.traceDeprecation = true` is set, then deprecated functions
* will invoke `console.trace()` instead of `console.error()`.
*
* @param {Function} fn - the function to deprecate
* @param {String} msg - the string to print to the console when `fn` is invoked
* @returns {Function} a new "deprecated" version of `fn`
* @api public
*/
function deprecate (fn, msg) {
if (config('noDeprecation')) {
return fn;
}
var warned = false;
function deprecated() {
if (!warned) {
if (config('throwDeprecation')) {
throw new Error(msg);
} else if (config('traceDeprecation')) {
console.trace(msg);
} else {
console.warn(msg);
}
warned = true;
}
return fn.apply(this, arguments);
}
return deprecated;
}
/**
* Checks `localStorage` for boolean values for the given `name`.
*
* @param {String} name
* @returns {Boolean}
* @api private
*/
function config (name) {
// accessing global.localStorage can trigger a DOMException in sandboxed iframes
try {
if (!global.localStorage) return false;
} catch (_) {
return false;
}
var val = global.localStorage[name];
if (null == val) return false;
return String(val).toLowerCase() === 'true';
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],82:[function(require,module,exports){
arguments[4][51][0].apply(exports,arguments)
},{"dup":51}],83:[function(require,module,exports){
module.exports = function isBuffer(arg) {
return arg && typeof arg === 'object'
&& typeof arg.copy === 'function'
&& typeof arg.fill === 'function'
&& typeof arg.readUInt8 === 'function';
}
},{}],84:[function(require,module,exports){
(function (process,global){
// Copyright Joyent, Inc. and other Node contributors.
//
// 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.
var formatRegExp = /%[sdj%]/g;
exports.format = function(f) {
if (!isString(f)) {
var objects = [];
for (var i = 0; i < arguments.length; i++) {
objects.push(inspect(arguments[i]));
}
return objects.join(' ');
}
var i = 1;
var args = arguments;
var len = args.length;
var str = String(f).replace(formatRegExp, function(x) {
if (x === '%%') return '%';
if (i >= len) return x;
switch (x) {
case '%s': return String(args[i++]);
case '%d': return Number(args[i++]);
case '%j':
try {
return JSON.stringify(args[i++]);
} catch (_) {
return '[Circular]';
}
default:
return x;
}
});
for (var x = args[i]; i < len; x = args[++i]) {
if (isNull(x) || !isObject(x)) {
str += ' ' + x;
} else {
str += ' ' + inspect(x);
}
}
return str;
};
// Mark that a method should not be used.
// Returns a modified function which warns once by default.
// If --no-deprecation is set, then it is a no-op.
exports.deprecate = function(fn, msg) {
// Allow for deprecating things in the process of starting up.
if (isUndefined(global.process)) {
return function() {
return exports.deprecate(fn, msg).apply(this, arguments);
};
}
if (process.noDeprecation === true) {
return fn;
}
var warned = false;
function deprecated() {
if (!warned) {
if (process.throwDeprecation) {
throw new Error(msg);
} else if (process.traceDeprecation) {
console.trace(msg);
} else {
console.error(msg);
}
warned = true;
}
return fn.apply(this, arguments);
}
return deprecated;
};
var debugs = {};
var debugEnviron;
exports.debuglog = function(set) {
if (isUndefined(debugEnviron))
debugEnviron = process.env.NODE_DEBUG || '';
set = set.toUpperCase();
if (!debugs[set]) {
if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
var pid = process.pid;
debugs[set] = function() {
var msg = exports.format.apply(exports, arguments);
console.error('%s %d: %s', set, pid, msg);
};
} else {
debugs[set] = function() {};
}
}
return debugs[set];
};
/**
* Echos the value of a value. Trys to print the value out
* in the best way possible given the different types.
*
* @param {Object} obj The object to print out.
* @param {Object} opts Optional options object that alters the output.
*/
/* legacy: obj, showHidden, depth, colors*/
function inspect(obj, opts) {
// default options
var ctx = {
seen: [],
stylize: stylizeNoColor
};
// legacy...
if (arguments.length >= 3) ctx.depth = arguments[2];
if (arguments.length >= 4) ctx.colors = arguments[3];
if (isBoolean(opts)) {
// legacy...
ctx.showHidden = opts;
} else if (opts) {
// got an "options" object
exports._extend(ctx, opts);
}
// set default options
if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
if (isUndefined(ctx.depth)) ctx.depth = 2;
if (isUndefined(ctx.colors)) ctx.colors = false;
if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
if (ctx.colors) ctx.stylize = stylizeWithColor;
return formatValue(ctx, obj, ctx.depth);
}
exports.inspect = inspect;
// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
inspect.colors = {
'bold' : [1, 22],
'italic' : [3, 23],
'underline' : [4, 24],
'inverse' : [7, 27],
'white' : [37, 39],
'grey' : [90, 39],
'black' : [30, 39],
'blue' : [34, 39],
'cyan' : [36, 39],
'green' : [32, 39],
'magenta' : [35, 39],
'red' : [31, 39],
'yellow' : [33, 39]
};
// Don't use 'blue' not visible on cmd.exe
inspect.styles = {
'special': 'cyan',
'number': 'yellow',
'boolean': 'yellow',
'undefined': 'grey',
'null': 'bold',
'string': 'green',
'date': 'magenta',
// "name": intentionally not styling
'regexp': 'red'
};
function stylizeWithColor(str, styleType) {
var style = inspect.styles[styleType];
if (style) {
return '\u001b[' + inspect.colors[style][0] + 'm' + str +
'\u001b[' + inspect.colors[style][1] + 'm';
} else {
return str;
}
}
function stylizeNoColor(str, styleType) {
return str;
}
function arrayToHash(array) {
var hash = {};
array.forEach(function(val, idx) {
hash[val] = true;
});
return hash;
}
function formatValue(ctx, value, recurseTimes) {
// Provide a hook for user-specified inspect functions.
// Check that value is an object with an inspect function on it
if (ctx.customInspect &&
value &&
isFunction(value.inspect) &&
// Filter out the util module, it's inspect function is special
value.inspect !== exports.inspect &&
// Also filter out any prototype objects using the circular check.
!(value.constructor && value.constructor.prototype === value)) {
var ret = value.inspect(recurseTimes, ctx);
if (!isString(ret)) {
ret = formatValue(ctx, ret, recurseTimes);
}
return ret;
}
// Primitive types cannot have properties
var primitive = formatPrimitive(ctx, value);
if (primitive) {
return primitive;
}
// Look up the keys of the object.
var keys = Object.keys(value);
var visibleKeys = arrayToHash(keys);
if (ctx.showHidden) {
keys = Object.getOwnPropertyNames(value);
}
// IE doesn't make error fields non-enumerable
// http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
if (isError(value)
&& (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
return formatError(value);
}
// Some type of object without properties can be shortcutted.
if (keys.length === 0) {
if (isFunction(value)) {
var name = value.name ? ': ' + value.name : '';
return ctx.stylize('[Function' + name + ']', 'special');
}
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
}
if (isDate(value)) {
return ctx.stylize(Date.prototype.toString.call(value), 'date');
}
if (isError(value)) {
return formatError(value);
}
}
var base = '', array = false, braces = ['{', '}'];
// Make Array say that they are Array
if (isArray(value)) {
array = true;
braces = ['[', ']'];
}
// Make functions say that they are functions
if (isFunction(value)) {
var n = value.name ? ': ' + value.name : '';
base = ' [Function' + n + ']';
}
// Make RegExps say that they are RegExps
if (isRegExp(value)) {
base = ' ' + RegExp.prototype.toString.call(value);
}
// Make dates with properties first say the date
if (isDate(value)) {
base = ' ' + Date.prototype.toUTCString.call(value);
}
// Make error with message first say the error
if (isError(value)) {
base = ' ' + formatError(value);
}
if (keys.length === 0 && (!array || value.length == 0)) {
return braces[0] + base + braces[1];
}
if (recurseTimes < 0) {
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
} else {
return ctx.stylize('[Object]', 'special');
}
}
ctx.seen.push(value);
var output;
if (array) {
output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
} else {
output = keys.map(function(key) {
return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
});
}
ctx.seen.pop();
return reduceToSingleString(output, base, braces);
}
function formatPrimitive(ctx, value) {
if (isUndefined(value))
return ctx.stylize('undefined', 'undefined');
if (isString(value)) {
var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
.replace(/'/g, "\\'")
.replace(/\\"/g, '"') + '\'';
return ctx.stylize(simple, 'string');
}
if (isNumber(value))
return ctx.stylize('' + value, 'number');
if (isBoolean(value))
return ctx.stylize('' + value, 'boolean');
// For some reason typeof null is "object", so special case here.
if (isNull(value))
return ctx.stylize('null', 'null');
}
function formatError(value) {
return '[' + Error.prototype.toString.call(value) + ']';
}
function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
var output = [];
for (var i = 0, l = value.length; i < l; ++i) {
if (hasOwnProperty(value, String(i))) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
String(i), true));
} else {
output.push('');
}
}
keys.forEach(function(key) {
if (!key.match(/^\d+$/)) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
key, true));
}
});
return output;
}
function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
var name, str, desc;
desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
if (desc.get) {
if (desc.set) {
str = ctx.stylize('[Getter/Setter]', 'special');
} else {
str = ctx.stylize('[Getter]', 'special');
}
} else {
if (desc.set) {
str = ctx.stylize('[Setter]', 'special');
}
}
if (!hasOwnProperty(visibleKeys, key)) {
name = '[' + key + ']';
}
if (!str) {
if (ctx.seen.indexOf(desc.value) < 0) {
if (isNull(recurseTimes)) {
str = formatValue(ctx, desc.value, null);
} else {
str = formatValue(ctx, desc.value, recurseTimes - 1);
}
if (str.indexOf('\n') > -1) {
if (array) {
str = str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n').substr(2);
} else {
str = '\n' + str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n');
}
}
} else {
str = ctx.stylize('[Circular]', 'special');
}
}
if (isUndefined(name)) {
if (array && key.match(/^\d+$/)) {
return str;
}
name = JSON.stringify('' + key);
if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
name = name.substr(1, name.length - 2);
name = ctx.stylize(name, 'name');
} else {
name = name.replace(/'/g, "\\'")
.replace(/\\"/g, '"')
.replace(/(^"|"$)/g, "'");
name = ctx.stylize(name, 'string');
}
}
return name + ': ' + str;
}
function reduceToSingleString(output, base, braces) {
var numLinesEst = 0;
var length = output.reduce(function(prev, cur) {
numLinesEst++;
if (cur.indexOf('\n') >= 0) numLinesEst++;
return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
}, 0);
if (length > 60) {
return braces[0] +
(base === '' ? '' : base + '\n ') +
' ' +
output.join(',\n ') +
' ' +
braces[1];
}
return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
}
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(ar) {
return Array.isArray(ar);
}
exports.isArray = isArray;
function isBoolean(arg) {
return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;
function isNull(arg) {
return arg === null;
}
exports.isNull = isNull;
function isNullOrUndefined(arg) {
return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;
function isNumber(arg) {
return typeof arg === 'number';
}
exports.isNumber = isNumber;
function isString(arg) {
return typeof arg === 'string';
}
exports.isString = isString;
function isSymbol(arg) {
return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;
function isUndefined(arg) {
return arg === void 0;
}
exports.isUndefined = isUndefined;
function isRegExp(re) {
return isObject(re) && objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;
function isDate(d) {
return isObject(d) && objectToString(d) === '[object Date]';
}
exports.isDate = isDate;
function isError(e) {
return isObject(e) &&
(objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;
function isFunction(arg) {
return typeof arg === 'function';
}
exports.isFunction = isFunction;
function isPrimitive(arg) {
return arg === null ||
typeof arg === 'boolean' ||
typeof arg === 'number' ||
typeof arg === 'string' ||
typeof arg === 'symbol' || // ES6 symbol
typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;
exports.isBuffer = require('./support/isBuffer');
function objectToString(o) {
return Object.prototype.toString.call(o);
}
function pad(n) {
return n < 10 ? '0' + n.toString(10) : n.toString(10);
}
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
'Oct', 'Nov', 'Dec'];
// 26 Feb 16:19:34
function timestamp() {
var d = new Date();
var time = [pad(d.getHours()),
pad(d.getMinutes()),
pad(d.getSeconds())].join(':');
return [d.getDate(), months[d.getMonth()], time].join(' ');
}
// log is just a thin wrapper to console.log that prepends a timestamp
exports.log = function() {
console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
};
/**
* Inherit the prototype methods from one constructor into another.
*
* The Function.prototype.inherits from lang.js rewritten as a standalone
* function (not on Function.prototype). NOTE: If this file is to be loaded
* during bootstrapping this function needs to be rewritten using some native
* functions as prototype setup using normal JavaScript does not work as
* expected during bootstrapping (see mirror.js in r114903).
*
* @param {function} ctor Constructor function which needs to inherit the
* prototype.
* @param {function} superCtor Constructor function to inherit prototype from.
*/
exports.inherits = require('inherits');
exports._extend = function(origin, add) {
// Don't do anything if add isn't an object
if (!add || !isObject(add)) return origin;
var keys = Object.keys(add);
var i = keys.length;
while (i--) {
origin[keys[i]] = add[keys[i]];
}
return origin;
};
function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./support/isBuffer":83,"_process":67,"inherits":82}]},{},[1]);
|
import { Notes } from '../lib/Notes';
import { Piano_500 } from '../lib/Audio/Audio_500';
let notes = new Notes();
notes.loadAudio([
Piano_500
]);
export default notes;
|
import React from "react";
import freesewing from "@freesewing/core";
import Workbench from "@freesewing/components/Workbench";
import "typeface-roboto-condensed";
import "@freesewing/css-theme";
import Pattern from "pattern";
const App = props => {
let instance = new Pattern();
let config = instance.config;
return (
<Workbench
freesewing={freesewing}
Pattern={Pattern}
config={config}
userLanguage="en"
/>
);
};
export default App;
|
# Copyright 2018 The Cirq Developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The circuit data structure.
Circuits consist of a list of Moments, each Moment made up of a set of
Operations. Each Operation is a Gate that acts on some Qubits, for a given
Moment the Operations must all act on distinct Qubits.
"""
from collections import defaultdict
from fractions import Fraction
from itertools import groupby
import math
from typing import (AbstractSet, Any, Callable, cast, Dict, FrozenSet, Iterable,
Iterator, List, Optional, overload, Sequence, Set, Tuple,
Type, TYPE_CHECKING, TypeVar, Union)
import html
import re
import numpy as np
from cirq import devices, ops, protocols, qis
from cirq.circuits._bucket_priority_queue import BucketPriorityQueue
from cirq.circuits.insert_strategy import InsertStrategy
from cirq.circuits.text_diagram_drawer import TextDiagramDrawer
from cirq.circuits.qasm_output import QasmOutput
from cirq.circuits.quil_output import QuilOutput
from cirq.type_workarounds import NotImplementedType
from cirq._compat import deprecated
import cirq._version
if TYPE_CHECKING:
import cirq
T_DESIRED_GATE_TYPE = TypeVar('T_DESIRED_GATE_TYPE', bound='ops.Gate')
class Circuit:
"""A mutable list of groups of operations to apply to some qubits.
Methods returning information about the circuit:
next_moment_operating_on
prev_moment_operating_on
next_moments_operating_on
operation_at
all_qubits
all_operations
findall_operations
findall_operations_between
findall_operations_until_blocked
findall_operations_with_gate_type
reachable_frontier_from
has_measurements
are_all_matches_terminal
are_all_measurements_terminal
unitary
final_state_vector
to_text_diagram
to_text_diagram_drawer
Methods for mutation:
insert
append
insert_into_range
clear_operations_touching
batch_insert
batch_remove
batch_insert_into
insert_at_frontier
Circuits can also be iterated over,
for moment in circuit:
...
and sliced,
circuit[1:3] is a new Circuit made up of two moments, the first being
circuit[1] and the second being circuit[2];
circuit[:, qubit] is a new Circuit with the same moments, but with only
those operations which act on the given Qubit;
circuit[:, qubits], where 'qubits' is list of Qubits, is a new Circuit
with the same moments, but only with those operations which touch
any of the given qubits;
circuit[1:3, qubit] is equivalent to circuit[1:3][:, qubit];
circuit[1:3, qubits] is equivalent to circuit[1:3][:, qubits];
and concatenated,
circuit1 + circuit2 is a new Circuit made up of the moments in circuit1
followed by the moments in circuit2;
and multiplied by an integer,
circuit * k is a new Circuit made up of the moments in circuit repeated
k times.
and mutated,
circuit[1:7] = [Moment(...)]
"""
def __init__(self,
*contents: 'cirq.OP_TREE',
strategy: 'cirq.InsertStrategy' = InsertStrategy.EARLIEST,
device: 'cirq.Device' = devices.UNCONSTRAINED_DEVICE) -> None:
"""Initializes a circuit.
Args:
contents: The initial list of moments and operations defining the
circuit. You can also pass in operations, lists of operations,
or generally anything meeting the `cirq.OP_TREE` contract.
Non-moment entries will be inserted according to the specified
insertion strategy.
strategy: When initializing the circuit with operations and moments
from `contents`, this determines how the operations are packed
together. This option does not affect later insertions into the
circuit.
device: Hardware that the circuit should be able to run on.
"""
self._moments: List['cirq.Moment'] = []
self._device = device
self.append(contents, strategy=strategy)
@property
def device(self) -> devices.Device:
return self._device
@device.setter
def device(self, new_device: 'cirq.Device') -> None:
new_device.validate_circuit(self)
self._device = new_device
def __copy__(self) -> 'Circuit':
return self.copy()
def copy(self) -> 'Circuit':
copied_circuit = Circuit(device=self._device)
copied_circuit._moments = self._moments[:]
return copied_circuit
def __bool__(self):
return bool(self._moments)
def __eq__(self, other):
if not isinstance(other, type(self)):
return NotImplemented
return self._moments == other._moments and self._device == other._device
def _approx_eq_(self, other: Any, atol: Union[int, float]) -> bool:
"""See `cirq.protocols.SupportsApproximateEquality`."""
if not isinstance(other, type(self)):
return NotImplemented
return cirq.protocols.approx_eq(
self._moments,
other._moments,
atol=atol
) and self._device == other._device
def __ne__(self, other) -> bool:
return not self == other
def __len__(self) -> int:
return len(self._moments)
def __iter__(self) -> Iterator['cirq.Moment']:
return iter(self._moments)
def _decompose_(self) -> 'cirq.OP_TREE':
"""See `cirq.SupportsDecompose`."""
return self.all_operations()
# pylint: disable=function-redefined
@overload
def __getitem__(self, key: slice) -> 'cirq.Circuit':
pass
@overload
def __getitem__(self, key: int) -> 'cirq.Moment':
pass
@overload
def __getitem__(self, key: Tuple[int, 'cirq.Qid']) -> 'cirq.Operation':
pass
@overload
def __getitem__(self,
key: Tuple[int, Iterable['cirq.Qid']]) -> 'cirq.Moment':
pass
@overload
def __getitem__(self, key: Tuple[slice, 'cirq.Qid']) -> 'cirq.Circuit':
pass
@overload
def __getitem__(self,
key: Tuple[slice, Iterable['cirq.Qid']]) -> 'cirq.Circuit':
pass
def __getitem__(self, key):
if isinstance(key, slice):
sliced_circuit = Circuit(device=self.device)
sliced_circuit._moments = self._moments[key]
return sliced_circuit
if hasattr(key, '__index__'):
return self._moments[key]
if isinstance(key, tuple):
if len(key) != 2:
raise ValueError('If key is tuple, it must be a pair.')
moment_idx, qubit_idx = key
# moment_idx - int or slice; qubit_idx - Qid or Iterable[Qid].
selected_moments = self._moments[moment_idx]
# selected_moments - Moment or list[Moment].
if isinstance(selected_moments, list):
if isinstance(qubit_idx, cirq.Qid):
qubit_idx = [qubit_idx]
new_circuit = Circuit(device=self.device)
new_circuit._moments = [
moment[qubit_idx] for moment in selected_moments
]
return new_circuit
return selected_moments[qubit_idx]
raise TypeError(
'__getitem__ called with key not of type slice, int or tuple.')
@overload
def __setitem__(self, key: int, value: 'cirq.Moment'):
pass
@overload
def __setitem__(self, key: slice, value: Iterable['cirq.Moment']):
pass
def __setitem__(self, key, value):
if isinstance(key, int):
if not isinstance(value, ops.Moment):
raise TypeError('Can only assign Moments into Circuits.')
self._device.validate_moment(value)
self._validate_op_tree_qids(value)
if isinstance(key, slice):
value = list(value)
if any(not isinstance(v, ops.Moment) for v in value):
raise TypeError('Can only assign Moments into Circuits.')
for moment in value:
self._device.validate_moment(moment)
self._validate_op_tree_qids(moment)
self._moments[key] = value
# pylint: enable=function-redefined
def __delitem__(self, key: Union[int, slice]):
del self._moments[key]
def __iadd__(self, other):
self.append(other)
return self
def __add__(self, other):
if not isinstance(other, type(self)):
if not isinstance(other, (ops.Operation, Iterable)):
return NotImplemented
# Auto wrap OP_TREE inputs into a circuit.
other = Circuit(other)
device = (self._device if other.device is devices.UNCONSTRAINED_DEVICE
else other.device)
device_2 = (other.device if self._device is devices.UNCONSTRAINED_DEVICE
else self._device)
if device != device_2:
raise ValueError("Can't add circuits with incompatible devices.")
result = self.copy()
return result.__iadd__(other)
def __radd__(self, other):
# The Circuit + Circuit case is handled by __add__
if not isinstance(other, (ops.Operation, Iterable)):
return NotImplemented
# Auto wrap OP_TREE inputs into a circuit.
result = self.copy()
result._moments[:0] = Circuit(other)._moments
result._device.validate_circuit(result)
return result
def __imul__(self, repetitions: int):
if not isinstance(repetitions, int):
return NotImplemented
self._moments *= repetitions
return self
def __mul__(self, repetitions: int):
if not isinstance(repetitions, int):
return NotImplemented
return Circuit(self._moments * repetitions,
device=self._device)
def __rmul__(self, repetitions: int):
if not isinstance(repetitions, int):
return NotImplemented
return self * repetitions
def __pow__(self, exponent: int) -> 'Circuit':
"""A circuit raised to a power, only valid for exponent -1, the inverse.
This will fail if anything other than -1 is passed to the Circuit by
returning NotImplemented. Otherwise this will return the inverse
circuit, which is the circuit with its moment order reversed and for
every moment all the moment's operations are replaced by its inverse.
If any of the operations do not support inverse, NotImplemented will be
returned.
"""
if exponent != -1:
return NotImplemented
inv_moments = []
for moment in self[::-1]:
inv_moment = cirq.inverse(moment, default=NotImplemented)
if inv_moment is NotImplemented:
return NotImplemented
inv_moments.append(inv_moment)
return cirq.Circuit(inv_moments, device=self._device)
def __repr__(self) -> str:
if not self._moments and self._device == devices.UNCONSTRAINED_DEVICE:
return 'cirq.Circuit()'
if not self._moments:
return f'cirq.Circuit(device={self._device!r})'
moment_str = _list_repr_with_indented_item_lines(self._moments)
if self._device == devices.UNCONSTRAINED_DEVICE:
return f'cirq.Circuit({moment_str})'
return f'cirq.Circuit({moment_str}, device={self._device!r})'
def __str__(self) -> str:
return self.to_text_diagram()
__hash__ = None # type: ignore
def with_device(
self,
new_device: 'cirq.Device',
qubit_mapping: Callable[['cirq.Qid'], 'cirq.Qid'] = lambda e: e,
) -> 'Circuit':
"""Maps the current circuit onto a new device, and validates.
Args:
new_device: The new device that the circuit should be on.
qubit_mapping: How to translate qubits from the old device into
qubits on the new device.
Returns:
The translated circuit.
"""
return Circuit([
ops.Moment(
operation.transform_qubits(qubit_mapping)
for operation in moment.operations)
for moment in self._moments
],
device=new_device)
def _repr_pretty_(self, p: Any, cycle: bool) -> None:
"""Print ASCII diagram in Jupyter."""
if cycle:
# There should never be a cycle. This is just in case.
p.text('Circuit(...)')
else:
p.text(self.to_text_diagram())
def _repr_html_(self) -> str:
"""Print ASCII diagram in Jupyter notebook without wrapping lines."""
return ('<pre style="overflow: auto; white-space: pre;">' +
html.escape(self.to_text_diagram()) + '</pre>')
def _first_moment_operating_on(self, qubits: Iterable['cirq.Qid'],
indices: Iterable[int]) -> Optional[int]:
qubits = frozenset(qubits)
for m in indices:
if self._has_op_at(m, qubits):
return m
return None
def next_moment_operating_on(self,
qubits: Iterable['cirq.Qid'],
start_moment_index: int = 0,
max_distance: int = None) -> Optional[int]:
"""Finds the index of the next moment that touches the given qubits.
Args:
qubits: We're looking for operations affecting any of these qubits.
start_moment_index: The starting point of the search.
max_distance: The number of moments (starting from the start index
and moving forward) to check. Defaults to no limit.
Returns:
None if there is no matching moment, otherwise the index of the
earliest matching moment.
Raises:
ValueError: negative max_distance.
"""
max_circuit_distance = len(self._moments) - start_moment_index
if max_distance is None:
max_distance = max_circuit_distance
elif max_distance < 0:
raise ValueError('Negative max_distance: {}'.format(max_distance))
else:
max_distance = min(max_distance, max_circuit_distance)
return self._first_moment_operating_on(
qubits,
range(start_moment_index, start_moment_index + max_distance))
def next_moments_operating_on(self,
qubits: Iterable['cirq.Qid'],
start_moment_index: int = 0
) -> Dict['cirq.Qid', int]:
"""Finds the index of the next moment that touches each qubit.
Args:
qubits: The qubits to find the next moments acting on.
start_moment_index: The starting point of the search.
Returns:
The index of the next moment that touches each qubit. If there
is no such moment, the next moment is specified as the number of
moments in the circuit. Equivalently, can be characterized as one
plus the index of the last moment after start_moment_index
(inclusive) that does *not* act on a given qubit.
"""
next_moments = {}
for q in qubits:
next_moment = self.next_moment_operating_on(
[q], start_moment_index)
next_moments[q] = (len(self._moments) if next_moment is None else
next_moment)
return next_moments
def prev_moment_operating_on(self,
qubits: Sequence['cirq.Qid'],
end_moment_index: Optional[int] = None,
max_distance: Optional[int] = None
) -> Optional[int]:
"""Finds the index of the next moment that touches the given qubits.
Args:
qubits: We're looking for operations affecting any of these qubits.
end_moment_index: The moment index just after the starting point of
the reverse search. Defaults to the length of the list of
moments.
max_distance: The number of moments (starting just before from the
end index and moving backward) to check. Defaults to no limit.
Returns:
None if there is no matching moment, otherwise the index of the
latest matching moment.
Raises:
ValueError: negative max_distance.
"""
if end_moment_index is None:
end_moment_index = len(self._moments)
if max_distance is None:
max_distance = len(self._moments)
elif max_distance < 0:
raise ValueError('Negative max_distance: {}'.format(max_distance))
else:
max_distance = min(end_moment_index, max_distance)
# Don't bother searching indices past the end of the list.
if end_moment_index > len(self._moments):
d = end_moment_index - len(self._moments)
end_moment_index -= d
max_distance -= d
if max_distance <= 0:
return None
return self._first_moment_operating_on(qubits,
(end_moment_index - k - 1
for k in range(max_distance)))
def transform_qubits(self,
func: Callable[['cirq.Qid'], 'cirq.Qid'],
*,
new_device: 'cirq.Device' = None) -> 'cirq.Circuit':
"""Returns the same circuit, but with different qubits.
Note that this method does essentially the same thing as
`cirq.Circuit.with_device`. It is included regardless because there are
also `transform_qubits` methods on `cirq.Operation` and `cirq.Moment`.
Args:
func: The function to use to turn each current qubit into a desired
new qubit.
new_device: The device to use for the new circuit, if different.
If this is not set, the new device defaults to the current
device.
Returns:
The receiving circuit but with qubits transformed by the given
function, and with an updated device (if specified).
"""
return self.with_device(
new_device=self.device if new_device is None else new_device,
qubit_mapping=func)
def _prev_moment_available(self, op: 'cirq.Operation',
end_moment_index: int) -> Optional[int]:
last_available = end_moment_index
k = end_moment_index
while k > 0:
k -= 1
if not self._can_commute_past(k, op):
return last_available
if self._can_add_op_at(k, op):
last_available = k
return last_available
def reachable_frontier_from(
self,
start_frontier: Dict['cirq.Qid', int],
*,
is_blocker: Callable[['cirq.Operation'], bool] = lambda op: False
) -> Dict['cirq.Qid', int]:
"""Determines how far can be reached into a circuit under certain rules.
The location L = (qubit, moment_index) is *reachable* if and only if:
a) There is not a blocking operation covering L.
AND
[
b1) qubit is in start frontier and moment_index =
max(start_frontier[qubit], 0).
OR
b2) There is no operation at L and prev(L) = (qubit,
moment_index-1) is reachable.
OR
b3) There is an (non-blocking) operation P covering L such that
(q', moment_index - 1) is reachable for every q' on which P
acts.
]
An operation in moment moment_index is blocking if
a) `is_blocker` returns a truthy value.
OR
b) The operation acts on a qubit not in start_frontier.
OR
c) The operation acts on a qubit q such that start_frontier[q] >
moment_index.
In other words, the reachable region extends forward through time along
each qubit in start_frontier until it hits a blocking operation. Any
location involving a qubit not in start_frontier is unreachable.
For each qubit q in `start_frontier`, the reachable locations will
correspond to a contiguous range starting at start_frontier[q] and
ending just before some index end_q. The result of this method is a
dictionary, and that dictionary maps each qubit q to its end_q.
Examples:
If start_frontier is {
cirq.LineQubit(0): 6,
cirq.LineQubit(1): 2,
cirq.LineQubit(2): 2,
} then the reachable wire locations in the following circuit are
highlighted with '█' characters:
0 1 2 3 4 5 6 7 8 9 10 11 12 13
0: ───H───@─────────────────█████████████████████─@───H───
│ │
1: ───────@─██H███@██████████████████████─@───H───@───────
│ │
2: ─────────██████@███H██─@───────@───H───@───────────────
│ │
3: ───────────────────────@───H───@───────────────────────
And the computed end_frontier is {
cirq.LineQubit(0): 11,
cirq.LineQubit(1): 9,
cirq.LineQubit(2): 6,
}
Note that the frontier indices (shown above the circuit) are
best thought of (and shown) as happening *between* moment indices.
If we specify a blocker as follows:
is_blocker=lambda: op == cirq.CZ(cirq.LineQubit(1),
cirq.LineQubit(2))
and use this start_frontier:
{
cirq.LineQubit(0): 0,
cirq.LineQubit(1): 0,
cirq.LineQubit(2): 0,
cirq.LineQubit(3): 0,
}
Then this is the reachable area:
0 1 2 3 4 5 6 7 8 9 10 11 12 13
0: ─██H███@██████████████████████████████████████─@───H───
│ │
1: ─██████@███H██─@───────────────────────@───H───@───────
│ │
2: ─█████████████─@───H───@───────@───H───@───────────────
│ │
3: ─█████████████████████─@───H───@───────────────────────
and the computed end_frontier is:
{
cirq.LineQubit(0): 11,
cirq.LineQubit(1): 3,
cirq.LineQubit(2): 3,
cirq.LineQubit(3): 5,
}
Args:
start_frontier: A starting set of reachable locations.
is_blocker: A predicate that determines if operations block
reachability. Any location covered by an operation that causes
`is_blocker` to return True is considered to be an unreachable
location.
Returns:
An end_frontier dictionary, containing an end index for each qubit q
mapped to a start index by the given `start_frontier` dictionary.
To determine if a location (q, i) was reachable, you can use
this expression:
q in start_frontier and start_frontier[q] <= i < end_frontier[q]
where i is the moment index, q is the qubit, and end_frontier is the
result of this method.
"""
active: Set['cirq.Qid'] = set()
end_frontier = {}
queue = BucketPriorityQueue[ops.Operation](drop_duplicate_entries=True)
def enqueue_next(qubit: 'cirq.Qid', moment: int) -> None:
next_moment = self.next_moment_operating_on([qubit], moment)
if next_moment is None:
end_frontier[qubit] = max(len(self), start_frontier[qubit])
if qubit in active:
active.remove(qubit)
else:
next_op = self.operation_at(qubit, next_moment)
assert next_op is not None
queue.enqueue(next_moment, next_op)
for start_qubit, start_moment in start_frontier.items():
enqueue_next(start_qubit, start_moment)
while queue:
cur_moment, cur_op = queue.dequeue()
for q in cur_op.qubits:
if (q in start_frontier and
cur_moment >= start_frontier[q] and
q not in end_frontier):
active.add(q)
continue_past = (
cur_op is not None and
active.issuperset(cur_op.qubits) and
not is_blocker(cur_op)
)
if continue_past:
for q in cur_op.qubits:
enqueue_next(q, cur_moment + 1)
else:
for q in cur_op.qubits:
if q in active:
end_frontier[q] = cur_moment
active.remove(q)
return end_frontier
def findall_operations_between(self,
start_frontier: Dict['cirq.Qid', int],
end_frontier: Dict['cirq.Qid', int],
omit_crossing_operations: bool = False
) -> List[Tuple[int, 'cirq.Operation']]:
"""Finds operations between the two given frontiers.
If a qubit is in `start_frontier` but not `end_frontier`, its end index
defaults to the end of the circuit. If a qubit is in `end_frontier` but
not `start_frontier`, its start index defaults to the start of the
circuit. Operations on qubits not mentioned in either frontier are not
included in the results.
Args:
start_frontier: Just before where to start searching for operations,
for each qubit of interest. Start frontier indices are
inclusive.
end_frontier: Just before where to stop searching for operations,
for each qubit of interest. End frontier indices are exclusive.
omit_crossing_operations: Determines whether or not operations that
cross from a location between the two frontiers to a location
outside the two frontiers are included or excluded. (Operations
completely inside are always included, and operations completely
outside are always excluded.)
Returns:
A list of tuples. Each tuple describes an operation found between
the two frontiers. The first item of each tuple is the index of the
moment containing the operation, and the second item is the
operation itself. The list is sorted so that the moment index
increases monotonically.
"""
result = BucketPriorityQueue[ops.Operation](
drop_duplicate_entries=True)
involved_qubits = set(start_frontier.keys()) | set(end_frontier.keys())
# Note: only sorted to ensure a deterministic result ordering.
for q in sorted(involved_qubits):
for i in range(start_frontier.get(q, 0),
end_frontier.get(q, len(self))):
op = self.operation_at(q, i)
if op is None:
continue
if (omit_crossing_operations and
not involved_qubits.issuperset(op.qubits)):
continue
result.enqueue(i, op)
return list(result)
def findall_operations_until_blocked(
self,
start_frontier: Dict['cirq.Qid', int],
is_blocker: Callable[['cirq.Operation'], bool] = lambda op: False
) -> List[Tuple[int, ops.Operation]]:
"""
Finds all operations until a blocking operation is hit.
An operation is considered blocking if
a) It is in the 'light cone' of start_frontier.
AND
(
1) is_blocker returns a truthy value.
OR
2) It acts on a blocked qubit.
)
Every qubit acted on by a blocking operation is thereafter itself
blocked.
The notion of reachability here differs from that in
reachable_frontier_from in two respects:
1) An operation is not considered blocking only because it is in a
moment before the start_frontier of one of the qubits on which it
acts.
2) Operations that act on qubits not in start_frontier are not
automatically blocking.
For every (moment_index, operation) returned:
1) moment_index >= min((start_frontier[q] for q in operation.qubits
if q in start_frontier), default=0)
2) set(operation.qubits).intersection(start_frontier)
Below are some examples, where on the left the opening parentheses show
`start_frontier` and on the right are the operations included (with
their moment indices) in the output. `F` and `T` indicate that
`is_blocker` return `False` or `True`, respectively, when applied to
the gates; `M` indicates that it doesn't matter.
─(─F───F─────── ┄(─F───F─)┄┄┄┄┄
│ │ │ │
─(─F───F───T─── => ┄(─F───F─)┄┄┄┄┄
│ ┊
───────────T─── ┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄
───M─────(─F─── ┄┄┄┄┄┄┄┄┄(─F─)┄┄
│ │ ┊ │
───M───M─(─F─── ┄┄┄┄┄┄┄┄┄(─F─)┄┄
│ => ┊
───────M───M─── ┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄
│ ┊
───────────M─── ┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄
───M─(─────M─── ┄┄┄┄┄()┄┄┄┄┄┄┄┄
│ │ ┊ ┊
───M─(─T───M─── ┄┄┄┄┄()┄┄┄┄┄┄┄┄
│ => ┊
───────T───M─── ┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄
│ ┊
───────────M─── ┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄
─(─F───F─── ┄(─F───F─)┄
│ │ => │ │
───F─(─F─── ┄(─F───F─)┄
─(─F─────────── ┄(─F─)┄┄┄┄┄┄┄┄┄
│ │
───F───F─────── ┄(─F─)┄┄┄┄┄┄┄┄┄
│ => ┊
───────F───F─── ┄┄┄┄┄┄┄┄┄(─F─)┄
│ │
─(─────────F─── ┄┄┄┄┄┄┄┄┄(─F─)┄
Args:
start_frontier: A starting set of reachable locations.
is_blocker: A predicate that determines if operations block
reachability. Any location covered by an operation that causes
`is_blocker` to return True is considered to be an unreachable
location.
Returns:
A list of tuples. Each tuple describes an operation found between
the start frontier and a blocking operation. The first item of
each tuple is the index of the moment containing the operation,
and the second item is the operation itself.
"""
op_list = [] # type: List[Tuple[int, ops.Operation]]
if not start_frontier:
return op_list
start_index = min(start_frontier.values())
blocked_qubits = set() # type: Set[cirq.Qid]
for index, moment in enumerate(self[start_index:], start_index):
active_qubits = set(
q for q, s in start_frontier.items() if s <= index)
for op in moment.operations:
if is_blocker(op) or blocked_qubits.intersection(op.qubits):
blocked_qubits.update(op.qubits)
elif active_qubits.intersection(op.qubits):
op_list.append((index, op))
if blocked_qubits.issuperset(start_frontier):
break
return op_list
def operation_at(self, qubit: 'cirq.Qid',
moment_index: int) -> Optional['cirq.Operation']:
"""Finds the operation on a qubit within a moment, if any.
Args:
qubit: The qubit to check for an operation on.
moment_index: The index of the moment to check for an operation
within. Allowed to be beyond the end of the circuit.
Returns:
None if there is no operation on the qubit at the given moment, or
else the operation.
"""
if not 0 <= moment_index < len(self._moments):
return None
for op in self._moments[moment_index].operations:
if qubit in op.qubits:
return op
return None
def findall_operations(self, predicate: Callable[['cirq.Operation'], bool]
) -> Iterable[Tuple[int, 'cirq.Operation']]:
"""Find the locations of all operations that satisfy a given condition.
This returns an iterator of (index, operation) tuples where each
operation satisfies op_cond(operation) is truthy. The indices are
in order of the moments and then order of the ops within that moment.
Args:
predicate: A method that takes an Operation and returns a Truthy
value indicating the operation meets the find condition.
Returns:
An iterator (index, operation)'s that satisfy the op_condition.
"""
for index, moment in enumerate(self._moments):
for op in moment.operations:
if predicate(op):
yield index, op
def findall_operations_with_gate_type(
self,
gate_type: Type[T_DESIRED_GATE_TYPE]
) -> Iterable[Tuple[int,
ops.GateOperation,
T_DESIRED_GATE_TYPE]]:
"""Find the locations of all gate operations of a given type.
Args:
gate_type: The type of gate to find, e.g. XPowGate or
MeasurementGate.
Returns:
An iterator (index, operation, gate)'s for operations with the given
gate type.
"""
result = self.findall_operations(lambda operation: isinstance(
operation.gate, gate_type))
for index, op in result:
gate_op = cast(ops.GateOperation, op)
yield index, gate_op, cast(T_DESIRED_GATE_TYPE, gate_op.gate)
def has_measurements(self):
return any(self.findall_operations(protocols.is_measurement))
def are_all_measurements_terminal(self):
"""Whether all measurement gates are at the end of the circuit."""
return self.are_all_matches_terminal(protocols.is_measurement)
def are_all_matches_terminal(self,
predicate: Callable[['cirq.Operation'], bool]):
"""Check whether all of the ops that satisfy a predicate are terminal.
Args:
predicate: A predicate on ops.Operations which is being checked.
Returns:
Whether or not all `Operation` s in a circuit that satisfy the
given predicate are terminal.
"""
return all(
self.next_moment_operating_on(op.qubits, i + 1) is None for
(i, op) in self.findall_operations(predicate)
)
def _pick_or_create_inserted_op_moment_index(self, splitter_index: int,
op: 'cirq.Operation',
strategy: 'cirq.InsertStrategy'
) -> int:
"""Determines and prepares where an insertion will occur.
Args:
splitter_index: The index to insert at.
op: The operation that will be inserted.
strategy: The insertion strategy.
Returns:
The index of the (possibly new) moment where the insertion should
occur.
Raises:
ValueError: Unrecognized append strategy.
"""
if (strategy is InsertStrategy.NEW or
strategy is InsertStrategy.NEW_THEN_INLINE):
self._moments.insert(splitter_index, ops.Moment())
return splitter_index
if strategy is InsertStrategy.INLINE:
if (0 <= splitter_index - 1 < len(self._moments) and
self._can_add_op_at(splitter_index - 1, op)):
return splitter_index - 1
return self._pick_or_create_inserted_op_moment_index(
splitter_index, op, InsertStrategy.NEW)
if strategy is InsertStrategy.EARLIEST:
if self._can_add_op_at(splitter_index, op):
p = self._prev_moment_available(op, splitter_index)
return p or 0
return self._pick_or_create_inserted_op_moment_index(
splitter_index, op, InsertStrategy.INLINE)
raise ValueError('Unrecognized append strategy: {}'.format(strategy))
def _has_op_at(self, moment_index: int,
qubits: Iterable['cirq.Qid']) -> bool:
return (0 <= moment_index < len(self._moments) and
self._moments[moment_index].operates_on(qubits))
def _can_add_op_at(self, moment_index: int,
operation: 'cirq.Operation') -> bool:
if not 0 <= moment_index < len(self._moments):
return True
return self._device.can_add_operation_into_moment(
operation,
self._moments[moment_index])
def _can_commute_past(self, moment_index: int,
operation: 'cirq.Operation') -> bool:
return not self._moments[moment_index].operates_on(operation.qubits)
def _validate_op_tree_qids(self, op_tree: 'cirq.OP_TREE') -> None:
"""Raises an exception if any operation in `op_tree` has qids that don't
match its qid shape.
Args:
operation: The operation to validate.
Raises:
ValueError: The operation had qids that don't match its qid shape.
"""
# Cast from Iterable[Operation, Moment] because preserve_moments is
# False.
for op in cast(Iterable['cirq.Operation'],
ops.flatten_op_tree(op_tree)):
if protocols.qid_shape(op) != protocols.qid_shape(op.qubits):
raise ValueError(
'Invalid operation. '
'An operation has qid shape <{!r}> but is on qids with '
'shape <{!r}>. The operation is <{!r}>.'.format(
protocols.qid_shape(op), protocols.qid_shape(op.qubits),
op))
def insert(
self,
index: int,
moment_or_operation_tree: Union['cirq.Operation', 'cirq.OP_TREE'],
strategy: 'cirq.InsertStrategy' = InsertStrategy.EARLIEST) -> int:
""" Inserts operations into the circuit.
Operations are inserted into the moment specified by the index and
'InsertStrategy'.
Moments within the operation tree are inserted intact.
Args:
index: The index to insert all of the operations at.
moment_or_operation_tree: The moment or operation tree to insert.
strategy: How to pick/create the moment to put operations into.
Returns:
The insertion index that will place operations just after the
operations that were inserted by this method.
Raises:
ValueError: Bad insertion strategy.
"""
moments_and_operations = list(
ops.flatten_to_ops_or_moments(
ops.transform_op_tree(moment_or_operation_tree,
self._device.decompose_operation,
preserve_moments=True),))
for moment_or_op in moments_and_operations:
if isinstance(moment_or_op, ops.Moment):
self._device.validate_moment(cast(ops.Moment, moment_or_op))
else:
self._device.validate_operation(
cast(ops.Operation, moment_or_op))
self._validate_op_tree_qids(moment_or_op)
# limit index to 0..len(self._moments), also deal with indices smaller 0
k = max(min(index if index >= 0 else len(self._moments) + index,
len(self._moments)), 0)
for moment_or_op in moments_and_operations:
if isinstance(moment_or_op, ops.Moment):
self._moments.insert(k, moment_or_op)
k += 1
else:
op = cast(ops.Operation, moment_or_op)
p = self._pick_or_create_inserted_op_moment_index(
k, op, strategy)
while p >= len(self._moments):
self._moments.append(ops.Moment())
self._moments[p] = self._moments[p].with_operation(op)
self._device.validate_moment(self._moments[p])
k = max(k, p + 1)
if strategy is InsertStrategy.NEW_THEN_INLINE:
strategy = InsertStrategy.INLINE
return k
def insert_into_range(self, operations: 'cirq.OP_TREE', start: int,
end: int) -> int:
"""Writes operations inline into an area of the circuit.
Args:
start: The start of the range (inclusive) to write the
given operations into.
end: The end of the range (exclusive) to write the given
operations into. If there are still operations remaining,
new moments are created to fit them.
operations: An operation or tree of operations to insert.
Returns:
An insertion index that will place operations after the operations
that were inserted by this method.
Raises:
IndexError: Bad inline_start and/or inline_end.
"""
if not 0 <= start <= end <= len(self):
raise IndexError('Bad insert indices: [{}, {})'.format(
start, end))
flat_ops = list(ops.flatten_to_ops(operations))
for op in flat_ops:
self._device.validate_operation(op)
self._validate_op_tree_qids(flat_ops)
i = start
op_index = 0
while op_index < len(flat_ops):
op = flat_ops[op_index]
while i < end and not self._device.can_add_operation_into_moment(
op, self._moments[i]):
i += 1
if i >= end:
break
self._moments[i] = self._moments[i].with_operation(op)
op_index += 1
if op_index >= len(flat_ops):
return end
return self.insert(end, flat_ops[op_index:])
@staticmethod
def _pick_inserted_ops_moment_indices(
operations: Sequence['cirq.Operation'],
start: int = 0,
frontier: Dict['cirq.Qid', int] = None
) -> Tuple[Sequence[int], Dict['cirq.Qid', int]]:
"""Greedily assigns operations to moments.
Args:
operations: The operations to assign to moments.
start: The first moment to consider assignment to.
frontier: The first moment to which an operation acting on a qubit
can be assigned. Updated in place as operations are assigned.
Returns:
The frontier giving the index of the moment after the last one to
which an operation that acts on each qubit is assigned. If a
frontier was specified as an argument, this is the same object.
"""
if frontier is None:
frontier = defaultdict(lambda: 0)
moment_indices = []
for op in operations:
op_start = max(start, max(frontier[q] for q in op.qubits))
moment_indices.append(op_start)
for q in op.qubits:
frontier[q] = max(frontier[q], op_start + 1)
return moment_indices, frontier
def _push_frontier(self,
early_frontier: Dict['cirq.Qid', int],
late_frontier: Dict['cirq.Qid', int],
update_qubits: Iterable['cirq.Qid'] = None
) -> Tuple[int, int]:
"""Inserts moments to separate two frontiers.
After insertion n_new moments, the following holds:
for q in late_frontier:
early_frontier[q] <= late_frontier[q] + n_new
for q in update_qubits:
early_frontier[q] the identifies the same moment as before
(but whose index may have changed if this moment is after
those inserted).
Args:
early_frontier: The earlier frontier. For qubits not in the later
frontier, this is updated to account for the newly inserted
moments.
late_frontier: The later frontier. This is not modified.
update_qubits: The qubits for which to update early_frontier to
account for the newly inserted moments.
Returns:
(index at which new moments were inserted, how many new moments
were inserted) if new moments were indeed inserted. (0, 0)
otherwise.
"""
if update_qubits is None:
update_qubits = set(early_frontier).difference(late_frontier)
n_new_moments = (max(early_frontier.get(q, 0) - late_frontier[q]
for q in late_frontier)
if late_frontier else 0)
if n_new_moments > 0:
insert_index = min(late_frontier.values())
self._moments[insert_index:insert_index] = (
[ops.Moment()] * n_new_moments)
for q in update_qubits:
if early_frontier.get(q, 0) > insert_index:
early_frontier[q] += n_new_moments
return insert_index, n_new_moments
return (0, 0)
def _insert_operations(self, operations: Sequence['cirq.Operation'],
insertion_indices: Sequence[int]) -> None:
"""Inserts operations at the specified moments. Appends new moments if
necessary.
Args:
operations: The operations to insert.
insertion_indices: Where to insert them, i.e. operations[i] is
inserted into moments[insertion_indices[i].
Raises:
ValueError: operations and insert_indices have different lengths.
NB: It's on the caller to ensure that the operations won't conflict
with operations already in the moment or even each other.
"""
if len(operations) != len(insertion_indices):
raise ValueError('operations and insertion_indices must have the'
'same length.')
self._moments += [
ops.Moment() for _ in range(1 + max(insertion_indices) - len(self))
]
moment_to_ops = defaultdict(
list) # type: Dict[int, List['cirq.Operation']]
for op_index, moment_index in enumerate(insertion_indices):
moment_to_ops[moment_index].append(operations[op_index])
for moment_index, new_ops in moment_to_ops.items():
self._moments[moment_index] = ops.Moment(
self._moments[moment_index].operations + tuple(new_ops))
def zip(*circuits):
"""Combines operations from circuits in a moment-by-moment fashion.
Moment k of the resulting circuit will have all operations from moment
k of each of the given circuits.
When the given circuits have different lengths, the shorter circuits are
implicitly padded with empty moments. This differs from the behavior of
python's built-in zip function, which would instead truncate the longer
circuits.
The zipped circuits can't have overlapping operations occurring at the
same moment index.
Args:
circuits: The circuits to merge together.
Returns:
The merged circuit.
Raises:
ValueError:
The zipped circuits have overlapping operations occurring at the
same moment index.
Examples:
>>> import cirq
>>> a, b, c, d = cirq.LineQubit.range(4)
>>> circuit1 = cirq.Circuit(cirq.H(a), cirq.CNOT(a, b))
>>> circuit2 = cirq.Circuit(cirq.X(c), cirq.Y(c), cirq.Z(c))
>>> circuit3 = cirq.Circuit(cirq.Moment(), cirq.Moment(cirq.S(d)))
>>> print(circuit1.zip(circuit2))
0: ───H───@───────
│
1: ───────X───────
<BLANKLINE>
2: ───X───Y───Z───
>>> print(circuit1.zip(circuit2, circuit3))
0: ───H───@───────
│
1: ───────X───────
<BLANKLINE>
2: ───X───Y───Z───
<BLANKLINE>
3: ───────S───────
>>> print(cirq.Circuit.zip(circuit3, circuit2, circuit1))
0: ───H───@───────
│
1: ───────X───────
<BLANKLINE>
2: ───X───Y───Z───
<BLANKLINE>
3: ───────S───────
"""
circuits = list(circuits)
n = max([len(c) for c in circuits], default=0)
result = cirq.Circuit()
for k in range(n):
try:
result.append(cirq.Moment(c[k] for c in circuits if k < len(c)))
except ValueError as ex:
raise ValueError(
f"Overlapping operations between zipped circuits "
f"at moment index {k}.\n{ex}") from ex
return result
def insert_at_frontier(self,
operations: 'cirq.OP_TREE',
start: int,
frontier: Dict['cirq.Qid', int] = None
) -> Dict['cirq.Qid', int]:
"""Inserts operations inline at frontier.
Args:
operations: the operations to insert
start: the moment at which to start inserting the operations
frontier: frontier[q] is the earliest moment in which an operation
acting on qubit q can be placed.
"""
if frontier is None:
frontier = defaultdict(lambda: 0)
flat_ops = tuple(ops.flatten_to_ops(operations))
if not flat_ops:
return frontier
qubits = set(q for op in flat_ops for q in op.qubits)
if any(frontier[q] > start for q in qubits):
raise ValueError('The frontier for qubits on which the operations'
'to insert act cannot be after start.')
next_moments = self.next_moments_operating_on(qubits, start)
insertion_indices, _ = self._pick_inserted_ops_moment_indices(
flat_ops, start, frontier)
self._push_frontier(frontier, next_moments)
self._insert_operations(flat_ops, insertion_indices)
return frontier
def batch_remove(self,
removals: Iterable[Tuple[int, 'cirq.Operation']]) -> None:
"""Removes several operations from a circuit.
Args:
removals: A sequence of (moment_index, operation) tuples indicating
operations to delete from the moments that are present. All
listed operations must actually be present or the edit will
fail (without making any changes to the circuit).
ValueError:
One of the operations to delete wasn't present to start with.
IndexError:
Deleted from a moment that doesn't exist.
"""
copy = self.copy()
for i, op in removals:
if op not in copy._moments[i].operations:
raise ValueError(
"Can't remove {} @ {} because it doesn't exist.".format(
op, i))
copy._moments[i] = ops.Moment(
old_op
for old_op in copy._moments[i].operations
if op != old_op)
self._device.validate_circuit(copy)
self._moments = copy._moments
def batch_replace(self, replacements: Iterable[
Tuple[int, 'cirq.Operation', 'cirq.Operation']]) -> None:
"""Replaces several operations in a circuit with new operations.
Args:
replacements: A sequence of (moment_index, old_op, new_op) tuples
indicating operations to be replaced in this circuit. All "old"
operations must actually be present or the edit will fail
(without making any changes to the circuit).
ValueError:
One of the operations to replace wasn't present to start with.
IndexError:
Replaced in a moment that doesn't exist.
"""
copy = self.copy()
for i, op, new_op in replacements:
if op not in copy._moments[i].operations:
raise ValueError(
f"Can't replace {op} @ {i} because it doesn't exist.")
copy._moments[i] = ops.Moment(
old_op if old_op != op else new_op
for old_op in copy._moments[i].operations)
self._device.validate_circuit(copy)
self._moments = copy._moments
def batch_insert_into(self,
insert_intos: Iterable[Tuple[int, 'cirq.OP_TREE']]
) -> None:
"""Inserts operations into empty spaces in existing moments.
If any of the insertions fails (due to colliding with an existing
operation), this method fails without making any changes to the circuit.
Args:
insert_intos: A sequence of (moment_index, new_op_tree)
pairs indicating a moment to add new operations into.
ValueError:
One of the insertions collided with an existing operation.
IndexError:
Inserted into a moment index that doesn't exist.
"""
copy = self.copy()
for i, insertions in insert_intos:
copy._moments[i] = copy._moments[i].with_operations(insertions)
self._device.validate_circuit(copy)
self._validate_op_tree_qids(copy)
self._moments = copy._moments
def batch_insert(self,
insertions: Iterable[Tuple[int, 'cirq.OP_TREE']]) -> None:
"""Applies a batched insert operation to the circuit.
Transparently handles the fact that earlier insertions may shift
the index that later insertions should occur at. For example, if you
insert an operation at index 2 and at index 4, but the insert at index 2
causes a new moment to be created, then the insert at "4" will actually
occur at index 5 to account for the shift from the new moment.
All insertions are done with the strategy 'EARLIEST'.
When multiple inserts occur at the same index, the gates from the later
inserts end up before the gates from the earlier inserts (exactly as if
you'd called list.insert several times with the same index: the later
inserts shift the earliest inserts forward).
Args:
insertions: A sequence of (insert_index, operations) pairs
indicating operations to add into the circuit at specific
places.
"""
# Work on a copy in case validation fails halfway through.
copy = self.copy()
shift = 0
# Note: python `sorted` is guaranteed to be stable. This matters.
insertions = sorted(insertions, key=lambda e: e[0])
groups = _group_until_different(insertions,
key=lambda e: e[0],
value=lambda e: e[1])
for i, group in groups:
insert_index = i + shift
next_index = copy.insert(insert_index,
reversed(group),
InsertStrategy.EARLIEST)
if next_index > insert_index:
shift += next_index - insert_index
self._moments = copy._moments
def append(self,
moment_or_operation_tree: Union['cirq.Moment', 'cirq.OP_TREE'],
strategy: 'cirq.InsertStrategy' = InsertStrategy.EARLIEST):
"""Appends operations onto the end of the circuit.
Moments within the operation tree are appended intact.
Args:
moment_or_operation_tree: The moment or operation tree to append.
strategy: How to pick/create the moment to put operations into.
"""
self.insert(len(self._moments), moment_or_operation_tree, strategy)
def clear_operations_touching(self, qubits: Iterable['cirq.Qid'],
moment_indices: Iterable[int]):
"""Clears operations that are touching given qubits at given moments.
Args:
qubits: The qubits to check for operations on.
moment_indices: The indices of moments to check for operations
within.
"""
qubits = frozenset(qubits)
for k in moment_indices:
if 0 <= k < len(self._moments):
self._moments[k] = self._moments[k].without_operations_touching(
qubits)
def all_qubits(self) -> FrozenSet['cirq.Qid']:
"""Returns the qubits acted upon by Operations in this circuit."""
return frozenset(q for m in self._moments for q in m.qubits)
def all_operations(self) -> Iterator[ops.Operation]:
"""Iterates over the operations applied by this circuit.
Operations from earlier moments will be iterated over first. Operations
within a moment are iterated in the order they were given to the
moment's constructor.
"""
return (op for moment in self for op in moment.operations)
def qid_shape(self,
qubit_order: 'cirq.QubitOrderOrList' = ops.QubitOrder.DEFAULT
) -> Tuple[int, ...]:
qids = ops.QubitOrder.as_qubit_order(qubit_order).order_for(
self.all_qubits())
return protocols.qid_shape(qids)
def all_measurement_keys(self) -> Tuple[str, ...]:
return protocols.measurement_keys(self)
def _qid_shape_(self) -> Tuple[int, ...]:
return self.qid_shape()
def _has_unitary_(self) -> bool:
if not self.are_all_measurements_terminal():
return False
unitary_ops = protocols.decompose(
self.all_operations(),
keep=protocols.has_unitary,
intercepting_decomposer=_decompose_measurement_inversions,
on_stuck_raise=None)
return all(protocols.has_unitary(e) for e in unitary_ops)
def _unitary_(self) -> Union[np.ndarray, NotImplementedType]:
"""Converts the circuit into a unitary matrix, if possible.
If the circuit contains any non-terminal measurements, the conversion
into a unitary matrix fails (i.e. returns NotImplemented). Terminal
measurements are ignored when computing the unitary matrix. The unitary
matrix is the product of the unitary matrix of all operations in the
circuit (after expanding them to apply to the whole system).
"""
if not self._has_unitary_():
return NotImplemented
return self.unitary(ignore_terminal_measurements=True)
def unitary(self,
qubit_order: 'cirq.QubitOrderOrList' = ops.QubitOrder.DEFAULT,
qubits_that_should_be_present: Iterable['cirq.Qid'] = (),
ignore_terminal_measurements: bool = True,
dtype: Type[np.number] = np.complex128) -> np.ndarray:
"""Converts the circuit into a unitary matrix, if possible.
Returns the same result as `cirq.unitary`, but provides more options.
Args:
qubit_order: Determines how qubits are ordered when passing matrices
into np.kron.
qubits_that_should_be_present: Qubits that may or may not appear
in operations within the circuit, but that should be included
regardless when generating the matrix.
ignore_terminal_measurements: When set, measurements at the end of
the circuit are ignored instead of causing the method to
fail.
dtype: The numpy dtype for the returned unitary. Defaults to
np.complex128. Specifying np.complex64 will run faster at the
cost of precision. `dtype` must be a complex np.dtype, unless
all operations in the circuit have unitary matrices with
exclusively real coefficients (e.g. an H + TOFFOLI circuit).
Returns:
A (possibly gigantic) 2d numpy array corresponding to a matrix
equivalent to the circuit's effect on a quantum state.
Raises:
ValueError: The circuit contains measurement gates that are not
ignored.
TypeError: The circuit contains gates that don't have a known
unitary matrix, e.g. gates parameterized by a Symbol.
"""
if not ignore_terminal_measurements and any(
protocols.is_measurement(op)
for op in self.all_operations()):
raise ValueError('Circuit contains a measurement.')
if not self.are_all_measurements_terminal():
raise ValueError('Circuit contains a non-terminal measurement.')
qs = ops.QubitOrder.as_qubit_order(qubit_order).order_for(
self.all_qubits().union(qubits_that_should_be_present))
# Force qubits to have dimension at least 2 for backwards compatibility.
qid_shape = self.qid_shape(qubit_order=qs)
side_len = np.product(qid_shape, dtype=int)
state = qis.eye_tensor(qid_shape, dtype=dtype)
result = _apply_unitary_circuit(self, state, qs, dtype)
return result.reshape((side_len, side_len))
def final_state_vector(
self,
initial_state: 'cirq.STATE_VECTOR_LIKE' = 0,
qubit_order: 'cirq.QubitOrderOrList' = ops.QubitOrder.DEFAULT,
qubits_that_should_be_present: Iterable['cirq.Qid'] = (),
ignore_terminal_measurements: bool = True,
dtype: Type[np.number] = np.complex128) -> np.ndarray:
"""Left-multiplies a state vector by the circuit's unitary effect.
A circuit's "unitary effect" is the unitary matrix produced by
multiplying together all of its gates' unitary matrices. A circuit
with non-unitary gates (such as measurement or parameterized gates) does
not have a well-defined unitary effect, and the method will fail if such
operations are present.
For convenience, terminal measurements are automatically ignored
instead of causing a failure. Set the `ignore_terminal_measurements`
argument to False to disable this behavior.
This method is equivalent to left-multiplying the input state by
`cirq.unitary(circuit)` but it's computed in a more efficient
way.
Args:
initial_state: The input state for the circuit. This can be a list
of qudit values, a big endian int encoding the qudit values,
a vector of amplitudes, or a tensor of amplitudes.
When this is an int, it refers to a computational
basis state (e.g. 5 means initialize to ``|5⟩ = |...000101⟩``).
If this is a vector of amplitudes (a flat numpy array of the
correct length for the system) or a tensor of amplitudes (a
numpy array whose shape equals this circuit's `qid_shape`), it
directly specifies the initial state's amplitudes. The vector
type must be convertible to the given `dtype` argument.
qubit_order: Determines how qubits are ordered when passing matrices
into np.kron.
qubits_that_should_be_present: Qubits that may or may not appear
in operations within the circuit, but that should be included
regardless when generating the matrix.
ignore_terminal_measurements: When set, measurements at the end of
the circuit are ignored instead of causing the method to
fail.
dtype: The numpy dtype for the returned unitary. Defaults to
np.complex128. Specifying np.complex64 will run faster at the
cost of precision. `dtype` must be a complex np.dtype, unless
all operations in the circuit have unitary matrices with
exclusively real coefficients (e.g. an H + TOFFOLI circuit).
Returns:
A (possibly gigantic) numpy array storing the superposition that
came out of the circuit for the given input state.
Raises:
ValueError: The circuit contains measurement gates that are not
ignored.
TypeError: The circuit contains gates that don't have a known
unitary matrix, e.g. gates parameterized by a Symbol.
"""
if not ignore_terminal_measurements and any(
protocols.is_measurement(op) for op in self.all_operations()):
raise ValueError('Circuit contains a measurement.')
if not self.are_all_measurements_terminal():
raise ValueError('Circuit contains a non-terminal measurement.')
qs = ops.QubitOrder.as_qubit_order(qubit_order).order_for(
self.all_qubits().union(qubits_that_should_be_present))
# Force qubits to have dimension at least 2 for backwards compatibility.
qid_shape = self.qid_shape(qubit_order=qs)
state_len = np.product(qid_shape, dtype=int)
state = qis.to_valid_state_vector(initial_state,
qid_shape=qid_shape,
dtype=dtype).reshape(qid_shape)
result = _apply_unitary_circuit(self, state, qs, dtype)
return result.reshape((state_len,))
@deprecated(deadline='v0.10.0', fix='Use final_state_vector instead.')
def final_wavefunction(
self,
initial_state: 'cirq.STATE_VECTOR_LIKE' = 0,
qubit_order: 'cirq.QubitOrderOrList' = ops.QubitOrder.DEFAULT,
qubits_that_should_be_present: Iterable['cirq.Qid'] = (),
ignore_terminal_measurements: bool = True,
dtype: Type[np.number] = np.complex128) -> np.ndarray:
"""Deprecated. Please use `final_state_vector`."""
return self.final_state_vector(
initial_state=initial_state,
qubit_order=qubit_order,
qubits_that_should_be_present=qubits_that_should_be_present,
ignore_terminal_measurements=ignore_terminal_measurements,
dtype=dtype)
def to_text_diagram(
self,
*,
use_unicode_characters: bool = True,
transpose: bool = False,
include_tags: bool = True,
precision: Optional[int] = 3,
qubit_order: 'cirq.QubitOrderOrList' = ops.QubitOrder.DEFAULT
) -> str:
"""Returns text containing a diagram describing the circuit.
Args:
use_unicode_characters: Determines if unicode characters are
allowed (as opposed to ascii-only diagrams).
transpose: Arranges qubit wires vertically instead of horizontally.
include_tags: Whether tags on TaggedOperations should be printed
precision: Number of digits to display in text diagram
qubit_order: Determines how qubits are ordered in the diagram.
Returns:
The text diagram.
"""
diagram = self.to_text_diagram_drawer(
use_unicode_characters=use_unicode_characters,
include_tags=include_tags,
precision=precision,
qubit_order=qubit_order,
transpose=transpose)
return diagram.render(
crossing_char=(None
if use_unicode_characters
else ('-' if transpose else '|')),
horizontal_spacing=1 if transpose else 3,
use_unicode_characters=use_unicode_characters)
def to_text_diagram_drawer(
self,
*,
use_unicode_characters: bool = True,
qubit_namer: Optional[Callable[['cirq.Qid'], str]] = None,
transpose: bool = False,
include_tags: bool = True,
draw_moment_groups: bool = True,
precision: Optional[int] = 3,
qubit_order: 'cirq.QubitOrderOrList' = ops.QubitOrder.DEFAULT,
get_circuit_diagram_info: Optional[
Callable[['cirq.Operation', 'cirq.CircuitDiagramInfoArgs'],
'cirq.CircuitDiagramInfo']] = None
) -> TextDiagramDrawer:
"""Returns a TextDiagramDrawer with the circuit drawn into it.
Args:
use_unicode_characters: Determines if unicode characters are
allowed (as opposed to ascii-only diagrams).
qubit_namer: Names qubits in diagram. Defaults to str.
transpose: Arranges qubit wires vertically instead of horizontally.
draw_moment_groups: Whether to draw moment symbol or not
precision: Number of digits to use when representing numbers.
qubit_order: Determines how qubits are ordered in the diagram.
get_circuit_diagram_info: Gets circuit diagram info. Defaults to
protocol with fallback.
Returns:
The TextDiagramDrawer instance.
"""
qubits = ops.QubitOrder.as_qubit_order(qubit_order).order_for(
self.all_qubits())
qubit_map = {qubits[i]: i for i in range(len(qubits))}
if qubit_namer is None:
qubit_namer = lambda q: str(q) + ('' if transpose else ': ')
diagram = TextDiagramDrawer()
diagram.write(0, 0, '')
for q, i in qubit_map.items():
diagram.write(0, i, qubit_namer(q))
if any(
isinstance(op.untagged, cirq.GlobalPhaseOperation)
for op in self.all_operations()):
diagram.write(0,
max(qubit_map.values(), default=0) + 1,
'global phase:')
moment_groups = [] # type: List[Tuple[int, int]]
for moment in self._moments:
_draw_moment_in_diagram(moment, use_unicode_characters, qubit_map,
diagram, precision, moment_groups,
get_circuit_diagram_info, include_tags)
w = diagram.width()
for i in qubit_map.values():
diagram.horizontal_line(i, 0, w)
if moment_groups and draw_moment_groups:
_draw_moment_groups_in_diagram(moment_groups,
use_unicode_characters,
diagram)
if transpose:
diagram = diagram.transpose()
return diagram
def _is_parameterized_(self) -> bool:
return any(protocols.is_parameterized(op)
for op in self.all_operations())
def _parameter_names_(self) -> AbstractSet[str]:
return {
name for op in self.all_operations()
for name in protocols.parameter_names(op)
}
def _resolve_parameters_(self,
param_resolver: 'cirq.ParamResolver') -> 'Circuit':
resolved_moments = []
for moment in self:
resolved_operations = _resolve_operations(
moment.operations,
param_resolver)
new_moment = ops.Moment(resolved_operations)
resolved_moments.append(new_moment)
resolved_circuit = Circuit(resolved_moments, device=self.device)
return resolved_circuit
def _qasm_(self) -> str:
return self.to_qasm()
def _to_qasm_output(
self,
header: Optional[str] = None,
precision: int = 10,
qubit_order: 'cirq.QubitOrderOrList' = ops.QubitOrder.DEFAULT,
) -> QasmOutput:
"""Returns a QASM object equivalent to the circuit.
Args:
header: A multi-line string that is placed in a comment at the top
of the QASM. Defaults to a cirq version specifier.
precision: Number of digits to use when representing numbers.
qubit_order: Determines how qubits are ordered in the QASM
register.
"""
if header is None:
header = 'Generated from Cirq v{}'.format(
cirq._version.__version__)
qubits = ops.QubitOrder.as_qubit_order(qubit_order).order_for(
self.all_qubits())
return QasmOutput(operations=self.all_operations(),
qubits=qubits,
header=header,
precision=precision,
version='2.0')
def _to_quil_output(
self, qubit_order: 'cirq.QubitOrderOrList' = ops.QubitOrder.DEFAULT
) -> QuilOutput:
qubits = ops.QubitOrder.as_qubit_order(qubit_order).order_for(
self.all_qubits())
return QuilOutput(operations=self.all_operations(), qubits=qubits)
def to_qasm(
self,
header: Optional[str] = None,
precision: int = 10,
qubit_order: 'cirq.QubitOrderOrList' = ops.QubitOrder.DEFAULT,
) -> str:
"""Returns QASM equivalent to the circuit.
Args:
header: A multi-line string that is placed in a comment at the top
of the QASM. Defaults to a cirq version specifier.
precision: Number of digits to use when representing numbers.
qubit_order: Determines how qubits are ordered in the QASM
register.
"""
return str(self._to_qasm_output(header, precision, qubit_order))
def to_quil(self,
qubit_order: 'cirq.QubitOrderOrList' = ops.QubitOrder.DEFAULT
) -> str:
return str(self._to_quil_output(qubit_order))
def save_qasm(
self,
file_path: Union[str, bytes, int],
header: Optional[str] = None,
precision: int = 10,
qubit_order: 'cirq.QubitOrderOrList' = ops.QubitOrder.DEFAULT,
) -> None:
"""Save a QASM file equivalent to the circuit.
Args:
file_path: The location of the file where the qasm will be written.
header: A multi-line string that is placed in a comment at the top
of the QASM. Defaults to a cirq version specifier.
precision: Number of digits to use when representing numbers.
qubit_order: Determines how qubits are ordered in the QASM
register.
"""
self._to_qasm_output(header, precision, qubit_order).save(file_path)
@property
def moments(self):
return self._moments
def _json_dict_(self):
return protocols.obj_to_dict_helper(self, ['moments', 'device'])
@classmethod
def _from_json_dict_(cls, moments, device, **kwargs):
return cls(moments, device=device)
def with_noise(self, noise: 'cirq.NOISE_MODEL_LIKE') -> 'cirq.Circuit':
"""Make a noisy version of the circuit.
Args:
noise: The noise model to use. This describes the kind of noise to
add to the circuit.
Returns:
A new circuit with the same moment structure but with new moments
inserted where needed when more than one noisy operation is
generated for an input operation. Emptied moments are removed.
"""
noise_model = devices.NoiseModel.from_noise_model_like(noise)
qubits = sorted(self.all_qubits())
c_noisy = Circuit()
for op_tree in noise_model.noisy_moments(self, qubits):
# Keep moments aligned
c_noisy += Circuit(op_tree)
return c_noisy
def _resolve_operations(operations: Iterable['cirq.Operation'],
param_resolver: 'cirq.ParamResolver'
) -> List['cirq.Operation']:
resolved_operations = [] # type: List['cirq.Operation']
for op in operations:
resolved_operations.append(protocols.resolve_parameters(
op, param_resolver))
return resolved_operations
def _get_operation_circuit_diagram_info_with_fallback(
op: 'cirq.Operation',
args: 'cirq.CircuitDiagramInfoArgs') -> 'cirq.CircuitDiagramInfo':
info = protocols.circuit_diagram_info(op, args, None)
if info is not None:
if len(op.qubits) != len(info.wire_symbols):
raise ValueError(
'Wanted diagram info from {!r} for {} '
'qubits but got {!r}'.format(
op,
len(op.qubits),
info))
return info
# Use the untagged operation's __str__.
name = str(op.untagged)
# Representation usually looks like 'gate(qubit1, qubit2, etc)'.
# Try to cut off the qubit part, since that would be redundant information.
redundant_tail = '({})'.format(', '.join(str(e) for e in op.qubits))
if name.endswith(redundant_tail):
name = name[:-len(redundant_tail)]
# Add tags onto the representation, if they exist
if op.tags:
name += f'{list(op.tags)}'
# Include ordering in the qubit labels.
symbols = (name,) + tuple('#{}'.format(i + 1)
for i in range(1, len(op.qubits)))
return protocols.CircuitDiagramInfo(wire_symbols=symbols)
def _is_exposed_formula(text: str) -> bool:
return re.match('[a-zA-Z_][a-zA-Z0-9_]*$', text) is None
def _formatted_exponent(info: 'cirq.CircuitDiagramInfo',
args: 'cirq.CircuitDiagramInfoArgs') -> Optional[str]:
if protocols.is_parameterized(info.exponent):
name = str(info.exponent)
return ('({})'.format(name)
if _is_exposed_formula(name)
else name)
if info.exponent == 0:
return '0'
# 1 is not shown.
if info.exponent == 1:
return None
# Round -1.0 into -1.
if info.exponent == -1:
return '-1'
# If it's a float, show the desired precision.
if isinstance(info.exponent, float):
if args.precision is not None:
# funky behavior of fraction, cast to str in constructor helps.
approx_frac = Fraction(info.exponent).limit_denominator(16)
if approx_frac.denominator not in [2, 4, 5, 10]:
if abs(float(approx_frac)
- info.exponent) < 10**-args.precision:
return '({})'.format(approx_frac)
return args.format_real(info.exponent)
return repr(info.exponent)
# If the exponent is any other object, use its string representation.
s = str(info.exponent)
if info.auto_exponent_parens and ('+' in s or ' ' in s or '-' in s[1:]):
# The string has confusing characters. Put parens around it.
return '({})'.format(info.exponent)
return s
def _draw_moment_in_diagram(
moment: 'cirq.Moment',
use_unicode_characters: bool,
qubit_map: Dict['cirq.Qid', int],
out_diagram: TextDiagramDrawer,
precision: Optional[int],
moment_groups: List[Tuple[int, int]],
get_circuit_diagram_info: Optional[
Callable[['cirq.Operation', 'cirq.CircuitDiagramInfoArgs'],
'cirq.CircuitDiagramInfo']] = None,
include_tags: bool = True):
if get_circuit_diagram_info is None:
get_circuit_diagram_info = (
_get_operation_circuit_diagram_info_with_fallback)
x0 = out_diagram.width()
non_global_ops = [op for op in moment.operations if op.qubits]
max_x = x0
for op in non_global_ops:
indices = [qubit_map[q] for q in op.qubits]
y1 = min(indices)
y2 = max(indices)
# Find an available column.
x = x0
while any(out_diagram.content_present(x, y)
for y in range(y1, y2 + 1)):
out_diagram.force_horizontal_padding_after(x, 0)
x += 1
args = protocols.CircuitDiagramInfoArgs(
known_qubits=op.qubits,
known_qubit_count=len(op.qubits),
use_unicode_characters=use_unicode_characters,
qubit_map=qubit_map,
precision=precision,
include_tags=include_tags)
info = get_circuit_diagram_info(op, args)
# Draw vertical line linking the gate's qubits.
if y2 > y1 and info.connected:
out_diagram.vertical_line(x, y1, y2)
# Print gate qubit labels.
for s, q in zip(info.wire_symbols, op.qubits):
out_diagram.write(x, qubit_map[q], s)
exponent = _formatted_exponent(info, args)
if exponent is not None:
if info.connected:
# Add an exponent to the last label only.
if info.exponent_qubit_index is not None:
y3 = qubit_map[op.qubits[info.exponent_qubit_index]]
else:
y3 = y2
out_diagram.write(x, y3, '^' + exponent)
else:
# Add an exponent to every label
for index in indices:
out_diagram.write(x, index, '^' + exponent)
if x > max_x:
max_x = x
global_phase: Optional[complex] = None
tags: List[Any] = []
for op in moment:
if isinstance(op.untagged, ops.GlobalPhaseOperation):
tags.extend(op.tags)
if global_phase is None:
global_phase = complex(1)
global_phase *= complex(op.untagged.coefficient)
# Print out global phase, unless it's 1 (phase of 0pi) or it's the only op.
if global_phase and (global_phase != 1 or not non_global_ops):
desc = _formatted_phase(global_phase, use_unicode_characters, precision)
if desc:
y = max(qubit_map.values(), default=0) + 1
if tags and include_tags:
desc = desc + str(tags)
out_diagram.write(x0, y, desc)
if not non_global_ops:
out_diagram.write(x0, 0, '')
# Group together columns belonging to the same Moment.
if moment.operations and max_x > x0:
moment_groups.append((x0, max_x))
def _formatted_phase(coefficient: complex, unicode: bool,
precision: Optional[int]) -> str:
h = math.atan2(coefficient.imag, coefficient.real) / math.pi
unit = 'π' if unicode else 'pi'
if h == 1:
return unit
return '{{:.{}}}'.format(precision).format(h) + unit
def _draw_moment_groups_in_diagram(moment_groups: List[Tuple[int, int]],
use_unicode_characters: bool,
out_diagram: TextDiagramDrawer):
out_diagram.insert_empty_rows(0)
h = out_diagram.height()
# Insert columns starting from the back since the insertion
# affects subsequent indices.
for x1, x2 in reversed(moment_groups):
out_diagram.insert_empty_columns(x2 + 1)
out_diagram.force_horizontal_padding_after(x2, 0)
out_diagram.insert_empty_columns(x1)
out_diagram.force_horizontal_padding_after(x1, 0)
x2 += 2
for x in range(x1, x2):
out_diagram.force_horizontal_padding_after(x, 0)
for y in [0, h]:
out_diagram.horizontal_line(y, x1, x2)
out_diagram.vertical_line(x1, 0, 0.5)
out_diagram.vertical_line(x2, 0, 0.5)
out_diagram.vertical_line(x1, h, h-0.5)
out_diagram.vertical_line(x2, h, h-0.5)
# Rounds up to 1 when horizontal, down to 0 when vertical.
# (Matters when transposing.)
out_diagram.force_vertical_padding_after(0, 0.5)
out_diagram.force_vertical_padding_after(h - 1, 0.5)
def _apply_unitary_circuit(circuit: Circuit, state: np.ndarray,
qubits: Tuple['cirq.Qid', ...],
dtype: Type[np.number]) -> np.ndarray:
"""Applies a circuit's unitary effect to the given vector or matrix.
This method assumes that the caller wants to ignore measurements.
Args:
circuit: The circuit to simulate. All operations must have a known
matrix or decompositions leading to known matrices. Measurements
are allowed to be in the circuit, but they will be ignored.
state: The initial state tensor (i.e. superposition or unitary matrix).
This is what will be left-multiplied by the circuit's effective
unitary. If this is a state vector, it must have shape
(2,) * num_qubits. If it is a unitary matrix it should have shape
(2,) * (2*num_qubits).
qubits: The qubits in the state tensor. Determines which axes operations
apply to. An operation targeting the k'th qubit in this list will
operate on the k'th axis of the state tensor.
dtype: The numpy dtype to use for applying the unitary. Must be a
complex dtype.
Returns:
The left-multiplied state tensor.
"""
buffer = np.empty_like(state)
def on_stuck(bad_op):
return TypeError(
'Operation without a known matrix or decomposition: {!r}'.format(
bad_op))
unitary_ops = protocols.decompose(
circuit.all_operations(),
keep=protocols.has_unitary,
intercepting_decomposer=_decompose_measurement_inversions,
on_stuck_raise=on_stuck)
return protocols.apply_unitaries(
unitary_ops, qubits,
protocols.ApplyUnitaryArgs(state, buffer, range(len(qubits))))
def _decompose_measurement_inversions(op: 'cirq.Operation') -> 'cirq.OP_TREE':
if isinstance(op.gate, ops.MeasurementGate):
return [ops.X(q) for q, b in zip(op.qubits, op.gate.invert_mask) if b]
return NotImplemented
def _list_repr_with_indented_item_lines(items: Sequence[Any]) -> str:
block = '\n'.join([repr(op) + ',' for op in items])
indented = ' ' + '\n '.join(block.split('\n'))
return '[\n{}\n]'.format(indented)
TIn = TypeVar('TIn')
TOut = TypeVar('TOut')
TKey = TypeVar('TKey')
@overload
def _group_until_different(items: Iterable[TIn],
key: Callable[[TIn], TKey],
) -> Iterable[Tuple[TKey, List[TIn]]]:
pass
@overload
def _group_until_different(items: Iterable[TIn],
key: Callable[[TIn], TKey],
value: Callable[[TIn], TOut]
) -> Iterable[Tuple[TKey, List[TOut]]]:
pass
def _group_until_different(items: Iterable[TIn],
key: Callable[[TIn], TKey],
value=lambda e: e):
"""Groups runs of items that are identical according to a keying function.
Args:
items: The items to group.
key: If two adjacent items produce the same output from this function,
they will be grouped.
value: Maps each item into a value to put in the group. Defaults to the
item itself.
Examples:
_group_until_different(range(11), key=is_prime) yields
(False, [0, 1])
(True, [2, 3])
(False, [4])
(True, [5])
(False, [6])
(True, [7])
(False, [8, 9, 10])
Yields:
Tuples containing the group key and item values.
"""
return ((k, [value(i) for i in v]) for (k, v) in groupby(items, key))
|
from tools import RaspEnum
Python27Path = "C:\Python27\python.exe"
Python27_64Path = "C:\Python27_64\python.exe"
Service_Phase = float(9999)
Time_My_Code = False
number_of_contingencies_for_screening = 6
class ComponentStatusEnum(RaspEnum):
ReconnectedService = (-2, "ReconnectedService")
Reconnected = (-1, "Reconnected")
Service = (1, "Service")
Disconnected = (2, "Disconnected")
class MonsterModulesEnum(RaspEnum):
PreProcess = (1, "Pre process")
Rasp = (2, "Rasp")
MonteCarlo = (3, "Monte carlo")
ServicePlan = (4, "Service plan")
PostProcess = (5, "Post process")
class RemedialMeasuresEnum(RaspEnum):
ConfigModel = (0, "ConfigModel")
InitialSolution = (1, "Initial Solution")
LoadReduction = (2, "Load Reduction")
LoadReductionDroop = (3, "Load Reduction Droop")
LoadReductionSequential = (4, "Load Reduction")
MoveLoad = (5, "Move Load")
ChangeProduction = (6, "Change Production")
ChangeProductionDroop = (7, "Change Production with droop")
CombinedLoadChangeProduction = (8, "Combined load and change production")
CombinedLoadChangeProductionDroop = (9, "Combined load and change production with droop")
CombinedAll = (10, "Combined all")
CombinedAllDroop = (11, "Combined all with droop")
TripNextOverload = (12, "Tripp next overload")
TripLine = (13, "Tripp line")
class ComponentTypeEnum(RaspEnum):
BaseComponent = (0, 'BaseComponent')
BusComponent = (1, 'BusComponent')
BranchComponent = (2, 'BranchComponent')
OverHeadLineComponent = (3, 'OverHeadLineComponent')
TwoWindingTransformerComponent = (4, 'TwoWindingTransformerComponent')
ThreeWindingTransformerComponent = (5, 'ThreeWindingTransformerComponent')
LoadComponent = (6, 'LoadComponent')
MachineComponent = (7, 'MachineComponent')
CableComponent = (8, 'CableComponent')
LineComponent = (9, 'LineComponent')
class ComponentStatus(RaspEnum):
on = (1, 'on')
off = (0, 'off')
class BusType(RaspEnum):
PQ = (1, "PQ")
PV = (2, "PV")
swing = (3, "swing")
disconnected = (4, "disconnected")
class WeatherTypeEnum(RaspEnum):
Wind = (1, 'wind')
Lightning = (2, 'lightning')
Ice_Snow = (3, 'ice_snow')
Other = (4, 'other')
class FailureSourceEnum(RaspEnum):
Wind = (1, 'wind')
Lightning = (2, 'lightning')
Ice_Snow = (3, 'ice_snow')
Other = (4, 'other')
Maintenance = (5, 'maintenance')
class FailureTypeEnum(RaspEnum):
Permanent = (1, 'permanent')
Temporary = (2, 'temporary')
class FailureTypeWithMaintenanceEnum(RaspEnum):
Permanent = (1, 'permanent')
Temporary = (2, 'temporary')
Maintenance = (3, 'maintenance')
|
import ast
from os import listdir
from os.path import isfile, join
directory = "/home/known/Desktop/Masters/Code/Actual/memory_capacity_retention_rnns/Notebooks/backup_15_11_2018_2000"
onlyfiles = [f for f in listdir(directory) if isfile(join(directory, f))]
with open('/home/known/Desktop/Masters/Code/Actual/memory_capacity_retention_rnns/Notebooks/patterns.csv', 'a') as the_file:
line_to_write = "folder_root,run_count,f_score,timesteps,sparsity_length,case_type,num_input,num_output,num_patterns_to_recall,num_patterns_total,random_seed,error_when_stopped,num_network_parameters,network_type,training_algorithm,batch_size,epocs,activation_function,num_correctly_identified,architecture,full_network_json ,model_history,full_network ,input_set,output_set"
the_file.write(line_to_write + '\n')
for f in onlyfiles:
if "patterns.log" in f:
file = open(directory + "/" + f)
line = file.readline()
info_seen = False
single_dataset = [line]
dataset = []
count = 0
while line:
line = file.readline()
single_dataset.append(line)
if "INFO" in line:
info_seen = True
if info_seen:
dataset.append(single_dataset)
single_dataset = []
single_dataset.append(line)
info_seen = False
count += 1
dataset.append(single_dataset)
file.close()
for element in dataset:
if element:
d = {}
split_line = element[0].split(";")
if(len(element) > 1):
if element[2]:
val_acc = element[2].split(";")[0]
else:
val_acc = ['']
line_to_write = split_line[0] + "," + split_line[1] + "," + split_line[2] + "," + \
split_line[3] + "," +split_line[4] + "," + split_line[5] + "," + \
split_line[6]+ "," + split_line[7] + "," + split_line[8] + "," +\
split_line[9] + "," + split_line[10] + "," + split_line[11] + "," +\
split_line[12] + "," + split_line[13]+ "," + split_line[14]+ "," +split_line[15] + "," + \
str( val_acc.count(',') +1)+ "," +split_line[17] + "," +split_line[18]
the_file.write(line_to_write + '\n')
|
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from .job_statistics_vertex_stage import JobStatisticsVertexStage
from .job_statistics import JobStatistics
from .job_data_path import JobDataPath
from .job_state_audit_record import JobStateAuditRecord
from .job_resource import JobResource
from .diagnostics import Diagnostics
from .usql_job_properties import USqlJobProperties
from .hive_job_properties import HiveJobProperties
from .job_properties import JobProperties
from .create_usql_job_properties import CreateUSqlJobProperties
from .create_job_properties import CreateJobProperties
from .job_inner_error import JobInnerError
from .job_error_details import JobErrorDetails
from .job_relationship_properties import JobRelationshipProperties
from .job_pipeline_run_information import JobPipelineRunInformation
from .job_pipeline_information import JobPipelineInformation
from .job_recurrence_information import JobRecurrenceInformation
from .create_job_parameters import CreateJobParameters
from .build_job_parameters import BuildJobParameters
from .base_job_parameters import BaseJobParameters
from .job_information_basic import JobInformationBasic
from .job_information import JobInformation
from .job_pipeline_information_paged import JobPipelineInformationPaged
from .job_recurrence_information_paged import JobRecurrenceInformationPaged
from .job_information_basic_paged import JobInformationBasicPaged
from .data_lake_analytics_job_management_client_enums import (
JobResourceType,
SeverityTypes,
CompileMode,
JobType,
JobState,
JobResult,
)
__all__ = [
'JobStatisticsVertexStage',
'JobStatistics',
'JobDataPath',
'JobStateAuditRecord',
'JobResource',
'Diagnostics',
'USqlJobProperties',
'HiveJobProperties',
'JobProperties',
'CreateUSqlJobProperties',
'CreateJobProperties',
'JobInnerError',
'JobErrorDetails',
'JobRelationshipProperties',
'JobPipelineRunInformation',
'JobPipelineInformation',
'JobRecurrenceInformation',
'CreateJobParameters',
'BuildJobParameters',
'BaseJobParameters',
'JobInformationBasic',
'JobInformation',
'JobPipelineInformationPaged',
'JobRecurrenceInformationPaged',
'JobInformationBasicPaged',
'JobResourceType',
'SeverityTypes',
'CompileMode',
'JobType',
'JobState',
'JobResult',
]
|
const a = require('./a');
console.log(a.name);
exports.name = 'b';
|
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
'use strict';
function main(parent) {
// [START cloudchannel_v1_generated_CloudChannelService_ListOffers_async]
/**
* TODO(developer): Uncomment these variables before running the sample.
*/
/**
* Required. The resource name of the reseller account from which to list Offers.
* Parent uses the format: accounts/{account_id}.
*/
// const parent = 'abc123'
/**
* Optional. Requested page size. Server might return fewer results than requested.
* If unspecified, returns at most 500 Offers.
* The maximum value is 1000; the server will coerce values above 1000.
*/
// const pageSize = 1234
/**
* Optional. A token for a page of results other than the first page.
*/
// const pageToken = 'abc123'
/**
* Optional. The expression to filter results by name (name of
* the Offer), sku.name (name of the SKU), or sku.product.name (name of the
* Product).
* Example 1: sku.product.name=products/p1 AND sku.name!=products/p1/skus/s1
* Example 2: name=accounts/a1/offers/o1
*/
// const filter = 'abc123'
/**
* Optional. The BCP-47 language code. For example, "en-US". The
* response will localize in the corresponding language code, if specified.
* The default value is "en-US".
*/
// const languageCode = 'abc123'
// Imports the Channel library
const {CloudChannelServiceClient} = require('@google-cloud/channel').v1;
// Instantiates a client
const channelClient = new CloudChannelServiceClient();
async function callListOffers() {
// Construct request
const request = {
parent,
};
// Run request
const iterable = await channelClient.listOffersAsync(request);
for await (const response of iterable) {
console.log(response);
}
}
callListOffers();
// [END cloudchannel_v1_generated_CloudChannelService_ListOffers_async]
}
process.on('unhandledRejection', err => {
console.error(err.message);
process.exitCode = 1;
});
main(...process.argv.slice(2));
|
def test():
x = 1
f = lambda: x
x = 2
print(f())
def test2(omit=None):
def scrub(attrs):
return tuple(a for a in attrs if a not in omit)
omit = omit or ()
print(scrub('abc'))
def test3():
for i in range(3):
j = i
print(i, j)
def test4(param=1):
def inner(p2=2):
print('locals', *locals().keys())
print('globals', *globals().keys())
inner()
if True:
test4()
else:
test()
test2()
test3()
|
'use strict';
module.exports = function (app) {
// Root routing
var core = require('../controllers/core.server.controller');
// Define error pages
app.route('/server-error').get(core.renderServerError);
// Return a 404 for all undefined api, module or lib routes
app.route('/:url(api|modules|lib)/*').get(core.renderNotFound);
app.route('/:url(uploads|thumb)/*').get(core.renderNotFound);
// Define application route
app.route('/*').get(core.renderIndex);
};
|
export { default } from 'ember-flexberry-gis/components/map-commands-dialogs/search-settings/wfs';
|
import { Component } from 'react';
import './App.css';
import Previousoutputs from './components/previousoutputs/previousoutputs.component'
import { db } from './firebase'
import Buttons from './components/buttons/buttons.component'
import firebase from 'firebase'
class App extends Component {
constructor(){
super()
this.state = {
output: '',
problem:'',
enabled: true
}
}
onClick = button => {
if(button === "="){
this.evaluate()
}
else if(button === "AC"){
this.clear()
}
else if(button === "DEL" && this.state.enabled === true){
this.delete()
}
else if(button === "DEL" && this.state.enabled === false){
return
}
else {
this.setState({
output: this.state.output + button,
problem: this.state.problem + button
})
}
}
sendMessage = () => {
const calculationsRef = db.collection("results");
calculationsRef.add({
problem: this.state.problem,
createdAt: firebase.firestore.FieldValue.serverTimestamp(),
solution: this.state.output
})
}
clear = () => {
this.setState({
output:'',
problem:'',
enabled: true
})
}
delete = () => {
try{
this.setState({
output: this.state.output.slice(0, -1),
problem: this.state.problem.slice(0, -1)
})
} catch(e){
this.setState({
output: 'ERROR',
problem: ''
})
}
};
evaluate = ()=> {
try {
this.setState({
output: (eval(this.state.output) || "" ) + "",
enabled: false
})
setTimeout(this.sendMessage, 200)
} catch(e){
this.setState({
output: 'ERROR',
problem: ''
})
}
}
render() {
return (
<div>
<div className='calcbody'>
<div className='calccell'>
<Buttons onClick={this.onClick} output={this.state.output} problem={this.state.problem}/>
</div>
<div className='calccell'>
<Previousoutputs/>
</div>
</div>
</div>
)
}
}
export default App;
|
import React, { Component } from 'react';
import * as PropTypes from 'prop-types';
import graphql from 'babel-plugin-relay/macro';
import { createFragmentContainer } from 'react-relay';
import { Formik, Field, Form } from 'formik';
import { withStyles } from '@material-ui/core/styles';
import { compose, pick } from 'ramda';
import * as Yup from 'yup';
import inject18n from '../../../../components/i18n';
import TextField from '../../../../components/TextField';
import { SubscriptionFocus } from '../../../../components/Subscription';
import { commitMutation } from '../../../../relay/environment';
const styles = theme => ({
drawerPaper: {
minHeight: '100vh',
width: '50%',
position: 'fixed',
overflow: 'hidden',
backgroundColor: theme.palette.navAlt.background,
transition: theme.transitions.create('width', {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.enteringScreen,
}),
padding: '30px 30px 30px 30px',
},
createButton: {
position: 'fixed',
bottom: 30,
right: 30,
},
importButton: {
position: 'absolute',
top: 30,
right: 30,
},
});
const groupMutationFieldPatch = graphql`
mutation GroupEditionOverviewFieldPatchMutation(
$id: ID!
$input: EditInput!
) {
groupEdit(id: $id) {
fieldPatch(input: $input) {
...GroupEditionOverview_group
}
}
}
`;
const groupEditionOverviewFocus = graphql`
mutation GroupEditionOverviewFocusMutation($id: ID!, $input: EditContext!) {
groupEdit(id: $id) {
contextPatch(input: $input) {
id
}
}
}
`;
const groupValidation = t => Yup.object().shape({
name: Yup.string().required(t('This field is required')),
description: Yup.string(),
});
class GroupEditionOverviewComponent extends Component {
handleChangeFocus(name) {
commitMutation({
mutation: groupEditionOverviewFocus,
variables: {
id: this.props.group.id,
input: {
focusOn: name,
},
},
});
}
handleSubmitField(name, value) {
groupValidation(this.props.t)
.validateAt(name, { [name]: value })
.then(() => {
commitMutation({
mutation: groupMutationFieldPatch,
variables: { id: this.props.group.id, input: { key: name, value } },
});
})
.catch(() => false);
}
render() {
const {
t, group, editUsers, me,
} = this.props;
const initialValues = pick(['name', 'description'], group);
return (
<div>
<Formik
enableReinitialize={true}
initialValues={initialValues}
validationSchema={groupValidation(t)}
onSubmit={() => true}
render={() => (
<Form style={{ margin: '20px 0 20px 0' }}>
<Field
name="name"
component={TextField}
label={t('Name')}
fullWidth={true}
onFocus={this.handleChangeFocus.bind(this)}
onSubmit={this.handleSubmitField.bind(this)}
helperText={
<SubscriptionFocus
me={me}
users={editUsers}
fieldName="name"
/>
}
/>
<Field
name="description"
component={TextField}
label={t('Description')}
fullWidth={true}
multiline={true}
rows={4}
style={{ marginTop: 10 }}
onFocus={this.handleChangeFocus.bind(this)}
onSubmit={this.handleSubmitField.bind(this)}
helperText={
<SubscriptionFocus
me={me}
users={editUsers}
fieldName="description"
/>
}
/>
</Form>
)}
/>
</div>
);
}
}
GroupEditionOverviewComponent.propTypes = {
classes: PropTypes.object,
theme: PropTypes.object,
t: PropTypes.func,
group: PropTypes.object,
editUsers: PropTypes.array,
me: PropTypes.object,
};
const GroupEditionOverview = createFragmentContainer(
GroupEditionOverviewComponent,
{
group: graphql`
fragment GroupEditionOverview_group on Group {
id
name
description
}
`,
},
);
export default compose(
inject18n,
withStyles(styles, { withTheme: true }),
)(GroupEditionOverview);
|
// Copyright 2014 the V8 project authors. All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// Flags: --allow-natives-syntax --turbo-deoptimization
(function OneByteSeqStringSetCharDeoptOsr() {
function deopt() {
%DeoptimizeFunction(f);
}
function f(string, osr) {
var world = " world";
%_OneByteSeqStringSetChar(0, (deopt(), 0x48), string);
for (var i = 0; osr && i < 2; i++) %OptimizeOsr();
return string + world;
}
assertEquals("Hello " + "world", f("hello", false));
%OptimizeFunctionOnNextCall(f);
assertEquals("Hello " + "world", f("hello", true));
})();
(function OneByteSeqStringSetCharDeopt() {
function deopt() {
%DeoptimizeFunction(f);
}
function g(x) {
}
function f(string) {
g(%_OneByteSeqStringSetChar(0, (deopt(), 0x48), string));
return string;
}
assertEquals("Hell" + "o", f("hello"));
%OptimizeFunctionOnNextCall(f);
assertEquals("Hell" + "o", f("hello"));
})();
(function TwoByteSeqStringSetCharDeopt() {
function deopt() {
%DeoptimizeFunction(f);
}
function g(x) {
}
function f(string) {
g(%_TwoByteSeqStringSetChar(0, (deopt(), 0x48), string));
return string;
}
assertEquals("Hell" + "o", f("\u20ACello"));
%OptimizeFunctionOnNextCall(f);
assertEquals("Hell" + "o", f("\u20ACello"));
})();
|
import Vue from 'vue'
import App from './App.vue'
Vue.directive('highlight', {
bind(el, binding, vnode) {
// el.style.backgroundColor = binding.value;
var delay = 0;
if(binding.modifiers['delayed']){
delay = 3000;
}
setTimeout(() => {
if(binding.arg == 'background'){
el.style.backgroundColor = binding.value;
} else {
el.style.color = binding.value;
}
}, delay);
}
});
new Vue({
el: '#app',
render: h => h(App)
})
|
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @noflow
* @flow-weak
* @jsdoc
*/
'use strict';
import NativeAsyncStorage from './NativeAsyncStorage';
import invariant from 'invariant';
// Use SQLite if available, otherwise file storage.
const RCTAsyncStorage = NativeAsyncStorage;
/**
* `AsyncStorage` is a simple, unencrypted, asynchronous, persistent, key-value
* storage system that is global to the app. It should be used instead of
* LocalStorage.
*
* See http://facebook.github.io/react-native/docs/asyncstorage.html
*/
const AsyncStorage = {
_getRequests: ([]: Array<any>),
_getKeys: ([]: Array<string>),
_immediate: (null: ?number),
/**
* Fetches an item for a `key` and invokes a callback upon completion.
*
* See http://facebook.github.io/react-native/docs/asyncstorage.html#getitem
*/
getItem: function(
key: string,
callback?: ?(error: ?Error, result: ?string) => void,
): Promise {
invariant(RCTAsyncStorage, 'RCTAsyncStorage not available');
return new Promise((resolve, reject) => {
RCTAsyncStorage.multiGet([key], function(errors, result) {
// Unpack result to get value from [[key,value]]
const value = result && result[0] && result[0][1] ? result[0][1] : null;
const errs = convertErrors(errors);
callback && callback(errs && errs[0], value);
if (errs) {
reject(errs[0]);
} else {
resolve(value);
}
});
});
},
/**
* Sets the value for a `key` and invokes a callback upon completion.
*
* See http://facebook.github.io/react-native/docs/asyncstorage.html#setitem
*/
setItem: function(
key: string,
value: string,
callback?: ?(error: ?Error) => void,
): Promise {
invariant(RCTAsyncStorage, 'RCTAsyncStorage not available');
return new Promise((resolve, reject) => {
RCTAsyncStorage.multiSet([[key, value]], function(errors) {
const errs = convertErrors(errors);
callback && callback(errs && errs[0]);
if (errs) {
reject(errs[0]);
} else {
resolve(null);
}
});
});
},
/**
* Removes an item for a `key` and invokes a callback upon completion.
*
* See http://facebook.github.io/react-native/docs/asyncstorage.html#removeitem
*/
removeItem: function(
key: string,
callback?: ?(error: ?Error) => void,
): Promise {
invariant(RCTAsyncStorage, 'RCTAsyncStorage not available');
return new Promise((resolve, reject) => {
RCTAsyncStorage.multiRemove([key], function(errors) {
const errs = convertErrors(errors);
callback && callback(errs && errs[0]);
if (errs) {
reject(errs[0]);
} else {
resolve(null);
}
});
});
},
/**
* Merges an existing `key` value with an input value, assuming both values
* are stringified JSON.
*
* **NOTE:** This is not supported by all native implementations.
*
* See http://facebook.github.io/react-native/docs/asyncstorage.html#mergeitem
*/
mergeItem: function(
key: string,
value: string,
callback?: ?(error: ?Error) => void,
): Promise {
invariant(RCTAsyncStorage, 'RCTAsyncStorage not available');
return new Promise((resolve, reject) => {
RCTAsyncStorage.multiMerge([[key, value]], function(errors) {
const errs = convertErrors(errors);
callback && callback(errs && errs[0]);
if (errs) {
reject(errs[0]);
} else {
resolve(null);
}
});
});
},
/**
* Erases *all* `AsyncStorage` for all clients, libraries, etc. You probably
* don't want to call this; use `removeItem` or `multiRemove` to clear only
* your app's keys.
*
* See http://facebook.github.io/react-native/docs/asyncstorage.html#clear
*/
clear: function(callback?: ?(error: ?Error) => void): Promise {
invariant(RCTAsyncStorage, 'RCTAsyncStorage not available');
return new Promise((resolve, reject) => {
RCTAsyncStorage.clear(function(error) {
callback && callback(convertError(error));
if (error && convertError(error)) {
reject(convertError(error));
} else {
resolve(null);
}
});
});
},
/**
* Gets *all* keys known to your app; for all callers, libraries, etc.
*
* See http://facebook.github.io/react-native/docs/asyncstorage.html#getallkeys
*/
getAllKeys: function(
callback?: ?(error: ?Error, keys: ?Array<string>) => void,
): Promise {
invariant(RCTAsyncStorage, 'RCTAsyncStorage not available');
return new Promise((resolve, reject) => {
RCTAsyncStorage.getAllKeys(function(error, keys) {
callback && callback(convertError(error), keys);
if (error) {
reject(convertError(error));
} else {
resolve(keys);
}
});
});
},
/**
* The following batched functions are useful for executing a lot of
* operations at once, allowing for native optimizations and provide the
* convenience of a single callback after all operations are complete.
*
* These functions return arrays of errors, potentially one for every key.
* For key-specific errors, the Error object will have a key property to
* indicate which key caused the error.
*/
/**
* Flushes any pending requests using a single batch call to get the data.
*
* See http://facebook.github.io/react-native/docs/asyncstorage.html#flushgetrequests
* */
flushGetRequests: function(): void {
const getRequests = this._getRequests;
const getKeys = this._getKeys;
this._getRequests = [];
this._getKeys = [];
invariant(RCTAsyncStorage, 'RCTAsyncStorage not available');
RCTAsyncStorage.multiGet(getKeys, function(errors, result) {
// Even though the runtime complexity of this is theoretically worse vs if we used a map,
// it's much, much faster in practice for the data sets we deal with (we avoid
// allocating result pair arrays). This was heavily benchmarked.
//
// Is there a way to avoid using the map but fix the bug in this breaking test?
// https://github.com/facebook/react-native/commit/8dd8ad76579d7feef34c014d387bf02065692264
const map = {};
result &&
result.forEach(([key, value]) => {
map[key] = value;
return value;
});
const reqLength = getRequests.length;
for (let i = 0; i < reqLength; i++) {
const request = getRequests[i];
const requestKeys = request.keys;
const requestResult = requestKeys.map(key => [key, map[key]]);
request.callback && request.callback(null, requestResult);
request.resolve && request.resolve(requestResult);
}
});
},
/**
* This allows you to batch the fetching of items given an array of `key`
* inputs. Your callback will be invoked with an array of corresponding
* key-value pairs found.
*
* See http://facebook.github.io/react-native/docs/asyncstorage.html#multiget
*/
multiGet: function(
keys: Array<string>,
callback?: ?(errors: ?Array<Error>, result: ?Array<Array<string>>) => void,
): Promise {
if (!this._immediate) {
this._immediate = setImmediate(() => {
this._immediate = null;
this.flushGetRequests();
});
}
const getRequest = {
keys: keys,
callback: callback,
// do we need this?
keyIndex: this._getKeys.length,
resolve: null,
reject: null,
};
const promiseResult = new Promise((resolve, reject) => {
getRequest.resolve = resolve;
getRequest.reject = reject;
});
this._getRequests.push(getRequest);
// avoid fetching duplicates
keys.forEach(key => {
if (this._getKeys.indexOf(key) === -1) {
this._getKeys.push(key);
}
});
return promiseResult;
},
/**
* Use this as a batch operation for storing multiple key-value pairs. When
* the operation completes you'll get a single callback with any errors.
*
* See http://facebook.github.io/react-native/docs/asyncstorage.html#multiset
*/
multiSet: function(
keyValuePairs: Array<Array<string>>,
callback?: ?(errors: ?Array<Error>) => void,
): Promise {
invariant(RCTAsyncStorage, 'RCTAsyncStorage not available');
return new Promise((resolve, reject) => {
RCTAsyncStorage.multiSet(keyValuePairs, function(errors) {
const error = convertErrors(errors);
callback && callback(error);
if (error) {
reject(error);
} else {
resolve(null);
}
});
});
},
/**
* Call this to batch the deletion of all keys in the `keys` array.
*
* See http://facebook.github.io/react-native/docs/asyncstorage.html#multiremove
*/
multiRemove: function(
keys: Array<string>,
callback?: ?(errors: ?Array<Error>) => void,
): Promise {
invariant(RCTAsyncStorage, 'RCTAsyncStorage not available');
return new Promise((resolve, reject) => {
RCTAsyncStorage.multiRemove(keys, function(errors) {
const error = convertErrors(errors);
callback && callback(error);
if (error) {
reject(error);
} else {
resolve(null);
}
});
});
},
/**
* Batch operation to merge in existing and new values for a given set of
* keys. This assumes that the values are stringified JSON.
*
* **NOTE**: This is not supported by all native implementations.
*
* See http://facebook.github.io/react-native/docs/asyncstorage.html#multimerge
*/
multiMerge: function(
keyValuePairs: Array<Array<string>>,
callback?: ?(errors: ?Array<Error>) => void,
): Promise {
invariant(RCTAsyncStorage, 'RCTAsyncStorage not available');
return new Promise((resolve, reject) => {
RCTAsyncStorage.multiMerge(keyValuePairs, function(errors) {
const error = convertErrors(errors);
callback && callback(error);
if (error) {
reject(error);
} else {
resolve(null);
}
});
});
},
};
// Not all native implementations support merge.
if (!RCTAsyncStorage.multiMerge) {
delete AsyncStorage.mergeItem;
delete AsyncStorage.multiMerge;
}
function convertErrors(errs) {
if (!errs) {
return null;
}
return (Array.isArray(errs) ? errs : [errs]).map(e => convertError(e));
}
function convertError(error) {
if (!error) {
return null;
}
const out = new Error(error.message);
out.key = error.key; // flow doesn't like this :(
return out;
}
module.exports = AsyncStorage;
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import { arc } from 'd3-shape';
import { select, selectAll, event } from 'd3-selection'; // eslint-disable-line
import { interpolate } from 'd3-interpolate';
import { scaleSqrt, scaleLinear, scaleOrdinal } from 'd3-scale';
import { transition } from 'd3-transition'; // eslint-disable-line
import { schemeCategory10 } from 'd3-scale-chromatic';
import { path } from 'd3-path';
import { hierarchy, partition } from 'd3-hierarchy';
import { theme } from '../../constants';
const Svg = styled.svg`
max-width: 400px;
.slice {
cursor: pointer;
}
.slice .main-arc {
stroke: #fff;
stroke-width: 1px;
}
.slice .hidden-arc {
fill: none;
}
.slice text {
pointer-events: none;
dominant-baseline: middle;
text-anchor: middle;
}
`;
Svg.defaultProps = {
theme,
};
class SunBurst extends Component {
static defaultProps = {
data: {},
width: 208,
height: 140,
};
static propTypes = {
data: PropTypes.object,
height: PropTypes.number,
width: PropTypes.number,
};
componentDidMount() {
const { width, height } = this.props;
this.sunBurstContainer = this.svg.attr(
'viewBox',
`${-width / 2} ${-height / 2} ${width} ${height}`,
);
this.renderSunBurst();
}
renderSunBurst() {
const { data, height, width } = this.props;
let maxRadius = Math.min(width, height) / 2;
maxRadius -= 5;
this.x = scaleLinear()
.range([0, 2 * Math.PI])
.clamp(true);
this.y = scaleSqrt().range([maxRadius * 0.1, maxRadius]);
this.color = scaleOrdinal(schemeCategory10);
this.partition = partition();
this.arc = arc()
.startAngle(d => this.x(d.x0))
.endAngle(d => this.x(d.x1))
.innerRadius(d => Math.max(0, this.y(d.y0)))
.outerRadius(d => Math.max(0, this.y(d.y1)));
this.root = hierarchy(data);
this.root.sum(d => d.size);
this.slice = this.svg
.selectAll('g.slice')
.data(this.partition(this.root).descendants());
// Exit
this.slice.exit().remove();
// Enter
this.newSlice = this.slice
.enter()
.append('g')
.attr('class', 'slice')
.on('click', d => {
event.stopPropagation();
this.focusOn(d);
});
this.newSlice.append('title').text(d => `${d.data.name}`);
this.newSlice
.append('path')
.attr('class', 'main-arc')
.style('fill', d => this.color((d.children ? d : d.parent).data.name))
.attr('d', this.arc);
this.newSlice
.append('path')
.attr('class', 'hidden-arc')
.attr('id', (_, i) => `hiddenArc${i}`)
.attr('d', this.middleArcLine);
this.text = this.newSlice
.append('text')
.attr('display', d => (this.textFits(d) ? null : 'none'));
this.text
.append('textPath')
.attr('startOffset', '50%')
.attr('xlink:href', (_, i) => `#hiddenArc${i}`)
.text(d => d.data.name)
.style('fill', 'none')
.style('stroke', '#fff')
.style('stroke-width', 5)
.style('stroke-linejoin', 'round');
this.text
.append('textPath')
.attr('startOffset', '50%')
.attr('xlink:href', (_, i) => `#hiddenArc${i}`)
.text(d => d.data.name);
}
middleArcLine = d => {
const halfPi = Math.PI / 2;
const angles = [this.x(d.x0) - halfPi, this.x(d.x1) - halfPi];
const r = Math.max(0, (this.y(d.y0) + this.y(d.y1)) / 2);
const middleAngle = (angles[1] + angles[0]) / 2;
const invertDirection = middleAngle > 0 && middleAngle < Math.PI; // On lower quadrants write text ccw
if (invertDirection) {
angles.reverse();
}
this.path = path();
this.path.arc(0, 0, r, angles[0], angles[1], invertDirection);
return this.path.toString();
};
textFits = d => {
const CHAR_SPACE = 6;
const deltaAngle = this.x(d.x1) - this.x(d.x0);
const r = Math.max(0, (this.y(d.y0) + this.y(d.y1)) / 2);
const perimeter = r * deltaAngle;
return d.data.name.length * CHAR_SPACE < perimeter;
};
focusOn = (d = { x0: 0, x1: 1, y0: 0, y1: 1 }) => {
// Reset to top-level if no data point specified
const transition = this.sunBurstContainer
.transition()
.duration(750)
.tween('scale', () => {
const xd = interpolate(this.x.domain(), [d.x0, d.x1]);
const yd = interpolate(this.y.domain(), [d.y0, 1]);
return t => {
this.x.domain(xd(t));
this.y.domain(yd(t));
};
});
transition
.selectAll('path.main-arc')
.attrTween('d', d => () => this.arc(d));
transition
.selectAll('path.hidden-arc')
.attrTween('d', d => () => this.middleArcLine(d));
transition
.selectAll('text')
.attrTween('display', d => () => (this.textFits(d) ? null : 'none'));
moveStackToFront(d);
function moveStackToFront(elD) {
transition
.selectAll('.slice')
.filter(d => d === elD)
.each(function(d) {
this.parentNode.appendChild(this);
if (d.parent) {
moveStackToFront(d.parent);
}
});
}
};
render() {
return (
<Svg
width={400}
height={400}
innerRef={node => {
this.svg = select(node);
}}
/>
);
}
}
export default SunBurst;
|
#! /usr/local/bin/python
"""
See LICENSE file for copyright and license details.
"""
from modules.constant import *
from generic.modules.calculator_finance import *
from decimal import Decimal
from generic.modules.function import print_in_columns
class Printer():
"""
Printer class
"""
def __init__(self):
"""
Initialise
"""
pass
def print_general(self, result_general, result_buy, result_sell, export_file = ""):
"""
Print the results with headers etc.
"""
try:
headers_general = [
["amount", "tax", "commission", "shares", "amount_simple"]
, ['-'*len("amount"), '-'*len("tax"), '-'*len("commission"), '-'*len("shares"), '-'*len("amount_simple")]]
headers_buy_sell = [
["cost_tax", "amount_with_tax"]
, ['-'*len("cost_tax"), '-'*len("amount_with_tax")]]
subheader = [["GENERAL"], ['-'*len("GENERAL")*2]]
print_in_columns(subheader)
print_in_columns(headers_general)
print_in_columns([result_general.values()])
if self.buy:
subheader = [["BUY"], ['-'*len("BUY")*2]]
print_in_columns(subheader)
print_in_columns(headers_buy_sell)
print_in_columns([result_buy.values()])
else:
subheader = [["SELL"], ['-'*len("SELL")*2]]
print_in_columns(subheader)
print_in_columns(headers_buy_sell)
print_in_columns([result_sell.values()])
except Exception as ex:
print('Error in print_results():', ex)
def print_gnucash(self, result_general, result_buy, result_sell, export_file = ""):
"""
Print statements to enter in gnucash.
"""
try:
headers = [
['account', 'shares', 'price', 'debit', 'credit']
, ['-'*len('account'), '-'*len('shares'), '-'*len('price'), '-'*len('debit'), '-'*len('credit')]]
if self.buy:
lines = []
lines.append(["assets:stock:<market>.<commodity>", self.shares, self.price, "", result_general["amount_simple"]])
lines.append(["expenses:commission:stock:<market>.<commodity>", "", "", self.commission])
lines.append(["expenses:tax:stock:<market>.<commodity>", "", "", result_buy["cost_tax"]])
lines.append(["assets:current_assets:stock:<bank account>", "", "", "", self.amount])
subheader = [["BUY"], ['-'*len("BUY")*2]]
print_in_columns(subheader)
print_in_columns(headers)
print_in_columns(lines)
else:
lines = []
lines.append(["assets:stock:<market>.<commodity>", self.shares, self.price, result_general["amount_simple"], ""])
lines.append(["expenses:commission:stock:<market>.<commodity>", "", "", self.commission, ""])
lines.append(["expenses:tax:stock:<market>.<commodity>", "", "", "", result_sell["cost_tax"]])
lines.append(["assets:current_assets:stock:<bank account>", "", "", "", self.amount])
subheader = [["SELL"], ['-'*len("SELL")*2]]
print_in_columns(subheader)
print_in_columns(headers)
print_in_columns(lines)
except Exception as ex:
print('Error in print_gnucash():', ex)
|
angular
.module('cms.documents', ['ngRoute', 'cms.shared'])
.constant('_', window._)
.constant('documents.modulePath', '/Admin/Modules/Documents/Js/');
angular.module('cms.documents').config([
'$routeProvider',
'shared.routingUtilities',
'documents.modulePath',
function (
$routeProvider,
routingUtilities,
modulePath) {
routingUtilities.registerCrudRoutes($routeProvider, modulePath, 'Document');
}]);
angular.module('cms.documents').factory('documents.documentService', [
'$http',
'$upload',
'shared.documentService',
function (
$http,
$upload,
sharedDocumentService) {
var service = _.extend({}, sharedDocumentService);
/* COMMANDS */
service.update = function (command) {
return service.uploadFile(service.getIdRoute(command.documentAssetId), command, 'PUT');
}
service.remove = function (id) {
return $http.delete(service.getIdRoute(id));
}
return service;
}]);
angular.module('cms.documents').controller('AddDocumentController', [
'$location',
'_',
'shared.focusService',
'shared.stringUtilities',
'shared.LoadState',
'documents.documentService',
function (
$location,
_,
focusService,
stringUtilities,
LoadState,
documentService
) {
var vm = this;
init();
/* INIT */
function init() {
initData();
vm.save = save;
vm.cancel = cancel;
vm.onFileChanged = onFileChanged;
vm.editMode = false;
vm.saveLoadState = new LoadState();
}
/* EVENTS */
function save() {
vm.saveLoadState.on();
documentService
.add(vm.command)
.progress(vm.saveLoadState.setProgress)
.then(redirectToList)
.finally(vm.saveLoadState.off);
}
function onFileChanged() {
var command = vm.command;
if (command.file && command.file.name) {
command.title = stringUtilities.capitaliseFirstLetter(stringUtilities.getFileNameWithoutExtension(command.file.name));
command.fileName = stringUtilities.slugify(command.title);
focusService.focusById('title');
}
}
/* PRIVATE FUNCS */
function initData() {
vm.command = {};
}
function cancel() {
redirectToList();
}
function redirectToList() {
$location.path('');
}
}]);
angular.module('cms.documents').controller('DocumentDetailsController', [
'$routeParams',
'$q',
'$location',
'_',
'shared.LoadState',
'shared.modalDialogService',
'shared.permissionValidationService',
'shared.urlLibrary',
'documents.documentService',
'documents.modulePath',
function (
$routeParams,
$q, $location,
_,
LoadState,
modalDialogService,
permissionValidationService,
urlLibrary,
documentService,
modulePath) {
var vm = this;
init();
/* INIT */
function init() {
// UI actions
vm.edit = edit;
vm.save = save;
vm.cancel = reset;
vm.remove = remove;
// Properties
vm.editMode = false;
vm.globalLoadState = new LoadState();
vm.saveLoadState = new LoadState();
vm.formLoadState = new LoadState(true);
vm.canUpdate = permissionValidationService.canUpdate('COFDOC');
vm.canDelete = permissionValidationService.canDelete('COFDOC');
// Init
initData(vm.formLoadState);
}
/* UI ACTIONS */
function edit() {
vm.editMode = true;
vm.mainForm.formStatus.clear();
}
function save() {
setLoadingOn(vm.saveLoadState);
documentService
.update(vm.command)
.then(onSuccess.bind(null, 'Changes were saved successfully', vm.saveLoadState))
.finally(setLoadingOff.bind(null, vm.saveLoadState));
}
function reset() {
vm.editMode = false;
vm.previewDocument = _.clone(vm.document);
vm.command = mapCommand(vm.document);
vm.previewUrl = urlLibrary.getDocumentUrl(vm.previewDocument);
vm.mainForm.formStatus.clear();
}
function remove() {
var options = {
title: 'Delete Document',
message: 'Are you sure you want to delete this document?',
okButtonTitle: 'Yes, delete it',
onOk: onOk
};
modalDialogService.confirm(options);
function onOk() {
setLoadingOn();
return documentService
.remove(vm.document.documentAssetId)
.then(redirectToList)
.catch(setLoadingOff);
}
}
/* PRIVATE FUNCS */
function onSuccess(message, loadStateToTurnOff) {
return initData(loadStateToTurnOff)
.then(vm.mainForm.formStatus.success.bind(null, message));
}
function initData(loadStateToTurnOff) {
return getDocument()
.then(setLoadingOff.bind(null, loadStateToTurnOff));
/* helpers */
function getDocument() {
return documentService.getById($routeParams.id).then(function (document) {
vm.document = document;
vm.previewDocument = document;
vm.command = mapCommand(document);
vm.previewUrl = urlLibrary.getDocumentUrl(document);
vm.editMode = false;
});
}
}
function mapCommand(document) {
return _.pick(document,
'documentAssetId',
'title',
'fileName',
'description',
'tags');
}
function redirectToList() {
$location.path('');
}
function setLoadingOn(loadState) {
vm.globalLoadState.on();
if (loadState && _.isFunction(loadState.on)) loadState.on();
}
function setLoadingOff(loadState) {
vm.globalLoadState.off();
if (loadState && _.isFunction(loadState.off)) loadState.off();
}
}]);
angular.module('cms.documents').controller('DocumentListController', [
'_',
'shared.LoadState',
'shared.SearchQuery',
'shared.urlLibrary',
'shared.permissionValidationService',
'documents.documentService',
function (
_,
LoadState,
SearchQuery,
urlLibrary,
permissionValidationService,
documentService) {
/* START */
var vm = this;
init();
/* INIT */
function init() {
vm.gridLoadState = new LoadState();
vm.query = new SearchQuery({
onChanged: onQueryChanged
});
vm.filter = vm.query.getFilters();
vm.toggleFilter = toggleFilter;
vm.getDocumentUrl = urlLibrary.getDocumentUrl;
vm.canCreate = permissionValidationService.canCreate('COFDOC');
vm.canUpdate = permissionValidationService.canUpdate('COFDOC');
toggleFilter(false);
loadGrid();
}
/* ACTIONS */
function toggleFilter(show) {
vm.isFilterVisible = _.isUndefined(show) ? !vm.isFilterVisible : show;
}
/* EVENTS */
function onQueryChanged() {
toggleFilter(false);
loadGrid();
}
/* HELPERS */
function loadGrid() {
vm.gridLoadState.on();
return documentService.getAll(vm.query.getParameters()).then(function (result) {
vm.result = result;
vm.gridLoadState.off();
});
}
}]);
|
const function504 = function (t, e, i) {
"use strict";
var n = this && this.__extends || function () {
var t = Object.setPrototypeOf || {
__proto__: []
}
instanceof Array && function (t, e) {
t.__proto__ = e
} || function (t, e) {
for (var i in e) e.hasOwnProperty(i) && (t[i] = e[i])
};
return function (e, i) {
function n() {
this.constructor = e
}
t(e, i), e.prototype = null === i ? Object.create(i) : (n.prototype = i.prototype, new n)
}
}();
Object.defineProperty(e, "__esModule", {
value: !0
});
var o = function () {
function t(t) {
this._a = t
}
return Object.defineProperty(t.prototype, "state", {
get: function () {
return null != this._a && this._a.length > 0 ? this._a[0] : 0
},
enumerable: !0,
configurable: !0
}), Object.defineProperty(t.prototype, "expedition_id", {
get: function () {
return null != this._a && this._a.length > 1 ? this._a[1] : -1
},
enumerable: !0,
configurable: !0
}), Object.defineProperty(t.prototype, "complete_unixtime", {
get: function () {
return null != this._a && this._a.length > 2 ? this._a[2] : -1
},
enumerable: !0,
configurable: !0
}), t
}();
e.DeckExpeditionModel = o;
var r = function (t) {
function e(e) {
return t.call(this, e) || this
}
return n(e, t), e.prototype.__update__ = function (t) {
this._a = t
}, e.prototype.__update_state__ = function (t) {
for (null == this._a && (this._a = []); this._a.length <= 0;) this._a.push(0);
this._a[0] = t
}, e.prototype.__update_id__ = function (t) {
for (null == this._a && (this._a = []); this._a.length <= 1;) this._a.push(0);
this._a[1] = t
}, e.prototype.__update_time__ = function (t) {
for (null == this._a && (this._a = []); this._a.length <= 2;) this._a.push(0);
this._a[2] = t
}, e
}(o);
e.DeckExpeditionModelEdit = r
}
|
from ..open_oas.builder.builder import OasBuilder
from unittest import TestCase
from ..tests.schemas.schemas import (
ErrorSchema,
GistSchema,
gistObj1,
)
from ..open_oas.decorators import Deferred, component_response
class TestComponentResponse(TestCase):
def run_tests(self, builder: OasBuilder):
klass_qualname = "flask_open_oas.tests.schemas.schemas.GistSchema"
obj_qualname = "flask_open_oas.tests.schemas.schemas.gistObj1"
error_qualname = "flask_open_oas.tests.schemas.schemas.ErrorSchema"
data = builder.get_data()
responses = data.get("components", {}).get("responses", {})
_map = {
"404": "Error",
"ok_response": "Gist",
"ok2_response": "Gist1",
}
for k in responses.keys():
self.assertEqual(
responses[k]["content"]["application/json"]["schema"]["$ref"],
f"#/components/schemas/{_map[k]}",
)
schemas = data.get("components", {}).get("schemas", {})
self.assertEqual(
schemas.get("Error", {}).get("x-schema"), error_qualname
)
self.assertEqual(schemas.get("Gist", {}).get("x-schema"), obj_qualname)
self.assertEqual(
schemas.get("Gist1", {}).get("x-schema"), klass_qualname
)
def test_data(self):
data = {
"components": {
"responses": {
"ok_response": {
"content": {
"application/json": {"schema": gistObj1},
},
"description": "",
},
"ok2_response": {
"content": {
"application/json": {"schema": GistSchema},
},
"description": "",
},
"404": {
"content": {
"application/json": {"schema": ErrorSchema},
},
"description": "",
},
},
},
}
builder = OasBuilder(data)
self.run_tests(builder)
def test_data_dict_schema(self):
data = {
"components": {
"responses": {
"ok_response": {
"content": {
"application/json": {
"schema": {"type": "object"},
},
},
"description": "",
},
"ok2_response": {
"content": {
"application/json": {
"schema": {"type": "object"},
},
},
"description": "",
},
"404": {
"content": {
"application/json": {
"schema": {"type": "object"},
},
},
"description": "",
},
},
},
}
builder = OasBuilder(data)
self.assertEqual(
builder.get_data().get("components"), data.get("components")
)
# pprint.pprint(builder.get_data())
# self.run_tests(builder)
def test_decorator(self):
component_response("ok_response", "application/json", gistObj1)
component_response("ok2_response", "application/json", GistSchema)
component_response("404", "application/json", ErrorSchema)
builder = OasBuilder()
self.run_tests(builder)
def tearDown(self) -> None:
Deferred._deferred = []
return super().tearDown()
|
/**
* Cherry framework script inits
*/
(function($){
"use strict";
CHERRY_API.utilites.namespace('tools.popup');
CHERRY_API.utilites.namespace('tools.slider');
CHERRY_API.utilites.namespace('tools.stickup');
CHERRY_API.utilites.namespace('tools.navigation');
// Init magnific popup
CHERRY_API.tools.popup = {
init: function( target ) {
var self = this;
if ( CHERRY_API.status.document_ready ) {
self.render( target );
} else {
CHERRY_API.variable.$document.on('ready', self.render( target ) );
}
},
render: function( target ) {
if ( ! $.isFunction( jQuery.fn.magnificPopup ) ) {
return;
}
// Init single image popup
$('.popup-img').each(function( index, el ) {
var _this = $(this),
zoom_init = _this.data( 'init' );
if ( null == zoom_init || undefined == zoom_init ) {
zoom_init = new Object();
zoom_init.type = "image";
}
_this.magnificPopup( zoom_init );
});
// Init gallery images popup
$('.popup-gallery').each(function(index, el) {
var _this = $(this),
gall_init = _this.data( 'popup-init' );
_this.magnificPopup( gall_init );
});
// init single lightboxes
if ( 1 == cherry_data.use_lightbox && 0 <= $('.single-popup-image').length ) {
$('.single-popup-image').magnificPopup({type:'image'});
}
if ( 1 == cherry_data.use_lightbox && 0 <= $('.single-popup-video').length ) {
$('.single-popup-video').magnificPopup({type:'iframe'});
}
}
}
// Init slick gallery
CHERRY_API.tools.slider = {
init: function( target ) {
var self = this;
if ( CHERRY_API.status.document_ready ) {
self.render( target );
} else {
CHERRY_API.variable.$document.on('ready', self.render( target ) );
}
},
render: function( target ) {
if ( $.isFunction( jQuery.fn.slick ) ) {
$('.post-gallery').each(function(index, el) {
var _this = $(this),
slick_init = _this.data( 'init' );
slick_init.customPaging = function( slider, i ) {
return slick_init.dotsFormat;
}
_this.slick(slick_init);
});
}
}
}
// Init slick gallery
CHERRY_API.tools.stickup = {
init: function( target ) {
var self = this;
if ( CHERRY_API.status.document_ready ) {
self.render( target );
} else {
CHERRY_API.variable.$document.on('ready', self.render( target ) );
}
},
render: function( target ) {
// Init slick gallery if Cherry Stick Up plugin exists in namespace
if ( $.isFunction( jQuery.fn.CherryStickUp ) ) {
$( sticky_data.selector ).CherryStickUp( sticky_data.args );
}
}
}
CHERRY_API.tools.navigation = {
init: function( target ) {
var self = this;
if ( CHERRY_API.status.document_ready ) {
self.render( target );
} else {
CHERRY_API.variable.$document.on('ready', self.render( target ) );
}
},
render: function( target ) {
var container, button, menu, links, subMenus;
var self = this;
container = document.getElementById( 'menu-primary' );
if ( ! container ) {
return;
}
button = container.getElementsByTagName( 'button' )[0];
if ( 'undefined' === typeof button ) {
return;
}
menu = container.getElementsByTagName( 'ul' )[0];
// Hide menu toggle button if menu is empty and return early.
if ( 'undefined' === typeof menu ) {
button.style.display = 'none';
return;
}
menu.setAttribute( 'aria-expanded', 'false' );
if ( -1 === menu.className.indexOf( 'nav-menu' ) ) {
menu.className += ' nav-menu';
}
button.onclick = function() {
if ( -1 !== container.className.indexOf( 'toggled' ) ) {
container.className = container.className.replace( ' toggled', '' );
button.setAttribute( 'aria-expanded', 'false' );
menu.setAttribute( 'aria-expanded', 'false' );
} else {
container.className += ' toggled';
button.setAttribute( 'aria-expanded', 'true' );
menu.setAttribute( 'aria-expanded', 'true' );
}
};
// Get all the link elements within the menu.
links = menu.getElementsByTagName( 'a' );
subMenus = menu.getElementsByTagName( 'ul' );
// Set menu items with submenus to aria-haspopup="true".
for ( var i = 0, len = subMenus.length; i < len; i++ ) {
subMenus[i].parentNode.setAttribute( 'aria-haspopup', 'true' );
}
// Each time a menu link is focused or blurred, toggle focus.
for ( i = 0, len = links.length; i < len; i++ ) {
links[i].addEventListener( 'focus', self.toggle_focus, true );
links[i].addEventListener( 'blur', self.toggle_focus, true );
}
self.double_tap_to_go( $( 'li', $(menu) ) );
// Add duration before menu closing
$( 'li', $(menu) ).hover(
function() {
self.show_sub( $(this) );
},
function() {
self.hide_sub( $(this) );
}
);
},
show_sub: function( item ) {
item.addClass('menu-hover');
},
hide_sub: function( item ) {
var duration_timeout;
clearTimeout( duration_timeout );
duration_timeout = setTimeout(
function() {
item.removeClass('menu-hover');
},
400
);
},
double_tap_to_go: function( item ) {
if( !( 'ontouchstart' in window ) &&
!navigator.msMaxTouchPoints &&
!navigator.userAgent.toLowerCase().match( /windows phone os 7/i ) ) return false;
item.each( function() {
var curItem = false;
$( this ).on( 'click', function( e ) {
var item = $( this );
if( item[ 0 ] != curItem[ 0 ] ) {
e.preventDefault();
curItem = item;
}
});
$( document ).on( 'click touchstart MSPointerDown', function( e ) {
var resetItem = true,
parents = $( e.target ).parents();
for( var i = 0; i < parents.length; i++ )
if( parents[ i ] == curItem[ 0 ] )
resetItem = false;
if( resetItem )
curItem = false;
});
});
},
toggle_focus: function() {
var self = this;
// Move up through the ancestors of the current link until we hit .nav-menu.
while ( -1 === self.className.indexOf( 'nav-menu' ) ) {
// On li elements toggle the class .focus.
if ( 'li' === self.tagName.toLowerCase() ) {
if ( -1 !== self.className.indexOf( 'focus' ) ) {
self.className = self.className.replace( ' focus', '' );
} else {
self.className += ' focus';
}
}
self = self.parentElement;
}
}
}
$(function(){
CHERRY_API.tools.popup.init();
CHERRY_API.tools.slider.init();
CHERRY_API.tools.stickup.init();
CHERRY_API.tools.navigation.init();
});
})(jQuery);
|
# -*- coding: utf-8 -*-
# SPDX-License-Identifier: BSD-2-Clause
"""Custom docutils writer for ReStructuredText.
"""
from __future__ import (print_function, unicode_literals, absolute_import)
import os
import sys
import re
import textwrap
import logging
from docutils import nodes, writers
from sphinx import addnodes
from sphinx.locale import admonitionlabels, versionlabels, _
from sphinx.writers.text import TextTranslator, MAXWIDTH, STDINDENT
class RstWriter(writers.Writer):
supported = ('text',)
settings_spec = ('No options here.', '', ())
settings_defaults = {}
output = None
def __init__(self, builder):
writers.Writer.__init__(self)
self.builder = builder
def translate(self):
visitor = RstTranslator(self.document, self.builder)
self.document.walkabout(visitor)
self.output = visitor.body
class RstTranslator(TextTranslator):
sectionchars = '*=-~"+`'
def __init__(self, document, builder):
TextTranslator.__init__(self, document, builder)
newlines = builder.config.text_newlines
if newlines == 'windows':
self.nl = '\r\n'
elif newlines == 'native':
self.nl = os.linesep
else:
self.nl = '\n'
self.sectionchars = builder.config.text_sectionchars
self.states = [[]]
self.stateindent = [0]
self.list_counter = []
self.sectionlevel = 0
self.table = None
if self.builder.config.rst_indent:
self.indent = self.builder.config.rst_indent
else:
self.indent = STDINDENT
self.wrapper = textwrap.TextWrapper(width=STDINDENT, break_long_words=False, break_on_hyphens=False)
def log_unknown(self, type, node):
logger = logging.getLogger("sphinxcontrib.writers.rst")
if len(logger.handlers) == 0:
# Logging is not yet configured. Configure it.
logging.basicConfig(level=logging.INFO, stream=sys.stderr, format='%(levelname)-8s %(message)s')
logger = logging.getLogger("sphinxcontrib.writers.rst")
logger.warning("%s(%s) unsupported formatting" % (type, node))
def wrap(self, text, width=STDINDENT):
self.wrapper.width = width
return self.wrapper.wrap(text)
def add_text(self, text):
self.states[-1].append((-1, text))
def new_state(self, indent=STDINDENT):
self.states.append([])
self.stateindent.append(indent)
def end_state(self, wrap=False, end=[''], first=None):
content = self.states.pop()
maxindent = sum(self.stateindent)
indent = self.stateindent.pop()
result = []
toformat = []
def do_format():
if not toformat:
return
if wrap:
res = self.wrap(''.join(toformat), width=MAXWIDTH-maxindent)
else:
res = ''.join(toformat).splitlines()
if end:
res += end
result.append((indent, res))
for itemindent, item in content:
if itemindent == -1:
toformat.append(item)
else:
do_format()
result.append((indent + itemindent, item))
toformat = []
do_format()
if first is not None and result:
itemindent, item = result[0]
if item:
result.insert(0, (itemindent - indent, [first + item[0]]))
result[1] = (itemindent, item[1:])
self.states[-1].extend(result)
def visit_document(self, node):
self.new_state(0)
def depart_document(self, node):
self.end_state()
self.body = self.nl.join(line and (' '*indent + line)
for indent, lines in self.states[0]
for line in lines)
# TODO: add header/footer?
def visit_highlightlang(self, node):
raise nodes.SkipNode
def visit_section(self, node):
self._title_char = self.sectionchars[self.sectionlevel]
self.sectionlevel += 1
def depart_section(self, node):
self.sectionlevel -= 1
def visit_topic(self, node):
self.new_state(0)
def depart_topic(self, node):
self.end_state()
visit_sidebar = visit_topic
depart_sidebar = depart_topic
def visit_rubric(self, node):
self.new_state(0)
self.add_text('-[ ')
def depart_rubric(self, node):
self.add_text(' ]-')
self.end_state()
def visit_compound(self, node):
# self.log_unknown("compount", node)
pass
def depart_compound(self, node):
pass
def visit_glossary(self, node):
# self.log_unknown("glossary", node)
pass
def depart_glossary(self, node):
pass
def visit_title(self, node):
if isinstance(node.parent, nodes.Admonition):
self.add_text(node.astext()+': ')
raise nodes.SkipNode
self.new_state(0)
def depart_title(self, node):
if isinstance(node.parent, nodes.section):
char = self._title_char
else:
char = '^'
text = ''.join(x[1] for x in self.states.pop() if x[0] == -1)
self.stateindent.pop()
self.states[-1].append((0, ['', text, '%s' % (char * len(text)), '']))
def visit_subtitle(self, node):
# self.log_unknown("subtitle", node)
pass
def depart_subtitle(self, node):
pass
def visit_attribution(self, node):
self.add_text('-- ')
def depart_attribution(self, node):
pass
def visit_desc(self, node):
self.new_state(0)
def depart_desc(self, node):
self.end_state()
def visit_desc_signature(self, node):
if node.parent['objtype'] in ('class', 'exception', 'method', 'function'):
self.add_text('**')
else:
self.add_text('``')
def depart_desc_signature(self, node):
if node.parent['objtype'] in ('class', 'exception', 'method', 'function'):
self.add_text('**')
else:
self.add_text('``')
def visit_desc_name(self, node):
self.add_text(node.rawsource)
raise nodes.SkipNode
def depart_desc_name(self, node):
pass
def visit_desc_addname(self, node):
# self.log_unknown("desc_addname", node)
pass
def depart_desc_addname(self, node):
pass
def visit_desc_type(self, node):
# self.log_unknown("desc_type", node)
pass
def depart_desc_type(self, node):
pass
def visit_desc_returns(self, node):
self.add_text(' -> ')
def depart_desc_returns(self, node):
pass
def visit_desc_parameterlist(self, node):
self.add_text('(')
self.first_param = 1
def depart_desc_parameterlist(self, node):
self.add_text(')')
def visit_desc_parameter(self, node):
if not self.first_param:
self.add_text(', ')
else:
self.first_param = 0
self.add_text(node.astext())
raise nodes.SkipNode
def visit_desc_optional(self, node):
self.add_text('[')
def depart_desc_optional(self, node):
self.add_text(']')
def visit_desc_annotation(self, node):
content = node.astext()
if len(content) > MAXWIDTH:
h = int(MAXWIDTH/3)
content = content[:h] + " ... " + content[-h:]
self.add_text(content)
raise nodes.SkipNode
def depart_desc_annotation(self, node):
pass
def visit_refcount(self, node):
pass
def depart_refcount(self, node):
pass
def visit_desc_content(self, node):
self.new_state(self.indent)
def depart_desc_content(self, node):
self.end_state()
def visit_figure(self, node):
self.new_state(self.indent)
def depart_figure(self, node):
self.end_state()
def visit_caption(self, node):
# self.log_unknown("caption", node)
pass
def depart_caption(self, node):
pass
def visit_productionlist(self, node):
self.new_state(self.indent)
names = []
for production in node:
names.append(production['tokenname'])
maxlen = max(len(name) for name in names)
for production in node:
if production['tokenname']:
self.add_text(production['tokenname'].ljust(maxlen) + ' ::=')
lastname = production['tokenname']
else:
self.add_text('%s ' % (' '*len(lastname)))
self.add_text(production.astext() + self.nl)
self.end_state(wrap=False)
raise nodes.SkipNode
def visit_seealso(self, node):
self.new_state(self.indent)
def depart_seealso(self, node):
self.end_state(first='')
def visit_footnote(self, node):
self._footnote = node.children[0].astext().strip()
self.new_state(len(self._footnote) + self.indent)
def depart_footnote(self, node):
self.end_state(first='[%s] ' % self._footnote)
def visit_citation(self, node):
if len(node) and isinstance(node[0], nodes.label):
self._citlabel = node[0].astext()
else:
self._citlabel = ''
self.new_state(len(self._citlabel) + self.indent)
def depart_citation(self, node):
self.end_state(first='[%s] ' % self._citlabel)
def visit_label(self, node):
raise nodes.SkipNode
# TODO: option list could use some better styling
def visit_option_list(self, node):
# self.log_unknown("option_list", node)
pass
def depart_option_list(self, node):
pass
def visit_option_list_item(self, node):
self.new_state(0)
def depart_option_list_item(self, node):
self.end_state()
def visit_option_group(self, node):
self._firstoption = True
def depart_option_group(self, node):
self.add_text(' ')
def visit_option(self, node):
if self._firstoption:
self._firstoption = False
else:
self.add_text(', ')
def depart_option(self, node):
pass
def visit_option_string(self, node):
# self.log_unknown("option_string", node)
pass
def depart_option_string(self, node):
pass
def visit_option_argument(self, node):
self.add_text(node['delimiter'])
def depart_option_argument(self, node):
pass
def visit_description(self, node):
# self.log_unknown("description", node)
pass
def depart_description(self, node):
pass
def visit_tabular_col_spec(self, node):
raise nodes.SkipNode
def visit_colspec(self, node):
self.table[0].append(node['colwidth'])
raise nodes.SkipNode
def visit_tgroup(self, node):
# self.log_unknown("tgroup", node)
pass
def depart_tgroup(self, node):
pass
def visit_thead(self, node):
# self.log_unknown("thead", node)
pass
def depart_thead(self, node):
pass
def visit_tbody(self, node):
self.table.append('sep')
def depart_tbody(self, node):
pass
def visit_row(self, node):
self.table.append([])
def depart_row(self, node):
pass
def visit_entry(self, node):
if 'morerows' in node or 'morecols' in node:
raise NotImplementedError('Column or row spanning cells are '
'not implemented.')
self.new_state(0)
def depart_entry(self, node):
text = self.nl.join(self.nl.join(x[1]) for x in self.states.pop())
self.stateindent.pop()
self.table[-1].append(text)
def visit_table(self, node):
if self.table:
raise NotImplementedError('Nested tables are not supported.')
self.new_state(0)
self.table = [[]]
def depart_table(self, node):
lines = self.table[1:]
fmted_rows = []
colwidths = self.table[0]
realwidths = colwidths[:]
separator = 0
# don't allow paragraphs in table cells for now
for line in lines:
if line == 'sep':
separator = len(fmted_rows)
else:
cells = []
for i, cell in enumerate(line):
par = self.wrap(cell, width=colwidths[i])
if par:
maxwidth = max(list(map(len, par)))
else:
maxwidth = 0
realwidths[i] = max(realwidths[i], maxwidth)
cells.append(par)
fmted_rows.append(cells)
def writesep(char='-'):
out = ['+']
for width in realwidths:
out.append(char * (width+2))
out.append('+')
self.add_text(''.join(out) + self.nl)
def writerow(row):
lines = list(zip(*row))
for line in lines:
out = ['|']
for i, cell in enumerate(line):
if cell:
out.append(' ' + cell.ljust(realwidths[i]+1))
else:
out.append(' ' * (realwidths[i] + 2))
out.append('|')
self.add_text(''.join(out) + self.nl)
for i, row in enumerate(fmted_rows):
if separator and i == separator:
writesep('=')
else:
writesep('-')
writerow(row)
writesep('-')
self.table = None
self.end_state(wrap=False)
def visit_acks(self, node):
self.new_state(0)
self.add_text(', '.join(n.astext() for n in node.children[0].children)
+ '.')
self.end_state()
raise nodes.SkipNode
def visit_image(self, node):
if 'alt' in node.attributes:
self.add_text(_('[image: %s]') % node['alt'])
self.add_text(_('[image]'))
raise nodes.SkipNode
def visit_transition(self, node):
indent = sum(self.stateindent)
self.new_state(0)
self.add_text('=' * (MAXWIDTH - indent))
self.end_state()
raise nodes.SkipNode
def visit_bullet_list(self, node):
self.list_counter.append(-1)
def depart_bullet_list(self, node):
self.list_counter.pop()
def visit_enumerated_list(self, node):
self.list_counter.append(0)
def depart_enumerated_list(self, node):
self.list_counter.pop()
def visit_definition_list(self, node):
self.list_counter.append(-2)
def depart_definition_list(self, node):
self.list_counter.pop()
def visit_list_item(self, node):
if self.list_counter[-1] == -1:
# bullet list
self.new_state(indent=2)
elif self.list_counter[-1] == -2:
# definition list
pass
else:
# enumerated list
self.list_counter[-1] += 1
self.new_state(len(str(self.list_counter[-1])) + self.indent)
def depart_list_item(self, node):
if self.list_counter[-1] == -1:
self.end_state(first='* ', end=None)
elif self.list_counter[-1] == -2:
pass
else:
self.end_state(first='%s. ' % self.list_counter[-1], end=None)
def visit_definition_list_item(self, node):
self._li_has_classifier = len(node) >= 2 and \
isinstance(node[1], nodes.classifier)
def depart_definition_list_item(self, node):
pass
def visit_term(self, node):
self.new_state(0)
def depart_term(self, node):
if not self._li_has_classifier:
self.end_state(end=None)
def visit_termsep(self, node):
self.add_text(', ')
raise nodes.SkipNode
def visit_classifier(self, node):
self.add_text(' : ')
def depart_classifier(self, node):
self.end_state(end=None)
def visit_definition(self, node):
self.new_state(self.indent)
def depart_definition(self, node):
self.end_state()
def visit_field_list(self, node):
# self.log_unknown("field_list", node)
pass
def depart_field_list(self, node):
pass
def visit_field(self, node):
self.new_state(0)
def depart_field(self, node):
self.end_state(end=None)
def visit_field_name(self, node):
self.add_text(':')
def depart_field_name(self, node):
self.add_text(':')
content = node.astext()
self.add_text((16-len(content))*' ')
def visit_field_body(self, node):
self.new_state(self.indent)
def depart_field_body(self, node):
self.end_state()
def visit_centered(self, node):
pass
def depart_centered(self, node):
pass
def visit_hlist(self, node):
# self.log_unknown("hlist", node)
pass
def depart_hlist(self, node):
pass
def visit_hlistcol(self, node):
# self.log_unknown("hlistcol", node)
pass
def depart_hlistcol(self, node):
pass
def visit_admonition(self, node):
self.new_state(0)
def depart_admonition(self, node):
self.end_state()
def _visit_admonition(self, node):
self.new_state(self.indent)
def _make_depart_admonition(name):
def depart_admonition(self, node):
self.end_state(first=admonitionlabels[name] + ': ')
return depart_admonition
visit_attention = _visit_admonition
depart_attention = _make_depart_admonition('attention')
visit_caution = _visit_admonition
depart_caution = _make_depart_admonition('caution')
visit_danger = _visit_admonition
depart_danger = _make_depart_admonition('danger')
visit_error = _visit_admonition
depart_error = _make_depart_admonition('error')
visit_hint = _visit_admonition
depart_hint = _make_depart_admonition('hint')
visit_important = _visit_admonition
depart_important = _make_depart_admonition('important')
visit_note = _visit_admonition
depart_note = _make_depart_admonition('note')
visit_tip = _visit_admonition
depart_tip = _make_depart_admonition('tip')
visit_warning = _visit_admonition
depart_warning = _make_depart_admonition('warning')
def visit_versionmodified(self, node):
self.new_state(0)
if node.children:
self.add_text(versionlabels[node['type']] % node['version'] + ': ')
else:
self.add_text(versionlabels[node['type']] % node['version'] + '.')
def depart_versionmodified(self, node):
self.end_state()
def visit_literal_block(self, node):
if node.rawsource != node.astext():
# most probably a parsed-literal block -- don't highlight
return super().visit_literal_block(node)
lang = node.get('language', 'default')
linenos = node.get('linenos', False)
if lang == 'default':
self.add_text("::")
else:
self.add_text(".. code-block:: {}\n".format(lang))
if node.get('linenos', False):
self.add_text(" :linenos:")
self.new_state(self.indent)
def depart_literal_block(self, node):
self.end_state(wrap=False)
def visit_doctest_block(self, node):
self.new_state(0)
def depart_doctest_block(self, node):
self.end_state(wrap=False)
def visit_line_block(self, node):
self.new_state(0)
def depart_line_block(self, node):
self.end_state(wrap=False)
def visit_line(self, node):
# self.log_unknown("line", node)
pass
def depart_line(self, node):
pass
def visit_block_quote(self, node):
self.add_text('..')
self.new_state(self.indent)
def depart_block_quote(self, node):
self.end_state()
def visit_compact_paragraph(self, node):
pass
def depart_compact_paragraph(self, node):
pass
def visit_paragraph(self, node):
if not isinstance(node.parent, nodes.Admonition) or \
isinstance(node.parent, addnodes.seealso):
self.new_state(0)
def depart_paragraph(self, node):
if not isinstance(node.parent, nodes.Admonition) or \
isinstance(node.parent, addnodes.seealso):
self.end_state()
def visit_target(self, node):
if 'refid' in node:
self.new_state(0)
self.add_text('.. _'+node['refid']+':'+self.nl)
def depart_target(self, node):
if 'refid' in node:
self.end_state(wrap=False)
def visit_index(self, node):
raise nodes.SkipNode
def visit_substitution_definition(self, node):
raise nodes.SkipNode
def visit_pending_xref(self, node):
pass
def depart_pending_xref(self, node):
pass
def visit_reference(self, node):
"""Run upon entering a reference
Because this class inherits from the TextTranslator class,
regularly defined links, such as::
`Some Text`_
.. _Some Text: http://www.some_url.com
were being written as plaintext. This included internal
references defined in the standard rst way, such as::
`Some Reference`
.. _Some Reference:
Some Title
----------
To resolve this, if ``refuri`` is not included in the node (an
internal, non-Sphinx-defined internal uri, the reference is
left unchanged (e.g. ```Some Text`_`` is written as such).
If ``internal`` is not in the node (as for an external,
non-Sphinx URI, the reference is rewritten as an inline link,
e.g. ```Some Text <http://www.some_url.com>`_``.
If ``reftitle` is in the node (as in a Sphinx-generated
reference), the node is converted to an inline link.
Finally, all other links are also converted to an inline link
format.
"""
if 'refuri' not in node:
if 'name' in node:
self.add_text('`%s`_' % node['name'])
elif 'refid' in node:
# We do not produce the necessary link targets to
# produce a link here.
return
else:
raise NotImplementedError
raise nodes.SkipNode
elif 'internal' not in node:
if 'name' in node:
self.add_text('`%s <%s>`_' % (node['name'], node['refuri']))
else:
self.add_text('`%s <%s>`_' % (node['refuri'], node['refuri']))
raise nodes.SkipNode
elif 'reftitle' in node:
# Include node as text, rather than with markup.
# reST seems unable to parse a construct like ` ``literal`` <url>`_
# Hence we revert to the more simple `literal <url>`_
self.add_text('`%s <%s>`_' % (node.astext(), node['refuri']))
# self.end_state(wrap=False)
raise nodes.SkipNode
else:
self.add_text('`%s <%s>`_' % (node.astext(), node['refuri']))
raise nodes.SkipNode
def depart_reference(self, node):
if 'refuri' not in node:
pass # Don't add these anchors
elif 'internal' not in node:
pass # Don't add external links (they are automatically added by the reST spec)
elif 'reftitle' in node:
pass
def visit_download_reference(self, node):
self.log_unknown("download_reference", node)
pass
def depart_download_reference(self, node):
pass
def visit_emphasis(self, node):
self.add_text('*')
def depart_emphasis(self, node):
self.add_text('*')
def visit_literal_emphasis(self, node):
self.add_text('*')
def depart_literal_emphasis(self, node):
self.add_text('*')
def visit_strong(self, node):
self.add_text('**')
def depart_strong(self, node):
self.add_text('**')
def visit_abbreviation(self, node):
self.add_text('')
def depart_abbreviation(self, node):
if node.hasattr('explanation'):
self.add_text(' (%s)' % node['explanation'])
def visit_title_reference(self, node):
# self.log_unknown("title_reference", node)
self.add_text('*')
def depart_title_reference(self, node):
self.add_text('*')
def visit_literal(self, node):
self.add_text('``')
def depart_literal(self, node):
self.add_text('``')
def visit_subscript(self, node):
self.add_text('_')
def depart_subscript(self, node):
pass
def visit_superscript(self, node):
self.add_text('^')
def depart_superscript(self, node):
pass
def visit_footnote_reference(self, node):
self.add_text('[%s]' % node.astext())
raise nodes.SkipNode
def visit_citation_reference(self, node):
self.add_text('[%s]' % node.astext())
raise nodes.SkipNode
def visit_Text(self, node):
self.add_text(node.astext())
def depart_Text(self, node):
pass
def visit_generated(self, node):
# self.log_unknown("generated", node)
pass
def depart_generated(self, node):
pass
def visit_inline(self, node):
# self.log_unknown("inline", node)
pass
def depart_inline(self, node):
pass
def visit_problematic(self, node):
self.add_text('>>')
def depart_problematic(self, node):
self.add_text('<<')
def visit_system_message(self, node):
self.new_state(0)
self.add_text('<SYSTEM MESSAGE: %s>' % node.astext())
self.end_state()
raise nodes.SkipNode
def visit_comment(self, node):
raise nodes.SkipNode
def visit_meta(self, node):
# only valid for HTML
raise nodes.SkipNode
def visit_raw(self, node):
if 'text' in node.get('format', '').split():
self.body.append(node.astext())
raise nodes.SkipNode
def unknown_visit(self, node):
raise NotImplementedError('Unknown node: ' + node.__class__.__name__)
|
def particion(arr, low, high):
i = (low-1)
pivot = arr[high]
for j in range(low, high):
if arr[j] <= pivot:
i = i+1
arr[i], arr[j] = arr[j], arr[i]
arr[i+1], arr[high] = arr[high], arr[i+1]
return (i+1)
def quicksort(arr, low, high):
if low < high:
pi = particion(arr, low, high)
quicksort(arr, low, pi-1)
quicksort(arr, pi+1, high)
arr = [1992, 1990, 10, 5, 6, 100, 0, 1, -10]
n = len(arr)
quicksort(arr, 0, n-1)
print("El array ordenado: ")
for i in range(n):
print("%d" %arr[i]),
|
/**
* secsy-webclient
*
* Copyright (c) 2016 Reto Inderbitzin <mail@indr.ch>
*
* For the full copyright and licence information, please view
* the LICENSE file that was distributed with this source code.
*/
import Ember from 'ember';
export default Ember.Controller.extend({
session: Ember.inject.service(),
canPullUpdates: Ember.computed('session.data.authenticated.sync_enabled', function () {
return this.get('session').get('data.authenticated.sync_enabled');
})
});
|
import React from 'react';
import { mount } from 'enzyme';
import { cloneDeep, set } from 'lodash';
import { BenefitsLines } from '../../../forms/output/BenefitsLines';
import { CLIENT_DEFAULTS } from '../../../utils/CLIENT_DEFAULTS';
// Skipping till highcharts testing is worked out
describe.skip('<BenefitsLines>', () => {
let activePrograms;
let client;
let defaultProps;
const buildGraph = () => {
return mount(<BenefitsLines { ...defaultProps } />);
};
beforeEach(() => {
activePrograms = [];
client = cloneDeep(CLIENT_DEFAULTS);
defaultProps = {
activePrograms: activePrograms,
client: client,
timescale: 'Monthly',
className: 'some-class',
};
});
it('renders message when no benefits selected', () => {
const graph = buildGraph();
expect(graph.children).toHaveLength(1);
expect(graph.childAt(0).is('Message')).toBe(true);
});
it('renders with snap and current earned less than future earned', () => {
activePrograms.push('snap');
set(client, 'current.earned', 100);
set(client, 'future.earned', 200);
expect(buildGraph()).toMatchSnapshot();
});
it('renders with snap and current earned greater than future earned', () => {
activePrograms.push('snap');
set(client, 'current.earned', 200);
set(client, 'future.earned', 100);
expect(buildGraph()).toMatchSnapshot();
});
it('renders with section8', () => {
activePrograms.push('section8');
set(client, 'current.earned', 100);
set(client, 'future.earned', 200);
expect(buildGraph()).toMatchSnapshot();
});
it('renders with both snap and section8', () => {
activePrograms.push('snap');
activePrograms.push('section8');
set(client, 'current.earned', 100);
set(client, 'future.earned', 200);
expect(buildGraph()).toMatchSnapshot();
});
});
|
/*!
* devextreme-angular
* Version: 19.1.6
* Build date: Tue Oct 22 2019
*
* Copyright (c) 2012 - 2019 Developer Express Inc. ALL RIGHTS RESERVED
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file in the root of the project for details.
*
* https://github.com/DevExpress/devextreme-angular
*/
import * as tslib_1 from "tslib";
/* tslint:disable:max-line-length */
import { BrowserTransferStateModule } from '@angular/platform-browser';
import { TransferState } from '@angular/platform-browser';
import { Component, NgModule, ElementRef, NgZone, PLATFORM_ID, Inject, Input, Output, OnDestroy, EventEmitter, OnChanges, DoCheck, SimpleChanges, ContentChildren, QueryList } from '@angular/core';
import DxPieChart from 'devextreme/viz/pie_chart';
import { DxComponent, DxTemplateHost, DxIntegrationModule, DxTemplateModule, NestedOptionHost, IterableDifferHelper, WatcherHelper } from 'devextreme-angular/core';
import { DxoAdaptiveLayoutModule } from 'devextreme-angular/ui/nested';
import { DxoAnimationModule } from 'devextreme-angular/ui/nested';
import { DxoCommonSeriesSettingsModule } from 'devextreme-angular/ui/nested';
import { DxoBorderModule } from 'devextreme-angular/ui/nested';
import { DxoHoverStyleModule } from 'devextreme-angular/ui/nested';
import { DxoHatchingModule } from 'devextreme-angular/ui/nested';
import { DxoLabelModule } from 'devextreme-angular/ui/nested';
import { DxoArgumentFormatModule } from 'devextreme-angular/ui/nested';
import { DxoConnectorModule } from 'devextreme-angular/ui/nested';
import { DxoFontModule } from 'devextreme-angular/ui/nested';
import { DxoFormatModule } from 'devextreme-angular/ui/nested';
import { DxoSelectionStyleModule } from 'devextreme-angular/ui/nested';
import { DxoSmallValuesGroupingModule } from 'devextreme-angular/ui/nested';
import { DxoExportModule } from 'devextreme-angular/ui/nested';
import { DxoLegendModule } from 'devextreme-angular/ui/nested';
import { DxoMarginModule } from 'devextreme-angular/ui/nested';
import { DxoTitleModule } from 'devextreme-angular/ui/nested';
import { DxoSubtitleModule } from 'devextreme-angular/ui/nested';
import { DxoLoadingIndicatorModule } from 'devextreme-angular/ui/nested';
import { DxiSeriesModule } from 'devextreme-angular/ui/nested';
import { DxoSeriesTemplateModule } from 'devextreme-angular/ui/nested';
import { DxoSizeModule } from 'devextreme-angular/ui/nested';
import { DxoTooltipModule } from 'devextreme-angular/ui/nested';
import { DxoShadowModule } from 'devextreme-angular/ui/nested';
import { DxiSeriesComponent } from 'devextreme-angular/ui/nested';
/**
* The PieChart is a widget that visualizes data as a circle divided into sectors that each represents a portion of the whole.
*/
var DxPieChartComponent = /** @class */ (function (_super) {
tslib_1.__extends(DxPieChartComponent, _super);
function DxPieChartComponent(elementRef, ngZone, templateHost, _watcherHelper, _idh, optionHost, transferState, platformId) {
var _this = _super.call(this, elementRef, ngZone, templateHost, _watcherHelper, transferState, platformId) || this;
_this._watcherHelper = _watcherHelper;
_this._idh = _idh;
_this._createEventEmitters([
{ subscribe: 'disposing', emit: 'onDisposing' },
{ subscribe: 'done', emit: 'onDone' },
{ subscribe: 'drawn', emit: 'onDrawn' },
{ subscribe: 'exported', emit: 'onExported' },
{ subscribe: 'exporting', emit: 'onExporting' },
{ subscribe: 'fileSaving', emit: 'onFileSaving' },
{ subscribe: 'incidentOccurred', emit: 'onIncidentOccurred' },
{ subscribe: 'initialized', emit: 'onInitialized' },
{ subscribe: 'legendClick', emit: 'onLegendClick' },
{ subscribe: 'optionChanged', emit: 'onOptionChanged' },
{ subscribe: 'pointClick', emit: 'onPointClick' },
{ subscribe: 'pointHoverChanged', emit: 'onPointHoverChanged' },
{ subscribe: 'pointSelectionChanged', emit: 'onPointSelectionChanged' },
{ subscribe: 'tooltipHidden', emit: 'onTooltipHidden' },
{ subscribe: 'tooltipShown', emit: 'onTooltipShown' },
{ emit: 'adaptiveLayoutChange' },
{ emit: 'animationChange' },
{ emit: 'commonSeriesSettingsChange' },
{ emit: 'customizeLabelChange' },
{ emit: 'customizePointChange' },
{ emit: 'dataSourceChange' },
{ emit: 'diameterChange' },
{ emit: 'disabledChange' },
{ emit: 'elementAttrChange' },
{ emit: 'exportChange' },
{ emit: 'innerRadiusChange' },
{ emit: 'legendChange' },
{ emit: 'loadingIndicatorChange' },
{ emit: 'marginChange' },
{ emit: 'minDiameterChange' },
{ emit: 'paletteChange' },
{ emit: 'paletteExtensionModeChange' },
{ emit: 'pathModifiedChange' },
{ emit: 'pointSelectionModeChange' },
{ emit: 'redrawOnResizeChange' },
{ emit: 'resolveLabelOverlappingChange' },
{ emit: 'rtlEnabledChange' },
{ emit: 'segmentsDirectionChange' },
{ emit: 'seriesChange' },
{ emit: 'seriesTemplateChange' },
{ emit: 'sizeChange' },
{ emit: 'sizeGroupChange' },
{ emit: 'startAngleChange' },
{ emit: 'themeChange' },
{ emit: 'titleChange' },
{ emit: 'tooltipChange' },
{ emit: 'typeChange' }
]);
_this._idh.setHost(_this);
optionHost.setHost(_this);
return _this;
}
Object.defineProperty(DxPieChartComponent.prototype, "adaptiveLayout", {
/**
* Specifies adaptive layout options.
*/
get: function () {
return this._getOption('adaptiveLayout');
},
set: function (value) {
this._setOption('adaptiveLayout', value);
},
enumerable: true,
configurable: true
});
Object.defineProperty(DxPieChartComponent.prototype, "animation", {
/**
* Specifies animation options.
*/
get: function () {
return this._getOption('animation');
},
set: function (value) {
this._setOption('animation', value);
},
enumerable: true,
configurable: true
});
Object.defineProperty(DxPieChartComponent.prototype, "commonSeriesSettings", {
/**
* An object defining the configuration options that are common for all series of the PieChart widget.
*/
get: function () {
return this._getOption('commonSeriesSettings');
},
set: function (value) {
this._setOption('commonSeriesSettings', value);
},
enumerable: true,
configurable: true
});
Object.defineProperty(DxPieChartComponent.prototype, "customizeLabel", {
/**
* Customizes the appearance of an individual point label.
*/
get: function () {
return this._getOption('customizeLabel');
},
set: function (value) {
this._setOption('customizeLabel', value);
},
enumerable: true,
configurable: true
});
Object.defineProperty(DxPieChartComponent.prototype, "customizePoint", {
/**
* Customizes the appearance of an individual series point.
*/
get: function () {
return this._getOption('customizePoint');
},
set: function (value) {
this._setOption('customizePoint', value);
},
enumerable: true,
configurable: true
});
Object.defineProperty(DxPieChartComponent.prototype, "dataSource", {
/**
* Binds the widget to data.
*/
get: function () {
return this._getOption('dataSource');
},
set: function (value) {
this._setOption('dataSource', value);
},
enumerable: true,
configurable: true
});
Object.defineProperty(DxPieChartComponent.prototype, "diameter", {
/**
* Specifies the diameter of the pie.
*/
get: function () {
return this._getOption('diameter');
},
set: function (value) {
this._setOption('diameter', value);
},
enumerable: true,
configurable: true
});
Object.defineProperty(DxPieChartComponent.prototype, "disabled", {
/**
* Specifies whether the widget responds to the user interaction.
*/
get: function () {
return this._getOption('disabled');
},
set: function (value) {
this._setOption('disabled', value);
},
enumerable: true,
configurable: true
});
Object.defineProperty(DxPieChartComponent.prototype, "elementAttr", {
/**
* Specifies the attributes to be attached to the widget's root element.
*/
get: function () {
return this._getOption('elementAttr');
},
set: function (value) {
this._setOption('elementAttr', value);
},
enumerable: true,
configurable: true
});
Object.defineProperty(DxPieChartComponent.prototype, "export", {
/**
* Configures the exporting and printing features.
*/
get: function () {
return this._getOption('export');
},
set: function (value) {
this._setOption('export', value);
},
enumerable: true,
configurable: true
});
Object.defineProperty(DxPieChartComponent.prototype, "innerRadius", {
/**
* Specifies the fraction of the inner radius relative to the total radius in the series of the 'doughnut' type. The value should be between 0 and 1.
*/
get: function () {
return this._getOption('innerRadius');
},
set: function (value) {
this._setOption('innerRadius', value);
},
enumerable: true,
configurable: true
});
Object.defineProperty(DxPieChartComponent.prototype, "legend", {
/**
* Specifies PieChart legend options.
*/
get: function () {
return this._getOption('legend');
},
set: function (value) {
this._setOption('legend', value);
},
enumerable: true,
configurable: true
});
Object.defineProperty(DxPieChartComponent.prototype, "loadingIndicator", {
/**
* Configures the loading indicator.
*/
get: function () {
return this._getOption('loadingIndicator');
},
set: function (value) {
this._setOption('loadingIndicator', value);
},
enumerable: true,
configurable: true
});
Object.defineProperty(DxPieChartComponent.prototype, "margin", {
/**
* Generates space around the widget.
*/
get: function () {
return this._getOption('margin');
},
set: function (value) {
this._setOption('margin', value);
},
enumerable: true,
configurable: true
});
Object.defineProperty(DxPieChartComponent.prototype, "minDiameter", {
/**
* Specifies the minimum diameter of the pie.
*/
get: function () {
return this._getOption('minDiameter');
},
set: function (value) {
this._setOption('minDiameter', value);
},
enumerable: true,
configurable: true
});
Object.defineProperty(DxPieChartComponent.prototype, "palette", {
/**
* Sets the palette to be used to colorize series and their elements.
*/
get: function () {
return this._getOption('palette');
},
set: function (value) {
this._setOption('palette', value);
},
enumerable: true,
configurable: true
});
Object.defineProperty(DxPieChartComponent.prototype, "paletteExtensionMode", {
/**
* Specifies what to do with colors in the palette when their number is less than the number of series (in the Chart widget) or points in a series (in the PieChart widget).
*/
get: function () {
return this._getOption('paletteExtensionMode');
},
set: function (value) {
this._setOption('paletteExtensionMode', value);
},
enumerable: true,
configurable: true
});
Object.defineProperty(DxPieChartComponent.prototype, "pathModified", {
/**
* Notifies the widget that it is embedded into an HTML page that uses a tag modifying the path.
*/
get: function () {
return this._getOption('pathModified');
},
set: function (value) {
this._setOption('pathModified', value);
},
enumerable: true,
configurable: true
});
Object.defineProperty(DxPieChartComponent.prototype, "pointSelectionMode", {
/**
* Specifies whether a single point or multiple points can be selected in the chart.
*/
get: function () {
return this._getOption('pointSelectionMode');
},
set: function (value) {
this._setOption('pointSelectionMode', value);
},
enumerable: true,
configurable: true
});
Object.defineProperty(DxPieChartComponent.prototype, "redrawOnResize", {
/**
* Specifies whether to redraw the widget when the size of the parent browser window changes or a mobile device rotates.
*/
get: function () {
return this._getOption('redrawOnResize');
},
set: function (value) {
this._setOption('redrawOnResize', value);
},
enumerable: true,
configurable: true
});
Object.defineProperty(DxPieChartComponent.prototype, "resolveLabelOverlapping", {
/**
* Specifies how a chart must behave when point labels overlap.
*/
get: function () {
return this._getOption('resolveLabelOverlapping');
},
set: function (value) {
this._setOption('resolveLabelOverlapping', value);
},
enumerable: true,
configurable: true
});
Object.defineProperty(DxPieChartComponent.prototype, "rtlEnabled", {
/**
* Switches the widget to a right-to-left representation.
*/
get: function () {
return this._getOption('rtlEnabled');
},
set: function (value) {
this._setOption('rtlEnabled', value);
},
enumerable: true,
configurable: true
});
Object.defineProperty(DxPieChartComponent.prototype, "segmentsDirection", {
/**
* Specifies the direction that the pie chart segments will occupy.
*/
get: function () {
return this._getOption('segmentsDirection');
},
set: function (value) {
this._setOption('segmentsDirection', value);
},
enumerable: true,
configurable: true
});
Object.defineProperty(DxPieChartComponent.prototype, "series", {
/**
* Specifies options for the series of the PieChart widget.
*/
get: function () {
return this._getOption('series');
},
set: function (value) {
this._setOption('series', value);
},
enumerable: true,
configurable: true
});
Object.defineProperty(DxPieChartComponent.prototype, "seriesTemplate", {
/**
* Defines options for the series template.
*/
get: function () {
return this._getOption('seriesTemplate');
},
set: function (value) {
this._setOption('seriesTemplate', value);
},
enumerable: true,
configurable: true
});
Object.defineProperty(DxPieChartComponent.prototype, "size", {
/**
* Specifies the widget's size in pixels.
*/
get: function () {
return this._getOption('size');
},
set: function (value) {
this._setOption('size', value);
},
enumerable: true,
configurable: true
});
Object.defineProperty(DxPieChartComponent.prototype, "sizeGroup", {
/**
* Allows you to display several adjoining pies in the same size.
*/
get: function () {
return this._getOption('sizeGroup');
},
set: function (value) {
this._setOption('sizeGroup', value);
},
enumerable: true,
configurable: true
});
Object.defineProperty(DxPieChartComponent.prototype, "startAngle", {
/**
* Specifies the angle in arc degrees from which the first segment of a pie chart should start.
*/
get: function () {
return this._getOption('startAngle');
},
set: function (value) {
this._setOption('startAngle', value);
},
enumerable: true,
configurable: true
});
Object.defineProperty(DxPieChartComponent.prototype, "theme", {
/**
* Sets the name of the theme the widget uses.
*/
get: function () {
return this._getOption('theme');
},
set: function (value) {
this._setOption('theme', value);
},
enumerable: true,
configurable: true
});
Object.defineProperty(DxPieChartComponent.prototype, "title", {
/**
* Configures the widget's title.
*/
get: function () {
return this._getOption('title');
},
set: function (value) {
this._setOption('title', value);
},
enumerable: true,
configurable: true
});
Object.defineProperty(DxPieChartComponent.prototype, "tooltip", {
/**
* Configures tooltips.
*/
get: function () {
return this._getOption('tooltip');
},
set: function (value) {
this._setOption('tooltip', value);
},
enumerable: true,
configurable: true
});
Object.defineProperty(DxPieChartComponent.prototype, "type", {
/**
* Specifies the type of the pie chart series.
*/
get: function () {
return this._getOption('type');
},
set: function (value) {
this._setOption('type', value);
},
enumerable: true,
configurable: true
});
Object.defineProperty(DxPieChartComponent.prototype, "seriesChildren", {
get: function () {
return this._getOption('series');
},
set: function (value) {
this.setChildren('series', value);
},
enumerable: true,
configurable: true
});
DxPieChartComponent.prototype._createInstance = function (element, options) {
return new DxPieChart(element, options);
};
DxPieChartComponent.prototype.ngOnDestroy = function () {
this._destroyWidget();
};
DxPieChartComponent.prototype.ngOnChanges = function (changes) {
_super.prototype.ngOnChanges.call(this, changes);
this.setupChanges('dataSource', changes);
this.setupChanges('palette', changes);
this.setupChanges('series', changes);
};
DxPieChartComponent.prototype.setupChanges = function (prop, changes) {
if (!(prop in this._optionsToUpdate)) {
this._idh.setup(prop, changes);
}
};
DxPieChartComponent.prototype.ngDoCheck = function () {
this._idh.doCheck('dataSource');
this._idh.doCheck('palette');
this._idh.doCheck('series');
this._watcherHelper.checkWatchers();
_super.prototype.ngDoCheck.call(this);
_super.prototype.clearChangedOptions.call(this);
};
DxPieChartComponent.prototype._setOption = function (name, value) {
var isSetup = this._idh.setupSingle(name, value);
var isChanged = this._idh.getChanges(name, value) !== null;
if (isSetup || isChanged) {
_super.prototype._setOption.call(this, name, value);
}
};
DxPieChartComponent.ctorParameters = function () { return [
{ type: ElementRef },
{ type: NgZone },
{ type: DxTemplateHost },
{ type: WatcherHelper },
{ type: IterableDifferHelper },
{ type: NestedOptionHost },
{ type: TransferState },
{ type: undefined, decorators: [{ type: Inject, args: [PLATFORM_ID,] }] }
]; };
tslib_1.__decorate([
Input()
], DxPieChartComponent.prototype, "adaptiveLayout", null);
tslib_1.__decorate([
Input()
], DxPieChartComponent.prototype, "animation", null);
tslib_1.__decorate([
Input()
], DxPieChartComponent.prototype, "commonSeriesSettings", null);
tslib_1.__decorate([
Input()
], DxPieChartComponent.prototype, "customizeLabel", null);
tslib_1.__decorate([
Input()
], DxPieChartComponent.prototype, "customizePoint", null);
tslib_1.__decorate([
Input()
], DxPieChartComponent.prototype, "dataSource", null);
tslib_1.__decorate([
Input()
], DxPieChartComponent.prototype, "diameter", null);
tslib_1.__decorate([
Input()
], DxPieChartComponent.prototype, "disabled", null);
tslib_1.__decorate([
Input()
], DxPieChartComponent.prototype, "elementAttr", null);
tslib_1.__decorate([
Input()
], DxPieChartComponent.prototype, "export", null);
tslib_1.__decorate([
Input()
], DxPieChartComponent.prototype, "innerRadius", null);
tslib_1.__decorate([
Input()
], DxPieChartComponent.prototype, "legend", null);
tslib_1.__decorate([
Input()
], DxPieChartComponent.prototype, "loadingIndicator", null);
tslib_1.__decorate([
Input()
], DxPieChartComponent.prototype, "margin", null);
tslib_1.__decorate([
Input()
], DxPieChartComponent.prototype, "minDiameter", null);
tslib_1.__decorate([
Input()
], DxPieChartComponent.prototype, "palette", null);
tslib_1.__decorate([
Input()
], DxPieChartComponent.prototype, "paletteExtensionMode", null);
tslib_1.__decorate([
Input()
], DxPieChartComponent.prototype, "pathModified", null);
tslib_1.__decorate([
Input()
], DxPieChartComponent.prototype, "pointSelectionMode", null);
tslib_1.__decorate([
Input()
], DxPieChartComponent.prototype, "redrawOnResize", null);
tslib_1.__decorate([
Input()
], DxPieChartComponent.prototype, "resolveLabelOverlapping", null);
tslib_1.__decorate([
Input()
], DxPieChartComponent.prototype, "rtlEnabled", null);
tslib_1.__decorate([
Input()
], DxPieChartComponent.prototype, "segmentsDirection", null);
tslib_1.__decorate([
Input()
], DxPieChartComponent.prototype, "series", null);
tslib_1.__decorate([
Input()
], DxPieChartComponent.prototype, "seriesTemplate", null);
tslib_1.__decorate([
Input()
], DxPieChartComponent.prototype, "size", null);
tslib_1.__decorate([
Input()
], DxPieChartComponent.prototype, "sizeGroup", null);
tslib_1.__decorate([
Input()
], DxPieChartComponent.prototype, "startAngle", null);
tslib_1.__decorate([
Input()
], DxPieChartComponent.prototype, "theme", null);
tslib_1.__decorate([
Input()
], DxPieChartComponent.prototype, "title", null);
tslib_1.__decorate([
Input()
], DxPieChartComponent.prototype, "tooltip", null);
tslib_1.__decorate([
Input()
], DxPieChartComponent.prototype, "type", null);
tslib_1.__decorate([
Output()
], DxPieChartComponent.prototype, "onDisposing", void 0);
tslib_1.__decorate([
Output()
], DxPieChartComponent.prototype, "onDone", void 0);
tslib_1.__decorate([
Output()
], DxPieChartComponent.prototype, "onDrawn", void 0);
tslib_1.__decorate([
Output()
], DxPieChartComponent.prototype, "onExported", void 0);
tslib_1.__decorate([
Output()
], DxPieChartComponent.prototype, "onExporting", void 0);
tslib_1.__decorate([
Output()
], DxPieChartComponent.prototype, "onFileSaving", void 0);
tslib_1.__decorate([
Output()
], DxPieChartComponent.prototype, "onIncidentOccurred", void 0);
tslib_1.__decorate([
Output()
], DxPieChartComponent.prototype, "onInitialized", void 0);
tslib_1.__decorate([
Output()
], DxPieChartComponent.prototype, "onLegendClick", void 0);
tslib_1.__decorate([
Output()
], DxPieChartComponent.prototype, "onOptionChanged", void 0);
tslib_1.__decorate([
Output()
], DxPieChartComponent.prototype, "onPointClick", void 0);
tslib_1.__decorate([
Output()
], DxPieChartComponent.prototype, "onPointHoverChanged", void 0);
tslib_1.__decorate([
Output()
], DxPieChartComponent.prototype, "onPointSelectionChanged", void 0);
tslib_1.__decorate([
Output()
], DxPieChartComponent.prototype, "onTooltipHidden", void 0);
tslib_1.__decorate([
Output()
], DxPieChartComponent.prototype, "onTooltipShown", void 0);
tslib_1.__decorate([
Output()
], DxPieChartComponent.prototype, "adaptiveLayoutChange", void 0);
tslib_1.__decorate([
Output()
], DxPieChartComponent.prototype, "animationChange", void 0);
tslib_1.__decorate([
Output()
], DxPieChartComponent.prototype, "commonSeriesSettingsChange", void 0);
tslib_1.__decorate([
Output()
], DxPieChartComponent.prototype, "customizeLabelChange", void 0);
tslib_1.__decorate([
Output()
], DxPieChartComponent.prototype, "customizePointChange", void 0);
tslib_1.__decorate([
Output()
], DxPieChartComponent.prototype, "dataSourceChange", void 0);
tslib_1.__decorate([
Output()
], DxPieChartComponent.prototype, "diameterChange", void 0);
tslib_1.__decorate([
Output()
], DxPieChartComponent.prototype, "disabledChange", void 0);
tslib_1.__decorate([
Output()
], DxPieChartComponent.prototype, "elementAttrChange", void 0);
tslib_1.__decorate([
Output()
], DxPieChartComponent.prototype, "exportChange", void 0);
tslib_1.__decorate([
Output()
], DxPieChartComponent.prototype, "innerRadiusChange", void 0);
tslib_1.__decorate([
Output()
], DxPieChartComponent.prototype, "legendChange", void 0);
tslib_1.__decorate([
Output()
], DxPieChartComponent.prototype, "loadingIndicatorChange", void 0);
tslib_1.__decorate([
Output()
], DxPieChartComponent.prototype, "marginChange", void 0);
tslib_1.__decorate([
Output()
], DxPieChartComponent.prototype, "minDiameterChange", void 0);
tslib_1.__decorate([
Output()
], DxPieChartComponent.prototype, "paletteChange", void 0);
tslib_1.__decorate([
Output()
], DxPieChartComponent.prototype, "paletteExtensionModeChange", void 0);
tslib_1.__decorate([
Output()
], DxPieChartComponent.prototype, "pathModifiedChange", void 0);
tslib_1.__decorate([
Output()
], DxPieChartComponent.prototype, "pointSelectionModeChange", void 0);
tslib_1.__decorate([
Output()
], DxPieChartComponent.prototype, "redrawOnResizeChange", void 0);
tslib_1.__decorate([
Output()
], DxPieChartComponent.prototype, "resolveLabelOverlappingChange", void 0);
tslib_1.__decorate([
Output()
], DxPieChartComponent.prototype, "rtlEnabledChange", void 0);
tslib_1.__decorate([
Output()
], DxPieChartComponent.prototype, "segmentsDirectionChange", void 0);
tslib_1.__decorate([
Output()
], DxPieChartComponent.prototype, "seriesChange", void 0);
tslib_1.__decorate([
Output()
], DxPieChartComponent.prototype, "seriesTemplateChange", void 0);
tslib_1.__decorate([
Output()
], DxPieChartComponent.prototype, "sizeChange", void 0);
tslib_1.__decorate([
Output()
], DxPieChartComponent.prototype, "sizeGroupChange", void 0);
tslib_1.__decorate([
Output()
], DxPieChartComponent.prototype, "startAngleChange", void 0);
tslib_1.__decorate([
Output()
], DxPieChartComponent.prototype, "themeChange", void 0);
tslib_1.__decorate([
Output()
], DxPieChartComponent.prototype, "titleChange", void 0);
tslib_1.__decorate([
Output()
], DxPieChartComponent.prototype, "tooltipChange", void 0);
tslib_1.__decorate([
Output()
], DxPieChartComponent.prototype, "typeChange", void 0);
tslib_1.__decorate([
ContentChildren(DxiSeriesComponent)
], DxPieChartComponent.prototype, "seriesChildren", null);
DxPieChartComponent = tslib_1.__decorate([
Component({
selector: 'dx-pie-chart',
template: '',
providers: [
DxTemplateHost,
WatcherHelper,
NestedOptionHost,
IterableDifferHelper
],
styles: [' :host { display: block; }']
}),
tslib_1.__param(7, Inject(PLATFORM_ID))
], DxPieChartComponent);
return DxPieChartComponent;
}(DxComponent));
export { DxPieChartComponent };
var DxPieChartModule = /** @class */ (function () {
function DxPieChartModule() {
}
DxPieChartModule = tslib_1.__decorate([
NgModule({
imports: [
DxoAdaptiveLayoutModule,
DxoAnimationModule,
DxoCommonSeriesSettingsModule,
DxoBorderModule,
DxoHoverStyleModule,
DxoHatchingModule,
DxoLabelModule,
DxoArgumentFormatModule,
DxoConnectorModule,
DxoFontModule,
DxoFormatModule,
DxoSelectionStyleModule,
DxoSmallValuesGroupingModule,
DxoExportModule,
DxoLegendModule,
DxoMarginModule,
DxoTitleModule,
DxoSubtitleModule,
DxoLoadingIndicatorModule,
DxiSeriesModule,
DxoSeriesTemplateModule,
DxoSizeModule,
DxoTooltipModule,
DxoShadowModule,
DxIntegrationModule,
DxTemplateModule,
BrowserTransferStateModule
],
declarations: [
DxPieChartComponent
],
exports: [
DxPieChartComponent,
DxoAdaptiveLayoutModule,
DxoAnimationModule,
DxoCommonSeriesSettingsModule,
DxoBorderModule,
DxoHoverStyleModule,
DxoHatchingModule,
DxoLabelModule,
DxoArgumentFormatModule,
DxoConnectorModule,
DxoFontModule,
DxoFormatModule,
DxoSelectionStyleModule,
DxoSmallValuesGroupingModule,
DxoExportModule,
DxoLegendModule,
DxoMarginModule,
DxoTitleModule,
DxoSubtitleModule,
DxoLoadingIndicatorModule,
DxiSeriesModule,
DxoSeriesTemplateModule,
DxoSizeModule,
DxoTooltipModule,
DxoShadowModule,
DxTemplateModule
]
})
], DxPieChartModule);
return DxPieChartModule;
}());
export { DxPieChartModule };
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290Ijoibmc6Ly9kZXZleHRyZW1lLWFuZ3VsYXIvdWkvcGllLWNoYXJ0LyIsInN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ICBEeFRlbXBsYXRlTW9kdWxlXHJcbiAgXVxyXG59KVxyXG5leHBvcnQgY2xhc3MgRHhQaWVDaGFydE1vZHVsZSB7IH1cclxuIl19
|
/* @flow strict */
import styles from './styles.module.scss';
import * as React from 'react';
import { Link } from 'react-router-dom';
import { isNull } from '../../../lib/is';
import { UserDetails } from '../Details';
import { enforceString } from '../../../lib/enforce';
import { routes, ROUTE_PARAMS } from '../../../routes';
import { Icon, Card, Button } from '../../../controls';
import { useUser, useRouteParam } from '../../../lib/hooks';
type Props = {||};
export function UserRead(props: Props) {
const id = useRouteParam(ROUTE_PARAMS.USER_ID.name, enforceString);
const { user, loadUser, loadingError } = useUser();
React.useEffect(() => {
loadUser(id);
}, [id, loadUser]);
if (isNull(user)) {
return null;
}
return (
<Card className={styles.UserRead}>
<Card.Header title="User">
<Link to={routes.user.update.path(user.id)}>
<Button
theme={Button.themes.PRIMARY}
leftIcon={<Icon.icons.Edit width={16} />}
>
Update
</Button>
</Link>
</Card.Header>
<Card.Body>
<UserDetails user={user} error={loadingError} />
</Card.Body>
</Card>
);
}
|
/**
* config for scripts/bundle.js
*/
const path = require("path"),
fs = require("fs-extra"),
webpack = require("webpack"),
_ = require("lodash"),
VirtualModulePlugin = require("virtual-module-webpack-plugin");
const PKGS = {
LIFE_EVENTS: "@life-events",
SHARED: "@shared",
SENDER: "@sender",
UPLOADER: "@uploader",
SHARED_UI: "@shared-ui",
UPLOADY: "@uploady",
CHUNKED_UPLOADY: "@chunked-uploady",
};
let licenseContent;
module.exports = {
org: "@rpldy/",
library: "rpldy",
targets: {
umd: "umd",
},
bundles: {
umd: {
/**
* Bundle the core functionality (no UI)
*/
"core": {
pkgs: [PKGS.LIFE_EVENTS, PKGS.SHARED, PKGS.SENDER, PKGS.UPLOADER],
target: PKGS.UPLOADER,
maxSize: 12000,
dontUsePolyfills: true,
},
/**
* Bundle the core functionality + core UI
*/
"ui-core": {
pkgs: ["core", PKGS.SHARED_UI, PKGS.UPLOADY],
target: PKGS.UPLOADY,
config: {
externals: ["react", "react-dom"],
},
maxSize: 15000,
},
/**
* Bundle the core functionality + core UI + Chunked Uploady
*/
"ui-core-chunked": {
pkgs: ["ui-core", PKGS.CHUNKED_UPLOADY],
target: PKGS.CHUNKED_UPLOADY,
config: {
externals: ["react", "react-dom"],
},
maxSize: 17500,
},
/**
* Bundle the entire repo's functionality
*/
"all": {
pkgs: "*",
exclude: ["native-uploady"],
target: PKGS.UPLOADY,
config: (entries) => {
const exports = entries.map((entry) => {
const namespace = _.camelCase(entry.name.split("/")[1]);
return `import * as ${namespace} from "${entry.location}/src/index"; export { ${namespace} };`;
});
return {
output: {
library: "rpldy",
//["rpldy", "[name]"],
},
entry: "./packages/ui/uploady/all-bundle-entry.js",
plugins: [
new VirtualModulePlugin({
moduleName: "./packages/ui/uploady/all.generated.js",
contents: `
${exports.join(" \r\n")}
`,
})
],
externals: ["react", "react-dom"],
optimization: {
splitChunks: {
cacheGroups: {
commons: {
filename: "[name]-all-bundle.js",
}
}
}
},
};
},
maxSize: 25000,
},
//TODO: find a way to make this work with global object assignment (wepackages/tus-sender/src/tusSender/initTusUpload/createUpload.js:88:94bpack externals root)
//
// /**
// * Bundle a umd bundle per repo package, without internal dependencies
// */
// "package": {
// pkgs: "*",
// target: "*", //output relative to package
// bundlePattern: `*(-runtime)?(\.min)?\\.js`,
// extraBundles: ["polyfills-bundle.js"],
// config: (entries, isProduction) => {
// const entry = entries.reduce((res, pkg) => {
// res[pkg.name.split("/")[1]] = pkg.location;
// return res;
// }, {});
//
// return {
// entry,
// externals: ["react", "react-dom",
// (context, request, callback) => {
// return /@rpldy/.test(request) ? callback(null, {
// commonjs: request,
// commonjs2: request,
// amd: request,
// root: request,
// }) : callback();
// //[`commonjs ${request}`, `amd ${request}`]) : callback();
// }
// ],
// output: {
// library: ["rpldy", "[name]"],
// filename: `rpldy.[name]${isProduction ? ".min" : ""}.js`,
// },
// optimization: {
// runtimeChunk: {
// name: "package-runtime",
// }
// },
// };
// }
// },
},
},
webpackConfig: {
base: {
mode: "development",
devtool: "source-map",
resolve: {
mainFields: ["main:dev", "module", "main"],
},
optimization: {
splitChunks: {
cacheGroups: {
commons: {
test: /[\\/]node_modules[\\/]/,
name: "polyfills",
filename: "[name]-bundle.js",
chunks: "all"
}
}
}
},
module: {
rules: [
{
test: /\.?js$/,
exclude: /node_module/,
use: {
loader: "babel-loader",
options: {
presets: [["@babel/preset-env", {
useBuiltIns: false,
// corejs: 3,
}]],
plugins: [["@babel/plugin-transform-runtime", {
corejs: 3,
"version": "^7.12.10"
}]]
}
}
}
]
},
},
production: {
mode: "production",
devtool: "cheap-module-source-map",
optimization: {
//needed for production build to work with single/shared polyfills bundle
namedChunks: true,
//needed for production build to work with single/shared polyfills bundle
namedModules: true,
//use hashed ids for smaller bundles
moduleIds: "hashed",
},
plugins: [
new webpack.BannerPlugin({
banner: () => {
if (!licenseContent) {
licenseContent = fs.readFileSync(path.resolve(process.cwd(), "LICENSE.md"), { encoding: "utf-8" });
}
return licenseContent;
}
}),
],
}
},
};
|
'use strict';
require('./warnAboutDeprecatedCJSRequire.js')('LocationUtils');
module.exports = require('./index.js').LocationUtils;
|
#!/usr/bin/python
import sys
import Adafruit_DHT
import httplib, urllib
import subprocess
import re
import os
import time
import MySQLdb as mdb
import datetime
databaseUsername="dbusrname"
databasePassword="dbpw"
databaseName="dbname"
key = 'thingspeak key'
sensor=Adafruit_DHT.DHT11
pinNum=4
def save(humidity):
params = urllib.urlencode({'field': humidity, 'key': key})
headers = {"Content-typZZe": "application/x-www-form-urlencoded", "Accept": "text/plain"}
conn = httplib.HTTPConnection("api.thingspeak.com:80")
try:
conn.request("POST", "/update", params, headers)
response = conn.getresponse()
print response.status, response.reason
data = response.read()
conn.close()
except:
print "connection failed"
def saveToDatabase(temperature,humidity):
con=mdb.connect("localhost", databaseUsername, databasePassword, databaseName)
currentDate=datetime.datetime.now().date()
now=datetime.datetime.now()
ti=datetime.datetime.now().time()
with con:
cur=con.cursor()
cur.execute("INSERT INTO dht11 (temperatura,wilgotnosc,data,czas) VALUES (%s,%s,%s,%s)",(temperature,humidity,currentDate, ti))
print "Saved temperature"
return "true"
def readInfo():
humidity, temperature = Adafruit_DHT.read_retry(sensor, pinNum)
print "Temperature: %.1f C" % temperature
print "Humidity: %s %%" % humidity
if humidity is not None and temperature is not None:
return saveToDatabase(temperature,humidity),save(humidity)
else:
print 'nie udalo sie sprobuj ponownie!'
sys.exit(1)
#sprawdzenie czy tabela istnieje
try:
queryFile=file("createTable.sql","r")
con=mdb.connect("localhost", databaseUsername,databasePassword,databaseName)
currentDate=datetime.datetime.now().date()
with con:
line=queryFile.readline()
query=""
while(line!=""):
query+=line
line=queryFile.readline()
cur=con.cursor()
cur.execute(query)
queryFile.close()
os.rename("createTable.sql","createTable.sql.bkp")
except IOError:
pass #tabela stworzona
status=readInfo() #pomiary
|
var webAudioMediaStreamSources = [];
function convertToAudioStream(mediaStream) {
if (!mediaStream) throw 'MediaStream is mandatory.';
if (mediaStream.getVideoTracks && !mediaStream.getVideoTracks().length) {
return mediaStream;
}
var context = new AudioContext();
var mediaStreamSource = context.createMediaStreamSource(mediaStream);
var destination = context.createMediaStreamDestination();
mediaStreamSource.connect(destination);
webAudioMediaStreamSources.push(mediaStreamSource);
return destination.stream;
}
var isOpera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
var isFirefox = typeof window.InstallTrigger !== 'undefined';
var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;
var isChrome = !!window.chrome && !isOpera;
var isIE = !!document.documentMode;
var isPluginRTC = isSafari || isIE;
var isMobileDevice = !!navigator.userAgent.match(/Android|iPhone|iPad|iPod|BlackBerry|IEMobile/i);
// detect node-webkit
var isNodeWebkit = !!(window.process && (typeof window.process == 'object') && window.process.versions && window.process.versions['node-webkit']);
window.MediaStream = window.MediaStream || window.webkitMediaStream;
window.AudioContext = window.AudioContext || window.webkitAudioContext;
function getRandomString() {
// suggested by @rvulpescu from #154
if (window.crypto && crypto.getRandomValues && navigator.userAgent.indexOf('Safari') == -1) {
var a = window.crypto.getRandomValues(new Uint32Array(3)),
token = '';
for (var i = 0, l = a.length; i < l; i++) {
token += a[i].toString(36);
}
return token;
} else {
return (Math.random() * new Date().getTime()).toString(36).replace(/\./g, '');
}
}
var chromeVersion = 50;
var matchArray = navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./);
if (isChrome && matchArray && matchArray[2]) {
chromeVersion = parseInt(matchArray[2], 10);
}
var firefoxVersion = 50;
matchArray = navigator.userAgent.match(/Firefox\/(.*)/);
if (isFirefox && matchArray && matchArray[1]) {
firefoxVersion = parseInt(matchArray[1], 10);
}
function isData(session) {
return !session.audio && !session.video && !session.screen && session.data;
}
function isNull(obj) {
return typeof obj == 'undefined';
}
function isString(obj) {
return typeof obj == 'string';
}
function isEmpty(session) {
var length = 0;
for (var s in session) {
length++;
}
return length == 0;
}
// this method converts array-buffer into string
function ab2str(buf) {
var result = '';
try {
result = String.fromCharCode.apply(null, new Uint16Array(buf));
} catch (e) {}
return result;
}
// this method converts string into array-buffer
function str2ab(str) {
if (!isString(str)) str = JSON.stringify(str);
var buf = new ArrayBuffer(str.length * 2); // 2 bytes for each char
var bufView = new Uint16Array(buf);
for (var i = 0, strLen = str.length; i < strLen; i++) {
bufView[i] = str.charCodeAt(i);
}
return buf;
}
function swap(arr) {
var swapped = [],
length = arr.length;
for (var i = 0; i < length; i++)
if (arr[i] && arr[i] !== true)
swapped.push(arr[i]);
return swapped;
}
function forEach(obj, callback) {
for (var item in obj) {
callback(obj[item], item);
}
}
var console = window.console || {
log: function() {},
error: function() {},
warn: function() {}
};
function log() {
console.log(arguments);
}
function error() {
console.error(arguments);
}
function warn() {
console.warn(arguments);
}
if (isChrome || isFirefox || isSafari) {
var log = console.log.bind(console);
var error = console.error.bind(console);
var warn = console.warn.bind(console);
}
function toStr(obj) {
return JSON.stringify(obj, function(key, value) {
if (value && value.sdp) {
log(value.sdp.type, '\t', value.sdp.sdp);
return '';
} else return value;
}, '\t');
}
function getLength(obj) {
var length = 0;
for (var o in obj)
if (o) length++;
return length;
}
// Get HTMLAudioElement/HTMLVideoElement accordingly
function createMediaElement(stream, session) {
var mediaElement = document.createElement(stream.isAudio ? 'audio' : 'video');
mediaElement.id = stream.streamid;
if (isPluginRTC) {
var body = (document.body || document.documentElement);
body.insertBefore(mediaElement, body.firstChild);
setTimeout(function() {
Plugin.attachMediaStream(mediaElement, stream)
}, 1000);
return Plugin.attachMediaStream(mediaElement, stream);
}
// "mozSrcObject" is always preferred over "src"!!
mediaElement[isFirefox ? 'mozSrcObject' : 'src'] = isFirefox ? stream : (window.URL || window.webkitURL).createObjectURL(stream);
mediaElement.controls = true;
mediaElement.autoplay = !!session.remote;
mediaElement.muted = session.remote ? false : true;
// http://goo.gl/WZ5nFl
// Firefox don't yet support onended for any stream (remote/local)
isFirefox && mediaElement.addEventListener('ended', function() {
stream.onended();
}, false);
mediaElement.play();
return mediaElement;
}
var onStreamEndedHandlerFiredFor = {};
function onStreamEndedHandler(streamedObject, connection) {
if (streamedObject.mediaElement && !streamedObject.mediaElement.parentNode) return;
if (onStreamEndedHandlerFiredFor[streamedObject.streamid]) return;
onStreamEndedHandlerFiredFor[streamedObject.streamid] = streamedObject;
connection.onstreamended(streamedObject);
}
var onLeaveHandlerFiredFor = {};
function onLeaveHandler(event, connection) {
if (onLeaveHandlerFiredFor[event.userid]) return;
onLeaveHandlerFiredFor[event.userid] = event;
connection.onleave(event);
}
function takeSnapshot(args) {
var userid = args.userid;
var connection = args.connection;
function _takeSnapshot(video) {
var canvas = document.createElement('canvas');
canvas.width = video.videoWidth || video.clientWidth;
canvas.height = video.videoHeight || video.clientHeight;
var context = canvas.getContext('2d');
context.drawImage(video, 0, 0, canvas.width, canvas.height);
connection.snapshots[userid] = canvas.toDataURL('image/png');
args.callback && args.callback(connection.snapshots[userid]);
}
if (args.mediaElement) return _takeSnapshot(args.mediaElement);
for (var stream in connection.streams) {
stream = connection.streams[stream];
if (stream.userid == userid && stream.stream && stream.stream.getVideoTracks && stream.stream.getVideoTracks().length) {
_takeSnapshot(stream.mediaElement);
continue;
}
}
}
function invokeMediaCaptured(connection) {
// to let user know that media resource has been captured
// now, he can share "sessionDescription" using sockets
if (connection.onMediaCaptured) {
connection.onMediaCaptured();
delete connection.onMediaCaptured;
}
}
function merge(mergein, mergeto) {
if (!mergein) mergein = {};
if (!mergeto) return mergein;
for (var item in mergeto) {
mergein[item] = mergeto[item];
}
return mergein;
}
function loadScript(src, onload) {
var script = document.createElement('script');
script.src = src;
script.onload = function() {
log('loaded resource:', src);
if (onload) onload();
};
document.documentElement.appendChild(script);
}
function capturePartOfScreen(args) {
var connection = args.connection;
var element = args.element;
if (!window.html2canvas) {
return loadScript(connection.resources.html2canvas, function() {
capturePartOfScreen(args);
});
}
if (isString(element)) {
element = document.querySelector(element);
if (!element) element = document.getElementById(element);
}
if (!element) throw 'HTML DOM Element is not accessible!';
// todo: store DOM element somewhere to minimize DOM querying issues
// html2canvas.js is used to take screenshots
html2canvas(element, {
onrendered: function(canvas) {
args.callback(canvas.toDataURL());
}
});
}
function initFileBufferReader(connection, callback) {
if (!window.FileBufferReader) {
loadScript(connection.resources.FileBufferReader, function() {
initFileBufferReader(connection, callback);
});
return;
}
function _private(chunk) {
chunk.userid = chunk.extra.userid;
return chunk;
}
var fileBufferReader = new FileBufferReader();
fileBufferReader.onProgress = function(chunk) {
connection.onFileProgress(_private(chunk), chunk.uuid);
};
fileBufferReader.onBegin = function(file) {
connection.onFileStart(_private(file));
};
fileBufferReader.onEnd = function(file) {
connection.onFileEnd(_private(file));
};
callback(fileBufferReader);
}
var screenFrame, loadedScreenFrame;
function loadScreenFrame(skip) {
if (DetectRTC.screen.extensionid != ReservedExtensionID) {
return;
}
if (loadedScreenFrame) return;
if (!skip) return loadScreenFrame(true);
loadedScreenFrame = true;
var iframe = document.createElement('iframe');
iframe.onload = function() {
iframe.isLoaded = true;
log('Screen Capturing frame is loaded.');
};
iframe.src = 'https://www.webrtc-experiment.com/getSourceId/';
iframe.style.display = 'none';
(document.body || document.documentElement).appendChild(iframe);
screenFrame = {
postMessage: function() {
if (!iframe.isLoaded) {
setTimeout(screenFrame.postMessage, 100);
return;
}
iframe.contentWindow.postMessage({
captureSourceId: true
}, '*');
}
};
}
function muteOrUnmute(e) {
var stream = e.stream,
root = e.root,
session = e.session || {},
enabled = e.enabled;
if (!session.audio && !session.video) {
if (!isString(session)) {
session = merge(session, {
audio: true,
video: true
});
} else {
session = {
audio: true,
video: true
};
}
}
// implementation from #68
if (session.type) {
if (session.type == 'remote' && root.type != 'remote') return;
if (session.type == 'local' && root.type != 'local') return;
}
log(enabled ? 'Muting' : 'UnMuting', 'session', toStr(session));
// enable/disable audio/video tracks
if (root.type == 'local' && session.audio && !!stream.getAudioTracks) {
var audioTracks = stream.getAudioTracks()[0];
if (audioTracks)
audioTracks.enabled = !enabled;
}
if (root.type == 'local' && (session.video || session.screen) && !!stream.getVideoTracks) {
var videoTracks = stream.getVideoTracks()[0];
if (videoTracks)
videoTracks.enabled = !enabled;
}
root.sockets.forEach(function(socket) {
if (root.type == 'local') {
socket.send({
streamid: root.streamid,
mute: !!enabled,
unmute: !enabled,
session: session
});
}
if (root.type == 'remote') {
socket.send({
promptMuteUnmute: true,
streamid: root.streamid,
mute: !!enabled,
unmute: !enabled,
session: session
});
}
});
if (root.type == 'remote') return;
// According to issue #135, onmute/onumute must be fired for self
// "fakeObject" is used because we need to keep session for renegotiated streams;
// and MUST pass exact session over onStreamEndedHandler/onmute/onhold/etc. events.
var fakeObject = merge({}, root);
fakeObject.session = session;
fakeObject.isAudio = !!fakeObject.session.audio && !fakeObject.session.video;
fakeObject.isVideo = !!fakeObject.session.video;
fakeObject.isScreen = !!fakeObject.session.screen;
if (!!enabled) {
// if muted stream is negotiated
stream.preMuted = {
audio: stream.getAudioTracks().length && !stream.getAudioTracks()[0].enabled,
video: stream.getVideoTracks().length && !stream.getVideoTracks()[0].enabled
};
root.rtcMultiConnection.onmute(fakeObject);
}
if (!enabled) {
stream.preMuted = {};
root.rtcMultiConnection.onunmute(fakeObject);
}
}
var Firefox_Screen_Capturing_Warning = 'Make sure that you are using Firefox Nightly and you enabled: media.getusermedia.screensharing.enabled flag from about:config page. You also need to add your domain in "media.getusermedia.screensharing.allowed_domains" flag. If you are using WinXP then also enable "media.getusermedia.screensharing.allow_on_old_platforms" flag. NEVER forget to use "only" HTTPs for screen capturing!';
var SCREEN_COMMON_FAILURE = 'HTTPs i.e. SSL-based URI is mandatory to use screen capturing.';
var ReservedExtensionID = 'ajhifddimkapgcifgcodmmfdlknahffk';
// if application-developer deployed his own extension on Google App Store
var useCustomChromeExtensionForScreenCapturing = document.domain.indexOf('webrtc-experiment.com') != -1;
function initHark(args) {
if (!window.hark) {
loadScript(args.connection.resources.hark, function() {
initHark(args);
});
return;
}
var connection = args.connection;
var streamedObject = args.streamedObject;
var stream = args.stream;
var options = {};
var speechEvents = hark(stream, options);
speechEvents.on('speaking', function() {
if (connection.onspeaking) {
connection.onspeaking(streamedObject);
}
});
speechEvents.on('stopped_speaking', function() {
if (connection.onsilence) {
connection.onsilence(streamedObject);
}
});
speechEvents.on('volume_change', function(volume, threshold) {
if (connection.onvolumechange) {
connection.onvolumechange(merge({
volume: volume,
threshold: threshold
}, streamedObject));
}
});
}
attachEventListener = function(video, type, listener, useCapture) {
video.addEventListener(type, listener, useCapture);
};
var Plugin = window.PluginRTC || {};
window.onPluginRTCInitialized = function(pluginRTCObject) {
Plugin = pluginRTCObject;
MediaStreamTrack = Plugin.MediaStreamTrack;
RTCPeerConnection = Plugin.RTCPeerConnection;
RTCIceCandidate = Plugin.RTCIceCandidate;
RTCSessionDescription = Plugin.RTCSessionDescription;
log(isPluginRTC ? 'Java-Applet' : 'ActiveX', 'plugin has been loaded.');
};
if (!isEmpty(Plugin)) window.onPluginRTCInitialized(Plugin);
// if IE or Safari
if (isPluginRTC) {
loadScript('https://cdn.webrtc-experiment.com/Plugin.EveryWhere.js');
// loadScript('https://cdn.webrtc-experiment.com/Plugin.Temasys.js');
}
var MediaStream = window.MediaStream;
if (typeof MediaStream === 'undefined' && typeof webkitMediaStream !== 'undefined') {
MediaStream = webkitMediaStream;
}
/*global MediaStream:true */
if (typeof MediaStream !== 'undefined' && !('stop' in MediaStream.prototype)) {
MediaStream.prototype.stop = function() {
this.getAudioTracks().forEach(function(track) {
track.stop();
});
this.getVideoTracks().forEach(function(track) {
track.stop();
});
};
}
|
#!/usr/bin/env python
#
# Electrum - lightweight Bitcoin client
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import platform
import sys
import traceback
from PyQt5.QtCore import QObject
import PyQt5.QtCore as QtCore
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import *
from electrum_dash.i18n import _
from electrum_dash.base_crash_reporter import BaseCrashReporter
from .util import MessageBoxMixin
class Exception_Window(BaseCrashReporter, QWidget, MessageBoxMixin):
_active_window = None
def __init__(self, main_window, exctype, value, tb):
BaseCrashReporter.__init__(self, exctype, value, tb)
self.main_window = main_window
QWidget.__init__(self)
self.setWindowTitle('Dash Electrum - ' + _('An Error Occurred'))
self.setMinimumSize(600, 300)
main_box = QVBoxLayout()
heading = QLabel('<h2>' + BaseCrashReporter.CRASH_TITLE + '</h2>')
main_box.addWidget(heading)
main_box.addWidget(QLabel(BaseCrashReporter.CRASH_MESSAGE))
main_box.addWidget(QLabel(BaseCrashReporter.REQUEST_HELP_MESSAGE))
collapse_info = QPushButton(_("Show report contents"))
collapse_info.clicked.connect(
lambda: self.msg_box(QMessageBox.NoIcon,
self, _("Report contents"), self.get_report_string()))
main_box.addWidget(collapse_info)
main_box.addWidget(QLabel(BaseCrashReporter.DESCRIBE_ERROR_MESSAGE))
self.description_textfield = QTextEdit()
self.description_textfield.setFixedHeight(50)
main_box.addWidget(self.description_textfield)
main_box.addWidget(QLabel(BaseCrashReporter.ASK_CONFIRM_SEND))
buttons = QHBoxLayout()
report_button = QPushButton(_('Send Bug Report'))
report_button.clicked.connect(self.send_report)
report_button.setIcon(QIcon(":icons/tab_send.png"))
buttons.addWidget(report_button)
never_button = QPushButton(_('Never'))
never_button.clicked.connect(self.show_never)
buttons.addWidget(never_button)
close_button = QPushButton(_('Not Now'))
close_button.clicked.connect(self.close)
buttons.addWidget(close_button)
main_box.addLayout(buttons)
self.setLayout(main_box)
self.show()
def send_report(self):
try:
response = BaseCrashReporter.send_report(self)
except BaseException as e:
traceback.print_exc(file=sys.stderr)
self.main_window.show_critical(_('There was a problem with the automatic reporting:') + '\n' +
str(e) + '\n' +
_("Please report this issue manually."))
return
QMessageBox.about(self, _("Crash report"), response.text)
self.close()
def on_close(self):
Exception_Window._active_window = None
sys.__excepthook__(*self.exc_args)
self.close()
def show_never(self):
self.main_window._auto_crash_reports.setChecked(False)
self.main_window.auto_crash_reports(False)
self.close()
def closeEvent(self, event):
self.on_close()
event.accept()
def get_user_description(self):
return self.description_textfield.toPlainText()
def get_wallet_type(self):
return self.main_window.wallet.wallet_type
def get_os_version(self):
return platform.platform()
def _show_window(*args):
if not Exception_Window._active_window:
Exception_Window._active_window = Exception_Window(*args)
class Exception_Hook(QObject):
_report_exception = QtCore.pyqtSignal(object, object, object, object)
def __init__(self, main_window, *args, **kwargs):
super(Exception_Hook, self).__init__(*args, **kwargs)
if not main_window.config.get(BaseCrashReporter.config_key, default=False):
if main_window._old_excepthook:
sys.excepthook = main_window._old_excepthook
return
self.main_window = main_window
main_window._old_excepthook = sys.excepthook
sys.excepthook = self.handler
self._report_exception.connect(_show_window)
def handler(self, *args):
self._report_exception.emit(self.main_window, *args)
|
/* global describe it before */
var expect = require('chai').expect
var net = require('net')
var EventEmitter = require('events').EventEmitter
/* this is a private module, so load directly */
var MessageSocket = require('../lib/jet/message-socket').MessageSocket
var jet = require('../lib/jet')
var http = require('http')
var https = require('https')
var fs = require('fs')
var commandRequestTest = function (port, command, params, checkResult) {
describe('who sends "' + command + '" as request', function () {
var sender
before(function () {
sender = new MessageSocket(port)
sender.sendMessage = function (message) {
sender.send(JSON.stringify(message))
}
})
var id = Math.random()
var request = {
id: id,
method: command,
params: params
}
it('sends back the correct result', function (done) {
sender.once('message', function (response) {
response = JSON.parse(response)
expect(response.id).to.equal(request.id)
if (checkResult) {
checkResult(response.result, response.error)
} else {
expect(response.result).to.be.true
expect(response).to.not.have.property('error')
}
done()
})
sender.sendMessage(request)
})
})
}
var testPort = 33301
describe('A Daemon', function () {
var daemon
before(function () {
daemon = new jet.Daemon()
daemon.listen({
tcpPort: testPort
})
})
it('should be instance of EventEmitter', function (done) {
expect(daemon).to.be.an.instanceof(EventEmitter)
expect(daemon.listen).to.be.a('function')
daemon.on('test', function (a, b) {
expect(a).to.equal(1)
done()
})
daemon.emit('test', 1, 2)
})
it('should emit "connection" for every new Peer', function (done) {
daemon.once('connection', function (peerMs) {
expect(peerMs).to.be.an('object')
done()
})
var sock = net.connect(testPort)
expect(sock).is.defined
})
describe('when connected to a peer sending "handmade" message', function () {
commandRequestTest(testPort, 'add', {
path: 'test',
value: 123
})
commandRequestTest(testPort, 'info', {}, function (result) {
expect(result.name).to.equal('node-jet')
expect(result.version).to.equal('1.0.6')
expect(result.protocolVersion).to.equal('1.0.0')
expect(result.features.fetch).to.equal('full')
expect(result.features.batches).to.be.true
expect(result.features.authentication).to.be.true
})
commandRequestTest(testPort, 'authenticate', {
user: 'foo',
password: 'bar'
}, function (result, error) {
expect(result).to.be.an('undefined')
expect(error.message).to.equal('Invalid params')
expect(error.data.invalidUser).to.be.true
})
})
it('releasing a peer (with fetchers and elements) does not brake', function (done) {
var peer = new jet.Peer({
port: testPort
})
var state = new jet.State('pathdoesnotmatter', 32)
var fetcher = new jet.Fetcher()
jet.Promise.all([
peer.connect(),
peer.fetch(fetcher),
peer.add(state)
]).then(function () {
peer.close()
})
peer.closed().then(function () {
done()
})
})
it('daemon emits disconnect event when peer disconnects', function (done) {
var peer = new jet.Peer({
port: testPort
})
daemon.on('disconnect', function (peerMS) {
expect(peerMS).to.be.an('object')
done()
})
peer.connect().then(function () {
peer.close()
})
})
it('timeout response is generated', function (done) {
var peer = new jet.Peer({
port: testPort
})
var tooLate = new jet.Method('alwaysTooLate')
tooLate.on('call', function (args, reply) {
setTimeout(function () {
reply({
result: 123
})
}, 100)
})
jet.Promise.all([
peer.connect(),
peer.add(tooLate),
peer.call('alwaysTooLate', [1, 2], {
timeout: 0.001
})
]).catch(function (err) {
expect(err).is.instanceof(jet.PeerTimeout)
done()
})
})
describe('hooking to a (http) server', function () {
var server
var daemon
before(function () {
server = http.createServer(function (req, res) {
res.writeHead(200, {
'Content-Type': 'text/plain'
})
res.end('Hello World\n')
})
server.listen(23456)
daemon = new jet.Daemon()
daemon.listen({
server: server
})
})
it('http get works', function (done) {
http.get({
hostname: 'localhost',
port: 23456
}, function (res) {
res.on('data', function (data) {
expect(data.toString()).to.equal('Hello World\n')
done()
})
})
})
it('peer can connect via websockets on same port', function (done) {
var peer = new jet.Peer({
url: 'ws://localhost:23456',
name: 'blabla'
})
peer.connect().then(function () {
peer.close()
done()
})
})
})
describe('hooking to a (https) server', function () {
var server
var daemon
before(function () {
var options = {
key: fs.readFileSync('test/fixtures/key.pem'),
cert: fs.readFileSync('test/fixtures/certificate.pem')
}
server = https.createServer(options, function (req, res) {
res.writeHead(200, {
'Content-Type': 'text/plain'
})
res.end('Hello World\n')
})
server.listen(23490)
daemon = new jet.Daemon()
daemon.listen({
server: server
})
})
it('https get works', function (done) {
https.get({
hostname: 'localhost',
port: 23490,
rejectUnauthorized: false
}, function (res) {
res.on('data', function (data) {
expect(data.toString()).to.equal('Hello World\n')
done()
})
})
})
it('peer can connect via secure websockets (wss) on same port', function (done) {
var peer = new jet.Peer({
url: 'wss://localhost:23490',
name: 'blabla',
rejectUnauthorized: false
})
peer.connect().then(function () {
peer.close()
done()
})
})
})
})
describe('A Daemon with simple fetching', function () {
var daemon
before(function () {
daemon = new jet.Daemon({
name: 'simple-jet',
features: {
fetch: 'simple'
}
})
daemon.listen({
tcpPort: testPort + 1
})
})
describe('when connected to a peer sending "handmade" message', function () {
commandRequestTest(testPort + 1, 'info', {}, function (result) {
expect(result.name).to.equal('simple-jet')
expect(result.version).to.equal('1.0.6')
expect(result.protocolVersion).to.equal('1.0.0')
expect(result.features.fetch).to.equal('simple')
expect(result.features.batches).to.be.true
expect(result.features.authentication).to.be.true
})
})
})
describe('A Daemon with specified users (authentication)', function () {
var john = {
password: '12345',
auth: {
fetchGroups: [],
setGroups: [],
callGroups: []
}
}
var daemon
before(function () {
daemon = new jet.Daemon({
users: {
john: john
}
})
daemon.listen({
tcpPort: testPort + 2
})
})
describe('when connected to a peer sending "handmade" message', function () {
commandRequestTest(testPort + 2, 'authenticate', {
user: 'john',
password: '12345'
}, function (result, error) {
expect(error).to.be.an('undefined')
expect(result).to.deep.equals(john.auth)
})
})
})
|
exports.min = function min(array) {
if (!array) {
return 0;
}
if (array.length == 0) {
return 0;
}
let res = array[0];
array.forEach(element => {
if (res > element) {
res = element;
}
});
return res;
}
exports.max = function max(array) {
if (!array) {
return 0;
}
if (array.length == 0) {
return 0;
}
let res = array[0];
array.forEach(element => {
if (res < element) {
res = element;
}
});
return res;
}
exports.avg = function avg(array) {
if (!array) {
return 0;
}
if (array.length == 0) {
return 0;
}
let res = 0;
array.forEach(element => {
res += element;
});
return res/array.length;
}
|
"""
main.py
Run the full model-training and evaluation pipeline. Note that you must've run the processing of the data first!
"""
import argparse
import random
import numpy as np
import pandas as pd
import torch
from data.process import main as process_data
from model.evaluate import main as evaluate
from model.setup import main as setup
from model.train import main as train
from model.visualize import main as visualize
from transformer.seq2seq import Seq2Seq
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='')
parser.add_argument("--version", type=bool, default=1)
parser.add_argument("--overwrite", type=bool, default=False)
# Data
parser.add_argument("--process_data", dest="process", type=bool, default=False)
parser.add_argument("--process_raw", dest="raw", type=bool, default=False)
# Training
parser.add_argument("--pre_train", dest="quotes", type=bool, default=False)
parser.add_argument("--train", dest="train", type=bool, default=False)
# Evaluation
parser.add_argument("--evaluate", type=bool, default=False)
parser.add_argument("--visualize", type=bool, default=True)
args = parser.parse_args()
# Planting the seeds
SEED = 42
random.seed(SEED)
np.random.seed(SEED)
torch.manual_seed(SEED)
torch.cuda.manual_seed(SEED)
torch.backends.cudnn.deterministic = True
# Set wider run-terminal
desired_width = 320
pd.set_option('display.width', desired_width)
# Process the raw data
if args.process:
process_data(
raw=args.raw,
limericks=True,
quotes=True,
)
# Setup the model
model: Seq2Seq = setup(
# model_name='model_pre', # TODO
overwrite=args.overwrite,
model_version=args.version,
)
# Train the model on our own dataset (limericks)
if args.train or args.quotes:
train(
model=model,
quotes=args.quotes,
quotes_epochs=5,
limericks=args.train,
limericks_epochs=20,
)
# Load most fit version of the model again
if args.evaluate or args.visualize:
model = setup(
model_name=str(model),
)
# Evaluate the model
if args.evaluate:
evaluate(
model=model,
)
# Visualize inference example
if args.visualize:
for example_idx in range(50):
src = model.tokenizer.test.examples[example_idx].src
trg = model.tokenizer.test.examples[example_idx].trg
visualize(
model=model,
src_id=f"test_sample_{example_idx}",
src=src,
trg=trg,
# save=False, # TODO
analysis=False,
)
|
import sqlite3
import datetime
import pytz
import pickle
db = sqlite3.connect("accounts.sqlite", detect_types=sqlite3.PARSE_DECLTYPES)
db.execute("CREATE TABLE IF NOT EXISTS accounts (name TEXT PRIMARY KEY NOT NULL, balance INTEGER NOT NULL)")
db.execute("CREATE TABLE IF NOT EXISTS transactions (time TIMESTAMP NOT NULL, account TEXT NOT NULL,"
" amount INTEGER NOT NULL, zone INTEGER NOT NULL, PRIMARY KEY (time, account))")
db.execute("CREATE VIEW IF NOT EXISTS localhistory AS SELECT starftime('%Y=%m-%d %H:%M:%f','localtime') "
"As localtime,history.account,history.amount FROM history ORDER BY history.time")
class Account(object):
@staticmethod
def _curent_time():
#return pytz.utc.localize(datetime.datetime.utcnow())
utc_time = pytz.utc.localize(datetime.datetime.utcnow())
local_time = utc_time.astimezone()
zone = local.time.tzinfo
return utc_time,zone
def __init__(self, name: object, opening_balance: object = 0):
cursor = db.execute("SELECT name, balance FROM accounts WHERE (name = ?)", (name,))
row = cursor.fetchone()
if row:
self.name, self._balance = row
print("Retrieved record for {}.".format(self.name), end=' ')
else:
self.name = name
self._balance = opening_balance
cursor.execute("INSERT INTO accounts VALUES (?, ?)", (name, opening_balance))
cursor.connection.commit()
print("Account created for {}".format(self.name), end=' ')
self.show_balance()
def _save_update(self,amount):
new_balance = self._balance + amount
deposit_time, zone = Account._curent_time() # unpacking of tuple
pickled_zone = pickle.dump(zone)
db.execute("UPDATE accounts SET balance = ? WHERE (name = ?)", (new_balance, self.name))
db.execute("INSERT INTO history VALUES(?, ?, ?, ?)",(deposit_time, self.name, amount, pickled_zone))
db.commit()
self._balance = new_balance
def deposit(self, amount:int) -> float:
if amount > 0.0:
# self._balance += amount
self._save_update(amount)
print("{:.2f} deposited".format(amount / 100))
return self._balance / 100
def withdraw(self, amount:int) -> float:
if 0 < amount < self._balance:
self._save_update(amount)
print("{:.2f} withdrawn".format(amount / 100))
return amount / 100
else:
print("The amount must be greater than zero no more than you account balance")
return 0.0
def show_balance(self):
print("Balance on account {} is {:.2f}".format(self.name, self._balance / 100))
if __name__ == "__main__":
ajey = Account("Ajey")
ajey.deposit(1010)
ajey.deposit(10)
ajey.deposit(10)
ajey.withdraw(30)
ajey.withdraw(0)
ajey.show_balance()
vasu = Account("Vasu")
radha = Account("Radha",3000)
ram = Account("Ram",500)
db.close()
|
//used as dedicated worker : debugger, console.log supported (and DOM, anonymous function.. are not supported)
//importScripts("jay_common.js") //jQuery is not defined
//w_winid is unique id for window(tab) which is saved and used in Redis.
//w_winid는 브라우저의 각 윈도우(탭)의 유니크한 ID이며 Redis에도 저장, 사용됨
let w_cnt = 0, w_winid
const SEC = 10
//////////////////////////////////////////start handling IndexedDB
const DATABASE = "jay", TBL = "winner", ONE_KEY = "just_one" //only 1 table & 1 record handled
let db //field(id, winid, udt), protocol(winid, code, msg);
let conn = indexedDB.open(DATABASE, 1) //Increment will trigger conn.onupgradeneeded (add version number if upgrade needed)
conn.onerror = function() {
console.log("indexedDB connect error: " + conn.errorCode)
postMessage({ code : "idb_conn_err", msg : "indexedDB connect error: " + conn.errorCode })
}
conn.onupgradeneeded = function(e) {
db = e.target.result //define field
const os = (db.objectStoreNames.contains(TBL)) ? e.target.transaction.objectStore(TBL) : db.createObjectStore(TBL, { keyPath: "id" })
if (!os.indexNames.contains("winid")) os.createIndex("winid", "winid", { unique : false })
if (!os.indexNames.contains("udt")) os.createIndex("udt", "udt", { unique : false })
os.transaction.oncomplete = function(e) {
const _msg = "idb_upgraded"
console.log(_msg)
postMessage({ code : _msg, msg : _msg }) //1.4) 2.4) 2.14) 3.5) Go to jay_main.js
}
}
conn.onsuccess = function(e) {
db = conn.result
const _msg = "idb_connected"
console.log(_msg)
postMessage({ code : _msg, msg : _msg }) //1.4) 2.4) 2.14) 3.5) Go to jay_main.js
}
//////////////////////////////////////////end
onmessage = function(e) {
if (e.data.code == "auto") {
if (!e.data.msg) { //1.6) 2.6) e.data.msg=null
competeWinner() //offline competition. offline 경합.
} else {
w_winid = e.data.msg //2.16) e.data.msg=someValue
setWinner() //Set new winner from the start since it is StandaloneType. Standalone이므로 경합없이 winner로 설정.
}
} else if (e.data.code == "manual") {
w_winid = e.data.msg //3.7)
setWinner() //Set new winner from the start since it is Manual & Standalone Type. Manual & Standalone이므로 경합없이 winner로 설정.
}
}
function competeWinner() {
try {
let isWinner = false
let udt = getCurDateTimeStr()
w_winid = w_winid ? w_winid : udt //20200817153202xxx
udt = udt.substr(0, 14) //20200817153202
const tx = db.transaction(TBL, "readwrite")
const os = tx.objectStore(TBL)
const os_req = os.get(ONE_KEY) //record is only one
os_req.onsuccess = function(e) {
const rec = os_req.result //only 1 record returned
if (!rec) {
const add_req = os.add({ id : ONE_KEY, winid : w_winid, udt : udt })
add_req.onsuccess = function() {
isWinner = true
}
add_req.onerror = function(e) {
const _msg = "competeWinner: add_req error: " + e.srcElement.error
console.log(_msg)
postMessage({ code : "competeWinner_err", msg : _msg })
}
} else {
if (rec.winid == w_winid) {
rec.udt = udt
const up_req = os.put(rec)
up_req.onsuccess = function() {
isWinner = true
}
up_req.onerror = function(e) {
const _msg = "competeWinner: up_req error: " + e.srcElement.error
console.log(_msg)
postMessage({ code : "competeWinner_err", msg : _msg })
}
} else {
const _diff = getDateTimeDiff(rec.udt, new Date())
if (_diff > (SEC * 2)) {
rec.winid = w_winid //Old w_winid가 업데이트 안되는 미사용분이므로 점유함. If old w_winid is not being updated, new w_winid is replaced.
rec.udt = udt
const up_req1 = os.put(rec)
up_req1.onsuccess = function() {
isWinner = true
}
up_req1.onerror = function(e) {
const _msg = "competeWinner: up_req1 error: " + e.srcElement.error
console.log(_msg)
postMessage({ code : "competeWinner_err", msg : _msg })
}
}
}
}
}
os_req.onerror = function(e) {
const _msg = "competeWinner: os_req error: " + e.srcElement.error
console.log(_msg)
postMessage({ code : "competeWinner_err", msg : _msg })
}
tx.oncomplete = function() {
if (isWinner) { //1.7) 2.7) Go to jay_main.js
postMessage({ code : "winner", msg : "competeWinner: checking as winner: " + w_cnt, winid : w_winid })
} else {
postMessage({ code : "0", msg : "competeWinner: competing to be winner: " + w_cnt, winid : w_winid })
}
w_cnt += 1
setTimeout(function() { competeWinner() }, SEC * 1000)
}
} catch (ex) {
console.log(ex.toString())
postMessage({ code : "competeWinner_err", msg : ex.message })
return
}
}
function setWinner() {
try {
let udt = getCurDateTimeStr()
udt = udt.substr(0, 14) //20200817153202
const tx = db.transaction(TBL, "readwrite")
const os = tx.objectStore(TBL)
const os_req = os.get(ONE_KEY) //record is only one
os_req.onsuccess = function(e) {
const rec = os_req.result //only 1 record returned
if (!rec) {
const add_req = os.add({ id : ONE_KEY, winid : w_winid, udt : udt })
add_req.onerror = function(e) {
const _msg = "setWinner: add_req error: " + e.srcElement.error
console.log(_msg)
postMessage({ code : "setWinner_err", msg : _msg })
}
} else {
rec.winid = w_winid
rec.udt = udt
const up_req = os.put(rec)
up_req.onerror = function(e) {
const _msg = "setWinner: up_req error: " + e.srcElement.error
console.log(_msg)
postMessage({ code : "setWinner_err", msg : _msg })
}
}
}
os_req.onerror = function(e) {
const _msg = "setWinner: os_req error: " + e.srcElement.error
console.log(_msg)
postMessage({ code : "setWinner_err", msg : _msg })
}
tx.oncomplete = function() { //2.17) 3.8)
postMessage({ code : "winner", msg : "setWinner: checking as winner: " + w_cnt, winid : w_winid })
w_cnt += 1
setTimeout(function() { competeWinner() }, SEC * 1000) //not setWinner()
}
} catch (ex) {
console.log(ex.toString())
postMessage({ code : "setWinner_err", msg : ex.message })
return
}
}
function getCurDateTimeStr() {
const now = new Date()
return now.getFullYear().toString() + (now.getMonth() + 1).toString().padStart(2, "0") + now.getDate().toString().padStart(2, "0") +
now.getHours().toString().padStart(2, "0") + now.getMinutes().toString().padStart(2, "0") + now.getSeconds().toString().padStart(2, "0") +
now.getMilliseconds().toString()
}
function getTimeStamp(str) { //str = 2012-08-02 14:12:04
var d = str.match(/\d+/g) //extract date parts
return new Date(d[0], d[1] - 1, d[2], d[3], d[4], d[5]);
}
function getDateTimeDiff(_prev, _now) {
const udt = _prev.substr(0, 4) + "-" + _prev.substr(4, 2) + "-" + _prev.substr(6, 2) + " " + _prev.substr(8, 2) + ":" + _prev.substr(10, 2) + ":" + _prev.substr(12, 2)
var dtPrev = getTimeStamp(udt)
return parseInt((_now - dtPrev) / 1000) //return seconds
}
|
export const appealHasDeathDismissal = (appeal) => {
return appeal.decisionIssues?.some((decisionIssue) =>
decisionIssue.disposition === 'dismissed_death');
};
export const appealSupportsSubstitution = (appeal) => {
return (
// AMA-only
!appeal.isLegacyAppeal &&
// Currently only allow substitutions for veteran
!appeal.appellantIsNotVeteran &&
// Currently disallow substitutions for remands, etc
appeal.caseType === 'Original'
);
};
export const appealHasSubstitution = (appeal) => Boolean(appeal.substitutions?.length);
export const supportsSubstitutionPreDispatch = ({
appeal,
currentUserOnClerkOfTheBoard,
featureToggles,
userIsCobAdmin,
hasSubstitution,
}) => {
return (
appealSupportsSubstitution(appeal) &&
currentUserOnClerkOfTheBoard &&
featureToggles?.listed_granted_substitution_before_dismissal && // eslint-disable-line camelcase
// For now, only allow a single substitution from a given appeal
!hasSubstitution &&
// below is needed to avoid showing multiple substitution buttons on post-dispatch appeals
!appealHasDeathDismissal(appeal) &&
// Only admins can perform sub on cases w/o FNOD status
(userIsCobAdmin || appeal.veteranAppellantDeceased)
);
};
// Function for determining if appellant substution functionality should be enabled
// Examines appeal data, feature toggles, and info re current user
export const supportsSubstitutionPostDispatch = ({
appeal,
currentUserOnClerkOfTheBoard,
hasSubstitution,
userIsCobAdmin,
}) => {
return (
appealSupportsSubstitution(appeal) &&
currentUserOnClerkOfTheBoard &&
// For now, only allow a single substitution from a given appeal
!hasSubstitution &&
// Only admins can perform sub on cases w/o all issues having disposition `dismissed_death`
(userIsCobAdmin || appealHasDeathDismissal(appeal))
);
};
export const isAppealDispatched = (appeal) => {
return ['dispatched', 'post_dispatch'].includes(appeal.status);
};
export const isSubstitutionSameAppeal = (appeal) => {
return !isAppealDispatched(appeal) && !appealHasDeathDismissal(appeal);
};
|
const path = require("path");
exports.createPages = ({ graphql, actions }) => {
const { createPage } = actions;
return new Promise((resolve, reject) => {
graphql(`
{
allContentfulService {
edges {
node {
slug
}
}
}
allContentfulLocation {
edges {
node {
slug
}
}
}
allContentfulNews {
edges {
node {
slug
}
}
}
allContentfulEquipmentList {
edges {
node {
slug
}
}
}
}
`).then(result => {
result.data.allContentfulService.edges.forEach(({ node }) => {
createPage({
path: "services/" + node.slug,
component: path.resolve(`./src/templates/service.js`),
context: {
// Data passed to context is available
// in page queries as GraphQL variables.
slug: node.slug
}
});
});
result.data.allContentfulLocation.edges.forEach(({ node }) => {
createPage({
path: "locations/" + node.slug,
component: path.resolve(`./src/templates/location.js`),
context: {
// Data passed to context is available
// in page queries as GraphQL variables.
slug: node.slug
}
});
});
result.data.allContentfulEquipmentList.edges.forEach(({ node }) => {
createPage({
path: "equipmentlist/" + node.slug,
component: path.resolve(`./src/templates/equipmentList.js`),
context: {
// Data passed to context is available
// in page queries as GraphQL variables.
slug: node.slug
}
});
});
result.data.allContentfulNews.edges.forEach(({ node }) => {
createPage({
path: "news/" + node.slug,
component: path.resolve(`./src/templates/newsArticle.js`),
context: {
// Data passed to context is available
// in page queries as GraphQL variables.
slug: node.slug
}
});
});
resolve();
});
});
};
|
var reqId
var timeoutPeriod = 35 * 1000;
function onQuerySubmitFromWebpage(queryType) {
$("#resultList").empty();
reqId = "0"
console.log("Value submitted:" + $("#queryInput").val());
$.ajax
({
url : "/data",
type : 'POST',
dataType: 'json',
data : JSON.stringify({ name: 'query', data: $("#queryInput").val(), type: queryType, requestId: reqId }),
success : function (data, textStatus, xhr) { onReceiveAnswerFromServer(data, textStatus, xhr) },
error : function (xhr, textStatus ) {
if (textStatus === 'timeout'){
modalError('Request time out!');
}else{
modalError('Error ' + xhr.status +': ' + xhr.statusText +" - " + xhr.responseJSON.text);
}
},
timeout : timeoutPeriod
});
}
function onReceiveAnswerFromServer(message, textStatus, xhr) {
if (!($("#progressModal").data('bs.modal') || {})._isShown) {
$("#progressModal").modal('show');
}
if(xhr.status != 200)
{
modalError('Error ' + xhr.status +': ' + xhr.statusText +" - " + message.text);
return;
}
reqId = message.requestId;
switch (message.progress) {
case -1:
$("#btnCloseModal").show();
modalError('Error ' + xhr.status +': ' + xhr.statusText +" - " + message.text);
break;
case 100:
$('#modalMessage').text('Finished!');
setProgressBarToSuccess();
if (!($("#progressModal").data('bs.modal') || {})._isShown) {
$("#progressModal").modal('show');
}
var resultList = message.resultsList;
populateResults(resultList);
let counter = 3;
$("#btnCloseModal").text("Close (" + counter + ")");
$("#btnCloseModal").show();
setInterval(function () {
counter--;
if (counter >= 0) {
$("#btnCloseModal").text("Close (" + counter + ")");
}
if (counter === 0) {
$("#progressModal").modal('hide');
}
}, 1000);
break;
default:
$("#btnCloseModal").hide();
$('#modalMessage').text(message.text);
$('#progressBar').css('width', message.progress + '%')
.attr('aria-valuenow', message.progress)
.removeClass('bg-danger')
.removeClass('bg-success')
.addClass('bg-primary')
.addClass('progress-bar-animated')
.addClass('progress-bar-striped');
$.ajax
({
url : "/data",
type : 'POST',
dataType: 'json',
data : JSON.stringify({ name: 'statusUpdate', data: message.progress, requestId: reqId}),
success : function (data, textStatus, xhr) { onReceiveAnswerFromServer(data, textStatus, xhr) },
error : function (xhr, textStatus ) {
if (textStatus === 'timeout'){
modalError('Request time out!');
}else{
modalError('Error ' + xhr.status +': ' + xhr.statusText +" - " + xhr.responseJSON.text);
}
},
timeout : timeoutPeriod
});
break;
}
}
function modalError(errorText) {
reqId = "0";
$('#modalMessage').text(errorText);
setProgressBarToError();
$("#btnCloseModal").text("Close");
if (!($("#progressModal").data('bs.modal') || {})._isShown) {
$("#progressModal").modal('show');
}
$("#btnCloseModal").show();
}
function setProgressBarToError() {
$('#progressBar').css('width', '100%')
.attr('aria-valuenow', '100')
.addClass('bg-danger')
.removeClass('progress-bar-animated')
.removeClass('progress-bar-striped');
}
function setProgressBarToSuccess() {
$('#progressBar').css('width', '100%')
.attr('aria-valuenow', '100')
.addClass('bg-success')
.removeClass('progress-bar-animated')
.removeClass('progress-bar-striped');
}
function populateResults(resultList) {
console.log("Reulst list populating!");
$("#resultList").empty();
for (var i = 0; i < resultList.length; i++) {
var aElement = document.createElement("a");
aElement.className = "list-group-item list-group-item-action";
aElement.target = "_blank";
aElement.href = resultList[i].url;
aElement.innerText = resultList[i].text;
$("#resultList").append(aElement);
}
}
|
import React, { useState, useEffect, useMemo } from 'react';
import { Field, TextInput, Select, ButtonGroup, Button, Box, Icon, Callout, FieldGroup } from '@rocket.chat/fuselage';
import { css } from '@rocket.chat/css-in-js';
import { useMutableCallback } from '@rocket.chat/fuselage-hooks';
import VerticalBar from '../../components/basic/VerticalBar';
import { UserAutoComplete } from '../../components/basic/AutoComplete';
import { useTranslation } from '../../contexts/TranslationContext';
import { useForm } from '../../hooks/useForm';
import { useUserRoom } from '../hooks/useUserRoom';
import { useEndpoint } from '../../contexts/ServerContext';
import { roomTypes, isEmail } from '../../../app/utils/client';
import { useToastMessageDispatch } from '../../contexts/ToastMessagesContext';
const clickable = css`
cursor: pointer;
`;
const FileExport = ({ onCancel, rid }) => {
const t = useTranslation();
const { values, handlers } = useForm({
dateFrom: '',
dateTo: '',
format: 'html',
});
const {
dateFrom,
dateTo,
format,
} = values;
const {
handleDateFrom,
handleDateTo,
handleFormat,
} = handlers;
const outputOptions = useMemo(() => [
['html', t('HTML')],
['json', t('JSON')],
], [t]);
const roomsExport = useEndpoint('POST', 'rooms.export');
const dispatchToastMessage = useToastMessageDispatch();
const handleSubmit = async () => {
try {
await roomsExport({
rid,
type: 'file',
...dateFrom && { dateFrom: new Date(dateFrom) },
...dateTo && { dateTo: new Date(dateTo) },
format,
});
dispatchToastMessage({
type: 'success',
message: t('Your_email_has_been_queued_for_sending'),
});
} catch (error) {
dispatchToastMessage({
type: 'error',
message: error,
});
}
};
return (
<FieldGroup>
<Field>
<Field.Label>{t('Date_From')}</Field.Label>
<Field.Row>
<TextInput type='date' value={dateFrom} onChange={handleDateFrom} />
</Field.Row>
</Field>
<Field>
<Field.Label>{t('Date_to')}</Field.Label>
<Field.Row>
<TextInput type='date' value={dateTo} onChange={handleDateTo} />
</Field.Row>
</Field>
<Field>
<Field.Label>{t('Output_format')}</Field.Label>
<Field.Row>
<Select value={format} onChange={handleFormat} placeholder={t('Format')} options={outputOptions}/>
</Field.Row>
</Field>
<ButtonGroup stretch mb='x12'>
<Button onClick={onCancel}>
{t('Cancel')}
</Button>
<Button primary onClick={() => handleSubmit()}>
{t('Export')}
</Button>
</ButtonGroup>
</FieldGroup>
);
};
const MailExportForm = ({ onCancel, rid }) => {
const t = useTranslation();
const room = useUserRoom(rid);
const roomName = room && room.t && roomTypes.getRoomName(room.t, room);
const [selectedMessages, setSelected] = useState([]);
const [errorMessage, setErrorMessage] = useState();
const { values, handlers } = useForm({
dateFrom: '',
dateTo: '',
toUsers: '',
additionalEmails: '',
subject: t('Mail_Messages_Subject', roomName),
});
const dispatchToastMessage = useToastMessageDispatch();
const {
toUsers,
additionalEmails,
subject,
} = values;
const reset = useMutableCallback(() => {
setSelected([]);
$(`#chat-window-${ rid }.messages-box .message.selected`)
.removeClass('selected');
});
useEffect(() => {
const $root = $(`#chat-window-${ rid }`);
$('.messages-box', $root).addClass('selectable');
const handler = function() {
const { id } = this;
if (this.classList.contains('selected')) {
this.classList.remove('selected');
setSelected((selectedMessages) => selectedMessages.filter((message) => message !== id));
} else {
this.classList.add('selected');
setSelected((selectedMessages) => selectedMessages.concat(id));
}
};
$('.messages-box .message', $root).on('click', handler);
return () => {
$('.messages-box', $root).removeClass('selectable');
$('.messages-box .message', $root)
.off('click', handler)
.filter('.selected')
.removeClass('selected');
};
}, [rid]);
const {
handleToUsers,
handleAdditionalEmails,
handleSubject,
} = handlers;
const roomsExport = useEndpoint('POST', 'rooms.export');
const handleSubmit = async () => {
if (toUsers.length === 0 && additionalEmails === '') {
setErrorMessage(t('Mail_Message_Missing_to'));
return;
}
if (additionalEmails !== '' && !isEmail(additionalEmails)) {
setErrorMessage(t('Mail_Message_Invalid_emails', additionalEmails));
return;
}
if (selectedMessages.length === 0) {
setErrorMessage(t('Mail_Message_No_messages_selected_select_all'));
return;
}
setErrorMessage(null);
try {
await roomsExport({
rid,
type: 'email',
toUsers: [toUsers],
toEmails: additionalEmails.split(','),
subject,
messages: selectedMessages,
});
dispatchToastMessage({
type: 'success',
message: t('Your_email_has_been_queued_for_sending'),
});
} catch (error) {
dispatchToastMessage({
type: 'error',
message: error,
});
}
};
return (
<FieldGroup>
<Field>
<Callout onClick={reset} title={t('Messages selected')} type={selectedMessages.length > 0 ? 'success' : 'info'}>
<p>{`${ selectedMessages.length } Messages selected`}</p>
{ selectedMessages.length > 0 && <Box is='p' className={clickable} >{t('Click here to clear the selection')}</Box> }
{ selectedMessages.length === 0 && <Box is='p'>{t('Click_the_messages_you_would_like_to_send_by_email')}</Box> }
</Callout>
</Field>
<Field>
<Field.Label>{t('To_users')}</Field.Label>
<Field.Row>
<UserAutoComplete value={toUsers} onChange={handleToUsers}/>
</Field.Row>
</Field>
<Field>
<Field.Label>{t('To_additional_emails')}</Field.Label>
<Field.Row>
<TextInput placeholder={t('Email_Placeholder_any')} value={additionalEmails} onChange={handleAdditionalEmails} addon={<Icon name='mail' size='x20'/>} />
</Field.Row>
</Field>
<Field>
<Field.Label>{t('Subject')}</Field.Label>
<Field.Row>
<TextInput value={subject} onChange={handleSubject} addon={<Icon name='edit' size='x20'/>} />
</Field.Row>
</Field>
{errorMessage && <Callout type={'danger'} title={errorMessage} />}
<ButtonGroup stretch mb='x12'>
<Button onClick={onCancel}>
{t('Cancel')}
</Button>
<Button primary onClick={() => handleSubmit()}>
{t('Send')}
</Button>
</ButtonGroup>
</FieldGroup>
);
};
export const ExportMessages = function ExportMessages({ rid, tabBar }) {
const t = useTranslation();
const [type, setType] = useState('email');
const exportOptions = useMemo(() => [
['email', t('Send_via_email')],
['file', t('Export_as_file')],
], [t]);
return (
<VerticalBar>
<VerticalBar.Header>
{t('Export_Messages')}
<VerticalBar.Close onClick={() => tabBar.close()} />
</VerticalBar.Header>
<VerticalBar.ScrollableContent>
<FieldGroup>
<Field>
<Field.Label>{t('Method')}</Field.Label>
<Field.Row>
<Select value={type} onChange={(value) => setType(value)} placeholder={t('Type')} options={exportOptions}/>
</Field.Row>
</Field>
</FieldGroup>
{type && type === 'file' && <FileExport rid={rid} onCancel={() => tabBar.close()} />}
{type && type === 'email' && <MailExportForm rid={rid} onCancel={() => tabBar.close()} />}
</VerticalBar.ScrollableContent>
</VerticalBar>
);
};
export default ExportMessages;
|
import React from 'react';
import { BrowserRouter, Route, Switch, Redirect } from 'react-router-dom';
import withContext from './Context';
import PrivateRoute from './PrivateRoute';
/* Import components. */
import Header from './components/Header';
import UserSignUp from './components/UserSignUp';
import UserSignIn from './components/UserSignIn';
import UserSignOut from './components/UserSignOut';
import Courses from './components/Courses';
import CourseDetail from './components/CourseDetail';
import CreateCourse from './components/CreateCourse';
import UpdateCourse from './components/UpdateCourse';
import UnhandledError from './components/UnhandledError';
import Forbidden from './components/Forbidden';
import NotFound from './components/NotFound';
/* Connect the components to the context. */
const UserSignUpWithContext = withContext (UserSignUp);
const UserSignInWithContext = withContext (UserSignIn);
const UserSignOutWithContext = withContext (UserSignOut);
const HeaderWithContext = withContext (Header);
const CoursesWithContext = withContext (Courses);
const CourseDetailWithContext = withContext (CourseDetail);
const CreateCourseWithContext = withContext (CreateCourse);
const UpdateCourseWithContext = withContext (UpdateCourse);
const App = () => (
<BrowserRouter>
<div>
<HeaderWithContext />
<Switch>
<Route exact path='/' render={() => <Redirect to='/courses' /> } />
<Route exact path='/courses' component={CoursesWithContext} />
<Route path='/signup' component={UserSignUpWithContext} />
<Route path='/signin' component={UserSignInWithContext} />
<Route path='/signout' component={UserSignOutWithContext} />
<PrivateRoute path='/courses/create' component={CreateCourseWithContext} />
<Route exact path='/courses/:id' render={({match}) => <CourseDetailWithContext match={match} /> }/>
<PrivateRoute path='/courses/:id/update' component={({match}) => <UpdateCourseWithContext match={match} /> } />
<Route path='/error' component={UnhandledError} />
<Route path='/forbidden' component={Forbidden} />
<Route path='/notfound' component={NotFound} />
<Route component={NotFound} />
</Switch>
</div>
</BrowserRouter>
);
export default App;
|
const { Client, Collection } = require("discord.js");
const { readdirSync } = require("fs");
// client class
class Nero extends Client {
constructor (opt) {
super (opt);
this.util = require("./handle/util");
this.snek = require('node-superfetch');
}
}
// const client
const client = new Nero({
fetchAllMembers: true
});
// events file handler
for (const event of readdirSync("./src/events")) {
client.on(event.split(".")[0], (...args) => require(`./events/${event}`)(client, ...args));
}
// module files handler
require("./handle/ModuleHandler")(client);
// client login
client.login(process.env.TOKEN);
process.on("error", e => console.error('[RIKKA ERROR]', e));
process.on("uncaughtExpection", e => console.error("[RIKKA UNCAUGHT EXCEPTION]", e));
process.on("unhandledRejection", e => console.error("[RIKKA UNHANDLED REJECTION]", e));
module.exports = Nero;
|