text
stringlengths 7
3.69M
|
|---|
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(['module', 'exports', './polyfills', './constants', './utils', './logger', './events', './keymaps'], factory);
} else if (typeof exports !== "undefined") {
factory(module, exports, require('./polyfills'), require('./constants'), require('./utils'), require('./logger'), require('./events'), require('./keymaps'));
} else {
var mod = {
exports: {}
};
factory(mod, mod.exports, global.polyfills, global.constants, global.utils, global.logger, global.events, global.keymaps);
global.humaninput = mod.exports;
}
})(this, function (module, exports, _polyfills, _constants, _utils, _logger, _events, _keymaps) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
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;
};
}();
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;
}
(0, _polyfills.polyfill)(); // Won't do anything unless we execute it
// Remove this line if you don't care about Safari keyboard support:
// Removing this saves ~1.3k in minified output!
// Sandbox-side variables and shortcuts
// const window = this;
var _HI = window.HumanInput; // For noConflict
var screen = window.screen;
var document = window.document;
// NOTE: "blur", "reset", and "submit" are all just handled via _genericEvent()
var defaultEvents = ["blur", "click", "compositionend", "compositionstart", "compositionupdate", "contextmenu", "focus", "hold", "input", "keydown", "keypress", "keyup", "reset", "submit"];
var instances = [];
var plugins = [];
// Lesser state tracking variables
var lastDownLength = 0;
var finishedKeyCombo = false; // Used with combos like ctrl-c
// Check if the browser supports KeyboardEvent.key:
var KEYSUPPORT = false;
if (Object.keys(window.KeyboardEvent.prototype).includes('key')) {
KEYSUPPORT = true;
}
var HumanInput = function (_EventHandler) {
_inherits(HumanInput, _EventHandler);
// Core API functions
function HumanInput(elem, settings) {
var _settings$listenEvent;
_classCallCheck(this, HumanInput);
// These are the defaults:
var defaultSettings = {
listenEvents: HumanInput.defaultListenEvents,
addEvents: [],
removeEvents: [],
eventOptions: {},
noKeyRepeat: true,
sequenceTimeout: 3500,
holdInterval: 250,
maxSequenceBuf: 12,
uniqueNumpad: false,
swipeThreshold: 50,
moveThreshold: 5,
disableSequences: false,
disableSelectors: false,
eventMap: {},
translate: _utils.noop,
logLevel: 'INFO',
logPrefix: (0, _utils.getLoggingName)(elem)
};
// Apply settings over the defaults:
for (var item in settings) {
defaultSettings[item] = settings[item];
}
settings = defaultSettings;
var log = new _logger.Logger(settings.logLevel, settings.logPrefix);
var _this = _possibleConstructorReturn(this, _EventHandler.call(this, log));
// Interestingly, you can't just return an existing instance if you haven't called super() yet
// (may be a WebPack thing) which is why this is down here and not at the top of the constructor:
if (instances.length) {
// Existing instance(s); check them for duplicates on the same element
for (var inst in instances) {
if (instances[inst].elem === elem) {
var _ret;
return _ret = instances[inst], _possibleConstructorReturn(_this, _ret); // Enforce singleton per element (efficiency!)
}
}
}
instances.push(_this); // Used when enforcing singletons
// For localization of our few strings:
_this.l = settings.translate;
(_settings$listenEvent = settings.listenEvents).push.apply(_settings$listenEvent, settings.addEvents);
if (settings.removeEvents.length) {
settings.listenEvents = settings.listenEvents.filter(function (item) {
return !settings.removeEvents.includes(item);
});
}
_this.settings = settings;
_this.elem = (0, _utils.getNode)(elem || window);
_this.Logger = _logger.Logger; // In case someone wants to use it separately
_this.log = log;
_this.VERSION = __VERSION__;
_this.plugin_instances = []; // Each instance of HumanInput gets its own set of plugin instances
// NOTE: Most state-tracking variables are set inside HumanInput.init()
// This needs to be set early on so we don't get errors in the early trigger() calls:
_this.eventMap = { forward: {}, reverse: {} };
// NOTE: keyMaps are only necessary for Safari
_this.keyMaps = { 0: {}, 1: {}, 2: {} };
if (_keymaps.keyMaps) {
_this.keyMaps = _keymaps.keyMaps;
}
// Apply some post-instantiation settings
if (settings.disableSequences) {
_this._handleSeqEvents = _utils.noop;
}
if (settings.disableSelectors) {
_this._handleSelectors = _utils.noop;
}
// These functions need to be bound to work properly ('this' will be window or this.elem which isn't what we want)
['_composition', '_contextmenu', '_holdCounter', '_resetSeqTimeout', '_resetStates', '_keydown', '_keypress', '_keyup', 'trigger'].forEach(function (event) {
_this[event] = _this[event].bind(_this);
});
// Take care of our multi-function functions :)
_this._compositionstart = _this._composition;
_this._compositionupdate = _this._composition;
_this._compositionend = _this._composition;
// Add some generic window/document events so plugins don't need to handle
// them on their own; it's better to have *one* listener.
if (typeof document.hidden !== "undefined") {
document.addEventListener('visibilitychange', function (e) {
if (document.hidden) {
_this.trigger('document:hidden', e);
} else {
_this.trigger('document:visible', e);
}
}, false);
}
var genericHandler = _this._genericEvent.bind(_this, 'window');
// Window focus and blur are also almost always user-initiated:
if (window.onblur !== undefined) {
(0, _utils.addListeners)(window, ['blur', 'focus'], genericHandler, true);
}
if (_this.elem === window) {
// Only attach window events if HumanInput was instantiated on the 'window'
// These events are usually user-initiated so they count:
(0, _utils.addListeners)(window, ['beforeunload', 'hashchange', 'languagechange'], genericHandler, true);
// Window resizing needs some de-bouncing or you end up with far too many events being fired while the user drags:
window.addEventListener('resize', (0, _utils.debounce)(genericHandler, 250), true);
// Orientation change is almost always human-initiated:
if (window.orientation !== undefined) {
window.addEventListener('orientationchange', function (e) {
var event = 'window:orientation';
_this.trigger(event, e);
// NOTE: There's built-in aliases for 'landscape' and 'portrait'
if (Math.abs(window.orientation) === 90) {
_this.trigger(event + ':landscape', e);
} else {
_this.trigger(event + ':portrait', e);
}
}, false);
}
}
// Start er up!
_this.init();
return _this;
}
HumanInput.prototype.map = function map(eventMap) {
/**:HumanInput.map(eventMap)
This function will update ``this.eventMap`` with the given *obj*'s keys and values and then with it's values and keys (so lookups can be performed in reverse).
*/
for (var item in eventMap) {
// Create both forward and reverse mappings
this.eventMap.forward[item] = eventMap[item];
this.eventMap.reverse[eventMap[item]] = item;
}
};
HumanInput.prototype.init = function init() {
var _this2 = this;
var settings = this.settings;
var listenEvents = settings.listenEvents;
var debug = this.log.debug;
if (this.eventCount) {
// It already exists/reset scenario
// This is so a reset can be detected and handled properly by external stuff
this.trigger('hi:reset');
}
this.scope = ''; // The current event scope (empty string means global scope)
this.state = { // Stores temporary/fleeting state information
down: [], // Tracks which keys/buttons are currently held down (pressed)
downAlt: [], // Used to keep keydown and keyup events in sync when the 'key' gets replaced inside the keypress event
holdStart: null, // Tracks the start time of hold events
holdArgs: [], // Keeps track of arguments that will be passed to hold events
seqBuffer: [] // For tracking sequences like 'a b c'
};
this.events = {}; // Tracks functions attached to events
// The eventMap can be used to change the name of triggered events (e.g. 'w': 'forward')
this.eventMap = { forward: {}, reverse: {} };
this.map(settings.eventMap); // Apply any provided eventMap
// NOTE: Possible new feature: Transform events using registerable functions:
// this.transforms = []; // Used for transforming event names
finishedKeyCombo = false; // Internal state tracking of keyboard combos like ctrl-c
// Setup our basic window listen events
// This tries to emulate fullscreen detection since the Fullscreen API doesn't friggin' work when the user presses F11 or selects fullscreen from the menu...
if (this.elem === window) {
this.on('window:resize', function () {
// NOTE: This may not work with multiple monitors
if (window.outerWidth === screen.width && window.outerHeight === screen.height) {
_this2.state.fullscreen = true;
_this2.trigger('fullscreen', true);
} else if (_this2.state.fullscreen) {
_this2.state.fullscreen = false;
_this2.trigger('fullscreen', false);
}
});
}
// Reset states if the user alt-tabs away (or similar)
this.on('window:blur', this._resetStates);
// Enable plugins
for (var i = 0; i < plugins.length; i++) {
// Instantiate the plugin (if not already)
if (!(this.plugin_instances[i] instanceof plugins[i])) {
this.plugin_instances[i] = new plugins[i](this);
}
var plugin = this.plugin_instances[i];
debug(this.l('Initializing Plugin:'), plugin.constructor.name);
if ((0, _utils.isFunction)(plugin.init)) {
var initResult = plugin.init(this);
for (var attr in initResult.exports) {
this[attr] = initResult.exports[attr];
}
}
}
// Set or reset our event listeners (enables changing built-in events at a later time)
this.off('hi:pause');
this.on('hi:pause', function () {
debug(_this2.l('Pause: Removing event listeners ', listenEvents));
listenEvents.forEach(function (event) {
var opts = settings.eventOptions[event] || true;
if ((0, _utils.isFunction)(_this2['_' + event])) {
_this2.elem.removeEventListener(event, _this2['_' + event], opts);
}
});
});
this.off(['hi:initialized', 'hi:resume']); // In case of re-init
this.on(['hi:initialized', 'hi:resume'], function () {
debug('HumanInput Version: ' + _this2.VERSION);
debug(_this2.l('Start/Resume: Addding event listeners'), listenEvents);
listenEvents.forEach(function (event) {
var opts = settings.eventOptions[event] || true;
if ((0, _utils.isFunction)(_this2['_' + event])) {
// TODO: Figure out why removeEventListener isn't working
_this2.elem.removeEventListener(event, _this2['_' + event], opts);
_this2.elem.addEventListener(event, _this2['_' + event], opts);
} else {
// No function for this event; use the generic event handler and hope for the best
_this2['_' + event] = _this2._genericEvent.bind(_this2, '');
_this2.elem.addEventListener(event, _this2['_' + event], opts);
}
});
});
this.trigger('hi:initialized', this);
};
HumanInput.prototype.noConflict = function noConflict() {
window.HumanInput = _HI;
return HumanInput;
};
HumanInput.prototype._resetStates = function _resetStates() {
// This gets called after the sequenceTimeout to reset the state of all keys and modifiers (and a few other things)
// Besides the obvious usefulness of this with sequences, it also serves as a fallback mechanism if something goes
// wrong with state tracking.
// NOTE: As long as something is 'down' this won't (normally) be called because the sequenceTimeout gets cleared on 'down' events and set on 'up' events.
var state = this.state;
state.seqBuffer = [];
state.down = [];
state.downAlt = [];
state.holdArgs = [];
lastDownLength = 0;
finishedKeyCombo = false;
clearTimeout(state.holdTimeout);
this.trigger('hi:resetstates');
};
HumanInput.prototype._resetSeqTimeout = function _resetSeqTimeout() {
var _this3 = this;
// Ensure that the seqBuffer doesn't get emptied (yet):
clearTimeout(this.state.seqTimer);
this.state.seqTimer = setTimeout(function () {
_this3.log.debug(_this3.l('Resetting event sequence states due to timeout'));
_this3._resetStates();
}, this.settings.sequenceTimeout);
};
HumanInput.prototype._genericEvent = function _genericEvent(prefix, e) {
// Can be used with any event handled via addEventListener() to trigger a corresponding event in HumanInput
var notFiltered = this.filter(e),
results;
if (notFiltered) {
if (prefix.type) {
e = prefix;prefix = null;
}
if (prefix) {
prefix = prefix + ':';
} else {
prefix = '';
}
results = this.trigger(this.scope + prefix + e.type, e);
if (e.target) {
// Also triger events like '<event>:#id' or '<event>:.class':
results = results.concat(this._handleSelectors(prefix + e.type, e));
}
(0, _utils.handlePreventDefault)(e, results);
}
};
HumanInput.prototype._handleSelectors = function _handleSelectors(eventName) {
// Triggers the given *eventName* using various combinations of information taken from the given *e.target*.
var results = [];
var args = Array.from(arguments).slice(1);
var toBind = this; // A fallback
var constructedEvent;
if (args[0] && args[0].target) {
toBind = args[0].target;
if (toBind.id) {
constructedEvent = eventName + ':#' + toBind.id;
results = this.trigger.apply(toBind, [constructedEvent].concat(args));
}
if (toBind.classList && toBind.classList.length) {
for (var i = 0; i < toBind.classList.length; i++) {
constructedEvent = eventName + ':.' + toBind.classList.item(i);
results = results.concat(this.trigger.apply(toBind, [constructedEvent].concat(args)));
}
}
}
return results;
};
HumanInput.prototype._addDown = function _addDown(event, alt) {
// Adds the given *event* to this.state.down and this.state.downAlt to ensure the two stay in sync in terms of how many items they hold.
// If an *alt* event is given it will be stored in this.state.downAlt explicitly
var state = this.state;
var index = state.down.indexOf(event);
if (index == -1) {
index = state.downAlt.indexOf(event);
}
if (index == -1 && alt) {
index = state.downAlt.indexOf(alt);
}
if (index == -1) {
state.down.push(event);
if (alt) {
state.downAlt.push(alt);
} else {
state.downAlt.push(event);
}
}
this.trigger('hi:adddown', event, alt); // So plugins and modules can do stuff when this happens
};
HumanInput.prototype._removeDown = function _removeDown(event) {
// Removes the given *event* from this.state.down and this.state.downAlt (if found); keeping the two in sync in terms of indexes
var state = this.state;
var settings = this.settings;
var down = state.down;
var downAlt = state.downAlt;
var index = state.down.indexOf(event);
clearTimeout(state.holdTimeout);
if (index === -1) {
// Event changed between 'down' and 'up' events
index = downAlt.indexOf(event);
}
if (index === -1) {
// Still no index? Try one more thing: Upper case
index = downAlt.indexOf(event.toUpperCase()); // Handles the situation where the user releases a key *after* a Shift key combo
}
if (index !== -1) {
down.splice(index, 1);
downAlt.splice(index, 1);
}
lastDownLength = down.length;
if (settings.listenEvents.includes('hold')) {
state.holdArgs.pop();
state.heldTime = settings.holdInterval;
state.holdStart = Date.now(); // This needs to be reset whenever this.state.down changes
if (down.length) {
// Continue 'hold' events for any remaining 'down' events
state.holdTimeout = setTimeout(this._holdCounter, settings.holdInterval);
}
}
this.trigger('hi:removedown', event); // So plugins and modules can do stuff when this happens
};
HumanInput.prototype._doDownEvent = function _doDownEvent(event) {
/*
Adds the given *event* to this.state.down, calls this._handleDownEvents(), removes the event from this.state.down, then returns the triggered results.
Any additional arguments after the given *event* will be passed to this._handleDownEvents().
*/
var args = Array.from(arguments).slice(1);
this._addDown(event);
var results = this._handleDownEvents.apply(this, args);
this._handleSeqEvents(args[0]); // args[0] will be the browser event
this._removeDown(event);
return results;
};
HumanInput.prototype._keyEvent = function _keyEvent(key) {
// Given a *key* like 'ShiftLeft' returns the "official" key event or just the given *key* in lower case
if (_constants.CONTROLKEYS.includes(key)) {
return _constants.ControlKeyEvent;
} else if (_constants.ALTKEYS.includes(key)) {
return _constants.AltKeyEvent;
} else if (_constants.SHIFTKEYS.includes(key)) {
return _constants.ShiftKeyEvent;
} else if (_constants.OSKEYS.includes(key)) {
return _constants.OSKeyEvent;
} else {
return key.toLowerCase();
}
};
HumanInput.prototype._contextmenu = function _contextmenu(e) {
if (this.filter(e)) {
var results = this._triggerWithSelectors(e.type, [e]);
/* NOTE: Unless the contextmenu is cancelled (i.e. preventDefault) we need to ensure that we reset all 'down' events.
The reason for this is because when the context menu comes up in the browser it immediately loses track of all
keys/buttons just like if the user were to alt-tab to a different application; the 'up' events will never fire.
*/
if (!(0, _utils.handlePreventDefault)(e, results)) {
this._resetStates();
}
}
};
HumanInput.prototype._handleShifted = function _handleShifted(down) {
/* A DRY function to remove the shift key from *down* if warranted (e.g. just ['!'] instead of ['ShiftLeft', '!']). Returns true if *down* was modified.
Note that *down* should be a copy of ``this.state.down`` and not the actual ``this.state.down`` array.
*/
var lastItemIndex = down.length - 1;
var shiftKeyIndex = -1;
for (var i = 0; i < down.length; i++) {
shiftKeyIndex = down[i].indexOf('Shift');
if (shiftKeyIndex != -1) {
break;
}
}
if (shiftKeyIndex != -1) {
// The last key in the 'down' array is all we care about...
// Use the difference between the 'key' and 'code' (aka the 'alt' name) to detect chars that require shift but aren't uppercase:
if (down[lastItemIndex] != this.state.downAlt[lastItemIndex]) {
down.splice(shiftKeyIndex, 1); // Remove the shift key
return true; // We're done here
}
}
};
HumanInput.prototype._handleDownEvents = function _handleDownEvents() {
var settings = this.settings;
var state = this.state;
var events = this._downEvents();
var results = [];
var args = Array.from(arguments);
for (var i = 0; i < events.length; i++) {
results = results.concat(this._triggerWithSelectors(events[i], args));
}
if (settings.listenEvents.includes('hold')) {
state.holdArgs.push(args);
state.heldTime = settings.holdInterval; // Restart it
state.holdStart = Date.now();
// Start the 'hold:' counter! If no changes to this.state.down, fire a hold:<n>:<event> event for every second the down events are held
clearTimeout(state.holdTimeout); // Just in case
state.holdTimeout = setTimeout(this._holdCounter, settings.holdInterval);
}
return results;
};
HumanInput.prototype._handleSeqEvents = function _handleSeqEvents(e) {
// NOTE: This function should only be called when a button or key is released (i.e. when state changes to UP)
var state = this.state;
var seqBuffer = state.seqBuffer;
var results = [];
var down = state.down.slice(0);
if (lastDownLength < down.length) {
// User just finished a combo (e.g. ctrl-a)
if (this.sequenceFilter(e)) {
this._handleShifted(down);
(0, _utils.sortEvents)(down);
seqBuffer.push(down);
if (seqBuffer.length > this.settings.maxSequenceBuf) {
// Make sure it stays within the specified max
seqBuffer.shift();
}
if (seqBuffer.length > 1) {
// Trigger all combinations of sequence buffer events
var combos = this._seqCombinations(seqBuffer);
for (var i = 0; i < combos.length; i++) {
var sliced = (0, _utils.seqSlicer)(combos[i]);
for (var j = 0; j < sliced.length; j++) {
results = results.concat(this.trigger(this.scope + sliced[j], this));
}
}
if (results.length) {
// Reset the sequence buffer on matched event so we don't end up triggering more than once per sequence
seqBuffer = [];
}
}
}
}
this._resetSeqTimeout();
};
HumanInput.prototype._normSpecial = function _normSpecial(location, key, code) {
// Just a DRY function for keys that need some extra love
if (key == ' ') {
// Spacebar
return code; // The code for spacebar is 'Space'
}
if (code.hasOwnProperty('includes')) {
// This check was put here to resolve the edge case in issue #14 (https://github.com/liftoff/HumanInput/issues/14)
if (code.includes('Left') || code.includes('Right')) {
// Use the left and right variants of the name as the 'key'
key = code; // So modifiers can be more specific
}
}
if (this.settings.uniqueNumpad && location === 3) {
return 'numpad' + key; // Will be something like 'numpad5' or 'numpadenter'
}
if (key.startsWith('Arrow')) {
key = key.substr(5); // Remove the 'arrow' part
}
return key;
};
HumanInput.prototype._holdCounter = function _holdCounter() {
// This function triggers 'hold' events every <holdInterval ms> when events are 'down'.
var state = this.state;
var settings = this.settings;
var events = this._downEvents();
if (!events.length) {
return;
}
clearTimeout(state.holdTimeout);
var lastArg = state.holdArgs[state.holdArgs.length - 1] || [];
var realHeldTime = Date.now() - state.holdStart;
this._resetSeqTimeout(); // Make sure the sequence buffer reset function doesn't clear out our hold times
for (var i = 0; i < events.length; i++) {
// This is mostly so plugins and whatnot can do stuff when hold events are triggered
this.trigger('hold', events[i], realHeldTime);
// This is the meat of hold events:
this._triggerWithSelectors('hold:' + state.heldTime + ':' + events[i], lastArg.concat([realHeldTime]));
}
state.heldTime += settings.holdInterval;
if (state.heldTime < 5001) {
// Any longer than this and it probably means something went wrong (e.g. browser bug with touchend not firing)
state.holdTimeout = setTimeout(this._holdCounter, settings.holdInterval);
}
};
HumanInput.prototype._triggerWithSelectors = function _triggerWithSelectors(event, args) {
// A DRY function that triggers the given *event* normally and then via this._handleSelectors()
var results = [];
var scopedEvent = this.scope + event;
results = results.concat(this.trigger.apply(this, [scopedEvent].concat(args)));
results = results.concat(this._handleSelectors.apply(this, [scopedEvent].concat(args)));
return results;
};
HumanInput.prototype._seqCombinations = function _seqCombinations(buffer, joinChar) {
/**:HumanInput._seqCombinations(buffer[, joinChar])
Returns all possible alternate name combinations of events (as an Array) for a given buffer (*buffer*) which must be an Array of Arrays in the form of::
[['ControlLeft', 'c'], ['a']]
The example above would be returned as an Array of strings that can be passed to :js:func:`utils.seqSlicer` like so::
['controlleft-c a', 'ctrl-c a']
The given *joinChar* will be used to join the characters for key combinations.
.. note:: Events will always be emitted in lower case. To use events with upper case letters use the 'shift' modifier (e.g. 'shift-a'). Shifted letters that are not upper case do not require the 'shift' modifier (e.g. '?'). This goes for combinations that include other modifiers (e.g. 'ctrl-#' would not be 'ctrl-shift-3').
*/
var i, j;
var joinChar_ = joinChar || '-';
var replacement = (0, _utils.cloneArray)(buffer);
var out = [];
var temp = [];
for (i = 0; i < buffer.length; i++) {
out.push(replacement[i].join(joinChar_).toLowerCase());
// Normalize names (shiftleft becomes shift)
for (j = 0; j < buffer[i].length; j++) {
replacement[i][j] = [this._keyEvent(buffer[i][j])];
}
}
out = [out.join(' ')]; // Make a version that has the original key/modifier names (e.g. shiftleft)
for (i = 0; i < replacement.length; i++) {
if (replacement[i].length) {
temp.push((0, _utils.arrayCombinations)(replacement[i], joinChar_));
}
}
for (i = 0; i < temp.length; i++) {
temp[i] = this.eventMap.forward[temp[i]] || temp[i];
}
temp = temp.join(' ');
if (temp != out[0]) {
// Only if they're actually different
out.push(temp);
}
return out;
};
HumanInput.prototype._downEvents = function _downEvents() {
/* Returns all events that could represent the current state of ``this.state.down``. e.g. ['shiftleft-a', 'shift-a'] but not ['shift', 'a']
*/
var events = [];
var shiftedKey;
var down = this.state.down.slice(0); // Make a copy because we're going to mess with it
var downLength = down.length; // Need the original length for reference
var unshiftedDown = this.state.downAlt.slice(0); // The 'alt' chars (from the code) represent the un-shifted form of the key
if (downLength) {
if (downLength === 1) {
return this._seqCombinations([down]);
}
if (downLength > 1) {
// Combo; may need shift key removed to generate the correct event (e.g. '!' instead of 'shift-!')
shiftedKey = this._handleShifted(down);
// Before sorting, fire the precise combo event
events = events.concat(this._seqCombinations([down], '->'));
if (shiftedKey) {
// Generate events for the un-shifted chars (e.g. shift->1, shift->2, etc)
events = events.concat(this._seqCombinations([unshiftedDown], '->'));
}
}
if (down.length > 1) {
// Is there more than one item *after* we may have removed shift?
(0, _utils.sortEvents)(down);
// Make events for all alternate names (e.g. 'controlleft-a' and 'ctrl-a'):
events = events.concat(this._seqCombinations([down]));
}
if (shiftedKey) {
(0, _utils.sortEvents)(unshiftedDown);
events = events.concat(this._seqCombinations([unshiftedDown]));
}
}
return events;
};
HumanInput.prototype._keydown = function _keydown(e) {
// NOTE: e.which and e.keyCode will be incorrect for a *lot* of keys
// and basically always incorrect with alternate keyboard layouts
// which is why we replace this.state.down[<the key>] inside _keypress()
// when we can (for browsers that don't support KeyboardEvent.key).
var state = this.state;
var results;
var keyCode = e.which || e.keyCode;
var location = e.location || 0;
// NOTE: Should I put e.code first below? Hmmm. Should we allow keyMaps to override the browser's native key name if it's available?
var code = this.keyMaps[location][keyCode] || this.keyMaps[0][keyCode] || e.code;
var key = e.key || code;
var event = e.type;
var notFiltered = this.filter(e);
var fpEvent = this.scope + 'faceplant';
if (e.repeat && notFiltered && this.settings.noKeyRepeat) {
e.preventDefault(); // Make sure keypress doesn't fire after this
return false; // Don't do anything if key repeat is disabled
}
key = this._normSpecial(location, key, code);
if (key == 'Compose') {
// This indicates that the user is entering a composition
state.composing = true;
return;
}
if (!state.down.includes(key)) {
this._addDown(key, code);
}
// Don't let the sequence buffer reset if the user is active:
this._resetSeqTimeout();
if (notFiltered) {
// This is in case someone wants just on('keydown'):
results = this._triggerWithSelectors(event, [e, key, code]);
// Now trigger the more specific keydown:<key> event:
results = results.concat(this._triggerWithSelectors(event += ':' + key.toLowerCase(), [e, key, code]));
if (state.down.length > 5) {
// 6 or more keys down at once? FACEPLANT!
results = results.concat(this.trigger(fpEvent, e)); // ...or just key mashing :)
}
/* NOTE: For browsers that support KeyboardEvent.key we can trigger the usual
events inside _keydown() (which is faster) but other browsers require
_keypress() be called first to fix localized/shifted keys. So for those
browser we call _handleDownEvents() inside _keyup(). */
if (KEYSUPPORT) {
results = results.concat(this._handleDownEvents(e, key, code));
}
(0, _utils.handlePreventDefault)(e, results);
}
};
HumanInput.prototype._keypress = function _keypress(e) {
// NOTE: keypress events don't always fire when modifiers are used!
// This means that such browsers may never get sequences like 'ctrl-?'
var charCode = e.charCode || e.which,
key = e.key || String.fromCharCode(charCode);
if (!KEYSUPPORT && charCode > 47 && key.length) {
// Replace the possibly-incorrect key with the correct one
this.state.down.pop();
this.state.down.push(key);
}
};
HumanInput.prototype._keyup = function _keyup(e) {
var state = this.state;
var results;
var keyCode = e.which || e.keyCode;
var location = e.location || 0;
// NOTE: Should I put e.code first below? Hmmm. Should we allow keyMaps to override the browser's native key name if it's available?
var code = this.keyMaps[location][keyCode] || this.keyMaps[0][keyCode] || e.code;
var key = e.key || code;
var event = e.type;
key = this._normSpecial(location, key, code);
if (_constants.MACOS) {
/* Macs have a bug where the keyup event doesn't fire for non-modifier keys if the command key
was held during a combo.
To prevent this from mis-firing hold events and ensure that state stays sane we have to
*assume* that any non-modifier keys are no longer being held after the command key is released.
Note to Apple: Fix your OS! */
if (_constants.OSKEYS.includes(key)) {
// It's the command key
var toRemove = [];
// Reset any non-modifier keys in this.state.down
for (var i = 0; i < state.down.length; i++) {
if (!_constants.AllModifiers.includes(state.down[i])) {
toRemove.push(state.down[i]);
}
}
for (var _i = 0; _i < toRemove.length; _i++) {
this._removeDown(toRemove[_i]);
}
}
}
if (!state.downAlt.length) {
// Implies key states were reset or out-of-order somehow
return; // Don't do anything since our state is invalid
}
if (state.composing) {
state.composing = false;
return;
}
if (this.filter(e)) {
if (!KEYSUPPORT) {
this._handleDownEvents(e);
}
// This is in case someone wants just on('keyup'):
results = this._triggerWithSelectors(event, [e, key, code]);
// Now trigger the more specific keyup:<key> event:
results = results.concat(this._triggerWithSelectors(event + ':' + key.toLowerCase(), [e, key, code]));
this._handleSeqEvents(e);
(0, _utils.handlePreventDefault)(e, results);
}
// Remove the key from this.state.down even if we're filtered (state must stay accurate)
this._removeDown(key);
};
HumanInput.prototype._composition = function _composition(e) {
var data = e.data;
var event = 'compos';
if (this.filter(e)) {
var results = this._triggerWithSelectors(e.type, [e, data]);
if (data) {
if (e.type == 'compositionupdate') {
event += 'ing:"' + data + '"';
} else if (e.type == 'compositionend') {
event += 'ed:"' + data + '"';
}
results = results.concat(this._triggerWithSelectors(event, [e]));
(0, _utils.handlePreventDefault)(e, results);
}
}
};
HumanInput.prototype.filter = function filter(event) {
/**:HumanInput.filter(event)
This function gets called before HumanInput events are triggered. If it returns ``False`` then ``trigger()`` will not be called.
Override this function to implement your own filter.
.. note:: The given *event* won't always be a browser-generated event but it should always have a 'type' and 'target'.
*/
var tagName = (event.target || event.srcElement).tagName,
// The events we're concerned with:
keyboardEvents = ['keydown', 'keyup', 'keypress'];
if (event.type && keyboardEvents.includes(event.type)) {
// Don't trigger keyboard events if the user is typing into a form
return !(tagName == 'INPUT' || tagName == 'SELECT' || tagName == 'TEXTAREA');
}
return true;
};
HumanInput.prototype.sequenceFilter = function sequenceFilter(event) {
/**:HumanInput.sequenceFilter(event)
This function gets called before HumanInput events are added to the sequence buffer. If it returns ``False`` then the event will not be added to the sequence buffer.
Override this function to implement your own filter.
.. note:: The given *event* won't always be a browser-generated event but it should always have a 'type' and 'target'.
*/
return true; // Don't filter out anything
};
HumanInput.prototype.pushScope = function pushScope(scope) {
/**:HumanInput.pushScope(scope)
Pushes the given *scope* into HumanInput.scope. Examples::
> HI = HumanInput(window);
> HI.pushScope('foo');
> HI.scope;
'foo:'
> HI.pushScope('bar');
> HI.scope;
'foo.bar:'
*/
if (this.scope.length) {
this.scope = this.scope.slice(0, -1) + '.' + scope + ':';
} else {
this.scope = scope + ':';
}
};
HumanInput.prototype.popScope = function popScope() {
/**:HumanInput.popScope()
Pops (and returns) the last scope out of HumanInput.scope. Examples::
> HI = HumanInput(window);
> HI.scope;
'foo.bar:'
> HI.popScope();
> HI.scope;
'foo:'
> HI.popScope();
> HI.scope;
''
*/
if (this.scope.length) {
this.scope = this.scope.slice(0, -1).split('.').slice(0, -1).join('.') + ':';
}
if (this.scope == ':') {
this.scope = '';
}
};
HumanInput.prototype.pause = function pause() {
/**:HumanInput.pause()
Halts all triggering of events until :js:func:`HumanInput.resume` is called.
*/
this.state.paused = true;
this.trigger('hi:pause', this);
};
HumanInput.prototype.resume = function resume() {
/**:HumanInput.resume()
Restarts triggering of events after a call to :js:func:`HumanInput.pause`.
*/
this.state.paused = false;
this.trigger('hi:resume', this);
};
HumanInput.prototype.startRecording = function startRecording() {
/**:HumanInput.startRecording()
Starts recording all triggered events. The array of recorded events will be returned when :js:func:`HumanInput.stopRecording` is called.
.. note:: You can tell if HumanInput is currently recording events by examining the ``HI.recording`` (instance) attribute (boolean).
.. warning:: Don't leave the recording running for too long as there's no limit to how big it can get!
*/
this.state.recording = true;
this.state.recordedEvents = [];
};
HumanInput.prototype.stopRecording = function stopRecording(filter) {
/**:HumanInput.stopRecording([filter])
Returns an array of all the events that were triggered since :js:func:`HumanInput.startRecording` was called. If a *filter* (String) is given it will be used to limit what gets returned. Example::
HI.startRecording();
// User types ctrl-a followed by ctrl-s
events = HI.stopRecording('-(?!\\>)'); // Only return events that contain '-' (e.g. combo events) but not '->' (ordered combos)
["controlleft-a", "ctrl-a", "controlleft-s", "ctrl-s", "controlleft-a controlleft-s", "ctrl-a ctrl-s"]
Alternatively, if ``filter == 'keystroke'`` the first completed keystroke (e.g. ``ctrl-b``) typed by the user will be returned. Here's an example demonstrating how this can be used with :js:func:`HumanInput.once` to capture a keystroke::
HI.startRecording();
HI.once('keyup', (e) => {
var keystroke = HI.stopRecording('keystroke');
HI.log.info('User typed:', keystroke, e);
});
.. note:: You can call ``stopRecording()`` multiple times after a recording to try different filters or access the array of recorded events.
*/
var keystroke;
var recordedEvents = this.state.recordedEvents;
var regex = new RegExp(filter);
var hasSelector = function hasSelector(str) {
return !(str.includes(':#') || str.includes(':.'));
};
this.state.recording = false;
if (!filter) {
return recordedEvents;
}
if (filter == 'keystroke') {
// Filter out events with selectors since we don't want those for this sort of thing:
var filteredEvents = recordedEvents.filter(hasSelector);
// Return the event that comes before the last 'keyup'
regex = new RegExp('keyup');
for (var i = 0; i < filteredEvents.length; i++) {
if (regex.test(filteredEvents[i])) {
break;
}
keystroke = filteredEvents[i];
}
return keystroke;
}
// Apply the filter
var events = recordedEvents.filter(function (item) {
return regex.test(item);
});
return events;
};
HumanInput.prototype.getSelText = function getSelText() {
/**:HumanInput.getSelText()
:returns: The text that is currently highlighted in the browser.
Example:
HumanInput.getSelText();
"localhost" // Assuming the user had highlighted the word, "localhost"
*/
var txt = '';
if (window.getSelection) {
txt = window.getSelection();
} else if (document.selection) {
txt = document.selection.createRange().text;
} else {
return;
}
return txt.toString();
};
HumanInput.prototype.isDown = function isDown(name) {
/**:HumanInput.isDown(name)
Returns ``true`` if the given *name* (string) is currently held (aka 'down' or 'pressed'). It works with any kind of key or button as well as combos such as, 'ctrl-a'. It also works with ``this.eventMap`` if you've remapped any events (e.g. ``HI.isDown('fire') == true``).
.. note:: Strings are used to track keys because key codes are browser and platform dependent (unreliable).
*/
var state = this.state;
var downEvents = this._downEvents();
name = name.toLowerCase();
name = this.eventMap.reverse[name] || name;
if (downEvents.includes(name)) {
return true;
}
for (var i = 0; i < state.down.length; i++) {
var down = state.down[i].toLowerCase();
var downAlt = state.downAlt[i].toLowerCase(); // In case something changed between down and up events
if (name == down || name == downAlt) {
return true;
} else if (_constants.SHIFTKEYS.includes(state.down[i])) {
if (name == _constants.ShiftKeyEvent) {
return true;
}
} else if (_constants.CONTROLKEYS.includes(state.down[i])) {
if (name == _constants.ControlKeyEvent) {
return true;
}
} else if (_constants.ALTKEYS.includes(state.down[i])) {
if (name == _constants.AltKeyEvent) {
return true;
}
} else if (_constants.OSKEYS.includes(state.down[i])) {
if (name == _constants.OSKeyEvent) {
return true;
}
}
}
return false;
};
HumanInput.prototype.getDown = function getDown() {
/**:HumanInput.getDown()
...and boogie! Returns the current state of all keys/buttons/whatever inside the ``this.state.down`` array in a user friendly format. For example, if the user is holding down the shift, control, and 'i' this function would return 'ctrl-shift-i' (it will always match HumanInput's event ordering). The results it returns will always be lowercase.
.. note:: This function does not return location-specific names like 'shiftleft'. It will always use the short name (e.g. 'shift').
*/
var down = (0, _utils.sortEvents)(this.state.down.slice(0));
var trailingDash = new RegExp('-$');
var out = '';
for (var i = 0; i < down.length; i++) {
out += this._keyEvent(down[i]) + '-';
}
return out.replace(trailingDash, ''); // Remove trailing dash
};
_createClass(HumanInput, [{
key: 'instances',
get: function get() {
return instances;
}
}, {
key: 'plugins',
get: function get() {
return plugins;
}
}]);
return HumanInput;
}(_events.EventHandler);
HumanInput.instances = instances; // So we can enforce singleton
HumanInput.plugins = plugins;
HumanInput.defaultListenEvents = defaultEvents;
exports.default = HumanInput;
module.exports = exports['default'];
});
|
import React from 'react';
function RecipeMeta(props) {
return (
<div className="recipe-meta">
<h1>{props.title}</h1>
<div>
<p>Time: {props.time}</p>
<p>Servings: {props.servings}</p>
</div>
</div>
)
}
export default RecipeMeta
|
console.log('ggg')
|
import React from "react";
import "./App.css";
import { Route, Link, Switch } from "react-router-dom";
import Login from "./components/Login";
import PrivateRoute from "./utils/PrivateRoute";
import FriendPage from "./components/FriendPage";
function App() {
return (
<div className="App">
<nav>
<Link to="/login">
<button>Login</button>
</Link>
<Link to="friend-page">
<button>Friend Page</button>
</Link>
</nav>
<Switch>
<PrivateRoute exact path="/friend-page" component={FriendPage} />
<Route path="/login" component={Login} />
</Switch>
</div>
);
}
export default App;
|
import Template from "./template";
import paper from "paper";
import ComponentPort from "../core/componentPort";
export default class Chamber extends Template {
constructor() {
super();
}
__setupDefinitions() {
this.__unique = {
position: "Point"
};
this.__heritable = {
componentSpacing: "Float",
width: "Float",
length: "Float",
height: "Float",
cornerRadius: "Float",
rotation: "Float"
};
this.__defaults = {
componentSpacing: 1000,
width: 5000,
length: 5000,
height: 250,
cornerRadius: 200,
rotation: 0
};
this.__units = {
componentSpacing: "μm",
width: "μm",
length: "μm",
height: "μm",
cornerRadius: "μm",
rotation: "°"
};
this.__minimum = {
componentSpacing: 0,
width: 5,
length: 5,
height: 1,
cornerRadius: 1,
rotation: 0
};
this.__maximum = {
componentSpacing: 10000,
width: 50000,
length: 50000,
height: 50000,
cornerRadius: 1000,
rotation: 360
};
this.__featureParams = {
componentSpacing: "componentSpacing",
position: "position",
width: "width",
length: "length",
height: "height",
cornerRadius: "cornerRadius",
rotation: "rotation"
};
this.__targetParams = {
componentSpacing: "componentSpacing",
position: "position",
width: "width",
length: "length",
height: "height",
cornerRadius: "cornerRadius",
rotation: "rotation"
};
this.__placementTool = "componentPositionTool";
this.__toolParams = {
position: "position"
};
this.__renderKeys = ["FLOW"];
this.__mint = "REACTION CHAMBER";
}
getPorts(params) {
let l = params["length"];
let w = params["width"];
let ports = [];
ports.push(new ComponentPort(0, -l / 2, "1", "FLOW"));
ports.push(new ComponentPort(w / 2, 0, "2", "FLOW"));
ports.push(new ComponentPort(0, l / 2, "3", "FLOW"));
ports.push(new ComponentPort(-w / 2, 0, "4", "FLOW"));
return ports;
}
render2D(params, key) {
let position = params["position"];
let px = position[0];
let py = position[1];
let l = params["length"];
let w = params["width"];
let rotation = params["rotation"];
let color = params["color"];
let radius = params["cornerRadius"];
let rendered = new paper.CompoundPath();
let rec = new paper.Path.Rectangle({
point: new paper.Point(px - w / 2, py - l / 2),
size: [w, l],
radius: radius
});
rendered.addChild(rec);
rendered.fillColor = color;
return rendered.rotate(rotation, px, py);
}
render2DTarget(key, params) {
let render = this.render2D(params, key);
render.fillColor.alpha = 0.5;
return render;
}
}
|
/* jshint indent: 2 */
module.exports = function(sequelize, DataTypes) {
const Roles = sequelize.define('Roles', {
id: {
type: DataTypes.INTEGER(11),
allowNull: false,
primaryKey: true,
autoIncrement: true
},
name: {
type: DataTypes.STRING,
allowNull: false
}
}, {
classMethods: {
associate: (models) => {
Roles.hasOne(models.Users);
}
}
});
return Roles;
};
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
class StatementCreate {
constructor(model) {
if (!model)
return;
this.userId = model.userId;
this.type = model.type;
this.month = model.month;
this.year = model.year;
this.openBalance = model.openBalance;
this.closeBalance = model.closeBalance;
this.accountId = model.accountId;
this.transactionFailed = model.transactionFailed;
this.manualStatement = model.manualStatement;
}
}
Object.seal(StatementCreate);
exports.default = StatementCreate;
|
const express=require("express")
const router=express.Router()
const controller=require("../controllers/contact")
router.post("/sendMail",controller.setMail)
module.exports=router;
|
import firebase from 'firebase';
export function updateAPIkey(value) {
//create a firebase update object
let firebaseUpdates = {};
//update the
firebaseUpdates[`/users/${firebase.auth().currentUser.uid}/CV_API_KEY`] = value;
//send the update to firebase
firebase.database().ref().update(firebaseUpdates);
}
|
// pages/cartoon/index.js
const app = getApp();
Page({
/**
* 页面的初始数据
*/
data: {
inputShowed: false,
showHistory: false,
inputVal: "",
isFixedTop: false,
list: [],
nextPage: null,
lasttPage: null,
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
this.pullup = this.selectComponent("#pullup");
this.loadList();
},
/**
* 监听页面滚动
*/
onPageScroll: function (e) {
if (e.scrollTop > 100) {
this.setData({
isFixedTop: true
})
} else {
this.setData({
isFixedTop: false
})
}
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
console.log('----下拉刷新列表----')
wx.showNavigationBarLoading()
this.loadList();
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
console.log("-----加载更多-----")
this.pullup.loadMore()
if (this.data.nextPage == null) {
this.pullup.loadMoreComplete("已全部加载")
} else {
setTimeout(() => {
this.loadList(null, this.data.nextPage);
}, 1000)
}
},
/**
* 加载列表
* parameter:name:搜索名称,api:下一页的api地址
*/
loadList: function (name, api) {
var that = this
app.service.getNovelList(name, api)
.then(res => {
console.log(res);
wx.stopPullDownRefresh()
wx.hideNavigationBarLoading()
// for (var i = 0; i < res.data.length; i++) {
// res.data[i].item_string = JSON.stringify(res.data[i]);
// }
if (api == null) {
that.setData({
list: res.data,
nextPage: res.links.next,
lastPage: res.links.previous
})
} else {
that.setData({
list: that.data.list.concat(res.data),
nextPage: res.links.next,
lastPage: res.links.previous
})
}
that.pullup.loadMoreComplete("加载成功")
})
.catch(res => {
that.pullup.loadMoreComplete("加载失败")
})
},
/**
* 搜索框
*/
showInput: function () {
this.setData({
inputShowed: true
});
},
hideInput: function () {
this.loadList()
this.setData({
inputVal: "",
inputShowed: false
});
},
clearInput: function () {
// this.loadList()
this.setData({
inputVal: ""
});
},
// showHistoryBlock: function(){
// this.setData({
// showHistory: true
// });
// },
inputTyping: function (e) {
this.loadList(e.detail.value, null)
console.log(e.detail)
this.setData({
inputVal: e.detail.value,
showHistory: false
});
}
})
|
(function () {
angular
.module('myApp')
.controller('JoinGroupController', JoinGroupController)
JoinGroupController.$inject = ['$state', '$scope', '$rootScope'];
function JoinGroupController($state, $scope, $rootScope) {
$rootScope.setData('showMenubar', true);
$rootScope.setData('selectedMenu', 'joingroup');
$rootScope.safeApply();
//Discriminate
$scope.$on("$destroy", function () {
if ($scope.groupsRef) $scope.groupsRef.off('value')
if ($scope.stGroupRef) $scope.stGroupRef.off('value')
});
$scope.getGroups = function () {
$rootScope.setData('loadingfinished', false);
$scope.groupsRef = firebase.database().ref('Groups');
$scope.groupsRef.on('value', function (snapshot) {
$scope.groupCodes = [];
$scope.groups = {};
for (groupKey in snapshot.val()) {
let group = snapshot.val()[groupKey]
let teacherKey = group.teacherKey
$scope.groups[group.code] = {
teacherKey: teacherKey,
groupKey: groupKey,
}
$scope.groupCodes.push(group.code);
}
$scope.getJoinedGroupKeys();
});
}
$scope.getJoinedGroupKeys = function () {
$scope.stGroupRef = firebase.database().ref('StudentGroups/' + $rootScope.settings.userId);
$scope.stGroupRef.on('value', function (groups) {
$scope.joinedKeys = [];
groups.forEach(function (group) {
$scope.joinedKeys.push(group.val());
});
$rootScope.setData('loadingfinished', true);
});
}
//add group to the student
$scope.JoinGroup = function () {
if (!$scope.groupcode) {
$rootScope.error("Please input group code!");
return;
}
if ($scope.groupCodes.indexOf($scope.groupcode) == -1) {
$rootScope.error('Invalid GroupCode!');
return;
}
var groupKey = $scope.groups[$scope.groupcode].groupKey; //Questions
if ($scope.joinedKeys.indexOf(groupKey) > -1) {
$rootScope.error("You are alread joined this group.\n please select other group.");
return;
}
firebase.database().ref('StudentGroups/' + $rootScope.settings.userId).push(groupKey).then(function () {
$rootScope.setData('loadingfinished', true);
$rootScope.success('You are joined to new group successfully!');
$state.go('myGroups');
});
}
}
})();
|
function gerarTabuada() {
var inicio = document.getElementById("txtnumber");
var res = document.getElementById("selres");
if (inicio.value === "") {
alert("Impossível Gerar Tabuada, Por favor digite um número!!!");
} else {
var f = Number(inicio.value);
for (let c = 0; c <= 10; c++) {
var numero = document.createElement("option");
numero.text += `${c} x ${f} = ${c * f} `;
numero.value= `tab${c} `
res.appendChild(numero);
}
}
}
|
import http from 'http'
import express from 'express'
import React from 'react'
import { renderToString } from 'react-dom/server'
import { match, RouterContext } from 'react-router'
import routes from './modules/Routes'
import apis from './api'
import path from 'path'
var app = express();
var PORT = process.env.PORT || 8080;
app.use(express.static(path.join(__dirname, 'public')));
app.use('/api/users', apis);
app.set('PORT', PORT);
app.get('*', (req, res)=>{
match({ routes, location: req.url }, (err, redirect, props) => {
if (err) {
res.status(500).send(err.message)
} else if (redirect) {
res.redirect(redirect.pathname + redirect.search)
} else if (props) {
// hey we made it!
const appHtml = renderToString(<RouterContext {...props}/>)
res.send(renderPage(appHtml))
} else {
res.status(404).send('Not Found')
}
})
})
function renderPage(appHtml) {
return `
<!doctype html public="storage">
<html>
<head>
<meta charset=utf-8/>
<title>Akadembox</title>
<link rel="stylesheet" href="css/app.css" />
<link rel="stylesheet" href="css/bootstrap.min.css" />
<link rel="stylesheet" href="css/custom.css" />
</head>
<body>
<div id=app>${appHtml}</div>
<script src="/bundle.js"></script>
<script src="jquery-1.10.2.js"></script>
<script src="bootstrap.min.js"></script>
</body>
</html>
`
}
var server = http.createServer(app);
server.listen(PORT, function(){
console.log('Server started....');
});
|
import React, { Component } from 'react';
import Pere from './Pere';
import { MyContext, ColorContext } from './MyContext'; // on importe nos contexts, dans lequel on met l'element parent le plus haut
class Arbre extends Component {
state = {
user: {
name: 'damien',
age: 29
}
}
// on imbrique un context dans un autre (colorContext dans MyContext), dans lequel on met notre element parent le plus haut
render() {
return (
<MyContext.Provider value={this.state.user} >
<ColorContext.Provider value={'red'}>
<Pere />
</ColorContext.Provider>
</MyContext.Provider>
)
}
}
export default Arbre;
|
var express = require('express');
var request = require('request');
var bodyParser = require('body-parser');
var app = express();
const SLACK_EVENT = require('./util/slack-events');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.set('port', (process.env.PORT || 5000));
var clientId = '113286865425.114138039170';
var clientSecret = '8a0d52be9868ad25e480bca703307f2f';
var slack = require('@slack/client')
var WebClient = slack.WebClient;
function createMessage(toggle){
return {
"response_type":"in_channel",
"attachments":[
{
"title":"The Pennsylvanian",
"title_link":"http://www.apartments.com/the-pennsylvanian-pittsburgh-pa/xtp479p/",
"image_url":"http://images1.apartments.com/i2/bVGCzMYmBCpZRHGpPAeE5RNgwrU894CTRCyOCD1htbM/110/the-pennsylvanian-pittsburgh-pa-primary-photo.jpg",
"actions":[
{
"type":"button",
"name":"previous",
"value":"previous",
"text":"pre",
"style":"default"
},
{
"type":"button",
"name":"like",
"value":"like",
"text": toggle && "Like" || "Unlike",
"style":"primary"
},
{
"type":"button",
"name":"next",
"value":"next",
"text":"next",
"style":"default"
}
],
"callback_id":"apt.json.view"
}
]
}
}
app.use(express.static(__dirname + '/public'));
// views is directory for all template files
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.get('/', function(req, res) {
res.send('Ngrok is working! Path Hit: ' + req.url);
});
// This route handles get request to a /oauth endpoint. We'll use this endpoint for handling the logic of the Slack oAuth process behind our app.
app.get('/oauth', function(req, res) {
// When a user authorizes an app, a code query parameter is passed on the oAuth endpoint. If that code is not there, we respond with an error message
if (!req.query.code) {
res.status(500);
res.send({"Error": "Looks like we're not getting code."});
console.log("Looks like we're not getting code.");
} else {
// If it's there...
// We'll do a GET call to Slack's `oauth.access` endpoint, passing our app's client ID, client secret, and the code we just got as query parameters.
request({
url: 'https://slack.com/api/oauth.access', //URL to hit
qs: {code: req.query.code, client_id: clientId, client_secret: clientSecret}, //Query string data
method: 'GET', //Specify the method
}, function (error, response, body) {
if (error) {
console.log(error);
} else {
res.json(body);
}
})
}
});
var result = {
"text":"your best choice",
"response_type":"in_channel",
"attachments":[
{
"color": "danger",
"title":"new apartment",
"title_link":"http://www.apartments.com/davison-square-pittsburgh-pa/rqd9zm0/",
"text":"this is @here",
"image_url":"http://images1.apartments.com/i2/ituFnTO-QCJFInE_dgv3kpFQPGJZUA35-aX71FbjM4o/118/davison-square-pittsburgh-pa.jpg",
"fields":[
{
"title":"price",
"value":125,
"short":true
},{
"title":"size",
"value":20,
"short":true
},{
"title":"address",
"value":"240 ave melwood",
"short":false
},{
"title":"address",
"value":"240 ave melwood",
"short":false
}
],
"actions":[
{
"name":"devare",
"text":"Devare",
"type":"button",
"style":"danger",
"value":true
}
],
"callback_id":"test"
}
]
}
// Route the endpoint that our slash command will point to and send back a simple response to indicate that ngrok is working
app.post('/command', function(req, res) {
res.setHeader('Content-Type', 'application/json');
console.log(req.body);
result["replace_original"] = false;
res.json(result);
});
app.post("/message_action",(req,res)=>{
console.log(req.body);
var payload = JSON.parse(req.body.payload);
var message_origin = createMessage(!toggle);
cli.chat.update(payload.message_ts,"D3C1G2Z35",`The following are the cadidate apts ${counter++}`, message_origin)
res.end();
})
app.post("/event_endpoint",(req,res)=>{
// var payload = req.body;
// switch(payload.type){
// case SLACK_EVENT.url_verification:
// res.setHeader('Content-Type', 'application/x-www-form-urlencoded');
// res.end(req.body.challenge)
// return;
// case SLACK_EVENT.event_callback:
// console.log(payload);
// break;
// default:
// console.log(payload);
// }
//
// res.status(200).end();
})
app.listen(app.get('port'), function() {
console.log('Node app is running on port', app.get('port'));
});
|
import {ADD_TASK,DELETE_TASK ,DID_TASK} from ('./taskTypes');
export const addTask =(task)=>({
type: ADD_TASK,
payload:task
})
export const deleteTask = (id)=>({
type:DELETE_TASK,
payload: id
})
export const didTask = (id)=>({
type: DID_TASK,
payload: id
})
|
import { useEffect, useState } from "react";
import userApi from "../../../api/userApi";
export default function PaymentHisory() {
const [state, setState] = useState();
//Hỏi anh Vương chỗ này
// useEffect(async () => {
// const res = await userApi.getProfilePayment();
// if (res) {
// console.log("payment", res);
// }
// }, [state]);
// if (!state) return "Loading....";
// console.log("data", state.data);
return (
<div className="tab4">
<YourCourseLearnt
name="Khóa học CFD1-offline"
date="09/09/2020"
money="1.500.000 VND"
/>
<YourCourseLearnt
name="Khóa học CFD1-offline"
date="09/02/2021"
money="1.500.000 VND"
/>
<YourCourseLearnt
name="Khóa học CFD1-online"
date="09/09/2021"
money="6.500.000 VND"
/>
<YourCourseLearnt
name="Khóa học CFD1-online"
date="09/12/2020"
money="2.500.000 VND"
/>
</div>
);
}
function YourCourseLearnt({ name, date, money }) {
return (
<div className="item itemhistory">
<div className="name">{name}</div>
<div className="date">{date}</div>
<div className="money">{money}</div>
</div>
);
}
|
angular.module('gt-gamers-guild.layout-ctrl', [])
.controller('LayoutCtrl', function($scope) {
$scope.hello = 'hello';
});
|
export default "someothertext";
|
'use strict';
var assert = require("chai").assert
, exponential = require("../lib/everpolate.js").exponential
describe('Exponential interpolation function', function () {
it('Evaluates interpolating value at the number \'x\'', function(){
assert.deepEqual( exponential(2, [1, 3, 7], [1, 5, 10]), [2.23606797749979])
})
it('Evaluates interpolating value on curves between the set of numbers \'x1, x2,..., xn\'', function () {
assert.deepEqual( exponential([1, 2, 3, 4, 5, 6, 7], [1, 3, 7], [1, 5, 10]), [1, 2.23606797749979, 5, 5.946035575013605, 7.0710678118654755, 8.408964152537145, 10])
})
})
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import ClothingPicker from './ClothingPicker';
class DesignPortal extends Component {
state = {
hati: 0,
topi: 0,
jacketi: 0,
bottomi: 0,
shoesi: 0
}
save = () => {
const outfit = [this.props.filteredhats[this.state.hati].id, this.props.filteredtops[this.state.topi].id, this.props.filteredjackets[this.state.jacketi].id, this.props.filteredbottoms[this.state.bottomi].id, this.props.filteredshoes[this.state.shoesi].id]
fetch(`${process.env.REACT_APP_APIURL}/outfits`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
occasion_id: 2,
user_id: this.props.user.id,
clothes: outfit
})
})
.then(res=>res.json())
.then(data => console.log(data))
}
goBack = (array) => {
let lastIdx = (array.length - 1)
if (this.props.hatIndex === 0) {
this.props.setHatIndex(lastIdx)
} else {
this.props.decreaseHatIndex()
}
}
goPrev = () => {
if (this.props.current === 'hat') {
if (this.state.hati === 0) {
this.setState({
hati: this.props.filteredhats.length - 1
})
} else {
this.setState(prevState => {
return {
hati: prevState.hati - 1
}
})
}
} else if (this.props.current === 'top') {
if (this.state.topi === 0) {
this.setState({
topi: this.props.filteredtops.length - 1
})
} else {
this.setState(prevState => {
return {
topi: prevState.topi - 1
}
})
}
} else if (this.props.current === 'jacket') {
if (this.state.jacketi === 0) {
this.setState({
jacketi: this.props.filteredjackets.length - 1
})
} else {
this.setState(prevState => {
return {
jacketi: prevState.jacketi - 1
}
})
}
} else if (this.props.current === 'bottom') {
if (this.state.bottomi === 0) {
this.setState({
bottomi: this.props.filteredbottoms.length - 1
})
} else {
this.setState(prevState => {
return {
bottomi: prevState.bottomi - 1
}
})
}
} else if (this.props.current === 'shoes') {
if (this.state.shoesi === 0) {
this.setState({
shoesi: this.props.filteredshoes.length - 1
})
} else {
this.setState(prevState => {
return {
shoesi: prevState.shoesi - 1
}
})
}
}
}
goNext = () => {
if (this.props.current === 'hat') {
if (this.state.hati === this.props.filteredhats.length - 1) {
this.setState({
hati: 0
})
} else {
this.setState(prevState => {
return {
hati: prevState.hati + 1
}
})
}
} else if (this.props.current === 'top') {
if (this.state.topi === this.props.filteredtops.length - 1) {
this.setState({
topi: 0
})
} else {
this.setState(prevState => {
return {
topi: prevState.topi + 1
}
})
}
} else if (this.props.current === 'jacket') {
if (this.state.jacketi === this.props.filteredjackets.length - 1) {
this.setState({
jacketi: 0
})
} else {
this.setState(prevState => {
return {
jacketi: prevState.jacketi + 1
}
})
}
} else if (this.props.current === 'bottom') {
if (this.state.bottomi === this.props.filteredbottoms.length - 1) {
this.setState({
bottomi: 0
})
} else {
this.setState(prevState => {
return {
bottomi: prevState.bottomi + 1
}
})
}
} else if (this.props.current === 'shoes') {
if (this.state.shoesi === this.props.filteredshoes.length - 1) {
this.setState({
shoesi: 0
})
} else {
this.setState(prevState => {
return {
shoesi: prevState.shoesi + 1
}
})
}
}
}
showCurrentClothing = () => {
if (this.props.current === 'hat') {
console.log(this.props.filteredhats)
if (this.props.filteredhats.length === 0) {
return 'No matching hat.'
} else {
return (
<div className='current-item'>
<button className='prev' onClick={this.goPrev}>Previous</button>
<img src={this.props.filteredhats[this.state.hati].image_url}/>
<button className='next' onClick={this.goNext}>Next</button>
</div>
)
}
} else if (this.props.current === 'top') {
if (this.props.filteredtops.length === 0) {
return 'No matching top.'
} else {
return (
<div className='current-item'>
<button className='prev' onClick={this.goPrev}>Previous</button>
<img src={this.props.filteredtops[this.state.topi].image_url}/>
<button className='next' onClick={this.goNext}>Next</button>
</div>
)
}
} else if (this.props.current === 'jacket') {
if (this.props.filteredjackets.length === 0) {
return 'No matching jacket.'
} else {
return (
<div className='current-item'>
<button className='prev' onClick={this.goPrev}>Previous</button>
<img src={this.props.filteredjackets[this.state.jacketi].image_url}/>
<button className='next' onClick={this.goNext}>Next</button>
</div>
)
}
} else if (this.props.current === 'bottom') {
if (this.props.filteredbottoms.length === 0) {
return 'No matching bottoms'
} else {
return (
<div className='current-item'>
<button className='prev' onClick={this.goPrev}>Previous</button>
<img src={this.props.filteredbottoms[this.state.bottomi].image_url}/>
<button className='next' onClick={this.goNext}>Next</button>
</div>
)
}
} else if (this.props.current === 'shoes') {
if (this.props.filteredshoes.length === 0) {
return 'No matching shoes.'
} else {
return (
<div className='current-item'>
<button className='prev' onClick={this.goPrev}>Previous</button>
<img src={this.props.filteredshoes[this.state.shoesi].image_url}/>
<button className='next' onClick={this.goNext}>Next</button>
</div>
)
}
}
}
resetIdx = () => {
this.setState({
hati: 0,
topi: 0,
jacketi: 0,
bottomi: 0,
shoesi: 0
})
}
handleColorSchemeChange = (event) => {
this.props.setColorScheme(event.target.value)
this.resetIdx()
}
handleColorChange = (event) => {
this.props.setPrimaryColor(event.target.value)
this.resetIdx()
}
render() {
return (
<div className='design-portal'>
<div className='info'>
<img src={require('../pics/colorwheel.png')} />
{'Please select how you would like to match your outfit:'}<br/><br/>
<select className='dropdown' onChange={(event) => this.handleColorSchemeChange(event)}>
<option value='complementary'>complementary</option>
<option value='analogous'>analogous</option>
<option value='triadic'>triadic</option>
</select><br/>
{'What would you like your primary color to be?'}<br/><br/>
<select className='dropdown' onChange={(event) => this.handleColorChange(event)}>
{
this.props.colors.map(c => <option value={c.name}>{c.name}</option>)
}
</select><br/><br/>
<button onClick={this.save}>Save Outfit</button>
</div>
<div className='current'>
{
this.props.current ?
this.showCurrentClothing()
:
'Please select an article of clothing!'
}
</div>
<div className='picker-container'>
<ClothingPicker category='hat'
idx={this.state.hati}
resetIdx={this.resetIdx}
/>
<ClothingPicker category='top'
idx={this.state.topi}
resetIdx={this.resetIdx}
/>
<ClothingPicker category='jacket'
idx={this.state.jacketi}
resetIdx={this.resetIdx}
/>
<ClothingPicker category='bottom'
idx={this.state.bottomi}
resetIdx={this.resetIdx}
/>
<ClothingPicker category='shoes'
idx={this.state.shoesi}
resetIdx={this.resetIdx}
/>
</div>
</div>
);
}
}
function mapStateToProps(state) {
return {
// loggedIn: state.loggedIn,
user: state.user,
colors: state.colors,
current: state.current,
myhats: state.myhats,
mytops: state.mytops,
myjackets: state.myjackets,
mybottoms: state.mybottoms,
myshoes: state.myshoes,
filteredhats: state.filteredhats,
filteredtops: state.filteredtops,
filteredjackets: state.filteredjackets,
filteredbottoms: state.filteredbottoms,
filteredshoes: state.filteredshoes
}
}
function mapDispatchToProps(dispatch) {
return {
// logOut: dispatch({type: 'LOG_IN', payload: false}),
setPrimaryColor: (data) => dispatch({type: 'SET_PRIMARY_COLOR', payload: data}),
setColorScheme: (data) => dispatch({type: 'SET_COLOR_SCHEME', payload: data}),
loadHats: (data) => dispatch({type: 'LOAD_HATS', payload: data}),
loadTops: (data) => dispatch({type: 'LOAD_TOPS', payload: data}),
loadJackets: (data) => dispatch({type: 'LOAD_JACKETS', payload: data}),
loadBottoms: (data) => dispatch({type: 'LOAD_BOTTOMS', payload: data}),
loadShoes: (data) => dispatch({type: 'LOAD_SHOES', payload: data})
}
}
export default connect(mapStateToProps, mapDispatchToProps)(DesignPortal);
|
import React, { Component } from 'react';
import { auth, database } from '../firebase';
import CurrentUser from '../user/CurrentUser';
import SignIn from '../signIn/SignIn';
import TodoList from '../todoList/TodoList';
import AddTodo from '../addTodo/AddTodo';
import NavContainer from '../navigation/NavContainer';
import './Application.css';
class Application extends Component {
constructor(props) {
super(props);
this.state = {
currentUser: null,
allTodos: ['1', '2'],
};
this.addTodoItem = this.addTodoItem.bind(this);
}
componentWillMount() {
auth.onAuthStateChanged((currentUser) => {
console.log('auth changed', currentUser);
this.setState({ currentUser });
});
}
addTodoItem(todo) {
this.setState({
allTodos: [...this.state.allTodos, todo]
})
}
render() {
const { currentUser } = this.state;
return <div className="Application">
<header className="Application--header">
<NavContainer />
<h1>Our Todo List</h1>
</header>
<div>
{ /* alternative to a ternary, single version! */ }
{ !currentUser && <SignIn /> }
{
currentUser &&
<div>
<CurrentUser user={currentUser} />
</div>
}
</div>
<div>
<AddTodo
addTodoItem={ this.addTodoItem }
/>
</div>
<div>
<TodoList
todos={ this.state.allTodos }
/>
</div>
</div>;
}
}
export default Application;
|
let numberOne = 0.7;
let numberTwo = 0.1;
// numberOne = ((numberOne * 100) + (numberTwo * 100) / 100);
numberOne += numberTwo;
numberOne += numberTwo;
numberOne += numberTwo;
numberOne += numberTwo;
numberOne += numberTwo;
numberOne += numberTwo;
numberOne += numberTwo;
numberOne += numberTwo;
numberOne += numberTwo;
numberOne += numberTwo;
numberOne += numberTwo;
numberOne += numberTwo;
numberOne += numberTwo;
// numberOne = parseFloat(numberOne.toFixed(2));
numberOne = Number(numberOne.toFixed(2));
console.log(numberOne);
console.log(Number.isInteger(numberOne));
// console.log(numberOne.toString() + numberTwo);
// numberOne = numberOne.toString(2);
// console.log(numberOne);
// console.log(numberOne.toFixed(2));
// let temp = numberOne * 'Ola';
// console.log(Number.isNaN(temp));
|
import actionTypes from './../actionTypes';
import ActionCreator from "./";
import store from "./../store";
export const GetUserInfo = (userid, token) => {
_GetUserInfo(userid, token);
return {
type: actionTypes.USER_GET_USER_INFO,
};
}
export const SaveUserInfo = (userInfo) => {
return {
type: actionTypes.USER_SAVE_USER_INFO,
payload: {
userInfo
}
};
}
export const DeleteUserInfo = () => {
return {
type: actionTypes.USER_DELETE_USER_INFO,
};
}
export const SaveRememberMe = (username) => {
return {
type: actionTypes.USER_SAVE_REMEMBER_ME,
payload: {
username
}
};
}
export const SaveIsLoggedIn = (isLoggedIn) => {
return {
type: actionTypes.USER_SAVE_IS_LOGGED_IN,
payload: {
isLoggedIn
}
};
}
export const Signup = (username, password1, password2, callbackFunc) => {
_Signup(username, password1, password2, callbackFunc);
return {
type: actionTypes.USER_SIGN_UP,
};
}
export const Login = (username, password, isRememberme, callbackFunc) => {
_Login(username, password, isRememberme, callbackFunc);
return {
type: actionTypes.USER_LOG_IN,
};
}
export const Logout = () => {
_LogOut();
return {
type: actionTypes.USER_LOG_OUT,
};
}
export const SaveJwt = (token) => {
return {
type: actionTypes.USER_SAVE_JWT,
payload: {
token
}
};
}
export const DeleteJwt = () => {
return {
type: actionTypes.USER_DELETE_JWT,
}
}
export const SaveUserid = (userid) => {
return {
type: actionTypes.USER_SAVE_USERID,
payload: {
userid
}
};
}
export const DeleteUserid = () => {
return {
type: actionTypes.USER_DELETE_USERID,
};
}
const _Login = (username, password, isRememberme, callbackFunc) => {
store.dispatch(ActionCreator.ShowDefaultSpinner());
fetch("/rest-auth/login/", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
username: username,
password: password,
})
})
.then(
response => response.json()
)
.then(json => {
store.dispatch(ActionCreator.HideDefaultSpinner());
if (json.token && json.user) {
callbackFunc(true, json);
store.dispatch(ActionCreator.SaveJwt(json.token));
store.dispatch(ActionCreator.SaveUserid(json.user.pk.toString()));
if (isRememberme) {
store.dispatch(ActionCreator.SaveRememberMe(json.user.username));
}
store.dispatch(ActionCreator.GetUserInfo(json.user.pk, json.token))
store.dispatch(ActionCreator.SaveIsLoggedIn(true));
} else {
store.dispatch(ActionCreator.SaveIsLoggedIn(false));
callbackFunc(false, json);
}
})
.catch (
err => {
store.dispatch(ActionCreator.SaveIsLoggedIn(false));
store.dispatch(ActionCreator.HideDefaultSpinner());
callbackFunc(false, "");
}
)
}
const _LogOut = () => {
store.dispatch(ActionCreator.ShowDefaultSpinner());
fetch("/rest-auth/logout/", {
method: "GET",
headers: {
"Content-Type": "application/json"
},
})
.then(
response => response.json()
)
.then(json => {
store.dispatch(ActionCreator.HideDefaultSpinner());
})
.catch (
err => {
store.dispatch(ActionCreator.HideDefaultSpinner());
}
)
store.dispatch(ActionCreator.DeleteJwt());
store.dispatch(ActionCreator.DeleteUserInfo());
store.dispatch(ActionCreator.DeleteUserid());
}
const _Signup = (username, password1, password2, callbackFunc) => {
store.dispatch(ActionCreator.ShowDefaultSpinner());
fetch(`/rest-auth/registration/`, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
username: username,
password1: password1,
password2: password2,
})
})
.then(response => response.json())
.then(json => {
callbackFunc(true, username, json);
store.dispatch(ActionCreator.HideDefaultSpinner());
})
.catch(
err => {
store.dispatch(ActionCreator.HideDefaultSpinner());
callbackFunc(false, "", "");
}
)
}
const _GetUserInfo = (userid, token) => {
fetch(`/users/${userid}/`, {
method: "GET",
headers: {
"Authorization": `JWT ${token}`,
"Content-Type": "application/json"
},
})
.then( response => {
if (response.status === 401){
store.dispatch(ActionCreator.Logout());
} else {
return response.json();
}
})
.then(json => {
if (json === undefined || json.result === undefined || json.result === null) {
store.dispatch(ActionCreator.SaveUserInfo(null));
} else {
store.dispatch(ActionCreator.SaveUserInfo(json.result));
}
})
.catch (
console.log("Fail to get userInfo")
)
}
|
export { default as Card} from "./CardElement"
|
import React, { useState } from 'react';
import './style.css';
import img from './img/resultsBg.svg';
import { Link } from 'react-router-dom';
export const Results = ({ name, counter, numberOfAnimals, onBackToGame }) => {
const [backToGame, setBackToGame] = useState(false);
return (
<>
<div className="signboard">
<div className="signboard-bg">
<img className="signboard-bg__img" src={img}></img>
<div className="signboard-content">
<h1 className="signboard-content__title">Děkujeme!</h1>
<p>
{' '}
Zachránce: <span style={{ fontWeight: 'bold' }}> {name}</span>
</p>
<p>
{' '}
{numberOfAnimals} zvířátka jsou doma na{' '}
<span style={{ fontWeight: 'bold' }}> {counter} </span> pokusů
</p>
<Link to="/hra">
<button
className="signboard-content__btn"
onClick={() => {
setBackToGame(true);
onBackToGame(backToGame);
}}
>
Hrát znovu
</button>
</Link>
</div>
</div>
</div>
</>
);
};
|
/*
* App Ownership Authorization For Matching Routes
* Must be mounted after users authorize.
* Possible Route Usage: /apps/:appId/*
*/
const AppModel = rootRequire('/models/App');
module.exports = (request, response, next) => {
const userId = request.user.id;
const { appId } = request.params;
AppModel.find({
where: {
id: appId,
userId,
},
}).then(app => {
if (!app) {
return response.respond(403, 'Insufficient app permissions.');
}
request.app = app;
next();
});
};
|
var namespacede_1_1telekom_1_1pde_1_1codelibrary_1_1ui_1_1modules =
[
[ "login", "namespacede_1_1telekom_1_1pde_1_1codelibrary_1_1ui_1_1modules_1_1login.html", "namespacede_1_1telekom_1_1pde_1_1codelibrary_1_1ui_1_1modules_1_1login" ]
];
|
import * as Promise from 'bluebird'
export const audioContext = new AudioContext();
export const manSamples = {
a: '/SWAR1505_TalkingJpnM/00.mp3',
b: '/SWAR1505_TalkingJpnM/01.mp3',
c: '/SWAR1505_TalkingJpnM/02.mp3',
d: '/SWAR1505_TalkingJpnM/03.mp3',
e: '/SWAR1505_TalkingJpnM/04.mp3',
f: '/SWAR1505_TalkingJpnM/05.mp3',
g: '/SWAR1505_TalkingJpnM/06.mp3',
h: '/SWAR1505_TalkingJpnM/07.mp3',
i: '/SWAR1505_TalkingJpnM/57.mp3',
j: '/SWAR1505_TalkingJpnM/58.mp3',
k: '/SWAR1505_TalkingJpnM/41.mp3',
l: '/SWAR1505_TalkingJpnM/42.mp3',
m: '/SWAR1505_TalkingJpnM/43.mp3',
n: '/SWAR1505_TalkingJpnM/44.mp3',
o: '/SWAR1505_TalkingJpnM/45.mp3',
p: '/SWAR1505_TalkingJpnM/46.mp3',
q: '/SWAR1505_TalkingJpnM/47.mp3',
r: '/SWAR1505_TalkingJpnM/48.mp3',
s: '/SWAR1505_TalkingJpnM/49.mp3',
t: '/SWAR1505_TalkingJpnM/31.mp3',
u: '/SWAR1505_TalkingJpnM/32.mp3',
v: '/SWAR1505_TalkingJpnM/33.mp3',
w: '/SWAR1505_TalkingJpnM/34.mp3',
x: '/SWAR1505_TalkingJpnM/35.mp3',
y: '/SWAR1505_TalkingJpnM/36.mp3',
z: '/SWAR1505_TalkingJpnM/37.mp3',
}
export const womanSamples = {
a: '/SWAR1506_TalkingJpnF/11.mp3',
b: '/SWAR1506_TalkingJpnF/12.mp3',
c: '/SWAR1506_TalkingJpnF/13.mp3',
d: '/SWAR1506_TalkingJpnF/14.mp3',
e: '/SWAR1506_TalkingJpnF/15.mp3',
f: '/SWAR1506_TalkingJpnF/16.mp3',
g: '/SWAR1506_TalkingJpnF/17.mp3',
h: '/SWAR1506_TalkingJpnF/18.mp3',
i: '/SWAR1506_TalkingJpnF/19.mp3',
j: '/SWAR1506_TalkingJpnF/20.mp3',
k: '/SWAR1506_TalkingJpnF/21.mp3',
l: '/SWAR1506_TalkingJpnF/62.mp3',
m: '/SWAR1505_TalkingJpnF/23.mp3',
n: '/SWAR1505_TalkingJpnF/24.mp3',
o: '/SWAR1505_TalkingJpnM/00.mp3',
p: '/SWAR1505_TalkingJpnF/26.mp3',
q: '/SWAR1505_TalkingJpnF/27.mp3',
r: '/SWAR1505_TalkingJpnF/28.mp3',
s: '/SWAR1505_TalkingJpnF/29.mp3',
t: '/SWAR1505_TalkingJpnF/30.mp3',
u: '/SWAR1505_TalkingJpnF/31.mp3',
v: '/SWAR1505_TalkingJpnF/32.mp3',
w: '/SWAR1505_TalkingJpnF/33.mp3',
x: '/SWAR1505_TalkingJpnF/34.mp3',
y: '/SWAR1505_TalkingJpnF/35.mp3',
z: '/SWAR1505_TalkingJpnF/36.mp3',
}
function sampleName(sample) {
const separated = sample.split('/')
return separated[separated.length - 1].replace('.', '_')
}
const pathToAudio = sample => {
const sound = new Audio(sample)
sound.type = "audio/wav"
const id = sampleName(sample)
sound.id = id
document.body.appendChild(sound)
const track = audioContext.createMediaElementSource(sound)
track.connect(audioContext.destination)
return sound
}
// Source (mediaElement)
export const manSampleMap = Object.keys(manSamples).reduce((map, symbol) => {
const path = manSamples[symbol]
const audio = pathToAudio(path)
map[symbol] = audio
return map;
}, {})
export function playSound(audio) {
return new Promise((resolve, reject) => {
if (!audio) reject('No audio')
audioContext.resume().then(() => {
audio.play()
const cb = () => {
resolve(audio)
audio.removeEventListener('ended', cb);
}
audio.addEventListener('ended', cb)
})
})
}
export function playWord(word, sampleMap) {
word = word.toLowerCase()
const chars = word.split('').filter((_, i) => i % 2)
const sounds = chars.map(char => sampleMap[char])
return Promise.mapSeries(sounds, playSound)
}
export function playSentence(sentence, sampleMap) {
const sentences = sentence.match(/[A-Za-z]+/g)
if (sentences) {
return Promise.mapSeries(sentences, word => {
return playWord(word, sampleMap)
})
}
return Promise.resolve()
}
|
import React, { useEffect } from "react";
import { Route, Switch } from 'react-router-dom';
import Accueil from '../../components/Accueil';
import Affretement from '../../components/Affretement';
import Carte from '../../components/Carte';
import Distribution from '../../components/Distribution';
import FormDevis from '../../components/FormDevis';
import Logistique from '../../components/Logistique';
import Mots from '../../components/Mots';
import PageContact from '../../components/PageContact';
import ProPartModale from '../../components/ProPartModale';
import Réseau from '../../components/Reseau';
import FormInscriptionPro from '../FormInscriptionPro';
import FormInscriptionPart from '../FormInscriptionPart';
import LoginForm from '../../containers/LoginForm';
import DeuxLoginForm from '../../components/DeuxLoginForm';
import './style.scss';
function App() {
return (
<div className="App">
<FormInscriptionPro />
<Switch>
<Route path="/affretement" component={Affretement} />
<Route path="/carte" component={Carte} />
<Route path="/distribution" component={Distribution} />
<Route path="/formDevis" component={FormDevis} />
<Route path="/logistique" component={Logistique} />
<Route path="/Mots" component={Mots} />
<Route path="/pageContact" component={PageContact} />
<Route path="/ProPartModale" component={ProPartModale} />
<Route path="/reseau" component={Réseau} />
</Switch>
</div>
);
}
export default App;
|
/**
* Created by xiaojiu on 2017/2/9.
*/
define(['../../../app'], function(app) {
app.factory('collectDifferenceConfirm', ['$http', '$q', '$filter', 'HOST', function($http, $q, $filter, HOST) {
return {
getThead: function() {
return [{
field: 'pl4GridCount',
name: '序号',
type: 'pl4GridCount'
}, {
field: 'supliers',
name: '供应商'
},{
field: 'sku',
name: '商品编码'
}, {
field: 'brand',
name: '商品品牌'
}, {
field: 'model',
name: '规格型号'
}, {
field: 'factoryCode',
name: '出厂编码'
}, {
field: 'goodsName',
name: '商品名称'
}, {
field: 'meaUnit',
name: '计量单位'
}, {
field: 'chuHuoCount',
name: '应收数量'
}, {
field: 'receCount',
name: '良品数量'
}, {
field: 'different',
name: '差异数量'
},{field:'bar',name:'操作',type:'operate',buttons:[{
text: '查看差异',
btnType: 'btn',
call: 'checkDetail',
openModal:'#editDate'
}]}]
},
getBanner: function(data){
data.param=$filter('json')(data.param);
var deferred = $q.defer();
$http.post(HOST + '/differentMonitor/query_differentDetail', data)
.success(function(data){
deferred.resolve(data);
})
.error(function(e) {
deferred.reject('error:' + e)
});
return deferred.promise;
},
getDataTable: function(data) {
//将parm转换成json字符串
data.param = $filter('json')(data.param);
/*console.log(data)*/
var deferred = $q.defer();
$http.post(HOST + '/differentMonitor/update_recedifferent', data)
.success(function(data) {
// console.log(data)
deferred.resolve(data);
})
.error(function(e) {
deferred.reject('error:' + e);
});
return deferred.promise;
},
getDataTableLook: function(data) {
//将parm转换成json字符串
data.param = $filter('json')(data.param);
/*console.log(data)*/
var deferred = $q.defer();
$http.post(HOST + '/ckTaskIn/getInGoodsDiffCountDetail', data)
.success(function(data) {
// console.log(data)
deferred.resolve(data);
})
.error(function(e) {
deferred.reject('error:' + e);
});
return deferred.promise;
},
printCongirm: function(data){
//将parm转换成json字符串
data.param=$filter('json')(data.param);
var deferred=$q.defer();
$http.post(HOST+'/pickGoodsTaskZdDetail/updatePrintStatus',data)
.success(function (data) {
deferred.resolve(data);
})
.error(function (e) {
deferred.reject('error:'+e);
});
return deferred.promise;
}
}
}]);
});
|
function customLine(x1,x2,y1,y2) {
this.x1=x1;
this.x2=x2;
this.y1=y1;
this.y2=y2;
}
var changeTicks = 0;
var changed = false;
var canvasWidth = 500;
var canvasHeight = 500;
var imgX = 0;
var imgY = 0;
var imgScale = 1.0;
var invScale = 1.0;
var UI = new Array();
var cnv;
var mode = 'move';
var bgimg;
var lastX;
var lastY;
var arr = new Array();
function drawLine(value) {
var width = canvasWidth * imgScale;
var height = canvasHeight * imgScale;
if (value.x1 > width || value.x2 > width
|| value.y1 > height || value.y2 > height)
return;
line(value.x1 * invScale, value.y1 * invScale, value.x2 * invScale, value.y2 * invScale);
stroke(0, 0, 255);
strokeWeight(5);
}
function clamp(val, max, min) {
return Math.max(Math.min(val, max), min);
}
function clampImgPosition(sc) {
var lastx = imgX;
var lasty = imgY;
imgX = clamp(imgX, bgimg.width * (1 - imgScale), 0);
imgY = clamp(imgY, bgimg.height * (1 - imgScale), 0);
arr.forEach((point) => adjustPointPosition(point, (lastx - imgX) * 1.377 * sc, (lasty - imgY) * 1.377 * sc));
}
function mouseDragged() {
if (mode === 'draw') {
changed = true;
var avgX = (mouseX + lastX) / 2;
var avgY = (mouseY + lastY) / 2;
arr.push(new customLine(mouseX * imgScale, avgX * imgScale, mouseY * imgScale, avgY * imgScale));
arr.push(new customLine(avgX * imgScale, lastX * imgScale, avgY * imgScale, lastY * imgScale));
}
else if (mode === 'move') {
moveImg(lastX - mouseX, lastY - mouseY);
}
}
function moveImg(dirX, dirY) {
var x = clamp(imgX + (dirX), bgimg.width * (1 - imgScale), 0) - imgX;
var y = clamp(imgY + (dirY), bgimg.height * (1 - imgScale), 0) - imgY;
imgX += x * 1.45 * imgScale;
imgY += y * 1.45 * imgScale;
arr.forEach((point) => adjustPointPosition(point, -x * imgScale, -y * imgScale));
}
function zoomIn() {
mode = 'move';
if (imgScale < 0.5)
return;
imgScale /= 2;
invScale = Math.pow(imgScale, -1);
clampImgPosition(2);
}
function zoomOut() {
mode = 'move';
if (imgScale >0.5)
return;
imgScale *= 2
invScale = Math.pow(imgScale, -1);
clampImgPosition(0.5);
}
function adjustPointScale(point, scale) {
point.x1 *= scale;
point.x2 *= scale;
point.y1 *= scale;
point.y2 *= scale;
}
function adjustPointPosition(point, changeX, changeY) {
point.x1 += changeX;
point.x2 += changeX;
point.y1 += changeY;
point.y2 += changeY;
}
function setDrawMode() {
mode = 'draw';
}
function setMoveMode() {
mode = 'move';
}
function saveCnv() {
var json = JSON.stringify(arr);
var form = document.getElementById("mapInput");
form.value = json;
}
function loadCnv(json) {
jsron = json.split('"').join('"');
arr = JSON.parse(jsron);
}
function clearCnv() {
arr = new Array();
}
function draw() {
background(51);
image(bgimg, 0, 0, canvasHeight, canvasWidth, imgX, imgY, bgimg.width*imgScale, bgimg.height*imgScale);
arr.forEach(drawLine);
lastX = mouseX;
lastY = mouseY;
}
function setup() {
cnv = createCanvas(canvasWidth, canvasHeight);
cnv.parent('mapHolder');
bgimg = loadImage('/images/map.jpg');
}
|
var target,
smallScreen = window.matchMedia("(max-width: 992px)").matches;
MarkerTarget.prototype = new google.maps.OverlayView();
function initMap() {
var map,
center = smallScreen ? {lat: 35.88, lng: 14.44} : {lat: 38, lng: 22},
zoom = 6,
srcTarget = '/images/maplogo.png',
boundsTarget = new google.maps.LatLngBounds(new google.maps.LatLng(55.684064, 37.341056),
new google.maps.LatLng(55.684789, 37.342386));
map = new google.maps.Map(document.getElementById('map'), {
center: center,
scrollwheel: false,
zoom: zoom
});
//target = new MarkerTarget(boundsTarget, srcTarget, map);
}
/** @constructor */
function MarkerTarget(bounds, image, map) {
// Initialize all properties.
this.bounds_ = bounds;
this.image_ = image;
this.map_ = map;
// Define a property to hold the image's div. We'll
// actually create this div upon receipt of the onAdd()
// method so we'll leave it null for now.
this.div_ = null;
// Explicitly call setMap on this overlay.
this.setMap(map);
}
/**
* onAdd is called when the map's panes are ready and the overlay has been
* added to the map.
*/
MarkerTarget.prototype.onAdd = function () {
var div = document.createElement('div');
div.style.borderStyle = 'none';
div.style.borderWidth = '0px';
div.style.position = 'absolute';
// Create the img element and attach it to the div.
var img = document.createElement('img');
img.src = this.image_;
img.style.width = '100%';
img.style.height = '100%';
img.style.position = 'absolute';
div.appendChild(img);
this.div_ = div;
// Add the element to the "overlayLayer" pane.
var panes = this.getPanes();
panes.overlayLayer.appendChild(div);
};
MarkerTarget.prototype.draw = function () {
// We use the south-west and north-east
// coordinates of the overlay to peg it to the correct position and size.
// To do this, we need to retrieve the projection from the overlay.
var overlayProjection = this.getProjection();
// Retrieve the south-west and north-east coordinates of this overlay
// in LatLngs and convert them to pixel coordinates.
// We'll use these coordinates to resize the div.
var sw = overlayProjection.fromLatLngToDivPixel(this.bounds_.getSouthWest());
var ne = overlayProjection.fromLatLngToDivPixel(this.bounds_.getNorthEast());
// Resize the image's div to fit the indicated dimensions.
var div = this.div_;
div.style.left = sw.x + 'px';
div.style.top = ne.y + 'px';
div.style.width = (ne.x - sw.x) + 'px';
div.style.height = (sw.y - ne.y) + 'px';
};
// The onRemove() method will be called automatically from the API if
// we ever set the overlay's map property to 'null'.
MarkerTarget.prototype.onRemove = function () {
this.div_.parentNode.removeChild(this.div_);
this.div_ = null;
};
//export default initMap;
google.maps.event.addDomListener(window, 'load', initMap);
|
module.exports = (sequelize, type) => {
return sequelize.define('aerista', {
id: {
type: type.INTEGER,
primaryKey: true,
autoIncrement: true
},
nombre1: {
allowNull: false,
type: type.STRING(50)
},
nombre2: {
allowNull: false,
type: type.STRING(100)
},
apellido1: {
allowNull: false,
type: type.STRING(50)
},
apellido2: {
allowNull: false,
type: type.STRING(100)
},
direccion: {
allowNull: false,
type: type.STRING(150)
},
telefono: {
allowNull: true,
type: type.STRING(20)
}
}
)
}
|
Component({
data: {
//输入框聚焦状态
isFocus: true,
//输入框聚焦样式 是否自动获取焦点
focusType: true,
valueData: '', //输入的值
dataLength: '',
boxList: [1, 2, 3, 4]
},
// 组件属性
properties: {
},
// 组件方法
methods: {
// 获得焦点时
handleUseFocus() {
this.setData({
focusType: true
})
},
// 失去焦点时
handleUseBlur() {
this.setData({
focusType: false
})
},
// 点击6个框聚焦
handleFocus() {
this.setData({
isFocus: true
})
},
// 获取输入框的值
handleSetData(e) {
console.log(e, 'ee');
// 更新数据
this.setData({
dataLength: e.detail.value.length,
valueData: e.detail.value
})
// 当输入框的值等于4时(发起支付等...)
if (e.detail.value.length === 6) {
// 通知用户输入数字达到6位数可以发送接口校验密码是否正确
this.triggerEvent('initData', e.detail.value)
}
},
//关闭
handleClose() {
this.triggerEvent('close')
},
//提交
handleSubmit(e) {
console.log(e);
if (this.data.valueData.length < 4) {
// 通知用户输入数字达到6位数可以发送接口校验密码是否正确
wx.showToast({
title: '请输入4位密码',
icon: 'none',
image: '',
duration: 1000,
mask: false,
success: (result)=>{
},
fail: ()=>{},
complete: ()=>{}
});
this.setData({
isFocus:true
})
return
}
this.triggerEvent('submit', this.data.valueData)
}
}
})
|
export default {
title: 'Inside UK\'s Technocracy And Mafia Behind It1',
seo: 'Democracy and capitalism are incompatible: money always talks. learn how the Conservative neo-elite are robbing population with Industrial Strategy.',
topics: ['UK', 'politics'],
og: {
image: './life-sucks/img/technocracy.jpg',
type: 'article',
},
figSm: true,
sitemap: false,
// focus: true,
}
export const links = {
ad: 'https://art-deco.github.io/license/',
'ref-forbes': 'https://www.forbes.com/profile/eileen-burbidge/',
'wired': 'https://www.youtube.com/watch?v=swIoyaBUpEg',
'ch-tn': 'https://beta.companieshouse.gov.uk/company/08843778/officers',
'ch-tn-wm': 'https://web.archive.org/save/https://beta.companieshouse.gov.uk/company/08843778/officers',
'ch-public': 'https://beta.companieshouse.gov.uk/company/10608507/filing-history',
'wiki-propaganda': 'https://en.wikipedia.org/wiki/Propaganda:_The_Formation_of_Men%27s_Attitudes',
'wework': 'https://www.youtube.com/watch?v=X2LwIiKhczo',
'bcs': 'https://www.bcs.org/get-qualified/become-chartered/chartered-it-professional/',
'korski-photo': 'https://www.pressreader.com/uk/scottish-daily-mail/20170328/281715499449399',
'crunch-echo': 'https://www.crunchbase.com/funding_round/echo-8-seed--730e481c#section-overview',
'tis': 'https://www.timesofisrael.com/britain-appoints-special-technology-ambassador-to-israel/',
'nhs': 'https://healthtech.blog.gov.uk/2019/06/24/nhsx-giving-patients-and-staff-the-technology-they-need/',
'tan': 'https://www.youtube.com/watch?v=7REeejwQ5Tc',
'siege': 'http://www.ejiltalk.org/is-gaza-still-occupied-by-israel/',
'zionism': 'https://www.nkusa.org/AboutUs/Zionism/judaism_isnot_zionism.cfm',
'pizza': 'https://www.haaretz.com/opinion/.premium-jews-and-capitalism-call-them-frenemies-1.5455400',
torah: 'https://torah.org/torah-portion/rabbiwein-5766-shoftim/',
'corrupt-leadership': 'https://www.myjewishlearning.com/article/corrupt-leadership/',
bribery: 'https://www.jewishvirtuallibrary.org/bribery',
wood: 'http://choppingwood.blogspot.com/2011/09/hasagat-gvul-message-for-each-of-us.html',
hassagat: 'https://www.jewishvirtuallibrary.org/hassagat-gevul',
'ef-history': 'https://medium.com/entrepreneur-first/entrepreneur-first-has-built-over-120-companies-so-who-built-ef-9ab067babab6',
te: 'https://tradingeconomics.com/united-kingdom/gdp-growth',
gps: 'https://www.medscape.com/slideshow/2019-uk-doctors-salary-report-6011623#8',
'alice-mat': 'https://www.youtube.com/watch?v=hJQr_h51dtg',
'al-jazeera': 'https://www.youtube.com/watch?v=ceCOhdgRBoc',
stats: 'https://www.ons.gov.uk/aboutus/transparencyandgovernance/freedomofinformationfoi/muslimpopulationintheuk/',
huddle: 'https://www.businessinsider.com/tech-city-not-needed-says-huddle-founder-2015-10',
'king-david': 'https://en.wikipedia.org/wiki/King_David_Hotel_bombing',
'network': 'https://www.theguardian.com/business/2019/may/02/railway-arches-sold-off-with-no-thought-for-tenants-says-watchdog',
}
|
function cargarOrdenes(){
var id = document.getElementById('doctor').value;
axios.post('/getOrdenes/'+id)
.then((resp)=>{
var tabla = document.getElementById('tablaordenes');
var cont = tabla.rows.length;
for (i = 0; i < (cont); i++) {
document.getElementById("borrar").remove();
}
for (i = 0; i < Object.keys(resp.data).length; i++) {
let suma = resp.data[i].id + 5000;
tabla.insertAdjacentHTML('afterbegin', '<tr id="borrar"><td>' + suma + '</td><td>' + resp.data[i].fechaImpresion + '</td><td>' + resp.data[i].numeroSocio + '</td><td>' + resp.data[i].user.name + '</td><td>' + resp.data[i].nombreDoctor + '</td><td>' + resp.data[i].monto_s + '</td><td>' + resp.data[i].monto_a + '</td><td>' + resp.data[i].lugarEmision + '</td><td>' + resp.data[i].estado + '</td><td>' + resp.data[i].fechaPago + '</td><td>' + resp.data[i].obs + '</td></tr>');
}
document.getElementById('paginador').style.display = "none";
})
.catch(function (error) {console.log(error);})
};
function pagarOrden(id){
event.preventDefault();
Swal.fire({
title: 'Pagar a la fecha actual?',
text: "Esta acción no se puede revertir!",
icon: 'question',
showCancelButton: true,
confirmButtonColor: '#FF7F00',
cancelButtonColor: '#d0aa5b',
confirmButtonText: 'Si, pagar!',
cancelButtonText: 'Cancelar'
}).then((result) => {
if (result.value) {
document.getElementById("formPagar"+id).submit();
Swal.fire(
'¡Pagado!',
'La órden ha sido pagada.',
'success'
)
}})
};
|
import reducer from "./modal";
import { modal } from "../actionTypes";
describe("modal reducer", () => {
it("should return the initial state", () => {
expect(reducer(undefined, {})).toEqual({
show: false,
title: "",
type: "primary",
onConfirm: null,
onCancel: null
});
});
it("showld set show true", () => {
expect(
reducer(undefined, {
type: modal.show
})
).toEqual({
show: true,
title: "",
type: "primary",
onConfirm: null,
onCancel: null
});
});
it("showld set show false", () => {
expect(
reducer(undefined, {
type: modal.hide
})
).toEqual({
show: false,
title: "",
type: "primary",
onConfirm: null,
onCancel: null
});
});
it("showld setup modal config", () => {
function onConfirm() {}
function onCancel() {}
expect(
reducer(undefined, {
type: modal.setup,
config: {
title: "new title",
type: "warning",
onConfirm,
onCancel
}
})
).toEqual({
show: false,
title: "new title",
type: "warning",
onConfirm,
onCancel
});
});
});
|
import request from '@/utils/request'
// 查询系统镜像列表
export function listImage(query) {
return request({
url: '/docker/image/list',
method: 'get',
params: query
})
}
// 查询系统镜像详细
export function getImage(id) {
return request({
url: '/docker/image/' + id,
method: 'get'
})
}
// 新增系统镜像
export function addImage(data) {
return request({
url: '/docker/image',
method: 'post',
data: data
})
}
// 修改系统镜像
export function updateImage(data) {
return request({
url: '/docker/image',
method: 'put',
data: data
})
}
// 删除系统镜像
export function delImage(id) {
return request({
url: '/docker/image/' + id,
method: 'delete'
})
}
// 导出系统镜像
export function exportImage(query) {
return request({
url: '/docker/image/export',
method: 'get',
params: query
})
}
|
var ul = document.getElementsByTagName('ul')[0];
var liLiveCollection = ul.getElementsByTagName('li');
var liStaticCollection = ul.querySelectorAll('li');
console.log(liLiveCollection);
console.log(liStaticCollection);
ul.removeChild(ul.firstElementChild);
console.log(liLiveCollection);
console.log(liStaticCollection);
var newLi = document.createElement('li');
newLi.className = 'new';
newLi.textContent = 'New';
ul.appendChild(newLi);
console.log(liLiveCollection);
console.log(liStaticCollection);
|
import React from 'react'
import { Link } from 'react-router-dom'
import Logo from '../assets/images/logo.png'
/**
* Función para mostrar el footer del sitio
* @returns Footer
*/
const Footer = () => {
return (
<footer>
<div className="container">
<div className="footer-container">
<div className="logo">
<Link to='/' className='logo' title='Ir al home'>
<img src={Logo} alt="Logo Capacítate para el empleo" />
</Link>
</div>
<ul className="menu-footer">
<li>
<Link to='/' title='Aviso de privacidad'>Aviso de privacidad</Link>
</li>
<li>
<Link to='/' title="Términos de uso">Términos de uso</Link>
</li>
<li>
<Link to='/' title="Contáctanos">Contáctanos</Link>
</li>
<li className='facebook'>
<a href="/" target="_blank" title='Ir a Facebook'><i className="fab fa-facebook-square"></i></a>
</li>
</ul>
</div>
</div>
</footer>
)
}
export default Footer
|
var1=61;
var2=60;
var3=var1+var2;
var4=var1-var2;
var5=var1/var2;
var6=var1*var2;
console.log("the addtion of two numbers is :",var3);
console.log("the subctraction of two numbers :",var4);
console.log("the division of two numbers is :",var5);
console.log("the mulctipication of two numbers",var6);
|
import React, { useContext, useEffect, useState } from 'react';
import { Link, useHistory } from 'react-router-dom';
import copy from 'clipboard-copy';
import RecipeContext from '../hooks/RecipeContext';
import recipeRequest from '../services/recipeRequest';
import whiteHeartIcon from '../images/whiteHeartIcon.svg';
import blackHeartIcon from '../images/blackHeartIcon.svg';
import shareIcon from '../images/shareIcon.svg';
import '../Style/RecipeDetails-Progress.css';
import '../Style/carousel.css';
const RecipeDetails = () => {
const six = 6;
const history = useHistory();
const {
foodRecommendation,
setFoodRecommendation,
DrinkRecommendation,
handleLikes,
setIds,
liked,
setLiked,
setDrinkRecommendation } = useContext(RecipeContext);
const [recipeDetailFood, setRecipeDetailFood] = useState([]);
const [recipeDetailDrink, setRecipeDetailDrink] = useState(undefined);
const [copied, setCopied] = useState('');
const { pathname } = history.location;
const ids = pathname.split('/')[2];
const kindof = pathname.split('/')[1];
const NINE = 9;
const TWENTY_NINE = 29;
const FOURTY_NINE = 49;
const THIRTY_SIX = 36;
const TWENTY_ONE = 21;
const FIFTY_ONE = 51;
const getAPI = async () => {
const food = await recipeRequest(`https://www.themealdb.com/api/json/v1/1/lookup.php?i=${ids}`);
const recipeFood = await food.meals;
const drink = await recipeRequest(`https://www.thecocktaildb.com/api/json/v1/1/lookup.php?i=${ids}`);
const recipeDrink = await drink.drinks;
setRecipeDetailFood(recipeFood);
setRecipeDetailDrink(recipeDrink);
};
const getRecommendation = async () => {
const foods = await recipeRequest('https://www.themealdb.com/api/json/v1/1/search.php?s=');
const foodsData = await foods.meals;
const drinks = await recipeRequest('https://www.thecocktaildb.com/api/json/v1/1/search.php?s=');
const drinksData = await drinks.drinks;
setFoodRecommendation(foodsData);
setDrinkRecommendation(drinksData);
};
const usarNoUse = async () => {
await getAPI();
await getRecommendation();
if (!localStorage.favoriteRecipes) {
localStorage.favoriteRecipes = JSON.stringify([]);
}
const favoriteStorage = JSON.parse(localStorage.favoriteRecipes)
.filter((item) => item.id === ids);
if (favoriteStorage.length >= 1) {
setLiked(blackHeartIcon);
} else {
setLiked(whiteHeartIcon);
}
};
const inProgressCheck = () => {
if (kindof === 'comidas') {
if (!localStorage.inProgressRecipes) {
localStorage.inProgressRecipes = JSON.stringify({
cocktails: {}, meals: { [ids]: ['null'] } });
} else if (JSON.parse(localStorage.inProgressRecipes).meals[ids]) {
// const reset = JSON.parse(localStorage.inProgressRecipes = )
localStorage.inProgressRecipes = JSON.stringify(
{ ...JSON.parse(localStorage.inProgressRecipes),
meals: { ...JSON.parse(localStorage.inProgressRecipes).meals },
},
);
} else {
localStorage.inProgressRecipes = JSON.stringify(
{ ...JSON.parse(localStorage.inProgressRecipes),
meals: { ...JSON.parse(localStorage.inProgressRecipes).meals,
[ids]: ['null'] },
},
);
}
} else if (!localStorage.inProgressRecipes) {
localStorage.inProgressRecipes = JSON.stringify({
cocktails: { [ids]: ['null'] }, meals: {} });
} else if (JSON.parse(localStorage.inProgressRecipes).cocktails[ids]) {
// const reset = JSON.parse(localStorage.inProgressRecipes = )
localStorage.inProgressRecipes = JSON.stringify(
{ ...JSON.parse(localStorage.inProgressRecipes),
cocktails: { ...JSON.parse(localStorage.inProgressRecipes).cocktails },
},
);
} else {
localStorage.inProgressRecipes = JSON.stringify(
{ ...JSON.parse(localStorage.inProgressRecipes),
cocktails: { ...JSON.parse(localStorage.inProgressRecipes)
.cocktails,
[ids]: ['null'] },
},
);
}
};
useEffect(() => {
usarNoUse();
inProgressCheck();
}, []);
const handleIngredients = (recipe, initial, middle, end) => {
const ingredients = Object.values(recipe).slice(initial, middle);
const measures = Object.values(recipe).slice(middle, end);
return ingredients
.filter((recipes) => recipes !== null && recipes !== '')
.map((ingredient, index) => (
<li key={ index } data-testid={ `${index}-ingredient-name-and-measure` }>
{ `${ingredient} - ${measures[index]}` }
</li>
));
};
const handleCopy = () => {
copy(window.location.href);
const TWO = 2000;
setCopied('Link copiado!');
setInterval(() => setCopied(''), TWO);
};
const renderRecipe = () => {
if (pathname === `/comidas/${ids}` && recipeDetailFood.length >= 1) {
return recipeDetailFood.map((food, index) => (
<div key={ index } className="details-container">
<img
alt="product"
data-testid="recipe-photo"
src={ food.strMealThumb }
/>
<div className="details-nav">
<button onClick={ () => handleLikes(recipeDetailFood[0]) } type="button">
<img data-testid="favorite-btn" src={ liked } alt="favorite" />
</button>
<div className="name-category">
<p
data-testid="recipe-title"
>
{ food.strMeal }
</p>
<p data-testid="recipe-category">
{food.strCategory}
</p>
</div>
<button type="button" onClick={ handleCopy }>
<img data-testid="share-btn" src={ shareIcon } alt="share" />
</button>
{copied}
</div>
<div className="ing-inst">
<div className="recipe-ingredients">
<h5>INGREDIENTS</h5>
{
handleIngredients(food, NINE, TWENTY_NINE, FOURTY_NINE)
}
</div>
<div className="recipe-instructions">
<h5>INSTRUCTIONS</h5>
<p data-testid="instructions">
{ food.strInstructions }
</p>
</div>
</div>
<div className="recipe-video">
<video data-testid="video" width="750" height="500" controls>
<source src={ food.strYoutube } type="video/mp4" />
<track src={ food.strYoutube } kind="captions" />
</video>
</div>
<div className="carousel scroller">
{
DrinkRecommendation && DrinkRecommendation.length && DrinkRecommendation
.filter((_, indexs) => indexs < six)
.map((drinks, indx) => (
<div
data-testid={ `${indx}-recomendation-card` }
key={ indx }
className="card"
>
<Link
onClick={ () => setIds(drinks.idDrink) }
to={ `/bebidas/${drinks.idDrink}` }
key={ indx }
className="recomendation-link"
>
<img
src={ drinks.strDrinkThumb }
data-testid={ `${indx}-card-img` }
alt={ drinks.strDrink }
/>
</Link>
<p
data-testid={ `${indx}-recomendation-title` }
className="carousel-item"
>
{ drinks.strDrink}
</p>
</div>
))
}
</div>
{(JSON.parse(localStorage.inProgressRecipes).meals[ids].length > 1) ? (
<button
type="button"
className="start-continue-recipe-btn"
data-testid="start-recipe-btn"
onClick={ () => history.push(`${pathname}/in-progress`) }
>
Continue Recipe
</button>
) : (
<button
type="button"
data-testid="start-recipe-btn"
className="start-continue-recipe-btn"
onClick={ () => history.push(`${pathname}/in-progress`) }
>
Start Recipe
</button>)}
</div>
));
}
if (recipeDetailDrink !== undefined) {
return recipeDetailDrink.map((drink, index) => (
<div key={ index } className="details-container">
<img
alt="product"
data-testid="recipe-photo"
src={ drink.strDrinkThumb }
/>
<div className="details-nav">
<button
onClick={ () => handleLikes(recipeDetailFood, recipeDetailDrink[0]) }
type="button"
>
<img src={ liked } data-testid="favorite-btn" alt="favorite" />
</button>
<div className="name-category">
<p
data-testid="recipe-title"
>
{ drink.strDrink }
</p>
<p data-testid="recipe-category">
{drink.strAlcoholic}
</p>
</div>
<button onClick={ handleCopy } type="button" data-testid="share-btn">
<img src={ shareIcon } alt="share" />
</button>
{ copied }
</div>
<div className="ing-inst">
<div className="recipe-ingredients">
<h5>INGREDIENTS</h5>
{
handleIngredients(drink, TWENTY_ONE, THIRTY_SIX, FIFTY_ONE)
}
</div>
<div className="recipe-instructions">
<h5>INSTRUCTIONS</h5>
<p data-testid="instructions">{ drink.strInstructions }</p>
</div>
</div>
<div className="carousel scroller">
{
foodRecommendation && foodRecommendation.length && foodRecommendation
.filter((_, idx) => idx < six)
.map((meals, ind) => (
<div
className="card"
data-testid={ `${ind}-recomendation-card` }
key="index"
>
<Link
onClick={ () => setIds(meals.idMeal) }
to={ `/comidas/${meals.idMeal}` }
key={ index }
className="recomendation-link"
>
<img
src={ meals.strMealThumb }
data-testid={ `${ind}-card-img` }
alt={ meals.strMeal }
/>
</Link>
<p
className="carousel-item"
data-testid={ `${ind}-recomendation-title` }
>
{ meals.strMeal}
</p>
</div>
))
}
</div>
{(JSON.parse(localStorage.inProgressRecipes).cocktails[ids].length > 1) ? (
<button
type="button"
style={ { position: 'fixed', bottom: 0 } }
data-testid="start-recipe-btn"
onClick={ () => history.push(`${pathname}/in-progress`) }
className="start-continue-recipe-btn"
>
Continue Recipe
</button>
) : (
<button
type="button"
data-testid="start-recipe-btn"
style={ { position: 'fixed', bottom: 0 } }
onClick={ () => history.push(`${pathname}/in-progress`) }
className="start-continue-recipe-btn"
>
Start Recipe
</button>)}
</div>
));
}
};
return (
<div>
{ renderRecipe() }
</div>
);
};
export default RecipeDetails;
|
import React from 'react';
import SingleProject from './SingleProject';
import GridList from '@material-ui/core/GridList';
import GridListTile from '@material-ui/core/GridListTile';
import GridListTileBar from '@material-ui/core/GridListTileBar';
import ListSubheader from '@material-ui/core/ListSubheader';
import Modal from '@material-ui/core/Modal';
//Images for projects
import RFID from '../resources/rfid.png';
import TODO from '../resources/todo-app.png';
import Tower from '../resources/tower.png';
import MIDI from '../resources/midi-controller.png';
import BachJam from '../resources/back-jam.png';
import Rooftops from '../resources/rooftops.jpg';
import Spectrogram from '../resources/spectrogram.png';
let projects = [
{
color: "",
picture: Spectrogram,
headerText: "Spectrogram",
subHeaderText: "Web Developer",
bodyText: <div>Designed an adjustable spectrogram for
<a className="projects-link" href="http://www.listeningtowaves.com/"> ListeningToWaves
</a> using JavaScript’s Web Audio API. It is based on a previous project by Boris Smus
(Click <a className="projects-link" href="https://github.com/borismus/spectrogram">here</a> for his project).
The project has a ton of controls, including changing the limits of the graph. You can also draw on it with your mouse or finger,
creating a sine wave at the touched frequency. Furthermore, there are options to
change the timbre of the sound as well as snap the drawn frequencies to a specific scale.
You can view a demo of the project
<a className="projects-link" href="http://listeningtowaves.github.io/Spectrogram/">here</a>.
I'm also currently working on a Web Audio-based oscilloscope and signal generator.</div>,
technologiesText: "Web Audio API, HTML/CSS, Vanilla Javascript, Music Theory",
buttonLink: "https://github.com/ListeningToWaves/Spectrogram",
buttonText: "View On Github",
anchorId: "web-dev",
key: 1
},
{
color: "#f2f271",
picture: RFID,
headerText: "Birch Aquarium RFID Pathways",
subHeaderText: "Product Designer",
bodyText: `Worked with a team to develop an RFID-based\
personalized system that would showcase the potential of RFID technology.\
The goal was for users to have an RFID ticket that they could register to\
a specific 'professional pathway'. Each pathway would be a specific role\
on a science team that the user would take on and as they traveled around\
the Aquarium they were able to scan their card and see additional content\
based on their pathway. We also created an update system that allows for\
simple, picture-based updates to the content.`,
technologiesText: 'Raspberry Pi, HTML/CSS, Vanilla Javascript, JQuery, Firebase',
buttonLink: "https://github.com/jguidry/SEE_2017_RFID_Pathways",
buttonText: "View On Github",
key: 2
},
{
color: "green",
picture: TODO,
headerText: "My Todo App",
subHeaderText: "Web Developer",
bodyText: `Based on Andrew Mead's 'Complete React Web App Developer Course'\
on Udemy, this app lets a user login using Github, and make a todo list.\
Users can then search todos, check off todos, and delete todos. The list\
will show a timestamp when actions are performed. Skills learned from this\
course heavily influenced the development of this website (which is also\
written in React).`,
technologiesText: 'React, Redux, Firebase, Heroku',
buttonLink: "https://github.com/mhrice/React-todo",
buttonText: "View On Github",
key: 3
},
{
color: "red",
picture: Tower,
headerText: "Tower",
subHeaderText: "Full-Stack Engineer",
bodyText: `Tower is a texting campaign platform from startup company\
Alchemy. I worked on both front-end and back-end to customize the UI and\
the functionality of the texting system. This project is currently in\
development as we are adding voicemail-drop functionality and email/push\
notifications.`,
technologiesText: `Ionic Framework, Firebase, Plivo, Firebase-Functions\
(as backend microservices)`,
buttonLink: "https://gitlab.ixir.io/Tower/client-app/",
buttonText: "View On Github",
key: 4
},
{
color: "purple",
picture: BachJam,
headerText: "Bach Little Fugue in Gm Jam",
subHeaderText: "Audio Programmer",
bodyText: `This was a fun electronic performace based on Bach's four-voice\
organ piece: 'Little' Fugue in G minor. Using Pure Data, I first created four\
seperate organ patches and programmed them to play each voice's individual\
MIDI data. I then created my own synth to 'jam' on top of the original voices.\
Next I constructed a drum sequencer, and for the live performace, I 'sang' in\
beatbox style drums and programed the drums to hit on different beats of\
each measure. I also produced audio effects to layer at various points\
including filtering, tremolo, and flanger as well as an eq. Finally, I\
mapped all of the controls to my Novation LaunchKey 49 and performed my\
jam with an annotated score.`,
technologiesText: 'Pure Data, Novation LaunchKey 49',
buttonLink: "https://github.com/mhrice/MUS172Final",
buttonText: "View On Github",
anchorId: "audio",
key: 5
},
{
color: "orange",
picture: MIDI,
headerText: "Arduino Sampler and Effects",
subHeaderText: "Audio Programmer",
bodyText: `I created an audio tool that would record samples with a\
microphone and then given the user the ability to play back the samples \
and add on effects. These effects included distortion, filtering, \
bitcrushing, and tempo changes. The user was provided with haptic and \
visual feedback using buttons and LEDs as well as a potentiometer and a \
multi-colored LED for individual parameter control.`,
technologiesText: 'Arduino, Pure Data',
buttonLink: "https://github.com/mhrice/MUS172Final",
buttonText: "View On Github",
key: 6,
anchorId: 'embedded'
},
{
color: "#3edcf2",
picture: Rooftops,
headerText: "Rooftops Album",
subHeaderText: "Producer",
bodyText: <div>I recorded, mixed, and mastered this album for a friend of
mine, Brian Frulla. This was recorded in spring of 2017 at my appartment
with a condenser mic (AT2020), as well as an EIE Pro Audio Interface
and a pair of Rockit KRK 8's. The genre is acoustic. For the most of the
tracks, there were only two inputs, Brian's guitar and his vocals, except
for the last track which featured Chris Mukiibi with extra vocals.
Overall it was super fun to produce this album and I'm looking forward to
collaborating more with Brian.
{/*<div className="soundcloud">
<h2> You can also see other music projects on my SoundCloud by clicking
this logo: </h2>
<iframe
allowTransparency="true"
scrolling="no"
frameBorder="no"
src="https://w.soundcloud.com/icon/?url=http%3A%2F%2Fsoundcloud.com%2Fmatthew-rice-6&color=orange_white&size=32"
style={{width: "32px", height: "32px"}}
title="soundcloud">
</iframe>
</div>*/}
</div>,
technologiesText: 'Ableton Live, Audio-Technica AT2020, Ozone 7',
buttonLink: "https://brianfrulla.bandcamp.com/album/rooftops",
buttonText: "View On Bandcamp",
key: 7
},
// {
// color: "yellow",
// picture: igm,
// headerText: "Header",
// subHeaderText: "Sub",
// bodyText: "This is a body paragraph.",
// buttonLink: "www.google.com",
// key: 7
// }
]
export default class Projects extends React.Component {
constructor(){
super();
this.state = {modalOpen: false, project:{}}
}
//color, picture, headerText, subHeaderText, bodyText, buttonLink
renderProjects() {
// <SingleProject
// color={project.color}
// picture={project.picture}
// headerText={project.headerText}
// subHeaderText={project.subHeaderText}
// bodyText={project.bodyText}
// buttonLink={project.buttonLink}
// technologiesText={project.technologiesText}
// buttonText={project.buttonText}
// anchorId={project.anchorId}
// key={project.key}
// theKey={project.key}
// />
// )
const listItems = projects.map((project, index)=>{
return(
<GridListTile key={project.key} className="project-item" onClick={(e)=>this.showProject(index)}>
<img src={project.picture}/>
<GridListTileBar title={project.headerText}/>
</GridListTile>
)
});
return listItems
}
showProject = (index) =>{
let project = projects[index];
this.setState({project: project, modalOpen: true});
}
handleClose = () =>{
this.setState({modalOpen: false})
}
render() {
let numCols;
if(this.props.width < 500){
numCols = 2;
}
else if(this.props.width < 800){
numCols = 3;
} else {
numCols = 4;
}
return (
<div className="projects-container">
<GridList cellHeight={160} cols={numCols} className="projects-grid" spacing={6}>
{this.renderProjects()}
</GridList>
<Modal
open={this.state.modalOpen}
onClose={this.handleClose}
>
<SingleProject
color={this.state.project.color}
picture={this.state.project.picture}
headerText={this.state.project.headerText}
subHeaderText={this.state.project.subHeaderText}
bodyText={this.state.project.bodyText}
buttonLink={this.state.project.buttonLink}
technologiesText={this.state.project.technologiesText}
buttonText={this.state.project.buttonText}
anchorId={this.state.project.anchorId}
key={this.state.project.key}
theKey={this.state.project.key}
tabIndex={-1}
/>
</Modal>
</div>
)
}
}
|
/**
*description:商品选择弹框
*author:fanwei
*date:2014/06/26
*/
define(function(require, exports, module){
var Fenye = require('../../widget/dom/fenye');
var Related = require('../../widget/dom/related');
var bodyParse = require('../../widget/http/bodyParse');
function GoodsSelect(opts) {
opts = opts || {};
this.gparam = bodyParse();
this.gid = this.gparam.goods_id || '';
this.getDataUrl = '/lgwx/index.php/view/goods/selection_list';
this.initParam = {p:1, num:5, series_id:'', brand_id: '', goods_id: this.gid};
this.fenyeId = 'goods-tpl-info';
this.oDataWrap = $('[sc = goods-list-wrap]');
this.save = [];
this.lastSave = [];
this.confirmUrl = opts.confirmUrl || '';
this.onConfirm = opts.onConfirm || null;
this.MAX = 10;
this.MIN = 2;
}
GoodsSelect.prototype = {
init: function() {
this.renderBox();
this.events();
},
events: function() {
var _this = this;
//查询
$(document).on('click', '[sc = goods-search-btn]', function(){
_this.search();
});
//选择
$(document).on('click', '[sc = goods-select-item]', function(){
var nowId;
nowId = $(this).attr('scid');
if( _this.gid == nowId ) {
alert('不能选择当前商品');
return false;
}
_this.select($(this));
});
//确定
$(document).on('click', '[sc = goods-confirm-select]', function(){
_this.confirm($(this));
});
},
search: function() {
//查询方法
var brand_id,
series_id;
brand_id = this.oBrand.val();
series_id = this.oSeries.val();
this.initParam.series_id = series_id;
this.initParam.brand_id = brand_id;
this.page.refresh( this.initParam );
},
select: function(oThis) {
//选择
var sTtype,
sId,
isChecked,
i,
num;
sTtype = oThis.attr('type');
sId = oThis.attr('scid');
switch( sTtype ) {
case 'radio':
this.save[0] = sId;
break;
case 'checkbox':
num = this.save.length;
isChecked = oThis.attr('checked');
if( isChecked ) {
this.save.push(sId);
} else {
this.removeId(sId);
}
break;
}
},
removeId: function(targetId) {
var num;
num = this.save.length;
for (i=0; i<num; i++) {
if( this.save[i] == targetId ) {
this.save.splice(i, 1);
this.lastSave.splice(i, 1);
}
}
},
confirm: function(oThis) {
var _this,
type,
result;
type = oThis.attr('type');
result = this.check(type);
if( result ) {
this.upload();
}
},
upload: function() {
var param,
_this;
_this = this;
param = {};
param.goods_id = this.save.join(',');
$.post(this.confirmUrl, param, function(data){
if( !data.err ) {
_this.copySave();
_this.onConfirm && _this.onConfirm( data );
} else {
alert(data.msg);
}
}, 'json');
},
cancel: function() {
this.copyLastSave();
this.matchSelect( this.save );
},
copyLastSave: function(oArr) {
var i,
num;
this.save = [];
num = this.lastSave.length;
for (i=0; i<num; i++) {
this.save[i] = this.lastSave[i];
}
},
copySave: function() {
var i,
num;
this.lastSave = [];
num = this.save.length;
for (i=0; i<num; i++) {
this.lastSave[i] = this.save[i];
}
},
check: function(type) {
var num;
num = this.save.length;
if( type == 'single' ) {
if( !num ) {
alert('请选择');
return false;
} else {
return true;
}
} else if( type == 'multi' ) {
if( num < this.MIN || num > this.MAX ) {
alert('请选择'+ this.MIN +'-'+ this.MAX +'个商品');
return false;
} else {
return true;
}
}
},
renderBox: function() {
var _this = this;
var _fenye = new Fenye(this.getDataUrl, this.fenyeId, this.initParam, function(){
_this.relation();
_this.matchSelect(_this.save);
}, null, this.oDataWrap);
this.page = _fenye;
},
relation: function() {
this.oBrand = $('[sc = brand]');
this.oSeries = $('[sc = series]');
var oRelated = new Related({
oMain: this.oBrand,
oSub: this.oSeries,
MainUrl: '/lgwx/index.php/view/series/brandToSeries',
SubUrl: '/lgwx/index.php/view/series/brandToSeries',
firstLoad: false,
tplMain: '',
tplSub: '<option value="">选择系列</option>'+
'{{each series_list}}'+
'<option value="{{$value.series_id}}" id="{{$value.series_id}}" {{if $value.select == 1}}selected="selected"{{/if}}>{{$value.series_name}}</option>'+
'{{/each}}',
paramName:'brand_id'
});
oRelated.init();
},
matchSelect: function(vId) {
//切换分页时匹配选中
var aSid,
nowInputSid,
dataSid,
arrId,
k,
num;
aSid = $('[sc = goods-select-item]');
num = vId.length;
aSid.each(function(i){
aSid.eq(i).removeAttr('checked');
});
aSid.each(function(i){
nowInputSid = aSid.eq(i).attr('scid');
for (k=0; k<vId.length; k++) {
dataSid = vId[k];
if( nowInputSid == dataSid ) {
aSid.eq(i).attr('checked', 'checked');
}
}
});
}
};
module.exports = GoodsSelect;
});
|
const crawlDomain = require('./src/crawler.js');
const util = require('util');
// Stop after visting MAX_PAGES
let MAX_PAGES = 50;
// The domain name should be passed in as a single argument e.g. 'www.google.com'
let domain = process.argv[2];
// Optional max pages
let new_max = process.argv[3];
if (!isNaN(parseInt(new_max, 10))) {
MAX_PAGES = parseInt(new_max, 10);
}
//normalize the trailing /
if (!domain.endsWith('/')) {
domain = domain + '/'
}
let startUrl = domain;
// I don't do any tests to test the domain's validity
// general node development style is to fail fast on bad input
// I handle input with or without a 'http[s]://' prefix.
// If given a specific one, I'll start the crawl with that scheme
// otherwise I'll start with http://domain
if (domain.startsWith('http')) {
domain = domain.slice(domain.indexOf('://') + 3);
} else {
startUrl = 'http://' + domain;
}
// Crawl the domain from the start page within the domain
crawlDomain(startUrl, domain, MAX_PAGES).then(crawledPages => {
// output the results to STDOUT in json
console.log(util.inspect(crawledPages));
});
|
import { connect } from 'react-redux';
import EditDialog from './EditDialog';
import {postOption, fetchJson, showError, validValue} from '../../../common/common';
import {Action} from '../../../action-reducer/action';
import {getPathValue} from '../../../action-reducer/helper';
import {updateTable} from './OrderPageContainer';
import {toFormValue} from '../../../common/check';
const URL_NEW = '/api/platform/importTemplate/new';
const URL_UPDATE = '/api/platform/importTemplate/edit';
const URL_API_LIST = '/api/platform/importTemplate/api_list';
const PARENT_STATE_PATH = ['platform', 'importTemplate'];
const STATE_PATH = ['platform', 'importTemplate', 'edit'];
const action = new Action(STATE_PATH);
const actionParent = new Action(PARENT_STATE_PATH);
const CLOSE_ACTION = action.assignParent({edit: undefined});
const buildEditState = (config, data, isEdit, editIndex, modeDic, fileList, upload, newModeValue) => {
let newConfig = config;
let label;
if(isEdit){
if(newModeValue){
data.modeValue = newModeValue;
modeDic.map(item =>{
if(data.uploadMode === item.value){
label = item.title;
}
})
if(data.active === 'active_unactivated'){
const [ ...controls ] = config.controls;
controls.map(item => {
if (item.key === 'modeValue') {
item.type = 'search';
item.title = label;
item.required = true;
}
});
newConfig = Object.assign({}, config, {controls});
}else if(data.active === "active_activated"){
const [ ...editControls ] = config.editControls;
editControls.map(item => {
if (item.key === 'modeValue') {
item.type = 'readonly';
item.title = label;
item.required = true;
}
});
newConfig = Object.assign({}, config, {editControls});
}
}else {
data;
modeDic.map(item =>{
if(data.uploadMode === item.value){
label = item.title;
}
})
if(data.active === 'active_unactivated'){
const [ ...controls ] = config.controls;
controls.map(item => {
if (item.key === 'modeValue') {
item.type = 'text';
item.title = label;
item.required = true;
}
});
newConfig = Object.assign({}, config, {controls});
}else if(data.active === "active_activated"){
const [ ...editControls ] = config.editControls;
editControls.map(item => {
if (item.key === 'modeValue') {
item.type = 'readonly';
item.title = label;
item.required = true;
}
});
newConfig = Object.assign({}, config, {editControls});
}
}
}else{
const [ ...controls ] = config.controls;
controls.map(item => {
if (item.key === 'modeValue') {
item.type = 'search';
item.title = 'EPLD导入库';
item.required = true;
}
});
newConfig = Object.assign({}, config, {controls});
}
return {
modeDic,
isEdit,
editIndex,
config: config.config,
...newConfig,
title: isEdit ? config.edit : config.add,
value: data,
fileList: fileList,
size: 'middle',
upload: upload
};
};
const getSelfState = (rootState) => {
return getPathValue(rootState, STATE_PATH);
};
const getParentState = (rootState) => {
return getPathValue(rootState, PARENT_STATE_PATH);
};
const changeActionCreator = (file) => (dispatch, getState) => {
dispatch(action.assign({fileList: [file]}));
};
const removeActionCreator = () => (dispatch) => {
dispatch(action.assign({fileList: []}));
};
const formSearchActionCreator = (key, value) => async (dispatch, getState) => {
const {controls} = getSelfState(getState());
if(key ==='modeValue'){
const body = {maxNumber: 10, filter: value};
const res = await fetchJson(URL_API_LIST, postOption(body));
if(res.returnCode !== 0){
showError(res.returnMsg);
return;
}
const index = controls.findIndex(item => item.key == key);
dispatch(action.update({options: res.result}, 'controls', index));
}
};
const formChangeActionCreator = (key, value) => (dispatch, getState) => {
const {modeDic, controls} = getSelfState(getState());
let label = '';
if(key === 'uploadMode' && value){
dispatch(action.assign({[key]: value, modeValue: ''}, 'value'));
dispatch(action.assign({fileList: []}));
if(value !== 'upload_mode_epld_excel'){
const upload = true;
dispatch(action.assign({upload}));
dispatch(action.update({type: 'text', required: true}, 'controls', {key: 'key', value: 'modeValue'}));
}else{
const upload = false;
dispatch(action.assign({upload}));
dispatch(action.update({type: 'search', required: true}, 'controls', {key: 'key', value: 'modeValue'}));
}
modeDic.map(item =>{
if(value === item.value){
label = item.title;
}
})
dispatch(action.update({title: label}, 'controls', {key: 'key', value: 'modeValue'}));
}
dispatch(action.assign({[key]: value}, 'value'));
};
const exitValidActionCreator = () => {
return action.assign({valid: false});
};
const okActionCreator = () => async (dispatch, getState) => {
const {isEdit, editIndex, value, controls, fileList} = getSelfState(getState());
if (!validValue(controls, value)) {
dispatch(action.assign({valid: true}));
return;
}
let newFile;
if(value.uploadMode === 'upload_mode_epld_excel'){
newFile = [];
}else{
if(fileList && fileList.length ===1){
newFile = fileList.map(item => ({fileFormat: item.fileFormat || 'id', fileName: item.name, fileUrl: item.response.result}));
}else{
showError('附件不能没空!');
return;
}
}
const postData = {
id: value.id? value.id: '',
uploadSubject: value.uploadSubject,
downloadSubject: value.downloadSubject,
uploadMode: value.uploadMode,
modeValue: value.modeValue,
notifyEmailAddress: value.notifyEmailAddress,
uploadTemplate: newFile
};
let option, data;
if(isEdit){
data = await fetchJson(URL_UPDATE, postOption(toFormValue(postData), 'put'));
}else{
option = postOption(toFormValue(postData));
data = await fetchJson(URL_NEW, option);
}
if (data.returnCode !== 0) {
showError(data.returnMsg);
return;
}
dispatch(CLOSE_ACTION);
return updateTable(dispatch, getState);
};
const cancelActionCreator = () => (dispatch) => {
dispatch(CLOSE_ACTION);
};
const mapStateToProps = (state) => {
return getSelfState(state);
};
const actionCreators = {
onOk: okActionCreator,
onCancel: cancelActionCreator,
onChange: changeActionCreator,
onRemove: removeActionCreator,
onFormSearch: formSearchActionCreator,
onFormChange: formChangeActionCreator,
onExitValid: exitValidActionCreator,
};
const Container = connect(mapStateToProps, actionCreators)(EditDialog);
export default Container;
export {buildEditState};
|
/**
* 화면 초기화 - 화면 로드시 자동 호출 됨
*/
function _Initialize() {
// 단위화면에서 사용될 일반 전역 변수 정의
// $NC.setGlobalVar({ });
// 단위화면에서 사용될 일반 전역 변수 정의
$NC.setGlobalVar({
ROWCHAK: "",
LAST_YN: ""
});
// 탭 초기화
$NC.setInitTab("#divMasterView", {
tabIndex: 0,
onActivate: tabOnActivate
});
// 그리드 초기화
grdT1MasterInitialize();
grdT1DetailInitialize();
grdT2MasterInitialize();
grdT2DetailInitialize();
grdT3MasterInitialize();
grdT3DetailInitialize();
grdSubInitialize();
// 조회조건 - 사업부 초기값 설정
$NC.setValue("#edtQBu_Cd", $NC.G_USERINFO.BU_CD);
$NC.setValue("#edtQBu_Nm", $NC.G_USERINFO.BU_NM);
$NC.setValue("#edtQCust_Cd", $NC.G_USERINFO.CUST_CD);
$NC.setInitDatePicker("#dtpQHas_Date");
$("#RePrint").click(doPrint4);
$("#Ts1").click(TS1);
$("#btnERPSend").click(Hassend);
$('#btnGoHap').click(function(){
var rowData = parent.G_GRDPROGRAMMENU.data.getItems();
parent.showProgramPopup(rowData[106]);
});
// 조회조건 - 물류센터 초기화
$NC.setInitCombo("/WC/getDataSet.do", {
P_QUERY_ID: "WC.POP_CSUSERCENTER",
P_QUERY_PARAMS: $NC.getParams({
P_USER_ID: $NC.G_USERINFO.USER_ID,
P_CENTER_CD: "%"
})
}, {
selector: "#cboQCenter_Cd",
codeField: "CENTER_CD",
nameField: "CENTER_NM",
onComplete: function() {
$NC.setValue("#cboQCenter_Cd", $NC.G_USERINFO.CENTER_CD);
}
});
// 조회조건 - 입출고구분 세팅
$NC.setInitCombo("/WC/getDataSet.do", {
P_QUERY_ID: "WC.POP_CMCODE",
P_QUERY_PARAMS: $NC.getParams({
P_CODE_GRP: "HAS_END_YN",
P_CODE_CD: "",
P_SUB_CD1: "",
P_SUB_CD2: ""
})
}, {
selector: "#cboQEnd_Yn",
codeField: "CODE_CD",
nameField: "CODE_NM",
fullNameField: "CODE_CD_F",
addAll: true
});
// 조회조건 - 입출고구분 세팅
$NC.setInitCombo("/WC/getDataSet.do", {
P_QUERY_ID: "WC.POP_CMCODE",
P_QUERY_PARAMS: $NC.getParams({
P_CODE_GRP: "LOC_DIV1",
P_CODE_CD: "",
P_SUB_CD1: "",
P_SUB_CD2: ""
})
}, {
selector: "#cboQLoc_Div",
codeField: "CODE_CD",
nameField: "CODE_NM",
fullNameField: "CODE_CD_F",
onComplete: function() {
$NC.setValue("#cboQLoc_Div");
}
});
}
function _OnLoaded() {
$NC.setInitSplitter("#divT1DetailView", "v", 750);
$NC.setInitSplitter("#test", "h", 200);
// 미처리/오류 내역 탭 화면에 splitter 설정
$NC.setInitSplitter("#divT2DetailView", "v", 800);
$NC.setInitSplitter("#divT3DetailView", "v", 700);
}
/**
* 화면 리사이즈 Offset 세팅
*/
function _SetResizeOffset() {
$NC.G_OFFSET.leftViewWidth = 625;
$NC.G_OFFSET.nonClientHeight = $("#divConditionView").outerHeight() + $NC.G_LAYOUT.nonClientHeight;
$NC.G_OFFSET.tabHeaderHeight = $("#divMasterView").children(".ui-tabs-nav:first").outerHeight();
}
/**
* Window Resize Event - Window Size 조정시 호출 됨
*/
function _OnResize(parent) {
var clientWidth = parent.width() - $NC.G_LAYOUT.border1 * 2; /* 탭일 경우는 좌우 */
var clientHeight = parent.height() - $NC.G_OFFSET.nonClientHeight - $NC.G_LAYOUT.border1;
$NC.resizeContainer("#divMasterView", clientWidth, clientHeight);
clientWidth -= $NC.G_LAYOUT.border1;
clientHeight -= ($NC.G_OFFSET.tabHeaderHeight + $NC.G_LAYOUT.border1);
// 기타입출고등록 탭
if ($("#divMasterView").tabs("option", "active") === 0) {
// var clientWidth = parent.width() - $NC.G_LAYOUT.border1;
// var clientHeight = parent.height() - $NC.G_OFFSET.nonClientHeight;
$("#lblQEND_YN").show();
$("#cboQEND_YN").show();
// Splitter 컨테이너 크기 조정
var container = $("#divT1DetailView");
$NC.resizeContainer(container, clientWidth, clientHeight);
container = $("#grdT1Master").parent();
// Master Grid 사이즈 조정
$NC.resizeGrid("#grdT1Master", container.width(), container.height() - $NC.G_LAYOUT.header);
// Splitter 컨테이너 크기 조정
container = $("#test");
var splitter = container.children(".splitter-bar");
splitter.width(container.width());
container = $("#grdT1Detail").parent();
// Detail Grid 사이즈 조정
$NC.resizeGrid("#grdT1Detail", container.width(), container.height() - $NC.G_LAYOUT.header);
container = $("#grdSub").parent();
// Sub Grid 사이즈 조정
$NC.resizeGrid("#grdSub", container.width(), container.height() - $NC.G_LAYOUT.header);
/*--------------------------------------*/
// Splitter 컨테이너 크기 조정
/*
var container = $("#divT1DetailView");
$NC.resizeContainer(container, clientWidth, clientHeight);
// Grid 사이즈 조정
$NC.resizeGrid("#grdT1Master", $("#grdT1Master").parent().width(), clientHeight - $NC.G_LAYOUT.header);
// Grid 사이즈 조정
$NC.resizeGrid("#grdT1Detail", $("#grdT1Detail").parent().width(), clientHeight - $NC.G_LAYOUT.header);
*/
} else if ($("#divMasterView").tabs("option", "active") === 1) {
$("#lblQEND_YN").hide();
$("#cboQEND_YN").hide();
// Splitter 컨테이너 크기 조정
var container = $("#divT2DetailView");
$NC.resizeContainer(container, clientWidth, clientHeight);
// Grid 사이즈 조정
$NC.resizeGrid("#grdT2Master", $("#grdT2Master").parent().width(), clientHeight - $NC.G_LAYOUT.header);
// Grid 사이즈 조정
$NC.resizeGrid("#grdT2Detail", $("#grdT2Detail").parent().width(), clientHeight - $NC.G_LAYOUT.header);
} else if ($("#divMasterView").tabs("option", "active") === 2) {
$("#lblQEND_YN").hide();
$("#cboQEND_YN").hide();
// Splitter 컨테이너 크기 조정
var container = $("#divT3DetailView");
$NC.resizeContainer(container, clientWidth, clientHeight);
// Grid 사이즈 조정
$NC.resizeGrid("#grdT3Master", $("#grdT3Master").parent().width(), clientHeight - $NC.G_LAYOUT.header);
// Grid 사이즈 조정
$NC.resizeGrid("#grdT3Detail", $("#grdT3Detail").parent().width(), clientHeight - $NC.G_LAYOUT.header);
}
}
/**
* Condition Change Event - Input, Select Change 시 호출 됨
*/
function _OnConditionChange(e, view, val) {
var id = view.prop("id").substr(4).toUpperCase();
// 브랜드 Key 입력
switch (id) {
case "BU_CD":
var P_QUERY_PARAMS;
var O_RESULT_DATA = [ ];
if (!$NC.isNull(val)) {
P_QUERY_PARAMS = {
P_USER_ID: $NC.G_USERINFO.USER_ID,
P_BU_CD: val
};
O_RESULT_DATA = $NP.getUserBuInfo({
queryParams: P_QUERY_PARAMS
});
}
if (O_RESULT_DATA.length <= 1) {
onUserBuPopup(O_RESULT_DATA[0]);
} else {
$NP.showUserBuPopup({
queryParams: P_QUERY_PARAMS,
queryData: O_RESULT_DATA
}, onUserBuPopup, onUserBuPopup);
}
return;
case "OWN_BRAND_CD":
var P_QUERY_PARAMS;
var O_RESULT_DATA = [ ];
if (!$NC.isNull(val)) {
var CUST_CD = $NC.G_USERINFO.CUST_CD;
var BU_CD = $NC.getValue("#edtQBu_Cd");
P_QUERY_PARAMS = {
P_CUST_CD: CUST_CD,
P_BU_CD: BU_CD,
P_OWN_BRAND_CD: val
};
O_RESULT_DATA = $NP.getOwnBrandInfo({
queryParams: P_QUERY_PARAMS,
queryData: O_RESULT_DATA
});
}
if (O_RESULT_DATA.length <= 1) {
onOwnBrandPopup(O_RESULT_DATA[0]);
} else {
$NP.showOwnBranPopup({
queryParams: P_QUERY_PARAMS,
queryData: O_RESULT_DATA
}, onOwnBrandPopup, onOwnBrandPopup);
}
return;
case "HASLOCATION_CD":
var P_QUERY_PARAMS;
var O_RESULT_DATA = [ ];
if (!$NC.isNull(val)) {
CENTER_CD = $NC.getValue("#cboQCenter_Cd");
P_QUERY_PARAMS = {
P_CENTER_CD: CENTER_CD,
P_ZONE_CD: "",
P_BANK_CD: "",
P_BAY_CD: "",
P_LEV_CD: "",
P_HASLOCATION_CD: val
};
O_RESULT_DATA = $NP.getLocation01Info({
queryParams: P_QUERY_PARAMS
});
}
if (O_RESULT_DATA.length <= 1) {
onLocationPopup(O_RESULT_DATA[0]);
} else {
$NP.showLocation01Popup({
queryParams: P_QUERY_PARAMS,
queryData: O_RESULT_DATA
}, onLocationPopup, onLocationPopup);
}
return;
}
onChangingCondition();
}
/**
* Inquiry Button Event - 메인 상단 조회 버튼 클릭시 호출 됨
*/
function _Inquiry() {
var CENTER_CD = $NC.getValue("#cboQCenter_Cd");
if ($NC.isNull(CENTER_CD)) {
alert("물류센터를 선택하십시오.");
$NC.setFocus("#cboQCenter_Cd");
return;
}
var BU_CD = $NC.getValue("#edtQBu_Cd");
if ($NC.isNull(BU_CD)) {
alert("사업부를 입력하십시오.");
$NC.setFocus("#edtQBu_Cd");
return;
}
var HAS_DATE = $NC.getValue("#dtpQHas_Date");
if ($NC.isNull(HAS_DATE)) {
alert("합포장일자를 입력하십시오.");
$NC.setFocus("#dtpQHas_Date");
return;
}
var LOC_DIV = $NC.getValue("#cboQLoc_Div");
if ($NC.isNull(LOC_DIV)) {
alert("합포장 로케이션 층구분을 선택하십시요.");
$NC.setFocus("#cboQLoc_Div");
return;
}
var END_YN_DIV = $NC.getValue("#cboQEnd_Yn");
var OUTBOUND_NO = $NC.getValue("#edtOutbound_No");
var BU_NO = $NC.getValue("#edtQHas_No");
var ORDERER_NM = $NC.getValue("#edtQOrderer_Nm");
var SHIPPER_NM = $NC.getValue("#edtShipper_Nm");
var HASLOCATION_CD = $NC.getValue("#edtQHaslocation_Cd");
// 상품별 출고내역 화면
if ($("#divMasterView").tabs("option", "active") === 0) {
var END_YN = $NC.getValue("#cboQEND_YN");
// 조회시 전역 변수 값 초기화
$NC.setInitGridVar(G_GRDT1MASTER);
// $NC.setInitGridVar(G_GRDT1DETAIL);
// $NC.setInitGridVar(RS_SUB);
$NC.setInitGridVar(G_GRDT1DETAIL);
$NC.setInitGridData(G_GRDT1DETAIL);
$NC.setGridDisplayRows("#grdT1Detail", 0, 0);
$NC.setInitGridVar(G_GRDSUB);
$NC.setInitGridData(G_GRDSUB);
$NC.setGridDisplayRows("#grdSub", 0, 0);
$NC.serviceCall("/LOM9110E/getDataSet.do", {
P_QUERY_ID: "LOM9110E.RS_SUB",
P_QUERY_PARAMS: $NC.getParams({
P_CENTER_CD: CENTER_CD,
P_LOC_DIV: LOC_DIV
})
}, onGetNonSendCnt);
G_GRDT1MASTER.queryParams = $NC.getParams({
P_CENTER_CD: CENTER_CD,
P_BU_CD: BU_CD,
P_HAS_DATE: HAS_DATE,
P_BU_NO: BU_NO,
P_ORDERER_NM: ORDERER_NM,
P_SHIPPER_NM: SHIPPER_NM,
P_LOCATION_CD: HASLOCATION_CD,
P_OUTBOUND_NO: OUTBOUND_NO,
P_LOC_DIV: LOC_DIV,
P_END_YN: END_YN
});
// 데이터 조회
$NC.serviceCall("/LOM9110E/getDataSet.do", $NC.getGridParams(G_GRDT1MASTER), onGetT1Master);
} else if ($("#divMasterView").tabs("option", "active") === 1) {
// 조회시 전역 변수 값 초기화
$NC.setInitGridVar(G_GRDT2MASTER);
G_GRDT2MASTER.queryParams = $NC.getParams({
P_CENTER_CD: CENTER_CD,
P_BU_CD: BU_CD,
P_HAS_DATE: HAS_DATE,
P_BU_NO: BU_NO,
P_ORDERER_NM: ORDERER_NM,
P_SHIPPER_NM: SHIPPER_NM,
P_END_YN: END_YN_DIV,
P_LOCATION_CD: HASLOCATION_CD,
P_LOC_DIV: LOC_DIV
});
// 데이터 조회
$NC.serviceCall("/LOM9110E/getDataSet.do", $NC.getGridParams(G_GRDT2MASTER), onGetT2Master);
} else {
// 조회시 전역 변수 값 초기화
$NC.setInitGridVar(G_GRDT3MASTER);
G_GRDT3MASTER.queryParams = $NC.getParams({
P_CENTER_CD: CENTER_CD,
P_BU_CD: BU_CD,
P_HAS_DATE: HAS_DATE,
P_BU_NO: BU_NO,
P_ORDERER_NM: ORDERER_NM,
P_SHIPPER_NM: SHIPPER_NM,
P_END_YN: END_YN_DIV,
P_LOCATION_CD: HASLOCATION_CD,
P_LOC_DIV: LOC_DIV
});
// 데이터 조회
$NC.serviceCall("/LOM9110E/getDataSet.do", $NC.getGridParams(G_GRDT3MASTER), onGetT3Master);
}
}
/**
* New Button Event - 메인 상단 신규 버튼 클릭시 호출 됨
*/
function _New() {
}
/**
* Save Button Event - 메인 상단 저장 버튼 클릭시 호출 됨
*/
function _Save() {
}
/**
* Delete Button Event - 메인 상단 삭제 버튼 클릭시 호출 됨
*/
function _Delete() {
}
/**
* Cancel Button Event - 메인 상단 취소 버튼 클릭시 호출 됨
*/
function _Cancel() {
}
/**
* Print Button Event - 메인 상단 출력 버튼 클릭시 호출 됨
*
* @param printIndex
* 선택한 출력물 Index
*/
function _Print(printIndex, printName) {
}
function tabOnActivate(event, ui) {
_OnResize($(window));
}
/**
* Tab Active Event
*
* @param event
* @param ui
* newTab: The tab that was just activated.<br>
* oldTab: The tab that was just deactivated.<br>
* newPanel: The panel that was just activated.<br>
* oldPanel: The panel that was just deactivated
*/
function tabOnActivate(event, ui) {
var id = ui.newTab.prop("id").substr(3).toUpperCase();
var container;
if (id === "TAB1") {
container = "#divT1DetailView";
} else {
container = "#divT2DetailView";
}
// 스플리터가 초기화가 되어 있으면 _OnResize 호출
if ($NC.isSplitter(container)) {
// 스필리터를 통한 _OnResize 호출
$(container).trigger("resize");
} else {
// 스플리터 초기화
$NC.setInitSplitter(container, "v", $NC.G_OFFSET.leftViewWidth);
}
}
function grdT1MasterOnGetColumns() {
var columns = [ ];
$NC.setGridColumn(columns, {
id: "CHECK_YN",
field: "CHECK_YN",
minWidth: 30,
width: 30,
sortable: false,
cssClass: "align-center",
formatter: Slick.Formatters.CheckBox,
editor: Slick.Editors.CheckBox,
editorOptions: {
valueChecked: "Y",
valueUnChecked: "N"
}
});
$NC.setGridColumn(columns, {
id: "HAS_DATE",
field: "HAS_DATE",
name: "합포장일자",
minWidth: 90,
cssClass: "align-center"
});
$NC.setGridColumn(columns, {
id: "LOC_DIV_F1",
field: "LOC_DIV_F",
name: "층 구분",
minWidth: 80
});
$NC.setGridColumn(columns, {
id: "LOCATION_CD",
field: "LOCATION_CD",
name: "로케이션코드",
minWidth: 80,
cssClass: "align-center"
});
$NC.setGridColumn(columns, {
id: "HAS_NO",
field: "HAS_NO",
name: "합포장번호",
minWidth: 70,
cssClass: "align-center"
});
$NC.setGridColumn(columns, {
id: "END_YN",
field: "END_YN",
name: "합포장구분",
minWidth: 80,
cssClass: "align-center"
});
$NC.setGridColumn(columns, {
id: "ORDERER_NM",
field: "ORDERER_NM",
name: "주문자명",
minWidth: 80
});
$NC.setGridColumn(columns, {
id: "SHIPPER_NM",
field: "SHIPPER_NM",
name: "수령자명",
minWidth: 80
});
$NC.setGridColumn(columns, {
id: "HAS_DATETIME",
field: "HAS_DATETIME",
name: "합포장분류시간",
minWidth: 160
});
return $NC.setGridColumnDefaultFormatter(columns);
}
function grdT1MasterInitialize() {
var options = {
frozenColumn: 3,
specialRow: {
compareKey: "END_YN1",
compareVal: "D",
compareOperator: "==",
cssClass: "specialrow3"
}
};
// Grid DataView 생성 및 초기화
// Grid Object, DataView 생성 및 초기화
$NC.setInitGridObject("#grdT1Master", {
columns: grdT1MasterOnGetColumns(),
queryId: "LOM9110E.RS_T1_MASTER",
sortCol: "HAS_DATE",
gridOptions: options
});
G_GRDT1MASTER.view.onClick.subscribe(grdMasterOnClick);
G_GRDT1MASTER.view.onSelectedRowsChanged.subscribe(grdMasterT1OnAfterScroll);
G_GRDT1MASTER.view.onHeaderClick.subscribe(grdMasterOnHeaderClick);
$NC.setGridColumnHeaderCheckBox(G_GRDT1MASTER, "CHECK_YN");
}
function grdMasterOnClick(e, args) {
G_GRDT1MASTER.view.getCanvasNode().focus();
if (args.cell === G_GRDT1MASTER.view.getColumnIndex("CHECK_YN")) {
if ($(e.target).is(":checkbox")) {
var checkVal = $(e.target).is(":checked") ? "Y" : "N";
var rowData = G_GRDT1MASTER.data.getItem(args.row);
if (rowData.CHECK_YN !== checkVal) {
rowData.CHECK_YN = checkVal;
G_GRDT1MASTER.data.updateItem(rowData.id, rowData);
}
}
}
}
function grdMasterT1OnAfterScroll(e, args) {
var row = args.rows[0];
var rowData = G_GRDT1MASTER.data.getItem(row);
if (G_GRDT1MASTER.lastRow != null) {
if (row == G_GRDT1MASTER.lastRow) {
e.stopImmediatePropagation();
return;
}
}
$NC.setInitGridVar(G_GRDT1DETAIL);
$NC.setInitGridVar(G_GRDSUB);
var CENTER_CD = $NC.getValue("#cboQCenter_Cd");
G_GRDT1DETAIL.queryParams = $NC.getParams({
P_CENTER_CD: CENTER_CD,
P_BU_CD: rowData.BU_CD,
P_HAS_DATE: rowData.HAS_DATE,
P_HAS_NO: rowData.HAS_NO
});
// 데이터 조회
$NC.serviceCall("/LOM9110E/getDataSet.do", $NC.getGridParams(G_GRDT1DETAIL), onGetT1Detail);
// 상단 현재로우/총건수 업데이트
$NC.setGridDisplayRows("#grdT1Master", row + 1);
}
function grdMasterOnHeaderClick(e, args) {
G_GRDT1MASTER.view.getCanvasNode().focus();
if (args.column.id == "CHECK_YN") {
if ($(e.target).is(":checkbox")) {
if (G_GRDT1MASTER.data.getLength() == 0) {
e.preventDefault();
e.stopImmediatePropagation();
return;
}
var checkVal = $(e.target).is(":checked") ? "Y" : "N";
var rowCount = G_GRDT1MASTER.data.getLength();
var rowData;
G_GRDT1MASTER.data.beginUpdate();
for ( var row = 0; row < rowCount; row++) {
rowData = G_GRDT1MASTER.data.getItem(row);
if (rowData.CHECK_YN !== checkVal) {
rowData.CHECK_YN = checkVal;
G_GRDT1MASTER.data.updateItem(rowData.id, rowData);
}
}
G_GRDT1MASTER.data.endUpdate();
e.stopPropagation();
e.stopImmediatePropagation();
}
}
}
function grdT1DetailOnGetColumns() {
var columns = [ ];
$NC.setGridColumn(columns, {
id: "CHECK_YN",
field: "CHECK_YN",
minWidth: 30,
width: 30,
sortable: false,
cssClass: "align-center",
formatter: Slick.Formatters.CheckBox,
editor: Slick.Editors.CheckBox,
editorOptions: {
valueChecked: "Y",
valueUnChecked: "N"
}
});
$NC.setGridColumn(columns, {
id: "LINE_NO",
field: "LINE_NO",
name: "합포장순번",
minWidth: 60,
cssClass: "align-center"
});
$NC.setGridColumn(columns, {
id: "END_YN",
field: "END_YN",
name: "합포장구분",
minWidth: 100,
cssClass: "align-center"
});
$NC.setGridColumn(columns, {
id: "BU_NO",
field: "BU_NO",
name: "주문번호",
cssClass: "align-center",
minWidth: 100
});
$NC.setGridColumn(columns, {
id: "OUTBOUND_DATE",
field: "OUTBOUND_DATE",
name: "출고일자",
minWidth: 80,
cssClass: "align-center"
});
$NC.setGridColumn(columns, {
id: "OUTBOUND_NO",
field: "OUTBOUND_NO",
name: "출고번호",
minWidth: 60,
cssClass: "align-center"
});
$NC.setGridColumn(columns, {
id: "PICK_BOX_NO",
field: "PICK_BOX_NO",
name: "용기번호",
minWidth: 70,
cssClass: "align-center"
});
$NC.setGridColumn(columns, {
id: "PICK_SEQ",
field: "PICK_SEQ",
name: "피킹라벨",
minWidth: 70,
cssClass: "align-center"
});
$NC.setGridColumn(columns, {
id: "ZONE_CD",
field: "ZONE_CD",
name: "존코드",
minWidth: 40,
cssClass: "align-center"
});
$NC.setGridColumn(columns, {
id: "HAS_DATETIME",
field: "HAS_DATETIME",
name: "합포장분류시간",
minWidth: 140
});
return $NC.setGridColumnDefaultFormatter(columns);
}
function grdT1DetailInitialize() {
var options = {
frozenColumn: 3,
specialRow: {
compareKey: "END_YN",
compareVal: "주문취소",
compareOperator: "==",
cssClass: "specialrow3"
}
};
// Grid Object, DataView 생성 및 초기화
$NC.setInitGridObject("#grdT1Detail", {
columns: grdT1DetailOnGetColumns(),
queryId: "LOM9110E.RS_DETAIL1",
sortCol: "LINE_NO",
gridOptions: options
});
G_GRDT1DETAIL.view.onClick.subscribe(grdT1DetailOnClick);
G_GRDT1DETAIL.view.onSelectedRowsChanged.subscribe(grdT1DetailOnAfterScroll);
G_GRDT1DETAIL.view.onHeaderClick.subscribe(grdT1DetailOnHeaderClick);
$NC.setGridColumnHeaderCheckBox(G_GRDT1DETAIL, "CHECK_YN");
}
function grdT1DetailOnClick(e, args) {
G_GRDT1DETAIL.focused = true;
}
/**
* 입고중량등록탭 하단그리드 행 클릭시 하단그리드 값 취득해서 표시 처리
*
* @param e
* @param args
*/
function grdT1DetailOnAfterScroll(e, args) {
var row = args.rows[0];
var rowData = G_GRDT1DETAIL.data.getItem(row);
if (G_GRDT1DETAIL.lastRow != null) {
if (row == G_GRDT1DETAIL.lastRow) {
e.stopImmediatePropagation();
return;
}
}
$NC.setInitGridVar(G_GRDSUB);
$NC.setInitGridData(G_GRDSUB);
$NC.setGridDisplayRows("#grdSub", 0, 0);
var CENTER_CD = $NC.getValue("#cboQCenter_Cd");
var BU_CD = $NC.getValue("#edtQBu_Cd");
G_GRDSUB.queryParams = $NC.getParams({
P_CENTER_CD: CENTER_CD,
P_BU_CD: BU_CD,
P_OUTBOUND_DATE: rowData.OUTBOUND_DATE,
P_OUTBOUND_NO: rowData.OUTBOUND_NO,
P_ZONE_CD: rowData.ZONE_CD,
P_PICK_SEQ: rowData.PICK_SEQ,
P_ITEM_CD: rowData.ITEM_CD
});
// 데이터 조회
$NC.serviceCall("/LOM9110E/getDataSet.do", $NC.getGridParams(G_GRDSUB), onGetSub);
// 상단 현재로우/총건수 업데이트
$NC.setGridDisplayRows("#grdT1Detail", row + 1);
}
function grdT1DetailOnHeaderClick(e, args) {
G_GRDT1DETAIL.view.getCanvasNode().focus();
if (args.column.id == "CHECK_YN") {
if ($(e.target).is(":checkbox")) {
if (G_GRDT1DETAIL.data.getLength() == 0) {
e.preventDefault();
e.stopImmediatePropagation();
return;
}
var checkVal = $(e.target).is(":checked") ? "Y" : "N";
var rowCount = G_GRDT1DETAIL.data.getLength();
var rowData;
G_GRDT1DETAIL.data.beginUpdate();
for ( var row = 0; row < rowCount; row++) {
rowData = G_GRDT1DETAIL.data.getItem(row);
if (rowData.CHECK_YN !== checkVal) {
if (rowData.LINE_NO !== '000000') {
rowData.CHECK_YN = checkVal;
G_GRDT1DETAIL.data.updateItem(rowData.id, rowData);
} else if (rowData.LINE_NO == '000000') {
// alert("합포장대상은 선택 할 수없습니다.");
// return;
}
}
}
G_GRDT1DETAIL.data.endUpdate();
e.stopPropagation();
e.stopImmediatePropagation();
}
}
}
function grdT2MasterOnGetColumns() {
var columns = [ ];
$NC.setGridColumn(columns, {
id: "HAS_DATE",
field: "HAS_DATE",
name: "합포장일자",
minWidth: 90,
cssClass: "align-center"
});
$NC.setGridColumn(columns, {
id: "LOC_DIV_F1",
field: "LOC_DIV_F",
name: "층 구분",
minWidth: 80
});
$NC.setGridColumn(columns, {
id: "LOCATION_CD",
field: "LOCATION_CD",
name: "로케이션코드",
minWidth: 80,
cssClass: "align-center"
});
$NC.setGridColumn(columns, {
id: "HAS_NO",
field: "HAS_NO",
name: "합포장번호",
minWidth: 70,
cssClass: "align-center"
});
$NC.setGridColumn(columns, {
id: "OUTBOUND_DATE",
field: "OUTBOUND_DATE",
name: "출고일자",
minWidth: 90,
cssClass: "align-center"
});
$NC.setGridColumn(columns, {
id: "OUTBOUND_NO",
field: "OUTBOUND_NO",
name: "출고번호",
minWidth: 70,
cssClass: "align-center"
});
$NC.setGridColumn(columns, {
id: "BU_NO",
field: "BU_NO",
name: "전표번호",
minWidth: 90
});
$NC.setGridColumn(columns, {
id: "END_YN",
field: "END_YN",
name: "합포장구분",
minWidth: 80,
cssClass: "align-center"
});
$NC.setGridColumn(columns, {
id: "ORDERER_NM",
field: "ORDERER_NM",
name: "주문자명",
minWidth: 80
});
$NC.setGridColumn(columns, {
id: "SHIPPER_NM",
field: "SHIPPER_NM",
name: "수령자명",
minWidth: 80
});
return $NC.setGridColumnDefaultFormatter(columns);
}
/**
* 배송처별 입고내역탭의 그리드 초기값 설정
*/
function grdT2MasterInitialize() {
var options = {
frozenColumn: 0
};
// Grid Object, DataView 생성 및 초기화
$NC.setInitGridObject("#grdT2Master", {
columns: grdT2MasterOnGetColumns(),
queryId: "LOM9110E.RS_T2_MASTER",
sortCol: "HAS_DATE",
gridOptions: options
});
G_GRDT2MASTER.view.onSelectedRowsChanged.subscribe(grdMasterT2OnAfterScroll);
}
function grdMasterT2OnAfterScroll(e, args) {
var row = args.rows[0];
var rowData = G_GRDT2MASTER.data.getItem(row);
if (G_GRDT2MASTER.lastRow != null) {
if (row == G_GRDT2MASTER.lastRow) {
e.stopImmediatePropagation();
return;
}
}
$NC.setInitGridVar(G_GRDT2DETAIL);
var CENTER_CD = $NC.getValue("#cboQCenter_Cd");
var BU_CD = $NC.getValue("#edtQBu_Cd");
G_GRDT2DETAIL.queryParams = $NC.getParams({
P_CENTER_CD: CENTER_CD,
P_BU_CD: BU_CD,
P_OUTBOUND_DATE: rowData.OUTBOUND_DATE,
P_OUTBOUND_NO: rowData.OUTBOUND_NO,
P_ZONE_CD: rowData.ZONE_CD,
});
// 데이터 조회
$NC.serviceCall("/LOM9110E/getDataSet.do", $NC.getGridParams(G_GRDT2DETAIL), onGetT2Detail);
// 상단 현재로우/총건수 업데이트
$NC.setGridDisplayRows("#grdT2Master", row + 1);
}
function grdT2DetailOnGetColumns() {
var columns = [ ];
$NC.setGridColumn(columns, {
id: "ITEM_CD",
field: "ITEM_CD",
name: "상품코드",
minWidth: 70
});
$NC.setGridColumn(columns, {
id: "ITEM_NM",
field: "ITEM_NM",
name: "상품명",
minWidth: 160
});
$NC.setGridColumn(columns, {
id: "ITEM_SPEC",
field: "ITEM_SPEC",
name: "규격",
minWidth: 70
});
$NC.setGridColumn(columns, {
id: "HAS_TYPE_F",
field: "HAS_TYPE_F",
name: "상품물성",
minWidth: 90
});
$NC.setGridColumn(columns, {
id: "ENTRY_QTY",
field: "ENTRY_QTY",
name: "구성수량",
minWidth: 70,
cssClass: "align-right"
});
return $NC.setGridColumnDefaultFormatter(columns);
}
/**
* 배송처별 입고내역탭의 그리드 초기값 설정
*/
function grdT2DetailInitialize() {
var options = {
frozenColumn: 3
};
// Grid Object, DataView 생성 및 초기화
$NC.setInitGridObject("#grdT2Detail", {
columns: grdT2DetailOnGetColumns(),
queryId: "LOM9110E.RS_DETAIL2",
sortCol: "ITEM_CD",
gridOptions: options
});
G_GRDT2DETAIL.view.onSelectedRowsChanged.subscribe(grdT2DetailOnAfterScroll);
}
function grdT2DetailOnAfterScroll(e, args) {
var row = args.rows[0];
if (G_GRDT2DETAIL.lastRow != null) {
if (row == G_GRDT2DETAIL.lastRow) {
e.stopImmediatePropagation();
return;
}
}
// 상단 현재로우/총건수 업데이트
$NC.setGridDisplayRows("#grdT2Detail", row + 1);
}
/**
* 검색조건 값 변경 되었을 경우의 처리
*/
function onChangingCondition() {
// 초기화
$NC.clearGridData(G_GRDT1DETAIL);
$NC.clearGridData(G_GRDT1MASTER);
$NC.clearGridData(G_GRDSUB);
$NC.clearGridData(G_GRDT2DETAIL);
$NC.clearGridData(G_GRDT2MASTER);
$NC.clearGridData(G_GRDT3DETAIL);
$NC.clearGridData(G_GRDT3MASTER);
// 버튼 활성화 처리
$NC.G_VAR.buttons._inquiry = "1";
$NC.G_VAR.buttons._new = "0";
$NC.G_VAR.buttons._save = "0";
$NC.G_VAR.buttons._cancel = "0";
$NC.G_VAR.buttons._delete = "0";
$NC.G_VAR.buttons._print = "0";
$NC.setInitTopButtons($NC.G_VAR.buttons);
}
/*------------------------------------------------------*/
function grdT3MasterOnGetColumns() {
var columns = [ ];
$NC.setGridColumn(columns, {
id: "CHECK_YN",
field: "CHECK_YN",
minWidth: 30,
width: 30,
sortable: false,
cssClass: "align-center",
formatter: Slick.Formatters.CheckBox,
editor: Slick.Editors.CheckBox,
editorOptions: {
valueChecked: "Y",
valueUnChecked: "N"
}
});
$NC.setGridColumn(columns, {
id: "HAS_DATE",
field: "HAS_DATE",
name: "합포장일자",
minWidth: 90,
cssClass: "align-center"
});
$NC.setGridColumn(columns, {
id: "LOC_DIV_F1",
field: "LOC_DIV_F",
name: "층 구분",
minWidth: 80
});
$NC.setGridColumn(columns, {
id: "LOCATION_CD",
field: "LOCATION_CD",
name: "로케이션코드",
minWidth: 80,
cssClass: "align-center"
});
$NC.setGridColumn(columns, {
id: "HAS_NO",
field: "HAS_NO",
name: "합포장번호",
minWidth: 70,
cssClass: "align-center"
});
$NC.setGridColumn(columns, {
id: "OUTBOUND_DATE",
field: "OUTBOUND_DATE",
name: "출고일자",
minWidth: 90
});
$NC.setGridColumn(columns, {
id: "OUTBOUND_NO",
field: "OUTBOUND_NO",
name: "출고번호",
minWidth: 100,
cssClass: "align-center"
});
$NC.setGridColumn(columns, {
id: "END_YN",
field: "END_YN",
name: "합포장구분",
minWidth: 80,
cssClass: "align-center"
});
$NC.setGridColumn(columns, {
id: "ORDERER_NM",
field: "ORDERER_NM",
name: "주문자명",
minWidth: 80
});
$NC.setGridColumn(columns, {
id: "SHIPPER_NM",
field: "SHIPPER_NM",
name: "수령자명",
minWidth: 80
});
return $NC.setGridColumnDefaultFormatter(columns);
}
/**
* 배송처별 입고내역탭의 그리드 초기값 설정
*/
function grdT3MasterInitialize() {
var options = {
frozenColumn: 1
};
// Grid Object, DataView 생성 및 초기화
$NC.setInitGridObject("#grdT3Master", {
columns: grdT3MasterOnGetColumns(),
queryId: "LOM9110E.RS_T3_MASTER",
sortCol: "HAS_DATE",
gridOptions: options
});
G_GRDT3MASTER.view.onSelectedRowsChanged.subscribe(grdMasterT3OnAfterScroll);
G_GRDT3MASTER.view.onHeaderClick.subscribe(grdMasterT3OnHeaderClick);
$NC.setGridColumnHeaderCheckBox(G_GRDT3MASTER, "CHECK_YN");
}
function grdMasterT3OnHeaderClick(e, args) {
G_GRDT3MASTER.view.getCanvasNode().focus();
if (args.column.id == "CHECK_YN") {
if ($(e.target).is(":checkbox")) {
if (G_GRDT3MASTER.data.getLength() == 0) {
e.preventDefault();
e.stopImmediatePropagation();
return;
}
var checkVal = $(e.target).is(":checked") ? "Y" : "N";
var rowCount = G_GRDT3MASTER.data.getLength();
var rowData;
G_GRDT3MASTER.data.beginUpdate();
for ( var row = 0; row < rowCount; row++) {
rowData = G_GRDT3MASTER.data.getItem(row);
if (rowData.CHECK_YN !== checkVal) {
rowData.CHECK_YN = checkVal;
G_GRDT3MASTER.data.updateItem(rowData.id, rowData);
}
}
G_GRDT3MASTER.data.endUpdate();
e.stopPropagation();
e.stopImmediatePropagation();
}
}
}
/**
* 온라인몰 출고내역 탭의 그리드 행 클릭시 처리
*
* @param e
* @param args
*/
function grdMasterT3OnAfterScroll(e, args) {
var row = args.rows[0];
var rowData = G_GRDT3MASTER.data.getItem(row);
if (G_GRDT3MASTER.lastRow != null) {
if (row == G_GRDT3MASTER.lastRow) {
e.stopImmediatePropagation();
return;
}
}
$NC.setInitGridVar(G_GRDT3DETAIL);
var CENTER_CD = $NC.getValue("#cboQCenter_Cd");
var BU_CD = $NC.getValue("#edtQBu_Cd");
G_GRDT3DETAIL.queryParams = $NC.getParams({
P_CENTER_CD: CENTER_CD,
P_BU_CD: BU_CD,
P_OUTBOUND_DATE: rowData.OUTBOUND_DATE,
P_OUTBOUND_NO: rowData.OUTBOUND_NO,
P_HAS_NO: rowData.HAS_NO,
P_HAS_DATE: rowData.HAS_DATE
});
// 데이터 조회
$NC.serviceCall("/LOM9110E/getDataSet.do", $NC.getGridParams(G_GRDT3DETAIL), onGetT3Detail);
// 상단 현재로우/총건수 업데이트
$NC.setGridDisplayRows("#grdT3Master", row + 1);
}
/**
* 온라인 출고내역 탭 조회 버튼 클릭후 처리
*
* @param ajaxData
*/
function onGetMasterT3(ajaxData) {
$NC.setInitGridData(G_GRDT3MASTER, ajaxData);
if (G_GRDT3MASTER.data.getLength() > 0) {
$NC.setGridSelectRow(G_GRDT3MASTER, 0);
} else {
$NC.setGridDisplayRows("#grdT3Master", 0, 0);
}
// 버튼 활성화 처리
$NC.G_VAR.buttons._inquiry = "1";
$NC.G_VAR.buttons._new = "0";
$NC.G_VAR.buttons._save = "0";
$NC.G_VAR.buttons._cancel = "0";
$NC.G_VAR.buttons._delete = "0";
$NC.G_VAR.buttons._excel = "1";
$NC.G_VAR.buttons._print = "0";
$NC.setInitTopButtons($NC.G_VAR.buttons);
}
function grdT3DetailOnGetColumns() {
var columns = [ ];
$NC.setGridColumn(columns, {
id: "OUTBOUND_NO",
field: "OUTBOUND_NO",
name: "출고번호",
minWidth: 100,
cssClass: "align-center"
});
$NC.setGridColumn(columns, {
id: "ITEM_CD",
field: "ITEM_CD",
name: "상품코드",
minWidth: 70
});
$NC.setGridColumn(columns, {
id: "ITEM_NM",
field: "ITEM_NM",
name: "상품명",
minWidth: 160
});
$NC.setGridColumn(columns, {
id: "ITEM_SPEC",
field: "ITEM_SPEC",
name: "규격",
minWidth: 70
});
$NC.setGridColumn(columns, {
id: "HAS_TYPE_F",
field: "HAS_TYPE_F",
name: "상품물성",
minWidth: 90
});
$NC.setGridColumn(columns, {
id: "ENTRY_QTY",
field: "ENTRY_QTY",
name: "구성수량",
minWidth: 70,
cssClass: "align-right"
});
return $NC.setGridColumnDefaultFormatter(columns);
}
/**
* 배송처별 입고내역탭의 그리드 초기값 설정
*/
function grdT3DetailInitialize() {
var options = {
frozenColumn: 3
};
// Grid Object, DataView 생성 및 초기화
$NC.setInitGridObject("#grdT3Detail", {
columns: grdT3DetailOnGetColumns(),
queryId: "LOM9110E.RS_DETAIL3",
sortCol: "ITEM_CD",
gridOptions: options
});
G_GRDT3DETAIL.view.onSelectedRowsChanged.subscribe(grdT3DetailOnAfterScroll);
}
function grdT3DetailOnAfterScroll(e, args) {
var row = args.rows[0];
if (G_GRDT3DETAIL.lastRow != null) {
if (row == G_GRDT3DETAIL.lastRow) {
e.stopImmediatePropagation();
return;
}
}
// 상단 현재로우/총건수 업데이트
$NC.setGridDisplayRows("#grdT3Detail", row + 1);
}
/*----------------------------------------------------------*/
function grdSubOnGetColumns() {
var columns = [ ];
$NC.setGridColumn(columns, {
id: "ITEM_CD",
field: "ITEM_CD",
name: "상품코드",
minWidth: 70
});
$NC.setGridColumn(columns, {
id: "ITEM_NM",
field: "ITEM_NM",
name: "상품명",
minWidth: 160
});
$NC.setGridColumn(columns, {
id: "ITEM_SPEC",
field: "ITEM_SPEC",
name: "규격",
minWidth: 70
});
$NC.setGridColumn(columns, {
id: "HAS_TYPE_F",
field: "HAS_TYPE_F",
name: "상품물성",
minWidth: 90
});
$NC.setGridColumn(columns, {
id: "CONFIRM_QTY",
field: "CONFIRM_QTY",
name: "구성수량",
minWidth: 70,
cssClass: "align-right"
});
return $NC.setGridColumnDefaultFormatter(columns);
}
function grdSubInitialize() {
var options = {
editable: true,
autoEdit: true,
frozenColumn: 0
};
// Grid Object, DataView 생성 및 초기화
$NC.setInitGridObject("#grdSub", {
columns: grdSubOnGetColumns(),
queryId: "LOM9110E.RS_SUB1",
sortCol: "ITEM_CD",
gridOptions: options
});
G_GRDSUB.view.onSelectedRowsChanged.subscribe(grdSubOnAfterScroll);
}
function grdSubOnAfterScroll(e, args) {
var row = args.rows[0];
if (G_GRDSUB.lastRow != null) {
if (row == G_GRDSUB.lastRow) {
e.stopImmediatePropagation();
return;
}
}
// 상단 현재로우/총건수 업데이트
$NC.setGridDisplayRows("#grdSub", row + 1);
}
/*----------------------------------------------------*/
/**
* 상품별 재고현황 탭 조회 버튼 클릭후 처리
*
* @param ajaxData
*/
function onGetT1Master(ajaxData) {
$NC.setInitGridData(G_GRDT1MASTER, ajaxData);
if (G_GRDT1MASTER.data.getLength() > 0) {
$NC.setGridSelectRow(G_GRDT1MASTER, 0);
} else {
$NC.setGridDisplayRows("#grdT1Master", 0, 0);
}
// 버튼 활성화 처리
$NC.G_VAR.buttons._inquiry = "1";
$NC.G_VAR.buttons._new = "0";
$NC.G_VAR.buttons._save = "0";
$NC.G_VAR.buttons._cancel = "0";
$NC.G_VAR.buttons._delete = "0";
$NC.G_VAR.buttons._excel = "1";
$NC.G_VAR.buttons._print = "0";
$NC.setInitTopButtons($NC.G_VAR.buttons);
}
/**
* 로케이션별 재고현황 탭 조회 버튼 클릭후 처리
*
* @param ajaxData
*/
function onGetT2Master(ajaxData) {
$NC.setInitGridData(G_GRDT2MASTER, ajaxData);
if (G_GRDT2MASTER.data.getLength() > 0) {
$NC.setGridSelectRow(G_GRDT2MASTER, 0);
} else {
$NC.setGridDisplayRows("#grdT2Master", 0, 0);
// 디테일 초기화
$NC.setInitGridVar(G_GRDT2DETAIL);
onGetT2Detail({
data: null
});
}
}
/**
* 로케이션별 재고현황 탭 조회 버튼 클릭후 처리
*
* @param ajaxData
*/
function onGetT3Master(ajaxData) {
$NC.setInitGridData(G_GRDT3MASTER, ajaxData);
if (G_GRDT3MASTER.data.getLength() > 0) {
$NC.setGridSelectRow(G_GRDT3MASTER, 0);
} else {
$NC.setGridDisplayRows("#grdT3Master", 0, 0);
// 디테일 초기화
$NC.setInitGridVar(G_GRDT3DETAIL);
onGetT3Detail({
data: null
});
}
}
/**
* 상품별 재고현황 탭 조회 버튼 클릭후 처리
*
* @param ajaxData
*/
function onGetT1Detail(ajaxData) {
$NC.setInitGridData(G_GRDT1DETAIL, ajaxData);
if (G_GRDT1DETAIL.data.getLength() > 0) {
if ($NC.isNull(G_GRDT1DETAIL.lastKeyVal)) {
$NC.setGridSelectRow(G_GRDT1DETAIL, 0);
} else {
$NC.setGridSelectRow(G_GRDT1DETAIL, {
selectKey: "ITEM_CD",
selectVal: G_GRDT1DETAIL.lastKeyVal
});
}
} else {
$NC.setGridDisplayRows("#grdT1Detail", 0, 0);
}
G_GRDT1DETAIL.view.getCanvasNode().focus();
}
/**
* 로케이션별 재고현황 탭 조회 버튼 클릭후 처리
*
* @param ajaxData
*/
function onGetT2Detail(ajaxData) {
$NC.setInitGridData(G_GRDT2DETAIL, ajaxData);
if (G_GRDT2DETAIL.data.getLength() > 0) {
$NC.setGridSelectRow(G_GRDT2DETAIL, 0);
} else {
$NC.setGridDisplayRows("#grdT2Detail", 0, 0);
}
}
/**
* 로케이션별 재고현황 탭 조회 버튼 클릭후 처리
*
* @param ajaxData
*/
function onGetT3Detail(ajaxData) {
$NC.setInitGridData(G_GRDT3DETAIL, ajaxData);
if (G_GRDT3DETAIL.data.getLength() > 0) {
$NC.setGridSelectRow(G_GRDT3DETAIL, 0);
} else {
$NC.setGridDisplayRows("#grdT3Detail", 0, 0);
}
}
function onGetSub(ajaxData) {
$NC.setInitGridData(G_GRDSUB, ajaxData);
if (G_GRDSUB.data.getLength() > 0) {
if ($NC.isNull(G_GRDSUB.lastKeyVal)) {
$NC.setGridSelectRow(G_GRDSUB, 0);
} else {
$NC.setGridSelectRow(G_GRDSUB, {
selectKey: "ITEM_CD",
selectVal: G_GRDSUB.lastKeyVal
});
}
} else {
$NC.setGridDisplayRows("#grdSub", 0, 0);
}
}
/**
* 검색조건의 로케이션 검색 이미지 클릭
*/
function showLocationPopup() {
CENTER_CD = $NC.getValue("#cboQCenter_Cd");
$NP.showLocation01Popup({
P_CENTER_CD: CENTER_CD,
P_ZONE_CD: "",
P_BANK_CD: "",
P_BAY_CD: "",
P_LEV_CD: "",
P_LOCATION_CD: "%"
}, onLocationPopup, function() {
$NC.setFocus("#edtQHaslocation_Cd", true);
});
}
/**
* 사업부 검색 결과
*
* @param seletedRowData
*/
function onLocationPopup(resultInfo) {
if (!$NC.isNull(resultInfo)) {
$NC.setValue("#edtQHaslocation_Cd", resultInfo.LOCATION_CD);
} else {
$NC.setValue("#edtQHaslocation_Cd");
$NC.setFocus("#edtQHaslocation_Cd", true);
}
onChangingCondition();
}
/**
* 검색조건의 사업부 검색 이미지 클릭
*/
function showUserBuPopup() {
$NP.showUserBuPopup({
P_USER_ID: $NC.G_USERINFO.USER_ID,
P_BU_CD: "%"
}, onUserBuPopup, function() {
$NC.setFocus("#edtQBu_Cd", true);
});
}
/**
* 사업부 검색 결과
*
* @param seletedRowData
*/
function onUserBuPopup(resultInfo) {
if (!$NC.isNull(resultInfo)) {
$NC.setValue("#edtQBu_Cd", resultInfo.BU_CD);
$NC.setValue("#edtQBu_Nm", resultInfo.BU_NM);
$NC.setValue("#edtQCust_Cd", resultInfo.CUST_CD);
$NC.setFocus("#dtpQInvest_Date1", true);
} else {
$NC.setValue("#edtQBu_Cd");
$NC.setValue("#edtQBu_Nm");
$NC.setValue("#edtQCust_Cd");
$NC.setFocus("#edtQBu_Cd", true);
}
onChangingCondition();
}
/**
* 검색조건의 브랜드 검색 팝업 클릭
*/
function showOwnBranPopup() {
var BU_CD = $NC.getValue("#edtQBu_Cd");
var CUST_CD = $NC.getValue("#edtQCust_Cd");
$NP.showOwnBranPopup({
P_CUST_CD: CUST_CD,
P_BU_CD: BU_CD,
P_OWN_BRAND_CD: '%'
}, onOwnBrandPopup, function() {
$NC.setFocus("#edtQOwn_Brand_Cd", true);
});
}
/**
* 브랜드 검색 결과
*
* @param seletedRowData
*/
function onOwnBrandPopup(resultInfo) {
if (!$NC.isNull(resultInfo)) {
$NC.setValue("#edtQOwn_Brand_Cd", resultInfo.OWN_BRAND_CD);
$NC.setValue("#edtQOwn_Brand_Nm", resultInfo.OWN_BRAND_NM);
} else {
$NC.setValue("#edtQOwn_Brand_Cd");
$NC.setValue("#edtQOwn_Brand_Nm");
$NC.setFocus("#edtQOwn_Brand_Cd", true);
}
onChangingCondition();
}
function TS4() {
var rowData = G_GRDT1DETAIL.data.getItems();
var rowCount = G_GRDT1DETAIL.data.getLength();
if (rowData.length === 0) {
alert("조회 후 처리하십시오.");
return;
}
var result = confirm("분류취소 처리 하시겠습니까?");
if (!result) {
return;
}
var CENTER_CD = $NC.getValue("#cboQCenter_Cd");
var BU_CD = $NC.getValue("#edtQBu_Cd");
var HAS_DATE = $NC.getValue("#dtpQHas_Date");
closingDS = [ ];
var chkCnt = 0;
for ( var row = 0; row < rowCount; row++) {
var rowData = G_GRDT1DETAIL.data.getItem(row);
var lastRowData = G_GRDT1MASTER.data.getItem(G_GRDT1MASTER.lastRow);
if (rowData.CHECK_YN == "Y") {
if (rowData.LINE_NO !== "0") {
chkCnt++;
var Ms = {
P_CENTER_CD: CENTER_CD,
P_BU_CD: BU_CD,
P_HAS_DATE: HAS_DATE,
P_HAS_NO: lastRowData.HAS_NO,
P_LINE_NO: rowData.LINE_NO
};
closingDS.push(Ms);
}
}
}
if (chkCnt == 0) {
alert("처리대상이 없습니다. 선택하십시오.");
return;
}
$NC.serviceCall("/LOM9110E/callProc_Bw.do", {
P_DS_MASTER: $NC.getParams(closingDS),
P_USER_ID: $NC.G_USERINFO.USER_ID
}, Ts1, onSaveError);
}
function Ts1(ajaxData) {
var resultData = $NC.toArray(ajaxData);
if (!$NC.isNull(resultData)) {
if (resultData.RESULT_DATA === "OK") {
alert("삭제처리되었습니다.");
doPrint3();
} else {
alert(resultData.RESULT_DATA);
return;
}
}
}
function Hassend() {
var rowCount = G_GRDT1MASTER.data.getLength();
if (rowCount === 0) {
alert("조회 후 처리하십시오.");
return;
}
closingDS = [ ];
closingDS1 = [ ];
var chkCnt = 0;
var chkCnt1 = 0;
var End_Yn_D = '';
var End_Yn_N = '';
for ( var row = 0; row < rowCount; row++) {
var rowData = G_GRDT1MASTER.data.getItem(row);
if (rowData.CHECK_YN == "Y") {
if (rowData.END_YN1 == "D") {
chkCnt++;
var Ms = {
P_CENTER_CD: $NC.getValue("#cboQCenter_Cd"),
P_BU_CD: $NC.getValue("#edtQBu_Cd"),
P_HAS_DATE: rowData.HAS_DATE,
P_HAS_NO: rowData.HAS_NO,
P_PROC_GUBN: "1"
};
closingDS.push(Ms);
End_Yn_D = 'D';
} else {
chkCnt1++;
var Ms = {
P_CENTER_CD: $NC.getValue("#cboQCenter_Cd"),
P_BU_CD: $NC.getValue("#edtQBu_Cd"),
P_HAS_DATE: rowData.HAS_DATE,
P_HAS_NO: rowData.HAS_NO,
};
closingDS1.push(Ms);
End_Yn_N = 'N';
}
}
}
if (chkCnt == 0 && chkCnt1 == 0) {
alert("처리대상이 없습니다. 선택하십시오.");
return;
}
if (End_Yn_D == "D") {
$NC.serviceCall("/LOM9110E/callPorpertiesUpdate.do", {
P_DS_MASTER: $NC.getParams(closingDS),
P_USER_ID: $NC.G_USERINFO.USER_ID
}, onExecSP, onSaveError);
} else if (End_Yn_N == "N") {
var result = confirm("합포장분할 처리시 재합포장 처리할수 없습니다. 그래도 하시겠습니까?");
if (!result) {
return;
}
$NC.serviceCall("/LOM9110E/callLineproc.do", {
P_DS_MASTER: $NC.getParams(closingDS1),
P_USER_ID: $NC.G_USERINFO.USER_ID
}, OnSaveHas, onSaveError);
}
/*
*/
}
function OnSaveHas(ajaxData) {
var resultData = $NC.toArray(ajaxData);
var resultData1 = resultData.RESULT_DATA;
var resultData2 = resultData1.substring(1);
var resultData3 = resultData1.substring(1, 4);
var TEST = "-";
// var RESULT_DATA1 = resultData1.split(TEST);
var O_HAS_NO = resultData2;
// var O_HAS_NO = RESULT_DATA1[1];
if (O_HAS_NO !== "") {
if (resultData3 == 'HAS') {
alert(O_HAS_NO);
return;
} else {
doPrint2(O_HAS_NO);
}
} else {
return;
}
}
function onExecSP(ajaxData) {
var resultData = $NC.toArray(ajaxData);
// if (!$NC.isNull(resultData)) {
// if (resultData === "OK") {
// }else{
// alert(resultData);
// }
//
// }
doPrint1();
}
function doPrint1() {
if (G_GRDT1MASTER.view.getEditorLock().isActive()) {
G_GRDT1MASTER.view.getEditorLock().commitCurrentEdit();
}
var center_Cd = $NC.getValue("#cboQCenter_Cd");
if ($NC.isNull(center_Cd)) {
alert("물류센터를 선택하십시오.");
$NC.setFocus("#cboQCenter_Cd");
return;
}
var checkedValueDS = [ ];
var rowCount = G_GRDT1MASTER.data.getLength();
for ( var row = 0; row < rowCount; row++) {
var rowData = G_GRDT1MASTER.data.getItem(row);
if (rowData.CHECK_YN === "Y") {
checkedValueDS.push(rowData.HAS_NO);
}
}
if (checkedValueDS.length == 0) {
alert("출력할 데이터를 선택하십시오.");
return;
}
var CENTER_CD = $NC.getValue("#cboQCenter_Cd");
var BU_CD = $NC.getValue("#edtQBu_Cd");
var HAS_DATE = $NC.getValue("#dtpQHas_Date");
$NC.G_MAIN.silentPrint({
printParams: [{
//reportDoc: "lo/LABEL_LOM12",
//queryId: "WR.RS_LABEL_LOM13",
reportDoc: "lo/LABEL_LOM12",
queryId: "WR.RS_LABEL_LOM13_NEW",
queryParams: {
P_CENTER_CD: CENTER_CD,
P_BU_CD: BU_CD,
P_HAS_DATE: HAS_DATE,
P_HAS_NO : "",
P_LINE_NO: "",
P_PICK_SEQ: "",
P_PICK_BOX_NO: "",
P_INQUERY_DIV: "6"
},
checkedValue: checkedValueDS.toString(),
iFrameNo: 1,
silentPrinterName: $NC.G_USERINFO.PRINT_CARD
}],
onAfterPrint: function() {
_Inquiry();
}
});
// $NC.G_MAIN.silentPrint(printOptions);
}
function doPrint2(resultData) {
var center_Cd = $NC.getValue("#cboQCenter_Cd");
if ($NC.isNull(center_Cd)) {
alert("물류센터를 선택하십시오.");
$NC.setFocus("#cboQCenter_Cd");
return;
}
var CENTER_CD = $NC.getValue("#cboQCenter_Cd");
var BU_CD = $NC.getValue("#edtQBu_Cd");
var HAS_DATE = $NC.getValue("#dtpQHas_Date");
$NC.G_MAIN.silentPrint({
printParams: [{
//reportDoc: "lo/LABEL_LOM14",
//queryId: "WR.RS_LABEL_LOM13",
reportDoc: "lo/LABEL_LOM12",
queryId: "WR.RS_LABEL_LOM13_NEW",
queryParams: {
P_CENTER_CD: CENTER_CD,
P_BU_CD: BU_CD,
P_HAS_DATE: HAS_DATE,
P_HAS_NO : "",
P_LINE_NO: "",
P_PICK_SEQ: "",
P_PICK_BOX_NO: "",
P_INQUERY_DIV: "6"
},
checkedValue: resultData,
iFrameNo: 1,
silentPrinterName: $NC.G_USERINFO.PRINT_CARD
}],
onAfterPrint: function() {
_Inquiry();
}
});
}
function doPrint3() {
if (G_GRDT1DETAIL.view.getEditorLock().isActive()) {
G_GRDT1DETAIL.view.getEditorLock().commitCurrentEdit();
}
var center_Cd = $NC.getValue("#cboQCenter_Cd");
if ($NC.isNull(center_Cd)) {
alert("물류센터를 선택하십시오.");
$NC.setFocus("#cboQCenter_Cd");
return;
}
var checkedValueDS = [ ];
var rowCount = G_GRDT1DETAIL.data.getLength();
for ( var row = 0; row < rowCount; row++) {
var rowData = G_GRDT1DETAIL.data.getItem(row);
var lastRowData = G_GRDT1MASTER.data.getItem(G_GRDT1MASTER.lastRow);
if (rowData.CHECK_YN === "Y") {
checkedValueDS.push(lastRowData.HAS_NO + "" + String(rowData.OUTBOUND_NO));
}
}
if (checkedValueDS.length == 0) {
alert("출력할 데이터를 선택하십시오.");
return;
}
var CENTER_CD = $NC.getValue("#cboQCenter_Cd");
var BU_CD = $NC.getValue("#edtQBu_Cd");
var HAS_DATE = $NC.getValue("#dtpQHas_Date");
$NC.G_MAIN.silentPrint({
printParams: [{
//reportDoc: "lo/LABEL_LOM15",
//queryId: "WR.RS_LABEL_LOM16",
reportDoc: "lo/LABEL_LOM12",
queryId: "WR.RS_LABEL_LOM13_NEW",
queryParams: {
P_CENTER_CD: CENTER_CD,
P_BU_CD: BU_CD,
P_HAS_DATE: HAS_DATE,
P_HAS_NO : "",
P_LINE_NO: "",
P_PICK_SEQ: "",
P_PICK_BOX_NO: "",
P_INQUERY_DIV: "4"
},
checkedValue: checkedValueDS.toString(),
iFrameNo: 1,
silentPrinterName: $NC.G_USERINFO.PRINT_CARD
}],
onAfterPrint: function() {
_Inquiry();
}
});
}
function doPrint4() {
if (G_GRDT3MASTER.view.getEditorLock().isActive()) {
G_GRDT3MASTER.view.getEditorLock().commitCurrentEdit();
}
var center_Cd = $NC.getValue("#cboQCenter_Cd");
if ($NC.isNull(center_Cd)) {
alert("물류센터를 선택하십시오.");
$NC.setFocus("#cboQCenter_Cd");
return;
}
var checkedValueDS = [ ];
var rowCount = G_GRDT3MASTER.data.getLength();
for ( var row = 0; row < rowCount; row++) {
var rowData = G_GRDT3MASTER.data.getItem(row);
if (rowData.CHECK_YN === "Y") {
checkedValueDS.push(rowData.HAS_NO + "" + rowData.END_YN1);
}
}
if (checkedValueDS.length == 0) {
alert("출력할 데이터를 선택하십시오.");
return;
}
var CENTER_CD = $NC.getValue("#cboQCenter_Cd");
var BU_CD = $NC.getValue("#edtQBu_Cd");
var HAS_DATE = $NC.getValue("#dtpQHas_Date");
$NC.G_MAIN.silentPrint({
printParams: [{
//reportDoc: "lo/LABEL_LOM12",
//queryId: "WR.RS_LABEL_LOM17",
reportDoc: "lo/LABEL_LOM12",
queryId: "WR.RS_LABEL_LOM13_NEW",
queryParams: {
P_CENTER_CD: CENTER_CD,
P_BU_CD: BU_CD,
P_HAS_DATE: HAS_DATE,
P_HAS_NO : "",
P_LINE_NO: "",
P_PICK_SEQ: "",
P_PICK_BOX_NO: "",
P_INQUERY_DIV: "5"
},
checkedValue: checkedValueDS.toString(),
iFrameNo: 1,
silentPrinterName: $NC.G_USERINFO.PRINT_CARD
}],
onAfterPrint: function() {
_Inquiry();
}
});
}
function _OnGridCheckBoxFormatterClick(e, view, args) {
if (args.grid == "grdT1Master") {
if (G_GRDT1MASTER.view.getEditorLock().isActive()) {
G_GRDT1MASTER.view.getEditorLock().commitCurrentEdit();
}
$NC.setGridSelectRow(G_GRDT1MASTER, args.row);
var rowData = G_GRDT1MASTER.data.getItem(args.row);
if (args.cell == G_GRDT1MASTER.view.getColumnIndex("CHECK_YN")) {
rowData.CHECK_YN = args.val === "Y" ? "N" : "Y";
}
G_GRDT1MASTER.data.updateItem(rowData.id, rowData);
}
if (args.grid == "grdT3Master") {
if (G_GRDT3MASTER.view.getEditorLock().isActive()) {
G_GRDT3MASTER.view.getEditorLock().commitCurrentEdit();
}
$NC.setGridSelectRow(G_GRDT3MASTER, args.row);
var rowData = G_GRDT3MASTER.data.getItem(args.row);
if (args.cell == G_GRDT3MASTER.view.getColumnIndex("CHECK_YN")) {
rowData.CHECK_YN = args.val === "Y" ? "N" : "Y";
}
G_GRDT3MASTER.data.updateItem(rowData.id, rowData);
}
if (args.grid == "grdT1Detail") {
if (G_GRDT1DETAIL.view.getEditorLock().isActive()) {
G_GRDT1DETAIL.view.getEditorLock().commitCurrentEdit();
}
$NC.setGridSelectRow(G_GRDT1DETAIL, args.row);
var rowData = G_GRDT1DETAIL.data.getItem(args.row);
if (args.cell == G_GRDT1DETAIL.view.getColumnIndex("CHECK_YN")) {
rowData.CHECK_YN = args.val === "Y" ? "N" : "Y";
if (rowData.LINE_NO !== "000000") {
G_GRDT1DETAIL.data.updateItem(rowData.id, rowData);
} else if (rowData.LINE_NO == "000000") {
rowData.CHECK_YN = "N";
G_GRDT1DETAIL.data.updateItem(rowData.id, rowData);
}
}
}
}
function onGetNonSendCnt(ajaxData) {
var resultRows = $NC.toArray(ajaxData);
if (resultRows.length > 0) {
$NC.setValue("#lblLo_Cnt_A", "총 셀수 : " + resultRows[0].TOTAL_LOC_CNT);
$NC.setValue("#lblLo_Cnt_B", "사용중 셀수 : " + resultRows[0].HAS_CNT);
$NC.setValue("#lblLo_Cnt_C", "빈 셀수 : " + resultRows[0].REMAIN_CNT);
} else {
$NC.setValue("#lblLo_Cnt_A", "총 셀수 : ");
$NC.setValue("#lblLo_Cnt_B", "사용중 셀수 : ");
$NC.setValue("#lblLo_Cnt_C", "빈 셀수 : ");
}
}
function onSaveError(ajaxData) {
$NC.onError(ajaxData);
}
function TS1() {
var rowData = G_GRDT1DETAIL.data.getItems();
var rowCount = G_GRDT1DETAIL.data.getLength();
if (rowData.length === 0) {
alert("조회 후 처리하십시오.");
return;
}
var result = confirm("취소 처리시 재합포장 처리할수 없습니다. 그래도 하시겠습니까?");
if (!result) {
return;
}
var spCallDs1 = [ ];
var chkCnt1 = 0;
var rowData = G_GRDT1DETAIL.data.getItems();
// for ( var row = 0; row < chkCnt1; row++) {
for ( var i = 0; i < rowCount; i++) {
// CHECK_YN === 'Y' 이면 checkSameDate() 함수에서 spCallDs1 배열에 같은 값이 있는지 체크한다.
if (rowData[i].CHECK_YN === 'Y' && checkSameDate(rowData[i], i)) {
chkCnt1++;
// 중복값이 없으면 spCallDs1에 push한다.
spCallDs1.push(rowData[i]);
}
}
;
// private 지역함수를 만든다.
function checkSameDate(row, i) {
for (i in spCallDs1) {
// BU_CD, BU_NO가 같으면 false를 반환한다.
if (row.CENTER_CD == spCallDs1[i].CENTER_CD && row.BU_NO == spCallDs1[i].BU_NO
&& row.OUTBOUND_DATE == spCallDs1[i].OUTBOUND_DATE && row.OUTBOUND_NO == spCallDs1[i].OUTBOUND_NO) {
return false;
}
}
return true;
}
console.log(spCallDs1);
spCallDS = [ ];
var chkCnt = 0;
var lastRowData = G_GRDT1MASTER.data.getItem(G_GRDT1MASTER.lastRow);
for ( var row = 0; row < chkCnt1; row++) {
chkCnt++;
var rowData1 = spCallDs1;
var Ms = {
P_CENTER_CD: rowData1[row].CENTER_CD,
P_BU_CD: rowData1[row].BU_CD,
P_HAS_DATE: lastRowData.HAS_DATE,
P_HAS_NO: lastRowData.HAS_NO,
P_LINE_NO: rowData1[row].LINE_NO
};
spCallDS.push(Ms);
}
if (chkCnt == 0) {
alert("처리대상이 없습니다. 선택하십시오.");
return;
}
$NC.serviceCall("/LOM9110E/callProc_Bw.do", {
P_DS_MASTER: $NC.getParams(spCallDS),
P_USER_ID: $NC.G_USERINFO.USER_ID
}, Ts1, onSaveError);
}
|
import React, { useState, useEffect, useContext } from 'react';
import { useHistory } from 'react-router-dom';
import { useMutation } from '@apollo/client';
import { TextField, Button, Typography } from '@material-ui/core';
import { NotificationContext } from '../context';
import { LOGIN } from '../queries';
const Login = ({ setToken }) => {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [login, result] = useMutation(LOGIN, {
onError: (error) => {
addMessage(error.graphQLErrors[0].message, 'error');
},
onCompleted: (data) => {
addMessage('Successfully logged in', 'success');
},
});
const history = useHistory();
const { addMessage } = useContext(NotificationContext);
useEffect(() => {
if (result.data) {
const token = result.data.login.value;
setToken(token);
localStorage.setItem('library-user-token', token);
history.push('/');
}
}, [result.data]); // eslint-disable-line
const handleLogin = (event) => {
event.preventDefault();
login({ variables: { username, password } });
};
return (
<div>
<Typography variant="h2">Login</Typography>
<form onSubmit={handleLogin}>
<div>
<TextField
value={username}
variant="outlined"
label="username"
onChange={({ target }) => setUsername(target.value)}
/>
</div>
<div>
<TextField
value={password}
variant="outlined"
type="password"
label="password"
onChange={({ target }) => setPassword(target.value)}
/>
</div>
<Button color="primary" variant="contained" type="submit">
Login
</Button>
</form>
</div>
);
};
export default Login;
|
class Repository {
constructor(modelInstance) {
this.modelInstance = modelInstance;
}
findRecord(where = {}, attributes, include, options = {}) {
let params = { where };
if (attributes) {
params.attributes = attributes;
}
if (include) {
params.include = include;
}
if (options) {
params = {
...params,
...options,
};
}
return this.modelInstance.findOne(params);
}
findAllRecords(where = {}, attributes, include, options = {}, plain = false) {
let params = { where };
if (attributes) {
params.attributes = attributes;
}
if (include) {
params.include = include;
}
if (options) {
params = {
...params,
...options,
};
}
const instance = this.modelInstance.findAll(params);
return plain ? instance.map(el => el.get({ plain: true })) : instance;
}
updateRecord(where = {}, values, options = {}) {
return new Promise((resolve, reject) => {
const params = {
where,
returning: true,
...options,
};
this.modelInstance
.update(values, params)
.then(updatedValues => {
let returnValues = null;
if (updatedValues[0]) {
returnValues = updatedValues[1][0];
}
resolve(returnValues);
})
.catch(err => {
reject(err);
});
});
}
updateRecords(where = {}, values, options = {}) {
return new Promise((resolve, reject) => {
const params = {
where,
returning: true,
...options,
};
this.modelInstance
.update(values, params)
.then(updatedValues => {
const rowsUpdated = updatedValues[0];
const rowsValues = updatedValues[1];
resolve({ rowsUpdated, rowsValues });
})
.catch(err => {
reject(err);
});
});
}
createRecord(values, options = {}) {
return this.modelInstance.create(values, options);
}
createOrUpdate(values, options = {}) {
return this.modelInstance.upsert(values, options);
}
createBulkRecords(data, options = {}) {
return this.modelInstance.bulkCreate(data, options);
}
deleteRecord(whereObject, options) {
const params = {
where: whereObject,
...options,
};
return this.modelInstance.destroy(params);
}
/**
* updateBulkRecords
* This function is used for bulk update of records and follows
* table map updation strategy by creating temporary table and mapping it to update all records.
* @param {*} dbInstance (sequelize db instance)
* @param {*} referenceKey (usually the primary key id used for joining data from temporary table)
* @param {*} [columnsToUpdate=[]] (columns that needs to update in a record)
* @param {*} updatedRows (all the updated records)
* (these records should contain the refrence key and all columns mentioned in columnsToUpdate)
* @returns Transaction Promise
* @memberof Repository
*/
async updateBulkRecords(dbInstance, referenceKey, columnsToUpdate = [], updatedRows) {
if (updatedRows && updatedRows.length) {
const tableToUpdate = this.modelInstance.tableName;
const tempKey = `compare_key_${referenceKey}`;
const tempTable = `new_ref_${tableToUpdate}`;
const columnsUpdateString = columnsToUpdate.map(column => `${column} = sncopy.${column}`);
// await dbInstance.sequelize.query(removeTable);
const updateQuery = `UPDATE ${tableToUpdate} SET ${columnsUpdateString.join(
',',
)} FROM ${tempTable} AS sncopy WHERE ${referenceKey} = sncopy.${tempKey};`;
const insertRecords = updatedRows.map(row => {
const newRecord = { ...row, [tempKey]: row[referenceKey] };
delete newRecord[`${referenceKey}`];
return newRecord;
});
const columns = Object.keys(insertRecords[0]);
const newTableColumns = columns
.map(
col => `${col} ${typeof insertRecords[0][col] === 'number' ? 'int4' : 'varchar (100)'}`,
)
.join(',');
const createTable = `CREATE TEMPORARY TABLE ${tempTable} (${newTableColumns}) ON COMMIT DROP;`;
const entriesToInsert = [];
for (let i = 0; i < insertRecords.length; i += 1) {
const record = insertRecords[i];
const values = Object.values(record);
entriesToInsert.push(`(${values.join(',')})`);
}
const bulkInsertQuery = `INSERT INTO ${tempTable} (${columns.join(
',',
)}) VALUES ${entriesToInsert.join(',')};`;
return dbInstance.sequelize.transaction(async t1 => {
await dbInstance.sequelize.query(createTable, { transaction: t1 });
await dbInstance.sequelize.query(bulkInsertQuery, { transaction: t1 });
await dbInstance.sequelize.query(updateQuery, { transaction: t1 });
});
} else {
throw new Error('records to update not found');
}
}
}
module.exports = Repository;
|
import request from '@/utils/request'
const chart = {
// 获取sysIframeGet
sysIframeGet(data) {
return request({ url: '/sysIframeGet', method: 'post', data })
},
// 获取getShouLiJieCun
getShouLiJieCun(data) {
return request({ url: '/chart/getShouLiJieCun3', method: 'post', data })
},
// 获取受理未归档案件列表
getShouliWeiBanjie(data) {
return request({ url: '/chart/getShouliWeiBanjie3', method: 'post', data })
},
// 获取办结未归档案件列表
getBanJieWeiGuiDang(data) {
return request({ url: '/chart/getBanJieWeiGuiDang3', method: 'post', data })
},
}
export default chart
|
import Ember from 'ember';
const { Component, computed } = Ember;
export default Component.extend({
valueChosen: computed('property', function() {
return this.get('property') !== undefined;
}),
valid: computed('valueChosen', 'property', function() {
return this.get('valueChosen') && (this.get('property') !== '');
})
});
|
import React, { Component } from "react";
import PropTypes from "prop-types";
import ModelRating from "./presenter";
import { WEBSITE_PATH } from "../../config/constants"
class Container extends Component {
static propTypes = {
pathname: PropTypes.string.isRequired,
model_filter: PropTypes.shape({
gender: PropTypes.array,
age_range: PropTypes.array,
job: PropTypes.array,
entertainment: PropTypes.array,
style: PropTypes.array,
career: PropTypes.array,
}),
modelFilterList: PropTypes.string,
FetchRatingModel: PropTypes.func.isRequired,
SaveRatingModelExpansion: PropTypes.func.isRequired,
rating_model_expansion_list: PropTypes.array,
}
static contextTypes = {
t: PropTypes.func.isRequired
};
componentDidMount() {
if (this.props.rating_model_expansion_list === null
|| this.props.rating_model_expansion_list === undefined
|| this.props.rating_model_expansion_list === []
|| this.props.rating_model_expansion_list.length === 0) {
this.props.FetchRatingModel("all", this.props.model_filter, true, this.FetchRatingModelCallback.bind(this))
}
}
componentWillReceiveProps(nextPros) {
if (nextPros.pathname === WEBSITE_PATH.MODEL_NEW
&& this.props.pathname !== nextPros.pathname
&& this.props.rating_model_expansion_list.length === 0) {
this.props.FetchRatingModel("all", this.props.model_filter, true, this.FetchRatingModelCallback.bind(this))
}
}
render() {
return (
<ModelRating
model_list={this.props.rating_model_expansion_list}
/>
)
}
FetchRatingModelCallback = (result, json) => {
if (result === true) {
this.props.SaveRatingModelExpansion(json.result)
}
}
}
export default Container;
|
import React from 'react'
import { Link, BrowserRouter as Router } from 'react-router-dom'
import BranchTile from '../../src/components/BranchTile'
describe('BranchTile', () => {
let wrapper
let branch = {
id: 1,
name: 'test branch',
repository_id: 1,
user_id: 1,
branch_goal: 'branch goal',
branch_method: 'branch method',
branch_resources: 'branch resources',
created_at: '2017-08-13T17:28:06.852Z',
updated_at: '2017-08-13T17:29:06.852Z'
}
beforeEach(() => {
wrapper = mount(
<Router>
<BranchTile
branchObject={branch}
/>
</Router>
)
})
it('should render a branch tile div', () => {
expect(wrapper.find('#branch-tile'))
expect(wrapper.find('#branch-tile').node.innerHTML.includes('<h3', '<a', '<span'))
});
it('should render the branch name as a link within an h3', () => {
expect(wrapper.find('#branch-tile').node.children[0].children[0].href.includes('/branch/1'))
expect(wrapper.find('#branch-tile').node.children[0].children[0].innerHTML.includes('test branch'))
});
})
|
import axios from '../../axios'
/*
* 保险模块
*/
// 请求保险报价
export const saveMemberQueryInsurance = data => {
return axios({
url: '/insurance/saveMemberQueryInsurance',
method: 'post',
data
})
}
// 所有保险公司
export const getCompanys = () => {
return axios({
url: '/insurance/getCompanys',
method: 'get'
})
}
// 根据保险公司id获取方案
export const findCategoryByCompanyId = companyId => {
return axios({
url: '/insurance/findCategoryByCompanyId',
method: 'get',
params: { companyId }
})
}
|
//Company Name
let company = "GOOG";
let i = 0;
let totalLength;
let dateText;
//Intialize let
let initialPriceListLow, initialPriceListHigh, initialDate;
let priceListLow, priceListHigh;
let date;
let maxValue;
let minValue;
let valueMain;
let timeValue;
let initialColor =[130, 200, 200];
let finalColor = [200, 30, 50];
let colorStep = [0,0,0];
let dollarStep = 0;
let xAxisStep = 0;
let categoryAdjuster = 0;
let axisAdjuster = 0;
function preload(){
table = loadTable(`GOOG.csv`, "header");
}
function setup(){
//Getting csv file name: QCOM.csv for example
smooth(2);
//Data Retriving
initialPriceListLow = table.getColumn("Low");
initialPriceListHigh = table.getColumn("High");
initialDate = table.getColumn("Date");
totalLength = initialPriceListLow.length;
priceListLow = new Array(totalLength);
priceListHigh = new Array(totalLength);
date = new Array(totalLength);
for(let i=0; i<totalLength; i++){
priceListLow[i] = parseFloat(initialPriceListLow[totalLength -1 - i].substring(1));
priceListHigh[i] = parseFloat(initialPriceListHigh[totalLength- 1 - i].substring(1));
date[i] = initialDate[totalLength-1-i];
}
//MaxValue of All Time
maxValue = ceil(reverse(sort(priceListHigh))[0]);
minValue = floor(sort(priceListHigh)[0]);
//SBUX: $50(minValue)-$1(categoryAdjuster) is default
//categoryAdjuster = (minValue + maxValue) * 0.003;
categoryAdjuster = (minValue) * 0.02;
// categoryAdjuster = (maxValue) * 0.004;
//Array Creation to Store Values
let valueMainArrayLength = ceil(maxValue*1.1/categoryAdjuster);
valueMain = new Array(valueMainArrayLength);
timeValue = new Array(totalLength);
for(let i=0; i<totalLength; i++){
let low = floor(min(priceListLow[i], priceListHigh[i])/categoryAdjuster);
let high = ceil(max(priceListLow[i], priceListHigh[i])/categoryAdjuster);
let diff = abs(priceListHigh[i] - priceListLow[i])/categoryAdjuster;
for(let j=low; j<high; j++){
let min_diff = min(min(max(priceListLow[i], priceListHigh[i])/categoryAdjuster - j, 1), j - min(priceListLow[i], priceListHigh[i])/categoryAdjuster + 1);
let diff_result = diff>1 ? min_diff/diff: 1;
console.log(diff_result);
if(!timeValue[i]){
timeValue[i] = []
}
if(!valueMain[j]){
valueMain[j] = []
}
let currentjLength = valueMain[j].length;
for(let k=0; k<currentjLength; k++){
timeValue[i].push(new Coordinate(j, valueMain[j].length));
}
valueMain[j].push(diff_result);
}
}
createCanvas(1250,800);
smooth();
frameRate(30);
pixelDensity(10);
background(40);
//Color Setup
for(let color_i = 0; color_i<3; color_i ++){
colorStep[color_i] = (finalColor[color_i] - initialColor[color_i])/totalLength;
}
//Size Setup
dollarStep = categoryAdjuster * 0.2/minValue ;
xAxisStep = dollarStep * width;
console.log(valueMain);
}
//Define Coordinate Class to store the (j,k) coordinate value per time
class Coordinate{
constructor(j,k){
this.j = j;
this.k = k;
}
}
//Draw Function
function draw(){
i ++;
if(i<totalLength){
// noStroke();
// fill(40);
// rect(width-200, 0, width,200);
// fill(255);
// text(date[i], width-120, 40);
// let priceText = let.format("$%d", let(priceListHigh[i]+priceListLow[i])/2);
// text(priceText, width-120, 90);
noStroke();
if (timeValue[i] != null){
let currentArrayLength = timeValue[i].length;
for(let t=0; t<currentArrayLength; t++){
//Retrive value of j, k coordinate
let jVal = timeValue[i][t].j;
let kVal = timeValue[i][t].k;
fill(color(initialColor[0] + colorStep[0]*i,initialColor[1] + colorStep[1]*i,initialColor[2] + colorStep[2]*i));
circle(jVal*xAxisStep, height-kVal*5, float(5*Math.pow(valueMain[jVal][kVal],1/1.4)));
}
}
}
}
|
import React from "react";
import { useSelector } from "react-redux";
import { setLang } from "../../../dispatches/setLang";
const langs = [
{
key:"en",
name:"English",
flag:"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHcAAAA+CAMAAAAmsHQcAAAAqFBMVEX///+/CzAAJ2jowcO7ABe+ACy8ABv//v6/DjPmur69ACnDLkK+AC3EOEvLWWPbmZ3y3d79+Pm9ACK/HDG5AAEAI2bAwc4AAFwAIGUAGmMABF0AHWQADV8AFWGqEj3X2eCyuMiepLktPnQ6SXtGUYCRmLHm6O0gNnCorsESLmx+haLHy9cAAFRzepry8/aIkKuvT2RTXodkbZG9hZKpADWnACnNvMbGpa8yIHPVAAADtUlEQVRYhe2Z627kNgyFFW2T2bbpvbSujm35JtmTuDPttu//ZiWlSbABFlgMwMBAm/NHOXFgjiV+JD0REqVlkX61fNE+3HxkkcB7+Uege0K9WJltylY9Wwdk/eIp7v0Nhyiu2Z6aASSE9TA6KR3aHm2PtkY7Hlayw3rYDGtcmKdV0YPFadDZVmRtO+GnQfvUklXVU0D713csuqW4IfUSNOje94AKrkcD0Gu0Gvr6YgHjwh8/8ojOF2NJ14WEt00y4mmijS7bfgSyJppEfyVtI5h0ydVFNPQ4YRJ0imYUzUxnPIlHPPK6E02i5GKOa0APVbTSSN+2A6A9tdGjVW0VwEh9brsaLXNctUgnvQO/YWiPNmWrirVbrcE7bTfFG9dsB0pkCI3oHO3xYcocoUWODO5x5qgRo5Hmz594lDlqKvuKo7Zw1BSOilXtNBNHv/KI9nnWM50yBB8AEoSaQAV5Wem32RpaGesGhZRqTEQM1J0icFRU2c6jJWsx6WjljovVUEyhgDOWQ812eBILcRQzVqRPv/Mox8VqlDnShSMsT6cKOdJ4qOsM7sIRNQv/9888Khwlk6zWfjsiOMkuc7ZqRKvScatd8uAUXmXmSEynzzkSn3PknjmaiCPOuBhwLRw1FB5t9cyRzlcv/YgKKWu9mj3Sg+mc1Aw6wazoZ5DJzpTTQSVsEPgJFNLmm194dMlnmeKQG1CItMjUJmoEaehyP0jtXPoCPPzGo2eOlgLO1/qRfLi959BNjovtfYidxV31MQ7YaPUpdh6oXrQBZy99jkh1DsxZN/wy6+Q1OGxArn6x1J4cYrXR58FKtlHyPfDNOWZ56UejprmucEQ2z3Uv/QhPQDPOOQTOa44QHHjNEbwJR3WSyA8ChMPFrEPGScPskaN0sQ5pm9nnK5wW2xMlcBha2lTZr0O250gW+mqY32C+ws7wmEnBESCDg1it2U7irHMlXQtGrHFzA+oQHI3ttxs02TFb30XkCNx5HGtckeR/PvAox91Ckth0UqelQU7HHq1JsljdYa3KV+mRP33DorvMUQEH93gse1xG6QtHW7HYnhbm96OwtvSq57v1ROD0a5uxateh2GjzXLeyzlfeqvrovbVWmaNWuLhjjYu19dGQ1RfryXq2fa6uE1NafeDC4l1f0WEfie/3kbhhmVuun3M+stSB6+vG/e0euhc/7KO9cXrXG+vbfSTueBrq1f13r7qxV9y7fbRbXr3rvy2m9/er3/dveb6wuPr7jf9bveL5N+PV+he6q/OiIzqTHQAAAABJRU5ErkJggg=="
},
{
key:"ar",
name:"عربي",
flag:"https://upload.wikimedia.org/wikipedia/commons/thumb/c/ce/Flag_of_Tunisia.svg/225px-Flag_of_Tunisia.svg.png"
},
{
key:"fr",
name:"Français",
flag:"https://upload.wikimedia.org/wikipedia/commons/thumb/3/3a/Flag_of_France_%281794%E2%80%931815%2C_1830%E2%80%931958%29.svg/320px-Flag_of_France_%281794%E2%80%931815%2C_1830%E2%80%931958%29.svg.png"
}
]
function DropDown({
show,
setshow,
}) {
const selected = useSelector(state=>state.language)
return (
<div
className="absolute w-40 flex flex-col bg-white"
style={{
top:"100%",
maxHeight: show ? 130 : 0,
overflow:"hidden",
transition:".3s ease all",
zIndex: 500
}}
>
{
langs.map((a,i)=>
<div
key={i}
className={`w-full flex flex-row py-2 px-3${selected.current === a.key ? " bg-blue-800 text-white":""}`}
onClick={()=>{
setLang({value:a.key, prevValue: selected.current})
setshow(false)
}}
>
<div
style={{
backgroundImage:"url("+a.flag+")",
backgroundSize:"contain",
backgroundRepeat:"no-repeat",
backgroundPosition:"center",
width: 20,
height: 20,
marginRight: 5
}}
/>
<div
style={{
color: selected === a.key ? "white":undefined
}}
>{a.name}</div>
</div>
)
}
</div>
);
}
export default DropDown;
|
linearSearch = (arr, value) => {
for (let i in arr) {
if (arr[i] === value) return i;
}
return -1;
};
console.log(linearSearch([1, 2, 3, 4, 5, 6, 7, 8], 3));
//Big O of Linear Search is O(n) as n(Items in array) grows so does the time it takes to perform the function
|
import { Component } from '@angular/core';
var FlightHistoryComponent = (function () {
function FlightHistoryComponent() {
}
return FlightHistoryComponent;
}());
export { FlightHistoryComponent };
FlightHistoryComponent.decorators = [
{ type: Component, args: [{
template: "\n<div class=\"list-group\">\n <a href=\"#\" class=\"list-group-item disabled\">\n History\n </a>\n <a class=\"list-group-item\">Graz - Hamburg</a>\n <a class=\"list-group-item\">Graz - Frankfurt</a>\n <a class=\"list-group-item\">Hamburg - Graz</a>\n <a class=\"list-group-item\">Frankfurt - Graz</a>\n</div>\n "
},] },
];
/** @nocollapse */
FlightHistoryComponent.ctorParameters = function () { return []; };
|
import React from 'react'
import { Card } from '../../Card/Card'
import { KillerDetails } from './KillerDetails'
import { getEpisodeBySeasonAndEpisode } from '../../../services/seasons/seasonServices'
import { Title } from '../../Titles/Title/Title'
import { ThemeContext } from '../../../contexts/theme-context'
export const CardKiller = (props) => {
const { killer, deaths, theme } = props
return (
<>
{killer && (
<>
<Title theme={theme} title={`${killer.name}`}></Title>
<Title
theme={theme}
title={`Number of Murders: ${killer.deathCount}`}
size="small"
isList={true}
></Title>
{deaths &&
deaths.map((death, index) => {
getEpisodeBySeasonAndEpisode(
death.season,
death.episode
)
return (
<Card
key={index}
name={`${death.death}`}
isList={true}
>
<KillerDetails {...props} death={death} />
</Card>
)
})}
</>
)}
</>
)
}
export const KillerPresenter = (props) => {
const { dark, theme } = React.useContext(ThemeContext)
return <CardKiller {...props} theme={theme} dark={dark} />
}
|
import React, { useState, useEffect } from 'react'
import { Link, withRouter } from 'react-router-dom'
import { Button, Card, Input, Form, Icon, message } from 'antd'
import './style.css'
import { authServices } from '../../services/'
const Login = (props) => {
const [ loading, setLoading ] = useState(false)
const { getFieldDecorator } = props.form
const handleSubmit = (e) => {
e.preventDefault()
props.form.validateFields(async (err, values) => {
if (!err) {
setLoading(true)
try {
const response = await authServices.login(values)
if (response.status) {
setLoading(false)
LoginSuccess(response.user)
}
} catch (error) {
setLoading(false)
message.error('Credenciales Inválidas.')
}
}
})
}
const LoginSuccess = (user) => {
localStorage.setItem('user', JSON.stringify(user))
setTimeout(() => {
props.history.push('home')
}, 2000)
}
return (
<div className="container">
<Card className="card-login" title="Iniciar Sesión">
<Form onSubmit={handleSubmit}>
<Form.Item>
{getFieldDecorator('identity', {
rules: [ { required: true, message: '¡Por favor introduce tu email!' } ]
})(
<Input
prefix={<Icon type="mail" style={{ color: 'rgba(0,0,0,.25)' }} />}
placeholder="Email"
/>
)}
</Form.Item>
<Form.Item>
{getFieldDecorator('password', {
rules: [ { required: true, message: '¡Por favor introduce tu password!' } ]
})(
<Input
prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />}
type="password"
placeholder="Contraseña"
/>
)}
</Form.Item>
<Form.Item>
<Button type="primary" loading={loading} htmlType="submit" block>
Inicia Sesión
</Button>
<div style={{ textAlign: 'center', marginTop: '5px' }}>
¿No tienes cuenta?
<Link to="/register" style={{ marginLeft: '5px', color: '#000' }}>
<strong>Registrate aquí</strong>
</Link>
</div>
</Form.Item>
</Form>
</Card>
</div>
)
}
const WrappedLoginForm = Form.create({ name: 'login_form' })(Login)
export default withRouter(WrappedLoginForm)
|
import WeatherByHour from "./weatherbyhour";
function WeatherDataPerDay({
weatherPerDay,
setClassVar,
setHourbyWeather,
classVar,
}) {
return (
<div className="weather-temperature">
{weatherPerDay.map((weather) => {
const classActive = classVar === weather.dt_txt ? "is-active" : "";
return (
<WeatherByHour
weather={weather}
key={weather.dt_txt}
setClassVar={setClassVar}
classActive={classActive}
setHourbyWeather={setHourbyWeather}
/>
);
})}
</div>
);
}
export default WeatherDataPerDay;
|
function register(env) {
env.addGlobal("blog_post_archive_url", handler);
}
function handler(selected_blog, year, month, day) {
return `http://blog.hubspot.com/marketing/archive/${year}/${ month }/${ day }`;
}
export {
handler,
register as default
};
|
/**
* @file This module contains all the unit tests of the application. Unit tests are
* implemented with the NodeUnit unit test library.
*/
var nodeUnit = require('nodeunit');
/**
* Test the home page with a unit test. TODO: Currently this is only provided
* for demonstration purposes.
*
* @param {object} test - Test object passed by nodeunit test library.
*/
exports.testHome = function (test) {
test.expect(1);
test.ok(true, 'This test always passes');
test.done();
};
|
import { createContext,useState } from "react";
const WeatherContext=createContext();
export const LocationProvider=(props)=>{
const [location,setLocation]=useState("Istanbul");
const values={
location:location,
setLocation:setLocation
}
return <WeatherContext.Provider value={values}>{props.children}</WeatherContext.Provider>
}
export default WeatherContext;
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Button from '@material-ui/core/Button';
import TextField from '@material-ui/core/TextField';
import Card from '@material-ui/core/Card';
import CardHeader from '@material-ui/core/CardHeader';
import CardContent from '@material-ui/core/CardContent';
import { Row, Col } from '../../components/grid.components';
export default class Login extends Component {
constructor(props) {
super(props);
this.state = {
email: '',
password: '',
};
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange = e => {
this.setState({ [e.target.name]: e.target.value });
};
handleSubmit = async e => {
e.preventDefault();
this.props.login(this.state);
};
render() {
return (
<Row justify="center" container>
<Col xs={12} sm={6} md={6} lg={6}>
<Card style={{ margin: '2.5% auto', padding: '2.5%' }}>
<CardHeader title="Login" />
<CardContent>
<Row container spacing={6}>
<Col xs={12} sm={12} md={12} lg={12}>
<TextField
required
onChange={this.handleChange}
name="email"
value={this.state.email}
id="email"
label="Your Email"
fullWidth
/>
</Col>
<Col xs={12} sm={12} md={12} lg={12}>
<TextField
required
type="password"
onChange={this.handleChange}
name="password"
value={this.state.password}
id="password"
label="Your Password"
fullWidth
/>
</Col>
</Row>
</CardContent>
<Row style={{ display: 'flex', justifyContent: 'center' }} container spacing={6}>
<Col xs={12} sm={12} md={12} lg={12}>
<Button onClick={this.handleSubmit} variant="outlined" color="primary">
Login
</Button>
</Col>
</Row>
</Card>
</Col>
</Row>
);
}
}
Login.propTypes = { login: PropTypes.func.isRequired };
|
//Creats a low-fidelity loading spinner. Refactored spinner1.js.
const sentence = "|/-\\|/-\\|";
let delay = 100;
for (const char of sentence) {
setTimeout(() => {
process.stdout.write(`\r${char} `);
}, 0 + delay);
delay += 200;
}
setTimeout(() => {
process.stdout.write('\n');
}, delay + 50);
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.FindCourseClassByModule = exports.FindCourseClass = void 0;
class FindCourseClass {
constructor(classRepo) {
this.classRepo = classRepo;
}
async execute(id) {
var courseClass = null;
var courseClasses = null;
if (id) {
courseClass = await this.classRepo.findById(id);
}
else {
courseClasses = await this.classRepo.findAll();
}
return courseClasses || courseClass;
}
}
exports.FindCourseClass = FindCourseClass;
class FindCourseClassByModule {
constructor(classRepo) {
this.classRepo = classRepo;
}
async execute(module_id) {
const courseClasses = await this.classRepo.findByModule(module_id);
return courseClasses;
}
}
exports.FindCourseClassByModule = FindCourseClassByModule;
|
const jwt = require('jsonwebtoken')
const myFunction = async () => {
// Needs to store a unique code for the user to be authenticated, the user id is nice
// The second (string) is another unique value that makes sure it was not changed. A random
// series of characters are enough
// Third, object to customize the time to be authenticated
// Can be writen in plain english, like '2 weeks', '1 month', '14 days', etc.
// The code below 'thisismynewcourse' can be hidden in an enviroment variable
const token = jwt.sign({_id: 'abc123'}, 'thisismynewcourse', { expiresIn: '7 days'})
console.log(token)
// Verify the token
const data = jwt.verify(token, 'thisismynewcourse')
console.log(data)
}
myFunction()
|
export {requestService} from './RequestService';
|
import React from 'react';
import {Slide, Heading, Text} from 'spectacle';
export default (
<Slide transition={["zoom"]} bgColor="primary">
<Heading size={5} caps lineHeight={1} textColor="secondary">
Разработка веб-сервисов на Go
</Heading>
<Text margin="10px 0 0" textColor="tertiary" size={1} bold>
{location.search.includes('park') ? 'Технопарк' : ''}
{location.search.includes('sphere') ? 'Техносфера' : ''}
{location.search.includes('atom') ? 'Техноатом' : ''}
</Text>
</Slide>
);
|
import "./phaser.js";
// You can copy-and-paste the code from any of the examples at https://examples.phaser.io here.
// You will need to change the `parent` parameter passed to `new Phaser.Game()` from
// `phaser-example` to `game`, which is the id of the HTML element where we
// want the game to go.
// The assets (and code) can be found at: https://github.com/photonstorm/phaser3-examples
// You will need to change the paths you pass to `this.load.image()` or any other
// loading functions to reflect where you are putting the assets.
// All loading functions will typically all be found inside `preload()`.
// The simplest class example: https://phaser.io/examples/v3/view/scenes/scene-from-es6-class
var config = {
type: Phaser.AUTO,
width: 800,
height: 600,
physics: {
default: 'arcade',
arcade: {
gravity: { y: 300 },
debug: false
}
/* matter: {
gravity: { y: 300 },
debug: true
} */
},
scene: {
preload: preload,
create: create,
update: update
}
};
var player;
var platforms;
var ball;
var rockets;
var cells;
var rails;
var key_w;
var key_a;
var key_s;
var key_d;
var key_q;
var key_e;
var key_r;
var mouse;
var weapon_type = 0; //0 for rocket, 1 for beam, 2 for cannon.
var ammo_rocket;
var ammo_beam;
var ammo_cannon;
var next_action = 0;
var weapon_text = "";
var Rail = new Phaser.Class({
Extends: Phaser.GameObjects.Image,
initialize:
// Rail Constructor
function Rail (scene)
{
Phaser.GameObjects.Image.call(this, scene, 0, 0, 'rail');
this.speed = 15;
this.born = 0;
this.direction = 0;
this.xSpeed = 0;
this.ySpeed = 0;
this.setSize(12, 12, true);
this.setScale(3);
this.scaleX = 10;
},
// Fires a rail from the player to the reticle
fire: function (shooter, target, time)
{
if (next_action > time)
{
return;
}
next_action = time + 1333; //cannon/railgun has 1.333 sec delay after firing
this.setPosition(shooter.x, shooter.y); // Initial position
this.direction = Math.atan( (target.x-this.x) / (target.y-this.y));
// Calculate X and y velocity of rail to moves it from shooter to target
if (target.y >= this.y)
{
this.xSpeed = this.speed*Math.sin(this.direction);
this.ySpeed = this.speed*Math.cos(this.direction);
}
else
{
this.xSpeed = -this.speed*Math.sin(this.direction);
this.ySpeed = -this.speed*Math.cos(this.direction);
}
//this.rotation = shooter.rotation; // angle rail with shooters rotation
this.angle = this.direction * (180/Math.PI) * -1 + 90;
this.born = 0; // Time since new rail spawned
},
// Updates the position of the rail each cycle
update: function (time, delta)
{
this.x += this.xSpeed * delta;
this.y += this.ySpeed * delta;
this.born += delta;
if (this.born > 1800)
{
this.setActive(false);
this.setVisible(false);
}
}
});
var Cell = new Phaser.Class({
Extends: Phaser.GameObjects.Image,
initialize:
// Cell Constructor
function Cell (scene)
{
Phaser.GameObjects.Image.call(this, scene, 0, 0, 'cell');
this.speed = 3;
this.born = 0;
this.direction = 0;
this.xSpeed = 0;
this.ySpeed = 0;
this.setSize(12, 12, true);
this.scaleX = 2;
},
// Fires a cell from the player to the reticle
fire: function (shooter, target, time)
{
if (next_action > time)
{
return;
}
next_action = time + 50;
this.setPosition(shooter.x, shooter.y); // Initial position
this.direction = Math.atan( (target.x-this.x) / (target.y-this.y));
// Calculate X and y velocity of cell to moves it from shooter to target
if (target.y >= this.y)
{
this.xSpeed = this.speed*Math.sin(this.direction);
this.ySpeed = this.speed*Math.cos(this.direction);
}
else
{
this.xSpeed = -this.speed*Math.sin(this.direction);
this.ySpeed = -this.speed*Math.cos(this.direction);
}
//this.rotation = shooter.rotation; // angle cell with shooters rotation
this.angle = this.direction * (180/Math.PI) * -1 + 90;
this.born = 0; // Time since new cell spawned
},
// Updates the position of the cell each cycle
update: function (time, delta)
{
this.x += this.xSpeed * delta;
this.y += this.ySpeed * delta;
this.born += delta;
if (this.born > 100)
{
this.setActive(false);
this.setVisible(false);
}
}
});
var Rocket = new Phaser.Class({
Extends: Phaser.GameObjects.Image,
initialize:
// Rocket Constructor
function Rocket (scene)
{
Phaser.GameObjects.Image.call(this, scene, 0, 0, 'rocket');
this.speed = 0.6;
this.born = 0;
this.direction = 0;
this.xSpeed = 0;
this.ySpeed = 0;
this.setSize(12, 12, true);
},
// Fires a rocket from the player to the reticle
fire: function (player, target, time)
{
if (next_action > time)
{
return;
}
next_action = time + 750; //rocket has 0.75 sec delay after firing
this.setPosition(player.x, player.y); // Initial position
this.direction = Math.atan( (target.x-this.x) / (target.y-this.y));
// Calculate X and y velocity of rocket to moves it from player to target
if (target.y >= this.y)
{
this.xSpeed = this.speed*Math.sin(this.direction);
this.ySpeed = this.speed*Math.cos(this.direction);
}
else
{
this.xSpeed = -this.speed*Math.sin(this.direction);
this.ySpeed = -this.speed*Math.cos(this.direction);
}
//this.rotation = player.rotation; // angle rocket with players rotation
//this.rotation = this.direction;
this.angle = this.direction * (180/Math.PI) * -1 + 90;
this.born = 0; // Time since new rocket spawned
},
// Updates the position of the rocket each cycle
update: function (time, delta)
{
this.x += this.xSpeed * delta;
this.y += this.ySpeed * delta;
this.born += delta;
if (this.born > 1800)
{
this.setActive(false);
this.setVisible(false);
}
}
});
var game = new Phaser.Game(config);
function preload ()
{
this.load.image('sky', 'assets/textures/sky.png');
this.load.image('ground', 'assets/textures/platform.png');
this.load.image('star', 'assets/textures/star.png');
this.load.image('bomb', 'assets/textures/bomb.png');
this.load.image('target', 'assets/demoscene/ball.png');
this.load.image('rocket', 'assets/sprites/bullets/bullet6.png');
this.load.image('cell', 'assets/sprites/bullets/cell.png');
this.load.image('rail', 'assets/sprites/bullets/railspiral.png');
this.load.spritesheet('dude', 'assets/animations/dude.png', { frameWidth: 32, frameHeight: 48 });
}
function create ()
{
this.add.image(400, 300, 'sky');
platforms = this.physics.add.staticGroup();
platforms.create(400, 568, 'ground').setScale(2).refreshBody();
platforms.create(600, 400, 'ground');
platforms.create(50, 250, 'ground');
platforms.create(750, 220, 'ground');
player = this.physics.add.sprite(100, 450, 'dude');
player.setBounce(0.2);
player.setCollideWorldBounds(true);
this.player = player;
//weapon text
this.weapon_text = this.add.text(250, 550, "Equip a weapon (Q, E, R)", { font: "24px Arial" });
//quakeball stuff
this.reticle = this.physics.add.sprite(800, 700, 'target');
this.reticle.setDisplaySize(25, 25).setCollideWorldBounds(true);
this.reticle.body.setAllowGravity(false);
//physics groups for attacks
this.rockets = this.physics.add.group({
classType: Rocket,
runChildUpdate: true ,
allowGravity: false
});
this.cells = this.physics.add.group({
classType: Cell,
runChildUpdate: true ,
allowGravity: false
});
this.rails = this.physics.add.group({
classType: Rail,
runChildUpdate: true ,
allowGravity: false
});
//collision rules
//this.physics.add.overlap(this.rockets, this.platforms);
//this.physics.add.collider(rockets, platforms);
this.anims.create({
key: 'left',
frames: this.anims.generateFrameNumbers('dude', { start: 0, end: 3 }),
frameRate: 10,
repeat: -1
});
this.anims.create({
key: 'turn',
frames: [ { key: 'dude', frame: 4 } ],
frameRate: 20
});
this.anims.create({
key: 'right',
frames: this.anims.generateFrameNumbers('dude', { start: 5, end: 8 }),
frameRate: 10,
repeat: -1
});
key_w = this.input.keyboard.addKey('W');
key_a = this.input.keyboard.addKey('A');
key_s = this.input.keyboard.addKey('S');
key_d = this.input.keyboard.addKey('D');
key_q = this.input.keyboard.addKey('Q');
key_e = this.input.keyboard.addKey('E');
key_r = this.input.keyboard.addKey('R');
mouse = this.input.activePointer;
this.mouse = mouse;
//Shoot when mouse clicked
//this.input.on('pointerdown', function (pointer, time, lastFired) {
/* this.input.on('pointerdown', function (pointer, time, lastFired) {
console.log("Mouse Down");
//if (this.player.active === false)
// return;
if (next_action > this.time.now)
{
return;
}
if (weapon_type==0) //if rocket equipped
{
// Get rocket from rockets group
var rocket = this.rockets.get().setActive(true).setVisible(true);
if (rocket)
{
rocket.fire(this.player, this.reticle, this.time.now);
//this.physics.add.collider(this.ball, rocket, this.ballHitCallback);
}
}
else if (weapon_type==1) //if beam equipped
{
// Get cell from cells group
var cell = this.cells.get().setActive(true).setVisible(true);
if (cell)
{
cell.fire(this.player, this.reticle, this.time.now);
//this.physics.add.collider(this.ball, rocket, this.ballHitCallback);
}
}
else if (weapon_type==2) //if cannon/railgun equipped
{
// Get rail from rails group
var rail = this.rails.get().setActive(true).setVisible(true);
if (rail)
{
rail.fire(this.player, this.reticle, this.time.now);
//this.physics.add.collider(this.ball, rocket, this.ballHitCallback);
}
}
}, this); */
// Pointer lock will only work after mousedown
game.canvas.addEventListener('mousedown', function () {
game.input.mouse.requestPointerLock();
});
// Exit pointer lock when Q or escape (by default) is pressed.
this.input.keyboard.on('keydown_Q', function (event) {
if (game.input.mouse.locked)
game.input.mouse.releasePointerLock();
}, 0, this);
// Move reticle upon locked pointer move
this.input.on('pointermove', function (pointer) {
if (this.input.mouse.locked)
{
this.reticle.x += pointer.movementX;
this.reticle.y += pointer.movementY;
}
}, this);
this.physics.add.collider(player, platforms);
}
function update ()
{
if (key_a.isDown)
{
player.setVelocityX(-160);
player.anims.play('left', true);
}
else if (key_d.isDown)
{
player.setVelocityX(160);
player.anims.play('right', true);
}
else
{
player.setVelocityX(0);
player.anims.play('turn');
}
if (key_w.isDown && player.body.touching.down)
{
player.setVelocityY(-330);
}
if (key_q.isDown)
{
this.weapon_text.setText("Rockets");
this.weapon_text.setFill("#F90F00");
weapon_type = 0;
}
if (key_e.isDown)
{
this.weapon_text.setText("Energy Beam");
this.weapon_text.setFill("#00F9EF");
weapon_type = 1;
}
if (key_r.isDown)
{
this.weapon_text.setText("Gauss Cannon");
this.weapon_text.setFill("#10F900");
weapon_type = 2;
}
if (mouse.isDown)
{
console.log("Mouse Down");
//if (this.player.active === false)
// return;
if (next_action > this.time.now)
{
return;
}
if (weapon_type==0) //if rocket equipped
{
// Get rocket from rockets group
var rocket = this.rockets.get().setActive(true).setVisible(true);
rocket.body.setSize(20, 20, true);
//var rocket = Rocket.create();
if (rocket)
{
rocket.fire(this.player, this.reticle, this.time.now);
this.physics.add.collider(rocket, platforms, function() {rocket.setActive(false);rocket.setVisible(false);});
}
}
else if (weapon_type==1) //if beam equipped
{
// Get cell from cells group
var cell = this.cells.get().setActive(true).setVisible(true);
cell.body.setSize(20, 20, true);
cell.body.setOffset(10, 5);
if (cell)
{
cell.fire(this.player, this.reticle, this.time.now);
this.physics.add.collider(cell, platforms, function() {cell.setActive(false);cell.setVisible(false);});
}
}
else if (weapon_type==2) //if cannon/railgun equipped
{
// Get rail from rails group
var rail = this.rails.get().setActive(true).setVisible(true);
rail.body.setSize(10, 10);
if (rail)
{
rail.fire(this.player, this.reticle, this.time.now);
this.physics.add.collider(rail, platforms, function() {rail.setActive(false);rail.setVisible(false);});
}
}
}
}
|
var sql = require('./BaseModel');
// const Config = require('../globals/Config');
var timeController = require('../controllers/TimeController');
// const _config = new Config();
var Task = function (task) {
this.task = task.task;
this.status = task.status;
this.created_at = new Date();
};
Task.getStockBy = function getStockBy(data) {
return new Promise(function (resolve, reject) {//user list
var str = " SELECT * FROM `tb_stock`"
console.log('checkLogin : ', str);
sql.query(str, function (err, res) {
if (err) {
console.log("error: ", err);
const require = {
data: [],
error: err,
query_result: false,
server_result: true
};
resolve(require);
}
else {
const require = {
data: res,
error: [],
query_result: true,
server_result: true
};
resolve(require);
}
});
});
};
Task.getStockByCode = function getStockByCode(data) {
return new Promise(function (resolve, reject) {//user list
var str = " SELECT * ,DATE_FORMAT(stock_date, '%d-%m-%Y') as stock_date, DATE_FORMAT(stock_date, '%H:%i:%s') as stock_time FROM tb_stock "
+ " LEFT JOIN tb_product ON tb_product.product_code = tb_stock.product_code"
+ " WHERE stock_id = '" + data.stock_id + "' ";
console.log('checkLogin : ', str);
sql.query(str, function (err, res) {
if (err) {
console.log("error: ", err);
const require = {
data: [],
error: err,
query_result: false,
server_result: true
};
resolve(require);
}
else {
const require = {
data: res[0],
error: [],
query_result: true,
server_result: true
};
resolve(require);
}
});
});
};
Task.getProductBy = function getProductBy(data) {
return new Promise(function (resolve, reject) {//user list
var str = " SELECT * FROM `tb_product` "
+ " LEFT JOIN tb_unit ON tb_unit.unit_id = tb_product.unit_id"
if (data.about_menu_data == 1) {
str += " WHERE tb_product.about_code = '" + data.about_code + "' OR tb_product.about_code = '" + data.about_main_branch + "' "
} else {
str += " WHERE tb_product.about_code = '" + data.about_code + "' "
}
console.log('checkLogin : ', str);
sql.query(str, function (err, res) {
if (err) {
console.log("error: ", err);
const require = {
data: [],
error: err,
query_result: false,
server_result: true
};
resolve(require);
}
else {
const require = {
data: res,
error: [],
query_result: true,
server_result: true
};
resolve(require);
}
});
});
};
Task.getSumStockInBy = function getSumStockInBy(data) {
return new Promise(function (resolve, reject) {//user list
var str = " SELECT IFNULL(SUM(stock_qty), 0) AS stock_in , unit_id AS unit FROM tb_stock as tb1 "
+ " WHERE tb1.product_code = '" + data.product_code + "'"
+ "GROUP BY unit_id"
// console.log('checkLogin : ', str);
sql.query(str, function (err, res) {
if (err) {
console.log("error: ", err);
const require = {
data: [],
error: err,
query_result: false,
server_result: true
};
resolve(require);
}
else {
const require = {
data: res,
error: [],
query_result: true,
server_result: true
};
resolve(require);
}
});
});
};
Task.getSumStockOutBy = function getSumStockOutBy(data) {
return new Promise(function (resolve, reject) {//user list
var str = " SELECT IFNULL(SUM(product_qty*menu_qty), 0) AS stock_out , unit AS unit FROM tb_stock_out as tb1 "
+ " WHERE tb1.product_code = '" + data.product_code + "'"
+ "GROUP BY unit"
sql.query(str, function (err, res) {
if (err) {
console.log("error: ", err);
const require = {
data: [],
error: err,
query_result: false,
server_result: true
};
resolve(require);
}
else {
const require = {
data: res,
error: [],
query_result: true,
server_result: true
};
resolve(require);
}
});
});
};
Task.getStockByProduct = function getStockByProduct(data) {
return new Promise(function (resolve, reject) {//user list
var str = " SELECT * ,DATE_FORMAT(stock_date, '%d-%m-%Y') as stock_date, DATE_FORMAT(stock_date, '%H:%i:%s') as stock_time FROM tb_stock "
+ " LEFT JOIN tb_product ON tb_product.product_code = tb_stock.product_code"
+ " LEFT JOIN tb_unit ON tb_unit.unit_id = tb_stock.unit_id"
+ " WHERE tb_stock.product_code = '" + data.product_code + "' ";
console.log('checkLogin : ', str);
sql.query(str, function (err, res) {
if (err) {
console.log("error: ", err);
const require = {
data: [],
error: err,
query_result: false,
server_result: true
};
resolve(require);
}
else {
const require = {
data: res,
error: [],
query_result: true,
server_result: true
};
resolve(require);
}
});
});
};
Task.getStockMaxCode = function getStockMaxCode(data) {
return new Promise(function (resolve, reject) {
var str = "IFNULL( LPAD( SUBSTRING(max(stock_code),4 ,8)+1,5, '0'),'00001') AS stock_code_max FROM `tb_stock` "; //insert usercode
console.log('checkLogin : ', str);
sql.query(str, function (err, res) {
if (err) {
console.log("error: ", err);
const require = {
data: [],
error: err,
query_result: false,
server_result: true
};
resolve(require);
}
else {
const require = {
data: res[0],
error: [],
query_result: true,
server_result: true
};
resolve(require);
}
});
});
};
Task.insertStock = function insertStock(data) {
return new Promise(function (resolve, reject) {
var str = "INSERT INTO `tb_stock` ("
+ "`product_code`,"
+ "`about_code`,"
+ "`stock_qty`,"
+ "`stock_price`,"
+ "`stock_qty_cal`,"
+ "`unit_id`,"
// + "`stock_cost`,"
+ "`stock_date`"
+ ") VALUES ("
+ " '" + data.product_code + "', "
+ " '" + data.about_code + "', "
+ " '" + data.stock_qty + "', "
+ " '" + data.stock_price + "', "
+ " '" + data.stock_qty_cal + "', "
+ " '" + data.unit_id + "', "
// + " '" + data.stock_cost + "', "
+ " '" + timeController.reformatTo() + "' "
+ " ) "
console.log('checkLogin : ', str);
sql.query(str, function (err, res) {
if (err) {
console.log("error: ", err);
const require = {
data: false,
error: err,
query_result: false,
server_result: true
};
resolve(require);
}
else {
const require = {
data: true,
error: [],
query_result: true,
server_result: true
};
resolve(require);
}
});
});
};
Task.deleteStockByCode = function deleteStockByCode(data) {
return new Promise(function (resolve, reject) {
var str = "DELETE FROM tb_stock WHERE product_code = '" + data.product_code + "'";//showdata editview
console.log('checkLogin : ', str);
sql.query(str, function (err, res) {
if (err) {
console.log("error: ", err);
const require = {
data: false,
error: err,
query_result: false,
server_result: true
};
resolve(require);
}
else {
const require = {
data: true,
error: [],
query_result: true,
server_result: true
};
resolve(require);
}
});
});
};
Task.updateStock = function updateStock(data) {
return new Promise(function (resolve, reject) {
var str = "UPDATE `tb_stock` SET"
+ "`stock_qty`= '" + data.stock_qty + "'"
+ "WHERE stock_id = '" + data.stock_id + "'";
console.log('checkLogin : ', str);
sql.query(str, function (err, res) {
if (err) {
console.log("error: ", err);
const require = {
data: false,
error: err,
query_result: false,
server_result: true
};
resolve(require);
}
else {
const require = {
data: true,
error: [],
query_result: true,
server_result: true
};
resolve(require);
}
});
});
};
Task.deleteByCode = function deleteByCode(data) {
return new Promise(function (resolve, reject) {
var str = "DELETE FROM tb_stock WHERE stock_id = '" + data.stock_id + "'";//showdata editview
console.log('checkLogin : ', str);
sql.query(str, function (err, res) {
if (err) {
console.log("error: ", err);
const require = {
data: false,
error: err,
query_result: false,
server_result: true
};
resolve(require);
}
else {
const require = {
data: true,
error: [],
query_result: true,
server_result: true
};
resolve(require);
}
});
});
};
Task.getStockByPriceQty = function getStockByPriceQty(data) {
return new Promise(function (resolve, reject) {//user list
var str = "SELECT ( IFNULL(SUM(`stock_price`),0) - "
+ " (SELECT IFNULL(SUM((product_qty * menu_qty * product_cost)),0) FROM `tb_stock_out` WHERE product_code = '" + data.product_code + "' )) "
+ " / (IFNULL(SUM(`stock_qty_cal`),0) - "
+ " (SELECT IFNULL(SUM((product_qty * menu_qty )),0) FROM `tb_stock_out` WHERE product_code = '" + data.product_code + "' )) AS product_cost"
+ " , product_code FROM `tb_stock` WHERE product_code = '" + data.product_code + "'";
console.log('checkLogin : ', str);
sql.query(str, function (err, res) {
if (err) {
console.log("error: ", err);
const require = {
data: [],
error: err,
query_result: false,
server_result: true
};
resolve(require);
}
else {
const require = {
data: res[0],
error: [],
query_result: true,
server_result: true
};
resolve(require);
}
});
});
};
Task.deleteStockBy = function deleteStockBy(data) {
return new Promise(function (resolve, reject) {//user list
var str = "DELETE FROM tb_stock WHERE stock_id = '" + data.stock_id + "'";
console.log('checkLogin : ', str);
sql.query(str, function (err, res) {
if (err) {
console.log("error: ", err);
const require = {
data: [],
error: err,
query_result: false,
server_result: true
};
resolve(require);
}
else {
const require = {
data: res[0],
error: [],
query_result: true,
server_result: true
};
resolve(require);
}
});
});
};
Task.getProductByKey = function getProductByKey(data) {
return new Promise(function (resolve, reject) {//user list
var str = " SELECT * FROM `tb_product` "
+ " LEFT JOIN tb_unit ON tb_unit.unit_id = tb_product.unit_id"
+ " WHERE (product_code LIKE '%" + data.keyword + "%' OR product_name LIKE '%" + data.keyword + "%')"
+ " ORDER BY product_code asc"
console.log('checkLogin : ', str);
sql.query(str, function (err, res) {
if (err) {
console.log("error: ", err);
const require = {
data: [],
error: err,
query_result: false,
server_result: true
};
resolve(require);
}
else {
const require = {
data: res,
error: [],
query_result: true,
server_result: true
};
resolve(require);
}
});
});
};
module.exports = Task;
|
import React, { Component, createContext, Fragment } from 'react';
import styled from 'styled-components';
import InfiniteScroll from 'react-infinite-scroller';
import ReactLoading from 'react-loading';
import axios from 'axios';
import uuid from 'uuid/v4';
import posed, { PoseGroup } from 'react-pose';
import Game from './Game';
import teams from '../../helpers/teams';
import TeamSelector from '../TeamSelector';
const Wrapper = styled.div`
text-align: center;
`;
const VideoContainer = styled.div`
margin-left: 40px;
margin-right: 40px;
display: grid;
grid-template-columns: 1fr;
grid-gap: 40px;
@media (min-width: 800px) {
grid-template-columns: 1fr 1fr;
grid-gap: 75px;
margin-top: 10px;
margin-left: 75px;
margin-right: 75px;
}
@media (min-width: 1100px) {
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
}
`;
const Select = styled.select`
margin-top: 15px;
display: inline-block;
`;
const Button = styled.button`
width: 250px;
height: 30px;
margin: 20px;
display: inline-block;
text-align: center;
border-radius: 4px;
border: 0;
`;
const PoseItem = posed.div({
enter: { opacity: 1 },
exit: { opacity: 0 },
});
const LoadingWrapper = styled.div`
display: flex;
width: 100%;
padding-top: 2rem;
justify-content: center;
`;
class LatestGames extends Component {
state = {
videos: [],
spoiler: false,
nextPageToken: true,
resetState: [],
selectedTeams: [],
};
getVideos = async (type) => {
const nonSpoilerVideos = `https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&playlistId=PL1NbHSfosBuHInmjsLcBuqeSV256FqlOO&key=AIzaSyDFlX0LLCc1b2cZG8aBM0BoN4a8aOq6hMQ${
this.state.nextPageToken && this.state.nextPageToken !== true
? `&pageToken=${this.state.nextPageToken}`
: ''
}`;
const spoilerVideos = `https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&maxResults=50&playlistId=PL1NbHSfosBuHQUCC9DPnnaHqGOGYJRjQV&key=AIzaSyDFlX0LLCc1b2cZG8aBM0BoN4a8aOq6hMQ${
this.state.nextPageToken && this.state.nextPageToken !== true
? `&pageToken=${this.state.nextPageToken}`
: ''
}`;
const {
data: { items, nextPageToken },
} = await axios.get(type === 'spoiler' ? spoilerVideos : nonSpoilerVideos);
this.setState({ nextPageToken });
return items;
};
getSpoilerGames = async () => {
const items = await this.getVideos('spoiler');
this.setState({ videos: items, spoiler: true });
};
selectTeam = (teamName) => {
const { resetState, selectedTeams } = this.state;
let displayTeams = [...selectedTeams];
if (teamName) {
if (displayTeams.includes(teamName)) {
displayTeams = displayTeams.filter(item => item !== teamName);
} else {
displayTeams.push(teamName);
}
}
const filtered = resetState.filter(item => item.snippet.title.match(new RegExp(displayTeams.join('|'), 'ig')));
this.setState({
videos: filtered,
selectedTeams: displayTeams,
});
};
fetchVideos = async () => {
const items = await this.getVideos();
this.setState({ resetState: this.state.resetState.concat(items) });
if (this.state.selectedTeams.length !== 0) {
this.selectTeam();
} else {
this.setState({
videos: this.state.videos.concat(items),
});
}
};
render() {
const { videos, selectedTeams } = this.state;
return (
<Wrapper>
<TeamSelector
selectTeam={this.selectTeam}
selectedTeams={selectedTeams}
/>
<InfiniteScroll
pageStart={0}
loadMore={this.fetchVideos}
hasMore={this.state.nextPageToken || false}
loader={(
<LoadingWrapper key={uuid()}>
<ReactLoading type="bubbles" color="#2D6669" key={uuid()} />
</LoadingWrapper>
)}
>
<VideoContainer>
<PoseGroup>
{videos.map(item => (
<PoseItem key={uuid()}>
<Game
id={item.id}
title={item.snippet.title}
thumbnail={item.snippet.thumbnails.high.url}
videoId={item.snippet.resourceId.videoId}
/>
</PoseItem>
))}
</PoseGroup>
</VideoContainer>
</InfiniteScroll>
</Wrapper>
);
}
}
export default LatestGames;
|
export const ADD_WATCHED_MOVIE = "ADD_WATCHED_MOVIE";
|
var express = require('express');
var path = require('path');
var app = express();
var connections = (process.env.NODE_ENV === 'production')
? require('./config/config.live') : require('./config/config.dev');
var url = connections.hostname + ':' + connections.port;
app.use(express.static(path.join(__dirname, './dist')));
app.listen(process.env.PORT || connections.port);
console.log('Serving on ' + url + ' in ' + connections.env);
|
require('dotenv').config();
const got = require('got');
const {
CHALLONGE_USERNAME,
CHALLONGE_API_KEY,
CHALLONGE_TOURNAMENT_ID,
DB_HOST,
DB_PORT,
DB_DATABASE,
DB_USER,
DB_PASSWORD
} = process.env;
const { Pool } = require('pg');
const pool = new Pool({
user: DB_USER,
host: DB_HOST,
database: DB_DATABASE,
password: DB_PASSWORD,
port: DB_PORT
});
const baseUrl = `https://${CHALLONGE_USERNAME}:${CHALLONGE_API_KEY}@api.challonge.com/v1/tournaments/${CHALLONGE_TOURNAMENT_ID}`;
const results = require('../../docs/data/groups-results.json');
(async () => {
const { body: participants } = await got(`${baseUrl}/participants.json`, { responseType: "json" });
const { rows: matches } = await pool.query(`select
p1.seed as p1seed,
p1.group as p1group,
p2.seed as p2seed,
p2.group as p2group
from (
select seed, "group"
from players
where seed <= 32 and not elite
order by seed
) p1 join (
select seed, "group"
from players
where seed > 32 and seed <= 64 and not elite
order by seed
) p2 on p1.seed = 65 - p2.seed`);
let position = 1;
const seeds = [];
results.forEach((row, i) => {
if (position < 3) {
const match = matches.find(match => (position == 1 && match.p1group == row.group) || (position == 2 && match.p2group == row.group));
if (position == 1) {
match.p1 = `${row.username} (1st of G${row.group}, orig seed ${match.p1seed})`;
match.p1Id = row.id;
seeds[match.p1seed] = participants.find(({ participant }) => participant.misc == match.p1Id);
} else {
match.p2 = `${row.username} (2nd of G${row.group}, orig seed ${match.p2seed})`;
match.p2Id = row.id;
seeds[match.p2seed] = participants.find(({ participant }) => participant.misc == match.p2Id);
}
}
position = results[i+1]?.group != row.group ? 1 : position + 1;
});
for (let i = 1; i < seeds.length; ++i) {
const { participant } = seeds[i];
console.log('seed', i, participant.name);
await got.put(`${baseUrl}/participants/${participant.id}.json`, {
json: {
participant: {
seed: i
}
}
});
}
// for (const match of matches) {
// console.log(`${match.p1.padEnd(50)} vs ${match.p2}`);
// const { rows: [row] } = await pool.query(`insert into matches (stage) values ($1) returning id`, ['ro64']);
// await pool.query(`insert into matches_players (matches_id, players_id) values ($1, $2), ($1, $3)`, [
// row.id,
// match.p1Id,
// match.p2Id
// ]);
// }
process.exit(0);
})();
|
// 所谓Promise, 就是一个对象,用来传递异步操作的消息
// 异步加载图片
function loadImageAsync(url) {
return new Promise(function(resolve, reject) {
var image = new Image();
image.onload = function() {
resolve(image);
}
image.onerror = function() {
reject(new Error('Could not load image at ' + url));
}
image.src = url;
})
}
// Promise.prototype.then();
function getJSON() {};
getJSON('/post/1.json').then(
post => getJSON(post.commentURL)
).then(
comments => console.log('Resolved: ', comments),
err => console.log('Rejected: ', err)
);
// Promise.prototype.catch();
// 一般来说,不要在then方法中定义Rejected状态的回调函数,而应总是使用catch方法
// unhandledRejection事件
// Promise.all();
// Promise.resolve();
// 实现 Promise.done()
Promise.prototype.done = function(onFullfilled, onRejected) {
this.then(onFullfilled, onRejected)
.catch(function(reason){
setTimeout( () => { throw reason }, 0);
});
}
// 实现 Promise.finally()
Promise.prototype.finally = function(callback) {
let P = this.constructor;
return this.then(
value => P.resolve(callback()).then(() => value),
reason => P.resolve(callback()).then(() => throw reason),
);
};
const preloadImage = function(path) {
return new Promise(function(resolve, reject) {
var image = new Image();
image.onload = resolve;
image.onerror = reject;
image.src = path;
});
};
// Generator 与 Promise的结合
|
import API from '../backend'
export const addTodo = (todo) => {
return fetch(`${API}/add`, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
todo: todo
})
}).then(res => {
return res;
})
.catch(err => console.log(err))
}
export const getAllTodos = () => {
return fetch(`${API}/todos`, {
method: "GET"
})
.then(res => res.json())
.catch(err => console.log(err))
}
export const deleteTodo = (id) => {
return fetch(`${API}/delete/${id}`, {
method: 'DELETE'
})
.then(res => res.json())
.catch(err => console.log(err))
}
export const updateTodo = (id, todo) => {
return fetch(`${API}/update/${id}`, {
method: 'PUT',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
todo: todo
})
})
.then(res => res.json())
.catch(err => console.log(err))
}
export const markComplete = (id) => {
return fetch(`${API}/mark/${id}`, {
method: "PUT"
}).then(res => res.json())
.catch(err => console.log(err))
}
|
// @flow
import React from "react";
import { connect } from "react-redux";
import { Navigation } from "./Navigation/Navigation.js";
import { toggleLibraryFactors } from "lk/redux/actions.js";
function LibraryFactors( props )
{
const ListForm = props.listLibraryForm;
return(
<section className="b-section active">
<div className="grid-row">
<div className="grid-cols-24">
<div className="b-section__container b-modul-a">
<div className="b-section__controls">
<ul>
<li><i className="a-icon icon-arrow_maximize"></i></li>
<li><i className="a-icon icon-arrow_minimize"></i></li>
<li onClick={ () => props.toggleLibraryFactors() }><i className="a-icon icon-close"></i></li>
</ul>
</div>
<div className="js__module_content">
<div className="b-section__minimize hide">
<div className="b-section__header">
<div className="b-framework-icon">
<span className="a-icon a-icon-small icon-library-pricing-factors-black"></span>
</div>
<div className="b-section__title">
<span>Библиотека ценообразующих факторов рынка недвижимости</span>
<p>описание факторов</p>
</div>
</div>
</div>
<div className="b-section__maximize">
<div className="b-section__header">
<div className="b-framework-icon">
<span className="a-icon a-icon-small icon-library-pricing-factors-black"></span>
</div>
<div className="b-section__title">
<span>Библиотека ценообразующих факторов рынка недвижимости</span>
<p>описание факторов</p>
</div>
</div>
<div className="b-section__sub-controls">
<ul>
<li><i className="a-icon a-icon-small icon-pin-black"></i></li>
<li><i className="a-icon a-icon-small icon-move-black"></i></li>
</ul>
</div>
<div className="b-section__content">
<div className="b-appbar">
<div className="b-appbar__container">
<span className="b-appbar__title">Каталог характеристик рынка недвижимости</span>
</div>
</div>
<div className="b-modul-a__container">
<div className="b-modul-a__primary-nav">
<Navigation />
</div>
{ ListForm ? <ListForm /> : <span /> }
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
);
}
const mapStateToProps = ( store ) => (
{
listLibraryForm: store.libraryFactors.listLibraryForm
} );
const mapDispatchToProps = ( dispatch ) => (
{
toggleLibraryFactors: () => dispatch( toggleLibraryFactors() )
} );
export default connect( mapStateToProps, mapDispatchToProps, null, { pure: true } )( LibraryFactors );
|
import React from 'react';
import Container from '../components/container'
const About = () => {
return (
<Container>
<h1>About</h1>
<p>Laborum aliquip cillum veniam labore ipsum magna qui anim. Et nisi eu culpa sit cupidatat magna excepteur commodo. Reprehenderit enim id elit est laboris nostrud. Nulla id esse est id labore tempor ipsum et aute. Nisi Lorem velit enim est culpa aute culpa culpa qui id ad. Dolor exercitation id amet nulla mollit id ipsum sit aliquip qui quis. Consequat consectetur culpa esse labore.</p>
</Container>
)
}
export default About;
|
const mysql = require("mysql");
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const app = express();
const port = process.env.PORT || 1100;
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cors());
// CONEXION A MI BASE DE DATOS
const connection = mysql.createConnection({
host: "localhost",
user: "root",
password: null,
database: "Angular"
});
connection.connect(function (error) {
if (error) {
console.log(error);
} else {
console.log("conexión correcta!");
}
});
// *************************** DISCOS **************************** //
// GET DE TODOS LOS DISCOS
app.get("/discos", (req, res) => {
let sql = "SELECT * FROM discos";
connection.query(sql, function (err, result) {
if (err) {
console.log(err);
} else {
console.log("Lista de discos...");
res.send(result);
console.log(result);
}
});
});
// GET BY ID DISCOS
app.get("/discos/:id", (req, res) => {
let params = req.params.id;
let sql = "SELECT titulo, interprete, anyoPublicacion FROM discos WHERE id = ?";
connection.query(sql, params, function (err, result) {
if (err) {
console.log(err);
} else {
console.log("Lista de discos por su id...");
res.send(result);
console.log(result);
}
});
});
// POST DISCOS
app.post("/discos", (req, res) => {
let params = [
req.body.titulo,
req.body.interprete,
req.body.anyoPublicacion
];
let sql =
"INSERT INTO discos (titulo, interprete, anyoPublicacion) VALUES (?,?,?)";
connection.query(sql, params, function (err, result) {
if (err) {
console.log(err);
} else {
console.log("Disco creado correctamente!");
res.send(result);
console.log(result);
}
});
});
// PUT DISCOS
app.put("/discos", (req, res) => {
let params = [
req.body.titulo,
req.body.interprete,
req.body.anyoPublicacion,
req.body.id
];
let sql =
"UPDATE discos SET titulo = ?, interprete = ?, anyoPublicacion = ? WHERE id = ? ";
connection.query(sql, params, function (err, result) {
if (err) {
console.log(err);
} else {
console.log("Disco Actualizado correctamente!");
res.send(result);
console.log(result);
}
});
});
// DELETE DISCOS
app.delete("/discos", (req, res) => {
let params = [req.body.id];
let sql = "DELETE discos FROM discos WHERE id = ?";
connection.query(sql, params, function (err, result) {
if (err) {
console.log(err);
} else {
console.log("Disco Borrado Correctamente!");
// res.send(
// `Los datos del disco con id ${req.body.id} han sido borrados!`
// );
res.send(result)
console.log(result);
}
});
});
app.listen(port, () => {
console.log(`Servidor escuchando en puerto: ${port}`);
});
|
import React, {useState} from "react";
import PropTypes from "prop-types";
import useInput from "../../Hooks/useInput";
import PostPresenter from "./PostPresenter";
const PostContainer = ({
id,
user,
files,
likeCount,
isLiked,
comments,
createdAt,
caption,
location
}) => {
const [isLikedS, setIsLiked] = useState(isLiked);
const [likeCountS, setLikeCount] =useState(likeCount);
const comment = useInput("");
return <PostPresenter
user = {user}
files = {files}
likeCount = {likeCountS}
location = {location}
caption = {caption}
isLiked = {isLikedS}
comments = {comments}
createdAt = {createdAt}
newComment = {comment}
setIsLiked = {setIsLiked}
setLikeCount = {setLikeCount}
/>;
};
PostContainer.propTypes = {
id:PropTypes.string.isRequired,
user:PropTypes.shape({
id:PropTypes.string.isRequired,
avatar:PropTypes.string,
userName: PropTypes.string.isRequired
}).isRequired,
files: PropTypes.arrayOf(
PropTypes.shape({
id:PropTypes.string.isRequired,
url:PropTypes.string.isRequired
})
).isRequired,
likeCount: PropTypes.number.isRequired,
isLiked : PropTypes.bool.isRequired,
comments: PropTypes.arrayOf(
PropTypes.shape({
id:PropTypes.string.isRequired,
text:PropTypes.string.isRequired,
user: PropTypes.shape({
id:PropTypes.string.isRequired,
userName: PropTypes.string.isRequired
}).isRequired
})
).isRequired,
caption:PropTypes.string.isRequired,
location:PropTypes.string,
createdAt: PropTypes.string.isRequired
}
export default PostContainer;
|
'use strict';
describe('Controller: SpeedtestsCtrl', function () {
beforeEach(module('myApp'));
var SpeedtestsCtrl,
scope,
$location,
$httpBackend,
deferred,
q,
routeParams = {},
sFactory;
afterEach(function() {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
beforeEach(inject(function (_$httpBackend_, $controller, $rootScope, _$location_, $q) {
$httpBackend = _$httpBackend_;
scope = $rootScope.$new();
$location = _$location_;
q = $q;
routeParams.location_id = 'derby-c';
routeParams.box_id = '123';
sFactory = {
get: function () {
deferred = q.defer();
return {$promise: deferred.promise};
},
};
SpeedtestsCtrl = $controller('SpeedtestsCtrl', {
$scope: scope,
Speedtest: sFactory,
$routeParams: routeParams
});
}));
it('should get the speedtests ctrl', function () {
spyOn(sFactory, 'get').andCallThrough()
expect(scope.loading).toBe(true);
expect(scope.box.slug).toBe('123')
expect(scope.location_name).toBe('derby-c')
scope.init();
deferred.resolve({box_id: 123});
scope.$apply()
expect(sFactory.get).toHaveBeenCalled();
// expect(scope.box.connected_clients.length).toBe(1);
// expect(scope.loading).toBe(false);
});
});
|
function textEditor(){
this.variableDeclaration = false;
this.forLoop = false;
this.whileLoop = false;
this.ifStatement = false;
this.forLoopWithIfStatment = false;
}
textEditor.prototype.checkForIfStatementInForLoop = function(node){
var nodeBody = node["body"]["body"];
for(var j = 0; j < nodeBody.length; j++){
if(nodeBody[j]["type"] === "IfStatement"){
this.forLoopWithIfStatment = true;
break;
}
}
};
textEditor.prototype.checkForVariableInForLoop = function(node){
if(node["init"] !== null && node["init"]["type"] === "VariableDeclaration"){
this.variableDeclaration = true;
}
};
textEditor.prototype.traverse = function(node) {
if(node === undefined){
$(".display-errors-box").text("Unexpected Token: set conditions for your statement or missing block");
}
var nodeBody = node["body"];
for(var i = 0; i < nodeBody.length; i++){
var currentNode = nodeBody[i];
var type = currentNode["type"];
if (type === "VariableDeclaration"){
this.variableDeclaration = true;
} else if (type === "ForStatement"){
this.forLoop = true;
this.checkForVariableInForLoop(currentNode);
this.checkForIfStatementInForLoop(currentNode);
} else if(type === "WhileStatement"){
this.whileLoop = true;
} else if (type === "IfStatement") {
this.ifStatement = true;
this.traverse(currentNode["consequent"]);
}
if(currentNode["body"] !== undefined){
this.traverse(currentNode);
}
}
};
function displayResults() {
var code = editor.getValue();
var newEditor = new textEditor();
$(".display-errors-box").text("");
try {
var node = esprima.parse(code);
}
catch(err){
$(".display-errors-box").text(err.description);
}
finally {
newEditor.traverse(node);
if(newEditor.variableDeclaration === true && newEditor.forLoop === true){
$(".for-loop-and-variable").css("background-color", "green");
} else {
$(".for-loop-and-variable").css("background-color", "red");
}
if(newEditor.whileLoop === false && newEditor.ifStatement === false){
$(".while-and-if").css("background-color", "green");
}else {
$(".while-and-if").css("background-color", "red");
}
if(newEditor.forLoopWithIfStatment === true){
$(".if-inside-for").css("background-color", "green");
}else {
$(".if-inside-for").css("background-color", "red");
}
}
}
|
import React from 'react'
import Questions from './questions'
import './styles.css'
export default class extends React.Component {
constructor(props) {
super(props)
this.state = {
survey: props.survey
}
}
render() {
const { questions } = this.state.survey
return <div>
<h2>Evoluquestion</h2>
<h3>Create, edit & publish your questionaires!</h3>
<Questions questions={ questions } />
</div>
}
}
|
import React, {useState, useCallback, useEffect} from "react";
import $ from 'jquery';
import List from './components/AttackPatterns'
const SERVER_IP = 'http://127.0.0.1:3001/';
const App = () => {
// defining current view (list or grid)
const [currentView, setCurrentView] = useState("list");
// handling change of current view
const handleToggleCurrentView = useCallback(() => {
setCurrentView(view => (view === "list" ? "grid" : "list"));
}, [setCurrentView]);
// for database output
const [data, setData] = React.useState([]);
const [isLoaded, setIsLoaded] = React.useState(false);
const [error, setError] = React.useState(null);
// getting database information from server
useEffect(()=> {
$.ajax({url: SERVER_IP, method: 'GET',
success: function(result){
setData(result);
setIsLoaded(true);
},
error: function(xhr, status, error) {
setIsLoaded(false);
setError(error);
}
})
});
// showing output (if the data has been loaded, the data if it loaded, or an error if occurred)
if (error) {
return <div>Error: {error}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<div>
<List
items={data}
currentView={currentView}
onToggleCurrentView={handleToggleCurrentView}
/>
</div>
);
}
}
export default App;
|
/**
* Created by lilit on 2018-06-05.
*/
//then import users and tweets at shared.js
export const RECEIVE_USERS = 'RECEIVE_USERS';
export function receiveUsers (users) {
return {
type: RECEIVE_USERS,
users
}
}
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { Grid, Header, Segment, Button, Icon, Dimmer, Loader, Message, Label, Card } from 'semantic-ui-react';
import DatePicker from 'react-datepicker';
import moment from 'moment';
import { getFilteredBookings, getAvailability } from '../redux/actions/booking';
import axios from 'axios';
import { push } from 'react-router-redux';
const square = { width: 175, height: 175, cursor: 'pointer' };
const Tim = {
'1': '7 am - 9 am',
'2': '9 am - 11am',
'3': '11 am - 1 pm',
'5': ' 3 pm - 5pm',
'6': '5 pm - 7pm',
'4': '1 pm - 3 pm'
};
class BookPage extends Component {
constructor(props) {
super(props);
this.state = { date: moment(), isOpen: false, loading: false, bookmodal: false, error: '', t: '' };
this.handleChange = this.handleChange.bind(this);
this.getAvailability = this.getAvailability.bind(this);
this.bookGround = this.bookGround.bind(this);
}
handleSmsSubmit(){
const booking = this.state.current.booking;
axios({
method: 'post',
url:'http//localhost:3000/api/sms',
data: {
Username: this.props.user.Username,
groundname: this.props.idvalues[booking.groundId].name,
date: booking.date.replace(/d/g, '-'),
slots: Tim[booking.slots]
}
.then(res=>{
console.log(res);
console.log(res.data);
})
})
}
handleChange(date) {
this.setState({
date: date,
isOpen: false
});
this.getAvailability(date);
}
getAvailability(date) {
const groundId = this.props.location.pathname.substr(this.props.location.pathname.lastIndexOf('/') + 1);
const dat = date.format('DD-MM-YYYY').replace(/-/g,'d');
this.props.getAvailability(groundId,dat );
}
componentDidMount() {
this.getAvailability(this.state.date);
}
componentWillReceiveProps(newProps) {
if (newProps.location.pathname !== this.props.location.pathname) {
this.getAvailability(this.state.date);
}
}
bookGround(timeframe) {
this.setState({ loading: true, error: '', t: timeframe });
const book = { userId: '',Username:'', date: '', slots: '' };
book.slots = Number(timeframe);
book.userId = this.props.user._id;
book.Username = this.props.user.Username;
const dat = this.state.date.format('DD-MM-YYYY').replace(/-/g,'d');
book.date = dat;
const groundId = this.props.location.pathname.substr(this.props.location.pathname.lastIndexOf('/') + 1);
console.log(groundId, book);
const that = this;
axios({ method: 'post', url: `http://localhost:3000/api/booking/${groundId}`, data: book })
.then((response) => {
console.log('done');
that.setState({ bookmodal: true, loading: false });
})
.catch(err => that.setState({ loading: false, error: err.message }));
}
render() {
console.log(this.props);
const curr = new Date();
const currenthour = curr.getHours();
const currday = moment();
console.log(currenthour);
console.log('checcck', ...{ a: 2 }, {});
const { booking } = this.props;
const groundId = this.props.location.pathname.substr(this.props.location.pathname.lastIndexOf('/') + 1);
return (
<div>
{this.state.error && <Message negative>{this.state.error}</Message>}
<Dimmer active={this.state.loading}>
<Loader />
</Dimmer>
<Dimmer active={this.state.bookmodal}>
<Card.Group>
<Card raised className="modalcard">
<Icon
color="red"
inverted
size="medium"
name="cancel"
onClick={() => {
this.setState({ bookmodal: false });
this.getAvailability(this.state.date);
}}
/>
<Card.Content>
<br />
<br />
<br />
<Header as="h2" color="teal">
CONGRATULATIONS!!
</Header>
<br />
<Header as="h3">
Your booking at {this.props.grounds[groundId] && this.props.grounds[groundId].name} is at {' '}
{this.state.date.format('DD-MM-YYYY')} between {Tim[this.state.t]}. Make sure you reach there in time!
</Header>
<br />
<Button
onClick={()=>{
this.setState({ bookmodal: false });
this.handleSmsSubmit();
this.props.push('/dashboard');
}}
color="green"
>
Oh Yeah!
</Button>
</Card.Content>
</Card>
</Card.Group>
</Dimmer>
<Header as="h1" textAlign="center">
Book Your Game Time
</Header>
<br />
<br />
<Grid centered padded stackable columns={4}>
<Grid.Column>
<Header as="h2">Change Date</Header>
<Segment circular color="green" raised style={square} onClick={() => this.setState({ isOpen: true })}>
<Header as="h2">
<br />
<Header.Subheader>
<Icon name="calendar" size="big" />
</Header.Subheader>
</Header>
<h3> {this.state.date.format('DD-MM-YYYY')}</h3>
</Segment>
{this.state.isOpen && (
<DatePicker
inline
withPortal
selected={this.state.date}
onChange={this.handleChange}
minDate={moment()}
maxDate={moment().add(2, 'weeks')}
/>
)}
</Grid.Column>
<Grid.Column>
<Header as="h2">Available On</Header>
<Button
size="large"
color={booking['1'] ? 'red' : 'green'}
disabled={
(currday.format('DD-MM-YYYY') == this.state.date.format('DD-MM-YYYY') && currenthour > 7) ||
booking['1']
}
onClick={() => this.bookGround('1')}
>
7 am - 9 am
</Button>
<Button
size="large"
color={booking['2'] ? 'red' : 'green'}
disabled={
(currday.format('DD-MM-YYYY') == this.state.date.format('DD-MM-YYYY') && currenthour > 9) ||
booking['2']
}
onClick={() => this.bookGround('2')}
>
9 am - 11am
</Button>
<br />
<br />
<br />
<Button
size="large"
color={booking['3'] ? 'red' : 'green'}
disabled={
(currday.format('DD-MM-YYYY') == this.state.date.format('DD-MM-YYYY') && currenthour > 11) ||
booking['3']
}
onClick={() => this.bookGround('3')}
>
11 am - 1 pm
</Button>
<Button
size="large"
color={booking['4'] ? 'red' : 'green'}
disabled={
(currday.format('DD-MM-YYYY') == this.state.date.format('DD-MM-YYYY') && currenthour > 13) ||
booking['4']
}
onClick={() => this.bookGround('4')}
>
1 pm - 3 pm
</Button>
<br />
<br />
<br />
<Button
size="large"
color={booking['5'] ? 'red' : 'green'}
disabled={
(currday.format('DD-MM-YYYY') == this.state.date.format('DD-MM-YYYY') && currenthour > 15) ||
booking['5']
}
onClick={() => this.bookGround('5')}
>
3 pm - 5pm
</Button>
<Button
size="large"
color={booking['6'] ? 'red' : 'green'}
disabled={
(currday.format('DD-MM-YYYY') == this.state.date.format('DD-MM-YYYY') && currenthour > 17) ||
booking['6']
}
onClick={() => this.bookGround('6')}
>
5 pm - 7pm
</Button>
<br />
<br />
<br />
<br />
<br />
<br /> <br />
<br />
<br />
<br />
</Grid.Column>
</Grid>
</div>
);
}
}
const mapDispatchToProps = dispatch => {
return {
getFilteredBookings: bindActionCreators(getFilteredBookings, dispatch),
getAvailability: bindActionCreators(getAvailability, dispatch),
push: bindActionCreators(push, dispatch)
};
};
const mapStateToProps = state => ({
location: state.router.location,
booking: state.booking.currentBooking,
user: state.userprofile.data,
grounds: state.ground.ids
});
export default connect(
mapStateToProps,
mapDispatchToProps
)(BookPage);
|
//Action creators are functions that return an action,
//an action is just an object that flows through all the different
//reducers, reducers can then use that action to produce a different value
//for a particular piece of state
export function selectBook(book) {
//selectBook is an ActionCreator, it needs to return an action,
//an object with a type property.
return {
type: 'BOOK_SELECTED',
payload: book
};
}
|
module.exports = {
'secret': 'jwtsecretxxxxx'
};
|
import someModule from './some-module';
const answer = () => 42;
console.log(answer());
console.log(someModule.some);
|
/*#################################################### Klasse Arrow ###################################################*/
function Arrow(bc,type){
//********************** Attribute **************************
//************************************************************
this.bc;
this.hLine;
this.startIb;
this.endDir;
this.endIb;
this.selectedIb;
this.arrowType;
this.isDBObject;
this.id;
var startX;
var startY;
var endX;
var endY;
var img_size;
this.stroke;
//********************** Methoden ***************************
//************************************************************
this.deleteArrow = function(){
document.getElementById(this.bc.parent_element_id).removeChild(this.endEl);
document.getElementById(this.bc.parent_element_id).removeChild(this.startEl);
document.getElementById(this.bc.parent_element_id).removeChild(this.middleEl);
document.getElementById(this.bc.parent_element_id).removeChild(this.startImg);
if (this.startIb != null){
this.startIb.arrowList = arrayRemove(this.startIb.arrowList,this);
}
if (this.endIb != null){
this.endIb.arrowList = arrayRemove(this.endIb.arrowList,this);
}
}
this.getMaxZ = function(){
return this.middleEl.style.zIndex;
}
this.setArrowFocus = function(){
this.bc.setFocus(this.endEl);
this.bc.setFocus(this.startEl);
this.bc.setFocus(this.middleEl);
this.bc.setFocus(this.startImg);
}
this.setPos = function(ib,x,y){
if (this.startIb == ib){
this.setStartPos(x,y);
}else if (this.endIb == ib){
this.setEndPos(x,y);
}
}
this.setSelectedIb = function(ib){
this.selectedIb = ib;
}
//depends on setSelectedIb
this.getOpposite = function(){
if (this.startIb == this.selectedIb){
return this.endIb;
}else if (this.endIb == this.selectedIb){
return this.startIb;
}
return null;
}
//depends on setSelectedIb
this.getSite = function(){
if (this.startIb == this.selectedIb){
return this.endDir;
}else if (this.endIb == this.selectedIb){
if (this.endDir == -1){
return -1;
}else{
return (this.endDir+2)%4;
}
}else{
return -1;
}
}
this.setStartPos = function (x,y){
this.endX = x;
this.endY = y;
this.refresh();
}
this.setEndPos = function (x,y){
this.startX = x;
this.startY = y;
this.refresh();
}
this.setType = function (type){
this.arrowType = type;
/*alert("event : "+ this.arrowType);*/
}
function dist(p1,p2){
return Math.sqrt((p1[0]-p2[0])*(p1[0]-p2[0]) + (p1[1]-p2[1])*(p1[1]-p2[1]));
}
this.refresh = function (){
if (this.startIb != null) {
var start_corner = this.startIb.getPos();
var s_left = start_corner[0][0];
var s_top = start_corner[0][1];
var s_right = start_corner[1][0];
var s_bottom = start_corner[1][1];
var e_left;
var e_top;
var e_right;
var e_bottom;
if (this.endIb != null){
var end_corner = this.endIb.getPos();
e_left = end_corner[0][0];
e_top = end_corner[0][1];
e_right = end_corner[1][0];
e_bottom = end_corner[1][1];
}else{
e_left = this.startX;
e_top = this.startY;
e_right = this.startX;
e_bottom = this.startY;
}
var side = -1; //0= top 1=right 2=bottom 3=left
if ((s_right <= e_left) && (e_bottom >= s_top) && (s_bottom >= e_top)){ //right
side = 1;
}else if ((s_left >= e_right) && (e_bottom >= s_top) && (s_bottom >= e_top)){ //left
side = 3;
}else if ((s_top >= e_bottom) && (s_left <= e_right) && (s_right >= e_left)){ //top
side = 0;
}else if ((s_bottom <= e_top) && (s_left <= e_right) && (s_right >= e_left)){ //bottom
side = 2;
}else if ((s_top >= e_bottom) && (s_right <= e_left)){ // topright
if ((s_top-e_bottom) > (e_left-s_right)){
side = 0;
}else{
side = 1;
}
}else if ((s_bottom <= e_top) && (s_right <= e_left)){ // bottomright
if ((e_top-s_bottom) > (e_left-s_right)){
side = 2;
}else{
side = 1;
}
}else if ((s_bottom <= e_top) && (s_left >= e_right)){ // bottomleft
if ((e_top-s_bottom) > (s_left-e_right)){
side = 2;
}else{
side = 3;
}
}else if ((s_top >= e_bottom) && (s_left >= e_right)){ // topleft
if ((s_top-e_bottom) > (s_left-e_right)){
side = 0;
}else{
side = 3;
}
}
this.endDir = side;
}
this.refreshPos();
}
this.refreshPos = function (){
if (this.endDir == -1){
this.endEl.style.display = "none";
this.middleEl.style.display = "none";
this.startEl.style.display = "none";
this.centerImgDiv.display = "none";
this.startImg.style.display = "none";
} else if (this.endDir == 3){
this.endEl.style.display = "block";
this.middleEl.style.display = "block";
this.startEl.style.display = "block";
this.centerImgDiv.display = "block";
var width = this.endX-this.startX;
this.endEl.style.left = this.startX+width/2;
this.endEl.style.top = this.endY;
this.endEl.style.width = width/2;
this.endEl.style.height = this.stroke;
if (this.endIb != null){
this.startImg.style.left = this.startX;
this.startImg.style.top = this.startY-(img_size/2);
this.startImg.src = "resources/arrow3.png";
this.startImg.style.display = "block";
}else{
this.startImg.style.display = "none";
}
var minY = 0;
var height = 0;
if (this.endY < this.startY){
height = this.startY - this.endY;
minY = this.endY;
}else{
height = this.endY - this.startY;
minY = this.startY;
}
this.middleEl.style.left = this.startX+width/2;
this.middleEl.style.top = minY;
this.middleEl.style.width = this.stroke;
this.middleEl.style.height = height;
this.startEl.style.left = this.startX;
this.startEl.style.top = this.startY;
this.startEl.style.width = width/2;
this.startEl.style.height = this.stroke;
this.centerImgDiv.style.left = -centerImgDivWidth/2;
this.centerImgDiv.style.top = height/2-centerImgDivHeight/2;
}else if (this.endDir == 1){
//right
this.endEl.style.display = "block";
this.middleEl.style.display = "block";
this.startEl.style.display = "block";
this.centerImgDiv.display = "block";
var width = this.startX-this.endX;
this.endEl.style.left = this.endX;
this.endEl.style.top = this.endY;
this.endEl.style.width = width/2;
this.endEl.style.height = this.stroke;
var height = 0;
if (this.endY < this.startY){
height = this.startY - this.endY;
}else{
height = this.endY - this.startY;
}
this.middleEl.style.left =this.endX+width/2;
this.middleEl.style.top = Math.min(this.endY,this.startY);//minY;
this.middleEl.style.width = this.stroke;
this.middleEl.style.height = height;
this.startEl.style.left = this.endX+width/2;
this.startEl.style.top = this.startY;
this.startEl.style.width = width/2;
this.startEl.style.height = this.stroke;
if (this.endIb != null){
this.startImg.style.left = this.startX-img_size;
this.startImg.style.top = this.startY-(img_size/2);
this.startImg.src = "resources/arrow1.png";
this.startImg.style.display = "block";
}else{
this.startImg.style.display = "none";
}
this.centerImgDiv.style.left = -centerImgDivWidth/2;
this.centerImgDiv.style.top = height/2-centerImgDivHeight/2;
}else if (this.endDir == 0){
//up
this.endEl.style.display = "block";
this.middleEl.style.display = "block";
this.startEl.style.display = "block";
this.centerImgDiv.display = "block";
var height = this.endY-this.startY;
this.endEl.style.left = this.endX;
this.endEl.style.top = this.startY + height/2;
this.endEl.style.width = this.stroke;
this.endEl.style.height = height/2;
var minX = 0;
var width = 0;
if (this.endX < this.startX){
width = this.startX - this.endX;
minX = this.endX;
}else{
width = this.endX - this.startX;
minX = this.startX;
}
this.middleEl.style.left = minX;
this.middleEl.style.top = this.startY + height/2;
this.middleEl.style.width = width;
this.middleEl.style.height = this.stroke;
this.startEl.style.left = this.startX;
this.startEl.style.top = this.startY;
this.startEl.style.width = this.stroke;
this.startEl.style.height = height/2;
if (this.endIb != null){
this.startImg.style.left = this.startX-(img_size/2);
this.startImg.style.top = this.startY;
this.startImg.src = "resources/arrow0.png";
this.startImg.style.display = "block";
}else{
this.startImg.style.display = "none";
}
this.centerImgDiv.style.left = width/2-centerImgDivWidth/2;
this.centerImgDiv.style.top = -centerImgDivHeight/2;
}else if (this.endDir == 2){
//down
this.endEl.style.display = "block";
this.middleEl.style.display = "block";
this.startEl.style.display = "block";
this.centerImgDiv.display = "block";
var height = this.startY-this.endY;
this.endEl.style.left = this.endX;
this.endEl.style.top = this.endY;
this.endEl.style.width = this.stroke;
this.endEl.style.height = height/2;
var minX = 0;
var width = 0;
if (this.endX < this.startX){
width = this.startX - this.endX;
minX = this.endX;
}else{
width = this.endX - this.startX;
minX = this.startX;
}
this.middleEl.style.left = minX;
this.middleEl.style.top = this.endY + height/2;
this.middleEl.style.width = width;
this.middleEl.style.height = this.stroke;
this.startEl.style.left = this.startX;
this.startEl.style.top = this.endY + height/2;
this.startEl.style.width = this.stroke;
this.startEl.style.height = height/2;
if (this.endIb != null){
this.startImg.style.left = this.startX-(img_size/2);
this.startImg.style.top = this.startY-img_size;
this.startImg.src = "resources/arrow2.png";
this.startImg.style.display = "block";
}else{
this.startImg.style.display = "none";
}
this.centerImgDiv.style.left = width/2-centerImgDivWidth/2;
this.centerImgDiv.style.top = -centerImgDivHeight/2;
}
}
//********************** Konstruktor ************************
//************************************************************
this.bc = bc;
this.hLine = true;
this.startIb = null;
this.endDir=-1;
this.endIb = null;
this.selectedIb = null;
this.arrowType = type;
this.isDBObject = false;
this.id = randomId();
var startX=0;
var startY=0;
var endX=0;
var endY=0;
var img_size = 20;
this.stroke = 2;
this.endEl = document.createElement("div");
this.endEl.style.backgroundColor ="#909090";
this.endEl.style.width = "10px";
this.endEl.style.height = "10px";
this.endEl.style.position="absolute";
document.getElementById(this.bc.parent_element_id).appendChild(this.endEl);
this.startEl = document.createElement("div");
this.startEl.style.backgroundColor ="#909090";
this.startEl.style.width = "10px";
this.startEl.style.height = "10px";
this.startEl.style.position="absolute";
document.getElementById(this.bc.parent_element_id).appendChild(this.startEl);
this.startImg = document.createElement("img");
this.startImg.style.width = "20px";
this.startImg.style.height = "20px";
this.startImg.style.position="absolute";
document.getElementById(this.bc.parent_element_id).appendChild(this.startImg);
this.middleEl = document.createElement("div");
this.middleEl.style.backgroundColor ="#909090";
this.middleEl.style.width = "10px";
this.middleEl.style.height = "10px";
this.middleEl.style.position="absolute";
document.getElementById(this.bc.parent_element_id).appendChild(this.middleEl);
var centerImgDivWidth = 48;
var centerImgDivHeight = 48;
this.centerImgDiv = document.createElement("img");
this.centerImgDiv.style.width = "48px";
this.centerImgDiv.style.height = "48px";
this.centerImgDiv.style.position="absolute";
switch (this.arrowType) {
case "MARK":
this.centerImgDiv.src = "resources/buttons/ausrufezeichen_symbol.png";
break;
case "QUEST":
this.centerImgDiv.src = "resources/buttons/frage_symbol.png";
break;
case "CONT":
this.centerImgDiv.src = "resources/buttons/blitz_symbol.png";
break;
default:
alert("das event war : " + this.arrowType);
break;
}
this.middleEl.appendChild(this.centerImgDiv);
this.bc.setFocus(this.centerImgDiv);
//******************* event-listener-Methoden ***************
//************************************************************
this.killArrowConfirm = function(ev){
check = confirm("Soll dieser Pfeil gelöscht werden ?");
if (check){
//hier den ajax command
}
return false;
};
this.centerImgDiv.ondblclick = this.killArrowConfirm.bindAsEventListener(this);
}
|
(function () {
'use strict';
angular
.module('sketchbook')
.factory('GhostService', fnGhostService);
/** @ngInject */
function fnGhostService() {
fnGhostService.fnGetColor = function (attrObj, value) {
var returnValue = attrObj.defaultColor ? attrObj.defaultColor : '#000';
var tempObj = null;
if (attrObj.mapType === "direct") {
tempObj = _.find(attrObj[attrObj.mapType], {'value': value}); //eslint-disable-line
returnValue = tempObj ? tempObj.color : returnValue;
} else if (attrObj.mapType === "range") {
tempObj = attrObj[attrObj.mapType].filter(function (obj) {
return value >= obj.from && value <= obj.to;
})[0];
returnValue = tempObj ? tempObj.color : returnValue;
}
return returnValue;
};
fnGhostService.fnGetIconValue = function (attrObj, value) {
var returnValue = attrObj.defaultIcon ? attrObj.defaultIcon : 'fa-times';
if(!isNaN(value) && value !== true) {
value = parseInt(value)
}
var tempObj = null;
if (attrObj.mapType === "direct") {
tempObj = _.find(attrObj[attrObj.mapType], {'value': value}); //eslint-disable-line
returnValue = tempObj ? tempObj.icon : returnValue;
} else if (attrObj.mapType === "range") {
tempObj = attrObj[attrObj.mapType].filter(function (obj) {
return value >= obj.from && value <= obj.to;
})[0];
returnValue = tempObj ? tempObj.icon : returnValue;
}
return returnValue;
};
fnGhostService.fnGetToggleValue = function (attrObj, value) {
var returnValue = attrObj.default.value === true ? attrObj.default.trueText : attrObj.default.falseText;
var tempObj = null;
if (attrObj.mapType === "direct") {
tempObj = _.find(attrObj[attrObj.mapType], {'value': value}); //eslint-disable-line
returnValue = tempObj ? (tempObj.isTrue ? attrObj.default.trueText : attrObj.default.falseText) : returnValue;
} else if (attrObj.mapType === "range") {
tempObj = attrObj[attrObj.mapType].filter(function (obj) {
return value >= obj.from && value <= obj.to;
})[0];
returnValue = tempObj ? (tempObj.isTrue ? attrObj.default.trueText : attrObj.default.falseText) : returnValue;
}
return {displayText : returnValue, switchValue: tempObj ? tempObj.isTrue : attrObj.default.value};
};
fnGhostService.fnGetTextValue = function (attrObj, value) {
var returnValue = "default string";
var tempObj = null;
if (attrObj.mapType === "direct") {
var tempVal = value.toString();
tempObj = _.find(attrObj[attrObj.mapType], {'value': tempVal}); //eslint-disable-line
returnValue = tempObj ? tempObj.text : value;
} else if (attrObj.mapType === "range") {
tempObj = attrObj[attrObj.mapType].filter(function (obj) {
return value >= obj.from && value <= obj.to;
})[0];
returnValue = tempObj ? tempObj.text : value;
}
return returnValue;
};
return fnGhostService;
}
})();
|
import { ADD_FORM, UPDATE_FORM, REMOVE_FORM } from '../actions';
const initialState = {
key : 0,
forms : []
}
function remove(array, element) {
return array.filter(e => e.key !== element);
}
export default (state = {...initialState}, action) => {
switch (action.type) {
case ADD_FORM: {
state.forms.push({
key : state.key,
value : ''
})
state.key++
return {
...state
}
}
case REMOVE_FORM: {
const forms = remove(state.forms, action.key)
return {
...state,
forms
}
}
case UPDATE_FORM: {
const {key, value} = action
const index = state.forms.findIndex(item => item.key === key)
state.forms[index] = {
...state.forms[index],
value
}
return {
...state
}
}
default:
return state;
}
};
|
var win = 0
var loss = 0
var guess = 0
var guessLeft = 9
var letterArray = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
var rand = letterArray[Math.floor(Math.random() * letterArray.length)];
console.log(rand);
var userGuess = prompt("pick a letter:")
for (i = 9 ; i = 0 ; i--){
if (userGuess === rand) {
console.log(win + 1)
}
else {
console.log(guessLeft - 1)
}
}
|
import React, { Component } from "react";
import { connect } from "react-redux";
import { Row, Col } from "reactstrap";
import Usage from "./Usage";
import Register from "./Register";
import MessageRegister from "./MessageRegister";
import { Link } from "react-router-dom";
import setting from "../img/setting.png";
import Language from "./Language";
class Setting extends Component {
render() {
return (
<Row id="setting">
<Col xs={12} className="mb-1"><Link to="/"><h4 style={{"color": "white"}}>⚒ Setting 🛠</h4></Link></Col>
<Usage />
<Register />
{/* <MessageRegister /> */}
<Language />
<Link to="/"><img id="setting-icon" src={setting} alt="setting" /></Link>
</Row>
);
}
}
const mapStateToProps = (state) => {
return {
};
};
export default connect(mapStateToProps)(Setting);
|
import React, {Component} from 'react';
import AddAsset from './AddAsset'
import muiTheme from './muitheme'
const styles = {
rootContainerStyle: {
display: "flex",
flexDirection: "column",
position: "absolute",
height: "100%",
width: "100%",
justifyContent: "flex-start"
},
formContainer: {
display: "flex",
flexDirection: "column",
height: "100%",
justifyContent: "flex-start",
marginTop: "50px"
},
formStyle: {
overflow: "auto",
display: "flex",
position: "relative",
justifyContent: "center",
marginRight: "auto",
marginLeft: "auto",
flexShrink: 0,
padding: 10
},
formCenterStyle: {
marginLeft: "auto",
marginRight: "auto",
width: "100%",
position: "relative",
display: "flex",
flexDirection: "column",
justifyContent: "center"
}
};
class CommonAddComponent extends Component {
getChildContext() {
return muiTheme
}
render() {
return <div style={styles.rootContainerStyle}>
<AddAsset {...this.props} />
<div style={styles.formContainer}>
<div style={styles.formStyle}>
<div style={styles.formCenterStyle}>
{this.props.children}
</div>
</div>
</div>
</div>
}
}
CommonAddComponent.childContextTypes = {
muiTheme: React.PropTypes.object.isRequired
};
export default CommonAddComponent;
|
// function hi(userName){
// console.log("Hi, ${userName}.");
// }
// hi('Thomas')
/*
- Write a function that takes two parameters:
- one parameter is for a first name,
- the other parameter is for a last name;
- have them come together in a variable inside the function.
- console.log 'Hello, my name is <your name>'
- call (or invoke) your function
*/
function hello(first, last){
let fullName = first + ' ' + last;
console.log("Hello, my name is " + fullName + '.')
}
hello('thomas', 'glover')
|
Package.describe({
name: 'universe:react-chartjs',
version: '1.0.2',
// Brief, one-line summary of the package.
summary: '',
// URL to the Git repository containing the source code for this package.
git: '',
// By default, Meteor will default to using README.md for documentation.
// To avoid submitting documentation, set this field to null.
documentation: 'README.md'
});
Package.onUse(function(api) {
api.versionsFrom('1.1.0.3');
api.use([
'chart:chart',
'universe:modules@0.4.1'
]);
api.addFiles('index.js');
api.addFiles('index.import.jsx');
api.addFiles('plugins/Chart.StackedBar.js', 'client');
api.addFiles('lib/core.import.jsx');
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.