id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
sequence
docstring
stringlengths
4
11.8k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
86
226
5,600
FineUploader/fine-uploader
client/js/uploader.api.js
function(id) { // If the edit filename feature is enabled, mark the filename element as "editable" and the associated edit icon if (this._isEditFilenameEnabled()) { this._templating.markFilenameEditable(id); this._templating.showEditIcon(id); // If the focusin event is not supported, we must add a focus handler to the newly create edit filename text input if (!this._focusinEventSupported) { this._filenameInputFocusHandler.addHandler(this._templating.getEditInput(id)); } } }
javascript
function(id) { // If the edit filename feature is enabled, mark the filename element as "editable" and the associated edit icon if (this._isEditFilenameEnabled()) { this._templating.markFilenameEditable(id); this._templating.showEditIcon(id); // If the focusin event is not supported, we must add a focus handler to the newly create edit filename text input if (!this._focusinEventSupported) { this._filenameInputFocusHandler.addHandler(this._templating.getEditInput(id)); } } }
[ "function", "(", "id", ")", "{", "// If the edit filename feature is enabled, mark the filename element as \"editable\" and the associated edit icon", "if", "(", "this", ".", "_isEditFilenameEnabled", "(", ")", ")", "{", "this", ".", "_templating", ".", "markFilenameEditable", "(", "id", ")", ";", "this", ".", "_templating", ".", "showEditIcon", "(", "id", ")", ";", "// If the focusin event is not supported, we must add a focus handler to the newly create edit filename text input", "if", "(", "!", "this", ".", "_focusinEventSupported", ")", "{", "this", ".", "_filenameInputFocusHandler", ".", "addHandler", "(", "this", ".", "_templating", ".", "getEditInput", "(", "id", ")", ")", ";", "}", "}", "}" ]
The file item has been added to the DOM.
[ "The", "file", "item", "has", "been", "added", "to", "the", "DOM", "." ]
057cc83a7e7657d032a75cf4a6b3612c7b4191da
https://github.com/FineUploader/fine-uploader/blob/057cc83a7e7657d032a75cf4a6b3612c7b4191da/client/js/uploader.api.js#L310-L321
5,601
FineUploader/fine-uploader
client/js/uploader.api.js
function(id, name, loaded, total) { this._parent.prototype._onProgress.apply(this, arguments); this._templating.updateProgress(id, loaded, total); if (total === 0 || Math.round(loaded / total * 100) === 100) { this._templating.hideCancel(id); this._templating.hidePause(id); this._templating.hideProgress(id); this._templating.setStatusText(id, this._options.text.waitingForResponse); // If ~last byte was sent, display total file size this._displayFileSize(id); } else { // If still uploading, display percentage - total size is actually the total request(s) size this._displayFileSize(id, loaded, total); } }
javascript
function(id, name, loaded, total) { this._parent.prototype._onProgress.apply(this, arguments); this._templating.updateProgress(id, loaded, total); if (total === 0 || Math.round(loaded / total * 100) === 100) { this._templating.hideCancel(id); this._templating.hidePause(id); this._templating.hideProgress(id); this._templating.setStatusText(id, this._options.text.waitingForResponse); // If ~last byte was sent, display total file size this._displayFileSize(id); } else { // If still uploading, display percentage - total size is actually the total request(s) size this._displayFileSize(id, loaded, total); } }
[ "function", "(", "id", ",", "name", ",", "loaded", ",", "total", ")", "{", "this", ".", "_parent", ".", "prototype", ".", "_onProgress", ".", "apply", "(", "this", ",", "arguments", ")", ";", "this", ".", "_templating", ".", "updateProgress", "(", "id", ",", "loaded", ",", "total", ")", ";", "if", "(", "total", "===", "0", "||", "Math", ".", "round", "(", "loaded", "/", "total", "*", "100", ")", "===", "100", ")", "{", "this", ".", "_templating", ".", "hideCancel", "(", "id", ")", ";", "this", ".", "_templating", ".", "hidePause", "(", "id", ")", ";", "this", ".", "_templating", ".", "hideProgress", "(", "id", ")", ";", "this", ".", "_templating", ".", "setStatusText", "(", "id", ",", "this", ".", "_options", ".", "text", ".", "waitingForResponse", ")", ";", "// If ~last byte was sent, display total file size", "this", ".", "_displayFileSize", "(", "id", ")", ";", "}", "else", "{", "// If still uploading, display percentage - total size is actually the total request(s) size", "this", ".", "_displayFileSize", "(", "id", ",", "loaded", ",", "total", ")", ";", "}", "}" ]
Update the progress bar & percentage as the file is uploaded
[ "Update", "the", "progress", "bar", "&", "percentage", "as", "the", "file", "is", "uploaded" ]
057cc83a7e7657d032a75cf4a6b3612c7b4191da
https://github.com/FineUploader/fine-uploader/blob/057cc83a7e7657d032a75cf4a6b3612c7b4191da/client/js/uploader.api.js#L324-L342
5,602
FineUploader/fine-uploader
client/js/s3/multipart.initiate.ajax.requester.js
handleInitiateRequestComplete
function handleInitiateRequestComplete(id, xhr, isError) { var promise = pendingInitiateRequests[id], domParser = new DOMParser(), responseDoc = domParser.parseFromString(xhr.responseText, "application/xml"), uploadIdElements, messageElements, uploadId, errorMessage, status; delete pendingInitiateRequests[id]; // The base ajax requester may declare the request to be a failure based on status code. if (isError) { status = xhr.status; messageElements = responseDoc.getElementsByTagName("Message"); if (messageElements.length > 0) { errorMessage = messageElements[0].textContent; } } // If the base ajax requester has not declared this a failure, make sure we can retrieve the uploadId from the response. else { uploadIdElements = responseDoc.getElementsByTagName("UploadId"); if (uploadIdElements.length > 0) { uploadId = uploadIdElements[0].textContent; } else { errorMessage = "Upload ID missing from request"; } } // Either fail the promise (passing a descriptive error message) or declare it a success (passing the upload ID) if (uploadId === undefined) { if (errorMessage) { options.log(qq.format("Specific problem detected initiating multipart upload request for {}: '{}'.", id, errorMessage), "error"); } else { options.log(qq.format("Unexplained error with initiate multipart upload request for {}. Status code {}.", id, status), "error"); } promise.failure("Problem initiating upload request.", xhr); } else { options.log(qq.format("Initiate multipart upload request successful for {}. Upload ID is {}", id, uploadId)); promise.success(uploadId, xhr); } }
javascript
function handleInitiateRequestComplete(id, xhr, isError) { var promise = pendingInitiateRequests[id], domParser = new DOMParser(), responseDoc = domParser.parseFromString(xhr.responseText, "application/xml"), uploadIdElements, messageElements, uploadId, errorMessage, status; delete pendingInitiateRequests[id]; // The base ajax requester may declare the request to be a failure based on status code. if (isError) { status = xhr.status; messageElements = responseDoc.getElementsByTagName("Message"); if (messageElements.length > 0) { errorMessage = messageElements[0].textContent; } } // If the base ajax requester has not declared this a failure, make sure we can retrieve the uploadId from the response. else { uploadIdElements = responseDoc.getElementsByTagName("UploadId"); if (uploadIdElements.length > 0) { uploadId = uploadIdElements[0].textContent; } else { errorMessage = "Upload ID missing from request"; } } // Either fail the promise (passing a descriptive error message) or declare it a success (passing the upload ID) if (uploadId === undefined) { if (errorMessage) { options.log(qq.format("Specific problem detected initiating multipart upload request for {}: '{}'.", id, errorMessage), "error"); } else { options.log(qq.format("Unexplained error with initiate multipart upload request for {}. Status code {}.", id, status), "error"); } promise.failure("Problem initiating upload request.", xhr); } else { options.log(qq.format("Initiate multipart upload request successful for {}. Upload ID is {}", id, uploadId)); promise.success(uploadId, xhr); } }
[ "function", "handleInitiateRequestComplete", "(", "id", ",", "xhr", ",", "isError", ")", "{", "var", "promise", "=", "pendingInitiateRequests", "[", "id", "]", ",", "domParser", "=", "new", "DOMParser", "(", ")", ",", "responseDoc", "=", "domParser", ".", "parseFromString", "(", "xhr", ".", "responseText", ",", "\"application/xml\"", ")", ",", "uploadIdElements", ",", "messageElements", ",", "uploadId", ",", "errorMessage", ",", "status", ";", "delete", "pendingInitiateRequests", "[", "id", "]", ";", "// The base ajax requester may declare the request to be a failure based on status code.", "if", "(", "isError", ")", "{", "status", "=", "xhr", ".", "status", ";", "messageElements", "=", "responseDoc", ".", "getElementsByTagName", "(", "\"Message\"", ")", ";", "if", "(", "messageElements", ".", "length", ">", "0", ")", "{", "errorMessage", "=", "messageElements", "[", "0", "]", ".", "textContent", ";", "}", "}", "// If the base ajax requester has not declared this a failure, make sure we can retrieve the uploadId from the response.", "else", "{", "uploadIdElements", "=", "responseDoc", ".", "getElementsByTagName", "(", "\"UploadId\"", ")", ";", "if", "(", "uploadIdElements", ".", "length", ">", "0", ")", "{", "uploadId", "=", "uploadIdElements", "[", "0", "]", ".", "textContent", ";", "}", "else", "{", "errorMessage", "=", "\"Upload ID missing from request\"", ";", "}", "}", "// Either fail the promise (passing a descriptive error message) or declare it a success (passing the upload ID)", "if", "(", "uploadId", "===", "undefined", ")", "{", "if", "(", "errorMessage", ")", "{", "options", ".", "log", "(", "qq", ".", "format", "(", "\"Specific problem detected initiating multipart upload request for {}: '{}'.\"", ",", "id", ",", "errorMessage", ")", ",", "\"error\"", ")", ";", "}", "else", "{", "options", ".", "log", "(", "qq", ".", "format", "(", "\"Unexplained error with initiate multipart upload request for {}. Status code {}.\"", ",", "id", ",", "status", ")", ",", "\"error\"", ")", ";", "}", "promise", ".", "failure", "(", "\"Problem initiating upload request.\"", ",", "xhr", ")", ";", "}", "else", "{", "options", ".", "log", "(", "qq", ".", "format", "(", "\"Initiate multipart upload request successful for {}. Upload ID is {}\"", ",", "id", ",", "uploadId", ")", ")", ";", "promise", ".", "success", "(", "uploadId", ",", "xhr", ")", ";", "}", "}" ]
Called by the base ajax requester when the response has been received. We definitively determine here if the "Initiate MPU" request has been a success or not. @param id ID associated with the file. @param xhr `XMLHttpRequest` object containing the response, among other things. @param isError A boolean indicating success or failure according to the base ajax requester (primarily based on status code).
[ "Called", "by", "the", "base", "ajax", "requester", "when", "the", "response", "has", "been", "received", ".", "We", "definitively", "determine", "here", "if", "the", "Initiate", "MPU", "request", "has", "been", "a", "success", "or", "not", "." ]
057cc83a7e7657d032a75cf4a6b3612c7b4191da
https://github.com/FineUploader/fine-uploader/blob/057cc83a7e7657d032a75cf4a6b3612c7b4191da/client/js/s3/multipart.initiate.ajax.requester.js#L99-L142
5,603
FineUploader/fine-uploader
client/js/upload-handler/form.upload.handler.js
expungeFile
function expungeFile(id) { delete detachLoadEvents[id]; // If we are dealing with CORS, we might still be waiting for a response from a loaded iframe. // In that case, terminate the timer waiting for a message from the loaded iframe // and stop listening for any more messages coming from this iframe. if (isCors) { clearTimeout(postMessageCallbackTimers[id]); delete postMessageCallbackTimers[id]; corsMessageReceiver.stopReceivingMessages(id); } var iframe = document.getElementById(handler._getIframeName(id)); if (iframe) { // To cancel request set src to something else. We use src="javascript:false;" // because it doesn't trigger ie6 prompt on https /* jshint scripturl:true */ iframe.setAttribute("src", "javascript:false;"); qq(iframe).remove(); } }
javascript
function expungeFile(id) { delete detachLoadEvents[id]; // If we are dealing with CORS, we might still be waiting for a response from a loaded iframe. // In that case, terminate the timer waiting for a message from the loaded iframe // and stop listening for any more messages coming from this iframe. if (isCors) { clearTimeout(postMessageCallbackTimers[id]); delete postMessageCallbackTimers[id]; corsMessageReceiver.stopReceivingMessages(id); } var iframe = document.getElementById(handler._getIframeName(id)); if (iframe) { // To cancel request set src to something else. We use src="javascript:false;" // because it doesn't trigger ie6 prompt on https /* jshint scripturl:true */ iframe.setAttribute("src", "javascript:false;"); qq(iframe).remove(); } }
[ "function", "expungeFile", "(", "id", ")", "{", "delete", "detachLoadEvents", "[", "id", "]", ";", "// If we are dealing with CORS, we might still be waiting for a response from a loaded iframe.", "// In that case, terminate the timer waiting for a message from the loaded iframe", "// and stop listening for any more messages coming from this iframe.", "if", "(", "isCors", ")", "{", "clearTimeout", "(", "postMessageCallbackTimers", "[", "id", "]", ")", ";", "delete", "postMessageCallbackTimers", "[", "id", "]", ";", "corsMessageReceiver", ".", "stopReceivingMessages", "(", "id", ")", ";", "}", "var", "iframe", "=", "document", ".", "getElementById", "(", "handler", ".", "_getIframeName", "(", "id", ")", ")", ";", "if", "(", "iframe", ")", "{", "// To cancel request set src to something else. We use src=\"javascript:false;\"", "// because it doesn't trigger ie6 prompt on https", "/* jshint scripturl:true */", "iframe", ".", "setAttribute", "(", "\"src\"", ",", "\"javascript:false;\"", ")", ";", "qq", "(", "iframe", ")", ".", "remove", "(", ")", ";", "}", "}" ]
Remove any trace of the file from the handler. @param id ID of the associated file
[ "Remove", "any", "trace", "of", "the", "file", "from", "the", "handler", "." ]
057cc83a7e7657d032a75cf4a6b3612c7b4191da
https://github.com/FineUploader/fine-uploader/blob/057cc83a7e7657d032a75cf4a6b3612c7b4191da/client/js/upload-handler/form.upload.handler.js#L29-L50
5,604
FineUploader/fine-uploader
client/js/upload-handler/form.upload.handler.js
initIframeForUpload
function initIframeForUpload(name) { var iframe = qq.toElement("<iframe src='javascript:false;' name='" + name + "' />"); iframe.setAttribute("id", name); iframe.style.display = "none"; document.body.appendChild(iframe); return iframe; }
javascript
function initIframeForUpload(name) { var iframe = qq.toElement("<iframe src='javascript:false;' name='" + name + "' />"); iframe.setAttribute("id", name); iframe.style.display = "none"; document.body.appendChild(iframe); return iframe; }
[ "function", "initIframeForUpload", "(", "name", ")", "{", "var", "iframe", "=", "qq", ".", "toElement", "(", "\"<iframe src='javascript:false;' name='\"", "+", "name", "+", "\"' />\"", ")", ";", "iframe", ".", "setAttribute", "(", "\"id\"", ",", "name", ")", ";", "iframe", ".", "style", ".", "display", "=", "\"none\"", ";", "document", ".", "body", ".", "appendChild", "(", "iframe", ")", ";", "return", "iframe", ";", "}" ]
Generates an iframe to be used as a target for upload-related form submits. This also adds the iframe to the current `document`. Note that the iframe is hidden from view. @param name Name of the iframe. @returns {HTMLIFrameElement} The created iframe
[ "Generates", "an", "iframe", "to", "be", "used", "as", "a", "target", "for", "upload", "-", "related", "form", "submits", ".", "This", "also", "adds", "the", "iframe", "to", "the", "current", "document", ".", "Note", "that", "the", "iframe", "is", "hidden", "from", "view", "." ]
057cc83a7e7657d032a75cf4a6b3612c7b4191da
https://github.com/FineUploader/fine-uploader/blob/057cc83a7e7657d032a75cf4a6b3612c7b4191da/client/js/upload-handler/form.upload.handler.js#L67-L76
5,605
FineUploader/fine-uploader
client/js/upload-handler/form.upload.handler.js
function(id, fileInput) { super_.add(id, {input: fileInput}); fileInput.setAttribute("name", inputName); // remove file input from DOM if (fileInput.parentNode) { qq(fileInput).remove(); } }
javascript
function(id, fileInput) { super_.add(id, {input: fileInput}); fileInput.setAttribute("name", inputName); // remove file input from DOM if (fileInput.parentNode) { qq(fileInput).remove(); } }
[ "function", "(", "id", ",", "fileInput", ")", "{", "super_", ".", "add", "(", "id", ",", "{", "input", ":", "fileInput", "}", ")", ";", "fileInput", ".", "setAttribute", "(", "\"name\"", ",", "inputName", ")", ";", "// remove file input from DOM", "if", "(", "fileInput", ".", "parentNode", ")", "{", "qq", "(", "fileInput", ")", ".", "remove", "(", ")", ";", "}", "}" ]
Adds File or Blob to the queue
[ "Adds", "File", "or", "Blob", "to", "the", "queue" ]
057cc83a7e7657d032a75cf4a6b3612c7b4191da
https://github.com/FineUploader/fine-uploader/blob/057cc83a7e7657d032a75cf4a6b3612c7b4191da/client/js/upload-handler/form.upload.handler.js#L143-L152
5,606
FineUploader/fine-uploader
client/js/upload-handler/form.upload.handler.js
function(spec) { var method = spec.method, endpoint = spec.endpoint, params = spec.params, paramsInBody = spec.paramsInBody, targetName = spec.targetName, form = qq.toElement("<form method='" + method + "' enctype='multipart/form-data'></form>"), url = endpoint; if (paramsInBody) { qq.obj2Inputs(params, form); } else { url = qq.obj2url(params, endpoint); } form.setAttribute("action", url); form.setAttribute("target", targetName); form.style.display = "none"; document.body.appendChild(form); return form; }
javascript
function(spec) { var method = spec.method, endpoint = spec.endpoint, params = spec.params, paramsInBody = spec.paramsInBody, targetName = spec.targetName, form = qq.toElement("<form method='" + method + "' enctype='multipart/form-data'></form>"), url = endpoint; if (paramsInBody) { qq.obj2Inputs(params, form); } else { url = qq.obj2url(params, endpoint); } form.setAttribute("action", url); form.setAttribute("target", targetName); form.style.display = "none"; document.body.appendChild(form); return form; }
[ "function", "(", "spec", ")", "{", "var", "method", "=", "spec", ".", "method", ",", "endpoint", "=", "spec", ".", "endpoint", ",", "params", "=", "spec", ".", "params", ",", "paramsInBody", "=", "spec", ".", "paramsInBody", ",", "targetName", "=", "spec", ".", "targetName", ",", "form", "=", "qq", ".", "toElement", "(", "\"<form method='\"", "+", "method", "+", "\"' enctype='multipart/form-data'></form>\"", ")", ",", "url", "=", "endpoint", ";", "if", "(", "paramsInBody", ")", "{", "qq", ".", "obj2Inputs", "(", "params", ",", "form", ")", ";", "}", "else", "{", "url", "=", "qq", ".", "obj2url", "(", "params", ",", "endpoint", ")", ";", "}", "form", ".", "setAttribute", "(", "\"action\"", ",", "url", ")", ";", "form", ".", "setAttribute", "(", "\"target\"", ",", "targetName", ")", ";", "form", ".", "style", ".", "display", "=", "\"none\"", ";", "document", ".", "body", ".", "appendChild", "(", "form", ")", ";", "return", "form", ";", "}" ]
Generates a form element and appends it to the `document`. When the form is submitted, a specific iframe is targeted. The name of the iframe is passed in as a property of the spec parameter, and must be unique in the `document`. Note that the form is hidden from view. @param spec An object containing various properties to be used when constructing the form. Required properties are currently: `method`, `endpoint`, `params`, `paramsInBody`, and `targetName`. @returns {HTMLFormElement} The created form
[ "Generates", "a", "form", "element", "and", "appends", "it", "to", "the", "document", ".", "When", "the", "form", "is", "submitted", "a", "specific", "iframe", "is", "targeted", ".", "The", "name", "of", "the", "iframe", "is", "passed", "in", "as", "a", "property", "of", "the", "spec", "parameter", "and", "must", "be", "unique", "in", "the", "document", ".", "Note", "that", "the", "form", "is", "hidden", "from", "view", "." ]
057cc83a7e7657d032a75cf4a6b3612c7b4191da
https://github.com/FineUploader/fine-uploader/blob/057cc83a7e7657d032a75cf4a6b3612c7b4191da/client/js/upload-handler/form.upload.handler.js#L261-L283
5,607
FineUploader/fine-uploader
client/js/upload-handler/xhr.upload.handler.js
function(id, chunkIdx) { var fileState = handler._getFileState(id); if (fileState) { delete fileState.temp.cachedChunks[chunkIdx]; } }
javascript
function(id, chunkIdx) { var fileState = handler._getFileState(id); if (fileState) { delete fileState.temp.cachedChunks[chunkIdx]; } }
[ "function", "(", "id", ",", "chunkIdx", ")", "{", "var", "fileState", "=", "handler", ".", "_getFileState", "(", "id", ")", ";", "if", "(", "fileState", ")", "{", "delete", "fileState", ".", "temp", ".", "cachedChunks", "[", "chunkIdx", "]", ";", "}", "}" ]
Clear the cached chunk `Blob` after we are done with it, just in case the `Blob` bytes are stored in memory.
[ "Clear", "the", "cached", "chunk", "Blob", "after", "we", "are", "done", "with", "it", "just", "in", "case", "the", "Blob", "bytes", "are", "stored", "in", "memory", "." ]
057cc83a7e7657d032a75cf4a6b3612c7b4191da
https://github.com/FineUploader/fine-uploader/blob/057cc83a7e7657d032a75cf4a6b3612c7b4191da/client/js/upload-handler/xhr.upload.handler.js#L90-L96
5,608
FineUploader/fine-uploader
client/js/upload-handler/xhr.upload.handler.js
function(id, responseParser) { var lastChunkIdx = handler._getTotalChunks(id) - 1, xhr = handler._getXhr(id, lastChunkIdx); if (responseParser) { return new qq.Promise().success(responseParser(xhr), xhr); } return new qq.Promise().success({}, xhr); }
javascript
function(id, responseParser) { var lastChunkIdx = handler._getTotalChunks(id) - 1, xhr = handler._getXhr(id, lastChunkIdx); if (responseParser) { return new qq.Promise().success(responseParser(xhr), xhr); } return new qq.Promise().success({}, xhr); }
[ "function", "(", "id", ",", "responseParser", ")", "{", "var", "lastChunkIdx", "=", "handler", ".", "_getTotalChunks", "(", "id", ")", "-", "1", ",", "xhr", "=", "handler", ".", "_getXhr", "(", "id", ",", "lastChunkIdx", ")", ";", "if", "(", "responseParser", ")", "{", "return", "new", "qq", ".", "Promise", "(", ")", ".", "success", "(", "responseParser", "(", "xhr", ")", ",", "xhr", ")", ";", "}", "return", "new", "qq", ".", "Promise", "(", ")", ".", "success", "(", "{", "}", ",", "xhr", ")", ";", "}" ]
Called when all chunks have been successfully uploaded. Expected promissory return type. This defines the default behavior if nothing further is required when all chunks have been uploaded.
[ "Called", "when", "all", "chunks", "have", "been", "successfully", "uploaded", ".", "Expected", "promissory", "return", "type", ".", "This", "defines", "the", "default", "behavior", "if", "nothing", "further", "is", "required", "when", "all", "chunks", "have", "been", "uploaded", "." ]
057cc83a7e7657d032a75cf4a6b3612c7b4191da
https://github.com/FineUploader/fine-uploader/blob/057cc83a7e7657d032a75cf4a6b3612c7b4191da/client/js/upload-handler/xhr.upload.handler.js#L111-L120
5,609
FineUploader/fine-uploader
client/js/upload-handler/xhr.upload.handler.js
function(id) { var localStorageId; if (resumeEnabled && handler.isResumable(id)) { localStorageId = handler._getLocalStorageId(id); if (localStorageId && localStorage.getItem(localStorageId)) { localStorage.removeItem(localStorageId); return true; } } return false; }
javascript
function(id) { var localStorageId; if (resumeEnabled && handler.isResumable(id)) { localStorageId = handler._getLocalStorageId(id); if (localStorageId && localStorage.getItem(localStorageId)) { localStorage.removeItem(localStorageId); return true; } } return false; }
[ "function", "(", "id", ")", "{", "var", "localStorageId", ";", "if", "(", "resumeEnabled", "&&", "handler", ".", "isResumable", "(", "id", ")", ")", "{", "localStorageId", "=", "handler", ".", "_getLocalStorageId", "(", "id", ")", ";", "if", "(", "localStorageId", "&&", "localStorage", ".", "getItem", "(", "localStorageId", ")", ")", "{", "localStorage", ".", "removeItem", "(", "localStorageId", ")", ";", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Removes a chunked upload record from local storage, if possible. Returns true if the item was removed, false otherwise.
[ "Removes", "a", "chunked", "upload", "record", "from", "local", "storage", "if", "possible", ".", "Returns", "true", "if", "the", "item", "was", "removed", "false", "otherwise", "." ]
057cc83a7e7657d032a75cf4a6b3612c7b4191da
https://github.com/FineUploader/fine-uploader/blob/057cc83a7e7657d032a75cf4a6b3612c7b4191da/client/js/upload-handler/xhr.upload.handler.js#L368-L381
5,610
FineUploader/fine-uploader
client/js/upload-handler/xhr.upload.handler.js
function(id, optChunkIdx, xhr, optAjaxRequester) { var xhrsId = optChunkIdx == null ? -1 : optChunkIdx, tempState = handler._getFileState(id).temp; tempState.xhrs = tempState.xhrs || {}; tempState.ajaxRequesters = tempState.ajaxRequesters || {}; tempState.xhrs[xhrsId] = xhr; if (optAjaxRequester) { tempState.ajaxRequesters[xhrsId] = optAjaxRequester; } return xhr; }
javascript
function(id, optChunkIdx, xhr, optAjaxRequester) { var xhrsId = optChunkIdx == null ? -1 : optChunkIdx, tempState = handler._getFileState(id).temp; tempState.xhrs = tempState.xhrs || {}; tempState.ajaxRequesters = tempState.ajaxRequesters || {}; tempState.xhrs[xhrsId] = xhr; if (optAjaxRequester) { tempState.ajaxRequesters[xhrsId] = optAjaxRequester; } return xhr; }
[ "function", "(", "id", ",", "optChunkIdx", ",", "xhr", ",", "optAjaxRequester", ")", "{", "var", "xhrsId", "=", "optChunkIdx", "==", "null", "?", "-", "1", ":", "optChunkIdx", ",", "tempState", "=", "handler", ".", "_getFileState", "(", "id", ")", ".", "temp", ";", "tempState", ".", "xhrs", "=", "tempState", ".", "xhrs", "||", "{", "}", ";", "tempState", ".", "ajaxRequesters", "=", "tempState", ".", "ajaxRequesters", "||", "{", "}", ";", "tempState", ".", "xhrs", "[", "xhrsId", "]", "=", "xhr", ";", "if", "(", "optAjaxRequester", ")", "{", "tempState", ".", "ajaxRequesters", "[", "xhrsId", "]", "=", "optAjaxRequester", ";", "}", "return", "xhr", ";", "}" ]
Registers an XHR transport instance created elsewhere. @param id ID of the associated file @param optChunkIdx The chunk index associated with this XHR, if applicable @param xhr XMLHttpRequest object instance @param optAjaxRequester `qq.AjaxRequester` associated with this request, if applicable. @returns {XMLHttpRequest}
[ "Registers", "an", "XHR", "transport", "instance", "created", "elsewhere", "." ]
057cc83a7e7657d032a75cf4a6b3612c7b4191da
https://github.com/FineUploader/fine-uploader/blob/057cc83a7e7657d032a75cf4a6b3612c7b4191da/client/js/upload-handler/xhr.upload.handler.js#L507-L521
5,611
FineUploader/fine-uploader
client/js/upload-handler/xhr.upload.handler.js
function() { var expirationDays = resume.recordsExpireIn; handler._iterateResumeRecords(function(key, uploadData) { var expirationDate = new Date(uploadData.lastUpdated); // transform updated date into expiration date expirationDate.setDate(expirationDate.getDate() + expirationDays); if (expirationDate.getTime() <= Date.now()) { log("Removing expired resume record with key " + key); localStorage.removeItem(key); } }); }
javascript
function() { var expirationDays = resume.recordsExpireIn; handler._iterateResumeRecords(function(key, uploadData) { var expirationDate = new Date(uploadData.lastUpdated); // transform updated date into expiration date expirationDate.setDate(expirationDate.getDate() + expirationDays); if (expirationDate.getTime() <= Date.now()) { log("Removing expired resume record with key " + key); localStorage.removeItem(key); } }); }
[ "function", "(", ")", "{", "var", "expirationDays", "=", "resume", ".", "recordsExpireIn", ";", "handler", ".", "_iterateResumeRecords", "(", "function", "(", "key", ",", "uploadData", ")", "{", "var", "expirationDate", "=", "new", "Date", "(", "uploadData", ".", "lastUpdated", ")", ";", "// transform updated date into expiration date", "expirationDate", ".", "setDate", "(", "expirationDate", ".", "getDate", "(", ")", "+", "expirationDays", ")", ";", "if", "(", "expirationDate", ".", "getTime", "(", ")", "<=", "Date", ".", "now", "(", ")", ")", "{", "log", "(", "\"Removing expired resume record with key \"", "+", "key", ")", ";", "localStorage", ".", "removeItem", "(", "key", ")", ";", "}", "}", ")", ";", "}" ]
Deletes any local storage records that are "expired".
[ "Deletes", "any", "local", "storage", "records", "that", "are", "expired", "." ]
057cc83a7e7657d032a75cf4a6b3612c7b4191da
https://github.com/FineUploader/fine-uploader/blob/057cc83a7e7657d032a75cf4a6b3612c7b4191da/client/js/upload-handler/xhr.upload.handler.js#L524-L538
5,612
elastic/apm-agent-nodejs
lib/instrumentation/express-utils.js
routePath
function routePath (route) { if (!route) return '' return route.path || (route.regexp && route.regexp.source) || '' }
javascript
function routePath (route) { if (!route) return '' return route.path || (route.regexp && route.regexp.source) || '' }
[ "function", "routePath", "(", "route", ")", "{", "if", "(", "!", "route", ")", "return", "''", "return", "route", ".", "path", "||", "(", "route", ".", "regexp", "&&", "route", ".", "regexp", ".", "source", ")", "||", "''", "}" ]
This works for both express AND restify
[ "This", "works", "for", "both", "express", "AND", "restify" ]
f23ca65801d7fee794e0d8f1f95275b7c0ad7417
https://github.com/elastic/apm-agent-nodejs/blob/f23ca65801d7fee794e0d8f1f95275b7c0ad7417/lib/instrumentation/express-utils.js#L24-L27
5,613
elastic/apm-agent-nodejs
lib/instrumentation/express-utils.js
getPathFromRequest
function getPathFromRequest (req, useBase, usePathAsTransactionName) { // Static serving route if (req[symbols.staticFile]) { return 'static file' } var path = getStackPath(req) var route = routePath(req.route) if (route) { return path ? join([ path, route ]) : route } if (useBase) { return path } // Enable usePathAsTransactionName config if (usePathAsTransactionName) { const parsed = parseUrl(req) return parsed && parsed.pathname } }
javascript
function getPathFromRequest (req, useBase, usePathAsTransactionName) { // Static serving route if (req[symbols.staticFile]) { return 'static file' } var path = getStackPath(req) var route = routePath(req.route) if (route) { return path ? join([ path, route ]) : route } if (useBase) { return path } // Enable usePathAsTransactionName config if (usePathAsTransactionName) { const parsed = parseUrl(req) return parsed && parsed.pathname } }
[ "function", "getPathFromRequest", "(", "req", ",", "useBase", ",", "usePathAsTransactionName", ")", "{", "// Static serving route", "if", "(", "req", "[", "symbols", ".", "staticFile", "]", ")", "{", "return", "'static file'", "}", "var", "path", "=", "getStackPath", "(", "req", ")", "var", "route", "=", "routePath", "(", "req", ".", "route", ")", "if", "(", "route", ")", "{", "return", "path", "?", "join", "(", "[", "path", ",", "route", "]", ")", ":", "route", "}", "if", "(", "useBase", ")", "{", "return", "path", "}", "// Enable usePathAsTransactionName config", "if", "(", "usePathAsTransactionName", ")", "{", "const", "parsed", "=", "parseUrl", "(", "req", ")", "return", "parsed", "&&", "parsed", ".", "pathname", "}", "}" ]
This function is also able to extract the path from a Restify request as it's storing the route name on req.route.path as well
[ "This", "function", "is", "also", "able", "to", "extract", "the", "path", "from", "a", "Restify", "request", "as", "it", "s", "storing", "the", "route", "name", "on", "req", ".", "route", ".", "path", "as", "well" ]
f23ca65801d7fee794e0d8f1f95275b7c0ad7417
https://github.com/elastic/apm-agent-nodejs/blob/f23ca65801d7fee794e0d8f1f95275b7c0ad7417/lib/instrumentation/express-utils.js#L37-L59
5,614
elastic/apm-agent-nodejs
lib/instrumentation/patch-async.js
activator
function activator (fn) { var fallback = function () { var args var cbIdx = arguments.length - 1 if (typeof arguments[cbIdx] === 'function') { args = Array(arguments.length) for (var i = 0; i < arguments.length - 1; i++) { args[i] = arguments[i] } args[cbIdx] = ins.bindFunction(arguments[cbIdx]) } return fn.apply(this, args || arguments) } // Preserve function length for small arg count functions. switch (fn.length) { case 1: return function (cb) { if (arguments.length !== 1) return fallback.apply(this, arguments) if (typeof cb === 'function') cb = ins.bindFunction(cb) return fn.call(this, cb) } case 2: return function (a, cb) { if (arguments.length !== 2) return fallback.apply(this, arguments) if (typeof cb === 'function') cb = ins.bindFunction(cb) return fn.call(this, a, cb) } case 3: return function (a, b, cb) { if (arguments.length !== 3) return fallback.apply(this, arguments) if (typeof cb === 'function') cb = ins.bindFunction(cb) return fn.call(this, a, b, cb) } case 4: return function (a, b, c, cb) { if (arguments.length !== 4) return fallback.apply(this, arguments) if (typeof cb === 'function') cb = ins.bindFunction(cb) return fn.call(this, a, b, c, cb) } case 5: return function (a, b, c, d, cb) { if (arguments.length !== 5) return fallback.apply(this, arguments) if (typeof cb === 'function') cb = ins.bindFunction(cb) return fn.call(this, a, b, c, d, cb) } case 6: return function (a, b, c, d, e, cb) { if (arguments.length !== 6) return fallback.apply(this, arguments) if (typeof cb === 'function') cb = ins.bindFunction(cb) return fn.call(this, a, b, c, d, e, cb) } default: return fallback } }
javascript
function activator (fn) { var fallback = function () { var args var cbIdx = arguments.length - 1 if (typeof arguments[cbIdx] === 'function') { args = Array(arguments.length) for (var i = 0; i < arguments.length - 1; i++) { args[i] = arguments[i] } args[cbIdx] = ins.bindFunction(arguments[cbIdx]) } return fn.apply(this, args || arguments) } // Preserve function length for small arg count functions. switch (fn.length) { case 1: return function (cb) { if (arguments.length !== 1) return fallback.apply(this, arguments) if (typeof cb === 'function') cb = ins.bindFunction(cb) return fn.call(this, cb) } case 2: return function (a, cb) { if (arguments.length !== 2) return fallback.apply(this, arguments) if (typeof cb === 'function') cb = ins.bindFunction(cb) return fn.call(this, a, cb) } case 3: return function (a, b, cb) { if (arguments.length !== 3) return fallback.apply(this, arguments) if (typeof cb === 'function') cb = ins.bindFunction(cb) return fn.call(this, a, b, cb) } case 4: return function (a, b, c, cb) { if (arguments.length !== 4) return fallback.apply(this, arguments) if (typeof cb === 'function') cb = ins.bindFunction(cb) return fn.call(this, a, b, c, cb) } case 5: return function (a, b, c, d, cb) { if (arguments.length !== 5) return fallback.apply(this, arguments) if (typeof cb === 'function') cb = ins.bindFunction(cb) return fn.call(this, a, b, c, d, cb) } case 6: return function (a, b, c, d, e, cb) { if (arguments.length !== 6) return fallback.apply(this, arguments) if (typeof cb === 'function') cb = ins.bindFunction(cb) return fn.call(this, a, b, c, d, e, cb) } default: return fallback } }
[ "function", "activator", "(", "fn", ")", "{", "var", "fallback", "=", "function", "(", ")", "{", "var", "args", "var", "cbIdx", "=", "arguments", ".", "length", "-", "1", "if", "(", "typeof", "arguments", "[", "cbIdx", "]", "===", "'function'", ")", "{", "args", "=", "Array", "(", "arguments", ".", "length", ")", "for", "(", "var", "i", "=", "0", ";", "i", "<", "arguments", ".", "length", "-", "1", ";", "i", "++", ")", "{", "args", "[", "i", "]", "=", "arguments", "[", "i", "]", "}", "args", "[", "cbIdx", "]", "=", "ins", ".", "bindFunction", "(", "arguments", "[", "cbIdx", "]", ")", "}", "return", "fn", ".", "apply", "(", "this", ",", "args", "||", "arguments", ")", "}", "// Preserve function length for small arg count functions.", "switch", "(", "fn", ".", "length", ")", "{", "case", "1", ":", "return", "function", "(", "cb", ")", "{", "if", "(", "arguments", ".", "length", "!==", "1", ")", "return", "fallback", ".", "apply", "(", "this", ",", "arguments", ")", "if", "(", "typeof", "cb", "===", "'function'", ")", "cb", "=", "ins", ".", "bindFunction", "(", "cb", ")", "return", "fn", ".", "call", "(", "this", ",", "cb", ")", "}", "case", "2", ":", "return", "function", "(", "a", ",", "cb", ")", "{", "if", "(", "arguments", ".", "length", "!==", "2", ")", "return", "fallback", ".", "apply", "(", "this", ",", "arguments", ")", "if", "(", "typeof", "cb", "===", "'function'", ")", "cb", "=", "ins", ".", "bindFunction", "(", "cb", ")", "return", "fn", ".", "call", "(", "this", ",", "a", ",", "cb", ")", "}", "case", "3", ":", "return", "function", "(", "a", ",", "b", ",", "cb", ")", "{", "if", "(", "arguments", ".", "length", "!==", "3", ")", "return", "fallback", ".", "apply", "(", "this", ",", "arguments", ")", "if", "(", "typeof", "cb", "===", "'function'", ")", "cb", "=", "ins", ".", "bindFunction", "(", "cb", ")", "return", "fn", ".", "call", "(", "this", ",", "a", ",", "b", ",", "cb", ")", "}", "case", "4", ":", "return", "function", "(", "a", ",", "b", ",", "c", ",", "cb", ")", "{", "if", "(", "arguments", ".", "length", "!==", "4", ")", "return", "fallback", ".", "apply", "(", "this", ",", "arguments", ")", "if", "(", "typeof", "cb", "===", "'function'", ")", "cb", "=", "ins", ".", "bindFunction", "(", "cb", ")", "return", "fn", ".", "call", "(", "this", ",", "a", ",", "b", ",", "c", ",", "cb", ")", "}", "case", "5", ":", "return", "function", "(", "a", ",", "b", ",", "c", ",", "d", ",", "cb", ")", "{", "if", "(", "arguments", ".", "length", "!==", "5", ")", "return", "fallback", ".", "apply", "(", "this", ",", "arguments", ")", "if", "(", "typeof", "cb", "===", "'function'", ")", "cb", "=", "ins", ".", "bindFunction", "(", "cb", ")", "return", "fn", ".", "call", "(", "this", ",", "a", ",", "b", ",", "c", ",", "d", ",", "cb", ")", "}", "case", "6", ":", "return", "function", "(", "a", ",", "b", ",", "c", ",", "d", ",", "e", ",", "cb", ")", "{", "if", "(", "arguments", ".", "length", "!==", "6", ")", "return", "fallback", ".", "apply", "(", "this", ",", "arguments", ")", "if", "(", "typeof", "cb", "===", "'function'", ")", "cb", "=", "ins", ".", "bindFunction", "(", "cb", ")", "return", "fn", ".", "call", "(", "this", ",", "a", ",", "b", ",", "c", ",", "d", ",", "e", ",", "cb", ")", "}", "default", ":", "return", "fallback", "}", "}" ]
Shim activator for functions that have callback last
[ "Shim", "activator", "for", "functions", "that", "have", "callback", "last" ]
f23ca65801d7fee794e0d8f1f95275b7c0ad7417
https://github.com/elastic/apm-agent-nodejs/blob/f23ca65801d7fee794e0d8f1f95275b7c0ad7417/lib/instrumentation/patch-async.js#L420-L474
5,615
elastic/apm-agent-nodejs
lib/instrumentation/modules/ioredis.js
wrapInitPromise
function wrapInitPromise (original) { return function wrappedInitPromise () { var command = this var cb = this.callback if (typeof cb === 'function') { this.callback = agent._instrumentation.bindFunction(function wrappedCallback () { var span = command[spanSym] if (span && !span.ended) span.end() return cb.apply(this, arguments) }) } return original.apply(this, arguments) } }
javascript
function wrapInitPromise (original) { return function wrappedInitPromise () { var command = this var cb = this.callback if (typeof cb === 'function') { this.callback = agent._instrumentation.bindFunction(function wrappedCallback () { var span = command[spanSym] if (span && !span.ended) span.end() return cb.apply(this, arguments) }) } return original.apply(this, arguments) } }
[ "function", "wrapInitPromise", "(", "original", ")", "{", "return", "function", "wrappedInitPromise", "(", ")", "{", "var", "command", "=", "this", "var", "cb", "=", "this", ".", "callback", "if", "(", "typeof", "cb", "===", "'function'", ")", "{", "this", ".", "callback", "=", "agent", ".", "_instrumentation", ".", "bindFunction", "(", "function", "wrappedCallback", "(", ")", "{", "var", "span", "=", "command", "[", "spanSym", "]", "if", "(", "span", "&&", "!", "span", ".", "ended", ")", "span", ".", "end", "(", ")", "return", "cb", ".", "apply", "(", "this", ",", "arguments", ")", "}", ")", "}", "return", "original", ".", "apply", "(", "this", ",", "arguments", ")", "}", "}" ]
wrap initPromise to allow us to get notified when the callback to a command is called. If we don't do this we will still get notified because we register a callback with command.promise.finally the wrappedSendCommand, but the finally call will not get fired until the tick after the command.callback have fired, so if the transaction is ended in the same tick as the call to command.callback, we'll lose the last span as it hasn't yet ended.
[ "wrap", "initPromise", "to", "allow", "us", "to", "get", "notified", "when", "the", "callback", "to", "a", "command", "is", "called", ".", "If", "we", "don", "t", "do", "this", "we", "will", "still", "get", "notified", "because", "we", "register", "a", "callback", "with", "command", ".", "promise", ".", "finally", "the", "wrappedSendCommand", "but", "the", "finally", "call", "will", "not", "get", "fired", "until", "the", "tick", "after", "the", "command", ".", "callback", "have", "fired", "so", "if", "the", "transaction", "is", "ended", "in", "the", "same", "tick", "as", "the", "call", "to", "command", ".", "callback", "we", "ll", "lose", "the", "last", "span", "as", "it", "hasn", "t", "yet", "ended", "." ]
f23ca65801d7fee794e0d8f1f95275b7c0ad7417
https://github.com/elastic/apm-agent-nodejs/blob/f23ca65801d7fee794e0d8f1f95275b7c0ad7417/lib/instrumentation/modules/ioredis.js#L32-L47
5,616
elastic/apm-agent-nodejs
lib/instrumentation/modules/http2.js
wrapCreateServer
function wrapCreateServer (original) { return function wrappedCreateServer (options, handler) { var server = original.apply(this, arguments) shimmer.wrap(server.constructor.prototype, 'emit', wrapEmit) wrappedCreateServer[symbols.unwrap]() return server } }
javascript
function wrapCreateServer (original) { return function wrappedCreateServer (options, handler) { var server = original.apply(this, arguments) shimmer.wrap(server.constructor.prototype, 'emit', wrapEmit) wrappedCreateServer[symbols.unwrap]() return server } }
[ "function", "wrapCreateServer", "(", "original", ")", "{", "return", "function", "wrappedCreateServer", "(", "options", ",", "handler", ")", "{", "var", "server", "=", "original", ".", "apply", "(", "this", ",", "arguments", ")", "shimmer", ".", "wrap", "(", "server", ".", "constructor", ".", "prototype", ",", "'emit'", ",", "wrapEmit", ")", "wrappedCreateServer", "[", "symbols", ".", "unwrap", "]", "(", ")", "return", "server", "}", "}" ]
The `createServer` function will unpatch itself after patching the first server prototype it patches.
[ "The", "createServer", "function", "will", "unpatch", "itself", "after", "patching", "the", "first", "server", "prototype", "it", "patches", "." ]
f23ca65801d7fee794e0d8f1f95275b7c0ad7417
https://github.com/elastic/apm-agent-nodejs/blob/f23ca65801d7fee794e0d8f1f95275b7c0ad7417/lib/instrumentation/modules/http2.js#L22-L29
5,617
elastic/apm-agent-nodejs
lib/parsers.js
getCulprit
function getCulprit (frames) { if (frames.length === 0) return var filename = frames[0].filename var fnName = frames[0].function for (var n = 0; n < frames.length; n++) { if (!frames[n].library_frame) { filename = frames[n].filename fnName = frames[n].function break } } return filename ? fnName + ' (' + filename + ')' : fnName }
javascript
function getCulprit (frames) { if (frames.length === 0) return var filename = frames[0].filename var fnName = frames[0].function for (var n = 0; n < frames.length; n++) { if (!frames[n].library_frame) { filename = frames[n].filename fnName = frames[n].function break } } return filename ? fnName + ' (' + filename + ')' : fnName }
[ "function", "getCulprit", "(", "frames", ")", "{", "if", "(", "frames", ".", "length", "===", "0", ")", "return", "var", "filename", "=", "frames", "[", "0", "]", ".", "filename", "var", "fnName", "=", "frames", "[", "0", "]", ".", "function", "for", "(", "var", "n", "=", "0", ";", "n", "<", "frames", ".", "length", ";", "n", "++", ")", "{", "if", "(", "!", "frames", "[", "n", "]", ".", "library_frame", ")", "{", "filename", "=", "frames", "[", "n", "]", ".", "filename", "fnName", "=", "frames", "[", "n", "]", ".", "function", "break", "}", "}", "return", "filename", "?", "fnName", "+", "' ('", "+", "filename", "+", "')'", ":", "fnName", "}" ]
Default `culprit` to the top of the stack or the highest non `library_frame` frame if such exists
[ "Default", "culprit", "to", "the", "top", "of", "the", "stack", "or", "the", "highest", "non", "library_frame", "frame", "if", "such", "exists" ]
f23ca65801d7fee794e0d8f1f95275b7c0ad7417
https://github.com/elastic/apm-agent-nodejs/blob/f23ca65801d7fee794e0d8f1f95275b7c0ad7417/lib/parsers.js#L220-L234
5,618
GoogleChromeLabs/carlo
lib/find_chrome.js
linux
function linux(canary) { let installations = []; // Look into the directories where .desktop are saved on gnome based distro's const desktopInstallationFolders = [ path.join(require('os').homedir(), '.local/share/applications/'), '/usr/share/applications/', ]; desktopInstallationFolders.forEach(folder => { installations = installations.concat(findChromeExecutables(folder)); }); // Look for google-chrome(-stable) & chromium(-browser) executables by using the which command const executables = [ 'google-chrome-stable', 'google-chrome', 'chromium-browser', 'chromium', ]; executables.forEach(executable => { try { const chromePath = execFileSync('which', [executable], {stdio: 'pipe'}).toString().split(newLineRegex)[0]; if (canAccess(chromePath)) installations.push(chromePath); } catch (e) { // Not installed. } }); if (!installations.length) throw new Error('The environment variable CHROME_PATH must be set to executable of a build of Chromium version 54.0 or later.'); const priorities = [ {regex: /chrome-wrapper$/, weight: 51}, {regex: /google-chrome-stable$/, weight: 50}, {regex: /google-chrome$/, weight: 49}, {regex: /chromium-browser$/, weight: 48}, {regex: /chromium$/, weight: 47}, ]; if (process.env.CHROME_PATH) priorities.unshift({regex: new RegExp(`${process.env.CHROME_PATH}`), weight: 101}); return sort(uniq(installations.filter(Boolean)), priorities)[0]; }
javascript
function linux(canary) { let installations = []; // Look into the directories where .desktop are saved on gnome based distro's const desktopInstallationFolders = [ path.join(require('os').homedir(), '.local/share/applications/'), '/usr/share/applications/', ]; desktopInstallationFolders.forEach(folder => { installations = installations.concat(findChromeExecutables(folder)); }); // Look for google-chrome(-stable) & chromium(-browser) executables by using the which command const executables = [ 'google-chrome-stable', 'google-chrome', 'chromium-browser', 'chromium', ]; executables.forEach(executable => { try { const chromePath = execFileSync('which', [executable], {stdio: 'pipe'}).toString().split(newLineRegex)[0]; if (canAccess(chromePath)) installations.push(chromePath); } catch (e) { // Not installed. } }); if (!installations.length) throw new Error('The environment variable CHROME_PATH must be set to executable of a build of Chromium version 54.0 or later.'); const priorities = [ {regex: /chrome-wrapper$/, weight: 51}, {regex: /google-chrome-stable$/, weight: 50}, {regex: /google-chrome$/, weight: 49}, {regex: /chromium-browser$/, weight: 48}, {regex: /chromium$/, weight: 47}, ]; if (process.env.CHROME_PATH) priorities.unshift({regex: new RegExp(`${process.env.CHROME_PATH}`), weight: 101}); return sort(uniq(installations.filter(Boolean)), priorities)[0]; }
[ "function", "linux", "(", "canary", ")", "{", "let", "installations", "=", "[", "]", ";", "// Look into the directories where .desktop are saved on gnome based distro's", "const", "desktopInstallationFolders", "=", "[", "path", ".", "join", "(", "require", "(", "'os'", ")", ".", "homedir", "(", ")", ",", "'.local/share/applications/'", ")", ",", "'/usr/share/applications/'", ",", "]", ";", "desktopInstallationFolders", ".", "forEach", "(", "folder", "=>", "{", "installations", "=", "installations", ".", "concat", "(", "findChromeExecutables", "(", "folder", ")", ")", ";", "}", ")", ";", "// Look for google-chrome(-stable) & chromium(-browser) executables by using the which command", "const", "executables", "=", "[", "'google-chrome-stable'", ",", "'google-chrome'", ",", "'chromium-browser'", ",", "'chromium'", ",", "]", ";", "executables", ".", "forEach", "(", "executable", "=>", "{", "try", "{", "const", "chromePath", "=", "execFileSync", "(", "'which'", ",", "[", "executable", "]", ",", "{", "stdio", ":", "'pipe'", "}", ")", ".", "toString", "(", ")", ".", "split", "(", "newLineRegex", ")", "[", "0", "]", ";", "if", "(", "canAccess", "(", "chromePath", ")", ")", "installations", ".", "push", "(", "chromePath", ")", ";", "}", "catch", "(", "e", ")", "{", "// Not installed.", "}", "}", ")", ";", "if", "(", "!", "installations", ".", "length", ")", "throw", "new", "Error", "(", "'The environment variable CHROME_PATH must be set to executable of a build of Chromium version 54.0 or later.'", ")", ";", "const", "priorities", "=", "[", "{", "regex", ":", "/", "chrome-wrapper$", "/", ",", "weight", ":", "51", "}", ",", "{", "regex", ":", "/", "google-chrome-stable$", "/", ",", "weight", ":", "50", "}", ",", "{", "regex", ":", "/", "google-chrome$", "/", ",", "weight", ":", "49", "}", ",", "{", "regex", ":", "/", "chromium-browser$", "/", ",", "weight", ":", "48", "}", ",", "{", "regex", ":", "/", "chromium$", "/", ",", "weight", ":", "47", "}", ",", "]", ";", "if", "(", "process", ".", "env", ".", "CHROME_PATH", ")", "priorities", ".", "unshift", "(", "{", "regex", ":", "new", "RegExp", "(", "`", "${", "process", ".", "env", ".", "CHROME_PATH", "}", "`", ")", ",", "weight", ":", "101", "}", ")", ";", "return", "sort", "(", "uniq", "(", "installations", ".", "filter", "(", "Boolean", ")", ")", ",", "priorities", ")", "[", "0", "]", ";", "}" ]
Look for linux executables in 3 ways 1. Look into CHROME_PATH env variable 2. Look into the directories where .desktop are saved on gnome based distro's 3. Look for google-chrome-stable & google-chrome executables by using the which command
[ "Look", "for", "linux", "executables", "in", "3", "ways", "1", ".", "Look", "into", "CHROME_PATH", "env", "variable", "2", ".", "Look", "into", "the", "directories", "where", ".", "desktop", "are", "saved", "on", "gnome", "based", "distro", "s", "3", ".", "Look", "for", "google", "-", "chrome", "-", "stable", "&", "google", "-", "chrome", "executables", "by", "using", "the", "which", "command" ]
c79322776443a0564f110fd3e45b8d2042924d1d
https://github.com/GoogleChromeLabs/carlo/blob/c79322776443a0564f110fd3e45b8d2042924d1d/lib/find_chrome.js#L53-L98
5,619
renovatebot/renovate
lib/manager/pipenv/update.js
matchAt
function matchAt(content, index, match) { return content.substring(index, index + match.length) === match; }
javascript
function matchAt(content, index, match) { return content.substring(index, index + match.length) === match; }
[ "function", "matchAt", "(", "content", ",", "index", ",", "match", ")", "{", "return", "content", ".", "substring", "(", "index", ",", "index", "+", "match", ".", "length", ")", "===", "match", ";", "}" ]
Return true if the match string is found at index in content
[ "Return", "true", "if", "the", "match", "string", "is", "found", "at", "index", "in", "content" ]
01b5ae2638350525a829a15aef7631ab3c13aae5
https://github.com/renovatebot/renovate/blob/01b5ae2638350525a829a15aef7631ab3c13aae5/lib/manager/pipenv/update.js#L9-L11
5,620
renovatebot/renovate
lib/manager/pipenv/update.js
replaceAt
function replaceAt(content, index, oldString, newString) { logger.debug(`Replacing ${oldString} with ${newString} at index ${index}`); return ( content.substr(0, index) + newString + content.substr(index + oldString.length) ); }
javascript
function replaceAt(content, index, oldString, newString) { logger.debug(`Replacing ${oldString} with ${newString} at index ${index}`); return ( content.substr(0, index) + newString + content.substr(index + oldString.length) ); }
[ "function", "replaceAt", "(", "content", ",", "index", ",", "oldString", ",", "newString", ")", "{", "logger", ".", "debug", "(", "`", "${", "oldString", "}", "${", "newString", "}", "${", "index", "}", "`", ")", ";", "return", "(", "content", ".", "substr", "(", "0", ",", "index", ")", "+", "newString", "+", "content", ".", "substr", "(", "index", "+", "oldString", ".", "length", ")", ")", ";", "}" ]
Replace oldString with newString at location index of content
[ "Replace", "oldString", "with", "newString", "at", "location", "index", "of", "content" ]
01b5ae2638350525a829a15aef7631ab3c13aae5
https://github.com/renovatebot/renovate/blob/01b5ae2638350525a829a15aef7631ab3c13aae5/lib/manager/pipenv/update.js#L14-L21
5,621
renovatebot/renovate
lib/platform/bitbucket-server/index.js
getFileList
function getFileList(branchName = config.baseBranch) { logger.debug(`getFileList(${branchName})`); return config.storage.getFileList(branchName); }
javascript
function getFileList(branchName = config.baseBranch) { logger.debug(`getFileList(${branchName})`); return config.storage.getFileList(branchName); }
[ "function", "getFileList", "(", "branchName", "=", "config", ".", "baseBranch", ")", "{", "logger", ".", "debug", "(", "`", "${", "branchName", "}", "`", ")", ";", "return", "config", ".", "storage", ".", "getFileList", "(", "branchName", ")", ";", "}" ]
Search Get full file list
[ "Search", "Get", "full", "file", "list" ]
01b5ae2638350525a829a15aef7631ab3c13aae5
https://github.com/renovatebot/renovate/blob/01b5ae2638350525a829a15aef7631ab3c13aae5/lib/platform/bitbucket-server/index.js#L195-L198
5,622
renovatebot/renovate
lib/config/massage.js
massageConfig
function massageConfig(config) { if (!allowedStrings) { allowedStrings = []; options.forEach(option => { if (option.allowString) { allowedStrings.push(option.name); } }); } const massagedConfig = clone(config); for (const [key, val] of Object.entries(config)) { if (allowedStrings.includes(key) && is.string(val)) { massagedConfig[key] = [val]; } else if (key === 'npmToken' && val && val.length < 50) { massagedConfig.npmrc = `//registry.npmjs.org/:_authToken=${val}\n`; delete massagedConfig.npmToken; } else if (is.array(val)) { massagedConfig[key] = []; val.forEach(item => { if (is.object(item)) { massagedConfig[key].push(massageConfig(item)); } else { massagedConfig[key].push(item); } }); } else if (is.object(val) && key !== 'encrypted') { massagedConfig[key] = massageConfig(val); } } if (is.nonEmptyArray(massagedConfig.packageRules)) { const newRules = []; const updateTypes = [ 'major', 'minor', 'patch', 'pin', 'digest', 'lockFileMaintenance', 'rollback', ]; for (const rule of massagedConfig.packageRules) { newRules.push(rule); for (const [key, val] of Object.entries(rule)) { if (updateTypes.includes(key)) { const newRule = clone(rule); newRule.updateTypes = rule.updateTypes || []; newRule.updateTypes.push(key); Object.assign(newRule, val); newRules.push(newRule); } } } for (const rule of newRules) { updateTypes.forEach(updateType => { delete rule[updateType]; }); } massagedConfig.packageRules = newRules; } return massagedConfig; }
javascript
function massageConfig(config) { if (!allowedStrings) { allowedStrings = []; options.forEach(option => { if (option.allowString) { allowedStrings.push(option.name); } }); } const massagedConfig = clone(config); for (const [key, val] of Object.entries(config)) { if (allowedStrings.includes(key) && is.string(val)) { massagedConfig[key] = [val]; } else if (key === 'npmToken' && val && val.length < 50) { massagedConfig.npmrc = `//registry.npmjs.org/:_authToken=${val}\n`; delete massagedConfig.npmToken; } else if (is.array(val)) { massagedConfig[key] = []; val.forEach(item => { if (is.object(item)) { massagedConfig[key].push(massageConfig(item)); } else { massagedConfig[key].push(item); } }); } else if (is.object(val) && key !== 'encrypted') { massagedConfig[key] = massageConfig(val); } } if (is.nonEmptyArray(massagedConfig.packageRules)) { const newRules = []; const updateTypes = [ 'major', 'minor', 'patch', 'pin', 'digest', 'lockFileMaintenance', 'rollback', ]; for (const rule of massagedConfig.packageRules) { newRules.push(rule); for (const [key, val] of Object.entries(rule)) { if (updateTypes.includes(key)) { const newRule = clone(rule); newRule.updateTypes = rule.updateTypes || []; newRule.updateTypes.push(key); Object.assign(newRule, val); newRules.push(newRule); } } } for (const rule of newRules) { updateTypes.forEach(updateType => { delete rule[updateType]; }); } massagedConfig.packageRules = newRules; } return massagedConfig; }
[ "function", "massageConfig", "(", "config", ")", "{", "if", "(", "!", "allowedStrings", ")", "{", "allowedStrings", "=", "[", "]", ";", "options", ".", "forEach", "(", "option", "=>", "{", "if", "(", "option", ".", "allowString", ")", "{", "allowedStrings", ".", "push", "(", "option", ".", "name", ")", ";", "}", "}", ")", ";", "}", "const", "massagedConfig", "=", "clone", "(", "config", ")", ";", "for", "(", "const", "[", "key", ",", "val", "]", "of", "Object", ".", "entries", "(", "config", ")", ")", "{", "if", "(", "allowedStrings", ".", "includes", "(", "key", ")", "&&", "is", ".", "string", "(", "val", ")", ")", "{", "massagedConfig", "[", "key", "]", "=", "[", "val", "]", ";", "}", "else", "if", "(", "key", "===", "'npmToken'", "&&", "val", "&&", "val", ".", "length", "<", "50", ")", "{", "massagedConfig", ".", "npmrc", "=", "`", "${", "val", "}", "\\n", "`", ";", "delete", "massagedConfig", ".", "npmToken", ";", "}", "else", "if", "(", "is", ".", "array", "(", "val", ")", ")", "{", "massagedConfig", "[", "key", "]", "=", "[", "]", ";", "val", ".", "forEach", "(", "item", "=>", "{", "if", "(", "is", ".", "object", "(", "item", ")", ")", "{", "massagedConfig", "[", "key", "]", ".", "push", "(", "massageConfig", "(", "item", ")", ")", ";", "}", "else", "{", "massagedConfig", "[", "key", "]", ".", "push", "(", "item", ")", ";", "}", "}", ")", ";", "}", "else", "if", "(", "is", ".", "object", "(", "val", ")", "&&", "key", "!==", "'encrypted'", ")", "{", "massagedConfig", "[", "key", "]", "=", "massageConfig", "(", "val", ")", ";", "}", "}", "if", "(", "is", ".", "nonEmptyArray", "(", "massagedConfig", ".", "packageRules", ")", ")", "{", "const", "newRules", "=", "[", "]", ";", "const", "updateTypes", "=", "[", "'major'", ",", "'minor'", ",", "'patch'", ",", "'pin'", ",", "'digest'", ",", "'lockFileMaintenance'", ",", "'rollback'", ",", "]", ";", "for", "(", "const", "rule", "of", "massagedConfig", ".", "packageRules", ")", "{", "newRules", ".", "push", "(", "rule", ")", ";", "for", "(", "const", "[", "key", ",", "val", "]", "of", "Object", ".", "entries", "(", "rule", ")", ")", "{", "if", "(", "updateTypes", ".", "includes", "(", "key", ")", ")", "{", "const", "newRule", "=", "clone", "(", "rule", ")", ";", "newRule", ".", "updateTypes", "=", "rule", ".", "updateTypes", "||", "[", "]", ";", "newRule", ".", "updateTypes", ".", "push", "(", "key", ")", ";", "Object", ".", "assign", "(", "newRule", ",", "val", ")", ";", "newRules", ".", "push", "(", "newRule", ")", ";", "}", "}", "}", "for", "(", "const", "rule", "of", "newRules", ")", "{", "updateTypes", ".", "forEach", "(", "updateType", "=>", "{", "delete", "rule", "[", "updateType", "]", ";", "}", ")", ";", "}", "massagedConfig", ".", "packageRules", "=", "newRules", ";", "}", "return", "massagedConfig", ";", "}" ]
Returns a massaged config
[ "Returns", "a", "massaged", "config" ]
01b5ae2638350525a829a15aef7631ab3c13aae5
https://github.com/renovatebot/renovate/blob/01b5ae2638350525a829a15aef7631ab3c13aae5/lib/config/massage.js#L13-L73
5,623
renovatebot/renovate
lib/versioning/poetry/index.js
poetry2npm
function poetry2npm(input) { const versions = input .split(',') .map(str => str.trim()) .filter(notEmpty); return versions.join(' '); }
javascript
function poetry2npm(input) { const versions = input .split(',') .map(str => str.trim()) .filter(notEmpty); return versions.join(' '); }
[ "function", "poetry2npm", "(", "input", ")", "{", "const", "versions", "=", "input", ".", "split", "(", "','", ")", ".", "map", "(", "str", "=>", "str", ".", "trim", "(", ")", ")", ".", "filter", "(", "notEmpty", ")", ";", "return", "versions", ".", "join", "(", "' '", ")", ";", "}" ]
This function works like cargo2npm, but it doesn't add a '^', because poetry treats versions without operators as exact versions.
[ "This", "function", "works", "like", "cargo2npm", "but", "it", "doesn", "t", "add", "a", "^", "because", "poetry", "treats", "versions", "without", "operators", "as", "exact", "versions", "." ]
01b5ae2638350525a829a15aef7631ab3c13aae5
https://github.com/renovatebot/renovate/blob/01b5ae2638350525a829a15aef7631ab3c13aae5/lib/versioning/poetry/index.js#L12-L18
5,624
renovatebot/renovate
lib/platform/bitbucket/index.js
initRepo
async function initRepo({ repository, endpoint, localDir }) { logger.debug(`initRepo("${repository}")`); const opts = hostRules.find({ platform: 'bitbucket' }, { endpoint }); // istanbul ignore next if (!(opts.username && opts.password)) { throw new Error( `No username/password found for Bitbucket repository ${repository}` ); } hostRules.update({ ...opts, platform: 'bitbucket', default: true }); api.reset(); config = {}; // TODO: get in touch with @rarkins about lifting up the caching into the app layer config.repository = repository; const platformConfig = {}; // Always gitFs const url = GitStorage.getUrl({ gitFs: 'https', auth: `${opts.username}:${opts.password}`, hostname: 'bitbucket.org', repository, }); config.storage = new GitStorage(); await config.storage.initRepo({ ...config, localDir, url, }); try { const info = utils.repoInfoTransformer( (await api.get(`/2.0/repositories/${repository}`)).body ); platformConfig.privateRepo = info.privateRepo; platformConfig.isFork = info.isFork; platformConfig.repoFullName = info.repoFullName; config.owner = info.owner; logger.debug(`${repository} owner = ${config.owner}`); config.defaultBranch = info.mainbranch; config.baseBranch = config.defaultBranch; config.mergeMethod = info.mergeMethod; } catch (err) /* istanbul ignore next */ { if (err.statusCode === 404) { throw new Error('not-found'); } logger.info({ err }, 'Unknown Bitbucket initRepo error'); throw err; } delete config.prList; delete config.fileList; await Promise.all([getPrList(), getFileList()]); return platformConfig; }
javascript
async function initRepo({ repository, endpoint, localDir }) { logger.debug(`initRepo("${repository}")`); const opts = hostRules.find({ platform: 'bitbucket' }, { endpoint }); // istanbul ignore next if (!(opts.username && opts.password)) { throw new Error( `No username/password found for Bitbucket repository ${repository}` ); } hostRules.update({ ...opts, platform: 'bitbucket', default: true }); api.reset(); config = {}; // TODO: get in touch with @rarkins about lifting up the caching into the app layer config.repository = repository; const platformConfig = {}; // Always gitFs const url = GitStorage.getUrl({ gitFs: 'https', auth: `${opts.username}:${opts.password}`, hostname: 'bitbucket.org', repository, }); config.storage = new GitStorage(); await config.storage.initRepo({ ...config, localDir, url, }); try { const info = utils.repoInfoTransformer( (await api.get(`/2.0/repositories/${repository}`)).body ); platformConfig.privateRepo = info.privateRepo; platformConfig.isFork = info.isFork; platformConfig.repoFullName = info.repoFullName; config.owner = info.owner; logger.debug(`${repository} owner = ${config.owner}`); config.defaultBranch = info.mainbranch; config.baseBranch = config.defaultBranch; config.mergeMethod = info.mergeMethod; } catch (err) /* istanbul ignore next */ { if (err.statusCode === 404) { throw new Error('not-found'); } logger.info({ err }, 'Unknown Bitbucket initRepo error'); throw err; } delete config.prList; delete config.fileList; await Promise.all([getPrList(), getFileList()]); return platformConfig; }
[ "async", "function", "initRepo", "(", "{", "repository", ",", "endpoint", ",", "localDir", "}", ")", "{", "logger", ".", "debug", "(", "`", "${", "repository", "}", "`", ")", ";", "const", "opts", "=", "hostRules", ".", "find", "(", "{", "platform", ":", "'bitbucket'", "}", ",", "{", "endpoint", "}", ")", ";", "// istanbul ignore next", "if", "(", "!", "(", "opts", ".", "username", "&&", "opts", ".", "password", ")", ")", "{", "throw", "new", "Error", "(", "`", "${", "repository", "}", "`", ")", ";", "}", "hostRules", ".", "update", "(", "{", "...", "opts", ",", "platform", ":", "'bitbucket'", ",", "default", ":", "true", "}", ")", ";", "api", ".", "reset", "(", ")", ";", "config", "=", "{", "}", ";", "// TODO: get in touch with @rarkins about lifting up the caching into the app layer", "config", ".", "repository", "=", "repository", ";", "const", "platformConfig", "=", "{", "}", ";", "// Always gitFs", "const", "url", "=", "GitStorage", ".", "getUrl", "(", "{", "gitFs", ":", "'https'", ",", "auth", ":", "`", "${", "opts", ".", "username", "}", "${", "opts", ".", "password", "}", "`", ",", "hostname", ":", "'bitbucket.org'", ",", "repository", ",", "}", ")", ";", "config", ".", "storage", "=", "new", "GitStorage", "(", ")", ";", "await", "config", ".", "storage", ".", "initRepo", "(", "{", "...", "config", ",", "localDir", ",", "url", ",", "}", ")", ";", "try", "{", "const", "info", "=", "utils", ".", "repoInfoTransformer", "(", "(", "await", "api", ".", "get", "(", "`", "${", "repository", "}", "`", ")", ")", ".", "body", ")", ";", "platformConfig", ".", "privateRepo", "=", "info", ".", "privateRepo", ";", "platformConfig", ".", "isFork", "=", "info", ".", "isFork", ";", "platformConfig", ".", "repoFullName", "=", "info", ".", "repoFullName", ";", "config", ".", "owner", "=", "info", ".", "owner", ";", "logger", ".", "debug", "(", "`", "${", "repository", "}", "${", "config", ".", "owner", "}", "`", ")", ";", "config", ".", "defaultBranch", "=", "info", ".", "mainbranch", ";", "config", ".", "baseBranch", "=", "config", ".", "defaultBranch", ";", "config", ".", "mergeMethod", "=", "info", ".", "mergeMethod", ";", "}", "catch", "(", "err", ")", "/* istanbul ignore next */", "{", "if", "(", "err", ".", "statusCode", "===", "404", ")", "{", "throw", "new", "Error", "(", "'not-found'", ")", ";", "}", "logger", ".", "info", "(", "{", "err", "}", ",", "'Unknown Bitbucket initRepo error'", ")", ";", "throw", "err", ";", "}", "delete", "config", ".", "prList", ";", "delete", "config", ".", "fileList", ";", "await", "Promise", ".", "all", "(", "[", "getPrList", "(", ")", ",", "getFileList", "(", ")", "]", ")", ";", "return", "platformConfig", ";", "}" ]
Initialize bitbucket by getting base branch and SHA
[ "Initialize", "bitbucket", "by", "getting", "base", "branch", "and", "SHA" ]
01b5ae2638350525a829a15aef7631ab3c13aae5
https://github.com/renovatebot/renovate/blob/01b5ae2638350525a829a15aef7631ab3c13aae5/lib/platform/bitbucket/index.js#L81-L135
5,625
renovatebot/renovate
lib/platform/bitbucket/index.js
getBranchCommit
async function getBranchCommit(branchName) { try { const branch = (await api.get( `/2.0/repositories/${config.repository}/refs/branches/${branchName}` )).body; return branch.target.hash; } catch (err) /* istanbul ignore next */ { logger.debug({ err }, `getBranchCommit('${branchName}') failed'`); return null; } }
javascript
async function getBranchCommit(branchName) { try { const branch = (await api.get( `/2.0/repositories/${config.repository}/refs/branches/${branchName}` )).body; return branch.target.hash; } catch (err) /* istanbul ignore next */ { logger.debug({ err }, `getBranchCommit('${branchName}') failed'`); return null; } }
[ "async", "function", "getBranchCommit", "(", "branchName", ")", "{", "try", "{", "const", "branch", "=", "(", "await", "api", ".", "get", "(", "`", "${", "config", ".", "repository", "}", "${", "branchName", "}", "`", ")", ")", ".", "body", ";", "return", "branch", ".", "target", ".", "hash", ";", "}", "catch", "(", "err", ")", "/* istanbul ignore next */", "{", "logger", ".", "debug", "(", "{", "err", "}", ",", "`", "${", "branchName", "}", "`", ")", ";", "return", "null", ";", "}", "}" ]
Return the commit SHA for a branch
[ "Return", "the", "commit", "SHA", "for", "a", "branch" ]
01b5ae2638350525a829a15aef7631ab3c13aae5
https://github.com/renovatebot/renovate/blob/01b5ae2638350525a829a15aef7631ab3c13aae5/lib/platform/bitbucket/index.js#L584-L594
5,626
renovatebot/renovate
lib/manager/homebrew/util.js
removeMultiLineComments
function removeMultiLineComments(content) { const beginRegExp = /(^|\n)=begin\s/; const endRegExp = /(^|\n)=end\s/; let newContent = content; let i = newContent.search(beginRegExp); let j = newContent.search(endRegExp); while (i !== -1 && j !== -1) { if (newContent[i] === '\n') { i += 1; } if (newContent[j] === '\n') { j += 1; } j += '=end'.length; newContent = newContent.substring(0, i) + newContent.substring(j); i = newContent.search(beginRegExp); j = newContent.search(endRegExp); } return newContent; }
javascript
function removeMultiLineComments(content) { const beginRegExp = /(^|\n)=begin\s/; const endRegExp = /(^|\n)=end\s/; let newContent = content; let i = newContent.search(beginRegExp); let j = newContent.search(endRegExp); while (i !== -1 && j !== -1) { if (newContent[i] === '\n') { i += 1; } if (newContent[j] === '\n') { j += 1; } j += '=end'.length; newContent = newContent.substring(0, i) + newContent.substring(j); i = newContent.search(beginRegExp); j = newContent.search(endRegExp); } return newContent; }
[ "function", "removeMultiLineComments", "(", "content", ")", "{", "const", "beginRegExp", "=", "/", "(^|\\n)=begin\\s", "/", ";", "const", "endRegExp", "=", "/", "(^|\\n)=end\\s", "/", ";", "let", "newContent", "=", "content", ";", "let", "i", "=", "newContent", ".", "search", "(", "beginRegExp", ")", ";", "let", "j", "=", "newContent", ".", "search", "(", "endRegExp", ")", ";", "while", "(", "i", "!==", "-", "1", "&&", "j", "!==", "-", "1", ")", "{", "if", "(", "newContent", "[", "i", "]", "===", "'\\n'", ")", "{", "i", "+=", "1", ";", "}", "if", "(", "newContent", "[", "j", "]", "===", "'\\n'", ")", "{", "j", "+=", "1", ";", "}", "j", "+=", "'=end'", ".", "length", ";", "newContent", "=", "newContent", ".", "substring", "(", "0", ",", "i", ")", "+", "newContent", ".", "substring", "(", "j", ")", ";", "i", "=", "newContent", ".", "search", "(", "beginRegExp", ")", ";", "j", "=", "newContent", ".", "search", "(", "endRegExp", ")", ";", "}", "return", "newContent", ";", "}" ]
Remove multi-line comments enclosed between =begin and =end
[ "Remove", "multi", "-", "line", "comments", "enclosed", "between", "=", "begin", "and", "=", "end" ]
01b5ae2638350525a829a15aef7631ab3c13aae5
https://github.com/renovatebot/renovate/blob/01b5ae2638350525a829a15aef7631ab3c13aae5/lib/manager/homebrew/util.js#L50-L69
5,627
renovatebot/renovate
lib/platform/azure/azure-helper.js
getFile
async function getFile(repoId, repository, filePath, branchName) { logger.trace(`getFile(filePath=${filePath}, branchName=${branchName})`); const azureApiGit = await azureApi.gitApi(); const item = await azureApiGit.getItemText( repoId, filePath, null, null, 0, // because we look for 1 file false, false, true, { versionType: 0, // branch versionOptions: 0, version: getBranchNameWithoutRefsheadsPrefix(branchName), } ); if (item && item.readable) { const fileContent = await streamToString(item); try { const jTmp = JSON.parse(fileContent); if (jTmp.typeKey === 'GitItemNotFoundException') { // file not found return null; } if (jTmp.typeKey === 'GitUnresolvableToCommitException') { // branch not found return null; } } catch (error) { // it 's not a JSON, so I send the content directly with the line under } return fileContent; } return null; // no file found }
javascript
async function getFile(repoId, repository, filePath, branchName) { logger.trace(`getFile(filePath=${filePath}, branchName=${branchName})`); const azureApiGit = await azureApi.gitApi(); const item = await azureApiGit.getItemText( repoId, filePath, null, null, 0, // because we look for 1 file false, false, true, { versionType: 0, // branch versionOptions: 0, version: getBranchNameWithoutRefsheadsPrefix(branchName), } ); if (item && item.readable) { const fileContent = await streamToString(item); try { const jTmp = JSON.parse(fileContent); if (jTmp.typeKey === 'GitItemNotFoundException') { // file not found return null; } if (jTmp.typeKey === 'GitUnresolvableToCommitException') { // branch not found return null; } } catch (error) { // it 's not a JSON, so I send the content directly with the line under } return fileContent; } return null; // no file found }
[ "async", "function", "getFile", "(", "repoId", ",", "repository", ",", "filePath", ",", "branchName", ")", "{", "logger", ".", "trace", "(", "`", "${", "filePath", "}", "${", "branchName", "}", "`", ")", ";", "const", "azureApiGit", "=", "await", "azureApi", ".", "gitApi", "(", ")", ";", "const", "item", "=", "await", "azureApiGit", ".", "getItemText", "(", "repoId", ",", "filePath", ",", "null", ",", "null", ",", "0", ",", "// because we look for 1 file", "false", ",", "false", ",", "true", ",", "{", "versionType", ":", "0", ",", "// branch", "versionOptions", ":", "0", ",", "version", ":", "getBranchNameWithoutRefsheadsPrefix", "(", "branchName", ")", ",", "}", ")", ";", "if", "(", "item", "&&", "item", ".", "readable", ")", "{", "const", "fileContent", "=", "await", "streamToString", "(", "item", ")", ";", "try", "{", "const", "jTmp", "=", "JSON", ".", "parse", "(", "fileContent", ")", ";", "if", "(", "jTmp", ".", "typeKey", "===", "'GitItemNotFoundException'", ")", "{", "// file not found", "return", "null", ";", "}", "if", "(", "jTmp", ".", "typeKey", "===", "'GitUnresolvableToCommitException'", ")", "{", "// branch not found", "return", "null", ";", "}", "}", "catch", "(", "error", ")", "{", "// it 's not a JSON, so I send the content directly with the line under", "}", "return", "fileContent", ";", "}", "return", "null", ";", "// no file found", "}" ]
if no branchName, look globaly @param {string} repoId @param {string} repository @param {string} filePath @param {string} branchName
[ "if", "no", "branchName", "look", "globaly" ]
01b5ae2638350525a829a15aef7631ab3c13aae5
https://github.com/renovatebot/renovate/blob/01b5ae2638350525a829a15aef7631ab3c13aae5/lib/platform/azure/azure-helper.js#L147-L184
5,628
renovatebot/renovate
lib/versioning/loose/generic.js
maxSatisfyingVersion
function maxSatisfyingVersion(versions, range) { return versions.find(v => equals(v, range)) || null; }
javascript
function maxSatisfyingVersion(versions, range) { return versions.find(v => equals(v, range)) || null; }
[ "function", "maxSatisfyingVersion", "(", "versions", ",", "range", ")", "{", "return", "versions", ".", "find", "(", "v", "=>", "equals", "(", "v", ",", "range", ")", ")", "||", "null", ";", "}" ]
we don't not have ranges, so versions has to be equal
[ "we", "don", "t", "not", "have", "ranges", "so", "versions", "has", "to", "be", "equal" ]
01b5ae2638350525a829a15aef7631ab3c13aae5
https://github.com/renovatebot/renovate/blob/01b5ae2638350525a829a15aef7631ab3c13aae5/lib/versioning/loose/generic.js#L70-L72
5,629
maxwellito/vivus
src/pathformer.js
Pathformer
function Pathformer(element) { // Test params if (typeof element === 'undefined') { throw new Error('Pathformer [constructor]: "element" parameter is required'); } // Set the element if (element.constructor === String) { element = document.getElementById(element); if (!element) { throw new Error('Pathformer [constructor]: "element" parameter is not related to an existing ID'); } } if (element instanceof window.SVGElement || element instanceof window.SVGGElement || /^svg$/i.test(element.nodeName)) { this.el = element; } else { throw new Error('Pathformer [constructor]: "element" parameter must be a string or a SVGelement'); } // Start this.scan(element); }
javascript
function Pathformer(element) { // Test params if (typeof element === 'undefined') { throw new Error('Pathformer [constructor]: "element" parameter is required'); } // Set the element if (element.constructor === String) { element = document.getElementById(element); if (!element) { throw new Error('Pathformer [constructor]: "element" parameter is not related to an existing ID'); } } if (element instanceof window.SVGElement || element instanceof window.SVGGElement || /^svg$/i.test(element.nodeName)) { this.el = element; } else { throw new Error('Pathformer [constructor]: "element" parameter must be a string or a SVGelement'); } // Start this.scan(element); }
[ "function", "Pathformer", "(", "element", ")", "{", "// Test params", "if", "(", "typeof", "element", "===", "'undefined'", ")", "{", "throw", "new", "Error", "(", "'Pathformer [constructor]: \"element\" parameter is required'", ")", ";", "}", "// Set the element", "if", "(", "element", ".", "constructor", "===", "String", ")", "{", "element", "=", "document", ".", "getElementById", "(", "element", ")", ";", "if", "(", "!", "element", ")", "{", "throw", "new", "Error", "(", "'Pathformer [constructor]: \"element\" parameter is not related to an existing ID'", ")", ";", "}", "}", "if", "(", "element", "instanceof", "window", ".", "SVGElement", "||", "element", "instanceof", "window", ".", "SVGGElement", "||", "/", "^svg$", "/", "i", ".", "test", "(", "element", ".", "nodeName", ")", ")", "{", "this", ".", "el", "=", "element", ";", "}", "else", "{", "throw", "new", "Error", "(", "'Pathformer [constructor]: \"element\" parameter must be a string or a SVGelement'", ")", ";", "}", "// Start", "this", ".", "scan", "(", "element", ")", ";", "}" ]
Pathformer Beta version Take any SVG version 1.1 and transform child elements to 'path' elements This code is purely forked from https://github.com/Waest/SVGPathConverter Class constructor @param {DOM|String} element Dom element of the SVG or id of it
[ "Pathformer", "Beta", "version" ]
c608973a8b576579bcb432558b531998f319592b
https://github.com/maxwellito/vivus/blob/c608973a8b576579bcb432558b531998f319592b/src/pathformer.js#L19-L42
5,630
maxwellito/vivus
src/vivus.js
Vivus
function Vivus(element, options, callback) { setupEnv(); // Setup this.isReady = false; this.setElement(element, options); this.setOptions(options); this.setCallback(callback); if (this.isReady) { this.init(); } }
javascript
function Vivus(element, options, callback) { setupEnv(); // Setup this.isReady = false; this.setElement(element, options); this.setOptions(options); this.setCallback(callback); if (this.isReady) { this.init(); } }
[ "function", "Vivus", "(", "element", ",", "options", ",", "callback", ")", "{", "setupEnv", "(", ")", ";", "// Setup", "this", ".", "isReady", "=", "false", ";", "this", ".", "setElement", "(", "element", ",", "options", ")", ";", "this", ".", "setOptions", "(", "options", ")", ";", "this", ".", "setCallback", "(", "callback", ")", ";", "if", "(", "this", ".", "isReady", ")", "{", "this", ".", "init", "(", ")", ";", "}", "}" ]
Vivus Beta version Take any SVG and make the animation to give give the impression of live drawing This in more than just inspired from codrops At that point, it's a pure fork. Class constructor option structure type: 'delayed'|'sync'|'oneByOne'|'script' (to know if the items must be drawn synchronously or not, default: delayed) duration: <int> (in frames) start: 'inViewport'|'manual'|'autostart' (start automatically the animation, default: inViewport) delay: <int> (delay between the drawing of first and last path) dashGap <integer> whitespace extra margin between dashes pathTimingFunction <function> timing animation function for each path element of the SVG animTimingFunction <function> timing animation function for the complete SVG forceRender <boolean> force the browser to re-render all updated path items selfDestroy <boolean> removes all extra styling on the SVG, and leaves it as original The attribute 'type' is by default on 'delayed'. - 'delayed' all paths are draw at the same time but with a little delay between them before start - 'sync' all path are start and finish at the same time - 'oneByOne' only one path is draw at the time the end of the first one will trigger the draw of the next one All these values can be overwritten individually for each path item in the SVG The value of frames will always take the advantage of the duration value. If you fail somewhere, an error will be thrown. Good luck. @constructor @this {Vivus} @param {DOM|String} element Dom element of the SVG or id of it @param {Object} options Options about the animation @param {Function} callback Callback for the end of the animation
[ "Vivus", "Beta", "version" ]
c608973a8b576579bcb432558b531998f319592b
https://github.com/maxwellito/vivus/blob/c608973a8b576579bcb432558b531998f319592b/src/vivus.js#L53-L65
5,631
dwyl/learn-to-send-email-via-google-script-html-no-server
google-apps-script.js
record_data
function record_data(e) { var lock = LockService.getDocumentLock(); lock.waitLock(30000); // hold off up to 30 sec to avoid concurrent writing try { Logger.log(JSON.stringify(e)); // log the POST data in case we need to debug it // select the 'responses' sheet by default var doc = SpreadsheetApp.getActiveSpreadsheet(); var sheetName = e.parameters.formGoogleSheetName || "responses"; var sheet = doc.getSheetByName(sheetName); var oldHeader = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0]; var newHeader = oldHeader.slice(); var fieldsFromForm = getDataColumns(e.parameters); var row = [new Date()]; // first element in the row should always be a timestamp // loop through the header columns for (var i = 1; i < oldHeader.length; i++) { // start at 1 to avoid Timestamp column var field = oldHeader[i]; var output = getFieldFromData(field, e.parameters); row.push(output); // mark as stored by removing from form fields var formIndex = fieldsFromForm.indexOf(field); if (formIndex > -1) { fieldsFromForm.splice(formIndex, 1); } } // set any new fields in our form for (var i = 0; i < fieldsFromForm.length; i++) { var field = fieldsFromForm[i]; var output = getFieldFromData(field, e.parameters); row.push(output); newHeader.push(field); } // more efficient to set values as [][] array than individually var nextRow = sheet.getLastRow() + 1; // get next row sheet.getRange(nextRow, 1, 1, row.length).setValues([row]); // update header row with any new data if (newHeader.length > oldHeader.length) { sheet.getRange(1, 1, 1, newHeader.length).setValues([newHeader]); } } catch(error) { Logger.log(error); } finally { lock.releaseLock(); return; } }
javascript
function record_data(e) { var lock = LockService.getDocumentLock(); lock.waitLock(30000); // hold off up to 30 sec to avoid concurrent writing try { Logger.log(JSON.stringify(e)); // log the POST data in case we need to debug it // select the 'responses' sheet by default var doc = SpreadsheetApp.getActiveSpreadsheet(); var sheetName = e.parameters.formGoogleSheetName || "responses"; var sheet = doc.getSheetByName(sheetName); var oldHeader = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0]; var newHeader = oldHeader.slice(); var fieldsFromForm = getDataColumns(e.parameters); var row = [new Date()]; // first element in the row should always be a timestamp // loop through the header columns for (var i = 1; i < oldHeader.length; i++) { // start at 1 to avoid Timestamp column var field = oldHeader[i]; var output = getFieldFromData(field, e.parameters); row.push(output); // mark as stored by removing from form fields var formIndex = fieldsFromForm.indexOf(field); if (formIndex > -1) { fieldsFromForm.splice(formIndex, 1); } } // set any new fields in our form for (var i = 0; i < fieldsFromForm.length; i++) { var field = fieldsFromForm[i]; var output = getFieldFromData(field, e.parameters); row.push(output); newHeader.push(field); } // more efficient to set values as [][] array than individually var nextRow = sheet.getLastRow() + 1; // get next row sheet.getRange(nextRow, 1, 1, row.length).setValues([row]); // update header row with any new data if (newHeader.length > oldHeader.length) { sheet.getRange(1, 1, 1, newHeader.length).setValues([newHeader]); } } catch(error) { Logger.log(error); } finally { lock.releaseLock(); return; } }
[ "function", "record_data", "(", "e", ")", "{", "var", "lock", "=", "LockService", ".", "getDocumentLock", "(", ")", ";", "lock", ".", "waitLock", "(", "30000", ")", ";", "// hold off up to 30 sec to avoid concurrent writing", "try", "{", "Logger", ".", "log", "(", "JSON", ".", "stringify", "(", "e", ")", ")", ";", "// log the POST data in case we need to debug it", "// select the 'responses' sheet by default", "var", "doc", "=", "SpreadsheetApp", ".", "getActiveSpreadsheet", "(", ")", ";", "var", "sheetName", "=", "e", ".", "parameters", ".", "formGoogleSheetName", "||", "\"responses\"", ";", "var", "sheet", "=", "doc", ".", "getSheetByName", "(", "sheetName", ")", ";", "var", "oldHeader", "=", "sheet", ".", "getRange", "(", "1", ",", "1", ",", "1", ",", "sheet", ".", "getLastColumn", "(", ")", ")", ".", "getValues", "(", ")", "[", "0", "]", ";", "var", "newHeader", "=", "oldHeader", ".", "slice", "(", ")", ";", "var", "fieldsFromForm", "=", "getDataColumns", "(", "e", ".", "parameters", ")", ";", "var", "row", "=", "[", "new", "Date", "(", ")", "]", ";", "// first element in the row should always be a timestamp", "// loop through the header columns", "for", "(", "var", "i", "=", "1", ";", "i", "<", "oldHeader", ".", "length", ";", "i", "++", ")", "{", "// start at 1 to avoid Timestamp column", "var", "field", "=", "oldHeader", "[", "i", "]", ";", "var", "output", "=", "getFieldFromData", "(", "field", ",", "e", ".", "parameters", ")", ";", "row", ".", "push", "(", "output", ")", ";", "// mark as stored by removing from form fields", "var", "formIndex", "=", "fieldsFromForm", ".", "indexOf", "(", "field", ")", ";", "if", "(", "formIndex", ">", "-", "1", ")", "{", "fieldsFromForm", ".", "splice", "(", "formIndex", ",", "1", ")", ";", "}", "}", "// set any new fields in our form", "for", "(", "var", "i", "=", "0", ";", "i", "<", "fieldsFromForm", ".", "length", ";", "i", "++", ")", "{", "var", "field", "=", "fieldsFromForm", "[", "i", "]", ";", "var", "output", "=", "getFieldFromData", "(", "field", ",", "e", ".", "parameters", ")", ";", "row", ".", "push", "(", "output", ")", ";", "newHeader", ".", "push", "(", "field", ")", ";", "}", "// more efficient to set values as [][] array than individually", "var", "nextRow", "=", "sheet", ".", "getLastRow", "(", ")", "+", "1", ";", "// get next row", "sheet", ".", "getRange", "(", "nextRow", ",", "1", ",", "1", ",", "row", ".", "length", ")", ".", "setValues", "(", "[", "row", "]", ")", ";", "// update header row with any new data", "if", "(", "newHeader", ".", "length", ">", "oldHeader", ".", "length", ")", "{", "sheet", ".", "getRange", "(", "1", ",", "1", ",", "1", ",", "newHeader", ".", "length", ")", ".", "setValues", "(", "[", "newHeader", "]", ")", ";", "}", "}", "catch", "(", "error", ")", "{", "Logger", ".", "log", "(", "error", ")", ";", "}", "finally", "{", "lock", ".", "releaseLock", "(", ")", ";", "return", ";", "}", "}" ]
record_data inserts the data received from the html form submission e is the data received from the POST
[ "record_data", "inserts", "the", "data", "received", "from", "the", "html", "form", "submission", "e", "is", "the", "data", "received", "from", "the", "POST" ]
7009d700b868a1872f186e758266ce79680e016c
https://github.com/dwyl/learn-to-send-email-via-google-script-html-no-server/blob/7009d700b868a1872f186e758266ce79680e016c/google-apps-script.js#L86-L141
5,632
dwyl/learn-to-send-email-via-google-script-html-no-server
form-submission-handler.js
getFormData
function getFormData(form) { var elements = form.elements; var fields = Object.keys(elements).filter(function(k) { return (elements[k].name !== "honeypot"); }).map(function(k) { if(elements[k].name !== undefined) { return elements[k].name; // special case for Edge's html collection }else if(elements[k].length > 0){ return elements[k].item(0).name; } }).filter(function(item, pos, self) { return self.indexOf(item) == pos && item; }); var formData = {}; fields.forEach(function(name){ var element = elements[name]; // singular form elements just have one value formData[name] = element.value; // when our element has multiple items, get their values if (element.length) { var data = []; for (var i = 0; i < element.length; i++) { var item = element.item(i); if (item.checked || item.selected) { data.push(item.value); } } formData[name] = data.join(', '); } }); // add form-specific values into the data formData.formDataNameOrder = JSON.stringify(fields); formData.formGoogleSheetName = form.dataset.sheet || "responses"; // default sheet name formData.formGoogleSendEmail = form.dataset.email || ""; // no email by default console.log(formData); return formData; }
javascript
function getFormData(form) { var elements = form.elements; var fields = Object.keys(elements).filter(function(k) { return (elements[k].name !== "honeypot"); }).map(function(k) { if(elements[k].name !== undefined) { return elements[k].name; // special case for Edge's html collection }else if(elements[k].length > 0){ return elements[k].item(0).name; } }).filter(function(item, pos, self) { return self.indexOf(item) == pos && item; }); var formData = {}; fields.forEach(function(name){ var element = elements[name]; // singular form elements just have one value formData[name] = element.value; // when our element has multiple items, get their values if (element.length) { var data = []; for (var i = 0; i < element.length; i++) { var item = element.item(i); if (item.checked || item.selected) { data.push(item.value); } } formData[name] = data.join(', '); } }); // add form-specific values into the data formData.formDataNameOrder = JSON.stringify(fields); formData.formGoogleSheetName = form.dataset.sheet || "responses"; // default sheet name formData.formGoogleSendEmail = form.dataset.email || ""; // no email by default console.log(formData); return formData; }
[ "function", "getFormData", "(", "form", ")", "{", "var", "elements", "=", "form", ".", "elements", ";", "var", "fields", "=", "Object", ".", "keys", "(", "elements", ")", ".", "filter", "(", "function", "(", "k", ")", "{", "return", "(", "elements", "[", "k", "]", ".", "name", "!==", "\"honeypot\"", ")", ";", "}", ")", ".", "map", "(", "function", "(", "k", ")", "{", "if", "(", "elements", "[", "k", "]", ".", "name", "!==", "undefined", ")", "{", "return", "elements", "[", "k", "]", ".", "name", ";", "// special case for Edge's html collection", "}", "else", "if", "(", "elements", "[", "k", "]", ".", "length", ">", "0", ")", "{", "return", "elements", "[", "k", "]", ".", "item", "(", "0", ")", ".", "name", ";", "}", "}", ")", ".", "filter", "(", "function", "(", "item", ",", "pos", ",", "self", ")", "{", "return", "self", ".", "indexOf", "(", "item", ")", "==", "pos", "&&", "item", ";", "}", ")", ";", "var", "formData", "=", "{", "}", ";", "fields", ".", "forEach", "(", "function", "(", "name", ")", "{", "var", "element", "=", "elements", "[", "name", "]", ";", "// singular form elements just have one value", "formData", "[", "name", "]", "=", "element", ".", "value", ";", "// when our element has multiple items, get their values", "if", "(", "element", ".", "length", ")", "{", "var", "data", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "element", ".", "length", ";", "i", "++", ")", "{", "var", "item", "=", "element", ".", "item", "(", "i", ")", ";", "if", "(", "item", ".", "checked", "||", "item", ".", "selected", ")", "{", "data", ".", "push", "(", "item", ".", "value", ")", ";", "}", "}", "formData", "[", "name", "]", "=", "data", ".", "join", "(", "', '", ")", ";", "}", "}", ")", ";", "// add form-specific values into the data", "formData", ".", "formDataNameOrder", "=", "JSON", ".", "stringify", "(", "fields", ")", ";", "formData", ".", "formGoogleSheetName", "=", "form", ".", "dataset", ".", "sheet", "||", "\"responses\"", ";", "// default sheet name", "formData", ".", "formGoogleSendEmail", "=", "form", ".", "dataset", ".", "email", "||", "\"\"", ";", "// no email by default", "console", ".", "log", "(", "formData", ")", ";", "return", "formData", ";", "}" ]
get all data in form and return object
[ "get", "all", "data", "in", "form", "and", "return", "object" ]
7009d700b868a1872f186e758266ce79680e016c
https://github.com/dwyl/learn-to-send-email-via-google-script-html-no-server/blob/7009d700b868a1872f186e758266ce79680e016c/form-submission-handler.js#L17-L60
5,633
browserslist/browserslist
index.js
resolve
function resolve (queries, context) { if (Array.isArray(queries)) { queries = flatten(queries.map(parse)) } else { queries = parse(queries) } return queries.reduce(function (result, query, index) { var selection = query.queryString var isExclude = selection.indexOf('not ') === 0 if (isExclude) { if (index === 0) { throw new BrowserslistError( 'Write any browsers query (for instance, `defaults`) ' + 'before `' + selection + '`') } selection = selection.slice(4) } for (var i = 0; i < QUERIES.length; i++) { var type = QUERIES[i] var match = selection.match(type.regexp) if (match) { var args = [context].concat(match.slice(1)) var array = type.select.apply(browserslist, args).map(function (j) { var parts = j.split(' ') if (parts[1] === '0') { return parts[0] + ' ' + byName(parts[0]).versions[0] } else { return j } }) switch (query.type) { case QUERY_AND: if (isExclude) { return result.filter(function (j) { // remove result items that are in array // (the relative complement of array in result) return array.indexOf(j) === -1 }) } else { return result.filter(function (j) { // remove result items not in array // (intersect of result and array) return array.indexOf(j) !== -1 }) } case QUERY_OR: default: if (isExclude) { var filter = { } array.forEach(function (j) { filter[j] = true }) return result.filter(function (j) { return !filter[j] }) } // union of result and array return result.concat(array) } } } throw unknownQuery(selection) }, []) }
javascript
function resolve (queries, context) { if (Array.isArray(queries)) { queries = flatten(queries.map(parse)) } else { queries = parse(queries) } return queries.reduce(function (result, query, index) { var selection = query.queryString var isExclude = selection.indexOf('not ') === 0 if (isExclude) { if (index === 0) { throw new BrowserslistError( 'Write any browsers query (for instance, `defaults`) ' + 'before `' + selection + '`') } selection = selection.slice(4) } for (var i = 0; i < QUERIES.length; i++) { var type = QUERIES[i] var match = selection.match(type.regexp) if (match) { var args = [context].concat(match.slice(1)) var array = type.select.apply(browserslist, args).map(function (j) { var parts = j.split(' ') if (parts[1] === '0') { return parts[0] + ' ' + byName(parts[0]).versions[0] } else { return j } }) switch (query.type) { case QUERY_AND: if (isExclude) { return result.filter(function (j) { // remove result items that are in array // (the relative complement of array in result) return array.indexOf(j) === -1 }) } else { return result.filter(function (j) { // remove result items not in array // (intersect of result and array) return array.indexOf(j) !== -1 }) } case QUERY_OR: default: if (isExclude) { var filter = { } array.forEach(function (j) { filter[j] = true }) return result.filter(function (j) { return !filter[j] }) } // union of result and array return result.concat(array) } } } throw unknownQuery(selection) }, []) }
[ "function", "resolve", "(", "queries", ",", "context", ")", "{", "if", "(", "Array", ".", "isArray", "(", "queries", ")", ")", "{", "queries", "=", "flatten", "(", "queries", ".", "map", "(", "parse", ")", ")", "}", "else", "{", "queries", "=", "parse", "(", "queries", ")", "}", "return", "queries", ".", "reduce", "(", "function", "(", "result", ",", "query", ",", "index", ")", "{", "var", "selection", "=", "query", ".", "queryString", "var", "isExclude", "=", "selection", ".", "indexOf", "(", "'not '", ")", "===", "0", "if", "(", "isExclude", ")", "{", "if", "(", "index", "===", "0", ")", "{", "throw", "new", "BrowserslistError", "(", "'Write any browsers query (for instance, `defaults`) '", "+", "'before `'", "+", "selection", "+", "'`'", ")", "}", "selection", "=", "selection", ".", "slice", "(", "4", ")", "}", "for", "(", "var", "i", "=", "0", ";", "i", "<", "QUERIES", ".", "length", ";", "i", "++", ")", "{", "var", "type", "=", "QUERIES", "[", "i", "]", "var", "match", "=", "selection", ".", "match", "(", "type", ".", "regexp", ")", "if", "(", "match", ")", "{", "var", "args", "=", "[", "context", "]", ".", "concat", "(", "match", ".", "slice", "(", "1", ")", ")", "var", "array", "=", "type", ".", "select", ".", "apply", "(", "browserslist", ",", "args", ")", ".", "map", "(", "function", "(", "j", ")", "{", "var", "parts", "=", "j", ".", "split", "(", "' '", ")", "if", "(", "parts", "[", "1", "]", "===", "'0'", ")", "{", "return", "parts", "[", "0", "]", "+", "' '", "+", "byName", "(", "parts", "[", "0", "]", ")", ".", "versions", "[", "0", "]", "}", "else", "{", "return", "j", "}", "}", ")", "switch", "(", "query", ".", "type", ")", "{", "case", "QUERY_AND", ":", "if", "(", "isExclude", ")", "{", "return", "result", ".", "filter", "(", "function", "(", "j", ")", "{", "// remove result items that are in array", "// (the relative complement of array in result)", "return", "array", ".", "indexOf", "(", "j", ")", "===", "-", "1", "}", ")", "}", "else", "{", "return", "result", ".", "filter", "(", "function", "(", "j", ")", "{", "// remove result items not in array", "// (intersect of result and array)", "return", "array", ".", "indexOf", "(", "j", ")", "!==", "-", "1", "}", ")", "}", "case", "QUERY_OR", ":", "default", ":", "if", "(", "isExclude", ")", "{", "var", "filter", "=", "{", "}", "array", ".", "forEach", "(", "function", "(", "j", ")", "{", "filter", "[", "j", "]", "=", "true", "}", ")", "return", "result", ".", "filter", "(", "function", "(", "j", ")", "{", "return", "!", "filter", "[", "j", "]", "}", ")", "}", "// union of result and array", "return", "result", ".", "concat", "(", "array", ")", "}", "}", "}", "throw", "unknownQuery", "(", "selection", ")", "}", ",", "[", "]", ")", "}" ]
Resolves queries into a browser list. @param {string|string[]} queries Queries to combine. Either an array of queries or a long string of queries. @param {object} [context] Optional arguments to the select function in `queries`. @returns {string[]} A list of browsers
[ "Resolves", "queries", "into", "a", "browser", "list", "." ]
8191c2d3c113cad16392734d6e3bf3c4e61cdfb0
https://github.com/browserslist/browserslist/blob/8191c2d3c113cad16392734d6e3bf3c4e61cdfb0/index.js#L190-L258
5,634
browserslist/browserslist
index.js
browserslist
function browserslist (queries, opts) { if (typeof opts === 'undefined') opts = { } if (typeof opts.path === 'undefined') { opts.path = path.resolve ? path.resolve('.') : '.' } if (typeof queries === 'undefined' || queries === null) { var config = browserslist.loadConfig(opts) if (config) { queries = config } else { queries = browserslist.defaults } } if (!(typeof queries === 'string' || Array.isArray(queries))) { throw new BrowserslistError( 'Browser queries must be an array or string. Got ' + typeof queries + '.') } var context = { ignoreUnknownVersions: opts.ignoreUnknownVersions, dangerousExtend: opts.dangerousExtend } env.oldDataWarning(browserslist.data) var stats = env.getStat(opts, browserslist.data) if (stats) { context.customUsage = { } for (var browser in stats) { fillUsage(context.customUsage, browser, stats[browser]) } } var result = resolve(queries, context).sort(function (name1, name2) { name1 = name1.split(' ') name2 = name2.split(' ') if (name1[0] === name2[0]) { if (FLOAT_RANGE.test(name1[1]) && FLOAT_RANGE.test(name2[1])) { return parseFloat(name2[1]) - parseFloat(name1[1]) } else { return compare(name2[1], name1[1]) } } else { return compare(name1[0], name2[0]) } }) return uniq(result) }
javascript
function browserslist (queries, opts) { if (typeof opts === 'undefined') opts = { } if (typeof opts.path === 'undefined') { opts.path = path.resolve ? path.resolve('.') : '.' } if (typeof queries === 'undefined' || queries === null) { var config = browserslist.loadConfig(opts) if (config) { queries = config } else { queries = browserslist.defaults } } if (!(typeof queries === 'string' || Array.isArray(queries))) { throw new BrowserslistError( 'Browser queries must be an array or string. Got ' + typeof queries + '.') } var context = { ignoreUnknownVersions: opts.ignoreUnknownVersions, dangerousExtend: opts.dangerousExtend } env.oldDataWarning(browserslist.data) var stats = env.getStat(opts, browserslist.data) if (stats) { context.customUsage = { } for (var browser in stats) { fillUsage(context.customUsage, browser, stats[browser]) } } var result = resolve(queries, context).sort(function (name1, name2) { name1 = name1.split(' ') name2 = name2.split(' ') if (name1[0] === name2[0]) { if (FLOAT_RANGE.test(name1[1]) && FLOAT_RANGE.test(name2[1])) { return parseFloat(name2[1]) - parseFloat(name1[1]) } else { return compare(name2[1], name1[1]) } } else { return compare(name1[0], name2[0]) } }) return uniq(result) }
[ "function", "browserslist", "(", "queries", ",", "opts", ")", "{", "if", "(", "typeof", "opts", "===", "'undefined'", ")", "opts", "=", "{", "}", "if", "(", "typeof", "opts", ".", "path", "===", "'undefined'", ")", "{", "opts", ".", "path", "=", "path", ".", "resolve", "?", "path", ".", "resolve", "(", "'.'", ")", ":", "'.'", "}", "if", "(", "typeof", "queries", "===", "'undefined'", "||", "queries", "===", "null", ")", "{", "var", "config", "=", "browserslist", ".", "loadConfig", "(", "opts", ")", "if", "(", "config", ")", "{", "queries", "=", "config", "}", "else", "{", "queries", "=", "browserslist", ".", "defaults", "}", "}", "if", "(", "!", "(", "typeof", "queries", "===", "'string'", "||", "Array", ".", "isArray", "(", "queries", ")", ")", ")", "{", "throw", "new", "BrowserslistError", "(", "'Browser queries must be an array or string. Got '", "+", "typeof", "queries", "+", "'.'", ")", "}", "var", "context", "=", "{", "ignoreUnknownVersions", ":", "opts", ".", "ignoreUnknownVersions", ",", "dangerousExtend", ":", "opts", ".", "dangerousExtend", "}", "env", ".", "oldDataWarning", "(", "browserslist", ".", "data", ")", "var", "stats", "=", "env", ".", "getStat", "(", "opts", ",", "browserslist", ".", "data", ")", "if", "(", "stats", ")", "{", "context", ".", "customUsage", "=", "{", "}", "for", "(", "var", "browser", "in", "stats", ")", "{", "fillUsage", "(", "context", ".", "customUsage", ",", "browser", ",", "stats", "[", "browser", "]", ")", "}", "}", "var", "result", "=", "resolve", "(", "queries", ",", "context", ")", ".", "sort", "(", "function", "(", "name1", ",", "name2", ")", "{", "name1", "=", "name1", ".", "split", "(", "' '", ")", "name2", "=", "name2", ".", "split", "(", "' '", ")", "if", "(", "name1", "[", "0", "]", "===", "name2", "[", "0", "]", ")", "{", "if", "(", "FLOAT_RANGE", ".", "test", "(", "name1", "[", "1", "]", ")", "&&", "FLOAT_RANGE", ".", "test", "(", "name2", "[", "1", "]", ")", ")", "{", "return", "parseFloat", "(", "name2", "[", "1", "]", ")", "-", "parseFloat", "(", "name1", "[", "1", "]", ")", "}", "else", "{", "return", "compare", "(", "name2", "[", "1", "]", ",", "name1", "[", "1", "]", ")", "}", "}", "else", "{", "return", "compare", "(", "name1", "[", "0", "]", ",", "name2", "[", "0", "]", ")", "}", "}", ")", "return", "uniq", "(", "result", ")", "}" ]
Return array of browsers by selection queries. @param {(string|string[])} [queries=browserslist.defaults] Browser queries. @param {object} [opts] Options. @param {string} [opts.path="."] Path to processed file. It will be used to find config files. @param {string} [opts.env="production"] Processing environment. It will be used to take right queries from config file. @param {string} [opts.config] Path to config file with queries. @param {object} [opts.stats] Custom browser usage statistics for "> 1% in my stats" query. @param {boolean} [opts.ignoreUnknownVersions=false] Do not throw on unknown version in direct query. @param {boolean} [opts.dangerousExtend] Disable security checks for extend query. @returns {string[]} Array with browser names in Can I Use. @example browserslist('IE >= 10, IE 8') //=> ['ie 11', 'ie 10', 'ie 8']
[ "Return", "array", "of", "browsers", "by", "selection", "queries", "." ]
8191c2d3c113cad16392734d6e3bf3c4e61cdfb0
https://github.com/browserslist/browserslist/blob/8191c2d3c113cad16392734d6e3bf3c4e61cdfb0/index.js#L282-L332
5,635
browserslist/browserslist
index.js
doMatch
function doMatch (string, qs) { var or = /^(?:,\s*|\s+OR\s+)(.*)/i var and = /^\s+AND\s+(.*)/i return find(string, function (parsed, n, max) { if (and.test(parsed)) { qs.unshift({ type: QUERY_AND, queryString: parsed.match(and)[1] }) return true } else if (or.test(parsed)) { qs.unshift({ type: QUERY_OR, queryString: parsed.match(or)[1] }) return true } else if (n === max) { qs.unshift({ type: QUERY_OR, queryString: parsed.trim() }) return true } return false }) }
javascript
function doMatch (string, qs) { var or = /^(?:,\s*|\s+OR\s+)(.*)/i var and = /^\s+AND\s+(.*)/i return find(string, function (parsed, n, max) { if (and.test(parsed)) { qs.unshift({ type: QUERY_AND, queryString: parsed.match(and)[1] }) return true } else if (or.test(parsed)) { qs.unshift({ type: QUERY_OR, queryString: parsed.match(or)[1] }) return true } else if (n === max) { qs.unshift({ type: QUERY_OR, queryString: parsed.trim() }) return true } return false }) }
[ "function", "doMatch", "(", "string", ",", "qs", ")", "{", "var", "or", "=", "/", "^(?:,\\s*|\\s+OR\\s+)(.*)", "/", "i", "var", "and", "=", "/", "^\\s+AND\\s+(.*)", "/", "i", "return", "find", "(", "string", ",", "function", "(", "parsed", ",", "n", ",", "max", ")", "{", "if", "(", "and", ".", "test", "(", "parsed", ")", ")", "{", "qs", ".", "unshift", "(", "{", "type", ":", "QUERY_AND", ",", "queryString", ":", "parsed", ".", "match", "(", "and", ")", "[", "1", "]", "}", ")", "return", "true", "}", "else", "if", "(", "or", ".", "test", "(", "parsed", ")", ")", "{", "qs", ".", "unshift", "(", "{", "type", ":", "QUERY_OR", ",", "queryString", ":", "parsed", ".", "match", "(", "or", ")", "[", "1", "]", "}", ")", "return", "true", "}", "else", "if", "(", "n", "===", "max", ")", "{", "qs", ".", "unshift", "(", "{", "type", ":", "QUERY_OR", ",", "queryString", ":", "parsed", ".", "trim", "(", ")", "}", ")", "return", "true", "}", "return", "false", "}", ")", "}" ]
Find query matches in a string. This function is meant to be called repeatedly with the returned query string until there is no more matches. @param {string} string A string with one or more queries. @param {BrowserslistQuery[]} qs Out parameter, will be filled with `BrowserslistQuery`. @returns {string} The rest of the query string minus the matched part.
[ "Find", "query", "matches", "in", "a", "string", ".", "This", "function", "is", "meant", "to", "be", "called", "repeatedly", "with", "the", "returned", "query", "string", "until", "there", "is", "no", "more", "matches", "." ]
8191c2d3c113cad16392734d6e3bf3c4e61cdfb0
https://github.com/browserslist/browserslist/blob/8191c2d3c113cad16392734d6e3bf3c4e61cdfb0/index.js#L363-L380
5,636
karpathy/convnetjs
demo/js/automatic.js
makeDataset
function makeDataset(arr, colstats) { var labelix = parseInt($("#labelix").val()); if(labelix < 0) labelix = D + labelix; // -1 should turn to D-1 var data = []; var labels = []; for(var i=0;i<N;i++) { var arri = arr[i]; // create the input datapoint Vol() var p = arri.slice(0, D-1); var xarr = []; for(var j=0;j<D;j++) { if(j===labelix) continue; // skip! if(colstats[j].numeric) { xarr.push(parseFloat(arri[j])); } else { var u = colstats[j].uniques; var ix = u.indexOf(arri[j]); // turn into 1ofk encoding for(var q=0;q<u.length;q++) { if(q === ix) { xarr.push(1.0); } else { xarr.push(0.0); } } } } var x = new convnetjs.Vol(xarr); // process the label (last column) if(colstats[labelix].numeric) { var L = parseFloat(arri[labelix]); // regression } else { var L = colstats[labelix].uniques.indexOf(arri[labelix]); // classification if(L==-1) { console.log('whoa label not found! CRITICAL ERROR, very fishy.'); } } data.push(x); labels.push(L); } var dataset = {}; dataset.data = data; dataset.labels = labels; return dataset; }
javascript
function makeDataset(arr, colstats) { var labelix = parseInt($("#labelix").val()); if(labelix < 0) labelix = D + labelix; // -1 should turn to D-1 var data = []; var labels = []; for(var i=0;i<N;i++) { var arri = arr[i]; // create the input datapoint Vol() var p = arri.slice(0, D-1); var xarr = []; for(var j=0;j<D;j++) { if(j===labelix) continue; // skip! if(colstats[j].numeric) { xarr.push(parseFloat(arri[j])); } else { var u = colstats[j].uniques; var ix = u.indexOf(arri[j]); // turn into 1ofk encoding for(var q=0;q<u.length;q++) { if(q === ix) { xarr.push(1.0); } else { xarr.push(0.0); } } } } var x = new convnetjs.Vol(xarr); // process the label (last column) if(colstats[labelix].numeric) { var L = parseFloat(arri[labelix]); // regression } else { var L = colstats[labelix].uniques.indexOf(arri[labelix]); // classification if(L==-1) { console.log('whoa label not found! CRITICAL ERROR, very fishy.'); } } data.push(x); labels.push(L); } var dataset = {}; dataset.data = data; dataset.labels = labels; return dataset; }
[ "function", "makeDataset", "(", "arr", ",", "colstats", ")", "{", "var", "labelix", "=", "parseInt", "(", "$", "(", "\"#labelix\"", ")", ".", "val", "(", ")", ")", ";", "if", "(", "labelix", "<", "0", ")", "labelix", "=", "D", "+", "labelix", ";", "// -1 should turn to D-1", "var", "data", "=", "[", "]", ";", "var", "labels", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "N", ";", "i", "++", ")", "{", "var", "arri", "=", "arr", "[", "i", "]", ";", "// create the input datapoint Vol()", "var", "p", "=", "arri", ".", "slice", "(", "0", ",", "D", "-", "1", ")", ";", "var", "xarr", "=", "[", "]", ";", "for", "(", "var", "j", "=", "0", ";", "j", "<", "D", ";", "j", "++", ")", "{", "if", "(", "j", "===", "labelix", ")", "continue", ";", "// skip!", "if", "(", "colstats", "[", "j", "]", ".", "numeric", ")", "{", "xarr", ".", "push", "(", "parseFloat", "(", "arri", "[", "j", "]", ")", ")", ";", "}", "else", "{", "var", "u", "=", "colstats", "[", "j", "]", ".", "uniques", ";", "var", "ix", "=", "u", ".", "indexOf", "(", "arri", "[", "j", "]", ")", ";", "// turn into 1ofk encoding", "for", "(", "var", "q", "=", "0", ";", "q", "<", "u", ".", "length", ";", "q", "++", ")", "{", "if", "(", "q", "===", "ix", ")", "{", "xarr", ".", "push", "(", "1.0", ")", ";", "}", "else", "{", "xarr", ".", "push", "(", "0.0", ")", ";", "}", "}", "}", "}", "var", "x", "=", "new", "convnetjs", ".", "Vol", "(", "xarr", ")", ";", "// process the label (last column)", "if", "(", "colstats", "[", "labelix", "]", ".", "numeric", ")", "{", "var", "L", "=", "parseFloat", "(", "arri", "[", "labelix", "]", ")", ";", "// regression", "}", "else", "{", "var", "L", "=", "colstats", "[", "labelix", "]", ".", "uniques", ".", "indexOf", "(", "arri", "[", "labelix", "]", ")", ";", "// classification", "if", "(", "L", "==", "-", "1", ")", "{", "console", ".", "log", "(", "'whoa label not found! CRITICAL ERROR, very fishy.'", ")", ";", "}", "}", "data", ".", "push", "(", "x", ")", ";", "labels", ".", "push", "(", "L", ")", ";", "}", "var", "dataset", "=", "{", "}", ";", "dataset", ".", "data", "=", "data", ";", "dataset", ".", "labels", "=", "labels", ";", "return", "dataset", ";", "}" ]
process input mess into vols and labels
[ "process", "input", "mess", "into", "vols", "and", "labels" ]
4c3358a315b4d71f31a0d532eb5d1700e9e592ee
https://github.com/karpathy/convnetjs/blob/4c3358a315b4d71f31a0d532eb5d1700e9e592ee/demo/js/automatic.js#L83-L129
5,637
karpathy/convnetjs
demo/js/images-demo.js
function() { var b = test_batch; var k = Math.floor(Math.random()*num_samples_per_batch); var n = b*num_samples_per_batch+k; var p = img_data[b].data; var x = new convnetjs.Vol(image_dimension,image_dimension,image_channels,0.0); var W = image_dimension*image_dimension; var j=0; for(var dc=0;dc<image_channels;dc++) { var i=0; for(var xc=0;xc<image_dimension;xc++) { for(var yc=0;yc<image_dimension;yc++) { var ix = ((W * k) + i) * 4 + dc; x.set(yc,xc,dc,p[ix]/255.0-0.5); i++; } } } // distort position and maybe flip var xs = []; if (random_flip || random_position){ for(var k=0;k<6;k++) { var test_variation = x; if(random_position){ var dx = Math.floor(Math.random()*5-2); var dy = Math.floor(Math.random()*5-2); test_variation = convnetjs.augment(test_variation, image_dimension, dx, dy, false); } if(random_flip){ test_variation = convnetjs.augment(test_variation, image_dimension, 0, 0, Math.random()<0.5); } xs.push(test_variation); } }else{ xs.push(x, image_dimension, 0, 0, false); // push an un-augmented copy } // return multiple augmentations, and we will average the network over them // to increase performance return {x:xs, label:labels[n]}; }
javascript
function() { var b = test_batch; var k = Math.floor(Math.random()*num_samples_per_batch); var n = b*num_samples_per_batch+k; var p = img_data[b].data; var x = new convnetjs.Vol(image_dimension,image_dimension,image_channels,0.0); var W = image_dimension*image_dimension; var j=0; for(var dc=0;dc<image_channels;dc++) { var i=0; for(var xc=0;xc<image_dimension;xc++) { for(var yc=0;yc<image_dimension;yc++) { var ix = ((W * k) + i) * 4 + dc; x.set(yc,xc,dc,p[ix]/255.0-0.5); i++; } } } // distort position and maybe flip var xs = []; if (random_flip || random_position){ for(var k=0;k<6;k++) { var test_variation = x; if(random_position){ var dx = Math.floor(Math.random()*5-2); var dy = Math.floor(Math.random()*5-2); test_variation = convnetjs.augment(test_variation, image_dimension, dx, dy, false); } if(random_flip){ test_variation = convnetjs.augment(test_variation, image_dimension, 0, 0, Math.random()<0.5); } xs.push(test_variation); } }else{ xs.push(x, image_dimension, 0, 0, false); // push an un-augmented copy } // return multiple augmentations, and we will average the network over them // to increase performance return {x:xs, label:labels[n]}; }
[ "function", "(", ")", "{", "var", "b", "=", "test_batch", ";", "var", "k", "=", "Math", ".", "floor", "(", "Math", ".", "random", "(", ")", "*", "num_samples_per_batch", ")", ";", "var", "n", "=", "b", "*", "num_samples_per_batch", "+", "k", ";", "var", "p", "=", "img_data", "[", "b", "]", ".", "data", ";", "var", "x", "=", "new", "convnetjs", ".", "Vol", "(", "image_dimension", ",", "image_dimension", ",", "image_channels", ",", "0.0", ")", ";", "var", "W", "=", "image_dimension", "*", "image_dimension", ";", "var", "j", "=", "0", ";", "for", "(", "var", "dc", "=", "0", ";", "dc", "<", "image_channels", ";", "dc", "++", ")", "{", "var", "i", "=", "0", ";", "for", "(", "var", "xc", "=", "0", ";", "xc", "<", "image_dimension", ";", "xc", "++", ")", "{", "for", "(", "var", "yc", "=", "0", ";", "yc", "<", "image_dimension", ";", "yc", "++", ")", "{", "var", "ix", "=", "(", "(", "W", "*", "k", ")", "+", "i", ")", "*", "4", "+", "dc", ";", "x", ".", "set", "(", "yc", ",", "xc", ",", "dc", ",", "p", "[", "ix", "]", "/", "255.0", "-", "0.5", ")", ";", "i", "++", ";", "}", "}", "}", "// distort position and maybe flip", "var", "xs", "=", "[", "]", ";", "if", "(", "random_flip", "||", "random_position", ")", "{", "for", "(", "var", "k", "=", "0", ";", "k", "<", "6", ";", "k", "++", ")", "{", "var", "test_variation", "=", "x", ";", "if", "(", "random_position", ")", "{", "var", "dx", "=", "Math", ".", "floor", "(", "Math", ".", "random", "(", ")", "*", "5", "-", "2", ")", ";", "var", "dy", "=", "Math", ".", "floor", "(", "Math", ".", "random", "(", ")", "*", "5", "-", "2", ")", ";", "test_variation", "=", "convnetjs", ".", "augment", "(", "test_variation", ",", "image_dimension", ",", "dx", ",", "dy", ",", "false", ")", ";", "}", "if", "(", "random_flip", ")", "{", "test_variation", "=", "convnetjs", ".", "augment", "(", "test_variation", ",", "image_dimension", ",", "0", ",", "0", ",", "Math", ".", "random", "(", ")", "<", "0.5", ")", ";", "}", "xs", ".", "push", "(", "test_variation", ")", ";", "}", "}", "else", "{", "xs", ".", "push", "(", "x", ",", "image_dimension", ",", "0", ",", "0", ",", "false", ")", ";", "// push an un-augmented copy", "}", "// return multiple augmentations, and we will average the network over them", "// to increase performance", "return", "{", "x", ":", "xs", ",", "label", ":", "labels", "[", "n", "]", "}", ";", "}" ]
sample a random testing instance
[ "sample", "a", "random", "testing", "instance" ]
4c3358a315b4d71f31a0d532eb5d1700e9e592ee
https://github.com/karpathy/convnetjs/blob/4c3358a315b4d71f31a0d532eb5d1700e9e592ee/demo/js/images-demo.js#L50-L96
5,638
karpathy/convnetjs
demo/js/images-demo.js
function() { var num_classes = net.layers[net.layers.length-1].out_depth; document.getElementById('testset_acc').innerHTML = ''; var num_total = 0; var num_correct = 0; // grab a random test image for(num=0;num<4;num++) { var sample = sample_test_instance(); var y = sample.label; // ground truth label // forward prop it through the network var aavg = new convnetjs.Vol(1,1,num_classes,0.0); // ensures we always have a list, regardless if above returns single item or list var xs = [].concat(sample.x); var n = xs.length; for(var i=0;i<n;i++) { var a = net.forward(xs[i]); aavg.addFrom(a); } var preds = []; for(var k=0;k<aavg.w.length;k++) { preds.push({k:k,p:aavg.w[k]}); } preds.sort(function(a,b){return a.p<b.p ? 1:-1;}); var correct = preds[0].k===y; if(correct) num_correct++; num_total++; var div = document.createElement('div'); div.className = 'testdiv'; // draw the image into a canvas draw_activations_COLOR(div, xs[0], 2); // draw Vol into canv // add predictions var probsdiv = document.createElement('div'); var t = ''; for(var k=0;k<3;k++) { var col = preds[k].k===y ? 'rgb(85,187,85)' : 'rgb(187,85,85)'; t += '<div class=\"pp\" style=\"width:' + Math.floor(preds[k].p/n*100) + 'px; background-color:' + col + ';\">' + classes_txt[preds[k].k] + '</div>' } probsdiv.innerHTML = t; probsdiv.className = 'probsdiv'; div.appendChild(probsdiv); // add it into DOM $(div).prependTo($("#testset_vis")).hide().fadeIn('slow').slideDown('slow'); if($(".probsdiv").length>200) { $("#testset_vis > .probsdiv").last().remove(); // pop to keep upper bound of shown items } } testAccWindow.add(num_correct/num_total); $("#testset_acc").text('test accuracy based on last 200 test images: ' + testAccWindow.get_average()); }
javascript
function() { var num_classes = net.layers[net.layers.length-1].out_depth; document.getElementById('testset_acc').innerHTML = ''; var num_total = 0; var num_correct = 0; // grab a random test image for(num=0;num<4;num++) { var sample = sample_test_instance(); var y = sample.label; // ground truth label // forward prop it through the network var aavg = new convnetjs.Vol(1,1,num_classes,0.0); // ensures we always have a list, regardless if above returns single item or list var xs = [].concat(sample.x); var n = xs.length; for(var i=0;i<n;i++) { var a = net.forward(xs[i]); aavg.addFrom(a); } var preds = []; for(var k=0;k<aavg.w.length;k++) { preds.push({k:k,p:aavg.w[k]}); } preds.sort(function(a,b){return a.p<b.p ? 1:-1;}); var correct = preds[0].k===y; if(correct) num_correct++; num_total++; var div = document.createElement('div'); div.className = 'testdiv'; // draw the image into a canvas draw_activations_COLOR(div, xs[0], 2); // draw Vol into canv // add predictions var probsdiv = document.createElement('div'); var t = ''; for(var k=0;k<3;k++) { var col = preds[k].k===y ? 'rgb(85,187,85)' : 'rgb(187,85,85)'; t += '<div class=\"pp\" style=\"width:' + Math.floor(preds[k].p/n*100) + 'px; background-color:' + col + ';\">' + classes_txt[preds[k].k] + '</div>' } probsdiv.innerHTML = t; probsdiv.className = 'probsdiv'; div.appendChild(probsdiv); // add it into DOM $(div).prependTo($("#testset_vis")).hide().fadeIn('slow').slideDown('slow'); if($(".probsdiv").length>200) { $("#testset_vis > .probsdiv").last().remove(); // pop to keep upper bound of shown items } } testAccWindow.add(num_correct/num_total); $("#testset_acc").text('test accuracy based on last 200 test images: ' + testAccWindow.get_average()); }
[ "function", "(", ")", "{", "var", "num_classes", "=", "net", ".", "layers", "[", "net", ".", "layers", ".", "length", "-", "1", "]", ".", "out_depth", ";", "document", ".", "getElementById", "(", "'testset_acc'", ")", ".", "innerHTML", "=", "''", ";", "var", "num_total", "=", "0", ";", "var", "num_correct", "=", "0", ";", "// grab a random test image", "for", "(", "num", "=", "0", ";", "num", "<", "4", ";", "num", "++", ")", "{", "var", "sample", "=", "sample_test_instance", "(", ")", ";", "var", "y", "=", "sample", ".", "label", ";", "// ground truth label", "// forward prop it through the network", "var", "aavg", "=", "new", "convnetjs", ".", "Vol", "(", "1", ",", "1", ",", "num_classes", ",", "0.0", ")", ";", "// ensures we always have a list, regardless if above returns single item or list", "var", "xs", "=", "[", "]", ".", "concat", "(", "sample", ".", "x", ")", ";", "var", "n", "=", "xs", ".", "length", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "n", ";", "i", "++", ")", "{", "var", "a", "=", "net", ".", "forward", "(", "xs", "[", "i", "]", ")", ";", "aavg", ".", "addFrom", "(", "a", ")", ";", "}", "var", "preds", "=", "[", "]", ";", "for", "(", "var", "k", "=", "0", ";", "k", "<", "aavg", ".", "w", ".", "length", ";", "k", "++", ")", "{", "preds", ".", "push", "(", "{", "k", ":", "k", ",", "p", ":", "aavg", ".", "w", "[", "k", "]", "}", ")", ";", "}", "preds", ".", "sort", "(", "function", "(", "a", ",", "b", ")", "{", "return", "a", ".", "p", "<", "b", ".", "p", "?", "1", ":", "-", "1", ";", "}", ")", ";", "var", "correct", "=", "preds", "[", "0", "]", ".", "k", "===", "y", ";", "if", "(", "correct", ")", "num_correct", "++", ";", "num_total", "++", ";", "var", "div", "=", "document", ".", "createElement", "(", "'div'", ")", ";", "div", ".", "className", "=", "'testdiv'", ";", "// draw the image into a canvas", "draw_activations_COLOR", "(", "div", ",", "xs", "[", "0", "]", ",", "2", ")", ";", "// draw Vol into canv", "// add predictions", "var", "probsdiv", "=", "document", ".", "createElement", "(", "'div'", ")", ";", "var", "t", "=", "''", ";", "for", "(", "var", "k", "=", "0", ";", "k", "<", "3", ";", "k", "++", ")", "{", "var", "col", "=", "preds", "[", "k", "]", ".", "k", "===", "y", "?", "'rgb(85,187,85)'", ":", "'rgb(187,85,85)'", ";", "t", "+=", "'<div class=\\\"pp\\\" style=\\\"width:'", "+", "Math", ".", "floor", "(", "preds", "[", "k", "]", ".", "p", "/", "n", "*", "100", ")", "+", "'px; background-color:'", "+", "col", "+", "';\\\">'", "+", "classes_txt", "[", "preds", "[", "k", "]", ".", "k", "]", "+", "'</div>'", "}", "probsdiv", ".", "innerHTML", "=", "t", ";", "probsdiv", ".", "className", "=", "'probsdiv'", ";", "div", ".", "appendChild", "(", "probsdiv", ")", ";", "// add it into DOM", "$", "(", "div", ")", ".", "prependTo", "(", "$", "(", "\"#testset_vis\"", ")", ")", ".", "hide", "(", ")", ".", "fadeIn", "(", "'slow'", ")", ".", "slideDown", "(", "'slow'", ")", ";", "if", "(", "$", "(", "\".probsdiv\"", ")", ".", "length", ">", "200", ")", "{", "$", "(", "\"#testset_vis > .probsdiv\"", ")", ".", "last", "(", ")", ".", "remove", "(", ")", ";", "// pop to keep upper bound of shown items", "}", "}", "testAccWindow", ".", "add", "(", "num_correct", "/", "num_total", ")", ";", "$", "(", "\"#testset_acc\"", ")", ".", "text", "(", "'test accuracy based on last 200 test images: '", "+", "testAccWindow", ".", "get_average", "(", ")", ")", ";", "}" ]
evaluate current network on test set
[ "evaluate", "current", "network", "on", "test", "set" ]
4c3358a315b4d71f31a0d532eb5d1700e9e592ee
https://github.com/karpathy/convnetjs/blob/4c3358a315b4d71f31a0d532eb5d1700e9e592ee/demo/js/images-demo.js#L403-L458
5,639
karpathy/convnetjs
demo/js/rldemo.js
function(lst, x, y, w, h) { lst.push(new Wall(new Vec(x,y), new Vec(x+w,y))); lst.push(new Wall(new Vec(x+w,y), new Vec(x+w,y+h))); lst.push(new Wall(new Vec(x+w,y+h), new Vec(x,y+h))); lst.push(new Wall(new Vec(x,y+h), new Vec(x,y))); }
javascript
function(lst, x, y, w, h) { lst.push(new Wall(new Vec(x,y), new Vec(x+w,y))); lst.push(new Wall(new Vec(x+w,y), new Vec(x+w,y+h))); lst.push(new Wall(new Vec(x+w,y+h), new Vec(x,y+h))); lst.push(new Wall(new Vec(x,y+h), new Vec(x,y))); }
[ "function", "(", "lst", ",", "x", ",", "y", ",", "w", ",", "h", ")", "{", "lst", ".", "push", "(", "new", "Wall", "(", "new", "Vec", "(", "x", ",", "y", ")", ",", "new", "Vec", "(", "x", "+", "w", ",", "y", ")", ")", ")", ";", "lst", ".", "push", "(", "new", "Wall", "(", "new", "Vec", "(", "x", "+", "w", ",", "y", ")", ",", "new", "Vec", "(", "x", "+", "w", ",", "y", "+", "h", ")", ")", ")", ";", "lst", ".", "push", "(", "new", "Wall", "(", "new", "Vec", "(", "x", "+", "w", ",", "y", "+", "h", ")", ",", "new", "Vec", "(", "x", ",", "y", "+", "h", ")", ")", ")", ";", "lst", ".", "push", "(", "new", "Wall", "(", "new", "Vec", "(", "x", ",", "y", "+", "h", ")", ",", "new", "Vec", "(", "x", ",", "y", ")", ")", ")", ";", "}" ]
World object contains many agents and walls and food and stuff
[ "World", "object", "contains", "many", "agents", "and", "walls", "and", "food", "and", "stuff" ]
4c3358a315b4d71f31a0d532eb5d1700e9e592ee
https://github.com/karpathy/convnetjs/blob/4c3358a315b4d71f31a0d532eb5d1700e9e592ee/demo/js/rldemo.js#L67-L72
5,640
karpathy/convnetjs
demo/js/rldemo.js
function() { // positional information this.p = new Vec(50, 50); this.op = this.p; // old position this.angle = 0; // direction facing this.actions = []; this.actions.push([1,1]); this.actions.push([0.8,1]); this.actions.push([1,0.8]); this.actions.push([0.5,0]); this.actions.push([0,0.5]); // properties this.rad = 10; this.eyes = []; for(var k=0;k<9;k++) { this.eyes.push(new Eye((k-3)*0.25)); } // braaain //this.brain = new deepqlearn.Brain(this.eyes.length * 3, this.actions.length); var spec = document.getElementById('qspec').value; eval(spec); this.brain = brain; this.reward_bonus = 0.0; this.digestion_signal = 0.0; // outputs on world this.rot1 = 0.0; // rotation speed of 1st wheel this.rot2 = 0.0; // rotation speed of 2nd wheel this.prevactionix = -1; }
javascript
function() { // positional information this.p = new Vec(50, 50); this.op = this.p; // old position this.angle = 0; // direction facing this.actions = []; this.actions.push([1,1]); this.actions.push([0.8,1]); this.actions.push([1,0.8]); this.actions.push([0.5,0]); this.actions.push([0,0.5]); // properties this.rad = 10; this.eyes = []; for(var k=0;k<9;k++) { this.eyes.push(new Eye((k-3)*0.25)); } // braaain //this.brain = new deepqlearn.Brain(this.eyes.length * 3, this.actions.length); var spec = document.getElementById('qspec').value; eval(spec); this.brain = brain; this.reward_bonus = 0.0; this.digestion_signal = 0.0; // outputs on world this.rot1 = 0.0; // rotation speed of 1st wheel this.rot2 = 0.0; // rotation speed of 2nd wheel this.prevactionix = -1; }
[ "function", "(", ")", "{", "// positional information", "this", ".", "p", "=", "new", "Vec", "(", "50", ",", "50", ")", ";", "this", ".", "op", "=", "this", ".", "p", ";", "// old position", "this", ".", "angle", "=", "0", ";", "// direction facing", "this", ".", "actions", "=", "[", "]", ";", "this", ".", "actions", ".", "push", "(", "[", "1", ",", "1", "]", ")", ";", "this", ".", "actions", ".", "push", "(", "[", "0.8", ",", "1", "]", ")", ";", "this", ".", "actions", ".", "push", "(", "[", "1", ",", "0.8", "]", ")", ";", "this", ".", "actions", ".", "push", "(", "[", "0.5", ",", "0", "]", ")", ";", "this", ".", "actions", ".", "push", "(", "[", "0", ",", "0.5", "]", ")", ";", "// properties", "this", ".", "rad", "=", "10", ";", "this", ".", "eyes", "=", "[", "]", ";", "for", "(", "var", "k", "=", "0", ";", "k", "<", "9", ";", "k", "++", ")", "{", "this", ".", "eyes", ".", "push", "(", "new", "Eye", "(", "(", "k", "-", "3", ")", "*", "0.25", ")", ")", ";", "}", "// braaain", "//this.brain = new deepqlearn.Brain(this.eyes.length * 3, this.actions.length);", "var", "spec", "=", "document", ".", "getElementById", "(", "'qspec'", ")", ".", "value", ";", "eval", "(", "spec", ")", ";", "this", ".", "brain", "=", "brain", ";", "this", ".", "reward_bonus", "=", "0.0", ";", "this", ".", "digestion_signal", "=", "0.0", ";", "// outputs on world", "this", ".", "rot1", "=", "0.0", ";", "// rotation speed of 1st wheel", "this", ".", "rot2", "=", "0.0", ";", "// rotation speed of 2nd wheel", "this", ".", "prevactionix", "=", "-", "1", ";", "}" ]
A single agent
[ "A", "single", "agent" ]
4c3358a315b4d71f31a0d532eb5d1700e9e592ee
https://github.com/karpathy/convnetjs/blob/4c3358a315b4d71f31a0d532eb5d1700e9e592ee/demo/js/rldemo.js#L283-L316
5,641
karpathy/convnetjs
src/convnet_net.js
function() { var new_defs = []; for(var i=0;i<defs.length;i++) { var def = defs[i]; if(def.type==='softmax' || def.type==='svm') { // add an fc layer here, there is no reason the user should // have to worry about this and we almost always want to new_defs.push({type:'fc', num_neurons: def.num_classes}); } if(def.type==='regression') { // add an fc layer here, there is no reason the user should // have to worry about this and we almost always want to new_defs.push({type:'fc', num_neurons: def.num_neurons}); } if((def.type==='fc' || def.type==='conv') && typeof(def.bias_pref) === 'undefined'){ def.bias_pref = 0.0; if(typeof def.activation !== 'undefined' && def.activation === 'relu') { def.bias_pref = 0.1; // relus like a bit of positive bias to get gradients early // otherwise it's technically possible that a relu unit will never turn on (by chance) // and will never get any gradient and never contribute any computation. Dead relu. } } new_defs.push(def); if(typeof def.activation !== 'undefined') { if(def.activation==='relu') { new_defs.push({type:'relu'}); } else if (def.activation==='sigmoid') { new_defs.push({type:'sigmoid'}); } else if (def.activation==='tanh') { new_defs.push({type:'tanh'}); } else if (def.activation==='maxout') { // create maxout activation, and pass along group size, if provided var gs = def.group_size !== 'undefined' ? def.group_size : 2; new_defs.push({type:'maxout', group_size:gs}); } else { console.log('ERROR unsupported activation ' + def.activation); } } if(typeof def.drop_prob !== 'undefined' && def.type !== 'dropout') { new_defs.push({type:'dropout', drop_prob: def.drop_prob}); } } return new_defs; }
javascript
function() { var new_defs = []; for(var i=0;i<defs.length;i++) { var def = defs[i]; if(def.type==='softmax' || def.type==='svm') { // add an fc layer here, there is no reason the user should // have to worry about this and we almost always want to new_defs.push({type:'fc', num_neurons: def.num_classes}); } if(def.type==='regression') { // add an fc layer here, there is no reason the user should // have to worry about this and we almost always want to new_defs.push({type:'fc', num_neurons: def.num_neurons}); } if((def.type==='fc' || def.type==='conv') && typeof(def.bias_pref) === 'undefined'){ def.bias_pref = 0.0; if(typeof def.activation !== 'undefined' && def.activation === 'relu') { def.bias_pref = 0.1; // relus like a bit of positive bias to get gradients early // otherwise it's technically possible that a relu unit will never turn on (by chance) // and will never get any gradient and never contribute any computation. Dead relu. } } new_defs.push(def); if(typeof def.activation !== 'undefined') { if(def.activation==='relu') { new_defs.push({type:'relu'}); } else if (def.activation==='sigmoid') { new_defs.push({type:'sigmoid'}); } else if (def.activation==='tanh') { new_defs.push({type:'tanh'}); } else if (def.activation==='maxout') { // create maxout activation, and pass along group size, if provided var gs = def.group_size !== 'undefined' ? def.group_size : 2; new_defs.push({type:'maxout', group_size:gs}); } else { console.log('ERROR unsupported activation ' + def.activation); } } if(typeof def.drop_prob !== 'undefined' && def.type !== 'dropout') { new_defs.push({type:'dropout', drop_prob: def.drop_prob}); } } return new_defs; }
[ "function", "(", ")", "{", "var", "new_defs", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "defs", ".", "length", ";", "i", "++", ")", "{", "var", "def", "=", "defs", "[", "i", "]", ";", "if", "(", "def", ".", "type", "===", "'softmax'", "||", "def", ".", "type", "===", "'svm'", ")", "{", "// add an fc layer here, there is no reason the user should", "// have to worry about this and we almost always want to", "new_defs", ".", "push", "(", "{", "type", ":", "'fc'", ",", "num_neurons", ":", "def", ".", "num_classes", "}", ")", ";", "}", "if", "(", "def", ".", "type", "===", "'regression'", ")", "{", "// add an fc layer here, there is no reason the user should", "// have to worry about this and we almost always want to", "new_defs", ".", "push", "(", "{", "type", ":", "'fc'", ",", "num_neurons", ":", "def", ".", "num_neurons", "}", ")", ";", "}", "if", "(", "(", "def", ".", "type", "===", "'fc'", "||", "def", ".", "type", "===", "'conv'", ")", "&&", "typeof", "(", "def", ".", "bias_pref", ")", "===", "'undefined'", ")", "{", "def", ".", "bias_pref", "=", "0.0", ";", "if", "(", "typeof", "def", ".", "activation", "!==", "'undefined'", "&&", "def", ".", "activation", "===", "'relu'", ")", "{", "def", ".", "bias_pref", "=", "0.1", ";", "// relus like a bit of positive bias to get gradients early", "// otherwise it's technically possible that a relu unit will never turn on (by chance)", "// and will never get any gradient and never contribute any computation. Dead relu.", "}", "}", "new_defs", ".", "push", "(", "def", ")", ";", "if", "(", "typeof", "def", ".", "activation", "!==", "'undefined'", ")", "{", "if", "(", "def", ".", "activation", "===", "'relu'", ")", "{", "new_defs", ".", "push", "(", "{", "type", ":", "'relu'", "}", ")", ";", "}", "else", "if", "(", "def", ".", "activation", "===", "'sigmoid'", ")", "{", "new_defs", ".", "push", "(", "{", "type", ":", "'sigmoid'", "}", ")", ";", "}", "else", "if", "(", "def", ".", "activation", "===", "'tanh'", ")", "{", "new_defs", ".", "push", "(", "{", "type", ":", "'tanh'", "}", ")", ";", "}", "else", "if", "(", "def", ".", "activation", "===", "'maxout'", ")", "{", "// create maxout activation, and pass along group size, if provided", "var", "gs", "=", "def", ".", "group_size", "!==", "'undefined'", "?", "def", ".", "group_size", ":", "2", ";", "new_defs", ".", "push", "(", "{", "type", ":", "'maxout'", ",", "group_size", ":", "gs", "}", ")", ";", "}", "else", "{", "console", ".", "log", "(", "'ERROR unsupported activation '", "+", "def", ".", "activation", ")", ";", "}", "}", "if", "(", "typeof", "def", ".", "drop_prob", "!==", "'undefined'", "&&", "def", ".", "type", "!==", "'dropout'", ")", "{", "new_defs", ".", "push", "(", "{", "type", ":", "'dropout'", ",", "drop_prob", ":", "def", ".", "drop_prob", "}", ")", ";", "}", "}", "return", "new_defs", ";", "}" ]
desugar layer_defs for adding activation, dropout layers etc
[ "desugar", "layer_defs", "for", "adding", "activation", "dropout", "layers", "etc" ]
4c3358a315b4d71f31a0d532eb5d1700e9e592ee
https://github.com/karpathy/convnetjs/blob/4c3358a315b4d71f31a0d532eb5d1700e9e592ee/src/convnet_net.js#L22-L68
5,642
karpathy/convnetjs
src/convnet_util.js
function(w) { if(w.length === 0) { return {}; } // ... ;s var maxv = w[0]; var minv = w[0]; var maxi = 0; var mini = 0; var n = w.length; for(var i=1;i<n;i++) { if(w[i] > maxv) { maxv = w[i]; maxi = i; } if(w[i] < minv) { minv = w[i]; mini = i; } } return {maxi: maxi, maxv: maxv, mini: mini, minv: minv, dv:maxv-minv}; }
javascript
function(w) { if(w.length === 0) { return {}; } // ... ;s var maxv = w[0]; var minv = w[0]; var maxi = 0; var mini = 0; var n = w.length; for(var i=1;i<n;i++) { if(w[i] > maxv) { maxv = w[i]; maxi = i; } if(w[i] < minv) { minv = w[i]; mini = i; } } return {maxi: maxi, maxv: maxv, mini: mini, minv: minv, dv:maxv-minv}; }
[ "function", "(", "w", ")", "{", "if", "(", "w", ".", "length", "===", "0", ")", "{", "return", "{", "}", ";", "}", "// ... ;s", "var", "maxv", "=", "w", "[", "0", "]", ";", "var", "minv", "=", "w", "[", "0", "]", ";", "var", "maxi", "=", "0", ";", "var", "mini", "=", "0", ";", "var", "n", "=", "w", ".", "length", ";", "for", "(", "var", "i", "=", "1", ";", "i", "<", "n", ";", "i", "++", ")", "{", "if", "(", "w", "[", "i", "]", ">", "maxv", ")", "{", "maxv", "=", "w", "[", "i", "]", ";", "maxi", "=", "i", ";", "}", "if", "(", "w", "[", "i", "]", "<", "minv", ")", "{", "minv", "=", "w", "[", "i", "]", ";", "mini", "=", "i", ";", "}", "}", "return", "{", "maxi", ":", "maxi", ",", "maxv", ":", "maxv", ",", "mini", ":", "mini", ",", "minv", ":", "minv", ",", "dv", ":", "maxv", "-", "minv", "}", ";", "}" ]
return max and min of a given non-empty array.
[ "return", "max", "and", "min", "of", "a", "given", "non", "-", "empty", "array", "." ]
4c3358a315b4d71f31a0d532eb5d1700e9e592ee
https://github.com/karpathy/convnetjs/blob/4c3358a315b4d71f31a0d532eb5d1700e9e592ee/src/convnet_util.js#L56-L68
5,643
karpathy/convnetjs
src/convnet_util.js
function(lst, probs) { var p = randf(0, 1.0); var cumprob = 0.0; for(var k=0,n=lst.length;k<n;k++) { cumprob += probs[k]; if(p < cumprob) { return lst[k]; } } }
javascript
function(lst, probs) { var p = randf(0, 1.0); var cumprob = 0.0; for(var k=0,n=lst.length;k<n;k++) { cumprob += probs[k]; if(p < cumprob) { return lst[k]; } } }
[ "function", "(", "lst", ",", "probs", ")", "{", "var", "p", "=", "randf", "(", "0", ",", "1.0", ")", ";", "var", "cumprob", "=", "0.0", ";", "for", "(", "var", "k", "=", "0", ",", "n", "=", "lst", ".", "length", ";", "k", "<", "n", ";", "k", "++", ")", "{", "cumprob", "+=", "probs", "[", "k", "]", ";", "if", "(", "p", "<", "cumprob", ")", "{", "return", "lst", "[", "k", "]", ";", "}", "}", "}" ]
sample from list lst according to probabilities in list probs the two lists are of same size, and probs adds up to 1
[ "sample", "from", "list", "lst", "according", "to", "probabilities", "in", "list", "probs", "the", "two", "lists", "are", "of", "same", "size", "and", "probs", "adds", "up", "to", "1" ]
4c3358a315b4d71f31a0d532eb5d1700e9e592ee
https://github.com/karpathy/convnetjs/blob/4c3358a315b4d71f31a0d532eb5d1700e9e592ee/src/convnet_util.js#L88-L95
5,644
karpathy/convnetjs
src/convnet_util.js
function(opt, field_name, default_value) { if(typeof field_name === 'string') { // case of single string return (typeof opt[field_name] !== 'undefined') ? opt[field_name] : default_value; } else { // assume we are given a list of string instead var ret = default_value; for(var i=0;i<field_name.length;i++) { var f = field_name[i]; if (typeof opt[f] !== 'undefined') { ret = opt[f]; // overwrite return value } } return ret; } }
javascript
function(opt, field_name, default_value) { if(typeof field_name === 'string') { // case of single string return (typeof opt[field_name] !== 'undefined') ? opt[field_name] : default_value; } else { // assume we are given a list of string instead var ret = default_value; for(var i=0;i<field_name.length;i++) { var f = field_name[i]; if (typeof opt[f] !== 'undefined') { ret = opt[f]; // overwrite return value } } return ret; } }
[ "function", "(", "opt", ",", "field_name", ",", "default_value", ")", "{", "if", "(", "typeof", "field_name", "===", "'string'", ")", "{", "// case of single string", "return", "(", "typeof", "opt", "[", "field_name", "]", "!==", "'undefined'", ")", "?", "opt", "[", "field_name", "]", ":", "default_value", ";", "}", "else", "{", "// assume we are given a list of string instead", "var", "ret", "=", "default_value", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "field_name", ".", "length", ";", "i", "++", ")", "{", "var", "f", "=", "field_name", "[", "i", "]", ";", "if", "(", "typeof", "opt", "[", "f", "]", "!==", "'undefined'", ")", "{", "ret", "=", "opt", "[", "f", "]", ";", "// overwrite return value", "}", "}", "return", "ret", ";", "}", "}" ]
syntactic sugar function for getting default parameter values
[ "syntactic", "sugar", "function", "for", "getting", "default", "parameter", "values" ]
4c3358a315b4d71f31a0d532eb5d1700e9e592ee
https://github.com/karpathy/convnetjs/blob/4c3358a315b4d71f31a0d532eb5d1700e9e592ee/src/convnet_util.js#L98-L113
5,645
karpathy/convnetjs
build/deepqlearn.js
function(state0, action0, reward0, state1) { this.state0 = state0; this.action0 = action0; this.reward0 = reward0; this.state1 = state1; }
javascript
function(state0, action0, reward0, state1) { this.state0 = state0; this.action0 = action0; this.reward0 = reward0; this.state1 = state1; }
[ "function", "(", "state0", ",", "action0", ",", "reward0", ",", "state1", ")", "{", "this", ".", "state0", "=", "state0", ";", "this", ".", "action0", "=", "action0", ";", "this", ".", "reward0", "=", "reward0", ";", "this", ".", "state1", "=", "state1", ";", "}" ]
An agent is in state0 and does action0 environment then assigns reward0 and provides new state, state1 Experience nodes store all this information, which is used in the Q-learning update step
[ "An", "agent", "is", "in", "state0", "and", "does", "action0", "environment", "then", "assigns", "reward0", "and", "provides", "new", "state", "state1", "Experience", "nodes", "store", "all", "this", "information", "which", "is", "used", "in", "the", "Q", "-", "learning", "update", "step" ]
4c3358a315b4d71f31a0d532eb5d1700e9e592ee
https://github.com/karpathy/convnetjs/blob/4c3358a315b4d71f31a0d532eb5d1700e9e592ee/build/deepqlearn.js#L10-L15
5,646
karpathy/convnetjs
demo/js/npgmain.js
randi
function randi(s, e) { return Math.floor(Math.random()*(e-s) + s); }
javascript
function randi(s, e) { return Math.floor(Math.random()*(e-s) + s); }
[ "function", "randi", "(", "s", ",", "e", ")", "{", "return", "Math", ".", "floor", "(", "Math", ".", "random", "(", ")", "*", "(", "e", "-", "s", ")", "+", "s", ")", ";", "}" ]
uniform distribution integer
[ "uniform", "distribution", "integer" ]
4c3358a315b4d71f31a0d532eb5d1700e9e592ee
https://github.com/karpathy/convnetjs/blob/4c3358a315b4d71f31a0d532eb5d1700e9e592ee/demo/js/npgmain.js#L56-L58
5,647
karpathy/convnetjs
demo/js/npgmain.js
randn
function randn(mean, variance) { var V1, V2, S; do { var U1 = Math.random(); var U2 = Math.random(); V1 = 2 * U1 - 1; V2 = 2 * U2 - 1; S = V1 * V1 + V2 * V2; } while (S > 1); X = Math.sqrt(-2 * Math.log(S) / S) * V1; X = mean + Math.sqrt(variance) * X; return X; }
javascript
function randn(mean, variance) { var V1, V2, S; do { var U1 = Math.random(); var U2 = Math.random(); V1 = 2 * U1 - 1; V2 = 2 * U2 - 1; S = V1 * V1 + V2 * V2; } while (S > 1); X = Math.sqrt(-2 * Math.log(S) / S) * V1; X = mean + Math.sqrt(variance) * X; return X; }
[ "function", "randn", "(", "mean", ",", "variance", ")", "{", "var", "V1", ",", "V2", ",", "S", ";", "do", "{", "var", "U1", "=", "Math", ".", "random", "(", ")", ";", "var", "U2", "=", "Math", ".", "random", "(", ")", ";", "V1", "=", "2", "*", "U1", "-", "1", ";", "V2", "=", "2", "*", "U2", "-", "1", ";", "S", "=", "V1", "*", "V1", "+", "V2", "*", "V2", ";", "}", "while", "(", "S", ">", "1", ")", ";", "X", "=", "Math", ".", "sqrt", "(", "-", "2", "*", "Math", ".", "log", "(", "S", ")", "/", "S", ")", "*", "V1", ";", "X", "=", "mean", "+", "Math", ".", "sqrt", "(", "variance", ")", "*", "X", ";", "return", "X", ";", "}" ]
normal distribution random number
[ "normal", "distribution", "random", "number" ]
4c3358a315b4d71f31a0d532eb5d1700e9e592ee
https://github.com/karpathy/convnetjs/blob/4c3358a315b4d71f31a0d532eb5d1700e9e592ee/demo/js/npgmain.js#L66-L78
5,648
karpathy/convnetjs
src/convnet_layers_normalization.js
function(opt) { var opt = opt || {}; // required this.k = opt.k; this.n = opt.n; this.alpha = opt.alpha; this.beta = opt.beta; // computed this.out_sx = opt.in_sx; this.out_sy = opt.in_sy; this.out_depth = opt.in_depth; this.layer_type = 'lrn'; // checks if(this.n%2 === 0) { console.log('WARNING n should be odd for LRN layer'); } }
javascript
function(opt) { var opt = opt || {}; // required this.k = opt.k; this.n = opt.n; this.alpha = opt.alpha; this.beta = opt.beta; // computed this.out_sx = opt.in_sx; this.out_sy = opt.in_sy; this.out_depth = opt.in_depth; this.layer_type = 'lrn'; // checks if(this.n%2 === 0) { console.log('WARNING n should be odd for LRN layer'); } }
[ "function", "(", "opt", ")", "{", "var", "opt", "=", "opt", "||", "{", "}", ";", "// required", "this", ".", "k", "=", "opt", ".", "k", ";", "this", ".", "n", "=", "opt", ".", "n", ";", "this", ".", "alpha", "=", "opt", ".", "alpha", ";", "this", ".", "beta", "=", "opt", ".", "beta", ";", "// computed", "this", ".", "out_sx", "=", "opt", ".", "in_sx", ";", "this", ".", "out_sy", "=", "opt", ".", "in_sy", ";", "this", ".", "out_depth", "=", "opt", ".", "in_depth", ";", "this", ".", "layer_type", "=", "'lrn'", ";", "// checks", "if", "(", "this", ".", "n", "%", "2", "===", "0", ")", "{", "console", ".", "log", "(", "'WARNING n should be odd for LRN layer'", ")", ";", "}", "}" ]
a bit experimental layer for now. I think it works but I'm not 100% the gradient check is a bit funky. I'll look into this a bit later. Local Response Normalization in window, along depths of volumes
[ "a", "bit", "experimental", "layer", "for", "now", ".", "I", "think", "it", "works", "but", "I", "m", "not", "100%", "the", "gradient", "check", "is", "a", "bit", "funky", ".", "I", "ll", "look", "into", "this", "a", "bit", "later", ".", "Local", "Response", "Normalization", "in", "window", "along", "depths", "of", "volumes" ]
4c3358a315b4d71f31a0d532eb5d1700e9e592ee
https://github.com/karpathy/convnetjs/blob/4c3358a315b4d71f31a0d532eb5d1700e9e592ee/src/convnet_layers_normalization.js#L8-L25
5,649
karpathy/convnetjs
src/convnet_magicnet.js
function() { var N = this.data.length; var num_train = Math.floor(this.train_ratio * N); this.folds = []; // flush folds, if any for(var i=0;i<this.num_folds;i++) { var p = randperm(N); this.folds.push({train_ix: p.slice(0, num_train), test_ix: p.slice(num_train, N)}); } }
javascript
function() { var N = this.data.length; var num_train = Math.floor(this.train_ratio * N); this.folds = []; // flush folds, if any for(var i=0;i<this.num_folds;i++) { var p = randperm(N); this.folds.push({train_ix: p.slice(0, num_train), test_ix: p.slice(num_train, N)}); } }
[ "function", "(", ")", "{", "var", "N", "=", "this", ".", "data", ".", "length", ";", "var", "num_train", "=", "Math", ".", "floor", "(", "this", ".", "train_ratio", "*", "N", ")", ";", "this", ".", "folds", "=", "[", "]", ";", "// flush folds, if any", "for", "(", "var", "i", "=", "0", ";", "i", "<", "this", ".", "num_folds", ";", "i", "++", ")", "{", "var", "p", "=", "randperm", "(", "N", ")", ";", "this", ".", "folds", ".", "push", "(", "{", "train_ix", ":", "p", ".", "slice", "(", "0", ",", "num_train", ")", ",", "test_ix", ":", "p", ".", "slice", "(", "num_train", ",", "N", ")", "}", ")", ";", "}", "}" ]
sets this.folds to a sampling of this.num_folds folds
[ "sets", "this", ".", "folds", "to", "a", "sampling", "of", "this", ".", "num_folds", "folds" ]
4c3358a315b4d71f31a0d532eb5d1700e9e592ee
https://github.com/karpathy/convnetjs/blob/4c3358a315b4d71f31a0d532eb5d1700e9e592ee/src/convnet_magicnet.js#L76-L84
5,650
karpathy/convnetjs
src/convnet_magicnet.js
function() { var input_depth = this.data[0].w.length; var num_classes = this.unique_labels.length; // sample network topology and hyperparameters var layer_defs = []; layer_defs.push({type:'input', out_sx:1, out_sy:1, out_depth: input_depth}); var nl = weightedSample([0,1,2,3], [0.2, 0.3, 0.3, 0.2]); // prefer nets with 1,2 hidden layers for(var q=0;q<nl;q++) { var ni = randi(this.neurons_min, this.neurons_max); var act = ['tanh','maxout','relu'][randi(0,3)]; if(randf(0,1)<0.5) { var dp = Math.random(); layer_defs.push({type:'fc', num_neurons: ni, activation: act, drop_prob: dp}); } else { layer_defs.push({type:'fc', num_neurons: ni, activation: act}); } } layer_defs.push({type:'softmax', num_classes: num_classes}); var net = new Net(); net.makeLayers(layer_defs); // sample training hyperparameters var bs = randi(this.batch_size_min, this.batch_size_max); // batch size var l2 = Math.pow(10, randf(this.l2_decay_min, this.l2_decay_max)); // l2 weight decay var lr = Math.pow(10, randf(this.learning_rate_min, this.learning_rate_max)); // learning rate var mom = randf(this.momentum_min, this.momentum_max); // momentum. Lets just use 0.9, works okay usually ;p var tp = randf(0,1); // trainer type var trainer_def; if(tp<0.33) { trainer_def = {method:'adadelta', batch_size:bs, l2_decay:l2}; } else if(tp<0.66) { trainer_def = {method:'adagrad', learning_rate: lr, batch_size:bs, l2_decay:l2}; } else { trainer_def = {method:'sgd', learning_rate: lr, momentum: mom, batch_size:bs, l2_decay:l2}; } var trainer = new Trainer(net, trainer_def); var cand = {}; cand.acc = []; cand.accv = 0; // this will maintained as sum(acc) for convenience cand.layer_defs = layer_defs; cand.trainer_def = trainer_def; cand.net = net; cand.trainer = trainer; return cand; }
javascript
function() { var input_depth = this.data[0].w.length; var num_classes = this.unique_labels.length; // sample network topology and hyperparameters var layer_defs = []; layer_defs.push({type:'input', out_sx:1, out_sy:1, out_depth: input_depth}); var nl = weightedSample([0,1,2,3], [0.2, 0.3, 0.3, 0.2]); // prefer nets with 1,2 hidden layers for(var q=0;q<nl;q++) { var ni = randi(this.neurons_min, this.neurons_max); var act = ['tanh','maxout','relu'][randi(0,3)]; if(randf(0,1)<0.5) { var dp = Math.random(); layer_defs.push({type:'fc', num_neurons: ni, activation: act, drop_prob: dp}); } else { layer_defs.push({type:'fc', num_neurons: ni, activation: act}); } } layer_defs.push({type:'softmax', num_classes: num_classes}); var net = new Net(); net.makeLayers(layer_defs); // sample training hyperparameters var bs = randi(this.batch_size_min, this.batch_size_max); // batch size var l2 = Math.pow(10, randf(this.l2_decay_min, this.l2_decay_max)); // l2 weight decay var lr = Math.pow(10, randf(this.learning_rate_min, this.learning_rate_max)); // learning rate var mom = randf(this.momentum_min, this.momentum_max); // momentum. Lets just use 0.9, works okay usually ;p var tp = randf(0,1); // trainer type var trainer_def; if(tp<0.33) { trainer_def = {method:'adadelta', batch_size:bs, l2_decay:l2}; } else if(tp<0.66) { trainer_def = {method:'adagrad', learning_rate: lr, batch_size:bs, l2_decay:l2}; } else { trainer_def = {method:'sgd', learning_rate: lr, momentum: mom, batch_size:bs, l2_decay:l2}; } var trainer = new Trainer(net, trainer_def); var cand = {}; cand.acc = []; cand.accv = 0; // this will maintained as sum(acc) for convenience cand.layer_defs = layer_defs; cand.trainer_def = trainer_def; cand.net = net; cand.trainer = trainer; return cand; }
[ "function", "(", ")", "{", "var", "input_depth", "=", "this", ".", "data", "[", "0", "]", ".", "w", ".", "length", ";", "var", "num_classes", "=", "this", ".", "unique_labels", ".", "length", ";", "// sample network topology and hyperparameters", "var", "layer_defs", "=", "[", "]", ";", "layer_defs", ".", "push", "(", "{", "type", ":", "'input'", ",", "out_sx", ":", "1", ",", "out_sy", ":", "1", ",", "out_depth", ":", "input_depth", "}", ")", ";", "var", "nl", "=", "weightedSample", "(", "[", "0", ",", "1", ",", "2", ",", "3", "]", ",", "[", "0.2", ",", "0.3", ",", "0.3", ",", "0.2", "]", ")", ";", "// prefer nets with 1,2 hidden layers", "for", "(", "var", "q", "=", "0", ";", "q", "<", "nl", ";", "q", "++", ")", "{", "var", "ni", "=", "randi", "(", "this", ".", "neurons_min", ",", "this", ".", "neurons_max", ")", ";", "var", "act", "=", "[", "'tanh'", ",", "'maxout'", ",", "'relu'", "]", "[", "randi", "(", "0", ",", "3", ")", "]", ";", "if", "(", "randf", "(", "0", ",", "1", ")", "<", "0.5", ")", "{", "var", "dp", "=", "Math", ".", "random", "(", ")", ";", "layer_defs", ".", "push", "(", "{", "type", ":", "'fc'", ",", "num_neurons", ":", "ni", ",", "activation", ":", "act", ",", "drop_prob", ":", "dp", "}", ")", ";", "}", "else", "{", "layer_defs", ".", "push", "(", "{", "type", ":", "'fc'", ",", "num_neurons", ":", "ni", ",", "activation", ":", "act", "}", ")", ";", "}", "}", "layer_defs", ".", "push", "(", "{", "type", ":", "'softmax'", ",", "num_classes", ":", "num_classes", "}", ")", ";", "var", "net", "=", "new", "Net", "(", ")", ";", "net", ".", "makeLayers", "(", "layer_defs", ")", ";", "// sample training hyperparameters", "var", "bs", "=", "randi", "(", "this", ".", "batch_size_min", ",", "this", ".", "batch_size_max", ")", ";", "// batch size", "var", "l2", "=", "Math", ".", "pow", "(", "10", ",", "randf", "(", "this", ".", "l2_decay_min", ",", "this", ".", "l2_decay_max", ")", ")", ";", "// l2 weight decay", "var", "lr", "=", "Math", ".", "pow", "(", "10", ",", "randf", "(", "this", ".", "learning_rate_min", ",", "this", ".", "learning_rate_max", ")", ")", ";", "// learning rate", "var", "mom", "=", "randf", "(", "this", ".", "momentum_min", ",", "this", ".", "momentum_max", ")", ";", "// momentum. Lets just use 0.9, works okay usually ;p", "var", "tp", "=", "randf", "(", "0", ",", "1", ")", ";", "// trainer type", "var", "trainer_def", ";", "if", "(", "tp", "<", "0.33", ")", "{", "trainer_def", "=", "{", "method", ":", "'adadelta'", ",", "batch_size", ":", "bs", ",", "l2_decay", ":", "l2", "}", ";", "}", "else", "if", "(", "tp", "<", "0.66", ")", "{", "trainer_def", "=", "{", "method", ":", "'adagrad'", ",", "learning_rate", ":", "lr", ",", "batch_size", ":", "bs", ",", "l2_decay", ":", "l2", "}", ";", "}", "else", "{", "trainer_def", "=", "{", "method", ":", "'sgd'", ",", "learning_rate", ":", "lr", ",", "momentum", ":", "mom", ",", "batch_size", ":", "bs", ",", "l2_decay", ":", "l2", "}", ";", "}", "var", "trainer", "=", "new", "Trainer", "(", "net", ",", "trainer_def", ")", ";", "var", "cand", "=", "{", "}", ";", "cand", ".", "acc", "=", "[", "]", ";", "cand", ".", "accv", "=", "0", ";", "// this will maintained as sum(acc) for convenience", "cand", ".", "layer_defs", "=", "layer_defs", ";", "cand", ".", "trainer_def", "=", "trainer_def", ";", "cand", ".", "net", "=", "net", ";", "cand", ".", "trainer", "=", "trainer", ";", "return", "cand", ";", "}" ]
returns a random candidate network
[ "returns", "a", "random", "candidate", "network" ]
4c3358a315b4d71f31a0d532eb5d1700e9e592ee
https://github.com/karpathy/convnetjs/blob/4c3358a315b4d71f31a0d532eb5d1700e9e592ee/src/convnet_magicnet.js#L87-L134
5,651
karpathy/convnetjs
src/convnet_magicnet.js
function() { this.candidates = []; // flush, if any for(var i=0;i<this.num_candidates;i++) { var cand = this.sampleCandidate(); this.candidates.push(cand); } }
javascript
function() { this.candidates = []; // flush, if any for(var i=0;i<this.num_candidates;i++) { var cand = this.sampleCandidate(); this.candidates.push(cand); } }
[ "function", "(", ")", "{", "this", ".", "candidates", "=", "[", "]", ";", "// flush, if any", "for", "(", "var", "i", "=", "0", ";", "i", "<", "this", ".", "num_candidates", ";", "i", "++", ")", "{", "var", "cand", "=", "this", ".", "sampleCandidate", "(", ")", ";", "this", ".", "candidates", ".", "push", "(", "cand", ")", ";", "}", "}" ]
sets this.candidates with this.num_candidates candidate nets
[ "sets", "this", ".", "candidates", "with", "this", ".", "num_candidates", "candidate", "nets" ]
4c3358a315b4d71f31a0d532eb5d1700e9e592ee
https://github.com/karpathy/convnetjs/blob/4c3358a315b4d71f31a0d532eb5d1700e9e592ee/src/convnet_magicnet.js#L137-L143
5,652
karpathy/convnetjs
src/convnet_magicnet.js
function(data) { // forward prop the best networks // and accumulate probabilities at last layer into a an output Vol var eval_candidates = []; var nv = 0; if(this.evaluated_candidates.length === 0) { // not sure what to do here, first batch of nets hasnt evaluated yet // lets just predict with current candidates. nv = this.candidates.length; eval_candidates = this.candidates; } else { // forward prop the best networks from evaluated_candidates nv = Math.min(this.ensemble_size, this.evaluated_candidates.length); eval_candidates = this.evaluated_candidates } // forward nets of all candidates and average the predictions var xout, n; for(var j=0;j<nv;j++) { var net = eval_candidates[j].net; var x = net.forward(data); if(j===0) { xout = x; n = x.w.length; } else { // add it on for(var d=0;d<n;d++) { xout.w[d] += x.w[d]; } } } // produce average for(var d=0;d<n;d++) { xout.w[d] /= nv; } return xout; }
javascript
function(data) { // forward prop the best networks // and accumulate probabilities at last layer into a an output Vol var eval_candidates = []; var nv = 0; if(this.evaluated_candidates.length === 0) { // not sure what to do here, first batch of nets hasnt evaluated yet // lets just predict with current candidates. nv = this.candidates.length; eval_candidates = this.candidates; } else { // forward prop the best networks from evaluated_candidates nv = Math.min(this.ensemble_size, this.evaluated_candidates.length); eval_candidates = this.evaluated_candidates } // forward nets of all candidates and average the predictions var xout, n; for(var j=0;j<nv;j++) { var net = eval_candidates[j].net; var x = net.forward(data); if(j===0) { xout = x; n = x.w.length; } else { // add it on for(var d=0;d<n;d++) { xout.w[d] += x.w[d]; } } } // produce average for(var d=0;d<n;d++) { xout.w[d] /= nv; } return xout; }
[ "function", "(", "data", ")", "{", "// forward prop the best networks", "// and accumulate probabilities at last layer into a an output Vol", "var", "eval_candidates", "=", "[", "]", ";", "var", "nv", "=", "0", ";", "if", "(", "this", ".", "evaluated_candidates", ".", "length", "===", "0", ")", "{", "// not sure what to do here, first batch of nets hasnt evaluated yet", "// lets just predict with current candidates.", "nv", "=", "this", ".", "candidates", ".", "length", ";", "eval_candidates", "=", "this", ".", "candidates", ";", "}", "else", "{", "// forward prop the best networks from evaluated_candidates", "nv", "=", "Math", ".", "min", "(", "this", ".", "ensemble_size", ",", "this", ".", "evaluated_candidates", ".", "length", ")", ";", "eval_candidates", "=", "this", ".", "evaluated_candidates", "}", "// forward nets of all candidates and average the predictions", "var", "xout", ",", "n", ";", "for", "(", "var", "j", "=", "0", ";", "j", "<", "nv", ";", "j", "++", ")", "{", "var", "net", "=", "eval_candidates", "[", "j", "]", ".", "net", ";", "var", "x", "=", "net", ".", "forward", "(", "data", ")", ";", "if", "(", "j", "===", "0", ")", "{", "xout", "=", "x", ";", "n", "=", "x", ".", "w", ".", "length", ";", "}", "else", "{", "// add it on", "for", "(", "var", "d", "=", "0", ";", "d", "<", "n", ";", "d", "++", ")", "{", "xout", ".", "w", "[", "d", "]", "+=", "x", ".", "w", "[", "d", "]", ";", "}", "}", "}", "// produce average", "for", "(", "var", "d", "=", "0", ";", "d", "<", "n", ";", "d", "++", ")", "{", "xout", ".", "w", "[", "d", "]", "/=", "nv", ";", "}", "return", "xout", ";", "}" ]
returns prediction scores for given test data point, as Vol uses an averaged prediction from the best ensemble_size models x is a Vol.
[ "returns", "prediction", "scores", "for", "given", "test", "data", "point", "as", "Vol", "uses", "an", "averaged", "prediction", "from", "the", "best", "ensemble_size", "models", "x", "is", "a", "Vol", "." ]
4c3358a315b4d71f31a0d532eb5d1700e9e592ee
https://github.com/karpathy/convnetjs/blob/4c3358a315b4d71f31a0d532eb5d1700e9e592ee/src/convnet_magicnet.js#L238-L275
5,653
karpathy/convnetjs
demo/js/regression.js
reload
function reload() { eval($("#layerdef").val()); // refresh buttons var t = ''; for(var i=1;i<net.layers.length-1;i++) { // ignore input and regression layers (first and last) var butid = "button" + i; t += "<input id=\""+butid+"\" value=\"" + net.layers[i].layer_type +"\" type=\"submit\" onclick=\"updateLix("+i+")\" style=\"width:80px; height: 30px; margin:5px;\";>"; } $("#layer_ixes").html(t); $("#button"+lix).css('background-color', '#FFA'); }
javascript
function reload() { eval($("#layerdef").val()); // refresh buttons var t = ''; for(var i=1;i<net.layers.length-1;i++) { // ignore input and regression layers (first and last) var butid = "button" + i; t += "<input id=\""+butid+"\" value=\"" + net.layers[i].layer_type +"\" type=\"submit\" onclick=\"updateLix("+i+")\" style=\"width:80px; height: 30px; margin:5px;\";>"; } $("#layer_ixes").html(t); $("#button"+lix).css('background-color', '#FFA'); }
[ "function", "reload", "(", ")", "{", "eval", "(", "$", "(", "\"#layerdef\"", ")", ".", "val", "(", ")", ")", ";", "// refresh buttons", "var", "t", "=", "''", ";", "for", "(", "var", "i", "=", "1", ";", "i", "<", "net", ".", "layers", ".", "length", "-", "1", ";", "i", "++", ")", "{", "// ignore input and regression layers (first and last)", "var", "butid", "=", "\"button\"", "+", "i", ";", "t", "+=", "\"<input id=\\\"\"", "+", "butid", "+", "\"\\\" value=\\\"\"", "+", "net", ".", "layers", "[", "i", "]", ".", "layer_type", "+", "\"\\\" type=\\\"submit\\\" onclick=\\\"updateLix(\"", "+", "i", "+", "\")\\\" style=\\\"width:80px; height: 30px; margin:5px;\\\";>\"", ";", "}", "$", "(", "\"#layer_ixes\"", ")", ".", "html", "(", "t", ")", ";", "$", "(", "\"#button\"", "+", "lix", ")", ".", "css", "(", "'background-color'", ",", "'#FFA'", ")", ";", "}" ]
layer id of layer we'd like to draw outputs of
[ "layer", "id", "of", "layer", "we", "d", "like", "to", "draw", "outputs", "of" ]
4c3358a315b4d71f31a0d532eb5d1700e9e592ee
https://github.com/karpathy/convnetjs/blob/4c3358a315b4d71f31a0d532eb5d1700e9e592ee/demo/js/regression.js#L21-L32
5,654
apostrophecms/apostrophe
lib/modules/apostrophe-areas/lib/api.js
hardLock
function hardLock(callback) { return self.apos.locks.lock('save-area-' + docId, { waitForSelf: true }, function(err) { if (err) { return callback(err); } hardLocked = true; return callback(null); }); }
javascript
function hardLock(callback) { return self.apos.locks.lock('save-area-' + docId, { waitForSelf: true }, function(err) { if (err) { return callback(err); } hardLocked = true; return callback(null); }); }
[ "function", "hardLock", "(", "callback", ")", "{", "return", "self", ".", "apos", ".", "locks", ".", "lock", "(", "'save-area-'", "+", "docId", ",", "{", "waitForSelf", ":", "true", "}", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "return", "callback", "(", "err", ")", ";", "}", "hardLocked", "=", "true", ";", "return", "callback", "(", "null", ")", ";", "}", ")", ";", "}" ]
Also grab a hard lock on this document, just for the duration of the actual "load, sanitize stuff, and update" operation, to avoid a race condition if saving two areas around the same time, as can happen during drag and drop between areas
[ "Also", "grab", "a", "hard", "lock", "on", "this", "document", "just", "for", "the", "duration", "of", "the", "actual", "load", "sanitize", "stuff", "and", "update", "operation", "to", "avoid", "a", "race", "condition", "if", "saving", "two", "areas", "around", "the", "same", "time", "as", "can", "happen", "during", "drag", "and", "drop", "between", "areas" ]
dca702fc95492eb3f86a2ad338a3791365266064
https://github.com/apostrophecms/apostrophe/blob/dca702fc95492eb3f86a2ad338a3791365266064/lib/modules/apostrophe-areas/lib/api.js#L293-L301
5,655
apostrophecms/apostrophe
lib/modules/apostrophe-areas/lib/api.js
advisoryLock
function advisoryLock(callback) { if (!(req.htmlPageId && req.user)) { // Some consumers of this API might not participate // in advisory locking. Also, make sure we have a // valid user to minimize the risk of a DOS attack // via nuisance locking return callback(null); } return self.apos.docs.lock(req, docId, req.htmlPageId, callback); }
javascript
function advisoryLock(callback) { if (!(req.htmlPageId && req.user)) { // Some consumers of this API might not participate // in advisory locking. Also, make sure we have a // valid user to minimize the risk of a DOS attack // via nuisance locking return callback(null); } return self.apos.docs.lock(req, docId, req.htmlPageId, callback); }
[ "function", "advisoryLock", "(", "callback", ")", "{", "if", "(", "!", "(", "req", ".", "htmlPageId", "&&", "req", ".", "user", ")", ")", "{", "// Some consumers of this API might not participate", "// in advisory locking. Also, make sure we have a", "// valid user to minimize the risk of a DOS attack", "// via nuisance locking", "return", "callback", "(", "null", ")", ";", "}", "return", "self", ".", "apos", ".", "docs", ".", "lock", "(", "req", ",", "docId", ",", "req", ".", "htmlPageId", ",", "callback", ")", ";", "}" ]
Grab an advisory lock, letting other users and tabs know who is editing this right now
[ "Grab", "an", "advisory", "lock", "letting", "other", "users", "and", "tabs", "know", "who", "is", "editing", "this", "right", "now" ]
dca702fc95492eb3f86a2ad338a3791365266064
https://github.com/apostrophecms/apostrophe/blob/dca702fc95492eb3f86a2ad338a3791365266064/lib/modules/apostrophe-areas/lib/api.js#L304-L313
5,656
apostrophecms/apostrophe
lib/modules/apostrophe-assets/public/js/always.js
function(eventName, fn) { apos.handlers[eventName] = (apos.handlers[eventName] || []).concat([ fn ]); }
javascript
function(eventName, fn) { apos.handlers[eventName] = (apos.handlers[eventName] || []).concat([ fn ]); }
[ "function", "(", "eventName", ",", "fn", ")", "{", "apos", ".", "handlers", "[", "eventName", "]", "=", "(", "apos", ".", "handlers", "[", "eventName", "]", "||", "[", "]", ")", ".", "concat", "(", "[", "fn", "]", ")", ";", "}" ]
Install an Apostrophe event handler. The handler will be called when apos.emit is invoked with the same eventName. The handler will receive any additional arguments passed to apos.emit.
[ "Install", "an", "Apostrophe", "event", "handler", ".", "The", "handler", "will", "be", "called", "when", "apos", ".", "emit", "is", "invoked", "with", "the", "same", "eventName", ".", "The", "handler", "will", "receive", "any", "additional", "arguments", "passed", "to", "apos", ".", "emit", "." ]
dca702fc95492eb3f86a2ad338a3791365266064
https://github.com/apostrophecms/apostrophe/blob/dca702fc95492eb3f86a2ad338a3791365266064/lib/modules/apostrophe-assets/public/js/always.js#L42-L44
5,657
apostrophecms/apostrophe
lib/modules/apostrophe-assets/public/js/always.js
function(eventName, fn) { if (!fn) { delete apos.handlers[eventName]; return; } apos.handlers[eventName] = _.filter(apos.handlers[eventName], function(_fn) { return fn !== _fn; }); }
javascript
function(eventName, fn) { if (!fn) { delete apos.handlers[eventName]; return; } apos.handlers[eventName] = _.filter(apos.handlers[eventName], function(_fn) { return fn !== _fn; }); }
[ "function", "(", "eventName", ",", "fn", ")", "{", "if", "(", "!", "fn", ")", "{", "delete", "apos", ".", "handlers", "[", "eventName", "]", ";", "return", ";", "}", "apos", ".", "handlers", "[", "eventName", "]", "=", "_", ".", "filter", "(", "apos", ".", "handlers", "[", "eventName", "]", ",", "function", "(", "_fn", ")", "{", "return", "fn", "!==", "_fn", ";", "}", ")", ";", "}" ]
Remove an Apostrophe event handler. If fn is not supplied, all handlers for the given eventName are removed.
[ "Remove", "an", "Apostrophe", "event", "handler", ".", "If", "fn", "is", "not", "supplied", "all", "handlers", "for", "the", "given", "eventName", "are", "removed", "." ]
dca702fc95492eb3f86a2ad338a3791365266064
https://github.com/apostrophecms/apostrophe/blob/dca702fc95492eb3f86a2ad338a3791365266064/lib/modules/apostrophe-assets/public/js/always.js#L48-L56
5,658
apostrophecms/apostrophe
lib/modules/apostrophe-assets/public/js/always.js
function(type, options, alias) { if (_.has(apos.modules, type)) { // Don't double-create singletons on apos.change(), leads to doubled click events etc. return; } var module = apos.create(type, options); apos.modules[type] = module; if (alias) { apos[alias] = module; } }
javascript
function(type, options, alias) { if (_.has(apos.modules, type)) { // Don't double-create singletons on apos.change(), leads to doubled click events etc. return; } var module = apos.create(type, options); apos.modules[type] = module; if (alias) { apos[alias] = module; } }
[ "function", "(", "type", ",", "options", ",", "alias", ")", "{", "if", "(", "_", ".", "has", "(", "apos", ".", "modules", ",", "type", ")", ")", "{", "// Don't double-create singletons on apos.change(), leads to doubled click events etc.", "return", ";", "}", "var", "module", "=", "apos", ".", "create", "(", "type", ",", "options", ")", ";", "apos", ".", "modules", "[", "type", "]", "=", "module", ";", "if", "(", "alias", ")", "{", "apos", "[", "alias", "]", "=", "module", ";", "}", "}" ]
Create a singleton representing a server-side module and register it in `apos.modules`. If it has an alias register it directly on the `apos` object too.
[ "Create", "a", "singleton", "representing", "a", "server", "-", "side", "module", "and", "register", "it", "in", "apos", ".", "modules", ".", "If", "it", "has", "an", "alias", "register", "it", "directly", "on", "the", "apos", "object", "too", "." ]
dca702fc95492eb3f86a2ad338a3791365266064
https://github.com/apostrophecms/apostrophe/blob/dca702fc95492eb3f86a2ad338a3791365266064/lib/modules/apostrophe-assets/public/js/always.js#L172-L182
5,659
apostrophecms/apostrophe
lib/modules/apostrophe-assets/public/js/vendor/jquery.projector.js
findSafe
function findSafe($element, selector, ignore) { var $self = $element; return $self.find(selector).filter(function() { var $parents = $(this).parents(); var i; for (i = 0; (i < $parents.length); i++) { if ($parents[i] === $self[0]) { return true; } if ($($parents[i]).is(ignore)) { return false; } } }); }
javascript
function findSafe($element, selector, ignore) { var $self = $element; return $self.find(selector).filter(function() { var $parents = $(this).parents(); var i; for (i = 0; (i < $parents.length); i++) { if ($parents[i] === $self[0]) { return true; } if ($($parents[i]).is(ignore)) { return false; } } }); }
[ "function", "findSafe", "(", "$element", ",", "selector", ",", "ignore", ")", "{", "var", "$self", "=", "$element", ";", "return", "$self", ".", "find", "(", "selector", ")", ".", "filter", "(", "function", "(", ")", "{", "var", "$parents", "=", "$", "(", "this", ")", ".", "parents", "(", ")", ";", "var", "i", ";", "for", "(", "i", "=", "0", ";", "(", "i", "<", "$parents", ".", "length", ")", ";", "i", "++", ")", "{", "if", "(", "$parents", "[", "i", "]", "===", "$self", "[", "0", "]", ")", "{", "return", "true", ";", "}", "if", "(", "$", "(", "$parents", "[", "i", "]", ")", ".", "is", "(", "ignore", ")", ")", "{", "return", "false", ";", "}", "}", "}", ")", ";", "}" ]
use this for supporting nested projector instances
[ "use", "this", "for", "supporting", "nested", "projector", "instances" ]
dca702fc95492eb3f86a2ad338a3791365266064
https://github.com/apostrophecms/apostrophe/blob/dca702fc95492eb3f86a2ad338a3791365266064/lib/modules/apostrophe-assets/public/js/vendor/jquery.projector.js#L216-L230
5,660
apostrophecms/apostrophe
lib/modules/apostrophe-assets/public/js/vendor/jquery.scrollintoview.js
function (domElement, styles) { styles = styles || (document.defaultView && document.defaultView.getComputedStyle ? document.defaultView.getComputedStyle(domElement, null) : domElement.currentStyle); var px = document.defaultView && document.defaultView.getComputedStyle ? true : false; var b = { top: (parseFloat(px ? styles.borderTopWidth : $.css(domElement, "borderTopWidth")) || 0), left: (parseFloat(px ? styles.borderLeftWidth : $.css(domElement, "borderLeftWidth")) || 0), bottom: (parseFloat(px ? styles.borderBottomWidth : $.css(domElement, "borderBottomWidth")) || 0), right: (parseFloat(px ? styles.borderRightWidth : $.css(domElement, "borderRightWidth")) || 0) }; return { top: b.top, left: b.left, bottom: b.bottom, right: b.right, vertical: b.top + b.bottom, horizontal: b.left + b.right }; }
javascript
function (domElement, styles) { styles = styles || (document.defaultView && document.defaultView.getComputedStyle ? document.defaultView.getComputedStyle(domElement, null) : domElement.currentStyle); var px = document.defaultView && document.defaultView.getComputedStyle ? true : false; var b = { top: (parseFloat(px ? styles.borderTopWidth : $.css(domElement, "borderTopWidth")) || 0), left: (parseFloat(px ? styles.borderLeftWidth : $.css(domElement, "borderLeftWidth")) || 0), bottom: (parseFloat(px ? styles.borderBottomWidth : $.css(domElement, "borderBottomWidth")) || 0), right: (parseFloat(px ? styles.borderRightWidth : $.css(domElement, "borderRightWidth")) || 0) }; return { top: b.top, left: b.left, bottom: b.bottom, right: b.right, vertical: b.top + b.bottom, horizontal: b.left + b.right }; }
[ "function", "(", "domElement", ",", "styles", ")", "{", "styles", "=", "styles", "||", "(", "document", ".", "defaultView", "&&", "document", ".", "defaultView", ".", "getComputedStyle", "?", "document", ".", "defaultView", ".", "getComputedStyle", "(", "domElement", ",", "null", ")", ":", "domElement", ".", "currentStyle", ")", ";", "var", "px", "=", "document", ".", "defaultView", "&&", "document", ".", "defaultView", ".", "getComputedStyle", "?", "true", ":", "false", ";", "var", "b", "=", "{", "top", ":", "(", "parseFloat", "(", "px", "?", "styles", ".", "borderTopWidth", ":", "$", ".", "css", "(", "domElement", ",", "\"borderTopWidth\"", ")", ")", "||", "0", ")", ",", "left", ":", "(", "parseFloat", "(", "px", "?", "styles", ".", "borderLeftWidth", ":", "$", ".", "css", "(", "domElement", ",", "\"borderLeftWidth\"", ")", ")", "||", "0", ")", ",", "bottom", ":", "(", "parseFloat", "(", "px", "?", "styles", ".", "borderBottomWidth", ":", "$", ".", "css", "(", "domElement", ",", "\"borderBottomWidth\"", ")", ")", "||", "0", ")", ",", "right", ":", "(", "parseFloat", "(", "px", "?", "styles", ".", "borderRightWidth", ":", "$", ".", "css", "(", "domElement", ",", "\"borderRightWidth\"", ")", ")", "||", "0", ")", "}", ";", "return", "{", "top", ":", "b", ".", "top", ",", "left", ":", "b", ".", "left", ",", "bottom", ":", "b", ".", "bottom", ",", "right", ":", "b", ".", "right", ",", "vertical", ":", "b", ".", "top", "+", "b", ".", "bottom", ",", "horizontal", ":", "b", ".", "left", "+", "b", ".", "right", "}", ";", "}" ]
gets border dimensions
[ "gets", "border", "dimensions" ]
dca702fc95492eb3f86a2ad338a3791365266064
https://github.com/apostrophecms/apostrophe/blob/dca702fc95492eb3f86a2ad338a3791365266064/lib/modules/apostrophe-assets/public/js/vendor/jquery.scrollintoview.js#L29-L46
5,661
apostrophecms/apostrophe
lib/modules/apostrophe-assets/public/js/vendor/jquery.selective.js
findSafe
function findSafe($context, selector) { if (arguments.length === 1) { selector = arguments[0]; $context = self.$el; } if (!options.nestGuard) { return $context.find(selector); } return $context.find(selector).not($context.find(options.nestGuard).find(selector)); }
javascript
function findSafe($context, selector) { if (arguments.length === 1) { selector = arguments[0]; $context = self.$el; } if (!options.nestGuard) { return $context.find(selector); } return $context.find(selector).not($context.find(options.nestGuard).find(selector)); }
[ "function", "findSafe", "(", "$context", ",", "selector", ")", "{", "if", "(", "arguments", ".", "length", "===", "1", ")", "{", "selector", "=", "arguments", "[", "0", "]", ";", "$context", "=", "self", ".", "$el", ";", "}", "if", "(", "!", "options", ".", "nestGuard", ")", "{", "return", "$context", ".", "find", "(", "selector", ")", ";", "}", "return", "$context", ".", "find", "(", "selector", ")", ".", "not", "(", "$context", ".", "find", "(", "options", ".", "nestGuard", ")", ".", "find", "(", "selector", ")", ")", ";", "}" ]
Borrowed from our jquery.findSafe plugin
[ "Borrowed", "from", "our", "jquery", ".", "findSafe", "plugin" ]
dca702fc95492eb3f86a2ad338a3791365266064
https://github.com/apostrophecms/apostrophe/blob/dca702fc95492eb3f86a2ad338a3791365266064/lib/modules/apostrophe-assets/public/js/vendor/jquery.selective.js#L471-L480
5,662
apostrophecms/apostrophe
lib/modules/apostrophe-pages/lib/api.js
getChildren
function getChildren(cb) { const path = self.matchDescendants(page); self.find(req, { path: path }).sort({ path: 1 }).toArray((err, res) => { if (!err) { tree = tree.concat(res); } return cb(err, res); }); }
javascript
function getChildren(cb) { const path = self.matchDescendants(page); self.find(req, { path: path }).sort({ path: 1 }).toArray((err, res) => { if (!err) { tree = tree.concat(res); } return cb(err, res); }); }
[ "function", "getChildren", "(", "cb", ")", "{", "const", "path", "=", "self", ".", "matchDescendants", "(", "page", ")", ";", "self", ".", "find", "(", "req", ",", "{", "path", ":", "path", "}", ")", ".", "sort", "(", "{", "path", ":", "1", "}", ")", ".", "toArray", "(", "(", "err", ",", "res", ")", "=>", "{", "if", "(", "!", "err", ")", "{", "tree", "=", "tree", ".", "concat", "(", "res", ")", ";", "}", "return", "cb", "(", "err", ",", "res", ")", ";", "}", ")", ";", "}" ]
get all children of page
[ "get", "all", "children", "of", "page" ]
dca702fc95492eb3f86a2ad338a3791365266064
https://github.com/apostrophecms/apostrophe/blob/dca702fc95492eb3f86a2ad338a3791365266064/lib/modules/apostrophe-pages/lib/api.js#L687-L695
5,663
apostrophecms/apostrophe
lib/modules/apostrophe-pages/lib/api.js
trashOrUntrashPages
function trashOrUntrashPages(cb) { const ids = tree.map(p => p._id); return self.apos.docs.db.update({ _id: { $in: ids } }, action, { multi: true }, (err, res) => { cb(err); }); }
javascript
function trashOrUntrashPages(cb) { const ids = tree.map(p => p._id); return self.apos.docs.db.update({ _id: { $in: ids } }, action, { multi: true }, (err, res) => { cb(err); }); }
[ "function", "trashOrUntrashPages", "(", "cb", ")", "{", "const", "ids", "=", "tree", ".", "map", "(", "p", "=>", "p", ".", "_id", ")", ";", "return", "self", ".", "apos", ".", "docs", ".", "db", ".", "update", "(", "{", "_id", ":", "{", "$in", ":", "ids", "}", "}", ",", "action", ",", "{", "multi", ":", "true", "}", ",", "(", "err", ",", "res", ")", "=>", "{", "cb", "(", "err", ")", ";", "}", ")", ";", "}" ]
flag pages appropiately as trash or not
[ "flag", "pages", "appropiately", "as", "trash", "or", "not" ]
dca702fc95492eb3f86a2ad338a3791365266064
https://github.com/apostrophecms/apostrophe/blob/dca702fc95492eb3f86a2ad338a3791365266064/lib/modules/apostrophe-pages/lib/api.js#L698-L705
5,664
apostrophecms/apostrophe
lib/modules/apostrophe-oembed/lib/wufoo.js
function(callback) { var matches = url.match(/(\w+)\.wufoo\.com\/forms\/[\w]+-[\w-]+/); if (!matches) { return setImmediate(callback); } return request(url, function(err, response, body) { if (err) { return callback(err); } var matches = body.match(/"(https?:\/\/\w+\.wufoo\.com\/forms\/\w+)\/"/); if (matches) { url = matches[1]; } return callback(null); }); }
javascript
function(callback) { var matches = url.match(/(\w+)\.wufoo\.com\/forms\/[\w]+-[\w-]+/); if (!matches) { return setImmediate(callback); } return request(url, function(err, response, body) { if (err) { return callback(err); } var matches = body.match(/"(https?:\/\/\w+\.wufoo\.com\/forms\/\w+)\/"/); if (matches) { url = matches[1]; } return callback(null); }); }
[ "function", "(", "callback", ")", "{", "var", "matches", "=", "url", ".", "match", "(", "/", "(\\w+)\\.wufoo\\.com\\/forms\\/[\\w]+-[\\w-]+", "/", ")", ";", "if", "(", "!", "matches", ")", "{", "return", "setImmediate", "(", "callback", ")", ";", "}", "return", "request", "(", "url", ",", "function", "(", "err", ",", "response", ",", "body", ")", "{", "if", "(", "err", ")", "{", "return", "callback", "(", "err", ")", ";", "}", "var", "matches", "=", "body", ".", "match", "(", "/", "\"(https?:\\/\\/\\w+\\.wufoo\\.com\\/forms\\/\\w+)\\/\"", "/", ")", ";", "if", "(", "matches", ")", "{", "url", "=", "matches", "[", "1", "]", ";", "}", "return", "callback", "(", "null", ")", ";", "}", ")", ";", "}" ]
If they used a pretty wufoo URL, we have to fetch it and find the canonical URL in it first.
[ "If", "they", "used", "a", "pretty", "wufoo", "URL", "we", "have", "to", "fetch", "it", "and", "find", "the", "canonical", "URL", "in", "it", "first", "." ]
dca702fc95492eb3f86a2ad338a3791365266064
https://github.com/apostrophecms/apostrophe/blob/dca702fc95492eb3f86a2ad338a3791365266064/lib/modules/apostrophe-oembed/lib/wufoo.js#L12-L27
5,665
apostrophecms/apostrophe
lib/modules/apostrophe-pieces/lib/helpers.js
function(filter, choice) { var choices = []; for (var i = 0; i < filter.choices.length; i++) { choices.push({ label: filter.choices[i].label, action: filter.name, value: filterValueToChoiceValue(filter.choices[i].value, choice), default: filter.choices[i].value === filter.def }); }; return choices; }
javascript
function(filter, choice) { var choices = []; for (var i = 0; i < filter.choices.length; i++) { choices.push({ label: filter.choices[i].label, action: filter.name, value: filterValueToChoiceValue(filter.choices[i].value, choice), default: filter.choices[i].value === filter.def }); }; return choices; }
[ "function", "(", "filter", ",", "choice", ")", "{", "var", "choices", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "filter", ".", "choices", ".", "length", ";", "i", "++", ")", "{", "choices", ".", "push", "(", "{", "label", ":", "filter", ".", "choices", "[", "i", "]", ".", "label", ",", "action", ":", "filter", ".", "name", ",", "value", ":", "filterValueToChoiceValue", "(", "filter", ".", "choices", "[", "i", "]", ".", "value", ",", "choice", ")", ",", "default", ":", "filter", ".", "choices", "[", "i", "]", ".", "value", "===", "filter", ".", "def", "}", ")", ";", "}", ";", "return", "choices", ";", "}" ]
Obsolete. Translates filter data for use with Pill component
[ "Obsolete", ".", "Translates", "filter", "data", "for", "use", "with", "Pill", "component" ]
dca702fc95492eb3f86a2ad338a3791365266064
https://github.com/apostrophecms/apostrophe/blob/dca702fc95492eb3f86a2ad338a3791365266064/lib/modules/apostrophe-pieces/lib/helpers.js#L51-L62
5,666
apostrophecms/apostrophe
lib/modules/apostrophe-versions/public/js/editor.js
function(self, options) { self._id = options._id; self.body = { _id: self._id }; self.beforeShow = function(callback) { self.$el.on('click', '[data-open-changes]', function() { var $toggle = $(this); var $version = $toggle.closest('[data-version]'); var currentId = $version.attr('data-version'); var oldId = $version.attr('data-previous'); var $versionContent = $version.find('[data-changes]'); var noChanges = self.$el.find('[data-no-changes]').attr('data-no-changes'); if ($versionContent.html() !== '') { $versionContent.html(''); } else { self.html('compare', { oldId: oldId, currentId: currentId }, function(html) { if (html && html.trim() === '') { html = noChanges; } $versionContent.html(html); }); } return false; }); self.$el.on('click', '[data-apos-revert]', function() { self.api('revert', { _id: $(this).closest('[data-version]').attr('data-version') }, function(result) { if (result.status !== 'ok') { apos.notify('An error occurred.', { type: 'error', dismiss: true }); return; } self.hide(); return self.options.afterRevert(); } ); return false; }); return callback(null); }; }
javascript
function(self, options) { self._id = options._id; self.body = { _id: self._id }; self.beforeShow = function(callback) { self.$el.on('click', '[data-open-changes]', function() { var $toggle = $(this); var $version = $toggle.closest('[data-version]'); var currentId = $version.attr('data-version'); var oldId = $version.attr('data-previous'); var $versionContent = $version.find('[data-changes]'); var noChanges = self.$el.find('[data-no-changes]').attr('data-no-changes'); if ($versionContent.html() !== '') { $versionContent.html(''); } else { self.html('compare', { oldId: oldId, currentId: currentId }, function(html) { if (html && html.trim() === '') { html = noChanges; } $versionContent.html(html); }); } return false; }); self.$el.on('click', '[data-apos-revert]', function() { self.api('revert', { _id: $(this).closest('[data-version]').attr('data-version') }, function(result) { if (result.status !== 'ok') { apos.notify('An error occurred.', { type: 'error', dismiss: true }); return; } self.hide(); return self.options.afterRevert(); } ); return false; }); return callback(null); }; }
[ "function", "(", "self", ",", "options", ")", "{", "self", ".", "_id", "=", "options", ".", "_id", ";", "self", ".", "body", "=", "{", "_id", ":", "self", ".", "_id", "}", ";", "self", ".", "beforeShow", "=", "function", "(", "callback", ")", "{", "self", ".", "$el", ".", "on", "(", "'click'", ",", "'[data-open-changes]'", ",", "function", "(", ")", "{", "var", "$toggle", "=", "$", "(", "this", ")", ";", "var", "$version", "=", "$toggle", ".", "closest", "(", "'[data-version]'", ")", ";", "var", "currentId", "=", "$version", ".", "attr", "(", "'data-version'", ")", ";", "var", "oldId", "=", "$version", ".", "attr", "(", "'data-previous'", ")", ";", "var", "$versionContent", "=", "$version", ".", "find", "(", "'[data-changes]'", ")", ";", "var", "noChanges", "=", "self", ".", "$el", ".", "find", "(", "'[data-no-changes]'", ")", ".", "attr", "(", "'data-no-changes'", ")", ";", "if", "(", "$versionContent", ".", "html", "(", ")", "!==", "''", ")", "{", "$versionContent", ".", "html", "(", "''", ")", ";", "}", "else", "{", "self", ".", "html", "(", "'compare'", ",", "{", "oldId", ":", "oldId", ",", "currentId", ":", "currentId", "}", ",", "function", "(", "html", ")", "{", "if", "(", "html", "&&", "html", ".", "trim", "(", ")", "===", "''", ")", "{", "html", "=", "noChanges", ";", "}", "$versionContent", ".", "html", "(", "html", ")", ";", "}", ")", ";", "}", "return", "false", ";", "}", ")", ";", "self", ".", "$el", ".", "on", "(", "'click'", ",", "'[data-apos-revert]'", ",", "function", "(", ")", "{", "self", ".", "api", "(", "'revert'", ",", "{", "_id", ":", "$", "(", "this", ")", ".", "closest", "(", "'[data-version]'", ")", ".", "attr", "(", "'data-version'", ")", "}", ",", "function", "(", "result", ")", "{", "if", "(", "result", ".", "status", "!==", "'ok'", ")", "{", "apos", ".", "notify", "(", "'An error occurred.'", ",", "{", "type", ":", "'error'", ",", "dismiss", ":", "true", "}", ")", ";", "return", ";", "}", "self", ".", "hide", "(", ")", ";", "return", "self", ".", "options", ".", "afterRevert", "(", ")", ";", "}", ")", ";", "return", "false", ";", "}", ")", ";", "return", "callback", "(", "null", ")", ";", "}", ";", "}" ]
Requires document id as the _id option
[ "Requires", "document", "id", "as", "the", "_id", "option" ]
dca702fc95492eb3f86a2ad338a3791365266064
https://github.com/apostrophecms/apostrophe/blob/dca702fc95492eb3f86a2ad338a3791365266064/lib/modules/apostrophe-versions/public/js/editor.js#L9-L53
5,667
apostrophecms/apostrophe
lib/modules/apostrophe-assets/index.js
function(pathname, css, req, next) { if (!self.options.bless) { fs.writeFileSync(pathname, css); return next(); } self.splitWithBless(pathname, css); return next(); }
javascript
function(pathname, css, req, next) { if (!self.options.bless) { fs.writeFileSync(pathname, css); return next(); } self.splitWithBless(pathname, css); return next(); }
[ "function", "(", "pathname", ",", "css", ",", "req", ",", "next", ")", "{", "if", "(", "!", "self", ".", "options", ".", "bless", ")", "{", "fs", ".", "writeFileSync", "(", "pathname", ",", "css", ")", ";", "return", "next", "(", ")", ";", "}", "self", ".", "splitWithBless", "(", "pathname", ",", "css", ")", ";", "return", "next", "(", ")", ";", "}" ]
If requested, use BLESS to split CSS into multiple files for <=IE9, but only if there's enough to make it necessary
[ "If", "requested", "use", "BLESS", "to", "split", "CSS", "into", "multiple", "files", "for", "<", "=", "IE9", "but", "only", "if", "there", "s", "enough", "to", "make", "it", "necessary" ]
dca702fc95492eb3f86a2ad338a3791365266064
https://github.com/apostrophecms/apostrophe/blob/dca702fc95492eb3f86a2ad338a3791365266064/lib/modules/apostrophe-assets/index.js#L1314-L1321
5,668
apostrophecms/apostrophe
lib/modules/apostrophe-utils/lib/helpers.js
function(list, property) { if (_.isArray(list)) { return _.some(list, function(item) { return _.has(item, property); }); } else { return _.has(list, property); } }
javascript
function(list, property) { if (_.isArray(list)) { return _.some(list, function(item) { return _.has(item, property); }); } else { return _.has(list, property); } }
[ "function", "(", "list", ",", "property", ")", "{", "if", "(", "_", ".", "isArray", "(", "list", ")", ")", "{", "return", "_", ".", "some", "(", "list", ",", "function", "(", "item", ")", "{", "return", "_", ".", "has", "(", "item", ",", "property", ")", ";", "}", ")", ";", "}", "else", "{", "return", "_", ".", "has", "(", "list", ",", "property", ")", ";", "}", "}" ]
The first parameter may also be a single object, in which case this function returns true if that object has the named property.
[ "The", "first", "parameter", "may", "also", "be", "a", "single", "object", "in", "which", "case", "this", "function", "returns", "true", "if", "that", "object", "has", "the", "named", "property", "." ]
dca702fc95492eb3f86a2ad338a3791365266064
https://github.com/apostrophecms/apostrophe/blob/dca702fc95492eb3f86a2ad338a3791365266064/lib/modules/apostrophe-utils/lib/helpers.js#L93-L99
5,669
apostrophecms/apostrophe
lib/modules/apostrophe-utils/lib/helpers.js
function(list, value) { if (_.isArray(list)) { for (var i = 0; i < list.length; i++) { var listItem = list[i]; if (listItem.indexOf(value) === 0) { return true; } } } else { if (list.indexOf(value) === 0) { return true; } } return false; }
javascript
function(list, value) { if (_.isArray(list)) { for (var i = 0; i < list.length; i++) { var listItem = list[i]; if (listItem.indexOf(value) === 0) { return true; } } } else { if (list.indexOf(value) === 0) { return true; } } return false; }
[ "function", "(", "list", ",", "value", ")", "{", "if", "(", "_", ".", "isArray", "(", "list", ")", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "list", ".", "length", ";", "i", "++", ")", "{", "var", "listItem", "=", "list", "[", "i", "]", ";", "if", "(", "listItem", ".", "indexOf", "(", "value", ")", "===", "0", ")", "{", "return", "true", ";", "}", "}", "}", "else", "{", "if", "(", "list", ".", "indexOf", "(", "value", ")", "===", "0", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
If the `list` argument is a string, returns true if it begins with `value`. If the `list` argument is an array, returns true if at least one of its elements begins with `value`.
[ "If", "the", "list", "argument", "is", "a", "string", "returns", "true", "if", "it", "begins", "with", "value", ".", "If", "the", "list", "argument", "is", "an", "array", "returns", "true", "if", "at", "least", "one", "of", "its", "elements", "begins", "with", "value", "." ]
dca702fc95492eb3f86a2ad338a3791365266064
https://github.com/apostrophecms/apostrophe/blob/dca702fc95492eb3f86a2ad338a3791365266064/lib/modules/apostrophe-utils/lib/helpers.js#L110-L124
5,670
apostrophecms/apostrophe
lib/modules/apostrophe-utils/lib/helpers.js
function(arr, property, value) { return _.find(arr, function(item) { return (item[property] === value); }); }
javascript
function(arr, property, value) { return _.find(arr, function(item) { return (item[property] === value); }); }
[ "function", "(", "arr", ",", "property", ",", "value", ")", "{", "return", "_", ".", "find", "(", "arr", ",", "function", "(", "item", ")", "{", "return", "(", "item", "[", "property", "]", "===", "value", ")", ";", "}", ")", ";", "}" ]
Find the first array element, if any, that has the specified value for the specified property.
[ "Find", "the", "first", "array", "element", "if", "any", "that", "has", "the", "specified", "value", "for", "the", "specified", "property", "." ]
dca702fc95492eb3f86a2ad338a3791365266064
https://github.com/apostrophecms/apostrophe/blob/dca702fc95492eb3f86a2ad338a3791365266064/lib/modules/apostrophe-utils/lib/helpers.js#L129-L133
5,671
apostrophecms/apostrophe
lib/modules/apostrophe-utils/lib/helpers.js
function(arr, property, value) { return _.filter(arr, function(item) { return (item[property] === value); }); }
javascript
function(arr, property, value) { return _.filter(arr, function(item) { return (item[property] === value); }); }
[ "function", "(", "arr", ",", "property", ",", "value", ")", "{", "return", "_", ".", "filter", "(", "arr", ",", "function", "(", "item", ")", "{", "return", "(", "item", "[", "property", "]", "===", "value", ")", ";", "}", ")", ";", "}" ]
Find all the array elements, if any, that have the specified value for the specified property.
[ "Find", "all", "the", "array", "elements", "if", "any", "that", "have", "the", "specified", "value", "for", "the", "specified", "property", "." ]
dca702fc95492eb3f86a2ad338a3791365266064
https://github.com/apostrophecms/apostrophe/blob/dca702fc95492eb3f86a2ad338a3791365266064/lib/modules/apostrophe-utils/lib/helpers.js#L147-L151
5,672
apostrophecms/apostrophe
lib/modules/apostrophe-utils/lib/helpers.js
function(arr, property, value) { return _.reject(arr, function(item) { return (item[property] === value); }); }
javascript
function(arr, property, value) { return _.reject(arr, function(item) { return (item[property] === value); }); }
[ "function", "(", "arr", ",", "property", ",", "value", ")", "{", "return", "_", ".", "reject", "(", "arr", ",", "function", "(", "item", ")", "{", "return", "(", "item", "[", "property", "]", "===", "value", ")", ";", "}", ")", ";", "}" ]
Reject array elements that have the specified value for the specified property.
[ "Reject", "array", "elements", "that", "have", "the", "specified", "value", "for", "the", "specified", "property", "." ]
dca702fc95492eb3f86a2ad338a3791365266064
https://github.com/apostrophecms/apostrophe/blob/dca702fc95492eb3f86a2ad338a3791365266064/lib/modules/apostrophe-utils/lib/helpers.js#L156-L160
5,673
apostrophecms/apostrophe
lib/modules/apostrophe-utils/lib/helpers.js
function(array, without, property) { return _.filter(Array.isArray(array) ? array : [], function(item) { return !_.find(without || [], function(other) { if (property) { return _.isEqual(item[property], other); } else { return _.isEqual(item, other); } }); }); }
javascript
function(array, without, property) { return _.filter(Array.isArray(array) ? array : [], function(item) { return !_.find(without || [], function(other) { if (property) { return _.isEqual(item[property], other); } else { return _.isEqual(item, other); } }); }); }
[ "function", "(", "array", ",", "without", ",", "property", ")", "{", "return", "_", ".", "filter", "(", "Array", ".", "isArray", "(", "array", ")", "?", "array", ":", "[", "]", ",", "function", "(", "item", ")", "{", "return", "!", "_", ".", "find", "(", "without", "||", "[", "]", ",", "function", "(", "other", ")", "{", "if", "(", "property", ")", "{", "return", "_", ".", "isEqual", "(", "item", "[", "property", "]", ",", "other", ")", ";", "}", "else", "{", "return", "_", ".", "isEqual", "(", "item", ",", "other", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
Given the arrays `array` and `without`, return only the elements of `array` that do not occur in `without`. If `without` is not an array it is treated as an empty array. If `property` is present, then that property of each element of array is compared to elements of `without`. This is useful when `array` contains full-blown choices with a `value` property, while `without `just contains actual values. A deep comparison is performed with `_.isEqual`.
[ "Given", "the", "arrays", "array", "and", "without", "return", "only", "the", "elements", "of", "array", "that", "do", "not", "occur", "in", "without", ".", "If", "without", "is", "not", "an", "array", "it", "is", "treated", "as", "an", "empty", "array", ".", "If", "property", "is", "present", "then", "that", "property", "of", "each", "element", "of", "array", "is", "compared", "to", "elements", "of", "without", ".", "This", "is", "useful", "when", "array", "contains", "full", "-", "blown", "choices", "with", "a", "value", "property", "while", "without", "just", "contains", "actual", "values", ".", "A", "deep", "comparison", "is", "performed", "with", "_", ".", "isEqual", "." ]
dca702fc95492eb3f86a2ad338a3791365266064
https://github.com/apostrophecms/apostrophe/blob/dca702fc95492eb3f86a2ad338a3791365266064/lib/modules/apostrophe-utils/lib/helpers.js#L216-L226
5,674
apostrophecms/apostrophe
lib/modules/apostrophe-utils/lib/helpers.js
function() { var result = {}; var i; for (i = 0; (i < arguments.length); i++) { if (!arguments[i]) { continue; } result = _.merge(result, arguments[i]); } return result; }
javascript
function() { var result = {}; var i; for (i = 0; (i < arguments.length); i++) { if (!arguments[i]) { continue; } result = _.merge(result, arguments[i]); } return result; }
[ "function", "(", ")", "{", "var", "result", "=", "{", "}", ";", "var", "i", ";", "for", "(", "i", "=", "0", ";", "(", "i", "<", "arguments", ".", "length", ")", ";", "i", "++", ")", "{", "if", "(", "!", "arguments", "[", "i", "]", ")", "{", "continue", ";", "}", "result", "=", "_", ".", "merge", "(", "result", ",", "arguments", "[", "i", "]", ")", ";", "}", "return", "result", ";", "}" ]
Pass as many objects as you want; they will get merged via `_.merge` into a new object, without modifying any of them, and the resulting object will be returned. If several objects have a property, the last object wins. This is useful to add one more option to an options object which was passed to you. If any argument is null, it is skipped gracefully. This allows you to pass in an options object without checking if it is null.
[ "Pass", "as", "many", "objects", "as", "you", "want", ";", "they", "will", "get", "merged", "via", "_", ".", "merge", "into", "a", "new", "object", "without", "modifying", "any", "of", "them", "and", "the", "resulting", "object", "will", "be", "returned", ".", "If", "several", "objects", "have", "a", "property", "the", "last", "object", "wins", ".", "This", "is", "useful", "to", "add", "one", "more", "option", "to", "an", "options", "object", "which", "was", "passed", "to", "you", ".", "If", "any", "argument", "is", "null", "it", "is", "skipped", "gracefully", ".", "This", "allows", "you", "to", "pass", "in", "an", "options", "object", "without", "checking", "if", "it", "is", "null", "." ]
dca702fc95492eb3f86a2ad338a3791365266064
https://github.com/apostrophecms/apostrophe/blob/dca702fc95492eb3f86a2ad338a3791365266064/lib/modules/apostrophe-utils/lib/helpers.js#L302-L312
5,675
apostrophecms/apostrophe
lib/modules/apostrophe-areas/public/js/splitHtml.js
cleanup
function cleanup(html) { html = cheerio.load(html); html('[' + ignoreAttr + ']').removeAttr(ignoreAttr); html = html.html(); return html; }
javascript
function cleanup(html) { html = cheerio.load(html); html('[' + ignoreAttr + ']').removeAttr(ignoreAttr); html = html.html(); return html; }
[ "function", "cleanup", "(", "html", ")", "{", "html", "=", "cheerio", ".", "load", "(", "html", ")", ";", "html", "(", "'['", "+", "ignoreAttr", "+", "']'", ")", ".", "removeAttr", "(", "ignoreAttr", ")", ";", "html", "=", "html", ".", "html", "(", ")", ";", "return", "html", ";", "}" ]
Use Cheerio to strip out any attributes we used to keep track of our work, then generate new HTML. This also closes any tags we opened but did not close.
[ "Use", "Cheerio", "to", "strip", "out", "any", "attributes", "we", "used", "to", "keep", "track", "of", "our", "work", "then", "generate", "new", "HTML", ".", "This", "also", "closes", "any", "tags", "we", "opened", "but", "did", "not", "close", "." ]
dca702fc95492eb3f86a2ad338a3791365266064
https://github.com/apostrophecms/apostrophe/blob/dca702fc95492eb3f86a2ad338a3791365266064/lib/modules/apostrophe-areas/public/js/splitHtml.js#L128-L133
5,676
apostrophecms/apostrophe
lib/modules/apostrophe-pager/index.js
function(options) { var pages = []; var fromPage = options.page - 2; if (fromPage < 2) { fromPage = 2; } for (var page = fromPage; (page < (fromPage + options.shown)); page++) { pages.push(page); } return pages; }
javascript
function(options) { var pages = []; var fromPage = options.page - 2; if (fromPage < 2) { fromPage = 2; } for (var page = fromPage; (page < (fromPage + options.shown)); page++) { pages.push(page); } return pages; }
[ "function", "(", "options", ")", "{", "var", "pages", "=", "[", "]", ";", "var", "fromPage", "=", "options", ".", "page", "-", "2", ";", "if", "(", "fromPage", "<", "2", ")", "{", "fromPage", "=", "2", ";", "}", "for", "(", "var", "page", "=", "fromPage", ";", "(", "page", "<", "(", "fromPage", "+", "options", ".", "shown", ")", ")", ";", "page", "++", ")", "{", "pages", ".", "push", "(", "page", ")", ";", "}", "return", "pages", ";", "}" ]
Generate the right range of page numbers to display in the pager. Just a little too much math to be comfortable in pure Nunjucks
[ "Generate", "the", "right", "range", "of", "page", "numbers", "to", "display", "in", "the", "pager", ".", "Just", "a", "little", "too", "much", "math", "to", "be", "comfortable", "in", "pure", "Nunjucks" ]
dca702fc95492eb3f86a2ad338a3791365266064
https://github.com/apostrophecms/apostrophe/blob/dca702fc95492eb3f86a2ad338a3791365266064/lib/modules/apostrophe-pager/index.js#L11-L21
5,677
apostrophecms/apostrophe
lib/modules/apostrophe-utils/lib/logger.js
function(msg) { // eslint-disable-next-line no-console if (console.debug) { // eslint-disable-next-line no-console console.debug.apply(console, arguments); } else { // eslint-disable-next-line no-console console.log.apply(console, arguments); } }
javascript
function(msg) { // eslint-disable-next-line no-console if (console.debug) { // eslint-disable-next-line no-console console.debug.apply(console, arguments); } else { // eslint-disable-next-line no-console console.log.apply(console, arguments); } }
[ "function", "(", "msg", ")", "{", "// eslint-disable-next-line no-console", "if", "(", "console", ".", "debug", ")", "{", "// eslint-disable-next-line no-console", "console", ".", "debug", ".", "apply", "(", "console", ",", "arguments", ")", ";", "}", "else", "{", "// eslint-disable-next-line no-console", "console", ".", "log", ".", "apply", "(", "console", ",", "arguments", ")", ";", "}", "}" ]
Log a debug message. Invokes `console.debug` if available, otherwise `console.log`. Overrides should be written with support for substitution strings in mind. See the `console.log` documentation.
[ "Log", "a", "debug", "message", ".", "Invokes", "console", ".", "debug", "if", "available", "otherwise", "console", ".", "log", ".", "Overrides", "should", "be", "written", "with", "support", "for", "substitution", "strings", "in", "mind", ".", "See", "the", "console", ".", "log", "documentation", "." ]
dca702fc95492eb3f86a2ad338a3791365266064
https://github.com/apostrophecms/apostrophe/blob/dca702fc95492eb3f86a2ad338a3791365266064/lib/modules/apostrophe-utils/lib/logger.js#L38-L47
5,678
apostrophecms/apostrophe
lib/modules/apostrophe-attachments/lib/tasks/rescale.js
function(callback) { async.forEachSeries(file.crops || [], function(crop, callback) { console.log('RECROPPING'); var originalFile = '/attachments/' + file._id + '-' + file.name + '.' + crop.left + '.' + crop.top + '.' + crop.width + '.' + crop.height + '.' + file.extension; console.log("Cropping " + tempFile + " to " + originalFile); return self.uploadfs.copyImageIn(tempFile, originalFile, { crop: crop }, function(err) { if (err) { console.error('WARNING: problem copying image back into uploadfs:'); console.error(err); return fileCallback(null); } return callback(null); }); }, callback); }
javascript
function(callback) { async.forEachSeries(file.crops || [], function(crop, callback) { console.log('RECROPPING'); var originalFile = '/attachments/' + file._id + '-' + file.name + '.' + crop.left + '.' + crop.top + '.' + crop.width + '.' + crop.height + '.' + file.extension; console.log("Cropping " + tempFile + " to " + originalFile); return self.uploadfs.copyImageIn(tempFile, originalFile, { crop: crop }, function(err) { if (err) { console.error('WARNING: problem copying image back into uploadfs:'); console.error(err); return fileCallback(null); } return callback(null); }); }, callback); }
[ "function", "(", "callback", ")", "{", "async", ".", "forEachSeries", "(", "file", ".", "crops", "||", "[", "]", ",", "function", "(", "crop", ",", "callback", ")", "{", "console", ".", "log", "(", "'RECROPPING'", ")", ";", "var", "originalFile", "=", "'/attachments/'", "+", "file", ".", "_id", "+", "'-'", "+", "file", ".", "name", "+", "'.'", "+", "crop", ".", "left", "+", "'.'", "+", "crop", ".", "top", "+", "'.'", "+", "crop", ".", "width", "+", "'.'", "+", "crop", ".", "height", "+", "'.'", "+", "file", ".", "extension", ";", "console", ".", "log", "(", "\"Cropping \"", "+", "tempFile", "+", "\" to \"", "+", "originalFile", ")", ";", "return", "self", ".", "uploadfs", ".", "copyImageIn", "(", "tempFile", ",", "originalFile", ",", "{", "crop", ":", "crop", "}", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "console", ".", "error", "(", "'WARNING: problem copying image back into uploadfs:'", ")", ";", "console", ".", "error", "(", "err", ")", ";", "return", "fileCallback", "(", "null", ")", ";", "}", "return", "callback", "(", "null", ")", ";", "}", ")", ";", "}", ",", "callback", ")", ";", "}" ]
Don't forget to recrop as well!
[ "Don", "t", "forget", "to", "recrop", "as", "well!" ]
dca702fc95492eb3f86a2ad338a3791365266064
https://github.com/apostrophecms/apostrophe/blob/dca702fc95492eb3f86a2ad338a3791365266064/lib/modules/apostrophe-attachments/lib/tasks/rescale.js#L87-L101
5,679
apostrophecms/apostrophe
lib/modules/apostrophe-modal/public/js/modal.js
function() { return $(apos.modalSupport.stack.length ? apos.modalSupport.stack[apos.modalSupport.stack.length - 1] : 'body'); }
javascript
function() { return $(apos.modalSupport.stack.length ? apos.modalSupport.stack[apos.modalSupport.stack.length - 1] : 'body'); }
[ "function", "(", ")", "{", "return", "$", "(", "apos", ".", "modalSupport", ".", "stack", ".", "length", "?", "apos", ".", "modalSupport", ".", "stack", "[", "apos", ".", "modalSupport", ".", "stack", ".", "length", "-", "1", "]", ":", "'body'", ")", ";", "}" ]
Returns jQuery object
[ "Returns", "jQuery", "object" ]
dca702fc95492eb3f86a2ad338a3791365266064
https://github.com/apostrophecms/apostrophe/blob/dca702fc95492eb3f86a2ad338a3791365266064/lib/modules/apostrophe-modal/public/js/modal.js#L1046-L1048
5,680
apostrophecms/apostrophe
lib/modules/apostrophe-assets/public/js/vendor/lodash.js
baseGet
function baseGet(object, path, pathKey) { if (object == null) { return; } object = toObject(object); if (pathKey !== undefined && pathKey in object) { path = [pathKey]; } var index = 0, length = path.length; while (object != null && index < length) { object = toObject(object)[path[index++]]; } return (index && index == length) ? object : undefined; }
javascript
function baseGet(object, path, pathKey) { if (object == null) { return; } object = toObject(object); if (pathKey !== undefined && pathKey in object) { path = [pathKey]; } var index = 0, length = path.length; while (object != null && index < length) { object = toObject(object)[path[index++]]; } return (index && index == length) ? object : undefined; }
[ "function", "baseGet", "(", "object", ",", "path", ",", "pathKey", ")", "{", "if", "(", "object", "==", "null", ")", "{", "return", ";", "}", "object", "=", "toObject", "(", "object", ")", ";", "if", "(", "pathKey", "!==", "undefined", "&&", "pathKey", "in", "object", ")", "{", "path", "=", "[", "pathKey", "]", ";", "}", "var", "index", "=", "0", ",", "length", "=", "path", ".", "length", ";", "while", "(", "object", "!=", "null", "&&", "index", "<", "length", ")", "{", "object", "=", "toObject", "(", "object", ")", "[", "path", "[", "index", "++", "]", "]", ";", "}", "return", "(", "index", "&&", "index", "==", "length", ")", "?", "object", ":", "undefined", ";", "}" ]
The base implementation of `get` without support for string paths and default values. @private @param {Object} object The object to query. @param {Array} path The path of the property to get. @param {string} [pathKey] The key representation of path. @returns {*} Returns the resolved value.
[ "The", "base", "implementation", "of", "get", "without", "support", "for", "string", "paths", "and", "default", "values", "." ]
dca702fc95492eb3f86a2ad338a3791365266064
https://github.com/apostrophecms/apostrophe/blob/dca702fc95492eb3f86a2ad338a3791365266064/lib/modules/apostrophe-assets/public/js/vendor/lodash.js#L2273-L2288
5,681
apostrophecms/apostrophe
lib/modules/apostrophe-assets/public/js/vendor/lodash.js
toIterable
function toIterable(value) { if (value == null) { return []; } if (!isArrayLike(value)) { return values(value); } if (lodash.support.unindexedChars && isString(value)) { return value.split(''); } return isObject(value) ? value : Object(value); }
javascript
function toIterable(value) { if (value == null) { return []; } if (!isArrayLike(value)) { return values(value); } if (lodash.support.unindexedChars && isString(value)) { return value.split(''); } return isObject(value) ? value : Object(value); }
[ "function", "toIterable", "(", "value", ")", "{", "if", "(", "value", "==", "null", ")", "{", "return", "[", "]", ";", "}", "if", "(", "!", "isArrayLike", "(", "value", ")", ")", "{", "return", "values", "(", "value", ")", ";", "}", "if", "(", "lodash", ".", "support", ".", "unindexedChars", "&&", "isString", "(", "value", ")", ")", "{", "return", "value", ".", "split", "(", "''", ")", ";", "}", "return", "isObject", "(", "value", ")", "?", "value", ":", "Object", "(", "value", ")", ";", "}" ]
Converts `value` to an array-like object if it's not one. @private @param {*} value The value to process. @returns {Array|Object} Returns the array-like object.
[ "Converts", "value", "to", "an", "array", "-", "like", "object", "if", "it", "s", "not", "one", "." ]
dca702fc95492eb3f86a2ad338a3791365266064
https://github.com/apostrophecms/apostrophe/blob/dca702fc95492eb3f86a2ad338a3791365266064/lib/modules/apostrophe-assets/public/js/vendor/lodash.js#L4581-L4592
5,682
apostrophecms/apostrophe
lib/modules/apostrophe-assets/public/js/vendor/lodash.js
toObject
function toObject(value) { if (lodash.support.unindexedChars && isString(value)) { var index = -1, length = value.length, result = Object(value); while (++index < length) { result[index] = value.charAt(index); } return result; } return isObject(value) ? value : Object(value); }
javascript
function toObject(value) { if (lodash.support.unindexedChars && isString(value)) { var index = -1, length = value.length, result = Object(value); while (++index < length) { result[index] = value.charAt(index); } return result; } return isObject(value) ? value : Object(value); }
[ "function", "toObject", "(", "value", ")", "{", "if", "(", "lodash", ".", "support", ".", "unindexedChars", "&&", "isString", "(", "value", ")", ")", "{", "var", "index", "=", "-", "1", ",", "length", "=", "value", ".", "length", ",", "result", "=", "Object", "(", "value", ")", ";", "while", "(", "++", "index", "<", "length", ")", "{", "result", "[", "index", "]", "=", "value", ".", "charAt", "(", "index", ")", ";", "}", "return", "result", ";", "}", "return", "isObject", "(", "value", ")", "?", "value", ":", "Object", "(", "value", ")", ";", "}" ]
Converts `value` to an object if it's not one. @private @param {*} value The value to process. @returns {Object} Returns the object.
[ "Converts", "value", "to", "an", "object", "if", "it", "s", "not", "one", "." ]
dca702fc95492eb3f86a2ad338a3791365266064
https://github.com/apostrophecms/apostrophe/blob/dca702fc95492eb3f86a2ad338a3791365266064/lib/modules/apostrophe-assets/public/js/vendor/lodash.js#L4601-L4613
5,683
apostrophecms/apostrophe
lib/modules/apostrophe-assets/public/js/vendor/lodash.js
has
function has(object, path) { if (object == null) { return false; } var result = hasOwnProperty.call(object, path); if (!result && !isKey(path)) { path = toPath(path); object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1)); if (object == null) { return false; } path = last(path); result = hasOwnProperty.call(object, path); } return result || (isLength(object.length) && isIndex(path, object.length) && (isArray(object) || isArguments(object) || isString(object))); }
javascript
function has(object, path) { if (object == null) { return false; } var result = hasOwnProperty.call(object, path); if (!result && !isKey(path)) { path = toPath(path); object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1)); if (object == null) { return false; } path = last(path); result = hasOwnProperty.call(object, path); } return result || (isLength(object.length) && isIndex(path, object.length) && (isArray(object) || isArguments(object) || isString(object))); }
[ "function", "has", "(", "object", ",", "path", ")", "{", "if", "(", "object", "==", "null", ")", "{", "return", "false", ";", "}", "var", "result", "=", "hasOwnProperty", ".", "call", "(", "object", ",", "path", ")", ";", "if", "(", "!", "result", "&&", "!", "isKey", "(", "path", ")", ")", "{", "path", "=", "toPath", "(", "path", ")", ";", "object", "=", "path", ".", "length", "==", "1", "?", "object", ":", "baseGet", "(", "object", ",", "baseSlice", "(", "path", ",", "0", ",", "-", "1", ")", ")", ";", "if", "(", "object", "==", "null", ")", "{", "return", "false", ";", "}", "path", "=", "last", "(", "path", ")", ";", "result", "=", "hasOwnProperty", ".", "call", "(", "object", ",", "path", ")", ";", "}", "return", "result", "||", "(", "isLength", "(", "object", ".", "length", ")", "&&", "isIndex", "(", "path", ",", "object", ".", "length", ")", "&&", "(", "isArray", "(", "object", ")", "||", "isArguments", "(", "object", ")", "||", "isString", "(", "object", ")", ")", ")", ";", "}" ]
Checks if `path` is a direct property. @static @memberOf _ @category Object @param {Object} object The object to query. @param {Array|string} path The path to check. @returns {boolean} Returns `true` if `path` is a direct property, else `false`. @example var object = { 'a': { 'b': { 'c': 3 } } }; _.has(object, 'a'); // => true _.has(object, 'a.b.c'); // => true _.has(object, ['a', 'b', 'c']); // => true
[ "Checks", "if", "path", "is", "a", "direct", "property", "." ]
dca702fc95492eb3f86a2ad338a3791365266064
https://github.com/apostrophecms/apostrophe/blob/dca702fc95492eb3f86a2ad338a3791365266064/lib/modules/apostrophe-assets/public/js/vendor/lodash.js#L9802-L9818
5,684
apostrophecms/apostrophe
lib/modules/apostrophe-areas/lib/helpers.js
function(widget, options) { var manager = self.getWidgetManager(widget.type); if (!manager) { // Not configured in this project self.warnMissingWidgetType(widget.type); return ''; } var partial; if (!manager.options.wrapperTemplate) { partial = _.partial(self.partial, 'widget'); } else { partial = _.partial(manager.partial, manager.options.wrapperTemplate); } return partial({ // The widget minus any properties that don't // absolutely need to be crammed into a JSON // attribute for the editor's benefit. Good filtering // here prevents megabytes of markup. -Tom and Sam dataFiltered: manager.filterForDataAttribute(widget), manager: manager, widget: widget, options: options, output: function() { return manager.output(widget, options); } }); }
javascript
function(widget, options) { var manager = self.getWidgetManager(widget.type); if (!manager) { // Not configured in this project self.warnMissingWidgetType(widget.type); return ''; } var partial; if (!manager.options.wrapperTemplate) { partial = _.partial(self.partial, 'widget'); } else { partial = _.partial(manager.partial, manager.options.wrapperTemplate); } return partial({ // The widget minus any properties that don't // absolutely need to be crammed into a JSON // attribute for the editor's benefit. Good filtering // here prevents megabytes of markup. -Tom and Sam dataFiltered: manager.filterForDataAttribute(widget), manager: manager, widget: widget, options: options, output: function() { return manager.output(widget, options); } }); }
[ "function", "(", "widget", ",", "options", ")", "{", "var", "manager", "=", "self", ".", "getWidgetManager", "(", "widget", ".", "type", ")", ";", "if", "(", "!", "manager", ")", "{", "// Not configured in this project", "self", ".", "warnMissingWidgetType", "(", "widget", ".", "type", ")", ";", "return", "''", ";", "}", "var", "partial", ";", "if", "(", "!", "manager", ".", "options", ".", "wrapperTemplate", ")", "{", "partial", "=", "_", ".", "partial", "(", "self", ".", "partial", ",", "'widget'", ")", ";", "}", "else", "{", "partial", "=", "_", ".", "partial", "(", "manager", ".", "partial", ",", "manager", ".", "options", ".", "wrapperTemplate", ")", ";", "}", "return", "partial", "(", "{", "// The widget minus any properties that don't", "// absolutely need to be crammed into a JSON", "// attribute for the editor's benefit. Good filtering", "// here prevents megabytes of markup. -Tom and Sam", "dataFiltered", ":", "manager", ".", "filterForDataAttribute", "(", "widget", ")", ",", "manager", ":", "manager", ",", "widget", ":", "widget", ",", "options", ":", "options", ",", "output", ":", "function", "(", ")", "{", "return", "manager", ".", "output", "(", "widget", ",", "options", ")", ";", "}", "}", ")", ";", "}" ]
apos.areas.widget renders one widget. Invoked by both `apos.area` and `apos.singleton`. Not often called directly, but see `area.html` if you are interested in doing so.
[ "apos", ".", "areas", ".", "widget", "renders", "one", "widget", ".", "Invoked", "by", "both", "apos", ".", "area", "and", "apos", ".", "singleton", ".", "Not", "often", "called", "directly", "but", "see", "area", ".", "html", "if", "you", "are", "interested", "in", "doing", "so", "." ]
dca702fc95492eb3f86a2ad338a3791365266064
https://github.com/apostrophecms/apostrophe/blob/dca702fc95492eb3f86a2ad338a3791365266064/lib/modules/apostrophe-areas/lib/helpers.js#L161-L187
5,685
apostrophecms/apostrophe
lib/modules/apostrophe-areas/lib/helpers.js
function(widget, options) { return self.widgetControlGroups(self.apos.templates.contextReq, widget, options); }
javascript
function(widget, options) { return self.widgetControlGroups(self.apos.templates.contextReq, widget, options); }
[ "function", "(", "widget", ",", "options", ")", "{", "return", "self", ".", "widgetControlGroups", "(", "self", ".", "apos", ".", "templates", ".", "contextReq", ",", "widget", ",", "options", ")", ";", "}" ]
Output the widget controls. The `addWidgetControlGroups` option can be used to append additional control groups. See the `widgetControlGroups` method for the format. That method can also be extended via the `super` pattern to make the decision dynamically.
[ "Output", "the", "widget", "controls", ".", "The", "addWidgetControlGroups", "option", "can", "be", "used", "to", "append", "additional", "control", "groups", ".", "See", "the", "widgetControlGroups", "method", "for", "the", "format", ".", "That", "method", "can", "also", "be", "extended", "via", "the", "super", "pattern", "to", "make", "the", "decision", "dynamically", "." ]
dca702fc95492eb3f86a2ad338a3791365266064
https://github.com/apostrophecms/apostrophe/blob/dca702fc95492eb3f86a2ad338a3791365266064/lib/modules/apostrophe-areas/lib/helpers.js#L236-L238
5,686
apostrophecms/apostrophe
lib/modules/apostrophe-caches/index.js
function(callback) { if (callback) { return body(callback); } else { return Promise.promisify(body)(); } function body(callback) { return self.cacheCollection.remove({ name: name }, callback); } }
javascript
function(callback) { if (callback) { return body(callback); } else { return Promise.promisify(body)(); } function body(callback) { return self.cacheCollection.remove({ name: name }, callback); } }
[ "function", "(", "callback", ")", "{", "if", "(", "callback", ")", "{", "return", "body", "(", "callback", ")", ";", "}", "else", "{", "return", "Promise", ".", "promisify", "(", "body", ")", "(", ")", ";", "}", "function", "body", "(", "callback", ")", "{", "return", "self", ".", "cacheCollection", ".", "remove", "(", "{", "name", ":", "name", "}", ",", "callback", ")", ";", "}", "}" ]
Empty the cache. If there is no callback a promise is returned.
[ "Empty", "the", "cache", ".", "If", "there", "is", "no", "callback", "a", "promise", "is", "returned", "." ]
dca702fc95492eb3f86a2ad338a3791365266064
https://github.com/apostrophecms/apostrophe/blob/dca702fc95492eb3f86a2ad338a3791365266064/lib/modules/apostrophe-caches/index.js#L186-L197
5,687
apostrophecms/apostrophe
lib/modules/apostrophe-pages/lib/routes.js
clean
function clean(nodes) { mark(nodes, []); return prune(nodes); function mark(nodes, ancestors) { _.each(nodes, function(node) { if (node.publish) { node.good = true; _.each(ancestors, function(ancestor) { ancestor.good = true; }); } mark(node.children || [], ancestors.concat([ node ])); }); } function prune(nodes) { var newNodes = []; _.each(nodes, function(node) { node.children = prune(node.children || []); if (node.good) { newNodes.push(node); } }); return newNodes; } }
javascript
function clean(nodes) { mark(nodes, []); return prune(nodes); function mark(nodes, ancestors) { _.each(nodes, function(node) { if (node.publish) { node.good = true; _.each(ancestors, function(ancestor) { ancestor.good = true; }); } mark(node.children || [], ancestors.concat([ node ])); }); } function prune(nodes) { var newNodes = []; _.each(nodes, function(node) { node.children = prune(node.children || []); if (node.good) { newNodes.push(node); } }); return newNodes; } }
[ "function", "clean", "(", "nodes", ")", "{", "mark", "(", "nodes", ",", "[", "]", ")", ";", "return", "prune", "(", "nodes", ")", ";", "function", "mark", "(", "nodes", ",", "ancestors", ")", "{", "_", ".", "each", "(", "nodes", ",", "function", "(", "node", ")", "{", "if", "(", "node", ".", "publish", ")", "{", "node", ".", "good", "=", "true", ";", "_", ".", "each", "(", "ancestors", ",", "function", "(", "ancestor", ")", "{", "ancestor", ".", "good", "=", "true", ";", "}", ")", ";", "}", "mark", "(", "node", ".", "children", "||", "[", "]", ",", "ancestors", ".", "concat", "(", "[", "node", "]", ")", ")", ";", "}", ")", ";", "}", "function", "prune", "(", "nodes", ")", "{", "var", "newNodes", "=", "[", "]", ";", "_", ".", "each", "(", "nodes", ",", "function", "(", "node", ")", "{", "node", ".", "children", "=", "prune", "(", "node", ".", "children", "||", "[", "]", ")", ";", "if", "(", "node", ".", "good", ")", "{", "newNodes", ".", "push", "(", "node", ")", ";", "}", "}", ")", ";", "return", "newNodes", ";", "}", "}" ]
If I can't publish at least one of a node's descendants, prune it from the tree. Returns a pruned version of the tree
[ "If", "I", "can", "t", "publish", "at", "least", "one", "of", "a", "node", "s", "descendants", "prune", "it", "from", "the", "tree", ".", "Returns", "a", "pruned", "version", "of", "the", "tree" ]
dca702fc95492eb3f86a2ad338a3791365266064
https://github.com/apostrophecms/apostrophe/blob/dca702fc95492eb3f86a2ad338a3791365266064/lib/modules/apostrophe-pages/lib/routes.js#L494-L518
5,688
apostrophecms/apostrophe
lib/modules/apostrophe-widgets/public/js/user.js
function(self, options) { self.options = options; self.editorName = self.name + '-widgets-editor'; // Opens the editor modal of a widget, unless the widget is contextualOnly, // in which case we simply save the widget and call the save method // Widget can opitonally be set to skipInitialModal which skips the first // edit modal but binds future editing interactions self.edit = function(data, options, save) { if (!data) { data = {}; } if (!data._id) { _.assign(data, apos.schemas.newInstance(self.schema)); } // Only create a modal editor if the schema is not contextual only if (self.options.contextualOnly) { return save(checkOrGenerateId(data), function() {}); } else { if (self.options.skipInitialModal && (!data || !data._id)) { return save(checkOrGenerateId(data), function() {}); } apos.create(self.editorName, { label: self.label, action: self.options.action, schema: self.options.schema, data: data, templateOptions: options, save: save, module: self }); } // Checks for an id or assign a generated one function checkOrGenerateId (data) { data = data || {}; if (!data._id) { data._id = apos.utils.generateId(); } return data; } }; // Area editor calls this to determine whether to apply an empty state // class for the widget self.isEmpty = function($widget) { return false; }; var superGetData = self.getData; self.getData = function($widget) { var data = superGetData($widget); // If the field is contextual and its type has a `contextualConvert` // function, we need to run that when retrieving the widget's data. // Or, if the field has a `contextualIsPresent` method, we can use that // to check whether an editor is actually present for it, bypassing the // need to restrict this feature solely to fields marked contextual // in the schema. _.each(self.schema, function(field) { var type = apos.schemas.fieldTypes[field.type]; if ( (type.contextualIsPresent && type.contextualIsPresent($widget, field) && type.contextualConvert) || (field.contextual && type.contextualConvert) ) { apos.schemas.fieldTypes[field.type].contextualConvert(data, field.name, $widget, field); } }); return data; }; // Start autosaving the area containing the given widget, // then invoke the given function. On failure fn is not invoked. // Invoked by widgets that are edited contextually on the page, // like apostrophe-rich-text, as opposed to widgets edited // via a modal. self.startAutosavingAreaThen = function($widget, fn) { var $area = $widget.closest('[data-apos-area]'); return $area.data('editor').startAutosavingThen(fn); }; }
javascript
function(self, options) { self.options = options; self.editorName = self.name + '-widgets-editor'; // Opens the editor modal of a widget, unless the widget is contextualOnly, // in which case we simply save the widget and call the save method // Widget can opitonally be set to skipInitialModal which skips the first // edit modal but binds future editing interactions self.edit = function(data, options, save) { if (!data) { data = {}; } if (!data._id) { _.assign(data, apos.schemas.newInstance(self.schema)); } // Only create a modal editor if the schema is not contextual only if (self.options.contextualOnly) { return save(checkOrGenerateId(data), function() {}); } else { if (self.options.skipInitialModal && (!data || !data._id)) { return save(checkOrGenerateId(data), function() {}); } apos.create(self.editorName, { label: self.label, action: self.options.action, schema: self.options.schema, data: data, templateOptions: options, save: save, module: self }); } // Checks for an id or assign a generated one function checkOrGenerateId (data) { data = data || {}; if (!data._id) { data._id = apos.utils.generateId(); } return data; } }; // Area editor calls this to determine whether to apply an empty state // class for the widget self.isEmpty = function($widget) { return false; }; var superGetData = self.getData; self.getData = function($widget) { var data = superGetData($widget); // If the field is contextual and its type has a `contextualConvert` // function, we need to run that when retrieving the widget's data. // Or, if the field has a `contextualIsPresent` method, we can use that // to check whether an editor is actually present for it, bypassing the // need to restrict this feature solely to fields marked contextual // in the schema. _.each(self.schema, function(field) { var type = apos.schemas.fieldTypes[field.type]; if ( (type.contextualIsPresent && type.contextualIsPresent($widget, field) && type.contextualConvert) || (field.contextual && type.contextualConvert) ) { apos.schemas.fieldTypes[field.type].contextualConvert(data, field.name, $widget, field); } }); return data; }; // Start autosaving the area containing the given widget, // then invoke the given function. On failure fn is not invoked. // Invoked by widgets that are edited contextually on the page, // like apostrophe-rich-text, as opposed to widgets edited // via a modal. self.startAutosavingAreaThen = function($widget, fn) { var $area = $widget.closest('[data-apos-area]'); return $area.data('editor').startAutosavingThen(fn); }; }
[ "function", "(", "self", ",", "options", ")", "{", "self", ".", "options", "=", "options", ";", "self", ".", "editorName", "=", "self", ".", "name", "+", "'-widgets-editor'", ";", "// Opens the editor modal of a widget, unless the widget is contextualOnly,", "// in which case we simply save the widget and call the save method", "// Widget can opitonally be set to skipInitialModal which skips the first", "// edit modal but binds future editing interactions", "self", ".", "edit", "=", "function", "(", "data", ",", "options", ",", "save", ")", "{", "if", "(", "!", "data", ")", "{", "data", "=", "{", "}", ";", "}", "if", "(", "!", "data", ".", "_id", ")", "{", "_", ".", "assign", "(", "data", ",", "apos", ".", "schemas", ".", "newInstance", "(", "self", ".", "schema", ")", ")", ";", "}", "// Only create a modal editor if the schema is not contextual only", "if", "(", "self", ".", "options", ".", "contextualOnly", ")", "{", "return", "save", "(", "checkOrGenerateId", "(", "data", ")", ",", "function", "(", ")", "{", "}", ")", ";", "}", "else", "{", "if", "(", "self", ".", "options", ".", "skipInitialModal", "&&", "(", "!", "data", "||", "!", "data", ".", "_id", ")", ")", "{", "return", "save", "(", "checkOrGenerateId", "(", "data", ")", ",", "function", "(", ")", "{", "}", ")", ";", "}", "apos", ".", "create", "(", "self", ".", "editorName", ",", "{", "label", ":", "self", ".", "label", ",", "action", ":", "self", ".", "options", ".", "action", ",", "schema", ":", "self", ".", "options", ".", "schema", ",", "data", ":", "data", ",", "templateOptions", ":", "options", ",", "save", ":", "save", ",", "module", ":", "self", "}", ")", ";", "}", "// Checks for an id or assign a generated one", "function", "checkOrGenerateId", "(", "data", ")", "{", "data", "=", "data", "||", "{", "}", ";", "if", "(", "!", "data", ".", "_id", ")", "{", "data", ".", "_id", "=", "apos", ".", "utils", ".", "generateId", "(", ")", ";", "}", "return", "data", ";", "}", "}", ";", "// Area editor calls this to determine whether to apply an empty state", "// class for the widget", "self", ".", "isEmpty", "=", "function", "(", "$widget", ")", "{", "return", "false", ";", "}", ";", "var", "superGetData", "=", "self", ".", "getData", ";", "self", ".", "getData", "=", "function", "(", "$widget", ")", "{", "var", "data", "=", "superGetData", "(", "$widget", ")", ";", "// If the field is contextual and its type has a `contextualConvert`", "// function, we need to run that when retrieving the widget's data.", "// Or, if the field has a `contextualIsPresent` method, we can use that", "// to check whether an editor is actually present for it, bypassing the", "// need to restrict this feature solely to fields marked contextual", "// in the schema.", "_", ".", "each", "(", "self", ".", "schema", ",", "function", "(", "field", ")", "{", "var", "type", "=", "apos", ".", "schemas", ".", "fieldTypes", "[", "field", ".", "type", "]", ";", "if", "(", "(", "type", ".", "contextualIsPresent", "&&", "type", ".", "contextualIsPresent", "(", "$widget", ",", "field", ")", "&&", "type", ".", "contextualConvert", ")", "||", "(", "field", ".", "contextual", "&&", "type", ".", "contextualConvert", ")", ")", "{", "apos", ".", "schemas", ".", "fieldTypes", "[", "field", ".", "type", "]", ".", "contextualConvert", "(", "data", ",", "field", ".", "name", ",", "$widget", ",", "field", ")", ";", "}", "}", ")", ";", "return", "data", ";", "}", ";", "// Start autosaving the area containing the given widget,", "// then invoke the given function. On failure fn is not invoked.", "// Invoked by widgets that are edited contextually on the page,", "// like apostrophe-rich-text, as opposed to widgets edited", "// via a modal.", "self", ".", "startAutosavingAreaThen", "=", "function", "(", "$widget", ",", "fn", ")", "{", "var", "$area", "=", "$widget", ".", "closest", "(", "'[data-apos-area]'", ")", ";", "return", "$area", ".", "data", "(", "'editor'", ")", ".", "startAutosavingThen", "(", "fn", ")", ";", "}", ";", "}" ]
Implicitly extends the definition in always.js
[ "Implicitly", "extends", "the", "definition", "in", "always", ".", "js" ]
dca702fc95492eb3f86a2ad338a3791365266064
https://github.com/apostrophecms/apostrophe/blob/dca702fc95492eb3f86a2ad338a3791365266064/lib/modules/apostrophe-widgets/public/js/user.js#L4-L93
5,689
apostrophecms/apostrophe
lib/modules/apostrophe-widgets/public/js/user.js
checkOrGenerateId
function checkOrGenerateId (data) { data = data || {}; if (!data._id) { data._id = apos.utils.generateId(); } return data; }
javascript
function checkOrGenerateId (data) { data = data || {}; if (!data._id) { data._id = apos.utils.generateId(); } return data; }
[ "function", "checkOrGenerateId", "(", "data", ")", "{", "data", "=", "data", "||", "{", "}", ";", "if", "(", "!", "data", ".", "_id", ")", "{", "data", ".", "_id", "=", "apos", ".", "utils", ".", "generateId", "(", ")", ";", "}", "return", "data", ";", "}" ]
Checks for an id or assign a generated one
[ "Checks", "for", "an", "id", "or", "assign", "a", "generated", "one" ]
dca702fc95492eb3f86a2ad338a3791365266064
https://github.com/apostrophecms/apostrophe/blob/dca702fc95492eb3f86a2ad338a3791365266064/lib/modules/apostrophe-widgets/public/js/user.js#L46-L52
5,690
apache/cordova-ios
bin/templates/scripts/cordova/lib/check_reqs.js
function (id, name, isFatal) { this.id = id; this.name = name; this.installed = false; this.metadata = {}; this.isFatal = isFatal || false; }
javascript
function (id, name, isFatal) { this.id = id; this.name = name; this.installed = false; this.metadata = {}; this.isFatal = isFatal || false; }
[ "function", "(", "id", ",", "name", ",", "isFatal", ")", "{", "this", ".", "id", "=", "id", ";", "this", ".", "name", "=", "name", ";", "this", ".", "installed", "=", "false", ";", "this", ".", "metadata", "=", "{", "}", ";", "this", ".", "isFatal", "=", "isFatal", "||", "false", ";", "}" ]
Object that represents one of requirements for current platform. @param {String} id The unique identifier for this requirements. @param {String} name The name of requirements. Human-readable field. @param {Boolean} isFatal Marks the requirement as fatal. If such requirement will fail next requirements' checks will be skipped.
[ "Object", "that", "represents", "one", "of", "requirements", "for", "current", "platform", "." ]
9dbd1f860cad4d148c57f05594036477eb95e9c7
https://github.com/apache/cordova-ios/blob/9dbd1f860cad4d148c57f05594036477eb95e9c7/bin/templates/scripts/cordova/lib/check_reqs.js#L171-L177
5,691
apache/cordova-ios
bin/templates/scripts/cordova/lib/prepare.js
cleanWww
function cleanWww (projectRoot, locations) { var targetDir = path.relative(projectRoot, locations.www); events.emit('verbose', 'Cleaning ' + targetDir); // No source paths are specified, so mergeAndUpdateDir() will clear the target directory. FileUpdater.mergeAndUpdateDir( [], targetDir, { rootDir: projectRoot, all: true }, logFileOp); }
javascript
function cleanWww (projectRoot, locations) { var targetDir = path.relative(projectRoot, locations.www); events.emit('verbose', 'Cleaning ' + targetDir); // No source paths are specified, so mergeAndUpdateDir() will clear the target directory. FileUpdater.mergeAndUpdateDir( [], targetDir, { rootDir: projectRoot, all: true }, logFileOp); }
[ "function", "cleanWww", "(", "projectRoot", ",", "locations", ")", "{", "var", "targetDir", "=", "path", ".", "relative", "(", "projectRoot", ",", "locations", ".", "www", ")", ";", "events", ".", "emit", "(", "'verbose'", ",", "'Cleaning '", "+", "targetDir", ")", ";", "// No source paths are specified, so mergeAndUpdateDir() will clear the target directory.", "FileUpdater", ".", "mergeAndUpdateDir", "(", "[", "]", ",", "targetDir", ",", "{", "rootDir", ":", "projectRoot", ",", "all", ":", "true", "}", ",", "logFileOp", ")", ";", "}" ]
Cleans all files from the platform 'www' directory.
[ "Cleans", "all", "files", "from", "the", "platform", "www", "directory", "." ]
9dbd1f860cad4d148c57f05594036477eb95e9c7
https://github.com/apache/cordova-ios/blob/9dbd1f860cad4d148c57f05594036477eb95e9c7/bin/templates/scripts/cordova/lib/prepare.js#L169-L176
5,692
apache/cordova-ios
bin/templates/scripts/cordova/lib/prepare.js
mapLaunchStoryboardResources
function mapLaunchStoryboardResources (splashScreens, launchStoryboardImagesDir) { var platformLaunchStoryboardImages = mapLaunchStoryboardContents(splashScreens, launchStoryboardImagesDir); var pathMap = {}; platformLaunchStoryboardImages.forEach(function (item) { if (item.target) { pathMap[item.target] = item.src; } }); return pathMap; }
javascript
function mapLaunchStoryboardResources (splashScreens, launchStoryboardImagesDir) { var platformLaunchStoryboardImages = mapLaunchStoryboardContents(splashScreens, launchStoryboardImagesDir); var pathMap = {}; platformLaunchStoryboardImages.forEach(function (item) { if (item.target) { pathMap[item.target] = item.src; } }); return pathMap; }
[ "function", "mapLaunchStoryboardResources", "(", "splashScreens", ",", "launchStoryboardImagesDir", ")", "{", "var", "platformLaunchStoryboardImages", "=", "mapLaunchStoryboardContents", "(", "splashScreens", ",", "launchStoryboardImagesDir", ")", ";", "var", "pathMap", "=", "{", "}", ";", "platformLaunchStoryboardImages", ".", "forEach", "(", "function", "(", "item", ")", "{", "if", "(", "item", ".", "target", ")", "{", "pathMap", "[", "item", ".", "target", "]", "=", "item", ".", "src", ";", "}", "}", ")", ";", "return", "pathMap", ";", "}" ]
Returns a dictionary representing the source and destination paths for the launch storyboard images that need to be copied. The resulting return looks like this: { 'target-path': 'source-path', ... } @param {Array<Object>} splashScreens splash screens as defined in config.xml for this platform @param {string} launchStoryboardImagesDir project-root/Images.xcassets/LaunchStoryboard.imageset/ @return {Object}
[ "Returns", "a", "dictionary", "representing", "the", "source", "and", "destination", "paths", "for", "the", "launch", "storyboard", "images", "that", "need", "to", "be", "copied", "." ]
9dbd1f860cad4d148c57f05594036477eb95e9c7
https://github.com/apache/cordova-ios/blob/9dbd1f860cad4d148c57f05594036477eb95e9c7/bin/templates/scripts/cordova/lib/prepare.js#L653-L662
5,693
apache/cordova-ios
bin/templates/scripts/cordova/lib/prepare.js
getLaunchStoryboardImagesDir
function getLaunchStoryboardImagesDir (projectRoot, platformProjDir) { var launchStoryboardImagesDir; var xcassetsExists = folderExists(path.join(projectRoot, platformProjDir, 'Images.xcassets/')); if (xcassetsExists) { launchStoryboardImagesDir = path.join(platformProjDir, 'Images.xcassets/LaunchStoryboard.imageset/'); } else { // if we don't have a asset library for images, we can't do the storyboard. launchStoryboardImagesDir = null; } return launchStoryboardImagesDir; }
javascript
function getLaunchStoryboardImagesDir (projectRoot, platformProjDir) { var launchStoryboardImagesDir; var xcassetsExists = folderExists(path.join(projectRoot, platformProjDir, 'Images.xcassets/')); if (xcassetsExists) { launchStoryboardImagesDir = path.join(platformProjDir, 'Images.xcassets/LaunchStoryboard.imageset/'); } else { // if we don't have a asset library for images, we can't do the storyboard. launchStoryboardImagesDir = null; } return launchStoryboardImagesDir; }
[ "function", "getLaunchStoryboardImagesDir", "(", "projectRoot", ",", "platformProjDir", ")", "{", "var", "launchStoryboardImagesDir", ";", "var", "xcassetsExists", "=", "folderExists", "(", "path", ".", "join", "(", "projectRoot", ",", "platformProjDir", ",", "'Images.xcassets/'", ")", ")", ";", "if", "(", "xcassetsExists", ")", "{", "launchStoryboardImagesDir", "=", "path", ".", "join", "(", "platformProjDir", ",", "'Images.xcassets/LaunchStoryboard.imageset/'", ")", ";", "}", "else", "{", "// if we don't have a asset library for images, we can't do the storyboard.", "launchStoryboardImagesDir", "=", "null", ";", "}", "return", "launchStoryboardImagesDir", ";", "}" ]
Returns the directory for the Launch Storyboard image set, if image sets are being used. If they aren't being used, returns null. @param {string} projectRoot The project's root directory @param {string} platformProjDir The platform's project directory
[ "Returns", "the", "directory", "for", "the", "Launch", "Storyboard", "image", "set", "if", "image", "sets", "are", "being", "used", ".", "If", "they", "aren", "t", "being", "used", "returns", "null", "." ]
9dbd1f860cad4d148c57f05594036477eb95e9c7
https://github.com/apache/cordova-ios/blob/9dbd1f860cad4d148c57f05594036477eb95e9c7/bin/templates/scripts/cordova/lib/prepare.js#L833-L845
5,694
apache/cordova-ios
bin/templates/scripts/cordova/lib/prepare.js
updateLaunchStoryboardImages
function updateLaunchStoryboardImages (cordovaProject, locations) { var splashScreens = cordovaProject.projectConfig.getSplashScreens('ios'); var platformProjDir = path.relative(cordovaProject.root, locations.xcodeCordovaProj); var launchStoryboardImagesDir = getLaunchStoryboardImagesDir(cordovaProject.root, platformProjDir); if (launchStoryboardImagesDir) { var resourceMap = mapLaunchStoryboardResources(splashScreens, launchStoryboardImagesDir); var contentsJSON = getLaunchStoryboardContentsJSON(splashScreens, launchStoryboardImagesDir); events.emit('verbose', 'Updating launch storyboard images at ' + launchStoryboardImagesDir); FileUpdater.updatePaths( resourceMap, { rootDir: cordovaProject.root }, logFileOp); events.emit('verbose', 'Updating Storyboard image set contents.json'); fs.writeFileSync(path.join(cordovaProject.root, launchStoryboardImagesDir, 'Contents.json'), JSON.stringify(contentsJSON, null, 2)); } }
javascript
function updateLaunchStoryboardImages (cordovaProject, locations) { var splashScreens = cordovaProject.projectConfig.getSplashScreens('ios'); var platformProjDir = path.relative(cordovaProject.root, locations.xcodeCordovaProj); var launchStoryboardImagesDir = getLaunchStoryboardImagesDir(cordovaProject.root, platformProjDir); if (launchStoryboardImagesDir) { var resourceMap = mapLaunchStoryboardResources(splashScreens, launchStoryboardImagesDir); var contentsJSON = getLaunchStoryboardContentsJSON(splashScreens, launchStoryboardImagesDir); events.emit('verbose', 'Updating launch storyboard images at ' + launchStoryboardImagesDir); FileUpdater.updatePaths( resourceMap, { rootDir: cordovaProject.root }, logFileOp); events.emit('verbose', 'Updating Storyboard image set contents.json'); fs.writeFileSync(path.join(cordovaProject.root, launchStoryboardImagesDir, 'Contents.json'), JSON.stringify(contentsJSON, null, 2)); } }
[ "function", "updateLaunchStoryboardImages", "(", "cordovaProject", ",", "locations", ")", "{", "var", "splashScreens", "=", "cordovaProject", ".", "projectConfig", ".", "getSplashScreens", "(", "'ios'", ")", ";", "var", "platformProjDir", "=", "path", ".", "relative", "(", "cordovaProject", ".", "root", ",", "locations", ".", "xcodeCordovaProj", ")", ";", "var", "launchStoryboardImagesDir", "=", "getLaunchStoryboardImagesDir", "(", "cordovaProject", ".", "root", ",", "platformProjDir", ")", ";", "if", "(", "launchStoryboardImagesDir", ")", "{", "var", "resourceMap", "=", "mapLaunchStoryboardResources", "(", "splashScreens", ",", "launchStoryboardImagesDir", ")", ";", "var", "contentsJSON", "=", "getLaunchStoryboardContentsJSON", "(", "splashScreens", ",", "launchStoryboardImagesDir", ")", ";", "events", ".", "emit", "(", "'verbose'", ",", "'Updating launch storyboard images at '", "+", "launchStoryboardImagesDir", ")", ";", "FileUpdater", ".", "updatePaths", "(", "resourceMap", ",", "{", "rootDir", ":", "cordovaProject", ".", "root", "}", ",", "logFileOp", ")", ";", "events", ".", "emit", "(", "'verbose'", ",", "'Updating Storyboard image set contents.json'", ")", ";", "fs", ".", "writeFileSync", "(", "path", ".", "join", "(", "cordovaProject", ".", "root", ",", "launchStoryboardImagesDir", ",", "'Contents.json'", ")", ",", "JSON", ".", "stringify", "(", "contentsJSON", ",", "null", ",", "2", ")", ")", ";", "}", "}" ]
Update the images for the Launch Storyboard and updates the image set's contents.json file appropriately. @param {Object} cordovaProject The cordova project @param {Object} locations A dictionary containing useful location paths
[ "Update", "the", "images", "for", "the", "Launch", "Storyboard", "and", "updates", "the", "image", "set", "s", "contents", ".", "json", "file", "appropriately", "." ]
9dbd1f860cad4d148c57f05594036477eb95e9c7
https://github.com/apache/cordova-ios/blob/9dbd1f860cad4d148c57f05594036477eb95e9c7/bin/templates/scripts/cordova/lib/prepare.js#L853-L870
5,695
apache/cordova-ios
bin/templates/scripts/cordova/lib/build.js
getDefaultSimulatorTarget
function getDefaultSimulatorTarget () { return require('./list-emulator-build-targets').run() .then(function (emulators) { var targetEmulator; if (emulators.length > 0) { targetEmulator = emulators[0]; } emulators.forEach(function (emulator) { if (emulator.name.indexOf('iPhone') === 0) { targetEmulator = emulator; } }); return targetEmulator; }); }
javascript
function getDefaultSimulatorTarget () { return require('./list-emulator-build-targets').run() .then(function (emulators) { var targetEmulator; if (emulators.length > 0) { targetEmulator = emulators[0]; } emulators.forEach(function (emulator) { if (emulator.name.indexOf('iPhone') === 0) { targetEmulator = emulator; } }); return targetEmulator; }); }
[ "function", "getDefaultSimulatorTarget", "(", ")", "{", "return", "require", "(", "'./list-emulator-build-targets'", ")", ".", "run", "(", ")", ".", "then", "(", "function", "(", "emulators", ")", "{", "var", "targetEmulator", ";", "if", "(", "emulators", ".", "length", ">", "0", ")", "{", "targetEmulator", "=", "emulators", "[", "0", "]", ";", "}", "emulators", ".", "forEach", "(", "function", "(", "emulator", ")", "{", "if", "(", "emulator", ".", "name", ".", "indexOf", "(", "'iPhone'", ")", "===", "0", ")", "{", "targetEmulator", "=", "emulator", ";", "}", "}", ")", ";", "return", "targetEmulator", ";", "}", ")", ";", "}" ]
Returns a promise that resolves to the default simulator target; the logic here matches what `cordova emulate ios` does. The return object has two properties: `name` (the Xcode destination name), `identifier` (the simctl identifier), and `simIdentifier` (essentially the cordova emulate target) @return {Promise}
[ "Returns", "a", "promise", "that", "resolves", "to", "the", "default", "simulator", "target", ";", "the", "logic", "here", "matches", "what", "cordova", "emulate", "ios", "does", "." ]
9dbd1f860cad4d148c57f05594036477eb95e9c7
https://github.com/apache/cordova-ios/blob/9dbd1f860cad4d148c57f05594036477eb95e9c7/bin/templates/scripts/cordova/lib/build.js#L90-L104
5,696
apache/cordova-ios
bin/templates/scripts/cordova/lib/build.js
findXCodeProjectIn
function findXCodeProjectIn (projectPath) { // 'Searching for Xcode project in ' + projectPath); var xcodeProjFiles = shell.ls(projectPath).filter(function (name) { return path.extname(name) === '.xcodeproj'; }); if (xcodeProjFiles.length === 0) { return Q.reject('No Xcode project found in ' + projectPath); } if (xcodeProjFiles.length > 1) { events.emit('warn', 'Found multiple .xcodeproj directories in \n' + projectPath + '\nUsing first one'); } var projectName = path.basename(xcodeProjFiles[0], '.xcodeproj'); return Q.resolve(projectName); }
javascript
function findXCodeProjectIn (projectPath) { // 'Searching for Xcode project in ' + projectPath); var xcodeProjFiles = shell.ls(projectPath).filter(function (name) { return path.extname(name) === '.xcodeproj'; }); if (xcodeProjFiles.length === 0) { return Q.reject('No Xcode project found in ' + projectPath); } if (xcodeProjFiles.length > 1) { events.emit('warn', 'Found multiple .xcodeproj directories in \n' + projectPath + '\nUsing first one'); } var projectName = path.basename(xcodeProjFiles[0], '.xcodeproj'); return Q.resolve(projectName); }
[ "function", "findXCodeProjectIn", "(", "projectPath", ")", "{", "// 'Searching for Xcode project in ' + projectPath);", "var", "xcodeProjFiles", "=", "shell", ".", "ls", "(", "projectPath", ")", ".", "filter", "(", "function", "(", "name", ")", "{", "return", "path", ".", "extname", "(", "name", ")", "===", "'.xcodeproj'", ";", "}", ")", ";", "if", "(", "xcodeProjFiles", ".", "length", "===", "0", ")", "{", "return", "Q", ".", "reject", "(", "'No Xcode project found in '", "+", "projectPath", ")", ";", "}", "if", "(", "xcodeProjFiles", ".", "length", ">", "1", ")", "{", "events", ".", "emit", "(", "'warn'", ",", "'Found multiple .xcodeproj directories in \\n'", "+", "projectPath", "+", "'\\nUsing first one'", ")", ";", "}", "var", "projectName", "=", "path", ".", "basename", "(", "xcodeProjFiles", "[", "0", "]", ",", "'.xcodeproj'", ")", ";", "return", "Q", ".", "resolve", "(", "projectName", ")", ";", "}" ]
Searches for first XCode project in specified folder @param {String} projectPath Path where to search project @return {Promise} Promise either fulfilled with project name or rejected
[ "Searches", "for", "first", "XCode", "project", "in", "specified", "folder" ]
9dbd1f860cad4d148c57f05594036477eb95e9c7
https://github.com/apache/cordova-ios/blob/9dbd1f860cad4d148c57f05594036477eb95e9c7/bin/templates/scripts/cordova/lib/build.js#L292-L308
5,697
apache/cordova-ios
cordova-js-src/plugin/ios/logger.js
logWithArgs
function logWithArgs(level, args) { args = [level].concat([].slice.call(args)); logger.logLevel.apply(logger, args); }
javascript
function logWithArgs(level, args) { args = [level].concat([].slice.call(args)); logger.logLevel.apply(logger, args); }
[ "function", "logWithArgs", "(", "level", ",", "args", ")", "{", "args", "=", "[", "level", "]", ".", "concat", "(", "[", "]", ".", "slice", ".", "call", "(", "args", ")", ")", ";", "logger", ".", "logLevel", ".", "apply", "(", "logger", ",", "args", ")", ";", "}" ]
log at the specified level with args
[ "log", "at", "the", "specified", "level", "with", "args" ]
9dbd1f860cad4d148c57f05594036477eb95e9c7
https://github.com/apache/cordova-ios/blob/9dbd1f860cad4d148c57f05594036477eb95e9c7/cordova-js-src/plugin/ios/logger.js#L192-L195
5,698
apache/cordova-ios
cordova-js-src/exec.js
handleBridgeChange
function handleBridgeChange() { if (proxyChanged()) { var commandString = commandQueue.shift(); while(commandString) { var command = JSON.parse(commandString); var callbackId = command[0]; var service = command[1]; var action = command[2]; var actionArgs = command[3]; var callbacks = cordova.callbacks[callbackId] || {}; execProxy(callbacks.success, callbacks.fail, service, action, actionArgs); commandString = commandQueue.shift(); }; return true; } return false; }
javascript
function handleBridgeChange() { if (proxyChanged()) { var commandString = commandQueue.shift(); while(commandString) { var command = JSON.parse(commandString); var callbackId = command[0]; var service = command[1]; var action = command[2]; var actionArgs = command[3]; var callbacks = cordova.callbacks[callbackId] || {}; execProxy(callbacks.success, callbacks.fail, service, action, actionArgs); commandString = commandQueue.shift(); }; return true; } return false; }
[ "function", "handleBridgeChange", "(", ")", "{", "if", "(", "proxyChanged", "(", ")", ")", "{", "var", "commandString", "=", "commandQueue", ".", "shift", "(", ")", ";", "while", "(", "commandString", ")", "{", "var", "command", "=", "JSON", ".", "parse", "(", "commandString", ")", ";", "var", "callbackId", "=", "command", "[", "0", "]", ";", "var", "service", "=", "command", "[", "1", "]", ";", "var", "action", "=", "command", "[", "2", "]", ";", "var", "actionArgs", "=", "command", "[", "3", "]", ";", "var", "callbacks", "=", "cordova", ".", "callbacks", "[", "callbackId", "]", "||", "{", "}", ";", "execProxy", "(", "callbacks", ".", "success", ",", "callbacks", ".", "fail", ",", "service", ",", "action", ",", "actionArgs", ")", ";", "commandString", "=", "commandQueue", ".", "shift", "(", ")", ";", "}", ";", "return", "true", ";", "}", "return", "false", ";", "}" ]
CB-10106
[ "CB", "-", "10106" ]
9dbd1f860cad4d148c57f05594036477eb95e9c7
https://github.com/apache/cordova-ios/blob/9dbd1f860cad4d148c57f05594036477eb95e9c7/cordova-js-src/exec.js#L147-L166
5,699
apache/cordova-ios
cordova-js-src/exec.js
cordovaExec
function cordovaExec() { var cexec = require('cordova/exec'); var cexec_valid = (typeof cexec.nativeFetchMessages === 'function') && (typeof cexec.nativeEvalAndFetch === 'function') && (typeof cexec.nativeCallback === 'function'); return (cexec_valid && execProxy !== cexec)? cexec : iOSExec; }
javascript
function cordovaExec() { var cexec = require('cordova/exec'); var cexec_valid = (typeof cexec.nativeFetchMessages === 'function') && (typeof cexec.nativeEvalAndFetch === 'function') && (typeof cexec.nativeCallback === 'function'); return (cexec_valid && execProxy !== cexec)? cexec : iOSExec; }
[ "function", "cordovaExec", "(", ")", "{", "var", "cexec", "=", "require", "(", "'cordova/exec'", ")", ";", "var", "cexec_valid", "=", "(", "typeof", "cexec", ".", "nativeFetchMessages", "===", "'function'", ")", "&&", "(", "typeof", "cexec", ".", "nativeEvalAndFetch", "===", "'function'", ")", "&&", "(", "typeof", "cexec", ".", "nativeCallback", "===", "'function'", ")", ";", "return", "(", "cexec_valid", "&&", "execProxy", "!==", "cexec", ")", "?", "cexec", ":", "iOSExec", ";", "}" ]
Proxy the exec for bridge changes. See CB-10106
[ "Proxy", "the", "exec", "for", "bridge", "changes", ".", "See", "CB", "-", "10106" ]
9dbd1f860cad4d148c57f05594036477eb95e9c7
https://github.com/apache/cordova-ios/blob/9dbd1f860cad4d148c57f05594036477eb95e9c7/cordova-js-src/exec.js#L240-L244