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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
bbe225148c3a43b55b3a13a5b09420e28054c70c | 4,963 | js | JavaScript | src/foam/nanos/medusa/ClusterConfigMonitorAgent.js | hchoura/foam3 | 912203e1c65ff0c1250b803cd44706b932390d66 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | src/foam/nanos/medusa/ClusterConfigMonitorAgent.js | hchoura/foam3 | 912203e1c65ff0c1250b803cd44706b932390d66 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | src/foam/nanos/medusa/ClusterConfigMonitorAgent.js | hchoura/foam3 | 912203e1c65ff0c1250b803cd44706b932390d66 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | /**
* @license
* Copyright 2019 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
foam.CLASS({
package: 'foam.nanos.medusa',
name: 'ClusterConfigMonitorAgent',
implements: [
'foam.core.ContextAgent'
],
documentation: 'Attempt to contact Nodes and Mediators, record ping time and mark them ONLINE or OFFLINE.',
javaImports: [
'foam.core.ContextAgent',
'foam.core.ContextAgentTimerTask',
'foam.core.FObject',
'foam.core.X',
'foam.dao.ArraySink',
'foam.dao.DAO',
'foam.log.LogLevel',
'static foam.mlang.MLang.AND',
'static foam.mlang.MLang.COUNT',
'static foam.mlang.MLang.EQ',
'static foam.mlang.MLang.GTE',
'foam.nanos.alarming.Alarm',
'foam.nanos.logger.PrefixLogger',
'foam.nanos.logger.Logger',
'foam.nanos.pm.PM',
'java.util.HashMap',
'java.util.List',
'java.util.Timer'
],
axioms: [
{
buildJavaClass: function(cls) {
cls.extras.push(`
public ClusterConfigMonitorAgent(foam.core.X x, String id, foam.dao.DAO dao) {
setX(x);
setId(id);
setDao(dao);
}
`);
}
}
],
properties: [
{
name: 'id',
class: 'String'
},
{
name: 'dao',
class: 'foam.dao.DAOProperty'
},
{
name: 'timerInterval',
class: 'Long',
value: 10000
},
{
name: 'initialTimerDelay',
class: 'Int',
value: 5000
},
{
name: 'lastAlarmsSince',
class: 'Date',
javaFactory: 'return new java.util.Date(1081157732);'
},
{
name: 'logger',
class: 'FObjectProperty',
of: 'foam.nanos.logger.Logger',
visibility: 'HIDDEN',
transient: true,
javaCloneProperty: '//noop',
javaFactory: `
return new PrefixLogger(new Object[] {
this.getClass().getSimpleName(),
this.getId()
}, (Logger) getX().get("logger"));
`
}
],
methods: [
{
documentation: 'Start as a NanoService',
name: 'start',
javaCode: `
getLogger().info("start", "interval", getTimerInterval());
Timer timer = new Timer(this.getClass().getSimpleName()+"-"+getId(), true);
timer.schedule(new ContextAgentTimerTask(getX(), this), getTimerInterval(), getTimerInterval());
`
},
{
name: 'execute',
args: [
{
name: 'x',
type: 'Context'
}
],
javaCode: `
PM pm = PM.create(x, this.getClass().getSimpleName(), getId());
ClusterConfigSupport support = (ClusterConfigSupport) x.get("clusterConfigSupport");
ClusterConfig config = support.getConfig(x, getId());
try {
if ( ! config.getEnabled() ) {
return;
}
ClusterConfig myConfig = support.getConfig(x, support.getConfigId());
DAO client = support.getClientDAO(x, "clusterConfigDAO", myConfig, config);
try {
long startTime = System.currentTimeMillis();
ClusterConfig cfg = (ClusterConfig) client.find_(x, config.getId());
if ( cfg != null ) {
cfg.setPingTime(System.currentTimeMillis() - startTime);
getDao().put_(x, cfg);
} else {
getLogger().warning("client,find", "null");
}
} catch ( Throwable t ) {
if ( config.getStatus() != Status.OFFLINE ) {
getLogger().debug(t.getMessage());
ClusterConfig cfg = (ClusterConfig) config.fclone();
cfg.setStatus(Status.OFFLINE);
config = (ClusterConfig) getDao().put_(x, cfg);
}
Throwable cause = t.getCause();
if ( cause == null ||
! ( cause instanceof java.io.IOException ) &&
config.getStatus() != Status.OFFLINE ) {
getLogger().warning(t.getMessage(), t);
}
return;
}
java.util.Date now = new java.util.Date();
client = support.getClientDAO(x, "alarmDAO", myConfig, config);
client = client.where(
AND(
EQ(Alarm.SEVERITY, LogLevel.ERROR),
EQ(Alarm.CLUSTERABLE, false),
EQ(Alarm.HOSTNAME, config.getName()),
GTE(Alarm.LAST_MODIFIED, getLastAlarmsSince())
)
);
List<Alarm> alarms = (List) ((ArraySink) client.select(new ArraySink())).getArray();
if ( alarms != null ) {
DAO alarmDAO = (DAO) x.get("alarmDAO");
for (Alarm alarm : alarms ) {
alarmDAO.put(alarm);
}
}
setLastAlarmsSince(now);
} catch ( Throwable t ) {
Throwable cause = t.getCause();
if ( cause == null ||
! ( cause instanceof java.io.IOException ) &&
config.getStatus() != Status.OFFLINE ) {
getLogger().debug(t.getMessage(), t);
}
pm.error(x, t);
} finally {
pm.log(x);
}
`
}
]
});
| 27.882022 | 109 | 0.545436 |
bbe238966d4c722ae1951370656ed828f2a29c33 | 963 | js | JavaScript | src/index.js | monomelodies/monad-multilang | f700b0460ba0b57c101c52c6e5b25ac73839a73e | [
"MIT"
] | null | null | null | src/index.js | monomelodies/monad-multilang | f700b0460ba0b57c101c52c6e5b25ac73839a73e | [
"MIT"
] | 1 | 2022-03-02T04:36:46.000Z | 2022-03-02T04:36:46.000Z | src/index.js | monomelodies/monad-multilang | f700b0460ba0b57c101c52c6e5b25ac73839a73e | [
"MIT"
] | null | null | null |
"use strict";
import 'angular-gettext';
import Provider from './Provider';
import Location from './Location';
import '../lib/templates';
export default angular.module('monad.multilang', ['monad.cms', 'monad.multilang.templates', 'gettext'])
.provider('monadLanguageService', Provider)
.service('monadLocation', Location)
.config(['$routeProvider', $routeProvider => {
$routeProvider.
when('/', {
template: '<noop></noop>',
controller: ['monadLocation', monadLocation => monadLocation.path('/')]
});
}])
.run(['$rootScope', 'monadLanguageService', ($rootScope, monadLanguageService) => {
$rootScope.$on('$routeChangeSuccess', (event, target) => {
if (target.params.language && target.params.language != monadLanguageService.current) {
monadLanguageService.current = target.params.language;
}
});
}])
.name
;
| 33.206897 | 103 | 0.602285 |
bbe2b9bf6ceda7ef6e5537f2acc3dede45228fdf | 13,039 | js | JavaScript | node_modules/megadraft/lib/components/Toolbar.js | BartoszWlazlo/Web-Semantic-Editor-FRONTEND | bd93f9a5115772bfd9a1531d7e9e352cb00991ad | [
"MIT"
] | null | null | null | node_modules/megadraft/lib/components/Toolbar.js | BartoszWlazlo/Web-Semantic-Editor-FRONTEND | bd93f9a5115772bfd9a1531d7e9e352cb00991ad | [
"MIT"
] | null | null | null | node_modules/megadraft/lib/components/Toolbar.js | BartoszWlazlo/Web-Semantic-Editor-FRONTEND | bd93f9a5115772bfd9a1531d7e9e352cb00991ad | [
"MIT"
] | null | null | null | "use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = undefined;
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _class, _temp; /*
* Copyright (c) 2016, Globo.com (https://github.com/globocom)
*
* License: MIT
*/
var _react = require("react");
var _react2 = _interopRequireDefault(_react);
var _draftJs = require("draft-js");
var _classnames = require("classnames");
var _classnames2 = _interopRequireDefault(_classnames);
var _ToolbarItem = require("./ToolbarItem");
var _ToolbarItem2 = _interopRequireDefault(_ToolbarItem);
var _utils = require("../utils");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
var Toolbar = (_temp = _class = function (_Component) {
_inherits(Toolbar, _Component);
function Toolbar(props) {
_classCallCheck(this, Toolbar);
var _this = _possibleConstructorReturn(this, (Toolbar.__proto__ || Object.getPrototypeOf(Toolbar)).call(this, props));
_this.state = {
show: false,
editingEntity: null,
link: "",
error: null
};
_this.renderButton = _this.renderButton.bind(_this);
_this.cancelEntity = _this.cancelEntity.bind(_this);
_this.removeEntity = _this.removeEntity.bind(_this);
_this.setError = _this.setError.bind(_this);
_this.cancelError = _this.cancelError.bind(_this);
return _this;
}
_createClass(Toolbar, [{
key: "toggleInlineStyle",
value: function toggleInlineStyle(inlineStyle) {
var newEditorState = _draftJs.RichUtils.toggleInlineStyle(this.props.editorState, inlineStyle);
this.props.onChange(newEditorState);
}
}, {
key: "toggleBlockStyle",
value: function toggleBlockStyle(blockType) {
this.props.onChange(_draftJs.RichUtils.toggleBlockType(this.props.editorState, blockType));
}
}, {
key: "toggleEntity",
value: function toggleEntity(entity) {
this.setState({ editingEntity: entity });
}
}, {
key: "renderButton",
value: function renderButton(item, position) {
var _this2 = this;
var current = null;
var toggle = null;
var active = null;
var key = item.label;
switch (item.type) {
case "custom":
{
key = "custom-" + position;
toggle = function toggle() {
return item.action(_this2.props.editorState);
};
break;
}
case "inline":
{
current = this.props.editorState.getCurrentInlineStyle();
toggle = function toggle() {
return _this2.toggleInlineStyle(item.style);
};
active = current.has(item.style);
break;
}
case "block":
{
var selection = this.props.editorState.getSelection();
current = this.props.editorState.getCurrentContent().getBlockForKey(selection.getStartKey()).getType();
toggle = function toggle() {
return _this2.toggleBlockStyle(item.style);
};
active = item.style === current;
break;
}
case "separator":
{
key = "sep-" + position;
break;
}
case "entity":
{
var _item$entity = item.entity,
entity = _item$entity === undefined ? "LINK" : _item$entity;
key = "entity-" + entity;
toggle = function toggle() {
return _this2.toggleEntity(entity);
};
active = this.hasEntity(entity);
break;
}
}
return _react2.default.createElement(_ToolbarItem2.default, { key: key, active: active, toggle: toggle, item: item });
}
}, {
key: "setError",
value: function setError(errorMsg) {
this.setState({ error: errorMsg });
}
}, {
key: "cancelError",
value: function cancelError() {
this.setState({ error: null });
}
}, {
key: "setBarPosition",
value: function setBarPosition() {
var editor = this.props.editor;
var toolbar = this.refs.toolbar;
var arrow = this.refs.arrow;
var selectionCoords = (0, _utils.getSelectionCoords)(editor, toolbar);
if (!selectionCoords) {
return null;
}
if (selectionCoords && !this.state.position || this.state.position.bottom !== selectionCoords.offsetBottom || this.state.position.left !== selectionCoords.offsetLeft || !this.state.show) {
this.setState({
show: true,
position: {
bottom: selectionCoords.offsetBottom,
left: selectionCoords.offsetLeft
}
}, function (state) {
var minOffsetLeft = 5;
var minOffsetRight = 5;
var toolbarDimensions = toolbar.getBoundingClientRect();
if (toolbarDimensions.left < minOffsetLeft) {
toolbar.style.left = -(toolbarDimensions.width / 2 + toolbarDimensions.left - minOffsetLeft) + "px";
arrow.style.left = toolbarDimensions.width / 2 + toolbarDimensions.left - minOffsetLeft + "px";
}
if (toolbarDimensions.left + toolbarDimensions.width > window.innerWidth - minOffsetRight) {
toolbar.style.left = -(toolbarDimensions.right - selectionCoords.offsetLeft + minOffsetRight) + "px";
arrow.style.left = toolbarDimensions.right - selectionCoords.offsetLeft + minOffsetRight + "px";
}
});
}
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate() {
// reset toolbar position every time
if (this.refs.toolbar && this.refs.arrow) {
this.refs.toolbar.style.left = "";
this.refs.arrow.style.left = "";
}
if (this.props.shouldDisplayToolbarFn()) {
return this.setBarPosition();
} else {
if (this.state.show) {
this.setState({
show: false,
editingEntity: null,
link: "",
error: null
});
}
}
}
}, {
key: "getCurrentEntityKey",
value: function getCurrentEntityKey() {
var selection = this.props.editorState.getSelection();
var anchorKey = selection.getAnchorKey();
var contentState = this.props.editorState.getCurrentContent();
var anchorBlock = contentState.getBlockForKey(anchorKey);
var offset = selection.anchorOffset;
var index = selection.isBackward ? offset - 1 : offset;
return anchorBlock.getEntityAt(index);
}
}, {
key: "getCurrentEntity",
value: function getCurrentEntity() {
var contentState = this.props.editorState.getCurrentContent();
var entityKey = this.getCurrentEntityKey();
if (entityKey) {
return contentState.getEntity(entityKey);
}
return null;
}
}, {
key: "hasEntity",
value: function hasEntity(entityType) {
var entity = this.getCurrentEntity();
if (entity && entity.getType() === entityType) {
return true;
}
return false;
}
}, {
key: "setEntity",
value: function setEntity(entityType, data) {
var mutability = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : "MUTABLE";
var editorState = this.props.editorState;
var contentState = editorState.getCurrentContent();
var contentStateWithEntity = contentState.createEntity(entityType, mutability, data);
var entityKey = contentStateWithEntity.getLastCreatedEntityKey();
var newState = _draftJs.RichUtils.toggleLink(editorState, editorState.getSelection(), entityKey);
var selectionState = _draftJs.EditorState.forceSelection(newState, editorState.getSelection());
this.props.onChange(selectionState);
}
}, {
key: "removeEntity",
value: function removeEntity() {
var editorState = this.props.editorState;
var selection = editorState.getSelection();
if (!selection.isCollapsed()) {
// toggleLink should be named toggleEntity: https://github.com/facebook/draft-js/issues/737
this.props.onChange(_draftJs.RichUtils.toggleLink(editorState, selection, null));
}
this.cancelEntity();
}
}, {
key: "cancelEntity",
value: function cancelEntity() {
this.props.editor && this.props.editor.focus();
this.setState({
editingEntity: null,
error: null
});
}
}, {
key: "renderEntityInput",
value: function renderEntityInput(entityType) {
var _this3 = this;
if (!this.props.entityInputs) {
console.warn("no entityInputs provided");
return null;
}
var Component = this.props.entityInputs[entityType];
var setEntity = function setEntity(data, mutability) {
return _this3.setEntity(entityType, data, mutability);
};
var entityData = {};
var entity = null;
if (this.hasEntity(entityType)) {
entity = this.getCurrentEntity();
if (entity) {
entityData = entity.getData();
}
}
if (Component) {
return _react2.default.createElement(Component, _extends({
editorState: this.props.editorState,
setEntity: setEntity,
entityType: entityType,
onChange: this.props.onChange,
cancelEntity: this.cancelEntity,
removeEntity: this.removeEntity,
setError: this.setError,
cancelError: this.cancelError,
entity: entity
}, entityData));
} else {
console.warn("unknown entity type: " + entityType);
return null;
}
}
}, {
key: "renderToolList",
value: function renderToolList() {
return _react2.default.createElement(
"ul",
{ className: "toolbar__list", onMouseDown: function onMouseDown(x) {
x.preventDefault();
} },
this.props.actions.map(this.renderButton)
);
}
}, {
key: "render",
value: function render() {
if (this.props.readOnly) {
return null;
}
var toolbarClass = (0, _classnames2.default)("toolbar", {
"toolbar--open": this.state.show,
"toolbar--error": this.state.error
});
return _react2.default.createElement(
"div",
{ className: toolbarClass,
style: this.state.position,
ref: "toolbarWrapper" },
_react2.default.createElement(
"div",
{ style: { position: "absolute", bottom: 0 } },
_react2.default.createElement(
"div",
{ className: "toolbar__wrapper", ref: "toolbar" },
this.state.editingEntity ? this.renderEntityInput(this.state.editingEntity) : this.renderToolList(),
_react2.default.createElement(
"p",
{ className: "toolbar__error-msg" },
this.state.error
),
_react2.default.createElement("span", { className: "toolbar__arrow", ref: "arrow" })
)
)
);
}
}]);
return Toolbar;
}(_react.Component), _class.defaultProps = {
shouldDisplayToolbarFn: function shouldDisplayToolbarFn() {
return !this.editorState.getSelection().isCollapsed();
}
}, _temp);
exports.default = Toolbar; | 36.119114 | 564 | 0.617915 |
bbe34b59244d7f5802dc3671ce140388d665deec | 60,880 | js | JavaScript | public/js/normal.js | nhh216/kusled | 668bba4cdfd44a6aeef11cd59c7e0d23ff7813ae | [
"MIT"
] | 1 | 2021-04-22T16:36:52.000Z | 2021-04-22T16:36:52.000Z | public/js/normal.js | nhh216/kusled | 668bba4cdfd44a6aeef11cd59c7e0d23ff7813ae | [
"MIT"
] | null | null | null | public/js/normal.js | nhh216/kusled | 668bba4cdfd44a6aeef11cd59c7e0d23ff7813ae | [
"MIT"
] | null | null | null | $(document).ready(function () {
$(function () {
if ($(".ellipsis_title").length != 0) {
$(".ellipsis_title").dotdotdot({
height: 48,
callback: dotdotdotCallback
});
}
});
// serviceHover();
window.addEventListener('load', function () {
if ($(".js_removedisplay_class").length > 0) {
$(".js_removedisplay_class").css("display", "block");
}
if ($("#overlay_loading").length > 0) {
$("#overlay_loading").css("z-index", "-1");
}
if ($("#box_type_list").length > 0) {
if ($("#product_id").val() > 0) {
boxType($("#product_id").val());
}
}
if ($("#ratings").length > 0) {
var rate_value = $("#rate_value").val();
var options = {
max_value: 5,
step_size: 1,
initial_value: rate_value,
}
$("#ratings").rate(options);
$("#ratings").on("change", function (ev, data) {
$("#ratings").css("width", "100%");
$("#ratings").html("<p style='font-size: 14px;'>Cảm ơn bạn đã đánh giá " + data.to + " sao!</p>");
data.product_id = $("#product_id").val();
$.ajax({
url: site_folder + '/index_ajax.php?module_name=product&action=update_rating',
type: "POST",
data: data,
success: function (data) {
return true;
}
});
});
}
if ($(".collapse_link").length > 0) {
$(".collapse_link a").attr("data-toggle", "collapse");
}
myCore.init();
$("#my-menu").css("display", "block");
$(".slider-cates5.so-categories .cat-wrap .content-box .image-cat").on("hover", function () {
$(".slider-cates5.so-categories .cat-wrap .content-box .image-cat").removeClass("active");
$(this).addClass("active");
});
if ($(".click_item_product").length > 0) {
$(".click_item_product").on("click", function () {
var href = $(this).data("href");
window.location.href = href;
})
}
});
$(".check_brand_search").on("click", function () {
var data = new Object();
var id = $(this).data("id");
data.brand_id = id;
data.check_brand = document.getElementById("brand_" + id).checked;
$.ajax({
url: site_folder + '/index_ajax.php?module_name=product&action=load_ajax',
data: data,
contentType: 'html',
success: function (data) {
$("#contentload_api").html(data);
return true;
}
});
});
$(".check_model_search").on("click", function () {
var data = new Object();
var id = $(this).data("id");
var value = $(this).data("value");
data.model_id = id;
data.models = value;
data.check_model = document.getElementById("manufacturer_" + id).checked;
$.ajax({
url: site_folder + '/index_ajax.php?module_name=product&action=load_ajax',
data: data,
contentType: 'html',
success: function (data) {
$("#contentload_api").html(data);
return true;
}
});
});
$(".check_years_search").on("click", function () {
var data = new Object(), id = $(this).data("id"), value = $(this).data("value");
data.year_id = id;
data.years = value;
data.check_year = document.getElementById("years_" + id).checked;
$.ajax({
url: site_folder + '/index_ajax.php?module_name=product&action=load_ajax',
data: data,
contentType: 'html',
success: function (data) {
$("#contentload_api").html(data);
return true;
}
});
});
$(".min_max_value").on("click", function () {
var data = new Object();
data.min_price = $(".min_value").val();
data.max_price = $(".max_value").val();
$.ajax({
url: site_folder + '/index_ajax.php?module_name=product&action=load_ajax',
data: data,
contentType: 'html',
success: function (data) {
$("#contentload_api").html(data);
return true;
}
});
});
$(".change_sort").on("change", function () {
var data = new Object();
data.sort = $(this).val();
$.ajax({
url: site_folder + '/index_ajax.php?module_name=product&action=load_ajax',
data: data,
contentType: 'html',
success: function (data) {
$("#contentload_api").html(data);
return true;
}
});
});
$(".change_view").on("change", function () {
var data = new Object();
data.limit = $(this).val();
$.ajax({
url: site_folder + '/index_ajax.php?module_name=product&action=load_ajax',
data: data,
contentType: 'html',
success: function (data) {
$("#contentload_api").html(data);
return true;
}
});
});
$(".bg_opacity_50").on("click", function () {
notificationWarning("Cần chá»n phân loại 1 trước khi chá»n loại 2.")
});
$('.leftmenutrigger').on('click', function (e) {
$('.side-nav').toggleClass("open");
e.preventDefault();
});
$('ul#menudroptop li.dropdown').hover(function () {
$(this).find('.dropdown-menu').stop(true, true).delay(200).fadeIn(500);
}, function () {
$(this).find('.dropdown-menu').stop(true, true).delay(200).fadeOut(500);
});
$("#formSearchHeader .input-group-append").on("click", function () {
$("#formSearchHeader").submit();
});
$("#Redeem").click(function () {
var rc = $("#coupon").val();
if (rc != "" && rc != "Nháºp mã khuyến mãi...") {
$.ajax({
url: site_folder + '/index_ajax.php?module_name=cart&action=check_coupon_code',
data: {cc: rc},
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data) {
if (data.ok) {
location.reload();
$("#redeem_msg").html("Mã giảm giá hợp lệ, bạn được giảm " + data.value + " " + data.type);
} else {
$("#redeem_msg").html("<span class='text-danger'>Mã giảm giá không hợp lệ hoặc đã được sỠdụng.</span>");
}
return true;
}
});
} else {
alert("Vui lòng nháºp mã khuyến mãi.");
}
return false;
});
$(".remove_redeem").click(function () {
var conf = window.confirm("Bạn muốn xóa mã giảm giá?");
if (conf) {
$.ajax({
url: site_folder + '/index_ajax.php?module_name=cart&action=remove_coupon_code',
data: {},
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data) {
if (data.ok) {
$("#redeem_msg").html("");
}
return true;
}
});
}
return false;
});
$(".remove_itemcart").click(function () {
var conf = window.confirm("Bạn muốn xóa sản phẩm nà y?");
if (conf) {
var productid = $(this).attr("rel-id");
$.ajax({
url: site_folder + '/index_ajax.php?module_name=cart&action=remove',
data: {id: productid},
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data) {
location.reload();
return true;
}
});
}
return false;
});
$("#changesort").on("change", function () {
var value = $(this).val();
var newurl = "";
var url = window.location.href;
// window.location.href=url+"&sort="+value;
if (url.indexOf('sort') > -1) {
newurl = replaceUrlParam(url, "sort", value);
} else {
newurl = url + "?sort=" + value;
}
window.location.href = newurl;
});
$(".btnNewletter").click(function (e) {
var email = $("#newsletter").val();
if (email != "") {
$.post(site_folder + '/index_ajax.php?module_name=footer&action=newsletter',
{email: email},
function (data) {
notificationSuccess("Äăng ký nháºn bản tin thà nh công!");
return true;
});
} else {
notificationError("Vui lòng nháºp địa chỉ email!")
}
});
$(".btnDh").click(function (e) {
var data = new Object();
data.note = $("#note").val();
if ($("#address_required").length > 0) {
notificationError("Bạn Vui lòng thêm địa chỉ nháºn hà ng!");
return false;
}
$(".btnDh").text("Äang xá» lý...");
$(".btnDh").css("pointer-events", "none");
var url = site_folder + "/index_ajax.php?module_name=check_out&action=xac-nhan";
$.ajax({
url: url,
data: data,
type: "POST",
success: function (result) {
if (result === "2") {
notificationWarning("Không tồn tại sản phẩm nà o trong giỠhà ng.");
} else if (result === "3") {
notificationWarning("Äặt hà ng lá»—i, xin vui lòng thá» lại hoặc liên hệ chúng tôi.");
} else if (result === "4") {
notificationWarning("Vui lòng chá»n đơn vị váºn chuyển.");
} else if (result === "5") {
notificationWarning("Tà i khoản đang nợ AUTO365, Vui lòng liên hệ để được hỗ trợ!");
} else if (result === "6") {
notificationWarning("Phương thức thanh toán không phù hợp. Vui lòng thỠlại với phương thức khác.");
} else if (result === "7") {
notificationWarning("Vui lòng nháºp số tiá»n thu thêm, thông tin ngưá»i gá»i và lưu lại trước khi hoà n thà nh đặt hà ng.");
} else {
window.location.href = site_folder + "/don-hang/chi-tiet/" + result;
}
$(".btnDh").text("Äặt hà ng");
$(".btnDh").css("pointer-events", "inherit");
}
});
});
$("#btn_checkout").on("click", function () {
var data = new Object();
data.fullname = $("#cart_fullname").val();
data.phone = $("#cart_phone").val();
data.address = $("#cart_address").val();
data.email = $("#cart_email").val();
data.note = $("#cart_note").val();
if (data.fullname !== "" && data.phone !== "" && data.address !== "") {
$("#btn_checkout").text("ÄANG XỬ LÃ...");
var url = site_folder + "/index_ajax.php?module_name=check_out_nologin&action=dathang";
$.post(url, {
data
}, function (result) {
if (result !== '') {
window.location.href = result;
} else {
alert("Quý khách vui lòng kiểm tra thông tin đặt hà ng! Nháºp thông tin theo mô tả.");
$("#btn_checkout").text("ÄẶT HÀNG");
}
});
} else {
alert("Quý khách vui lòng kiểm tra thông tin đặt hà ng! Nháºp đầy đủ ô bắt buá»™c nháºp.");
}
});
$(".btn_useabove").click(function () {
$("#shipping_fullname").val($("#customer_fullname").val());
$("#shipping_phone").val($("#customer_phone").val());
$("#shipping_email").val($("#customer_email").val());
$("#shipping_address").val($("#customer_address").val());
$("#shipping_provinces").val($("#customer_provinces").val());
});
$('.add').click(function () {
if ($(this).prev().val() < 50) {
$(this).prev().val(+$(this).prev().val() + 1);
}
});
$('.sub').click(function () {
if ($(this).next().val() > 1) {
if ($(this).next().val() > 1) $(this).next().val(+$(this).next().val() - 1);
}
});
$(function () {
if ($("div.ellipsis_detail").length != 0) {
$("div.ellipsis_detail").dotdotdot({
height: 1472,
callback: dotdotdotCallback
});
}
});
$(function () {
$('[data-toggle="tooltip"]').tooltip()
})
//end documen ready
// withdraw
$("#btnWithraw").click(function (e) {
var data = new Object();
data.number_withdraw = $("#number_withdraw").val();
var max_withdraw = $("#number_withdraw").attr("max");
if (
data.number_withdraw === "" ||
typeof data.number_withdraw === "undefined"
) {
notificationWarning("Quý khách cần nháºp số tiá»n yêu cầu rút!");
return false;
} else if (parseInt(data.number_withdraw) > parseInt(max_withdraw)) {
notificationError("Quý khách chỉ được yêu cầu rút tối đa số dư hiện tại!");
return false;
} else {
$("#btnWithraw").text("Äang xá» lý...");
document.getElementById("btnWithraw").disabled = true;
var url = site_folder + "/index_ajax.php?module_name=wallet&action=ActionWithdraw";
$.ajax({
url: url,
data: data,
type: "POST",
success: function (result) {
notificationSuccess("Gá»i yêu cầu rút tiá»n thà nh công! Vui lòng chá» chúng tôi xác nháºn chuyển tiá»n!");
$("#btnWithraw").text("Xác nháºn yêu cầu");
document.getElementById("btnWithraw").disabled = false;
}
});
}
});
var valuerate = $(".rate2").data("rating");
var options = {
max_value: 5,
step_size: 1,
initial_value: valuerate,
};
$(".rate2").rate(options);
$(".rate2").on("change", function (ev, data) {
data.product_id = $("#product_id").val();
console.log(data.from, data.to);
$.post(site_folder + '/index_ajax.php?module_name=product&action=updaterating', {
"from": data.from,
"to": data.to,
"product_id": data.product_id
},
function (data) {
return true;
});
});
// active tab register
var url = window.location.href;
var activeTab = url.substring(url.indexOf("#") + 1);
$('a[href="#' + activeTab + '"]').tab('show')
//end documen ready
$("#codamount").on({
keyup: function () {
formatCurrency($(this));
},
blur: function () {
formatCurrency($(this), "blur");
}
});
jQuery(function ($) {
$(".sidebar-dropdown > a").click(function () {
$(".sidebar-submenu").slideUp(200);
if (
$(this)
.parent()
.hasClass("active")
) {
$(".sidebar-dropdown").removeClass("active");
$(this)
.parent()
.removeClass("active");
} else {
$(".sidebar-dropdown").removeClass("active");
$(this)
.next(".sidebar-submenu")
.slideDown(200);
$(this)
.parent()
.addClass("active");
}
});
$("#close-sidebar").click(function () {
$(".page-wrapper").removeClass("toggled");
});
$("#show-sidebar").click(function () {
$(".page-wrapper").addClass("toggled");
});
});
// END DOCUMENT #enddocument
});
//start 28.2.2020 #start
//end 28.2.2020 #end
function replaceUrlParam(url, paramName, paramValue) {
if (paramValue == null) {
paramValue = '';
}
var pattern = new RegExp('\\b(' + paramName + '=).*?(&|#|$)');
if (url.search(pattern) >= 0) {
return url.replace(pattern, '$1' + paramValue + '$2');
}
url = url.replace(/[?#]$/, '');
return url + (url.indexOf('?') > 0 ? '&' : '?') + paramName + '=' + paramValue;
};
function dotdotdotCallback(isTruncated) {
var elementExists = document.getElementsByClassName("ddd-truncated");
var ellipsis_detail = $("div.ellipsis_detail");
if (elementExists.length > 0) {
$(".button_ellipsis_detail").on('click', function () {
$(this).html("Thu gá»n <i class='fa fa-caret-up'></i>");
ellipsis_detail.trigger("destroy");
ellipsis_detail.dotdotdot({
height: null,
callback: dotdotdotCallback
});
});
} else {
$(".button_ellipsis_detail").on('click', function () {
$(this).html("Xem thêm <i class='fa fa-caret-down'></i>");
ellipsis_detail.trigger("destroy");
ellipsis_detail.dotdotdot({
height: 1472,
callback: dotdotdotCallback
});
});
}
}
function addWishlist(id) {
var url = site_folder + "/index_ajax.php?module_name=product&action=wishlist&id=" + id;
$.ajax({
url: url,
type: "POST",
success: function (res) {
if (parseInt(res) >= 0) {
$("#addWishlist").addClass("active");
notificationSuccess("Thêm thà nh công sản phẩm yêu thÃch!");
} else {
var c = window.confirm("Hệ thống yêu cầu đăng nháºp để thÃch sản phẩm, bạn có đồng ý chuyển qua trang đăng nháºp?");
if (c) {
window.location.href = site_folder + "/dang-nhap";
}
return true;
}
}
});
// ga('send', {
// 'hitType': 'event',
// 'eventCategory': 'WISHLIST',
// 'eventAction': 'Add',
// 'eventLabel': id,
// 'eventValue': '1',
// 'nonInteraction': true
// });
};
function addTocard(id) {
var data = new Object();
// data = $("#formProductItem").serialize();
data.id = id;
data.quantity = $("#formProductItem input[name='quantity']").val();
if (typeof $("#formProductItem input[name='product_type']").val() !== "undefined"
) {
var product_type_parent = getRadioVal(document.getElementById('formProductItem'), 'product_type_parent');
var product_type = getRadioVal(document.getElementById('formProductItem'), 'product_type');
console.log(product_type);
if (typeof product_type === "undefined" || product_type === "") {
$.notify({
message: 'Vui lòng chá»n loại sản phẩm'
}, {
type: 'warning',
placement: {
from: "bottom",
align: "right"
}
});
return false;
}
}
data.product_detail_id = product_type;
data.quantity_detail = $("#countQuantity").val();
if (parseInt(data.quantity) > parseInt(data.quantity_detail)) {
$.notify({
message: 'Số lượng hà ng tại kho không đủ cung cấp.'
}, {
type: 'warning',
placement: {
from: "bottom",
align: "right"
}
});
return false;
}
var url = site_folder + "/index_ajax.php?module_name=cart&action=add_ajax&id=" + id;
$.ajax({
url: url,
type: "POST",
data: data,
success: function (res) {
if (parseInt(res) >= 0) {
$("#addCart").addClass("active");
var numcart = $("#cardNum").attr("mydata-quantity");
$("#cardNum").attr("mydata-quantity", parseInt(numcart) + parseInt(1));
$.notify({
message: 'Thêm và o giỠhà ng thà nh công! Click xem giỠhà ng',
url: site_folder + "/gio-hang"
}, {
type: 'success',
placement: {
from: "bottom",
align: "right"
}
});
} else if (parseInt(res) >= -1) {
$("#signin").modal("show");
return true;
}
}
});
// ga('send', {
// 'hitType': 'event',
// 'eventCategory': 'CART',
// 'eventAction': 'Add',
// 'eventLabel': id,
// 'eventValue': '1',
// 'nonInteraction': true
// });
};
function addTocardNologin(id) {
var data = new Object();
data.id = id;
data.quantity = $("#formProductItem input[name='quantity']").val();
if (typeof $("#formProductItem input[name='product_type']").val() !== "undefined"
) {
var product_type_parent = getRadioVal(document.getElementById('formProductItem'), 'product_type_parent');
var product_type = getRadioVal(document.getElementById('formProductItem'), 'product_type');
if (typeof product_type === "undefined" || product_type === "") {
$.notify({
message: 'Vui lòng chá»n loại sản phẩm'
}, {
type: 'warning',
placement: {
from: "bottom",
align: "right"
}
});
return false;
}
data.product_detail_id = product_type;
}
var url = site_folder + "/index_ajax.php?module_name=cart_nologin&action=add_ajax&id=" + id;
$.ajax({
url: url,
type: "POST",
data: data,
success: function (res) {
window.location.href = site_folder + "/dat-hang-nhanh";
}
});
};
function updateImageCart(id, input) {
var data = new FormData();
data.append("id", id);
for ($i = 0; $i < input.files.length; $i++) {
if (input.files && input.files[$i]) {
var reader = new FileReader();
reader.onload = function (e) {
$("#created_img" + id).append(' <div style="padding: 10px;display: inline-block;float: left;width: 100px;">' +
'<a href="javscript:;" onclick="removeImageAfter()" class="removeImage"><i class="fa fa-trash"></i></a>' +
'<img id="blah' + $i + '" src="' + e.target.result + '" alt="your image" width="100%"/></div>');
};
reader.readAsDataURL(input.files[$i]);
data.append("file[]", input.files[$i]);
}
}
//Post form
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST", site_folder + "/index_ajax.php?module_name=cart&action=updateImageCart", true);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
// location.reload();
$("#required_upload").val(1);
$("#img_uploaded_" + id).html(xmlhttp.responseText);
$.notify({
message: 'Thêm hình ảnh thà nh công!'
}, {
type: 'success',
placement: {
from: "bottom",
align: "right"
}
});
}
}
xmlhttp.send(data);
}
function removeImage(id, value) {
$("#parents_image_" + id).remove();
var url = site_folder + "/index_ajax.php?module_name=cart&action=removeImage";
$.ajax({
url: url,
type: "POST",
data: {value: value, id: id},
success: function (data, textStatus, jqXHR) {
$.notify({
message: 'Xóa hình ảnh thà nh công!'
}, {
type: 'success',
placement: {
from: "bottom",
align: "right"
}
});
if (document.querySelectorAll('.removeImage').length <= 0) {
$("#required_upload").val("");
}
return;
}
});
}
function updateNoteCart(id) {
var note = $("textarea[name='notes[" + id + "]']").val();
if (note != "") {
var url = site_folder + "/index_ajax.php?module_name=cart&action=updateNoteCart";
$.ajax({
url: url,
type: "POST",
data: {note: note, id: id},
success: function (data, textStatus, jqXHR) {
$.notify({
message: 'Cáºp nháºt ghi chú thà nh công!'
}, {
type: 'success',
placement: {
from: "bottom",
align: "right"
}
});
return;
}
});
}
}
function buyNow(id) {
var data = new Object();
// data = $("#formProductItem").serialize();
data.id = id;
data.quantity = $("#formProductItem input[name='quantity']").val();
if (typeof $("#formProductItem input[name='product_type']").val() !== "undefined"
) {
var product_type_parent = getRadioVal(document.getElementById('formProductItem'), 'product_type_parent');
var product_type = getRadioVal(document.getElementById('formProductItem'), 'product_type');
console.log(product_type);
if (typeof product_type === "undefined" || product_type === "") {
$.notify({
message: 'Vui lòng chá»n loại sản phẩm'
}, {
type: 'warning',
placement: {
from: "bottom",
align: "right"
}
});
return false;
}
}
data.product_detail_id = product_type;
data.quantity_detail = $("#countQuantity").val();
if (parseInt(data.quantity) > parseInt(data.quantity_detail)) {
$.notify({
message: 'Số lượng hà ng tại kho không đủ cung cấp.'
}, {
type: 'warning',
placement: {
from: "bottom",
align: "right"
}
});
return false;
}
var url = site_folder + "/index_ajax.php?module_name=cart&action=add_ajax&id=" + id;
$.ajax({
url: url,
type: "POST",
data: data,
success: function (res) {
if (parseInt(res) >= 0) {
window.location.href = site_folder + "/gio-hang";
} else {
$("#signin").modal("show");
return true;
}
}
});
// ga('send', {
// 'hitType': 'event',
// 'eventCategory': 'CART',
// 'eventAction': 'Add',
// 'eventLabel': id,
// 'eventValue': '1',
// 'nonInteraction': true
// });
$('.iframe-link-ajax').magnificPopup({
type: 'ajax',
fixedContentPos: true,
fixedBgPos: true,
overflowY: 'auto',
closeBtnInside: true,
closeOnContentClick: true,
preloader: false,
midClick: true,
modal: "closeOnContentClick",
removalDelay: 300,
mainClass: 'my-mfp-zoom-in',
//gallery: { enabled: true }
});
};
function ChangeUploadFile() {
var x = document.getElementById("uploadFilehieuchuan");
var txt = "";
if ('files' in x) {
if (x.files.length == 0) {
txt = "Select one or more files.";
} else {
for (var i = 0; i < x.files.length; i++) {
var file = x.files[i];
if ('name' in file) {
txt += "name: " + file.name + "<br>";
}
if ('size' in file) {
txt += "size: " + file.size + " bytes <br>";
}
}
}
}
else {
if (x.value == "") {
txt += "Chá»n 1 hoặc nhiá»u files.";
} else {
txt += "Trình duyệt không hỗ trợ!";
txt += "<br>The path of the selected file: " + x.value; // If the browser does not support the files property, it will return the path of the selected file instead.
}
}
$("#fileuploadHieuchuan").append(txt);
}
function appendboxComment(comment_id) {
$("#boxCMT" + comment_id).html(" <div class=\"form-group\">\n" +
" <input type=\"text\" name=\"fullname\" id=\"fullname" + comment_id + "\" class=\"form-control form-control-nopd\"\n" +
" placeholder=\"HỠtên\" required/>\n" +
" </div>\n" +
" <div class=\"form-group\">\n" +
" <textarea name=\"comment\" class=\"form-control form-control-nopd\" id=\"comment" + comment_id + "\" cols=\"30\" rows=\"3\"\n" +
" placeholder=\"Má»i bạn để lại bình luáºn (Vui lòng gõ tiếng việt có dấu)\"\n" +
" required></textarea>\n" +
" </div>\n" +
" <div class=\"form-group text-right\">\n" +
" <button type=\"button\" onclick='RepCommentPro(" + comment_id + ")' class=\"btn btn-orange\">GỬI CÂU HỎI</button>\n" +
" </div>");
}
function addCommentPro() {
var comment = $("#comment").val();
var product_id = $("#product_id").val();
var fullname = $("#fullname").val();
if (comment !== "" && fullname !== "") {
$.post(site_folder + '/index_ajax.php?module_name=product&action=submitcomment', {
"comment": comment,
"fullname": fullname,
"product_id": product_id
},
function (data) {
$("#add_comment").html("<p class='alert alert-success'>Gá»i câu há»i thà nh công!</p>");
$("#fullname").val("");
$("#comment").val("");
return true;
});
} else {
alert("Vui lòng nháºp ná»™i dung đánh giá.");
}
}
function RepCommentPro(comment_id = 0) {
var comment = $("#comment" + comment_id).val();
var product_id = $("#product_id").val();
var fullname = $("#fullname" + comment_id).val();
if (comment !== "" && fullname !== "") {
$.post(site_folder + '/index_ajax.php?module_name=product&action=submitcomment', {
"comment": comment,
"fullname": fullname,
"comment_id": comment_id,
"product_id": product_id
},
function (data) {
$("#boxCMT" + comment_id).html("<p class='alert alert-success'>Gá»i câu há»i thà nh công!</p>");
return true;
});
} else {
alert("Vui lòng nháºp ná»™i dung đánh giá.");
}
}
function updateCartItem(id) {
var $this = $("#qty-" + id), qty = $this.val();
var url = site_folder + "/index_ajax.php?module_name=cart&action=updateCartItem&quantity=" + qty + "&id=" + id;
$.ajax({
url: url,
success: function (result) {
window.location.reload();
}
});
}
function addQty(id) {
var $this = $("#qty-" + id), qty = $this.val();
$this.val(parseInt(qty) + parseInt(1));
var url = site_folder + "/index_ajax.php?module_name=cart&action=update_add_cart&qty=add&id=" + id;
$.ajax({
url: url,
success: function (result) {
window.location.reload();
}
});
}
function subQty(id) {
var $this = $("#qty-" + id), qty = $this.val();
if (qty > 1) {
if (qty > 1) $this.val(parseInt(qty) - parseInt(1));
var url = site_folder + "/index_ajax.php?module_name=cart&action=update_add_cart&qty=sub&id=" + id;
$.ajax({
url: url,
success: function (result) {
window.location.reload();
}
});
}
}
//NOLOGIN
function updateCartItemNologin(id) {
var $this = $("#qty-" + id), qty = $this.val();
var url = site_folder + "/index_ajax.php?module_name=cart_nologin&action=updateCartItem&quantity=" + qty + "&id=" + id;
$.ajax({
url: url,
success: function (result) {
window.location.reload();
}
});
}
function addQtyNologin(id) {
var $this = $("#qty-" + id), qty = $this.val();
$this.val(parseInt(qty) + parseInt(1));
var url = site_folder + "/index_ajax.php?module_name=cart_nologin&action=update_add_cart&qty=add&id=" + id;
$.ajax({
url: url,
success: function (result) {
window.location.reload();
}
});
}
function subQtyNologin(id) {
var $this = $("#qty-" + id), qty = $this.val();
if (qty > 1) {
if (qty > 1) $this.val(parseInt(qty) - parseInt(1));
var url = site_folder + "/index_ajax.php?module_name=cart_nologin&action=update_add_cart&qty=sub&id=" + id;
$.ajax({
url: url,
success: function (result) {
window.location.reload();
}
});
}
}
//NOLOGIN
function getDistrict(sel) {
$("#input_ship_province").val(sel.options[sel.selectedIndex].text);
var url = site_folder + "/index_ajax.php?module_name=profile&action=getDistrict&province_id=" + $("#province_id").val();
$.ajax({
url: url,
success: function (result) {
$("#district_id").html(result);
}
});
}
function getWard(sel) {
$("#input_ship_district").val(sel.options[sel.selectedIndex].text);
var url = site_folder + "/index_ajax.php?module_name=profile&action=getWard&district_id=" + $("#district_id").val();
$.ajax({
url: url,
success: function (result) {
$("#ward_id").html(result);
}
});
}
function ChangeWard(sel) {
$("#input_ship_ward").val(sel.options[sel.selectedIndex].text);
}
function saveAddressShip() {
var data = new Object();
data.ship_name = $("#addressForm input[name='ship_name']").val();
data.ship_phone = $("#addressForm input[name='ship_phone']").val();
data.ship_email = $("#addressForm input[name='ship_email']").val();
data.ship_address = $("#addressForm input[name='ship_address']").val();
data.province_id = $("#addressForm select[name='ship_province']").val();
data.district_id = $("#addressForm select[name='ship_district']").val();
data.ward_id = $("#addressForm select[name='ship_ward']").val();
data.ship_province = $("#addressForm #input_ship_province").val();
data.ship_district = $("#addressForm #input_ship_district").val();
data.ship_ward = $("#addressForm #input_ship_ward").val();
data.note = $("#addressForm textarea[name='note']").val();
if (data.ship_name != "" && data.ship_phone != "" && data.ship_address != ""
&& data.province_id != "" && data.district_id != "" && data.ward_id != "") {
overlaybg();
var url = site_folder + "/index_ajax.php?module_name=check_out&action=saveAddressShip";
$.ajax({
url: url,
data: data,
type: "POST",
success: function (result) {
unoverlaybg();
if (result.length == 1) {
location.reload();
} else {
alert(result);
}
return false;
}
});
} else {
notificationError("Vui lòng nháºp các trưá»ng bắt buá»™c!");
unoverlaybg();
}
}
function changeAddress(_id) {
$("#address_id_change").val(_id);
}
function changeAddressShip(_id) {
overlaybg();
$(".divinputcheck").removeClass("checked");
// data.ship_member_id = $("#address_id_change").val();
$(".divinputcheck_" + _id).addClass("checked");
var data = new Object();
data.ship_member_id = _id;
var url = site_folder + "/index_ajax.php?module_name=check_out&action=changeAddressShip";
$.ajax({
url: url,
data: data,
type: "POST",
success: function (result) {
location.reload();
}
});
}
function savePayment(value, payment_method) {
if (document.getElementById("radio_button_" + value).disabled == true) {
if (value == 3) {
notificationError("Số tiá»n trong tà i khoản và không đủ đặt hà ng!");
} else {
notificationError("Tà i khoản và đang nợ AUTO365, Vui lòng liên hệ quản trị để được hỗ trợ!");
}
return;
}
$("form#changePaymentForm .my-checkbox").removeClass("checked");
$(".btn_check_payment_default").removeClass("checked");
$("#my_checkbox_" + value).addClass("checked");
$("#optioncod_1").removeClass("active");
if (value === 1) {
$("#optioncod").addClass("active");
$("#shipCarBus").removeClass("active");
} else {
$("#optioncod").removeClass("active");
$("#shipCarBus").addClass("active");
}
var data = new Object();
data.payment = value;
data.payment_method = payment_method;
var url = site_folder + "/index_ajax.php?module_name=check_out&action=savePayment";
$.ajax({
url: url,
data: data,
type: "POST",
success: function (result) {
if (result === '3') {
document.getElementById("radio_button_3").checked = false;
$("#my_checkbox_3").removeClass("checked");
notificationError("Số tiá»n trong tà i khoản và không đủ đặt hà ng!");
} else if (result === '4') {
document.getElementById("radio_button_3").checked = false;
notificationError("Tà i khoản và đang nợ AUTO365, Vui lòng liên hệ quản trị để được hỗ trợ!");
} else {
if (value > 1) {
// location.reload();
window.location.href = site_folder + "/dat-hang";
}
}
return false;
}
});
}
function savePaymentCod(value) {
$("form#changePaymentForm #optioncod .my-checkbox").removeClass("checked");
$(".check_thu_ho_css").removeClass("checked");
$("#optioncod #my_checkbox_c_" + value).addClass("checked");
if (value == 1) {
$("#optioncod_1").addClass("active");
} else {
$("#optioncod_1").removeClass("active");
}
var data = new Object();
data.thu_ho = value;
var url = site_folder + "/index_ajax.php?module_name=check_out&action=savePaymentCOD";
$.ajax({
url: url,
data: data,
type: "POST",
success: function (result) {
// location.reload();
window.location.href = site_folder + "/dat-hang";
return false;
}
});
}
function saveInfoSend() {
var data = new Object();
data.send_info = $("#infoSend").val();
data.codamount = $("#codamount").val();
data.send_name = $("#send_name").val();
if (data.codamount == "" || data.codamount == 'undefined') {
notificationWarning("Vui lòng nháºp số tiá»n muốn thu thêm.");
return;
}
if (data.send_name == "" || data.send_name == 'undefined') {
notificationWarning("Vui lòng nháºp tên ngưá»i gá»i hà ng.");
return;
}
if (data.send_info == "" || data.send_info == 'undefined') {
notificationWarning("Vui lòng nháºp thông tin ngưá»i gá»i hà ng.");
return;
}
var url = site_folder + "/index_ajax.php?module_name=check_out&action=savePaymentCOD";
$.ajax({
url: url,
data: data,
type: "POST",
success: function (result) {
console.log(result);
if (result === "8") {
notificationWarning("Thông tin ngưá»i gá»i và ngưá»i nháºn hà ng không được trùng.");
return;
} else {
// location.reload();
window.location.href = site_folder + "/dat-hang";
}
// notificationSuccess("Lưu địa thà nh công!");
return false;
}
});
}
function saveDelivery(value, _index) {
overlaybg();
$(".label_shipchagne_modal").removeClass("checked");
var data = new Object();
data.ship_id = value;
data.ship_index = _index;
var url = site_folder + "/index_ajax.php?module_name=check_out&action=saveDelivery";
$.ajax({
url: url,
data: data,
type: "POST",
success: function (result) {
$(".shipchagne_" + _index).addClass("checked");
// location.reload();
window.location.href = site_folder + "/dat-hang";
return;
}
});
unoverlaybg();
return;
}
function changeValueTypeParent(_id, id_type, quantity) {
$(".checkParent .product-variation").removeClass("checked");
$(".checkParent .check_" + _id).addClass("checked");
$(".checkSubType .product-variation").removeClass("checked");
$("#countpro_whouse").html(quantity + " sản phẩm tại kho");
$("#countQuantity").val(quantity);
$(".spLock").removeClass("bg_opacity_50");
// getTypeS(id_type);
ChangeConvert(_id);
}
function ChangeConvert(id_type) {
$(".c_all_sublist").css("display", "none");
$(".listSub_" + id_type).css("display", "block");
}
function changeValueType(_id, id_type, quantity, price, sku) {
var data = new Object();
data.quantity = $("#formProductItem input[name='quantity']").val();
$(".checkSubType .product-variation").removeClass("checked");
$(".checkSubType .check_sub" + _id).addClass("checked");
document.getElementById("typesSub_" + _id).checked = true;
$("#countpro_whouse").html(quantity + " sản phẩm tại kho");
$("#countQuantity").val(quantity);
$("#pricePro").html(numberFormat(price) + "Ä‘");
$("#sku_sp").html(sku);
}
function getTypeS(id_type) {
var data = new Object();
data.id = $("#product_id").val();
data.type_c_id = id_type;
var url = site_folder + "/index_ajax.php?module_name=product&action=getTypeS";
$.ajax({
url: url,
data: data,
type: "POST",
success: function (result) {
$("#SSubType").html(result);
return false;
}
});
}
function loginPage() {
var data = new Object();
data.phone = $("form#loginForm #phone").val();
data.pass = $("form#loginForm #pass").val();
var url = site_folder + "/index_ajax.php?module_name=login&action=loginajax";
$.ajax({
url: url,
data: data,
type: "POST",
success: function (result) {
if (result.length == 1) {
location.reload();
} else {
alert(result);
}
return false;
}
});
}
function hasWhiteSpace(s) {
return s.indexOf(' ') >= 0;
}
function registerPage() {
var username = $('input[name="register[username]"]').val();
if (username == "") {
notificationWarning("Vui lòng nháºp Tên đăng nháºp!");
return;
}
if (username.indexOf(" ") >= 0) {
notificationWarning("Tên đăng nháºp viết liá»n, không dấu.");
return;
}
if ($('input[name="register[phone]"]').val() == "") {
notificationWarning("Vui lòng nháºp Số Ä‘iện thoại!");
return;
}
if ($('input[name="register[zalo_phone]"]').val() == "") {
notificationWarning("Vui lòng nháºp Số Äiện thoại Zalo!");
return;
}
if ($('input[name="register[zalo_name]"]').val() == "") {
notificationWarning("Vui lòng nháºp Số tên Zalo!");
return;
}
if ($('input[name="register[password]"]').val() == "") {
notificationWarning("Vui lòng nháºp Số Máºt khẩu!");
return;
}
if ($('input[name="register[repassword]"]').val() == "") {
notificationWarning("Vui lòng nháºp Số Xác nháºn máºt khẩu!");
return;
}
if ($('input[name="register[repassword]"]').val() != $('input[name="register[password]"]').val()) {
notificationWarning("Máºt khẩu và Máºt khẩu xác nháºn không giống nhau!");
return;
}
var form = document.forms.namedItem("registerForm");
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
var data = new FormData(form);
var url = site_folder + "/index_ajax.php?module_name=login&action=registerajax";
xmlhttp.open("POST", url, true);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
if (xmlhttp.responseText != "") {
alert(xmlhttp.responseText);
} else {
location.reload();
}
}
}
xmlhttp.send(data);
}
function changeDefaultAddress(id) {
var data = new Object();
data.id = id;
var url = site_folder + "/index_ajax.php?module_name=profile&action=changeAddressDefault";
$.ajax({
url: url,
data: data,
type: "POST",
success: function (result) {
location.reload();
return false;
}
});
}
function removeAddress(id) {
if (confirm("Xác nháºn xóa địa chỉ?")) {
window.location.href = site_folder + "/thong-tin-ca-nhan/dia-chi/" + id + "?ac=del";
}
return;
}
function thanhToanCart() {
if ($("#required_upload").val() == "" || $("#required_upload").val() == "undefined") {
notificationWarning("Vui lòng tải lên hình ảnh mẫu cho sản phẩm muốn đặt hà ng.");
return;
}
if ($("#quote_note").length > 0) {
if ($("#quote_note").val() != "") {
$("#btn_pendding").text("Äang xá» lý...");
$("#btn_pendding").css("pointer-events", "none");
window.location.href = site_folder + "/dat-hang?from=cart";
} else {
notificationWarning("Vui lòng nháºp mô tả vá» sản phẩm muốn đặt hà ng.");
}
} else {
$("#btn_pendding").text("Äang xá» lý...");
$("#btn_pendding").css("pointer-events", "none");
window.location.href = site_folder + "/dat-hang?from=cart";
}
}
function readURL(input) {
var data = new FormData();
data.append("avatar", input.files[0]);
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST", site_folder + "/index_ajax.php?module_name=profile&action=updateavatar", true);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
location.reload();
}
}
xmlhttp.send(data);
}
function showhidemodal(el) {
$(".modal").modal("hide");
$("#" + el).modal("show");
}
function showMenu() {
$("#menuListLeft").addClass("active");
}
function loadingOpen() {
$("#loader").removeClass("loader");
$("#loader").removeClass("loader-fade");
}
function loadingClose() {
$("#loader").addClass("loader");
$("#loader").addClass("loader-fade");
}
function boxType(product_id) {
var data = new Object();
data.product_id = product_id;
var url = site_folder + "/index_ajax.php?module_name=ajax&action=box_type";
$.ajax({
url: url,
type: "POST",
data: data,
dataType: "html",
cache: false,
success: function (res) {
if (res !== "") {
$("#box_type_list").html(res);
} else {
return true;
}
}
});
}
function showModalStore(code) {
if (code !== '') {
var data = new Object();
data.code = code;
var url = site_folder + "/index_ajax.php?module_name=contact&action=detail";
$.ajax({
url: url,
type: "POST",
data: data,
success: function (result) {
$("#detail_store").modal();
console.log(result);
$("#detail_store .modal-content").html(result);
}
})
}
}
/*$(".hover_width_resize").hover(function(){
// $(this).css("background-color", "yellow");
// $(this).removeClass();
$(this).css("transition", "1s all");
$(this).css("width", "100%");
// $(this).addClass("col-md-12");
}, function(){
// $(this).removeClass("col-md-12");
// $(this).addClass("col-md-6");
// $(this).css("background-color", "pink");
$(this).css("width", "50%");
});*/
function bigBox(x) {
$(this).removeClass("col-md-12");
$(this).addClass("col-md-12");
}
function normalBox(x) {
x.style.height = "32px";
x.style.width = "32px";
}
function saveCacheChangeCate(category_id) {
var data = new Object();
data.category_id = category_id;
var url = site_folder + "/index_ajax.php?module_name=product&action=saveCacheChangeCate";
$.ajax({
url: url,
type: "POST",
data: data,
success: function (result) {
return;
}
})
}
// serviceHover = () => {
// let left = $(".product-home-main .w-product .left");
// let right = $(".product-home-main .w-product .right");
// if (left.length > 0 && right.length > 0) {
// left.mouseenter(function () {
// $(this).addClass("left-hover").removeClass("right-hover");
// right.addClass("left-hover").removeClass("right-hover");
//
// });
//
// left.mouseleave(function (e) {
// $(this).removeClass("left-hover");
// right.removeClass("left-hover");
// });
//
// right.mouseenter(function () {
// $(this).addClass("right-hover").removeClass("left-hover");
// left.addClass("right-hover").removeClass("left-hover");
// });
//
// right.mouseleave(function (e) {
// $(this).removeClass("right-hover");
// left.removeClass("right-hover");
// });
//
// }
// }
var myCore = {
init: function () {
this.Basic.init();
},
Basic: {
init: function () {
this.preloader();
this.dotdotdot();
this.menuHover();
// this.menuClick();
this.checkMobile();
this.categorySlider();
this.productImageZoom();
this.showContentProd();
this.productGalleryV1();
},
currentWidth: function () {
return $(window).innerWidth();
},
preloader: function () {
jQuery(window).on('load', function () {
jQuery('#preloader').fadeOut('slow', function () {
jQuery(this).remove();
});
});
},
dotdotdot: function () {
if ($('.threedot').length != 0) {
$('.threedot').dotdotdot({
ellipsis: '...',
watch: true,
wrap: 'word',
after: "a.readmore"
});
}
},
menuHover: function () {
$('.nav-menu .ul-main .li-main').hover(function () {
$(this).find('.a-main').toggleClass('active');
})
},
menuClick: function () {
$('.menu-toogle').click(function () {
$('.ul-main').addClass("show");
});
$('.close-menu').click(function () {
$('.ul-main').removeClass("show");
});
// $('.nav-menu .ul-main .li-main .a-main').click(function (e) {
// e.preventDefault();
// var self = $(this);
// if ($(".nav-menu .ul-main").hasClass("menu-mobile")) {
// self.next().addClass("show");
//
// } else {
// $(".sub-box").removeClass("show");
// }
//
// });
$(".sub-menu-close").click(function (e) {
e.preventDefault();
$(".sub-box").removeClass("show");
})
},
checkMobile: function () {
if (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|ipad|iris|kindle|Android|Silk|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(navigator.userAgent) ||
/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(navigator.userAgent.substr(0, 4))) {
$("body").addClass('isMobile');
$(".ul-main").addClass("menu-mobile");
} else {
$("body").removeClass('isMobile');
$(".ul-main").removeClass("menu-mobile");
}
},
categorySlider: function () {
$('.banner-cate').not('.slick-initialized').slick({
centerMode: true,
centerPadding: '60px',
slidesToShow: 1
});
},
productImageZoom: function () {
if ($(".isMobile").length <= 0) {
var zoomWidth = $(".product-block .wrap .right").innerWidth();
var zoomHeight = $(".product-block .wrap .right").innerHeight();
$("#zoom_01").elevateZoom({
gallery: 'gallery_01',
cursor: 'pointer',
galleryActiveClass: 'active',
imageCrossfade: false,
borderSize: 1,
zoomWindowWidth: zoomWidth,
zoomWindowHeight: zoomHeight,
zoomWindowOffetx: 15,
zoomWindowOffety: -15
});
$("#zoom_01").bind("click", function (e) {
var ez = $('#zoom_01').data('elevateZoom');
$.fancybox(ez.getGalleryList());
return false;
});
} else {
$("#gallery_01 a").click(function (e) {
e.preventDefault();
var imgLink = $(this).attr("data-image");
$("#zoom_01").attr("src", imgLink);
});
}
},
productGalleryV1: function () {
var _productGallery = $('#imageGallery');
if (_productGallery.length > 0) {
_productGallery.lightSlider({
gallery: true,
item: 1,
loop: true,
thumbItem: 4,
slideMargin: 0,
enableDrag: false,
currentPagerPosition: 'left',
onSliderLoad: function (el) {
$("body").on("click", ".lslide.active .slide_img_play", function () {
el.lightGallery({
selector: '#imageGallery .lslide'
});
$("body .lslide.active").trigger("click");
})
if (_productGallery.hasClass("has-video")) {
if ($(".lslide.active").find("iframe").length == 0) {
var iframe = '<iframe width="100%" src="' + $("#imageGallery").attr('data-iframe') + '"' +
' frameborder="0" ' +
'allowfullscreen></iframe>';
$(".lslide.active").addClass("contain-iframe").append(iframe);
$('.lslide img').removeClass("slide_img_play");
}
$("body").on("click", ".lslide.active .play_video", function () {
$('.lslide img').removeClass("slide_img_play");
if ($(".lslide.active").find("iframe").length == 0) {
var iframe = '<iframe width="100%" src="' + $("#imageGallery").attr('data-iframe') + '" ' +
'frameborder="0" ' +
'allowfullscreen></iframe>';
$(".lslide.active").addClass("contain-iframe").append(iframe);
}
})
} else {
el.lightGallery({
selector: '#imageGallery .lslide'
});
}
},
onAfterSlide: function () {
$('.lslide').removeClass("contain-iframe").find("iframe").remove();
$('.lslide img').addClass("slide_img_play");
}
});
}
},
showContentProd: function () {
var self = $(".prod-information-block .prod-desc .content");
var height = self.innerHeight();
if (height >= 500) {
self.addClass("isReadMore");
}
$(".prod-information-block .prod-desc .readmore-block a").click(function () {
self.toggleClass("isExpand");
if ($(".isExpand").length > 0) {
$(this).html("Thu Gá»n Ná»™i Dung");
} else {
$(this).html("Xem Thêm Nội Dung");
}
});
}
}
};
function openListAgency(code) {
$("#agencyModal").modal('show');
var data = new Object();
data.code = code;
var url = site_folder + "/index_ajax.php?module_name=agency&action=agency&code="+code;
$.ajax({
url: url,
type: "POST",
data: data,
success: function (result) {
$("#contentAgency").html(result);
}
})
}
| 35.211105 | 1,667 | 0.489504 |
bbe3540a2f605ba09702f49fb8d07bf17bca3f89 | 5,428 | js | JavaScript | source/main/utils/setupLogging.js | katapultmedia/daedalus | caac11bfcdaf7918989871da5f661a665e15f4dd | [
"ECL-2.0",
"Apache-2.0"
] | 1,291 | 2017-01-19T04:35:51.000Z | 2022-03-31T20:33:09.000Z | source/main/utils/setupLogging.js | katapultmedia/daedalus | caac11bfcdaf7918989871da5f661a665e15f4dd | [
"ECL-2.0",
"Apache-2.0"
] | 1,797 | 2017-01-13T11:01:09.000Z | 2022-03-30T16:05:31.000Z | source/main/utils/setupLogging.js | katapultmedia/daedalus | caac11bfcdaf7918989871da5f661a665e15f4dd | [
"ECL-2.0",
"Apache-2.0"
] | 361 | 2017-01-12T19:02:33.000Z | 2022-03-27T16:32:28.000Z | // @flow
import fs from 'fs';
import path from 'path';
import log from 'electron-log-daedalus';
import rimraf from 'rimraf';
import ensureDirectoryExists from './ensureDirectoryExists';
import { pubLogsFolderPath, appLogsFolderPath } from '../config';
import {
constructMessageBody,
formatMessage,
stringifyData,
} from '../../common/utils/logging';
import { isFileNameWithTimestamp } from '../../common/utils/files';
import type {
ConstructMessageBodyParams,
MessageBody,
LogSystemInfoParams,
StateSnapshotLogParams,
WalletMigrationReportData,
} from '../../common/types/logging.types';
const isTest = process.env.NODE_ENV === 'test';
const isDev = process.env.NODE_ENV === 'development';
export const setupLogging = () => {
const logFilePath = path.join(pubLogsFolderPath, 'Daedalus.json');
ensureDirectoryExists(pubLogsFolderPath);
rimraf.sync(path.join(pubLogsFolderPath, './Daedalus.*'));
log.transports.console.level = isTest ? 'error' : 'info';
log.transports.rendererConsole.level = isDev ? 'info' : 'error';
log.transports.file.level = 'debug';
log.transports.file.maxSize = 5 * 1024 * 1024; // 5MB, unit bytes
log.transports.file.maxItems = 4;
log.transports.file.timeStampPostfixFormat = '{y}{m}{d}{h}{i}{s}';
log.transports.file.file = logFilePath;
log.transports.console.format = (message: Object): string =>
formatMessage(message);
log.transports.file.format = (message: Object): string => {
// Debug level logging is recorded as "info" in Daedalus log files
// but at the same time we do not want to output it to console or terminal window
const level = message.level === 'debug' ? 'info' : message.level;
return formatMessage({ ...message, level });
};
log.transports.rendererConsole.format = (message: Object): string => {
// deconstruct message data
const date = message.date.toISOString();
const [year, time] = date.split('T');
const [context, messageData] = message.data;
const { message: msg, data = {} } = messageData;
// log minimal message body in the renderer console
let messageBody = { msg, data };
if (typeof data === 'string') {
messageBody = { ...messageBody, data: { response: data } };
}
return `[${year}T${time.slice(0, -1)}Z] ${context} ${stringifyData(
messageBody
)}`;
};
// Removes existing compressed logs
fs.readdir(appLogsFolderPath, (err, files) => {
files.filter(isFileNameWithTimestamp()).forEach((fileName) => {
const filePath = path.join(appLogsFolderPath, fileName);
try {
fs.unlinkSync(filePath);
} catch (error) {
// eslint-disable-next-line no-console
console.error(
`Compressed log file "${filePath}" deletion failed: ${error}`
);
}
});
});
};
export const logSystemInfo = (props: LogSystemInfoParams): MessageBody => {
const { ...data } = props;
const {
network,
osName,
platformVersion,
daedalusVersion,
startTime: at,
} = data;
const env = `${network}:${osName}:${platformVersion}`;
const messageBodyParams: ConstructMessageBodyParams = {
at,
env,
ns: ['daedalus', `v${daedalusVersion}`, `*${network}*`],
data,
msg: 'Updating System-info.json file',
pid: '',
sev: 'info',
thread: '',
};
const messageBody: MessageBody = constructMessageBody(messageBodyParams);
const systemInfoFilePath = path.join(pubLogsFolderPath, 'System-info.json');
fs.writeFileSync(systemInfoFilePath, JSON.stringify(messageBody));
return messageBody;
};
export const logStateSnapshot = (
props: StateSnapshotLogParams
): MessageBody => {
const { ...data } = props;
const { currentTime: at, systemInfo, coreInfo } = data;
const {
platform,
platformVersion,
cpu,
ram,
availableDiskSpace,
} = systemInfo;
const {
daedalusVersion,
daedalusProcessID,
daedalusMainProcessID,
isBlankScreenFixActive,
cardanoNodeVersion,
cardanoNetwork,
cardanoNodePID,
cardanoWalletVersion,
cardanoWalletPID,
cardanoWalletApiPort,
daedalusStateDirectoryPath,
} = coreInfo;
const env = `${cardanoNetwork}:${platform}:${platformVersion}`;
const messageBodyParams: ConstructMessageBodyParams = {
at,
env,
msg: 'Updating State-snapshot.json file',
pid: '',
sev: 'info',
thread: '',
ns: ['daedalus', `v${daedalusVersion}`, `*${cardanoNetwork}*`],
platform,
platformVersion,
cpu,
ram,
availableDiskSpace,
daedalusVersion,
daedalusProcessID,
daedalusMainProcessID,
isBlankScreenFixActive,
cardanoNetwork,
cardanoNodeVersion,
cardanoNodePID,
cardanoWalletVersion,
cardanoWalletPID,
cardanoWalletApiPort,
daedalusStateDirectoryPath,
data,
};
const messageBody: MessageBody = constructMessageBody(messageBodyParams);
const stateSnapshotFilePath = path.join(
pubLogsFolderPath,
'State-snapshot.json'
);
fs.writeFileSync(stateSnapshotFilePath, JSON.stringify(messageBody));
return messageBody;
};
export const generateWalletMigrationReport = (
data: WalletMigrationReportData
) => {
const walletMigrationrReportFilePath = path.join(
pubLogsFolderPath,
'Wallet-migration-report.json'
);
const generatedAt = new Date().toISOString();
fs.writeFileSync(
walletMigrationrReportFilePath,
JSON.stringify({ ...data, generatedAt })
);
};
| 30.494382 | 85 | 0.680914 |
bbe37cd620faf22739b69bff4259a7ddec6937e9 | 4,403 | js | JavaScript | lib/services/mysqlManagement/lib/models/serverSecurityAlertPolicy.js | scbedd/azure-sdk-for-node | 6faf0dce4bb2a7d65592047852cb5abeb5282bbc | [
"Apache-2.0",
"MIT"
] | 748 | 2015-01-01T08:16:53.000Z | 2022-03-30T22:10:40.000Z | lib/services/mysqlManagement/lib/models/serverSecurityAlertPolicy.js | scbedd/azure-sdk-for-node | 6faf0dce4bb2a7d65592047852cb5abeb5282bbc | [
"Apache-2.0",
"MIT"
] | 2,114 | 2015-01-06T10:28:57.000Z | 2022-03-31T02:07:25.000Z | lib/services/mysqlManagement/lib/models/serverSecurityAlertPolicy.js | scbedd/azure-sdk-for-node | 6faf0dce4bb2a7d65592047852cb5abeb5282bbc | [
"Apache-2.0",
"MIT"
] | 567 | 2015-01-16T13:21:23.000Z | 2022-01-06T00:49:46.000Z | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'use strict';
const models = require('./index');
/**
* A server security alert policy.
*
* @extends models['ProxyResource']
*/
class ServerSecurityAlertPolicy extends models['ProxyResource'] {
/**
* Create a ServerSecurityAlertPolicy.
* @member {string} state Specifies the state of the policy, whether it is
* enabled or disabled. Possible values include: 'Enabled', 'Disabled'
* @member {array} [disabledAlerts] Specifies an array of alerts that are
* disabled. Allowed values are: Sql_Injection, Sql_Injection_Vulnerability,
* Access_Anomaly
* @member {array} [emailAddresses] Specifies an array of e-mail addresses to
* which the alert is sent.
* @member {boolean} [emailAccountAdmins] Specifies that the alert is sent to
* the account administrators.
* @member {string} [storageEndpoint] Specifies the blob storage endpoint
* (e.g. https://MyAccount.blob.core.windows.net). This blob storage will
* hold all Threat Detection audit logs.
* @member {string} [storageAccountAccessKey] Specifies the identifier key of
* the Threat Detection audit storage account.
* @member {number} [retentionDays] Specifies the number of days to keep in
* the Threat Detection audit logs.
*/
constructor() {
super();
}
/**
* Defines the metadata of ServerSecurityAlertPolicy
*
* @returns {object} metadata of ServerSecurityAlertPolicy
*
*/
mapper() {
return {
required: false,
serializedName: 'ServerSecurityAlertPolicy',
type: {
name: 'Composite',
className: 'ServerSecurityAlertPolicy',
modelProperties: {
id: {
required: false,
readOnly: true,
serializedName: 'id',
type: {
name: 'String'
}
},
name: {
required: false,
readOnly: true,
serializedName: 'name',
type: {
name: 'String'
}
},
type: {
required: false,
readOnly: true,
serializedName: 'type',
type: {
name: 'String'
}
},
state: {
required: true,
serializedName: 'properties.state',
type: {
name: 'Enum',
allowedValues: [ 'Enabled', 'Disabled' ]
}
},
disabledAlerts: {
required: false,
serializedName: 'properties.disabledAlerts',
type: {
name: 'Sequence',
element: {
required: false,
serializedName: 'StringElementType',
type: {
name: 'String'
}
}
}
},
emailAddresses: {
required: false,
serializedName: 'properties.emailAddresses',
type: {
name: 'Sequence',
element: {
required: false,
serializedName: 'StringElementType',
type: {
name: 'String'
}
}
}
},
emailAccountAdmins: {
required: false,
serializedName: 'properties.emailAccountAdmins',
type: {
name: 'Boolean'
}
},
storageEndpoint: {
required: false,
serializedName: 'properties.storageEndpoint',
type: {
name: 'String'
}
},
storageAccountAccessKey: {
required: false,
serializedName: 'properties.storageAccountAccessKey',
type: {
name: 'String'
}
},
retentionDays: {
required: false,
serializedName: 'properties.retentionDays',
type: {
name: 'Number'
}
}
}
}
};
}
}
module.exports = ServerSecurityAlertPolicy;
| 28.777778 | 79 | 0.525778 |
bbe4379cb466c01c6137c2d706e6e44d85a5f89c | 25,514 | js | JavaScript | lib/inspect.js | klein0r/ioBroker.javascript | 3574660276f690356a43a83acbc8049c6a453d89 | [
"MIT"
] | 299 | 2015-01-11T20:57:37.000Z | 2022-03-24T14:31:46.000Z | lib/inspect.js | klein0r/ioBroker.javascript | 3574660276f690356a43a83acbc8049c6a453d89 | [
"MIT"
] | 893 | 2015-06-02T06:30:58.000Z | 2022-03-31T08:48:45.000Z | lib/inspect.js | klein0r/ioBroker.javascript | 3574660276f690356a43a83acbc8049c6a453d89 | [
"MIT"
] | 174 | 2015-01-20T19:42:28.000Z | 2022-03-04T20:07:06.000Z | /*
* Copyright Node.js contributors. All rights reserved.
*
* 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.
*/
'use strict';
const { spawn } = require('child_process');
const { EventEmitter } = require('events');
const net = require('net');
const util = require('util');
const path = require('path');
const fs = require('fs');
let breakOnStart;
for (let i = 0; i < process.argv.length; i++) {
if (process.argv[i] === '--breakOnStart') {
breakOnStart = true;
}
}
//const runAsStandalone = typeof __dirname !== 'undefined';
const InspectClient = require('node-inspect/lib/internal/inspect_client');
const createRepl = require('./debugger');
const debuglog = util.debuglog('inspect');
class StartupError extends Error {
constructor(message) {
super(message);
this.name = 'StartupError';
}
}
function portIsFree(host, port, timeout = 9999) {
if (port === 0) return Promise.resolve(); // Binding to a random port.
const retryDelay = 150;
let didTimeOut = false;
return new Promise((resolve, reject) => {
setTimeout(() => {
didTimeOut = true;
reject(new StartupError(
`Timeout (${timeout}) waiting for ${host}:${port} to be free`));
}, timeout);
function pingPort() {
if (didTimeOut) return;
const socket = net.connect(port, host);
let didRetry = false;
function retry() {
if (!didRetry && !didTimeOut) {
didRetry = true;
setTimeout(pingPort, retryDelay);
}
}
socket.on('error', (error) => {
if (error.code === 'ECONNREFUSED') {
resolve();
} else {
retry();
}
});
socket.on('connect', () => {
socket.destroy();
retry();
});
}
pingPort();
});
}
function runScript(script, scriptArgs, inspectHost, inspectPort, childPrint) {
return portIsFree(inspectHost, inspectPort)
.then(() => {
return new Promise((resolve) => {
const args = [breakOnStart ? `--inspect-brk=${inspectPort}` : `--inspect=${inspectPort}`].concat([script], scriptArgs);
const child = spawn(process.execPath, args);
child.stdout.setEncoding('utf8');
child.stderr.setEncoding('utf8');
child.stdout.on('data', childPrint);
child.stderr.on('data', text => childPrint(text, true));
let output = '';
function waitForListenHint(text) {
output += text;
if (/Debugger listening on ws:\/\/\[?(.+?)\]?:(\d+)\//.test(output)) {
const host = RegExp.$1;
const port = Number.parseInt(RegExp.$2);
child.stderr.removeListener('data', waitForListenHint);
resolve([child, port, host]);
}
}
child.stderr.on('data', waitForListenHint);
});
});
}
function createAgentProxy(domain, client) {
const agent = new EventEmitter();
agent.then = (...args) => {
// TODO: potentially fetch the protocol and pretty-print it here.
const descriptor = {
[util.inspect.custom](depth, { stylize }) {
return stylize(`[Agent ${domain}]`, 'special');
},
};
return Promise.resolve(descriptor).then(...args);
};
return new Proxy(agent, {
get(target, name) {
if (name in target) return target[name];
return function callVirtualMethod(params) {
return client.callMethod(`${domain}.${name}`, params);
};
},
});
}
class NodeInspector {
constructor(options, stdin, stdout) {
this.options = options;
this.stdin = stdin;
this.stdout = stdout;
this.scripts = {};
this.paused = true;
this.child = null;
if (options.script) {
this._runScript = runScript.bind(null,
options.script,
options.scriptArgs,
options.host,
options.port,
this.childPrint.bind(this));
} else {
this._runScript =
() => Promise.resolve([null, options.port, options.host]);
}
this.client = new InspectClient();
this.domainNames = ['Debugger', 'HeapProfiler', 'Profiler', 'Runtime'];
this.domainNames.forEach((domain) => {
this[domain] = createAgentProxy(domain, this.client);
});
this.handleDebugEvent = (fullName, params) => {
const [domain, name] = fullName.split('.');
if (domain === 'Debugger' && name === 'scriptParsed') {
//console.log(params.url);
if ((scriptToDebug && params.url.includes(scriptToDebug)) || (instanceToDebug && params.url.includes(instanceToDebug))) {
console.log('My scriptID: ' + params.scriptId);
this.mainScriptId = params.scriptId;
this.mainFile = params.url.replace('file:///', '');
// load text of script
this.scripts[this.mainScriptId ] = this.Debugger.getScriptSource({ scriptId: this.mainScriptId })
.then(script => ({script: script.scriptSource, scriptId: this.mainScriptId}));
}
return;
} else
if (domain === 'Debugger' && name === 'resumed') {
this.Debugger.emit(name, params);
sendToHost({cmd: 'resumed', context: params});
return;
} else
if (domain === 'Debugger' && name === 'paused') {
console.log('PAUSED!!');
if (!alreadyPausedOnFirstLine && params.reason === 'exception') {
// ignore all exceptions by start
this.Debugger.resume();
return;
}
//console.warn(fullName + ': => \n' + JSON.stringify(params, null, 2));
this.Debugger.emit(name, params);
if (!alreadyPausedOnFirstLine) {
alreadyPausedOnFirstLine = true;
this.scripts[this.mainScriptId]
.then(data =>
sendToHost({cmd: 'readyToDebug', scriptId: data.scriptId, script: data.script, context: params, url: this.mainFile}));
} else {
//this.scripts[params.loca]
// .then(data =>
sendToHost({cmd: 'paused', context: params});
}
return;
}
if (domain === 'Runtime') {
//console.warn(fullName + ': => \n' + JSON.stringify(params, null, 2));
}
if (domain === 'Runtime' && name === 'consoleAPICalled') {
const text = params.args[0].value;
if (instanceToDebug) {
sendToHost({cmd: 'log', severity: params.type === 'warning' ? 'warn' : 'error', text, ts: Date.now() });
} else if (text.includes('$$' + scriptToDebug + '$$')) {
console.log(`${fullName} [${params.executionContextId}]: => ${text}`);
const [severity, _text] = text.split('$$' + scriptToDebug + '$$');
sendToHost({cmd: 'log', severity, text: _text, ts: params.args[1] && params.args[1].value ? params.args[1].value : Date.now() });
} else if (params.type === 'warning' || params.type === 'error') {
sendToHost({
cmd: 'log',
severity: params.type === 'warning' ? 'warn' : 'error',
text,
ts: Date.now()
});
}
return;
} else if (domain === 'Runtime' && (params.id === 2 || params.executionContextId === 2)) {
if (name === 'executionContextCreated') {
console.warn(fullName + ': => \n' + JSON.stringify(params, null, 2));
} else if (name === 'executionContextDestroyed') {
console.warn(fullName + ': => \n' + JSON.stringify(params, null, 2));
sendToHost({cmd: 'finished', context: params});
}
return;
} else if (domain === 'Runtime' && name === 'executionContextDestroyed' && params.executionContextId === 1) {
sendToHost({cmd: 'finished', context: params});
console.log('Exited!');
setTimeout(() =>
process.exit(125), 200);
} else if (domain === 'Debugger' && name === 'scriptFailedToParse') {
// ignore
return;
}
console.warn(`${fullName}: =>\n${JSON.stringify(params, null, 2)}`);
/*if (domain in this) {
this[domain].emit(name, params);
}*/
};
this.client.on('debugEvent', this.handleDebugEvent);
const startRepl = createRepl(this);
// Handle all possible exits
process.on('exit', () => this.killChild());
process.once('SIGTERM', process.exit.bind(process, 0));
process.once('SIGHUP', process.exit.bind(process, 0));
this.run()
.then(() => startRepl())
.then((repl) => {
this.repl = repl;
this.repl.on('exit', () => {
process.exit(0);
});
this.paused = false;
})
.then(null, (error) => process.nextTick(() => { throw error; }));
}
suspendReplWhile(fn) {
if (this.repl) {
this.repl.pause();
}
this.stdin.pause();
this.paused = true;
return new Promise((resolve) => {
resolve(fn());
}).then(() => {
this.paused = false;
if (this.repl) {
this.repl.resume();
this.repl.displayPrompt();
}
this.stdin.resume();
}).then(null, (error) => process.nextTick(() => { throw error; }));
}
killChild() {
this.client.reset();
if (this.child) {
this.child.kill();
this.child = null;
}
}
run() {
this.killChild();
return this._runScript().then(([child, port, host]) => {
this.child = child;
let connectionAttempts = 0;
const attemptConnect = () => {
++connectionAttempts;
debuglog('connection attempt #%d', connectionAttempts);
this.stdout.write('.');
return this.client.connect(port, host)
.then(() => {
debuglog('connection established');
this.stdout.write(' ok');
}, (error) => {
debuglog('connect failed', error);
// If it's failed to connect 10 times then print failed message
if (connectionAttempts >= 10) {
this.stdout.write(' failed to connect, please retry\n');
process.exit(1);
}
return new Promise((resolve) => setTimeout(resolve, 500))
.then(attemptConnect);
});
};
this.print(`connecting to ${host}:${port} ..`, true);
return attemptConnect();
});
}
clearLine() {
if (this.stdout.isTTY) {
this.stdout.cursorTo(0);
this.stdout.clearLine(1);
} else {
this.stdout.write('\b');
}
}
print(text, oneline = false) {
this.clearLine();
this.stdout.write(oneline ? text : `${text}\n`);
}
childPrint(text, isError) {
isError && this.print(
text.toString()
.split(/\r\n|\r|\n/g)
.filter((chunk) => !!chunk)
.map((chunk) => `< ${chunk}`)
.join('\n')
);
if (!this.paused) {
this.repl.displayPrompt(true);
}
if (/Waiting for the debugger to disconnect\.\.\.\n$/.test(text)) {
this.killChild();
sendToHost({cmd: 'finished', text});
}
}
}
function parseArgv([target, ...args]) {
let host = '127.0.0.1';
let port = 9229;
let isRemote = false;
let script = target;
let scriptArgs = args;
const hostMatch = target.match(/^([^:]+):(\d+)$/);
const portMatch = target.match(/^--port=(\d+)$/);
if (hostMatch) {
// Connecting to remote debugger
// `node-inspect localhost:9229`
host = hostMatch[1];
port = parseInt(hostMatch[2], 10);
isRemote = true;
script = null;
} else if (portMatch) {
// start debugee on custom port
// `node inspect --port=9230 script.js`
port = parseInt(portMatch[1], 10);
script = args[0];
scriptArgs = args.slice(1);
} else if (args.length === 1 && /^\d+$/.test(args[0]) && target === '-p') {
// Start debugger against a given pid
const pid = parseInt(args[0], 10);
try {
process._debugProcess(pid);
} catch (e) {
if (e.code === 'ESRCH') {
/* eslint-disable no-console */
console.error(`Target process: ${pid} doesn't exist.`);
/* eslint-enable no-console */
process.exit(1);
}
throw e;
}
script = null;
isRemote = true;
}
return {
host, port, isRemote, script, scriptArgs,
};
}
function startInspect(argv = process.argv.slice(2), stdin = process.stdin, stdout = process.stdout) {
/* eslint-disable no-console */
/*if (argv.length < 1) {
const invokedAs = runAsStandalone ?
'node-inspect' :
`${process.argv0} ${process.argv[1]}`;
console.error(`Usage: ${invokedAs} script.js`);
console.error(` ${invokedAs} <host>:<port>`);
console.error(` ${invokedAs} -p <pid>`);
process.exit(1);
}*/
const options = parseArgv(argv);
inspector = new NodeInspector(options, stdin, stdout);
stdin.resume();
function handleUnexpectedError(e) {
if (!(e instanceof StartupError)) {
console.error('There was an internal error in node-inspect. Please report this bug.');
console.error(e.message);
console.error(e.stack);
} else {
console.error(e.message);
}
if (inspector.child) inspector.child.kill();
process.exit(1);
}
process.on('uncaughtException', handleUnexpectedError);
/* eslint-enable no-console */
}
function extractErrorMessage(stack) {
if (!stack) {
return '<unknown>';
}
const m = stack.match(/^\w+: ([^\n]+)/);
return m ? m[1] : stack;
}
function convertResultToError(result) {
const { className, description } = result;
const err = new Error(extractErrorMessage(description));
err.stack = description;
Object.defineProperty(err, 'name', { value: className });
return err;
}
let inspector;
let scriptToDebug;
let instanceToDebug;
let alreadyPausedOnFirstLine = false;
process.on('message', message => {
if (typeof message === 'string') {
try {
message = JSON.parse(message);
} catch (e) {
return console.error(`Cannot parse: ${message}`);
}
}
processCommand(message);
});
sendToHost({cmd: 'ready'});
// possible commands
// start - {cmd: 'start', scriptName: 'script.js.myName'} - start the debugging
// end - {cmd: 'end'} - end the debugging and stop process
// source - {cmd: 'source', scriptId} - read text of script by id
// watch - {cmd: 'watch', expressions: ['i']} - add to watch the variable
// unwatch - {cmd: 'unwatch', expressions: ['i']} - add to watch the variable
// sb - {cmd: 'sb', breakpoints: [{scriptId: 50, lineNumber: 4, columnNumber: 0}]} - set breakpoint
// cb - {cmd: 'cb', breakpoints: [{scriptId: 50, lineNumber: 4, columnNumber: 0}]} - clear breakpoint
// pause - {cmd: 'pause'} - pause execution
// cont - {cmd: 'cont'} - resume execution
// next - {cmd: 'next'} - Continue to next line in current file
// step - {cmd: 'step'} - Step into, potentially entering a function
// out - {cmd: 'step'} - Step out, leaving the current function
function processCommand(data) {
if (data.cmd === 'start') {
scriptToDebug = data.scriptName;
instanceToDebug = data.adapterInstance;
if (scriptToDebug) {
startInspect([__dirname + '/../main.js', data.instance || 0, '--debug', '--debugScript', scriptToDebug]);
} else {
const [adapter, instance] = instanceToDebug.split('.');
let file;
try {
file = require.resolve('iobroker.' + adapter);
} catch (e) {
// try to locate in the same dir
const dir = path.normalize(path.join(__dirname, '..', 'iobroker.' + adapter));
if (fs.existsSync(dir)) {
const pack = require(path.join(dir, 'package.json'));
if (fs.existsSync(path.join(dir, pack.main || (adapter + '.js')))) {
file = path.join(dir, pack.main || (adapter + '.js'));
}
}
if (!file) {
sendToHost({cmd: 'error', error: 'Cannot locate iobroker.' + adapter, errorContext: e});
return setTimeout(() => {
sendToHost({cmd: 'finished', context: 'Cannot locate iobroker.' + adapter});
setTimeout(() => process.exit(124), 500);
}, 200);
}
}
file = file.replace(/\\/g, '/');
instanceToDebug = file;
console.log(`Start ${file} ${instance} --debug`);
startInspect([file, instance, '--debug']);
}
} else if (data.cmd === 'end') {
process.exit();
} else if (data.cmd === 'source') {
inspector.Debugger.getScriptSource({scriptId: data.scriptId})
.then(script =>
sendToHost({cmd: 'script', scriptId: data.scriptId, text: script.scriptSource}));
} else if (data.cmd === 'cont') {
inspector.Debugger.resume()
.catch(e => sendToHost({cmd: 'error', error: e}));
} else if (data.cmd === 'next') {
inspector.Debugger.stepOver()
.catch(e => sendToHost({cmd: 'error', error: e}));
} else if (data.cmd === 'pause') {
inspector.Debugger.pause()
.catch(e => sendToHost({cmd: 'error', error: e}));
} else if (data.cmd === 'step') {
inspector.Debugger.stepInto()
.catch(e => sendToHost({cmd: 'error', error: e}));
} else if (data.cmd === 'out') {
inspector.Debugger.stepOut()
.catch(e => sendToHost({cmd: 'error', error: e}));
} else if (data.cmd === 'sb') {
console.log(JSON.stringify(data));
Promise.all(data.breakpoints.map(bp =>
inspector.Debugger.setBreakpoint({
location: {
scriptId: bp.scriptId,
lineNumber: bp.lineNumber,
columnNumber: bp.columnNumber
}
})
.then(result =>
({id: result.breakpointId, location: result.actualLocation}))
.catch(e =>
sendToHost({cmd: 'error', error: `Cannot set breakpoint: ${e}`, errorContext: e, bp}))))
.then(breakpoints =>
sendToHost({cmd: 'sb', breakpoints}));
} else if (data.cmd === 'cb') {
Promise.all(data.breakpoints.map(breakpointId =>
inspector.Debugger.removeBreakpoint({breakpointId})
.then(() => breakpointId)
.catch(e =>
sendToHost({cmd: 'error', error: `Cannot clear breakpoint: ${e}`, errorContext: e, id: breakpointId}))))
.then(breakpoints =>
sendToHost({cmd: 'cb', breakpoints}));
} else if (data.cmd === 'watch') {
Promise.all(data.expressions.map(expr =>
inspector.Debugger.watch(expr)
.catch(e =>
sendToHost({cmd: 'error', error: `Cannot watch expr: ${e}`, errorContext: e, expr}))))
.then(() => console.log('Watch done'));
} else if (data.cmd === 'unwatch') {
Promise.all(data.expressions.map(expr =>
inspector.Debugger.unwatch(expr)
.catch(e =>
sendToHost({cmd: 'error', error: `Cannot unwatch expr: ${e}`, errorContext: e, expr}))))
.then(() => console.log('Watch done'));
} else if (data.cmd === 'scope') {
Promise.all(data.scopes.filter(scope => scope && scope.object && scope.object.objectId).map(scope =>
inspector.Runtime.getProperties({
objectId: scope.object.objectId,
generatePreview: true,
})
.then(result => ({type: scope.type, properties: result}))
.catch(e =>
sendToHost({cmd: 'error', error: `Cannot get scopes expr: ${e}`, errorContext: e}))))
.then(scopes =>
sendToHost({cmd: 'scope', scopes: scopes}));
} else if (data.cmd === 'setValue') {
inspector.Debugger.setVariableValue({
variableName: data.variableName,
scopeNumber: data.scopeNumber,
newValue: data.newValue,
callFrameId: data.callFrameId,
})
.catch(e =>
sendToHost({cmd: 'setValue', variableName: `Cannot setValue: ${e}`, errorContext: e}))
.then(() =>
sendToHost(data));
} else if (data.cmd === 'expressions') {
Promise.all(data.expressions.map(item =>
inspector.Debugger.evaluateOnCallFrame({
callFrameId: data.callFrameId,
expression: item.name,
objectGroup: 'node-inspect',
returnByValue: true,
generatePreview: true,
})
.then(({ result, wasThrown }) => {
if (wasThrown) {
return {name: item.name, result: convertResultToError(result)};
} else {
return {name: item.name, result};
}
})
.catch(e =>
sendToHost({cmd: 'expressions', variableName: `Cannot setValue: ${e}`, errorContext: e}))))
.then(expressions =>
sendToHost({cmd: 'expressions', expressions}));
} else if (data.cmd === 'stopOnException') {
inspector.Debugger.setPauseOnExceptions({state: data.state ? 'all' : 'none'})
.catch(e =>
sendToHost({cmd: 'stopOnException', variableName: `Cannot stopOnException: ${e}`, errorContext: e}));
} else if (data.cmd === 'getPossibleBreakpoints') {
inspector.Debugger.getPossibleBreakpoints({start: data.start, end: data.end})
.then(breakpoints =>
sendToHost({cmd: 'getPossibleBreakpoints', breakpoints}))
.catch(e =>
sendToHost({cmd: 'getPossibleBreakpoints', variableName: `Cannot getPossibleBreakpoints: ${e}`, errorContext: e}));
} else {
console.error(`Unknown command: ${JSON.stringify(data)}`);
}
}
function sendToHost(data) {
if (data.cmd === 'error') {
console.error(data.text);
data.expr && console.error(`[EXPRESSION] ${data.expr}`);
data.bp && console.error(`[BP] ${data.bp}`);
}
if (typeof data !== 'string') {
data = JSON.stringify(data);
}
process.send && process.send(data);
}
| 38.657576 | 149 | 0.509603 |
bbe45a8d55230dbb4ac9ecf717bbca4e814ab284 | 21,985 | js | JavaScript | ajax/libs/angular-formly/4.0.1/formly.min.js | algolia/cdnjs | a0586b35ac4862680d2e090651acc8ccf44a5dda | [
"MIT"
] | 5 | 2015-02-20T16:11:30.000Z | 2017-05-15T11:50:44.000Z | packages/angular-formly/4.0.1/formly.min.js | tmthrgd/pagespeed-libraries-cdnjs | dc23979ff751a976ad1b978fcd516ec02d43081c | [
"MIT"
] | null | null | null | packages/angular-formly/4.0.1/formly.min.js | tmthrgd/pagespeed-libraries-cdnjs | dc23979ff751a976ad1b978fcd516ec02d43081c | [
"MIT"
] | 4 | 2015-07-14T16:16:05.000Z | 2021-03-10T08:15:54.000Z | // angular-formly version 4.0.1 built with ♥ by Astrism <astrisms@gmail.com>, Kent C. Dodds <kent@doddsfamily.us> (ó ì_í)=óò=(ì_í ò)
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("angular"),require("apiCheck")):"function"==typeof define&&define.amd?define(["angular","apiCheck"],t):"object"==typeof exports?exports.ngFormly=t(require("angular"),require("apiCheck")):e.ngFormly=t(e.angular,e.apiCheck)}(this,function(e,t){return function(e){function t(r){if(n[r])return n[r].exports;var o=n[r]={exports:{},id:r,loaded:!1};return e[r].call(o.exports,o,o.exports,t),o.loaded=!0,o.exports}var n={};return t.m=e,t.c=n,t.p="",t(0)}([function(e,t,n){"use strict";e.exports=n(8)},function(e,t,n){"use strict";var r=n(21);r.version||(r=window.angular),e.exports=r},function(e,t,n){"use strict";function r(e,t,n,r){return s.isFunction(t)?t(r||n,n,e):e.$eval(t,{$viewValue:r||n,$modelValue:n})}function o(e,t,n){var r=t.type;return!r&&t.template?r="template":!r&&t.templateUrl&&(r="templateUrl"),[e,r,t.key,n].join("_")}function i(e){s.forEach(arguments,function(t,n){n&&s.forEach(t,function(t,n){s.isDefined(e[n])?a(e[n],t)&&i(e[n],t):e[n]=s.copy(t)})})}function a(e,t){return s.isObject(e)&&s.isObject(t)&&Object.getPrototypeOf(e)===Object.getPrototypeOf(t)}var s=n(1);e.exports={formlyEval:r,getFieldId:o,reverseDeepMerge:i}},function(e){"use strict";e.exports=function(e){function t(e,t){function n(e){return e&&angular.isFunction(e.then)}function r(e){var t=["expression","message"],n={};if(angular.forEach(e,function(e,r){if(!angular.isString(e)){var o=[];angular.forEach(e,function(e,n){-1===t.indexOf(n)&&o.push(n)}),o.length&&(n[r]=o)}}),Object.keys(n).length)throw new Error(["Validators are only allowed to be functions or objects that have "+t.join(", ")+".","You provided some extra properties: "+JSON.stringify(n)].join(" "))}return{require:"ngModel",link:function(o,i,a,s){var l=o.$eval(a.formlyCustomValidation);if(l){r(l),o.options.validation.messages=o.options.validation.messages||{};var p=s.hasOwnProperty("$validators")&&!a.hasOwnProperty("useParsers");angular.forEach(l,function(r,i){function a(){var a=u?"$asyncValidators":"$validators";s[a][i]=function(i,a){var s=e.formlyEval(o,r,i,a);return u?n(s)?s:s?t.when(s):t.reject(s):s}}function l(){var t=void 0;s.$parsers.unshift(function(a){var l=e.formlyEval(o,r,s.$modelValue,a);return n(l)?(s.$pending=s.$pending||{},s.$pending[i]=!0,t=l,l.then(function(){t===l&&s.$setValidity(i,!0)})["catch"](function(){t===l&&s.$setValidity(i,!1)})["finally"](function(){1===Object.keys(s.$pending).length?delete s.$pending:delete s.$pending[i]})):s.$setValidity(i,l),a})}var f=r.message;f&&(o.options.validation.messages[i]=function(){return e.formlyEval(o,f,s.$modelValue,s.$viewValue)}),r=angular.isObject(r)?r.expression:r;var u=!angular.isString(r);p?a():l()})}}}}e.directive("formlyCustomValidation",t),t.tests=null,t.$inject=["formlyUtil","$q"]}},function(e,t,n){"use strict";var r=n(1);e.exports=function(e){function t(e,t,o,i,a,s,l,p,f,u){function c(e){var t=r.element("<a></a>");return t.append(e).html()}function d(e){var t=a.getType(e.type,!0,e),n=e.template||t&&t.template,r=e.templateUrl||t&&t.templateUrl;if(!n&&!r)throw f.getFieldError("template-type-type-not-supported","template type '"+e.type+"' not supported. On element:",e);return m(n||r,!n)}function m(n,r){if(r){var o={cache:i};return e.get(n,o).then(function(e){return e.data})["catch"](function(e){u("problem-loading-template-for-templateurl","Problem loading template for "+n,e)})}return t.when(n)}function y(e){var n=v(e);return function(r){if(!n.length)return t.when(r);n.forEach(function(t){f.checkWrapper(t,e)});var o=n.map(function(e){return m(e.template||e.templateUrl,!e.template)});return t.all(o).then(function(e){e.forEach(function(e,t){f.checkWrapperTemplate(e,n[t])}),e.reverse();var t=e.shift();return e.forEach(function(e){t=g(t,e)}),g(t,r)})}}function g(e,t){var n=r.element("<a></a>");n.append(e);var o=n.find("formly-transclude");return o.replaceWith(t),n.html()}function v(e){var t=e.wrapper;if(null===t)return[];t=t?n(t).map(a.getWrapper):n(a.getWrapperByType(e.type));var r=a.getType(e.type,!0,e);if(r&&r.wrapper){var o=n(r.wrapper).map(a.getWrapper);t=t.concat(o)}var i=a.getWrapper();return i&&t.push(i),t}function h(e){l["throw"](l.formlyFieldOptions,arguments,{prefix:"formly-field directive",url:"formly-field-directive-validation-failed"});var t=e.type&&a.getType(e.type);t&&t.validateOptions&&t.validateOptions(e)}return{restrict:"AE",transclude:!0,scope:{options:"=",model:"=",formId:"=?",index:"=?",fields:"=?",formState:"=?",form:"=?"},controller:["$scope","$timeout","$parse","$controller",function(e,o,i,l){function f(){o(function(){var n=e.options,o=c();r.forEach(n.expressionProperties,function(r,a){var s=i(a).assign,l=t.when(p.formlyEval(e,r,o));l.then(function(e){s(n,e)})})})}function c(t){return e.model&&e.options.key?(r.isDefined(t)&&(e.model[e.options.key]=t),e.model[e.options.key]):void 0}function d(e){p.reverseDeepMerge(e,{data:{},templateOptions:{},validation:{}})}function m(e,t){t&&y(e,t.defaultOptions);var o=n(e.optionsTypes).reverse();r.forEach(o,function(t){y(e,a.getType(t,!0,e).defaultOptions)})}function y(e,t){t&&(r.isFunction(t)&&(t=t(e)),p.reverseDeepMerge(e,t))}function g(e,t){r.extend(e,{key:e.key||t||0,value:c,runExpressions:f})}function v(e,t){function n(){o(),clearInterval(l)}if(!t.noFormControl){var o,i=2e3,a=5,s=0,l=setInterval(function(){if(s++,!r.isDefined(t.key))return n();var o=e.form&&e.form[e.id];o?(t.formControl=o,e.fc=o,x(e,t),n()):a*s>i&&(u("couldnt-set-the-formcontrol-after-timems","Couldn't set the formControl after "+i+"ms",e),n())},a);o=e.$on("$destroy",n)}}function O(e,t){t.model&&e.$watch("options.model",f,!0)}function x(e,t){e.$watch(function(){return"boolean"==typeof e.options.validation.show?e.fc.$invalid&&e.options.validation.show:e.fc.$invalid&&e.fc.$touched},function(n){t.validation.errorExistsAndShouldBeVisible=n,e.showError=n})}function b(e){e.validation.messages=e.validation.messages||{},r.forEach(s.messages,function(t,n){e.validation.messages[n]||(e.validation.messages[n]=function(e,n,r){return p.formlyEval(r,t,n,e)})})}function w(e){var t=void 0===arguments[1]?{}:arguments[1],n=void 0===arguments[2]?{}:arguments[2];r.forEach([n.controller,t.controller],function(t){t&&l(t,{$scope:e})})}var E=e.options,k=E.type&&a.getType(E.type);d(E),m(E,k),h(E),e.id=p.getFieldId(e.formId,E,e.index),g(E,e.index),f(),v(e,E),O(e,E),b(E),e.to=e.options.templateOptions,w(e,E,k)}],link:function(e,n){function i(t){n.html(c(t)),o(n.contents())(e),l&&l.link&&l.link.apply(f,p),e.options.link&&e.options.link.apply(f,p)}function s(n){return function(o){var i=t.when(o);return r.forEach(n,function(n){i=i.then(function(o){return t.when(n(o,e.options,e)).then(function(e){return r.isString(e)?e:c(e)})})}),i}}var l=e.options.type&&a.getType(e.options.type),p=arguments,f=this;d(e.options).then(s(a.templateManipulators.preWrapper)).then(y(e.options)).then(s(a.templateManipulators.postWrapper)).then(i)["catch"](function(t){u("there-was-a-problem-setting-the-template-for-this-field","There was a problem setting the template for this field ",e.options,t)})}}}function n(e){return e&&!r.isArray(e)?e=[e]:e||(e=[]),e}e.directive("formlyField",t),t.tests=null,t.$inject=["$http","$q","$compile","$templateCache","formlyConfig","formlyValidationMessages","formlyApiCheck","formlyUtil","formlyUsability","formlyWarn"]}},function(e){"use strict";e.exports=function(e){e.directive("formlyFocus",["$timeout","$document",function(e,t){return{link:function(n,r,o){var i=null,a=r[0],s=t[0];o.$observe("formlyFocus",function(t){"true"===t?e(function(){i=s.activeElement,a.focus()},~~o.focusWait):"false"===t&&s.activeElement===a&&(a.blur(),o.hasOwnProperty("refocus")&&i&&i.focus())})}}}])}},function(e,t,n){"use strict";var r=function(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)},o=Array.prototype.slice,i=n(1);e.exports=function(e){function t(e){var t=1;return{restrict:"E",template:function(e,t){var n=t.rootEl||"ng-form";return"\n <"+n+' class="formly"\n name="form"\n role="form">\n <div formly-field\n ng-repeat="field in fields track by $index"\n ng-if="!field.hide"\n class="formly-field {{field.type ? \'formly-field-\' + field.type : \'\'}}"\n options="field"\n model="field.model || model"\n fields="fields"\n form="form"\n form-id="formId"\n form-state="options.formState"\n index="$index">\n </div>\n <div ng-transclude></div>\n </'+n+">\n "},replace:!0,transclude:!0,scope:{fields:"=",model:"=",form:"=?",options:"=?"},controller:["$scope",function(n){function a(e,t){e.key=e.key||t||0}function s(t,r){if(i.isDefined(t.watcher)){var o=t.watcher;i.isArray(o)||(o=[o]),i.forEach(o,function(o){if(!i.isDefined(o.listener))throw e.getFieldError("all-field-watchers-must-have-a-listener","All field watchers must have a listener",t);var a=l(o,t,r),s=p(o,t,r),f=o.type||"$watch";o.stopWatching=n[f](a,s,o.watchDeep)})}}function l(e,t,n){var a=e.expression||"model['"+t.key+"']";if(i.isFunction(a)){var s=a;a=function(){var t=f.apply(void 0,[e,n].concat(o.call(arguments)));return s.apply(void 0,r(t))},a.displayName="Formly Watch Expression for field for "+t.key}return a}function p(e,t,n){var a=e.listener;if(i.isFunction(a)){var s=a;a=function(){var t=f.apply(void 0,[e,n].concat(o.call(arguments)));return s.apply(void 0,r(t))},a.displayName="Formly Watch Listener for field for "+t.key}return a}function f(e,t){for(var r=arguments.length,o=Array(r>2?r-2:0),i=2;r>i;i++)o[i-2]=arguments[i];return[n.fields[t]].concat(o,[e.stopWatching])}n.formId="formly_"+t++,n.options=n.options||{},n.options.formState=n.options.formState||{},i.forEach(n.fields,a),i.forEach(n.fields,s),n.$watch("model",function(e){i.forEach(n.fields,function(t){t.runExpressions&&t.runExpressions(e)})},!0)}],link:function(t,n,r){if(r.hasOwnProperty("result"))throw e.getFormlyError('The "result" attribute on a formly-form is no longer valid. Use "model" instead');if("form"!==r.name)throw e.getFormlyError('The "name" attribute on a formly-form is no longer valid. Use "form" instead')}}}e.directive("formlyForm",t),t.tests=null,t.$inject=["formlyUsability"]}},function(e,t,n){"use strict";e.exports=function(e){n(3)(e),n(4)(e),n(6)(e),n(5)(e)}},function(e,t,n){"use strict";var r="formly",o=n(1),i=o.module(r,[]);n(15)(i),n(20)(i),n(7)(i),n(17)(i),e.exports=r},function(e,t,n){"use strict";e.exports=function(e){var t=n(22)({output:{prefix:"angular-formly:",docsBaseUrl:"https://github.com/formly-js/angular-formly/blob/4.0.1/other/ERRORS_AND_WARNINGS.md#"}});e.constant("formlyApiCheck",t);var r=t.oneOfType([t.string,t.func]),o=t.oneOfType([t.oneOf([null]),t.typeOrArrayOf(t.string)]),i={type:t.shape.ifNot(["template","templateUrl"],t.string).optional,template:t.shape.ifNot(["type","templateUrl"],t.string).optional,templateUrl:t.shape.ifNot(["type","template"],t.string).optional,key:t.oneOfType([t.string,t.number]),model:t.object.optional,expressionProperties:t.objectOf(t.oneOfType([r,t.shape({expression:r,message:r.optional}).strict])).optional,data:t.object.optional,templateOptions:t.object.optional,wrapper:o.optional,modelOptions:t.shape({updateOn:t.string.optional,debounce:t.oneOfType([t.object,t.string]).optional,allowInvalid:t.bool.optional,getterSetter:t.bool.optional,timezone:t.string.optional}).optional,watcher:t.typeOrArrayOf(t.shape({expression:r.optional,listener:r})).optional,validators:t.objectOf(t.oneOfType([t.func,t.shape({expression:r,message:r.optional}).strict])).optional,noFormControl:t.bool.optional,hide:t.bool.optional,ngModelAttrs:t.objectOf(t.shape({expression:t.shape.ifNot(["value","attribute","bound"],t.any).optional,value:t.shape.ifNot("expression",t.any).optional,attribute:t.shape.ifNot("expression",t.any).optional,bound:t.shape.ifNot("expression",t.any).optional}).strict).optional,optionsTypes:t.typeOrArrayOf(t.string).optional,link:t.func.optional,controller:t.oneOfType([t.string,t.func,t.array]).optional,validation:t.shape({show:t.oneOfType([t.bool,t.oneOf([null])]).optional,messages:t.objectOf(t.func).optional,errorExistsAndShouldBeVisible:t.bool.optional}).optional,formControl:t.object.optional,value:t.func.optional,runExpressions:t.func.optional},a=t.shape(i).strict,s=angular.copy(i);s.key=t.string.optional;var l=t.shape({name:t.string,template:t.shape.ifNot("templateUrl",t.string).optional,templateUrl:t.shape.ifNot("template",t.string).optional,controller:t.oneOfType([t.func,t.string,t.array]).optional,link:t.func.optional,defaultOptions:t.oneOfType([t.func,t.shape(s)]).optional,"extends":t.string.optional,wrapper:o.optional,data:t.object.optional,validateOptions:t.func.optional,overwriteOk:t.bool.optional}).strict;angular.extend(t,{formlyTypeOptions:l,formlyFieldOptions:a,formlyExpression:r})}},function(e,t,n){"use strict";var r=n(1),o=n(2);e.exports=function(e){function t(e,t){function n(e){if(r.isArray(e))r.forEach(e,n);else{if(!r.isObject(e))throw T("You must provide an object or array for setType. You provided: "+JSON.stringify(arguments));i(e),e["extends"]&&a(e),k[e.name]=e}}function i(n){t["throw"](t.formlyTypeOptions,arguments,{prefix:"formlyConfig.setType",url:"settype-validation-failed"}),n.overwriteOk?n.overwriteOk=void 0:v(n.name,k,n,"types"),e.checkAllowedProperties(W,n)}function a(e){var t=u(e["extends"],!0,e);s(e,t),l(e,t),p(e,t),f(e,t),o.reverseDeepMerge(e,t)}function s(e,t){var n=t.controller;if(r.isDefined(n)){var o=e.controller;r.isDefined(o)?(e.controller=function(e,t){t(n,{$scope:e}),t(o,{$scope:e})},e.controller.$inject=["$scope","$controller"]):e.controller=n}}function l(e,t){var n=t.link;if(r.isDefined(n)){var o=e.link;e.link=r.isDefined(o)?function(){n.apply(void 0,arguments),o.apply(void 0,arguments)}:n}}function p(e,t){var n=t.validateOptions;if(r.isDefined(n)){var i=e.validateOptions,a=e.defaultOptions;e.validateOptions=r.isDefined(i)?function(e){i(e);var t=r.copy(e),s=a;s&&(r.isFunction(s)&&(s=s(t)),o.reverseDeepMerge(t,s)),n(t)}:n}}function f(e,t){var n=t.defaultOptions;if(r.isDefined(n)){var i=e.defaultOptions,a=r.isFunction(i),s=r.isFunction(n);s?e.defaultOptions=function(e){var t=n(e),r={};return o.reverseDeepMerge(r,e,t),a?i(r):(o.reverseDeepMerge(t,i),t)}:a&&(e.defaultOptions=function(e){var t={};return o.reverseDeepMerge(t,e,n),i(t)})}}function u(e,t,n){if(!e)return void 0;var r=k[e];if(r||t!==!0)return r;throw T('There is no type by the name of "'+e+'": '+JSON.stringify(n))}function c(e,t){for(var n=!0;n;){n=!1;var o=e,i=t;if(r.isArray(o))return o.map(function(e){return c(e)});if(r.isObject(o))return o.types=d(o),o.name=m(o,i),y(o),$[o.name]=o,o;r.isString(o)&&(e={template:o,name:i},n=!0)}}function d(e){return r.isString(e.types)?[e.types]:r.isDefined(e.types)?e.types:[]}function m(e,t){return e.name||t||e.types.join(" ")||A}function y(t){e.checkWrapper(t),t.template&&e.checkWrapperTemplate(t.template,t),t.overwriteOk?delete t.overwriteOk:v(t.name,$,t,"templateWrappers"),g(t)}function g(e){var t=!r.isArray(e.types)||!e.types.every(r.isString);if(t)throw T("Attempted to create a template wrapper with types that is not a string or an array of strings")}function v(e,t,n,r){t.hasOwnProperty(e)&&w(["Attempting to overwrite "+e+" on "+r+" which is currently",""+JSON.stringify(t[e])+" with "+JSON.stringify(n),'To supress this warning, specify the property "overwriteOk: true"'].join(" "))}function h(e){return $[e||A]}function O(e){var t=[];for(var n in $)$.hasOwnProperty(n)&&$[n].types&&-1!==$[n].types.indexOf(e)&&t.push($[n]);return t}function x(e){var t=$[e];return delete $[e],t}function b(e){var t=O(e);if(t)return r.isArray(t)?(t.forEach(function(e){return x(e.name)}),t):x(t.name)}function w(){j.disableWarnings||console.warn.apply(console,arguments)}var E=this,k={},$={},A="default",j=this,T=e.getFormlyError,W=["name","template","templateUrl","controller","link","defaultOptions","extends","wrapper","data","validateOptions","overwriteOk"];r.extend(this,{setType:n,getType:u,setWrapper:c,getWrapper:h,getWrapperByType:O,removeWrapperByName:x,removeWrappersForType:b,disableWarnings:!1,extras:{disableNgModelAttrsManipulator:!1,ngModelAttrsManipulatorPreferBound:!1},templateManipulators:{preWrapper:[],postWrapper:[]},$get:function(){return E}})}e.provider("formlyConfig",t),t.tests=null,t.$inject=["formlyUsabilityProvider","formlyApiCheck"]}},function(e){"use strict";e.exports=function(e){e.constant("formlyErrorAndWarningsUrlPrefix","https://github.com/formly-js/angular-formly/wiki/Errors-and-Warnings#")}},function(e,t,n){"use strict";var r=n(1);e.exports=function(e){e.provider("formlyUsability",["formlyVersion",function(e){function t(e,t,n){return arguments.length<3&&(n=t,t=e,e=null),new Error(o(e,t)+(" Field definition: "+r.toJson(n)))}function n(e,t){return t||(t=e,e=null),new Error(o(e,t))}function o(e,t){var n="";return null!==e&&(n=""+p+e),"Formly Error: "+t+". "+n}function i(e,t){if(e.template&&e.templateUrl)throw n("Template wrappers can only have a templateUrl or a template. This one provided both: "+JSON.stringify(e));if(!e.template&&!e.templateUrl)throw n("Template wrappers must have one of a templateUrl or a template. This one provided neither: "+JSON.stringify(e));e.validateOptions&&e.validateOptions(t)}function a(e,t){var r="<formly-transclude></formly-transclude>";if(-1===e.indexOf(r))throw n('Template wrapper templates must use "'+r+'" somewhere in them. This one does not have "<formly-transclude></formly-transclude>" in it: '+e+"\nAdditional information: "+JSON.stringify(t))}function s(e,n,r){var o=Object.keys(n).filter(function(t){return-1===e.indexOf(t)});if(o.length){var i=JSON.stringify(o.join(", ")),a=JSON.stringify(e.join(", "));throw t("you-have-specified-properties-for-context-that-are-not-allowed",["You have specified properties for "+r+" that are not allowed: "+i,"Allowed properties are: "+a].join("\n"),n)}}var l=this,p="https://github.com/formly-js/angular-formly/blob/"+e+"/other/ERRORS_AND_WARNINGS.md#";r.extend(this,{getFormlyError:n,getFieldError:t,checkWrapper:i,checkWrapperTemplate:a,checkAllowedProperties:s,$get:function(){return l}})}])}},function(e){"use strict";e.exports=function(e){e.factory("formlyValidationMessages",function(){function e(e,t,o,i,a){r.messages[e]=n(t,o,i,a)}function t(e,t){r.messages[e]=function(){return t}}function n(e,t,n,r){return function(o,i,a){return a.options.templateOptions[e]?""+t+" "+a.options.templateOptions[e]+" "+n:r}}var r={addTemplateOptionValueMessage:e,addStringMessage:t,messages:{}};return r})}},function(e){"use strict";e.exports=function(e){e.constant("formlyVersion","4.0.1")}},function(e,t,n){"use strict";e.exports=function(e){n(9)(e),n(12)(e),n(10)(e),n(14)(e),n(11)(e),n(13)(e)}},function(e){"use strict";e.exports=function(e){function t(e){function t(t,n,r){function o(){if(n.templateOptions||n.expressionProperties){var e=n.templateOptions||{},t=n.expressionProperties||{},r=i();angular.extend(r,n.ngModelAttrs),angular.forEach(r,function(r,o){var i=void 0,l=void 0,p="options.templateOptions['"+o+"']",u=e[o],c=a(t,o),d=angular.isDefined(u),m=angular.isDefined(c);if(r.value)l=r.value,i=o;else if(r.expression&&d)if(l=r.expression,angular.isString(e[o]))i="$eval("+p+")";else{if(!angular.isFunction(e[o]))throw new Error("options.templateOptions."+o+" must be a string or function: "+JSON.stringify(n));i=""+p+"(model[options.key], options, this, $event)"}else r.bound&&m?(l=r.bound,i=p):r.attribute&&m?(l=r.attribute,i="{{"+p+"}}"):r.attribute&&d?(l=r.attribute,i=u):r.bound&&d&&(l=r.bound,i=p);angular.isDefined(l)&&angular.isDefined(i)&&s(f,l,i)})}}function i(){var t={focus:{attribute:"formly-focus"}},n=[],r=["required","disabled","pattern","minlength"],o=["change","keydown","keyup","keypress","click","focus","blur"],i=["placeholder","min","max","tabindex","type"];return e.extras.ngModelAttrsManipulatorPreferBound?n.push("maxlength"):r.push("maxlength"),angular.forEach(n,function(e){t[e]={bound:"ng-"+e}}),angular.forEach(r,function(e){t[e]={attribute:e,bound:"ng-"+e}}),angular.forEach(o,function(e){var n="on"+e.substr(0,1).toUpperCase()+e.substr(1);t[n]={expression:"ng-"+e}}),angular.forEach(i,function(e){t[e]={attribute:e}}),t}function a(e,t){return e["templateOptions."+t]||e["templateOptions['"+t+"']"]||e['templateOptions["'+t+'"]']}function s(e,t,n){e.attr(t)||e.attr(t,n)}var l=angular.element("<a></a>"),p=n.data;if(p.noTouchy)return t;l.append(t);var f=angular.element(l[0].querySelectorAll("[ng-model]"));return f&&f.length?(s(f,"id",r.id),s(f,"name",r.id),angular.isDefined(n.validators)&&s(f,"formly-custom-validation","options.validators"),angular.isDefined(n.modelOptions)&&(s(f,"ng-model-options","options.modelOptions"),n.modelOptions.getterSetter&&f.attr("ng-model","options.value")),o(),l.html()):t}e.extras.disableNgModelAttrsManipulator||e.templateManipulators.preWrapper.push(t)}e.run(t),t.$inject=["formlyConfig"]}},function(e,t,n){"use strict";e.exports=function(e){n(16)(e)}},function(e,t,n){"use strict";var r=n(2);e.exports=function(e){function t(){return r}e.factory("formlyUtil",t),t.tests=null}},function(e){"use strict";var t=function(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t<e.length;t++)n[t]=e[t];return n}return Array.from(e)};e.exports=function(e){e.factory("formlyWarn",["formlyConfig","formlyErrorAndWarningsUrlPrefix","$log",function(e,n,r){return function(){if(!e.disableWarnings){var o=Array.prototype.slice.call(arguments),i=o.shift();o.unshift("Formly Warning:"),o.push(""+n+i),r.warn.apply(r,t(o))}}}])}},function(e,t,n){"use strict";e.exports=function(e){n(18)(e),n(19)(e)}},function(t){t.exports=e},function(e){e.exports=t}])});
//# sourceMappingURL=formly.min.js.map | 5,496.25 | 21,812 | 0.701569 |
bbe4ecbcff4a1209f02071c5e009d0ac5720f05c | 235 | js | JavaScript | src/config.js | propulsor/MarketsingalFront | ea0778db263fb69b3b386d8e88a7f7df710ad03d | [
"MIT"
] | null | null | null | src/config.js | propulsor/MarketsingalFront | ea0778db263fb69b3b386d8e88a7f7df710ad03d | [
"MIT"
] | null | null | null | src/config.js | propulsor/MarketsingalFront | ea0778db263fb69b3b386d8e88a7f7df710ad03d | [
"MIT"
] | null | null | null | export const ORACLE= {
// address:"0x07CEDA6e4bB790D43ee0bd6c72A8931e4158173f",
// endpoint: "test"
address:"0xfdd1F743679ccA49864137eB0dc5787b2A19Ac43",
endpoint:"TrendSignals",
URL : "https://marketsignal.info"
}
| 29.375 | 60 | 0.72766 |
5e0e58ab18599067918a1e1d56a6b2102e876547 | 1,442 | js | JavaScript | components/letterhead.js | manishsingh003/workshops | af5089bb4a7ee0859c093479e9d77c4fb8a3c36a | [
"MIT"
] | 64 | 2020-02-05T02:34:34.000Z | 2022-03-22T19:37:24.000Z | components/letterhead.js | manishsingh003/workshops | af5089bb4a7ee0859c093479e9d77c4fb8a3c36a | [
"MIT"
] | 41 | 2020-03-02T19:13:35.000Z | 2022-03-30T13:54:29.000Z | components/letterhead.js | manishsingh003/workshops | af5089bb4a7ee0859c093479e9d77c4fb8a3c36a | [
"MIT"
] | 47 | 2020-03-04T02:23:17.000Z | 2022-03-22T19:37:26.000Z | import Head from 'next/head'
import Meta from '@hackclub/meta'
import Header from '../components/header'
import Authored from '../components/authored'
import { Container, Button } from 'theme-ui'
import { GitHub } from 'react-feather'
import { Styled as Content } from '../components/content'
const Letterhead = ({
title,
desc,
author = { name: null, avatar: null, url: null },
date,
img,
path,
includeMeta = true,
hideGitHub = false,
children,
...props
}) => (
<>
{includeMeta && (
<Meta
as={Head}
title={title}
description={
author?.name && date
? `${desc} Written by ${author.name} on ${date}.`
: desc
}
image={img}
/>
)}
<Header title={title} desc={desc} {...props}>
{author?.name && <Authored {...author} date={date} />}
</Header>
<Container as={Content} variant="copy" pt={3} pb={[4, 5]}>
{children}
{!hideGitHub && (
<Button
as="a"
target="_blank"
href={`https://github.com/hackclub/workshops/blob/main/pages/${path}`}
variant="outline"
sx={{
mt: 2,
fontSize: 1,
textDecoration: 'none !important',
'@media print': { display: 'none' }
}}
>
<GitHub />
Edit on GitHub
</Button>
)}
</Container>
</>
)
export default Letterhead
| 23.639344 | 80 | 0.520111 |
5e0e7084c1a1dd0ab6807166dd08b6d1203259e3 | 666 | js | JavaScript | lib/SharpNetworkLocked.js | eugeneilyin/mdi-norm | e9ee50f99aafa1f4dd77ffbe8c06fbdc49ec58f4 | [
"MIT"
] | 3 | 2018-11-11T01:48:20.000Z | 2019-12-02T06:13:14.000Z | lib/SharpNetworkLocked.js | eugeneilyin/mdi-norm | e9ee50f99aafa1f4dd77ffbe8c06fbdc49ec58f4 | [
"MIT"
] | 1 | 2019-02-21T05:59:35.000Z | 2019-02-21T21:57:57.000Z | lib/SharpNetworkLocked.js | eugeneilyin/mdi-norm | e9ee50f99aafa1f4dd77ffbe8c06fbdc49ec58f4 | [
"MIT"
] | null | null | null | "use strict";
var _babelHelpers = require("./utils/babelHelpers.js");
exports.__esModule = true;
var _react = _babelHelpers.interopRequireDefault(require("react"));
var _Icon = require("./Icon");
var _fragments = require("./fragments");
var SharpNetworkLocked =
/*#__PURE__*/
function SharpNetworkLocked(props) {
return _react.default.createElement(_Icon.Icon, props, _react.default.createElement("path", {
d: "M22 16v-.36" + _fragments.bki + "v.5h-1v6h7v-6z" + _fragments.kk + "m-1.5-5c.15 0 .3.01.46.02.01 0 .03.01.04.01V1L1 20h13v-6h1.26c.22-.63.58-1.2 1.06-1.68.85-.85 1.98-1.32 3.18-1.32z"
}));
};
exports.SharpNetworkLocked = SharpNetworkLocked; | 31.714286 | 191 | 0.708709 |
5e0e9beb55ecf5295ed9197eb6884329a9d31bfc | 238 | js | JavaScript | src/library/Grid/constants.js | avetisk/mineral-ui | 5abbc4b7fd4937a85322e11f4bd0def194dfe7cc | [
"Apache-2.0"
] | 562 | 2017-04-21T19:37:27.000Z | 2022-02-13T03:27:24.000Z | src/library/Grid/constants.js | avetisk/mineral-ui | 5abbc4b7fd4937a85322e11f4bd0def194dfe7cc | [
"Apache-2.0"
] | 590 | 2017-04-25T19:38:34.000Z | 2020-10-07T14:53:04.000Z | src/library/Grid/constants.js | targetx/fork-mineral-ui | f47073b76443dcd895b218e43d510df0616870ec | [
"Apache-2.0"
] | 68 | 2017-04-25T21:11:10.000Z | 2022-01-21T12:25:59.000Z | /* @flow */
export const ALIGN_ITEMS = {
start: 'start',
end: 'end',
center: 'center',
stretch: 'stretch'
};
export const GUTTER_WIDTH = {
xxs: 'xxs',
xs: 'xs',
sm: 'sm',
md: 'md',
lg: 'lg',
xl: 'xl',
xxl: 'xxl'
};
| 13.222222 | 29 | 0.516807 |
5e0ec45b55b8f5d4d5e0773846093dd0d8db86fa | 602 | js | JavaScript | src/base/arcgis_js_v4.6/esri/nls/fr/basemaps.js | lidonghai1/vue-arcgis-element-ui | 3ea1b7079f9c060c3fd834e488c172a9289b52ac | [
"MIT"
] | 1 | 2019-06-14T09:54:36.000Z | 2019-06-14T09:54:36.000Z | src/base/arcgis_js_v4.6/esri/nls/fr/basemaps.js | lidonghai1/vue-arcgis-element-ui | 3ea1b7079f9c060c3fd834e488c172a9289b52ac | [
"MIT"
] | null | null | null | src/base/arcgis_js_v4.6/esri/nls/fr/basemaps.js | lidonghai1/vue-arcgis-element-ui | 3ea1b7079f9c060c3fd834e488c172a9289b52ac | [
"MIT"
] | 2 | 2019-06-14T09:54:40.000Z | 2020-04-13T14:47:30.000Z | // All material copyright ESRI, All Rights Reserved, unless otherwise specified.
// See https://js.arcgis.com/4.6/esri/copyright.txt for details.
//>>built
define({streets:"Rues",satellite:"Imagerie",hybrid:"Imagerie avec \u00e9tiquettes",terrain:"MNT avec \u00e9tiquettes",topo:"Topographie",gray:"Nuances de gris","dark-gray":"Nuances de gris fonc\u00e9",oceans:"Oc\u00e9ans","national-geographic":"National Geographic",osm:"OpenStreetMap","streets-night-vector":"World Street Map (Night)","streets-relief-vector":"World Street Map (with Relief)","streets-navigation-vector":"World Navigation Map"}); | 150.5 | 446 | 0.767442 |
5e0f08fbfd09230a65e03c660bf28077220267c6 | 760 | js | JavaScript | src/commands/CrystalMathLabs/200all.js | kickable/oldschoolbot | 7f47508bb9d23703e97ad2dbd5ef6a0ae8e649ea | [
"MIT"
] | 1 | 2019-12-05T06:01:28.000Z | 2019-12-05T06:01:28.000Z | src/commands/CrystalMathLabs/200all.js | kickable/oldschoolbot | 7f47508bb9d23703e97ad2dbd5ef6a0ae8e649ea | [
"MIT"
] | 5 | 2019-12-05T06:17:15.000Z | 2019-12-05T18:41:28.000Z | src/commands/CrystalMathLabs/200all.js | kickable/oldschoolbot | 7f47508bb9d23703e97ad2dbd5ef6a0ae8e649ea | [
"MIT"
] | null | null | null | const { Command } = require('klasa');
const fetch = require('node-fetch');
const { cmlErrorCheck } = require('../../../config/util');
module.exports = class extends Command {
constructor(...args) {
super(...args, {
cooldown: 2,
description: 'Shows the Time to 200m all of an account',
usage: '(username:...rsn)',
requiredPermissions: ['EMBED_LINKS']
});
}
async run(msg, [username]) {
const time = await fetch(
`http://crystalmathlabs.com/tracker/api.php?type=virtualhiscores&page=timeto200mall&players=${username}`
)
.then(res => res.text())
.then(
async res =>
cmlErrorCheck(res) || parseInt(res.split(',')[1].split('.')[0]).toLocaleString()
);
return msg.sendLocale('TT200_RESULT', [username, time]);
}
};
| 26.206897 | 107 | 0.638158 |
5e0f0eac9363ef7e5962dc1e86acfc654a5586c3 | 1,559 | js | JavaScript | demo/webpack.config.js | johnnynotsolucky/cycle-calendar | fe3ee3e44ab33ebba2507300e32a216a3eae50c8 | [
"Apache-2.0"
] | 4 | 2017-04-06T21:18:55.000Z | 2017-12-16T08:38:59.000Z | demo/webpack.config.js | johnnynotsolucky/cycle-calendar | fe3ee3e44ab33ebba2507300e32a216a3eae50c8 | [
"Apache-2.0"
] | 1 | 2017-04-10T11:09:59.000Z | 2017-04-10T11:09:59.000Z | demo/webpack.config.js | johnnynotsolucky/cycle-calendar | fe3ee3e44ab33ebba2507300e32a216a3eae50c8 | [
"Apache-2.0"
] | 1 | 2018-03-21T22:35:45.000Z | 2018-03-21T22:35:45.000Z | 'use strict';
const path = require('path');
const webpack = require('webpack');
const autoprefixer = require('autoprefixer');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var DashboardPlugin = require('webpack-dashboard/plugin');
module.exports = {
devtool: 'eval',
entry: {
main: './demo/index',
vendor: [
'xstream',
'@cycle/run',
'@cycle/dom',
]
},
output: {
path: path.join(__dirname, 'dist'),
filename: '[name].[chunkhash].js',
publicPath: '/'
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
names: ['vendor', 'manifest'],
minChunks: function (modules) {
return module.context && module.context.indexOf('node_modules') !== -1;
}
}),
new webpack.NoEmitOnErrorsPlugin(),
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'demo/index.html',
inject: true
}),
new DashboardPlugin(),
],
module: {
rules: [{
test: /\.js$/,
use: [{ loader: 'babel-loader' }],
exclude: /(node_modules)/,
}, {
test: /\.styl$/,
use: [
{ loader: 'style-loader' },
{ loader: 'css-loader' },
{
loader: 'postcss-loader',
options: {
plugins() {
return [autoprefixer({ browsers: [ 'last 2 versions' ] })];
}
}
},
{ loader: 'stylus-loader' }
],
}]
},
devServer: {
open: true, // to open the local server in browser
contentBase: path.resolve(__dirname, './'),
},
};
| 23.621212 | 79 | 0.536883 |
5e0f333bf29a3621a2aaf170c4505a580e913841 | 855 | js | JavaScript | packages/react-devtools-inline/playwright.config.js | arthur-mountain/React | a621cb099dafb8bd77370ed4f4d832f049642183 | [
"MIT"
] | null | null | null | packages/react-devtools-inline/playwright.config.js | arthur-mountain/React | a621cb099dafb8bd77370ed4f4d832f049642183 | [
"MIT"
] | null | null | null | packages/react-devtools-inline/playwright.config.js | arthur-mountain/React | a621cb099dafb8bd77370ed4f4d832f049642183 | [
"MIT"
] | null | null | null | const semver = require('semver');
const fs = require('fs');
const ReactVersionSrc = fs.readFileSync(require.resolve('shared/ReactVersion'));
const reactVersion = /export default '([^']+)';/.exec(ReactVersionSrc)[1];
const config = {
use: {
headless: true,
browserName: 'chromium',
launchOptions: {
// This bit of delay gives async React time to render
// and DevTools operations to be sent across the bridge.
slowMo: 100,
},
url: process.env.REACT_VERSION
? 'http://localhost:8080/e2e-regression.html'
: 'http://localhost:8080/e2e.html',
react_version: process.env.REACT_VERSION
? semver.coerce(process.env.REACT_VERSION).version
: reactVersion,
},
// Some of our e2e tests can be flaky. Retry tests to make sure the error isn't transient
retries: 2,
};
module.exports = config;
| 31.666667 | 91 | 0.674854 |
5e10354d68b830e29b08cc077fde14695a629d89 | 469 | js | JavaScript | app/routes/partner.routes.js | nikhilmaguwala/food-delivery-backend | c2f9df24df2e9be2facabe37699be1c69ce57780 | [
"MIT"
] | null | null | null | app/routes/partner.routes.js | nikhilmaguwala/food-delivery-backend | c2f9df24df2e9be2facabe37699be1c69ce57780 | [
"MIT"
] | null | null | null | app/routes/partner.routes.js | nikhilmaguwala/food-delivery-backend | c2f9df24df2e9be2facabe37699be1c69ce57780 | [
"MIT"
] | null | null | null | module.exports = app => {
const partner = require("../controllers/partner.controller");
const router = require("express").Router();
// Create a new Partner
router.post("/signup", partner.signup);
// Partner SignIn
router.post("/signin", partner.signin);
// Delete a Partner with id
router.delete("/:id", partner.delete);
// Delete all Partners
router.delete("/", partner.deleteAll);
app.use('/api/partner', router);
};
| 23.45 | 65 | 0.63113 |
5e10913f1de45d1f6048478ce3024c4510162cec | 577 | js | JavaScript | public/javascripts/delete_user.js | johntradiction/web-project | 5e1f20e9c21aaf753a6725d8b8bffb3e152c9bef | [
"Apache-2.0"
] | null | null | null | public/javascripts/delete_user.js | johntradiction/web-project | 5e1f20e9c21aaf753a6725d8b8bffb3e152c9bef | [
"Apache-2.0"
] | null | null | null | public/javascripts/delete_user.js | johntradiction/web-project | 5e1f20e9c21aaf753a6725d8b8bffb3e152c9bef | [
"Apache-2.0"
] | null | null | null | $(clickHandler);
function clickHandler() {
$(".deleteButton").click(function() {
if (confirm('Are you sure?')) {
const uid = $(this).attr("data-uid");
console.log("delete: ", uid);
deleteUser(uid);
} else {}
});
}
function deleteUser(uid) {
const request = $.ajax({
url: `/users/user/${uid}`,
type: "delete",
success: function(data) {
console.log("delete done", data);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("error happend");
console.log(jqXHR, textStatus, errorThrown);
}
});
} | 22.192308 | 53 | 0.584055 |
5e10946e27d8c999aeee06296f688d67f3b18026 | 1,460 | js | JavaScript | template.js | ryanve/universal | 993a0f69182940822fd53975472a26464d81da08 | [
"MIT"
] | 2 | 2015-12-31T02:36:10.000Z | 2022-03-01T04:17:33.000Z | template.js | ryanve/universal | 993a0f69182940822fd53975472a26464d81da08 | [
"MIT"
] | null | null | null | template.js | ryanve/universal | 993a0f69182940822fd53975472a26464d81da08 | [
"MIT"
] | null | null | null | exports.description = 'Create a universal module';
exports.notes = 'Fields are used to create a package.json file.\n' +
'.version should adhere to semver.org\n' +
'.main is used to generate build filenames\n' +
'.repo assumes GitHub if like: username/project\n';
exports.after = 'Open package.json and update fields as needed.\n' +
'Remove the .private field when ready to npm publish.\n' +
'Google package.json for info.';
exports.warnOn = '*'; // paths
exports.template = function(grunt, init, done) {
var name;
init.process({type: 'universal'}, [
name = init.prompt('name'),
init.prompt('description', ''),
init.prompt('version', '0.0.0'),
init.prompt('license', 'MIT'),
init.prompt('author_name'),
init.prompt('main', 'index.js'),
init.prompt('repo', function(value, data, done) {
grunt.util.spawn({
cmd: 'git',
args: ['config', '--get', 'github.user'],
fallback: 'none'
}, function(err, result) {
done(err, result + '/' + name.default);
});
})
], function(err, data) {
data.repo = data.repo.split('//github.com/').pop();
data.author = data.author_name;
data.keywords = [];
data.homepage = data.repo ? 'https://github.com/' + data.repo : '';
data.repository = {type: 'git'};
data.repository.url = data.repo ? 'https://github.com/' + data.repo + '.git' : '';
init.copyAndProcess(init.filesToCopy(data), data);
done();
});
}; | 37.435897 | 86 | 0.611644 |
5e10a9ff3fd3e2e88a97636f12413762cdc5e914 | 21,762 | js | JavaScript | Source/Chronozoom.UI/scripts/cz.min.js | ikbenpinda/ChronoZoom | e89771ea6e1603a9a9d2609d18f484f0f70c0427 | [
"Apache-2.0"
] | null | null | null | Source/Chronozoom.UI/scripts/cz.min.js | ikbenpinda/ChronoZoom | e89771ea6e1603a9a9d2609d18f484f0f70c0427 | [
"Apache-2.0"
] | null | null | null | Source/Chronozoom.UI/scripts/cz.min.js | ikbenpinda/ChronoZoom | e89771ea6e1603a9a9d2609d18f484f0f70c0427 | [
"Apache-2.0"
] | null | null | null | var constants,CZ;(function(n){n.timeSeriesChart;n.leftDataSet;n.rightDataSet,function(t){function u(t){return!t||!t.DisplayName||!n.Service.superCollectionName?!1:n.Service.superCollectionName.toLowerCase()==="sandbox"?!0:n.Service.canEdit}function e(t,f){n.Tours.tourCaptionFormContainer=f[16];var e=u(t);n.Tours.takeTour=function(t){n.HomePageViewModel.closeAllForms();n.Tours.tourCaptionForm=new n.UI.FormTourCaption(n.Tours.tourCaptionFormContainer,{activationSource:$(),navButton:".cz-form-nav",closeButton:".cz-tour-form-close-btn > .cz-form-btn",titleTextblock:".cz-tour-form-title",contentContainer:".cz-form-content",minButton:".cz-tour-form-min-btn > .cz-form-btn",captionTextarea:".cz-form-tour-caption",tourPlayerContainer:".cz-form-tour-player",bookmarksCount:".cz-form-tour-bookmarks-count",narrationToggle:".cz-toggle-narration",context:t});n.Tours.tourCaptionForm.show();n.Tours.removeActiveTour();n.Tours.activateTour(t,undefined)};n.HomePageViewModel.panelShowToursList=function(t){var u,o;if(typeof t=="undefined"&&(t=e),t&&n.Tours.tours&&n.Tours.tours.length===0){n.Overlay.Hide();n.HomePageViewModel.closeAllForms();n.Authoring.UI.createTour();return}u=r("#toursList");u.isFormVisible?u.close():(n.Overlay.Hide(),i(),o=new n.UI.FormToursList(f[9],{activationSource:$(this),navButton:".cz-form-nav",closeButton:".cz-form-close-btn > .cz-form-btn",titleTextblock:".cz-form-title",tourTemplate:f[10],tours:n.Tours.tours,takeTour:n.Tours.takeTour,editTour:t?function(t){n.Authoring.showEditTourForm&&n.Authoring.showEditTourForm(t)}:null,createTour:".cz-form-create-tour"}),o.show())}}function h(){var c,h,l,a;n.UILoader.loadAll(s).done(function(){var f=arguments,h,s;n.Settings.isCosmosCollection=n.Common.isInCosmos();n.Settings.isCosmosCollection&&$(".header-regimes").show();n.Menus.isEditor=n.Service.canEdit;n.Menus.Refresh();n.Overlay.Initialize();n.timeSeriesChart=new n.UI.LineChart(f[11]);n.HomePageViewModel.panelToggleTimeSeries=function(){var t,u,e;n.Overlay.Hide();t=r("#timeSeriesDataForm");t===!1?(i(),u=f[12],e=new n.UI.TimeSeriesDataForm(u,{activationSource:$(),closeButton:".cz-form-close-btn > .cz-form-btn"}),e.show()):t.isFormVisible?t.close():(i(),t.show())};n.HomePageViewModel.panelToggleSearch=function(){var t=r("#header-search-form"),u;t===!1?(i(),u=new n.UI.FormHeaderSearch(f[14],{activationSource:$(this),navButton:".cz-form-nav",closeButton:".cz-form-close-btn > .cz-form-btn",titleTextblock:".cz-form-title",searchTextbox:".cz-form-search-input",searchResultsBox:".cz-form-search-results",progressBar:".cz-form-progress-bar",resultSections:".cz-form-search-results > .cz-form-search-section",resultsCountTextblock:".cz-form-search-results-count"}),u.show()):t.isFormVisible?t.close():(i(),t.show())};$("#editCollectionButton img").click(function(){i();var t=new n.UI.FormEditCollection(f[19],{activationSource:$(),navButton:".cz-form-nav",closeButton:".cz-form-close-btn > .cz-form-btn",deleteButton:".cz-form-delete",titleTextblock:".cz-form-title",saveButton:".cz-form-save",errorMessage:".cz-form-errormsg",collectionName:"#cz-collection-name",collectionPath:"#cz-collection-path",collectionTheme:n.Settings.theme,backgroundInput:$(".cz-form-collection-background"),kioskmodeInput:$(".cz-form-collection-kioskmode"),mediaListContainer:".cz-form-medialist",timelineBackgroundColorInput:$(".cz-form-timeline-background"),timelineBackgroundOpacityInput:$(".cz-form-timeline-background-opacity"),timelineBorderColorInput:$(".cz-form-timeline-border"),exhibitBackgroundColorInput:$(".cz-form-exhibit-background"),exhibitBackgroundOpacityInput:$(".cz-form-exhibit-background-opacity"),exhibitBorderColorInput:$(".cz-form-exhibit-border"),chkDefault:"#cz-form-collection-default",chkPublic:"#cz-form-public-search",chkEditors:"#cz-form-multiuser-enable",btnEditors:"#cz-form-multiuser-manage"});t.show()});$("body").on("click","#cz-form-multiuser-manage",function(){var t=new n.UI.FormManageEditors(f[20],{activationSource:$(this),navButton:".cz-form-nav",titleTextblock:".cz-form-title",closeButton:".cz-form-close-btn > .cz-form-btn",saveButton:".cz-form-save"});t.show()});n.Authoring.initialize(n.Common.vc,{showMessageWindow:function(t,i,r){var u=new n.UI.MessageWindow(f[13],t,i);r&&u.container.bind("close",function(){u.container.unbind("close",r);r()});u.show()},hideMessageWindow:function(){var n=f[13].data("form");n&&n.close()},showEditTourForm:function(t){n.Tours.removeActiveTour();var i=new n.UI.FormEditTour(f[7],{activationSource:$(),navButton:".cz-form-nav",closeButton:".cz-form-close-btn > .cz-form-btn",titleTextblock:".cz-form-title",saveButton:".cz-form-save",deleteButton:".cz-form-delete",addStopButton:".cz-form-tour-addstop",titleInput:".cz-form-title",tourStopsListBox:"#stopsList",tourStopsTemplate:f[8],context:t});i.show()},showCreateTimelineForm:function(t){n.Authoring.hideMessageWindow();n.Authoring.mode="createTimeline";var i=new n.UI.FormEditTimeline(f[1],{activationSource:$(),navButton:".cz-form-nav",closeButton:".cz-form-close-btn > .cz-form-btn",titleTextblock:".cz-form-title",startDate:".cz-form-time-start",endDate:".cz-form-time-end",mediaListContainer:".cz-form-medialist",backgroundUrl:".cz-form-background-url",saveButton:".cz-form-save",deleteButton:".cz-form-delete",titleInput:".cz-form-item-title",errorMessage:".cz-form-errormsg",context:t});i.show()},showCreateRootTimelineForm:function(t){n.Authoring.mode="createRootTimeline";var i=new n.UI.FormEditTimeline(f[1],{activationSource:$(),navButton:".cz-form-nav",closeButton:".cz-form-close-btn > .cz-form-btn",titleTextblock:".cz-form-title",startDate:".cz-form-time-start",endDate:".cz-form-time-end",mediaListContainer:".cz-form-medialist",backgroundUrl:".cz-form-background-url",saveButton:".cz-form-save",deleteButton:".cz-form-delete",titleInput:".cz-form-item-title",errorMessage:".cz-form-errormsg",context:t});i.show()},showEditTimelineForm:function(t){var i=new n.UI.FormEditTimeline(f[1],{activationSource:$(),navButton:".cz-form-nav",closeButton:".cz-form-close-btn > .cz-form-btn",titleTextblock:".cz-form-title",startDate:".cz-form-time-start",endDate:".cz-form-time-end",mediaListContainer:".cz-form-medialist",backgroundUrl:".cz-form-background-url",saveButton:".cz-form-save",deleteButton:".cz-form-delete",titleInput:".cz-form-item-title",errorMessage:".cz-form-errormsg",context:t});i.show()},showCreateExhibitForm:function(t){n.Authoring.hideMessageWindow();var i=new n.UI.FormEditExhibit(f[2],{activationSource:$(),navButton:".cz-form-nav",closeButton:".cz-form-close-btn > .cz-form-btn",titleTextblock:".cz-form-title",titleInput:".cz-form-item-title",datePicker:".cz-form-time",createArtifactButton:".cz-form-create-artifact",contentItemsListBox:".cz-listbox",errorMessage:".cz-form-errormsg",saveButton:".cz-form-save",deleteButton:".cz-form-delete",contentItemsTemplate:f[4],context:t});i.show()},showEditExhibitForm:function(t){var i=new n.UI.FormEditExhibit(f[2],{activationSource:$(),navButton:".cz-form-nav",closeButton:".cz-form-close-btn > .cz-form-btn",titleTextblock:".cz-form-title",titleInput:".cz-form-item-title",datePicker:".cz-form-time",createArtifactButton:".cz-form-create-artifact",contentItemsListBox:".cz-listbox",errorMessage:".cz-form-errormsg",saveButton:".cz-form-save",deleteButton:".cz-form-delete",contentItemsTemplate:f[4],context:t});i.show()},showEditContentItemForm:function(t,i,r,u){var e=new n.UI.FormEditCI(f[3],{activationSource:$(),prevForm:r,navButton:".cz-form-nav",closeButton:".cz-form-close-btn > .cz-form-btn",titleTextblock:".cz-form-title",errorMessage:".cz-form-errormsg",saveButton:".cz-form-save",titleInput:".cz-form-item-title",mediaSourceInput:".cz-form-item-mediasource",mediaInput:".cz-form-item-mediaurl",descriptionInput:".cz-form-item-descr",attributionInput:".cz-form-item-attribution",mediaTypeInput:".cz-form-item-media-type",mediaListContainer:".cz-form-medialist",context:{exhibit:i,contentItem:t}});e.show(u)}});t.sessionForm=new n.UI.FormHeaderSessionExpired(f[15],{activationSource:$(),navButton:".cz-form-nav",closeButton:".cz-form-close-btn > .cz-form-btn",titleTextblock:".cz-form-title",titleInput:".cz-form-item-title",context:"",sessionTimeSpan:"#session-time",sessionButton:"#session-button"});h=new n.UI.FormLogin(f[6],{activationSource:$(),navButton:".cz-form-nav",closeButton:".cz-form-close-btn > .cz-form-btn",titleTextblock:".cz-form-title",titleInput:".cz-form-item-title",context:""});n.HomePageViewModel.panelToggleLogin=function(){h.isFormVisible?h.close():(i(),h.show())};s=new n.UI.FormEditProfile(f[5],{activationSource:$(),navButton:".cz-form-nav",closeButton:".cz-form-close-btn > .cz-form-btn",titleTextblock:".cz-form-title",saveButton:"#cz-form-save",logoutButton:"#cz-form-logout",titleInput:".cz-form-item-title",usernameInput:".cz-form-username",emailInput:".cz-form-email",agreeInput:".cz-form-agree",loginPanel:"#login-panel",profilePanel:"#profile-panel",loginPanelLogin:"#profile-panel.auth-panel-login",context:"",allowRedirect:!0});n.HomePageViewModel.panelToggleProfile=function(){s.isFormVisible?s.close():(i(),s.show())};n.Service.getProfile().done(function(t){t!==""&&(n.Settings.isAuthorized=!0,n.Menus.isSignedIn=!0,n.Menus.Refresh(),n.Settings.userSuperCollectionName=t.DisplayName||"",n.Settings.userCollectionName=t.DisplayName||"",n.Settings.userDisplayName=t.DisplayName||"",n.Authoring.timer=setTimeout(function(){n.Authoring.showSessionForm()},(n.Settings.sessionTime-60)*1e3));n.Authoring.isEnabled=u(t);e(t,f)}).fail(function(){var t=u(null);n.Authoring.isEnabled=t;n.Settings.isAuthorized=t;e(null,f)}).always(function(){n.Common.loadData().then(function(t){t||(n.Authoring.isEnabled?n.Authoring.showCreateRootTimelineForm&&n.Authoring.showCreateRootTimelineForm(o):n.Authoring.showMessageWindow("There is no content in this collection yet. Please click on the ChronoZoom logo, (found just above this message,) to see some other collections that you can view.","Collection Has No Content"))});n.Service.getCollection().done(function(t){t!=null&&(n.Common.collectionTitle=t.Title||"",n.Settings.collectionOwner=t.User.DisplayName);$("#editCollectionButton").find(".title").text(n.Common.collectionTitle)});n.Authoring.isEnabled&&$("#editCollectionButton").find(".hidden").removeClass("hidden");n.Menus.isSignedIn&&n.Settings.userSuperCollectionName===""?(n.Overlay.Show(),s.show(),$("#username").focus()):n.Menus.isSignedIn&&sessionStorage.getItem("showMyCollections")==="requested"?n.Overlay.Show(!0):n.Tours.getAutoTourGUID()===""&&(n.Settings.isCosmosCollection&&window.location.hash===""||window.location.hash==="#/t00000000-0000-0000-0000-000000000000")&&n.Overlay.Show();sessionStorage.removeItem("showMyCollections");$("#splash").fadeOut("slow")})});n.Service.getServiceInformation().then(function(t){n.Settings.contentItemThumbnailBaseUri=t.thumbnailsPath;n.Settings.signinUrlMicrosoft=t.signinUrlMicrosoft;n.Settings.signinUrlGoogle=t.signinUrlGoogle;n.Settings.signinUrlYahoo=t.signinUrlYahoo});n.Settings.applyTheme(null,n.Service.superCollectionName!=null);n.Service.superCollectionName&&n.Service.getCollections(n.Service.superCollectionName).then(function(t){$(t).each(function(i){if(t[i]&&(t[i].Default&&typeof n.Service.collectionName=="undefined"||t[i].Path===n.Service.collectionName)){var r=null;try{r=JSON.parse(t[i].theme)}catch(u){}n.Settings.applyTheme(r,!1)}})});$("#breadcrumbs-nav-left").click(n.BreadCrumbs.breadCrumbNavLeft);$("#breadcrumbs-nav-right").click(n.BreadCrumbs.breadCrumbNavRight);$("#biblCloseButton").mouseout(function(){n.Common.toggleOffImage("biblCloseButton","png")}).mouseover(function(){n.Common.toggleOnImage("biblCloseButton","png")});navigator.userAgent.match(/(iPhone|iPod|iPad)/)&&document.addEventListener("touchmove",function(n){n.preventDefault()});navigator.userAgent.indexOf("Mac")!=-1&&(c=document.getElementsByTagName("body")[0],c.style.overflow="hidden");Seadragon.Config.imagePath=n.Settings.seadragonImagePath;window.location.hash&&(n.Common.startHash=window.location.hash);n.Search.initializeSearch();n.Bibliography.initializeBibliography();var v=n.Gestures.getGesturesStream(n.Common.vc),y=n.Gestures.applyAxisBehavior(n.Gestures.getGesturesStream(n.Common.ax)),p=n.Gestures.getPanPinGesturesStream($("#timeSeriesContainer")),w=v.Merge(y.Merge(p));n.Common.controller=new n.ViewportController.ViewportController2(function(t){var i=n.Common.vc.virtualCanvas("getViewport"),u=n.Common.axis.markerPosition,e=i.pointVirtualToScreen(u,0).x,o,r,s;n.Common.vc.virtualCanvas("setVisible",t,n.Common.controller.activeAnimation);n.Common.updateAxis(n.Common.vc,n.Common.ax);i=n.Common.vc.virtualCanvas("getViewport");n.Tours.pauseTourAtAnyAnimation&&(n.Tours.tourPause(),n.Tours.pauseTourAtAnyAnimation=!1);o=n.Common.vc.virtualCanvas("getHoveredInfodot");r=n.Common.controller.activeAnimation!=undefined;r&&(s=i.pointScreenToVirtual(e,0).x,n.Common.updateMarker());f(i)},function(){return n.Common.vc.virtualCanvas("getViewport")},w);h=!0;n.Common.controller.onAnimationComplete.push(function(t){if(h=!1,n.Common.setNavigationStringTo&&n.Common.setNavigationStringTo.bookmark)n.UrlNav.navigationAnchor=n.UrlNav.navStringTovcElement(n.Common.setNavigationStringTo.bookmark,n.Common.vc.virtualCanvas("getLayerContent")),window.location.hash=n.Common.setNavigationStringTo.bookmark;else{n.Common.setNavigationStringTo&&n.Common.setNavigationStringTo.id==t&&(n.UrlNav.navigationAnchor=n.Common.setNavigationStringTo.element);var i=n.Common.vc.virtualCanvas("getViewport");window.location.hash=n.UrlNav.vcelementToNavString(n.UrlNav.navigationAnchor,i)}n.Common.setNavigationStringTo=null});window.addEventListener("hashchange",function(){if(window.location.hash&&h&&n.Common.hashHandle){var t=window.location.hash,i=n.UrlNav.navStringToVisible(window.location.hash.substring(1),n.Common.vc);i&&(n.Common.isAxisFreezed=!0,n.Common.controller.moveToVisible(i,!0),window.location.hash!=t&&(h=!1,window.location.hash=t));n.Common.hashHandle=!0}else h=!0});n.Common.controller.onAnimationComplete.push(function(t){n.Tours.tourBookmarkTransitionCompleted!=undefined&&n.Tours.tourBookmarkTransitionCompleted(t);n.Tours.tour!=undefined&&n.Tours.tour.state!="finished"&&(n.Tours.pauseTourAtAnyAnimation=!0)});n.Common.controller.onAnimationUpdated.push(function(t){var i,r;n.Tours.tour!=undefined&&n.Tours.tourBookmarkTransitionInterrupted!=undefined&&(i=n.Tours.tour.state,n.Tours.tourBookmarkTransitionInterrupted(t),r=n.Tours.tour.state,i=="play"&&r=="pause"&&n.Tours.tourPause(),n.Common.setNavigationStringTo=null)});n.Common.updateLayout();n.Common.vc.bind("elementclick",function(t){n.Search.navigateToElement(t)});n.Common.vc.bind("cursorPositionChanged",function(){n.Common.updateMarker()});n.Common.ax.bind("thresholdBookmarkChanged",function(t){var i=n.UrlNav.navStringToVisible(t.Bookmark,n.Common.vc);i!=undefined&&n.Common.controller.moveToVisible(i,!1)});n.Common.vc.bind("innerZoomConstraintChanged",function(t){n.Common.controller.effectiveExplorationZoomConstraint=t.zoomValue;n.Common.axis.allowMarkerMovesOnHover=!t.zoomValue});n.Common.vc.bind("breadCrumbsChanged",function(t){n.BreadCrumbs.updateBreadCrumbsLabels(t.breadCrumbs)});$(window).bind("resize",function(){n.timeSeriesChart&&n.timeSeriesChart.updateCanvasHeight();n.Common.updateLayout();var t=n.Common.vc.virtualCanvas("getViewport");f(t)});l=n.Common.vc.virtualCanvas("getViewport");n.Common.vc.virtualCanvas("setVisible",n.VCContent.getVisibleForElement({x:-137e8,y:0,width:137e8,height:5535444444.4444447},1,l,!1),!0);n.Common.updateAxis(n.Common.vc,n.Common.ax);a=window.location.hash.match("b=([a-z0-9_-]+)");a&&($("#bibliography .sources").empty(),$("#bibliography .title").append($("<span><\/span>",{text:"Loading..."})),$("#bibliographyBack").css("display","block"))}function i(){$(".cz-major-form").each(function(n,t){var i=$(t).data("form");i&&i.isFormVisible===!0&&i.close()})}function r(n){var t=$(n).data("form");return t?t:!1}function c(){$("#timeSeriesContainer").height("30%");$("#timeSeriesContainer").show();$("#vc").height("70%");n.timeSeriesChart.updateCanvasHeight();n.Common.updateLayout()}function l(){n.leftDataSet=undefined;n.rightDataSet=undefined;$("#timeSeriesContainer").height(0);$("#timeSeriesContainer").hide();$("#vc").height("100%");n.Common.updateLayout()}function f(t){var v=t.pointScreenToVirtual(0,0).x,a,s,b,k,h,c,f,l,u,d;if(v<n.Settings.maxPermitedTimeRange.left&&(v=n.Settings.maxPermitedTimeRange.left),a=t.pointScreenToVirtual(t.width,t.height).x,a>n.Settings.maxPermitedTimeRange.right&&(a=n.Settings.maxPermitedTimeRange.right),n.timeSeriesChart!==undefined){var e=t.pointVirtualToScreen(v,0).x,o=t.pointVirtualToScreen(a,0).x,p=n.Dates.getYMDFromCoordinate(v).year,w=n.Dates.getYMDFromCoordinate(a).year;if(n.timeSeriesChart.clear(e,o),n.timeSeriesChart.clearLegend("left"),n.timeSeriesChart.clearLegend("right"),s="Time Series Chart",(n.rightDataSet!==undefined||n.leftDataSet!==undefined)&&n.timeSeriesChart.drawVerticalGridLines(e,o,p,w),b=o-e,n.rightDataSet!==undefined&&n.leftDataSet!==undefined&&(b/=2),k=n.timeSeriesChart.checkLegendVisibility(b),n.leftDataSet!==undefined){var y=n.leftDataSet.getVerticalPadding()+10,i=Number.MAX_VALUE,r=Number.MIN_VALUE;if(n.leftDataSet.series.forEach(function(n){n.appearanceSettings!==undefined&&n.appearanceSettings.yMin!==undefined&&n.appearanceSettings.yMin<i&&(i=n.appearanceSettings.yMin);n.appearanceSettings!==undefined&&n.appearanceSettings.yMax!==undefined&&n.appearanceSettings.yMax>r&&(r=n.appearanceSettings.yMax)}),r-i==0&&(h=Math.max(.1,Math.abs(i)),c=.01,r+=h*c,i-=h*c),f={labelCount:4,tickLength:10,majorTickThickness:1,stroke:"black",axisLocation:"left",font:"16px Calibri",verticalPadding:y},l=n.timeSeriesChart.generateAxisParameters(e,o,i,r,f),n.timeSeriesChart.drawHorizontalGridLines(l,f),n.timeSeriesChart.drawDataSet(n.leftDataSet,e,o,y,p,w,r,i),n.timeSeriesChart.drawAxis(l,f),k)for(u=0;u<n.leftDataSet.series.length;u++)n.timeSeriesChart.addLegendRecord("left",n.leftDataSet.series[u].appearanceSettings.stroke,n.leftDataSet.series[u].appearanceSettings.name);s+=" ("+n.leftDataSet.name}if(n.rightDataSet!==undefined){var y=n.rightDataSet.getVerticalPadding()+10,i=Number.MAX_VALUE,r=Number.MIN_VALUE;if(n.rightDataSet.series.forEach(function(n){n.appearanceSettings!==undefined&&n.appearanceSettings.yMin!==undefined&&n.appearanceSettings.yMin<i&&(i=n.appearanceSettings.yMin);n.appearanceSettings!==undefined&&n.appearanceSettings.yMax!==undefined&&n.appearanceSettings.yMax>r&&(r=n.appearanceSettings.yMax)}),r-i==0&&(h=Math.max(.1,Math.abs(i)),c=.01,r+=h*c,i-=h*c),f={labelCount:4,tickLength:10,majorTickThickness:1,stroke:"black",axisLocation:"right",font:"16px Calibri",verticalPadding:y},l=n.timeSeriesChart.generateAxisParameters(o,e,i,r,f),n.timeSeriesChart.drawHorizontalGridLines(l,f),n.timeSeriesChart.drawDataSet(n.rightDataSet,e,o,y,p,w,r,i),n.timeSeriesChart.drawAxis(l,f),k)for(u=0;u<n.rightDataSet.series.length;u++)n.timeSeriesChart.addLegendRecord("right",n.rightDataSet.series[u].appearanceSettings.stroke,n.rightDataSet.series[u].appearanceSettings.name);d=s.indexOf("(")>0?", ":" (";s+=d+n.rightDataSet.name+")"}else s+=")";$("#timeSeriesChartHeader").text(s)}}var s={"#header-edit-form":"/ui/header-edit-form.html","#auth-edit-timeline-form":"/ui/auth-edit-timeline-form.html","#auth-edit-exhibit-form":"/ui/auth-edit-exhibit-form.html","#auth-edit-contentitem-form":"/ui/auth-edit-contentitem-form.html","$('<div><\/div>')":"/ui/contentitem-listbox.html","#profile-form":"/ui/header-edit-profile-form.html","#login-form":"/ui/header-login-form.html","#auth-edit-tours-form":"/ui/auth-edit-tour-form.html","$('<div><!--Tours Authoring--><\/div>')":"/ui/tourstop-listbox.html","#toursList":"/ui/tourslist-form.html","$('<div><!--Tours list item --><\/div>')":"/ui/tour-listbox.html","#timeSeriesContainer":"/ui/timeseries-graph-form.html","#timeSeriesDataForm":"/ui/timeseries-data-form.html","#message-window":"/ui/message-window.html","#header-search-form":"/ui/header-search-form.html","#header-session-expired-form":"/ui/header-session-expired-form.html","#tour-caption-form":"/ui/tour-caption-form.html","#mediapicker-form":"/ui/mediapicker-form.html","#overlay":"/ui/overlay.html","#auth-edit-collection-form":"/ui/auth-edit-collection-form.html","#auth-edit-collection-editors":"/ui/auth-edit-collection-editors.html"},o;t.sessionForm;t.rootCollection;o={title:"My Timeline",x:1950,endDate:9999,children:[],parent:{guid:null}};$(document).ready(function(){var i,r;window.console=window.console||function(){var n={};return n.log=n.warn=n.debug=n.info=n.log=n.error=n.time=n.dir=n.profile=n.clear=n.exception=n.trace=n.assert=function(){},n}();$(".bubbleInfo").hide();$("#wait").hide();$(document).ajaxStart(function(){$("#wait").show()});$(document).ajaxStop(function(){$("#wait").hide()});i=localStorage.getItem("theme")||"";i===""&&(i="theme-linen",localStorage.setItem("theme",i));$("body").addClass(i);r=n.UrlNav.getURL();t.rootCollection=r.superCollectionName===undefined;n.Service.superCollectionName=r.superCollectionName;n.Service.collectionName=r.collectionName;n.Common.initialContent=r.content;n.Extensions.registerExtensions();n.Media.SkyDriveMediaPicker.isEnabled=!0;n.Media.initialize();n.Common.initialize();$(".header-logo").click(function(){n.Overlay.Show(!1)});typeof n.Service.superCollectionName=="undefined"&&n.Common.isInCosmos()&&(n.Service.superCollectionName="chronozoom");n.Service.getCanEdit().done(function(t){n.Service.canEdit=t===!0;h()})});t.closeAllForms=i;t.getFormById=r;t.showTimeSeriesChart=c;t.hideTimeSeriesChart=l;t.updateTimeSeriesChart=f}(n.HomePageViewModel||(n.HomePageViewModel={}));var t=n.HomePageViewModel})(CZ||(CZ={}));
//# sourceMappingURL=cz.min.js.map
| 7,254 | 21,726 | 0.768863 |
5e1191a985449ed623761f151f92b87a54158e4d | 2,980 | js | JavaScript | js/Aurora.js | truemaxdh/SpecialEffects | c4247fb6ba5c05606d643bdefc4db26e6b144e9b | [
"MIT"
] | null | null | null | js/Aurora.js | truemaxdh/SpecialEffects | c4247fb6ba5c05606d643bdefc4db26e6b144e9b | [
"MIT"
] | null | null | null | js/Aurora.js | truemaxdh/SpecialEffects | c4247fb6ba5c05606d643bdefc4db26e6b144e9b | [
"MIT"
] | null | null | null | if (typeof specialEffects === 'undefined' || !specialEffects) {
specialEffects = {};
}
// Bubbles
function _bubble(cx, cy, r, dx, dy, c, gco, dur) {
this.cx = cx;
this.cy = cy;
this.r = r;
this.dx = dx;
this.dy = dy;
this.color = c;
this.gco = gco;
this.duration = dur;
}
specialEffects.aurora = function(el) {
console.log(el.style);
const obj = this.aurora;
obj.objName = "aurora";
this.runningObj = obj;
var cnv = document.createElement("CANVAS");
cnv.style.position = "relative";
cnv.style.width = el.style.width;
cnv.style.height = el.style.height;
cnv.id = "cnv";
cnv.width = cnv.style.width.replace("px","");
cnv.height = cnv.style.height.replace("px","");
el.appendChild(cnv);
this.aurora.ctx = cnv.getContext("2d");
this.aurora.w = cnv.width;
this.aurora.h =cnv.height;
this.aurora.bubbles = [];
this.aurora.lastTimeStamp = null;
var cnt = 3 + Math.random() * 10;
for (var i = 0; i < cnt; i++) {
this.aurora.bubbles.push(
new _bubble(
Math.random() * cnv.width,
Math.random() * cnv.height,
Math.random() * Math.min(cnv.width, cnv.height) * 0.5 + Math.min(cnv.width, cnv.height) * 0.5,
((Math.random() < 0.5)?-1:1) * (Math.random() * 13 + 2),
((Math.random() < 0.5)?-1:1) * (Math.random() * 13 + 2),
"" + parseInt(Math.random() * 255) + "," + parseInt(Math.random() * 255) + "," + parseInt(Math.random() * 255),
"saturation",
100
)
);
}
this.aurora.drawFrm();
}
specialEffects.aurora.drawFrm = function(timeStamp) {
var obj = specialEffects.aurora
if (!obj.lastTimeStamp) obj.lastTimeStamp = timeStamp;
if ((timeStamp - obj.lastTimeStamp) > 30) {
obj.lastTimeStamp = timeStamp;
for (var i = 0; i < obj.bubbles.length; i++) {
var b = obj.bubbles[i];
// draw
//ctx.globalCompositeOperation = (Math.random() < 0.998) ? "saturation" : "source-over";
obj.ctx.globalCompositeOperation = b.gco;
if (b.gco == "source-over")
obj.ctx.globalAlpha = 0.2;
else
obj.ctx.globalAlpha = 1;
obj.ctx.beginPath();
const g = obj.ctx.createRadialGradient(
b.cx, b.cy, b.r * 0.1, b.cx, b.cy, b.r
);
g.addColorStop(0, "rgba(" + b.color + ",1)");
g.addColorStop(1, "rgba(" + b.color + ",0)");
obj.ctx.fillStyle = g;
obj.ctx.arc(b.cx, b.cy, b.r, 0, 2 * Math.PI);
obj.ctx.fill();
// bounce
if ((b.cx + b.dx) < 0 || (b.cx + b.dx) >= obj.w) b.dx *= -1;
if ((b.cy + b.dy) < 0 || (b.cy + b.dy) >= obj.h) b.dy *= -1;
b.cx += b.dx;
b.cy += b.dy;
if (--b.duration <= 0) {
//b.gco = (Math.random() < 0.998) ? "saturation" : "source-over";
b.gco = (Math.random() < 0.5) ? "saturation" : "source-over";
b.duration = Math.random() * 100 + 50;
}
}
}
if (specialEffects.runningObj.objName == obj.objName)
requestAnimationFrame(obj.drawFrm);
}
| 29.215686 | 119 | 0.557383 |
5e11ebbd6bf6e145a55c73b42111858bc2a88c6a | 144 | js | JavaScript | workbox-config.js | AmphiBee/demo-vue | fa117da1d281086f0eee0dafdefdab32cb8f7c9d | [
"MIT"
] | null | null | null | workbox-config.js | AmphiBee/demo-vue | fa117da1d281086f0eee0dafdefdab32cb8f7c9d | [
"MIT"
] | null | null | null | workbox-config.js | AmphiBee/demo-vue | fa117da1d281086f0eee0dafdefdab32cb8f7c9d | [
"MIT"
] | null | null | null | module.exports = {
"globDirectory": "src/",
"globPatterns": [
"**/*.{vue,png,ico,svg,js,scss}"
],
"swDest": "src/assets/js/sw.js"
}; | 20.571429 | 36 | 0.555556 |
5e12af15bd68d5bcdd1ac2e1b187a2bd38e52888 | 556 | js | JavaScript | samples/text.js | Quezion/nodejs-assistant | 9bea870fee607a0adab534954f7b77e528c8af2b | [
"MIT"
] | 17 | 2019-05-01T17:44:59.000Z | 2021-08-22T14:35:33.000Z | samples/text.js | Quezion/nodejs-assistant | 9bea870fee607a0adab534954f7b77e528c8af2b | [
"MIT"
] | 15 | 2019-12-09T23:36:04.000Z | 2022-01-22T04:14:43.000Z | samples/text.js | Quezion/nodejs-assistant | 9bea870fee607a0adab534954f7b77e528c8af2b | [
"MIT"
] | 11 | 2019-08-15T13:02:40.000Z | 2022-01-21T18:09:09.000Z | const { Assistant, AssistantLanguage } = require('nodejs-assistant');
const { getCredentials } = require('./credentials');
const startTextAssistant = async () => {
const credentials = await getCredentials();
const assistant = new Assistant(credentials, {
deviceId: 'test device',
deviceModelId: 'test device model',
locale: AssistantLanguage.ENGLISH,
});
const conversation = assistant.startTextConversation();
conversation
.on('message', (text) => console.log('Assistant: ', text))
.send('Hi!');
};
startTextAssistant();
| 27.8 | 69 | 0.692446 |
5e12f4b5283e31866b4ff25159234afcd0db78f3 | 322 | js | JavaScript | src/app/pages/news/components/News/tests/styles.test.js | mlobunko/without-water | c9beafd542d999dc30409a0bdab18473c481a3e3 | [
"MIT"
] | null | null | null | src/app/pages/news/components/News/tests/styles.test.js | mlobunko/without-water | c9beafd542d999dc30409a0bdab18473c481a3e3 | [
"MIT"
] | null | null | null | src/app/pages/news/components/News/tests/styles.test.js | mlobunko/without-water | c9beafd542d999dc30409a0bdab18473c481a3e3 | [
"MIT"
] | null | null | null | import React from 'react';
import { shallow } from 'enzyme';
import 'jest-styled-components';
import { StyledNewsComponent } from '../styles';
describe('StyledNewsComponent', () => {
it('renders correctly', () => {
const wrapper = shallow(<StyledNewsComponent />);
expect(wrapper).toMatchSnapshot();
});
});
| 24.769231 | 53 | 0.667702 |
5e13ae44b0b6f04ded324fae4502f1f1950f0c07 | 893 | js | JavaScript | js/demo/chart-pie-demo.min.js | teebbstudios/teebb-admin-html | 91cde03348e7621c80bdba00af7a220f41483249 | [
"MIT"
] | null | null | null | js/demo/chart-pie-demo.min.js | teebbstudios/teebb-admin-html | 91cde03348e7621c80bdba00af7a220f41483249 | [
"MIT"
] | 5 | 2020-06-11T17:29:23.000Z | 2021-05-08T21:50:55.000Z | js/demo/chart-pie-demo.min.js | teebbstudios/teebb-admin-html | 91cde03348e7621c80bdba00af7a220f41483249 | [
"MIT"
] | null | null | null | /*!
* Start Bootstrap - SB Admin 2 v4.0.4 (https://startbootstrap.com/template-overviews/sb-admin-2)
* Copyright 2013-2020 Start Bootstrap
* Licensed under MIT (https://github.com/BlackrockDigital/startbootstrap-sb-admin-2/blob/master/LICENSE)
*/
Chart.defaults.global.defaultFontFamily="Nunito",Chart.defaults.global.defaultFontColor="#858796";var ctx=document.getElementById("myPieChart"),myPieChart=new Chart(ctx,{type:"doughnut",data:{labels:["Direct","Referral","Social"],datasets:[{data:[55,30,15],backgroundColor:["#4e73df","#1cc88a","#36b9cc"],hoverBackgroundColor:["#2e59d9","#17a673","#2c9faf"],hoverBorderColor:"rgba(234, 236, 244, 1)"}]},options:{maintainAspectRatio:!1,tooltips:{backgroundColor:"rgb(255,255,255)",bodyFontColor:"#858796",borderColor:"#dddfeb",borderWidth:1,xPadding:15,yPadding:15,displayColors:!1,caretPadding:10},legend:{display:!1},cutoutPercentage:80}}); | 127.571429 | 641 | 0.763718 |
5e14af700693867dd3179c22ff24d093c3f25b26 | 3,159 | js | JavaScript | js/kv.h5Shim/js/kv.h5Shim.js | kiva/kvForm | fca8dd0b0ab7b24e4a667b1fdfd02d752f282c6d | [
"MIT"
] | null | null | null | js/kv.h5Shim/js/kv.h5Shim.js | kiva/kvForm | fca8dd0b0ab7b24e4a667b1fdfd02d752f282c6d | [
"MIT"
] | null | null | null | js/kv.h5Shim/js/kv.h5Shim.js | kiva/kvForm | fca8dd0b0ab7b24e4a667b1fdfd02d752f282c6d | [
"MIT"
] | null | null | null | /**
* Simulate the following HTML5 form attributes:
* - autofocus
* - placeholder
*
*/
(function ($, kv, global, undefined) {
'use strict';
/**
* Feature detection. Opted to de-couple from Modernzr.
*/
var browserSupport = (function () {
var inputEl = global.document.createElement('input');
return {
placeholder: 'placeholder' in inputEl
, autofocus: 'autofocus' in inputEl
};
}());
/**
* Helper function.
* Given a jquery object, process and return a subset of its css properties as an object
*
* @param $el
*/
function getPlaceholderCSS($el){
var s
, p
, b
, padding = {Top: 0, Right: 0, Bottom: 0, Left: 0 }
, margin = {Top: 0, Right: 0, Bottom: 0, Left: 0 }
, css = {
background: 'url(/img/1px.png) no-repeat' // IE 7/8 hack, makes the entire input region clickable
, offset: $el.offset()
, paddingTop: 0
, paddingRight: 0
, paddingBottom: 0
, paddingLeft: 0
, position: 'absolute'
, marginTop: 0
, marginRight: 0
, marginBottom: 0
, marginLeft: 0
, height: $el.height()
, width: $el.width()
};
// get the padding ( padding + border )
for (s in padding){
p = parseInt( $el.css('padding-' + s), 10);
b = parseInt( $el.css('border-' + s + '-width'), 10);
p = $.isNumeric(p) ? p : 0;
b = $.isNumeric(b) ? b : 0;
css['padding' + s ] = p + b;
}
// get the margin
for (s in margin){
css['margin' + s] = $el.css('margin-' + s);
}
return css;
}
/**
* Add "autofocus" support to non-standard browsers
*/
function autofocusShim() {
$('input[autofocus=""]:visible').first().focus();
}
/**
* Add "placeholder" support to non-standard browsers
*/
function placeholderShim(){
var $inputs = $('input[placeholder]');
// Add the placeholder text to all inputs that have the "placeholder" attribute
$inputs.each( function(){
var $this = $(this)
, css = getPlaceholderCSS($this)
, $placeholder = $('<div class="placeholder" />')
, $wrap = $('<div class="inputWrap" />')
, text = $this.attr("placeholder");
// Create the placeholder that will cover over the input element and delegate the click to the input
$placeholder
.css(css)
.text(text)
.click(function(){
$this.focus();
});
// Some browsers (IE & FF) need to be explicitly told to not display the placeholder if the input field is not empty
if ($this.val()) {
$placeholder.hide();
}
// Wrap the input element, and position the placeholder relative to it and directly over input element
$this
.focus( function() {
$placeholder.hide();
})
.blur( function(){
if( this.value === ''){
$placeholder.show();
}
})
.wrap($wrap)
.before($placeholder); // As if all this other stuff wasn't bad enough...this last bit makes me wanna puke, toss it when we stop supporting ie7 ( http://jaspan.com/ie-inherited-margin-bug-form-elements-and-haslayout )
});
}
kv.extend({
h5Shim: function () {
if (!browserSupport.autofocus){
autofocusShim();
}
if(!browserSupport.placeholder) {
placeholderShim();
}
}
});
}(jQuery, kv, window)); | 23.574627 | 221 | 0.605888 |
5e14bcfa9c917f7d2117815f1f1f5c316563f044 | 1,817 | js | JavaScript | src/components/AddCategoryFilter.js | xingjianpan/react-redux-news-reader | 68e43480ccc327722192e378144847d34a427a20 | [
"MIT"
] | null | null | null | src/components/AddCategoryFilter.js | xingjianpan/react-redux-news-reader | 68e43480ccc327722192e378144847d34a427a20 | [
"MIT"
] | null | null | null | src/components/AddCategoryFilter.js | xingjianpan/react-redux-news-reader | 68e43480ccc327722192e378144847d34a427a20 | [
"MIT"
] | null | null | null | import React, {Component} from 'react';
import { Field, reduxForm } from 'redux-form';
import { connect } from 'react-redux';
import PlusIcon from 'react-icons/lib/fa/plus';
import { addFilter, removeKeywordFromFilter } from '../actions';
class AddCategoryFilter extends Component {
handleFormSubmit(formProps) {
if ('categoryName' in formProps && formProps['categoryName'].trim().length !== 0) {
this.props.addFilter(formProps.categoryName);
this.props.reset(); //reset form and clear fields
}
return
}
handleRemoveKeywordFromFilter(text) {
this.props.removeKeywordFromFilter(text);
}
renderFormControl() {
return (
<div>
<ul>
{this.props.filters.map((item) => {
return (
<div key={item}>
<li onClick={() => { this.handleRemoveKeywordFromFilter(item); }}>
{item}
</li>
</div>
);
})
}
</ul>
</div>
);
}
render() {
const { handleSubmit } = this.props;
return (
<div>
<div>
<p>过滤掉不想看的新闻类别, 单击取消过滤</p>
<form onSubmit={handleSubmit(this.handleFormSubmit.bind(this))}>
<Field name="categoryName" label="categoryName" component="input" type="text" className="form-control" />
<button type="submit"><PlusIcon /></button>
</form>
</div>
{this.renderFormControl()}
</div>
);
}
}
AddCategoryFilter = reduxForm({
form: 'AddCategoryForm', // a unique name for this form
})(AddCategoryFilter);
const mapStateToProps = (state) => {
const { filters } = state.newsListFilter;
return {
filters,
};
};
export default connect(mapStateToProps,
{ addFilter, removeKeywordFromFilter })(AddCategoryFilter);
| 25.591549 | 117 | 0.586681 |
5e155a3d1238bfc565df444d45d5150e8ef88715 | 266 | js | JavaScript | wishlist-mobil/app/modules/auth/index.js | tomtom80/de.klingbeil.swaglist | 795da34321efd7a8df54d617e85405a398383fc1 | [
"Apache-2.0"
] | null | null | null | wishlist-mobil/app/modules/auth/index.js | tomtom80/de.klingbeil.swaglist | 795da34321efd7a8df54d617e85405a398383fc1 | [
"Apache-2.0"
] | 2 | 2021-05-07T23:40:49.000Z | 2022-02-12T05:12:45.000Z | wishlist-mobil/app/modules/auth/index.js | tomtom80/de.klingbeil.swaglist | 795da34321efd7a8df54d617e85405a398383fc1 | [
"Apache-2.0"
] | null | null | null |
import * as actions from './actions';
import * as constants from './constants';
import * as actionTypes from './actionTypes';
import reducer from './reducer';
import * as theme from '../../styles/theme';
export { actions, constants, actionTypes, reducer, theme };
| 29.555556 | 59 | 0.703008 |
5e16786eb9192114df937d134e24930285d0f510 | 585 | js | JavaScript | lib/app/index.js | Hiro-Nakamura/sails | 50ace7a96e3204847e6744dbaa00d7cc9941048c | [
"MIT"
] | null | null | null | lib/app/index.js | Hiro-Nakamura/sails | 50ace7a96e3204847e6744dbaa00d7cc9941048c | [
"MIT"
] | null | null | null | lib/app/index.js | Hiro-Nakamura/sails | 50ace7a96e3204847e6744dbaa00d7cc9941048c | [
"MIT"
] | null | null | null | /**
* Module dependencies.
*/
// try {console.time('require_core');}catch(e){}
var Sails = require('./Sails');
var _ = require('@sailshq/lodash');
/**
* Expose `Sails` factory...thing.
* (maintains backwards compatibility w/ constructor usage)
*/
module.exports = SailsFactory;
function SailsFactory() {
return new Sails();
}
// Backwards compatibility for Sails singleton usage:
var singleton = SailsFactory();
SailsFactory.isLocalSailsValid = _.bind(singleton.isLocalSailsValid, singleton);
SailsFactory.isSailsAppSync = _.bind(singleton.isSailsAppSync, singleton);
| 20.172414 | 80 | 0.724786 |
5e16cd99efc6407976f50e65e2dda88b6bf24b6b | 1,026 | js | JavaScript | protractor-tests/login/basic_signout.spec.js | bcejmxjs/blackbelt | 2affd807d8872771108196f421fb840bf53bb8e8 | [
"MIT"
] | 5 | 2015-02-23T22:28:43.000Z | 2020-11-27T21:58:51.000Z | protractor-tests/login/basic_signout.spec.js | bcejmxjs/blackbelt | 2affd807d8872771108196f421fb840bf53bb8e8 | [
"MIT"
] | 36 | 2015-03-07T20:40:44.000Z | 2015-05-07T22:32:08.000Z | protractor-tests/login/basic_signout.spec.js | bcejmxjs/blackbelt | 2affd807d8872771108196f421fb840bf53bb8e8 | [
"MIT"
] | null | null | null | // Generic page object -- interacts with header
var Page = function() {
this.dropdown = function() {
return element(by.id('profile_dropdown'))
.element(by.className('dropdown'))
}
this.signout_btn = function() {
return element(by.className('dropdown-menu'))
.element(by.linkText('Signout'));
}
this.get = function() {
browser.get(browser.baseUrl + '/#!/');
}
this.signout = function() {
this.dropdown().click();
this.signout_btn().click();
}
}
var page = new Page();
describe('Basic user signout', function() {
it('Do signout', function() {
page.get();
page.signout();
});
//--------------------------------------------------
it('Sh- remain on the homepage', function() {
expect(
browser.getCurrentUrl())
.toBe(browser.baseUrl + '/#!/');
});
//--------------------------------------------------
it('Sh- allow access of signin page', function() {
browser.get(browser.baseUrl + '/#!/signin');
expect(
browser.getCurrentUrl())
.toBe(browser.baseUrl + '/#!/signin');
});
}); | 23.860465 | 53 | 0.566277 |
5e170ac9df575a9d43d9477e1f54f6bbd6175ea9 | 927 | js | JavaScript | public/index/index.js | wangyang2010344/mve | 87faf3598839322e0c27d30b8261cf143f084d04 | [
"Apache-2.0"
] | 1 | 2021-09-14T01:43:04.000Z | 2021-09-14T01:43:04.000Z | public/index/index.js | wy2010344/mve | 87faf3598839322e0c27d30b8261cf143f084d04 | [
"Apache-2.0"
] | null | null | null | public/index/index.js | wy2010344/mve | 87faf3598839322e0c27d30b8261cf143f084d04 | [
"Apache-2.0"
] | null | null | null | define(["require", "exports", "../lib/front-mve.controls/window/index", "../lib/mve/modelChildren"], function (require, exports, index_1, modelChildren_1) {
"use strict";
return index_1.DesktopIndex(function (p) {
return {
type: "div",
init: function () {
new Promise(function (resolve_1, reject_1) { require(["./index/首页"], resolve_1, reject_1); }).then(function (index) {
p.model.push(index.panel);
});
},
style: {
width: function () {
return p.width() + "px";
},
height: function () {
return p.height() + "px";
}
},
children: modelChildren_1.modelChildren(p.model, function (me, row, index) {
return row.render(me, p, index);
})
};
});
});
| 37.08 | 156 | 0.461704 |
5e171e1529a357b20d570d1bf924519b5b0d616b | 211 | js | JavaScript | app/modules/auth/router.js | waltcow/kitty | 9c66952b55d73ec5606d37466bbb3b71231a73ec | [
"MIT"
] | null | null | null | app/modules/auth/router.js | waltcow/kitty | 9c66952b55d73ec5606d37466bbb3b71231a73ec | [
"MIT"
] | null | null | null | app/modules/auth/router.js | waltcow/kitty | 9c66952b55d73ec5606d37466bbb3b71231a73ec | [
"MIT"
] | null | null | null | import * as auth from './controller'
export const baseUrl = '/auth';
export const routes = [
{
method: 'POST',
route: '/',
handlers: [
auth.authUser
]
}
];
| 15.071429 | 36 | 0.473934 |
5e177eb66c9950219e6804f494565537cee3e38f | 257 | js | JavaScript | addon/components/s-icon.js | lordozb/space-ui | 304273c3a6d802a79f3b2d7201239f46636bd349 | [
"MIT"
] | 5 | 2019-08-08T12:52:05.000Z | 2020-05-12T09:55:24.000Z | addon/components/s-icon.js | lordozb/space-ui | 304273c3a6d802a79f3b2d7201239f46636bd349 | [
"MIT"
] | 4 | 2019-10-22T05:13:27.000Z | 2022-02-10T18:54:03.000Z | addon/components/s-icon.js | lordozb/space-ui | 304273c3a6d802a79f3b2d7201239f46636bd349 | [
"MIT"
] | 4 | 2019-10-11T06:49:35.000Z | 2020-04-08T09:27:59.000Z | import Component from '@ember/component';
import layout from '../templates/components/s-icon';
import SpreadMixin from '../mixins/spread';
export default Component.extend(SpreadMixin, {
layout,
tagName: '',
supportsDataTestProperties: true
});
| 25.7 | 52 | 0.731518 |
5e17b1bcdd5b262cdf54db8a5e122d3f25a5ba1b | 4,162 | js | JavaScript | resources/js/wholeSalersApp.js | dinhtu/new_xs | 52ec5f22bb6e6c92f85bfa5bd6ef9b8ce4337b5c | [
"MIT"
] | null | null | null | resources/js/wholeSalersApp.js | dinhtu/new_xs | 52ec5f22bb6e6c92f85bfa5bd6ef9b8ce4337b5c | [
"MIT"
] | null | null | null | resources/js/wholeSalersApp.js | dinhtu/new_xs | 52ec5f22bb6e6c92f85bfa5bd6ef9b8ce4337b5c | [
"MIT"
] | null | null | null | require('./bootstrap');
// require('@coreui/coreui/dist/js/coreui.bundle.min');
import Vue from "vue";
import VModal from "vue-js-modal";
import VeeValidate from "vee-validate";
import VueSweetalert2 from 'vue-sweetalert2';
import 'sweetalert2/dist/sweetalert2.min.css';
Vue.use(VeeValidate, {
locale: "ja"
});
Vue.use(VModal);
Vue.use(VueSweetalert2);
Vue.filter('replaceDateTime', function(value) {
if (value) {
return value.split('T')[0] + ' ' + value.split('T')[1].replace('.000000Z', '')
}
});
import moment from 'moment-timezone'
Vue.config.productionTip = false
//Nl2br
import Nl2br from 'vue-nl2br'
Vue.component('nl2br', Nl2br)
import ProfileCreate from "./components/wholeSalers/profile/create.vue"
import ProfileShow from "./components/wholeSalers/profile/show.vue"
import ProfileEdit from "./components/wholeSalers/profile/edit.vue"
import AccountInfoEdit from "./components/wholeSalers/accountInfo/edit.vue"
import SystemInfoEdit from "./components/wholeSalers/systemInfo/edit.vue"
import ReadHistoryIndex from "./components/wholeSalers/readHistory/index.vue"
import TraceabilityProductInfo from "./components/wholeSalers/traceAbility/productInfo/show.vue";
import TraceabilityProductBasic from "./components/wholeSalers/traceAbility/productBasic/show.vue";
import TraceabilityProductDetail from "./components/wholeSalers/traceAbility/productDetail/show.vue";
import TraceabilityProductDistribution from "./components/wholeSalers/traceAbility/productDistribution/show.vue";
import TraceabilityProductInfoEdit from "./components/wholeSalers/traceAbility/productInfo/edit.vue";
import TraceabilityProductBasicEdit from "./components/wholeSalers/traceAbility/productBasic/edit.vue";
import TraceabilityProductDetailEdit from "./components/wholeSalers/traceAbility/productDetail/edit.vue";
import TraceabilityProductDistributionEdit from "./components/wholeSalers/traceAbility/productDistribution/edit.vue";
import TraceabilityAlert from "./components/wholeSalers/traceAbility/alert/show.vue";
import TraceabilityDefault from "./components/wholeSalers/traceAbility/default/show.vue";
import TraceabilityControl from "./components/wholeSalers/traceAbility/control/show.vue";
import TraceabilityControlEdit from "./components/wholeSalers/traceAbility/control/edit.vue";
import PastTraceability from "./components/wholeSalers/pastTraceAbility/index.vue";
import InfoIndex from "./components/wholeSalers/info/index.vue";
import QrCodeInfo from "./components/producer/qrCode/show.vue";
new Vue({
created() {
// this.$validator.extend('required', {
// validate: function (value) {
// return value.trim() != '';
// }
// })
this.$validator.extend('code', {
validate: function(value) {
return /^[A-Za-z0-9]{1,20}$/i.test(value.trim())
}
});
this.$validator.extend("password_rule", {
validate: function(value) {
return /^[A-Za-z0-9]*$/i.test(value);
}
});
this.$validator.extend("is_hiragana", {
validate: function(value) {
return /^[ア-ン゛゜ァ-ォャ-ョーヴ ]*$/i.test(value);
}
});
this.$validator.extend("email_format", {
validate: function(value) {
return /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/i.test(value);
}
});
},
el: "#app",
components: {
ProfileCreate,
ProfileShow,
ProfileEdit,
AccountInfoEdit,
SystemInfoEdit,
PastTraceability,
InfoIndex,
QrCodeInfo,
ReadHistoryIndex,
TraceabilityProductInfo,
TraceabilityProductBasic,
TraceabilityProductDetail,
TraceabilityProductDistribution,
TraceabilityProductInfoEdit,
TraceabilityProductBasicEdit,
TraceabilityProductDetailEdit,
TraceabilityProductDistributionEdit,
TraceabilityAlert,
TraceabilityDefault,
TraceabilityControl,
TraceabilityControlEdit
},
methods: {},
mounted() {}
});
| 38.897196 | 117 | 0.688131 |
5e193bb41e00507d0e964e9e13a035b4c68e21a6 | 2,488 | js | JavaScript | src/scenes/sceneLeaderboard.js | Stricks1/shooterGame | 90a352ce289b95f5d8afec7ee9e95bbcead4c000 | [
"MIT"
] | 13 | 2020-09-07T21:20:11.000Z | 2020-12-16T16:36:16.000Z | src/scenes/sceneLeaderboard.js | Stricks1/shooterGame | 90a352ce289b95f5d8afec7ee9e95bbcead4c000 | [
"MIT"
] | 2 | 2020-09-01T14:29:08.000Z | 2020-09-09T15:27:47.000Z | src/scenes/sceneLeaderboard.js | Stricks1/shooterGame | 90a352ce289b95f5d8afec7ee9e95bbcead4c000 | [
"MIT"
] | null | null | null | import { BaseScene } from './baseScene';
import { Align } from '../common/util/align';
import Button from '../common/ui/button';
import Api from '../common/util/api';
import loading from '../../assets/images/loadImg.png';
// eslint-disable-next-line import/prefer-default-export
export class SceneLeaderboard extends BaseScene {
constructor() {
super('SceneLeaderboard');
}
// eslint-disable-next-line class-methods-use-this
preload() {
this.load.spritesheet('loading', loading, { frameWidth: 60, frameHeight: 53 });
}
create() {
super.create();
this.setBackground('seaBg');
this.makeAlignGrid(11, 11);
const whiteBg = this.add.image(0, 0, 'panelBack');
Align.scaleToGameW(whiteBg, 0.9, this);
this.aGrid.placeAtIndex(60, whiteBg);
this.placeText('LEADERBOARD', 16, 'TITLE_TEXT');
const loading = this.physics.add.sprite(0, 0, 'loading');
this.anims.create({
key: 'loading',
frames: this.anims.generateFrameNumbers('loading', { start: 0, end: 3 }),
frameRate: 10,
repeat: -1,
});
this.aGrid.placeAtIndex(60, loading);
loading.anims.play('loading', true);
Align.scaleToGameW(loading, 0.25, this);
Api.getScores().then((response) => {
const highScores = response.sort((a, b) => b.score - a.score);
let playersName1 = '';
let playersName2 = '';
for (let i = 0; i < 10; i += 1) {
if (i < 5) {
playersName1 += `${i + 1} - ${highScores[i].user}: ${
highScores[i].score
}\n\n`;
} else {
playersName2 += `${i + 1} - ${highScores[i].user}: ${
highScores[i].score
}\n\n`;
}
if (i === highScores.length - 1) {
break;
}
}
loading.destroy();
if (playersName2 !== '') {
this.placeText(playersName1, 58, 'BLACK2');
this.placeText(playersName2, 62, 'BLACK2');
} else {
this.placeText(playersName1, 60, 'BLACK2');
}
}).catch(() => {
loading.destroy();
this.placeText('Problem to connect with API\n Try again later', 60, 'RED');
});
this.returnBtn = new Button(
this,
'btn1',
'btnH1',
'Back to Menu',
'SceneTitle',
true,
);
this.aGrid.placeAtIndex(93, this.returnBtn);
this.makeUi();
}
makeUi() {
super.makeSoundPanel();
super.makeGear();
}
// eslint-disable-next-line class-methods-use-this
update() {}
} | 27.955056 | 90 | 0.571945 |
5e198c5ace7ee4e3fcbe562f1e8d06742dd46d62 | 983 | js | JavaScript | tocs/front-end/src/components/Address.js | EugeneChang/TO-Chinese-School-2020 | 73c35e5bb5e1eebb0a2f79d39e17a64c314247cb | [
"MIT"
] | null | null | null | tocs/front-end/src/components/Address.js | EugeneChang/TO-Chinese-School-2020 | 73c35e5bb5e1eebb0a2f79d39e17a64c314247cb | [
"MIT"
] | null | null | null | tocs/front-end/src/components/Address.js | EugeneChang/TO-Chinese-School-2020 | 73c35e5bb5e1eebb0a2f79d39e17a64c314247cb | [
"MIT"
] | null | null | null | import React, { } from "react";
import { formatAddress }from '../utils/utilities';
const Address = ({ street, city, state, zipcode, homePhone, cellPhone, email }) => {
return (
<dl className="row">
<dt className="col-12 col-md-6 text-left text-md-right">Address:</dt>
<dd className="col-12 col-md-6 text-left border-bottom border-md-bottom-0">{formatAddress({ street, city, state, zipcode })}</dd>
<dt className="col-12 col-md-6 text-left text-md-right">Home Phone:</dt>
<dd className="col-12 col-md-6 text-left border-bottom border-md-bottom-0">{homePhone}</dd>
<dt className="col-12 col-md-6 text-left text-md-right">Cell Phone: </dt>
<dd className="col-12 col-md-6 text-left border-bottom border-md-bottom-0">{cellPhone}</dd>
<dt className="col-12 col-md-6 text-left text-md-right">Email:</dt>
<dd className="col-12 col-md-6 text-left border-bottom border-md-bottom-0">{email}</dd>
</dl>
);
};
export default Address; | 49.15 | 135 | 0.663276 |
5e19d6c746fff47fe6a6f8223a6509fd3301f58b | 487 | js | JavaScript | packages/create-treats-app/index.js | afifkhaidir-tkpd/treats | 04c1bec49dba992f95e76b3c8accd53fccd92cad | [
"Apache-2.0"
] | 150 | 2018-12-25T09:12:11.000Z | 2021-12-18T06:16:19.000Z | packages/create-treats-app/index.js | afifkhaidir-tkpd/treats | 04c1bec49dba992f95e76b3c8accd53fccd92cad | [
"Apache-2.0"
] | 22 | 2018-12-29T16:04:56.000Z | 2021-08-06T15:12:24.000Z | packages/create-treats-app/index.js | afifkhaidir-tkpd/treats | 04c1bec49dba992f95e76b3c8accd53fccd92cad | [
"Apache-2.0"
] | 35 | 2018-12-25T14:56:11.000Z | 2022-03-04T06:09:16.000Z | #!/usr/bin/env node
const nodePolyfill = require("./scripts/util/polyfill");
nodePolyfill();
const argv = require("yargs")
.options({
debug: {
describe: "Debug mode"
}
})
.help()
.epilog(
" 🍰 Treats - Tokopedia React Development Kits, learn more on our documentation https://github.com/tokopedia/treats"
)
.strict().argv;
require("./scripts/generate")({
template: "create-treats-app",
noconfig: true, ...argv
});
| 22.136364 | 124 | 0.595483 |
5e19fe31d13b5ebc6097674135fd4caace4a6593 | 5,687 | js | JavaScript | mtg.js | Tethik/mtg | 3c94dc6d67f369a423ec53caec78a602d38d4245 | [
"MIT"
] | null | null | null | mtg.js | Tethik/mtg | 3c94dc6d67f369a423ec53caec78a602d38d4245 | [
"MIT"
] | null | null | null | mtg.js | Tethik/mtg | 3c94dc6d67f369a423ec53caec78a602d38d4245 | [
"MIT"
] | null | null | null | var module = angular.module('mtg', ['ngRoute', 'timer']);
DEBUG = true;
module.controller('main', function($scope, $filter) {
$scope.matches = [];
$scope.players = [{}, {}];
var orderBy = $filter('orderBy');
$scope.importFromStorage = function() {
console.log("Importing from local storage");
tourney = JSON.parse(localStorage.tourney);
console.log(tourney);
$scope.title = tourney.title;
$scope.players = tourney.players;
$scope.matches = tourney.matches;
// ugly way of rebind players to respective matches.
for(var m = 0; m < $scope.matches.length; m++)
{
for(var i = 0; i < $scope.players.length; i++) {
if($scope.matches[m].players[0].id == $scope.players[i].id)
$scope.matches[m].players[0] = $scope.players[i];
if($scope.matches[m].players[1].id == $scope.players[i].id)
$scope.matches[m].players[1] = $scope.players[i];
}
}
$scope.inited = true;
$scope.updatePlayerRanks();
};
$scope.exportToStorage = function() {
localStorage.tourney = JSON.stringify({
players: $scope.players,
matches: $scope.matches,
title: $scope.title,
inited: $scope.inited,
});
console.log("Exported to storage");
};
$scope.initPlayers = function() {
for(var p = 0; p < $scope.players.length; p++) {
$scope.players[p].won =
$scope.players[p].lost =
$scope.players[p].draw = 0;
$scope.players[p].rank = 1;
$scope.players[p].id = p;
}
};
$scope.updatePlayerRanks = function() {
$scope.players = orderBy($scope.players, ['-won','-draw']);
prev = $scope.players[0];
prev.rank = 1;
for(var i = 1; i < $scope.players.length; i++) {
curr = $scope.players[i];
if(curr.won == prev.won && curr.draw == prev.draw) // Not counting losses here.
{
curr.rank = prev.rank;
} else {
curr.rank = prev.rank + 1;
prev = curr;
}
}
console.log($scope.players);
};
$scope.createMatches = function() {
$scope.matches = [];
index = 0;
for(var p = 0; p < $scope.players.length; p++) {
var player1 = $scope.players[p];
for(var p2 = p+1; p2 < $scope.players.length; p2++) {
var player2 = $scope.players[p2];
var match = {
players: [player1, player2],
scores: [0, 0],
status: 'queued',
index: -1
}
$scope.matches.push(match);
}
}
// Semi-Random ordering of the matches.
// Should be so that min n-1 players have a match in the first
// round. This problem could be reduced to finding a Hamilton path...
indexes = [];
for(var i = 0; i < $scope.matches.length; i++)
indexes.push(i);
// Random shuffle. This could probably be improved in terms of efficiency.
matches_without_index = [];
while(indexes.length > 0) {
pick = Math.floor(Math.random() * indexes.length);
ind = indexes[pick];
matches_without_index.push(ind);
indexes.splice(pick, 1);
}
console.log(matches_without_index);
picked_players = [];
for(var i = 0; i < $scope.matches.length;) {
var m = 0;
for(; m < $scope.matches.length; m++) {
var match = $scope.matches[matches_without_index[m]]; // accessing the random order.
if(match.index > -1)
continue; // already visited.
if(picked_players.indexOf(match.players[0]) > -1 || picked_players.indexOf(match.players[1]) > -1)
continue; // at least one of the players already has a matchup this round.
match.index = i++;
picked_players.push(match.players[0]);
picked_players.push(match.players[1]);
break;
}
if(m == $scope.matches.length) {
picked_players = []; // new round.
}
}
$scope.matchesLeft = $scope.matches.length;
};
$scope.init = function() {
console.log("Init was called");
$scope.inited = true;
$scope.initPlayers();
$scope.createMatches();
$scope.exportToStorage();
};
$scope.matchEvaluator = function(a) {
statusorder = ['playing','queued','ended']
letters = ['a','b','c'];
return letters[statusorder.indexOf(a.status)] + a.index;
};
$scope.getMatchesLeft = function() {
var count = 0;
for(var i = 0; i < $scope.matches.length; i++)
if($scope.matches[i].status != 'ended')
count++;
return count;
};
$scope.reorderMatches = function() {
$scope.matches = orderBy($scope.matches, $scope.matchEvaluator, false);
$scope.exportToStorage();
};
$scope.startMatch = function(match) {
match.status = 'playing';
match.endtime = new Date().getTime() + 45*60*1000; // todo flytta till setting.
$scope.reorderMatches();
};
$scope.editMatch = function(match) {
match.status = 'playing';
if(match.scores[0] == match.scores[1])
{
match.players[0].draw -= 1;
match.players[1].draw -= 1;
} else if(match.scores[0] > match.scores[1]) {
match.players[0].won -= 1;
match.players[1].lost -= 1;
} else {
match.players[1].won -= 1;
match.players[0].lost -= 1;
}
$scope.updatePlayerRanks();
$scope.reorderMatches();
};
$scope.endMatch = function(match) {
match.status = 'ended';
if(match.scores[0] == match.scores[1])
{
match.players[0].draw += 1;
match.players[1].draw += 1;
} else if(match.scores[0] > match.scores[1]) {
match.players[0].won += 1;
match.players[1].lost += 1;
} else {
match.players[1].won += 1;
match.players[0].lost += 1;
}
$scope.reorderMatches();
$scope.updatePlayerRanks();
};
$scope.reset = function() {
$scope.matches = [];
$scope.players = [{}, {}];
$scope.inited = false;
if(DEBUG) {
$scope.players = [{name:'Herp'}, {name:'Derp'}, {name:'Merp'}];
}
$scope.exportToStorage();
};
if (localStorage.tourney) {
$scope.importFromStorage();
}
});
| 25.85 | 102 | 0.606998 |
5e1b244ea608b765faf20d09e0046e6ba6b7ce59 | 191 | js | JavaScript | index.js | wbinnssmith/leftpad-stream | 3a36fc6e5752550ee5f9455c34811cedb4570273 | [
"MIT"
] | 1 | 2020-08-06T21:43:15.000Z | 2020-08-06T21:43:15.000Z | index.js | wbinnssmith/leftpad-stream | 3a36fc6e5752550ee5f9455c34811cedb4570273 | [
"MIT"
] | null | null | null | index.js | wbinnssmith/leftpad-stream | 3a36fc6e5752550ee5f9455c34811cedb4570273 | [
"MIT"
] | null | null | null | const through = require('through2');
const leftpad = require('left-pad');
module.exports = function(pad) {
return through((chunk, enc, cb) => {
cb(null, leftpad(chunk, pad));
});
}
| 19.1 | 38 | 0.633508 |
5e1b78c7b0328fe3cee2f2522ba431d0401f1ce5 | 626 | js | JavaScript | frontend/src/components/SearchBar.js | SJTUSummerProj2020/- | c1101454d5a5e00217484c02f0eb193c50a58855 | [
"Apache-2.0"
] | 3 | 2020-07-06T05:29:22.000Z | 2020-07-06T06:42:36.000Z | frontend/src/components/SearchBar.js | SJTUSummerProj2020/- | c1101454d5a5e00217484c02f0eb193c50a58855 | [
"Apache-2.0"
] | 6 | 2020-07-21T01:57:24.000Z | 2021-12-14T21:52:46.000Z | frontend/src/components/SearchBar.js | SJTUSummerProj2020/- | c1101454d5a5e00217484c02f0eb193c50a58855 | [
"Apache-2.0"
] | 5 | 2020-07-21T06:15:05.000Z | 2021-04-16T06:32:06.000Z | import React from 'react';
import { Icon, Button, Input, AutoComplete } from 'antd';
import 'antd/dist/antd.min.css';
import {history} from "../utils/history";
const {Search} = Input;
export class SearchBar extends React.Component{
searchChange = (value) => {
if(value === ""){
history.push('/');
}
else{
let pathname = '/search?name=' + value;
history.push(pathname);
}
};
render() {
return(
<Search
placeholder={"搜索你感兴趣的演出"}
onSearch={this.searchChange}
/>
);
}
}
| 21.586207 | 57 | 0.50639 |
5e1bfb97217ab120aed3fea706a24aab36d4b14c | 4,266 | js | JavaScript | packages/validator/src/plugins/validation/2and3/semantic-validators/operation-ids.js | vmarkovtsev/openapi-validator | e9dcc90a1d55b658d98f0f0ca3e4ab74708c667a | [
"Apache-2.0"
] | null | null | null | packages/validator/src/plugins/validation/2and3/semantic-validators/operation-ids.js | vmarkovtsev/openapi-validator | e9dcc90a1d55b658d98f0f0ca3e4ab74708c667a | [
"Apache-2.0"
] | null | null | null | packages/validator/src/plugins/validation/2and3/semantic-validators/operation-ids.js | vmarkovtsev/openapi-validator | e9dcc90a1d55b658d98f0f0ca3e4ab74708c667a | [
"Apache-2.0"
] | null | null | null | // Assertation 1: Operations must have a unique operationId.
// Assertation 2: OperationId must conform to naming conventions.
const pickBy = require('lodash/pickBy');
const reduce = require('lodash/reduce');
const merge = require('lodash/merge');
const each = require('lodash/each');
const MessageCarrier = require('../../../utils/message-carrier');
module.exports.validate = function({ resolvedSpec }, config) {
const messages = new MessageCarrier();
config = config.operations;
const validOperationKeys = [
'get',
'head',
'post',
'put',
'patch',
'delete',
'options',
'trace'
];
const operations = reduce(
resolvedSpec.paths,
(arr, path, pathKey) => {
const pathOps = pickBy(path, (obj, k) => {
return validOperationKeys.indexOf(k) > -1;
});
const allPathOperations = Object.keys(pathOps);
each(pathOps, (op, opKey) =>
arr.push(
merge(
{
pathKey: `${pathKey}`,
opKey: `${opKey}`,
path: `paths.${pathKey}.${opKey}`,
allPathOperations
},
op
)
)
);
return arr;
},
[]
);
const operationIdPassedConventionCheck = (
opKey,
operationId,
allPathOperations,
pathEndsWithParam
) => {
// Only consider paths for which
// - paths that do not end with param has a GET and POST operation
// - paths that end with param has a GET, DELETE, POST, PUT or PATCH.
const verbs = [];
if (!pathEndsWithParam) {
// operationId for GET should starts with "list"
if (opKey === 'get') {
verbs.push('list');
}
// operationId for POST should starts with "create" or "add"
else if (opKey === 'post') {
verbs.push('add');
verbs.push('create');
}
} else {
// operationId for GET should starts with "get"
if (opKey === 'get') {
verbs.push('get');
}
// operationId for DELETE should starts with "delete"
else if (opKey === 'delete') {
verbs.push('delete');
}
// operationId for PATCH should starts with "update"
else if (opKey === 'patch') {
verbs.push('update');
}
// If PATCH operation doesn't exist for path, POST operationId should start with "update"
else if (opKey === 'post') {
if (!allPathOperations.includes('patch')) {
verbs.push('update');
}
}
// operationId for PUT should starts with "replace"
else if (opKey === 'put') {
verbs.push('replace');
}
}
if (verbs.length > 0) {
const checkPassed = verbs
.map(verb => operationId.startsWith(verb))
.some(v => v);
return { checkPassed, verbs };
}
return { checkPassed: true };
};
operations.forEach(op => {
// wrap in an if, since operationIds are not required
if (op.operationId) {
// Assertation 2: OperationId must conform to naming conventions
// We'll use a heuristic to decide if this path is part of a resource oriented API.
// If path ends in path param, look for corresponding create/list path
// Conversely, if no path param, look for path with path param
const pathEndsWithParam = op.pathKey.endsWith('}');
const isResourceOriented = pathEndsWithParam
? Object.keys(resolvedSpec.paths).includes(
op.pathKey.replace('/\\{[A-Za-z0-9-_]+\\}$', '')
)
: Object.keys(resolvedSpec.paths).some(p =>
p.startsWith(op.pathKey + '/{')
);
if (isResourceOriented) {
const { checkPassed, verbs } = operationIdPassedConventionCheck(
op['opKey'],
op.operationId,
op.allPathOperations,
pathEndsWithParam
);
if (checkPassed === false) {
messages.addMessage(
op.path + '.operationId',
`operationIds should follow naming convention: operationId verb should be ${verbs}`.replace(
',',
' or '
),
config.operation_id_naming_convention,
'operation_id_naming_convention'
);
}
}
}
});
return messages;
};
| 28.065789 | 104 | 0.563526 |
5e1c9808242eaa7186814b4b62d77017024a9867 | 327 | js | JavaScript | app/scripts/controllers/DeleteBookmarkCtrl.js | aivanochko/charttab | da90202c21239ec04d62d4c5363a5c9e2a5abea4 | [
"MIT"
] | null | null | null | app/scripts/controllers/DeleteBookmarkCtrl.js | aivanochko/charttab | da90202c21239ec04d62d4c5363a5c9e2a5abea4 | [
"MIT"
] | null | null | null | app/scripts/controllers/DeleteBookmarkCtrl.js | aivanochko/charttab | da90202c21239ec04d62d4c5363a5c9e2a5abea4 | [
"MIT"
] | null | null | null | angular.module('charttab').controller('DeleteBookmarkCtrl', function (ui, bookmarks) {
let vm = this;
vm.title = vm.bookmark.title;
vm.id = vm.bookmark.id;
vm.entity = 'bookmark';
vm.remove = function () {
bookmarks.remove(vm.id).then(ui.hideDialog);
};
vm.cancel = ui.hideDialog;
});
| 19.235294 | 86 | 0.617737 |
5e1d96f3779201c1f4ffcc54702bf09d7c2a00b9 | 3,390 | js | JavaScript | public/src/scripts/tables/app.table.ctrls.js | vinicio7/vista | 493bf593766bad03676b8022870505b2074100e1 | [
"MIT"
] | null | null | null | public/src/scripts/tables/app.table.ctrls.js | vinicio7/vista | 493bf593766bad03676b8022870505b2074100e1 | [
"MIT"
] | null | null | null | public/src/scripts/tables/app.table.ctrls.js | vinicio7/vista | 493bf593766bad03676b8022870505b2074100e1 | [
"MIT"
] | null | null | null | ;(function() {
"use strict";
angular.module("app.table.ctrls", [])
// Responsive Table Data (static)
.controller("ResponsiveTableDemoCtrl", ["$scope", function($scope) {
$scope.responsiveData = [
{
post: "My First Blog",
author: "Johnny",
categories: "WebDesign",
tags: ["wordpress", "blog"],
date: "20-3-2004",
tagColor: "pink"
},
{
post: "How to Design",
author: "Jenifer",
categories: "design",
tags: ["photoshop", "illustrator"],
date: "2-4-2012",
tagColor: "primary"
},
{
post: "Something is missing",
author: "Joe",
categories: "uncategorized",
tags: ["abc", "def", "ghi"],
date: "20-5-2013",
tagColor: "success"
},
{
post: "Learn a new language",
author: "Rinky",
categories: "language",
tags: ["C++", "Java", "PHP"],
date: "10-5-2014",
tagColor: "danger"
},
{
post: "I love singing. Do you?",
author: "AJ",
categories: "singing",
tags: ["music"],
date: "2-10-2014",
tagColor: "info"
}
];
}])
// Data Table
.controller("DataTableCtrl", ["$scope", "$filter", function($scope, $filter) {
// data
$scope.datas = [
{engine: "Gecko", browser: "Firefox 3.0", platform: "Win 98+/OSX.2+", version: 1.7, grade: "A"},
{engine: "Gecko", browser: "Firefox 5.0", platform: "Win 98+/OSX.2+", version: 1.8, grade: "A"},
{engine: "KHTML", browser: "Konqureror 3.5", platform: "KDE 3.5", version: 3.5, grade: "A"},
{engine: "Presto", browser: "Opera 8.0", platform: "Win 95+/OS.2+", version: "-", grade: "A"},
{engine: "Misc", browser: "IE Mobile", platform: "Windows Mobile 6", version: "-", grade: "C"},
{engine: "Trident", browser: "IE 5.5", platform: "Win 95+", version: 5, grade: "A"},
{engine: "Trident", browser: "IE 6", platform: "Win 98+", version: 7, grade: "A"},
{engine: "Webkit", browser: "Safari 3.0", platform: "OSX.4+", version: 419.3, grade: "A"},
{engine: "Webkit", browser: "iPod Touch / iPhone", platform: "OSX.4+", version: 420, grade: "B"},
];
var prelength = $scope.datas.length;
// create random data (uses `track by $index` in html for duplicacy)
for(var i = prelength; i < 100; i++) {
var rand = Math.floor(Math.random()*prelength);
$scope.datas.push($scope.datas[rand]);
}
$scope.searchKeywords = "";
$scope.filteredData = [];
$scope.row = "";
$scope.numPerPageOpts = [5, 7, 10, 25, 50, 100];
$scope.numPerPage = $scope.numPerPageOpts[1];
$scope.currentPage = 1;
$scope.currentPageStores = []; // data to hold per pagination
$scope.select = function(page) {
var start = (page - 1)*$scope.numPerPage,
end = start + $scope.numPerPage;
$scope.currentPageStores = $scope.filteredData.slice(start, end);
}
$scope.onFilterChange = function() {
$scope.select(1);
$scope.currentPage = 1;
$scope.row = '';
}
$scope.onNumPerPageChange = function() {
$scope.select(1);
$scope.currentPage = 1;
}
$scope.onOrderChange = function() {
$scope.select(1);
$scope.currentPage = 1;
}
$scope.search = function() {
$scope.filteredData = $filter("filter")($scope.datas, $scope.searchKeywords);
$scope.onFilterChange();
}
$scope.order = function(rowName) {
if($scope.row == rowName)
return;
$scope.row = rowName;
$scope.filteredData = $filter('orderBy')($scope.datas, rowName);
$scope.onOrderChange();
}
// init
$scope.search();
$scope.select($scope.currentPage);
}])
}()) | 25.488722 | 99 | 0.609145 |
5e1de76d730d3e2a349727d8f85a54d677f30ba4 | 1,889 | js | JavaScript | src/controllers/users.js | codeliezel/PropertyPro-Lite-Backend | 62032b1b28b0be97687222bfdcd4e4e8c5754554 | [
"MIT"
] | 2 | 2020-03-23T06:56:21.000Z | 2020-05-01T15:03:48.000Z | src/controllers/users.js | funmi5/PropertyPro-Lite-Backend | 62032b1b28b0be97687222bfdcd4e4e8c5754554 | [
"MIT"
] | 8 | 2019-07-12T19:39:31.000Z | 2019-07-18T17:46:40.000Z | src/controllers/users.js | funmi5/PropertyPro-Lite-Backend | 62032b1b28b0be97687222bfdcd4e4e8c5754554 | [
"MIT"
] | 2 | 2019-07-11T19:02:13.000Z | 2019-07-19T13:31:25.000Z | import moment from 'moment';
import db from '../config/index';
import { Helper } from '../utils/index';
import { signupQuery, signinQuery } from '../models/index';
const { generateToken } = Helper;
/**
* @class Usercontroller
* @description Controllers for users
* @exports Usercontroller
*/
export class Usercontroller {
/**
* @method signUp
* @description Method for signing up users
* @param {object} req - The Request Object
* @param {object} res - The Response Object
* @returns {object} response body object
*/
static async signUp(req, res) {
const {
email, firstName, lastName, password, phoneNumber, address,
} = req.body;
const hashPassword = Helper.hashPassword(password);
const values = [email, firstName, lastName, hashPassword, phoneNumber,
address, moment(new Date())];
try {
const { rows } = await db.query(signupQuery, values);
const token = generateToken(rows[0].id);
return res.status(201).json({ status: '201', data: rows, token });
} catch (error) {
if (error.routine === '_bt_check_unique') {
return res.status(409).json({ status: 409, error: 'OOPS! This particular email has already been registered!' });
}
}
}
/**
* @method signIn
* @description Method for signing in users
* @param {object} req - The Request Object
* @param {object} res - The Response Object
* @returns {object} response body object
*/
static async signIn(req, res) {
try {
const { rows } = await db.query(signinQuery, [req.body.email]);
const token = generateToken(rows[0].id);
return res.status(200).json({ status: '200', token });
} catch (error) {
return res.status(500).json({ status: '500', error: 'Oops, there\'s an error!' });
}
}
}
export default Usercontroller;
| 33.140351 | 121 | 0.622022 |
5e1dfaac9f94558776f9b05434876d01987a5b3c | 205 | js | JavaScript | src/app/config/commonStyle.js | rickyHong/Microsoft-taxi-data-visualization-repl | 5d9d8995b0da34cd5283ae558591b6047bf67317 | [
"MIT"
] | null | null | null | src/app/config/commonStyle.js | rickyHong/Microsoft-taxi-data-visualization-repl | 5d9d8995b0da34cd5283ae558591b6047bf67317 | [
"MIT"
] | null | null | null | src/app/config/commonStyle.js | rickyHong/Microsoft-taxi-data-visualization-repl | 5d9d8995b0da34cd5283ae558591b6047bf67317 | [
"MIT"
] | null | null | null | const commonStyle = {
myblue: `rgba(12, 21, 36, 1)`,
mypink: `rgba(255, 94, 146, 1)`,
myorange: `rgba(244, 91, 60, 1)`,
myskyblue: `rgba(103, 135, 254, 1)`,
}
;
export default commonStyle; | 22.777778 | 40 | 0.580488 |
5e1e6b16e9022136af4beced827f19c4129d93d4 | 733 | js | JavaScript | src/cli/maha.js | ccetc/mahaplatform.com | 6e8610fe6e835e071492784655dbb5502863d031 | [
"MIT"
] | null | null | null | src/cli/maha.js | ccetc/mahaplatform.com | 6e8610fe6e835e071492784655dbb5502863d031 | [
"MIT"
] | null | null | null | src/cli/maha.js | ccetc/mahaplatform.com | 6e8610fe6e835e071492784655dbb5502863d031 | [
"MIT"
] | null | null | null | import _ from 'lodash'
const run = async (filepath, args) => {
const script = require(filepath).default
await script(args)
}
const maha = async (command, args) => {
if(command === 'bootstrap') await run('./bootstrap', args)
if(command === 'ccev2') await run('./ccev2', args)
if(command === 'dev') await run('./dev', args)
if(command === 'env') await run('./env', args)
if(command === 'g') await run('./generate', args)
if(command === 'knex') await run('./knex', args)
if(command === 'start') await run('./start', args)
if(command === 'team') await run('./team', args)
if(command === 'translate') await run('./translate', args)
if(!_.includes(['dev','start'], command)) process.exit()
}
export default maha
| 33.318182 | 60 | 0.61528 |
5e1e72e739c1eb5ac1484e525b4e5d4c0ca0d7d5 | 588 | js | JavaScript | src/js/modules/sliders/sliderPrograms.js | zabellfour/radio | 625ae6ade2f9b386f80f5593e71bf7f48b5a72c0 | [
"MIT"
] | null | null | null | src/js/modules/sliders/sliderPrograms.js | zabellfour/radio | 625ae6ade2f9b386f80f5593e71bf7f48b5a72c0 | [
"MIT"
] | null | null | null | src/js/modules/sliders/sliderPrograms.js | zabellfour/radio | 625ae6ade2f9b386f80f5593e71bf7f48b5a72c0 | [
"MIT"
] | null | null | null | var sliderPrograms = {
init: function() {
var slider = $('.program-slider');
if (!slider) {
return;
}
slider.owlCarousel({
items: 4,
dots: false,
nav: true,
responsive: {
// breakpoint from 0 up
0: {
items: 2
},
480: {
items: 3
},
1024: {
items: 4
}
}
});
}
};
export default sliderPrograms; | 18.967742 | 42 | 0.312925 |
5e1f4c2f571921b3976ccc85e4146876557b25df | 264 | js | JavaScript | src/FileUtility.js | aks427/canvas-image-capture | dfac3c3d2280d0e2954ab199853b3dbd1a8dfe3a | [
"MIT"
] | null | null | null | src/FileUtility.js | aks427/canvas-image-capture | dfac3c3d2280d0e2954ab199853b3dbd1a8dfe3a | [
"MIT"
] | null | null | null | src/FileUtility.js | aks427/canvas-image-capture | dfac3c3d2280d0e2954ab199853b3dbd1a8dfe3a | [
"MIT"
] | null | null | null | /* eslint-disable import/prefer-default-export */
export const loadFileAsDataUrl = file => new Promise((callback) => {
const fileReader = new FileReader();
fileReader.onload = () => {
callback(fileReader.result);
};
fileReader.readAsDataURL(file);
});
| 29.333333 | 68 | 0.693182 |
5e1f68a741abfad7b43a8b37bf61cd68309fe198 | 982 | js | JavaScript | hw3/tests/hw4.test.js | robinsph21/CS341-HW3 | ff0aec64d2cd9f03b7df58ea426db1d882258f4d | [
"MIT"
] | null | null | null | hw3/tests/hw4.test.js | robinsph21/CS341-HW3 | ff0aec64d2cd9f03b7df58ea426db1d882258f4d | [
"MIT"
] | 1 | 2021-05-11T03:01:07.000Z | 2021-05-11T03:01:07.000Z | hw3/tests/hw4.test.js | robinsph21/CS341-HW3 | ff0aec64d2cd9f03b7df58ea426db1d882258f4d | [
"MIT"
] | null | null | null | const fs = require('fs');
const request = require('supertest');
const express = require('express');
const app = express();
const router = express.Router();
test('Proper path set', () => {
var appjs = fs.readFileSync('app.js', 'utf8');
expect(appjs).toEqual(expect.stringContaining('app.use\(\'/orders\','));
});
// Credit:
// https://stackoverflow.com/questions/9517880/how-does-one-unit-test-routes-with-express#answer-33459311
test('Test JSON request returns 200', () => {
router.get('/orders', function(req, res){
res.json({
"error":null,
"data":[
{"topping":"cherry", "quantity":"2"},
{"topping":"plain", "quantity":"6"},
{"topping":"chocolate", "quantity":"3"}
]
});
});
app.use(router);
request(app).get('/orders').expect('Content-Type', /json/).expect(200).end( function(err, res) {
// Do nothing
});
});
// test('', () => {
//
// });
| 28.057143 | 105 | 0.547862 |
5e1fad55258ab8455836af4b3d3090adde467c5e | 3,693 | js | JavaScript | data/split-book-data/B07QY2QMCR.1645023043620.js | joshuaspatrick/MyAudibleLibrary | c65bd60363a7c909246d339dec8b2a57a7b1806b | [
"0BSD"
] | null | null | null | data/split-book-data/B07QY2QMCR.1645023043620.js | joshuaspatrick/MyAudibleLibrary | c65bd60363a7c909246d339dec8b2a57a7b1806b | [
"0BSD"
] | null | null | null | data/split-book-data/B07QY2QMCR.1645023043620.js | joshuaspatrick/MyAudibleLibrary | c65bd60363a7c909246d339dec8b2a57a7b1806b | [
"0BSD"
] | null | null | null | window.peopleAlsoBoughtJSON = [{"asin":"B08DDCVRRC","authors":"Tyler Shultz","cover":"51Di+gUJ9HL","length":"3 hrs and 36 mins","narrators":"Tyler Shultz","title":"Thicker than Water"},{"asin":"B085F3F6CX","authors":"Chris Grabenstein","cover":"51GKoszPFmL","length":"3 hrs and 12 mins","narrators":"Mark Sanderlin, Elizabeth Hess, Oliver Wyman, and others","title":"Stuck"},{"asin":"B08DDC8Y8F","authors":"Jesse Eisenberg","cover":"518x9ZiVZbL","length":"5 hrs and 17 mins","narrators":"Kaitlyn Dever, Jesse Eisenberg, Finn Wolfhard","title":"When You Finish Saving the World"},{"asin":"B089T5SW3N","authors":"Dan Rather","cover":"51NK159FbkL","length":"1 hr and 24 mins","narrators":"Dan Rather","title":"Dan Rather: Stories of a Lifetime"},{"asin":"B0883GHNZQ","authors":"Harvey Fierstein","cover":"51Hhvqc6SML","length":"1 hr and 13 mins","narrators":"Harvey Fierstein","title":"Bella Bella"},{"asin":"B08DDJ56J2","authors":"Joan Didion","cover":"513oKbpMTgL","length":"1 hr and 28 mins","narrators":"Vanessa Redgrave","title":"The Year of Magical Thinking"},{"asin":"B08DG7X16V","authors":"Common, Awoye Timpo, NSangou Njikam","cover":"516mu-GabiL","length":"1 hr and 21 mins","narrators":"Common","subHeading":"A Journey Through Lyrics & Life","title":"Bluebird Memories"},{"asin":"B08DDD5V8J","authors":"Sanjay Gupta MD","cover":"51sWmdvLSzL","length":"46 mins","narrators":"Dr. Sanjay Gupta","subHeading":"Raising Kids During a Pandemic","title":"Childhood, Interrupted"},{"asin":"B0842XZJC7","authors":"Patrick Allitt, The Great Courses","cover":"51KcBsX2C7L","length":"4 hrs and 28 mins","narrators":"Patrick Allitt","title":"The Life and Times of Prince Albert"},{"asin":"B0898CK44Z","authors":"Nikki Levy","cover":"5193sX9kjFL","length":"1 hr and 34 mins","narrators":"Nikki Levy, Shangela, full cast","title":"Coming Out Party"},{"asin":"B074GG7MT1","authors":"Alexander C. Kane","cover":"618fOq1qlyL","length":"8 hrs and 50 mins","narrators":"Bahni Turpin","title":"Andrea Vernon and the Corporation for UltraHuman Protection"},{"asin":"B07ZRY8L2Q","authors":"Carrie Seim","cover":"513GsJpvEgL","length":"2 hrs and 13 mins","narrators":"Gabriel Vaughan, Bill Andrew Quinn, Jessica Almasy, and others","title":"The Flying Flamingo Sisters"}];
window.bookSummaryJSON = "<p>Sherlock Holmes is the most portrayed fictional character of all time, and he has been reimagined by actors, playwrights and directors over centuries - but who is the creator behind the detective? </p> <p>Conan Doyle’s own life was often stranger than fiction, and his most famous characters’ stories and personalities bear more than a passing resemblance to his own life and his closest friends. </p> <p>Biographer and broadcaster Lucinda Hawksley gains unprecedented access to a treasure trove of Doyle’s never-before-seen personal letters and diaries. This is a chance for Sherlock fans to see their detective hero and his creator as they’ve never seen them before. Through interviews with Doyle aficionados, academics, actors and family members, we explore Doyle’s travels and sailing adventures across the globe, his pioneering work as a doctor, his life in the Freemasons and his fights against miscarriages of justice. As well as his many triumphs, we will also explore the challenges he faced, from the death of his first wife and son to the initial rejection he faced as an author. </p> <p>We will also look beyond Sherlock to Doyle’s other great works including his fantasy and science fiction novels and hear how one of his most famous, <i>The Lost World</i>, part-inspired Michael Crichton’s book of the same name, which became the successful Jurassic Park film franchise.</p>";
| 1,231 | 2,256 | 0.748985 |
5e1fbd72e74089fb65e763effcc2d42f092e7345 | 302 | js | JavaScript | webpack.mix.js | 17grad/laravel-content-administration | 294f02760814a5e98b0be5ec522874dd474ad5e6 | [
"MIT"
] | 1 | 2021-03-10T04:59:54.000Z | 2021-03-10T04:59:54.000Z | webpack.mix.js | 17grad/laravel-content-administration | 294f02760814a5e98b0be5ec522874dd474ad5e6 | [
"MIT"
] | null | null | null | webpack.mix.js | 17grad/laravel-content-administration | 294f02760814a5e98b0be5ec522874dd474ad5e6 | [
"MIT"
] | null | null | null | const mix = require('laravel-mix');
mix.js('resources/js/app.js', 'public/js').sass(
'resources/sass/app.scss',
'public/css'
);
mix.webpackConfig({
resolve: {
alias: {
'@fj-js': path.resolve(__dirname, 'resources/js/'),
'@fj-sass': path.resolve(__dirname, 'resources/sass/'),
},
},
});
| 18.875 | 58 | 0.625828 |
5e1fcae85fdf397b79c023ca75dba85f8a009a3e | 292 | js | JavaScript | web/src/hooks/channel/settings/index.js | aereeeee/2019-02 | d5894a9a21a90f465be553cc9b43562b4f88d1ec | [
"MIT"
] | 37 | 2019-11-04T03:06:31.000Z | 2021-03-13T11:32:32.000Z | web/src/hooks/channel/settings/index.js | aereeeee/2019-02 | d5894a9a21a90f465be553cc9b43562b4f88d1ec | [
"MIT"
] | 119 | 2019-11-07T08:15:59.000Z | 2020-06-26T17:08:13.000Z | web/src/hooks/channel/settings/index.js | aereeeee/2019-02 | d5894a9a21a90f465be553cc9b43562b4f88d1ec | [
"MIT"
] | 9 | 2019-11-16T14:07:30.000Z | 2020-12-12T08:47:43.000Z | export { default as useUpdateChannelOptions } from './useUpdateChannelOptions';
export { default as useAnonymousChanged } from './useAnonymousChanged';
export { default as useChannelNameChanged } from './useChannelNameChanged';
export { default as useEmojiChanged } from './useEmojiChanged';
| 58.4 | 79 | 0.794521 |
5e1fddf26528553ac73ded3e2d76110baf1ccbce | 360 | js | JavaScript | lib/run.js | notablemind/jupyter-node | 1388e1957792ef167ccfc7a9cf6c64c3950ded76 | [
"MIT"
] | 737 | 2015-04-22T15:55:22.000Z | 2022-02-27T23:10:37.000Z | lib/run.js | notablemind/jupyter-node | 1388e1957792ef167ccfc7a9cf6c64c3950ded76 | [
"MIT"
] | 61 | 2015-04-29T17:19:21.000Z | 2020-01-08T06:43:57.000Z | lib/run.js | liuderchi/jupyter-nodejs | 4bd5062a7b5488c488c8230c1bda946110b38cb6 | [
"MIT"
] | 98 | 2015-04-22T21:51:43.000Z | 2022-03-31T11:59:04.000Z |
import path from 'path'
import Kernel from './kernel'
if (process.argv.length != 3) {
console.log('Need a JSON config object')
process.exit()
}
const config = require(path.resolve(process.argv[2]))
const kernel = new Kernel(config)
kernel.init(err => {
if (err) {
console.error("Failed to init")
console.log(err)
process.exit()
}
})
| 15.652174 | 53 | 0.652778 |
5e202f1f0bcfbb19dd2bef823693d09d7ab5a01b | 489 | js | JavaScript | node_modules/pg/lib/native/result.js | anudr01d/anudr01d.github.io | f0886dce42932c2fc6bab5446c0707c441412d70 | [
"MIT"
] | 31 | 2015-01-05T03:40:13.000Z | 2021-06-06T08:05:37.000Z | node_modules/pg/lib/native/result.js | anudr01d/anudr01d.github.io | f0886dce42932c2fc6bab5446c0707c441412d70 | [
"MIT"
] | 6 | 2016-06-02T18:14:24.000Z | 2017-07-07T07:01:20.000Z | node_modules/pg/lib/native/result.js | anudr01d/anudr01d.github.io | f0886dce42932c2fc6bab5446c0707c441412d70 | [
"MIT"
] | 20 | 2015-01-18T12:17:06.000Z | 2018-12-16T15:38:13.000Z | var NativeResult = module.exports = function(pq) {
this.command = null;
this.rowCount = 0;
this.rows = null;
this.fields = null;
};
NativeResult.prototype.addCommandComplete = function(pq) {
this.command = pq.cmdStatus().split(' ')[0];
this.rowCount = pq.cmdTuples();
var nfields = pq.nfields();
if(nfields < 1) return;
this.fields = [];
for(var i = 0; i < nfields; i++) {
this.fields.push({
name: pq.fname(i),
dataTypeID: pq.ftype(i)
});
}
};
| 21.26087 | 58 | 0.609407 |
5e20a66bcee2e5d616de56086446de66f2e48b78 | 3,975 | js | JavaScript | extern/Halide/osx/share/doc/Halide/mini__qurt_8h.js | HiDoYa/webassembly-video-filters | 70bcaaaeb94a763988975aa8e1582ed10c2f2c39 | [
"MIT"
] | 5 | 2021-01-15T03:40:25.000Z | 2021-09-05T22:53:38.000Z | extern/Halide/osx/share/doc/Halide/mini__qurt_8h.js | HiDoYa/webassembly-video-filters | 70bcaaaeb94a763988975aa8e1582ed10c2f2c39 | [
"MIT"
] | 1 | 2021-05-05T21:57:46.000Z | 2021-05-05T23:18:06.000Z | extern/Halide/osx/share/doc/Halide/mini__qurt_8h.js | HiDoYa/webassembly-video-filters | 70bcaaaeb94a763988975aa8e1582ed10c2f2c39 | [
"MIT"
] | null | null | null | var mini__qurt_8h =
[
[ "_qurt_thread_attr", "struct__qurt__thread__attr.html", null ],
[ "qurt_mutex_aligned8", "unionqurt__mutex__aligned8.html", null ],
[ "qurt_cond_t", "unionqurt__cond__t.html", null ],
[ "QURT_HTHREAD_L1I_PREFETCH", "group__qurt__thread__macros.html#ga940622819891dbfaf7bf7e8e99740d6f", null ],
[ "QURT_HTHREAD_L1D_PREFETCH", "group__qurt__thread__macros.html#ga1785a2d9327292a7caf262b51f875a50", null ],
[ "QURT_HTHREAD_L2I_PREFETCH", "group__qurt__thread__macros.html#ga31aeebd0ee68816e1c42a0c185a8c728", null ],
[ "QURT_HTHREAD_L2D_PREFETCH", "group__qurt__thread__macros.html#gaf8058250ae3deeed789d94e4b6a8e36c", null ],
[ "QURT_HTHREAD_DCFETCH", "group__qurt__thread__macros.html#ga993da0121182551dbc915dd91e043cc5", null ],
[ "QURT_THREAD_ATTR_NAME_MAXLEN", "group__qurt__thread__macros.html#ga5e61cac72e9a110d4b4f04174bfa6d8f", null ],
[ "QURT_THREAD_ATTR_TCB_PARTITION_RAM", "group__qurt__thread__macros.html#ga5d8f0688f426d98d06f0c8bc7eee3d94", null ],
[ "QURT_THREAD_ATTR_TCB_PARTITION_TCM", "group__qurt__thread__macros.html#ga5e84f14fdf89901e55ebe6119575a02b", null ],
[ "QURT_THREAD_ATTR_TCB_PARTITION_DEFAULT", "group__qurt__thread__macros.html#ga814c77ab3dd3043c4d44b499f450466d", null ],
[ "QURT_THREAD_ATTR_PRIORITY_DEFAULT", "group__qurt__thread__macros.html#gaecf40aa9ef4ed251e1466107aa70d5b0", null ],
[ "QURT_THREAD_ATTR_ASID_DEFAULT", "group__qurt__thread__macros.html#ga52f9acc9a413968831a89481547ba6d2", null ],
[ "QURT_THREAD_ATTR_AFFINITY_DEFAULT", "group__qurt__thread__macros.html#ga8c0943916a6b5c4523a64a9051954596", null ],
[ "QURT_THREAD_ATTR_BUS_PRIO_DEFAULT", "group__qurt__thread__macros.html#ga27a5e1c49ee6b8f7c0e9ca8f762675e2", null ],
[ "QURT_THREAD_ATTR_TIMETEST_ID_DEFAULT", "group__qurt__thread__macros.html#ga3d664fb856b7d9eba26b52f383d983ec", null ],
[ "qurt_thread_t", "mini__qurt_8h.html#aee47afd498b75df65c089f744befb2e8", null ],
[ "qurt_thread_attr_t", "mini__qurt_8h.html#aff5eb1355d32baa3b65ac24e8216cb0b", null ],
[ "qurt_mutex_t", "mini__qurt_8h.html#aa5f3c37b281bff4be02457de1e07250e", null ],
[ "qurt_size_t", "mini__qurt_8h.html#a7a8347f5611d503fb88f354d388745fa", null ],
[ "qurt_mem_pool_t", "mini__qurt_8h.html#a517a4b46a7468ed607c2aa282bd6d8b9", null ],
[ "qurt_hvx_mode_t", "mini__qurt_8h.html#aadda49b6c7e9ab50c86af6f978839e74", [
[ "QURT_HVX_MODE_64B", "mini__qurt_8h.html#aadda49b6c7e9ab50c86af6f978839e74a0edf57217d7f877544e07b138a9342ee", null ],
[ "QURT_HVX_MODE_128B", "mini__qurt_8h.html#aadda49b6c7e9ab50c86af6f978839e74ac13526cab3a2fc1dc838c278308f6001", null ]
] ],
[ "qurt_thread_set_priority", "mini__qurt_8h.html#a8fb79c7b918fd04b86e55f590a8d1418", null ],
[ "qurt_thread_create", "mini__qurt_8h.html#a97eb87bb7208c64e7ac39fcb2b74b024", null ],
[ "qurt_thread_join", "mini__qurt_8h.html#ac88e59ce9e22adc909f361be0fb33135", null ],
[ "qurt_mutex_init", "mini__qurt_8h.html#a9d18929e7ccc94a057188c26648c5872", null ],
[ "qurt_mutex_destroy", "mini__qurt_8h.html#a5b3b3280101fea4cf13b10576825cc70", null ],
[ "qurt_mutex_lock", "mini__qurt_8h.html#a75d673e568ed5c64c515b7517f70e424", null ],
[ "qurt_mutex_unlock", "mini__qurt_8h.html#a0e6810988d2ee908bc8c51ffdd9d22ca", null ],
[ "qurt_cond_init", "mini__qurt_8h.html#a2e6dec95eec59ff032d63888f8da51c1", null ],
[ "qurt_cond_destroy", "mini__qurt_8h.html#aa7cba173d8ac9e5d02061e8ca4650e44", null ],
[ "qurt_cond_signal", "mini__qurt_8h.html#a84e235b482a0fc9f88002679e38ef1d5", null ],
[ "qurt_cond_wait", "mini__qurt_8h.html#a4adfa5201cf228a6f140208715563ccd", null ],
[ "qurt_hvx_lock", "mini__qurt_8h.html#afe97ee1b6f259a77966c8d41c90c2e07", null ],
[ "qurt_hvx_unlock", "mini__qurt_8h.html#ac56b09f5f52d454288ccc8930e0b909b", null ],
[ "qurt_hvx_get_mode", "mini__qurt_8h.html#a025d8e1b92a75a0c00dd118d6a4dc4fa", null ]
]; | 92.44186 | 127 | 0.789686 |
5e20e729163c29a95058960bb5d7cd7ff3acdf2d | 500 | js | JavaScript | app/build/precache-manifest.1fc6d8ef3f9076de773e19af4aab31e3.js | Xu-Angel/Novel | c2bfec57745b4e940ff8c1c491cdedbe460321fe | [
"MIT"
] | 48 | 2019-04-04T02:21:35.000Z | 2022-03-29T07:57:18.000Z | app/build/precache-manifest.1fc6d8ef3f9076de773e19af4aab31e3.js | Xu-Angel/Novel | c2bfec57745b4e940ff8c1c491cdedbe460321fe | [
"MIT"
] | 9 | 2019-04-04T03:43:18.000Z | 2021-05-08T11:55:56.000Z | app/build/precache-manifest.1fc6d8ef3f9076de773e19af4aab31e3.js | Xu-Angel/Novel | c2bfec57745b4e940ff8c1c491cdedbe460321fe | [
"MIT"
] | 7 | 2019-04-04T04:10:55.000Z | 2022-03-29T07:57:17.000Z | self.__precacheManifest = [
{
"revision": "42ac5946195a7306e2a5",
"url": "/static/js/runtime~main.a8a9905a.js"
},
{
"revision": "3d916d55ec5a9d355eea",
"url": "/static/js/main.e5de3fc5.chunk.js"
},
{
"revision": "5066f10d00fb68dc6c20",
"url": "/static/js/2.f16a817b.chunk.js"
},
{
"revision": "3d916d55ec5a9d355eea",
"url": "/static/css/main.942356e2.chunk.css"
},
{
"revision": "abc5f4ce35ce5730fd0c99bb3ed9f9d7",
"url": "/index.html"
}
]; | 22.727273 | 51 | 0.614 |
5e219a07639f16ca0ca297aa9a8aa71e061e9449 | 140 | js | JavaScript | build/inputex-menu/lang/inputex-menu_pl.js | johan--/inputex | b35843cb0b5a83d2ae91444b3082c863b3ff3029 | [
"MIT"
] | null | null | null | build/inputex-menu/lang/inputex-menu_pl.js | johan--/inputex | b35843cb0b5a83d2ae91444b3082c863b3ff3029 | [
"MIT"
] | null | null | null | build/inputex-menu/lang/inputex-menu_pl.js | johan--/inputex | b35843cb0b5a83d2ae91444b3082c863b3ff3029 | [
"MIT"
] | null | null | null | YUI.add("lang/inputex-menu_pl",function(e){e.Intl.add("inputex-menu","pl",{menuTypeInvite:"Kliknij tutaj, aby wybra\u0107"})},"@VERSION@");
| 70 | 139 | 0.714286 |
5e22bab73210542cbbb3afaaf7e1bc51f35bdf33 | 289 | js | JavaScript | public/asset/js/pages/ui/modals.js | hamadaali22/estalia | 276e17a5f1c36fbb06144a16b4b0fe05bacd6ec4 | [
"MIT"
] | null | null | null | public/asset/js/pages/ui/modals.js | hamadaali22/estalia | 276e17a5f1c36fbb06144a16b4b0fe05bacd6ec4 | [
"MIT"
] | null | null | null | public/asset/js/pages/ui/modals.js | hamadaali22/estalia | 276e17a5f1c36fbb06144a16b4b0fe05bacd6ec4 | [
"MIT"
] | null | null | null | 'use strict';
$(function () {
$('.js-modal-buttons .btn').on('click', function () {
var color = $(this).data('color');
$('#mdModal .modal-content').removeAttr('class').addClass('modal-content modal-col-' + color);
$('#mdModal').modal('show');
});
}); | 36.125 | 103 | 0.529412 |
5e23501868776e445edb20b7727bfa3da2aca9a5 | 879 | js | JavaScript | tests/config.js | ajaydeshmukh123/test | 3b005fe8bab10f502868f140f248cc84531ee476 | [
"MIT"
] | 1 | 2018-09-19T12:58:21.000Z | 2018-09-19T12:58:21.000Z | tests/config.js | ajaydeshmukh123/test | 3b005fe8bab10f502868f140f248cc84531ee476 | [
"MIT"
] | null | null | null | tests/config.js | ajaydeshmukh123/test | 3b005fe8bab10f502868f140f248cc84531ee476 | [
"MIT"
] | null | null | null | //Personify.js
//For more information, visit http://personifyjs.github.io.
//Created by Essam Al Joubori, Rohan Agrawal, Phil Elauria
//Copyright 2014 - 2015 Essam Al Joubori, Rohan Agrawal, Phil Elauria
//For use under the MIT license
// In order to run 'npm test' you will need to paste your Watson and Twitter
// OAuth credentials (see README.md for more details).
var config = {
translateConfig : {
service_url : '...',
service_username : '...',
service_password : '...'
},
personalityConfig : {
service_url: '...',
service_username: '...',
service_password: '...'
},
twitterConfig : {
consumer_key: '...',
consumer_secret: '...',
access_token: '...',
access_token_secret: '...'
}
};
module.exports = config; | 29.3 | 77 | 0.564278 |
5e23c233918848ad0c0f06c497d805913e9669b7 | 38,524 | js | JavaScript | plugins/cindygl/src/js/CodeBuilder.js | gagern/CindyJS | 7f50fee654f96556b9018ed9553e0e84da39dbb8 | [
"Apache-2.0"
] | null | null | null | plugins/cindygl/src/js/CodeBuilder.js | gagern/CindyJS | 7f50fee654f96556b9018ed9553e0e84da39dbb8 | [
"Apache-2.0"
] | 5 | 2015-11-04T13:42:58.000Z | 2017-01-13T10:49:51.000Z | plugins/cindygl/src/js/CodeBuilder.js | gagern/CindyJS | 7f50fee654f96556b9018ed9553e0e84da39dbb8 | [
"Apache-2.0"
] | null | null | null | /**
* @constructor
*/
function CodeBuilder(api) {
this.variables = {};
this.uniforms = {};
this.scopes = {};
this.sections = {};
this.typetime = 0; //the last time when a type got changed
this.myfunctions = {};
this.api = api;
this.texturereaders = {};
}
/** @type {Object} */
CodeBuilder.prototype.sections;
/**
* adds a snipped of code to the header of the current code builder and marks the corresponding identifier
* Ignores call if code has already been added to the identifier in the given section.
* @param {string} section section to which the code is suppoed to be added
* @param {string} name an identifier for the corresponding code
* @param {function():string} codegen is a callback that generates code to be added (at the end of the corresponding section)
*/
CodeBuilder.prototype.add = function(section, name, codegen) {
this.mark(section, name);
if (!this.sections[section].codes[name]) {
//console.log(`adding ${name} to ${section}: ${code}`);
this.sections[section].codes[name] = codegen();
this.sections[section].marked[name] = true;
this.sections[section].order.push(name);
}
};
/**
* marks a given identifier in a given section.
* returns wheather code with a given identifier has been marked before
* @param {string} section section to which the code is suppoed to be marked
* @param {string} name an identifier
*/
CodeBuilder.prototype.mark = function(section, name) {
if (!this.sections[section]) this.sections[section] = {
order: [],
marked: {},
codes: {}
};
let r = this.sections[section].marked[name] || false;
this.sections[section].marked[name] = true;
return r;
};
/**
* returns the entire section code in correct order
* @param {string} section
* @return {string}
*/
CodeBuilder.prototype.generateSection = function(section) {
return this.sections[section] ?
this.sections[section].order.map(name => this.sections[section].codes[name]).join('\n') : '\n';
};
/** @dict @type {Object} */
CodeBuilder.prototype.myfunctions;
/** @dict @type {number} */
CodeBuilder.prototype.typetime;
/** @dict @type {Object} */
CodeBuilder.prototype.variables;
/** @dict @type {Object} */
CodeBuilder.prototype.uniforms;
/** @type {CindyJS.pluginApi} */
CodeBuilder.prototype.api;
/** @type {Object.<TextureReader>} */
CodeBuilder.prototype.texturereaders;
/**
* Creates new term that is casted to toType
* assert that fromType is Type of term
* assert that fromType is a subtype of toType
*/
CodeBuilder.prototype.castType = function(term, fromType, toType) {
if (typesareequal(fromType, toType)) return term;
if (fromType === type.anytype) return term;
if (!issubtypeof(fromType, toType)) {
console.error(`${typeToString(fromType)} is no subtype of ${typeToString(toType)} (trying to cast the term ${term})`);
return term;
} else if (fromType.type === "constant") {
return pastevalue(fromType.value, toType);
} else {
let implementation = inclusionfunction(toType)([fromType]);
if (!implementation) {
console.error(`cannot find an implementation for ${typeToString(fromType)} -> ${typeToString(toType)}, using identity`);
return term;
}
let generator = implementation.generator;
return generator(this.castType(term, fromType, implementation.args[0]), {}, this);
}
};
/**
* Initializes the entry in this.variables for the variable with given name if it is not initialized yet.
*/
CodeBuilder.prototype.initvariable = function(vname, declareglobal) {
if (!this.variables[vname]) this.variables[vname] = {};
if (!this.variables[vname].assigments) this.variables[vname].assigments = [];
if (!this.variables[vname].T) this.variables[vname].T = false;
if (!this.hasOwnProperty('global')) this.variables[vname]['global'] = declareglobal;
};
/**
* computes the type of the expr, assuming it is evaluated with the given variable-bindings
* It might consider the type of variables (variables[name].T)
*/
CodeBuilder.prototype.computeType = function(expr) { //expression
let bindings = expr.bindings;
if (expr['isuniform']) {
return this.uniforms[expr['uvariable']].type;
} else if (expr['ctype'] === 'variable') {
let name = expr['name'];
name = bindings[name] || name;
return this.variables[name].T;
} else if (expr['ctype'] === 'function' && this.myfunctions.hasOwnProperty(expr['oper'])) {
return this.variables[bindings[expr['oper']]].T;
} else if (expr['ctype'] === 'number') {
return constant(expr);
} else if (expr['ctype'] === 'void') {
return type.voidt;
} else if (expr['ctype'] === 'field') {
let t = generalize(this.getType(expr['obj']));
if (t.type === 'list') return t.parameters;
if (!t) return false;
} else if (expr['ctype'] === 'string') {
return type.image;
} else if (expr['ctype'] === 'function' || expr['ctype'] === 'infix') {
var argtypes = new Array(expr['args'].length);
let allconstant = true;
for (let i = 0; i < expr['args'].length; i++) {
argtypes[i] = this.getType(expr['args'][i]);
allconstant &= (argtypes[i].type === 'constant');
}
if (allconstant && expr['impl']) { //use api.evaluateAndVal to compute type of constant expression
let constantexpression = {
"ctype": expr['ctype'],
"oper": expr['oper'],
"impl": expr['impl'],
"args": argtypes.map(a => a.value)
};
let val = this.api.evaluateAndVal(constantexpression);
return constant(val);
} else { //if there is something non-constant, we will the functions specified in WebGL.js
let f = getPlainName(expr['oper']);
let implementation = webgl[f] ? webgl[f](argtypes) : false;
if (!implementation && argtypes.every(a => finalparameter(a))) { //no implementation found and all args are set
console.error(`Could not find an implementation for ${f} with args (${argtypes.map(typeToString).join(', ')})`);
console.log(expr);
throw ("error");
}
return implementation ? implementation.res : false;
}
}
console.error("Don't know how to compute type of");
console.log(expr);
return false;
};
/**
* gets the type of the expr, trying to use cached results. Otherwise it will call computeType
*/
CodeBuilder.prototype.getType = function(expr) { //expression, current function
if (!expr.computedType || !expr.typetime || this.typetime > expr.typetime) {
expr.computedType = this.computeType(expr);
expr.typetime = this.typetime;
}
return expr.computedType;
};
/**
* finds the occuring variables, saves them to this.variables with their occuring assigmets.
* Furthermore attaches an bindings-dictionary to each expression that is tranversed.
*/
CodeBuilder.prototype.determineVariables = function(expr, bindings) {
//for some reason this reference does not work in local function. Hence generate local variables
let variables = this.variables; //functionname -> list of variables occuring in this scope. global corresponds to ''-function
let myfunctions = this.myfunctions;
var self = this;
rec(expr, bindings, 'global', false);
//clones the a bindings-dict and addes one variable of given type to it
function addvar(bindings, varname, type) {
let ans = {}; //clone bindings
for (let i in bindings) ans[i] = bindings[i];
let ivar = generateUniqueHelperString();
self.initvariable(ivar, false);
variables[ivar].T = type;
variables[ivar].iterationvariable = true;
ans[varname] = ivar;
return ans;
}
//dfs over executed code
function rec(expr, bindings, scope, forceconstant) {
expr.bindings = bindings;
for (let i in expr['args']) {
let needtobeconstant = forceconstant || (expr['oper'] === "repeat$2" && i == 0) || (expr['oper'] === "repeat$3" && i == 0) || (expr['oper'] === "_" && i == 1);
let nbindings = bindings;
if (["repeat", "forall", "apply"].indexOf(getPlainName(expr['oper'])) != -1) {
if (i == 1) {
nbindings = (expr['oper'] === "repeat$2") ? addvar(bindings, '#', type.int) :
(expr['oper'] === "repeat$3") ? addvar(bindings, expr['args'][1]['name'], type.int) :
(expr['oper'] === "forall$2" || expr['oper'] === "apply$2") ? addvar(bindings, '#', false) :
(expr['oper'] === "forall$3" || expr['oper'] === "apply$3") ? addvar(bindings, expr['args'][1]['name'], false) : bindings;
} else if (i == 2) { //take same bindings as for second argument
nbindings = expr['args'][1].bindings;
}
}
rec(expr['args'][i],
nbindings,
scope,
needtobeconstant);
}
if (expr['ctype'] === 'field') rec(expr['obj'], bindings, scope, forceconstant);
if (expr['ctype'] === 'variable') {
let vname = expr['name'];
vname = bindings[vname] || vname;
if (forceconstant && self.variables[vname]) {
//console.log(`mark ${vname} as constant iteration variable`);
self.variables[vname].forceconstant = true;
}
}
//was there something happening to the (return)variables?
if (expr['oper'] === '=') { //assignment to variable
let vname = expr['args'][0]['name'];
vname = bindings[vname] || vname;
self.initvariable(vname, true);
variables[vname].assigments.push(expr['args'][1]);
} else if (expr['oper'] && getPlainName(expr['oper']) === 'regional' && scope != 'global') {
for (let i in expr['args']) {
let vname = expr['args'][i]['name'];
let iname = generateUniqueHelperString();
bindings[vname] = iname;
if (!myfunctions[scope].variables) myfunctions[scope].variables = [];
myfunctions[scope].variables.push(iname);
self.initvariable(iname, false);
}
} else if (expr['oper'] === "forall$2" || expr['oper'] === "apply$2" || expr['oper'] === "forall$3" || expr['oper'] === "apply$3") {
let it = (expr['args'].length === 2) ? expr['args'][1].bindings['#'] : expr['args'][2].bindings[expr['args'][1]['name']];
variables[it].assigments.push({ //add function that accesses first element of array for type detection
"ctype": "infix",
"oper": "_",
"args": [expr['args'][0], {
"ctype": "number",
"value": {
"real": 1,
"imag": 0
}
}],
bindings: expr['args'][0].bindings
});
} else if (expr['ctype'] === 'function' && myfunctions.hasOwnProperty(expr['oper'])) { // call of user defined function
let rfun = expr['oper'];
let pname = rfun.replace('$', '_'); //remove $
self.initvariable(pname, false);
bindings[rfun] = pname;
let localbindungs = {};
for (let i in myfunctions[rfun]['arglist']) {
let localname = myfunctions[rfun]['arglist'][i]['name'];
let a = pname + '_' + localname;
localbindungs[localname] = a;
self.initvariable(a, false);
variables[a].assigments.push(expr['args'][i]);
}
if (!myfunctions[rfun].visited) {
myfunctions[rfun].visited = true;
rec(myfunctions[rfun]['body'], localbindungs, rfun, forceconstant);
//the return variable of the function should be added as well
variables[pname].assigments.push(myfunctions[rfun]['body']); //the expression will be evalueted in scope of rfun
}
}
}
};
/**
* Computes the types of all occuring this.variables and user defined functions. These types are choosen such that the lca of all this.assigments
*/
CodeBuilder.prototype.determineTypes = function() {
let changed = true;
for (let v in this.variables) {
this.variables[v].T = this.variables[v].T || false; //false corresponds no type yet
if (this.variables[v].forceconstant) {
this.variables[v].T = constint(1);
this.typetime++;
}
}
while (changed) { //TODO: implement queue to make this faster
changed = false;
for (let v in this.variables)
if (!this.variables[v].forceconstant) {
for (let i in this.variables[v].assigments) {
let e = this.variables[v].assigments[i];
let othertype = generalize(this.getType(e)); //type of expression e in function f
let oldtype = this.variables[v].T || false;
let newtype = oldtype;
if (othertype) {
if (!oldtype) newtype = othertype;
else {
if (issubtypeof(othertype, oldtype)) newtype = oldtype; //dont change anything
else newtype = lca(oldtype, othertype);
}
if (newtype && newtype !== oldtype) {
this.variables[v].T = newtype;
//console.log(`variable ${v} got type ${typeToString(newtype)} (oltype/othertype is ${typeToString(oldtype)}/${typeToString(othertype)})`);
this.typetime++;
changed = true;
}
}
}
}
}
};
/**
* computes the dict this.uniforms
* and sets .uniformvariable
* for all terms that have no child dependent on # or any variable dependent on #
*/
CodeBuilder.prototype.determineUniforms = function(expr) {
let variables = this.variables;
let myfunctions = this.myfunctions;
var variableDependendsOnPixel = {
'cgl_pixel': true
}; //dict of this.variables being dependent on #
//KISS-Fix: every variable appearing on left side of assigment is varying
for (let v in variables)
if (variables[v].assigments.length >= 1 || variables[v].iterationvariable)
variableDependendsOnPixel[v] = true;
//run expression to get all expr["dependsOnPixel"]
dependsOnPixel(expr);
let visitedFunctions = {
'': true
};
let uniforms = this.uniforms;
computeUniforms(expr, false);
function dependsOnPixel(expr) {
//Have we already found out that expr depends on pixel?
if (expr.hasOwnProperty("dependsOnPixel")) {
return expr["dependsOnPixel"];
}
//Is expr a variable that depends on pixel? (according the current variableDependendsOnPixel)
if (expr['ctype'] === 'variable') {
let vname = expr['name'];
vname = expr.bindings[vname] || vname;
if (variableDependendsOnPixel[vname]) {
return expr["dependsOnPixel"] = true;
}
return expr["dependsOnPixel"] = false;
}
let alwaysPixelDependent = [ //Operators that are supposed to be interpreted as pixel dependent;
'random', //our random function is dependent on pixel!
'verbatimglsl' //we dont analyse verbatimglsl functions
];
if (expr['ctype'] === 'function' && alwaysPixelDependent.indexOf(getPlainName(expr['oper'])) != -1) {
return expr["dependsOnPixel"] = true;
}
//repeat is pixel dependent iff it's code is pixel dependent. Then it also makes the running variable pixel dependent.
if (expr['oper'] === "repeat$2" || expr['oper'] === "forall$2" || expr['oper'] === "apply$2") {
if (dependsOnPixel(expr['args'][1])) {
variableDependendsOnPixel[expr['args'][1].bindings['#']] = true;
return expr["dependsOnPixel"] = true;
} else return expr["dependsOnPixel"] = false;
} else if (expr['oper'] === "repeat$3" || expr['oper'] === "forall$3" || expr['oper'] === "apply$3") {
if (dependsOnPixel(expr['args'][2])) {
variableDependendsOnPixel[expr['args'][2].bindings[expr['args'][1]['name']]] = true;
expr['args'][1]["dependsOnPixel"] = true;
return expr["dependsOnPixel"] = true;
} else return expr["dependsOnPixel"] = false;
}
//run recursion on all dependent arguments
for (let i in expr['args']) {
if (dependsOnPixel(expr['args'][i])) {
return expr["dependsOnPixel"] = true;
}
}
//Oh yes, it also might be a user-defined function!
if (expr['ctype'] === 'function' && myfunctions.hasOwnProperty(expr['oper'])) {
let rfun = expr['oper'];
if (dependsOnPixel(myfunctions[rfun].body)) {
return expr["dependsOnPixel"] = true;
}
}
//p.x
if (expr['ctype'] === 'field') {
return expr["dependsOnPixel"] = dependsOnPixel(expr['obj']);
}
return expr["dependsOnPixel"] = false;
}
//now find use those elements in expression trees that have no expr["dependsOnPixel"] and as high as possible having that property
function computeUniforms(expr, forceconstant) {
if (dependsOnPixel(expr)) {
//then run recursively on all childs
for (let i in expr['args']) {
let needtobeconstant = forceconstant || (expr['oper'] === "repeat$2" && i == 0) || (expr['oper'] === "repeat$3" && i == 0) || (expr['oper'] === "_" && i == 1);
computeUniforms(expr['args'][i], needtobeconstant);
}
if (expr['ctype'] === 'field') {
computeUniforms(expr['obj'], forceconstant);
}
//Oh yes, it also might be a user-defined function!
if (expr['ctype'] === 'function' && myfunctions.hasOwnProperty(expr['oper'])) {
let rfun = expr['oper'];
if (!visitedFunctions.hasOwnProperty(rfun)) { //only do this once per function
visitedFunctions[rfun] = true;
computeUniforms(myfunctions[rfun].body, forceconstant);
}
}
} else {
//assert that parent node was dependent on pixel
//we found a highest child that is not dependent -> this will be a candidate for a uniform!
//To pass constant numbers as uniforms is overkill
//TODO better: if it does not contain variables or functions
if (expr['ctype'] === 'number') return;
//nothing to pass
if (expr['ctype'] === 'void') return;
if (expr['oper'] === '..') forceconstant = true; //if this would vary, then also its length, ergo its type. Hence we can assume that it is constant :-)
//check whether uniform with same expression has already been generated. Note this causes O(n^2) running time :/ One might use a hashmap if it becomes relevant
let found = false;
let uname;
for (let otheruname in uniforms)
if (!found) {
if (expressionsAreEqual(expr, uniforms[otheruname].expr)) {
found = true;
uname = otheruname;
}
}
if (!found) {
uname = generateUniqueHelperString();
uniforms[uname] = {
expr: expr,
type: false,
forceconstant: forceconstant
};
}
expr["isuniform"] = true;
expr["uvariable"] = uname;
}
}
};
CodeBuilder.prototype.determineUniformTypes = function() {
for (let uname in this.uniforms) {
let tval = this.api.evaluateAndVal(this.uniforms[uname].expr);
this.uniforms[uname].type = this.uniforms[uname].forceconstant ? constant(tval) : guessTypeOfValue(tval);
//console.log(`guessed type ${typeToString(this.uniforms[uname].type)} for ${(this.uniforms[uname].expr['name']) || (this.uniforms[uname].expr['oper'])}`);
}
};
/**
* examines recursively all code generates myfunctions, which is cloned from results from api.getMyfunction(...)
*/
CodeBuilder.prototype.copyRequiredFunctions = function(expr) {
if (expr['ctype'] === 'function' && !this.myfunctions.hasOwnProperty(expr['oper']) && this.api.getMyfunction(expr['oper']) !== null) { //copy and transverse recursively all occuring myfunctions
let fun = expr['oper'];
this.myfunctions[fun] = cloneExpression(this.api.getMyfunction(fun));
this.copyRequiredFunctions(this.myfunctions[fun].body);
}
for (let i in expr['args']) {
this.copyRequiredFunctions(expr['args'][i]);
}
}
CodeBuilder.prototype.precompile = function(expr, bindings) {
this.copyRequiredFunctions(expr);
this.determineVariables(expr, bindings);
this.determineUniforms(expr);
this.determineUniformTypes();
this.determineTypes();
for (let u in this.uniforms)
if (this.uniforms[u].type.type === 'list') createstruct(this.uniforms[u].type, this);
for (let v in this.variables)
if (this.variables[v].T.type === 'list') createstruct(this.variables[v].T, this);
};
/**
* compiles an CindyJS-expression to GLSL-Code
* generateTerm = true <-> returns a term that corresponds to value of expression, precode might be generated
* @returns: {code: string of precode that has evaluated before it is possible to evalue expr
* [if generateTerm then also with the additional keys] term: expression in webgl, type: type of expression }
*/
CodeBuilder.prototype.compile = function(expr, generateTerm) {
var self = this; //for some reason recursion on this does not work, hence we create a copy; see http://stackoverflow.com/questions/18994712/recursive-call-within-prototype-function
let ctype = this.getType(expr);
if (expr['isuniform']) {
let uname = expr['uvariable'];
let uniforms = this.uniforms;
return generateTerm ? {
code: '',
term: ctype.type === 'constant' ? pastevalue(ctype.value, generalize(ctype)) : uname,
} : {
code: ''
};
} else if (expr['oper'] === ";") {
let r = {
term: ''
}; //default return value
let code = '';
let lastindex = expr['args'].length - 1;
for (let i = lastindex; i >= 0; i--) {
if (expr['args'][i]['ctype'] === 'void') lastindex = i - 1; //take last non-void entry
}
for (let i = 0; i <= lastindex; i++) {
r = this.compile(expr['args'][i], generateTerm && (i === lastindex)); //last one is responsible to generate term if required
code += r.code;
}
return generateTerm ? {
code: code,
term: r.term,
} : {
code: code
};
}
if (ctype.type === 'constant') {
return generateTerm ? {
term: pastevalue(ctype.value, generalize(ctype)),
code: ''
} : {
code: ''
};
} else if (expr['oper'] === "=") {
let r = this.compile(expr['args'][1], true);
let varexpr = this.compile(expr['args'][0], true).term; //note: this migth be also a field access
let t = `${varexpr} = ${this.castType(r.term, this.getType(expr['args'][1]), this.getType(expr['args'][0]))}`;
if (generateTerm) {
return {
code: r.code,
term: t,
};
} else {
return {
code: `${r.code + t};\n`
}
}
} else if (expr['oper'] === "repeat$2" || expr['oper'] === "repeat$3") {
let number = this.compile(expr['args'][0], true);
let ntype = this.getType(expr['args'][0]);
if (ntype.type !== 'constant') {
console.error('repeat possible only for fixed constant number in GLSL');
return false;
}
let it = (expr['oper'] === "repeat$2") ? expr['args'][1].bindings['#'] : expr['args'][2].bindings[expr['args'][1]['name']];
let n = Number(number.term);
let code = '';
if (this.variables[it].T.type === 'constant') {
for (let k = 1; k <= n; k++) { //unroll
this.variables[it].T = constint(k); //overwrites binding
this.typetime++;
let r = this.compile(expr['args'][(expr['oper'] === "repeat$2") ? 1 : 2], (k === n) && generateTerm);
code += r.code;
if ((k === n) && generateTerm) {
return {
code: code,
term: r.term,
};
}
}
} else { //non constant running variable
let ansvar = '';
let r = this.compile(expr['args'][(expr['oper'] === "repeat$2") ? 1 : 2], generateTerm);
let rtype = this.getType(expr['args'][(expr['oper'] === "repeat$2") ? 1 : 2]);
if (generateTerm) {
ansvar = generateUniqueHelperString();
if (!this.variables[ansvar]) {
this.initvariable(ansvar, true);
this.variables[ansvar].T = rtype;
}
}
code += `for(int ${it}=1; ${it} <= ${n}; ${it}++) {\n`;
code += r.code;
if (generateTerm) {
code += `${ansvar} = ${r.term};\n`;
}
code += '}\n';
if (generateTerm) {
return {
code: code,
term: ansvar,
};
}
}
//generateTerm == false
return ({
code: code
});
} else if (expr['oper'] === "forall$2" || expr['oper'] === "forall$3" || expr['oper'] === "apply$2" || expr['oper'] === "apply$3") {
let arraytype = this.getType(expr['args'][0]);
if (!(arraytype.type === 'list' || (arraytype.type === 'constant' && arraytype.value['ctype'] === 'list'))) {
console.error(`${expr['oper']} only possible for lists`);
return false;
}
let n = arraytype.length || arraytype.value["value"].length;
let r;
let it = (expr['args'].length === 2) ? expr['args'][1].bindings['#'] : expr['args'][2].bindings[expr['args'][1]['name']];
let ittype = this.variables[it].T;
let code = '';
let ans = '';
if (generateTerm) {
ans = generateUniqueHelperString();
code += `${webgltype(ctype)} ${ans};\n`;
}
if (ctype.type === 'list') createstruct(ctype, this);
if (this.variables[it].T.type === 'constant' || arraytype.type === 'constant') {
let arrayval = this.api.evaluateAndVal(expr['args'][0]);
for (let i = 0; i < n; i++) {
this.variables[it].T = constant(arrayval['value'][i]); //overwrites binding
this.typetime++;
//console.log(`current binding: ${it} -> ${typeToString(this.variables[it].T)}`);
r = this.compile(expr['args'][(expr['args'].length === 2) ? 1 : 2], generateTerm);
code += r.code;
if (expr['oper'] === "forall$2" || expr['oper'] === "forall$3") {
if ((i + 1 === n) && generateTerm) {
code += `${ans} = ${r.term};\n`;
}
} else { //apply
if (generateTerm) {
code += `${accesslist(ctype, i)([ans], [], this)} = ${r.term};\n`;
}
}
}
} else { //assume that array is non-constant
r = this.compile(expr['args'][(expr['args'].length === 2) ? 1 : 2], generateTerm);
let array = this.compile(expr['args'][0], true);
code += array.code;
let sterm = array.term;
//evaluate array.term to new variable sterm if it is complicated and it used at least twice
if (!this.variables[sterm] && !this.uniforms[sterm] && arraytype.length >= 2) {
sterm = generateUniqueHelperString();
code += `${webgltype(arraytype)} ${sterm} = ${array.term};\n`;
}
this.variables[it]['global'] = true;
//unroll forall/apply because dynamic access of arrays would require branching
for (let i = 0; i < n; i++) {
code += `${it} = ${accesslist(arraytype, i)([sterm], [], this)};\n`
code += r.code;
if (generateTerm) {
if (expr['oper'] === "forall$2" || expr['oper'] === "forall$3") {
if (i === n - 1) {
code += `${ans} = ${r.term};\n`;
}
} else code += `${accesslist(ctype, i)([ans], [], this)} = ${r.term};\n`;
}
}
if (ittype.type === 'list') createstruct(ittype, this);
}
return (generateTerm ? {
code: code,
term: ans,
} : {
code: code
});
} else if (expr['oper'] === "if$2" || expr['oper'] === "if$3") {
let cond = this.compile(expr['args'][0], true);
let condt = this.getType(expr['args'][0]);
let code = '';
let ansvar = '';
let ifbranch = this.compile(expr['args'][1], generateTerm);
if (generateTerm) {
ansvar = generateUniqueHelperString();
if (!this.variables[ansvar]) {
this.initvariable(ansvar, true);
this.variables[ansvar].T = ctype;
}
}
if (condt.type != 'constant') {
code += cond.code;
code += `if(${cond.term}) {\n`;
}
if (condt.type != 'constant' || (condt.type == 'constant' && condt.value["value"])) {
code += ifbranch.code;
if (generateTerm) {
code += `${ansvar} = ${this.castType(ifbranch.term, this.getType(expr['args'][1]), ctype)};\n`;
}
}
if (expr['oper'] === "if$3") {
let elsebranch = this.compile(expr['args'][2], generateTerm);
if (condt.type != 'constant')
code += '} else {\n';
if (condt.type != 'constant' || (condt.type == 'constant' && !condt.value["value"])) {
code += elsebranch.code;
if (generateTerm) {
code += `${ansvar} = ${this.castType(elsebranch.term, this.getType(expr['args'][2]), ctype)};\n`;
}
}
}
if (condt.type != 'constant')
code += '}\n';
return (generateTerm ? {
code: code,
term: ansvar,
} : {
code: code
});
} else if (expr['ctype'] === "function" || expr['ctype'] === "infix") {
let fname = expr['oper'];
if (getPlainName(fname) === 'verbatimglsl') {
let glsl = this.api.evaluateAndVal(expr['args'][0]).value;
return (generateTerm ? {
term: glsl,
code: ''
} : {
code: glsl
});
}
let r = expr['args'].map(e => self.compile(e, true)); //recursion on all arguments
let termGenerator;
let currenttype = expr['args'].map(e => self.getType(e)); //recursion on all arguments
let targettype;
if (this.myfunctions.hasOwnProperty(fname)) { //user defined function
termGenerator = this.usemyfunction(fname);
targettype = new Array(r.length)
for (let i = 0; i < r.length; i++) {
targettype[i] = this.variables[this.myfunctions[fname].body.bindings[this.myfunctions[fname]['arglist'][i]['name']]].T;
}
} else { //cindyscript-function
fname = getPlainName(fname);
if (fname === 'regional')
return (generateTerm ? {
term: '',
code: ''
} : {
code: ''
});
let implementation = webgl[fname](currenttype);
if (!implementation) {
console.error(`Could not find an implementation for ${fname}(${currenttype.map(typeToString).join(', ')}).\nReturning empty code`);
return (generateTerm ? {
term: '',
code: ''
} : {
code: ''
});
}
targettype = implementation.args;
termGenerator = implementation.generator;
}
let code = '';
let argterms = new Array(r.length);
for (let i = 0; i < r.length; i++) {
code += r[i].code;
argterms[i] = this.castType(r[i].term, currenttype[i], targettype[i]);
}
//console.log("Running Term Generator with arguments" + JSON.stringify(argterms) + " and this: " + JSON.stringify(this));
let term = termGenerator(argterms, expr['modifs'], this);
//console.log("generated the following term:" + term);
if (generateTerm)
return {
term: term,
code: code
};
else
return {
code: `${code + term};\n`
};
} else if (expr['ctype'] === "variable") {
let term = expr['name'];
term = expr.bindings[term] || term;
return (generateTerm ? {
term: term,
code: ''
} : {
code: `${term};\n`
});
} else if (expr['ctype'] === "void") {
return (generateTerm ? {
term: '',
code: ''
} : {
code: ''
});
} else if (expr['ctype'] === 'field') {
let index = {
'x': 0,
'y': 1,
'z': 2,
'r': 0,
'g': 1,
'b': 2,
'a': 3
}[expr['key']];
if (index != undefined) {
let term = accesslist(this.getType(expr['obj']), index)([self.compile(expr['obj'], true).term], null, this);
return (generateTerm ? {
term: term,
code: ''
} : {
code: `${term};\n`
});
}
}
console.error(`dont know how to this.compile ${JSON.stringify(expr)}`);
};
CodeBuilder.prototype.usemyfunction = function(fname) {
this.compileFunction(fname, this.myfunctions[fname]['arglist'].length);
return usefunction(fname.replace('$', '_'));
};
CodeBuilder.prototype.compileFunction = function(fname, nargs) {
var self = this;
if (this.mark('compiledfunctions', fname)) return; //visited
let m = this.myfunctions[fname];
let pname = fname.replace('$', '_'); //remove $
let bindings = m.body.bindings;
let vars = new Array(nargs);
for (let i = 0; i < nargs; i++) {
vars[i] = m['arglist'][i]['name'];
}
let isvoid = (this.variables[pname].T === type.voidt);
let code = `${webgltype(this.variables[pname].T)} ${pname}(${vars.map(varname => webgltype(self.variables[bindings[varname]].T) + ' ' + bindings[varname]).join(', ')}){\n`;
for (let i in m.variables) {
let iname = m.variables[i];
code += `${webgltype(this.variables[iname].T)} ${iname};\n`;
}
let r = self.compile(m.body, !isvoid);
let rtype = self.getType(m.body);
code += r.code;
if (!isvoid)
code += `return ${this.castType(r.term, rtype, this.variables[pname].T)};\n`; //TODO REPL
code += '}\n';
this.add('compiledfunctions', fname, () => code);
};
CodeBuilder.prototype.generateListOfUniforms = function() {
let ans = [];
for (let uname in this.uniforms)
if (this.uniforms[uname].type.type != 'constant' && this.uniforms[uname].type != type.image)
ans.push(`uniform ${webgltype(this.uniforms[uname].type)} ${uname};`);
return ans.join('\n');
};
CodeBuilder.prototype.generateColorPlotProgram = function(expr) { //TODO add arguments for #
helpercnt = 0;
expr = cloneExpression(expr); //then we can write dirty things on expr...
this.initvariable('cgl_pixel', false);
this.variables['cgl_pixel'].T = type.vec2;
let bindings = {
'#': 'cgl_pixel'
}
this.precompile(expr, bindings); //determine this.variables, types etc.
let r = this.compile(expr, true);
let rtype = this.getType(expr);
let colorterm = this.castType(r.term, rtype, type.color);
if (!issubtypeof(rtype, type.color)) {
console.error("expression does not generate a color");
}
let code = this.generateSection('structs');
code += this.generateSection('uniforms');
code += this.generateListOfUniforms();
code += generateHeaderOfTextureReaders(this);
code += this.generateSection('includedfunctions');
code += this.generateSection('functions');
for (let iname in this.variables)
if (this.variables[iname].T && this.variables[iname]['global']) {
code += `${webgltype(this.variables[iname].T)} ${iname};\n`;
}
code += this.generateSection('compiledfunctions');
code += `void main(void) {\n${r.code}gl_FragColor = ${colorterm};\n}\n`;
console.log(code);
let generations = {};
if (this.sections['compiledfunctions'])
for (let fname in this.sections['compiledfunctions'].marked) {
generations[fname] = this.api.getMyfunction(fname).generation;
}
return {
code: code,
uniforms: this.uniforms,
texturereaders: this.texturereaders,
generations: generations //all used functions with their generation
};
};
| 39.190234 | 197 | 0.536834 |
5e23d11165a723ee28a2a2f29a296afcbbe51725 | 1,235 | js | JavaScript | third_party/blink/web_tests/http/tests/devtools/elements/elements-panel-structure.js | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | third_party/blink/web_tests/http/tests/devtools/elements/elements-panel-structure.js | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | third_party/blink/web_tests/http/tests/devtools/elements/elements-panel-structure.js | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2021-01-05T23:43:46.000Z | 2021-01-07T23:36:34.000Z | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
(async function() {
TestRunner.addResult(`Tests that elements panel shows DOM tree structure.\n`);
await TestRunner.loadModule('elements_test_runner');
await TestRunner.showPanel('elements');
await TestRunner.loadHTML(`
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<div id="level1">
<div id="level2">"Quoted Text". Special characters: ><"'     ​‌‍‎‏ ‪‫‬‭‮­<div id="level3"></div>
</div>
</div>
<div id="control-character"></div>
`);
await TestRunner.evaluateInPagePromise(`
document.querySelector("#control-character").textContent = "\ufeff\u0093";
`);
// Warm up highlighter module.
runtime.loadModulePromise('source_frame').then(function() {
ElementsTestRunner.expandElementsTree(step1);
});
function step1() {
ElementsTestRunner.dumpElementsTree();
TestRunner.completeTest();
}
})();
| 39.83871 | 240 | 0.676113 |
5e248b3d44eb02e39a03c982af7aec664cf2159c | 1,911 | js | JavaScript | documents/libraryFineSolution.js | TraiLynne/blog | 46d8a661ef924c1f154c02de2ca961a3c50c08e1 | [
"MIT"
] | null | null | null | documents/libraryFineSolution.js | TraiLynne/blog | 46d8a661ef924c1f154c02de2ca961a3c50c08e1 | [
"MIT"
] | 2 | 2021-05-10T14:43:46.000Z | 2021-09-01T22:47:21.000Z | documents/libraryFineSolution.js | TraiLynne/blog | 46d8a661ef924c1f154c02de2ca961a3c50c08e1 | [
"MIT"
] | null | null | null | // variables
const onTime = 'on time';
const dailyFee = 'daily';
const monthlyFee = 'monthly';
const fixedFee = 'fixed';
let feesToApply = [onTime, 0];
let isItLate = (d1, m1, y1, d2, m2, y2) => {
return y1< y2 ?
false
: (y1 > y2) ?
true
: (y1 == y2) && (m1 > m2) ?
true
: (m1 == m2) && (d1 > d2) ?
true
: false
}
let determineFee = (d1, m1, y1, d2, m2, y2) => {
y1 > y2 ?
feesToApply = [fixedFee, 0]
: m1 > m2 ?
feesToApply = [monthlyFee, (m1 - m2)]
: d1 > d2 ?
feesToApply = [dailyFee, (d1 - d2)]
: feesToApply = 'is this right?'
}
let applyFee = feeArray => {
switch(feeArray[0]) {
case dailyFee:
return 15 * feeArray[1];
case monthlyFee:
return 500 * feeArray[1];
case fixedFee:
return 10000;
default:
return 0;
}
}
function libraryFineOriginal(d1, m1, y1, d2, m2, y2) {
isItLate(d1, m1, y1, d2, m2, y2) ?
determineFee(d1, m1, y1, d2, m2, y2)
: feesToApply[0] = onTime;
return applyFee(feesToApply);
}
// Complete the libraryFine function below.
function libraryFine(d1, m1, y1, d2, m2, y2) {
return y1 < y2 ?
0
: y1 > y2 ?
10000
: (y1 == y2) && (m1 > m2) ?
500 * (m1 - m2)
: (y1 == y2) && (m1 == m2) && (d1 > d2) ?
15 * (d1 - d2)
: 0
// === *** OR *** === //
// if (y1 < y2){
// return 0;
// } else if (y1 > y2) {
// return 10000
// } else if ((y1 == y2) && (m1 > m2)){
// return 500 * (m1 - m2);
// } else if ((y1 == y2) && (m1 == m2) && (d1 > d2)){
// return 15 * (d1 - d2)
// } else {
// return 0
// }
} | 24.5 | 57 | 0.413919 |
5e24c55d797eabdaadb251101b90192dfcdfd036 | 151 | js | JavaScript | ch2/filesystem/watcher.js | karstengresch/learn-n8trw | bf654f95c59ce0d16f1a61445e753167dcbb2296 | [
"Unlicense"
] | null | null | null | ch2/filesystem/watcher.js | karstengresch/learn-n8trw | bf654f95c59ce0d16f1a61445e753167dcbb2296 | [
"Unlicense"
] | null | null | null | ch2/filesystem/watcher.js | karstengresch/learn-n8trw | bf654f95c59ce0d16f1a61445e753167dcbb2296 | [
"Unlicense"
] | null | null | null | 'use strict';
const fs = require('fs');
fs.watch('target.txt', () => console.log('File changed!'));
console.log("Watching target.txt for changes...");
| 30.2 | 59 | 0.655629 |
5e2506c0975d4285f7284132ca550ec60396c628 | 246 | js | JavaScript | src/api/expenseDefinitions.js | PatyCu/sheriff | 9cf3a98b739e0fd73b8d5e4a899818a0ae800a29 | [
"MIT"
] | 1 | 2018-03-02T17:15:41.000Z | 2018-03-02T17:15:41.000Z | src/api/expenseDefinitions.js | PatyCu/sheriff | 9cf3a98b739e0fd73b8d5e4a899818a0ae800a29 | [
"MIT"
] | null | null | null | src/api/expenseDefinitions.js | PatyCu/sheriff | 9cf3a98b739e0fd73b8d5e4a899818a0ae800a29 | [
"MIT"
] | null | null | null | export const EXPENSE_TITLES = {
TICKETS: "tickets",
HOTEL: "hotel",
TRANSPORTATION: "transportation",
LUNCH: "lunch",
DRINKS: "drinks",
GAZ: "gaz"
};
export const CURRENCIES = {
EUR: "€",
USD: "$",
GBP: "£"
}; | 17.571429 | 37 | 0.54878 |
5e258f5d4714826c6eedcbb375615f92e47d0055 | 532 | js | JavaScript | src-es5/app.js | suhasmshetty/es6-on-production-master | 7db0f66b9c9f59732dd7740100de3bf4dcf4a354 | [
"MIT"
] | null | null | null | src-es5/app.js | suhasmshetty/es6-on-production-master | 7db0f66b9c9f59732dd7740100de3bf4dcf4a354 | [
"MIT"
] | null | null | null | src-es5/app.js | suhasmshetty/es6-on-production-master | 7db0f66b9c9f59732dd7740100de3bf4dcf4a354 | [
"MIT"
] | null | null | null | var Controller = require('./controller');
var helpers = require('./helpers');
var $on = helpers.$on;
var Template = require('./template');
var Store = require('./store');
var View = require('./view');
var store = new Store('todos-vanilla-es6');
var template = new Template();
var view = new View(template);
/**
* @type {Controller}
*/
var controller = new Controller(store, view);
function setView() {
return controller.setView(document.location.hash);
};
$on(window, 'load', setView);
$on(window, 'hashchange', setView);
| 21.28 | 52 | 0.672932 |
5e25d60460d5a93eee696a31d970d06bcc651f0f | 450 | js | JavaScript | AFunctions.js | panzer/Javascript-NeuralNet | 0b9a74714892d802d70acf95964a584b7b04a9bc | [
"MIT"
] | 1 | 2017-05-30T14:56:47.000Z | 2017-05-30T14:56:47.000Z | AFunctions.js | panzer/Javascript-NeuralNet | 0b9a74714892d802d70acf95964a584b7b04a9bc | [
"MIT"
] | 2 | 2017-05-30T18:23:18.000Z | 2017-05-30T18:24:42.000Z | AFunctions.js | panzer/Javascript-NeuralNet | 0b9a74714892d802d70acf95964a584b7b04a9bc | [
"MIT"
] | null | null | null |
var identity = function(x) {
return x;
}
var binary = function(x) {
if (x < 0) {
return 0;
} else {
return 1;
}
}
var sigmoid = function(x) {
return 1 / (1 + pow(Math.E, -x));
}
var arctan = function(x) {
atan(x);
}
var relu = function(x) {
if (x < 0) {
return 0;
} else {
return x;
}
}
var softSine = function(x) {
return x / (1 + abs(x));
}
var guassian = function(x) {
return pow(Math.E, pow(-x, 2))
}
| 12.162162 | 35 | 0.522222 |
5e26511dbd8f0f322f86bf1a1e63ef89b510328c | 1,720 | js | JavaScript | js/script.js | dmswl208/test | 567a5b2ee5538bdeb86abcd3c40fbcf921484a1c | [
"MIT"
] | null | null | null | js/script.js | dmswl208/test | 567a5b2ee5538bdeb86abcd3c40fbcf921484a1c | [
"MIT"
] | null | null | null | js/script.js | dmswl208/test | 567a5b2ee5538bdeb86abcd3c40fbcf921484a1c | [
"MIT"
] | null | null | null | $(document).ready(function(){
var w01 = 0;
var w02 = 0;
var w03 = 0;
view01();
$('.right_btn').click(function(){
if(w01==1){
view02();
}
else if (w02==1){
view03();
}
else if (w03==1){
view01();
}
});
setInterval(tri, 4000);
function tri(){
$('.right_btn').trigger('click');
}
$('.left_btn').click(function(){
if(w01==1){
view03();
}
else if (w02==1){
view01();
}
else if(w03==1){
view02();
}
});
$('.bottom_btn li').click(function(){
var idx = $(this).index();
if(idx==0){
view01();
}
else if(idx==1){
view02();
}
else if(idx==2){
view03();
}
});
function view01(){
w01 = 1;
w02 = 0;
w03 = 0;
$('.sl_wrap ul li').fadeOut(0);
$('.sl_01').fadeIn(600);
$('.bottom_btn li a').css('background-color','#fff');
$('.bottom_btn li:nth-child(1) a').css('background-color','red');
}
function view02(){
w01 = 0;
w02 = 1;
w03 = 0;
$('.sl_wrap ul li').fadeOut(0);
$('.sl_02').fadeIn(600);
$('.bottom_btn li a').css('background-color','#fff');
$('.bottom_btn li:nth-child(2) a').css('background-color','red');
}
function view03(){
w01 = 0;
w02 = 0;
w03 = 1;
$('.sl_wrap ul li').fadeOut(0);
$('.sl_03').fadeIn(600);
$('.bottom_btn li a').css('background-color','#fff');
$('.bottom_btn li:nth-child(3) a').css('background-color','red');
}
});
| 17.916667 | 72 | 0.419186 |
5e26b7600d30032b0f391e0ea7d2f5ba0231d63c | 71 | js | JavaScript | public/js/admin/vinculacion/seguimiento/surveys/create.js | oscarortegag/sistema_estadias | 630fe8df3db799f246b4f1e0d170edee5e869b88 | [
"MIT"
] | null | null | null | public/js/admin/vinculacion/seguimiento/surveys/create.js | oscarortegag/sistema_estadias | 630fe8df3db799f246b4f1e0d170edee5e869b88 | [
"MIT"
] | null | null | null | public/js/admin/vinculacion/seguimiento/surveys/create.js | oscarortegag/sistema_estadias | 630fe8df3db799f246b4f1e0d170edee5e869b88 | [
"MIT"
] | null | null | null | $(document).ready(function() {
CKEDITOR.replace('description')
});
| 17.75 | 35 | 0.661972 |
5e26df6e22ea615f7b79460192c1f6f49e30c364 | 1,804 | js | JavaScript | src/components/buttons/Font.js | HsuTing/drawing-pad | 9123ea5304415899a97910f70ac15e27c75b1d25 | [
"MIT"
] | null | null | null | src/components/buttons/Font.js | HsuTing/drawing-pad | 9123ea5304415899a97910f70ac15e27c75b1d25 | [
"MIT"
] | 1 | 2017-07-18T06:48:57.000Z | 2017-07-18T18:41:40.000Z | src/components/buttons/Font.js | HsuTing/drawing-pad | 9123ea5304415899a97910f70ac15e27c75b1d25 | [
"MIT"
] | null | null | null | 'use strict';
import React from 'react';
import PropTypes from 'prop-types';
import radium from 'radium';
import AddIcon from 'react-icons/lib/md/add';
import SubIcon from 'react-icons/lib/md/remove';
import Input from 'cat-components/lib/input';
import * as style from './style/font';
@radium
export default class Font extends React.Component {
static propTypes = {
ctx: PropTypes.object,
style: PropTypes.object.isRequired
}
constructor(props) {
super(props);
this.state = {
fontSize: '1'
};
this.onChange = this.onChange.bind(this);
this.add = this.count('add').bind(this);
this.sub = this.count('sub').bind(this);
}
componentDidUpdate() {
const {ctx} = this.props;
const {fontSize} = this.state;
ctx.lineWidth = fontSize;
}
render() {
const {fontSize} = this.state;
return (
<div style={[this.props.style, style.root]}>
<SubIcon style={style.icon('sub')}
onClick={this.sub}
/>
<Input style={style.input}
value={fontSize}
onChange={this.onChange}
rules={[{
validator: 'isInt',
not: true,
message: 'Is not int',
options: {
min: 1
}
}]}
maxLength={2}
/>
<AddIcon style={style.icon('add')}
onClick={this.add}
/>
</div>
);
}
onChange({value, error, isError}) {
if(isError && value !== '')
return;
this.setState({fontSize: value});
}
count(type) {
return () => {
const {fontSize} = this.state;
const newFontSize = fontSize * 1 + (type === 'add' ? 1 : -1);
if(newFontSize < 100 && newFontSize > 0)
this.setState({fontSize: newFontSize.toString()});
}
}
}
| 21.73494 | 67 | 0.554324 |
5e26fd788cd9a524d05641eb33e0c80cd7fe2554 | 51 | js | JavaScript | study-notes/subjects/js/02-JavaScript作用域和函数/02_作用域的面试题/05_作用域补充.js | coderZsq/coderZsq.practice.web | 53b554c42300556ae9bcc686087707c55b0181ae | [
"MIT"
] | 5 | 2018-08-07T03:42:07.000Z | 2021-04-13T19:38:51.000Z | study-notes/subjects/js/02-JavaScript作用域和函数/02_作用域的面试题/05_作用域补充.js | coderZsq/coderZsq.practice.web | 53b554c42300556ae9bcc686087707c55b0181ae | [
"MIT"
] | 38 | 2019-07-20T13:14:53.000Z | 2022-02-13T16:25:50.000Z | study-notes/subjects/js/02-JavaScript作用域和函数/02_作用域的面试题/05_作用域补充.js | coderZsq/coderZsq.practice.web | 53b554c42300556ae9bcc686087707c55b0181ae | [
"MIT"
] | null | null | null | function foo() {
m = 100
}
foo()
console.log(m)
| 7.285714 | 16 | 0.568627 |
5e27b14d87eda78894a25716246ec19390a85d37 | 564 | js | JavaScript | dev/Lec22/FirstFiles.js | heyprasoon/pep_Level1 | 7f1d2691b628aeec10b600e2f802d9b7dc3ce9cf | [
"Apache-2.0"
] | null | null | null | dev/Lec22/FirstFiles.js | heyprasoon/pep_Level1 | 7f1d2691b628aeec10b600e2f802d9b7dc3ce9cf | [
"Apache-2.0"
] | null | null | null | dev/Lec22/FirstFiles.js | heyprasoon/pep_Level1 | 7f1d2691b628aeec10b600e2f802d9b7dc3ce9cf | [
"Apache-2.0"
] | null | null | null | // read a file, capitlize every word, write the file
let minimist = require("minimist");
let args = minimist(process.argv);
// node FirstFiles.js --source=f1.txt --dest=f2.txt
// args.source (f1.txt) and args.dest (f2.txt)
let fs = require("fs");
let stext = fs.readFileSync(args.source, "utf-8");
let words = stext.split(" "); // string has split
for(let i = 0; i < words.length; i++){
words[i] = words[i].toUpperCase();
}
let dtext = words.join(" "); // array has join
console.log(dtext);
//fs.writeFileSync(args.dest, dtext, "utf-8");
| 29.684211 | 53 | 0.638298 |
5e289991c457f64248409f344880b6c41d4e7ce6 | 3,513 | js | JavaScript | node_modules/ssim.js/dist/index.js | jimi006/jimi006.github.io | fd4e01540a34add04e8e1c5e41603b7470c0e2cf | [
"MIT"
] | null | null | null | node_modules/ssim.js/dist/index.js | jimi006/jimi006.github.io | fd4e01540a34add04e8e1c5e41603b7470c0e2cf | [
"MIT"
] | null | null | null | node_modules/ssim.js/dist/index.js | jimi006/jimi006.github.io | fd4e01540a34add04e8e1c5e41603b7470c0e2cf | [
"MIT"
] | null | null | null | "use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ssim = exports.getOptions = void 0;
/**
* SSIM External API
*
* @module main
*/
var matlab_1 = require("./matlab");
var math_1 = require("./math");
var ssim_1 = require("./ssim");
var originalSsim_1 = require("./originalSsim");
var bezkrovnySsim_1 = require("./bezkrovnySsim");
var downsample_1 = require("./downsample");
var defaults_1 = require("./defaults");
var weberSsim_1 = require("./weberSsim");
var ssimTargets = {
fast: ssim_1.ssim,
original: originalSsim_1.originalSsim,
bezkrovny: bezkrovnySsim_1.bezkrovnySsim,
weber: weberSsim_1.weberSsim,
};
function validateOptions(options) {
Object.keys(options).forEach(function (option) {
if (!(option in defaults_1.defaults)) {
throw new Error("\"" + option + "\" is not a valid option");
}
});
if ('k1' in options && (typeof options.k1 !== 'number' || options.k1 < 0)) {
throw new Error("Invalid k1 value. Default is " + defaults_1.defaults.k1);
}
if ('k2' in options && (typeof options.k2 !== 'number' || options.k2 < 0)) {
throw new Error("Invalid k2 value. Default is " + defaults_1.defaults.k2);
}
if (!(options.ssim in ssimTargets)) {
throw new Error("Invalid ssim option (use: " + Object.keys(ssimTargets).join(', ') + ")");
}
}
function getOptions(userOptions) {
var options = __assign(__assign({}, defaults_1.defaults), userOptions);
validateOptions(options);
return options;
}
exports.getOptions = getOptions;
function validateDimensions(_a) {
var pixels1 = _a[0], pixels2 = _a[1], options = _a[2];
if (pixels1.width !== pixels2.width || pixels1.height !== pixels2.height) {
throw new Error('Image dimensions do not match');
}
return [pixels1, pixels2, options];
}
function toGrayScale(_a) {
var pixels1 = _a[0], pixels2 = _a[1], options = _a[2];
return [matlab_1.rgb2gray(pixels1), matlab_1.rgb2gray(pixels2), options];
}
function toResize(_a) {
var pixels1 = _a[0], pixels2 = _a[1], options = _a[2];
var pixels = downsample_1.downsample([pixels1, pixels2], options);
return [pixels[0], pixels[1], options];
}
function comparison(_a) {
var pixels1 = _a[0], pixels2 = _a[1], options = _a[2];
return ssimTargets[options.ssim](pixels1, pixels2, options);
}
/**
* @method ssim - The ssim method. You can call the package directly or through the `ssim` property.
* @public
* @example import mod = from 'ssim.js';
* mod(imgBuffer1, imgBuffer2);
* mod.ssim(imgBuffer1, imgBuffer2);
*/
function ssim(image1, image2, userOptions) {
var start = new Date().getTime();
var options = getOptions(userOptions);
var ssimMap = comparison(toResize(toGrayScale(validateDimensions([image1, image2, options]))));
var mssim = ssimMap.mssim !== undefined
? ssimMap.mssim
: math_1.mean2d(ssimMap);
return {
mssim: mssim,
ssim_map: ssimMap,
performance: new Date().getTime() - start,
};
}
exports.ssim = ssim;
exports.default = ssim;
//# sourceMappingURL=index.js.map | 35.846939 | 100 | 0.63877 |
5e28fee01a2dd4a6621e06f90493f85b43ad7d66 | 988 | js | JavaScript | WebAppBuilderForArcGIS/client/stemapp/widgets/ReviewerDashboard/setting/nls/pt-br/strings.js | vgauri1797/Eclipse | d342fe9e7e68718ae736c2b9a1e88c84ad50dfcf | [
"Apache-2.0"
] | null | null | null | WebAppBuilderForArcGIS/client/stemapp/widgets/ReviewerDashboard/setting/nls/pt-br/strings.js | vgauri1797/Eclipse | d342fe9e7e68718ae736c2b9a1e88c84ad50dfcf | [
"Apache-2.0"
] | null | null | null | WebAppBuilderForArcGIS/client/stemapp/widgets/ReviewerDashboard/setting/nls/pt-br/strings.js | vgauri1797/Eclipse | d342fe9e7e68718ae736c2b9a1e88c84ad50dfcf | [
"Apache-2.0"
] | null | null | null | define({
"drsSOEURL": "URL de Servidor do Revisor de Dados",
"chartSection": "Número de Partes/Barras no gráfico",
"selectByGeography": "Incluir filtro por geografia",
"selectUrl": "Camada de serviço para filtrar por geografia",
"selectMapUrl": "Serviço para filtrar por geografia",
"geometryServiceURL": "URL do Serviço de Geometria",
"includeFieldNames": "Selecionar Campos",
"fieldNames": "Nomes de Campo",
"lifecyclePhaseFieldName": "LIFECYCLEPHASE",
"setSource": "Configurar",
"defaultFieldName": "severidade",
"warning": "Entrada incorreta",
"includeDefaultFieldName": "O nome de campo padrão deve ser selecionado",
"selectFieldWarning": "Pelo menos um campo deve ser visível",
"defaultFieldNotVisible": "O campo padrão deve ser visível",
"batchJobCheckGroup": "batchjobcheckgroup",
"defaultColumn": "Padrão",
"visibleColumn": "Visível",
"fieldNameColumn": "Nome de Campo do Painel",
"aliasColumn": "Nome Alternativo"
}); | 44.909091 | 76 | 0.715587 |
5e29080bae6c95c1e7091d4b2f81f2281f81751f | 1,471 | js | JavaScript | src/Orchard.Web/Modules/Acai.NewsStatistics/Scripts/Acai.NewsStatistics.List.js | charles0525/orchard | 53f5c838fc538743dd5103c4a55b3a4ca09303e6 | [
"BSD-3-Clause"
] | 1 | 2019-01-16T06:06:50.000Z | 2019-01-16T06:06:50.000Z | src/Orchard.Web/Modules/Acai.NewsStatistics/Scripts/Acai.NewsStatistics.List.js | charles0525/orchard | 53f5c838fc538743dd5103c4a55b3a4ca09303e6 | [
"BSD-3-Clause"
] | null | null | null | src/Orchard.Web/Modules/Acai.NewsStatistics/Scripts/Acai.NewsStatistics.List.js | charles0525/orchard | 53f5c838fc538743dd5103c4a55b3a4ca09303e6 | [
"BSD-3-Clause"
] | null | null | null | var exportExcel={
init:function(){
$(function(){
$('.export-btn').on('click',exportExcel.createExportFile);
});
},
createExportFile:function(layerId){
if(!layerId){
layerId='news-layer';
}
var params ={__RequestVerificationToken:$('[name="__RequestVerificationToken"]').val()};
$.ajax({
type: "post",
dataType: "json",
data: params,
url: '/Acai.NewsStatistics/Admin/ExportPost',
success: function (data) {
var json = data;
if (json != null && json.status==1) {
if (!!json.msg) {
exportExcel.downloadFile(layerId, json.msg);
}
}
else {
alert(json.msg);
}
},
beforeSend: function (XHR) {
},
complete: function (XHR, TS) {
}
});
},
downloadFile:function(layerId, file){
var iframe = document.getElementById(layerId + "_iframe");
if (iframe != undefined && iframe != null) {
document.body.removeChild(iframe);
}
iframe = document.createElement("iframe");
iframe.id = layerId + "_iframe";
iframe.src = file;
iframe.style.display = "none";
document.body.appendChild(iframe);
}
}
exportExcel.init(); | 30.645833 | 96 | 0.470428 |
5e294bcb854fa0ae98f549ffd4e24bb10e279075 | 1,023 | js | JavaScript | src/jvContacts.Web.React/ClientApp/src/styles/Workspace.js | j-valenzuela/contacts-react-net | b0f22d5061b3365a180de02a54cb9830a3857b03 | [
"MIT"
] | 1 | 2020-10-06T03:54:38.000Z | 2020-10-06T03:54:38.000Z | src/jvContacts.Web.React/ClientApp/src/styles/Workspace.js | j-valenzuela/contacts-react-net | b0f22d5061b3365a180de02a54cb9830a3857b03 | [
"MIT"
] | 5 | 2020-09-04T21:54:40.000Z | 2022-02-17T23:06:08.000Z | src/jvContacts.Web.React/ClientApp/src/styles/Workspace.js | j-valenzuela/contacts-react-net | b0f22d5061b3365a180de02a54cb9830a3857b03 | [
"MIT"
] | 2 | 2020-11-01T03:59:05.000Z | 2021-07-07T16:34:40.000Z | import { drawerWidth } from './variables';
const WorkspaceStyles = theme => ({
content: {
backgroundColor: theme.palette.background.default,
minWidth: 0,
width: '100%',
position: 'relative',
display: 'block',
[theme.breakpoints.up('sm')]: {
overflowY: 'auto',
overflowX: 'hidden',
},
transition: theme.transitions.create('margin', {
easing: theme.transitions.easing.sharp,
duration: theme.transitions.duration.leavingScreen,
}),
'-webkit-overflow-scrolling': 'touch',
},
'content-left': {
[theme.breakpoints.up('md')]: {
marginLeft: -drawerWidth,
},
},
'content-right': {
marginRight: -drawerWidth,
},
contentShift: {
transition: theme.transitions.create('margin', {
easing: theme.transitions.easing.easeOut,
duration: theme.transitions.duration.enteringScreen,
}),
},
'contentShift-left': {
marginLeft: 0,
},
'contentShift-right': {
marginRight: 0,
}
});
export default WorkspaceStyles; | 24.357143 | 58 | 0.629521 |
5e29ab91692302708ef4b527d5ee30d90760753b | 1,852 | js | JavaScript | src/env.js | jacksongraves/tradovate-autotrader | 51d3511a41367be6c39d55ace7d7aea9fff9baf7 | [
"MIT"
] | null | null | null | src/env.js | jacksongraves/tradovate-autotrader | 51d3511a41367be6c39d55ace7d7aea9fff9baf7 | [
"MIT"
] | null | null | null | src/env.js | jacksongraves/tradovate-autotrader | 51d3511a41367be6c39d55ace7d7aea9fff9baf7 | [
"MIT"
] | null | null | null | // env.js
// NOTE: These are REQUIRED for the safe operation of your strategy
module.exports = {
// MARKET DATA AND TRADING ------------------------------------------------------
// Which contract to trade
// ESU1
// symbol: 2173694,
// MESU1
symbol: 2155088,
// Warmup prevents submitting an order until the system has had time to process the first few fields / arrays, etc (milliseconds)
warmup: 10e3,
// Morning Time: Inject into the `productSession` for reference
morningTime: { hour: 8, minute: 30 },
// Allowable Trading Hours: Must supply both fields if using them
minAllowedTradingTime: { hour: 8, minute: 0 }, // 0900
maxAllowedTradingTime: { hour: 14, minute: 0 }, // 1500
// Overtrading Half Life: How many intervals we want to give to prevent ourselves from overtrading? (integer)
overtradingHalfLife: 5,
// Maxmium number of lots ot allow
maxPosition: 1,
// Decision interval: How often we allow the system to make decisions to modify orders (milliseconds)
decisionInterval: 10e3,
// Max index (integer) that we can store in memory (e.g., for fixed-width bars)
maxIndex: 1000,
// Max time (in milliseconds) to store in memory
maxMilliseconds: 600e3,
// Minimum time (in milliseconds) to enforce delay between API requests
minMilliseconds: 1e3,
// Element size for tick or bar subscriptions, e.g., 1-tick or 1-volume
elementSize: 1,
// Number of elements to retrieve initially and hold in memory for the market data subscriptions
asMuchAsElements: 10000,
// Subscribe to quotes
getQuotes: true,
// Subscribe to Histogram updates
getHistograms: true,
// Subscribe to DOM updates
getDOMs: true,
// Subscribe to a volume chart for order flow
getVolumes: true,
// Subscribe to a bar chart (default in minute bars)
getBars: true,
// Subscribe to a tick chart
getTicks: false
} | 28.060606 | 130 | 0.705724 |
5e2a11c3cbc9be84672700f794d9bb4c43b245f5 | 643 | js | JavaScript | src/jsutils/defineInspect.js | HED-ddresser/graphql-js | 8bed6b504a83632be47377a2ea742db0d0c2d349 | [
"MIT"
] | null | null | null | src/jsutils/defineInspect.js | HED-ddresser/graphql-js | 8bed6b504a83632be47377a2ea742db0d0c2d349 | [
"MIT"
] | null | null | null | src/jsutils/defineInspect.js | HED-ddresser/graphql-js | 8bed6b504a83632be47377a2ea742db0d0c2d349 | [
"MIT"
] | null | null | null | // @flow strict
import invariant from './invariant';
import nodejsCustomInspectSymbol from './nodejsCustomInspectSymbol';
/**
* The `defineInspect()` function defines `inspect()` prototype method as alias of `toJSON`
*/
export default function defineInspect(
classObject: Class<any> | ((...args: Array<any>) => mixed),
): void {
const fn = classObject.prototype.toJSON;
invariant(typeof fn === 'function');
classObject.prototype.inspect = fn;
/* istanbul ignore else (See: https://github.com/graphql/graphql-js/issues/2317) */
if (nodejsCustomInspectSymbol) {
classObject.prototype[nodejsCustomInspectSymbol] = fn;
}
}
| 29.227273 | 91 | 0.718507 |
5e2b0907963301d344efe1646b16911dd080bb72 | 629 | js | JavaScript | node_modules/github-scraper/lib/scrapers.js | LukasSchikirianski/LukasSchikirianski.github.io | 489bad0116d6903b53a6c81daeb076e2aaec56bb | [
"MIT"
] | 3 | 2020-08-18T20:48:53.000Z | 2021-06-22T18:16:55.000Z | node_modules/github-scraper/lib/scrapers.js | LukasSchikirianski/LukasSchikirianski.github.io | 489bad0116d6903b53a6c81daeb076e2aaec56bb | [
"MIT"
] | null | null | null | node_modules/github-scraper/lib/scrapers.js | LukasSchikirianski/LukasSchikirianski.github.io | 489bad0116d6903b53a6c81daeb076e2aaec56bb | [
"MIT"
] | 2 | 2020-11-15T18:12:19.000Z | 2021-06-22T15:30:00.000Z | module.exports = {
// feed: require('./feed'), // activity feed (RSS)
followers: require('./followers'), // also scrapes following or stargazers
// issue: require('./issue'),
// issues: require('./issues'),
// issues_search: require('./issues_search'),
// labels : require('./labels'),
// milestones : require('./milestones'),
org: require('./org'),
people: require('./people'),
profile: require('./profile'),
repo: require('./repo'),
// repos: require('./repos'),
repos_user: require('./repos_user'),
// starred: require('./starred')
stars_watchers: require('./stars_watchers')
}
| 34.944444 | 80 | 0.608903 |
5e2b2b1df6dc89234ae34ba9e985a0e2e0cdb76d | 669 | js | JavaScript | public/sketches/6-4-2015_9-58-16/scripts/main.js | abberg/athousandmore.com | e4b7ef1c0331699128d8dce293f4fbbc890d9b4f | [
"MIT"
] | null | null | null | public/sketches/6-4-2015_9-58-16/scripts/main.js | abberg/athousandmore.com | e4b7ef1c0331699128d8dce293f4fbbc890d9b4f | [
"MIT"
] | null | null | null | public/sketches/6-4-2015_9-58-16/scripts/main.js | abberg/athousandmore.com | e4b7ef1c0331699128d8dce293f4fbbc890d9b4f | [
"MIT"
] | null | null | null | (function(){
"use strict";
var loop = ab.gameLoop(),
three = ab.threeBase(),
sketch = ab.sketch(three);
loop.addEventListener('framestart', function(event){
var timestamp = event.detail.timestamp;
sketch.framestart(timestamp);
})
loop.addEventListener('frameupdate', function(event){
var timestep = event.detail.timestep;
sketch.update(timestep);
})
loop.addEventListener('framedraw', function(event){
var interpolation = event.detail.interpolation;
sketch.draw(interpolation);
three.renderer().render(three.scene(), three.camera());
});
sketch.init();
loop.start();
if(ab.controlBar){
ab.controlBar(loop, three);
}
}()) | 17.605263 | 57 | 0.690583 |
5e2b79d255ec2d1e1e85c5ed612dbcd6add60d06 | 5,599 | js | JavaScript | views/EmployeeDetails.js | IT20206932/WonderLankaTours | a470aeb6891f54686576650d31247f1fe400abee | [
"MIT"
] | 1 | 2021-11-23T09:05:46.000Z | 2021-11-23T09:05:46.000Z | views/EmployeeDetails.js | IT20206932/WonderLankaTours | a470aeb6891f54686576650d31247f1fe400abee | [
"MIT"
] | null | null | null | views/EmployeeDetails.js | IT20206932/WonderLankaTours | a470aeb6891f54686576650d31247f1fe400abee | [
"MIT"
] | null | null | null | import driverStyles from "../assets/css/EmployeeDetails.module.css";
import{Button} from 'reactstrap'
import{ useHistory } from "react-router-dom"
import { useState } from 'react';
import { useEffect } from 'react';
import IndexHeader from 'components/Headers/IndexHeader';
import IndexNavbar from 'components/Navbars/IndexNavbar';
import DemoFooter from 'components/Footers/DemoFooter';
import axios from 'axios';
import { toast } from 'react-toastify';
import "react-toastify/dist/ReactToastify.css";
import {
Label,
Input,
Row,
Col,
InputGroup,
InputGroupAddon,
InputGroupText,
FormGroup,
Alert,
Container,
} from "reactstrap";
toast.configure();
function EmployeeDetails(){
let history = useHistory();
const [employees , setEmployees] = useState([]);
const [message , setMessage] = useState("");
const [searchVal , setSearchVal] = useState("");
useEffect(() => {
axios.get("http://localhost:8070/employees/details").then((res) =>{
setEmployees(res.data);
console.log(res.data);
}).catch((err) =>{
console.log(err);
})
}, []);
function onDelete(employee) {
if (
window.confirm(
"Employee " + employee.employeeid + " will be removed from the database"
)
)
axios.delete(`http://localhost:8070/employees/delete${employee._id}`).then((res) =>{
console.log(res);
toast.success('Employee Deleted!', {
position: "bottom-right",
autoClose: 5000,
hideProgressBar: false,
});
}).catch((err) =>{
console.log(err);
alert("Error!");
})
}
var number = 1;
return(
<div>
<IndexNavbar />
<IndexHeader />
<Container>
<center><h1>Employee Details</h1><br/><br/></center>
<Row>
<Col>
<FormGroup>
<InputGroup style = {{marginLeft : "70px"}} className="form-group-no-border">
<InputGroupAddon addonType="prepend">
<InputGroupText>
<i className="nc-icon nc-zoom-split" />
</InputGroupText>
</InputGroupAddon>
<Input placeholder="Search " type="text"
onChange = {(e) =>{
setSearchVal(e.target.value);
}}/>
</InputGroup>
</FormGroup>
</Col>
</Row>
<center>
<table width ="90%" border ="2px"className = {driverStyles.tbldata}>
<tr>
<th className={driverStyles.tbldata}>Employee User Name</th>
<th className={driverStyles.tbldata}>Employee Password</th>
<th className={driverStyles.tbldata}>Employee Role</th>
<th className={driverStyles.tbldata}>Actions</th>
</tr>
<tbody>
{employees.filter((val) =>{
if(searchVal === ''){
return val;
}
else if (val.empname.toLowerCase().includes(searchVal.toLowerCase())){
return val;
}
}).map((employee) =>(
<tr className={driverStyles.tbldata}>
<td className={driverStyles.tbldata}>{employee.empname}</td>
<td className={driverStyles.tbldata}>{employee.emppwd}</td>
<td className={driverStyles.tbldata}>{employee.emprole}</td>
<td className={driverStyles.tbldata}>
<button
className={driverStyles.btnEdit}
onClick = {()=>{
history.push(`/edit-employee/${employee._id}`);
}}
>Edit</button>
<button className={driverStyles.btnDelete}
onClick = {() =>{
onDelete(employee);
}}
>Delete</button>
</td>
</tr>
))}
</tbody>
</table>
</center>
<span style = {{textAlign:"left" , color : "red"}}>{message}</span> <br/><br/>
</Container>
</div>
);
}
export default EmployeeDetails;
| 31.455056 | 97 | 0.392749 |
5e2b8802f660edb080932f27cfb77fe48fb5a3ce | 27,024 | js | JavaScript | webapps/phpproject/phpMyAdmin/js/normalization.js | Duck-ComEn/TE_WebApplication | 7de0bfb55adc94813d43cd0f320819ac20f8a1e2 | [
"Apache-2.0"
] | null | null | null | webapps/phpproject/phpMyAdmin/js/normalization.js | Duck-ComEn/TE_WebApplication | 7de0bfb55adc94813d43cd0f320819ac20f8a1e2 | [
"Apache-2.0"
] | null | null | null | webapps/phpproject/phpMyAdmin/js/normalization.js | Duck-ComEn/TE_WebApplication | 7de0bfb55adc94813d43cd0f320819ac20f8a1e2 | [
"Apache-2.0"
] | null | null | null | /* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* @fileoverview events handling from normalization page
* @name normalization
*
* @requires jQuery
*/
/**
* AJAX scripts for normalization.php
*
*/
var normalizeto = '1nf';
var primary_key;
var data_parsed = null;
function appendHtmlColumnsList()
{
$.get(
"normalization.php",
{
"token": PMA_commonParams.get('token'),
"ajax_request": true,
"db": PMA_commonParams.get('db'),
"table": PMA_commonParams.get('table'),
"getColumns": true
},
function(data) {
if (data.success === true) {
$('select[name=makeAtomic]').html(data.message);
}
}
);
}
function goTo3NFStep1(newTables)
{
if (Object.keys(newTables).length === 1) {
newTables = [PMA_commonParams.get('table')];
}
$.post(
"normalization.php",
{
"token": PMA_commonParams.get('token'),
"ajax_request": true,
"db": PMA_commonParams.get('db'),
"tables": newTables,
"step": '3.1'
}, function(data) {
$("#page_content").find("h3").html(PMA_messages.str3NFNormalization);
$("#mainContent").find("legend").html(data.legendText);
$("#mainContent").find("h4").html(data.headText);
$("#mainContent").find("p").html(data.subText);
$("#mainContent").find("#extra").html(data.extra);
$("#extra").find("form").each(function() {
var form_id = $(this).attr('id');
var colname = $(this).data('colname');
$("#" + form_id + " input[value='" + colname + "']").next().remove();
$("#" + form_id + " input[value='" + colname + "']").remove();
});
$("#mainContent").find("#newCols").html('');
$('.tblFooters').html('');
if (data.subText !== "") {
$('.tblFooters').html('<input type="button" onClick="processDependencies(\'\', true);" value="' + PMA_messages.strDone + '"/>');
}
}
);
}
function goTo2NFStep1() {
$.post(
"normalization.php",
{
"token": PMA_commonParams.get('token'),
"ajax_request": true,
"db": PMA_commonParams.get('db'),
"table": PMA_commonParams.get('table'),
"step": '2.1'
}, function(data) {
$("#page_content h3").html(PMA_messages.str2NFNormalization);
$("#mainContent legend").html(data.legendText);
$("#mainContent h4").html(data.headText);
$("#mainContent p").html(data.subText);
$("#mainContent #extra").html(data.extra);
$("#mainContent #newCols").html('');
if (data.subText !== '') {
$('.tblFooters').html('<input type="submit" value="' + PMA_messages.strDone + '" onclick="processDependencies(\'' + escapeJsString(escapeHtml(data.primary_key)) + '\');">');
} else {
if (normalizeto === '3nf') {
$("#mainContent #newCols").html(PMA_messages.strToNextStep);
setTimeout(function() {
goTo3NFStep1([PMA_commonParams.get('table')]);
}, 3000);
}
}
});
}
function goToFinish1NF()
{
if (normalizeto !== '1nf') {
goTo2NFStep1();
return true;
}
$("#mainContent legend").html(PMA_messages.strEndStep);
$("#mainContent h4").html(
"<h3>" + PMA_sprintf(PMA_messages.strFinishMsg, escapeHtml(PMA_commonParams.get('table'))) + "</h3>"
);
$("#mainContent p").html('');
$("#mainContent #extra").html('');
$("#mainContent #newCols").html('');
$('.tblFooters').html('');
}
function goToStep4()
{
$.post(
"normalization.php",
{
"token": PMA_commonParams.get('token'),
"ajax_request": true,
"db": PMA_commonParams.get('db'),
"table": PMA_commonParams.get('table'),
"step4": true
}, function(data) {
$("#mainContent legend").html(data.legendText);
$("#mainContent h4").html(data.headText);
$("#mainContent p").html(data.subText);
$("#mainContent #extra").html(data.extra);
$("#mainContent #newCols").html('');
$('.tblFooters').html('');
for(var pk in primary_key) {
$("#extra input[value='" + escapeJsString(primary_key[pk]) + "']").attr("disabled","disabled");
}
}
);
}
function goToStep3()
{
$.post(
"normalization.php",
{
"token": PMA_commonParams.get('token'),
"ajax_request": true,
"db": PMA_commonParams.get('db'),
"table": PMA_commonParams.get('table'),
"step3": true
}, function(data) {
$("#mainContent legend").html(data.legendText);
$("#mainContent h4").html(data.headText);
$("#mainContent p").html(data.subText);
$("#mainContent #extra").html(data.extra);
$("#mainContent #newCols").html('');
$('.tblFooters').html('');
primary_key = $.parseJSON(data.primary_key);
for(var pk in primary_key) {
$("#extra input[value='" + escapeJsString(primary_key[pk]) + "']").attr("disabled","disabled");
}
}
);
}
function goToStep2(extra)
{
$.post(
"normalization.php",
{
"token": PMA_commonParams.get('token'),
"ajax_request": true,
"db": PMA_commonParams.get('db'),
"table": PMA_commonParams.get('table'),
"step2": true
}, function(data) {
$("#mainContent legend").html(data.legendText);
$("#mainContent h4").html(data.headText);
$("#mainContent p").html(data.subText);
$("#mainContent #extra,#mainContent #newCols").html('');
$('.tblFooters').html('');
if (data.hasPrimaryKey === "1") {
if(extra === 'goToStep3') {
$("#mainContent h4").html(PMA_messages.strPrimaryKeyAdded);
$("#mainContent p").html(PMA_messages.strToNextStep);
}
if(extra === 'goToFinish1NF') {
goToFinish1NF();
} else {
setTimeout(function() {
goToStep3();
}, 3000);
}
} else {
//form to select columns to make primary
$("#mainContent #extra").html(data.extra);
}
}
);
}
function goTo2NFFinish(pd)
{
var tables = {};
for (var dependson in pd) {
tables[dependson] = $('#extra input[name="' + dependson + '"]').val();
}
datastring = {"token": PMA_commonParams.get('token'),
"ajax_request": true,
"db": PMA_commonParams.get('db'),
"table": PMA_commonParams.get('table'),
"pd": JSON.stringify(pd),
"newTablesName":JSON.stringify(tables),
"createNewTables2NF":1};
$.ajax({
type: "GET",
url: "normalization.php",
data: datastring,
async:false,
success: function(data) {
if (data.success === true) {
if(data.queryError === false) {
if (normalizeto === '3nf') {
$("#pma_navigation_reload").click();
goTo3NFStep1(tables);
return true;
}
$("#mainContent legend").html(data.legendText);
$("#mainContent h4").html(data.headText);
$("#mainContent p").html('');
$("#mainContent #extra").html('');
$('.tblFooters').html('');
} else {
PMA_ajaxShowMessage(data.extra, false);
}
$("#pma_navigation_reload").click();
} else {
PMA_ajaxShowMessage(data.error, false);
}
}
});
}
function goTo3NFFinish(newTables)
{
for (var table in newTables) {
for (var newtbl in newTables[table]) {
var updatedname = $('#extra input[name="' + newtbl + '"]').val();
newTables[table][updatedname] = newTables[table][newtbl];
if (updatedname !== newtbl) {
delete newTables[table][newtbl];
}
}
}
datastring = {"token": PMA_commonParams.get('token'),
"ajax_request": true,
"db": PMA_commonParams.get('db'),
"newTables":JSON.stringify(newTables),
"createNewTables3NF":1};
$.ajax({
type: "GET",
url: "normalization.php",
data: datastring,
async:false,
success: function(data) {
if (data.success === true) {
if(data.queryError === false) {
$("#mainContent legend").html(data.legendText);
$("#mainContent h4").html(data.headText);
$("#mainContent p").html('');
$("#mainContent #extra").html('');
$('.tblFooters').html('');
} else {
PMA_ajaxShowMessage(data.extra, false);
}
$("#pma_navigation_reload").click();
} else {
PMA_ajaxShowMessage(data.error, false);
}
}
});
}
var backup = '';
function goTo2NFStep2(pd, primary_key)
{
$("#newCols").html('');
$("#mainContent legend").html(PMA_messages.strStep + ' 2.2 ' + PMA_messages.strConfirmPd);
$("#mainContent h4").html(PMA_messages.strSelectedPd);
$("#mainContent p").html(PMA_messages.strPdHintNote);
var extra = '<div class="dependencies_box">';
var pdFound = false;
for (var dependson in pd) {
if (dependson !== primary_key) {
pdFound = true;
extra += '<p class="displayblock desc">' + escapeHtml(dependson) + " -> " + escapeHtml(pd[dependson].toString()) + '</p>';
}
}
if(!pdFound) {
extra += '<p class="displayblock desc">' + PMA_messages.strNoPdSelected + '</p>';
extra += '</div>';
} else {
extra += '</div>';
datastring = {"token": PMA_commonParams.get('token'),
"ajax_request": true,
"db": PMA_commonParams.get('db'),
"table": PMA_commonParams.get('table'),
"pd": JSON.stringify(pd),
"getNewTables2NF":1};
$.ajax({
type: "GET",
url: "normalization.php",
data: datastring,
async:false,
success: function(data) {
if (data.success === true) {
extra += data.message;
} else {
PMA_ajaxShowMessage(data.error, false);
}
}
});
}
$("#mainContent #extra").html(extra);
$('.tblFooters').html('<input type="button" value="' + PMA_messages.strBack + '" id="backEditPd"/><input type="button" id="goTo2NFFinish" value="' + PMA_messages.strGo + '"/>');
$("#goTo2NFFinish").click(function(){
goTo2NFFinish(pd);
});
}
function goTo3NFStep2(pd, tablesTds)
{
$("#newCols").html('');
$("#mainContent legend").html(PMA_messages.strStep + ' 3.2 ' + PMA_messages.strConfirmTd);
$("#mainContent h4").html(PMA_messages.strSelectedTd);
$("#mainContent p").html(PMA_messages.strPdHintNote);
var extra = '<div class="dependencies_box">';
var pdFound = false;
for (var table in tablesTds) {
for (var i in tablesTds[table]) {
dependson = tablesTds[table][i];
if (dependson !== '' && dependson !== table) {
pdFound = true;
extra += '<p class="displayblock desc">' + escapeHtml(dependson) + " -> " + escapeHtml(pd[dependson].toString()) + '</p>';
}
}
}
if(!pdFound) {
extra += '<p class="displayblock desc">' + PMA_messages.strNoTdSelected + '</p>';
extra += '</div>';
} else {
extra += '</div>';
datastring = {"token": PMA_commonParams.get('token'),
"ajax_request": true,
"db": PMA_commonParams.get('db'),
"tables": JSON.stringify(tablesTds),
"pd": JSON.stringify(pd),
"getNewTables3NF":1};
$.ajax({
type: "GET",
url: "normalization.php",
data: datastring,
async:false,
success: function(data) {
data_parsed = $.parseJSON(data.message);
if (data.success === true) {
extra += data_parsed.html;
} else {
PMA_ajaxShowMessage(data.error, false);
}
}
});
}
$("#mainContent #extra").html(extra);
$('.tblFooters').html('<input type="button" value="' + PMA_messages.strBack + '" id="backEditPd"/><input type="button" id="goTo3NFFinish" value="' + PMA_messages.strGo + '"/>');
$("#goTo3NFFinish").click(function(){
if (!pdFound) {
goTo3NFFinish([]);
} else {
goTo3NFFinish(data_parsed.newTables);
}
});
}
function processDependencies(primary_key, isTransitive)
{
var pd = {};
var tablesTds = {};
var dependsOn;
pd[primary_key] = [];
$("#extra form").each(function() {
var tblname;
if (isTransitive === true) {
tblname = $(this).data('tablename');
primary_key = tblname;
if (!(tblname in tablesTds)) {
tablesTds[tblname] = [];
}
tablesTds[tblname].push(primary_key);
}
var form_id = $(this).attr('id');
$('#' + form_id + ' input[type=checkbox]:not(:checked)').removeAttr('checked');
dependsOn = '';
$('#' + form_id + ' input[type=checkbox]:checked').each(function(){
dependsOn += $(this).val() + ', ';
$(this).attr("checked","checked");
});
if (dependsOn === '') {
dependsOn = primary_key;
} else {
dependsOn = dependsOn.slice(0, -2);
}
if (! (dependsOn in pd)) {
pd[dependsOn] = [];
}
pd[dependsOn].push($(this).data('colname'));
if (isTransitive === true) {
if (!(tblname in tablesTds)) {
tablesTds[tblname] = [];
}
if ($.inArray(dependsOn, tablesTds[tblname]) === -1) {
tablesTds[tblname].push(dependsOn);
}
}
});
backup = $("#mainContent").html();
if (isTransitive === true) {
goTo3NFStep2(pd, tablesTds);
} else {
goTo2NFStep2(pd, primary_key);
}
return false;
}
function moveRepeatingGroup(repeatingCols) {
var newTable = $("input[name=repeatGroupTable]").val();
var newColumn = $("input[name=repeatGroupColumn]").val();
if (!newTable) {
$("input[name=repeatGroupTable]").focus();
return false;
}
if (!newColumn) {
$("input[name=repeatGroupColumn]").focus();
return false;
}
datastring = {"token": PMA_commonParams.get('token'),
"ajax_request": true,
"db": PMA_commonParams.get('db'),
"table": PMA_commonParams.get('table'),
"repeatingColumns": repeatingCols,
"newTable":newTable,
"newColumn":newColumn,
"primary_columns":primary_key.toString()
};
$.ajax({
type: "POST",
url: "normalization.php",
data: datastring,
async:false,
success: function(data) {
if (data.success === true) {
if(data.queryError === false) {
goToStep3();
}
PMA_ajaxShowMessage(data.message, false);
$("#pma_navigation_reload").click();
} else {
PMA_ajaxShowMessage(data.error, false);
}
}
});
}
AJAX.registerTeardown('normalization.js', function () {
$("#extra").off("click", "#selectNonAtomicCol");
$("#splitGo").unbind('click');
$('.tblFooters').off("click", "#saveSplit");
$("#extra").off("click", "#addNewPrimary");
$(".tblFooters").off("click", "#saveNewPrimary");
$("#extra").off("click", "#removeRedundant");
$("#mainContent p").off("click", "#createPrimaryKey");
$("#mainContent").off("click", "#backEditPd");
$("#mainContent").off("click", "#showPossiblePd");
$("#mainContent").off("click", ".pickPd");
});
AJAX.registerOnload('normalization.js', function() {
var selectedCol;
normalizeto = $("#mainContent").data('normalizeto');
$("#extra").on("click", "#selectNonAtomicCol", function() {
if ($(this).val() === 'no_such_col') {
goToStep2();
} else {
selectedCol = $(this).val();
}
});
$("#splitGo").click(function() {
if(!selectedCol || selectedCol === '') {
return false;
}
var numField = $("#numField").val();
$.get(
"normalization.php",
{
"token": PMA_commonParams.get('token'),
"ajax_request": true,
"db": PMA_commonParams.get('db'),
"table": PMA_commonParams.get('table'),
"splitColumn": true,
"numFields": numField
},
function(data) {
if (data.success === true) {
$('#newCols').html(data.message);
$('.default_value').hide();
$('.enum_notice').hide();
$('.tblFooters').html("<input type='submit' id='saveSplit' value='" + PMA_messages.strSave + "'/>" +
"<input type='submit' id='cancelSplit' value='" + PMA_messages.strCancel + "' " +
"onclick=\"$('#newCols').html('');$(this).parent().html('')\"/>");
}
}
);
return false;
});
$('.tblFooters').on("click","#saveSplit", function() {
central_column_list = [];
if ($("#newCols #field_0_1").val() === '') {
$("#newCols #field_0_1").focus();
return false;
}
datastring = $('#newCols :input').serialize();
datastring += "&ajax_request=1&do_save_data=1&field_where=last";
$.post("tbl_addfield.php", datastring, function(data) {
if (data.success) {
$.get(
"sql.php",
{
"token": PMA_commonParams.get('token'),
"ajax_request": true,
"db": PMA_commonParams.get('db'),
"table": PMA_commonParams.get('table'),
"dropped_column": selectedCol,
"purge" : 1,
"sql_query": 'ALTER TABLE `' + PMA_commonParams.get('table') + '` DROP `' + selectedCol + '`;',
"is_js_confirmed": 1
},
function(data) {
if (data.success === true) {
appendHtmlColumnsList();
$('#newCols').html('');
$('.tblFooters').html('');
} else {
PMA_ajaxShowMessage(data.error, false);
}
selectedCol = '';
}
);
} else {
PMA_ajaxShowMessage(data.error, false);
}
});
});
$("#extra").on("click", "#addNewPrimary", function() {
$.get(
"normalization.php",
{
"token": PMA_commonParams.get('token'),
"ajax_request": true,
"db": PMA_commonParams.get('db'),
"table": PMA_commonParams.get('table'),
"addNewPrimary": true
},
function(data) {
if (data.success === true) {
$('#newCols').html(data.message);
$('.default_value').hide();
$('.enum_notice').hide();
$('.tblFooters').html("<input type='submit' id='saveNewPrimary' value='" + PMA_messages.strSave + "'/>" +
"<input type='submit' id='cancelSplit' value='" + PMA_messages.strCancel + "' " +
"onclick=\"$('#newCols').html('');$(this).parent().html('')\"/>");
} else {
PMA_ajaxShowMessage(data.error, false);
}
}
);
return false;
});
$(".tblFooters").on("click", "#saveNewPrimary", function() {
var datastring = $('#newCols :input').serialize();
datastring += "&field_key[0]=primary_0&ajax_request=1&do_save_data=1&field_where=last";
$.post("tbl_addfield.php", datastring, function(data) {
if (data.success === true) {
$("#mainContent h4").html(PMA_messages.strPrimaryKeyAdded);
$("#mainContent p").html(PMA_messages.strToNextStep);
$("#mainContent #extra").html('');
$("#mainContent #newCols").html('');
$('.tblFooters').html('');
setTimeout(function() {
goToStep3();
}, 2000);
} else {
PMA_ajaxShowMessage(data.error, false);
}
});
});
$("#extra").on("click", "#removeRedundant", function() {
var dropQuery = 'ALTER TABLE `' + PMA_commonParams.get('table') + '` ';
$("#extra input[type=checkbox]:checked").each(function() {
dropQuery += 'DROP `' + $(this).val() + '`, ';
});
dropQuery = dropQuery.slice(0, -2);
$.get(
"sql.php",
{
"token": PMA_commonParams.get('token'),
"ajax_request": true,
"db": PMA_commonParams.get('db'),
"table": PMA_commonParams.get('table'),
"sql_query": dropQuery,
"is_js_confirmed": 1
},
function(data) {
if (data.success === true) {
goToStep2('goToFinish1NF');
} else {
PMA_ajaxShowMessage(data.error, false);
}
}
);
});
$("#extra").on("click", "#moveRepeatingGroup", function() {
var repeatingCols = '';
$("#extra input[type=checkbox]:checked").each(function() {
repeatingCols += $(this).val() + ', ';
});
if (repeatingCols !== '') {
var newColName = $("#extra input[type=checkbox]:checked:first").val();
repeatingCols = repeatingCols.slice(0, -2);
var confirmStr = PMA_sprintf(PMA_messages.strMoveRepeatingGroup, escapeHtml(repeatingCols), escapeHtml(PMA_commonParams.get('table')));
confirmStr += '<input type="text" name="repeatGroupTable" placeholder="' + PMA_messages.strNewTablePlaceholder + '"/>' +
'( ' + escapeHtml(primary_key.toString()) + ', <input type="text" name="repeatGroupColumn" placeholder="' + PMA_messages.strNewColumnPlaceholder + '" value="' + escapeHtml(newColName) + '">)' +
'</ol>';
$("#newCols").html(confirmStr);
$('.tblFooters').html('<input type="submit" value="' + PMA_messages.strCancel + '" onclick="$(\'#newCols\').html(\'\');$(\'#extra input[type=checkbox]\').removeAttr(\'checked\')"/>' +
'<input type="submit" value="' + PMA_messages.strGo + '" onclick="moveRepeatingGroup(\'' + escapeJsString(escapeHtml(repeatingCols)) + '\')"/>');
}
});
$("#mainContent p").on("click", "#createPrimaryKey", function(event) {
event.preventDefault();
var url = { create_index: 1,
server: PMA_commonParams.get('server'),
db: PMA_commonParams.get('db'),
table: PMA_commonParams.get('table'),
token: PMA_commonParams.get('token'),
added_fields: 1,
add_fields:1,
index: {Key_name:'PRIMARY'},
ajax_request: true
};
var title = PMA_messages.strAddPrimaryKey;
indexEditorDialog(url, title, function(){
//on success
$(".sqlqueryresults").remove();
$('.result_query').remove();
$('.tblFooters').html('');
goToStep2('goToStep3');
});
return false;
});
$("#mainContent").on("click", "#backEditPd", function(){
$("#mainContent").html(backup);
});
$("#mainContent").on("click", "#showPossiblePd", function(){
if($(this).hasClass('hideList')) {
$(this).html('+ ' + PMA_messages.strShowPossiblePd);
$(this).removeClass('hideList');
$("#newCols").slideToggle("slow");
return false;
}
if($("#newCols").html() !== '') {
$("#showPossiblePd").html('- ' + PMA_messages.strHidePd);
$("#showPossiblePd").addClass('hideList');
$("#newCols").slideToggle("slow");
return false;
}
$("#newCols").insertAfter("#mainContent h4");
$("#newCols").html('<div class="center">' + PMA_messages.strLoading + '<br/>' + PMA_messages.strWaitForPd + '</div>');
$.post(
"normalization.php",
{
"token": PMA_commonParams.get('token'),
"ajax_request": true,
"db": PMA_commonParams.get('db'),
"table": PMA_commonParams.get('table'),
"findPdl": true
}, function(data) {
$("#showPossiblePd").html('- ' + PMA_messages.strHidePd);
$("#showPossiblePd").addClass('hideList');
$("#newCols").html(data.message);
});
});
$("#mainContent").on("click", ".pickPd", function(){
var strColsLeft = $(this).next('.determinants').html();
var colsLeft = strColsLeft.split(',');
var strColsRight = $(this).next().next().html();
var colsRight = strColsRight.split(',');
for (var i in colsRight) {
$('form[data-colname="' + colsRight[i].trim() + '"] input[type="checkbox"]').prop('checked', false);
for (var j in colsLeft) {
$('form[data-colname="' + colsRight[i].trim() + '"] input[value="' + colsLeft[j].trim() + '"]').prop('checked', true);
}
}
});
});
| 38.008439 | 209 | 0.482941 |
5e2de93c50be42be242968180b5957b1ce957e02 | 11,769 | js | JavaScript | packages/zoe/src/zoeService/types.js | ctjlewis/agoric-sdk | 05e43706fad9988d2571971e46f98aba7ad2435c | [
"Apache-2.0"
] | null | null | null | packages/zoe/src/zoeService/types.js | ctjlewis/agoric-sdk | 05e43706fad9988d2571971e46f98aba7ad2435c | [
"Apache-2.0"
] | null | null | null | packages/zoe/src/zoeService/types.js | ctjlewis/agoric-sdk | 05e43706fad9988d2571971e46f98aba7ad2435c | [
"Apache-2.0"
] | null | null | null | // eslint-disable-next-line spaced-comment
/// <reference types="ses"/>
/**
* @typedef {Object} ZoeService
*
* Zoe provides a framework for deploying and working with smart
* contracts. It is accessed as a long-lived and well-trusted service
* that enforces offer safety for the contracts that use it. Zoe has a
* single `invitationIssuer` for the entirety of its lifetime. By
* having a reference to Zoe, a user can get the `invitationIssuer`
* and thus validate any `invitation` they receive from someone else.
*
* Zoe has two different facets: the public Zoe service and the
* contract facet (ZCF). Each contract instance has a copy of ZCF
* within its vat. The contract and ZCF never have direct access to
* the users' payments or the Zoe purses.
*
* @property {GetInvitationIssuer} getInvitationIssuer
*
* Zoe has a single `invitationIssuer` for the entirety of its
* lifetime. By having a reference to Zoe, a user can get the
* `invitationIssuer` and thus validate any `invitation` they receive
* from someone else. The mint associated with the invitationIssuer
* creates the ERTP payments that represent the right to interact with
* a smart contract in particular ways.
*
* @property {Install} install
* @property {StartInstance} startInstance
* @property {Offer} offer
* @property {GetPublicFacet} getPublicFacet
* @property {GetIssuers} getIssuers
* @property {GetBrands} getBrands
* @property {GetTerms} getTerms
* @property {GetInstallationForInstance} getInstallationForInstance
* @property {GetInstance} getInstance
* @property {GetInstallation} getInstallation
* @property {GetInvitationDetails} getInvitationDetails - return an
* object with the instance, installation, description, invitation
* handle, and any custom properties specific to the contract.
* @property {GetFeeIssuer} getFeeIssuer
* @property {MakeFeePurse} makeFeePurse
* @property {BindDefaultFeePurse} bindDefaultFeePurse
* @property {GetConfiguration} getConfiguration
*/
/**
* @callback GetInvitationIssuer
* @returns {Promise<Issuer>}
*/
/**
* @callback GetFeeIssuer
* @returns {Promise<Issuer>}
*/
/**
* @typedef {Purse} FeePurse
*/
/**
* @callback MakeFeePurseInternal
* @returns {FeePurse}
*/
/**
* @callback MakeFeePurse
* @returns {Promise<FeePurse>}
*/
/**
* @callback BindDefaultFeePurse
* @param {ERef<FeePurse>} defaultFeePurse
* @returns {ZoeService}
*/
/**
* @callback GetConfiguration
* @returns {{
* feeIssuerConfig: FeeIssuerConfig,
* zoeFeesConfig: ZoeFeesConfig,
* meteringConfig: MeteringConfig
* }}
*/
/**
* @callback GetPublicFacet
* @param {Instance} instance
* @param {ERef<FeePurse>=} feePurse
* @returns {Promise<Object>}
*/
/**
* @callback GetPublicFacetFeePurseRequired
* @param {Instance} instance
* @param {ERef<FeePurse>} feePurse
* @returns {Promise<Object>}
*/
/**
* @callback GetIssuers
* @param {Instance} instance
* @returns {Promise<IssuerKeywordRecord>}
*/
/**
* @callback GetBrands
* @param {Instance} instance
* @returns {Promise<BrandKeywordRecord>}
*/
/**
* @callback GetTerms
* @param {Instance} instance
* @returns {Promise<Terms>}
*/
/**
* @callback GetInstallationForInstance
* @param {Instance} instance
* @returns {Promise<Installation>}
*/
/**
* @callback GetInstance
* @param {ERef<Invitation>} invitation
* @returns {Promise<Instance>}
*/
/**
* @callback GetInstallation
* @param {ERef<Invitation>} invitation
* @returns {Promise<Installation>}
*/
/**
* @callback GetInvitationDetails
* @param {ERef<Invitation>} invitation
* @returns {Promise<InvitationDetails>}
*/
/**
* @callback Install
*
* Create an installation by safely evaluating the code and
* registering it with Zoe. Returns an installation.
*
* @param {SourceBundle} bundle
* @param {ERef<FeePurse>=} feePurse
* @returns {Promise<Installation>}
*/
/**
* @callback InstallFeePurseRequired
*
* See Install for comments.
*
* @param {SourceBundle} bundle
* @param {ERef<FeePurse>} feePurse
* @returns {Promise<Installation>}
*/
/**
* @callback StartInstance
*
* Zoe is long-lived. We can use Zoe to create smart contract
* instances by specifying a particular contract installation to use,
* as well as the `terms` of the contract. The `terms.issuers` is a
* record mapping string names (keywords) to issuers, such as `{
* Asset: simoleanIssuer}`. (Note that the keywords must begin with a
* capital letter and must be ASCII identifiers.) Parties to the
* contract will use the keywords to index their proposal and their
* payments.
*
* The custom terms are the arguments to the contract, such as the
* number of bids an auction will wait for before closing. Custom
* terms are up to the discretion of the smart contract. We get back
* the creator facet, public facet, and creator invitation as defined
* by the contract.
*
* @param {ERef<Installation>} installation
* @param {IssuerKeywordRecord=} issuerKeywordRecord
* @param {Object=} terms
* @param {Object=} privateArgs - an optional configuration object
* that can be used to pass in arguments that should not be in the
* public terms
* @param {ERef<FeePurse>=} feePurse
* @returns {Promise<StartInstanceResult>}
*/
/**
* @callback StartInstanceFeePurseRequired
*
* See StartInstance for comments.
*
* @param {ERef<Installation>} installation
* @param {IssuerKeywordRecord=} issuerKeywordRecord
* @param {Object=} terms
* @param {Object=} privateArgs
* @param {ERef<FeePurse>} feePurse
* @returns {Promise<StartInstanceResult>}
*/
/**
* @callback Offer
*
* To redeem an invitation, the user normally provides a proposal (their
* rules for the offer) as well as payments to be escrowed by Zoe. If
* either the proposal or payments would be empty, indicate this by
* omitting that argument or passing undefined, rather than passing an
* empty record.
*
* The proposal has three parts: `want` and `give` are used by Zoe to
* enforce offer safety, and `exit` is used to specify the particular
* payout-liveness policy that Zoe can guarantee. `want` and `give`
* are objects with keywords as keys and amounts as values.
* `paymentKeywordRecord` is a record with keywords as keys, and the
* values are the actual payments to be escrowed. A payment is
* expected for every rule under `give`.
*
* @param {ERef<Invitation>} invitation
* @param {Proposal=} proposal
* @param {PaymentPKeywordRecord=} paymentKeywordRecord
* @param {Object=} offerArgs
* @param {ERef<FeePurse>=} feePurse
* @returns {Promise<UserSeat>} seat
*/
/**
* @callback OfferFeePurseRequired
*
* See Offer for comments.
*
* @param {ERef<Invitation>} invitation
* @param {Proposal=} proposal
* @param {PaymentPKeywordRecord=} paymentKeywordRecord
* @param {Object=} offerArgs
* @param {ERef<FeePurse>} feePurse
* @returns {Promise<UserSeat>} seat
*/
/**
* @typedef {Object} UserSeat
* @property {() => Promise<Allocation>} getCurrentAllocation
* @property {() => Promise<ProposalRecord>} getProposal
* @property {() => Promise<PaymentPKeywordRecord>} getPayouts
* @property {(keyword: Keyword) => Promise<Payment>} getPayout
* @property {() => Promise<OfferResult>} getOfferResult
* @property {() => void=} tryExit
* @property {() => Promise<boolean>} hasExited
* @property {() => Promise<Notifier<Allocation>>} getNotifier
*/
/**
* @typedef {any} OfferResult
*/
/**
* @typedef {Object} AdminFacet
* @property {() => Promise<Completion>} getVatShutdownPromise
*/
/**
* @typedef {Object} StartInstanceResult
* @property {any} creatorFacet
* @property {any} publicFacet
* @property {Instance} instance
* @property {Payment | undefined} creatorInvitation
* @property {AdminFacet} adminFacet
*/
/**
* @typedef {Partial<ProposalRecord>} Proposal
*
* @typedef {{give: AmountKeywordRecord,
* want: AmountKeywordRecord,
* exit: ExitRule
* }} ProposalRecord
*/
/**
* @typedef {Record<Keyword,Amount>} AmountKeywordRecord
*
* The keys are keywords, and the values are amounts. For example:
* { Asset: AmountMath.make(5n, assetBrand), Price:
* AmountMath.make(9n, priceBrand) }
*/
/**
* @typedef {Object} Waker
* @property {() => void} wake
*/
/**
* @typedef {bigint} Deadline
*/
/**
* @typedef {Object} Timer
* @property {(deadline: Deadline, wakerP: ERef<Waker>) => void} setWakeup
*/
/**
* @typedef {Object} OnDemandExitRule
* @property {null} onDemand
*/
/**
* @typedef {Object} WaivedExitRule
* @property {null} waived
*/
/**
* @typedef {Object} AfterDeadlineExitRule
* @property {{timer:Timer, deadline:Deadline}} afterDeadline
*/
/**
* @typedef {OnDemandExitRule | WaivedExitRule | AfterDeadlineExitRule} ExitRule
*
* The possible keys are 'waived', 'onDemand', and 'afterDeadline'.
* `timer` and `deadline` only are used for the `afterDeadline` key.
* The possible records are:
* `{ waived: null }`
* `{ onDemand: null }`
* `{ afterDeadline: { timer :Timer<Deadline>, deadline :Deadline } }
*/
/**
* @typedef {Handle<'Instance'>} Instance
*/
/**
* @typedef {Object} VatAdminSvc
* @property {(bundle: SourceBundle) => RootAndAdminNode} createVat
* @property {(BundleName: string) => RootAndAdminNode} createVatByName
*/
/**
* @typedef {Record<string, any>} SourceBundle Opaque type for a JSONable source bundle
*/
/**
* @typedef {Record<Keyword,ERef<Payment>>} PaymentPKeywordRecord
* @typedef {Record<Keyword,Payment>} PaymentKeywordRecord
*/
/**
* @typedef {Object} StandardInvitationDetails
* @property {Installation} installation
* @property {Instance} instance
* @property {InvitationHandle} handle
* @property {string} description
*/
/**
* @typedef {StandardInvitationDetails & Record<string, any>} InvitationDetails
*/
/**
* @typedef {Object} Installation
* @property {() => SourceBundle} getBundle
*/
/**
* @typedef {Object} FeeIssuerConfig
* @property {string} name
* @property {AssetKind} assetKind
* @property {DisplayInfo} displayInfo
* @property {Value} initialFunds
*/
/**
* @typedef {Object} ZoeServiceFeePurseRequired
*
* See ZoeService for further comments and explanation (not copied here).
*
* @property {GetInvitationIssuer} getInvitationIssuer
* @property {InstallFeePurseRequired} install
* @property {StartInstanceFeePurseRequired} startInstance
* @property {OfferFeePurseRequired} offer
* @property {GetPublicFacetFeePurseRequired} getPublicFacet
* @property {GetIssuers} getIssuers
* @property {GetBrands} getBrands
* @property {GetTerms} getTerms
* @property {GetInstallationForInstance} getInstallationForInstance
* @property {GetInstance} getInstance
* @property {GetInstallation} getInstallation
* @property {GetInvitationDetails} getInvitationDetails
* @property {GetFeeIssuer} getFeeIssuer
* @property {MakeFeePurse} makeFeePurse
* @property {BindDefaultFeePurse} bindDefaultFeePurse
* @property {GetConfiguration} getConfiguration
*/
/**
* @typedef {Object} ZoeFeesConfig
* @property {NatValue} getPublicFacetFee
* @property {NatValue} installFee
* @property {NatValue} startInstanceFee
* @property {NatValue} offerFee
* @property {ERef<TimerService> | undefined} timeAuthority
* @property {bigint} highFee
* @property {bigint} lowFee
* @property {bigint} shortExp
* @property {bigint} longExp
*/
/**
* @typedef {Object} MeteringConfig
* @property {Computrons} initial - the amount of computrons a meter
* starts with
* @property {Computrons} incrementBy - when a meter is refilled, this
* amount will be added
* @property {Computrons} threshold - Zoe will be notified when the meter
* drops below this amount
* @property {{ feeNumerator: bigint, computronDenominator: bigint }}
* price - the price of computrons in RUN
*/
| 28.021429 | 87 | 0.715779 |
5e2e6839fda8684f09be7f44e82af39f6ffc6619 | 4,687 | js | JavaScript | src/mock/data.js | efaste/mywebsite | 7779a1a61ac03e83107f367e3971bed0b9185a68 | [
"MIT"
] | null | null | null | src/mock/data.js | efaste/mywebsite | 7779a1a61ac03e83107f367e3971bed0b9185a68 | [
"MIT"
] | null | null | null | src/mock/data.js | efaste/mywebsite | 7779a1a61ac03e83107f367e3971bed0b9185a68 | [
"MIT"
] | null | null | null | import { nanoid } from 'nanoid';
// HEAD DATA
export const headData = {
title: 'Efaste Mushundusi', // e.g: 'Name | Developer'
lang: '', // e.g: en, es, fr, jp
description: ' ', // e.g: Welcome to my website
};
// HERO DATA
export const heroData = {
title: '',
name: 'Efaste Mushundusi',
subtitle: 'I am an Operation management and Information system Student ',
cta: '',
};
// ABOUT DATA
export const aboutData = {
img: ' ',
paragraphOne: 'My name is Efaste Mushundusi I am a student from Northern Illinois University College of Business majoring in operation management and information system an emphasis in data analytics.',
paragraphTwo: 'The biggest value I bring to your company is my communication and leadership skills and my academic experience and skills. ',
paragraphThree: 'The one thing that sets me apart from other potential employees is my thirst for learning new technology and skills that will benefit the company and the stakeholders.',
resume: 'https://my.indeed.com/p/efastem-79uc46x', // if no resume, the button will not show up
};
// PROJECTS DATA
export const projectsData = [
{
id: nanoid(),
img: 'DatabasePicture4.png',
title: 'Loan Company Database created with Microsoft Sql Server Management Studio',
info: 'This is a database Project I created for my Database Management Class, created with microsoft sql server management studio.',
url: 'https://youtu.be/lz5N1jKogxU',
info2: '',
repo: 'https://youtu.be/lz5N1jKogxU', // if no repo, the button will not show up
},
{
id: nanoid(),
img: 'Games.PNG',
title: 'Global Video Game Sales Report Dashboard" ',
info: 'This dashboard shows global video games sales from major market and top platforms over the years.',
info2: '',
url: 'https://public.tableau.com/profile/efaste#!/vizhome/GlobalVideoGameSalesReportDashboard/GlobalVideoGameSalesReportDashboard',
repo: 'https://public.tableau.com/profile/efaste#!/vizhome/GlobalVideoGameSalesReportDashboard/GlobalVideoGameSalesReportDashboard', // if no repo, the button will not show up
},
{
id: nanoid(),
img: 'Hotel.PNG',
title: 'Hotel Customer Booking Report Dashboard" ',
info: 'This dashboard shows global customer booking data by customer type.',
info2: '',
url: 'https://public.tableau.com/profile/efaste#!/vizhome/HotelCustomerBookingReportDashboard/HotelCustomerBookingReportDashboard',
repo: 'https://public.tableau.com/profile/efaste#!/vizhome/HotelCustomerBookingReportDashboard/HotelCustomerBookingReportDashboard', // if no repo, the button will not show up
},
{
id: nanoid(),
img: 'Supermarket.PNG',
title: 'Supermarket statistics by gender',
info: 'This dashboard shows the activities of shoppers by their gender type. ',
info2: '',
url: 'https://public.tableau.com/profile/efaste#!/vizhome/Supermarketstatisticsbygender/Supermarketstatisticsbygender',
repo: 'https://public.tableau.com/profile/efaste#!/vizhome/Supermarketstatisticsbygender/Supermarketstatisticsbygender', // if no repo, the button will not show up
},
{
id: nanoid(),
img: 'Coffee.PNG',
title: 'Coffee Sales Report Dashboard',
info: 'This dashboard shows the sales of coffee by each states and by their brand name. ',
info2: '',
url: 'https://public.tableau.com/profile/efaste#!/vizhome/SummaryofCoffeeSales/CoffeeSalesReportDashBoard',
repo: 'https://public.tableau.com/profile/efaste#!/vizhome/SummaryofCoffeeSales/CoffeeSalesReportDashBoard', // if no repo, the button will not show up
},
{
id: nanoid(),
img: 'Superstore.PNG',
title: 'Superstore Report Dashboard" ',
info: 'This dashboard shows sales and profit by manager region.',
info2: '',
url: 'https://public.tableau.com/profile/efaste#!/vizhome/OMIS473Combochart/SuperstoreReportDashboard',
repo: 'https://public.tableau.com/profile/efaste#!/vizhome/OMIS473Combochart/SuperstoreReportDashboard', // if no repo, the button will not show up
},
];
// CONTACT DATA
export const contactData = {
cta: '',
btn: '',
email: 'efastemushundusi@gmail.com',
};
// FOOTER DATA
export const footerData = {
networks: [
{
id: nanoid(),
name: 'twitter',
url: '',
},
{
id: nanoid(),
name: 'codepen',
url: '',
},
{
id: nanoid(),
name: 'linkedin',
url: 'https://www.linkedin.com/in/efaste-mushundusi-9a95471b1/',
},
{
id: nanoid(),
name: 'github',
url: '',
},
],
};
// Github start/fork buttons
export const githubButtons = {
isEnabled: true, // set to false to disable the GitHub stars/fork buttons
};
| 38.418033 | 203 | 0.694474 |
5e2edf113163940d0bf93f29fca1ba3b2a217f22 | 387 | js | JavaScript | XilinxProcessorIPLib/drivers/prd/doc/html/api/xprd__example_8c.js | erique/embeddedsw | 4b5fd15c71405844e03f2c276daa38cfcbb6459b | [
"BSD-2-Clause",
"MIT"
] | 595 | 2015-02-03T15:07:36.000Z | 2022-03-31T18:21:23.000Z | XilinxProcessorIPLib/drivers/prd/doc/html/api/xprd__example_8c.js | erique/embeddedsw | 4b5fd15c71405844e03f2c276daa38cfcbb6459b | [
"BSD-2-Clause",
"MIT"
] | 144 | 2016-01-08T17:56:37.000Z | 2022-03-31T13:23:52.000Z | XilinxProcessorIPLib/drivers/prd/doc/html/api/xprd__example_8c.js | erique/embeddedsw | 4b5fd15c71405844e03f2c276daa38cfcbb6459b | [
"BSD-2-Clause",
"MIT"
] | 955 | 2015-03-30T00:54:27.000Z | 2022-03-31T11:32:23.000Z | var xprd__example_8c =
[
[ "XPRD_DEVICE_ID", "xprd__example_8c.html#a3d9140c35fd5787425c30bde913ebe47", null ],
[ "main", "xprd__example_8c.html#a840291bc02cba5474a4cb46a9b9566fe", null ],
[ "XPrd_Example", "xprd__example_8c.html#a410824c3df6d31386f454dee2c709dcb", null ],
[ "XPrd_TestDecouplerState", "xprd__example_8c.html#a7d27eeac5a2c92eea613b73500530488", null ]
]; | 55.285714 | 98 | 0.775194 |
5e2eeb652cf04a006bb486fbd89fc7b9da2c42be | 1,051 | js | JavaScript | Segunda-Documentacion-VillaFarm/backend2/index.js | Desarrollo-Software-2021-1/Villa-Farm | db82cf3e53fe22198e3999f2ccb406a413e85791 | [
"MIT"
] | null | null | null | Segunda-Documentacion-VillaFarm/backend2/index.js | Desarrollo-Software-2021-1/Villa-Farm | db82cf3e53fe22198e3999f2ccb406a413e85791 | [
"MIT"
] | null | null | null | Segunda-Documentacion-VillaFarm/backend2/index.js | Desarrollo-Software-2021-1/Villa-Farm | db82cf3e53fe22198e3999f2ccb406a413e85791 | [
"MIT"
] | null | null | null | const express = require('express');
const mongoose = require('mongoose');
const morgan = require('morgan');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
require('dotenv').config();
app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(cors());
mongoose.connect(process.env.DATABASE, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
}).then(() => {console.log("Coneccion de base de datos exitosa!")})
//rutas
app.use('/api/auth',require('./routes/authentication/auth'));
app.use('/api/posts',require('./routes/post/post'))
app.use('/api/postsproducts',require('./routes/post/postproduct'))
app.use('/api/like',require('./routes/like/like'))
app.use('/api/comment',require('./routes/comment/comment'))
app.use('/api/follow',require('./routes/follow/follow'))
//listen to port
const port = process.env.PORT;
app.listen(port,() => {
console.log(`Servidor de VILLAFARM esta siendo ejecutado en el puerto ${port}`)
}) | 29.194444 | 84 | 0.67079 |
5e2f4405059212c532174ad3c78cb6edc772a38a | 577 | js | JavaScript | 01 - User Record Access/User_Record_Access/User_Record_AccessHelper.js | carlwillimott/salesforce-lightning | 6665fe9176b0abde196fb417c675277c199c81af | [
"MIT"
] | null | null | null | 01 - User Record Access/User_Record_Access/User_Record_AccessHelper.js | carlwillimott/salesforce-lightning | 6665fe9176b0abde196fb417c675277c199c81af | [
"MIT"
] | null | null | null | 01 - User Record Access/User_Record_Access/User_Record_AccessHelper.js | carlwillimott/salesforce-lightning | 6665fe9176b0abde196fb417c675277c199c81af | [
"MIT"
] | null | null | null | ({
init: function(component, event, helper) {
var action = component.get('c.getUserAccess');
action.setStorable();
action.setParams({
userId: component.get('v.userId'),
recordId: component.get('v.recordId')
});
action.setCallback(this, function(response) {
if (response.getState() === 'SUCCESS') {
component.set('v.access', response.getReturnValue());
component.set('v.loaded', true);
}
});
$A.enqueueAction(action);
}
}); | 20.607143 | 69 | 0.518198 |
5e2f770a966830187766dad5b21df10a19c9d176 | 1,657 | js | JavaScript | interpreter/exception.js | Hadaward/interpreter | 401a056b3a1cb200ed11bf947965c385f9c08233 | [
"MIT"
] | 2 | 2022-01-30T18:07:36.000Z | 2022-03-22T12:49:37.000Z | interpreter/exception.js | Hadaward/interpreter | 401a056b3a1cb200ed11bf947965c385f9c08233 | [
"MIT"
] | null | null | null | interpreter/exception.js | Hadaward/interpreter | 401a056b3a1cb200ed11bf947965c385f9c08233 | [
"MIT"
] | 1 | 2022-01-05T20:44:00.000Z | 2022-01-05T20:44:00.000Z | module.exports = class {
constructor(name, pos_start, pos_end, details) {
this.name = name
this.details = details
this.position_end = pos_end
this.position_start = pos_start
this.toString = function() {
return `${this.name}: ${this.details}\nInterpreter, line ${this.position_start.lineNumber + 1}\n\n${this.position_start.inputText}`;
};
}
}
module.exports.IllegalCharError = class extends module.exports {
constructor(pos_start, pos_end, details) {
super("Illegal Character", pos_start, pos_end, details);
}
}
module.exports.InvalidSyntaxError = class extends module.exports {
constructor(pos_start, pos_end, details) {
super("Invalid Syntax", pos_start, pos_end, details);
}
}
module.exports.RuntimeError = class extends module.exports {
constructor(pos_start, pos_end, details, context) {
super("Runtime Error", pos_start, pos_end, details);
this.context = context;
this.toString = function() {
return `${this.generate_traceback()}${this.name}: ${this.details}\n\n${this.position_start.inputText}`
};
}
generate_traceback() {
let result = '';
let position = this.position_start;
let context = this.context;
while (context != null && context != undefined && context) {
result = ` Interpreter, line ${position.lineNumber + 1}, in ${context.name}\n` + result;
position = context.parent_entry_position;
context = context.parent;
}
return `Traceback (most recent call last):\n${result}`;
}
}
module.exports.log = function(exception) {
if (exception instanceof module.exports) {
console.error(exception.toString());
}
} | 30.127273 | 136 | 0.682559 |
5e30197b6192588a1fa2101b58bb92839d8cdfb7 | 997 | js | JavaScript | src/container/App.js | zhufengreact/react-tutorial | 1d7bc8c97dba120f09e6d301c356c35f207afec3 | [
"MIT"
] | null | null | null | src/container/App.js | zhufengreact/react-tutorial | 1d7bc8c97dba120f09e6d301c356c35f207afec3 | [
"MIT"
] | null | null | null | src/container/App.js | zhufengreact/react-tutorial | 1d7bc8c97dba120f09e6d301c356c35f207afec3 | [
"MIT"
] | null | null | null | import React, { Component } from 'react';
import {
SimpleComponent,
ComponentDemo,
SpreadDemo,
StyleDemo,
StateDemo,
PropsDemo,
PropTypesDemo,
LifeCycleDemo,
DestroyComponent,
HandleDOMComponent,
HandleEvent,
SelfCreateComponent,
UseChildrenComponent,
FormApp,
MixinDemo
} from '../components';
let data = {
name: 'AlphaGo',
type: 'robot'
};
class App extends Component {
render(){
return (
<div>
{
/*
<SimpleComponent />
<ComponentDemo name="guoyongfeng" />
<SpreadDemo {...data} />
<StyleDemo />
<StateDemo />
<PropsDemo title="设置的标题" />
<PropTypesDemo />
<LifeCycleDemo />
<DestroyComponent />
<HandleDOMComponent />
<HandleEvent />
<SelfCreateComponent />
<UseChildrenComponent />
<FormApp />
*/
}
<MixinDemo />
</div>
)
}
}
export default App;
| 17.803571 | 46 | 0.54664 |
5e3057c11e92e1ecd6c1f580a12d4c9b0b8dec5e | 146 | js | JavaScript | l8/public/metch/js/pages/crud/forms/widgets/bootstrap-switchf552.js | nyulacska/_brad | f7acb10280c4960337e81b373a253b81b9200636 | [
"Unlicense"
] | 481 | 2018-05-19T22:38:46.000Z | 2022-03-29T07:37:13.000Z | l8/public/metch/js/pages/crud/forms/widgets/bootstrap-switchf552.js | nyulacska/_brad | f7acb10280c4960337e81b373a253b81b9200636 | [
"Unlicense"
] | 41 | 2018-08-01T01:42:38.000Z | 2022-01-09T11:42:05.000Z | l8/public/metch/js/pages/crud/forms/widgets/bootstrap-switchf552.js | nyulacska/_brad | f7acb10280c4960337e81b373a253b81b9200636 | [
"Unlicense"
] | 129 | 2018-05-20T04:14:45.000Z | 2022-03-07T01:03:38.000Z | var KTBootstrapSwitch={init:function(){$("[data-switch=true]").bootstrapSwitch()}};jQuery(document).ready((function(){KTBootstrapSwitch.init()})); | 146 | 146 | 0.746575 |
5e3061bcb4c09c51b6d993dabb1a7047050aa857 | 1,905 | js | JavaScript | .eslintrc.js | citruslab/audius-mobile-client | 7cc2792c226767777a67893851957f62a53f062a | [
"Apache-2.0"
] | null | null | null | .eslintrc.js | citruslab/audius-mobile-client | 7cc2792c226767777a67893851957f62a53f062a | [
"Apache-2.0"
] | null | null | null | .eslintrc.js | citruslab/audius-mobile-client | 7cc2792c226767777a67893851957f62a53f062a | [
"Apache-2.0"
] | null | null | null | module.exports = {
root: true,
env: {
es6: true,
},
extends: [
'standard',
'@react-native-community',
'plugin:@typescript-eslint/recommended',
'plugin:jest/recommended',
'plugin:react/recommended',
'prettier/react',
'prettier-standard/prettier-file',
],
globals: {
Atomics: 'readonly',
SharedArrayBuffer: 'readonly',
},
parser: '@typescript-eslint/parser',
parserOptions: {
ecmaFeatures: {
jsx: true,
},
ecmaVersion: 2018,
sourceType: 'module',
},
plugins: ['react', 'react-hooks', '@typescript-eslint', 'jest'],
rules: {
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/no-non-null-assertion': 'off',
'@typescript-eslint/member-delimiter-style': 'off',
'@typescript-eslint/no-empty-interface': 'off',
'@typescript-eslint/camelcase': 'off',
'@typescript-eslint/ban-ts-ignore': 'off',
'@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/no-use-before-define': 'off',
'@typescript-eslint/no-empty-function': 'off',
'@typescript-eslint/no-var-requires': 'off',
'@typescript-eslint/no-unused-vars': ['error', {args: 'none'}], // We should turn this one on soon
'@typescript-eslint/no-this-alias': 'off',
'no-use-before-define': 'off',
camelcase: 'off',
'no-unused-vars': 'off',
'func-call-spacing': 'off',
semi: ['error', 'never'],
'no-undef': 'off',
'no-empty': 'off',
'no-shadow': 'off',
'arrow-parens': 'off',
'padded-blocks': 'off',
'jest/expect-expect': 'off',
'react-hooks/rules-of-hooks': 'error',
'react-hooks/exhaustive-deps': 'warn',
'react/display-name': 'off',
'react/prop-types': 'off',
'react-native/no-inline-styles': 'off',
'prettier/prettier': 'error',
'space-before-function-paren': 'off',
'generator-star-spacing': 'off',
},
};
| 27.608696 | 102 | 0.608924 |
5e3085f1a2c363c36c9877099bff8fa0c106e76c | 1,803 | js | JavaScript | chromeExtension_v3/serviceWorker.js | galdiatorocks/boilerplate | 84ef2cb4a4d35874b9194fce6f0fbe5fd34e62bb | [
"MIT"
] | null | null | null | chromeExtension_v3/serviceWorker.js | galdiatorocks/boilerplate | 84ef2cb4a4d35874b9194fce6f0fbe5fd34e62bb | [
"MIT"
] | null | null | null | chromeExtension_v3/serviceWorker.js | galdiatorocks/boilerplate | 84ef2cb4a4d35874b9194fce6f0fbe5fd34e62bb | [
"MIT"
] | null | null | null | console.log("Service Worker Here");
let color = '#3aa757';
chrome.runtime.onInstalled.addListener(() => {
// chrome.storage.sync.set({color});
chrome.storage.local.set({color});
console.log("The background.js is running", `color: ${color}`);
})
let active_tab_id = 0
chrome.tabs.onActivated.addListener(tab => {
console.log(tab);
chrome.tabs.get(tab.tabId, current_tab_info => {
console.log(current_tab_info.url)
active_tab_id = tab.tabId;
let googleRegex = /^https:\/\/www\.google/;
if(googleRegex.test(current_tab_info.url)) {
console.log(current_tab_info);
chrome.scripting.insertCSS({
target: {tabId: active_tab_id},
files: ['mystyles.css']
})
chrome.scripting.executeScript({
target: {tabId: active_tab_id},
files: ['./imageRoll.js']
}, ()=>console.log("I Injected")
)
}
let isInviteRegex = /^https:\/\/internshala\.com\/employer\/applications\/1778109\/1\/invite/;
if(isInviteRegex.test(current_tab_info.url)){
console.log(current_tab_info);
chrome.scripting.executeScript(
{
target: {tabId: active_tab_id},
files: ['internshalaInviteApplicant.js']
},() => console.log("IS js injected")
);
}
})
})
chrome.runtime.onMessage.addListener((request, sender/*, sendResponse*/) => {
if(request.message == 'Yo check the storage.');
chrome.tabs.sendMessage(active_tab_id, {message: 'yo i got your message'});
// sendResponse({message: 'yo I got your message'});
chrome.storage.local.get("password", value => {
console.log(value);
})
}) | 34.673077 | 102 | 0.575707 |
5e30ac62eceb890a2bf54fd3022239f01848285b | 354 | js | JavaScript | node_modules/@iconify/icons-ic/round-format-strikethrough.js | kagwicharles/Seniorproject-ui | 265956867c8a00063067f03e8772b93f2986c626 | [
"MIT"
] | null | null | null | node_modules/@iconify/icons-ic/round-format-strikethrough.js | kagwicharles/Seniorproject-ui | 265956867c8a00063067f03e8772b93f2986c626 | [
"MIT"
] | null | null | null | node_modules/@iconify/icons-ic/round-format-strikethrough.js | kagwicharles/Seniorproject-ui | 265956867c8a00063067f03e8772b93f2986c626 | [
"MIT"
] | 1 | 2021-09-28T19:15:17.000Z | 2021-09-28T19:15:17.000Z | var data = {
"body": "<path d=\"M12 19c1.1 0 2-.9 2-2v-1h-4v1c0 1.1.9 2 2 2zM5 5.5C5 6.33 5.67 7 6.5 7H10v3h4V7h3.5c.83 0 1.5-.67 1.5-1.5S18.33 4 17.5 4h-11C5.67 4 5 4.67 5 5.5zM4 14h16c.55 0 1-.45 1-1s-.45-1-1-1H4c-.55 0-1 .45-1 1s.45 1 1 1z\" fill=\"currentColor\"/>",
"width": 24,
"height": 24
};
exports.__esModule = true;
exports.default = data;
| 44.25 | 258 | 0.621469 |
5e30e64ceef9a1118e0525f319d4dbbf47e0e80c | 11,115 | js | JavaScript | tests/js/front-end/contact-form.test.js | malwr-io/material-design-wp-plugin | 726101dc1787e242119dd59dece6716c18304987 | [
"Apache-2.0"
] | 1 | 2021-03-14T20:03:46.000Z | 2021-03-14T20:03:46.000Z | tests/js/front-end/contact-form.test.js | malwr-io/material-design-wp-plugin | 726101dc1787e242119dd59dece6716c18304987 | [
"Apache-2.0"
] | null | null | null | tests/js/front-end/contact-form.test.js | malwr-io/material-design-wp-plugin | 726101dc1787e242119dd59dece6716c18304987 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* External dependencies
*/
import fs from 'fs';
import path from 'path';
import '@testing-library/jest-dom/extend-expect';
import { waitFor } from '@testing-library/dom';
import MutationObserver from '@sheerun/mutationobserver-shim';
/**
* Internal dependencies
*/
import {
initReCaptchaToken,
initContactForm,
} from '../../../assets/src/front-end/contact-form';
jest.dontMock( 'fs' );
window.MutationObserver = MutationObserver;
/**
* Render the contact form.
*/
const setup = () => {
document.body.innerHTML = `<div id="content">${ fs.readFileSync(
path.resolve( __dirname, './contact-form.html' ),
'utf-8'
) }</div>`;
};
/**
* Retrieves FormData object from the mock.
*
* @param {Object} mock XHR mock object.
*/
const retrieveFormDataFromMock = mock => {
const formDataInstance = mock.calls[ 0 ][ 0 ];
const formDataAsObject = {};
formDataInstance.forEach( ( value, key ) => {
formDataAsObject[ key ] = value;
} );
return [ formDataInstance, formDataAsObject ];
};
/**
* XMLHttpRequest mock.
*/
const mockXMLHttpRequest = () => {
const mock = {
open: jest.fn(),
addEventListener: jest.fn(),
setRequestHeader: jest.fn(),
send: jest.fn(),
getResponseHeader: jest.fn(),
upload: {
addEventListener: jest.fn(),
},
DONE: 4,
};
jest.spyOn( window, 'XMLHttpRequest' ).mockImplementation( () => mock );
return mock;
};
describe( 'Front-end: Contact Form', () => {
const tokenValue = 'CAPTCHA_TOKEN';
const ready = jest.fn( fn => fn() );
const execute = jest.fn( () => {
return new Promise( resolve => {
resolve( tokenValue );
} );
} );
beforeAll( () => {
global.materialDesign = {
ajax_url: 'http://example.com/',
recaptcha_site_key: 'SITE_KEY',
};
global.grecaptcha = {
ready,
execute,
};
} );
beforeEach( () => {
jest.clearAllMocks();
} );
describe( 'initContactForm', () => {
it( 'returns false when the specific contact form does not exists', () => {
document.body.innerHTML = `<div id="content">${ fs.readFileSync(
path.resolve( __dirname, './invalid-contact-form.html' ),
'utf-8'
) }</div>`;
const result = initContactForm();
expect( result ).toStrictEqual( false );
} );
it( 'instantiates text fields as Material Design text fields', () => {
setup();
initContactForm();
expect(
document
.querySelector( '.mdc-notched-outline' )
.classList.contains( 'mdc-notched-outline--upgraded' )
).toStrictEqual( true );
} );
it( 'calls successfully the ajax request and shows the success message when the form submission is successful', async () => {
setup();
document.getElementById( 'material-design-name-1' ).value = 'Test Name';
document.getElementById( 'material-design-email-1' ).value =
'email@example.com';
document.getElementById( 'material-design-website-1' ).value =
'http://example.com';
document.getElementById( 'material-design-message-1' ).value =
'Test message';
const xhr = mockXMLHttpRequest();
initContactForm();
document.querySelector( '.mdc-button' ).click();
expect( xhr.send.mock.calls[ 0 ][ 0 ] ).not.toBeUndefined();
const [ formDataInstance, formDataAsObject ] = retrieveFormDataFromMock(
xhr.send.mock
);
expect( xhr.open ).toHaveBeenCalledWith(
'POST',
global.materialDesign.ajax_url
);
expect( xhr.send ).toHaveBeenCalledWith( formDataInstance );
expect( formDataAsObject ).toStrictEqual( {
_wp_http_referer: '/3732-2/',
action: 'material_design_submit_contact_form',
contact_fields:
'{"material-design-name-1":{"name":"material-design-name-1","label":"Name","value":"Test Name"},"material-design-email-1":{"name":"material-design-email-1","label":"Email","value":"email@example.com"},"material-design-website-1":{"name":"material-design-website-1","label":"Website","value":"http://example.com"},"material-design-message-1":{"name":"material-design-message-1","label":"Message","value":"Test message"}}',
material_design_contact_form_nonce: '8d2ba7b1f1',
material_design_token: 'token_here',
token: 'token_here',
} );
xhr.readyState = XMLHttpRequest.DONE;
xhr.status = 200;
xhr.responseText = JSON.stringify( { success: true } );
expect( xhr.onreadystatechange ).not.toBeUndefined();
xhr.onreadystatechange.call();
await waitFor( () => {
expect(
document.getElementById(
'materialDesignContactFormSuccessMsgContainer'
).style.display
).toStrictEqual( 'block' );
} );
} );
it( 'calls successfully the ajax request and shows the error message when the form submission is not successful', async () => {
setup();
document.getElementById( 'material-design-name-1' ).value = 'Test Name';
document.getElementById( 'material-design-email-1' ).value =
'email@example.com';
document.getElementById( 'material-design-website-1' ).value =
'http://example.com';
document.getElementById( 'material-design-message-1' ).value =
'Test message';
document.getElementsByName( '_wp_http_referer' )[ 0 ].value = '';
const xhr = mockXMLHttpRequest();
initContactForm();
document.querySelector( '.mdc-button' ).click();
expect( xhr.send.mock.calls[ 0 ][ 0 ] ).not.toBeUndefined();
const [ formDataInstance, formDataAsObject ] = retrieveFormDataFromMock(
xhr.send.mock
);
expect( xhr.open ).toHaveBeenCalledWith(
'POST',
global.materialDesign.ajax_url
);
expect( xhr.send ).toHaveBeenCalledWith( formDataInstance );
expect( formDataAsObject ).toStrictEqual( {
_wp_http_referer: '',
action: 'material_design_submit_contact_form',
contact_fields:
'{"material-design-name-1":{"name":"material-design-name-1","label":"Name","value":"Test Name"},"material-design-email-1":{"name":"material-design-email-1","label":"Email","value":"email@example.com"},"material-design-website-1":{"name":"material-design-website-1","label":"Website","value":"http://example.com"},"material-design-message-1":{"name":"material-design-message-1","label":"Message","value":"Test message"}}',
material_design_contact_form_nonce: '8d2ba7b1f1',
material_design_token: 'token_here',
token: 'token_here',
} );
xhr.readyState = XMLHttpRequest.DONE;
xhr.status = 200;
// Simulate a valid request that failed.
xhr.responseText = JSON.stringify( { success: false } );
expect( xhr.onreadystatechange ).not.toBeUndefined();
xhr.onreadystatechange.call();
await waitFor( () => {
expect(
document.getElementById(
'materialDesignContactFormErrorMsgContainer'
).style.display
).toStrictEqual( 'block' );
} );
} );
it( 'calls the ajax request with failure and shows the error message when the form submission is not successful', async () => {
setup();
document.getElementById( 'material-design-name-1' ).value = 'Test Name';
document.getElementById( 'material-design-email-1' ).value =
'email@example.com';
document.getElementById( 'material-design-website-1' ).value =
'http://example.com';
document.getElementById( 'material-design-message-1' ).value =
'Test message';
document.getElementsByName( 'action' )[ 0 ].value = '';
const xhr = mockXMLHttpRequest();
initContactForm();
document.querySelector( '.mdc-button' ).click();
expect( xhr.send.mock.calls[ 0 ][ 0 ] ).not.toBeUndefined();
const [ formDataInstance, formDataAsObject ] = retrieveFormDataFromMock(
xhr.send.mock
);
expect( xhr.open ).toHaveBeenCalledWith(
'POST',
global.materialDesign.ajax_url
);
expect( xhr.send ).toHaveBeenCalledWith( formDataInstance );
expect( formDataAsObject ).toStrictEqual( {
_wp_http_referer: '/3732-2/',
action: '',
contact_fields:
'{"material-design-name-1":{"name":"material-design-name-1","label":"Name","value":"Test Name"},"material-design-email-1":{"name":"material-design-email-1","label":"Email","value":"email@example.com"},"material-design-website-1":{"name":"material-design-website-1","label":"Website","value":"http://example.com"},"material-design-message-1":{"name":"material-design-message-1","label":"Message","value":"Test message"}}',
material_design_contact_form_nonce: '8d2ba7b1f1',
material_design_token: 'token_here',
token: 'token_here',
} );
xhr.readyState = XMLHttpRequest.DONE;
// Simulate a HTTP error.
xhr.status = 401;
xhr.responseText = null;
expect( xhr.onreadystatechange ).not.toBeUndefined();
xhr.onreadystatechange.call();
await waitFor( () => {
expect(
document.getElementById(
'materialDesignContactFormErrorMsgContainer'
).style.display
).toStrictEqual( 'block' );
} );
} );
it( 'errors', () => {
setup();
document.getElementById( 'material-design-email-1' ).value = 'bad email';
initContactForm();
document.getElementById( 'materialDesignContactForm' ).checkValidity();
expect(
document
.getElementById( 'material-design-email-1' )
.closest( '.mdc-text-field' )
.classList.contains( 'mdc-text-field--invalid' )
).toStrictEqual( true );
} );
} );
describe( 'initReCaptchaToken', () => {
it( 'runs only when an element with id `materialDesignContactForm` exists', () => {
setup();
// Remove the form element.
document.getElementById( 'materialDesignContactForm' ).remove();
initReCaptchaToken();
expect( ready ).toHaveBeenCalledTimes( 0 );
} );
it( 'runs only when an element with name `material_design_token` exists', () => {
setup();
// Remove the token text element.
document.querySelector( '[name=material_design_token]' ).remove();
initReCaptchaToken();
expect( ready ).toHaveBeenCalledTimes( 0 );
} );
it( 'runs only when `recaptcha_site_key` is set and valid', () => {
setup();
delete global.materialDesign.recaptcha_site_key;
initReCaptchaToken();
expect( ready ).toHaveBeenCalledTimes( 0 );
global.materialDesign.recaptcha_site_key = '';
initReCaptchaToken();
expect( ready ).toHaveBeenCalledTimes( 0 );
} );
it( 'invokes grecaptcha ready, executes and sets the token field value', async () => {
global.materialDesign.recaptcha_site_key = 'SITE_KEY';
setup();
initReCaptchaToken();
expect( ready ).toHaveBeenCalledTimes( 1 );
expect( execute ).toHaveBeenCalledTimes( 1 );
await waitFor( () =>
expect(
document.querySelector( '[name=material_design_token]' ).value
).toStrictEqual( tokenValue )
);
} );
} );
} );
| 31.398305 | 426 | 0.673054 |
5e319158dd379e2d194abe9a3427afcd738bd772 | 10,919 | js | JavaScript | src/pages/activity/components/listProductSimple/index.js | dacheng-mall/platform-client | 54d694eb9d5402b893756f62a03b1235d4aa7daf | [
"Apache-2.0"
] | null | null | null | src/pages/activity/components/listProductSimple/index.js | dacheng-mall/platform-client | 54d694eb9d5402b893756f62a03b1235d4aa7daf | [
"Apache-2.0"
] | null | null | null | src/pages/activity/components/listProductSimple/index.js | dacheng-mall/platform-client | 54d694eb9d5402b893756f62a03b1235d4aa7daf | [
"Apache-2.0"
] | null | null | null | import React from 'react';
import { connect } from 'dva';
import moment from 'moment';
import _ from 'lodash';
import { Modal, Form, Input, Select, InputNumber, Radio, Button, DatePicker, Col, Row } from 'antd';
import { FormItem } from '../../../../utils/ui';
import { upload } from '../../../../utils';
import { getProductsWithoutPage } from '../../../products/services';
import Images from '../../../products/components/form/Images';
import { updateActivityproducts, createActivityproducts } from '../../services/activity';
import styles from './index.less';
const source = window.config.source;
const RangePicker = DatePicker.RangePicker;
function Products(props) {
const click = (p, e) => {
e.preventDefault();
props.onEdit(p);
if (props.canRemove) {
}
};
const remove = (id, aid, e) => {
e.stopPropagation();
if (props.canRemove) {
props.onRemove(id, aid);
}
};
return _.map(props.data, (p) => {
return (
<div
onClick={click.bind(null, p)}
key={p.id}
className={styles.item}
style={{ textAlign: 'center' }}
>
<img style={{ width: '88px', height: '88px' }} src={`${source}${p.images}`} />
<br />
{p.showName}
{props.canRemove ? <div onClick={remove.bind(null, p.id, p.activityId)}>删除</div> : null}
</div>
);
});
}
class ListProductSimple extends React.PureComponent {
state = {
current: null,
products: [],
};
remove = (id, aid) => {
this.props.dispatch({
type: 'activities/remove',
payload: { id, aid },
});
};
show = (p) => {
const { beginTime, finishTime, images: _images } = p;
const images = [];
let range;
if (beginTime && finishTime) {
range = [moment(beginTime), moment(finishTime)];
}
console.log('p', p);
if (_images) {
_.forEach(_images.split(','), (image) => {
images.push({
_url: image,
url: `${source}${image}`,
});
});
}
this.setState({
current: {
...p,
range,
price: p.product.price,
images,
},
products: [
{
title: p.product.title,
id: p.product.id,
price: p.product.price,
img: p.product.mainImageUrl,
},
],
});
};
hide = () => {
this.setState({
current: null,
products: [],
});
};
select = (productId) => {
const target = _.find(this.state.products, ['id', productId]);
this.setState({
current: { ...this.state.current, productId, price: target.price },
});
};
timer = null;
search = (title) => {
if (_.trim(title)) {
if (this.timer) {
clearTimeout(this.timer);
}
this.timer = setTimeout(() => {
getProductsWithoutPage({ title }).then(({ data }) => {
this.setState({
products: _.map(data, (d) => ({
title: d.title,
id: d.id,
price: d.price,
img: d.mainImageUrl,
})),
});
});
}, 300);
}
};
submit = async () => {
if (this.props.user.userType === 3) {
this.hide();
return;
}
const { current } = this.state;
this.props.form.validateFields(async (err, values) => {
if (err) {
return;
}
console.log(values);
const todos = {};
_.forEach(values.images, (img, i) => {
if (img && img.originFileObj) {
todos[`_images[${i}].url`] = upload(img.originFileObj);
values.images[i] = {
url: '',
};
} else {
values.images[i].url = values.images[i]._url;
delete values.images[i]._url;
delete values.images[i].uid;
}
});
if (!_.isEmpty(todos)) {
const ups = Object.values(todos);
if (ups.length > 0) {
const [image] = await Promise.all(_.map(ups, (up) => up()));
if (image) {
values.images = image.key;
}
}
} else {
delete values.images;
}
console.log(values);
// return;
if (values.range) {
values.beginTime = moment(values.range[0]).format('YYYY-MM-DD HH:mm:ss');
values.finishTime = moment(values.range[1]).format('YYYY-MM-DD HH:mm:ss');
delete values.range;
}
if (current.id) {
// 这里是编辑商品
delete values.productId;
values.id = current.id;
updateActivityproducts(values).then(({ data }) => {
this.props.onEdit('update', data);
this.hide();
});
} else {
// 这里需要添加新的;
values.activityId = this.props.activityId;
values.displayOrder = _.isArray(this.props.data) ? this.props.data.length : 0;
createActivityproducts(values).then(({ data }) => {
this.props.onEdit('create', data);
this.hide();
});
}
});
};
renderProducts = (products) =>
_.map(products, (p) => (
<Select.Option key={p.id} value={p.id}>
{p.title}
</Select.Option>
));
plusProduct = () => {
this.setState({
current: {},
products: [],
});
};
render() {
const { getFieldDecorator } = this.props.form;
return (
<div className={styles.wrap}>
<div className={styles.products}>
<Products
data={this.props.data}
key="product"
onEdit={this.show}
onRemove={this.remove}
canRemove={this.props.user.userType === 1}
/>
</div>
{this.props.user.userType === 3 ? null : (
<Button type="primary" icon="plus" shape="circle" onClick={this.plusProduct} />
)}
{this.state.current ? (
<Modal
visible={!!this.state.current}
onCancel={this.hide}
onOk={this.submit}
key="modal"
title={`${this.props.user.userType === 3 ? '查看' : '编辑'}活动关联商品`}
width={1000}
>
<Form>
<Row gutter={10}>
<Col span={12}>
<FormItem label="图片">
{getFieldDecorator('images', {
initialValue: this.state.current.images,
rules: [{ required: false, message: '必填项' }],
})(<Images max={1} />)}
</FormItem>
<FormItem label="显示名称">
{getFieldDecorator('showName', {
initialValue: this.state.current.showName,
rules: [{ required: true, message: '必填项' }],
})(
<Input
placeholder="请输入活动显示名称"
disabled={this.props.user.userType === 3}
/>,
)}
</FormItem>
<FormItem label="原价(元)">
{getFieldDecorator('price', {
initialValue: this.state.current.price,
})(
<InputNumber
mix={0}
placeholder="请输入"
disabled={this.props.user.userType === 3}
style={{ width: '100px' }}
/>,
)}
</FormItem>
<FormItem label="活动价(元)">
{getFieldDecorator('activityPrice', {
initialValue: this.state.current.activityPrice,
})(
<InputNumber
mix={0}
placeholder="请输入"
disabled={this.props.user.userType === 3}
style={{ width: '100px' }}
/>,
)}
</FormItem>
</Col>
<Col span={12}>
<FormItem label="周期">
{getFieldDecorator('range', {
initialValue: this.state.current.range,
})(
<RangePicker
showTime
format="YYYY-MM-DD HH:mm:ss"
disabled={this.props.user.userType === 3}
/>,
)}
</FormItem>
<FormItem label="中奖概率">
{getFieldDecorator('probability', {
initialValue: this.state.current.probability,
})(
<InputNumber
min={0}
max={0.99999}
placeholder="小于1"
disabled={this.props.user.userType === 3}
style={{ width: '100px' }}
/>,
)}
</FormItem>
<FormItem label="库存(件)">
{getFieldDecorator('stock', {
initialValue: this.state.current.stock,
rules: [{ required: true, message: '必填项' }],
})(
<InputNumber
min={0}
placeholder="正整数"
disabled={this.props.user.userType === 3}
style={{ width: '100px' }}
/>,
)}
</FormItem>
<FormItem label="包含(件)">
{getFieldDecorator('totalCount', {
initialValue: this.state.current.totalCount || 1,
})(
<InputNumber
min={1}
placeholder="请输入库存"
disabled={this.props.user.userType === 3}
/>,
)}
</FormItem>
<FormItem label="状态">
{getFieldDecorator('status', {
initialValue: this.state.current.status || 'waiting',
})(
<Radio.Group disabled={this.props.user.userType === 3}>
<Radio.Button value="waiting">等待</Radio.Button>
<Radio.Button value="sellOut">售罄</Radio.Button>
<Radio.Button value="frozen">冻结</Radio.Button>
<Radio.Button value="expired">过期</Radio.Button>
<Radio.Button value="enable">进行中</Radio.Button>
</Radio.Group>,
)}
</FormItem>
</Col>
</Row>
</Form>
</Modal>
) : null}
</div>
);
}
}
function mapStateToProps({ activity, app }) {
return { ...activity, user: app.user };
}
export default connect(mapStateToProps)(Form.create()(ListProductSimple));
| 31.833819 | 100 | 0.441158 |
5e31cd49d1812777ee65e84297bfb81ed32a3656 | 1,494 | js | JavaScript | web-foodint-dev/index.js | wolfram77/temp | 173bb9986d045c15b32975338aea24f91d9cbddc | [
"Unlicense"
] | null | null | null | web-foodint-dev/index.js | wolfram77/temp | 173bb9986d045c15b32975338aea24f91d9cbddc | [
"Unlicense"
] | null | null | null | web-foodint-dev/index.js | wolfram77/temp | 173bb9986d045c15b32975338aea24f91d9cbddc | [
"Unlicense"
] | null | null | null | var pgconfig = require('pg-connection-string').parse;
var bodyParser = require('body-parser');
var express = require('express');
var EventEmitter = require('events');
var http = require('http');
var _ = require('lodash');
var pg = require('pg');
var DFood = require('./src/data/food');
var DGroups = require('./src/data/groups');
var DNames = require('./src/data/names');
var IJson = require('./src/json');
var ISql = require('./src/sql')
// settings
var idata = {}, ijson, isql;
var e = new EventEmitter();
var url = process.env.DATABASE_URL;
pg.defaults.ssl = true;
// connect to db
console.log('pg.connect: '+url);
var pool = new pg.Pool(pgconfig(url));
pool.connect(function(err, db, done) {
if(err) throw err;
console.log('pg.connect: done');
idata.food = new DFood(pool);
idata.groups = new DGroups(pool);
idata.names = new DNames(pool);
ijson = new IJson(idata);
isql = new ISql(pool, idata.names);
e.emit('ready');
done();
});
// set up server
e.on('ready', () => {
console.log('server: setting up');
var x = express();
x.use(bodyParser.json());
x.use(bodyParser.urlencoded({'extended': true}));
x.use((req, res, next) => {
req.body = _.assign(req.body, req.query);
next();
});
x.use('/json', ijson);
x.use('/sql', isql);
x.get('/', (req, res) => {
res.sendFile(__dirname+'/README.md');
});
// x.use('/', express.static(uroot));
var server = http.createServer(x);
server.listen(process.env.PORT||80, function() {
console.log('server: done');
});
});
| 26.210526 | 53 | 0.641901 |
5e326600a040c1d3f2735ab3b9af5366e9c32db0 | 48 | js | JavaScript | src/config/index.js | ginocoates/node-payslip | 391eb392fd60dd5fdf82e871c3ec129f9af968df | [
"MIT"
] | null | null | null | src/config/index.js | ginocoates/node-payslip | 391eb392fd60dd5fdf82e871c3ec129f9af968df | [
"MIT"
] | null | null | null | src/config/index.js | ginocoates/node-payslip | 391eb392fd60dd5fdf82e871c3ec129f9af968df | [
"MIT"
] | null | null | null | module.exports = {
defaultRules: '2012-13'
};
| 12 | 25 | 0.645833 |
5e32e42db6462b77473a27b37a6109ba9e4a22f1 | 642 | js | JavaScript | src/layouts/index.js | johnchourajr/gatsby-netlify-site-template | fce9f559bbc6f8550df548041f3cdb768579cb79 | [
"MIT"
] | null | null | null | src/layouts/index.js | johnchourajr/gatsby-netlify-site-template | fce9f559bbc6f8550df548041f3cdb768579cb79 | [
"MIT"
] | null | null | null | src/layouts/index.js | johnchourajr/gatsby-netlify-site-template | fce9f559bbc6f8550df548041f3cdb768579cb79 | [
"MIT"
] | null | null | null | import React from 'react'
import PropTypes from 'prop-types'
import Head from '../components/core/Head'
import Header from '../components/core/Header'
import BodyWrap from '../components/core/BodyWrap'
import Footer from '../components/core/Footer'
import { mainNav, subNav } from '../components/data/NavData'
import './all.scss'
const TemplateWrapper = ({ children, location }) => (
<div>
<Head />
<Header mainNav={mainNav}/>
<BodyWrap location={location}>
{children}
</BodyWrap>
<Footer subNav={subNav} />
</div>
)
TemplateWrapper.propTypes = {
children: PropTypes.func,
}
export default TemplateWrapper
| 23.777778 | 60 | 0.694704 |
5e33607cc46e3928ffea1f67d53728012f9fe68d | 4,361 | js | JavaScript | 2018/RedGL_old1/beta/rnd_shader_maker/trash2/UPDATER.js | redcamel/RedRnd | ffd37eb08e945ca0a5ea21dc2e25174739bd5392 | [
"MIT"
] | 1 | 2020-08-19T00:40:02.000Z | 2020-08-19T00:40:02.000Z | 2018/RedGL_old1/beta/rnd_shader_maker/trash2/UPDATER.js | redcamel/RedRnd | ffd37eb08e945ca0a5ea21dc2e25174739bd5392 | [
"MIT"
] | null | null | null | 2018/RedGL_old1/beta/rnd_shader_maker/trash2/UPDATER.js | redcamel/RedRnd | ffd37eb08e945ca0a5ea21dc2e25174739bd5392 | [
"MIT"
] | 1 | 2020-08-19T00:40:03.000Z | 2020-08-19T00:40:03.000Z | 'use strict';
Recard.static('UPDATER', (function () {
var result;
result = {
init: function () {
Recard.LOOPER.del('UPDATER')
Recard.LOOPER.add('UPDATER', function () {
var svgList = Recard.INDEX.getLineList()
var nodeList = Recard.queryAll('[nodeItem]')
svgList.forEach(function (item) {
item.remove()
})
svgList.length = 0
nodeList.forEach(function (item) {
for(var k in item['prev']){
var startItem, endItem
var starKeytItem, endKeyItem
var sL, sT
var eL, eT
var tPrevData
tPrevData = item['prev'][k]
// console.log('시작아이템정보',tPrevData)
if (tPrevData && (startItem = tPrevData['target'])) {
var startTargetKey
var endTargetKey
// 목표아이템을 찾고
endItem = startItem['next'][tPrevData['targetKey']]['target']
// 소스아이템의 목표키를 찾는다.
startTargetKey = startItem['next'][tPrevData['targetKey']]['targetKey']
endTargetKey = tPrevData['targetKey']
// console.log(startTargetKey,endTargetKey)
// console.log(startItem,endItem)
starKeytItem = startItem.query('[key="' + startTargetKey + '"]')
endKeyItem = endItem.query('[key="' + endTargetKey + '"]')
// console.log(starKeytItem,endKeyItem)
sL = startItem.S('left') + starKeytItem.__dom__.offsetLeft + starKeytItem.__dom__.clientWidth + 3
sT = startItem.S('top') + starKeytItem.__dom__.offsetTop + starKeytItem.__dom__.clientHeight / 2
eL = endItem.S('left') + endKeyItem.__dom__.offsetLeft - 3
eT = endItem.S('top') + endKeyItem.__dom__.offsetTop + endKeyItem.__dom__.clientHeight / 2
// console.log(
// [
// 'M' + sL + ',' + sT,
// 'C' + (sL - eL) / 4 + ',' + (sT - eT) / 4,
// (sL - eL) / 4 * 3 + ',' + (sT - eT) / 4 * 3,
// eL + ',' + eT
// ].join(' ')
// );
svgList.push(
Recard.Dom(document.createElementNS('http://www.w3.org/2000/svg', 'svg')).S(
'position', 'absolute',
'top', 0,
'left', 0,
'@viewBox', [
0, 0,
Recard.WIN.w,
Recard.WIN.h
].join(','),
'>', Recard.Dom(document.createElementNS('http://www.w3.org/2000/svg', 'path')).S(
'@fill', 'none',
'@stroke', 'red',
'@stroke-linecap', 'round',
'@stroke-width', 4,
'@d', [
'M' + sL + ',' + sT,
'C' + sL + ',' + (sT),
sL + ',' + (eT),
///
eL + ',' + eT
].join(' ')
),
'z-index', 0,
'<', 'body'
)
)
}
}
})
})
}
}
return result
})()) | 50.709302 | 125 | 0.311626 |
5e3360ad0b437860d3c6633194f593daec4b0f4c | 4,099 | js | JavaScript | src/shared/lib/geography/country-levels.js | ngolosov/coronadatascraper | 63f503bd32dd4c31fed6fa768bc3817b1f3c90da | [
"BSD-2-Clause"
] | 233 | 2020-03-14T02:10:33.000Z | 2020-03-30T04:17:15.000Z | src/shared/lib/geography/country-levels.js | ngolosov/coronadatascraper | 63f503bd32dd4c31fed6fa768bc3817b1f3c90da | [
"BSD-2-Clause"
] | 515 | 2020-03-30T04:50:31.000Z | 2021-03-31T02:26:22.000Z | src/shared/lib/geography/country-levels.js | ngolosov/coronadatascraper | 63f503bd32dd4c31fed6fa768bc3817b1f3c90da | [
"BSD-2-Clause"
] | 153 | 2020-03-14T17:45:47.000Z | 2020-03-30T02:26:09.000Z | /* eslint-disable no-use-before-define */
import assert from 'assert';
import fips from 'country-levels/fips.json';
import iso1 from 'country-levels/iso1.json';
import iso2 from 'country-levels/iso2.json';
import path from 'path';
import { readJSON } from '../fs.js';
import * as geography from './index.js';
const levels = {
iso1,
iso2,
fips
};
const countryLevelsDir = path.dirname(require.resolve('country-levels/package.json'));
export function isId(str) {
if (Array.isArray(str)) {
return false;
}
if (!str) return false;
const [level, code] = str.split(':');
return level in levels && Boolean(code);
}
export function getIdFromLocation(location) {
const smallestLocationStr = geography.getSmallestLocationStr(location);
return isId(smallestLocationStr) ? smallestLocationStr : null;
}
export function splitId(id) {
assert(isId(id), `Wrong id: ${id}`);
const [level, code] = id.split(':');
return { level, code };
}
const getLevelData = level => {
assert(level in levels, `Country Level ID: not supported ${level}`);
return levels[level];
};
export const getLocationData = id => {
// Return an array of aggregated features
if (id.includes('+')) {
const parts = id.split('+');
const data = parts.map(getLocationData);
return data;
}
const { level, code } = splitId(id);
const levelData = getLevelData(level);
const locationData = levelData[code];
assert(locationData, `Country Level data missing for: ${id}`);
return locationData;
};
export const getFeature = async id => {
const locationData = getLocationData(id);
if (Array.isArray(locationData)) {
const features = await Promise.all(locationData.map(l => getFeature(l.countrylevel_id)));
const newGeometry = combineFeatureGeometry(features);
const newFeature = {
type: 'Feature',
properties: {
name: getName(id),
countrylevel_id: id
},
geometry: newGeometry
};
return newFeature;
}
assert(locationData.geojson_path, `Missing geojson_path for ${id}`);
const geojsonPath = path.join(countryLevelsDir, 'geojson', locationData.geojson_path);
const feature = await readJSON(geojsonPath);
const cleanProps = {
name: feature.properties.name,
countrylevel_id: feature.properties.countrylevel_id
};
feature.properties = cleanProps;
return feature;
};
export const getPopulation = id => {
const locationData = getLocationData(id);
if (Array.isArray(locationData)) {
return locationData.reduce((a, l) => {
a += l.population;
return a;
}, 0);
}
return locationData.population;
};
export const getName = id => {
const locationData = getLocationData(id);
if (Array.isArray(locationData)) {
return locationData.map(l => l.name).join(', ');
}
return locationData.name;
};
export const getTimezone = id => {
const locationData = getLocationData(id);
if (Array.isArray(locationData)) {
return locationData[0].timezone || 'UTC';
}
return locationData.timezone || 'UTC';
};
// this function transforms ids to Id columns and replaces names
// with human readable version
// it mutates the object
export const transformLocationIds = location => {
for (const loc of ['country', 'state', 'county', 'city']) {
const locId = location[loc];
if (isId(locId)) {
location[`${loc}Id`] = locId;
location[loc] = getName(locId);
}
}
};
export const combineFeatureGeometry = features => {
const newGeometry = { type: 'MultiPolygon', coordinates: [] };
for (const feature of features) {
const geomType = feature.geometry.type;
if (geomType === 'Polygon') {
// Wrap the coords in an array so that it looks like a MultiPolygon.
newGeometry.coordinates = newGeometry.coordinates.concat([feature.geometry.coordinates]);
} else if (geomType === 'MultiPolygon') {
newGeometry.coordinates = newGeometry.coordinates.concat(feature.geometry.coordinates);
} else {
throw new Error(`Invalid geometry type ${feature.properties.countrylevel_id} ${geomType}`);
}
}
return newGeometry;
};
| 27.884354 | 97 | 0.68041 |
5e336c397fbe87ff16865d8c1ddbf2c227a0084b | 1,758 | js | JavaScript | src/StateLabel.js | lerebear/components | a83aa5a5b034beacc0f569a4a1b1a171e6b4a78e | [
"MIT"
] | null | null | null | src/StateLabel.js | lerebear/components | a83aa5a5b034beacc0f569a4a1b1a171e6b4a78e | [
"MIT"
] | null | null | null | src/StateLabel.js | lerebear/components | a83aa5a5b034beacc0f569a4a1b1a171e6b4a78e | [
"MIT"
] | null | null | null | import React from 'react'
import PropTypes from 'prop-types'
import styled from 'styled-components'
import {GitMergeIcon, GitPullRequestIcon, IssueClosedIcon, IssueOpenedIcon, QuestionIcon} from '@primer/octicons-react'
import {variant} from 'styled-system'
import theme from './theme'
import {COMMON, get} from './constants'
import StyledOcticon from './StyledOcticon'
import sx from './sx'
const octiconMap = {
issueOpened: IssueOpenedIcon,
pullOpened: GitPullRequestIcon,
issueClosed: IssueClosedIcon,
pullClosed: GitPullRequestIcon,
pullMerged: GitMergeIcon,
draft: GitPullRequestIcon,
}
const colorVariants = variant({
prop: 'status',
scale: 'stateLabels.status',
})
const sizeVariants = variant({
prop: 'variant',
scale: 'stateLabels.sizes',
})
const StateLabelBase = styled.span`
display: inline-flex;
align-items: center;
font-weight: 600;
line-height: 16px;
color: ${get('colors.white')};
text-align: center;
border-radius: ${get('radii.3')};
${colorVariants};
${sizeVariants};
${COMMON};
${sx};
`
function StateLabel({children, status, variant, ...rest}) {
const octiconProps = variant === 'small' ? {width: '1em'} : {}
return (
<StateLabelBase {...rest} variant={variant} status={status}>
{status && <StyledOcticon mr={1} {...octiconProps} icon={octiconMap[status] || QuestionIcon} />}
{children}
</StateLabelBase>
)
}
StateLabel.defaultProps = {
theme,
variant: 'normal',
}
StateLabel.propTypes = {
status: PropTypes.oneOf(['issueOpened', 'pullOpened', 'issueClosed', 'pullClosed', 'pullMerged', 'draft']).isRequired,
theme: PropTypes.object,
variant: PropTypes.oneOf(['small', 'normal']),
...COMMON.propTypes,
...sx.propTypes,
}
export default StateLabel
| 25.852941 | 120 | 0.700228 |