hexsha
string
size
int64
ext
string
lang
string
max_stars_repo_path
string
max_stars_repo_name
string
max_stars_repo_head_hexsha
string
max_stars_repo_licenses
list
max_stars_count
int64
max_stars_repo_stars_event_min_datetime
string
max_stars_repo_stars_event_max_datetime
string
max_issues_repo_path
string
max_issues_repo_name
string
max_issues_repo_head_hexsha
string
max_issues_repo_licenses
list
max_issues_count
int64
max_issues_repo_issues_event_min_datetime
string
max_issues_repo_issues_event_max_datetime
string
max_forks_repo_path
string
max_forks_repo_name
string
max_forks_repo_head_hexsha
string
max_forks_repo_licenses
list
max_forks_count
int64
max_forks_repo_forks_event_min_datetime
string
max_forks_repo_forks_event_max_datetime
string
content
string
avg_line_length
float64
max_line_length
int64
alphanum_fraction
float64
7593248e3015968ecf563c5ebdbb2dee3afb571f
10,889
js
JavaScript
src/Microsoft_Azure_Nginx/Client/Project/Summary/ViewModels/ProjectBlade.js
juniwang/AzurePortalExt4Nginx
eb1347a183bddf34ad2e7a0f4c19102d81442dd5
[ "MIT" ]
null
null
null
src/Microsoft_Azure_Nginx/Client/Project/Summary/ViewModels/ProjectBlade.js
juniwang/AzurePortalExt4Nginx
eb1347a183bddf34ad2e7a0f4c19102d81442dd5
[ "MIT" ]
null
null
null
src/Microsoft_Azure_Nginx/Client/Project/Summary/ViewModels/ProjectBlade.js
juniwang/AzurePortalExt4Nginx
eb1347a183bddf34ad2e7a0f4c19102d81442dd5
[ "MIT" ]
null
null
null
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; define(["require", "exports", "Fx/Composition/TemplateBlade", "Fx/Controls/Essentials", "Fx/Controls/Toolbar/MoveResourceToolbarButton", "NginxStrings", "_generated/ExtensionDefinition", "_generated/BladeReferences", "../../../_generated/HubsExtension/BladeReferences", "_generated/Svg", "Project/ViewModels/ProjectCommands"], function (require, exports, TemplateBlade, Essentials_1, MoveButton, Strings, ExtensionDefinition_1, BladeRefs, HubsBladeRefs, Svg_1, ProjectCommands_1) { "use strict"; var ViewModels = MsPortalFx.ViewModels; var Toolbars = ViewModels.Toolbars; var Grid = ViewModels.Controls.Lists.Grid; var log = Logger("NoPdlProject"); var ResourceBladeConfigMetadata = { essentialsExpanded: { isSharedAcrossPartAndBladeTypes: false }, timespan: { isSharedAcrossPartAndBladeTypes: true, sharedKey: "Azure_Project_Service_Timespan" }, servicesSortColumn: { isSharedAcrossPartAndBladeTypes: false }, servicesSortAscending: { isSharedAcrossPartAndBladeTypes: false }, }; var ProjectBlade = (function () { function ProjectBlade() { this.title = ko.observable(); this.subtitle = ko.observable(); this.icon = ko.observable(Svg_1.Content.SVG.project); this.essentials = ko.observable(null); this.serviceListSectionTitle = ko.observable(Strings.SectionHeader.services); this._id = ko.observable(); this._essentialsExpanded = ko.observable(false); this._timespan = ko.observable("forever"); this._sortColumn = ko.observable("name"); this._sortAscending = ko.observable(true); } ProjectBlade.prototype.onPin = function () { log.debug("onPin", this.context); return new MsPortalFx.Composition.PartReference("ProjectPart", this.context.parameters); }; ProjectBlade.prototype.onRebind = function () { log.debug("onRebind", this.context); this._syncFromConfiguration(this.context.configuration); this._id(this.context.parameters.id); this.context.container.revealContent(); return this._binder.promise; }; ProjectBlade.prototype.onInitialize = function () { log.debug("onInitialize", this.context); var _a = this.context, container = _a.container, parameters = _a.parameters, model = _a.model, configuration = _a.configuration; this._binder = model.projectEntityCache.binder(container, this._id); this._binder.bind(this.title, function (p) { return p.name(); }); this._syncFromConfiguration(configuration); this._servicesView = this.context.model.serviceQueryCache.createView(container); this._initializeServiceGrid(container); this._initializeToolbar(container); this._initializeEssentials(container); this._id(parameters.id); container.revealContent(); return this._binder.promise; }; ProjectBlade.prototype._initializeServiceGrid = function (container) { var _this = this; this.gridVM = new Grid.ViewModel(container, this._servicesView.items, Grid.Extensions.SelectableRow, { selectableRow: { selectionMode: 1 }, onRowClicked: function (service) { var bladeRef = (service.type() == "Container") ? new BladeRefs.ServiceBladeReference({ id: service.id() }) : new HubsBladeRefs.ResourceMenuBladeReference({ id: service.id() }); container.openBlade(bladeRef); }, }); var columns = [ { itemKey: "name", name: ko.observable(Strings.ColumnTitle.name), activatable: ko.observable(true), }, { itemKey: "type", name: ko.observable(Strings.ColumnTitle.type), activatable: ko.observable(true), }, { itemKey: "state", name: ko.observable(Strings.ColumnTitle.state), activatable: ko.observable(true), }, { itemKey: "updated", name: ko.observable(Strings.ColumnTitle.updated), activatable: ko.observable(true), }, { itemKey: "host", name: ko.observable(Strings.ColumnTitle.host), activatable: ko.observable(true), }, { itemKey: "weight", name: ko.observable(Strings.ColumnTitle.weight), activatable: ko.observable(true), }, ]; this.gridVM.columns = ko.observableArray(columns); this.gridVM.showHeader = true; this.gridVM.summary = ko.observable(Strings.servicesListGridSummary); this.gridVM.noRowsMessage = ko.observable(Strings.loadingText); this._servicesView.loading.subscribeAndRun(container, function (isLoading) { return _this.gridVM.noRowsMessage(isLoading ? Strings.loadingText : Strings.noServicesInProject); }); this._id.subscribeAndRun(container, function (projectId) { return _this._servicesView.fetch(projectId); }); this._timespan.subscribe(container, function (timespan) { return _this._saveConfiguration(); }); this._sortColumn.subscribe(container, function (sortColumn) { return _this._saveConfiguration(); }); this._sortAscending.subscribe(container, function (sortAscending) { return _this._saveConfiguration(); }); }; ProjectBlade.prototype._initializeToolbar = function (container) { var commandBar = container.commandBar = new Toolbars.Toolbar(container); var deleteCommand = new Toolbars.DialogButton(); var deleteHelper = new ProjectCommands_1.ProjectDelete(this._id, ExtensionDefinition_1.BladeNames.projectBlade); deleteCommand.label(ProjectCommands_1.ProjectDelete.label); deleteCommand.icon(ProjectCommands_1.ProjectDelete.icon); deleteCommand.command = { canExecute: deleteHelper.canExecute, execute: function (result) { return deleteHelper.execute(result); }, }; deleteCommand.dialogOptions = ProjectCommands_1.ProjectDelete.messageBox; this._id.subscribeAndRun(container, function (id) { var move = new MoveButton.ViewModel(container, { resourceId: id }); commandBar.setItems([move, deleteCommand]); }); }; ProjectBlade.prototype._syncFromConfiguration = function (configuration) { var config = configuration.getValues(); log.debug(configuration, config); var settings = config.settings; var essentialsExpanded = settings.essentialsExpanded; var timespan = settings.timespan; var servicesSortColumn = settings.servicesSortColumn; var servicesSortAscending = settings.servicesSortAscending; this._essentialsExpanded(typeof essentialsExpanded === boolType ? essentialsExpanded : false); this._timespan(typeof timespan === stringType ? timespan : "forever"); this._sortColumn(typeof servicesSortColumn === stringType ? servicesSortColumn : "name"); this._sortAscending(typeof servicesSortAscending === boolType ? servicesSortAscending : true); }; ProjectBlade.prototype._saveConfiguration = function () { this.context.configuration.updateValues({ settings: { essentialsExpanded: this._essentialsExpanded(), timespan: this._timespan(), servicesSortColumn: this._sortColumn(), servicesSortAscending: this._sortAscending(), }, }); }; ProjectBlade.prototype._initializeEssentials = function (container) { var _this = this; this._id.subscribeAndRun(container, function (id) { return _this.essentials(id && new Essentials_1.ViewModel(container, { resourceId: id, expanded: _this._essentialsExpanded, additionalRight: [], })); }); var state = this._binder.binding(function (p) { return p.properties().provisioningState(); }); ko.reactor(container, function () { var essentialsVm = _this.essentials(); var projectState = state(); if (essentialsVm && projectState) { essentialsVm.modifyStatus(projectState); } }); this._essentialsExpanded.subscribe(container, function (expand) { return _this._saveConfiguration(); }); }; return ProjectBlade; }()); __decorate([ TemplateBlade.ProxiedMember ], ProjectBlade.prototype, "icon", void 0); ProjectBlade = __decorate([ TemplateBlade.Decorator({ htmlTemplate: "<div data-bind=\"pcControl: essentials\"></div>\n <div style=\"margin: 25px\">\n <div class=\"msportalfx-text-header\" data-bind=\"text: serviceListSectionTitle\"></div>\n <div data-bind=\"pcControl: gridVM\"></div>\n </div>", forAsset: { assetIdParameter: "id", assetType: ExtensionDefinition_1.AssetTypes.Project.name, }, }), TemplateBlade.Rebindable.Decorator(), TemplateBlade.Configurable.Decorator({ settings: { metadata: ResourceBladeConfigMetadata, scope: TemplateBlade.Configurable.SettingsScope.PerId, }, }), TemplateBlade.Pinnable.Decorator() ], ProjectBlade); exports.ProjectBlade = ProjectBlade; });
54.174129
481
0.596106
7593da88a45afe3517732fa5d61a7385a380339b
33
js
JavaScript
public/javascripts/public/grey/theme.js
ussrinivas/AndroidModelGenerator
06522f09dea2d58d8e30263e560489860a292b31
[ "MIT" ]
58
2015-08-11T13:25:31.000Z
2022-03-11T06:43:06.000Z
public/javascripts/public/grey/theme.js
ussrinivas/AndroidModelGenerator
06522f09dea2d58d8e30263e560489860a292b31
[ "MIT" ]
14
2017-04-06T13:05:10.000Z
2022-02-11T13:13:16.000Z
public/javascripts/public/grey/theme.js
ussrinivas/AndroidModelGenerator
06522f09dea2d58d8e30263e560489860a292b31
[ "MIT" ]
13
2018-02-28T23:24:32.000Z
2022-02-01T12:57:52.000Z
Syntax.themes["grey"] = ["base"]
16.5
32
0.606061
7594f414cab118b4e57a068c4123e95cb67be171
6,028
js
JavaScript
js/DOM.js
Sembiance/common
b9c8b73fac64e6fd3fd5c05b9d93ef4af169399a
[ "Unlicense" ]
21
2017-08-27T06:13:23.000Z
2022-01-17T23:52:34.000Z
js/DOM.js
Sembiance/common
b9c8b73fac64e6fd3fd5c05b9d93ef4af169399a
[ "Unlicense" ]
null
null
null
js/DOM.js
Sembiance/common
b9c8b73fac64e6fd3fd5c05b9d93ef4af169399a
[ "Unlicense" ]
5
2017-09-28T02:53:38.000Z
2020-12-13T07:22:48.000Z
"use strict"; /*global TextRectangle: true*/ // Adds several helper methods to the built in DOM elements if(typeof Element!=="undefined") { Element.prototype.getComputedStyle = function getComputedStyle() { return window.getComputedStyle(this); }; Element.prototype.getXY = function getXY() { const r=this.getBoundingClientRect(); return [r.left, r.top]; }; Element.prototype.getWidthHeight = function getWidthHeight() { return this.getDim(); }; Element.prototype.getDim = function getDim() { const r = this.getBoundingClientRect(); return [r.width, r.height]; }; // Polyfill for NODE.remove() if(!Element.prototype.remove) { Element.prototype.remove = function remove() { if(this.parentNode!==null) this.parentNode.removeChild(this); // eslint-disable-line unicorn/prefer-dom-node-remove }; } // Polyfill for NODE.before() if(!Element.prototype.before) { Element.prototype.before = function before(...args) { if(this.parentNode===null) return; args.forEach(arg => this.parentNode.insertBefore((typeof arg==="string" ? document.createTextNode(arg) : arg), this)); }; } Element.prototype.setText = function setText(text) { if(!this.childNodes || this.childNodes.length!==1) { this.innerHTML = ""; this.appendChild(document.createTextNode(text)); // eslint-disable-line unicorn/prefer-dom-node-append return this; } this.childNodes[0].nodeValue = text; return this; }; // PolyFill for NODE.append() if(!Element.prototype.append) { Element.prototype.append = function append(...args) { args.forEach(arg => this.appendChild((typeof arg==="string" ? document.createTextNode(arg) : arg))); // eslint-disable-line unicorn/prefer-dom-node-append }; } // Returns the first prev sibling that the passed in function returns true to upon receiving it passed in Element.prototype.getPreviousSibling = function getPreviousSibling(f) { for(let c=this;c;c=c.previousSibling) // eslint-disable-line consistent-this { if(f(c)) return c; if(c.nodeName.toLowerCase()==="html") return null; } return null; }; // Returns the first sibling that the passed in function returns true to upon receiving it passed in Element.prototype.getNextSibling = function getNextSibling(f) { for(let c=this.nextSibling;c;c=c.nextSibling) { if(f(c)) return c; if(c.nodeName.toLowerCase()==="html") return null; } return null; }; // Returns the first ancestor that the passed in function returns true to upon receiving it passed in Element.prototype.getAncestor = function getAncestor(f) { for(let c=this;c;c=c.parentNode) // eslint-disable-line consistent-this { if(f(c)) return c; if(c.nodeName.toLowerCase()==="html") return null; } return null; }; // Returns the width of one em for this element Element.prototype.getEmWidth = function getEmWidth() { const computedFontSize = this.getComputedStyle().fontSize; if(!computedFontSize) return 16; const matchedParts = computedFontSize.match(/(\d+(\.\d+)?)px$/); // eslint-disable-line prefer-named-capture-group if(!matchedParts || matchedParts.length<2 || !matchedParts[1]) return 16; return Number(matchedParts[1]); }; // Returns the elements width Element.prototype.getWidth = function getWidth() { return this.getBoundingClientRect().width; }; // Returns the elements height Element.prototype.getHeight = function getHeight() { return this.getBoundingClientRect().height; }; // Returns the elements computed padding width Element.prototype.getPaddingWidth = function getPaddingWidth() { const cs = this.getComputedStyle(); return (parseFloat(cs.paddingLeft)+parseFloat(cs.paddingRight)); }; // Returns the elements computed padding height Element.prototype.getPaddingHeight = function getPaddingHeight() { const cs = this.getComputedStyle(); return (parseFloat(cs.paddingTop)+parseFloat(cs.paddingBottom)); }; // Returns the elements computed margin width Element.prototype.getMarginWidth = function getMarginWidth() { const cs = this.getComputedStyle(); return (parseFloat(cs.marginLeft)+parseFloat(cs.marginRight)); }; // Returns the elements computed margin height Element.prototype.getMarginHeight = function getMarginHeight() { const cs = this.getComputedStyle(); return (parseFloat(cs.marginTop)+parseFloat(cs.marginBottom)); }; // Disables the element by setting the disabled attribute and class Element.prototype.disable = function disable() { this.classList.add("disabled"); this.setAttribute("disabled", "disabled"); }; // Enables the element by removing the disabled attribute and class Element.prototype.enable = function enable() { this.classList.remove("disabled"); this.removeAttribute("disabled"); }; // Safely scrolls the element into view. Currently only supports vevrtical movement. // .scrollIntoView should always be avoided due to it moving the whole darn screen if anything at all is offscreen. Piece of junk that function is. Element.prototype.safeScrollIntoView = function safeScrollIntoView(scrollParent) { const thisHeight = this.getHeight(); const thisBottomOffset = (this.offsetTop + thisHeight); if(scrollParent.scrollTop>thisBottomOffset || (scrollParent.scrollTop+scrollParent.getHeight())<thisBottomOffset) scrollParent.scrollTop = this.offsetTop - ((scrollParent.getHeight()-thisHeight)/2); }; // Alias classList.includes() to classList.contains() to match the standard way of doing things with Array/String DOMTokenList.prototype.includes = function includes(...args) { return this.contains(...args); }; } // Adds width/height properties to getBoundingClientRect for IE8 if("TextRectangle" in window && !("width" in TextRectangle.prototype)) Object.defineProperties(TextRectangle.prototype, { "width" : { get : function() { return this.right-this.left; } }, "height" : { get : function() { return this.bottom-this.top; } } }); // eslint-disable-line object-shorthand
29.120773
225
0.723623
75951a5e7831064f3d26d49b57299cda3be20c89
7,203
js
JavaScript
node_modules/imager/node_modules/pkgcloud/lib/pkgcloud/rackspace/storage/client/containers.js
SFDevLabs/gridlum
081d1c14f3f15d72b65de68d765e3772e9646888
[ "MIT" ]
null
null
null
node_modules/imager/node_modules/pkgcloud/lib/pkgcloud/rackspace/storage/client/containers.js
SFDevLabs/gridlum
081d1c14f3f15d72b65de68d765e3772e9646888
[ "MIT" ]
null
null
null
node_modules/imager/node_modules/pkgcloud/lib/pkgcloud/rackspace/storage/client/containers.js
SFDevLabs/gridlum
081d1c14f3f15d72b65de68d765e3772e9646888
[ "MIT" ]
null
null
null
/* * containers.js: Instance methods for working with containers from Rackspace Cloudfiles * * (C) 2011 Nodejitsu Inc. * */ var async = require('async'), request = require('request'), base = require('../../../core/storage'), pkgcloud = require('../../../../../lib/pkgcloud'), _ = require('underscore'), storage = pkgcloud.providers.rackspace.storage; // // ### function getContainers (callback) // #### @options {object} Options for the getContainers call // #### @callback {function} Continuation to respond to when complete. // Gets all Rackspace Cloudfiles containers for this instance. // exports.getContainers = function (options, callback) { var self = this; if (typeof options === 'function') { callback = options; options = {}; } var getContainerOpts = { path: '', qs: { format: 'json' } }; if (options.limit) { getContainerOpts.qs.limit = options.limit; } if (options.marker) { getContainerOpts.qs.marker = options.marker; } this.request(getContainerOpts, function (err, body) { if (err) { return callback(err); } else if (!body || !(body instanceof Array)) { return new Error('Malformed API Response') } if (!options.loadCDNAttributes) { return callback(null, body.map(function (container) { return new storage.Container(self, container); })); } else { var containers = []; async.forEachLimit(body, 10, function(c, next) { var container = new storage.Container(self, c); containers.push(container); container.refreshCdnDetails(function(err) { if (err) { return next(err); } next(); }) }, function(err) { callback(err, containers); }); } }); }; // // ### function getContainer (container, callback) // #### @container {string|storage.Container} Name of the container to return // #### @callback {function} Continuation to respond to when complete. // Responds with the Rackspace Cloudfiles container for the specified // `container`. // exports.getContainer = function (container, callback) { var containerName = container instanceof storage.Container ? container.name : container, self = this; this.request({ method: 'HEAD', container: containerName }, function (err, body, res) { if (err) { return callback(err); } self._getCdnContainerDetails(containerName, function(err, details) { if (err) { return callback(err); } container = _.extend({}, details, { name: containerName, count: parseInt(res.headers['x-container-object-count'], 10), bytes: parseInt(res.headers['x-container-bytes-used'], 10) }); container.metadata = self.deserializeMetadata(self.CONTAINER_META_PREFIX, res.headers); callback(null, new (storage.Container)(self, container)); }); }); }; // // ### function createContainer (options, callback) // #### @options {string|Container} Container to create in Rackspace Cloudfiles. // #### @callback {function} Continuation to respond to when complete. // Creates the specified `container` in the Rackspace Cloudfiles associated // with this instance. // exports.createContainer = function (options, callback) { var containerName = typeof options === 'object' ? options.name : options, self = this; var createContainerOpts = { method: 'PUT', container: containerName }; if (options.metadata) { createContainerOpts.headers = self.serializeMetadata(self.CONTAINER_META_PREFIX, options.metadata); } this.request(createContainerOpts, function (err) { return err ? callback(err) : callback(null, new (storage.Container)(self, { name: containerName, metadata: options.metadata })); }); }; // // ### function updateContainerMetadata (container, callback) // #### @container {Container} Container to update in Rackspace Cloudfiles. // #### @callback {function} Continuation to respond to when complete. // Updates the metadata in the specified `container` in the Rackspace Cloudfiles associated // with this instance. // exports.updateContainerMetadata = function (container, callback) { this._updateContainerMetadata(container, this.serializeMetadata(this.CONTAINER_META_PREFIX, container.metadata), callback); }; // // ### function removeContainerMetadata (container, callback) // #### @container {Container} Container to remove metadata from in Rackspace Cloudfiles. // #### @metadataToRemove {object} object with keys representing metadata to remove // #### @callback {function} Continuation to respond to when complete. // Removes the provided `metadata` in the specified `container` in the Rackspace Cloudfiles associated // with this instance. // exports.removeContainerMetadata = function (container, metadataToRemove, callback) { this._updateContainerMetadata(container, this.serializeMetadata(this.CONTAINER_REMOVE_META_PREFIX, metadataToRemove), callback); }; // // ### function _updateContainerMetadata (container, headers, callback) // #### @container {Container} Container to update with provided header metadata in Rackspace Cloudfiles. // #### @metadata {object} Raw headers to pass as part of the update call. // #### @callback {function} Continuation to respond to when complete. // Updates the specified `container` with the provided metadata `headers`in the Rackspace Cloudfiles associated // with this instance. // exports._updateContainerMetadata = function(container, metadata, callback) { var self = this; if (!(container instanceof base.Container)) { throw new Error('Must update an existing container instance'); } var updateContainerOpts = { method: 'POST', container: container.name, headers: metadata }; this.request(updateContainerOpts, function (err) { // omit our newly deleted header fields, if any if (!err) { container.metadata = _.omit(container.metadata, _.keys(self.deserializeMetadata(self.CONTAINER_REMOVE_META_PREFIX, metadata))); } return err ? callback(err) : callback(null, container); }); }; // // ### function destroyContainer (container, callback) // #### @container {string} Name of the container to destroy // #### @callback {function} Continuation to respond to when complete. // Destroys the specified `container` and all files in it. // exports.destroyContainer = function (container, callback) { var containerName = container instanceof base.Container ? container.name : container, self = this; this.getFiles(container, function (err, files) { if (err) { return callback(err); } function deleteContainer(err) { if (err) { return callback(err); } self.request({ method: 'DELETE', container: containerName }, function(err) { return err ? callback(err) : callback(null, true); }); } function destroyFile(file, next) { file.remove(next); } if (files.length === 0) { return deleteContainer(); } async.forEach(files, destroyFile, deleteContainer); }); };
29.520492
111
0.667777
75951c0492cacb14b3c8ab4674f251370cd283db
2,194
js
JavaScript
src/core/domRenderer/attachEvents.js
Datanautika/ash
46d873444c55eda4a84f8266dba5fd1ad1e54fcc
[ "MIT" ]
2
2016-01-29T02:58:25.000Z
2017-05-16T05:27:31.000Z
src/core/domRenderer/attachEvents.js
Datanautika/ash
46d873444c55eda4a84f8266dba5fd1ad1e54fcc
[ "MIT" ]
null
null
null
src/core/domRenderer/attachEvents.js
Datanautika/ash
46d873444c55eda4a84f8266dba5fd1ad1e54fcc
[ "MIT" ]
null
null
null
import constants from '../internals/constants'; import isFunction from '../internals/isFunction'; import parseAshNodeId from './parseAshNodeId'; import topics from './events'; const ID_ATTRIBUTE_NAME = constants.ID_ATTRIBUTE_NAME; const STREAM_ID_ATTRIBUTE_NAME = constants.STREAM_ID_ATTRIBUTE_NAME; const INDEX_SEPARATOR = constants.INDEX_SEPARATOR; /** * Handles fired events. * * @param {string} eventName * @param {Event} event */ function eventHandler(eventName, event) { let id = event.target[ID_ATTRIBUTE_NAME]; let streamId = event.target[STREAM_ID_ATTRIBUTE_NAME]; if (id) { let indices = parseAshNodeId(id); while (indices.length) { for (let i = 0; i < topics[eventName].length; i++) { if (topics[eventName][i].id === id && topics[eventName][i].streamId === streamId) { topics[eventName][i].callback(event); } } indices.pop(); id = indices.join(INDEX_SEPARATOR); } } } /** * Ataches events descried by `events` to the `node`. * If the node is newly inserted, `isNewlyInserted` must be set to true, so the node ids aren't overridden during eventual events reindexing. * * @param {Node} node * @param {Object} events * @param {boolean} isNewlyInserted */ export default function attachEvents(node, events, isNewlyInserted) { for (let eventName in events) { if (events.hasOwnProperty(eventName) && isFunction(events[eventName])) { if (!topics[eventName]) { topics[eventName] = []; global.document.addEventListener(eventName, eventHandler.bind(this, eventName), true); } for (let i = 0; i < topics[eventName].length; i++) { if (topics[eventName][i].streamId === node[STREAM_ID_ATTRIBUTE_NAME] && topics[eventName][i].id === node[ID_ATTRIBUTE_NAME]) { topics[eventName][i].callback = events[eventName]; topics[eventName][i].isNewlyInserted = !!isNewlyInserted; return; } } // push new event topics[eventName].push({ id: node[ID_ATTRIBUTE_NAME], streamId: node[STREAM_ID_ATTRIBUTE_NAME], callback: events[eventName], isNewlyInserted: !!isNewlyInserted, isReindexed: {} }); } } }
29.253333
142
0.670921
7596d68f5eea33b292a440c39401426021767bb3
2,693
js
JavaScript
src/index.js
mix3d/music-helper
e7538b21077bace42d9998095d408d39fcc7704b
[ "MIT" ]
null
null
null
src/index.js
mix3d/music-helper
e7538b21077bace42d9998095d408d39fcc7704b
[ "MIT" ]
2
2021-03-09T22:47:36.000Z
2021-05-10T19:15:15.000Z
src/index.js
mix3d/music-helper
e7538b21077bace42d9998095d408d39fcc7704b
[ "MIT" ]
null
null
null
import Vex from "vexflow/src/index.js"; import { KeySignature } from 'vexflow/src/keysignature.js'; // Create an SVG renderer and attach it to the DIV element named "boo". const vexflowdiv = document.getElementById("music"); const renderer = new Vex.Flow.Renderer( vexflowdiv, Vex.Flow.Renderer.Backends.SVG ); let width = window.innerWidth; let height = window.innerHeight; let scale = 2; // Size our svg: renderer.resize(width, height-64); window.addEventListener("resize", () => { width = window.innerWidth; height = window.innerHeight; renderer.resize(width, height-64); drawStaff(); }); // And get a drawing context: const context = renderer.getContext(); context.scale(scale, scale); // From other guy: // context.options.scaleToContainer = true; let stave = new Vex.Flow.Stave(10, 0, width / scale - 20, {}); const clefSelector = document.getElementById("clef"); const keySelector = document.getElementById("key"); const majorKeys = [ "C", "F", "Bb", "Eb", "Ab", "Db", "Gb", "Cb", "G", "D", "A", "E", "B", "F#", "C#" ]; const minorKeys = [ 'Am', 'Dm', 'Gm', 'Cm', 'Fm', 'Bbm', 'Ebm', 'Abm', 'Em', 'Bm', 'F#m', 'C#m', 'G#m', 'D#m', 'A#m', ]; // Create the dropdown items // TODO: make this a popup with visual key selector majorKeys.forEach(key => { let o = document.createElement('option') o.value = key; o.textContent = key; keySelector.children.majorKey.appendChild(o) }) minorKeys.forEach(key => { let o = document.createElement('option') o.value = key; o.textContent = key; keySelector.children.minorKey.appendChild(o) }) clefSelector.oninput = ev => { stave.setClef(clefSelector.value); // FIXME IN SOURCE: update key signatures // stave.setKeySignature(keySelector.value) // const keySignatures = stave.getModifiers(); // keySignatures.filter(key => key.category === KeySignature.CATEGORY).forEach(key => { // key.setKeySig(keySelector.value) // key.format() // }) drawStaff(); }; keySelector.oninput = ev => { stave.setKeySignature(keySelector.value) drawStaff() } // Initialize Stave from DOM stave.setClef(clefSelector.value); stave.setKeySignature(keySelector.value) // Connect it to the rendering context and draw! stave.setContext(context).draw(); function drawStaff() { context.scale(context.state.scale.x, context.state.scale.y); stave.setWidth(width / scale - 20); context.clear(); stave.draw(); } let svgPt; function domToSvg(svg, point) { if (!svgPt) svgPt = svg.createSVGPoint(); svgPt.x = point.x; svgPt.y = point.y; var sp = svgPt.matrixTransform(svg.getScreenCTM().inverse()); return { x: sp.x, y: sp.y }; }
21.039063
89
0.663201
75976dd14b9ac74d9185aa5e25db420f9ebcd40f
216
js
JavaScript
src/utils/link.js
adapttive/strapi-starter-gridsome-blog
67f408d7704cf021360aa8ac7e45d1a9c37d325b
[ "MIT" ]
1
2021-07-15T08:17:15.000Z
2021-07-15T08:17:15.000Z
src/utils/link.js
adapttive/strapi-starter-gridsome-blog
67f408d7704cf021360aa8ac7e45d1a9c37d325b
[ "MIT" ]
null
null
null
src/utils/link.js
adapttive/strapi-starter-gridsome-blog
67f408d7704cf021360aa8ac7e45d1a9c37d325b
[ "MIT" ]
1
2021-08-15T11:54:48.000Z
2021-08-15T11:54:48.000Z
export function getUrl (slug, type) { let prefix = type if (type === 'blog-category') { prefix = 'blog/category' } else if (type === 'blog-tag') { prefix = 'blog/tag' } return prefix + '/' + slug }
21.6
37
0.569444
75980210c6ea2185ca1ea1230350a37e480e009b
645
js
JavaScript
backend/src/routes.js
rafaelsene01/TesteNagro
58b3c8a249f11cc58335ca4c2791fa4a06181dc1
[ "MIT" ]
null
null
null
backend/src/routes.js
rafaelsene01/TesteNagro
58b3c8a249f11cc58335ca4c2791fa4a06181dc1
[ "MIT" ]
null
null
null
backend/src/routes.js
rafaelsene01/TesteNagro
58b3c8a249f11cc58335ca4c2791fa4a06181dc1
[ "MIT" ]
null
null
null
import { Router } from 'express'; import PessoaController from './app/controllers/PessoaController'; import ImovelController from './app/controllers/ImovelController'; const routes = new Router(); routes.get('/grower', PessoaController.index); routes.post('/grower', PessoaController.store); routes.put('/grower/:id', PessoaController.update); routes.delete('/grower/:id', PessoaController.delete); routes.get('/properties', ImovelController.index); routes.post('/properties', ImovelController.store); routes.put('/properties/:id', ImovelController.update); routes.delete('/properties/:id', ImovelController.delete); export default routes;
33.947368
66
0.772093
7598024a4f70dc8960fc134ee65afc967b64e7a0
342
js
JavaScript
index.js
scola84/node-api-codec-deflate
002ebfdf6566eff405732eed9bc6eff4a35c65b3
[ "MIT" ]
null
null
null
index.js
scola84/node-api-codec-deflate
002ebfdf6566eff405732eed9bc6eff4a35c65b3
[ "MIT" ]
null
null
null
index.js
scola84/node-api-codec-deflate
002ebfdf6566eff405732eed9bc6eff4a35c65b3
[ "MIT" ]
null
null
null
const encoding = 'deflate'; import { Inflate as Decoder, Deflate as Encoder } from 'zlib'; export const codec = { Decoder, Encoder, encoding }; export function decoder() { return { encoding, create: () => new Decoder() }; } export function encoder() { return { encoding, create: () => new Encoder() }; }
12.666667
31
0.602339
7598fc68561d10010f6b78bff7c1af55910c5401
700
js
JavaScript
src/components/ListPosts/index.js
Rodrizio343/unep-react
b2490e5be53d5cd6da538b152f05cffcc7979ac9
[ "MIT" ]
null
null
null
src/components/ListPosts/index.js
Rodrizio343/unep-react
b2490e5be53d5cd6da538b152f05cffcc7979ac9
[ "MIT" ]
null
null
null
src/components/ListPosts/index.js
Rodrizio343/unep-react
b2490e5be53d5cd6da538b152f05cffcc7979ac9
[ "MIT" ]
null
null
null
import React from 'react' import { useQuery } from '@apollo/client' import {GET_ALL_POSTS} from 'graphql/querys/posts'; import PostItem from 'components/PostItem' import './ListPosts.css' import Spinner from 'components/Spinner'; const ListPosts = () => { const {data, error, loading} = useQuery(GET_ALL_POSTS) const {posts} = data || ""; if(loading) return <Spinner /> if(error) return "Ups, algo salio mal..." return ( <div className="posts-grid"> {posts.map((post) => ( <PostItem title={post.title} description={post.content} key={post.id} id={post.id}/> )) } </div> ) } export default ListPosts
26.923077
100
0.605714
7599244697e6bf5b6aedb4f623fe30a54e6a05e7
855
js
JavaScript
js/preload.js
babelshift/Spigot
1611445f2687e418b49de1bf6128e1f98a85cbe8
[ "MIT" ]
null
null
null
js/preload.js
babelshift/Spigot
1611445f2687e418b49de1bf6128e1f98a85cbe8
[ "MIT" ]
3
2020-10-06T15:18:43.000Z
2021-01-28T20:55:05.000Z
js/preload.js
babelshift/Spigot
1611445f2687e418b49de1bf6128e1f98a85cbe8
[ "MIT" ]
null
null
null
const { contextBridge, ipcRenderer, net } = require('electron'); // Expose protected methods that allow the renderer process to use // the ipcRenderer without exposing the entire object contextBridge.exposeInMainWorld( "api", { send: (channel, data) => { // whitelist channels let validChannels = ["getAppStoreDetails", "playGame", "viewInSteam", "getPlayerCount", "selectSteamFolder"]; if (validChannels.includes(channel)) { ipcRenderer.send(channel, data); } }, receive: (channel, func) => { let validChannels = ["fromMain", "getPlayerCountResponse", "selectSteamFolderResponse"]; if (validChannels.includes(channel)) { // Deliberately strip event as it includes `sender` ipcRenderer.on(channel, (event, ...args) => func(...args)); } } });
40.714286
117
0.638596
7599e36110cbf2179cacba29f4e39472492799d5
247
js
JavaScript
public/assets/js/forgot-password.controller.js
Darragh-McCarthy/Harpoon
3fa20d851ba76a48fa64f40bd69b495dae635b0f
[ "MIT" ]
1
2017-10-14T01:32:16.000Z
2017-10-14T01:32:16.000Z
public/assets/js/forgot-password.controller.js
Darragh-McCarthy/Harpoon
3fa20d851ba76a48fa64f40bd69b495dae635b0f
[ "MIT" ]
null
null
null
public/assets/js/forgot-password.controller.js
Darragh-McCarthy/Harpoon
3fa20d851ba76a48fa64f40bd69b495dae635b0f
[ "MIT" ]
null
null
null
(function(){ 'use strict'; angular.module('harpoonAjaxLogin') .controller('ForgotPassword', ForgotPassword); ForgotPassword.$inject=[]; function ForgotPassword() { var _this = this; _this.headerTestText = 'Controller is working!'; } })();
15.4375
49
0.712551
759ab283824166e219b60a4648ff2eb6a550b1c5
1,909
js
JavaScript
app.js
gatsbimantico/cv
136636de64c4e0a5cc95b1223f20007ee52319a6
[ "Unlicense" ]
null
null
null
app.js
gatsbimantico/cv
136636de64c4e0a5cc95b1223f20007ee52319a6
[ "Unlicense" ]
null
null
null
app.js
gatsbimantico/cv
136636de64c4e0a5cc95b1223f20007ee52319a6
[ "Unlicense" ]
null
null
null
import { location } from './utils/index.js'; import native from './utils/native-components.js'; import CandidatePage from './pages/candidate.js'; import { applyTheme } from './controllers/theme-styles/theme-style.js'; const externalCV = location.current.searchParams.get('cv'); const username = location.current.searchParams.get('u'); Promise.all([ import(externalCV || '/cv/cv.js').then(r => r.default), username ? fetch(`https://api.github.com/users/${username}/gists`) .then(r => r.json()) .then(gists => fetch( gists .filter(a => a.files['resume.json']) .sort((a, b) => b.updated_at > a.updated_at)[0] .files['resume.json'].raw_url ).then(r => r.json()) .catch(() => null)) .catch(() => null) : null, fetch('./manifest.json').then(r => r.json()), fetch('./package.json').then(r => r.json()), ]) .then(([cvJs, cvJson, manifest, pkg]) => { const cv = cvJson || cvJs; native.setTitle(`${cv.basics.name} (${cv.basics.label}) ${manifest.name}`); Promise.all([ // native.addStyleSheet('https://fonts.googleapis.com/css?family=Nanum+Gothic:400,700|Work+Sans:300,600&display=swap'), native.addStyleSheet('./css/candidate.css'), ]).then(() => { native.render(CandidatePage({ cv, manifest })); applyTheme({ color: cv.color }); }); if ( manifest.version === pkg.version && // to skip the service worker on development 'serviceWorker' in navigator ) { navigator.serviceWorker.register('./service-worker.js'); } }) .catch((err) => { native.render(` <div style="height:50px;position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);"> ${err} </div> `); }); window.onload = function () { document.getElementsByTagName('body')[0].className += 'loaded'; }
34.709091
126
0.585123
759abb09a57712dd8bad4ca5a4849f06277e1527
737
js
JavaScript
storage-ext/lib/cluster.js
guywmartin/genetic-constructor-ce
8ea6382d52d2b1ed6d2c2282120491d09f22e623
[ "Apache-2.0" ]
13
2017-05-11T05:53:58.000Z
2022-02-04T00:23:20.000Z
storage-ext/lib/cluster.js
guywmartin/genetic-constructor-ce
8ea6382d52d2b1ed6d2c2282120491d09f22e623
[ "Apache-2.0" ]
1
2020-09-04T04:10:28.000Z
2020-09-04T04:10:28.000Z
storage-ext/lib/cluster.js
kingdavid72/VectorDesign
8ea6382d52d2b1ed6d2c2282120491d09f22e623
[ "Apache-2.0" ]
8
2017-06-07T21:26:40.000Z
2021-08-07T23:44:17.000Z
"use strict"; var cluster = require('cluster'); var numCPUs = require('os').cpus().length; var config = require('./config'); var PORT = config.lookup("apiPort"); var dbInit = require('./db-init'); if (cluster.isMaster) { // make sure the DB is ready dbInit(function () { // Fork workers for (var i = 0; i < numCPUs; i++) { cluster.fork(); } cluster.on('exit', (worker, code, signal) => { console.log(`worker ${worker.process.pid} died`); cluster.fork(); }); }); } else { // Workers can share any TCP connection // In this case it is an HTTP server var app = require('./app')(); app.listen(PORT, function () { console.log('Process ' + process.pid + ' is listening.'); }); }
22.333333
61
0.588874
759c0f1d11714d60c7fc74484a221e49f133c14e
2,418
js
JavaScript
src/components/About Us/about-section.js
hellomarksmart/markavo-website
50783126ccf3f691526f54c7b2e6ac9ec7fb9235
[ "0BSD" ]
null
null
null
src/components/About Us/about-section.js
hellomarksmart/markavo-website
50783126ccf3f691526f54c7b2e6ac9ec7fb9235
[ "0BSD" ]
97
2022-01-19T10:47:48.000Z
2022-03-29T11:27:16.000Z
src/components/About Us/about-section.js
hellomarksmart/markavo-website
50783126ccf3f691526f54c7b2e6ac9ec7fb9235
[ "0BSD" ]
null
null
null
import * as React from "react" const AboutSection = ({ heading, description, about_items }) => { return ( <div className="bg-white"> <div className="max-w-default mx-auto px-4 py-0 px-4 sm:px-6 lg:px-8 lg:pt-16"> <div className="space-y-12 xl:grid xl:grid-cols-3 xl:gap-8 xl:space-y-0"> <div className="space-y-5 sm:space-y-4"> <h2 className="text-3xl font-extrabold tracking-tight sm:text-3.5xl"> {heading} </h2> <p className="text-lg text-gray-500">{description}</p> </div> <div className="lg:col-span-2"> <ul className="space-y-12 sm:divide-y sm:divide-gray-200 sm:space-y-0 sm:-mt-8 lg:gap-x-8 lg:space-y-0 ml-0"> {about_items?.map((item, i) => { return ( <li key={i} className="mb-0 sm:py-7"> <div className="w-full space-y-4 sm:space-y-0 sm:flex sm:flex-col md:flex-row"> <div className="md:w-medium xl:max-w-medium"> <img className="w-full h-imageH_sm object-cover shadow-lg rounded-lg sm:h-imageH sm:w-imageW " src={item?.image.url} alt={item?.image.alt ? item?.image.alt : ""} /> </div> <div className="w-full w-full sm:col-span-2 sm:pt-6 md:pt-0 md:w-twoThirds"> <div className="space-y-4 mt-0"> <div className="leading-6 font-medium space-y-1"> <h3 className="mb-1 text-base"> {item?.name.text} </h3> <p className="text-emerald-600 text-base pb-3"> {item?.position.text} </p> </div> <div className="text-lg"> <p className="text-gray-500 text-base -mt-4"> {item?.description.text} </p> </div> </div> </div> </div> </li> ) })} </ul> </div> </div> </div> </div> ) } export default AboutSection
42.421053
121
0.418941
759c3aaf3e242fb8be018a67cd5313e8cb1518b0
1,362
js
JavaScript
FillNums.js
hhelenxu/SudokuGame
0eac6b8f8f7c769b357aa84e1d3a9c4839aa876a
[ "MIT" ]
1
2020-12-10T05:55:49.000Z
2020-12-10T05:55:49.000Z
FillNums.js
hhelenxu/SudokuGame
0eac6b8f8f7c769b357aa84e1d3a9c4839aa876a
[ "MIT" ]
null
null
null
FillNums.js
hhelenxu/SudokuGame
0eac6b8f8f7c769b357aa84e1d3a9c4839aa876a
[ "MIT" ]
null
null
null
import React, { useState } from 'react'; import { StyleSheet, Text, TouchableHighlight } from 'react-native'; import { changeSelected } from './Sudoku'; export const FillNums = (props) => { const [selected, setSelected] = useState(props.selected); return ( <TouchableHighlight onPress={() => { changeSelected(props.num); setSelected(!selected); props.onChange(props.num); }} style={[styles.Box, props.selected ? styles.selected : styles.unselected]}> <Text style={props.num=='-1' ? styles.small : styles.text}> {props.num==-1 ? 'erase' : props.num} </Text> </TouchableHighlight> ) } const styles = StyleSheet.create({ Box: { marginRight: 10, marginLeft: 10, marginTop: 10, paddingTop: 3, paddingBottom: 3, paddingRight: 10, paddingLeft: 10, borderRadius: 5, borderWidth: 1, borderColor: 'black', width: 50, justifyContent: 'center' }, selected: { backgroundColor: 'grey', }, unselected: { backgroundColor: 'white', }, text: { fontSize: 40, color: '#007AFF', textAlign: 'center' }, small: { fontSize: 20, color: '#007AFF', textAlign: 'center', } })
26.192308
86
0.541116
759cd6319313177e5e99900aebede4868e3fab05
26
js
JavaScript
src/assets/lib-calc.js
zsckare/cosasbebo
a9dc57ef7c7d5e88ca3d0f5ac4fdef80955af781
[ "MIT" ]
8
2020-05-23T14:52:00.000Z
2021-07-03T05:03:56.000Z
src/assets/lib-calc.js
MaxCodeXTC/ecommerce-biolerplate
1f414539b1b29b9c7b8e0772ed65e549f6b25156
[ "MIT" ]
6
2021-05-11T15:04:24.000Z
2022-02-19T02:36:23.000Z
src/assets/lib-calc.js
MaxCodeXTC/ecommerce-biolerplate
1f414539b1b29b9c7b8e0772ed65e549f6b25156
[ "MIT" ]
6
2020-05-26T08:57:31.000Z
2022-01-22T15:04:17.000Z
// add calc functions here
26
26
0.769231
759cd851c1d48f27a9a1884d033f0c1f52396524
486
js
JavaScript
scripts/documentready.js
strangecyan/Material-Inbox
ec10bca0f5adf6a7e8b4dbd06dae988c8a7d5b00
[ "BSD-3-Clause" ]
null
null
null
scripts/documentready.js
strangecyan/Material-Inbox
ec10bca0f5adf6a7e8b4dbd06dae988c8a7d5b00
[ "BSD-3-Clause" ]
null
null
null
scripts/documentready.js
strangecyan/Material-Inbox
ec10bca0f5adf6a7e8b4dbd06dae988c8a7d5b00
[ "BSD-3-Clause" ]
null
null
null
$( document ).ready(function() { //PLUGIN INIT //fastclick.js init $(function() { //FastClick.attach(document.body); }); //HOVER EVENTS messagehoverinit(); $( ".canspring").hover( function() { $(this).addClass('sprung'); $(this).find('.springboardlabel').addClass('addedlabel') }, function() { $(this).removeClass('sprung'); $(this).find('.springboardlabel').removeClass('addedlabel') } ); newinput(); newinput(); newinput(); });
17.357143
64
0.592593
759d2022777c7ecdcfd3497e2d53ba3deda8cbec
4,363
js
JavaScript
lib/contextify.js
bucharest-gold/huilu
373f22bff91799f9ebcdc7d6962be0cdafda3648
[ "Apache-2.0" ]
null
null
null
lib/contextify.js
bucharest-gold/huilu
373f22bff91799f9ebcdc7d6962be0cdafda3648
[ "Apache-2.0" ]
4
2016-09-14T13:39:09.000Z
2017-05-08T20:29:43.000Z
lib/contextify.js
bucharest-gold/huilu
373f22bff91799f9ebcdc7d6962be0cdafda3648
[ "Apache-2.0" ]
2
2016-11-04T17:29:44.000Z
2021-01-31T23:23:45.000Z
'use strict'; const xtend = require('xtend'); const format = require('util').format; const colorMap = require('./color-map'); // TODO: fix unused - remove this when thigs get stable. // function inspect (obj, depth) { // console.error(require('util').inspect(obj, false, depth || 5, true)); // } const oneDecimal = (x) => (Math.round(x * 10) / 10); const htmlEscape = (s) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;'); /** * Extracts a context object from the parsed callgraph @see `stackparse.js`. * This context can then be used to generate the svg file via a template. * * @name contextify * @private * @function * @param {Object} parsed nodes * @param {Object} opts options that affect visual and how the nodes are filtered */ // Contextifier proto function contextify (parsed, opts) { let time = parsed.time; let timeMax = opts.timemax; let ypadTop = opts.fontsize * 4; // pad top, include title let ypadBottom = opts.fontsize * 2 + 10; // pad bottom, include labels let xpad = 10; // pad left and right let depthMax = 0; let frameHeight = opts.frameheight; let paletteMap = {}; if (timeMax < time && timeMax / time > 0.02) { console.error('Specified timemax %d is less than actual total %d, so it will be ignored', timeMax, time); timeMax = Infinity; } timeMax = Math.min(time, timeMax); let widthPerTime = (opts.imagewidth - 2 * xpad) / timeMax; let minWidthTime = opts.minwidth / widthPerTime; function markNarrowBlocks (nodes) { function mark (k) { var val = parsed.nodes[k]; if (typeof val.stime !== 'number') throw new Error('Missing start for ' + k); if ((val.etime - val.stime) < minWidthTime) { val.narrow = true; return; } val.narrow = false; depthMax = Math.max(val.depth, depthMax); } Object.keys(nodes).forEach(mark); } // NodeProcessor proto function processNode (node) { let func = node.func; let depth = node.depth; let etime = node.etime; let stime = node.stime; let factor = opts.factor; let countName = opts.countname; let isRoot = !func.length && depth === 0; if (isRoot) etime = timeMax; let samples = Math.round((etime - stime * factor) * 10) / 10; let samplesTxt = samples.toLocaleString(); let pct; let pctTxt; let escapedFunc; let name; let sampleInfo; if (isRoot) { name = 'all'; sampleInfo = format('(%s %s, 100%)', samplesTxt, countName); } else { pct = Math.round((100 * samples) / (timeMax * factor) * 10) / 10; pctTxt = pct.toLocaleString(); escapedFunc = htmlEscape(func); name = escapedFunc; sampleInfo = format('(%s %s), %s%%)', samplesTxt, countName, pctTxt); } let x1 = oneDecimal(xpad + stime * widthPerTime); let x2 = oneDecimal(xpad + etime * widthPerTime); let y1 = oneDecimal(imageHeight - ypadBottom - (depth + 1) * frameHeight + 1); let y2 = oneDecimal(imageHeight - ypadBottom - depth * frameHeight); let chars = (x2 - x1) / (opts.fontsize * opts.fontwidth); let showText = false; let text; if (chars >= 3) { // enough room to display function name? showText = true; text = func.slice(0, chars); if (chars < func.length) text = text.slice(0, chars - 2) + '..'; text = htmlEscape(text); } return { name: name, search: name.toLowerCase(), samples: sampleInfo, rect_x: x1, rect_y: y1, rect_w: x2 - x1, rect_h: y2 - y1, rect_fill: colorMap.colorMap(paletteMap, opts.colors, opts.hash, func), text: text, text_x: x1 + (showText ? 3 : 0), text_y: 3 + (y1 + y2) / 2, narrow: node.narrow, func: htmlEscape(func) }; } function processNodes (nodes) { const keys = Object.keys(nodes); let acc = new Array(keys.length); for (var i = 0; i < keys.length; i++) { acc[i] = processNode(nodes[keys[i]]); } return acc; } markNarrowBlocks(parsed.nodes); let imageHeight = (depthMax * frameHeight) + ypadTop + ypadBottom; let ctx = xtend(opts, { imageheight: imageHeight, xpad: xpad, titleX: opts.imagewidth / 2, detailsY: imageHeight - (frameHeight / 2) }); ctx.nodes = processNodes(parsed.nodes); return ctx; } module.exports = { contextify: contextify };
29.086667
112
0.617007
759d322dbd555a269390fef8650c9487bf5b77ab
927
js
JavaScript
src/icons/cash-stack.js
Arun-45/react-bootstrap-icons
922084b34bee197e20b386a3d197f604f21a0283
[ "MIT" ]
1
2020-11-11T07:32:26.000Z
2020-11-11T07:32:26.000Z
src/icons/cash-stack.js
Arun-45/react-bootstrap-icons
922084b34bee197e20b386a3d197f604f21a0283
[ "MIT" ]
null
null
null
src/icons/cash-stack.js
Arun-45/react-bootstrap-icons
922084b34bee197e20b386a3d197f604f21a0283
[ "MIT" ]
null
null
null
import React, { forwardRef } from 'react'; import PropTypes from 'prop-types'; const CashStack = forwardRef(({ color, size, ...rest }, ref) => { return ( <svg ref={ref} xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width={size} height={size} fill={color} {...rest} > <path d="M14 3H1a1 1 0 0 1 1-1h12a1 1 0 0 1 1 1h-1z" /> <path fillRule="evenodd" d="M15 5H1v8h14V5zM1 4a1 1 0 0 0-1 1v8a1 1 0 0 0 1 1h14a1 1 0 0 0 1-1V5a1 1 0 0 0-1-1H1z" /> <path d="M13 5a2 2 0 0 0 2 2V5h-2zM3 5a2 2 0 0 1-2 2V5h2zm10 8a2 2 0 0 1 2-2v2h-2zM3 13a2 2 0 0 0-2-2v2h2zm7-4a2 2 0 1 1-4 0 2 2 0 0 1 4 0z" /> </svg> ); }); CashStack.propTypes = { color: PropTypes.string, size: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), }; CashStack.defaultProps = { color: 'currentColor', size: '1em', }; export default CashStack;
25.75
149
0.587918
759de3c8626d0cc4a9a86e523a3cd3986cb3a3a8
2,171
js
JavaScript
api/data/routes/todo/todo.js
build-week-party-planner/BE
52454ec800ca47086ebe7eb736e22a395bb45202
[ "MIT" ]
null
null
null
api/data/routes/todo/todo.js
build-week-party-planner/BE
52454ec800ca47086ebe7eb736e22a395bb45202
[ "MIT" ]
1
2021-05-10T01:36:22.000Z
2021-05-10T01:36:22.000Z
api/data/routes/todo/todo.js
build-week-party-planner/BE
52454ec800ca47086ebe7eb736e22a395bb45202
[ "MIT" ]
1
2019-07-10T02:11:42.000Z
2019-07-10T02:11:42.000Z
//Import express const express = require("express"); const knex = require("knex"); const knexConfig = require("../../../../knexfile.js"); const db = knex(knexConfig.development); //Import models const todoModel = require("./todo-model.js"); //Import middleware const checkToken = require("../../../middleware.js"); //Create Router const router = express.Router(); //Endpoints router.get("/", checkToken, async (req, res) => { try { const todo = await todoModel.getTodo(); res.status(200).json(todo); } catch (err) { res .status(500) .json({ message: "We ran into an error retrieving the todo" }); } }); router.get("/:id", checkToken, async (req, res) => { const { id } = req.params; try { const todo = await todoModel.getTodoById(id); if (todo) { res.status(200).json(todo); } else { res.status(404).json({ message: "Invalid ID" }); } } catch (err) { res .status(500) .json({ message: "We ran into an error retrieving the todo" }); } }); router.post("/", checkToken, async (req, res) => { const todo = req.body; try { const addTodoItem = await todoModel.addTodo(todo); console.log("did i make it here"); res.status(200).json(addTodoItem); } catch (err) { res.status(500).json({ message: "Error adding todo" }); } }); router.delete("/:id", checkToken, async (req, res) => { const { id } = req.params; if (!id) { res.status(404).json({ message: "missing ID or wrong ID" }); } else { try { const deletedTodo = await todoModel.deleteTodo(id); res.status(204).json(deletedTodo); } catch (err) { res.status(500).json({ message: "Error deleting Todo" }); } } }); router.put("/:id", checkToken, async (req, res) => { const { id } = req.params; try { const updatingTodo = await todoModel.updateTodo(id, req.body); if (updatingTodo) { res.status(200).json(updatingTodo); } else { res.status(404).json({ message: "Error in updating todo" }); } } catch (err) { res.status(500).json({ message: "Error updating todo" }); } }); module.exports = router;
23.597826
69
0.592354
759e2516f076a150cc0b79b2ec73f5a18fa20da9
846
js
JavaScript
src/Columns.js
horaklukas/loin
2e777a04df4964ca5ad6e7b547c5737c42ea0f74
[ "MIT" ]
null
null
null
src/Columns.js
horaklukas/loin
2e777a04df4964ca5ad6e7b547c5737c42ea0f74
[ "MIT" ]
null
null
null
src/Columns.js
horaklukas/loin
2e777a04df4964ca5ad6e7b547c5737c42ea0f74
[ "MIT" ]
null
null
null
import React from 'react'; import styles from './styles'; import Timer from './Timer'; const DEFAULT_MAX_COLUMNS_COUNT = 3; /** * type Props = { * count?: number, * color?: string * } */ export const LoadingIndicator = (props/*: Props */) => { const maxColumnsCount = props.count || DEFAULT_MAX_COLUMNS_COUNT; const columnsCount = props.ticks % (maxColumnsCount + 1); const columnStyle = styles.column if (props.color) { columnStyle.backgroundColor = props.color; } return ( <div className="indicator"> {getColumns(columnsCount, columnStyle)} </div> ) }; const getColumns = (count, style) => { let columns = []; for (let i = 0; i < count; i++) { columns.push(<span className="column" style={style} key={`col${i}`} />); } return columns; } export default Timer(LoadingIndicator);
21.15
76
0.640662
759e4e57e31871b038ad59cafa885a5615c3d725
386
js
JavaScript
src/containers/Search/index.test.js
ehellman/3r-styletron-hmr
34c1e2a23fd155f00efb7197158332f2ed2c27e0
[ "MIT" ]
null
null
null
src/containers/Search/index.test.js
ehellman/3r-styletron-hmr
34c1e2a23fd155f00efb7197158332f2ed2c27e0
[ "MIT" ]
null
null
null
src/containers/Search/index.test.js
ehellman/3r-styletron-hmr
34c1e2a23fd155f00efb7197158332f2ed2c27e0
[ "MIT" ]
null
null
null
// pkg.json // "pretest": "npm run test:clean && npm run lint", // "test:clean": "rimraf ./coverage", // "test": "cross-env NODE_ENV=test jest --coverage", // "test:watch": "cross-env NODE_ENV=test jest --watchAll", // "coveralls": "cat ./coverage/lcov.info | coveralls" // "coveralls": "2.11.15", // "enzyme": "2.6.0", // "jest-cli": "18.0.0", // "react-addons-test-utils": "15.4.1",
32.166667
59
0.606218
759f6f07f5ca4bfc4416569da7fcfd950783c84a
155
js
JavaScript
angular/controllers/dashboard_controller.js
PhilCowart/raingauge-api
6057423086f858f944025dbe8af2d24313a03bef
[ "MIT" ]
null
null
null
angular/controllers/dashboard_controller.js
PhilCowart/raingauge-api
6057423086f858f944025dbe8af2d24313a03bef
[ "MIT" ]
null
null
null
angular/controllers/dashboard_controller.js
PhilCowart/raingauge-api
6057423086f858f944025dbe8af2d24313a03bef
[ "MIT" ]
null
null
null
rainGaugeControllers.controller('DashboardCtrl', function($scope, $rootScope, $auth, accountFactory, myAccount) { $rootScope.account = myAccount; });
22.142857
113
0.754839
75a0b057a23f2eec2f90f77a016e7bd317ad6e66
7,100
js
JavaScript
gulpfile.js
JoshuaBolitho/Basic-Frontend-Boilerplate
d0c4d2a71cda7482c302e4ae16d58cc505e00264
[ "MIT" ]
null
null
null
gulpfile.js
JoshuaBolitho/Basic-Frontend-Boilerplate
d0c4d2a71cda7482c302e4ae16d58cc505e00264
[ "MIT" ]
null
null
null
gulpfile.js
JoshuaBolitho/Basic-Frontend-Boilerplate
d0c4d2a71cda7482c302e4ae16d58cc505e00264
[ "MIT" ]
null
null
null
var gulp = require('gulp'); // Task manager used to perform all the below tasks. var del = require('del'); // Simple module for deleting files and folders on the HD. var path = require('path'); // Module provides utilities for working with file and directory paths. var argv = require('yargs').argv; // Exposes passed arguments from the command line. var gutil = require('gulp-util'); // Utility functions for gulp plugins, such as logging. var source = require('vinyl-source-stream'); // Converts a stream to a virtual file. var buffer = require('gulp-buffer'); // Converts stream to buffer var exorcist = require('exorcist'); // Browserify writes js.map to output.js when debug=true. Exorcist pulls it out and creates external output.js.map var gulpif = require('gulp-if'); // Adds the ability to apply conditional logic within gulp var uglify = require('gulp-uglify'); // Adds the ability to apply conditional logic within gulp var browserify = require('browserify'); // Converts Common.js require modules to vanilla javascript, includes dependency management. var babelify = require('babelify'); // Converts ES6 javascript schema to browser friendly version. var browserSync = require('browser-sync'); // Serves site files and performs reloads on file updates var sass = require('gulp-sass'); // CSS preprocessor for converting SASS to CSS var sourcemaps = require('gulp-sourcemaps'); // Builds a CSS sourcemap var autoprefixer = require('gulp-autoprefixer'); // Magic task that add all the CSS browser prefixes automatically var processHTML = require('gulp-processhtml'); // Handles build time conditions in index.html. var hoganify = require('hoganify'); // Compiles hogan modules from mustache templates and then embeds the result to app.min.js, so templates can be accessed as require modules. var gulpSequence = require('gulp-sequence'); // PATH CONSTANTS var BUILD_PATH = './build'; var SCRIPTS_PATH = BUILD_PATH + '/js'; var SOURCE_PATH = './src'; var ASSET_PATH = SOURCE_PATH + '/assets'; var ENTRY_FILE = SOURCE_PATH + '/js/app.js'; var OUTPUT_FILE = 'app.min.js'; /************************************************************* ** ** Deletes the entire contents of the build directory ** **************************************************************/ function cleanBuild () { del([BUILD_PATH + '/**/*.*']); } /************************************************************* ** ** Copies 'src/assets' folder into the '/build' folder. ** **************************************************************/ function copyAssets () { return gulp.src(ASSET_PATH + '/**/*') .pipe(gulp.dest(BUILD_PATH + '/assets')); } /************************************************************* ** ** Javascript is originally written in ES2015 script because ** of how clean and easy to structure it is. Since there are ** plenty of browsers that can't read it properly it's just ** easier to translate it back to browser friendly ** javascript. ** **************************************************************/ function processJavascript () { var sourcemapPath = SCRIPTS_PATH + '/' + OUTPUT_FILE + '.map'; // handles js files so that they work on the web var browserified = browserify({ paths: [ path.join(__dirname, SOURCE_PATH + '/js') ], entries: [ENTRY_FILE], debug: true }); // converts ES6 to vanilla javascript. Note that preset is an NPM dependency browserified.transform(babelify, { "presets": ["es2015"] }); browserified.transform(hoganify, { live:false, ext:'.html,.mustache' }); // bundles all the "require" dependencies together into one container var bundle = browserified.bundle().on('error', function(error){ gutil.log(gutil.colors.red('[Build Error]', error.message)); this.emit('end'); }); // now that stream is machine readable javascript, finish the rest of the gulp build tasks return bundle .pipe( exorcist(sourcemapPath) ) .pipe( source(OUTPUT_FILE) ) .pipe( buffer() ) //.pipe( uglify() ) .pipe( gulp.dest(SCRIPTS_PATH) ) } /************************************************************* ** ** Converts SASS to CSS ** **************************************************************/ function processSASS () { var autoprefixerOptions = { browsers: ['last 2 versions', '> 5%', 'Firefox ESR'] }; return gulp.src(SOURCE_PATH + '/scss/main.scss') .pipe(sourcemaps.init()) .pipe(sass().on('error', sass.logError)) .pipe(sourcemaps.write()) .pipe(autoprefixer(autoprefixerOptions)) .pipe(gulp.dest(BUILD_PATH + '/css')) } /************************************************************* ** ** Handles conditional comments in index.html ** **************************************************************/ function processIndexHTML () { return gulp.src(SOURCE_PATH + '/index.html') .pipe( processHTML({}) ) .pipe( gulp.dest(BUILD_PATH) ) } /************************************************************* ** ** Starts the Browsersync server and watches for file ** updates, which will prompt specific build tasks to the ** type of file updated. ** **************************************************************/ function serve () { var options = { server: { baseDir: BUILD_PATH }, open: false // Change it to true if you wish to allow Browsersync to open a browser window. }; browserSync(options); // Watches for changes in files inside the './src' folder. gulp.watch(SOURCE_PATH + '/js/**/*.js', ['watch-js']); // Watches for updates to sass css preprocessor files. gulp.watch(SOURCE_PATH + '/scss/**/*.scss', ['watch-sass']); // Watches for updates in index.html gulp.watch(SOURCE_PATH + '/index.html', ['watch-html']); // Watches for updates in mustache partials and templates and reloads javascript, since the they get compiled into js objects. gulp.watch(SOURCE_PATH + '/views/**/*.mustache', ['watch-js']); // Watches for changes in files inside the './static' folder. Also sets 'keepFiles' to true (see cleanBuild()). gulp.watch(ASSET_PATH + '/**/*', ['watch-assets']).on('change', function() { return; }); } // TODO: minify CSS // TODO: compress images in copy-assets, or maybe just add it to a final-build task. gulp.task('clean-build', cleanBuild); gulp.task('process-sass', processSASS); gulp.task('process-html', processIndexHTML); gulp.task('copy-assets', copyAssets); gulp.task('process-javascript', processJavascript); gulp.task('watch-js', ['build'], browserSync.reload); gulp.task('watch-sass', ['process-sass'], browserSync.reload); gulp.task('watch-html', ['process-html'], browserSync.reload); gulp.task('watch-assets', ['copy-assets'], browserSync.reload); gulp.task('build', function(callback){ gulpSequence('clean-build', 'copy-assets', 'process-sass', 'process-html', 'process-javascript')(callback); }); gulp.task('serve', function(callback){ gulpSequence('build', serve)(callback); });
37.566138
192
0.606338
75a0f75a813f06fc20c0ffa4df80952a283e4d2f
2,423
js
JavaScript
src/components/SubscribeForm.js
PierreLeGuen/new.leguen.fr
ae58f360e8a2248ea026f8cf97a6aa0963d3e211
[ "MIT" ]
2
2020-01-09T12:31:18.000Z
2020-05-01T12:49:07.000Z
src/components/SubscribeForm.js
22940dev/portfolio-sagarkharbe
4e3b0c243ad533c9cbca0b1f79e2eef21f512426
[ "MIT" ]
8
2021-04-06T09:58:56.000Z
2022-02-26T01:43:43.000Z
src/components/SubscribeForm.js
22940dev/portfolio-sagarkharbe
4e3b0c243ad533c9cbca0b1f79e2eef21f512426
[ "MIT" ]
2
2019-09-19T15:55:36.000Z
2021-01-25T23:11:10.000Z
import addToMailchimp from 'gatsby-plugin-mailchimp' import React, { useState } from 'react' import styled from 'styled-components' import Swal from 'sweetalert2' import bg from '../assets/images/footer-bg2.png' import { media } from '../styles' const Form = styled.form` background-color: #0e0e0e; border-top: 1px solid #eee; border-bottom: 1px solid #eee; background-image: url(${bg}); background-position: center; background-repeat: no-repeat; background-size: cover; margin: 10px auto; align-items: center; padding: 44px 12px; opacity: 0.9; display: flex; flex-direction: column; ` const Title = styled.h2` margin-bottom: 1.3em; color: white; text-align: center; font-size: 24px; ${media.sm` font-size: 35px; `} ` const Input = styled.input` padding: 10px 1rem !important; max-width: 500px; font-weight: 600 !important; color: white !important; background: transparent !important; border-color: white !important; ` const Buttons = styled.button` margin: 15px 0; margin-top: 26px; background: #efc026; border: 0; border-radius: 3px; padding: 10px 32px; transition: 0.2s; cursor: pointer; font-weight: bold; box-shadow: 0 0 2px 0px gray; &:hover { background: #e2b420; } ` const SubscribeForm = () => { const [email, setEmail] = useState('') const handleSubmit = e => { e.preventDefault() addToMailchimp(email) .then(data => { // console.log(data) // alert(data.result + ' ' + data.msg) Swal.fire({ type: data.result, title: data.result === 'success' ? 'Success' : 'Error', html: data.msg, confirmButtonClass: 'Btn', cancelButtonClass: 'Btn', onClose: () => { if (data.result === 'success') setEmail('') } }) }) .catch(error => { // Errors in here are client side // Mailchimp always returns a 200 }) } const handleEmailChange = event => { setEmail(event.currentTarget.value) } return ( <Form onSubmit={handleSubmit}> <Title>Subscribe to my email list!</Title> <Input placeholder="Email address" name="email" value={email} type="text" onChange={handleEmailChange} /> <Buttons size="small" type="primary"> Subscribe </Buttons> </Form> ) } export default SubscribeForm
23.524272
65
0.612464
75a1cca4cbe61544538005df765fc5c07208a7ee
4,726
js
JavaScript
backend/controllers/commentController.js
Aritro08/KaiNet-Social-Network-Platform
016e4c3562be6bba33cfd062c992c9be6b0b0e7a
[ "Apache-2.0" ]
null
null
null
backend/controllers/commentController.js
Aritro08/KaiNet-Social-Network-Platform
016e4c3562be6bba33cfd062c992c9be6b0b0e7a
[ "Apache-2.0" ]
null
null
null
backend/controllers/commentController.js
Aritro08/KaiNet-Social-Network-Platform
016e4c3562be6bba33cfd062c992c9be6b0b0e7a
[ "Apache-2.0" ]
null
null
null
const Post = require('../models/post'); const Comment = require('../models/comment'); exports.addComment = (req, res, next) => { let count; const comment = new Comment({ parentId: req.body.parentId, postId: req.params.id, username: req.body.userName, content: req.body.content, userId: req.body.userId, commentDate: Date.now() }); comment.save().then(resData => { Post.findByIdAndUpdate(req.params.id, { $inc: {'commentCount': 1} }).then(resData => { count = resData.commentCount + 1; res.status(200).json({ count: count }); }).catch(err => { return res.status(500).json({ message: 'Server error - failed to update post.' }) }); }).catch(err => { return res.status(500).json({ message: 'Server error - failed to add comment.' }); }); } exports.getComments = (req, res, next) => { Comment.find({postId: req.params.id}).lean().exec().then(comments => { let threads = []; let threadComment; let findThreads = (threadComment, threads) => { threads.forEach(thread => { if(thread._id.toString() === threadComment.parentId.toString()) { thread.children.push(threadComment); } if(thread.children.length > 0) { findThreads(threadComment, thread.children); } }); } comments.forEach(comment => { threadComment = comment; threadComment['children'] = []; threadComment['replyFormDisplay'] = false; let parentId = comment.parentId; if(!parentId) { threads.push(comment); return; } findThreads(threadComment, threads); }); res.status(200).json({ comments: threads }); }).catch(err => { return res.status(500).json({ message: 'Server error - failed to load comments.' }); }); } exports.editComment = (req, res, next) => { Comment.findOneAndUpdate(req.params.id, { $set: {'content': req.body.content} }).then(resData => { if(!resData) { return res.status(401).json({ message: 'Not authorised to perform task.' }); } res.status(200).json({ message: 'comment' }); }).catch(err => { return res.status(500).json({ message: 'Server error - failed to update comment.' }); }); } exports.deleteComment = (req, res, next) => { let decPostCommentCount = () => { Post.findByIdAndUpdate(req.body.postId, { $inc: {'commentCount': -1} }).then(resData => { count = resData.commentCount - 1; res.status(200).json({ count: count }); }).catch(err => { return res.status(500).json({ message: 'Server error - failed to update post after deletion.', count: 0 }); }); } Comment.findOne({_id: req.params.id, userId: req.userData.id}).then(delComment => { if(!delComment) { return res.status(401).json({ message: 'Not Authorised to perform task.' }); } let id = delComment._id.toString(); Comment.find({parentId: id}).lean().exec().then(comments => { if(comments.length >= 1) { delComment.content = '[deleted]'; delComment.save().then(resData => { decPostCommentCount(); }).catch(err => { return res.status(500).json({ message: 'Server error - comment could not be deleted.', count: 0 }); }); } else { delComment.delete().then(resData => { decPostCommentCount(); }).catch(err => { return res.status(500).json({ message: 'Server error - comment could not be deleted.', count: 0 }); }); } }).catch(err => { return res.status(500).json({ message: 'Server error - comments not found.', count: 0 }); }); }).catch(err => { return res.status(500).json({ message: 'Server error - comment not found.', count: 0 }); }); }
32.819444
87
0.469107
75a247f6a11a46bbefb717bfb919dd6b4594270f
1,181
js
JavaScript
libs/arcgis_js_api_3.34/esri/dijit/geoenrichment/ReportPlayer/core/charts/utils/cleanUp/_ChartTypeSupports.js
GitHubYangZhiwen/arcgis-js-siteapp-3.x
3f81d15eb2a89eacb6cd548a9591edb40b920e50
[ "Apache-2.0" ]
null
null
null
libs/arcgis_js_api_3.34/esri/dijit/geoenrichment/ReportPlayer/core/charts/utils/cleanUp/_ChartTypeSupports.js
GitHubYangZhiwen/arcgis-js-siteapp-3.x
3f81d15eb2a89eacb6cd548a9591edb40b920e50
[ "Apache-2.0" ]
null
null
null
libs/arcgis_js_api_3.34/esri/dijit/geoenrichment/ReportPlayer/core/charts/utils/cleanUp/_ChartTypeSupports.js
GitHubYangZhiwen/arcgis-js-siteapp-3.x
3f81d15eb2a89eacb6cd548a9591edb40b920e50
[ "Apache-2.0" ]
null
null
null
// All material copyright ESRI, All Rights Reserved, unless otherwise specified. // See http://js.arcgis.com/3.34/esri/copyright.txt for details. //>>built define("esri/dijit/geoenrichment/ReportPlayer/core/charts/utils/cleanUp/_ChartTypeSupports","esri/dijit/geoenrichment/utils/ObjectUtil esri/dijit/geoenrichment/ReportPlayer/core/charts/utils/ChartTypes ./chartTypes/classic/_ColumnBarLike ./chartTypes/classic/_LineLike ./chartTypes/classic/_Pie ./chartTypes/graphic/_ColumnBarLike ./chartTypes/graphic/_ColumnBarPictureLike ./chartTypes/graphic/_LineLike ./chartTypes/graphic/_Pie ./chartTypes/graphic/_Donut ./chartTypes/graphic/_Ring ./chartTypes/graphic/_Gauge ./chartTypes/graphic/_Waffle".split(" "), function(g,a,h,k,l,m,n,p,q,r,t,u,v){var d={},c={};c[a.COLUMN]=c[a.BAR]=h;c[a.LINE]=k;c[a.PIE]=l;var b={};b[a.COLUMN]=b[a.BAR]=m;b[a.PICTURE_COLUMN]=b[a.PICTURE_BAR]=n;b[a.LINE]=b[a.VERTICAL_LINE]=p;b[a.PIE]=q;b[a.DONUT]=r;b[a.RING]=t;b[a.GAUGE]=u;b[a.WAFFLE]=v;d.cleanUpJsonForChartType=function(a,e){return g.filterByPattern(a,(e?b:c)[a.type])};d.supportsProperty=function(a,e,d){e=e.split(".");var f=(d?b:c)[a];e.forEach(function(a){f=f&&f[a]});return!!f};return d});
236.2
555
0.751905
75a338133e05519b4291909001af3c725e272099
3,177
js
JavaScript
js/interact.js
kthornbloom/interact-live-chat
ba237dd00d8911c5891209dda1be89e90342876d
[ "MIT" ]
null
null
null
js/interact.js
kthornbloom/interact-live-chat
ba237dd00d8911c5891209dda1be89e90342876d
[ "MIT" ]
null
null
null
js/interact.js
kthornbloom/interact-live-chat
ba237dd00d8911c5891209dda1be89e90342876d
[ "MIT" ]
null
null
null
var instanse = false; var state; var mes; var file; url = new URL(window.location.href); if (url.searchParams.get('chatid')) { var chatid = url.searchParams.get('chatid'); } else { var chatid = new Date().getTime(); var url = document.location.href+"?chatid="+chatid; document.location = url; } function Chat () { this.update = updateChat; this.send = sendChat; this.sysMessage = sysMessage; this.getState = getStateOfChat; } //gets the state of the chat function getStateOfChat(){ if(!instanse){ instanse = true; $.ajax({ type: "POST", url: "process.php", data: { 'function': 'getState', 'file': file, 'chatid':chatid }, dataType: "json", success: function(data){ state = data.state; instanse = false; }, }); } } // Chat History function initChat(){ $.ajax({ type: "POST", url: "process.php", data: { 'function': 'update', 'state': state, 'file': file, 'chatid':chatid }, dataType: "json", success: function(data){ if(data.text){ $.each(data.text, function(index, value) { $('#chat-area').append(value); }); document.getElementById('chat-area').scrollTop = document.getElementById('chat-area').scrollHeight; } } }); } initChat(); //Updates the chat function updateChat(){ if(!instanse){ instanse = true; $.ajax({ type: "POST", url: "process.php", data: { 'function': 'update', 'state': state, 'file': file, 'chatid':chatid }, dataType: "json", success: function(data){ if(data.text){ for (var i = 0; i < data.text.length; i++) { $('#chat-area').append($(data.text[i])); document.getElementById('chat-area').scrollTop = document.getElementById('chat-area').scrollHeight; var lastMessage = $('#chat-area > div:last-of-type').attr('class'), yourName = $('#name').html(); if(window.Notification && Notification.permission !== "denied" && lastMessage != yourName) { Notification.requestPermission(function(status) { // status is "granted", if accepted by user var n = new Notification('New Message', { icon: 'images/chat.png' // optional }); setTimeout(n.close.bind(n), 2000); }); var audio = new Audio('audio/chime.mp3'); audio.play(); } } } instanse = false; state = data.state; }, }); } else { setTimeout(updateChat, 1500); } } //send the message function sendChat(message, nickname){ updateChat(); $.ajax({ type: "POST", url: "process.php", data: { 'function': 'send', 'message': message, 'nickname': nickname, 'file': file, 'chatid':chatid }, dataType: "json", success: function(data){ updateChat(); }, }); } //send the message function sysMessage(message){ $.ajax({ type: "POST", url: "process.php", data: { 'function': 'sysMessage', 'message': message, 'file': file, 'chatid':chatid }, dataType: "json", success: function(data){ updateChat(); }, }); }
20.496774
106
0.56311
75a392f4955e3e547500195bbf6ef053200a8351
69
js
JavaScript
components/ProfileForm/index.js
rickychan0611/peacefulmall-rest
228b6cbc6a63052de026ee9fc79fcd1294acf551
[ "MIT" ]
null
null
null
components/ProfileForm/index.js
rickychan0611/peacefulmall-rest
228b6cbc6a63052de026ee9fc79fcd1294acf551
[ "MIT" ]
3
2021-07-05T16:59:22.000Z
2021-07-13T21:02:20.000Z
components/ProfileForm/index.js
rickychan0611/peaceful-restaurant
3b33a23ec11f1f81e072d993d96d581d48dd138a
[ "MIT" ]
null
null
null
import ProfileForm from "./ProfileForm"; export default ProfileForm;
23
40
0.811594
75a43b4ad9040971a63996d14b1b27b4d834f80a
843
js
JavaScript
src/Merchello.Web.UI.Client/src/common/models/factories/saleshistory/SalesHistoryMessageDisplayBuilder.factory.js
raindigi/Merchello
7116fefe5be4eb424d43afc6590cfa3077ade185
[ "MIT" ]
191
2015-01-22T16:22:22.000Z
2022-01-12T18:50:07.000Z
src/Merchello.Web.UI.Client/src/common/models/factories/saleshistory/SalesHistoryMessageDisplayBuilder.factory.js
raindigi/Merchello
7116fefe5be4eb424d43afc6590cfa3077ade185
[ "MIT" ]
286
2015-01-16T12:30:01.000Z
2022-03-02T01:45:41.000Z
src/Merchello.Web.UI.Client/src/common/models/factories/saleshistory/SalesHistoryMessageDisplayBuilder.factory.js
raindigi/Merchello
7116fefe5be4eb424d43afc6590cfa3077ade185
[ "MIT" ]
300
2015-01-07T15:32:27.000Z
2022-02-08T12:31:44.000Z
/** * @ngdoc service * @name merchello.models.salesHistoryMessageDisplayBuilder * * @description * A utility service that builds salesHistoryMessageDisplayBuilder models */ angular.module('merchello.models') .factory('salesHistoryMessageDisplayBuilder', ['genericModelBuilder', 'SalesHistoryMessageDisplay', function(genericModelBuilder, SalesHistoryMessageDisplay) { var Constructor = SalesHistoryMessageDisplay; return { createDefault: function() { return new Constructor(); }, transform: function(jsonResult) { return genericModelBuilder.transform(jsonResult, Constructor); } }; }]);
35.125
86
0.562278
75a5229c37ec2ed4b03e90f60c6473927862bd7f
1,188
js
JavaScript
pages/index.js
davidchristie/kaenga-housing-calculator-spike
9a11850a45c309798ef6eabbc93bab294c210dd0
[ "MIT" ]
null
null
null
pages/index.js
davidchristie/kaenga-housing-calculator-spike
9a11850a45c309798ef6eabbc93bab294c210dd0
[ "MIT" ]
3
2017-07-27T12:01:34.000Z
2017-07-27T12:02:05.000Z
pages/index.js
davidchristie/kaenga-housing-calculator-spike
9a11850a45c309798ef6eabbc93bab294c210dd0
[ "MIT" ]
null
null
null
import Link from 'next/link' import withRedux from 'next-redux-wrapper' import React from 'react' import { Button, Grid, Jumbotron } from 'react-bootstrap' import Page from '../components/Page' import initStore from '../store' class Index extends React.Component { render () { return ( <Page> <Grid> <Jumbotron> <h1>Housing Calculator</h1> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. </p> <p> Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </p> <Link href='/question?id=1'> <a> <Button bsStyle='primary'>Start</Button> </a> </Link> </Jumbotron> </Grid> </Page> ) } } export default withRedux(initStore)(Index)
33.942857
245
0.618687
75a57c44290ba6f9676748b7555a9815a1935a12
1,886
js
JavaScript
doxygen/html/classreview__remarks__dlg.js
mikewolfli/workflow
98ad4a2a822aae774355c03cb1eea5cc97d986b8
[ "Unlicense" ]
3
2016-05-30T05:39:52.000Z
2017-11-10T07:26:53.000Z
doxygen/html/classreview__remarks__dlg.js
mikewolfli/workflow
98ad4a2a822aae774355c03cb1eea5cc97d986b8
[ "Unlicense" ]
null
null
null
doxygen/html/classreview__remarks__dlg.js
mikewolfli/workflow
98ad4a2a822aae774355c03cb1eea5cc97d986b8
[ "Unlicense" ]
1
2020-01-02T01:05:01.000Z
2020-01-02T01:05:01.000Z
var classreview__remarks__dlg = [ [ "review_remarks_dlg", "classreview__remarks__dlg.html#a4832a1bbdb07e02773be2460ae8dab4f", null ], [ "~review_remarks_dlg", "classreview__remarks__dlg.html#aacdd824be776879cc1ab6eda31807dd6", null ], [ "refresh_control", "classreview__remarks__dlg.html#a1fc0afde64afa83cbc4acc5e8666485c", null ], [ "show_control", "classreview__remarks__dlg.html#a4aa12fd4798e4e84fec74c33877fac9b", null ], [ "Button1", "classreview__remarks__dlg.html#a3f36f96a3435ee95e9d3681cc1c4b1b1", null ], [ "Button2", "classreview__remarks__dlg.html#aee3ca3773be27519c0dcdb335afe4736", null ], [ "Button3", "classreview__remarks__dlg.html#a60c0c7cc39913b0381df5cfcdf8edd00", null ], [ "choice_urgent_level", "classreview__remarks__dlg.html#a279e02acdbc09026e87fe05b9ef82aef", null ], [ "m_qty", "classreview__remarks__dlg.html#a6f43d7a36388345e6946691ef3fc83da", null ], [ "m_remarks", "classreview__remarks__dlg.html#a1275858b643c3bfe27dfa9e8ee7a629c", null ], [ "m_res_cm", "classreview__remarks__dlg.html#ab0206fbb36f3bc6403b2bb279583bf39", null ], [ "m_urgent_level", "classreview__remarks__dlg.html#a7053a5c247eb2e1890014af54a794cc8", null ], [ "StaticText1", "classreview__remarks__dlg.html#a7a3ac21023fb4f66a69c5271eec18739", null ], [ "StaticText2", "classreview__remarks__dlg.html#a81ad46cbb110cf3ee76deeaf99688934", null ], [ "StaticText3", "classreview__remarks__dlg.html#a4d816fa891ab0ce05de0aad49bf90208", null ], [ "StaticText4", "classreview__remarks__dlg.html#a4cda97f2c7f80af34727fe75ed82a80c", null ], [ "tc_drawing_qty", "classreview__remarks__dlg.html#a0858dfc5f0954ff45501159a3f2988e6", null ], [ "tc_remarks", "classreview__remarks__dlg.html#a2806b19de75f8b8390b1cff2d6991474", null ], [ "tc_res_cm", "classreview__remarks__dlg.html#a3f7a7db247f4dd4b8fc77b9112fd20a9", null ] ];
85.727273
104
0.794274
75a5cc734c5af6f23e5f6a1eb34e7f9d8bd4b8fd
39,162
js
JavaScript
src/data/cities.js
meep-morp/Citrics-FE
69741475e63d6d20142578810ef928be786ad30d
[ "MIT" ]
null
null
null
src/data/cities.js
meep-morp/Citrics-FE
69741475e63d6d20142578810ef928be786ad30d
[ "MIT" ]
5
2020-10-08T20:33:36.000Z
2020-10-15T18:11:53.000Z
src/data/cities.js
meep-morp/Citrics-FE
69741475e63d6d20142578810ef928be786ad30d
[ "MIT" ]
2
2020-10-23T20:07:56.000Z
2020-10-26T16:02:28.000Z
const CityData = { 'Phenix City, Alabama': 0, 'Vestavia Hills, Alabama': 1, 'Apache Junction, Arizona': 2, 'Bullhead City, Arizona': 3, 'Casa Grande, Arizona': 4, 'El Mirage, Arizona': 5, 'Lake Havasu City, Arizona': 6, 'Oro Valley, Arizona': 7, 'Prescott Valley, Arizona': 8, 'Sierra Vista, Arizona': 9, 'Fort Smith, Arkansas': 10, 'Hot Springs, Arkansas': 11, 'Little Rock, Arkansas': 12, 'North Little Rock, Arkansas': 13, 'Pine Bluff, Arkansas': 14, 'Aliso Viejo, California': 15, 'Apple Valley, California': 16, 'Baldwin Park, California': 17, 'Bell Gardens, California': 18, 'Beverly Hills, California': 19, 'Buena Park, California': 20, 'Cathedral City, California': 21, 'Chino Hills, California': 22, 'Chula Vista, California': 23, 'Citrus Heights, California': 24, 'Costa Mesa, California': 25, 'Culver City, California': 26, 'Daly City, California': 27, 'Dana Point, California': 28, 'Diamond Bar, California': 29, 'El Cajon, California': 30, 'El Centro, California': 31, 'El Monte, California': 32, 'Foster City, California': 33, 'Fountain Valley, California': 34, 'Garden Grove, California': 35, 'Huntington Beach, California': 36, 'Huntington Park, California': 37, 'Laguna Hills, California': 38, 'Laguna Niguel, California': 39, 'La Habra, California': 40, 'Lake Elsinore, California': 41, 'Lake Forest, California': 42, 'La Mesa, California': 43, 'La Mirada, California': 44, 'La Puente, California': 45, 'La Verne, California': 46, 'Long Beach, California': 47, 'Los Angeles, California': 48, 'Los Banos, California': 49, 'Manhattan Beach, California': 50, 'Menlo Park, California': 51, 'Mission Viejo, California': 52, 'Monterey Park, California': 53, 'Moreno Valley, California': 54, 'Morgan Hill, California': 55, 'Mountain View, California': 56, 'National City, California': 57, 'Newport Beach, California': 58, 'Palm Desert, California': 59, 'Palm Springs, California': 60, 'Palo Alto, California': 61, 'Pico Rivera, California': 62, 'Pleasant Hill, California': 63, 'Rancho Cordova, California': 64, 'Rancho Cucamonga, California': 65, 'Rancho Palos Verdes, California': 66, 'Rancho Santa Margarita, California': 67, 'Redondo Beach, California': 68, 'Redwood City, California': 69, 'Rohnert Park, California': 70, 'San Bernardino, California': 71, 'San Bruno, California': 72, 'San Diego, California': 73, 'San Dimas, California': 74, 'San Francisco, California': 75, 'San Gabriel, California': 76, 'San Jacinto, California': 77, 'San Jose, California': 78, 'San Leandro, California': 79, 'San Luis Obispo, California': 80, 'San Marcos, California': 81, 'San Mateo, California': 82, 'San Rafael, California': 83, 'San Ramon, California': 84, 'Santa Ana, California': 85, 'Santa Barbara, California': 86, 'Santa Clara, California': 87, 'Santa Clarita, California': 88, 'Santa Cruz, California': 89, 'Santa Maria, California': 90, 'Santa Monica, California': 91, 'Santa Rosa, California': 92, 'Simi Valley, California': 93, 'South Gate, California': 94, 'South San Francisco, California': 95, 'Temple City, California': 96, 'Thousand Oaks, California': 97, 'Union City, California': 98, 'Walnut Creek, California': 99, 'West Covina, California': 100, 'West Hollywood, California': 101, 'West Sacramento, California': 102, 'Yorba Linda, California': 103, 'Yuba City, California': 104, 'Castle Rock, Colorado': 105, 'Colorado Springs, Colorado': 106, 'Commerce City, Colorado': 107, 'Fort Collins, Colorado': 108, 'Grand Junction, Colorado': 109, 'Wheat Ridge, Colorado': 110, 'New Haven, Connecticut': 111, 'West Haven, Connecticut': 112, 'Washington, District of Columbia': 113, 'Altamonte Springs, Florida': 114, 'Boca Raton, Florida': 115, 'Bonita Springs, Florida': 116, 'Boynton Beach, Florida': 117, 'Cape Coral, Florida': 118, 'Coconut Creek, Florida': 119, 'Coral Gables, Florida': 120, 'Coral Springs, Florida': 121, 'Cutler Bay, Florida': 122, 'Deerfield Beach, Florida': 123, 'Delray Beach, Florida': 124, 'Fort Lauderdale, Florida': 125, 'Fort Myers, Florida': 126, 'Fort Pierce, Florida': 127, 'Hallandale Beach, Florida': 128, 'Lake Worth, Florida': 129, 'Miami Beach, Florida': 130, 'Miami Gardens, Florida': 131, 'North Miami, Florida': 132, 'North Miami Beach, Florida': 133, 'North Port, Florida': 134, 'Ormond Beach, Florida': 135, 'Palm Bay, Florida': 136, 'Palm Beach Gardens, Florida': 137, 'Palm Coast, Florida': 138, 'Panama City, Florida': 139, 'Pembroke Pines, Florida': 140, 'Plant City, Florida': 141, 'Pompano Beach, Florida': 142, 'Port St. Lucie, Florida': 143, 'St. Cloud, Florida': 144, 'St. Petersburg, Florida': 145, 'West Palm Beach, Florida': 146, 'Winter Garden, Florida': 147, 'Winter Haven, Florida': 148, 'Winter Springs, Florida': 149, 'Athens-Clarke County, Georgia': 150, 'Augusta-Richmond County, Georgia': 151, 'East Point, Georgia': 152, 'Peachtree City, Georgia': 153, 'Sandy Springs, Georgia': 154, 'Warner Robins, Georgia': 155, 'Boise City, Idaho': 156, "Coeur d'Alene, Idaho": 157, 'Idaho Falls, Idaho': 158, 'Twin Falls, Idaho': 159, 'Arlington Heights, Illinois': 160, 'Buffalo Grove, Illinois': 161, 'Chicago Heights, Illinois': 162, 'Des Plaines, Illinois': 163, 'Downers Grove, Illinois': 164, 'Elk Grove Village, Illinois': 165, 'Mount Prospect, Illinois': 166, 'Oak Lawn, Illinois': 167, 'Oak Park, Illinois': 168, 'Orland Park, Illinois': 169, 'Park Ridge, Illinois': 170, 'Rock Island, Illinois': 171, 'St. Charles, Illinois': 172, 'Tinley Park, Illinois': 173, 'Fort Wayne, Indiana': 174, 'New Albany, Indiana': 175, 'South Bend, Indiana': 176, 'Terre Haute, Indiana': 177, 'Cedar Falls, Iowa': 178, 'Cedar Rapids, Iowa': 179, 'Council Bluffs, Iowa': 180, 'Des Moines, Iowa': 181, 'Iowa City, Iowa': 182, 'Sioux City, Iowa': 183, 'Kansas City, Kansas': 184, 'Overland Park, Kansas': 185, 'Bowling Green, Kentucky': 186, 'Baton Rouge, Louisiana': 187, 'Lake Charles, Louisiana': 188, 'New Iberia, Louisiana': 189, 'New Orleans, Louisiana': 190, 'College Park, Maryland': 191, 'Barnstable Town, Massachusetts': 192, 'Braintree Town, Massachusetts': 193, 'Fall River, Massachusetts': 194, 'Franklin Town, Massachusetts': 195, 'New Bedford, Massachusetts': 196, 'Weymouth Town, Massachusetts': 197, 'Ann Arbor, Michigan': 198, 'Battle Creek, Michigan': 199, 'Bay City, Michigan': 200, 'Dearborn Heights, Michigan': 201, 'East Lansing, Michigan': 202, 'Farmington Hills, Michigan': 203, 'Grand Rapids, Michigan': 204, 'Lincoln Park, Michigan': 205, 'Port Huron, Michigan': 206, 'Rochester Hills, Michigan': 207, 'Royal Oak, Michigan': 208, 'St. Clair Shores, Michigan': 209, 'Sterling Heights, Michigan': 210, 'Apple Valley, Minnesota': 211, 'Brooklyn Center, Minnesota': 212, 'Brooklyn Park, Minnesota': 213, 'Coon Rapids, Minnesota': 214, 'Cottage Grove, Minnesota': 215, 'Eden Prairie, Minnesota': 216, 'Inver Grove Heights, Minnesota': 217, 'Maple Grove, Minnesota': 218, 'St. Cloud, Minnesota': 219, 'St. Louis Park, Minnesota': 220, 'St. Paul, Minnesota': 221, 'Olive Branch, Mississippi': 222, 'Blue Springs, Missouri': 223, 'Cape Girardeau, Missouri': 224, 'Jefferson City, Missouri': 225, 'Kansas City, Missouri': 226, 'St. Charles, Missouri': 227, 'St. Joseph, Missouri': 228, 'St. Louis, Missouri': 229, 'St. Peters, Missouri': 230, 'University City, Missouri': 231, 'Butte-Silver Bow, Montana': 232, 'Great Falls, Montana': 233, 'Grand Island, Nebraska': 234, 'Carson City, Nevada': 235, 'Las Vegas, Nevada': 236, 'North Las Vegas, Nevada': 237, 'Concord, New Hampshire': 238, 'Manchester, New Hampshire': 239, 'Nashua, New Hampshire': 240, 'Atlantic City, New Jersey': 241, 'Bayonne, New Jersey': 242, 'Camden, New Jersey': 243, 'Clifton, New Jersey': 244, 'East Orange, New Jersey': 245, 'Elizabeth, New Jersey': 246, 'Fair Lawn, New Jersey': 247, 'Fort Lee, New Jersey': 248, 'Garfield, New Jersey': 249, 'Hackensack, New Jersey': 250, 'Hoboken, New Jersey': 251, 'Jersey City, New Jersey': 252, 'Kearny, New Jersey': 253, 'Linden, New Jersey': 254, 'Newark, New Jersey': 255, 'New Brunswick, New Jersey': 256, 'Passaic, New Jersey': 257, 'Paterson, New Jersey': 258, 'Perth Amboy, New Jersey': 259, 'Plainfield, New Jersey': 260, 'Trenton, New Jersey': 261, 'Union City, New Jersey': 262, 'Vineland, New Jersey': 263, 'Westfield, New Jersey': 264, 'West New York, New Jersey': 265, 'Alamogordo, New Mexico': 266, 'Albuquerque, New Mexico': 267, 'Clovis, New Mexico': 268, 'Farmington, New Mexico': 269, 'Hobbs, New Mexico': 270, 'Las Cruces, New Mexico': 271, 'Rio Rancho, New Mexico': 272, 'Roswell, New Mexico': 273, 'Santa Fe, New Mexico': 274, 'Albany, New York': 275, 'Binghamton, New York': 276, 'Buffalo, New York': 277, 'Hempstead, New York': 278, 'Ithaca, New York': 279, 'Jamestown, New York': 280, 'Long Beach, New York': 281, 'Mount Vernon, New York': 282, 'New Rochelle, New York': 283, 'New York, New York': 284, 'Niagara Falls, New York': 285, 'North Tonawanda, New York': 286, 'Poughkeepsie, New York': 287, 'Rochester, New York': 288, 'Rome, New York': 289, 'Schenectady, New York': 290, 'Syracuse, New York': 291, 'Troy, New York': 292, 'Utica, New York': 293, 'Valley Stream, New York': 294, 'White Plains, New York': 295, 'Yonkers, New York': 296, 'Apex, North Carolina': 297, 'Asheville, North Carolina': 298, 'Burlington, North Carolina': 299, 'Cary, North Carolina': 300, 'Chapel Hill, North Carolina': 301, 'Charlotte, North Carolina': 302, 'Concord, North Carolina': 303, 'Durham, North Carolina': 304, 'Fayetteville, North Carolina': 305, 'Gastonia, North Carolina': 306, 'Goldsboro, North Carolina': 307, 'Greensboro, North Carolina': 308, 'Greenville, North Carolina': 309, 'Hickory, North Carolina': 310, 'High Point, North Carolina': 311, 'Huntersville, North Carolina': 312, 'Jacksonville, North Carolina': 313, 'Kannapolis, North Carolina': 314, 'Monroe, North Carolina': 315, 'Mooresville, North Carolina': 316, 'Raleigh, North Carolina': 317, 'Rocky Mount, North Carolina': 318, 'Salisbury, North Carolina': 319, 'Wake Forest, North Carolina': 320, 'Wilmington, North Carolina': 321, 'Wilson, North Carolina': 322, 'Winston-Salem, North Carolina': 323, 'Bismarck, North Dakota': 324, 'Fargo, North Dakota': 325, 'Grand Forks, North Dakota': 326, 'Minot, North Dakota': 327, 'Bowling Green, Ohio': 328, 'Cleveland Heights, Ohio': 329, 'Cuyahoga Falls, Ohio': 330, 'Grove City, Ohio': 331, 'Huber Heights, Ohio': 332, 'North Olmsted, Ohio': 333, 'North Royalton, Ohio': 334, 'Upper Arlington, Ohio': 335, 'Broken Arrow, Oklahoma': 336, 'Oklahoma City, Oklahoma': 337, 'Grants Pass, Oregon': 338, 'Oregon City, Oregon': 339, 'Bethel Park, Pennsylvania': 340, 'State College, Pennsylvania': 341, 'Cranston, Rhode Island': 342, 'East Providence, Rhode Island': 343, 'Pawtucket, Rhode Island': 344, 'Providence, Rhode Island': 345, 'Warwick, Rhode Island': 346, 'Woonsocket, Rhode Island': 347, 'Charleston, South Carolina': 348, 'Columbia, South Carolina': 349, 'Florence, South Carolina': 350, 'Goose Creek, South Carolina': 351, 'Greenville, South Carolina': 352, 'Hilton Head Island, South Carolina': 353, 'Mount Pleasant, South Carolina': 354, 'North Charleston, South Carolina': 355, 'Rock Hill, South Carolina': 356, 'Spartanburg, South Carolina': 357, 'Summerville, South Carolina': 358, 'Sumter, South Carolina': 359, 'Rapid City, South Dakota': 360, 'Sioux Falls, South Dakota': 361, 'Johnson City, Tennessee': 362, 'La Vergne, Tennessee': 363, 'Cedar Hill, Texas': 364, 'Cedar Park, Texas': 365, 'College Station, Texas': 366, 'Copperas Cove, Texas': 367, 'Corpus Christi, Texas': 368, 'Deer Park, Texas': 369, 'Del Rio, Texas': 370, 'El Paso, Texas': 371, 'Flower Mound, Texas': 372, 'Fort Worth, Texas': 373, 'Grand Prairie, Texas': 374, 'Haltom City, Texas': 375, 'La Porte, Texas': 376, 'League City, Texas': 377, 'Missouri City, Texas': 378, 'New Braunfels, Texas': 379, 'North Richland Hills, Texas': 380, 'Port Arthur, Texas': 381, 'Round Rock, Texas': 382, 'San Angelo, Texas': 383, 'San Antonio, Texas': 384, 'San Juan, Texas': 385, 'San Marcos, Texas': 386, 'Sugar Land, Texas': 387, 'Texas City, Texas': 388, 'The Colony, Texas': 389, 'Wichita Falls, Texas': 390, 'Cottonwood Heights, Utah': 391, 'Pleasant Grove, Utah': 392, 'St. George, Utah': 393, 'Salt Lake City, Utah': 394, 'South Jordan, Utah': 395, 'Spanish Fork, Utah': 396, 'West Valley City, Utah': 397, 'Newport News, Virginia': 398, 'Virginia Beach, Virginia': 399, 'University Place, Washington': 400, 'Charleston, West Virginia': 401, 'Huntington, West Virginia': 402, 'Parkersburg, West Virginia': 403, 'Eau Claire, Wisconsin': 404, 'Fond du Lac, Wisconsin': 405, 'Green Bay, Wisconsin': 406, 'La Crosse, Wisconsin': 407, 'Menomonee Falls, Wisconsin': 408, 'New Berlin, Wisconsin': 409, 'Oak Creek, Wisconsin': 410, 'West Allis, Wisconsin': 411, 'West Bend, Wisconsin': 412, 'Queen Creek, Arizona': 413, 'San Luis, Arizona': 414, 'Paso Robles, California': 415, 'Los Altos, California': 416, 'Los Gatos, California': 417, 'San Carlos, California': 418, 'San Pablo, California': 419, 'Cooper City, Florida': 420, 'Dania Beach, Florida': 421, 'Miami Lakes, Florida': 422, 'Winter Park, Florida': 423, 'Post Falls, Idaho': 424, 'Crown Point, Indiana': 425, 'West Lafayette, Indiana': 426, 'Dover, New Hampshire': 427, 'Rochester, New Hampshire': 428, 'Princeton, New Jersey': 429, 'Cornelius, North Carolina': 430, 'Fuquay-Varina, North Carolina': 431, 'Garner, North Carolina': 432, 'Holly Springs, North Carolina': 433, 'Sanford, North Carolina': 434, 'Aiken, South Carolina': 435, 'Greer, South Carolina': 436, 'Myrtle Beach, South Carolina': 437, 'Mount Juliet, Tennessee': 438, 'Spring Hill, Tennessee': 439, 'Harker Heights, Texas': 440, 'Little Elm, Texas': 441, 'American Fork, Utah': 442, 'Eagle Mountain, Utah': 443, 'Saratoga Springs, Utah': 444, 'Des Moines, Washington': 445, 'Lake Stevens, Washington': 446, 'Morgantown, West Virginia': 447, 'Alabaster, Alabama': 448, 'Auburn, Alabama': 449, 'Birmingham, Alabama': 450, 'Decatur, Alabama': 451, 'Dothan, Alabama': 452, 'Florence, Alabama': 453, 'Gadsden, Alabama': 454, 'Hoover, Alabama': 455, 'Huntsville, Alabama': 456, 'Madison, Alabama': 457, 'Mobile, Alabama': 458, 'Montgomery, Alabama': 459, 'Prattville, Alabama': 460, 'Tuscaloosa, Alabama': 461, 'Anchorage, Alaska': 462, 'Fairbanks, Alaska': 463, 'Juneau, Alaska': 464, 'Avondale, Arizona': 465, 'Buckeye, Arizona': 466, 'Chandler, Arizona': 467, 'Flagstaff, Arizona': 468, 'Gilbert, Arizona': 469, 'Glendale, Arizona': 470, 'Goodyear, Arizona': 471, 'Marana, Arizona': 472, 'Maricopa, Arizona': 473, 'Mesa, Arizona': 474, 'Peoria, Arizona': 475, 'Phoenix, Arizona': 476, 'Prescott, Arizona': 477, 'Scottsdale, Arizona': 478, 'Surprise, Arizona': 479, 'Tempe, Arizona': 480, 'Tucson, Arizona': 481, 'Yuma, Arizona': 482, 'Benton, Arkansas': 483, 'Bentonville, Arkansas': 484, 'Conway, Arkansas': 485, 'Fayetteville, Arkansas': 486, 'Jonesboro, Arkansas': 487, 'Rogers, Arkansas': 488, 'Springdale, Arkansas': 489, 'Adelanto, California': 490, 'Alameda, California': 491, 'Alhambra, California': 492, 'Anaheim, California': 493, 'Antioch, California': 494, 'Arcadia, California': 495, 'Azusa, California': 496, 'Bakersfield, California': 497, 'Beaumont, California': 498, 'Bell, California': 499, 'Bellflower, California': 500, 'Berkeley, California': 501, 'Brea, California': 502, 'Brentwood, California': 503, 'Burbank, California': 504, 'Calexico, California': 505, 'Camarillo, California': 506, 'Campbell, California': 507, 'Carlsbad, California': 508, 'Carson, California': 509, 'Ceres, California': 510, 'Cerritos, California': 511, 'Chico, California': 512, 'Chino, California': 513, 'Claremont, California': 514, 'Clovis, California': 515, 'Coachella, California': 516, 'Colton, California': 517, 'Compton, California': 518, 'Concord, California': 519, 'Corona, California': 520, 'Covina, California': 521, 'Cupertino, California': 522, 'Cypress, California': 523, 'Danville, California': 524, 'Davis, California': 525, 'Delano, California': 526, 'Downey, California': 527, 'Dublin, California': 528, 'Encinitas, California': 529, 'Escondido, California': 530, 'Fairfield, California': 531, 'Folsom, California': 532, 'Fontana, California': 533, 'Fremont, California': 534, 'Fresno, California': 535, 'Fullerton, California': 536, 'Gardena, California': 537, 'Gilroy, California': 538, 'Glendale, California': 539, 'Glendora, California': 540, 'Hanford, California': 541, 'Hawthorne, California': 542, 'Hayward, California': 543, 'Hemet, California': 544, 'Hesperia, California': 545, 'Highland, California': 546, 'Hollister, California': 547, 'Indio, California': 548, 'Inglewood, California': 549, 'Irvine, California': 550, 'Lakewood, California': 551, 'Lancaster, California': 552, 'Lawndale, California': 553, 'Lincoln, California': 554, 'Livermore, California': 555, 'Lodi, California': 556, 'Lompoc, California': 557, 'Lynwood, California': 558, 'Madera, California': 559, 'Manteca, California': 560, 'Martinez, California': 561, 'Menifee, California': 562, 'Merced, California': 563, 'Milpitas, California': 564, 'Modesto, California': 565, 'Monrovia, California': 566, 'Montclair, California': 567, 'Montebello, California': 568, 'Moorpark, California': 569, 'Murrieta, California': 570, 'Napa, California': 571, 'Newark, California': 572, 'Norwalk, California': 573, 'Novato, California': 574, 'Oakland, California': 575, 'Oakley, California': 576, 'Oceanside, California': 577, 'Ontario, California': 578, 'Orange, California': 579, 'Oxnard, California': 580, 'Pacifica, California': 581, 'Palmdale, California': 582, 'Paramount, California': 583, 'Pasadena, California': 584, 'Perris, California': 585, 'Petaluma, California': 586, 'Pittsburg, California': 587, 'Placentia, California': 588, 'Pleasanton, California': 589, 'Pomona, California': 590, 'Porterville, California': 591, 'Poway, California': 592, 'Redding, California': 593, 'Redlands, California': 594, 'Rialto, California': 595, 'Richmond, California': 596, 'Riverside, California': 597, 'Rocklin, California': 598, 'Rosemead, California': 599, 'Roseville, California': 600, 'Sacramento, California': 601, 'Salinas, California': 602, 'Santee, California': 603, 'Seaside, California': 604, 'Stanton, California': 605, 'Stockton, California': 606, 'Sunnyvale, California': 607, 'Temecula, California': 608, 'Torrance, California': 609, 'Tracy, California': 610, 'Tulare, California': 611, 'Turlock, California': 612, 'Tustin, California': 613, 'Upland, California': 614, 'Vacaville, California': 615, 'Vallejo, California': 616, 'Victorville, California': 617, 'Visalia, California': 618, 'Vista, California': 619, 'Watsonville, California': 620, 'Westminster, California': 621, 'Whittier, California': 622, 'Wildomar, California': 623, 'Woodland, California': 624, 'Yucaipa, California': 625, 'Arvada, Colorado': 626, 'Aurora, Colorado': 627, 'Boulder, Colorado': 628, 'Brighton, Colorado': 629, 'Broomfield, Colorado': 630, 'Centennial, Colorado': 631, 'Denver, Colorado': 632, 'Englewood, Colorado': 633, 'Greeley, Colorado': 634, 'Lakewood, Colorado': 635, 'Littleton, Colorado': 636, 'Longmont, Colorado': 637, 'Loveland, Colorado': 638, 'Northglenn, Colorado': 639, 'Parker, Colorado': 640, 'Pueblo, Colorado': 641, 'Thornton, Colorado': 642, 'Westminster, Colorado': 643, 'Bridgeport, Connecticut': 644, 'Bristol, Connecticut': 645, 'Danbury, Connecticut': 646, 'Hartford, Connecticut': 647, 'Meriden, Connecticut': 648, 'Middletown, Connecticut': 649, 'Milford, Connecticut': 650, 'Naugatuck, Connecticut': 651, 'Norwalk, Connecticut': 652, 'Norwich, Connecticut': 653, 'Shelton, Connecticut': 654, 'Stamford, Connecticut': 655, 'Torrington, Connecticut': 656, 'Waterbury, Connecticut': 657, 'Dover, Delaware': 658, 'Newark, Delaware': 659, 'Wilmington, Delaware': 660, 'Apopka, Florida': 661, 'Aventura, Florida': 662, 'Bradenton, Florida': 663, 'Clearwater, Florida': 664, 'Davie, Florida': 665, 'Deltona, Florida': 666, 'Doral, Florida': 667, 'Dunedin, Florida': 668, 'Gainesville, Florida': 669, 'Greenacres, Florida': 670, 'Hialeah, Florida': 671, 'Hollywood, Florida': 672, 'Homestead, Florida': 673, 'Jacksonville, Florida': 674, 'Jupiter, Florida': 675, 'Kissimmee, Florida': 676, 'Lakeland, Florida': 677, 'Largo, Florida': 678, 'Lauderhill, Florida': 679, 'Margate, Florida': 680, 'Melbourne, Florida': 681, 'Miami, Florida': 682, 'Miramar, Florida': 683, 'Ocala, Florida': 684, 'Ocoee, Florida': 685, 'Orlando, Florida': 686, 'Oviedo, Florida': 687, 'Pensacola, Florida': 688, 'Plantation, Florida': 689, 'Sanford, Florida': 690, 'Sarasota, Florida': 691, 'Sunrise, Florida': 692, 'Tallahassee, Florida': 693, 'Tamarac, Florida': 694, 'Tampa, Florida': 695, 'Titusville, Florida': 696, 'Wellington, Florida': 697, 'Weston, Florida': 698, 'Albany, Georgia': 699, 'Alpharetta, Georgia': 700, 'Atlanta, Georgia': 701, 'Columbus, Georgia': 702, 'Dalton, Georgia': 703, 'Douglasville, Georgia': 704, 'Dunwoody, Georgia': 705, 'Gainesville, Georgia': 706, 'Hinesville, Georgia': 707, 'Marietta, Georgia': 708, 'Milton, Georgia': 709, 'Newnan, Georgia': 710, 'Rome, Georgia': 711, 'Roswell, Georgia': 712, 'Savannah, Georgia': 713, 'Smyrna, Georgia': 714, 'Valdosta, Georgia': 715, 'Caldwell, Idaho': 716, 'Lewiston, Idaho': 717, 'Meridian, Idaho': 718, 'Nampa, Idaho': 719, 'Pocatello, Idaho': 720, 'Addison, Illinois': 721, 'Algonquin, Illinois': 722, 'Aurora, Illinois': 723, 'Bartlett, Illinois': 724, 'Belleville, Illinois': 725, 'Berwyn, Illinois': 726, 'Bloomington, Illinois': 727, 'Bolingbrook, Illinois': 728, 'Carpentersville, Illinois': 729, 'Champaign, Illinois': 730, 'Chicago, Illinois': 731, 'Cicero, Illinois': 732, 'Danville, Illinois': 733, 'Decatur, Illinois': 734, 'DeKalb, Illinois': 735, 'Elgin, Illinois': 736, 'Elmhurst, Illinois': 737, 'Evanston, Illinois': 738, 'Galesburg, Illinois': 739, 'Glenview, Illinois': 740, 'Gurnee, Illinois': 741, 'Joliet, Illinois': 742, 'Lombard, Illinois': 743, 'Moline, Illinois': 744, 'Mundelein, Illinois': 745, 'Naperville, Illinois': 746, 'Normal, Illinois': 747, 'Northbrook, Illinois': 748, 'Oswego, Illinois': 749, 'Palatine, Illinois': 750, 'Pekin, Illinois': 751, 'Peoria, Illinois': 752, 'Plainfield, Illinois': 753, 'Quincy, Illinois': 754, 'Rockford, Illinois': 755, 'Romeoville, Illinois': 756, 'Schaumburg, Illinois': 757, 'Skokie, Illinois': 758, 'Springfield, Illinois': 759, 'Streamwood, Illinois': 760, 'Urbana, Illinois': 761, 'Waukegan, Illinois': 762, 'Wheaton, Illinois': 763, 'Wheeling, Illinois': 764, 'Woodridge, Illinois': 765, 'Anderson, Indiana': 766, 'Bloomington, Indiana': 767, 'Carmel, Indiana': 768, 'Columbus, Indiana': 769, 'Elkhart, Indiana': 770, 'Evansville, Indiana': 771, 'Fishers, Indiana': 772, 'Gary, Indiana': 773, 'Goshen, Indiana': 774, 'Greenwood, Indiana': 775, 'Hammond, Indiana': 776, 'Indianapolis, Indiana': 777, 'Jeffersonville, Indiana': 778, 'Kokomo, Indiana': 779, 'Lafayette, Indiana': 780, 'Lawrence, Indiana': 781, 'Merrillville, Indiana': 782, 'Mishawaka, Indiana': 783, 'Muncie, Indiana': 784, 'Noblesville, Indiana': 785, 'Portage, Indiana': 786, 'Richmond, Indiana': 787, 'Valparaiso, Indiana': 788, 'Westfield, Indiana': 789, 'Ames, Iowa': 790, 'Ankeny, Iowa': 791, 'Bettendorf, Iowa': 792, 'Davenport, Iowa': 793, 'Dubuque, Iowa': 794, 'Marion, Iowa': 795, 'Urbandale, Iowa': 796, 'Waterloo, Iowa': 797, 'Hutchinson, Kansas': 798, 'Lawrence, Kansas': 799, 'Leavenworth, Kansas': 800, 'Leawood, Kansas': 801, 'Lenexa, Kansas': 802, 'Manhattan, Kansas': 803, 'Olathe, Kansas': 804, 'Salina, Kansas': 805, 'Shawnee, Kansas': 806, 'Topeka, Kansas': 807, 'Wichita, Kansas': 808, 'Covington, Kentucky': 809, 'Hopkinsville, Kentucky': 810, 'Lexington-Fayette, Kentucky': 811, 'Owensboro, Kentucky': 812, 'Richmond, Kentucky': 813, 'Alexandria, Louisiana': 814, 'Houma, Louisiana': 815, 'Kenner, Louisiana': 816, 'Lafayette, Louisiana': 817, 'Monroe, Louisiana': 818, 'Shreveport, Louisiana': 819, 'Bangor, Maine': 820, 'Lewiston, Maine': 821, 'Portland, Maine': 822, 'Annapolis, Maryland': 823, 'Baltimore, Maryland': 824, 'Bowie, Maryland': 825, 'Frederick, Maryland': 826, 'Gaithersburg, Maryland': 827, 'Hagerstown, Maryland': 828, 'Rockville, Maryland': 829, 'Salisbury, Maryland': 830, 'Attleboro, Massachusetts': 831, 'Beverly, Massachusetts': 832, 'Boston, Massachusetts': 833, 'Brockton, Massachusetts': 834, 'Cambridge, Massachusetts': 835, 'Chelsea, Massachusetts': 836, 'Chicopee, Massachusetts': 837, 'Everett, Massachusetts': 838, 'Fitchburg, Massachusetts': 839, 'Haverhill, Massachusetts': 840, 'Holyoke, Massachusetts': 841, 'Lawrence, Massachusetts': 842, 'Leominster, Massachusetts': 843, 'Lowell, Massachusetts': 844, 'Lynn, Massachusetts': 845, 'Malden, Massachusetts': 846, 'Marlborough, Massachusetts': 847, 'Medford, Massachusetts': 848, 'Newton, Massachusetts': 849, 'Peabody, Massachusetts': 850, 'Pittsfield, Massachusetts': 851, 'Quincy, Massachusetts': 852, 'Revere, Massachusetts': 853, 'Salem, Massachusetts': 854, 'Somerville, Massachusetts': 855, 'Springfield, Massachusetts': 856, 'Taunton, Massachusetts': 857, 'Waltham, Massachusetts': 858, 'Westfield, Massachusetts': 859, 'Woburn, Massachusetts': 860, 'Worcester, Massachusetts': 861, 'Dearborn, Michigan': 862, 'Detroit, Michigan': 863, 'Eastpointe, Michigan': 864, 'Flint, Michigan': 865, 'Holland, Michigan': 866, 'Jackson, Michigan': 867, 'Kalamazoo, Michigan': 868, 'Kentwood, Michigan': 869, 'Lansing, Michigan': 870, 'Livonia, Michigan': 871, 'Midland, Michigan': 872, 'Muskegon, Michigan': 873, 'Novi, Michigan': 874, 'Pontiac, Michigan': 875, 'Portage, Michigan': 876, 'Roseville, Michigan': 877, 'Saginaw, Michigan': 878, 'Southfield, Michigan': 879, 'Southgate, Michigan': 880, 'Taylor, Michigan': 881, 'Troy, Michigan': 882, 'Warren, Michigan': 883, 'Westland, Michigan': 884, 'Wyoming, Michigan': 885, 'Andover, Minnesota': 886, 'Blaine, Minnesota': 887, 'Bloomington, Minnesota': 888, 'Burnsville, Minnesota': 889, 'Duluth, Minnesota': 890, 'Eagan, Minnesota': 891, 'Edina, Minnesota': 892, 'Lakeville, Minnesota': 893, 'Mankato, Minnesota': 894, 'Maplewood, Minnesota': 895, 'Minneapolis, Minnesota': 896, 'Minnetonka, Minnesota': 897, 'Moorhead, Minnesota': 898, 'Plymouth, Minnesota': 899, 'Richfield, Minnesota': 900, 'Rochester, Minnesota': 901, 'Roseville, Minnesota': 902, 'Shakopee, Minnesota': 903, 'Woodbury, Minnesota': 904, 'Biloxi, Mississippi': 905, 'Greenville, Mississippi': 906, 'Gulfport, Mississippi': 907, 'Hattiesburg, Mississippi': 908, 'Jackson, Mississippi': 909, 'Meridian, Mississippi': 910, 'Southaven, Mississippi': 911, 'Tupelo, Mississippi': 912, 'Ballwin, Missouri': 913, 'Chesterfield, Missouri': 914, 'Columbia, Missouri': 915, 'Florissant, Missouri': 916, 'Independence, Missouri': 917, 'Joplin, Missouri': 918, 'Springfield, Missouri': 919, 'Wildwood, Missouri': 920, 'Billings, Montana': 921, 'Bozeman, Montana': 922, 'Missoula, Montana': 923, 'Bellevue, Nebraska': 924, 'Kearney, Nebraska': 925, 'Lincoln, Nebraska': 926, 'Omaha, Nebraska': 927, 'Henderson, Nevada': 928, 'Reno, Nevada': 929, 'Sparks, Nevada': 930, 'Akron, Ohio': 931, 'Beavercreek, Ohio': 932, 'Brunswick, Ohio': 933, 'Canton, Ohio': 934, 'Cincinnati, Ohio': 935, 'Cleveland, Ohio': 936, 'Columbus, Ohio': 937, 'Dayton, Ohio': 938, 'Delaware, Ohio': 939, 'Dublin, Ohio': 940, 'Elyria, Ohio': 941, 'Euclid, Ohio': 942, 'Fairborn, Ohio': 943, 'Fairfield, Ohio': 944, 'Findlay, Ohio': 945, 'Gahanna, Ohio': 946, 'Hamilton, Ohio': 947, 'Kettering, Ohio': 948, 'Lakewood, Ohio': 949, 'Lancaster, Ohio': 950, 'Lima, Ohio': 951, 'Lorain, Ohio': 952, 'Mansfield, Ohio': 953, 'Marion, Ohio': 954, 'Mason, Ohio': 955, 'Massillon, Ohio': 956, 'Mentor, Ohio': 957, 'Middletown, Ohio': 958, 'Newark, Ohio': 959, 'Parma, Ohio': 960, 'Reynoldsburg, Ohio': 961, 'Springfield, Ohio': 962, 'Stow, Ohio': 963, 'Strongsville, Ohio': 964, 'Toledo, Ohio': 965, 'Warren, Ohio': 966, 'Westerville, Ohio': 967, 'Westlake, Ohio': 968, 'Youngstown, Ohio': 969, 'Bartlesville, Oklahoma': 970, 'Edmond, Oklahoma': 971, 'Enid, Oklahoma': 972, 'Lawton, Oklahoma': 973, 'Moore, Oklahoma': 974, 'Muskogee, Oklahoma': 975, 'Norman, Oklahoma': 976, 'Stillwater, Oklahoma': 977, 'Tulsa, Oklahoma': 978, 'Albany, Oregon': 979, 'Beaverton, Oregon': 980, 'Bend, Oregon': 981, 'Corvallis, Oregon': 982, 'Eugene, Oregon': 983, 'Gresham, Oregon': 984, 'Hillsboro, Oregon': 985, 'Keizer, Oregon': 986, 'McMinnville, Oregon': 987, 'Medford, Oregon': 988, 'Portland, Oregon': 989, 'Salem, Oregon': 990, 'Springfield, Oregon': 991, 'Tigard, Oregon': 992, 'Allentown, Pennsylvania': 993, 'Altoona, Pennsylvania': 994, 'Bethlehem, Pennsylvania': 995, 'Chester, Pennsylvania': 996, 'Erie, Pennsylvania': 997, 'Harrisburg, Pennsylvania': 998, 'Lancaster, Pennsylvania': 999, 'Norristown, Pennsylvania': 1000, 'Philadelphia, Pennsylvania': 1001, 'Pittsburgh, Pennsylvania': 1002, 'Reading, Pennsylvania': 1003, 'Scranton, Pennsylvania': 1004, 'Wilkes-Barre, Pennsylvania': 1005, 'York, Pennsylvania': 1006, 'Bartlett, Tennessee': 1007, 'Brentwood, Tennessee': 1008, 'Chattanooga, Tennessee': 1009, 'Clarksville, Tennessee': 1010, 'Cleveland, Tennessee': 1011, 'Collierville, Tennessee': 1012, 'Columbia, Tennessee': 1013, 'Cookeville, Tennessee': 1014, 'Franklin, Tennessee': 1015, 'Gallatin, Tennessee': 1016, 'Germantown, Tennessee': 1017, 'Hendersonville, Tennessee': 1018, 'Jackson, Tennessee': 1019, 'Kingsport, Tennessee': 1020, 'Knoxville, Tennessee': 1021, 'Memphis, Tennessee': 1022, 'Murfreesboro, Tennessee': 1023, 'Nashville-Davidson, Tennessee': 1024, 'Smyrna, Tennessee': 1025, 'Abilene, Texas': 1026, 'Allen, Texas': 1027, 'Amarillo, Texas': 1028, 'Arlington, Texas': 1029, 'Austin, Texas': 1030, 'Baytown, Texas': 1031, 'Beaumont, Texas': 1032, 'Bedford, Texas': 1033, 'Brownsville, Texas': 1034, 'Bryan, Texas': 1035, 'Burleson, Texas': 1036, 'Carrollton, Texas': 1037, 'Conroe, Texas': 1038, 'Coppell, Texas': 1039, 'Dallas, Texas': 1040, 'Denton, Texas': 1041, 'DeSoto, Texas': 1042, 'Duncanville, Texas': 1043, 'Edinburg, Texas': 1044, 'Euless, Texas': 1045, 'Friendswood, Texas': 1046, 'Frisco, Texas': 1047, 'Galveston, Texas': 1048, 'Garland, Texas': 1049, 'Georgetown, Texas': 1050, 'Grapevine, Texas': 1051, 'Harlingen, Texas': 1052, 'Houston, Texas': 1053, 'Huntsville, Texas': 1054, 'Hurst, Texas': 1055, 'Irving, Texas': 1056, 'Keller, Texas': 1057, 'Killeen, Texas': 1058, 'Lancaster, Texas': 1059, 'Laredo, Texas': 1060, 'Lewisville, Texas': 1061, 'Longview, Texas': 1062, 'Lubbock, Texas': 1063, 'Lufkin, Texas': 1064, 'McAllen, Texas': 1065, 'McKinney, Texas': 1066, 'Mansfield, Texas': 1067, 'Mesquite, Texas': 1068, 'Midland, Texas': 1069, 'Mission, Texas': 1070, 'Nacogdoches, Texas': 1071, 'Odessa, Texas': 1072, 'Pasadena, Texas': 1073, 'Pearland, Texas': 1074, 'Pflugerville, Texas': 1075, 'Pharr, Texas': 1076, 'Plano, Texas': 1077, 'Richardson, Texas': 1078, 'Rockwall, Texas': 1079, 'Rosenberg, Texas': 1080, 'Rowlett, Texas': 1081, 'Schertz, Texas': 1082, 'Sherman, Texas': 1083, 'Socorro, Texas': 1084, 'Temple, Texas': 1085, 'Texarkana, Texas': 1086, 'Tyler, Texas': 1087, 'Victoria, Texas': 1088, 'Waco, Texas': 1089, 'Weslaco, Texas': 1090, 'Wylie, Texas': 1091, 'Bountiful, Utah': 1092, 'Clearfield, Utah': 1093, 'Draper, Utah': 1094, 'Layton, Utah': 1095, 'Lehi, Utah': 1096, 'Logan, Utah': 1097, 'Murray, Utah': 1098, 'Ogden, Utah': 1099, 'Orem, Utah': 1100, 'Provo, Utah': 1101, 'Riverton, Utah': 1102, 'Roy, Utah': 1103, 'Sandy, Utah': 1104, 'Taylorsville, Utah': 1105, 'Tooele, Utah': 1106, 'Burlington, Vermont': 1107, 'Alexandria, Virginia': 1108, 'Blacksburg, Virginia': 1109, 'Charlottesville, Virginia': 1110, 'Chesapeake, Virginia': 1111, 'Danville, Virginia': 1112, 'Hampton, Virginia': 1113, 'Harrisonburg, Virginia': 1114, 'Leesburg, Virginia': 1115, 'Lynchburg, Virginia': 1116, 'Manassas, Virginia': 1117, 'Norfolk, Virginia': 1118, 'Petersburg, Virginia': 1119, 'Portsmouth, Virginia': 1120, 'Richmond, Virginia': 1121, 'Roanoke, Virginia': 1122, 'Suffolk, Virginia': 1123, 'Auburn, Washington': 1124, 'Bellevue, Washington': 1125, 'Bellingham, Washington': 1126, 'Bothell, Washington': 1127, 'Bremerton, Washington': 1128, 'Burien, Washington': 1129, 'Edmonds, Washington': 1130, 'Everett, Washington': 1131, 'Issaquah, Washington': 1132, 'Kennewick, Washington': 1133, 'Kent, Washington': 1134, 'Kirkland, Washington': 1135, 'Lacey, Washington': 1136, 'Lakewood, Washington': 1137, 'Longview, Washington': 1138, 'Lynnwood, Washington': 1139, 'Marysville, Washington': 1140, 'Olympia, Washington': 1141, 'Pasco, Washington': 1142, 'Puyallup, Washington': 1143, 'Redmond, Washington': 1144, 'Renton, Washington': 1145, 'Richland, Washington': 1146, 'Sammamish, Washington': 1147, 'Seattle, Washington': 1148, 'Shoreline, Washington': 1149, 'Spokane, Washington': 1150, 'Tacoma, Washington': 1151, 'Vancouver, Washington': 1152, 'Wenatchee, Washington': 1153, 'Yakima, Washington': 1154, 'Appleton, Wisconsin': 1155, 'Beloit, Wisconsin': 1156, 'Brookfield, Wisconsin': 1157, 'Franklin, Wisconsin': 1158, 'Greenfield, Wisconsin': 1159, 'Janesville, Wisconsin': 1160, 'Kenosha, Wisconsin': 1161, 'Madison, Wisconsin': 1162, 'Manitowoc, Wisconsin': 1163, 'Milwaukee, Wisconsin': 1164, 'Oshkosh, Wisconsin': 1165, 'Racine, Wisconsin': 1166, 'Sheboygan, Wisconsin': 1167, 'Waukesha, Wisconsin': 1168, 'Wausau, Wisconsin': 1169, 'Wauwatosa, Wisconsin': 1170, 'Casper, Wyoming': 1171, 'Cheyenne, Wyoming': 1172, 'Laramie, Wyoming': 1173, 'Opelika, Alabama': 1174, 'Kingman, Arizona': 1175, 'Sahuarita, Arizona': 1176, 'Sherwood, Arkansas': 1177, 'Atascadero, California': 1178, 'Banning, California': 1179, 'Burlingame, California': 1180, 'Goleta, California': 1181, 'Saratoga, California': 1182, 'Fountain, Colorado': 1183, 'Lafayette, Colorado': 1184, 'Windsor, Colorado': 1185, 'Clermont, Florida': 1186, 'Parkland, Florida': 1187, 'Canton, Georgia': 1188, 'Chamblee, Georgia': 1189, 'Kennesaw, Georgia': 1190, 'LaGrange, Georgia': 1191, 'Lawrenceville, Georgia': 1192, 'Statesboro, Georgia': 1193, 'Woodstock, Georgia': 1194, 'Plainfield, Indiana': 1195, 'Elizabethtown, Kentucky': 1196, 'Florence, Kentucky': 1197, 'Georgetown, Kentucky': 1198, 'Nicholasville, Kentucky': 1199, 'Gloucester, Massachusetts': 1200, 'Savage, Minnesota': 1201, 'Liberty, Missouri': 1202, 'Wentzville, Missouri': 1203, 'Helena, Montana': 1204, 'Hilliard, Ohio': 1205, 'Owasso, Oklahoma': 1206, 'Shawnee, Oklahoma': 1207, 'Redmond, Oregon': 1208, 'Lebanon, Tennessee': 1209, 'Morristown, Tennessee': 1210, 'Cibolo, Texas': 1211, 'Cleburne, Texas': 1212, 'Kyle, Texas': 1213, 'Leander, Texas': 1214, 'Midlothian, Texas': 1215, 'Southlake, Texas': 1216, 'Waxahachie, Texas': 1217, 'Weatherford, Texas': 1218, 'Herriman, Utah': 1219, 'Holladay, Utah': 1220, 'Kaysville, Utah': 1221, 'Midvale, Utah': 1222, 'Springville, Utah': 1223, 'Syracuse, Utah': 1224, 'Pullman, Washington': 1225, 'Fitchburg, Wisconsin': 1226, 'Gillette, Wyoming': 1227, 'Elk Grove, California': 1228, 'La Quinta, California': 1229, 'San Clemente, California': 1230, 'San Juan Capistrano, California': 1231, 'New Britain, Connecticut': 1232, 'Daytona Beach, Florida': 1233, 'Lauderdale Lakes, Florida': 1234, 'North Lauderdale, Florida': 1235, 'Oakland Park, Florida': 1236, 'Pinellas Park, Florida': 1237, 'Port Orange, Florida': 1238, 'Riviera Beach, Florida': 1239, 'Royal Palm Beach, Florida': 1240, 'Johns Creek, Georgia': 1241, 'Calumet City, Illinois': 1242, 'Carol Stream, Illinois': 1243, 'Crystal Lake, Illinois': 1244, 'Glendale Heights, Illinois': 1245, 'Hanover Park, Illinois': 1246, 'Hoffman Estates, Illinois': 1247, 'North Chicago, Illinois': 1248, 'Michigan City, Indiana': 1249, 'West Des Moines, Iowa': 1250, 'Bossier City, Louisiana': 1251, 'Long Branch, New Jersey': 1252, 'Sayreville, New Jersey': 1253, 'Freeport, New York': 1254, 'Spring Valley, New York': 1255, 'Indian Trail, North Carolina': 1256, 'Midwest City, Oklahoma': 1257, 'Lake Oswego, Oregon': 1258, 'West Jordan, Utah': 1259, 'Federal Way, Washington': 1260, 'Mount Vernon, Washington': 1261, 'Spokane Valley, Washington': 1262, 'Walla Walla, Washington': 1263, 'Matthews, North Carolina': 1264, 'West Fargo, North Dakota': 1265, 'North Ridgeville, Ohio': 1266, 'Farmers Branch, Texas': 1267, 'Cedar City, Utah': 1268, 'Sun Prairie, Wisconsin': 1269, 'Ventura, California': 1270, 'Honolulu, Hawaii': 1271, 'Louisville, Kentucky': 1272, 'Methuen, Massachusetts': 1273, 'Watertown, Massachusetts': 1274, "Lee's Summit, Missouri": 1275, "O'Fallon, Missouri": 1276, 'DeLand, Florida': 1277, }; export default CityData;
30.523772
44
0.658521
75a5fbeea5b59ca28490162b2e990b1c26b8e118
365
js
JavaScript
src/utils/db.js
fstnetwork/transaction-maker
422da8baa9f2860c0609f640dfad367466ec7683
[ "MIT" ]
null
null
null
src/utils/db.js
fstnetwork/transaction-maker
422da8baa9f2860c0609f640dfad367466ec7683
[ "MIT" ]
4
2021-05-16T22:32:15.000Z
2021-05-16T22:32:16.000Z
src/utils/db.js
fstnetwork/transaction-maker
422da8baa9f2860c0609f640dfad367466ec7683
[ "MIT" ]
null
null
null
const path = require("path"); const level = require("level"); let db_pub = null; let db_tag = null; function setDB(argv) { if (db_pub === null && db_tag === null) { db_pub = level(path.resolve(argv.root_dir, "level_db_pub")); db_tag = level(path.resolve(argv.root_dir, "level_db_tag")); } return [db_pub, db_tag]; } module.exports = { setDB, };
19.210526
64
0.643836
75a6510708c4a976bd82ef752bcd8f7975b4a8f5
1,319
js
JavaScript
events/ready.js
ee3devYT/djs-command-handler13
420d770f8a85d477d3f29ef11c704ff7da6191e6
[ "MIT" ]
3
2021-11-15T02:43:26.000Z
2022-01-07T16:10:30.000Z
events/ready.js
ee3devYT/djs-command-handler13
420d770f8a85d477d3f29ef11c704ff7da6191e6
[ "MIT" ]
null
null
null
events/ready.js
ee3devYT/djs-command-handler13
420d770f8a85d477d3f29ef11c704ff7da6191e6
[ "MIT" ]
null
null
null
const chalk = require('chalk'); const discord = require('discord.js') module.exports = { run: (client) => { client.user.setPresence({ activities: [{ name: "Ee3Dev on YT", // replace this with whatever you want type: "WATCHING" // there are only 5 types of activity PLAYING, STREAMING, WATCHING, LISTENING, COMPETING }], status: "online" // there are only 3 types of status dnd, online, idle }) //======================================================= IGNORE ====================================================================== console.log(chalk.bold.yellowBright('📣 Name - ') + (chalk.italic.greenBright(`${client.user.tag}`))); console.log(chalk.bold.yellowBright('📣 ID - ') + (chalk.italic.greenBright(`${client.user.id}`))); console.log(chalk.bold.yellowBright('📣 Servers - ') + (chalk.italic.greenBright(`${client.guilds.cache.size}`))) console.log(chalk.bold.yellowBright('📣 Users - ') + (chalk.italic.greenBright(`${client.users.cache.size}`))) console.log(chalk.bold.yellowBright('📣 Status - ') + (chalk.italic.greenBright(`Ready!`))) //======================================================================================================================================== } }
57.347826
138
0.489765
75a658480c2f6bdaf940e191c2b4b90aa8d581e3
181
js
JavaScript
src/Edabit/10 - NextPerfectSquare/index.js
Dheyson/js-tdd-course
438e6aac828469da2aa0c12a43c630689636d649
[ "MIT" ]
null
null
null
src/Edabit/10 - NextPerfectSquare/index.js
Dheyson/js-tdd-course
438e6aac828469da2aa0c12a43c630689636d649
[ "MIT" ]
1
2021-05-11T15:44:28.000Z
2021-05-11T15:44:28.000Z
src/10 - NextPerfectSquare/index.js
dheysonalves/js-tdd-course
827a2a62a1efd08c8a2cf395a5281d16845d127f
[ "MIT" ]
null
null
null
const nextSquare = ((squareNumber) => { if (!Number.isInteger(Math.sqrt(squareNumber))) return null; return (Math.sqrt(squareNumber) + 1) ** 2; }); export default nextSquare;
22.625
62
0.690608
75a7e20213098eb527f977c7a755261d6a39e6b3
423
js
JavaScript
app/js/store/user/reducer.js
longtc/minimal-react-app
22571cc0566e8bf512ab2c8ceb96abad3bfc6141
[ "MIT" ]
null
null
null
app/js/store/user/reducer.js
longtc/minimal-react-app
22571cc0566e8bf512ab2c8ceb96abad3bfc6141
[ "MIT" ]
null
null
null
app/js/store/user/reducer.js
longtc/minimal-react-app
22571cc0566e8bf512ab2c8ceb96abad3bfc6141
[ "MIT" ]
null
null
null
import produce from "immer"; import { LOGIN_SUCCESS } from "./action"; export const initialUser = { accessToken: "", refreshToken: "", userId: "", userName: "", }; export function userReducer(state, action) { // eslint-disable-next-line no-unused-vars return produce(state, draft => { switch (action.type) { case LOGIN_SUCCESS: { return action.user; // break; } } }); }
18.391304
44
0.605201
75a811c7130cac2775f0e09d3b4363f9636737bf
157,447
js
JavaScript
1.1/essence.js
Berkmann18/Essencejs
a0aef7bf7fce4b6bb113063306ccc849596327f4
[ "MIT" ]
2
2017-01-09T00:38:26.000Z
2019-04-29T10:24:44.000Z
1.1/essence.js
Berkmann18/EssenceJS
a0aef7bf7fce4b6bb113063306ccc849596327f4
[ "MIT" ]
null
null
null
1.1/essence.js
Berkmann18/EssenceJS
a0aef7bf7fce4b6bb113063306ccc849596327f4
[ "MIT" ]
null
null
null
"use strict"; /* global Essence:false, $G, Sys, base64, UnitTest, modules, debugging */ /* eslint no-unused-vars: 0 */ /* eslint no-undef: 0 */ /** * @module essence * @description Core module of the framework * @license MIT * @author Maximilian Berkmann <maxieberkmann@gmail.com> * @copyright Maximilian Berkmann 2016 * @typedef {(number|string)} NumberLike * @typedef {(number|number[])} Nums * @typedef {(string|string[])} Str * @typedef {(number|boolean)} Bool * @typedef {(Array|Object|string)} Iterable * @typedef {(Array|Object)} Dict * @typedef {(XML|string)} Code * @typedef {(Node|TreeNode|NTreeNode|Vertex)} Node * @requires modules/Files * @requires modules/DOM * @requires modules/UI * @requires modules/Web * @requires modules/Misc * @requires modules/Ajax * @requires modules/DataStruct * @requires modules/Maths * @requires modules/Security * @requires modules/QTest */ /** * @description This is the main object of the library as well as being the core module of the framework. * @type {{version: string, author: string, description: string, source: string, element: $n, handleError: module:essence.handleError, say: module:essence.say, applyCSS: module:essence.applyCSS, addCSS: module:essence.addCSS, addJS: module:essence.addJS, update: module:essence.update, eps: number, emptyDoc: module:essence.emptyDoc, editor: module:essence.editor, processList: Array, global: null, addProcess: module:essence.addProcess, processSize: number, serverList: Array, addServer: module:essence.addServer, serverSize: number, toString: module:essence.toString, txt2print: string, addToPrinter: module:essence.addToPrinter, print: module:essence.print, preInit: module:essence.preInit, init: module:essence.init, time: module:essence.time, sayClr: module:essence.sayClr, ask: module:essence.ask, isComplete: module:essence.isComplete, loadedModules: Array, updateAll: module:essence.updateAll}} * @this Essence * @namespace * @exports essence * @since 1.0 * @property {NumberLike} Essence.version EssenceJS' version * @property {string} Essence.author Author * @property {string} Essence.description Description of EssenceJS * @property {string} Essence.source Source of the script * @property {HTMLElement} Essence.element $n element * @property {function((string|Error), (URL|string), NumberLike)} Essence.handleError Error handler * @property {function(...string)} Essence.say EssenceJS's console logger * @property {function(boolean)} Essence.applyCSS Apply EssenceJS's CSS * @property {function(Code)} Essence.addCSS Add CSS rules * @property {function(string)} Essence.addJS Add JS commands * @property {Function} Essence.update EssenceJS' self update's mechanism * @property {number} Essence.eps Matlab's epsilon * @property {function(string, string)} Essence.emptyDoc Empty the document * @property {function(Code)} Essence.editor In-browser editor * @property {process[]} Essence.processList Process list * @property {Object} Essence.global $G * @property {function(process)} Essence.addProcess Process adder * @property {number} Essence.processSize Total process size * @property {server[]} Essence.serverList Server list * @property {function(server)} Essence.addServer Server adder * @property {number} Essence.serverSize Total server size * @property {function(): string} Essence.toString String representation of EssenceJS's namespace * @property {string} Essence.txt2print Text to print * @property {function(string, string)} Essence.addToPrinter Add text to the printer and print them * @property {function(string, string)} Essence.print Print stuff to the screen * @property {Function} Essence.preInit Pre-initialisation * @property {Function} Essence.init Initialisation * @property {function(...string)} Essence.time Say something with the time stamped * @property {function(NumberLike[])} Essence.sayClr Log the colour * @property {function(string, function(string))} Essence.ask Ask something to the user * @property {function(): boolean} Essence.isComplete Module inclusion completeness check * @property {string[]} Essence.loadedModules List of loaded modules * @property {Function} Essence.updateAll Update all modules */ var Essence = { version: "1.1b", author: "Maximilian Berkmann", description: "library used for DHTML connexions, maths, database management and cryptography", source: "http://berkmann18.github.io/rsc/essence.js", element: $n, handleError: function (msg, url, line) { isType(msg, "Error")? alert("[Essence.js] An error has occurred (line/column " + msg.lineNumber + "/" + msg.columnNumber + " of " + msg.fileName + ").\n\nMessage: " + msg.stack): alert("[Essence.js] An error has occurred (line " + line + " of " + url + ").\n\nMessage: " + msg) }, say: function (msg, type, style, style0, style1, style2) { //Say something in the console type = isNon(type)? "": type.slice(0, 4).toLowerCase(); if (style && !style0) { if (type === "info") console.info("%c[EssenceJS]%c " + msg, "color: #00f; text-decoration: bold;-webkit-text-decoration: bold;-moz-text-decoration: bold;", "color: #000", style); else if (type === "erro") console.error("%c[EssenceJS]%c " + msg, "color: #f00; text-decoration: bold;-webkit-text-decoration: bold;-moz-text-decoration: bold;", "color: #000", style); else if (type === "warn") console.warn("%c[EssenceJS]%c " + msg, "color: #fc0; text-decoration: bold;-webkit-text-decoration: bold;-moz-text-decoration: bold;", "color: #000", style); else if (type === "succ") console.log("%c[EssenceJS]%c " + msg, "color: #0f0; text-decoration: bold;-webkit-text-decoration: bold;-moz-text-decoration: bold;", "color: #000", style); else console.log("%c[EssenceJS]%c " + msg, "color: #808080; text-decoration: bold;-webkit-text-decoration: bold;-moz-text-decoration: bold;", "color: #000", style); } else if (style && style0 && !style1) { if (type === "info") console.info("%c[EssenceJS]%c " + msg, "color: #00f; text-decoration: bold;-webkit-text-decoration: bold;-moz-text-decoration: bold;", "color: #000", style, style0); else if (type === "erro") console.error("%c[EssenceJS]%c " + msg, "color: #f00; text-decoration: bold;-webkit-text-decoration: bold;-moz-text-decoration: bold;", "color: #000", style, style0); else if (type === "warn") console.warn("%c[EssenceJS]%c " + msg, "color: #fc0; text-decoration: bold;-webkit-text-decoration: bold;-moz-text-decoration: bold;", "color: #000", style, style0); else if (type === "succ") console.log("%c[EssenceJS]%c " + msg, "color: #0f0; text-decoration: bold;-webkit-text-decoration: bold;-moz-text-decoration: bold;", "color: #000", style, style0); else console.log("%c[EssenceJS]%c " + msg, "color: #808080; text-decoration: bold;-webkit-text-decoration: bold;-moz-text-decoration: bold;", "color: #000", style, style0); } else if (style && style0 && style1 && !style2) { if (type === "info") console.info("%c[EssenceJS]%c " + msg, "color: #00f; text-decoration: bold;-webkit-text-decoration: bold;-moz-text-decoration: bold;", "color: #000", style, style0, style1); else if (type === "erro") console.error("%c[EssenceJS]%c " + msg, "color: #f00; text-decoration: bold;-webkit-text-decoration: bold;-moz-text-decoration: bold;", "color: #000", style, style0, style1); else if (type === "warn") console.warn("%c[EssenceJS]%c " + msg, "color: #fc0; text-decoration: bold;-webkit-text-decoration: bold;-moz-text-decoration: bold;", "color: #000", style, style0, style1); else if (type === "succ") console.log("%c[EssenceJS]%c " + msg, "color: #0f0; text-decoration: bold;-webkit-text-decoration: bold;-moz-text-decoration: bold;", "color: #000", style, style0, style1); else console.log("%c[EssenceJS]%c " + msg, "color: #808080; text-decoration: bold;-webkit-text-decoration: bold;-moz-text-decoration: bold;", "color: #000", style, style0, style1); } else if (style && style0 && style1 && style2) { if (type === "info") console.info("%c[EssenceJS]%c " + msg, "color: #00f; text-decoration: bold;-webkit-text-decoration: bold;-moz-text-decoration: bold;", "color: #000", style, style0, style1, style2); else if (type === "erro") console.error("%c[EssenceJS]%c " + msg, "color: #f00; text-decoration: bold;-webkit-text-decoration: bold;-moz-text-decoration: bold;", "color: #000", style, style0, style1, style2); else if (type === "warn") console.warn("%c[EssenceJS]%c " + msg, "color: #fc0; text-decoration: bold;-webkit-text-decoration: bold;-moz-text-decoration: bold;", "color: #000", style, style0, style1, style2); else if (type === "succ") console.log("%c[EssenceJS]%c " + msg, "color: #0f0; text-decoration: bold;-webkit-text-decoration: bold;-moz-text-decoration: bold;", "color: #000", style, style0, style1, style2); else console.log("%c[EssenceJS]%c " + msg, "color: #808080; text-decoration: bold;-webkit-text-decoration: bold;-moz-text-decoration: bold;", "color: #000", style, style0, style1, style2); } else { if (type === "info") console.info("%c[EssenceJS]%c " + msg, "color: #00f; text-decoration: bold;-webkit-text-decoration: bold;-moz-text-decoration: bold;", "color: #000"); else if (type === "erro") console.error("%c[EssenceJS]%c " + msg, "color: #f00; text-decoration: bold;-webkit-text-decoration: bold;-moz-text-decoration: bold;", "color: #000"); else if (type === "warn") console.warn("%c[EssenceJS]%c " + msg, "color: #fc0; text-decoration: bold;-webkit-text-decoration: bold;-moz-text-decoration: bold;", "color: #000"); else if (type === "succ") console.log("%c[EssenceJS]%c " + msg, "color: #0f0; text-decoration: bold;-webkit-text-decoration: bold;-moz-text-decoration: bold;", "color: #000"); else console.log("%c[EssenceJS]%c " + msg, "color: #808080; text-decoration: bold;-webkit-text-decoration: bold;-moz-text-decoration: bold;", "color: #000"); } }, applyCSS: function (nonMinify) { include_once(getExtPath(getDirectoryPath(gatherScripts()[gatherScripts()["essence.min.js"]? "essence.min.js": "essence.js"])) + (nonMinify? "essence.css": "essence.min.css"), "link", getDirectoryPath()); /*if ($end("html").val(true).indexOf("<body></body>") > -1) { //A bit of cleaning var ix = $end("html").val(true).indexOf("<body></body>"); var bfr = $end("html").val(true).slice(0, ix), aft = $end("html").val(true).slice(ix + 13, $end("html").val(true).length); $end("html").write(bfr + aft, true); }*/ }, addCSS: function (nstyle) { if ($n("style", true) === null) { var s = document.createElement("style"); s.innerText = nstyle; //start.media = "all"; s.type = "text/css"; s.id = "EssenceCSS"; $n("head").appendChild(s); } else if ($e("style[type='text/css']", true) != null) $e("style[type='text/css']").after(nstyle); else $e("style").after(nstyle); }, addJS: function (nscript) { if ($n("script", true) === null) { var s = document.createElement("script"); s.innerText = nscript; s.type = "text/javascript"; $n("head").appendChild(s); } else $e("script[type='text/javascript']").after(nscript); }, update: function () { //To keep the script updated !! var $s = $n("*script").toArray(); var scripts = filenameList($s.map(function (script) { return script.src; })); for (var i = 0; i < scripts.length; i++) { if (stripPath(scripts[i]) === "essence.js" || stripPath(scripts[i]) === "essence.min.js") $s[i].src = Essence.source; } Essence.say("%cEssence(.min).js%c has been updated", "succ", "text-decoration: underline", "text-decoration: none"); }, /** @const {number} Essence.eps Epsilon */ eps: Math.pow(2, -52), //Matlab'sepsilon (useful when dealing with null values to keep them in the real range or just not null emptyDoc: function (title, author) { //Empty the document and fill it with a basic structure $e("html").write("<head><title>" + (title || document.title) + "</title><meta charset='UTF-8' /><meta name='author' content=" + (author || "unknown") + " /><script type='text/javascript' src=" + Essence.source + "></script></head><body></body>", true); }, editor: function (ctt) { location.href = "data:text/html, <html contenteditable>" + (ctt? ctt + "</html>": "</html>"); }, processList: [["Name (signature)", "Author", "Size"]], global: null, addProcess: function (pcs) { pcs.update(); Essence.processList.push([pcs.name + " (" + pcs.sig + ")", pcs.author, pcs.bitsize]); pcs.id = Essence.processList.length - 1; Essence.processSize += pcs.bitsize; }, processSize: 0, serverList: [["Name", "Author", "Maximum size"]], addServer: function (serv) { serv.update(); Essence.serverList.push([serv.name, serv.author, serv.maxsize]); Essence.serverSize += serv.maxsize; }, serverSize: 0, toString: function () { return "[object Essence]" }, txt2print: "", addToPrinter: function (txt, type) { //Allow the usage of print without having to directly touch to txt2print txt.has("\n\r")? this.print(txt, type): this.txt2print += txt; }, print: function (txt, type) { //Works like the print in Java if (txt) this.txt2print += txt; //noinspection JSValidateTypes this.txt2print = this.txt2print.split("\b"); for (var i = 0; i < this.txt2print.length; i++) { this.say(this.txt2print[i], type); } this.txt2print = ""; }, preInit: function () { //noinspection JSValidateTypes $G.t1 = $G.t1.getTime(); }, init: function () { //noinspection JSValidateTypes $G.t2 = new Date(); $G.t2 = $G.t2.getTime(); $G.t = ($G.t2 - $G.t1 > 1000)? ($G.t2 - $G.t1) / 1000 + "s": ($G.t2 - $G.t1) + "ms"; if (debugging) Essence.say("Page loaded in %c" + $G.t + "%c", "succ", "font-style: italic", "font-style: none"); }, time: function(msg, style, style0) { //Like Essence.say(msg) but with the timestamp console.log("[%c" + getTimestamp(true) + "%c] "+msg, "color: #00f;", "color: #000;", style || "", style0 || "") }, sayClr: function (clrs) { //Display a RGB(A) coloured console log clrs.length === 4? console.log("%cr%cg%cb%ca(%c" + clrs.join(", %c") + "%c)", "color: #f00", "color: #0f0", "color: #00f", "color: #00f", "color: #000", "color: #f00", "color: #0f0", "color: #00f", "color: #00f", "color: #000"): console.log("%cr%cg%cb%c(%c" + clrs.join(", %c") + "%c)", "color: #f00", "color: #0f0", "color: #00f", "color: #00f", "color: #000", "color: #f00", "color: #0f0", "color: #00f", "color: #00f", "color: #000"); }, ask: function (label, callback) { //Ask something to the user Sys.in.recording = true; Essence.say((label || "Is there a problem") + " ? (please type in the window and not the console)", "quest"); while ($G["lastKeyPair"][1] != 96 /*$G["lastKeyPair"][1] != 13*/ && $G["lastKeyPair"][1] != 10) { //Quits on enter and ` //Essence.say("waiting for an enter"); } alert("OUT !!"); Sys.in.recording = false; if(callback) callback(Sys.in.data.join("")); return Sys.in.data.join(""); }, isComplete: function () { var complete = true; this.loadedModules = []; for (var i = 0; i < modules.length; i++) { try { eval(window[modules[i]].loaded); } catch (e) { Essence.say("The module " + modules[i] + " is not right !", "warn"); init(modules[i]); } finally { complete &= window[modules[i]].loaded; } if (window[modules[i]].loaded) this.loadedModules.push(window[modules[i]]); } //noinspection PointlessBooleanExpressionJS return !!complete; }, loadedModules: [], updateAll: function () { this.update(); this.isComplete(); this.loadedModules.map(function (m) { m.update(); }); }, listModules: function () { var list = moduleList(true); var weights = list.line(4).get(1); } }, /** * @description List of modules * @global * @type {string[]} * @since 1.1 */ modules = [], /** * @description Debugging flag * @global * @type {boolean} * @since 1.1 */ debugging = false, /** * @description Empty function * @global * @type {Function} * @since 1.1 * @readonly * @returns {undefined} */ $f = function () {}, /** * @description Test mode on/off * @type {boolean} * @global * @since 1.1 */ testMode = false, /** * @description Performance/profiling mode on/off * @type {boolean} * @global * @since 1.1 */ perfMod = true; /** * @description EssenceJS Module * @param {string} [name="Module"] Name * @param {string} [desc=""] Description * @param {string[]} [dpc=[]] Dependencies * @param {number} [ver=1] Version * @param {Function} [rn=function () {}] Run method * @param {string} [pathVer=Essence.version.substr(0, 3)] Path's version * @constructor * @this Module * @returns {Module} Module * @property {string} Module.name Name of the module * @property {number} Module.version Version of the module * @property {string[]} Module.dependency Dependencies * @property {string} Module.description Description of the module * @property {Function} Module.run Runner method * @property {boolean} Module.loaded Loading flag * @property {string} Module.path Path of the module * @property {Function} Module.load Load the module as well as initializing its dependencies * @property {function(): string} Module.toString String representation * @property {function(): number} Module.getWeight Weight of the module on EssenceJS's module ecosystem * @property {Function} Module.update Update the module * @property {function(): String} Module.getUsage List of modules dependent on this one * @since 1.1 */ function Module (name, desc, dpc, ver, rn, pathVer) { this.name = name || "Module"; this.version = ver || 1; this.dependency = dpc || []; this.description = desc || ""; this.run = rn || $f; this.loaded = false; this.path = (pathVer? pathVer : Essence.version.substr(0, 3)) + "/modules/" + this.name + ".js"; this.load = function () { if (perfMod) console.timeStamp("Loading module:" + this.name); if (debugging) Essence.say("Loading " + this.name); if (this.dependency.length > 0) { if (debugging) Essence.say("Initiating dependencies for %c" + this.name + "%c", "info", "color: #f0f", "color: #000"); //For less redundancy here: this.dependency -> complement(this.dependency, modules) init(this.dependency, false, false, pathVer); } /*if (gatherExternalScripts(true).has(this.path) || filenameList(gatherExternalScripts(true)).has(this.path)) */this.loaded = true; if (perfMod) console.timeStamp("Loaded module:" + this.name); }; this.toString = function () { return "Module(name='" + this.name + "', version=" + this.version + ", dependency=[" + this.dependency + "], description='" + this.description + "', loaded=" + this.loaded + ", run=" + this.run + ", path='" + this.path + "')"; }; this.getWeight = function () { var dpcs = moduleList(false, true).line(3).get(1), weight = 0, names = moduleList(false, true).line().get(1); //List of dependencies of all loaded modules for (var i = 0; i < dpcs.length; i++) { if (dpcs[i].has(this.name) && names[i] != this.name && dpcs[i].count(this.name) < 2) weight++; else if (names[i] === this.name && dpcs[i].has(this.name)) weight--; //Penalty } return weight; }; this.update = function () { //This method should not be used before EssenceJS is fully implemented onto the environment using it if (perfMod) console.timeStamp("Updated module:" + this.name); var $s = $n("*script").toArray(); var scripts = filenameList($s.map(function (script) { return script.src; })); for (var i = 0; i < scripts.length; i++) { if (stripPath(scripts[i]) === this.name + ".js") $s[i].src = "http://berkmann18.github.io/rsc/modules/" + this.name + ".js"; else if (stripPath(scripts[i]) === this.name + ".min.js") $s[i].src = "http://berkmann18.github.io/rsc/modules/" + this.name + ".min.js"; } Essence.say(this.name.capitalize() + "(.min).js has been updated", "succ"); if (perfMod) console.timeStamp("Updated module:" + this.name); }; this.getUsage = function () { var dpcs = moduleList(false, true).line(3).get(1), usage = "", names = moduleList(false, true).line().get(1); //List of dependencies of all loaded modules for (var i = 0; i < dpcs.length; i++) { if (dpcs[i].has(this.name) && names[i] != this.name && dpcs[i].count(this.name) < 2) usage += names[i] + ", "; } return usage.get(-2); }; return this; } /** * @description ES6-like module loader * @func * @param {Str} mdl Module * @param {NumberLike} [ver] Version of the directory containing it * @param {string} [extpath] External path * @returns {undefined} * @since 1.1 * @example <caption>Example 1:</caption> * require("myModule"); //It will import the script located at "modules/myModule.js" * require(["moduleA", "moduleB", "moduleC"]); //It will import "modules/moduleA.js", "modules/moduleB.js" and "modules/moduleC.js" * @example <caption>Example 2:</caption> * require("myModule", 1.1); //It will import the script located at "1.1/modules/myModule.js" * @see module:essence~$require * @deprecated */ function require (mdl, ver, extpath) { if (perfMod) console.timeStamp("Start of require(" + mdl + ", " + ver + ")"); if (isType(mdl, "Array")) { for (var i = 0; i < mdl.length; i++) { //noinspection JSDeprecatedSymbols require(mdl[i], ver); } } else if (modules.indexOf(mdl) === -1) { include_once((ver? ver + "/": "") + "modules/" + mdl + ".js", "script", extpath || getDirectoryPath()); modules.push(mdl); if (debugging) console.log("The module %c%start%c is now included into %c%start " + getTimestamp(true), "color: red; text-decoration: bold; -webkit-text-decoration: bold; -moz-text-decoration: bold;", mdl, "color: #000; text-decoration: none;", " text-decoration: bold; -webkit-text-decoration: bold; -moz-text-decoration: bold;", getFilename()); } else if (debugging) console.log("The module %c%start%c is already included into %c%start " + getTimestamp(true), "color: red; text-decoration: bold; -webkit-text-decoration: bold; -moz-text-decoration: bold;", mdl, "color: #000; text-decoration: none;", " text-decoration: bold; -webkit-text-decoration: bold; -moz-text-decoration: bold;", getFilename()); if (perfMod) console.timeStamp("End of require(" + mdl + ", " + version + ")"); } /** * @description ES6-like module loader * @func * @param {Str} mdl Module * @returns {undefined} * @since 1.1 * @example <caption>Example 1:</caption> * require("myModule"); //It will import the script located at "modules/myModule.js" * require(["moduleA", "moduleB", "moduleC"]); //It will import "modules/moduleA.js", "modules/moduleB.js" and "modules/moduleC.js" */ function $require (mdl) { if (perfMod) console.timeStamp("Start of $require(" + mdl + ")"); var toND = function (x, n) { var i = this + ""; //Because it won't work with other types than strings n = n || 2; if (parseFloat(i) < Math.pow(10, n - 1)) { while (i.split(".")[0].length < n) i = "0" + i; } return i }, getT = function () { var d = new Date(); return getDate() + " " + toND(d.getHours(), 2) + ":" + toND(d.getMinutes(), 2) + ":" + toND(d.getSeconds(), 2) + "." + toND(d.getMilliseconds(), 2) }, stripP = function (p) { return p.split("/")[p.split("/").length - 1] }, _g = function (x, start, end) { var res = ""; if (start < 0 && !end) { end = start; start = 0; } if (end < 0) end = x.length + end - 1; for (var i = (start || 0); i <= (end || x.length - 1); i++) res += x[i]; return res },getFn = function () { return _g(stripP(location.pathname), (-stripP(location.pathname).lastIndexOf(".") - 1)); }; if (isType(mdl, "Array")) { for (var i = 0; i < mdl.length; i++) $require(mdl[i]); } else if (modules.indexOf(mdl) === -1) { gatherScripts()["essence.min.js"]? include_once(getExtPath(getDirectoryPath(gatherScripts()["essence.min.js"])) + "modules/" + mdl + ".min.js", "script"): include_once(getExtPath(getDirectoryPath(gatherScripts()["essence.js"])) + "modules/" + mdl + ".js", "script"); modules.push(mdl); if (debugging) console.log("The module %c%start%c is now included into %c%start " + getT(), "color: red; text-decoration: bold; -webkit-text-decoration: bold; -moz-text-decoration: bold;", mdl, "color: #000; text-decoration: none;", " text-decoration: bold; -webkit-text-decoration: bold; -moz-text-decoration: bold;", getFn()); } else if (debugging) console.log("The module %c%start%c is already included into %c%start " + getT(), "color: red; text-decoration: bold; -webkit-text-decoration: bold; -moz-text-decoration: bold;", mdl, "color: #000; text-decoration: none;", " text-decoration: bold; -webkit-text-decoration: bold; -moz-text-decoration: bold;", getFn()); if (perfMod) console.timeStamp("End of $require(" + mdl + ")"); } /** * @description Run a module that was already imported (see {@link require}) after initiating its dependencies * @func * @since 1.1 * @param {Str} module Module * @param {NumberLike} [ver] Directory version * @returns {undefined} * @example * run("myModule"); //will run myModule.run() * run(["moduleA", "moduleB"]); //will run moduleA.run() then moduleB.run() (unless module is a dependency of moduleA in which case it will be ran before) */ function run (module, ver) { if (perfMod) console.timeStamp("Start of run(" + module + ", " + ver + ")"); if (isType(module, "Array")) { for (var i = 0; i < module.length; i++) run(module[i], ver); } else if (modules.indexOf(module) > -1) { /** * @description Go onto the running phase of the module * @inner * @func * @returns {undefined} */ var go = function () { if (perfMod) console.timeStamp("Go in run(" + module + ", " + ver + ")"); try { if (debugging) Essence.say("Running " + module + " " + getTimestamp(true), "info"); /*init(window[module].dependency, false, function (x) { if (debugging) Essence.say("%c" + x + "%c from %c" + module + "%c's dependency has been initiated !! " + getTimestamp(true), "info", "color: #c0f", "color: #000", "color: #f0c", "color: #000"); //console.info("") }, ver);*/ if (!window[module].loaded) window[module].load(); window[module].run(); } catch (e) { Essence.time("The module %c" + module + "%c have problems regarding it's run method.", "color: #c0f", "color: #000"); } }, /** * @description Retry to get the module to be usable and launch go() * @inner * @func * @param {number} [stackLayer=0] Stack layer * @returns {undefined} */ retry = function (stackLayer) { if (perfMod) console.timeStamp("Retry in run(" + module + ", " + ver + ")"); if (!stackLayer) stackLayer = 0; Essence.say("The module %c" + module + "%c isn't available ! " + getTimestamp(true), "erro", "color: #c0f", "color: #000"); if (debugging) Essence.say("Retrying to run %c" + module + "%c " + getTimestamp(true), "info", "color: #c0f", "color: #000"); if (window[module]) go(); else if (stackLayer <= 2) setTimeout(retry(stackLayer + 1), 1); else Essence.say("It's not possible to run %c" + module + "%c :( ! " + getTimestamp(true) + "\nModule: " + window[module], "info", "color: #c0f", "color: #000"); init(module); }; window[module]? go(): retry(); } else Essence.say("The module %c" + module + "%c isn't in the list !! " + getTimestamp(true), "erro", "color: #c0f", "color: #000"); if (perfMod) console.timeStamp("End of $require(" + module + ", " + ver + ")"); } /** * @description Initiate a module * @param {Str} mdls Module(start) * @param {function(*)|boolean} [mid] Mid-execution function * @param {function(*)|boolean} [cb] Callback function * @param {NumberLike} [ver] Version (if the modules are in a version based partitioning (end.g: 1.0/modules/ModuleA.js, 1.1/modules/ModuleA.js, beta/modules/ModuleA.js) * @param {*} [argsMid] Arguments for the mid() * @param {*} [argsCB] Arguments for the cb() * @since 1.0 * @returns {undefined} * @func * @example <caption>Example 1:</caption> * init("myModule"); //Initiate the module myModule * init(["moduleA", "moduleB"]); //Initiate the modules moduleA and moduleB * @example <caption>Example 2:</caption> * init("myModule", function () {}, function () { * Essence.say("myModule has been fully initiated !", "info"); * }, "alpha"); //Initiate the myModule.js module located at alpha/modules/ and with a callback * init(["moduleA", "moduleB"], function (mdl) { * Essence.say("Midway through " + mdl, "info"); * }, function (mdl) { * Essence.say("Finished initiating " + mdl, "succ"); * }); */ function init (mdls, mid, cb, ver, argsMid, argsCB) { if (perfMod) console.timeStamp("Start of init(" + mdls + ")"); if (isType(mdls, "Array")) { for (var i = 0; i < mdls.length; i++) init(mdls[i], mid, cb, ver, mdls[i], mdls[i]); } else { if (debugging) Essence.say("Initiating " + mdls); if (modules.indexOf(mdls) === -1) $require(mdls); else if (debugging) Essence.say("The module %c" + mdls + "%c was already initiated !!", "info", "color: #c0f", "color: #000"); if (mid) mid(argsMid || mdls); //Used when initiating a module that has dependencies setTimeout(function () { //Delayed running to leave some time for the module to be fully available to this page //if (!window[mdls].loaded) window[mdls].load(); run(mdls); if (cb) cb(argsCB || mdls); }, 1); } if (perfMod) console.timeStamp("End of init(" + mdls + ")"); } /** * @ignore * @external module/File~getDirectoryPath * @inheritdoc * @param {string} [path=location.href] Path * @returns {string} Directory path * @since 1.1 */ var getDirectoryPath = function (path) { if(!path) path = location.href; return path.substring(0, path.indexOf(path.split("/")[path.split("/").length - 1])) }, /** * @ignore * @external module/DOM~gatherScripts * @inheritdoc * @param {boolean} [asList=false] Result should be a list or an object * @returns {*} List/dictionary of scripts */ gatherScripts = function (asList) { var $s = $n("*script"), res = asList? []: {}; for(var i = 0; i < $s.length; i++) asList? res.push($s[i].src): res[$s[i].src.split("/")[$s[i].src.split("/").length - 1]] = $s[i].src; return res }, /** * @ignore * @external module/DOM~gatherStylesheets * @inheritdoc * @param {boolean} [asList=false] Result should be a list or an object * @returns {*} List/dictionary of stylesheets */ gatherStylesheets = function (asList) { var $l = $n("*link"), res = asList? []: {}; for(var i = 0; i<$l.length; i++) asList? res.push($l[i].href): res[$l[i].href.split("/")[$l[i].href.split("/").length - 1]] = $l[i].href; return res },/** * @ignore * @inheritdoc * @external module/File~getCurrentPath * @param {string} path Path * @param {string} [localPath="file:///"] Local path * @returns {string} Current path */ getCurrentPath = function (path, localPath) { if (!localPath) localPath = "file:///"; var parts = path.split("/"), res, pParts = localPath.split("/"), i = 0, j = 0, _get = function (o, start, end) { var r = []; if (start < 0 && !end) { end = start; start = 0; } if (end < 0) end = o.length + end - 1; for (var i = (start || 0); i <= (end || o.length - 1); i++) r.push(o[i]); return r.filter(function (x) { return x != undefined; }); }; while (localPath.indexOf(parts[i]) > -1) i++; res = _get(parts, i).join("/"); while (res.indexOf(pParts[j]) > -1) { console.log("Gone through " + pParts[j]); j++; } if (j > 0) { for(i = 0; i < j; i++) res = "../" + res; } return res }, /** * @ignore * @inheritdoc * @external module/File:getExtPath * @param {string} path Full path * @returns {string} External path */ getExtPath = function (path) { var cp = location.href, sF = function (s0, s1) { var sf = "", pos = -1; while (pos <= Math.min(s0.length, s1.length)) { pos++; if (s0[pos] === s1[pos]) sf += s0[pos]; else break; } return sf; }, ct = function (o, c) { var n = 0; for (var i = 0; i < o.length; i++) { if (o[i] === c) n++; } return n }; var parentPath = sF(cp, path); return "../".repeat(ct(getCurrentPath(cp, parentPath), "/")) + getCurrentPath(path, parentPath); }, /** * @ignore * @inheritdoc * @external module/File:filenameList * @returns {Array} File name list */ filenameList = function (list) { var res = []; for(var i = 0; i < list.length; i++) res.push(stripPath(list[i])); return res.remove() }; /** * @summary Module Loading section * @since 1.1 * @returns {undefined} * @func */ (function () { //document.scripts[i].ownerDocument may be useful to correct the link of the included modules if (perfMod) console.timeStamp("Module Loader init"); if (debugging) Essence.say("Initiating the Module Loader"); $require(["Files", "DOM", "UI", "Web", "Maths", "Ajax", "DataStruct", "Security", "Misc", "QTest"]); /* init(["Web", "Maths", "Ajax", "DataStruct", "Security", "Misc", "QTest"], function (mdl) { Essence.say(mdl + " on the way!", "info"); }, function (mdl) { Essence.say(mdl + " is ready!", "succ"); }, 1.1); */ setTimeout(function () { run(modules, Essence.version.substr(0, 3)); if (perfMod) console.timeStamp("Modules ran!"); }, 690); setTimeout(function () { if (debugging) { //noinspection JSValidateTypes if (Essence.isComplete()) Essence.say("Essence is complete !", "succ"); else Essence.time("List of loaded modules: " + Essence.loadedModules.map(function (m) { return m.name; }).toStr(true)); } if (!filenameList(gatherExternalScripts(true)).has("essence.js")) Essence.source = Essence.source.replace(".js", ".min.js"); UnitTest.libTests = [ //essence //Ajax /*[GET("_ijt"), function () { var val = null; parseURL("_ijt", function (x) { val = x; }); return val; }, "GET],*/ //DataStruct [binarySearch(["hi", " ", "dude"], " ", "BinarySearch"), true], //[binarySearch(["hi", " ", "dude"], "!", "BinarySearch"), false], //[search(["hi", " ", "dude"], "!", "Search"), -1], [Perm("abc"), ["abc", "acb", "cab", "cba", "bac", "bca"], "Perm"], //DOM [unescapeHTML(escapeHTML("<p>Hi</p>")), "<p>Hi</p>", "Un(escape)"], [escapeHTML(unescapeHTML("&lt;p&gt;Hi&lt;/p&gt;")), "&lt;p&gt;Hi&lt;/p&gt;", "Es(unescape)"], //Files [getDirectoryPath() + stripPath(location.href), location.href, "Path"], //Maths [min2dec(dec2min(.56)), .56, "min<->dec"], [toS(s2t(75.23)), 75.23, "start<->time"], [isPrime(23), true, "Prime"], [isPrime(25), false, "!Prime"], //Misc [rmDuplicates("hello world !"), "helo wrd!", "NoDuplic"], [unRegExpify(RegExpify("Hi ${name}")), "Hi ${name}", "RE<->"], //QTest //Security [decrypt(encrypt("Hello", 5), -5), "Hello"," de(encrypt)"], [encrypt(decrypt("Hello", -5), 5), "Hello", "en(decrypt)"], [abcDecode(abcEncode("Lorem")), "Lorem", "de(encode)"], [abcEncode(abcDecode("6415180513")), "6415180513", "en(decode)"], [ilDecrypt(ilEncrypt("Hello")), "Hello", "il-De(En)"], [ilEncrypt(ilDecrypt("Hello")), "Hello", "il-En(De)"], //Result: £ƒ¡¡« //[RSA(RSA("Secrete", keys), ??), "Secrete", "RSA"], [fromFSHA(toFSHA("password")), "password", "fromFSHA(to)"], [toFSHA(fromFSHA("password")), "password", "toFSHA(from)"] //UI //Web ]; if (testMode) { UnitTest.basicTests(); UnitTest.multiTest(UnitTest.libTests); } if (debugging && !Essence.loadedModules.map(function (m) { return m.name; }).equals(modules) ) Essence.say("The following modules weren't loaded: " + complement(modules, Essence.loadedModules.map(function (m) { return m.name; })) ); if (Essence.source.has("essence.min")) { //If it's the minimised version, change the modules to their minimised version as well var $s = $n("*script").toArray(); for (var i = 0; i < $s.length; i++) { if (!$s[i].src.has(".min.js")) $s[i].src.replace(".js", ".min.js"); } } if (perfMod) console.timeStamp("Module edit"); }, 1e3); if (perfMod) console.timeStamp("Module Loading done"); })(); /** * @description Globals won't be globals !! * @type {{t1: Date, t2: number, t: ?number, lastKeyPair: Array}} * @default * @since 1.0 * @global */ var $G = { t1: new Date(), t2: 0, t: null, lastKeyPair: [], lorem: "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi. Nam eget dui. Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed ipsum. Nam quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem. Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros faucibus tincidunt. Duis leo. Sed fringilla mauris sit amet nibh. Donec sodales sagittis magna. Sed consequat, leo eget bibendum sodales, augue velit cursus nunc," }; //noinspection JSValidateTypes Essence.global = $G; /** * @description Element selector * @param {string} selector A CSS selector * @param {boolean} [silence=false] Flag to use when <code>selector</code> doesn't exist yet (end.g: a particular selector used by a JS object/function which may not be in the page yet). * @returns {?Element} Element * @since 1.0 * @func */ function $e (selector, silence) { //THE selector !! if (silence) { try { return new Element(selector) } catch (e) { if (debugging) Essence.say("%c$e(\"" + selector + "\")%c isn't there (yet).", "warn", "color: #f00", "color: #000"); return null; } } else return new Element(selector); } /** * @description Element's node * @param {string} selector A CSS selector * @param {boolean} [silence=false] Flag to use when <code>selector</code> doesn't exist yet (end.g: a particular selector used by a JS object/function which may not be in the page yet). * @returns {HTMLElement} Element node * @since 1.0 * @func */ function $n (selector, silence) { //To get directly the node without having to use $end(selector).node return (silence && isNon($e(selector, silence)))? null: $e(selector).node; } /** * @description Element * @param {string} selector A CSS selector * @this Element * @returns {Element} Element object * @constructor * @since 1.0 * @throws {InvalidParamError} Invalid parameter * @property {HTMLElement} Element.node Node * @property {String} Element.selector Selector * @property {function(boolean, boolean): (NumberLike|XML)} Element.val Get the node's value * @property {function(): number} Element.size Get the node's value's size * @property {function(): boolean} Element.isEmpty Check if the node's value is empty * @property {function(*, boolean, boolean)} Element.write Write something to the node * @property {function(*, boolean, boolean)} Element.before Write something to the node before its value * @property {function(*, boolean, boolean)} Element.after Write something to the node after its value * @property {function(string, ?string)} Element.remove Remove a character/string from the node's value and optionally insert jointers * @property {function(string, string)} Element.setCSS Set a CSS rule or change a CSS property * @property {function(string, string)} Element.setInlineCSS Set a CSS rule or change a CSS property inline to a righty of elements * @property {function(string[])} Element.setStyles Set multiple CSS rules * @property {function(string): NumberLike} Element.css Get the value of a CSS property * @property {function(string): boolean} Element.hasClass Check if the node is affiliated to a class * @property {function(string): boolean} Element.hasCSS Check if the node's CSS include a particular rule * @property {function(string)} Element.addClass Affiliate the node to a particular class * @property {function(string)} Element.rmClass Disjoin the node from a particular class * @property {function(string, (Str|Nums), number)} Element.toggleCSS Toggle a CSS property * @property {Function} Element.show Show the node * @property {Function} Element.hide Hide the node * @property {function(string)} Element.on Event handler * @property {function(): string} Element.toString String representation of the element * @property {function(): string} Element.tagName Tagname of the element * @property {Function} Element.scrollBottom Scroll to the bottom of the node * @property {Function} Element.scrollTop Scroll to the top of the node * @property {Function} Element.scrollLeft Scroll to the left of the node * @property {Function} Element.scrollRight Scroll to the right of the node * @property {function(number, number)} Element.scroll Scroll in any directions * @property {function(string, number)} Element.autoScroll Auto scrolling animation * @property {function(string, *): *} Element.attr Get/set the attribute of the node * @property {function(string)} Element.rmAttr Remove an attribute from the node * @property {Function} Element.invColour Invert the colour and background colour (by negation) * @property {function(): string[]} Element.classes Get an array of classes of the element * @property {function(function(HTMLElement))} Element.multi Execute a callback on all nodes of a $e("*...") element * @property {function(string, Array)} Element.multiElm Execute a method on all elements of a $e("*...") element * @property {function()} Element.delete Self-destruction of the element by self-removal of the DOM * @property {function(String, String, boolean, boolean)} Element.replace Replace a string in the element's value by a new one * @todo All the CSS implementations on $e("*..") must always be wrote in a CSS place and not inline (like now) * @property {function()} Element.moveCSS Move the inline-CSS into the current stylesheet */ function Element (selector) { if (/^([#.*_-`~&]\W*|\S|undefined|null|)$/.test(selector)) throw new InvalidParamError("Element cannot accept the selector '" + selector + "' as its invalid."); //Reject invalid selectors if (selector[0] === "#") this.node = document.querySelector(selector) || document.getElementById(selector.slice(1, selector.length)); //Id else if (selector[0] === ".") this.node = document.querySelector(selector) || document.getElementByClassName(selector.slice(1, selector.length)); //Class else if (selector[0] === "*") this.node = document.querySelectorAll(selector.slice(1, selector.length)) || document.getElementsByTagName(selector.slice(1, selector.length)); //Node list else this.node = document.querySelector(selector); if (this.node === null) throw new Error("The node $n(\"" + selector + "\") doesn't exist !!"); this.selector = selector; this.val = function (getHTML, withTags) { if (isType(this.node, "Array")) { var arr = []; for (var i = 0; i < this.node.length; i++) { if (this.node[i].value && !getHTML && !withTags) arr.push(this.node[i].value); else if (this.node[i].innerHTML && getHTML && !withTags) arr.push(this.node[i].innerHTML); else if (this.node[i].innerText && !getHTML && !withTags) arr.push(this.node[i].innerText); else if (this.node[i].outerHTML && !getHTML && withTags) arr.push(this.node[i].outerHTML); else arr.push(this.node[i].value? this.node[i].value: this.node[i].innerText); } return arr } if (this.node.value && !getHTML && !withTags) return this.node.value; else if (this.node.innerHTML && getHTML && !withTags) return this.node.innerHTML; else if (this.node.innerText && !getHTML && !withTags) return this.node.innerText; else if (this.node.outerHTML && !getHTML && withTags) return this.node.outerHTML; else return this.node.value? this.node.value: this.innerText }; this.size = function () { return this.val().length }; this.isEmpty = function () { return isNon(this.val()); }; this.write = function (nval, parseToHTML, incTags) { if (typeof this.val(true) == "undefined") this.node.innerText = "?"; if (isType(this.node, "Array")) { for (var i = 0; i < this.node.length; i++) { if (this.node[i].value && !parseToHTML && !incTags) this.node[i].value = isType(nval, "Array")? nval[i]: nval; else if (this.node[i].innerHTML && parseToHTML && !incTags) this.node[i].innerHTML = isType(nval, "Array")? nval[i]: nval; else if (this.node[i].innerText && !parseToHTML && !incTags)this.node[i].innerText = isType(nval, "Array")? nval[i]: nval; else if (this.node[i].outerHTML && !parseToHTML && incTags) this.node[i].outerHTML = isType(nval, "Array")? nval[i]: nval; else this.node[i].value? (this.node[i].value = isType(nval, "Array")? nval[i]: nval): (this.node[i].innerText = isType(nval, "Array")? nval[i]: nval); } } if (this.node.value && !parseToHTML && !incTags) this.node.value = nval; else if (this.node.innerHTML && parseToHTML && !incTags) this.node.innerHTML = nval; else if (this.node.innerText && !parseToHTML && !incTags) this.node.innerText = nval; else if (this.node.outerHTML && incTags && !parseToHTML) this.node.outerHTML = nval; else this.node.value? this.node.value = nval: this.innerText = nval; }; this.before = function (nval, parseToHTML, incTags) { if (typeof this.val(true) == "undefined") this.node.innerText = "?"; if (isType(this.node, "Array")) { for (var i = 0; i < this.node.length; i++) { if (this.node[i].value && !parseToHTML && !incTags) this.node[i].value = isType(nval, "Array")? nval[i] + this.node[i].value: nval + this.node[i].value; else if (this.node[i].innerHTML && parseToHTML && !incTags) this.node[i].innerHTML = isType(nval, "Array")? nval[i] + this.node[i].innerHTML: nval+ this.node[i].innerHTML; else if (this.node[i].innerText && !parseToHTML && !incTags) this.node[i].innerText = isType(nval, "Array")? nval[i] + this.node[i].innerText: nval + this.node[i].innerText; else if (this.node[i].outerHTML && !parseToHTML && incTags) this.node[i].outerHTML = isType(nval, "Array")? nval[i] + this.node[i].outerHTML: nval + this.node[i].outerHTML; else this.node[i].value? (this.node[i].value = isType(nval, "Array")? nval[i] + this.node[i].value: nval + this.node[i].value): (this.node[i].innerText = isType(nval, "Array")? nval[i] + this.node[i].innerText: nval + this.node[i].innerText); } } if (this.node.value && !parseToHTML && !incTags) this.node.value = nval + this.node.value; else if (this.node.innerHTML && parseToHTML && !incTags) this.node.innerHTML = nval + this.node.innerHTML; else if (this.node.innerText && !parseToHTML && !incTags) this.node.innerText = nval + this.node.innerText; else if (this.node.outerHTML && incTags && !parseToHTML) this.node.outerHTML = nval + this.node.outerHTML; else this.node.value? this.node.value = nval + this.node.value: this.innerText = nval + this.innerText; }; this.after = function (nval, parseToHTML, incTags) { if (typeof this.val(true) == "undefined") this.node.innerText = "?"; if (isType(this.node, "Array")) { for (var i = 0; i < this.node.length; i++) { if (this.node[i].value && !parseToHTML && !incTags) this.node[i].value += isType(nval, "Array")? nval[i]: nval; else if (this.node[i].innerHTML && parseToHTML && !incTags) this.node[i].innerHTML += isType(nval, "Array")? nval[i]: nval; else if (this.node[i].innerText && !parseToHTML && !incTags)this.node[i].innerText += isType(nval, "Array")? nval[i]: nval; else if (this.node[i].outerHTML && !parseToHTML && incTags) this.node[i].outerHTML += isType(nval, "Array")? nval[i]: nval; else this.node[i].value? (this.node[i].value += isType(nval, "Array")? nval[i]: nval): (this.node[i].innerText += isType(nval, "Array")? nval[i]: nval); } } if (this.node.value && !parseToHTML && !incTags) this.node.value += nval; else if (this.node.innerHTML && parseToHTML && !incTags) this.node.innerHTML += nval; else if (this.node.innerText && !parseToHTML && !incTags) this.node.innerText += nval; else if (this.node.outerHTML && incTags && !parseToHTML) this.node.outerHTML += nval; else this.node.value? this.node.value += nval: this.innerText += nval; }; this.remove = function (c, r) { //Remove the character from the string/array/number and return it with the r character as a joiner or a blank when r isn't specified if (isType(this.val(), "Array")) { for (var i = 0; i < this.size(); i++) { if (this.val()[i] == c) this.write(this.val().slice(0, i).concat(this.val().slice(i + 1, this.size()))); } } this.write(this.val().split(c).join(r || "")); //Silent removing }; this.setCSS = function (prop, val) { //Change the css property if (isType(this.node, "NodeList")) addCSSRule(/\*\S/.test(selector)? selector.get(1): selector, camelCaseTo(prop, "hyphen") + ": " + val) else this.node.style[prop] = val; }; this.setInlineCSS = function (prop, vals) { for (var i = 0; i < this.node.length; i++) this.node[i].style[prop] = isType(vals, "Array")? vals[i]: vals; }; this.setStyles = function (sAndV) { //Style and vals: [style0, val0, style1, val1, ...] for(var i = 0; i < sAndV.length - 1; i += 2) this.setCSS(sAndV[i], sAndV[i + 1]); }; this.css = function (prop) { //Get the CSS property of the element's node if (isType(this.node, "Array")) { var arr = []; for(var i = 0; i < this.node.length; i++) arr.push(this.node[i].style[prop]); return arr } return isType(this.node, "NodeList")? this.node.toArray().map(function (currentNode) { return currentNode.style[prop]; }): this.node.style[prop] }; this.hasClass = function (className) { //Check if the element's node has the specified CSS class if (isType(this.node, "Array")) { var arr = []; for(var i = 0; i < this.node.length; i++) arr.push(new RegExp(" " + className + " ").test(" " + this.node[i].className + " ") || new RegExp(" " + className + " ").test(" " + this.node[i][className] + " ") || this.node[i].style.clasName == className); } return new RegExp(" " + className + " ").test(" " + this.node.className + " ") || new RegExp(" " + className + " ").test(" " + this.node[className] + " ") || this.node.style.className == className }; this.hasCSS = function (prop) { //Check if the element's node has the specified CSS property if (isType(this.node, "Array")) { var arr = []; for(var i = 0; i < this.node.length; i++) arr.push(new RegExp(" " + prop + " ").test(" " + this.node[i].style[prop] + " ") || new RegExp(" " + prop + " ").test(" " + this.node[i][prop] + " ")); } return new RegExp(" " + prop + " ").test(" " + this.node.style[prop] + " ") || new RegExp(" " + prop + " ").test(" " + this.node[prop] + " ") }; this.addClass = function (className) { //Add a class to the element's node if (isType(this.node, "Array")) { for (var i = 0; i < this.node.length; i++) { if (!this.node[i].hasClass(className)) this.node[i].className += " " + className; } } else if (!this.hasClass(className)) this.node.className += " " + className; }; this.rmClass = function (className) { //Remove the class from the element's node var newClass = " " + this.node.className.replace(/[\t\r\n]/g, " ") + " "; if (isType(this.node, "Array")) { for (var i = 0; i < this.node.length; i++) { newClass = " " + this.node[i].className.replace(/[\t\r\n]/g, " ") + " "; if (this.node[i].hasClass(className)) { while(newClass.indexOf(" " + className + " ") >= 0) newClass = newClass.replace(" " + className + " ", " "); this.node[i].className = newClass.replace(/^\s+|\s+$/g, ""); } } } else if (this.hasClass(className)) { while (newClass.indexOf(" " + className + " ") >= 0) newClass = newClass.replace(" " + className + " ", " "); this.node.className = newClass.replace(/^\s+|\s+$/g, ""); } }; this.toggleCSS = function (prop, params, stackLayer) { //Toggle between two or more values if (!stackLayer) stackLayer = 0; if (this.css(prop) === "" && stackLayer < 1) this.toggleCSS(prop, params, stackLayer + 1); if (prop === "visibility") { (this.css("visibility") === "visible")? this.setCSS("visibility", "hidden"): this.setCSS("visibility", "visible"); } else if (prop === "enabled") { (this.css("enabled") === "enabled")? this.setCSS("enabled", "disabled"): this.setCSS("enabled", "enabled"); } else if (prop === "display") { (this.css("display") === "block" || this.css("display") === params)? this.setCSS("display", "none"): this.setCSS("display", params || "block"); } else if (!isNon(prop) && !isNon(params)) { //For color, bgcolor, opacity, font-size, ... if (isNon(this.css(prop))) this.setCSS(prop, params[0]); for (var i = 0; i < params.length; i++) { //Slide through the parameters and go to the next one if the one already set is present if (this.css(prop) === params[i]) { this.setCSS(prop, params[(i + 1) % params.length]); break; } } } }; this.show = function () { this.setCSS("opacity", 1); this.setCSS("display", "block"); }; this.hide = function () { this.setCSS("opacity", 0); this.setCSS("display", "none"); }; this.on = function (evt, act) { //OnEvt handler var evts = ["abort", "autocomplete", "autocompleteerror", "beforeunload", "blur", "cancel", "canplay", "canplaythrough", "change", "click", "close", "contextmenu", "cuechange", "dblclick", "devicemotion", "deviceorientation", "drag", "dragend", "dragenter", "dragleave", "dragover", "dragstart", "drop", "durationchange", "emptied", "ended", "error", "focus", "hashchange", "input", "invalid", "keydown", "keypress", "keyup", "languagechange", "load", "loadeddata", "loadedmetadata", "loadstart", "message", "mousedown", "mouseenter", "mouseleave", "mousemove", "mouseout", "mouseover", "mouseup", "mousewheel", "offline", "online", "pagehide", "pageshow", "pause", "play", "playing", "popstate", "progress", "ratechange", "reset", "resize", "scroll", "search", "seeked", "seeking", "select", "show", "stalled", "storage", "submit", "suspend", "timeupdate", "toggle", "transitionend", "unload", "volumechange", "waiting", "webkitanimationend", "webkitanimationiteration", "webkitanimationstart", "webkittransitionend", "wheel"]; if (evts.has(evt.normal())) { isType(this.node, "NodeList")? this.node.toArray().map(function (node) { node.addEventListener(evt.normal(), act) }): this.node.addEventListener(evt.normal(), act); } }; this.toString = function () { return "[object Element]" }; this.tagName = function() { //get the enclosing tag's name return this.node.tagName.toLowerCase() }; this.scrollTop = function () { this.node.scrollTop = this.node.offsetTop; }; //noinspection JSUnusedGlobalSymbols this.scrollBottom = function () { this.node.scrollTop = this.node.offsetHeight - this.node.offsetTop; }; this.scrollLeft = function () { this.node.scrollLeft = this.node.offsetLeft; }; //noinspection JSUnusedGlobalSymbols this.scrollRight = function () { this.node.scrollLeft = this.node.offsetWidth - this.node.offsetLeft; }; this.scroll = function (x, y) { this.node.scrollLeft += x || 0; this.node.scrollTop += y || 0; }; //noinspection JSUnusedGlobalSymbols this.autoScroll = function (dir, speed) { if (!dir) dir = "d"; var self = this, iv = setInterval(function () { switch (dir.toLowerCase()[0]) { case "l": self.scroll(-1, 0); if (self.node.scrollLeft === self.node.offsetLeft) clearInterval(iv); break; case "rad": self.scroll(1, 0); if (self.node.scrollLeft === self.node.offsetWidth - self.node.offsetLeft) clearInterval(iv); break; case "u": self.scroll(0, -1); if (self.node.scrollTop === self.node.offsetTop) clearInterval(iv); break; default: //d self.scroll(0, 1); if (self.node.scrollTop === self.node.scrollHeight - self.node.offsetTop) clearInterval(iv); } }, speed || 50); }; //Maybe do something with $n(...).scrollIntoView() this.attr = function (name, nval) { if (isType(this.node, "NodeList")) { var res = []; for (var i = 0; i < this.node.length; i++) res += isNon(nval)? this.node[i].getAttribute(name): this.node[i].setAttribute(name, nval); return res; } else return isNon(nval)? this.node.getAttribute(name): this.node.setAttribute(name, nval); }; //noinspection JSUnusedGlobalSymbols this.rmAttr = function (name) { if (isType(this.node, "NodeList")) { var res = []; for (var i = 0; i < this.node.length; i++) this.node[i].removeAttribute(name); } else this.node.removeAttribute(name); }; this.invColour = function () { //First make sure there's a colour and a background colour specified on the affect element(s) if (isType(this.css("color"), "Array") || isType(this.css("backgroundColor"), "Array")) { this.node.toArray().filter(function (node) { return node.style.color === ""; }).map(function (node) { return node.style.color = "inherit"; }); this.node.toArray().filter(function (node) { return node.style.backgroundColor === ""; }).map(function (node) { return node.style.backgroundColor = "inherit"; }); } else { if (this.css("color") === "") this.setCSS("color", "inherit"); //if the colour wasn't set or is only known to CSS as the default inherited value if (this.css("backgroundColor") === "") this.setCSS("backgroundColor", "inherit"); } negateColour(selector, "color", "a"); negateColour(selector, "backgroundColor", "a"); }; this.classes = function () { return this.node.className.split(" "); }; this.multi = function (cb) { var nodes = this.node.toArray(); for (var i = 0; i < nodes.length; i++) cb(nodes[i]); }; //noinspection JSUnusedGlobalSymbols this.multiElm = function (method, args) { //Caution: every nodes treated must have an id var nodes = this.node.toArray(); for (var i = 0; i < nodes.length; i++) $e(nodes[i].id)[method](args[0], args[1], args[2]); }; this.delete = function () { this.write("", false, true); //Or this.node.parentElement.removeChild(this.node); }; this.replace = function (oldVal, newVal, parseToHTML, incTags) { this.write(this.val(parseToHTML, incTags).replace(oldVal, newVal), parseToHTML, incTags); }; this.moveCSS = function () { console.log("moving %s's rules to style", selector); addCSSRule(selector, this.attr("style")); this.rmAttr("style"); }; return this } /** * @description Include an external file/resource as a child of the document * @param {string} file Filename * @param {string} [type="link"] Type of the file * @returns {undefined} * @since 1.0 * @func * @example * include("script.js"); //It will include the script.js just like include("script.js", "script"); * include("style.css"); //same as include("style.css", "link") and include("style.css", "stylesheet"); */ function include (file, type) { if (!type) type = (file.indexOf(".js") > 0)? "script": "link"; var el = document.createElement(type); if (type === "script") el.src = file; else { el.href = file; el.rel = "stylesheet"; } el.type = (type === "script")? "text/javascript": "text/css"; document.head.appendChild(el) } /** * @description Avoid including a file if it's already included * @param {string} file Filename * @param {string} [type="link"] Type of the file * @param {string} [parentPath=""] Parent path * @returns {undefined|boolean} False flag or nothing * @since 1.0 * @func * @see module:essence~include */ function include_once (file, type, parentPath) { if (!type) type = (file.indexOf(".js") > 0)? "script": "link"; var r = type === "script"? gatherScripts(true): gatherStylesheets(true); if ((parentPath && (keyList(r, true).indexOf(parentPath + file) > -1 || valList(r, true).indexOf(parentPath + file) > -1)) || keyList(r, true).indexOf(file) > -1 || valList(r, true).indexOf(file) > -1) return false; else include(file, type) } /** * @description Removes an external resource * @param {string} file File name * @param {string} [type="link"] Type of the file * @returns {undefined} * @since 1.0 * @func * @example * exclude("oldscript.js"); //will remove the reference to the oldscript.js script. */ function exclude (file, type) { if (!type) type = (file.indexOf(".js")>0)? "script": "link"; var el = document.createElement(type); if (type === "script") el.src = file; else el.href = file; el.type = (type === "script")? "text/javascript": "text/css"; console.log("el", el); document.head.removeChild(el) } //will be replaced by this.filter(x => x === c).length in v1.2 /** * @description Counts how many times a character/property/number <code>c</code> is present in the object * @param {(string|Bool)} c Character data * @this Object * @returns {number} Number of occurrences of <code>c</code> in the object * @since 1.0 * @method * @example * "Hello world".count("o"); //2 * [4, 2, 0, -4, 1, 2, 3].count(0); //1 * @memberof Object.prototype * @external Object */ Object.prototype.count = function (c) { var n = 0; for (var i = 0; i < this.length; i++) { if (this[i] === c) n++; } return n }; /** * @description Get all the positions of a character/property/number c * @param {NumberLike} c Character/property/number * @this Object * @returns {number[]} Array of positions * @since 1.0 * @method * @example * "AbcdAbc".positions("A"); //[0, 4] * @memberof Object.prototype * @external Object */ Object.prototype.positions = function (c) { var pos = []; //noinspection JSUnresolvedVariable for (var i = 0; i < this.length; i++) { if (this[i] === c) pos.push(i); } return pos }; /** * @description Check if an object is iterable hence if it's a string/array/object * @this Object * @returns {boolean} Iterability check result * @since 1.0 * @method * @memberof Object.prototype * @external Object * @example * var myStr = "Hello", myNum = 1.4142, myBool = true, myArr = range(3), myObj = {a: 0, b: 1}; * myStr.isIterable(); //true * myNum.isIterable(); //false * myBool.isIterable(); //false * myArr.isIterable(); //true * myObj.isIterable(); //true */ Object.prototype.isIterable = function () { return isType(this, "String") || isType(this, "Array") || isType(this, "Object") }; /** * @description Self-destruction of the object. * Source: {@link https://Google.github.io/styleguide/javascriptguide.xml?showone=delete#delete} * @this Object * @returns {undefined} * @since 1.0 * @method * @memberof Object.prototype * @external Object */ Object.prototype.delete = function () { this.property = null; delete this; }; /** * @summary Equality check * @description Check if obj and the current object are the same * @param {*} obj Object to compared to * @this Object * @returns {boolean} Equality check result * @since 1.0 * @method * @memberof Object.prototype * @external Object * @example * var a = "Hello", b = "hello", c = ["h", "e", "l", "l", "o"]; * a.equals(b); //false * a.toLowerCase().equals(b); //true * c.join("").equals(a); //true * c.equals(a); //false */ Object.prototype.equals = function (obj) { return this.toString() === obj.toString() || this.toLocaleString() === obj.toLocaleString() }; /** * @description Multiple replacement * @param {Array[]} rules Rules containing (RegExp|String)/(RegExp|String) pairs * @this Object * @returns {*} Resulting object * @since 1.0 * @method * @memberof Object.prototype * @external Object * @example * "Hello world !".multiReplace([[/[A-Za-z]/g, "1"], [/(\s|\!)/, "0"]]); //"1111101111100" */ Object.prototype.multiReplace = function (rules) { var res = this.replace(rules[0][0], rules[0][1]); for (var i = 1; i < rules.length; i++) res = res.replace(rules[i][0], rules[i][1]); return res }; /** * @description Generates an array representation of the object * @this Object * @returns {Array} Resulting array * @since 1.0 * @method * @memberof Object.prototype * @external Object */ Object.prototype.toArray = function () { //Or perhaps Array.from(this) var res = []; for (var i in this) { if (this.hasOwnProperty(i)) res.push(this[i]); } return res; }; /** * @description Comparison check * @param {*} obj Object to be compared to * @this Object * @returns {number} Comparison check result * @since 1.0 * @method * @throws {TypeError} Type difference between this and obj * @memberof Object.prototype * @external Object */ Object.prototype.compareTo = function (obj) { if (getType(this) != getType(obj)) throw new TypeError(this + " and " + obj + "aren't of the same type, so can't be compared."); if ((getType(this) === "Object" && getCustomType(this) === getCustomType(obj)) || getType(this) === getType(obj)) { return this.equals(obj)? 0: (this.toString() < obj.toString() || this.toLocaleString() < obj.toLocaleString())? -1: 1; } }; /** * @description Check if an object has a property * @param {string} prop Property * @returns {boolean} Containment check result * @memberof Object.prototype * @external Object * @since 1.1 * @this Object * @method * @example * var a = {name: "A", size: 8}, b = ["1", "4", "9", "h", "w", "_"]; * a.has("name"); //true * a.has("value"); //false * b.has("w"); //true * b.has(" "); //false */ Object.prototype.has = function (prop) { return this[prop] != undefined; }; /** * @description Emptiness check on the object. * Source: {@link https://stackoverflow.com/a/679937/5893085|SO} * @return {boolean} Emptiness state * @memberof Object.prototype * @external Object * @this Object * @since 1.1 * @method * @example * var a = {}, b = new Object(), c = {x: 5}, d = ""; * a.isEmpty(); //true * b.isEmpty(); //true * c.isEmpty(); //false * d.isEmpty(); //true */ Object.prototype.isEmpty = function () { for (var prop in this) { if (this.hasOwnProperty(prop)) return false; } return true; }; /** * @description High level inheritance. * @param {*} parent Parent * @return {undefined} * @memberof Object.prototype * @external Object * @this Object * @since 1.1 * @method */ Object.prototype.inherits = function(parent) { this.prototype = Object.create(parent.prototype); this.prototype.constructor = this; }; /** * @description Check if an array has a value * @param {*} val Value * @return {boolean} Containment check result * @this Array * @method * @since 1.1 * @memberof Array.prototype * @external Array * @override */ Array.prototype.has = function (val) { return this.indexOf(val) > -1; }; /** * @description Get the first element of the array * @param {*} [nval] New value of the first element * @this Array * @returns {*} First element * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.first = function (nval) { return !isNon(nval)? this[0] = nval: this[0] }; /** * @description Get the last element of the array * @param {*} [nval] New value of the last element * @this Array * @returns {*} Last element * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.last = function (nval) { return !isNon(nval)? this[this.length - 1] = nval: this[this.length - 1] }; /** * @description Line of a 2D array * @param {number} [n=0] Index * @returns {Array} Line * @since 1.0 * @this Array * @method * @memberof Array.prototype * @external Array */ Array.prototype.line = function (n) { return this.map(function (i) { if (n < 0) n = this[i].length - n; return i[n || 0]; }) }; /** * @description Block of a 2D array * @param {number} [start=0] Starting index * @param {number} [end=this.length-1] Ending index * @returns {Array} Block * @this Array * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.block = function (start, end) { return this.map(function (i) { return i.get(start, end); }) }; /** * @description Returns the last index of the array * @this Array * @returns {number} Last index * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.lastIndex = function () { return this.length - 1 }; /** * @description Returns the middle index of the array * @param {boolean} [under=false] Indicates if we want the value under the virtual value * @this Array * @returns {number} Middle index * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.midIndex = function (under) { return under? Math.floor(this.length / 2) - 1: Math.floor(this.length / 2) }; /** * @description Returns the values of the array that are in an even position * @this Array * @returns {Array} Array of elements * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.even = function () { var e = []; for(var i = 0; i < this.length; i += 2) e.push(this[i]); return e }; /** * @description Returns the values of the array that are in an odd position * @this Array * @returns {Array} Array of elements * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.odd = function () { var o = []; for(var i = 1; i < this.length; i += 2) o.push(this[i]); return o }; /** * @description Get the maximum value of the array * @param {number} [start=0] Starting position * @param {number} [end=this.length-1] Ending position * @this Array * @returns {*} Maximum value * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.max = function (start, end) { var m = this[start || 0]; if ((!start && !end) || (start === 0 && end >= this.length - 1)) for(var i = 1; i < this.length; i++) m = Math.max(m, this[i]); else if (start && !end) for(i = start + 1; i < this.length; i++) m = Math.max(m, this[i]); else for(i = start + 1; i <= end; i++) m = Math.max(m, this[i]); return m }; /** * @description Get the maximum value of the array * @param {number} [start=0] Starting position * @param {number} [n=this.length-1] Number of values * @this Array * @returns {*} Maximum value * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.maxOf = function (start, n) { var m = this[start || 0]; for(var i = start + 1; i <= (n || this.length - 1); i++) m = Math.max(m, this[i]); return m }; /** * @description Get the median value of the array * @param {*} [nval] New value of the median cell * @this Array * @returns {*} Median * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.median = function (nval) { var arr = this.sort(function (a, b) { return a - b }); var half = Math.floor(arr.length / 2); return arr.length % 2? (nval? arr[half] = nval: arr[half]): (arr[half - 1] + arr[half]) / 2 }; /** * @description Get the minimum value of the array * @param {number} [start=0] Starting position * @param {number} [end=this.length-1] Ending position * @this Array * @returns {*} Minimum value * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.min = function (start, end) { var m = this[start || 0]; if ((!start && !end) || (start === 0 && end >= this.length-1)) for(var i = 1; i < this.length; i++) m = Math.min(m, this[i]); else if (start && !end) for(i = start + 1; i < this.length; i++) m = Math.min(m, this[i]); else for(i = start + 1; i <= end; i++) m = Math.min(m, this[i]); return m }; /** * @description Get the minimum value of the array * @param {number} [start=0] Starting position * @param {number} [n=this.length-1] Number of values * @this Array * @returns {*} Minimum value * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.minOf = function (start, n) { var m = this[start || 0]; for(var i = start + 1; i <= (n || this.length - 1); i++) m = Math.min(m, this[i]); return m }; /** * @description Shuffles the array * @param {number} [n=this.length] Number of shuffles * @this Array * @returns {Array} Shuffled array * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.shuffle = function (n) { for(var i = 0; i < (n || this.length); i++) swap(this, randTo(this.length - 1), randTo(this.length - 1)) return this; }; /** * @description Return the length of the longest row * @this Array * @returns {number} Max length * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.maxLength = function () { var ml = 0; for(var i = 0; i < this.length; i++) ml = Math.max(ml, this[i].length); return ml }; /** * @description Return the length of the shortest row * @this Array * @returns {number} Min length * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.minLength = function () { var ml = this[0].length; for(var i = 0; i < this.length; i++) ml = Math.min(ml, this[i].length); return ml }; /** * @description fill() for 2D arrays * @param {*} c Data * @this Array * @return {Array} The array post-modification * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.Fill2D = function (c) { return this.fill(new Array(this.length).fill(c)) }; /** * @description Remove a character/number/string from the array without affecting the initial one (it should !) * @param {*} [c] Data to remove * @param {boolean} [preserveInitial] Flag indicating whether the initial array is going to remain unchanged * @this Array * @returns {Array} Array after the operation * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.remove = function (c, preserveInitial) { //Note: it will automatically remove undefined and it goes bunckers when trying to remove objects var arr = this; if (preserveInitial) { if (isType(c, "Array")) { for(var i = 0; i < c.length; i++) arr = arr.remove(); return arr; } else { for (i = 0; i < this.length; i++) { if (arr[i] === c) arr = arr.slice(0, i).concat(arr.slice(i + 1, arr.length)); } arr = arr.map(function (x) { //Double check return x === c? undefined: x }); if (arr.has(undefined) && arr.length > 0) { var w = []; for ( i = 0; i < arr.length; i++) { if (arr[i] !== undefined) w.push(isType(arr[i], "Number")? parseFloat(arr[i]): arr[i]); } arr = w; } return arr } } else { var pos = Copy(this.positions(c)); for (i = 0; i < pos.length; i++) this.splice(pos[i], 1); return this; } }; /** * @description Debug an array by displaying in the console each of its elements * @this Array * @returns {undefined} * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.debug = function () { Essence.say("%cDebugging the following array:%c " + this, "text-decoration: bold", "text-decoration: none"); for(var i = 0; i < this.length; i++) Essence.say(i + ": " + this[i]) }; /** * @description Get the number of occurrences of each elements in array as well as the position(s) of each occurrences * @param {boolean} simplified Simplify the output * @todo Fix the thingy with the occurrences' positions not showing up * @this Array * @returns {Array} Result * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.getOccurrences = function (simplified) { var arr = rmDuplicates(this), res = []; for (var i = 0; i < arr.length; i++) res.push(arr[i] + ":" + this.count(arr[i]) + "{" + this.positions(arr[i]).toStr(true) + "}"); if (simplified) { for (i = 0; i < res.length; i++) res[i] = parseInt(res[i].replace(/(?:.*?):(\d+)\{(.*?)}/g, "$1")); } return res }; /** * @description Replace a character with an other * @param {*} Ci Initial character * @param {*} Cf Final character * @param {boolean} toStr String representation * @this Array * @returns {Array|string} Result * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.replace = function (Ci, Cf, toStr) { for (var i = 0; i < this.length; i++) { if (this[i] === Ci || (isType(Ci, "RegExp") && Ci.test(this[i]))) this[i] = Cf; } return toStr? this.toString(): this; }; /** * @description Sum of every elements of the array * @param {number} [start=0] Starting position * @param {number} [end=this.length-1] Ending position * @this Array * @returns {number} Sum * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.sum = function (start, end) { var s = 0; if ((!start && !end) || (start === 0 && end >= this.length - 1)) for(var i = 0; i < this.length; i++) s += this[i]; else if (start && !end) for(i = start; i < this.length; i++) s += this[i]; else for(i = start; i <= end; i++) s += this[i]; return s }; /** * @description Product of every elements of the array * @param {number} [start=0] Staring position * @param {number} [end=this.length-1] Ending position * @this Array * @returns {number} Product * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.prod = function (start, end) { var p = 0; if ((!start && !end) || (start === 0 && end >= this.length - 1)) for(var i = 0; i < this.length; i++) p *= this[i]; else if (start && !end) for(i = start; i < this.length; i++) p *= this[i]; else for(i = start; i <= end; i++) p *= this[i]; return p }; /** * @description Sum for 2D arrays * @param {number[]} [start=[0, 0]] Starting position * @param {number[]} [end=[this.length-1, this[this.length-1].length-1]] Ending positions * @returns {number} Sum * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.sum2d = function (start, end) { var s = 0; if ((!start && !end) || (start.equals([0, 0]) && end >= this.length - 1)) { for (var i = 0; i < this.length; i++) { for (var j = 0; j < this[i].length; j++) s += this[i][j]; } } else if (start && !end) { for (i = start[0]; i < this.length; i++) { for (j = start[1]; j < this[i].length; j++) s += this[i][j]; } } else { for (i = start[0]; i < end[0]; i++) { for (j = start[1]; j < end[1]; j++) s += this[i][j]; } } return s }; /** * @description Mean of each elements or a portion of it * @param {number} [nbDec=2] Number of decimals * @param {number} [start=0] Starting position * @param {number} [end=this.length-1] Ending position * @returns {number} Mean * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.mean = function (nbDec, start, end) { if (!start) start = 0; if (!end) end = this.lastIndex(); var sum = this.sum(start, end); return (sum / (this.get(start, end).length)).toNDec(nbDec); }; //noinspection JSUnusedGlobalSymbols /** * @description Mean of each elements. * @param {number} [nbDec=2] Number of decimals * @param {number} [start=0] Starting position * @param {number} [n=this.length-start-1] Number of values to take into account * @returns {number} Mean of N * @since 1.1 * @method * @memberof Array.prototype * @external Array */ Array.prototype.meanOf = function (nbDec, start, n) { if (!start) start = 0; if (!n) n = this.length - start - 1; var sum = 0; for (var i = 0; i < n; i++) sum += this[start + i]; return (sum / n).toNDec(nbDec); }; //noinspection JSUnusedGlobalSymbols /** * @description Minimum mean of n of all the means of the values * @param {number} [n=this.length-1] Number of values for the mean of n * @param {number} [nbDec=2] Number of decimals * @returns {*} Minimum Mean of N * @since 1.1 * @method * @throws {Error} n should be less than or equal to this.length * @memberof Array.prototype * @external Array */ Array.prototype.minMean = function (n, nbDec) { if (!n) n = this.length - 1; if (this.length - (n - 1) < 0) throw new Error("You're expecting a minimum mean with more values than the are."); var means = []; for (var i = 0; i < n; i++) means.push(this.mean(nbDec, i, i + n - 1)); return means.min(); }; //noinspection JSUnusedGlobalSymbols /** * @description Maximum mean of n of all the means of the values * @param {number} [n=this.length-1] Number of values for the mean of n * @param {number} [nbDec=2] Number of decimals * @returns {*} Maximum Mean of N * @since 1.1 * @method * @throws {Error} n should be less than or equal to this.length * @memberof Array.prototype * @external Array */ Array.prototype.maxMean = function (n, nbDec) { if (!n) n = this.length - 1; if (this.length - (n - 1) < 0) throw new Error("You're expecting a maximum mean with more values than the are."); var means = []; for (var i = 0; i < n; i++) means.push(this.mean(nbDec, i, n + i - 1)); return means.max(); }; /** * @description Timewise (Speedcubing) average of each times * @param {number} [nbDec=2] Number of decimals * @param {number} [start=0] Starting positions * @param {number} [end=this.length-1] Ending positions * @returns {number} Average * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.avg = function (nbDec, start, end) { if (!start) start = 0; if (!end) end = this.lastIndex(); var sum = this.sum(start, end) - this.max(start, end) - this.min(start, end); return (sum / (this.get(start, end).length - 2)).toNDec(nbDec) }; //noinspection JSUnusedGlobalSymbols /** * @description Timewise (Speedcubing) average of n times * @param {number} [nbDec=2] Number of decimals * @param {number} [start=0] Starting positions * @param {number} [n=this.length-start] Ending positions * @returns {number} Average Of N * @since 1.1 * @method * @memberof Array.prototype * @external Array */ Array.prototype.avgOf = function (nbDec, start, n) { if (!start) start = 0; if (!n) n = this.length - start - 1; var sum = 0; for (var i = 0; i < n; i++) { if (this[start + i] != this.maxOf(start, n) || this[start + i] != this.minOf(start, n + 1)) sum += this[start + i]; } return (sum / (n - 2)).toNDec(nbDec) }; //noinspection JSUnusedGlobalSymbols /** * @description Minimum time-wise average of n of all the means of the times * @param {number} [n=this.length-1] Number of times for the mean of n * @param {number} [nbDec=2] Number of decimals * @returns {*} Minimum Average of N * @since 1.1 * @method * @throws {Error} n should be less than or equal to this.length * @memberof Array.prototype * @external Array */ Array.prototype.minAvg = function (n, nbDec) { if (!n) n = this.length - 1; if (this.length - (n - 1) < 0) throw new Error("You're expecting a minimum average with more values than the are."); var avgs = []; for (var i = 0; i < n; i++) avgs.push(this.avg(nbDec, i, i + n - 1)); return avgs.min(); }; //noinspection JSUnusedGlobalSymbols /** * @description Maximum time-wise average of n of all the means of the times * @param {number} [n=this.length-1] Number of times for the mean of n * @param {number} [nbDec=2] Number of decimals * @returns {*} Maximum Average of N * @since 1.1 * @method * @throws {Error} n should be less than or equal to this.length * @memberof Array.prototype * @external Array */ Array.prototype.maxAvg = function (n, nbDec) { if (!n) n = this.length - 1; if (this.length - (n - 1) < 0) throw new Error("You're expecting a maximum average with more values than the are."); var avgs = []; for (var i = 0; i < n; i++) avgs.push(this.avg(nbDec, i, n + i - 1)); return avgs.max(); }; /** * @description Variance * @this Array * @param {number} [nbDec=2] Number of decimals * @returns {number} Variance * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.variance = function (nbDec) { return (sumPow2(this, nbDec) / this.length - Math.pow(this.mean(nbDec), 2)).toNDec(nbDec) }; /** * @description Standard deviation * @this Array * @param {number} [nbDec=2] Number of decimals * @returns {number} Standard deviation * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.stddev = function (nbDec) { var stdDev = Math.sqrt(this.variance(nbDec)); return stdDev.toNDec(nbDec) }; /** * @description Get a random cell of the array * @param {number} [n] Number of random elements to be returned * @this Array * @returns {*} Random element(s) * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.rand = function (n) { if (n && n > 0) { var res = []; for (var i = 0; i < n; i++) res.push(this.rand()); return res }else return this[lenRand(this.length)] }; /** * @description Quartile * @param {number} n Nth quartile * @param {number} [nbDec=2] Number of decimals * @this Array * @returns {*} Nth quartile * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.quartile = function (n, nbDec) { //Q1, Q2, Q3 return this.length % 2 === 0? ((this[Math.floor(n * this.length / 4) - 1] + this[Math.floor(n * this.length / 4)]) / 2).toNDec(nbDec): (this[Math.floor(n * this.length / 4)]).toNDec(nbDec) }; /** * @description Quintile * @param {number} n Nth quintile * @param {number} [nbDec=2] Number of decimals * @this Array * @returns {*} Nth quintile * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.quintile = function (n, nbDec) { //Q1, ..., Q4 return this.length % 2 === 0? ((this[Math.floor(n * this.length / 5) - 1] + this[Math.floor(n * this.length / 5)]) / 2).toNDec(nbDec): (this[Math.floor(n * this.length / 5)]).toNDec(nbDec) }; /** * @description Decile * @param {number} n Nth decile * @param {number} nbDec Number of decimals * @this Array * @returns {*} Nth decile * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.decile = function (n, nbDec) { //D1, ..., D9 return this.length % 2 === 0? ((this[Math.floor(n * this.length / 10) - 1] + this[Math.floor(n * this.length / 10)]) / 2).toNDec(nbDec): (this[Math.floor(n * this.length / 10)]).toNDec(nbDec) }; /** * @description Percentile * @param {number} n Nth percentile * @param {number} nbDec Number of decimals * @this Array * @returns {*} Nth percentile * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.percentile = function (n, nbDec) { //P1, ..., P99 return this.length % 2 === 0? ((this[Math.floor(n * this.length / 100) - 1] + this[Math.floor(n * this.length / 100)]) / 2).toNDec(nbDec): (this[Math.floor(n * this.length / 100)]).toNDec(nbDec) }; /** * @description Get the average increment between the values of the array * @param {number} [nbDec=2] Number of decimals * @this Array * @returns {Number} Increment * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.getIncrement = function (nbDec) { return nbDec == 0? parseInt(((this.max() - this.min()) / (this.length - 1))): ((this.max() - this.min()) / (this.length - 1)).toNDec(nbDec) }; /** * @description Increment every elements by n||1 * @param {number} [n=1] Increment value * @returns {undefined} * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.increment = function (n) { for(var i = 0; i < this.length; i++) this[i] += n || 1 }; /** * @description Inter Quartile Range * @param {number} [nbDec=2] Number of decimals * @this Array * @returns {number} IQR * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.iqr = function (nbDec) { //Inter-Quartile Range return this.quartile(3, nbDec) - this.quartile(1, nbDec).toNDec(nbDec) }; /** * @description Get the sub/ful-array * @param {number} [start=0] Starting position * @param {number} [end=this.length-1] Ending position * @this Array * @returns {Array} Resulting sub-array * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.get = function (start, end) { var res = []; if (start < 0 && !end) { end = start; start = 0; } if (end < 0) end = this.length + end - 1; for(var i = (start || 0); i <= (end || this.length - 1); i++) res.push(this[i]); return res.remove() }; /** * @description QuickSort adapted from https://Www.nczonline.net/blog/2012/11/27/computer-science-in-javascript-quicksort/ * @param {number} [left=0] Left position * @param {number} [right=this.lastIndex()] Right position * @this Array * @returns {Array} Sorted array * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.quickSort = function (left, right) { if (!left && !right) { left = 0; right = this.lastIndex(); } var i; if (this.length > 1) { var pivot = this[Math.floor((right + left)/2)], j = right; i = left; while (i <= j) { while(this[i] < pivot) i++; while(this[j] > pivot) j--; if (i <= j) { swap(this, i, j); i++; j--; } } if (left < i - 1) this.quickSort(left, i - 1); if (i < right) this.quickSort(i, right); } return this }; /** * @description Reverse QuickSort * @param {number} [left=0] Left position * @param {number} [right=this.length-1] Right position * @this Array * @returns {Array} Sorted array * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.revSort = function (left, right) { if (!left && !right) { left = 0; right = this.lastIndex(); } var i; if (this.length > 1) { var pivot = this[Math.floor((right + left) / 2)], j = right; i = left; while (i <= j) { while(this[i] > pivot) i++; while(this[j] < pivot) j--; if (i <= j) { swap(this, i, j); i++; j--; } } if (left > i-1) this.revSort(left, i - 1); if (i > right) this.revSort(i, right); } return this }; /** * @description BubbleSort (my version) * @param {(NumberLike|boolean)} [order="a"] Sorting order * @this Array * @returns {Array} Sorted array * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.bubbleSort = function (order) { var arr = this, j = 1, s = true; if (isNon(order) || isType(order, "String") && order[0].toLowerCase() === "a") { while (s) { s = false; for (var i = 0; i <= arr.length - j; i++) { if (arr[i] > arr[i + 1]) { arr = swap(arr, i, i + 1); s = true; } if (i < arr.length - (j + 1)) { if (arr[i] > arr[i + 2]) arr = swap(arr, i, i + 2); if (arr[i + 1] > arr[i + 2]) { arr = swap(arr, i + 1, i + 2); s = true; } } if (i < arr.length - (j + 2)) { if (arr[i] > arr[i + 3]) arr = swap(arr, i, i + 3); if (arr[i + 1] > arr[i + 3]) { arr = swap(arr, i + 1, i + 3); //start = true; } } } j++; } }else if (order === 1 || order[0].toLowerCase() === "d") { //Descending order while (s) { s = false; for (i = 0; i <= arr.length - j; i++) { if (arr[i] < arr[i + 1]) { arr = swap(arr, i, i + 1); s = true; } if (i < arr.length - (j + 1)) { if (arr[i] < arr[i + 2]) arr = swap(arr, i, i + 2); if (arr[i + 1]<arr[i + 2]) { arr = swap(arr, i + 1, i + 2); s = true; } } if (i < arr.length - (j + 2)) { if (arr[i] < arr[i + 3]) arr = swap(arr, i, i + 3); if (arr[i + 1] < arr[i + 3]) { arr = swap(arr, i + 1, i + 3); //start = true } } } j++; } } return arr }; /** * @description Brute force sort * @this Array * @returns {Array} Sorted array * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.bruteForceSort = function () { for (var i = 0; i < this.length; i++) { var s = this[i], pos = i; for (var j = i + 1; j <= this.length; j++) { if (s > this[j]) { s = this[j]; pos = j; } } var temp = this[i]; this[i] = s; this[pos] = temp; } return this }; /** * @description Max's Sort (mine) * @this Array * @returns {Array} Sorted Array * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.maxSort = function () { //Ignores repeated values and loose data var med = this.median(), res = new Array(this.length), inc = this.getIncrement(3), q1 = this.quartile(1), q3 = this.quartile(3); //Pre-sort some elements res[0] = this.min(); res.last(this.max()); if(parseInt(res.length / 2) === (res.length / 2)) res[res.length / 2] = med; if(parseInt(res.length / 4) === (res.length / 4)) res[res.length / 4] = q1; if(parseInt(3 * res.length / 4) === (3 * res.length / 4)) res[3 * res.length / 4] = q3; for (var i = 1; i < this.length - 1; i++) { //Add elements in the correct order that belongs to x if (this[i] === Math.floor(res[0] + i * inc)) res[i] = this[i]; else if (this[i] === Math.round(res[0] + i * inc)) res[i] = this[i]; else if (this[i] == Math.ceil(res[0] + i * inc)) res[i] = this[i]; else if (this[i] >= Math.floor(res[0] + i * inc) && this[i] <= Math.ceil(res[0] + i * inc)) res[i] = this[i] } console.log("current result: " + res.toStr(true)); for (i = this.length - 1; i > 1; i--) { //Same thing but from the end to complete the missing ones if (this[i] === Math.floor(res[res.length - 1] - i * inc) && isNon(res[i])) res[i] = this[i]; else if (this[i] === Math.round(res[res.length - 1] - i * inc) && isNon(res[i])) res[i] = this[i]; else if (this[i] === Math.ceil(res[res.length - 1] + i * inc) && isNon(res[i])) res[i] = this[i]; else if (this[i] >= Math.floor(res[res.length - 1] + i * inc) && this[i]<= Math.ceil(res[0] + i * inc) && isNon(res[i])) res[i] = this[i] } console.log("current result: " + res.toStr(true)); for (i = 1; i < this.length - 1; i++) { for (var j = 0; j < this.length; j++) { if (this[j] === Math.floor(res[0] + i * inc)) res[i] = this[j]; else if (this[j] === Math.round(res[0] + i * inc)) res[i] = this[j]; else if (this[j] === Math.ceil(res[0] + i * inc)) res[i] = this[j]; else if (this[j] >= Math.floor(res[0] + i * inc) && this[j] <= Math.ceil(res[0] + i * inc)) res[i] = this[j]; } } return res }; /** * @description Centre sort * @param {number} [l=0] Left position * @param {number} [r=this.length-1] Right position] * @returns {Array} Sorted array * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.cenSort = function (l, r) { //Ignores repeated values and loose database var res = new Array(this.length); if (!l && !r) { l = Math.floor(this.length / 2); r = Math.ceil(this.length / 2); } if (this.length <= 1) return this; var pivot = this[Math.floor((r + l)/2)], j = r, i = l; while (i <= j) { while(this[i] < pivot) i--; while(this[j] > pivot) j++; if (i >= j) { swap(this, i, j); i--; j++; } } if (l > i-1) this.cenSort(l, i - 1); if (i > r) this.cenSort(i, r); return res }; /** * @description Set sort. * Source: somewhere. * @this Array * @returns {Array} New array * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.setSort = function () { //A faster algorithm than quickSort only for integers where the extremities are known var t = [], l = this.length, res = []; for(var i = 0; i < 1000; i++) t[i] = 0; for(i = 0; i < l; i++) t[this[i]] = 1; for (i = 0; i < 1000; i++) { if (1 === t[i]) res.push(i); } return res }; /** * @description Clean the array * @param {boolean} [noDuplic=false] No duplicates * @this Array * @returns {Array} Cleaned array * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.clean = function (noDuplic) { //Remove undesirable items var arr = [], j = 0; for (var i = 0; i < this.length; i++) { if (!isNon(this[i])) arr[j++] = this[i]; } return noDuplic? rmDuplicates(arr).remove(): arr; //Take off (or not) duplicates of actual values and double clean it }; /** * @description eXtreme cleaning of the array * @this Array * @returns {Array} Cleaned array * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.xclean = function () { return this.clean(true).remove() }; /** * @description Substitute every elements from $s to $e with from $s to $e of the array $arr * @param {Array} arr Array * @param {number} [s=0] Starting position * @param {number} [e=this.length-1] Ending position * @this Array * @returns {Array} Modified array * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.chg = function(arr, s, e) { s = s || 0; e = e || this.length - 1; var a = this.get(s, e), b = arr.get(s, e); for (var i = 0; i < a.length; i++) a[i] = b[i] return a; }; /** * @description Exchange of elements between two arrays * @param {Array} arr Array * @param {number} s Starting position * @param {number} e Ending position * @returns {Array} Current resulting array * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.exchange = function(arr, s, e) { s = s || 0; e = e || this.length - 1; var a = this.get(s, e), b = arr.get(s, e); for (var i = 0; i < a.length; i++) { var tmp = a[i]; a[i] = b[i]; b[i] = tmp; } return a; }; /** * @description Rotate an array by $deg%90 deg * @param {number} deg Degree of rotation * @todo Finish the section for 4x4+ matrices * @this Array * @returns {Array} Rotated array * @since 1.0 * @method * @throws {Error} deg isn't a multiple of 90° * @memberof Array.prototype * @external Array */ Array.prototype.rot = function (deg) { var tmp; if (deg % 90 != 0) throw new Error("The absolute degree of rotation must be either 90° or 180°"); if (this.numElm() === 4 && this.length === 2) { //2x2 matrix if (deg === 90) { tmp = this[0][0]; this[0][0] = this[1][0]; this[1][0] = this[1][1]; this[1][1] = this[0][1]; this[0][1] = tmp; }else if (deg === -90) { tmp = this[0][0]; this[0][0] = this[0][1]; this[0][1] = this[1][1]; this[1][1] = this[1][0]; this[1][0] = tmp; }else if (Math.abs(deg) === 180) { tmp = [this[0][0], this[0][1]]; this[0][0] = this[1][1]; this[1][1] = tmp[0]; this[0][1] = this[1][0]; this[1][0] = tmp[1]; } }else if (this.numElm() === 9 && this.length === 3) { //3x3 matrix if (deg === 90) { tmp = [this[0][0], this[0][1]]; this[0][0] = this[2][0]; this[2][0] = this[2][2]; this[2][2] = this[0][2]; this[0][2] = tmp[0]; this[0][1] = this[1][0]; this[1][0] = this[2][1]; this[2][1] = this[1][2]; this[1][2] = tmp[1]; }else if (deg ==-90) { tmp = [this[0][0], this[0][1]]; this[0][0] = this[0][2]; this[0][2] = this[2][2]; this[2][2] = this[2][0]; this[2][0] = tmp[0]; this[0][1] = this[1][2]; this[1][2] = this[2][1]; this[2][1] = this[1][0]; this[1][0] = tmp[1]; }else if (Math.abs(deg) === 180) { tmp = [this[0][0], this[0][1], this[0][2], this[1][0]]; this[0][0] = this[2][2]; this[2][2] = tmp[0]; this[0][2] = this[2][0]; this[2][0] = tmp[2]; this[0][1] = this[2][1]; this[2][1] = tmp[1]; this[1][0] = this[1][2]; this[1][2] = tmp[3]; } }else if (this.numElm() === 16 && this.length === 4) { //4x4 matrix although I'm trying to make this as responsive as I get for 4x4+ matrices if (deg === 90) { tmp = this[0].get(-1); //Get all but the last element of the first row for (var j = 0; j < 1/*this.length / 2*/; j++) { //Weird error tmp = this[j].get(-1); for (var i = 0; i < this.maxLength() - 1; i++) { if(j > 0) Essence.say("#" + i); if(j > 0) Essence.say(this[j][i] + "<-" + this[this.length - 1 - i][j]); this[j][i] = this[this.length - 1 - i][j]; if(j > 0) Essence.say(this[this.length - 1 - i][j] + "<-" + this[this.length - 1 - j][this.length - 1 - i]); this[this.length - 1 - i][j] = this[this.length - 1 - j][this.length - 1 - i]; if(j > 0) Essence.say(this[this.length - 1 - j][this.length - 1 - i] + "<-" + this[i][this.length - 1 - j]); this[this.length - 1 - j][this.length - 1 - i] = this[i][this.length - 1 - j]; if(j > 0) Essence.say(this[i][this.length - 1 - j] + "<-" + tmp[i]); this[i][this.length - 1 - j] = tmp[i]; } } } else if (deg === -90) { tmp = [this[0][0], this[0][1]]; this[0][0] = this[0].last(); this[0].last(this.last().last()); this.last().last(this.last()[0]); this.last()[0] = tmp[0]; this[0][1] = this[1].last(); this[1].last(this.last()[1]); this.last()[1] = this[1][0]; this[1][0] = tmp[1]; } else if (Math.abs(deg) === 180) { tmp = [this[0][0], this[0][1], this[0].last(), this[1][0]]; this[0][0] = this.last().last(); this.last().last(tmp[0]); this[0].last(this.last()[0]); this.last()[0] = tmp.last(); this[0][1] = this.last()[1]; this.last()[1] = tmp[1]; this[1][0] = this[1].last(); this[1].last(tmp[3]); } }else throw "Unsupported matrix. Please wait or contact the developer to add this matrix\' support."; return this }; /** * @description Number of elements * @this Array * @returns {number} Number of elements * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.numElm = function () { return this.linearise().length }; /** * @description Size of the array * @param {boolean} [str=false] String format or not * @this Array * @returns {string|number[]} Size * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.size = function (str) { //Get the width * height size of the array return str? this.length + "x" + this.maxLength(): [this.length, this.maxLength()] }; /** * @description Determinant of the matrix * @this Array * @returns {number} Determinant * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.det = function () { var d = 0; if (this.numElm() === 4 && this.length === 2) d = this[0][0] * this[1][1]-this[0][1] * this[1][0]; else if (this.numElm() === 9 && this.length === 3) { d = this[0][0] * (this[1][1] * this.last().last()-this[1].last() * this.last()[1])-this[0][1] * (this[1][0] * this.last().last()-this[1].last() * this.last()[0]) + this[0].last() * (this[1][0] * this.last()[1]-this[1][1] * this.last()[0]); }else Essence.say("Unsupported matrix format", "error"); return d }; /** * @description Translate the array * @this Array * @returns {Array} Translated array * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.translate = function () { if (this.size()[0] === this.size()[1]) { //NxN for (var i = 0; i < Math.round(this.length / 2); i++) { for (var j = 0; j < this[0].length; j++) { if (!(1 === i && 0 === j && this[0].length > 2)) { var r = this[i][j]; this[i][j] = this[j][i] || ""; this[j][i] = r; } } } if (this.size(true) === "4x4") { var t = this[2].last(); this[2].last(this.last()[2]); this.last()[2] = t } } else { //NxM var arr = new Array(this.maxLength()).fill([]); for (i = 0; i < this.maxLength(); i++) arr[i] = this.line(i) return arr; } return this }; /** * @description Look for some $x in the array * @param {*} x Element looked for * @returns {number} Position of the element * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.lookFor = function (x) { for (var i = 0; i < this.length; i++) { if (this[i] === x || this[i].equals(x)) return i; } return -1 }; /** * @description Divide the array into an array with n-sized cells * @this Array * @param {number} n Size of each chunks * @returns {Array} Resulting array * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.divide = function (n) { var res = new Array(Math.round(this.length / n)).fill(""), k = 0; for (var i = 0; i < res.length; i++) { for(var j = 0; j < n; j++) res[i] += this[k++]; } return res }; /** * @description Adjoint of the matrix * @this Array * @returns {Array} Adjoint matrix * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.getAdjoint = function () { var m = this.translate(), res = mkArray(this.length, 2, Essence.eps); //+-+ //-+- //+-+ if (m.numElm() === 4 && m.length === 2) { res[0] = [m[1][1], -m[1][0]]; res[1] = [-m[0][1], m[0][1]]; }else if (m.numElm() === 9 && m.length === 3) { res[0] = [m[1][1] * m.last().last()-m[1].last() * m.last()[1], -(m[1][0] * m.last().last()-m[1].last() * m.last()[0]), m[1][0] * m.last()[1]-m[1][1] * m.last()[0]]; res[1] = [-(m[0][1] * m[1].last()-m[0].last() * m[1][1]), m[0][0] * m.last().last()-m[0].last() * m.last()[0], -(m[0][0] * m.last()[1]-m[0][1] * m.last()[0])]; res.last([m[0][1] * m[1].last()-m[0].last() * m[1][1], -(m[0][0] * m[1].last()-m[0].last() * m[1][0]), m[0][0] * m[1][1]-m[0][1] * m[1][0]]); }else Essence.say("Unsupported matrix format", "error"); return res }; /** * @description Invertibility check * @this Array * @returns {boolean} Is it invertible ? * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.isInvertible = function() { return this.det() != 0 }; /** * @description Dot product * @param {number} a Scalar * @this Array * @returns {Array} Resulting array * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.dotProd = function (a) { //A.this where a is a scalar and this a matrix var res = []; for (var i = 0; i < this.length; i++) { res[i] = []; for(var j = 0; j < this[i].length; j++) res[i][j] = a * this[i][j]; } return res }; /** * @description Dot addition * @param {number} a Scalar * @since 1.0 * @method * @returns {Array} Resulting array * @memberof Array.prototype * @external Array */ Array.prototype.dotAdd = function (a) { var res = []; for (var i = 0; i < this.length; i++) { res[i] = []; for(var j = 0; j < this[i].length; j++) res[i][j] = a + this[i][j]; } return res }; /** * @description Dot subtraction * @param {number} a Scalar * @param {string} [order=false] Order * @this Array * @returns {Array} Resulting array * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.dotSub = function (a, order) { var res = []; order = order.toLowerCase().remove(); for (var i = 0; i < this.length; i++) { res[i] = []; for(var j = 0; j < this[i].length; j++) res[i][j] = (order === "a-b")? a - this[i][j]: this[i][j] - a; } return res }; /** * @description Dot Fraction * @param {number} a Scalar * @param {string} order Order * @returns {Array} Resulting array * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.dotFrac = function (a, order) { var res = []; order = order.toLowerCase().remove(); for (var i = 0; i < this.length; i++) { res[i] = []; for(var j = 0; j < this[i].length; j++) res[i][j] = (order === "a/b")? a / this[i][j]: this[i][j] / a; } return res }; /** * @description String[]([]) to String * @param {boolean} [clean=false] Clean output * @this Array * @returns {string} String representation * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.toStr = function (clean) { var str = ""; if (is2dArray(this)) { for (var i in this) { if (this.hasOwnProperty(i)) str += clean? this[i].join(", "): this[i].join(""); } return clean? this.toStr().split("").join(", "): str }else return this.join(clean? ", ": "") }; /** * @description Number[] to Number * @returns {number} Integer representation * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.toInt = function () { var n = 0; for (var i in this) { if (this.hasOwnProperty(i)) n += this[i] * Math.pow(10, this.length - i - 1); } return n }; /** * @description Invert the matrix * @this Array * @returns {?Array} Inverse * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.inv = function () { return this.isInvertible()? this.dotProd(1 / this.det() * this.getAdjoint()): null; }; /** * @description Mix up the array * @this Array * @returns {Array} Mixed array * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.mix = function () { //Mix up the array var randPos = mixedRange(0, 1, this.length - 1, true), res = []; for (var i = 0; i < this.length; i++) res[i] = this[randPos[i]]; return res }; /** * @description Few mixes * @this Array * @returns {Array} Mixed array * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.littleMix = function () { var res = [], ic; if (is2dArray(this)) { res = Copy(this).linearise(); res = res.littleMix().toNcol(this.size()[1]).sanitise(getType(this[0][0])); //Assuming all cells are of the same type } else { ic = this.getIncrement(0); for (var i = 0; i < this.length; i++) { var r = randTo(ic); res.push(this[i]); if (i > 0 && r === 0) swap(res, i, i - 1); else if (i > 1 && r === ic) swap(res, i, i - 2); } } return res }; /** * @description Push that adds elements of an array instead of the array itself (just like Array.concat) * @this Array * @param {Array} arr Array used to append * @returns {Array} New array * @since 1.0 * @method * @memberof Array.prototype * @external Array * @deprecated */ Array.prototype.append = function (arr) { for (var i = 0; i < arr.length; i++) this.push(arr[i]); return this; }; /** * @description Unshift that adds element of an array instead of the array itself * @this Array * @param {Array} arr Array used to prepend * @returns {Array} New array * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.prepend = function (arr) { for (var i = 0; i < arr.length; i++) this.unshift(arr[i]); return this; }; /** * @description List of unique elements of the array * @this Array * @returns {Array} Array of unique elements * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.unique = function () { var u = []; for (var i = 0; i < this.length; i++) { if (this.count(this[i]) === 1) u.push(this[i]); } return u }; /** * @description N-D array to 1D array * @param {boolean} [jointer=false] Jointer * @returns {Array} res Resulting 1D array * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.to1d = function (jointer) { var res = Copy(this); for(var i = 0; i < res.length; i++) res[i] = res[i].join(jointer || ""); return res }; /** * @description 1D array to N-D array * @param {number} n Dimension * @this Array * @returns {Array} Resulting N-D array * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.toNd = function (n) { if(!n) n = 2; var sz = nthroot(this.length, n, 0), res = [], k = 0; //Size of the sz**n for (var i = 0; i < sz; i++) { res[i] = []; for (var j = 0; j < sz; j++) res[i][j] = this[k++]; } return res; }; /** * @description 1D array to N-column array * @param {number} n Number of columns * @this Array * @returns {Array} Resulting array * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.toNcol = function (n) { var res = [], k = 0; //Size of the sz**n for (var i = 0; i < this.length / n; i++) { res[i] = []; for (var j = 0; j < n; j++) res[i][j] = this[k++]; } return res; }; /** * @description 1D array to N-row array * @param {number} n Number of rows * @this Array * @returns {Array} Resulting array * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.toNrow = function (n) { var res = [], k = 0; //Size of the sz**n for (var i = 0; i < n; i++) { res[i] = []; for (var j = 0; j < this.length / n; j++) res[i][j] = this[k++]; } return res; }; /** * @description Linear 1D array * @this Array * @returns {Array} Linearised array * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.linearise = function() { return this.toString().split(","); }; /** * @description Ensure that all the elements are of the same length * @param {NumberLike} [cr=" "] Filler * @returns {Array} Uniformed array * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.uniform = function (cr) { var res = this, ml = res.maxLength(); for (var i = 0; i < res.length; i++) { while(res[i].length < ml) isType(res[i], "Array")? res[i].push(cr || " "): res[i] += cr || " "; } return res }; /** * @description Zip the array * @this Array * @returns {Array} Zipped array * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.zip = function () { var res = [], j; for (var i = 0; i < this.length; i++) { if (this[i] === this[i + 1]) { j = 1; while(this[i] === this[i + j]) j++; res.push(this[i] + "@" + j); i += j-1; }else res.push(this[i]); } return res.length < this.length? res: this; //Make sure that the compressed array isn't longer than the initial one }; /** * @description Unzip the array * @param {boolean} [noPairs=false] Keep pairs or not ? * @this Array * @returns {Array} Unzipped array * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.unzip = function (noPairs) { var res = []; for (var i = 0; i < this.length; i++) { if (/[\S\s](@)(\d+)/g.test(this[i])) res.push(this[i][0].repeat(this[i][this[i].indexOf("@") + 1])); else res.push(this[i]); } return noPairs? res.join("").split(""): res; }; /** * @description Trim the array * @param {(string|boolean)} side Side * @this Array * @returns {Array} res Trimed array * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.trimAll = function (side) { //Trimes every elements var res = []; side = side? side[0].toLowerCase(): ""; //noinspection JSUnresolvedFunction for (var i = 0; i < this.length; i++) res[i] = (side === "l")? this[i].trimLeft(): ((side === "rad")? this[i].trimRight(): this[i].trim()); return res }; /** * @description Sorted state check * @this Array * @returns {boolean} Sorted or not * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.isSorted = function () { //Check if the array is sorted if (this[0] > this[1]) return false; for (var i = 1; i < this.length; i++) { if (this[i] > this[i+1]) return false } return true }; /** * @description Ensure that the element isn't pushed when it's already there * @this Array * @param {*} obj Object * @returns {undefined} * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.uniquePush = function (obj) { //Post-init duplicate safe push if (isType(obj, "Array")) { for (var i = 0; i < obj.length; i++) { if (this.indexOf(obj[i]) === -1) this.push(obj[i]); } } else if (this.has(obj)) throw "the object " + obj.toString() + "is already present in " + this.toString(); else this.push(obj); }; /** * @description Replace all occurrences of $str instead of just the first one * @param {NumberLike} str String/number * @param {NumberLike} nstr New string/number * @returns {(Array|string)} Result * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.replaceAll = function (str, nstr) { var res = this.replace(str, nstr), i = 0; while (res.has(str) || i === this.length) { res = this.replace(str, nstr); i++; } return res; }; /** * @description Neighbour check * @param {Nums} y Row number * @param {Nums} x Column number * @returns {Array} Neighbours * @since 1.0 * @method * @throws {RangeError} y|x is too big * @memberof Array.prototype * @external Array */ Array.prototype.neighbour = function (y, x) { var n = [], seq; if (isType(y, "Array")) { x = parseInt(y[1]); y = parseInt(y[0]); } else { y = parseInt(y); x = parseInt(x); } if (y >= this.length) throw new RangeError("The y-coord is out of bounds"); if (x >= this.maxLength()) throw new RangeError("The x-coord is out of bounds"); if (is2dArray(this)) { seq = [[-1, 0], [-1, 1], [0, 1], [1, 1], [1, 0], [1, -1], [0, -1], [-1, -1]]; for (var i = 0; i < seq.length; i++) { try { if (!isNon(this[y + seq[i][0]][x + seq[i][1]])) n.push(this[y + seq[i][0]][x + seq[i][1]]); } catch (e) { /* eslint no-empty: 0 */ } } } else { try { if (!isNon(this[y - 1])) n.push(this[y - 1]); if (!isNon(this[y + 1])) n.push(this[y + 1]); } catch (e) {} } return n; }; /** * @description Make sure all the cells are of the right type * @param {string} type Type * @this Array * @returns {Array} Sanitised array * @since 1.0 * @method * @memberof Array.prototype * @external Array */ Array.prototype.sanitise = function (type) { for (var i = 0; i < this.length; i++) { for (var j = 0; j < this[i].length; j++) this[i][j] = name2Type(type, this[i][j]); } return this; }; /** * @description Get a portion of the array * @param {number} [denominator=2] How many parts (half by default) * @param {number} [numerator=1] Position of the part (1st half by default) * @returns {Array} Portion of the array * @since 1.1 * @method * @memberof Array.prototype * @external Array */ Array.prototype.portion = function (denominator, numerator) { return (this.length % 2 === 0)? this.get((numerator || 1) * Math.round(this.length) / (denominator || 2)): this.get(Math.floor((numerator || 1) * Math.floor(this.length) / (denominator || 2))); }; /** * @description Remove the first element <code>n</code> of the array (so not all values equal to n). * @param {*} n Element * @param {boolean} [preserveInitial] Flag indicating whether the initial array is going to remain unchanged * @returns {Array.<*>} Array without that first element n * @see external:Array.remove * @since 1.1 * @method * @memberof Array.prototype * @external Array */ Array.prototype.removeFirst = function (n, preserveInitial) { var self = this; return preserveInitial? this.filter(function (x, i) { return x != n || i != self.indexOf(n); }): this.splice(this.indexOf(n), 1); }; //noinspection JSUnusedGlobalSymbols /** * @description Remove the last element <code>n</code> of the array (so not all values equal to n). * @param {*} n Element * @param {boolean} [preserveInitial] Flag indicating whether the initial array is going to remain unchanged * @return {Array.<*>} Array without that last element n * @see external:Array.remove * @since 1.1 * @method * @memberof Array.prototype * @external Array */ Array.prototype.removeLast = function (n, preserveInitial) { var self = this; return preserveInitial? this.filter(function (x, i) { return x != n || i != self.lastIndexOf(n); }): this.splice(this.lastIndexOf(n), 1); }; /** * @description Performs a binary search on the host array. This method can either be * injected into Array.prototype or called with a specified scope like this: * binaryIndexOf.call(someArray, searchElement);<br />Source: {@link http://oli.me.uk/2013/06/08/searching-javascript-arrays-with-a-binary-search/} * @param {*} searchElement The item to search for within the array. * @return {number} The index of the element which defaults to -1 when not found. * @since 1.1 * @method * @memberof Array.prototype * @external Array * @this Array */ Array.prototype.binaryIndexOf = function (searchElement) { var minIndex = 0, maxIndex = this.length - 1, currentIndex, currentElement, resultIndex; while (minIndex <= maxIndex) { resultIndex = currentIndex = (minIndex + maxIndex) >> 1; currentElement = this[currentIndex]; if (currentElement < searchElement) minIndex = currentIndex + 1; else if (currentElement > searchElement) maxIndex = currentIndex - 1; else return currentIndex; } return ~maxIndex; }; /** * @description Place an item at the right place (to not mess up the order). * @param {*} n Term to place * @returns {Array} Modified array * @this Array * @since 1.1 * @method * @memberof Array.prototype * @external Array * @example * var arr = [0, 1, 2, 4]; * arr.place(3); //arr = [0, 1, 2, 3, 4] */ Array.prototype.place = function (n) { this.splice(Math.abs(this.binaryIndexOf(n)), 0, n); return this; }; /** * @description Place items of an array at the right places (to not mess up the order). * @param {Array} arr Array containing the terms to place * @returns {Array} Modified array * @this Array * @since 1.1 * @method * @memberof Array.prototype * @external Array * @example * var arr = [0, 1, 2, 4, 8]; * arr.multiPlace([3, 5, 6, 7, 9]); //arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] */ Array.prototype.multiPlace = function (arr) { for (var i = 0; i < arr.length; i++) this.place(arr[i]); return this; }; /** * @description Check if the string has a character * @inheritdoc * @param {*} val Character * @returns {boolean} Containment check result * @this String * @method * @since 1.1 * @memberof String.prototype * @external String */ String.prototype.has = Array.prototype.has; /** * @inheritdoc * @description Get the last element of the string * @param {*} [nval] New value of the last element * @this String * @returns {*} Last element * @since 1.0 * @method * @memberof String.prototype * @external String */ String.prototype.last = function (nval) { return this.split("").last(nval); }; String.prototype.splice = function (index, count, add) { if (index < 0) { index = this.length + index; if (index < 0) { index = 0; } } return this.slice(0, index) + (add || "") + this.slice(index + count); }; /** * @description Remove the character $c from the string * @param {string} c Character * @this String * @returns {string} Resulting string * @since 1.0 * @method * @memberof String.prototype * @external String */ String.prototype.remove = function (c) { //Remove c from the string var str = this; if (isType(c, "Array")) { for (var i in c) { if (c.hasOwnProperty(i)) str = str.remove(); } return str; } else { var v = str.split(c).map(function (x) { return x === c? undefined: x }).join(""); return v.has(undefined)? str.remove(): v } }; /** * @description A FP fix that preserve for Number like strings. * @param {NumberLike} [n=2] Number of decimals * @this String * @returns {string} Floating point number * @since 1.0 * @method * @memberof String.prototype * @external String */ String.prototype.toNDec = function (n) { return Number(this).toFixed(n || 2); }; /** * @description to N digits * @param {number} [n=2] Number of digits * @this String * @returns {String} Resulting string * @since 1.0 * @method * @memberof String.prototype * @external String */ String.prototype.toNDigits = function (n) { var i = this; n = n || 2; if (parseFloat(i) < Math.pow(10, n - 1)) { while (i.split(".")[0].length < n) i = "0" + i; } return i }; /** * @description Mix the string * @param {string} separator Separation character * @param {string} jointer Joining character * @this String * @returns {string} Mixed string * @memberof String.prototype * @external String */ String.prototype.mix = function (separator, jointer) { separator = isNon(separator)? "": separator; jointer = !jointer? separator: jointer; var randPos = mixedRange(0, 1, this.length - 1), iStr = this.split(separator), fStr = []; for (var i = 0; i < this.length; i++) fStr[i] = iStr[randPos[i]]; return fStr.join(jointer) }; /** * @description Divide the string into n-sized chunks * @this String * @param {number} n Number of chunks * @returns {string[]} Divided string * @since 1.0 * @method * @memberof String.prototype * @external String */ String.prototype.divide = function (n) { var res = new Array(Math.round(this.length / n)).fill(""), k = 0; for (var i = 0; i < res.length; i++) { for (var j = 0; j < n; j++) res[i] += this[k++]; } return res }; /** * @description Capitalize the first letter(s) * @param {boolean} whole Every words or just the first one * @this String * @returns {string} String * @since 1.0 * @method * @memberof String.prototype * @external String */ String.prototype.capitalize = function (whole) { var res = this.toString(); //Because it will return the String object rather than the actual string if (whole) { var str = res.split(" "); for(var i = 0; i < str.length; i++) str[i] = str[i].capitalize(); return str.join(" ") }else return this.charAt(0).toUpperCase() + this.slice(1); //http://stackoverflow.com/questions/1026069/capitalize-the-first-letter-of-string-in-javascript/1026087#1026087 }; /** * @description Ascii sum * @this String * @returns {number} Ascii sum * @since 1.0 * @method * @memberof String.prototype * @external String */ String.prototype.sum = function () { var sum = 0; for(var i = 0; i < this.length; i++) sum += this.charCodeAt(i); return sum }; /** * @description Ascii product * @this String * @returns {number} Ascii product * @since 1.0 * @method * @memberof String.prototype * @external String */ String.prototype.prod = function () { var prod = 1; for(var i = 0; i < this.length; i++) prod *= this.charCodeAt(i); return prod }; /** * @description Ascii mean * @this String * @returns {number} Mean * @since 1.0 * @method * @memberof String.prototype * @external String */ String.prototype.mean = function () { var strArr = []; for(var i = 0; i < this.length; i++) strArr[i] = this.charCodeAt(i); return strArr.mean(2) }; /** * @description Normalise the string * @this String * @returns {string} Normalised string * @since 1.0 * @method * @memberof String.prototype * @external String */ String.prototype.normal = function () { return this.toLowerCase().remove() }; /** * @description Get the occurrences of each characters as well as their positions * @type {Array.getOccurrences|*} * @returns {undefined} * @since 1.0 * @method * @see external:Array.prototype.getOccurrences * @inheritdoc * @memberof String.prototype * @external String */ String.prototype.getOccurrences = Array.prototype.getOccurrences; /** * @description Get a portion of the string * @param {number} [start=0] Starting position * @param {number} [end=this.length-1] Ending position * @this String * @returns {string} Resulting string * @since 1.0 * @method * @memberof String.prototype * @external String */ String.prototype.get = function (start, end) { var res = ""; if (start < 0 && !end) { end = start; start = 0; } if (end < 0) end = this.length + end - 1; for(var i = (start || 0); i <= (end || this.length - 1); i++) res += this[i]; return res }; /** * @description Zip the string * @this String * @returns {string} Zipped string * @since 1.0 * @method * @memberof String.prototype * @external String */ String.prototype.zip = function () { //Compress the string var res = "", j; for (var i = 0; i < this.length; i++) { if (this[i] === this[i + 1]) { j = 1; while(this[i] === this[i + j]) j++; res += this[i] + "@" + j; i += j - 1; } else res += this[i]; } return res.length < this.length? res: this; //Make sure that the compression doesn't end up making the string longer }; /** * @description Unzip the string * @param {boolean} [noPairs=false] Pairs or not ? * @this String * @returns {string} Unzipped string * @since 1.0 * @method * @memberof String.prototype * @external String */ String.prototype.unzip = function (noPairs) { //Decompress the string (when being compressed using String.zip()) with(out) pairs var res = ""; for (var i = 0; i < this.length; i++) { if (/[\S\s](\@)(\d+)/g.test(this[i])) res += this[i][0].repeat(this[i][this[i].indexOf("@") + 1]); else res += this[i]; } return noPairs? res.split("").join(""): res; }; /** * @description Replace all the occurrences of $str instead of just the first one * @param {string} str String * @param {string} nstr New string * @param {string} sep Separation * @this String * @returns {string} Modified string * @since 1.0 * @method * @memberof String.prototype * @external String */ String.prototype.replaceAll = function(str, nstr, sep) { var res = sep? this.split(sep).replace(str, nstr) : this.replace(str, nstr), i = 0; if (sep === "") return this.replace(RegExpify(str), nstr); //Avoid the infinite loop caused by sep = "" while (res.has(str) || i === this.length) { //Look up the occurrences until there's none of them left or the interpreter reached the end res = this.replace(str, nstr); i++; } return sep? res.join(sep): res; }; /** * @description Chunk the string into substrings of words * @param {number} [start=0] Starting position * @param {number} [end=this.length-1] Ending position * @this String * @returns {string} Chunked string * @since 1.0 * @method * @memberof String.prototype * @external String */ String.prototype.chunk = function (start, end) { return this.split(" ").get(start, end).join(" "); }; /** * @description Return the chunk that is the same at the beginning of both string * @param {string} str String * @this String * @returns {string} Same string * @method * @since 1.1 * @memberof String.prototype * @external String */ String.prototype.sameFirst = function (str) { var sf = "", pos = -1; while (pos <= Math.min(this.length, str.length)) { pos++; //(this[pos] === str[pos])? sf += this[pos]: break; if (this[pos] === str[pos]) sf += this[pos]; else break; } return sf; }; //noinspection JSUnusedGlobalSymbols /** * @description Return the chunk that is the same at the end of both string * @param {string} str String * @this String * @returns {string} Same string * @method * @since 1.1 * @memberof String.prototype * @external String */ String.prototype.sameLast = function (str) { var sf = "", pos = 1, minLen = Math.min(this.length, str.length); while (pos <= minLen) { //(this[this.length - pos] === str[str.length - pos])? sf = this[this.length - pos] + sf: break; if (this[this.length - pos] === str[str.length - pos]) sf = this[this.length - pos] + sf; else break; pos++; } return sf; }; /** * @description String equivalent of Array.map * @param {Function} cb Callback function * @param {string} [sep=""] Seperator/jointor * @return {string} Mapped string * @memberof String.prototype * @since 1.1 * @method * @external String * @this String */ String.prototype.map = function (cb, sep) { return this.split(sep || "").map(cb).join(sep || ""); }; /** * @description Reverse a string * @memberOf String.prototype * @param {string} [splitter=""] Splitting/joining string * @return {string} Reversed string * @method * @since 1.1 * @external String * @this String */ String.prototype.reverse = function (splitter) { return this.split(splitter || "").reverse().join(splitter || ""); }; //noinspection JSUnusedGlobalSymbols /** * @description Minify a string/code * @param {boolean} [noComment=false] Remove HTML/CSS like comments * @param {boolean} [noSpace=false] Remove spaces * @method * @since 1.1 * @external String * @return {string} Minified version of the string/code */ String.prototype.minify = function (noComment, noSpace) { var min = noSpace? this.trim().replace(/(\t|\n|\s)/gm, ""): this.trim().replace(/(\t|\n|\s{2,})/gm, ""); return noComment? min.replace(/(<!--(.*?)-->|\/\*+(.*?)\*+\/)/gm, ""): min; }; /** * @description Get a portion of the string * @inheritdoc * @param {number} [denominator=2] How many parts (halfs by default) * @param {number} [numerator=1] Position of the part (1st half by default) * @returns {String} Portion of the string * @this String * @method * @since 1.1 * @memberof String.prototype * @external String */ String.prototype.portion = function (denominator, numerator) { return this.split("").portion(denominator, numerator).join(""); }; /** * @description Counts how many times a word is present in the string. * @param {String} word Word to be counted * @param {String} [separation=" "] Separation character * @this String * @returns {number} Number of occurrences of the word in the string * @since 1.0 * @method * @inheritdoc * @memberof String.prototype * @external String */ String.prototype.countWord = function (word, separation) { return this.split(separation || " ").count(word); }; /** * @description Length of the number * @this Number * @returns {Nums} Length * @since 1.0 * @method * @memberof Number.prototype * @external Number */ Number.prototype.length = function () { if (String(this).has(".")) return [parseInt(String(this).split(".")[0].length), parseInt(String(this).split(".")[1].length)]; var l = 0, x = this; while (Math.floor(x) != 0) { x /= 10; l++; console.log(x); } return l }; /** * @description A FP fixing that preserve the number format * @param {number} [n=2] Number of decimals * @this Number * @returns {number} Floating point number * @since 1.0 * @method * @memberof Number.prototype * @external Number */ Number.prototype.toNDec = function (n) { //A bit like .toFixed(n) and .toPrecision(n) but returning a double instead of a string var pow10s = Math.pow(10, n || 2); return Math.round(pow10s * this) / pow10s }; /** * @description Keep a fixed amount of unit digits * @param {number} [n=2] Number of digits * @returns {string} New number * @since 1.0 * @method * @memberof Number.prototype * @external Number */ Number.prototype.toNDigits = function (n) { //Get the number to be a n-digit number var i = this + ""; //Because it won't work with other types than strings n = n || 2; if (parseFloat(i) < Math.pow(10, n - 1)) { while (i.split(".")[0].length < n) i = "0" + i; } return i }; /** * @description Sign of the number * @param {boolean} str Symbols string representation ? * @returns {NumberLike} Sign * @since 1.0 * @method * @memberof Number.prototype * @external Number */ Number.prototype.sign = function (str) { //Get the sign of the number return str? (this < 0? "-": (this > 0? " + ": "")): (this < 0? -1: (this > 0? 1: 0)) }; /** * @description Prime check * @param {number} n Number to check in relation * @returns {boolean} Prime check result * @since 1.0 * @method * @memberof Number.prototype * @external Number */ Number.prototype.isPrime = function (n) { for (var i = 2; i < n; i++) { if (primeCheck(i, n)) return false } return true }; /** * @description Clean the number * @param {number} [nbDec=2] Number of decimals * @returns {*} Cleaned number * @since 1.0 * @method * @memberof Number.prototype * @external Number */ Number.prototype.clean = function (nbDec) { if (this === 0) return 0; else if (this > 0 && this[0] == "+") return nbDec? this.slice(1, this.length).toNDec(nbDec): this.slice(1, this.length); else if (this == "-") return this + 1; else if (this == "+") return 1; else return nbDec? this.toNDec(nbDec): this }; /** * @description Number to Number[] * @returns {number[]} Number array * @since 1.0 * @method * @memberof Number.prototype * @external Number */ Number.prototype.toArr = function () { var arr = new Array(this.length()), i = 0, n = this; while (n > 0) { arr[i] = n % 10; i++; n /= 10; } return arr }; /** * @description Inheritance.<br /> * Source: Somewhere * @param {*} parentClassOrObj Parent * @returns {Function} this Current function/constructor * @since 1.0 * @method * @memberof Function.prototype * @external Function */ Function.prototype.inheritsFrom = function (parentClassOrObj) { if (parentClassOrObj.constructor === Function) { //Normal Inheritance this.prototype = new parentClassOrObj; this.prototype.constructor = this; this.prototype.parent = parentClassOrObj.prototype; } else { //Pure Virtual Inheritance this.prototype = parentClassOrObj; this.prototype.constructor = this; this.prototype.parent = parentClassOrObj; } //noinspection JSValidateTypes return this }; /** * @description Type check * @param {*} obj Object * @param {string} type Type * @returns {boolean} Type check result * @since 1.0 * @func */ function isType (obj, type) { //Only works for native types (treats custom ones as objects) return getType(obj, true) === "[object " + type + "]" } /** * @description Custom type check * @param {*} obj Object * @param {string} type Type * @returns {boolean} Custom type check result * @since 1.0 * @func */ function isCustomType (obj, type) { //Same as isType but for custom types return getCustomType(obj) === type } /** * @description Type getter * @param {*} obj Object * @param {boolean} [preserve=false] Preserve the format * @returns {string} Type * @since 1.0 * @func */ function getType (obj, preserve) { //Only works for native types. preserve would leave the [object type] var t = Object.prototype.toString.call(obj); return preserve? t: t.split(" ")[1].slice(0, t.split(" ")[1].length - 1) } /** * @description Custom type getter * @param {*} obj Object * @param {boolean} [preserve=false] Preserve the format of strings like [object Element] * @returns {string} Custom type * @since 1.0 * @func */ function getCustomType (obj, preserve) { //Same as getType but for custom types which won't work for native types var t = obj.toLocaleString(); if (t.indexOf("[") === 0) return preserve? t: t.split(" ")[1].slice(0, t.split(" ")[1].length - 1); //[object Type] else return t.split("(")[0].trim() } /** * @description 2D array check * @param {*} obj Object * @returns {boolean} 2D array check result * @since 1.0 * @func */ function is2dArray (obj) { //Check if an array has 2 dimensions (nxm matrix) if (isType(obj, "Array")) { for (var i = 0; i < obj.length; i++) { if (isType(obj[i], "Array")) return true } } else return false } /** * @description Check if $val is nothing/empty * @param {*} val Value * @returns {boolean} Voidness/emptyness result * @since 1.0 * @func */ function isNon (val) { return (val === false || val === undefined || val === null || val === "" || val.equals([]) || val.equals({})) } /** * @description Check if a variable/object exist or not. * @param {*} obj Object/variable to check * @return {boolean} Existence result * @since 1.1 * @func * @example * var a = undefined, b, c = null; * exist(a); //true because: a in window === true * exist(b); //true because: b in window === true * exist(c); //true because: (typeof c !== "undefined" && c !== undefined) === true * exist(d); //false */ function exist (obj) { /* eslint no-shadow-restricted-names: 0 */ var undefined, t; try { //noinspection JSUnusedAssignment t = typeof obj !== "undefined" || obj !== undefined || obj in window; /* eslint no-shadow-restricted-names: 2 */ } catch (e) { t = false; } return t; } /** * @description Returns a copy of an element in order to do mutation-safe operations with it * @param {*} el Element * @returns {*} Copy of <code>el</code> * @since 1.0 * @func */ function Copy (el) { if (isType(el, "String") || isType(el, "Number") || isType(el, "Boolean")) return el; //As they are immutable types else{ var clone = {}; for (var i in el) { if (el.hasOwnProperty(i)) clone[i] = el[i]; } return isType(el, "Array")? clone.toArray(): clone; } } /** * @description Get the information about the key pressed * @param {*} keyStroke Keystroke * @param {boolean} [tLC=false] To lower case * @returns {Array} Keystroke information * @since 1.0 * @func */ function getKey (keyStroke, tLC) { //Get information about the key pressed var code = !document.all? keyStroke.which: event.keyCode; var char = tLC? String.fromCharCode(code).toLowerCase(): String.fromCharCode(code); return [char, code] } /** * @description Get the time (in the format: hh:mm:ss[.xxx]) * @param {boolean} [ms=false] Include milliseconds * @returns {string} Time * @since 1.0 * @func */ function getTime (ms) { var d = new Date(); return ms? d.getHours().toNDigits() + ":" + d.getMinutes().toNDigits() + ":" + d.getSeconds().toNDigits() + "." + d.getMilliseconds().toNDigits(): d.getHours().toNDigits() + ":" + d.getMinutes().toNDigits() + ":" + d.getSeconds().toNDigits() } /** * @description Get the date * @param {boolean} [short=false] Shortness (end.g: 26May2016 instead of 26/05/2016 * @returns {string} Date * @since 1.0 * @func */ function getDate (short) { var m = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], d = new Date(); return short? d.getDate().toNDigits() + m[d.getMonth()] + d.getUTCFullYear(): d.toLocaleDateString(); } /** * @description Get the timestamp * @param {boolean} [readable=false] Readable (dd/MM/yyyy hh:mm:ss.xxx) or not (ddMMM-hh-mm-ss) * @returns {string} Timestamp * @since 1.0 * @see module:essence~getDate * @see module:essence~getTime * @func */ function getTimestamp (readable) { return readable? getDate() + " " + getTime(true): getDate(true) + "-" + getTime().replace(/:/g, "-") } //noinspection JSUnusedGlobalSymbols /** * @description Date to textual format * @param {Date} d Date * @returns {string} Textual format (in dd/mm/yyyy) * @see module:essence~txt2date * @func * @since 1.1 * @throws {Error} d isn't a Date */ function date2txt (d) { if (!isType(d, "Date")) throw new Error("$d is not a Date object"); return d.getDate().toNDigits() + "/" + (d.getMonth() + 1).toNDigits() + "/" + d.getFullYear(); } //noinspection JSUnusedGlobalSymbols /** * @description Textual date (in dd/mm/yyyy) to Date * @param {string} txt Textual date * @returns {Date} Date * @see module:essence~date2txt * @func * @since 1.1 */ function txt2date (txt) { var p = txt.split("/"); return new Date(p[2], p[1] - 1, p[0]); } /** * @description Display the date and at time at a particular place * @param {string} [id] ID of the element to be used * @returns {undefined} * @since 1.0 * @func */ function dateTime (id) { var date = new Date(); var year = date.getFullYear(), month = date.getMonth(); var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; var d = date.getDate(), day = date.getDay(), h = date.getHours(); var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; var tt = "", GMT = date.getTimezoneOffset(), m, s; if (h < 10) h = "0" + h; m = date.getMinutes(); if (h > 12) { h -= 12; tt = "PM"; } else tt = "AM"; if (m < 10) m = "0" + m; s = date.getSeconds(); if (s < 10) s = "0" + s; GMT = (GMT >= 0)? "GMT+" + GMT: "GMT-" + GMT; var result = "We're " + days[day] + " " + d + " " + months[month] + " " + year + " and it'ss" + h + ":" + m + ":" + s + " " + tt + " " + GMT; $e("#" + id || "body").write(result); setTimeout("dateTime(\"" + id + "\");", 1000); } /** * @description Kinch's week day finder * @param {string} d Date * @author Daniel "Kinch" Sheppard * @returns {string} Week day * @since 1.0 * @func */ function dayOfWeek (d) { var day = parseInt(d.split("/")[0]), m = [0, 3, 3, 6, 1, 4, 6, 2, 5, 0, 3, 5], days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]; //Months from Jan to Dec var y = parseInt(d.split("/").last()) % 100 + Math.floor(d.split("/").last() / 4), c = Math.floor(d.split("/").last() / 100 % 4), cCode; if (c === 0) cCode = 6; else if (c === 1) cCode = 4; else if (c === 2) cCode = 2; else cCode = 0; return days[(day + m[parseInt(d.split("/")[1]) - 1] + y + cCode) % 7] } /** * @description Date to number * @param {string} [d=getDate()] Date * @returns {number} Number * @see module:essence~num2date * @since 1.0 * @func */ function date2num (d) { if(!d) d = getDate(); var p = d.split("/"); return parseFloat(parseFloat(p[2] + "." + p[1]).toNDec() + "0" + p[0]); } /** * @description Number to date * @param {number} n Number * @returns {string} Date * @see module:essence~date2num * @since 1.0 * @func */ function num2date (n) { var p = n.toString().split("."); return p[1].get(3) + "/" + p[1].get(-3) + "/" + p[0]; } //noinspection JSUnusedGlobalSymbols /** * @description Date difference calculator.<br /> * Source: {@link http://www.htmlgoodies.com/html5/javascript/calculating-the-difference-between-two-dates-in-javascript.html} * @param {Date} [from=new Date()] Starting date * @param {Date} to Ending date * @param {string} [part="d"] Part * @param {boolean} [round=false] Rounding flag * @returns {number} Difference * @func * @since 1.1 */ function dateDiff (from, to, part, round) { if (!from) from = new Date(); var divideBy = { //in ms y: 959230512000, m: 2628028800.0000005, w: 604800000, d: 86400000, h: 3600000, min: 60000, s: 1000, ms: 1 }; return round? Math.round( (to - from) / divideBy[part || "d"]): (to - from) / divideBy[part]; } //noinspection JSUnusedGlobalSymbols /** * @description Date (days/weeks/months/years) to seconds * @param {number} [d=0] Days * @param {number} [w=0] Weeks * @param {number} [m=0] Months * @param {number} [y=0] Years * @returns {number} Seconds * @func * @since 1.1 * @see module:essence~s2date */ function date2s (d, w, m, y) { return (d || 0) * 86400 + (w || 0) * 7 * 86400 + (m || 0) * 30.417 * 86400 + (y || 0) * 365 * 30.417 * 86400; } //noinspection JSUnusedGlobalSymbols /** * @description Seconds to days/weeks/months/years * @param {number} s Seconds * @param {string} [what="d"] Option * @returns {number} Result * @func * @since 1.1 * @see module:essence~date2s */ function s2date (s, what) { if (!what) what = "d"; switch (what.toLowerCase()[0]) { case "width": return s / (7 * 86400); //Weeks case "m": return s / (30.417 * 86400); //Months case "y": return s / (365 * 30.417 * 86400); //Years default: return s / 86400; //Days } } /** * @description Generate a string * @param {number} len Length * @param {Object} filter Filter (specific character, no uppercase/lowercase, cumulative/no (sensitive) repeat) * { * name: "specificChar/noUpperCase/noLowerCase/cumulativeRepeat/cumulativeSensitiveRepeat/noRepeat", * character: * * } * @returns {string} Generated string * @since 1.0 * @func */ function genStr (len, filter) { //Generate a string var str = "", az = asciiTable("a-z"), AZ = asciiTable("A-Z"), zero9 = range(9), commonChar = ["&", "~", "\"", "#", "\'", "{", "[", "(", "-", "|", "`", "_", "\\", "^", "@", ")", "]", " + ", "=", "}", " % ", " * ", "?", ",", ";", ".", "/", ":", "!", " "], charlist; charlist = az.concat(AZ, zero9, commonChar); var c = "", i = 0; while (str.length < len) { c = charlist.rand(); if (filter.name === "specificChar") { //noinspection JSUnresolvedVariable while(c === filter.character) c = charlist.rand(); }else if (filter.name === "noUpperCase") { c = c.toLowerCase(); }else if (filter.name === "noLowerCase") { c = c.toUpperCase(); }else if (filter.name === "cumulativeRepeat") { while(c == str[i-1]) c = charlist.rand(); }else if (filter.name === "cumulativeSensitiveRepeat") { while(c === str[i-1]) c = charlist.rand(); }else if (filter.name === "noRepeat") { charlist = charlist.remove(); c = charlist.rand(); } str += c; i++; } if (str.length < len) str += charlist.rand(); else if (str.length > len) str = str.slice(0, len + 1); if (str === "") genStr(len, filter); //May cause overflows return str } /** * @description Make a $len^$dim array * @param {number} len Length * @param {number} dim Dimension * @param {*} [fill=false] Content to be used to fill * @returns {Array} Array * @since 1.0 * @func * @throws {Error} Invalid/unsupported dimension */ function mkArray (len, dim, fill) { //Arr.fill(new Array(...).fill(...)) is already there var arr = []; if (dim === 1) { if (isNon(fill)) arr = new Array(len); else { for(var i = 0; i < len; i++) arr[i] = fill; } }else if (dim === 2) { if (isNon(fill)) { arr = new Array(len); for(i = 0; i < len; i++) arr[i] = new Array(len); } else { for (i = 0; i < len; i++) { arr[i] = new Array(len); for(var j = 0; j < len; j++) arr[i][j] = fill; } } }else if (dim === 3) { if (isNon(fill)) { arr = new Array(len); for (i = 0; i < len; i++) { arr[i] = new Array(len); for(j = 0; j < len; j++) arr[i][j] = new Array(len); } } else { for (i = 0; i < len; i++) { arr[i] = new Array(len); for (j = 0; j < len; j++) { arr[i][j] = new Array(len); for(var k = 0; k < len; k++) arr[i][j][k] = fill; } } } }else if (dim === 4) { if (isNon(fill)) { arr = new Array(len); for (i = 0; i < len; i++) { arr[i] = new Array(len); for (j = 0; j < len; j++) { arr[i][j] = new Array(len); for(k = 0; k < len; k++) arr[i][j][k] = new Array(len); } } } else { for (i = 0; i < len; i++) { arr[i] = new Array(len); for (j = 0; j < len; j++) { arr[i][j] = new Array(len); for (k = 0; k < len; k++) { arr[i][j][k] = new Array(len); for (var l = 0; l < len; l++) { arr[i][j][k][l] = fill; } } } } } } else throw new Error("Unvalid dimension. Only 1D-4D arrays can be made."); return arr } /** * @description Numerical array (like an n-puzzle) * @param {number} n Size of the array (matrix) * @param {number} [start=0] Starting number * @returns {number[]} Numerical array * @since 1.0 * @func */ function numArr (n, start) { //Like an n-puzzle var na = [], x = start || 0; for (var i = 0; i < n; i++) { na[i] = []; for(var j = 0; j < n; j++) na[i][j] = x++; } return na } /** * @description Swap two (proprietary) elements * @param {*} obj Object/first element to swap * @param {*} e1 First proprietary/second element to swap * @param {*} [e2] Second proprietary element to swap * @returns {Dict} Swapping result * @since 1.0 * @func */ function swap (obj, e1, e2) { //Swap two proprietary elements or two elements var tmp; if (e2) { //Affect the original object tmp = obj[e1]; obj[e1] = obj[e2]; obj[e2] = tmp; return obj } else { //Preserves the original object tmp = obj; obj = e1; e1 = tmp; return [obj, e1] } } /** * @description Make sure that $a and $b are of the same lengths and fill the empty spaces with $cr * @param {string|Array} a Element a * @param {string|Array} b Element b * @param {string} [cr=" "] Filling character * @returns {Array} Resized elements * @since 1.0 * @func * @throws {Error} a and b must be iterable */ function toSameLength (a, b, cr) { if (!a.isIterable() || !b.isIterable()) throw new Error("invalid length equality operation on non-iterable objects"); if (!cr) cr = " "; if (a.length > b.length) { for(var i = b.length; i < a.length; i++) isType(b[i], "String")? b += cr: b.push(cr); } else if (a.length < b.length) { for(i = a.length; i < b.length; i++) isType(a[i], "String")? a += cr: a.push(cr); } return [a, b] } /** * @description Look for an element in a matrix * @param {*} x Element to look for * @param {Array} mtx Matrix * @param {boolean} [toCoord=false] Coordinate representation * @returns {Nums} Position * @since 1.0 * @func */ function lookfor (x, mtx, toCoord) { for (var i = 0; i < mtx.length; i++) { for (var j = 0; j < mtx[i].length; j++) { if (mtx[i][j] === x || mtx[i][j].equals(x)) return toCoord? [j, i]: [i, j]; //I is the row number and j the column which oppose j being the x-coord and i the y-coord } } return -1 } /** * @description List of keys of a map (like keys in ES6) * @param {Array} map Map * @param {boolean} [propOnly=false] Properties only * @returns {Array} Key list * @since 1.0 * @func */ function keyList (map, propOnly) { var list = []; //ES6 only: if (propOnly) return keys(map) if (propOnly) { for (var key in map) { if (map.hasOwnProperty(key)) list.push(key); } } else for(key in map) list.push(key); return list } /** * @description List of values of a map (like values in ES6) * @param {Array} map Map * @param {boolean} [propOnly=false] Properties only * @returns {Array} Value list * @since 1.0 * @func */ function valList (map, propOnly) { var list = []; //ES6 only: if (propOnly) return values(map) if (propOnly) { for (var key in map) { if (map.hasOwnProperty(key)) list.push(map[key]); } }else for(key in map) list.push(map[key]); return list } /** * @description Same as keyList() but returns an HTML table * @param {Array} map Map * @param {boolean} [propOnly=false] Properties only * @returns {string} HTML table * @since 1.0 * @func */ function keyTable (map, propOnly) { //Same as above but in the form of the HTML table var table = "<table cellspacing=0><caption>KeyTable" + ((map.name || map.title)? ": <i>" + (map.name || map.title) + "</i>": "") + "</caption><tr><th>Key</th><th>Value</th></tr>"; for (var key in map) { table += (propOnly && map.hasOwnProperty(key))? "<tr><td>" + key + "</td><td>" + map[key] + "</td></tr>": "<tr><td>" + key + "</td><td>" + map[key] + "</td></tr>"; } return table + "</table>" } /** * @description Character to hexadecimal * @param {string} c Character * @returns {string} Hexadecimal code * @since 1.0 * @func */ function char2hex (c) { return conv(c.charCodeAt(0), 10, 16) } /** * @description Hexadecimal to character * @param {NumberLike} h Hexadecimal code * @returns {string} Character * @since 1.0 * @func */ function hex2char (h) { return String.fromCharCode(conv(h, 16)) } /** * @description Character to binary * @param {string} c Character * @returns {string} Binary code * @since 1.0 * @func */ function char2bin (c) { return conv(c.charCodeAt(0), 10, 2) } /** * @description Binary to character * @param {NumberLike} b Binary code * @returns {string} Character * @since 1.0 * @func */ function bin2char (b) { return String.fromCharCode(conv(b, 2)) } /** * @description Text to number converter * @param {string} txt Text * @param {number} [base=10] Base * @returns {string} Converted text * @since 1.0 * @func */ function txt2num (txt, base) { var res = ""; for (var i = 0; i < txt.length; i++) res += conv(txt.charCodeAt(i), 10, base || 10) + " "; return res.trimRight(); } /** * @description Number to text * @param {NumberLike} num Number * @param {number} [base=10] Base * @returns {string} Converted number * @since 1.0 * @func */ function num2txt (num, base) { var res = ""; for (var i = 0; i < num.split(" ").length; i++) res += String.fromCharCode(conv(num.split(" ")[i], base || 10)); return res; } /** * @description Time how long an action took * @param {function(*)} act Action * @param {*} [params] Parameters * @param {string} [pref="auto"] Preference (auto/none, ms/millisec, start/sec) * @returns {string} Time * @since 1.0 * @func */ function timeUp (act, params, pref) { var t1 = new Date(); t1 = (t1.getMinutes() * 60 + t1.getSeconds()) * 1000 + t1.getMilliseconds(); act(params); var t2 = new Date(); t2 = (t2.getMinutes() * 60 + t2.getSeconds()) * 1000 + t2.getMilliseconds(); if (isNon(pref) || pref.slice(0, 4).toLowerCase() === "auto" || pref.slice(0, 4).toLowerCase() === "none") return (t2 - t1 > 1000)? (t2 - t1) / 1000 + "start": (t2 - t1) + "ms"; else if (pref.toLowerCase() === "ms" || pref.slice(0, 8).toLowerCase() === "millisec") return (t2-t1) + "ms"; else return (t2-t1) / 1000 + "s"; } /** * @description Time how long a callback took * @param {Function} cb Callback * @param {*} [params] Parameters * @returns {number} Time * @since 1.1 * @func */ function time (cb, params) { var t1 = new Date().getTime(); cb(params); var t2 = new Date().getTime(); return t2 - t1; } /** * @description Pause the JS execution for a bit and place the callback (if specified) at the end of the execution queue (parsed by the browser which also includes the UI). * A neat wait of keeping the code passed in the parameter to be executed in order of execution (instead of being pushed at the end of the execution queue), is to pass a command/instruction instead of a function (with that command/instructions). * @param {Function} [cb=$f] Callback * @returns {undefined} * @since 1.1 * @func */ function wait (cb) { setTimeout(cb || $f, 0); } /** * @description Time how long an asynchronous callback took * @param {Function} cb Callback * @param {*} [params] Parameters * @returns {number} Time * @since 1.1 * @func */ function asyncTime (cb, params) { var t1 = new Date().getTime(), done = "^no", maybe; maybe = cb(params); do { wait(); done = maybe; } while(maybe != undefined || done == "^no"); var t2 = new Date().getTime(); return t2 - t1; }
33.435337
1,378
0.626941
75a876296782bdd3c7238e000ea451f058cfea97
336
js
JavaScript
app-84-kokyakukanri/src/backend/utils.js
Lorenzras/kintone-customize
b875b3d7a27eba11243b9308ee052d65d4ba011d
[ "MIT" ]
null
null
null
app-84-kokyakukanri/src/backend/utils.js
Lorenzras/kintone-customize
b875b3d7a27eba11243b9308ee052d65d4ba011d
[ "MIT" ]
null
null
null
app-84-kokyakukanri/src/backend/utils.js
Lorenzras/kintone-customize
b875b3d7a27eba11243b9308ee052d65d4ba011d
[ "MIT" ]
null
null
null
import {updateAgents} from './setName'; // eslint-disable-next-line import/prefer-default-export export const excludedShopQuery = (shopField = '店舗名') => [ 'すてくら', 'なし', '本部', 'システム管理部', '本社', '買取店', ] .map((item) => `${shopField} not like "${item}"`) .join(' and '); export const initProcess = () => { updateAgents(); };
22.4
57
0.604167
75a8abf418b84662a42428e80b88e963cb433dbb
487
js
JavaScript
js_notes/hello-koa/controllers/index.js
ftconan/javascript
6e6a72e268fcef2f6d8c1df479cc86f1f1aa70f5
[ "MIT" ]
null
null
null
js_notes/hello-koa/controllers/index.js
ftconan/javascript
6e6a72e268fcef2f6d8c1df479cc86f1f1aa70f5
[ "MIT" ]
3
2020-02-14T02:16:47.000Z
2020-02-16T03:25:48.000Z
js_notes/hello-koa/controllers/index.js
ftconan/javascript
6e6a72e268fcef2f6d8c1df479cc86f1f1aa70f5
[ "MIT" ]
null
null
null
/* @author: magician @file: index.js @date: 2020/2/13 */ 'use strict'; module.exports = { 'GET /': async (ctx, next) => { ctx.render('index.html'); } }; // module.exports = { // 'GET /': async (ctx, next) => { // let user = ctx.state.user; // // if (user) { // ctx.render('room.html', { // user: user // }); // } else { // ctx.response.redirect('/signin'); // } // } // };
18.037037
48
0.406571
75a9908cb9a92a7f5ce8faf2ed21359ee2a097bb
375
js
JavaScript
src/components/ProductsNav/productsNav.js
SreckoJarcevic/gatsby
9a215947506d90540522b0b257c5832b72bfd71a
[ "MIT" ]
null
null
null
src/components/ProductsNav/productsNav.js
SreckoJarcevic/gatsby
9a215947506d90540522b0b257c5832b72bfd71a
[ "MIT" ]
6
2021-03-09T08:02:26.000Z
2022-02-18T02:16:05.000Z
src/components/ProductsNav/productsNav.js
SreckoJarcevic/gatsby
9a215947506d90540522b0b257c5832b72bfd71a
[ "MIT" ]
null
null
null
import React from "react" import { Link } from "gatsby" import styles from "./productsNav.module.css" const productsNav = () => { return ( <div className={styles.Nav}> <Link to="ehr">EHR</Link> <Link to="pms">PMS</Link> <Link to="check-in-kiosk">KIOSK</Link> <Link to="patient-portal">PORTAL</Link> </div> ) } export default productsNav
22.058824
45
0.624
75a9e8a108e1daf22fc2fe2b0a9cfd39f7e3f1ce
729
js
JavaScript
server/components/watson-tts-component/watson-tts-loader.js
with-watson/watson-services-pipeline-app
be235584e340b1474530ba82b50b5ebe77663817
[ "Apache-2.0" ]
null
null
null
server/components/watson-tts-component/watson-tts-loader.js
with-watson/watson-services-pipeline-app
be235584e340b1474530ba82b50b5ebe77663817
[ "Apache-2.0" ]
null
null
null
server/components/watson-tts-component/watson-tts-loader.js
with-watson/watson-services-pipeline-app
be235584e340b1474530ba82b50b5ebe77663817
[ "Apache-2.0" ]
null
null
null
'use strict' module.exports = async function (app, options) { if (!app.models['WatsonTTS']) await defineWatsonTTS() function defineWatsonTTS() { return new Promise((resolve, reject) => { // Create a Model Constructor using the json definition const WatsonTTSConstructor = app.registry.createModel(require('./models/watson-tts.json')) // Create a Model from the Model Constructor const watsonTTS = app.model(WatsonTTSConstructor, { dataSource: null, public: true }) // Instantiate the Remote Model implementation const watsonTTSRemote = require('./models/watson-tts')(watsonTTS) resolve(watsonTTSRemote) }) } }
38.368421
102
0.641975
75aa1d9152f9fdefa4c0ff2bbff3f65669243bb5
9,225
js
JavaScript
src/scripts/index.js
navisayslisten/AceEditorVTT
1af741d982fdf98536c2e8bdff654ccc8a083972
[ "MIT" ]
1
2020-11-27T02:46:06.000Z
2020-11-27T02:46:06.000Z
src/scripts/index.js
navisayslisten/AceEditorVTT
1af741d982fdf98536c2e8bdff654ccc8a083972
[ "MIT" ]
2
2020-11-27T02:45:58.000Z
2021-10-03T16:05:57.000Z
src/scripts/index.js
navisayslisten/AceEditorVTT
1af741d982fdf98536c2e8bdff654ccc8a083972
[ "MIT" ]
null
null
null
import { themes } from "./ace-themes"; const ace = require("ace-builds/src-min-noconflict/ace"); require("ace-builds/webpack-resolver"); require("ace-builds/src-min-noconflict/ext-language_tools"); require("ace-builds/src-min-noconflict/ext-error_marker"); ace.config.set("basePath", "modules/AceEditorVTT/scripts/"); const furnaceMessage = "Ace Editor VTT is not compatible with Furnace. Ace is now disabled, in favor of Furnace."; let aceConfig; let editor; let configElement; Hooks.once("ready", function () { furnaceUICheck(); }); Hooks.on("init", function () { game.AceEditorVTT = {}; CONFIG.debug.AceEditorVTT = false; AceSettings.init(); }); Hooks.on("closeSettingsConfig", function () { updateEditor(); }); Hooks.on("renderMacroConfig", function (config) { aceConfig = config; configElement = config.element; setupAceUI(); configElement.find(".ace-editor-button").on("click", (event) => { event.preventDefault(); if (furnaceUICheck()) { editor.container.remove(); editor.destroy(); return; } if (configElement.find(".ace-editor").css("display") === "none") { updateEditor(); configElement.find(".command label").css("display", "none"); configElement .find('.command textarea[name="command"]') .css("display", "none"); configElement.find(".ace-editor").css("display", ""); editor.setValue( configElement.find('.command textarea[name="command"]').val(), -1 ); editor.resize(); editor.renderer.updateFull(true); } else { configElement.find(".command label").css("display", ""); configElement .find('.command textarea[name="command"]') .css("display", ""); configElement.find(".ace-editor").css("display", "none"); } }); configElement.find('.command textarea[name="command"]').css("display", ""); configElement.find(".ace-editor").css("display", "none"); editor.getSession().on("change", () => { configElement .find('textarea[name="command"]') .val(editor.getSession().getValue()); }); editor.commands.addCommand({ name: "Save", bindKey: { win: "Ctrl-S", mac: "Command-S" }, exec: () => configElement.find("form.editable").trigger("submit"), }); editor.commands.addCommand({ name: "Execute", bindKey: { win: "Ctrl-E", mac: "Command-E" }, exec: () => configElement.find("button.execute").trigger("click"), }); // watch for resizing of editor new ResizeObserver(() => { editor.resize(); editor.renderer.updateFull(true); }).observe(editor.container); createMacroConfigHook(config.id, editor); }); function setupAceUI() { const settings = new AceSettings().getSettingsData(); // If not enabled, or if Furnace is enabled, bail! if (!settings.enabled) return configElement.find(".ace-editor").css("display", "none"); if (furnaceUICheck()) return; configElement .find("div.form-group.stacked.command") .append( `<div class="ace-editor" id="aceEditor-${aceConfig.object.id}"></div>` ); if (!settings.fontSize instanceof Number || settings.fontSize <= 0) { console.error(`Invalid fontSize: ${settings.fontSize}`); return; } configElement.find('.command textarea[name="command"]').css("display", ""); var relativeElement = configElement.find( ".window-content .form-group:nth-of-type(2)" ); $( '<div class="form-group stacked" style="align-self: flex-end;"><button type="button" class="ace-editor-button" title="Toggle Ace Editor" name="editorButton" style="min-width: 50px;width: auto;padding: 0 16px;border-radius: 3px;"><i class="fas fa-terminal"></i> Toggle ACE</button></div>' ).insertAfter(relativeElement); editor = ace.edit(`aceEditor-${aceConfig.object.id}`); editor.getSession().setUseWorker(settings.errorCheck); editor.setOptions({ mode: "ace/mode/javascript", fontSize: `${settings.fontSize}pt`, showPrintMargin: false, foldStyle: "markbegin", enableBasicAutocompletion: settings.autoComplete, enableSnippets: settings.autoComplete, enableLiveAutocompletion: settings.autoComplete, minLines: 15, wrap: settings.lineWrap, theme: `ace/theme/${settings.theme}`, }); } function createMacroConfigHook(id, editor) { Hooks.once("closeMacroConfig", function (aceConfig) { if (id === aceConfig.id) { editor.destroy(); editor.container.remove(); } else { createMacroConfigHook(id, editor); } }); } function furnaceUICheck() { const aceEnabled = game.settings.get("AceEditorVTT", "enabled"); if (!aceEnabled) return; if ( $("div.furnace-macro-expand").length > 0 || $('link[href*="furnace"]').length > 0 ) { ui.notifications.error(furnaceMessage); console.error(furnaceMessage); disableAce(); $("a.close").trigger("click"); return true; } return false; } function disableAce() { game.settings .set("AceEditorVTT", "enabled", false) .then((r) => console.debug(`AEVTT now set to ${r}`)); } function updateEditor() { const enabled = game.settings.get("AceEditorVTT", "enabled"); if (!enabled) { editor.destroy(); editor.container.remove(); configElement.find('.command textarea[name="command"]').css("display", ""); configElement.find(".ace-editor").css("display", "none"); configElement.find(".ace-editor-button").css("display", "none"); return; } else { } const settings = new AceSettings().getSettingsData(); editor.getSession().setUseWorker(settings.errorCheck); editor.setOptions({ mode: "ace/mode/javascript", fontSize: `${settings.fontSize}pt`, showPrintMargin: false, foldStyle: "markbegin", enableBasicAutocompletion: settings.autoComplete, enableSnippets: settings.autoComplete, enableLiveAutocompletion: settings.autoComplete, minLines: 15, wrap: settings.lineWrap, theme: `ace/theme/${settings.theme}`, }); editor.renderer.updateFull(true); } class AceSettings extends FormApplication { constructor(object = {}, options) { super(object, options); } static get defaultOptions() { return { ...super.defaultOptions, height: "auto", title: "AceEditorVTT", width: 600, classes: ["AceEditorVTT", "settings"], tabs: [ { navSelector: ".tabs", contentSelector: "form", initial: "name", }, ], submitOnClose: true, }; } static init() { game.settings.register("AceEditorVTT", "enabled", { name: "Enable Ace Editor for macros.", type: Boolean, hint: "If disabled you will only see the default macro editor.", scope: "client", config: true, default: true, }); game.settings.register("AceEditorVTT", "autoComplete", { name: "Enable code autocomplete feature.", hint: "Will allow auto-complete features for Javascript. Ctrl+Spacebar shortcut will activate it manually.", type: Boolean, scope: "client", config: true, default: false, }); game.settings.register("AceEditorVTT", "errorCheck", { name: "Enable Javascript error checking.", hint: "Errors will show up for chat macros too; these can be ignored. Or disable this feature.", type: Boolean, scope: "client", config: true, default: false, }); game.settings.register("AceEditorVTT", "lineWrap", { name: "Enable line wrap", type: Boolean, scope: "client", config: true, default: true, }); game.settings.register("AceEditorVTT", "theme", { name: "Set your Ace Editor color/style theme.", type: String, hint: "Themes can be found at https://github.com/ajaxorg/ace/tree/master/lib/ace/theme. " + "Default is solarized_dark", scope: "client", config: true, choices: themes, default: "solarized_dark", }); game.settings.register("AceEditorVTT", "fontSize", { name: "Set the Ace Editor font size.", type: Number, scope: "client", config: true, default: 11, }); } getSettingsData() { return { enabled: game.settings.get("AceEditorVTT", "enabled"), autoComplete: game.settings.get("AceEditorVTT", "autoComplete"), errorCheck: game.settings.get("AceEditorVTT", "errorCheck"), lineWrap: game.settings.get("AceEditorVTT", "lineWrap"), fontSize: game.settings.get("AceEditorVTT", "fontSize"), theme: game.settings.get("AceEditorVTT", "theme"), }; } _getHeaderButtons() { let btns = super._getHeaderButtons(); btns[0].label = "Save & Close"; return btns; } getData(options = {}) { let data = super.getData(); data.settings = this.getSettingsData(); return data; } activateListeners(html) { super.activateListeners(html); updateEditor(); } _updateObject(ev, formData) { const data = expandObject(formData); for (let [key, value] of Object.entries(data)) { game.settings .set("AceEditorVTT", key, value) .then((r) => console.debug(`${vtt} | Set Ace Editor setting: ${key} to ${value}`) ); } } }
29.193038
291
0.635447
75ab3aae4654e06289cd23367335c36f07374213
2,269
js
JavaScript
commands/role.js
QuantumToast/shardbotpublic
c3e37363160822339ac1e524502f40325d7ae9e1
[ "MIT" ]
null
null
null
commands/role.js
QuantumToast/shardbotpublic
c3e37363160822339ac1e524502f40325d7ae9e1
[ "MIT" ]
1
2021-04-22T21:25:44.000Z
2021-04-22T21:25:44.000Z
commands/role.js
QuantumToast/shardbotpublic
c3e37363160822339ac1e524502f40325d7ae9e1
[ "MIT" ]
3
2021-07-22T22:27:16.000Z
2021-11-07T11:58:40.000Z
const roleList = { ["trade"]: "775135243936989224", ['manhattan']: '772177728363429939', ['staten']: '772177684406730783', ['bronx']: '772177617767759874', ['brooklyn']: '772177655070982154', ['queens']: '775147647215992852', ['survey']: '783075338245767168', ['hero']: '783121530375897089', ['villain']: '783121635037020211', ['cluster']: '789362434925133824' } module.exports.run = async (client, message, args) => { //console.log(message.guild.roles); if (args[0]){ if (roleList[args[0].toLowerCase()]){ const role = message.guild.roles.cache.get(roleList[args[0].toLowerCase()]); //var member = message.guild.mem //add role if(message.member.roles.cache.get(role.id)){ message.member.roles.remove(role).catch(console.error); message.reply(`Removed ${args[0].toLowerCase()} role.`) } else{ const teamData = await client.teamsDB.get(`${message.author.id}`,null); //checking villain and hero roles, each requires 2k rep if (args[0].toLowerCase()=='hero' && (!teamData || teamData.reputation < 1000)){ message.reply("You need 1,000 reputation to have the hero role.") return; } if (args[0].toLowerCase()=='villain' && (!teamData || teamData.reputation > -1000)){ message.reply("You need -1,000 reputation to have the villain role.") return; } message.member.roles.add(role).catch(console.error); message.reply(`Assigned ${args[0].toLowerCase()} role.`) } }else{ return; } }else{ message.reply(module.exports.help.description) return; } } module.exports.help = { name: "role", description: "Toggles optional roles for Shardbot server.\n"+ "`hero / villain / survey /trade / manhattan / staten / bronx / brooklyn / queens `" } module.exports.requirements = { userPerms: [], clientPerms: [], ownerOnly: false, shardHubOnly: true, }
36.596774
101
0.54253
75ab55600314e4d86899117cf6b3f72313f4acf9
2,474
js
JavaScript
main/app/client/templates/hmo_plan_change_request/hmo_plan_change_request_entry/hmo_plan_change_request_entry.js
c2gconsulting/bulkpay
224a52427f80a71f66613c367a5596cbd5e97294
[ "MIT" ]
null
null
null
main/app/client/templates/hmo_plan_change_request/hmo_plan_change_request_entry/hmo_plan_change_request_entry.js
c2gconsulting/bulkpay
224a52427f80a71f66613c367a5596cbd5e97294
[ "MIT" ]
4
2020-04-29T23:02:58.000Z
2020-12-18T12:43:52.000Z
main/app/client/templates/hmo_plan_change_request/hmo_plan_change_request_entry/hmo_plan_change_request_entry.js
c2gconsulting/bulkpay
224a52427f80a71f66613c367a5596cbd5e97294
[ "MIT" ]
1
2017-11-19T10:20:51.000Z
2017-11-19T10:20:51.000Z
/*****************************************************************************/ /* HmoPlanChangeRequestEntry: Event Handlers */ /*****************************************************************************/ Template.HmoPlanChangeRequestEntry.events({ 'click #edit': (e,tmpl) => { Modal.show('HmoPlanChangeRequestCreate', tmpl.data); }, 'click #delete': (e,tmpl) => { swal({ title: "Are you sure you want to delete it?", text: "You will not be able to recover it!", type: "warning", showCancelButton: true, confirmButtonColor: "#DD6B55", confirmButtonText: "Yes, delete it!", closeOnConfirm: false }, function(){ let docId = tmpl.data._id; Meteor.call("hmoPlanChangeRequests/delete", docId, function(err,res){ if(!err){ swal("Deleted!", `Request Deleted`, "success"); } else { swal("Error!", err.reason, "error"); } }); }); } }); /*****************************************************************************/ /* HmoPlanChangeRequestEntry: Helpers */ /*****************************************************************************/ Template.HmoPlanChangeRequestEntry.helpers({ 'active': (status) => { if(status === "Open") return "warning"; if(status === "Approved") return "success"; if(status === "Rejected") return "danger"; }, 'name': (id) => { let leave = HmoPlans.findOne({_id: id}); if(leave) return leave.name; }, 'canEdit': ()=> { let status = Template.instance().data.approvalStatus; if(status){ return status !== "Approved"; } }, 'click view': () => { }, 'toTwoDecimalPlaces': function(theNumber) { return theNumber ? theNumber.toFixed(2) : '' } }); /*****************************************************************************/ /* HmoPlanChangeRequestEntry: Lifecycle Hooks */ /*****************************************************************************/ Template.HmoPlanChangeRequestEntry.onCreated(function () { }); Template.HmoPlanChangeRequestEntry.onRendered(function () { }); Template.HmoPlanChangeRequestEntry.onDestroyed(function () { });
33.890411
85
0.417947
75acaf0074fe301a7eb510585ae6af7ebd3fd4c1
7,522
js
JavaScript
hook/remote-deployment.js
ewanharris/ti.windows-remote-deployment
882be5bcfe19eceff23029a2ead90890fe59440b
[ "Apache-2.0" ]
null
null
null
hook/remote-deployment.js
ewanharris/ti.windows-remote-deployment
882be5bcfe19eceff23029a2ead90890fe59440b
[ "Apache-2.0" ]
3
2017-09-05T12:53:30.000Z
2017-09-05T13:02:22.000Z
hook/remote-deployment.js
ewanharris/ti.windows-remote-deployment
882be5bcfe19eceff23029a2ead90890fe59440b
[ "Apache-2.0" ]
null
null
null
/** * This hook deploys the built application to a remote device * * @copyright * Copyright (c) 2017 by Ewan Harris. All Rights Reserved. */ 'use strict'; // TODO: // - Break winappdeploycmd stuff out into a seperate file // - Add prompting for code in this hook // - Figure out if logging is possible // - Allow storage of IPs? i.e. when we pair add to a 'database' 'use strict'; const exec = require('child_process').exec; const fs = require('fs'); const path = require('path'); const utils = require('../utils'); let appxLocation; let deployCmd; let deviceIP; let fields; let windowslib; exports.id = 'com.eh.remote-deployment'; /** The Titanium CLI version that this hook is compatible with */ exports.cliVersion = '>=3.2'; /** * Initialize the hook. * * @param {Object} logger - The logger instance * @param {Object} config - The CLI config object * @param {CLI} cli - The CLI instance * @param {Object} appc - The node-appc library */ exports.init = function init(logger, config, cli, appc) { utils.injectSDKModulePath(cli.env.getSDK().path); windowslib = require('windowslib'); fields = require('fields'); // Configures our little batch of options cli.addHook('build.windows.config', function (data, finished) { // We don't need the extra logic here as Windows support wasn't in 3.2.1 const r = data.result[1] || {}; r.flags || (r.flags = {}); r.flags['remote-deploy'] = { default: false, desc: 'enable remote deployment' }; r.options || (r.options = {}); r.options.ip = { default: null, desc: 'Device IP address' }; finished(null, data); }); cli.addHook('build.pre.construct', function(data, finished) { if(cli.argv['remote-deploy']) { cli.argv['build-only'] = true; } finished(); }); /** * General thoughts on the structure of the plugin * - Get the target, use it to determine win.ARM vs win10.x86 * - Get the build dir look get the location of the .appxbundle * - Maybe pull the app id? Then we can look up whether it is installed and determine whether to uninstall first? * - Install the app * - Handle any potential mess */ cli.on('build.post.compile', function(data, finished) { if (cli.argv['remote-deploy']) { cli.argv['build-only'] = true; // Performs the setup functionality // 1. Obtain the appxbundle location // 2. Obtain the winappdeploycmd path const setup = [ new Promise((resolve, reject) => { const appNameRegex = new RegExp(cli.tiapp.name, 'i'); const appVerRegex = new RegExp(cli.tiapp.name + '_(\\d+\\.*){4}_(Test|Debug_Test)', 'i'); const target = cli.argv['T'] || cli.argv.target; const dirName = target === 'wp-device' ? 'win10.ARM' : 'win10.x86'; // We're only gonna go to the AppxPackages, from there it's gonna be a minefield // to guess the path so we'll just do some further work from there. logger.trace(`Project type is ${dirName}`); const projectDir = cli.argv['project-dir'] || cli.arg['d']; let appxLookupPath = path.join(projectDir, 'build', 'windows', dirName, 'AppPackages'); logger.trace(`Looking for ${appxLookupPath}`); if (!fs.existsSync(appxLookupPath)) { return finished(new Error('Cannot find the AppPackages dir, please ensure you\'re using --win-sdk 10.0')) } const appNameDir = fs.readdirSync(appxLookupPath).filter(item => appNameRegex.test(item)); logger.trace(`${appxLookupPath} contents are ${appNameDir}`); appxLookupPath = path.join(appxLookupPath, appNameDir[0]); logger.trace(`Looking for ${appxLookupPath}`); const appVerDir = fs.readdirSync(appxLookupPath).filter(item => appVerRegex.test(item)); logger.trace(`${appxLookupPath} contents are ${appVerDir}`); appxLookupPath = path.join(appxLookupPath, appVerDir[0]); logger.trace(`Looking for ${appxLookupPath}`); const appxName = fs.readdirSync(appxLookupPath).filter(item => path.extname(item) === '.appxbundle'); const appxLocation = path.join(appxLookupPath, appxName[0]); logger.trace(`Looking for ${appxLocation}`); if (fs.existsSync(appxLocation)) { return resolve(appxLocation); } else { return reject('Unable to find appxbundle') } }), new Promise((resolve, reject) => { windowslib.windowsphone.detect(function(err, results) { if (err) { return reject(err); } const cmd = `"${results['windowsphone']['10.0'].deployCmd}"`; deployCmd = cmd; return resolve(cmd); }); }) ]; // Performs some checks before we attempt to connect and install // 1. Were we given an ip // - If not, prompt // 2. Can we connect to the device with winappdeploycmd // - If not, prompt for a code, maybe with a link to pairing docs // 3. Is the app already installed on the device // - If yes, run uninstall first // 4. Install the app (finally); Promise.all(setup) .then(results => { return new Promise((resolve, reject) => { appxLocation = results[0]; if (!cli.argv['ip']) { logger.info('No device-ip argument specified, prompting for one'); fields.text({ title: 'What is the device-ip?', validate: function (value) { return !!value; } }).prompt(function (err, value) { if (err) { logger.error('There was an error!\n' + err); } else { deviceIP = value; resolve(deviceIP); } }); } else { deviceIP = cli.argv['ip']; resolve(deviceIP); } }); }).then(ip => { deviceIP = ip; return new Promise(function(resolve, reject) { exec(`${deployCmd} list -ip ${deviceIP}`, function(err, stdout, stderr) { if (err) { // Maybe we're not paired? Prompt for code with docs logger.warn('Was unable to connect to the specified IP'); logger.warn('Guiding through the pairing process'); logger.error('Please use ti pair-device as this is currently unimplemented'); process.exit(1); } else { // All good in the hood, lets move on... // after checking if the app is installed logger.info('Able to connect to the specified IP'); const id = cli.tiapp.windows.id || cli.tiapp.id; return resolve(utils.parseListData(stdout, id)); } }); }); }) .then(installed => { return new Promise((resolve, reject) => { if (installed) { // Uninstall the app logger.info('Application is already installed on device, uninstalling it first'); exec(`${deployCmd} uninstall -ip ${deviceIP} -file ${appxLocation}`, function(err, stdout, stderr) { if (err) { logger.error('Was unable to uninstall the application') return reject(err); } else { logger.info('App uninstalled'); return resolve(); } }); } else { return resolve(); } }); }) .then(() => { logger.info('Installing the application') exec(`${deployCmd} install -ip ${deviceIP} -file ${appxLocation}`, function(err, stdout, stderr) { if (err) { logger.error('Was unable to install the application') finished(); } else { logger.info('App installed'); finished(); } }); }).catch(err =>{ logger.error('Oh no something went wrong'); logger.error(err) logger.error('Maybe try logging an issue over here => link') }); } else { finished(); } }); };
33.580357
114
0.621643
75af4fffc2a0649e03db0146557f8d1c87912e8e
226
js
JavaScript
src/models/UserModel.js
12bedeveloper/MDModel
4395c91eb5e5b4c216fff4694acfce350686e13a
[ "MIT" ]
null
null
null
src/models/UserModel.js
12bedeveloper/MDModel
4395c91eb5e5b4c216fff4694acfce350686e13a
[ "MIT" ]
null
null
null
src/models/UserModel.js
12bedeveloper/MDModel
4395c91eb5e5b4c216fff4694acfce350686e13a
[ "MIT" ]
null
null
null
const { MDModel } = require('../db'); class UserModel extends MDModel { static getTotalRecords() { return this.collection.countDocuments(); } } UserModel.collectionName = 'user'; module.exports.UserModel = UserModel;
22.6
44
0.716814
75af8a4919fac9fc39018140b098e143706a0108
2,413
js
JavaScript
script/support.js
wooorm/udhr
a95ee9ad9212be588e260e99ef3276e41344fd19
[ "MIT" ]
16
2015-01-28T10:48:00.000Z
2021-06-30T09:02:57.000Z
script/support.js
wooorm/udhr
a95ee9ad9212be588e260e99ef3276e41344fd19
[ "MIT" ]
2
2015-12-16T15:50:05.000Z
2021-07-03T09:10:44.000Z
script/support.js
wooorm/udhr
a95ee9ad9212be588e260e99ef3276e41344fd19
[ "MIT" ]
3
2015-07-11T18:49:13.000Z
2016-08-14T16:11:16.000Z
// @ts-ignore remove when typed import zone from 'mdast-zone' import u from 'unist-builder' import {udhr} from '../index.js' var ohchrBase = 'https://www.ohchr.org/EN/UDHR/Pages/Language.aspx?LangID=' var isoBase = 'https://iso639-3.sil.org/code/' var locationBase = 'https://www.openstreetmap.org/#map=5/' var own = {}.hasOwnProperty export default function support() { return transformer } /** * @typedef {import('unist').Node} Node * @typedef {import('mdast').Root} Root * @typedef {import('mdast').TableCell} TableCell * @typedef {import('mdast').Link} Link * @typedef {import('mdast').PhrasingContent} PhrasingContent */ /** * @param {Root} tree */ function transformer(tree) { zone(tree, 'support', replace) } /** * @param {Node?} start * @param {unknown} _ * @param {Node?} end */ function replace(start, _, end) { return [start, table(), end] } function table() { var header = ['Name', 'BCP 47', 'OHCHR', 'ISO 639-3', 'Direction', 'Location'] var content = [ u( 'tableRow', header.map((d) => cell(d)) ) ] /** @type {string} */ var key for (key in udhr) { if (!own.call(udhr, key)) continue /** @type {string|PhrasingContent} */ var ohchr = udhr[key].ohchr /** @type {string|PhrasingContent} */ var iso = udhr[key].iso6393 /** @type {string|PhrasingContent} */ var loc = 'No' if (ohchr) { ohchr = u('link', {url: ohchrBase + ohchr}, [u('text', ohchr)]) } if (iso) { iso = u('link', {url: isoBase + iso}, [u('text', iso)]) } if (udhr[key].latitude || udhr[key].longitude) { loc = u( 'link', {url: locationBase + udhr[key].latitude + '/' + udhr[key].longitude}, [ u( 'text', [ udhr[key].latitude.toFixed(1), udhr[key].longitude.toFixed(1) ].join(', ') ) ] ) } content.push( u('tableRow', [ cell(udhr[key].name || ''), cell(udhr[key].bcp47 || ''), cell(ohchr || ''), cell(iso || ''), cell(udhr[key].direction || ''), cell(loc) ]) ) } return u('table', {align: []}, content) /** * @param {string|PhrasingContent} value * @returns {TableCell} */ function cell(value) { return u('tableCell', [ typeof value === 'string' ? u('text', value) : value ]) } }
22.137615
80
0.542478
75b0dec0ac7b6029f7bf9e5d918672484633d121
8,796
js
JavaScript
src/client/pages/PokemonPage/PokemonPage.js
12evgen/pokemon-app
0b994b8a80e49cfeadcc0898db89bc4e15b9d312
[ "MIT" ]
1
2021-01-25T10:21:57.000Z
2021-01-25T10:21:57.000Z
src/client/pages/PokemonPage/PokemonPage.js
12evgen/pokemon-app
0b994b8a80e49cfeadcc0898db89bc4e15b9d312
[ "MIT" ]
null
null
null
src/client/pages/PokemonPage/PokemonPage.js
12evgen/pokemon-app
0b994b8a80e49cfeadcc0898db89bc4e15b9d312
[ "MIT" ]
null
null
null
import React, { Component } from 'react' import PropTypes from 'prop-types' import { reaction } from 'mobx' import { inject, observer } from 'mobx-react' import { Helmet } from 'react-helmet' import { Spin, Progress, Icon, Tag } from 'antd' import { Link } from 'react-router-dom' import { parseId } from '../../utils/parseId' import './PokemonPage.scss' @inject('pokemonDetailsStore') @observer class PokemonPage extends Component { constructor (props) { super(props) this.state = { loading: true } } static propTypes = { pokemonDetailsStore: PropTypes.any, match: PropTypes.shape({ params: PropTypes.shape({ id: PropTypes.string }) }) }; colorType = { 1: '#f50', 2: '#2db7f5', 3: '#87d068', 4: '#108ee9' } colorAbilities = { 1: 'magenta', 2: 'green', 3: 'cyan', 4: 'purple' } componentDidMount () { reaction(() => this.props.match.params.id, async (data) => { this.props.pokemonDetailsStore.getPokemonDetails(this.props.match.params.id) this.setState(() => ({ loading: true })) }, { fireImmediately: true }) reaction(() => this.props.pokemonDetailsStore.pokemonDetails, async (data) => { this.setState(() => ({ loading: false })) }, { fireImmediately: true }) } componentWillUnmount () { this.setState(() => ({ loading: true })) this.props.pokemonDetailsStore.pokemonDetails = null this.props.pokemonDetailsStore.pokemonSpecies = null this.props.pokemonDetailsStore.pokemonEvolution = null } get evolution () { const { chain } = this.props.pokemonDetailsStore.pokemonEvolution const firstGen = chain const evolution = [firstGen] if (evolution[0].evolves_to.length !== 0) { evolution[0].evolves_to.forEach(evol => { evolution.push(evol) }) if (evolution[1].evolves_to.length !== 0) { evolution[1].evolves_to.forEach(evol => { evolution.push(evol) }) } } return evolution } render () { const { pokemonDetails, pokemonSpecies, pokemonEvolution } = this.props.pokemonDetailsStore const { loading } = this.state return !loading && pokemonDetails && pokemonSpecies && pokemonEvolution ? ( <React.Fragment> <Helmet> <title>{pokemonDetails.name} - Pokemon</title> </Helmet> <div className={`pokemon-detais pokemon-detais--${pokemonSpecies.color.name}`}> <div className={`wrapper`}> <div className='pokemon-detais__name'> <div className='pokemon-detais__main'> <div className='pokemon-detais__avatar'> <img src={`https://pokeres.bastionbot.org/images/pokemon/${pokemonDetails.id}.png`} alt={pokemonDetails.name} /> </div> <div className='pokemon-detais__desc'> <h1 className='pokemon-detais__title'> {`${pokemonDetails.name} #${pokemonDetails.id}`} </h1> {/* Desc */} <div className='pokemon-detais__text'> {pokemonSpecies.flavor_text_entries[1].language.name === 'en' ? pokemonSpecies.flavor_text_entries[1].flavor_text : pokemonSpecies.flavor_text_entries[2].flavor_text} </div> {/* Specifications */} <div className='pokemon-detais__specifications'> <h3 className='pokemon-detais__specifications-title'>Profile</h3> <div className='pokemon-detais__specifications-wrapper'> <div className='pokemon-detais__specifications-item'> <div className='pokemon-detais__specifications-name'>Height</div> <div className='pokemon-detais__specifications-value'>{`${pokemonDetails.height / 10} m`}</div> </div> <div className='pokemon-detais__specifications-item'> <div className='pokemon-detais__specifications-name'>Weight</div> <div className='pokemon-detais__specifications-value'>{`${pokemonDetails.weight / 10} kg`}</div> </div> <div className='pokemon-detais__specifications-item'> <div className='pokemon-detais__specifications-name'>Gender Rate</div> <div className='pokemon-detais__specifications-value'> {pokemonSpecies.gender_rate !== -1 ? ( `${pokemonSpecies.gender_rate}%` ) : ( <span>Gender Unknown</span> )} </div> </div> <div className='pokemon-detais__specifications-item'> <div className='pokemon-detais__specifications-name'>Capture Rate</div> <div className='pokemon-detais__specifications-value'> {`${pokemonSpecies.capture_rate}%`} </div> </div> <div className='pokemon-detais__specifications-item'> <div className='pokemon-detais__specifications-name'>Egg Groups:</div> <div className='pokemon-detais__specifications-value'> {pokemonSpecies.egg_groups[0].name} </div> </div> </div> </div> {/* Types */} <div className='pokemon-detais__types'> <h3 className='pokemon-detais__types-title'>Type</h3> <div className='pokemon-detais__types-wrapper'> {pokemonDetails.types.map(type => { return ( <Tag key={type.slot} color={this.colorType[type.slot]}>{type.type.name}</Tag> ) })} </div> </div> {/* Abilities */} <div className='pokemon-detais__abilities'> <h3 className='pokemon-detais__abilities-title'>Abilities</h3> <div className='pokemon-detais__abilities-wrapper'> {pokemonDetails.abilities.map(ability => { return ( <Tag key={ability.slot} color={this.colorAbilities[ability.slot]}>{ability.ability.name}</Tag> ) })} </div> </div> </div> </div> </div> <div className='pokemon-detais__evolution'> <h3 className='pokemon-detais__evolution-title'>Evolution</h3> <div className='pokemon-detais__evolution-wrapper'> {this.evolution.map(gen => { const { name, url } = gen.species return ( <div className='pokemon-detais__evolution-item' key={name}> <img src={`https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${parseId(url)}.png`} className='pokemon-detais__evolution-avatar' alt={name} /> <Link to={`/pokemon/${parseId(url)}`} className='pokemon-detais__evolution-link'> {name} </Link> </div> ) })} </div> </div> <div className='pokemon-detais__stats'> <h3 className='pokemon-detais__stats-title'>Statistics</h3> <div className='pokemon-detais__stats-wrapper'> {pokemonDetails.stats.map(stat => { return ( <div className='pokemon-detais__stats-item' key={stat.stat.name}> <div className='pokemon-detais__stats-name'> {stat.stat.name} </div> <div className='pokemon-detais__stats-progress'> <Progress percent={stat.base_stat} /> </div> </div> ) })} </div> </div> </div> </div> </React.Fragment> ) : ( <div className='box-center'> <Spin indicator={<Icon type='loading' style={{ fontSize: 24 }} spin />} /> </div> ) } } export default PokemonPage
38.920354
124
0.50864
75b0eff4852c5cc2977ed3095f1a57cca6aaafbb
81
js
JavaScript
index.js
kthurman59/javascript-logging-lab-js-intro-000
f30623692d342f685d5175f6a0f831ba5e163848
[ "RSA-MD" ]
null
null
null
index.js
kthurman59/javascript-logging-lab-js-intro-000
f30623692d342f685d5175f6a0f831ba5e163848
[ "RSA-MD" ]
null
null
null
index.js
kthurman59/javascript-logging-lab-js-intro-000
f30623692d342f685d5175f6a0f831ba5e163848
[ "RSA-MD" ]
null
null
null
console.error("HALP!") console.log("Stuff Stuff") console.warn("Don't do this!")
20.25
30
0.703704
75b1081e772a01c0da1996c10f539f2cf3ae62a8
975
js
JavaScript
dist/ClrGridView.js
sprucehq/clr-icons-react
ea1b161eab002406900e838476c842796a71f987
[ "MIT" ]
null
null
null
dist/ClrGridView.js
sprucehq/clr-icons-react
ea1b161eab002406900e838476c842796a71f987
[ "MIT" ]
2
2019-11-08T23:18:04.000Z
2021-05-09T19:30:40.000Z
dist/ClrGridView.js
sprucehq/clr-icons-react
ea1b161eab002406900e838476c842796a71f987
[ "MIT" ]
null
null
null
import * as React from "react"; var ClrGridView = function() { return React.createElement( "svg", { version: "1.1", viewBox: "0 0 36 36", preserveAspectRatio: "xMidYMid meet", xmlns: "http://www.w3.org/2000/svg", focusable: "false", role: "img", xmlnsXlink: "http://www.w3.org/1999/xlink" }, React.createElement("path", { d: "M14,4H6A2,2,0,0,0,4,6v8a2,2,0,0,0,2,2h8a2,2,0,0,0,2-2V6A2,2,0,0,0,14,4ZM6,14V6h8v8Z" }), React.createElement("path", { d: "M30,4H22a2,2,0,0,0-2,2v8a2,2,0,0,0,2,2h8a2,2,0,0,0,2-2V6A2,2,0,0,0,30,4ZM22,14V6h8v8Z" }), React.createElement("path", { d: "M14,20H6a2,2,0,0,0-2,2v8a2,2,0,0,0,2,2h8a2,2,0,0,0,2-2V22A2,2,0,0,0,14,20ZM6,30V22h8v8Z" }), React.createElement("path", { d: "M30,20H22a2,2,0,0,0-2,2v8a2,2,0,0,0,2,2h8a2,2,0,0,0,2-2V22A2,2,0,0,0,30,20ZM22,30V22h8v8Z" }) ); }; export default ClrGridView;
29.545455
99
0.570256
75b133023475f24d0ad0bc24282d1eee1f876fd9
466
js
JavaScript
src/App/Methods/onScreenChange.js
izure1/WeJS
90ede9d7f1688a6b251981085d77584c41d06963
[ "MIT" ]
null
null
null
src/App/Methods/onScreenChange.js
izure1/WeJS
90ede9d7f1688a6b251981085d77584c41d06963
[ "MIT" ]
null
null
null
src/App/Methods/onScreenChange.js
izure1/WeJS
90ede9d7f1688a6b251981085d77584c41d06963
[ "MIT" ]
null
null
null
import screenfull from 'screenfull' export default function onScreenChange(e) { if (!screenfull.isFullscreen) this.appScale = 1 else { const appWidth = this.app.width const appHeight = this.app.height const screenWidth = screen.width const screenHeight = screen.height const scaleX = screenWidth / appWidth const scaleY = screenHeight / appHeight this.appScale = scaleX > scaleY ? scaleX : scaleY } }
20.26087
54
0.671674
75b1494971eeb80a7f43306ebaf4614f52efe0df
857
js
JavaScript
server/db/models/asset.js
dropar/drop
90937398a4e9c75f6c43446a7e5ef52b1d256ca7
[ "MIT" ]
null
null
null
server/db/models/asset.js
dropar/drop
90937398a4e9c75f6c43446a7e5ef52b1d256ca7
[ "MIT" ]
9
2018-09-30T16:51:07.000Z
2018-10-06T16:36:30.000Z
server/db/models/asset.js
dropar/drop
90937398a4e9c75f6c43446a7e5ef52b1d256ca7
[ "MIT" ]
null
null
null
const Sequelize = require('sequelize') const db = require('../db') const Asset = db.define('asset', { displayName: { // displayName type: Sequelize.STRING, allowNull: false }, authorName: { type: Sequelize.STRING, allowNull: true }, assetUrl: { // asset.formats[].root.url type: Sequelize.TEXT, allowNull: false }, thumbnailUrl: { // thumbnail.url type: Sequelize.TEXT, allowNull: false }, category: { type: Sequelize.ENUM('Animals','Architecture', 'Art', 'Food', 'Nature', 'Objects', 'People', 'Scenes', 'Technology','Transport', 'Other', 'N/A'), allowNull: false }, googleApiId: { // name type: Sequelize.STRING, allowNull: true }, triangleCount: { // asset.formats[].formatComplexity.triangleCount type: Sequelize.INTEGER, allowNull: true, } }) module.exports = Asset
23.805556
149
0.638273
75b177608de5893319fb3a115491ca0b9cb0da9d
3,342
js
JavaScript
libs/util/fs.js
nartallax/Adamantos
a867899615f4978d6e119b2ac6eea3bb551c9261
[ "MIT" ]
2
2016-06-25T05:00:51.000Z
2017-09-29T16:28:44.000Z
libs/util/fs.js
nartallax/Adamantos
a867899615f4978d6e119b2ac6eea3bb551c9261
[ "MIT" ]
null
null
null
libs/util/fs.js
nartallax/Adamantos
a867899615f4978d6e119b2ac6eea3bb551c9261
[ "MIT" ]
null
null
null
aPackage('nart.util.fs', () => { var log = aRequire('nart.util.log'), fs = aRequire.node('fs'), path = aRequire.node('path'), err = aRequire('nart.util.err'); var rmDir = (path, cb) => { fs.readdir(path, err(files => { (files || []).eachAsync((f, cb) => { f = path + '/' + f; fs.stat(f, err(stat => { if(!stat) return; stat.isDirectory()? rmDir(f, cb): fs.unlink(f, err(cb)) })) }, () => { fs.rmdir(path, err(cb)) }) })); } var eachFileRecursive = (dirPath, onFile, after) => { fs.readdir(dirPath, err(files => { (files || []).eachAsync((f, cb) => { f = path.join(dirPath, f); fs.stat(f, err(stat => { if(!stat) return; stat.isDirectory()? eachFileRecursive(f, onFile, cb): (onFile(f), cb()) })) }, after) })); } var mkDir = (() => { var byParts = (parts, cb) => { switch(parts.length){ case 0: return cb(); case 1: return parts[0]? fs.mkdir(parts[0], cb): cb(); default: byParts(parts.slice(0, parts.length - 1), e => { if(e && (e.code || '').toLowerCase() !== 'eexist'){ return cb(e); } fs.mkdir(parts.join(path.sep), cb); }) break; } } return (dirPath, cb) => byParts(dirPath.split(path.sep), cb || (() => {})) })(); var getFileInDir = (baseDir, cb, filePrefix, filePostfix, onError) => { var name = path.join(baseDir, (filePrefix || '') + Math.round((Math.random() + 1) * 0xffffffff) + (filePostfix || '')); fs.stat(name, e => { if(e && !e.message.startsWith('ENOENT')){ (onError || log)(e) getFileInDir(baseDir, cb, filePrefix, filePostfix, onError); } else cb(name); }) } var normalizePath = pth => path.join.apply(path, pth.split(/[\\\/]/)); var splitPath = pth => normalizePath(pth).split(/[\\\/]/); return { // atomic... or very close to. putFile: (path, data, cb, onError) => { var tmp = path + '.temporary'; // по докам, если data instanceof Buffer, то третий параметр игнорируется // так что и Buffer должно получаться писать fs.writeFile(tmp, data, 'utf8', e => { e && (onError || log)(e); fs.rename(tmp, path, e => { e && (onError || log)(e); cb && cb() }) }) }, // NOT atomic, not even close appendFile: (path, data, cb, onError) => { fs.open(path, 'a', (e, id) => { e && (onError || log)(e); fs.write(id, data, null, 'utf8', e => { e && (onError || log)(e); fs.close(id, e => { e && (onError || log)(e); cb && cb(); }); }); }); }, // recursive rmDir: rmDir, // recursive, relatively failsafe mkDir: mkDir, // leave only existing file paths // do not alters the order of the items, just removes some of them filterExisting: (paths, cb, onError) => { var emap = {}; paths.eachAsync((file, cb) => { fs.stat(file, (e, data) => { if(e){ if(!e.message.startsWith('ENOENT')) (onError || log)(e); } else { emap[file] = true; } cb(); }) }, () => cb(paths.filter(p => emap[p]))) }, eachFileRecursiveIn: eachFileRecursive, getFileInDir: getFileInDir, readLines: (path, cb) => fs.readFile(path, 'utf8', err(text => cb((text || '').split(/[\n\r]+/)))), normalizePath: normalizePath, splitPath: splitPath } })
24.394161
121
0.52693
75b2794a1399c587aff4e50feb4f9340f89e23a9
4,594
js
JavaScript
test/checkInputTest.js
justusjonas74/uic-918-3
43126b1d4922858f129f846fc16ab5420c931803
[ "MIT" ]
15
2018-06-25T23:51:34.000Z
2022-01-06T06:20:54.000Z
test/checkInputTest.js
justusjonas74/uic-918-3
43126b1d4922858f129f846fc16ab5420c931803
[ "MIT" ]
7
2018-11-14T09:52:47.000Z
2022-02-24T06:40:27.000Z
test/checkInputTest.js
justusjonas74/uic-918-3
43126b1d4922858f129f846fc16ab5420c931803
[ "MIT" ]
null
null
null
var chai = require('chai') var chaiAsPromised = require('chai-as-promised') chai.use(chaiAsPromised) chai.should() const path = require('path') const fs = require('fs') const {fileExists, fileWillExists, loadFileOrBuffer, readFileAsync} = require('../lib/checkInput') describe('checkInput.js', () => { var filePath = {} beforeEach((done) => { const file = 'index.js' filePath.relative_true = file filePath.relative_false = file + '1458' filePath.absolute_true = path.resolve(file) filePath.absolute_false = path.resolve(file) + '254' done() }) describe('fileExists', () => { it('should return false if no file path given', () => { fileExists(null).should.be.false // eslint-disable-line no-unused-expressions }) it('should return false if a file with relative path isn\'t found', () => { fileExists(filePath.relative_false).should.be.false // eslint-disable-line no-unused-expressions }) it('should return true if a file with relative path is found', () => { fileExists(filePath.relative_true).should.be.true // eslint-disable-line no-unused-expressions }) it('should return false if a file with absolute path isn\'t found', () => { fileExists(filePath.absolute_false).should.be.false // eslint-disable-line no-unused-expressions }) it('should return true if a file with absolute path is found', () => { fileExists(filePath.absolute_true).should.be.true // eslint-disable-line no-unused-expressions }) }) describe('fileWillExists', () => { it('should return false if no file path given', () => { return fileWillExists(null).should.be.rejected // eslint-disable-line no-unused-expressions }) it('should return false if a file with relative path isn\'t found', () => { return fileWillExists(filePath.relative_false).should.be.rejected // eslint-disable-line no-unused-expressions }) it('should return true if a file with relative path is found', () => { return fileWillExists(filePath.relative_true).should.eventually.equal(filePath.relative_true) // eslint-disable-line no-unused-expressions }) it('should return false if a file with absolute path isn\'t found', () => { return fileWillExists(filePath.absolute_false).should.be.rejected // eslint-disable-line no-unused-expressions }) it('should return true if a file with absolute path is found', () => { return fileWillExists(filePath.absolute_true).should.eventually.equal(filePath.absolute_true)// eslint-disable-line no-unused-expressions }) }) describe('readFileAsync', () => { it('should return false if no file path given', () => { return readFileAsync(null).should.be.rejected // eslint-disable-line no-unused-expressions }) it('should return false if a file with relative path isn\'t found', () => { return readFileAsync(filePath.relative_false).should.be.rejected // eslint-disable-line no-unused-expressions }) it('should return true if a file with relative path is found', () => { return readFileAsync(filePath.relative_true).should.become(fs.readFileSync(filePath.relative_true)) // eslint-disable-line no-unused-expressions }) it('should return false if a file with absolute path isn\'t found', () => { return readFileAsync(filePath.absolute_false).should.be.rejected // eslint-disable-line no-unused-expressions }) it('should return true if a file with absolute path is found', () => { return readFileAsync(filePath.absolute_true).should.become(fs.readFileSync(filePath.absolute_true))// eslint-disable-line no-unused-expressions }) }) describe('isBufferOrString', () => { describe('with no optional parameters', () => { it('should be fulfilled with a string', () => { loadFileOrBuffer(filePath.relative_true).should.be.fulfilled // eslint-disable-line no-unused-expressions return loadFileOrBuffer(filePath.relative_true).should.become(fs.readFileSync(filePath.relative_true)) // eslint-disable-line no-unused-expressions }) it('should be fulfilled with a Buffer', () => { const buf = Buffer.from('01125684') loadFileOrBuffer(buf).should.be.fulfilled // eslint-disable-line no-unused-expressions return loadFileOrBuffer(buf).should.become(buf) // eslint-disable-line no-unused-expressions }) it('should be rejected with a wrong file path', () => { return loadFileOrBuffer(filePath.relative_false).should.be.rejected // eslint-disable-line no-unused-expressions }) }) }) })
49.397849
155
0.694384
75b27b0ba8aa82da97862e1619bba14a19b13635
773
js
JavaScript
backend/src/migrations/20190722114252_delete_criacao_columns.js
dmcardoso/feed-track
1754af09ce7aa9fae3f50456190410ecddef2baf
[ "MIT" ]
1
2020-10-07T22:04:03.000Z
2020-10-07T22:04:03.000Z
backend/src/migrations/20190722114252_delete_criacao_columns.js
dmcardoso/feed-track
1754af09ce7aa9fae3f50456190410ecddef2baf
[ "MIT" ]
3
2019-09-27T12:55:07.000Z
2021-09-02T02:25:29.000Z
backend/src/migrations/20190722114252_delete_criacao_columns.js
dmcardoso/feed-track
1754af09ce7aa9fae3f50456190410ecddef2baf
[ "MIT" ]
1
2021-01-18T01:28:08.000Z
2021-01-18T01:28:08.000Z
exports.up = function (knex) { return knex.schema.alterTable('feedbacks', (table) => { table.dropColumn('criacao'); }) .then(() => knex.schema.alterTable('filiais', (table) => { table.dropColumn('criacao'); })) .then(() => knex.schema.alterTable('funcionarios', (table) => { table.dropColumn('criacao'); })); }; exports.down = function (knex) { return knex.schema.alterTable('feedbacks', (table) => { table.dateTime('criacao').notNullable(); }).then(() => knex.schema.alterTable('filiais', (table) => { table.dateTime('criacao').notNullable(); })).then(() => knex.schema.alterTable('funcionarios', (table) => { table.dateTime('criacao').notNullable(); })); };
35.136364
71
0.56533
75b2bbf0784595e9ef1365ab88725d5335e288c4
6,261
js
JavaScript
app.js
Eleson-Souza/api-de-games-docs
b95e48de5572509f0cfbc0f6a94cf6b59f8b51ab
[ "MIT" ]
null
null
null
app.js
Eleson-Souza/api-de-games-docs
b95e48de5572509f0cfbc0f6a94cf6b59f8b51ab
[ "MIT" ]
1
2021-05-11T17:44:56.000Z
2021-05-11T17:44:56.000Z
app.js
Eleson-Souza/api-de-games-docs
b95e48de5572509f0cfbc0f6a94cf6b59f8b51ab
[ "MIT" ]
1
2020-06-21T17:55:15.000Z
2020-06-21T17:55:15.000Z
// API REST const express = require('express'); const app = express(); const bodyParser = require('body-parser'); const connection = require('./database/connection'); const Games = require('./models/Games'); const Users = require('./models/Users'); const cors = require('cors'); const authWithToken = require('./middleware/authWithToken'); // biblioteca que gera um token após uma autenticação de um login, para garantir maior segurança. const jwt = require('jsonwebtoken'); // senha secreta para gerar o token. //const JWTSecret = 'ID68(@WCPw|uzY5*'; // Mecanismo de segurança que quando ativado, bloqueia a utilização externa da API. // Neste caso, o bloqueio fica desativado. app.use(cors()); app.use(bodyParser.urlencoded({extended: false})); app.use(bodyParser.json()); // Database connection .authenticate() .then(() => { //console.log('Conexão ao banco realizada com sucesso!'); }) .catch((err) => { console.log('Ocorreu um erro ao se conectar: ' + err); }); // listando todos os games do banco app.get('/games', authWithToken.authToken, (req, res) => { Games.findAll().then((games) => { res.json({user: req.loggedUser, games: games}); res.statusCode = 200; }); }); // exibindo game com um id específico app.get('/game/:id', authWithToken.authToken, (req, res) => { if(isNaN(req.params.id)) { res.sendStatus(400); } else { var id = parseInt(req.params.id); // lista de links do HATEOAS var HATEOAS = [ { href: `http://localhost:45679/game/${id}`, method: "DELETE", rel: "delete_game" }, { href: `http://localhost:45679/game/${id}`, method: "PUT", rel: "edit_game" }, { href: `http://localhost:45679/game/${id}`, method: "GET", rel: "get_game" }, { href: `http://localhost:45679/games`, method: "GET", rel: "get_all_games" }, ]; Games.findByPk(id).then((game) => { if(game != undefined) { res.json({game, _links: HATEOAS}); } else { res.sendStatus(404); } }); } }); // Criando um novo game a partir dos dados recebidos pelo body na requisição app.post('/game', authWithToken.authToken, (req, res) => { var {title, year, price} = req.body; if(isNaN(year) || isNaN(price) || year == '' || price == '' || title == '') { res.sendStatus(400); } else { Games.create({ title, year, price }).then(() => { res.sendStatus(200); }); } }); // deletando um game a partir do id app.delete('/game/:id', authWithToken.authToken, (req, res) => { if(isNaN(req.params.id)) { res.sendStatus(400); } else { var id = parseInt(req.params.id); Games.findByPk(id).then((game) => { if(game != undefined) { Games.destroy({ where: { id: id } }).then(() => { res.sendStatus(200); }); } else { res.sendStatus(404); } }); } }); // Editando um game a partir do id, com os dados recebidos pelo body na requisição. app.put('/game/:id', authWithToken.authToken, (req, res) => { if(isNaN(req.params.id)) { res.sendStatus(400); } else { var id = parseInt(req.params.id); Games.findByPk(id).then((game) => { if(game != undefined) { var {title, year, price} = req.body; // Se o valor for definido, irá ser realizado o update. if(title != undefined) { Games.update({title: title}, {where: {id: id}}); } if(year != undefined) { Games.update({year: year}, {where: {id: id}}); } if(price != undefined) { Games.update({price: price}, {where: {id: id}}); } res.sendStatus(200); } else { res.sendStatus(404); } }); } }); // autentificação do usuário (login) utilizando o JWT app.post('/auth', /* authToken, */ (req, res) => { var {email, password} = req.body; // se email foi informado (não é indefinido ou nulo) if(email) { // busca o email no banco, se estiver correto verifica a senha. Users.findOne({where: {email: email}}).then(user => { if(user) { if(user.password == password) { // Utilizando o JWT após a autentificação. sign({dados que poderão ser acessados posteriormente}, senha para gerar token, tempo de expiração, callback(erro, token)=>{}) jwt.sign({ id: user.id, email: user.email }, authWithToken.JWTSecret, {expiresIn: '48h'}, (err, token) => { if(err) { res.status(400); res.json({err: 'Falha interna'}); } else { res.status(200); res.json({token: token}); } }); } else { res.status(401); res.json({ err: 'Credenciais inválidas!', status: res.statusCode }); } } else { res.status(404); res.json({ err: 'O e-mail enviado não existe na base de dados!', status: res.statusCode }); } }); } else { res.status(400); res.json({err: 'O e-mail enviado é inválido!', status: res.statusCode}); } }); var port = 1234; app.listen(port, () => { console.log('API rodando na porta ' + port); });
31.149254
188
0.472608
75b2c7b743315d86bc5ae4baa8a1e4d40937aea1
93
js
JavaScript
blueprints/ember-theater/files/app/ember-theater/config.js
ember-theater/ember-cli-theater
b5d37c0d176a3759f9bc94cd94faa5ac671992f7
[ "MIT" ]
10
2015-11-11T16:59:08.000Z
2016-02-18T08:16:16.000Z
blueprints/ember-theater/files/app/ember-theater/config.js
ember-theater/ember-cli-theater
b5d37c0d176a3759f9bc94cd94faa5ac671992f7
[ "MIT" ]
80
2015-11-19T06:32:47.000Z
2016-04-30T23:31:55.000Z
blueprints/ember-theater/files/app/ember-theater/config.js
affinity-engine/ember-theater
b5d37c0d176a3759f9bc94cd94faa5ac671992f7
[ "MIT" ]
1
2015-12-04T03:44:15.000Z
2015-12-04T03:44:15.000Z
export default { plugins: [], mediaLoader: { type: '', filesToPreload: [] } };
11.625
22
0.526882
75b32879841faac0c5fa6f452c06857e6974a804
1,246
js
JavaScript
examples/counter/index.js
jseminck/js-vdom
e471f378d5166fac5eba932505fd7f80a555e964
[ "MIT" ]
null
null
null
examples/counter/index.js
jseminck/js-vdom
e471f378d5166fac5eba932505fd7f80a555e964
[ "MIT" ]
null
null
null
examples/counter/index.js
jseminck/js-vdom
e471f378d5166fac5eba932505fd7f80a555e964
[ "MIT" ]
null
null
null
/** @jsx createElement */ import {createElement, render} from './../../dist/index.js';; let counter = 0; let lastActionClass = ""; let lastAction = ""; let size = "11px"; const counterJSX = (counter) => ( <div> <h2>Counter</h2> <div> The number is: <span>{counter}</span> {lastAction && lastActionClass && ( <div style={{fontSize: size}}> The last action was... <span className={lastActionClass}>{lastAction}</span> </div> )} </div> <button id="increase" onClick={increase}>Increase value</button> <button id="decrease" onClick={decrease}>Decrease value</button> </div> ); const $root = document.getElementById('root'); const $increase = document.getElementById('increase'); const $decrease = document.getElementById('decrease'); render($root, counterJSX(counter)); function increase() { counter++; size = "14px"; lastAction = "Increase"; lastActionClass = "action-increase"; render($root, counterJSX(counter)); }; function decrease() { counter--; size = "8px"; lastAction = "Decrease"; lastActionClass = "action-decrease"; render($root, counterJSX(counter)); };
26.510638
96
0.596308
75b3dda72e2586e4c2f4166ca0417b56ac71d3a7
7,369
js
JavaScript
index.js
BurlingtonCodeAcademy/guess-the-number-anismemon
79c62da4ea7b52502e1dcb98016ee1aca381c1bb
[ "MIT" ]
null
null
null
index.js
BurlingtonCodeAcademy/guess-the-number-anismemon
79c62da4ea7b52502e1dcb98016ee1aca381c1bb
[ "MIT" ]
null
null
null
index.js
BurlingtonCodeAcademy/guess-the-number-anismemon
79c62da4ea7b52502e1dcb98016ee1aca381c1bb
[ "MIT" ]
1
2020-05-28T12:58:45.000Z
2020-05-28T12:58:45.000Z
const readline = require('readline'); const rl = readline.createInterface(process.stdin, process.stdout); // ---------------------------------------------------------------------------------------------------------------------- // ----------- functions used by main game __________-------------------------------------------------------------------- function ask(questionText) { return new Promise((resolve, reject) => { rl.question(questionText, resolve); }); } // ----------- binary search function to optimize guessing in computerGuess game ---------------------------------------- function binarySearch(min, max) { return Math.floor((max + min) / 2); } // ---------- random number generator in playerGuess game --------------------------------------------------------------- function randomInt(max, min) { return Math.floor(min + (Math.random() * (max - min + 1))) } // ----------- global variables for common answers ---------------------------------------------------------------------- let yesAnswer = ["yes", "y", "yeah", "yup"] let noAnswer = ["no", "n", "nah", "nope"] // didn't use but could be helpful later let highAnswer = ["h", "higher", "high", "up"] let lowAnswer = ["l", "lower", "low", "down"] // ---------------------------------------------------------------------------------------------------------------------- // -------------- guessing game setup - select which game to play -------------------------------------------------------- start(); async function start() { console.log("Let's play a guessing game! Either you (the human) can guess a number that I (the computer) think of, or I can guess a number you think of.") let whichGame = await ask("\nType 'C' if you want me to guess, or 'H' if you want to guess. "); // ------------- loop to give you a couple of chances to type 'c' and 'h' if you mistype -------------------------------- let i = 0 while (i < 3) { if (whichGame.toLowerCase() === 'c') { computerGuess() } else if (whichGame.toLowerCase() === 'h') { playerGuess() } i++ whichGame = await ask("\nType 'C' if you want me to guess, or 'H' if you want to guess. "); } console.log("\nMaybe next time!") process.exit() // --------------------------------------------------------------------------------------------------------------------- // ----- interactive game where the computer guesses player's number --------------------------------------------------- async function computerGuess() { // --------------- user input to set max value ----------------------------------------------------------------------- let max = parseInt(await ask("\nGreat. Please give me the upper range for my guesses. ")); // ----------- default max if no value selected ---------------------------------------------------------------------- if (isNaN(max)) { max = 100; } // ------------ other variables needed ------------------------------------------------------------------------------- let min = 1; let guess = binarySearch(min, max); let answerYesNo = ""; let answerHighLow = ""; let count = 1; console.log("\nNow I'll guess a number between 1 and " + max + ".") answerYesNo = await ask("\nIs it ... " + guess + "? (Y/N) ") // ------------- loop for computer's guesses -------------------------------------------------------------------------- while (!yesAnswer.includes(answerYesNo.toLowerCase())) { answerHighLow = await ask("\nIs it higher (H) or lower (L)? ") // -------------------- guessing mechanism -------------------------------------------------------------------------- if (highAnswer.includes(answerHighLow.toLowerCase())) { min = guess + 1; } else if (lowAnswer.includes(answerHighLow.toLowerCase())) { max = guess - 1; } else { answerHighLow = await ask("\nIs it higher (H) or lower (L)? ") } guess = binarySearch(min, max) answerYesNo = await ask("\nIs it ... " + guess + "? (Y/N) ") count += 1; // --------------- cheat detector checks if player gave inaccurate responses ------------------------------------------ if (min > max) { console.log("\nThere appears to be a problem. Are you sure about your number?"); process.exit(); } } // ------------------ conclusion to game and offer to play the other game ---------------------------------------------- console.log("\nWow! I guessed it in " + count + " tries!") let playOtherGame = await ask("\nNow would you like to guess my number? Y/N ") if (yesAnswer.includes(playOtherGame.toLowerCase())) { playerGuess() } else { console.log("\nThanks for playing!") process.exit(); } } // --------------------------------------------------------------------------------------------------------------------- // --------- interactive game where player guesses computer's randomly generated number -------------------------------- async function playerGuess() { // --------- checks that the range numbers input are actually numbers --------------------------------------------------- let lowerRange = parseInt(await ask("\nPlease give me a minimum value. ")); let upperRange = parseInt(await ask("\nPlease give me a maximum value. ")) let i = 1 while (isNaN(lowerRange) || isNaN(upperRange)) { if (isNaN(lowerRange)) { lowerRange = parseInt(await ask("\nPlease give me a valid minimum value. ")); } if (isNaN(upperRange)) { upperRange = parseInt(await ask("\nPlease give me a valid maximum value. ")) } if (i === 2) { process.exit() } i++ } // ----------- computer generates a random number using the specified range -------------------------------------------- let compNum = randomInt(upperRange, lowerRange); let playerGuess = parseInt(await ask("\nGuess a number. ")) let count = 1; // ------------- loop for player's guesses --------------------------------------------------------------------------- while (playerGuess !== compNum) { // ------------ checks if guess is within specified range ---------------------------------------------------------- if (playerGuess > upperRange || playerGuess < lowerRange) { console.log("\nYour number is outside the guessing range!") playerGuess = parseFloat(await ask("\nPlease guess again. ")) // ----- player keeps guessing ----------------------------------------------------------------------------------- } else if (playerGuess < compNum) { playerGuess = parseFloat(await ask("\nThe correct number is higher. Guess again. ")) } else { playerGuess = parseFloat(await ask("\nThe correct number is lower. Guess again. ")) } count += 1; } // -------- conclusion to game and offer to play other game --------------------------------------------------------- console.log("\nCongratulations! You guessed the correct number in " + count + " tries!") let playOtherGame = await ask("\nNow would you like me to guess your number? Y/N ") if (yesAnswer.includes(playOtherGame.toLowerCase())) { computerGuess() } else { console.log("\nThanks for playing!") process.exit() } } }
40.26776
156
0.454471
75b3e3fb236acaaa44ec8b8f5e63369660815e78
231
js
JavaScript
Exercises/7-objects.js
KirillSkomarovskiy/Reusable
e3b12c7c541250a752a500b3bd18b17c077c49db
[ "MIT" ]
null
null
null
Exercises/7-objects.js
KirillSkomarovskiy/Reusable
e3b12c7c541250a752a500b3bd18b17c077c49db
[ "MIT" ]
null
null
null
Exercises/7-objects.js
KirillSkomarovskiy/Reusable
e3b12c7c541250a752a500b3bd18b17c077c49db
[ "MIT" ]
null
null
null
'use strict'; const fn = () => { const obj1 = { name: 'John Doe', }; let obj2 = { name: 'Mary Moe', }; obj1.name = 'new name1'; obj2.name = 'new name2'; obj1 = {}; obj2 = {}; }; module.exports = { fn };
12.157895
26
0.471861
75b4277b7f770ec4694fe6394bb3581cdf4a1f90
858
js
JavaScript
client/src/components/common/ConfirmDeleteModal/ConfirmDeleteModal.js
tligodsp/quan-ly-khoa-luan
83faac935d2c030aa09732f15ad1427580350a6c
[ "MIT" ]
null
null
null
client/src/components/common/ConfirmDeleteModal/ConfirmDeleteModal.js
tligodsp/quan-ly-khoa-luan
83faac935d2c030aa09732f15ad1427580350a6c
[ "MIT" ]
null
null
null
client/src/components/common/ConfirmDeleteModal/ConfirmDeleteModal.js
tligodsp/quan-ly-khoa-luan
83faac935d2c030aa09732f15ad1427580350a6c
[ "MIT" ]
null
null
null
import React from 'react'; import { Card, CardBody, CardHeader, CardFooter, Button, } from "shards-react"; import DeleteOutlineIcon from '@material-ui/icons/DeleteOutline'; import './styles.css'; const ConfirmDeleteModal = ({ onClose, onConfirm }) => { return ( <Card large className="mb-4"> <CardHeader className="modal-header"> <h5 className="m-0">Xác nhận</h5> </CardHeader> <CardBody> <div className="confirm-delete-body"> <DeleteOutlineIcon className="delete-icon" /> <div>Bạn có thực sự muốn xóa?</div> </div> </CardBody> <CardFooter className="modal-footer"> <Button theme="light" onClick={onClose}>Hủy</Button> <Button onClick={onConfirm} theme="danger">Xóa</Button> </CardFooter> </Card> ); } export default ConfirmDeleteModal;
25.235294
65
0.630536
75b5338d6b8a96707130be4d018635aac60b0fdd
5,071
js
JavaScript
test/pai.spec.js
Myo-Finance/myo.tokens
6dd47b703f07f0da1a3f49f9d2e8363a37732d85
[ "MIT" ]
null
null
null
test/pai.spec.js
Myo-Finance/myo.tokens
6dd47b703f07f0da1a3f49f9d2e8363a37732d85
[ "MIT" ]
null
null
null
test/pai.spec.js
Myo-Finance/myo.tokens
6dd47b703f07f0da1a3f49f9d2e8363a37732d85
[ "MIT" ]
null
null
null
/* MIT License Copyright (c) 2020 Myo.Finance Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ const {use, expect} = require("chai"); const {ethers} = require("ethers"); const {solidity, deployContract} = require("ethereum-waffle"); const {getProvider} = require("./setup"); const PAI = require("../build/PAI.json"); const {parseEther} = require("ethers/lib/utils"); use(solidity); describe("PAI ERC20 smart contract", () => { let token; let wallet, walletTo; let wallets; let provider; before(async () => { provider = await getProvider(); wallets = provider.getWallets(); wallet = wallets[0]; walletTo = wallets[1]; }); // parameters to use for our test coin const COIN_NAME = "Peso Argentino Intangible"; const TICKER = "PAI"; const NUM_DECIMALS = 18; /* Deploy a new ERC20 Token before each test */ beforeEach(async () => { token = await deployContract(wallet, PAI); }); it("Correctly sets vanity information", async () => { const name = await token.name(); expect(name).to.equal(COIN_NAME); const decimals = await token.decimals(); expect(decimals).to.equal(NUM_DECIMALS); const symbol = await token.symbol(); expect(symbol).to.equal(TICKER); }); describe("Transfers", () => { let walletBalance; beforeEach(async () => { const amount = parseEther("1000"); await token.mint(wallet.address, amount); walletBalance = await token.balanceOf(wallet.address); }); it("Transfer adds amount to destination account", async () => { const transferAmount = parseEther("100"); const mintAmount = parseEther("7"); await token.mint(walletTo.address, mintAmount); await token.transfer(walletTo.address, transferAmount); expect(await token.balanceOf(walletTo.address)).to.equal( transferAmount.add(mintAmount) ); }); it("Transfer emits event", async () => { const amount = parseEther("100"); await expect(token.transfer(walletTo.address, amount)) .to.emit(token, "Transfer") .withArgs(wallet.address, walletTo.address, amount); }); it("Transfer above availability reverts", async () => { const amount = parseEther("1007"); await expect(token.transfer(walletTo.address, amount)).to.be.reverted; }); it("Transfer from empty account reverts", async () => { const tokenFromOtherWallet = token.connect(walletTo); await expect(tokenFromOtherWallet.transfer(wallet.address, 1)).to.be .reverted; }); }); describe("Minting and Burning", async () => { it("Only owner can mint new tokens", async () => { const tokenFromNonOwner = token.connect(wallets[1]); await expect(tokenFromNonOwner.mint(wallet.address, parseEther("1"))).to .be.reverted; const mintAmount = parseEther("1"); const prevBalance = await token.balanceOf(wallet.address); await expect(token.mint(wallet.address, mintAmount)).to.not.be.reverted; expect(await token.balanceOf(wallet.address)).to.equal( prevBalance.add(mintAmount) ); }); it("Burn decreasess the balance of msg.sender", async () => { const mintAmount = parseEther("10"); const prevBalance = await token.balanceOf(wallet.address); await token.mint(wallet.address, mintAmount); await expect(token.burn(mintAmount)).not.to.be.reverted; expect(await token.balanceOf(wallet.address)).to.be.equal(prevBalance); }); it("Mint emits event", async () => { await expect(token.mint(wallets[1].address, parseEther("1"))) .to.emit(token, "Transfer") .withArgs( ethers.constants.AddressZero, wallets[1].address, parseEther("1") ); }); it("Burn emits event", async () => { await token.mint(wallet.address, parseEther("1")); await expect(token.burn(parseEther("1"))) .to.emit(token, "Transfer") .withArgs( wallet.address, ethers.constants.AddressZero, parseEther("1") ); }); }); });
32.50641
78
0.668113
75b56e05e659d7a860b90ebbe64b2a604939e8db
360
js
JavaScript
lib/projects.js
nmarley/coinjs
bf0e604409b8dfabed9dbb04cdfb969cbab0e445
[ "MIT" ]
null
null
null
lib/projects.js
nmarley/coinjs
bf0e604409b8dfabed9dbb04cdfb969cbab0e445
[ "MIT" ]
null
null
null
lib/projects.js
nmarley/coinjs
bf0e604409b8dfabed9dbb04cdfb969cbab0e445
[ "MIT" ]
1
2019-01-05T13:10:36.000Z
2019-01-05T13:10:36.000Z
'use strict;' var Projects = { bitcoin: { mainnet: { port: 8332, }, testnet: { port: 18332, }, }, litecoin: { mainnet: { port: 9332, }, testnet: { port: 19332, }, }, darkcoin: { mainnet: { port: 9998, }, testnet: { port: 19998, }, }, } module.exports = Projects
11.612903
25
0.436111
75b64926e0002fe2d45e041d933fff5daeb58a49
5,154
js
JavaScript
docs/assets/js/35.ffb46cd4.js
deulos/vue-flux-docs
52a18b2caf82080dc6950cd44052b9d594abe321
[ "MIT" ]
1
2020-03-27T18:41:53.000Z
2020-03-27T18:41:53.000Z
docs/assets/js/35.ffb46cd4.js
ragnarlotus/vue-flux-docs
52a18b2caf82080dc6950cd44052b9d594abe321
[ "MIT" ]
null
null
null
docs/assets/js/35.ffb46cd4.js
ragnarlotus/vue-flux-docs
52a18b2caf82080dc6950cd44052b9d594abe321
[ "MIT" ]
null
null
null
(window.webpackJsonp=window.webpackJsonp||[]).push([[35],{306:function(e,t,n){"use strict";n.d(t,"b",(function(){return i})),n.d(t,"a",(function(){return s}));n(312),n(67),n(10),n(95),n(313);var o=n(25),r=n(45),i=function(){function e(){Object(o.a)(this,e)}return Object(r.a)(e,null,[{key:"generate",value:function(){for(var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1,t=[],n=1;n<=60;n++)t.push(n.toString().padStart(2,"0")+".jpg");for(var o,r,i=[],a=1;a<=e;a++)o=Math.floor(Math.random()*t.length),r=t.splice(o,1)[0],i.push(r);return i.length>1?i:i[0]}}]),e}(),a=["The early bird gets the worm, but the second mouse gets the cheese","Be on the alert to recognize your prime at whatever time of your life it may occur","Your road to glory will be rocky, but fulfilling","Courage is not simply one of the virtues, but the form of every virtue at the testing point","Patience is your alley at the moment, don’t worry!","Nothing is impossible to a willing heart","Don’t worry about money, the best things in life are free","Don’t pursue happiness – create it","Courage is not the absence of fear; it is the conquest of it","Nothing is so much to be feared as fear","All things are difficult before they are easy","The real kindness comes from within you","A ship in harbor is safe, but that’s not why ships are built","You don’t need strength to let go of something, what you really need is understanding","If you want the rainbow, you have to tolerate the rain","Fear is interest paid on a debt you may not owe","Hardly anyone knows how much is gained by ignoring the future","The wise man is the one that makes you think that he is dumb","The usefulness of a cup is in its emptiness","He who throws mud loses ground","Success lies in the hands of those who wants it","To avoid criticism, do nothing, say nothing, be nothing","One that would have the fruit must climb the tree","It takes less time to do a thing right than it does to explain why you did it wrong","Big journeys begin with a single step","Of all our human resources, the most precious is the desire to improve","Do the thing you fear and the death of fear is certain","You never show your vulnerability, you are always self assured and confident","People learn little from success, but much from failure","Be not afraid of growing slowly, be afraid only of standing still","We must always have old memories and young hopes","A person who won’t read has no advantage over a person who can’t read","He who expects no gratitude shall never be disappointed","I hear and I forget, I see and I remember, I do and I understand","The best way to get rid of an enemy is to make a friend","It’s amazing how much good you can do if you don’t care who gets the credit","Never forget that a half truth is a whole lie","Happiness isn’t an outside job, it’s an inside job","If you do no run your subconscious mind yourself, someone else will","Yes by calling full, you created emptiness"],s=function(){function e(){Object(o.a)(this,e)}return Object(r.a)(e,null,[{key:"generate",value:function(e){for(var t,n=[],o=1;o<=e;o++)t=Math.floor(Math.random()*a.length),n.push(a[t]);return n}}]),e}()},312:function(e,t,n){"use strict";var o=n(1),r=n(100),i=n(47),a=n(14),s=n(12),u=n(101),h=n(49),l=n(48),f=n(19),c=l("splice"),d=f("splice",{ACCESSORS:!0,0:0,1:2}),g=Math.max,m=Math.min;o({target:"Array",proto:!0,forced:!c||!d},{splice:function(e,t){var n,o,l,f,c,d,y=s(this),p=a(y.length),w=r(e,p),b=arguments.length;if(0===b?n=o=0:1===b?(n=0,o=p-w):(n=b-2,o=m(g(i(t),0),p-w)),p+n-o>9007199254740991)throw TypeError("Maximum allowed length exceeded");for(l=u(y,o),f=0;f<o;f++)(c=w+f)in y&&h(l,f,y[c]);if(l.length=o,n<o){for(f=w;f<p-o;f++)d=f+n,(c=f+o)in y?y[d]=y[c]:delete y[d];for(f=p;f>p-o+n;f--)delete y[f-1]}else if(n>o)for(f=p-o;f>w;f--)d=f+n-1,(c=f+o-1)in y?y[d]=y[c]:delete y[d];for(f=0;f<n;f++)y[f+w]=arguments[f+2];return y.length=p-o+n,l}})},313:function(e,t,n){"use strict";var o=n(1),r=n(318).start;o({target:"String",proto:!0,forced:n(320)},{padStart:function(e){return r(this,e,arguments.length>1?arguments[1]:void 0)}})},318:function(e,t,n){var o=n(14),r=n(319),i=n(24),a=Math.ceil,s=function(e){return function(t,n,s){var u,h,l=String(i(t)),f=l.length,c=void 0===s?" ":String(s),d=o(n);return d<=f||""==c?l:(u=d-f,(h=r.call(c,a(u/c.length))).length>u&&(h=h.slice(0,u)),e?l+h:h+l)}};e.exports={start:s(!1),end:s(!0)}},319:function(e,t,n){"use strict";var o=n(47),r=n(24);e.exports="".repeat||function(e){var t=String(r(this)),n="",i=o(e);if(i<0||i==1/0)throw RangeError("Wrong number of repetitions");for(;i>0;(i>>>=1)&&(t+=t))1&i&&(n+=t);return n}},320:function(e,t,n){var o=n(99);e.exports=/Version\/10\.\d+(\.\d+)?( Mobile\/\w+)? Safari\//.test(o)},379:function(e,t,n){"use strict";n.r(t);var o=n(306),r={name:"demos-index-2",components:{FluxParallax:n(315).FluxParallax},data:function(){return{src:"../img/slides/"}},created:function(){this.src+=o.b.generate()}},i=n(44),a=Object(i.a)(r,(function(){var e=this.$createElement;return(this._self._c||e)("flux-parallax",{staticStyle:{height:"250px"},attrs:{src:this.src,type:"fixed"}})}),[],!1,null,null,null);t.default=a.exports}}]);
5,154
5,154
0.689367
75b6bd41a0d812ac81f8a6fa9b56e3678b3f289c
965
js
JavaScript
dist/lib/assets/Networks/network-icon.png.js
PiggyPrize/app-react-components
08832424053eec4703b55f71d1c04aaab665c8e4
[ "MIT" ]
null
null
null
dist/lib/assets/Networks/network-icon.png.js
PiggyPrize/app-react-components
08832424053eec4703b55f71d1c04aaab665c8e4
[ "MIT" ]
null
null
null
dist/lib/assets/Networks/network-icon.png.js
PiggyPrize/app-react-components
08832424053eec4703b55f71d1c04aaab665c8e4
[ "MIT" ]
null
null
null
'use strict'; var DefaultNetworkLogo = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABIAAAAQCAYAAAAbBi9cAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAH5SURBVHgBlVNBchMxEJyZtVO+ZbkA4YL5gXlB/IM4V8pr1i+InA/EvCD6QbYCxZXkB+YHmxckF7ANl6U4QKUiTWYkex1XKi5nLiuNVj3dPSOARZj+j95oMB3DFmH6857JZuZhjsJBPm0jNo+YoNgGyH55dYFAB6Y/7a4B4R2N2cHIFns3CroJxOS/OvrlxA0J6agG0otMnNqvL8vAzNO3TUDk+ESZaFGP/mrJisBDjtA4C8xccsbkDzcB+WRniESnCz0FEAavCDnZZ/r7PTBD/2cpz3yIElaSJCcNscWLisFfLlkhQztiIqS2eFeBgy4wTJbMYMdVZjA/MYNZeZzNg1ykRmTiYYKEvZADvNYiJJcriJk2MJcrDq0KGbv2/HVHvdBCwiQwhwbcMMJuwBQVNaNwj7FCau4uQGMOOZWLXZUPCUyISc7/S2GXPmoCsMcIpGzc+7AEd4n+9iAY74UJu09RkcyQ2nDXbMvmKtZK3ip4g5HLODutEvytejAGallVHC7pvjb8ehgJQ48TrvP6n3o0kdnJ627I6Ot6AbIWmlOpAsKhu/JUQP0L0pLWhXw/SrXUnu8JG9zXNTwVXrqFHKQiojwrtvWZyX6a4+z3KTwjTDbNR4OZXZmtlD+/EU+4owO3FUh45CRs/o3XgDQ4aR7CM0I7+tDHexnEAHkQhKEOAAAAAElFTkSuQmCC"; module.exports = DefaultNetworkLogo; //# sourceMappingURL=network-icon.png.js.map
137.857143
866
0.935751
75b6d1a1204b4e1df51943e8f305c69685486ae6
44,161
js
JavaScript
unpackage/dist/dev/mp-weixin/pages/release_res/release_res.js
Mr-gtt/lichees-mp-c
7aa7c7af16ba7c13188853b35b31238763bd70ec
[ "MIT" ]
2
2021-12-28T08:02:25.000Z
2021-12-28T08:07:28.000Z
unpackage/dist/dev/mp-weixin/pages/release_res/release_res.js
Mr-gtt/lichees-mp-c
7aa7c7af16ba7c13188853b35b31238763bd70ec
[ "MIT" ]
null
null
null
unpackage/dist/dev/mp-weixin/pages/release_res/release_res.js
Mr-gtt/lichees-mp-c
7aa7c7af16ba7c13188853b35b31238763bd70ec
[ "MIT" ]
null
null
null
(global["webpackJsonp"] = global["webpackJsonp"] || []).push([["pages/release_res/release_res"],{ /***/ 58: /*!********************************************************************************************************!*\ !*** C:/Users/LENOVO/Desktop/uni-app/demo1/demo1/main.js?{"page":"pages%2Frelease_res%2Frelease_res"} ***! \********************************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* WEBPACK VAR INJECTION */(function(createPage) {__webpack_require__(/*! uni-pages */ 4); var _vue = _interopRequireDefault(__webpack_require__(/*! vue */ 2)); var _release_res = _interopRequireDefault(__webpack_require__(/*! ./pages/release_res/release_res.vue */ 59));function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { default: obj };} createPage(_release_res.default); /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./node_modules/@dcloudio/uni-mp-weixin/dist/index.js */ 1)["createPage"])) /***/ }), /***/ 59: /*!*************************************************************************************!*\ !*** C:/Users/LENOVO/Desktop/uni-app/demo1/demo1/pages/release_res/release_res.vue ***! \*************************************************************************************/ /*! no static exports found */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _release_res_vue_vue_type_template_id_4cf4cb50___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./release_res.vue?vue&type=template&id=4cf4cb50& */ 60); /* harmony import */ var _release_res_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./release_res.vue?vue&type=script&lang=js& */ 62); /* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _release_res_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_1__) if(__WEBPACK_IMPORT_KEY__ !== 'default') (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _release_res_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_1__[key]; }) }(__WEBPACK_IMPORT_KEY__)); /* harmony import */ var _release_res_vue_vue_type_style_index_0_lang_css___WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ./release_res.vue?vue&type=style&index=0&lang=css& */ 64); /* harmony import */ var _E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_runtime_componentNormalizer_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./node_modules/@dcloudio/vue-cli-plugin-uni/packages/vue-loader/lib/runtime/componentNormalizer.js */ 15); var renderjs /* normalize component */ var component = Object(_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_runtime_componentNormalizer_js__WEBPACK_IMPORTED_MODULE_3__["default"])( _release_res_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_1__["default"], _release_res_vue_vue_type_template_id_4cf4cb50___WEBPACK_IMPORTED_MODULE_0__["render"], _release_res_vue_vue_type_template_id_4cf4cb50___WEBPACK_IMPORTED_MODULE_0__["staticRenderFns"], false, null, null, null, false, _release_res_vue_vue_type_template_id_4cf4cb50___WEBPACK_IMPORTED_MODULE_0__["components"], renderjs ) component.options.__file = "pages/release_res/release_res.vue" /* harmony default export */ __webpack_exports__["default"] = (component.exports); /***/ }), /***/ 60: /*!********************************************************************************************************************!*\ !*** C:/Users/LENOVO/Desktop/uni-app/demo1/demo1/pages/release_res/release_res.vue?vue&type=template&id=4cf4cb50& ***! \********************************************************************************************************************/ /*! exports provided: render, staticRenderFns, recyclableRender, components */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_16_0_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_template_js_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_uni_app_loader_page_meta_js_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_release_res_vue_vue_type_template_id_4cf4cb50___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!./node_modules/@dcloudio/vue-cli-plugin-uni/packages/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/@dcloudio/vue-cli-plugin-uni/packages/webpack-preprocess-loader??ref--16-0!./node_modules/@dcloudio/webpack-uni-mp-loader/lib/template.js!./node_modules/@dcloudio/vue-cli-plugin-uni/packages/webpack-uni-app-loader/page-meta.js!./node_modules/@dcloudio/vue-cli-plugin-uni/packages/vue-loader/lib??vue-loader-options!./node_modules/@dcloudio/webpack-uni-mp-loader/lib/style.js!./release_res.vue?vue&type=template&id=4cf4cb50& */ 61); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "render", function() { return _E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_16_0_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_template_js_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_uni_app_loader_page_meta_js_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_release_res_vue_vue_type_template_id_4cf4cb50___WEBPACK_IMPORTED_MODULE_0__["render"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "staticRenderFns", function() { return _E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_16_0_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_template_js_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_uni_app_loader_page_meta_js_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_release_res_vue_vue_type_template_id_4cf4cb50___WEBPACK_IMPORTED_MODULE_0__["staticRenderFns"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "recyclableRender", function() { return _E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_16_0_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_template_js_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_uni_app_loader_page_meta_js_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_release_res_vue_vue_type_template_id_4cf4cb50___WEBPACK_IMPORTED_MODULE_0__["recyclableRender"]; }); /* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "components", function() { return _E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_16_0_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_template_js_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_uni_app_loader_page_meta_js_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_release_res_vue_vue_type_template_id_4cf4cb50___WEBPACK_IMPORTED_MODULE_0__["components"]; }); /***/ }), /***/ 61: /*!********************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************!*\ !*** ./node_modules/@dcloudio/vue-cli-plugin-uni/packages/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/@dcloudio/vue-cli-plugin-uni/packages/webpack-preprocess-loader??ref--16-0!./node_modules/@dcloudio/webpack-uni-mp-loader/lib/template.js!./node_modules/@dcloudio/vue-cli-plugin-uni/packages/webpack-uni-app-loader/page-meta.js!./node_modules/@dcloudio/vue-cli-plugin-uni/packages/vue-loader/lib??vue-loader-options!./node_modules/@dcloudio/webpack-uni-mp-loader/lib/style.js!C:/Users/LENOVO/Desktop/uni-app/demo1/demo1/pages/release_res/release_res.vue?vue&type=template&id=4cf4cb50& ***! \********************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************/ /*! exports provided: render, staticRenderFns, recyclableRender, components */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "render", function() { return render; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "staticRenderFns", function() { return staticRenderFns; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "recyclableRender", function() { return recyclableRender; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "components", function() { return components; }); var components try { components = { uniDataCheckbox: function() { return Promise.all(/*! import() | components/uni-data-checkbox/uni-data-checkbox */[__webpack_require__.e("common/vendor"), __webpack_require__.e("components/uni-data-checkbox/uni-data-checkbox")]).then(__webpack_require__.bind(null, /*! @/components/uni-data-checkbox/uni-data-checkbox.vue */ 209)) } } } catch (e) { if ( e.message.indexOf("Cannot find module") !== -1 && e.message.indexOf(".vue") !== -1 ) { console.error(e.message) console.error("1. 排查组件名称拼写是否正确") console.error( "2. 排查组件是否符合 easycom 规范,文档:https://uniapp.dcloud.net.cn/collocation/pages?id=easycom" ) console.error( "3. 若组件不符合 easycom 规范,需手动引入,并在 components 中注册该组件" ) } else { throw e } } var render = function() { var _vm = this var _h = _vm.$createElement var _c = _vm._self._c || _h } var recyclableRender = false var staticRenderFns = [] render._withStripped = true /***/ }), /***/ 62: /*!**************************************************************************************************************!*\ !*** C:/Users/LENOVO/Desktop/uni-app/demo1/demo1/pages/release_res/release_res.vue?vue&type=script&lang=js& ***! \**************************************************************************************************************/ /*! no static exports found */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_babel_loader_lib_index_js_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_12_1_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_script_js_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_release_res_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!./node_modules/babel-loader/lib!./node_modules/@dcloudio/vue-cli-plugin-uni/packages/webpack-preprocess-loader??ref--12-1!./node_modules/@dcloudio/webpack-uni-mp-loader/lib/script.js!./node_modules/@dcloudio/vue-cli-plugin-uni/packages/vue-loader/lib??vue-loader-options!./node_modules/@dcloudio/webpack-uni-mp-loader/lib/style.js!./release_res.vue?vue&type=script&lang=js& */ 63); /* harmony import */ var _E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_babel_loader_lib_index_js_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_12_1_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_script_js_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_release_res_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_babel_loader_lib_index_js_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_12_1_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_script_js_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_release_res_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__); /* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_babel_loader_lib_index_js_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_12_1_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_script_js_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_release_res_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__) if(__WEBPACK_IMPORT_KEY__ !== 'default') (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_babel_loader_lib_index_js_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_12_1_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_script_js_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_release_res_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0__[key]; }) }(__WEBPACK_IMPORT_KEY__)); /* harmony default export */ __webpack_exports__["default"] = (_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_babel_loader_lib_index_js_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_12_1_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_script_js_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_release_res_vue_vue_type_script_lang_js___WEBPACK_IMPORTED_MODULE_0___default.a); /***/ }), /***/ 63: /*!*********************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************!*\ !*** ./node_modules/babel-loader/lib!./node_modules/@dcloudio/vue-cli-plugin-uni/packages/webpack-preprocess-loader??ref--12-1!./node_modules/@dcloudio/webpack-uni-mp-loader/lib/script.js!./node_modules/@dcloudio/vue-cli-plugin-uni/packages/vue-loader/lib??vue-loader-options!./node_modules/@dcloudio/webpack-uni-mp-loader/lib/style.js!C:/Users/LENOVO/Desktop/uni-app/demo1/demo1/pages/release_res/release_res.vue?vue&type=script&lang=js& ***! \*********************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /* WEBPACK VAR INJECTION */(function(uni) {Object.defineProperty(exports, "__esModule", { value: true });exports.default = void 0; var _cloudbase = _interopRequireDefault(__webpack_require__(/*! ../../helper/cloudbase.js */ 11));function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { default: obj };} // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // var tDialog = function tDialog() {__webpack_require__.e(/*! require.ensure | components/t-dialog */ "components/t-dialog").then((function () {return resolve(__webpack_require__(/*! ../../components/t-dialog.vue */ 202));}).bind(null, __webpack_require__)).catch(__webpack_require__.oe);}; // import uniDataCheckbox from '../../components/uni-data-checkbox/uni-data-checkbox.vue' var chooseLocation = requirePlugin('chooseLocation');var _default = { name: 'releaseRes', components: { tDialog: tDialog // uniDataCheckbox }, data: function data() {return { resTitle: '', resTypeValue: 0, resTypeRange: [{ "value": 0, "text": "学习", "apiPath": "/learning" }, { "value": 1, "text": "运动", "apiPath": "/sport" }, { "value": 2, "text": "玩乐", "apiPath": "/amuse" }], resPersonNum: 2, resPersonNumArrIndex: 0, resPersonNumArr: [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], // resDate:'', resDateText: '2021-06-01', // resTime:'', resSTimeText: '08:00', resETimeText: '10:00', joinDeadLineText: '2021-05-31', resSTime: '', resETime: '', joinDeadLine: '', hasLoca: false, resLoca: {}, resLocaName: '', resLocaDet: '', resRemark: '', userProfile: { realName: '', phoneNum: '', wxid: '', avatar: '' }, ownerUserInfo: '', ownerOpenid: '', dialogShow: false };}, onShow: function onShow() {this.dialogShow = false;var pages = getCurrentPages(); // 获取栈实例 // console.log(pages) // 打印如下 var page = pages[pages.length - 1]; // 获取当前页面的数据,包含页面路由 // console.log(page) // 打印如下 var location = chooseLocation.getLocation(); // console.log(location) if (location) {page.$vm.chooseLocation(location);}}, computed: {}, methods: { resTitleInput: function resTitleInput(e) {this.resTitle = e.detail.value;}, changeResType: function changeResType(e) {console.log(e.detail.value);}, resPersonNumInput: function resPersonNumInput(e) {this.resPersonNumArrIndex = e.target.value;this.resPersonNum = this.resPersonNumArr[this.resPersonNumArrIndex]; // console.log(this.resPersonNum) }, resLocaDetInput: function resLocaDetInput(e) {this.resLocaDet = e.detail.value;}, resRemarkInput: function resRemarkInput(e) {this.resRemark = e.detail.value;}, realNameInput: function realNameInput(e) {this.userProfile.realName = e.detail.value;}, phoneNumInput: function phoneNumInput(e) {this.userProfile.phoneNum = e.detail.value;}, wxidInput: function wxidInput(e) {this.userProfile.wxid = e.detail.value;}, getResDate: function getResDate(e) {console.log(e.target.value);this.resDateText = e.target.value;}, getresSTime: function getresSTime(e) {this.resSTimeText = e.target.value;console.log(e.target.value);}, getresETime: function getresETime(e) {this.resETimeText = e.target.value;console.log(e.target.value);}, getJoinDeadLine: function getJoinDeadLine(e) {this.joinDeadLineText = e.target.value;console.log(e.target.value);}, chooseLoca: function chooseLoca() {var key = 'L6WBZ-SLZRO-RPOWQ-S4VCD-XB2MJ-4CB2O'; //使用在腾讯位置服务申请的key var referer = 'lichees-mp'; //调用插件的app的名称 var location = JSON.stringify({ latitude: 22.532742, longitude: 113.936699 });var category = '生活服务,娱乐休闲';wx.navigateTo({ url: "plugin://chooseLocation/index?key=".concat(key, "&referer=").concat(referer, "&location=").concat(location, "&category=").concat(category) });}, saveRes: function saveRes() {console.log(this.resLocaName);}, sendPost: function sendPost() {var postData = { "openid": this.ownerOpenid, detail: { "loca_geo": this.resLoca, "loca_text": this.resLocaName + this.resLocaDet, "owner": { "openid": this.ownerOpenid, "name": this.userProfile.realName, "nickName": this.userProfile.realName, "phone_number": this.userProfile.phoneNum, "wxid": this.userProfile.wxid, "avatar": 'cloud://cloud1-0gcmjje1d9bf828c.636c-cloud1-0gcmjje1d9bf828c-1305469619/avatar/avatar.jpg' }, "members": [], "person_num": this.resPersonNum, "remarks": this.resRemark }, brief: { "title": this.resTitle, "loca_text": this.resLocaName + ' ' + this.resLocaDet, "res_starttime": this.resSTime.toISOString(), "res_endtime": this.resETime.toISOString(), "person_num": this.resPersonNum, "joined_num": 1, "join_deadline": this.joinDeadLine.toISOString() } };try {var userInfo = uni.getStorageSync('userInfo');if (userInfo) {postData.detail.owner.avatar = userInfo.avatarUrl;postData.detail.owner.nickName = userInfo.nickName;}console.log(postData);this.postNewData(this.resTypeRange[this.resTypeValue].apiPath, postData).then(function (res) {console.log(res);if (res.data.code === '501') {uni.showToast({ title: '发布成功', duration: 2000, position: 'bottom', icon: 'none' });setTimeout(function () {uni.uni.redirectTo({ url: '/pages/home/home?tabIndex=' + this.resTypeValue, success: function success(res) {}, fail: function fail() {}, complete: function complete() {} });}, 2000);} else {uni.showToast({ title: '发布失败', duration: 2000, position: 'bottom', icon: 'none' }); } }); } catch (e) { console.log(e); console.log(postData); uni.showToast({ title: '发布失败', duration: 2000, position: 'bottom', icon: 'none' }); } }, postNewData: function postNewData(path, newData) { return new Promise(function (resolve, reject) { _cloudbase.default.postCloud(path, newData). then(function (res) { resolve(res); }). catch(function (err) { reject(err); }); }); }, comfireBtn: function comfireBtn() { var date = this.dateHelper(this.resDateText); var date2 = this.dateHelper(this.joinDeadLineText); var startTime = this.timeHelper(this.resSTimeText); var endTime = this.timeHelper(this.resETimeText); // console.log(date) // console.log(startTime) // console.log(endTime) this.resSTime = new Date(date.year, date.month - 1, date.day, startTime.hour, startTime.minute); this.resETime = new Date(date.year, date.month - 1, date.day, endTime.hour, endTime.minute); this.joinDeadLine = new Date(date2.year, date2.month - 1, date2.day); console.log(this.resSTime); console.log(this.resETime); console.log(this.joinDeadLine); var errMsgCheck = this.checkFormData(); if (errMsgCheck == '') { console.log('passed check'); } else { console.log(errMsgCheck); uni.showToast({ title: errMsgCheck, duration: 2000, position: 'bottom', icon: 'none' }); // uni.hideLoading(); return; } uni.showLoading({ title: '加载中' }); try { this.ownerOpenid = uni.getStorageSync('openid'); this.ownerUserInfo = uni.getStorageSync('userInfo'); if (this.ownerOpenid && this.ownerUserInfo) { console.log(this.ownerOpenid); uni.hideLoading(); this.sendPost(); } else { var that = this; wx.login({ success: function success(codeRes) { console.log('/wxuser/code/' + codeRes.code); _cloudbase.default.getCloud('/wxuser/code/' + codeRes.code). then(function (res) { console.log(res.data); var resData = res.data; if (resData.code == '101') { that.ownerUserInfo = resData.userInfo; that.ownerOpenid = resData.openid; try { uni.setStorageSync('userInfo', that.ownerUserInfo); uni.setStorageSync('openid', that.ownerOpenid); console.log('saved userInfo openid in localStorage'); that.sendPost(); uni.hideLoading(); } catch (e) { console.log(e); } } else if (resData.code == '-101') { that.ownerOpenid = resData.openid; uni.setStorageSync('openid', that.ownerOpenid); uni.hideLoading(); that.dialogShow = true; } }). catch(function (err) { console.log(err); }); } }); } } catch (e) { console.log(e); } }, dialogCancel: function dialogCancel() { this.dialogShow = false; }, dateHelper: function dateHelper(dateText) { var dateArr = dateText.split('-'); var year = dateArr[0] - 0; var month = dateArr[1] - 0; var day = dateArr[2] - 0; var res = { year: year, month: month, day: day }; return res; }, timeHelper: function timeHelper(timeText) { var timeArr = timeText.split(':'); var hour = timeArr[0] - 0; var minute = timeArr[1] - 0; var res = { hour: hour, minute: minute }; return res; }, checkFormData: function checkFormData() { var mustInfo = [this.resTitle, this.hasLoca, this.userProfile.realName, this.userProfile.phoneNum, this.userProfile.wxid]; console.log(mustInfo); var regNum = /^[0-9]+.?[0-9]*$/; var regPhoneNum = /^1[3-9]\d{9}$/; function trim(s) { return s.replace(/\s+/g, ""); } var errMsg = ''; // for(var i=0; i<mustInfo.length; i++) { // if(mustInfo[i]) { // continue // } // else{ // switch(i){ // case 0: if (regNum.test(trim(mustInfo[0]))) {errMsg = '局子标题不可为纯数字';return errMsg;} if (trim(mustInfo[0]) === '') {errMsg = '局子标题不可为空';return errMsg;} // errMsg = '请输入局子标题' // break; // case 1: if (!mustInfo[1]) {errMsg = '请选择集合地点';return errMsg;} // break; // case 2: if (trim(mustInfo[2]) === '') {errMsg = '请输入姓名';return errMsg;} // break; // case 3: if (trim(mustInfo[3]) === '') {errMsg = '请输入手机号码';return errMsg;} if (!regPhoneNum.test(mustInfo[3])) {errMsg = '手机号码格式错误';return errMsg;} // break; // case 4: if (trim(mustInfo[4]) === '') {errMsg = '请输入微信号';return errMsg;} // break; // } // } // } return errMsg; // return 'passed' }, confirmLogin: function confirmLogin(e) {var _this = this; this.dialogShow = false; wx.getUserProfile({ // lang:'zh_CN', desc: '用于发布信息', success: function success(res) { console.log(res); // console.log(res.userInfo.avatarUrl) _this.ownerUserInfo = res.rawData; uni.setStorage({ key: 'userInfo', data: res.userInfo, success: function success() { console.log('success saved userinfo'); var openid = uni.getStorageSync('openid'); if (openid) { console.log(openid); _cloudbase.default.postCloud('/wxuser/openid/' + openid, res.userInfo). then(function (res) { console.log(res.data); console.log('登陆成功,请再次点击发布'); uni.showToast({ title: '登陆成功,请再次点击发布', duration: 2000, position: 'bottom', icon: 'none' }); }); } } }); }, fail: function fail(err) { console.log(err); } }); }, chooseLocation: function chooseLocation(loca) { console.log(loca); this.resLoca = { "type": "Point", "coordinates": [loca.longitude, loca.latitude] // 数字数组:[经度, 纬度] }; this.resLocaName = loca.name; this.hasLoca = true; } } };exports.default = _default; /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./node_modules/@dcloudio/uni-mp-weixin/dist/index.js */ 1)["default"])) /***/ }), /***/ 64: /*!**********************************************************************************************************************!*\ !*** C:/Users/LENOVO/Desktop/uni-app/demo1/demo1/pages/release_res/release_res.vue?vue&type=style&index=0&lang=css& ***! \**********************************************************************************************************************/ /*! no static exports found */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony import */ var _E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_mini_css_extract_plugin_dist_loader_js_ref_6_oneOf_1_0_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_css_loader_dist_cjs_js_ref_6_oneOf_1_1_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_loaders_stylePostLoader_js_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_6_oneOf_1_2_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_postcss_loader_src_index_js_ref_6_oneOf_1_3_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_release_res_vue_vue_type_style_index_0_lang_css___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!./node_modules/mini-css-extract-plugin/dist/loader.js??ref--6-oneOf-1-0!./node_modules/css-loader/dist/cjs.js??ref--6-oneOf-1-1!./node_modules/@dcloudio/vue-cli-plugin-uni/packages/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/@dcloudio/vue-cli-plugin-uni/packages/webpack-preprocess-loader??ref--6-oneOf-1-2!./node_modules/postcss-loader/src??ref--6-oneOf-1-3!./node_modules/@dcloudio/vue-cli-plugin-uni/packages/vue-loader/lib??vue-loader-options!./node_modules/@dcloudio/webpack-uni-mp-loader/lib/style.js!./release_res.vue?vue&type=style&index=0&lang=css& */ 65); /* harmony import */ var _E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_mini_css_extract_plugin_dist_loader_js_ref_6_oneOf_1_0_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_css_loader_dist_cjs_js_ref_6_oneOf_1_1_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_loaders_stylePostLoader_js_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_6_oneOf_1_2_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_postcss_loader_src_index_js_ref_6_oneOf_1_3_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_release_res_vue_vue_type_style_index_0_lang_css___WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_mini_css_extract_plugin_dist_loader_js_ref_6_oneOf_1_0_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_css_loader_dist_cjs_js_ref_6_oneOf_1_1_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_loaders_stylePostLoader_js_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_6_oneOf_1_2_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_postcss_loader_src_index_js_ref_6_oneOf_1_3_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_release_res_vue_vue_type_style_index_0_lang_css___WEBPACK_IMPORTED_MODULE_0__); /* harmony reexport (unknown) */ for(var __WEBPACK_IMPORT_KEY__ in _E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_mini_css_extract_plugin_dist_loader_js_ref_6_oneOf_1_0_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_css_loader_dist_cjs_js_ref_6_oneOf_1_1_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_loaders_stylePostLoader_js_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_6_oneOf_1_2_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_postcss_loader_src_index_js_ref_6_oneOf_1_3_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_release_res_vue_vue_type_style_index_0_lang_css___WEBPACK_IMPORTED_MODULE_0__) if(__WEBPACK_IMPORT_KEY__ !== 'default') (function(key) { __webpack_require__.d(__webpack_exports__, key, function() { return _E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_mini_css_extract_plugin_dist_loader_js_ref_6_oneOf_1_0_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_css_loader_dist_cjs_js_ref_6_oneOf_1_1_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_loaders_stylePostLoader_js_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_6_oneOf_1_2_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_postcss_loader_src_index_js_ref_6_oneOf_1_3_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_release_res_vue_vue_type_style_index_0_lang_css___WEBPACK_IMPORTED_MODULE_0__[key]; }) }(__WEBPACK_IMPORT_KEY__)); /* harmony default export */ __webpack_exports__["default"] = (_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_mini_css_extract_plugin_dist_loader_js_ref_6_oneOf_1_0_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_css_loader_dist_cjs_js_ref_6_oneOf_1_1_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_loaders_stylePostLoader_js_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_webpack_preprocess_loader_index_js_ref_6_oneOf_1_2_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_postcss_loader_src_index_js_ref_6_oneOf_1_3_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_vue_cli_plugin_uni_packages_vue_loader_lib_index_js_vue_loader_options_E_HBuilderX_HBuilderX_3_1_7_20210330_HBuilderX_plugins_uniapp_cli_node_modules_dcloudio_webpack_uni_mp_loader_lib_style_js_release_res_vue_vue_type_style_index_0_lang_css___WEBPACK_IMPORTED_MODULE_0___default.a); /***/ }), /***/ 65: /*!**************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************!*\ !*** ./node_modules/mini-css-extract-plugin/dist/loader.js??ref--6-oneOf-1-0!./node_modules/css-loader/dist/cjs.js??ref--6-oneOf-1-1!./node_modules/@dcloudio/vue-cli-plugin-uni/packages/vue-loader/lib/loaders/stylePostLoader.js!./node_modules/@dcloudio/vue-cli-plugin-uni/packages/webpack-preprocess-loader??ref--6-oneOf-1-2!./node_modules/postcss-loader/src??ref--6-oneOf-1-3!./node_modules/@dcloudio/vue-cli-plugin-uni/packages/vue-loader/lib??vue-loader-options!./node_modules/@dcloudio/webpack-uni-mp-loader/lib/style.js!C:/Users/LENOVO/Desktop/uni-app/demo1/demo1/pages/release_res/release_res.vue?vue&type=style&index=0&lang=css& ***! \**************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { // extracted by mini-css-extract-plugin if(false) { var cssReload; } /***/ }) },[[58,"common/runtime","common/vendor"]]]); //# sourceMappingURL=../../../.sourcemap/mp-weixin/pages/release_res/release_res.js.map
55.339599
2,352
0.707366
75b7a376f22b3581a6aa40e998d48c0b7fc451b4
197
js
JavaScript
Serveur.js
Vendriix/Serv-Node.js
94b3327222632ba735c26898cb0b3406fec306bd
[ "Unlicense" ]
null
null
null
Serveur.js
Vendriix/Serv-Node.js
94b3327222632ba735c26898cb0b3406fec306bd
[ "Unlicense" ]
null
null
null
Serveur.js
Vendriix/Serv-Node.js
94b3327222632ba735c26898cb0b3406fec306bd
[ "Unlicense" ]
null
null
null
//Tuesday, Aug 14th //By Vendrix //Node.js const http = require('http'); const server = http.createServer(); server.on('request', (req, res) => { res.end('server'); }); server.listen(3000);
14.071429
35
0.634518
75b7ec5567733bb916c1afc19a3340ce0f4fc6ba
129
js
JavaScript
src/core/math/vec2/angleRadians.js
hg42/csg.js
ad49d1f64272db9a943e569ec5ff851fc249b846
[ "MIT" ]
null
null
null
src/core/math/vec2/angleRadians.js
hg42/csg.js
ad49d1f64272db9a943e569ec5ff851fc249b846
[ "MIT" ]
null
null
null
src/core/math/vec2/angleRadians.js
hg42/csg.js
ad49d1f64272db9a943e569ec5ff851fc249b846
[ "MIT" ]
null
null
null
const angleRadians = (vector) => { // y=sin, x=cos return Math.atan2(vector[1], vector[0]) } module.exports = angleRadians
16.125
41
0.658915
75b8b46ac49c286687ffc1acbdc7473b9ee61411
1,676
js
JavaScript
projects/gear-ratio/src/render.js
erik/sketches
0a454ada58dee6db576e93cb2216dd750290329e
[ "MIT" ]
1
2020-02-11T06:00:11.000Z
2020-02-11T06:00:11.000Z
projects/gear-ratio/src/render.js
erik/sketches
0a454ada58dee6db576e93cb2216dd750290329e
[ "MIT" ]
1
2017-09-23T19:41:29.000Z
2017-09-25T05:12:38.000Z
projects/gear-ratio/src/render.js
erik/sketches
0a454ada58dee6db576e93cb2216dd750290329e
[ "MIT" ]
null
null
null
function toDOMNode (thing) { if (thing instanceof Node) { return thing } if (typeof thing === 'function') { return toDOMNode(thing.call(this)) } return document.createTextNode(thing.toString()) } function createElement (tag, attrs, children) { let node = null if (typeof tag === 'string') { const ns = attrs.xmlns || 'http://www.w3.org/1999/xhtml' node = document.createElementNS(ns, tag) } else if (typeof tag === 'function') { node = toDOMNode(tag(attrs, children)) } else if (typeof tag.render === 'function') { const props = {} const remainingAttrs = {} for (const k of (tag.props || [])) { if (!(k in attrs)) { console.warn(`[${tag}]: missing prop: ${k}`) continue } props[k] = attrs[k] } for (const k in attrs) { if (!(k in props)) { remainingAttrs[k] = attrs[k] } } attrs = remainingAttrs node = tag.render.call(props, remainingAttrs) } else { console.error('Unknown tag type', tag) node = toDOMNode(tag) } const callbackRe = /^on([A-Z])/ for (const key in attrs) { const val = attrs[key] if (key === 'class') { node.classList.add(...val.split(' ')) } else if (callbackRe.test(key) && typeof val === 'function') { const event = key.replace(callbackRe, key[2].toLowerCase()) node.addEventListener(event, val) } else { node.setAttribute(key, val) } } children = children || []; (Array.isArray(children) ? children : [children]) .map(ch => ch && toDOMNode(ch)) .forEach(n => n && node.appendChild(n)) return node } // shortcuts export const h = createElement
23.605634
67
0.584726
75ba654c5d7d96adb0b85a3c0ee04276610dcdec
739
js
JavaScript
client/src/main.js
yasamnoya/picterest
2cdf7362d64385ef7750ca096a9372aa145634d6
[ "MIT" ]
null
null
null
client/src/main.js
yasamnoya/picterest
2cdf7362d64385ef7750ca096a9372aa145634d6
[ "MIT" ]
null
null
null
client/src/main.js
yasamnoya/picterest
2cdf7362d64385ef7750ca096a9372aa145634d6
[ "MIT" ]
null
null
null
import Vue from 'vue'; import axios from 'axios'; import 'bootstrap'; import 'bootstrap/dist/css/bootstrap.css'; import { library } from '@fortawesome/fontawesome-svg-core'; import { faTrashAlt, faThumbsUp } from '@fortawesome/free-solid-svg-icons'; import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome'; import VueManonry from 'vue-masonry-css'; import App from './App.vue'; import router from './router'; library.add(faTrashAlt); library.add(faThumbsUp); axios.defaults.baseURL = process.env.VUE_APP_BACKEND_URL; axios.defaults.withCredentials = true; Vue.config.productionTip = false; Vue.use(VueManonry); Vue.component('font-awesome-icon', FontAwesomeIcon); new Vue({ router, render: (h) => h(App), }).$mount('#app');
28.423077
75
0.744249
75bc781bdf3557666afff20d8950218a1db55c97
993
js
JavaScript
js/utils/komposer-utils.js
krizka/tools
554ccd5a76411798cc6cfaae5fba944ba492661a
[ "MIT" ]
1
2020-08-08T01:17:39.000Z
2020-08-08T01:17:39.000Z
js/utils/komposer-utils.js
krizka/tools
554ccd5a76411798cc6cfaae5fba944ba492661a
[ "MIT" ]
null
null
null
js/utils/komposer-utils.js
krizka/tools
554ccd5a76411798cc6cfaae5fba944ba492661a
[ "MIT" ]
null
null
null
/** * Created by kriz on 25/11/16. */ import { Tracker } from 'meteor/tracker'; import { compose } from 'react-komposer'; export function getTrackerLoader(reactiveMapper) { return (props, onData, env) => { let trackerCleanup = null; const handler = Tracker.nonreactive(() => Tracker.autorun(() => { // assign the custom clean-up function. trackerCleanup = reactiveMapper(props, onData, env); })); return () => { if (typeof trackerCleanup === 'function') trackerCleanup(); return handler.stop(); }; }; } export const composeWithTracker = (reactiveMapper, options) => compose(getTrackerLoader(reactiveMapper), options); export function getPromiseLoader(promise) { return (props, onData) => { promise.then(data => onData(null, data), err => onData(err)); }; } export const composeWithPromise = (reactiveMapper, options) => compose(getPromiseLoader(reactiveMapper), options);
30.090909
114
0.636455
75bddeebc11d064009200ef1c6e393b840fa4fd8
331
js
JavaScript
config/layout.js
samb2/SambNodejsCMS
af4fd4f823a34391dbde165ca4d928364828a510
[ "MIT" ]
null
null
null
config/layout.js
samb2/SambNodejsCMS
af4fd4f823a34391dbde165ca4d928364828a510
[ "MIT" ]
null
null
null
config/layout.js
samb2/SambNodejsCMS
af4fd4f823a34391dbde165ca4d928364828a510
[ "MIT" ]
null
null
null
const path = require('path'); const expressLayouts = require('express-ejs-layouts'); module.exports = { public_dir: 'public', view_dir: path.resolve('./resource/views'), view_engine: 'ejs', ejs: { expressLayouts, extractScripts: true, extractStyles: true, master: 'layout' } };
22.066667
54
0.610272
75be5aab5644196c2c708d449fba02cea9c974a1
13,704
js
JavaScript
src/js/panels/rating/base.js
zhenyarudenok/conferences
a6e9be853346ecb7509cc76d3df3ea52686c8803
[ "MIT" ]
null
null
null
src/js/panels/rating/base.js
zhenyarudenok/conferences
a6e9be853346ecb7509cc76d3df3ea52686c8803
[ "MIT" ]
null
null
null
src/js/panels/rating/base.js
zhenyarudenok/conferences
a6e9be853346ecb7509cc76d3df3ea52686c8803
[ "MIT" ]
null
null
null
import React from 'react'; import {connect} from 'react-redux'; import bridge from '@vkontakte/vk-bridge'; import axios from 'axios'; import {closePopout, goBack, openModal, closeModal, openPopout, setPage} from '../../store/router/actions'; import { Avatar, Banner, Group, Panel, PanelHeader, Placeholder, Snackbar, Button, Spinner, PullToRefresh, TabsItem, Tabs, HorizontalScroll, Div, Alert, Search, Cell, Footer } from "@vkontakte/vkui"; import { Icon20CheckCircleFillGreen, Icon16ErrorCircleFill, Icon56ErrorTriangleOutline, Icon56ErrorOutline } from '@vkontakte/icons'; import {hash} from '../../components/modals/Information'; import {Swipeable} from 'react-swipeable'; const isOnline = require('is-online'); var info; var bars = [ {name: "Все", icon: "", selected: true}, {name: "Развлечения", icon: "🎉", selected: false}, {name: "Игры", icon: "🎮", selected: false}, {name: "Общение", icon: "💬", selected: false}, {name: "Музыка", icon: "🎵", selected: false}, {name: "Спорт", icon: "⚽", selected: false}, {name: "Фильмы", icon: "🎥", selected: false}, {name: "Книги", icon: "📚", selected: false} ]; var rating = []; var ratingSort = []; class MainPanelBase extends React.Component { constructor(props) { super(props); this.state = { snackbar: null, bars: [ {name: "Все", icon: "", selected: true}, {name: "Развлечения", icon: "🎉", selected: false}, {name: "Игры", icon: "🎮", selected: false}, {name: "Общение", icon: "💬", selected: false}, {name: "Музыка", icon: "🎵", selected: false}, {name: "Спорт", icon: "⚽", selected: false}, {name: "Фильмы", icon: "🎥", selected: false}, {name: "Книги", icon: "📚", selected: false} ], i: 0, rating: [], ratingSort: [], ratingAll: [], activeTab: "Все", loading: true, search: '', error: '' }; this.showError = this.showError.bind(this); this.showSuccess = this.showSuccess.bind(this); this.onChange = this.onChange.bind(this); this.search = this.search.bind(this); } onChange(e) { this.setState({search: e.target.value}); } get rating() { const search = this.state.search.toLowerCase().trim(); if (this.state.activeTab === "Все") { return rating.filter( ({title}) => title.toLowerCase().indexOf(search) > -1 ); } } get ratingSort() { const search = this.state.search.toLowerCase().trim(); if (this.state.activeTab !== "Все") { return rating.filter( ({title}) => title.toLowerCase().indexOf(search) > -1 ); } } search(search) { const result = this.state.rating.filter( ({title}) => title.toLowerCase().indexOf(this.state.search.toLowerCase()) > -1 ); console.log(result); } showError(text) { if (this.state.snackbar) return; this.setState({ snackbar: <Snackbar layout="vertical" onClose={() => this.setState({snackbar: null})} before={<Icon16ErrorCircleFill width={24} height={24}/>} > {text} </Snackbar> }); } showSuccess(text) { if (this.state.snackbar) return; this.setState({ snackbar: <Snackbar layout="vertical" onClose={() => this.setState({snackbar: null})} before={<Icon20CheckCircleFillGreen width={24} height={24}/>} > {text} </Snackbar> }); } getRating() { // window.location.href.search("?", ""); axios({ method: 'get', url: 'https://conferences-api.evgrg.xyz/rating', headers: { xvk: window.location.search.replace("?", "") } }) .then(res => { rating = res.data; this.setState({ rating: res.data, ratingAll: res.data, loading: false }); }) .catch(error => { this.props.openPopout( <Alert header="Информация" text="Произошла ошибка сервера. Перезайдите в приложение." actions={[{ title: 'Хорошо', autoclose: true, action: this.showImg }]} onClose={() => this.props.closePopout()} /> ); this.setState({ loading: 'error', error: error.toString() }); }); } openInformation(item) { this.getByID(item); } getByID(item) { axios({ method: 'get', url: 'https://conferences-api.evgrg.xyz/getByID?id='+item.id, headers: { xvk: window.location.search.replace("?", "") } }) .then(res => { if (res.data.status === false) { if (item.id === 0) return; return this.showError("Беседа не была добавлена или находится на модерации"); } info = res.data; this.props.openModal("INFORMATION_CONFERENCE"); }) } sortRating(value) { for (var i = 0; i < this.state.rating.length; i++) { if (this.state.rating[i].category.toLowerCase() === value.toLowerCase()) { this.state.ratingSort.push(rating[i]); } } } changeInfo(value, i, type) { this.state.ratingSort.length = 0; this.sortRating(value); if (type === 'click') { this.setState({ activeTab: value, i: i }); } else { if (type === 'swipeRight') { this.setState({ activeTab: value, i: this.state.i - 1 }); } else { this.setState({ activeTab: value, i: this.state.i + 1 }); } } } swipe(motion) { if (motion === 'left') { if (this.state.i + 1 === this.state.bars.length) { return this.changeInfo(this.state.bars[0].name, 0, 'click'); } this.changeInfo(this.state.bars[this.state.i + 1].name); } else { if (this.state.i === 0) { console.log(this.state.i); return this.changeInfo(this.state.bars[7].name, 7, 'click'); } this.changeInfo(this.state.bars[this.state.i - 1].name, null, 'swipeRight'); } } checkHash() { const {id, setPage} = this.props; console.log('VAR - ' + hash); console.log('HASH - ' + window.location.hash.replace("#", "")) if (window.location.hash.replace("#", "") === hash) { return console.log('hash = hash'); } else { this.getByID({id: Number(window.location.hash.replace("#", ""))}); } } componentDidMount() { this.getRating(); this.checkHash(); } render() { const {id, setPage} = this.props; return ( <Panel id={id}> <PanelHeader>Рейтинг</PanelHeader> <PullToRefresh onRefresh={() => this.getRating()} isFetching={this.state.fetching} > <Group separator="hide"> <Tabs> <HorizontalScroll> {this.state.bars.map((item, index) => <TabsItem onClick={() => this.changeInfo(item.name, index, 'click')} selected={this.state.activeTab === item.name} > {item.name} </TabsItem> )} </HorizontalScroll> </Tabs> </Group> <Swipeable onSwipedLeft={() => this.swipe('left')} onSwipedRight={() => this.swipe('right')} > <div> {this.state.activeTab === "Все" && <Group> <Search value={this.state.search} onChange={this.onChange} after={null} /> </Group> } <Group> {this.state.activeTab === 'Все' ? <> {this.rating.map((item, index) => <Banner before={<Avatar size={48} src={item.avatar}/>} header={item.title} subheader={item.shortDescription} asideMode="expand" onClick={() => this.openInformation(item)} /> ) } {this.rating.length === 0 && this.state.loading === false && <Placeholder icon={<Icon56ErrorTriangleOutline/>} header="Тут ничего нет" action={<Button size="m" onClick={() => this.props.openModal("ADD_CONFERENCE")}>Добавить</Button>} > Скорее добавь свою беседу! </Placeholder> } </> : <> {this.state.ratingSort.map((item, index) => <Banner before={<Avatar size={48} src={item.avatar}/>} header={item.title} subheader={item.shortDescription} asideMode="expand" onClick={() => this.openInformation(item)} /> ) } </> } {this.state.ratingSort.length === 0 && this.state.activeTab !== "Все" && this.state.loading === false && <Placeholder icon={<Icon56ErrorTriangleOutline/>} header="Тут ничего нет" action={<Button size="m" onClick={() => this.props.openModal("ADD_CONFERENCE")}>Добавить</Button>} > Скорее добавь свою беседу! </Placeholder> } {this.state.loading === true && <Placeholder icon={<Spinner size="large"/>} header="Загружаемся" /> } {this.state.loading === 'error' && <Placeholder icon={<Icon56ErrorOutline/>} header="Не удалось загрузиться" > {this.state.error} </Placeholder> } </Group> </div> </Swipeable> </PullToRefresh> {this.state.snackbar} </Panel> ); } } const mapDispatchToProps = { setPage, goBack, openPopout, closePopout, openModal, closeModal }; export default connect(null, mapDispatchToProps)(MainPanelBase); export var info;
34.870229
136
0.379086
75be601378db3e62326c3d69b331b02c586a7e86
2,989
js
JavaScript
website/static/js/insurance.js
LegallGuillaume/MyCompta
adef2afe96eefb5a92fd2740a3b18b884b87484d
[ "BSD-2-Clause" ]
null
null
null
website/static/js/insurance.js
LegallGuillaume/MyCompta
adef2afe96eefb5a92fd2740a3b18b884b87484d
[ "BSD-2-Clause" ]
1
2020-07-16T06:14:34.000Z
2020-07-16T10:42:36.000Z
website/static/js/insurance.js
LegallGuillaume/MyCompta
adef2afe96eefb5a92fd2740a3b18b884b87484d
[ "BSD-2-Clause" ]
null
null
null
function add_insurance_fn() { socket = io.connect(); var form = $('#newInsurance'); var data = { insurance_name: form.find('#insurance-name').val(), insurance_type: form.find('#insurance-type').val(), insurance_region: form.find('#insurance-region').val(), insurance_contract: form.find('#insurance-contract').val() }; socket.emit('v3-insurance-add', data); form.find('#insurance-name').val(''); form.find('#insurance-type').val(''); form.find('#insurance-region').val(''); form.find('#insurance-contract').val(''); $('.modal').modal('hide'); } function del_insurance_fn() { socket = io.connect(); var form = $('#deleteInsurance'); var data = { insurance_name: form.find('#insurance-name').val().split(' -- ')[0] }; socket.emit('v3-insurance-delete', data); form.find('#insurance-name').val(''); $('.modal').modal('hide'); } function sel_insurance_fn() { socket = io.connect(); var form = $('#selInsurance'); var data = { insurance_name: form.find('#insurance-name').val().split(' -- ')[0] }; socket.emit('v3-insurance-sel', data); form.find('#insurance-name').val(''); $('.modal').modal('hide'); } function add_card_insurance(data) { var itb = document.getElementById('container-insurance'); var html_line = '<div id="'+ data['name'].replace(' ', '-') +'" class="col-3">' html_line += ' <div class="card mb-3 shadow-gray border-gray" style="max-width: 18rem; background-color: transparent;">' html_line += ' <div class="card-header text-md text-center font-weight-bold co-gray bg-light">'+ data['name'] +' -- ' + data['id'] +'</div>' html_line += ' <div class="card-body text-info">' html_line += ' <h5 class="card-title text-right font-weight-bold">' + data['type'] + ', ' + data['region'] + '</h5>' html_line += ' <p class="card-text text-right sel-insurance">' + (data['sel'] ? data['SELECT'] : data['NOTSELECT']) + '</p>' html_line += ' </div>' html_line += ' </div>' html_line += '</div>' itb.insertAdjacentHTML('afterbegin', html_line); var dinsurance = $('#deleteInsurance'); select = dinsurance.find('#insurance-name')[0]; select.insertAdjacentHTML('afterbegin', '<option id="op_'+ data['name'].replace(' ', '-') +'">'+ data['name'] +' -- ' + data['id'] +'</option>') var sinsurance = $('#selInsurance'); select2 = sinsurance.find('#insurance-name')[0]; select2.insertAdjacentHTML('afterbegin', '<option id="op_'+ data['name'].replace(' ', '-') +'">'+ data['name'] +' -- ' + data['id'] +'</option>') } function del_card_insurance(data) { var itb = document.getElementById(data['name']); itb.remove(); var ito = $('#op_' + data['name'].replace(' ', '-')); ito.remove(); } function sel_card_insurance(data) { var itb = $('#' + data['name']); itb.find('.sel-insurance').text(data['SELECT']) }
36.901235
149
0.582469
75beaa038b3e5bd6da0cab21e82127f3ba39fae3
1,668
js
JavaScript
app/assets/javascripts/comments.js
billgewrgoulas/Treegram-Web-Application
021160c25869119f45c6606bc5b57686be8865a6
[ "MIT" ]
null
null
null
app/assets/javascripts/comments.js
billgewrgoulas/Treegram-Web-Application
021160c25869119f45c6606bc5b57686be8865a6
[ "MIT" ]
null
null
null
app/assets/javascripts/comments.js
billgewrgoulas/Treegram-Web-Application
021160c25869119f45c6606bc5b57686be8865a6
[ "MIT" ]
null
null
null
//fix issue with turbolinks /*$(document).on("turbolinks:load",function(){ $(".cool-new-comment-box").focus(function(event){ $("#text").css({"width": "500px", "height": "100px"}) $("#css-post").show(); $("#css-cancel").show(); }); $("#css-cancel").on("click" , function(){ $("#text").css({"width": "400px", "height": "47px"}) $("#css-post").hide(); $("#css-cancel").hide(); }) }) function newComment(){ if($(" .cool-new-comment-box").val() == ""){ confrim("u must write something"); return; } $.ajax({ url: $("#super-form").attr("action"), dataType: 'Json', type: 'POST', data: $("#super-form").serialize(), success: function(data){ myCallback(data.text,data.email,data.avatar); }, error: function() { confirm("panic monster!!!!!!"); }, }); } function myCallback(text,email,avatar){ if(avatar == "/avatars/thumb/missing.png"){ avatar = "/system/users/avatars/uicon.jpg"; } $(" .cool-new-comment-box").val(""); var newComment = ` <div class="lots-of-divs"> <img src = ${url} class="rounded-circle" style="width: 40px; height:40px;margin-right:3px;"> <div class="comment"> <b>${email} said: </b> </br> <div class="comment-body"> <p> ${text} </p> </div> </div> </div> `; $(" .comments-list").prepend(newComment).fadeIn("slow"); } */ //part 2
15.885714
104
0.456235
75beb84661d399a63a857cdd5b4aa9e7bc73ae97
3,374
js
JavaScript
Genie/www/Code.js
ppml38/Tuxedo-Server-API
3afec153cad9e5e0e4504334251664e7f35abdb2
[ "MIT" ]
1
2020-03-23T10:04:41.000Z
2020-03-23T10:04:41.000Z
Genie/www/Code.js
ppml38/DB2-Tuxedo-Server-API
3afec153cad9e5e0e4504334251664e7f35abdb2
[ "MIT" ]
null
null
null
Genie/www/Code.js
ppml38/DB2-Tuxedo-Server-API
3afec153cad9e5e0e4504334251664e7f35abdb2
[ "MIT" ]
null
null
null
function msgaddr(result) { //console.log("msg loggin"); document.getElementById("air_addr").innerHTML = ""; //document.getElementById("loading").style.visibility = "hidden"; if(result[0][0]!="#ERROR#" & result[0][0]!="#CERROR#" ) { for(var i=0;i<result.length-3;i++) //-3 is because, last 3 rows is because of additional 2 \n\r at the end of response from server { document.getElementById("air_addr").innerHTML +=((i==0?"":"<br>")+result[i][2]+result[i][1].trim()); } } else document.getElementById("air_addr").innerHTML = "No Address found"; } function omsgaddr(result) { //console.log("Omg loggin"); document.getElementById("ogs_addr").innerHTML = ""; //document.getElementById("loading").style.visibility = "hidden"; if(result[0][0]!="#ERROR#" & result[0][0]!="#CERROR#" ) { for(var i=0;i<result.length-3;i++) //-3 is because, last 3 rows is because of additional 2 \n\r at the end of response from server { document.getElementById("ogs_addr").innerHTML +=((i==0?"":"<br>")+result[i][2]+result[i][1].trim()); } } else document.getElementById("ogs_addr").innerHTML = "No Address found"; } function omsgtxt(result) { document.getElementById("ogs_text").innerHTML = ""; //document.getElementById("loading").style.visibility = "hidden"; if(result[0][0]!="#ERROR#" & result[0][0]!="#CERROR#" ) { var prevv=0; for(var i=0;i<result.length-3;i++) //-3 is because, last 3 rows is because of additional 2 \n\r at the end of response from server { if(prevv!=result[i][0]) { document.getElementById("ogs_text").innerHTML +="<br>"; } document.getElementById("ogs_text").innerHTML +=((i==0?"":"<br>")+result[i][1].trim()); prevv = result[i][0]; } } else document.getElementById("ogs_text").innerHTML = "No message"; } function msgtxt(result) { document.getElementById("air_text").innerHTML = ""; //document.getElementById("loading").style.visibility = "hidden"; if(result[0][0]!="#ERROR#" & result[0][0]!="#CERROR#" ) { var prevv=0; for(var i=0;i<result.length-3;i++) //-3 is because, last 3 rows is because of additional 2 \n\r at the end of response from server { if(prevv!=result[i][0]) { document.getElementById("air_text").innerHTML +="<br>"; } document.getElementById("air_text").innerHTML +=((i==0?"":"<br>")+result[i][1].trim()); prevv = result[i][0]; } } else document.getElementById("air_text").innerHTML = "No message"; } function send() { document.getElementById("air_addr").innerHTML = "<marquee direction='right'>o&nbsp&nbspo&nbsp&nbspo&nbsp&nbspo</marquee>"; document.getElementById("air_text").innerHTML = "<marquee direction='right'>o&nbsp&nbspo&nbsp&nbspo&nbsp&nbspo</marquee>"; document.getElementById("ogs_addr").innerHTML = "<marquee direction='right'>o&nbsp&nbspo&nbsp&nbspo&nbsp&nbspo</marquee>"; document.getElementById("ogs_text").innerHTML = "<marquee direction='right'>o&nbsp&nbspo&nbsp&nbspo&nbsp&nbspo</marquee>"; //document.getElementById("loading").style.visibility = "visible"; genie("msgaddr.q!__ID~"+document.getElementById("rq").value ,msgaddr); genie("omsgaddr.q!__ID~"+document.getElementById("rq").value ,omsgaddr); genie("msgtxt.q!__ID~"+document.getElementById("rq").value ,msgtxt); genie("omsgtxt.q!__ID~"+document.getElementById("rq").value ,omsgtxt); }
39.694118
132
0.662418
75bef3cb8f180a41de58986f53f58163e2361bf3
37,318
js
JavaScript
wome.js
ncoden/Bookino
02fac759954b0956e58ddc7c368564213b494df4
[ "Apache-2.0" ]
null
null
null
wome.js
ncoden/Bookino
02fac759954b0956e58ddc7c368564213b494df4
[ "Apache-2.0" ]
null
null
null
wome.js
ncoden/Bookino
02fac759954b0956e58ddc7c368564213b494df4
[ "Apache-2.0" ]
null
null
null
//WOME BETA 0.1 client (WOME_B0.1_client) //Website Oriented Multilanguage Engine - client file for BETA 0.1 //Copyright WOME © 2013-2014 Nicolas Coden. All rights reserved //===== VARIABLES ET INIT ===== //variables partagées principales var e_wome = {}; //informations générales sur wome et le site var e_page = {}; //informations sur le rendu du site et de la page var e_user = {}; //toutes les infos sur l'utilisateur, connecte ou non //variables necessaires à wome var zones = []; var ajax = {}; var l_messages = {}; var l_chronos = {}; var l_forms = {}; var l_infos = {}; var timeout_info = null; var si_focus = false; var si_init = true; var init_pages = {}; var timeout = {}; //===== FONCTIONS ===== //FONCTIONS NECESSAIRES function nl(mot){ var mot = mot.toUpperCase(); return si_defini(l, mot, mot); } function getXMLHttpRequest(){ var xhr = null; if(window.XMLHttpRequest || window.ActiveXObject){ if(window.ActiveXObject){ try{ xhr = new ActiveXObject("Msxml2.XMLHTTP"); }catch(e){ xhr = new ActiveXObject("Microsoft.XMLHTTP"); } }else{ xhr = new XMLHttpRequest(); }; }else{ alert("Votre navigateur est trop ancien. Veuillez intaller Google Chrome pour utiliser correctement Bookino"); return null; }; return xhr; } function url_relative(url_donnee){ //fourni l'url relative de la page var url = url_donnee.split('/'); var taille = Object.keys(url).length; var urlrelative = ''; for(i=3; i<taille; i++){ if(url[i] != ''){ urlrelative += '/'+url[i]; }; }; return urlrelative; } function url_delapage(nom){ return ('/' + langue + '/' + l['P_NOM:'+nom]); } function trouver_cle(e){ //parcour tous les elements et cherche "cle" while(e.parent().length && e.parent().attr('cle') == undefined){ e = e.parent(); } //si trouve, retourne cle if(e.parent().length){ return e.parent().attr('cle'); }else{ return false; }; } function lire_attr(element, attr){ //defini chaine var tableau = {}; var chaine = $(element).attr(attr); if(chaine){ return lire_chaine(chaine); }else{ return false; }; } function lire_chaine(chaine){ //declare regex var regex_chainesimple = /^[a-zA-Z0-9]+$/; var regex_chaine = /^\'(.*)\'$/; var regex_tableau = /^\{(.*)\}$/; var regex_morceaux = /([^\;]+)\;?/; var regex_indexs = /^([^\:]+)\:(.*)$/; var chaine = chaine.trim(); if(chaine.match(regex_chainesimple)){ //si chaine simple return chaine.match(regex_chainesimple)[0]; }else if(chaine.match(regex_chaine)){ //si chaine return chaine.match(regex_chaine)[1]; }else if(chaine.match(regex_tableau)){ //si tableau var tab_chaine = chaine.match(regex_tableau)[1]; var morceaux = tab_chaine.split(regex_morceaux); var tableau = {}; var i = 1; //parcour morceaux while(morceaux[i]){ console.log(morceaux[i]); //si avec index if(morceaux[i].match(regex_indexs) && !lire_chaine(morceaux[i].match(regex_indexs)[0])){ var match = morceaux[i].match(regex_indexs); var index = match[1]; var valeur = lire_chaine(match[2]); tableau[index] = valeur; }else{ //sinon var index = 0; while(tableau[index]){ index++; } var valeur = lire_chaine(morceaux[i]); tableau[index] = valeur; }; i = i + 2; } return tableau; }else{ //sinon return false; }; } // console.log(lire_chaine("chaine")); // console.log(lire_chaine("{0:tableau}")); // console.log(lire_chaine("{0:'tableau';1:'tableau';}")); // console.log(lire_chaine("{'tableau';'tableau';}")); // console.log(lire_chaine("{A:1;B:2;C:3;D:4}")); //console.log(lire_chaine("{A:{'a';1;'index':'c'};B:{'index1':a;'index2':'b';'c'};'chaine1';index0:'chaine2'}")); function si_defini(tableau, index, defaut){ if(typeof(tableau[index]) != 'undefined'){ return tableau[index]; }else{ return defaut; }; } function element_visible(element){ //trouve le parent visuel autour d'un champ //de formulaire var nodename = $(element).get(0).nodeName; var parent = $(element).parent(); if(nodename != 'LABEL'){ if(parent.hasClass('C_champ') || parent.hasClass('C_choix')){ var e_visible = parent.get(0); }else{ var e_visible = element; }; }else{ var e_visible = element; }; return e_visible; } //FONCTIONS BOOKINO function champ_actions(element, sens, e){ if(sens=='focus'){si_focus = true;}; if(sens=='blur'){si_focus = false;}; //si DIV, vise l'element enfant INPUT if(element.nodeName == 'DIV'){ parent = $(element); element = $(element).find('INPUT'); }else{ parent = $(element); element = $(element); }; if(typeof(e)!='undefined' && (e.type=='keydown')){ touche = e.keyCode; }else{ touche = 0; }; //recupere propriétés defaut = element.attr('defaut'); motdepasse = element.attr('motdepasse'); if(typeof(motdepasse)=='undefined'){motdepasse = false;}; valeur = element.val(); if(parent.attr('fermer') != 'undefined'){ fermer = true; }else{ fermer = false; }; if(typeof(defaut)!='undefined' && defaut!=''){ //si focus if(sens=='focus'){ if(valeur == defaut){ element.val(''); element.css('color', 'rgb(46,46,46)'); if(motdepasse){element.attr('type', 'password');}; }; }; //si blur if(sens=='blur'){ if(valeur == ''){ element.val(defaut); element.css('color', 'rgb(143,143,143)'); if(motdepasse){element.attr('type', 'text');}; }; }; //si keydown if(sens=='keydown' && touche>32 && touche<127){ if(valeur == defaut){ element.val(String.fromCharCode(touche)); element.css('color', 'rgb(46,46,46)'); if(motdepasse){element.attr('type', 'password');}; }; if(fermer){ parent.addClass('fermer'); }; }; }; } function champ_fermer(element, verifier){ //selectionne l'element INPUT if(element.nodeName == 'DIV'){ parent = $(element); champ = $(element).find('INPUT'); }else{ parent = $(element); champ = $(element); }; if(typeof(verifier)=='undefined'){ verifier = false; }; if(champ.val()=='' || !verifier){ //retire le 'X' parent.removeClass('fermer'); //vide le champ champ.focus(); champ.val(''); if(parent.is('.recherche_champ')){ recherche_fermer(); }; }; } function raccourcis(e){ touche = e.keyCode; //si touche alphanumérique et aucun element n'a le focus if(touche>32 && touche<127 && !si_focus){ s_touche = String.fromCharCode(touche); if(s_touche=='s' || s_touche=='S'){$('#recherche_champ').select();}; if(e_user.connecte){ if(s_touche=='a' || s_touche=='A'){menu_afficher('amis');}; if(s_touche=='n' || s_touche=='N'){menu_afficher('infos');}; if(s_touche=='m' || s_touche=='M'){menu_afficher('general');}; }; return false; }; } function zone_montrer(id_zone, niveau){ //defini zone precedente if(typeof(zones[id_zone])=='undefined'){ zones[id_zone] = 0; $('.C_zone').css({'-webkit-transition':'none', 'transition':'none'}); zhauteur = $('#zone_'+id_zone+'_0').height(); $('#zone_'+id_zone).css('height', zhauteur); setTimeout(function(){$('.C_zone').css({'-webkit-transition':'height 500ms', 'transition':'height 500ms'});},1); }; setTimeout(function(){ niveau_precedent = zones[id_zone]; //si la zone est sur un niveau différent if(zones[id_zone]!=niveau){ zones[id_zone]=niveau; hauteur = $('#zone_'+id_zone+'_'+niveau).height(); //applique les propriétés $('#zone_'+id_zone).css('overflow', 'hidden'); $('#zone_'+id_zone+'_'+niveau).css('display', 'block'); $('#zone_'+id_zone).css('height', hauteur); $('#zone_'+id_zone+'_'+niveau_precedent).removeClass('visible'); $('#zone_'+id_zone+'_'+niveau).addClass('visible'); setTimeout(function(){ $('#zone_'+id_zone).css('overflow', 'visible'); $('#zone_'+id_zone+'_'+niveau_precedent).css('display', 'none'); },500); }; },2); return false; } function recherche_lancer(recherche, defaut){ taille = recherche.length; $('#recherche_personnes > .contenu > .nombre').html('').addClass('verif'); $('#recherche_autrepersonnes > .contenu > .nombre').html('').addClass('verif'); if(taille>0 && recherche!=defaut){ ajax_ajouter('rechercher', {action:'rechercher', recherche:recherche}, 'un', false, function(reponse, ajax){ connaissances = reponse.connaissances; autresusers = reponse.autresusers; connaissances_html = ''; autresusers_html = ''; for(var i=0; i<connaissances.length; i++){ connaissances_html += '\ <DIV class="C_liste_flottant">\ <A href="/'+l['P_NOM:UTILISATEUR']+'/'+connaissances[i][0]+'" class="C_user">\ <IMG class="image" src="http://f.bookino.org/datas/users/'+connaissances[i][1]+'/profil_45.png"/>\ <DIV class="nom">'+connaissances[i][0]+'</DIV>\ </A>\ </DIV>\ '; } for(var i=0; i<autresusers.length; i++){ autresusers_html += '\ <DIV class="C_liste_flottant">\ <A href="/'+l['P_NOM:UTILISATEUR']+'/'+autresusers[i][0]+'" class="C_user">\ <IMG class="image" src="http://f.bookino.org/datas/users/'+autresusers[i][1]+'/profil_45.png"/>\ <DIV class="nom">'+autresusers[i][0]+'</DIV>\ </A>\ </DIV>\ '; } if(connaissances_html!=''){ $('#recherche_personnes').addClass('trouve'); }else{ $('#recherche_personnes').removeClass('trouve'); }; if(autresusers_html!=''){ $('#recherche_autrepersonnes').addClass('trouve'); }else{ $('#recherche_autrepersonnes').removeClass('trouve'); }; $('#recherche_personnes > .contenu > .nombre').html('('+connaissances.length+')').removeClass('verif'); $('#recherche_autrepersonnes > .contenu > .nombre').html('('+autresusers.length+')').removeClass('verif'); $('#recherche_personnes > .contenu > .texte').html(connaissances_html); $('#recherche_autrepersonnes > .contenu > .texte').html(autresusers_html); }); ajax_priorite('haute', 1); $('.POS_Bookino > .menu').removeClass('liens').addClass('recherche'); }else{ recherche_fermer(); }; } function recherche_fermer(){ $('.POS_Bookino > .menu').removeClass('recherche').addClass('liens'); $('#recherche_personnes').removeClass('trouve'); $('#recherche_autrepersonnes').removeClass('trouve'); $('#recherche_personnes > .contenu > .texte').html(''); $('#recherche_autrepersonnes > .contenu > .texte').html(''); } function ajax_priorite(niveau, temps){ if(niveau=='haute'){ if(temps > ajax.priorites.haute){ ajax.priorites.haute=temps; }; }; if(niveau=='moyenne'){ if(temps > ajax.priorites.moyenne){ ajax.priorites.moyenne=temps; }; }; } function ajax_init(){ ajax = {etat:'attend', actions:{}, temps:0, priorites:{haute:0, moyenne:0}}; setInterval(function(){ //decremente priorités priorite = 'basse'; if(ajax.priorites.haute > 0){ ajax.priorites.haute--; priorite='haute'; }else if(ajax.priorites.moyenne > 0){ ajax.priorites.moyenne--; priorite='moyenne'; }; //lance ajax ajax.temps++; if(priorite=='haute' && ajax.temps>=1){ajax_exec(); ajax.temps=0;}; if(priorite=='moyenne' && ajax.temps>=3){ajax_exec(); ajax.temps=0;}; if(priorite=='basse' && ajax.temps>=10){ajax_exec(); ajax.temps=0;}; }, 1000); setTimeout(function(){ ajax_exec(); }, 1); } function ajax_ajouter(nom, donnees, nbfois, binaire, action_fin, type){ if(binaire && typeof(ajax.actions[nom])=='object'){ //si action inverse, annule console.log('AJAX annulé'); ajax_supprimer(nom); }else{ //sinon ajoute à la liste if(type == undefined){type = 'script';}; if(donnees != null){ donnees['_init'] = si_init; ajax.actions[nom] = {type:type, donnees:donnees, nbfois:nbfois, action_fin:action_fin, etat:'attente'}; }; }; } function ajax_supprimer(nom){ if(typeof(ajax.actions[nom]) == 'object'){ delete ajax.actions[nom]; }; } function ajax_exec(){ taille = Object.keys(ajax.actions).length; //si quelque chose à envoyer if(taille>0 && ajax.etat=='attend'){ ajax.etat = 'envoi'; var envoye = {scripts:{}, forms:{}, donnees:{ 'url_envoi': e_page.url, }}; //recupere les donnees à envoyer for(var nom in ajax.actions){ if(ajax.actions[nom].type == 'form'){ groupe = 'forms'; }else{ groupe = 'scripts'; }; ajax.actions[nom].etat = 'envoi'; envoye[groupe][nom] = ajax.actions[nom].donnees; } url = '/'+e_page.langue; //envoi en ajax $.ajax($.extend(true,{ url: url, type: 'POST', port: 'ajax', dataType: 'json', data: envoye, beforeSend:function(jqXHR, settings){ this.actions = ajax.actions; this.donnees = envoye.donnees; }, success:function(reponses, textStatus, jqXHR){ ajax.etat = 'analyse'; var actions = this.actions; var donnees = this.donnees; console.log('AJAX reponse: ' + Object.keys(reponses).length + ' données'); for(var nom in actions){ //prepare donnes pour la reponse var type = actions[nom].type; var envoye = actions[nom].donnees; var najax = { init: envoye._init, envoye: envoye, donnees: donnees, type: type, }; var action_fin = actions[nom].action_fin; var nombre_fois = actions[nom].nbfois; var reponse = reponses[nom]; if(type == 'form'){ //action pour les formulaires form_id = nom; //affiche "valide" sur le bouton $('#'+form_id+' BUTTON[type=submit]').removeClass('verif').removeClass('serveur').addClass('valide'); setTimeout(function(form_id){ var nom = form_id; //fait action de fin et supprime si une fois if(action_fin != null){action_fin(reponse, najax);}; if(typeof(ajax.actions[nom]) != 'undefined'){ ajax.actions[nom].donnees._init = false; }; if(nombre_fois == 'un'){ajax_supprimer(nom);}; //retabli le formulaire setTimeout(function(form_id){ $('#'+form_id+' BUTTON, #'+form_id+' INPUT, #'+form_id+' SELECT, #'+form_id+' TEXTAREA').attr('disabled', false); $('#'+form_id+' BUTTON[type=submit]').removeClass('valide'); }, 500, form_id); }, 500, form_id); }else{ //action pour les scripts if(typeof(actions[nom])!='undefined'){ if(action_fin != null){action_fin(reponse, najax);}; if(typeof(ajax.actions[nom] != 'undefined')){ ajax.actions[nom].donnees._init = false; }; if(nombre_fois == 'un'){ajax_supprimer(nom);}; }; }; } //execution du js transmis if(typeof(reponses.js) != 'undefined'){ action = new Function(reponses.js); action(); }; ajax.etat = 'attend'; }, error: function(jqXHR, textStatus, errorThrown){ ajax.etat = 'analyse'; var actions = this.actions; var donnees = this.donnees; console.log('AJAX erreur'); console.log(textStatus, errorThrown); for(var nom in actions){ var type = actions[nom].type; //si formulaire, action d'erreur if(type == 'form'){ form_id = nom; setTimeout(function(){ $('#'+form_id+' BUTTON[type=submit]').removeClass('verif').removeClass('valide').addClass('serveur').attr('disabled', false) }, 4000); }; if(typeof(ajax.actions[nom] != 'undefined')){ ajax.actions[nom].donnees._init = false; }; } ajax.etat = 'attend'; }, xhrFields: { onprogress: function(e){ if(e.lengthComputable){ $('.POS_Bookino .chargement').css('width', (50 + e.loaded/e.total*50 + '%')); }; } } }, url)); }; } function ajax_form(form, datas, action_fin){ //calcul des propriétés var form_id = form.id; donnees={}; if(typeof(datas)=='object'){ for(var nom in datas){ nom=nom.trim(); if(datas[nom] == '_value'){ donnees[nom] = $('*[name="'+nom+'"]').val(); }else{ donnees[nom] = datas[nom]; }; } }; donnees['ajax_type'] = 'formulaire'; //affichage chargement $('#'+form_id+' BUTTON[type=submit]').removeClass('serveur').removeClass('valide').addClass('verif'); $('#'+form_id+' BUTTON, #'+form_id+' INPUT, #'+form_id+' SELECT, #'+form_id+' TEXTAREA').attr('disabled', true); //envoi ajax ajax_ajouter(form_id, donnees, action_fin, 'un', false); ajax_priorite('haute', 1); } function langue_date(date_donnee){ if(date_donnee!='' && date_donnee!='undefined' && typeof(date_donnee)!='undefined'){ //defini les variables dates var date = new Date(date_donnee['year'], date_donnee['month']-1, date_donnee['day'], date_donnee['hour'], date_donnee['minute'], date_donnee['second']); var date_now = new Date(); var decalage = (date_now.getTime() - date.getTime()); //calcul le decalage et la date finale decalage = decalage/1000; var annees = Math.floor(decalage/( 3600*24*365)); var reste = decalage - annees* 3600*24*365; var mois = Math.floor((reste)/( 3600*24*30.41)); reste = reste - mois* 3600*24*30.41; var jours = Math.floor((reste)/( 3600*24)); reste = reste - jours* 3600*24; var heures = Math.floor((reste)/( 3600)); reste = reste - heures* 3600; var minutes = Math.floor((reste)/( 60)); reste = reste - minutes* 60; var secondes = Math.floor(reste); //construit la phrase if(decalage < 60){date = ''+secondes+' secondes';} else if(decalage < 60*2){date = '1 minute';} else if(decalage < 3600){date = minutes+' minutes';} else if(decalage < 3600*2){date = '1 heure';} else if(decalage < 3600*24){date = heures+' heures';} else if(decalage < 3600*24*2){date = '1 jour';} else if(decalage < 3600*24*7){date = jours+' jours';} else if(decalage < 3600*24*7*2){date = '1 semaine';} else if(decalage < 3600*24*31){date = jours/4+' semaines';} else if(decalage < 3600*24*31*2){date = '1 mois';} else if(decalage < 3600*24*365){date = mois+' mois';} else if(decalage < 3600*24*365*2){date = '1 an';} else{date = annees+' ans';}; }else{ date = ''; decalage = 0; }; return {date_langue:date, decalage:decalage}; } function page(url){ if(url.length>4 && url.substr(0,4)=='http'){ //si lien externe, enregistre return true; }else{ //si lien interne, change la page if(typeof(ajax.actions['page']) == 'undefined'){ //si nom de page, construit url if(url.charAt(0)!='/'){ url = url_delapage(url); }; //sauvegarde la page actuelle page_actualiser(); //barre de chargement $('.POS_Bookino .chargement').addClass('visible').css('width', '50%'); $('BODY').addClass('verif'); //actions de fin des pages for(init_nom in init_pages){ if(init_pages[init_nom].active && init_pages[init_nom].fin != null){ init_pages[init_nom].fin(); }; } //supprime les actions ajax non constantes for(var nom in ajax.actions){ if(ajax.actions[nom].nbfois == 'page'){ ajax_supprimer(nom); }; } //requete ajax ajax_ajouter('page', {action:'page', url:url}, 'un', false, function(reponse, ajax){ if(reponse && reponse.page){ var titre = reponse.titre; var entete = reponse.entete; var contenu = reponse.contenu; var adresse = reponse.url; var relative = reponse.relative; var logs = reponse.logs; recherche_fermer(); info_toutcacher(); //retire les balises inexistantes $('HEAD>SCRIPT, HEAD>LINK').each(function(){ if((this.id).length>5 && (this.id).substring(0,5)=='head_'){ balise_nom = (this.id).substring(5); if(typeof(entete[balise_nom]) == 'undefined'){ $(this).remove(); if(typeof(init_pages[balise_nom]) != 'undefined'){ init_pages[balise_nom].active = false; }; }; }; }); //rajoute les balises manquantes et actualise les autres for(balise_nom in entete){ if($('[id="head_'+balise_nom+'"]').length == 0){ $('#head_js').before(entete[balise_nom]); }; } $('#head_js').replaceWith(entete['js']); //actions de debut des pages for(init_nom in init_pages){ if(init_pages[init_nom].active && init_pages[init_nom].debut != null){ init_pages[init_nom].debut(); }; } document.title = titre; $('.POS_body').html(contenu); $('.logs').html(logs); //ajoute à l'historique if(window.history.state==null || window.history.state.adresse!=adresse){ window.history.pushState({'titre':titre, 'entete':entete, 'contenu':contenu, 'adresse':adresse}, titre, adresse); }else if(window.history.state!=null && window.history.state.adresse==adresse){ window.history.state.titre = titre; window.history.state.entete = entete; window.history.state.contenu = contenu; window.history.state.adresse = adresse; }; //modifi les liens de la langue $('.U_langue').each(function(){ $(this).attr('href', 'http://bookino.org/' + $(this).attr('langue') + '/' + relative + '?language=' + langue); }); //barre de chargement $('BODY').removeClass('verif'); window.scrollTo(0, 0); $('.POS_Bookino .chargement').css('width', '100%'); setTimeout(function(){ $('.POS_Bookino .chargement').removeClass('visible'); $('.POS_Bookino .chargement').css('width', '0'); }, 100); }; }); ajax_exec(); }; return false; }; } function rediriger(url){ window.location = url; } function page_actualiser(){ var adresse = e_page.url; window.history.replaceState({ 'titre': document.title, 'entete': $('HEAD').html(), 'contenu': $('.POS_body').html(), 'adresse': adresse, }, document.title, adresse); } function form_ajouter(form_nom, actualiser, champs, action_fin){ l_forms[form_nom] = {champs:champs, actualiser:actualiser, action_fin:action_fin}; } function form_verifier(form_nom, champ_nom, evenement){ //si le formulaire existe if(typeof(l_forms[form_nom]) != 'undefined'){ var form_valide = true; var regles = { 'obligatoire': [function(e_champ, valeur, value){return (value=='' || value==undefined || (typeof(e_champ.proprietes)!='undefined' && typeof(e_champ.proprietes.defaut)!='undefined' && e_champ.proprietes.defaut==value));}, ['change'], []], 'taille_min': [function(e_champ, valeur, value){return (value.length < valeur);}, ['change'], ['keyup']], 'taille_max': [function(e_champ, valeur, value){return (value.length > valeur);}, ['change'], ['keyup']], }; //declare si non donné if(typeof(champ_nom)!='undefined' && champ_nom && typeof(l_forms[form_nom].champs[champ_nom])!='undefined'){ var champs = {}; champs[champ_nom] = l_forms[form_nom].champs[champ_nom]; }else{ var champs = l_forms[form_nom].champs; }; if(typeof(evenement) == 'undefined'){var evenement = false;}; //verifi champs suivant evenement for(var nom_champ in champs){ var nom = '[name="form_'+form_nom+'['+nom_champ+']"]'; var necessaire = si_defini(champs[nom_champ], 'necessaire', []); var jq_champ = $(nom); var e_champ = l_forms[form_nom].champs[nom_champ]; //verifi si bouton radio if(jq_champ.get(0).nodeName=='INPUT' && jq_champ.attr('type')=='radio'){ var value = $(nom+':checked').val(); }else{ var value = jq_champ.val(); }; var erreur = false; var erreur_valeur = false; //parcour toutes les regles for(var regle in regles){ if(typeof(necessaire[regle]) != 'undefined'){ var valeur = necessaire[regle]; var fonction = regles[regle][0]; var evenements1 = regles[regle][1]; var evenements2 = regles[regle][2]; //s'il y a une erreur, et que l'evenement principale ou secondaire l'autorise if(fonction(e_champ, valeur, value) //si erreur && ((evenement=='*' || evenements1=='*' || evenements1.indexOf(evenement)>=0) //evenement principal || ((evenements2=='*' || evenements2.indexOf(evenement)>=0) && (typeof(e_champ.erreur)!='undefined')))){ //evenement secondaire form_valide = false; erreur = regle; erreur_valeur = valeur; break; }; }; } form_erreur(form_nom, nom_champ, erreur, erreur_valeur); } return form_valide; }else{ return false; }; } function form_erreur(form_nom, champ_nom, raison, valeur){ //determine champ et element HTML de l'info var nom = '[name="form_'+form_nom+'['+champ_nom+']"]'; var champ = l_forms[form_nom].champs[champ_nom]; var e_visible = element_visible(nom); //si erreur if(raison){ if(typeof(champ.erreur) != 'undefined' && champ.erreur != raison && champ.erreur != false){ info_cacher(e_visible, true); }; //construit phrase var phrase = nl('\'T_'+form_nom+'_'+champ_nom+':'+raison+'\''); phrase = phrase.replace('&'+raison+'&', valeur); //si erreur, affiche $(e_visible).attr('info', 'texte:'+phrase+';couleur:blanc;direction:droite;visible:visible') .addClass('accept_icon accept_border erreur'); info_afficher(e_visible); l_forms[form_nom].champs[champ_nom].erreur = raison; }else{ //si pas d'erreur, retire info_cacher(e_visible, true); $(e_visible).attr('info', '').removeClass('erreur'); l_forms[form_nom].champs[champ_nom].erreur = false; }; } function form_envoyer(form_nom){ //fonction form : ne fait que changer de page (ou actualiser) en // recuperant les données du formulaire & fait la // mise en forme. //verifie validité var form_id = '#form_'+form_nom; var valide = form_verifier(form_nom, false, '*'); if(valide){ var url = $(form_id).attr('action'); var externe = (url.length>4 && url.substring(0,4)=='http'); $(form_id+' BUTTON[type=submit]').addClass('verif'); var form = l_forms[form_nom]; if(typeof(form) == 'undefined' || (url && externe) || form.actualiser){ //si lien externe return true; }else{ //si lien interne ou sans redirection $(form_id+' INPUT, '+form_id+' TEXTAREA, '+form_id+' SELECT, '+form_id+' BUTTON').attr('disabled', 'disabled'); //recupere les valeurs var donnees = {}; $(form_id+' INPUT, '+form_id+' TEXTAREA, '+form_id+' SELECT').each(function(){ var champ_nom = this.name.match(/\[(\w+)]/); if(champ_nom){ //verifi si bouton radio if(this.nodeName=='INPUT' && $(this).attr('type')=='radio'){ var value = $('[name="'+this.name+'"]:checked').val(); }else{ var value = $(this).val(); }; donnees[champ_nom[1]] = value; }; }); //ajoute ajax if(!externe){ ajax_ajouter('form_'+form_nom, donnees, 'un', false, form.action_fin, 'form') if(url){ page(url); }; }; return false; }; }else{ return false; }; } function captcha_actualiser(nom){ $('#captcha_'+nom).attr('src', '/captcha'); } function message(nom, titre, texte, cache, boutons){ //prepare le contenu $('.POS_message .titre').html(titre); $('.POS_message .texte').html(texte); l_messages[nom] = {}; l_messages[nom]['_cache'] = cache; //prepare les boutons html_boutons = ''; for(bnom in boutons){ html_action = boutons[bnom][0]; html_class = boutons[bnom][1]; if(typeof(l[bnom]) != 'undefined'){ bnom = l[bnom]; }; l_messages[nom][bnom] = html_action; html_boutons += '<DIV class="C_bouton ' + html_class + '" onclick="message_action(\'' + nom + '\', \'' + bnom + '\')">' + bnom + '</DIV>'; } $('.POS_message .boutons').html(html_boutons); //affiche le message $('.POS_message').css('display', 'block'); if(cache){$('.POS_cache').css('display', 'block');}; setTimeout(function(){ $('.POS_message').css('opacity', '1'); if(cache){$('.POS_cache').css('opacity', '1');}; }, 1); } function message_fermer(cache){ $('.POS_message').css('opacity', '0'); if(cache){$('.POS_cache').css('opacity', '0');}; setTimeout(function(){ $('.POS_message').css('display', 'none'); if(cache){$('.POS_cache').css('display', 'none');}; }, 100); } function message_action(nom, bnom){ //si message existe if(typeof(l_messages[nom]) != 'undefined' && typeof(l_messages[nom][bnom]) != 'undefined'){ var action = l_messages[nom][bnom]; var cache = l_messages[nom]['_cache']; //si fonction, execute if(typeof(action) == 'function'){ action(); message_fermer(cache); }; //sinon, gere les cas particuliers if(typeof(action) == 'string'){ if(action == '_annuler'){ message_fermer(cache); }; }; delete l_messages[nom]; }; } function info_afficher(element){ //recupere les infos e_visible = element_visible(element); donnees = lire_attr(e_visible, 'info'); if(typeof(donnees) == 'string'){ var nom = donnees.replace(/ /g,""); var titre = ''; var texte = donnees; var couleur = 'noir'; var direction = 'haut'; var fixe = 'nonfixe'; var visible = 'auto'; }else{ var titre = si_defini(donnees, 'titre', ''); var texte = si_defini(donnees, 'texte', ''); var couleur = si_defini(donnees, 'couleur', 'noir'); var direction = si_defini(donnees, 'direction', 'haut'); var fixe = si_defini(donnees, 'fixe', 'nonfixe'); var visible = si_defini(donnees, 'visible', 'auto'); var nom = si_defini(donnees, 'nom', texte).replace(/ /g,""); }; if(nom!='' && texte!=''){ //recupere les tailles et positions var position = $(e_visible).offset(); var largeur = $(e_visible).outerWidth(); var hauteur = $(e_visible).outerHeight(); var x_fenetre = $(document).scrollLeft(); var y_fenetre = $(document).scrollTop(); //prepare la nouvelle bulle var nom_e = '#info_'+nom; if(typeof(l_infos[nom]) == 'undefined'){ if($(nom_e).length == 0){ $('BODY').append('<DIV class="POS_info" id="info_'+nom+'"><DIV class="contenu"></DIV></DIV>'); l_infos[nom] = {titre:titre, texte:texte, couleur:couleur, direction:direction, fixe:fixe, visible:visible} }; }; //calcul le contenu et ecrit var html = ''; if(titre != ''){html += '<DIV class="titre">'+titre+'</DIV>';}; html += texte; $(nom_e+' > .contenu').html(html); //place l'info var largeur_info = $(nom_e).outerWidth(); var hauteur_info = $(nom_e).outerHeight(); var decalage = 10; //emplacements de base (centre) var x = position.left + largeur/2 - largeur_info/2; var y = position.top + hauteur/2 - hauteur_info/2; //puis suivant haut/bas/gauche/droite if(direction == 'haut'){y = position.top - hauteur_info - decalage;}; if(direction == 'bas'){y = position.top + hauteur + decalage;}; if(direction == 'gauche'){x = position.left - largeur_info - decalage;}; if(direction == 'droite'){x = position.left + largeur + decalage;}; if(fixe == 'fixe'){ var position_css = 'fixed'; x -= x_fenetre; y -= y_fenetre; }else{ var position_css = 'absolute'; }; //ajoute les class $(nom_e+' > .contenu').removeClass('blanc noir haut bas gauche droite') .addClass(couleur).addClass(direction); //empeche l'info de disparaitre clearTimeout(timeout['info_'+nom]); //affiche $(nom_e).css({'position':position_css, 'top':y, 'left':x}); if(visible=='visible' || visible=='auto'){ $(nom_e).css({'display':'block'}); setTimeout(function(){ $(nom_e).css('opacity', '1'); }, 1); }; }; } function info_cacher(element, forcer){ //recupere nom e_visible = element_visible(element); donnees = lire_attr(element, 'info'); if(typeof(forcer) == 'undefined'){var forcer = false;}; if(typeof(donnees) == 'string'){ var nom = donnees.replace(/ /g,""); }else{ var texte = si_defini(donnees, 'texte', ''); var nom = si_defini(donnees, 'nom', texte).replace(/ /g,""); }; //si info existe et non bloqué if(typeof(l_infos[nom]) != 'undefined' && (l_infos[nom].visible=='auto' || l_infos[nom].visible=='cache' || forcer)){ var info_nom = '#info_'+nom; //cache $(info_nom).css('opacity', '0'); //supprime timeout['info_'+nom] = setTimeout(function(){ $(info_nom).remove(); delete l_infos[nom]; }, 100, info_nom, nom); }; } function info_toutcacher(){ for(var nom in l_infos){ var info_nom = '#info_'+nom; //cache $(info_nom).css('opacity', '0'); //supprime timeout['info_'+nom] = setTimeout(function(){ $(info_nom).remove(); delete l_infos[nom]; }, 100, info_nom, nom); } } function chrono_ajouter(element){ if($(element).length){ //tri infos var infos = $(element).attr('chrono'); var infos = infos.split(';'); var actions = []; if(infos[5] == 'null'){ var action = 'null'; }else{ var temp = infos[5].match(/^\{(.*)\}$/); temp = temp[1].split(','); var taille = temp.length; for(var i=0; i<taille; i++){ var split = temp[i].split(':'); var numero = split[0]; var action = split[1]; actions[numero] = new Function(action); } }; var taille = Object.keys(l_chronos).length; //ajoute dans tableau l_chronos[infos[0]] = { element: element, temps: infos[1], limite: infos[2], sens: infos[3], afficher: infos[4], actions: actions, etat: 'play', }; }; } function chrono_supprimer(nom){ delete l_chronos[nom]; } function chrono_pause(nom){ //cherche l'index if(typeof(l_chronos[nom]) == 'object'){ l_chronos[nom].etat = 'pause'; }; } function chrono_play(nom){ //cherche l'index if(typeof(l_chronos[nom]) == 'object'){ l_chronos[nom].etat = 'play'; }; } function chrono_temps(nom, temps){ //cherche l'index if(typeof(l_chronos[nom]) == 'object'){ l_chronos[nom].temps = temps; $(l_chronos[nom].element).html(temps); }; } function init_ajouter(adresse, action_debut, action_fin){ init_pages[adresse] = { active: true, debut: action_debut, fin: action_fin }; } function init(){ //SAUVEGARDE LA PAGE page_actualiser(); //RECUPERE LES CHRONOS $("[chrono]").each(function(){ //recupere infos chrono_ajouter(this); }); //LANCE BOUCLE DE CHRONOS setInterval(function(){ for(i in l_chronos){ var element = l_chronos[i].element; var temps = l_chronos[i].temps; var limite = l_chronos[i].limite; var sens = l_chronos[i].sens; var afficher = l_chronos[i].afficher; var actions = l_chronos[i].actions; //fait action if(typeof(actions[temps])=='function'){actions[temps]();}; var etat = l_chronos[i].etat; if(etat == 'play'){ //augmente ou diminu chrono if(sens=='+'){l_chronos[i].temps++; temps++;}; if(sens=='-' && temps>0){l_chronos[i].temps--; temps--;}; //affiche si necessaire if(afficher){ $(element).html(temps); }; //si fin, oubli chrono if(temps == limite){ if(typeof(actions[temps])=='function'){actions[temps]();}; delete(l_chronos[i]); }; } } }, 1000); //LANCE ACTIONS DES PAGES for(nom in init_pages){ init_pages[nom].debut(); } } //INIT ET EVENEMENTS $(document).ready(function(){ si_init = true; init(); ajax_init(); si_init = false; //gere les evenements $(document).on('keyup', '#recherche_champ', function(){recherche_lancer( $(this).val(), $(this).attr('defaut') );}); $(document).on('focus', '#recherche_champ', function(){recherche_lancer( $(this).val(), $(this).attr('defaut') );}); $(document).on('focus', '.C_champ, .C_champ.champ', function(e){champ_actions(this, 'focus', e);}); $(document).on('blur', '.C_champ, .C_champ.champ', function(e){champ_actions(this, 'blur', e);}); $(document).on('keydown', '.C_champ, .C_champ.champ', function(e){champ_actions(this, 'keydown', e);}); $(document).on('keyup', '.C_champ, .C_champ.champ', function(e){champ_fermer(this, true);}); $(document).on('change', '.C_champ, .C_champ.champ', function(e){champ_fermer(this, true);}); $(document).on('click', '[pour=zone_montrer]', function(){zone_montrer( $(this).attr('zone'), $(this).attr('niveau') );}); $(document).on('click', '[pour=champ_fermer]', function(){champ_fermer( this.parentNode );}); $(document).on('click', 'A', function(e){return page( $(this).attr('href') );}); $(document).on('mouseenter', '[info]', function(){info_afficher(this);}); $(document).on('mouseleave', '[info]', function(){info_cacher(this);}); //recupere toutes les touches pour les raccourcis $(document).keypress(function(e){return raccourcis(e);}); //empecher le scroll [scrollcontrole] $(document).on('mousewheel DOMMouseScroll', '[scrollcontrole]', function(e){ var scrollTo = null; if(e.type == 'mousewheel'){ scrollTo = (e.originalEvent.wheelDelta * -1); }else if(e.type == 'DOMMouseScroll'){ scrollTo = 20 * e.originalEvent.detail; }; if(scrollTo){ e.preventDefault(); $(this).scrollTop(scrollTo + $(this).scrollTop()); }; }); //gerer l'historique de la page window.onpopstate = function(e){ if(e.state){ //retire les balises inexistantes $('HEAD').each(function(){ if((this.id).length>5 && (this.id).substring(0,5)=='head_'){ balise_nom = (this.id).substring(5); if(typeof(e.state.entete[balise_nom]) == 'undefined'){ $(this).remove(); }; }; }); //rajoute les balises manquantes for(balise_nom in e.state.entete){ if($('[id="head_'+balise_nom+'"]').length == 0){ $('HEAD').append(e.state.entete[balise_nom]); }; } document.title = e.state.titre; $('.POS_body').html(e.state.contenu); $('.logs').html(e.state.logs); }; }; });
28.058647
140
0.617128
75bf211b60f3374f633df61d1b8f7257585f995d
1,077
js
JavaScript
front-vue2/src/services/EmployeeService.js
Francisco-gui/employeee-crud
1aa39f3c30b4cd0aad1bd46eccfb5779e20dfef1
[ "MIT" ]
3
2022-03-11T20:57:01.000Z
2022-03-11T21:07:23.000Z
front-vue2/src/services/EmployeeService.js
Francisco-gui/employeee-crud
1aa39f3c30b4cd0aad1bd46eccfb5779e20dfef1
[ "MIT" ]
null
null
null
front-vue2/src/services/EmployeeService.js
Francisco-gui/employeee-crud
1aa39f3c30b4cd0aad1bd46eccfb5779e20dfef1
[ "MIT" ]
null
null
null
import Api from './Api'; export default { async createNewEmployee(employee) { try { const response = await Api().post('/employees', employee); return response.data; } catch (error) { return console.log(error); } }, async getEmployees() { try { const response = await Api().get('/employees'); return response.data; } catch (error) { return console.log(error); } }, async getEmployeeId(id) { try { const response = await Api().get(`/employees/${id}`); return response.data; } catch (error) { return console.log(error); } }, async updateEmployee(employee) { try { const id = employee.employee_id; const response = await Api().put(`/employees/${id}`, employee); return response.data; } catch (error) { return console.log(error); } }, async deleteEmployee(id) { try { const response = await Api().delete(`/employees/${id}`); return response.data; } catch (error) { return console.log(error); } }, };
21.117647
69
0.576602
92f9ce0b101bdeb8142197f088f33c7b7cd1f843
1,131
js
JavaScript
public/javascripts/app.product.list.js
GabrielNicolasAvellaneda/silo-production-manager
345e1f84006d19bf854855e7afbf476871b19e5a
[ "Apache-2.0" ]
null
null
null
public/javascripts/app.product.list.js
GabrielNicolasAvellaneda/silo-production-manager
345e1f84006d19bf854855e7afbf476871b19e5a
[ "Apache-2.0" ]
null
null
null
public/javascripts/app.product.list.js
GabrielNicolasAvellaneda/silo-production-manager
345e1f84006d19bf854855e7afbf476871b19e5a
[ "Apache-2.0" ]
null
null
null
/** * Created by developer on 18/10/2015. */ angular.module('app') .controller('ProductListController', function ($scope, $http, $log, $location, $routeParams) { var isRawMaterialListing = function () { return $routeParams.filter; }; $scope.title = isRawMaterialListing()? 'Materiales' : 'Producto'; $scope.subtitle = 'Listado'; $scope.products = []; $scope.loading = true; var path = isRawMaterialListing()? '/api/products' : '/api/products?all=true'; $http.get(path) .then(function (res) { $scope.products = res.data; $scope.loading = false; } ); $scope.hasResults = function () { return $scope.products && $scope.products.length > 0 }; $scope.query = {}; $scope.lastestQuery = {}; $scope.search = function () { $scope.latestQuery = $scope.query; $http.post('/api/products/search', $scope.query).then(function (response) { $scope.products = response.data; }); } });
28.275
98
0.528736
92f9ead6fc4532bb4d70be4ab67d7ae2af61c5aa
3,883
js
JavaScript
src/components/category/component.js
mirocosic/xtrack-mobile
1ca2ebb3b61570abf17749466c44ed891121d9a9
[ "MIT" ]
5
2018-11-10T17:52:33.000Z
2021-12-09T20:22:40.000Z
src/components/category/component.js
mirocosic/xtrack-mobile
1ca2ebb3b61570abf17749466c44ed891121d9a9
[ "MIT" ]
29
2019-04-11T00:13:49.000Z
2021-11-24T20:25:34.000Z
src/components/category/component.js
mirocosic/xtrack-mobile
1ca2ebb3b61570abf17749466c44ed891121d9a9
[ "MIT" ]
null
null
null
import React, { Component } from "react" import PropTypes from "prop-types" import { Alert, View, TouchableOpacity } from "react-native" import { DarkModeContext } from "react-native-dark-mode" import Swipeable from "react-native-gesture-handler/Swipeable" import { RectButton } from "react-native-gesture-handler" import { get, truncate } from "lodash" import Icon from "../icon" import { Copy } from "../typography" import styles from "./styles" import palette from "../../utils/palette" class Category extends Component { static contextType = DarkModeContext countTransactions = catId => { const { transactions } = this.props return transactions.filter( transaction => get(transaction, "categoryId") === catId, ).length } renderDeleteButton = cat => ( <RectButton style={styles.deleteButton} onPress={() => { this.deleteCategory(cat) }}> <Icon type="trash-alt" /> </RectButton> ) renderEditButton = cat => ( <RectButton style={styles.editButton} onPress={() => this.props.navigation.navigate("CategoryEdit", { id: cat.id }) }> <Icon type="pen" /> </RectButton> ) renderActions = cat => ( <View style={{ flexDirection: "row", width: 160 }}> {this.renderDeleteButton(cat)} {this.renderEditButton(cat)} </View> ) deleteCategory = category => { const { remove, removeTransactions } = this.props if (this.countTransactions(category.id) > 0) { Alert.alert("Warning!", "Cannot delete category that has transactions", [ { text: "Cancel", style: "cancel", }, { text: "Delete all transactions", onPress: () => { removeTransactions(category) remove(category) }, }, ]) } else { remove(category) } } render() { const { selectCategory, navigation, data, theme } = this.props const cat = data const darkMode = theme === "system" ? this.context === "dark" : theme === "dark" return ( <Swipeable renderRightActions={() => this.renderActions(cat)} containerStyle={{ borderBottomWidth: 1, borderColor: "gray" }}> <RectButton key={cat.id} style={[styles.wrap, darkMode && styles.wrapDark]} activeOpacity={darkMode ? 0.5 : 0.1} rippleColor={darkMode ? palette.darkGray : palette.lightBlue} onPress={() => navigation.navigate("CategoryEdit", { id: cat.id })}> <View key={cat.id} style={[styles.categoryWrap, darkMode && styles.catWrapDark]}> <View style={{ flexDirection: "row", alignItems: "center", flex: 1 }}> <Icon type={cat.icon} style={{ marginRight: 10 }} textStyle={{ color: get(cat, "color", "blue") }} /> <Copy style={{flexWrap: "wrap", flex: 1}}> {`${truncate(cat.name, {length: 135})} `} <Copy style={{ fontSize: 10 }}>{`(${this.countTransactions(cat.id)})`}</Copy> </Copy> {cat.defaultCategory && ( <Icon type="star" textStyle={{ color: "orange", fontSize: 10 }} /> )} </View> <TouchableOpacity onPress={() => { selectCategory(cat) navigation.navigate("CategoryEdit") }}> <Icon type="chevronRight" style={{ backgroundColor: "transparent" }} textStyle={{ color: "gray" }} /> </TouchableOpacity> </View> </RectButton> </Swipeable> ) } } Category.propTypes = { remove: PropTypes.func.isRequired } export default Category
30.100775
93
0.542107
92fa76579da41dfa04bbe07efccdec58240f6c70
2,560
js
JavaScript
tests/logger/logger.query.test.js
myronovich/horondi_client_be
d1cbbdf6740241c71c0488508ac5462118545f03
[ "MIT" ]
15
2020-10-04T10:51:05.000Z
2022-01-13T16:15:51.000Z
tests/logger/logger.query.test.js
myronovich/horondi_client_be
d1cbbdf6740241c71c0488508ac5462118545f03
[ "MIT" ]
894
2020-09-03T16:42:38.000Z
2022-03-31T16:34:06.000Z
tests/logger/logger.query.test.js
myronovich/horondi_client_be
d1cbbdf6740241c71c0488508ac5462118545f03
[ "MIT" ]
11
2020-09-27T14:35:42.000Z
2022-01-15T18:37:46.000Z
const logger = require('../../logger'); const { initLogger } = require('../../loggerHttp'); const { regularLogMessage, logLevels, totalLevelsCount, logString, matchLogString, messageString, dbUri, } = require('./logger.variables'); const loggerHttp = initLogger(dbUri); let logMockFn; let mockStdoutWrite; let mockStdout; let mockFilestream; describe('Logger looks query', () => { beforeEach(() => { logMockFn = jest.fn(() => regularLogMessage); mockStdoutWrite = jest .spyOn(process.stdout, 'write') .mockImplementation(() => true); mockStdout = jest.spyOn(console, 'log').mockImplementation(() => {}); mockFilestream = jest .spyOn(loggerHttp, 'log') .mockImplementation(() => true); }); it('Should receive loggers', () => { expect(logger).toBeDefined(); expect(loggerHttp).toBeDefined(); }); it('Should log call several times', () => { logLevels.forEach(level => logger.log({ level, message: logMockFn() })); expect(logMockFn).toHaveBeenCalled(); expect(logMockFn.mock.calls.length).toBe(totalLevelsCount); }); it('Should write message to console', () => { const log = logger.log('info', logString); expect(log).not.toBeUndefined(); expect(mockStdoutWrite).toHaveBeenCalledWith( expect.stringMatching(matchLogString) ); expect(mockStdoutWrite).toHaveBeenCalledTimes(1); }); it('Should write full string', () => { const log = logger.info(regularLogMessage); const log2 = logger.error(regularLogMessage); expect(log).not.toBeUndefined(); expect(log2).not.toBeUndefined(); expect(mockStdoutWrite).toHaveBeenCalledWith( expect.stringMatching(regularLogMessage) ); expect(mockStdoutWrite).toHaveBeenCalledTimes(2); }); it('Should write logs to file', async () => { const logsCount = 5; for (let i = 0; i < logsCount; i++) { loggerHttp.log({ level: 'info', message: messageString }); loggerHttp.error(logString); } expect(mockFilestream).toHaveBeenCalledTimes(logsCount); }); it('Should write log to database and file without errors', () => { const logFn = () => { loggerHttp.log({ level: 'info', message: messageString }); loggerHttp.error(logString); }; expect(() => { logFn(); }).not.toThrow(); }); afterEach(() => { mockStdoutWrite.mockRestore(); mockStdoutWrite.mockClear(); mockStdout.mockRestore(); mockStdout.mockClear(); mockFilestream.mockRestore(); mockFilestream.mockClear(); }); });
26.391753
76
0.648047
92fada2e5722df21ced2b44af87d54b5b839259b
197
js
JavaScript
app/lib/httpClient.js
chuongxl/SoccerTV
73c27799646c2e41c61eae14be65867af0ec73a0
[ "MIT" ]
null
null
null
app/lib/httpClient.js
chuongxl/SoccerTV
73c27799646c2e41c61eae14be65867af0ec73a0
[ "MIT" ]
null
null
null
app/lib/httpClient.js
chuongxl/SoccerTV
73c27799646c2e41c61eae14be65867af0ec73a0
[ "MIT" ]
null
null
null
export const downloadHTMLAsync = async (url) => { try { let res = await fetch(url); let result = await res.text(); return result; } catch (error) { console.error(error); } };
19.7
49
0.598985
92fafbb1985acad7d9ba61098d12723abdf70d0b
408
js
JavaScript
src/timspec/exports.js
axkibe/tim.js
7e9a66334ba102f41db776fd51d2c71e86bf1043
[ "MIT" ]
1
2020-07-23T19:45:06.000Z
2020-07-23T19:45:06.000Z
src/timspec/exports.js
axkibe/tim.js
7e9a66334ba102f41db776fd51d2c71e86bf1043
[ "MIT" ]
null
null
null
src/timspec/exports.js
axkibe/tim.js
7e9a66334ba102f41db776fd51d2c71e86bf1043
[ "MIT" ]
null
null
null
/* | A group of exports */ 'use strict'; tim.define( module, ( def, export_group ) => { if( TIM ) { def.group = [ 'string' ]; } const fs = require( 'fs' ); /* | Creates it from a "exports.json" file */ def.static.createFromFile = function( filename ) { const text = fs.readFileSync( filename ); const group = JSON.parse( text ); return export_group.create( 'group:init', group ); }; } );
11.333333
51
0.610294
92fd67c9b1b91c0429809e8c22e257a7cf21eb92
2,067
js
JavaScript
lib/-alerts.js
estebanrfp/dKanban
a75ff6b3e9bc916d83e9a3bdacdd2ac75b0e7e25
[ "MIT" ]
12
2020-09-05T23:57:32.000Z
2021-12-17T06:56:35.000Z
lib/-alerts.js
estebanrfp/dKanban
a75ff6b3e9bc916d83e9a3bdacdd2ac75b0e7e25
[ "MIT" ]
null
null
null
lib/-alerts.js
estebanrfp/dKanban
a75ff6b3e9bc916d83e9a3bdacdd2ac75b0e7e25
[ "MIT" ]
1
2021-08-17T09:56:34.000Z
2021-08-17T09:56:34.000Z
function x (e) { const div = e.target.parentElement div.style.opacity = '0' setTimeout(() => { div.style.display = 'none' }, 600) } function Alert (message, mode = null) { document.querySelector('.notifications').innerHTML += ` <div class="alert ${ mode }"> <span class="closebtn" onclick="x(event)">&times;</span> ${ message } </div>` } const closes = document.getElementsByClassName('closebtn') let time = 600 for (const x of closes) { x.onclick = e => { const div = e.target.parentElement div.style.opacity = '0' setTimeout(() => { div.style.display = 'none' }, 600) } setTimeout(() => x.click(), time) time = time + 1800 } export default Alert // alert('<strong>Danger!</strong> Indicates a dangerous or potentially negative action.') // alert('<strong>Success!</strong> Indicates a successful or positive action.', 'success') // alert('<strong>Info!</strong> Indicates a neutral informative change or action.', 'info') // alert('<strong>Warning!</strong> Indicates a warning that might need attention.', 'warning') // const close = document.getElementsByClassName('closebtn') // let time = 600 // for (const x of close) { // x.onclick = e => { // const div = e.target.parentElement // div.style.opacity = '0' // setTimeout(() => { div.style.display = 'none' }, 600) // } // setTimeout(() => x.click(), time) // time = time + 1800 // } // let time = 600 // function alert (message, mode = null) { // const div = document.createElement('div') // div.classList.add('alert') // div.classList.add(mode) // div.innerHTML = message // const close = document.createElement('span') // close.className = 'closebtn' // close.innerHTML = '&times;' // close.onclick = e => { // remove // const div = e.target.parentElement // div.style.opacity = '0' // setTimeout(() => { div.style.display = 'none' }, 600) // } // div.appendChild(close) // document.querySelector('.notifications').appendChild(div) // setTimeout(() => button.click(), time) // time = time + 100 // }
30.850746
95
0.628931
92fdbda47c21cf6c1996aeb0e2631163cd7c368c
522
js
JavaScript
src/client/vue/src/store/index.js
akeating/pespa
f6be1a61cdcbdf0b7ee7ce20161504300ed4d0e4
[ "MIT" ]
28
2017-04-07T03:23:30.000Z
2021-09-29T13:41:04.000Z
src/client/vue/src/store/index.js
akeating/pespa
f6be1a61cdcbdf0b7ee7ce20161504300ed4d0e4
[ "MIT" ]
null
null
null
src/client/vue/src/store/index.js
akeating/pespa
f6be1a61cdcbdf0b7ee7ce20161504300ed4d0e4
[ "MIT" ]
7
2017-10-22T10:47:53.000Z
2021-04-21T23:11:22.000Z
import Vue from 'vue'; import Vuex from 'vuex'; import mutations from './mutations'; import actions from './actions'; Vue.use(Vuex); // root state object. const state = { currentUser: null, counter: { version: NaN, count: NaN }, connected: false }; // getters are functions const getters = {}; // A Vuex instance is created by combining the state, mutations, actions, // and getters. export default new Vuex.Store({ strict: process.env.NODE_ENV !== 'production', state, getters, actions, mutations });
19.333333
73
0.689655
92fe6750721219f359165430fd89fc93a2dca9d1
2,324
js
JavaScript
lib/init.js
MarcLoupias/resume-cli
5aaf9b8d610e8b4a1e259048e3c58d2630a60da3
[ "MIT" ]
1
2017-09-13T20:19:59.000Z
2017-09-13T20:19:59.000Z
lib/init.js
MarcLoupias/resume-cli
5aaf9b8d610e8b4a1e259048e3c58d2630a60da3
[ "MIT" ]
1
2019-06-05T19:49:30.000Z
2019-06-05T21:01:28.000Z
lib/init.js
MarcLoupias/resume-cli
5aaf9b8d610e8b4a1e259048e3c58d2630a60da3
[ "MIT" ]
1
2019-04-22T20:50:15.000Z
2019-04-22T20:50:15.000Z
var fs = require('fs'); var read = require('read'); var resumeJson = require('resume-schema').resumeJson; var chalk = require('chalk'); // slowly replace colors with chalk function fillInit() { console.log('\nThis utility will generate a resume.json file in your current working directory.'); console.log('Fill out your name and email to get started, or leave the fields blank.'); console.log('All fields are optional.\n'); console.log('Press ^C at any time to quit.'); read({ prompt: 'name: ' }, function(er, name) { if (er) { console.log(); process.exit(); } read({ prompt: 'email: ' }, function(er, email) { if (er) { console.log(); process.exit(); } resumeJson.basics.name = name; resumeJson.basics.email = email; fs.writeFileSync(process.cwd() + '/resume.json', JSON.stringify(resumeJson, undefined, 2)); console.log('\nYour resume.json has been created!'.green); console.log(''); console.log('To generate a formatted .html .md .txt or .pdf resume from your resume.json'); console.log('type: `resume export [someFileName]` including file extension eg: `resume export myresume.html`'); console.log('\nYou can optionally specify an available theme for html and pdf resumes using the --theme flag.'); console.log('Example: `resume export myresume.pdf --theme flat`'); console.log('Or simply type: `resume export` and follow the prompts.'); console.log(''); process.exit(); callback(true); }); }); } function init() { if (fs.existsSync('./resume.json')) { console.log(chalk.yellow('There is already a resume.json file in this directory.')); read({ prompt: 'Do you want to override? [y/n]:' }, function(er, answer) { if (er) { console.log(); process.exit(); } if (answer === 'y') { fillInit(); } else { process.exit(); } }); } else { fillInit(); } } module.exports = init; //todo: fix success wording
31.835616
124
0.540017
13008952bdb156e6e2f6cb77e30a155396548776
5,052
js
JavaScript
spot-client/src/index.js
CommanderRoot/jitsi-meet-spot
1bb0a1a4715cd1eb580c26e26f52ed51909788a9
[ "Apache-2.0" ]
72
2017-09-16T14:47:27.000Z
2021-11-19T19:23:06.000Z
spot-client/src/index.js
CommanderRoot/jitsi-meet-spot
1bb0a1a4715cd1eb580c26e26f52ed51909788a9
[ "Apache-2.0" ]
262
2017-08-17T11:09:12.000Z
2022-03-25T18:42:49.000Z
spot-client/src/index.js
thexdesk/jitsi-meet-spot
8913542261a3c9b715d3600d8231fbfd1f921213
[ "Apache-2.0" ]
46
2017-08-02T14:03:15.000Z
2022-03-22T08:09:19.000Z
import defaultsDeep from 'lodash.defaultsdeep'; import React from 'react'; import { render } from 'react-dom'; import { Provider } from 'react-redux'; import { Router } from 'react-router-dom'; import { createStore } from 'redux'; import thunk from 'redux-thunk'; import 'common/css'; import { SegmentHandler, analytics } from 'common/analytics'; import { globalDebugger } from 'common/debugging'; import { isElectron } from 'common/detection'; import { history } from 'common/history'; import { logger } from 'common/logger'; import reducers, { getAnalyticsAppKey, getDesktopSharingFramerate, getDeviceId, getExternalApiUrl, routeChanged, setBootstrapStarted, setDefaultValues, setSetupCompleted } from 'common/app-state'; import { setPermanentPairingCode, SpotBackendService } from 'common/backend'; import 'common/i18n'; import { MiddlewareRegistry, ReducerRegistry, StateListenerRegistry } from 'common/redux'; import { RemoteControlServiceSubscriber, remoteControlClient } from 'common/remote-control'; import { getBoolean, getPersistedState, loadScript, setPersistedState } from 'common/utils'; import { ExternalApiSubscriber } from 'spot-remote/external-api'; import App from './app'; const queryParams = new URLSearchParams(window.location.search); const startParams = {}; for (const [ key, value ] of queryParams.entries()) { startParams[key] = value; } const store = createStore( ReducerRegistry.combineReducers(reducers), defaultsDeep({}, { spotTv: { // This needs to overwrite the persisted value if it's defined in the params volumeControlSupported: startParams.volumeControlSupported ? getBoolean(startParams.volumeControlSupported) : undefined } }, getPersistedState(), { config: { ...setDefaultValues(window.JitsiMeetSpotConfig) }, setup: { startParams }, spotTv: { // Will get overridden on Spot-Remote by Spot-TV updates. electron: isElectron() } }), MiddlewareRegistry.applyMiddleware(thunk) ); // StateListenerRegistry StateListenerRegistry.subscribe(store); const remoteControlServiceSubscriber = new RemoteControlServiceSubscriber(); const externalApiSubscriber = new ExternalApiSubscriber(message => { const externalListener = window.opener || (window.parent === window ? null : window.parent); externalListener && externalListener.postMessage(message, '*'); }); globalDebugger.register('store', store); store.subscribe(() => { setPersistedState(store); const newReduxState = store.getState(); remoteControlServiceSubscriber.onUpdate(newReduxState); externalApiSubscriber.onUpdate(newReduxState); }); // Allow selenium tests to skip the setup flow. const testRefreshToken = queryParams.get('testBackendRefreshToken'); if (testRefreshToken) { // Permanent paring code is required to get through intermediate layers down to the backend service. // When refresh token is stored the paring code is not really used. This eventually should be refactored in // future to check for refresh token rather than rely on the permanent pairing code being present. // Here come up with just any permanent code, because it doesn't matter. const permanentPairingCode = '12345678'; SpotBackendService.injectTestRefreshToken(permanentPairingCode, testRefreshToken); store.dispatch(setPermanentPairingCode(permanentPairingCode)); store.dispatch(setSetupCompleted()); } store.dispatch(setBootstrapStarted()); const reduxState = store.getState(); const deviceId = getDeviceId(reduxState); const analyticsAppKey = getAnalyticsAppKey(reduxState); if (analyticsAppKey) { analytics.addHandler(new SegmentHandler(deviceId, analyticsAppKey)); } // eslint-disable-next-line max-params window.onerror = (message, url, lineNo, columnNo, error) => { logger.error('Uncaught error', { columnNo, lineNo, message: message || (error && error.message), error: error && error.stack, url }); }; window.onunhandledrejection = event => { if (event.reason instanceof Error) { const { message, stack } = event.reason; logger.error('Unhandled promise rejection', { message, stack }); return; } logger.error('Unhandled promise rejection', { message: event.reason, stack: 'n/a' }); }; remoteControlClient.configureWirelessScreensharing({ desktopSharingFrameRate: getDesktopSharingFramerate(reduxState) }); history.listen(location => { store.dispatch(routeChanged(location)); }); loadScript(getExternalApiUrl(reduxState)) .then(() => { render( <Provider store = { store }> <Router history = { history }> <App /> </Router> </Provider>, document.getElementById('root') ); });
29.202312
111
0.684877
1300d926c6ad8b254f4cb3f2cbe1b1203db6bf7a
217
js
JavaScript
services/database/server/imports/api/methods/calculations/index.js
atomsandbits/atomsandbits
796b3275eedfd1bdc2d6d0fb444fffe6a181b1f6
[ "MIT" ]
1
2018-05-11T00:05:29.000Z
2018-05-11T00:05:29.000Z
services/database/server/imports/api/methods/calculations/index.js
atomsandbits/atomsandbits
796b3275eedfd1bdc2d6d0fb444fffe6a181b1f6
[ "MIT" ]
null
null
null
services/database/server/imports/api/methods/calculations/index.js
atomsandbits/atomsandbits
796b3275eedfd1bdc2d6d0fb444fffe6a181b1f6
[ "MIT" ]
1
2020-10-27T19:24:30.000Z
2020-10-27T19:24:30.000Z
import './create-calculation'; import './ping-calculation-running'; import './save-calculation-result'; import './save-intermediate-calculation-result'; import './set-calculation-running'; import './create-project';
27.125
48
0.751152
1300daaafb9872ff49e49f795dd6c1cbdef5eecd
1,005
js
JavaScript
src/helpers/routes.js
lesliecdubs/pamela-rae-schuller
42e38ca06b6e1c16b576337591c1e0b9e0cd5d2d
[ "MIT" ]
null
null
null
src/helpers/routes.js
lesliecdubs/pamela-rae-schuller
42e38ca06b6e1c16b576337591c1e0b9e0cd5d2d
[ "MIT" ]
13
2021-01-01T11:21:35.000Z
2022-02-28T02:04:29.000Z
src/helpers/routes.js
lesliecdubs/pamela-rae-schuller
42e38ca06b6e1c16b576337591c1e0b9e0cd5d2d
[ "MIT" ]
null
null
null
export const allRoutes = { home: '', meet: 'about', media: 'media', comedy: 'comedy', tour: 'tour', press: 'press', book: 'book', links: 'links', youtube: 'https://www.youtube.com/channel/UClgywpOftm8vFXCC8yzMfpw', facebook: 'https://www.facebook.com/PamelaRaeSchuller/', twitter: 'https://twitter.com/PamelaComedy', instagram: 'https://www.instagram.com/pamelacomedy/', } const routeFactory = (name, path, opts = {}) => ({ name, path, ...opts }) export const menuRoutes = [ routeFactory('Meet Pam', allRoutes.meet), routeFactory('Media', allRoutes.media), routeFactory('Comedy', allRoutes.comedy), routeFactory('Tour', allRoutes.tour), routeFactory('Press', allRoutes.press), ] export const bookRoute = routeFactory('Book Now', allRoutes.book) export const socialRoutes = [ routeFactory('Youtube', allRoutes.youtube), routeFactory('Facebook', allRoutes.facebook), routeFactory('Twitter', allRoutes.twitter), routeFactory('Instagram', allRoutes.instagram), ]
29.558824
73
0.701493
130102903ddd9c02abf1df87cfda467fca6d99f6
740
js
JavaScript
scripts/check-extraneous.js
romaindurand/maju.app
efe4a5b2351bf102846da52c85fe4c21751a7541
[ "MIT" ]
12
2018-12-03T22:42:09.000Z
2021-12-29T16:40:45.000Z
scripts/check-extraneous.js
romaindurand/maju.app
efe4a5b2351bf102846da52c85fe4c21751a7541
[ "MIT" ]
40
2018-06-28T00:13:03.000Z
2021-12-29T16:52:44.000Z
scripts/check-extraneous.js
romaindurand/maju.app
efe4a5b2351bf102846da52c85fe4c21751a7541
[ "MIT" ]
1
2019-01-22T10:02:25.000Z
2019-01-22T10:02:25.000Z
require('dotenv').config() const MongoClient = require('mongodb').MongoClient const mongoUrl = `mongodb://${process.env.MONGO_USER}:${process.env.MONGO_PASSWORD}` + `@${process.env.MONGO_HOST}:${process.env.MONGO_PORT}?authMechanism=DEFAULT&authSource=${process.env.MONGO_DATABASE}` MongoClient.connect(mongoUrl, { useNewUrlParser: true }, async (err, client) => { if (err) throw err const db = client.db(process.env.MONGO_DATABASE) const polls = await db.collection('polls').find({}).toArray() const pollsId = polls.map(poll => poll.uid) const votes = await db.collection('votes').find({}).toArray() const orphanVotes = votes.filter(vote => !pollsId.includes(vote.pollId)) console.log({orphanVotes}) client.close() })
41.111111
119
0.721622
130181ca28b305cd66c32870b8d6582948f433bc
1,363
js
JavaScript
paradigms/1643.js
DavidWesley/URI-Online-Judge-Only-JS
0ad4adfe084a38cc55ccc0d110c0a71495622b7e
[ "MIT" ]
null
null
null
paradigms/1643.js
DavidWesley/URI-Online-Judge-Only-JS
0ad4adfe084a38cc55ccc0d110c0a71495622b7e
[ "MIT" ]
null
null
null
paradigms/1643.js
DavidWesley/URI-Online-Judge-Only-JS
0ad4adfe084a38cc55ccc0d110c0a71495622b7e
[ "MIT" ]
null
null
null
function binetFormule(nth) { if (nth < 0) return 0 const sqrt5 = Math.sqrt(5) const nthPower = (equation) => Math.pow(equation / 2, nth) / sqrt5 return Math.round(nthPower(1 + sqrt5) - nthPower(1 - sqrt5)) } class BruceAlgorithm { static #SIZE = 22 static #FIBS = new Map(Array.from({ length: this.#SIZE }, (_, i) => [i + 1, binetFormule(i + 2)])) static decToFibNotation(num = 0) { const notation = new Array(this.#SIZE).fill(0) for (let index = this.#SIZE - 1; index > 0 && num > 0; index--) { const fib = this.#FIBS.get(index) if (num - fib >= 0) { notation[this.#SIZE - index] = 1 num -= fib } } return notation } static fibToDecNumber(notation = Array(this.#SIZE).fill(0)) { let res = 0 for (let index = 1; index < notation.length; index++) res += notation[notation.length - index] * this.#FIBS.get(index) return res } } function convertKilometersToMilesFromBruceAlgorithm(num) { const fibNotation = BruceAlgorithm.decToFibNotation(num) fibNotation.pop() return BruceAlgorithm.fibToDecNumber(fibNotation) } const { readFileSync } = require("fs") const [numLines, ...lines] = readFileSync("/dev/stdin", "utf8").split("\n") function main() { const responses = lines .slice(0, +numLines) .map((line) => convertKilometersToMilesFromBruceAlgorithm(+line)) console.log(responses.join("\n")) } main()
25.716981
99
0.66471
1303136c296ff9e98aefb2a76b72b93028ff0aaa
1,690
jsm
JavaScript
B2G/gecko/browser/devtools/responsivedesign/CmdResize.jsm
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
3
2015-08-31T15:24:31.000Z
2020-04-24T20:31:29.000Z
B2G/gecko/browser/devtools/responsivedesign/CmdResize.jsm
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
null
null
null
B2G/gecko/browser/devtools/responsivedesign/CmdResize.jsm
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
3
2015-07-29T07:17:15.000Z
2020-11-04T06:55:37.000Z
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ const { classes: Cc, interfaces: Ci, utils: Cu } = Components; this.EXPORTED_SYMBOLS = [ ]; Cu.import("resource:///modules/devtools/gcli.jsm"); /* Responsive Mode commands */ gcli.addCommand({ name: 'resize', description: gcli.lookup('resizeModeDesc') }); gcli.addCommand({ name: 'resize on', description: gcli.lookup('resizeModeOnDesc'), manual: gcli.lookup('resizeModeManual'), exec: gcli_cmd_resize }); gcli.addCommand({ name: 'resize off', description: gcli.lookup('resizeModeOffDesc'), manual: gcli.lookup('resizeModeManual'), exec: gcli_cmd_resize }); gcli.addCommand({ name: 'resize toggle', description: gcli.lookup('resizeModeToggleDesc'), manual: gcli.lookup('resizeModeManual'), exec: gcli_cmd_resize }); gcli.addCommand({ name: 'resize to', description: gcli.lookup('resizeModeToDesc'), params: [ { name: 'width', type: 'number', description: gcli.lookup("resizePageArgWidthDesc"), }, { name: 'height', type: 'number', description: gcli.lookup("resizePageArgHeightDesc"), }, ], exec: gcli_cmd_resize }); function gcli_cmd_resize(args, context) { let browserDoc = context.environment.chromeDocument; let browserWindow = browserDoc.defaultView; let mgr = browserWindow.ResponsiveUI.ResponsiveUIManager; mgr.handleGcliCommand(browserWindow, browserWindow.gBrowser.selectedTab, this.name, args); }
26
70
0.672189
130390bec1ecab284891941b5a4f6190012aaa22
9,552
js
JavaScript
wordbattle/src/states/ChallengeMenu.js
seattleuser/wordsgame
cc099721d1b7484006badeeb73d0c1d6244e8d3e
[ "Apache-2.0" ]
1
2018-11-27T08:15:31.000Z
2018-11-27T08:15:31.000Z
wordbattle/src/states/ChallengeMenu.js
seattleuser/wordsgame
cc099721d1b7484006badeeb73d0c1d6244e8d3e
[ "Apache-2.0" ]
12
2019-04-02T04:07:55.000Z
2022-03-01T23:50:21.000Z
wordbattle/src/states/ChallengeMenu.js
seattleuser/wordsgame
cc099721d1b7484006badeeb73d0c1d6244e8d3e
[ "Apache-2.0" ]
6
2018-03-05T16:58:03.000Z
2019-01-11T08:22:09.000Z
import ChallengeList from '../challengeList.json' export default class Menu extends Phaser.State { create () { this.add.sprite(game.world.centerX, game.world.centerY, 'bg1').anchor.set(0.5) this.background = this.add.graphics() this.drawBackground() // this.scale.onSizeChange.add(this.drawBackground) let topText = this.add.text(game.world.centerX, 100 * game.scaleRatio, 'Select your Challenge', { font: '45px Berkshire Swash' }) topText.anchor.set(0.5) topText.scale.setTo(game.scaleRatio) this.buttons = [] this.previousCategories = [] this.categoryNames = [] this.makeButtons(ChallengeList) this.backButton = this.add.sprite(game.world.centerX, game.world.height - 80 * game.scaleRatio, 'shortButton') this.backButton.anchor.set(0.5) this.backButton.scale.set(0.5, 0.5) this.backButton.inputEnabled = true this.backButton.input.useHandCursor = true this.backButton.events.onInputDown.add(() => { this.goBack() }) this.backButton.events.onInputOver.add(() => { this.backButton.loadTexture('shortButton_selected') }) this.backButton.events.onInputOut.add(() => { this.backButton.loadTexture('shortButton') }) this.backText = this.add.text(game.world.centerX, game.world.height - 80 * game.scaleRatio, 'Go Back') this.backText.anchor.set(0.5) this.backText.scale.setTo(game.scaleRatio) } makeButtons (buttons, startingIndex) { startingIndex = startingIndex || 0 // Load progress data let challengeData = window.localStorage.getItem('challengeData') if (challengeData) challengeData = JSON.parse(challengeData) else challengeData = {} // Clear old buttons for (let i = this.buttons.length - 1; i >= 0; i--) { if (this.buttons[i].checkmark) this.buttons[i].checkmark.destroy() if (this.buttons[i].icon) this.buttons[i].icon.destroy() this.buttons[i].text.destroy() this.buttons[i].destroy() } if (this.backArrow) { this.backArrow.destroy() } if (this.forwardArrow) { this.forwardArrow.destroy() } let buttonWidth = 250 * game.scaleRatio let buttonHeight = 220 * game.scaleRatio let buttonSpacing = 25 * game.scaleRatio let buttonsPerRow = 3 let rowsPerPage = 2 let buttonAreaWidth = (buttonWidth * buttonsPerRow) + (buttonSpacing * (buttonsPerRow - 1)) let buttonAreaHeight = game.world.height - 300 - (buttonSpacing * 2) let buttonStartX = (game.world.width - buttonAreaWidth) / 2 + (buttonAreaWidth - (buttonWidth * buttonsPerRow) - (buttonSpacing * (buttonsPerRow - 1))) / 2 let buttonStartY = 200 * game.scaleRatio + buttonSpacing // Back arrow if (startingIndex > 0) { this.backArrow = this.add.image(game.world.centerX - (buttonAreaWidth / 2) - (100 * game.scaleRatio), game.world.centerY, 'arrow') this.backArrow.anchor.set(0.5, 0.5) this.backArrow.scale.set(-1 * game.scaleRatio, game.scaleRatio) this.backArrow.alpha = 0.5 this.backArrow.inputEnabled = true this.backArrow.input.useHandCursor = true this.backArrow.events.onInputDown.add(() => { this.makeButtons(buttons, startingIndex - buttonsPerRow * rowsPerPage) }) this.backArrow.events.onInputOver.add(() => { this.backArrow.alpha = 1 }) this.backArrow.events.onInputOut.add(() => { this.backArrow.alpha = 0.5 }) } // Forward arrow if (buttons.length - startingIndex > buttonsPerRow * rowsPerPage) { this.forwardArrow = this.add.image(game.world.centerX + (buttonAreaWidth / 2) + (100 * game.scaleRatio), game.world.centerY, 'arrow') this.forwardArrow.anchor.set(0.5, 0.5) this.forwardArrow.scale.set(game.scaleRatio) this.forwardArrow.alpha = 0.5 this.forwardArrow.inputEnabled = true this.forwardArrow.input.useHandCursor = true this.forwardArrow.events.onInputDown.add(() => { this.makeButtons(buttons, buttonsPerRow * rowsPerPage) }) this.forwardArrow.events.onInputOver.add(() => { this.forwardArrow.alpha = 1 }) this.forwardArrow.events.onInputOut.add(() => { this.forwardArrow.alpha = 0.5 }) } // Back arrow if (startingIndex > 0) { this.backArrow = this.add.image(game.world.centerX - 250, game.world.height - 150, 'arrow') this.backArrow.anchor.set(0.5, 0.5) this.backArrow.scale.set(-1, 1) this.backArrow.inputEnabled = true this.backArrow.input.useHandCursor = true this.backArrow.events.onInputDown.add(() => { this.makeButtons(buttons, startingIndex - buttonsPerRow * rowsPerPage) }) } // Forward arrow if (buttons.length - startingIndex > buttonsPerRow * rowsPerPage) { this.forwardArrow = this.add.image(game.world.centerX + 250, game.world.height - 150, 'arrow') this.forwardArrow.anchor.set(0.5, 0.5) this.forwardArrow.inputEnabled = true this.forwardArrow.input.useHandCursor = true this.forwardArrow.events.onInputDown.add(() => { this.makeButtons(buttons, buttonsPerRow * rowsPerPage) }) } for (let y = 0; y < rowsPerPage; y++) { for (let x = 0; x < buttonsPerRow; x++) { let option = buttons[(y * buttonsPerRow) + x + startingIndex] if (option) { let newButton = this.add.image(x * (buttonWidth + buttonSpacing) + buttonStartX, y * (buttonHeight + buttonSpacing) + buttonStartY, 'button') newButton.scale.set(game.scaleRatio) this.buttons.push(newButton) newButton.text = this.add.text(x * (buttonWidth + buttonSpacing) + buttonStartX + buttonWidth / 2, y * (buttonHeight + buttonSpacing) + buttonStartY + buttonHeight - 25 * game.scaleRatio, option.name) newButton.text.anchor.set(0.5) newButton.text.scale.setTo(game.scaleRatio) newButton.inputEnabled = true newButton.input.useHandCursor = true newButton.events.onInputOver.add(() => { newButton.loadTexture('button_selected') }) newButton.events.onInputOut.add(() => { newButton.loadTexture('button') }) newButton.events.onInputDown.add(() => { if (option.subCategories) { this.categoryNames.push(option.name) this.makeButtons(option.subCategories) this.previousCategories.push(buttons) } else { dtml.recordGameEvent('wordsbattle', 'ChallengeSelected', option.name) this.state.start('Game', true, false, 'challenge', this.categoryNames[this.categoryNames.length - 1], option.name) } }) // Button Icon if (this.cache.checkImageKey('icon_' + option.name.toLowerCase())) { newButton.icon = this.add.image(x * (buttonWidth + buttonSpacing) + buttonStartX + buttonWidth / 2, y * (buttonHeight + buttonSpacing) + buttonStartY + buttonHeight / 2, 'icon_' + option.name.toLowerCase()) newButton.icon.anchor.set(0.5) newButton.icon.scale.set(game.scaleRatio) } else { newButton.icon = this.add.image(x * (buttonWidth + buttonSpacing) + buttonStartX + buttonWidth / 2, y * (buttonHeight + buttonSpacing) + buttonStartY + buttonHeight / 2, 'icon_default') newButton.icon.anchor.set(0.5) newButton.icon.scale.set(game.scaleRatio) } // Checkmark if (this.isCategoryCompleted(option, challengeData)) { newButton.checkmark = this.add.sprite(x * (buttonWidth + buttonSpacing) + buttonStartX + buttonWidth - 25, y * (buttonHeight + buttonSpacing) + buttonStartY + 25, 'checkmark') newButton.checkmark.anchor.set(0.5) newButton.checkmark.scale.set(game.scaleRatio) } } } } // Bring button checkmarks to top of draw order for (let i = 0; i < this.buttons.length; i++) { if (this.buttons[i].checkmark) this.buttons[i].checkmark.bringToTop() } } goBack () { if (this.previousCategories.length > 0) { this.categoryNames.pop() this.makeButtons(this.previousCategories[this.previousCategories.length - 1]) this.previousCategories.pop() } else { this.state.start('Menu') } } isCategoryCompleted (category, challengeData) { if (category.subCategories) { if (challengeData[category.name]) { for (let i = 0; i < category.subCategories.length; i++) { let subCategory = category.subCategories[i] if (!this.isCategoryCompleted(subCategory, challengeData)) { return false } } return true } } else { for (let topLevelCategory in challengeData) { if (challengeData[topLevelCategory][category.name] === true) { return true } } } } allChallengesCompleted () { // Load progress data let challengeData = window.localStorage.getItem('challengeData') if (challengeData) challengeData = JSON.parse(challengeData) else return false for (let i = 0; i < ChallengeList.length; i++) { if (!this.isCategoryCompleted(ChallengeList[i], challengeData)) { return false } } return true } drawBackground () { this.background.clear() this.background.beginFill(0xC5D763) this.background.drawRect(0, 200 * game.scaleRatio, game.world.width, game.world.height - 200 * game.scaleRatio) this.background.endFill() } }
40.303797
218
0.644054
1304a40eee1a2124ed1cfff17de805d73c652f3e
1,908
js
JavaScript
NiuniuClient/assets/script/common/ScrollViewFixed.js
isoundy000/Niuniu
6892fa8a8fe64fd81922016f76a96432d5843ad0
[ "MIT" ]
34
2019-03-26T20:58:45.000Z
2022-02-21T06:45:52.000Z
NiuniuClient/assets/script/common/ScrollViewFixed.js
whitegl0ves/Niuniu
0e81ae0ef024c891088412e4ed2a50bd7c405ff1
[ "MIT" ]
null
null
null
NiuniuClient/assets/script/common/ScrollViewFixed.js
whitegl0ves/Niuniu
0e81ae0ef024c891088412e4ed2a50bd7c405ff1
[ "MIT" ]
19
2019-05-07T17:35:33.000Z
2020-11-27T14:23:17.000Z
/** * 修改系统ScrollView,去除本身触摸事件,增加设置滚动越界距离 * 触摸事件由外部传递过去(touchstart touchmove touchend touchcancle) */ "use strict"; cc.Class({ extends: cc.ScrollView, properties:{ maxBounceDistance:{ tooltip: "允许超过边界的最大值", default: cc.v2(100,100) }, rate: { tooltip: "移动速率(0-1), 1表示跟随手指, 0表示不动", default: 1, max: 1, min: 0 }, }, // mark 取消自身的触摸事件 _registerEvent(){ }, _moveContent(deltaMove, canStartBounceBack) { let adjustedMove = this._flattenVectorByDirection(deltaMove); let scaleFactor = cc.director.getContentScaleFactor(); scaleFactor = 1; let newPosition = cc.pAdd(this.getContentPosition(), adjustedMove); let maxOffset = this.getMaxScrollOffset(); newPosition.x = newPosition.x>=(-maxOffset.x/2-this.maxBounceDistance.x * scaleFactor)?newPosition.x:(-maxOffset.x/2-this.maxBounceDistance.x * scaleFactor); newPosition.x = newPosition.x<=(maxOffset.x/2+this.maxBounceDistance.x * scaleFactor)?newPosition.x:(maxOffset.x/2+this.maxBounceDistance.x * scaleFactor); newPosition.y = newPosition.y>=(-maxOffset.y/2-this.maxBounceDistance.x * scaleFactor)?newPosition.y:(-maxOffset.y/2-this.maxBounceDistance.x * scaleFactor); newPosition.y = newPosition.y<=(maxOffset.y/2+this.maxBounceDistance.x * scaleFactor)?newPosition.y:(maxOffset.y/2+this.maxBounceDistance.x * scaleFactor); this.setContentPosition(newPosition); var outOfBoundary = this._getHowMuchOutOfBoundary(); this._updateScrollBar(outOfBoundary); if (this.elastic && canStartBounceBack) { this._startBounceBackIfNeeded(); } }, _handleMoveLogic: function(touch) { let deltaMove = touch.getDelta(); this._processDeltaMove(cc.pMult(deltaMove, this.rate)); } });
34.690909
165
0.655136
1304bf59415f3b3f6dae682c6d4bc2be2e39d5bb
480
js
JavaScript
input/releases/qpid-proton-0.15.0/proton/c/api/group__receiver.js
ChugR/qpid-site
f17c8263f61547552dbf223bb8dd6b242d48a44f
[ "Apache-2.0" ]
null
null
null
input/releases/qpid-proton-0.15.0/proton/c/api/group__receiver.js
ChugR/qpid-site
f17c8263f61547552dbf223bb8dd6b242d48a44f
[ "Apache-2.0" ]
null
null
null
input/releases/qpid-proton-0.15.0/proton/c/api/group__receiver.js
ChugR/qpid-site
f17c8263f61547552dbf223bb8dd6b242d48a44f
[ "Apache-2.0" ]
null
null
null
var group__receiver = [ [ "pn_link_drain", "group__receiver.html#ga2f48aec7e3de526bbdea1c4e99708357", null ], [ "pn_link_draining", "group__receiver.html#gacda3e0bc16ff65cbfa99087f9da025c7", null ], [ "pn_link_flow", "group__receiver.html#gaf331f33acd1fddbb6f8e674a8a7c6aa2", null ], [ "pn_link_recv", "group__receiver.html#gaa98289676877e6c820a95e4bce94eda6", null ], [ "pn_link_set_drain", "group__receiver.html#ga22837f7f8e152add8de867bbe4163892", null ] ];
60
92
0.777083
1304c2a8c00715bd05d223ca752ad774380b4d3b
5,345
js
JavaScript
src/pages/Archives/Device/Sdevice/DevOutPage.js
lijifa/sxf-admin
2022463090bc35f812f31da1c96a20865d4f3fa7
[ "MIT" ]
null
null
null
src/pages/Archives/Device/Sdevice/DevOutPage.js
lijifa/sxf-admin
2022463090bc35f812f31da1c96a20865d4f3fa7
[ "MIT" ]
null
null
null
src/pages/Archives/Device/Sdevice/DevOutPage.js
lijifa/sxf-admin
2022463090bc35f812f31da1c96a20865d4f3fa7
[ "MIT" ]
null
null
null
import { Component, Fragment } from 'react'; import { connect } from 'dva'; import { Form, Button, Spin, Input, Row, Col } from "antd"; import {responseMsg, changeTime} from '@/utils/utils'; import DevTypeSelect from '@/components/TKDevTypeSelect'; import OrgSelect from '@/components/TKOrgSelect'; import StatusSelect from '@/components/MsStatusSelect'; import styles from './styles.less'; const FormItem = Form.Item; const deviceAttachSelect = [ {key: 0, value: '自有'}, {key: 1, value: '携机入网'} ] const deviceStatusSelect = [ {key: 2, value: '库存状态'}, {key: 4, value: '报修状态'}, {key: 5, value: '报废状态'}, {key: 9, value: '注销状态'} ] const namespace = 'sdevice'; @connect(({ sdevice }) => ({ result: sdevice.editRes, })) class DevOut extends Component { constructor (props) { super(props) } state = { devbrandMapId: '', modelCode: '', partnerMapId: this.props.detailData ? this.props.detailData.partnerMapId : 0, partnerMapIdP: this.props.detailData ? this.props.detailData.partnerMapIdP : 0, instMapId: this.props.detailData ? this.props.detailData.instMapId : 0, } //获取组织数据 onChangeOrg = (data) => { if (data[0]) { this.setState({ instMapId: data[0].id }) } if (data[1]) { this.setState({ partnerMapId: data[1].id }) } if (data[2]) { this.setState({ partnerMapIdP: data[2].id }) } } //获取品牌数据 onChangeDevType = (data) => { if (data[0]) { this.setState({ devbrandMapId: data[0].id }) } if (data[1]) { this.setState({ modelCode: data[1].id }) } } handleSubmit = e => { e.preventDefault(); const { devbrandMapId, modelCode, instMapId, partnerMapId, partnerMapIdP } = this.state; const { dispatch, form, detailData, onReturnList } = this.props; form.validateFields((err, fieldsValue) => { if (err) return; const { deviceSn, deviceStatus, deviceAttach } = fieldsValue const values = { id: detailData ? detailData.id : '', deviceSnList: [deviceSn], devbrandMapId, modelCode, deviceStatus: deviceStatus ? deviceStatus : 2, deviceAttach, instMapId, partnerMapIdP, partnerMapId, devBatchId: 0 }; dispatch({ type: detailData ? `${namespace}/update` : `${namespace}/add`, payload: values, callback: (res) => { if (res) { if (res.code == '00') { responseMsg(res) onReturnList() }else{ responseMsg(res) } } } }); }); }; render () { const { form } = this.props //const { submiting, checkNum, isSubmit, createGrpFlag, skuGrpData, skuGrpId1 } = this.state const { getFieldDecorator } = form const decoratorConfig = { rules: [{ required: true, message: '此项必填' }] } return( <div className={styles.editFormItem} style={{height: 'calc(100vh - 80px)'}}> <Form onSubmit={this.handleSubmit} > <Row gutter={16}> <Col span={16}> <FormItem label='归属'> {getFieldDecorator('orgData', Object.assign({}, decoratorConfig, {initialValue: []})) ( <OrgSelect allData={true} placeholder='请选择归属机构' onChange={(val) => this.onChangeOrg(val)} /> )} </FormItem> </Col> </Row> <Row gutter={16}> <Col span={16}> <FormItem label='隶属标识'> {getFieldDecorator('deviceAttach', Object.assign({}, decoratorConfig, {initialValue: 0})) ( <StatusSelect options={deviceAttachSelect} placeholder='隶属标识'/> )} </FormItem> </Col> </Row> <hr style={{ height:'1px', marginBottom: '7px', border:'none', borderTop:'1px dashed #ccc' }}/> <Row gutter={16}> <Col span={16}> <FormItem label='品牌/型号'> {getFieldDecorator('devData', Object.assign({}, decoratorConfig, {initialValue: []})) ( <DevTypeSelect allData={true} placeholder='请选择品牌/型号' onChange={(val)=>this.onChangeDevType(val)} /> )} </FormItem> </Col> </Row> <div style={{ position: 'absolute', bottom: 0, width: '100%', borderTop: '1px solid #e8e8e8', padding: '10px 16px', textAlign: 'right', left: 0, background: '#fff', borderRadius: '0 0 4px 4px', }} > <Button style={{ marginRight: 8, }} onClick={this.props.onClose} > 取消 </Button> <Button type="primary" htmlType="submit">保存</Button> </div> </Form> </div> ) } } const DevOutFormPage = Form.create()(DevOut); export default DevOutFormPage
27.410256
105
0.50159
1305c7fe40ca741b2bdb80cef5ab0a136b9e7864
481
js
JavaScript
tunnel.js
stonerworx/home
fa4a71baee6c264a814afbf1b3f9396da8cda012
[ "MIT" ]
null
null
null
tunnel.js
stonerworx/home
fa4a71baee6c264a814afbf1b3f9396da8cda012
[ "MIT" ]
null
null
null
tunnel.js
stonerworx/home
fa4a71baee6c264a814afbf1b3f9396da8cda012
[ "MIT" ]
null
null
null
const localtunnel = require('localtunnel'); exports.tunnel = (subdomain, port) => { const tunnel = localtunnel(port, { subdomain }, (err, t) => { if (err) { console.log('error opening tunnel', err); process.exit(1); } console.log('tunnel openend', t.url); }); tunnel.on('close', () => { console.log('tunnel closed.'); process.exit(1); }); tunnel.on('error', err => { console.log('tunnel error', err); process.exit(1); }); };
20.913043
63
0.567568
13063f565dd7e9dcb01373afc710e1dc506eade0
1,143
js
JavaScript
assets/js/user/user_info.js
wu-yiqiang/bigThings
dcb173371ceea6aff938c7895b514fa46b118e70
[ "MIT" ]
null
null
null
assets/js/user/user_info.js
wu-yiqiang/bigThings
dcb173371ceea6aff938c7895b514fa46b118e70
[ "MIT" ]
null
null
null
assets/js/user/user_info.js
wu-yiqiang/bigThings
dcb173371ceea6aff938c7895b514fa46b118e70
[ "MIT" ]
null
null
null
$(function() { var form = layui.form var layer = layui.layer form.verify({ nickname: function(value) { if (value.length > 6) { return '昵称长度必须在 1 ~ 6 个字符之间!' } } }) initUserInfo() // 初始化用户的基本信息 function initUserInfo() { $.ajax({ method: 'GET', url: '/my/userinfo', success: function(res) { if (res.status !== 0) { return layer.msg('获取用户信息失败!') } // console.log(res) // 调用 form.val() 快速为表单赋值 form.val('formUserInfo', res.data) } }) } // 重置表单的数据 $('#btnReset').on('click', function(e) { // 阻止表单的默认重置行为 e.preventDefault() initUserInfo() }) // 监听表单的提交事件 $('.layui-form').on('submit', function(e) { // 阻止表单的默认提交行为 e.preventDefault() // 发起 ajax 数据请求 $.ajax({ method: 'POST', url: '/my/userinfo', data: $(this).serialize(), success: function(res) { if (res.status !== 0) { return layer.msg('更新用户信息失败!') } layer.msg('更新用户信息成功!') // 调用父页面中的方法,重新渲染用户的头像和用户的信息 window.parent.getUserInfo() } }) }) })
19.706897
45
0.508311