code stringlengths 28 313k | docstring stringlengths 25 85.3k | func_name stringlengths 1 74 | language stringclasses 1
value | repo stringlengths 5 60 | path stringlengths 4 172 | url stringlengths 44 218 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
update(id, updatedConnection) {
let _this = this;
let connections;
return new Promise((resolve, reject) => {
if (!id) return reject(new errors.InvalidArugmentError('id is required'));
if (!updatedConnection) return reject(new errors.InvalidArugmentError('updatedConnection is required'));
... | Update a connection by id
@param {string} id - id of the connection to update
@param {object} updates - hash of updates to apply to the connection
@param {string} [updates.name] - connection name
@param {string} [updates.host] - Connection host
@param {string} [updates.port ]- Connection port
@param {string} [updates.d... | update | javascript | officert/mongotron | src/lib/modules/connection/repository.js | https://github.com/officert/mongotron/blob/master/src/lib/modules/connection/repository.js | MIT |
delete(id) {
var _this = this;
return new Promise((resolve, reject) => {
if (!id) return reject(new errors.InvalidArugmentError('id is required'));
return _this.list()
.then((connections) => {
return findConnectionById(id, connections)
.then(function(connection) {
... | Delete a connection by id
@param {string} id - id of the connection to delete | delete | javascript | officert/mongotron | src/lib/modules/connection/repository.js | https://github.com/officert/mongotron/blob/master/src/lib/modules/connection/repository.js | MIT |
existsByName(name) {
var _this = this;
return _this.list()
.then((connections) => {
return new Promise((resolve) => {
var existingConnection = _.findWhere(connections, {
name: name
});
return resolve(existingConnection ? true : false);
});
}... | Check if a connection exists by name
@param {String} name | existsByName | javascript | officert/mongotron | src/lib/modules/connection/repository.js | https://github.com/officert/mongotron/blob/master/src/lib/modules/connection/repository.js | MIT |
function _applyConnectionUpdatesPreValidation(connection, updates) {
return new Promise((resolve) => {
if ('name' in updates) connection.name = updates.name;
if ('host' in updates) {
connection.host = updates.host;
delete connection.replicaSet;
if (mongoUtils.isLocalHost(updates.host)) {
... | Validate updates to a connection
@param {Connection} connection - connection instance
@param {object} updates - hash of updates to apply to validate
@private | _applyConnectionUpdatesPreValidation | javascript | officert/mongotron | src/lib/modules/connection/service.js | https://github.com/officert/mongotron/blob/master/src/lib/modules/connection/service.js | MIT |
validateCreate(data) {
return new Promise((resolve, reject) => {
_baseValidate(data)
.then(resolve)
.catch(reject);
});
} | Validate a connection for creating
@param {object} data | validateCreate | javascript | officert/mongotron | src/lib/modules/connection/validator.js | https://github.com/officert/mongotron/blob/master/src/lib/modules/connection/validator.js | MIT |
validateUpdate(data) {
return new Promise((resolve, reject) => {
_baseValidate(data)
.then(resolve)
.catch(reject);
});
} | Validate a connection for updating
@param {object} data | validateUpdate | javascript | officert/mongotron | src/lib/modules/connection/validator.js | https://github.com/officert/mongotron/blob/master/src/lib/modules/connection/validator.js | MIT |
evaluate(expression, scope) {
return new Promise((resolve, reject) => {
if (!expression) return reject(new Error('Expression - eval() - expression is required'));
let astTokens = esprima.tokenize(expression);
let startTime = process.hrtime();
_eval(expression, scope)
.then(result ... | evaluate a JS expression
@param {String} expression
@param {Object} [scope] - a customized scope that the expression will be evaluated in
@returns Promise | evaluate | javascript | officert/mongotron | src/lib/modules/expression/index.js | https://github.com/officert/mongotron/blob/master/src/lib/modules/expression/index.js | MIT |
function _eval(expression, scope) {
return new Promise((resolve, reject) => {
if (!expression) return reject(new Error('evaluator - eval() - must pass an expression'));
if (!_.isString(expression)) return reject(new Error('evaluator - eval() - expression must be a string'));
var evalScope = {
Objec... | @private
@param {String} expression
@param {Object} scope | _eval | javascript | officert/mongotron | src/lib/modules/expression/index.js | https://github.com/officert/mongotron/blob/master/src/lib/modules/expression/index.js | MIT |
function parseKeybindingsFileData(data) {
return new Promise((resolve, reject) => {
if (!data || !_.isArray(data)) return reject(new Error('keybindings - list() - error parsing keybindings file data'));
//TODO: should we group these by context name to avoid duplicates??
var commands = [];
_.each(da... | @function parseKeybindingsFileData
@private
@param {Object} data - raw contexts from keybindings file | parseKeybindingsFileData | javascript | officert/mongotron | src/lib/modules/keybindings/index.js | https://github.com/officert/mongotron/blob/master/src/lib/modules/keybindings/index.js | MIT |
changeActive(themeName) {
var _this = this;
var newActiveTheme;
if (!themeName) return Promise.reject(new Error('theme - changeActive() - themeName is required'));
return _this.list()
.then((themes) => {
return new Promise((resolve, reject) => {
newActiveTheme = _.findWhere(the... | Change active theme
@param {string} themeName - Name of the theme to change to | changeActive | javascript | officert/mongotron | src/lib/modules/themes/index.js | https://github.com/officert/mongotron/blob/master/src/lib/modules/themes/index.js | MIT |
function parseThemesFileData(data) {
return new Promise((resolve, reject) => {
if (!data || !_.isArray(data)) return reject(new Error('themes - list() - error parsing themes file data'));
return resolve(data);
});
} | @function parseThemesFileData
@private
@param {Object} data - raw contexts from themes file | parseThemesFileData | javascript | officert/mongotron | src/lib/modules/themes/index.js | https://github.com/officert/mongotron/blob/master/src/lib/modules/themes/index.js | MIT |
get(key) {
if (!key) throw new Error('localStorageService - get() - key is required');
let json;
try {
var val = $window.localStorage.getItem(key);
if (val) json = JSON.parse(val);
} catch (e) {}
if (!json) json = CACHE[key];
return json;
} | @desc get a value by key
@param {String} key
@return {String} | get | javascript | officert/mongotron | src/ui/services/localStorageService.js | https://github.com/officert/mongotron/blob/master/src/ui/services/localStorageService.js | MIT |
set(key, value) {
if (!key) throw new Error('localStorageService - set() - key is required');
if (!value) throw new Error('localStorageService - set() - value is required');
if (value) {
try {
var val = JSON.stringify(value);
$window.localStorage.setItem(key, v... | @desc set a value by key
@param {String} key
@param {Object} obj
@return null | set | javascript | officert/mongotron | src/ui/services/localStorageService.js | https://github.com/officert/mongotron/blob/master/src/ui/services/localStorageService.js | MIT |
remove(key) {
if (!key) throw new Error('localStorageService - remove() - key is required');
try {
$window.localStorage.removeItem(key);
} catch (e) {
delete CACHE[key];
}
return null;
} | @desc remove a value by key
@param {String} key
@return null | remove | javascript | officert/mongotron | src/ui/services/localStorageService.js | https://github.com/officert/mongotron/blob/master/src/ui/services/localStorageService.js | MIT |
exists(key) {
if (!key) throw new Error('localStorageService - exists() - key is required');
var exists = null;
try {
exists = this.get(key) !== null && this.get(key) !== undefined;
} catch (e) {
exists = CACHE[key] ? true : false;
}
return exists;
... | @desc check if a value exists by key
@param {String} key
@return {Boolean} | exists | javascript | officert/mongotron | src/ui/services/localStorageService.js | https://github.com/officert/mongotron/blob/master/src/ui/services/localStorageService.js | MIT |
compareMongoObjectIds(expected, result) {
var expectedString = expected.toString();
var resultString = result.toString();
if (result instanceof mongodb.ObjectId !== true) return false;
if (expectedString !== resultString) return false;
return true;
} | Tests that the resulting objectId is an instance of mongodb.ObjectId
and tests that it matches the toString value of the expected ObjectId
@param {ObjectId} expected The ObjectId that's expected
@param {ObjectId} result The ObjectId that's returned
@return {[type]} [description] | compareMongoObjectIds | javascript | officert/mongotron | tests/utils/testUtils.js | https://github.com/officert/mongotron/blob/master/tests/utils/testUtils.js | MIT |
function encodeQueryString(obj) {
var str = [];
for (var p in obj) {
if (obj.hasOwnProperty(p)) {
str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p]));
}
}
return str.join('&');
} | Helper method to parse query objects to string.
@param {object} query
@returns {string} | encodeQueryString | javascript | muaz-khan/WebRTC-Experiment | Chrome-Extensions/file-sharing/rmc-files-handler.js | https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Chrome-Extensions/file-sharing/rmc-files-handler.js | MIT |
pack = function(serialized) {
var cursor = 0,
i = 0,
j = 0,
endianness = BIG_ENDIAN;
var ab = new ArrayBuffer(serialized[0].byte_length + serialized[0].header_size);
var view = new DataView(ab);
for (i = 0; i < serialized.... | packs seriarized elements array into a packed ArrayBuffer
@param {Array} serialized Serialized array of elements.
@return {DataView} view of packed binary | pack | javascript | muaz-khan/WebRTC-Experiment | Conversation.js/AndroidRTC/scripts/FileBufferReader.js | https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Conversation.js/AndroidRTC/scripts/FileBufferReader.js | MIT |
unpack = function(view, cursor) {
var i = 0,
endianness = BIG_ENDIAN,
start = cursor;
var type, length, byte_length, value, elem;
// Retrieve "type"
type = view.getUint8(cursor, endianness);
cursor += TYPE_LENGTH;
... | Unpack binary data into an object with value and cursor
@param {DataView} view [description]
@param {Number} cursor [description]
@return {Object} | unpack | javascript | muaz-khan/WebRTC-Experiment | Conversation.js/AndroidRTC/scripts/FileBufferReader.js | https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Conversation.js/AndroidRTC/scripts/FileBufferReader.js | MIT |
deferredSerialize = function(array, callback) {
var length = array.length,
results = [],
count = 0,
byte_length = 0;
for (var i = 0; i < array.length; i++) {
(function(index) {
serialize(array[index], function(re... | deferred function to process multiple serialization in order
@param {array} array [description]
@param {Function} callback [description]
@return {void} no return value | deferredSerialize | javascript | muaz-khan/WebRTC-Experiment | Conversation.js/AndroidRTC/scripts/FileBufferReader.js | https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Conversation.js/AndroidRTC/scripts/FileBufferReader.js | MIT |
serialize = function(obj, callback) {
var subarray = [],
unit = 1,
header_size = TYPE_LENGTH + BYTES_LENGTH,
type, byte_length = 0,
length = 0,
value = obj;
type = find_type(obj);
unit = Length[type] ==... | Serializes object and return byte_length
@param {mixed} obj JavaScript object you want to serialize
@return {Array} Serialized array object | serialize | javascript | muaz-khan/WebRTC-Experiment | Conversation.js/AndroidRTC/scripts/FileBufferReader.js | https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Conversation.js/AndroidRTC/scripts/FileBufferReader.js | MIT |
deserialize = function(buffer, callback) {
var view = buffer instanceof DataView ? buffer : new DataView(buffer);
var result = unpack(view, 0);
return result.value;
} | Deserialize binary and return JavaScript object
@param ArrayBuffer buffer ArrayBuffer you want to deserialize
@return mixed Retrieved JavaScript object | deserialize | javascript | muaz-khan/WebRTC-Experiment | Conversation.js/AndroidRTC/scripts/FileBufferReader.js | https://github.com/muaz-khan/WebRTC-Experiment/blob/master/Conversation.js/AndroidRTC/scripts/FileBufferReader.js | MIT |
function computeOffsetPixels(offset, contextHeight) {
const pixelOffset = parseOffsetAsPixels(offset);
if (typeof pixelOffset === 'number') {
return pixelOffset;
}
const percentOffset = parseOffsetAsPercentage(offset);
if (typeof percentOffset === 'number') {
return percentOffset * contextHeight;
... | @param {string|number} offset
@param {number} contextHeight
@return {number} A number representing `offset` converted into pixels. | computeOffsetPixels | javascript | civiccc/react-waypoint | src/computeOffsetPixels.js | https://github.com/civiccc/react-waypoint/blob/master/src/computeOffsetPixels.js | MIT |
function ensureRefIsProvidedByChild(children, ref) {
if (children && !isDOMElement(children) && !ref) {
throw new Error(errorMessage);
}
} | Raise an error if "children" is not a DOM Element and there is no ref provided to Waypoint
@param {?React.element} children
@param {?HTMLElement} ref
@return {undefined} | ensureRefIsProvidedByChild | javascript | civiccc/react-waypoint | src/ensureRefIsUsedByChild.js | https://github.com/civiccc/react-waypoint/blob/master/src/ensureRefIsUsedByChild.js | MIT |
function getCurrentPosition(bounds) {
if (bounds.viewportBottom - bounds.viewportTop === 0) {
return INVISIBLE;
}
// top is within the viewport
if (bounds.viewportTop <= bounds.waypointTop
&& bounds.waypointTop <= bounds.viewportBottom) {
return INSIDE;
}
// bottom is within the viewport
i... | @param {object} bounds An object with bounds data for the waypoint and
scrollable parent
@return {string} The current position of the waypoint in relation to the
visible portion of the scrollable parent. One of the constants `ABOVE`,
`BELOW`, `INSIDE` or `INVISIBLE`. | getCurrentPosition | javascript | civiccc/react-waypoint | src/getCurrentPosition.js | https://github.com/civiccc/react-waypoint/blob/master/src/getCurrentPosition.js | MIT |
function isDOMElement(Component) {
return (typeof Component.type === 'string');
} | When an element's type is a string, it represents a DOM node with that tag name
https://facebook.github.io/react/blog/2015/12/18/react-components-elements-and-instances.html#dom-elements
@param {React.element} Component
@return {bool} Whether the component is a DOM Element | isDOMElement | javascript | civiccc/react-waypoint | src/isDOMElement.js | https://github.com/civiccc/react-waypoint/blob/master/src/isDOMElement.js | MIT |
function parseOffsetAsPercentage(str) {
if (str.slice(-1) === '%') {
return parseFloat(str.slice(0, -1)) / 100;
}
return undefined;
} | Attempts to parse the offset provided as a prop as a percentage. For
instance, if the component has been provided with the string "20%" as
a value of one of the offset props. If the value matches, then it returns
a numeric version of the prop. For instance, "20%" would become `0.2`.
If `str` isn't a percentage, then `u... | parseOffsetAsPercentage | javascript | civiccc/react-waypoint | src/parseOffsetAsPercentage.js | https://github.com/civiccc/react-waypoint/blob/master/src/parseOffsetAsPercentage.js | MIT |
function parseOffsetAsPixels(str) {
if (!isNaN(parseFloat(str)) && isFinite(str)) {
return parseFloat(str);
} if (str.slice(-2) === 'px') {
return parseFloat(str.slice(0, -2));
}
return undefined;
} | Attempts to parse the offset provided as a prop as a pixel value. If
parsing fails, then `undefined` is returned. Three examples of values that
will be successfully parsed are:
`20`
"20px"
"20"
@param {string|number} str A string of the form "{number}" or "{number}px",
or just a number.
@return {number|undefined} Th... | parseOffsetAsPixels | javascript | civiccc/react-waypoint | src/parseOffsetAsPixels.js | https://github.com/civiccc/react-waypoint/blob/master/src/parseOffsetAsPixels.js | MIT |
_findLongestCommonSequence = function (seq1, seq2, seq1IsInLcs, seq2IsInLcs) {
if (!_areTypeOf(Array, seq1, seq2)) {
throw new Error('Array parameters are required')
}
// Deal with edge case
if (_isEmptyArray(seq1) || _isEmptyArray(seq2)) {
return []
}
// Function to calculate lcs ... | Finds longest common sequence between two sequences
@see {@link https://wordaligned.org/articles/longest-common-subsequence} | _findLongestCommonSequence | javascript | locutusjs/locutus | src/php/xdiff/xdiff_string_diff.js | https://github.com/locutusjs/locutus/blob/master/src/php/xdiff/xdiff_string_diff.js | MIT |
function trim (str) {
return str.trim().replace(/^"(.*)"$/, '$1').replace(/^'(.*)'$/, '$1');
} | Meta Helper
@description Generate meta tags for HTML header
@example
<%- meta(post) %> | trim | javascript | locutusjs/locutus | website/themes/icarus/scripts/meta.js | https://github.com/locutusjs/locutus/blob/master/website/themes/icarus/scripts/meta.js | MIT |
function section(title) {
return $('<section>').addClass('ins-section').append($('<header>').addClass('ins-section-header').text(title))
} | Insight search plugin
@author PPOffice { @link https://github.com/ppoffice } | section | javascript | locutusjs/locutus | website/themes/icarus/source/js/insight.js | https://github.com/locutusjs/locutus/blob/master/website/themes/icarus/source/js/insight.js | MIT |
function filter(keywords, obj, fields) {
var result = false
var keywordArray = parseKeywords(keywords)
var containKeywords = keywordArray.filter(function (keyword) {
var containFields = fields.filter(function (field) {
if (!obj.hasOwnProperty(field)) return false
if (obj[field].toUpper... | Judge if a given post/page/category/tag contains all of the keywords.
@param Object obj Object to be weighted
@param Array<String> fields Object's fields to find matches | filter | javascript | locutusjs/locutus | website/themes/icarus/source/js/insight.js | https://github.com/locutusjs/locutus/blob/master/website/themes/icarus/source/js/insight.js | MIT |
function weight(keywords, obj, fields, weights) {
var value = 0
parseKeywords(keywords).forEach(function (keyword) {
var pattern = new RegExp(keyword, 'img') // Global, Multi-line, Case-insensitive
fields.forEach(function (field, index) {
if (obj.hasOwnProperty(field)) {
var matche... | Calculate the weight of a matched post/page/category/tag.
@param Object obj Object to be weighted
@param Array<String> fields Object's fields to find matches
@param Array<Integer> weights Weight of every field | weight | javascript | locutusjs/locutus | website/themes/icarus/source/js/insight.js | https://github.com/locutusjs/locutus/blob/master/website/themes/icarus/source/js/insight.js | MIT |
function shutdownWorkers (signal) {
return new Promise((resolve) => {
if (!cluster.isMaster) { return resolve() }
const wIds = Object.keys(cluster.workers)
if (wIds.length === 0) { return resolve() }
// Filter all the valid workers
const workers = wIds.map(id => cluster.workers[id]).filter(v => v)... | Shutdown all worker processes.
From https://medium.com/@gaurav.lahoti/graceful-shutdown-of-node-js-workers-dd58bbff9e30
@param signal Signal to send to the workers | shutdownWorkers | javascript | godaddy/terminus | example/express.cluster.js | https://github.com/godaddy/terminus/blob/master/example/express.cluster.js | MIT |
function compareNums(a, b) {
return a - b;
} | This file automatically generated from `pre-publish.js`.
Do not manually edit. | compareNums | javascript | twbs/bootlint | dist/browser/bootlint.js | https://github.com/twbs/bootlint/blob/master/dist/browser/bootlint.js | MIT |
function sortedColumnClasses(classes) {
// extract column classes
var colClasses = [];
while (true) {
var match = COL_REGEX.exec(classes);
if (!match) {
break;
}
var colClass = match[0];
colClasses.push(colClass);
... | Moves any grid column classes to the end of the class string and sorts the grid classes by ascending screen size.
@param {string} classes The "class" attribute of a DOM node
@returns {string} The processed "class" attribute value | sortedColumnClasses | javascript | twbs/bootlint | dist/browser/bootlint.js | https://github.com/twbs/bootlint/blob/master/dist/browser/bootlint.js | MIT |
function width2screensFor(classes) {
var width = null;
var width2screens = {};
while (true) {
var match = COL_REGEX_G.exec(classes);
if (!match) {
break;
}
var screen = match[1];
width = match[2];
var screens... | @param {string} classes The "class" attribute of a DOM node
@returns {Object.<string, integer[]>} Object mapping grid column widths (1 thru 12) to sorted arrays of screen size numbers (see SCREEN2NUM)
Widths not used in the classes will not have an entry in the object. | width2screensFor | javascript | twbs/bootlint | dist/browser/bootlint.js | https://github.com/twbs/bootlint/blob/master/dist/browser/bootlint.js | MIT |
function incrementingRunsFrom(list) {
list = list.concat([Infinity]);// use Infinity to ensure any nontrivial (length >= 2) run ends before the end of the loop
var runs = [];
var start = null;
var prev = null;
for (var i = 0; i < list.length; i++) {
var current = list... | Given a sorted array of integers, this finds all contiguous runs where each item is incremented by 1 from the next.
For example:
[0, 2, 3, 5] has one such run: [2, 3]
[0, 2, 3, 4, 6, 8, 9, 11] has two such runs: [2, 3, 4], [8, 9]
[0, 2, 4] has no runs.
@param {integer[]} list Sorted array of integers
@re... | incrementingRunsFrom | javascript | twbs/bootlint | dist/browser/bootlint.js | https://github.com/twbs/bootlint/blob/master/dist/browser/bootlint.js | MIT |
function getBrowserWindowObject() {
var theWindow = null;
try {
/* eslint-disable-next-line no-undef */
theWindow = window;
} catch (e) {
// deliberately do nothing
// empty
}
return theWindow;
} | @returns {(Window|null)} The browser window object, or null if this is not running in a browser environment | getBrowserWindowObject | javascript | twbs/bootlint | dist/browser/bootlint.js | https://github.com/twbs/bootlint/blob/master/dist/browser/bootlint.js | MIT |
function LintError(id, message, elements) {
this.id = id;
this.url = WIKI_URL + id;
this.message = message;
this.elements = elements || cheerio('');
} | @param {integer} id Unique string ID for this type of lint error. Of the form "E###" (e.g. "E123").
@param {string} message Human-readable string describing the error
@param {jQuery} elements jQuery or Cheerio collection of referenced DOM elements pointing to all problem locations in the document
@class | LintError | javascript | twbs/bootlint | dist/browser/bootlint.js | https://github.com/twbs/bootlint/blob/master/dist/browser/bootlint.js | MIT |
function LintWarning(id, message, elements) {
this.id = id;
this.url = WIKI_URL + id;
this.message = message;
this.elements = elements || cheerio('');
} | @param {integer} id Unique string ID for this type of lint warning. Of the form "W###" (e.g. "W123").
@param {string} message Human-readable string describing the warning
@param {jQuery} elements jQuery or Cheerio collection of referenced DOM elements pointing to all problem locations in the document
@class | LintWarning | javascript | twbs/bootlint | dist/browser/bootlint.js | https://github.com/twbs/bootlint/blob/master/dist/browser/bootlint.js | MIT |
reporter = function (lint) {
var background = 'background: #' + (lint.id[0] === 'W' ? 'f0ad4e' : 'd9534f') + '; color: #ffffff;';
if (!seenLint) {
if (alertOnFirstProblem) {
/* eslint-disable-next-line no-alert, no-undef */
... | Lints the HTML of the current document.
If there are any lint warnings, one general notification message will be window.alert()-ed to the user.
Each warning will be output individually using console.warn().
@param {string[]} disabledIds Array of string IDs of linters to disable
@param {object} [alertOpts] Options objec... | reporter | javascript | twbs/bootlint | dist/browser/bootlint.js | https://github.com/twbs/bootlint/blob/master/dist/browser/bootlint.js | MIT |
function parse(urlStr) {
var anchor = document.createElement('a');
anchor.href = urlStr;
var urlObj = {};
URL_PROPERTIES.forEach(function (property) {
urlObj[property] = anchor[property];
});
return urlObj;
} | @param {string} urlStr URL to parse
@returns {object} Object with fields representing the various parts of the parsed URL. | parse | javascript | twbs/bootlint | dist/browser/bootlint.js | https://github.com/twbs/bootlint/blob/master/dist/browser/bootlint.js | MIT |
function Location(line, column) {
this.line = line;
this.column = column;
} | Represents a location within a source code file.
@param {integer} line A 0-based line index
@param {integer} column A 0-based column index
@class | Location | javascript | twbs/bootlint | src/location.js | https://github.com/twbs/bootlint/blob/master/src/location.js | MIT |
function LocationIndex(string) {
// ensure newline termination
if (string[string.length - 1] !== '\n') {
string += '\n';
}
this._stringLength = string.length;
/*
* Each triple in _lineStartEndTriples consists of:
* [0], the 0-based line index of the ... | Maps code unit indices into the string to line numbers and column numbers.
@param {string} string String to construct the index for
@class | LocationIndex | javascript | twbs/bootlint | src/location.js | https://github.com/twbs/bootlint/blob/master/src/location.js | MIT |
invalid = function invalid() {
_this8.setState(function () {
return {
data: _this8.store.get(),
reset: false
};
});
return;
} | Returns true if this action can be handled remote store
From #990, Sometimes, we need some actions as remote, some actions are handled by default
so function will tell you the target action is can be handled as remote or not.
@param {String} [action] Required.
@param {Object} [props] Optional. If not given, this.pr... | invalid | javascript | AllenFang/react-bootstrap-table | dist/react-bootstrap-table.js | https://github.com/AllenFang/react-bootstrap-table/blob/master/dist/react-bootstrap-table.js | MIT |
isRemoteDataSource(props) {
const { remote } = (props || this.props);
return remote === true || Util.isFunction(remote);
} | Returns true if in the current configuration,
the datagrid should load its data remotely.
@param {Object} [props] Optional. If not given, this.props will be used
@return {Boolean} | isRemoteDataSource | javascript | AllenFang/react-bootstrap-table | src/BootstrapTable.js | https://github.com/AllenFang/react-bootstrap-table/blob/master/src/BootstrapTable.js | MIT |
render() {
this.clickNum = 0;
const { selectRow, row, isSelected, className, index, hidden } = this.props;
let { style } = this.props;
let backgroundColor = null;
let selectRowClass = null;
if (selectRow) {
backgroundColor = Utils.isFunction(selectRow.bgColor) ?
selectRow.bgColor(... | if clickToSelectAndEditCell is enabled,
there should be a delay to prevent a selection changed when
user dblick to edit cell on same row but different cell | render | javascript | AllenFang/react-bootstrap-table | src/TableRow.js | https://github.com/AllenFang/react-bootstrap-table/blob/master/src/TableRow.js | MIT |
filterArray(targetVal, filterVal) {
// case insensitive
return filterVal.indexOf(targetVal) > -1;
} | Filter if targetVal is contained in filterVal. | filterArray | javascript | AllenFang/react-bootstrap-table | src/store/TableDataStore.js | https://github.com/AllenFang/react-bootstrap-table/blob/master/src/store/TableDataStore.js | MIT |
function Strategy(options, verify) {
if (typeof options == 'function') {
verify = options;
options = {};
}
if (!verify) { throw new TypeError('HTTPBearerStrategy requires a verify function'); }
passport.Strategy.call(this);
/** The name of the strategy, set to `'bearer'`.
*
* @type {string... | Create a new `Strategy` object.
@classdesc This `Strategy` authenticates HTTP requests that use the Bearer
authentication scheme, as specified by {@link https://www.rfc-editor.org/rfc/rfc6750 RFC 6750}.
The bearer token credential can be sent in the HTTP request in one of three
different ways. Preferably, the token ... | Strategy | javascript | jaredhanson/passport-http-bearer | lib/strategy.js | https://github.com/jaredhanson/passport-http-bearer/blob/master/lib/strategy.js | MIT |
function verified(err, user, info) {
if (err) { return self.error(err); }
if (!user) {
if (typeof info == 'string') {
info = { message: info }
}
info = info || {};
return self.fail(self._challenge('invalid_token', info.message));
}
self.success(user, info);
} | Authenticate request by verifying access token.
When a bearer token is sent in the request, it will be parsed and the verify
function will be called to verify the token and authenticate the request. If
a token is not present, authentication will fail with the appropriate
challenge and status code.
This function is p... | verified | javascript | jaredhanson/passport-http-bearer | lib/strategy.js | https://github.com/jaredhanson/passport-http-bearer/blob/master/lib/strategy.js | MIT |
function _Utils_cmp(x, y, ord)
{
if (typeof x !== 'object')
{
return x === y ? /*EQ*/ 0 : x < y ? /*LT*/ -1 : /*GT*/ 1;
}
/**/
if (x instanceof String)
{
var a = x.valueOf();
var b = y.valueOf();
return a === b ? 0 : a < b ? -1 : 1;
}
//*/
/**_UNUSED/
if (typeof x.$ === 'undefined')
//*/
/**/
if ... | _UNUSED/
if (x.$ < 0)
{
x = $elm$core$Dict$toList(x);
y = $elm$core$Dict$toList(y);
}
// | _Utils_cmp | javascript | Boscop/web-view | webview-examples/examples/todo-elm/elm.js | https://github.com/Boscop/web-view/blob/master/webview-examples/examples/todo-elm/elm.js | MIT |
function _Json_succeed(msg)
{
return {
$: 0,
a: msg
};
} | /
function _Json_errorToString(error)
{
return $elm$json$Json$Decode$errorToString(error);
}
// | _Json_succeed | javascript | Boscop/web-view | webview-examples/examples/todo-elm/elm.js | https://github.com/Boscop/web-view/blob/master/webview-examples/examples/todo-elm/elm.js | MIT |
function _VirtualDom_text(string)
{
return {
$: 0,
a: string
};
} | /
var node = args && args['node'] ? args['node'] : _Debug_crash(0);
// | _VirtualDom_text | javascript | Boscop/web-view | webview-examples/examples/todo-elm/elm.js | https://github.com/Boscop/web-view/blob/master/webview-examples/examples/todo-elm/elm.js | MIT |
function _Browser_makeAnimator(model, draw)
{
draw(model);
var state = 0;
function updateIfNeeded()
{
state = state === 1
? 0
: ( _Browser_requestAnimationFrame(updateIfNeeded), draw(model), 1 );
}
return function(nextModel, isSync)
{
model = nextModel;
isSync
? ( draw(model),
state === 2 ... | /
var domNode = args && args['node'] ? args['node'] : _Debug_crash(0);
// | _Browser_makeAnimator | javascript | Boscop/web-view | webview-examples/examples/todo-elm/elm.js | https://github.com/Boscop/web-view/blob/master/webview-examples/examples/todo-elm/elm.js | MIT |
exit = (code) => {
if (process.env.NODE_ENV === 'test') {
throw new Error(`Exit called with code: ${code}`);
} else {
process.exit(code);
}
} | Custom exit function that handles both production and test environments
@param {number} code - Exit code to return
@throws {Error} In test environment instead of exiting | exit | javascript | addyosmani/git2txt | index.js | https://github.com/addyosmani/git2txt/blob/master/index.js | MIT |
function normalizeGitHubUrl(url) {
try {
// Remove trailing slashes
url = url.replace(/\/+$/, '');
// Handle git@ URLs
if (url.startsWith('git@github.com:')) {
return url;
}
// Handle full HTTPS URLs
if (url.startsWith('https://gi... | Normalizes various GitHub URL formats to a consistent format
@param {string} url - The GitHub repository URL to normalize
@returns {string} Normalized GitHub URL
@throws {Error} If URL format is invalid | normalizeGitHubUrl | javascript | addyosmani/git2txt | index.js | https://github.com/addyosmani/git2txt/blob/master/index.js | MIT |
async function validateInput(input) {
if (!input || input.length === 0) {
throw new Error('Repository URL is required');
}
const url = input[0];
if (!url.includes('github.com') && !url.match(/^[\w-]+\/[\w-]+$/)) {
throw new Error('Only GitHub repositories are supported');
}
ret... | Validates the command line input
@param {string[]} input - Command line arguments
@returns {Promise<string>} Validated repository URL
@throws {Error} If input is missing or invalid | validateInput | javascript | addyosmani/git2txt | index.js | https://github.com/addyosmani/git2txt/blob/master/index.js | MIT |
async function downloadRepository(url) {
const spinner = process.env.NODE_ENV !== 'test' ? ora('Downloading repository...').start() : null;
const tempDir = path.join(os.tmpdir(), `git2txt-${Date.now()}`);
try {
// Normalize the GitHub URL
const normalizedUrl = normalizeGitHubUrl(url);
... | Downloads a GitHub repository to a temporary directory
@param {string} url - GitHub repository URL
@returns {Promise<Object>} Object containing temporary directory path and repository name
@throws {Error} If download fails | downloadRepository | javascript | addyosmani/git2txt | index.js | https://github.com/addyosmani/git2txt/blob/master/index.js | MIT |
async function processFiles(directory, options) {
let spinner = process.env.NODE_ENV !== 'test' ? ora('Processing files...').start() : null;
const thresholdBytes = options.threshold * 1024 * 1024;
let output = '';
let processedFiles = 0;
let skippedFiles = 0;
/**
* Recursively processes fi... | Processes files in the repository directory and combines them into a single text output
@param {string} directory - Path to the repository directory
@param {Object} options - Processing options
@param {number} options.threshold - File size threshold in MB
@param {boolean} options.includeAll - Whether to include all fil... | processFiles | javascript | addyosmani/git2txt | index.js | https://github.com/addyosmani/git2txt/blob/master/index.js | MIT |
async function processDirectory(dir) {
const entries = await fs.readdir(dir, { withFileTypes: true });
for (const entry of entries) {
const fullPath = path.join(dir, entry.name);
if (entry.isDirectory() && entry.name !== 'node_modules' && entry.name !== '.gi... | Recursively processes files in a directory
@param {string} dir - Directory to process | processDirectory | javascript | addyosmani/git2txt | index.js | https://github.com/addyosmani/git2txt/blob/master/index.js | MIT |
async function writeOutput(content, outputPath) {
let spinner = process.env.NODE_ENV !== 'test' ? ora('Writing output file...').start() : null;
try {
await fs.writeFile(outputPath, content);
if (spinner) spinner.succeed(`Output saved to ${chalk.green(outputPath)}`);
} catch (error) {
... | Writes the processed content to an output file
@param {string} content - Content to write
@param {string} outputPath - Path to the output file
@returns {Promise<void>}
@throws {Error} If writing fails | writeOutput | javascript | addyosmani/git2txt | index.js | https://github.com/addyosmani/git2txt/blob/master/index.js | MIT |
async function cleanup(directory) {
try {
await fs.rm(directory, { recursive: true, force: true });
} catch (error) {
if (process.env.NODE_ENV !== 'test') {
console.error(chalk.yellow('Warning: Failed to clean up temporary files'));
}
}
} | Cleans up temporary files and directories
@param {string} directory - Directory to clean up
@returns {Promise<void>} | cleanup | javascript | addyosmani/git2txt | index.js | https://github.com/addyosmani/git2txt/blob/master/index.js | MIT |
async function main() {
let tempDir;
try {
const url = await validateInput(cli.input);
if (process.env.NODE_ENV !== 'test') {
const result = await downloadRepository(url);
tempDir = result.tempDir;
const outputPath = cli.flags.output || `${result.... | Main application function that orchestrates the entire process
@returns {Promise<void>} | main | javascript | addyosmani/git2txt | index.js | https://github.com/addyosmani/git2txt/blob/master/index.js | MIT |
renderLoop = function(){
requestAnimationFrame(renderLoop);
game._board.render();
} | Update the sizes of the renderer (this makes the game responsive) | renderLoop | javascript | Aerolab/blockrain.js | dist/blockrain.jquery.js | https://github.com/Aerolab/blockrain.js/blob/master/dist/blockrain.jquery.js | MIT |
function Shape(game, orientations, symmetrical, blockType) {
$.extend(this, {
x: 0,
y: 0,
symmetrical: symmetrical,
init: function() {
$.extend(this, {
orientation: 0,
x: Math.floor(game._BLOCK_WIDTH / 2) - 1,
y: -1
... | The shapes have a reference point (the dot) and always rotate left.
Keep in mind that the blocks should keep in the same relative position when rotating,
to allow for custom per-block themes. | Shape | javascript | Aerolab/blockrain.js | dist/blockrain.jquery.js | https://github.com/Aerolab/blockrain.js/blob/master/dist/blockrain.jquery.js | MIT |
getCustomBlockImageCoordinates = function(image, blockType, blockIndex) {
// The image is based on the first ("upright") orientation
var positions = game._shapes[blockType][0];
// Find the number of tiles it should have
var minX = Math.min(positions[0], po... | Draws one block (Each piece is made of 4 blocks)
The blockType is used to draw any block.
The falling attribute is needed to apply different styles for falling and placed blocks. | getCustomBlockImageCoordinates | javascript | Aerolab/blockrain.js | dist/blockrain.jquery.js | https://github.com/Aerolab/blockrain.js/blob/master/dist/blockrain.jquery.js | MIT |
getBlockVariation = function(blockTheme, blockVariation) {
if( $.isArray(blockTheme) ) {
if( blockVariation !== null && typeof blockTheme[blockVariation] !== 'undefined' ) {
return blockTheme[blockVariation];
}
else if(blockTheme.length > 0) {
... | The theme allows us to do many things:
- Use a specific color for the falling block (primary), regardless of the proper color.
- Use another color for the placed blocks (secondary).
- Default to the "original" block color in any of those cases by setting primary and/or secondary to null.
- With primary and secondary as... | getBlockVariation | javascript | Aerolab/blockrain.js | dist/blockrain.jquery.js | https://github.com/Aerolab/blockrain.js/blob/master/dist/blockrain.jquery.js | MIT |
handleAssetLoad = function() {
// Rerender the board as soon as an asset loads
if( game._board ) {
game._board.render(true);
}
} | Find base64 encoded images and load them as image objects, which can be used by the canvas renderer | handleAssetLoad | javascript | Aerolab/blockrain.js | dist/blockrain.jquery.js | https://github.com/Aerolab/blockrain.js/blob/master/dist/blockrain.jquery.js | MIT |
create = object => ({
...suffixProperties(object, "Object"),
...StyleSheet.create(object)
}) | Very frequently you may want to use a style with some tweaks.
This class generates properties with the Object suffix, that can be
used to create a customized entry in a `StyleSheet`, e.g.:
const styles = StyleSheet.create({
wrapper: {
...material.title1Object,
color: 'palevioletred',
},
});
P... | create | javascript | hectahertz/react-native-typography | src/internal/CombinedStyleSheet.js | https://github.com/hectahertz/react-native-typography/blob/master/src/internal/CombinedStyleSheet.js | MIT |
function O2(r,e,t,i){Li.has(e)||Li.set(e,new Lg.default({maxSize:25e3}));for(let n of r.split(`
`))if(n=n.trim(),!i.has(n))if(i.add(n),Li.get(e).has(n))for(let s of Li.get(e).get(n))t.add(s);else{let s=e(n).filter(o=>o!=="!*"),a=new Set(s);for(let o of a)t.add(o);Li.get(e).set(n,a)}} | ":"**"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,C... | O2 | javascript | LibreSpark/LibreTV | libs/tailwindcss.min.js | https://github.com/LibreSpark/LibreTV/blob/master/libs/tailwindcss.min.js | Apache-2.0 |
function QRCodeModel(typeNumber, errorCorrectLevel) {
this.typeNumber = typeNumber;
this.errorCorrectLevel = errorCorrectLevel;
this.modules = null;
this.moduleCount = 0;
this.dataCache = null;
this.dataList = [];
} | @fileoverview
- Using the 'QRCode for Javascript library'
- Fixed dataset of 'QRCode for Javascript library' for support full-spec.
- this library has no dependencies.
@author davidshimjs
@see <a href="http://www.d-project.com/" target="_blank">http://www.d-project.com/</a>
@see <a href="http://jeromeetienne.github.co... | QRCodeModel | javascript | bryanbraun/checkboxland | docs/demos/qr-code/qrcode.js | https://github.com/bryanbraun/checkboxland/blob/master/docs/demos/qr-code/qrcode.js | MIT |
isValidPackageName = function(packageName) {
try {
return [validPackageName(packageName), null];
} catch (error) {
if (error instanceof ValidationError) return [false, error];
throw error;
}
} | Utils that shared both server and client. | isValidPackageName | javascript | openupm/openupm | app/common/utils.js | https://github.com/openupm/openupm/blob/master/app/common/utils.js | BSD-3-Clause |
getCachedAvatarImageFilename = function(username, size) {
username = username.toLowerCase();
return `${username}-${size}x${size}.png`;
} | Get the cached avatar image filename
@param {string} username
@param {Number} size | getCachedAvatarImageFilename | javascript | openupm/openupm | app/common/utils.js | https://github.com/openupm/openupm/blob/master/app/common/utils.js | BSD-3-Clause |
isPackageBlockedByScope = function(packageName, scope) {
if (scope.startsWith("^"))
return packageName.startsWith(scope.slice(1, scope.length));
else
return packageName == scope;
} | Return if the package name is blocked by the given block scope
@param {String} packageName
@param {String} scope
@returns {Boolean} | isPackageBlockedByScope | javascript | openupm/openupm | app/common/utils.js | https://github.com/openupm/openupm/blob/master/app/common/utils.js | BSD-3-Clause |
aggregateExtraData = async function() {
logger.info("aggregateExtraData");
const packageNames = await loadPackageNames();
const aggData = {};
for (let packageName of packageNames) {
// Verify package
if (!packageExists(packageName)) {
logger.error({ pkg: packageName }, "package doesn't exist");
... | Aggregate extra data for all packages into redis. | aggregateExtraData | javascript | openupm/openupm | app/jobs/aggregatePackageExtra.js | https://github.com/openupm/openupm/blob/master/app/jobs/aggregatePackageExtra.js | BSD-3-Clause |
getInvalidTags = function ({
remoteTags,
validTags,
gitTagIgnore,
gitTagPrefix,
minVersion
}) {
let tags = differenceBy(remoteTags, validTags, x => x.tag);
if (gitTagPrefix) {
tags = tags.filter(x => x.tag.startsWith(gitTagPrefix));
}
if (gitTagIgnore) {
const ignoreRe = new RegExp(gitTagIgnor... | Return invalid tags. Tags have been ignored, without the given prefix, or filtered by
minVersion are not considered invalid. | getInvalidTags | javascript | openupm/openupm | app/jobs/buildPackage.js | https://github.com/openupm/openupm/blob/master/app/jobs/buildPackage.js | BSD-3-Clause |
fetchBackerData = async function(force) {
logger.info("fetchBackerData");
const backers = yaml.safeLoad(await readFile(backersPath, "utf8"));
for (const backer of backers.items) {
if (backer.githubUser)
await cacheAvatarImageForGithubUser(backer.githubUser, force);
}
} | Fetch backer data
@param {Array} packageNames
@param {Boolean} force | fetchBackerData | javascript | openupm/openupm | app/jobs/fetchBackerData.js | https://github.com/openupm/openupm/blob/master/app/jobs/fetchBackerData.js | BSD-3-Clause |
fetchExtraData = async function(packageNames, force) {
logger.info("fetchExtraData");
if (!packageNames) packageNames = [];
for (let packageName of packageNames) {
// Verify package
if (!packageExists(packageName)) {
logger.error({ pkg: packageName }, "package doesn't exist");
continue;
}
... | Fetch package extra data into redis for given packageNames array.
@param {Array} packageNames
@param {Boolean} force | fetchExtraData | javascript | openupm/openupm | app/jobs/fetchPackageExtra.js | https://github.com/openupm/openupm/blob/master/app/jobs/fetchPackageExtra.js | BSD-3-Clause |
fetchPackageMeta = async function(packageName) {
let resp = null;
const source = CancelToken.source();
setTimeout(() => {
if (resp === null) source.cancel("ECONNTIMEOUT");
}, 10000);
resp = await AxiosService.create().get(
urljoin("https://package.openupm.com", packageName),
{
headers: { Acc... | Fetch package meta json.
@param {string} packageName | fetchPackageMeta | javascript | openupm/openupm | app/jobs/fetchPackageExtra.js | https://github.com/openupm/openupm/blob/master/app/jobs/fetchPackageExtra.js | BSD-3-Clause |
_fetchPackageInfo = async function(packageName) {
logger.info({ pkg: packageName }, "_fetchPackageInfo");
try {
const pkgMeta = await fetchPackageMeta(packageName);
const version = pkgMeta["dist-tags"].latest;
const versionInfo = pkgMeta.versions[version];
// Save the unity version.
const unityV... | Fetch package info from the registry.
@param {string} packageName | _fetchPackageInfo | javascript | openupm/openupm | app/jobs/fetchPackageExtra.js | https://github.com/openupm/openupm/blob/master/app/jobs/fetchPackageExtra.js | BSD-3-Clause |
_fetchPackageScopes = async function(packageName) {
logger.info({ pkg: packageName }, "_fetchPackageScopes");
// a list of pending {name, version}
const pendingList = [{ name: packageName, version: null }];
// a list of processed {name, version}
const processedList = [];
// a set of package names exists on ... | Fetch package scopes for dependencies.
@param {string} packageName | _fetchPackageScopes | javascript | openupm/openupm | app/jobs/fetchPackageExtra.js | https://github.com/openupm/openupm/blob/master/app/jobs/fetchPackageExtra.js | BSD-3-Clause |
_fetchRepoInfo = async function(repo, packageName) {
logger.info({ pkg: packageName }, "_fetchRepoInfo");
try {
const headers = { Accept: "application/vnd.github.v3.json" };
const githubToken = getGithubToken();
if (githubToken) headers.authorization = `Bearer ${githubToken}`;
let resp = null;
c... | Fetch repository information like stars and pushed time.
@param {object} repo | _fetchRepoInfo | javascript | openupm/openupm | app/jobs/fetchPackageExtra.js | https://github.com/openupm/openupm/blob/master/app/jobs/fetchPackageExtra.js | BSD-3-Clause |
_cacheImage = async function(pkg, packageName, force) {
logger.info({ pkg: packageName }, "_cacheImage");
try {
const query = await PackageExtra.getImageQueryForPackage(packageName);
if (!query) return;
// check cache
let imageEntry = await getImage(query);
if (!force && imageEntry && imageEntr... | Cache the image url
@param {object} pkg
@param {string} packageName
@param {Boolean} force | _cacheImage | javascript | openupm/openupm | app/jobs/fetchPackageExtra.js | https://github.com/openupm/openupm/blob/master/app/jobs/fetchPackageExtra.js | BSD-3-Clause |
_cacheAvatarImage = async function(pkg, packageName, force) {
logger.info({ pkg: packageName }, "_cacheAvatarImage");
if (pkg.owner) await cacheAvatarImageForGithubUser(pkg.owner, force);
if (pkg.parentOwner)
await cacheAvatarImageForGithubUser(pkg.parentOwner, force);
if (pkg.hunter) await cacheAvatarImage... | Cache the avatar image url
@param {object} pkg
@param {string} packageName
@param {Boolean} force | _cacheAvatarImage | javascript | openupm/openupm | app/jobs/fetchPackageExtra.js | https://github.com/openupm/openupm/blob/master/app/jobs/fetchPackageExtra.js | BSD-3-Clause |
cacheAvatarImageForGithubUser = async function(username, force) {
for (const [sizeName, entry] of Object.entries(config.packageExtra.avatar)) {
logger.info(
{ username, width: entry.size, height: entry.size, sizeName },
"cacheAvatarImageForGithubUser"
);
try {
const query = await Package... | Cache the avatar image url for the GitHub user
@param {string} username
@param {Boolean} force | cacheAvatarImageForGithubUser | javascript | openupm/openupm | app/jobs/fetchPackageExtra.js | https://github.com/openupm/openupm/blob/master/app/jobs/fetchPackageExtra.js | BSD-3-Clause |
_fetchReadme = async function(pkg, packageName) {
logger.info({ pkg: packageName }, "_fetchReadme");
const langs = ["en-US", "zh-CN"];
for (const lang of langs) {
const readmePathPropKey = PackageExtra.getPropKeyForLang(
PackageExtra.propKeys.readme,
lang
);
const readmePath = pkg[readmePa... | Fetch repository readme.
@param {object} repo | _fetchReadme | javascript | openupm/openupm | app/jobs/fetchPackageExtra.js | https://github.com/openupm/openupm/blob/master/app/jobs/fetchPackageExtra.js | BSD-3-Clause |
fetchPackageMonthlyInstallCount = async function(packageName) {
let resp = null;
const source = CancelToken.source();
setTimeout(() => {
if (resp === null) source.cancel("ECONNTIMEOUT");
}, 10000);
resp = await AxiosService.create().get(
urljoin(
"https://package.openupm.com/downloads/point/last... | Fetch package meta json.
@param {string} packageName
@returns {Number} | fetchPackageMonthlyInstallCount | javascript | openupm/openupm | app/jobs/fetchPackageExtra.js | https://github.com/openupm/openupm/blob/master/app/jobs/fetchPackageExtra.js | BSD-3-Clause |
_fetchPackageInstallCount = async function(packageName) {
logger.info({ pkg: packageName }, "_fetchPackageInstallCount");
try {
const result = await fetchPackageMonthlyInstallCount(packageName);
const count = result.downloads || 0;
await PackageExtra.setMonthlyDownloads(packageName, count);
} catch (e... | Fetch package install count.
@param {string} packageName | _fetchPackageInstallCount | javascript | openupm/openupm | app/jobs/fetchPackageExtra.js | https://github.com/openupm/openupm/blob/master/app/jobs/fetchPackageExtra.js | BSD-3-Clause |
_fetchStars = async function(repo) {
try {
const headers = { Accept: "application/vnd.github.v3.json" };
const githubToken = getGithubToken();
if (githubToken) headers.authorization = `Bearer ${githubToken}`;
let resp = null;
const source = CancelToken.source();
setTimeout(() => {
if (re... | Fetch repository stars.
@param {string} repo | _fetchStars | javascript | openupm/openupm | app/jobs/fetchSiteInfo.js | https://github.com/openupm/openupm/blob/master/app/jobs/fetchSiteInfo.js | BSD-3-Clause |
getPropKeyForLang = function(propKey, lang) {
if (!lang || lang == "en-US") return propKey;
else if (lang == "zh-CN") return propKey + "_zhCN";
else throw new Error("Not implemented yet");
} | Get the property key appended with a language code except en-US.
@param {String} propKey - the property key
@param {String} lang - the ISO 639-1 standard language code
@returns the property key for lang | getPropKeyForLang | javascript | openupm/openupm | app/models/packageExtra.js | https://github.com/openupm/openupm/blob/master/app/models/packageExtra.js | BSD-3-Clause |
getImageQueryForPackage = async function(packageName) {
// get the image url
const pkg = await loadPackage(packageName);
const imageUrl = pkg.image;
if (!imageUrl) return null;
const width = config.packageExtra.image.width;
const height = config.packageExtra.image.height;
const fit = pkg.imageFit == "cont... | Get image query data for a package, return { imageUrl, width, height, fit }
@param {string} packageName | getImageQueryForPackage | javascript | openupm/openupm | app/models/packageExtra.js | https://github.com/openupm/openupm/blob/master/app/models/packageExtra.js | BSD-3-Clause |
getImageQueryForGithubUser = async function(username, size) {
// get the image url
const imageUrl = `https://github.com/${username}.png?size=${size}`;
return { imageUrl, width: size, height: size, fit: "cover" };
} | Get image query data for a GitHub user, return { imageUrl, width, height, fit }
@param {string} username
@param {Number} size | getImageQueryForGithubUser | javascript | openupm/openupm | app/models/packageExtra.js | https://github.com/openupm/openupm/blob/master/app/models/packageExtra.js | BSD-3-Clause |
getCachedImageFilename = async function(packageName) {
const imageQuery = await getImageQueryForPackage(packageName);
if (imageQuery) {
const imageData = await getImage(imageQuery);
if (imageData) return imageData.filename;
}
return null;
} | Get the cached image filename
@param {string} packageName | getCachedImageFilename | javascript | openupm/openupm | app/models/packageExtra.js | https://github.com/openupm/openupm/blob/master/app/models/packageExtra.js | BSD-3-Clause |
getMonthlyDownloads = async function(packageName) {
const value = await getValue(packageName, propKeys.monthlyDownloads);
return parseInt(value) || 0;
} | Get monthly downloads for a package.
@param {string} packageName - The name of the package.
@returns {Promise<number>} - A Promise that resolves to the number of downloads. | getMonthlyDownloads | javascript | openupm/openupm | app/models/packageExtra.js | https://github.com/openupm/openupm/blob/master/app/models/packageExtra.js | BSD-3-Clause |
setMonthlyDownloads = async function(packageName, downloads) {
await setValue(packageName, propKeys.monthlyDownloads, downloads);
} | Set monthly downloads for a package.
@param {string} packageName - The name of the package.
@param {number} downloads - The number of downloads to set.
@returns {Promise<void>} - A Promise that resolves when the downloads have been set. | setMonthlyDownloads | javascript | openupm/openupm | app/models/packageExtra.js | https://github.com/openupm/openupm/blob/master/app/models/packageExtra.js | BSD-3-Clause |
setAggregatedExtraData = async function(obj) {
const jsonText = JSON.stringify(obj, null, 0);
await redis.client.set(allPackagesExtraKey, jsonText);
} | Set aggregated extra data.
@param {object} obj | setAggregatedExtraData | javascript | openupm/openupm | app/models/packageExtra.js | https://github.com/openupm/openupm/blob/master/app/models/packageExtra.js | BSD-3-Clause |
setRecentPackages = async function(arr) {
const jsonText = JSON.stringify(arr, null, 0);
await redis.client.set(recentPackagesKey, jsonText);
} | Set recent packages.
@param {object} obj | setRecentPackages | javascript | openupm/openupm | app/models/packageExtra.js | https://github.com/openupm/openupm/blob/master/app/models/packageExtra.js | BSD-3-Clause |
setFeedRecentUpdate = async function(objs) {
// Sort by time.
objs = orderBy(objs, ["time"], ["desc"]);
// Generate the feed.
const feed = new Feed({
title: "OpenUPM Recent Updates",
description: "Feed of OpenUPM Recently Updated Packages",
id: "https://openupm.com/",
link: "https://openupm.com/... | Set aggregated extra data.
@param {Array} objs
[{
packageName: str,
displayName: str,
time: int,
version: str,
author: [
{
name: str,
link: str
}, ...]
}, ...] | setFeedRecentUpdate | javascript | openupm/openupm | app/models/packageFeed.js | https://github.com/openupm/openupm/blob/master/app/models/packageFeed.js | BSD-3-Clause |
function getGithubToken() {
if (config.github.tokens && config.github.tokens.length > 0)
// Return random token from the list.
return config.github.tokens[
Math.floor(Math.random() * config.github.tokens.length)
];
// Fall back to the single token.
if (config.github.token) return config.github.t... | Return GitHub token from the configuration.
@returns The GitHub token. | getGithubToken | javascript | openupm/openupm | app/utils/github.js | https://github.com/openupm/openupm/blob/master/app/utils/github.js | BSD-3-Clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.