text
stringlengths
7
3.69M
import React, { Component } from 'react' import s from './Avatar.css' class Avatar extends Component{ render(){ return( <div className={s.avatar} > <img src={this.props.src} alt={this.props.user} /> </div> ) } } export default Avatar
๏ปฟangular.module('ngApp.uploadShipment').controller('WithServiceFinalMessageController', function ($scope, $uibModal, BatchProcessedShipments, BatchUnprocessedShipments, BatchProcess, config, SessionRecord) { function init() { $scope.UnsuccessFullShipments = []; $scope.ImagePath = config.BUILD_URL; $scope.Total = BatchProcess; $scope.Processed = BatchProcessedShipments; $scope.Unprocessed = BatchUnprocessedShipments; $scope.SessionName = SessionRecord.SessionName; } init(); });
export const getModules = ({ app: { config: { modules }, }, }) => modules; export const getPages = ({ app: { config: { pages }, }, }) => pages;
'use strict'; // api globals var appToken = 'RLf82kXaTSeOLmaES2qZ5Bkc8'; var metioriteLandingUrl = 'https://data.nasa.gov/resource/gh4g-9sfh.json'; var seattleCrime = 'https://data.seattle.gov/resource/3xqu-vnum.json'; // app globals var metoriteData = []; function Metiorite(name, mass, fall, year){ this.name = name; this.mass = mass; this.fall = fall; this.year = year; metoriteData.push(this); } Metiorite.prototype.createLiEl = function(){ var li = document.createElement('li'); var section = document.createElement('section'); li.appendChild(section); var h1 = document.createElement('h1'); h1.textContent = this.name; section.appendChild(h1); var p = document.createElement('p'); p.textContent = 'Mass: ' + this.mass + ', Year: ' + new Date(this.year).getFullYear(); section.appendChild(p); return li; }; function handleRequestFail(data, textSatus){ dubugger; } function getDataFromUrl(url, data, handler){ url += '?$$app_token=' + appToken; $.getJSON(url, data, handler).fail(function(xhr){ alert( 'Sorry, there was a problem!' ); console.log('Error Status Code: ' + xhr.status); console.log('Error Status Text: ' + xhr.statusText); console.dir(xhr); }); //$.ajax({ //url: url, //type: 'GET', //data: data, //dataType: 'json', //success: handler, //}).fail(function(xhr) { //alert( 'Sorry, there was a problem!' ); //console.log('Error Status Code: ' + xhr.status); //console.log('Error Status Text: ' + xhr.statusText); //console.dir(xhr); //}) } function render250Metiorites(offset){ var metioriteImageListUL = document.getElementsByClassName('metiorite-image-list')[0]; if (offset < metoriteData.length){ for (var i = offset; i < metoriteData.length && i < (offset + 250); i++){ var meatiorLi = metoriteData[i].createLiEl(); metioriteImageListUL.appendChild(meatiorLi); } } } function handleAjaxRequest(data){ if (Array.isArray(data)){ for(var i = 0; i < data.length; i++){ var item = data[i] new Metiorite(item.name, item.mass, item.fall, item.year); } render250Metiorites(0); } } var options = { '$limit': 5, '$offset': 100, }; getDataFromUrl(metioriteLandingUrl, options, handleAjaxRequest); //function handleSetateRequest(data){ //console.dir(data); //debugger; //} //getDataFromUrl(seattleCrime, options, handleSetateRequest);
const inputUsername = document.querySelector('[data-id=username]') inputUsername.addEventListener('input', (event) => { const target = event.currentTarget const lowerCaseWords = [ 'de', 'da', 'do', 'dos' ] const valueArray = target.value.split(' ') target.value = valueArray.map((word) => { return lowerCaseWords.includes(word.toLowerCase()) ? word.toLowerCase() : `${word.charAt(0).toUpperCase()}${word.slice(1).toLowerCase()}` }).join(' ') }) const groupSelect = document.querySelector('[data-id=group-select]') const groupColors = document.querySelector('[data-id=group-colors]') const label = document.createElement('label') const select = document.createElement('select') const colors = [ { name: 'Azoxo', hex: '#5865F2' }, { name: 'Verde', hex: '#57F287' }, { name: 'Amarelo', hex: '#FEE75C' }, { name: 'Fรบcsia', hex: '#EB459E' }, { name: 'Vermelho', hex: '#ED4245' } ] colors.forEach(value => { const option = document.createElement('option') option.value = value.hex option.innerText = value.name select.appendChild(option) }) label.innerText = 'Selecione uma cor' select.setAttribute('multiple', '') select.addEventListener('change', (event) => { groupColors.innerHTML = '' const target = event.target const options = target.selectedOptions Array.from(options).forEach((option) => { const span = document.createElement('span') span.style.backgroundColor = option.value groupColors.appendChild(span) }) }) groupSelect.appendChild(label) groupSelect.appendChild(select)
var mentor = "Dylan Westover"; console.log("My mentor's name is "+mentor)
import React, { Component } from 'react'; import './modal.css'; class Modal extends Component { constructor (props) { super(props) this.state = { visible: true } } render () { const { visible } = this.state; const { title, children } = this.props return visible && <div className="modal-wrapper"> <div className="modal"> <div className="modal-title">{title}</div> <div className="modal-content">{children}</div> <div className="modal-operator"> <button className="modal-operator-close" onClick={this.closeModal}>ๅ–ๆถˆ</button> <button className="modal-operator-confirm" onClick={this.confirm}>็กฎ่ฎค</button> </div> </div> <div className="mask" onClick={this.maskClick}></div> </div> } maskClick = () => { console.log('ๆˆ‘็‚นๅ‡ปไบ†่’™ๅฑ‚'); this.setState({ visible: false }) } closeModal = ()=>{ const { onClose } = this.props; onClose && onClose(); this.setState({ visible: false }) } confirm = () => { const { confirm } = this.props; confirm && confirm(); this.setState({ visible: false }) } componentWillReceiveProps(props){ this.setState({ visible: props.visible }) } } export default Modal;
const { SlashCommandBuilder } = require('@discordjs/builders'); const axios = require('axios'); const dotenv = require('dotenv'); dotenv.config(); module.exports = { data: new SlashCommandBuilder() .setName('gif') .setDescription('Get a gif!') .addStringOption(option => option.setName('searchterm') .setRequired(true) .setDescription('Your search term!')), async execute(selection) { const response = await axios.get(`https://g.tenor.com/v1/random?q=${selection.options._hoistedOptions[0].value}&key=${process.env.TENOR_API_TOKEN}&limit=10`); const randomGif = await response.data.results[Math.floor(Math.random() * response.data.results.length)].url; await selection.reply(randomGif); } };
// import { useHistory } from "react-router-dom"; // function HovedsideButton() { // let history = useHistory(); // function handleClick() { // history.push("/loginside"); // } // return ( // <button type="button" onClick={handleClick}> // Tilbake // </button> // ); // } // export default HovedsideButton;
import Position from './position'; import { ANIMATION_DURATION_MS, CLASS_NO_ANIMATION, ID_OVERLAY, OVERLAY_HTML } from '../common/constants'; import { createNodeFromString } from '../common/utils'; /** * Responsible for overlay creation and manipulation i.e. * cutting out the visible part, animating between the sections etc */ export default class Overlay { /** * @param {Object} options * @param {Window} window * @param {Document} document */ constructor(options, window, document) { this.options = options; this.positionToHighlight = new Position({}); // position at which layover is to be patched at this.highlightedElement = null; // currently highlighted dom element (instance of Element) this.lastHighlightedElement = null; // element that was highlighted before current one this.hideTimer = null; this.window = window; this.document = document; } /** * Prepares the overlay */ makeNode() { let pageOverlay = this.document.getElementById(ID_OVERLAY); if (!pageOverlay) { pageOverlay = createNodeFromString(OVERLAY_HTML); document.body.appendChild(pageOverlay); } this.node = pageOverlay; this.node.style.opacity = '0'; if (!this.options.animate) { this.node.classList.add(CLASS_NO_ANIMATION); } else { this.node.classList.remove(CLASS_NO_ANIMATION); } } /** * Highlights the dom element on the screen * @param {Element} element */ highlight(element) { if (!element || !element.node) { console.warn('Invalid element to highlight. Must be an instance of `Element`'); return; } // If highlighted element is not changed from last time if (element.isSame(this.highlightedElement)) { return; } // There might be hide timer from last time // which might be getting triggered this.window.clearTimeout(this.hideTimer); // Trigger the hook for highlight started element.onHighlightStarted(); // Old element has been deselected if (this.highlightedElement && !this.highlightedElement.isSame(this.lastHighlightedElement)) { this.highlightedElement.onDeselected(); } // get the position of element around which we need to draw const position = element.getCalculatedPosition(); if (!position.canHighlight()) { return; } this.lastHighlightedElement = this.highlightedElement; this.highlightedElement = element; this.positionToHighlight = position; this.show(); // Element has been highlighted this.highlightedElement.onHighlighted(); } show() { if (this.node && this.node.parentElement) { return; } this.makeNode(); window.setTimeout(() => { this.node.style.opacity = `${this.options.opacity}`; this.node.style.position = 'fixed'; this.node.style.left = '0'; this.node.style.top = '0'; this.node.style.bottom = '0'; this.node.style.right = '0'; }); } hideOverlay() { this.node.style.opacity = '0'; this.hideTimer = window.setTimeout(() => { this.node.style.position = 'absolute'; this.node.style.left = ''; this.node.style.top = ''; this.node.style.bottom = ''; this.node.style.right = ''; this.node.parentElement.removeChild(this.node); }, ANIMATION_DURATION_MS); } /** * Returns the currently selected element * @returns {null|*} */ getHighlightedElement() { return this.highlightedElement; } /** * Gets the element that was highlighted before current element * @returns {null|*} */ getLastHighlightedElement() { return this.lastHighlightedElement; } /** * Removes the overlay and cancel any listeners */ clear() { this.positionToHighlight = new Position(); if (this.highlightedElement) { this.highlightedElement.onDeselected(true); } this.highlightedElement = null; this.lastHighlightedElement = null; this.hideOverlay(); } /** * Refreshes the overlay i.e. sets the size according to current window size * And moves the highlight around if necessary */ refresh() { // If no highlighted element, cancel the refresh if (!this.highlightedElement) { return; } // Reposition the stage and show popover this.highlightedElement.showPopover(); this.highlightedElement.showStage(); } }
import isPlainObject from "./isPlainObject" import owns from "./owns" import createDOMBackend from "./createDOMBackend" import applyTransforms from "./applyTransforms" import assertValidIdentifier from "./assertValidIdentifier" import createRenderer from "./createRenderer" let globalId = 0 export default function sansSel({ name="", backend=null, _renderer=null, _styles=null, _transforms=null }={}) { if (process.env.NODE_ENV !== "production") { if (typeof name !== "string") { throw new Error("The 'name' option should be a string") } if (backend !== null && typeof backend !== "function") { throw new Error("The 'backend' option should be a function") } } const renderer = _renderer || createRenderer(backend || createDOMBackend()) const transformsCache = Object.create(null) const namespaces = Object.create(null) const transforms = Object.create(_transforms) const styles = Object.create(_styles) function sansSelInstance() { return renderer(getRules(arguments)) } sansSelInstance.namespace = namespace sansSelInstance.addTransform = addTransform sansSelInstance.addTransforms = multiSetter(addTransform) sansSelInstance.addRule = addRule sansSelInstance.addRules = multiSetter(addRule) function multiSetter(fn) { return (set) => { if (process.env.NODE_ENV !== "production") { if (!set || typeof set !== "object") { throw new Error("The 'set' argument should be an object") } } for (const name in set) fn(name, set[name]) return sansSelInstance } } function getRulesRec(names, result) { let i, l for (i = 0, l = names.length; i < l; i++) { const name = names[i] if (name) { const type = typeof name if (type === "object" && name) { if (name._rules) { getRulesRec(name._rules, result) } else if (name.length) { getRulesRec(name, result) } else { result.push(name) } } else if (type === "string") { if (!(name in styles)) { throw new Error(`Unknown style "${name}"`) } result.push(styles[name]) } else { throw new Error(`Style "${name}" has wrong type`) } } } return result } function getRules() { return getRulesRec(arguments, []) } function namespace(namespaceName) { if (process.env.NODE_ENV !== "production") { assertValidIdentifier(namespaceName) if (typeof namespaceName !== "string") { throw new Error("The 'name' argument should be a string") } } if (!(namespaceName in namespaces)) { namespaces[namespaceName] = sansSel({ name: name ? `${name}_${namespaceName}` : namespaceName, _renderer: renderer, _transforms: transforms, _styles: styles, }) } return namespaces[namespaceName] } function addTransform(name, definition) { if (process.env.NODE_ENV !== "production") { if (typeof name !== "string") { throw new Error("The 'name' argument should be a string") } if (!definition || (typeof definition !== "object" && typeof definition !== "function")) { throw new Error("The 'definition' argument should be an object or a function") } if (owns(transforms, name)) { throw new Error(`The transform ${name} already exists`) } } transforms[name] = definition return sansSelInstance } function addRule(ruleName, declarations) { if (process.env.NODE_ENV !== "production") { if (typeof ruleName !== "string") { throw new Error("The 'name' argument should be a string") } assertValidIdentifier(ruleName) if (!isPlainObject(declarations)) { throw new Error("The 'declaration' argument should be a plain object") } if (owns(styles, ruleName)) { throw new Error(`A "${ruleName}" style already exists`) } } const directParents = declarations.inherit ? Array.isArray(declarations.inherit) ? declarations.inherit : [declarations.inherit] : [] styles[ruleName] = { id: globalId, class: `${name}__${ruleName}`, parents: getRules(directParents), declarations: applyTransforms(transforms, declarations, transformsCache), } globalId += 1 return sansSelInstance } return sansSelInstance }
var TreeNode = require('./tree_node').TreeNode; // Given a sorted (increasing order) array, // write an algorithm to create a binary tree with minimal height function createMinimalBST(array) { if (array.length === 0) { return null; } var midpoint = array.length >> 1, middle = array[midpoint], left = array.slice(0, midpoint), right = array.slice(midpoint + 1), node = new TreeNode(middle); node.left = createMinimalBST(left); node.right = createMinimalBST(right); return node; } exports.createMinimalBST = createMinimalBST;
const { Transform, pipeline } = require("stream"); const fs = require("fs-extra"); const path = require("path"); const vfs = require("vinyl-fs"); const cheerio = require("cheerio"); const html = fs.readFileSync("./jsdoc/classes.list.html", "utf8"); // const style = `<style> // .pae-container { // display: inline-block; // cursor: pointer; // position: fixed; // top: 0; // right: 0; // } // </style>`; const style = fs.readFileSync("./resources/navigation.html", "utf8"); console.log(style); const $ = cheerio.load(html); $("body").append(style); console.log($.html());
import g from 'src/App/helpers/plain/provedGet' import ig from 'src/App/helpers/immutable/provedGet' import PropTypes from 'src/App/helpers/propTypes' import ImmutablePropTypes from 'src/App/helpers/propTypes/immutable' import {assertPropTypes} from 'src/App/helpers/propTypes/check' const dataModelProps = process.env.NODE_ENV === 'production' ? null : Object.freeze({ isLoaded: PropTypes.bool, }), propsModel = process.env.NODE_ENV === 'production' ? null : PropTypes.shape({ currentSection: PropTypes.nullable(PropTypes.string), data: PropTypes.oneOfType([ ImmutablePropTypes.recordOf(dataModelProps), ImmutablePropTypes.shape(dataModelProps), ]) }), optionalPropsModel = process.env.NODE_ENV === 'production' ? null : PropTypes.nullable(propsModel) export default (prevProps, nextProps) => { if (process.env.NODE_ENV !== 'production') { assertPropTypes(optionalPropsModel, prevProps, 'areWeSwitchedOnPage', 'prevProps') assertPropTypes(propsModel, nextProps, 'areWeSwitchedOnPage', 'nextProps') } if ( // if we went to new section ( prevProps !== null && g(prevProps, 'currentSection') !== g(nextProps, 'currentSection') ) || // if we still on the same section but new data is just loaded (prevProps === null && ig(g(nextProps, 'data'), 'isLoaded')) || ( prevProps !== null && !ig(g(prevProps, 'data'), 'isLoaded') && ig(g(nextProps, 'data'), 'isLoaded') ) ) return true else return false }
๏ปฟvar booksDb = require("./books-db"); var path = require("path"); var connect = require("connect"); var url = require("url"); var multipartyHandle = require("./../multiparty-handle"); var xml2js = require("xml2js"); var xmlBuilder = new xml2js.Builder({ rootName: "books" }); var parseXml = xml2js.parseString; var CsvStringifier = require("csv-stringify"); var parseCsv = require("csv-parse"); var fs = require("fs"); var formHtml = fs.readFileSync("./serialization/index.html"); var mimes = { "json": "application/json", "xml": "application/xml", "csv": "application/csv" }; function createHeader(dataType) { return { "Content-Type": mimes[dataType], "Content-Disposition": "attachment;filename=books." + dataType }; } function handleGetRequest(dataType, req, res) { var query = url.parse(path.basename(decodeURI(req.url)), true).query; res.writeHead(200, createHeader(dataType)); var books = booksDb.read(query); switch (dataType) { case "xml": res.end(xmlBuilder.buildObject({ book: books })); break; case "csv": var csvStrigifier = CsvStringifier(books, { header: true }); csvStrigifier.pipe(res); break; case "json": default: res.end(JSON.stringify(books)); break; } } function handleParseResult(res, error, result) { if (error) { console.dir(error); res.writeHead(400); res.end(); return; } var books = result.books && result.books.book || result; booksDb.create(books); res.writeHead(200); res.end(); } function handlePostRequest(dataType, req, res) { var handle = new multipartyHandle(); handle.form.on("error", function(error) { handleParseResult(res, error); }) .on("close", function() { var text = handle.files && handle.files[0].getText(); if (!text) { handleParseResult(res, { message: "Upload error" }); return; } switch (dataType) { case "xml": parseXml(text, { explicitArray: false }, handleParseResult.bind(null, res)); break; case "csv": parseCsv(text, { columns: true }, handleParseResult.bind(null, res)); break; case "json": try { var books = JSON.parse(text); handleParseResult(res, null, books); } catch (e) { handleParseResult(res, e); } break; default: handleParseResult(res, { message: "Data type " + dataType + " is not supported" }); break; } }) .parse(req); }; function handleRequest(dataType, req, res) { if (req.method === "GET") handleGetRequest(dataType, req, res); else if (req.method === "POST") handlePostRequest(dataType, req, res); } var app = connect(); var server = app.use("/xml", handleRequest.bind(null, "xml")) .use("/json", handleRequest.bind(null, "json")) .use("/csv", handleRequest.bind(null, "csv")) .use("/", function(req, res) { res.writeHead(200, { "Content-Type": "text/html" }); res.end(formHtml); }) .listen(1010, function() { console.log("Server started on port " + server.address().port); });
import Vue from 'vue' import Vuex from 'vuex' import { productsList, productDelete, productAdd, productUpdate } from '../api/products' import { userLogin, userValidate, userRegister } from '../api/users' import { contractsList, contractAdd, contractDelete, contractEdit } from '../api/contracts' Vue.use(Vuex) export default new Vuex.Store({ state: { id: localStorage.getItem('id') || '', token: localStorage.getItem('token') || '', items: [] }, mutations: { setToken: (state, token) => { state.token = token }, setId: (state, id) => { state.id = id }, setItems: (state, items) => { state.items = items } }, actions: { // Products getProducts: () => { return productsList() }, deleteProduct: (context, data) => { return productDelete(data.value) }, addProduct: (context, data) => { return productAdd(data) }, editProduct: (context, data) => { return productUpdate(data) }, // Contracts getContracts: (context, data) => { return contractsList(data.axios) }, addContract: (context, data) => { return contractAdd(data.data, data.axios) }, deleteContract: (context, data) => { return contractDelete(data.data, data.axios) }, editContract: (context, data) => { return contractEdit(data.data, data.axios, data.id) }, // Validation login: (context, data) => { return userLogin(data) }, validate: (context, data) => { return userValidate(data) }, register: (context, data) => { return userRegister(data) } }, getters: { getToken: state => state.token, getId: state => state.id, getItems: state => state.items } })
var MongoClient = require('mongodb'); var settings = require('../settings'); var request = require('request'); var url = settings.MongoConnectionsString; var MongoDB = { OpenConnection: function(req, res, next, onOpen) { MongoClient.connect(url, function(err, db) { if(err) res.send('Error connecting to db'); onOpen(db); }); } }; module.exports = MongoDB;
angular.module('sxroApp') .controller('StackDisassemblyCtrl', ['$scope','StackDisassemblyFactory','StacksFactory','ToastService', function ( $scope, StackDisassemblyFactory, StacksFactory, ToastService) { $scope.stackdisassemblydata = {}; /** * * @param fetch all the stacks * @return array */ StacksFactory.query(function(data) { $scope.stacks = data.data; $scope.AjaxInProgress = false; }, function(error) { ToastService.error('Connection interrupted!'); }); }]);
let debug = true; let singlePage = true;
export { default } from '@upfluence/ember-upf-utils/resources/country-codes';
// @flow import * as React from "react"; import omit from "lodash/omit"; import { NavigationGroupOrElement } from "./NavigationGroupOrElement.js"; import type { NavigationElementPropsType } from "./NavigationElement.js"; import type { NavigationGroupPropsType } from "./NavigationGroup.js"; type Item = NavigationGroupPropsType | NavigationElementPropsType; type Props = { items: Array<Item>, showListForm: ( {} ) => void }; type State = { activeEntity: string | null } export class Navigation extends React.PureComponent <Props, State> { constructor( props: Props ) { super( props ); this.state = { activeEntity: null }; } onClickHandler = ( elementProps: NavigationElementPropsType ) => { this.setState( { activeEntity: elementProps.entity } ); this.props.showListForm( omit( elementProps, [ "activeEntity", "onClick" ] ) ); } render() { return ( <nav> { this.props.items.map( ( element ) => <NavigationGroupOrElement key={ element.title } activeEntity={ this.state.activeEntity } onClick={ this.onClickHandler } { ...element } /> ) } </nav> ); } }
๏ปฟangular.module('ngApp.apiUser').controller('ApiController', function (AppSpinner, $scope, SessionService, toaster, ProfileandSettingService, $translate) { var setModalOptions = function () { $translate(['Frayte-Error', 'FrayteWarning', 'No_API_Available']).then(function (translations) { $scope.TitleFrayteWarning = translations.FrayteWarning; $scope.TitleFrayteError = translations.FrayteError; $scope.No_API_Available = translations.No_API_Available; }); }; var getInitial = function () { ProfileandSettingService.ApiDetail($scope.customerId).then(function (response) { if (response.data !== null) { $scope.CustomerApi = response.data; } else { toaster.pop({ type: 'warning', title: $scope.TitleFrayteWarning, body: $scope.TextSuccessfullyChangedPassword, showCloseButton: true }); } }, function () { toaster.pop({ type: 'warning', title: $scope.TitleFrayteError, body: $scope.No_API_Available, showCloseButton: true }); }); }; function init() { var userInfo = SessionService.getUser(); $scope.RoleId = userInfo.RoleId; if ($scope.RoleId === 3) { $scope.customerId = userInfo.EmployeeId; getInitial(); } setModalOptions(); } init(); });
#!/usr/bin/env node process.title = 'linx' require('commander') .version(require('../package').version) .usage('<command> [options]') .command('generate', 'generate file from a template') .parse(process.argv) require('./linx-generate')
/** * Copyright (c) 2013 Oculus Info Inc. * http://www.oculusinfo.com/ * * Released under the MIT License. * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is furnished to do * so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ define(['jquery', '../util/ui_util', './table', './timeline', './attr_chart', './map', './wordcloud', './buildCase', './nodeSummary', './clusterManager', '../util/rest', './linkCriteria', './refine', './graph', './searchpanel', './simplesearchpanel', './pagingpanel', './selection', '../util/colors'], function($, ui_util, table, timeline, attr_chart, map, wordcloud, buildCase, nodeSummary, cluster, rest, linkCriteria, refine, graph, searchpanel, simplesearchpanel, pagingpanel, selection, colors) { var SIMPLE_SEARCH_WIDTH = 317, SIMPLE_SEARCH_HEIGHT = 27, WIDGET_TITLE_HEIGHT = 20, TRANSITION_TIME = 700, BORDER_STYLE = '1px solid '+ colors.BORDER_DARK, getClusterDetails = function(baseUrl, datasetName, clustersetName, clusterId, callback) { rest.get(baseUrl + 'rest/clusterDetails/' + datasetName + '/' + clustersetName + "/" + clusterId, 'Get cluster details', function(response) { var entityDetails, j, i = 0, transformedResponse = { memberDetails : [] }; for (i; i < response.memberDetails.length; i++) { entityDetails = {}; for (j = 0; j < response.memberDetails[i].map.entry.length; j++) { entityDetails[response.memberDetails[i].map.entry[j].key] = response.memberDetails[i].map.entry[j].value; } transformedResponse.memberDetails.push(entityDetails); } callback(transformedResponse); }); }, detailsCallback = function(response, callback) { var entityDetails, j, i = 0, transformedResponse = { memberDetails : [] }; for (i; i < response.memberDetails.length; i++) { entityDetails = {}; for (j = 0; j < response.memberDetails[i].map.entry.length; j++) { entityDetails[response.memberDetails[i].map.entry[j].key] = response.memberDetails[i].map.entry[j].value; } transformedResponse.memberDetails.push(entityDetails); } callback(transformedResponse); }, searchTipDetailsCallback = function(graph, widget, callback) { var entityDetails, j, i, current, nodeId, key, nodeDetails={}, response = graph.response, maxNode = {memberDetails: {length: -1}}, transformedResponse, nodeMap = {}; for (var h=0; h<graph.nodes.length;h++) { nodeMap[graph.nodes[h].id] = { label: graph.nodes[h].name, ring: graph.nodes[h].ring } } graph.nodeMap=nodeMap; for (var k = 0; k<response.memberDetails.entry.length;k++) { transformedResponse = { memberDetails : [] }; key = response.memberDetails.entry[k].key; current = [].concat(response.memberDetails.entry[k].value.memberDetails); for (i = 0; i < current.length; i++) { entityDetails = {}; for (j = 0; j < current[i].map.entry.length; j++) { entityDetails[current[i].map.entry[j].key] = current[i].map.entry[j].value; } transformedResponse.memberDetails.push(entityDetails); } if (transformedResponse.memberDetails.length>maxNode.memberDetails.length && nodeMap[key].ring==0) { maxNode = transformedResponse; nodeId = key; } nodeDetails[key] = transformedResponse; nodeDetails[key].label = nodeMap[key].label; } widget.nodeDetails = nodeDetails; if(callback) { callback(nodeId); } }, getPreclusterDetails = function(baseUrl, preclusterType, clusterId, callback) { rest.get(baseUrl + 'rest/preclusterDetails/' + preclusterType + "/" + clusterId, 'Get precluster details', function(response) { detailsCallback(response, callback); }); }, getPreclusterSearchDetails = function(baseUrl, graph, widget, callback) { var attributeIds = []; for (var i=0;i<graph.nodes.length;i++) { attributeIds.push(graph.nodes[i].id); } graph.attributeIds = attributeIds; rest.post(baseUrl + "rest/preclusterDetails/fetchAds/", '{ids:'+ JSON.stringify(graph.attributeIds) + '}', "Cluster Search Details", function (response) { graph.response=response; searchTipDetailsCallback(graph, widget, callback); }, false, function () { alert('error fetching ads'); }); }, getAttributeSearchDetails = function(baseUrl, graph, widget, callback) { var attributeIds = []; for (var i=0;i<graph.nodes.length;i++) { attributeIds.push(graph.nodes[i].id); } graph.attributeIds = attributeIds; rest.post(baseUrl + "rest/attributeDetails/fetchAds/", '{ids:'+ JSON.stringify(graph.attributeIds) + '}', "Attribute Search Details", function (response) { graph.response=response; searchTipDetailsCallback(graph, widget, callback); }, false, function () { alert('error fetching ads'); }); }, getAttributeDetails = function(baseUrl, attribute, value, callback) { rest.get(baseUrl + 'rest/attributeDetails/' + attribute + "/" + value, 'Get attribute details', function(response) { detailsCallback(response, callback); }); }, getAttributeIdDetails = function(baseUrl, attributeid, callback) { rest.get(baseUrl + 'rest/attributeDetails/id/' + attributeid, 'Get attribute id details', function(response) { detailsCallback(response, callback); }); }, createWidget = function(container, baseUrl) { var linkWidgetObj = { searchPanel: null, graphCanvasContainer: null, simpleSearchContainer: null, simpleSearch: null, movementPanel: {}, mapPanel: {}, wordCloudPanel: {}, attributesPanel: {}, buildCasePanel: {}, nodeSummaryPanel: {}, timeline : null, wordCloud:null, attrChart: null, buildCase: null, nodeSummary:null, searchToggleButton:null, isAdvancedSearchMode:false, sidePanelWidth:null, detailsHeight:null, visitedNodes:[], nodeDetails:{}, selection:selection.createSelectionManager(), init: function() { this.amplifyInit(); this.createGraphCanvas(); this.createSimpleSearchCanvas(); this.pagingPanel = pagingpanel.createWidget(this); this.initSidePanels(); //start with the Case Builder and Summary panels expanded /*this.buildCasePanel.collapseDiv.click(); setTimeout(function() { that.nodeSummaryPanel.collapseDiv.click(); }, 50);*/ }, amplifyInit: function() { var setPanel = function (panel, amp) { panel.height = amp.height; panel.uncollapse = amp.uncollapse; panel.collapsed = amp.collapsed; }, movementPanelAmp = amplify.store('movementPanel'), mapPanelAmp = amplify.store('mapPanel'), wordCloudPanelAmp = amplify.store('wordCloudPanel'), attributesPanelAmp = amplify.store('attributesPanel'), buildCasePanelAmp = amplify.store('buildCasePanel'), nodeSummaryPanelAmp = amplify.store('nodeSummaryPanel'), sidePanelWidthAmp = amplify.store('sidePanelWidth'), detailsHeightAmp = amplify.store('detailsHeight'); movementPanelAmp?setPanel(this.movementPanel,movementPanelAmp):this.movementPanel = {height:WIDGET_TITLE_HEIGHT,uncollapse:120,collapsed:true}; mapPanelAmp?setPanel(this.mapPanel,mapPanelAmp):this.mapPanel = {height:WIDGET_TITLE_HEIGHT,uncollapse:233,collapsed:true}; wordCloudPanelAmp?setPanel(this.wordCloudPanel,wordCloudPanelAmp):this.wordCloudPanel = {height:WIDGET_TITLE_HEIGHT,uncollapse:200,collapsed:true}; attributesPanelAmp?setPanel(this.attributesPanel,attributesPanelAmp):this.attributesPanel = {height:WIDGET_TITLE_HEIGHT,uncollapse:300,collapsed:true}; buildCasePanelAmp?setPanel(this.buildCasePanel,buildCasePanelAmp):this.buildCasePanel = {height:WIDGET_TITLE_HEIGHT,uncollapse:316,collapsed:true}; nodeSummaryPanelAmp?setPanel(this.nodeSummaryPanel,nodeSummaryPanelAmp):this.nodeSummaryPanel = {height:WIDGET_TITLE_HEIGHT,uncollapse:200,collapsed:true}; this.sidePanelWidth = sidePanelWidthAmp?sidePanelWidthAmp:300; this.detailsHeight = detailsHeightAmp?detailsHeightAmp:300; }, initSidePanels: function () { var that = this, jqContainer = $(container), startX = 0, startY = 0, sidePanels = [ { panel:this.nodeSummaryPanel, label:'Summary' }, { panel:this.buildCasePanel, label:'Case Builder' }, { panel:this.movementPanel, label:'Movement' }, { panel:this.mapPanel, label:'Map' }, { panel:this.wordCloudPanel, label:'Word Cloud' }, { panel:this.attributesPanel, label:'Attributes' } ], getUpper = function (upperPanelsCount, attr) { var upper = 0, i = 0; for(i;i<upperPanelsCount;i++) { upper += parseFloat(sidePanels[i].panel.header.css(attr)); } return upper; }, makeCollapsible = function(sidePanel) { sidePanel.collapseDiv = $('<div/>') .addClass('ui-icon') .addClass(sidePanel.collapsed?'ui-icon-triangle-1-e':'ui-icon-triangle-1-s') .css({ position:'relative', float:'left', cursor:'pointer', width:'16px', height:'16px' }); sidePanel.label.css({ height:WIDGET_TITLE_HEIGHT+'px', cursor:'pointer', position:'relative', width: 'calc(100% - 17px)', float:'left', 'padding-top':'1.5px', 'font-weight':'bold', 'white-space': 'nowrap', color: colors.SIDEPANEL_LABEL, overflow:'hidden' }); sidePanel.header.append(sidePanel.collapseDiv); sidePanel.header.append(sidePanel.label); sidePanel.header.on('click', function(event) { var i, numUncollapsed = 0; if (sidePanel.collapsed) { var heightToSteal = 0, heightTaken = 0, curHeightTaken; sidePanel.collapsed = false; sidePanel.collapseDiv.removeClass('ui-icon-triangle-1-e').addClass('ui-icon-triangle-1-s'); for (i=0; i<sidePanels.length; i++) { if (sidePanels[i].panel==sidePanel) continue; if (!sidePanels[i].panel.collapsed) { numUncollapsed++; heightToSteal += sidePanels[i].panel.height; } } if (numUncollapsed>0) { for (i=0; i<sidePanels.length; i++) { if (sidePanels[i].panel==sidePanel) continue; if (!sidePanels[i].panel.collapsed) { curHeightTaken = sidePanels[i].panel.height/(numUncollapsed+1); sidePanels[i].panel.height -= curHeightTaken; heightTaken += curHeightTaken; } } sidePanel.height += heightTaken; } else { sidePanel.height = sidePanel.uncollapse; } } else { sidePanel.collapsed = true; sidePanel.collapseDiv.removeClass('ui-icon-triangle-1-s').addClass('ui-icon-triangle-1-e'); for (i=0; i<sidePanels.length; i++) { if (sidePanels[i].panel==sidePanel) continue; if (!sidePanels[i].panel.collapsed) numUncollapsed++; } if (numUncollapsed>0) { for (i=0; i<sidePanels.length; i++) { if (sidePanels[i].panel==sidePanel) continue; if (!sidePanels[i].panel.collapsed) sidePanels[i].panel.height += sidePanel.height/numUncollapsed; } } sidePanel.uncollapse = sidePanel.height; sidePanel.height = WIDGET_TITLE_HEIGHT; } that.panelResize(); }); }, createPanel = function(sidePanel) { sidePanel.panel.header = $('<div/>') .css({ width:that.sidePanelWidth+'px', top:sidePanel.top+'px', position:'absolute' }).addClass('moduleHeader'); sidePanel.panel.label = $('<div/>') .css({ position:'absolute', left:'2px', top:'1px' }).text(sidePanel.label); sidePanel.panel.canvas = $('<div/>') .css({ position:'absolute', top:WIDGET_TITLE_HEIGHT+'px', right:'0px', 'padding-top':'1.5px', width:that.sidePanelWidth+'px', height:(sidePanel.height-WIDGET_TITLE_HEIGHT)+'px', overflow:'hidden', 'border-left': BORDER_STYLE, cursor: 'default' }); jqContainer.append(sidePanel.panel.header).append(sidePanel.panel.canvas); }, makeDraggable = function(upperPanel, sidePanel) { sidePanel.header.draggable({ axis:'y', helper: 'clone', start: function(event, ui) { if (upperPanel.collapsed||sidePanel.collapsed) return false; startY = event.clientY; }, stop: function(event, ui) { var endY = event.clientY, delta = endY-startY; if (sidePanel.height-delta<WIDGET_TITLE_HEIGHT) delta = sidePanel.height-WIDGET_TITLE_HEIGHT; if (upperPanel.height+delta<WIDGET_TITLE_HEIGHT) delta = WIDGET_TITLE_HEIGHT-upperPanel.height; sidePanel.height -= delta; upperPanel.height += delta; that.panelResize(); } }); }; //add the side panels for (var i=0; i<sidePanels.length; i++) { var panel = sidePanels[i]; panel.top = getUpper(panel,'top'); panel.height = getUpper(panel,'height'); createPanel(panel); makeCollapsible(sidePanels[i].panel); if (i>0) { makeDraggable(sidePanels[i-1].panel,panel.panel); } } //add other elements this.detailsCanvas = $('<div/>') .css({ 'background':'url(\'img/table.png\')', 'background-position':'center', 'background-repeat':'no-repeat', 'background-size':'100% 100%', position:'absolute', height:this.detailsHeight+'px', right:this.sidePanelWidth+'px', left:'0px', bottom:'0px', overflow:'auto', 'border-top':BORDER_STYLE, 'border-right':BORDER_STYLE, cursor: 'default' }); jqContainer.append(this.detailsCanvas); this.searchToggleButton = $('<div/>') .button({ text:false, disabled:true, icons:{ primary:'ui-icon-triangle-1-e' }, label:'Advanced controls (disabled)' }) .css({ position:'absolute', top:WIDGET_TITLE_HEIGHT+4+'px', left:'2px', margin:'0px', width:'20px', height:'20px', display: 'none' //TODO remove }) .click(function() { if (that.isAdvancedSearchMode) { that.onSimpleSearch(); } else { that.onAdvancedSearch(); } }); jqContainer.append(this.searchToggleButton); //resize for side panel this.resizeBar = $('<div/>') .css({ position:'absolute', bottom:'0px', top:'0px', width:'3px', right:this.sidePanelWidth+'px', background:colors.APPWIDGET_RESIZE_BAR, cursor:'ew-resize' }) .draggable({ axis:'x', cursor: 'ew-resize', helper: 'clone', start: function(event, ui) { startX = event.clientX; }, stop: function(event, ui) { var endX = event.clientX, w = that.sidePanelWidth-(endX-startX); if (w<10) w = 10; that.sidePanelWidth = w; amplify.store('sidePanelWidth', w); that.panelResize(); } }); jqContainer.append(this.resizeBar); //resize for details table this.detailResizeBar = $('<div/>') .css({ position:'absolute', bottom:this.detailsHeight+'px', height:'3px', left:'0px', right:this.sidePanelWidth+'px', background:colors.APPWIDGET_RESIZE_BAR, cursor:'ns-resize' }) .draggable({ axis:'y', cursor: 'ns-resize', helper: 'clone', start: function(event, ui) { startY = event.clientY; }, stop: function(event, ui) { var endY = event.clientY, h = that.detailsHeight-(endY-startY); if (h<WIDGET_TITLE_HEIGHT) h = WIDGET_TITLE_HEIGHT; that.detailsHeight = h; amplify.store('detailsHeight', h); that.panelResize(); } }); jqContainer.append(this.detailResizeBar); }, onSimpleSearch: function() { var that = this; this.graphHeader.animate({left:'0px'}, TRANSITION_TIME/2); this.graphCanvasContainer.animate({left:'0px'}, TRANSITION_TIME/2, function() { that.graphCanvasContainer.resize(); }); this.searchToggleButton.animate({left:'2px'}, TRANSITION_TIME/2, function() { that.searchToggleButton.button({ icons:{ primary:'ui-icon-triangle-1-e' }, label:'Show advanced controls' }); }); this.graphPropertiesCanvas.animate({width:'0px'}, TRANSITION_TIME/2, function() { that.simpleSearchContainer.animate({top:WIDGET_TITLE_HEIGHT+'px', opacity:1}, TRANSITION_TIME/2); }); this.isAdvancedSearchMode = false; }, doSimpleSearch: function(searchStr,clusterType) { var that = this; this.softClear(); this.graphWidget.displayLoader(); this.pagingPanel.hidePagingControls(); this.graphWidget.simpleGraph(baseUrl, searchStr, clusterType, function(graph) { that.pagingPanel.setFullGraph(graph, null, null, clusterType); that.nodeSummaryPanel.canvas.empty(); that.nodeSummary = new nodeSummary.createWidget(that,baseUrl,graph); var clusterid = that.nodeSummary.centerNode.id; that.displayDetailsSpinners(); that.graphWidget.markSelectedCluster(clusterid); getPreclusterDetails(baseUrl, clusterType, clusterid, function(response) { that.showClusterDetails(response, that.nodeSummary.centerNode.label); that.nodeDetails[clusterid] = response; }); }, function() { alert('Error fetching graph'); that.softClear(); }); }, fetchClusterId: function(clusterid,clusterType) { var that = this; this.softClear(); this.graphWidget.displayLoader(); this.pagingPanel.hidePagingControls(); this.graphWidget.fetchClusterId(baseUrl, clusterid, clusterType, function(graph) { var title = graph.nodes[0].label; that.pagingPanel.setFullGraph(graph, null, null, clusterType); that.nodeSummaryPanel.canvas.empty(); that.nodeSummary = new nodeSummary.createWidget(that,baseUrl,graph); var clusterid = that.nodeSummary.centerNode.id; that.displayDetailsSpinners(); getPreclusterDetails(baseUrl, clusterType, clusterid, function(response) { that.showClusterDetails(response, title); that.nodeDetails[clusterid] = response; }); that.graphWidget.markSelectedCluster(clusterid); }, function() { alert('Error fetching graph'); that.softClear(); }); }, redirect: function(attribute, value, callback) { var that = this, $dSpinner = $('#details-spinner'); this.table.mainDiv.css('display','none'); $dSpinner.css('display',''); rest.get(baseUrl + 'rest/attributeDetails/getattrid/'+attribute+'/'+value, "get Attribute ID", function (response) { if(response) { var caseid; if (that.buildCase.currentCase && that.buildCase.currentCase.case_id) { caseid = that.buildCase.currentCase.case_id; } window.open(baseUrl + 'graph.html?attributeid=' + response + (caseid ? '&case_id=' + caseid : ''), '_self'); } else { that.table.mainDiv.css('display','inline'); $dSpinner.css('display','none'); alert('cluster for ' + attribute + ': ' + value + ' could not be found.'); callback(false); } }, function () { alert('error fetching cluster for ' + attribute + ': ' + value); callback(false); }); }, fetchAttribute: function(attribute, value) { var that = this; this.softClear(); this.graphWidget.displayLoader(); this.pagingPanel.hidePagingControls(); this.graphWidget.fetchAttribute(baseUrl, attribute, value, function(graph) { that.graphWidget.ATTRIBUTE_MODE = true; that.graphWidget.createControlsCanvas(); that.pagingPanel.setFullGraph(graph, null, null, "attribute"); that.graphWidget.selectNode(graph.nodes[0].id); that.displayDetailsSpinners(); getAttributeDetails(baseUrl, attribute, value, function(response) { that.showClusterDetails(response, graph.nodes[0].label); }); }, function() { alert('Error fetching graph'); that.softClear(); }); }, fetchAttributeId: function(attributeid) { var that = this; this.softClear(); this.graphWidget.displayLoader(); this.pagingPanel.hidePagingControls(); this.graphWidget.fetchAttributeId(baseUrl, attributeid, function(graph) { if (graph) { var title = graph.nodes[0].label; that.pagingPanel.setFullGraph(graph, null, null, "attribute"); that.nodeSummaryPanel.canvas.empty(); that.nodeSummary = new nodeSummary.createWidget(that, baseUrl, graph); that.displayDetailsSpinners(); that.visitedNodes.push(attributeid); getAttributeIdDetails(baseUrl, attributeid, function (response) { that.showClusterDetails(response, title); that.nodeDetails[attributeid] = response; }); that.graphWidget.markSelectedCluster(attributeid); that.graphWidget.markVisitedNodes(that.visitedNodes); } else { alert('Error fetching graph'); that.softClear(); } }, function() { alert('Error fetching graph'); that.softClear(); }); }, fetchImageGraph: function(imageid) { var that = this; this.softClear(); this.graphWidget.displayLoader(); this.pagingPanel.hidePagingControls(); this.graphWidget.fetchImageId(baseUrl, imageid, function(graph) { var title = graph.nodes[0].label; that.pagingPanel.setFullGraph(graph, null, null, 'org'); that.nodeSummaryPanel.canvas.empty(); that.nodeSummary = new nodeSummary.createWidget(that,baseUrl,graph); that.displayDetailsSpinners(); var clusterid = that.nodeSummary.centerNode.id; getPreclusterDetails(baseUrl, 'org', clusterid, function(response) { that.showClusterDetails(response, title); that.nodeDetails[clusterid] = response; that.table.filterImage(imageid); }); that.graphWidget.markSelectedCluster(clusterid); }, function() { alert('Error fetching graph'); that.softClear(); }); }, onAdvancedSearch: function() { var that = this; this.simpleSearchContainer.animate({top:'-50px', opacity:0}, TRANSITION_TIME/2, function() { that.graphHeader.animate({left:'300px'}, TRANSITION_TIME/2); that.graphCanvasContainer.animate({left:'300px'}, TRANSITION_TIME/2, function() { that.graphCanvasContainer.resize(); }); that.graphPropertiesCanvas.animate({width:'300px'}, TRANSITION_TIME/2); that.searchToggleButton.animate({left:(300+2)+'px'}, TRANSITION_TIME/2,function(){ that.searchToggleButton.button({ icons:{ primary:'ui-icon-triangle-1-w' }, label:'Show simple controls' }); }); }); this.isAdvancedSearchMode = true; }, createGraphCanvas: function() { var that = this, jqContainer = $(container), $logout = $('<div/>') .text('Logout') .button() .addClass('logoutButton') .css({ position:'absolute', top:'1px', right:'-3.5px', height:'14px', padding: '.1em .5em' }) .on('click',function(event) { window.location.href = 'OpenAdsLogout.jsp'; }); this.graphHeader = $('<div/>') .css({ height:WIDGET_TITLE_HEIGHT+'px', top:'0px', left:'0px', right:this.sidePanelWidth, position:'absolute', 'border-left': BORDER_STYLE, 'border-right': BORDER_STYLE }).addClass('moduleHeader'); this.graphLabel = $('<div/>') .css({ position:'absolute', left:'2px', top:'1px' }); this.graphHeader.append(this.graphLabel).append($logout); jqContainer.append(this.graphHeader); this.graphCanvasContainer = $('<div/>') .css({ 'background':'url(\'img/graph.png\')', 'background-position':'center', 'background-repeat':'no-repeat', position:'absolute', top:WIDGET_TITLE_HEIGHT+'px', left:'0px', right:this.sidePanelWidth+'px', bottom:this.detailsHeight+'px', 'border-left': BORDER_STYLE, 'border-right': BORDER_STYLE, overflow:'hidden' }); jqContainer.append(this.graphCanvasContainer); this.graphWidget = graph.createWidget(this, baseUrl, function(event, datasetName, clustersetName, preclusterType) { var clusterId = event.data.id; if (event.eventType === 'dblclick') { if (datasetName && clustersetName) { that.displayDetailsSpinners(); getClusterDetails(baseUrl, datasetName, clustersetName, clusterId, function (response) { that.showClusterDetails(response, clustersetName); }); } else if (preclusterType) { if (preclusterType == 'attribute') { that.fetchAttributeId(clusterId); } else { that.fetchClusterId(clusterId, preclusterType); } } else if (event.data.fields) { var html = ''; for (var field in event.data.fields) { html += '<BR/><B>' + field + ':</B>' + ui_util.escapeHtml(event.data.fields[field]); } that.detailsCanvas.html(html); } } else if (event.eventType === 'click') { that.updatePanels(clusterId); } }); this.graphLabel.text('Ads grouped by ' + (this.graphWidget.ATTRIBUTE_MODE?'Attribute':'Entity')) }, updatePanels: function(nodeId) { var that = this, update = function () { that.nodeSummaryPanel.canvas.empty(); that.nodeSummary = new nodeSummary.createWidget(that,baseUrl,that.graphWidget.linkData, nodeId); if(!that.nodeDetails[nodeId].label) { that.nodeDetails[nodeId].label = that.graphWidget.linkData.nodeMap[nodeId].label; } that.showClusterDetails(that.nodeDetails[nodeId]); }; this.displayDetailsSpinners(); setTimeout(function() { if(!that.nodeDetails[nodeId]) { if(that.graphWidget.ATTRIBUTE_MODE) { getAttributeIdDetails(baseUrl, nodeId, function(response) { that.nodeDetails[nodeId] = response; update(); }); } else { getPreclusterDetails(baseUrl, 'org', nodeId, function(response) { that.nodeDetails[nodeId] = response; update(); }); } } else { update(); } }, 10); }, createSimpleSearchCanvas: function() { this.simpleSearchContainer = $('<div/>') .css({ position:'absolute', top:WIDGET_TITLE_HEIGHT+'px', left:'26px', width:SIMPLE_SEARCH_WIDTH + 'px', height:SIMPLE_SEARCH_HEIGHT + 'px', border:'1px solid ' + colors.BORDER_DARK, overflow:'hidden', opacity:1, display: 'none' //TODO remove }); $(container).append(this.simpleSearchContainer); this.simpleSearch = simplesearchpanel.createWidget(this.simpleSearchContainer, this, baseUrl); }, createGraphPropertiesCanvas: function() { var jqContainer = $(container); this.graphPropertiesHeader = $('<div/>') .css({ height:WIDGET_TITLE_HEIGHT+'px', width:'300px', top:'0px', left:'0px', position:'absolute' }).addClass('moduleHeader'); this.graphPropertiesLabel = $('<div/>') .css({ position:'absolute', left:'2px', top:'1px' }).text('Advanced Search'); this.graphPropertiesHeader.append(this.graphPropertiesLabel); jqContainer.append(this.graphPropertiesHeader); this.graphPropertiesCanvas = $('<div/>') .css({ top:WIDGET_TITLE_HEIGHT+'px', width:'0px', bottom:this.detailsHeight+'px', left:'0px', position:'absolute', 'overflow-y':'auto' }); jqContainer.append(this.graphPropertiesCanvas); this.searchPanel = searchpanel.createWidget(this.graphPropertiesCanvas, this, baseUrl); }, displayLoader: function() { this.graphWidget.displayLoader(); }, showClusterDetails: function(response, title) { var headerList = [], objectData = [], that = this, i = 0, fields; if (!title && response.label) { title = response.label; } for (i; i<response.memberDetails.length; i++) { fields = response.memberDetails[i]; if (i==0) { for (var field in fields) { if (fields.hasOwnProperty(field)) { headerList.push(field); } } } fields.locationLabel = fields.location; objectData.push(fields); } //add node link click function this.graphWidget.selectLinksFn = function(event) { var i, j, detailsList, found1, found2, val1 = event.data.source.label, val2 = event.data.target.label, attributes = ['phone', 'email', 'websites'], result = []; for(i=0;i<objectData.length;i++) { found1 = found2 = false; for(j=0;j<attributes.length;j++) { detailsList = objectData[i][attributes[j]]; if (!found1 && detailsList && detailsList.indexOf(val1) > -1) { found1 = true; } if (!found2 && detailsList && detailsList.indexOf(val2) > -1) { found2 = true; } if (found1 && found2) { result.push(objectData[i].id); break; } } } that.selection.set('graph', result); }; this.movementPanel.canvas.css('background-image', ''); this.wordCloudPanel.canvas.css('background-image', ''); this.mapPanel.canvas.css('background-image', ''); this.attributesPanel.canvas.css('background-image', ''); this.detailsCanvas.css('background-image', ''); this.detailsCanvas.empty(); if (this.table) { this.table.destroyTable(); } this.table = table.createWidget(baseUrl, this.detailsCanvas, headerList, objectData, title, this.selection); this.table.searchFn = function(attribute, value, callback) { if (attribute=='images') { that.fetchImageGraph(value); } else { that.redirect(attribute, value, callback); } }; if (!this.buildCase) { var caseId = decodeURIComponent(ui_util.getParameter('case_id')); this.buildCase = new buildCase.createWidget(this.buildCasePanel.canvas, baseUrl); if(caseId && caseId!=undefined && caseId!=null && caseId!='null') { this.buildCase.loadCaseContentsURL(caseId); } } this.buildCase.resize(this.sidePanelWidth, this.buildCasePanel.canvas.height()); this.movementPanel.canvas.empty(); if (this.timeline) { this.timeline.destroy(); } this.timeline = new timeline.createWidget(this.movementPanel.canvas.get(0), objectData, this.selection); this.timeline.resize(this.sidePanelWidth, this.movementPanel.height); this.mapPanel.canvas.empty(); this.mapObj = new map.createWidget(baseUrl, this.mapPanel.canvas.get(0), objectData, this.selection); this.mapObj.resize(this.sidePanelWidth, this.mapPanel.height); this.wordCloudPanel.canvas.empty(); if (this.wordCloud) { this.wordCloud.destroy(); } this.wordCloud = new wordcloud.createWidget(baseUrl, this.wordCloudPanel.canvas, objectData, this.selection); this.wordCloud.resize(this.sidePanelWidth, this.wordCloudPanel.canvas.height()); this.attributesPanel.canvas.empty(); if (this.attrChart) { this.attrChart.destroy(); } this.attrChart = new attr_chart.createWidget(this.attributesPanel.canvas, objectData); this.attrChart.resize(this.sidePanelWidth, this.attributesPanel.canvas.height()); this.selection.listen('table', function(selectedIds) { that.table.selectionChanged(selectedIds);}); this.selection.listen('timeline', function(selectedIds) { that.timeline.selectionChanged(selectedIds);}); this.selection.listen('map', function(selectedIds) { that.mapObj.selectionChange(selectedIds) }); }, panelResize: function() { var totalHeight = this.nodeSummaryPanel.height + this.buildCasePanel.height + this.movementPanel.height + this.mapPanel.height + this.wordCloudPanel.height + this.attributesPanel.height, overflow, delta; if (totalHeight>this.height && this.nodeSummaryPanel.height>WIDGET_TITLE_HEIGHT) { overflow = totalHeight-this.height; delta = Math.min(overflow,this.nodeSummaryPanel.height-WIDGET_TITLE_HEIGHT); this.nodeSummaryPanel.height -= delta; totalHeight -= delta; } if (totalHeight>this.height && this.buildCasePanel.height>WIDGET_TITLE_HEIGHT) { overflow = totalHeight-this.height; delta = Math.min(overflow,this.buildCasePanel.height-WIDGET_TITLE_HEIGHT); this.buildCasePanel.height -= delta; totalHeight -= delta; } if (totalHeight>this.height && this.wordCloudPanel.height>WIDGET_TITLE_HEIGHT) { overflow = totalHeight-this.height; delta = Math.min(overflow,this.wordCloudPanel.height-WIDGET_TITLE_HEIGHT); this.wordCloudPanel.height -= delta; totalHeight -= delta; } if (totalHeight>this.height && this.attributesPanel.height>WIDGET_TITLE_HEIGHT) { overflow = totalHeight-this.height; delta = Math.min(overflow,this.attributesPanel.height-WIDGET_TITLE_HEIGHT); this.attributesPanel.height -= delta; totalHeight -= delta; } if (totalHeight>this.height && this.mapPanel.height>WIDGET_TITLE_HEIGHT) { overflow = totalHeight-this.height; delta = Math.min(overflow,this.mapPanel.height-WIDGET_TITLE_HEIGHT); this.mapPanel.height -= delta; totalHeight -= delta; } if (totalHeight>this.height && this.movementPanel.height>WIDGET_TITLE_HEIGHT) { overflow = totalHeight-this.height; delta = Math.min(overflow,this.movementPanel.height-WIDGET_TITLE_HEIGHT); this.movementPanel.height -= delta; totalHeight -= delta; } if (totalHeight<this.height && !this.nodeSummaryPanel.collapsed) { this.nodeSummaryPanel.height += this.height-totalHeight; totalHeight = this.height; } if (totalHeight<this.height && !this.buildCasePanel.collapsed) { this.buildCasePanel.height += this.height-totalHeight; totalHeight = this.height; } if (totalHeight<this.height && !this.attributesPanel.collapsed) { this.attributesPanel.height += this.height-totalHeight; totalHeight = this.height; } if (totalHeight<this.height && !this.wordCloudPanel.collapsed) { this.wordCloudPanel.height += this.height-totalHeight; totalHeight = this.height; } if (totalHeight<this.height && !this.mapPanel.collapsed) { this.mapPanel.height += this.height-totalHeight; totalHeight = this.height; } if (totalHeight<this.height && !this.movementPanel.collapsed) { this.movementPanel.height += this.height-totalHeight; totalHeight = this.height; } this.nodeSummaryPanel.header.css({width:this.sidePanelWidth + 'px'}); this.nodeSummaryPanel.canvas.css({width:this.sidePanelWidth + 'px', height:(this.nodeSummaryPanel.height-WIDGET_TITLE_HEIGHT) + 'px'}); this.buildCasePanel.header.css({width:this.sidePanelWidth + 'px', top:this.nodeSummaryPanel.height + 'px'}); this.buildCasePanel.canvas.css({width:this.sidePanelWidth + 'px', top:this.nodeSummaryPanel.height+WIDGET_TITLE_HEIGHT + 'px',height:(this.buildCasePanel.height-WIDGET_TITLE_HEIGHT) + 'px'}); this.movementPanel.header.css({width:this.sidePanelWidth + 'px', top:this.nodeSummaryPanel.height+this.buildCasePanel.height + 'px'}); this.movementPanel.canvas.css({width:this.sidePanelWidth+'px', top:this.nodeSummaryPanel.height+this.buildCasePanel.height+WIDGET_TITLE_HEIGHT + 'px', height:(this.movementPanel.height-WIDGET_TITLE_HEIGHT) + 'px'}); this.mapPanel.header.css({width:this.sidePanelWidth+'px', top:this.nodeSummaryPanel.height+this.buildCasePanel.height+this.movementPanel.height+'px'}); this.mapPanel.canvas.css({width:this.sidePanelWidth+'px', top:this.nodeSummaryPanel.height+this.buildCasePanel.height+this.movementPanel.height+WIDGET_TITLE_HEIGHT + 'px', height:(this.mapPanel.height-WIDGET_TITLE_HEIGHT)+'px'}); this.wordCloudPanel.header.css({width:this.sidePanelWidth+'px', top:this.nodeSummaryPanel.height+this.buildCasePanel.height+this.movementPanel.height+this.mapPanel.height+'px'}); this.wordCloudPanel.canvas.css({width:this.sidePanelWidth+'px', top:this.nodeSummaryPanel.height+this.buildCasePanel.height+this.movementPanel.height+this.mapPanel.height + WIDGET_TITLE_HEIGHT + 'px', height:(this.wordCloudPanel.height-WIDGET_TITLE_HEIGHT)+'px'}); this.detailsCanvas.css({right:this.sidePanelWidth+'px',height:this.detailsHeight+'px'}); this.attributesPanel.header.css({width:this.sidePanelWidth+'px', top:this.nodeSummaryPanel.height+this.buildCasePanel.height+this.movementPanel.height+this.mapPanel.height+this.wordCloudPanel.height+'px'}); this.attributesPanel.canvas.css({width:this.sidePanelWidth+'px', top:this.nodeSummaryPanel.height+this.buildCasePanel.height+this.movementPanel.height+this.mapPanel.height+this.wordCloudPanel.height+WIDGET_TITLE_HEIGHT+'px', height:(this.attributesPanel.height-WIDGET_TITLE_HEIGHT)+'px'}); this.resizeBar.css({right:this.sidePanelWidth+'px'}); this.detailResizeBar.css({bottom:this.detailsHeight+'px',right:this.sidePanelWidth+'px'}); if(this.table) this.table.updateSelectedOverlay(); if (this.timeline) this.timeline.resize(this.sidePanelWidth, this.movementPanel.canvas.height()); if (this.mapObj) this.mapObj.resize(this.sidePanelWidth, this.mapPanel.canvas.height()); if (this.wordCloud) this.wordCloud.resize(this.sidePanelWidth, this.wordCloudPanel.canvas.height()); if (this.attrChart) this.attrChart.resize(this.sidePanelWidth, this.attributesPanel.canvas.height()); this.graphHeader.css({right:this.sidePanelWidth}); this.graphCanvasContainer.css({right:this.sidePanelWidth+'px',bottom:this.detailsHeight+'px'}); if (this.graphWidget) this.graphWidget.resize(this.width-this.sidePanelWidth, this.graphCanvasContainer.height()); if (this.graphPropertiesCanvas) this.graphPropertiesCanvas.css({bottom:this.detailsHeight+'px'}); this.amplifyUpdate(); }, amplifyUpdate: function() { var amplifyStore = function (panel, amp) { var amplifyStore = { height: panel.height, uncollapse: panel.uncollapse, collapsed: panel.collapsed }; amplify.store(amp, amplifyStore); }; amplifyStore(this.nodeSummaryPanel, 'nodeSummaryPanel'); amplifyStore(this.buildCasePanel, 'buildCasePanel'); amplifyStore(this.movementPanel, 'movementPanel'); amplifyStore(this.mapPanel, 'mapPanel'); amplifyStore(this.wordCloudPanel,'wordCloudPanel'); amplifyStore(this.attributesPanel,'attributesPanel'); }, resize: function(w,h) { this.width = w; this.height = h; this.panelResize(); if (this.graphWidget) { this.graphWidget.resize(w,h); } }, displayDetailsSpinners: function() { this.movementPanel.canvas.empty(); this.wordCloudPanel.canvas.empty(); this.mapPanel.canvas.empty(); this.attributesPanel.canvas.empty(); this.detailsCanvas.empty(); this.movementPanel.canvas.css({'background' : 'url("./img/ajaxLoader.gif") no-repeat center center'}); this.wordCloudPanel.canvas.css({'background' : 'url("./img/ajaxLoader.gif") no-repeat center center'}); this.mapPanel.canvas.css({'background' : 'url("./img/ajaxLoader.gif") no-repeat center center'}); this.attributesPanel.canvas.css({'background' : 'url("./img/ajaxLoader.gif") no-repeat center center'}); this.detailsCanvas.css({'background' : 'url("./img/ajaxLoader.gif") no-repeat center center'}); }, softClear : function() { this.graphWidget.empty(); this.movementPanel.canvas.empty(); this.mapPanel.canvas.empty(); this.attributesPanel.canvas.empty(); this.detailsCanvas.empty(); this.graphCanvasContainer.css('background-image', ''); this.movementPanel.canvas.css('background-image', ''); this.wordCloudPanel.canvas.css('background-image', ''); this.mapPanel.canvas.css('background-image', ''); this.attributesPanel.canvas.css('background-image', ''); this.detailsCanvas.css('background-image', ''); //this.movementPanel.canvas.append(this.movementPanel.description); this.selection.clear(); } }; linkWidgetObj.init(); return linkWidgetObj; }; return { createWidget:createWidget } });
<script> let power = 4, state = { w: 520, maxWidth:520, h: 260, origin: [270, 130], background: [0,61,93], renderer: 'svg', ppm: 300, items: [ // real lens and fake one { type: 'thinlens', id: 'L#1', power: 3, aperture: 0.5, axis: [1,0], position: [0,0.001], ui: { xlock: true, ylock: true}, style: { strokeWeight: 3 } }, // a ray { type: 'divergent light', position: [-0.6,0.3], id: 'rule3', off: false, target: [0,0], spread: 0, raycount: 1, ui: {xlock:[-Infinity, -1/power]}, style: { stroke: [220,220,0], strokeWeight: 2, arrows: ['50%',''] } }, // object & image { type: 'js', init(state) { let p = findObject(state, 'rule3').position findObject(state,'object').start = [p[0],0] findObject(state,'object').end = [...p] let img = 1/(1/p[0]+power) findObject(state,'image').start = [img,0] findObject(state,'image').end = [img, p[1]*img/p[0]] findObject(state, 'end').position = [img,-5,img,5] } }, { type: 'barrier', id: 'end', position: [1,-5, 1, 5], style: { visible:false } }, { type: 'dimension', id: 'object', start: [], end: [], label: ' ', style: { stroke: [255, 255, 255], strokeWeight: 5, arrowLength: 10, arrowWidth: 5, z_order:-1 } }, { type: 'dimension', id: 'image', start: [], end: [], label: ' ', style: { stroke: [200, 200, 255], strokeWeight: 5, arrowLength: 10, arrowWidth: 5, z_order:-1, visible: true } }, // optic axis { type: 'dimension', start: [-2,0], end: [2,0], label: ' ', style: { stroke: [255, 255, 255], strokeDash: [5,5] } }, ] }; makeP5App(state)(window) </script>
const restify = require('restify-plugins'); var client = restify.createJsonClient({ url : 'http://localhost:3000' }); client.post('/foo', {bar : 'bar'}, function (err, req, res, obj) { if(err){ console.log(err.message); } });
// Learn more about this file at: // https://victorzhou.com/blog/build-an-io-game-part-1/#5-client-rendering import { debounce } from 'throttle-debounce'; import { getAsset } from './assets'; import { getCurrentState } from './state'; import { getCurrentInput } from './input'; const Constants = require('../shared/constants'); const { PLAYER_RADIUS, PLAYER_MAX_HP, BULLET_RADIUS, MAP_SIZE } = Constants; const BULLET_TRAIL = {} // Get the canvas graphics context const canvas = document.getElementById('game-canvas'); const context = canvas.getContext('2d'); setCanvasDimensions(); function setCanvasDimensions() { // On small screens (e.g. phones), we want to "zoom out" so players can still see at least // 800 in-game units of width. const scaleRatio = Math.max(1, 800 / window.innerWidth); canvas.width = scaleRatio * window.innerWidth; canvas.height = scaleRatio * window.innerHeight; } window.addEventListener('resize', debounce(40, setCanvasDimensions)); function render() { const { me, others, bullets } = getCurrentState(); if (!me) { return; } // Draw background renderBackground(me.x, me.y); // Draw boundaries context.strokeStyle = '#535353'; context.shadowColor = '#3A3A3A'; context.shadowBlur = 15; context.lineWidth = 4; context.strokeRect(canvas.width / 2 - me.x, canvas.height / 2 - me.y, MAP_SIZE, MAP_SIZE); // Draw all bullets bullets.forEach(renderBullet.bind(null, me)); const bulletIds = bullets.map(b => b.id); const keysToDelete = [] for (let key in Object.keys(BULLET_TRAIL)) { if (!bulletIds.includes(key)) { keysToDelete.push(key); } } for (let key of keysToDelete) { delete BULLET_TRAIL[key]; } // Draw all players renderPlayer(me, me); others.forEach(otherPlayer => renderOtherPlayer(me, otherPlayer)); } function renderBackground(x, y) { // const imagebg = new Image(); // imagebg.src = backgroundImage; // const bgimagepattern = context.createPattern(imagebg, 'repeat'); const backgroundX = MAP_SIZE / 2 - x + canvas.width / 2; const backgroundY = MAP_SIZE / 2 - y + canvas.height / 2; const backgroundGradient = context.createRadialGradient( backgroundX, backgroundY, MAP_SIZE / 10, backgroundX, backgroundY, MAP_SIZE / 2, ); backgroundGradient.addColorStop(0, '#333'); backgroundGradient.addColorStop(1, '#000'); context.fillStyle = backgroundGradient; context.fillRect(0, 0, canvas.width, canvas.height); } const CURRENT_PLAYER = {} // Renders a ship at the given coordinates function renderPlayer(me, player) { const { id, x, y, direction } = player; const canvasX = canvas.width / 2 + x - me.x; const canvasY = canvas.height / 2 + y - me.y; const striperID = hasNaNAtEnd(id) ? id.slice(0, id.length - 3) : id; if (!CURRENT_PLAYER[striperID]) { CURRENT_PLAYER[striperID] = [{x: x, y:y, mex: me.x, mey: me.y}] }else { if (CURRENT_PLAYER[striperID].length > 20) { CURRENT_PLAYER[striperID].shift(); } CURRENT_PLAYER[striperID].push({x:x, y:y, mex: me.x, mey: me.y}) } const numPrevPlayerTrail = CURRENT_PLAYER[striperID].length; const opacityIncrease = 1 / numPrevPlayerTrail; let count = 0; for (let obj of CURRENT_PLAYER[striperID]) { if (count > 8) { count += 1; continue; } const {x, y, mex, mey} = obj; context.beginPath(); context.arc(canvas.width / 2 + x - me.x,canvas.height / 2 + y - me.y , 10, 0, 2 * Math.PI, true); const opacity = opacityIncrease * count; const styleString = "rgba(137, 196, 244, " + opacity.toString() + ")" context.fillStyle = styleString; context.fill(); count += 1; } // Draw ship context.save(); context.translate(canvasX, canvasY); context.rotate(direction); context.drawImage( getAsset('ship3.svg'), -PLAYER_RADIUS, -PLAYER_RADIUS, PLAYER_RADIUS * 2, PLAYER_RADIUS * 2, ); context.restore(); // Draw health bar context.fillStyle = 'white'; context.fillRect( canvasX - PLAYER_RADIUS, canvasY + PLAYER_RADIUS + 8, PLAYER_RADIUS * 2, 2, ); context.fillStyle = 'red'; context.fillRect( canvasX - PLAYER_RADIUS + PLAYER_RADIUS * 2 * player.hp / PLAYER_MAX_HP, canvasY + PLAYER_RADIUS + 8, PLAYER_RADIUS * 2 * (1 - player.hp / PLAYER_MAX_HP), 2, ); // Draw input field context.font = '18px DM Sans'; context.fillStyle = 'white'; context.textAlign = 'center'; const input = getCurrentInput() === '' ? 'Type an answer + enter' : getCurrentInput(); context.fillText(input, canvasX, canvasY + 56); } function hasNaNAtEnd(string) { const last3Char = string.slice(string.length - 3); return last3Char === 'NaN'; } const OTHER_PLAYERS = {} // Renders a ship at the given coordinates function renderOtherPlayer(me, player) { const { x, y, direction, id } = player; let user = null; const striperID = hasNaNAtEnd(id) ? id.slice(0, id.length - 3) : id; const otherPlayer = window.players[striperID]; if (otherPlayer || user) { user = otherPlayer; } const canvasX = canvas.width / 2 + x - me.x; const canvasY = canvas.height / 2 + y - me.y; if (!OTHER_PLAYERS[striperID]) { OTHER_PLAYERS[striperID] = [{x: x, y:y, mex: me.x, mey: me.y}] }else { if (OTHER_PLAYERS[striperID].length > 12) { OTHER_PLAYERS[striperID].shift(); } OTHER_PLAYERS[striperID].push({x:x, y:y, mex: me.x, mey: me.y}) } const numPrevPlayerTrail = OTHER_PLAYERS[striperID].length; const opacityIncrease = 1 / numPrevPlayerTrail; let count = 0; for (let obj of OTHER_PLAYERS[striperID]) { const {x, y, mex, mey} = obj; context.beginPath(); context.arc(canvas.width / 2 + x - me.x,canvas.height / 2 + y - me.y , 10, 0, 2 * Math.PI, true); const opacity = opacityIncrease * count; const styleString = "rgba(255, 69, 0, " + opacity.toString() + ")" context.fillStyle = styleString; context.fill(); count += 1; } // Draw ship context.save(); context.translate(canvasX, canvasY); context.rotate(direction); context.drawImage( getAsset('ship2.svg'), -PLAYER_RADIUS, -PLAYER_RADIUS, PLAYER_RADIUS * 2, PLAYER_RADIUS * 2, ); context.restore(); // Draw health bar context.fillStyle = 'white'; context.fillRect( canvasX - PLAYER_RADIUS, canvasY + PLAYER_RADIUS + 8, PLAYER_RADIUS * 2, 2, ); context.fillStyle = 'red'; context.fillRect( canvasX - PLAYER_RADIUS + PLAYER_RADIUS * 2 * player.hp / PLAYER_MAX_HP, canvasY + PLAYER_RADIUS + 8, PLAYER_RADIUS * 2 * (1 - player.hp / PLAYER_MAX_HP), 2, ); // setup font context.font = '26px DM Sans'; context.fillStyle = 'white'; context.textAlign = 'center'; // draw math question context.fillText(user.mathQuestion.mathString, canvasX, canvasY - 40); context.font = '14px DM Sans'; // draw draw username context.fillText(user.username, canvasX, canvasY + 48); } function renderBullet(me, bullet) { const { id, x, y } = bullet; const striperID = hasNaNAtEnd(id) ? id.slice(0, id.length - 3) : id; if (!BULLET_TRAIL[striperID]) { BULLET_TRAIL[striperID] = [{x: x, y:y, mex: me.x, mey: me.y}] }else { if (BULLET_TRAIL[striperID].length > 3) { BULLET_TRAIL[striperID].shift(); } BULLET_TRAIL[striperID].push({x:x, y:y, mex: me.x, mey: me.y}) } const numPrevBullets = BULLET_TRAIL[striperID].length; const opacityIncrease = 1 / numPrevBullets; let count = 0; for (let obj of BULLET_TRAIL[striperID]) { const {x, y, mex, mey} = obj; context.beginPath(); context.arc(canvas.width / 2 + x - me.x - BULLET_RADIUS,canvas.height / 2 + y - me.y - BULLET_RADIUS, 10, 0, 2 * Math.PI, true); const opacity = opacityIncrease * count; const styleString = "rgba(98, 54, 255, " + opacity.toString() + ")" context.fillStyle = styleString; context.fill(); count += 1; } context.drawImage( getAsset('bullet.svg'), canvas.width / 2 + x - me.x - BULLET_RADIUS, canvas.height / 2 + y - me.y - BULLET_RADIUS, BULLET_RADIUS * 2, BULLET_RADIUS * 2, ); } function renderMainMenu() { const t = Date.now() / 7500; const x = MAP_SIZE / 2 + 800 * Math.cos(t); const y = MAP_SIZE / 2 + 800 * Math.sin(t); renderBackground(x, y); } let renderInterval = setInterval(renderMainMenu, 1000 / 60); // Replaces main menu rendering with game rendering. export function startRendering() { clearInterval(renderInterval); renderInterval = setInterval(render, 1000 / 60); } // Replaces game rendering with main menu rendering. export function stopRendering() { clearInterval(renderInterval); renderInterval = setInterval(renderMainMenu, 1000 / 60); }
import React, {Component, PropTypes} from 'react'; import ListItem from 'material-ui/lib/lists/list-item'; class Channel extends Component { static propTypes = { name: PropTypes.string.isRequired, selected: PropTypes.bool.isRequired, onClick: PropTypes.func.isRequired } render() { const style = {}; if (this.props.selected) { style.backgroundColor = '#f0f0f0'; } return ( <ListItem primaryText={this.props.name} style={style} onClick={this.props.onClick} /> ); } } export default Channel;
import React, { useState, useEffect } from "react"; import { Typography } from "@material-ui/core"; import { IconButton } from "@material-ui/core"; import Input from "../../common/Input/Input"; import ExpansionPanel from "@material-ui/core/ExpansionPanel"; import ExpansionPanelSummary from "@material-ui/core/ExpansionPanelSummary"; import ExpansionPanelDetails from "@material-ui/core/ExpansionPanelDetails"; import Fab from "@material-ui/core/Fab"; import AddIcon from "@material-ui/icons/Add"; import DeleteIcon from "@material-ui/icons/Delete"; import CloudUploadIcon from '@material-ui/icons/CloudUpload'; import Button from '@material-ui/core/Button'; import InfoOutlinedIcon from '@material-ui/icons/InfoOutlined'; import InputLabel from '@material-ui/core/InputLabel'; import InputAdornment from '@material-ui/core/InputAdornment'; import FormControl from '@material-ui/core/FormControl'; import DialogTitle from '@material-ui/core/DialogTitle'; import Dialog from '@material-ui/core/Dialog'; import DialogContent from '@material-ui/core/DialogContent'; import MenuItem from '@material-ui/core/MenuItem'; import Select from '@material-ui/core/Select'; import moment from 'moment'; import CloseIcon from '@material-ui/icons/Close'; import FormUtils from "../../utils/formUtils"; import utils from "../../utils/utils"; import useStyles from "./BookingFormStyle"; import "./BookingForm.scss"; import ratemasterService from "../../services/ratemasterService"; import Loader from "../../common/Loader/Loader"; import taxService from "../../services/taxService"; import FormControlLabel from '@material-ui/core/FormControlLabel'; import Checkbox from '@material-ui/core/Checkbox'; import GuestNameDialog from './GuestNameDialog' const BookingForm = props => { const classes = useStyles(); let [expanded] = React.useState("panel1"); const { onFormSubmit, onInputChange: inputfun, onDatePickerChange: datefun, onSelectChange: selectfun, onSelectChange1: selectfun1, onAddRoom, onDeleteRoom, availableRooms, data, errors, options, options1, onFileSelect, onBack, shouldDisable, openDatePickerCheckIn, openDatePickerCheckOut, handleDatePicker, enableFileUpload, onSetPrice, handleFlatRateChange, updatedata, onCheckIn, setData, isDirtyroomSelected, isEdit, onHandleAdditionalGuest, additionalGuests } = props; console.log("errorsshouldDisable", errors, shouldDisable) const [loading, setLoading] = React.useState(false); const [openPriceModal, setOpenPriceModal] = React.useState(false) const [dayWiseRates, setDayWiseRates] = React.useState([]) const [formattedRates, setFormattedRates] = React.useState({}) const [planTypes, setPlanTypes] = React.useState([ { planType: "AP" }, { planType: "CP" }, { planType: "EP" }, { planType: "MAP" }, ]); const proofTypes = [ { label: "Passport", value: "Passport" } ] const [taxSlabs, setTaxSlabs] = React.useState([]); // const roomOptions = availableRooms.map(room => { // return { label: room.roomNumber, value: room.roomNumber }; // }); // data.rooms.map(roomId => // availableRooms.filter(room => { // if (room._id === roomId) selectedRooms.push(room); // return room; // }) // ); React.useEffect(() => { fetchTaxes() }, []) React.useEffect(() => { if (data["checkIn"] > data["checkOut"]) { return } fetchRates() }, [data["checkIn"], data["checkOut"]]) React.useEffect(() => { formatRates() }, [dayWiseRates, data.planType, data.flatRoomRate, data.roomCharges]) React.useEffect(() => { calculateBookingPrice(formattedRates, data.rooms) }, [data.rooms]) const fetchTaxes = async () => { setLoading(true) const taxSlabs = await taxService.getTaxSlabs("GST"); setTaxSlabs(taxSlabs); setLoading(false); }; const fetchRates = async () => { if (!data["checkIn"] || !data["checkOut"]) return setLoading(true); const dayRates = await ratemasterService.getDayWiseRate(data["checkIn"], data["checkOut"]); if (dayRates) { setDayWiseRates(dayRates) } console.log("----------------dayRates", dayRates) setLoading(false); } const formatRates = () => { const rates = {} dayWiseRates.forEach(el => { if (el.planType === data.planType && !rates[el.roomType]) { rates[el.roomType] = [] rates[el.roomType].push(el) } else if (el.planType === data.planType && rates[el.roomType]) { rates[el.roomType].push(el) } }) // .sort((a,b) => moment(a.date).isBefore(b.date)) Object.keys(rates).forEach(el => { // debugger let arr = rates[el] rates[el] = arr.sort((a, b) => { if (a.date > b.date) { return 1; } return -1; }) }) // console.log setFormattedRates(rates) calculateBookingPrice(rates, data.rooms) } const calculateBookingPrice = (rates, rooms) => { console.log("--------shouldDisable", shouldDisable, data.roomCharges) // debugger if (shouldDisable) return let price = data.flatRoomRate ? data.roomCharges : 0 console.log("rates, rooms", rates, rooms) const roomWiseRatesForBooking = [] let dates = data.flatRoomRate && daysBetweenDates(data.checkIn, data.checkOut) let nights = dates.length > 0 ? dates.length : 1 let divi = data.flatRoomRate && Number(nights) * Number(rooms.length) // console.log("data.roomCharges/divi",data.roomCharges/divi,data.roomCharges,divi) let singleRooomSingleNightRateT = data.flatRoomRate && data.roomCharges / divi; console.log("singleRooomSingleNightRateT", dates, singleRooomSingleNightRateT) rooms.forEach(room => { const bookingRate = { roomNumber: room.roomNumber, } const bookingRates = [] if (!data.flatRoomRate) { rates[room.roomType] && rates[room.roomType].forEach(dayrate => { // debugger price += parseInt(dayrate.rate) const slab = taxSlabs.filter(el => dayrate.rate > el.greaterThan && dayrate.rate <= (el.lessThanAndEqual || 9999999999)) let taxPercent; let tax; if (slab.length > 0) { taxPercent = slab[0].taxPercent tax = dayrate.rate * (slab[0].taxPercent / 100) } bookingRates.push({ date: dayrate.date, rate: dayrate.rate, extra: dayrate.extraRate, taxPercent, tax: Number(tax).toFixed(2) }) }) } else { let singleRooomSingleNightRate; const slab = taxSlabs.filter(el => Number(singleRooomSingleNightRateT) > Number(el.greaterThan) && Number(singleRooomSingleNightRateT) <= (Number(el.lessThanAndEqual) || 9999999999)) let taxPercent; let tax; if (slab.length > 0) { console.log("slab Price", slab) taxPercent = slab[0].taxPercent singleRooomSingleNightRate = (Number(singleRooomSingleNightRateT) / ((100 + Number(taxPercent)) / 100)).toFixed(2) // console.log("singleRooomSingleNightRate Price",singleRooomSingleNightRate) // const slab2 = taxSlabs.filter(el => singleRooomSingleNightRate>el.greaterThan && singleRooomSingleNightRate<= (el.lessThanAndEqual || 9999999999)) // if(Number(slab2[0].taxPercent) !== Number(taxPercent)){ // console.log("slab2 Price",slab2) // taxPercent = slab2[0].taxPercent // singleRooomSingleNightRate = (Number(singleRooomSingleNightRateT)/((100+Number(taxPercent))/100)).toFixed(2) // console.log("singleRooomSingleNightRate2 Price",singleRooomSingleNightRate) // } tax = (singleRooomSingleNightRate * (taxPercent / 100)).toFixed(2) } dates.forEach(el => { bookingRates.push({ date: el.toISOString(), rate: Number(singleRooomSingleNightRate).toFixed(2), extra: 0, taxPercent, tax: Number(tax).toFixed(2) }) }) } bookingRate.rates = bookingRates roomWiseRatesForBooking.push(bookingRate) }) console.log("Final Price", price, roomWiseRatesForBooking) onSetPrice(price, roomWiseRatesForBooking) }; const daysBetweenDates = (startDate, endDate) => { let dates = []; const currDate = moment(startDate).startOf("day"); //console.log(currDate) const lastDate = moment(endDate).startOf("day"); //console.log("lastDate",currDate,lastDate) while (currDate.add(1, "days").diff(lastDate) < 0) { dates.push(currDate.clone().toDate()); } dates.unshift(moment(startDate).toDate()); // dates.push(moment(endDate).toDate()); console.log(dates) return dates; } const handleChange = panel => (event, isExpanded) => { // setExpanded(isExpanded ? panel : false); }; const getInputArgObj = (id, label, type, shouldDisable) => { return { id, label, type, value: data[id], onChange: inputfun, error: errors[id], disabled: shouldDisable, }; }; const getDateArgObj = (id, label, type, minDate, shouldDisable, open) => { return { id, label, type, value: data[id], onChange: datefun, error: errors[id], minDate, disabled: shouldDisable, // open: open }; }; const getRoomOptions = roomType => { // if (availableRooms.length === 0) return []; const roomsByType = availableRooms.filter( room => room.roomType === roomType ); return roomsByType.map(room => { return { label: room.roomNumber, value: room.roomNumber, room }; }); }; const getPlanOptions = () => { return planTypes.map(plan => { return { label: plan.planType, value: plan.planType }; }); }; const getRoomTypeOptions = (roomtypes) => { return roomtypes.map(room => { return { label: room.roomType, value: room.roomType, key: room.roomType }; }); }; const checkRoomError = index => { if (errors.rooms && errors.rooms.length > 0) { const err = errors.rooms.find(error => error.index === index); return err ? err.message : null; } return null; }; console.log("*******formattedRates", formattedRates) //Type useEffect(() => { if (data.bookedBy === "Agent") { setIsAgent(true); setIsMember(false); console.log("Hello Agent") } else if (data.bookedBy === 'Head Office') { setisHeadOffice(true) setIsAgent(false) setIsMember(false); console.log("Hello member") } else if (data.bookedBy === "Member") { setIsMember(true) setIsAgent(false) setisHeadOffice(false) console.log("Hello member") } else { setIsAgent(false) setIsMember(false) setisHeadOffice(false) } }, [data.bookedBy]) //Adding BookedOptions const [bookedBy, setBookedBy] = useState("") const [agent, setAgent] = useState("") const [nationality, setNationality] = useState("") const [memberShipNumber, setMembershipNumber] = useState() const [isAgent, setIsAgent] = useState(false); const [isMember, setIsMember] = useState(false); const [isHeadOffice, setisHeadOffice] = useState(false); const bookedByOptions = [ { label: "Walk In", value: "Walk In" }, { label: "Agent", value: "Agent" }, { label: "Member", value: "Member" }, { label: "Head Office", value: "Head Office" }, ] const agentOption = [ { label: "Make my Trip", value: "Make my Trip" }, { label: "Gobibo", value: "Gobibo" }, { label: "Sitram Travel Agent", value: "Sitram Travel Agent" }, { label: "Local Agent", value: "Local Agent" }, ] //Adding Nationality const nationalityOptions = [ { label: "Indian", value: "Indian" } , { label: "British", value: "British" } , { label: "American", value: "American" } , { label: "Australian", value: "Australian" } , { label: "Japan", value: "Japan" } , { label: "Saudi Arab", value: "Saudi Arab" } , { label: "UAE", value: "UAE" } , { label: "Africa", value: "Africa" }, , { label: "French", value: "French" } ] console.log(memberShipNumber) //BookedByType const selectBookedByOption = (event) => { // setBookedBy(event.target.value); updatedata({ bookedBy: event.target.value }) } const selectAgentOption = (event) => { setAgent(event.target.value); updatedata({ agent: event.target.value }) } const selectNationalityOption = (event) => { setNationality(event.target.value); updatedata({ nationality: event.target.value }) } // console.log("TESTTING",isEdit) //Guest Name Add const [open, setOpen] = React.useState(false); const handleClickOpen = () => { setOpen(true); }; const handleClose = () => { setOpen(false); }; const onHandleGuest = (guests) => { setOpen(false); onHandleAdditionalGuest(guests) }; return ( <React.Fragment> <GuestNameDialog open={open} onClose={handleClose} shouldDisable={shouldDisable} onHandleGuest={onHandleGuest} additionalGuests={additionalGuests}/> <form onSubmit={event => onFormSubmit(event)} style={{ marginBottom: "2rem" }}> {loading && <Loader color="#0088bc" />} <div className="form-group"> {FormUtils.renderInput( getInputArgObj("firstName", "First Name", "text", shouldDisable) )} {FormUtils.renderInput( getInputArgObj("lastName", "Last Name", "text", shouldDisable) )} <IconButton> <Fab size="small" color="primary" aria-label="add" onClick={handleClickOpen} disabled={shouldDisable} > <AddIcon /> </Fab> </IconButton> {FormUtils.renderInput( getInputArgObj( "contactNumber", "Contact Number", "number", shouldDisable ) )} </div> <div className="form-group"> {FormUtils.renderAddressInput( getInputArgObj("address", "Address", "text", shouldDisable) )} {FormUtils.renderNationality({ id: "nationality", label: "Nationality", name: "nationality", value: data.nationality, onChange: event => selectNationalityOption(event), nationalityOptions, disabled: shouldDisable })} </div> <div className="form-group"> <div className={classes.datePicker} onClick={() => handleDatePicker("checkIn")} > {FormUtils.renderDatepicker( getDateArgObj( "checkIn", "Check In", "text", utils.getDate(), shouldDisable, // openDatePickerCheckIn ) )} </div> <div className={classes.datePicker} onClick={() => handleDatePicker("checkOut")} > {FormUtils.renderDatepicker( getDateArgObj( "checkOut", "Check Out", "text", utils.getDate(), shouldDisable, // openDatePickerCheckOut ) )} </div> {FormUtils.renderInput( getInputArgObj("nights", "Nights Stay", "number", true) )} {FormUtils.renderInput( getInputArgObj("adults", "Adults", "number", shouldDisable) )} {FormUtils.renderInput( getInputArgObj("children", "Children", "number", shouldDisable) )} </div> <div className="form-group" style={{ position: "relative" }}> {FormUtils.renderSelect({ id: "planType", label: "Plan Type", name: "planType", value: data.planType, onChange: event => selectfun1(event), options: getPlanOptions(), disabled: shouldDisable })} <FormControlLabel control={ <Checkbox checked={data.flatRoomRate} onChange={handleFlatRateChange} name="flatRoomRate" color="primary" disabled={shouldDisable} /> } label="Flat Rate" style={{ minWidth: "max-content", marginLeft: "0.3rem" }} /> {FormUtils.renderInput( getInputArgObj("roomCharges", "Total Room Charge", "number", shouldDisable || !data.flatRoomRate) )} <IconButton color="primary" aria-label="Price breakup" style={{ position: "absolute", left: "65%", top: "20px" }} onClick={() => setOpenPriceModal(true)}> <InfoOutlinedIcon /> </IconButton> {FormUtils.renderInput( getInputArgObj("advance", "Advance", "number", shouldDisable) )} </div> <div className="form-group"> {FormUtils.renderBookedBy({ id: "bookedBy", name: "bookedBy", label: "Booked By", value: data.bookedBy, onChange: event => selectfun1(event), bookedByOptions, disabled: shouldDisable, error: errors["bookedBy"] })} {isAgent && FormUtils.renderAgent({ id: "agent", name: "agent", label: "Select Agent", value: data.agent, onChange: event => selectfun1(event), agentOption, disabled: shouldDisable, error: errors["agent"] })} {isAgent && FormUtils.renderInput( getInputArgObj("referencenumber", "Reference number", "string", shouldDisable) )} {isHeadOffice && FormUtils.renderInput( getInputArgObj("referencenumber", "Reference number", "string", shouldDisable) )} { isMember && FormUtils.renderInput({ id: "memberNumber", label: "Membership Number", type: "string", value: data.memberNumber, onChange: (e) => selectfun1(e), error: errors["memberNumber"], disabled: shouldDisable, } ) } </div> <div className="form-group"> {data.nationality === "Indian" && FormUtils.renderproof1({ id: "proofs", name: "proofs", label: "Proof Type", value: data.proofs, onChange: event => selectfun1(event), options1, disabled: shouldDisable, error: errors["proofs"] })} {data.nationality !== "Indian" && FormUtils.renderproof2({ id: "proofs", name: "proofs", label: "Proof Type", value: data.proofs, onChange: event => selectfun1(event), proofTypes, disabled: shouldDisable, error: errors["proofs"] })} {FormUtils.renderInput( getInputArgObj("Idproof", "ID Proof Number", "text", shouldDisable) )} </div> <div className="form-group"> <div> {/* <label htmlFor="proofImage"> Upload Proof Image </label> */} <input accept="image/*" className={classes.input} id="proofImage" type="file" onChange={onFileSelect} disabled={shouldDisable && !enableFileUpload} style={{ display: "none" }} /> <label htmlFor="proofImage"> <Button variant="contained" color="primary" component="span" startIcon={<CloudUploadIcon />} disabled={shouldDisable && !enableFileUpload}> Id Proof </Button> </label> {/* <label htmlFor="proofImage"> <Button variant="contained" color="default" className={classes.uploadButton} startIcon={<CloudUploadIcon />} >style={{display:"none"}} Upload Proof Image </Button> </label> */} </div> <div> <img src={data["idProofImage"]} width="300px" /> </div> </div> <div className={classes.panel}> <ExpansionPanel expanded={expanded === "panel1"} onChange={handleChange("panel1")} > <ExpansionPanelSummary aria-controls="panel1a-content" id="panel1a-header" className={classes.panelHeader} > <div className={classes.expansionPanelSummary} > <Typography className={classes.panelLabel} >Room</Typography> <Fab size="small" color="primary" aria-label="add" onClick={onAddRoom} disabled={shouldDisable} > <AddIcon /> </Fab> </div> </ExpansionPanelSummary> <ExpansionPanelDetails className={classes.expansionPanelDetails}> {data.rooms.map((room, index) => { const error = checkRoomError(index); return ( <div key={`room-${index}`} className="form-group"> {FormUtils.renderSelect({ id: "roomType", label: "Room Type", value: room.roomType, renderValue: (value) => (<label>{value}</label>), onChange: event => selectfun(event, index), options: getRoomTypeOptions(options), error, disabled: shouldDisable })} {/* <FormControl style={{width:"80%"}}> <InputLabel id="demo-simple-select-label">Age</InputLabel> <Select labelId="demo-simple-select-label" id="demo-simple-select" // value= {"Delux"} renderValue={(value)=>(<label>{value}</label>)} value= {room.roomType} > {options && options.map(el=><MenuItem value={el.roomType} key={el.roomType}>{el.roomType}</MenuItem>)} </Select> </FormControl> */} {FormUtils.renderSelect({ id: "roomNumber", label: "Room Number", value: room.roomNumber, onChange: event => selectfun(event, index), options: getRoomOptions(room.roomType), error: error ? " " : null, disabled: shouldDisable })} <div> <IconButton color="secondary" className={classes.deleteButton} onClick={() => onDeleteRoom(index)} disabled={index === 0 ? true : shouldDisable} > <DeleteIcon /> </IconButton> </div> </div> ); })} </ExpansionPanelDetails> </ExpansionPanel> </div> <div className={classes.button}> {FormUtils.renderButton({ type: "button", size: "large", label: "Back", color: "secondary", className: classes.buttonSec, disabled: false, onClick: onBack })} {FormUtils.renderButton({ type: "submit", size: "large", label: data._id ? "Save" : "Book", color: "primary", className: null, disabled: Object.keys(errors).length || shouldDisable ? true : false })} {data.status && !isDirtyroomSelected && !data.status.checkedIn && !isEdit && moment().startOf('date').toDate() >= moment(data.checkIn).startOf('date').toDate() && FormUtils.renderButton({ type: "button", size: "large", label: "CheckIn", color: "primary", className: null, disabled: Object.keys(errors).length ? true : false, style: { marginLeft: "1rem" }, onClick: onCheckIn })} {/* && moment(data.checkOut).toDate() >= moment(data.checkIn).startOf('date').toDate() */} </div> <Dialog onClose={() => setOpenPriceModal(false)} aria-labelledby="simple-dialog-title" open={openPriceModal} maxWidth="md" fullWidth={true}> {/* <div style={{textAlign:"right", padding:"0.5rem"}}> <CloseIcon onClick={()=>setOpenPriceModal(false)} style={{cursor:"pointer"}}/> </div> */} <DialogTitle id="simple-dialog-title" style={{ textAlign: "center" }}> Date Wise Price Breakup <CloseIcon onClick={() => setOpenPriceModal(false)} style={{ cursor: "pointer", float: "right" }} /> </DialogTitle> <DialogContent style={{ maxHeight: "500px", overflowY: "auto" }}> <span style={{ float: "right" }}>Nights Stay - {" " + data.nights}</span> {Object.keys(formattedRates).map(element => { return ( <React.Fragment> <p>{element}-{data.planType}</p> <div style={{ overflowX: "auto" }}> <table className={classes.pricebreaktable}> <tr className={classes.pricebreaktableTr}> {formattedRates[element].map(rate => { return ( <th className={classes.pricebreaktableTh}>{moment(rate.date).format('D.MMM.YYYY')}</th> ) })} </tr> <tr> {formattedRates[element].map(rate => { return ( <td className={classes.pricebreaktableTd}>Rate: {rate.rate}</td> ) })} </tr> <tr> {formattedRates[element].map(rate => { return ( <td className={classes.pricebreaktableTd}>Extra Rate: {rate.extraRate}</td> ) })} </tr> </table> </div> </React.Fragment> ) })} {/* <div> { dayWiseRates.map(rate => { if(rate.planType === data.planType){ return( <div> <div>{moment(rate.date).format('Do MMMM YYYY')}</div> <div>{rate.roomType}</div> <div>{rate.rate}</div> <div>{rate.extraRate}</div> </div> ) } }) } </div> */} </DialogContent> </Dialog> </form> </React.Fragment> ); }; export default BookingForm;
import React from 'react'; import { HashRouter as Router, Route, Switch } from 'react-router-dom'; import { createHashHistory } from 'history'; import CourseReactGA from 'react-ga'; import Loadable from 'react-loadable'; import Loading from 'App/components/Loading'; import { MainContainer } from 'App'; const history = createHashHistory(); /** * Dynamic imports * * @since 2.2.0 */ const CourseContainer = Loadable({ loader: () => import( /* webpackChunkName: 'CourseContainer' */ 'Course/containers/CourseContainer' ), loading: Loading }); const LessonContainer = Loadable({ loader: () => import( /* webpackChunkName: 'LessonContainer' */ 'Lesson/containers/LessonContainer' ), loading: Loading }); const InstructorContainer = Loadable({ loader: () => import( /* webpackChunkName: 'InstructorContainer' */ 'Instructor/containers/InstructorContainer' ), loading: Loading }); const QuizContainer = Loadable({ loader: () => import( /* webpackChunkName: 'QuizContainer' */ 'Quiz/containers/QuizContainer' ), loading: Loading }); /** * Initialize Google analytics. Check for the global object on page * If it does not exist, initialize it * * @todo Figure out use case for fetching a UA code when not already embedded in page * * @since 2.1.0 */ function checkForTrackingCode() { if (!typeof ga === 'function') { CourseReactGA.initialize('[GOOGLE UA CODE]'); } } checkForTrackingCode(); /** * Log the page view to analytics. Only send information * to analytics if on a non-index route. * * @since 2.1.0 */ function logPageView(location) { if (history.location) { const { pathname } = history.location; if (pathname !== '/') { CourseReactGA.set({ page: pathname }); CourseReactGA.pageview(pathname); } } } history.listen(logPageView); /** * The App * * @since 1.0.0 */ const Routes = () => ( <MainContainer> <Router> <Switch> <Route exact path='/' component={ CourseContainer } /> <Route path='/lesson/:lessonSlug' component={ LessonContainer } /> <Route path='/instructors/:slug' component={ InstructorContainer } /> <Route exact path='/quiz' component={ QuizContainer } /> </Switch> </Router> </MainContainer> ); export default Routes;
var _ = require('lodash'); var gulp = require('gulp'); var $ = require('gulp-load-plugins')(); var doiuse = require('doiuse'); var cssnext = require('postcss-cssnext'); var mergeLonghand = require('postcss-merge-longhand'); var mergeRules = require('postcss-merge-rules'); module.exports = function () { var setup = this.opts.setup; var browserSync = this.opts.browserSync; var asserts = setup.asserts; var src = asserts.src.styles; var dest = asserts.root + asserts.res.styles; var optionsSass = setup.plugins.gulpSass; var optionsDoiuse = setup.plugins.doiuse; var optionsPostcss = [ cssnext, mergeLonghand, mergeRules, setup.isVerbose ? doiuse(optionsDoiuse) : undefined ]; optionsPostcss = _(optionsPostcss).reject(_.isUndefined).value(); return gulp.src(src, {cwd: asserts.base.src}) .pipe($.if(setup.isLocal, $.plumber())) .pipe($.if(setup.isVerbose, $.sourcemaps.init())) .pipe($.sass(optionsSass)) .pipe($.postcss(optionsPostcss)) .pipe($.if(setup.isVerbose, $.sourcemaps.write('.'))) .pipe(gulp.dest(dest, {cwd: asserts.dist})) .pipe(browserSync.stream()); };
/* * Module code goes here. Use 'module.exports' to export things: * module.exports.thing = 'a thing'; * * You can import it from another modules like this: * var mod = require('manager.paths'); * mod.thing == 'a thing'; // true */ var logger = require("screeps.logger"); logger = new logger("manager.paths"); var obj = function() { } obj.prototype.init = function() { logger.log("init") this.mem = {}; // RawMemory.setActiveSegments([0,2,3]); // this.mem = {}; // if (RawMemory.segments[0]) { // var allPaths = RawMemory.segments[0]; // if (RawMemory.segments[2]) { // allPaths += RawMemory.segments[2]; // } // if (RawMemory.segments[3]) { // allPaths += RawMemory.segments[3]; // } // logger.log(allPaths); // if (allPaths) { // this.mem = JSON.parse(allPaths) // } else { // } // } // Memory.paths = false; // if (!Memory.paths) { // Memory.paths = {}; // } } var lastParseTick = 0; obj.prototype.tickInit = function() { var startCpu = Game.cpu.getUsed(); //this.mem = Memory.paths; // RawMemory.setActiveSegments([0,2,3,99]); // var dataLength = 0; // if (RawMemory.segments[0] && (lastParseTick+1 != Game.time)) { // var allPaths = RawMemory.segments[0]; // if (RawMemory.segments[2]) { // allPaths += RawMemory.segments[2]; // } // if (RawMemory.segments[3]) { // allPaths += RawMemory.segments[3]; // } // dataLength = allPaths.length; // if (allPaths && allPaths.length < 210000) { // this.mem = JSON.parse(allPaths) // if (dataLength > 190000) { // for(var d in this.mem) { // var dest = this.mem[d]; // logger.log("-----------]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]]--", dest, _.keys(dest).length); // if (_.keys(dest).length < 2) { // delete this.mem[d]; // } // } // } // } else { // } //lastParseTick = Game.time; //} var cpu = Game.cpu.getUsed(); //global.utils.stats.runningAvgStat("paths", "parseCpu", cpu-startCpu, 0.9); //global.utils.stats.setStat("paths", "dataSize", dataLength); logger.log("paths parsed", startCpu, cpu, cpu-startCpu, "********************", this.mem.length) } obj.prototype.tick = function() { } obj.prototype.tickEnd = function() { logger.log('tickEnd---------------------') var displayFlags = global.utils.flagsByColor(Game.flags, COLOR_WHITE, COLOR_GREY); for(var f in displayFlags) { var flag = displayFlags[f]; var destName = flag.pos.roomName+"-"+flag.pos.x+"-"+flag.pos.y; if (this.mem[destName]) { var flow = this.mem[destName]; logger.log('-----------------drawing path', flag.pos) global.utils.drawFlowField(flag.pos, flow); } } //drawFlowField // var allPaths = JSON.stringify(this.mem); // var sections = allPaths.match(/.{1,100000}/g); // if (sections.length > 3) { // return; // } // if (sections.length > 0) // RawMemory.segments[0] = sections[0]; // if (sections.length > 1) { // RawMemory.segments[2] = sections[1]; // } else { // RawMemory.segments[2] = "" // } // if (sections.length > 2) { // RawMemory.segments[3] = sections[2]; // } else { // RawMemory.segments[3] = "" // } } obj.prototype.getFlowDir = function(dest, currentPos) { //this.mem = {}; //return false; var destName = dest.roomName+"-"+dest.x+"-"+dest.y //logger.log(destName) var flow = this.mem[destName]; if (flow) { if (flow[currentPos.roomName] && flow[currentPos.roomName][currentPos.x] && flow[currentPos.roomName][currentPos.x][currentPos.y]) { var myflow = flow[currentPos.roomName][currentPos.x][currentPos.y]; //global.utils.drawFlowField(dest, flow); return myflow; } } return false; } obj.prototype.savePath = function(dest, pathInfo) { //return; // if (pathInfo.ops < 10) { // return; // } //logger.log('saving path', dest.roomName, dest.x, dest.y, JSON.stringify(pathInfo)) var destName = dest.roomName+"-"+dest.x+"-"+dest.y if (!this.mem[destName]) { this.mem[destName] = {}; } var flow = this.mem[destName]; var lastPos = false; for(var p in pathInfo.path) { var pos = pathInfo.path[p]; if (lastPos) { var dir = lastPos.getDirectionTo(pos); flow = this.setFlowValue(flow, lastPos, dir); //logger.log(flow[pos.roomName][pos.x][pos.y]); } lastPos = pos; } this.mem[destName] = flow; } obj.prototype.setFlowValue = function(flow, pos, direction) { if (!flow[pos.roomName]) { flow[pos.roomName] = {}; } if (!flow[pos.roomName][pos.x]) { flow[pos.roomName][pos.x] = {}; } //logger.log(pos.roomName, pos.x, pos.y, direction); // only update flow if it has no value for this square if (!flow[pos.roomName][pos.x][pos.y]) { flow[pos.roomName][pos.x][pos.y] = direction; } return flow; } /* Creep.prototype.oldMoveTo = Creep.prototype.moveTo; Creep.prototype.moveTo = function(target, opts) { if (opts == undefined) { opts = {}; } opts.reusePath=100; opts.ignoreCreeps=true; if (target == null) { console.log(this.name, "is dumb and going no where") return; } if (this.memory.stuck == undefined) { this.memory.stuck = 0; } if (this.memory.stuckLastTick == undefined) { this.memory.stuckLastTick = 0; } //this.memory.stuckLastTick=0 if (this.memory.lastPos) { //if we're in the same position we were in, we may be stuck if (this.memory.lastPos.x == this.pos.x && this.memory.lastPos.y == this.pos.y) { this.memory.stuck++; if (this.memory.stuck > 1) { this.memory.stuckLastTick = (this.memory.stuckLastTick == 0 ? 2 : this.memory.stuckLastTick++); } } else { if (this.memory.stuck > 0) { this.memory.stuck--; } if (this.memory.stuckLastTick > 0) { this.memory.stuckLastTick--; } } } this.memory.lastPos = this.pos; // if (this.memory.stuckLastTick) { // this.say("s"+this.memory.stuckLastTick); // opts.ignoreCreeps = false; // var res = this.oldMoveTo(target, opts); // return res; // } else { // var res = this.oldMoveTo(target, opts); // return res; // } var targetPos; if (target instanceof RoomPosition) { targetPos = target; } else { targetPos = target.pos; } if (Creep.prototype.mem[targetPos.gridName()] == undefined) { Creep.prototype.mem[targetPos.gridName()] = { count: 0, paths: {} }; } Creep.prototype.mem[targetPos.gridName()].count++; var alreadyOnPath = this.pathsContain(Creep.prototype.mem[targetPos.gridName()].paths, this.pos); if (this.memory.stuckLastTick) { this.say("s"+this.memory.stuckLastTick); opts.ignoreCreeps = false; var res = this.oldMoveTo(target, opts); return res; } else { if (!Creep.prototype.mem[targetPos.gridName()].paths[this.pos.gridName()]) { Creep.prototype.mem[targetPos.gridName()].paths[this.pos.gridName()] = { count:0 }; } if (alreadyOnPath) { Creep.prototype.mem[targetPos.gridName()].paths[alreadyOnPath].count++; var path = Creep.prototype.mem[targetPos.gridName()].paths[alreadyOnPath].path; //logger.log(this.name, 'moving by path2', this.pos, alreadyOnPath) this.say("on a path!"); if (Creep.prototype.mem[targetPos.gridName()].paths[alreadyOnPath].count > 4) { this.buildRoad(); } return this.moveByPath(path); } else { Creep.prototype.mem[targetPos.gridName()].paths[this.pos.gridName()].count++; path = this.pos.findPathTo(targetPos, opts); Creep.prototype.mem[targetPos.gridName()].paths[this.pos.gridName()].path = path; //logger.log(this.name, 'moving by path', this.pos, target, targetPos) this.say("routing!"); return this.moveByPath(path); } } } */ module.exports = obj;
window.onload = function() { var button = document.querySelector('button'); var video = document.querySelector('video'); var canvas = document.querySelector('canvas'); var width = canvas.width; var height = canvas.height; var capturing = false; video.width = width; video.height = height; // We need the 2D context to individually manipulate pixel data var ctx = canvas.getContext('2d'); // Start with a black background ctx.fillStyle = '#000'; ctx.fillRect(0, 0, width, height); // Since we're continuously accessing and overwriting the pixels // object, we'll request it once and reuse it across calls to draw() // for best performance (we don't need to create ImageData objects // on every frame) var pixels = ctx.getImageData(0, 0, width, height); var data = pixels.data; var numPixels = data.length; var stream = canvas.captureStream(30); var recorder = new MediaRecorder(stream); recorder.addEventListener('dataavailable', finishCapturing); button.onclick = function() { startCapturing(); }; function startCapturing() { capturing = true; draw(); recorder.start(); setTimeout(function() { recorder.stop(); }, 2000); } function finishCapturing(e) { capturing = false; var videoData = [ e.data ]; var blob = new Blob(videoData, { 'type': 'video/webm' }); var videoURL = URL.createObjectURL(blob); video.src = videoURL; video.play(); } function draw() { // We don't want to render again if we're not capturing if(capturing) { requestAnimationFrame(draw); } drawWhiteNoise(); } function drawWhiteNoise() { var offset = 0; for(var i = 0; i < numPixels; i++) { var grey = Math.round(Math.random() * 255); // The data array has pixel values in RGBA order // (Red, Green, Blue and Alpha for transparency) // We will make R, G and B have the same value ('grey'), // then skip the Alpha value by increasing the offset, // as we're happy with the opaque value we set when painting // the background black at the beginning data[offset++] = grey; data[offset++] = grey; data[offset++] = grey; offset++; // skip the alpha component } // And tell the context to draw the updated pixels in the canvas ctx.putImageData(pixels, 0, 0); } };
angular.module('PersonalWebsiteAngularApp').controller('navigationCtrl', function($scope, $location) { return $scope.isActive = function(currentUrl) { return currentUrl === $location.$$path; }; });
// console.log(global); //2.ๅœจๅฆไธ€ไธชๆ–‡ไปถ้‡Œๅผ•ๅ…ฅไธŠไธ€ไธชๅœจglobalไธŠๆทปๅŠ ไผ ้€’ๅ€ผ็š„ๆ–‡ไปถ๏ผŒไฝฟๅพ—ไธคไธชๆ–‡ไปถไน‹้—ดไบง็”Ÿๅ…ณ่” require('./m3.js'); //3.ๅœจๅฆไธ€ไธชๆ–‡ไปถไฝฟ็”จไธŠไธ€ไธชๆ–‡ไปถไผ ้€’็š„ๅ€ผ console.log(global.str)
var points = [] var bounds ={ min: {x: undefined, y: undefined}, max: {x: undefined, y: undefined} } /*----------------------------------------------------------------------------*/ function addPoint(x, y, radius) { radius = Number(radius || 10) var pointElement = document.createElement('div') pointElement.setAttribute('style', [ 'position: absolute', 'left: ' + (x - radius / 2) + 'px', 'top: ' + (y - radius / 2) + 'px', 'width: ' + radius + 'px', 'height: ' + radius + 'px', 'background: rgba(0, 0, 0, 0.75)', 'border-radius: 50%' ].join(';') ) document.body.appendChild(pointElement) if (points.length > 1) { for (var index = 0; index < points.length; index += 1) { if (points[index].x < bounds.min.x || typeof bounds.min.x === 'undefined') { bounds.min.x = points[index].x; } if (points[index].y < bounds.min.y || typeof bounds.min.y === 'undefined') { bounds.min.y = points[index].y; } if (points[index].x > bounds.max.x || typeof bounds.max.x === 'undefined') { bounds.max.x = points[index].x; } if (points[index].y > bounds.max.y || typeof bounds.max.y === 'undefined') { bounds.max.y = points[index].y; } } var width = bounds.max.x - bounds.min.x; var height = bounds.max.y - bounds.min.y; setBounds(bounds.min.x, bounds.min.y, width, height); } } /*----------------------------------------------------------------------------*/ function setBounds(x, y, width, height) { var boundsElement = document.getElementById('bounds') if (!boundsElement) { boundsElement = document.createElement('div') boundsElement.setAttribute('id', 'bounds') document.body.appendChild(boundsElement) } boundsElement.setAttribute('style', [ 'position: absolute', 'z-index: 1', 'border: solid 1px rgba(196, 0, 0, 0.75)', 'left: ' + Number(x) + 'px', 'top:' + Number(y) + 'px', 'width: ' + (Number(width) - 2) + 'px', 'height: ' + (Number(height) - 2) + 'px' ].join(';') ) } /*----------------------------------------------------------------------------*/ document.addEventListener('mousedown', mouseDown); var isMouseDown = false; function mouseDown(event) { isMouseDown = true; points.push({ x: event.clientX, y: event.clientY}); addPoint(event.clientX, event.clientY); } document.addEventListener('mouseup', mouseUp); function mouseUp(event) { isMouseDown = false; } document.addEventListener('mousemove', mouseMove); function mouseMove(event) { if (isMouseDown) { var lastPoint = points[points.length - 1]; var currentPoint = { x: event.clientX, y: event.clientY }; if (Math.abs(currentPoint.x - lastPoint.x) > 10 || Math.abs(currentPoint.y - lastPoint.y) > 10) { points.push(currentPoint); addPoint(currentPoint.x, currentPoint.y); } } }
import React, { Component } from "react"; class PageContent extends Component { render() { return ( <div> <p>Can you spot the item that doesn&apos;t belong?</p> <ul> <li>Lorem</li> <li>Ipsum</li> <li>Dolor</li> <li>Sit</li> <li>Bumblebees</li> <li>Aenean</li> <li>Consectetur</li> </ul> </div> ); } } export default PageContent;
import YinFft from './yinfft.js' const notes = ['A', 'A#', 'B', 'C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#'] function pitchToN (pitch) { const n = 12 * (Math.log2(pitch) - Math.log2(440)) return Math.round(n) } function nToPitch (n) { return 440 * 2 ** (n / 12) } function nToLabel (n) { return notes[(n + 5 * notes.length) % notes.length] } function getClosestNote (pitch) { const n = pitchToN(pitch) // const minN = pitchToN(82.41) E low guitar const minN = pitchToN(64) // C piano const maxN = pitchToN(335) if (n < minN || n > maxN) { return null } return nToLabel(n) } class TunerACE extends HTMLElement { constructor () { super() const root = this.attachShadow({ mode: 'open' }) const template = document.createElement('template') template.innerHTML = ` <div> <div class="pitch-main"></div> <div> <input type="range" disabled/> </div> <div> <span class="lower"></span> <span class="upper"></span> </div> <div style="clear:both;"></div> </div> <style> input{ width: 100%; margin:0;} input[type=range]::-webkit-slider-runnable-track, input[type=range]::-moz-range-track{ width: 99%; /* border make it overflow */ height: 8.4px; box-shadow: 1px 1px 1px #000000, 0px 0px 1px #0d0d0d; border-radius: 1.3px; border: 0.2px solid #010101; background: red; background: -moz-linear-gradient(90deg, red 0%, yellow 25%, green 51%, yellow 75%, red 100%); background: -webkit-gradient(left, right, color-stop(0%, red), color-stop(25%, yellow), color-stop(51%, green), color-stop(75%, yellow), color-stop(100%, red)); background: -webkit-linear-gradient(90deg, red 0%, yellow 25%, green 51%, yellow 75%, red 100%); background: -o-linear-gradient(90deg, red 0%, yellow 25%, green 51%, yellow 75%, red 100%); background: -ms-linear-gradient(90deg, red 0%, yellow 25%, green 51%, yellow 75%, red 100%); background: linear-gradient(90deg, red 0%, yellow 25%, green 51%, yellow 75%, red 100%); } div.pitch-main { font-size: 3em; text-align:center; } .lower { float: left; } .upper { float: right; } </style>` root.appendChild(template.content.cloneNode(true)) this.note = root.querySelector('.pitch-main') this.lower = root.querySelector('.lower') this.upper = root.querySelector('.upper') this.input = root.querySelector('input') } static get observedAttributes () { return ['pitch'] } attributeChangedCallback (name, old, now) { if (name === 'pitch') { const pitch = parseFloat(now) console.log('newpitch', pitch, getClosestNote(pitch)) if (isNaN(pitch) || !getClosestNote(pitch)) { this.lower.innerHTML = '--' this.upper.innerHTML = '--' this.lower.setAttribute('title', '--') this.upper.setAttribute('title', '--') return } const n = pitchToN(pitch) const minN = n - 1 const maxN = n + 1 this.note.innerHTML = nToLabel(n) + '(' + pitch.toFixed(2) + 'hz)' this.lower.setAttribute('title', nToPitch(minN).toFixed(2) + ' hz') this.upper.setAttribute('title', nToPitch(maxN).toFixed(2) + ' hz') this.lower.innerHTML = nToLabel(minN) this.upper.innerHTML = nToLabel(maxN) this.input.min = nToPitch(minN) this.input.max = nToPitch(maxN) this.input.value = pitch } } }; customElements.define('my-tuner', TunerACE) class PitchDrawer { constructor (node) { this.chunks = [] this.pitchDrawNode = node this.tuner = document.createElement('my-tuner') this.tuner.setAttribute('pitch', 100) node.appendChild(this.tuner) this.started = false } draw (v) { const yin = new YinFft() const pitch = yin(v) console.log('pitch', pitch) this.tuner.setAttribute('pitch', pitch) } start (arr) { this.chunks = [arr] this.started = true } feed (arr) { if (!this.started) return this.chunks.push(arr) const l = this.chunks[0].length if (this.chunks.length * l === 32768) { const newbuf = new Uint8Array(32768) this.chunks.forEach((c, i) => { newbuf.set(c, l * i) }) this.draw(newbuf) this.started = false } } } export default PitchDrawer
/* BEGIN BUBBLE SHIT */ var max_income = 123000; var min_income = 18000; var max_pop = 1000000; var min_pop = 169; var min_vote = 0; var max_vote = 1; var min_unemp = 0; var max_unemp = .26; var min_max = { "income": {'min': min_income, 'max': max_income}, "pop" : {'min': min_pop, 'max': max_pop}, "vote" : {'min': min_vote, 'max': max_vote}, "unemp" : {'min': min_unemp, 'max': max_unemp} } var dem_title = { "income": "Median Income", "vote" : "% GOP Vote 2016", "unemp" : "Unemployment Rate" } var dem_label = { "income": "Income: $", "vote" : "% GOP Vote: ", "unemp" : "Unemployment" } var dem_pos = { "income": income_pos, "vote" : pos_vote, "unemp" : unemp_pos } var quantize = d3.scaleQuantize() .domain([0, 4]) .range(d3.range(5).map(function(i) { if (i == 0) return "#9adbb5"; else if (i == 1) return "rgb(205, 235, 178)"; else if (i == 2) return "#F6F5AE"; else if (i == 3) return "rgb(253, 223, 158)"; else return "rgb(211, 85, 65)"; })) var move_dict = d3.map(); og_data.forEach( function(d){ move_dict.set( d.fips, d.move_index) }); var county_dict = d3.map(); var sab_dict = d3.map(); og_data.forEach( function(d){ county_dict.set( d.fips, d.county); sab_dict.set(d.fips, d.sab); }); var pop_dict = d3.map() dem_data.forEach( function(d){ pop_dict.set( d.fips, d.pop_2019); }); var unemp_dict = d3.map() unemp_data.forEach( function(d) { unemp_dict.set(d.id, d.rate); }); function get_rad_range(width) { if (width >= 900) { return [3,8] } else if (width >= 600) { return [2,5] } return [1.5,3] } function numberWithCommas(x) { return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); } percentFormat = d3.format(',.2%'); function get_x_value(dem, data) { if (dem == "income") { return numberWithCommas(data.income); } else if (dem == "unemp") { return percentFormat(data.unemp); } return (dem == "vote") ? percentFormat(data.vote) : data.cases; } function get_node_x(dem, node) { if (dem == "income") { return node.median_income } else if (dem == "unemp") return node.unemp return (dem == "vote") ? node.per_gop : node.cpc } function get_d_x(dem, node) { if (dem == "income") { return node.income } else if (dem == "unemp") { return node.unemp } return (dem == "vote") ? node.vote : node.cpc } function get_move(d) { var val = document.getElementById("myRange").value; return move_dict.get(d.fips)[val-1] } function make_x_axis(dem) { var margin = {top: 300, right: 250, bottom: 50, left: 50}; var width = $("#maps").width() var height = $("#maps").height() pos = $("#maps").position().top; var bubbles = d3.select(".bubble_svg") var x = d3.scaleLinear() .domain( [min_max[dem].min, min_max[dem].max] ) .range( [margin.left, width - margin.right] ); var xAxis = d3.axisBottom(x); var xAxisTitle = bubbles.append("text") .attr("class", "axisTitle") .text(dem_title[dem]); xAxisTitle .attr("x", width - xAxisTitle.node().getBBox().width - width/4.5) .attr("y", ( height/2) - xAxisTitle.node().getBBox().height - height/5) bubbles.append("g") .attr("class", "x axis") .attr("transform", "translate(0," + (height/2) + ")") .call(xAxis); } function update_demographic(dem, val) { console.log("update"); console.log(dem); var margin = {top: 300, right: 250, bottom: 50, left: 50}; var t = d3.transition() .duration(750); var width = $("#maps").width() var height = $("#maps").height() var bubbles = d3.select(".bubble_svg") bubbles.select(".axisTitle").remove() bubbles.select("g.x.axis").remove() bubbles.select(".d3-tip").remove() var tip = d3.tip() .attr('class', 'd3-tip') .offset([-5, 0]) .html(function(d) { return "County: " + toTitleCase(d.county) + " (" + d.sab + ")<br>Move Index: " + get_move(d) + "<br>Population: " + numberWithCommas(d.pop) + "<br>" + dem_label[dem] + ": " + get_x_value(dem, d); }) bubbles.call(tip); var x = d3.scaleLinear() .domain([min_max[dem].min, min_max[dem].max] ) .range([margin.left, width - margin.right]); var y_dict = d3.map(); y_pos = dem_pos[dem]; y_pos.forEach( function(d){ y_dict.set(d.fips, 250 - d.y )}); var circle = bubbles.selectAll("circle") .attr("x", function(d) { return x(get_d_x(dem, d))}) .attr("y", function(d) { return y_dict.get(d.fips)}) .on('mouseover', tip.show) .on('mouseout', tip.hide) .transition(t) .attr("cx", function(d) { return x(get_d_x(dem, d))}) .attr("cy", function(d) { return y_dict.get(d.fips)}) .attr("transform", "translate(0," + height/2 + ")") make_x_axis(dem) } // to be used with swapmap to replace map with bubbles function make_bubbles_rep(us, val, dem) { console.log(dem); console.log("swap map"); var margin = {top: 300, right: 250, bottom: 50, left: 50}; d3.select(".bubble_svg").remove(); var width = $("#maps").width() var height = $("#maps").height() pos = $("#maps").position().top; rad_range = get_rad_range(width) var x = d3.scaleLinear() .domain( [min_max[dem].min, min_max[dem].max] ) .range( [margin.left, width - margin.right]); var radquantize = d3.scaleQuantize() .domain([min_max['pop'].min, min_max['pop'].max]) .range(rad_range) d3.json("./bubble/dem-data.json", function(error, data) { if (error) throw error; var bubbles = d3.select("#maps").append("svg") .attr("width", width) .attr("height", height) .attr("class", "bubble_svg") .attr("shape-rendering", "geometric-precision"); $("#maps").css("visibility", "visible"); var tip = d3.tip() .attr('class', 'd3-tip') .offset([-5, 0]) .html(function(d) { return "County: " + toTitleCase(d.county) + " (" + d.sab + ")<br>Move Index: " + get_move(d) + "<br>Population: " + numberWithCommas(d.pop) + "<br>" + dem_label[dem] + ": " + get_x_value(dem, d); }) bubbles.call(tip); var y_dict = d3.map(); y_pos = dem_pos[dem] y_pos.forEach( function(d){ y_dict.set(d.fips, 250 - d.y )}); //add education metric var nodes = data.map(function(node, index) { return { index: index, fips: node.fips, pop: node.pop_2019, income: node.median_income, county: node.county, sab: node.sab, vote: node.per_gop, unemp: unemp_dict.get(node.fips), x: x(get_node_x(dem, node)), fx: x(get_node_x(dem, node)), r: radquantize(node.pop_2019), y: y_dict.get(node.fips) }; }); // var simulation = d3.forceSimulation(nodes) // .force("x", d3.forceX(function(d) { return d.x; }).strength(1)) // .force("collide", d3.forceCollide().radius(function(d){ return d.r})) // .force("manyBody", d3.forceManyBody().strength(-1)) // .tick(); var circle = bubbles.selectAll("circle") .data(nodes) .enter().append("circle") .style("fill", function(d) { return quantize(move_dict.get(d.fips)[val-1]); }) .attr("cx", function(d) { return x(get_d_x(dem, d))} ) .attr("cy", function(d) { return y_dict.get(d.fips)} ) .attr("r", function(d) { return d.r} ) .style("opacity", function(d) { return ((d.y + height/2) <= d.r || (d.y + height/2) >= (height - d.r)) ? 0 : 0.75}) .attr("transform", "translate(0," + height/2 + ")") .on('mouseover', tip.show) .on('mouseout', tip.hide) .on('click', function(d) { handleClick(d.fips) }) make_x_axis(dem) if (selected_fips != null) highlight_single(selected_fips); }); }
const express = require('express'); const dotenv = require('dotenv'); const path = require('path'); const helpers = require('./helpers/pug-helpers'); const mainRoutes = require('./routes/main'); const projectRoutes = require('./routes/project'); dotenv.config({ path: '.env' }); const app = express(); // Set up template engine app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'pug'); // Add helpers to local variables for access in pug templates app.use((req, res, next) => { res.locals.h = helpers; next(); }); // Add main static files app.use(express.static(path.join(__dirname, 'public/site'))); app.use('/project', express.static(path.join(__dirname, 'public/site'))); // Add main routes app.use('/', mainRoutes); // Add static files for projects app.use(express.static(path.join(__dirname, 'public/projects'))); app.use(express.static(path.join(__dirname, 'public/projects/myreads'))); app.use(express.static(path.join(__dirname, 'public/projects/senate-map'))); app.use(express.static(path.join(__dirname, 'public/projects/message-board'))); app.use(express.static(path.join(__dirname, 'public/projects/todos'))); app.use(express.static(path.join(__dirname, 'public/documents'))); // Add project routes app.use('/', projectRoutes); // Handle 404s app.use((req, res) => { res.status(404).send('404: Page Not Found'); }); app.set('port', process.env.PORT || 3000); const server = app.listen(app.get('port'), () => { console.log(`Listening on port ${app.get('port')}โ€ฆ`); });
import React from "react"; import './NavControl.scss'; import {faUserCircle} from "@fortawesome/free-solid-svg-icons"; import {FontAwesomeIcon} from "@fortawesome/react-fontawesome"; import AnimationMixin from "../../plugin/animation"; class NavControl extends React.Component { componentDidMount() { window.addEventListener("scroll", this.scrollEvent, true) } componentWillUnmount() { window.removeEventListener("scroll", this.scrollEvent) } scrollEvent() { const navControl = document.getElementById("nav-control"); AnimationMixin.fixTop(navControl); } render() { return( <div className="NavControl" id="nav-control"> <FontAwesomeIcon icon={faUserCircle} className="nav-icon"/> <FontAwesomeIcon icon={faUserCircle} className="nav-icon"/> </div> ) } } export default NavControl;
const mysql = require("mysql"); const inquirer = require("inquirer"); const cTable = require("console.table"); // set up connection to server // ========================================================= var connection = mysql.createConnection({ host: "localhost", // Your port; if not 3306 PORT: 3306, // Your username user: "root", // Your password password: "20164Runner", database: "employeeTracker_DB" }); connection.connect(function (err) { if (err) throw err; console.log("connected as id " + connection.threadId + "\n"); start(); }); // Function to run inquirer // ========================================================= function questions(options) { return inquirer.prompt(options); } // main function to run program // ========================================================= const start = function () { questions({ name: "action", type: "rawlist", message: "What would you like to do?", choices: [ "View all employees", "View all employees by manager", "View all departments", "View all roles", "Search Employees", "Add employees", "Add departments", "Add roles", "Update an employee's data" ] }) .then(function (answer) { switch (answer.action) { case "View all employees": allEmployees(); break; case "View all employees by manager": employeesByManager(); break; case "View all departments": allDepartments(); break; case "View all roles": allRoles(); break; case "Search Employees": employeeSearch(); break; case "Add employees": addEmployee(); break; case "Add roles": addRole(); break; case "Add departments": addDepartment(); break; case "Update an employee's data": update(); break; } }) } // query specific functions used above in main program // ========================================================= const allEmployees = function () { var query = "SELECT employee.id, employee.first_name, employee.last_name, roles.title, department.department_name AS department, roles.salary " query += "FROM employee " query += "LEFT JOIN roles ON (employee.role_id = roles.id) " query += "LEFT JOIN department ON (roles.department_id = department.id);" connection.query(query, function (error, results, fields) { console.log(""); console.table(results); }) start() } const allDepartments = function () { var query = "SELECT * " query += "FROM department " connection.query(query, function (error, results, fields) { console.log(""); console.table(results); }) start(); } const allRoles = function () { var query = "SELECT * " query += "FROM roles " query += "INNER JOIN department ON (roles.department_id = department.id)" connection.query(query, function (error, results, fields) { console.log(""); console.table(results); }) start(); } const employeeSearch = function () { questions({ name: "id", type: "input", message: "Please enter the id of the employee you would like to view." }) .then(function (answer) { var query = "SELECT employee.id, employee.first_name, employee.last_name, roles.title, department.department_name AS department, roles.salary " query += "FROM employee " query += "LEFT JOIN roles ON (employee.role_id = roles.id) " query += "LEFT JOIN department ON (roles.department_id = department.id) " query += "WHERE employee.id = ?" connection.query(query, [answer.id], function (error, results, fields) { console.log(""); console.table(results); }) start() }) } // Add Functions ===== const addEmployee = function () { questions([{ name: "fName", type: "input", message: "Please enter the first name of the employee you would like to add" }, { name: "lName", type: "input", message: "Please enter the last name of the employee you would like to add" }, { name: "role", type: "input", message: "Please enter the role ID of the employee you would like to add" }, { name: "manager", type: "input", message: "Please enter the manager ID of the employee you would like to add" }] ) .then(function (answer) { var query = "INSERT INTO employee (first_name, last_name, role_id, manager_id) " query += "VALUES (?, ?, ?, ?)" connection.query(query, [answer.fName, answer.lName, answer.role, answer.manager], function (error, results, fields) { console.table(results); if (error) throw error; }) console.log("successfully added") start() }) } const addDepartment = function () { questions([{ name: "name", type: "input", message: "Please enter the name of the department you would like to add" }] ) .then(function (answer) { var query = "INSERT INTO department (department_name) " query += "VALUES (?)" connection.query(query, [answer.name], function (error, results, fields) { console.table(results); if (error) throw error; }) console.log("successfully added") start() }) } const addRole = function () { questions([{ name: "title", type: "input", message: "Please enter the title of the role you would like to add" }, { name: "salary", type: "input", message: "Please enter the salary of the role you would like to add" }, { name: "department_id", type: "input", message: "Please enter the department ID of the role you would like to add" }] ) .then(function (answer) { var query = "INSERT INTO roles (title, salary, department_id) " query += "VALUES (?, ?, ?)" connection.query(query, [answer.title, answer.salary, answer.department_id], function (error, results, fields) { console.table(results); if (error) throw error; }) console.log("successfully added") start() }) } // =================== // update function ==== const update = function () { questions([{ name: "id", type: "input", message: "Please enter the ID of the employee you would like to update" }, { name: "employeeAttribute", type: "rawlist", message: "Please choose the data of the employee you would like to update", choices: [ "first_name", "last_name", "role_id", "manager_id" ] }, { name: "employeeValue", type: "input", message: "Please enter the updated value of the employee you would like to update" } ]) .then(function (answer) { console.log(answer); switch (answer.employeeAttribute) { case "first_name": var query = "UPDATE employee SET first_name = ? WHERE id = ?" connection.query(query, [answer.employeeValue, Number(answer.id)], function (error, results, fields) { console.table(results); if (error) { return console.log(error); } }) console.log("successfully updated"); start(); break; case "last_name": var query = "UPDATE employee SET last_name = ? WHERE id = ?" connection.query(query, [answer.employeeValue, Number(answer.id)], function (error, results, fields) { console.table(results); if (error) { return console.log(error); } }) console.log("successfully updated"); start(); break; case "role_id": var query = "UPDATE employee SET role_id = ? WHERE id = ?" connection.query(query, [answer.employeeValue, Number(answer.id)], function (error, results, fields) { console.table(results); if (error) { return console.log(error); } }) console.log("successfully updated"); start(); break; case "manager_id": var query = "UPDATE employee SET manager_id = ? WHERE id = ?" connection.query(query, [answer.employeeValue, Number(answer.id)], function (error, results, fields) { console.table(results); if (error) { return console.log(error); } }) console.log("successfully updated"); start(); break; } })}
"use strict"; import { NavbarTop } from "./navbarTop.js"; import { NavbarBottom } from "./navbarBottom.js"; import { OutlayCategory } from "./outlayCategory.js"; import { OutlayEntry } from "./outlayEntry.js"; import { db, outlayObjectStoreName, outlayCategoryObjectStoreName, settingObjectStoreName, outlayCategorySelectedKeyName, outlayEntriesDateMinCalcKeyName, } from "./db.js"; import { Setting } from "./setting.js"; import { Category } from "./category.js"; import { setContentHeight } from "./pattern.js"; let categorySelectedId; let categorySelected; let categorySelectedParent; let categorySelectedParentInit; export class OutlayCategoryMove { static async displayData() { NavbarTop.show({ menu: { buttonHTML: "&#9776;", content: [ { innerHTML: "ะŸะตั€ะตะผะตัั‚ะธั‚ัŒ ะบะฐั‚ะตะณะพั€ะธัŽ", href: "#func=OutlayCategoryMove", }, { innerHTML: "ะงะตะบะธ", href: "Javascript:OutlayEntries_displayData()", }, { innerHTML: "ะ˜ั‚ะพะณะธ ะฒ ั€ะฐะทั€ะตะทะต ะบะฐั‚ะตะณะพั€ะธะน", href: "Javascript:OutlaySummary_displayData()", }, { innerHTML: "ะฃั‚ะธะปะธั‚ั‹", href: "#func=OutlayUtils", }, ], }, titleHTML: "ะŸะตั€ะตะผะตั‰ะตะฝะธะต ะบะฐั‚ะตะณะพั€ะธะธ", buttons: [ { onclick: OutlayCategoryMove.save, title: "ะกะพั…ั€ะฐะฝะธั‚ัŒ", innerHTML: "&#10004;", id: "buttonSave", }, ], }); NavbarBottom.show([ { text: "ะงะตะบะธ", href: 'Javascript:displayData("OutlayEntries")' }, { text: "ะšะฐั‚ะตะณะพั€ะธะธ", href: 'Javascript:displayData("OutlayCategory")' }, { text: "ะ˜ั‚ะพะณะธ", href: 'Javascript:displayData("OutlaySummary")' }, ]); const divContent = document.getElementsByClassName("content")[0]; { while (divContent.firstChild) { divContent.removeChild(divContent.firstChild); } } divContent.appendChild( await OutlayCategory.displayTree( null, db.transaction(outlayCategoryObjectStoreName), true ) ); categorySelectedId = await Setting.get(outlayCategorySelectedKeyName); categorySelected = document.getElementById(categorySelectedId) .parentElement; categorySelected.className = "categoryToMove"; categorySelectedParentInit = categorySelected.parentElement.parentElement; categorySelectedParent = categorySelectedParentInit; categorySelectedParent.className = "categoryToMoveParent"; // https://vc.ru/dev/89555-javascript-massivy-peresechenie-raznost-i-obedinenie-v-es6 for (let li of Array.prototype.slice .call(divContent.getElementsByTagName("LI"), 0) .filter( (x) => !Array.prototype.slice .call(categorySelected.getElementsByTagName("LI"), 0) .includes(x) )) { li.querySelector("li > span:nth-child(2)").onclick = OutlayCategoryMove.categoryParentSelect; } OutlayCategoryMove.navbarTopRefresh(); setContentHeight(); } static categoryParentSelect() { categorySelectedParent.className = null; categorySelectedParent = this.parentElement.parentElement; categorySelectedParent.className = "categoryToMoveParent"; const categorySelectedText = categorySelected .querySelector(".categoryToMove > li > span:nth-child(2)") .innerHTML.trim(); { let categoryMoved = false; for (let ul of categorySelectedParent.querySelectorAll( ".categoryToMoveParent > li > ul" )) { if ( categorySelectedText < ul.querySelector("li > span:nth-child(2)").innerHTML.trim() ) { categorySelectedParent .querySelector(".categoryToMoveParent > li") .insertBefore(categorySelected, ul); categoryMoved = true; break; } } if (!categoryMoved) { categorySelectedParent .querySelector(".categoryToMoveParent > li") .appendChild(categorySelected); } } OutlayCategoryMove.navbarTopRefresh(); } static navbarTopRefresh() { const navBarTopTitle = document .getElementsByClassName("navBarTopTitle") .item(0); navBarTopTitle.innerHTML = ' "' + categorySelected .querySelector(".categoryToMove > li > span:nth-child(2)") .innerHTML.trim() + '" ะธะท "' + categorySelectedParentInit .querySelector("li > span:nth-child(2)") .innerHTML.trim() + '"'; if (categorySelectedParentInit === categorySelectedParent) { navBarTopTitle.innerHTML = "ะŸะตั€ะตะผะตั‰ะตะฝะธะต " + navBarTopTitle.innerHTML; document.getElementById("buttonSave").className = "buttonDisabled"; } else { navBarTopTitle.innerHTML = "ะŸะตั€ะตะผะตัั‚ะธั‚ัŒ " + navBarTopTitle.innerHTML + ' ะฒ "' + categorySelectedParent .querySelector("li > span:nth-child(2)") .innerHTML.trim() + '"'; } } static async save() { if ("buttonDisabled" === document.getElementById("buttonSave").className) { return; } if ( !window.confirm( 'ะ’ั‹ ะดะตะนัั‚ะฒะธั‚ะตะปัŒะฝะพ ั…ะพั‚ะธั‚ะต ะฟะตั€ะตะผะตัั‚ะธั‚ัŒ "' + categorySelected .querySelector(".categoryToMove > li > span:nth-child(2)") .innerHTML.trim() + '" ะธะท "' + categorySelectedParentInit .querySelector("li > span:nth-child(2)") .innerHTML.trim() + '" ะฒ "' + categorySelectedParent .querySelector("li > span:nth-child(2)") .innerHTML.trim() + '"?' ) ) return; try { const transaction = db.transaction( [ outlayCategoryObjectStoreName, outlayObjectStoreName, settingObjectStoreName, ], "readwrite" ); await Setting.set( outlayEntriesDateMinCalcKeyName, (await OutlayEntry.getEntryYoungest(transaction)).date, transaction ); const category = await Category.get(categorySelectedId, transaction); category.parentId = Number(categorySelectedParent.firstChild.id); await Category.set(category, transaction); transaction.onerror = function (event) { alert("ะžะจะ˜ะ‘ะšะ: " + event.target.error); }; transaction.oncomplete = function () { history.back(); }; } catch (error) { alert(error); } } }
var home = {}, football = { goalkeeper : "Van der Sar", midfielder : "De Jong", attacker : "Depay" }; function isEmpty(object) { for(var key in object) { return false; } return true; } console.log(isEmpty(home)); console.log(isEmpty(football));
'use strict'; angular.module('FEF-Angular-UI.MqService', []) .factory('MqService', function() { if (typeof Modernizr === 'undefined') { throw 'Modernizr is not defined'; } return { mq: Modernizr.mq } });
(function () { 'use strict'; angular .module('app.socket',[]) .factory('socket',['User',function (User) { var socket = io(); socket.log = function (texto) { socket.emit('users:logs',{ log:texto, date:new Date(), user:User.current }) }; return socket; }]); })();
// /* // * // * WordPres็‰ˆๅพฎไฟกๅฐ็จ‹ๅบ // * author: jianbo // * organization: ๅฎˆๆœ›่ฝฉ www.watch-life.net // * github: https://github.com/iamxjb/winxin-app-watch-life.net // * ๆŠ€ๆœฏๆ”ฏๆŒๅพฎไฟกๅท๏ผšiamxjb // * ๅผ€ๆบๅ่ฎฎ๏ผšMIT // * // * *Copyright (c) 2017 https://www.watch-life.net All rights reserved. // */ // var Api = require('../../utils/api.js'); // var util = require('../../utils/util.js'); // var WxParse = require('../../wxParse/wxParse.js'); // var wxApi = require('../../utils/wxApi.js') // var wxRequest = require('../../utils/wxRequest.js') var wxCharts = require('../../utils/wxcharts.js') import config from '../../utils/config.js' // var pageCount = config.getPageCount; let lineChart = null Page({ /** * ้กต้ข็š„ๅˆๅง‹ๆ•ฐๆฎ */ data: { tabInd:0, animation:true, data0:"60%", data1:300, data2:200, data3:300, }, tabInds(event){ let ind = event.currentTarget.dataset.index if (this.data.tabInd ===ind) { return false; } else { if (ind==0){ this.setData({ tabInd: ind, data1: 100, data2: 200, data3: 300, }); } else if (ind == 1){ this.setData({ tabInd: ind, data1: 200, data2: 200, data3: 200, }); }else{ this.setData({ tabInd: ind, data1: 300, data2: 200, data3: 100, }); } this.data.animation = false this.chartss() } }, chartss() { lineChart = new wxCharts({ animation: this.data.animation, //ๆ˜ฏๅฆๆœ‰ๅŠจ็”ป canvasId: 'ringCanvas', type: 'ring', extra: { ringWidth: 30, pie: { offsetAngle: -90 } }, title: { name: this.data.data0, color: '#FF5B1F', fontSize: 14 }, // subtitle: { // name: '่ฟ›ๅบฆ', // color: '#191F23', // fontSize: 12 // }, series: [{ name: '็›ฎๆ ‡', data: this.data.data1, color: '#C552DB', stroke: true }, { name: '้”€้‡', data: this.data.data2, color: '#E66878', stroke: true }, { name: '่ฟ›ๅบฆ', data: this.data.data3, color: '#F2AB62', stroke: true }], disablePieStroke: true, width: 150, height: 150, dataLabel: false, legend: false, padding: 10, }); }, /** * ็”Ÿๅ‘ฝๅ‘จๆœŸๅ‡ฝๆ•ฐ--็›‘ๅฌ้กต้ขๅŠ ่ฝฝ */ onLoad: function (options) { this.chartss() }, /** * ็”Ÿๅ‘ฝๅ‘จๆœŸๅ‡ฝๆ•ฐ--็›‘ๅฌ้กต้ขๅˆๆฌกๆธฒๆŸ“ๅฎŒๆˆ */ onReady: function () { }, /** * ็”Ÿๅ‘ฝๅ‘จๆœŸๅ‡ฝๆ•ฐ--็›‘ๅฌ้กต้ขๆ˜พ็คบ */ onShow: function () { }, /** * ็”Ÿๅ‘ฝๅ‘จๆœŸๅ‡ฝๆ•ฐ--็›‘ๅฌ้กต้ข้š่— */ onHide: function () { }, /** * ็”Ÿๅ‘ฝๅ‘จๆœŸๅ‡ฝๆ•ฐ--็›‘ๅฌ้กต้ขๅธ่ฝฝ */ onUnload: function () { }, /** * ้กต้ข็›ธๅ…ณไบ‹ไปถๅค„็†ๅ‡ฝๆ•ฐ--็›‘ๅฌ็”จๆˆทไธ‹ๆ‹‰ๅŠจไฝœ */ onPullDownRefresh: function () { }, /** * ้กต้ขไธŠๆ‹‰่งฆๅบ•ไบ‹ไปถ็š„ๅค„็†ๅ‡ฝๆ•ฐ */ onReachBottom: function () { }, /** * ็”จๆˆท็‚นๅ‡ปๅณไธŠ่ง’ๅˆ†ไบซ */ onShareAppMessage: function () { } }) // Page({ // data: { // postsList: [], // postsShowSwiperList:[], // isLastPage:false, // page: 1, // search: '', // categories: 0, // showerror:"none", // showCategoryName:"", // categoryName:"", // showallDisplay:"block", // displayHeader:"none", // displaySwiper: "none", // floatDisplay: "none", // displayfirstSwiper:"none", // topNav: [] // }, // formSubmit: function (e) { // var url = '../list/list' // var key =''; // if (e.currentTarget.id =="search-input") // { // key = e.detail.value; // } // else{ // key = e.detail.value.input; // } // if (key != '') { // url = url + '?search=' +key; // wx.navigateTo({ // url: url // }) // } // else // { // wx.showModal({ // title: 'ๆ็คบ', // content: '่ฏท่พ“ๅ…ฅๅ†…ๅฎน', // showCancel: false, // }); // } // }, // onShareAppMessage: function () { // return { // title: 'โ€œ' + config.getWebsiteName+'โ€็ฝ‘็ซ™ๅพฎไฟกๅฐ็จ‹ๅบ,ๅŸบไบŽWordPress็‰ˆๅฐ็จ‹ๅบๆž„ๅปบ.ๆŠ€ๆœฏๆ”ฏๆŒ๏ผšwww.watch-life.net', // path: 'pages/index/index', // success: function (res) { // // ่ฝฌๅ‘ๆˆๅŠŸ // }, // fail: function (res) { // // ่ฝฌๅ‘ๅคฑ่ดฅ // } // } // }, // onPullDownRefresh: function () { // var self = this; // self.setData({ // showerror: "none", // showallDisplay:"block", // displaySwiper:"none", // floatDisplay:"none", // isLastPage:false, // page:1, // postsShowSwiperList:[] // }); // this.fetchTopFivePosts(); // this.fetchPostsData(self.data); // }, // onReachBottom: function () { // var self = this; // if (!self.data.isLastPage) { // self.setData({ // page: self.data.page + 1 // }); // console.log('ๅฝ“ๅ‰้กต' + self.data.page); // this.fetchPostsData(self.data); // } // else { // console.log('ๆœ€ๅŽไธ€้กต'); // } // }, // onLoad: function (options) { // var self = this; // self.fetchTopFivePosts(); // self.fetchPostsData(self.data); // self.setData({ // topNav: config.getIndexNav // }); // }, // onShow: function (options){ // wx.setStorageSync('openLinkCount', 0); // }, // fetchTopFivePosts: function () { // var self = this; // //่Žทๅ–ๆป‘ๅŠจๅ›พ็‰‡็š„ๆ–‡็ซ  // var getPostsRequest = wxRequest.getRequest(Api.getSwiperPosts()); // getPostsRequest.then(response => { // if (response.data.status =='200' && response.data.posts.length > 0) { // self.setData({ // // postsShowSwiperList: response.data.posts, // postsShowSwiperList: self.data.postsShowSwiperList.concat(response.data.posts.map(function (item) { // if (item.post_medium_image == null || item.post_medium_image == '') { // item.post_medium_image = "../../images/logo700.png"; // } // return item; // })), // displaySwiper: "block" // }); // } // else { // self.setData({ // displaySwiper: "none" // }); // } // }).catch(function (response){ // console.log(response); // self.setData({ // showerror: "block", // floatDisplay: "none" // }); // }) // .finally(function () { // }); // }, // //่Žทๅ–ๆ–‡็ซ ๅˆ—่กจๆ•ฐๆฎ // fetchPostsData: function (data) { // var self = this; // if (!data) data = {}; // if (!data.page) data.page = 1; // if (!data.categories) data.categories = 0; // if (!data.search) data.search = ''; // if (data.page === 1) { // self.setData({ // postsList: [] // }); // }; // wx.showLoading({ // title: 'ๆญฃๅœจๅŠ ่ฝฝ', // mask:true // }); // var getPostsRequest = wxRequest.getRequest(Api.getPosts(data)); // getPostsRequest // .then(response => { // if (response.statusCode === 200) { // if (response.data.length) { // if(response.data.length < pageCount) // { // self.setData({ // isLastPage: true // }); // } // self.setData({ // floatDisplay: "block", // postsList: self.data.postsList.concat(response.data.map(function (item) { // var strdate = item.date // if (item.category_name != null) { // item.categoryImage = "../../images/category.png"; // } // else { // item.categoryImage = ""; // } // if (item.post_medium_image == null || item.post_medium_image == '') { // item.post_medium_image = "../../images/logo700.png"; // } // item.date = util.cutstr(strdate, 10, 1); // return item; // })), // }); // setTimeout(function () { // wx.hideLoading(); // }, 900); // } // else { // if (response.data.code == "rest_post_invalid_page_number") { // self.setData({ // isLastPage: true // }); // wx.showToast({ // title: 'ๆฒกๆœ‰ๆ›ดๅคšๅ†…ๅฎน', // mask: false, // duration: 1500 // }); // } // else { // wx.showToast({ // title: response.data.message, // duration: 1500 // }) // } // } // } // }) // .catch(function (response) // { // if (data.page == 1) { // self.setData({ // showerror: "block", // floatDisplay: "none" // }); // } // else { // wx.showModal({ // title: 'ๅŠ ่ฝฝๅคฑ่ดฅ', // content: 'ๅŠ ่ฝฝๆ•ฐๆฎๅคฑ่ดฅ,่ฏท้‡่ฏ•.', // showCancel: false, // }); // self.setData({ // page: data.page - 1 // }); // } // }) // .finally(function (response) { // wx.hideLoading(); // wx.stopPullDownRefresh(); // }); // }, // //ๅŠ ่ฝฝๅˆ†้กต // loadMore: function (e) { // var self = this; // if (!self.data.isLastPage) // { // self.setData({ // page: self.data.page + 1 // }); // //console.log('ๅฝ“ๅ‰้กต' + self.data.page); // this.fetchPostsData(self.data); // } // else // { // wx.showToast({ // title: 'ๆฒกๆœ‰ๆ›ดๅคšๅ†…ๅฎน', // mask: false, // duration: 1000 // }); // } // }, // // ่ทณ่ฝฌ่‡ณๆŸฅ็œ‹ๆ–‡็ซ ่ฏฆๆƒ… // redictDetail: function (e) { // // console.log('ๆŸฅ็œ‹ๆ–‡็ซ '); // var id = e.currentTarget.id, // url = '../detail/detail?id=' + id; // wx.navigateTo({ // url: url // }) // }, // //้ฆ–้กตๅ›พๆ ‡่ทณ่ฝฌ // onNavRedirect:function(e){ // var redicttype = e.currentTarget.dataset.redicttype; // var url = e.currentTarget.dataset.url == null ? '' : e.currentTarget.dataset.url; // var appid = e.currentTarget.dataset.appid == null ? '' : e.currentTarget.dataset.appid; // var extraData = e.currentTarget.dataset.extraData == null ? '' : e.currentTarget.dataset.extraData; // if (redicttype == 'apppage') {//่ทณ่ฝฌๅˆฐๅฐ็จ‹ๅบๅ†…้ƒจ้กต้ข // wx.navigateTo({ // url: url // }) // } // else if (redicttype == 'webpage')//่ทณ่ฝฌๅˆฐweb-viewๅ†…ๅตŒ็š„้กต้ข // { // url = '../webpage/webpage?url=' + url; // wx.navigateTo({ // url: url // }) // } // else if (redicttype == 'miniapp')//่ทณ่ฝฌๅˆฐๅ…ถไป–app // { // wx.navigateToMiniProgram({ // appId: appid, // envVersion: 'release', // path: url, // extraData: extraData, // success(res) { // // ๆ‰“ๅผ€ๆˆๅŠŸ // }, // fail: function (res) { // console.log(res); // } // }) // } // }, // // ่ทณ่ฝฌ่‡ณๆŸฅ็œ‹ๅฐ็จ‹ๅบๅˆ—่กจ้กต้ขๆˆ–ๆ–‡็ซ ่ฏฆๆƒ…้กต // redictAppDetail: function (e) { // // console.log('ๆŸฅ็œ‹ๆ–‡็ซ '); // var id = e.currentTarget.id; // var redicttype = e.currentTarget.dataset.redicttype; // var url = e.currentTarget.dataset.url == null ? '':e.currentTarget.dataset.url; // var appid = e.currentTarget.dataset.appid == null ? '' : e.currentTarget.dataset.appid; // if (redicttype == 'detailpage')//่ทณ่ฝฌๅˆฐๅ†…ๅฎน้กต // { // url = '../detail/detail?id=' + id; // wx.navigateTo({ // url: url // }) // } // if (redicttype == 'apppage') {//่ทณ่ฝฌๅˆฐๅฐ็จ‹ๅบๅ†…้ƒจ้กต้ข // wx.navigateTo({ // url: url // }) // } // else if (redicttype == 'webpage')//่ทณ่ฝฌๅˆฐweb-viewๅ†…ๅตŒ็š„้กต้ข // { // url = '../webpage/webpage?url=' + url; // wx.navigateTo({ // url: url // }) // } // else if (redicttype == 'miniapp')//่ทณ่ฝฌๅˆฐๅ…ถไป–app // { // wx.navigateToMiniProgram({ // appId: appid, // envVersion: 'release', // path: url, // success(res) { // // ๆ‰“ๅผ€ๆˆๅŠŸ // }, // fail: function (res) { // console.log(res); // } // }) // } // }, // //่ฟ”ๅ›ž้ฆ–้กต // redictHome: function (e) { // //console.log('ๆŸฅ็œ‹ๆŸ็ฑปๅˆซไธ‹็š„ๆ–‡็ซ '); // var id = e.currentTarget.dataset.id, // url = '/pages/index/index'; // wx.switchTab({ // url: url // }); // } // })
/*globals $*/ /** * Check A Box v0.1.4 * http://immobilienscout24.github.io/CheckABox/ * */ $.fn.checkABox=function(m,d){var q={checkedClass:"ui-icon-on",uncheckedClass:"",iconClass:"ui-icon icon-ok",iconHtml:"<span></span>"},p=$(this),g="relatedIcon"; function e(s){return s.prop(g);}function h(s){return s.is(":checked");}function f(t,s){t.prop("checked",s);t.trigger("change");}function n(u,t){var s=e(u); s.toggleClass(q.checkedClass,t);s.toggleClass(q.uncheckedClass,!t);}function k(){p.each(function(t,s){s=$(s);n(s,h(s));});}function r(s,t){f(s,t);n(s,t); }function b(s){r(s,!h(s));}function i(s){return(h(s)?q.checkedClass:q.uncheckedClass);}function j(s){if($(s.currentTarget).is("label")){s.stopPropagation(); }}function c(s){return(s.is("input[type='radio']")&&h(s));}function a(s){return function(t){j(t);t.preventDefault();if(!c(s)){b(s);k();}};}function o(s){s.each(function(u,t){var w,v,x=$(t); if(!x.prop("checkABoxEnabled")){x.prop("checkABoxEnabled",true);w=$(q.iconHtml);w.addClass(i(x)+" "+q.iconClass);x.prop(g,w);v=x.parent();v.on("mousedown",a(x)); v.on("touchstart",a(x));w.insertBefore(x);}});}function l(s){d=d||{};$.extend(q,d);if(typeof s==="boolean"){r(p,s);}else{if(s==="toggle"){b(p);}else{if(s==="bind"){o(p); }else{if(s==="refresh"){k();}}}}}l(m);return p;};
import React, {Component} from 'react'; import { Text, View, TouchableOpacity, Image, Dimensions, FlatList, StyleSheet } from 'react-native'; import { connect } from 'react-redux'; import Header from'../../Header'; let backIcon = require('../../../../media/appIcon/backList.png'); const url = 'http://192.168.1.32:8080/ShoppingApp/images/product/'; const { width, height } = Dimensions.get('window'); class ListProduct extends Component<Props> { //hร m mแปŸ menu openMenu(){ this.props.navigation.toggleDrawer(); } //hร m mแปŸ trang tรฌn kiแบฟm openSearch(){ this.props.navigation.navigate('SearchScreen'); } render() { const { navigate } = this.props.navigation; const { topProducts } = this.props; const product = this.props.navigation.getParam('product', null); const { name } = product; const { container, wrapper, header, titleStyle, productContainer, productInfo, productImage, lastRowInfo, dotStyle, txtName, txtPrice, txtMaterial, txtColor, txtDetail } = styles; return ( <View style={ container }> <Header onOpen={this.openMenu.bind(this)} onSearch={this.openSearch.bind(this)}/> <View style={ wrapper }> <View style={ header }> <TouchableOpacity onPress={() => {this.props.navigation.goBack()}}> <Image source={ backIcon } style={{ width: 30, height: 30 }}/> </TouchableOpacity> <Text style={ titleStyle }>{ name }</Text> <View style={{ width: 30 }}/> </View> <FlatList data={topProducts} renderItem = { ({item}) =>{ return ( <View style={ productContainer }> <Image source={{uri: `${url}${item.images[0]}`}} style={ productImage }/> <View style={ productInfo }> <Text style={ txtName }>{item.name}</Text> <Text style={ txtPrice }>{item.price}$</Text> <Text style={ txtMaterial }>Material: {item.material}</Text> <View style={ lastRowInfo }> <Text style={ txtColor }>Color: {item.color}</Text> <View style={{ backgroundColor: item.color.toLowerCase(), width: 14, height: 14, borderRadius: 7 }} /> <TouchableOpacity onPress={() => {navigate('DetailScreen', {product: item})}} > <Text style={ txtDetail }>Show Detail</Text> </TouchableOpacity> </View> </View> </View> ); }} /> </View> </View> ); } } function mapStateToProps(state){ return { topProducts: state.topProducts }; } export default connect(mapStateToProps)(ListProduct); const styles = StyleSheet.create({ container: { flex: 1, }, wrapper: { margin: 10, padding: 10, backgroundColor: '#fff', flex: 1 }, header: { height: height/20, backgroundColor: '#fff', flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10 }, titleStyle: { color: '#B10D65', fontFamily: 'avenir', fontSize: 20 }, productContainer: { paddingTop: 10, paddingHorizontal: 10, marginBottom: 20, flexDirection: 'row', borderTopWidth: 1, borderTopColor: '#F0F0F0' }, productInfo: { flex: 1, justifyContent: 'space-between', paddingHorizontal: 20 }, productImage: { width: 80, height: (80 * 452) / 361 }, lastRowInfo: { flexDirection: 'row', justifyContent: 'space-between' }, txtName: { fontFamily: 'avenir', color: '#BCBCBC', fontSize: 18, fontWeight: '400' }, txtPrice: { fontFamily: 'avenir', color: '#B10D65', }, txtColor: { fontFamily: 'avenir' }, txtDetail: { fontFamily: 'avenir', color: '#B10D65', } });
$(document).ready(function() { var id_region = $('#txtId_region').val(); cargar_fb(); function cargar_fb() { funcion = 'cargarFb'; $.post('../../Controlador/region_controler.php', { funcion, id_region }, (response) => { const obj = JSON.parse(response); let template = `<div id="fb-root"></div> <br><br> <script async defer crossorigin="anonymous" src="https://connect.facebook.net/es_LA/sdk.js#xfbml=1&version=v10.0" nonce="5vkyCoVX"></script> <div class="fb-page" data-href="${obj.facebook}" data-tabs="timeline" data-width="" data-height="" data-small-header="true" data-adapt-container-width="true" data-hide-cover="false" data-show-facepile="true"> <blockquote cite="${obj.facebook}" class="fb-xfbml-parse-ignore"><a href="${obj.facebook}"></a></blockquote> </div>`; $('#divFb').html(template); }); } });
var RenewalFeeEscrow = artifacts.require('./RenewalFeeEscrow.sol') let SUBNETDAO_FOR_RECEIVING_PAYMENTS = '' module.exports = function (deployer, network, accounts) { if (network === 'development') { SUBNETDAO_FOR_RECEIVING_PAYMENTS = accounts[9] } console.log("Constructor arguments: ", SUBNETDAO_FOR_RECEIVING_PAYMENTS) deployer.deploy(RenewalFeeEscrow, SUBNETDAO_FOR_RECEIVING_PAYMENTS) }
import React from "react"; import Modal from "@material-ui/core/Modal"; import Backdrop from "@material-ui/core/Backdrop"; import Fade from "@material-ui/core/Fade"; import { useStyles } from "./style"; export default function ModalUntility(props) { const classes = useStyles(); const { item, open, setOpen } = props; const handleClose = () => { setOpen(false); }; return ( <div> <Modal className={classes.modal} open={open} onClose={handleClose} closeAfterTransition BackdropComponent={Backdrop} BackdropProps={{ timeout: 500, }} > <Fade in={open}> <div className={classes.paper}> <iframe width="100%" height="100%" src={item} loading="true" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" aria-controls ></iframe> </div> </Fade> </Modal> </div> ); }
import styled from 'styled-components'; const H1 = styled.h1` color: #04476d; font-size: calc(1.65vw + 1.65vh + 1.65vmin); font-weight: 800; line-height: 1.5; margin: 0; padding: 0 0 0 0; text-align: center; `; export default H1;
/** * Backbone object for all file actions functionality. */ var Files = Backbone.Model.extend({ defaults: { }, initialize: function () { }, /** * Rename a file. * * @param {string} promptQuestionString Translated version of "Which file to rename?". * @param {string} namespace The namespace. * @param {string} parentPath Parent path of the folder to rename. * @param {string} oldName Old name of the file to be renamed. * @param {object} element The object that calls this function, usually of type HTMLAnchorElement) */ renameFile: function (promptQuestionString, namespace, parentPath, oldName, element) { var newName = window.prompt(promptQuestionString, oldName); if (!newName.length) { return; } $.ajax({ url: bolt.paths.async + 'renamefile', type: 'POST', data: { namespace: namespace, parent: parentPath, oldname: oldName, newname: newName }, success: function (result) { document.location.reload(); }, error: function () { console.log('Something went wrong renaming this file!'); } }); }, /** * Delete a file from the server. * * @param {string} namespace * @param {string} filename * @param {object} element */ deleteFile: function (namespace, filename, element) { if (!confirm('Are you sure you want to delete ' + filename + '?')) { return; } $.ajax({ url: bolt.paths.async + 'deletefile', type: 'POST', data: { namespace: namespace, filename: filename }, success: function (result) { console.log('Deleted file ' + filename + ' from the server'); // If we are on the files table, remove image row from the table, as visual feedback if (element !== null) { $(element).closest('tr').slideUp(); } // TODO delete from Stack if applicable }, error: function () { console.log('Failed to delete the file from the server'); } }); }, duplicateFile: function (namespace, filename) { $.ajax({ url: bolt.paths.async + 'duplicatefile', type: 'POST', data: { namespace: namespace, filename: filename }, success: function (result) { document.location.reload(); }, error: function () { console.log('Something went wrong duplicating this file!'); } }); } });
/* https://www.codewars.com/kata/valid-parentheses/train/csharp Write a function called that takes a string of parentheses, and determines if the order of the parentheses is valid. The function should return true if the string is valid, and false if it's invalid. Examples "()" => true ")(()))" => false "(" => false "(())((()())())" => true Constraints 0 <= input.length <= 100 */ // Split into array // Move through array, if ( +1, if ) -1 // If it ever drops below zero, fail. If it ends at 0, pass function validParentheses(parens){ const arr = parens.split(''); let count = 0; arr.forEach((par, i) => { if (par === ')') { count++; } else if (par === '(') { count--; } else { return false; } if (count < 0) { return false; } }); return count === 0; }
import React, { useState } from 'react'; import { ButtonDropdown, DropdownToggle, DropdownMenu, DropdownItem } from 'reactstrap'; import './Account.css' import IconButton from "@material-ui/core/IconButton"; import Tooltip from "@material-ui/core/Tooltip"; import AddIcon from "@material-ui/icons/Add"; import { Link } from 'react-router-dom'; const Example = (props) => { const [dropdownOpen, setOpen] = useState(false); const toggle = () => setOpen(!dropdownOpen); return ( <ButtonDropdown isOpen={dropdownOpen} toggle={toggle}> <DropdownToggle style={{backgroundColor:'white', border: 'none'}} caret> <Tooltip title={"Tambah Data Karyawan"}> <IconButton> <AddIcon /> </IconButton> </Tooltip> </DropdownToggle> <DropdownMenu> <Link to="/add-account"><DropdownItem>Add Acount</DropdownItem></Link> </DropdownMenu> </ButtonDropdown> ); } export default Example;
import React from 'react' import ReactDOM from 'react-dom' class UserInfo extends React.Component { constructor(props) { super(props) this.state = { message: '', region: {} } this.changeProvice = this.changeProvice.bind(this) this.changeCity = this.changeCity.bind(this) this.submit = this.submit.bind(this) } componentDidMount() { // console.log(location.search) let uuid = urlParameter('uuid') if (!!!uuid) { this.setState({ message: '้“พๆŽฅๆฅๆบๅผ‚ๅธธใ€‚' }) } let elProvince = document.getElementById('province') axios({ method: 'GET', url: './assets/data/list.json', responseType: 'json' }).then(response => { this.setState({ region: response.data }) for (let key in response.data) { if (key.substr(2, 4) === '0000') { elProvince.options.add(new Option(response.data[key], key)) } } }) } changeProvice() { let elProvince = document.getElementById('province') let elCity = document.getElementById('city') let elDistrict = document.getElementById('district') elCity.innerHTML = '' elCity.options.add(new Option('ๆœช้€‰ๆ‹ฉ', '')) elDistrict.innerHTML = '' elDistrict.options.add(new Option('ๆœช้€‰ๆ‹ฉ', '')) for (let key in this.state.region) { if (key.substr(0, 2) === elProvince.value.substr(0, 2) && key.substr(2, 4) !== '0000') { if (elProvince.options[elProvince.options.selectedIndex].text.indexOf('ๅธ‚') !== -1) { elCity.options.add(new Option(this.state.region[key], key)) } else { if (key.substr(4, 2) === '00') { elCity.options.add(new Option(this.state.region[key], key)) } } } } } changeCity() { let elProvince = document.getElementById('province') let elCity = document.getElementById('city') let elDistrict = document.getElementById('district') elDistrict.innerHTML = '' elDistrict.options.add(new Option('ๆœช้€‰ๆ‹ฉ', '')) if (elProvince.options[elProvince.options.selectedIndex].text.indexOf('ๅธ‚') !== -1) { return false } for (let key in this.state.region) { if (key.substr(0, 4) === elCity.value.substr(0, 4) && key.substr(4, 2) !== '00') { elDistrict.options.add(new Option(this.state.region[key], key)) } } } submit() { this.setState({ message: '' }) let elName = document.getElementById('name') let elMobile = document.getElementById('mobile') let elProvince = document.getElementById('province') let elCity = document.getElementById('city') let elAddress = document.getElementById('address') let elPostage = document.getElementById('postage') if (!!!elName.value || !!!elMobile.value || !!!elProvince.value || !!!elCity.value || !!!elAddress.value || !!!elPostage.checked) { this.setState({ message: '่ฏทๅฎŒๆ•ดๅกซๅ†™็”จๆˆทไฟกๆฏใ€‚' }) return false } axios({ method: 'POST', url: './api/customer/', data: { user_uuid: urlParameter('uuid'), name: elName.value, mobile: elMobile.value, province: elProvince.value, city: elCity.value, district: document.getElementById('district').value, address: elAddress.value, postage: elPostage.checked }, responseType: 'json' }).then(response => { console.log(response.data) }) } render() { return ( <div className="row"> <div className="col-12"> <h2>ๅกซๅ†™็”จๆˆทไฟกๆฏ</h2> <hr/> <div className="form-group"> <label className="text-primary">ๅง“ๅ</label> <input type="text" id="name" className="form-control"/> <label className="text-secondary">่ฏทๅกซๅ†™ๆ”ถ่ดงไบบๅ…จๅ๏ผˆ่ต„ๆ–™ไธ่ฏฆ๏ผŒไธไบˆๅ‘่ดง๏ผ‰</label> </div> <div className="form-group"> <label className="text-primary">ๆ‰‹ๆœบๅท</label> <input type="text" id="mobile" className="form-control"/> <label className="text-secondary">่ฏทๅกซๅ†™ๆญฃ็กฎๆ‰‹ๆœบๅท็ ๏ผˆๅท็ ไธ่ฏฆ๏ผŒไธไบˆๅ‘่ดง๏ผ‰</label> </div> <div className="form-group"> <label className="text-primary">ๆ”ถ่ดงๅœฐๅ€</label> <select id="province" className="form-control" onChange={this.changeProvice}> <option value="">ๆœช้€‰ๆ‹ฉ</option> </select> <br/> <select id="city" className="form-control" onChange={this.changeCity}> <option value="">ๆœช้€‰ๆ‹ฉ</option> </select> <br/> <select id="district" className="form-control"> <option value="">ๆœช้€‰ๆ‹ฉ</option> </select> <span className="text-secondary">ๆ–ฐ็–†ใ€่ฅฟ่—ใ€ๆธฏๆพณๅฐ็ญ‰ๅœฐๅŒบไธๅ‚ไธŽๆญคๆฌกๆดปๅŠจ</span> </div> <div className="form-group"> <label className="text-primary">่ฏฆ็ป†่ก—้“ๅœฐๅ€</label> <input type="text" id="address" className="form-control"/> <span className="text-danger">่ฏทๅกซๅ†™ๅŽฟ/ไนก/่ก—้“/่ทฏ/ๅท๏ผˆ่ต„ๆ–™ไธ่ฏฆ๏ผŒไธไบˆๅ‘่ดง๏ผ‰</span> </div> <div className="form-check"> <input type="radio" value="postage" id="postage" className="form-check-input"/> <label className="text-primary" htmlFor="postage">ๆŽฅๅ—้‚ฎ่ดน่‡ช็†(่ฟ่ดน+ไฟไปท่ดนๅœจ19่‡ณ39ๅ…ƒไน‹้—ด๏ผŒๆ”ถๅˆฐ่ดงๆ”ฏไป˜็ป™ๅฟซ้€’ๅฐๅ“ฅๅณๅฏ๏ผŒๅ่ฟœๅœฐๅŒบๆœ€้ซ˜ไธ่ถ…่ฟ‡39ๅ…ƒ๏ผŒไธๆŽฅๅ—็š„ไธไบˆๅ‘่ดง๏ผ๏ผ‰</label> </div> <hr/> <div className="col-12"> <span className="text-danger">ๆธฉ้ฆจๆ็คบ๏ผš</span> <span className="text-primary"> ๆœฌๆฌกๆดปๅŠจ้™้‡2000ๅฅ—๏ผŒๆŠขๅฎŒๆˆชๆญข๏ผไป…ๅ…่ดนๆไพ›็คผๅ“๏ผŒ้‚ฎ่ดน่‡ช็†ใ€‚ </span> <br/> <br/> </div> {this.state.message && <div className="col-12 alert alert-danger"> {this.state.message} </div> } <div className="col-12"> <button type="button" id="submit" className="btn btn-outline-dark btn-block" onClick={this.submit}> ๅกซๅ†™ๅฎŒๆฏ•๏ผŒ็กฎ่ฎคๆไบคใ€‚ </button> </div> </div> </div> ) } } ReactDOM.render( <UserInfo/>, document.getElementById('app') )
import { mount, shallowMount } from '@vue/test-utils' import Pageables from '@/store/Pageables.js' describe('Pageables.vue', () => { describe('Getters', () => { it ('returns all the pages', () => { const state = { all: [] } expect(Pageables.getters['all'](state)).toEqual([]); }) it ('returns all the pages by id', () => { const state = { all: [ {id: 1, title: 'Foo'}, {id: 2, title: 'Bar'}, {id: 3, title: 'Baz'}, {id: 2, title: 'BarBaz'}, {id: 4, title: 'Foobar'}, ] } expect(Pageables.getters['allById'](state)(2)).toEqual([ {id: 2, title: 'Bar'}, {id:2, title: 'BarBaz'} ]); }) it ('returns the first page by id', () => { const state = { all: [ {id: 1, title: 'Foo'}, {id: 2, title: 'Bar'}, {id: 3, title: 'Baz'}, {id: 2, title: 'BarBaz'}, {id: 4, title: 'Foobar'}, ] } expect(Pageables.getters['byId'](state)(2)).toEqual({id: 2, title: 'Bar'}); }) it ('returns elements by a page slug', () => { const state = { dictionary: { 'page-1': [{id: 1, title: 'Foo'}], 'page-2': [{id: 2, title: 'Bar'}], 'page-3': [{id: 3, title: 'Baz'}], } } expect(Pageables.getters['byPageSlug'](state)('page-2')).toEqual([{id: 2, title: 'Bar'}]); expect(Pageables.getters['byPageSlug'](state)('page-4')).toEqual([]); }) it ('returns an empty array if page slug does not exist', () => { const state = { dictionary: { } } expect(Pageables.getters['byPageSlug'](state)('page-4')).toEqual([]); }) it ('returns elements count by a page slug', () => { const state = { dictionary: { 'page-1': [{id: 1, title: 'Foo'}], 'page-2': [{id: 2, title: 'Bar'}], 'page-3': [{id: 3, title: 'Baz'}], } } expect(Pageables.getters['countByPageSlug'](state)('page-2')).toEqual(1); expect(Pageables.getters['countByPageSlug'](state)('page-4')).toEqual(0); }) it ('asserts that a page has an element by id', () => { const state = { dictionary: { 'page-1': [{id: 1, title: 'Foo'}], 'page-2': [{id: 2, title: 'Bar'}], 'page-3': [{id: 3, title: 'Baz'}], } } expect(Pageables.getters['pageHas'](state)({ page: {slug: 'page-1'}, record: {id: 1} })).toEqual(true); expect(Pageables.getters['pageHas'](state)({ page: {slug: 'page-1'}, record: {id: 2} })).toEqual(false); }) it ('asserts that a page has an element by id and pivot property', () => { const state = { dictionary: { 'page-1': [ {id: 1, title: 'Foo', pivot: {preferences: {color: 'red'}}}, {id: 1, title: 'Bar', pivot: {preferences: {color: 'blue'}}}, ], } } expect(Pageables.getters['pageHasWithPivot'](state)({ page: {slug: 'page-1'}, record: {id: 1, pivot: {preferences: {color: 'red'}}}, pivotProperty: 'color', })).toEqual(true); expect(Pageables.getters['pageHasWithPivot'](state)({ page: {slug: 'page-1'}, record: {id: 1, pivot: {preferences: {color: 'green'}}}, pivotProperty: 'color', })).toEqual(false); }) it ('returns an array of ids for pageables associated with a page', () => { const state = { dictionary: { 'page-1': [ {id: 1, title: 'Foo'}, {id: 3, title: 'Bar'}, ], 'page-2': [ {id: 2, title: 'Baz'} ] } } expect(Pageables.getters['idsForPage'](state)({slug: 'page-1'})).toEqual([1, 3]); }) it ('returns an array of ids and pivot data for pageables associated with a page', () => { const state = { dictionary: { 'page-1': [ {id: 1, title: 'Foo', pivot: {preferences: {color: 'red'}}}, {id: 3, title: 'Bar', pivot: {preferences: {color: 'blue'}}}, ], 'page-2': [ {id: 2, title: 'Foo', pivot: {preferences: {color: 'green'}}}, ], } } expect(Pageables.getters['idsAndPivotForPage'](state)({ page: {slug: 'page-1'}, pivotProperty: 'color', })).toEqual([ {id: 1, color: 'red'}, {id: 3, color: 'blue'} ]); }) }) describe('Mutators', () => { let payload; beforeEach (() => { payload = { '_library': [{id: 1, title: 'Red'}, {id: 2, title: 'Green'}, {id: 3, title: 'Blue'}], 'page-1': [{id: 1, title: 'Red'}], 'page-2': [{id: 2, title: 'Green'}, {id: 3, title: 'Blue'}], 'page-3': [], } }) it ('initializes the store', () => { const state = { all: [], dictionary: {}, } expect(state.all).toEqual([]); expect(state.dictionary).toEqual({}); Pageables.mutations['initialize'](state, payload) expect(state.all).toBe(payload['_library']); expect(state.dictionary).toBe(payload); }) it ('initializes the store without a library property', () => { const state = { all: [], dictionary: {}, } let dictionary = { 'page-1': [{id: 1, title: 'Red'}], 'page-2': [{id: 2, title: 'Green'}, {id: 3, title: 'Blue'}], 'page-3': [], } expect(state.all).toEqual([]); expect(state.dictionary).toEqual({}); Pageables.mutations['initialize'](state, dictionary) expect(state.all).toBe(dictionary); expect(state.dictionary).toBe(dictionary); }) it ('removes a pageable by id', () => { const state = { all: [{id: 1}, {id: 2}, {id: 3}, {id: 2}] } expect(state.all.length).toBe(4); Pageables.mutations['removeById'](state, 2); expect(state.all.length).toBe(2); }) it ('overrides a pageable by id', () => { const state = { all: [ {id: 1, title: 'Red'}, {id: 2, title: 'Green'}, {id: 3, title: 'Blue'}, {id: 2, title: 'Brown'} ] } expect(state.all.length).toBe(4); expect(state.all[1]).toEqual({id: 2, title: 'Green'}); expect(state.all[3]).toEqual({id: 2, title: 'Brown'}); Pageables.mutations['overrideById'](state, { id: 2, record: {id: 2, title: 'Orange'} }); expect(state.all.length).toBe(4); expect(state.all[1]).toEqual({id: 2, title: 'Orange'}); expect(state.all[3]).toEqual({id: 2, title: 'Orange'}); }) it ('adds a pageable to the library', () => { const state = { all: [ {id: 1, title: 'Red'}, {id: 2, title: 'Green'}, {id: 3, title: 'Blue'}, ] } expect(state.all.length).toBe(3); Pageables.mutations['add'](state, {id: 4, title: 'Orange'}); expect(state.all.length).toBe(4); }) it ('adds a pageable to a page by slug', () => { const state = { dictionary: { 'page-1': [{id: 1, title: 'Red'}], 'page-2': [{id: 2, title: 'Green'}, {id: 3, title: 'Blue'}], 'page-3': [], } } expect(state.dictionary['page-1'].length).toBe(1); Pageables.mutations['addToPage'](state, { page: {id: 1, slug: 'page-1'}, record: {id: 4, title: 'Orange'} }); expect(state.dictionary['page-1'].length).toBe(2); }) it ('removes a pageable from a page by slug', () => { const state = { dictionary: { 'page-1': [{id: 1, title: 'Red'}], 'page-2': [{id: 2, title: 'Green'}, {id: 3, title: 'Blue'}], 'page-3': [], } } expect(state.dictionary['page-2'].length).toBe(2); Pageables.mutations['removeFromPage'](state, { page: {slug: 'page-2'}, record: {id: 3} }); expect(state.dictionary['page-2'].length).toBe(1); }) it ('removes a pageable from a page by index', () => { const state = { dictionary: { 'page-1': [{id: 1, title: 'Red'}], 'page-2': [{id: 2, title: 'Green'}, {id: 3, title: 'Blue'}], 'page-3': [], } } expect(state.dictionary['page-2'].length).toBe(2); Pageables.mutations['removeFromPageByIndex'](state, { page: {slug: 'page-2'}, index: 0 }); expect(state.dictionary['page-2'].length).toBe(1); expect(state.dictionary['page-2'][0]).toEqual({id: 3, title: 'Blue'}); }) it ('removes a pageable from a page by id and by pivot', () => { const state = { dictionary: { 'page-1': [ {id: 1, title: 'Foo', pivot: {preferences: {color: 'red'}}} ], 'page-2': [ {id: 2, title: 'Bar', pivot: {preferences: {color: 'lime'}}}, {id: 2, title: 'Bar', pivot: {preferences: {color: 'green'}}}, {id: 3, title: 'Baz', pivot: {preferences: {color: 'blue'}}} ], 'page-3': [], } } expect(state.dictionary['page-2'].length).toBe(3); Pageables.mutations['removeFromPageByIdAndPivot'](state, { page: {slug: 'page-2'}, record: {id: 2, pivot: {preferences: {color: 'green'}}}, pivotProperty: 'color' }); expect(state.dictionary['page-2'].length).toBe(2); expect(state.dictionary['page-2'][0].title).toEqual('Bar'); expect(state.dictionary['page-2'][0].pivot.preferences.color).toEqual('lime'); expect(state.dictionary['page-2'][1].title).toEqual('Baz'); expect(state.dictionary['page-2'][1].pivot.preferences.color).toEqual('blue'); }) describe('Modify pages pageables if the page has none', () => { let state; beforeEach (() => { state = { dictionary: {} } }) it ('adds a pageable to a page by slug', () => { expect(Object.keys(state.dictionary).length).toBe(0); Pageables.mutations['addToPage'](state, { page: {id: 1, slug: 'page-4'}, record: {id: 4, title: 'Orange'} }); expect(Object.keys(state.dictionary).length).toBe(1); expect(state.dictionary['page-4'].length).toBe(1); }) it ('removes a pageable from a page by slug', () => { expect(Object.keys(state.dictionary).length).toBe(0); Pageables.mutations['removeFromPage'](state, { page: {slug: 'page-2'}, record: {id: 3} }); expect(Object.keys(state.dictionary).length).toBe(1); }) it ('removes a pageable from a page by index', () => { expect(Object.keys(state.dictionary).length).toBe(0); Pageables.mutations['removeFromPageByIndex'](state, { page: {slug: 'page-2'}, index: 0 }); expect(Object.keys(state.dictionary).length).toBe(1); }) it ('removes a pageable from a page by id and by pivot', () => { expect(Object.keys(state.dictionary).length).toBe(0); Pageables.mutations['removeFromPageByIdAndPivot'](state, { page: {slug: 'page-4'}, record: {id: 2, pivot: {preferences: {color: 'green'}}}, pivotProperty: 'color' }); expect(Object.keys(state.dictionary).length).toBe(1); }) }) }) })
/** * ํ™”๋ฉด ์ดˆ๊ธฐํ™” - ํ™”๋ฉด ๋กœ๋“œ์‹œ ์ž๋™ ํ˜ธ์ถœ ๋จ */ function _Initialize() { // ๋‹จ์œ„ํ™”๋ฉด์—์„œ ์‚ฌ์šฉ๋  ์ผ๋ฐ˜ ์ „์—ญ ๋ณ€์ˆ˜ ์ •์˜ $NC.setGlobalVar({ // ์ฒดํฌํ•  ์ •์ฑ… ๊ฐ’ policyVal: { LI420: "" // ์žฌ๊ณ  ๊ด€๋ฆฌ ๊ธฐ์ค€ }, printOptions: [{ PRINT_INDEX: 0, PRINT_COMMENT: "์ž…๊ณ ๋ผ๋ฒจ ์ถœ๋ ฅ" }], // ์˜ค๋ฅธ์ชฝ ํ•˜๋‹จ ๊ทธ๋ฆฌ๋“œ NEW๋ฒ„ํŠผ ํด๋ฆญ์‹œ๋งˆ๋‹ค 1์”ฉ ์ฆ๊ฐ€ SEQ_NO: 0 }); // ๊ทธ๋ฆฌ๋“œ ์ดˆ๊ธฐํ™” grdMasterInitialize(); grdDetailInitialize(); grdSubInitialize(); grdSub1Initialize(); // ์กฐํšŒ์กฐ๊ฑด - ๋ฌผ๋ฅ˜์„ผํ„ฐ ์„ธํŒ… $NC.setInitCombo("/WC/getDataSet.do", { P_QUERY_ID: "WC.POP_CSUSERCENTER", P_QUERY_PARAMS: $NC.getParams({ P_USER_ID: $NC.G_USERINFO.USER_ID, P_CENTER_CD: "%" }) }, { selector: "#cboQCenter_Cd", codeField: "CENTER_CD", nameField: "CENTER_NM", onComplete: function() { $NC.setValue("#cboQCenter_Cd", $NC.G_USERINFO.CENTER_CD); // ์ •์ฑ…์ฝ”๋“œ ์ทจ๋“ setPolicyValInfo(); } }); // ์กฐํšŒ์กฐ๊ฑด - ์ž…๊ณ ๊ตฌ๋ถ„ ์„ธํŒ… $NC.setInitCombo("/WC/getDataSet.do", { P_QUERY_ID: "WC.POP_CMCODE", P_QUERY_PARAMS: $NC.getParams({ P_CODE_GRP: "INOUT_CD", P_CODE_CD: "%", P_SUB_CD1: "E1", P_SUB_CD2: "E2" }) }, { selector: "#cboQInout_Cd", codeField: "CODE_CD", nameField: "CODE_NM", fullNameField: "CODE_CD_F", addAll: true }); // ์ถ”๊ฐ€ ์กฐํšŒ์กฐ๊ฑด ์‚ฌ์šฉ $NC.setInitAdditionalCondition(); // ๋ธŒ๋žœ๋“œ ์ดˆ๊ธฐ๊ฐ’ ์„ค์ • $NC.setValue("#edtQBu_Cd", $NC.G_USERINFO.BU_CD); $NC.setValue("#edtQBu_Nm", $NC.G_USERINFO.BU_NM); $("#btnQBu_Cd").click(showUserBuPopup); $("#btnQBrand_Cd").click(showBuBrandPopup); $("#btnQVendor_Cd").click(showVendorPopup); // ๋ธŒ๋žœ๋“œ์˜ ์œ„ํƒ์‚ฌ ์ฝ”๋“œ ๊ฐ’ ์„ค์ • $NC.setValue("#edtQCust_Cd", $NC.G_USERINFO.CUST_CD); // ๋ถ„ํ• ๊ตฌ๋ถ„ ์ดˆ๊ธฐ๊ฐ’ ์„ค์ • (์ฒดํฌ) $NC.setValue("#rgbQSplit_Div1", "1"); // ์ถœ๊ณ ์ผ์ž์— ๋‹ฌ๋ ฅ์ด๋ฏธ์ง€ ์„ค์ • $NC.setInitDatePicker("#dtpQInbound_Date"); // ์ž๋™๋ถ„ํ•  ํด๋ฆญ ์ด๋ฒคํŠธ $("#btnAutoSplit").click(autoSplit); // ์ €์žฅ๊ถŒํ•œ์ด ์žˆ๋Š” ๊ฒฝ์šฐ๋งŒ ์ž๋™๋ถ„ํ•  ๊ฐ€๋Šฅ var permission = $NC.getProgramPermission(); $NC.setEnable("#btnAutoSplit", permission.canSave); } function _OnLoaded() { // $NC.setInitSplitter("#divRightView", "h", 200); } /** * ํ™”๋ฉด ๋ฆฌ์‚ฌ์ด์ฆˆ Offset ์„ธํŒ… */ function _SetResizeOffset() { $NC.G_OFFSET.leftViewWidth = 800; $NC.G_OFFSET.RightViewHeight = 100; $NC.G_OFFSET.nonClientHeight = $("#divConditionView").outerHeight() + $NC.G_LAYOUT.nonClientHeight; //$NC.G_OFFSET.rightBottomHeightOffset = $("#divSplitInfo").outerHeight(); // $NC.G_OFFSET.rightBottom1HeightOffset = $("#divSplitInfo").outerHeight(); } /** * Window Resize Event - Window Size ์กฐ์ •์‹œ ํ˜ธ์ถœ ๋จ */ function _OnResize(parent) { var clientWidth = parent.width() - $NC.G_OFFSET.leftViewWidth - $NC.G_LAYOUT.nonClientWidth; var clientHeight = parent.height() - $NC.G_OFFSET.nonClientHeight; var testHeight = Math.ceil(clientHeight / 3); $NC.resizeContainer("#divLeftView", $NC.G_OFFSET.leftViewWidth, clientHeight); $NC.resizeContainer("#divRightView", clientWidth, testHeight * 3 ); // Grid ์‚ฌ์ด์ฆˆ ์กฐ์ • $NC.resizeGrid("#grdMaster", $NC.G_OFFSET.leftViewWidth, clientHeight - $NC.G_LAYOUT.header); // Grid ์‚ฌ์ด์ฆˆ ์กฐ์ • $NC.resizeGrid("#grdDetail", clientWidth, testHeight - $NC.G_LAYOUT.header ); var test1 = $NC.G_LAYOUT.header - 10 + 'px'; // Grid ์‚ฌ์ด์ฆˆ ์กฐ์ • $NC.resizeGrid("#grdSub1", clientWidth, testHeight - $NC.G_LAYOUT.header ); // Grid ์‚ฌ์ด์ฆˆ ์กฐ์ • $NC.resizeGrid("#grdSub", clientWidth, testHeight - $NC.G_LAYOUT.header ); } /** * Input, Select Change Event ์ฒ˜๋ฆฌ * * @param e * ์ด๋ฒคํŠธ ํ•ธ๋“ค๋Ÿฌ * @param view * ๋Œ€์ƒ Object */ function _OnConditionChange(e, view, val) { // ์กฐํšŒ ์กฐ๊ฑด์— Object Change var id = view.prop("id").substr(4).toUpperCase(); switch (id) { case "CENTER_CD": setPolicyValInfo(); break; //์‚ฌ์—…๋ถ€ Key ์ž…๋ ฅ case "BU_CD": var P_QUERY_PARAMS; var O_RESULT_DATA = [ ]; if (!$NC.isNull(val)) { P_QUERY_PARAMS = { P_USER_ID: $NC.G_USERINFO.USER_ID, P_BU_CD: val }; O_RESULT_DATA = $NP.getUserBuInfo({ queryParams: P_QUERY_PARAMS }); } if (O_RESULT_DATA.length <= 1) { onUserBuPopup(O_RESULT_DATA[0]); } else { $NP.showUserBuPopup({ queryParams: P_QUERY_PARAMS, queryData: O_RESULT_DATA }, onUserBuPopup, onUserBuPopup); } return; // ๋ธŒ๋žœ๋“œ Key ์ž…๋ ฅ case "BRAND_CD": var P_QUERY_PARAMS; var O_RESULT_DATA = [ ]; if (!$NC.isNull(val)) { var BU_CD = $NC.getValue("#edtQBu_Cd"); P_QUERY_PARAMS = { P_BU_CD: BU_CD, P_BRAND_CD: val }; O_RESULT_DATA = $NP.getBuBrandInfo({ queryParams: P_QUERY_PARAMS }); } if (O_RESULT_DATA.length <= 1) { onBuBrandPopup(O_RESULT_DATA[0]); } else { $NP.showBuBrandPopup({ queryParams: P_QUERY_PARAMS, queryData: O_RESULT_DATA }, onBuBrandPopup, onBuBrandPopup); } return; case "VENDOR_CD": var P_QUERY_PARAMS; var O_RESULT_DATA = [ ]; if (!$NC.isNull(val)) { var CUST_CD = $NC.getValue("#edtQCust_Cd"); P_QUERY_PARAMS = { P_CUST_CD: CUST_CD, P_VENDOR_CD: val, P_VIEW_DIV: "2" }; O_RESULT_DATA = $NP.getVendorInfo({ queryParams: P_QUERY_PARAMS }); } if (O_RESULT_DATA.length <= 1) { onVendorPopup(O_RESULT_DATA[0]); } else { $NP.showVendorPopup({ queryParams: P_QUERY_PARAMS, queryData: O_RESULT_DATA }, onVendorPopup, onVendorPopup); } return; case "INBOUND_DATE": $NC.setValueDatePicker(view, val, "๊ฒ€์ƒ‰ ์ž…๊ณ ์ผ์ž๋ฅผ ์ •ํ™•ํžˆ ์ž…๋ ฅํ•˜์‹ญ์‹œ์˜ค."); break; } // ํ™”๋ฉดํด๋ฆฌ์–ด onChangingCondition(); } /** * Input Change Event - Input, Select Change ์‹œ ํ˜ธ์ถœ ๋จ */ function _OnInputChange(e, view, val) { } /** * Inquiry Button Event - ๋ฉ”์ธ ์ƒ๋‹จ ์กฐํšŒ ๋ฒ„ํŠผ ํด๋ฆญ์‹œ ํ˜ธ์ถœ ๋จ */ function _Inquiry() { var CENTER_CD = $NC.getValue("#cboQCenter_Cd"); if ($NC.isNull(CENTER_CD)) { alert("๋ฌผ๋ฅ˜์„ผํ„ฐ๋ฅผ ์„ ํƒํ•˜์‹ญ์‹œ์˜ค."); $NC.setFocus("#cboQCenter_Cd"); return; } var BU_CD = $NC.getValue("#edtQBu_Cd"); if ($NC.isNull(BU_CD)) { alert("์‚ฌ์—…๋ถ€์ฝ”๋“œ๋ฅผ ์ž…๋ ฅํ•˜์‹ญ์‹œ์˜ค."); $NC.setFocus("#edtQBrand_Cd"); return; } var INOUND_DATE = $NC.getValue("#dtpQInbound_Date"); if ($NC.isNull(INOUND_DATE)) { alert("์ž…๊ณ ์ผ์ž๋ฅผ ์ž…๋ ฅํ•˜์‹ญ์‹œ์˜ค."); $NC.setFocus("#dtpQInbound_Date"); return; } var BRAND_CD = $NC.getValue("#edtQBrand_Cd", true); var VENDOR_CD = $NC.getValue("#edtQVendor_Cd", true); var ITEM_CD = $NC.getValue("#edtQItem_Cd", true); var ITEM_NM = $NC.getValue("#edtQItem_Nm", true); var INOUT_CD = $NC.getValue("#cboQInout_Cd"); // ์กฐํšŒ์‹œ ์ „์—ญ ๋ณ€์ˆ˜ ๊ฐ’ ์ดˆ๊ธฐํ™” $NC.setInitGridVar(G_GRDMASTER); $NC.setInitGridVar(G_GRDDETAIL); $NC.setInitGridVar(G_GRDSUB); G_GRDMASTER.queryParams = $NC.getParams({ P_CENTER_CD: CENTER_CD, P_BU_CD: BU_CD, P_INBOUND_DATE: INOUND_DATE, P_INOUT_CD: INOUT_CD, P_VENDOR_CD: VENDOR_CD, P_BRAND_CD: BRAND_CD, P_ITEM_CD: ITEM_CD, P_ITEM_NM: ITEM_NM }); // ๋ฐ์ดํ„ฐ ์กฐํšŒ $NC.serviceCall("/LI05010E/getDataSet.do", $NC.getGridParams(G_GRDMASTER), onGetMaster); } /** * New Button Event - ๋ฉ”์ธ ์ƒ๋‹จ ์‹ ๊ทœ ๋ฒ„ํŠผ ํด๋ฆญ์‹œ ํ˜ธ์ถœ ๋จ */ function _New() { } /** * Save Button Event - ๋ฉ”์ธ ์ƒ๋‹จ ์ €์žฅ ๋ฒ„ํŠผ ํด๋ฆญ์‹œ ํ˜ธ์ถœ ๋จ */ function _Save() { if (G_GRDMASTER.data.getLength() === 0 || G_GRDDETAIL.data.getLength() === 0 || G_GRDSUB.data.getLength() === 0) { alert("์ €์žฅํ•  ๋ฐ์ดํ„ฐ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค."); return; } // ํ˜„์žฌ ์ˆ˜์ •๋ชจ๋“œ๋ฉด if (G_GRDSUB.view.getEditorLock().isActive()) { G_GRDSUB.view.getEditorLock().commitCurrentEdit(); } var totConfirmQty = 0; var rowDetailData = G_GRDDETAIL.data.getItem(G_GRDDETAIL.lastRow); var saveDS = [ ]; var rowCount = G_GRDSUB.data.getLength(); for ( var row = 0; row < rowCount; row++) { var rowData = G_GRDSUB.data.getItem(row); totConfirmQty += Number(rowData.CONFIRM_QTY); if (rowData.CRUD !== "R") { if (!grdSubOnBeforePost(row)) { return; } var saveData = { P_CENTER_CD: rowData.CENTER_CD, P_BU_CD: rowData.BU_CD, P_INBOUND_DATE: rowData.INBOUND_DATE, P_INBOUND_NO: rowData.INBOUND_NO, P_LINE_NO: rowData.LINE_NO, P_INBOUND_SEQ: rowData.INBOUND_SEQ, P_LOCATION_CD: rowData.LOCATION_CD, P_ENTRY_QTY: rowData.CONFIRM_QTY, P_CONFIRM_QTY: rowData.CONFIRM_QTY, P_CRUD: rowData.CRUD }; saveDS.push(saveData); } } if (totConfirmQty != Number(rowDetailData.ENTRY_QTY)) { alert("๋“ฑ๋ก์ˆ˜๋Ÿ‰(" + rowDetailData.ENTRY_QTY + ")๊ณผ \nํ™•์ •์ˆ˜๋Ÿ‰์˜ ํ•ฉ(" + totConfirmQty + ")์ด ์ผ์น˜ํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค."); return; } if (saveDS.length > 0) { $NC.serviceCall("/LI05010E/save.do", { P_DS_MASTER: $NC.toJson(saveDS), P_USER_ID: $NC.G_USERINFO.USER_ID }, onSave, onSaveError); } } /** * Delete Button Event - ๋ฉ”์ธ ์ƒ๋‹จ ์‚ญ์ œ ๋ฒ„ํŠผ ํด๋ฆญ์‹œ ํ˜ธ์ถœ ๋จ */ function _Delete() { } /** * Cancel Button Event - ๋ฉ”์ธ ์ƒ๋‹จ ์ทจ์†Œ ๋ฒ„ํŠผ ํด๋ฆญ์‹œ ํ˜ธ์ถœ ๋จ */ function _Cancel() { var lastKeyVal = $NC.getGridLastKeyVal(G_GRDMASTER, { selectKey: "INBOUND_NO" }); var lastKeyValD = $NC.getGridLastKeyVal(G_GRDDETAIL, { selectKey: "LINE_NO" }); var lastKeyValS = $NC.getGridLastKeyVal(G_GRDSUB, { selectKey: "INBOUND_SEQ" }); _Inquiry(); G_GRDMASTER.lastKeyVal = lastKeyVal; G_GRDDETAIL.lastKeyVal = lastKeyValD; G_GRDSUB.lastKeyVal = lastKeyValS; } /** * Print Button Event - ๋ฉ”์ธ ์ƒ๋‹จ ์ถœ๋ ฅ ๋ฒ„ํŠผ ํด๋ฆญ์‹œ ํ˜ธ์ถœ ๋จ * * @param printIndex * ์„ ํƒํ•œ ์ถœ๋ ฅ๋ฌผ Index */ function _Print(printIndex, printName) { if (G_GRDDETAIL.data.getLength() == 0 || G_GRDDETAIL.lastRow == null) { alert("์ถœ๋ ฅํ•  ๋ฐ์ดํ„ฐ๋ฅผ ์„ ํƒํ•˜์‹ญ์‹œ์˜ค."); return; } var rowData = G_GRDDETAIL.data.getItem(G_GRDDETAIL.lastRow); // ์ž…๊ณ ๋ผ๋ฒจ if (printIndex == 0) { // ์ถœ๋ ฅ ํ˜ธ์ถœ $NC.G_MAIN.showPrintPreview({ reportDoc: "common/LABEL_PALLET", queryId: "WR.RS_LABEL_PALLET02", queryParams: { P_CENTER_CD: rowData.CENTER_CD, P_BU_CD: rowData.BU_CD, P_INBOUND_DATE: rowData.INBOUND_DATE, P_INBOUND_NO: rowData.INBOUND_NO, P_LINE_NO: rowData.LINE_NO, P_PROCESS_GRP: "LI" } }); } } function grdMasterOnGetColumns() { var columns = [ ]; $NC.setGridColumn(columns, { id: "INBOUND_NO", field: "INBOUND_NO", name: "์ž…๊ณ ๋ฒˆํ˜ธ", minWidth: 80, cssClass: "align-center" }); $NC.setGridColumn(columns, { id: "VENDOR_NM", field: "VENDOR_NM", name: "๊ณต๊ธ‰์ฒ˜", minWidth: 150 }); $NC.setGridColumn(columns, { id: "INOUT_NM", field: "INOUT_NM", name: "์ž…๊ณ ๊ตฌ๋ถ„", minWidth: 80 }); $NC.setGridColumn(columns, { id: "ORDER_DATE", field: "ORDER_DATE", name: "์˜ˆ์ •์ผ์ž", minWidth: 80, cssClass: "align-center" }); $NC.setGridColumn(columns, { id: "ORDER_NO", field: "ORDER_NO", name: "์˜ˆ์ •๋ฒˆํ˜ธ", minWidth: 70, cssClass: "align-center" }); $NC.setGridColumn(columns, { id: "BU_DATE", field: "BU_DATE", name: "์ „ํ‘œ์ผ์ž", minWidth: 80, cssClass: "align-center" }); $NC.setGridColumn(columns, { id: "BUD_NO", field: "BU_NO", name: "์ „ํ‘œ๋ฒˆํ˜ธ", minWidth: 100 }); $NC.setGridColumn(columns, { id: "REMARK1", field: "REMARK1", name: "๋น„๊ณ ", minWidth: 130 }); return $NC.setGridColumnDefaultFormatter(columns); } /** * ์™ผ์ชฝ๊ทธ๋ฆฌ๋“œ ์ดˆ๊ธฐํ™” */ function grdMasterInitialize() { var options = { frozenColumn: 1 }; // Grid Object, DataView ์ƒ์„ฑ ๋ฐ ์ดˆ๊ธฐํ™” $NC.setInitGridObject("#grdMaster", { columns: grdMasterOnGetColumns(), queryId: "LI05010E.RS_MASTER", sortCol: "INBOUND_NO", gridOptions: options }); G_GRDMASTER.view.onSelectedRowsChanged.subscribe(grdMasterOnAfterScroll); } function grdDetailOnGetColumns(policyLI420) { if ($NC.isNull(policyLI420)) { policyLI420 = "1"; } var columns = [ ]; $NC.setGridColumn(columns, { id: "LINE_NO", field: "LINE_NO", name: "์ˆœ๋ฒˆ", minWidth: 50, cssClass: "align-right" }); $NC.setGridColumn(columns, { id: "ITEM_CD", field: "ITEM_CD", name: "์ƒํ’ˆ์ฝ”๋“œ", minWidth: 90 }); $NC.setGridColumn(columns, { id: "ITEM_NM", field: "ITEM_NM", name: "์ƒํ’ˆ๋ช…", minWidth: 150 }); $NC.setGridColumn(columns, { id: "ITEM_SPEC", field: "ITEM_SPEC", name: "๊ทœ๊ฒฉ", minWidth: 80 }); $NC.setGridColumn(columns, { id: "BRAND_NM", field: "BRAND_NM", name: "๋ธŒ๋žœ๋“œ๋ช…", minWidth: 80 }); $NC.setGridColumn(columns, { id: "ITEM_STATE_F", field: "ITEM_STATE_F", name: "์ƒํƒœ", minWidth: 80, cssClass: "align-center" }); $NC.setGridColumn(columns, { id: "ITEM_LOT", field: "ITEM_LOT", name: "LOT๋ฒˆํ˜ธ", minWidth: 80 }); $NC.setGridColumn(columns, { id: "QTY_IN_BOX", field: "QTY_IN_BOX", name: "์ž…์ˆ˜", minWidth: 70, cssClass: "align-right" }); $NC.setGridColumn(columns, { id: "ORDER_QTY", field: "ORDER_QTY", name: "์˜ˆ์ •์ˆ˜๋Ÿ‰", minWidth: 70, cssClass: "align-right" }); $NC.setGridColumn(columns, { id: "ENTRY_QTY", field: "ENTRY_QTY", name: "๋“ฑ๋ก์ˆ˜๋Ÿ‰", minWidth: 70, cssClass: "align-right" }); $NC.setGridColumn(columns, { id: "ENTRY_BOX", field: "ENTRY_BOX", name: "๋“ฑ๋กBOX", minWidth: 70, cssClass: "align-right" }); $NC.setGridColumn(columns, { id: "ENTRY_EA", field: "ENTRY_EA", name: "๋“ฑ๋กEA", minWidth: 70, cssClass: "align-right" }); $NC.setGridColumn(columns, { id: "ENTRY_WEIGHT", field: "ENTRY_WEIGHT", name: "๋“ฑ๋ก์ค‘๋Ÿ‰", minWidth: 70, cssClass: "align-right" }); if (policyLI420 == "2") { $NC.setGridColumn(columns, { id: "VALID_DATE", field: "VALID_DATE", name: "์œ ํ†ต๊ธฐํ•œ", minWidth: 100, cssClass: "align-center" }); $NC.setGridColumn(columns, { id: "BATCH_NO", field: "BATCH_NO", name: "์ œ์กฐ๋ฐฐ์น˜๋ฒˆํ˜ธ", minWidth: 100 }); } return $NC.setGridColumnDefaultFormatter(columns); } /** * ์˜ค๋ฅธ์ชฝ ์ƒ๋‹จ ๊ทธ๋ฆฌ๋“œ ์ดˆ๊ธฐํ™” */ function grdDetailInitialize() { var options = { frozenColumn: 2 }; // Grid Object, DataView ์ƒ์„ฑ ๋ฐ ์ดˆ๊ธฐํ™” $NC.setInitGridObject("#grdDetail", { columns: grdDetailOnGetColumns(), queryId: "LI05010E.RS_DETAIL", sortCol: "LINE_NO", gridOptions: options }); G_GRDDETAIL.view.onSelectedRowsChanged.subscribe(grdDetailOnAfterScroll); G_GRDDETAIL.height = 300; $("#grdDetail").height(G_GRDDETAIL.height); } function grdSubOnGetColumns() { var columns = [ ]; $NC.setGridColumn(columns, { id: "ITEM_CD", field: "ITEM_CD", name: "์ƒํ’ˆ์ฝ”๋“œ", minWidth: 120 }); $NC.setGridColumn(columns, { id: "ITEM_NM", field: "ITEM_NM", name: "์ƒํ’ˆ๋ช…", minWidth: 180 }); $NC.setGridColumn(columns, { id: "CONFIRM_QTY", field: "CONFIRM_QTY", name: "ํ™•์ •์ˆ˜๋Ÿ‰", minWidth: 70, cssClass: "align-right", editor: Slick.Editors.Number, editorOptions: { isKeyField: true } }); $NC.setGridColumn(columns, { id: "INBOUND_SEQ", field: "INBOUND_SEQ", name: "์ž…๊ณ SEQ", minWidth: 150, cssClass: "align-center" }); return $NC.setGridColumnDefaultFormatter(columns); } /** * ์˜ค๋ฅธ์ชฝ ํ•˜๋‹จ ๊ทธ๋ฆฌ๋“œ ์ดˆ๊ธฐํ™” */ function grdSubInitialize() { var options = { editable: true, autoEdit: true, frozenColumn: 1 }; // Grid Object, DataView ์ƒ์„ฑ ๋ฐ ์ดˆ๊ธฐํ™” $NC.setInitGridObject("#grdSub", { columns: grdSubOnGetColumns(), queryId: "LI05010E.RS_SUB1", sortCol: "LOCATION_ID", gridOptions: options }); G_GRDSUB.view.onSelectedRowsChanged.subscribe(grdSubOnAfterScroll); G_GRDSUB.view.onBeforeEditCell.subscribe(grdSubOnBeforeEditCell); G_GRDSUB.view.onCellChange.subscribe(grdSubOnCellChange); } /** * ์˜ค๋ฅธ์ชฝ ํ•˜๋‹จ๊ทธ๋ฆฌ๋“œ์˜ ์ž…๋ ฅ์ฒดํฌ ์ฒ˜๋ฆฌ */ function grdSubOnBeforePost(row) { var rowData = G_GRDSUB.data.getItem(row); if ($NC.isNull(rowData)) { return true; } /* // ์‚ญ์ œ ๋ฐ์ดํ„ฐ๋ฉด Return if (rowData.CRUD == "D") { return true; } // ์‹ ๊ทœ์ผ ๋•Œ ํ‚ค ๊ฐ’์ด ์—†์œผ๋ฉด ์‹ ๊ทœ ์ทจ์†Œ if (rowData.CRUD == "N") { } */ if (rowData.CRUD != "R") { if ($NC.isNull(rowData.CONFIRM_QTY) || Number(rowData.CONFIRM_QTY) == 0) { alert("ํ™•์ •์ˆ˜๋Ÿ‰์„ ์ •ํ™•ํžˆ ์ž…๋ ฅํ•˜์‹ญ์‹œ์˜ค."); $NC.setGridSelectRow(G_GRDSUB, { selectRow: row, activeCell: G_GRDSUB.view.getColumnIndex("CONFIRM_QTY"), editMode: true }); return false; } } return true; } /** * ์˜ค์ชฝ ๋ฅธํ•˜๋‹จ๊ทธ๋ฆฌ๋“œ ํŽธ์ง‘๋ถˆ๊ฐ€๋Šฅ * * @param e * @param args * @returns {Boolean} */ function grdSubOnBeforeEditCell(e, args) { return true; } /** * ์˜ค๋ฅธ์ชฝ ํ•˜๋‹จ๊ทธ๋ฆฌ๋“œ์˜ ์…€ ๊ฐ’ ๋ณ€๊ฒฝ์‹œ ์ฒ˜๋ฆฌ * * @param e * @param args */ function grdSubOnCellChange(e, args) { var rowData = args.item; if ($NC.isNull(rowData.CONFIRM_QTY)) rowData.CONFIRM_QTY = "0"; if (Number(rowData.CONFIRM_QTY) < 0) { alert("ํ™•์ •์ˆ˜๋Ÿ‰์—๋Š” 0๋ณด๋‹ค ์ž‘์€๊ฐ’์„ ์ž…๋ ฅํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."); rowData.CONFIRM_QTY = 0; $NC.setGridSelectRow(G_GRDSUB, { selectRow: G_GRDSUB.lastRow, activeCell: G_GRDSUB.view.getColumnIndex("CONFIRM_QTY"), editMode: true }); return; } if ($NC.isNull(rowData.CRUD) || rowData.CRUD === "R") { rowData.CRUD = "U"; } G_GRDSUB.data.updateItem(rowData.id, rowData); // ๋งˆ์ง€๋ง‰ ์„ ํƒ Row ์ˆ˜์ • ์ƒํƒœ๋กœ ๋ณ€๊ฒฝ G_GRDSUB.lastRowModified = true; G_GRDSUB.view.getCanvasNode().focus(); } /*---------------test-----------------*/ function grdSub1OnGetColumns() { var columns = [ ]; $NC.setGridColumn(columns, { id: "ITEM_CD", field: "ITEM_CD", name: "์ƒํ’ˆ์ฝ”๋“œ", minWidth: 120 }); $NC.setGridColumn(columns, { id: "ITEM_NM", field: "ITEM_NM", name: "์ƒํ’ˆ๋ช…", minWidth: 180 }); $NC.setGridColumn(columns, { id: "CONFIRM_QTY", field: "CONFIRM_QTY", name: "ํ™•์ •์ˆ˜๋Ÿ‰", minWidth: 70, cssClass: "align-right", editor: Slick.Editors.Number, editorOptions: { isKeyField: true } }); $NC.setGridColumn(columns, { id: "INBOUND_SEQ", field: "INBOUND_SEQ", name: "์ž…๊ณ SEQ", minWidth: 150, cssClass: "align-center" }); return $NC.setGridColumnDefaultFormatter(columns); } /** * ์˜ค๋ฅธ์ชฝ ํ•˜๋‹จ ๊ทธ๋ฆฌ๋“œ ์ดˆ๊ธฐํ™” */ function grdSub1Initialize() { var options = { editable: true, autoEdit: true, frozenColumn: 1 }; // Grid Object, DataView ์ƒ์„ฑ ๋ฐ ์ดˆ๊ธฐํ™” $NC.setInitGridObject("#grdSub1", { columns: grdSub1OnGetColumns(), queryId: "LI05010E.RS_SUB1", sortCol: "LOCATION_ID", gridOptions: options }); } /** * ์˜ค๋ฅธ์ชฝ ํ•˜๋‹จ๊ทธ๋ฆฌ๋“œ์˜ ์ž…๋ ฅ์ฒดํฌ ์ฒ˜๋ฆฌ */ function grdSub1OnBeforePost(row) { var rowData = G_GRDSUB1.data.getItem(row); if ($NC.isNull(rowData)) { return true; } /* // ์‚ญ์ œ ๋ฐ์ดํ„ฐ๋ฉด Return if (rowData.CRUD == "D") { return true; } // ์‹ ๊ทœ์ผ ๋•Œ ํ‚ค ๊ฐ’์ด ์—†์œผ๋ฉด ์‹ ๊ทœ ์ทจ์†Œ if (rowData.CRUD == "N") { } */ if (rowData.CRUD != "R") { if ($NC.isNull(rowData.CONFIRM_QTY) || Number(rowData.CONFIRM_QTY) == 0) { alert("ํ™•์ •์ˆ˜๋Ÿ‰์„ ์ •ํ™•ํžˆ ์ž…๋ ฅํ•˜์‹ญ์‹œ์˜ค."); $NC.setGridSelectRow(G_GRDSUB1, { selectRow: row, activeCell: G_GRDSUB1.view.getColumnIndex("CONFIRM_QTY"), editMode: true }); return false; } } return true; } /** * ์˜ค์ชฝ ๋ฅธํ•˜๋‹จ๊ทธ๋ฆฌ๋“œ ํŽธ์ง‘๋ถˆ๊ฐ€๋Šฅ * * @param e * @param args * @returns {Boolean} */ function grdSub1OnBeforeEditCell(e, args) { return true; } /** * ์˜ค๋ฅธ์ชฝ ํ•˜๋‹จ๊ทธ๋ฆฌ๋“œ์˜ ์…€ ๊ฐ’ ๋ณ€๊ฒฝ์‹œ ์ฒ˜๋ฆฌ * * @param e * @param args */ function grdSub1OnCellChange(e, args) { var rowData = args.item; if ($NC.isNull(rowData.CONFIRM_QTY)) rowData.CONFIRM_QTY = "0"; if (Number(rowData.CONFIRM_QTY) < 0) { alert("ํ™•์ •์ˆ˜๋Ÿ‰์—๋Š” 0๋ณด๋‹ค ์ž‘์€๊ฐ’์„ ์ž…๋ ฅํ•  ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค."); rowData.CONFIRM_QTY = 0; $NC.setGridSelectRow(G_GRDSUB, { selectRow: G_GRDSUB1.lastRow, activeCell: G_GRDSUB1.view.getColumnIndex("CONFIRM_QTY"), editMode: true }); return; } if ($NC.isNull(rowData.CRUD) || rowData.CRUD === "R") { rowData.CRUD = "U"; } G_GRDSUB1.data.updateItem(rowData.id, rowData); // ๋งˆ์ง€๋ง‰ ์„ ํƒ Row ์ˆ˜์ • ์ƒํƒœ๋กœ ๋ณ€๊ฒฝ G_GRDSUB1.lastRowModified = true; G_GRDSUB1.view.getCanvasNode().focus(); } /** * ๊ฒ€์ƒ‰์กฐ๊ฑด์˜ ์‚ฌ์—…๋ถ€ ๊ฒ€์ƒ‰ ํŒ์—… ํด๋ฆญ */ function showUserBuPopup() { $NP.showUserBuPopup({ P_USER_ID: $NC.G_USERINFO.USER_ID, P_BU_CD: "%" }, onUserBuPopup, function() { $NC.setFocus("#edtQBu_Cd", true); }); } /** * ์‚ฌ์—…๋ถ€ ๊ฒ€์ƒ‰ ๊ฒฐ๊ณผ * * @param seletedRowData */ function onUserBuPopup(resultInfo) { if (!$NC.isNull(resultInfo)) { $NC.setValue("#edtQBu_Cd", resultInfo.BU_CD); $NC.setValue("#edtQBu_Nm", resultInfo.BU_NM); } else { $NC.setValue("#edtQBu_Cd"); $NC.setValue("#edtQBu_Nm"); $NC.setFocus("#edtQBu_Cd", true); } $NC.setValue("#edtQBrand_Cd"); $NC.setValue("#edtQBrand_Nm"); onChangingCondition(); setPolicyValInfo(); } /** * ๊ฒ€์ƒ‰์กฐ๊ฑด์˜ ๋ธŒ๋žœ๋“œ ๊ฒ€์ƒ‰ ํŒ์—… ํด๋ฆญ */ function showBuBrandPopup() { var BU_CD = $NC.getValue("#edtQBu_Cd"); $NP.showBuBrandPopup({ P_BU_CD: BU_CD, P_BRAND_CD: "%" }, onBuBrandPopup, function() { $NC.setFocus("#edtQBrand_Cd", true); }); } /** * ๋ธŒ๋žœ๋“œ ๊ฒ€์ƒ‰ ๊ฒฐ๊ณผ * * @param seletedRowData */ function onBuBrandPopup(resultInfo) { if (!$NC.isNull(resultInfo)) { $NC.setValue("#edtQBrand_Cd", resultInfo.BRAND_CD); $NC.setValue("#edtQBrand_Nm", resultInfo.BRAND_NM); } else { $NC.setValue("#edtQBrand_Cd"); $NC.setValue("#edtQBrand_Nm"); $NC.setFocus("#edtQBrand_Cd", true); } onChangingCondition(); } /** * ๊ฒ€์ƒ‰์กฐ๊ฑด์˜ ๋ฐฐ์†ก์ฒ˜ ๊ฒ€์ƒ‰ ์ด๋ฏธ์ง€ ํด๋ฆญ */ function showVendorPopup() { var CUST_CD = $NC.getValue("#edtQCust_Cd"); $NP.showVendorPopup({ queryParams: { P_CUST_CD: CUST_CD, P_VENDOR_CD: "%", P_VIEW_DIV: "1" } }, onVendorPopup, function() { $NC.setFocus("#edtQVendor_Cd", true); }); } function onVendorPopup(resultInfo) { if (!$NC.isNull(resultInfo)) { $NC.setValue("#edtQVendor_Cd", resultInfo.VENDOR_CD); $NC.setValue("#edtQVendor_Nm", resultInfo.VENDOR_NM); } else { $NC.setValue("#edtQVendor_Cd"); $NC.setValue("#edtQVendor_Nm"); $NC.setFocus("#edtQVendor_Cd", true); } onChangingCondition(); } /** * ์™ผ์ชฝ๊ทธ๋ฆฌ๋“œ ํ–‰ ํด๋ฆญ์‹œ ์ฒ˜๋ฆฌ * * @param e * @param args */ function grdMasterOnAfterScroll(e, args) { var row = args.rows[0]; var rowData = G_GRDMASTER.data.getItem(row); if (G_GRDMASTER.lastRow != null) { if (row == G_GRDMASTER.lastRow) { e.stopImmediatePropagation(); return; } } // ์กฐํšŒ์‹œ ์ „์—ญ ๋ณ€์ˆ˜ ๊ฐ’ ์ดˆ๊ธฐํ™” $NC.setInitGridVar(G_GRDDETAIL); onGetDetail({ data: null }); G_GRDDETAIL.queryParams = $NC.getParams({ P_CENTER_CD: rowData.CENTER_CD, P_BU_CD: rowData.BU_CD, P_INBOUND_DATE: rowData.INBOUND_DATE, P_INBOUND_NO: rowData.INBOUND_NO }); // ๋ฐ์ดํ„ฐ ์กฐํšŒ $NC.serviceCall("/LI05010E/getDataSet.do", $NC.getGridParams(G_GRDDETAIL), onGetDetail); // ์ƒ๋‹จ ํ˜„์žฌ๋กœ์šฐ/์ด๊ฑด์ˆ˜ ์—…๋ฐ์ดํŠธ $NC.setGridDisplayRows("#grdMaster", row + 1); } /** * ์˜ค๋ฅธ์ชฝ ์ƒ๋‹จ ๊ทธ๋ฆฌ๋“œ ํ–‰ ํด๋ฆญ์‹œ ์ฒ˜๋ฆฌ * * @param e * @param args */ function grdDetailOnAfterScroll(e, args) { var row = args.rows[0]; if (G_GRDDETAIL.lastRow != null) { if (row == G_GRDDETAIL.lastRow) { e.stopImmediatePropagation(); return; } } // ์กฐํšŒ์‹œ ์ „์—ญ ๋ณ€์ˆ˜ ๊ฐ’ ์ดˆ๊ธฐํ™” $NC.setInitGridVar(G_GRDSUB); onGetSub({ data: null }); var rowData = G_GRDDETAIL.data.getItem(row); G_GRDSUB.queryParams = $NC.getParams({ P_CENTER_CD: rowData.CENTER_CD, P_BU_CD: rowData.BU_CD, P_INBOUND_DATE: rowData.INBOUND_DATE, P_INBOUND_NO: rowData.INBOUND_NO, P_LINE_NO: rowData.LINE_NO }); // ๋ฐ์ดํ„ฐ ์กฐํšŒ $NC.serviceCall("/LI05010E/getDataSet.do", $NC.getGridParams(G_GRDSUB), onGetSub); // ์ƒ๋‹จ ํ˜„์žฌ๋กœ์šฐ/์ด๊ฑด์ˆ˜ ์—…๋ฐ์ดํŠธ $NC.setGridDisplayRows("#grdDetail", row + 1); } /** * ์˜ค๋ฅธ์ชฝ ํ•˜๋‹จ๊ทธ๋ฆฌ๋“œ ํ–‰ ํด๋ฆญ์‹œ ํ•˜๋‹จ๊ทธ๋ฆฌ๋“œ ๊ฐ’ ์ทจ๋“ํ•ด์„œ ํ‘œ์‹œ ์ฒ˜๋ฆฌ * * @param e * @param args */ function grdSubOnAfterScroll(e, args) { var row = args.rows[0]; if (G_GRDSUB.lastRow != null) { if (row == G_GRDSUB.lastRow) { e.stopImmediatePropagation(); return; } } // ์ƒ๋‹จ ํ˜„์žฌ๋กœ์šฐ/์ด๊ฑด์ˆ˜ ์—…๋ฐ์ดํŠธ $NC.setGridDisplayRows("#grdSub", row + 1); } /** * ์กฐํšŒ๋ฒ„ํŠผ ํด๋ฆญํ›„ ์™ผ์ชฝ ๊ทธ๋ฆฌ๋“œ์— ๋ฐ์ดํ„ฐ ํ‘œ์‹œ์ฒ˜๋ฆฌ */ function onGetMaster(ajaxData) { $NC.setInitGridData(G_GRDMASTER, ajaxData); if (G_GRDMASTER.data.getLength() > 0) { if ($NC.isNull(G_GRDMASTER.lastKeyVal)) { $NC.setGridSelectRow(G_GRDMASTER, 0); } else { $NC.setGridSelectRow(G_GRDMASTER, { selectKey: "INBOUND_NO", selectVal: G_GRDMASTER.lastKeyVal }); } } else { $NC.setGridDisplayRows("#grdMaster", 0, 0); // ์ค‘๋ถ„๋ฅ˜ ์ „์—ญ ๋ณ€์ˆ˜ ๊ฐ’ ์ดˆ๊ธฐํ™” $NC.setInitGridVar(G_GRDDETAIL); onGetDetail({ data: null }); } // ๋ฒ„ํŠผ ํ™œ์„ฑํ™” ์ฒ˜๋ฆฌ $NC.G_VAR.buttons._inquiry = "1"; $NC.G_VAR.buttons._new = "0"; $NC.G_VAR.buttons._save = "1"; $NC.G_VAR.buttons._cancel = "1"; $NC.G_VAR.buttons._delete = "0"; $NC.G_VAR.buttons._print = "1"; $NC.setInitTopButtons($NC.G_VAR.buttons, $NC.G_VAR.printOptions); } /** * ์˜ค๋ฅธ์ชฝ ์ƒ๋‹จ ๊ทธ๋ฆฌ๋“œ์— ๋ฐ์ดํ„ฐ ํ‘œ์‹œ์ฒ˜๋ฆฌ */ function onGetDetail(ajaxData) { $NC.setInitGridData(G_GRDDETAIL, ajaxData); if (G_GRDDETAIL.data.getLength() > 0) { if ($NC.isNull(G_GRDDETAIL.lastKeyVal)) { $NC.setGridSelectRow(G_GRDDETAIL, 0); } else { $NC.setGridSelectRow(G_GRDDETAIL, { selectKey: "LINE_NO", selectVal: G_GRDDETAIL.lastKeyVal }); } } else { $NC.setGridDisplayRows("#grdDetail", 0, 0); // ์†Œ๋ถ„๋ฅ˜ ์ „์—ญ ๋ณ€์ˆ˜ ๊ฐ’ ์ดˆ๊ธฐํ™” $NC.setInitGridVar(G_GRDSUB); onGetSub({ data: null }); } G_GRDDETAIL.view.getCanvasNode().focus(); } /** * ์˜ค๋ฅธ์ชฝ ํ•˜๋‹จ ๊ทธ๋ฆฌ๋“œ์— ๋ฐ์ดํ„ฐ ํ‘œ์‹œ์ฒ˜๋ฆฌ */ function onGetSub(ajaxData) { $NC.setInitGridData(G_GRDSUB, ajaxData); if (G_GRDSUB.data.getLength() > 0) { if ($NC.isNull(G_GRDSUB.lastKeyVal)) { $NC.setGridSelectRow(G_GRDSUB, 0); } else { $NC.setGridSelectRow(G_GRDSUB, { selectKey: "INBOUND_SEQ", selectVal: G_GRDSUB.lastKeyVal }); } } else { $NC.setGridDisplayRows("#grdSub", 0, 0); } $NC.G_VAR.SEQ_NO = 0; } /** * ์ €์žฅ ์ฒ˜๋ฆฌ ์„ฑ๊ณต ํ–ˆ์„ ๊ฒฝ์šฐ ์ฒ˜๋ฆฌ */ function onSave(ajaxData) { var resultData = $NC.toArray(ajaxData); if (!$NC.isNull(resultData)) { if (resultData.RESULT_DATA !== "OK") { alert(resultData.RESULT_DATA); return; } } var rowData = G_GRDDETAIL.data.getItem(G_GRDDETAIL.lastRow); var lastKeyVal = $NC.getGridLastKeyVal(G_GRDSUB, { selectKey: "INBOUND_SEQ" }); // ์กฐํšŒ์‹œ ์ „์—ญ ๋ณ€์ˆ˜ ๊ฐ’ ์ดˆ๊ธฐํ™” $NC.setInitGridVar(G_GRDSUB); G_GRDSUB.queryParams = $NC.getParams({ P_CENTER_CD: rowData.CENTER_CD, P_BU_CD: rowData.BU_CD, P_INBOUND_DATE: rowData.INBOUND_DATE, P_INBOUND_NO: rowData.INBOUND_NO, P_LINE_NO: rowData.LINE_NO }); // ๋ฐ์ดํ„ฐ ์กฐํšŒ $NC.serviceCall("/LI05010E/getDataSet.do", $NC.getGridParams(G_GRDSUB), onGetSub); G_GRDSUB.lastKeyVal = lastKeyVal; } /** * ์ €์žฅ ์ฒ˜๋ฆฌ ์‹คํŒจ ํ–ˆ์„ ๊ฒฝ์šฐ ์ฒ˜๋ฆฌ */ function onSaveError(ajaxData) { $NC.onError(ajaxData); } /** * ๊ฒ€์ƒ‰ํ•ญ๋ชฉ ๊ฐ’ ๋ณ€๊ฒฝ์‹œ ํ™”๋ฉด ํด๋ฆฌ์–ด */ function onChangingCondition() { $NC.clearGridData(G_GRDMASTER); $NC.clearGridData(G_GRDDETAIL); $NC.clearGridData(G_GRDSUB); $NC.G_VAR.buttons._inquiry = "1"; $NC.G_VAR.buttons._new = "0"; $NC.G_VAR.buttons._save = "0"; $NC.G_VAR.buttons._cancel = "0"; $NC.G_VAR.buttons._delete = "0"; $NC.G_VAR.buttons._print = "1"; $NC.setInitTopButtons($NC.G_VAR.buttons, $NC.G_VAR.printOptions); } /** * ์ž๋™๋ถ„ํ•  ๋ฒ„ํŠผ ํด๋ฆญ ์ด๋ฒคํŠธ ์ฒ˜๋ฆฌ */ function autoSplit() { if (G_GRDMASTER.data.getLength() === 0 || G_GRDDETAIL.data.getLength() === 0 || G_GRDSUB.data.getLength() === 0) { alert("์ž๋™๋ถ„ํ•  ๋Œ€์ƒ ๋ฐ์ดํ„ฐ๊ฐ€ ์—†์Šต๋‹ˆ๋‹ค."); return; } var SPLIT_VAL = $NC.getValue("#edtQSplit_Val"); if ($NC.isNull(SPLIT_VAL) || Number(SPLIT_VAL) == 0) { alert("์ˆ˜๋Ÿ‰๋ฅผ ์ •ํ™•ํžˆ ์ž…๋ ฅํ•˜์‹ญ์‹œ์˜ค."); $NC.setFocus("#edtQSplit_Val"); return; } var result = confirm("์ž๋™๋ถ„ํ•  ํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ?"); if (!result) return; var rowData = G_GRDDETAIL.data.getItem(G_GRDDETAIL.lastRow); var SPLIT_FLAG = $(':radio[name="rgbQSplit_Div"]:checked').val(); $NC.serviceCall("/LI05010E/setSplitPallet.do", { P_QUERY_PARAMS: $NC.getParams({ P_CENTER_CD: rowData.CENTER_CD, P_BU_CD: rowData.BU_CD, P_INBOUND_DATE: rowData.INBOUND_DATE, P_INBOUND_NO: rowData.INBOUND_NO, P_LINE_NO: rowData.LINE_NO, P_SPLIT_FLAG: SPLIT_FLAG, P_SPLIT_VAL: SPLIT_VAL, P_USER_ID: $NC.G_USERINFO.USER_ID }) }, onSave, onSaveError); } /** * ์ •์ฑ…์ •๋ณด ์ทจ๋“ */ function setPolicyValInfo() { $NC.G_VAR.policyVal.LI420 = ""; // ๊ฐ’ ์˜ค๋ฅ˜ ์ฒดํฌ๋Š” ์•ˆํ•จ var CENTER_CD = $NC.getValue("#cboQCenter_Cd"); var BU_CD = $NC.getValue("#edtQBu_Cd"); for ( var POLICY_CD in $NC.G_VAR.policyVal) { // ๋ฐ์ดํ„ฐ ์กฐํšŒ $NC.serviceCall("/LI05010E/callSP.do", { P_QUERY_ID: "WF.GET_POLICY_VAL", P_QUERY_PARAMS: $NC.getParams({ P_CENTER_CD: CENTER_CD, P_BU_CD: BU_CD, P_POLICY_CD: POLICY_CD }) }, onGetPolicyVal); } } /** * ์ •์ฑ…์ •๋ณด ์ทจ๋“ํ›„ ์ฒ˜๋ฆฌ * * @param ajaxData */ function onGetPolicyVal(ajaxData) { var resultData = $NC.toArray(ajaxData); if (!$NC.isNull(resultData)) { if (resultData.O_MSG === "OK") { $NC.G_VAR.policyVal[resultData.P_POLICY_CD] = resultData.O_POLICY_VAL; if (resultData.P_POLICY_CD != "LI420") { return; } // ์žฌ๊ณ ๊ด€๋ฆฌ๊ธฐ์ค€์— ๋”ฐ๋ผ ์œ ํšจ์ผ์ž/๋ฐฐ์น˜๋ฒˆํ˜ธ๋ณ„ ํ‘œ์‹œ/๋น„ํ‘œ์‹œ var policyVal = resultData.O_POLICY_VAL; G_GRDDETAIL.view.setColumns(grdDetailOnGetColumns(policyVal)); } } }
var type_name=['ๆœ่ฃ…้ž‹ๅŒ…','ๆ‰‹ๆœบๆ•ฐ็ ','็พŽๅฆ†้ฅฐๅ“','็™พ่ดง้ฃŸๅ“','่ฟๅŠจๆˆทๅค–','ๅ…ถไป–']; var school_address=['็‡•ๅฑฑๆ กๅŒบ','่ˆœ่€•ๆ กๅŒบ','ๆ˜Žๆฐดๆ กๅŒบ','ๅœฃไบ•ๆ กๅŒบ','่Žฑ่Šœๆ กๅŒบ']; //็”ปๅ›พ function drawImg(){ getProCount(); getUserCount(); getForderCount(); getForderCountZ(); } //ๅ„็ฑปๅ•†ๅ“็ฑปๅˆซ็ปŸ่ฎก function getProCount(){ //alert(1); var count=[]; var arr=getProType(7); var type_val=[]; var url=baseurl+'product/getProCount'; //alert(url); $.get(url,function(data){ //console.log(data.length); for(var i=0;i<data.length;i++){ type_val.push(data[i]['ptype']); count.push(parseInt(data[i]['id_count'])); } if(arr.length!=type_val.length){ for(var j=0;j<arr.length;j++){ if(!contains(type_val,arr[j])){ count.splice(j,0,0); } } } //alert(count); var option = { title : { text: 'ๅ„็ง็ฑปๅž‹ๅ•†ๅ“ๆ‰€ๅ ๆฏ”ไพ‹', x:'center' }, tooltip : { trigger: 'item', formatter: "{a} <br/>{b} : {c} ({d}%)" }, legend: { orient: 'vertical', left: 'left', data: type_name }, series : [ { name: 'ๆ•ฐๆฎๅฑ•็คบ', type: 'pie', radius : '55%', center: ['50%', '60%'], data:[ {value:count[0], name:type_name[0]}, {value:count[1], name:type_name[1]}, {value:count[2], name:type_name[2]}, {value:count[3], name:type_name[3]}, {value:count[4], name:type_name[4]}, {value:count[5], name:type_name[5]} ], itemStyle: { emphasis: { shadowBlur: 10, shadowOffsetX: 0, shadowColor: 'rgba(0, 0, 0, 0.5)' } } } ] }; //$("#productCount").empty(); // ไธบechartsๅฏน่ฑกๅŠ ่ฝฝๆ•ฐๆฎ var myChart = echarts.init(document.getElementById('productCount')); myChart.setOption(option); var app={}; app.currentIndex=-1; setInterval(function () { var dataLen = option.series[0].data.length; // ๅ–ๆถˆไน‹ๅ‰้ซ˜ไบฎ็š„ๅ›พๅฝข myChart.dispatchAction({ type: 'downplay', seriesIndex: 0, dataIndex: app.currentIndex }); app.currentIndex = (app.currentIndex + 1) % dataLen; // ้ซ˜ไบฎๅฝ“ๅ‰ๅ›พๅฝข myChart.dispatchAction({ type: 'highlight', seriesIndex: 0, dataIndex: app.currentIndex }); // ๆ˜พ็คบ tooltip myChart.dispatchAction({ type: 'showTip', seriesIndex: 0, dataIndex: app.currentIndex }); }, 2000); }); } //ๅ„ๆ กๅŒบ็”จๆˆทๆ•ฐ้‡็ปŸ่ฎก function getUserCount(){ var url=baseurl+'user/getUserCount'; var address=[]; var arr=getProType(6); // alert(arr); var count=[]; $.get(url,function(data){ for(var i=0;i<data.length;i++){ //alert(data[i]['address']); address.push(data[i]['address']); count.push(data[i]['id_count']); } if(arr.length!=address.length){ for(var j=0;j<arr.length;j++){ if(!contains(address,arr[j])){ count.splice(j,0,0); } } } // alert(school_address); // alert(count); var option = { color: ['#3398DB'], title : { text: 'ๅ„ๆ กๅŒบ็”จๆˆทๆ•ฐ้‡็ปŸ่ฎก', x:'center' }, tooltip : { trigger: 'axis', axisPointer : { // ๅๆ ‡่ฝดๆŒ‡็คบๅ™จ๏ผŒๅๆ ‡่ฝด่งฆๅ‘ๆœ‰ๆ•ˆ type : 'shadow' // ้ป˜่ฎคไธบ็›ด็บฟ๏ผŒๅฏ้€‰ไธบ๏ผš'line' | 'shadow' } }, grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true }, xAxis : [ { type : 'category', data : school_address, axisTick: { alignWithLabel: true } } ], yAxis : [ { type : 'value' } ], series : [ { name:'็”จๆˆทๆ•ฐ้‡', type:'bar', barWidth: '60%', data:count } ] }; var myChart = echarts.init(document.getElementById('userCount')); myChart.setOption(option); }); } //ๅ„ๆ กๅŒบ่ฎขๅ•ๆ•ฐ้‡็ปŸ่ฎก function getForderCount(){ var url=baseurl+'forder/getForderCount'; var saddress=[]; var arr=getProType(6); var count=[]; $.get(url,function(data){ for(var i=0;i<data.length;i++){ saddress.push(data[i]['saddress']); count.push(data[i]['id_count']); } if(saddress.length!=arr.length){ for(var j=0;j<arr.length;j++){ if(!contains(saddress,arr[j])){ count.splice(j,0,0); } } } var option = { title : { text: 'ๅ„ๆ กๅŒบ่ฎขๅ•ๆ•ฐ้‡ๆฏ”ไพ‹', x:'center' }, tooltip: { trigger: 'item', formatter: "{a} <br/>{b}: {c} ({d}%)" }, legend: { orient: 'vertical', x: 'left', data:school_address }, series: [ { name:'็ปŸ่ฎกๅˆ†ๆž', type:'pie', radius: ['50%', '70%'], avoidLabelOverlap: false, label: { normal: { show: false, position: 'center' }, emphasis: { show: true, textStyle: { fontSize: '30', fontWeight: 'bold' } } }, labelLine: { normal: { show: false } }, data:[ {value:count[0], name:school_address[0]}, {value:count[1], name:school_address[1]}, {value:count[2], name:school_address[2]}, {value:count[3], name:school_address[3]}, {value:count[4], name:school_address[4]} ] } ] }; var myChart = echarts.init(document.getElementById('forderCountBySchoolAddress')); myChart.setOption(option); }); } /* * ๅ„ๆ กๅŒบ่ฎขๅ•ๆ•ฐ้‡ๆŠ˜็บฟๅ›พ */ function getForderCountZ(){ var url=baseurl+'forder/getForderCountZ'; var dateArr=[]; var count=[]; $.get(url,function(data){ for(var i=0;i<data.length;i++){ dateArr.push(data[i]['f_time']); count.push(data[i]['id_count']); } var option = { title: { text: '่ฎขๅ•ๆ•ฐ้‡้€ๆ—ฅ็ปŸ่ฎก' }, tooltip: { trigger: 'axis' }, legend: { data:'่ฎขๅ•ๆ•ฐ้‡' }, grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true }, toolbox: { feature: { saveAsImage: {} } }, xAxis: { type: 'category', boundaryGap: false, data: dateArr }, yAxis: { type: 'value' }, series: [ { name:'่ฎขๅ•ๆ•ฐ้‡', type:'line', data:count } ] }; var myChart = echarts.init(document.getElementById('forderCountByZheXian')); myChart.setOption(option); }); } //่Žทๅ–ๅ•†ๅ“็ฑปๅž‹ๆ•ฐ็ป„ function getProType(val){ var arr=[]; for(var i=1;i<val;i++){ arr.push(i); } return arr; } //ๆŸฅ่ฏขๆŸไธ€ๅ…ƒ็ด ๅœจๆ•ฐ็ป„ไธญๆ˜ฏๅฆๅญ˜ๅœจ function contains(arr, val) { for ( var i = 0; i < arr.length; i++) { if (arr[i] == val) return true; } return false; }
/** * Our Schema for Users */ var mongoose = require('mongoose'); var Schema = mongoose.Schema; // Define the User Schema var userSchema = new Schema({ firstname: { type: String, required: true }, lastname: { type: String, required: true }, ccs: { type: String, required: true, unique: true } }); // The primary user model var User = mongoose.model('User', userSchema); module.exports = User;
import React, { useState } from 'react' import axios from 'axios' const AddEmployee = () => { const [Hire, setHire] = useState({ firstName: '', lastName: '', email: '', jobTitle: '', city: '', state: '', zip: '' }) const submitNewEmployee = async e => { e.preventDefault() console.log(Hire) const resp = await axios.post( `https://sdg-staff-directory-app.herokuapp.com/api/realcompany/Employees`, Hire ) console.log('employee form', resp.data) } const updateForm = e => { setHire({ ...Hire, [e.target.id]: e.target.value }) } return ( <> <section className="contact-header"> <h5 className="form-header">New Employee Form</h5> </section> <section className="form"> <form action="" className="col s12" onSubmit={e => submitNewEmployee(e)} > {/* onSubmit={newEmployee} */} <div className="row"> <div className="input-field col s6"> <i className="material-icons prefix">account_circle</i> <input id="firstName" type="text" className="validate" // value={Hire.firstName} onChange={updateForm} /> <label htmlFor="first_name">First Name</label> </div> <div className="row"> <div className="input-field col s6"> <input id="lastName" type="text" className="validate" // value={Hire.lastName} onChange={updateForm} /> <label htmlFor="last_name">Last Name</label> </div> <div className="row email"> <div className="input-field col s6"> <i className="material-icons prefix">email</i> <input id="email" type="text" className="validate" // value={Hire.email} onChange={updateForm} /> <label htmlFor="email">Email</label> <span className="helper-text" data-error="wrong" data-success="right" ></span> </div> <div className="row"> <div className="input-field col s6"> <input id="jobTitle" type="text" className="validate" // value={Hire.job_Title} onChange={updateForm} /> <label htmlFor="jobTitle">Job Title</label> </div> </div> <div className="row city"> <div className="input-field col s2"> <i className="material-icons prefix">add_location</i> <input id="city" type="text" className="validate" // value={Hire.city} onChange={updateForm} /> <label htmlFor="city">City</label> </div> <div className="row"> <div className="input-field col s1"> <input id="state" type="text" className="validate" // value={Hire.state} onChange={updateForm} /> <label htmlFor="state">State</label> </div> <div className="row"> <div className="input-field col s1"> <input id="zip" type="text" className="validate" // value={Hire.zip} onChange={updateForm} /> <label htmlFor="zip">Zip</label> </div> </div> <button className="btn waves-effect waves-light" type="submit" name="action" > <i className="material-icons right">send</i> Done </button> </div> </div> </div> </div> </div> </form> </section> </> ) } export default AddEmployee
const mongoose =require("mongoose"); const mongoosePaginate = require('mongoose-paginate-v2'); Customer = new mongoose.Schema({ customer_name : { type:String, require:true }, customer_code:{ type:String, require:true }, customer_email:{ type:String, require:true }, customer_contact:{ type:String, require:true }, customer_gst:{ type:String, require:true }, customer_pan:{ type:String, require:true }, customer_state:{ type:Number, require:true }, customer_city:{ type:Number, require:true }, customer_country:{ type:Number, require:true }, customer_status:{ type:Number, default:1 }, added_date:{ type :Date, default: Date.now } }) Customer.plugin(mongoosePaginate); module.exports = mongoose.model('customer',Customer);
$(function () { // perloader js $(window).on('load', function () { $('.preloader').delay(2500).fadeOut(800); }) // back to top js let btn = $('#button'); $(window).scroll(function () { if ($(window).scrollTop() > 200) { btn.addClass('show'); } else { btn.removeClass('show'); } }); btn.on('click', function (e) { e.preventDefault(); $('html, body').animate({ scrollTop: 0 }, 1000); }); // sticky menu js $(window).scroll(function () { let scrolling = $(this).scrollTop(); if (scrolling > 0) { $('.nav').addClass('fixed'); } else { $('.nav').removeClass('fixed'); } }) //animation scroll js let html_body = $('html, body'); $('nav a').on('click', function () { if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) { var target = $(this.hash); target = target.length ? target : $('[name=' + this.hash.slice(1) + ']'); if (target.length) { html_body.animate({ scrollTop: target.offset().top - 80 }, 1000); return false; } } }); })
import request from '@/utils/request' const roles = { // ่Žทๅ–้ป˜่ฎค้…็ฝฎ่ทฏ็”ฑไฟกๆฏ getDefaultRoutes(data) { return request({ url: '/vueDefaultRouteGet', method: 'post', data }) }, // ่Žทๅ–ๆƒ้™็ป„ๅˆ—่กจ getRoutesGroup(data){ return request({ url: '/group/get', method: 'post', data }) }, // ่Žทๅ–ๆƒ้™็ป„ไฟกๆฏ getRoutesData(data){ return request({ url: '/vueRoleGet', method: 'post', data }) }, // ็งป้™คๆƒ้™็ป„ไฟกๆฏ delRoutesData(data){ return request({ url: '/vueRoleDel', method: 'post', data }) }, // ไฟฎๆ”นๆƒ้™็ป„ไฟกๆฏ editRoutesData(data){ return request({ url: '/vueRoleUpdate', method: 'post', data }) }, // ๆœบๆž„ไฟกๆฏ orgTreeGet(data){ return request({ url: '/orgTreeGet', method: 'post', data }) }, // ่ง’่‰ฒ getRoleList(data) { return request({ url: '/roleGetByPage', method: 'post', data }) }, } export default roles
// pages/report/2020/steps/consultant.js Page({data: {}})
// learn 55.ะ‘ะฐะนะณัƒัƒะปะฐะณั‡ ั„ัƒะฝะบั†ะธะนะณ ะฐัˆะธะณะปะฐะฝ ัƒะดะฐะผัˆะธะป ั…ัั€ัะณะถาฏาฏะปัั…. /*ะœะฐั‚ะตั€ --> ะะผัŒั‚ะฐะฝ --> ั…าฏะฝ */ /*ะ‘ะฐะนะณัƒัƒะปะฐะณั‡ ั„ัƒะฝะบั†ั‹ะฝ ะฝัั€ะธะนะณ ั‚ะพะผะพะพั€ ะฑะธั‡ะธะถ javascript delevoper-ัƒัƒะด ะฐะผะฐะฐั€ ั‚ะพั…ะธั€ัะพะฝ ะทะฐั€ั‡ะธะผ ะฑะฐะนะดะฐะณ. ะญะฝะณะธะนะฝ ั„ัƒะฝะบั†ัƒัƒะด ะถะธะถะธะณััั€ ะฑะธั‡ะธะณะดัะณ. ะ‘ะฐะนะณัƒัƒะปะฐะณั‡ ั„ัƒะฝะบั†ั‹ะณ ะทะฐะฐะฒะฐะป new ะณัะถ ะฑะธั‡ะธะณะดัะฝั. */ // ะ‘ะฐะนะณัƒัƒะปะฐะณั‡ ั„ัƒะฝะบั†: // function Materi(une) { // this.une = une; // this.haragdah = function () { // console.log(this.une + "าฏะฝัั‚ัะน ะผะฐั‚ะตั€ะธ ะฑะฐะนะฝะฐ. "); // }; // } // var m1 = new Materi(1000000); // m1.haragdah(); /* ัะฝั ั„ัƒะฝะบั† ะฝัŒ haragdah ะณัั… ั„ัƒะฝะบั†ั‹ะฝ copy ะดะพั‚ะพั€ ะฑาฏั… ะผะฐั‚ะตั€ะธ, ั…าฏะฝ, ะฐะผัŒั‚ะฐะฝ ั…ัƒัƒะปะปะฐะฐะด broser-ั‹ะฝ ัะฐะฝะฐั… ะพะนะด ะฑะฐะนั€ัˆัƒัƒะปะดะฐะณ ะฑะพะปะพั…ะพะพั€ ัƒะดะฐะฐะฝ ะฐะถะธะปะปะฐะฝะฐ.าฎาฏะฝััั ััั€ะณะธะนะปัั…ะธะนะฝ ั‚ัƒะปะด ั…ะฐั€ะฐะณะดะฐั… object-ะธะนะณ ะผะฐั‚ะตั€ะธะนะฝ prototype ะดะพั‚ะพั€ ั…ะธะนะณััะด ำฉะฝะณำฉ. ะ‘าฏั… ั„ัƒะฝะบั† prototype ะพะฑัŠะตะบั‚ะฐะน ะฑะฐะนะดะฐะณ.*/ // ะŸั€ะพะณั€ั€ะฐะผะผะธัั‚ัƒัƒะด ะตั€ ะฝัŒ ะณะฐะดะฝะฐะฐั ำฉะณั‡ ะฑะฐะนะณะฐะฐ าฏะฝั ะดะพั‚ะพั€ ั…ะฐะดะณะฐะปะฐะณะดะฐะถ ะฑะฐะนะณะฐะฐ าฏะฝะธะนะฝ ะฝัั€ะธะนะณ ะธะถะธะปั…ัะฝ ำฉะณั‡ะธั…ัำฉะฝ ะฑะฐะนะดะฐะณ. // function Materi(une) { // this.une = une; // } // Materi.prototype.haragdah = function () { // console.log(this.une + "าฏะฝัั‚ัะน ะผะฐั‚ะตั€ะธ ะฑะฐะนะฝะฐ. "); // } // var m1 = new Materi(1000000); // m1.haragdah(); // 1. ะฅะธะนั… ะฐะปั…ะฐะผ // ะ”ะพะพั€ั… ะถะธัˆัั ะฑะพะป: ะะผัŒั‚ะฐะฝะณะฐะฐั€ ะพั€ะถ ะธั€ััะฝ une-ะธะนะณ call-ะฐั€ ะดะฐะถัƒัƒะปะฐะฐะด ะดะฐั€ะฐะฐ ะฝัŒ ะฐะผัŒั‚ะฐะฝั‹ ะฑะฐะนะณัƒัƒะปะปะฐะณั‡ะฐะฐั€ ะพั€ะถ ะธั€ััะฝ // ungu call ั„ัƒะฝะบั†ะฐะฐั€ Materi ะดะฐะถัƒัƒะปั‡ะธั…ะฝะฐ. // ะœะฐั‚ะตั€ะธ ั„ัƒะฝะบั† าฏาฏัะณัะถ ำฉะณัำฉะฝ function Materi(une, ungu) { this.ungu = ungu; this.une = une; } // ะœะฐั‚ะตั€ะธ ะณะฐะดะฝะฐ haragdah ั„ัƒะฝะบั† าฏาฏัะณัะถ ำฉะณัำฉะฝ ะฅัั€ะฒัั ะดะพั‚ะพั€ ะฝัŒ haragdah ั„ัƒะฝะบั† าฏาฏัะณัะถ ำฉะณะฒำฉะป ัƒะดะฐะฐะฝ ะฑะพะปะฝะพ. Materi.prototype.haragdah = function () { console.log(this.une + " าฏะฝัั‚ัะน ะผะฐั‚ะตั€ะธ ะฑะฐะนะฝะฐ. "); }; //Amitan ั„ัƒะฝะบั† าฏาฏัะณัะถ ำฉะณัำฉะฝ function Amitan(nas, une, ungu) { Materi.call(this, une, ungu); this.nas = nas; } // ะœะฐั‚ะตั€ะธ-ะด Amitan ะพะฑัŠะตั‚ ัƒะดะฐะผัˆัƒัƒะปะถ ำฉะณั‡ ะฑะฐะนะฝะฐ. Amitan.prototype = Object.create(Materi.prototype); Amitan.prototype.hoolloh = function () { console.log( this.nas + " ะฝะฐัั‚ะฐะน " + this.une + " าฏะฝัั‚ัะน " + this.ungu + " ำฉะฝะณำฉั‚ัะน าฏะฝัั ั…ะพะพะปะพะปะปะพะพ " ); }; //ะฅาฏะฝ ั„ัƒะฝะบั† าฏาฏัะณัะถ ำฉะณัำฉะฝ function ะฅาฏะฝ(ะฝัั€, ะฝะฐั, าฏะฝั, ำฉะฝะณำฉ) { Amitan.call(this, ะฝะฐั, าฏะฝั, ำฉะฝะณำฉ); this.ะฝัั€ = ะฝัั€; } // Amitan-ะด ะฅาฏะฝ ะพะฑัŠะตั‚ ัƒะดะฐะผัˆัƒัƒะปะถ ำฉะณั‡ ะฑะฐะนะฝะฐ. ะฅาฏะฝ.prototype = Object.create(Amitan.prototype); ะฅาฏะฝ.prototype.setgeh = function (bodol) { console.log( this.ะฝัั€ + " ะฝัั€ั‚ัะน " + this.nas + " ะฝะฐัั‚ะฐะน " + this.une + " าฏะฝัั‚ัะน " + this.ungu + " ำฉะฝะณำฉั‚ัะน ั…าฏะฝ " + bodol + " ะณัะถ ะฑะพะดะปะพะพ " ); }; // unee -ะฝะด ัƒั‚ะณะฐ ำฉะณำฉำฉะด ั…ัะฒะปัะถ ะฑะฐะนะฝะฐ. var unee = new Amitan(20, 40000, "alag"); unee.haragdah(); unee.hoolloh(); // p1 -ะฝะด ัƒั‚ะณะฐ ำฉะณำฉำฉะด ั…ัะฒะปัะถ ะฑะฐะนะฝะฐ. var p1 = new ะฅาฏะฝ(" ะ‘ะพะปะดะพะพ ", 18, 150, " ัˆะฐั€ "); p1.haragdah(); p1.hoolloh(); p1.setgeh("Javascript ะปะฐะนั‚ะฐะน ัŽะผะฐะฐะฐ"); // 2. ะฅะธะนั… ะฐะปั…ะฐะผ Materi Amitan 2 ะฑะฐะนะณัƒัƒะปะฐะณั‡ ั„ัƒะฝะบั†ั‹ะณ ะณะฐั€ ะฐั€ะณะฐะฐั€ ะทะฐะปะณะฐะถ ะฑะฐะนะฝะฐ ะณัััะฝ าฏะณ. // Object.create -ะฝัŒ ัˆะธะฝััั€ ะพะฑัŠะตะบั‚ าฏาฏัะณัะถ ำฉะณะดำฉะณ. ะ“ัั…ะดัั ัะผะฐั€ ะฝัะณัะฝ ะพะฑัŠะตะบั‚ะพะพั ะทะฐะณะฒะฐั€ ะฑะพะปะณะพะถ ะฐั€ะณัƒะผะตะฝั‚ะฐะฐั€ ะฝัŒ ะดะฐะถัƒัƒะปัะฐะฝ ะพะฑัŠะตะบั‚ะพะพั // ะทะฐะณะฒะฐั€ ะฑะพะปะณะพะถ าฏาฏัะณัะดัะณ. ะ”ััั€ั… ะถะธัˆัั ะฝัŒ ะดััั€ ะทะฐะณัŒะฐั€ ะฝัŒ Materi ะฑะฐะนะฝะฐ. // ะ˜ะนะผ ะฑะฐะนะดะปะฐะฐั€ ะฑะฐะนะณัƒัƒะปะฐะณั‡ ั„ัƒะฝะบั† ะฐัˆะธะณะปะฐะถ ัƒะดะฐะผัˆะธ ั…ะธะนั…ะฝัั. ะ“ัั…ะดัั ัะฝั ะฑะพะป
//RAFCE shortcut to paste this const Header = () => { return ( <div className = 'container pb-5'> <h1 className = 'row-12 text-light text-center'>Image changer</h1> </div> ) } export default Header
describe('standard.h.willMount', () => { test.todo('Executa o evento willMount da instancia vinculada') test.todo('Executa o metodo associado ao evento willMount') })
// Functional component or stateless component without hooks import React from 'react' // function Greet() { // return <h1>Hello CVGA</h1> // } // export const Greet = () => <h1>Hello CVGA</h1> // using arrow functions // above is named export //below deault export if we change the name in app js it won't effect output // const Greet = () => <h1>Hello CVGA </h1> //using arrow functions const Greet = (props) =>{ console.log(props); return <h1>Hello CVGA, {props.name} a.k.a {props.codeName}</h1> } export default Greet
import axios from 'axios' // URL and endpoint constants const API_URL = 'https://geocode.xyz/' function getGeoLocation (options) { return new Promise(function (resolve, reject) { navigator.geolocation.getCurrentPosition(resolve, reject, options) }) } // VUE Store const state = { data: {}, ready: false } const getters = { location: state => { return state } } const mutations = { SET_LOCATION (state, location) { state.data = location state.ready = true }, CLEAR_LOCATION (state) { state.data = {} state.ready = false } } const actions = { getLocation: ({commit}) => { let options = { enableHighAccuracy: true } getGeoLocation(options) .then((position) => { axios({ method: 'get', url: API_URL + position.coords.latitude + ',' + position.coords.longitude + '?geoit=json' }) .then(function (response) { commit('SET_LOCATION', response.data) }) .catch(function (error) { console.log(error) }) }) .catch((err) => { console.error(err.message) }) } } export default { state, mutations, getters, actions }
import React from 'react'; import PlayerList from '../../../controller/components/lobby/PlayerList'; import TopBar from './../shared/TopBar'; import BottomBar from './../shared/BottomBar'; import styles from './lobby.less'; const Lobby = (props) => { const className = styles['lobby'] + (props.className ? ' ' + props.className : ''); let bottomLine1; if(props.players.length < props.numPlayersRequired) { const delta = props.numPlayersRequired - props.players.length; bottomLine1 = <p>Waiting on at least {delta} more player{delta != 1 ? 's' : ''} to join.</p>; } else { const playersReadyCount = props.players.filter(p => !p.ready).length; bottomLine1 = <p>Waiting on {playersReadyCount} player{playersReadyCount != 1 ? 's' : ''} to get ready.</p> } let bottomLine2; if(props.serverIP){ bottomLine2 = <p>Point your mobile browser at: {props.serverIP}/controller</p> } const localPlayerZx = ( <button onClick={props.zxButtonClicked}>z-x keys</button> ) const localPlayerArrow = ( <button onClick={props.arrowsButtonClicked}>arrow keys</button> ) return ( <div className= {className }> <TopBar height="5">Lobby { localPlayerArrow } { localPlayerZx } </TopBar> <PlayerList { ... props }/> <BottomBar height="15">{ bottomLine1 } { bottomLine2 }</BottomBar> </div> ); } export default Lobby;
import React, { useState, useEffect } from 'react'; const FetchUseEffect = () => { const [state, setState] = useState({ email: '', picture: '' }); useEffect(() => { fetch('https://randomuser.me/api/') .then(rs => rs.json()) .then(data => { const [user] = data.results; setState({ email: user.email, picture: user.picture.medium }); }); }, []); const { email, picture } = state; return ( <div> <img src={picture} alt="" /> <div>{email}</div> </div> ); }; export default FetchUseEffect;
window.onload = function(){ var marco = document.getElementById("marco"); marco.addEventListener("click", function(){ var url = "http://" + window.location.host + "/STOMPSpringMarcopolo/marcopolo"; // ๅˆ›ๅปบSockJS่ฟžๆŽฅ var sock = new SockJS(url); // ๅˆ›ๅปบSTOMPๅฎขๆˆท็ซฏ var stomp = Stomp.over(sock); var payload = JSON.stringify({"message": "Marco!"}); // ่ฟžๆŽฅSTOMP็ซฏ็‚น // ไฝฟ็”จๅ†…ๅญ˜ๆถˆๆฏไปฃ็†็š„ๆ—ถๅ€™๏ผŒๅ‰ไธคไธชๅ€ผๅฏไปฅ้šไพฟๅ†™ stomp.connect("guest", "guest", function(){ // ๅ‘้€ๆถˆๆฏ stomp.send("/app/marco", {}, payload); }); }); };
๏ปฟ// ็™ปๅฝ•็ฎก็† export default { type: 'แž”แŸ‚แž„แž…แŸ‚แž€แž”แŸ’แžšแž—แŸแž‘แž แžถแž„', addType: 'แž”แž„แŸ’แž€แžพแžแž”แŸ’แžšแž—แŸแž‘', checkSelectorHolder: 'แžŸแžผแž˜แž‡แŸ’แžšแžพแžŸแžšแžพแžŸแžŸแŸ’แžแžถแž“แž—แžถแž–แž™แž›แŸ‹แž–แŸ’แžšแž˜', displaySelectorHolder: 'แžŸแžผแž˜แž‡แŸ’แžšแžพแžŸแžšแžพแžŸแžŸแŸ’แžแžถแž“แž—แžถแž–แžกแžพแž„แž’แŸ’แž“แžพ', checkStatus: 'แžŸแŸ’แžแžถแž“แž—แžถแž–แž“แŸƒแž€แžถแžšแžแŸ’แžšแžฝแžแž–แžทแž“แžทแžแŸ’แž™', checkStatusA: 'แžšแž„แž…แžถแŸ†แž€แžถแžšแžแŸ’แžšแžฝแžแž–แžทแž“แžทแžแŸ’แž™', checkStatusB: 'แž”แžถแž“แž–แžทแž“แžทแžแŸ’แž™แžšแžฝแž…', checkStatusC: 'แž˜แžทแž“แžขแž“แžปแž‰แŸ’แž‰แžถแž', putaway: 'แžกแžพแž„ แž…แžปแŸ‡แž’แŸ’แž“แžพ', putawayA: 'แžŸแŸ’แžแžทแžแž€แŸ’แž“แžปแž„แž€แžถแžšแž›แž€แŸ‹', putawayB: 'แž“แŸ…แž€แŸ’แž“แžปแž„แžƒแŸ’แž›แžถแŸ†แž„', putawayC: 'แžกแžพแž„แž’แŸ’แž“แžพ', putawayD: 'แž”แž‰แŸ’แž‡แžถแž€แŸ‹แž–แŸแž›แžœแŸแž›แžถแž“แŸƒแž€แžถแžšแžกแžพแž„แž’แŸ’แž“แžพ', putawayE: 'แž…แžปแŸ‡แž–แžธแž’แŸ’แž“แžพ (แžšแž€แŸ’แžŸแžถแž‘แžปแž€แž‘แŸ…แž€แŸ’แž“แžปแž„แžŸแŸ’แžแžปแž€)', putawayF: 'แžŸแŸ’แžแžถแž“แžธแž™แŸแž€แŸ‚แž†แŸ’แž“แŸƒ', putawayG: 'แžŸแŸ’แžแžถแž“แž—แžถแž–แž›แž€แŸ‹', putawayTip: 'แž…แžปแž…แžŠแžพแž˜แŸ’แž”แžธแž€แŸ‚แž”แŸ’แžšแŸ‚แžŠแŸ„แž™แž•แŸ’แž‘แžถแž›แŸ‹แž“แžผแžœแžŸแŸ’แžแžถแž“แž—แžถแž–แž“แŸƒแž€แžถแžšแžกแžพแž„แžšแžบแž…แžปแŸ‡แž’แŸ’แž“แžพ', price: 'แžแž˜แŸ’แž›แŸƒ', inventory: 'แžŸแŸ’แžแžปแž€', saled: 'แž”แžถแž“แž›แž€แŸ‹', piEdit: 'แžŸแŸ’แžแžปแž€ แž“แžทแž„ แžแž˜แŸ’แž›แŸƒ', typeEdit: 'แž€แžถแžšแž€แŸ‚แž”แŸ’แžšแŸ‚แž”แŸ’แžšแž—แŸแž‘แž‘แŸ†แž“แžทแž‰', parentType: 'แž”แŸ’แžšแž—แŸแž‘แž”แŸ‚แž„แž…แŸ‚แž€แž€แŸ†แž–แžผแž›', name: 'แžˆแŸ’แž“แŸ„แŸ‡', intro: 'แž€แžถแžšแžŽแŸ‚แž“แžถแŸ†', goodsType: 'แž”แŸ’แžšแž—แŸแž‘แž‘แŸ†แž“แžทแž‰', goodsType1: 'แž‘แŸ†แž“แžทแž‰แž’แž˜แŸ’แž˜แžแžถ', goodsType2: 'แž€แžถแžšแž‘แžทแž‰แž‡แžถแž€แŸ’แžšแžปแž˜', goodsType3: 'แž‘แŸ†แž“แžทแž‰แž–แžทแž“แŸ’แž‘แžป', cobuy: 'แž€แžถแžšแž‘แžทแž‰แž‡แžถแž€แŸ’แžšแžปแž˜', cobuyPrice: 'แžแž˜แŸ’แž›แŸƒแž“แŸƒแž€แžถแžšแž‘แžทแž‰แž‡แžถแž€แŸ’แžšแžปแž˜', cobuyuser: 'แž…แŸ†แž“แžฝแž“แž˜แž“แžปแžŸแŸ’แžŸแž“แŸƒแž€แžถแžšแž‘แžทแž‰แž‡แžถแž€แŸ’แžšแžปแž˜', cobuysec: 'แž–แŸแž›แžœแŸแž›แžถแž˜แžถแž“แž”แŸ’แžšแžŸแžทแž‘แŸ’แž’แž—แžถแž–', conbuytip1: 'แžขแŸ’แž“แž€แž”แžถแž“แž…แžถแž”แŸ‹แž•แŸ’แžแžพแž˜แž€แžถแžšแž‘แžทแž‰แž‡แžถแž€แŸ’แžšแžปแž˜ แžŸแžผแž˜แž€แŸ†แžŽแžแŸ‹แž…แŸ†แž“แžฝแž“แž˜แž“แžปแžŸแŸ’แžŸแž“แŸƒแž€แžถแžšแž‘แžทแž‰แž‡แžถแž€แŸ’แžšแžปแž˜แžขแŸ„แž™แž”แžถแž“แžแŸ’แžšแžนแž˜แžแŸ’แžšแžผแžœ (แž˜แžทแž“แžแžทแž…แž‡แžถแž„ 2แžขแŸ’แž“แž€)', conbuytip2: 'แžŸแžผแž˜แž€แŸ†แžŽแžแŸ‹แžšแž™แŸˆแž–แŸแž›แžŸแžปแž–แž›แž—แžถแž–แž“แŸƒแž€แžถแžšแž”แž‰แŸ’แž‡แžถแž‘แžทแž‰แž‡แžถแž€แŸ’แžšแžปแž˜ (แž”แŸ’แžšแžŸแžทแž“แž”แžพแž€แžถแžšแž‘แžทแž‰แž‡แžถแž€แŸ’แžšแžปแž˜แž˜แžทแž“แž‡แŸ„แž‚แž‡แŸแž™แž€แŸ’แž“แžปแž„แžšแž™แŸˆแž–แŸแž›แž“แŸแŸ‡แž‘แŸ แž€แžถแžšแž”แž‰แŸ’แž‡แžถแž‘แžทแž‰แž“แžนแž„แžแŸ’แžšแžผแžœแž›แžปแž”แž…แŸ„แž›แžŠแŸ„แž™แžŸแŸ’แžœแŸแž™แž”แŸ’แžšแžœแžแŸ’แžแžท)', hour: 'แž˜แŸ‰แŸ„แž„', note: 'แžŸแž˜แŸ’แž‚แžถแž›แŸ‹', edit: 'แž€แžถแžšแž€แŸ‚แž”แŸ’แžšแŸ‚แž‘แŸ†แž“แžทแž‰', next: 'แž‡แŸ†แž แžถแž“แž”แž“แŸ’แž‘แžถแž”แŸ‹', pre: 'แž‡แŸ†แž แžถแž“แž˜แžปแž“', placeholder: 'แžŸแžผแž˜แž‡แŸ’แžšแžพแžŸแžšแžพแžŸแž‘แŸ†แž“แžทแž‰', selectorTitle: 'แž€แžถแžšแž‡แŸ’แžšแžพแžŸแžšแžพแžŸแž‘แŸ†แž“แžทแž‰', step1: 'แž‡แŸ†แž แžถแž“แž‘แžธ แŸก', step1Tip: 'แž€แŸ†แžŽแžแŸ‹แž”แŸ’แžšแž—แŸแž‘แž‘แŸ†แž“แžทแž‰ แž“แžทแž„ แž‚แžปแžŽแž›แž€แŸ’แžแžŽแŸˆ', step2: 'แž‡แŸ†แž แžถแž“แž‘แžธ แŸข', step2Tip: 'แž‡แŸ’แžšแžพแžŸแžšแžพแžŸแž”แŸ’แžšแž—แŸแž‘ แž“แžทแž„ แžแžถแžšแžถแž„แž”แž„แŸ’แž แžถแž‰แž‘แŸ†แž“แžทแž‰', step3: 'แž‡แŸ†แž แžถแž“แž‘แžธ แŸฃ', step3Tip: 'แž€แŸ†แžŽแžแŸ‹แž€แžถแžšแžŽแŸ‚แž“แžถแŸ†แž›แŸ†แžขแžทแžแžขแŸ†แž–แžธแž‘แŸ†แž“แžทแž‰', step4: 'แž‡แŸ†แž แžถแž“แž‘แžธ แŸค', step4Tip: 'แž€แžถแžšแž€แŸ†แžŽแžแŸ‹แž”แž‰แŸ’แž‡แžถแž€แŸ‹แž–แžธแž•แž›แžทแž•แž›, แžŸแŸ’แžแžปแž€ แž แžพแž™ แž“แžนแž„ แžแž˜แŸ’แž›แŸƒ', sysType: 'แž”แŸ’แžšแž—แŸแž‘แž‘แŸ†แž“แžทแž‰', sysTypeProp: 'แž”แŸ’แžšแž—แŸแž‘แž‚แžปแžŽแž›แž€แŸ’แžแžŽแŸ‡', goodsPic: 'แžšแžผแž”แž—แžถแž–แž‘แŸ†แž“แžทแž‰', picdes: 'แž€แžถแžšแžŽแŸ‚แž“แžถแŸ†แž–แžธแžšแžผแž”แž—แžถแž–', sp: 'แž—แžถแž–แž‡แžถแž€แŸ‹แž›แžถแž€แŸ‹ แž“แžทแž„ แž‚แžปแžŽแž›แž€แŸ’แžแžŽแŸˆ', spec: 'แžˆแŸ’แž˜แŸ„แŸ‡แž‡แžถแž€แŸ‹แž›แžถแž€แŸ‹', spec1: '+แž—แžถแž–แž‡แžถแž€แŸ‹แž›แžถแž€แŸ‹', prop: 'แžˆแŸ’แž˜แŸ„แŸ‡แž‚แžปแžŽแž›แž€แŸ’แžแžŽแŸˆ', prop1: 'แž‚แžปแžŽแž›แž€แŸ’แžแžŽแŸˆ', shareTip: 'แžขแŸ’แž“แž€แž˜แžทแž“แž˜แžถแž“แžŸแžทแž‘แŸ’แž’แžทแž…แŸ‚แž€แž…แžถแž™แž‘แŸ แžŸแžผแž˜แž–แžทแž‚แŸ’แžšแŸ„แŸ‡แž‡แžถแž˜แžฝแž™แžขแŸ’แž“แž€แž‚แŸ’แžšแž”แŸ‹แž‚แŸ’แžšแž„แž”แŸ’แžšแžŸแžทแž“แž”แžพแžขแŸ’แž“แž€แžแŸ’แžšแžผแžœแž€แžถแžšแž…แŸ‚แž€แž…แžถแž™', commissionPercent: 'แžขแžแŸ’แžšแžถแž€แŸ†แžšแŸƒแž‡แžพแž„แžŸแžถแžš ๏ผˆโ€ฐ๏ผ‰', commissionMoney: 'แž€แž˜แŸ’แžšแŸƒแž‡แžพแž„แžŸแžถแžš ๏ผˆ$๏ผ‰', shareSet: 'แž€แŸ†แžŽแžแŸ‹แž‘แŸ†แž“แžทแž‰แž…แŸ‚แž€แž…แžถแž™', shareGoods: 'แž…แŸ‚แž€แž…แžถแž™แž‘แŸ†แž“แžทแž‰', shareAll: 'แž‘แŸ†แž“แžทแž‰แž‘แžถแŸ†แž„แžขแžŸแŸ‹แžแŸ’แžšแžผแžœแž”แžถแž“แžŠแžถแž€แŸ‹แž›แžพแž’แŸ’แž“แžพ', goodsSelect: 'แž€แžถแžšแž‡แŸ’แžšแžพแžŸแžšแžพแžŸแž‘แŸ†แž“แžทแž‰', systip1: 'แžŸแžผแž˜แž‡แŸ’แžšแžพแžŸแžšแžพแžŸแž”แŸ’แžšแž—แŸแž‘แž‘แŸ†แž“แžทแž‰', dpTypeTip1: 'แžŸแžผแž˜แž€แŸ†แžŽแžแŸ‹แž”แŸ’แžšแž—แŸแž‘แž แžถแž„แž‡แžถแž˜แžปแž“แžŸแžทแž“', dpTypeTip2: 'แžŸแžผแž˜แž‡แŸ’แžšแžพแžŸแžšแžพแžŸแž”แŸ’แžšแž—แŸแž‘แž‘แŸ†แž“แžทแž‰แž€แŸ’แž“แžปแž„แž แžถแž„แžขแŸ„แž™แžแŸ’แžšแžผแžœแž‘แŸ†แž“แžทแž‰แžŠแŸ‚แž›แž…แž„แŸ‹แž›แž€แŸ‹', nameTip: 'แžŸแžผแž˜แž€แŸ†แžŽแžแŸ‹แžˆแŸ’แž˜แŸ„แŸ‡แž‘แŸ†แž“แžทแž‰', imgTip: 'แžŸแžผแž˜แžขแžถแž”แŸ‹แžกแžผแžแž“แžผแžœแžšแžผแž”แž—แžถแž–แžŽแŸ‚แž“แžถแŸ†แž‘แŸ†แž“แžทแž‰', ipTip: 'แžŸแžผแž˜แž€แŸ†แžŽแžแŸ‹แž€แžถแžšแž”แž‰แŸ’แž‡แžถแž€แŸ‹แž‘แŸ†แž“แžทแž‰ แž“แžทแž„ แžแž˜แŸ’แž›แŸƒแž‘แŸ†แž“แžทแž‰แž™แŸ‰แžถแž„แž แŸ„แž…แžŽแžถแžŸแŸ‹แž˜แžฝแž™', postageRuleTip: 'แžŸแžผแž˜แž‡แŸ’แžšแžพแžŸแžšแžพแžŸแž…แŸ’แž”แžถแž”แŸ‹แž“แŸƒแž€แžถแžšแžŠแžนแž€แž‡แž‰แŸ’แž‡แžผแž“', addressIdTip: 'แžŸแžผแž˜แž‡แŸ’แžšแžพแžŸแžšแžพแžŸแž‘แžธแž€แž“แŸ’แž›แŸ‚แž„แžŠแžนแž€แž‡แž‰แŸ’แž‡แžผแž“แž‘แŸ†แž“แžทแž‰', needExp: 'แž–แžทแž“แŸ’แž‘แžปแžŠแŸ‚แž›แžแŸ’แžšแžผแžœแž€แžถแžš', exp: 'แž–แžทแž“แŸ’แž‘แžป', whole: 'แž‘แžถแŸ†แž„แžขแžŸแŸ‹', goodsInfo1: 'แž–แŸแžแŸŒแž˜แžถแž“แž˜แžผแž›แžŠแŸ’แž‹แžถแž“', goodsInfo2: 'แž–แžแŸแž˜แžถแž“แžขแŸ†แž–แžธแžšแž€แžถแžšแž›แž€แŸ‹', goodsInfo3: 'แž–แžทแž–แžŽแŸŒแž“แžถแžšแžผแž”แž—แžถแž–', goodsInfo4: 'แž–แžแŸแž˜แžถแž“แž€แžถแžšแžŠแžนแž€แž‡แž‰แŸ’แž‡แžผแž“', goodsInfo5: 'แžŸแŸแžœแžถแž€แž˜แŸ’แž˜แž€แŸ’แžšแŸ„แž™แž›แž€แŸ‹แžšแžฝแž…', riderPost: 'แž€แžถแžšแžšแžŠแžนแž€แž‡แž‰แŸ’แž‡แžผแž“แž€แŸ’แž“แžปแž„แž€แŸ’แžšแžปแž„แžแŸ‚แž˜แžฝแž™', riderPostSupport: 'แž‚แžถแŸ†แž‘แŸ’แžš', posageRule: 'แž…แŸ’แž”แžถแž”แŸ‹แž“แŸƒแž€แžถแžšแžŠแžนแž€แž‡แž‰แŸ’แž‡แžผแž“', postAddr: 'แž‘แžธแž€แž“แŸ’แž›แŸ‚แž„แž“แŸƒแž€แžถแžšแžŠแžนแž€แž‡แž‰แŸ’แž‡แžผแž“', saveGoods: 'แžšแž€แŸ’แžŸแžถแž‘แžปแž€แž–แŸแžแŸŒแž˜แžถแž“แž‘แŸ†แž“แžทแž‰', saveTip1: 'แž–แŸแžแŸŒแž˜แžถแž“แž‘แŸ†แž“แžทแž‰แžแŸ’แžšแžผแžœแž”แžถแž“แžšแž€แŸ’แžŸแžถแž‘แžปแž€แžŠแŸ„แž™แž‡แŸ„แž‚แž‡แŸแž™แŸ” แžแžพแžขแŸ’แž“แž€แž…แž„แŸ‹แž”แž“แŸ’แžแž”แž“แŸ’แžแŸ‚แž˜แžœแžถแž‘แŸ?', saveTip2: 'แž–แŸแžแŸŒแž˜แžถแž“แž‘แŸ†แž“แžทแž‰แžแŸ’แžšแžผแžœแž”แžถแž“แžšแž€แŸ’แžŸแžถแž‘แžปแž€แžŠแŸ„แž™แž‡แŸ„แž‚แž‡แŸแž™!', saveTip3: 'แžแžพแžขแŸ’แž“แž€แž…แž„แŸ‹แž”แž“แŸ’แžแž”แž“แŸ’แžแŸ‚แž˜แž‘แŸ?', xgLabel: 'แž€แžถแžšแž‘แžทแž‰แž‘แŸ†แž“แžทแž‰แž˜แžถแž“แž€แŸ†แžŽแžแŸ‹', xgLabel1: 'แž‘แžทแž‰แž‚แŸ’แž˜แžถแž“แžŠแŸ‚แž“แž€แŸ†แžŽแžแŸ‹', xgLabel2: 'แž‘แžทแž‰แž˜แžถแž“แž€แŸ†แžŽแžแŸ‹', delTip: 'แžแžพแžขแŸ’แž“แž€แž”แŸ’แžšแžถแž€แžŠแžแžถแž›แžปแž”แž‘แŸ†แž“แžทแž‰แž”แž…แŸ’แž…แžปแž”แŸ’แž”แž“แŸ’แž“แžฌ?', restore: 'แžŸแŸ’แžŠแžถแžšแž˜แž€แžœแžทแž‰', commodityPreview: 'แž–แžทแž“แžทแžแŸ’แž™แž˜แžพแž›แž‘แŸ†แž“แžทแž‰', goodsLang: 'แž€แŸ†แžŽแžแŸ‹แž—แžถแžŸแžถแž“แŸƒแž–แŸแžแŸŒแž˜แžถแž“แž‘แŸ†แž“แžทแž‰', goodsLangSet: 'แž”แŸ’แžšแž—แŸแž‘แž—แžถแžŸแžถ', goodsLangSetTip: 'แž…แžปแž…แžŠแžพแž˜แŸ’แž”แžธแž€แŸ†แžŽแžแŸ‹', goodsLangSetTip1: 'แžŸแžผแž˜แž€แŸ†แžŽแžแŸ‹แž”แŸ†แž–แŸแž‰แž–แžแŸแž˜แžถแž“แžแžถแž˜แž›แŸ†แž“แžถแŸ†แžŠแžพแž˜แž˜แžปแž“แžŸแžทแž“', baseSetTip: 'แžŸแžผแž˜แž€แŸ†แžŽแžแŸ‹แž”แŸ†แž–แŸแž‰แž‘แžทแž“แŸ’แž“แž“แŸแž™แž˜แžผแž›แžŠแŸ’แž’แžถแž“แžแžถแž„แž€แŸ’แžšแŸ„แž˜แž˜แžปแž“แžŸแžทแž“', addressSetTip: 'แž€แŸ†แžŽแžแŸ‹แžขแžถแžŸแŸแž™แžŠแŸ’แž‹แžถแž“', postageSet: 'แž€แŸ†แžŽแžแŸ‹แž…แŸ’แž”แžถแž”แŸ‹แž“แŸƒแž€แžถแžšแžŠแžนแž€แž‡แž‰แŸ’แž‡แžผแž“', dpTypeSet: 'แž€แŸ†แžŽแžแŸ‹แž”แŸ’แžšแž—แŸแž‘แž แžถแž„', weight: 'แž‘แž˜แŸ’แž„แž“แŸ‹', imgae: 'แžšแžผแž”แž—แžถแž–แž‘แŸ†แž“แžทแž‰', shangJia: 'แžŠแžถแž€แŸ‹แž›แžพแž’แŸ’แž“แžพ', refuse: 'แž”แžŠแžทแžŸแŸแž’', approvalSuccess: 'แžขแž“แžปแž‰แŸ’แž‰แžถแžแžŠแŸ„แž™แž‡แŸ„แž‚แž‡แŸแž™', notListed: 'แž˜แžทแž“แž”แžถแž“แžŠแžถแž€แŸ‹แž›แžพแž’แŸ’แž“แžพ', hasBeenAddedTo: 'แž”แžถแž“แžŠแžถแž€แŸ‹แž‘แŸ…แž›แžพแž’แŸ’แž“แžพ', removed: 'แž”แžถแž“แž™แž€แž…แŸแž‰แž–แžธแž’แŸ’แž“แžพ', backGoodsList: 'แžแŸ’แžšแžกแž”แŸ‹แž‘แŸ…แž”แž‰แŸ’แž‡แžธแž‘แŸ†แž“แžทแž‰แžœแžทแž‰', successTip: 'แžšแŸ†แž›แžนแž€แž‡แŸ„แž‚แž‡แŸแž™', lookGoodsInfo: 'แž˜แžพแž›แž–แŸแžแŸŒแž˜แžถแž“แž›แž˜แŸ’แžขแžทแžแž‘แŸ†แž“แžทแž‰', noSaveGoodsTip: 'แžขแŸ’แž“แž€แž˜แžถแž“แž‘แžทแž“แŸ’แž“แž“แŸแž™แž‘แŸ†แž“แžทแž‰แž˜แžทแž“แž‘แžถแž“แŸ‹แž”แžถแž“แžšแž€แŸ’แžŸแžถแž‘แžปแž€ แž”แŸ’แžšแžถแž€แžŠแžแžถแžแžพแžแŸ’แžšแžผแžœแžŸแŸ’แžแžถแžšแž‘แžทแž“แŸ’แž“แž“แŸแž™', lijihuifusuju: 'แžŸแŸ’แžแžถแžšแž‘แžทแž“แŸ’แž“แž“แŸแž™แž—แŸ’แž›แžถแž˜แŸ—', cancelhuifusuju: 'แž”แŸ„แŸ‡แž”แž„แŸ‹แž€แžถแžšแžŸแŸ’แžแžถแžšแž‘แžทแž“แŸ’แž“แž“แŸแž™', distributionLowProfits: 'แžœแžถแž‚แžบแž‡แžถแž‘แŸ†แž“แžทแž‰แžŠแŸ‚แž›แž˜แžถแž“แž€แž˜แŸ’แžšแžทแžแž…แŸ†แžŽแžผแž›แžแžทแž…แžšแžบ', yes: 'แžแŸ’แžšแžผแžœแž แžพแž™', not: 'แžขแžแŸ‹แž‘แŸ', lowMarginGoods: 'แž‘แŸ†แž“แžทแž‰แž˜แžถแž“แž€แž˜แŸ’แžšแžทแžแž…แŸ†แžŽแžผแž›แžแžทแž…', noLowMarginGoods: 'แž˜แžทแž“แž˜แŸ‚แž“แž‘แŸ†แž“แžทแž‰แžŠแŸ‚แž›แž˜แžถแž“แž€แž˜แŸ’แžšแžทแžแž…แŸ†แžŽแžผแž›แžแžทแž…', introGoods: 'แž›แž€แŸ’แžแžŽแŸˆแž–แžทแžŸแŸแžŸ', introDetail: 'แž€แžถแžšแž–แžทแž–แžŽแŸŒแž“แžถแž‡แžถแžขแž€แŸ’แžŸแžš', goodslist: 'แž”แž‰แŸ’แž‡แžธโ€‹แž‘แŸ†แž“แžทแž‰', wkcgm: 'แž‘แžทแž‰แžŠแŸ„แž™แž‚แŸ’แž˜แžถแž“แž—แžถแž‚แž แŸŠแžปแž“' }
/* eslint-disable max-len */ /* eslint-disable no-irregular-whitespace */ /* eslint-disable react/no-string-refs */ /** * ้™ๆ€ไบŒ็ปด็  */ import React, { Component, PureComponent } from 'react'; import { StyleSheet, View, Text, Dimensions, TouchableOpacity, ImageBackground, } from 'react-native'; import CameraRoll from '@react-native-community/cameraroll'; import { connect } from 'rn-dva'; import QRCode from 'react-native-qrcode-svg'; import ViewShot from 'react-native-view-shot'; import CommonStyles from '../../common/Styles'; import Header from '../../components/Header'; import ImageView from '../../components/ImageView'; import DashLine from '../../components/DashLine'; import ModalDemo from '../../components/Model'; import * as scanConfig from '../../config/scanConfig'; import config from '../../config/config'; import {RequestWritePermission} from '../../config/permission.js'; const { width, height } = Dimensions.get('window'); function getwidth(val) { return (width * val) / 375; } class ReceiptStaticQrCodeScreen extends PureComponent { constructor(props) { super(props); this.state = { }; } takeToImage=() => { this.refs.location.capture().then(async (uri) => { console.log(uri); let granted = await RequestWritePermission(); if(!granted) return; CameraRoll.saveToCameraRoll(uri) .then((result) => { Toast.show('ๅทฒไฟๅญ˜ๅˆฐๆ‰‹ๆœบ็›ธๅ†Œ'); console.log(`ไฟๅญ˜ๆˆๅŠŸ๏ผๅœฐๅ€ๅฆ‚ไธ‹๏ผš\n${result}`); }) .catch((error) => { if(error=='Error: ็”จๆˆทๆ‹’็ป่ฎฟ้—ฎ'){ CustomAlert.onShow( "alert", "่‹ฅ่ฆ็ปง็ปญไฟๅญ˜ๅ›พ็‰‡๏ผŒ่ฏทๅˆฐๆ‰‹ๆœบ่ฎพ็ฝฎไธญๅฟƒๆ‰“ๅผ€็›ธๅ†Œๆƒ้™", "ๆ‚จๅทฒๆ‹’็ป็›ธๅ†Œ่ฎฟ้—ฎๆƒ้™" ); }else{ alert(`ไฟๅญ˜ๅคฑ่ดฅ๏ผ\n${error}`);ย  ย  } }); }).catch( error => alert(error), ); } renderTakeImage=(qrUri) => { const { navigation, userShop } = this.props; const params = navigation.state.params || {}; const shopIcon = params.logo || userShop.logo || ''; console.log(qrUri); return ( <ImageBackground resizeMode="stretch" style={styles.contentSty} source={require('../../images/qrcode/background.png')} > <View style={styles.storeImg}> <ImageView source={shopIcon ? { uri: shopIcon } : require('../../images/qrcode/store.png')} resizeMode="cover" sourceWidth={83} sourceHeight={83} /> </View> <Text style={styles.storeName}>{params.title || userShop.name}</Text> <View style={styles.codeimg}> <QRCode value={qrUri} size={222} /> </View> </ImageBackground> ); } render() { const { navigation, user, userShop } = this.props; const params = navigation.state.params || {}; let qrParams = {}; const shopIcon = params.logo || userShop.logo || ''; params.title ? qrParams = {// ๅบ—้“บ่ฏฆๆƒ… storeId: params.storeId || userShop.id, userId: user.id, lat: params.lat, lng: params.lng, securityCode: user.securityCode, } : qrParams = {// ้™ๆ€ไบŒ็ปด็  userId: user.id, merchantId: user.merchantId, storeId: userShop.id, }; const takeImageUri =`${config.baseUrl_share_h5}codeShop?shopId=${params.storeId || userShop.id}&merchantId=${user.merchantId}&logo=${shopIcon}&name=${encodeURIComponent(`${params.title}`)}&securityCode=${user.securityCode}&condensationCode=1`; // const otherUri=scanConfig.qrCodeValue(params.title ?'store_detail':'store_receipt', qrParams) const otherUri = params.title ? takeImageUri : scanConfig.qrCodeValue('store_receipt', qrParams); return ( <View style={styles.container}> <Header title={params.title ? 'ๅบ—้“บไบŒ็ปด็ ' : '้™ๆ€ไบŒ็ปด็ '} navigation={navigation} goBack rightView={ params.title && ( <TouchableOpacity style={styles.headerItem} onPress={this.takeToImage} > <Text style={{ fontSize: 17, color: '#fff' }}>ไฟๅญ˜</Text> </TouchableOpacity> ) } /> { this.renderTakeImage(otherUri) } <ViewShot ref="location" style={{ position: 'absolute', top: -height }} options={{ format: 'png', quality: 1 }}> {this.renderTakeImage(takeImageUri)} </ViewShot> </View> ); } } const styles = StyleSheet.create({ container: { ...CommonStyles.containerWithoutPadding, alignItems: 'center', backgroundColor: '#4688ED', }, headerItem: { width: 50, }, contentSty: { width: 314, height: 415, marginTop: 57, alignItems: 'center', }, storeImg: { // ...CommonStyles.shadowStyle, justifyContent: 'center', alignItems: 'center', width: 83, height: 83, marginTop: -83 / 2 + 21, borderWidth: 1, borderColor: '#F1F1F1', borderRadius: 83 / 2, backgroundColor: '#fff', overflow: 'hidden', }, storeName: { fontSize: 16, color: '#000', fontWeight: '500', marginTop: 10, letterSpacing: 0.1, }, codeimg: { justifyContent: 'center', alignItems: 'center', flex: 1, marginTop: getwidth(15), }, }); export default connect( state => ({ user: state.user.user || {}, userShop: state.user.userShop || {}, }), )(ReceiptStaticQrCodeScreen);
global.ROUTER.web.Request = {};
/** * ไฝœ่€…๏ผšluanjie ๆ—ถ้—ด๏ผš2021-7 ๆ่ฟฐ๏ผš็™ปๅฝ•้กต้ข */ (function() { "use strict"; initLiserners(); console.log(sha1.hex('123')); /** * ็›‘ๅฌ้กต้ขๆ‰€ๆœ‰็‚นๅ‡ปไบ‹ไปถ */ function initLiserners() { $(".sendbox").on("click", function() { var username=$('#username').val(); var password=$('#password').val(); console.log(sha1.hex(password)) var registdata={ username:username, password:sha1.hex(password) } console.log(registdata) // regist(registdata); login(registdata); }) } //ๆณจๅ†ŒๆŽฅๅฃ็š„่ฐƒ็”จ function regist(data) { var url = 'http://127.0.0.1:3300/rest/regist'; //console.log('่ฏทๆฑ‚ๅœฐๅ€' + url); $.ajax(url, { data:data, type:'post', dataType: "json", timeout: "15000", //่ถ…ๆ—ถๆ—ถ้—ด่ฎพ็ฝฎไธบ3็ง’๏ผ› headers:{ authcode:'123456' }, success: function(response) { console.log(JSON.stringify(response)); }, error: function(error) { console.log("่ฏฆๆƒ…error"); console.log(JSON.stringify(error)); } }); } //็™ปๅฝ•ๆŽฅๅฃ็š„่ฐƒ็”จ function login(data) { var url = 'http://127.0.0.1:3300/rest/login'; //console.log('่ฏทๆฑ‚ๅœฐๅ€' + url); $.ajax(url, { data:data, type:'post', dataType: "json", timeout: "15000", //่ถ…ๆ—ถๆ—ถ้—ด่ฎพ็ฝฎไธบ3็ง’๏ผ› headers:{ authcode:'123456' }, success: function(response) { console.log(JSON.stringify(response)); }, error: function(error) { console.log("่ฏฆๆƒ…error"); console.log(JSON.stringify(error)); } }); } })();
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import CityOptionItem from './CityOptionItem'; class ProvinceSelect extends Component { constructor(){ super(); this.state={}; this.handleChange=this.handleChange.bind(this); } handleChange(event){ if(this.props.dataChange){ this.props.dataChange(this.refs.area_option.value); } } render(){ let element; if(this.props.areaList){ element = this.props.areaList.map((area,index)=>{ return (<CityOptionItem key={index} area={area} />); }); } return ( <select onChange={this.handleChange} ref="area_option" className="area_select"> {element} </select> ); } } ProvinceSelect.propTypes={ areaList:PropTypes.array, dataChange:PropTypes.func } export default ProvinceSelect;
function Cities (props) { if(props.City==null){ return null; } else{ return <option value={props.City}>{props.City}</option> }} export default Cities
import React from "react"; import Button from "./ButtonLibrary/Button"; function CustomButtonLibrary() { return ( <div> <Button type="primary">Click Me</Button> <Button type="disabled">Click Me</Button> </div> ); } export default CustomButtonLibrary;
/******************** ใŠๅ•ใ„ๅˆใ‚ใ› ********************/ $(document).ready(function() { // $('#sendBtn').click(function() { // $('#vals').submit(); // }); }); $(function() { $('#vals').submit(function(){ var result = ajaxSendMail(); result.done(function(response) { console.debug(response); showSent(response); // jAlert('ใŠๅ•ใ„ๅˆใ‚ใ›ๅ†…ๅฎนใŒ้€ไฟกใ•ใ‚Œใพใ—ใŸ' ,'ใŠๅ•ใ„ๅˆใ‚ใ›' , // function(r) { // location.href = 'index.html'; // } // ); }); result.fail(function(result, textStatus, errorThrown) { console.log("error for ajaxSendMail for inquiry:" + result.status + ' ' + textStatus); }); result.always(function() { }); return false; }); }); /********** ใƒกใƒผใƒซ้€ไฟก **********/ function ajaxSendMail() { var retAddr = $('#retAddr').val(); var sentence = $('#sentence').val(); var destAddr = $('#destAddr').val(); var branchNo = $('#branchID').val(); //console.debug(dataStr); var jqXHR; jqXHR = $.ajax({ type : "post" , url : "../cgi/ajax/sendInqMail.php" , data : { retAddr : retAddr , sentence : sentence , destAddr : destAddr , branchNo : branchNo } , cache : false }); return jqXHR; } /********** ๅ†…ๅฎน้€ไฟก **********/ function send() { window.history.back(-1); } /********** ๆˆปใ‚‹ **********/ function ret() { window.history.back(-1); } function showSent(retVal) { var height = $("#vals").height(); var retAddr = $('#retAddr').val(); var str; str = 'ใŠๅ•ใ„ๅˆใ‚ใ›ใฎ้€ไฟกใŒๅฎŒไบ†ใ—ใพใ—ใŸใ€‚<br>' + 'ๆ•ฐๆ—ฅไธญใซ' + retAddr + 'ใซๅ›ž็ญ”ใ—ใพใ™ใฎใงใ—ใฐใ‚‰ใใŠๅพ…ใกใใ ใ•ใ„ใ€‚<br>'; // '้•ทๆœŸ้–“ๅ›ž็ญ”ใŒใชใ„ใจใใฏใ€‡ใ€‡ใซใ”้€ฃ็ตกใใ ใ•ใ„ใ€‚'; $("#vals").html(str); height-=10; $("#vals").css('height' ,height + 'px'); }
function F(a, b, c, d, e) { return a + b * c / d + e; } var a = "one"; var b = 1; var c = a + b; var arr = [b, 2 + b, 3]; c = 2 + " equals "+ c + '?'; if (b === 1 - 1 - 1) { a = "-1"; } else { a = "-2"; } for (/*!int */ var i = 0; i < arr.length; ++i) { arr[i] = arr[i] * 2; } var j = 1, n = 10; while (j < n) { b += j; j += 2; }
function uniteUnique(arr) { var args = Array.prototype.slice.call(arguments); var flattened = args.reduce(function(a, b) { return a.concat(b); }); var unique = flattened.filter(function(item, index, inputArray) { return inputArray.indexOf(item) === index; }); return unique; } uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]);
//1.2.1 // var message = 'hi'; // // { // var message = 'bye'; // } // // console.log(message); // let message = 'hi'; // // { // let message = 'bye'; // } // // console.log(message); //1.2.2 // var fs = []; // // for (var i = 0; i < 10; i++) { // fs.push(function() { // console.log(i); // }) // } // // fs.forEach(function(f) { // f(); // }) // var fs = []; // // for (let i = 0; i < 10; i++) { // fs.push(function() { // console.log(i); // }) // } // // fs.forEach(function(f) { // f(); // }); //1.2.3 // function varFunc() { // var previous = 0; // var current = 1; // var i; // var temp; // // for (i = 0; i < n; i += 1) { // temp = previous; // previous = current; // current = temp + current; // } // } function letFunc(n) { let previous = 0; let current = 1; for (let i = 0; i < n; i += 1) { let temp = previous; previous = current; current = temp + current; console.log(current); } } console.log(letFunc(10));
const mongoose = require("mongoose"); const { Schema } = mongoose; const ContactSchema = new Schema({ name: { type: String, required: [true, "Please provide a name."], }, email: { type: String, required: [true, "Please provide a email."], match: [ /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/, "Please provide a valid email", ], }, subject: { type: String, required: [true, "Please provide a subject."], }, content: { type: String, required: [true, "Please provide a content."], }, createdAt: { type: Date, default: Date.now(), }, }); module.exports = mongoose.model("Contact",ContactSchema);
/** * @param {number} n - a positive integer * @return {number} */ var hammingWeight = function(n) { var count = 0; for (var i= 0; i<=31; i++) { if((n & (1 << i)) !== 0) count++; } return count; }; console.log(hammingWeight(4)); //1 console.log(hammingWeight(11)); //3 console.log(hammingWeight(128)); //1
/* * ๆœฌ้…็ฝฎๆ–‡ไปถๅฃฐๆ˜Žไบ†ๆ•ดไธชๅบ”็”จ็š„ๆ•ฐๆฎๅบ“่ฟžๆŽฅ้ƒจๅˆ†ใ€‚ */ var ioc = { /* * ๆ•ฐๆฎๅบ“่ฟžๆŽฅๆฑ  */ dataSource : { type : "com.mchange.v2.c3p0.ComboPooledDataSource", fields : { driverClass : "com.mysql.jdbc.Driver", jdbcUrl : "jdbc:mysql://172.16.106.24:3399/hansight", user : "hansight", password : "hansight" } }, /* * ่ฟ™ไธช้…็ฝฎๅพˆๅฅฝ็†่งฃ๏ผŒ args ่กจ็คบ่ฟ™ไธชๅฏน่ฑกๆž„้€ ๅ‡ฝๆ•ฐ็š„ๅ‚ๆ•ฐใ€‚ๆ˜พ็„ถ๏ผŒไธ‹้ข็š„ๆณจๅ…ฅๆ–นๅผๅฐ†่ฐƒ็”จ new NutDao(dataSource) */ dao : { type : "org.nutz.dao.impl.NutDao", args : [ { refer : "dataSource" } ] } };
import React, { Component } from 'react' import { View, Text, StyleSheet, TouchableOpacity, Dimensions } from 'react-native' import { chooseColor } from './helperFunctions' import ReactNativeComponentTree from 'react-native'; import GameOver from './GameOver' var lineButtonWidth; var fontSize; export default class Gameboard extends Component { constructor(props) { super(props) } componentDidMount() { this.getLineButtonDimensions() } getLineButtonDimensions() { var {height, width} = Dimensions.get('window'); lineButtonWidth = (width - 70) / Math.sqrt(this.props.numberOfTrains) fontSize = height * .05 } render() { if (this.props.lives > 0) { return( <View style={styles.gameboardWrapper}> <View style={styles.dataWrapper}> <View style={styles.metaDataWrapper}> <Text style={styles.metaData}>lives: {this.props.lives}</Text> <Text style={styles.metaData}>score: {this.props.counter}</Text> </View> <View style={styles.currentStationWrapper}> <Text style={StyleSheet.flatten([styles.currentStation, {fontSize: fontSize}])}> {this.props.currentStation} ({this.props.currentLine}) </Text> </View> </View> <View style={styles.lineButtonWrapper}> {this.props.linesInPlay.map(line => { return( <TouchableOpacity id={line} key={line} onPress={() => this.props.checkMatch(line)} style={StyleSheet.flatten([ styles.lineButton, chooseColor(line, lineButtonWidth), {width: lineButtonWidth, height: lineButtonWidth, borderRadius: lineButtonWidth/2, margin: (this.props.numberOfTrains > 9 ? 5 : 10) } ])} > <Text style={StyleSheet.flatten([styles.lineButtonText, chooseColor(line, lineButtonWidth)])}>{line}</Text> </TouchableOpacity> ) })} </View> </View> ) } else if (this.props.lives === 0) { return( <GameOver counter={this.props.counter} wrongGuesses={this.props.wrongGuesses} rightAnswersOne={this.props.rightAnswersOne} rightAnswersTwo={this.props.rightAnswersTwo} rightAnswersThree={this.props.rightAnswersThree} playAgain={this.props.playAgain} lineButtonWidth={lineButtonWidth} /> ) } } } const styles = StyleSheet.create({ gameboardWrapper: { display: "flex", flex: 1, width: "100%", height: "auto", alignItems: "center", backgroundColor: "#161A1C", }, dataWrapper: { display: "flex", alignItems: "center", height: "32%", width: "100%", }, metaDataWrapper: { display: "flex", position: "relative", flexDirection: "row", justifyContent: "space-between", width: "100%", borderTopColor: "white", borderTopWidth: 1, borderBottomColor: "white", borderBottomWidth: 1, }, metaData: { fontSize: 16, paddingLeft: 20, paddingRight: 20, paddingTop: 10, paddingBottom: 10, color: "white", }, currentStationWrapper: { width: "80%", flex: 2, display: "flex", justifyContent: "center", alignItems: "center", alignContent: "center", }, currentStation: { width: "100%", textAlign: "center", color: "#FFF", fontWeight: "800", textDecorationLine: "underline", }, lineButtonWrapper: { display: "flex", flex: 2, position: "relative", flexDirection: "row", justifyContent: "center", alignContent: "center", flexWrap: "wrap", width: "100%", borderTopColor: "white", borderTopWidth: 1, }, lineButton: { display: "flex", alignItems: "center", justifyContent: "center", overflow: 'hidden', backgroundColor: "blue", }, lineButtonText: { fontSize: 35, fontWeight: "600", }, });
/** * ๅปบ็ญ‘็ฑปๅž‹็š„ๅ‰็ซฏๆŽงๅˆถJS * ไฝœ่€…๏ผšๅ•ๆท‘ๅ…ฐ * */ $(function(){ var typeNo=null; var name=null; //่ฎพ็ฝฎ็ณป็ปŸ้กต้ขๆ ‡้ข˜ $("span#mainpagetille").html("ๅปบ็ญ‘็ฑปๅž‹็ฎก็†"); //ๆ˜พ็คบๅปบ็ญ‘็ฑปๅž‹ๅˆ—่กจ $("table#BuildingTypeGrid").jqGrid({ url: host+'buildType/list/all/page', datatype: "json", colModel: [ { label: '็ฑปๅž‹็ผ–ๅท', name: 'no', width: 50}, { label: '็ฑปๅž‹ๅ็งฐ', name: 'name', width: 50} ], caption:"ๅปบ็ญ‘็ฑปๅž‹ๅˆ—่กจ", viewrecords: true, autowidth: true, height:300, rowNum: 10, rowList:[5,6,7,8,9,10], jsonReader : { root: "list", page: "page", total: "pageCount", records: "count", repeatitems: true, id: "no" }, pager: "#BuildingTypeGridPager",//jqGridๅˆ†้กตๆ ทๅผ multiselect:false, onSelectRow:function(ptno){ typeNo=ptno; } }); function reloadBuildingTypeList() { $("table#BuildingTypeGrid").jqGrid().trigger("reloadGrid"); } //===========================ๅขžๅŠ ๅปบ็ญ‘็ฑปๅž‹ๅค„็†================================= //็‚นๅ‡ปๅปบ็ญ‘็ฑปๅž‹ๅขžๅŠ ้“พๆŽฅๅค„็†๏ผŒๅตŒๅ…ฅadd.html $("a#BuildingTypeAddLink").off().on("click",function(){ $("div#BuildingTypeDialogArea").load("buildingType/add.html",function(){ //้ชŒ่ฏๆไบคๆ•ฐๆฎ $("form#BuildingTypeDialogArea").validate({ rules: { no: { required: true }, name: { required: true } }, message:{ no: { required: "็ฑปๅž‹็ผ–ๅทไธบ็ฉบ" }, name: { required: "็ฑปๅž‹ๅ็งฐ็ฉบ" } } }); //ๅขžๅŠ ๅปบ็ญ‘็ฑปๅž‹็š„ๅผน็ช— $("div#BuildingTypeDialogArea").dialog({ title:"ๅขžๅŠ ๅปบ็ญ‘็ฑปๅž‹", width:400 }); //ๆ‹ฆๆˆชๅขžๅŠ ๆไบค่กจๅ• $("form#BuildingTypeAddForm").ajaxForm(function(result){ if(result.status=="OK"){ reloadBuildingTypeList(); //ๆ›ดๆ–ฐๅปบ็ญ‘็ฑปๅž‹ๅˆ—่กจ } //alert(result.message); //BootstrapDialog.alert(result.message); BootstrapDialog.show({ title: 'ๅปบ็ญ‘็ฑปๅž‹ๆ“ไฝœไฟกๆฏ', message:result.message, buttons: [{ label: '็กฎๅฎš', action: function(dialog) { dialog.close(); } }] }); $("div#BuildingTypeDialogArea").dialog( "close" ); $("div#BuildingTypeDialogArea").dialog( "destroy" ); $("div#BuildingTypeDialogArea").html(""); }); //็‚นๅ‡ปๅ–ๆถˆๆŒ‰้’ฎๅค„็† $("input[value='ๅ–ๆถˆ']").on("click",function(){ $("div#BuildingTypeDialogArea").dialog( "close" ); $("div#BuildingTypeDialogArea").dialog( "destroy" ); $("div#BuildingTypeDialogArea").html(""); }); }); }); //===========================ไฟฎๆ”นๅปบ็ญ‘็ฑปๅž‹ๅค„็†================================= $("a#BuildingTypeModifyLink").off().on("click",function(){ if(typeNo==null){ BootstrapDialog.show({ title: 'ๅปบ็ญ‘็ฑปๅž‹ๆ“ไฝœไฟกๆฏ', message:"่ฏท้€‰ๆ‹ฉ่ฆไฟฎๆ”น็š„ๅปบ็ญ‘็ฑปๅž‹", buttons: [{ label: '็กฎๅฎš', action: function(dialog) { dialog.close(); } }] }); } else { $("div#BuildingTypeDialogArea").load("buildingType/modify.html",function(){ //ๅ–ๅพ—้€‰ๆ‹ฉ็š„ๅปบ็ญ‘็ฑปๅž‹ $.getJSON(host+"buildType/get",{no:typeNo},function(data){ //alert(typeNo); if(data){ $("input[name='no']").val(typeNo); $("input[name='name']").val(data.name); } }); $("div#BuildingTypeDialogArea" ).dialog({ title:"ๅปบ็ญ‘็ฑปๅž‹ไฟฎๆ”น", width:600 }); //ๆ‹ฆๆˆช่กจๅ•ๆไบค $("form#BuildingTypeModifyForm").ajaxForm(function(result){ if(result.status=="OK"){ reloadBuildingTypeList(); //ๆ›ดๆ–ฐๅปบ็ญ‘็ฑปๅž‹ๅˆ—่กจ } //alert(result.message); //BootstrapDialog.alert(result.message); BootstrapDialog.show({ title: 'ๅปบ็ญ‘็ฑปๅž‹ๆ“ไฝœไฟกๆฏ', message:result.message, buttons: [{ label: '็กฎๅฎš', action: function(dialog) { dialog.close(); } }] }); $("div#BuildingTypeDialogArea").dialog( "close" ); $("div#BuildingTypeDialogArea").dialog( "destroy" ); $("div#BuildingTypeDialogArea").html(""); }); //็‚นๅ‡ปๅ–ๆถˆๆŒ‰้’ฎๅค„็† $("input[value='ๅ–ๆถˆ']").on("click",function(){ $( "div#BuildingTypeDialogArea").dialog( "close" ); $( "div#BuildingTypeDialogArea").dialog( "destroy" ); $("div#BuildingTypeDialogArea").html(""); }); }); } }); //===========================ๅˆ ้™คๅปบ็ญ‘็ฑปๅž‹ๅค„็†================================= $("a#BuildingTypeDeleteLink").off().on("click",function(){ if(typeNo==null){ BootstrapDialog.show({ title: 'ๅปบ็ญ‘็ฑปๅž‹ๆ“ไฝœไฟกๆฏ', message:"่ฏท้€‰ๆ‹ฉ่ฆๅˆ ้™ค็š„ๅปบ็ญ‘็ฑปๅž‹", buttons: [{ label: '็กฎๅฎš', action: function(dialog) { dialog.close(); } }] }); } else { BootstrapDialog.confirm('็กฎ่ฎคๅˆ ้™คๆญคๅปบ็ญ‘็ฑปๅž‹ไนˆ?', function(result){ if(result) { $.post(host+"buildType/delete",{no:typeNo},function(result){ if(result.status=="OK"){ reloadBuildingTypeList(); //ๆ›ดๆ–ฐๅปบ็ญ‘็ฑปๅž‹ๅˆ—่กจ } BootstrapDialog.show({ title: 'ๅปบ็ญ‘็ฑปๅž‹ๆ“ไฝœไฟกๆฏ', message:result.message, buttons: [{ label: '็กฎๅฎš', action: function(dialog) { dialog.close(); } }] }); }); } }); } }); //===========================ๆŸฅ็œ‹ๅปบ็ญ‘็ฑปๅž‹ๅค„็†================================= $("a#BuildingTypeViewLink").off().on("click",function(){ if(typeNo==null){ BootstrapDialog.show({ title: 'ๅปบ็ญ‘็ฑปๅž‹ๆ“ไฝœไฟกๆฏ', message:"่ฏท้€‰ๆ‹ฉ่ฆๆŸฅ็œ‹็š„ๅปบ็ญ‘็ฑปๅž‹", buttons: [{ label: '็กฎๅฎš', action: function(dialog) { dialog.close(); } }] }); } else{ $("div#BuildingTypeDialogArea").load("buildingType/view.html",function(){ //ๅ–ๅพ—้€‰ๆ‹ฉ็š„ๅปบ็ญ‘็ฑปๅž‹ $.getJSON(host+"buildType/get",{no:typeNo},function(data){ if(data){ $("span#no").html(typeNo); $("span#name").html(data.name); } }); //ๅผนๅ‡บDialog $("div#BuildingTypeDialogArea" ).dialog({ title:"ๅปบ็ญ‘็ฑปๅž‹่ฏฆ็ป†", width:600 }); //็‚นๅ‡ปๅ–ๆถˆๆŒ‰้’ฎๅค„็† $("input[value='ๅ…ณ้—ญ']").on("click",function(){ $( "div#BuildingTypeDialogArea").dialog( "close" ); $( "div#BuildingTypeDialogArea").dialog( "destroy" ); $("div#BuildingTypeDialogArea").html(""); }); }); } }); });
'use strict'; $(window).on('load resize', function() { let width = $(document).width(); if ( width < 767.9 && !$('.top-directions__slider').hasClass('slick-initialized') ) { let topDirectionsSlider = $('.top-directions__slider').slick({ infinite: true, fade: true, autoplay: false, speed: 300, autoplaySpeed: 5000, pauseOnDotsHover: true, pauseOnHover: true, slidesToShow: 1, rows: 1, swipeToSlide: true, swipe: true, adaptiveHeight: false, dots: true, arrows: false, appendDots: $('.top-directions__dots-container'), mobileFirst: true, responsive: [ { breakpoint: 767.9, settings: 'unslick' } ] }); topDirectionsSlider.on('afterChange', function(event, slick, currentSlide, nextSlide) { let prevSlide1, prevSlide2; if(currentSlide === slick.$slides.length - 1 ) { prevSlide1 = $(slick.$slides[0]).data('bg'); } else { prevSlide1 = $(slick.$slides[currentSlide + 1]).data('bg'); } if( currentSlide === slick.$slides.length - 2 ) { prevSlide2 = $(slick.$slides[0]).data('bg'); } else if(currentSlide > slick.$slides.length - 2) { prevSlide2 = $(slick.$slides[1]).data('bg'); } else { prevSlide2 = $(slick.$slides[currentSlide + 2]).data('bg'); } $('.top-directions__prev-slide_1').css({'background':'url(' + prevSlide1 + ') center no-repeat', 'background-size':'cover'}); $('.top-directions__prev-slide_2').css({'background':'url(' + prevSlide2 + ') center no-repeat', 'background-size':'cover'}); }); $('.top-directions__prev-slide_1').css({'background':'url(' + $('.top-directions__item:nth-child(2)').data('bg') + ') center no-repeat', 'background-size':'cover'}); $('.top-directions__prev-slide_2').css({'background':'url(' + $('.top-directions__item:nth-child(3)').data('bg') + ') center no-repeat', 'background-size':'cover'}); } });
module.exports ={ "secret_key":"she_come_dey_fuck_u,i_wanttoshifturwombforu" }
import Vue from 'vue'; import Vuex from 'vuex'; import user from './modules/user'; import carrier from './modules/carrier'; import mock from './modules/mock'; //ไพง่พนๆ ๅˆ‡ๆข import toggleSideBar from './modules/toggleSideBar'; //ๆต่งˆ้กต้ขๅก็‰‡ import tabView from './modules/tabView'; import getters from './getters'; Vue.use(Vuex); const store = new Vuex.Store({ modules: { user, carrier, mock, toggleSideBar, tabView, }, getters }); export default store
// @flow import React from 'react'; import {View, Text} from '../../components/core'; import {ResponsiveImage} from '../../components'; import {baseTextStyle} from '../../constants/text'; import {themeColors} from '../../constants/colors'; import CODEPOLITAN from '../../assets/images/communityPartners/codepolitan.png'; import ID_RUBY from '../../assets/images/communityPartners/id-ruby.png'; import SARCCOM from '../../assets/images/communityPartners/sarccom.png'; import BNCC from '../../assets/images/communityPartners/bncc.png'; export default function CommunityPartners() { return ( <View> <Text style={{ fontWeight: baseTextStyle.FONT_BOLD, textAlign: 'center', fontSize: 20, paddingVertical: 10, color: themeColors.THEME_COLOR, }} > Community Partners </Text> <View style={{flexDirection: 'row', paddingTop: 10, alignItems: 'center'}} > <View style={{flex: 1}}> <ResponsiveImage source={SARCCOM} style={{marginBottom: 30}} /> <ResponsiveImage source={CODEPOLITAN} /> </View> <View style={{flex: 1, paddingHorizontal: 10}}> <ResponsiveImage source={ID_RUBY} style={{marginBottom: 30}} /> <ResponsiveImage source={BNCC} /> </View> </View> </View> ); }
var http = require('http'); var qs = require('querystring'); var fs = require('fs'); var server = http.createServer(function(req, res) { if (req.method === 'POST') { var body=''; req.on('data', function(chunk) { console.log(chunk); body+=chunk; }); req.on('end', function() { var data = qs.parse(body); res.writeHead(200, {'Content-Type': 'text/html'}); var file = fs.createReadStream('index.html'); file.pipe(res); //res.end(JSON.stringify(data)); }); } if (req.method === 'GET') { res.writeHead(200, {'Content-Type': 'text/html'}); var file = fs.createReadStream('index.html'); file.pipe(res); } }).listen(8888); console.log('Listening on port 8888');
import React from "react"; import './Objective.scss'; class Objective extends React.Component { render() { return ( <div className="Objective"> <h2 className="title">Hello, I'm Pham Ngoc Lam</h2> <p> It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. </p> </div> ); } } export default Objective;
import React from 'react' import { StyleSheet, Text, View, Image} from 'react-native' import Icon from 'react-native-vector-icons/FontAwesome'; import { colors } from '../../utils/colors'; import { Rupiah } from '../../helper/Rupiah'; import {logo} from '../../assets'; import { TouchableOpacity } from 'react-native-gesture-handler'; import { SafeAreaView } from 'react-native-safe-area-context'; const NotifAlert = ({navigation, route}) => { const dateRegister = () => { var todayTime = new Date(); var month = todayTime.getMonth() + 1; var day = todayTime.getDate(); var year = todayTime.getFullYear(); var hour = todayTime.getHours(); var minute = todayTime.getMinutes(); return year + "-" + month + "-" + day + " " + hour +":"+ minute; } return ( <SafeAreaView style={styles.container}> <View style={{flexDirection : 'row', justifyContent : 'center'}}> <View style={{flex : 2}}> <TouchableOpacity onPress={() => navigation.goBack()}> <Icon name = 'times' size = {20} /> </TouchableOpacity> </View> <View style={{flex : 2, alignItems :'center', justifyContent : 'center'}}> <Text style={styles.title}>USADHA BAKTHI</Text> </View> <View style={{flex : 2}}> </View> </View> <View style={{alignItems : 'center'}}> <Image source={logo} style={{marginTop : 60, height : 100, width : 100, borderRadius :100}}/> <Text style={{fontSize : 20, marginTop : 70, textAlign : 'center', color : 'green'}}>{route.params.notif}</Text> <Text style={{marginTop : 30, fontSize : 15, color : '#000'}}>{dateRegister()}</Text> <TouchableOpacity style={styles.btn} onPress={() => navigation.navigate('Dashboard')}> <Text style={{color : '#ffffff', fontSize: 15, fontWeight : 'bold'}}>Kembali</Text> </TouchableOpacity> </View> </SafeAreaView> ) } export default NotifAlert const styles = StyleSheet.create({ container : { flex : 1, backgroundColor : '#ffffff', padding : 20, alignItems : 'center', }, title : { textAlign : 'center', fontSize : 20, fontWeight : 'bold' }, btn : { borderWidth : 1, padding : 10, width : 340, borderRadius : 10, alignItems : 'center', justifyContent : 'center', marginTop : 40, borderColor : colors.btn, backgroundColor : colors.btn } })
"use strict"; const _ = require('lodash'), semver = require('semver'), params = require('./parameters'), // private data _configuration = { dbType: null, // shoud be overriden in driver implementation dbVer: null, // shoud be overriden in driver implementation maxRows: 10000, // max rows for fetch results getConnMaxProbes: 30, // times getConnWaitMinTime: 1000, // miliseconds getConnWaitMaxTime: 4000, poolFetchTimeout: 60, // timeout in seconds for waiting to getDbConnection() succesful callback gatherStats: false }; // private data let _driver = null; let _dbPool = null; class AbstractDriver { /** * Base Constructor * * @param driver * @param cfg * @constructor */ constructor(driver, cfg) { this.setCfg(cfg); this.setDriver(driver); // disable setters (no longer needed) this.setCfg = null; this.setDriver = null; } performStandardSetupChecks(requiredVer) { // check driver version match if(!semver.satisfies(this.getCfg().driverVersion, requiredVer)) { throw new Error('Driver version (' + this.getCfg().driverVersion + ') is not supported! Required version is ' + requiredVer); } // todo-me: replace it with injected object handler not global // check and eventually setup MyError global handler if(typeof global.MyError !== 'function') { global.MyError = Error; } // check connection param object existence if(typeof this.getCfg().connection !== 'object') { throw new Error('No connection parameters is provided in config data!'); } } // getters/setters methods setCfg(cfg) { _.extend(_configuration, cfg); } setDriver(driver) { _driver = driver; } setDbPool(dbPool) { _dbPool = dbPool; } getCfg() { return _configuration; } getDriver() { return _driver; } getDbPool() { return _dbPool; } getFnParams(args, fnName) { return params[fnName](args); } // Templates methods setupPool () { throw new Error('setupPool() must be implemented!'); } getDbConnection () { throw new Error('getDbConnection() must be implemented!'); } executeTransaction () { throw new Error('executeTransaction() must be implemented!'); } selectOneRowSql () { throw new Error('selectOneRowSql() must be implemented!'); } selectOneRow () { throw new Error('selectOneRow() must be implemented!'); } selectOneValueSql () { throw new Error('selectOneValueSql() must be implemented!'); } selectOneValue () { throw new Error('selectOneValue() must be implemented!'); } selectAllRowsSql () { throw new Error('selectAllRowsSql() must be implemented!'); } selectAllRows () { throw new Error('selectAllRows() must be implemented!'); } getSqlForSelectAllRowsSql () { throw new Error('getSqlForSelectAllRowsSql() must be implemented!'); } getSqlForSelectAllRows () { throw new Error('getSqlForSelectAllRows() must be implemented!'); } runProcedure () { throw new Error('runProcedure() must be implemented!'); } insertReturningId () { throw new Error('insertReturningId() must be implemented!'); } insertReturningIdSql () { throw new Error('insertReturningIdSql() must be implemented!'); } querySql () { throw new Error('querySql() must be implemented!'); } update () { throw new Error('update() must be implemented!'); } insert () { throw new Error('insert() must be implemented!'); } del () { throw new Error('del() must be implemented!'); } } module.exports = AbstractDriver;
import CONSTANT from "../../constants.js"; export default ({ target, store, actionCreators }) => { const { addToFavorites, deleteFromFavorites } = actionCreators; const addItemToFavorites = target.dataset.favorite === CONSTANT.ADD_TO_FAVORITES; addItemToFavorites ? store.dispatch(addToFavorites(target.id)) : store.dispatch(deleteFromFavorites(target.id)); document.getElementById("searchInput").value = ""; };
// 'use strict'; const gulp = require('gulp'); const plumber = require('gulp-plumber'); const imagemin = require('gulp-imagemin'); const terser = require('gulp-terser'); const babel = require('gulp-babel'); const webpack = require('webpack-stream'); const sass = require('gulp-sass'); const rename = require('gulp-rename'); const concat = require('gulp-concat'); const autoprefixer = require('gulp-autoprefixer'); const cleancss = require('gulp-clean-css'); const purgecss = require('gulp-purgecss'); sass.compiler = require('node-sass'); // images gulp.task('images', function() { return gulp .src('src/images/**/*') .pipe(imagemin({ optimizationLevel: 3, progressive: true, interlaced: true })) .pipe(gulp.dest('dist/images/')); }); // assets gulp.task('assets', function() { return gulp.src('src/assets/**/*').pipe(gulp.dest('dist/assets/')); }); // scripts gulp.task('scripts', function() { return gulp .src(['!src/scripts/bundle.js', 'src/scripts/**/*.js']) .pipe( plumber({ errorHandler: function(error) { console.log(error.message); this.emit('end'); } }) ) .pipe( babel({ presets: ['@babel/env'] }) ) .pipe(webpack()) .pipe(concat('bundle.js')) .pipe(terser()) .pipe(gulp.dest('dist/scripts')); }); // styles gulp.task('styles', function() { return gulp .src('src/styles/**/*.scss') .pipe(sass().on('error', sass.logError)) .pipe(rename('style.css')) .pipe( autoprefixer({ browsers: ['last 10 versions'], cascade: false }) ) .pipe( purgecss({ content: ['src/**/*.html'] }) ) .pipe(cleancss({ level: '2', minify: 'true' })) .pipe(gulp.dest('src/styles')) .pipe(gulp.dest('dist/styles')); }); // html gulp.task('html', function() { return gulp.src('src/**/*.html').pipe(gulp.dest('dist')); }); // default gulp.task('default', gulp.series('images', 'assets', 'scripts', 'styles', 'html')); // watch gulp.task('watch', function() { gulp.watch('src/images/**/*', gulp.series('images')); gulp.watch('src/assets/**/*', gulp.series('assets')); gulp.watch('src/scripts/**/*.js', gulp.series('scripts')); gulp.watch('src/styles/**/*.scss', gulp.series('styles')); gulp.watch('src/**/*.html', gulp.series('html')); });