text
stringlengths 7
3.69M
|
|---|
import React, { Component } from 'react';
import {withRouter} from "react-router-dom";
class Login extends Component {
constructor(props) {
super(props);
this.onSubmit = this.onSubmit.bind(this);
}
onSubmit(e) {
e.preventDefault();
const regex = /^[0-9]+$/;
const userId = document.getElementById('userId').value;
// NOVO
if (userId === "") {
document.getElementById('errorMassage').innerHTML = "Please enter your ID!";
return;
}
if (!regex.test(userId)) {
document.getElementById('errorMassage').innerHTML = "You've entered the wrong ID! ID is integer.";
return;
}
this.props.history.push(`/${userId}`);
}
render() {
return (
<div>
<form onSubmit={this.onSubmit}>
<input type="text" id="userId" placeholder="Enter user ID" />
<button type="submit">Login</button>
</form>
<h4 id="errorMassage"></h4>
</div>
);
}
}
export default withRouter(Login);
|
const BASE_IP = 'localhost'; // 테스트
// const BASE_IP = '58.229.183.87'; // 실서버
const BASE_PORT = 8000; //angular
// exports.API_SERVER = 'http://' + BASE_IP + ':3000';
exports.CHAT_SERVER = 'http://' + BASE_IP + ':3001';
// export const API_URL = API_SERVER + '/api';
// export const IMG_URL = API_SERVER + '/images';
// export const EXCEL_URL = API_SERVER + '/excels';
exports.USER_TYPE_MANAGER = 1;
exports.USER_TYPE_CUSTOMER = 2;
exports.USER_TYPE_NORMAL = 3;
exports.USER_TYPE_AUTO = 4;
exports.USER_TYPE_AUTO_DELAY = 5;
exports.USER_TYPE_PARTNER = 6;
exports.MSG_TYPE_NORMAL = 1;
exports.MSG_TYPE_CUSTOMER = 2;
exports.MSG_TYPE_MANAGER = 3;
exports.MSG_TYPE_NOTICE = 4;
exports.MSG_TYPE_FILE = 5;
exports.MSG_TYPE_CLOSE = 6;
exports.MSG_TYPE_IVR = 7;
exports.MSG_TYPE_MANAGER_ONLY = 8;
exports.MSG_TYPE_MANAGER_ONLY_RED = 9;
exports.MSG_TYPE_KEYWORD = 10;
exports.CONSULT_STATUS_NEW = 1;
exports.CONSULT_STATUS_WAITING = 2;
exports.CONSULT_STATUS_PROCEEDING = 3;
exports.CONSULT_STATUS_COMPLETE = 4;
exports.CONSULT_STATUS_REQ_CHANGE = 5;
exports.CONSULT_STATUS_REQ_REVIEW = 6;
exports.CONSULT_CHANNEL_NORMAL = 1;
exports.CONSULT_CHANNEL_IVR = 2;
exports.ROOM_TYPE_NORMAL = 1;
exports.ROOM_TYPE_TEAM = 2;
exports.ROOM_TYPE_GROUP = 3;
exports.ROOM_TYPE_PARTNER = 4;
|
(function() {
/**
* Throws exception with optional message if condition is false.
* @param {boolean} condition
* @param {string} [message=Assertion failed]
*/
function assert(condition, message) {
if (!condition) {
message = message || "Assertion failed";
if (typeof Error !== "undefined") {
throw new Error(message);
}
throw message;
}
}
function testEcs() {
var ecs = new ECS([]);
/**
* JUST ENTITIES AND COMPONENTS
*/
// Creating entities
var ent0 = ecs.createEntity();
// Adding components
var pos = {x: 0, y: 42, _componentType: 'Position'};
var graph = {shape: 'rect', color: {fill: 'blue', border: 'black'}, _componentType: 'Graphics'};
ecs.addComponent(pos, ent0);
ecs.addComponent(graph, ent0);
// Building entities
var ent1 = ecs.buildEntity({
Foo: {value: 'bar', _componentType: 'Foo'},
Position: {x: 0, y: 133, _componentType: 'Position'}
});
// Retrieving components
assert( ecs.getComponent('Graphics', ent0).color.fill === 'blue' );
assert( ecs.getComponent('NonExistingComponent', ent0) === null );
assert( ecs.getComponent('Foo', ent1) );
assert( ecs.getComponent('Position', ent1).y === 133 );
var comps = ecs.getComponents(['Position', 'Graphics'], ent0);
assert( comps.Position.x === 0 );
assert( comps.Graphics.color.fill === 'blue' );
var renderable = ecs.getAspect(Aspect.all(['Position', 'Graphics']), ent0);
assert( renderable.Position.x === 0 );
assert( renderable.Graphics.color.fill === 'blue' );
// Removing components
ecs.removeComponent('Position', ent1);
assert( ecs.getComponent('Position', ent1) === null );
// Checking
assert( ecs.hasComponent('Graphics', ent0) === true );
assert( ecs.hasComponent('NonExistingComponent', ent0) === false );
assert( ecs.hasComponent('Position', ent1) === false );
// Matching aspects
var renderables = Aspect.all(['Graphics', 'Position']);
assert( ecs.isMatchingAspect(renderables, ent0) );
assert( !ecs.isMatchingAspect(renderables, ent1) );
var fooOrPos = Aspect.any(['Foo', 'Position']);
assert( ecs.isMatchingAspect(fooOrPos, ent0) );
assert( ecs.isMatchingAspect(fooOrPos, ent1) );
var empty = Aspect.all([]);
assert( ecs.isMatchingAspect(fooOrPos, ent0) );
assert( ecs.isMatchingAspect(fooOrPos, ent1) );
// Removing entities
ecs.removeEntity(ent0);
assert( ecs.getComponent('Position', ent0) !== null );
assert( !ecs.isentity(ent0) );
ecs.removeEntity(ent1);
assert( ecs.getComponent('Foo', ent1) !== null );
ecs.doRemovals();
assert( ecs.getComponent('Position', ent0) === null );
assert( ecs.getComponent('Foo', ent1) === null );
assert( !ecs.isentity(ent0) );
/**
* SYSTEMS
*/
var TestSystem = (function(){
function TestSystem() {
}
TestSystem.prototype = {
constructor: TestSystem,
aspects: {
tests: Aspect.any(['Test1', 'Test2']),
foobars: Aspect.all(['TestFoo', 'TestBar']),
empty: Aspect.all(['NonExistingComponent']),
notfound: Aspect.all(['TestThatShouldNeverBeFound'])
},
name: 'TestSystem',
onInit: function(ecs) {
this.ecs = ecs;
},
onUpdate: function(dt, nodes) {
for (var i = 0; i < nodes.tests.length; ++i) {
var test1 = this.ecs.getComponent('Test1', nodes.tests[i]);
if (test1) test1._testVal = dt;
var test2 = this.ecs.getComponent('Test2', nodes.tests[i]);
if (test2) test2._testVal = dt;
}
for (var i = 0; i < nodes.foobars.length; ++i) {
//console.log(nodes);
//console.log(this.ecs.components);
//console.log('Has Foo: ', this.ecs.hasComponent('TestFoo', nodes.foobars[i]));
var foo = this.ecs.getComponent('TestFoo', nodes.foobars[i]);
foo._testVal = dt;
var bar = this.ecs.getComponent('TestBar', nodes.foobars[i]);
bar._testVal = dt;
}
//console.log('Tests found: ', nodes.tests.length);
//console.log('Foobars found: ', nodes.foobars.length);
//console.log('Empty is empty: ', nodes.empty.length === 0 && nodes.empty.length === nodes.notfound.length);
},
onEntityAdded: function(entity_id) {
//console.log('Entity added to test system: ', entity_id);
},
onEntityRemoved: function(entity_id) {
//console.log('Entity removed from test system: ', entity_id);
}
};
return TestSystem;
})();
// Init
var testval = Math.floor(Math.random() * Math.pow(2, 16)).toString();
var ecs = new ECS([ new TestSystem() ]);
// Adding entities
var t0 = ecs.buildEntity({Test1: {}, Test2: {}});
var t1 = ecs.buildEntity({Test1: {}});
var t2 = ecs.buildEntity({Test2: {}});
var fb0 = ecs.buildEntity({TestFoo: {}, TestBar: {}});
var f0 = ecs.buildEntity({TestFoo: {}});
var b0 = ecs.buildEntity({TestBar: {}});
var ft0 = ecs.buildEntity({TestFoo: {}, Test1: {}});
// Updating
function testSystemWithDt(dt) {
ecs.update('TestSystem', dt);
if (ecs.hasComponent('Test1', t0)) {
assert( ecs.getComponent('Test1', t0)._testVal === dt );
}
if (ecs.hasComponent('Test2', t0)) {
assert( ecs.getComponent('Test2', t0)._testVal === dt );
}
assert( ecs.getComponent('Test1', t1)._testVal === dt );
assert( ecs.getComponent('Test2', t2)._testVal === dt );
if (ecs.hasComponent('Test1', ft0)) {
assert( ecs.getComponent('Test1', ft0)._testVal === dt );
}
assert( ecs.getComponent('TestFoo', fb0)._testVal === dt );
assert( ecs.getComponent('TestBar', fb0)._testVal === dt );
assert( ecs.getComponent('TestFoo', f0)._testVal == null );
if (ecs.hasComponent('TestFoo', t0)) {
assert( ecs.getComponent('TestFoo', ft0)._testVal == null );
}
assert( ecs.getComponent('TestBar', b0)._testVal == null );
}
testSystemWithDt(1);
testSystemWithDt(100500);
testSystemWithDt(333);
testSystemWithDt(0);
// Removing entities
ecs.removeEntity(t0);
ecs.removeEntity(ft0);
ecs.doRemovals();
testSystemWithDt(1);
testSystemWithDt(100500);
testSystemWithDt(333);
testSystemWithDt(0);
// Adding components to entities
ecs.addComponent({_componentType: 'TestFoo'}, t1);
ecs.addComponent({_componentType: 'TestBar'}, t1);
testSystemWithDt(1);
assert( ecs.getComponent('TestFoo', t1)._testVal === 1 );
assert( ecs.getComponent('TestBar', t1)._testVal === 1 );
}
function testFsm() {
/**
* Coroutine-like FSMs
*/
var coroutines = new FsmManager();
function getMovementVector(ax, ay, bx, by) {
var dx = bx - ax;
var dy = by - ay;
var magnitude = Math.sqrt(dx*dx + dy*dy);
return {
x: dx / magnitude,
y: dy / magnitude
};
}
function getMovementStep(obj, destination, velocity) {
var vector = getMovementVector(obj.x, obj.y, destination.x, destination.y);
var sign_x = Math.sign(vector.x);
var sign_y = Math.sign(vector.y);
var abs_movement_dx = Math.abs(vector.x * velocity);
var abs_movement_dy = Math.abs(vector.y * velocity);
var abs_dx = Math.abs(destination.x - obj.x);
var abs_dy = Math.abs(destination.y - obj.y);
return {
x: Math.min(abs_movement_dx, abs_dx) * sign_x,
y: Math.min(abs_movement_dy, abs_dy) * sign_y
};
}
var moveTo = coroutines.wrap(Fsm({
enter: function(obj, x, y, velocity) {
this.velocity = velocity;
this.obj = obj;
this.destination = {x: x, y: y};
//console.log('Object movement begin...');
return this.states.update;
},
update: function(dt) {
//console.log(this);
var step = getMovementStep(this.obj, this.destination, this.velocity);
this.obj.x += step.x * dt;
this.obj.y += step.y * dt;
//console.log('Moving object by ', step, ' | Obj: ', this.obj);
if (this.obj.x === this.destination.x && this.obj.y === this.destination.y) {
return this.states.exit;
}
return this.states.update;
},
exit: function() {
//console.log('Object successfully moved to ', this.destination);
}
}));
var obj = {x: 0, y: 0};
moveTo(obj, 50, 100, 10);
coroutines.update(1);
assert(obj.x > 0);
assert(obj.x < 50);
for (var i = 0; i < 20; ++i) {
coroutines.update(1);
}
assert(Math.abs(obj.x - 50) < 0.0001);
assert(Math.abs(obj.y - 100) < 0.0001);
}
try {
testEcs();
testFsm();
} catch(e) {
console.log('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!');
console.log('! TESTS FAILED !')
console.log('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!');
}
})();
|
// --------------------------------- for Contact Us page------------------------------------
import { displayMessage } from "./script-shared.js";
const messageOnMessageSubmit = "Message was successfully sent";
const sendMessageButton = document.getElementById('sendMessageButton');
const contactForm = document.getElementById('contactForm');
// Send message form
sendMessageButton.addEventListener('click', function(e){
// Check validation for inputs of form
var forms = document.querySelectorAll(".needs-validation");
for (const form of forms) {
if (!form.checkValidity()) {
form.classList.add("was-validated");
return;
}
}
contactForm.reset();
contactForm.classList.remove('was-validated');
// Display confirmation message
displayMessage(messageOnMessageSubmit);
});
// Local Storage: get from Local Storage + display in navbar number of items in cart
let cartLS = [];
let productsInsideCart = document.getElementById('productsInsideCart');
window.onload = () => {
let myExistingCart = localStorage.getItem('myCart');
if(myExistingCart) {
const myCartObj = JSON.parse(myExistingCart);
myCartObj.forEach((item) => cartLS.push(item));
productsInsideCart.innerText = cartLS.length;
}
};
// Newsletter
let sendNewsletter = document.getElementById('sendNewsletter');
let inputEmailNewsletter = document.getElementById('inputEmailNewsletter')
sendNewsletter.addEventListener('click', () => {
inputEmailNewsletter.value = '';
});
|
/**
* Quink, Copyright (c) 2013-2014 IMD - International Institute for Management Development, Switzerland.
*
* This file is part of Quink.
*
* Quink is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Quink is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Quink. If not, see <http://www.gnu.org/licenses/>.
*/
/*global embedded_image_upload */
require([
'Underscore',
'jquery',
'ext/PluginAdapterContext'
], function (_, $, Context) {
'use strict';
//the iframe and the imageUploader component
var frame,
imageUploader;
/**
* Runs func every delay milliseconds until func returns true.
* (same technique as method draw and svg edit to wait till DOM is loaded)
*/
function until(func, delay) {
if (!func()) {
_.delay(until, delay, func, delay);
}
}
/**
* Called by function configureForEmbed to
* size the body of the iframe to match the body of the containing document. Anything else
* doesn't seem to work on iOS. Specifically trying to do it all in css using height 100%
* results in an iframe that's too tall for the viewport.
* The timeout is to allow the reflow to take place after resizing the iframe's body. The
* additional resize is needed on desktop Chrome which won't have resized the iframe to
* accommodate the changed body size. The additional iframe resize breaks the layout on iOS
* which will have already resized the frame.
*/
function sizeFrame() {
var reqHeight = window.innerHeight,
initialHeight = frame.height();
frame.contents().find('body').height(reqHeight);
setTimeout(function () {
if (frame.height() === initialHeight) {
frame.height(reqHeight);
}
}, 0);
}
/**
* Called from open() function (via underscore until) to
* set up the frame to be embedded
*
* If data is provided, load with the image so that it can be viewed and, optionally, changed
*/
function configureForEmbed(data) {
if (data) {
until(_.partial(imageUploader.setImage, data), 100);
}
sizeFrame();
setTimeout(function () {
frame.removeClass('qk_invisible');
Context.publish('opened');
}, 0);
return true;
}
/**
*
* remove the iframe containing the image uploader so that control can pass back to the main form
* called by functions save() and exit()
*
*/
function closePlugin(topic, data) {
frame.detach();
frame.addClass('qk_invisible');
window.removeEventListener('orientationchange', sizeFrame, false);
Context.publish(topic, data);
}
/**
* Callback
*
* set up in fetchMarkup call when opening the plugin.
* ("save" menu option -> save() method
*/
function save() {
imageUploader.getImageElementAsString()(function (data, error) {
if (error) {
console.log('save error: ' + error);
} else {
closePlugin('saved', data);
}
});
}
/**
* Callback
*
* set up in fetchMarkup call when opening the plugin.
* ("exit" menu option -> exit() method
*/
function exit() {
closePlugin('exited');
}
/**
* Callback
*
* established in fetchMarkup's Context.publish call
* "open plugin" -> open() method
* (fetchScript() completes before this call is issued)
*
* Loads the image upload DOM nodes into the document and configures it to run embedded.
*/
function open(data) {
frame.appendTo('body');
window.addEventListener('orientationchange', sizeFrame, false);
until(_.partial(configureForEmbed, data), 100);
}
//called by function fetchCss to
//get the markup that comprises the UI for this plugin
function fetchMarkup() {
var url = Context.adapterUrl('image-upload/ImageUploadEmbed.html');
$.get(url).done(function (data) {
frame = $(data);
imageUploader = new embedded_image_upload(frame[0]);
//associate methods in this object with the lifecycle callbacks for plugins
Context.publish('loaded', {
open: open,
save: save,
exit: exit,
dom: frame[0].parentNode
});
}).fail(function (jqxhr, textStatus, error) {
console.log('Failed to load image upload markup from: ' + url + '. ' + jqxhr.status + '. ' + error);
});
}
//called by function fetchScript to
//get the style sheet that comprises the UI for this plugin
function fetchCss() {
var url = Context.adapterUrl('image-upload/ImageUploadEmbed.css');
$.get(url).done(function (data) {
$('<style>').html(data).appendTo('head');
fetchMarkup();
}).fail(function (jqxhr, textStatus, error) {
console.log('Failed to load image upload css from: ' + url + '. ' + jqxhr.status + '. ' + error);
});
}
/**
* Get the scripts, then the css, which gets the html
*/
function fetchPluginArtifacts() {
var url = Context.pluginUrl('image-upload/embedapi.js');
$.getScript(url).done(function () {
fetchCss();
}).fail(function (jqxhr, textStatus, error) {
console.log('Failed to load embed-image-upload from: ' + url + '. ' + jqxhr.status + '. ' + error);
});
}
//immediately run fetchScript to set things up
fetchPluginArtifacts();
});
|
"use strict";
//get observation target data maxDate and minDate
function ajaxGetDateBound() {
loading("Calculating...");
//console.log(getFunction());
var URLs = "php/_dbqueryGetDate.php";
$.ajax({
url: URLs,
type: "GET",
data: {
data: JSON.stringify(observeTargetTmp),
dataset: ((getFunction() == FUNC_LIFEZONE) ? FUNC_LIFEZONE : FUNC_ACTIVATION),
},
dataType: 'json',
success: function (json) {
//console.log(json);
//clone
var minData = json.minDate,
maxData = json.maxDate;
console.log("ajaxGetDateBound: minData:" + minData + "/maxData:" + maxData);
//datepicker setting
$("#from").datepicker("setDate", new Date(minData));
$("#to").datepicker("setDate", new Date(maxData));
onChangeTrigger();
loadingDismiss();
},
error: function (xhr, ajaxOptions, thrownError) {
alert("ajaxGetDateBound:" + xhr.status);
alert(thrownError);
}
});
}
//fetch map value with regionJson existed
function ajaxFetchMapValue(hasComparison, isComparison) {
var mapObj = (isComparison) ? comparisonMap : firstMap;
//console.log("ajaxFetchMapValue "+((isComparison)?"comparisonMap":"firstMap")+" Start:"+getCurrentTime());
// console.log(JSON.stringify(observeLoc));
// console.log(JSON.stringify(observeDistBranch));
// console.log(JSON.stringify(observeDistName));
// console.log(JSON.stringify(observeTarget));
// console.log(mapObj.fromFormatStr);
// console.log(mapObj.toFormatStr);
// console.log(((getFunction()==FUNC_LIFEZONE) ? FUNC_LIFEZONE : FUNC_ACTIVATION));
//
// console.log(JSON.stringify(observeSpec.color));
// console.log(JSON.stringify(observeSpec.cpu));
// console.log(JSON.stringify(observeSpec.rear_camera));
// console.log(JSON.stringify(observeSpec.front_camera));
// console.log(JSON.stringify(permission));
var URLs = "php/_dbqueryCntGroupByISO.php";
$.ajax({
url: URLs,
data: {
color: JSON.stringify(observeSpec.color),
cpu: JSON.stringify(observeSpec.cpu),
rearCamera: JSON.stringify(observeSpec.rear_camera),
frontCamera: JSON.stringify(observeSpec.front_camera),
iso: JSON.stringify(observeLoc),
distBranch: JSON.stringify(observeDistBranch),
onlineDist: JSON.stringify(observeDistName),
data: JSON.stringify(observeTarget),
from: mapObj.fromFormatStr,
to: mapObj.toFormatStr,
dataset: ((getFunction() == FUNC_LIFEZONE) ? FUNC_LIFEZONE : FUNC_ACTIVATION),
permission: JSON.stringify(permission),
},
type: "POST",
dataType: 'json',
success: function (json) {
//clone
console.log(((isComparison) ? "comparisonMap" : "firstMap") + "---JSON");
//console.log(json);
if (json.length == 0) {
showToast("Empty Data During This Date Time Period");
mapObj.isEmpty = true;
} else {
mapObj.isEmpty = false;
}
if (mapObj.countryMapping && mapObj.countryMapping.length != 0)
mapObj.countryMapping.length = 0;
mapObj.countryMapping = json.slice();
// console.log(mapObj.countryMapping);
//piechart
//updateTrendChart(isComparison);
//max count setting
mapObj.setMaxMin();
mapObj.updateMapProperties();
mapObj.mapDataLoad();
//updateMapPoly(isComparison);
mapObj.updateLegend();
if (mapObj.info == null) {
mapObj.setInfo();
}
mapObj.info.update();
mapObj.setHighlightFeature();
//free
mapObj.countryMapping = null;
//mapObj.jsonData=null;
// console.log(mapObj.jsonData);
if (hasComparison) {
comparisonMap.currentRegionIso = observeLoc.slice();
ajaxFetchMapValue(false, !isComparison);
} else {
if (needToLoadTwoModeSameTime) {
loadingRegionFinish = true;
if (loadingRegionFinish && loadingMarkerFinish) {
needToLoadTwoModeSameTime = false;
loadingDismiss();
loadingRegionFinish = false;
loadingMarkerFinish = false;
}
} else {
loadingDismiss();
}
}
//console.log("ajaxFetchMapValue "+((isComparison)?"comparisonMap":"firstMap")+" End:"+getCurrentTime());
},
error: function (xhr, ajaxOptions, thrownError) {
alert("ajaxFetchMapValue:" + xhr.status);
alert(thrownError);
}
});
}
//fetch map value without regionJson existed
//need to query regionJson Data first
//then fetch map value
function ajaxExtractMap(hasComparison, callback, args) {
//method 1
//extract from topojson file
//REF : http://mapshaper.org/
//http://blog.webkid.io/maps-with-leaflet-and-topojson/
//---------------------------------------------------------------------------------------
console.log("ajaxExtractMap Start:" + getCurrentTime());
firstMap.cleanMap();
if (hasComparison) {
comparisonMap.cleanMap();
}
firstMap.currentRegionIso = observeLoc.slice();
//console.log(JSON.stringify(observeLoc));
firstMap.jsonData = {
"type": "FeatureCollection",
"features": [],
};
var urls = [];
if (!isL1(firstMap)) {
$.each(firstMap.currentRegionIso, function (index, loc) {
urls.push("php/geojson/topo/l2/" + loc + ".json");
});
} else {
$.each(firstMap.currentRegionIso, function (index, loc) {
urls.push("php/geojson/topo/l1/" + loc + ".json");
});
}
var jxhr = [];
$.each(urls, function (i, url) {
jxhr.push(
$.getJSON(url, function (json) {
for (var key in json.objects) {
//console.log(key);
//console.log(topojson.feature(json, json.objects[key]).features);
$.each(topojson.feature(json, json.objects[key]).features, function (index, regionjson) {
regionjson.properties["isComparison"] = false;
regionjson.properties["boundBox"] = boundInit(regionjson.geometry);
firstMap.jsonData.features.push(regionjson);
});
}
})
);
});
// console.log(firstMap.jsonData);
$.when.apply($, jxhr).done(function () {
if (hasComparison) {
comparisonMap.jsonData = {
"type": "FeatureCollection",
"features": [],
};
comparisonMap.jsonData.features = JSON.parse(JSON.stringify(firstMap.jsonData.features));
for (var i = 0; i < comparisonMap.jsonData.features.length; ++i) {
comparisonMap.jsonData.features[i].properties.isComparison = true;
comparisonMap.jsonData.features[i].properties.boundBox = boundInit(comparisonMap.jsonData.features[i].geometry);
}
}
//ajaxFetchMapValue(hasComparison,false);
if (callback) {
// console.log("callback");
callback.apply(this, args);
}
console.log("ajaxExtractMap End:" + getCurrentTime());
});
}
//fetch map value with regionJson existed
function ajaxFetchParallelValue() {
var mapObj = firstMap;
var URLs = "php/_dbqueryGetParallelValue.php";
// console.log(JSON.stringify(observeSpec.color));
$.ajax({
url: URLs,
data: {
color: JSON.stringify(observeSpec.color),
cpu: JSON.stringify(observeSpec.cpu),
rearCamera: JSON.stringify(observeSpec.rear_camera),
frontCamera: JSON.stringify(observeSpec.front_camera),
data: JSON.stringify(observeTarget),
permission: JSON.stringify(permission),
},
type: "POST",
dataType: 'json',
success: function (json) {
//clone
console.log("firstMap---JSON");
if (json.length == 0) {
showToast("Empty Data During This Date Time Period");
mapObj.isEmpty = true;
} else {
mapObj.isEmpty = false;
}
if (mapObj.countryMapping && mapObj.countryMapping.length != 0)
mapObj.countryMapping.length = 0;
mapObj.countryMapping = json;
mapObj.updateParallelMapProperties();
mapObj.mapDataLoad();
mapObj.updateLegend();
if (mapObj.info == null) {
mapObj.setInfo();
}
mapObj.info.update();
mapObj.setHighlightFeature();
//free
// mapObj.countryMapping = null;
mapObj.zoomToSelectedLocation();
loadingDismiss();
},
error: function (xhr, ajaxOptions, thrownError) {
alert("ajaxFetchParallelValue:" + xhr.status);
alert(thrownError);
}
});
}
function ajaxExtractParallelMap(callback) {
console.log("ajaxExtractParallelMap Start:" + getCurrentTime());
firstMap.cleanMap();
firstMap.currentRegionIso = observeLoc.slice();
// console.log(observeLoc);
firstMap.jsonData = {
"type": "FeatureCollection",
"features": [],
};
var url = "php/geojson/topo/world.json";
var jxhr = [];
jxhr.push(
$.getJSON(url, function (json) {
for (var key in json.objects) {
$.each(topojson.feature(json, json.objects[key]).features, function (index, regionjson) {
if (isInArray(observeLoc, regionjson.properties.ISO_A3)) {
regionjson.properties["boundBox"] = boundInit(regionjson.geometry);
firstMap.jsonData.features.push(regionjson);
}
});
}
})
);
$.when.apply($, jxhr).done(function () {
if (callback) {
callback.apply(this);
}
console.log("ajaxExtractParallelMap End:" + getCurrentTime());
});
}
function ajaxParallelChart(iso, exportFileType) {
var URLs = "php/_dbqueryGetParallelTrend.php";
$.ajax({
url: URLs,
data: {
color: JSON.stringify(observeSpec.color),
cpu: JSON.stringify(observeSpec.cpu),
rearCamera: JSON.stringify(observeSpec.rear_camera),
frontCamera: JSON.stringify(observeSpec.front_camera),
data: JSON.stringify(observeTarget),
iso: iso,
permission: JSON.stringify(permission),
exportFileType: exportFileType,
},
type: "POST",
dataType: 'json',
success: function (json) {
// console.log(json);
trendParallel.updateParallelChart(json, iso);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
function ajaxParallelExport(exportFileType) {
var URLs = "php/_dbqueryGetParallelExport.php";
$.ajax({
url: URLs,
data: {
color: JSON.stringify(observeSpec.color),
cpu: JSON.stringify(observeSpec.cpu),
rearCamera: JSON.stringify(observeSpec.rear_camera),
frontCamera: JSON.stringify(observeSpec.front_camera),
data: JSON.stringify(observeTarget),
iso: JSON.stringify(observeLoc),
permission: JSON.stringify(permission),
exportFileType: exportFileType,
},
type: "POST",
dataType: 'text',
success: function (text) {
var filename = exportFileType + "_report";
tableExportToExcel(text, filename);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
function ajaxGetMarker() {
var mapObj = firstMap;
console.log("ajaxGetMarker Start:" + getCurrentTime());
var URLs = "php/_dbqueryGetMarker_.php";
$.ajax({
url: URLs,
data: {
color: JSON.stringify(observeSpec.color),
cpu: JSON.stringify(observeSpec.cpu),
rearCamera: JSON.stringify(observeSpec.rear_camera),
frontCamera: JSON.stringify(observeSpec.front_camera),
iso: JSON.stringify(observeLoc),
distBranch: JSON.stringify(observeDistBranch),
onlineDist: JSON.stringify(observeDistName),
data: JSON.stringify(observeTarget),
from: mapObj.fromFormatStr,
to: mapObj.toFormatStr,
dataset: ((getFunction() == FUNC_LIFEZONE) ? FUNC_LIFEZONE : FUNC_ACTIVATION),
permission: JSON.stringify(permission),
},
type: "POST",
dataType: 'json',
success: function (json) {
//clone
console.log("ajaxGetMarker End:" + getCurrentTime());
if (json.length == 0) {
showToast("Empty Data During This Date Time Period");
mapObj.isEmpty = true;
//return
} else {
mapObj.isEmpty = false;
}
console.log("addLayer Start:" + getCurrentTime());
addPruneCluster(json);
console.log("addLayer End:" + getCurrentTime());
mapObj.info.update();
if (needToLoadTwoModeSameTime) {
loadingMarkerFinish = true;
if (loadingRegionFinish && loadingMarkerFinish) {
needToLoadTwoModeSameTime = false;
loadingDismiss();
loadingRegionFinish = false;
loadingMarkerFinish = false;
}
} else {
loadingDismiss();
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert("ajaxGetMarker:" + xhr.status);
alert(thrownError);
}
});
}
function ajaxAddBookmark(stringifyObserveTarget, stringifyObserveLoc, stringifyObserveSpec, activeMode, dataset) {
// console.log(dataset);
$.ajax({
type: 'GET',
url: 'php/_dbqueryAddBookmark.php',
data: {
user: account,
title: $('#bookmark_title').val(),
desc: $('#bookmark_description').val(),
stringifyObserveTarget: stringifyObserveTarget,
stringifyObserveLoc: stringifyObserveLoc,
stringifyObserveSpec: stringifyObserveSpec,
activeMode: activeMode,
dataset: ((dataset == FUNC_DISTBRANCH) ? FUNC_ACTIVATION : dataset),
},
dataType: 'json',
success: function (response) {
console.log("bookmark Saved success");
showToast("Bookmark is saved");
ajaxLoadBookmark();
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
function ajaxLoadBookmark() {
$.ajax({
type: 'GET',
url: 'php/_dbqueryLoadBookmark.php',
data: {
user: account,
},
dataType: 'json',
success: function (json) {
if (json) {
bookmarkList = jQuery.extend(json, {});
// console.log(bookmarkList);
//createBookmarkPopup();
}
},
// error: function(jqXHR, textStatus, errorThrown) {},
});
}
function ajaxRemoveBookmark(idOfBookmarkDel) {
$.ajax({
type: 'GET',
url: 'php/_dbqueryDeleteBookmark.php',
dataType: 'json',
data: {
user: account,
index: JSON.stringify(idOfBookmarkDel),
},
success: function (json) {
// bookmarkList=[];
ajaxLoadBookmark();
// console.log(bookmarkList);
showToast("Bookmark is deleted");
},
error: function (jqXHR, textStatus, errorThrown) {},
});
}
function ajaxTrendOfBranchChart(mapObj, branchName) {
if (linechart != null) {
linechart.destroy();
}
// console.log(FUNC_ACTIVATION);
// console.log(JSON.stringify(observeSpec.color));
// console.log(JSON.stringify(observeSpec.cpu));
// console.log(JSON.stringify(observeSpec.rear_camera));
// console.log(JSON.stringify(observeSpec.front_camera));
// console.log(JSON.stringify(observeTarget));
// console.log(mapObj.fromFormatStr);
// console.log(mapObj.toFormatStr);
// console.log(branchName);
// console.log(JSON.stringify(observeLoc));
// console.log(JSON.stringify(permission));
var URLs = "php/_dbqueryGetTrendOfBranch.php";
$.ajax({
url: URLs,
data: {
dataset: FUNC_ACTIVATION,
color: JSON.stringify(observeSpec.color),
cpu: JSON.stringify(observeSpec.cpu),
rearCamera: JSON.stringify(observeSpec.rear_camera),
frontCamera: JSON.stringify(observeSpec.front_camera),
data: JSON.stringify(observeTarget),
from: mapObj.fromFormatStr,
to: mapObj.toFormatStr,
branch: branchName,
iso: JSON.stringify(observeLoc),
permission: JSON.stringify(permission),
},
type: "POST",
dataType: 'json',
success: function (json) {
console.log(json);
//empty data set
updateBranchChart(json, branchName);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
function ajaxRegionChart(countryID, iso, displayname, displaynum, mapObj) {
if (linechart != null) {
linechart.destroy();
}
var URLs = "php/_dbquerySingleISOCnt.php";
$.ajax({
url: URLs,
data: {
dataset: ((getFunction() == FUNC_LIFEZONE) ? FUNC_LIFEZONE : FUNC_ACTIVATION),
color: JSON.stringify(observeSpec.color),
cpu: JSON.stringify(observeSpec.cpu),
rearCamera: JSON.stringify(observeSpec.rear_camera),
frontCamera: JSON.stringify(observeSpec.front_camera),
data: JSON.stringify(observeTarget),
from: mapObj.fromFormatStr,
to: mapObj.toFormatStr,
countryID: countryID,
isL1: isL1(firstMap),
iso: iso,
distBranch: JSON.stringify(observeDistBranch),
onlineDist: JSON.stringify(observeDistName),
permission: JSON.stringify(permission),
},
type: "POST",
dataType: 'json',
success: function (json) {
// console.log(json);
//empty data set
updateRegionChart(json, displayname, displaynum);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
function ajaxTrendChart(mapObj) {
var URLs = "php/_dbqueryGetTrend.php";
$.post(URLs, {
color: JSON.stringify(observeSpec.color),
cpu: JSON.stringify(observeSpec.cpu),
rearCamera: JSON.stringify(observeSpec.rear_camera),
frontCamera: JSON.stringify(observeSpec.front_camera),
iso: JSON.stringify(observeLoc),
distBranch: JSON.stringify(observeDistBranch),
onlineDist: JSON.stringify(observeDistName),
data: JSON.stringify(observeTarget),
from: mapObj.fromFormatStr,
to: mapObj.toFormatStr,
dataset: ((getFunction() == FUNC_LIFEZONE) ? FUNC_LIFEZONE : FUNC_ACTIVATION),
permission: JSON.stringify(permission),
},
function (json) {
// console.log(json);
updateTrendChart(json);
},
'json'
);
}
function ajaxGetDeviceSpec(devices, checkOption) {
if (specDeviceTmp.length == 0) {
allSpec = {};
checkboxSpecInit();
} else {
$.ajax({
type: 'GET',
url: 'php/_dbqueryGetDeviceSpec.php',
dataType: 'json',
data: {
device_name: JSON.stringify(devices)
},
success: function (json) {
allSpec = json;
$.each(allSpec, function (name, spec) {
spec.sort;
});
checkboxSpecInit(checkOption);
},
error: function (jqXHR, textStatus, errorThrown) {},
});
}
}
function ajaxFetchTableValue(isDiff) {
// var mapObj = (isComparison) ? comparisonMap : firstMap;
//console.log("ajaxFetchMapValue "+((isComparison)?"comparisonMap":"firstMap")+" Start:"+getCurrentTime());
var URLs = "php/_dbqueryGetTableContent.php";
return $.ajax({
url: URLs,
data: {
color: JSON.stringify(observeSpec.color),
cpu: JSON.stringify(observeSpec.cpu),
rearCamera: JSON.stringify(observeSpec.rear_camera),
frontCamera: JSON.stringify(observeSpec.front_camera),
iso: JSON.stringify(observeLoc),
distBranch: JSON.stringify(observeDistBranch),
onlineDist: JSON.stringify(observeDistName),
data: JSON.stringify(observeTarget),
from: firstMap.fromFormatStr,
to: firstMap.toFormatStr,
dataset: ((getFunction() == FUNC_LIFEZONE) ? FUNC_LIFEZONE : FUNC_ACTIVATION),
permission: JSON.stringify(permission),
},
type: "POST",
dataType: 'json',
success: function (json) {
var mapObj = {};
if (isDiff) {
console.log("isDiff");
mapObj.jsonData = {
"type": "FeatureCollection",
"features": [],
};
var urls = [];
if (observeLoc.length == 1) {
$.each(observeLoc, function (index, loc) {
urls.push("php/geojson/topo/l2/" + loc + ".json");
});
} else if (observeLoc.length > 1) {
$.each(observeLoc, function (index, loc) {
urls.push("php/geojson/topo/l1/" + loc + ".json");
});
}
var jxhr = [];
$.each(urls, function (i, url) {
jxhr.push(
$.getJSON(url, function (json) {
for (var key in json.objects) {
console.log(key + " loading...");
$.each(topojson.feature(json, json.objects[key]).features, function (index, regionjson) {
mapObj.jsonData.features.push({
properties: regionjson.properties,
});
});
}
})
);
});
$.when.apply($, jxhr).done(function () {
createTable(isDiff, json, mapObj);
loadingDismiss();
});
} else {
createTable(isDiff, json);
loadingDismiss();
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert("ajaxFetchTableValue:" + xhr.status);
alert(thrownError);
}
});
}
//Ajax to get dealer's geoJson of select countries
function ajaxGetDealer() {
$.ajax({
type: 'GET',
url: 'php/_dbqueryGetDealer.php',
dataType: 'json',
data: {
country: JSON.stringify(observeLocFullName)
},
success: function (json) {
allDealer = json;
json = null;
dealerLayer();
},
error: function (jqXHR, textStatus, errorThrown) {},
});
}
//Ajax to get SC's geoJson of select countries
function ajaxGetSC() {
$.ajax({
type: 'GET',
url: 'php/_dbqueryGetSC.php',
dataType: 'json',
data: {
country: JSON.stringify(observeLoc),
products: JSON.stringify(defaultProductList)
},
success: function (json) {
allSC = json;
json = null;
scLayer();
},
error: function (jqXHR, textStatus, errorThrown) {},
});
}
function ajaxLoadBranchDist() {
$.ajax({
type: 'GET',
url: 'php/_dbqueryLoadDistBranch.php',
dataType: 'json',
success: function (json) {
//order by dist
distBranch.length = 0;
var currentDist = null;
var branchList = [];
var first = true;
for (var i in json.channel) {
var dist = json.channel[i].dist;
var branch = json.channel[i].branch;
if (dist != currentDist) {
if (!first) {
distBranch.push({
dist: currentDist,
branch: branchList.slice()
});
branchList.length = 0;
currentDist = dist;
} else {
first = false;
currentDist = dist;
}
}
branchList.push(branch);
}
//last one
distBranch.push({
dist: currentDist,
branch: branchList.slice()
});
// console.log(distBranch);
//sort order by branch
json.channel.sort(function (a, b) {
return (a.branch > b.branch) ? 1 : ((b.branch > a.branch) ? -1 :
(a.dist > b.dist) ? 1 : ((b.dist > a.dist) ? -1 : 0));
});
var currentBranch = null;
var DistList = [];
var first = true;
for (var i in json.channel) {
var dist = json.channel[i].dist;
var branch = json.channel[i].branch;
if (branch != currentBranch) {
if (!first) {
branchDist.push({
branch: currentBranch,
dist: DistList.slice()
});
DistList.length = 0;
currentBranch = branch;
} else {
first = false;
currentBranch = branch;
}
}
DistList.push(dist);
}
//last one
branchDist.push({
branch: currentBranch,
dist: DistList.slice()
});
//order by online dist
onlineDist.length = 0;
var currentOnline = null;
var distList = [];
var first = true;
for (var i in json.online) {
var online = json.online[i].online_dist;
var dist = json.online[i].dist;
if (online != currentOnline) {
if (!first) {
onlineDist.push({
online_dist: currentOnline,
dist: distList.slice()
});
distList.length = 0;
currentOnline = online;
} else {
first = false;
currentOnline = online;
}
}
distList.push(dist);
}
//last one
onlineDist.push({
online_dist: currentOnline,
dist: distList.slice()
});
createDistBranchCheckBox();
},
})
}
function ajaxGetBranchObject(callback) {
if (observeBranchName.length == 0) {
allBranchObject = [];
callback();
} else {
$.ajax({
type: 'GET',
url: 'php/_dbqueryGetBranchObject.php',
async: "false",
dataType: 'json',
data: {
iso: JSON.stringify(observeLoc),
branchName: JSON.stringify(observeBranchName)
},
success: function (json) {
console.log(json);
allBranchObject = json.union;
delete json.union;
allHighlighBranch = json;
json = null;
// console.log(allBranchObject);
// console.log(allHighlighBranch);
callback();
},
error: function (jqXHR, textStatus, errorThrown) {
alert("ajaxGetBranchObject:" + jqXHR.status);
alert(errorThrown);
},
});
}
}
function ajaxSaveLog() {
//device filter
var observeTargetStr = '';
if (observeTarget.length == 1 && observeTarget[0].datatype == 'all') {
observeTargetStr += '[all]';
} else {
for (var i in observeTarget) {
var type = observeTarget[i].datatype;
observeTargetStr += '[' + observeTarget[i][type] + ']';
}
}
//model filter
var model = getFilterModel();
var modelStr = '';
for (var i in model) {
var type = model[i].datatype;
modelStr += '[' + model[i] + ']';
}
//loc filter
var observeLocStr = '';
for (var i in observeLoc) {
observeLocStr += '[' + observeLoc[i] + ']';
}
//observation time
var dateStr = '[' + firstMap.fromFormatStr + '][' + firstMap.toFormatStr + ']';
//filter all content
var filter_content = {
observeTarget: observeTarget,
observeLoc: observeLoc,
observeSpec: observeSpec,
};
if (observeDistBranch.length > 0)
filter_content['observeDistBranch'] = observeDistBranch;
//current time
var date = new Date();
var dformat = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate();
$.ajax({
type: 'POST',
url: 'php/_dbquerySaveLog.php',
dataType: 'json',
data: {
date: dformat,
username: account,
filter_device: observeTargetStr,
filter_model: modelStr,
filter_country: observeLocStr,
filter_date: dateStr,
filter_content: JSON.stringify(filter_content),
dataset: getFunction(),
},
success: function (json) {
console.log("log saved");
}
});
}
function ajaxGetGapData(callback) {
// console.log(JSON.stringify(observeSpec.color));
// console.log(JSON.stringify(observeSpec.cpu));
// console.log(JSON.stringify(observeSpec.rear_camera));
// console.log(JSON.stringify(observeSpec.front_camera));
//
// console.log(JSON.stringify(observeLoc));
// console.log(JSON.stringify(observeTarget));
// console.log(firstMap.fromFormatStr);
// console.log(firstMap.toFormatStr);
// console.log(((getFunction()==FUNC_LIFEZONE) ? FUNC_LIFEZONE : FUNC_ACTIVATION));
// console.log(JSON.stringify(permission));
$.ajax({
type: 'GET',
url: 'php/_dbqueryGetGap.php',
dataType: 'json',
data: {
color: JSON.stringify(observeSpec.color),
cpu: JSON.stringify(observeSpec.cpu),
rearCamera: JSON.stringify(observeSpec.rear_camera),
frontCamera: JSON.stringify(observeSpec.front_camera),
iso: JSON.stringify(observeLoc),
data: JSON.stringify(observeTarget),
from: firstMap.fromFormatStr,
to: firstMap.toFormatStr,
dataset: FUNC_ACTIVATION,
permission: JSON.stringify(permission),
},
success: function (json) {
// console.log(json);
// setModeOn(MODE_GAP);
allBranchGap = json;
if (callback)
callback();
},
error: function (xhr, ajaxOptions, thrownError) {
alert("ajaxGetGapData:" + xhr.status);
alert(thrownError);
}
});
}
function ajaxGetGapExport(groupBy) {
loading('File creating...');
console.log(currentPointingBranch);
$.post(
"php/_dbqueryGetGapExport.php", {
color: JSON.stringify(observeSpec.color),
cpu: JSON.stringify(observeSpec.cpu),
rearCamera: JSON.stringify(observeSpec.rear_camera),
frontCamera: JSON.stringify(observeSpec.front_camera),
iso: JSON.stringify(observeLoc),
data: JSON.stringify(observeTarget),
from: firstMap.fromFormatStr,
to: firstMap.toFormatStr,
dataset: ((getFunction() == FUNC_LIFEZONE) ? FUNC_LIFEZONE : FUNC_ACTIVATION),
distBranch: JSON.stringify(observeDistBranch),
groupBy: groupBy,
branch: (isNowBranchTrend ? currentPointingBranch : null),
permission: JSON.stringify(permission),
},
function (text) {
// console.log(text);
var filename = '[' + observeLoc[0] + '][' + firstMap.fromFormatStr + ']-[' + firstMap.toFormatStr + '][Group By ' + groupBy + ']' + "_GapReport";
tableExportToExcel(text, filename);
},
'text'
);
}
function ajaxGetHeatMap() {
// console.log(JSON.stringify(observeSpec.color));
// console.log(JSON.stringify(observeSpec.cpu));
// console.log(JSON.stringify(observeSpec.rear_camera));
// console.log(JSON.stringify(observeSpec.front_camera));
//
// console.log(JSON.stringify(observeLoc));
// console.log(JSON.stringify(observeDistBranch));
// console.log(JSON.stringify(observeDistName));
// console.log(JSON.stringify(lifeZoneTime));
// console.log(JSON.stringify(observeTarget));
// console.log(JSON.stringify(permission));
loading("Data loading...");
$.ajax({
url: "php/_dbqueryGetLifezoneData.php",
type: "POST",
data: {
color: JSON.stringify(observeSpec.color),
cpu: JSON.stringify(observeSpec.cpu),
rearCamera: JSON.stringify(observeSpec.rear_camera),
frontCamera: JSON.stringify(observeSpec.front_camera),
iso: JSON.stringify(observeLoc),
distBranch: JSON.stringify(observeDistBranch),
onlineDist: JSON.stringify(observeDistName),
time: JSON.stringify(lifeZoneTime),
data: JSON.stringify(observeTarget),
permission: JSON.stringify(permission),
},
dataType: 'json',
success: function (json) {
// console.log(json);
//empty data return
if (json[lifeZoneTime['week']][lifeZoneTime['time']].length == 0)
showToast("Empty Data");
if ($.isEmptyObject(heatmapLayer)) {
addHeatMap(json);
} else {
changeHeatData(json);
}
loadingDismiss();
},
error: function (xhr, ajaxOptions, thrownError) {
alert("ajaxGetHeatMap:" + xhr.status);
alert(thrownError);
}
});
}
function ajaxGetSQMarker() {
loading("Data loading...");
$.ajax({
url: "php/_dbqueryGetSQDevice.php",
type: "POST",
data: {
iso: JSON.stringify(observeLoc),
data: JSON.stringify(observeTarget),
view: currentView,
category: 1,
permission: JSON.stringify(permission),
},
dataType: 'json',
success: function (json) {
setSQMarker(json);
json = null;
loadingDismiss();
},
error: function (xhr, ajaxOptions, thrownError) {
alert("ajaxGetHeatMap:" + xhr.status);
alert(thrownError);
}
});
}
function ajaxGetSQRegion() {
loading("Data loading...");
$.ajax({
url: "php/_dbqueryGetSQRegion.php",
type: "POST",
data: {
color: JSON.stringify(observeSpec.color),
cpu: JSON.stringify(observeSpec.cpu),
rearCamera: JSON.stringify(observeSpec.rear_camera),
frontCamera: JSON.stringify(observeSpec.front_camera),
iso: JSON.stringify(observeLoc),
data: JSON.stringify(observeTarget),
view: currentView,
category: 1,
permission: JSON.stringify(permission),
},
dataType: 'json',
success: function (json) {
setSQRegion(json);
json = null;
loadingDismiss();
},
error: function (xhr, ajaxOptions, thrownError) {
alert("ajaxGetHeatMap:" + xhr.status);
alert(thrownError);
}
});
}
function ajaxGetActivationDistribution() {
var mapObj = firstMap;
var URLs = "php/_dbqueryGetActivationDistribution.php";
$.ajax({
url: URLs,
data: {
color: JSON.stringify(observeSpec.color),
cpu: JSON.stringify(observeSpec.cpu),
rearCamera: JSON.stringify(observeSpec.rear_camera),
frontCamera: JSON.stringify(observeSpec.front_camera),
iso: JSON.stringify(observeLoc),
data: JSON.stringify(observeTarget),
from: mapObj.fromFormatStr,
to: mapObj.toFormatStr,
permission: JSON.stringify(permission),
distributedBy: currentDistributedBy,
distributedLevel: currentDistributedLevel,
},
type: "POST",
dataType: 'json',
success: function (json) {
activationDistribution.showChart(json);
// console.log(json);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("ajaxGetActivationDistribution:" + xhr.status);
alert(thrownError);
}
});
}
function ajaxGetActivationTrend() {
var mapObj = firstMap;
var URLs = "php/_dbqueryGetActivationTrend.php";
$.ajax({
url: URLs,
data: {
color: JSON.stringify(observeSpec.color),
cpu: JSON.stringify(observeSpec.cpu),
rearCamera: JSON.stringify(observeSpec.rear_camera),
frontCamera: JSON.stringify(observeSpec.front_camera),
iso: JSON.stringify(observeLoc),
data: JSON.stringify(observeTarget),
from: mapObj.fromFormatStr,
to: mapObj.toFormatStr,
permission: JSON.stringify(permission),
trendBy: currentTrendBy,
trendLevel: currentTrendLevel,
trendTime: currentTrendTimescale,
},
type: "POST",
dataType: 'json',
success: function (json) {
// activationDistribution.showChart(json);
console.log(json);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("ajaxGetActivationDistribution:" + xhr.status);
alert(thrownError);
}
});
}
|
/**
* Date Author Des
*----------------------------------------------
* 2018/5/18 gongtiexin 登陆组件
* */
import React, { Component } from 'react';
import { inject, observer } from 'mobx-react';
import { Link } from 'react-router-dom';
import PropTypes from 'prop-types';
import { Button, Checkbox, Form, Icon, Input } from 'antd';
import Particles from 'particlesjs';
import './index.less';
import { browserRedirect } from '../../utils/constants';
import { NAMESPACE_MANAGEMENT_LIST } from '../../router/constants';
const { Item: FormItem, create } = Form;
@create()
@inject(({ store: { userStore } }) => ({ userStore }))
@observer
export default class Login extends Component {
state = {
loading: false,
};
particles = null;
static propTypes = {
form: PropTypes.object.isRequired,
userStore: PropTypes.object.isRequired,
history: PropTypes.object.isRequired,
};
componentDidMount() {
this.particlesInit();
}
componentWillUnmount() {
this.particles?.destroy();
}
particlesInit = () => {
if (browserRedirect() === 'pc') {
this.particles = Particles.init({
selector: '.particles-background',
connectParticles: true,
color: '#999999',
maxParticles: 150,
});
}
};
handleSubmit = e => {
e.preventDefault();
this.props.form.validateFields((err, values) => {
if (!err) {
console.log('Received values of form: ', values);
this.setState({ loading: true });
this.props.userStore
.login(values)
.then(() => this.props.history.push(NAMESPACE_MANAGEMENT_LIST))
.finally(() => this.setState({ loading: false }));
}
});
};
render() {
const { getFieldDecorator } = this.props.form;
const { loading } = this.state;
return (
<div id="login">
<canvas className="particles-background" />
<div className="login-box">
<div className="message">Fusion DiscoveryX</div>
<div id="darkbannerwrap" />
<Form onSubmit={this.handleSubmit} className="login-form">
<FormItem>
{getFieldDecorator('account', {
rules: [{ required: true, message: '请输入您的用户名!' }],
})(
<Input
prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />}
placeholder="用户名"
className="login-form-input"
/>,
)}
</FormItem>
<FormItem>
{getFieldDecorator('password', {
rules: [{ required: true, message: '请输入您的密码!' }],
})(
<Input
prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />}
type="password"
placeholder="密码"
className="login-form-input"
/>,
)}
</FormItem>
<FormItem>
{getFieldDecorator('remember', {
valuePropName: 'checked',
initialValue: true,
})(<Checkbox>记住密码</Checkbox>)}
<Link className="login-form-forgot" to="/#">
忘记密码
</Link>
<Button
loading={loading}
type="primary"
htmlType="submit"
className="login-form-button"
>
登录
</Button>
或者
<Link to="/#">现在去注册!</Link>
</FormItem>
</Form>
</div>
</div>
);
}
}
|
'use strict'
const appEventEmitter = require('../appEventEmitter');
const liveLogins = require('../notifications/liveLogins');
//Dummy impl; ideally it will read a que and emit event for a specific user
setInterval(() => {
let allLiveLogins = liveLogins.getAll();
for(let i = 0; i < allLiveLogins.length; i++){
if(allLiveLogins[i].userId <= 5){
appEventEmitter.emit('ready', allLiveLogins[i].userId);
} else {
appEventEmitter.emit('preview', allLiveLogins[i].userId);
}
}
}, 5000);
|
var structAnsiAttr =
[
[ "attr", "structAnsiAttr.html#a6f96f39ebfeebf2ee366e18f4329eb2f", null ],
[ "fg", "structAnsiAttr.html#adb4ab54c8f829bd8cfaf094fdb476765", null ],
[ "bg", "structAnsiAttr.html#af5d23b90bdd04c64a734ded7c452bc9f", null ],
[ "pair", "structAnsiAttr.html#a7b35e9ab905f75615091259003a9a02f", null ]
];
|
exports.puppeteer = () =>{
const fs = require('fs');
const assert = require('assert');
const puppeteer = require('puppeteer');
puppeteer.launch().then(async () => {
console.log("poppeteer start...")
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.goto('https://tweetdeck.twitter.com/');
if (!!await page.$(".form-legend")) {
console.log("login...")
let caution__json = fs.readFileSync("./loginData.json","utf8");
caution__json = JSON.parse(caution__json);
let caution__username = caution__json.username
let caution__password = caution__json.password
await page.click(".Button");
await page.waitForNavigation();
await page.type(".js-username-field", caution__username);
await page.type(".js-password-field", caution__password);
await page.click("button.submit,.medium,.js-submit input");
await page.waitForNavigation();
//await page.screenshot({ path: 'login_screenshot.png' });
if (!!await page.$(".message-text")) {
console.log("loin Failure");
process.exit(1);
} else {
console.log("login sucsess");
}
}else{
console.log("areadyLogin")
}
//await page.screenshot({ path: 'after1login.png' });
const innerJavaScript = await page.evaluate(() => {
//////////////////////////////↓↓↓extention↓↓↓//////////////////////////////////////////////////////////////
/*
node = document.getElementsByClassName("stream-item js-stream-item is-draggable is-actionable")[0].dataset.tweetId
*/
const portNumber = 8899
const ws = new WebSocket(`ws://localhost:${portNumber}/`);
var userName = 'ゲスト' + Math.floor(Math.random() * 100);
ws.onerror = function (e) {
'サーバに接続できませんでした。'
}
ws.onmessage = event => {
document.getElementsByClassName("js-show-drawer js-show-tip Button Button--primary Button--large tweet-button margin-t--4 margin-b--8")[0].click()
let username = JSON.parse(event.data).username.replace(/@/,"")
let text = JSON.parse(event.data).text
let userListTemp = document.getElementsByClassName("avatar compose-account-img size48");
let userList = [];
for(let i=0;i<userListTemp.length;i++){
userList.push(userListTemp[i].alt.replace(/'s avatar/,"").toLowerCase())
}
if(userListTemp[userList.indexOf(username.toLowerCase())]){
userListTemp[userList.indexOf(username.toLowerCase())].click();
document.getElementsByTagName("textarea")[0].value = text
document.getElementsByClassName("js-progress-circle stroke-twitter-blue")[0].innerHTML = "<circle class='js-progress-circle stroke-twitter-blue' cx='50%' cy='50%' r='8' fill='none' stroke-width='2' style='stroke-dasharray: 30.2655; stroke-dashoffset: 60.2655;'></circle>"
document.getElementsByClassName("js-send-button js-spinner-button js-show-tip Button--primary btn-extra-height padding-v--6 padding-h--12")[0].className = "js-send-button js-spinner-button js-show-tip Button--primary btn-extra-height padding-v--6 padding-h--12"
document.getElementsByClassName("js-send-button js-spinner-button js-show-tip Button--primary btn-extra-height padding-v--6 padding-h--12")[0].click()
}
}
const output = (returnJSON) => {
ws.send(JSON.stringify({
data: returnJSON
}));
}
const deckScraping = () => {
const tweetNodeList = document.getElementsByClassName("stream-item js-stream-item is-draggable is-actionable");
for (let i = 0; i < tweetNodeList.length; i++) {
const node = tweetNodeList[i];
if (node.class + " ".match(/alreadySearch/)) continue;
node.class += "alreadySearch";
const getTweetText = () => {
return node.getElementsByClassName("js-tweet-text tweet-text with-linebreaks")[0].innerText;
}
const replyTarget = () => {
if (node.getElementsByClassName("js-other-replies-link other-replies-link")[0]) return node.getElementsByClassName("js-other-replies-link other-replies-link")[0].innerText.split(" ");
if (getTweetText().match(/(@\w{1,15})+/gi)) return getTweetText().match(/(@\w{1,15})+/gi);
if (node.getElementsByClassName("color-twitter-blue txt-link txt-ellipsis link-complex-target margin-b--5")[0]) return "取得はできませんが、Show this threadリンクが検出されたためリプライであることは間違いありません。"
}
let tweetData;
switch (node.parentNode.parentNode.parentNode.parentNode.parentNode.getElementsByClassName("pull-left margin-hs column-type-icon icon")[0].className.replace(/pull-left margin-hs column-type-icon icon icon-/, "")) {
case "home":
case "notifications":
case "list":
case "user":
case "activity":
case "favorite":
case "mention":
case "search":
tweetData = {
"tweet_id": node.dataset.tweetId,
"retweeted_by": (() => {
if (node.getElementsByClassName("nbfc")[0].innerText.match(/Retweeted/)) return node.getElementsByClassName("nbfc")[0].childNodes[1].innerText;
})(),
"reply_target": replyTarget(),
"icon": node.getElementsByClassName("avatar")[0].src,
"name": node.getElementsByClassName("fullname link-complex-target")[0].innerText,
"screen_name": node.getElementsByClassName("username txt-mute")[0].innerText,
"time_absolute": node.getElementsByClassName("tweet-timestamp js-timestamp txt-mute flex-shrink--0")[0].dateTime,
"time_relative": node.getElementsByClassName("tweet-timestamp js-timestamp txt-mute flex-shrink--0")[0].dateTime,
"text": getTweetText(),
"quote": (() => {
if (!node.getElementsByClassName("js-quote-detail quoted-tweet nbfc br--4 padding-al margin-b--8 position-rel margin-tm is-actionable")[0]) return;
const quoteNode = node.getElementsByClassName("js-quote-detail quoted-tweet nbfc br--4 padding-al margin-b--8 position-rel margin-tm is-actionable")[0];
return {
"tweet_id": quoteNode.dataset.tweetId,
"reply_target": (() => {
if (quoteNode.getElementsByClassName("js-other-replies-link other-replies-link")[0]) return node.getElementsByClassName("js-other-replies-link other-replies-link")[0].innerText.split(" ");
if (quoteNode.getElementsByClassName("js-quoted-tweet-text with-linebreaks")[0].innerText.match(/(@\w{1,15})+/gi)) return quoteNode.getElementsByClassName("js-quoted-tweet-text with-linebreaks")[0].innerText.match(/(@\w{1,15})+/gi);
if (quoteNode.getElementsByClassName("margin-t--4 margin-b---3 txt-mute")[0]) return "取得はできませんが、Show this threadリンクが検出されたためリプライであることは間違いありません。"
})(),
"name": quoteNode.getElementsByClassName("fullname link-complex-target")[0].innerText,
"screen_name": quoteNode.getElementsByClassName("username txt-mute")[0].innerText,
"text": quoteNode.getElementsByClassName("js-quoted-tweet-text with-linebreaks")[0].innerText
}
})()
}
break;
}
const noticeUserName = () => {
if (node.getElementsByClassName("account-link txt-bold")[0].innerText) return node.getElementsByClassName("account-link txt-bold")[0].innerText
}
let notifications_data
if (node.parentNode.parentNode.parentNode.parentNode.parentNode.getElementsByClassName("pull-left margin-hs column-type-icon icon")[0].className === "pull-left margin-hs column-type-icon icon icon-notifications") {
if (node.getElementsByClassName("nbfc txt-line-height--20 flex-auto padding-b--2")[0]) {
//RT,Fav
notifications_data = {
"status": node.getElementsByClassName("nbfc txt-line-height--20 flex-auto padding-b--2")[0].innerText.replace(noticeUserName()),
"notice_user_id": node.getElementsByClassName("account-link txt-bold")[0].href,
"notice_user_name": noticeUserName()
}
//引用
} else if (node.getElementsByClassName("js-quote-detail quoted-tweet nbfc br--4 padding-al margin-b--8 position-rel margin-tm is-actionable")[0]) {
notifications_data = {
"status": "quote_tweet"
}
} else {
//りぷ?
notifications_data = {
"status": "reply",
"debug_messeage": "noticeカラムのRT,ファボ,引用,フォロー,リスト追加通知以外がここに分類されます。引っかかるものはリプライのみと認識して開発しています。万が一リプライ以外が反応した場合対応しますので開発者にご連絡ください。"
}
}
}
const returnJSON = {
"column": node.parentNode.parentNode.parentNode.parentNode.parentNode.getElementsByClassName("pull-left margin-hs column-type-icon icon")[0].className.replace(/pull-left margin-hs column-type-icon icon icon-/, ""),
"column_user": (() => {
if (node.parentNode.parentNode.parentNode.parentNode.getElementsByClassName("attribution txt-mute txt-sub-antialiased")[0]) return node.parentNode.parentNode.parentNode.parentNode.getElementsByClassName("attribution txt-mute txt-sub-antialiased")[0].innerText;
return;
})(),
"status": (() => {
if (notifications_data) return "notifications_" + notifications_data.status
if (tweetData.retweeted_by) return "tweet_retweet"
if (tweetData.reply_target) return "tweet_reply"
if (tweetData.quote) return "tweet_quote"
return "tweet_nomal"
})(),
"tweet_data": tweetData,
"notifications_data": notifications_data
}
output(returnJSON)
}
const addListNodeList = document.getElementsByClassName("activity-header flex flex-row flex-align--baseline");
for (let i = 0; i < addListNodeList.length; i++) {
const addListNode = addListNodeList[i];
if (addListNode.class + " ".match(/alreadySearch/)) continue;
addListNode.class += "alreadySearch";
let returnJSON
returnJSON = {
"column": addListNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.getElementsByClassName("pull-left margin-hs column-type-icon icon")[0].className.replace(/pull-left margin-hs column-type-icon icon icon-/, ""),
"column_user": (() => {
if (addListNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.getElementsByClassName("attribution txt-mute txt-sub-antialiased")[0]) return addListNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.getElementsByClassName("attribution txt-mute txt-sub-antialiased")[0].innerText;
return;
})(),
"status": "add_list",
"notifications_data": {
"status": "add_list",
"name": addListNode.getElementsByClassName("account-link txt-bold")[0].innerText,
"screen_name": addListNode.getElementsByClassName("account-link txt-bold")[0].href.replace(/https:\/\/twitter.com\//, "@"),//ここから
"list_name": addListNode.getElementsByClassName("account-link txt-bold")[0].nextSibling.nextSibling.innerText,
"list_url": addListNode.getElementsByClassName("account-link txt-bold")[0].nextSibling.nextSibling.href
}
}
output(returnJSON)
}
const followNodeList = document.getElementsByClassName("account-summary cf");
for (let i = 0; i < followNodeList.length; i++) {
const followNode = followNodeList[i];
if (followNode.class + " ".match(/alreadySearch/)) continue;
followNode.class += "alreadySearch";
let status = (() => {
if (followNode.parentNode.getElementsByClassName("account-link txt-bold")[0]) return "followed_you"
return "followed_otheruser"
})()
let returnJSON = {
"column": followNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.getElementsByClassName("pull-left margin-hs column-type-icon icon")[0].className.replace(/pull-left margin-hs column-type-icon icon icon-/, ""),
"column_user": (() => {
if (followNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.getElementsByClassName("attribution txt-mute txt-sub-antialiased")[0]) return followNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.getElementsByClassName("attribution txt-mute txt-sub-antialiased")[0].innerText;
return;
})(),
"status": status,
"notifications_data": {
"status": status,
"followed": {
"name": followNode.parentNode.getElementsByClassName("account-link")[0].innerText,
"screen_name": followNode.parentNode.getElementsByClassName("account-link")[0].href.replace(/https:\/\/twitter.com\//i, "@")
},
"followed_target": (() => {
if (status === "followed_you") return "you"
return {
"name": followNode.parentNode.getElementsByClassName("account-summary cf")[0].getElementsByClassName("fullname inline-block link-complex-target position-rel txt-ellipsis")[0].innerText,
"screen_name": followNode.parentNode.getElementsByClassName("account-summary cf")[0].getElementsByClassName("username txt-mute")[0].innerText
}
})()
}
}
output(returnJSON)
}
}
const start = () => {
if (location.href.match(/https\:\/\/tweetdeck\.twitter\.com\/\*?/)) {
setTimeout(() => {
if (document.getElementsByClassName("Button Button--primary block txt-size--18 txt-center")[0]) document.getElementsByClassName("Button Button--primary block txt-size--18 txt-center")[0].click()
setInterval(deckScraping, 4)
}, 2000)
}
}
start()
//////////////////////////////↑↑↑extention↑↑↑//////////////////////////////////////////////////////////////
})//innerJavascript
});//puppeteer
}
|
import React, { useContext } from "react";
import { ThemeContext } from "./themeContext";
import Button from "./components/Button";
import Body from "./components/Body";
const App = () => {
const { theme } = useContext(ThemeContext);
return (
<main className={`${theme}-theme`}>
<Button />
<Body />
</main>
);
};
export default App;
|
app.controller('apiClubController', function($scope, Gapi, $rootScope, $modal, $timeout, $filter, ngTableParams) {
$rootScope.trampLevels = [
{name: "Novice", value: 1},
{name: "Intermediate", value: 2},
{name: "Inter-advanced", value: 3},
{name: "Advanced", value: 4},
{name: "Elite", value: 5},
{name: "Elite-pro", value: 6}
];
$rootScope.syncLevels = [
{name: "Novice and Intermediate", value: 1},
{name: "Intervanced and Advanced", value: 2},
{name: "Elite and Pro-Elite", value: 3}
];
$rootScope.teams = [
{name: "A", value: 1},
{name: "B", value: 2},
{name: "C", value: 3}
];
// Set stats
$scope.memberCount = 0;
$scope.socialCount = 0;
$scope.MarshallsCount = 0;
$scope.ScorekeeperCount = 0;
$scope.commistoCount = 0;
$scope.trampJudgesCount = 0;
$scope.tumblingJudgesCount = 0;
$scope.dmtJudges = 0;
$scope.totalJudges = 0;
//Tramp
$scope.trampCount1 = 0;
$scope.trampCount2 = 0;
$scope.trampCount3 = 0;
$scope.trampCount4 = 0;
$scope.trampCount5 = 0;
$scope.trampCount6 = 0;
//Tumbling
$scope.tumblingCount1 = 0;
$scope.tumblingCount2 = 0;
$scope.tumblingCount3 = 0;
$scope.tumblingCount4 = 0;
$scope.tumblingCount5 = 0;
//Tumbling
$scope.dmtCount1 = 0;
$scope.dmtCount2 = 0;
$scope.dmtCount3 = 0;
$rootScope.data = [];
// table vars
$scope.tableParams = new ngTableParams({
page: 1, // show first page
count: 5, // count per page
sorting: {
name: 'asc' // initial sorting
},
filter: {
}
}, {
counts: [5,10,25,50],
total: 0,
getData: function($defer, params) {
params.total($scope.data.length);
var filteredData = params.filter() ?
$filter('filter')($scope.data, params.filter()) :
$scope.data;
var orderedData = params.sorting() ?
$filter('orderBy')(filteredData, params.orderBy()) :
$scope.data;
$defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
}
},{
});
$scope.tableParams.settings().$scope = $scope;
// Get club members and compute stats
$scope.callApiGetClub = function(nameParam) {
// Set stats
$scope.memberCount = 0;
$scope.socialCount = 0;
$scope.MarshallsCount = 0;
$scope.ScorekeeperCount = 0;
$scope.commistoCount = 0;
$scope.trampJudgesCount = 0;
$scope.tumblingJudgesCount = 0;
$scope.dmtJudges = 0;
$scope.totalJudges = 0;
//Tramp
$scope.trampCount1 = 0;
$scope.trampCount2 = 0;
$scope.trampCount3 = 0;
$scope.trampCount4 = 0;
$scope.trampCount5 = 0;
$scope.trampCount6 = 0;
//Tumbling
$scope.tumblingCount1 = 0;
$scope.tumblingCount2 = 0;
$scope.tumblingCount3 = 0;
$scope.tumblingCount4 = 0;
$scope.tumblingCount5 = 0;
//Tumbling
$scope.dmtCount1 = 0;
$scope.dmtCount2 = 0;
$scope.dmtCount3 = 0;
gapi.client.api.getDmtTumblingCount({Option: 1}).execute(function(resp) {
if(resp.items){
$rootScope.maxTotalTumbling = resp.items[0];
$rootScope.$apply();
}
})
gapi.client.api.getDmtTumblingCount({Option: 2}).execute(function(resp) {
if(resp.items){
$rootScope.maxTotalDmt = resp.items[0];
$rootScope.$apply();
}
})
gapi.client.api.getDmtTumblingCount({Option: 3}).execute(function(resp) {
if(resp.items){
$rootScope.maxTotalSync = resp.items[0];
$rootScope.$apply();
}
})
gapi.client.api.getClub({ Name: nameParam}).execute(function(resp){
$rootScope.club = resp;
if(resp.members){
$rootScope.data = $scope.club.members;
// Get stats for each member
for(var i = 0; i < resp.members.length; i++){
var member = resp.members[i];
//stats
$scope.memberCount++;
if(member.socialTicket){ $scope.socialCount++ }
if(member.marshling){ $scope.MarshallsCount++ }
if(member.scorekeeper){ $scope.ScorekeeperCount++ }
if(member.pastCommISTO){ $scope.commistoCount++ }
//judges
if(member.trampolineFormJudge){ $scope.trampJudgesCount++ }
if(member.tumblingJudge){ $scope.tumblingJudgesCount++ }
if(member.dmtJudge){ $scope.dmtJudges++ }
if(member.trampolineFormJudge || member.tumblingJudge || member.dmtJudge){
$scope.totalJudges++
}
//tramp
if(member.trampolineLevel && member.trampolineCompetitor){
switch (member.trampolineLevel) {
case "1":
$scope.trampCount1++;
break;
case "2":
$scope.trampCount2++;
break;
case "3":
$scope.trampCount3++;
break;
case "4":
$scope.trampCount4++;
break;
case "5":
$scope.trampCount5++;
break;
case "6":
$scope.trampCount6++;
break;
}
}
//tumbling
if(member.tumblingLevel && member.tumblingCompetitor){
switch (member.tumblingLevel) {
case "1":
$scope.tumblingCount1++;
break;
case "2":
$scope.tumblingCount2++;
break;
case "3":
$scope.tumblingCount3++;
break;
case "4":
$scope.tumblingCount4++;
break;
case "5":
$scope.tumblingCount5++;
break;
}
}
//dmt
if(member.dmtLevel && member.dmtCompetitor){
switch (member.dmtLevel) {
case "1":
$scope.dmtCount1++;
break;
case "2":
$scope.dmtCount2++;
break;
case "3":
$scope.dmtCount3++;
break;
}
}
}
$scope.tableParams.reload();
$scope.$apply();
}
})
}
$scope.callApiGetAllMembers = function() {
console.log("callApiGetAllMembers");
// Set stats
$scope.memberCount = 0;
$scope.socialCount = 0;
$scope.MarshallsCount = 0;
$scope.ScorekeeperCount = 0;
$scope.commistoCount = 0;
$scope.trampJudgesCount = 0;
$scope.tumblingJudgesCount = 0;
$scope.dmtJudges = 0;
$scope.totalJudges = 0;
//Tramp
$scope.trampCount1 = 0;
$scope.trampCount2 = 0;
$scope.trampCount3 = 0;
$scope.trampCount4 = 0;
$scope.trampCount5 = 0;
$scope.trampCount6 = 0;
//Tumbling
$scope.tumblingCount1 = 0;
$scope.tumblingCount2 = 0;
$scope.tumblingCount3 = 0;
$scope.tumblingCount4 = 0;
$scope.tumblingCount5 = 0;
//Tumbling
$scope.dmtCount1 = 0;
$scope.dmtCount2 = 0;
$scope.dmtCount3 = 0;
gapi.client.api.getAllClubs().execute(function(resp){
console.log("callApiGetAllMembers - returned");
var allMembers = [];
console.log(resp.items.length)
for(var i = 0; i < resp.items.length; i++){
if(resp.items[i].members && resp.items[i].members.length > 0){
var tmpMembers = resp.items[i].members;
allMembers = allMembers.concat(tmpMembers);
}
}
$rootScope.club = { name: "All members" }
$rootScope.data = allMembers;
// Get stats for each member
for(var i = 0; i < allMembers.length; i++){
var member = allMembers[i];
//stats
$scope.memberCount++;
if(member.socialTicket){ $scope.socialCount++ }
if(member.marshling){ $scope.MarshallsCount++ }
if(member.scorekeeper){ $scope.ScorekeeperCount++ }
if(member.pastCommISTO){ $scope.commistoCount++ }
//judges
if(member.trampolineFormJudge){ $scope.trampJudgesCount++ }
if(member.tumblingJudge){ $scope.tumblingJudgesCount++ }
if(member.dmtJudge){ $scope.dmtJudges++ }
if(member.trampolineFormJudge || member.tumblingJudge || member.dmtJudge){
$scope.totalJudges++
}
//tramp
if(member.trampolineLevel && member.trampolineCompetitor){
switch (member.trampolineLevel) {
case "1":
$scope.trampCount1++;
break;
case "2":
$scope.trampCount2++;
break;
case "3":
$scope.trampCount3++;
break;
case "4":
$scope.trampCount4++;
break;
case "5":
$scope.trampCount5++;
break;
case "6":
$scope.trampCount6++;
break;
}
}
//tumbling
if(member.tumblingLevel && member.tumblingCompetitor){
switch (member.tumblingLevel) {
case "1":
$scope.tumblingCount1++;
break;
case "2":
$scope.tumblingCount2++;
break;
case "3":
$scope.tumblingCount3++;
break;
case "4":
$scope.tumblingCount4++;
break;
case "5":
$scope.tumblingCount5++;
break;
}
}
//dmt
if(member.dmtLevel && member.dmtCompetitor){
switch (member.dmtLevel) {
case "1":
$scope.dmtCount1++;
break;
case "2":
$scope.dmtCount2++;
break;
case "3":
$scope.dmtCount3++;
break;
}
}
}
$scope.tableParams.reload();
$scope.$apply();
})
}
$scope.deleteMemberModal = function(clubName, id, name){
var instance = $modal.open({
templateUrl: 'partials/deleteMemberModal.html',
controller: 'deleteMemberModalController',
controllerAs: 'deleteMemberModalController',
resolve: {
clubName: function(){ return clubName },
id: function(){ return id },
name: function(){ return name }
}
})
return instance;
}
// Call club details
Gapi.load()
.then(function () {
$scope.callApiGetClub($rootScope.currentUser.clubName);
// if commISTO user add club options also
if($rootScope.currentUser.userType === 2){
gapi.client.api.getAllClubNames().execute(
function(resp){
if(resp.items){
$scope.allClubNames = resp;
}
$scope.$apply();
})
}
});
})
|
module.exports = {
// method of operation
get: {
tags: ["Purchase"], // operation's tag.
description: "Get purchase details of a specific customer", // operation's desc.
operationId: "getCustomerPurchase", // unique operation id.
parameters: [
// expected params.
{
name: "id", // name of the param
in: "path", // location of the param
schema: {
$ref: "#/components/schemas/id", // data model of the param
},
required: true, // Mandatory param
description: "A customer's ID", // param desc.
},
],
// expected responses
responses: {
// success response code
200: {
description: "Admin can retrieve purchase details of a specific customer", // response desc.
content: {
// content-type
"application/json": {
schema: {
$ref: "#/components/schemas/Purchase", // Purchase model
},
},
},
},
500: {
description: "This is a generic server error", // response desc.
content: {
// content-type
"application/json": {
schema: {
$ref: "#/components/schemas/InternalServerError", // InternalServerError model
},
},
},
},
},
},
};
|
var app1 = new Vue({
el: '#app-1',
data: {
message: 'Hello there'
}
});
var app2 = new Vue({
el: '#app-2',
data: {
message: 'Yes I am glad that you wanted to see me :))'
}
});
var app3 = new Vue({
el: '#app-3',
data: {
seen: true
}
});
var app4 = new Vue({
el: '#app-4',
data: {
icons: [
{
text: 'Github',
icon: "fab fa-github-square",
},
{
text: 'Facebook',
icon: 'fab fa-facebook',
},
{
text: 'Twitter',
icon: 'fab fa-twitter',
},
{
text: 'Youtube',
icon: 'fab fa-youtube',
}
]
}
});
var app5 = new Vue({
el: '#app-5',
data: {
message: 'You are so amazing!!'
},
methods: {
display: function() {
alert('Here you are')
}
}
});
|
import Head from "next/head";
import Header from "../components/partials/Header";
import Footer from "../components/partials/Footer";
import Video from "../components/partials/utils/Video";
import { useRouter } from "next/router";
import { Context } from "../context/Context";
import { useContext, useEffect } from "react";
import BurgerMenu from "./partials/utils/BurgerMenu";
import Loading from "./utility/Loading";
export default function Layout({
title = "oGraetz - Web Developer",
keywords = "oGraetz, Oliver Graetz, Web Developer, JavaScript",
description = "Oliver Graetz, Professional Web Developer based in Vienna",
children,
}) {
const router = useRouter();
const { burgerMenu, setBurgerMenu, loading } = useContext(Context);
// Set burgerMenu false on pageload
useEffect(() => {
setBurgerMenu(false);
}, []);
return (
<>
<Head>
<title>{title}</title>
<meta name="description" content={description} />
<meta name="keywords" content={keywords} />
<meta
name="viewport"
content="minimum-scale=1, initial-scale=1, width=device-width"
/>
<link rel="icon" href="/favicon.ico" />
<link
rel="stylesheet"
href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap"
/>
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.2/css/all.min.css"
integrity="sha512-HK5fgLBL+xu6dm/Ii3z4xhlSUyZgTT9tuc/hSrtw6uzJOvgRr2a9jyxxT1ely+B+xFAmJKVSTbpM/CuL7qxO8w=="
crossOrigin="anonymous"
/>
</Head>
<Header />
{!router.asPath.includes("/blog") &&
!router.asPath.includes("/projects") && <Video />}
{!burgerMenu ? (
!loading ? (
<main className="flex-column gap">{children}</main>
) : (
<Loading />
)
) : (
<BurgerMenu color="#2e0347;" />
)}
{!burgerMenu ? router.asPath === "/" ? <Footer /> : "" : ""}
</>
);
}
|
document.addEventListener("DOMContentLoaded", function(event) {
var btnTr = document.getElementById("btnTr");
btnTr.onclick = function(){
tr();
}
var btnEo = document.getElementById("btnEo");
btnEo.onclick = function(){
eo();
}
var btnAr = document.getElementById("btnAr");
btnAr.onclick = function(){
ar();
}
var btnJp = document.getElementById("btnJp");
btnJp.onclick = function(){
jp();
}
});
function tr(){
$("input").keyup(function (evt) {
this.value = this.value.replace("&", "");
this.value = this.value.replace(/Ax/g, "Â");
this.value = this.value.replace(/Ix/g, "İ");
this.value = this.value.replace(/Ux/g, "Ü");
this.value = this.value.replace(/Ox/g, "Ö");
this.value = this.value.replace(/Gx/g, "Ğ");
this.value = this.value.replace(/Gh/g, "Ğ");
this.value = this.value.replace(/Sx/g, "Ş");
this.value = this.value.replace(/Sh/g, "Ş");
this.value = this.value.replace(/Cx/g, "Ç");
this.value = this.value.replace(/Ch/g, "Ç");
this.value = this.value.replace(/ax/g, "â");
this.value = this.value.replace(/ae/g, "â");
this.value = this.value.replace(/ix/g, "ı");
this.value = this.value.replace(/ie/g, "ı");
this.value = this.value.replace(/ux/g, "ü");
this.value = this.value.replace(/ue/g, "ü");
this.value = this.value.replace(/ox/g, "ö");
this.value = this.value.replace(/oe/g, "ö");
this.value = this.value.replace(/gx/g, "ğ");
this.value = this.value.replace(/gh/g, "ğ");
this.value = this.value.replace(/sx/g, "ş");
this.value = this.value.replace(/sh/g, "ş");
this.value = this.value.replace(/cx/g, "ç");
this.value = this.value.replace(/ch/g, "ç");
});
}
function eo(){
$("input").keyup(function (evt) {
this.value = this.value.replace("^", "");
this.value = this.value.replace(/Hx/g, "Ĥ");
this.value = this.value.replace(/Cx/g, "Ĉ");
this.value = this.value.replace(/Ç/g, "Ĉ");
this.value = this.value.replace(/Ux/g, "Ŭ");
this.value = this.value.replace(/Ü/g, "Ŭ");
this.value = this.value.replace(/Jx/g, "Ĵ");
this.value = this.value.replace(/Gx/g, "Ĝ");
this.value = this.value.replace(/Ğ/g, "Ĝ");
this.value = this.value.replace(/Sx/g, "Ŝ");
this.value = this.value.replace(/Ş/g, "Ŝ");
this.value = this.value.replace(/hx/g, "ĥ");
this.value = this.value.replace(/cx/g, "ĉ");
this.value = this.value.replace(/ç/g, "ĉ");
this.value = this.value.replace(/ux/g, "ŭ");
this.value = this.value.replace(/ü/g, "ŭ");
this.value = this.value.replace(/jx/g, "ĵ");
this.value = this.value.replace(/gx/g, "ĝ");
this.value = this.value.replace(/ğ/g, "ĝ");
this.value = this.value.replace(/sx/g, "ŝ");
this.value = this.value.replace(/ş/g, "ŝ");
});
}
function ar(){
$("input[type=text]").keypress(function (evt) {
this.value = this.value.replace(/E/g, "أ");
this.value = this.value.replace(/e/g, "ا");
this.value = this.value.replace(/b/g, "ب");
this.value = this.value.replace(/t/g, "ت");
this.value = this.value.replace(/ts/g, "ث");
this.value = this.value.replace(/c/g, "ج");
this.value = this.value.replace(/j/g, "ج");
this.value = this.value.replace(/h/g, "ح");
this.value = this.value.replace(/x/g, "خ");
this.value = this.value.replace(/d/g, "د");
this.value = this.value.replace(/Z/g, "ذ");
this.value = this.value.replace(/r/g, "ر");
this.value = this.value.replace(/z/g, "ز");
this.value = this.value.replace(/s/g, "س");
this.value = this.value.replace(/ş/g, "ش");
this.value = this.value.replace(/sh/g, "ش");
this.value = this.value.replace(/S/g, "ص");
this.value = this.value.replace(/D/g, "ض");
this.value = this.value.replace(/T/g, "ط");
this.value = this.value.replace(/Z/g, "ظ");
this.value = this.value.replace(/a/g, "ع");
this.value = this.value.replace(/G/g, "غ");
this.value = this.value.replace(/ğ/g, "غ");
this.value = this.value.replace(/f/g, "ف");
this.value = this.value.replace(/K/g, "ق");
this.value = this.value.replace(/g/g, "ق");
this.value = this.value.replace(/k/g, "ك");
this.value = this.value.replace(/L/g, "ل");
this.value = this.value.replace(/m/g, "م");
this.value = this.value.replace(/n/g, "ن");
this.value = this.value.replace(/v/g, "و");
this.value = this.value.replace(/u/g, "و");
this.value = this.value.replace(/y/g, "ي");
this.value = this.value.replace(/i/g, "ي");
});
}
function jp(){
$("input[type=text]").keypress(function (evt) {
this.value = this.value.replace(/ka/g, "か");
this.value = this.value.replace(/sa/g, "さ");
this.value = this.value.replace(/ta/g, "た");
this.value = this.value.replace(/na/g, "な");
this.value = this.value.replace(/ha/g, "は");
this.value = this.value.replace(/ma/g, "ま");
this.value = this.value.replace(/ya/g, "や");
this.value = this.value.replace(/ra/g, "ら");
this.value = this.value.replace(/wa/g, "わ");
this.value = this.value.replace(/ki/g, "き");
this.value = this.value.replace(/shi/g, "し");
this.value = this.value.replace(/şi/g, "し");
this.value = this.value.replace(/chi/g, "ち");
this.value = this.value.replace(/çi/g, "ち");
this.value = this.value.replace(/ni/g, "に");
this.value = this.value.replace(/hi/g, "ひ");
this.value = this.value.replace(/mi/g, "み");
this.value = this.value.replace(/ri/g, "り");
this.value = this.value.replace(/wi/g, "ゐ");
this.value = this.value.replace(/ku/g, "く");
this.value = this.value.replace(/su/g, "す");
this.value = this.value.replace(/tsu/g, "つ");
this.value = this.value.replace(/nu/g, "ぬ");
this.value = this.value.replace(/fu/g, "ふ");
this.value = this.value.replace(/mu/g, "む");
this.value = this.value.replace(/yu/g, "ゆ");
this.value = this.value.replace(/ru/g, "る");
this.value = this.value.replace(/ke/g, "け");
this.value = this.value.replace(/se/g, "せ");
this.value = this.value.replace(/te/g, "て");
this.value = this.value.replace(/ne/g, "ね");
this.value = this.value.replace(/he/g, "へ");
this.value = this.value.replace(/me/g, "め");
this.value = this.value.replace(/re/g, "れ");
this.value = this.value.replace(/we/g, "ゑ");
this.value = this.value.replace(/ko/g, "こ");
this.value = this.value.replace(/so/g, "そ");
this.value = this.value.replace(/to/g, "と");
this.value = this.value.replace(/no/g, "の");
this.value = this.value.replace(/ho/g, "ほ");
this.value = this.value.replace(/mo/g, "も");
this.value = this.value.replace(/yo/g, "よ");
this.value = this.value.replace(/ro/g, "ろ");
this.value = this.value.replace(/wo/g, "を");
this.value = this.value.replace(/kya/g, "きゃ");
this.value = this.value.replace(/sha/g, "しゃ");
this.value = this.value.replace(/cha/g, "ちゃ");
this.value = this.value.replace(/nya/g, "にゃ");
this.value = this.value.replace(/hya/g, "ひゃ");
this.value = this.value.replace(/mya/g, "みゃ");
this.value = this.value.replace(/rya/g, "りゃ");
this.value = this.value.replace(/kyu/g, "きゅ");
this.value = this.value.replace(/shu/g, "しゅ");
this.value = this.value.replace(/chu/g, "ちゅ");
this.value = this.value.replace(/nyu/g, "にゅ");
this.value = this.value.replace(/hyu/g, "ひゅ");
this.value = this.value.replace(/myu/g, "みゅ");
this.value = this.value.replace(/ryu/g, "りゅ");
this.value = this.value.replace(/kyo/g, "きょ");
this.value = this.value.replace(/sho/g, "しょ");
this.value = this.value.replace(/cho/g, "ちょ");
this.value = this.value.replace(/nyo/g, "にょ");
this.value = this.value.replace(/hyo/g, "ひょ");
this.value = this.value.replace(/myo/g, "みょ");
this.value = this.value.replace(/ryo/g, "りょ");
this.value = this.value.replace(/ga/g, "が");
this.value = this.value.replace(/za/g, "ざ");
this.value = this.value.replace(/da/g, "だ");
this.value = this.value.replace(/ba/g, "ば");
this.value = this.value.replace(/pa/g, "ぱ");
this.value = this.value.replace(/gi/g, "ぎ");
this.value = this.value.replace(/zi/g, "じ");
this.value = this.value.replace(/ji/g, "ぢ");
this.value = this.value.replace(/dji/g, "ぢ");
this.value = this.value.replace(/jyi/g, "ぢ");
this.value = this.value.replace(/bi/g, "び");
this.value = this.value.replace(/pi/g, "ぴ");
this.value = this.value.replace(/gu/g, "ぐ");
this.value = this.value.replace(/zu/g, "ず");
this.value = this.value.replace(/du/g, "づ");
this.value = this.value.replace(/dzu/g, "づ");
this.value = this.value.replace(/bu/g, "ぶ");
this.value = this.value.replace(/pu/g, "ぷ");
this.value = this.value.replace(/ge/g, "げ");
this.value = this.value.replace(/ze/g, "ぜ");
this.value = this.value.replace(/de/g, "で");
this.value = this.value.replace(/be/g, "べ");
this.value = this.value.replace(/pe/g, "ぺ");
this.value = this.value.replace(/go/g, "ご");
this.value = this.value.replace(/zo/g, "ぞ");
this.value = this.value.replace(/do/g, "ど");
this.value = this.value.replace(/bo/g, "ぼ");
this.value = this.value.replace(/po/g, "ぽ");
this.value = this.value.replace(/gya/g, "ぎゃ");
this.value = this.value.replace(/ja/g, "じゃ");
this.value = this.value.replace(/ja2/g, "ぢゃ");
this.value = this.value.replace(/bya/g, "びゃ");
this.value = this.value.replace(/pya/g, "ぴゃ");
this.value = this.value.replace(/gyu/g, "ぎゅ");
this.value = this.value.replace(/ju/g, "じゅ");
this.value = this.value.replace(/ju2/g, "ぢゅ");
this.value = this.value.replace(/byu/g, "びゅ");
this.value = this.value.replace(/pyu/g, "ぴゅ");
this.value = this.value.replace(/gyo/g, "ぎょ");
this.value = this.value.replace(/jo/g, "じょ");
this.value = this.value.replace(/jo2/g, "ぢょ");
this.value = this.value.replace(/byo/g, "びょ");
this.value = this.value.replace(/pyo/g, "ぴょ");
this.value = this.value.replace(/n/g, "ん");
this.value = this.value.replace(/x/g, "ゝ");
this.value = this.value.replace(/x2/g, "ゞ");
this.value = this.value.replace(/a/g, "あ");
this.value = this.value.replace(/i/g, "い");
this.value = this.value.replace(/u/g, "う");
this.value = this.value.replace(/e/g, "え");
this.value = this.value.replace(/o/g, "お");
this.value = this.value.replace(".", "。");
this.value = this.value.replace(",", "、");
this.value = this.value.replace(/KA/g, "カ");
this.value = this.value.replace(/GA/g, "ガ");
this.value = this.value.replace(/SA/g, "サ");
this.value = this.value.replace(/ZA/g, "ザ");
this.value = this.value.replace(/TA/g, "タ");
this.value = this.value.replace(/DA/g, "ダ");
this.value = this.value.replace(/NA/g, "ナ");
this.value = this.value.replace(/HA/g, "ハ");
this.value = this.value.replace(/BA/g, "バ ");
this.value = this.value.replace(/PA/g, "パ");
this.value = this.value.replace(/MA/g, "マ");
this.value = this.value.replace(/YA/g, "ヤ");
this.value = this.value.replace(/RA/g, "ラ");
this.value = this.value.replace(/WA/g, "ワ");
this.value = this.value.replace(/KI/g, "キ");
this.value = this.value.replace(/GI/g, "ギ");
this.value = this.value.replace(/SI/g, "シ");
this.value = this.value.replace(/ZI/g, "ジ");
this.value = this.value.replace(/TI/g, "チ");
this.value = this.value.replace(/DI/g, "ヂ");
this.value = this.value.replace(/NI/g, "ニ");
this.value = this.value.replace(/HI/g, "ヒ");
this.value = this.value.replace(/BI/g, "ビ");
this.value = this.value.replace(/PI/g, "ピ");
this.value = this.value.replace(/MI/g, "ミ");
this.value = this.value.replace(/RI/g, "リ");
this.value = this.value.replace(/WI/g, "ヰ");
this.value = this.value.replace(/KU/g, "ク");
this.value = this.value.replace(/GU/g, "グ");
this.value = this.value.replace(/SU/g, "ス");
this.value = this.value.replace(/ZU/g, "ズ");
this.value = this.value.replace(/TU/g, "ツ");
this.value = this.value.replace(/DU/g, "ヅ");
this.value = this.value.replace(/NU/g, "ヌ");
this.value = this.value.replace(/HU/g, "フ");
this.value = this.value.replace(/BU/g, "ブ");
this.value = this.value.replace(/PU/g, "プ");
this.value = this.value.replace(/MU/g, "ム");
this.value = this.value.replace(/YU/g, "ユ");
this.value = this.value.replace(/RU/g, "ル");
this.value = this.value.replace(/KE/g, "ケ");
this.value = this.value.replace(/GE/g, "ゲ");
this.value = this.value.replace(/SE/g, "セ");
this.value = this.value.replace(/ZE/g, "ゼ");
this.value = this.value.replace(/TE/g, "テ");
this.value = this.value.replace(/DE/g, "デ");
this.value = this.value.replace(/NE/g, "ネ");
this.value = this.value.replace(/HE/g, "ヘ");
this.value = this.value.replace(/BE/g, "ベ");
this.value = this.value.replace(/PE/g, "ペ");
this.value = this.value.replace(/ME/g, "メ");
this.value = this.value.replace(/RE/g, "レ");
this.value = this.value.replace(/WE/g, "ヱ");
this.value = this.value.replace(/KO/g, "コ");
this.value = this.value.replace(/GO/g, "ゴ");
this.value = this.value.replace(/SO/g, "ソ");
this.value = this.value.replace(/ZO/g, "ゾ");
this.value = this.value.replace(/TO/g, "ト");
this.value = this.value.replace(/DO/g, "ド");
this.value = this.value.replace(/NO/g, "ノ");
this.value = this.value.replace(/HO/g, "ホ");
this.value = this.value.replace(/BO/g, "ボ");
this.value = this.value.replace(/PO/g, "ポ");
this.value = this.value.replace(/MO/g, "モ");
this.value = this.value.replace(/YO/g, "ヨ");
this.value = this.value.replace(/RO/g, "ロ");
this.value = this.value.replace(/WO/g, "ヲ");
this.value = this.value.replace(/A/g, "ア");
this.value = this.value.replace(/I/g, "イ");
this.value = this.value.replace(/U/g, "ウ");
this.value = this.value.replace(/E/g, "エ");
this.value = this.value.replace(/O/g, "オ");
this.value = this.value.replace(/N/g, "ン");
this.value = this.value.replace(/-/g, "ー");
});
}
|
sap.ui.define([
"sap/ui/core/mvc/Controller"
], function(Controller) {
"use strict";
return Controller.extend("uk.me.seancampbell.controller.Main", {
});
});
|
var Poseidon ={
age: 16001,
hobbies: ["swimming", "killing fish", "tidal waves"],
favoritePlaces: ["Pacific Ocean", "Great Pacific Garbage Patch", "Gary's Bathtub"],
friends: [],
enemies: [
{
name: "Hades",
age: 16001.5,
hobbies: ["Dying", "Spongebaths", "Cooking"],
},
{
name: "Zeus",
age: 15394,
hobbies: ["Barn Fires", "Netflix n Chill"],
},
{
name: "Kyle",
age: 26,
hobbies: ["Hiking", "Fidget Spinners", "Selling booze to highschoolers"],
schoolsBannedFrom: [
{
school: "his old highschool",
dateBanned: 2011,
bannedUntil: 3011,
},
{
school: "all universities",
dateBanned: 2013,
bannedUntil: "North Korea takes over",
banPlacedBy: "unknown"
}
]
}
],
olympicGames: [
{
place: "Munich",
year: 1972,
event: "100m freestyle",
medal: "Silver",
beatenBy: "Aquaman"
},
{
place: "Sochi",
year: 2014,
event: "Ski Jumping",
medal: "Gold",
},
{
place: "Rio",
year: 2016,
event: "did not compete, helped fill the swimming pools in",
}
]
};
console.log("Poseidon enjoys " + Poseidon.hobbies[2] + ", swimming in " + Poseidon.favoritePlaces[2] + " and hates " + Poseidon.enemies[2].name)
|
module.exports = {
validateData(arr) {
for (let i = 0; i < arr.length; i++) {
switch (typeof arr[i]) {
case 'string':
return (
arr[i] &&
arr[i].trim() != '' &&
arr[i] !== null &&
arr[i] !== 'undefined'
);
default:
return false;
}
}
}
};
|
const diagram = new dhx.Diagram("diagram_container", {
type: "org",
defaultShapeType: "img-card",
scale: 0.9
});
diagram.data.load('http://localhost/pmii_bondowoso/assets/dhtmlx/data.json');
// const template = ({ photo, name, post, phone, mail }) => (
// <div class="dhx-diagram-demo_personal-card">
// <div class="dhx-diagram-demo_personal-card__container dhx-diagram-demo_personal-card__img-container">
// <img src="${photo}" alt="${name}-${post}"></img>
// </div>
// <div class="dhx-diagram-demo_personal-card__container">
// <h3>${name}</h3>
// <p>${post}</p>
// <span class="dhx-diagram-demo_personal-card__info">
// <i class="mdi mdi-cellphone-android"></i>
// <p>${phone}</p>
// </span>
// <span class="dhx-diagram-demo_personal-card__info">
// <i class="mdi mdi-email-outline"></i>
// <a href="mailto:${mail}" target="_blank">${mail}</a>
// </span>
// </div>
// </div>
// );
|
// test/unit/index.test.js
const Module = require('../../src');
describe('This module', () => {
it('Should exist', () => {
expect(Module).not.toBeUndefined();
});
});
|
'use strict';
/*
* @author Rachel Carbone
*/
var app = angular.module('editor.controllers', []);
app.controller('HeaderMainCtrl', ['$scope', '$state', 'AuthService', 'USER_ROLES',
function($scope, $state, AuthService, USER_ROLES) {
$scope.currentUser = AuthService.getUser();
$scope.userRoles = USER_ROLES;
$scope.logout = AuthService.logout;
$scope.visibleToRole = AuthService.visibleToRole;
$scope.goToProfile = function(analystId) {
$state.go('app.userProfile', { 'analystId' : analystId });
};
$scope.goToState = function(state) {
$state.go(state);
};
}]);
|
const db = require('./db');
module.exports.new = (user_email, billing_date, billed, btc_hashes, eth_hashes, btc_address, eth_address)=>{
return new Promise((res,rej)=>{
db.connect().then((obj)=>{
obj.none('insert into orders (email, billing_date, billed, btc_hashes, eth_hashes, btc_address, eth_address) values ($1, $2, $3, $4, $5, $6, $7)',[user_email, billing_date, billed, btc_hashes, eth_hashes, btc_address, eth_address]).then((data)=>{
res(data);
obj.done();
}).catch((error)=>{
console.log(error);
rej(error);
obj.done();
});
}).catch((error)=>{
rej(error);
});
});
}
module.exports.almost_new = (email, billing_date, billed, btc_hashes, eth_hashes, btc_address, eth_address, order_paid)=>{
return new Promise((res,rej)=>{
db.connect().then((obj)=>{
obj.none('insert into orders (email, billing_date, billed, btc_hashes, eth_hashes, btc_address, eth_address, order_paid) values ($1, $2, $3, $4, $5, $6, $7, $8)',[email, billing_date, billed, btc_hashes, eth_hashes, btc_address, eth_address, order_paid]).then((data)=>{
res(data);
obj.done();
}).catch((error) => {
rej(error);
});
});
})
}
module.exports.show = (id) => {
return new Promise((res, rej) => {
db.connect().then((obj) => {
obj.any('select * from orders where id = $1', [id]).then((data) => {
res(data);
obj.done();
}).catch((error) => {
console.log(error);
rej(error);
obj.done();
});
}).catch((error) => {
rej(error);
});
});
}
module.exports.all = () => {
return new Promise((res, rej) => {
db.connect().then((obj) => {
obj.any('select * from orders').then((data) => {
res(data);
obj.done();
}).catch((error) => {
rej(error);
obj.done();
});
}).catch((error) => {
rej(error);
});
});
}
module.exports.pay = (id) => {
return new Promise((res, rej) => {
db.connect().then((obj) => {
obj.none('update orders set monthly_paid = true where id = $1', [id]).then((data) => {
console.log(`${data} confirm de /pay`);
res(data);
obj.done();
}).catch((error) => {
console.log(`${error} confirm de payout`);
rej(error);
obj.done();
});
}).catch((error) => {
rej(error);
});
});
}
module.exports.confirm = (email) => {
return new Promise((res, rej) => {
db.connect().then((obj) => {
obj.none('update orders set order_paid = true where email = $1', [email]).then((data) => {
res(data);
obj.done();
}).catch((error) => {
rej(error);
obj.done();
});
}).catch((error) => {
rej(error);
});
});
}
module.exports.delete = (id) => {
return new Promise((res, rej) => {
db.connect().then((obj) => {
obj.none('delete from orders where id = $1', [id]).then((data) => {
console.log(data);
res(data);
obj.done();
}).catch((error) => {
console.log(error);
rej(error);
obj.done();
});
}).catch((error) => {
rej(error);
});
});
}
module.exports.history = (id) => {
return new Promise((res, rej) => {
db.connect().then((obj) => {
obj.none('select monthly_paid from orders where id = $1', [id]).then((data) => {
res(data);
obj.done();
}).catch((error) => {
console.log(error);
rej(error);
obj.done();
});
}).catch((error) => {
rej(error);
});
});
}
module.exports.btc_hashes = (email) => {
return new Promise((res, rej) => {
db.connect().then((obj) => {
obj.one('select btc_hashes from orders where email = $1 and btc_hashes is not null', [email]).then((data) => {
res(data);
obj.done();
}).catch((error) => {
rej(error);
obj.done();
});
}).catch((error) => {
rej(error);
});
});
}
module.exports.eth_hashes = (email) => {
return new Promise((res, rej) => {
db.connect().then((obj) => {
obj.one('select eth_hashes from orders where email = $1 and eth_hashes is not null', [email]).then((data) => {
res(data);
obj.done();
}).catch((error) => {
console.log(error);
rej(error);
obj.done();
});
}).catch((error) => {
rej(error);
});
});
}
|
var expCtrl = angular.module('expCtrl', []);
expCtrl.controller('expCtrl', function($scope, Experience) {
$scope.formData = {};
Experience.getAll()
.success(function(data) {
$scope.projects = data;
});
});
|
function parallax(){
$(".my-paroller").paroller({ factor: 0.1, factorXs: 0.1, factorSm: 0.1, type: 'foreground', direction: 'vertical' });
}
$(document).ready(function(){
parallax();
})
|
import React from 'react';
import { connect } from 'react-redux';
import {
Row, Col
} from 'antd';
import CustomBreadcrumb from '@/components/BreadCrumb';
import Query from './query';
import EndPoints from './endpoints';
import Counters from './counters';
import Charts from './charts';
const Graph = () => (
<>
<CustomBreadcrumb arr={['Graph']} />
<Query />
<Row gutter={16}>
<Col span={10}>
<EndPoints />
</Col>
<Col span={14}>
<Counters />
</Col>
</Row>
<Charts />
</>
);
export default connect()(Graph);
|
const fp = require('fastify-plugin')
module.exports = fp(async function (fastify
, opts) {
fastify.decorate('user', {
hasUser: function (pid) {
if (pid instanceof Number) {
pid += ''
}
return opts.user[pid] !== undefined
},
getUser: function (pid) {
if (pid instanceof Number) {
pid += ''
}
return opts.user[pid] ? opts.user[pid] : null
}
})
})
|
const { peopleRepo } = require('./people-repo');
const express = require('express');
const app = express();
app.get('/people', async (req, res) => {
const response = await peopleRepo.readPeople();
res.set('Content-Type', 'application/json');
res.set('Access-Control-Allow-Origin', '*');
res.send(response);
});
app.listen(3000, () => {
console.log('Server listening on port 3000');
});
|
// ///////////////////////////////
// This module contains functions
// that manage user data
// ///////////////////////////////
// Email registration and login
export const register = ( app, email, password ) => app.auth.createUserWithEmailAndPassword( email, password )
export const login = ( app, email, password ) => app.auth.signInWithEmailAndPassword( email, password )
// Grabbing the currently logged in user
export const get = app => {
return new Promise( ( resolve, reject ) => {
app.auth.onAuthStateChanged( user => {
user ? resolve( user ) : reject( user )
} )
} )
}
// Log the user out
export const logout = app => app.auth.signOut( )
// Delete the current user
export const destroy = app => {
return new Promise( resolve => {
app.auth.onAuthStateChanged( user => {
if ( user ) user.delete( ).then( resolve )
} )
} )
}
|
import React from 'react';
import { Link } from 'react-router-dom';
import '../../grid.css';
import './populartourism.css';
import dalat from '../../img/tourslist/popularTourism/cathedral-of-da-lat-360x480.jpg';
import nhatrang from '../../img/tourslist/popularTourism/nha-trang-360x225.jpg';
import phuquoc from '../../img/tourslist/popularTourism/phuquoc-360x225.jpg';
import quynhon from '../../img/tourslist/popularTourism/quynhon11-360x225.jpg';
import dongbac from '../../img/tourslist/popularTourism/ivivu-thac-ban-gioc-bia-360x225.jpg';
const PopularTourism = () => {
return (
<div className="populartourism-container">
<div className="grid wide">
<div className="populartourism">
<h1 className="populartourism-title">Các điểm du lịch phổ biến</h1>
<Link to="/tat-ca-diem-den" className="populartourism-more">
<span>XEM TẤT CẢ</span>
<i className="fas fa-chevron-right"></i>
</Link>
</div>
<div className="row">
<div className="col l-4 m-6 c-12">
<Link to="/tour-da-lat">
<div className="populartourism-dalat">
<img className="img-dalat" src={dalat} alt="dalat" />
<div>
<i className="fas fa-map-marker-alt"></i>
<span>Đà Lạt</span>
</div>
</div>
</Link>
</div>
<div className="col l-4 m-6 c-12">
<div className="populartourism-nhatrang-phuquoc">
<Link to="/tour-nha-trang">
<div className="populartourism-nhatrang">
<img className="img" src={nhatrang} alt="nhatrang" />
<div>
<i className="fas fa-map-marker-alt"></i>
<span>Nha Trang</span>
</div>
</div>
</Link>
<Link to="/tour-phu-quoc">
<div className="populartourism-phuquoc">
<img className="img" src={phuquoc} alt="phuquoc" />
<div>
<i className="fas fa-map-marker-alt"></i>
<span>Phú Quốc</span>
</div>
</div>
</Link>
</div>
</div>
<div className="col l-4 m-12 c-12">
<div className="populartourism-quynhon-dongbac">
<Link to="/tour-quy-nhon">
<div className="populartourism-quynhon">
<img className="img" src={quynhon} alt="quynhon" />
<div>
<i className="fas fa-map-marker-alt"></i>
<span>Quy Nhơn</span>
</div>
</div>
</Link>
<Link to="/tour-dong-bac">
<div className="populartourism-dongbac">
<img className="img" src={dongbac} alt="dongbac" />
<div>
<i className="fas fa-map-marker-alt"></i>
<span>Đông Bắc</span>
</div>
</div>
</Link>
</div>
</div>
</div>
</div>
</div>
);
};
export default PopularTourism;
|
import React, { useState } from "react";
import { Slider, Typography } from "@material-ui/core";
// or
export default function Nav({
onQuickSort,
onMergeSort,
onReset,
isRunning,
onHeapSort,
onBubbelSort,
onValueChange,
barValue,
}) {
const [value, setValue] = useState(10);
const handleChange = (sliderValue) => {
setValue(sliderValue);
onValueChange(sliderValue);
};
return (
<header>
<div className="row">
<button onClick={onMergeSort} disabled={isRunning}>
Merge Sort
</button>
<button onClick={onQuickSort} disabled={isRunning}>
Quicke Sort
</button>
<button onClick={onHeapSort} disabled={isRunning}>
Heap Sort
</button>
<button onClick={onBubbelSort} disabled={isRunning}>
Bubble Sort
</button>
<button onClick={onReset} disabled={isRunning}>
New Array
</button>
<h1>{barValue}</h1>
</div>
<Typography id="discrete-slider-small-steps" gutterBottom>
Change Animations speed and numbers of bars
</Typography>
<Slider
onChange={(e, value) => handleChange(value)}
style={{ width: "10%" }}
disabled={isRunning}
value={value}
max={100}
step={2}
min={1}
/>
<div className="line" />
</header>
);
}
|
let num = 123;
let num2 = "24";
let sum = num + +num2;
console.log(sum);
|
import React, { PureComponent } from 'react';
import { Link } from 'react-router-dom';
import styled from 'styled-components';
import fire from '../../firebaseConfig';
import TextFields from '../../components/TextField/index';
import FlatButton from '../../components/Buttons/FlatPlain';
export const Wrapper = styled.div`
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 100%;
width: 100%;
padding: 0;
margin: 0;
a {
margin: 12px 0;
font-weight: bold;
text-decoration: none;
}
`;
class Login extends PureComponent {
constructor(props) {
super(props);
this.state = {
email: '',
password: '',
};
this.signUp = this.signUp.bind(this);
this.handleChange = this.handleChange.bind(this);
}
signUp(e){
fire.auth().createUserWithEmailAndPassword(this.state.email, this.state.password)
.then((u) => {
if(u.user.uid) {
this.setState({user: u.user.uid});
}
})
.catch((error) => {
console.log('error: ', error);
})
}
componentWillUpdate(){
if(this.state.user){
this.props.history.push('/');
}
}
handleChange(e){
this.setState({ [e.target.name]: e.target.value });
}
render() {
return (
<form>
<Wrapper>
<TextFields name='email' label='Enter your email address' type='email' onChangeHandler={this.handleChange} value={this.state.email} />
<TextFields name='password' label='Enter password' type='password' onChangeHandler={this.handleChange} value={this.state.password} />
<FlatButton name='Sign up' type='button' handleClick={this.signUp} />
<Link to='/reset'>Reset Password</Link>
</Wrapper>
</form>
);
}
}
export default Login;
|
import React, { Component } from 'react';
import './Profile.scss';
import { ProfileHead } from 'components/ProfileHead';
import { ProfileBody } from 'components/ProfileBody';
class Profile extends Component {
state = {
data: {},
isData: false
};
constructor() {
super();
this.setState({
isData: false
});
}
componentDidMount() {
//console.log(this.props.match.params);
if (this.props.match.params) {
fetch(
'http://localhost:9090/api/user/' + this.props.match.params.nickname
).then(res => {
console.log(res);
res.json().then(data => {
this.setState({
data,
isData: true
});
console.log(data);
});
});
}
}
render() {
if (!this.state.isData) {
return '로딩중...';
} else {
return (
<div className="ProfileTemplate">
<div className="ProfileHead_mobile_head" />
<div className="ProfileSection">
<ProfileHead data={this.state.data} />
<ProfileBody data={this.state.data} />
</div>
</div>
);
}
}
}
export default Profile;
|
(function($, window) {
'use strict';
/** Prevent duplicate loading */
if ($.ui.HierarchicalSelect) {
return;
}
var Class = {
create: function() {
return function() {
this.initialize.apply(this, arguments);
};
}
};
var HierarchicalSelect = Class.create();
HierarchicalSelect.prototype = {
_errorMessages: {
rootStructureIncorrect: 'Hierarchical Select Error: Data structure for root select group is incorrect. Please use as data something like: \n' +
'{\n' +
'\t0: [\n' +
'\t\t{\n' +
'\t\t\tkey: 97,\n' +
'\t\t\ttitle: "Air Conditioners",\n' +
'\t\t\tfolder: true,\n' +
'\t\t\tselected: false\n' +
'\t\t},\n' +
'\t\t{\n' +
'\t\t\tkey: 531,\n' +
'\t\t\ttitle: "Conditioning",\n' +
'\t\t\tfolder: false,\n' +
'\t\t\tselected: false\n' +
'\t\t}\n' +
'\t]\n' +
'}\n',
ajaxRouteEmpty: 'Hierarchical Select Error: AJAX route is not set.'
},
initialize: function ($widget) {
var self = this;
self._initWidgetOptions($widget);
self._initHtml();
self._initSliderVariables();
self._initConstants();
self._initSelectGroups();
self._initEvents();
},
_initWidgetOptions: function ($widget) {
this.$widget = $widget;
this.options = $widget.options;
this.element = $widget.element;
this.$select = $($widget.options.select);
this._selectedOptionsInSelectGroups = [];
this.searchPlaceholder = this.options.searchPlaceholder;
this.displayedSelects = this.options.displayedSelects || [0];
this.data = this.options.data || null;
if (!this._hasDataStructure(this.data[0])) {
console.error(this._errorMessages.rootStructureIncorrect);
return false;
}
this.ajaxRoute = this.options.ajaxRoute || '';
if (this.ajaxRoute == '') {
console.error(this._errorMessages.ajaxRouteEmpty);
return false;
}
},
_initHtml: function () {
this.element
.addClass('hierarchical')
.html( '<button type="button" class="controls prev disabled fa fa-chevron-left"></button>'+
'<button type="button" class="controls next disabled fa fa-chevron-right"></button>'+
'<div class="row hierarchical-overflow-container"><div class="hierarchical-items-container"></div></div>'
);
this.$btnNext = this.element.find('.next');
this.$btnPrev = this.element.find('.prev');
this.$overflowContainer = this.element.find('.hierarchical-overflow-container');
this.$containerItems = this.element.find('.hierarchical-items-container');
},
_initSliderVariables: function() {
this.currentPos = 0;
this.outsideLeftPosition = 0;
this.currentMaxVisibleItems = 0;
this.itemWidth = 0;
this.itemOuterWidth = 0;
this.visibleRemainingWidthOfItem = 0;
},
_initConstants: function() {
this.ANIMATE_TIME = 100;
this.MOUSE_UP_DELAY = 150;
this.TAB_KEY_CODE = 9;
this.LEFT_ARROW_KEY_CODE = 37;
this.RIGHT_ARROW_KEY_CODE = 39;
},
_initSelectGroups: function () {
var self = this;
var newGroupKey = 0;
$.each(self.displayedSelects, function (key, selectGroupId) {
self._newSelectGroup(newGroupKey, self.data[selectGroupId]);
newGroupKey++;
});
},
_initEvents: function () {
var self = this;
self.$btnNext.on('click', function () {
self._next();
});
self.$btnPrev.on('click', function () {
self._prev();
});
self.$overflowContainer.on('scroll', function () {
self._onScroll();
}).on('mousedown', function (event) {
if (event.which == 2) {
event.preventDefault();
event.stopPropagation();
return false;
}
});
$(document).on('keydown keypress keyup', function(event) {
if ($.inArray(event.which, [self.TAB_KEY_CODE, self.LEFT_ARROW_KEY_CODE, self.RIGHT_ARROW_KEY_CODE]) !== -1) {
setTimeout(function () {
self._onMouseUp();
}, self.MOUSE_UP_DELAY);
}
});
self.element.parents('.widget-box').find('a[data-action="collapse"]').on('click', function () {
setTimeout(function () {
self._updateWidths();
}, self.MOUSE_UP_DELAY);
});
$(window).on('resize', function () {
self._updateWidths();
});
},
_newSelectGroup: function (key, categories) {
var $selectGroup = this._createSelectGroup(key, categories);
this._addSelectGroupEvents($selectGroup, categories);
this.$containerItems.append($selectGroup);
if (this._isFirstSelectGroup()) {
this.$firstSelectGroup = this.$containerItems.find('.hierarchical-select-group').eq(0);
}
this._unblockAllSelectGroups();
this.currentPos = this._getNoOfExistingGroups();
this._updateWidths();
this.$btnNext.addClass('disabled');
this._animateAction('append');
},
_createSelectGroup: function (key, categories) {
var self = this;
var $selectGroup = $('<div class="hierarchical-select-group col-xs-12 col-sm-6 col-md-4 col-lg-3">' +
'<div class="hierarchical-select-group-search-container">' +
'<input type="text" class="hierarchical-select-group-search form-control" placeholder="' + this.searchPlaceholder + '">' +
'<span class="fa fa-search form-control-feedback" aria-hidden="true"></span>' +
'</div>' +
'<select data-key="' + key + '" size="6" class="hierarchical-select-group-select form-control">' +
'</select>' +
'</div>');
var $select = $selectGroup.find('.hierarchical-select-group-select');
$.each(categories, function(index, category) {
self._createSelectOption($select, category.key, category.title, category.selected, category.folder);
});
return $($selectGroup);
},
_addSelectGroupEvents: function ($selectGroup, categories) {
var $input = $selectGroup.find('.hierarchical-select-group-search');
var $select = $selectGroup.find('.hierarchical-select-group-select');
this._filterByText($input, $select, categories);
this._selectGroupSelect($select);
},
_filterByText: function ($input, $select, categories) {
$input.on('input change keyup', function() {
var search = $.trim($(this).val());
var regex = new RegExp(search,'gi');
$select.find('option').each(function(index, option) {
if ($(option).text().match(regex) !== null) {
$(option).removeClass('hidden').removeAttr('disabled');
} else {
$(option).addClass('hidden').attr('disabled', 'disabled');
}
});
});
},
_selectGroupSelect: function ($select) {
var self = this;
$select.on('change', function() {
var $this = $(this);
var selectGroupKey = self._getSelectGroupKey($select);
var categoryKey = $this.val();
self._blockAllSelectGroups();
self._saveSelectSelection(selectGroupKey, categoryKey);
self._removeFollowingSelectGroups(selectGroupKey);
self._loadChildrenForSelection($this, categoryKey);
}).on('keydown keypress keyup', function(event) {
if ($.inArray(event.which, [self.LEFT_ARROW_KEY_CODE, self.RIGHT_ARROW_KEY_CODE]) !== -1) {
event.preventDefault();
event.stopPropagation();
return false;
}
});
},
_createSelectOption: function ($select, value, text, selected, folder) {
if (selected) {
selected = 'selected="selected"';
} else {
selected = '';
}
folder = folder || false;
$select.append('<option value="' + value + '"' + selected + ' data-folder="' + folder + '">' + text + '</option>');
},
_saveSelectSelection: function(selectGroupKey, categoryKey) {
this._selectedOptionsInSelectGroups[selectGroupKey] = categoryKey;
this.$select.find('option').removeAttr('selected');
if (this.$select.find('option[value="' + categoryKey + '"]').length == 0) {
this._createSelectOption(this.$select, categoryKey, '', true, false);
} else {
this.$select.val(categoryKey);
}
},
_removeFollowingSelectGroups: function(selectGroupKey) {
this._cleanSelectedOptionsInSelectGroups(selectGroupKey);
while (this._isNotLastSelectGroup(selectGroupKey)) {
this._removeLastSelectGroup();
}
},
_loadChildrenForSelection: function ($select, categoryKey) {
var self = this;
if (this._categoryHasChildren($select, categoryKey)) {
var newGroupKey = this._getNoOfExistingGroups();
if (this._categoryChildrenAreLoaded(categoryKey)) {
this._newSelectGroup(newGroupKey, this.data[categoryKey]);
} else {
$.get(this.ajaxRoute,
{
key: categoryKey
},
function(categoryChildrenData) {
self.data[categoryKey] = [];
$.each(categoryChildrenData, function(index, categoryData) {
self.data[categoryKey].push({
key: categoryData.key,
title: categoryData.title,
folder: ( categoryData.folder ? categoryData.folder : false ),
selected: ( categoryData.selected ? categoryData.selected : false )
});
});
self._newSelectGroup(newGroupKey, self.data[categoryKey]);
},
'json'
);
}
} else {
this._unblockAllSelectGroups($select);
}
},
_updateWidths: function () {
this._resetWidths();
this._calculateNewWidths();
this._setNewWidths();
this._setCurrentPosAfterResize();
this._setButtonsState();
this._animateAction('resize');
},
_resetWidths: function () {
var selectGroups = this.$containerItems.find('.hierarchical-select-group');
this.$containerItems.css({
'width': '',
'left': ''
});
$.each(selectGroups, function (key, value) {
$(this).css({
'width': ''
});
});
},
_calculateNewWidths: function() {
this.itemWidth = this.$firstSelectGroup.width() - 1;
this.itemOuterWidth = this.$firstSelectGroup.outerWidth() - 1;
this.currentMaxVisibleItems = Math.floor(this.$overflowContainer.width() / this.itemWidth);
},
_setNewWidths: function() {
var self = this;
var selectGroups = self.$containerItems.find('.hierarchical-select-group');
$.each(selectGroups, function () {
$(this).width(self.itemWidth);
});
self.$containerItems.width(self._getNoOfExistingGroups() * this.itemOuterWidth);
self.visibleRemainingWidthOfItem = 0;
self.isScrolling = false;
},
_onScroll: function () {
var self = this;
if (!self.isScrolling) {
self.isScrolling = true;
self.$overflowContainer.off('mouseup');
self.$overflowContainer.on('mouseup', function (e) {
setTimeout(function () {
self._onMouseUp();
}, self.MOUSE_UP_DELAY);
});
}
},
_animateAction: function (typeOfInteraction) {
var scrollLeftPos = Math.max(0, (this.currentPos - this.currentMaxVisibleItems) * this.itemOuterWidth);
switch (typeOfInteraction) {
case 'append':
this.$containerItems.parent().scrollLeft(scrollLeftPos - this.itemOuterWidth);
this.$containerItems.parent().stop().animate({scrollLeft: scrollLeftPos}, this.ANIMATE_TIME);
break;
case 'removeLast':
this.$containerItems.parent().scrollLeft(scrollLeftPos);
break;
case 'next':
case 'prev':
this.$containerItems.parent().stop().animate({scrollLeft: scrollLeftPos}, this.ANIMATE_TIME);
break;
case 'resize':
this.$containerItems.parent().scrollLeft(scrollLeftPos);
break;
}
},
_setCurrentPosAfterResize: function () {
var noOfExistingGroups = this._getNoOfExistingGroups();
if (noOfExistingGroups >= this.currentMaxVisibleItems) {
if (this.visibleRemainingWidthOfItem !== 0) {
this.currentPos = Math.max(this.currentPos + 1, this.currentMaxVisibleItems);
} else {
this.currentPos = Math.max(this.currentPos, this.currentMaxVisibleItems);
}
} else {
this.currentPos = noOfExistingGroups;
}
},
_setButtonsState: function () {
var self = this;
var noOfExistingGroups = self._getNoOfExistingGroups();
setTimeout(function() {
if (self.currentPos >= noOfExistingGroups) {
self.$btnNext.addClass('disabled');
} else {
self.$btnNext.removeClass('disabled');
}
if (noOfExistingGroups <= self.currentMaxVisibleItems || self.$containerItems.parent().scrollLeft() == 0) {
self.$btnPrev.addClass('disabled');
} else {
self.$btnPrev.removeClass('disabled');
}
}, self.MOUSE_UP_DELAY);
},
_next: function () {
if (this.visibleRemainingWidthOfItem !== 0) {
var nextFullyViewedItemXPos = this.$containerItems.parent().scrollLeft() + this.visibleRemainingWidthOfItem;
this.visibleRemainingWidthOfItem = 0;
this._setCurrentPosToNextFullyViewedItem(nextFullyViewedItemXPos);
} else {
this.currentPos = Math.min(this._getNoOfExistingGroups(), this.currentPos + 1);
}
this._setButtonsState();
this._animateAction('next');
},
_setCurrentPosToNextFullyViewedItem: function (nextFullyViewedItemXPos) {
this.currentPos = Math.min(Math.floor(nextFullyViewedItemXPos / this.itemOuterWidth) + this.currentMaxVisibleItems, this._getNoOfExistingGroups());
},
_prev: function () {
var previousFullyViewedItemXPos = this.$containerItems.parent().scrollLeft() - (this.itemOuterWidth - this.visibleRemainingWidthOfItem);
this.visibleRemainingWidthOfItem = 0;
this._setCurrentPosToPreviousFullyViewedItem(previousFullyViewedItemXPos);
this._setButtonsState();
this._animateAction('prev');
},
_setCurrentPosToPreviousFullyViewedItem: function (previousFullyViewedItemXPos) {
this.currentPos = Math.round(previousFullyViewedItemXPos / this.itemOuterWidth) + this.currentMaxVisibleItems;
},
_onMouseUp: function () {
var noOfExistingGroups = this._getNoOfExistingGroups();
this.outsideLeftPosition = this.$containerItems.parent().scrollLeft();
this.visibleRemainingWidthOfItem = this.itemOuterWidth - (this.outsideLeftPosition % this.itemOuterWidth);
if (this.visibleRemainingWidthOfItem == this.itemOuterWidth) {
this.visibleRemainingWidthOfItem = 0;
}
if (this.outsideLeftPosition > 0) {
var itemsNotVisible = this._getNoOfItemsNotVisible();
this.currentPos = Math.min(itemsNotVisible + this.currentMaxVisibleItems, noOfExistingGroups);
} else {
this.currentPos = this.currentMaxVisibleItems;
}
this.isScrolling = true;
this._setButtonsState();
},
_getNoOfItemsNotVisible: function () {
return Math.round(this.outsideLeftPosition / this.itemOuterWidth);
},
_isFirstSelectGroup: function () {
return (this._getNoOfExistingGroups() == 1);
},
_getSelectGroupKey: function ($select) {
return parseInt($select.attr('data-key'));
},
_isGroupKeyOption: function (selectGroupKey, key) {
return this._selectedOptionsInSelectGroups[selectGroupKey] == key;
},
_hasDataStructure: function(data) {
return (data instanceof Array && data.length > 0);
},
_getNoOfExistingGroups: function() {
return this.element.find('.hierarchical-select-group').length;
},
_cleanSelectedOptionsInSelectGroups: function(selectGroupKey) {
this._selectedOptionsInSelectGroups.splice(selectGroupKey + 1, this._selectedOptionsInSelectGroups.length);
},
_isNotLastSelectGroup: function(selectGroupKey) {
var noOfExistingGroups = this._getNoOfExistingGroups();
return (noOfExistingGroups > selectGroupKey + 1);
},
_removeLastSelectGroup: function() {
this.$overflowContainer.off('mouseup');
this.element.find('.hierarchical-select-group:last').remove();
this.currentPos = this._getNoOfExistingGroups();
this._updateWidths();
this._animateAction('removeLast');
},
_categoryHasChildren: function ($select, categoryKey) {
return ( $select.find('option[value="' + categoryKey + '"]').attr('data-folder') == 'true' ? true : false );
},
_categoryChildrenAreLoaded: function (categoryKey) {
return ( this.data[categoryKey] && this._hasDataStructure(this.data[categoryKey]) );
},
_blockAllSelectGroups: function() {
this.element.find('select').blur().css('overflow-y', 'hidden');
this.element.find('input, select').attr('disabled', 'disabled');
this.$overflowContainer.blockControl();
},
_unblockAllSelectGroups: function($select) {
this.element.find('select').css('overflow-y', 'scroll').blur();
this.element.find('input, select').removeAttr('disabled');
this.$overflowContainer.unblockControl();
if ($select) {
$select.focus();
} else {
var noOfExistingGroups = this._getNoOfExistingGroups();
this.element.find('select').eq(noOfExistingGroups - 2).focus();
}
}
};
$.widget('ui.HierarchicalSelect', {
options: {
searchPlaceholder: 'Search',
select: '',
data: null,
displayedSelects: [0],
ajaxRoute: ''
},
_create: function() {
this.HierarchicalSelect = new HierarchicalSelect(this);
}
});
}(jQuery, window));
|
const express = require("express");
const cors = require("cors");
const mongoose = require("mongoose");
const port = process.env.PORT || 8080;
const dotenv = require("dotenv");
const router = require("./routers/allapis");
dotenv.config();
const app = express();
app.use(cors());
app.use(express.json());
//database
mongoose
.connect(process.env.DB_URL)
.then((res) => {
console.log("db connected successfully..");
})
.catch((err) => console.log("error:", err));
//get all rooms
app.use(router);
//root route
app.get("/", (req, res) => {
res.send("Server is running.");
});
app.listen(port, () => {
console.log("server is running");
});
|
function updateBacklog() {
resetBacklog();
var teamVal = document.getElementById("backLogSelect").value;
if (teamVal == "All") {
$.ajax({
url: '/Home/GetAllUnsized',
type: 'GET',
dataType: 'json',
cache: false,
error: function () {
alert('Error occured');
},
success: function (data) {
addUnsized(data);
}
});
$.ajax({
url: '/Home/GetAllSized',
type: 'GET',
dataType: 'json',
cache: false,
error: function () {
alert('Error occured');
},
success: function (data) {
addSized(data, teamVal);
document.getElementById("loading").hidden = true;
document.getElementById("loaderBacklog").hidden = true;
document.getElementById("backLogSelect").disabled = false;
document.getElementById("backLogBtn").disabled = false;
}
});
} else {
$.ajax({
url: '/Home/GetUnsized',
type: 'GET',
data: { team: teamVal },
dataType: 'json',
cache: false,
error: function () {
alert('Error occured');
},
success: function (data) {
addUnsized(data);
document.getElementById("loading").hidden = true;
document.getElementById("loaderBacklog").hidden = true;
document.getElementById("backLogSelect").disabled = false;
}
});
$.ajax({
url: '/Home/GetSized',
type: 'GET',
data: { team: teamVal },
dataType: 'json',
cache: false,
error: function () {
alert('Error occured');
},
success: function (data) {
addSized(data, teamVal);
}
});
}
}
function resetBacklog() {
document.getElementById("unsizedStoriesDisp").innerText = "";
document.getElementById("storyPointsInBacklog").innerHTML = "";
document.getElementById("backLogSelect").disabled = true;
document.getElementById("backLogBtn").disabled = true;
document.getElementById("loading").hidden = false;
document.getElementById("loaderBacklog").hidden = false;
}
|
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import Topbar from './components/Topbar/Topbar';
import Sidebar from './components/Sidebar/Sidebar';
import Backdrop from './components/Backdrop/Backdrop';
import Calendar from './components/Calendar/Calendar';
class Main extends React.Component{
state = {
sideHidden: false
};
sidebarToggle = () => {
this.setState((prevState) => {
return{sideHidden: !prevState.sideHidden};
});
};
backdropToggle = () => {
this.setState({sideHidden: false});
};
render(){
let backdrop;
if(this.state.sideHidden){
backdrop = <Backdrop click={this.backdropToggle}/>
}
return(
<div style={{height: '100%'}}>
<Topbar sidebarToggler={this.sidebarToggle} />
<Sidebar show={this.state.sideHidden} />
{backdrop}
<main style={{marginTop: '64px'}}>
<Calendar month={new Date().getMonth()} year={new Date().getFullYear()}/>
</main>
</div>
)
}
}
ReactDOM.render(<Main />, document.getElementById('root'));
class HideButton extends React.Component{
constructor(props){
super(props);
this.state = {
hidden : false,
};
}
showStuff = () => {
var table = document.getElementById("table");
table.style.display = "block";
this.setState({hidden : !this.state.hidden});
}
hideStuff = () => {
var table = document.getElementById("table");
table.style.display = "none";
this.setState({hidden : !this.state.hidden});
}
render(){
if(this.state.hidden){
return(
<div>
<button type="button" onClick={this.showStuff}>Show</button>
</div>
);
}else{
return(
<div>
<button type="button" onClick={this.hideStuff}>Hide</button>
</div>
);
}
}
}
ReactDOM.render(<HideButton />, document.getElementById('button'));
class Table extends React.Component{
constructor(props){
super(props);
this.state = {
value : '',
Notes : [],
}
}
onChangeValue = event => {
this.setState({value : event.target.value});
};
onAddItem = () => {
this.setState(state => {
if(!state.Notes.includes(state.value)){
const Notes = state.Notes.concat(state.value);
return {
Notes,
value: '',
};
}else{
return {
value : '',
};
}
});
};
onDeleteItem = i => {
this.setState(state => {
const Notes = state.Notes.filter((item, j) => i !== j);
return {
Notes,
};
});
};
renderEntry(){
return this.state.Notes.map((note, remove) => {
return(
<tr key={note}>
<td>{note}</td>
<td><button type="button" onClick={() => this.onDeleteItem(remove)}> X </button></td>
</tr>
)
})
}
render(){
return(
<div>
<input type="text" value={this.state.value} onChange={this.onChangeValue}/>
<button type="button" onClick={this.onAddItem} disabled={!this.state.value}>Add</button>
<table>
<tbody>
{this.renderEntry()}
</tbody>
</table>
</div>
);
}
}
ReactDOM.render(<Table />, document.getElementById('table'));
|
Ext.define('AM.view.common.ReportPanel',
{
extend: 'Ext.Panel',
alias: 'widget.common_reportPanel',
requires: ['AM.view.graph.Line',
'AM.view.graph.HorizontalBar',
'AM.view.graph.VerticalBar',
'AM.view.map.GMapPanel'],
initialize: function () {
this.callParent(arguments);
this.panelConfig = this.config.panelConfig;
this.on('painted', this.loadMetaData, this);
},
loadMetaData: function () {
this.reportIdentifier = {};
this.reportIdentifier.configId = this.panelConfig.configId;
this.reportIdentifier.reportId = this.panelConfig.reportId;
ajaxService.processRequest("report", "getReportMetaData", {
loadMaskMessage: 'Loading meta data.....',
loadMaskEl: this.getEl == undefined ? Ext.getBody() : this.getEl(),
args: this.reportIdentifier,
success: this.afterDataLoad,
scope: this
});
},
afterDataLoad: function (data) {
var reportType = data.reportType;
if (this.tempGraphCount != undefined) {
tempGraphCount = this.tempGraphCount;
}
tempGraphCount++;
switch (tempGraphCount) {
case 1 :
this.loadLineGraphData();
break;
case 2 :
this.loadPieGraphData();
break;
case 3 :
this.loadHorizontalBarData();
break;
case 4 :
this.loadMapHeatData();
break;
default :
this.loadMapHeatData();
break;
}
},
loadLineGraphData: function () {
ajaxService.processRequest("report", "getReportData", {
loadMaskMessage: 'Loading chart data.....',
loadMaskEl: this.getEl == undefined ? Ext.getBody() : this.getEl(),
args: this.reportIdentifier,
success: this.afterLineGraphDataLoad,
scope: this
});
},
afterLineGraphDataLoad: function (data) {
this.title = data.title;
this.add({
xtype: 'graph_line',
config: data
});
},
loadPieGraphData: function () {
ajaxService.processRequest("report", "getPieData", {
loadMaskMessage: 'Loading chart data.....',
loadMaskEl: this.getEl == undefined ? Ext.getBody() : this.getEl(),
args: this.reportIdentifier,
success: this.afterPieGraphDataLoad,
scope: this
});
},
afterPieGraphDataLoad: function (data) {
this.title = data.title;
this.add({
xtype: 'graph_pi',
config: data
});
},
loadHorizontalBarData: function () {
ajaxService.processRequest("report", "getHorizontalBarData", {
loadMaskMessage: 'Loading chart data.....',
loadMaskEl: this.getEl == undefined ? Ext.getBody() : this.getEl(),
args: this.reportIdentifier,
success: this.afterHorizontalBarDataLoad,
scope: this
});
},
afterHorizontalBarDataLoad: function (data) {
this.title = data.title;
this.add({
xtype: 'graph_horizontalBar',
config: data
});
},
loadVerticalBarData: function () {
ajaxService.processRequest("report", "getVerticalBarData", {
loadMaskMessage: 'Loading chart data.....',
loadMaskEl: this.getEl == undefined ? Ext.getBody() : this.getEl(),
args: this.reportIdentifier,
success: this.afterVerticalBarDataLoad,
scope: this
});
},
afterVerticalBarDataLoad: function (data) {
this.title = data.title;
this.add({
xtype: 'graph_verticalBar',
config: data
});
},
loadMapHeatData: function () {
ajaxService.processRequest("location", "getSiteAccessGeoData", {
loadMaskMessage: 'Loading chart data.....',
loadMaskEl: this.getEl == undefined ? Ext.getBody() : this.getEl(),
args: this.reportIdentifier,
success: this.afterMapHeatDataLoad,
scope: this
});
},
afterMapHeatDataLoad: function (data) {
this.title = data.title;
this.add({
xtype: 'gmappanel',
config: data
});
}
});
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { injectIntl, intlShape } from 'react-intl';
import muiThemeable from 'material-ui/styles/muiThemeable';
import { setSimpleValue } from '../../store/simpleValues/actions';
import { withRouter } from 'react-router-dom';
import FontIcon from 'material-ui/FontIcon';
import { withFirebase } from 'firekit-provider'
import { ListItem } from 'material-ui/List';
import Divider from 'material-ui/Divider';
import Avatar from 'material-ui/Avatar';
import Toggle from 'material-ui/Toggle';
import ReactList from 'react-list';
import { List } from 'material-ui/List';
class UserRoles extends Component {
componentWillMount() {
this.props.watchList('user_roles');
this.props.watchList('roles');
}
hanldeRoleToggleChange = (e, isInputChecked, key) => {
const { firebaseApp, match } = this.props
const uid=match.params.uid
if(isInputChecked){
firebaseApp.database().ref(`/user_roles/${uid}/${key}`).set(true)
}else{
firebaseApp.database().ref(`/user_roles/${uid}/${key}`).remove()
}
}
renderRoleItem = (i, k) => {
const { roles, user_roles, match } = this.props
const uid=match.params.uid
const key=roles[i].key
const val=roles[i].val
let userRoles=[]
if(user_roles!==undefined){
user_roles.map(role=>{
if(role.key===uid){
if(role.val!==undefined){
userRoles=role.val
}
}
return role
})
}
return <div key={key}>
<ListItem
leftAvatar={
<Avatar
alt="person"
src={val.photoURL}
icon={<FontIcon className="material-icons" >account_box</FontIcon>}
/>
}
rightToggle={
<Toggle
toggled={userRoles[key]===true}
onToggle={(e, isInputChecked)=>{this.hanldeRoleToggleChange(e, isInputChecked, key)}}
/>
}
key={key}
id={key}
primaryText={val.name}
secondaryText={val.description}
/>
<Divider inset={true}/>
</div>
}
render() {
const { roles } = this.props;
return (
<div style={{height: '100%'}}>
<List style={{height: '100%'}} >
<ReactList
itemRenderer={(i, k) => this.renderRoleItem(i, k)}
length={roles?roles.length:0}
type='simple'
/>
</List>
</div>
);
}
}
UserRoles.propTypes = {
intl: intlShape.isRequired,
muiTheme: PropTypes.object.isRequired,
match: PropTypes.object.isRequired,
};
const mapStateToProps = (state, ownProps) => {
const { auth, intl, lists, filters } = state;
const { match } = ownProps
const uid = match.params.uid
return {
filters,
auth,
uid,
intl,
user_roles: lists.user_roles,
roles: lists.roles?lists.roles:[]
}
}
export default connect(
mapStateToProps, { setSimpleValue }
)(injectIntl(withRouter(withFirebase(muiThemeable()(UserRoles)))));
|
/*
CONTENTS
1) Methods for simulating backup thread assembly
2) Methods for simulating backup processing
3) Method for estimating backup completion times (backupTimeEstimator)
*/
/**************** 1) Assembling backup threads ****************/
function openThreadCount(backups, maxThreads) {
/*
Return the # of open threads, given a limit ("maxThreads")
and an array of active backup threads ("backups").
*/
return maxThreads - backups.length;
}
function checkAllThreadsInUse(backups, maxThreads) {
/*
Return whether all threads are in use.
*/
if (openThreadCount(backups, maxThreads) === 0) {
return true;
} else {
return false;
}
}
function getNewBackups(time, queue, openThreads, startTimes, backupDuration) {
/*
What backups are in the queue, given the time? Of these
backups "in potentia", choose the ones with the lowest startTimes
(i.e., the ones that have been in the queue the longest).
Append info (start, duration) for a number of backups <= the number
of open threads to an array of new backups; return this. If there are
no viable new backups, return [].
*/
var newBackups = [], potentia;
potentia = queue.filter(q => q <= time);
for (var i = 0; i < potentia.length; i++) {
if (newBackups.length < openThreads) {
newBackups.push({
'start': potentia[i],
'duration': getBackupDuration(potentia[i], startTimes, backupDuration)
});
} else {
break;
}
}
return newBackups;
}
function getBackupDuration(t, startTimes, backupDuration) {
/*
Given a backup start time, t, return its corresponding backup duration.
*/
return backupDuration[startTimes.indexOf(t)];
}
function removeNewBackupsFromQueue(newBackups, queue) {
/*
Remove backups that are about to begin from the queue of all other
backups that have yet to begin.
*/
var newTimes = newBackups.map(entry => entry.start);
return queue.filter(t => !newTimes.includes(t));
}
function addNewBackups(
maxThreads,
startTimes,
backupDuration,
state,
openThreads
) {
/*
Transfer backups from an array of potential backups ("queue")
to array of active backups ("backups"), as is viable.
Both arrays are contained within a "state" object, which is
effectively what is getting updated here. As a point of reference,
the initial state is as follows: {
'backups': [],
'queue': startTimes,
'time': startTimes[0],
'allThreadsInUse': false
}.
*/
var newBackups = getNewBackups(
state.time,
state.queue,
openThreads,
startTimes,
backupDuration
);
if (newBackups.length > 0) {
state.backups = state.backups.concat(newBackups);
state.queue = removeNewBackupsFromQueue(newBackups, state.queue);
}
return state;
}
function setState(maxThreads, startTimes, backupDuration, state) {
/*
Iff open threads, update the state object accordingly, attempting
to fill any open threads.
*/
var openThreads = openThreadCount(state.backups, maxThreads);
if (openThreads > 0) {
state = addNewBackups(
maxThreads,
startTimes,
backupDuration,
state,
openThreads
);
state.allThreadsInUse = checkAllThreadsInUse(state.backups, maxThreads);
}
return state;
}
/**************** 2) Simulating backup processing ****************/
function getMinDuration(backups) {
/*
Return a number, min, the minimum duration balance of any particular
backup among all active backups (given the number of threads currently
running; i.e., backups.length).
The backupTimeEstimator method short-circuits this method's being
called when backups = [].
*/
var min = Infinity;
for (var i = 0; i < backups.length; i++) {
if (backups[i].duration < min) {
min = backups[i].duration;
}
}
min *= backups.length;
return min;
}
function getRoundDuration(state) {
/*
Return a number (float), the duration for the current backup "round"
given constraints.
A round will either be the duration to complete the backup closest
to being completed (the one with the smallest duration balance), or
the time until the next backup is added to the queue (special case
given empty threads).
*/
minRoundDuration = getMinDuration(state.backups);
if (!state.allThreadsInUse) {
var timeTillNextUp = state.queue[0] - state.time; // 'NaN' if empty queue
if (timeTillNextUp <= minRoundDuration) {
return timeTillNextUp;
}
}
return minRoundDuration;
}
function simulateBackupProgress(backups, backupRoundDuration) {
/*
Update backup duration balance for all active backups to
reflect a given amount of progress.
*/
var progress = backupRoundDuration / backups.length;
backups.forEach(entry => {
entry.duration -= progress;
});
// JS objects assigned by reference so no need to return anything
}
function trackCompletedBackups(state, startTimes, completionTimes) {
/*
For completed backups at a given time, associate this time with the
indices for these backups in the "completionTimes" array.
Return the completionTimes array.
*/
var completedBackups = getCompletedBackups(state.backups);
if (completedBackups.length > 0) {
completedBackups.forEach(entry => {
completionTimes[startTimes.indexOf(entry.start)] = round(state.time, 5);
});
}
return completionTimes;
}
function round(value, decimals) {
/*
Round a number to a given decimal place.
*/
return Number(Math.round(value+'e'+decimals)+'e-'+decimals);
}
function getCompletedBackups(backups) {
/*
Return those backups that are done being backed up. This includes any
backups whose durations are epsilonically close to but slightly < 0
(-2.2737367544323206e-13, e.g.).
*/
return backups.filter(entry => entry.duration <= 0);
}
function removeCompletedBackups(backups) {
/*
Return those backups that are not done being backed up.
*/
return backups.filter(entry => entry.duration > 0);
}
/**************** 3) Estimating backup completion times ****************/
function backupTimeEstimator(startTimes, backupDuration, maxThreads) {
/*
[input] array.integer "startTimes"
- A sorted array of unique positive integers. The ith element is the
time the ith job was added to the backup queue.
- Guaranteed constraints:
0 ≤ startTimes.length ≤ 400,
1 ≤ startTimes[i] ≤ 109.
[input] array.integer "backupDuration"
- Array of positive integers of the same size as startTimes. For each
valid i backupDuration[i] is the amount of time it takes to back up
the ith job if there is only one running thread.
- Guaranteed constraints:
backupDuration.length = startTimes.length,
1 ≤ backupDuration[i] ≤ 104.
[input] integer maxThreads
- The maximum number of threads that can work in parallel.
- Guaranteed constraints:
1 ≤ maxThreads ≤ 45.
[output] array.float
- Array of the same length as startTimes, where the ith element is the
moment by which the ith job is backed up. Rounded to 10**(-5).
*/
var state = {
'backups': [],
'queue': startTimes,
'time': startTimes[0],
'allThreadsInUse': false};
var backupRoundDuration;
var completionTimes = Array(startTimes.length).fill(null);
/*
Each iteration of the following for loop represents a single "round"
of backing up, however long that round happens to take.
[A round will either be the duration to complete the backup closest
to being completed (the one with the smallest duration balance), or
the time until the next backup is added to the queue (special case
given empty threads).]
*/
for (var i = 0; i < 1000; i++) {
// Exit condition:
if (state.queue.length <= 0 && state.backups.length <= 0) {
break;
}
// Each round we first attempt to add new backups:
state = setState(maxThreads, startTimes, backupDuration, state);
// If no active backups, jump to next relevant moment in time:
if (state.backups.length === 0) {
state.time = state.queue[0];
continue;
}
// If active backups, simulate backup activity...
backupRoundDuration = getRoundDuration(state);
simulateBackupProgress(state.backups, backupRoundDuration);
state.time += backupRoundDuration;
// ...and account for it:
completionTimes = trackCompletedBackups(state, startTimes, completionTimes);
state.backups = removeCompletedBackups(state.backups);
state.allThreadsInUse = checkAllThreadsInUse(state.backups, maxThreads);
}
return completionTimes;
}
/*
Ben Ellentuck, 4/11/17
ellentuckben@gmail.com
*/
|
import React, { Component } from 'react'
import Sidebar from './Sidebar'
import CircularProgress from '@material-ui/core/CircularProgress';
import Backdrop from '@material-ui/core/Backdrop';
import axios from '../config/axios';
import { Calendar, momentLocalizer } from "react-big-calendar";
import moment from "moment";
import withDragAndDrop from "react-big-calendar/lib/addons/dragAndDrop";
import "react-big-calendar/lib/addons/dragAndDrop/styles.css";
import "react-big-calendar/lib/css/react-big-calendar.css";
const localizer = momentLocalizer(moment);
const DnDCalendar = withDragAndDrop(Calendar);
export class Dashboard extends Component {
//total pemasukan - total budget
state = {
dataEvent:null,
totalPengeluaran:0,
totalPemasukan:0,
totalBudget:0,
saldo:0,
dataMou:null,
dataSurat:null,
mailIn:0,
mailOut:0,
rabcashin:0,
events:null
}
componentDidMount(){
let data = JSON.parse(localStorage.getItem('dataEvent'))
this.setState({dataEvent:data})
this.getRab(data)
this.getCashflow(data)
this.getMou(data)
this.getSurat(data)
this.getTimeline(data)
}
getTimeline = (dataEvent)=>{
axios.get(`/agenda/${dataEvent.idEvent}`)
.then(res=>{
let data = res.data.map(val=>{
return{
id_agenda:val.id_agenda,
id_user:val.id_user,
id_event:val.id_event,
start: new Date(val.start),
end: new Date(val.end),
title:val.title
}
})
this.setState({events:data})
})
.catch(err=>{
console.log(err)
})
}
getRab = (dataEvent)=>{
axios.get(`/rab/${dataEvent.idEvent}`)
.then(res=>{
let total = 0
res.data.map(val=>{
return total = total + (val.jumlah * val.harga_satuan)
})
this.setState({totalBudget:total})
})
.catch(err=>{
console.log(err)
})
}
getMou = (dataEvent)=>{
axios.get(`/mou_terakhir/${dataEvent.idEvent}`)
.then(res=>{
this.setState({dataMou:res.data})
})
.catch(err=>{
console.log(err)
})
}
getCashflow = (dataEvent)=>{
axios.get(`/cashflow/${dataEvent.idEvent}`)
.then(res=>{
let totalPemasukan = 0
let totalPengeluaran = 0
let saldo = 0
let jumlah = 0
res.data.map(val=>{
if(val.jenis === 'Pemasukan'){
totalPemasukan = totalPemasukan + val.jumlah
jumlah = val.jumlah
}else{
totalPengeluaran = totalPengeluaran + val.jumlah
jumlah = -val.jumlah
}
return saldo = saldo + jumlah
})
this.setState({totalPemasukan, totalPengeluaran, saldo})
})
.catch(err=>{
console.log(err)
})
}
getSurat = (dataEvent)=>{
axios.get(`/surat_terakhir/${dataEvent.idEvent}`)
.then(res=>{
let mailIn = 0
let mailOut = 0
res.data.map(val=>{
if(val.tanggal_keluar){
return mailOut = mailOut +1
}else{
return mailIn = mailIn + 1
}
})
this.setState({mailIn, mailOut,dataSurat:res.data.reverse()})
})
.catch(err=>{
console.log(err)
})
}
renderSurat = ()=>{
if(this.state.dataSurat.length === 0){
return(
<tr>
<td className="text-center" colSpan={6}>No Data</td>
</tr>
)
}
let data = this.state.dataSurat.map(val=>{
let tanggal_masuk = '-'
let tanggal_keluar = '-'
if(val.tanggal_masuk){
tanggal_masuk = val.tanggal_masuk.slice(0,10)
}else{
tanggal_keluar = val.tanggal_keluar.slice(0,10)
}
return(
<tr key={val.id_surat}>
<td>{val.nosurat}</td>
<td>{tanggal_masuk}</td>
<td>{tanggal_keluar}</td>
<td>{val.perihal}</td>
<td>{val.surat_dari}</td>
<td>{val.kepada}</td>
<td>{val.pj}</td>
</tr>
)
})
return data
}
renderMou = ()=>{
if(this.state.dataMou.length === 0){
return(
<tr>
<td className="text-center" colSpan={6}>No Data</td>
</tr>
)
}
let data = this.state.dataMou.map(val=>{
return(
<tr key={val.id_perjanjian}>
<td>{val.nama_instansi}</td>
<td>{val.nama_panitia}</td>
<td>{val.jabatan}</td>
<td>{val.divisi}</td>
<td>{val.tanggal.toString().slice(0,10)}</td>
<td>{val.deskripsi}</td>
</tr>
)
})
return data
}
render() {
if(this.state.dataEvent === null || this.state.dataMou === null || this.state.dataSurat===null || this.state.events === null){
return(
<Backdrop open={true}>
<CircularProgress color="inherit" />
</Backdrop>
)
}
return (
<div className="container-fluid" style={{marginTop:'80px'}}>
<Sidebar/>
<div className="border rounded p-4" style={{marginLeft:'320px', marginBottom:'23px', height:'680px'}}>
<h1 className="text-center mb-4">{this.state.dataEvent.namaEvent}</h1>
<div className="row">
<div className="col-8 border rounded-lg p-0">
<h2 className="text-center text-white" style={{backgroundColor:'#363755'}}>Agenda</h2>
<DnDCalendar
className="mx-4"
defaultDate={moment().toDate()}
defaultView="month"
events={this.state.events}
onDoubleClickEvent={this.toggleEdit}
localizer={localizer}
// onEventDrop={this.onEventDrop}
// onEventResize={this.onEventResize}
resizable
style={{ height: "56vh" }}
/>
</div>
<div className="col-4 border rounded-lg p-0">
<h2 className="text-center text-white" style={{backgroundColor:'#363755'}}>Finance</h2>
<div className="px-3 row">
<div className="col-6">
<p>Total RAB :</p>
<p>Total Cash In :</p>
<p>Total Cash Out :</p>
<p>Balance :</p>
<p>RAB-Cash in : </p>
</div>
<div className="col-6">
<p className="font-weight-bold">Rp.{Intl.NumberFormat().format(this.state.totalBudget).replace(/,/g, '.')}</p>
<p className="font-weight-bold">Rp.{Intl.NumberFormat().format(this.state.totalPemasukan).replace(/,/g, '.')}</p>
<p className="font-weight-bold">Rp.{Intl.NumberFormat().format(this.state.totalPengeluaran).replace(/,/g, '.')}</p>
<p className="font-weight-bold">Rp.{Intl.NumberFormat().format(this.state.saldo).replace(/,/g, '.')}</p>
<p className="font-weight-bold">Rp.{Intl.NumberFormat().format(this.state.totalPemasukan - this.state.totalBudget).replace(/,/g, '.')}</p>
</div>
</div>
</div>
</div>
<div className="row">
<div className="col-12 mt-3 border rounded-lg p-0">
<h2 className="text-center text-white" style={{backgroundColor:'#363755'}}>Archiving</h2>
<div className="px-3">
<p>Mail In : {this.state.mailIn}</p>
<p>Mail Out : {this.state.mailOut}</p>
<h1 className="text-center">Surat Terakhir</h1>
<table className="table table-bordered table-hover">
<thead>
<tr>
<th>No Surat</th>
<th>Tanggal Masuk</th>
<th>Tanggal Keluar</th>
<th>Perihal</th>
<th>Surat Dari</th>
<th>Kepada</th>
<th>PJ</th>
</tr>
</thead>
<tbody>
{this.renderSurat()}
</tbody>
</table>
</div>
<div className="px-5">
<h1 className="text-center">MoU Terakhir</h1>
<table className="table table-bordered table-hover">
<thead>
<tr>
<th>Nama Instansi</th>
<th>Nama Panitia</th>
<th>Jabatan</th>
<th>Divisi</th>
<th>Tanggal Kontrak</th>
<th>Isi Kontrak</th>
</tr>
</thead>
<tbody>
{this.renderMou()}
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
)
}
}
export default Dashboard
|
export default function parseURLQuery(query) {
const result = {};
for (const segment of query.split('&')) {
const equalIndex = segment.indexOf("=");
if (equalIndex > -1) {
const key = segment.slice(0, equalIndex);
const value = segment.slice(equalIndex + 1);
result[decodeURIComponent(key)] = decodeURIComponent(value);
}
}
return result;
}
|
import { createAsyncThunk, createEntityAdapter, createSlice } from '@reduxjs/toolkit'
import PouchDb from 'pouchdb'
import PouchDbFind from 'pouchdb-find'
import moment from 'moment'
import omit from 'lodash/omit'
PouchDb.plugin(PouchDbFind)
const db = new PouchDb('scans')
db.createIndex({ index: { fields: ['order'] } })
db.createIndex({ index: { fields: ['patientId'] } })
const list = createAsyncThunk(
'scans/list',
async ({ appointmentId, patientId }) => {
const response = await db.find({
sort: [{ order: 'desc' }],
selector: appointmentId ? {
patientId,
appointmentId,
order: { $exists: true }
} : {
patientId,
order: { $exists: true }
}
})
return response.docs
}
)
const add = createAsyncThunk(
'scans/add',
async payload => {
const newScan = {
order: (await db.info()).doc_count,
date: moment().format('YYYY-MM-DD @ HH:mm'),
...omit(payload, ['mesh'])
}
const { id, rev } = await db.post(newScan)
await db.putAttachment(
id,
'scan.ply',
rev,
// eslint-disable-next-line no-undef
new Blob([payload.mesh], { type: 'application/octet-stream' }),
'application/octet-stream'
)
return {
...newScan,
_id: id
}
}
)
const update = createAsyncThunk(
'scans/update',
async payload => {
await db.put(payload)
return payload
}
)
const details = createAsyncThunk(
'scans/details',
async (id, { dispatch }) => {
try {
const scan = await db.get(id, {
attachments: true
})
return scan
} catch (e) {
console.error(e)
}
}
)
const load = createAsyncThunk(
'scans/load',
async (id, { dispatch }) => {
try {
const scan = await db.get(id, {
attachments: true
})
return scan
} catch (e) {
console.error(e)
}
}
)
export async function getLastScan (patientId) {
const lastScan = await db.find({
limit: 1,
sort: [{ order: 'desc' }],
selector: {
patientId,
order: { $exists: true }
}
})
if (lastScan.docs[0]) {
return db.get(lastScan.docs[0]._id, {
attachments: true
})
}
return null
}
const editScan = createAsyncThunk(
'scans/edit',
async id => {
return db.get(id, {
attachments: false
})
}
)
const remove = createAsyncThunk(
'scans/remove',
async payload => {
return db.remove(payload)
}
)
const adapter = createEntityAdapter({
selectId: ({ _id }) => _id
})
const slice = createSlice({
name: 'scans',
initialState: adapter.getInitialState({
loading: false,
current: undefined,
error: null,
loadedScans: {}
}),
reducers: {
add: adapter.addOne,
update: adapter.updateOne,
remove: adapter.removeOne
},
extraReducers: {
[list.pending]: state => {
state.loading = true
},
[list.fulfilled]: (state, { payload }) => {
adapter.setAll(state, payload)
state.loading = false
},
[details.pending]: state => {
state.current = undefined
state.loading = true
},
[load.pending]: state => {
state.loading = true
},
[load.fulfilled]: (state, { payload }) => {
console.info({ payload })
state.loadedScans[payload._id] = payload
state.loading = false
},
[details.fulfilled]: (state, { payload }) => {
state.current = payload
state.loading = false
},
[editScan.pending]: state => {
state.current = undefined
state.loading = true
},
[editScan.fulfilled]: (state, { payload }) => {
state.current = payload
state.loading = false
},
[add.fulfilled]: (state, { payload }) => {
state.current = payload
state.loading = false
},
[update.fulfilled]: (state, { payload }) => {
state.current = payload
},
[remove.fulfilled]: state => {
state.current = undefined
}
}
})
export const actions = { update, add, remove, list, details, editScan, load }
export const selectors = {
current: state => state.scans.current,
loading: state => state.scans.loading,
...adapter.getSelectors(state => state.scans),
loadedScans: state => state.scans.loadedScans
}
export default slice.reducer
|
/* eslint-disable no-console */
const chalk = require('chalk')
function logCli(msgType, message) {
if (message && typeof message === 'string') {
console.log(
chalk.bgBlue.black(` ${msgType.toUpperCase()} `),
`${message.toUpperCase()}`
)
} else if (msgType && typeof msgType === 'string') {
console.log(chalk.bgBlue.black(` ${msgType.toUpperCase()} `))
}
}
module.exports = logCli
|
/*
Mon Oct 20 2014 21:00:11 GMT+0800 (CST)
combined files by KMD:
easydialog/kissy5.0_code/index.js
easydialog/kissy5.0_code/alert.js
easydialog/kissy5.0_code/common.js
easydialog/kissy5.0_code/confirm.js
easydialog/kissy5.0_code/prompt.js
*/
define('kg/easydialog/2.5.0/index',["./alert","./confirm","./prompt"],function(require, exports, module) {
/**
* @fileoverview 基于Overlay.Dialog dd封装了alert,confirm,prompt,使用dialog会很简单
* @author bofang.zxj<bofang.zxj@taobao.com>
* @module easydialog
**/
var Alert = require('./alert');
var Confirm = require('./confirm');
var Prompt = require('./prompt');
module.exports = {
alert: Alert,
confirm: Confirm,
prompt: Prompt
};
});
define('kg/easydialog/2.5.0/alert',["util","base","node","./common"],function(require, exports, module) {
/**
* @fileoverview 基于Overlay.Dialog dd封装了alert
* @author bofang.zxj<bofang.zxj@taobao.com>
* @module easydialog
**/
var Util = require('util');
var Base = require('base');
var Node = require('node');
var Common = require('./common');
var $ = Node.all;
var TPL_BODY = '<div class="ks-easy-dialog ks-easy-dialog-ok">' + '<div class="ks-easy-dialog-head">{title}</div>' + '<div class="ks-easy-dialog-body">' + '<div class="ks-easy-dialog-title">{content}</div>' + '<p class="ks-easy-dialog-btn-content">' + '<button class="ks-easy-dialog-yes J_KsDialogOkBtn J_KsEasyDialogBtn">\u786E\u5B9A</button></p>' + '</div>';
'</div>';
function Alert() {
Alert.superclass.constructor.call(this);
}
;
/**
* 绑定事件
* @param {Object} oDialog dialog名
* @param {Function} callback callback 函数
*/
function bindEvent(oDialog, callback) {
oDialog.on('afterRenderUI', function () {
var elContent = $(oDialog.get('el'));
var elBtn = elContent.all('.J_KsEasyDialogBtn');
elBtn.on('click', function (e) {
oDialog.destroy();
callback && callback({ result: true });
});
});
}
Util.extend(Alert, Base, {
/**
* 模拟window.prompt
* @param {String} message 提示的信息
* @param {Object} config 配置信息
* @param {Function} callback 回调函数
* @return {Obejct} dialog
*/
alert: function (message, config, callback) {
var oParseData = Common.parseData(config, callback);
var oConfig = oParseData.config;
var oEasyDialog = Common.getDialog(oConfig);
var funcCallback = oParseData.callback;
// 设置内容
Common.setContent(oEasyDialog, TPL_BODY, {
title: oConfig.title,
content: message
});
// 事件绑定
bindEvent(oEasyDialog, funcCallback);
oEasyDialog.show();
// 拖动配置
oConfig.isNeedDrag && Common.setDragAble(oEasyDialog);
return oEasyDialog;
}
});
module.exports = new Alert().alert;
});
define('kg/easydialog/2.5.0/common',["util","node","overlay","dd"],function(require, exports, module) {
/**
* @fileoverview alert,confirm,prompt通用的模块
* @author bofang.zxj<bofang.zxj@taobao.com>
* @module easydialog
**/
var Util = require('util');
var Node = require('node');
var Overlay = require('overlay');
var DD = require('dd');
var re = {};
var $ = Node.all;
var DOMAIN = document.domain;
/**
* Dialog 默认参数配置
* @type {Object}
*/
var oDefaultConfig = {
title: DOMAIN + ' \u7F51\u9875\u63D0\u793A',
isNeedDrag: true,
theme: 'gallery/easydialog/1.1/theme/theme-tb.css',
width: 350,
height: 110,
zIndex: 9999,
closable: true,
prefixCls: 'ks-easydialog-',
closeAction: 'destroy',
mask: true,
effect: {},
align: {
points: [
'cc',
'cc'
]
}
};
Util.mix(re, {
/**
* 处理传入的参数
* @param {Object} config 配置参数
* @param {Function} callback 函数名
* @return {Obejct} {config:Object,callback:Function}
*/
parseData: function (config, callback) {
var reConfig;
var reCallback;
if (Util.isPlainObject(config)) {
reConfig = Util.mix(oDefaultConfig, config);
} else if (Util.isFunction(config)) {
reConfig = oDefaultConfig;
callback = config;
} else {
// S.log('easydialog params are error !');
reCallback = callback;
reConfig = oDefaultConfig;
}
if (Util.isFunction(callback)) {
reCallback = callback;
}
// 加载css
this.loadCss(reConfig.theme);
return {
config: reConfig,
callback: reCallback
};
},
/**
* 获取Dialog
* @param {Object} config 配置信息
* @return {Object} Overlay
*/
getDialog: function (config) {
return new Overlay.Dialog(config);
},
/**
* 设置dialog可以拖动
* @param {Object} oDialog dialog对象
* @return {Object}
*/
setDragAble: function (oDialog) {
var elContent = $(oDialog.get('el'));
var elTxt = elContent.one('.J_KsEasyDialogPromptTxt');
var self = this;
var oDD;
oDD = self._initDD(elContent);
//输入框focus的时候不需要拖动
if (elTxt) {
elContent.on('mousedown', function () {
if (!oDD) {
oDD = self._initDD(elContent);
} // !oDD &&
});
elTxt.on('mousedown', function (e) {
oDD && oDD.destroy();
oDD = null;
});
}
},
_initDD: function (el) {
return new DD.Draggable({
node: el,
cursor: 'move',
move: true
});
},
/**
* 加载css
* @param {String} cssUrl css路劲
* @return {Object} this
*/
loadCss: function (cssUrl) {
if (cssUrl && Util.isString(cssUrl)) {
require(cssUrl);
}
return this;
},
/**
* 设置dialog内容
* @param {Object} oDialog dialog对象
* @param {String} body 的html内容
* @param {Object} oContent 内容对象
* @param {String} head dialog的title
* @param {String} body dialog的body内容
* @return {Object} this
*/
setContent: function (oDialog, strHtml, oContent) {
// alert(strHtml)
oDialog.set('bodyContent', Util.substitute(strHtml, oContent));
return this;
}
});
module.exports = re;
});
define('kg/easydialog/2.5.0/confirm',["util","base","node","./common"],function(require, exports, module) {
/**
* @fileoverview 基于Overlay.Dialog dd封装confirm
* @author bofang.zxj<bofang.zxj@taobao.com>
* @module easydialog
**/
var Util = require('util');
var Base = require('base');
var Node = require('node');
var Common = require('./common');
var $ = Node.all;
var TPL_BODY = '<div class="ks-easy-dialog ks-easy-dialog-confirm">' + '<div class="ks-easy-dialog-head">{title}</div>' + '<div class="ks-easy-dialog-body J_KsEasyDialogBody">' + '<div class="ks-easy-dialog-title">{content}</div>' + '<p class="ks-easy-dialog-btn-content"><button class="ks-easy-dialog-yes J_KsDialogOkBtn J_KsEasyDialogBtn" >\u786E\u5B9A</button>' + '<button class="ks-easy-dialog-no J_KsDialogNoBtn J_KsEasyDialogBtn">\u53D6\u6D88</button></p>' + '</div>';
'</div>';
var DOMAIN = document.domain;
function Confirm() {
Confirm.superclass.constructor.call(this);
}
;
/**
* 绑定事件
* @param {Object} oDialog dialog名
* @param {Function} callback callback 函数
*/
function bindEvent(oDialog, callback) {
oDialog.on('afterRenderUI', function () {
var elContent = $(oDialog.get('el'));
var elBtn = elContent.all('.J_KsEasyDialogBtn');
elBtn.on('click', function (e) {
var elTarget = $(e.target);
var result = elTarget.hasClass('ks-easy-dialog-yes');
oDialog.destroy();
callback && callback({ result: result });
});
});
}
Util.extend(Confirm, Base, {
/**
* 模拟window.prompt
* @param {String} message 提示的信息
* @param {Object} config 配置信息
* @param {Function} callback 回调函数
* @return {Obejct} dialog
*/
confirm: function (message, config, callback) {
// S.log(callback);
var oParseData = Common.parseData(config, callback);
var oConfig = oParseData.config;
var oEasyDialog = Common.getDialog(oConfig);
var funcCallback = oParseData.callback;
// 设置内容
Common.setContent(oEasyDialog, TPL_BODY, {
title: oConfig.title,
content: message
});
// 事件绑定
bindEvent(oEasyDialog, funcCallback);
oEasyDialog.show();
// 拖动配置
oConfig.isNeedDrag && Common.setDragAble(oEasyDialog);
}
});
module.exports = new Confirm().confirm;
});
define('kg/easydialog/2.5.0/prompt',["util","base","node","./common"],function(require, exports, module) {
/**
* @fileoverview 基于Overlay.Dialog dd封装prompt
* @author bofang.zxj<bofang.zxj@taobao.com>
* @module easydialog
**/
var Util = require('util');
var Base = require('base');
var Node = require('node');
var Common = require('./common');
var $ = Node.all;
var TPL_BODY = '<div class="ks-easy-dialog ks-easy-dialog-prompt">' + '<div class="ks-easy-dialog-head">{title}</div>' + '<div class="ks-easy-dialog-body">' + '<div class="ks-easy-dialog-prompt-title">{content}</div>' + '<p class="ks-easy-dialog-txt">' + '{inputType}' + '</p><p class="ks-easy-dialog-btn-content"><button class="ks-easy-dialog-yes J_KsEasyDialogBtn" >\u786E\u5B9A</button>' + '<button class="ks-easy-dialog-no J_KsEasyDialogBtn">\u53D6\u6D88</button></p>' + '</div>' + '</div>';
var TPL_TXT_TYPE_INPUT = '<input type="text" class="ks-easy-dialog-prompt-txt J_KsEasyDialogPromptTxt">';
var TPL_TXT_TYPE_TEXTAREA = '<textarea class="ks-easy-dialog-prompt-textarea J_KsEasyDialogPromptTxt"></textarea>';
/**
* Prompt 类
*/
function Prompt() {
Prompt.superclass.constructor.call(this);
}
;
/**
* 绑定事件
* @param {Object} oDialog dialog名
* @param {Function} callback callback 函数
*/
function bindEvent(oDialog, callback) {
oDialog.on('afterRenderUI', function () {
var elContent = $(oDialog.get('el'));
var elBtn = elContent.all('.J_KsEasyDialogBtn');
var elTxt = elContent.all('.J_KsEasyDialogPromptTxt');
Util.later(function () {
elTxt.fire('focus');
}, 100);
elBtn.on('click', function (e) {
var elTarget = $(e.target);
var result = elTarget.hasClass('ks-easy-dialog-yes');
var txt = result ? elTxt.val() : null;
oDialog.destroy();
callback && callback({
txt: txt,
result: result
});
});
});
}
Util.extend(Prompt, Base, {
/**
* 模拟window.prompt
* @param {String} message 提示的信息
* @param {Object} config 配置信息
* @param {Function} callback 回调函数
* @return {Obejct} dialog
*/
prompt: function (message, config, callback) {
var oParseData = Common.parseData(config, callback);
var oConfig = oParseData.config;
var oEasyDialog = Common.getDialog(oConfig);
var funcCallback = oParseData.callback;
// 设置内容
Common.setContent(oEasyDialog, TPL_BODY.replace('{inputType}', oConfig.inputType ? TPL_TXT_TYPE_TEXTAREA : TPL_TXT_TYPE_INPUT), {
title: oConfig.title,
content: message
});
bindEvent(oEasyDialog, funcCallback);
oEasyDialog.show();
// 拖动配置
oConfig.isNeedDrag && Common.setDragAble(oEasyDialog);
//console.log(oEasyDialog.get('el'));
return oEasyDialog;
}
});
module.exports = new Prompt().prompt;
});
|
$(function(){
// 隐藏视频控制框
setTimeout(function(){
var video=document.getElementsByClassName("yl_video")[0];
video.controls=false;
if(video.currentTime>=2*60){
video.controls=true;}
},10)
// 回到顶部
$(window).on("scroll", function() {
var h = $(window).scrollTop();
if(h > 50) {
$(".back-top").css("display", "block");
} else {
$(".back-top").css("display", "none");
}
});
$(".back-top").click(function() {
$("html,body").animate({
scrollTop: 0
}, 500);
});
// 切换课程类型
$(".type_box").first().show();
$(".class_list li").click(function(){
$(this).addClass("active").siblings().removeClass("active");
$(".type_box").hide();
$(".type_box").eq($(this).index()).show();
})
})
|
jQuery(document).ready(function($){
// image upload js for homepage
$('.upload-wrap input[type=file]').change(function () {
var id = $(this).attr('id');
var newimage = new FileReader();
newimage.readAsDataURL(this.files[0]);
newimage.onload = function (e) {
$('#bg').css('background-image', 'url("./img/image.png")');
$('.uploadpreview.' + id).css('background-image', 'url(' + e.target.result + ')');
};
$('<span class="close-btn"><img src="./img/clear.png" alt="close">').insertAfter(this);
});
$(document).on('click', 'span.close-btn', function () {
$($(this)[0].previousElementSibling.previousElementSibling).css('background-image', '');
$(this).remove();
});
// Tab JS
$('.tabs a').click(function(){
$('.panel').hide();
$('.tabs a.active').removeClass('active');
$(this).addClass('active');
var panel = $(this).attr('href');
$(panel).fadeIn(1000);
return false; // prevents link action
}); // end click
$('.tabs li:first a').click();
// js for color selections
$(".single-color-item.addclass").on("click", function(){
$(".single-color-item.addclass").removeClass("active");
$(this).addClass("active");
});
$(".single-color-item.color-picker").on("click", function(){
$(".single-color-item.addclass").removeClass("active");
});
// js for redo-undo-btns
$(".redo-undo-btns").on("click", function(){
$(".redo-undo-btns").removeClass("active");
$(this).addClass("active");
});
// js for text-alignment
$(".single-font-alignment").on("click", function(){
$(".single-font-alignment").removeClass("active");
$(this).addClass("active");
});
// JS for font selection section
$(".font-change-btn").on("click", function(){
$(".font-change").toggleClass("active");
});
$(".font-change-btn").on("click", function(){
$(".overlay").toggleClass("active");
});
$(".overlay").on("click", function(){
$(".overlay, .font-change").removeClass("active");
});
// JS for range slider
var slider = document.getElementById("slider");
slider.oninput = function() {
$('.fill').css('width', this.value + '%');
}
var slider = document.getElementById("slider2");
slider.oninput = function() {
$('.fill2').css('width', this.value + '%');
}
var slider = document.getElementById("slider3");
slider.oninput = function() {
$('.fill3').css('width', this.value + '%');
}
// js for text-alignment
$(".slider.round").on("click", function(){
$(".color-box, .range-wrapper, .bottom-section, .font-change, .overlay, .tabs, .overlay2, .toggle-button, .redo-undo-buttons").toggleClass("disbale");
});
});
|
app.controller('SiteController', function($scope, $routeParams, $location) {
});
|
var o = function() {
function r() {
this.currentCount = 0, this.limitCount = 0, this.propId = 0, this.propIcon = "";
}
return r.get = function(a, e, t, o) {
void 0 === o && (o = "");
var i = new r();
return i.propId = a, i.currentCount = e, i.limitCount = t, i.propIcon = o, i;
}, r;
}();
exports.default = o;
|
import inquirer from 'inquirer';
export function queryCommands() {
return inquirer.prompt([
{
type: 'list',
name: 'command',
message: 'choose: ',
choices: [
{ name: 'Create file', value: 'createFile' },
{ name: 'Create folder', value: 'createFolder' },
{ name: 'Delete file', value: 'deleteFile' },
{ name: 'Delete folder', value: 'deleteFolder' },
{ name: 'Display disk status', value: 'displayDiskStatus' },
{
name: 'Display disk structure',
value: 'displayDiskStructure'
},
{ name: 'Exit', value: 'exit' }
]
}
]);
}
export function queryDirectory() {
return inquirer.prompt([
{
name: 'directory',
message: 'Enter Directory: '
}
]);
}
export function queryDirectoryAndSize() {
return inquirer.prompt([
{
name: 'directory',
message: 'Enter Directory: '
},
{
type: 'number',
name: 'size',
message: 'Enter file size: '
}
]);
}
export function queryAllocationType() {
return inquirer.prompt([
{
type: 'list',
name: 'allocationType',
message: 'choose: ',
choices: [
{ name: 'Contiguous Allocation', value: 'contiguous' },
{ name: 'Linked Allocation', value: 'linked' },
{ name: 'Indexed Allocation', value: 'indexed' }
]
}
]);
}
export default { queryDirectory, queryDirectoryAndSize };
|
import React from 'react'
import { Appbar } from 'react-native-paper'
const ToolBar = ({ title, statusBarHeight, action }) => {
const Action = action ?
<Appbar.BackAction
onPress={action}
/> : null
return (
<Appbar.Header statusBarHeight={statusBarHeight} >
{Action}
<Appbar.Content titleStyle={ !action ? {textAlign: 'center'} : null} title={title} />
</Appbar.Header>
)
}
export default ToolBar
|
export const value1 = 1;
export const value2 = 2;
export const value3 = 3;
export const value4 = 4;
export const value5 = 5;
export const value6 = 6;
export const value7 = 7;
export const value8 = 8;
export const value9 = 9;
export const value10 = 10;
export const value11 = 11;
export const value12 = 12;
export const value13 = 13;
export const value14 = 14;
export const value15 = 15;
export const value16 = 16;
export const value17 = 17;
export const value18 = 18;
export const value19 = 19;
export const value20 = 20;
export const value21 = 21;
export const value22 = 22;
export const value23 = 23;
export const value24 = 24;
export const value25 = 25;
export const value26 = 26;
export const value27 = 27;
export const value28 = 28;
export const value29 = 29;
export const value30 = 30;
export const value31 = 31;
export const value32 = 32;
export const value33 = 33;
export const value34 = 34;
export const value35 = 35;
export const value36 = 36;
export const value37 = 37;
export const value38 = 38;
export const value39 = 39;
export const value40 = 40;
export const value41 = 41;
export const value42 = 42;
export const value43 = 43;
export const value44 = 44;
export const value45 = 45;
export const value46 = 46;
export const value47 = 47;
export const value48 = 48;
export const value49 = 49;
|
$('.btn-reject').click(function(){
$('input[name="vendor_draft_id"]').val($(this).attr('data-id'));
$('.modal_reject').modal('show');
});
$('.btn-reject-submit').click(function(){
$(this).attr('disabled', 'disabled');
$(this).html('Please wait...');
$.post($('#reject_url').val(), $('.modal_reject form').serialize() , function(json){
$(this).removeAttr('disabled');
$(this).html('Submit');
$('.modal_reject').modal('hide');
location = json.location;
});
});
|
/**
* enable fetching object consequential peroperties
* example:
* var foo = {bar: {foo: 3}}
* foo.get('bar.foo') === 3
*/
Object.prototype.get = function (prop) {
const segs = prop.split('.');
let result = this;
let i = 0;
while (result && i < segs.length) {
result = result[segs[i]];
i++;
}
return result;
}
/**
* set consequential peroperty a value
* @example:
* var foo = {};
* foo.set('foo.bar', 3);
* foo is now {foo: {bar: 3}}
*/
Object.prototype.set = function (prop, val) {
const segs = prop.split('.');
let target = this;
let i = 0;
while (i < segs.length) {
if (typeof target[segs[i]] === 'undefined') {
target[segs[i]] = i === segs.length - 1 ? val : {};
} else if (i === segs.length - 1) {
target[segs[i]] = val;
}
target = target[segs[i]];
i++;
}
}
/**
* update style attribute of a node, by an obj
*/
const setStyle = (node, styleObj) => {
Object.assign(node.style, styleObj);
}
/**
* all watchers, to be dirty-checked every time
*/
const Watchers = {
root: {},
currentWatcherStack: []
};
/**
* check watcher value change and update
*/
function triggerWatcher(watcher) {
console.group('triggerWatcher', watcher.expression);
let newV = watcher.val();
if (watcher.isModel) {
watcher.update(undefined, newV || '');
watcher.oldV = newV;
} else if (!watcher.isArray && (0 !== newV)) {
watcher.update(0, newV);
watcher.oldV = newV;
} else if (watcher.isArray) {
let oldV = watcher.oldV || [];
diff(oldV, newV, watcher.update.add, watcher.update.remove)
watcher.oldV = newV.slice(0);
}
console.groupEnd();
}
/**
* add setter watchers
* @param {Watcher} watcher - watcher to bind
* @param {Array} location - watchers array in setter
*/
function bindWatcherOnSetter(watcher, setterLocation) {
watcher.locations = watcher.locations || new Set();
if (!watcher.locations.has(setterLocation)) {
watcher.locations.add(setterLocation);
}
if (!setterLocation.has(watcher)) {
setterLocation.add(watcher);
}
}
/**
* remove setter watchers
* @param {Watcher} watcher - watcher to bind
*/
function unwatch(watcher) {
let list = watcher.parent.childs;
list.splice(list.indexOf(watcher), 1);
watcher.locations.forEach(loc => {
loc.delete(watcher);
});
}
|
const users = [
{
id:1,
name:'Tanya Sinclair',
text: 'I’ve been interested in coding for a while but never taken the jump, until now. I couldn’t recommend this course enough. I’m now in the job of my dreams and so excited about the future. ',
job: "UX Engineer",
imagen: "images/image-tanya.jpg"
},
{
id:2,
name:'John Tarkpor',
text: '“ If you want to lay the best foundation possible I’d recommend taking this course. The depth the instructors go into is incredible. I now feel so confident about starting up as a professional developer. ”',
job: "Junior Front-end Developer",
imagen: "images/image-john.jpg"
}
]
let text = document.querySelector(".testimony");
let author = document.querySelector("#name");
let job = document.querySelector("#job");
let img = document.querySelector("#person-img")
let prevBtn = document.querySelector(".prev-btn");
let nextBtn = document.querySelector(".next-btn");
let currentItem = 0;
window.addEventListener('DOMContentLoaded', function(){
person(currentItem);
})
const person = (p) => {
const item = users[p];
img.src = item.imagen;
author.textContent = item.name;
job.textContent = item.job;
text.textContent = item.text;
}
nextBtn.addEventListener("click", function() {
(currentItem > users.length-2)?currentItem=0:currentItem++;
person(currentItem)
})
prevBtn.addEventListener("click", function() {
(currentItem <= 0)?currentItem=users.length-1:currentItem--;
person(currentItem)
})
|
import Button from "components/website/button/Button";
import asset from "plugins/assets/asset";
import Title from "components/website/pages/home/section-news/title/TitleStyle1";
import { useRouter } from "next/router";
import { ListNews } from "components/website/pages/news/list-news/ListNews";
import { Row, Wrapper } from "components/website/pages/news/NewsElements";
import { MainContent } from "components/website/contexts/MainContent";
import { useEffect, useRef, useState, useContext } from "react";
export default function News({
urlBackground = asset("/images/bg-session-news-home.jpg"),
}) {
const valueLanguageContext = useContext(MainContent);
const [dataSectionNews, setDataSectionNews] = useState()
const Language = {
en: {
name: "en",
title : "News",
nameButton:"VIEW ALL NEWS"
},
vi: {
name: "vi",
title : "Tin Tức",
nameButton:"Xem tất cả"
}
}
const router = useRouter();
const getLink = ()=>{
router.push("/news");
}
useEffect(() => {
if (valueLanguageContext.languageCurrent) {
setDataSectionNews(Language[`${valueLanguageContext.languageCurrent}`])
}
}, [])
useEffect(() => {
if (valueLanguageContext.languageCurrent) {
setDataSectionNews(Language[`${valueLanguageContext.languageCurrent}`])
}
}, [valueLanguageContext.languageCurrent]);
return (
<section>
<div
className="sectionNewsHome"
style={{
background: `url(${asset(
"/images/bg-session-news-home.jpg"
)}) no-repeat center top/100% 100%`,
}}
>
{/* <img className="bgNewsHome" src={urlBackground}/> */}
{/* <Title textLine1={"news"} style={{ position: " relative" }}></Title> */}
{
dataSectionNews ? (
<Title
textLine1={dataSectionNews.title}
style={{ position: " relative" }}
/>
) :<Title textLine1={"news"} style={{ position: " relative" }}></Title>
}
<div className="containerNewsHome">
<Wrapper>
<Row>
<ListNews
title={"OTHER NEWS"}
color="#004FC4"
linkData={`https://api.lipovitan.zii.vn/api/v1/posts?limit=3`}
></ListNews>
</Row>
<div className="center">
{
dataSectionNews
? <Button cbFunction={getLink}>{dataSectionNews.nameButton}</Button>
: <Button cbFunction={getLink}>view all news</Button>
}
</div>
</Wrapper>
</div>
</div>
<style jsx>{`
.bgNewsHome {
width: 100%;
}
.sectionNewsHome {
position: relative;
padding: 50px 0;
}
.containerNewsHome {
width: 100%;
//position: absolute;
//width: 100%;
//left: 50%;
//top: 50%;
//transform: translate(-50%, -40%);
display: flex;
justify-content: center;
}
.center {
display: flex;
justify-content: center;
}
@media screen and (max-width: 1440px) {
.containerBannerTop {
bottom: 7%;
}
}
`}</style>
</section>
);
}
|
$(function() {
// Set up the background image by creating a new image element inside a div
// that takes up the entire screen and is centered to accomadate for large
// images.
var root = $("#root");
var imgSrc = root.data("image-src");
var container = $("<div>");
container.css("z-index", -100);
container.css("position", "fixed");
container.css("top", 0);
container.css("left", 0);
container.css("overflow", "hidden");
container.css("width", $(window).width());
container.css("height", $(window).height());
container.css("transform", "transform3d(0, 0, 0)");
var img = $("<img>");
img.attr("src", imgSrc);
if ($(window).width() > 1200) {
img.css("width", $(window).width());
img.css("height", "auto");
img.css("top", 0);
img.css("bottom", 0);
img.css("margin", "auto");
img.css("left", 0);
} else {
img.css("height", $(window).height() + 300);
img.css("width", "auto");
img.css("top", 0);
img.css("bottom", -60);
}
img.css("position", "absolute");
container.append(img);
$("body").prepend(container);
headers = [$("#projects-header"), $("#research-header"), $("#work-header")];
contents = [$("#projects"), $("#research"), $("#work")];
for (var i = 0; i < headers.length; i++) {
(function(i) {
headers[i].click(function() {
var el = contents[i];
var toggle;
var display = el.css("display");
if (display === "none") {
toggle = "block";
headers[i].addClass("active");
for (var j = 0; j < headers.length; j++) {
if (j != i) {
headers[j].removeClass("active");
}
}
} else if (display === "block") {
toggle = "none";
headers[i].removeClass("active");
}
var toggled = false;
for (var j = 0; j < contents.length; j++) {
if (contents[j].is(":visible")) {
contents[j].fadeOut("200", function() {
if (j != i) {
contents[i].fadeIn("200");
}
});
toggled = true;
break;
}
}
if (!toggled) {
contents[i].fadeIn("slow");
}
});
})(i);
}
});
|
import React from 'react';
import styled from 'styled-components';
import { FieldPrimary } from '../../../../lib/elements/field';
import { FieldLayout } from '../../../../lib/elements/layout'
import { SubmitButton } from '../../../../lib/elements/button'
import { ErrorMessage, PendingMessage } from '../../../../lib/elements/message';
import { Loader } from '../../../../lib/elements/loader';
import { spacing } from '../../../../lib/theme';
export const LoginFormComponent = (props) => {
const {
fieldLogin,
fieldPassword,
values,
errors,
touched,
handleChange,
handleBlur,
handleSubmit,
isPending,
isError,
isSuccess,
errorMessage,
pageLoading,
} = props;
const isFieldErr = name => {
return errors[name] && touched[name] && errors[name]
};
const isSubmitDisabled = () => {
return isPending || isSuccess;
};
return (
<form onSubmit={handleSubmit}>
<Container>
{pageLoading && <Loader/>}
<FieldLayout>
<FieldPrimary
titleTid={'SIGNUP.SIGNUP_FORM.FIELD.LOGIN.TITLE'}
placeholderTid={'SIGNUP.SIGNUP_FORM.FIELD.LOGIN.PLACEHOLDER'}
name={fieldLogin}
onChange={handleChange}
onBlur={handleBlur}
value={values[fieldLogin]}
error={isFieldErr(fieldLogin)}
/>
<FieldPrimary
type='password'
titleTid={'SIGNUP.SIGNUP_FORM.FIELD.PASSWORD.TITLE'}
placeholderTid={'SIGNUP.SIGNUP_FORM.FIELD.PASSWORD.PLACEHOLDER'}
name={fieldPassword}
onChange={handleChange}
onBlur={handleBlur}
value={values[fieldPassword]}
error={isFieldErr(fieldPassword)}
/>
</FieldLayout>
<SubmitButton
type="submit"
disabled={isSubmitDisabled()}
titleTid={'SIGNUP.SIGNUP_FORM.SUBMIT_BUTTON.TITLE'}
/>
<PendingMessage isPending={isPending} pendingMessageTId={'SIGNUP.SIGNUP_FORM.PENDING_MESSAGE.TITLE'}/>
<ErrorMessage isError={isError} errorMessage={errorMessage}/>
</Container>
</form>
);
};
const Container = styled.div`
display: grid;
gap: ${spacing(3)};
`;
|
import React from "react";
import styled from "styled-components";
import API from "../../module/api";
import { Container, Row, Col } from "reactstrap";
import { Button, Form, FormGroup, Input } from "reactstrap";
import { Textfit } from "react-textfit";
const Headline = styled(Textfit)`
text-align: center;
font-weight: bold;
color: #73777a;
margin: 0 10px 50px 10px;
`;
const ButtonSubmit = styled(Button)`
font-weight: bold !important;
background-color: #fd7e47 !important;
border: none !important;
:hover {
background-color: #f5692c !important;
}
`;
class Signin extends React.Component {
constructor(props) {
super(props);
this.state = { username: "", password: "", unauthen: false };
}
goBack = () => {
this.props.history.goBack();
}
submitHandler = event => {
event.preventDefault();
const query = {};
query.username = this.state.username;
query.password = this.state.password;
API.post("/login", query)
.then(res => {
if (res && res.data) {
const token = res.data.token;
localStorage.setItem("jwt", token || null);
this.goBack()
}
})
.catch(err => {
this.setState({ unauthen: true });
console.error(err);
});
};
changeHandler = event => {
let name = event.target.name;
let val = event.target.value;
this.setState({ [name]: val });
};
render() {
console.log(this.props);
const { unauthen } = this.state;
return (
<div
style={{
height: "100vh",
width: "100vw",
backgroundColor: "#F9F9F9"
}}
>
<Container style={{ paddingTop: "25vh" }}>
<div className="mx-auto my-0" style={{ maxWidth: "400px" }}>
<Headline mode="single">KNOWLEDGE BASE</Headline>
</div>
<Row>
<Col xs={8} className="mx-auto my-0">
<Form
onSubmit={this.submitHandler}
className="mx-auto my-0"
style={{ maxWidth: "350px" }}
>
<FormGroup>
<Input
onChange={this.changeHandler}
type="text"
name="username"
id="username"
placeholder="Usename"
/>
</FormGroup>
<FormGroup>
<Input
onChange={this.changeHandler}
type="password"
name="password"
id="password"
placeholder="Password"
/>
</FormGroup>
{unauthen && (
<p
style={{
fontSize: "0.75em",
fontStyle: "italic",
color: "red",
textAlign: "center"
}}
>
The username and password did not match. Please
try again.
</p>
)}
<ButtonSubmit type="submit" className="w-100">
SIGN IN
</ButtonSubmit>
</Form>
</Col>
</Row>
</Container>
</div>
);
}
}
export default Signin;
|
import { connect } from "react-redux";
import AdminsComponent from "../../Admin/AdminUser/admin";
import {
fetchAdmins,
deleteAdmins,
patchAdmin,
} from "../../actions/actions_admin_adminusers";
const mapStateToProps = state => ({
adminUser: state.adminUser,
});
const mapDispatchToProps = dispatch => ({
fetchAdmins: () => {
dispatch(fetchAdmins());
},
deleteAdmins: (adminID) => {
dispatch(deleteAdmins(adminID));
},
patchAdmin: (adminPatchDetails, adminID) => {
dispatch(patchAdmin(adminPatchDetails, adminID));
},
});
const Admins = connect(
mapStateToProps,
mapDispatchToProps,
)(AdminsComponent);
export default Admins;
|
#!/usr/bin/env node
// // Övning - dependencies
// const clc = require("cli-color");
// for (let i = 0; i <= 100; i += 1) {
// if (i % 2 === 0) {
// console.log(clc.blue(i));
// } else {
// console.log(clc.red(i));
// }
// }
//Övning - Publicera ett paket till npm
const clc = require("cli-color");
if (process.argv[2] === undefined) {
console.log("No Argument");
} else {
console.log(clc.bold.red(process.argv[2]));
}
|
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { withStyles } from 'material-ui/styles'
import { reduxForm, change } from 'redux-form'
import compose from 'recompose/compose'
import { connect } from 'react-redux'
import update from 'immutability-helper'
import Chip from 'material-ui/Chip'
import TextField from 'material-ui/TextField'
import Grid from 'material-ui/Grid'
const styles = theme => ({
chipContainer: {
margin: 10,
},
})
// eslint-disable-next-line
String.prototype.capitalize = function() {
return this.charAt(0).toUpperCase() + this.slice(1)
}
export class TagsInput extends Component {
constructor(props) {
super(props)
this.state = {
chips: [],
Key: {
backspace: 8,
tab: 9,
enter: 13,
},
INVALID_CHARS: /[^a-zA-Z0-9 ]/g,
}
}
static defaultProps = {
placeHolder: 'Enter a tag...',
maxLength: 20,
max: 20,
}
componentDidMount = () => {
this.setChips(this.props.chips)
}
componentWillReceiveProps = nextProps => {
this.setChips(nextProps.chips)
}
setChips = chips => {
if (chips && chips.length) {
this.setState({ chips: chips })
}
}
onKeyDown = event => {
var keyPressed = event.which
if (keyPressed === this.state.Key.enter || (keyPressed === this.state.Key.tab && event.target.value)) {
event.preventDefault()
this.updateChips(event)
} else if (keyPressed === this.state.Key.backspace) {
var chips = this.state.chips
if (!event.target.value && chips.length) {
this.deleteChip(chips[chips.length - 1])
}
}
}
updateChips = event => {
if (!this.props.max || this.state.chips.length < this.props.max) {
var value = event.target.value
if (!value) return
var chip = value.trim().capitalize()
if (chip && this.state.chips.indexOf(chip) < 0) {
this.setState({
chips: update(this.state.chips, { $push: [chip] }),
})
}
event.target.value = ''
}
}
deleteChip = chip => {
var index = this.state.chips.indexOf(chip)
if (index >= 0) {
this.setState({
chips: update(this.state.chips, {
$splice: [[index, 1]],
}),
})
}
}
focusInput = event => {
var children = event.target.children
if (children.length) {
children[children.length - 1].focus()
}
}
clearInvalidChars = event => {
var value = event.target.value
if (this.state.INVALID_CHARS.test(value)) {
event.target.value = value.replace(this.state.INVALID_CHARS, '')
} else if (value.length > this.props.maxLength) {
event.target.value = value.substr(0, this.props.maxLength)
}
}
render() {
var _this = this
const { classes } = this.props
var placeHolder = this.props.placeHolder
this.props.change('tags', this.state.chips)
return (
<div className={classes.chipContainer}>
<Grid container direction="row" spacing={8}>
{this.state.chips.map(function(chip, index) {
return (
<Grid item>
<Chip label={chip} key={index} onRequestDelete={_this.deleteChip.bind(null, chip)} />
</Grid>
)
})}
</Grid>
<TextField
placeholder={placeHolder}
inputProps={this.state.chips}
onKeyUp={this.clearInvalidChars}
onKeyDown={this.onKeyDown}
/>
</div>
)
}
}
const mapDispatchToProps = (dispatch, props) => ({
change: (name, value) => dispatch(change('AddEventForm', name, value)),
})
TagsInput.PropTypes = {
placeHolder: PropTypes.string.isRequired,
max: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
maxLength: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
}
export default compose(
withStyles(styles),
connect(mapDispatchToProps, null),
reduxForm({ form: 'AddEventForm', destroyOnUnmount: false, forceUnregisterOnUnmount: true })
)(TagsInput)
|
function forclear(){
document.getElementById('output').innerHTML="0";
}
function removeZero(){
let value=document.getElementById('output').innerHTML;
if (value=="0") {
value = " ";
document.getElementById("output").innerHTML = value;
}
}
function perc(){
let value=document.getElementById("output").innerHTML;
value=value/100;
document.getElementById('output').innerHTML= value;
}
function fordisplay(value){
removeZero();
document.getElementById("output").innerHTML += value;
}
function solve(){
removeZero();
let pt = document.getElementById('output').innerHTML;
let ketqua = eval(pt);
document.getElementById("output").innerHTML = ketqua;
}
|
const arryLi = [
'Սահմանադրություն',
'Սահմանադրական օրենք',
'Օրենսգիրք',
'Սահմանադրության փոփոխություններ',
'Օրենք',
'Հռչակագիր',
'Դեկլարացիա',
'Հրամանագիր',
'Ուղերձ',
'Որոշում',
'Համատեղ որոշում',
'Օրենքի ուժ ունեցող որոշում',
'Կարգ',
'Կարգադրություն',
'Հայտարարություն',
'Եզրակացություն',
'Դիմում',
'Հրահանգ',
'Հրաման',
'Համատեղ հրաման',
'Կանոններ',
'Կանոնադրություն',
'Կանոնակարգ',
'Պլենումի որոշում',
'Պարզաբանում',
'Իրազեկման թերթիկ',
'Հրահանգչական նամակ',
'Մեթոդական ցուցում',
'Ցանկ',
'Ցուցում',
'Պաշտոնական պարզաբանում',
'Պաշտոնական տեղեկատվություն',
'Պաշտոնական հաղորդագրություն',
'Տեղեկատվություն',
'Արձանագրային որոշում',
'Աշխատակարգային որոշում',
'Սահմանադրության նախագիծ',
'Վճիռ',
'ՄԻՋԱԶԳԱՅԻՆ ՊԱՅՄԱՆԱԳՐԵՐ',
'Միջազգային պայմանագիր',
'Խարտիա',
'Կոնվենցիա',
'Համաձայնագիր',
'Հյուպատոսական կոնվենցիա',
'Արձանագրություն',
'Եզրափակիչ ակտ',
'Փոխըմբռնման հուշագիր',
'Միջազգային դաշնագիր',
'Ֆակուլտատիվ արձանագրություն',
];
export { arryLi };
|
const express = require('express');
const apiController = require('../controllers/apiController');
const router = express.Router();
router.route('/news').get(apiController.getAllNews);
router.route('/news/:id').get(apiController.getNews);
router.route('/players').get(apiController.getAllPlayers);
router.route('/players/:id').get(apiController.getPlayer);
module.exports = router;
|
"use strict";
require("run-with-mocha");
const assert = require("assert");
const testTools = require("./_test-tools")
const IIRFilterNodeFactory = require("../../src/factories/IIRFilterNodeFactory");
describe("IIRFilterNodeFactory", () => {
it("should defined all properties", () => {
const IIRFilterNode = IIRFilterNodeFactory.create({}, class {});
const properties = testTools.getPropertyNamesToNeed("IIRFilterNode");
const notDefined = properties.filter((name) => {
return !Object.getOwnPropertyDescriptor(IIRFilterNode.prototype, name);
});
assert(notDefined.length === 0);
});
describe("instance", () => {
describe("constructor", () => {
it("audioContext.createIIRFilter()", () => {
const api = testTools.createAPI();
const context = new api.AudioContext();
const node = context.createIIRFilter([ 1, 0 ], [ 1, 0 ]);
assert(node instanceof api.IIRFilterNode);
});
it("new instance", () => {
const api = testTools.createAPI();
const context = new api.AudioContext();
const node = new api.IIRFilterNode(context, {
feedforward: [ 1, 0 ], feedback: [ 1, 0 ]
});
assert(node instanceof api.IIRFilterNode);
});
it("new instance, but @protected", () => {
const api = testTools.createAPI({ protected: true });
const context = new api.AudioContext();
assert.throws(() => {
return new api.IIRFilterNode(context, {
feedforward: [ 1, 0 ], feedback: [ 1, 0 ]
});
}, TypeError);
});
});
describe("getFrequencyResponse", () => {
it("works", () => {
const api = testTools.createAPI();
const context = new api.AudioContext();
const node = new api.IIRFilterNode(context, {
feedforward: [ 1, 0 ], feedback: [ 1, 0 ]
});
const frequencyHz = new Float32Array([ 440, 880, 1760, 3520 ]);
const magResponse = new Float32Array(4);
const phaseResponse = new Float32Array(4);
node.getFrequencyResponse(frequencyHz, magResponse, phaseResponse);
});
it("throws error", () => {
const api = testTools.createAPI();
const context = new api.AudioContext();
const node = new api.IIRFilterNode(context, {
feedforward: [ 1, 0 ], feedback: [ 1, 0 ]
});
const frequencyHz = new Float32Array([ 440, 880, 1760, 3520 ]);
const magResponse = new Float32Array(2);
const phaseResponse = new Float32Array(2);
assert.throws(() => {
node.getFrequencyResponse(frequencyHz, magResponse, phaseResponse);
}, TypeError);
});
});
});
});
|
m.elements({
links: $('a')
});
|
import express from 'express';
import { getter, getAll } from '../controllers/general/getter';
import updater from '../controllers/general/updater';
import deleter from '../controllers/general/deleter';
import createUser from '../controllers/users/createUser';
import signIn from '../controllers/users/signIn';
import activateUser from '../controllers/users/activate';
import getProfile from '../controllers/profile/getProfile';
import getMembers from '../controllers/members/getMembers';
import { setLike, getLike } from '../controllers/profile/like';
import getMatches from '../controllers/messages/getMatches';
const router = express.Router();
//Exemple de requete get et delete :
// http://localhost:5000/api/users/email?value=greg.philips@gmail.com
//Exemple de requete put :
// http://localhost:5000/api/users/email?value=greg.philips@yopmail.com&id=22
router.get('/users/getall', getMembers);
router.get('/matches/getall', getMatches);
router.post('/users', createUser);
router.post('/users/signin', signIn);
router.post('/users/activate', activateUser);
router.get('/users/profile/:username', getProfile);
router.get('/like/set/:username', setLike);
router.get('/like/get/:username', getLike);
router.get('/:table', getAll);
router.get('/:table/:field', getter);
router.put('/:table/:field', updater);
router.delete('/:table/:field', deleter);
module.exports = router;
|
import "@babel/polyfill";
import "./import/modules";
import "./import/components";
import {
User
} from "%ui%/es6-class";
import {
DOM
} from "%ui%/dom-creator";
import {
getIncrementor
} from "%ui%/hosting";
import singleton from "%ui%/mediator";
// import { randomValue,
// myPromise,
// callPromise
// } from "%ui%/random promise";
// document.querySelector('#btn').onclick = callPromise;
document.addEventListener('DOMContentLoaded', () => {
const select = document.querySelector('#myselect');
const showBtn = document.querySelector('#mybtn');
const axios = require('axios');
const values = [];
const out = document.querySelector('.out');
axios.get("https://restcountries.eu/rest/v2/all")
.then(response => {
response.data.forEach(function (item) {
let newOption = new Option(item['name'], item['callingCodes']);
let flag = document.createElement("img");
flag.src = item['flag'];
newOption.append(flag);
select.append(newOption);
});
// console.log(response.data);
})
.catch(error => {
console.log("error", error);
})
showBtn.addEventListener('click', () => {
values.length = 0;
if (select.multiple) {
for (let i = 0; i < select.options.length; i++) {
if (select.options[i].selected) {
values.push(select.options[i].innerText);
values.push(select.options[i].value);
}
}
} else
values.push(select.value);
console.log(values);
out.innerHTML = values.join(", ");
})
});
// API - https://restcountries.eu/rest/v2/all
// 1) За допомогою цього API та axios npm module, побудувати власний MULTIPLAY select
// у якому є прапор країни та її назва, де можна вибрати декілька країн натиснувши
// на кожну з них. Якщо робим клік на країну, яка уже вибрана, вибір скасовується.
// Після вибору країн зі списку натискаємо на кнопку "Показати результати".
// І відображаємо список кодів телефонів вибраних країн.
|
$(document).ready(function () {
//Shipping address form validations
$("#existing-address-form").validate({
rules: {
existingAddress: {
required: true
}
},
messages: {
existingAddress: {
required: "Please, select an existing address."
}
},
submitHandler: function (form) {
//Do SOMETHING
form.submit();
}
});
$("#new-address-form").validate({
rules: {
firstName: {
required: true,
minlength: 2,
maxlength: 100,
regex: $.__nameRegex,
normalizer: function (value) {
return $.trim(value);
}
},
lastName: {
required: true,
minlength: 2,
maxlength: 100,
regex: $.__nameRegex,
normalizer: function (value) {
return $.trim(value);
}
},
company: {
required: true
},
phoneNumber: {
required: true,
number: true
},
country: {
required: true
},
zipCode: {
required: true
},
addressLineOne: {
required: true
},
city: {
required: true
},
state: {
required: true
}
},
messages: {
firstName: {
required: "Please enter a first name.",
minlength: "Please enter at least {0} characters.",
maxlength: "Maximum character length: {0}.",
regex: "Only letters and the following symbols: -,'. are accepted."
},
lastName: {
required: "Please enter a last name.",
minlength: "Please enter at least {0} characters.",
maxlength: "Maximum character length: {0}.",
regex: "Only letters and the following symbols: -,'. are accepted."
},
country: {
required: "Please, select a country."
},
state: {
required: "Please, select a state."
}
},
submitHandler: function (form) {
//Do SOMETHING
form.submit();
}
});
//Additional details form validations
$("#additional-details-form").validate({
rules: {
projectName: {
required: true
}
},
submitHandler: function (form) {
//Do SOMETHING
form.submit();
}
});
});
|
import React, { PureComponent } from 'react'
export default class Footer extends PureComponent {
render() {
return (
<footer class="footer-distributed ui container">
<div class="footer-right">
<a href="https://www.facebook.com/achhabra1">
<i class="facebook icon"></i>
</a>
<a href="https://www.linkedin.com/in/aman-chhabra-54884b24/">
<i class="linkedin icon"></i>
</a>
<a href="https://github.com/achhabra2">
<i class="github icon"></i>
</a>
</div>
<div class="footer-left">
<p class="footer-links">
<a href="/about">About</a>
·
<a href="/help">Help</a>
·
<a href="/contact">Contact</a>
</p>
<p>Inquire App by Aman Chhabra © 2017</p>
</div>
</footer>
)
}
}
|
module.exports = function (message, emojiMap) {
if(!message || !message.payload || !message.payload.text) {
return []
}
var renderDom = []
// 文本消息
var temp = message.payload.text.replace(/\&\;/g, '&')
var left = -1
var right = -1
Object.keys(emojiMap).forEach(function(item) {
temp = temp.split(item).join('「' + item + '」')
})
while (temp !== '') {
left = temp.indexOf('「')
right = temp.indexOf('」')
switch (left) {
case 0:
if (right === -1) {
renderDom.push({
name: 'text',
text: temp
})
temp = ''
} else {
var _emoji = temp.slice(1, right)
if (emojiMap[_emoji]) {
renderDom.push({
name: 'img',
src: emojiMap[_emoji]
})
temp = temp.substring(right + 1)
} else {
renderDom.push({
name: 'text',
text: '「'
})
temp = temp.slice(1)
}
}
break
case -1:
renderDom.push({
name: 'text',
text: temp
})
temp = ''
break
default:
renderDom.push({
name: 'text',
text: temp.slice(0, left)
})
temp = temp.substring(left)
break
}
}
return renderDom
}
|
import ViewerLayer from "../../layer/ViewerLayer";
import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
import Fill from "ol/style/Fill";
import Stroke from "ol/style/Stroke";
import Vue from "vue";
import axios from "axios";
import GeoJSON from "ol/format/GeoJSON";
import Style from "ol/style/Style";
import {SharedEventBus} from "../../../shared";
class ViewerLayerKerkenBAG extends ViewerLayer {
constructor(props) {
super(props);
this.styleCache = [];
}
OLLayer(url) {
let source = new VectorSource({
loader: function () {
console.log('trip bag loader');
let pand_id=Vue.prototype.$config.kerk.pand_id;
if (pand_id.length>0) {
let filter = '<Filter>';
if (pand_id.length>1) filter += '<OR>';
for (const id of pand_id) {
filter+='<PropertyIsEqualTo><PropertyName>identificatie</PropertyName><Literal>' + id + '</Literal></PropertyIsEqualTo>';
}
if (pand_id.length>1) filter += '</OR>';
filter += '</Filter>';
return axios.get(url, {
params: {
request: 'GetFeature',
service: 'WFS',
version: '2.0.0',
typeNames: 'bag:pand',
count: pand_id.length,
outputFormat: 'application/json',
srsname: 'EPSG:4326',
filter: filter
}
}).then(function (response) {
console.log('response finished');
Vue.prototype.$config.kerk.pand_id = [];
let format = new GeoJSON;
let features = format.readFeatures(response.data, {
dataProjection: 'EPSG:4326',
featureProjection: Vue.prototype.$config.crs
});
source.addFeatures(features);
}).catch(function (error) {
SharedEventBus.$emit('show-message', 'problem loading bag pand: ' + error);
console.error(error);
});
}
}
});
return new VectorLayer({
visible: true,
style: new Style({
stroke: new Stroke({
color: 'rgba(0, 0, 255, 1.0)',
width: 2
}),
fill: new Fill({
color: 'rgba(0, 0, 255, 0.3)'
}),
}),
opacity: 1,
source: source,
zIndex: this.zindex,
});
}
}
export default ViewerLayerKerkenBAG;
|
X.define("modules.homePage.home",["model.homeModel","model.userModel","model.companyModel","common.layer"],function (homeModel,userModel,companyModel,layer) {
//初始化视图对象
var view = X.view.newOne({
el: $(".xbn-content"),
url: X.config.homePage.tpl.home
});
//初始化控制器
var ctrl = X.controller.newOne({
view: view
});
ctrl.rendering = function(){
var callback = function(result){
var data = result.data[0];
return view.render(data, function () {
var getData;
var callback = function(result){
if(result.statusCode ==2000000){
getData = result.data[0];
ctrl.vmdata = ctrl.getViewModel(ctrl.view.el.find(".js-home"),{meta: {"logoUrl": {size: 2,type:0,filePicker:".filePicker",uploadSuccess:function(){
var data = {
logoUrl: ctrl.vmdata.getControl("logoUrl").getValue()
};
var callback = function(result){
if(result.statusCode =="2000000"){
layer.successMsg("上传成功",function(number){
layer.closeIt(number);
});
}
};
companyModel.putLogoUrl(data,callback);
}}},data:getData});
ctrl.vmdata.initControl();
ctrl.view.el.find(".userName").html(getData.userName);
ctrl.view.el.find(".mobile").html(getData.mobile);
ctrl.view.el.find(".lastLoginDate").html(getData.lastLoginDate);
ctrl.view.el.find(".tenderCount").click(function(evt){
menuCall(evt,"bid.publicBidding");
});
ctrl.view.el.find(".myBiddingCount").click(function(evt){
menuCall(evt,"bid.myBid");
});
ctrl.view.el.find(".answeredCount").click(function(evt){
menuCall(evt,"bid.myBid");
});
ctrl.view.el.find(".unansweredCount").click(function(evt){
menuCall(evt,"bid.myBid");
});
ctrl.view.el.find(".js-sysMsgCount").click(function(evt){
menuCall(evt,"message.systemMessage");
});
}
};
userModel.getUserInfo(callback);
view.el.find(".js-tel").html(X.config.contact.tel);
view.el.find(".js-email").html(X.config.contact.email);
});
};
homeModel.statistics(callback);
};
function menuCall(evt,mid){
evt.stopPropagation();
evt.preventDefault();
X.publish(X.CONSTANTS.channel.menuCall,{m:mid});
}
ctrl.load = function (para) {
ctrl.rendering();
};
$.addTemplateFormatter({
platformMsgCountFormater:function(value, template){
if(value > 99){
return "99+"
}else{
return value;
}
}
});
return ctrl;
});
|
import Compiler from '../src/Compiler.js';
let compiler=new Compiler()
test("1",()=>{expect(compiler.calc("1")).toBe(1)})
test("11",()=>{expect(compiler.calc("11")).toBe(11)})
test("1+2=3",()=>{expect(compiler.calc("1+2")).toBe(3)})
test("1 plus 2=3",()=>{expect(compiler.calc("1 plus 2")).toBe(3)})
test("1plus2=3",()=>{expect(compiler.calc("1plus2")).toBe(3)})
test("1+2*3=7",()=>{expect(compiler.calc("1+2*3")).toBe(7)})
test("1 + 2 = 3",()=>{expect(compiler.calc("1 + 2 ")).toBe(3)})
test("1 + 2 * 5 + (3 + 5) = 19",()=>{expect(compiler.calc("1 + 2 * 5 + (3 + 5) ")).toBe(19)})
test("12+21=33",()=>{expect(compiler.calc("12+21")).toBe(33)})
test("3* ( 1+2 )=9",()=>{expect(compiler.calc("3* (1+2 )")).toBe(9)})
test("3*(1+2)=9",()=>{expect(compiler.calc("3*(1+2)")).toBe(9)})
|
import React, { Component } from 'react';
import { withStyles } from '@material-ui/core/styles';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
import Paper from '@material-ui/core/Paper';
const CustomTableCell = withStyles(theme => ({
head: {
backgroundColor: theme.palette.common.black,
color: theme.palette.common.white,
},
body: {
fontSize: 14,
},
}))(TableCell);
const styles = theme => ({
root: {
width: '60%',
marginLeft: 'auto',
marginRight: 'auto',
marginTop: theme.spacing.unit * 3,
overflowX: 'auto',
},
table: {
minWidth: 700,
},
row: {
'&:nth-of-type(odd)': {
backgroundColor: theme.palette.background.default,
},
},
});
let id = 0;
function createData(name, calories, fat, carbs, protein) {
id += 1;
return { id, name, calories, fat, carbs, protein };
}
const rows = [
createData('Frozen yoghurt', 159, 6.0, 24, 4.0),
createData('Ice cream sandwich', 237, 9.0, 37, 4.3),
createData('Eclair', 262, 16.0, 24, 6.0),
createData('Cupcake', 305, 3.7, 67, 4.3),
createData('Gingerbread', 356, 16.0, 49, 3.9),
];
import { firestore } from 'firebase';
const db = firestore();
class LeaderBoard extends Component {
constructor(props) {
super(props);
this.state = {
results: [],
loading: true
}
}
componentWillMount() {
db.collection('answers').get().then(data => {
data.docs.forEach(doc => {
const user = doc.id;
const { lastAnswerTimeStamp, nextQuestionId} = doc.data();
this.state.results.push({ user, lastAnswerTimeStamp, nextQuestionId})
});
this.setState({loading: false});
});
}
render() {
const { classes } = this.props;
const results = this.state.results;
console.log(results);
results.sort((a,b) => {
const keyA = a.nextQuestionId;
const keyB = b.nextQuestionId;
if (keyA > keyB) {
return -1;
}
if (keyA < keyB) {
return 1;
}
if (keyA === keyB) {
const key2A = a.lastAnswerTimeStamp || 0;
const key2B = b.lastAnswerTimeStamp || 0;
return key2A > key2B ? 1 : -1;
}
});
console.log(results);
return (
<Paper className={classes.root}>
<Table className={classes.table}>
<TableHead>
<TableRow>
<CustomTableCell align="center">Rank</CustomTableCell>
<CustomTableCell align="center">User</CustomTableCell>
<CustomTableCell align="center">Score</CustomTableCell>
</TableRow>
</TableHead>
<TableBody>
{results.map((row, index) => (
<TableRow className={classes.row} key={index}>
<CustomTableCell align="center">
{index + 1}
</CustomTableCell>
<CustomTableCell align="center">{row.user}</CustomTableCell>
<CustomTableCell align="center">{(row.nextQuestionId || 0) * 10}</CustomTableCell>
</TableRow>
))}
</TableBody>
</Table>
</Paper>
);
}
}
export default withStyles(styles)(LeaderBoard);;
|
const clientes = []
let indice = 0
class Pessoa {
constructor(nome, aniversario, endereco, email, telefone) {
this.nome = nome
this.aniversario = aniversario
this.endereco = endereco
this.email = email
this.telefone = telefone
}
getNome = () => {
return this.nome
}
getAniversario = () => {
return this.aniversario
}
getEndereco = () => {
return this.endereco
}
getEmail = () => {
return this.email
}
getTelefone = () => {
return this.telefone
}
setNome = (novoNome) => {
this.nome = novoNome
}
setTel = (novoTel) => {
this.telefone = novoTel
}
setAniversario = (novoAniv) => {
this.aniversario = novoAniv
}
setEmail = (novoEmail) => {
this.email = novoEmail
}
setEndereco = (novoEnd) => {
this.endereco = novoEnd
}
}
function criarCliente() {
const nome = document.querySelector("#nome")
const aniv = document.querySelector("#aniv")
const end = document.querySelector("#end")
const email = document.querySelector("#email")
const tel = document.querySelector("#tel")
if (nome.value != "", aniv.value != "", end.value != "", email.value != "", tel.value != "") {
clientes[indice] = new Pessoa(nome.value, aniv.value, end.value, email.value, tel.value)
let pessoas = new Array()
if (localStorage.hasOwnProperty("pessoas")) {
pessoas = JSON.parse(localStorage.getItem("pessoas"))
}
pessoas.push({ cliente: clientes[indice] })
localStorage.setItem("pessoas", JSON.stringify(pessoas))
nome.value = ""
aniv.value = ""
end.value = ""
email.value = ""
tel.value = ""
indice++
const teste = document.querySelector(".enviado")
teste.style.display = "inline-block"
setTimeout(() => {
teste.style.display = "none"
}, 3000);
} else {
alert("Coloque informações válidas!")
}
}
function criarInstanciaPessoa(obj) {
return new Pessoa(obj.nome, obj.aniversario, obj.endereco, obj.email, obj.telefone)
}
|
/**
* @name DashboardSectionTitle
* @author Mario Arturo Lopez Martinez
* @overview Title for dashboard sections
* @param {string} title to be displayed
* @example <DashboardSectionTitle title="Projects" />
*/
import React from "react"
import styled from "styled-components"
const Background = styled.div`
font-family: "BioSans", sans-serif;
color: ${props => props.theme.primaryGreen};
padding: 0 0 2rem 0;
text-align: ${props => (props.center ? "center" : "left")};
&h1 {
font-family: "BioSans", sans-serif;
}
`
const Line = styled.hr`
margin-top: -0.3em;
margin-bottom: 2rem;
border: 0;
float: ${props => (props.center ? "none" : "left")};
border-top: 2px solid #feb81c;
width: ${props => (props.center ? "180px" : "60px")};
`
export default ({ title, ...props }) => (
<Background {...props}>
<h4>{title}</h4>
<Line {...props} />
</Background>
)
|
/**
* Converts an RGB color value to HSL. Conversion formula
* adapted from http://en.wikipedia.org/wiki/HSL_color_space.
* Assumes r, g, and b are contained in the set [0, 255] and
* returns h, s, and l in the set [0, 1].
*
* @param {number} r The red color value
* @param {number} g The green color value
* @param {number} b The blue color value
* @return {Array} The HSL representation
*/
function rgbToHsl(r, g, b){
r /= 255, g /= 255, b /= 255;
var max = Math.max(r, g, b), min = Math.min(r, g, b);
var h, s, l = (max + min) / 2;
if(max == min){
h = s = 0; // achromatic
}else{
var d = max - min;
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
switch(max){
case r: h = (g - b) / d + (g < b ? 6 : 0); break;
case g: h = (b - r) / d + 2; break;
case b: h = (r - g) / d + 4; break;
}
h /= 6;
}
return [h, s, l];
}
var SmokeEffectWidget = (function(){
var container = document.getElementById('smokeEffectContainer');
var containerWidth, containerHeight;
var Blip, blips, canvas, ch, clear, ctx, cw, divider, pi2;
var rand, run;
var color;
var numberBlip;
var speed;
canvas = document.getElementById('canvas');
ctx = canvas.getContext('2d');
divider = 1.2;
pi2 = Math.PI * 2;
blips = [];
var timeoutAnimation;
var isStop = false;
var isRunning = false;
rand = function(min, max) {
return Math.floor((Math.random() * (max - min + 1)) + min);
};
window.requestAnimationFrame = function(callback, element) {
return window.setTimeout(function() {
return callback(new Date());
}, 1000 / (10 * speed));
};
Blip = function(x, y) {
this.x = x;
this.y = y;
this.r = .1;
this.rGrowthBase = 1;
this.rGrowth = 1;
var isSquare = (cw - 20 <= ch && ch <= cw + 20) || (ch - 20 <= cw && cw <= ch + 20);
this.rMax = (cw + ch)/(isSquare ? 6 : 7.5);
this.alpha = 1;
};
Blip.prototype.update = function() {
var percent = (this.rMax - this.r) / this.rMax;
this.rGrowth = .1 + this.rGrowthBase * percent;
this.r += this.rGrowth;
this.alpha = percent;
if (this.r > this.rMax) {
return false;
}
return true;
};
Blip.prototype.render = function() {
ctx.beginPath();
ctx.arc(this.x, this.y, this.r, 0, pi2, false);
ctx.fillStyle = 'hsla('+(color[0]*360)+', '+(color[1]*100)+'%, 1%, ' + this.alpha + ')';
ctx.fill();
};
clear = function() {
ctx.globalCompositeOperation = 'destination-out';
//ctx.fillStyle = 'hsla(0, 0%, 0%, .05)';
ctx.fillStyle = 'rgba(255,0,0, 0.1)';
ctx.fillRect(0, 0, cw, ch);
ctx.globalCompositeOperation = 'lighter';
};
run = function() {
if(isStop) {
isRunning = false;
blips = [];
if(timeoutAnimation){
clearTimeout(timeoutAnimation);
timeoutAnimation = null;
}
return;
}
isRunning = true;
var i;
timeoutAnimation = window.requestAnimationFrame(run);
clear();
i = blips.length;
while (i--) {
if(!blips[i].update()) {
blips.splice(i, 1);
}
}
i = blips.length;
while (i--) {
blips[i].render();
}
if(blips.length < numberBlip){
blips.push(new Blip(rand(0, cw), rand(0, ch)));
}
};
/*==============================================*/
/*===== Start point of animation =====*/
/*==============================================*/
function reloadGlobalVariables() {
containerWidth = parseInt(window.getComputedStyle(container).getPropertyValue('width'));
containerHeight = parseInt(window.getComputedStyle(container).getPropertyValue('height'));
cw = canvas.width = containerWidth / divider;
ch = canvas.height = containerHeight / divider;
}
function stopCurrentAnimation(callback) {
isStop = true;
if(isRunning) {
var timeout = setTimeout(function(){
clearTimeout(timeout);
stopCurrentAnimation(callback);
}, 200);
} else {
isStop = false;
if(callback)
callback();
}
}
function startAnimation() {
stopCurrentAnimation(function(){
run();
});
}
/*==============================================*/
/*===== Default settings from Banner Flow =====*/
/*==============================================*/
function loadSettings() {
if(typeof BannerFlow !== "undefined"){
numberBlip = BannerFlow.settings.maxNumberBlip > 0 ? BannerFlow.settings.maxNumberBlip : 400;
speed = BannerFlow.settings.speed > 0 ? BannerFlow.settings.speed : 6;
color = BannerFlow.settings.color;
color = color.substring("rgba(".length);
color = color.substring(0, color.length-1);
var arrColor = color.split(',');
color = rgbToHsl(arrColor[0], arrColor[1], arrColor[2]);
} else {
numberBlip = 400;
speed = 6;
//color = "rgba(190, 195, 196, 1)";
color = "rgba(242, 242, 194, 1)";
color = color.substring("rgba(".length);
color = color.substring(0, color.length-1);
var arrColor = color.split(',');
color = rgbToHsl(arrColor[0], arrColor[1], arrColor[2]);
}
}
/*====================================================*/
var timeoutStart;
function init() {
if(timeoutStart) {
clearTimeout(timeoutStart);
timeoutStart = setTimeout(function() {
loadSettings();
reloadGlobalVariables();
startAnimation();
}, 500);
} else {
timeoutStart = setTimeout(function(){
loadSettings();
reloadGlobalVariables();
startAnimation();
}, 0);
}
}
function onStart() {
init();
}
function onResize(){
init();
}
function resetParameter(){
init();
}
return {
start: onStart,
onResized: onResize,
onSettingChanged: resetParameter
};
})();
if(typeof BannerFlow == "undefined"){
SmokeEffectWidget.start();
} else {
BannerFlow.addEventListener(BannerFlow.INIT, function () {
SmokeEffectWidget.start();
});
BannerFlow.addEventListener(BannerFlow.RESIZE, function () {
SmokeEffectWidget.onResized();
});
BannerFlow.addEventListener(BannerFlow.SETTINGS_CHANGED, function () {
SmokeEffectWidget.onSettingChanged();
});
}
|
import React from 'react'
import Sidebar from './Sidebar'
import MainImage from '../photos/homepage.jpg'
import Suitcase2 from '../photos/suitcase2.jpg'
import Event1 from '../photos/event1.jpg'
import Money1 from '../photos/money1.jpg'
import { Icon, Statistic, Grid, Image, Segment, Header } from 'semantic-ui-react'
const Home = (props) => {
return (
<div>
{!props.activeUser.username ? <BasicPage /> : <LoggedIn activeUser={props.activeUser}/>}
</div>
)
}
const LoggedIn = (props) => {
return (
<div className='main-body double-centered'>
<Grid>
<Grid.Column width={4}>
<Sidebar activeUser={props.activeUser}/>
</Grid.Column>
<Grid.Column width={12}>
Welcome {props.activeUser.username}!
</Grid.Column>
</Grid>
</div>
)
}
const BasicPage = (props) => {
return (
<div>
<Image className='main-body' src={MainImage} alt='map'/>
<Statistic.Group widths='four'>
<Statistic>
<Statistic.Value>800,000</Statistic.Value>
<Statistic.Label>Miles</Statistic.Label>
</Statistic>
<Statistic>
<Statistic.Value text>
one
<br />
Hundred
</Statistic.Value>
<Statistic.Label>Suitcases</Statistic.Label>
</Statistic>
<Statistic>
<Statistic.Value>
<Icon name='plane' /> 76{/* props.trips.total */}
</Statistic.Value>
<Statistic.Label>Trips</Statistic.Label>
</Statistic>
<Statistic>
<Statistic.Value>
42 {/* props.users.total */}
</Statistic.Value>
<Statistic.Label>Members</Statistic.Label>
</Statistic>
</Statistic.Group>
<div className="ui divider"></div>
<Grid centered columns={3} padded='true'>
<Grid.Column>
<Segment>
<Image fluid rounded src={Suitcase2} />
<Header as='h1' textAlign='center'>
Track
<Header.Subheader>how far your bags have travelled</Header.Subheader>
</Header>
</Segment>
</Grid.Column>
<Grid.Column>
<Segment>
<Image fluid rounded src={Event1} />
<Header as='h1' textAlign='center'>
Add
<Header.Subheader>fun events and places to see</Header.Subheader>
</Header>
</Segment>
</Grid.Column>
<Grid.Column>
<Segment>
<Image fluid rounded src={Money1} />
<Header as='h1' textAlign='center'>
Budget
<Header.Subheader>your entire trip easily</Header.Subheader>
</Header>
</Segment>
</Grid.Column>
</Grid>
<div className="ui divider"></div>
</div>
)
}
export default Home
|
const hyperswarm = require("hyperswarm-web");
const hypercore = require("hypercore");
const ram = require("random-access-memory");
const pump = require("pump");
const { toPromises } = require("hypercore-promisifier");
const sw = hyperswarm();
async function createCore() {
const response = await fetch("https://krc1s.sse.codesandbox.io/key");
const payload = await response.json();
const publicKey = payload.body;
console.log("fetch server hypercore key ", publicKey);
const core = toPromises(
hypercore(ram, publicKey, { valueEncoding: "utf-8" })
);
await core.ready();
const cleanup = async () => {
await core.close();
};
return { core, cleanup };
}
async function main() {
console.log("creating browser hypercore");
const { core } = await createCore();
console.log("listening browser hypercore updates");
core.createReadStream({ live: true }).on("data", (chunk) => {
console.log(chunk.toString());
});
sw.join(core.discoveryKey, {
lookup: true, // find & connect to peers
announce: true // optional- announce self as a connection target
});
console.log("waiting for connection");
sw.on("connection", (conn, info) => {
console.log("client connected to peer ", info.peer.host);
const stream = core.replicate(false, { live: true });
pump(stream, conn, stream);
});
}
main();
|
import HolidayImg from "../images/this_holiday_539.png";
const ThisHoliday = () => {
return <section className="hero this-holiday xl:mx-20">
<div>
<img className="hero-img" src={HolidayImg} alt="holiday pass" />
</div>
<div className="overlay bg-gray-800 text-center px-10 py-20 text-white sm:bg-transparent sm:text-left">
<h2 className="font-semibold text-xl mb-2">
This holiday, find your joy
</h2>
<p className="mb-2 text">
Follow the story of Rufus, a pup whose dream takes him into Microsoft
worlds like Minecraft, Flight Simulator, Teams and Halo
</p>
<button className="mr-4 bg-white text-black py-2 px-5 hover:underline hover:bg-opacity-80">
Watch now
</button>
</div>
</section>;
};
export default ThisHoliday;
|
import { combineReducers } from 'redux';
import usuarios from '../modules/reducers'
export default combineReducers({
usuarios
});
|
const chai = require('chai');
const nock = require('nock');
const sinon = require('sinon');
const logger = require('@elastic.io/component-logger')();
const reassemble = require('../lib/actions/reassemble');
const objectStorageUri = 'https://ma.estr';
process.env.ELASTICIO_OBJECT_STORAGE_TOKEN = 'token';
process.env.ELASTICIO_WORKSPACE_ID = 'test';
process.env.ELASTICIO_FLOW_ID = 'test';
process.env.ELASTICIO_API_URI = 'https://api.hostname';
process.env.ELASTICIO_OBJECT_STORAGE_URI = objectStorageUri;
process.env.ELASTICIO_STEP_ID = 'step_id';
const { expect } = chai;
chai.use(require('chai-as-promised'));
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
describe('Reassemble unit test', () => {
let self;
beforeEach(() => {
self = {
emit: sinon.spy(),
logger,
};
});
after(() => {
nock.restore();
nock.cleanAll();
nock.activate();
});
it('Base Case: Group Size is 1', async () => {
const msg = {
body: {
groupId: 'group123',
messageId: 'msg123',
groupSize: 1,
},
};
const getMessageGroups = nock(objectStorageUri).get('/objects?query[externalid]=group123').reply(200, []);
const postMessageGroup = nock(objectStorageUri)
.post('/objects', { messages: [], messageIdsSeen: {} })
.matchHeader('x-query-externalid', 'group123')
.reply(200, { objectId: 'group123' });
const getMessageGroup = nock(objectStorageUri)
.get('/objects/group123')
.reply(200, { messages: [], messageIdsSeen: {} });
const getMessageGroup1 = nock(objectStorageUri)
.get('/objects/group123')
.reply(200, { messages: [{ msg123: undefined }], messageIdsSeen: { msg123: 'msg123' } });
const putMessageGroup1 = nock(objectStorageUri).put('/objects/group123').reply(200, {});
const deleteMessageGroup = nock(objectStorageUri).delete('/objects/group123').reply(200, {});
await reassemble.process.call(self, msg, { mode: 'groupSize' });
// eslint-disable-next-line no-unused-expressions
expect(self.emit.calledOnce).to.be.true;
expect(self.emit.lastCall.args[1].body).to.deep.equal({
groupSize: 1,
groupId: 'group123',
messageData: {
msg123: undefined,
undefined,
},
});
expect(getMessageGroups.isDone()).to.equal(true);
expect(postMessageGroup.isDone()).to.equal(true);
expect(getMessageGroup.isDone()).to.equal(true);
expect(getMessageGroup1.isDone()).to.equal(true);
expect(putMessageGroup1.isDone()).to.equal(true);
expect(deleteMessageGroup.isDone()).to.equal(true);
});
it('Base Case: Group Size is 0', async () => {
const msg = {
body: {
groupId: 'group123',
messageId: 'msg123',
groupSize: 0,
},
};
await expect(reassemble.process.call(self, msg, { mode: 'groupSize' })).to.eventually.be.rejectedWith('Size must be a positive integer.');
});
xit('Interleaved Case with duplicate deliveries', async () => {
const msgBodies = [
{
groupId: '1', groupSize: 3, messageId: '1', messageData: '1-1',
},
{
groupId: '2', groupSize: 2, messageId: '1', messageData: '2-1',
},
{
groupId: '2', groupSize: 2, messageId: '1', messageData: '2-1',
},
{
groupId: '1', groupSize: 3, messageId: '3', messageData: '1-3',
},
{
groupId: '2', groupSize: 2, messageId: '2', messageData: '2-2',
},
{
groupId: '1', groupSize: 3, messageId: '2', messageData: '1-2',
},
];
// eslint-disable-next-line no-plusplus
for (let i = 0; i < msgBodies.length; i++) {
nock(objectStorageUri).get('/objects?query[externalid]=1').reply(200, []);
nock(objectStorageUri)
.post('/objects', { messages: [], messageIdsSeen: {} })
.matchHeader('x-query-externalid', '1')
.reply(200, { objectId: '1' });
nock(objectStorageUri)
.get('/objects/1')
.reply(200, { messages: [], messageIdsSeen: {} });
nock(objectStorageUri).put('/objects/1').reply(200, {});
nock(objectStorageUri)
.get('/objects/1')
.reply(200, { messages: [{ messageId: '1', groupId: '1', messageData: '1-1' }], messageIdsSeen: { 1: '1' } });
nock(objectStorageUri).put('/objects/1').reply(200, {});
nock(objectStorageUri).delete('/objects/1').reply(200, {});
nock(objectStorageUri).get('/objects?query[externalid]=2').reply(200, []);
nock(objectStorageUri)
.post('/objects', { messages: [], messageIdsSeen: {} })
.matchHeader('x-query-externalid', '2')
.reply(200, { objectId: '2' });
nock(objectStorageUri)
.get('/objects/2')
.reply(200, { messages: [], messageIdsSeen: {} });
nock(objectStorageUri).put('/objects/2').reply(200, {});
nock(objectStorageUri)
.get('/objects/2')
.reply(200, { messages: [{ messageId: '1', groupId: '2', messageData: '2-1' }], messageIdsSeen: { 1: '1' } });
nock(objectStorageUri).put('/objects/2').reply(200, {});
nock(objectStorageUri).delete('/objects/2').reply(200, {});
// eslint-disable-next-line no-await-in-loop
await reassemble.process.call(self, { body: msgBodies[i] }, { mode: 'groupSize' });
// eslint-disable-next-line default-case
switch (i) {
case i <= 3:
expect(self.emit.callCount).to.be.equal(0);
break;
case 4:
expect(self.emit.callCount).to.be.equal(1);
expect(self.emit.lastCall.args[1].body).to.deep.equal({
groupSize: 2,
groupId: '2',
messageData: {
1: '2-1',
2: '2-2',
},
});
break;
case 5:
expect(self.emit.callCount).to.be.equal(2);
expect(self.emit.lastCall.args[1].body).to.deep.equal({
groupSize: 3,
groupId: '1',
messageData: {
1: '1-1',
2: '1-2',
3: '1-3',
},
});
break;
}
}
});
it('Base Case: Group Size is 1, messageData is provided', async () => {
const msg = {
body: {
groupId: 'group123',
messageId: 'msg123',
groupSize: 1,
messageData: {
id: 1,
},
},
};
const getMessageGroups = nock(objectStorageUri).get('/objects?query[externalid]=group123').reply(200, []);
const postMessageGroup = nock(objectStorageUri)
.post('/objects', { messages: [], messageIdsSeen: {} })
.matchHeader('x-query-externalid', 'group123')
.reply(200, { objectId: 'group123' });
const getMessageGroup = nock(objectStorageUri)
.get('/objects/group123')
.reply(200, { messages: [], messageIdsSeen: {} });
const putMessageGroup = nock(objectStorageUri).put('/objects/group123').reply(200, {});
const getMessageGroup1 = nock(objectStorageUri)
.get('/objects/group123')
.reply(200, { messages: [{ messageId: 'msg123', groupId: 'group123', messageData: { id: 1 } }], messageIdsSeen: { msg123: 'msg123' } });
const deleteMessageGroup = nock(objectStorageUri).delete('/objects/group123').reply(200, {});
await reassemble.process.call(self, msg, { mode: 'groupSize' });
// eslint-disable-next-line no-unused-expressions
expect(self.emit.calledOnce).to.be.true;
expect(self.emit.lastCall.args[1].body).to.deep.equal({
groupSize: 1,
groupId: 'group123',
messageData: {
msg123: {
id: 1,
},
},
});
expect(getMessageGroups.isDone()).to.equal(true);
expect(postMessageGroup.isDone()).to.equal(true);
expect(getMessageGroup.isDone()).to.equal(true);
expect(putMessageGroup.isDone()).to.equal(true);
expect(getMessageGroup1.isDone()).to.equal(true);
expect(deleteMessageGroup.isDone()).to.equal(true);
});
it('Base Case: No group Group Size, emit after 1000 miliseconds if no incoming message', async () => {
const msg = {
body: {
groupId: 'group123',
messageId: 'msg123',
groupSize: undefined,
timersec: 1000,
},
};
const getMessageGroups = nock(objectStorageUri).get('/objects?query[externalid]=group123').reply(200, []);
const postMessageGroup = nock(objectStorageUri)
.post('/objects', { messages: [], messageIdsSeen: {} })
.matchHeader('x-query-externalid', 'group123')
.reply(200, { objectId: 'group123' });
const getMessageGroup = nock(objectStorageUri)
.get('/objects/group123')
.reply(200, { messages: [], messageIdsSeen: {} });
const putMessageGroup = nock(objectStorageUri).put('/objects/group123').reply(200, {});
const getMessageGroup1 = nock(objectStorageUri)
.get('/objects/group123')
.reply(200, { messages: [{ msg123: undefined }], messageIdsSeen: { msg123: 'msg123' } });
const getMessageGroup2 = nock(objectStorageUri)
.get('/objects/group123')
.reply(200, { messages: [{ groupId: 'group123' }], messageIdsSeen: { msg123: 'msg123' } });
const deleteMessageGroup = nock(objectStorageUri).delete('/objects/group123').reply(200, {});
await reassemble.process.call(self, msg, { mode: 'timeout' });
// timersec + 0,5 second
await sleep(1500);
// expect(self.emit.calledOnce).to.be.true;
expect(self.emit.lastCall.args[1].body).to.deep.equal({
groupSize: 1,
groupId: 'group123',
messageData: {
undefined,
},
});
expect(getMessageGroups.isDone()).to.equal(true);
expect(postMessageGroup.isDone()).to.equal(true);
expect(getMessageGroup.isDone()).to.equal(true);
expect(putMessageGroup.isDone()).to.equal(true);
expect(getMessageGroup1.isDone()).to.equal(true);
expect(getMessageGroup2.isDone()).to.equal(true);
expect(deleteMessageGroup.isDone()).to.equal(true);
});
it('Base Case: Group Size is 2, with different messageId and messageData', async () => {
const msg = [
{
groupId: 'a', groupSize: 2, messageId: '1', messageData: '1-1',
},
{
groupId: 'a', groupSize: 2, messageId: '2', messageData: '1-2',
},
];
// First Run
nock(objectStorageUri).get('/objects?query[externalid]=a').reply(200, []);
nock(objectStorageUri)
.post('/objects', { messages: [], messageIdsSeen: {} })
.matchHeader('x-query-externalid', 'a')
.reply(200, { objectId: 'a' });
nock(objectStorageUri)
.get('/objects/a')
.reply(200, { messages: [], messageIdsSeen: {} });
nock(objectStorageUri).put('/objects/a').reply(200, {});
nock(objectStorageUri)
.get('/objects/a')
.reply(200, {
messages: [{
groupSize: 2, messageId: '1', groupId: 'a', messageData: '1-1',
}],
messageIdsSeen: { 1: '1' },
});
nock(objectStorageUri).put('/objects/a').reply(200, {});
nock(objectStorageUri).delete('/objects/a').reply(200, {});
// Second Run
nock(objectStorageUri).get('/objects?query[externalid]=a').reply(200, []);
nock(objectStorageUri)
.post('/objects', { messages: [], messageIdsSeen: {} })
.matchHeader('x-query-externalid', 'a')
.reply(200, { objectId: 'a' });
nock(objectStorageUri)
.get('/objects/a')
.reply(200, { messages: [], messageIdsSeen: {} });
nock(objectStorageUri).put('/objects/a').reply(200, {});
nock(objectStorageUri)
.get('/objects/a')
.reply(200, {
messages: [{
groupSize: 2, groupId: '1', messageId: '1', messageData: '1-1',
}, {
groupSize: 2, groupId: '2', messageId: '2', messageData: '1-2',
}],
messageIdsSeen: { 1: '1', 2: '2' },
});
nock(objectStorageUri).put('/objects/a').reply(200, {});
nock(objectStorageUri).delete('/objects/a').reply(200, {});
for (let i = 0; i < msg.length; i += 1) {
// eslint-disable-next-line no-await-in-loop
await reassemble.process.call(self, { body: msg[i] }, { mode: 'groupSize' });
// eslint-disable-next-line default-case
switch (i) {
case 0:
expect(self.emit.callCount).to.be.equal(0);
break;
case 1:
expect(self.emit.callCount).to.be.equal(1);
expect(self.emit.lastCall.args[1].body).to.deep.equal({
groupSize: 2,
groupId: 'a',
messageData: {
1: '1-1',
2: '1-2',
},
});
break;
}
}
});
it('Base Case: Group Size is 2, with messageId UNDEFINED and messageData defined', async () => {
const msg = [
{
groupId: 'b', groupSize: 2, messageData: '1-1',
},
{
groupId: 'b', groupSize: 2, messageData: '1-2',
},
];
// First Run
nock(objectStorageUri).get('/objects?query[externalid]=b').reply(200, []);
nock(objectStorageUri)
.post('/objects', { messages: [], messageIdsSeen: {} })
.matchHeader('x-query-externalid', 'b')
.reply(200, { objectId: 'b' });
nock(objectStorageUri)
.get('/objects/b')
.reply(200, { messages: [], messageIdsSeen: {} });
nock(objectStorageUri).put('/objects/b').reply(200, {});
nock(objectStorageUri)
.get('/objects/b')
.reply(200, {
messages: [{
groupSize: 2, groupId: 'b', messageData: '1-1',
}],
messageIdsSeen: { 1: '1' },
});
nock(objectStorageUri).put('/objects/b').reply(200, {});
nock(objectStorageUri).delete('/objects/b').reply(200, {});
// Second Run
nock(objectStorageUri).get('/objects?query[externalid]=b').reply(200, []);
nock(objectStorageUri)
.post('/objects', { messages: [], messageIdsSeen: {} })
.matchHeader('x-query-externalid', 'b')
.reply(200, { objectId: 'b' });
nock(objectStorageUri)
.get('/objects/b')
.reply(200, { messages: [], messageIdsSeen: {} });
nock(objectStorageUri).put('/objects/b').reply(200, {});
nock(objectStorageUri)
.get('/objects/b')
.reply(200, {
messages: [{
groupSize: 2, groupId: 'b', messageData: '1-1',
}, {
groupSize: 2, groupId: 'b', messageData: '1-2',
}],
messageIdsSeen: { 1: '1', 2: '2' },
});
nock(objectStorageUri).put('/objects/b').reply(200, {});
nock(objectStorageUri).delete('/objects/b').reply(200, {});
for (let i = 0; i < msg.length; i += 1) {
// eslint-disable-next-line no-await-in-loop
await reassemble.process.call(self, { body: msg[i] }, { mode: 'groupSize' });
// eslint-disable-next-line default-case
switch (i) {
case 0:
expect(self.emit.callCount).to.be.equal(0);
break;
case 1:
expect(self.emit.callCount).to.be.equal(1);
// eslint-disable-next-line no-case-declarations
const results = self.emit.lastCall.args[1].body;
expect(results).to.deep.equal({
groupSize: 2,
groupId: 'b',
messageData: results.messageData,
});
break;
}
}
});
it('Base Case: Using time delay, with messageId UNDEFINED and messageData defined', async () => {
const msg = [
{
groupId: 'c', timersec: 1000, messageData: '1-1',
},
{
groupId: 'c', timersec: 1000, messageData: '1-2',
},
];
// First Run
nock(objectStorageUri).get('/objects?query[externalid]=c').reply(200, []);
nock(objectStorageUri)
.post('/objects', { messages: [], messageIdsSeen: {} })
.matchHeader('x-query-externalid', 'c')
.reply(200, { objectId: 'c' });
nock(objectStorageUri)
.get('/objects/c')
.reply(200, { messages: [], messageIdsSeen: {} });
nock(objectStorageUri).put('/objects/c').reply(200, {});
nock(objectStorageUri)
.get('/objects/c')
.reply(200, {
messages: [{
groupId: 'c', messageData: '1-1',
}],
messageIdsSeen: {},
});
nock(objectStorageUri).put('/objects/c').reply(200, {});
// Second Run
nock(objectStorageUri).get('/objects?query[externalid]=c').reply(200, []);
nock(objectStorageUri)
.post('/objects', { messages: [], messageIdsSeen: {} })
.matchHeader('x-query-externalid', 'c')
.reply(200, { objectId: 'c' });
nock(objectStorageUri)
.get('/objects/c')
.reply(200, { messages: [], messageIdsSeen: {} });
nock(objectStorageUri).put('/objects/c').reply(200, {});
nock(objectStorageUri)
.get('/objects/c')
.reply(200, {
messages: [{
groupId: 'c', messageData: '1-1',
}, {
groupId: 'c', messageData: '1-2',
}],
messageIdsSeen: {},
});
nock(objectStorageUri).put('/objects/c').reply(200, {});
nock(objectStorageUri)
.get('/objects/c')
.reply(200, {
messages: [{
groupId: 'c', messageData: '1-1',
}, {
groupId: 'c', messageData: '1-2',
}],
messageIdsSeen: { 1: '1', 2: '2' },
});
nock(objectStorageUri).delete('/objects/c').reply(200, {});
for (let i = 0; i < msg.length; i += 1) {
// eslint-disable-next-line no-await-in-loop
await reassemble.process.call(self, { body: msg[i] }, { mode: 'timeout' });
// eslint-disable-next-line default-case
switch (i) {
case 0:
expect(self.emit.callCount).to.be.equal(0);
break;
case 1:
// eslint-disable-next-line no-await-in-loop
await sleep(1500);
expect(self.emit.callCount).to.be.equal(1);
// eslint-disable-next-line no-case-declarations
const results = self.emit.lastCall.args[1].body;
expect(results).to.deep.equal({
groupId: 'c',
groupSize: 2,
messageData: results.messageData,
});
break;
}
}
});
});
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import ExerciseHeaderContainer from './ExerciseHeaderContainer';
import { getExerciseById } from '../reducers';
class ExerciseContainer extends Component {
componentDidMount() {
console.log(this.exercise);
}
render() {
const { exercise } = this.props;
return(
<div>
<ExerciseHeaderContainer exercise={exercise}/>
</div>
);
}
}
const mapStateToProps = (state, { params }) => {
return {
exercise: getExerciseById(state, params.exerciseId),
}
}
export default connect(mapStateToProps,)(ExerciseContainer);
|
import {getUsers} from "./userAdministration";
export const MAX_USERNAME_LENGTH = 50;
export const MIN_USERNAME_LENGTH = 3;
export const MAX_PASSWORD_LENGTH = 128;
export const MIN_PASSWORD_LENGTH = 8;
export const usernameLoginConfig = {
required: "Please, inform your name",
maxLength: {
value: MAX_USERNAME_LENGTH,
message: `Username can be up to ${MAX_USERNAME_LENGTH} characters.`
},
minLength: {
value: MIN_USERNAME_LENGTH,
message: `Username must have at least ${MIN_USERNAME_LENGTH} characters.`
},
pattern: { value: /\w/, message: "Username must have only letters and numbers." },
};
export const usernameRegisterConfig = {
...usernameLoginConfig,
validate: username => {
const users = getUsers();
if (users[username]) return "Username already in use";
}
};
export const passwordConfig = {
required: "Please, inform your password",
maxLength: {
value: MAX_PASSWORD_LENGTH,
message: `Password must have ${MAX_PASSWORD_LENGTH} or less characters.`
},
minLength: {
value: MIN_PASSWORD_LENGTH,
message: `Password must have at least ${MIN_PASSWORD_LENGTH} characters.`
},
pattern: {
value: /\w/, message: "Password must have only letters, numbers and special symbols."
},
};
|
/*
Write a function called recursiveRange which accepts a number and adds up all
the numbers from 0 to the number passed to the function.
*/
function recursiveRange(n) {
// base case: n = 0
if (n === 0) return 0;
return n + recursiveRange(n - 1);
}
console.log(recursiveRange(6)); // 21
console.log(recursiveRange(10)); // 55
console.log(recursiveRange(3)); // 6
|
/*eslint no-console: 0, no-unused-vars: 0, no-shadow: 0, newcap: 0*/
/*eslint-env node, es6 */
"use strict";
var express = require("express");
module.exports = function() {
var app = express.Router();
let store = {};
store.accounts = [];
app.get('/', (req, res) => {
res.status(200).send(store.accounts);
});
app.post('/', (req, res) => {
let newAccount = req.body;
let id = store.accounts.length;
store.accounts.push(newAccount);
res.status(201).send({id: id});
});
app.put('/:id', (req, res) => {
store.accounts[req.params.id] = req.body;
res.status(200).send(store.accounts[req.params.id]);
});
app.delete('/:id', (req, res) => {
store.accounts.splice(req.params.id, 1);
res.status(204).send();
});
return app;
};
|
import React from 'react'
const ColorBtn = ({ color, text }) => {
const onClick = () => {
console.log({ color })
}
return <button onClick={onClick}
style={{ backgroundColor: color }} className="colorbtn">{text}</button>
}
export default ColorBtn
|
import { Link, IndexLink } from 'react-router';
import h from 'react-hyperscript';
import './header.scss';
function Header() {
return (
h('nav', { className: 'jumbotron header' }, [
h(IndexLink, { to: '/', activeClassName: 'active' }, 'Home'),
h('span', ' | '),
h(Link, { to: '/report', activeClassName: 'active' }, 'Report'),
h('span', ' | '),
h(Link, { to: '/statistics', activeClassName: 'active' }, 'Statistics'),
h('span', ' | '),
h(Link, { to: '/gallery', activeClassName: 'active' }, 'Gallery'),
h('span', ' | '),
h(Link, { to: '/admin', activeClassName: 'active' }, 'Admin'),
h('span', ' | '),
h(Link, { to: '/about', activeClassName: 'active' }, 'About'),
])
);
}
export default Header;
|
appModule.controller('resetPasswordController', ['$scope', 'resetPasswordService', 'retrievePasswordService','$location', function ($scope, resetPasswordService,retrievePasswordService, $location) {
$scope.user = {};
$scope.initialize = function () {
$scope.currentTime = new Date();
$scope.resetPasswordToken = getQueryVariable('code');
if ($scope.resetPasswordToken) {
retrievePasswordService.decryptResetPasswordCode($scope.resetPasswordToken, function (data) {
var resultArray = data.split('&');
resetPasswordService.getUserByEmail(resultArray[0], function (data) {
$scope.user = data;
}, function () {
});
}, function () {
});
}
}
$scope.resetPassword= function() {
$scope.user.password = $scope.newPassword;
resetPasswordService.resetUserPassword($scope.user, function () {
$location.url("");
$location.path("/login");
}, function () {
});
}
}]);
|
isc.TabSet.create({
ID: "BodyTabSet",
// width: "100%",
// height: "30%",
tabs: [
//{
// id: "CaseContent",
// title: "BodyContent",
// pane: bodyprofilePane
//
// },
{
id: "caseEdit",
title: "Edit",
pane: crmItemBodyEditForm
}]
});
|
import { useEffect, useState, useContext } from 'react'
import api from '../api/api'
import { Context } from '../context/AuthContext'
export default() => {
const { state } = useContext(Context)
const [todos, setTodos] = useState([])
const [errorMessage, setErrorMessage] = useState('')
const userId = state.user._id
const showUserTodos = async() => {
try{
const response = await api.get(`/todos/${userId}`)
setTodos(response.data)
} catch(err) {
setErrorMessage("Something went wrong, try again later")
}
}
useEffect(() => {
showUserTodos()
}, [])
return [showUserTodos, todos, errorMessage]
}
|
import { REHYDRATE } from 'redux-persist/constants';
export default (state = [] ,action) => {
switch (action.type) {
case REHYDRATE:
return action.payload.tripList || [];
case 'add_OldTrip':
return [action.payload, ...state];
break;
case 'remove_OldTrip':
return [...state.slice(0,parseInt(action.payload)),
...state.slice(parseInt(action.payload)+1)];
break;
case 'remove_AllTrips':
return [];
break;
default:
return state;
}
};
|
//TODO, parallel initialization, subsequent, and waiting for callback.
var Client = function(params){
this.isInitialized = false;
this.hasFailed = false;
this.initializationRequirements = {
"requestHandler": [],
"gameSession": ["requestHandler"],
"multiplayerSessionManager": ["gameSession"],
"multiplayerSession": ["gameSession", "multiplayerSessionManager"],
"clientEventHandler": [],
"clientMessageHandler": ["multiplayerSession", "clientEventHandler"],
"entityManager": ["clientEventHandler"],
"spatialManager": null,
"renderManager": ["spatialManager"],
"cameraManager": ["spatialManager"],
"sceneManager": null
};
this.clientMessageHandler = null;
this.clientEventHandler = null;
this.entityStash = null;
this.entityTypeStash = null;
this.entityTableColumns = null;
this.entityManager = null;
this.spatialManager = null; //Spatial Components
this.renderManager = null; //Render Components
this.cameraManager = null; //Camera Components
this.movementPredictionManager = null;
this.inputHandler = null;
this.sceneManager = null;
this.privateEntityStash = null;
this.privateEntityManager = null;
var that = this;
Client.prototype.initialize = function() {
var that = this;
// Game Data //
that.entityStash = new EntityStash();
that.privateEntityStash = new EntityStash();
that.entityTypeStash = new EntityTypeStash();
that.entityTableColumns = new EntityTableColumns();
// EventHandler //
that.clientEventHandler = new ClientEventHandler({});
// MessageHandler //
that.clientMessageHandler = new ClientMessageHandler({
multiplayerSession: T.multiplayerSession,
clientEventHandler: that.clientEventHandler,
clientId: T.multiplayerSession.playerId
});
that.clientEventHandler.clientMessageHandler = that.clientMessageHandler;
that.entityManager = new EntityManager({
entityStash: that.entityStash,
entityTypeStash: that.entityTypeStash,
entityTableColumns: that.entityTableColumns,
eventHandler: that.clientEventHandler
});
that.clientEventHandler.registerListenerToType(that.entityManager, EventType.UPDATE);
that.privateEntityManager = new EntityManager({
entityStash: that.privateEntityStash,
entityTypeStash: that.entityTypeStash,
entityTableColumns: that.entityTableColumns,
eventHandler: that.clientEventHandler
});
that.clientEventHandler.registerListenerToType(that.privateEntityManager, EventType.LOCALENTITY);
that.spatialManager = new SpatialManager({
entityStash: that.entityStash,
entityTypeStash: that.entityTypeStash,
entityTableColumns: that.entityTableColumns
});
that.clientEventHandler.registerListenerToType(that.spatialManager, EventType.UPDATE);
that.renderManager = new RenderManager({
spatialManager: that.spatialManager,
entityStash: that.entityStash,
entityTypeStash: that.entityTypeStash,
entityTableColumns: that.entityTableColumns
});
that.clientEventHandler.registerListenerToType(that.renderManager, EventType.UPDATE);
that.cameraManager = new CameraManager({
spatialManager: that.spatialManager,
entityStash: that.entityStash,
entityTypeStash: that.entityTypeStash,
entityTableColumns: that.entityTableColumns
});
that.clientEventHandler.registerListenerToType(that.cameraManager, EventType.UPDATE);
that.movementPredictionManager = new MovementPredictionManager({
spatialManager: that.spatialManager,
entityStash: that.entityStash,
entityTypeStash: that.entityTypeStash,
entityTableColumns: that.entityTableColumns
});
that.inputHandler = new InputHandler();
that.sceneManager = new SceneManager({
inputHandler: that.inputHandler,
renderManager: that.renderManager,
cameraManager: that.cameraManager
});
that.isInitialized = true;
log("Client: INITIALIZE complete.", LogType.IMPORTANT);
};
if (T.multiplayerSession) {
that.initialize();
} else {
// MP Session (by joining) //
var mpSession = T.multiplayerSessionManager.joinAnySession(
function multiplayerSessionCreatedFn(mpSession) {
T.multiplayerSession = mpSession;
T.multiplayerSession.onclose = function () {
alert("Server Lost.", LogType.IMPORTANT);
}
that.initialize();
},
function multiplayerSessionFailedFn() {
log("Client: multiplayer session creation failed.", LogType.IMPORTANT);
that.hasFailed = true;
that.destroy();
log("Client: INITIALIZE failed.", LogType.IMPORTANT);
},
function multiplayerSessionErrorFn() {
log("Client: multiplayer session creation error.", LogType.ERROR);
that.hasFailed = true;
that.destroy();
log("Client: INITIALIZE failed.", LogType.IMPORTANT);
alert("Client: INITIALIZE failed.");
}
);
}
Client.prototype.onConnectedInitialize = function () {
testInit();
};
///////////////////////////////////////////////////////////////////////////////
Client.prototype.update = function () {
//local systems update
if (this.clientEventHandler) this.clientEventHandler.update();
if (this.movementPredictionManager) this.movementPredictionManager.update();
if (this.spatialManager) this.spatialManager.update();
if (this.renderManager) this.renderManager.update();
if (this.cameraManager) this.cameraManager.update();
if (this.sceneManager && this.sceneManager.isInitialized) {
this.sceneManager.update();
}
testLoop();
};
Client.prototype.destroy = function () {
var that = this;
if (that.multiplayerSession) {
that.multiPlayerSession.destroy();
that.multiPlayerSession = null;
}
};
};
|
// Other Event
$(function(){
//Hover effect
$('.hover-light').hover(
function () {
$(this).addClass('hover-light-on');
},
function () {
$(this).removeClass('hover-light-on');
}
);
//Modal close
$("#close").click(function () {
$("div#out").fadeOut("fast");
});
});
|
export const GET_API_DATA = 'GET_API_DATA';
export const DELETE_API_DATA = 'DELETE_API_DATA';
export const GET_GENDER_DATA = 'GET_GENDER_DATA';
export const DELETE_GENDER_DATA = 'DELETE_GENDER_DATA';
export const GET_CITY_DATA = 'GET_CITY_DATA';
export const DELETE_CITY_DATA = 'DELETE_CITY_DATA';
export const getRestApiVal = (val) => {
console.log("maggie", val);
if(val !== null) {
return (d) => {
fetch('http://localhost:4040/api/setUpTodos').then((res) => {
res.json().then((response) => {
console.log("cehck the res--->", response);
return d({
type :GET_API_DATA ,
response
});
});
});
}
}
else{
return (d) => {
return d({
type: DELETE_API_DATA
});
};
}
}
export const getGenderVal = (val) => {
if(val !== null && val !== undefined){
return (d) => {
fetch('http://localhost:4040/api/gender/' +val).then((res) => {
res.json().then((response) => {
return d({
type :GET_GENDER_DATA ,
response
});
});
});
}
}
else{
return (d) => {
return d({
type: DELETE_GENDER_DATA
});
};
}
}
export const getCityVal = (val) => {
if(val !== null && val !== undefined){
return (d) => {
fetch('http://localhost:4040/api/city/' +val).then((res) => {
res.json().then((response) => {
return d({
type: GET_CITY_DATA ,
response
});
});
});
}
}
else{
return (d) => {
return d({
type: DELETE_CITY_DATA
});
};
}
}
// axios({
// method:'GET',
// url:'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=SPY&apikey=2QEL3WC4KITIBISR',
// }).then((response)=>{
// return d({
// type :GET_API_DATA ,
// response}
// );
// }).catch((e) => {
// console.log("e", e);
// });
// export const addTodo = text => {
// return {
// type: 'GET_TODO_DATA',
// text
// }
// }
|
// Global namespace, window variables, etc.
$ = jQuery;
var App = {
windowWidth: $(window).width(),
windowHeight: $(window).height(),
scrollTop: $(window).scrollTop(),
};
$(window).resize(function() {
App.windowWidth = $(window).width();
App.windowHeight = $(window).height();
});
$(window).scroll(function() {
App.scrollTop = $(window).scrollTop();
});
App.breakpoint = function(checkIfSize) {
var xs = 480;
var sm = 768;
var md = 992;
var lg = 1200;
var breakpoint;
if(App.windowWidth < xs) {
breakpoint = 'xs';
} else if(App.windowWidth >= md) {
breakpoint = 'lg';
} else if(App.windowWidth >= sm) {
breakpoint = 'md';
} else {
breakpoint = 'sm';
}
if(checkIfSize !== undefined) {
if(checkIfSize == 'xs') {
return App.windowWidth < xs;
} else if(checkIfSize == 'sm') {
return (App.windowWidth >= xs && App.windowWidth < sm);
} else if(checkIfSize == 'md') {
return (App.windowWidth >= sm && App.windowWidth < md);
} else if(checkIfSize == 'lg') {
return App.windowWidth >= md;
}
} else {
return breakpoint;
}
};
App.breakpoint.isMobile = function() {
return ( App.breakpoint('xs') || App.breakpoint('sm') );
};
|
const MenuItem = (data) => `
<li class="menu__items-item">
<a class="menu__items-link" href="#${data.hash}">${data.name}</a>
</li>
`;
export default MenuItem;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.