code
stringlengths 24
2.07M
| docstring
stringlengths 25
85.3k
| func_name
stringlengths 1
92
| language
stringclasses 1
value | repo
stringlengths 5
64
| path
stringlengths 4
172
| url
stringlengths 44
218
| license
stringclasses 7
values |
---|---|---|---|---|---|---|---|
function localIjToCell(origin, coords) {
// Validate input coords
if (!coords || typeof coords.i !== 'number' || typeof coords.j !== 'number') {
throw new Error('Coordinates must be provided as an {i, j} object');
}
// Allocate memory for the CoordIJ struct and an H3 index to hold the return value
const ij = C._malloc(SZ_COORDIJ);
const out = C._malloc(SZ_H3INDEX);
storeCoordIJ(ij, coords);
try {
throwIfError(
H3.localIjToCell(...h3IndexToSplitLong(origin), ij, LOCAL_IJ_DEFAULT_MODE, out)
);
return validateH3Index(readH3IndexFromPointer(out));
} finally {
C._free(ij);
C._free(out);
}
}
|
Produces an H3 index for IJ coordinates anchored by an origin.
- The coordinate space used by this function may have deleted
regions or warping due to pentagonal distortion.
- Coordinates are only comparable if they come from the same
origin index.
- Failure may occur if the index is too far away from the origin
or if the index is on the other side of a pentagon.
- This function is experimental, and its output is not guaranteed
to be compatible across different versions of H3.
@static
@param {H3IndexInput} origin Origin H3 index
@param {CoordIJ} coords Coordinates as an `{i, j}` pair
@return {H3Index} H3 index at the relative coordinates
@throws {H3Error} If the H3 index cannot be calculated
|
localIjToCell
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function greatCircleDistance(latLng1, latLng2, unit) {
const coord1 = storeLatLng(latLng1[0], latLng1[1]);
const coord2 = storeLatLng(latLng2[0], latLng2[1]);
let result;
switch (unit) {
case UNITS.m:
result = H3.greatCircleDistanceM(coord1, coord2);
break;
case UNITS.km:
result = H3.greatCircleDistanceKm(coord1, coord2);
break;
case UNITS.rads:
result = H3.greatCircleDistanceRads(coord1, coord2);
break;
default:
result = null;
}
C._free(coord1);
C._free(coord2);
if (result === null) {
throw JSBindingError(E_UNKNOWN_UNIT, unit);
}
return result;
}
|
Great circle distance between two geo points. This is not specific to H3,
but is implemented in the library and provided here as a convenience.
@static
@param {number[]} latLng1 Origin coordinate as [lat, lng]
@param {number[]} latLng2 Destination coordinate as [lat, lng]
@param {string} unit Distance unit (either UNITS.m, UNITS.km, or UNITS.rads)
@return {number} Great circle distance
@throws {H3Error} If the unit is invalid
|
greatCircleDistance
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function cellArea(h3Index, unit) {
const [lower, upper] = h3IndexToSplitLong(h3Index);
const out = C._malloc(SZ_DBL);
try {
switch (unit) {
case UNITS.m2:
throwIfError(H3.cellAreaM2(lower, upper, out));
break;
case UNITS.km2:
throwIfError(H3.cellAreaKm2(lower, upper, out));
break;
case UNITS.rads2:
throwIfError(H3.cellAreaRads2(lower, upper, out));
break;
default:
throw JSBindingError(E_UNKNOWN_UNIT, unit);
}
return readDoubleFromPointer(out);
} finally {
C._free(out);
}
}
|
Exact area of a given cell
@static
@param {H3IndexInput} h3Index H3 index of the hexagon to measure
@param {string} unit Distance unit (either UNITS.m2, UNITS.km2, or UNITS.rads2)
@return {number} Cell area
@throws {H3Error} If the input is invalid
|
cellArea
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function edgeLength(edge, unit) {
const [lower, upper] = h3IndexToSplitLong(edge);
const out = C._malloc(SZ_DBL);
try {
switch (unit) {
case UNITS.m:
throwIfError(H3.edgeLengthM(lower, upper, out));
break;
case UNITS.km:
throwIfError(H3.edgeLengthKm(lower, upper, out));
break;
case UNITS.rads:
throwIfError(H3.edgeLengthRads(lower, upper, out));
break;
default:
throw JSBindingError(E_UNKNOWN_UNIT, unit);
}
return readDoubleFromPointer(out);
} finally {
C._free(out);
}
}
|
Calculate length of a given unidirectional edge
@static
@param {H3IndexInput} edge H3 index of the edge to measure
@param {string} unit Distance unit (either UNITS.m, UNITS.km, or UNITS.rads)
@return {number} Cell area
@throws {H3Error} If the input is invalid
|
edgeLength
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function getHexagonAreaAvg(res, unit) {
validateRes(res);
const out = C._malloc(SZ_DBL);
try {
switch (unit) {
case UNITS.m2:
throwIfError(H3.getHexagonAreaAvgM2(res, out));
break;
case UNITS.km2:
throwIfError(H3.getHexagonAreaAvgKm2(res, out));
break;
default:
throw JSBindingError(E_UNKNOWN_UNIT, unit);
}
return readDoubleFromPointer(out);
} finally {
C._free(out);
}
}
|
Average hexagon area at a given resolution
@static
@param {number} res Hexagon resolution
@param {string} unit Area unit (either UNITS.m2, UNITS.km2, or UNITS.rads2)
@return {number} Average area
@throws {H3Error} If the input is invalid
|
getHexagonAreaAvg
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function getHexagonEdgeLengthAvg(res, unit) {
validateRes(res);
const out = C._malloc(SZ_DBL);
try {
switch (unit) {
case UNITS.m:
throwIfError(H3.getHexagonEdgeLengthAvgM(res, out));
break;
case UNITS.km:
throwIfError(H3.getHexagonEdgeLengthAvgKm(res, out));
break;
default:
throw JSBindingError(E_UNKNOWN_UNIT, unit);
}
return readDoubleFromPointer(out);
} finally {
C._free(out);
}
}
|
Average hexagon edge length at a given resolution
@static
@param {number} res Hexagon resolution
@param {string} unit Distance unit (either UNITS.m, UNITS.km, or UNITS.rads)
@return {number} Average edge length
@throws {H3Error} If the input is invalid
|
getHexagonEdgeLengthAvg
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function cellToVertex(h3Index, vertexNum) {
const [lower, upper] = h3IndexToSplitLong(h3Index);
const vertexIndex = C._malloc(SZ_H3INDEX);
try {
throwIfError(H3.cellToVertex(lower, upper, vertexNum, vertexIndex));
return validateH3Index(readH3IndexFromPointer(vertexIndex));
} finally {
C._free(vertexIndex);
}
}
|
Find the index for a vertex of a cell.
@static
@param {H3IndexInput} h3Index Cell to find the vertex for
@param {number} vertexNum Number (index) of the vertex to calculate
@return {H3Index} Vertex index
@throws {H3Error} If the input is invalid
|
cellToVertex
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function cellToVertexes(h3Index) {
const [lower, upper] = h3IndexToSplitLong(h3Index);
const maxNumVertexes = 6;
const vertexIndexes = C._calloc(maxNumVertexes, SZ_H3INDEX);
try {
throwIfError(H3.cellToVertexes(lower, upper, vertexIndexes));
return readArrayOfH3Indexes(vertexIndexes, maxNumVertexes);
} finally {
C._free(vertexIndexes);
}
}
|
Find the indexes for all vertexes of a cell.
@static
@param {H3IndexInput} h3Index Cell to find all vertexes for
@return {H3Index[]} All vertex indexes of this cell
@throws {H3Error} If the input is invalid
|
cellToVertexes
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function vertexToLatLng(h3Index) {
const latlng = C._malloc(SZ_LATLNG);
const [lower, upper] = h3IndexToSplitLong(h3Index);
try {
throwIfError(H3.vertexToLatLng(lower, upper, latlng));
return readLatLng(latlng);
} finally {
C._free(latlng);
}
}
|
Get the lat, lng of a given vertex
@static
@param {H3IndexInput} h3Index A vertex index
@returns {CoordPair} Latitude, longitude coordinates of the vertex
@throws {H3Error} If the input is invalid
|
vertexToLatLng
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function isValidVertex(h3Index) {
const [lower, upper] = h3IndexToSplitLong(h3Index);
return Boolean(H3.isValidVertex(lower, upper));
}
|
Returns true if the input is a valid vertex index.
@static
@param {H3IndexInput} h3Index An index to test for being a vertex index
@returns {boolean} True if the index represents a vertex
|
isValidVertex
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function getNumCells(res) {
validateRes(res);
const countPtr = C._malloc(SZ_INT64);
try {
// Get number as a long value
throwIfError(H3.getNumCells(res, countPtr));
return readInt64AsDoubleFromPointer(countPtr);
} finally {
C._free(countPtr);
}
}
|
The total count of hexagons in the world at a given resolution. Note that above
resolution 8 the exact count cannot be represented in a JavaScript 32-bit number,
so consumers should use caution when applying further operations to the output.
@static
@param {number} res Hexagon resolution
@return {number} Count
@throws {H3Error} If the resolution is invalid
|
getNumCells
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function getRes0Cells() {
const count = H3.res0CellCount();
const hexagons = C._malloc(SZ_H3INDEX * count);
try {
throwIfError(H3.getRes0Cells(hexagons));
return readArrayOfH3Indexes(hexagons, count);
} finally {
C._free(hexagons);
}
}
|
Get all H3 indexes at resolution 0. As every index at every resolution > 0 is
the descendant of a res 0 index, this can be used with h3ToChildren to iterate
over H3 indexes at any resolution.
@static
@return {H3Index[]} All H3 indexes at res 0
|
getRes0Cells
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function getPentagons(res) {
validateRes(res);
const count = H3.pentagonCount();
const hexagons = C._malloc(SZ_H3INDEX * count);
try {
throwIfError(H3.getPentagons(res, hexagons));
return readArrayOfH3Indexes(hexagons, count);
} finally {
C._free(hexagons);
}
}
|
Get the twelve pentagon indexes at a given resolution.
@static
@param {number} res Hexagon resolution
@return {H3Index[]} All H3 pentagon indexes at res
@throws {H3Error} If the resolution is invalid
|
getPentagons
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function degsToRads(deg) {
return (deg * Math.PI) / 180;
}
|
Convert degrees to radians
@static
@param {number} deg Value in degrees
@return {number} Value in radians
|
degsToRads
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function radsToDegs(rad) {
return (rad * 180) / Math.PI;
}
|
Convert radians to degrees
@static
@param {number} rad Value in radians
@return {number} Value in degrees
|
radsToDegs
|
javascript
|
uber/h3-js
|
lib/h3core.js
|
https://github.com/uber/h3-js/blob/master/lib/h3core.js
|
Apache-2.0
|
function setComplete() {
$timeout.cancel(startTimeout);
cfpLoadingBar.complete();
reqsCompleted = 0;
reqsTotal = 0;
}
|
calls cfpLoadingBar.complete() which removes the
loading bar from the DOM.
|
setComplete
|
javascript
|
chieffancypants/angular-loading-bar
|
build/loading-bar.js
|
https://github.com/chieffancypants/angular-loading-bar/blob/master/build/loading-bar.js
|
MIT
|
function isCached(config) {
var cache;
var defaultCache = $cacheFactory.get('$http');
var defaults = $httpProvider.defaults;
// Choose the proper cache source. Borrowed from angular: $http service
if ((config.cache || defaults.cache) && config.cache !== false &&
(config.method === 'GET' || config.method === 'JSONP')) {
cache = angular.isObject(config.cache) ? config.cache
: angular.isObject(defaults.cache) ? defaults.cache
: defaultCache;
}
var cached = cache !== undefined ?
cache.get(config.url) !== undefined : false;
if (config.cached !== undefined && cached !== config.cached) {
return config.cached;
}
config.cached = cached;
return cached;
}
|
Determine if the response has already been cached
@param {Object} config the config option from the request
@return {Boolean} retrns true if cached, otherwise false
|
isCached
|
javascript
|
chieffancypants/angular-loading-bar
|
build/loading-bar.js
|
https://github.com/chieffancypants/angular-loading-bar/blob/master/build/loading-bar.js
|
MIT
|
function _start() {
if (!$animate) {
$animate = $injector.get('$animate');
}
$timeout.cancel(completeTimeout);
// do not continually broadcast the started event:
if (started) {
return;
}
var document = $document[0];
var parent = document.querySelector ?
document.querySelector($parentSelector)
: $document.find($parentSelector)[0]
;
if (! parent) {
parent = document.getElementsByTagName('body')[0];
}
var $parent = angular.element(parent);
var $after = parent.lastChild && angular.element(parent.lastChild);
$rootScope.$broadcast('cfpLoadingBar:started');
started = true;
if (includeBar) {
$animate.enter(loadingBarContainer, $parent, $after);
}
if (includeSpinner) {
$animate.enter(spinner, $parent, loadingBarContainer);
}
_set(startSize);
}
|
Inserts the loading bar element into the dom, and sets it to 2%
|
_start
|
javascript
|
chieffancypants/angular-loading-bar
|
build/loading-bar.js
|
https://github.com/chieffancypants/angular-loading-bar/blob/master/build/loading-bar.js
|
MIT
|
function _set(n) {
if (!started) {
return;
}
var pct = (n * 100) + '%';
loadingBar.css('width', pct);
status = n;
// increment loadingbar to give the illusion that there is always
// progress but make sure to cancel the previous timeouts so we don't
// have multiple incs running at the same time.
if (autoIncrement) {
$timeout.cancel(incTimeout);
incTimeout = $timeout(function() {
_inc();
}, 250);
}
}
|
Set the loading bar's width to a certain percent.
@param n any value between 0 and 1
|
_set
|
javascript
|
chieffancypants/angular-loading-bar
|
build/loading-bar.js
|
https://github.com/chieffancypants/angular-loading-bar/blob/master/build/loading-bar.js
|
MIT
|
function _inc() {
if (_status() >= 1) {
return;
}
var rnd = 0;
// TODO: do this mathmatically instead of through conditions
var stat = _status();
if (stat >= 0 && stat < 0.25) {
// Start out between 3 - 6% increments
rnd = (Math.random() * (5 - 3 + 1) + 3) / 100;
} else if (stat >= 0.25 && stat < 0.65) {
// increment between 0 - 3%
rnd = (Math.random() * 3) / 100;
} else if (stat >= 0.65 && stat < 0.9) {
// increment between 0 - 2%
rnd = (Math.random() * 2) / 100;
} else if (stat >= 0.9 && stat < 0.99) {
// finally, increment it .5 %
rnd = 0.005;
} else {
// after 99%, don't increment:
rnd = 0;
}
var pct = _status() + rnd;
_set(pct);
}
|
Increments the loading bar by a random amount
but slows down as it progresses
|
_inc
|
javascript
|
chieffancypants/angular-loading-bar
|
build/loading-bar.js
|
https://github.com/chieffancypants/angular-loading-bar/blob/master/build/loading-bar.js
|
MIT
|
function _status() {
return status;
}
|
Increments the loading bar by a random amount
but slows down as it progresses
|
_status
|
javascript
|
chieffancypants/angular-loading-bar
|
build/loading-bar.js
|
https://github.com/chieffancypants/angular-loading-bar/blob/master/build/loading-bar.js
|
MIT
|
function _completeAnimation() {
status = 0;
started = false;
}
|
Increments the loading bar by a random amount
but slows down as it progresses
|
_completeAnimation
|
javascript
|
chieffancypants/angular-loading-bar
|
build/loading-bar.js
|
https://github.com/chieffancypants/angular-loading-bar/blob/master/build/loading-bar.js
|
MIT
|
function _complete() {
if (!$animate) {
$animate = $injector.get('$animate');
}
_set(1);
$timeout.cancel(completeTimeout);
// Attempt to aggregate any start/complete calls within 500ms:
completeTimeout = $timeout(function() {
var promise = $animate.leave(loadingBarContainer, _completeAnimation);
if (promise && promise.then) {
promise.then(_completeAnimation);
}
$animate.leave(spinner);
$rootScope.$broadcast('cfpLoadingBar:completed');
}, 500);
}
|
Increments the loading bar by a random amount
but slows down as it progresses
|
_complete
|
javascript
|
chieffancypants/angular-loading-bar
|
build/loading-bar.js
|
https://github.com/chieffancypants/angular-loading-bar/blob/master/build/loading-bar.js
|
MIT
|
function setComplete() {
$timeout.cancel(startTimeout);
cfpLoadingBar.complete();
reqsCompleted = 0;
reqsTotal = 0;
}
|
calls cfpLoadingBar.complete() which removes the
loading bar from the DOM.
|
setComplete
|
javascript
|
chieffancypants/angular-loading-bar
|
src/loading-bar.js
|
https://github.com/chieffancypants/angular-loading-bar/blob/master/src/loading-bar.js
|
MIT
|
function isCached(config) {
var cache;
var defaultCache = $cacheFactory.get('$http');
var defaults = $httpProvider.defaults;
// Choose the proper cache source. Borrowed from angular: $http service
if ((config.cache || defaults.cache) && config.cache !== false &&
(config.method === 'GET' || config.method === 'JSONP')) {
cache = angular.isObject(config.cache) ? config.cache
: angular.isObject(defaults.cache) ? defaults.cache
: defaultCache;
}
var cached = cache !== undefined ?
cache.get(config.url) !== undefined : false;
if (config.cached !== undefined && cached !== config.cached) {
return config.cached;
}
config.cached = cached;
return cached;
}
|
Determine if the response has already been cached
@param {Object} config the config option from the request
@return {Boolean} retrns true if cached, otherwise false
|
isCached
|
javascript
|
chieffancypants/angular-loading-bar
|
src/loading-bar.js
|
https://github.com/chieffancypants/angular-loading-bar/blob/master/src/loading-bar.js
|
MIT
|
function _start() {
if (!$animate) {
$animate = $injector.get('$animate');
}
$timeout.cancel(completeTimeout);
// do not continually broadcast the started event:
if (started) {
return;
}
var document = $document[0];
var parent = document.querySelector ?
document.querySelector($parentSelector)
: $document.find($parentSelector)[0]
;
if (! parent) {
parent = document.getElementsByTagName('body')[0];
}
var $parent = angular.element(parent);
var $after = parent.lastChild && angular.element(parent.lastChild);
$rootScope.$broadcast('cfpLoadingBar:started');
started = true;
if (includeBar) {
$animate.enter(loadingBarContainer, $parent, $after);
}
if (includeSpinner) {
$animate.enter(spinner, $parent, loadingBarContainer);
}
_set(startSize);
}
|
Inserts the loading bar element into the dom, and sets it to 2%
|
_start
|
javascript
|
chieffancypants/angular-loading-bar
|
src/loading-bar.js
|
https://github.com/chieffancypants/angular-loading-bar/blob/master/src/loading-bar.js
|
MIT
|
function _set(n) {
if (!started) {
return;
}
var pct = (n * 100) + '%';
loadingBar.css('width', pct);
status = n;
// increment loadingbar to give the illusion that there is always
// progress but make sure to cancel the previous timeouts so we don't
// have multiple incs running at the same time.
if (autoIncrement) {
$timeout.cancel(incTimeout);
incTimeout = $timeout(function() {
_inc();
}, 250);
}
}
|
Set the loading bar's width to a certain percent.
@param n any value between 0 and 1
|
_set
|
javascript
|
chieffancypants/angular-loading-bar
|
src/loading-bar.js
|
https://github.com/chieffancypants/angular-loading-bar/blob/master/src/loading-bar.js
|
MIT
|
function _inc() {
if (_status() >= 1) {
return;
}
var rnd = 0;
// TODO: do this mathmatically instead of through conditions
var stat = _status();
if (stat >= 0 && stat < 0.25) {
// Start out between 3 - 6% increments
rnd = (Math.random() * (5 - 3 + 1) + 3) / 100;
} else if (stat >= 0.25 && stat < 0.65) {
// increment between 0 - 3%
rnd = (Math.random() * 3) / 100;
} else if (stat >= 0.65 && stat < 0.9) {
// increment between 0 - 2%
rnd = (Math.random() * 2) / 100;
} else if (stat >= 0.9 && stat < 0.99) {
// finally, increment it .5 %
rnd = 0.005;
} else {
// after 99%, don't increment:
rnd = 0;
}
var pct = _status() + rnd;
_set(pct);
}
|
Increments the loading bar by a random amount
but slows down as it progresses
|
_inc
|
javascript
|
chieffancypants/angular-loading-bar
|
src/loading-bar.js
|
https://github.com/chieffancypants/angular-loading-bar/blob/master/src/loading-bar.js
|
MIT
|
function _status() {
return status;
}
|
Increments the loading bar by a random amount
but slows down as it progresses
|
_status
|
javascript
|
chieffancypants/angular-loading-bar
|
src/loading-bar.js
|
https://github.com/chieffancypants/angular-loading-bar/blob/master/src/loading-bar.js
|
MIT
|
function _completeAnimation() {
status = 0;
started = false;
}
|
Increments the loading bar by a random amount
but slows down as it progresses
|
_completeAnimation
|
javascript
|
chieffancypants/angular-loading-bar
|
src/loading-bar.js
|
https://github.com/chieffancypants/angular-loading-bar/blob/master/src/loading-bar.js
|
MIT
|
function _complete() {
if (!$animate) {
$animate = $injector.get('$animate');
}
_set(1);
$timeout.cancel(completeTimeout);
// Attempt to aggregate any start/complete calls within 500ms:
completeTimeout = $timeout(function() {
var promise = $animate.leave(loadingBarContainer, _completeAnimation);
if (promise && promise.then) {
promise.then(_completeAnimation);
}
$animate.leave(spinner);
$rootScope.$broadcast('cfpLoadingBar:completed');
}, 500);
}
|
Increments the loading bar by a random amount
but slows down as it progresses
|
_complete
|
javascript
|
chieffancypants/angular-loading-bar
|
src/loading-bar.js
|
https://github.com/chieffancypants/angular-loading-bar/blob/master/src/loading-bar.js
|
MIT
|
_failSafeSpawn = (command, args) => execa(command, args).then(
({ stdout }) => stdout,
err => `ERROR: ${err.message}`
)
|
@deprecated will be removed when platforms implement the calls.
|
_failSafeSpawn
|
javascript
|
apache/cordova-cli
|
src/info.js
|
https://github.com/apache/cordova-cli/blob/master/src/info.js
|
Apache-2.0
|
_failSafeSpawn = (command, args) => execa(command, args).then(
({ stdout }) => stdout,
err => `ERROR: ${err.message}`
)
|
@deprecated will be removed when platforms implement the calls.
|
_failSafeSpawn
|
javascript
|
apache/cordova-cli
|
src/info.js
|
https://github.com/apache/cordova-cli/blob/master/src/info.js
|
Apache-2.0
|
function _formatNodeList (list, level = 0) {
const content = [];
for (const item of list) {
const indent = String.prototype.padStart((4 * level), ' ');
let itemString = `${indent}${item.key}:`;
if ('value' in item) {
// Pad multi-line values with a new line on either end
itemString += (/[\r\n]/.test(item.value))
? `\n${item.value.trim()}\n`
: ` ${item.value}`;
} else {
// Start of section
itemString = `\n${itemString}\n`;
}
content.push(itemString);
if (item.children) {
content.push(..._formatNodeList(item.children, level + 1));
}
}
return content;
}
|
@deprecated will be removed when platforms implement the calls.
|
_formatNodeList
|
javascript
|
apache/cordova-cli
|
src/info.js
|
https://github.com/apache/cordova-cli/blob/master/src/info.js
|
Apache-2.0
|
function toArray(arg) {
if (typeof arg === 'string') {
return [arg];
} else if (arg) {
return arg;
} else {
return [];
}
}
|
Minimist gives us a string, array or null: normalize to array.
@param {(string|Array<string>)}
@return {!Array<string>}
|
toArray
|
javascript
|
google/closure-compiler-js
|
cmd.js
|
https://github.com/google/closure-compiler-js/blob/master/cmd.js
|
Apache-2.0
|
function readAllFiles(paths) {
return Promise.all(paths.map(path => readFile(path)));
}
|
@param {!Array<string>} paths
@return {!Promise<!Array{src: string, path: string}>>}
|
readAllFiles
|
javascript
|
google/closure-compiler-js
|
cmd.js
|
https://github.com/google/closure-compiler-js/blob/master/cmd.js
|
Apache-2.0
|
function readFile(path) {
return new Promise((resolve, reject) => {
if (path === null) {
let src = '';
process.stdin.resume();
process.stdin.on('data', buf => src += buf.toString());
process.stdin.on('end', () => resolve({src, path: '-'}));
} else {
fs.readFile(path, 'utf8', (err, src) => err ? reject(err) : resolve({src, path}));
}
});
}
|
@param {?string} path
@return {!Promise<{src: string, path: string}>}
|
readFile
|
javascript
|
google/closure-compiler-js
|
cmd.js
|
https://github.com/google/closure-compiler-js/blob/master/cmd.js
|
Apache-2.0
|
function parseDefines(flags){
/**
* compile() expects 'defines' to be object, but minimist may only return array or string
* so, we need to convert to proper object.
* The supported format will be similar to the following,
* https://github.com/google/closure-compiler/wiki/Annotating-JavaScript-for-the-Closure-Compiler#define-type-description
* but instead of using --define 'name=value' we should support --defines 'name=value'
*/
if (Array.isArray(flags.defines) || typeof flags.defines === "string"){
let defines = {};
function parseDefines(d) {
let key, value;
{
let a = d.split("=");
key = a[0];
value = a[1];
}
defines[key] =
/^(?:true|false)$/.test(value)
? value === 'true'
: !isNaN(parseFloat(value)) && isFinite(value)
? parseFloat(value)
: value;
}
if (Array.isArray(flags.defines)) {
flags.defines.forEach(parseDefines);
} else {
parseDefines(flags.defines);
}
flags.defines = defines;
}
}
|
@param {?string} path
@return {!Promise<{src: string, path: string}>}
|
parseDefines
|
javascript
|
google/closure-compiler-js
|
cmd.js
|
https://github.com/google/closure-compiler-js/blob/master/cmd.js
|
Apache-2.0
|
function parseDefines(d) {
let key, value;
{
let a = d.split("=");
key = a[0];
value = a[1];
}
defines[key] =
/^(?:true|false)$/.test(value)
? value === 'true'
: !isNaN(parseFloat(value)) && isFinite(value)
? parseFloat(value)
: value;
}
|
compile() expects 'defines' to be object, but minimist may only return array or string
so, we need to convert to proper object.
The supported format will be similar to the following,
https://github.com/google/closure-compiler/wiki/Annotating-JavaScript-for-the-Closure-Compiler#define-type-description
but instead of using --define 'name=value' we should support --defines 'name=value'
|
parseDefines
|
javascript
|
google/closure-compiler-js
|
cmd.js
|
https://github.com/google/closure-compiler-js/blob/master/cmd.js
|
Apache-2.0
|
function cmdCompile(flags) {
parseDefines(flags);
return compile(flags);
}
|
compile() expects 'defines' to be object, but minimist may only return array or string
so, we need to convert to proper object.
The supported format will be similar to the following,
https://github.com/google/closure-compiler/wiki/Annotating-JavaScript-for-the-Closure-Compiler#define-type-description
but instead of using --define 'name=value' we should support --defines 'name=value'
|
cmdCompile
|
javascript
|
google/closure-compiler-js
|
cmd.js
|
https://github.com/google/closure-compiler-js/blob/master/cmd.js
|
Apache-2.0
|
function ready(sources, externs) {
const flags = Object.assign(Object.assign({}, argv), {jsCode: sources, externs: externs});
const output = cmdCompile(flags);
let code = 0;
if (logger(flags, output)) {
code = 1;
}
console.log(output.compiledCode);
process.exit(code);
}
|
@param {!Array<{src: string, path: string}>} sources
@param {!Array<{src: string, path: string}>} externs
|
ready
|
javascript
|
google/closure-compiler-js
|
cmd.js
|
https://github.com/google/closure-compiler-js/blob/master/cmd.js
|
Apache-2.0
|
function error(err) {
console.error(err);
process.exit(1);
}
|
@param {!Array<{src: string, path: string}>} sources
@param {!Array<{src: string, path: string}>} externs
|
error
|
javascript
|
google/closure-compiler-js
|
cmd.js
|
https://github.com/google/closure-compiler-js/blob/master/cmd.js
|
Apache-2.0
|
function caretPrefix(line, charNo) {
return line.substr(0, charNo).replace(/[^\t]/g, ' ');
}
|
@param {string} line to generate prefix for
@param {number} charNo to generate prefix at
@return {string} prefix for showing a caret
|
caretPrefix
|
javascript
|
google/closure-compiler-js
|
logger.js
|
https://github.com/google/closure-compiler-js/blob/master/logger.js
|
Apache-2.0
|
function fileFor(file) {
if (!file) { return null; }
// Filenames are the same across source and externs, so prefer source files.
for (const files of [options.jsCode, options.externs]) {
if (!files) { continue; }
for (const cand of files) {
if (cand.path == file) {
return cand;
}
}
}
return null;
}
|
@param {!Object} options
@param {!Object} output
@param {function(string)} logger
@return {boolean} Whether this output should fail a compilation.
|
fileFor
|
javascript
|
google/closure-compiler-js
|
logger.js
|
https://github.com/google/closure-compiler-js/blob/master/logger.js
|
Apache-2.0
|
function writemsg(color, msg) {
if (!msg.file && msg.lineNo < 0) {
logger(msg.type);
} else {
logger(`${msg.file}:${msg.lineNo} (${msg.type})`)
}
logger(msg.description);
const file = fileFor(msg.file);
if (file) {
const lines = file.src.split('\n'); // TODO(samthor): cache this for logger?
const line = lines[msg.lineNo - 1] || '';
logger(color + line + COLOR_END);
logger(COLOR_GREEN + caretPrefix(line, msg.charNo) + '^' + COLOR_END);
}
logger('');
}
|
@param {!Object} options
@param {!Object} output
@param {function(string)} logger
@return {boolean} Whether this output should fail a compilation.
|
writemsg
|
javascript
|
google/closure-compiler-js
|
logger.js
|
https://github.com/google/closure-compiler-js/blob/master/logger.js
|
Apache-2.0
|
function cleanupOptionKey(key) {
// replace "_foo" with "Foo"
key = key.replace(/_(\w)/g, match => match[1].toUpperCase());
// remove leading dashes
key = key.replace(/^--/, '');
return key;
}
|
Convert keys in the form "--foo_bar" or "zing_foo" to "fooBar" or "zingFoo", respectively.
@param {string} key to convert
@return {string}
|
cleanupOptionKey
|
javascript
|
google/closure-compiler-js
|
lib/gulp.js
|
https://github.com/google/closure-compiler-js/blob/master/lib/gulp.js
|
Apache-2.0
|
constructor(compilationOptions, pluginOptions) {
super({objectMode: true});
this.compilationOptions_ = compilationOptions;
this.pluginName_ = pluginOptions.pluginName || PLUGIN_NAME;
this.logger_ = pluginOptions.logger || (message => console.info(message));
this.fileList_ = [];
}
|
@return {function(Object<string>=, Object<string>=):Object}
|
constructor
|
javascript
|
google/closure-compiler-js
|
lib/gulp.js
|
https://github.com/google/closure-compiler-js/blob/master/lib/gulp.js
|
Apache-2.0
|
_transform(file, enc, cb) {
if (file.isNull()) {
// Ignore empty files.
} else if (file.isStream()) {
this.emit('error', new PluginError(this.pluginName_, 'Streaming not supported'));
} else {
this.fileList_.push(file);
}
cb();
}
|
@return {function(Object<string>=, Object<string>=):Object}
|
_transform
|
javascript
|
google/closure-compiler-js
|
lib/gulp.js
|
https://github.com/google/closure-compiler-js/blob/master/lib/gulp.js
|
Apache-2.0
|
_flush(cb) {
const options = {};
for (const k in this.compilationOptions_) {
options[cleanupOptionKey(k)] = this.compilationOptions_[k];
}
options.jsCode = (options.jsCode || []).concat(this.fileList_.map(file => {
return {
// TODO(samthor): It's not clear we always want to have modules rooted 'here'
path: path.relative(process.cwd(), file.path),
src: file.contents.toString(),
sourceMap: file.sourceMap ? JSON.stringify(file.sourceMap) : undefined,
};
}));
const outputFile = options.jsOutputFile;
delete options.jsOutputFile;
const output = compile(options);
if (logger(options, output, this.logger_)) {
const message = `Compilation error, ${output.errors.length} errors`;
this.emit('error', new PluginError(this.pluginName_, message));
}
const file = new File({
path: outputFile || DEFAULT_OUTPUT_PATH,
contents: new Buffer(output.compiledCode),
});
if (output.sourceMap) {
file.sourceMap = JSON.parse(output.sourceMap);
}
this.push(file);
cb();
}
|
@return {function(Object<string>=, Object<string>=):Object}
|
_flush
|
javascript
|
google/closure-compiler-js
|
lib/gulp.js
|
https://github.com/google/closure-compiler-js/blob/master/lib/gulp.js
|
Apache-2.0
|
constructor(plugin, message) {
this.plugin = plugin;
this.message = message;
}
|
@return {function(Object<string>=, Object<string>=):Object}
|
constructor
|
javascript
|
google/closure-compiler-js
|
lib/gulp.js
|
https://github.com/google/closure-compiler-js/blob/master/lib/gulp.js
|
Apache-2.0
|
function formatMessage(msg) {
let formatted = `(${msg.type}) ${msg.description}`;
if (msg.file && msg.lineNo >= 0) {
formatted = `${msg.file}:${msg.lineNo} ${formatted}`;
}
return formatted;
}
|
@fileoverview Webpack plugin for Closure Compiler.
|
formatMessage
|
javascript
|
google/closure-compiler-js
|
lib/webpack.js
|
https://github.com/google/closure-compiler-js/blob/master/lib/webpack.js
|
Apache-2.0
|
getDefaultProps() {
return {
horizontal : true,
pagingEnabled : true,
showsHorizontalScrollIndicator : false,
showsVerticalScrollIndicator : false,
bounces : false,
scrollsToTop : false,
removeClippedSubviews : true,
automaticallyAdjustContentInsets : false,
showsPagination : true,
showsButtons : false,
loop : true,
autoplay : false,
autoplayTimeout : 2.5,
autoplayDirection : true,
index : 0,
}
}
|
Default props
@return {object} props
@see http://facebook.github.io/react-native/docs/scrollview.html
|
getDefaultProps
|
javascript
|
stage88/react-weather
|
js/dependencies/swiper/index.js
|
https://github.com/stage88/react-weather/blob/master/js/dependencies/swiper/index.js
|
MIT
|
onScrollBegin(e) {
// update scroll state
this.setState({
isScrolling: true
})
this.setTimeout(() => {
this.props.onScrollBeginDrag && this.props.onScrollBeginDrag(e, this.state, this)
})
}
|
Scroll begin handle
@param {object} e native event
|
onScrollBegin
|
javascript
|
stage88/react-weather
|
js/dependencies/swiper/index.js
|
https://github.com/stage88/react-weather/blob/master/js/dependencies/swiper/index.js
|
MIT
|
onScrollEnd(e) {
// update scroll state
this.setState({
isScrolling: false
})
// making our events coming from android compatible to updateIndex logic
if (!e.nativeEvent.contentOffset) {
if (this.state.dir == 'x') {
e.nativeEvent.contentOffset = {x: e.nativeEvent.position * this.state.width}
} else {
e.nativeEvent.contentOffset = {y: e.nativeEvent.position * this.state.height}
}
}
this.updateIndex(e.nativeEvent.contentOffset, this.state.dir)
// Note: `this.setState` is async, so I call the `onMomentumScrollEnd`
// in setTimeout to ensure synchronous update `index`
this.setTimeout(() => {
this.autoplay()
// if `onMomentumScrollEnd` registered will be called here
this.props.onMomentumScrollEnd && this.props.onMomentumScrollEnd(e, this.state, this)
})
}
|
Scroll end handle
@param {object} e native event
|
onScrollEnd
|
javascript
|
stage88/react-weather
|
js/dependencies/swiper/index.js
|
https://github.com/stage88/react-weather/blob/master/js/dependencies/swiper/index.js
|
MIT
|
updateIndex(offset, dir) {
let state = this.state
let index = state.index
let diff = offset[dir] - state.offset[dir]
let step = dir == 'x' ? state.width : state.height
// Do nothing if offset no change.
if(index > 0 && !diff) {
return;
}
// Note: if touch very very quickly and continuous,
// the variation of `index` more than 1.
index = index + diff / step
if(this.props.loop) {
if(index <= -1) {
index = state.total - 1
offset[dir] = step * state.total
}
else if(index >= state.total) {
index = 0
offset[dir] = step
}
}
this.setState({
index: index,
offset: offset,
})
this.props.onSelectedIndexChange && this.props.onSelectedIndexChange(index, offset);
}
|
Update index after scroll
@param {object} offset content offset
@param {string} dir 'x' || 'y'
|
updateIndex
|
javascript
|
stage88/react-weather
|
js/dependencies/swiper/index.js
|
https://github.com/stage88/react-weather/blob/master/js/dependencies/swiper/index.js
|
MIT
|
scrollTo(index) {
if (this.state.isScrolling || this.state.total < 2) return
let state = this.state
let diff = (this.props.loop ? 1 : 0) + index + this.state.index
let x = 0
let y = 0
if(state.dir == 'x') x = diff * state.width
if(state.dir == 'y') y = diff * state.height
if (Platform.OS === 'android') {
this.refs.scrollView && this.refs.scrollView.setPage(diff)
} else {
this.refs.scrollView && this.refs.scrollView.scrollTo({
y: y,
x: x
})
}
// update scroll state
this.setState({
isScrolling: true,
autoplayEnd: false,
})
// trigger onScrollEnd manually in android
if (Platform.OS === 'android') {
this.setTimeout(() => {
this.onScrollEnd({
nativeEvent: {
position: diff,
}
});
}, 50);
}
}
|
Scroll by index
@param {number} index offset index
|
scrollTo
|
javascript
|
stage88/react-weather
|
js/dependencies/swiper/index.js
|
https://github.com/stage88/react-weather/blob/master/js/dependencies/swiper/index.js
|
MIT
|
renderPagination() {
// By default, dots only show when `total` > 2
if(this.state.total <= 1) return null
let dots = []
let ActiveDot = this.props.activeDot || <View style={{
backgroundColor: '#007aff',
width: 8,
height: 8,
borderRadius: 4,
marginLeft: 3,
marginRight: 3,
marginTop: 3,
marginBottom: 3,
}} />;
let Dot = this.props.dot || <View style={{
backgroundColor:'rgba(0,0,0,.2)',
width: 8,
height: 8,
borderRadius: 4,
marginLeft: 3,
marginRight: 3,
marginTop: 3,
marginBottom: 3,
}} />;
for(let i = 0; i < this.state.total; i++) {
dots.push(i === this.state.index
?
React.cloneElement(ActiveDot, {key: i})
:
React.cloneElement(Dot, {key: i})
)
}
return (
<View pointerEvents='none' style={[styles['pagination_' + this.state.dir], this.props.paginationStyle]}>
{dots}
</View>
)
}
|
Render pagination
@return {object} react-dom
|
renderPagination
|
javascript
|
stage88/react-weather
|
js/dependencies/swiper/index.js
|
https://github.com/stage88/react-weather/blob/master/js/dependencies/swiper/index.js
|
MIT
|
renderTitle() {
let child = this.props.children[this.state.index]
let title = child && child.props.title
return title
? (
<View style={styles.title}>
{this.props.children[this.state.index].props.title}
</View>
)
: null
}
|
Render pagination
@return {object} react-dom
|
renderTitle
|
javascript
|
stage88/react-weather
|
js/dependencies/swiper/index.js
|
https://github.com/stage88/react-weather/blob/master/js/dependencies/swiper/index.js
|
MIT
|
renderButtons() {
return (
<View pointerEvents='box-none' style={[styles.buttonWrapper, {width: this.state.width, height: this.state.height}, this.props.buttonWrapperStyle]}>
{this.renderPrevButton()}
{this.renderNextButton()}
</View>
)
}
|
Render pagination
@return {object} react-dom
|
renderButtons
|
javascript
|
stage88/react-weather
|
js/dependencies/swiper/index.js
|
https://github.com/stage88/react-weather/blob/master/js/dependencies/swiper/index.js
|
MIT
|
renderScrollView(pages) {
if (Platform.OS === 'ios')
return (
<ScrollView ref="scrollView"
{...this.props}
contentContainerStyle={[styles.wrapper, this.props.style]}
contentOffset={this.state.offset}
onScrollBeginDrag={this.onScrollBegin}
onMomentumScrollEnd={this.onScrollEnd}>
{pages}
</ScrollView>
);
return (
<ViewPagerAndroid ref="scrollView"
{...this.props}
initialPage={this.state.index}
onPageSelected={this.onScrollEnd}
style={{flex: 1}}>
{pages}
</ViewPagerAndroid>
);
}
|
Render pagination
@return {object} react-dom
|
renderScrollView
|
javascript
|
stage88/react-weather
|
js/dependencies/swiper/index.js
|
https://github.com/stage88/react-weather/blob/master/js/dependencies/swiper/index.js
|
MIT
|
injectState(props) {
/* const scrollResponders = [
'onMomentumScrollBegin',
'onTouchStartCapture',
'onTouchStart',
'onTouchEnd',
'onResponderRelease',
]*/
for(let prop in props) {
// if(~scrollResponders.indexOf(prop)
if(typeof props[prop] === 'function'
&& prop !== 'onMomentumScrollEnd'
&& prop !== 'renderPagination'
&& prop !== 'onScrollBeginDrag'
&& prop !== 'onScroll'
) {
let originResponder = props[prop]
props[prop] = (e) => originResponder(e, this.state, this)
}
}
return props
}
|
Inject state to ScrollResponder
@param {object} props origin props
@return {object} props injected props
|
injectState
|
javascript
|
stage88/react-weather
|
js/dependencies/swiper/index.js
|
https://github.com/stage88/react-weather/blob/master/js/dependencies/swiper/index.js
|
MIT
|
render() {
let state = this.state
let props = this.props
let children = props.children
let index = state.index
let total = state.total
let loop = props.loop
let dir = state.dir
let key = 0
let pages = []
let pageStyle = [{width: state.width, height: state.height}, styles.slide]
// For make infinite at least total > 1
if(total > 1) {
// Re-design a loop model for avoid img flickering
pages = Object.keys(children)
if(loop) {
pages.unshift(total - 1)
pages.push(0)
}
pages = pages.map((page, i) =>
<View style={pageStyle} key={i}>{children[page]}</View>
)
}
else pages = <View style={pageStyle}>{children}</View>
return (
<View style={[styles.container, {
width: state.width,
height: state.height
}]}>
{this.renderScrollView(pages)}
{props.showsPagination && (props.renderPagination
? this.props.renderPagination(state.index, state.total, this)
: this.renderPagination())}
{this.renderTitle()}
{this.props.showsButtons && this.renderButtons()}
</View>
)
}
|
Default render
@return {object} react-dom
|
render
|
javascript
|
stage88/react-weather
|
js/dependencies/swiper/index.js
|
https://github.com/stage88/react-weather/blob/master/js/dependencies/swiper/index.js
|
MIT
|
getInitialState = () =>
// For our initial server render, we won't know if the user
// prefers reduced motion, but it doesn't matter. This value
// will be overwritten on the client, before any animations
// occur.
isRenderingOnServer ? true : !window.matchMedia(QUERY).matches
|
https://www.joshwcomeau.com/snippets/react-hooks/use-prefers-reduced-motion/
|
getInitialState
|
javascript
|
bchiang7/v4
|
src/hooks/usePrefersReducedMotion.js
|
https://github.com/bchiang7/v4/blob/master/src/hooks/usePrefersReducedMotion.js
|
MIT
|
getInitialState = () =>
// For our initial server render, we won't know if the user
// prefers reduced motion, but it doesn't matter. This value
// will be overwritten on the client, before any animations
// occur.
isRenderingOnServer ? true : !window.matchMedia(QUERY).matches
|
https://www.joshwcomeau.com/snippets/react-hooks/use-prefers-reduced-motion/
|
getInitialState
|
javascript
|
bchiang7/v4
|
src/hooks/usePrefersReducedMotion.js
|
https://github.com/bchiang7/v4/blob/master/src/hooks/usePrefersReducedMotion.js
|
MIT
|
function usePrefersReducedMotion() {
const [prefersReducedMotion, setPrefersReducedMotion] = useState(getInitialState);
useEffect(() => {
const mediaQueryList = window.matchMedia(QUERY);
const listener = event => {
setPrefersReducedMotion(!event.matches);
};
mediaQueryList.addListener(listener);
return () => {
mediaQueryList.removeListener(listener);
};
}, []);
return prefersReducedMotion;
}
|
https://www.joshwcomeau.com/snippets/react-hooks/use-prefers-reduced-motion/
|
usePrefersReducedMotion
|
javascript
|
bchiang7/v4
|
src/hooks/usePrefersReducedMotion.js
|
https://github.com/bchiang7/v4/blob/master/src/hooks/usePrefersReducedMotion.js
|
MIT
|
function LoggerFactory(options) {
options = options || {
prefix: true
};
// If `console.log` is not accessible, `log` is a noop.
if (
typeof console !== 'object' ||
typeof console.log !== 'function' ||
typeof console.log.bind !== 'function'
) {
return function noop() {};
}
return function log() {
var args = Array.prototype.slice.call(arguments);
// All logs are disabled when `io.sails.environment = 'production'`.
if (io.sails.environment === 'production') return;
// Add prefix to log messages (unless disabled)
var PREFIX = '';
if (options.prefix) {
args.unshift(PREFIX);
}
// Call wrapped logger
console.log
.bind(console)
.apply(this, args);
};
}//</LoggerFactory>
|
The JWR (JSON WebSocket Response) received from a Sails server.
@api public
@param {Object} responseCtx
=> :body
=> :statusCode
=> :headers
@constructor
|
LoggerFactory
|
javascript
|
CodeGenieApp/serverless-express
|
examples/sails-example/assets/dependencies/sails.io.js
|
https://github.com/CodeGenieApp/serverless-express/blob/master/examples/sails-example/assets/dependencies/sails.io.js
|
Apache-2.0
|
function _emitFrom(socket, requestCtx) {
if (!socket._raw) {
throw new Error('Failed to emit from socket- raw SIO socket is missing.');
}
// Since callback is embedded in requestCtx,
// retrieve it and delete the key before continuing.
var cb = requestCtx.cb;
delete requestCtx.cb;
// Name of the appropriate socket.io listener on the server
// ( === the request method or "verb", e.g. 'get', 'post', 'put', etc. )
var sailsEndpoint = requestCtx.method;
socket._raw.emit(sailsEndpoint, requestCtx, function serverResponded(responseCtx) {
// Send back (emulatedHTTPBody, jsonWebSocketResponse)
if (cb && !requestCtx.calledCb) {
cb(responseCtx.body, new JWR(responseCtx));
// Set flag indicating that callback was called, to avoid duplicate calls.
requestCtx.calledCb = true;
// Remove the callback from the list.
socket._responseCbs.splice(socket._responseCbs.indexOf(cb), 1);
// Remove the context from the list.
socket._requestCtxs.splice(socket._requestCtxs.indexOf(requestCtx), 1);
}
});
}
|
`SailsSocket.prototype._connect()`
Begin connecting this socket to the server.
@api private
|
_emitFrom
|
javascript
|
CodeGenieApp/serverless-express
|
examples/sails-example/assets/dependencies/sails.io.js
|
https://github.com/CodeGenieApp/serverless-express/blob/master/examples/sails-example/assets/dependencies/sails.io.js
|
Apache-2.0
|
function isObject (item) {
return (item && typeof item === 'object' && !Array.isArray(item))
}
|
Simple object check.
@param item
@returns {boolean}
|
isObject
|
javascript
|
CodeGenieApp/serverless-express
|
jest-helpers/merge-deep.js
|
https://github.com/CodeGenieApp/serverless-express/blob/master/jest-helpers/merge-deep.js
|
Apache-2.0
|
constructor(wsInstance) {
/**
* @type {WebSlides}
* @private
*/
this.ws_ = wsInstance;
this.enable_ = false;
this.init_();
this.bindEvent_();
}
|
@param {WebSlides} wsInstance The WebSlides instance
@constructor
|
constructor
|
javascript
|
ksky521/nodeppt
|
packages/nodeppt-js/plugins/keyboard.js
|
https://github.com/ksky521/nodeppt/blob/master/packages/nodeppt-js/plugins/keyboard.js
|
MIT
|
onKeyPress_(event) {
let method;
let argument;
if (DOM.isFocusableElement() || this.ws_.isDisabled()) {
return;
}
switch (event.which) {
case Keys.AV_PAGE:
method = this.enable_ ? this.goNext : this.ws_.goNext;
break;
case Keys.SPACE:
if (event.shiftKey) {
method = this.enable_ ? this.goPrev : this.ws_.goPrev;
} else {
method = this.enable_ ? this.goNext : this.ws_.goNext;
}
break;
case Keys.RE_PAGE:
method = this.enable_ ? this.goPrev : this.ws_.goPrev;
break;
case Keys.HOME:
method = this.ws_.goToSlide;
argument = 0;
break;
case Keys.END:
method = this.ws_.goToSlide;
argument = this.ws_.maxSlide_ - 1;
break;
case Keys.DOWN:
method = this.ws_.isVertical ? (this.enable_ ? this.goNext : this.ws_.goNext) : null;
break;
case Keys.UP:
method = this.ws_.isVertical ? (this.enable_ ? this.goPrev : this.ws_.goPrev) : null;
break;
case Keys.RIGHT:
method = !this.ws_.isVertical ? (this.enable_ ? this.goNext : this.ws_.goNext) : null;
break;
case Keys.LEFT:
method = !this.ws_.isVertical ? (this.enable_ ? this.goPrev : this.ws_.goPrev) : null;
break;
case Keys.F:
if (!event.metaKey && !event.ctrlKey) {
method = this.ws_.fullscreen;
}
break;
}
if (method) {
method.call(this.enable_ ? this : this.ws_, argument);
// Prevents Firefox key events.
event.preventDefault();
}
}
|
Reacts to the keydown event. It reacts to the arrows and space key
depending on the layout of the page.
@param {KeyboardEvent} event The key event.
@private
|
onKeyPress_
|
javascript
|
ksky521/nodeppt
|
packages/nodeppt-js/plugins/keyboard.js
|
https://github.com/ksky521/nodeppt/blob/master/packages/nodeppt-js/plugins/keyboard.js
|
MIT
|
function toArray(arrayLike) {
return emptyArr.slice.call(arrayLike);
}
|
Reacts to the keydown event. It reacts to the arrows and space key
depending on the layout of the page.
@param {KeyboardEvent} event The key event.
@private
|
toArray
|
javascript
|
ksky521/nodeppt
|
packages/nodeppt-js/plugins/keyboard.js
|
https://github.com/ksky521/nodeppt/blob/master/packages/nodeppt-js/plugins/keyboard.js
|
MIT
|
function applyClass(token) {
// init attributes
token.attrs = token.attrs || [];
// get index of class attribute
let keys = token.attrs.map(arr => arr[0]);
let idx = keys.indexOf('class');
if (idx === -1) {
// Add class attribute if not defined
token.attrs.push(['class', className]);
} else {
// Get the current class list to append.
// Watch out for duplicates
let classStr = token.attrs[idx][1] || '';
let classList = classStr.split(' ');
// Add the class if we don't already have it
if (classList.indexOf(className) === -1) {
token.attrs[idx][1] = classStr += ' ' + className;
}
}
}
|
Adds class to token
@param {any} token
@param {string} className
|
applyClass
|
javascript
|
ksky521/nodeppt
|
packages/nodeppt-parser/lib/markdown/plus-list.js
|
https://github.com/ksky521/nodeppt/blob/master/packages/nodeppt-parser/lib/markdown/plus-list.js
|
MIT
|
function loadPrismLang(lang) {
if (!lang) return undefined;
let langObject = Prism.languages[lang];
if (langObject === undefined) {
try {
require('prismjs/components/index')([lang]);
return Prism.languages[lang];
} catch (e) {
// nothing to do
}
}
return langObject;
}
|
Loads the provided {@code lang} into prism.
@param {String} lang
Code of the language to load.
@return {Object} The Prism language object for the provided {@code lang} code. {@code undefined} if the language is not known to Prism.
|
loadPrismLang
|
javascript
|
ksky521/nodeppt
|
packages/nodeppt-parser/lib/markdown/prism.js
|
https://github.com/ksky521/nodeppt/blob/master/packages/nodeppt-parser/lib/markdown/prism.js
|
MIT
|
function loadPrismPlugin(name) {
try {
require(`prismjs/plugins/${name}/prism-${name}`);
} catch (e) {
throw new Error(`Cannot load Prism plugin "${name}". Please check the spelling.`);
}
}
|
Loads the provided Prism plugin.a
@param name
Name of the plugin to load
@throws {Error} If there is no plugin with the provided {@code name}
|
loadPrismPlugin
|
javascript
|
ksky521/nodeppt
|
packages/nodeppt-parser/lib/markdown/prism.js
|
https://github.com/ksky521/nodeppt/blob/master/packages/nodeppt-parser/lib/markdown/prism.js
|
MIT
|
function selectLanguage(options, lang) {
let langToUse = lang;
if (langToUse === '' && options.defaultLanguageForUnspecified !== undefined) {
langToUse = options.defaultLanguageForUnspecified;
}
let prismLang = loadPrismLang(langToUse);
if (prismLang === undefined && options.defaultLanguageForUnknown !== undefined) {
langToUse = options.defaultLanguageForUnknown;
prismLang = loadPrismLang(langToUse);
}
return [langToUse, prismLang];
}
|
Select the language to use for highlighting, based on the provided options and the specified language.
@param {Object} options
The options that were used to initialise the plugin.
@param {String} lang
Code of the language to highlight the text in.
@return {Array} An array where the first element is the name of the language to use, and the second element is the PRISM language object for that language.
|
selectLanguage
|
javascript
|
ksky521/nodeppt
|
packages/nodeppt-parser/lib/markdown/prism.js
|
https://github.com/ksky521/nodeppt/blob/master/packages/nodeppt-parser/lib/markdown/prism.js
|
MIT
|
function checkLanguageOption(options, optionName) {
const language = options[optionName];
if (language !== undefined && loadPrismLang(language) === undefined) {
throw new Error(`Bad option ${optionName}: There is no Prism language '${language}'.`);
}
}
|
Checks whether an option represents a valid Prism language
@param {MarkdownItPrismOptions} options
The options that have been used to initialise the plugin.
@param optionName
The key of the option insides {@code options} that shall be checked.
@throws {Error} If the option is not set to a valid Prism language.
|
checkLanguageOption
|
javascript
|
ksky521/nodeppt
|
packages/nodeppt-parser/lib/markdown/prism.js
|
https://github.com/ksky521/nodeppt/blob/master/packages/nodeppt-parser/lib/markdown/prism.js
|
MIT
|
function test(tokens, i, t) {
let res = {
match: false,
j: null // position of child
};
let ii = t.shift !== undefined ? i + t.shift : t.position;
let token = get(tokens, ii); // supports negative ii
if (token === undefined) {
return res;
}
for (let key in t) {
if (key === 'shift' || key === 'position') {
continue;
}
if (token[key] === undefined) {
return res;
}
if (key === 'children' && isArrayOfObjects(t.children)) {
if (token.children.length === 0) {
return res;
}
let match;
let childTests = t.children;
let children = token.children;
if (childTests.every(tt => tt.position !== undefined)) {
// positions instead of shifts, do not loop all children
match = childTests.every(tt => test(children, tt.position, tt).match);
if (match) {
// we may need position of child in transform
let j = last(childTests).position;
res.j = j >= 0 ? j : children.length + j;
}
} else {
for (let j = 0; j < children.length; j++) {
match = childTests.every(tt => test(children, j, tt).match);
if (match) {
res.j = j;
// all tests true, continue with next key of pattern t
break;
}
}
}
if (match === false) {
return res;
}
continue;
}
switch (typeof t[key]) {
case 'boolean':
case 'number':
case 'string':
if (token[key] !== t[key]) {
return res;
}
break;
case 'function':
if (!t[key](token[key])) {
return res;
}
break;
case 'object':
if (isArrayOfFunctions(t[key])) {
let r = t[key].every(tt => tt(token[key]));
if (r === false) {
return res;
}
break;
}
// fall through for objects !== arrays of functions
default:
throw new Error(
`Unknown type of pattern test (key: ${key}). Test should be of type boolean, number, string, function or array of functions.`
);
}
}
// no tests returned false -> all tests returns true
res.match = true;
return res;
}
|
Test if t matches token stream.
@param {array} tokens
@param {number} i
@param {object} t Test to match.
@return {object} { match: true|false, j: null|number }
|
test
|
javascript
|
ksky521/nodeppt
|
packages/nodeppt-parser/lib/markdown/attrs/index.js
|
https://github.com/ksky521/nodeppt/blob/master/packages/nodeppt-parser/lib/markdown/attrs/index.js
|
MIT
|
function isArrayOfObjects(arr) {
return Array.isArray(arr) && arr.length && arr.every(i => typeof i === 'object');
}
|
Test if t matches token stream.
@param {array} tokens
@param {number} i
@param {object} t Test to match.
@return {object} { match: true|false, j: null|number }
|
isArrayOfObjects
|
javascript
|
ksky521/nodeppt
|
packages/nodeppt-parser/lib/markdown/attrs/index.js
|
https://github.com/ksky521/nodeppt/blob/master/packages/nodeppt-parser/lib/markdown/attrs/index.js
|
MIT
|
function isArrayOfFunctions(arr) {
return Array.isArray(arr) && arr.length && arr.every(i => typeof i === 'function');
}
|
Test if t matches token stream.
@param {array} tokens
@param {number} i
@param {object} t Test to match.
@return {object} { match: true|false, j: null|number }
|
isArrayOfFunctions
|
javascript
|
ksky521/nodeppt
|
packages/nodeppt-parser/lib/markdown/attrs/index.js
|
https://github.com/ksky521/nodeppt/blob/master/packages/nodeppt-parser/lib/markdown/attrs/index.js
|
MIT
|
function get(arr, n) {
return n >= 0 ? arr[n] : arr[arr.length + n];
}
|
Get n item of array. Supports negative n, where -1 is last
element in array.
@param {array} arr
@param {number} n
|
get
|
javascript
|
ksky521/nodeppt
|
packages/nodeppt-parser/lib/markdown/attrs/index.js
|
https://github.com/ksky521/nodeppt/blob/master/packages/nodeppt-parser/lib/markdown/attrs/index.js
|
MIT
|
function last(arr) {
return arr.slice(-1)[0] || {};
}
|
Get n item of array. Supports negative n, where -1 is last
element in array.
@param {array} arr
@param {number} n
|
last
|
javascript
|
ksky521/nodeppt
|
packages/nodeppt-parser/lib/markdown/attrs/index.js
|
https://github.com/ksky521/nodeppt/blob/master/packages/nodeppt-parser/lib/markdown/attrs/index.js
|
MIT
|
function escapeRegExp(s) {
return s.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&');
}
|
Escapes special characters in string s such that the string
can be used in `new RegExp`. For example "[" becomes "\\[".
@param {string} s Regex string.
@return {string} Escaped string.
|
escapeRegExp
|
javascript
|
ksky521/nodeppt
|
packages/nodeppt-parser/lib/markdown/attrs/utils.js
|
https://github.com/ksky521/nodeppt/blob/master/packages/nodeppt-parser/lib/markdown/attrs/utils.js
|
MIT
|
function replaceUnsafeChar(ch) {
return HTML_REPLACEMENTS[ch];
}
|
from https://github.com/markdown-it/markdown-it/blob/master/lib/common/utils.js
|
replaceUnsafeChar
|
javascript
|
ksky521/nodeppt
|
packages/nodeppt-parser/lib/markdown/attrs/utils.js
|
https://github.com/ksky521/nodeppt/blob/master/packages/nodeppt-parser/lib/markdown/attrs/utils.js
|
MIT
|
resolve(p) {
return path.resolve(this.service.context, p);
}
|
Resolve path for a project.
@param {string} p - Relative path from project root
@return {string} The resolved absolute path.
|
resolve
|
javascript
|
ksky521/nodeppt
|
packages/nodeppt-serve/PluginAPI.js
|
https://github.com/ksky521/nodeppt/blob/master/packages/nodeppt-serve/PluginAPI.js
|
MIT
|
registerCommand(name, opts, fn) {
if (typeof opts === 'function') {
fn = opts;
opts = null;
}
this.service.commands[name] = {fn, opts: opts || {}};
}
|
Resolve path for a project.
@param {string} p - Relative path from project root
@return {string} The resolved absolute path.
|
registerCommand
|
javascript
|
ksky521/nodeppt
|
packages/nodeppt-serve/PluginAPI.js
|
https://github.com/ksky521/nodeppt/blob/master/packages/nodeppt-serve/PluginAPI.js
|
MIT
|
resolveWebpackConfig(chainableConfig) {
return this.service.resolveWebpackConfig(chainableConfig);
}
|
Resolve path for a project.
@param {string} p - Relative path from project root
@return {string} The resolved absolute path.
|
resolveWebpackConfig
|
javascript
|
ksky521/nodeppt
|
packages/nodeppt-serve/PluginAPI.js
|
https://github.com/ksky521/nodeppt/blob/master/packages/nodeppt-serve/PluginAPI.js
|
MIT
|
get value() {
return this.state.selected
}
|
Get the value of checked Checkbox in CheckboxGroup. Often use in form.
@returns {Array}
|
value
|
javascript
|
invertase/react-native-material-design
|
lib/CheckboxGroup.js
|
https://github.com/invertase/react-native-material-design/blob/master/lib/CheckboxGroup.js
|
MIT
|
function getColor(string) {
if (string) {
if (string.indexOf('#') > -1 || string.indexOf('rgba') > -1) {
return string;
}
if (COLOR[string]) {
return COLOR[string].color;
}
if (COLOR[`${string}500`]) {
return COLOR[`${string}500`].color;
}
}
return COLOR[`${PRIMARY}500`].color;
}
|
Detect whether a color is a hex code/rgba or a paper element style
@param string
@returns {*}
|
getColor
|
javascript
|
invertase/react-native-material-design
|
lib/helpers.js
|
https://github.com/invertase/react-native-material-design/blob/master/lib/helpers.js
|
MIT
|
function isCompatible(feature) {
const version = Platform.Version;
switch (feature) {
case 'TouchableNativeFeedback':
return version >= 21;
break;
case 'elevation':
return version >= 21;
break;
default:
return true;
break;
}
}
|
Detect whether a specific feature is compatible with the device
@param feature
@returns bool
|
isCompatible
|
javascript
|
invertase/react-native-material-design
|
lib/helpers.js
|
https://github.com/invertase/react-native-material-design/blob/master/lib/helpers.js
|
MIT
|
get value() {
return this.state.selected
}
|
Get the value of checked RadioButton in RadioButtonGroup. Often use in form.
@returns {string}
|
value
|
javascript
|
invertase/react-native-material-design
|
lib/RadioButtonGroup.js
|
https://github.com/invertase/react-native-material-design/blob/master/lib/RadioButtonGroup.js
|
MIT
|
function configure(dataset, options) {
var override = dataset.datalabels;
var listeners = {};
var configs = [];
var labels, keys;
if (override === false) {
return null;
}
if (override === true) {
override = {};
}
options = merge({}, [options, override]);
labels = options.labels || {};
keys = Object.keys(labels);
delete options.labels;
if (keys.length) {
keys.forEach(function(key) {
if (labels[key]) {
configs.push(merge({}, [
options,
labels[key],
{_key: key}
]));
}
});
} else {
// Default label if no "named" label defined.
configs.push(options);
}
// listeners: {<event-type>: {<label-key>: <fn>}}
listeners = configs.reduce(function(target, config) {
each(config.listeners || {}, function(fn, event) {
target[event] = target[event] || {};
target[event][config._key || DEFAULT_KEY] = fn;
});
delete config.listeners;
return target;
}, {});
return {
labels: configs,
listeners: listeners
};
}
|
@see https://github.com/chartjs/Chart.js/issues/4176
|
configure
|
javascript
|
chartjs/chartjs-plugin-datalabels
|
src/plugin.js
|
https://github.com/chartjs/chartjs-plugin-datalabels/blob/master/src/plugin.js
|
MIT
|
function dispatchEvent(chart, listeners, label, event) {
if (!listeners) {
return;
}
var context = label.$context;
var groups = label.$groups;
var callback;
if (!listeners[groups._set]) {
return;
}
callback = listeners[groups._set][groups._key];
if (!callback) {
return;
}
if (callbackHelper(callback, [context, event]) === true) {
// Users are allowed to tweak the given context by injecting values that can be
// used in scriptable options to display labels differently based on the current
// event (e.g. highlight an hovered label). That's why we update the label with
// the output context and schedule a new chart render by setting it dirty.
chart[EXPANDO_KEY]._dirty = true;
label.update(context);
}
}
|
@see https://github.com/chartjs/Chart.js/issues/4176
|
dispatchEvent
|
javascript
|
chartjs/chartjs-plugin-datalabels
|
src/plugin.js
|
https://github.com/chartjs/chartjs-plugin-datalabels/blob/master/src/plugin.js
|
MIT
|
function dispatchMoveEvents(chart, listeners, previous, label, event) {
var enter, leave;
if (!previous && !label) {
return;
}
if (!previous) {
enter = true;
} else if (!label) {
leave = true;
} else if (previous !== label) {
leave = enter = true;
}
if (leave) {
dispatchEvent(chart, listeners.leave, previous, event);
}
if (enter) {
dispatchEvent(chart, listeners.enter, label, event);
}
}
|
@see https://github.com/chartjs/Chart.js/issues/4176
|
dispatchMoveEvents
|
javascript
|
chartjs/chartjs-plugin-datalabels
|
src/plugin.js
|
https://github.com/chartjs/chartjs-plugin-datalabels/blob/master/src/plugin.js
|
MIT
|
function handleMoveEvents(chart, event) {
var expando = chart[EXPANDO_KEY];
var listeners = expando._listeners;
var previous, label;
if (!listeners.enter && !listeners.leave) {
return;
}
if (event.type === 'mousemove') {
label = layout.lookup(expando._labels, event);
} else if (event.type !== 'mouseout') {
return;
}
previous = expando._hovered;
expando._hovered = label;
dispatchMoveEvents(chart, listeners, previous, label, event);
}
|
@see https://github.com/chartjs/Chart.js/issues/4176
|
handleMoveEvents
|
javascript
|
chartjs/chartjs-plugin-datalabels
|
src/plugin.js
|
https://github.com/chartjs/chartjs-plugin-datalabels/blob/master/src/plugin.js
|
MIT
|
function handleClickEvents(chart, event) {
var expando = chart[EXPANDO_KEY];
var handlers = expando._listeners.click;
var label = handlers && layout.lookup(expando._labels, event);
if (label) {
dispatchEvent(chart, handlers, label, event);
}
}
|
@see https://github.com/chartjs/Chart.js/issues/4176
|
handleClickEvents
|
javascript
|
chartjs/chartjs-plugin-datalabels
|
src/plugin.js
|
https://github.com/chartjs/chartjs-plugin-datalabels/blob/master/src/plugin.js
|
MIT
|
function url() {
return 'http://localhost:3000/examples/detached-dom';
}
|
The initial `url` of the scenario we would like to run.
|
url
|
javascript
|
facebook/memlab
|
packages/e2e/static/example/scenarios/detached-dom.js
|
https://github.com/facebook/memlab/blob/master/packages/e2e/static/example/scenarios/detached-dom.js
|
MIT
|
async function action(page) {
const elements = await page.$x(
"//button[contains(., 'Create detached DOMs')]",
);
const [button] = elements;
if (button) {
await button.click();
}
// clean up external references from memlab
await Promise.all(elements.map(e => e.dispose()));
}
|
Specify how memlab should perform action that you want
to test whether the action is causing memory leak.
@param page - Puppeteer's page object:
https://pptr.dev/api/puppeteer.page/
|
action
|
javascript
|
facebook/memlab
|
packages/e2e/static/example/scenarios/detached-dom.js
|
https://github.com/facebook/memlab/blob/master/packages/e2e/static/example/scenarios/detached-dom.js
|
MIT
|
async function back(page) {
await page.click('a[href="/"]');
}
|
Specify how memlab should perform action that would
reset the action you performed above.
@param page - Puppeteer's page object:
https://pptr.dev/api/puppeteer.page/
|
back
|
javascript
|
facebook/memlab
|
packages/e2e/static/example/scenarios/detached-dom.js
|
https://github.com/facebook/memlab/blob/master/packages/e2e/static/example/scenarios/detached-dom.js
|
MIT
|
function registerTwoPhaseEvent(registrationName, dependencies) {
registerDirectEvent(registrationName, dependencies);
registerDirectEvent(registrationName + 'Capture', dependencies);
}
|
Mapping from lowercase registration names to the properly cased version,
used to warn in the case of missing event handlers. Available
only in true.
@type {Object}
|
registerTwoPhaseEvent
|
javascript
|
facebook/memlab
|
packages/lens/src/tests/lib/react-dom-v18.dev.js
|
https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-dom-v18.dev.js
|
MIT
|
function registerDirectEvent(registrationName, dependencies) {
{
if (registrationNameDependencies[registrationName]) {
error('EventRegistry: More than one plugin attempted to publish the same ' + 'registration name, `%s`.', registrationName);
}
}
registrationNameDependencies[registrationName] = dependencies;
{
var lowerCasedName = registrationName.toLowerCase();
possibleRegistrationNames[lowerCasedName] = registrationName;
if (registrationName === 'onDoubleClick') {
possibleRegistrationNames.ondblclick = registrationName;
}
}
for (var i = 0; i < dependencies.length; i++) {
allNativeEvents.add(dependencies[i]);
}
}
|
Mapping from lowercase registration names to the properly cased version,
used to warn in the case of missing event handlers. Available
only in true.
@type {Object}
|
registerDirectEvent
|
javascript
|
facebook/memlab
|
packages/lens/src/tests/lib/react-dom-v18.dev.js
|
https://github.com/facebook/memlab/blob/master/packages/lens/src/tests/lib/react-dom-v18.dev.js
|
MIT
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.