text
stringlengths 7
3.69M
|
|---|
const express = require('express');
const router = express.Router();
const mongoose = require('mongoose'); //Generate ID
const checkAuth = require('../middleware/checkauth');
const User = require('../models/user');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcrypt');
router.get('/:userId', checkAuth, (req, res, next) => {
const token = req.headers.authorization.split(" ")[1];
const decode = jwt.verify(token, "bismillah");
const userId = decode.userId;
User.findById(req.params.userId)
.exec()
.then(user => {
if(!user) {
return res.status(404).json({
message: "User not Exist"
});
}
res.status(200).json({
user: user,
request: {
type: 'GET',
url: 'http://localhost:3000/profiles'
}
});
})
.catch(err => {
res.status(500).json({
error: err
});
});
});
router.patch('/edit/:userId', checkAuth, (req, res, next) => {
const token = req.headers.authorization.split(" ")[1];
const decode = jwt.verify(token, "bismillah");
const userId = decode.userId;
const id = req.params.userId;
const updateOps = {};
for (const ops of req.body) {
updateOps[ops.propName] = ops.value;
}
User.update({ _id: id }, { $set: updateOps })
.exec()
.then(result => {
res.status(200).json({
message: "Profile updated",
request: {
type: "PATCH",
url: "http://localhost:3000/profiles" + id
}
});
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
});
router.patch('/editpassword/:userId', (req, res, next) => {
// const token = req.headers.authorization.split(" ")[1];
// const decode = jwt.verify(token, "bismillah");
// const userId = decode.userId;
const id = req.params.userId;
bcrypt.hash(req.body.password, 10, (err, hash) => {
User.update({ _id: id }, { $set: {password : hash}})
.exec()
.then(result => {
res.status(200).json({
message: "Profile updated",
request: {
type: "PATCH",
url: "http://localhost:3000/profiles" + id
}
});
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
})
});
module.exports = router;
|
var randomIzq = Math.ceil(Math.random() * 100)
var randomAbajo = Math.ceil(Math.random() * 100)
var izq = []
var aba = []
for (var i = 0; i < randomIzq; i++) {
izq.push('verde');
}
for (var i = 0; i < randomAbajo; i++) {
aba.push('rojo');
}
console.log (izq.length);
console.log (aba.length);
if (izq.length >aba.length) {
grande = izq;
} else {
grande = aba;
}
console.log (grande);
for (var i = 0; i < grande.length; i++) {
if (izq.length > i) {
console.log(izq[i])
}
if (aba.length > i) {
console.log(aba[i])
}
}
|
/**
* Created by jason on 2018/9/10.
*/
layui.define("layer",function(exports){ //提示:模块也可以依赖其它模块,如:layui.define('layer', callback);
var layer = layui.layer;
var obj = {
hello: function(str){
layer.alert('Hello '+ (str||'mymod'));
}
};
//输出mymod接口
exports('mymod', obj);
});
|
import React from 'react';
import "./searchbar.css";
function SearchBar({search, handleInputChange}) {
return (
<div id="searchBarWrapper" className="input-group mb-3">
<input
id="searchBar"
name="search"
type="text"
className="form-control"
placeholder="Search"
aria-label="Username"
aria-describedby="basic-addon1"
value={search}
onChange={handleInputChange}>
</input>
</div>
)
}
export default SearchBar
|
const THREE = require('three');
const dat = require('dat.gui');
const fs = require('fs');
const vertexShaderCode = fs.readFileSync(`${__dirname}/vertexshader.glsl`, 'utf8');
const fragmentShaderCode = fs.readFileSync(`${__dirname}/fragmentshader.glsl`, 'utf8');
let scene, camera, renderer;
let star, debugStar;
const WIDTH = window.innerWidth;
const HEIGHT = window.innerHeight;
const uniforms = {
baseColor: {value: null},
coreSize: {value: null},
glowFalloff: {value: null},
glowIntensity: {value: null},
};
const params = {
baseColor: "#ff9500",
coreSize: 0.1,
glowFalloff: 1.4,
glowIntensity: 0.96,
scale: 1.0,
enableDebug: false,
}
function init() {
scene = new THREE.Scene();
initStar();
initBackdrop();
initCamera();
initRenderer();
initDatGui();
updateParameters();
timeStart = new Date().getTime();
document.body.appendChild(renderer.domElement);
}
function initCamera() {
camera = new THREE.PerspectiveCamera(40, WIDTH / HEIGHT, 0.01, 1000);
camera.position.set(0, 0, 3.75);
camera.lookAt(scene.position);
}
function initRenderer() {
renderer = new THREE.WebGLRenderer();
renderer.setSize(WIDTH, HEIGHT);
renderer.setPixelRatio(window.devicePixelRatio || 1);
}
function initStar() {
const material = new THREE.ShaderMaterial({
uniforms: uniforms,
vertexShader: vertexShaderCode,
fragmentShader: fragmentShaderCode,
transparent: true
});
const geometry = new THREE.PlaneGeometry(2, 2);
const plane = new THREE.Mesh(
geometry,
material
);
plane.position.x = -0.6;
const debugPlane = makeDebugObject(plane);
scene.add(plane);
scene.add(debugPlane);
star = plane;
debugStar = debugPlane;
}
function initBackdrop() {
const geometry = new THREE.PlaneGeometry(205, 137);
const material = new THREE.MeshBasicMaterial({
map: new THREE.TextureLoader().load(`${__dirname}/img/Milkyway.jpg`)
});
const backdrop = new THREE.Mesh(
geometry,
material
);
backdrop.position.z = -200;
scene.add(backdrop);
scene.add(makeDebugObject(backdrop));
}
function makeDebugObject(mesh) {
const debugObject = mesh.clone(true);
debugObject.material = new THREE.MeshBasicMaterial({wireframe: true});
debugObject.isDebugObject = true;
return debugObject;
}
function updateParameters() {
uniforms.baseColor.value = new THREE.Color(params.baseColor);
uniforms.coreSize.value = params.coreSize;
uniforms.glowFalloff.value = params.glowFalloff;
uniforms.glowIntensity.value = params.glowIntensity;
scene.traverse((child) => {
if (child.isDebugObject) child.visible = params.enableDebug;
});
star.scale.set(params.scale, params.scale, params.scale);
debugStar.scale.copy(star.scale);
}
function initDatGui() {
var gui = new dat.GUI();
gui.addColor(params, 'baseColor').onChange(updateParameters);
gui.add(params, "coreSize", 0.02, 0.5).onChange(updateParameters);
gui.add(params, "glowFalloff", 0.1, 5.0).onChange(updateParameters);
gui.add(params, "glowIntensity", 0.02, 3.0).onChange(updateParameters);
gui.add(params, "scale", 0.05, 8.0).onChange(updateParameters);
gui.add(params, "enableDebug").onChange(updateParameters)
}
function render() {
requestAnimationFrame(render);
renderer.render(scene, camera);
}
init();
render();
|
/*
* jQuery Currency v0.6 ( January 2015 )
* Simple, unobtrusive currency converting and formatting
*
* Copyright 2015, sMarty
* Free to use and abuse under the MIT license.
* http://www.opensource.org/licenses/mit-license.php
*
* http://coderspress.com
*
*/
(function ($) {
$.fn.currency = function (method) {
var methods = {
init: function (options) {
var settings = $.extend({}, this.currency.defaults, options);
return this.each(function () {
var $element = $(this),
element = this;
var value = 0;
if ($element.is(':input')) {
value = $element.val();
} else {
value = $element.text();
}
if (helpers.isNumber(value)) {
if (settings.convertFrom != '') {
if ($element.is(':input')) {
$element.val(value + ' ' + settings.convertLoading);
} else {
$element.html(value + ' ' + settings.convertLoading);
}
$.post(settings.convertLocation, {
amount: value,
from: settings.convertFrom,
to: settings.region
}, function (data) {
value = data;
if ($element.is(':input')) {
$element.val(helpers.format_currency(value, settings));
} else {
$element.html(helpers.format_currency(value, settings));
}
});
} else {
if ($element.is(':input')) {
$element.val(helpers.format_currency(value, settings));
} else {
$element.html(helpers.format_currency(value, settings));
}
}
}
});
},
}
var helpers = {
format_currency: function (amount, settings) {
var bc = settings.region;
var currency_before = '';
var currency_after = '';
if (bc == 'ALL') currency_before = 'ALL';
if (bc == 'ARS') currency_before = 'ARS';
if (bc == 'AWG') currency_before = 'AWG';
if (bc == 'AUD') currency_before = 'AUD';
if (bc == 'BSD') currency_before = 'BSD';
if (bc == 'BBD') currency_before = 'BBD';
if (bc == 'BYR') currency_before = 'BYR';
if (bc == 'BZD') currency_before = 'BZD';
if (bc == 'BMD') currency_before = 'BMD';
if (bc == 'BOB') currency_before = 'BOB';
if (bc == 'BAM') currency_before = 'BAM';
if (bc == 'BWP') currency_before = 'BWP';
if (bc == 'BRL') currency_before = 'BRL';
if (bc == 'BND') currency_before = 'BND';
if (bc == 'CAD') currency_before = 'CAD';
if (bc == 'KYD') currency_before = 'KYD';
if (bc == 'CLP') currency_before = 'CLP';
if (bc == 'CNY') currency_before = 'CNY';
if (bc == 'COP') currency_before = 'COP';
if (bc == 'CRC') currency_before = 'CRC';
if (bc == 'HRK') currency_before = 'HRK';
if (bc == 'CZK') currency_before = 'CZK';
if (bc == 'DKK') currency_before = 'DKK';
if (bc == 'DOP') currency_before = 'DOP';
if (bc == 'XCD') currency_before = 'XCD';
if (bc == 'EGP') currency_before = 'EGP';
if (bc == 'SVC') currency_before = 'SVC';
if (bc == 'EEK') currency_before = 'EEK';
if (bc == 'EUR') currency_before = 'EUR';
if (bc == 'FKP') currency_before = 'FKP';
if (bc == 'FJD') currency_before = 'FJD';
if (bc == 'GBP') currency_before = 'GBP';
if (bc == 'GHC') currency_before = 'GHC';
if (bc == 'GIP') currency_before = 'GIP';
if (bc == 'GTQ') currency_before = 'GTQ';
if (bc == 'GGP') currency_before = 'GGP';
if (bc == 'GYD') currency_before = 'GYD';
if (bc == 'HNL') currency_before = 'HNL';
if (bc == 'HKD') currency_before = 'HKD';
if (bc == 'HUF') currency_before = 'HUF';
if (bc == 'ISK') currency_before = 'ISK';
if (bc == 'IDR') currency_before = 'IDR';
if (bc == 'IMP') currency_before = 'IMP';
if (bc == 'JMD') currency_before = 'JMD';
if (bc == 'JPY') currency_before = 'JPY';
if (bc == 'JEP') currency_before = 'JEP';
if (bc == 'LVL') currency_before = 'LVL';
if (bc == 'LBP') currency_before = 'LBP';
if (bc == 'LRD') currency_before = 'LRD';
if (bc == 'LTL') currency_before = 'LTL';
if (bc == 'MYR') currency_before = 'MYR';
if (bc == 'MXN') currency_before = 'MXN';
if (bc == 'MZN') currency_before = 'MZN';
if (bc == 'NAD') currency_before = 'NAD';
if (bc == 'ANG') currency_before = 'ANG';
if (bc == 'NZD') currency_before = 'NZD';
if (bc == 'NIO') currency_before = 'NIO';
if (bc == 'NOK') currency_before = 'NOK';
if (bc == 'PAB') currency_before = 'PAB';
if (bc == 'PYG') currency_before = 'PYG';
if (bc == 'PEN') currency_before = 'PEN';
if (bc == 'PLN') currency_before = 'PLN';
if (bc == 'RON') currency_before = 'RON';
if (bc == 'SHP') currency_before = 'SHP';
if (bc == 'SGD') currency_before = 'SGD';
if (bc == 'SBD') currency_before = 'SBD';
if (bc == 'SOS') currency_before = 'SOS';
if (bc == 'ZAR') currency_before = 'ZAR';
if (bc == 'SEK') currency_before = 'SEK';
if (bc == 'CHF') currency_before = 'CHF';
if (bc == 'SRD') currency_before = 'SRD';
if (bc == 'SYP') currency_before = 'SYP';
if (bc == 'TWD') currency_before = 'TWD';
if (bc == 'TTD') currency_before = 'TTD';
if (bc == 'TRY') currency_before = 'TRY';
if (bc == 'TRL') currency_before = 'TRL';
if (bc == 'TVD') currency_before = 'TVD';
if (bc == 'GBP') currency_before = 'GBP';
if (bc == 'USD') currency_before = 'USD';
if (bc == 'UYU') currency_before = 'UYU';
if (bc == 'VEF') currency_before = 'VEF';
if (bc == 'ZWD') currency_before = 'ZWD';
if (currency_before != '') currency_before += ' ';
var output = '';
if (!settings.hidePrefix) output += currency_before;
output += helpers.number_format(amount, settings.decimals, settings.decimal, settings.thousands);
if (!settings.hidePostfix) output += currency_after;
return output;
},
// Kindly borrowed from http://phpjs.org/functions/number_format
number_format: function (number, decimals, dec_point, thousands_sep) {
number = (number + '').replace(/[^0-9+\-Ee.]/g, '');
var n = !isFinite(+number) ? 0 : +number,
prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
s = '',
toFixedFix = function (n, prec) {
var k = Math.pow(10, prec);
return '' + Math.round(n * k) / k;
};
// Fix for IE parseFloat(0.55).toFixed(0) = 0;
s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
if (s[0].length > 3) {
s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
}
if ((s[1] || '').length < prec) {
s[1] = s[1] || '';
s[1] += new Array(prec - s[1].length + 1).join('0');
}
return s.join(dec);
},
isNumber: function (n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
}
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
$.error('Method "' + method + '" does not exist in currency plugin!');
}
}
$.fn.currency.defaults = {
region: "USD", // The 3 digit ISO code you want to display your currency in
thousands: ",", // Thousands separator
decimal: ".", // Decimal separator
decimals: 2, // How many decimals to show
hidePrefix: false, // Hide any prefix
hidePostfix: false, // Hide any postfix
convertFrom: "", // If converting, the 3 digit ISO code you want to convert from,
convertLoading: "(Converting...)", // Loading message appended to values while converting
convertLocation: "convert.php" // Location of convert.php file
}
$.fn.currency.settings = {}
})(jQuery);
|
import React, { Component } from 'react';
import classes from './App.css';
import Persons from '../components/Persons/Persons.js';
import Cockpit from '../components/Cockpit/Cockpit';
import withClass from '../hoc/withClass';
import Aux from '../hoc/Aux';
class App extends Component {
constructor(props) {
super(props);
console.log('[App.js] constructor');
this.state = {
persons : [
{
id: '1',
name: "Nisar",
age: 29
},
{
id: '2',
name: "Vikus",
age: 30
},
{
id: '3',
name: "Shanky",
age: 30
}
],
showPersons : false,
showCockpit : true,
changeCounter : 0
}
}
static getDerivedStateFromProps(props, state) {
console.log('[App.js] getDerivedStateFromProps', props);
return state;
}
componentDidMount(){
console.log('[App.js] componentDidMount');
}
shouldComponentUpdate(nextProps, nextState){
console.log('[App.js] shouldComponentUpdate');
return true;
}
componentDidUpdate(){
console.log('[App.js] componentDidUpdate');
}
switchNameHandler = (newName) => {
console.log('was clicked');
this.setState({
persons : [
{
id: '1',
name: newName,
age: 30
},
{
id: '2',
name: "Vikus",
age: 30
},
{
id: '3',
name: "Shanky",
age: 30
}
]
}
);
}
nameChangedHandler = (event, id) => {
const personIndex = this.state.persons.findIndex(p => {
return p.id === id;
});
const person = {
...this.state.persons[personIndex]
};
person.name = event.target.value;
const persons = [...this.state.persons];
persons[personIndex] = person;
this.setState({
persons : persons,
changeCounter : this.changeCounter + 1
});
}
togglePersonshandler = () => {
const doesShow = this.state.showPersons;
this.setState({
showPersons : !doesShow
}
);
}
deletePersonHandler = (personIndex) => {
// fetch all persons and update new state
const persons = [...this.state.persons];
persons.splice(personIndex,1);
this.setState({persons : persons});
}
maxScoreSightseeingPair = function(A) {
let max = 0;
for(let i = 0 ; i < A.length - 1 ; i++){
for(let j = i + 1 ; j < A.length ; j++){
let current = A[i] + A[j] + i - j;
if(current > max){
current = max;
}
}
}
return max;
};
render() {
console.log('[App.js] render');
let persons = null;
if(this.state.showPersons){
persons = (
<Persons
persons={this.state.persons}
clicked = {this.deletePersonHandler}
changed = {this.nameChangedHandler}
/>
);
}
return (
<Aux>
<button onClick={() => {this.setState({showCockpit:false})}}> Remove Cockpit </button>
{this.state.showCockpit ?
<Cockpit
title={this.props.appTitle}
showPersons={this.state.showPersons}
persons={this.state.persons}
toggle={this.togglePersonshandler}
/> : null }
{persons}
</Aux>
);
}
}
export default withClass(App, classes.App);
|
'use strict'
const mongoose = require('mongoose');
const co = require('co');
const parallel = require('co-parallel');
const config = require('../config');
const Simcard = require('../app/models/simcard');
mongoose.connect(config.database);
let db = mongoose.connection;
let officialRechargeHistories = [
];
db.once('open', () => {
co(function* () {
try {
let reqs = officialRechargeHistories.map(transferFee);
yield parallel(reqs, 20);
} catch(err) {
console.error(err);
} finally {
db.close(() => console.log('Database has disconnected!'));
}
})
.catch(err => console.error(err));
});
function* transferFee(officialRechargeHistory) {
return yield Simcard.findOneAndUpdate({ phoneno: officialRechargeHistory[0], mobileAccount: {$ne: null} }, { '$inc': { 'mobileAccount.balance': officialRechargeHistory[1] }})
}
|
(function () {
'use strict';
/**
* @ngdoc object
* @name 0709kinderfest.controller:C0709kinderfestCtrl
*
* @description
*
*/
angular
.module('0709kinderfest')
.controller('C0709kinderfestCtrl', C0709kinderfestCtrl);
function C0709kinderfestCtrl() {
var vm = this;
vm.ctrlName = 'C0709kinderfestCtrl';
}
}());
|
const express = require('express');
const OngController = require('./controller/OngController');
const IncidenteController = require('./controller/IncidenteController');
const ProfileController = require('./controller/ProfileController');
const SessionController = require('./controller/SessionController');
const routes = express.Router();
// ======== Incident ======== //
// Listar
routes.get('/incidents', IncidenteController.index);
// Cadastrar
routes.post('/incidents', IncidenteController.create);
// Deletar
routes.delete('/incidents/:id', IncidenteController.delete);
// ======== Profile Controller ======== //
routes.get('/profile', ProfileController.index);
// ======== ONGs ======== //
// Listar
routes.get('/ongs', OngController.index);
// Cadastrar
routes.post('/ongs', OngController.create);
// ======== Sessions ======== //
routes.post('/sessions', SessionController.index);
module.exports = routes;
|
var isVisible = false;
function change() {
var ps = document.getElementById("password");
if (isVisible) {
ps.type = "password";
isVisible = false;
}
else {
ps.type = "text";
isVisible = true;
}
}
|
import "./Panel.scss";
import classNames from "classnames";
import { FaCheck, FaRegSadTear } from "react-icons/fa";
const Entities = require("html-entities").AllHtmlEntities;
function Panel(props) {
const entities = new Entities();
const { id, info, selected, setSelected, somethingSelected, audioOn } = props;
let successSound = new Audio("/sounds/success.mp3");
let failureSound = new Audio("/sounds/wrong-8bit.mp3");
failureSound.volume = 0.3;
successSound.volume = 0.2;
const success = () => {
if (audioOn) successSound.play();
};
const failure = () => {
if (audioOn) failureSound.play();
};
const { questionString, answerString, correct } = info;
const className = classNames(
"panel",
{
"panel__answer--selectedTrue": selected && correct === true,
},
{
"panel__answer--selectedTrue": somethingSelected && correct === true,
},
{
"panel__answer--selectedFalse": selected && correct === false,
},
{ panel__answer: answerString },
{ panel__question: questionString }
);
return (
<>
{answerString && (
<div
className={className}
onClick={() => setSelected(id)}
onMouseDown={correct ? success : failure}
>
<FaRegSadTear className="icon__incorrect" />
<p>{entities.decode(answerString)}</p>
<FaCheck className="icon__correct" />
</div>
)}
{questionString && (
<div className={className}>
<p>{entities.decode(questionString)}</p>
</div>
)}
</>
);
}
export default Panel;
|
'use strict';
app.controller('hotWordEditController', ['$scope', '$state','$http','hintService','sessionStorageService',
function($scope, $state,$http,hintService,sessionStorageService) {
$scope.formData = {};
$scope.needCacheArray = ["hotWordListDataTableProperties","hotWordIdForEdit"];
sessionStorageService.clearNoCacheItem($scope.needCacheArray);
if($scope.rowIds&&$scope.rowIds[0]){
sessionStorageService.setItem("hotWordIdForEdit",$scope.rowIds[0]);
}else{
$scope.rowIds[0] = sessionStorageService.getItemStr("hotWordIdForEdit");
}
if(!$scope.rowIds||$scope.rowIds[0]==""){
$state.go($scope.state.list);//返回到列表界面
}
var id = $scope.rowIds[0];
initData(id);
function initData(id){
$http({
url:"opr/hotWordAction!detailsHotWord.action",
method:"post",
data:{
id:id
}
}).then(function(resp){
if(resp.data.code===1){
$scope.formData = resp.data.details ;
$scope.formData.updateTime = undefined ;
}else{
alert(resp.data.message);
$state.go($scope.state.list);
}
});
}
$scope.submit = function(){
$http({
url:"opr/hotWordAction!updateHotWord.action",
method:"post",
data:$scope.formData
}).then(function(resp){
if(resp.data.code === 1){
hintService.hint({title: "成功", content: "修改成功!" });
$state.go($scope.state.list);
}else{
alert(resp.data.message);
}
$scope.isDoing = false ;
});
}
$scope.cancel = function(){
$state.go($scope.state.list);
}
}]);
|
import * as types from '../types'
let user = JSON.parse(localStorage.getItem('user'));
const initialState = user ? { loggedIn: true, user } : {};
export default function authReducer(state=initialState, action){
switch(action.type){
case types.USER_LOGIN_SUCCESS:
return {
loggedIn:true,
user:{...action.user}
}
case types.USER_LOGIN_FAILD:
return {}
case types.USER_LOGOUT:
return {}
default:
return state
}
}
|
$(document).ready(function () {
$.ajax({
type: "GET",
url: "http://localhost:8081/pharmacy/allpharmacies",
dataType: "json",
beforeSend: function(xhr) {
if (localStorage.token) {
xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.token);
}
},
success: function (data) {
console.log("SUCCESS : ", data);
for (i = 0; i < data.length; i++) {
var row = "<tr>";
row += "<td>" + data[i]['id'] + "</td>";
row += "<td>" + data[i]['address'] + "</td>";
row += "<td>" + data[i]['description'] + "</td>";
row += "<td>" + data[i]['name'] + "</td>";
row += "<td>" + data[i]['rating'] + "</td>";
var btn = "<button class='btnRegisterAdminPharmacy' id = " + data[i]['id'] + ">Register Admin Pharmacy</button>";
row += "<td>" + btn + "</td>";
$('#pharmacies').append(row);
}
},
error: function (data) {
console.log("ERROR : ", data);
}
});
});
$(document).on('click', '.btnRegisterAdminPharmacy', function () {
var pharmacyDiv = $(".pharmaciesall");
pharmacyDiv.hide();
var formaDiv=$(".adminForm");
formaDiv.show();
var id=this.id;
$(document).on("submit", "form", function (event) { // kada je submitovana forma za kreiranje novog zaposlenog
event.preventDefault();
var namee = $("#namee").val();
var lastName = $("#lastName").val();
var password = $("#password").val();
var adress = $("#adress").val();
var email = $("#email").val();
var city = $("#city").val();
var country = $("#country").val();
var phoneNumber = $("#phoneNumber").val();
var pharmacyID=id;
var newUserJSON = formToJSON(namee,lastName, password, adress, email, city, country, phoneNumber, pharmacyID);
$.ajax({
type: "POST",
url: "http://localhost:8081/systemadmins/signupAdminPharmacy",
dataType: "json",
contentType: "application/json",
data: newUserJSON,
beforeSend: function (xhr) {
if (localStorage.token) {
xhr.setRequestHeader('Authorization', 'Bearer ' + localStorage.token);
}
},
success: function () {
alert("success");
window.location.href = "adminSystemHomePage.html";
},
error: function (error) {
alert(error);
}
});
});
});
function formToJSON(namee,lastName, password, adress, email, city, country, phoneNumber,pharmacyID) {
return JSON.stringify(
{
"firstName": namee,
"lastName": lastName,
"password": password,
"address": adress,
"email": email,
"city": city,
"country": country,
"phone": phoneNumber,
"pharmacyID": pharmacyID
}
);
};
|
export const actions = {
SET_LEFT: ({ commit }, value) => {
commit('setLeft', value);
},
SET_RIGHT: ({ commit }, value) => {
commit('setRight', value);
}
};
export const getters = {
GET_DATA: (state) => state.end
};
export const mutations = {
setLeft: (state, value) => {
state.end = [parseInt(value), state.end[1]];
},
setRight: (state, value) => {
state.end = [state.end[0], parseInt(value)];
}
};
export const state = () => ({
end: [0, 0]
});
|
var searchData=
[
['residual_37',['residual',['../functions_8h.html#aa1cedc577fcd89781cfd04cc225b8eb7',1,'functions.h']]],
['restr_38',['restr',['../restr_8h.html#a47d0e284c45801b46002f838c54e9343',1,'restr.h']]],
['restr_2eh_39',['restr.h',['../restr_8h.html',1,'']]]
];
|
/**
* Copyright 2016 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
goog.provide('audioCat.audio.junction.GainJunction');
goog.require('audioCat.audio.junction.Junction');
goog.require('audioCat.audio.junction.SubsequentJunction');
goog.require('audioCat.audio.junction.Type');
/**
* A junction for controlling gain.
* @param {!audioCat.utility.IdGenerator} idGenerator Generates IDs unique
* throughout the application.
* @param {!audioCat.audio.AudioContextManager} audioContextManager Manages the
* audio context.
* @param {number} gain The initial gain value in sample units.
* @param {number=} opt_numberOfOutputChannels The optional number of output
* channels. Unset if not provided.
* @constructor
* @extends {audioCat.audio.junction.Junction}
* @implements {audioCat.audio.junction.SubsequentJunction}
*/
audioCat.audio.junction.GainJunction = function(
idGenerator,
audioContextManager,
gain,
opt_numberOfOutputChannels) {
goog.base(
this,
audioContextManager,
idGenerator,
audioCat.audio.junction.Type.GAIN);
/**
* The gain node from the online audio context.
* @private {!GainNode}
*/
this.gainNode_ = audioContextManager.createGainNode();
if (goog.isDef(opt_numberOfOutputChannels)) {
audioContextManager.setChannelCount(
this.gainNode_, opt_numberOfOutputChannels);
}
this.setGain(gain);
};
goog.inherits(audioCat.audio.junction.GainJunction,
audioCat.audio.junction.Junction);
/**
* Obtains the gain of the junction.
* @param {!GainNode=} opt_gainNode Gets the gain of a different gain node if
* this argument is provided.
* @return {number} The gain of the junction.
*/
audioCat.audio.junction.GainJunction.prototype.getGain =
function(opt_gainNode) {
return this.audioContextManager.getGain(opt_gainNode || this.gainNode_);
};
/**
* Sets the gain of the junction.
* @param {number} gain The gain to set.
* @param {!GainNode=} opt_gainNode Sets the gain of a different gain node if
* this argument is provided.
*/
audioCat.audio.junction.GainJunction.prototype.setGain =
function(gain, opt_gainNode) {
this.audioContextManager.setGain(opt_gainNode || this.gainNode_, gain);
};
/** @override */
audioCat.audio.junction.GainJunction.prototype.cleanUp = function() {
if (this.cleanedUp) {
return;
}
this.gainNode_.disconnect();
this.cleanedUp = true;
};
/** @override */
audioCat.audio.junction.GainJunction.prototype.connect = function(junction) {
this.gainNode_.connect(junction.obtainRawNode());
junction.addPreviousJunction(this);
};
/** @override */
audioCat.audio.junction.GainJunction.prototype.disconnect = function() {
this.gainNode_.disconnect();
this.removeNextConnection();
};
/** @override */
audioCat.audio.junction.GainJunction.prototype.obtainRawNode =
function(opt_offlineAudioContext) {
if (opt_offlineAudioContext) {
var audioContextManager = this.audioContextManager;
var offlineGainNode = audioContextManager.createGainNode(
opt_offlineAudioContext);
audioContextManager.setChannelCount(
offlineGainNode,
audioContextManager.getChannelCount(this.gainNode_));
this.setGain(audioContextManager.getGain(this.gainNode_), offlineGainNode);
offlineGainNode.connect(
this.nextJunction.obtainRawNode(opt_offlineAudioContext));
return offlineGainNode;
}
return this.gainNode_;
};
|
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
export default new Vuex.Store({
state: {
sidebarPcClose: false,
sidebarmbClose: true,
bodyWidth: 0,
smWidth: 576
},
mutations: {
SIDEBARCOLLAPSE(state) {
if (state.bodyWidth > state.smWidth) {
state.sidebarPcClose = !state.sidebarPcClose;
} else {
state.sidebarmbClose = !state.sidebarmbClose;
}
},
GETBODYWIDTH(state) {
const item = document.querySelector("body");
state.bodyWidth = item.clientWidth;
}
},
actions: {
sidebarCollapse(context) {
context.commit("GETBODYWIDTH");
context.commit("SIDEBARCOLLAPSE");
}
},
modules: {}
});
|
import React from 'react';
import Product from '../Components/Product';
import Bud1 from './budweiser-photos/bud1.jpg'
import Bud2 from './budweiser-photos/bud2.jpg';
import Bud3 from './budweiser-photos/bud3.jpg';
import Bud4 from './budweiser-photos/bud4.jpg';
const Budweiser = (props) => {
return (
<div id='budwesier'>
<div className='container text-center'>
<h3 className='pt-4 pb-2'>Budweiser</h3>
<div className='row'>
<div className='col-lg-3'>
<Product img={Bud1} name='Budweiser 16 oz' price={1.25} cartState={props.cartState}
totalState={props.totalState} setTotal={props.setTotal} setCartState={props.setCartState}>
</Product>
</div>
<div className='col-lg-3'>
<Product img={Bud2} name='Budweiser 6 pack' price={Number(5).toFixed(2)} cartState={props.cartState}
totalState={props.totalState} setTotal={props.setTotal} setCartState={props.setCartState}>
</Product>
</div>
<div className='col-lg-3'>
<Product img={Bud3} name='Budweiser 40 oz' price={Number(2.50).toFixed(2)} cartState={props.cartState}
totalState={props.totalState} setTotal={props.setTotal} setCartState={props.setCartState}>
</Product>
</div>
<div className='col-lg-3'>
<Product img={Bud4} name='Budweiser 30 pack' price={Number(23).toFixed(2)} cartState={props.cartState}
totalState={props.totalState} setTotal={props.setTotal} setCartState={props.setCartState}>
</Product>
</div>
</div>
</div>
</div>
)
}
export default Budweiser;
|
import React, { useEffect, useMemo, useState, useCallback } from "react";
import { useDispatch, useSelector } from "react-redux";
import { Link } from "react-router-dom";
import * as R from "ramda";
import moment from "moment";
import "moment/locale/ru";
import Table from "@material-ui/core/Table";
import TableBody from "@material-ui/core/TableBody";
import TableCell from "@material-ui/core/TableCell";
import TableContainer from "@material-ui/core/TableContainer";
import TableHead from "@material-ui/core/TableHead";
import TableRow from "@material-ui/core/TableRow";
import Paper from "@material-ui/core/Paper";
import { InfoLikes } from "components/recipes/Likes";
import { FilterIngredietns } from "components/recipes/List/FilterIngredients";
import { HeadItem } from "components/recipes/List/HeadItem";
import { SearchInput } from "components/ui/SearchInput";
import { EditRecipe } from "components/ui/EditRecipe";
import { recipeActions } from "store/recipe/actions";
import { getItems } from "store/recipe/selectors";
import { getProfileId } from "store/auth/selectors";
import { useOrder } from "./useOrder";
import { getOptionsHeadItems } from "./optionsHeadItems";
import "./styles.css";
const optionsHeadItems = getOptionsHeadItems([
{
label: "Имя",
value: "name",
},
{
label: "Лайки",
value: "likes",
isDisabledOrder: true,
},
{
label: "Сложность",
value: "complexity",
},
{
label: "Ингредиенты",
value: "ingredients",
isDisabledOrder: true,
},
{
label: "Дата Создания",
value: "createdAt",
},
]);
export const RecipesList = () => {
const dispatch = useDispatch();
const [searchValue, setSearchValue] = useState("");
const [filterIngredietns, setFilterIngredients] = useState([]);
const [order, handleChangeOrder] = useOrder(optionsHeadItems);
const items = useSelector(getItems);
const userId = useSelector(getProfileId);
useEffect(() => {
dispatch(
recipeActions.getItems({
searchValue,
ingredients: filterIngredietns,
...order,
})
);
}, [dispatch, searchValue, order, filterIngredietns]);
const handleOnSearch = useCallback((value) => {
setSearchValue(value);
}, []);
const headItemsContent = useMemo(() => {
return {
ingredients: (ref) => (
<FilterIngredietns
innerRef={ref}
onChange={(value) => setFilterIngredients(R.map(R.prop("id"))(value))}
/>
),
};
}, []);
const rendererHeadItems = useMemo(() => {
return R.map((item) => {
return (
<HeadItem
key={item.value}
value={item.value}
label={item.label}
isDisabledOrder={item.isDisabledOrder}
order={order}
handleChangeOrder={handleChangeOrder}
>
{item.content}
</HeadItem>
);
})(optionsHeadItems.getItemsWithContent(headItemsContent));
}, [order, handleChangeOrder, headItemsContent]);
const rendererItems = useMemo(() => {
return R.compose(
R.map((item) => {
const isItemCurrentUser = R.compose(
R.equals(userId),
R.path(["user", "id"])
)(item);
return (
<TableRow key={item.id}>
<TableCell component="th" scope="row">
<div className="recipe-item-name-wrapper">
<Link
className="recipe-item-name"
to={`/recipe/info/${item.id}`}
>
{item.name}
</Link>
{isItemCurrentUser && <EditRecipe id={item.id} />}
</div>
</TableCell>
<TableCell component="th" scope="row">
<InfoLikes items={item.likes} recipeId={item.id} />
</TableCell>
<TableCell component="th" scope="row">
{`${item.complexity}/10`}
</TableCell>
<TableCell component="th" scope="row">
<div className="recipe-item-ingredients-list">
{R.map((ingredient) => {
return <span key={ingredient.id}>{ingredient.name}</span>;
})(item.ingredients)}
</div>
</TableCell>
<TableCell component="th" scope="row">
{moment(item.createdAt).locale("ru").format("lll")}
</TableCell>
</TableRow>
);
}),
R.values
)(items);
}, [items, userId]);
return (
<TableContainer component={Paper}>
<SearchInput onSearch={handleOnSearch} />
<Table size="small" aria-label="a dense table">
<TableHead>
<TableRow>{rendererHeadItems}</TableRow>
</TableHead>
<TableBody>{rendererItems}</TableBody>
</Table>
</TableContainer>
);
};
|
import React from 'react';
import Avatar from '@material-ui/core/Avatar';
import Snackbar from '@material-ui/core/Snackbar';
import Button from '@material-ui/core/Button';
import CssBaseline from '@material-ui/core/CssBaseline';
import TextField from '@material-ui/core/TextField';
import Link from '@material-ui/core/Link';
import Paper from '@material-ui/core/Paper';
import Grid from '@material-ui/core/Grid';
import LockOutlinedIcon from '@material-ui/icons/LockOutlined';
import Typography from '@material-ui/core/Typography';
import { makeStyles } from '@material-ui/core/styles';
import image from '../images/signin.jpg';
import BackendServices from '../services/backendServices';
const useStyles = makeStyles(theme => ({
root: {
height: '100vh',
},
imageDiv: {
backgroundSize: 'cover',
width: '100%',
height: '100%',
backgroundPosition: 'center',
},
image: {
position: 'absolute',
top: 0
},
title: {
position: 'absolute',
margin: '30px',
zIndex: 1,
},
paper: {
margin: theme.spacing(8, 4),
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
},
avatar: {
margin: theme.spacing(1),
backgroundColor: theme.palette.secondary.main,
},
form: {
width: '100%', // Fix IE 11 issue.
marginTop: theme.spacing(1),
},
submit: {
margin: theme.spacing(3, 0, 2),
},
}));
export default function SignIn() {
const classes = useStyles();
const [values, setValues] = React.useState({
email: '',
password: ''
});
const [state, setState] = React.useState({
open: false,
message: '',
vertical: 'top',
horizontal: 'right',
});
const { vertical, horizontal, open, message } = state;
const handleClose = () => {
setState({ ...state, open: false });
};
const handleChange = prop => event => {
setValues({ ...values, [prop]: event.target.value });
};
const login = async () => {
try {
let response = await BackendServices.login({
practiceEmail: values.email,
password: values.password
});
if (response.data.status) {
setState({ ...state, open: true, message: 'Login Successfully!' });
localStorage.setItem('email', response.data.data.email);
localStorage.setItem('userId', response.data.data.userId);
localStorage.setItem('token', response.data.data.token);
window.location.pathname = '/profile';
} else {
setState({ ...state, open: true, message: 'Invalid Data!' });
}
} catch (error) {
if (new Error(error).message === 'Error: Request failed with status code 422')
setState({ ...state, open: true, message: 'Invalid Data!' });
else
setState({ ...state, open: true, message: new Error(error).message });
}
}
return (
<Grid container component="main" className={classes.root}>
<CssBaseline />
<Snackbar
anchorOrigin={{ vertical, horizontal }}
key={`${vertical},${horizontal}`}
open={open}
onClose={handleClose}
ContentProps={{
'aria-describedby': 'message-id',
}}
message={<span id="message-id">{message}</span>}
/>
<Grid item xs={false} sm={4} md={7} className={classes.imageDiv} >
<Typography component="h1" variant="h4" className={classes.title}>
MeetMe
</Typography>
<img src={image} alt="medical" className={classes.image} />
</Grid>
<Grid item xs={12} sm={8} md={5} component={Paper} elevation={6} square>
<div className={classes.paper}>
<Avatar className={classes.avatar}>
<LockOutlinedIcon />
</Avatar>
<Typography component="h1" variant="h5">
Sign In
</Typography>
<form className={classes.form} noValidate>
<TextField
variant="outlined"
margin="normal"
required
fullWidth
id="email"
label="Email Address"
name="email"
value={values.email}
onChange={handleChange('email')}
autoComplete="email"
inputProps={{
'aria-label': 'email',
}}
autoFocus
/>
<TextField
variant="outlined"
margin="normal"
required
fullWidth
name="password"
label="Password"
type="password"
id="password"
value={values.password}
onChange={handleChange('password')}
inputProps={{
'aria-label': 'password',
}}
autoComplete="current-password"
/>
<Button
type="button"
fullWidth
variant="contained"
color="primary"
className={classes.submit}
onClick={login}
>
Sign In
</Button>
<Grid container>
<Grid item>
<Link href="/signup" variant="body2">
{"Don't have an account? Sign Up"}
</Link>
</Grid>
</Grid>
</form>
</div>
</Grid>
</Grid>
);
}
|
/*
EXERCISE 51:
Create a function called "build2DWithIdx" that takes a parameter called num (a non-negative number) and builds a 2D array with the dimensions num * num
and filling in each sub-element with a string of the row index next to the column index.
For example:
build2D(1) should return [['00']]
build2d(2) should return [['00','01'],['10','11']]
build2d(0) should return []
build2d(3) should return [['01','02','03']',['10','11','12']',['20','21','22']]
*/
function build2DWithIdx(num) {}
|
import React from 'react';
import GraphicLevel from './GraphicLevel.js';
import { Segment, Header, Grid } from 'semantic-ui-react'
import PropTypes from 'prop-types';
const GraphicComponent = (props) => {
return (
<div>
<Segment className="component" textAlign='center'>
<Grid>
<Grid.Column floated='left' width={8}>
<GraphicLevel {...props} />
</Grid.Column>
<Grid.Column width={8}>
<Header as='h2'> Levels of Graphic & Interactivity </Header>
</Grid.Column >
</Grid>
</Segment>
</div>
)
}
GraphicComponent.PropTypes = {
graphicLevel: PropTypes.number.isRequired,
newGraphicLevel: PropTypes.func.isRequired
}
export default GraphicComponent
|
var searchData=
[
['path',['PATH',['../prex_8c.html#ab0139008fdda107456f13f837872b410',1,'prex.c']]],
['path_5fmax',['PATH_MAX',['../mutt_8h.html#ae688d728e1acdfe5988c7db45d6f0166',1,'mutt.h']]],
['pgp_5fencrypt',['PGP_ENCRYPT',['../ncrypt_2lib_8h.html#a6694d25dff1ee1958351160a84bb2dc0',1,'lib.h']]],
['pgp_5fgoodsign',['PGP_GOODSIGN',['../ncrypt_2lib_8h.html#ae480697fdeb3d6b2c127e0ae36c52e8e',1,'lib.h']]],
['pgp_5finline',['PGP_INLINE',['../ncrypt_2lib_8h.html#a68503f0e36de213094c8546b4f74eef1',1,'lib.h']]],
['pgp_5fkey',['PGP_KEY',['../ncrypt_2lib_8h.html#abd2087cae2885c199218f5530ce7945b',1,'lib.h']]],
['pgp_5fkv_5faddr',['PGP_KV_ADDR',['../pgpkey_8c.html#a6e39bb3b1a46448f00f6591543553baf',1,'pgpkey.c']]],
['pgp_5fkv_5fmatch',['PGP_KV_MATCH',['../pgpkey_8c.html#a40d5acd8017ff315f8840d04c56cc8ca',1,'pgpkey.c']]],
['pgp_5fkv_5fno_5fflags',['PGP_KV_NO_FLAGS',['../pgpkey_8c.html#a0bfe8fe961efecdedbf5f47cd0c75500',1,'pgpkey.c']]],
['pgp_5fkv_5fstring',['PGP_KV_STRING',['../pgpkey_8c.html#a6def4a22eecb2b0aadca924b534f71c7',1,'pgpkey.c']]],
['pgp_5fkv_5fstrongid',['PGP_KV_STRONGID',['../pgpkey_8c.html#a3834779d4fa65b6cd9afc052e8dcc723',1,'pgpkey.c']]],
['pgp_5fkv_5fvalid',['PGP_KV_VALID',['../pgpkey_8c.html#a5403e07f6af4309818f8f3c470116833',1,'pgpkey.c']]],
['pgp_5fsign',['PGP_SIGN',['../ncrypt_2lib_8h.html#a14f75a650c49341776276f44881d54b2',1,'lib.h']]],
['pgp_5ftraditional_5fchecked',['PGP_TRADITIONAL_CHECKED',['../ncrypt_2lib_8h.html#a3c4cec129dc84794f15f44382c25fc36',1,'lib.h']]],
['pka_5fnotation_5fname',['PKA_NOTATION_NAME',['../crypt__gpgme_8c.html#a7808a5649f1126b2c55383593dc453d6',1,'crypt_gpgme.c']]],
['pop_5fcache_5flen',['POP_CACHE_LEN',['../pop_2private_8h.html#a606d455144b12dcddd75503a8fb737a4',1,'private.h']]],
['pop_5fcmd_5fresponse',['POP_CMD_RESPONSE',['../pop_2private_8h.html#a320026da03c4cc9c4b7a15a78dd77568',1,'private.h']]],
['pop_5fport',['POP_PORT',['../pop_2private_8h.html#ac8bd6d29115abf7dcc47ae26f0cbb3d6',1,'private.h']]],
['pop_5fquery',['pop_query',['../pop_2private_8h.html#a517e9120e2ec9d86ea2f93dd10696e4f',1,'private.h']]],
['pop_5fssl_5fport',['POP_SSL_PORT',['../pop_2private_8h.html#a2e7c786c53a65d43284b8de44a98a5fc',1,'private.h']]],
['prefix_5flast',['PREFIX_LAST',['../config_2sort_8c.html#ab46bc6b350e3c88c5b8d61d060752a42',1,'sort.c']]],
['prefix_5freverse',['PREFIX_REVERSE',['../config_2sort_8c.html#a1b0cb48d9bf1a33177b94a344be2831b',1,'sort.c']]],
['prex_5fdow',['PREX_DOW',['../prex_8c.html#a62b36cd222fb65c5b9777db5b0d6d1c8',1,'prex.c']]],
['prex_5fdow_5fnocase',['PREX_DOW_NOCASE',['../prex_8c.html#a187af9207700c77f9bce74f39b3b4290',1,'prex.c']]],
['prex_5fmonth',['PREX_MONTH',['../prex_8c.html#a7f1d6e69661920424c3dab13811cf980',1,'prex.c']]],
['prex_5ftime',['PREX_TIME',['../prex_8c.html#a764a49e2052d6153d8d48ab29a8d826c',1,'prex.c']]],
['prex_5fyear',['PREX_YEAR',['../prex_8c.html#ab22a780ee67ee6a818fcc4d34c0da3a7',1,'prex.c']]],
['public_5fkey_5fblock',['PUBLIC_KEY_BLOCK',['../crypt__gpgme_8c.html#aa313b6df071b5718005a87f7e33d2da6',1,'crypt_gpgme.c']]]
];
|
// @ts-expect-error 'createTransformer is nullable, but there is no easy way to make a non-null assertion in JS'
// eslint-disable-next-line @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-var-requires
module.exports = require('babel-jest').default.createTransformer({
'presets': ['@babel/preset-env']
});
|
exports.config = {
tests: './*_test.js',
output: './output',
helpers: {
Puppeteer: {
url: 'http://localhost:8000/',
show: true, // <--追記
}
},
// 追記ここから
plugins: {
stepByStepReport: {
enabled: true,
deleteSuccessful: false,
},
},
// 追記ここまで
include: {
I: './steps_file.js'
},
bootstrap: null,
mocha: {},
name: 'puppeteer-sample'
}
|
var fred = ['fred', 'flinestone', 'fred@gmail.com', 50 ];
console.log('length =', fred.length)
//for(var i = 0; i < fred.lengthh; i++) {
for (var i in fred) {
if (i == 0)
console.log ('First name: ', fred[i])
else if (i == 1)
console.log ('Last name: ', fred[i])
else if (i == 2)
console.log ('Email name: ', fred[i])
else if (i == 3)
console.log('Age', fred[i])
console.log(i);
console.log(fred[i]);
}
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SMSController = exports.smsController = void 0;
const smsManager_1 = require("../data/smsManager");
const twilio_1 = require("../data/sms/twilio");
class SMSController {
sendSMS(to, msg) {
let sms = new smsManager_1.SMSManager(new twilio_1.twilioSMS());
return sms.sendSMS(to, msg);
}
}
exports.SMSController = SMSController;
let smsController = new SMSController();
exports.smsController = smsController;
|
import React from 'react';
import { Link } from 'react-router-dom';
import { makeStyles } from '@material-ui/core/styles';
import { Card, CardActionArea, CardContent, CardMedia, Typography } from '@material-ui/core';
import { formatDistanceStrict } from 'date-fns/esm'
const dateTime = require('date-time');
const useStyles = makeStyles({
root: {
width: '20vw',
margin: 10,
},
media: {
height: '40vh',
width: '100%',
},
details: {
display: 'flex',
flexDirection: 'column',
justifyContent: 'flex-start',
width: '100%',
},
title: {
fontSize: '1.1em',
textAlign: 'left',
width: '60%',
overflow: 'hidden',
textOverflow: 'ellipsis'
},
price: {
fontSize: '1.1em',
textAlign: 'left',
color: 'green'
},
time: {
fontSize: '0.9em',
textAlign: 'left',
color: '#CCC'
}
});
export default function ProductCard({ id, src, name, price, city, date }) {
const classes = useStyles();
const postDate = date;
const distance = formatDistanceStrict(
new Date(postDate),
new Date(dateTime())
)
const title = name.replace(/ /g, '_');
return (
<Link
to={{
pathname: `/item/${id}/${title}`,
state: { id },
}}
style={{ textDecoration: 'none' }}
onClick={() => localStorage.setItem('productId', id)}
>
<Card className={classes.root}>
<CardActionArea>
<CardMedia className={classes.media} image={src} />
<CardContent className={classes.details}>
<div style={{ display: 'flex', justifyContent: 'space-between' }}>
<Typography noWrap className={classes.title}>
{name}
</Typography>
<Typography className={classes.price}>
{price} SEK
</Typography>
</div>
<Typography className={classes.time}>
{distance} ago in {city}
</Typography>
</CardContent>
</CardActionArea>
</Card>
</Link>
);
}
|
const initState = {
coupons: [],
};
export const couponReducer = (state = initState, action) => {
switch (action.type) {
case "ADD_COUPON": {
const newCoupon = action.coupon;
return {
...state,
coupons: [...state.coupons, newCoupon],
};
}
case "ADD_COUPON_ERROR": {
return state;
}
case "UPDATE_COUPON": {
const newDiscount = action.discount;
const coupon = state.coupons.filter(
(item) => item.name === action.coupon.name
);
coupon.discount = newDiscount;
return {
...state,
coupons: [...state.coupons],
};
}
default:
return state;
}
};
|
var error, MError;
module.exports = function(app) {
const ErrorReport = app.ErrorReport;
if (!error) {
MError = Ember.Object.extend({
errorHandler: error,
name: 'Error',
message: 'some error occurred',
liveTime: 0,
icon: 'err',
init: function(err) {
this._super();
if (err.status === 0) {
this.setProperties({
name: 'Offline',
message: 'Please check internet connection',
});
} else if (err.responseJSON) {
if (err.responseJSON.name) {
this.set('name', err.responseJSON.name);
}
if (err.responseJSON.message) {
this.set('message', err.responseJSON.message);
if (NODE_DEV) {
this.set('message', this.get('message') + '\n' + err.responseJSON.stack);
}
}
} else if (err.name || err.message) {
this.set('name', err.name);
if (err.stack) {
if (NODE_DEV) {
this.set('message', err.message + '\n' + err.stack);
}
} else {
this.set('message', err.message);
}
} else if (typeof err === 'string') {
this.set('message', err);
}
if (NODE_DEV) {
if (console.trace) {
console.trace();
}
}
// if (options.liveTime) {
// Ember.run.later(this, function () {
// this.errorHandler.removeError(this);
// }, options.liveTime);
// }
}
});
error = Ember.Object.create({
errors: [],
set: function(err, report = true) {
if (err.status === 401) {
return err;
} else if (typeof err === 'string') {
this.errors.pushObject(new MError(new Error(err)));
} else {
this.errors.pushObject(new MError(err));
}
if (!err.status && report === true) {
app.ErrorReport.report(err);
}
return err;
},
actions: {
removeError: function(err) {
this.errors.removeObject(err);
}
}
});
}
return error;
};
|
define([
'common/views/module',
'client/views/table',
'client/views/date-picker',
'client/views/json-summary'
], function (ModuleView, Table, DatePicker, JsonSummary) {
return ModuleView.extend({
datePickerClass: DatePicker,
views: function () {
var pageType = this.model.get('parent').get('page-type');
var views = {};
if (pageType === 'module') {
if (this.hasTable) {
views['.visualisation-table'] = {
view: Table,
options: this.visualisationOptions
};
}
if (this.hasDatePicker) {
views['.date-picker'] = {
view: this.datePickerClass
};
}
if (this.collection) {
views['.json-summary'] = {
view: JsonSummary
};
}
}
return _.extend(ModuleView.prototype.views.apply(this, arguments), views);
}
});
});
|
var expect = require('expect');
var { generateMessage, generateLocationMessage } = require('./message');
describe('generateMessage', () => {
it('should generate correct message object', () => {
var from = 'Jen'
,text = 'some message'
,message = generateMessage(from,text);
expect(message.createdAt).toBeA('number');
expect(message).toInclude({from,text});
})
})
describe('generateLocationMessage', () => {
it('should generate correct location message object', () => {
var from = 'Jen'
,coords = {latitude:1,longitude:1}
,url = 'https://www.google.com/maps?q=1,1';
var message = generateLocationMessage(from,coords);
expect(message.createdAt).toBeA('number');
expect(message).toInclude({from,url});
})
})
|
const request = require('request-promise-native')
const IntegrationCopyRequest = require('../models/integrationCopyRequest')
const IntegrationCopyItem = require('../models/integrationCopyItem')
const baseApi = "https://api.apigum.com";
class Integration {
constructor(apiKey){
this.APIKey = apiKey
}
updateCredentials(apiKey, credentials){
throw new Error('Not Implemented');
}
async create(triggerApp, actionApp, integrationId){
// set trigger
const trigger = new IntegrationCopyItem();
trigger.AppId = triggerApp.AppId;
Object.entries(triggerApp.Keys).forEach((item) => {
trigger.KeyValuePairs.push({
Name: item[0],
Value: item[1],
})
})
// set action
const action = new IntegrationCopyItem();
action.AppId = actionApp.AppId;
Object.entries(actionApp.Keys).forEach((item) => {
action.KeyValuePairs.push({
Name: item[0],
Value: item[1],
})
})
const integration = new IntegrationCopyRequest();
integration.TriggerKeys.push(trigger);
integration.ActionKeys.push(action);
return await request({
uri: `${baseApi}/v1/integrations/${integrationId}/copy`,
headers: {
Authorization: `Basic ${new Buffer(`${this.APIKey}:X`, "ascii").toString('base64')}`
},
method: 'POST',
body: integration,
json: true
})
}
async updateScript(integrationId, script){
const body = {
Code: script
}
return await request({
uri: `${baseApi}/v1/integrations/${integrationId}/code`,
headers: {
Authorization: `Basic ${new Buffer(`${this.APIKey}:X`, "ascii").toString('base64')}`
},
method: 'PUT',
body,
json: true
})
}
async delete(integrationId){
return await request({
uri: `${baseApi}/v1/integrations/${integrationId}`,
headers: {
Authorization: `Basic ${new Buffer(`${this.APIKey}:X`, "ascii").toString('base64')}`
},
method: 'DELETE'
})
}
clearCache(integrationId){
throw new Error('Not Implemented');
}
async publish(integrationId){
return await request({
uri: `${baseApi}/v1/integrations/${integrationId}/publish`,
headers: {
Authorization: `Basic ${new Buffer(`${this.APIKey}:X`, "ascii").toString('base64')}`
},
method: 'PUT',
body: null
})
}
async unpublish(integrationId){
return await request({
uri: `${baseApi}/v1/integrations/${integrationId}/unpublish`,
headers: {
Authorization: `Basic ${new Buffer(`${this.APIKey}:X`, "ascii").toString('base64')}`
},
method: 'PUT',
body: null
})
}
}
module.exports = Integration
|
const formatTime = date => {
const year = date.getFullYear()
const month = date.getMonth() + 1
const day = date.getDate()
const hour = date.getHours()
const minute = date.getMinutes()
const second = date.getSeconds()
return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
const formatNumber = n => {
n = n.toString()
return n[1] ? n : '0' + n
}
const cmdservice = {
serviceUUID: "000000FF-0000-1000-8000-00805F9B34FB",
charUUID: "0000FF01-0000-1000-8000-00805F9B34FB",
}
const notifyservice = {
serviceUUID: "000000EE-0000-1000-8000-00805F9B34FB",
charUUID: "0000EE01-0000-1000-8000-00805F9B34FB",
}
module.exports = {
formatTime: formatTime,
sendCmd: sendCmd,
buf2string: buf2string,
enableNotify: enableNotify,
disableNotify: disableNotify
}
/* 将Arraybuffer数据转换成string格式 */
function buf2string(buffer) {
var arr = Array.prototype.map.call(new Uint8Array(buffer), x => x)
return arr.map((char, i) => {
return String.fromCharCode(char);
}).join('');
}
/* 将操作码op和要发送的字符串str包装成网关能够识别的蓝牙数据包 */
function cmdFormat(op, str) {
var len;
if(str==null)
{
len=3;
}
else{
len = str.length + 3;
}
let buffer = new ArrayBuffer(len);
let dataview = new DataView(buffer);
dataview.setUint8(0, 0xfe);
dataview.setUint8(1, op);
dataview.setUint8(len - 1, 0xff);
for (var i = 2, j = 0; i < len - 1; i++, j++) {
dataview.setUint8(i, str.charAt(j).charCodeAt())
}
return dataview.buffer;
}
/*蓝牙发送函数,将待发送字符串加上头尾及操作符;当发送长度大于20时,自动切片发送,每片间隔300ms */
function sendCmd(deviceid, op, str) {
let buffer = cmdFormat(op, str);
let pos = 0;
let len = buffer.byteLength;
while (len > 0) {
let tmpbuffer;
if (len > 20) {
tmpbuffer = buffer.slice(pos, pos + 20);
pos += 20;
len -= 20;
wx.writeBLECharacteristicValue({
deviceId: deviceid,
serviceId: cmdservice.serviceUUID,
characteristicId: cmdservice.charUUID,
value: tmpbuffer,
success: function(res) {
}
})
} else {
tmpbuffer = buffer.slice(pos, pos + len);
pos += len;
len -= len;
wx.writeBLECharacteristicValue({
deviceId: deviceid,
serviceId: cmdservice.serviceUUID,
characteristicId: cmdservice.charUUID,
value: tmpbuffer,
success: function(res) {
}
})
}
/*延迟300ms */
setTimeout(() => {
}, 300)
}
}
function enableNotify(deviceid){
/**使能蓝牙Notify功能 */
wx.notifyBLECharacteristicValueChange({
state: true,
deviceId: deviceid,
serviceId: "000000EE-0000-1000-8000-00805F9B34FB",
characteristicId: "0000EE01-0000-1000-8000-00805F9B34FB",
success(res) {
return res;
}
})
}
function disableNotify(deviceid) {
/**关闭蓝牙Notify功能 */
wx.notifyBLECharacteristicValueChange({
state: false,
deviceId: deviceid,
serviceId: "000000EE-0000-1000-8000-00805F9B34FB",
characteristicId: "0000EE01-0000-1000-8000-00805F9B34FB",
success(res) {
}
})
}
function exceCmd(deviceid, op, str){
var msg="";
/**使能蓝牙Notify功能 */
wx.notifyBLECharacteristicValueChange({
state: true,
deviceId: deviceid,
serviceId: "000000EE-0000-1000-8000-00805F9B34FB",
characteristicId: "0000EE01-0000-1000-8000-00805F9B34FB",
success(res) {
return res;
}
})
/**通过蓝牙发送操作指令 */
sendCmd(deviceid,op,str);
/**通过蓝牙notify接收处理指令回复 */
wx.onBLECharacteristicValueChange(function (res) {
console.log(res.value);
let dataview = new DataView(res.value);
let len = dataview.byteLength;
let head = 0;
let end = len;
if (dataview.getUint8(0) == 0xfe) {
head += 2;
}
if (dataview.getUint8(len - 1) == 0xff) {
end -= 1;
}
msg += buf2string(res.value.slice(head, end));
})
wx.notifyBLECharacteristicValueChange({
state: false,
deviceId: deviceid,
serviceId: "000000EE-0000-1000-8000-00805F9B34FB",
characteristicId: "0000EE01-0000-1000-8000-00805F9B34FB",
success(res) {
}
})
}
|
/**
* 캐릭터 개체를 나타내는 클래스
*
* - 이 클래스는 캐릭터의 기본적인 정보와 데이터들을 소유하고 있다.
*
* - 구체적인 기능들은 CharacterComponent를 상속받아 구현하는, 각 기능별 컴포넌트 클래스들이 담당한다.
*
* - 캐릭터는 기능에 따라 여러 개의 CharacterComponent 객체를 소유한다.
*/
cc.Class(
{
extends : cc.Component,
properties :
{
},
// LIFE-CYCLE CALLBACKS:
onLoad : function()
{
console.log("Character.onLoad()");
},
start : function()
{
console.log("Character.start()");
},
update : function(deltaTime)
{
},
lateUpdate : function()
{
},
onDestory : function()
{
console.log("Character.onDestroy()");
}
});
|
var localization = require('./localization');
localization.start().then(function() {
var interval = setInterval(function() {
console.log('PRESENCE: ', localization.getPresenceRSSIMap());
console.log('--------------------------------------------');
}, 2000);
var interval = setInterval(function() {
console.log('FILAMENT: ', localization.getFilamentRSSIMap());
console.log('--------------------------------------------');
}, 2000);
});
|
/* This is functionally the same as goal.js, but more readable so
* you don't have to de-obfuscate it yourself.
*/
function g(x) {
if (x === 'al')
return 'gal';
else if (x === undefined) {
var os = '';
return function (y) {
os += 'o';
if (y === 'al')
return 'g' + os + 'al';
else if (y === undefined)
return arguments.callee;
};
}
}
print(g('al'));
print(g()('al'));
print(g()()('al'));
print(g()()()('al'));
|
import React from "react";
export const LoginContext = React.createContext({ userInfo: null });
|
angular.module('shinetech-app').constant('emailtemplate', {
webname: 'Shinetech Plan Poker',
weburl: 'http://shinetechchina.com.cn/',
webcompany: 'Shinetechchina',
webaddress: 'Shaanxi xi\'an',
webtel: '15812345678',
webmail: '472514904@qq.com',
emailsmtp: 'smtp.163.com',
emailssl:'1',
emailport:'25',
emailfrom: 'skiller1651@163.com',
emailusername:'skiller1651@163.com',
emailpassword: 'cXd3bHp6MDIyNA',
emailnickname:'Shinetech'
});
|
import './users.css';
// Icons
import { FaPlus } from "react-icons/fa";
import Table from '../../core/table/table';
import { useState, useEffect } from 'react';
function Users() {
const axios = require('axios').default;
let [rows, setRows] = useState([]);
useEffect(() => {
; (async () => {
const { data } = await axios.get('https://fiap-back-end.herokuapp.com/users');
setRows(data.map(el => ({
id: el.id,
name: el.name,
email: el.email,
document: el.document,
birthday: el.birthday,
mobile: el.mobile,
isEnabled: el.isEnabled ? 'Sim' : 'Não'
})
));
})();
}, [axios]);
return (
<>
<div className="table-header">
<h3>Usuários</h3>
<a href="/users/new">
<span>Novo</span> <FaPlus />
</a>
</div>
{
rows.length > 0 && <Table columns={['ID', 'Nome', 'E-mail', 'Document', 'Data de nascimento', 'Telefone', 'Ativo']} rows={rows} path="users" />
}
</>
);
}
export default Users;
|
'use strict'
document.write('<h2>Hello webpack demo2</h2>');
|
import React, {Component} from 'react';
import {
KeyboardAvoidingView,
StyleSheet,
Text,
View,
Image,
ImageBackground,
TouchableOpacity,
TextInput,
ActivityIndicator,Vibration
} from 'react-native';
import {
Toast,
ScrollableTab,
Separator,
Item,
Icon,
Input
} from 'native-base';
import {white} from 'ansi-colors';
const axios = require('axios');
import * as Font from 'expo-font'
import {NavigationActions} from 'react-navigation';
import {AsyncStorage} from 'react-native';
const DURATION = 20000
const PATTERN = [10]
export default class Login extends Component {
constructor(props) {
super(props)
this.state = {
email: null,
password: null,
leaderData: [],
secureTextEntry: true,
loading: false,
message: '',
fontLoaded: false
}
}
storeLoginSession = async() => {
try {
await AsyncStorage.setItem('loginEmail', this.state.leaderData.Email);
Toast.show({text: 'Logging you in...', buttonText: 'Okay', duration: 4000})
// alert("Nice saving data")
} catch (error) {
alert("Error saving data")
}
}
storeLoginSession2 = async() => {
try {
await AsyncStorage.setItem('loginData', JSON.stringify(this.state.leaderData));
Toast.show({text: `Logged in as ${this.state.leaderData.Email}`, buttonText: 'Okay', duration: 4000})
//alert("Nice saving data")
} catch (error) {
alert("Error saving data")
}
}
removeLoginSession = async() => {
try {
await AsyncStorage.removeItem('loginEmail');
alert("Nice removing data")
} catch (error) {
alert("Error saving data")
}
}
retrieveLoginSession = async() => {
try {
const value = await AsyncStorage.getItem('isLoggedIn');
if (value !== null) {
alert("data is " + value)
console.log(value);
} else {
alert("no data")
}
} catch (error) {
alert("Error retrieving data" + error)
// Error retrieving data
}
};
// componentDidMount(){ //this.retrieveData() //this.storeData()
// //this.removeLoginSession() }
async componentDidMount() {
await Font.loadAsync({'Roboto_medium': require('../assets/Roboto-Medium.ttf')});
this.setState({fontLoaded: true});
}
showPass = () => {
this.setState({
secureTextEntry: !this.state.secureTextEntry
})
}
loginFn = () => {
this.setState({message: 'Please wait...', loading: true})
4
if (this.state.email === null || this.state.password === null) {
alert("Fields cannot be empty!")
this.setState({message: '', loading: false})
return 0;
}
setTimeout(() => {
axios({method: 'GET', url: `http://134.209.148.107/api/leaders/${this.state.email}/`}).then(res => {
this.setState({leaderData: res.data})
//alert(res.data.password)
if (this.state.email === res.data.Email && this.state.password === res.data.password) {
//alert("Niccee")
this.storeLoginSession2()
setTimeout(() => {
// this.props.navigation.reset([NavigationActions.navigate({ routeName:
// 'Dashboard' })], 0)
// this.props.navigation.navigate('Dashboard',{leaderName:this.state.leaderData.N
// ame})
this
.props
.navigation
.reset([NavigationActions.navigate({
routeName: 'Dashboard',
params: {
leaderName: this.state.leaderData.Name,
leaderData: this.state.leaderData
}
})], 0)
}, 1000);
} else {
this.setState({message: '', loading: false})
alert("Email and password do not match!")
Vibration.vibrate(PATTERN)
this.setState({password: null})
this.set
}
}).catch((error) => {
this.setState({message: '', loading: false})
console.log(error.response.status)
alert(error.response.stat)
if(error.response.status === 404){
alert("User does not exist")
}
})
}, 2000);
}
render() {
return (
<View style={styles.container}>
<ImageBackground
source={require('../assets/mbodabg-01.png')}
style={{
height: '100%',
width: '100%'
}}>
<KeyboardAvoidingView
style={{
backgroundColor: 'rgba(0,0,0,.2)',
flex: 1
}}
behavior="padding"
enabled>
<View
style={{
backgroundColor: 'rgba(0,0,0,.2)',
flex: 1,
height: '100%',
alignContent: 'flex-end',
justifyContent: 'flex-end',
padding: 0,
backgroundColor: 'rgba(0,0,0,.2)'
}}>
<View
style={{
padding: 10,
width: '100%'
}}>
<Text
style={{
color: 'white',
fontSize: 30,
fontWeight: 'bold',
padding: 20,
textAlign: 'center'
}}>Login</Text>
<TextInput
autoCapitalize='none'
onChangeText={(email) => this.setState({email})}
value={this.state.email}
keyboardType='email-address'
placeholder="Enter your email"
placeholderTextColor='#efefef'
style={{
color: 'white',
padding: 20,
marginBottom: 20,
borderWidth: 1,
borderColor: 'white',
width: '100%',
borderRadius: 4,
backgroundColor: 'rgba(0,0,0,.8)'
}}></TextInput>
{/* <TextInput
onChangeText={(password) => this.setState({password})}
value={this.state.password}
secureTextEntry={this.state.secureTextEntry}
placeholder='Password'
placeholderTextColor='#efefef'
style={{
color: 'white',
padding: 20,
marginBottom: 10,
borderWidth: 1,
borderColor: 'white',
width: '100%',
borderRadius: 4,
backgroundColor: 'rgba(0,0,0,.8)'
}}></TextInput> */}
<TextInput
onChangeText={(password) => this.setState({password})}
value={this.state.password}
secureTextEntry={this.state.secureTextEntry}
placeholder='Password'
placeholderTextColor='#efefef'
style={{
color: 'white',
padding: 20,
marginBottom: 10,
borderWidth: 1,
borderColor: 'white',
width: '100%',
borderRadius: 4,
backgroundColor: 'rgba(0,0,0,.8)',
width:'100%'
}}></TextInput>
{this.state.secureTextEntry
? <TouchableOpacity
onPress={() => this.showPass()}
style={{
alignItems: 'center',
padding: 20,
marginBottom: 0,
}}>
<Text style={{color:'orange'}}>
Show
<Icon style={{color:'white',fontSize:15}} active name='eye' type="FontAwesome" />
</Text>
</TouchableOpacity>
: <TouchableOpacity
onPress={() => this.showPass()}
style={{
alignItems: 'center',
padding: 20,
marginBottom: 0,
}}><Text style={{color:'orange'}}>
Hide
<Icon color='white' style={{color:'white',fontSize:15,marginLeft:10}} active name='eye-slash' type="FontAwesome" />
</Text>
</TouchableOpacity>
}
</View>
{this.state.loading
? <TouchableOpacity
disabled
style={{
backgroundColor: '#efefef',
padding: 20,
alignItems: 'center'
}}>
<ActivityIndicator size="small" color="#0000ff"/>
</TouchableOpacity>
: <TouchableOpacity
onPress={() => this.loginFn()}
style={{
backgroundColor: 'rgba(15,157,88,.8)',
padding: 20,
alignItems: 'center',
borderRadius: 2,
width: '100%',
marginBottom: 0
}}>
<Text
style={{
letterSpacing: 4,
color: 'white'
}}>SUBMIT</Text>
</TouchableOpacity>
}
</View>
</KeyboardAvoidingView>
</ImageBackground>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1
}
});
|
/**기린은 중국집에서 친구들과 만나기로 하고, 음식을 시켰습니다.
음식이 나오고 한참을 기다렸지만 만나기로 한 친구 2명이 오지 않았어요.
기린은 배가 너무 고파 혼자 음식을 먹기 시작합니다. 원형 테이블에는 N 개의 음식들이 있습니다.
한 개의 음식을 다 먹으면 그 음식의 시계방향으로 K 번째 음식을 먹습니다.
하지만 아직 오지 않은 친구들을 위해 2개의 접시를 남겨야 합니다.
마지막으로 남는 음식은 어떤 접시인가요?
입력은 2개의 정수로 이루어지며 공백으로 구분되어 입력됩니다.
첫 번째 숫자가 음식의 개수 N, 두 번째 숫자가 K입니다.
첫 번째 가져가는 음식이 K 번째 음식이며 나머지는 첫 번째 음식으로부터 시계방향으로 가져갑니다.
입력
6 3
남은 음식들의 번호를 배열의 형태로 출력합니다.
출력
[3, 5]
*/
const user_input = prompt('입력해주세요').split(' ');
const n = parseInt(user_input[0], 10);
const k = parseInt(user_input[1], 10);
function sol(n, k) {
let index = 0;
// q에 n만큼의 숫자를 넣어준다.
let q = [];
for(let i = 0; i < n; i++){
q.push(i + 1);
}
while (q.length > 2) {
if (index > q.length-1) {
// 순환하다 index가 q의 길이보다 클 경우에 q.length만큼 빼준다.
// [1,2,3,4,5,6] -> 1다음 4가 빠지고 그 다음은 4+3 = 7(index : 6)이 빠져야 하는데
// index(현재 빠져야 할 index)가 q.length보다 크므로 q.legnth, 즉 4를 빼준다.
// 이걸 마지막 2개가 남을 때까지 반복한다.
index -= q.length;
}
q.splice(index, 1);
index += k;
index -= 1;
}
return q;
}
console.log(sol(n, k));
|
var _typeof2 = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function(obj) {
return typeof obj;
} : function(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports.default = void 0;
var _checkIPhoneX = require("./checkIPhoneX");
function _defineProperty(e, t, o) {
return t in e ? Object.defineProperty(e, t, {
value: o,
enumerable: !0,
configurable: !0,
writable: !0
}) : e[t] = o, e;
}
function _typeof(e) {
return (_typeof = "function" == typeof Symbol && "symbol" == _typeof2(Symbol.iterator) ? function(e) {
return typeof e === "undefined" ? "undefined" : _typeof2(e);
} : function(e) {
return e && "function" == typeof Symbol && e.constructor === Symbol && e !== Symbol.prototype ? "symbol" : typeof e === "undefined" ? "undefined" : _typeof2(e);
})(e);
}
var defaultSafeArea = {
top: !1,
bottom: !1
}, setSafeArea = function setSafeArea(e) {
return "boolean" == typeof e ? Object.assign({}, defaultSafeArea, {
top: e,
bottom: e
}) : null !== e && "object" === _typeof(e) ? Object.assign({}, defaultSafeArea) : "string" == typeof e ? Object.assign({}, defaultSafeArea, _defineProperty({}, e, !0)) : defaultSafeArea;
}, _default = Behavior({
properties: {
safeArea: {
type: [ Boolean, String, Object ],
value: !1
}
},
observers: {
safeArea: function safeArea(e) {
this.setData({
safeAreaConfig: setSafeArea(e)
});
}
},
definitionFilter: function definitionFilter(e) {
var t = ((0, _checkIPhoneX.getSystemInfo)() || {}).statusBarHeight, o = (0, _checkIPhoneX.checkIPhoneX)();
Object.assign(e.data = e.data || {}, {
safeAreaConfig: defaultSafeArea,
statusBarHeight: t,
isIPhoneX: o
});
}
});
exports.default = _default;
|
const chalk = require('chalk');
module.exports = function(){
console.log(chalk.yellow(
`EXERCISE 3:
Write a small function called "lengthAnnouncer" that takes a parameter called "str" and returns the length of the string in the following format:
"<str> has <str length> characters!"
For example:
lengthAnnouncer('Sand') should return 'Sand has 4 characters!'
lengthAnnouncer('Bob') should return 'Bob has 3 characters!'
lengthAnnouncer('dream big') should return 'dream big has 9 characters!'
`
));
process.exit();
};
|
import React, { Component } from "react";
import history from "../../utils/history";
import axios from "axios";
import classnames from "classnames";
import { votingCodeIdInLS } from "../../config";
import isEmpty from "../../utils/isEmpty";
class Landing extends Component {
static propTypes = {};
constructor(props) {
super(props);
this.state = {
code: "",
errors: {},
};
}
handleChange = (e) => {
this.setState({
[e.target.name]: e.target.value.toLowerCase(),
});
};
handleOnKeyDown = (e) => {
if (e.key === "Enter" && !e.shiftKey && !e.ctrlKey) {
e.preventDefault();
try {
this.handleClick(e);
} catch (e) {
console.log(e);
}
}
};
handleClick = async (e) => {
try {
// store voting code to local storage:
localStorage.setItem(votingCodeIdInLS, this.state.code);
// redirect to the specific poll
const { data: poll } = await axios.get(`/api/poll/${this.state.code}/false`);
if (poll.status === "ended") {
this.setState({
errors: {
code: "Deja, balsavimas jau sustabdytas!",
},
});
} else history.push(`/poll/${poll.name}`);
} catch (e) {
console.log(e);
if (e.response.status === 404) {
this.setState({ errors: { code: "Balsavimas nerastas, pasitikrink kodą!" } });
}
}
};
render() {
const { errors } = this.state;
/* THIS IS BUGGY - #TODO #FIXME */
return (
<div className="landing-page d-flex justify-content-center">
<div className="container">
<div className="row ">
<div className="col-12" id="error-col">
{!isEmpty(errors) && errors.code && (
<div className="text-lg text-xpink" style={{ fontSize: "1rem" }}>
<h3>{errors.code}</h3>
</div>
)}
</div>
<div className="col-12 d-flex" id="main-col">
<div className="input-group">
<div className="input-group-prepend">
<span className="input-group-text input" id="input-left">
<i className="fas fa-hashtag fa-lg" />
</span>
</div>
<input
type="text"
name="code"
value={this.state.code}
onChange={this.handleChange}
onKeyDown={this.handleOnKeyDown}
className="form-control form-control-lg input"
id="input-middle"
placeholder="Tavo balsavimo kodas"
autoFocus={
true // })} // "is-invalid": !isEmpty(errors), // className={classnames("form-control form-control-lg input", {
}
/>
<div className="input-group-append">
<button
type="submit"
className="btn btn-xpink input"
id="input-right"
onClick={this.handleClick}
>
<i className="fas fa-arrow-right fa-lg" />
</button>
</div>
</div>
</div>
</div>
</div>
</div>
);
}
}
export default Landing;
|
import React from 'react'
import styles from './Footer.module.css'
export const Footer = ({selectedProducts}) => {
const footerItems = Object.values(selectedProducts)
let finalPrice = 0
function submit(obj) {
let formData = new FormData()
Object.entries(obj).forEach((el) => {
let [id, data] = el
formData.append(`product[${id}]`, data.quantity)
})
fetch('https://datainlife.ru/junior_task/add_basket.php', {
method: 'POST',
body: formData
})
}
return (
<footer>
<div>
<div className={styles.product}>
<div className={styles.name}>Наименование</div>
<div className={styles.quantity}>Количество</div>
<div className={styles.price}>Сумма</div>
</div>
{footerItems.filter((item) => item.quantity > 0).map((item, index) => {
finalPrice += item.totalPrice
return (
<div key={index} className={styles.product}>
<div className={styles.name}>{item.name}</div>
<div className={styles.quantity}>{item.quantity}</div>
<div className={styles.price}>{item.totalPrice}</div>
</div>
)
})}
</div>
<div className={styles.final}>
<div>
<span>Общая стоимость заказа: </span>
<span> {finalPrice}</span>
</div>
<button onClick={() => submit(selectedProducts)}>В корзину</button>
</div>
</footer>
)
}
|
function addGuitar( color, wood, price ) {
if( window.addGuitarListener ) {
element.addGuitarListener( wood, price, false );
} else if( document.attachGuitar ) {
element.attachGuitar( 'on' + wood, price );
} else {
element[ 'on' + wood ] = price;
}
}
|
/*
删除链表中等于给定值 val 的所有节点。
示例:
输入: 1->2->6->3->4->5->6, val = 6
输出: 1->2->3->4->5
来源:力扣(LeetCode)
*/
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @param {number} val
* @return {ListNode}
*/
var removeElements = function(head, val) {
while(head && head.val == val) {
head = head.next;
}
if(!head) {
return null;
}
let res = head;
while(1) {
if(head.next && head.next.val == val) {
if(head.next.next) {
head.next = head.next.next;
}
else {
head.next = null;
}
}
else {
head = head.next;
}
if(!head || !head.next) {
break;
}
}
return res;
};
function ListNode(val) {
this.val = val;
this.next = null;
}
function showNodes(head) {
let res = '';
if(!head) {
return null;
}
while (1) {
res += head.val;
if(!head.next) {
break;
}
res += ' -> ';
head = head.next;
}
return res;
}
let head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(2);
head.next.next.next = new ListNode(1);
// head.next.next.next.next = new ListNode(4)
// head.next.next.next.next.next = new ListNode(5)
// head.next.next.next.next.next.next = new ListNode(6)
const val = 2;
console.log(showNodes(head));
let res = removeElements(head, val);
console.log(showNodes(res));
|
import React, {Component} from "react";
import {NavLink, withRouter} from "react-router-dom";
import exim from "../../../assets/images/exim.svg";
import cancel from "../../../assets/images/cancel.png";
import play from "../../../assets/images/blackPlay.svg";
import greenCall from "../../../assets/images/greenCall.svg";
import vBar from "../../../assets/images/vBar.svg";
import $ from "jquery"
class Navigation extends Component{
state={
mob:false
}
componentDidMount=()=>{
if($(window).width()<=800){
this.setState({
mob:true
})
}
let path=window.location.pathname+"";
if(path.indexOf("courses")!==-1)
this.selectedNav(3);
else if(path.indexOf("pricing")!==-1)
this.selectedNav(2);
else if(path.indexOf("blog")!==-1)
this.selectedNav(4);
else if(path.indexOf("about")!==-1)
this.selectedNav(5);
else
this.selectedNav(1);
this.props.history.listen((location, action) => {
// console.log("on route change");
let path=window.location.pathname+"";
if(path.indexOf("courses")!==-1)
this.selectedNav(3);
else if(path.indexOf("pricing")!==-1)
this.selectedNav(2);
else if(path.indexOf("blog")!==-1)
this.selectedNav(4);
else if(path.indexOf("about")!==-1)
this.selectedNav(5);
else
this.selectedNav(1);
});
}
selectedNav=(nav)=>{
switch (nav) {
case 1:
$(".nav__list_Hr").css("display","none")
$(".nav__list_Hr-1").css("display","block")
$(".nav__list_item").css("color","#ADADAD")
$(".nav__list_item-1").css("color","#0062FF")
break;
case 2:
$(".nav__list_Hr").css("display","none")
$(".nav__list_Hr-2").css("display","block")
$(".nav__list_item").css("color","#ADADAD")
$(".nav__list_item-2").css("color","#0062FF")
break;
case 3:
$(".nav__list_Hr").css("display","none")
$(".nav__list_Hr-3").css("display","block")
$(".nav__list_item").css("color","#ADADAD")
$(".nav__list_item-3").css("color","#0062FF")
break;
case 4:
$(".nav__list_Hr").css("display","none")
$(".nav__list_Hr-4").css("display","block")
$(".nav__list_item").css("color","#ADADAD")
$(".nav__list_item-4").css("color","#0062FF")
break;
case 5:
$(".nav__list_Hr").css("display","none")
$(".nav__list_Hr-5").css("display","block")
$(".nav__list_item").css("color","#ADADAD")
$(".nav__list_item-5").css("color","#0062FF")
break;
default:
$(".nav__list_Hr").css("display","none")
$(".nav__list_Hr-1").css("display","block")
$(".nav__list_item").css("color","#ADADAD")
$(".nav__list_item-1").css("color","#0062FF")
}
}
mobNavHndler=()=>{
$(".nav__mob_wrapper").css({"opacity":"0","visibility":"hidden"});
$(".nav__mob_wrapper2").css({"animation":"none","opacity":"0","visibility":"hidden"});
$(".nav__mob_wrapper3").css({"animation":"none","opacity":"0","visibility":"hidden"})
}
menuHandler=()=>{
$(".nav__mob_wrapper2").css({"animation":"wrapper2 1.5s linear","opacity":"1","visibility":"visible"});
setTimeout(()=>{
$(".nav__mob_wrapper").css({"opacity":"1","visibility":"visible"});
$(".nav__mob_wrapper3").css({"animation":"wrapper3 10s linear infinite","opacity":"1","visibility":"visible"})
},800)
setTimeout(()=>{
$(".nav__mob_wrapper2").css({"animation":"wrapper2 3s linear","opacity":"0","visibility":"hidden"});
},1400)
}
render(){
;
return (
<div className="nav">
<NavLink to ="/"><img className="nav__compName" src={exim} alt="EXIM"/></NavLink>
{this.state.mob?
<div className="nav__mob">
<div onClick={this.menuHandler} className="nav__mob_text">Menu <span>.</span></div>
<div className="nav__mob_wrapper">
<img className="nav__mob_wrapper-cancel" onClick={this.mobNavHndler} src={cancel} alt=""/>
<NavLink exact activeStyle={{color:"#0062FF",fontWeight:"bold"}} onClick={()=>this.mobNavHndler()} className="nav__mob_wrapper-link" to="/"><div className="nav__list_item nav__list_item-1">Home</div></NavLink>
<NavLink exact activeStyle={{color:"#0062FF",fontWeight:"bold"}} onClick={()=>this.mobNavHndler()} className="nav__mob_wrapper-link" to="/courses"><div className="nav__list_item nav__list_item-3">Courses</div></NavLink>
<NavLink exact activeStyle={{color:"#0062FF",fontWeight:"bold"}} onClick={()=>this.mobNavHndler()} className="nav__mob_wrapper-link" to="/pricing"><div className="nav__list_item nav__list_item-2">Pricing</div></NavLink>
<NavLink activeStyle={{color:"#0062FF",fontWeight:"bold"}} onClick={()=>this.mobNavHndler()} className="nav__mob_wrapper-link" to="/blogs/main"><div className="nav__list_item nav__list_item-4">Blogs</div></NavLink>
<NavLink exact activeStyle={{color:"#0062FF",fontWeight:"bold"}} onClick={()=>this.mobNavHndler()} className="nav__mob_wrapper-link" to="/about"><div className="nav__list_item nav__list_item-5">About Us</div></NavLink>
<a className="nav__mob_wrapper-play" href="https://play.google.com/store/apps/details?id=co.kevin.pbhaa"><img src={play} alt=""/></a>
</div>
<div className="nav__mob_wrapper2">
</div>
<div className="nav__mob_wrapper3">
</div>
</div>
:<ul className="nav__list">
<NavLink onClick={()=>this.selectedNav(1)} className="nav__link" to="/"><li className="nav__list_item nav__list_item-1">Home</li><hr className="nav__list_Hr nav__list_Hr-1"/></NavLink>
<NavLink onClick={()=>this.selectedNav(3)} className="nav__link" to="/courses"><li className="nav__list_item nav__list_item-3">Courses</li><hr className="nav__list_Hr nav__list_Hr-3"/></NavLink>
<NavLink onClick={()=>this.selectedNav(2)} className="nav__link" to="/pricing"><li className="nav__list_item nav__list_item-2">Pricing</li><hr className="nav__list_Hr nav__list_Hr-2"/></NavLink>
<NavLink onClick={()=>this.selectedNav(4)} className="nav__link" to="/blogs/main"><li className="nav__list_item nav__list_item-4">Blogs</li><hr className="nav__list_Hr nav__list_Hr-4"/></NavLink>
<NavLink onClick={()=>this.selectedNav(5)} className="nav__link" to="/about"><li className="nav__list_item nav__list_item-5">About Us</li><hr className="nav__list_Hr nav__list_Hr-5"/></NavLink>
<a href="tel://+918517885555" className="about__1_text-call nav__list_a" id="nav__list_a"><img className="about__1_text-call--img1" src={greenCall} alt=""/> +91 8517885555</a>
</ul>}
</div>
)
}
}
export default withRouter(Navigation);
|
import React from 'react'
export default class Header extends React.Component{
render(){
return(
<div className="header d-flex">
<h3>
<a href="#/">
StarDB
</a>
</h3>
<ul className="d-flex nav-list">
<li>
<a href="#/people">People</a>
</li>
<li>
<a href="#/planets">Planets</a>
</li>
<li>
<a href="#/starships">Starships</a>
</li>
</ul>
</div>
)
}
}
|
const AWS = require('aws-sdk');
const dynamodb = new AWS.DynamoDB();
const TABLE_NAME = process.env.CIRCUIT_BREAKER_TABLE_NAME
const axios = require('axios')
let responseStatus = 'SUCCESS'
let responseData
exports.handler = (event, context) => {
console.log("REQUEST RECEIVED:\n" + JSON.stringify(event));
dynamodb.putItem({
"TableName": TABLE_NAME,
"Item" : {
"id": {
"S": event.ResourceProperties.DefaultFunction
},
"state": {
"S": "CLOSED"
},
"fallback": {
"S": event.ResourceProperties.FallbackFunction
},
"successThreshold": {
"N": event.ResourceProperties.SuccessThreshold
},
"failureThreshold": {
"N": event.ResourceProperties.FailureThreshold
},
"successCount": {
"N": 0
},
"failureCount": {
"N": 0
},
"timeout": {
"N": event.ResourceProperties.CircuitBreakerTimeout
},
"nextAttempt": {
"S": new Date(Date.now()).toISOString()
}
}
}, function(err, data) {
if (err) {
responseStatus = "FAILED"
responseData = {
message: "Error while inserting circuit breaker"
}
console.log('Error while inserting circuit breaker: ', err)
sendResponse(event, context, responseStatus, responseData)
}
else {
responseData = {
message: "Circuit breaker inserted with success!"
}
sendResponse(event, context, responseStatus, responseData)
}
});
};
function sendResponse(event, context, responseStatus, responseData){
const responseBody = {
"Status": responseStatus,
"Reason": `See the details in CloudWatch Log Stream`,
"PhysicalResourceId": "FillCircuitBreakerFunction",
"StackId": event.StackId,
"RequestId": event.RequestId,
"LogicalResourceId": event.LogicalResourceId,
"NoEcho": false,
"Data": responseData || {}
}
axios.put(event.ResponseURL, responseBody).then(data => {
return "Circuit breaker inserted with success!"
})
.catch(err =>{
return err
})
}
|
import Head from "next/head";
import styles from "../styles/Home.module.css";
import { MyEditor } from "../components/Editor";
import { NoSsr } from "../components/NoSsr";
export default function Home() {
return (
<div className={styles.container}>
<Head>
<title>Create Next App</title>
<meta name="description" content="Generated by create next app" />
<link rel="icon" href="/favicon.ico" />
<meta charSet="utf-8" />
</Head>
<main className={styles.main}>
<h1>Hello</h1>
<div style={{ height: 450, width: 450, border: "1px solid black" }}>
<NoSsr>
<MyEditor />
</NoSsr>
</div>
</main>
</div>
);
}
|
angular
.module('homer')
.factory('MyAccountService', function($q) {
var data = {
personalData: {
username: 'consumer1',
email: 'consumer1@mailinator.com'
},
paymentSettings: {
method: 'CREDIT_CARD',
cardDetails: {
brand: 'Visa',
ending: '2345'
}
},
program: {
name: 'Top Box Evanston',
pickupLocation: {
name: 'Walker Elementary',
city: 'Evanston',
state: 'IL',
streetOne: '3601 Church St',
zip: '60203',
latitude: 42.0464424,
longitude: -87.7188606
}
}
};
return {
load: function() {
return $q(function(resolve) {
resolve({data: data});
});
},
save: function(newData) {
return $q(function(resolve) {
_.assign(data, newData);
resolve({data: {success: true}});
})
}
}
})
.filter('paymentMethod', function() {
return function(val) {
return _.startCase(val);
}
})
.factory('StripeService', function() {
var stripe = Stripe("pk_test_mqOdMBx5L08kX8Lz3es9uk1T");
return {
createCard: function(elem) {
var elements = stripe.elements();
var card = elements.create('card');
card.mount(elem);
return card;
},
createToken: function(card) {
return stripe.createToken(card);
}
}
})
.directive('stripeCreditCard', function() {
return {
restrict: 'A',
require: 'ngModel',
template: '<div class="stripe-container"></div>',
link: function(scope, element, attrs, ctrl) {
scope.$stripeCard.ngModel = ctrl;
},
controllerAs: '$stripeCard',
controller: function($scope, $element, $attrs, StripeService, $parse) {
var card = StripeService.createCard($element.find('.stripe-container')[0]);
var vm = this;
var onSuccessFn = $parse($attrs.onSuccess);
card.addEventListener('change', function(ev) {
function setValidity(error) {
var errorKeys = ['invalid_number', 'invalid_expiry_month', 'invalid_expiry_year', 'invalid_expiry_year_past',
'invalid_cvc', 'invalid_swipe_data', 'incorrect_number', 'expired_card', 'incorrect_cvc', 'incorrect_zip',
'card_declined', 'missing', 'processing_error'];
_.each(errorKeys, function(errKey) {
var ngErrorKey = _.kebabCase('card_' + errKey);
var receivedError = _.get(error, 'code');
vm.ngModel.$setValidity(ngErrorKey, !_.isEqual(receivedError, errKey));
});
}
if(ev.error) {
$scope.$apply(function() {
vm.ngModel.$setViewValue(null);
setValidity(ev.error);
});
} else if(ev.complete) {
StripeService.createToken(card).then(function(result) {
$scope.$apply(function() {
vm.ngModel.$setViewValue(result.token.id);
setValidity(null);
onSuccessFn($scope, {$scope: $scope, $data: result});
})
});
}
});
}
}
})
.controller('csMyAccount', function($scope, MyAccountService) {
$scope.data = {};
$scope.ctx = {
paymentMethods: ['CREDIT_CARD', 'ON_PICKUP']
};
MyAccountService.load().then(function(resp) {
$scope.data = resp.data;
});
$scope.savePersonalInformation = function(data, successCallback, errorCallback) {
MyAccountService.save({personalData: data}).then(successCallback, errorCallback);
};
$scope.savePaymentSettings = function(data, successCallback, errorCallback) {
MyAccountService.save({paymentSettings: data}).then(
function() {
successCallback();
$scope.creditCardInputVisible = false;
},
errorCallback);
};
$scope.cancelPaymentSettingsEdition = function() {
$scope.creditCardInputVisible = false
};
$scope.setCardDetails = function(scope, data) {
_.assign(_.get(scope.data, 'cardDetails'), {
brand: _.get(data, 'token.card.brand'),
ending: _.get(data, 'token.card.last4')
});
};
});
|
/**
* Created by janeluck on 8/14/16.
*/
function fib(max) {
var n = 0, a = 0, b = 1;
while (n < max) {
console.log(b);
a = b;
b = a + b;
n++
}
}
|
'use strict';
app.factory('weatherService', function($http, $httpParamSerializerJQLike){
return {
post: function(lng, lat) {
return $http({
method: 'POST',
url: '/weather',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $httpParamSerializerJQLike({
"lng": lng,
"lat": lat
})
});
}
}
});
|
import React, { useState} from "react";
import { useDispatch } from "react-redux";
import { addTask } from "../redux/Actions/tasks";
import { Button, Container,Row,Col } from "react-bootstrap";
const AddTask = () => {
const [task, setTask] = useState({name:"",description:""});
const dispatch = useDispatch();
const handleChange = (e) => {
if (task.name) {
dispatch(addTask({ id: Math.random(), ...task, isDone: false }));
setTask({name:"",description:""});
} else {
alert("Le champs nom est vide !!!");
}
};
return (
<form onSubmit={handleChange} >
<Container>
<Row>
<Col sm={4}>
<p>Nom de la Tache</p>
<input
type="text"
name="name"
onChange={(e) => setTask({...task,name:e.target.value})}
value={task.name}
/>
</Col>
<Col sm={4}>
<p>Description de la tache en une ligne</p>
<input
type="text"
name="description"
onChange={(e) => setTask({...task,description:e.target.value})}
value={task.description}
/>
</Col>
<Col sm={4}>
<br/>
<Button variant="primary" onClick={handleChange}>
Ajouter la Tâche
</Button>
</Col>
</Row>
</Container>
</form>
);
};
export default AddTask;
|
/**
* HomeScreen
* @flow
*/
import React, {Component} from "react";
import {StyleSheet, Text, View, ScrollView, Dimensions} from "react-native";
const styles = StyleSheet.create({
container: {
flex: 1
},
column : {
marginTop : 70,
borderColor : 'red',
borderWidth : 1,
backgroundColor: '#D3D3D3',
width : Dimensions.get("window").width
}
});
export default class HomeScreen extends Component {
_renderScrollViewContent() {
const data = Array.from({length: 40});
return (
<ScrollView
style={styles.container}
horizontal
>
{data.map((_, i) =>
<View key={i} style={styles.column}>
<Text>{i + 1}</Text>
</View>
)}
</ScrollView>
);
}
render() {
return (
<View style={styles.container}>
{this._renderScrollViewContent()}
</View>
);
}
}
|
// Informational responses (100–199),
// Successful responses (200–299),
// Redirects (300–399),
// Client errors (400–499),
// and Server errors (500–599).
import {select} from 'redux-saga/effects';
export default function* (url, params, timeout = 8000) {
const headers = {
'Content-Type': 'application/json',
};
// const user = yield select(state => state.auth.userData);
if (false) {
let {token} = user;
headers.Authorization = 'Bearer ' + token;
}
// Merge headers from params if exist
if (!!params?.headers) {
params.headers = {
...params.headers,
...headers,
};
} else {
params = {...params, headers};
}
// Stringify request body
if (!!params?.body) {
params.body = JSON.stringify(params.body);
}
const controller = new AbortController();
const {signal} = controller;
params.signal = signal;
const _timeout = setTimeout(() => controller.abort(), timeout);
const response = yield fetch(url, params);
clearTimeout(_timeout);
const {status} = response;
const result = yield response.json();
if (status >= 200 && status < 300) {
return result;
} else {
__DEV__ && console.log({url, params, error: result});
throw result;
}
}
|
var qReqs = 0;
var reqsPage, modelsPage, catsPage, docsPage;
var activePage = null;
var activeId = 0;
var builtIds = [false, false, false, false];
var fullData = JSON.parse(fullInfo);
var docsDict = JSON.parse(docsInfo);
var reqs = {};
var pages = ["#pageRequests", "#pageModels", "#pageCategories", "#pageDocuments"];
function buildPages() {
let main = document.querySelector('#mainPage');
reqsPage = document.createElement('div');
reqsPage.id = 'reqsPage';
reqsPage.className = 'tabbed';
main.appendChild(reqsPage);
modelsPage = document.createElement('div');
modelsPage.id = 'modelsPage';
modelsPage.className = 'tabbed';
main.appendChild(modelsPage);
catsPage = document.createElement('div');
catsPage.id = 'catsPage';
catsPage.className = 'tabbed';
main.appendChild(catsPage);
docsPage = document.createElement('div');
docsPage.id = 'docsPage';
docsPage.className = 'tabbed';
main.appendChild(docsPage);
}
function addRequest(node, id) {
if (node.checked) {
qReqs++;
reqs[id] = true
}
else if(qReqs) {
qReqs--;
delete reqs[id]
}
else {
return;
}
if (!qReqs) {
buildActivePage();
//activePage = null;
return;
}
if (!activePage) {
buildPages();
activePage = reqsPage;
activeId = 1;
document.querySelector(pages[activeId-1]).classList.add("active");
}
for (i=0; i<builtIds.length; i++)
builtIds[i] = false;
buildActivePage();
}
function addAllRequests(node) {
let chks = document.querySelectorAll(".chk");
let needSelect = node.innerHTML == "Select All";
chks.forEach(function(chk) {
if (needSelect && !chk.checked || !needSelect && chk.checked)
chk.click();
});
if (node.innerHTML == "Select All")
node.innerHTML = "Unselect All";
else
node.innerHTML = "Select All";
}
function buildActivePage() {
switch (activeId) {
case 1:
buildReqsPage();
break;
case 2:
buildModelsPage();
break;
case 3:
buildCatsPage();
break;
case 4:
buildDocsPage()
default:
break;
}
builtIds[activeId-1] = true;
activePage.classList.add("vis");
}
function changePage(pageId) {
if (!qReqs) {
return;
}
activePage.classList.remove('vis');
document.querySelector(pages[activeId-1]).classList.remove("active");
if (pageId == "Requests") {
activePage = reqsPage;
activeId = 1;
}
else if(pageId == "Models") {
activePage = modelsPage;
activeId = 2;
}
else if(pageId == "Categories") {
activePage = catsPage;
activeId = 3;
}
else {
activePage = docsPage;
activeId = 4;
}
document.querySelector(pages[activeId-1]).classList.add("active");
if (!builtIds[activeId-1])
buildActivePage(reqs)
activePage.classList.add("vis");
}
function buildReqsPage() {
while(reqsPage.firstChild) {
reqsPage.removeChild(reqsPage.firstChild);
}
if (!qReqs)
return;
let tabCols = Object.keys(reqs).length;
let table = document.createElement("table");
table.className = "commontable";
reqsPage.appendChild(table);
let trh = document.createElement("tr");
table.appendChild(trh);
let ch = document.createElement("th");
ch.innerHTML = "Info";
ch.className = "features";
trh.appendChild(ch);
let keys = Object.keys(reqs);
for (key in reqs) {
ch = document.createElement("th");
trh.appendChild(ch);
let title = document.createTextNode("Request " + key);
ch.appendChild(title);
}
let tr = document.createElement("tr");
table.appendChild(tr);
ch = document.createElement("td");
ch.className = "bold";
ch.innerHTML = "Data Set";
tr.appendChild(ch);
for (key in reqs) {
ch = document.createElement("td");
ch.innerHTML = fullData[key]["datasetPath"];
tr.appendChild(ch);
}
tr = document.createElement("tr");
table.appendChild(tr);
ch = document.createElement("td");
ch.className = "bold";
ch.innerHTML = "Sources";
tr.appendChild(ch);
for (key in reqs) {
ch = document.createElement("td");
ch.innerHTML = fullData[key].sourcesPath;
tr.appendChild(ch);
}
tr = document.createElement("tr");
table.appendChild(tr);
ch = document.createElement("td");
ch.innerHTML = "Preprocess";
ch.className = "expanded bold"
ch.colspan = keys.length + 1;
tr.appendChild(ch);
tr = document.createElement("tr");
table.appendChild(tr);
ch = document.createElement("td");
ch.innerHTML = "Preprocess";
ch.className = "expandedcont bold";
tr.appendChild(ch);
for (key in reqs) {
ch = document.createElement("td");
ch.innerHTML = fullData[key]["preprocess"]["actualtoks"];
tr.appendChild(ch);
}
tr = document.createElement("tr");
table.appendChild(tr);
ch = document.createElement("td");
ch.innerHTML = "Normalization";
ch.className = "expandedcont bold";
tr.appendChild(ch);
for (key in reqs) {
ch = document.createElement("td");
ch.innerHTML = fullData[key]["preprocess"]["normalization"];
tr.appendChild(ch);
}
tr = document.createElement("tr");
table.appendChild(tr);
ch = document.createElement("td");
ch.innerHTML = "Exclude stop words";
ch.className = "expandedcont bold";
tr.appendChild(ch);
for (key in reqs) {
ch = document.createElement("td");
ch.innerHTML = fullData[key]["preprocess"]["stopwords"];
tr.appendChild(ch);
}
tr = document.createElement("tr");
table.appendChild(tr);
ch = document.createElement("td");
ch.innerHTML = "Excluded POS";
ch.className = "expandedcont bold";
tr.appendChild(ch);
for (key in reqs) {
ch = document.createElement("td");
ch.innerHTML = fullData[key]["preprocess"]["expos"] || "none";
tr.appendChild(ch);
}
tr = document.createElement("tr");
table.appendChild(tr);
ch = document.createElement("td");
ch.innerHTML = "Excluded words";
ch.className = "expandedcont bold";
tr.appendChild(ch);
for (key in reqs) {
ch = document.createElement("td");
ch.innerHTML = fullData[key]["preprocess"]["extrawords"] || "none";
tr.appendChild(ch);
}
tr = document.createElement("tr");
table.appendChild(tr);
ch = document.createElement("td");
ch.innerHTML = "Categories";
ch.className = "expanded bold"
ch.colspan = keys.length + 1;
tr.appendChild(ch);
tr = document.createElement("tr");
table.appendChild(tr);
ch = document.createElement("td");
ch.innerHTML = "At all";
ch.className = "expandedcont bold";
tr.appendChild(ch);
for (key in reqs) {
ch = document.createElement("td");
ch.innerHTML = fullData[key]["categories"].length;
tr.appendChild(ch);
}
tr = document.createElement("tr");
table.appendChild(tr);
ch = document.createElement("td");
ch.innerHTML = "Excluded categories";
ch.className = "expandedcont bold";
tr.appendChild(ch);
for (key in reqs) {
ch = document.createElement("td");
ch.innerHTML = fullData[key]["preprocess"]["excat"] || "none";
tr.appendChild(ch);
}
tr = document.createElement("tr");
table.appendChild(tr);
ch = document.createElement("td");
ch.innerHTML = "Documents";
ch.className = "expanded bold";
ch.colspan = keys.length + 1;
tr.appendChild(ch);
tr = document.createElement("tr");
table.appendChild(tr);
ch = document.createElement("td");
ch.innerHTML = "At all";
ch.className = "expandedcont bold";
tr.appendChild(ch);
for (key in reqs) {
ch = document.createElement("td");
ch.innerHTML = Object.keys(fullData[key]["docs"]).length;
tr.appendChild(ch);
}
tr = document.createElement("tr");
table.appendChild(tr);
ch = document.createElement("td");
ch.innerHTML = "Labels";
ch.className = "expandedcont bold";
tr.appendChild(ch);
for (key in reqs) {
ch = document.createElement("td");
let labs = 0;
for (doc in fullData[key]["docs"]) {
labs += fullData[key]["docs"][doc]["actual"].split(",").length;
}
ch.innerHTML = "" + labs;
tr.appendChild(ch);
}
tr = document.createElement("tr");
table.appendChild(tr);
ch = document.createElement("td");
ch.innerHTML = "Models (F1-Measure)";
ch.className = "expanded bold"
ch.colspan = keys.length + 1;
tr.appendChild(ch);
let qModels = 0;
for (key in reqs) {
if (Object.keys(fullData[key]["models"]).length > qModels)
qModels = Object.keys(fullData[key]["models"]).length;
}
let f1 = 0;
for (i=0; i<qModels; i++) {
tr = document.createElement("tr");
ch = document.createElement("td");
tr.append(ch);
table.appendChild(tr);
for (key in reqs) {
ch = document.createElement("td");
models = Object.keys(fullData[key]["models"]);
if (i < models.length) {
if (fullData[key]["models"][models[i]]["all"]["f1"] > f1) {
let elf1 = document.querySelectorAll("span.f1");
elf1.forEach(function(sp) {
sp.classList.remove("f1");
});
f1 = fullData[key]["models"][models[i]]["all"]["f1"];
}
let spanclass = "";
if (fullData[key]["models"][models[i]]["all"]["f1"] == f1)
spanclass = "f1";
ch.innerHTML = "<span class='" + spanclass + "'>" + models[i].toUpperCase() + " (" +
(fullData[key]["models"][models[i]]["all"]["f1"] *100).toFixed(2) + "%)</span>";
}
else
ch.innerHTML = "";
tr.appendChild(ch);
}
}
}
function buildModelsPage() {
while(modelsPage.firstChild) {
modelsPage.removeChild(modelsPage.firstChild);
}
if (!qReqs)
return;
let tabCols = Object.keys(reqs).length;
let table = document.createElement("table");
table.className = "commontable";
modelsPage.appendChild(table);
let trh = document.createElement("tr");
table.appendChild(trh);
let ch = document.createElement("th");
ch.innerHTML = "Info";
ch.className = "features";
trh.appendChild(ch);
let keys = Object.keys(reqs);
for (key in reqs) {
for (model in fullData[key]["models"]) {
ch = document.createElement("th");
trh.appendChild(ch);
let title = document.createElement("div");
title.innerHTML = "Request " + key;
ch.appendChild(title);
title = document.createElement("div");
title.innerHTML = "Model: " + model.toUpperCase()
ch.appendChild(title);
}
}
tr = document.createElement("tr");
table.appendChild(tr);
ch = document.createElement("td");
ch.innerHTML = "Documents";
ch.className = "expanded bold";
ch.colspan = keys.length + 1;
tr.appendChild(ch);
for (i=0; i<7; i++) {
addModelsPageRaw(table, i);
}
tr = document.createElement("tr");
table.appendChild(tr);
ch = document.createElement("td");
ch.innerHTML = "Labels";
ch.className = "expanded bold";
ch.colspan = keys.length + 1;
tr.appendChild(ch);
for (i=7; i<12; i++) {
addModelsPageRaw(table, i);
}
tr = document.createElement("tr");
table.appendChild(tr);
ch = document.createElement("td");
ch.innerHTML = "Metrics";
ch.className = "expanded bold";
ch.colspan = keys.length + 1;
tr.appendChild(ch);
for (i=12; i<25; i++) {
addModelsPageRaw(table, i);
}
tr = document.createElement("tr");
table.appendChild(tr);
ch = document.createElement("td");
ch.innerHTML = "Categories (by F1 in descending order)";
ch.className = "expanded bold";
ch.colspan = keys.length + 1;
tr.append(ch);
let cAr = createCatsArrays();
let rows = 0;
for (key in cAr) {
if (cAr[key].length > rows)
rows = cAr[key].length;
}
addModelsPageCatsRows(table, rows, cAr);
}
function addModelsPageRaw(table, ind) {
let fullNames = ["Documents at all", "Exactly classified", "Classified completely, but with errors",
"Partially classified", "Classified partially with errors", "Classified falsely", "Not classified",
"Actual labels", "Pedicted at all", "Predicted correctly", "Predicted falsely", "Not predicted",
"Exact Match Ratio", "Accuracy", "Precision", "Recall", "F1-Measure", "Hamming Loss",
"Macro-Averaged Precision", "Macro-Averaged Recall", "Macro-Averaged F1-Measure",
"Micro-Averaged Precision", "Micro-Averaged Recall", "Micro-Averaged F1-Measure", "Rank threshold"];
let shortNames= ["d_docs", "dd_ex", "dd_cf", "dd_p", "dd_pf", "dd_f", "dd_n",
"d_actual", "d_predicted", "d_correctly", "d_falsely", "d_notPredicted",
"emr", "accuracy", "precision", "recall", "f1", "hl", "macroPrecision",
"macroRecall", "macroF1", "microPrecision", "microRecall", "microF1", "rank"];
let tr = document.createElement("tr");
table.appendChild(tr);
let ch = document.createElement("td");
ch.innerHTML = fullNames[ind];
ch.className = "expandedcont bold";
tr.appendChild(ch);
for (key in reqs) {
for (model in fullData[key]["models"]) {
ch = document.createElement("td");
ch.className = "digs";
tr.appendChild(ch);
if (shortNames[i] == "rank") {
let rank = 0.5
if (fullData[key].hasOwnProperty("ranks"))
rank = fullData[key]["ranks"][model];
if (!rank) {
console.log("Rank is " + rank + " for model " + model);
rank = 0.5
}
ch.innerHTML = (rank * 100).toFixed(2) + "%";
}
else if (shortNames[i].startsWith("d"))
ch.innerHTML = fullData[key]["models"][model]["all"][shortNames[i]];
else if(shortNames[i].startsWith("hl"))
ch.innerHTML = fullData[key]["models"][model]["all"][shortNames[i]].toFixed(4);
else
ch.innerHTML = (fullData[key]["models"][model]["all"][shortNames[i]] * 100).toFixed(2) + "%";
}
}
}
function addModelsPageCatsRows(table, rows, arr) {
//console.log("Rows: " + rows + ", keys: " + Object.keys(arr).length);
for (let i=0; i<rows; i++) {
let tr = document.createElement("tr");
table.appendChild(tr);
tr.appendChild(document.createElement("td"));
for (key in reqs) {
for (model in fullData[key]["models"]) {
let keyArr = key + " | " + model;
//console.log("Key: " + keyArr + ", cats: " + arr[keyArr].length);
let td = document.createElement("td");
if (arr[keyArr].length - 1 >= i) {
let cat = arr[keyArr][i];
//console.dir(cat);
td.innerHTML = "<div><table class='catstab'><tr>" +
"<td class='txt' style='overflow: hidden; white-space: nowrap; text-overflow: ellipsis;'>" +
cat["name"] + "</td>" +
"<td class='digs'>" + (cat.f1 * 100).toFixed(2) + "%</td></tr></table></div>"
}
tr.appendChild(td);
}
}
}
}
function createCatsArrays() {
let catsArrays = {}
for (key in reqs) {
for (model in fullData[key]["models"]) {
let arKey = key + " | " + model;
catsArrays[arKey] = []
for (category in fullData[key]["models"][model]) {
if (category != "all") {
let catObj = fullData[key]["models"][model][category];
catObj["name"] = category;
catsArrays[arKey].push(catObj);
}
}
catsArrays[arKey].sort(function(a, b) {
return b.f1 - a.f1;
});
}
}
return catsArrays;
}
function buildCatsPage() {
while(catsPage.firstChild) {
catsPage.removeChild(catsPage.firstChild);
}
if (!qReqs)
return;
let tabCols = Object.keys(reqs).length;
let table = document.createElement("table");
table.className = "commontable";
catsPage.appendChild(table);
let trh = document.createElement("tr");
table.appendChild(trh);
let ch = document.createElement("th");
ch.innerHTML = "Info";
ch.className = "features";
trh.appendChild(ch);
let keys = Object.keys(reqs);
for (key in reqs) {
for (model in fullData[key]["models"]) {
ch = document.createElement("th");
trh.appendChild(ch);
let title = document.createElement("div");
title.innerHTML = "Request " + key;
ch.appendChild(title);
title = document.createElement("div");
title.innerHTML = "Model: " + model.toUpperCase()
ch.appendChild(title);
}
}
catsObj = {};
for (key in reqs) {
let cats = fullData[key]["categories"];
for (i=0; i<cats.length; i++) {
if (!catsObj.hasOwnProperty(cats[i]))
catsObj[cats[i]] = true;
}
}
for (cat in catsObj) {
addCatsPageRaws(table, cat);
}
}
function addCatsPageRaws(table, category) {
let fullNames = ["Labels", "Predicted labels at all", "Correctly predicted labels",
"Falsely predicted labels", "Not predicted labels", "Precision", "Recall", "F1-Measure"];
let shortNames= ["d_actual", "d_predicted", "d_correctly", "d_falsely", "d_notPredicted",
"precision", "recall", "f1"];
let tr = document.createElement("tr");
table.appendChild(tr);
let td = document.createElement("td");
td.className = "expanded bold";
td.innerHTML = category;
tr.appendChild(td);
for (i=0; i<fullNames.length; i++) {
tr = document.createElement("tr");
table.appendChild(tr);
td = document.createElement("td");
td.className = "expandedcont bold";
td.innerHTML = fullNames[i];
tr.appendChild(td);
for (key in reqs) {
for (model in fullData[key]["models"]) {
td = document.createElement("td");
td.className = "digs";
tr.appendChild(td);
if (fullData[key]["models"][model].hasOwnProperty(category)) {
if (shortNames[i].startsWith("d"))
td.innerHTML = fullData[key]["models"][model][category][shortNames[i]];
else
td.innerHTML = (fullData[key]["models"][model][category][shortNames[i]]* 100).toFixed(2) + "%";
}
else
td.innerHTML = "N/A";
}
}
}
}
function buildDocsPage() {
while(docsPage.firstChild) {
docsPage.removeChild(docsPage.firstChild);
}
if (!qReqs)
return;
let tabCols = Object.keys(reqs).length;
let table = document.createElement("table");
table.className = "docstable";
docsPage.appendChild(table);
let trh = document.createElement("tr");
table.appendChild(trh);
let ch = document.createElement("th");
ch.innerHTML = "Info";
ch.className = "features";
trh.appendChild(ch);
let keys = Object.keys(reqs);
for (key in reqs) {
for (model in fullData[key]["models"]) {
ch = document.createElement("th");
trh.appendChild(ch);
let title = document.createElement("div");
title.innerHTML = key;
ch.appendChild(title);
title = document.createElement("div");
title.innerHTML = model.toUpperCase()
ch.appendChild(title);
}
}
for (doc in docsDict) {
let tr = document.createElement("tr");
table.appendChild(tr);
let td = document.createElement("td");
td.innerHTML = doc;
td.title = docsDict[doc];
td.className = "docname";
tr.appendChild(td);
let tdClass = "";
for (key in reqs) {
for (model in fullData[key]["models"]) {
td = document.createElement("td");
tr.append(td);
if (!fullData[key]["docs"].hasOwnProperty(doc)) {
td.innerHTML = "N/A";
tdClass = "";
}
else {
let fullList = fullData[key]["docs"][doc][model].split(" | ");
let predList = fullList[0];
let remList = "";
if (fullList.length > 1)
remList = fullList[1];
td.title = "Document: " + doc + "\n" +
"Tagged by: " + fullData[key]["docs"][doc]["actual"] + "\n" +
//"Predicted: " + fullData[key]["docs"][doc][model];
"Predicted: " + predList;
if (remList != "") {
td.title += "\n=== Other: ===";
let rems = remList.split(",");
let j = 0;
for (let i=0; i<rems.length; i++) {
if (rems[i] !== "") {
j++;
if (j%3 == 1)
td.title += "\n";
td.title += rems[i];
if (i < rems.length - 1)
td.title += ",";
}
}
}
let acts = fullData[key]["docs"][doc]["actual"].split(",");
//let preds = fullData[key]["docs"][doc][model].split(",");
let preds = predList.split(",");
let lenPreds = preds.length == 1 && preds[0] == ""? 0 : preds.length;
let found = 0;
for (let i = 0; i<acts.length; i++) {
//if (fullData[key]["docs"][doc][model].indexOf(acts[i]) >=0 )
if (predList.indexOf(acts[i]) >=0 )
found++;
}
if (found == acts.length) {
if (found == lenPreds)
tdClass = "exact";
else
tdClass = "comp";
}
else if(found > 0) {
if (found == lenPreds)
tdClass = "part";
else
tdClass = "partnerr";
}
else if(lenPreds > 0)
tdClass = "fals";
else
tdClass = "notpred";
}
td.className = tdClass;
}
}
}
}
|
import { getUserContext } from "../api/endpoints";
export var userContext = {};
export const initUserContext = () => {
if (!userContext.id) {
return getUserContext().then(res => {
const { data } = res;
if (data.id) {
gtag("set", {
user: data.id
});
}
userContext = res.data;
});
}
};
export const resetUserContext = () => {
userContext = {};
return initUserContext();
};
export const isUserLoggedIn = () => {
return userContext.id && !userContext.temp;
};
|
let container = document.getElementsByClassName('colorLevel')[0];
let settings ={
"width":130,
"height":130,
"background":"#BBBBBB",
"boundary":true,
"boundaryColor":"#000000",
"min":0,
"max":1000
}
var slider = new Clap(container, "demo", settings);
|
const Markup = require('telegraf/markup')
const flat = (arr) => arr.reduce((acc, val) => acc.concat(val), [])
module.exports = class {
constructor(opts) {
this.options = Object.assign({
duplicates: false,
inline: false,
inlineSeparator: ':',
newline: false
}, opts)
this.buttons = []
this.buttons[0] = []
this.line = 0
}
new() {
this.buttons = []
this.buttons[0] = []
this.line = 0
return this
}
add(...buts) {
if (Array.isArray(buts[0])) {
buts = buts[0]
}
for (let but of buts) {
if ((!this.exist(but) && but) || this.options.duplicates) {
if (this.options.inline) {
const butt = but.split(this.options.inlineSeparator)
this.buttons[this.line].push(Markup.callbackButton(butt[0], butt[1] || butt[0]))
} else {
this.buttons[this.line].push(but)
}
}
if (this.options.newline) {
this.next()
}
}
this.fix()
this.next()
return this
}
next() {
this.line++
this.buttons[this.line] = []
}
exist(but) {
for (let i in this.buttons) {
if (this.buttons[i].includes(but)) {
return true
}
}
return false
}
remove(but) {
for (let i in this.buttons) {
if (this.buttons[i].includes(but)) {
this.buttons[i].splice(this.buttons[i].indexOf(but), 1)
}
}
this.fix()
return this
}
fix() {
for (let i in this.buttons) {
if (!this.buttons[i].length) {
this.buttons.splice(i, 1)
this.line--
}
}
}
rename(but, newbut) {
for (let i in this.buttons) {
if (this.buttons[i].includes(but)) {
this.buttons[i][this.buttons[i].indexOf(but)] = newbut
}
}
return this
}
empty() {
return !this.buttons.length ? true : false
}
draw(group = false) {
const buttons = group ? flat(this.buttons) : this.buttons
if (this.options.inline) {
return Markup.inlineKeyboard(buttons, group || {}).extra({parse_mode: 'HTML'})
} else {
return Markup.keyboard(buttons, group || {}).resize().extra()
}
}
clear() {
return Markup.removeKeyboard().extra()
}
}
|
import React from 'react';
import {Font} from 'expo';
import { StyleSheet, Text, View, StatusBar } from 'react-native';
import { Router, Scene } from 'react-native-router-flux'
import Home from './src/components/Home'
import Login from './src/components/screens/Login'
import Loading from "./src/components/Loading";
export default class App extends React.Component {
state = {
fontLoaded: false,
};
async componentDidMount() {
await Font.loadAsync({
'Roboto_medium': require('./assets/fonts/Roboto_medium.ttf'),
}
);
this.setState({fontLoaded: true})
}
render() {
if(!this.state.fontLoaded){
return(<Loading />)
}
return(
<Router >
<Scene key="root">
<Scene key="Home" component={Home} title="home" hideNavBar={true} />
<Scene key="Login" component={Login} title="login" hideNavBar={true} initial/>
</Scene>
</Router>
)
}
}
|
/* Text formatting */
import { formatBUT, formatMED, formatLG } from '/static/textFormatting.js'
/* Button behavior helper */
import { assignButtonBehavior } from '/static/buttonUtils.js'
/* ---------- Scene that displays results and stats about the game ---------- */
class EndScene extends Phaser.Scene {
/* ----- Defines the key identifier for the scene ----- */
constructor() {
super({key: 'endScene'});
}
/* ----- Receives the socket and statistics about the game ----- */
init(data) {
this.socket = data.socket;
this.round = data.round;
this.score = data.score;
this.cometsDestroyedStats = data.cometsDestroyedStats;
}
/* ----- Loads the assets used in the scene ----- */
preload() {
this.load.image('background', '/assets/game/background/background.png');
this.load.image('button', '/assets/game/ui/button.png');
}
/* ----- Code run on scene start ----- */
create() {
/* Displays assets */
this.add.image(640, 360, 'background').setScale(1);
/* Creates texts to display statistics */
this.add.text(460, 160, 'Game Over', formatLG);
this.add.text(460, 260, `Round: ${this.round}`, formatMED);
this.add.text(460, 310, `Score: ${this.score}`, formatMED);
this.cometsDestroyedStats.forEach((player, i) => {
this.add.text(460, 360 + (50 * i), `${player.name} destroyed ${player.cometsDestroyed} comets`, formatMED);
});
/* Creates return to lobby button */
this.add.text(615, 625,
`Return
to
Lobby`,
formatBUT).setDepth(1);
this.lobbyButton = this.add.image(640, 650, 'button');
assignButtonBehavior(this.lobbyButton, () => {
this.socket.emit('requestEndToLobby');
})
/* Reloads the window to start from the lobbyScene again */
this.socket.on('reloadEnd', () => {
location.reload();
});
}
}
export default EndScene;
|
function spy(args) {
let specialKey = args.shift();
let pattern = new RegExp(`( |^)(${specialKey}\\s+)([!%$#A-Z]{8,})( |\\.|,|$)`, 'gi');
let validatedMessage = '';
for(let sentence of args){
let match = pattern.exec(sentence);
while (match){
let message = match[3];
if(validMessage(message)){
validatedMessage = cryptMessage(message);
sentence = sentence.replace(match[0], match[1] + match[2] + validatedMessage + match[4]);
}
match = pattern.exec(sentence);
}
console.log(sentence);
}
function validMessage(text) {
if(text === text.toUpperCase())
return true;
return false;
}
function cryptMessage(message) {
message = message.replace(/!/g, '1');
message = message.replace(/%/g, '2');
message = message.replace(/#/g, '3');
message = message.replace(/\$/g, '4');
return message.toLowerCase();
}
}
spy(
[
`specialKey`,
`In this text the specialKey HELLOWORLD! is correct, but`,
`the following specialKey $HelloWorl#d and spEcIaLKEy HOLLOWORLD1 are not, while`,
`SpeCIaLkeY SOM%%ETH$IN and SPECIALKEY ##$$##$$ are!`,
]
);
|
import React, { Component } from "react";
// import {Link} from "react-router-dom";
import { APIHandler } from "../../api/handler";
// import CategoryList from "./CategoryList";
import "./../../styles/categoryCard.css";
// import ParticlesBg from 'particles-bg';
import "./../../styles/vars.css";
const categoryHandler = new APIHandler("/api/category");
export default class CategoryCard extends Component {
state = {
category: "",
};
async componentDidMount() {
const apiRes = await categoryHandler.getAll();
this.setState({ category: apiRes.data });
}
render() {
const {category} = this.state;
return (
<div className={`card-category ${this.props.categoryClass}`}>
{/* <ParticlesBg color="var(--color-gradient)" type="lines" bg={true} /> */}
{this.props.text}
{category.name}
</div>
);
}
}
|
exports.up = function(knex, Promise) {
return knex.schema.createTable('games', t => {
t.increments();
t.string('title').unique();
t.string('genre');
t.integer('releaseYear');
})
};
exports.down = function(knex, Promise) {
return knex.schema.dropTableIfExists('games');
};
|
import React from 'react';
import Drawer from 'material-ui/Drawer';
import MenuItem from 'material-ui/MenuItem';
import Avatar from 'material-ui/Avatar';
import Divider from 'material-ui/Divider';
import Menu from 'material-ui/Menu'
import RaisedButton from 'material-ui/RaisedButton';
import NewGameDialog from './newgamedialog';
class SideBar extends React.Component {
constructor(props) {
super(props);
this.state = {
users: []
};
this.style = {
top: 100,
bottom: 106,
left: 50,
position: 'fixed',
width: props.width
};
}
componentDidMount() {
const userService = this.props.app.service('users');
userService.find({
query: {
$sort: { email: 1 },
$limit: false
}
}).then((page) => {
this.setState({
users: page.data.reverse()
});
});
// Listen to newly created users
userService.on('created', (user) => {
this.setState({
users: this.state.users.concat(user)
});
});
}
renderGame(game) {
return(
<MenuItem key={game._id} value={game} primaryText={game._id} />
);
}
gameClicked(event,value) {
this.props.onActiveGame(value);
};
render() {
return (
<div>
<div style={this.style}>
<Menu onChange={this.gameClicked.bind(this)}>
{this.props.games.map(this.renderGame)}
</Menu>
<div>
<NewGameDialog users={this.state.users}/>
</div>
</div>
</div>
);
}
}
export default SideBar;
|
import React from "react";
import NumberFormat from "react-number-format";
import randomstring from "randomstring";
import withStyles from "@material-ui/core/styles/withStyles";
import Hidden from "@material-ui/core/Hidden";
import TableRow from "@material-ui/core/TableRow";
import TableHead from "@material-ui/core/TableHead";
import TableCell from "@material-ui/core/TableCell";
import TableBody from "@material-ui/core/TableBody";
import Table from "@material-ui/core/Table";
import TableFooter from "@material-ui/core/TableFooter";
import Snackbar from "@material-ui/core/Snackbar";
import BezopSnackBar from "../../assets/jss/bezop-mkr/BezopSnackBar";
import tooltipsStyle from "../../assets/jss/material-kit-react/tooltipsStyle";
import Currency from "../../helpers/currencyOperations";
import { getUserProfile, getUsersToken } from "../Auth/AccessControl";
import GridContainer from "../Grid/GridContainer";
import GridItem from "../Grid/GridItem";
import { API_URL } from "../Auth/UsersAuth";
import Shipment from "./Sections/Shipment";
import Payment from "./Sections/Payment";
import CartObject from "../../helpers/customerOperations";
const styles = theme => ({
root: {
width: "100%",
marginTop: theme.spacing.unit * 2,
overflowX: "auto",
padding: "0px",
},
table: {
minWidth: 700,
},
cartIcon: {
fontSize: "1.3em",
marginBottom: "-10px",
},
header: {
borderBottom: "1px solid lightgray",
},
tableHeader: {
textTransform: "uppercase",
},
tablePadding: {
padding: "2px 0px",
},
productName: {
fontWeight: "500",
},
productHeadings: {
margin: "0px",
paddingLeft: "5px",
},
bigMore: {
float: "right", fontSize: "0.4em",
},
tooltip: tooltipsStyle.tooltip,
});
class Checkout extends React.Component {
constructor(props) {
super(props);
this.state = {
Cart: CartObject.getCart(),
Products: (props.data.products) ? props.data.products : {},
currentCurrency: this.getCurrentCurrency() || { code: "USD", exchange: 1, symbol: "$" },
couponCode: 0,
orderShipment: this.initShipment(),
saveShipment: false,
loading: false,
orderStatus: this.getStatus(),
variantSnackBar: "success",
snackBarOpenSuccess: false,
snackBarMessageSuccess: "Yet to decide the action",
};
this.products = {};
this.cart = {
getQuantity: (id) => {
try {
const { state } = this;
const product = (state.Products) ? state.Products[id] : {};
return CartObject.getQuantity(product);
} catch (ex) {
console.log(ex.message);
}
return 1;
},
emptyCart: () => {
try {
const { events } = props.data;
CartObject.emptyCart(this, events);
} catch (ex) {
console.log(ex.message);
}
},
};
}
componentWillReceiveProps(newProps) {
this.setState({ Products: newProps.data.products });
}
onCloseHandlerSuccess = () => {
this.setState({
snackBarOpenSuccess: false,
});
};
getProducts = ids => fetch(`${API_URL}/products/operations/${ids.join("/")}/?key=${process.env.REACT_APP_API_KEY}`)
.then(response => response.json())
.then((json) => {
if (json.success && Object.keys(json.data).length > 0) {
this.setState({ Products: json.data });
}
throw new Error(json.message);
})
.catch(error => console.log(error.message));
setShipmentValues = (event) => {
try {
const { id, value } = event.target;
const { orderShipment } = this.state;
switch (id) {
case "fullname":
case "phone":
case "email":
case "note":
orderShipment[id] = value;
this.setState({ orderShipment, saveShipment: false });
break;
case "zip":
case "country":
case "state":
case "city":
case "street":
case "building":
orderShipment.shipping[id] = value;
this.setState({ orderShipment, saveShipment: false });
break;
default:
}
} catch (ex) {
console.log(ex.message);
}
};
getCurrentCurrency = () => {
try {
const order = JSON.parse(localStorage.getItem("order"));
if (!order) window.location.href = "/cart";
return order.vendorOrders
? Currency.getCurrencyById(order.vendorOrders[0].payable.currency)
: Currency.getCurrencyById(order.payable.currency);
} catch (ex) {
console.log(ex.message);
}
return null;
};
getStatus = () => {
try {
const order = JSON.parse(localStorage.getItem("order"));
return typeof order.vendorOrders === "object";
} catch (ex) {
console.log(ex.message);
}
return false;
};
initShipment = () => {
try {
const { fullname, phone, email, shipping, id } = getUserProfile("customer");
const order = JSON.parse(localStorage.getItem("order"));
if (order.orderStatus === undefined) {
return (Object.assign(order, {
orderNum: randomstring.generate(10),
customer: id,
fullname,
phone,
email,
note: "",
shipping: {
zip: shipping.zip,
country: shipping.country,
state: shipping.state,
city: shipping.city,
street: shipping.street,
building: shipping.building,
},
}));
}
return order;
} catch (ex) {
console.log(ex.message);
}
return null;
};
saveShipmentStatus = () => {
this.setState({ saveShipment: true, variantSnackBar: "success", snackBarOpenSuccess: true, snackBarMessageSuccess: "Shipment Saved." });
};
placeOrder = () => {
this.setState({ loading: true });
const { orderShipment, Cart } = this.state;
const { accessToken } = getUsersToken("customer");
const productIds = [];
Cart.map(item => productIds.push(item.product));
const orders = { Products: productIds, vendorOrders: [] };
this.cart.emptyCart();
Object.keys(orderShipment.products).map((vendorId) => {
const vendorOrder = {
payable: {
currency: orderShipment.payable.currency,
amount: 0,
},
shipmentDetails: {
deliveryNote: orderShipment.note,
recipient: orderShipment.fullname,
country: orderShipment.shipping.country,
state: orderShipment.shipping.state,
city: orderShipment.shipping.city,
street: orderShipment.shipping.street,
building: orderShipment.shipping.building,
zip: orderShipment.shipping.zip,
phone: orderShipment.phone,
email: orderShipment.email,
},
orderNum: orderShipment.orderNum,
vendor: vendorId,
customer: orderShipment.customer,
products: [],
};
Object.keys(orderShipment.products[vendorId]).map((pid) => {
vendorOrder.products.push({
quantity: orderShipment.products[vendorId][pid].quantity,
product: pid,
});
vendorOrder.payable.amount += orderShipment.products[vendorId][pid].subTotal;
return null;
});
fetch(`${API_URL}/orders/customer/?key=${process.env.REACT_APP_API_KEY}`, {
body: JSON.stringify(vendorOrder),
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Authorization: `Bearer ${accessToken}`,
},
method: "POST",
})
.then(res => res.json())
.then((responseJSON) => {
if (responseJSON.success && Object.keys(responseJSON.data).length > 1) {
const order = responseJSON.data;
orders.vendorOrders.push(order);
localStorage.setItem("order", JSON.stringify(orders));
// this.setState({ orderStatus: true, loading: false });
window.location.reload();
} else {
console.log(responseJSON);
this.setState({ loading: false });
}
})
.catch((ex) => {
console.log(ex.message);
this.setState({ loading: false });
});
return null;
});
};
render() {
const { classes } = this.props;
const {
Products,
Cart,
currentCurrency,
couponCode,
orderShipment,
saveShipment,
loading,
orderStatus,
variantSnackBar,
snackBarOpenSuccess,
snackBarMessageSuccess,
} = this.state;
let tax = 0;
let shipment = 0;
let subTotal = 0;
const coupon = couponCode;
try {
if (Object.keys(Products).length > 0) {
Object.values(Products).map((product) => {
const Price = Currency.resolvePrices(product);
let productQuantity = 1;
Cart.map((item) => {
if (item.product === product.id) {
productQuantity = item.quantity;
}
return item;
});
const discount = Price.discount * productQuantity;
const vat = Price.tax * productQuantity;
const shipping = Price.shipping * productQuantity;
const total = (((Price.unitPrice * productQuantity) - discount) + vat + shipping);
subTotal += total;
tax += vat;
shipment += shipping;
this.products[product.id] = {
unitPrice: Price.unitPrice,
discount,
vat,
shipping,
total,
};
return null;
});
}
} catch (ex) {
console.log(ex.message);
}
const grandTotal = subTotal - coupon;
return (
<div className={classes.root}>
<Snackbar
anchorOrigin={{ vertical: "top", horizontal: "center" }}
open={snackBarOpenSuccess}
onClose={this.onCloseHandlerSuccess}
>
<BezopSnackBar
onClose={this.onCloseHandlerSuccess}
variant={variantSnackBar}
message={snackBarMessageSuccess}
/>
</Snackbar>
<GridContainer>
<GridItem md={8}>
{!orderStatus ? (
<Shipment
classes={classes}
orderShipment={orderShipment}
setShipmentValues={this.setShipmentValues}
saveShipmentStatus={this.saveShipmentStatus}
saveShipment={saveShipment}
loading={loading}
placeOrder={this.placeOrder}
/>)
: (
<Payment
Products={Products}
classes={classes}
getProducts={this.getProducts}
/>)}
</GridItem>
<GridItem md={4}>
<Hidden smDown>
<h2 className={classes.header}>
Order Summary
</h2>
</Hidden>
<Hidden mdUp>
<h3 className={classes.header}>
Order Summary
</h3>
</Hidden>
<Table padding="none">
<TableHead style={{ background: "lightgray" }}>
<TableRow className={classes.tableHeader}>
<TableCell>
Product
</TableCell>
<TableCell numeric>
Quantity
</TableCell>
<TableCell numeric>
Subtotal
</TableCell>
</TableRow>
</TableHead>
<TableBody>
{(Object.values(Products).length > 0)
? Object.values(Products).map(product => (
<TableRow key={product.id}>
<TableCell className={classes.tablePadding}>
<h6 className={classes.productName} title={product.name}>
{`${(product.name.length > 20) ? `${product.name.slice(0, 20)}...` : product.name}`}
</h6>
</TableCell>
<TableCell numeric className={classes.tablePadding}>
<h5 style={{ textAlign: "center", width: "70px", margin: "auto" }}>
{this.cart.getQuantity(product.id)}
</h5>
</TableCell>
<TableCell numeric className={classes.tablePadding}>
<NumberFormat
value={Currency.dollarConverter(currentCurrency.code || "USD", this.products[product.id].total, "FROM_USD")}
displayType="text"
thousandSeparator
prefix={`${currentCurrency.symbol} `}
decimalScale={2}
fixedDecimalScale
renderText={value => (
<h5>
{value}
</h5>
)}
/>
</TableCell>
</TableRow>
))
: <TableRow />
}
</TableBody>
</Table>
<hr />
<Table padding="none">
<TableBody>
<TableRow>
<TableCell className={classes.tablePadding}>
<h4 className={classes.productHeadings}>
Tax:
</h4>
</TableCell>
<TableCell numeric className={classes.tablePadding}>
<NumberFormat
value={Currency.dollarConverter(currentCurrency.code || "USD", tax, "FROM_USD")}
displayType="text"
thousandSeparator
prefix={`${currentCurrency.symbol} `}
decimalScale={2}
fixedDecimalScale
renderText={value => (
<h4>
{value}
</h4>
)}
/>
</TableCell>
</TableRow>
<TableRow>
<TableCell className={classes.tablePadding}>
<h4 className={classes.productHeadings}>
Shipping Fee:
</h4>
</TableCell>
<TableCell numeric className={classes.tablePadding}>
<NumberFormat
value={Currency.dollarConverter(currentCurrency.code || "USD", shipment, "FROM_USD")}
displayType="text"
thousandSeparator
prefix={`${currentCurrency.symbol} `}
decimalScale={2}
fixedDecimalScale
renderText={value => (
<h4>
{value}
</h4>
)}
/>
</TableCell>
</TableRow>
{coupon > 0 ? (
<TableRow>
<TableCell className={classes.tablePadding}>
<h4 className={classes.productHeadings}>
Coupon Code:
</h4>
</TableCell>
<TableCell numeric className={classes.tablePadding}>
<NumberFormat
value={Currency.dollarConverter(currentCurrency.code || "USD", coupon, "FROM_USD")}
displayType="text"
thousandSeparator
prefix={`${currentCurrency.symbol} `}
decimalScale={2}
fixedDecimalScale
renderText={value => (
<h4>
{value}
</h4>
)}
/>
</TableCell>
</TableRow>)
: null}
</TableBody>
<TableFooter>
<TableRow style={{ background: "lightgray" }}>
<TableCell className={classes.tablePadding}>
<h3 className={classes.productHeadings}>
Grand Total:
</h3>
</TableCell>
<TableCell numeric className={classes.tablePadding}>
<NumberFormat
value={Currency.dollarConverter(currentCurrency.code || "USD", grandTotal, "FROM_USD")}
displayType="text"
thousandSeparator
prefix={`${currentCurrency.symbol} `}
decimalScale={2}
fixedDecimalScale
renderText={value => (
<h3>
{value}
</h3>
)}
/>
</TableCell>
</TableRow>
</TableFooter>
</Table>
</GridItem>
</GridContainer>
</div>
);
}
}
export default withStyles(styles)(Checkout);
|
$(".innerNav a.animate").click(function(e){
e.preventDefault();
var href = $(this).attr("href");
$("html, body").animate({
scrollTop: $(href).offset().top -50
}, 900);
});
$(document).ready(function(){
$(window).scroll(function(){
var navigation = $(".navigation").offset();
if($(this).scrollTop() > 100){
$(".toTop").fadeIn();
} else {
$(".toTop").fadeOut();
}
});
$(".toTop").click(function(){
$("html, body").animate({
scrollTop: 0
}, 500);
});
});
$(document).ready(function() {
var navpos = $('.navigation').offset();
console.log(navpos.top);
$(window).bind('scroll', function() {
if ($(window).scrollTop() > navpos.top) {
$('.navigation').addClass('fixed');
}
else {
$('.navigation').removeClass('fixed');
}
});
});
|
const container = document.querySelector("#movie-container");
// Rendering to DOM
const renderMovies = (movies) => {
movies.forEach(movie => {
container.innerHTML += movieFactory(movie);
});
}
// Creating HTML respresentation
const movieFactory = (movie) => {
return `
<ul>
<li>${movie.title}</li>
<li>${movie.releaseDate}</li>
</ul>
`
}
// Trying to add new movie to HTML page when save btn is clicked
const newMovie = document.getElementById("movie-entry").value;
const newContainer = document.getElementById("new-movie-container");
// Creating HTML respresentation
const newMovieFactory = (movie) => {
return `
<ul>
<li>${movie}</li>
</ul>
`
}
// Rendering to DOM
const showMovie = (newMovie) => {
newContainer.innerHTML += newMovieFactory(newMovie);
}
|
import React from 'react';
import { connect } from 'react-redux';
import { StyleSheet, View, Text } from 'react-native';
import CryptoJS from 'crypto-js';
import {
UIStyle,
UIDetailsInput,
UIUploadFileInput,
UILinkInput,
UIContractAddressInput,
UILocalized,
UIButton,
UILink,
UIColor,
UIToastMessage,
UINavigationBar,
UIDetailsCheckbox,
} from '../../services/UIKit/UIKit';
import icoClose from '@uikit/assets/ico-close/close-blue.png';
import GovernanceScreen from './GovernanceScreen';
import EnvManager from './helpers/EnvManager';
import TONLocalized from '../../helpers/TONLocalized';
import FBStorage from '../../services/Firebase/FBStorage';
import FBInfoRequests from '../../services/Firebase/FBInfoRequests';
import Configs from '../../configs';
import SubmissionsFunctions from './SubmissionsFunctions';
const submissionPackage = require('./SubmissionPckg.js');
const PROPOSALS_TABLE = EnvManager.getProposalsTable();
const DOCUMENT_MAX_SIZE = 50000000;
const forumLink = EnvManager.isKorea() ? 'forum.tonkorea.org' : 'forum.freeton.org';
const styles = StyleSheet.create({
topDivider: {
borderBottomWidth: 1,
borderBottomColor: UIColor.whiteLight(),
},
noLetterSpacing: { letterSpacing: 0 },
});
const closeForm = (navigation) => {
if (navigation.state?.params?.initialRoute) {
navigation.navigate('ContestsScreen');
} else {
navigation.pop();
}
};
const getList = (snapshot) => {
const list = [];
snapshot.forEach(doc => list.push(doc.data()));
return list;
};
class ManifestNewSubmissionScreen extends GovernanceScreen {
static navigationOptions: CreateNavigationOptions = ({ navigation }) => {
if (!navigation.state.params) return { header: null };
const { topBarDivider } = navigation.state.params;
const dividerStyle = topBarDivider ? styles.topDivider : null;
return {
header: (
<UINavigationBar
containerStyle={[
UIStyle.width.full(),
dividerStyle,
]}
headerLeft={(
<UILink
textAlign={UILink.TextAlign.Left}
icon={icoClose}
title="Close"
onPress={() => closeForm(navigation)}
buttonSize={UIButton.buttonSize.medium}
/>
)}
/>
),
};
}
constructor(props) {
super(props);
this.state = {
submissionAddress: '',
fileSubmission: null,
discussionLink: '',
contest: null,
participantAddress: '',
contactAddress: '',
proccessing: false,
waitForFBAuthAndSDK: false,
gridColumns: 8,
checkNotUSA: false,
};
}
componentDidMount() {
super.componentDidMount();
this.tryAction();
}
componentDidUpdate(prevProps, prevState) {
if (
this.props.isLoggedIn &&
prevProps.isLoggedIn !== this.props.isLoggedIn &&
this.state.waitForFBAuthAndSDK
) {
this.tryAction();
this.setStateSafely({ waitForFBAuthAndSDK: false });
}
}
tryAction() {
let contest = null;
const { proposalAddress } = this.getNavigationParams();
if (this.props.isLoggedIn) {
FBInfoRequests.getCollection(PROPOSALS_TABLE)
.where('proposalWalletAddress', '==', proposalAddress)
.get()
.then((snapshotProposals) => {
[contest] = getList(snapshotProposals);
})
.catch((error) => {
console.log('get contest error: ', error);
})
.finally(() => {
if (!contest) this.props.navigation.navigate('ErrorScreen');
this.setStateSafely({ contest });
});
} else {
this.setStateSafely({
waitForFBAuthAndSDK: true,
});
}
}
getSubmissionAddress() {
return window.TONClient.crypto.ed25519Keypair()
.then((keys) => {
return { submissionAddress: '', keyPublic: keys.public };
})
.catch((error) => {
console.log('getSubmissionAddress error: ', error);
});
}
getFileSubmission() {
return this.state.fileSubmission;
}
readFile(file: File, cb: (bytes: any) => void) {
if (!file) {
cb && cb(null);
return;
}
const reader = new FileReader();
reader.onloadend = (evt: any) => {
cb && cb(evt.target.result);
};
reader.readAsArrayBuffer(file);
}
doesParticipantExist() {
return new Promise(resolve => resolve(false));
}
onSubmit = () => {
if (this.getFileSubmission() && this.getFileSubmission().size >= DOCUMENT_MAX_SIZE) {
UIToastMessage.showMessage(UILocalized.FileIsTooBig);
return;
}
this.setStateSafely({ proccessing: true });
const { contest } = this.state;
if (!contest) return;
let success = false;
this.readFile(this.getFileSubmission(), (fileBytes) => {
this.doesParticipantExist()
.then((doesExist) => {
const fType = this.getFileSubmission().type;
// console.log('fType', fType);
if (fType !== 'application/pdf') {
throw new Error('Wrong file format, PDF required');
}
const blob = new Blob([fileBytes], { type: fType }); // 'application/pdf'
const uid = Math.random().toString(36).substring(2) + (new Date()).getTime().toString(36);
// required UNIQUE filename in firebase storage:
const uniqName = `${uid}-${this.getFileSubmission().name}`;
return FBStorage.uploadDocument(blob, fType, uniqName);
})
.then((uploadedFileLink) => {
const discussionLink = this.state.discussionLink.startsWith(`https://${forumLink}`) ?
this.state.discussionLink :
`https://${forumLink}/${this.state.discussionLink}`;
const wordArray = CryptoJS.lib.WordArray.create(fileBytes);
const hash = CryptoJS.SHA256(wordArray).toString();
// console.log('SHA256 Checksum', `0x${hash}`);
return SubmissionsFunctions.submitSubmission(
contest.contestAddress,
this.state.participantAddress,
discussionLink,
uploadedFileLink,
`0x${hash}`,
this.state.contactAddress,
);
})
.then((result) => {
// console.log('submitSubmission ok', result);
success = true;
UIToastMessage.showMessage(TONLocalized.Contests.JoinRequestSent);
})
.catch((error) => {
console.log('submitSubmission error', error);
UIToastMessage.showMessage(error.message);
})
.finally(() => {
if (success) {
this.props.navigation.navigate(
'ProposalScreen',
{ proposalAddress: this.state.contest.proposalWalletAddress },
);
}
this.setStateSafely({ proccessing: false });
});
});
}
isSubmitDisabled() {
const isValid =
this.state.checkNotUSA &&
this.state.fileSubmission &&
this.state.discussionLink &&
this.state.participantAddress && this.participantAddressRef.isAddressValid(this.state.participantAddress);
return (!isValid);
}
onSubmitEditingName(ref) {
if (ref === this.participantAddressRef) {
this.contactAddressRef && this.contactAddressRef.focus();
} else if (ref === this.contactAddressRef) {
this.discussionLinkRef && this.discussionLinkRef.focus();
} else if (ref === this.discussionLinkRef) {
this.discussionLinkRef && this.discussionLinkRef.blur();
}
}
renderCenterColumn = () => {
const { contest } = this.state;
return (
<View>
<Text style={[UIStyle.text.primaryTitleBold(), styles.noLetterSpacing, UIStyle.margin.topVast()]}>
{TONLocalized.Contests.AddSubmission}
</Text>
<View style={UIStyle.margin.topHuge()}>
<Text style={[UIStyle.text.tertiaryTinyRegular(), styles.noLetterSpacing]}>
{TONLocalized.Contests.Contest}
</Text>
<Text style={[UIStyle.text.primaryBodyRegular(), styles.noLetterSpacing, UIStyle.margin.topTiny()]}>
{contest?.title}
</Text>
</View>
<UIContractAddressInput
ref={(me) => { this.participantAddressRef = me; }}
value={this.state.participantAddress}
onChangeText={participantAddress => this.setStateSafely({ participantAddress })}
onSubmitEditing={() => this.onSubmitEditingName(this.participantAddressRef)}
placeholder={TONLocalized.Contests.FreetonWalletAddress}
verify
/>
<UIContractAddressInput
ref={(me) => { this.contactAddressRef = me; }}
value={this.state.contactAddress}
onChangeText={contactAddress => this.setStateSafely({ contactAddress })}
onSubmitEditing={() => this.onSubmitEditingName(this.contactAddressRef)}
placeholder={TONLocalized.Contests.TonsurfAddressOptional}
verify
containerStyle={[UIStyle.margin.topSmall()]}
/>
<Text style={[UIStyle.text.tertiaryTinyRegular(), styles.noLetterSpacing, { marginTop: 8 }]}>
{TONLocalized.Contests.AddressToContactYou}
</Text>
<UILinkInput
ref={(me) => { this.discussionLinkRef = me; }}
value={this.state.discussionLink}
returnKeyType="next"
placeholder={TONLocalized.Contests.SubmissionLink}
beginningTag={`https://${forumLink}/`}
onChangeText={(discussionLink) => { this.setStateSafely({ discussionLink }); }}
onSubmitEditing={() => this.onSubmitEditingName(this.discussionLinkRef)}
containerStyle={[{ height: 72 }, UIStyle.margin.topSmall()]}
/>
<Text style={[UIStyle.text.tertiaryTinyRegular(), styles.noLetterSpacing, { marginTop: -8 }]}>
{`On ${forumLink}`}
</Text>
<UIUploadFileInput
uploadText={TONLocalized.Contests.AttachPDFText}
fileType="document"
onChangeFile={fileSubmission => this.setStateSafely({ fileSubmission })}
floatingTitleText={TONLocalized.Contests.AttachPDFText}
floatingTitle={!!this.state.fileSubmission}
containerStyle={[{ marginTop: 16 }]}
/>
<UIDetailsCheckbox
details={TONLocalized.Contests.ISignedAndAgree}
onPress={() => { this.setStateSafely({ checkNotUSA: !this.state.checkNotUSA }); }}
active={this.state.checkNotUSA}
style={UIStyle.margin.topDefault()}
switcherPosition="left"
/>
<UIButton
title={TONLocalized.Contests.Submit}
buttonSize={UIButton.ButtonSize.Large}
style={[UIStyle.margin.topHuge(), UIStyle.margin.bottomHuge()]}
onPress={this.onSubmit}
disabled={this.isSubmitDisabled()}
showIndicator={this.state.proccessing}
/>
</View>
);
}
}
const mapStateToProps = (state, ownProps) => {
return ({
isNarrow: state.controller.mobile,
isLoggedIn: state.auth.isLoggedIn,
...ownProps,
});
};
export default connect(mapStateToProps)(ManifestNewSubmissionScreen);
|
const fs = require("fs")
const Discord = require("discord.js")
module.exports = {
/* JS Stick Letters
__ __ ___ __
/ ` / \ |\ | |__ | / _`
\__, \__/ | \| | | \__>
*/
name: 'config',
description: 'Obtenir toutes les informations de la configuration serveur.',
syntax: 'config [read|modify] <setting> [value]',
execute(msg, args, config){
function readObject(object,element,embed,root){
for(i in object[element]){
if(typeof object[element][i] == "object"){
readObject(object[element], i, embed, `${root}/${i}`)
} else {
embed.addField(`${root}/${i}`,`${object[element][i]}`,true)
}
}
}
const embed = new Discord.MessageEmbed();
if(!args[0]){
embed.setTitle("Liste des paramètres de la config");
for(i in config){
(typeof config[i] == "object" ? readObject(config, i, embed, i) : embed.addField(`${i}`,`${config[i]}`,true))
}
return msg.channel.send(embed)
}
function unknownParamater(){
error.execute(msg, `Paramètre "${setting}" inconnu.\n(faites \`${config.prefix}config\` pour obtenir la liste des paramètres)`)
}
setting = !args[1] ? args[0] : args[1]
mode = !args[1] ? null : args[0];
value = args[2]
error = require("../utils/error.js")
if(mode == null || mode == "read"){
if(!config[setting]){unknownParamater()} else {
embed.addField(setting, config[setting],true)
msg.channel.send(embed)
}
} else if(mode == "modify"){
function stringContains(e,t){return-1!=e.indexOf(t)}
function getKeyPath(object, path){
if(!object || path.length === 0) return object;
return getKeyPath(object[path.shift()], path)
}
function setKeyPath(object, path, value){
if(!object || path.length === 0) return null
if(path.length === 1) object[path[0]] = value
else return setKeyPath(object[path.shift()], path, value)
}
oldValue = getKeyPath(config, setting.split("."))
try{value=typeof oldValue!="string"?JSON.parse(value):value}catch(e){}
if(!oldValue) return unknownParamater();
if(typeof oldValue == "object"){
embed.setDescription(`Quel paramètre voudriez-vous accéder dans "${setting.split(".").join("/")}" ?`)
.setColor("#3498db");
for(i in oldValue){
(typeof oldValue[i] == "object" ? readObject(oldValue, i, embed, i) : embed.addField(`${i}`,`${oldValue[i]}`,true))
}
return msg.channel.send(embed);
}
if(typeof oldValue != typeof value) return error.execute(msg, `"${typeof oldValue}" attendu au lieu de "${typeof value}"`)
if(oldValue == value) return error.execute(msg,`Rien n'a changé, "${setting}" toujours égal à \`${oldValue}\``);
setKeyPath(config, setting.split("."), value)
fs.writeFileSync("./handler/configs/" + msg.guild.id + ".json", JSON.stringify(config, null, 2), "utf-8")
embed.setColor("#2ecc71")
.setDescription(`Læ "${setting}" du serveur a été modifié pour "${value}"`)
.setAuthor(msg.author.username, msg.author.displayAvatarURL());
msg.channel.send(embed)
} else {
error.execute(msg, `Mode "${inconnu}", faites \`${config.prefix}help config\` pour plus d'informations`)
}
}
}
|
angular.module('easyNutri').factory('modalFactory', function () {
var modalFactory = {};
var notif = {};
var exists = false;
modalFactory.setNotificacao = function (notificacao) {
if (notificacao != null) {
notif = notificacao;
exists = true;
return true;
}
return false;
};
return modalFactory;
});
|
'use strict'
import test from 'ava'
import m from '../../'
test('html', t => {
t.throws(
() => {
m.getElements()
},
'Argument «html» must be a «string», not «undefined»'
)
t.throws(
() => {
m.getElements(null)
},
'Argument «html» must be a «string», not «object»'
)
t.throws(
() => {
m.getElements([])
},
'Argument «html» must be a «string», not «object»'
)
t.throws(
() => {
m.getElements({})
},
'Argument «html» must be a «string», not «object»'
)
t.throws(
() => {
m.getElements(123)
},
'Argument «html» must be a «string», not «number»'
)
t.throws(
() => {
m.getElements(true)
},
'Argument «html» must be a «string», not «boolean»'
)
t.throws(
() => {
m.getElements(Symbol('foo'))
},
'Argument «html» must be a «string», not «symbol»'
)
t.throws(
() => {
m.getElements(() => {})
},
'Argument «html» must be a «string», not «function»'
)
t.notThrows(
() => {
m.getElements('beleberda')
}
)
})
|
import React from 'react';
import {StyleSheet,View,Text } from 'react-native';
import CountDowns from 'react-native-countdown-component';
const CountDown = props => {
return (
<View style={{width:'100%',justifyContent:'center'}}>
<CountDowns
size={15}
until={ 100}
onFinish={() => alert('Finished')}
digitStyle={{backgroundColor: '#FFF', borderWidth: 2, borderColor: '#1CC625'}}
digitTxtStyle={{color: '#1CC625'}}
timeLabelStyle={{color: 'red', fontWeight: 'bold'}}
separatorStyle={{color: '#1CC625'}}
timeToShow={['H', 'M', 'S']}
timeLabels={{m: null, s: null}}
showSeparator
/>
<Text>ssss {JSON.stringify(props.time)}</Text>
</View>
)
}
export default CountDown;
|
export default /* glsl */`
#ifdef CUBEMAP_ROTATION
uniform mat3 cubeMapRotationMatrix;
#endif
vec3 cubeMapRotate(vec3 refDir) {
#ifdef CUBEMAP_ROTATION
return refDir * cubeMapRotationMatrix;
#else
return refDir;
#endif
}
`;
|
import { ContactData } from './contactData.js';
import { partition, makeAlert } from './helpers.js';
import { tagBp, contactBp, contactRowBp } from '../blueprints/bundle.js';
import { alerted, tagsUpdated } from './events.js';
export let domCache;
(function() {
const DomCache = (function() {
let contacts = [],
allTags = [],
activeTags = [];
// get contacts by their active tags
const getByTags = function getByActiveTags() {
let taggedContacts = contacts.filter(contact => {
return activeTags.every(tag => ContactData.tags(contact).includes(tag));
});
if (taggedContacts.length) {
return taggedContacts;
} else {
return false;
}
};
// filter a contactArr by name
const filterByName = function filterContactsByName(name, contactArr) {
return contactArr.filter(contact => {
return ContactData.name(contact).toLowerCase().includes(name);
});
};
// return a non-mutable copy of a cache
const copy = function copyCache(cache) {
return [...cache];
};
// cache agnostic includes
const includes = function cacheIncludes(searchElem) {
let isIncluded = false,
isTag = searchElem instanceof HTMLSpanElement,
isContact = searchElem.full_name,
isStr = typeof searchElem === "string";
if (isContact) {
isIncluded = contacts.some(contact => {
return searchElem.id === ContactData.id(contact);
});
}
else if (isTag) {
isIncluded = allTags.map(tag => tag.innerText).includes(searchElem.innerText);
}
else if (isStr) {
isIncluded = activeTags.includes(searchElem);
}
return isIncluded;
};
// cache agnostic indexOf
const indexOf = function indexOfCache(searchElem) {
let isTag = searchElem instanceof HTMLSpanElement,
isContact = searchElem instanceof HTMLDivElement,
isContactJson = searchElem.full_name,
isStr = typeof searchElem === "string";
if (isContact || isContactJson) {
let id = isContact ? ContactData.id(searchElem) : String(searchElem.id);
return contacts.map(ct => ContactData.id(ct)).indexOf(id);
}
else if (isTag) {
return allTags.map(tag => tag.innerText).indexOf(searchElem.innerText);
}
else if (isStr) {
return activeContacts.indexOf(searchElem);
}
return -1;
};
// build rows containing contact cards
const buildRows = function buildContactRows(contactArr=contacts) {
let frag = new DocumentFragment(),
rows = partition(copy(contactArr), 2);
rows.forEach(row => {
let rowDiv = _ui.make(contactRowBp).firstElementChild;
row.forEach(contact => rowDiv.appendChild(contact));
frag.appendChild(rowDiv);
});
return frag;
};
// append tag spans to contact card
const setContactTags = function setContactTags(tags, container) {
let spans = tags.map(tagVal => {
let tagSpan = _ui.make(tagBp, [tagVal.trim()]).firstElementChild;
domCache.pushTag(tagSpan.cloneNode(true));
return tagSpan;
});
container.replaceChildren(...spans);
};
// build contact card based on json data
const buildContact = function buildContactCard(contactJson) {
let data = ContactData.unmarshal(contactJson),
contactCard = _ui.make(contactBp, data),
tagsContainer = contactCard.querySelector('.tags'),
tags = contactJson.tags === null ? [] : contactJson.tags.split(',');
setContactTags(tags, tagsContainer);
return contactCard.firstElementChild;
};
// get count of tag / tag values across all contacts
const tagCount = function totalTagCount(tag) {
tag = typeof tag === "string" ? tag : tag.innerText;
let allContactTags = contacts.flatMap(ct => ContactData.tags(ct)),
count = 0;
return allContactTags.reduce((totalCount, currentTag) => {
if (currentTag === tag) {
return totalCount + 1;
} else {
return totalCount;
}
}, count);
};
// removes any non-existant tags then dispatches `tagsUpdated`
const updateTags = function updateTagsContainer(thisArg) {
let removedTags = [];
allTags.map(tag => tagCount(tag))
.forEach((count, idx) => {
if (count === 0) {
removedTags.push(allTags[idx]);
}
});
if (removedTags.length) {
removedTags.forEach(tag => thisArg.spliceTag(tag));
_ui.get({id: 'filterTags'}).dispatchEvent(tagsUpdated);
}
};
// update element state based on `activeTags`
const tagState = function setTagState(state) {
let condition;
if (state === 'active') {
condition = (tag) => includes(tag.innerText);
} else {
condition = (tag) => !includes(tag.innerText);
}
_ui.get({class: 'badge'}).forEach(uniqTag => {
if (condition(uniqTag)) {
_ui.state(uniqTag, state);
}
});
};
return {
init() {
return this;
},
// visual bug fix when going from no contacts back to contact rows
activateTags() {
tagState('active');
},
// check for active tags then return doc frag from `buildRows`
activeContacts() {
let taggedContacts = getByTags();
if (taggedContacts) {
return buildRows(taggedContacts);
} else {
return makeAlert('danger', 'No contacts found.');
}
},
// return a non-mutable copy of `contacts`
allContacts() {
return copy(contacts);
},
// return doc frag from `buildRows` with default parameter
contactRows() {
return buildRows();
},
// return a doc frag containing all existing tag spans
tags() {
let frag = new DocumentFragment();
copy(allTags).forEach(tag => frag.appendChild(tag));
return frag;
},
// if contact doesn't exist in `contacts`, add it, then return length of `contacts`
pushContact(contactJson) {
if (!includes(contactJson)) {
contacts.push(buildContact(contactJson));
}
return contacts.length;
},
// update a contact with provided json data (will overwrite all fields with new vals)
updateContact(contactJson) {
let contactIdx = indexOf(contactJson),
tags = contactJson.tags === null ? [] : contactJson.tags.split(',');
if (contactIdx !== -1) {
ContactData.set(contacts[contactIdx], contactJson);
let tagContainer = contacts[contactIdx].querySelector('.tags');
setContactTags(tags, tagContainer);
updateTags(this);
}
},
// if contact exists, splice it, returning array containing spliced contact or empty if not found
spliceContact(contactId) {
let contactIdx = indexOf({full_name: "fake_contact_json", id: contactId});
if (contactIdx !== -1) {
let spliced = contacts.splice(contactIdx, 1);
updateTags(this);
return spliced;
}
return [];
},
// if tag doesn't exist in `allTags`, add it then return length
pushTag(tag) {
if (!includes(tag)) {
tag.blueprint = 'tag';
allTags.push(tag);
_ui.get({id: 'filterTags'}).dispatchEvent(tagsUpdated);
}
return allTags.length;
},
// if tag exists, splice it, returning array containing spliced tag or empty if not found
spliceTag(tag) {
let tagIdx = indexOf(tag);
if (tagIdx !== -1) {
return allTags.splice(tagIdx, 1);
}
return [];
},
// toggle active tag state for filtering
toggleTag(tag) {
let tagValue = tag.innerText,
tagIdx = activeTags.indexOf(tagValue);
if (tagIdx === -1) {
activeTags.push(tagValue);
} else {
activeTags.splice(tagIdx, 1);
tagState('default');
}
},
// filter rows by name, returning doc frag from `buildRows`
filterRows(name) {
let taggedContacts = getByTags(),
filterContacts;
filterContacts = taggedContacts ? taggedContacts : contacts;
return buildRows(filterByName(name.toLowerCase(), filterContacts));
},
};
})();
domCache = Object.create(DomCache).init();
})();
|
/**다음의 값이 주어졌을 때
```
l = [10, 20, 25, 27, 34, 35, 39]
```
n번 순회를 결정합니다. 예를 들어 2번 순회하면
```
l = [35, 39, 10, 20, 25, 27, 34]
```
여기서 변하기 전 원소와 변한 후 원소의 값의 차가 가장 작은 값을 출력하는 프로그램을 작성하세요.
예를 들어 2번 순회했을 때 변하기 전의 리스트와 변한 후의 리스트의 값은 아래와 같습니다.
**순회전_리스트 = [10, 20, 25, 27, 34, 35, 39]
순회후_리스트 = [35, 39, 10, 20, 25, 27, 34]
리스트의_차 = [25, 19, 15, 7, 9, 8, 5]**
39와 변한 후의 34 값의 차가 5이므로 리스트의 차 중 최솟값입니다. 따라서 39와 34의 인덱스인 6과 39와 34를 출력하는 프로그램을 만들어주세요.
```jsx
const l = [10, 20, 25, 27, 34, 35, 39]; //기존 입력 값
const n = parseInt(prompt('순회횟수는?), 10);
function rotate(inL, inN){
<빈칸을 채워주세요>
}
rotate(l, n)
```
**입력**
순회횟수는 : 2
**출력**
index : 6
value : 39, 34
---
**입력**
순회횟수는 : 3
**출력**
index : 5
value : 35, 25
*/
function rotate(a, t){
let b = a.slice();
let c = [];
for (let i = 0; i < t; i++){
b.unshift(b.pop());
}
for (let i in a){ // let i in b 도 된다.
c.push(Math.abs(a[i]-b[i]));
}
//최솟값
const m = Math.min.apply(null, c);
//최솟값의 인덱스 구하기
let index = c.indexOf(m);
console.log("index :", index);
console.log("value :", a[index], b[index]);
}
const l = [10, 20, 25, 27, 34, 35, 39]; //기존 입력 값
const turn = prompt('순회 횟수는?');
rotate(l, turn);
|
import {_webapp} from './webapp'
/**
* 存储localStorage
*/
export const setStore = (name, content) => {
if (!name) return
if (typeof content !== 'string') {
content = JSON.stringify(content)
}
window.localStorage.setItem(name, content)
}
/**
* 获取localStorage
*/
export const getStore = name => {
if (!name) return
return window.localStorage.getItem(name)
}
/**
* 删除localStorage
*/
export const removeStore = name => {
if (!name) return
window.localStorage.removeItem(name)
}
export const GetQueryString=function(url,name){
let reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
// let r = window.location.search.substr(1).match(reg);
let r = url.substr(1).match(reg);
if(r!=null)return unescape(r[2]); return null;
}
/**
*
* app端的数据交互功能
*/
export const fn = {
}
|
//0引入用来发送请求的方法
import { request } from '../../request/index.js';
Page({
data: {
swiperList:[],
//导航数组
catesList:[],
//楼层数据
floorList:[]
},
onLoad: function (options) {
// //发送异步请求
// var reqTash=wx.request({
// url: "https://api-hmugo-web.itheima.net/api/public/v1/home/swiperdata",
// https://api-hmugo-web.itheima.net/api/public/v1/categories
// success:(result)=>{
// this.setData({
// swiperList:result.data.message
// })
// }
// });
this.getSwiperList();
this.getCateList();
this.getFloorList();
// request({url:"/home/swiperdata"})
// .then(result=>{
// this.setData({
// swiperList:result.data.message
// })
// })
},
//获取轮播图数据方法
getSwiperList(){
request({url:"/home/swiperdata"})
.then(result=>{
this.setData({
swiperList:result
})
})
},
//获取分类导航数据方法
getCateList(){
request({url:"/home/catitems"})
.then(result=>{
this.setData({
catesList:result
})
})
},
//获取楼层数据方法
getFloorList(){
request({url:"/home/floordata"})
.then(result=>{
this.setData({
floorList:result
})
})
},
onReady: function () {
//,https://api-hmugo-web.itheima.net/api/public/v1/home/floordata
}
})
|
$(function () {
// Hide & Show forms
var credentialsForm = $('.Credentials-form');
var identityForm = $('.Identity-form');
var triggerCredentialFormButton = $('#CredentialsForm');
var triggerIdentityFormButton = $('#IdentityForm');
var hideFormButton = $('#HideForm');
triggerCredentialFormButton.click(function () {
if (credentialsForm.hasClass('hidden')) {
credentialsForm.removeClass('hidden');
displayFormButton('hide');
} else {
credentialsForm.addClass('hidden');
displayFormButton('show');
}
});
triggerIdentityFormButton.click(function () {
if (identityForm.hasClass('hidden')) {
identityForm.removeClass('hidden');
displayFormButton('hide');
} else {
identityForm.addClass('hidden');
displayFormButton('show');
}
});
hideFormButton.click(function () {
credentialsForm.addClass('hidden');
identityForm.addClass('hidden');
displayFormButton('show');
});
function displayFormButton(action) {
if (action == 'hide') {
$('.FormButton').addClass('hidden');
hideFormButton.removeClass('hidden');
} else if (action == 'show') {
$('.FormButton').removeClass('hidden');
hideFormButton.addClass('hidden');
}
}
// Change credential form
function credentialFormIsValid() {
return $('input[name="new_password"]').val() == $('input[name="new_password_confirm"]').val();
}
credentialsForm.submit(function () {
$('.alert').addClass('hidden');
event.preventDefault();
var credentials = {
email: $('input[name="email"]').val(),
current_password: $('input[name="current_password"]').val(),
new_password: $('input[name="new_password"]').val()
};
// Verification
if (credentialFormIsValid()) {
// Send request
$.ajax({
url: '/services/ChangeCredentialsService.php',
method: 'POST',
data: credentials,
complete: function (data) {
var response = data.responseJSON;
switch (response.status) {
case 'success':
document.location.href = 'profil.php';
break;
case 'incorrect_password':
$('.incorrect_password').removeClass('hidden');
break;
case 'error':
$('.server_error').removeClass('hidden');
}
}
})
} else {
$('.not_the_same').removeClass('hidden');
}
});
// Change Identity Form
identityForm.submit(function () {
$('.alert').addClass('hidden');
event.preventDefault();
var identity = {
last_name: $('input[name="last_name"]').val(),
first_name: $('input[name="first_name"]').val(),
city: $('select[name="city"]').select2().val(),
number: $('input[name="number"]').val()
};
$.ajax({
url: '/services/ChangeIdentityService.php',
method: 'POST',
data: identity,
complete: function (data) {
var response = data.responseJSON;
switch (response.status) {
case 'success':
document.location.href = 'profil.php';
break;
case 'error':
$('.server_error').removeClass('hidden');
break;
}
}
})
});
// Mise a disposition des villes
$('select[name="city"]').select2({
ajax: {
url: '/services/GetCityService.php',
dataType: 'json',
data: function (params) {
var query = {
search: params.term,
};
return query;
},
processResults: function (data) {
var resultat = data.map(function (item) {
return {
id: item.id_city,
text: item.name,
};
});
return {
results: resultat
};
}
},
minimumInputLength: 1,
});
});
|
import React, { useState } from 'react';
const ProductForm = props => {
const productFormStyle = {
display: 'flex',
flexDirection: 'column',
alignItems: 'center'
}
const formSpanStyle = {
display: 'flex',
justifyContent: 'space-between',
width: '20%',
padding: '8px 8px',
alignItems: 'center',
backgroundColor: 'lightgrey',
borderRadius: '5px',
color: 'grey',
marginTop: '20px'
}
const formButtonStyle = {
display: 'flex',
justifyContent:'center',
alignItems: 'center',
width:'140px',
height: '25px',
marginTop: '20px',
color: 'grey',
backgroundColor: 'lightgrey',
border: 'none',
borderRadius: '3px',
cursor: 'pointer'
}
const formInputStyle = {
border: '0',
borderRadius: '2px',
height: '20px'
}
const {setProduct, product, handleSubmit} = props
const titleHandler = (e) => {
setProduct({...product,title:e.target.value})
}
const priceHandler = (e) => {
setProduct({...product,price:e.target.value})
}
const descHandler = (e) => {
setProduct({...product,description:e.target.value})
}
return (
<div>
<form onSubmit={handleSubmit} style={productFormStyle}>
<span style={formSpanStyle}>
<label htmlFor="title">
Title
</label>
{product?
<input onChange={titleHandler} style={formInputStyle} type="text" name="title" id="title" placeholder={product.title}/>
:
<input onChange={titleHandler} style={formInputStyle} type="text" name="title" id="title"/>
}
</span>
<span style={formSpanStyle}>
<label htmlFor="price">
Price
</label>
{product?
<input onChange={priceHandler} style={formInputStyle} type="text" name="price" id="price" placeholder={"$"+product.price} />
:
<input onChange={priceHandler} style={formInputStyle} type="text" name="price" id="price" />
}
</span>
<span style={formSpanStyle}>
<label htmlFor="description">
Description
</label>
{product?
<input onChange={descHandler} style={formInputStyle} type="text" name="description" id="description" placeholder={product.description}/>
:
<input onChange={descHandler} style={formInputStyle} type="text" name="description" id="description"/>
}
</span>
<button style={formButtonStyle}>Create</button>
</form>
</div>
);
};
export default ProductForm;
|
const express = require('express');
const fs = require('fs');
const path = require('path');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const morgan = require('morgan');
const moment = require('moment');
const createError = require('http-errors');
const methodOverride = require('method-override');
const parse_filepath = require('parse-filepath');
const PageHelper = require('../helpers/PageHelper');
const AuthHelper = require("../../applications/Auth/helpers/AuthHelper");
const logger = require(__loggerPath);
const DatabaseHelper = require(__rootPath + '/components/helpers/DatabaseHelper');
const useragent = require('express-useragent');
const { route } = require('../../applications/DataUse/routes/dataUse');
const ObjectHelper = require('../helpers/ObjectHelper');
const LogInfoHelper = require(__rootPath + '/components/helpers/LogInfoHelper');
module.exports = {
setMiddlewareConfig: function(app) { // 미들웨어 설정
app.set('views', __rootPath);
app.set('view engine', 'ejs');
app.set('env', 'release');
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(methodOverride('_method'));
app.use(morgan(function (tokens, req, res) { //웹 로그 설정
let url = tokens.url(req, res);
if(parse_filepath(url).ext.length > 0) { return; }
if(!forward.config.logger.global.weblog) { return; }
logger.debug(`[${tokens.method(req, res)}] ${url} ${tokens.status(req, res)}`);
// menu log 저장
if(JSON.stringify( forward.config.menu ).indexOf(req.url.toString()) == -1) { return; }
LogInfoHelper.insertMenuLog(req);
}));
app.use(useragent.express());
},
webIndexConfig: function(app) {
app.all('/', function(req, res) { res.redirect(forward.config.web.link.index); }); // 인덱스 페이지 설정
app.all('/favicon.ico', function(req, res) { res.redirect(forward.config.web.link.favicon); }); // 파비콘 설정
},
setErrorHandler: function(app) { // 에러핸들러 설정
app.use(function(req, res, next) {
next(createError(404));
});
app.use(function(err, req, res, next) {
let errStatus = err.status || 500;
let errorPage = forward.config.web.page.error.notFound;
if(req.originalUrl.indexOf("/openapi/data") != -1){ // API 요청일 경우
res.contentType('text/xml'); // 컨텐츠 타입 xml로 설정
res.status(errStatus);
res.send(ObjectHelper.getXMLFromJson({RESULT: false, MESSAGE: 'API SERVICE OCCURED ERROR. PLEASE TRY AGAIN.'}));
} else {
if(errStatus != 404) {
logger.error(err.message, err.stack);
errorPage = forward.config.web.page.error.exception;
}
res.status(errStatus);
res.render(errorPage, { status: errStatus, message: err.message, stack: err.stack });
}
});
},
registMapper: function(currentApplication) { //맵퍼 설정
let mapperCnt = 0;
let mapperPath = path.join(__rootPath, currentApplication.path, 'mappers');
if(!fs.existsSync(mapperPath)) { return; }
fs.readdirSync(mapperPath).forEach(function(mapperEntry) {
if(fs.statSync(path.join(mapperPath, mapperEntry)).isDirectory()) { return; }
forward.database.mariadb.mybatisMapper.createMapper([ path.join(mapperPath, mapperEntry) ]);
logger.debug(`${currentApplication.name} 애플리케이션의 ${parse_filepath(mapperEntry).name} 맵퍼를 등록하였습니다.`);
mapperCnt++;
});
return mapperCnt;
},
registRouter: function(app, currentApplication) { // 라우터 설정
let routerCnt = 0;
let applicationRoutesPath = path.join(__rootPath, currentApplication.path, 'routes');
if(!fs.existsSync(applicationRoutesPath) || currentApplication.url.path == null) { return; }
currentApplication.url.list = new Array();
fs.readdirSync(applicationRoutesPath).forEach(routerEntry => { //라우터 폴더의 파일들을 확인한다.
if(fs.statSync(path.join(applicationRoutesPath, routerEntry)).isDirectory()) { return; } // 파일이 아니라면 건너 뛴다.
let url = `${forward.config.web.server.contextPath}${currentApplication.url.path}`.replace(/\/\//g, '/');
let router = require(path.join(__rootPath, currentApplication.path, 'routes', routerEntry));
app.use(url, router); // 라우터 등록
function registRoutingURL(url) {
currentApplication.url.list.push(url);
logger.debug(`${currentApplication.name} 애플리케이션의 라우터 주소 ${url} 을 매핑하였습니다.`);
}
router.stack.forEach(function(routingUrl) { //라우팅 URL 등록
let routeUrl = routingUrl.route.path;
if(Array.isArray(routeUrl)) { // 라우팅 URL이 여러개라면
routeUrl.forEach(function(routingUrlEntry) {
registRoutingURL((url+routingUrlEntry).replace(/\/\//g, '/'));
});
} else {
registRoutingURL((url+routeUrl).replace(/\/\//g, '/'));
}
});
routerCnt++;
});
return routerCnt;
}
}
|
window.$=HTMLElement.prototype.$=function(selector){
var elems=(this==window?document:this)
.querySelectorAll(selector);
if(elems==null){
return null;
}else if(elems.length==1){
return elems[0];
}else{
return elems;
}
}
window.onload=function(){
$("li.app_jd").onmouseover=
$("li.service").onmouseover=function(){
//this-->li
this.$("[id$='_items']").style.display="block";
this.$("b+a").className="hover";
}
$("li.app_jd").onmouseout=
$("li.service").onmouseout=function(){
//this-->li
this.$("[id$='_items']").style.display="none";
this.$("b+a").className="";
}
$("#category").onmouseover=
$("#category").onmouseout=function(){
var cate_box=$("#cate_box");
cate_box.style.display=
cate_box.style.display=="block"?"none":"block";
}
//找到id为cate_box下的所有li元素,绑定mouseover事件
var lis=$("#cate_box>li");
for(var i=0;i<lis.length;i++){
lis[i].onmouseover=function(){
this.$("div.sub_cate_box").style.display="block";
this.$("h3").className="hover";
}
lis[i].onmouseout=function(){
this.$("div.sub_cate_box").style.display="none";
this.$("h3").className="";
}
}
preview.init();
console.log(preview);
}
/*缩略图和放大图*/
var preview={
LIWIDTH:62,//每个li的宽度
moved:0,//左移的个数,左移就+1,右移就-1
COUNT:0,
ul:null,
aBack:null,
aFor:null,
maskW:0,
maskH:0,
maskTop:0,
maskLeft:0,
init:function(){//初始化
//留住this
var self=this;
//找到id为icon_list的ul,保存在self的ul中
self.ul=$("#icon_list");
//获取self下所有li,将length属性值保存到self的count中
self.count=self.ul.$("li").length;
//找到id为preview下的直接子元素h1下的直接子元素a
var as=$("#preview>h1>a");
//保存在as中
//将as[0]保存在self的aBack中
self.aBack=as[0];
self.aFor=as[1];
self.aBack.onclick=
self.aFor.onclick=function(){
if(this.className.indexOf("_disable")==-1){
if(getComputedStyle){
style=getComputedStyle(self.ul);
}else{
style=self.ul.currentStyle;
}
if(this.className=="forward"){
self.moved++;
self.ul.style.left=parseFloat(style.left)-self.LIWIDTH+"px";
}else{
self.moved--;
self.ul.style.left=parseFloat(style.left)+self.LIWIDTH+"px";
}
if(self.moved==0){
self.aBack.className+="_disable";
}else if(self.count-self.moved==5){
// 否则,如果self的count-selft的moved==5
// self的aFor的className追加"_disabled"
self.aFor.className+="_disabled";
}else{//否则
// 替换aBack和aFor的className中的"_disabled"
// 为"",再赋值回className中
self.aFor.className="forward";
self.aBack.className="backward";
}
}
}
//为self的ul绑定mouseover事件处理函数
self.ul.onmouseover=function(){
// 获得事件对象e
var e=window.event||arguments[0];
// 获得目标对象target
var target=e.srcElement||e.target;
// 如果target是img元素
if(target.nodeName=="IMG"){
var src=target.src
var i=src.lastIndexOf(".");
src=src.slice(0,i)+"-m"+src.slice(i);
$("#mImg").src=src;
}
// xxxx/product-s1.jpg
}
//找到id为superMask的div,
//将mouseover和mouseout事件绑定为同一处理函数
// 如果id为mask的div是显示的
// 就改为隐藏的
// id为largeDiv的div同时隐藏
// 否则
// 将id为mask的div显示出来
// id为largeDiv的div同时显示
// 获得id为mImg元素的src属性。存在src中
var div=$("#superMask")
div.onmouseover=div.onmouseout=function(){
if($("#mask").style.display=="block"){
$("#mask").style.display="none";
$("#largeDiv").style.display="none";
}else{
$("#mask").style.display="block";
$("#largeDiv").style.display="block";
var src=$("#mImg").src;
var i=src.lastIndexOf(".");
src=src.slice(0,i-1)+"l"+src.slice(i);
$("#largeDiv").style.backgroundImage="url("+src+")"
}
}
//初始化mask的宽度和最大top,最大left
//获得id为mask的元素计算后的样式style
//设置self的maskW为style
if(getComputedStyle){
var style=getComputedStyle($("#mask"));
}else{
var style=$("#mask").currentStyle;
}
self.maskW=parseFloat(style.width);
self.maskH=parseFloat(style.height);
var style=getComputedStyle($("#superMask"));
self.maxTop=parseFloat(style.width)-self.maskW;
self.maxLeft=parseFloat(style.height)-self.maskH;
$("#superMask").onmousemove=function(){
var e=window.event||arguments[0];
var x=e.offsetX, y=e.offsetY;
var left=x-self.maskW/2;
var top=y-self.maskH/2;
top<0?top=0:
top>self.maxTop?top=self.maxTop:top=top;
left<0?left=0:
left>self.maxLeft?left=self.maxLeft:left=left;
$("#mask").style.left=left+"px";
$("#mask").style.top=top+"px";
$("#largeDiv").style.backgroundPosition=-left*16/7+"px "+(-top*16/7)+"px"
}
}
}
/*实现顶部菜单弹出的统一方法*/
function showItems(li) {
li.querySelector("a").className+=" hover";
li.querySelector("a+[id$='items']").style.display="block";
}
function hideItems(li) {
li.querySelector("a").className=li.querySelector("a").className.slice(0,-6);
li.querySelector("a+[id$='items']").style.display="";
}
/*实现全部商品分类两级菜单弹出*/
function showCate(category) {
category.querySelector("#cate_box").style.display="block";
}
function hideCate(category){
category.querySelector("#cate_box").style.display="";
}
function showSubCate(li) {
li.querySelector("h3+div").style.display="block";
li.querySelector("h3").className="hover";
}
function hideSubCate(li) {
li.querySelector("h3+div").style.display="";
li.querySelector("h3").className="";
}
/*实现产品图片部分*/
/*实现小图片列表移动*/
/*小图预览区域的图片轮换*/
const LIWIDTH=62;
var moved=0; //移动次数
function move(a){
var iconList=a.parentNode.querySelector("a~ul");
var count=iconList.querySelectorAll("li").length;
if(a.className.indexOf('_disabled')==-1){
moved+=a.className=="forward"?1:-1;
iconList.style.left=moved*LIWIDTH*(-1)+20+'px';
var aBackward= a.className=="backward"?a:
iconList.parentNode.querySelector("a[class^='backward']");
var aForward= a.className=="forward"?a:
iconList.parentNode.querySelector("a[class^='forward']");
if(moved==0) {
aBackward.className+="_disabled";
}else if(moved==count-5) {
aForward.className+="_disabled"
}else {
aBackward.className="backward";
aForward.className="forward";
}
}
}
/*实现鼠标进入小图片,切换中图片*/
function changeMImage(e){//当鼠标悬停在小图片上时更改中等产品图片
//...\product-s1.jpg-->...\product-s1-m.jpg
var source= e.srcElement|| e.target;
if(source.nodeName=="IMG"){
var dot=source.src.lastIndexOf('.');
var mSrc=source.src.substring(0,dot)+'-m'+source.src.substring(dot);
document.querySelector("#mImg").src=mSrc;
}
}
/*中图片局部放大*/
//可显示的175x175的半透明遮罩层
//显示产品大图的区块
//var largeDiv=document.getElementById('largeDiv');
//鼠标进入,显示大图:
function showMask(superMask){
var mask=superMask.parentNode.querySelector("#mask");
mask.style.display="block";
var mImgSrc=mask.parentNode.querySelector('#mImg').src;
//...\product-s1-m.jpg-->...\product-s1-l.jpg
var d=mImgSrc.lastIndexOf('.');
var largeSrc=mImgSrc.substring(0,d-1)+'l'+mImgSrc.substring(d);
var largeDiv=document.querySelector("#largeDiv");
largeDiv.style.backgroundImage='url('+largeSrc+')';
largeDiv.style.display='block';
}
function hideMask(superMask){
superMask.parentNode.querySelector("#mask").style.display='';
document.querySelector("#largeDiv").style.display='';
}
//鼠标移动,改变大图背景位置
var width=350;//mask活动区域的宽
var height=350;//mask活动区域的高
function zoom(e,superMask){
//获取鼠标当前坐标-遮罩层的一半=遮罩层的坐标
var left=e.offsetX-175/2;
//遮罩层最左边不能<0,最右边不能超出容器宽-175
left=left>width-175?(width-175):left>0?left:0;
var top=e.offsetY-175/2;
//遮罩层最上边不能<0,最下边不能超出容器高-175
top=top>height-175?height-175:top>0?top:0;
var mask=superMask.parentNode.querySelector("#mask");
mask.style.left=left+'px';
mask.style.top=top+'px';
/***控制大图预览区***/
var largeDiv=document.querySelector("#largeDiv");
largeDiv.style.backgroundPositionX=left*2*(-1)+'px';
largeDiv.style.backgroundPositionY=top*2*(-1)+'px';
}
/*产品介绍里的页签切换*/
var tabsArray=
["product_info","product_data","product_package","product_saleAfter"];
function showTab(li, index){
var lis=li.parentNode.getElementsByTagName("li");
for(var i=0;i<lis.length;i++){ lis[i].className=""; }
li.className="current";
if(index!=-1){
for (var i=0;i<tabsArray.length;i++){
var tabDiv=document.getElementById(tabsArray[i]);
tabDiv.style.display=i==index?"block":"none";
}
}else{
for (var i=0;i<tabsArray.length;i++){
var tabObj = document.getElementById(tabsArray[i]);
tabObj.style.display = "none";
}
}
}
|
import React, {
Component,
} from 'react'
import {
View,
} from 'react-native'
import Promocoes from '@containers/Promocoes'
export default class PromocoesScreen extends Component {
static route = {
navigationBar: {
title: 'Promocoes',
},
}
static defaultProps = {}
static propTypes = {}
constructor(props) {
super(props)
this.state = {}
}
render() {
return (
<View style={{flex : 1}}>
<Promocoes />
</View>
)
}
}
|
/* DOM Selectors */
const form = document.querySelector('#end-form'),
username = document.querySelector('#input-name'),
saveBtn = document.querySelector('#save-btn'),
mostRecentScore = JSON.parse(localStorage.getItem('mostRecentScore')) || [],
result = document.querySelector('#result');
/* Event Listeners */
username.addEventListener('keyup', () => {
saveBtn.disabled = !username.value;
});
form.addEventListener('submit', e => {
// Prevent Form From Submitting
e.preventDefault();
// Get User Input Value
const name = username.value;
// User Object
const player = {
name,
score : mostRecentScore.score,
time : mostRecentScore.time
};
// Update Local Storage
const highScores = JSON.parse(localStorage.getItem('highScores')) || [];
highScores.unshift(player);
highScores.splice(5);
localStorage.setItem('highScores', JSON.stringify(highScores));
// Relocate
window.location.replace('/');
});
window.addEventListener('DOMContentLoaded', () => {
// Update Most Recent Score
const splitTime = mostRecentScore.time.split('');
const html = `<h3 id="result" class="result">${mostRecentScore.score}/<span class="end-color">11</span> - ${splitTime[0]}<span class="end-color">m</span> ${splitTime[3]}<span class="end-color">s</span></h3>`;
result.innerHTML = html;
});
|
'use strict';
// Module dependencies
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// Degree Schema
var DegreeSchema = new Schema({
university: {
type: Schema.Types.ObjectId, ref: 'University',
required: true
},
fullPath: {
type: String,
trim: true,
required: 'Dieses Feld ist zwingend erforderlich.'
},
shortPath: {
type: String,
trim: true,
required: 'Dieses Feld ist zwingend erforderlich. Falls die Hochschule keine nennenswerte Abkürzung trägt, bitte die vollständige Studiengangsbezeichnung angeben.'
},
level: {
type: String,
enum: ['Bachelor', 'Master', 'Diplom', 'Lehramt', 'Staatsexamen'],
required: true
},
description: {
type: String,
trim: true
},
leads: {
type: Number,
trim: true,
default: 0
},
subjects: [{ type: Schema.Types.ObjectId, ref: 'Subject' }],
created: {
type: Date,
default: Date.now
},
creator: {type: Schema.Types.ObjectId, ref: 'User'},
updated: {
type: Date,
default: Date.now
},
updater: {type: Schema.Types.ObjectId, ref: 'User'}
});
//DegreeSchema.index({'subjects':1});
module.exports = mongoose.model('Degree', DegreeSchema);
|
const express = require('express');
const util = require('util');
const moment = require('moment');
const _ = require('lodash');
const router = express.Router();
const config = require('../config');
const { respondJson, respondOnError } = require('../utils/respond');
const { itemModel } = require('../model');
const resultCode = require('../utils/resultCode');
const { writeFile, createDir, createSaveFileData, deleteFile } = require('../modules/fileModule');
const { imagesTypeCheck } = require('../utils/common');
const controllerName = 'Item';
router.use((req, res, next) => {
console.log(util.format('[Logger]::[Controller]::[%sController]::[Access Ip %s]::[Access Time %s]',
controllerName,
req.ip,
moment().tz('Asia/Seoul').format('YYYY-MM-DD HH:mm:ss')
));
next();
});
router.post('/list', async (req, res) => {
try {
const { brandId } = req.body;
const options = {
where: {
brandId: brandId
}
};
return go(
options,
itemModel.find,
data => data.length >= 0
? respondJson(res, resultCode.success, data)
: respondOnError(res, resultCode.error, { desc: 'Error on find all items' })
);
} catch (error) {
return respondOnError(res, resultCode.error, error.message);
}
});
router.post('/detail', async (req, res) => {
try {
const { id } = req.body;
const options = {
where: {
id: id
}
};
return go(
options,
itemModel.findOne,
data => {
data.dataValues
? respondJson(res, resultCode.success, data.dataValues)
: respondOnError(res, resultCode.error, { desc: 'Not Found Item! Check Your URL Parameter!'})
}
);
}
catch (error) {
respondOnError(res, resultCode.error, error.message);
}
});
router.post('/create', async (req, res) => {
try {
const fileName = req.files ? req.files.image.name : false;
const { modelNumber = "미입력", category = "미정", price = 0, name, discountPrice = null, brandId = null, amount, information = null, image } = req.body;
const data = {
modelNumber: modelNumber,
category: category,
price: price,
name: name,
discountPrice: discountPrice,
brandId: brandId,
amount: amount,
information: (information instanceof Object) ? information : information ? JSON.parse(information) : null
};
if (image && image instanceof String) {
data.imageUrl = image;
}
fileName
? go(
null,
createDir,
dir => createSaveFileData(fileName, dir, brandId),
result => {
data.imagePath = result.path;
data.imageUrl = `${config.server.base_url}/assets/images/${moment().tz('Asia/Seoul').format('YYYYMMDD')}/${result.name}`;
req.files.image.name = result.name;
return req.files;
},
imagesTypeCheck,
writeFile,
_ => itemModel.create(data).catch(e => { throw e }),
result => !!result.dataValues
? respondJson(res, resultCode.success, result.dataValues)
: respondOnError(res, resultCode.error, { desc: 'Item with Image Create Fail, Check Your Parameters!' })
)
: go(
data,
insertData => itemModel.create(insertData).catch(e => { throw e }),
result => {
return !!result
? respondJson(res, resultCode.success, result)
: respondOnError(res, resultCode.error, { desc: 'Item Create Fail, Check Your Parameters!' })
}
);
} catch (error) {
respondOnError(res, resultCode.error, error.message);
}
});
router.post('/update', async (req, res) => {
try {
const fileName = req.files ? req.files.image.name : false;
const { id, modelNumber, category="미정", price = 0, name, discountPrice = null, brandId = null, amount, information = null, image } = req.body;
const options = {
where: {
id: id
},
data: {
modelNumber: modelNumber,
category: category,
price: price,
name: name,
discountPrice: discountPrice,
brandId: brandId,
amount: amount,
information: (!!information && information instanceof Object) ? information : information ? JSON.parse(information) : null
}
};
if (image && image instanceof String) {
options.data.imageUrl = image;
}
fileName
? go(
null,
_ => itemModel.find({ where: { id: id } }),
result => {
if (result[0]) {
resultData = JSON.parse(JSON.stringify(result[0]));
if (result[0].imagePath) {
deleteFile(result[0].imagePath);
}
} else{
throw new Error("No Such Data")
}
},
createDir,
dir => createSaveFileData(fileName, dir, brandId),
result => {
options.data.imagePath = result.path;
options.data.imageUrl = `${config.server.base_url}/assets/images/${moment().tz('Asia/Seoul').format('YYYYMMDD')}/${result.name}`;
req.files.image.name = result.name;
return req.files;
},
imagesTypeCheck,
writeFile,
_ => itemModel.update(options).catch(e => { throw e }),
result => result[0] > 0
? respondJson(res, resultCode.success, { desc: 'Item Update Success' })
: respondOnError(res, resultCode.error, { desc: 'Item with Image Update Fail, Check Your Parameters!' })
)
: go(
options,
options => itemModel.update(options).catch(e => { throw e }),
result => {
if (result[0] > 0) {
let options = {
where: {
id: id
}
};
return itemModel.findOne(options).catch(e => { throw e });
} else {
return false;
}
},
result => !!result && result.dataValues
? respondJson(res, resultCode.success, result.dataValues)
: respondOnError(res, resultCode.error, { desc: 'Item Update Fail, Check Your Parameters!' })
);
} catch (error) {
respondOnError(res, resultCode.error, error.message);
}
});
router.post('/delete', async (req, res) => {
try {
const { id } = req.body;
const options = {
where: {
id: id
}
};
return await go(
options,
itemModel.find,
result => {
if (result[0]) {
if (result[0].imagePath) {
deleteFile(result[0].imagePath);
};
return {
where: {
id: result[0].id
}
};
} else {
throw new Error("No Such Data")
}
},
options => itemModel.delete(options).catch(e => { throw e }),
result => {
return result > 0
? respondJson(res, resultCode.success, result)
: respondOnError(res, resultCode.error, { desc: 'Item Delete Fail, Check Your Parameters!' })
}
);
} catch (error) {
respondOnError(res, resultCode.error, error.message);
}
});
router.post('/decreseAmount', async (req, res) => {
try {
const { id, amount = 1 } = req.body;
const options = {
by: amount,
where: {
id: id
}
};
return await go(
options,
options => itemModel.decrementAmount(options).catch(e => { throw e }),
result => {
return result
? respondJson(res, resultCode.success, result)
: respondOnError(res, resultCode.error, { desc: 'Item Decrease Fail, Check Your Parameters!' })
}
);
} catch (error) {
respondOnError(res, resultCode.error, error.message);
}
});
module.exports = router;
|
//this is the source file for the StorageLocationReservationController
function getCookie(c_name) {
var c_value = document.cookie;
var c_start = c_value.indexOf(" " + c_name + "=");
if (c_start == -1) {
c_start = c_value.indexOf(c_name + "=");
}
if (c_start == -1) {
c_value = null;
} else {
c_start = c_value.indexOf("=", c_start) + 1;
var c_end = c_value.indexOf(";", c_start);
if (c_end == -1) {
c_end = c_value.length;
}
c_value = unescape(c_value.substring(c_start, c_end));
}
return c_value;
}
var mouseX;
var mouseY;
function getcords(e) {
mouseX = Event.pointerX(e);
mouseY = Event.pointerY(e);
}
Event.observe(document, 'mousemove', getcords);
function popup(msg) {
$('detailsBox').innerHTML = msg;
$('detailsBox').style.display = '';
$('detailsBox').style.top = (mouseY + 10) + 'px';
$('detailsBox').style.left = (mouseX + 10) + 'px';
}
function kill() {
$('detailsBox').innerHTML = '';
$('detailsBox').style.display = 'none';
}
var ResvPageJs = new Class.create();
ResvPageJs.prototype = {
searchRequest : {
search_callbackId : '', // the search call back id
sortingField : 'slaEnd', // the name of the sorting field
sortingDirection : 'asc', // the order of the sorting direction: asc |
// asc
pageNo : 1
// the current page number for the result
},
owner : { // the owner information of the current user for the facility
// requests
id : '',
name : '',
position : ''
},
selectRange : { // the range of shift select
startRowNo : '',
endRowNo : ''
},
refreshInfo : {
maxExeTime : 600, // the total seconds for refresh time in seconds
timer : null, // the PeriodicalExecuter
reloadPaneId : 'refreshPanel', // the html id of the reload button
refreshCallBackId : '' // the call back id of the refreshing data
},
skipCheck : false, // skips unchecking checkboxes during actions
skipQtyCheck : false,
totalRowsHoderId : '', // this is just a holder for the total rows returned
// from the searching.
resultTableId : '', // the table id of the search results
reponseHolderId : '', // the response holder for the result from ajax call
selectedRequestIds : [], // the selected request ids
resPaneWith : 700, // the width of the modalbox
delImage : '/themes/images/delete_mini.gif', // the image file path for
// delete/unreserving.
loadingImage : '/themes/images/ajax-loader.gif', // the image file path
// for loading.
openNewWindowParams : 'width=750, menubar=0, toolbar=0, status=0, scrollbars=1, resizable=1', // the
// default
// value
// for
// open
// a
// new
// window
floatHeadId : 'floatHead', // the id of the div that contains the floating
// table head
foundNewFrIds : '',// to set color for the new frs
// constructor
initialize : function(reponseHolderId, refreshTime, resultTableId,
totalRowsHolderId, getMoreResultBtnId, whHolderId, showAvailBtnId,
showRsrvdBtnId, getCommentsBtnId, sendEmailBtnId,
changeStatusBtnId, status_cancel, status_attended, ftStatus_avail,
ftStatus_transit, refreshCallBackId, takeFRBtnId, showPushBtnId,
showExtraAvailBtnId, showEmailPanelId, checkPartBtnId,
maxExecutionTime, reservationLabelBtnId, autoTake,
createTnDnBtn, showTransitNotePanelBtn,
fieldTaskEditBaseUrl, createMoveToTechBtn, showMoveToTechPanelBtn,
createWarningBtn,updateFRHatBtn
) {
this.reponseHolderId = reponseHolderId;
this.refreshInfo.maxExeTime = refreshTime;
this.resultTableId = resultTableId;
this.totalRowsHolderId = totalRowsHolderId;
this.getMoreResultBtnId = getMoreResultBtnId;
this.whHolderId = whHolderId; // the holder for default warehouse
// facility name
this.showAvailBtnId = showAvailBtnId; // the call back function id for
// show avail parts
this.showRsrvdBtnId = showRsrvdBtnId; // the call back function id for
// show rsrvd parts
this.getCommentsBtnId = getCommentsBtnId; // the call back function id
// for show comments
this.sendEmailBtnId = sendEmailBtnId; // the call back function id for
// send email
this.changeStatusBtnId = changeStatusBtnId; // the call back function id
// for cancel
this.status_cancel = status_cancel; // the cancel status for facility
// request
this.status_attended = status_attended; // the attended status for
// facility request
this.ftStatus_avail = ftStatus_avail; // the avail status for field
// task
this.ftStatus_transit = ftStatus_transit; // the transit status for
// field task
this.refreshInfo.refreshCallBackId = refreshCallBackId; // the call back
// id for
// refreshing
// the page
this.takeFRBtnId = takeFRBtnId; // the call back id for take FR
this.showPushBtnId = showPushBtnId; // the call back id for showing push
// FR panel
this.showExtraAvailBtnId = showExtraAvailBtnId; // the call back
// function id for show
// avail parts from
// other stores
this.showEmailPanelId = showEmailPanelId; // the call back function id
// for show email panel
this.checkPartBtnId = checkPartBtnId; // Checks that part is correct
// part type for request
this.maxExecutionTime = (maxExecutionTime * 1000); // max execution of
// a request
this.skipCheck = false;
this.reservationLabelBtnId = reservationLabelBtnId;
this.autoTake = autoTake;
this.createTnDnBtn = createTnDnBtn;
this.showTransitNotePanelBtn = showTransitNotePanelBtn;
this.fieldTaskEditBaseUrl = fieldTaskEditBaseUrl;
this.createMoveToTechBtn = createMoveToTechBtn;
this.showMoveToTechPanelBtn = showMoveToTechPanelBtn;
this.createWarningBtn = createWarningBtn;
this.updateFRHatBtn = updateFRHatBtn;
},
// set the owner information
setOwnerInfo : function(ownerId, ownerName, position) {
this.owner.id = ownerId;
this.owner.name = ownerName;
this.owner.position = position;
},
checkAutoTake : function(autoTake) {
var autoTake = $(autoTake);
if (autoTake != null) {
if (autoTake.checked == true) {
return true;
}
}
return false;
},
showConfirmTransitNote : function() {
var tmp = {};
tmp.request = new Prado.CallbackRequest(this.showTransitNotePanelBtn, {
'onComplete' : function(sender, parameter) {
}
});
tmp.request.setRequestTimeOut(this.maxExecutionTime);
tmp.request.dispatch();
},
preConfirmMoveToTech : function(message, createMoveToTechCallbackId) {
var tmp = {};
tmp.message=message[0].unescapeHTML();
tmp.newhtml = "<div confirmbox='confirmtake'>"
tmp.newhtml += "<b>Please confirm below:</b><br /><br />";
tmp.newhtml += tmp.message +"<br />";
tmp.newhtml += "<input type='button' newpreference='saveBtn' onclick=\"pageJs.showConfirmMoveToTech(''); return false;\" value='Proceed'>";
tmp.newhtml += "<input type='button' onclick='Modalbox.hide(); return false;' value='Cancel'>";
tmp.newhtml += "</div>";
Modalbox.show(new Element('div').update(tmp.newhtml), {
'title' : 'Confirm Taking Task',
'width' : '1000'
});
return false;
},
showConfirmMoveToTech : function(checkflag) {
var tmp = {};
tmp.me = this;
// gathering data
try {
tmp.selectedRquestIds = this.getSelectedIds();
} catch (e) {
this.showError(e);
return;
}
tmp.resultTableId = '';
if (tmp.me.checkRervedForSelected(tmp.selectedRquestIds) != "") {
tmp.errormessage = "Some of the facility requests have zero reserved parts against them!\n";
tmp.errormessage += "You must have reservations against all the requests to Move To Tech."
alert(tmp.errormessage);
} else {
tmp.request = new Prado.CallbackRequest(
this.showMoveToTechPanelBtn, {
'onComplete' : function(sender, parameter) {
try {
tmp.result = pageJs.analyzeResp();
if (checkflag) {
// confirm task with the FRs
tmp.me.preConfirmMoveToTech(tmp.result,
tmp.me.createMoveToTechBtn);
} else {
// then move to tech
tmp.me.createMoveToTech(
tmp.me.createMoveToTechBtn, true,
true);
}
} catch (e) {
this.showError(e);
return;
}
}
});
tmp.callParams = {
'selectedIds' : tmp.selectedRquestIds
};
tmp.request.setCallbackParameter(tmp.callParams);
tmp.request.setRequestTimeOut(this.maxExecutionTime);
tmp.request.dispatch();
}
},
getWarehouseDetails : function(){
var tmp = {};
tmp.me= this;
tmp.result='';
tmp.callParams = {};
tmp.request = new Prado.CallbackRequest(this.updateFRHatBtn, {
'onComplete' : function(sender, parameter) {
Modalbox.hide();
try {
tmp.result = parameter.evalJSON();
if(tmp.result.errors && tmp.result.errors.size() > 0)
throw tmp.result.errors.join('\n');
tmp.result = tmp.result.resultData;
pageJs.setOwnerInfo(tmp.result['id'], tmp.result['name'], tmp.result['position']);
} catch (e) {
this.showError(e);
return;
}
}
});
tmp.callParams['id'] = tmp.result['id'];
tmp.callParams['name'] = tmp.result['name'];
tmp.callParams['position'] = tmp.result['position'];
tmp.request.setCallbackParameter(tmp.callParams);
tmp.request.setRequestTimeOut(this.maxExecutionTime);
tmp.request.dispatch();
},
createTnDn : function(noteType, callbackId, confirm, warehouseToName, transitNoteNo) {
var tmp = {};
tmp.me = this;
// gathering data
try {
tmp.selectedRquestIds = this.getSelectedIds();
} catch (e) {
this.showError(e);
return;
}
tmp.showTransitNotePanelBtn = this.showTransitNotePanelBtn;
tmp.resultTableId = '';
if (tmp.me.checkRervedForSelected(tmp.selectedRquestIds) != "") {
tmp.errormessage = "Some of the facility requests have zero reserved parts against them!\n";
tmp.errormessage += "You must have reservations against all the requests you have selected."
alert(tmp.errormessage);
} else {
mb.showLoading('generating note (' + noteType + ')');
// send the request
tmp.request = new Prado.CallbackRequest(callbackId, {
'onComplete' : function(sender, parameter) {
Modalbox.hide();
try {
tmp.result = pageJs.analyzeResp();
if (confirm) {
pageJs.showConfirmTransitNote();
}
} catch (e) {
}
}
});
tmp.callParams = {
'selectedIds' : tmp.selectedRquestIds
};
tmp.callParams['noteType'] = noteType;
tmp.callParams['checkTransitNote'] = confirm;
tmp.callParams['warehouseToId'] = $(warehouseToName).value;
tmp.callParams['selectedTransitNoteNo'] = transitNoteNo;
tmp.request.setCallbackParameter(tmp.callParams);
tmp.request.setRequestTimeOut(this.maxExecutionTime);
tmp.request.dispatch();
}
},
createMoveToTech : function(callbackId, confirm, warehouseToName) {
var tmp = {};
var tmp2 = {};
tmp.me = this;
// gathering data
try {
tmp.selectedRquestIds = this.getSelectedIds();
} catch (e) {
this.showError(e);
return;
}
tmp.errormessage = "";
tmp.resultTableId = this.resultTableId;
tmp.showTransitNotePanelBtn = this.showTransitNotePanelBtn;
tmp.selectedRquestIds
.each(function(id) {
tmp.currentRow = $$(
'table#' + tmp.resultTableId + ' tr[requestid="'
+ id + '"]').first();
tmp.currentRow = tmp.currentRow
.down('[resultrow="reserved"]');
tmp.countReserved = tmp.currentRow
.down('[atag="reserved"]').innerHTML;
if (tmp.countReserved == 0) {
tmp.errormessage = "Some of the facility requests have zero reserved parts against them!\n";
tmp.errormessage += "You must have reservations against all the requests your moving to Tech."
}
});
if (tmp.errormessage != "") {
alert(tmp.errormessage);
} else {
mb.showLoading('moving to technician');
// send the request
tmp.request = new Prado.CallbackRequest(callbackId, {
'onComplete' : function(sender, parameter) {
Modalbox.hide();
try {
tmp.result = pageJs.analyzeResp();
} catch (e) {
this.showError(e);
return;
}
}
});
tmp.callParams = {
'selectedIds' : tmp.selectedRquestIds
};
tmp.callParams['checkMoveToTech'] = confirm;
tmp.callParams['moveToTechWarehouseToId'] = $(warehouseToName).value;
tmp.request.setCallbackParameter(tmp.callParams);
tmp.request.setRequestTimeOut(this.maxExecutionTime);
tmp.request.dispatch();
}
},
// change on title actions. Called from the dropdown list in the title of
// the result list
changeTitleAction : function(action, clickedBtn, emailCallBackId,
printPickListCallBackId, pushFTStatusCallBackId, currentUser,
takeFRCallBackId, showPushFRCallBackId, reservationLabelBtn,
autoTake, createTnDnId, createMoveToTechId) {
switch (action) {
case 'picklist': {
this.printPickList(printPickListCallBackId, clickedBtn,
currentUser, autoTake);
break;
}
case 'label': {
this.printLabel(undefined, reservationLabelBtn, autoTake);
break;
}
case 'email': {
this.email(undefined, emailCallBackId, clickedBtn);
break;
}
case 'take': {
this.takeFR(takeFRCallBackId);
break;
}
case 'push': {
this.showPushFR(showPushFRCallBackId);
break;
}
case this.status_attended:
case this.status_cancel: {
this.showChangeStatusDiv(undefined, this.changeStatusBtnId, action,
clickedBtn);
break;
}
case 'pushToAvail': {
this.pushFT(pushFTStatusCallBackId, this.ftStatus_avail);
break;
}
case 'createTransitNote': {
this.createTnDn('TN', createTnDnId, true, false, '');
break;
}
case 'createDispatchNote': {
this.createTnDn('DN', createTnDnId, true, false, '');
break;
}
case 'moveToTech': {
this.showConfirmMoveToTech(true);
break;
}
default: {
this.showError("Invalid selection for action: ".action);
}
}
},
pushFTWrapper : function(action, pushFTStatusCallBackId, requestId) {
switch (action) {
case 'pushToAvail': {
this.pushFT(pushFTStatusCallBackId, this.ftStatus_avail, requestId);
break;
}
default: {
this.showError('Please select a status');
}
}
},
// displaying the sorting directions for the selected column
displaySorting : function() {
var tmp = {};
tmp.sortingField = this.searchRequest.sortingField;
tmp.sortingDirection = this.searchRequest.sortingDirection;
// removing all existing order displays
$$('table#' + this.resultTableId + ' th b.sortOrder').each(
function(item) {
item.remove();
});
// adding back the one we wants to display
$$('table#' + this.resultTableId + ' th')
.each(
function(item) {
// display the one that we are sorting on
if (item.readAttribute('resulttableheader') !== null) {
if (item.readAttribute('resulttableheader')
.strip() === tmp.sortingField) {
if (tmp.sortingDirection === 'asc')
tmp.nextSortingDirect = '↑';
else
tmp.nextSortingDirect = '↓';
item.innerHTML += ' <b class="sortOrder">'
+ tmp.nextSortingDirect + '</b>';
}
}
});
},
// reorder from the table header
reOrder : function(field) {
var sortOrder = 'asc';
if (this.searchRequest.sortingField === $(field).readAttribute(
'resulttableheader')) {
if (this.searchRequest.sortingDirection === 'asc')
sortOrder = 'desc';
else
sortOrder = 'asc';
} else
this.searchRequest.sortingField = $(field).readAttribute(
'resulttableheader');
this.searchRequest.sortingDirection = sortOrder;
this.search(this.searchRequest.search_callbackId, true);
},
// search data, posting request to the backend
search : function(callbackId, resetResultTable) {
this.searchRequest.search_callbackId = callbackId;
try {
var tmp = {};
// clear the selected ids
this.checkAll(new Element('input', {
'type' : 'checkbox',
'checked' : false
}));// de-select all
// stop refresh
this.stopTimer();
// remove the refresh panel
if ($(this.refreshInfo.reloadPaneId) !== undefined
&& $(this.refreshInfo.reloadPaneId) !== null)
$(this.refreshInfo.reloadPaneId).remove();
// if resetResultTable is true. it's the first time for searching!
if (resetResultTable === true) {
this.searchRequest.pageNo = 1;
// blocking user inputs when searching...
mb.showLoading('searching');
// clean up the tbody
tmp.resultTableBody = $(this.resultTableId).down('tbody');
tmp.resultTableBody.select('tr').each(function(item) {
item.remove();
});
// hide floating table head
if ($(this.floatHeadId) !== null
&& $(this.floatHeadId) !== undefined)
$(this.floatHeadId).remove();
}
tmp.request = new Prado.CallbackRequest(callbackId, {
'onComplete' : function(sender, parameter) {
pageJs.postSearch()
}
});
tmp.request.setCallbackParameter({
'searchParams' : this.searchRequest
});
tmp.request.setRequestTimeOut(this.maxExecutionTime);
tmp.request.dispatch();
} catch (err) {
// console.error(err);
}
return false;
},
// get the next page result
nextPage : function() {
this.skipCheck = true;
var tmp = $(this.getMoreResultBtnId);
// stop refresh
this.stopTimer();
this.searchRequest.pageNo = this.searchRequest.pageNo + 1;
tmp.disabled = true;
tmp.writeAttribute({
'orginalvalue' : tmp.value
});
tmp.value = 'Getting results ...';
this.search(this.searchRequest.search_callbackId);
},
// load the content when scroll the windows bar
loadWhenScroll : function() {
var tmp = {};
// float the thead
tmp.resultTable = $(pageJs.resultTableId);
tmp.tableHead = tmp.resultTable.down('thead');
// load next page when scroll
tmp.topPos = $(pageJs.getMoreResultBtnId).viewportOffset()[1];
if (tmp.topPos <= 0 || $(pageJs.getMoreResultBtnId).disabled === true)
return false;
if (tmp.topPos <= (document.viewport.getHeight() - 20)) {
pageJs.nextPage();
}
},
// load the menu when scrolling
loadFormItemWhenScroll : function() {
var tmp = {};
tmp.floatHeadId = pageJs.floatHeadId;
tmp.resultTable = $(pageJs.resultTableId);
tmp.tableHead = tmp.resultTable.down('thead');
var menuheight = $('form-item').cumulativeScrollOffset();
if ($('form-item') != null
&& navigator.userAgent.indexOf('Chrome') == -1
&& $('content').getHeight() > 1500) {
if (menuheight[1] > 250) {
$('form-item').setStyle({
position : 'fixed',
top : '47px',
height : '33px',
'width' : '960px'
});
/*
* if(menuheight[1]>650) { if($(tmp.floatHeadId) === null ||
* $(tmp.floatHeadId) === undefined) { tmp.floatHead = new
* Element('div', {'id': 'floatHead', 'style': 'position:
* fixed;width: ' + $('resultList').up('div').getWidth() + 'px;
* top: 95px;'}).update("<table class='DataList'><thead>" +
* tmp.tableHead.innerHTML + "</thead></table>");
* tmp.floatHead.select('th').last().update('Back to Top');
* tmp.resultTable.up().insert({after: tmp.floatHead}); } } else {
* if($(tmp.floatHeadId) !== null && $(tmp.floatHeadId) !==
* undefined) $(tmp.floatHeadId).remove(); }
*/
} else {
$('form-item').removeAttribute('style');
if ($(tmp.floatHeadId) !== null
&& $(tmp.floatHeadId) !== undefined)
$(tmp.floatHeadId).remove();
}
} else {
// if chrome browser
if (menuheight[1] > 650) {
if ($(tmp.floatHeadId) === null
|| $(tmp.floatHeadId) === undefined) {
tmp.floatHead = new Element('div', {
'id' : 'floatHead',
'style' : 'position: fixed;width: '
+ $('resultList').up('div').getWidth()
+ 'px; top: 0;'
}).update("<table class='DataList'><thead>"
+ tmp.tableHead.innerHTML + "</thead></table>");
tmp.floatHead.select('th').last().update('Back to Top');
tmp.resultTable.up().insert({
after : tmp.floatHead
});
}
} else {
if ($(tmp.floatHeadId) !== null
&& $(tmp.floatHeadId) !== undefined)
$(tmp.floatHeadId).remove();
}
}
},
// analyze response
analyzeResp : function(sliencemode) {
var tmp = {};
tmp.resultHTML = $(this.reponseHolderId).innerHTML;
if (tmp.resultHTML.strip().empty())
return [];
try {
tmp.result = tmp.resultHTML.evalJSON();
} catch (e) {
this.showError('Invalid JSON Message!');
}
if (tmp.result.errors !== undefined && tmp.result.errors.size() > 0) {
if (sliencemode === undefined || sliencemode === false)
this.showError(tmp.result.errors);
throw tmp.result.errors.join(' ');
}
if (tmp.result.resultData !== undefined)
return tmp.result.resultData;
return [];
},
// post search: dealing with the response after searching.
postSearch : function() {
try {
var tmp = {};
// hide the searching div..
try {
Modalbox.hide();
} catch (er) {
}
;
// clear the selected ids
// this.checkAll(new Element('input',{'type': 'checkbox', 'checked':
// true}));//de-select all
// show the result table
tmp.resultTableBody = $(this.resultTableId).down('tbody');
tmp.resultTableBodyTRLength = tmp.resultTableBody.select('tr').length;
tmp.result = this.analyzeResp();
for (tmp.i = 0; tmp.i < tmp.result.length; tmp.i = tmp.i + 1) {
tmp.newRowNo = tmp.resultTableBodyTRLength + tmp.i;
tmp.newRow = this.getResultTR(tmp.result[tmp.i], tmp.newRowNo,
false);
if (tmp.newRowNo === 0)
tmp.resultTableBody.update(tmp.newRow);
else
tmp.resultTableBody.select('tr').last().insert({
after : tmp.newRow
});
}
// show sorting direction
this.displaySorting();
// if the new row number is less than total rows, display the fetch
// next button
$(this.getMoreResultBtnId).hide();
$(this.getMoreResultBtnId).disabled = true;
if (tmp.resultTableBody.getElementsBySelector('tr').size() < ($(this.totalRowsHolderId).innerHTML
.strip() * 1)) {
// reset getMoreResultBtnId
$(this.getMoreResultBtnId).disabled = false;
try {
if ($(this.getMoreResultBtnId)
.readAttribute('orginalvalue') != null) {
if ($(this.getMoreResultBtnId).readAttribute(
'orginalvalue').strip() !== '')
$(this.getMoreResultBtnId).value = $(
this.getMoreResultBtnId).readAttribute(
'orginalvalue');
}
} catch (er) {
}
$(this.getMoreResultBtnId).show();
}
// show the result table
$(this.resultTableId).up().show();
// start the timer
if (this.refreshInfo.timer === null)
this.startTimer();
} catch (err) {
}
this.skipCheck = false;
return false;
},
// get result tr
getResultTR : function(resultRow, rowNo, checked) {
var rowAttributes;
if (resultRow.status === 'cancel' || resultRow.status === 'closed'
|| resultRow.status === 'complete') {
rowAttributes = "background:#FFCCCC;";
}
if (resultRow.status === 'new') {
rowAttributes = "background:#d0f4b7;";
}
// if new rows found on refresh then
if (this.foundNewFrIds !== null) {
var frs = this.foundNewFrIds.split(',');
for ( var i = 0; i < frs.length; i++) {
if (frs[i] == resultRow.id)
rowAttributes = "background:#b7d0f4;";
}
}
var tmp = '<tr style="' + rowAttributes + '" class="resultRow '
+ (rowNo % 2 === 0 ? 'DataListItem' : 'DataListAlterItem')
+ '" requestid="' + resultRow.id + '" fieldtaskid="'
+ resultRow.fieldTaskId + '" rowno="' + rowNo + '" >';
if (checked == true) {
tmp += '<td resultrow="id"><input class="chkbox" checked type="checkbox" value="'
+ resultRow.id
+ '" onclick="pageJs.selectOneItem(this.value, this.checked, event);" title="Select this request"/></td>';
} else {
tmp += '<td resultrow="id"><input class="chkbox" type="checkbox" value="'
+ resultRow.id
+ '" onclick="pageJs.selectOneItem(this.value, this.checked, event);" title="Select this request"/></td>';
}
if (resultRow.FrCount > 1) {
var frCount = '(' + resultRow.FrCount + ')';
} else {
var frCount = '';
}
var ptHmHtml = '';
if (resultRow.ptHotMessage != '')
ptHmHtml = '<img src="/themes/images/red_flag_16.png" onmouseover="document.getElementById(\'HotMessage' + resultRow.id + '\').style.display=\'block\';" onmouseout="document.getElementById(\'HotMessage' + resultRow.id + '\').style.display=\'none\';" />' + resultRow.ptHotMessage + '<br />';
tmp += '<td resultrow="parttype">' // part code column
+ '<div>'
+ ptHmHtml.replace(/</g, "<").replace(/>/g, ">")
+ '<span resultrow="partcode" title = "PartCode">'
+ resultRow.partCode
+ '</span> - <span resultrow="requestedQty" Title="Requested Quantity">'
+ resultRow.qty
+ '</span></div>'
+ '<div><span resultrow="partname">'
+ resultRow.partName
+ '</span></div>'
+ '</td>'
+ '<td resultrow="fieldtask">' // part code column
+ '<div><a onMouseover=\'popup("'
+ resultRow.popupMessage.unescapeHTML()
+ '");\' onMouseout="kill();" resultrow="fieldtaskid" href="javascript: void(0);" onclick="'
+ "pageJs.openNewWindow('"
+ this.fieldTaskEditBaseUrl
+ resultRow.fieldTaskId
+ "'); return false;"
+ '">'
+ resultRow.fieldTaskId
+ '</a> - <span resultrow="taskstatus" title="FieldTask Status" >'
+ resultRow.taskStatus
+ '</span> <span resultrow="taskstatus" title="No Of Open Facility Request" >'
+ frCount + '</span></div>'
+ '<div><b>S: </b><span resultrow="site">' + resultRow.site
+ '</span></div>'
+ '<div><b>C: </b><span resultrow="worktype">'
+ resultRow.worktype + '</span></div>'
+ '<div><b>Z: </b><span resultrow="zoneset">'
+ resultRow.zoneset + '</span></div>'
+ '<div><b>Billable: </b><span resultrow="zoneset">'
+ resultRow.billable + '</span></div>' + '</td>';
if (resultRow.slaEnd.indexOf('CLIENT') != -1) {
tmp = tmp
+ '<td resultrow="slaend" style="font-weight:bold;color:#FF0000">'; // sla
// end
// column
} else {
tmp = tmp + '<td resultrow="slaend">'; // sla end column
}
tmp = tmp + resultRow.slaEnd;
tmp = tmp + '</td>';
var Pcolor = 'blue';
var Priority = 'P99';
var PriorityTitle = 'Priority not available';
if (resultRow.frPriority !== null) {
Priority = resultRow.frPriority['priority'];
Pcolor = resultRow.frPriority['colour'];
PriorityTitle = resultRow.frPriority['title'];
}
tmp = tmp + '<td resultrow="frpriority"><label title="Priority '+Priority+'"><font color='+Pcolor+' size="6px"><b>'+Priority+'</b></font></label></td>'; //FR Priority
tmp = tmp + '<td resultrow="availqty">'; // avail qty
if (resultRow.availQty == null) {
resultRow.availQty = 0;
}
var countGood = 0;
var countBad = 0;
if (resultRow.availQty != 0) {
var split = resultRow.availQty.split(":");
countGood = split[0];
countBad = split[1];
}
//comp avail qty
if (resultRow.compatibleAvailQty == null) {
resultRow.compatibleAvailQty = 0;
}
var countCompGood = 0;
var countCompBad = 0;
if (resultRow.compatibleAvailQty !== 0) {
var split = resultRow.compatibleAvailQty.split(":");
countCompGood = split[0];
countCompBad = split[1];
}
tmp = tmp
+ '<a href="javascript: void(0);" style="color:green;font-weight:bold" title="No. of Good Part(s)" onclick="'
+ "return pageJs.viewAvailList('" + resultRow.id + "', '"
+ this.showAvailBtnId + "',1,false);" + '" >' + countGood + '</a>';
tmp = tmp
+ '<br><a href="javascript: void(0);" style="color:red;font-weight:bold" title="No. of Not Good Part(s)" onclick="'
+ "return pageJs.viewAvailList('" + resultRow.id + "', '"
+ this.showAvailBtnId + "',0,false);" + '" >' + countBad + '</a><br>';
if(countGood*1 === 0 && (countCompGood*1 >0 || countCompBad*1 >0))
{
//start of Compatible avail qty
tmp = tmp
+ '<br>'
+ '<hr>'
+ '<br>';
tmp = tmp
+ '<a href="javascript: void(0);" style="color:green;font-weight:bold" title="No. of Compatible Good Part(s)" onclick="'
+ "return pageJs.viewAvailList('" + resultRow.id + "', '"
+ this.showAvailBtnId + "',1,true);" + '" >C-'+countCompGood*1 + '</a>';
tmp = tmp
+ '<br><a href="javascript: void(0);" style="color:red;font-weight:bold" title="No. of Compatible Not Good Part(s)" onclick="'
+ "return pageJs.viewAvailList('" + resultRow.id + "', '"
+ this.showAvailBtnId + "',0,true);" + '" >C-'+countCompBad*1 + '</a>';
//end of Compatible avail qty
}
tmp = tmp
+'</td>';
//end of avail qty
tmp = tmp
+ '<td resultrow="reserved">' // reserved qty
+ '<a href="javascript:void(0);" atag="reserved" title="No. of Reserved Part(s)" onclick="'
+ "return pageJs.viewResrvdList('" + resultRow.id + "', '"
+ this.showRsrvdBtnId + "');" + '" >';
if (resultRow.reserved !== null)
tmp = tmp + resultRow.reserved;
else
tmp = tmp + '0';
tmp = tmp + '</a></td>' + '<td resultrow="status">' // facility request
// status
+ resultRow.status;
if (resultRow.status != 'new') {
tmp = tmp + '<br>(' + resultRow.updatedFullName + ')';
}
tmp = tmp + '</td>';
tmp = tmp + '<td resultrow="statusElapsedTime">' // facility request
// Updated Elapsed
// Time
+ resultRow.updatedElapsedTime;
tmp = tmp + '</td>';
tmp = tmp
+ '<td resultrow="owner" ownerpos="'
+ resultRow.ownerPos
+ '" ownerid="'
+ resultRow.ownerId
+ '">' // facility request owner
+ '<div resultrow="ownername">'
+ resultRow.owner
+ '</div>'
+ '<a href="javascript: void(0);" onclick="pageJs.takeFR(pageJs.takeFRBtnId, '
+ resultRow.id
+ ');" style="margin: 0 10px 0 0;" title="Take this request">take</a>'
+ '<a href="javascript: void(0);" onclick="pageJs.showPushFR(pageJs.showPushBtnId, '
+ resultRow.id
+ ');" title="Push this request to somewhere else">push</a>'
+ '</td>'
+ '<td resultrow="btns">' // buttons
+ '<input type="image" resultrow="commentsBtn" src="/themes/images/comment_icon.png" onclick="'
+ "return pageJs.showComments('"
+ resultRow.id
+ "', '"
+ this.getCommentsBtnId
+ "', this);"
+ '" title="Show/Add Comments"/> '
+ '<input type="image" resultrow="emailBtn" src="/themes/images/mail.gif" onclick="'
+ "return pageJs.email('" + resultRow.id + "', '"
+ this.showEmailPanelId + "', this);"
+ '" title="Send an email"/> ';
if (resultRow.sendToWarehouseId === null)
tmp = tmp
+ '<input type="image" resultrow="deliveryLookupBtn" src="/themes/images/history_disabled.gif" onclick="'
+ "pageJs.openNewWindow('/partdeliverylookup'); return false;"
+ '" title="set a delivery look reference"/> ';
tmp = tmp + '<input resultrow="cancelBtn" type="image" src="'
+ this.delImage + '" onclick="'
+ "pageJs.showChangeStatusDiv('" + resultRow.id + "', '"
+ this.changeStatusBtnId + "', '" + this.status_cancel
+ "', this); return false;"
+ '" title="cancelling the current request" style="';
if (resultRow.cancelable === false)
tmp = tmp + 'display: none;';
tmp = tmp + '" />';
tmp = tmp
+ '<input resultrow="reopenBtn" type="image" src="/themes/images/big_yes.gif" onclick="'
+ "pageJs.showChangeStatusDiv('" + resultRow.id + "', '"
+ this.changeStatusBtnId + "', '" + this.status_attended
+ "', this); return false;"
+ '" title="reopening the current request" style="';
if (resultRow.reopenable === false)
tmp = tmp + 'display: none;';
tmp = tmp + '" />';
tmp = tmp
+ '<input type="image" src="/themes/images/print.png" onclick="'
+ " pageJs.printLabel('"
+ resultRow.id
+ "', '"
+ this.reservationLabelBtnId
+ "', '"
+ this.autoTake
+ "');return false;"
+ '" title="Print Label For Rsvd / PickList" style="margin: 0 0 0 5px;" />';
tmp = tmp + '</td>';
+'</tr>';
return tmp;
},
printLabel : function(requestId, callbackId, autoTake) {
// gathering data
var tmp = {};
tmp.pageBody = '';
try {
tmp.selectedRquestIds = this.getSelectedIds(requestId);
} catch (e) {
this.showError(e);
return;
}
tmp.getBrowser = this.getBrowser();
tmp.resultTableId = this.resultTableId;
tmp.reponseHolderId = this.reponseHolderId;
tmp.openNewWindowParams = this.openNewWindowParams;
// gathering data
tmp._newLine = '<br>';
// show UI for disabled printing Btn, once btn clicked
mb.showLoading('generating the reservation label');
// send the request
tmp.request = new Prado.CallbackRequest(
callbackId,
{
'onComplete' : function(sender, parameter) {
try {
Modalbox.hide();
var ob = $(tmp.reponseHolderId).innerHTML
.evalJSON();
tmp.pageBody = '';
ob
.each(function(value, index) {
tmp.currentRow = $$(
'table#' + tmp.resultTableId
+ ' tr[requestid="'
+ ob[index]['fr']
+ '"]').first();
tmp.pageBody += tmp._newLine;
tmp.pageBody += tmp._newLine;
tmp.pageBody += tmp._newLine;
tmp.pageBody += tmp._newLine;
tmp.pageBody += tmp._newLine;
tmp.pageBody += tmp._newLine;
tmp.pageBody += tmp._newLine;
tmp.pageBody += tmp._newLine;
tmp.pageBody += tmp._newLine;
tmp.pageBody += tmp._newLine;
tmp.pageBody += tmp._newLine;
tmp.pageBody += tmp._newLine;
tmp.pageBody += tmp._newLine;
tmp.pageBody += 'FACILITY REQUEST'
+ tmp._newLine;
tmp.pageBody += '<br>'
+ Barcode
.DrawCode39Barcode(
tmp.currentRow
.down('[resultrow="fieldtaskid"]').innerHTML,
0)
+ tmp._newLine;
if (ob[index]['shipTo'] != null) {
tmp.pageBody += '<b>SHIP TO:</b><br /> '
+ ob[index]['shipTo'].replace(/</g, "<").replace(/>/g, ">")
+ tmp._newLine;
}
tmp.pageBody += '<br><b>FIELD TASK: '
+ tmp.currentRow
.down('[resultrow="fieldtaskid"]').innerHTML
+ '</b>' + tmp._newLine;
tmp.pageBody += '<b>SITE: '
+ tmp.currentRow
.down('[resultrow="site"]').innerHTML
+ '</b>' + tmp._newLine;
tmp.pageBody += '<b>CONTRACT: '
+ tmp.currentRow
.down('[resultrow="worktype"]').innerHTML
+ '</b>' + tmp._newLine;
tmp.pageBody += '<b>ZONE SET: '
+ tmp.currentRow
.down('[resultrow="zoneset"]').innerHTML
+ '</b>' + tmp._newLine;
tmp.pageBody += 'SLA END: '
+ tmp.currentRow
.down('[resultrow="slaend"]').innerHTML
+ tmp._newLine;
tmp.pageBody += 'PART: '
+ tmp.currentRow
.down('[resultrow="partname"]').innerHTML
+ tmp._newLine;
tmp.pageBody += 'PART CODE: <b>'
+ tmp.currentRow
.down('[resultrow="partcode"]').innerHTML
+ '</b>' + tmp._newLine;
tmp.pageBody += 'REQUESTED Qty: '
+ tmp.currentRow
.down('[resultrow="requestedQty"]').innerHTML
+ tmp._newLine;
if (ob[index]['location'] != null) {
tmp.pageBody += 'LOCATION: '
+ ob[index]['location']
+ tmp._newLine;
}
if (ob[index]['comment'] != null) {
tmp.pageBody += 'COMMENT: '
+ ob[index]['comment']
+ tmp._newLine;
}
tmp.pageBody += tmp._newLine
+ '------------------------------------------------------------------------------------------------------';
tmp.pageBody += tmp._newLine
+ '</br></br>';
if (index < ob.length - 1) {
tmp.pageBody += '<hr style="page-break-after:always; visibility: hidden">';
}
});
var win = window.open('', '',
tmp.openNewWindowParams);
win.document
.writeln('<html><head><title>Facility Request </title></head>'
+ '<body>'
+ tmp.pageBody
+ '</body></html>');
win.window.print();
win.document.close();
pageJs.updateListForAutoTake(autoTake,
tmp.selectedRquestIds);
} catch (er) {
}
}
});
tmp.request.setCallbackParameter({
'selectedIds' : tmp.selectedRquestIds
});
tmp.request.setRequestTimeOut(this.maxExecutionTime);
tmp.request.dispatch();
},
// show the error message
showError : function(msgArray) {
if (msgArray === null || typeof (msgArray) === "undefined"
|| msgArray === undefined) {
alert('Not a Valid Action. Please try again.');
} else {
if (typeof msgArray === 'object')
alert(msgArray);
else
alert(msgArray.stripTags());
}
},
// selecting all the items on the page.
checkAll : function(checkBox) {
if (!this.skipCheck) {
var tmp = {};
tmp.resultTable = $$('table#' + this.resultTableId).first();
tmp.checkboxes = tmp.resultTable
.select('td[resultrow="id"] input.chkbox');
for (tmp.i = 0; tmp.i < tmp.checkboxes.size(); tmp.i = tmp.i + 1) {
if (tmp.checkboxes[tmp.i].disabled !== true)
this.selectOneItem(tmp.checkboxes[tmp.i].value,
checkBox.checked);
}
// check or uncheck the first one on the table header
tmp.resultTable.getElementsBySelector('thead input.chkbox').first().checked = checkBox.checked;
}
},
// select one item; selected = true: select that item; otherwise, it's a
// de-selecting action
selectOneItem : function(requestId, selected, event) {
var tmp = {};
tmp.selectedRow = $(this.resultTableId).down(
'tr[requestid="' + requestId + '"]');
tmp.selectedRow.down('td[resultrow="id"] input.chkbox').checked = selected;
tmp.rowNo = tmp.selectedRow.readAttribute('rowno').strip();
// shift select range
if (event !== undefined && event.shiftKey === true
&& !this.selectRange.startRowNo.empty()) {
this.selectRange.endRowNo = tmp.rowNo;
for (tmp.i = this.selectRange.startRowNo * 1; tmp.i <= this.selectRange.endRowNo * 1; tmp.i = tmp.i + 1) {
try {
tmp.requestId = $(this.resultTableId).down(
'tr[rowno="' + tmp.i + '"]').readAttribute(
'requestid').strip();
this.selectOneItem(tmp.requestId, selected);
} catch (er) {
}
}
this.selectRange.startRowNo = this.selectRange.endRowNo = '';
return;
}
this.selectRange.startRowNo = tmp.rowNo;
if (selected === true) // select
this.selectedRequestIds.push(requestId);
else // de-select
{
tmp.newSelectedIds = [];
this.selectedRequestIds.each(function(id) {
if (id !== requestId)
tmp.newSelectedIds.push(id);
});
this.selectedRequestIds = tmp.newSelectedIds;
}
},
// view avail/compatible avail parts list
viewAvailListOtherStores : function(requestId, callbackId, goodParts, compatibleParts) {
var tmp = {};
// gathering data
try {
tmp.selectedRquestIds = requestId;
} catch (e) {
this.showError(e);
return;
}
if(compatibleParts)
mb.showLoading('getting the compatible available parts list');
else
mb.showLoading('getting the available parts list');
tmp.request = new Prado.CallbackRequest(callbackId, {
'onComplete' : function(sender, parameter) {
pageJs.showAvailListOtherStores(goodParts, compatibleParts);
}
});
tmp.callParams = {
'selectedIds' : tmp.selectedRquestIds
};
tmp.callParams['otherStores'] = true;
tmp.callParams['goodParts'] = goodParts;
tmp.callParams['compatibleParts'] = compatibleParts;
tmp.request.setCallbackParameter(tmp.callParams);
tmp.request.setRequestTimeOut(this.maxExecutionTime);
tmp.request.dispatch();
},
// display the avail list in Modalbox
showAvailListOtherStores : function(goodParts) {
var type = '';
if (goodParts == 1) {
type = '(Good) ';
} else {
type = '(Not Good) ';
}
Modalbox.show(new Element('div')
.update($(this.reponseHolderId).innerHTML), {
beforeLoad : function() {
Modalbox.activate();
},
title : type + 'Part(s) in Other Locations',
width : pageJs.resPaneWith
});
},
// view avail/compatible avail parts list
viewAvailList : function(requestId, callbackId, goodParts, compatibleParts) {
var tmp = {};
// gathering data
try {
tmp.selectedRquestIds = requestId;
} catch (e) {
this.showError(e);
return;
}
if(compatibleParts)
mb.showLoading('getting the compatible available parts list');
else
mb.showLoading('getting the available parts list');
tmp.request = new Prado.CallbackRequest(callbackId, {
'onComplete' : function(sender, parameter) {
if(compatibleParts)
pageJs.showAvailList(goodParts,'Compatible');
else
pageJs.showAvailList(goodParts,'');
}
});
tmp.callParams = {
'selectedIds' : tmp.selectedRquestIds
};
tmp.callParams['goodParts'] = goodParts;
tmp.callParams['compatibleParts'] = compatibleParts;
tmp.request.setCallbackParameter(tmp.callParams);
tmp.request.setRequestTimeOut(this.maxExecutionTime);
tmp.request.dispatch();
},
// display the avail list in Modalbox
showAvailList : function(goodParts,prefix) {
var type = '';
if (goodParts == 1) {
type = '(Good) ';
} else {
type = '(Not Good) ';
}
Modalbox
.show(
new Element('div')
.update($(this.reponseHolderId).innerHTML),
{
beforeLoad : function() {
Modalbox.activate();
},
title : type
+ prefix +' Part(s) in '
+ $(this.whHolderId).options[$(this.whHolderId).selectedIndex].text
+ ': ',
width : pageJs.resPaneWith
});
},
// view Resrvd parts list
viewResrvdList : function(requestId, callbackId) {
var tmp = {};
// gathering data
try {
tmp.selectedRquestIds = this.getSelectedIds(requestId);
} catch (e) {
this.showError(e);
return;
}
mb.showLoading('getting reserved parts list');
tmp.request = new Prado.CallbackRequest(callbackId, {
'onComplete' : function(sender, parameter) {
pageJs.showResrvdList()
}
});
tmp.request.setCallbackParameter({
'selectedIds' : tmp.selectedRquestIds
});
tmp.request.setRequestTimeOut(this.maxExecutionTime);
tmp.request.dispatch();
},
// display the Resrvd list in Modalbox
showResrvdList : function() {
var tmp = {};
Modalbox.show(new Element('div')
.update($(this.reponseHolderId).innerHTML), {
beforeLoad : function() {
Modalbox.activate();
},
title : 'Reserved Part(s) for selected request:',
width: 700
});
},
// search for part instance to reserve
reservePI : function(requestId, callbackId, unsrvCallbackId, clickedBtn,
callbackIdCheck, checkPartType, checkPartErrors, errorBL) {
var tmp = {};
// gathering data
try {
tmp.selectedRquestIds = this.getSelectedIds(requestId);
} catch (e) {
this.showError(e);
return;
}
// getting the new tr with elements
tmp.resrvInfo = {};
tmp.resrvNewPartTR = $(clickedBtn).up('tr[resrpartpan="reservedTr"]');
tmp.resrvNewPartBarcode = tmp.resrvNewPartTR
.down('input[resrpartpan="reservedSerialNoSearch"]');
tmp.resrvNewPartBL = tmp.resrvNewPartTR
.down('input[resrpartpan="reservedBLNoSearch"]');
tmp.resrvComments = tmp.resrvNewPartTR
.down('input[resrpartpan="reservedComments"]');
tmp.resrvNewPartQty = tmp.resrvNewPartTR
.down('input[resrpartpan="reservedQty"]');
tmp.bpregex = new RegExp(tmp.resrvNewPartTR
.down('input[resrpartpan="bpregex"]').value.strip());
tmp.partregex = new RegExp(tmp.resrvNewPartTR
.down('input[resrpartpan="partregex"]').value.strip());
// forming up the information
tmp.resrvInfo.barcode = tmp.resrvNewPartBarcode.value.strip();
tmp.resrvInfo.BL = tmp.resrvNewPartBL.value.strip();
tmp.resrvInfo.comments = tmp.resrvComments.value.strip();
tmp.resrvInfo.qty = tmp.resrvNewPartQty.value;
if (!tmp.resrvInfo.qty.match(/^\d+$/)) {
tmp.resrvNewPartQty.focus();
this.showError('Invalid qty!');
return;
}
//if BP and no BL then focus on BL
tmp.barcode = tmp.resrvInfo.barcode;
if(tmp.barcode.match(/BP|BCP/i) != "" && tmp.barcode.match(/BP|BCP/i) !== null)
{
if(tmp.resrvInfo.BL === '' || tmp.resrvInfo.BL === null)
{
tmp.resrvNewPartBL.focus();
this.skipQtyCheck=false;
return false;
}
else
{
if(!this.skipQtyCheck)
{
this.skipQtyCheck=true;
tmp.resrvNewPartQty.focus();
return false;
}
}
}
// check barcode to see whether it's a valid part barcode or parttype
// barcode
if (tmp.resrvInfo.barcode.match(tmp.partregex) === null) {
tmp.resrvNewPartBarcode.value = '';
tmp.resrvNewPartBarcode.focus();
this.showError('Invalid barcode(= ' + tmp.resrvInfo.barcode + ')!');
return;
}
$(clickedBtn).disabled = true;
$(clickedBtn).value = 'reserving...';
var process = false;
tmp.request = new Prado.CallbackRequest(callbackIdCheck, {
'onComplete' : function(sender, parameter) {
process = true;
if($(errorBL).value != "")
{
process = false;
alert($(errorBL).value);
$(clickedBtn).disabled = false;
$(clickedBtn).value = 'Add';
tmp.resrvNewPartBL.focus();
}
if(process)
{
if($(checkPartErrors).value != "")
{
process = false;
$(clickedBtn).disabled = false;
$(clickedBtn).value = 'Add';
alert($(checkPartErrors).value);
}
}
if(process)
{
if($(checkPartType).value != '')
{
process = false;
$(clickedBtn).disabled = false;
$(clickedBtn).value = 'Add';
if(confirm($(checkPartType).value)) {
process = true;
}
}
}
if (process) {
// disable serial number input field
$(clickedBtn).disabled = true;
tmp.clickedBtnValue = $(clickedBtn).value;
$(clickedBtn).value = 'reserving...';
tmp.resrvNewPartBarcode.disabled = true;
tmp.resrvNewPartQty.disabled = true;
// cleanup
tmp.resrvNewPartBarcode.value = '';
tmp.resrvNewPartQty.value = '1';
// send the request
Modalbox.deactivate(); // deactive the ui
tmp.request = new Prado.CallbackRequest(callbackId, {
'onComplete' : function(sender, parameter) {
$(clickedBtn).value = tmp.clickedBtnValue;
$(clickedBtn).disabled = false;
tmp.resrvNewPartBarcode.disabled = false;
tmp.resrvNewPartQty.disabled = false;
Modalbox.activate();
pageJs.updateRsrvdPartList(requestId,
tmp.resrvNewPartTR.up(), unsrvCallbackId);
tmp.resrvNewPartBarcode.focus();
}
});
tmp.request.setCallbackParameter({
'selectedIds' : tmp.selectedRquestIds,
'resrvInfo' : tmp.resrvInfo
});
tmp.request.dispatch();
}
}
});
tmp.request.setCallbackParameter({
'selectedIds' : tmp.selectedRquestIds,
'resrvInfo' : tmp.resrvInfo
});
tmp.request.setRequestTimeOut(this.maxExecutionTime);
tmp.request.dispatch();
},
// post script for reservePI function
updateRsrvdPartList : function(requestId, tbody, unsrvCallbackId) {
var tmp = {};
// if there is no data return, assume the results contains error!
try {
tmp.result = this.analyzeResp();
} catch (e) {
return;
}
// udpate the result List
if (tmp.result.requests !== undefined) {
tmp.result.requests.each(function(request) {
pageJs.reloadRow(request.id, request, false);
});
}
this.viewResrvdList(requestId, this.showRsrvdBtnId);
},
// reapply the css style to result table, so they will look like zebra style
resApplyClassName : function(tbody) {
var tmp = {};
tmp.tbody = tbody;
tmp.i = 0;
tmp.tbody.select('tr').each(function(item) {
// removes the original class name
item.removeClassName(tmp.trClass);
if (tmp.i % 2 === 0)
tmp.trClass = 'ResultDataListAlterItem';
else
tmp.trClass = 'ResultDataListItem';
item.removeClassName(tmp.trClass);
// add the new classname
item.addClassName(tmp.trClass);
tmp.i++;
});
},
// unreserve pi
unresrvPI : function(requestId, callbackId, clickedBtn) {
var tmp = {};
// gathering data
try {
tmp.selectedRquestIds = this.getSelectedIds(requestId);
} catch (e) {
this.showError(e);
return;
}
$(clickedBtn).disabled = true;
$(clickedBtn).src = this.loadingImage;
tmp.delImage = this.delImage;
tmp.resrvNewPartTR = $(clickedBtn).up('tr');
tmp.unResrvInfo = {};
tmp.unResrvInfo.piId = tmp.resrvNewPartTR.readAttribute('rsvdpiid');
tmp.unResrvInfo.comment = prompt(
"Please provide reason for unreserving this part",
"");
if (tmp.unResrvInfo.comment === null) {
$(clickedBtn).src = tmp.delImage;
$(clickedBtn).disabled = false;
return false;
}
tmp.unResrvInfo.comment = tmp.unResrvInfo.comment.strip();
if (tmp.unResrvInfo.comment.empty()) {
this.showError("Please provide reason for unreserving this part");
$(clickedBtn).src = tmp.delImage;
$(clickedBtn).disabled = false;
return false;
}
// send the request
tmp.request = new Prado.CallbackRequest(callbackId, {
'onComplete' : function(sender, parameter) {
$(clickedBtn).src = tmp.delImage;
$(clickedBtn).disabled = false;
pageJs.updateRsrvdPartList(requestId, tmp.resrvNewPartTR.up());
}
});
tmp.request.setCallbackParameter({
'selectedIds' : tmp.selectedRquestIds,
'unResrvInfo' : tmp.unResrvInfo
});
tmp.request.setRequestTimeOut(this.maxExecutionTime);
tmp.request.dispatch();
},
// scanBarcode do click button for barcode scanning
enterEvent : function(event, buttonToClick) {
if ((event.which && event.which == 13)
|| (event.keyCode && event.keyCode == 13)) {
buttonToClick.click();
return false;
}
return true;
},
updateListForAutoTake : function(autoTake, selectedRequestIds) {
var tmp = {};
if (pageJs.checkAutoTake(autoTake)) {
tmp.request = new Prado.CallbackRequest(
pageJs.refreshInfo.refreshCallBackId, {
'onComplete' : function(sender, parameter) {
try {
tmp.result = pageJs.analyzeResp();
tmp.result.requests
.each(function(request) {
pageJs.reloadRow(request.id,
request, true);
});
} catch (er) {
}
}
});
tmp.request.setCallbackParameter({
'ids' : selectedRequestIds,
'firstid' : '',
'searchRequest' : pageJs.searchRequest
});
tmp.request.dispatch();
}
},
// click event for print pick list
printPickList : function(callbackId, clickedBtn, currentUser, autoTake) {
var tmp = {};
// gathering data
tmp.selectedRquestIds = this.selectedRequestIds;
// check if selected any
if (tmp.selectedRquestIds.length === 0) {
this.showError('Please select some items first!');
return;
}
// show UI for disabled printing Btn, once btn clicked
mb.showLoading('generating pick list');
// send the request
tmp.request = new Prado.CallbackRequest(callbackId, {
'onComplete' : function(sender, parameter) {
// open the new window for printing
pageJs.writeConsole('Pick List For Selected Request(s) - By '
+ currentUser, $(pageJs.reponseHolderId).innerHTML);
Modalbox.hide();
pageJs.updateListForAutoTake(autoTake, tmp.selectedRquestIds);
}
});
tmp.request.setCallbackParameter({
'selectedIds' : this.selectedRequestIds
});
tmp.request.setRequestTimeOut(this.maxExecutionTime);
tmp.request.dispatch();
},
// writes a content to a new open widow
writeConsole : function(title, content) {
var top = {};
top.consoleRef = this.openNewWindow('', 'newWindow',
this.openNewWindowParams);
top.consoleRef.document.writeln('<html><head><title>' + title
+ '</title></head>' + '<body>' + content + '</body></html>');
top.consoleRef.document.close();
},
// open part delivery lookup page
openNewWindow : function(url, title, params) {
if (params === undefined)
params = this.openNewWindowParams;
params = '';
var tmp = window.open(url, title, params);
if (tmp.focus) {
tmp.focus();
}
return tmp;
},
// show comments div
showComments : function(requestId, callbackId, clickedbtn) {
var tmp = {};
// gathering data
try {
tmp.selectedRquestIds = this.getSelectedIds(requestId);
} catch (e) {
this.showError(e);
return;
}
mb.showLoading('getting comments for the selected request');
tmp.request = new Prado.CallbackRequest(callbackId, {
'onComplete' : function(sender, parameter) {
try {
Modalbox.show(new Element('div')
.update($(pageJs.reponseHolderId).innerHTML), {
beforeLoad : function() {
Modalbox.activate();
},
title : 'Comments for selected request',
width : pageJs.resPaneWith
});
} catch (e) {
}
}
});
tmp.request.setCallbackParameter({
'selectedIds' : tmp.selectedRquestIds
});
tmp.request.setRequestTimeOut(this.maxExecutionTime);
tmp.request.dispatch();
return false;
},
// submit new comments
sumbmitNewComments : function(requestId, callbackId, clickedBtn) {
var tmp = {};
tmp.selectedRquestIds = [];
tmp.selectedRquestIds.push(requestId);
// disabled the clicked button
$(clickedBtn).disabled = true;
tmp.clickedBtnValue = $(clickedBtn).value;
$(clickedBtn).value = 'adding ...';
// capture the new comments users typed in
tmp.commentsDiv = $(clickedBtn).up('div[detailspanel="detailspanel"]');
tmp.newCommentHolder = tmp.commentsDiv
.down('[detailsPanel="newComments"]');
tmp.newComment = tmp.newCommentHolder.value.strip();
if (tmp.newComment.empty()) {
this.showError('Empty comments NOT allow!');
$(clickedBtn).disabled = false;
$(clickedBtn).value = tmp.clickedBtnValue;
return false;
}
tmp.request = new Prado.CallbackRequest(callbackId, {
'onComplete' : function(sender, parameter) {
$(clickedBtn).disabled = false;
$(clickedBtn).value = tmp.clickedBtnValue;
pageJs.updateCommentsList(tmp.commentsDiv
.down('table[detailspanel="commentsList"]'));
}
});
tmp.request.setCallbackParameter({
'selectedIds' : tmp.selectedRquestIds,
'newComment' : tmp.newComment
});
tmp.request.setRequestTimeOut(this.maxExecutionTime);
tmp.request.dispatch();
tmp.newCommentHolder.value = '';
return false;
},
// post adding new comments
updateCommentsList : function(commentsTable) {
var tmp = {};
tmp.tbody = commentsTable.down('tbody');
try {
tmp.result = this.analyzeResp();
} catch (e) {
return this.showError(e);
}
tmp.lastRow = tmp.tbody.getElementsBySelector('tr').first();
tmp.newRowClassName = 'ResultDataListItem';
if (tmp.lastRow.hasClassName(tmp.newRowClassName))
tmp.newRowClassName = 'ResultDataListAlterItem';
tmp.newRow = '<tr class="' + tmp.newRowClassName + '"><td>'
+ tmp.result.user + '</td><td>' + tmp.result.time + '</td><td>'
+ tmp.result.comment + '</td></tr>';
tmp.lastRow.insert({
before : tmp.newRow
});
Modalbox.resizeToContent();
// update the result list
if (tmp.result.requests !== undefined && tmp.result.requests.size() > 0)
tmp.result.requests.each(function(resultRow) {
pageJs.reloadRow(resultRow.id, resultRow, false);
});
},
// sendEmail
email : function(requestId, callbackId, clickedBtn) {
var tmp = {};
tmp.emailTo_newLine = '\n';
tmp.resultTableId = this.resultTableId;
// if there is a id passed in, it means it was called from the email
// button from each line item.
// gathering data
try {
tmp.selectedRquestIds = this.getSelectedIds(requestId);
} catch (e) {
this.showError(e);
return;
}
// gathering data
tmp.emailBody = tmp.emailTo_newLine;
tmp.rowNo = 1;
var tasksSelected = '';
tmp.selectedRquestIds
.each(function(id) {
tmp.currentRow = $$(
'table#' + tmp.resultTableId + ' tr[requestid="'
+ id + '"]').first();
tmp.emailSubject = 'Task: '
+ tmp.currentRow.down('[resultrow="fieldtaskid"]').innerHTML
+ ' Requires Part Code: '
+ tmp.currentRow.down('[resultrow="partcode"]').innerHTML
+ ' Qty: '
+ tmp.currentRow.down('[resultrow="requestedQty"]').innerHTML;
if (tasksSelected != '') {
tasksSelected += ", "
+ tmp.currentRow
.down('[resultrow="fieldtaskid"]').innerHTML;
} else {
tasksSelected += tmp.currentRow
.down('[resultrow="fieldtaskid"]').innerHTML;
}
tmp.emailBody += tmp.emailTo_newLine;
tmp.emailBody += '== REQUEST NO.: ' + tmp.rowNo
+ '====================' + tmp.emailTo_newLine;
tmp.emailBody += 'PART: '
+ tmp.currentRow.down('[resultrow="partname"]').innerHTML
+ tmp.emailTo_newLine;
tmp.emailBody += 'PART CODE: '
+ tmp.currentRow.down('[resultrow="partcode"]').innerHTML
+ tmp.emailTo_newLine;
tmp.emailBody += 'REQUESTED Qty: '
+ tmp.currentRow.down('[resultrow="requestedQty"]').innerHTML
+ tmp.emailTo_newLine;
tmp.emailBody += 'FIELD TASK: '
+ tmp.currentRow.down('[resultrow="fieldtaskid"]').innerHTML
+ tmp.emailTo_newLine;
tmp.emailBody += 'SLA END: '
+ tmp.currentRow.down('[resultrow="slaend"]').innerHTML
+ tmp.emailTo_newLine;
tmp.emailBody += 'SITE: '
+ tmp.currentRow.down('[resultrow="site"]').innerHTML
+ tmp.emailTo_newLine;
tmp.emailBody += 'CONTRACT: '
+ tmp.currentRow.down('[resultrow="worktype"]').innerHTML
+ tmp.emailTo_newLine;
tmp.emailBody += 'ZONE SET: '
+ tmp.currentRow.down('[resultrow="zoneset"]').innerHTML
+ tmp.emailTo_newLine;
tmp.emailBody += '===================='
+ tmp.emailTo_newLine;
tmp.rowNo++;
});
if (tmp.rowNo > 2) {
tmp.emailSubject = "Multiple Facility Requests for Tasks: "
+ tasksSelected;
}
Modalbox.hide();
tmp.request = new Prado.CallbackRequest(callbackId);
tmp.callParams = {
'selectedIds' : tmp.selectedRquestIds
};
tmp.callParams['body'] = tmp.emailBody;
tmp.callParams['subject'] = tmp.emailSubject;
tmp.request.setCallbackParameter(tmp.callParams);
tmp.request.setRequestTimeOut(this.maxExecutionTime);
tmp.request.dispatch();
return false;
},
// show the status changing Div
showChangeStatusDiv : function(requestId, callbackId, newstatus, clickedBtn) {
var tmp = {};
// if there is a id passed in, it means it was called from the email
// button from each line item.
// gathering data
try {
tmp.selectedRquestIds = this.getSelectedIds(requestId);
} catch (e) {
this.showError(e);
return;
}
// checking ownership
tmp.errors = [];
tmp.selectedRquestIds
.each(function(id) {
tmp.ownerPos = $(pageJs.resultTableId).down(
'tr[requestid=' + id + '] td[resultrow="owner"]')
.readAttribute('ownerPos').strip();
tmp.ftStatus = $(pageJs.resultTableId).down(
'tr[requestid=' + id + ']').down(
'[resultrow="taskstatus"]').innerHTML;
if (!tmp.ownerPos.startsWith(pageJs.owner.position.strip())) {
tmp.emsg = '<div>';
tmp.emsg += "<a href='javascript: void(0);' onclick=\"$$('tr[requestid="
+ id
+ "]').first().scrollTo(); return false;\" title='Click here to scroll to that request'>Request</a>: ";
tmp.emsg += 'You do NOT have access to this request, take it before you do anything!';
tmp.emsg += '</div>';
tmp.errors.push(tmp.emsg)
}
});
if (tmp.errors.size() > 0)
Modalbox.show(new Element('div').update(tmp.errors.join(''))
.setStyle({
'color' : 'red',
'font-weight' : 'bold'
}), {
afterLoad : function() {
Modalbox.resizeToContent();
},
title : 'Error Occurred ... ',
width : pageJs.resPaneWith
});
else {
if (newstatus == 'cancel') {
var confirmation = confirm('This task is in status '
+ tmp.ftStatus
+ ' .\nAre you sure you want to cancel this Facility Request?.\n\n');
if (confirmation)
this
.showComfirmDiv(
'Please provide a reason for changing the status to: '
+ newstatus,
"if($(this).up('div[commentdiv=commentdiv]').down('[commentdiv=comments]').value.strip().empty()){alert('Comments is compulsory!');return false;} pageJs.submitEachRequest(0, '"
+ tmp.selectedRquestIds.join(',')
+ "', '"
+ callbackId
+ "', Object.toJSON({comment: $(this).up('div[commentdiv=commentdiv]').down('[commentdiv=comments]').value.strip(), newStatus: '"
+ newstatus + "'}))");
} else
this
.showComfirmDiv(
'Please provide a reason for changing the status to: '
+ newstatus,
"if($(this).up('div[commentdiv=commentdiv]').down('[commentdiv=comments]').value.strip().empty()){alert('Comments is compulsory!');return false;} pageJs.submitEachRequest(0, '"
+ tmp.selectedRquestIds.join(',')
+ "', '"
+ callbackId
+ "', Object.toJSON({comment: $(this).up('div[commentdiv=commentdiv]').down('[commentdiv=comments]').value.strip(), newStatus: '"
+ newstatus + "'}))");
}
},
// submit each id
submitEachRequest : function(currentIndex, ids, callbackId, info, errors) {
var tmp = {};
tmp.callbackId = callbackId;
tmp.requestIds = ids.split(',');
if (tmp.requestIds.size() === 0)
return this.showError("select some request(s) first!");
tmp.info = Object.toJSON({});
if (info !== undefined)
tmp.info = info;
tmp.errors = [];
if (errors !== undefined)
tmp.errors = errors;
// show the processing div
if (currentIndex === 0) {
tmp.newDiv = '<div processingdiv="processingdiv">Processing <b processingdiv="processingindex">1</b> of <b processingdiv="totalrequestcout">'
+ tmp.requestIds.size() + '</b></div>';
Modalbox.show(new Element('div').update(tmp.newDiv), {
beforeLoad : function() {
Modalbox.deactivate();
},
title : 'Processing request(s) ... ',
width : pageJs.resPaneWith
});
}
tmp.currentRequestId = [];
tmp.currentRequestId.push(tmp.requestIds[currentIndex]);
tmp.request = new Prado.CallbackRequest(callbackId, {
'onComplete' : function(sender, parameter) {
tmp.errors = pageJs.postSubmitEachRequest(currentIndex, ids,
callbackId, info, tmp.errors);
}
});
tmp.request.setCallbackParameter({
'selectedIds' : tmp.currentRequestId,
'info' : tmp.info.evalJSON(),
'retainSelectedIds' : tmp.currentRequestId
});
tmp.request.setRequestTimeOut(this.maxExecutionTime);
tmp.request.dispatch();
},
// postsumbit each request
postSubmitEachRequest : function(currentIndex, ids, callbackId, info,
errors) {
var tmp = {};
tmp.info = info;
tmp.requestIds = ids.split(',');
tmp.callbackId = callbackId;
tmp.info = info;
tmp.errors = errors;
// update the result list with new data
try {
tmp.result = this.analyzeResp(true);
if (tmp.result.requests !== undefined) {
tmp.result.requests.each(function(request) {
pageJs.reloadRow(request.id, request, true);
});
}
} catch (e) {
tmp.errors.push({
'requestId' : tmp.requestIds[currentIndex],
'emsg' : e
});
}
// if we have more to run, we run for the next one
if ((currentIndex * 1) < (tmp.requestIds.size() - 1)) {
tmp.processingIndexDiv = $$(
'div[processingdiv="processingdiv"] [processingdiv="processingindex"]')
.first();
if (tmp.processingIndexDiv !== undefined
&& tmp.processingIndexDiv !== null)
tmp.processingIndexDiv.update((currentIndex * 1) + 1);
this.submitEachRequest((currentIndex * 1) + 1, tmp.requestIds
.join(','), tmp.callbackId, tmp.info, tmp.errors);
}
// display the end result, when it's all finished
else {
tmp.newDiv = '<b style="color: green;"> Updated successfully! </b>';
if (tmp.errors.size() > 0) {
tmp.newDiv = '<b style="color: red;"> Error(s) occurred: </b>';
tmp.newDiv += '<table class="ResultDataList">';
tmp.newDiv += '<thead>';
tmp.newDiv += '<tr>';
tmp.newDiv += '<th>Row Info</th>';
tmp.newDiv += '<th>Result</th>';
tmp.newDiv += '</tr>';
tmp.newDiv += '</thead>';
tmp.newDiv += '<tbody>';
tmp.i = 0;
tmp.errors
.each(function(error) {
tmp.newTRClass = (tmp.i % 2 === 0 ? 'ResultDataListAlterItem'
: 'ResultDataListItem');
tmp.newDiv += '<tr class="' + tmp.newTRClass + '">';
tmp.newDiv += "<td><a href='javascript: void(0);' onclick=\"$$('tr[requestid="
+ error.requestId
+ "]').first().scrollTo(); return false;\">Row(id="
+ error.requestId + ")</a>: </td>";
tmp.newDiv += '<td>' + error.emsg + '</td>';
tmp.newDiv += '</tr>';
tmp.i = (tmp.i * 1) + 1;
});
tmp.newDiv += '</tbody>';
tmp.newDiv += '</table>';
tmp.newDiv += '<br /><input type="button" value="close" onclick="Modalbox.hide();" />';
}
if (tmp.errors.size() > 0) {
Modalbox.show(new Element('div').update(tmp.newDiv), {
beforeLoad : function() {
Modalbox.activate();
},
afterLoad : function() {
Modalbox.resizeToContent();
},
title : 'Actions finished!',
width : pageJs.resPaneWith
});
} else {
Modalbox.show(new Element('div').update(tmp.newDiv), {
beforeLoad : function() {
Modalbox.activate();
},
afterLoad : function() {
Modalbox.resizeToContent();
setTimeout('Modalbox.hide();', '1000');
},
title : 'Actions finished!',
width : pageJs.resPaneWith
});
}
// this.checkAll(new Element('input',{'type': 'checkbox', 'checked':
// false}));//deselect all
}
return tmp.errors;
},
// show Comfirm Div
showComfirmDiv : function(divTitle, callbackfunction) {
var tmp = {};
tmp.newDiv = '<div commentdiv="commentdiv">';
tmp.newDiv += '<h3 commentdiv="title">' + divTitle + '</h3>';
tmp.newDiv += '<textarea commentdiv="comments" style="width: 98%;"></textarea>';
tmp.newDiv += '<input commentdiv="submitBtn" value="YES" type="button" onclick="'
+ callbackfunction + '; return false;"/>';
tmp.newDiv += '<input value="NO" onclick="Modalbox.hide(); return false;" type="button"/>';
tmp.newDiv += '</div>';
Modalbox.show(new Element('div').update(tmp.newDiv), {
'title' : divTitle,
'width' : pageJs.resPaneWith
});
},
// show perferences div
showPreferences : function(callbackId, clickedBtn) {
this
.showError("This function is NOT ready yet!\nPlease watch this space here!");
return false;
},
// show Comfirm Div
confirmPushFT : function(message, confirmCallbackBtnId, newstatus,
requestId) {
var tmp = {};
tmp.message= message[0].unescapeHTML();
tmp.newhtml = "<div confirmbox='confirmAvailable'>"
tmp.newhtml += "<b>Please confirm below :</b><br /><br />";
tmp.newhtml += "<b>Are you sure you want to push the selected fieldtask(s) to "
+ newstatus + "?</b><br /><br />";
tmp.newhtml += "<b>Warning:</b><br />";
tmp.newhtml += tmp.message+ "<br />";
tmp.newhtml += "<input type='button' newpreference='saveBtn' onclick=\"pageJs.pushFT('"
+ confirmCallbackBtnId
+ "','"
+ newstatus
+ "', "
+ requestId
+ ", true); return false;\" value='Proceed'>";
tmp.newhtml += "<input type='button' onclick='Modalbox.hide(); return false;' value='Cancel'>";
tmp.newhtml += "</div>";
Modalbox.show(new Element('div').update(tmp.newhtml), {
'title' : 'Confirm Task',
'width' : '1000'
});
return false;
},
showConfirmPushFt : function(message, confirmCallbackBtnId, callbackId,
newstatus, requestId, checkflag) {
var tmp = {};
tmp.me = this;
// gathering data
try {
tmp.selectedRquestIds = this.getSelectedIds(requestId);
} catch (e) {
this.showError(e);
return;
}
tmp.request = new Prado.CallbackRequest(this.createWarningBtn, {
'onComplete' : function(sender, parameter) {
try {
tmp.result = pageJs.analyzeResp();
if (checkflag) {
// confirm task with the FRs
tmp.me.confirmPushFT(tmp.result, callbackId, newstatus,
requestId);
} else {
// then push FT
tmp.me.pushFT(callbackId, newstatus, requestId, true);
}
} catch (e) {
this.showError(e);
return;
}
}
});
tmp.callParams = {
'selectedIds' : tmp.selectedRquestIds
};
tmp.request.setCallbackParameter(tmp.callParams);
tmp.request.setRequestTimeOut(this.maxExecutionTime);
tmp.request.dispatch();
},
checkRervedForSelected : function(selectedRquestIds) {
var tmp = {};
tmp.selectedRquestIds = selectedRquestIds;
tmp.errormessage = "";
tmp.resultTableId = this.resultTableId;
tmp.selectedRquestIds
.each(function(id) {
tmp.currentRow = $$(
'table#' + tmp.resultTableId + ' tr[requestid="'
+ id + '"]').first();
tmp.currentRow = tmp.currentRow
.down('[resultrow="reserved"]');
tmp.countReserved = tmp.currentRow
.down('[atag="reserved"]').innerHTML;
if (tmp.countReserved == 0) {
tmp.errormessage += "Some of the facility requests have zero reserved parts against them!\n";
}
});
return tmp.errormessage;
},
// push FT to avail
pushFT : function(callbackId, newstatus, requestId, confirmFlag) {
var tmp = {};
tmp.me = this;
// gathering data
try {
tmp.selectedRquestIds = this.getSelectedIds(requestId);
} catch (e) {
this.showError(e);
return;
}
tmp.resultTableId = '';
if (tmp.me.checkRervedForSelected(tmp.selectedRquestIds) != "") {
tmp.errormessage = "Some of the facility requests have zero reserved parts against them!\n";
tmp.errormessage += "You must have reservations against all the requests to Push To Available."
alert(tmp.errormessage);
} else {
tmp.message = '';
if (!confirmFlag || confirmFlag === undefined) {
tmp.me.showConfirmPushFt(tmp.message, this.createWarningBtn,
callbackId, newstatus, requestId, true);
return false;
}
tmp.resultTable = $(this.resultTableId);
tmp.fieldTaskArray = {};
// looping through all ids:
// - select those request that has the same field task id, as we are
// pushing the field task status here!!!
this.selectedRequestIds.each(function(id) {
tmp.resultRowTr = tmp.resultTable.down('tr[requestid="' + id
+ '"]');
if (tmp.resultRowTr !== undefined) {
tmp.fieldTaskId = tmp.resultRowTr
.readAttribute('fieldtaskid');
// push the field task id into array for processing
if (tmp.fieldTaskArray[tmp.fieldTaskId] === undefined)
tmp.fieldTaskArray[tmp.fieldTaskId] = [];
tmp.fieldTaskArray[tmp.fieldTaskId].push(id);
}
});
// start submission
this.submitEachRequest(0, tmp.selectedRquestIds.join(','),
callbackId, Object.toJSON({
'newstatus' : newstatus,
'fieldTaskArray' : tmp.fieldTaskArray
}));
}
},
// on change event for preference list
changePreferences : function(list, callBackId, chgCallBackId,
search_callbackId) {
var tmp = {};
tmp.selectedPvalue = $(list).value.strip();
if (tmp.selectedPvalue.empty())
return false;
// list all preference for deleting
if (tmp.selectedPvalue === 'chg') {
this.showPreferenceList(callBackId, list);
return;
}
// change preferences selections
mb.showLoading('changing view');
tmp.request = new Prado.CallbackRequest(chgCallBackId, {
'onComplete' : function(sender, parameter) {
// search with normal search
pageJs.search(search_callbackId, true);
}
});
tmp.request.setCallbackParameter({
'name' : tmp.selectedPvalue
});
tmp.request.setRequestTimeOut(this.maxExecutionTime);
tmp.request.dispatch();
},
// showing the confirmation for adding a new preference
confirmAddView : function(addNewPCallbackId, viewPListCallbackId,
dropDownListId) {
var tmp = {};
tmp.newhtml = "<div newpreference='newpreferencediv'>"
tmp.newhtml += "Please give the current seach criteria a name that you can use for the future:<br />";
tmp.newhtml += "<input newpreference='newname' style='width:95%;' onkeydown=\"pageJs.enterEvent(event, $(this).up('div[newpreference=newpreferencediv]').down('input[newpreference=saveBtn]'));\">";
tmp.newhtml += "<input type='button' newpreference='saveBtn' onclick=\"pageJs.addNewPreference('"
+ addNewPCallbackId
+ "', '"
+ viewPListCallbackId
+ "', '"
+ dropDownListId + "', this); return false;\" value='save'>";
tmp.newhtml += "<input type='button' onclick='Modalbox.hide(); return false;' value='cancel'>";
tmp.newhtml += "</div>";
Modalbox.show(new Element('div').update(tmp.newhtml), {
'title' : 'Saving New Search Criteria',
'width' : pageJs.resPaneWith
});
return false;
},
// adding a new preference
addNewPreference : function(callBackId, viewPreferenceCallBackId,
dropDownListId, clickedBtn) {
var tmp = {};
tmp.newname = $(clickedBtn).up('div').down(
'input[newpreference="newname"]').value.strip();
if (tmp.newname.empty()) {
this.showError("A preference name is needed!");
return;
}
// loop through the droplist list to see whether we've got the name
// already
tmp.nameExsits = false;
$(dropDownListId)
.select('option')
.each(
function(item) {
if (item.value.strip() === tmp.newname) {
if (!confirm('There is one preference called: '
+ tmp.newname
+ ' in your list, do you wish to overwrite that?')) {
tmp.nameExsits = false;
return false;
} else {
tmp.nameExsits = true;
}
}
});
// not found or overwrite the exsiting name
if (tmp.nameExsits === true || tmp.nameExsits === false) {
$(clickedBtn).disabled = true;
tmp.clickedBtnvalue = $(clickedBtn).value;
$(clickedBtn).value = "saving...";
tmp.request = new Prado.CallbackRequest(
callBackId,
{
'onComplete' : function(sender, parameter) {
$(clickedBtn).disabled = false;
$(clickedBtn).value = tmp.clickedBtnvalue;
tmp.newhtml = 'New Preference Saved!';
try {
tmp.result = pageJs.analyzeResp(true);
} catch (e) {
tmp.newhtml = '<b style="color: red;">' + e
+ '</b>';
}
tmp.newhtml += '<input type="button" value="OK" onclick="Modalbox.hide(); return false;"/>';
Modalbox.show(new Element('div')
.update(tmp.newhtml), {
'title' : 'Saved',
'width' : pageJs.resPaneWith
});
// update the preference list
if (tmp.result !== undefined
&& tmp.result.name !== undefined
&& tmp.nameExsits === false)
$(dropDownListId).select('option').last()
.insert(
{
before : '<option value="'
+ tmp.result.name
+ '">'
+ tmp.result.name
+ '</option>'
});
// pageJs.showPreferenceList(viewPreferenceCallBackId);
}
});
tmp.request.setCallbackParameter({
'name' : tmp.newname,
'action' : 'add'
});
tmp.request.setRequestTimeOut(this.maxExecutionTime);
tmp.request.dispatch();
}
},
// deleting a preference
delPreference : function(callBackId, dropDownListId, clickedBtn) {
var tmp = {};
tmp.newname = $(clickedBtn).value.strip();
if (!confirm('Are you sure you want to delete this preference(='
+ tmp.newname + ')?'))
return false;
mb.showLoading('deleting');
tmp.request = new Prado.CallbackRequest(
callBackId,
{
'onComplete' : function(sender, parameter) {
tmp.newhtml = 'Selected Preference Deleted Successfully!';
try {
tmp.result = pageJs.analyzeResp(true);
} catch (e) {
tmp.newhtml = "<b style='color: red;'> " + e
+ "</b>";
}
tmp.newhtml += '<input type="button" value="OK" onclick="Modalbox.hide(); return false;"/>';
Modalbox.show(new Element('div').update(tmp.newhtml), {
'title' : 'Deleting Result',
'width' : pageJs.resPaneWith
});
// update the preference list
if (tmp.result !== undefined
&& tmp.result.name !== undefined)
$(dropDownListId).select(
'option[value="' + tmp.result.name + '"]')
.first().remove();
}
});
tmp.request.setCallbackParameter({
'name' : tmp.newname,
'action' : 'del'
});
tmp.request.setRequestTimeOut(this.maxExecutionTime);
tmp.request.dispatch();
return false;
},
// showPreferenceList
showPreferenceList : function(callBackId, dropDownListId) {
var tmp = {};
mb.showLoading('getting preference list');
// reset preference list
this.resetPreferenceList(dropDownListId);
tmp.request = new Prado.CallbackRequest(callBackId, {
'onComplete' : function(sender, parameter) {
Modalbox.show(new Element('div')
.update($(pageJs.reponseHolderId).innerHTML), {
beforeLoad : function() {
Modalbox.activate();
},
title : 'Your View Preferences: ',
width : pageJs.resPaneWith
});
}
});
tmp.request.setCallbackParameter({
'name' : tmp.newname,
'action' : 'add'
});
tmp.request.setRequestTimeOut(this.maxExecutionTime);
tmp.request.dispatch();
},
resetPreferenceList : function(dropDownListId) {
// unselect the item from the list
$(dropDownListId).select('option').each(function(item) {
if (item.value.strip() === '')
item.selected = true;
else
item.selected = false;
});
},
// start referesh
startTimer : function() {
var tmp = {};
// get all reuqest ids
this.checkAll(new Element('input', {
'type' : 'checkbox',
'checked' : true
}));// select all
tmp.selectedIds = this.selectedRequestIds;
this.checkAll(new Element('input', {
'type' : 'checkbox',
'checked' : false
}));// de-select all
try {
if ($(this.resultTableId).down('tbody').select('tr.resultRow')
.first() != null) {
tmp.firstId = $(this.resultTableId).down('tbody').select(
'tr.resultRow').first().readAttribute('requestid')
.strip();
} else {
tmp.firstId = '';
}
} catch (e) {
tmp.firstId = '';
}
if (tmp.selectedIds.size() <= 0) {
tmp.selectedIds = '';
}
this.refreshInfo.timer = new PeriodicalExecuter(function() {
tmp.request = new Prado.CallbackRequest(
pageJs.refreshInfo.refreshCallBackId, {
'onComplete' : function(sender, parameter) {
pageJs.postRefresh();
}
});
tmp.request.setCallbackParameter({
'ids' : tmp.selectedIds,
'firstid' : tmp.firstId,
'searchRequest' : pageJs.searchRequest
});
tmp.request.dispatch();
}, this.refreshInfo.maxExeTime);
},
// stop referesh
stopTimer : function() {
if (this.refreshInfo.timer !== null)
this.refreshInfo.timer.stop();
this.refreshInfo.timer = null;
},
// called by startTimer's onComplete
postRefresh : function() {
var tmp = {};
tmp.resultTableBody = $(this.resultTableId).down('tbody');
tmp.updateContentCSS = 'updatedContent';
tmp.updateRowCSS = 'updatedRow';
try {
tmp.result = this.analyzeResp();
// check whether there is new request coming in
if (tmp.result.hasnew !== undefined && tmp.result.hasnew === true) {
tmp.btnPane = tmp.resultTableBody.up('div#resultPanelWrapper')
.down('#btnPane');
if ($(this.refreshInfo.reloadPaneId) === undefined
|| $(this.refreshInfo.reloadPaneId) === null) {
this.foundNewFrIds = tmp.result.hasnew_frId;
tmp.refreshBtn = '<a style="margin-right: 25px;" href="javascript: void(0);" id="'
+ this.refreshInfo.reloadPaneId
+ '" title="Reload the page with new requests" onclick="pageJs.search(pageJs.searchRequest.search_callbackId, true); return false;"><img src="/themes/images/refresh.gif" /> <b>Found new request(s)</b></a>';
tmp.btnPane.down().insert({
before : tmp.refreshBtn
});
}
}
tmp.result.requests
.each(function(item) {
tmp.foundDiff = false;
tmp.row = tmp.resultTableBody.select(
'tr.resultRow[requestid="' + item.id + '"]')
.first();
// check ft status
tmp.foundDiff = pageJs.updateContent(item.taskStatus
.strip(), tmp.row
.down('[resultrow="taskstatus"]'),
tmp.updateContentCSS, tmp.foundDiff, true);
// check fr status
tmp.foundDiff = pageJs.updateContent(item.status
.strip(), tmp.row.down('[resultrow="status"]'),
tmp.updateContentCSS, tmp.foundDiff, false);
// check reserved
if (item.reserved === null)
item.reserved = '0';
tmp.foundDiff = pageJs.updateContent(item.reserved
.strip(), tmp.row
.down('[resultrow="reserved"]').down('a'),
tmp.updateContentCSS, tmp.foundDiff, true);
// check sla end
if (item.slaEnd === null)
item.slaEnd = '';
tmp.foundDiff = pageJs.updateContent(item.slaEnd
.strip(), tmp.row.down('[resultrow="slaend"]'),
tmp.updateContentCSS, tmp.foundDiff, true);
// check ownership
if (item.owner === null)
item.owner = '';
tmp.foundDiff = pageJs.updateContent(
item.owner.strip(), tmp.row
.down('div[resultrow="ownername"]'),
tmp.updateContentCSS, tmp.foundDiff, true);
if (tmp.foundDiff === true) {
tmp.row.addClassName(tmp.updateRowCSS);
// hide all buttons
tmp.row
.down('[resultrow="btns"]')
.update(
'<input type="image" src="/themes/images/refresh.gif" refreshdiv="button" onclick="return pageJs.reloadRow('
+ item.id
+ ', $(this.next('
+ "'[refreshdiv=data]'"
+ ')).innerHTML.strip().evalJSON(),false);" title="refresh this row"/><span refreshdiv="data" style="display: none;">'
+ Object.toJSON(item)
+ '</span>');
// disable checkbox
pageJs.selectOneItem(item.id, false);
tmp.row.down('[resultrow="id"]').down(
'input[type="checkbox"]').disabled = true;
}
});
} catch (e) {
// as this is refresh reques, so we don't want to show the users the
// error!
Logger.error(e);
}
},
// update content of the different status
updateContent : function(expectedValue, element, newClassName,
foundDiffBefore, exactMatch) {
var tmp = {};
var changed = false;
tmp.original = element.innerHTML.strip();
if (exactMatch) {
if (expectedValue !== tmp.original) {
changed = true;
}
} else {
if (tmp.original.indexOf(expectedValue) == -1) {
changed = true;
}
}
if (changed) {
element.addClassName(newClassName);
element.update(expectedValue);
element.writeAttribute({
'title' : tmp.original + ' => ' + expectedValue
});
return true; // found difference!
}
return foundDiffBefore;
},
// update the current row
reloadRow : function(requestId, newData, checked) {
try {
var tmp = {};
tmp.row = $(this.resultTableId).down(
'tr[requestid="' + requestId + '"]');
if (tmp.row === undefined || tmp.row === null)
return false;
tmp.data = newData;
tmp.rowNo = tmp.row.readAttribute('rowno');
tmp.newHtml = this.getResultTR(tmp.data, tmp.rowNo, checked);
tmp.rowPrevious = tmp.row.previous();
tmp.rowNext = tmp.row.next();
tmp.row.remove();
if (tmp.rowPrevious === undefined || tmp.rowPrevious === null) {
if (tmp.rowNext === undefined || tmp.rowNext === null) {
// only one record
tmp.row = $(this.resultTableId).down('tbody');
tmp.row.insert({
top : tmp.newHtml
});
} else {
tmp.rowNext.insert({
before : tmp.newHtml
});
}
} else {
tmp.rowPrevious.insert({
after : tmp.newHtml
});
}
return false;
} catch (e) {
// console.debug(e);
}
},
// take facility request
takeFR : function(callbackId, requestId) {
var tmp = {};
// gathering data
try {
tmp.selectedRquestIds = this.getSelectedIds(requestId);
} catch (e) {
this.showError(e);
return;
}
if (!confirm('Are you sure you want to take selected request(s)?'))
return;
this.submitEachRequest(0, tmp.selectedRquestIds.join(','), callbackId);
},
// show the pushing panel
showPushFR : function(callBackId, requestId) {
var tmp = {};
// gathering data
try {
tmp.selectedRquestIds = this.getSelectedIds(requestId);
} catch (e) {
this.showError(e);
return;
}
var lastPushLocation = getCookie('lastPushLocation');
mb.showLoading('loading');
tmp.request = new Prado.CallbackRequest(callBackId, {
'onComplete' : function(sender, parameter) {
Modalbox.show(new Element('div')
.update($(pageJs.reponseHolderId).innerHTML), {
beforeLoad : function() {
Modalbox.activate();
},
title : 'Choose where to push selected FR(s) to: ',
width : pageJs.resPaneWith
});
}
});
tmp.callParams = {
'selectedIds' : tmp.selectedRquestIds
};
if (lastPushLocation != null) {
tmp.callParams['lastPushLocation'] = lastPushLocation;
}
tmp.request.setCallbackParameter(tmp.callParams);
tmp.request.setRequestTimeOut(this.maxExecutionTime);
tmp.request.dispatch();
},
// push FR action
pushFR : function(callbackId, requestIds, clickedBtn) {
var tmp = {};
tmp.selectedRquestIds = requestIds.split(',');
if (tmp.selectedRquestIds.length === 0)
return this.showError('Please select some items first!');
tmp.pushDiv = $(clickedBtn).up('div[pushfrdiv="pushfrdiv"]');
tmp.comments = tmp.pushDiv.down('[pushfrdiv="comments"]').value.strip();
if (tmp.comments.empty())
return this.showError('Comments are required!');
tmp.newOwnerId = tmp.pushDiv.down('[pushfrdiv="newOwnerId"]').value
.strip();
if (tmp.newOwnerId.empty())
return this.showError('A new owner is required!');
tmp.info = {
'newOwnerId' : tmp.newOwnerId,
'comments' : tmp.comments
};
document.cookie = "lastPushLocation=" + tmp.newOwnerId + "; path=/";
this.submitEachRequest(0, tmp.selectedRquestIds.join(','), callbackId,
Object.toJSON(tmp.info));
},
// get the selected request ids
getSelectedIds : function(requestId) {
var tmp = {};
if (requestId !== undefined) {
tmp.selectedRquestIds = [ requestId ];
} else {
// gathering data
tmp.selectedRquestIds = this.selectedRequestIds;
}
// check if selected any
if (tmp.selectedRquestIds.length === 0)
throw 'Please select some items first!';
return tmp.selectedRquestIds;
},
// get the right browser
getBrowser : function() {
var nVer = navigator.appVersion;
var nAgt = navigator.userAgent;
var browserName = navigator.appName;
var fullVersion = '' + parseFloat(navigator.appVersion);
var majorVersion = parseInt(navigator.appVersion, 10);
var nameOffset, verOffset, ix;
// In Opera, the true version is after "Opera" or after "Version"
if ((verOffset = nAgt.indexOf("Opera")) != -1) {
browserName = "Opera";
fullVersion = nAgt.substring(verOffset + 6);
if ((verOffset = nAgt.indexOf("Version")) != -1)
fullVersion = nAgt.substring(verOffset + 8);
}
// In MSIE, the true version is after "MSIE" in userAgent
else if ((verOffset = nAgt.indexOf("MSIE")) != -1) {
browserName = "Microsoft Internet Explorer";
fullVersion = nAgt.substring(verOffset + 5);
}
// In Chrome, the true version is after "Chrome"
else if ((verOffset = nAgt.indexOf("Chrome")) != -1) {
browserName = "Chrome";
fullVersion = nAgt.substring(verOffset + 7);
}
// In Safari, the true version is after "Safari" or after "Version"
else if ((verOffset = nAgt.indexOf("Safari")) != -1) {
browserName = "Safari";
fullVersion = nAgt.substring(verOffset + 7);
if ((verOffset = nAgt.indexOf("Version")) != -1)
fullVersion = nAgt.substring(verOffset + 8);
}
// In Firefox, the true version is after "Firefox"
else if ((verOffset = nAgt.indexOf("Firefox")) != -1) {
browserName = "Firefox";
fullVersion = nAgt.substring(verOffset + 8);
}
// In most other browsers, "name/version" is at the end of userAgent
else if ((nameOffset = nAgt.lastIndexOf(' ') + 1) < (verOffset = nAgt
.lastIndexOf('/'))) {
browserName = nAgt.substring(nameOffset, verOffset);
fullVersion = nAgt.substring(verOffset + 1);
if (browserName.toLowerCase() == browserName.toUpperCase()) {
browserName = navigator.appName;
}
}
// trim the fullVersion string at semicolon/space if present
if ((ix = fullVersion.indexOf(";")) != -1)
fullVersion = fullVersion.substring(0, ix);
if ((ix = fullVersion.indexOf(" ")) != -1)
fullVersion = fullVersion.substring(0, ix);
majorVersion = parseInt('' + fullVersion, 10);
if (isNaN(majorVersion)) {
fullVersion = '' + parseFloat(navigator.appVersion);
majorVersion = parseInt(navigator.appVersion, 10);
}
return browserName;
}
};
|
import React from 'react';
import {Col, Row} from 'react-native-easy-grid/index';
import {Button, Icon, Text} from 'react-native-elements';
import i18n from 'i18n-js';
import {useDerbyTheme} from '../../utils/theme';
import {StyleSheet} from 'react-native';
import {sortByTeam} from '../../utils/helpers';
const MatchSubscriptions = ({subscriptions}) => {
const {sizes, colors} = useDerbyTheme();
const stylesCardLabel = {
color: colors.text,
fontSize: sizes.BASE * 0.8,
fontFamily: 'Rubik_400Regular',
marginRight: sizes.BASE,
marginTop: 1,
};
return (
<>
<Row style={{marginTop: sizes.BASE * 0.7}}>
<Col>
<Text
style={[
stylesCardLabel,
{
fontFamily: 'Rubik_500Medium',
marginBottom: sizes.BASE / 2.5,
marginTop: sizes.BASE / 1.5,
},
]}>
{i18n.t('match_screen_subscribed_players')}
</Text>
</Col>
</Row>
<Row style={{flexWrap: 'wrap'}}>
{subscriptions.sort(sortByTeam).map((subs) => {
return (
<Button
containerStyle={{
marginTop: sizes.BASE * 0.4,
marginRight: sizes.BASE * 0.4,
}}
disabled={true}
disabledStyle={{backgroundColor: colors.backgroundCard}}
disabledTitleStyle={[
styles.submitButtonText,
{
color: colors.text,
fontSize: sizes.BASE * 0.7,
},
]}
titleStyle={[
styles.submitButtonText,
{
color: colors.text,
fontSize: sizes.BASE * 0.7,
},
]}
buttonStyle={[
styles.submitButtonNoWidth,
{
paddingHorizontal: sizes.BASE,
paddingVertical: sizes.BASE / 4,
borderWidth: 2,
borderColor: colors.joy2,
},
]}
icon={
<Icon
size={sizes.BASE}
name={
subs.subscription === 'playing' ? 'caretup' : 'caretdown'
}
type="antdesign"
color={
subs.subscription === 'playing'
? colors.joy2
: subs.subscription === 'not-playing'
? colors.error
: colors.textMuted
}
style={{marginRight: sizes.BASE / 2}}
/>
}
title={subs.first_name + ' ' + subs.last_name}
key={subs.first_name + ' ' + subs.last_name}
/>
);
})}
</Row>
</>
);
};
const styles = StyleSheet.create({
submitButtonText: {fontFamily: 'Rubik_300Light'},
submitButton: {
width: 200,
borderRadius: Math.round(45 / 2),
height: 35,
marginRight: 1,
},
submitButtonNoWidth: {
borderRadius: Math.round(45 / 2),
height: 25,
marginRight: 1,
},
});
export default MatchSubscriptions;
|
'use strict'
const Model = require('./Model')
module.exports = class Device extends Model {
static get label () {
return '设备'
}
static get fields() {
return {
_id: { sortable: true },
os: { label: '操作系统' },
version: { label: '系统版本' },
model: { label: '机型' },
// name: { label: '名称' },
width: { label: '屏幕宽度(px)' },
height: { label: '屏幕高度(px)' },
jpushId: { label: 'jpushId' },
created_at: { label: '注册时间', sortable: true },
updated_at: { label: '更新时间', sortable: true },
actions: false
}
}
}
|
import React, { Component } from 'react';
class ImageList extends Component {
render() {
return (
<div className="image">
<img src={this.props.photo.urls.small} alt={this.props.photo.id} />
</div>
);
};
}
export default ImageList;
|
// http://socialinnovationsimulation.com/2013/07/11/tutorial-making-maps-on-d3/
var width = 960,
height = 500
var projection = d3.geo.albersUsa()
var path = d3.geo.path()
.projection(projection);
var vis = d3.select('#example').append('svg')
.attr({
'width': width,
'height': height
})
queue()
.defer(d3.json, '../data/us-10m.json')
.defer(d3.json, '../data/ga-districts.json')
.defer(d3.json, '../data/us-congress-113.json')
.await(ready);
function ready(error, us, ga, congress){
console.log('us: ', us)
console.log('ga: ', ga)
console.log('congress: ', congress)
// vis.selectAll('append')
// .data(topojson.feature(us, us.objects.counties).features)
// .enter().append('path')
// .attr({
// 'd': path
// })
// vis.selectAll('append')
// .data(topojson.feature(us, us.objects.states).features)
// .enter().append('path')
// .attr({
// 'd': path
// })
// vis.append('path')
// .attr('id', 'land')
// .datum(topojson.feature(us, us.objects.land))
// .attr('d', path);
vis.selectAll('append')
.data(topojson.feature(congress, congress.objects.districts).features)
.enter().append('path')
.attr({
'd': path,
'class': 'house'
})
// this returns arcs
var alaskaState = us.objects.states.geometries.filter(function(d){
return d.id === 2
})[0]
var hawaiiState = us.objects.states.geometries.filter(function(d){
return d.id === 15
})[0]
vis.append('path')
.attr('id', 'land')
.datum(topojson.feature(us, alaskaState))
.attr('d', path);
vis.append('path')
.attr('id', 'land')
.datum(topojson.feature(us, hawaiiState))
.attr('d', path);
}
|
//if given sum is equal to sum of any two elements in the array,
//function need to return true; otherwise function need to return false.
function returnSum(sum,array){
var lett = array.concat(arr[0]);
for(i=0;i<lett;i++){
for(j=i+1;j<lett;j++){
if(lett[i]+lett[j]===sum){
return true;
}}}}
Console.log(returnSum(3, [1,2,3,6]));
|
(function () {
'use strict';
var rateBoard = {
templateUrl: 'app/components/rate-board/rate-board.html',
controller: rateBoardController
};
angular
.module('newlotApp')
.component('rateBoard', rateBoard);
rateBoardController.$inject = ['Rate'];
function rateBoardController(Rate) {
var vm = this;
vm.rates = [];
_getRateBoard();
function _getRateBoard() {
Rate.get({}, function (response) {
if (response.docs && response.docs.length > 0) {
vm.rates = response.docs[0].rates;
}
});
}
}
})();
|
const expect = require('chai').expect;
const {Checkout} = require ("./supermarket.js")
console.log(Checkout)
// var a = "1"
describe('Checkout test', function(){
it('Can create an instance of the Checkout class.', function(){
const expected = "object";
const actual = typeof new Checkout();
expect(actual).to.deep.equal(expected)
})
it('Can add an item.', function(){
const expected = 1
var instance = new Checkout()
instance.addItem("large eggs")
const actual = instance.listItems.length;
expect(actual).to.deep.equal(expected)
})
it('Can add an item price.', function(){
const expected = 5
var instance = new Checkout()
instance.addItem("large eggs", 5)
const actual = instance.listItems [0].price;
expect(actual).to.deep.equal(expected)
})
it('Can calculate the current total.', function(){
const expected = 8
var instance = new Checkout()
instance.addItem("large eggs", 5)
instance.addItem("milk", 3)
const actual = instance.calculator();
expect(actual).to.deep.equal(expected)
})
it('Can add multiple items and get correct total.', function(){
const expected = 9
var instance = new Checkout()
instance.addItem("large eggs", 5)
instance.addItem("milk", 3)
instance.addItem("apple", 1)
const actual = instance.calculator();
expect(actual).to.deep.equal(expected)
})
it('Can add discount rules.', function(){
const expected = 12.2
var instance = new Checkout()
instance.addItem("large eggs", 5, 0.5)
instance.addItem("milk", 3, 0.2)
instance.addItem("apple", 1, 0.1)
const actual = instance.calculator();
expect(actual).to.deep.equal(expected)
})
it('Can apply discount rules to the total.', function(){
const expected = 12.2
var instance = new Checkout()
instance.addItem("large eggs", 5, 0.5)
instance.addItem("milk", 3, 0.2)
instance.addItem("apple", 1, 0.1)
const actual = instance.calculator();
expect(actual).to.deep.equal(expected)
})
it('Exception is thrown for item added without a price.', function(){
var instance = new Checkout()
const expected = "one of the items doesn't have a price";
instance.addItem("large eggs", 5, 0.5)
instance.addItem("milk")
instance.addItem("apple", 1, 0.1)
const actual = instance.calculator();
expect(actual).to.deep.equal(expected)
})
}
)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.