text
stringlengths
7
3.69M
var title= document.querySelector('h1'); title.addEventListener('click', updateName); function updateName() { var name= prompt('Nombre del juegador'); title.textContent = 'Jugardor 1: ' + name; }
require('dotenv').config(); const express = require('express'); const bodyParser = require('body-parser'); const path = require('path'); const helmet = require('helmet'); const compression = require('compression'); const expressLayouts = require('express-ejs-layouts'); const contentsRouter = require("./router/contents"); const app = new express(); app.use(helmet()); // 보안 이슈 자동으로 해결 // 경로 설정 app.use('/js', express.static(__dirname + '/node_modules/bootstrap/dist/js')); app.use('/js', express.static(__dirname + '/node_modules/jquery/dist')); app.use('/css', express.static(__dirname + '/node_modules/bootstrap/dist/css')); // ejs 설정 app.set('view engine', 'ejs'); app.set('views', [ path.join(__dirname, '/views/page'), path.join(__dirname, '/views/partials') ]); // layout 설정 app.set('layout', 'layout'); app.use(expressLayouts); // qs 분석 app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: false})); app.use(compression()); // 전송되는 데이터 압축 app.get('/', (req, res, next) => { res.render('index.ejs', {title: "index"}) next(); }); app.use('/contents', contentsRouter); app.listen(3000, () => { console.log('Example app listening on port 3000!'); });
/** * Copyright 2013 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @providesModule DefaultDOMPropertyConfig */ /*jslint bitwise: true*/ "use strict"; var DOMProperty = require('DOMProperty'); var MUST_USE_ATTRIBUTE = DOMProperty.injection.MUST_USE_ATTRIBUTE; var MUST_USE_PROPERTY = DOMProperty.injection.MUST_USE_PROPERTY; var HAS_BOOLEAN_VALUE = DOMProperty.injection.HAS_BOOLEAN_VALUE; var HAS_SIDE_EFFECTS = DOMProperty.injection.HAS_SIDE_EFFECTS; var HAS_POSITIVE_NUMERIC_VALUE = DOMProperty.injection.HAS_POSITIVE_NUMERIC_VALUE; var MUST_USE_NAMESPACED_ATTRIBUTE = DOMProperty.injection.MUST_USE_NAMESPACED_ATTRIBUTE; var xmlNamespace = 'http://www.w3.org/XML/1998/namespace'; var xlinkNamespace = 'http://www.w3.org/1999/xlink'; var DefaultDOMPropertyConfig = { isCustomAttribute: RegExp.prototype.test.bind( /^(data|aria)-[a-z_][a-z\d_.\-]*$/ ), Properties: { /** * Standard Properties */ accept: null, accessKey: null, action: null, allowFullScreen: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, allowTransparency: MUST_USE_ATTRIBUTE, alt: null, async: HAS_BOOLEAN_VALUE, autoComplete: null, // autoFocus is polyfilled/normalized by AutoFocusMixin // autoFocus: HAS_BOOLEAN_VALUE, autoPlay: HAS_BOOLEAN_VALUE, cellPadding: null, cellSpacing: null, charSet: MUST_USE_ATTRIBUTE, checked: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, className: MUST_USE_PROPERTY, cols: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE, colSpan: null, content: null, contentEditable: null, contextMenu: MUST_USE_ATTRIBUTE, controls: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, data: null, // For `<object />` acts as `src`. dateTime: MUST_USE_ATTRIBUTE, defer: HAS_BOOLEAN_VALUE, dir: null, disabled: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, draggable: null, encType: null, form: MUST_USE_ATTRIBUTE, frameBorder: MUST_USE_ATTRIBUTE, height: MUST_USE_ATTRIBUTE, hidden: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, href: null, htmlFor: null, httpEquiv: null, icon: null, id: MUST_USE_PROPERTY, label: null, lang: null, list: null, loop: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, max: null, maxLength: MUST_USE_ATTRIBUTE, method: null, min: null, multiple: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, name: null, pattern: null, placeholder: null, poster: null, preload: null, radioGroup: null, readOnly: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, rel: null, required: HAS_BOOLEAN_VALUE, role: MUST_USE_ATTRIBUTE, rows: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE, rowSpan: null, scope: null, scrollLeft: MUST_USE_PROPERTY, scrollTop: MUST_USE_PROPERTY, selected: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, size: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE, span: HAS_POSITIVE_NUMERIC_VALUE, spellCheck: null, src: null, step: null, style: null, tabIndex: null, target: null, title: null, type: null, value: MUST_USE_PROPERTY | HAS_SIDE_EFFECTS, width: MUST_USE_ATTRIBUTE, wmode: MUST_USE_ATTRIBUTE, /** * Non-standard Properties */ autoCapitalize: null, // Supported in Mobile Safari for keyboard hints autoCorrect: null, // Supported in Mobile Safari for keyboard hints property: null, // Supports OG in meta tags /** * SVG Properties */ accentHeight: MUST_USE_ATTRIBUTE, accumulate: MUST_USE_ATTRIBUTE, additive: MUST_USE_ATTRIBUTE, alphabetic: MUST_USE_ATTRIBUTE, amplitude: MUST_USE_ATTRIBUTE, arabicForm: MUST_USE_ATTRIBUTE, ascent: MUST_USE_ATTRIBUTE, attributeName: MUST_USE_ATTRIBUTE, attributeType: MUST_USE_ATTRIBUTE, azimuth: MUST_USE_ATTRIBUTE, baseFrequency: MUST_USE_ATTRIBUTE, baseProfile: MUST_USE_ATTRIBUTE, bbox: MUST_USE_ATTRIBUTE, begin: MUST_USE_ATTRIBUTE, bias: MUST_USE_ATTRIBUTE, by: MUST_USE_ATTRIBUTE, calcMode: MUST_USE_ATTRIBUTE, capHeight: MUST_USE_ATTRIBUTE, clipPathUnits: MUST_USE_ATTRIBUTE, contentScriptType: MUST_USE_ATTRIBUTE, contentStyleType: MUST_USE_ATTRIBUTE, cursor: MUST_USE_ATTRIBUTE, cx: MUST_USE_ATTRIBUTE, cy: MUST_USE_ATTRIBUTE, d: MUST_USE_ATTRIBUTE, descent: MUST_USE_ATTRIBUTE, diffuseConstant: MUST_USE_ATTRIBUTE, divisor: MUST_USE_ATTRIBUTE, dur: MUST_USE_ATTRIBUTE, dx: MUST_USE_ATTRIBUTE, dy: MUST_USE_ATTRIBUTE, edgeMode: MUST_USE_ATTRIBUTE, elevation: MUST_USE_ATTRIBUTE, end: MUST_USE_ATTRIBUTE, exponent: MUST_USE_ATTRIBUTE, externalResourcesRequired: MUST_USE_ATTRIBUTE, filterRes: MUST_USE_ATTRIBUTE, filterUnits: MUST_USE_ATTRIBUTE, format: MUST_USE_ATTRIBUTE, from: MUST_USE_ATTRIBUTE, fx: MUST_USE_ATTRIBUTE, fy: MUST_USE_ATTRIBUTE, g1: MUST_USE_ATTRIBUTE, g2: MUST_USE_ATTRIBUTE, glyphName: MUST_USE_ATTRIBUTE, glyphRef: MUST_USE_ATTRIBUTE, gradientTransform: MUST_USE_ATTRIBUTE, gradientUnits: MUST_USE_ATTRIBUTE, hanging: MUST_USE_ATTRIBUTE, horizAdvX: MUST_USE_ATTRIBUTE, horizOriginX: MUST_USE_ATTRIBUTE, horizOriginY: MUST_USE_ATTRIBUTE, ideographic: MUST_USE_ATTRIBUTE, svgIn: MUST_USE_ATTRIBUTE, in2: MUST_USE_ATTRIBUTE, intercept: MUST_USE_ATTRIBUTE, k: MUST_USE_ATTRIBUTE, k1: MUST_USE_ATTRIBUTE, k2: MUST_USE_ATTRIBUTE, k3: MUST_USE_ATTRIBUTE, k4: MUST_USE_ATTRIBUTE, kernelMatrix: MUST_USE_ATTRIBUTE, kernelUnitLength: MUST_USE_ATTRIBUTE, keyPoints: MUST_USE_ATTRIBUTE, keySplines: MUST_USE_ATTRIBUTE, keyTimes: MUST_USE_ATTRIBUTE, lengthAdjust: MUST_USE_ATTRIBUTE, limitingConeAngle: MUST_USE_ATTRIBUTE, local: MUST_USE_ATTRIBUTE, markerHeight: MUST_USE_ATTRIBUTE, markerUnits: MUST_USE_ATTRIBUTE, markerWidth: MUST_USE_ATTRIBUTE, maskContentUnits: MUST_USE_ATTRIBUTE, maskUnits: MUST_USE_ATTRIBUTE, mathematical: MUST_USE_ATTRIBUTE, media: MUST_USE_ATTRIBUTE, mode: MUST_USE_ATTRIBUTE, numOctaves: MUST_USE_ATTRIBUTE, offset: MUST_USE_ATTRIBUTE, operator: MUST_USE_ATTRIBUTE, order: MUST_USE_ATTRIBUTE, orient: MUST_USE_ATTRIBUTE, orientation: MUST_USE_ATTRIBUTE, origin: MUST_USE_ATTRIBUTE, overlinePosition: MUST_USE_ATTRIBUTE, overlineThickness: MUST_USE_ATTRIBUTE, panose1: MUST_USE_ATTRIBUTE, path: MUST_USE_ATTRIBUTE, pathLength: MUST_USE_ATTRIBUTE, patternContentUnits: MUST_USE_ATTRIBUTE, patternTransform: MUST_USE_ATTRIBUTE, patternUnits: MUST_USE_ATTRIBUTE, points: MUST_USE_ATTRIBUTE, pointsAtX: MUST_USE_ATTRIBUTE, pointsAtY: MUST_USE_ATTRIBUTE, pointsAtZ: MUST_USE_ATTRIBUTE, preserveAlpha: MUST_USE_ATTRIBUTE, preserveAspectRatio: MUST_USE_ATTRIBUTE, primitiveUnits: MUST_USE_ATTRIBUTE, r: MUST_USE_ATTRIBUTE, radius: MUST_USE_ATTRIBUTE, refX: MUST_USE_ATTRIBUTE, refY: MUST_USE_ATTRIBUTE, renderingIntent: MUST_USE_ATTRIBUTE, repeatCount: MUST_USE_ATTRIBUTE, repeatDur: MUST_USE_ATTRIBUTE, repeatExtensions: MUST_USE_ATTRIBUTE, requiredExtensions: MUST_USE_ATTRIBUTE, requiredFeatures: MUST_USE_ATTRIBUTE, restart: MUST_USE_ATTRIBUTE, result: MUST_USE_ATTRIBUTE, rotate: MUST_USE_ATTRIBUTE, rx: MUST_USE_ATTRIBUTE, ry: MUST_USE_ATTRIBUTE, scale: MUST_USE_ATTRIBUTE, seed: MUST_USE_ATTRIBUTE, slope: MUST_USE_ATTRIBUTE, spacing: MUST_USE_ATTRIBUTE, specularConstant: MUST_USE_ATTRIBUTE, specularExponent: MUST_USE_ATTRIBUTE, spreadMethod: MUST_USE_ATTRIBUTE, startOffset: MUST_USE_ATTRIBUTE, stdDeviation: MUST_USE_ATTRIBUTE, stemh: MUST_USE_ATTRIBUTE, stemv: MUST_USE_ATTRIBUTE, stitchTiles: MUST_USE_ATTRIBUTE, strikethroughPosition: MUST_USE_ATTRIBUTE, strikethroughThickness: MUST_USE_ATTRIBUTE, string: MUST_USE_ATTRIBUTE, surfaceScale: MUST_USE_ATTRIBUTE, systemLanguage: MUST_USE_ATTRIBUTE, tableValues: MUST_USE_ATTRIBUTE, targetX: MUST_USE_ATTRIBUTE, targetY: MUST_USE_ATTRIBUTE, textLength: MUST_USE_ATTRIBUTE, to: MUST_USE_ATTRIBUTE, transform: MUST_USE_ATTRIBUTE, u1: MUST_USE_ATTRIBUTE, u2: MUST_USE_ATTRIBUTE, underlinePosition: MUST_USE_ATTRIBUTE, underlineThickness: MUST_USE_ATTRIBUTE, unicode: MUST_USE_ATTRIBUTE, unicodeRange: MUST_USE_ATTRIBUTE, unitsPerEm: MUST_USE_ATTRIBUTE, vAlphabetic: MUST_USE_ATTRIBUTE, vHanging: MUST_USE_ATTRIBUTE, vIdeographic: MUST_USE_ATTRIBUTE, vMathematical: MUST_USE_ATTRIBUTE, values: MUST_USE_ATTRIBUTE, version: MUST_USE_ATTRIBUTE, vertAdvY: MUST_USE_ATTRIBUTE, vertOriginX: MUST_USE_ATTRIBUTE, vertOriginY: MUST_USE_ATTRIBUTE, viewBox: MUST_USE_ATTRIBUTE, viewTarget: MUST_USE_ATTRIBUTE, widths: MUST_USE_ATTRIBUTE, x1: MUST_USE_ATTRIBUTE, x2: MUST_USE_ATTRIBUTE, x: MUST_USE_ATTRIBUTE, xHeight: MUST_USE_ATTRIBUTE, xChannelSelector: MUST_USE_ATTRIBUTE, xlinkActuate: MUST_USE_NAMESPACED_ATTRIBUTE, xlinkArcrole: MUST_USE_NAMESPACED_ATTRIBUTE, xlinkHref: MUST_USE_NAMESPACED_ATTRIBUTE, xlinkRole: MUST_USE_NAMESPACED_ATTRIBUTE, xlinkShow: MUST_USE_NAMESPACED_ATTRIBUTE, xlinkTitle: MUST_USE_NAMESPACED_ATTRIBUTE, xlinkType: MUST_USE_NAMESPACED_ATTRIBUTE, xmlBase: MUST_USE_NAMESPACED_ATTRIBUTE, xmlLang: MUST_USE_NAMESPACED_ATTRIBUTE, xmlSpace: MUST_USE_NAMESPACED_ATTRIBUTE, y1: MUST_USE_ATTRIBUTE, y2: MUST_USE_ATTRIBUTE, y: MUST_USE_ATTRIBUTE, yChannelSelector: MUST_USE_ATTRIBUTE, z: MUST_USE_ATTRIBUTE, zoomAndPan: MUST_USE_ATTRIBUTE }, DOMAttributeNames: { className: 'class', htmlFor: 'for', /** * SVG */ accentHeight: 'accent-height', arabicForm: 'arabic-form', attributeName: 'attributeName', attributeType: 'attributeType', baseFrequency: 'baseFrequency', baseProfile: 'baseProfile', calcMode: 'calcMode', capHeight: 'cap-height', clipPathUnits: 'clipPathUnits', contentScriptType: 'contentScriptType', contentStyleType: 'contentStyleType', diffuseConstant: 'diffuseConstant', edgeMode: 'edgeMode', externalResourcesRequired: 'externalResourcesRequired', filterRes: 'filterRes', filterUnits: 'filterUnits', glyphName: 'glyph-name', glyphRef: 'glyphRef', gradientTransform: 'gradientTransform', gradientUnits: 'gradientUnits', horizAdvX: 'horiz-adv-x', horizOriginX: 'horiz-origin-x', horizOriginY: 'horiz-origin-y', svgIn: 'in', kernelMatrix: 'kernelMatrix', kernelUnitLength: 'kernelUnitLength', keyPoints: 'keyPoints', keySplines: 'keySplines', keyTimes: 'keyTimes', lengthAdjust: 'lengthAdjust', limitingConeAngle: 'limitingConeAngle', markerHeight: 'markerHeight', markerUnits: 'markerUnits', markerWidth: 'markerWidth', maskContentUnits: 'maskContentUnits', maskUnits: 'maskUnits', numOctaves: 'numOctaves', overlinePosition: 'overline-position', overlineThickness: 'overline-thickness', panose1: 'panose-1', pathLength: 'pathLength', patternContentUnits: 'patternContentUnits', patternTransform: 'patternTransform', patternUnits: 'patternUnits', pointsAtX: 'pointsAtX', pointsAtY: 'pointsAtY', pointsAtZ: 'pointsAtZ', preserveAlpha: 'preserveAlpha', preserveAspectRatio: 'preserveAspectRatio', primitiveUnits: 'primitiveUnits', refX: 'refX', refY: 'refY', renderingIntent: 'rendering-intent', repeatCount: 'repeatCount', repeatDur: 'repeatDur', requiredExtensions: 'requiredExtensions', requiredFeatures: 'requiredFeatures', specularConstant: 'specularConstant', specularExponent: 'specularExponent', spreadMethod: 'spreadMethod', startOffset: 'startOffset', stdDeviation: 'stdDeviation', stitchTiles: 'stitchTiles', strikethroughPosition: 'strikethrough-position', strikethroughThickness: 'strikethrough-thickness', surfaceScale: 'surfaceScale', systemLanguage: 'systemLanguage', tableValues: 'tableValues', targetX: 'targetX', targetY: 'targetY', textLength: 'textLength', underlinePosition: 'underline-position', underlineThickness: 'underline-thickness', unicodeRange: 'unicode-range', unitsPerEm: 'units-per-em', vAlphabetic: 'v-alphabetic', vHanging: 'v-hanging', vIdeographic: 'v-ideographic', vMathematical: 'v-mathematical', vertAdvY: 'vert-adv-y', vertOriginX: 'vert-origin-x', vertOriginY: 'vert-origin-y', viewBox: 'viewBox', viewTarget: 'viewTarget', xHeight: 'x-height', xChannelSelector: 'xChannelSelector', xlinkActuate: 'actuate', xlinkArcrole: 'arcrole', xlinkHref: 'href', xlinkRole: 'role', xlinkShow: 'show', xlinkTitle: 'title', xlinkType: 'type', xmlBase: 'base', xmlLang: 'lang', xmlSpace: 'space', yChannelSelector: 'yChannelSelector', zoomAndPan: 'zoomAndPan' }, DOMPropertyNames: { autoCapitalize: 'autocapitalize', autoComplete: 'autocomplete', autoCorrect: 'autocorrect', autoFocus: 'autofocus', autoPlay: 'autoplay', encType: 'enctype', radioGroup: 'radiogroup', spellCheck: 'spellcheck' }, DOMAttributeNamespaces: { xlinkActuate: xlinkNamespace, xlinkArcrole: xlinkNamespace, xlinkHref: xlinkNamespace, xlinkRole: xlinkNamespace, xlinkShow: xlinkNamespace, xlinkTitle: xlinkNamespace, xlinkType: xlinkNamespace, xmlBase: xmlNamespace, xmlLang: xmlNamespace, xmlSpace: xmlNamespace }, DOMMutationMethods: { /** * Setting `className` to null may cause it to be set to the string "null". * * @param {DOMElement} node * @param {*} value */ className: function(node, value) { node.className = value || ''; } } }; module.exports = DefaultDOMPropertyConfig;
const test = require('ava'); const request = require('supertest'); const { makeApp } = require('./_helper'); test('GET /health', async t => { t.plan(2); const res = await request(makeApp()).get('/health'); t.is(res.status, 200); t.is(res.text, 'OK'); });
let num = 50; //делаем пока верно условие // while (num < 55) { // console.log(num); // num++; // } //что-то делаем, потом проверяем // do { // console.log(num); // num++; // } // while (num < 56); for (i = 1; i < 8; i++) { console.log(i) } for (i = 1; i < 8; i++) { if (i == 6) { break //выходим из цикла } console.log(i); } for (i = 1; i < 8; i++) { if (i == 6) { continue //пропускаем этот шаг } console.log(i); }
var React = require('react'); var DeleteItemBtn = React.createClass({ deleteItem: function (e) { // Passing order of task this.props.clicked(this.props.order); }, render: function () { return (<button className="itemDelete" data-order={this.props.order} onClick={this.deleteItem} >X</button> ); } }); var CheckItem = React.createClass({ getInitialState: function() { return {item: this.props.item, itemIdx: this.props.order }; }, modifyItem: function (e) { // Passing order of task this.props.clicked(this.props.order, !this.props.item.done); }, render: function () { return (<input className="itemCheck" type="checkbox" checked={this.props.item.done} onChange={this.modifyItem} />); } }); var TodoList = React.createClass({ handleDeleteItem: function(idx){ //console.log('handleDeleteItem: '+idx); this.props.items.splice(idx, 1) this.setState(this.state); return; }, handleModifyItem: function(idx, isDone){ //console.log('handleDeleteItem: '+idx); this.props.items[idx]['done'] = isDone this.setState(this.state); return; }, render: function() { var handleDeleteItem = this.handleDeleteItem; var handleModifyItem = this.handleModifyItem; var createItem = function(item, idx) { return ( <li> <CheckItem clicked={handleModifyItem} order={idx} item={item} /> <span className="itemLabel" >{item.text}</span> <DeleteItemBtn clicked={handleDeleteItem} order={idx} item={item} /> </li> ); }; return ( <div> <div class="itemsCompletedCounter" >items completed: {this.props.items.filter(function(el){ return el.done }).length}</div> <ul>{this.props.items.map(createItem)}</ul> </div> ); } }); var TodoPage = React.createClass({ getInitialState: function() { return {items: [{ 'text' : 'dog', 'done': true}, { 'text' : 'cat', 'done': false}], text: ''}; }, onChange: function(e) { this.setState({text: e.target.value}); }, handleSubmit: function(e) { e.preventDefault(); //var nextItems = this.state.items.concat([this.state.text]); if(!this.state.text) return; var nextItems = this.state.items.concat([{'text': this.state.text, 'done' : false}]); var nextText = ''; this.setState({items: nextItems, text: nextText}); }, render: function() { return ( <div> <form onSubmit={this.handleSubmit}> <input name="addItemText" className="addItemText" onChange={this.onChange} value={this.state.text} /> <button name="addItemBtn" className="addItemBtn" >{'Add'}</button> </form> <TodoList items={this.state.items} /> </div> ); } }); module.exports = TodoPage;
import { reactLocalStorage } from 'reactjs-localstorage'; import lodash from 'lodash'; import history from './../../../../history'; import React, { useContext, useState, useEffect } from 'react'; import { VeContext } from "./../../../../contexts/VeContext" function CamOnQuyKhach(props) { const { VeStateContext, AddNewVe } = useContext(VeContext) if (VeStateContext.length == 0 || lodash.isEmpty(reactLocalStorage.getObject("CurrentUser"))) { history.push("/") } function ExecCamOnQuyKhach() { if (VeStateContext.length > 0) { AddNewVe([]) } return ( <div className="flex justify-center items-center h-screen"> <div className="border border-main mb-24 shadow-xl"> <div className="p-8"> <span className="text-2xl">Cảm ơn quý khách đã sử dụng dịch vụ của chúng tôi</span> </div> <div className="text-center p-4"> <button className="text-main hover:underline cursor-pointer">Quay Về Trang Chủ</button> <button className="text-main hover:underline cursor-pointer ml-24">Xem Danh Sách Vé Của Bạn</button> </div> </div> </div> ) } return ( <div> {ExecCamOnQuyKhach()} </div> ) } export default CamOnQuyKhach
/* * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Created with IntelliJ IDEA. * User: Natalia.Ukhorskaya * Date: 3/30/12 * Time: 3:37 PM */ var ProblemsView = (function () { function ProblemsView(element, /*Nullable*/ tabs) { var instance = { addMessages:function (data) { addMessagesToProblemsView(data); }, clear:function () { element.html(""); } }; function addMessagesToProblemsView(data) { element.html(""); if (tabs != null) { tabs.tabs("select", 0); } var i = 0; var problems = document.createElement("div"); function processError(i, p, f) { if (data[i] == undefined) { element.html(problems.innerHTML); return; } var title = unEscapeString(data[i].titleName); var start = eval('(' + data[i].x + ')'); var severity = data[i].severity; var problem = createElementForProblemsView(severity, start, title); p.appendChild(problem); i++; setTimeout(function (i, problems) { return function () { f(i, problems, processError); } }(i, problems), 10); } processError(i, problems, processError); } function createElementForProblemsView(severity, start, title) { var p = document.createElement("p"); var img = document.createElement("img"); if (severity == 'WARNING') { img.src = "/static/icons/warning.png"; if (title.indexOf("is never used") > 0) { p.className = "problemsViewWarningNeverUsed"; } else { p.className = "problemsViewWarning"; } } else if (severity == 'STACKTRACE') { p.className = "problemsViewStacktrace"; } else { img.src = "/static/icons/error.png"; p.className = "problemsViewError"; } p.appendChild(img); var titleDiv = document.createElement("span"); if (start == null) { titleDiv.innerHTML = " " + unEscapeString(title); } else { titleDiv.innerHTML = "(" + (start.line + 1) + ", " + (start.ch + 1) + ") : " + unEscapeString(title); } p.appendChild(titleDiv); return p; } return instance; } return ProblemsView; })();
import _ from 'underscore'; import $ from 'jquery'; import app from '../../../app'; import BaseModel from '../../../base/model/base'; export default class LoginModel extends BaseModel { constructor (options) { super(options); this.schema = { title: { type : 'Text', title : 'Titel', validators : [ { type: 'required', message: '' } ] }, message: { type : 'TextArea', title : 'Beitrag', validators : [ { type: 'required', message: '' } ] } //, //link: { // type : 'Text', // title : 'Link' //}, //linktext: { // type : 'Text', // title : 'Titel' //} }; } sync () { let dta = { title: this.get('title'), message: this.get('message') //link: this.get('link'), //linktext: this.get('linktext') }; return $.ajax({ type: 'post', dataType: 'json', url: _.getApiUrl('savepost'), data: { dta: JSON.stringify(dta) }, success: function () { app.trigger('post:done'); app.user.fetch(); } }); } }
import * as actionTypes from './types'; export const initialModalState = { modalOpen: false, modalProps: null, }; export const modalReducer = (state = initialModalState, action) => { switch(action.type) { case(actionTypes.OPEN_MODAL): return { modalOpen: true, modalProps: action.payload, }; case(actionTypes.CLOSE_MODAL): return { modalOpen: false, modalProps: null, }; } return state; };
const { Given, When, Then, AfterAll} = require('@cucumber/cucumber'); const assert = require("assert"); require('chromedriver'); const {Builder, By, Key, until, Capabilities} = require("selenium-webdriver"); const chrome = require('selenium-webdriver/chrome'); const chromePath = require('chromedriver').path; let service = new chrome.ServiceBuilder(chromePath).build(); chrome.setDefaultService(service); var {setDefaultTimeout} = require('@cucumber/cucumber'); setDefaultTimeout(60 * 1000); let driver = new Builder().withCapabilities(Capabilities.chrome()).build(); driver.manage().window().maximize(); When("we request the products list", async function() { await driver.get('https://e83b40c1trial-dev-mydreamapp-approuter.cfapps.eu10.hana.ondemand.com/namespaceui/index.html'); }); Then ("we should receive", async function(dataTable) { await driver.wait(until.elementsLocated(By.xpath("//tbody/tr"))); await driver.sleep(2000); const tasksElements = await driver.findElements(By.xpath("//tbody/tr")); await driver.sleep(2000); const expectations = dataTable.hashes(); for (let i = 0; i < expectations.length; i++) { const taskName = await tasksElements[i].findElement(By.xpath('descendant::span[1]')).getText(); const description = await tasksElements[i].findElement(By.xpath("td[3]/span")).getText(); assert.equal(taskName, expectations[i].name); assert.equal(description, expectations[i].description); } }); Given ("first view", async function() { await driver.findElement(By.xpath("//span[text()='Task planning']")); }); When ("we click on the first item", async function() { this.taskNameText = await driver.findElement(By.xpath("//tbody/tr[1]/td/div/descendant::span[1]")).getText(); await driver.findElement(By.xpath("//tbody/tr[1]")).click(); }); Then ("we rout to details page with specific info", async function() { await driver.sleep(2000); const taskName = await driver.wait(until.elementLocated(By.xpath("//*[@id='__section0-title']"))).getText(); assert.equal(taskName, this.taskNameText); await driver.navigate().back(); }); When ("we click on the second item with activated header checkbox", async function() { const checkbox = await driver.wait(until.elementLocated(By.id("container-ui---tasksList--checkbox"))); const item = await driver.findElement(By.xpath("//tbody/tr[4]")); checkbox.click(); item.click(); }); Then ("we rout to details page with opened dialog form with id {string}", async function(id) { await driver.sleep(2000); const idFromDialog = await driver.wait(until.elementLocated(By.id("__text54"))).getText(); const closeBtn = await driver.findElement(By.id("container-ui---taskDetails--closeDialogBtn")); assert.equal(id, idFromDialog); closeBtn.click(); await driver.navigate().back(); }); Given ("search field", async function() { await driver.wait(until.elementLocated(By.id("container-ui---tasksList--smartFilterBar-filterItemControlA_-Name-inner"))); }); When ("we enter {string} in the input field", async function(query) { this.query = query; const inputField = await driver.wait(until.elementLocated(By.id("container-ui---tasksList--smartFilterBar-filterItemControlA_-Name-inner"))); await inputField.sendKeys("Fix the monitor", Key.ENTER); }); Then ("we see items matching the request", async function() { await driver.sleep(2000); const tasksElements = await driver.wait(until.elementsLocated(By.xpath("//tbody/tr"))); for (let i=0; i < tasksElements.length; i++) { const itemName = await driver.findElement(By.xpath(`//tbody/child::tr[${i+1}]/td/div/descendant::span[1]`)).getText(); assert.equal(itemName, this.query); } }); When ("we go to the second view", async function() { const item = await driver.findElement(By.xpath("//tbody/tr[1]")); item.click(); }); When ("reload the page", async function() { await driver.navigate().refresh(); }); Then ("we should see opened dialog", async function() { await driver.wait(until.elementLocated(By.id("container-ui---taskDetails--jobDetailsFragment"))); }); When("dialog with some data", async function() { await driver.findElement(By.id("container-ui---taskDetails--jobDetailsFragment")); }); Then ("data from dialog is equal to data from section", async function() { await driver.sleep(2000); const labelFromDialogContainers = await driver.findElements(By.xpath("//div[@class='sapUiRespGridBreak sapUiRespGridSpanXL12 sapUiRespGridSpanL12 sapUiRespGridSpanM12 sapUiRespGridSpanS6 sapUiFormElementLbl']/descendant::bdi")); const section = await driver.findElement(By.id("container-ui---taskDetails--simpleFormJobDetails")); const valuesFromDialog = []; const valuesFromSection = []; for (let elem of labelFromDialogContainers) { let text = await elem.getText(); const valueFromDialog = await elem.findElement(By.xpath("ancestor::div[1]/following-sibling::div[1]/span")).getText(); await valuesFromDialog.push(valueFromDialog); const labelFromSection = await section.findElement(By.xpath(`descendant::*[contains(text(), '${text}')]`)); if (text === "ID") { var valueFromSection = await labelFromSection.findElement(By.xpath("ancestor::div[1]/following-sibling::div[1]//descendant::span/span")).getText(); } else { var valueFromSection = await labelFromSection.findElement(By.xpath("ancestor::div[1]/following-sibling::div[1]/span")).getText(); } await valuesFromSection.push(valueFromSection); }; for (let i = 0; i < valuesFromDialog.length; i++) { assert.equal(valuesFromDialog[i], valuesFromSection[i]); } }); AfterAll(async function() { await driver.close(); });
//Enable to use the app builder library const express = require("express"); //Enable to use the router function const router = express.Router(); //Enable to use MongoDB driver const mongoose=require("mongoose"); //Enable to use the library of the models folder refered to this subspace const Espacio1=require("../models/espacio1"); //Webservices to localhost:3000/espacio1/ -> Coge todos los elementos de la DB router.get('/',(req, res, next) => { Espacio1.find() .select("_id attribute1 attribute2") // selecciona que atributos van a pasarse (de cada elemento) en el json de respuesta desde la DB .exec() //ejecuta la Query .then(docs => { //Prepara la respuesta donde además de la informacion de la DB mandamos info adicional const response = { //configuramos lo que va a ir en la respuesta count: docs.length, //contador de objetos espacio1: docs.map(doc=>{ //mapeo de los attributos, etc. que va a llevar la respuesta, haciendo un JsonArray con la respuesta de la DB y +info return { _id: doc._id, attribute1: doc.attribute1, attribute2: doc.attribute2, request: { //nivel inferior type: "GET", url: "localhost:3000/espacio1/"+doc._id } } }) }; console.log("From DB",response); // if(docs.length>=0){ res.json(response); //Ejecuta la respuesta || solo un parametro puede ser devuelto como json res.status(200); // }else{} // res.status(404).json({ // message: "No entries found" // }); // } }) .catch(err=> { console.log(err); res.json({ error:err }); res.status(500); }); }); //La variable "Espacio1", almacena los post request y los almacena como json router.post('/',(req, res, next) => { //Este constructor llama al model referente a espacio1 como esquema de datos valido const espacio1=new Espacio1({ _id: new mongoose.Types.ObjectId(), attribute1: req.body.attribute1, attribute2: req.body.attribute2 }); //Permite guardar datos de acuerdo al model de Espacio1 y con try-catch espacio1 .save() // guardamos el body parseado de la POST request .then(result => { //Preparamos una respuesta del servidor ante la peticion de POST console.log(result); res.status(201).json({ //Preparamos el mensaje de retorno message: "Created element", createdEspacio1: { //Creamos un objeto donde mapeamos el body del post y preparamos la respuesta del servidor al POST attribute1: result.attribute1, attribute2: result.attribute2, _id: result._id, request: { type: "POST", url: "localhost:3000/espacio1/"+result._id } } }); }) .catch(err => { console.log(err); res.status(500).json({ error:err }); }); //Webservices to localhost:3000/espacio1/:id //exec() executes the query to the DB router.get('/:Id', (req, res, next)=>{ const id = req.params.Id; Espacio1.findById(id) // es Espacio1 porque es el metodo del objeto de model .select("_id attribute1 attribute2") // selecciona que atributos van a pasarse (de cada elemento) en el json de respuesta desde la DB .exec() //ejecuta el query .then(docs => { console.log("From DB:",docs); if(docs){ res.status(200).json({ espacio1: docs, request: { //nivel inferior type: "GET", description: "Get_prodcut_by_id", url: "localhost:3000/espacio1/"+docs._id } }); } else { res.status(404).json({message:"No valid id entry"}) } }) .catch(err =>{ console.log(err); res.status(500).json({ error: err }); }); //Dummy code // if(id=="001") { // res.status(200).json({ // message: "Option1", // id: id // }); // } else { // res.status(200).json({ // message: "ID accepted" // }); // } }); router.patch('/:Id',(req, res, next) => { const id=req.params.Id; //se requiere parametro tipo id para encontrar el elemento (en la DB) const updateOps ={}; // se prepara un array con los updates para el elemento( en la DB) for (const ops of req.body){ //se recorren los parametros el body del elemento updateOps[ops.propAttribute1]=ops.value; //se modifican los attributos por Update[key]= value y se guardan en el array } Espacio1.update({_id: id},{ $set: updateOps }) //se hace un update del elemento matcheado por id y aplicando el array .exec() .then(result => { console.log(result); res.status(200).json({ message : "Element updated!", request: { type: "PATCH", url: "localhost:3000/espacio1/"+id } }) }) .catch(err=> { console.log(err); res.status(500).json({ error: err }); }); // res.status(200).json({ // message: 'Updated' // }); }); router.delete('/:Id',(req, res, next) => { const id= req.params.Id; Espacio1.remove({_id: id }) .exec() .then(result => { console.log(result); res.status(200).json(result); }) .catch(err=> { console.log(err); res.status(500).json({ error:err }); }); });}) module.exports=router;
/** * Created by Administrator on 11/14/2017. */ const path=require("path") const db=require(path.join(__dirname,"../config/dbconfig.js")) const tagDao={ getTagsbyall(sql,param){ return new Promise((resove,reject)=>{ db.connect(sql,param,(err,data)=>{ if(err){ console.log("错误发生",err.message) }else{ resove(data) } }) }) }, getCreatePerson(sql,param){ return new Promise((resove,reject)=>{ db.connect(sql,param,(err,data)=>{ if(err){ console.log("查询用户表错误",err.message) }else{ resove(data) } }) }) }, addTag(sql,param){ return new Promise((resove,reject)=>{ db.connect(sql,param,(err,data)=>{ if(err){ console.log("插入标签数据错误",err.message) }else{ resove(data) } }) }) }, validateTagCun(sql,param){ return new Promise((resove,reject)=>{ db.connect(sql,param,(err,data)=>{ if(err){ reject(err) console.log("查询错误",err.message) }else{ resove(data) } }) }) }, updateTag(sql,param){ return new Promise((resolve,reject)=>{ db.connect(sql,param,(err,data)=>{ if(err) { reject(err) }else{ resolve(data); } }) }) }, startandEndUse(sql,param){ return new Promise((resolv,reject)=>{ db.connect(sql,param,(err,data)=>{ if(err) { console.log(err.message) reject(err) }else{ resolv(data); } }) }) }, getTotalCount(sql,param) { return new Promise((resove,reject)=>{ db.connect(sql,param,(err,data)=>{ if(err){ console.log("错误发生",err.message) }else{ resove(data) } }) }) } } module.exports=tagDao
load("/common/common.js"); grouped(["func","blog","smoke"],function(){ test("Blogger Test", function (driver) { var driver = session.get("driver"); try { //var homePage = loginAsTestUser(driver); var homePage = new HomePage(driver).waitForIt(); var bloggerName = "TIM BLAIR"; logged("Navigate to blog and select blogger " + bloggerName, function(){ console.log("Click menu"); homePage.menu.click(); console.log("Select blogger " + bloggerName); homePage.selectedMenuItem("blogs", bloggerName) }); var blogPage = new BlogPage(driver); // verify bloger name var actualBloggerName = blogPage.getBloggerName(); var verifyMsg = "Verify that bloger name is " + bloggerName; console.log(verifyMsg); if(bloggerName == actualBloggerName){ this.report.info(verifyMsg) .withDetails("Blogger name is as expected."); } else{ this.report.error(verifyMsg) .withDetails("Actual: " + actualBloggerName + ", expected: " + "bac") .withAttachment(bloggerName, takeScreenshot(driver)); } // verify that default filter should be LASTEST POSTS, posts should be displayed verifyMsg = "Verify that default filter should be LATEST POSTS, posts should be displayed"; var currentBlogFilter = blogPage.getCurrentBlogFilter(); var numberOfShowingBlog = blogPage.getNumberOfShowingBlog(); console.log(verifyMsg); if((currentBlogFilter == "LATEST POSTS") && (numberOfShowingBlog > 0)){ this.report.info(verifyMsg) .withDetails("Default filter is as expected, there are " + numberOfShowingBlog + " posts."); } else{ this.report.error(verifyMsg) .withDetails("Actual: " + currentBlogFilter + " and " + numberOfShowingBlog + " posts, expected: LASTEST POSTS and posts shoule be greater than zero.") .withAttachment(verifyMsg, takeScreenshot(driver)); } // verify that click show more, more posts are shown console.log("Click show more"); blogPage.clickShowMore(); verifyMsg = "Verify that click show more, more posts are shown"; var numberOfShowingBlogWhenClickingShowMore = blogPage.getNumberOfShowingBlog(); console.log(verifyMsg); console.log("\t=> Before clicking show more: " + numberOfShowingBlog + " post shown, after clicking show more: " + numberOfShowingBlogWhenClickingShowMore + " post shown"); if(numberOfShowingBlogWhenClickingShowMore > numberOfShowingBlog){ this.report.info(verifyMsg) .withDetails("More posts are shown as expected, there are " + numberOfShowingBlogWhenClickingShowMore + " posts."); } else{ this.report.error(verifyMsg) .withDetails("No more post shown when clicking show more") .withAttachment(verifyMsg, takeScreenshot(driver)); } // select to fileter by an archived category, verify that posts filtered by selected category, posts should be displayed blogPage.filterArchiveBlogPostRandomly(); verifyMsg = "Filter by archive - " + blogPage.selectedCategory + ", posts should be displayed"; currentBlogFilter = blogPage.getCurrentBlogFilter(); numberOfShowingBlog = blogPage.getNumberOfShowingBlog(); console.log(verifyMsg); if((blogPage.getCurrentBlogFilter() == "ARCHIVE " + blogPage.selectedCategory) && (numberOfShowingBlog > 0)){ this.report.info(verifyMsg) .withDetails("Filter is as expected, there are " + numberOfShowingBlog + " post"); } else{ this.report.error(verifyMsg) .withDetails("Actual: " + currentBlogFilter + " and " + numberOfShowingBlog + " posts, expected: ARCHIVE " + blogPage.selectedCategory + " and posts should be greater than zero.") .withAttachment(verifyMsg, takeScreenshot(driver)); } } catch(err){ var msg = "Exception message: " + err.message + "\nStack trace: " + err.stack; console.log("===> " + msg); this.report.error(msg) .withAttachment("BloggerTestException", takeScreenshot(driver)); } }) });
import React from 'react'; import ReactDOMServer from 'react-dom/server'; import express from 'express'; import {StaticRouter} from 'react-router-dom'; import App from './App'; const app = express(); // ssr을 처리할 핸들러 함수 const serverRender=(req,res,next)=>{ // 이 함수는 404가 떠야 하는 상황에 404를 띄우지 않고 서버 사이드 렌더링 해줌 const context={}; const jsx=( <StaticRouter location={req.url} context={context}> <App /> </StaticRouter> ) const root =ReactDOMServer.renderToString(jsx); // 렌더링을 하고 res.send(root); // 클라이언트에게 결과물을 응답 } app.use(serverRender); // 5000포트로 서버를 가동 app.listen(5000,()=>{ console.log('5000'); }) const html=ReactDOMServer.renderToString( <div>Hello Server Side Rendering</div> ); console.log(html);
const User = require('../models/usersModel') exports.listarUsuarios = async (req, res) => { const users = await User.find().sort('name'); res.send(users); }; exports.crearUsuarios = async (req, res) => { // const { error } = validate(req.body); // if (error) return res.status(400).send(error.details[0].message); console.log(req.body) let user = new User({ name: req.body.name, email: req.body.email, password: req.body.password, photo: req.body.photo, phone: req.body.phone }); user = await user.save(); res.send(user); }; exports.modificarUsuario = async (req, res) => { // const { error } = validate(req.body); // if (error) return res.status(400).send(error.details[0].message); const user = await User.findByIdAndUpdate(req.params.id, { name: req.body.name, email: req.body.email, password: req.body.password, photo: req.body.photo, phone: req.body.phone }, { new: true }); if (!user) return res.status(404).send('The user with the given ID was not found.'); res.send(user); }; exports.eliminarUsuario = async (req, res) => { const user = await User.findByIdAndRemove(req.params.id); if (!user) return res.status(404).send('The user with the given ID was not found.'); res.send(user); }; exports.verUsuario = async (req, res) => { const user = await User.findById(req.params.id); if (!user) return res.status(404).send('The user with the given ID was not found.'); res.send(user); };
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; class BinaryCalculator extends React.Component { constructor(props) { super(); this.state = {bits: Array(+props.bits).fill(0)}; } handleClick(i) { const bits = this.state.bits.slice(); bits[i] = bits[i] == 0 ? 1 : 0; this.setState({bits:bits}); } render() { const clickers = []; for(let i = 0; i < +this.state.bits.length; i++) { clickers.push( <Bit onClick={() => {this.handleClick(i)}} value={this.state.bits[i]} /> ); } const result = parseInt(this.state.bits.reduce((acc, ele) => {return acc + ele}, ""), 2); return <div className="binaryCalculator">{ clickers }<Result value={result}/></div>; } } class Bit extends React.Component { constructor() { super(); this.state = {count: 0}; } render() { return <div onClick={() => {this.props.onClick()}}><h2>{this.props.value}</h2></div>; } handleClick() { this.setState({count: this.state.count + 1}); } } class Result extends React.Component { render() { return <div><h1>=&nbsp;&nbsp;&nbsp;{this.props.value}</h1></div>; } } ReactDOM.render( <BinaryCalculator bits="8" />, document.getElementById('root') );
angular.module('ram.touchspin', []) .directive('ramTouchSpin', ['$timeout', '$interval', '$document', '$locale', '$parse', function ($timeout, $interval, $document, $locale, $parse) { 'use strict'; var keyCodes = { left: 37, right: 39, up: 38, down: 40 }; var setScopeValues = function (scope, attrs) { if(attrs.min !== undefined){ scope.min = parseFloat(Number(attrs.min)); }else{ scope.min = undefined; } if(attrs.max !== undefined){ scope.max = parseFloat(Number(attrs.max)); }else{ scope.max = undefined; } scope.step = attrs.step || 1; scope.prefix = attrs.prefix || undefined; scope.postfix = attrs.postfix || undefined; scope.decimals = attrs.decimals || 0; scope.stepInterval = attrs.stepInterval || 100; scope.stepIntervalDelay = attrs.stepIntervalDelay || 500; scope.emptyStringNull = attrs.nullable || false; //used in toFloat as well, TODO: improve var localeDecimalSeparator; if($locale.NUMBER_FORMATS.DECIMAL_SEP === undefined){ //Be prepared for the case that variable name changes, this is not a public api //TODO: make sure this is in the public api (feature request: https://github.com/angular/angular.js/issues/13289) localeDecimalSeparator = '.'; } else{ localeDecimalSeparator = $locale.NUMBER_FORMATS.DECIMAL_SEP; } scope.decimalSep = attrs.decimalSep || localeDecimalSeparator; if (attrs.withKey === "false") { scope.withKey = false; } else { scope.withKey = true; } if (attrs.vertical === "false") { scope.verticalButtons = false; } else { scope.verticalButtons = true; } if (scope.decimalSep === ".") { scope.regex = /^-?(?:\d+|\d*\.(\d+)?)$/i; } else if (scope.decimalSep === ",") { scope.regex = /^-?(?:\d+|\d*\,(\d+)?)$/i; } else { //any decimal separator scope.regex = new RegExp("^-?(?:\\d+|\\d*" + scope.decimalSep + "(\\d+)?)$"); } }; var toFloat = function (value, scope) { if(value === "" && scope.emptyStringNull){ return null; } if (scope.decimalSep !== "." && (typeof value === "string" || value instanceof String)) { value = value.replace(scope.decimalSep, "."); } value = parseFloat(Number(value)); return value; } var toString = function (value, decimalSep) { if(value === null || value === undefined){ return ""; } if( typeof value === 'number'){ value = value.toString(); } value = value.replace('.', decimalSep); return value; } return { restrict: 'EA', scope: { disabled:'=?ngDisabled' }, require: '?ngModel', replace: true, link: function (scope, element, attrs, ngModelCtrl) { if(!ngModelCtrl){ throw Error("Missing ng-model attribute on ram-touch-spin element"); } var timeout, timer, clickStart; scope.focused = false; if(scope.disabled === undefined){ scope.disabled = false; } scope.valid = true; setScopeValues(scope, attrs); var orignalRender = ngModelCtrl.$render; var input = element.find('input'); var modelSetter = $parse(attrs['ngModel']).assign; ngModelCtrl.$render = function () { scope.val = toString( ngModelCtrl.$viewValue, scope.decimalSep); ngModelCtrl.$modelValue = ngModelCtrl.$viewValue; }; //TODO: make sure timers are deleted when element is destroyed var updateNgviewValue = function(val){ //consistency check, we should not have a string type value here if(typeof value === "string"){ throw new Error("value was of string type!"); } ngModelCtrl.$setViewValue(val); orignalRender(); ngModelCtrl.$setValidity('invalid', true); scope.valid = true; modelSetter(scope.$parent, ngModelCtrl.$viewValue); } //ngModel default value is NaN if(isNaN(ngModelCtrl.$viewValue)){ var initval = attrs.initval || (scope.emptyStringNull ? null : 0); if( attrs.initval){ updateNgviewValue( toFloat(initval, scope)); } scope.val = initval; } //handle nullable by adding a ngModelController parser if(attrs.nullable){ ngModelCtrl.$parsers.push(function(viewValue) { if(viewValue === "") { return null; } return viewValue; }); } //This additional parser is a fix for old browsers (Chrome 18) where we have a string value for a strange reason. ngModelCtrl.$parsers.push(function(viewValue) { if(typeof viewValue === "string"){ return toFloat(viewValue, scope); } return viewValue; }); scope.updateValue = function () { if (scope.val !== undefined) { //check regex first //TODO: move regex away from scope object if(scope.val === "" || scope.regex.test(scope.val)){ }else{ ngModelCtrl.$setValidity('invalid', false); scope.valid = false; orignalRender(); return; } //parse and update var value = toFloat(scope.val, scope); var outOfBounds = false if (scope.max != undefined && value > scope.max){ value = scope.max; outOfBounds = true; } else if (scope.min != undefined && value < scope.min) { value = scope.min; outOfBounds = true; } if(outOfBounds){ ngModelCtrl.$setValidity('invalid', false); scope.valid = false; orignalRender(); return; } updateNgviewValue(value); } } scope.increment = function () { var value = parseFloat(parseFloat(Number(ngModelCtrl.$viewValue)) + parseFloat(scope.step)).toFixed(scope.decimals); if (scope.max != undefined && value > scope.max) return; updateNgviewValue( toFloat(value, scope)); ngModelCtrl.$render(); }; scope.decrement = function () { var value = parseFloat(parseFloat(Number(ngModelCtrl.$viewValue)) - parseFloat(scope.step)).toFixed(scope.decimals); if (scope.min != undefined && value < scope.min) { value = parseFloat(scope.min).toFixed(scope.decimals); updateNgviewValue( toFloat(value, scope)); return; } updateNgviewValue( toFloat(value, scope)); ngModelCtrl.$render(); }; scope.startSpinUp = function () { scope.increment(); clickStart = Date.now(); timeout = $timeout(function() { timer = $interval(function() { scope.increment(); }, scope.stepInterval); }, scope.stepIntervalDelay); }; scope.startSpinDown = function () { scope.decrement(); clickStart = Date.now(); timeout = $timeout(function() { timer = $interval(function() { scope.decrement(); }, scope.stepInterval); }, scope.stepIntervalDelay); }; scope.stopSpin = function () { $timeout.cancel(timeout); $interval.cancel(timer); }; scope.focus = function () { scope.focused = true; } scope.blur = function () { scope.focused = false; } var $body = $document.find('body'); $body.bind('keydown', function (event) { if (!scope.withKey || !scope.focused) { return; } event = event || window.event; var which = event.which; if (which === keyCodes.up) { scope.increment(); event.preventDefault(); scope.$apply(); } else if (which === keyCodes.down) { scope.decrement(); event.preventDefault(); scope.$apply(); } }); }, template: '<div class="input-group bootstrap-touchspin" ng-class="{\'has-error\': !valid}">' + ' <span class="input-group-btn" ng-if="!verticalButtons">' + ' <button class="btn btn-default bootstrap-touchspin-down" ng-mousedown="startSpinDown()" ng-mouseup="stopSpin()" ng-disabled="disabled" tabindex="-1"><i class="fa fa-minus"></i></button>' + ' </span>' + ' <span class="input-group-addon bootstrap-touchspin-prefix" ng-show="prefix" ng-bind="prefix"></span>' + ' <input type="text" ng-model="val" class="form-control" ng-change="updateValue()" ng-blur="blur()" ng-focus="focus()" ng-disabled="disabled">' + ' <span class="input-group-addon bootstrap-touchspin-postfix" ng-show="postfix" ng-bind="postfix"></span>' + ' <span class="input-group-btn" ng-if="!verticalButtons">' + ' <button class="btn btn-default bootstrap-touchspin-down" ng-mousedown="startSpinUp()" ng-mouseup="stopSpin()" ng-disabled="disabled" tabindex="-1"><i class="fa fa-plus"></i></button>' + ' </span>' + ' <span class="input-group-btn-vertical" ng-if="verticalButtons">' + ' <button class="btn btn-default bootstrap-touchspin-up" type="button" ng-mousedown="startSpinUp()" ng-mouseup="stopSpin()" ng-disabled="disabled" tabindex="-1">' + ' <i class="glyphicon glyphicon-chevron-up"></i>' + ' </button>' + ' <button class="btn btn-default bootstrap-touchspin-down" type="button"ng-mousedown="startSpinDown()" ng-mouseup="stopSpin()" ng-disabled="disabled" tabindex="-1">' + ' <i class="glyphicon glyphicon-chevron-down"></i>' + ' </button>' + ' </span>' + '</div>' }; }]);
import test from 'ava'; import fs from 'fs'; import path from 'path'; import copyfiles from 'copyfiles'; import rimraf from 'rimraf'; // $FlowIgnore import spawn from 'cross-spawn'; const IMAGE_FILES = '/**/*.+(tiff|jpeg|jpg|gif|png|bmp)'; const WORKSPACE = 'test/__workspace__'; const RESOURCE = 'resource'; const SAMPLE_IMAGE = 'sample(cal).png'; const SAMPLE_DIFF_IMAGE = 'sample(cal).png'; const replaceReportPath = report => { Object.keys(report).forEach(key => { report[key] = typeof report[key] === 'string' ? report[key].replace(/\\/g, '/') : report[key].map(r => r.replace(/\\/g, '/')); }); return report; }; test.beforeEach(async t => { await new Promise(resolve => copyfiles([`${RESOURCE}${IMAGE_FILES}`, WORKSPACE], resolve)); await new Promise(resolve => copyfiles([`${RESOURCE}/reg.json`, WORKSPACE], resolve)); }); test.serial('should display default diff message', async t => { const stdout = await new Promise(async resolve => { const chunks = []; rimraf(`${WORKSPACE}/resource/expected`, () => { const p = spawn('./dist/cli.js', [ `${WORKSPACE}/resource/actual`, `${WORKSPACE}/resource/expected`, `${WORKSPACE}/diff`, '-E', ]); p.stdout.on('data', chunk => { chunks.push(Buffer.from(chunk)); }); p.on('close', () => { resolve(Buffer.concat(chunks).toString('utf8')); }); }); }); t.true(stdout.indexOf('Inspect your code changes, re-run with `-U` to update them') !== -1); }); test.serial.only('should display custom diff message', async t => { const stdout = await new Promise(async resolve => { const chunks = []; rimraf(`${WORKSPACE}/resource/expected`, () => { const p = spawn('./dist/cli.js', [ `${WORKSPACE}/resource/actual`, `${WORKSPACE}/resource/expected`, `${WORKSPACE}/diff`, '-E', '-D Custom diff message', ]); p.stdout.on('data', chunk => { chunks.push(Buffer.from(chunk)); }); p.on('close', () => { resolve(Buffer.concat(chunks).toString('utf8')); }); }); }); t.true(stdout.indexOf('Custom diff message') !== -1); }); test.serial('should display error message when passing only 1 argument', async t => { const stdout = await new Promise(resolve => { const p = spawn('./dist/cli.js', ['./sample/actual']); p.stdout.on('data', data => resolve(data)); p.stderr.on('data', data => console.error(data)); }); t.true(stdout.indexOf('please specify actual, expected and diff images directory') !== -1); }); test.serial('should display error message when passing only 2 argument', async t => { const stdout = await new Promise(resolve => { const p = spawn('./dist/cli.js', ['./sample/actual', './sample/expected']); p.stdout.on('data', data => resolve(data)); p.stderr.on('data', data => console.error(data)); }); t.true(stdout.indexOf('please specify actual, expected and diff images directory') !== -1); }); test.serial('should generate image diff with exit code 1', async t => { const code = await new Promise(resolve => { const p = spawn('./dist/cli.js', [ `${WORKSPACE}/resource/actual`, `${WORKSPACE}/resource/expected`, `${WORKSPACE}/diff`, ]); p.on('close', code => resolve(code)); }); t.true(code === 1); try { fs.readFileSync(`${WORKSPACE}/diff/${SAMPLE_DIFF_IMAGE}`); t.pass(); } catch (e) { console.log(e); t.fail(); } }); test.serial('should exit process without error when ignore change option set', async t => { const code = await new Promise(resolve => { const p = spawn('./dist/cli.js', [ `${WORKSPACE}/resource/actual`, `${WORKSPACE}/resource/expected`, `${WORKSPACE}/diff`, '-I', ]); p.on('close', code => resolve(code)); p.stderr.on('data', data => console.error(data)); p.on('error', e => { t.fail(); console.error(e); }); }); t.true(code === 0); }); test.serial('should exit with code 1 when extended error option set and file added', async t => { const code = await new Promise(async resolve => { rimraf(`${WORKSPACE}/resource/expected`, () => { const p = spawn('./dist/cli.js', [ `${WORKSPACE}/resource/actual`, `${WORKSPACE}/resource/expected`, `${WORKSPACE}/diff`, '-E', ]); p.on('close', code => resolve(code)); p.stderr.on('data', data => console.error(data)); }); }); t.true(code === 1); }); test.serial('should exit with code 1 when extended error option set and file deleted', async t => { const code = await new Promise(async resolve => { rimraf(`${WORKSPACE}/resource/actual`, () => { const p = spawn('./dist/cli.js', [ `${WORKSPACE}/resource/actual`, `${WORKSPACE}/resource/expected`, `${WORKSPACE}/diff`, '-E', ]); p.on('close', code => resolve(code)); p.stderr.on('data', data => console.error(data)); }); }); t.true(code === 1); }); test.serial('should generate report json to `./reg.json` when not specified dist path', async t => { await new Promise(resolve => { const p = spawn('./dist/cli.js', [ `${WORKSPACE}/resource/actual`, `${WORKSPACE}/resource/expected`, `${WORKSPACE}/diff`, ]); p.on('close', code => resolve(code)); p.stderr.on('data', data => console.error(data)); }); try { fs.readFileSync(`./reg.json`); t.pass(); } catch (e) { t.fail(); } }); test.serial('should generate report json to `${WORKSPACE}/dist/reg.json` when dist path specified', async t => { await new Promise(resolve => { const p = spawn('./dist/cli.js', [ `${WORKSPACE}/resource/actual`, `${WORKSPACE}/resource/expected`, `${WORKSPACE}/diff`, `-J`, `${WORKSPACE}/dist/reg.json`, ]); p.on('close', code => resolve(code)); p.stderr.on('data', data => console.error(data)); }); try { fs.readFileSync(`${WORKSPACE}/dist/reg.json`); t.pass(); } catch (e) { t.fail(); } }); test.serial('should generate report html to `${WORKSPACE}/dist/report.html` when `-R` option enabled', async t => { await new Promise(resolve => { const p = spawn('./dist/cli.js', [ `${WORKSPACE}/resource/actual`, `${WORKSPACE}/resource/expected`, `${WORKSPACE}/diff`, `-R`, `${WORKSPACE}/dist/report.html`, ]); p.on('close', code => resolve(code)); p.stderr.on('data', data => console.error(data)); }); try { fs.readFileSync(`${WORKSPACE}/dist/report.html`); t.pass(); } catch (e) { console.error(e); t.fail(); } }); test.serial( 'should generate worker js and wasm files under `${WORKSPACE}/dist` when `-R -X` option enabled', async t => { await new Promise(resolve => { const p = spawn('./dist/cli.js', [ `${WORKSPACE}/resource/actual`, `${WORKSPACE}/resource/expected`, `${WORKSPACE}/diff`, `-R`, `${WORKSPACE}/dist/report.html`, `-X`, 'client', ]); p.on('close', code => resolve(code)); p.stderr.on('data', data => console.error(data)); }); try { t.truthy(fs.existsSync(`${WORKSPACE}/dist/worker.js`)); t.truthy(fs.existsSync(`${WORKSPACE}/dist/detector.wasm`)); } catch (e) { console.error(e); t.fail(); } }, ); test.serial('should generate fail report', async t => { await new Promise(resolve => { const p = spawn('./dist/cli.js', [ `${WORKSPACE}/resource/actual`, `${WORKSPACE}/resource/expected`, `${WORKSPACE}/diff`, ]); p.on('close', code => resolve(code)); p.stderr.on('data', data => console.error(data)); }); try { const report = replaceReportPath(JSON.parse(fs.readFileSync(`./reg.json`, 'utf8'))); const expected = { actualItems: [`${SAMPLE_IMAGE}`], expectedItems: [`${SAMPLE_IMAGE}`], diffItems: [`${SAMPLE_DIFF_IMAGE}`], failedItems: [`${SAMPLE_IMAGE}`], newItems: [], deletedItems: [], passedItems: [], actualDir: `./${WORKSPACE}/resource/actual`, expectedDir: `./${WORKSPACE}/resource/expected`, diffDir: `./${WORKSPACE}/diff`, }; t.deepEqual(report, expected); } catch (e) { t.fail(); } }); test.serial('should generate fail report with -T 0.00', async t => { await new Promise(resolve => { const p = spawn('./dist/cli.js', [ `${WORKSPACE}/resource/actual`, `${WORKSPACE}/resource/expected`, `${WORKSPACE}/diff`, `-T`, '0.00', ]); p.on('close', code => resolve(code)); p.stderr.on('data', data => console.error(data)); }); try { const report = replaceReportPath(JSON.parse(fs.readFileSync(`./reg.json`, 'utf8'))); const expected = { actualItems: [`${SAMPLE_IMAGE}`], expectedItems: [`${SAMPLE_IMAGE}`], diffItems: [`${SAMPLE_DIFF_IMAGE}`], failedItems: [`${SAMPLE_IMAGE}`], newItems: [], deletedItems: [], passedItems: [], actualDir: `./${WORKSPACE}/resource/actual`, expectedDir: `./${WORKSPACE}/resource/expected`, diffDir: `./${WORKSPACE}/diff`, }; t.deepEqual(report, expected); } catch (e) { t.fail(); } }); test.serial('should not generate fail report with -T 1.00', async t => { await new Promise(resolve => { const p = spawn('./dist/cli.js', [ `${WORKSPACE}/resource/actual`, `${WORKSPACE}/resource/expected`, `${WORKSPACE}/diff`, `-T`, '1.00', ]); p.on('close', code => resolve(code)); p.stderr.on('data', data => console.error(data)); }); try { const report = replaceReportPath(JSON.parse(fs.readFileSync(`./reg.json`, 'utf8'))); const expected = { actualItems: [`${SAMPLE_IMAGE}`], expectedItems: [`${SAMPLE_IMAGE}`], diffItems: [], failedItems: [], newItems: [], deletedItems: [], passedItems: [`${SAMPLE_IMAGE}`], actualDir: `./${WORKSPACE}/resource/actual`, expectedDir: `./${WORKSPACE}/resource/expected`, diffDir: `./${WORKSPACE}/diff`, }; t.deepEqual(report, expected); } catch (e) { t.fail(); } }); test.serial('should generate fail report with -S 0', async t => { await new Promise(resolve => { const p = spawn('./dist/cli.js', [ `${WORKSPACE}/resource/actual`, `${WORKSPACE}/resource/expected`, `${WORKSPACE}/diff`, `-S`, '0', ]); p.on('close', code => resolve(code)); p.stderr.on('data', data => console.error(data)); }); try { const report = replaceReportPath(JSON.parse(fs.readFileSync(`./reg.json`, 'utf8'))); const expected = { actualItems: [`${SAMPLE_IMAGE}`], expectedItems: [`${SAMPLE_IMAGE}`], diffItems: [`${SAMPLE_DIFF_IMAGE}`], failedItems: [`${SAMPLE_IMAGE}`], newItems: [], deletedItems: [], passedItems: [], actualDir: `./${WORKSPACE}/resource/actual`, expectedDir: `./${WORKSPACE}/resource/expected`, diffDir: `./${WORKSPACE}/diff`, }; t.deepEqual(report, expected); } catch (e) { t.fail(); } }); test.serial('should not generate fail report with -S 10000000', async t => { await new Promise(resolve => { const p = spawn('./dist/cli.js', [ `${WORKSPACE}/resource/actual`, `${WORKSPACE}/resource/expected`, `${WORKSPACE}/diff`, `-S`, '100000000', ]); p.on('close', code => resolve(code)); p.stderr.on('data', data => console.error(data)); }); try { const report = replaceReportPath(JSON.parse(fs.readFileSync(`./reg.json`, 'utf8'))); const expected = { actualItems: [`${SAMPLE_IMAGE}`], expectedItems: [`${SAMPLE_IMAGE}`], diffItems: [], failedItems: [], newItems: [], deletedItems: [], passedItems: [`${SAMPLE_IMAGE}`], actualDir: `./${WORKSPACE}/resource/actual`, expectedDir: `./${WORKSPACE}/resource/expected`, diffDir: `./${WORKSPACE}/diff`, }; t.deepEqual(report, expected); } catch (e) { t.fail(); } }); test.serial('should update images with `-U` option', async t => { let code = await new Promise(resolve => { const p = spawn('./dist/cli.js', [ `${WORKSPACE}/resource/actual`, `${WORKSPACE}/resource/expected`, `${WORKSPACE}/diff`, '-U', ]); p.on('close', code => resolve(code)); // p.stdout.on('data', data => console.log(data.toString())); p.stderr.on('data', data => console.error(data)); }); t.true(code === 0); const report = replaceReportPath(JSON.parse(fs.readFileSync(`./reg.json`, 'utf8'))); const expected = { actualItems: [`${SAMPLE_IMAGE}`], expectedItems: [`${SAMPLE_IMAGE}`], diffItems: [`${SAMPLE_DIFF_IMAGE}`], failedItems: [`${SAMPLE_IMAGE}`], newItems: [], deletedItems: [], passedItems: [], actualDir: `./${WORKSPACE}/resource/actual`, expectedDir: `./${WORKSPACE}/resource/expected`, diffDir: `./${WORKSPACE}/diff`, }; t.deepEqual(report, expected); }); test.serial('should delete from /expected when they are missing from /actual with `-U` option', async t => { const code = await new Promise(resolve => { rimraf(`${WORKSPACE}/resource/actual/${SAMPLE_IMAGE}`, () => { const p = spawn('./dist/cli.js', [ `${WORKSPACE}/resource/actual`, `${WORKSPACE}/resource/expected`, `${WORKSPACE}/diff`, '-U', ]); p.on('close', code => resolve(code)); // p.stdout.on('data', data => console.log(data.toString())); p.stderr.on('data', data => console.error(data)); }); }); t.true(code === 0); const report = replaceReportPath(JSON.parse(fs.readFileSync(`./reg.json`, 'utf8'))); const expected = { actualItems: [], expectedItems: [], diffItems: [], failedItems: [], newItems: [], deletedItems: [`${SAMPLE_IMAGE}`], passedItems: [], actualDir: `./${WORKSPACE}/resource/actual`, expectedDir: `./${WORKSPACE}/resource/expected`, diffDir: `./${WORKSPACE}/diff`, }; t.deepEqual(report, expected); const wasDeleted = !fs.existsSync(`${WORKSPACE}/resource/expected/${SAMPLE_IMAGE}`); t.true(wasDeleted, `File ${SAMPLE_IMAGE} was not deleted from /expected`); }); test.serial('should generate success report', async t => { const stdout = await new Promise(resolve => { const p = spawn('./dist/cli.js', [ `${WORKSPACE}/resource/expected`, `${WORKSPACE}/resource/expected`, `${WORKSPACE}/diff`, ]); p.on('close', code => resolve(code)); p.stderr.on('data', data => console.error(data)); }); try { const report = replaceReportPath(JSON.parse(fs.readFileSync(`./reg.json`, 'utf8'))); const expected = { actualItems: [`${SAMPLE_IMAGE}`], expectedItems: [`${SAMPLE_IMAGE}`], diffItems: [], failedItems: [], newItems: [], deletedItems: [], passedItems: [`${SAMPLE_IMAGE}`], actualDir: `./${WORKSPACE}/resource/expected`, expectedDir: `./${WORKSPACE}/resource/expected`, diffDir: `./${WORKSPACE}/diff`, }; t.deepEqual(report, expected); } catch (e) { t.fail(); } }); test.serial('should generate newItem report', async t => { const stdout = await new Promise(async resolve => { rimraf(`${WORKSPACE}/resource/expected`, () => { const p = spawn('./dist/cli.js', [ `${WORKSPACE}/resource/actual`, `${WORKSPACE}/resource/expected`, `${WORKSPACE}/diff`, ]); p.on('close', code => resolve(code)); p.stderr.on('data', data => console.error(data)); }); }); try { const report = replaceReportPath(JSON.parse(fs.readFileSync(`./reg.json`, 'utf8'))); const expected = { actualItems: [`${SAMPLE_IMAGE}`], expectedItems: [], diffItems: [], failedItems: [], newItems: [`${SAMPLE_IMAGE}`], deletedItems: [], passedItems: [], actualDir: `./${WORKSPACE}/resource/actual`, expectedDir: `./${WORKSPACE}/resource/expected`, diffDir: `./${WORKSPACE}/diff`, }; t.deepEqual(report, expected); } catch (e) { t.fail(); } }); test.serial('should generate deletedItem report', async t => { const stdout = await new Promise(async resolve => { rimraf(`${WORKSPACE}/resource/actual`, () => { const p = spawn('./dist/cli.js', [ `${WORKSPACE}/resource/actual`, `${WORKSPACE}/resource/expected`, `${WORKSPACE}/diff`, ]); p.on('close', code => resolve(code)); p.stderr.on('data', data => console.error(data)); }); }); try { const report = replaceReportPath(JSON.parse(fs.readFileSync(`./reg.json`, 'utf8'))); const expected = { actualItems: [], expectedItems: [`${SAMPLE_IMAGE}`], diffItems: [], failedItems: [], newItems: [], deletedItems: [`${SAMPLE_IMAGE}`], passedItems: [], actualDir: `./${WORKSPACE}/resource/actual`, expectedDir: `./${WORKSPACE}/resource/expected`, diffDir: `./${WORKSPACE}/diff`, }; t.deepEqual(report, expected); } catch (e) { t.fail(); } }); test.serial('should generate report from json', async t => { await new Promise((resolve, reject) => { const p = spawn('./dist/cli.js', [`-F`, `${WORKSPACE}/resource/reg.json`, `-R`, `./from-json.html`]); p.on('close', code => resolve(code)); p.stderr.on('data', data => reject(data)); }); try { const report = fs.readFileSync(`./from-json.html`); t.true(!!report); } catch (e) { console.log(e); t.fail(); } }); test.serial('perf', async t => { const copy = (s, d, done) => { const r = fs.createReadStream(s); const w = fs.createWriteStream(d); r.pipe(w); w.on('close', ex => { done(); }); }; for (let i = 0; i < 100; i++) { await Promise.all([ new Promise(resolve => copy(`${WORKSPACE}/resource/actual/sample(cal).png`, `${WORKSPACE}/resource/actual/sample${i}.png`, resolve), ), new Promise(resolve => copy( `${WORKSPACE}/resource/expected/sample(cal).png`, `${WORKSPACE}/resource/expected/sample${i}.png`, resolve, ), ), ]); } console.time('100images'); await new Promise(resolve => { const p = spawn( './dist/cli.js', [`${WORKSPACE}/resource/actual`, `${WORKSPACE}/resource/expected`, `${WORKSPACE}/diff`], { cwd: path.resolve(__dirname, '../') }, ); p.on('close', code => resolve(code)); // p.stdout.on('data', data => console.log(data)); p.stderr.on('data', data => { console.error(data.toString()); }); }); console.timeEnd('100images'); t.pass(); }); test.afterEach.always(async t => { await new Promise(done => rimraf(`${WORKSPACE}${IMAGE_FILES}`, done)); await new Promise(done => rimraf(`./reg.json`, done)); });
'use strict' // Allow 10 mins (600000ms) from posting to editing const UPDATABLE_TIME = 600000 window.onload = function() { getPosts(); } var allPostsDiv = document.getElementById('posts'); function getPosts() { fetch('http://localhost:3000/posts_api.json').then(function(res) { res.json().then(function(json) { let postArray = json; renderPosts(postArray); }); }); } document.getElementById('Js-Send').addEventListener("click", function(event) { if (document.getElementById('post_image').files.length === 0) { event.preventDefault(); let captionField = document.getElementById('postcaption') if (confirm('Send caption without a picture?')) { let caption = captionField.value; createPostWithoutImage(caption); captionField.value = ""; } } captionField.value = ""; }); function createPostWithoutImage(caption) { fetch('http://localhost:3000/new_post_api', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ "post": { "caption": `${caption}` } }) }).then(function(res) { res.json().then(function(post) { renderIndividualPost(post) }) }) } function renderPosts(posts_array) { allPostsDiv.innerHTML = ""; posts_array.forEach(function(post) { renderIndividualPost(post); }); } function renderIndividualPost(post) { let postDiv = document.createElement('div'); postDiv.id = post.id; postDiv.className = "each-post"; allPostsDiv.prepend(postDiv); addPostDetails(post, postDiv); addPostImageHTML(post, postDiv); postCaption(post, postDiv); if (isCurrentUser(post.user.username)) { addEditAndDeleteButtons(post, postDiv); } } function addPostDetails(post, postDiv) { let postDetailsDiv = document.createElement('div'); postDetailsDiv.className = "post-details"; postDetailsDiv.innerHTML = `<h4 class="post-username"> ${post.user.username} </h4> <h5 class="post-timestamp"> ${post.created_at} </h5>`; postDiv.appendChild(postDetailsDiv); } function addPostImageHTML(post, postDiv) { let imageHTML if (post.image_url) { imageHTML = `<div class="image"> <img src="http://localhost:3000${post.image_url}"> </div>` } else { imageHTML = `<div class="image">no picture this time!</div>` } postDiv.innerHTML += imageHTML; } function postCaption(post, postDiv) { if (post.created_at === post.updated_at) { var postCaptionHTML = `<div class="post-caption" id="caption-${post.id}"><p>${post.caption}</p></div>` } else { var postCaptionHTML = `<div class="post-caption" id="caption-${post.id}"><p>${post.caption} <em>(edited)</em></p></div>` } postDiv.innerHTML += postCaptionHTML; } function addEditAndDeleteButtons(post, postDiv) { let userButtonsDiv = document.createElement('div'); userButtonsDiv.className = "edit-del-links"; postDiv.appendChild(userButtonsDiv); addDeleteButton(post, userButtonsDiv); if (isUpdatable(post)) { addEditButton(post, userButtonsDiv); } } function addDeleteButton(post, div) { let deleteButton = document.createElement('button'); deleteButton.className = "delete-button"; deleteButton.id = `delete-post-${post.id}`; deleteButton.innerHTML = `<i class="far fa-trash-alt"></i>`; div.appendChild(deleteButton); deleteButton.addEventListener("click", function() { if (confirm("Are you sure you want to delete this post?")) { deletePost(post.id); } }); } function addEditButton(post, div) { let editButton = document.createElement('button'); editButton.className = "edit-button" editButton.id = `edit-post-${post.id}`; editButton.innerHTML = `<i class="fas fa-pencil-alt"></i>` div.appendChild(editButton); editButton.addEventListener("click", function() { editPost(post, editButton); }); setTimeout(function() { editButton.remove() }, UPDATABLE_TIME - (Date.now() - Date.parse(post.created_at))) } function editPost(post, editButton) { let captionArea = document.getElementById(`caption-${post.id}`) captionArea.innerHTML = `<textarea type="text" id="test-edit-input" class="caption" />` document.getElementById(`test-edit-input`).value = post.caption let updateButton = document.createElement('INPUT') updateButton.setAttribute("type", "submit") updateButton.setAttribute("value", "Update") editButton.after(updateButton); editButton.remove(); updateButton.addEventListener("click", function(event) { event.preventDefault(); updatePost(post.id); updateButton.after(editButton); updateButton.remove(); }) } function deletePost(id) { fetch(`http://localhost:3000/posts/${id}`, { method: 'DELETE' }).then(function() { getPosts(); }); } function updatePost(id) { let updatedCaption = document.getElementById('test-edit-input').value; fetch(`http://localhost:3000/posts/${id}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ "post" : { "caption" : `${updatedCaption}`} }) }).then(function() { document.getElementById(`caption-${id}`).innerHTML = `<p>${updatedCaption} <em>(edited)</em>` }) } function isCurrentUser(username) { return document.getElementById('current-user').innerHTML === username } function isUpdatable(post) { return Date.now() - Date.parse(post.created_at) < UPDATABLE_TIME }
const formidable = require("formidable"); exports.formparser = (req) => new Promise(function (resolve, reject) { const form = new formidable.IncomingForm({ keepExtensions: true }); form.parse(req, function (err, fields, files) { if (err) return reject(err); resolve({ fields, files }); }); });
({ constants : { 'MAX_FILE_SIZE': 25000000,//4500000 'CHUNK_SIZE': 950000, //'PRIMARY_CONTACT_IMAGE': 'Primary Contact Image', //'PRIMARY_CONTACT_IMAGE_ID': 'uploaded_contact_image', 'INSURANCE_ID': 'insurance_att', 'LICENSE_ID': 'license_att', 'CERTIFICATION_ID': 'certification_att', 'TAX_ID': 'tax_att', 'OTHER_ID': 'other_att', 'NEW_ATTACHEMNT': 'New file selected' }, /** * Adding a file to a list of files for future deletion */ addFileToDelete: function (component, fileID) { var fileIds = component.get('v.filesToDelete'); if (!fileIds) { fileIds = []; } fileIds.push(fileID); component.set('v.filesToDelete', fileIds); }, prepareAllInformation : function(component) { var action = component.get("c.getAllInfoWrapper"); action.setParams({ applicationId: component.get("v.applicationId"), tradeAllyId : component.get("v.tradeAllyId") }); action.setCallback(this, function(response) { var state = response.getState(); if (state === "SUCCESS") { var allInfo = response.getReturnValue(); component.set( "v.appNotExists", ( allInfo.appNotExists || ( component.get("v.tradeAllyId") && allInfo.isCommunityUser) ) ); component.set("v.isValidUser", allInfo.isValidUser); component.set("v.allInfoWrapper", allInfo); // initialize uploaded files and the number of files. For phase 1, each object can have one file only. // In phase 2, this may change and this initialization will have to be refactored. if (allInfo.insuranceFiles) { component.set('v.insuranceFileIds', Object.values(allInfo.insuranceFiles)); component.set('v.insuranceCount', Object.values(allInfo.insuranceFiles).length); } if (allInfo.licenseFiles) { component.set('v.licenseFileIds', Object.values(allInfo.licenseFiles)); component.set('v.licenseCount', Object.values(allInfo.licenseFiles).length); } if (allInfo.certificationFiles) { component.set('v.certificationFileIds', Object.values(allInfo.certificationFiles)); component.set('v.certificationCount', Object.values(allInfo.certificationFiles).length); } if (allInfo.taxFiles) { component.set('v.taxFileIds', Object.values(allInfo.taxFiles)); component.set('v.taxCount', Object.values(allInfo.taxFiles).length); } if (allInfo.otherFiles) { component.set('v.otherFileIds', Object.values(allInfo.otherFiles)); component.set('v.otherCount', Object.values(allInfo.otherFiles).length); } } else if (state === "INCOMPLETE") { this.showToast(component, 'error', $A.get("$Label.c.Status_incomplete"), 'Error'); } else if (state === "ERROR") { var errors = response.getError(); if (errors) { if (errors.length > 0) { for (var i = 0; i < errors.length; i++) { if (errors[0].pageErrors) { if (errors[0].pageErrors.length > 0) { for (var j = 0; j < errors[i].pageErrors.length; j++) { this.showToast(component, 'error', 'Internal server error: ' + errors[i].pageErrors[j].message, 'Error'); } } } this.showToast(component, 'error', errors[i].message, 'Error'); } } } else { this.showToast(component, 'error', $A.get("$Label.c.Internal_server_error"), 'Error'); } } this.hideSpinner(component); }); $A.enqueueAction(action); }, reviewWrappedFields : function(wrappedFields) { var isValid = true; for (var i = 0; i < wrappedFields.length; i++) { if (wrappedFields[i].isValid == false) { isValid = false; break; } if ( wrappedFields[i].required == true && ( ( ( wrappedFields[i].type == 'REFERENCE' || wrappedFields[i].type == 'STRING' || wrappedFields[i].type == 'EMAIL' || wrappedFields[i].type == 'PHONE' || wrappedFields[i].type == 'URL' || wrappedFields[i].type == 'TEXTAREA' || wrappedFields[i].type == 'RICHTEXTAREA' || wrappedFields[i].type == 'PICKLIST' || wrappedFields[i].type == 'COMBOBOX' ) && !wrappedFields[i].value ) || ( wrappedFields[i].type == 'DATETIME' && !wrappedFields[i].valueDateTime ) || ( wrappedFields[i].type == 'DATE' && !wrappedFields[i].valueDate ) || ( wrappedFields[i].type == 'BOOLEAN' && ( !wrappedFields[i].valueBoolean || wrappedFields[i].valueBoolean == false ) ) || ( ( wrappedFields[i].type == 'INTEGER' || wrappedFields[i].type == 'CURRENCY' || wrappedFields[i].type == 'DOUBLE' || wrappedFields[i].type == 'PERCENT' ) && !wrappedFields[i].valueNumber ) ) ) { isValid = false; break; } } return isValid; }, reviewWrappedListOfFields : function(wrappedListOfFields) { var isValid = true; for (var m = 0; m < wrappedListOfFields.length; m++) { isValid = this.reviewWrappedFields(wrappedListOfFields[m]); if (isValid == false) { break; } } return isValid; }, validateUpdatedFields : function(allInfoWrapper,sectionNumber) { var isValid = true; if (sectionNumber === 1) { isValid = this.reviewWrappedFields(allInfoWrapper.listOfTradeAllyFields); } else if (sectionNumber === 2) { isValid = this.reviewWrappedFields(allInfoWrapper.listOfContactFields); if (isValid) { isValid = this.reviewWrappedFields(allInfoWrapper.listOfTradeAllyBACIFields); } } else if (sectionNumber === 3) { isValid = this.reviewWrappedFields(allInfoWrapper.listOfTradeAllyPPFields); } else if (sectionNumber === 4) { isValid = this.reviewWrappedListOfFields(allInfoWrapper.listOfTradeAllyReferencesFields); } else if (sectionNumber === 5) { isValid = this.reviewWrappedListOfFields(allInfoWrapper.listOfTradeAllyTradeReferencesFields); } else if (sectionNumber === 6) { isValid = this.reviewWrappedListOfFields(allInfoWrapper.listOfInsurancesFields); } else if (sectionNumber === 7) { isValid = this.reviewWrappedListOfFields(allInfoWrapper.listOfLicensesFields); } else if (sectionNumber === 8) { isValid = this.reviewWrappedListOfFields(allInfoWrapper.listOfCertificationsFields); } else if (sectionNumber === 9) { isValid = this.reviewWrappedListOfFields(allInfoWrapper.listOfTaxFields); } else if (sectionNumber === 10) { isValid = this.reviewWrappedListOfFields(allInfoWrapper.listOfOtherFields); } else if (sectionNumber === 11) { isValid = this.reviewWrappedListOfFields(allInfoWrapper.listOfTradeAllyDemographicFields); } else if (sectionNumber === 12) { isValid = this.reviewWrappedFields(allInfoWrapper.listOfApplicationFields); } return isValid; }, reviewCRForNumberOfRecords : function(wrappedFields) { var numberOfRecords = 0; if (wrappedFields && wrappedFields.length > 0 && wrappedFields[0].recordId) { numberOfRecords = 1; } return numberOfRecords; }, reviewCRListForNumberOfRecords : function(wrappedListOfFields,minimumNumber) { var numberOfRecords = 0; if (wrappedListOfFields.length) { for (var h = 0; h < wrappedListOfFields.length; h++) { numberOfRecords += this.reviewCRForNumberOfRecords(wrappedListOfFields[h]); } } return (numberOfRecords >= minimumNumber); }, checkNumberOfCR : function(allInfoWrapper) { var enoughCR = true; if(allInfoWrapper.tab4Visible == true) { enoughCR = this.reviewCRListForNumberOfRecords(allInfoWrapper.listOfTradeAllyReferencesFields, allInfoWrapper.numberOfCR); } if (enoughCR && allInfoWrapper.tab5Visible == true) { enoughCR = this.reviewCRListForNumberOfRecords(allInfoWrapper.listOfTradeAllyTradeReferencesFields, allInfoWrapper.numberOfTR); } return enoughCR; }, checkNumberOfInsurances : function(component, allInfoWrapper) { var enoughInsurances = true; if(allInfoWrapper.tab6Visible == true) { // enoughInsurances = this.reviewCRListForNumberOfRecords(allInfoWrapper.listOfInsurancesFields, allInfoWrapper.numberOfInsurances); enoughInsurances = component.get('v.insuranceCount') >= allInfoWrapper.numberOfInsurances; } return enoughInsurances; }, checkNumberOfLicenses : function(component, allInfoWrapper) { var enoughLicenses = true; if(allInfoWrapper.tab7Visible == true) { // enoughLicenses = this.reviewCRListForNumberOfRecords(allInfoWrapper.listOfLicensesFields, allInfoWrapper.numberOfLicenses); enoughLicenses = component.get('v.licenseCount') >= allInfoWrapper.numberOfLicenses; } return enoughLicenses; }, checkNumberOfCertifications : function(component, allInfoWrapper) { var enoughCertifications = true; if(allInfoWrapper.tab8Visible == true) { // enoughCertifications = this.reviewCRListForNumberOfRecords(allInfoWrapper.listOfCertificationsFields, allInfoWrapper.numberOfCertifications); enoughCertifications = component.get('v.certificationCount') >= allInfoWrapper.numberOfCertifications; } return enoughCertifications; }, checkNumberOfDocs : function(component, allInfoWrapper) { var enoughDocs = true; if(allInfoWrapper.tab9Visible == true) { // enoughDocs = this.reviewCRListForNumberOfRecords(allInfoWrapper.listOfTaxFields, allInfoWrapper.numberOfTaxDocs); enoughDocs = component.get('v.taxCount') >= allInfoWrapper.numberOfTaxDocs; } if (enoughDocs && allInfoWrapper.tab10Visible == true) { // enoughDocs = this.reviewCRListForNumberOfRecords(allInfoWrapper.listOfOtherFields, allInfoWrapper.numberOfOtherDocs); enoughDocs = component.get('v.otherCount') >= allInfoWrapper.numberOfOtherDocs; } return enoughDocs; }, savePartOfChanges : function(component, event, sectionNumber) { var allInfoWrapper = component.get("v.allInfoWrapper"); var validUpdate = this.validateUpdatedFields(allInfoWrapper,parseInt(sectionNumber,10)); if (validUpdate) { // console.log('sectionNumber ',sectionNumber); var enoughCR = true; var enoughDocs = true; var enoughInsurances = true; var enoughLicenses = true; var enoughCertifications = true; // final step validation if (sectionNumber === '12') { enoughCR = this.checkNumberOfCR(allInfoWrapper); enoughDocs = this.checkNumberOfDocs(component, allInfoWrapper); enoughInsurances = this.checkNumberOfInsurances(component, allInfoWrapper); enoughLicenses = this.checkNumberOfLicenses(component, allInfoWrapper); enoughCertifications = this.checkNumberOfCertifications(component, allInfoWrapper); } if (enoughCR && enoughDocs && enoughInsurances && enoughLicenses && enoughCertifications) { // console.log(JSON.parse(JSON.stringify(allInfoWrapper))); var action = component.get("c.savePartOfInfo"); action.setParams({ informationString: JSON.stringify(allInfoWrapper), sectionNumber: sectionNumber }); action.setCallback(this, function(response) { var state = response.getState(); if (state === "SUCCESS") { // logic to show pop up window for subscription if (!component.get('v.allInfoWrapper.isSubscribed')) { var index = component.get('v.activeTab'); if (index === '12') { this.createSubscriptionPopUp(component); } } var listOfIds = response.getReturnValue(); if (sectionNumber === '12') { if (listOfIds.length) { component.set('v.isApplicationSubmitted', true); } this.hideSpinner(component); } else if (listOfIds !== null && listOfIds.length > 0) { if (sectionNumber === '6') { this.cleanupInsuranceFileUpload(component, listOfIds); } else if (sectionNumber === '7') { this.cleanupLicenseFileUpload(component, listOfIds); //the list of IDs are the list of objects, such as insurance, cert, license, tax, other doc ID, etc. } else if (sectionNumber === '8') { this.cleanupCertificationFileUpload(component, listOfIds); } else if (sectionNumber === '9') { this.cleanupTaxFileUpload(component, listOfIds); } else if (sectionNumber === '10') { this.cleanupOtherFileUpload(component, listOfIds); } this.goNextTab(component, event); } else { this.resetUpdatedFields(component,parseInt(sectionNumber,10),event); } // TODO: removing this condition check will remove the blocking spinner... if (sectionNumber !== '4' && sectionNumber !== '5' && sectionNumber !== '6' && sectionNumber !== '7' && sectionNumber !== '8' && sectionNumber !== '9' && sectionNumber !== '10') { //logic to switch on next tab this.goNextTab(component, event); //If all info was saved, the application will be submitted and the success window will be displayed this.showToast(component, 'success', 'Changes saved successfully', 'Success'); } this.hideSpinner(component); } else if (state === "INCOMPLETE") { this.showToast(component, 'error', $A.get("$Label.c.Status_incomplete"), 'Error'); this.hideSpinner(component); } else if (state === "ERROR") { var errors = response.getError(); if (errors) { if (errors.length > 0) { for (var i = 0; i < errors.length; i++) { if (errors[0].pageErrors) { if (errors[0].pageErrors.length > 0) { for (var j = 0; j < errors[i].pageErrors.length; j++) { this.showToast(component, 'error', 'Internal server error: ' + errors[i].pageErrors[j].message, 'Error'); } } } this.showToast(component, 'error', errors[i].message, 'Error'); } } } else { this.showToast(component, 'error', $A.get("$Label.c.Internal_server_error"), 'Error'); } this.hideSpinner(component); } }); $A.enqueueAction(action); } else { if(!enoughCR) this.showToast(component, 'error', $A.get("$Label.c.Minimum_References"), 'Error'); if(!enoughInsurances) this.showToast(component, 'error', $A.get("$Label.c.Minimum_Insurances"), 'Error'); if(!enoughLicenses) this.showToast(component, 'error', $A.get("$Label.c.Minimum_Licenses"), 'Error'); if(!enoughCertifications) this.showToast(component, 'error', $A.get("$Label.c.Minimum_Certifications"), 'Error'); if(!enoughDocs) this.showToast(component, 'error', $A.get("$Label.c.Minimum_Docs"), 'Error'); } } else { this.showToast(component, 'error', $A.get("$Label.c.Valid_Data_and_Required_Fields"), 'Error'); } }, /** * cleanupFileUpload performs following tasks: * 1. update the corresponding sections' files with a list of files IDs * 2. disable the upload button once the file is uploaded * 3. if the user is editing an existing application, uploading a new file will replace the existing file by index */ cleanupFileUpload: function (component, event, section) { var uploadButtonID = event.getSource().get('v.id'); var index = parseInt(uploadButtonID.replace(section + "_upload_btn_", "")); var files = event.getParam('files'); var fileIdsAttr = 'v.' + section + 'FileIds'; var fileIds = component.get(fileIdsAttr); if (!fileIds) { fileIds = []; } var filesToDelete = component.get('v.filesToDelete'); if (!filesToDelete) { filesToDelete = []; } files.forEach(function(file) { if (index + 1 > fileIds.length) { fileIds.push(file.documentId); } else { var currentDocId = fileIds[index]; fileIds[index] = (file.documentId); filesToDelete.push(currentDocId); } }); component.set(fileIdsAttr, fileIds); component.set('v.filesToDelete', filesToDelete); event.getSource().set('v.disabled', true); }, /** * DeleteFilePromise returns a promise that can be resolved. True means records were deleted successfully, false means * failure. */ deleteFilesPromise: function(component) { var action = component.get('c.serverDeleteFilesByIDs'); var fileIDs = component.get('v.filesToDelete'); action.setParams({ fileIds: fileIDs }); return new Promise(function(resolve, reject) { action.setCallback(this, function(response) { var state = response.getState(); if (state === 'SUCCESS') { component.set('v.filesToDelete', []); // once the file is deleted, reset the queue. resolve(response.getReturnValue()); } else if (state === 'ERROR') { reject(response.getError()[0]); } }); $A.enqueueAction(action); }); }, /** * saveObjectAndFilesPromise */ saveObjectsAndFilesPromise: function(component, objectType, objectIDs) { var objectname = objectType; // the original object name value: insurance, certification, license, tax, and other var objectName = objectType.charAt(0).toUpperCase() + objectType.slice(1); // Insurance, Certification, License, Tax, and Other var files = component.get('v.' + objectname + 'FileIds'); var objectField = objectname + 'Ids'; var action = component.get('c.save' + objectName + 'AndFiles'); var params = { appId: component.get('v.allInfoWrapper.applicationId'), fileIds: files }; params[objectField] = objectIDs; action.setParams(params); return new Promise(function(resolve, reject) { action.setCallback(this, function(response){ var state = response.getState(); if (state === 'SUCCESS') { // when the file and update objects are successfully stored in Salesforce, update the client-side's data (count of objects) // The count of object will be used for checking if the required number of files are included in the application during application submit (tab 12) // This part will likely be refactored to accommondate changes in phase 2 var countAttr = 'v.' + objectname + 'Count'; component.set(countAttr, objectIDs.length); resolve(response.getReturnValue()); } else if (state === 'ERROR') { reject(response.getError()[0]); } }); $A.enqueueAction(action); }); }, /** * cleanupLicenseFiles, including: * 1) create license object and associate them with this application * 2) rename those files with a prefix */ cleanupLicenseFileUpload: function(component, objectIDs) { var filesToDelete = component.get('v.filesToDelete'); Promise.all([ this.saveObjectsAndFilesPromise(component, 'license', objectIDs), this.deleteFilesPromise(component) ]).then(function(results){ // if results[0] is false, then an error occurred in the back end // if results[1] is false, then an error occurred in the back end }).catch(function(err){ }); }, cleanupInsuranceFileUpload: function(component, objectIDs) { var filesToDelete = component.get('v.filesToDelete'); Promise.all([ this.saveObjectsAndFilesPromise(component, 'insurance', objectIDs), this.deleteFilesPromise(component) ]).then(function(results){ // if results[0] is false, then an error occurred in the back end // if results[1] is false, then an error occurred in the back end }).catch(function(err){ }); }, cleanupCertificationFileUpload: function(component, objectIDs) { var filesToDelete = component.get('v.filesToDelete'); Promise.all([ this.saveObjectsAndFilesPromise(component, 'certification', objectIDs), this.deleteFilesPromise(component) ]).then(function(results){ // if results[0] is false, then an error occurred in the back end // if results[1] is false, then an error occurred in the back end }).catch(function(err){ }); }, cleanupTaxFileUpload: function (component, objectIDs) { var filesToDelete = component.get('v.filesToDelete'); Promise.all([ this.saveObjectsAndFilesPromise(component, 'tax', objectIDs), this.deleteFilesPromise(component) ]).then(function(results){ // if results[0] is false, then an error occurred in the back end // if results[1] is false, then an error occurred in the back end }).catch(function(err){ }); }, cleanupOtherFileUpload: function(component, objectIDs) { var filesToDelete = component.get('v.filesToDelete'); Promise.all([ this.saveObjectsAndFilesPromise(component, 'other', objectIDs), this.deleteFilesPromise(component) ]).then(function(results){ // if results[0] is false, then an error occurred in the back end // if results[1] is false, then an error occurred in the back end }).catch(function(err){ }); }, resetUpdatedFields : function(component,sectionNumber,event) { if ( sectionNumber === 4 || sectionNumber === 5 || sectionNumber === 6 || sectionNumber === 7 || sectionNumber === 8 || sectionNumber === 9 || sectionNumber === 10 ) { this.loadPartOfData(component,sectionNumber,event); } else { var allInfoWrapper = component.get("v.allInfoWrapper"); if (sectionNumber === 1) { for (var i = 0; i < allInfoWrapper.listOfTradeAllyFields.length; i++) { allInfoWrapper.listOfTradeAllyFields[i].wasUpdated = false; } } else if (sectionNumber === 2) { for (i = 0; i < allInfoWrapper.listOfContactFields.length; i++) { allInfoWrapper.listOfContactFields[i].wasUpdated = false; } for (i = 0; i < allInfoWrapper.listOfTradeAllyBACIFields.length; i++) { allInfoWrapper.listOfTradeAllyBACIFields[i].wasUpdated = false; } } else if (sectionNumber === 3) { for (i = 0; i < allInfoWrapper.listOfTradeAllyPPFields.length; i++) { allInfoWrapper.listOfTradeAllyPPFields[i].wasUpdated = false; } } else if (sectionNumber === 11) { for (i = 0; i < allInfoWrapper.listOfTradeAllyDemographicFields.length; i++) { allInfoWrapper.listOfTradeAllyDemographicFields[i].wasUpdated = false; } } component.set('v.allInfoWrapper', allInfoWrapper); this.hideSpinner(component); } }, loadPartOfData : function(component,sectionNumber,event) { var action = component.get("c.getPartOfData"); //console.log('sectionNumber ',sectionNumber); action.setParams({ applicationId : component.get("v.applicationId"), sectionNumber : sectionNumber }); action.setCallback(this, function(response) { var state = response.getState(); if (state === "SUCCESS") { var tempListOfFields = response.getReturnValue(); //console.log('tempListOfFields ',tempListOfFields); //console.log('sectionNumber ',sectionNumber); var enoughCR = true; var allInfoWrapper = component.get("v.allInfoWrapper"); if (sectionNumber === 4) { allInfoWrapper.listOfTradeAllyReferencesFields = tempListOfFields; allInfoWrapper.listOfTradeAllyReferencesIdsToDelete = []; enoughCR = this.reviewCRListForNumberOfRecords(allInfoWrapper.listOfTradeAllyReferencesFields,allInfoWrapper.numberOfCR); } else if (sectionNumber === 5) { allInfoWrapper.listOfTradeAllyTradeReferencesFields = tempListOfFields; allInfoWrapper.listOfTradeAllyCustomReferencesIdsToDelete = []; enoughCR = this.reviewCRListForNumberOfRecords(allInfoWrapper.listOfTradeAllyTradeReferencesFields,allInfoWrapper.numberOfTR); } else if (sectionNumber === 6) { allInfoWrapper.listOfInsurancesFields = tempListOfFields; allInfoWrapper.listOfInsurancesIdsToDelete = []; enoughCR = this.checkNumberOfInsurances(allInfoWrapper); } else if (sectionNumber === 7) { allInfoWrapper.listOfLicensesFields = tempListOfFields; allInfoWrapper.listOfLicensesIdsToDelete = []; enoughCR = this.checkNumberOfLicenses(allInfoWrapper); } else if (sectionNumber === 8) { allInfoWrapper.listOfCertificationsFields = tempListOfFields; allInfoWrapper.listOfCertificationsIdsToDelete = []; enoughCR = this.checkNumberOfCertifications(allInfoWrapper); } else if (sectionNumber === 9) { allInfoWrapper.listOfTaxFields = tempListOfFields; allInfoWrapper.listOfTaxIdsToDelete = []; enoughCR = this.reviewCRListForNumberOfRecords(allInfoWrapper.listOfTaxFields,allInfoWrapper.numberOfTaxDocs); } else if (sectionNumber === 10) { allInfoWrapper.listOfOtherFields = tempListOfFields; allInfoWrapper.listOfOtherIdsToDelete = []; enoughCR = this.reviewCRListForNumberOfRecords(allInfoWrapper.listOfOtherFields,allInfoWrapper.numberOfOtherDocs); } component.set("v.allInfoWrapper", allInfoWrapper); if (sectionNumber === 4 || sectionNumber === 5 || sectionNumber === 6 || sectionNumber === 7 || sectionNumber === 8 || sectionNumber === 9 || sectionNumber === 10) { //console.log('enoughCR ',enoughCR); if (enoughCR) { this.goNextTab(component, event); this.showToast(component, 'success', 'Changes saved successfully', 'Success'); } else { this.showToast(component, 'error', 'Minimum number is not reached', 'Error'); } } //console.log('allInfoWrapper ',allInfoWrapper); } else if (state === "INCOMPLETE") { this.showToast(component, 'error', $A.get("$Label.c.Status_incomplete"), 'Error'); } else if (state === "ERROR") { var errors = response.getError(); if (errors) { if (errors.length > 0) { for (var i = 0; i < errors.length; i++) { if (errors[0].pageErrors) { if (errors[0].pageErrors.length > 0) { for (var j = 0; j < errors[i].pageErrors.length; j++) { this.showToast(component, 'error', 'Internal server error: ' + errors[i].pageErrors[j].message, 'Error'); } } } this.showToast(component, 'error', errors[i].message, 'Error'); } } } else { this.showToast(component, 'error', $A.get("$Label.c.Internal_server_error"), 'Error'); } } this.hideSpinner(component); }); $A.enqueueAction(action); }, createSubscriptionPopUp: function (component) { var applicationId = component.get('v.allInfoWrapper.applicationId'); $A.createComponent( 'c:SubscriptionPopUp', { "applicationId" : applicationId }, function(newComponent, state, errorMessage) { if (state === 'SUCCESS') { var body = component.get("v.body"); body.push(newComponent); component.set("v.body", body); component.set("v.allInfoWrapper.isSubscribed", true); } else if (state === "INCOMPLETE") { this.showToast(component, 'error', $A.get("$Label.c.Status_incomplete"), 'Error'); } else if (state === "ERROR") { var errors = response.getError(); if (errors) { if (errors.length > 0) { for (var i = 0; i < errors.length; i++) { if (errors[0].pageErrors) { if (errors[0].pageErrors.length > 0) { for (var j = 0; j < errors[i].pageErrors.length; j++) { this.showToast(component, 'error', 'Internal server error: ' + errors[i].pageErrors[j].message, 'Error'); } } } this.showToast(component, 'error', errors[i].message, 'Error'); } } } else { this.showToast(component, 'error', $A.get("$Label.c.Internal_server_error"), 'Error'); } } } ); this.hideSpinner(component); }, goNextTab : function (component, event) { var allInfoWrapper = component.get("v.allInfoWrapper"); var isTab = component.get('v.isTab'); if (!isTab) { component.set('v.isTab', true); var index = component.get('v.activeTab'); var str = 'tab-' + index; var subStr = 'tab-scoped-' + index; var tab = component.find(str); var subTab = component.find(subStr); var newIndex = Number(event.target.getAttribute('data-section')) + 1; if(newIndex == 3 && allInfoWrapper.tab3Visible == false) { newIndex = 4; } if(newIndex == 4 && allInfoWrapper.tab4Visible == false) { newIndex = 5; } if(newIndex == 5 && allInfoWrapper.tab5Visible == false) { newIndex = 6; } if(newIndex == 6 && allInfoWrapper.tab6Visible == false) { newIndex = 7; } if(newIndex == 7 && allInfoWrapper.tab7Visible == false) { newIndex = 8; } if(newIndex == 8 && allInfoWrapper.tab8Visible == false) { newIndex = 9; } if(newIndex == 9 && allInfoWrapper.tab9Visible == false) { newIndex = 10; } if(newIndex == 10 && allInfoWrapper.tab10Visible == false) { newIndex = 11; } if(newIndex == 11 && allInfoWrapper.tab11Visible == false) { newIndex = 12; } var activeTab = component.find("tab-" + newIndex); var newSubStr = 'tab-scoped-' + newIndex; var newSubTab = component.find(newSubStr); $A.util.addClass(tab, 'selected'); $A.util.removeClass(tab, 'slds-is-active'); $A.util.removeClass(tab, 'selected'); $A.util.removeClass(subTab, 'slds-show'); $A.util.addClass(subTab, 'slds-hide'); component.set('v.activeTab', newIndex); $A.util.addClass(activeTab, 'slds-is-active'); $A.util.removeClass(newSubTab, 'slds-hide'); $A.util.addClass(newSubTab, 'slds-show'); component.set('v.isTab', false); window.scrollTo(0, 0); } }, showToast: function (component, type, message, title) { var showToast = $A.get("e.force:showToast"); // console.log('showToast ', showToast); showToast.setParams({ mode: 'pester', type: type, title: title, message: message, duration: '5000' }); showToast.fire(); this.hideSpinner(component); }, showSpinner : function(component) { component.set("v.Spinner", true); }, hideSpinner : function(component){ component.set("v.Spinner", false); } })
import { arrayRemoveItem } from '../../utils' const initialState = { map: {}, idsMap: { normal: [], expired: [] }, pagingMap: { normal: { page: 1, limit: 10, finished: false }, expired: { page: 1, limit: 10, finished: false } } } const coupons = function (state = initialState, action) { switch (action.type) { case 'FETCH_COUPON_LIST_SUCCESS': const { isRefresh, tab, couponList, paging } = action.payload state.pagingMap[tab] = paging if (isRefresh) state.idsMap[tab] = [] couponList.map(coupon => { const { usercouponId: id } = coupon state.idsMap[tab].push(id) state.map[id] = coupon }) return { ...state } case 'POST_COUPON_CODE_SUCCESS': const { coupon } = action.payload state.idsMap.normal.unshift(coupon.usercouponId) state.map[coupon.usercouponId] = coupon return { ...state } case 'POST_ORDER_SUCCESS': const { couponId } = action.payload arrayRemoveItem(state.idsMap.normal, couponId) delete state.map[couponId] return { ...state } default: return state } } export default coupons
import React from "react" import "../styling/styles.css" import Layout from "../components/layout" import SEO from "../components/seo" import { faEnvelope } from "@fortawesome/free-solid-svg-icons" import { FontAwesomeIcon } from "@fortawesome/react-fontawesome" import { faTwitter, faLinkedin, faGithub, } from "@fortawesome/fontawesome-free-brands" const IndexPage = () => ( <Layout> <div className="home-container"> <div className="hero-text-container"> <div className="name"> <svg height="100" width="1000" style={{ strokeWidth: 2 }} stroke="#333" className="text-line" > <text className="name-text" x="0" y="80" fill="none"> Hey, I'm Julien Assouline </text> </svg> </div> <p className="title-description"> I'm a Full Stack Developer passionate about building applications, tools, data visualizations and coding, in general, to improve peoples lives and make the world a better place. </p> <div className="icons-container"> <a href="mailto:julien1993@hotmail.ca"> <FontAwesomeIcon icon={faEnvelope} className="icon fa-5x" />{" "} </a> <a href="https://github.com/JulienAssouline"> <FontAwesomeIcon icon={faGithub} className="icon fa-5x" />{" "} </a> <a href="https://www.linkedin.com/in/julienassouline/"> <FontAwesomeIcon icon={faLinkedin} className="icon fa-5x" />{" "} </a> <a href="https://twitter.com/JulienAssouline"> <FontAwesomeIcon icon={faTwitter} className="icon fa-5x" />{" "} </a> </div> </div> </div> </Layout> ) export default IndexPage
// Modificer løsningen til Opgave 14.3, så kun brugere med et bestemt password kan logge ind på chatserveren. // FEJL: TJekker ikke for session på alle endpoints - kan løses ved routing (se evt. næste uges opg) // MONGODB / MONGOOSE const mongoose = require('mongoose'); const url = 'mongodb://localhost/chatDB'; mongoose.connect(url, { useNewUrlParser: true, useUnifiedTopology: true }); const chatBeskedSchema = new mongoose.Schema({ navn: String, rum: String, tekst: String, nr: Number }); const ChatBesked = mongoose.model('ChatBesked', chatBeskedSchema); // Creates 3 dummy messages if db is empty async function populateDatabase() { try { if (await isDBEmpty()) { await ChatBesked.create({ navn: 'navn1', rum: 'rum1', tekst: 'tekst1', nr: 0 }); await ChatBesked.create({ navn: 'navn2', rum: 'rum1', tekst: 'tekst2', nr: 1 }); await ChatBesked.create({ navn: 'navn3', rum: 'rum2', tekst: 'tekst3', nr: 2 }); } } catch (error) { console.log(error); } } // Populate DB (if empty) populateDatabase(); // Try to find any element in db, if null - db is empty and return true async function isDBEmpty() { return await (ChatBesked.findOne().exec()) == null; } async function getChatMessages() { return await ChatBesked.find().select('-_id -__v').exec(); } async function getChatMessagesInRoom(room) { return await ChatBesked.find().select('-_id -__v').where('rum').eq(room).exec(); } async function getRooms() { return await ChatBesked.find().select('rum -_id').distinct('rum').exec(); } // Gets message with highest nr and adds 1 or return 0 if db is empty async function getNextChatMessageNumber() { return (await isDBEmpty()) ? 0 : (await ChatBesked.findOne().sort('-nr').exec()).nr + 1; } // EXPRESS const express = require('express'); const app = express(); const cors = require('cors'); const port = 8080; app.use(cors()); app.use(express.json()); app.use(express.static(__dirname + '/filer')); app.get('/beskeder', async (req, res) => { res.send(await getChatMessages()); }); app.get('/beskeder/:rum', async (req, res) => { const rum = req.params.rum; res.send(await getChatMessagesInRoom(rum)); }); app.get('/rum', async (req, res) => { res.send(await getRooms()); }); app.post('/besked', async (req, res) => { const body = req.body; await ChatBesked.create({ navn: body.navn, rum: body.rum, tekst: body.tekst, nr: await getNextChatMessageNumber() }); res.status(201).send(req.body); }); app.delete('/besked/:nr', async (req, res) => { const nr = parseInt(req.params.nr); const deleteInfo = await ChatBesked.deleteOne().where('nr').equals(nr).exec(); if (deleteInfo.deletedCount == 1) res.status(200).send({ resultat: 'Besked slettet!' }); else res.status(404).send(); }); // EXPRESS-SESSION & HBS & CONNECT-MONGODB-SESSION // Opgave 15.3 fra app.js const session = require('express-session'); const hbs = require('hbs'); const MongoDBStore = require('connect-mongodb-session')(session); app.set('view engine', 'hbs'); app.set('views', __dirname + '/templates'); const store = new MongoDBStore({ uri: url, // MongoDB connection collection: 'mySessions' // MongoDB collection }); // Catch errors store.on('error', function (error) { console.log(error); }); app.use(session({ secret: 'hemmelig', cookie: { maxAge: 1000 * 60 * 10 // 1000 ms * 60 = 10 min * 10 = 10 minutes }, store, resave: true, saveUninitialized: true })); app.post('/login', async (req, res) => { const { navn, password } = req.body; if (password === '111' && navn) { req.session.navn = navn; res.status(201).send(['login ok!']); } else { res.sendStatus(401); } }); app.get('/session', async (req, res) => { const navn = req.session.navn; if (navn) { res.render('velkommen.hbs', { navn }); } else { res.redirect('/ingenAdgang.html'); } }); app.get('/logout', (req, res) => { req.session.destroy((err) => { if (err) { console.log(err); } else { res.redirect('/'); } }); }); // app.listen(port, () => { console.log(`Example app listening at http://localhost:${port}`) });
/* * Test for ti.urbanAirship module: Demonstrates how to set up push notifications * using the Urban Airship push notification library. */ /// open a single window var window = Ti.UI.createWindow({backgroundColor: 'white', layout: 'vertical'}); var pushOnSwitch = Ti.UI.createSwitch({ value: false, isSwitch: true, top: 10, left: 10, height: Ti.UI.SIZE || 'auto', width: 200, titleOn: 'Disable Push', titleOff: 'Enable Push' }); window.add(pushOnSwitch); window.add(Ti.UI.createLabel({ text: 'APID:', top: 10, left: 10, textAlign: 'left', color: 'black', font: {fontSize: 18, fontStyle: 'bold'}, height: Ti.UI.SIZE || 'auto' })); var labelAPID = Ti.UI.createLabel({ text: '', top: 10, left: 10, textAlign: 'left', color: 'black', height: Ti.UI.SIZE || 'auto' }); window.add(labelAPID); window.add(Ti.UI.createLabel({ text: 'Last Message:', top: 10, left: 10, textAlign: 'left', color: 'black', font: {fontSize: 18, fontStyle: 'bold'}, height: Ti.UI.SIZE || 'auto' })); var labelMessage = Ti.UI.createLabel({ text: '', top: 10, left: 10, textAlign: 'left', color: 'black', height: Ti.UI.SIZE || 'auto' }); window.add(labelMessage); window.add(Ti.UI.createLabel({ text: 'Payload:', top: 10, left: 10, textAlign: 'left', color: 'black', font: {fontSize: 18, fontStyle: 'bold'}, height: Ti.UI.SIZE || 'auto' })); var labelPayload = Ti.UI.createLabel({ text: '', top: 10, left: 10, textAlign: 'left', color: 'black', height: Ti.UI.SIZE || 'auto' }); window.add(labelPayload); window.open(); var UrbanAirship = require('ti.urbanairship'); Ti.API.info("module is => " + UrbanAirship); // Set UA options UrbanAirship.showOnAppClick = true; UrbanAirship.tags = [ 'testingtesting', 'appcelerator', 'my-tags' ]; UrbanAirship.alias = 'testDevice'; // Display current pushId (use ua.c2dmId if using C2DM) labelAPID.text = UrbanAirship.pushId; // Set switch to current state of push pushOnSwitch.value = UrbanAirship.pushEnabled; // Toggle push state on switch change pushOnSwitch.addEventListener('change', function (e) { UrbanAirship.pushEnabled = e.value; }); function eventCallback(e) { if (e.clicked) { Ti.API.info('User clicked a notification'); } else { Ti.API.info('Push message received'); } Ti.API.info(' Message: ' + e.message); Ti.API.info(' Payload: ' + e.payload); labelMessage.text = e.message; labelPayload.text = e.payload; } function eventSuccess(e) { Ti.API.info('Received device token: ' + e.deviceToken); labelAPID.text = e.deviceToken; } function eventError(e) { Ti.API.info('Error:' + e.error); var alert = Ti.UI.createAlertDialog({ title: 'Error', message: e.error }); alert.show(); } UrbanAirship.addEventListener(UrbanAirship.EVENT_URBAN_AIRSHIP_CALLBACK, eventCallback); UrbanAirship.addEventListener(UrbanAirship.EVENT_URBAN_AIRSHIP_SUCCESS, eventSuccess); UrbanAirship.addEventListener(UrbanAirship.EVENT_URBAN_AIRSHIP_ERROR, eventError);
/****************************************************************************** * * PROJECT: Flynax Classifieds Software * VERSION: 4.1.0 * LICENSE: FL43K5653W2I - http://www.flynax.com/license-agreement.html * PRODUCT: Real Estate Classifieds * DOMAIN: avisos.com.bo * FILE: COOKIE.JS * * The software is a commercial product delivered under single, non-exclusive, * non-transferable license for one domain or IP address. Therefore distribution, * sale or transfer of the file in whole or in part without permission of Flynax * respective owners is considered to be illegal and breach of Flynax License End * User Agreement. * * You are not allowed to remove this information from the file without permission * of Flynax respective owners. * * Flynax Classifieds Software 2013 | All copyrights reserved. * * http://www.flynax.com/ ******************************************************************************/ function createCookie( name, value, days) { value = encodeURI(value); if (days) { var date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000)); var expires = "; expires="+date.toGMTString(); } else { var expires = ""; } document.cookie = name+"="+value+expires+"; path=/"; } function readCookie(name) { var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return decodeURI(c.substring(nameEQ.length,c.length)); } return null; } function eraseCookie(name) { createCookie(name,"",-1); }
import * as React from 'react'; import { Icon, Input, Button } from 'react-native-elements'; import { KeyboardAvoidingView, keyboardVerticalOffset,ScrollView,View, Text, Image } from 'react-native'; import styles from './style'; function ResetPasswordNew({ navigation}) { return ( <View style={{padding: 20, marginTop:40}}> <KeyboardAvoidingView behavior='position' keyboardVerticalOffset={keyboardVerticalOffset}> <Text style={styles.resetText}>Create New Password</Text> <Text style={styles.emailText}>Your new password must be different from previous used password!</Text> <Input inputContainerStyle={styles.inputContainerStyle} label={"Password"} labelStyle={styles.labelStyle} rightIcon={{ type: 'font-awesome', name: 'eye' }} rightIconContainerStyle={styles.rightIconStyle} secureTextEntry={true} /> <Input inputContainerStyle={styles.inputContainerStyle} label={"Confirm Password"} labelStyle={styles.labelStyle} rightIcon={{ type: 'font-awesome', name: 'eye' }} rightIconContainerStyle={styles.rightIconStyle} secureTextEntry={true} /> <Button title="Create" buttonStyle={styles.buttonRegister} containerStyle={styles.buttonContent} onPress={() => navigation.push('ResetPasswordSuccess')} /> </KeyboardAvoidingView > </View> ); } export default ResetPasswordNew
function traverse(tree, call) { function treeLoop(tree) { call.enter && call.enter(tree); if(tree.children) { tree.children.forEach(element => { treeLoop(element); }); } } treeLoop(tree); } module.exports = traverse;
/* Description: Substitution - Cryptography #1 Cryptography is a very interesting and important subject in computer science. Cryptography is used in our daily lives when using a computer so it benificial to learn more about it. In this kata series you will learn about some encrypting and decrypting methods and how you can possibly apply them. Task Your task is to create a text to int substitution object which has the methods Encrypt and Decrypt. The two functions Encrypt and Decrypt will take a string of characters you must then convert those characters into their ascii value and add 58, then you must put them into a string and return that. */ const Substitution = () => { return { Encrypt: (word) => { return word.split('').map(letter => letter.charCodeAt() + 58).join(''); }, Decrypt: (word) => { return word.match(/\d{1,3}/g).map(num => parseInt(num) - 58).map(n => String.fromCharCode(n)).join(''); } }; };
/** * Copyright 2019-2020 ForgeRock AS. All Rights Reserved * * Use of this code requires a commercial software license with ForgeRock AS. * or with one of its affiliates. All use shall be exclusively subject * to such license between the licensee and ForgeRock AS. */ import { shallowMount, createLocalVue } from '@vue/test-utils'; import BootstrapVue from 'bootstrap-vue'; import generateIDMAPI from './__mocks__/generateIDMAPI'; import ListResource from './index'; describe('ListResource Component', () => { let wrapper = null; const $route = { path: '/test', meta: {}, params: { resourceName: 'resourceName', resourceType: 'managed', }, }; beforeEach(() => { const localVue = createLocalVue(); localVue.use(BootstrapVue); wrapper = shallowMount(ListResource, { localVue, stubs: { 'router-link': true, }, mocks: { $route, $t: () => {}, generateIDMAPI: () => { const retv = { data: { pagedResultsCookie: {}, }, get: () => { const retva = { then: () => {}, }; return retva; }, }; return retv; }, }, propsData: { routerParameters: { resourceName: 'resourceName', icon: 'testIcon', routeName: 'ListResource', resourceType: 'managed', managedProperties: { sn: { viewable: true, type: 'number', }, name: { viewable: true, type: 'string', }, viewTest: { viewable: false, type: 'boolean', }, typeTest: { viewable: true, type: 'array', }, }, order: ['name', 'sn', 'viewTest', 'typeTest'], }, }, }); }); it('Component successfully loaded', () => { expect(wrapper.isVueInstance()).toEqual(true); expect(wrapper.name()).toEqual('ListResource'); }); it('Loads table column definitions', () => { wrapper.vm.resource = 'user'; wrapper.vm.loadTableDefs(); expect(wrapper.vm.resourceName).toEqual('resourceName'); expect(wrapper.vm.displayFields[0]).toEqual('name'); expect(wrapper.vm.displayFields[1]).toEqual('sn'); expect(wrapper.vm.displayFields.length).toEqual(2); }); it('Loads data for table rows', async () => { generateIDMAPI.get.mockImplementationOnce(() => Promise.resolve({ data: { result: ['test'] }, })); wrapper.vm.loadData({}, ['field1'], 'field1', ''); const result = await generateIDMAPI.get(); expect(result.data.result[0]).toEqual('test'); // TODO: ensure we can test within return value // expect(wrapper.vm.tableData).toEqual('test'); }); beforeEach(() => { jest.spyOn(ListResource, 'mounted') .mockImplementation(() => { }); }); it('ListResource page loaded', () => { expect(wrapper.name()).toBe('ListResource'); expect(wrapper).toMatchSnapshot(); }); it('ListResource sort column', () => { wrapper.setMethods({ loadTable: () => { } }); expect(wrapper.vm.calculateSort(false, 'test')).toBe('-test'); expect(wrapper.vm.calculateSort(true, 'test')).toBe('test'); }); it('Sorting change reset', () => { wrapper.setMethods({ loadTable: () => { } }); wrapper.vm.sortingChanged({ sortDesc: false, sortBy: 'test', }); expect(wrapper.vm.currentPage).toBe(0); }); it('New search entered', () => { wrapper.setMethods({ loadTable: () => { } }); wrapper.vm.search(); expect(wrapper.vm.sortBy).toBeNull(); expect(wrapper.vm.currentPage).toBe(0); }); it('Generated query filter for search', () => { expect(wrapper.vm.generateSearch('test', ['test1', 'test2'])).toBe('test1+sw+"test"+OR+test2+sw+"test"'); expect(wrapper.vm.generateSearch('', ['test1', 'test2'])).toBe('true'); }); it('Clear search and sort', () => { wrapper.setMethods({ loadTable: () => { } }); wrapper.vm.clear(); expect(wrapper.vm.sortBy).toBeNull(); expect(wrapper.vm.currentPage).toBe(0); }); });
import React, { Component } from 'react' import { connect } from 'react-redux' import { Link } from 'react-router-dom' import TimeAgo from 'react-timeago' import Up from 'react-icons/lib/go/arrow-up' import Down from 'react-icons/lib/go/arrow-down' import User from 'react-icons/lib/fa/user' import Clock from 'react-icons/lib/fa/clock-o' import Pencil from 'react-icons/lib/fa/pencil' import Trash from 'react-icons/lib/fa/trash' import { sendPostVote } from '../actions' class FullPost extends Component { render() { const { post, sendPostVote } = this.props if (post) return ( <div className='full-post'> <div className='vote-score'> <div> <button onClick={() => sendPostVote(post.id, 'upVote')}> <Up /> </button> </div> <div>{post.voteScore}</div> <div> <button onClick={() => sendPostVote(post.id, 'downVote')}> <Down /> </button> </div> </div> <div> <h3><b>{post.title}</b></h3> <p>{post.body}</p> </div> <span className='meta'> <User /> <b>{post.author}</b>{' | '} <Clock /> <TimeAgo date={post.timestamp} />{' | '} <Pencil />&nbsp; <Link to={`/edit/post/${post.id}`}>Edit</Link>{' | '} <Trash />&nbsp; <Link to={`/delete/post/${post.id}`}>Delete</Link> </span> </div> ) return null } } function mapDispatchToProps (dispatch) { return { sendPostVote: (id, option) => dispatch(sendPostVote(id, option)) } } export default connect(null, mapDispatchToProps)(FullPost)
/*global Plot */ // Written by Irena Shaffer and Alexandru Cioaca $(document).ready(function() { "use strict"; var av_name = "polynomialCON"; var av = new JSAV(av_name); var width = 350, height = 140; var xStart = 250; var yEnd = 20; var yStart = yEnd + height; //end position of the y on the chart var xMax = 300, yMax = 1500; function _0(n) { return 0 * n; } // Slide 1 av.umsg("Consider the following polynomial. We can look at it as a sum," + " whose terms are powers of x, multiplied with the coefficients $a_i$."); var polyLab = av.label("$P(x) = a_0 + a_1x + a_2x^2 + a_3x^3$", {left: 50, top: 0}); av.displayInit(); // Slide 2 av.umsg("But we can also look at it geometrically, and recognize that each term in the polynomial is adding something to the final curve."); av.step(); // Slide 3 av.umsg("First we have the constant component $a_0$, which is a horizontal line."); polyLab.hide(); polyLab = av.label("$P(x) =$ <font color = red> $a_0$ </font> $+ a_1x + a_2x^2 + a_3x^3$", {left: 50, top: 0}); var xAxis = Plot.drawCurve(_0, xStart, yStart, yEnd, xMax, yMax, width, height, 0.5, false); av.g.polyline(xAxis, {stroke: "grey", "stroke-width": 2}); av.g.line(xStart + width / 2, yEnd, xStart + width / 2, yStart + height, {stroke: "grey", "stroke-width": 2}); av.g.line(xStart + width, yEnd + height, xStart + width - 10, yEnd + height - 5, {stroke: "grey", "stroke-width": 2}); av.g.line(xStart + width, yEnd + height, xStart + width - 10, yEnd + height + 5, {stroke: "grey", "stroke-width": 2}); av.g.line(xStart + width / 2, yEnd, xStart + width / 2 - 5, yEnd + 10, {stroke: "grey", "stroke-width": 2}); av.g.line(xStart + width / 2, yEnd, xStart + width / 2 + 5, yEnd + 10, {stroke: "grey", "stroke-width": 2}); av.label("x", {left: xStart + width, top: yEnd + height - 10}); av.label("y", {left: xStart + width / 2 + 10, top: yEnd - 10}); function _200(n) { return 200 + n * 0; } var curve1 = Plot.drawCurve(_200, xStart, yStart, yEnd, xMax, yMax, width, height, 0.5, false); av.g.polyline(curve1, {stroke: "red", "stroke-width": 2}); av.step(); // Slide 4 av.umsg("Then, the linear component $a_1x$, is a line with slope $a_1$."); polyLab.hide(); polyLab = av.label("$P(x) = $ <font color = red> $a_0$ </font> $ + $ <font color = purple> $a_1x$ </font> $ + a_2x^2 + a_3x^3$", {left: 50, top: 0}); function _4x(n) { return 4 * (n - 150); } var curve2 = Plot.drawCurve(_4x, xStart, yStart, yEnd, xMax, yMax, width, height, 0.5, false); av.g.polyline(curve2, {stroke: "purple", "stroke-width": 2}); av.step(); // Slide 5 av.umsg("Adding these two terms would have the effect of shifting the purple line upwards by the height of the red line."); av.step(); // Slide 6 av.umsg("Next, the quadratic term $a_2x^2$ is a parabola."); polyLab.hide(); polyLab = av.label("$P(x) = $<font color = red>$a_0$</font>$ + $<font color = purple>$a_1x$</font>" + "$ + $<font color = blue>$a_2x^2$</font>$ + a_3x^3$", {left: 50, top: 0}); var curve3 = Plot.drawCurve(_xpow2, xStart + 85, yStart, yEnd, xMax, yMax, width, height, 0.5, false); av.g.polyline(curve3, {stroke: "blue", "stroke-width": 2}); function _xpow2(n) { return Math.pow(0.5 * (n - 77), 2); } av.step(); // Slide 7 av.umsg("Last, we have the 3rd degree term $a_3x^3$, which is a cubic polynomial."); polyLab.hide(); polyLab = av.label("$P(x) = $ <font color = red> $a_0$ </font> $ + $ <font color = purple> $a_1x$ </font>" + "$+$ <font color = blue> $a_2x^2$ </font> $+$ <font color = green> $a_3x^3$ </font>", {left: 50, top: 0}); var curve4 = Plot.drawCurve(_xpow3, xStart + 105, yStart, yEnd, xMax, yMax, width, height, 0.5, false); av.g.polyline(curve4, {stroke: "green", "stroke-width": 2}); function _xpow3(n) { return Math.pow(0.2 * (n - 57), 3); } av.step(); // Slide 8 function _cubic(n) { return 200 + 4 * (n - 68) + Math.pow(0.5 * (n - 74), 2) + Math.pow(0.2 * (n - 71), 3); } var curve5 = Plot.drawCurve(_cubic, xStart + 105, yStart, yEnd, xMax, yMax, width, height, 0.1, false); av.g.polyline(curve5, {"stroke-width": 3.5}); av.umsg("Adding these 4 componets gives us our polynomial (in black)."); av.recorded(); });
'use strict'; module.exports = function(Node) { /*var ds = Node.dataSource; var sql = "SELECT * FROM node"; console.log(Node.dataSource); ds.database.query(sql);*/ /* Node.afterCreate = function(next) { if (this.node_id) Node.findById(this.node_id) .then(function(instance) { Node.upsertWithWhere({where: {id: instance.id}}, {count_child: instance.count_child+1}) .then(function(obj) { }).catch(function(err){ throw err; }) }).catch(function(err){ throw err; }) next(); }; */ };
import resolve from "rollup-plugin-node-resolve"; // https://github.com/rollup/plugins/issues/67 import commonjs from "@rollup/plugin-commonjs"; import postcss from "rollup-plugin-postcss"; import json from "@rollup/plugin-json"; import VuePlugin from "rollup-plugin-vue"; import replace from "@rollup/plugin-replace"; import { terser } from "rollup-plugin-terser"; import gzipPlugin from "rollup-plugin-gzip"; //import { brotliCompressSync, constants } from "zlib"; import postcss_url from "postcss-url"; import path from "path"; import fs from "fs"; import glob from "glob"; let fontFolder = "../assets/public/static/fonts"; fs.mkdirSync(fontFolder, { recursive: true, }); const production = !(process.env.NODE_ENV === "debug"); const plugins = [ VuePlugin({ // https://github.com/vuejs/rollup-plugin-vue/issues/238 needMap: false, }), commonjs(), resolve({ //browser: true, preferBuiltins: false, }), postcss({ minimize: production, plugins: [ postcss_url({ // copy ALMOST does what we want - it renames the asset files... however, // what we ACTUALLY want is to move the files AND rename them relative to the root // so let's do that here url: function (asset, dir, options, decl, warn, result, addDependency) { if (asset.url.startsWith("data:")) { return asset.url; } // We really only need woff2 files, since we are targeting modern browsers if (path.extname(asset.absolutePath) == ".woff2") { let toURL = fontFolder + "/" + path.basename(asset.absolutePath); fs.copyFile(asset.absolutePath, toURL, (err) => { if (err) throw err; console.log(asset.relativePath, " -> ", toURL); }); } return "/static/fonts/" + path.basename(asset.url); }, }), ], }), json({ compact: production, }), replace({ "process.env.NODE_ENV": JSON.stringify(production ? "production" : "debug"), "_DEBUG": JSON.stringify(!production) }), ]; if (production) { plugins.push( terser({ compress: { drop_console: false, ecma: 10, // Heedy doesn't do backwards compatibility }, mangle: true, module: true, }) ); plugins.push(gzipPlugin()); } else { console.log("Running debug build"); } function checkExternal(modid, parent, isResolved) { return ( (!isResolved && modid.endsWith(".mjs") && modid.startsWith(".")) || modid.startsWith("http") ); } function out(name, loc = "", format = "es") { let filename = name.slice(0, name.lastIndexOf(".")); return { input: "src/" + name, output: { name: filename, file: "../assets/public/static/" + loc + filename + (format == "es" ? ".mjs" : ".js"), format: format, }, plugins: plugins, external: checkExternal, }; } // g allows using globs to define output files let g = (x) => glob .sync(x, { cwd: "./src", }) .map((a) => out(a)); export default [...g("*.js"), ...g("dist/*.js"), ...g("heedy/*.js")];
import React, { Component } from 'react'; import './ChoiceButton.css'; class ChoiceButton extends Component{ constructor(props){ super(props); this.state = { // if still empty } } render(){ let extraClass; if(this.props.mode === this.props.value){ extraClass = "Choice-button-selected" }else{ extraClass = "Choice-button-not-selected" } // using an ES6 string literal `Hello ${Surname}.` return ( <button className={`Choice-button ${extraClass}`} onClick={this.props.handleClick} > {this.props.text} </button> ); } } export default ChoiceButton;
$(document).ready(function(){ console.log('=========jquery ok ===========') checkDelete('.delete'); }); function checkDelete(idButton){ var $button = $(idButton); var confirmMsg = '<p>êtes vous sure de vouloir supprimer ce produit</p>'; var choice = '<button id="deleteYes" type="submit">oui</button><button id="deleteNo" >non</button>'; var $msg = '<div id="confirmMsg">'+confirmMsg+choice+'</div>'; $button.on('click', function(evt){ evt.preventDefault(); if($msg !=undefined && $msg!= null && $msg!=""){ $(this).css('display','none') $(this).after($msg); var $confirmMsg = $('#confirmMsg'); var $yes = $('#deleteYes'); var $no = $('#deleteNo'); $no.on('click',function(evt){$ evt.preventDefault(); $confirmMsg.remove(); $button.css('display','block') }); } else{ alert('script error'); } }) }
import Phaser from './importPhaser'; import Player from './Player'; import loadState from './states/load'; import mainState from './states/main'; import prepareState from './states/prepare'; import Sounds from './Sounds'; let game, gameWidth = 0, gameHeight = 0, gameObj; function setGameWidth(width) { gameWidth = width; } function setGameHeight(height) { gameHeight = height; } if(window.innerWidth > window.innerHeight) { game = new Phaser.Game(window.innerWidth, window.innerHeight, Phaser.CANVAS, ''); setGameWidth(window.innerWidth); setGameHeight(window.innerHeight); } else { game = new Phaser.Game(window.innerHeight, window.innerWidth, Phaser.CANVAS, ''); setGameWidth(window.innerHeight); setGameHeight(window.innerWidth); } Phaser.World.prototype.displayObjectUpdateTransform = function() { if (!game.scale.correct) { this.x = game.camera.y + game.width; this.y = -game.camera.x; this.rotation = Phaser.Math.degToRad(Phaser.Math.wrapAngle(90)); } else { this.x = -game.camera.x; this.y = -game.camera.y; this.rotation = 0; } window.PIXI.DisplayObject.prototype.updateTransform.call(this); }; gameObj = { init() { game.state.add('load', loadState); game.state.add('prepare', prepareState); game.state.add('main', mainState); this._load(); }, _load() { game.state.start('load'); }, addPlayer() { if(!this._player) { this._player = new Player(this._getPlayerIdentifier()); } }, _getPlayerIdentifier() { return '0'; }, _getServerUrl() { return 'http://jianfengdoudizhu.game.webxinxin.com'; }, get player() { return this._player; }, showAbsenceNum(num) { prepareState.showAbsenceNum(num); }, beginGame() { Sounds.playBG(); prepareState.beginGame(); }, async dealCards(cards, currentPlayerIndex) { await mainState.dealCards(cards, currentPlayerIndex); }, startCallPoints() { mainState.startCallPoints(); }, showPoint(point, playerIndex) { Sounds.playCallPoint(point); mainState.showPoint(point, playerIndex); }, async sendDiZhuCards(cards, dizhuIndex) { return mainState.sendDiZhuCards(cards, dizhuIndex); }, playCards() { mainState.beginPlayCards(); }, dropCards(cards) { mainState.dropCards(cards); }, showDroppedCards(cards, deckIndex, playerIndex, isCover) { Sounds.playCards(cards, deckIndex); mainState.showDroppedCards(cards, playerIndex, isCover); }, coverCards() { mainState.beginCoverCards(); }, discard() { Sounds.playDiscard(); mainState.discard(); }, showDiscarded(playerIndex) { mainState.showDiscarded(playerIndex); }, showAlarm() { Sounds.playAlarm(); }, finishGame(win) { Sounds.stopBG(); if(win) { Sounds.playWin(); } else { Sounds.playLose(); } mainState.finishGame(win); }, showLeftTime(playerIndex, leftTime) { mainState.showLeftTime(playerIndex, leftTime); }, async startGame() { return this._player.startGame(); }, setConnected(v) { this._isConnected = v; if(v) { prepareState.addBtns(); } }, get isConnected() { return this._isConnected; }, }; export default game; export {gameWidth, gameHeight, setGameWidth, setGameHeight, gameObj};
import React from 'react'; export default class PhotoIndexScreen extends React.Component { render() { return ( <div> <h1>Photos</h1> <ul> <li><a href="#/photos/1">Photo #1</a></li> <li><a href="#/photos/2">Photo #2</a></li> <li><a href="#/photos/3">Photo #3</a></li> </ul> </div> ); } }
$(document).ready(function () { var MTDS = new METODOS(); var fecha = MTDS.TODAY(); var Secciones; var Lockers; var Matriculas; if (objSess.idtipo == 1) { $('#msg_renovar_user').addClass('elem-hide'); $('#msg_renovar_admin').removeClass('elem-hide'); $('#renovarMat').removeClass('elem-hide'); $('#renovarCom').removeClass('elem-hide'); } else { console.log(''); } window.s_usuario = function () { var param = {action: "selUsuario"}; $.ajax({ type: "POST", url: domin, data: param, dataType: "json", success: function (response) { var arr = new Array(); Secciones = response; arr.push({ id: 0, Nombre: 'Selecciona matricula' }); $.each(response, function (indx, obj) { var OBJ = { id: obj.id, Nombre: obj.Matricula }; arr.push(OBJ); }); MTDS.FULLER_COMBO('Renovar_Matricula', arr); }, error: function (e) { console.log(e); } }); }; window.s_Seccion = function () { var param = {action:"selSeccion"} $.ajax({ type: "POST", url: domin, data: param, dataType: "json", success: function (response) { var arr = new Array(); Secciones = response; arr.push({ id: 0, Nombre: 'NINGUNO' }); $.each(response, function (indx, obj) { var OBJ = {id: obj.id, Nombre: obj.Nombre }; arr.push(OBJ); }); //console.log(Secciones); MTDS.FULLER_COMBO('Renovar_Seccion', arr); }, error: function (e) { console.log(e); } }); }; window.s_LockerByUserOcupado = function (idUser, idSecc) { var param = {action:"selLockerUserOcupado", idsec: idSecc, idU: idUser }; $.ajax({ type: "POST", url: domin , data: param, dataType: "json", success: function (response) { var arr = new Array(); Lockers = response; $.each(response, function (indx, obj) { var OBJ = [obj.id, obj.Numero, obj.Precio, obj.idEstatus, obj.idSeccion, obj.idUsuario]; arr.push(OBJ); }); MTDS.FULLER_COMBO('Renovar_NumLocker', Lockers); ImgLocker(); }, error: function (e) { console.log(e); alertError.iziModal('open'); } }); }; window.u_RenovarByUsuario = function (idLocker, idUsuario, fecha) { var param = {action:"renovaUser", idl: idLocker, idU: idUsuario, dia: fecha }; $.ajax({ type: "POST", url: domin, data: param, success: function (response) { console.log(response); window.location.href = "imprimir.html?Concepto=Renovar&idl=" + idLocker + "&id=" + idUsuario; }, error: function (e) { console.log(e); alertError.iziModal('open'); } }); }; window.u_RenovarByAdmin = function (idLocker, idUsuario, idRentador, Comentarios, fecha) { var param = {action:"renovaAdmin", idl: idLocker, idU: idUsuario, idRen: idRentador, com: Comentarios, dia: fecha }; $.ajax({ type: "POST", url: domin, data: param, success: function (response) { console.log(response); window.location.href = "imprimir.html?Concepto=Renovar&idl=" + idLocker + "&id=" + idUsuario; }, error: function (e) { console.log(e); alertError.iziModal('open'); } }); }; s_usuario(); s_Seccion(); $('#Renovar_Matricula').on('change', function () { var idU= $(this).val(); if (objSess.idtipo != 1) { s_LockerByUserOcupado(objSess.id, idSec); } else { s_LockerByUserOcupado(idU, $('#Renovar_Seccion').val()); } }); $('#Renovar_Seccion').on('change', function () { var idSec = $(this).val(); if (objSess.idtipo != 1) { s_LockerByUserOcupado(objSess.id, idSec); } else { s_LockerByUserOcupado($('#Renovar_Matricula').val(), idSec); } }); function resetImgLocker() { $('#imgDelLocker').removeClass('img_5') .removeClass('img_1') .removeClass('img_2') .removeClass('img_3') .removeClass('img_4'); $('#precioLock').empty(); } function ImgLocker() { var numeroLocker = $('#Renovar_NumLocker option:selected').text(); if (numeroLocker.match("^11") || numeroLocker.match("^21")) { //console.log('arriba!'); resetImgLocker(); $('#precioLock').text('$80'); $('#imgDelLocker').addClass('img_1'); } if (numeroLocker.match("^12") || numeroLocker.match("^22")) { //console.log('segundo!'); resetImgLocker(); $('#precioLock').text('$60'); $('#imgDelLocker').addClass('img_2'); } if (numeroLocker.match("^13") || numeroLocker.match("^23")) { //console.log('tercero!'); resetImgLocker(); $('#precioLock').text('$40'); $('#imgDelLocker').addClass('img_3'); } if (numeroLocker.match("^14") || numeroLocker.match("^24")) { //console.log('abajo!'); resetImgLocker(); $('#precioLock').text('$20'); $('#imgDelLocker').addClass('img_4'); } } $('#Renovar_NumLocker').on('change', function () { ImgLocker(); }); $('#Renovar').on('click', function () { var idNumLocker = $('#Renovar_NumLocker').val(); var byMatri = $('#Renovar_Matricula').val(); var comment = $('#coment_renov').val(); var checkCom = ''; if (comment == '') {checkCom = '-';} else { checkCom = comment; } if (idNumLocker == null) { console.log('nel no tienes'); } else { if (objSess.idtipo != 1) { u_RenovarByUsuario(idNumLocker, objSess.id, fecha); } else { u_RenovarByAdmin(idNumLocker, byMatri, objSess.id, checkCom, fecha); } } }); });
// const express = require('express') // const router = express.Router() // const fs = require('fs') // const shops = require('../Database/shops.json') // router.get('/', (req, res) => { // res.send(shops) // }) // router.get('/:id', (req, res) => { // const shopsInventory = shops.find(shop => { // return shop.id == req.params.id // }) // shopsInventory // ? res.send(shopsInventory) // : res.status(404).send('That item does not exist') // }) // module.exports = router
const { Router } = require('express'); const { clientesGet, clientesPost, clientesPut, clientesDelete } = require('../controllers/clientes'); const router = Router(); router.get('/', clientesGet); router.post('/', clientesPost); router.put('/:id', clientesPut); router.delete('/', clientesDelete ); module.exports = router;
import React from 'react' import './index.css' import img1 from '../../imgs/1.png' import img3 from '../../imgs/3.png' export default class Page1 extends React.Component { constructor() { super() this.state = { offOn: true, } } click() { let { offOn } = this.state; console.log(offOn) this.setState({ offOn:false }, () => { if (offOn) { offOn = !offOn; this.ratating() } }) } ratating() { let { offOn } = this.state; let oTurntable = document.querySelector('.img3') let cat = 51.4; let num = 0; let timer = null; let rdm = 0; //随机度数 let that = this; clearInterval(timer); timer = setInterval(function () { if (Math.floor(rdm / 360) < 3) { rdm = Math.floor(Math.random() * 3600); } else { oTurntable.style.transform = "rotate(" + rdm + "deg)"; clearInterval(timer); setTimeout(function () { that.setState({ offOn: !offOn }) num = rdm % 360; let o = { 0: () => alert("4999元"), 1: () => alert("50元"), 2: () => alert("10元"), 3: () => alert("5元"), 4: () => alert("免息服务"), 5: () => alert("提交白金"), 6: () => alert("未中奖"), } o[Math.floor(num/cat)]() }, 4000); } }, 30); } render() { return ( <div> Page1 <div className='bgdiv'> <img className="img1" src={img1} alt="pointer" onClick={() => { this.click() }} /> <img className="img3" src={img3} alt="turntable" /> </div> </div> ) } }
/// <reference path="jquery-3.2-vsdoc2.js" /> /*=========================================================================== // Copyright (C) 2010 爱橙科技 // 作者:吴岸标 // 创建日期:2010-03-25 // 功能描述:模型列表页面通用的JS功能代码 ===========================================================================*/ var HQB_Model_AddUrlParam_; $(pageInit); function pageInit() { // 当没有搜索项时隐藏搜索按钮 displaySearchBtn(); // 截取(长度限制)列表中的字符串 clipListItemContent(); // 为复选框注册点击事件 checkBoxInit(); // 给文本链接加URL传递参数 AddDeliverUrlParam(); $("#btnNew").click(function() { location.href = $("#btnNew").attr("Href") + "&" + HQB_Model_AddUrlParam_; }); $("body").find("input[BtnType='Edit']").each(function() { $(this).click(function() { location.href = $(this).attr("Href") + "&" + HQB_Model_AddUrlParam_; }) }); } // 为复选框注册点击事件 function checkBoxInit() { if ($("#SlectAll")[0] != null) { $("#SlectAll").click(function() { if ($(this).attr("checked") == true) { $("#HQB_ListInfo").find("input[type='checkbox']").each(function() { $(this).attr("checked", "checked"); $(this).parent().parent().addClass("trclick"); } ); $(this).parent().parent().removeClass("trclick"); } else { $("#HQB_ListInfo").find("input[type='checkbox']").each(function() { $(this).removeAttr("checked"); $(this).parent().parent().removeClass("trclick"); } ); } }); } $(".listInfotr").each(function(i) { $(this).click(function() { var chkArray = $(this).children("td").children(":checkbox"); if (chkArray.length > 0) { var b = chkArray[0].checked; var src = arguments[0].target || window.event.srcElement; if (b) { if (src.type != 'checkbox' && src.tagName != "A") { //避免重复2次修改 $(this).removeClass("trclick"); chkArray[0].checked = false; } } else { if (src.type != 'checkbox') { //避免重复2次修改 $(this).addClass("trclick"); chkArray[0].checked = true; } } } }) }) } // 当没有搜索项时隐藏搜索按钮 function displaySearchBtn() { var i = 0; $("#searchContainer").find("ul li").each(function() { i++; }); if (i < 2) { $("#searchContainer").hide(); } } // 列表中复选框全选或取消 function isSelected() { var isTrue; var titleContent; titleContent = ""; isTrue = false; $("#_ListInfoListTable").find("input[type='checkbox']:not('#SlectAll')").each(function() { if ($(this).attr("checked") == true) { if (titleContent == "") { titleContent = $("#Title_" + $(this).val()).text(); } else { titleContent = titleContent + "," + $("#Title_" + $(this).val()).text(); } isTrue = true; } } ); if (!isTrue) { alert({ msg: '请选择要操作的记录!', title: '提示信息' }) } $("#hidLogTitle").val(titleContent); return isTrue; } // 给文本链接加URL传递参数 function AddDeliverUrlParam() { var deliverUrlParam, backDeliverUrlParam; var arrDeliverUrlParam, arrBackDeliverUrlParam; var arrTemp; HQB_Model_AddUrlParam_ = ""; deliverUrlParam = $("#HQB_Model_DeliverUrlParam").val(); backDeliverUrlParam = $("#HQB_BackUrlParam").val(); arrDeliverUrlParam = deliverUrlParam.split("&") arrBackDeliverUrlParam = backDeliverUrlParam.split("&"); for (var i = 0; i < arrDeliverUrlParam.length; i++) { for (var k = 0; k < arrBackDeliverUrlParam.length; k++) { if (arrDeliverUrlParam[i] == arrBackDeliverUrlParam[k]) { arrBackDeliverUrlParam[i] = ""; break; } } } for (var m = 0; m < arrDeliverUrlParam.length; m++) { if (arrDeliverUrlParam[m] != "") { if (HQB_Model_AddUrlParam_ != "") { HQB_Model_AddUrlParam_ = HQB_Model_AddUrlParam_ + "&" + arrDeliverUrlParam[m]; } else { HQB_Model_AddUrlParam_ = arrDeliverUrlParam[m]; } } } if (arrBackDeliverUrlParam != null && arrBackDeliverUrlParam.length > 0) { if (HQB_Model_AddUrlParam_ != "") { HQB_Model_AddUrlParam_ = HQB_Model_AddUrlParam_ + "&" + arrBackDeliverUrlParam.join("&"); } else { HQB_Model_AddUrlParam_ = arrBackDeliverUrlParam.join("&"); } } if (HQB_Model_AddUrlParam_ != "") { $("body").find("a").each(function() { if ($(this).attr("href") != null) { try { if ($(this).attr("href").indexOf("?") > -1) { arrTemp = $(this).attr("href").split("?")[1].split("&"); for (var k = 0; k < arrTemp.length; k++) { for (var m = 0; m < arrBackDeliverUrlParam.length; m++) { if (arrTemp[k] == arrBackDeliverUrlParam[m]) { arrTemp[k] = ""; } } } if (arrTemp.length > 0) { $(this).attr("href", $(this).attr("href").split("?")[0] + "?" + arrTemp.join("&") + "&" + HQB_Model_AddUrlParam_); } else { $(this).attr("href", $(this).attr("href").split("?")[0] + "?" + HQB_Model_AddUrlParam_); } } else { $(this).attr("href", $(this).attr("href") + "?" + HQB_Model_AddUrlParam_); } } catch (e) { } } }); } } function checkNum(numValue) { if (numValue == null || numValue == "") return false; for (k = 0; k < numValue.length; k++) { if (("0123456789").indexOf(numValue.substr(k, 1)) == -1) { return false; } } return true; } function setOrders(tableName, id, orderValue) { var param; if (!checkNum(orderValue)) { alert({ msg: "排序号必须是数字!", title: "操作提示" }); return; } param = "{tableName:'" + tableName + "',id:'" + id + "',orderValue:" + orderValue + "}"; if ($("#HQB_Orders_" + id)[0] != null) { $("#HQB_Orders_" + id).find("div").each(function() { $(this).css("display", "block"); }); $("#HQB_Orders_" + id).find("span").each(function() { $(this).css("display", "none"); }); } $.ajax( { type: "POST", contentType: "application/json", url: "/sysadmin/Model/ModelAjaxDeal.asmx/SetOrder", data: param, dataType: 'json', success: function(result) { if ($("#HQB_Orders_" + id)[0] != null) { $("#HQB_Orders_" + id).find("div").each(function() { $(this).css("display", "none"); }); $("#HQB_Orders_" + id).find("span").each(function() { $(this).css("display", "block"); }); } }, error: function(XMLHttpRequest, textStatus, errorThrown) { if ($("#HQB_Orders_" + id)[0] != null) { $("#HQB_Orders_" + id).find("div").each(function() { $(this).css("display", "none"); }); $("#HQB_Orders_" + id).find("span").each(function() { $(this).css("display", "block"); $(this).find("input[type='text']").each(function() { $(this).val("更新失败请重试"); }); }); } } } ); } //截取(长度限制)列表中的字符串 function clipListItemContent() { var strWidth; var width; var strCount; $("#HQB_ListInfo ul li[isClip='1']").mouseover(function() { var position = $(this).position(); $("#HQB_Replcae_Title_Display").css("width", $(this).css("width")); $("#HQB_Replcae_Title_Display").css("top", position.top + "px"); $("#HQB_Replcae_Title_Display").css("left", position.left + "px"); $("#HQB_Replcae_Title_Display table tr td").html($(this).html()); $("#HQB_Replcae_Title_Display").css("display", "block"); } ); } // 打开链接页,并需要传递当前页(调用页)地址 function setLocation(url) { var deliverUrlParam; deliverUrlParam = "OriginalUrl={page:" + $("#hdnTableName").val().replace("K_U_", "").replace("K_F_", "") + ",nodeCode:" + $("#hdnNodeCode").val() + "}&&NodeCode=" + $("#hdnNodeCode").val(); deliverUrlParam += $("#HQB_Model_DeliverUrlParam").val(); deliverUrlParam = removeRepeatParam(deliverUrlParam); window.location.href = url + deliverUrlParam; } // 返回调用页 function backOriginalUrl(urlParam) { var url, backUrlParm; url = urlParam.page + "list.aspx?"; backUrlParm = "NodeCode=" + urlParam.nodeCode + "&" + $("#HQB_BackUrlParam").val(); backUrlParm = removeRepeatParam(backUrlParm); window.location.href = url + backUrlParm; } // 删除重复的URL参数 function removeRepeatParam(urlParam) { var arrParam, arrResult; var result = ""; var checkISAdded = ","; var filedName; if (urlParam != "") { arrParam = urlParam.split("&"); arrResult = new Array(arrParam.length); for (var i = 0; i < arrParam.length; i++) { if (arrParam[i] != "") { filedName = arrParam[i].split("=")[0]; if (filedName != null && filedName != "" != undefined) { if (checkISAdded.indexOf("," + filedName + ",") < 0) { arrResult[i] = arrParam[i]; checkISAdded += filedName + ","; } } } } for (var i = 0; i < arrResult.length; i++) { if (arrResult[i] != "" && arrResult[i] != null && arrResult[i] != undefined) { if (result == "") { result = arrResult[i]; } else { result += "&" + arrResult[i]; } } } } return result; } var HQB_Log_IsValide; var HQB_Log_ID; var HQB_CommandObject; HQB_Log_IsValide = false; // 按钮操作 function setAction(action) { var reg; reg = /.*\.[a-zA-Z]+.*/gi; if (reg.test(action)) { window.open(action); } else { $("#HQB_Action").val(action); return isSelected(); } } // 按钮操作 function confirmSetAction(obj, action, message) { HQB_CommandObject = obj; selfconfirm({ msg: message, fn: function(data) { SetSubmitCommand(data, action) } }) return HQB_Log_IsValide; } function reConfirm(obj, message) { if (!HQB_Log_IsValide) { selfconfirm({ msg: message, fn: function (data) { setTitle(data) } }) } return HQB_Log_IsValide; } function SetSubmitCommand(data, action) { if (data == "true") { if (isSelected()) { if (HQB_CommandObject) { $("#HQB_Action").val(action); HQB_Log_IsValide = true; $(HQB_CommandObject).click(); } } else { } } } // Repeater中的按钮操作 function rptConfirmSetAction(obj, action, message) { HQB_CommandObject = obj; selfconfirm({ msg: message, fn: function(data) { SetRptSubmitCommand(data, action) } }) return HQB_Log_IsValide; } function SetRptSubmitCommand(data, action) { if (data == "true") { if (HQB_CommandObject) { $("#HQB_Action").val(action); HQB_Log_IsValide = true; $("#hidLogTitle").val($("#Title_" + $(HQB_CommandObject).attr("RecordID")).text()); $(HQB_CommandObject).click(); } } } // 记录批量添加至专题 function batchSpecialSet() { var id = "", urlAddress = ""; $("#_ListInfoListTable").find("input[type='checkbox']:not('#SlectAll')").each(function() { if ($(this).attr("checked") == true) { isTrue = true; id = id + $(this).val() + ","; } } ); if (id != "") { id = id.substr(0, id.length - 1); urlAddress = "AppendToSpecial.aspx?action=content&id=" + id + "&modelid=" + $("#hdnModelID").val() + "&NodeCode=" + $("#hdnNodeCode").val(); openframe({ title: "添加到专题栏目", url: urlAddress, width: '640', height: '280' }) } else { alert({ msg: '请选择要添加的记录项!', title: '提示信息' }) } } // 记录批量添加至节点(栏目) function batchNodeSet() { var id = "", urlAddress = ""; $("#_ListInfoListTable").find("input[type='checkbox']:not('#SlectAll')").each(function() { if ($(this).attr("checked") == true) { isTrue = true; id = id + $(this).val() + ","; } } ); if (id != "") { id = id.substr(0, id.length - 1); urlAddress = "AppendToNode.aspx?id=" + id + "&modelid=" + $("#hdnModelID").val() + "&NodeCode=" + $("#hdnNodeCode").val(); openframe({ title: "添加到节点/栏目", url: urlAddress, width: '640', height: '280' }) } else { alert({ msg: '请选择要添加的记录项!', title: '提示信息' }) } } // 关闭Dialog function CloseDialog() { $("body").find("#norDialog").remove().end(); $("#norDialogBackground").remove(); } // 排序 sortType 1 只要升序 2 只要降序 3 两者皆要 function sort(fieldName, sortType) { var sortStr, frontSort, ascSort, descSort, urlParam; ascSort = fieldName + " asc "; descSort = fieldName + " desc "; frontSort = getCookie("_ContentTemplateListSort_"); switch (sortType) { case "1": sortStr = ascSort; setCookies("_ContentTemplateListSort_", "1"); break; case "2": sortStr = descSort; setCookies("_ContentTemplateListSort_", "0"); break; case "3": if (frontSort == null || frontSort == "") { sortStr = ascSort; setCookies("_ContentTemplateListSort_", "1"); } else if (frontSort == "1") { sortStr = descSort; setCookies("_ContentTemplateListSort_", "0"); } else { sortStr = ascSort; setCookies("_ContentTemplateListSort_", "1"); } break; default: sortStr = ""; break; } try { urlParam = getUrlParam("&Sort=" + $("#hdnTableName").val()); if (urlParam != null) { sortStr = urlParam + "&Sort=" + sortStr; } else { sortStr = "?Sort=" + sortStr; } } catch (e) { sortStr = "?Sort=" + sortStr; } location.href = sortStr; } // 获取当前URL中的参数部分 function getUrlParam(filterContent) { var urlParam; var reg; var matchArr; reg = new RegExp("[?]{1}(([a-z A-Z 0-9 _]+)[=]{1}([a-z A-Z 0-9 _]+)[&]{0,1})+"); matchArr = reg.exec(location.href); if (matchArr != null) { urlParam = matchArr[0]; urlParam = urlParam.replace(filterContent, ""); } else { urlParam = null; } return urlParam; } // 关闭弹出的对话框,再弹出另外一个 function closeFrameAndOpenDilog(obj) { CloseDialog(); alert(obj); } var isOpen = true; $(function() { var SortArr = SortList.split(","); $('tbody').sortable({ items: 'tr:not(:first)', handle: '.dragOrders', stop: function(event, ui) { var tableName = $("#hdnTableName").val(); var idList = ""; $(".listInfotr").find("input[type='checkbox']").each(function() { if (idList == "") idList = $(this).val(); else idList += "," + $(this).val(); }); var param; param = "{tableName:'" + tableName + "',idlist:'" + idList + "',sortList:'" + SortList + "'}"; $.ajax( { type: "POST", contentType: "application/json", url: "/sysadmin/Model/ModelAjaxDeal.asmx/SetOrderDrag", data: param, dataType: 'json', success: function(result) { var k = 0; $(".listInfotr").find("input[type='text']").each(function() { $(this).val(SortArr[k]); k++; }); }, error: function(XMLHttpRequest, textStatus, errorThrown) { alert({ msg: '排序更新数据失败!', title: '操作提示' }) } } ); } }); }); function CloseOrOpenSortTable(obj) { if (isOpen) { $('tbody').sortable('disable'); obj.value = "开启拖动排序" isOpen = false; } else { $('tbody').sortable('enable'); obj.value = "关闭拖动排序" isOpen = true; } }
const UnauthorizedError = require('./UnauthorizedError'); class TokenExpiredError extends UnauthorizedError { constructor(type = 'token_exired', message = 'Token expired') { super(type, message); } } module.exports = TokenExpiredError;
// write a CLI program // you can pass in a file name // the program will count the number of lines of code // print it in the console // node loc.js ex1.js // 24 // node loc.js ex2.js // 17 // node loc.js loc.js // 11 // hint: you need the fs module & process.argv var fs = require('fs'); var buffer = fs.readFileSync( process.argv[2] ); var lines = buffer.toString().split('\n'); console.log(lines.length);
const { cpus } = require('os'); const cpusName = () => { const result = cpus(); const names = result.map((item) => { console.log(item.model); return item.model; }); console.log('Name:',names); const speed = result.map((item) => { console.log(item.speed); return item.speed; }); console.log('Speed:',speed); }; cpusName(); module.exports.cpusName = cpusName;
'use strict'; //create logger const log = require('Utils/logger.js'); const logger = log.getLogger(); const mongoose = require('mongoose'); const joi = require('joi'); let pushSchema = mongoose.Schema({ seeker_id : String, provider_id : String, provider_name : String, seeker_name : String, seeker_image : { original : {type: String, default: null}, thumbnail : {type: String, default: null} }, provider_image : { original : {type: String, default: null}, thumbnail : {type: String, default: null} }, booking_datetime : String, booking_type : String, ODS_type : String, booking_id : String, push_date : String, push_type : String, message : String, is_read : { type : Boolean , default : false} //seeker_name :String, //seeker_device_token :String, //seeker_device_type :String, //gig_id : String, //gig_name : String, //bid_amount : String, //tools : {type:Boolean,default:false}, //supplies : {type:Boolean,default:false}, //description : String, //unit : String, //quantity : String, //is_seeker_location :Boolean, //virtual_address :String, /*booking_address :{ Address1 :String, Address2 :String, City :String, State :String, ZipCode :String, Country :String }, booking_latitude :String, booking_longitude :String, booking_address1:{ Address1 :String, Address2 :String, City:String, State:String, ZipCode:String, Country:String, }, booking_latitude1:String, booking_longitude1:String, first_name: {type: String, required: true}, last_name: {type: String, required: true},*/ //provider_device_token :String, //provider_device_type :String }, { collection : 'push' } ) module.exports.pushSchema = mongoose.model('pushSchema', pushSchema,'push');
import { Component } from "react"; import { connect } from "react-redux"; import { Redirect } from "react-router"; import { handleAddQuestion } from "../../actions/questions"; class New extends Component { state = { optionOne: "", optionTwo: "", redirect: false }; handleOptionOne = (e) => { this.setState({ optionOne: e.target.value }); }; handleOptionTwo = (e) => { this.setState({ optionTwo: e.target.value }); }; handleSubmit = (e) => { e.preventDefault(); const { optionOne, optionTwo } = this.state; const { dispatch } = this.props; dispatch(handleAddQuestion(optionOne, optionTwo)); this.setState({ optionOne: "", optionTwo: "", redirect: true }); }; render() { if (this.state.redirect) return <Redirect to="/" />; const submitDisabled = this.state.optionOne === "" || this.state.optionTwo === ""; return ( <div className="view"> <h1>Create New Poll</h1> <div className="list-item"> <p className="question-label">Would You Rather</p> <form onSubmit={this.handleSubmit}> <input placeholder="First option" className="input" onChange={this.handleOptionOne} value={this.state.optionOne} ></input> <p className="question-label">OR</p> <input placeholder="Second option" className="input" onChange={this.handleOptionTwo} value={this.state.optionTwo} ></input> <div> <button type="submit" className="submit" disabled={submitDisabled} > Submit </button> </div> </form> </div> </div> ); } } export default connect()(New);
import includes from 'lodash/includes' import memoize from '../utils/memoize' import { Record } from 'immutable' /** * Start-and-end convenience methods to auto-generate. */ const START_END_METHODS = [ 'collapseTo%' ] /** * Start-end-and-edge convenience methods to auto-generate. */ const EDGE_METHODS = [ 'has%AtStartOf', 'has%AtEndOf', 'has%Between', 'has%In' ] /** * Default properties. */ const DEFAULTS = { anchorKey: null, anchorOffset: 0, focusKey: null, focusOffset: 0, isBackward: null, isFocused: false } /** * Selection. */ class Selection extends new Record(DEFAULTS) { /** * Create a new `Selection` with `properties`. * * @param {Object} properties * @return {Selection} selection */ static create(properties = {}) { if (properties instanceof Selection) return properties return new Selection(properties) } /** * Get the kind. * * @return {String} kind */ get kind() { return 'selection' } /** * Get whether the selection is blurred. * * @return {Boolean} isBlurred */ get isBlurred() { return !this.isFocused } /** * Get whether the selection is collapsed. * * @return {Boolean} isCollapsed */ get isCollapsed() { return ( this.anchorKey == this.focusKey && this.anchorOffset == this.focusOffset ) } /** * Get whether the selection is expanded. * * @return {Boolean} isExpanded */ get isExpanded() { return !this.isCollapsed } /** * Get whether the selection is forward. * * @return {Boolean} isForward */ get isForward() { return this.isBackward == null ? null : !this.isBackward } /** * Get the start key. * * @return {String} startKey */ get startKey() { return this.isBackward ? this.focusKey : this.anchorKey } get startOffset() { return this.isBackward ? this.focusOffset : this.anchorOffset } get endKey() { return this.isBackward ? this.anchorKey : this.focusKey } get endOffset() { return this.isBackward ? this.anchorOffset : this.focusOffset } /** * Check whether anchor point of the selection is at the start of a `node`. * * @param {Node} node * @return {Boolean} */ hasAnchorAtStartOf(node) { if (this.anchorOffset != 0) return false const first = node.kind == 'text' ? node : node.getTexts().first() return this.anchorKey == first.key } /** * Check whether anchor point of the selection is at the end of a `node`. * * @param {Node} node * @return {Boolean} */ hasAnchorAtEndOf(node) { const last = node.kind == 'text' ? node : node.getTexts().last() return this.anchorKey == last.key && this.anchorOffset == last.length } /** * Check whether the anchor edge of a selection is in a `node` and at an * offset between `start` and `end`. * * @param {Node} node * @param {Number} start * @param {Number} end * @return {Boolean} */ hasAnchorBetween(node, start, end) { return ( this.anchorOffset <= end && start <= this.anchorOffset && this.hasAnchorIn(node) ) } /** * Check whether the anchor edge of a selection is in a `node`. * * @param {Node} node * @return {Boolean} */ hasAnchorIn(node) { const nodes = node.kind == 'text' ? [node] : node.getTexts() return nodes.some(n => n.key == this.anchorKey) } /** * Check whether focus point of the selection is at the end of a `node`. * * @param {Node} node * @return {Boolean} */ hasFocusAtEndOf(node) { const last = node.kind == 'text' ? node : node.getTexts().last() return this.focusKey == last.key && this.focusOffset == last.length } /** * Check whether focus point of the selection is at the start of a `node`. * * @param {Node} node * @return {Boolean} */ hasFocusAtStartOf(node) { if (this.focusOffset != 0) return false const first = node.kind == 'text' ? node : node.getTexts().first() return this.focusKey == first.key } /** * Check whether the focus edge of a selection is in a `node` and at an * offset between `start` and `end`. * * @param {Node} node * @param {Number} start * @param {Number} end * @return {Boolean} */ hasFocusBetween(node, start, end) { return ( start <= this.focusOffset && this.focusOffset <= end && this.hasFocusIn(node) ) } /** * Check whether the focus edge of a selection is in a `node`. * * @param {Node} node * @return {Boolean} */ hasFocusIn(node) { const nodes = node.kind == 'text' ? [node] : node.getTexts() return nodes.some(n => n.key == this.focusKey) } /** * Check whether the selection is at the start of a `node`. * * @param {Node} node * @return {Boolean} isAtStart */ isAtStartOf(node) { const { isExpanded, startKey, startOffset } = this if (isExpanded) return false if (startOffset != 0) return false const first = node.kind == 'text' ? node : node.getTexts().first() return startKey == first.key } /** * Check whether the selection is at the end of a `node`. * * @param {Node} node * @return {Boolean} isAtEnd */ isAtEndOf(node) { const { endKey, endOffset, isExpanded } = this if (isExpanded) return false const last = node.kind == 'text' ? node : node.getTexts().last() return endKey == last.key && endOffset == last.length } /** * Normalize the selection, relative to a `node`, ensuring that the anchor * and focus nodes of the selection always refer to leaf text nodes. * * @param {Node} node * @return {Selection} selection */ normalize(node) { let selection = this const { isCollapsed } = selection let { anchorKey, anchorOffset, focusKey, focusOffset, isBackward } = selection // If the selection isn't formed yet or is malformed, set it to the // beginning of the node. if ( anchorKey == null || focusKey == null || !node.hasDescendant(anchorKey) || !node.hasDescendant(focusKey) ) { const first = node.getTexts().first() return selection.merge({ anchorKey: first.key, anchorOffset: 0, focusKey: first.key, focusOffset: 0, isBackward: false }) } // Get the anchor and focus nodes. let anchorNode = node.getDescendant(anchorKey) let focusNode = node.getDescendant(focusKey) // If the anchor node isn't a text node, match it to one. if (anchorNode.kind != 'text') { let anchorText = anchorNode.getTextAtOffset(anchorOffset) let offset = anchorNode.getOffset(anchorText) anchorOffset = anchorOffset - offset anchorNode = anchorText } // If the focus node isn't a text node, match it to one. if (focusNode.kind != 'text') { let focusText = focusNode.getTextAtOffset(focusOffset) let offset = focusNode.getOffset(focusText) focusOffset = focusOffset - offset focusNode = focusText } // If `isBackward` is not set, derive it. if (isBackward == null) { let texts = node.getTexts() let anchorIndex = texts.indexOf(anchorNode) let focusIndex = texts.indexOf(focusNode) isBackward = anchorIndex == focusIndex ? anchorOffset > focusOffset : anchorIndex > focusIndex } // Merge in any updated properties. return selection.merge({ anchorKey: anchorNode.key, anchorOffset, focusKey: focusNode.key, focusOffset, isBackward }) } /** * Focus the selection. * * @return {Selection} selection */ focus() { return this.merge({ isFocused: true }) } /** * Blur the selection. * * @return {Selection} selection */ blur() { return this.merge({ isFocused: false }) } /** * Move the focus point to the anchor point. * * @return {Selection} selection */ collapseToAnchor() { return this.merge({ focusKey: this.anchorKey, focusOffset: this.anchorOffset, isBackward: false }) } /** * Move the anchor point to the focus point. * * @return {Selection} selection */ collapseToFocus() { return this.merge({ anchorKey: this.focusKey, anchorOffset: this.focusOffset, isBackward: false }) } /** * Move to the start of a `node`. * * @return {Selection} selection */ collapseToStartOf(node) { return this.merge({ anchorKey: node.key, anchorOffset: 0, focusKey: node.key, focusOffset: 0, isBackward: false }) } /** * Move to the end of a `node`. * * @return {Selection} selection */ collapseToEndOf(node) { return this.merge({ anchorKey: node.key, anchorOffset: node.length, focusKey: node.key, focusOffset: node.length, isBackward: false }) } /** * Move to the entire range of `start` and `end` nodes. * * @param {Node} start * @param {Node} end (optional) * @return {Selection} selection */ moveToRangeOf(start, end = start) { return this.merge({ anchorKey: start.key, anchorOffset: 0, focusKey: end.key, focusOffset: end.length, isBackward: start == end ? false : null }) } /** * Move the selection forward `n` characters. * * @param {Number} n (optional) * @return {Selection} selection */ moveForward(n = 1) { return this.merge({ anchorOffset: this.anchorOffset + n, focusOffset: this.focusOffset + n }) } /** * Move the selection backward `n` characters. * * @param {Number} n (optional) * @return {Selection} selection */ moveBackward(n = 1) { return this.merge({ anchorOffset: this.anchorOffset - n, focusOffset: this.focusOffset - n }) } /** * Move the selection to `anchor` and `focus` offsets. * * @param {Number} anchor * @param {Number} focus (optional) * @return {Selection} selection */ moveToOffsets(anchor, focus = anchor) { return this.merge({ anchorOffset: anchor, focusOffset: focus, isBackward: null }) } /** * Extend the focus point forward `n` characters. * * @param {Number} n (optional) * @return {Selection} selection */ extendForward(n = 1) { return this.merge({ focusOffset: this.focusOffset + n, isBackward: null }) } /** * Extend the focus point backward `n` characters. * * @param {Number} n (optional) * @return {Selection} selection */ extendBackward(n = 1) { return this.merge({ focusOffset: this.focusOffset - n, isBackward: null }) } /** * Extend the focus point to the start of a `node`. * * @param {Node} node * @return {Selection} selection */ extendToStartOf(node) { return this.merge({ focusKey: node.key, focusOffset: 0, isBackward: null }) } /** * Extend the focus point to the end of a `node`. * * @param {Node} node * @return {Selection} selection */ extendToEndOf(node) { return this.merge({ focusKey: node.key, focusOffset: node.length, isBackward: null }) } } /** * Add start, end and edge convenience methods. */ START_END_METHODS.concat(EDGE_METHODS).forEach((pattern) => { const [ p, s ] = pattern.split('%') const anchor = `${p}Anchor${s}` const edge = `${p}Edge${s}` const end = `${p}End${s}` const focus = `${p}Focus${s}` const start = `${p}Start${s}` Selection.prototype[start] = function (...args) { return this.isBackward ? this[focus](...args) : this[anchor](...args) } Selection.prototype[end] = function (...args) { return this.isBackward ? this[anchor](...args) : this[focus](...args) } if (!includes(EDGE_METHODS, pattern)) return Selection.prototype[edge] = function (...args) { return this[anchor](...args) || this[focus](...args) } }) /** * Memoize read methods. */ memoize(Selection.prototype, [ 'hasAnchorAtStartOf', 'hasAnchorAtEndOf', 'hasAnchorBetween', 'hasAnchorIn', 'hasFocusAtEndOf', 'hasFocusAtStartOf', 'hasFocusBetween', 'hasFocusIn', 'isAtStartOf', 'isAtEndOf' ]) /** * Export. */ export default Selection
const schemesModel = require("./schemes.model"); module.exports = { list:()=>{ return schemesModel.find(); }, getSingle:(code)=>{ return schemesModel.findOne({productCode:code}); } }
/** * randomInt * Generate a random number from 0 to max - 1 * randomInt(4) // return 0 or 1 or 2 or 3 */ function randomInt (max) { return Math.floor(Math.random() * max) } /* retrieve elements from HTML */ const tries = document.getElementById('tries') const correct = document.getElementById('correct') const board = document.getElementById('board') const blocks = document.getElementsByClassName('block') const submit = document.getElementById('submit') const reset = document.getElementById('reset') const message = document.getElementById('message') /* game object keep track of the game status */ const game = { active: false, tries: 0, correct: 0, codeLength: blocks.length, code: [], colors: ['red', 'blue', 'green', 'orange'] } /** * setCode * Randomly create the code for the game * and store it in game.code */ function setCode () { // Make a copy of game.colors to the colors variable const colors = game.colors.slice(0) // Create for loop to get a color for each block for (let i = 0; i < game.codeLength; i++) { // Random selects a color from the colors arrays, removes it // And stores the color to the color variable // Using splice to remove the color from the array // Splice return an array of the item remove // Using [0] to get the first item from the array returned const color = colors.splice(randomInt(colors.length), 1)[0] // Add color to code array. game.code.push(color) } } function checkCode () { game.correct = 0 if (game.active) { game.tries++ } for (let i = 0; i < game.codeLength; i++) { console.log(blocks[i].dataset.color, game.code[i]) if (blocks[i].dataset.color === game.code[i]) { game.correct++ } } if (game.correct === game.codeLength) { tries.textContent = game.tries correct.textContent = game.correct endGame() } else { tries.textContent = game.tries correct.textContent = game.correct } } function resetBoard () { for (const block of blocks) { block.classList.remove(block.dataset.color) block.classList.add('red') block.dataset.color = 'red' } } function rotateColor (el) { const index = game.colors.indexOf(el.dataset.color) const color = (index + 1 < game.colors.length ? game.colors[index+1] : game.colors[0]) el.classList.remove(el.dataset.color) el.classList.add(color) el.dataset.color = color } function endGame () { game.active = false message.classList.add('show') } function startGame () { game.active = false game.tries = 0 game.correct = 0 resetBoard() setCode() checkCode() message.classList.remove('show') game.active = true } board.addEventListener('click', function (event) { if (event.target.classList.contains('block')) { rotateColor(event.target) } }) document.addEventListener('keyup', function (event) { if (blocks[event.key - 1]) { rotateColor(blocks[event.key - 1]) } }) reset.addEventListener('click', startGame) submit.addEventListener('click', checkCode) startGame()
const { ObjectID } = require("mongodb"); const { mongoose } = require("./../server/db/mongoose.js"); const { Todo } = require("./../server/models/todo.js"); const { User } = require("./../server/models/user.js"); // Todo.remove({}) removes all documents // But does not return the document // Todo.remove({}).then(result => { // console.log(result); // }); // $ node playground/mongoose-remove.js // ...returns { n: 3, ok: 1 } // number deleted, 1 = success // Todo.findOneAndRemove and Todo.findByIdAndRemove // ...return the document // ...or null if nothing with that id found Todo.findByIdAndRemove("5af32cbf14f32bda1a83cc04").then(todo => { console.log(todo); }); // $ node playground/mongoose-remove.js // { completed: false, // completedAt: null, // _id: 5af32cbf14f32bda1a83cc04, // text: 'Something eles to do' } // Todo.findOneAndRemove({_id: "5af32cbf14f32bda1a83cc04"}).then(todo => { // console.log(todo); // });
console.log(5>2); console.log("apple" > "pineapple"); console.log("2" > "12"); console.log(undefined == null); console.log(undefined === null); console.log(null == "\n0\n"); console.log(null == +"\n0\n");
var express = require('express'); var app = express(); var mongodb = require('./routes/mongodb'); var mongoose = require('./routes/mongoose'); app.use('/mongodb', mongodb); app.use('/mongoose', mongoose); app.get('/', function (req, res) { res.send('Hello World!'); }); app.listen(3000, function () { console.log('Example app listening on port 3000!'); });
import React from 'react'; import styled, {keyframes} from 'styled-components' import {NavLink} from "react-router-dom"; export default ({isAdded, gds, toggleGds, addedOpacity, addGds = null}) => { return ( <Product className={addedOpacity && !isAdded && "removed"}> <Image backgroundImage={gds.img}/> <Inside> <Name>{gds.name}</Name> <Info>{gds.info}</Info> <Buttons> <Add className={isAdded && "active"} onClick={()=> {toggleGds(gds)}}>+</Add> { addGds !== null && <Pay onClick={()=> {addGds(gds)}} to={"/calc"}>Рассчет стоимости</Pay> } </Buttons> </Inside> </Product> ) } const fade = keyframes` 0% { opacity: 0; } 100% { opacity: 1; } `; const Inside = styled.div` position: relative; z-index: 1; display: flex; width: 100%; height: 100%; background: radial-gradient(258.00px at 50% 50%, rgba(255, 255, 255, 0) 0%, rgba(0, 0, 0, 0.5) 100%); opacity: 0; transition: 0.7s; padding: 20px; flex-direction: column; @media all and (max-width: 480px) { padding: 15px; } `; const Product = styled.div` display: flex; height: 300px; position: relative; box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.06); background-color: #fff; transition: 0.7s; animation: ${fade} 1.5s; &:not(:last-of-type) { margin-bottom: 20px; } &.removed { opacity: 0.6; } &:hover { box-shadow: 0px 4px 12px rgba(0, 0, 0, 0.1); ${Inside} { opacity: 1; } } `; const Image = styled.div` position: absolute; top: 0; left: 0; width: 100%; height: 100%; background-image: ${props => `url("${props.backgroundImage}")`}; -webkit-background-size: cover; background-size: cover; background-position: 50% 50%; `; const Name = styled.strong` color: #fff; font-family: "Lora",serif; font-size: 32px; margin-bottom: 10px; `; const Info = styled.p` color: #fff; font-weight: 600; font-size: 18px; flex-grow: 1; `; const Buttons = styled.div` display: flex; justify-content: flex-start; `; const Add = styled.div` width: 40px; height: 40px; font-weight: 800; font-size: 26px; line-height: 35px; text-align: center; border: 2px solid #8CDB90; color: #8CDB90; border-radius: 30px; margin-right: 10px; cursor: pointer; transition: 0.7s; &:hover { opacity: 0.9; } &.active { background-color: #8CDB90; color: #fff; } `; const Pay = styled(NavLink)` text-decoration: none; height: 40px; padding: 0 20px; border-radius: 40px; display: flex; font-weight: 600; align-items: center; justify-content: center; border: 2px solid #8CDB90; color: #8CDB90; cursor: pointer; transition: 0.7s; font-size: 16px; &:hover { background-color: #8CDB90; color: #fff; } `;
/** * static game constants */ var startLevel = 1; var logMultiplier = 9; var soundHold = 1; var pitch0 = 200; var pitch1 = 300; var pitch2 = 400; var pitch3 = 500; var moveInterval = 300; var sqAnimSpd = 100; var resultAnimInSpd = 800; var resultAnimOutSpd = 2000; var wKey = 87; var eKey = 69; var nKey = 78; var mKey = 77; var spaceKey = 32; var timerSpd = 500; /** * end static game constants */ var iconAnim = 500; var timer = null; var timeSecs = 3; var aiPlayer = null; var hPlayer = null; var gameInProgress = false; var isRecording = false; var level = startLevel; /*for sound in mobile browsers*/ var isFirstTap = true; $(document).ready(function(){ var navHeight = $('.navbar').height(); var windowResize = function(){ $('.main').css('height', $(window).height() - navHeight*2); $('.sq').css('height', (($(window).height() - navHeight*2)/2)); }; $(window).resize(function(){ windowResize(); }); $(window).load(function(){ windowResize(); }); var Move = function(color){ this.color = color; this.sound = new Wad({source: 'sine'}); this.sound.env.hold = soundHold switch(color){ case 0: this.pitch = pitch0; break; case 1: this.pitch = pitch1; break; case 2: this.pitch = pitch2; break; case 3: this.pitch = pitch3; break; default: } }; var Player = function(){ this.moves = []; this.moveCount = 0; this.timer = null; }; Player.prototype.playMove = function(){ initMove(this.moves[this.moveCount]); this.moveCount++; }; Player.prototype.playMoveSequence = function(){ this.timer = window.setInterval((function(){ if(this.moveCount < this.moves.length){ initMove(this.moves[this.moveCount]); this.moveCount++; }else{ this.moveCount = 0; window.clearInterval(this.timer); isRecording = true; } }).bind(this), moveInterval); }; Player.prototype.randMoves = function(numMoves){ for(var i = 0; i < numMoves; i++){ this.moves.push(new Move(getRandomInt(0,3))); } }; Player.prototype.recordMoveSequence = function(){ if(aiPlayer.moves.length >= hPlayer.moves.length){ if(aiPlayer.moves[hPlayer.moveCount].color === hPlayer.moves[hPlayer.moveCount].color){ gameInProgress = false; if(aiPlayer.moves.length === hPlayer.moves.length){ isRecording = false; resultToScreen(true); level += 1; updateLevel(); } }else{ resultToScreen(false); isRecording = false; gameInProgress = false; level = startLevel; } }else{ isRecording = false; gameInProgress = false; } }; var updateLevel = function(){ $('.level').html('round: ' + level); } var initGame = function(){ aiPlayer = new Player(); hPlayer = new Player(); var logLevel = Math.floor(Math.log(level*logMultiplier)) aiPlayer.randMoves(logLevel); aiPlayer.playMoveSequence(hPlayer.recordMoveSequence); }; var initMove = function(obj){ $('.sq-' + obj.color).animate({opacity: 0.5}, sqAnimSpd, function(){ obj.sound.play({pitch: obj.pitch}); $('.sq-' + obj.color).animate({opacity: 1.0}, sqAnimSpd); }); }; var resultToScreen = function(isSuccess){ if(isSuccess){ $('.main').prepend('<div class="result-display">{0}</div>'.supplant(['WIN'])); $('.result-display').fadeOut(0); $('.result-display').fadeIn(resultAnimInSpd, function(){ $(this).fadeOut(resultAnimOutSpd, function(){ $(this).remove(); }); }); }else{ $('.main').prepend('<div class="result-display">{0}</div>'.supplant(['FAIL'])); $('.result-display').fadeOut(0); $('.result-display').fadeIn(resultAnimInSpd, function(){ $(this).fadeOut(resultAnimOutSpd, function(){ $(this).remove(); }); }); } }; var startTimer = function(){ if(timer === null){ timeToScreen(); timer = window.setInterval(timeToScreen, timerSpd); }else{ clearInterval(timer); timer = null; timeSecs = 3; initGame(); $('.status').html('space to start'); }; }; var timeToScreen = function(){ $('.status').html(timeSecs); timeSecs--; if(timeSecs < 0){ startTimer(); }; }; $(document).on('keydown', function(e){ if(isRecording){ switch(e.which){ case wKey: hPlayer.moves.push(new Move(0)); hPlayer.recordMoveSequence(); hPlayer.playMove(); break; case eKey: hPlayer.moves.push(new Move(1)); hPlayer.recordMoveSequence(); hPlayer.playMove(); break; case nKey: hPlayer.moves.push(new Move(2)); hPlayer.recordMoveSequence(); hPlayer.playMove(); break; case mKey: hPlayer.moves.push(new Move(3)); hPlayer.recordMoveSequence(); hPlayer.playMove(); break; default: } } }); $(document).on('click, tap', '.sq', function(e){ // e.stopPropagation(); if(isRecording){ if($(this).hasClass('sq-0')){ hPlayer.moves.push(new Move(0)); hPlayer.recordMoveSequence(); hPlayer.playMove(); }else if($(this).hasClass('sq-1')){ hPlayer.moves.push(new Move(1)); hPlayer.recordMoveSequence(); hPlayer.playMove(); }else if($(this).hasClass('sq-2')){ hPlayer.moves.push(new Move(2)); hPlayer.recordMoveSequence(); hPlayer.playMove(); }else if($(this).hasClass('sq-3')){ hPlayer.moves.push(new Move(3)); hPlayer.recordMoveSequence(); hPlayer.playMove(); } }else{ if(!gameInProgress){ if(isFirstTap){ var startSound = new Wad({source: 'sine'}); startSound.env.hold = 0.1; startSound.setVolume(0.01); startSound.play({pitch: 50}); isFirstTap = false; } gameInProgress = true; updateLevel(); startTimer(); }else if(gameInProgress){ gameInProgress = false; level = startLevel; } } }); //spacebar $(document).on('keydown', function(e){ if(e.which === spaceKey){ if(!gameInProgress){ gameInProgress = true; updateLevel(); startTimer(); }else if(gameInProgress){ gameInProgress = false; level = startLevel; } } }); $(document).on('click, tap', '.start-btn', function(){ var startSound = new Wad({source: 'sine'}); startSound.play(); }); $(document).on('click, tap', '.start-game', function(){ if(!gameInProgress){ gameInProgress = true; updateLevel(); startTimer(); }else if(gameInProgress){ gameInProgress = false; level = startLevel; } }); $(document).on('click', '.new-game', function(){ gameInProgress = false; level = startLevel; updateLevel(); }) $('.li-icon img').hover(function(){ $(this).animate({opacity: 0.0}, iconAnim); }, function(){ $(this).animate({opacity: 1.0}, iconAnim); }); $('.gh-icon img').hover(function(){ $(this).animate({opacity: 0.0}, iconAnim); }, function(){ $(this).animate({opacity: 1.0}, iconAnim); }); $('.glyphicon-envelope').hover(function(){ $(this).animate({color: 'rgba(0, 122, 184, 1.0)'}, iconAnim); }, function(){ $(this).animate({color: 'rgba(0, 0, 0, 1.0)'}, iconAnim);; }); updateLevel(); $('.status').html('space to start'); });
'use strict'; angular.module('esn.inbox-james') .service('inboxJamesDeletedMessagesService', inboxJamesDeletedMessagesService); function inboxJamesDeletedMessagesService(inboxJamesRestangular) { return { submitRestoringRequest: submitRestoringRequest }; function submitRestoringRequest(targetUser, content) { return inboxJamesRestangular.all('restoringDeletedMessagesRequest').customPOST({ targetUser: targetUser, content: content }); } }
import React from 'react' import { Link as GLink } from 'gatsby' import { Link, useThemeUI, get } from 'theme-ui' import Avatar from '@components/Avatar' import { buildResponsiveVariant as rv } from '../../utils' const authorImageSize = 48 const CardFooterAuthorAvatar = ({ variant, omitAuthor, author }) => { const context = useThemeUI() if (omitAuthor) return null const responsiveVariant = rv(variant, 'authorPhoto') const visibility = responsiveVariant.reduce( (mobileVisibility, variant) => mobileVisibility === false && get(context.theme, variant, {}).display === 'none' ? false : true, false ) return visibility ? ( author && author.thumbnail ? ( <Link as={GLink} to={author.slug} aria-label={author.name} sx={{ variant: responsiveVariant }} > <Avatar avatar={author.thumbnail} width={authorImageSize} simple /> </Link> ) : null ) : null } export default CardFooterAuthorAvatar
var searchData= [ ['input',['Input',['../classInput.html',1,'']]], ['interactive_5feditor',['Interactive_editor',['../classInteractive__editor.html',1,'']]] ];
(function (window) { // Create object var helloSpeaker = {}; var speakWord = "Hello"; // Attach function to object helloSpeaker.speak = function (name) { console.log(speakWord + " " + name); } // Expose object to window window.helloSpeaker = helloSpeaker; }) (window); // Immediately invoke function
const mongoose = require('mongoose'); const Schema = mongoose.Schema; const bcrypt = require('bcryptjs'); const Asset = require('./asset.model.js'); const Job = require('./job.model'); const Education = require('./education.model'); const schema = new Schema({ username: { type: String, required: true }, hash: { type: String, required: true }, roles: { type: String, enum: ['admin', 'user'] }, retired: Boolean, age: Number, bank_account: Number, networth: Number, assets: [{ purchase_date: { type: Date }, asset_name: { type: Schema.Types.ObjectId, ref: 'Asset' } }], original_signup: Date, last_sign_in: Date, job: { start_date: {type: Date}, months_worked: {type: Number}, job_name: { type: Schema.Types.ObjectId, ref: 'Job' } }, activities: [{ wonReward: {type: Boolean}, activity_name: { type: Schema.Types.ObjectId, ref: 'Activity' } }], education: { type: Schema.Types.ObjectId, ref: 'Education' } }); schema.virtual('password').set(function(password) { this.hash = bcrypt.hashSync(password, 8); }); schema.methods.comparePassword = function(password) { return bcrypt.compareSync(password, this.hash); }; const User = mongoose.model('User', schema); module.exports = User;
import React from "react"; const Wizard = ({ player }) => { const x = player.x; const y = player.y; const width = player.width; const height = player.height; const isFacingRight = player.facingDirection === "right"; const health = player.health; let healthColor; switch (true) { case health < 30: healthColor = "red"; break; case health < 70: healthColor = "yellow"; break; case health < 101: default: healthColor = "lime"; break; } return ( <div style={{ position: "absolute", left: x - width / 2, bottom: y - height / 2, width: width, height: height, backgroundColor: "green", }} > <div style={{ height: 10, width: "99%", backgroundColor: "grey", border: "black solid 1px", marginBottom: "10px", }} > <div style={{ height: "100%", width: `${health}%`, backgroundColor: healthColor, }} /> </div> <div style={{ position: "absolute", left: !isFacingRight ? 0 : "", right: isFacingRight ? 0 : "", width: "10px", height: "10px", backgroundColor: "blue", zIndex: 100, }} ></div> </div> ); }; export default Wizard;
const account = { name: 'Leo Carey-Williams', expenses: [], income: [], addExpense: function (item, amount) { this.expenses.push({item, amount}) }, addIncome: function (item, amount) { this.income.push({item, amount}) }, getAccountSummary: function () { let expenseTotal = 0 let incomeTotal = 0 this.expenses.forEach((expense) => { expenseTotal += expense.amount }) this.income.forEach((income) => { incomeTotal += income.amount }) let total = incomeTotal - expenseTotal return `${this.name}'s account has £${total}. ${expenseTotal} in expenses and ${incomeTotal} in income.` } } account.addExpense('Rent', 950) account.addExpense('Laptop', 2400) account.addIncome('Freelance', 650) account.addIncome('Security', 3000) console.log(account.getAccountSummary())
import { SET_ALERT, CREATE_PREORDER, UPDATE_PREORDER, SET_SELECTED_TABLE_ORDERS, RESET_SELECTED_TABLE_ORDERS } from "../actionTypes"; import { cloudBusinessApiUrl } from "../../utilities/constants"; export const createPreorder = tableId => async dispatch => { dispatch({ type: CREATE_PREORDER, payload: { newPreorder: { name: "", recipes: [], req_recipes_quantities: [], user: "", location: "", table: tableId, status: "open", cost: 0, price: 0, profit: 0 } } }); }; export const findOpenOrdersByTable = (idToken, tableId) => async dispatch => { const options = { headers: { "Content-Type": "application/json", Authorization: idToken } }; const res = await fetch( `${cloudBusinessApiUrl}/orders/open/${tableId}`, options ); const ordersObject = await res.json(); if (ordersObject.error) { dispatch({ type: SET_ALERT, payload: { type: "error", triggeredBy: "findOpenOrdersByTable", message: JSON.stringify(ordersObject.error) } }); } else { dispatch({ type: SET_SELECTED_TABLE_ORDERS, payload: { selectedTableOrders: ordersObject } }); } }; export const resetSelectedTableOrders = () => dispatch => { dispatch({ type: RESET_SELECTED_TABLE_ORDERS }) }
//---------------------------------------------------------------- // // kitte.js // Summary: 切手組み合わせ作成JavaScript // Author : Ayumi Tagawa // //---------------------------------------------------------------- //--------------------------------------------------------------- // 初期画面 //--------------------------------------------------------------- $(document).on("pageinit", "#topPage", function() { // 「組合せを調べる」ボタン押下時 $("#searchButton").click( function() { var input_num = $("#input_number").val(); if( input_num == "" ) { alert("金額を入力してください"); return false; // リンク先に飛ばさない } if( input_num.match( /[^0-9]+/ ) ) { alert("半角数値を入力しください"); return false; // リンク先に飛ばさない } }); // 金額選択プルダウン選択時 $("#postalAmount").on("change", function(event) { /* if($(this).val() == 0) { $("#input_number").textinput("enable"); } else { $("#input_number").textinput("disable"); } */ $("#input_number").val($(this).val()); }); //XXX $("#search_form").validate(); }); //--------------------------------------------------------------- // 計算結果画面 //--------------------------------------------------------------- $(document).on('pageinit', '#resultPage', function() { $('#resultPage').on('pageshow', function() { // 切手の計算をする(最小枚数計算) var amount = $('#input_number').val(); // タイトルに目標金額を設定 $("#title").text(amount + "円分の切手"); // 1) 使用する切手の情報を配列に入れる var stampList = []; $('#stampList option:selected').each(function() { stampList.unshift($(this).val()); }); // 金額の大きい切手から順番に割って、商と余りを計算する // 最後の切手まで計算して余りがある場合には「計算できません」と表示 var resultList = []; resultList = combine(amount, stampList, 0); $("#resultList").empty(); if (resultList == null) { alert("組合せがありません"); } else { //resultList.sort(asc); for (var i = 0; i < resultList.length; i++) { $("#resultList").append( $("<tr>").append( $("<td>").append('<img src="img/pic_' + resultList[i][0] + '_en.gif" width="50%" height="50%"/>'), $("<td>").text(resultList[i][0] + "円切手"), $("<td>").text("× " + resultList[i][1] + "枚") ) ); } } }); }); //--------------------------------------------------------------- // 共通関数 // 最小枚数を見つけるアルゴリズム function combine( amount, stampList, no ) { if( no > stampList.length - 1 ) return null; var stamp_count = Math.floor(amount / stampList[no]); var amari = amount % stampList[no]; if( amari === 0 ) { return new Array( new Array(stampList[no], stamp_count) ); } else { // 金額に対して切手を全て当てはめた状態から減らしていって、組合せを検索する for( var i = stamp_count ; i >= 0; i-- ) { // 切手のリストが終わっていたら終わり var result = combine( amount - (stampList[no] * i), stampList, no+1); if( result == null ) continue; if(i === 0) { return result; } else { result.push( new Array(stampList[no],i) ); } return result; } return null; } } // 配列昇順ソート function asc( a, b ) { return ( a - b ); } // 配列降順ソート function desc( a, b ) { return ( b - a ); }
var searchData= [ ['homepageconfig',['HomepageConfig',['../classhomepage_1_1apps_1_1HomepageConfig.html',1,'homepage::apps']]] ];
/** * Created by nisabhar on 3/11/2016. */ define(['ojs/ojcore', 'knockout', 'jquery','ojL10n!pcs/resources/nls/pcsSnippetsResource', '!text!pcs/startform/templates/pcs-startform.html', 'pcs/startform/viewModel/startformContainer', '!text!pcs/startform/templates/pcs-startform-error.html', 'pcs/util/loggerUtil', 'jqueryui-amd/widget' ], function(oj, ko, $, bundle, tmpl, startform, errortmpl,loggerUtil) { 'use strict'; // define your widget under pcs namespace $.widget('pcs.startform', { //Options to be used as defaults options: { //Data Object needed to get the startForm object startformData: { processDefId: '', processName: '', serviceName: '', title: '', description: '', operation: '', startType: 'START_PCS_FORM', isDocsEnabled: false }, //Hidden option for PM's to pre populate form data payload: {}, // to hide submit button or not hideSubmit: false, /**/ // to hide save button or not hideSave: false, // to hide discard button or not hideDiscard: false, // to hide hideAttachment or not hideAttachment: false, //to automatically reload after submit reloadOnSubmit: true, //to automatically reload after save reloadOnSave: true, //Height for the form Iframe formHeight: '', // submit button label string submitLabel: bundle.pcs.startform.submit, //to be used for internally, when this is being used internally in appList consumed: false }, // Check if the Required options are provided to the widget _isValid: function() { if (this.options.startformData === undefined || this.options.startformData.processDefId === undefined || this.options.startformData.serviceName === undefined || this.options.startformData.operation === undefined) { return false; } if (this.options.startformData.processDefId === '' || this.options.startformData.serviceName === '' || this.options.startformData.operation === '') { return false; } return true; }, _create: function() { // _create will automatically run the first time // this widget is called. Put the initial widget // setup code here, then you can access the element // on which the widget was called via this.element. // The options defined above can be accessed // via this.options this.element.addStuff(); var widget = this; // Check if PCSConenction is set if ($.pcsConnection === undefined) { this.element.html('<div style=\'color:red\'>' + bundle.pcs.common.pcs_connection + ' </div>'); return; } // check if the the plugin is initialized correctly if (!this._isValid()) { this.element.html(errortmpl); return; } var data = this.options; data.rootElement = widget.element; var params = { data: data }; this.element.html(tmpl); var vm = new startform(params); this.model = vm; //ko.cleanNode(this.element['0']); ko.applyBindings(vm, this.element['0']); }, // Destroy an instantiated plugin and clean up modifications // that the widget has made to the DOM destroy: function() { //t his.element.removeStuff(); // For UI 1.8, destroy must be invoked from the base // widget $.Widget.prototype.destroy.call(this); // For UI 1.9, define _destroy instead and don't worry // about calling the base widget }, _destroy: function (){ loggerUtil.log('Destroying startform'); // clean everything up if (this.model) { this.model.dispose(); } }, // Respond to any changes the user makes to the option method _setOption: function(key, value) { this.options[key] = value; // For UI 1.8, _setOption must be manually invoked // from the base widget $.Widget.prototype._setOption.apply(this, arguments); // For UI 1.9 the _super method can be used instead // this._super( '_setOption', key, value ); } }); });
import {Lokacija} from './lokacija.js'; export class Zoo{ constructor(zoo, tipoviStanista) { this.id = zoo.id; this.naziv = zoo.naziv; this.n = zoo.n; this.m = zoo.m; this.kapacitet = zoo.kapacitet; this.lokacije = Array.from({length:zoo.m}, (_,i) => Array.from({length:zoo.n}, (_,j) => new Lokacija(0, i, j, "Prazno", 0, zoo.kapacitet, null))); zoo.lokacije.forEach(x => { this.lokacije[x.x][x.y] = new Lokacija(x.id, x.x, x.y, x.vrsta, x.zbir, zoo.kapacitet, x.staniste); }); this.tipoviStanista = tipoviStanista; this.glavni = null; } crtaj(host) { this.glavni = document.createElement("div"); this.glavni.classList.add("kontejner"); this.crtajFormu(this.glavni); this.crtajLokacije(this.glavni); host.appendChild(this.glavni); } crtajFormu(host) { let glavni = document.createElement("div"); glavni.className = "kontForma"; host.prepend(glavni); var labela = document.createElement("h3"); labela.innerHTML = "Unos zivotinja"; glavni.appendChild(labela); labela = document.createElement("label"); labela.innerHTML = "Ime vrste"; glavni.appendChild(labela); let input = document.createElement("input"); input.className = "vrsta"; glavni.appendChild(input); labela = document.createElement("label"); labela.innerHTML = "Kolicina"; glavni.appendChild(labela); input = document.createElement("input"); input.className = "kolicina"; input.type = "number"; glavni.appendChild(input); let opcija = null; let divRb = null; this.tipoviStanista.forEach((staniste, index) => { divRb = document.createElement("div"); opcija = document.createElement("input"); opcija.type = "radio"; opcija.name = staniste.naziv; opcija.value = staniste.id; labela = document.createElement("label"); labela.innerHTML = staniste.naziv; divRb.appendChild(opcija); divRb.appendChild(labela); glavni.appendChild(divRb); }) divRb = document.createElement("div"); let selX = document.createElement("select"); labela = document.createElement("label"); labela.innerHTML = "X:" divRb.appendChild(labela); divRb.appendChild(selX); for (let i = 0; i < this.m; i++) { opcija = document.createElement("option"); opcija.innerHTML = i; opcija.value = i; selX.appendChild(opcija); } glavni.appendChild(divRb); let selY = document.createElement("select"); labela = document.createElement("label"); labela.innerHTML = "Y:" divRb.appendChild(labela); divRb.appendChild(selY); for (let i = 0; i < this.n; i++) { opcija = document.createElement("option"); opcija.innerHTML = i; opcija.value = i; selY.appendChild(opcija); } glavni.appendChild(divRb); const dugme = document.createElement("button"); dugme.innerHTML = "Dodaj zivotinje"; glavni.appendChild(dugme); dugme.onclick = (ev) => { var vrstaZivotinje = this.glavni.querySelector(".vrsta").value; var kolicina = parseInt(this.glavni.querySelector(".kolicina").value); var staniste = this.glavni.querySelector(`input:checked`); if (staniste == null) alert("Molimo Vas izaberite tip stnaista"); let x = parseInt(selX.value); let y = parseInt(selY.value); let stan = { id: parseInt(staniste.value), naziv: staniste.name}; const lokId = this.lokacije[x][y].id; fetch("https://localhost:44348/ZooVrt/IzmeniLokaciju/" + this.id, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ id: lokId, vrsta: vrstaZivotinje, zbir: kolicina, staniste: stan, x: x, y: y, }) }).then((p) => { if (p.ok) { return p.json(); } else { alert("Greška prilikom upisa ovde."); } }) .then(id => { this.lokacije[x][y].izmeni(parseInt(id), vrstaZivotinje, kolicina, this.tipoviStanista.find(x => x.id == stan.id)); this.ocistiUnos(); }) .catch(p => { alert("Greška prilikom upisa."); }); } } ocistiUnos = () => { this.glavni.firstChild.remove(); this.crtajFormu(this.glavni); } crtajLokacije(host) { let glavni = document.createElement("div"); glavni.className = "kontLokacije"; for (let i = 0; i < this.m; i++) { let lokDiv = document.createElement("div"); lokDiv.className = "red"; for (let j = 0; j < this.n; j++) { this.lokacije[i][j].crtaj(lokDiv); } glavni.appendChild(lokDiv); } host.appendChild(glavni); } }
export const zh_login = { 'title': '登录', 'logout': '注销', 'success_login': '欢迎', 'success_logout': '再见', 'form': { 'username': '用户名或邮箱', 'password': '密码' }, 'forgot_password': '忘记密码?', 'not_has_account': '没有帐户?创建帐户.' }
import fs from "fs"; export default function (mongoose) { // autoregister the models const modelsDir = __dirname + '/models/'; const files = fs.readdirSync(modelsDir); for (var file of files) { const model = require(modelsDir + file); model.register(mongoose); } }
/** * Copyright 2020 ForgeRock AS. All Rights Reserved * * Use of this code requires a commercial software license with ForgeRock AS. * or with one of its affiliates. All use shall be exclusively subject * to such license between the licensee and ForgeRock AS. */ import { mount } from '@vue/test-utils'; import SchemaResetSecretField from './index'; let wrapper; beforeEach(() => { wrapper = mount(SchemaResetSecretField, { mocks: { $t: () => {}, }, }); }); describe('Schema reset secret field', () => { it('Schema reset secret field successfully loaded', () => { expect(wrapper.name()).toEqual('SchemaResetSecretField'); }); });
import React, { Component } from 'react'; import SearchForm from './SearchForm' import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import { faTimes } from '@fortawesome/free-solid-svg-icons' import { deleteAllJobs, toggleUiPanel, getSortState, updateSortState, updateInactiveState, getJobs } from '../../actions' import { connect } from 'react-redux' const INITIAL_STATE = { showAddNew: false, showClearSortPrompt: false } class JobsCntrlPanel extends Component { constructor(props) { super(props) this.navPanel = React.createRef() this.state = { ...INITIAL_STATE }; this.togglePanels = this.togglePanels.bind(this) this.clearJobs = this.clearJobs.bind(this) this.checkHeight = this.checkHeight.bind(this) this.checkSortState = this.checkSortState.bind(this) this.clearSortPrefs = this.clearSortPrefs.bind(this) } togglePanels (order) { const { toggleUiPanel } = this.props switch (order) { case "add": toggleUiPanel('addNew', null) break case "sort": toggleUiPanel('sort', null) break case "wishlist": toggleUiPanel('wishlist', null) break case "close": toggleUiPanel('close', null) break default: toggleUiPanel('close', null) } } clearJobs () { const { clearJobs } = this.props let userId = this.props.authUser.uid const message = `Heads up! This will clear all of your job applications and start you over from scratch. Sure you want to do it?` if (window.confirm(message)) { clearJobs(userId) } } checkHeight (ref) { if (ref.current !== null) { let sticky = ref.current.offsetTop if (window.pageYOffset >= sticky) { ref.current.classList.add("sticky") } else { ref.current.classList.remove("sticky"); } } } checkSortState () { if (this.props.sort || this.props.inactive !== 'showAll') { this.setState({ showClearSortPrompt: true }) } else { this.setState({ showClearSortPrompt: false }) } } clearSortPrefs () { const { updateSortState, updateInactiveState, getJobs } = this.props let userId = this.props.authUser.uid updateSortState(userId, null) updateInactiveState(userId, 'showAll') getJobs(userId) } componentDidMount () { const { getSortState } = this.props let userId = this.props.authUser.uid getSortState(userId) let navPanel = this.navPanel window.addEventListener('scroll', () => this.checkHeight(navPanel)) if (this.props.sort || this.props.inactive !== 'showAll') { this.checkSortState() } } componentDidUpdate (prevProps) { if (this.props !== prevProps) { this.checkSortState() } } componentWillUnmount () { window.removeEventListener('scroll', () => this.checkHeight(null)) } render() { return ( <div className="jobs-cntrl-panel col-md-3"> <div className="cntrls-wrap" ref={this.navPanel}> <SearchForm /> <h3 className="add-new-job" onClick={() => this.togglePanels("add")}> Add job </h3> <h3 onClick={() => this.togglePanels("sort")} > Sort jobs </h3> {this.state.showClearSortPrompt && <div className="clear-sort-prompt" onClick={() => this.clearSortPrefs()}> <FontAwesomeIcon icon={faTimes} /> Clear sorting preferences </div>} <h3 onClick={() => this.togglePanels("wishlist")} > Wishlist </h3> <h3 onClick={this.clearJobs} className="delete-all">Delete jobs </h3> </div> </div> ); } } const mapStateToProps = (state) => ({ uber: state, order: state.controlState.order, authUser: state.sessionState.authUser, sort: state.sortState.sortOrder, inactive: state.inactiveState.inactiveState }); const mapDispatchToProps = (dispatch) => ({ toggleUiPanel: (order, data) => dispatch(toggleUiPanel(order, data)), clearJobs: (userId) => dispatch(deleteAllJobs(userId)), getSortState: (userId) => dispatch(getSortState(userId)), updateSortState: (order, userId) => dispatch(updateSortState(order, userId)), updateInactiveState: (order, userId) => dispatch(updateInactiveState(order,userId)), getJobs: (userId) => dispatch(getJobs(userId)) }); export default connect(mapStateToProps, mapDispatchToProps)(JobsCntrlPanel);
// Hardcode for the sake of simplicity // const ingredients = [ 'Tomato', 'Cheese', 'Lettuce' ]; const ingredients = [ {id: 1, name: 'Tomato', quantity: '2pc'}, {id: 2, name: 'Chilli Flakes', quantity: '10g'}, {id: 3, name: 'Salt', quantity: '2tbsp'} ]; const instructions = [ {id: 1, name: 'Cook'}, {id: 2, name: 'Bake'}, {id: 3, name: 'Fry'} ]; export const finishedCookingCount = 0; export const recipes = [ { id: 1, title: 'Pasta Salad', image: 'https://www.jessicagavin.com/wp-content/uploads/2020/07/italian-pasta-salad-14-1200.jpg', ingredients, instructions, type: 'Healthy', duration: '30 min', difficulty: 'Easy', quantity: '6' }, { id: 2, title: 'Pancakes with Blueberry Syrup', image: 'https://media.eggs.ca/assets/RecipePhotos/_resampled/FillWyIxMjgwIiwiNzIwIl0/Fluffy-Pancakes-New-CMS.jpg', ingredients, instructions, type: 'Breakfast & Brunch', duration: '15 min', difficulty: 'Easy', quantity: '6' }, { id: 3, title: 'Egg Fried Rice', image: 'https://www.carolinescooking.com/wp-content/uploads/2016/01/vegetable-egg-fried-rice-photo-1.jpg', ingredients, instructions, type: 'Rice', duration: '20 min', difficulty: 'Easy', quantity: '2' }, { id: 4, title: 'Spaghetti Bolognese', image: 'http://wallflowerkitchen.com/wp-content/uploads/2016/08/Explore-Asian-Ratatouille-Spaghetti-Vegan-Gluten-Free-5-735x1103.jpg', ingredients, instructions, type: 'Pasta', duration: '45 min', difficulty: 'Medium', quantity: '1' }, { id: 5, title: 'Veg Mushroom Burger with Truffle Porcini Mayo', image: 'http://static1.squarespace.com/static/58d08c6ad482e92f5e34a8df/t/5f11c00b81b7367d75137a44/1594998814921/porcini-truffle-burgers-rustic-board.jpeg?format=1500w', ingredients, instructions, type: 'Burger', duration: '1 h 10 min', difficulty: 'Hard', quantity: '6' }, ];
import _slicedToArray from "@babel/runtime/helpers/slicedToArray"; import React, { useState } from 'react'; import { Insets } from '@ctkit/layout'; import Table from '@ctkit/table'; import { Pagination } from "semantic-ui-react"; import isEmpty from 'lodash.isempty'; // ------------------------------------------------------------------------------ //import DataExportPopoverMenu from './DataExportPopoverMenu'; export default (function (_ref) { var dataList = _ref.dataList, todosPerPage = _ref.todosPerPage, columns = _ref.columns, emptyMessage = _ref.emptyMessage; var _useState = useState(1), _useState2 = _slicedToArray(_useState, 2), _activePage = _useState2[0], _setActivePage = _useState2[1]; var calculPaginationPages = function calculPaginationPages() { var count = dataList.length / todosPerPage; return count; }; var handlePaginationChange = function handlePaginationChange(e, _ref2) { var activePage = _ref2.activePage; return _setActivePage(activePage); }; var indexOfLastTodo = _activePage * todosPerPage; var indexOfFirstTodo = indexOfLastTodo - todosPerPage; console.log('inside TableView ', dataList); var currentTodos = dataList.slice(indexOfFirstTodo, indexOfLastTodo); return React.createElement(Insets, { ml: 10 }, React.createElement(Table, { columns: columns, data: currentTodos, emptyMessage: emptyMessage, loading: dataList.loading }), !isEmpty(dataList) && dataList.length / todosPerPage > 1 && React.createElement("div", { className: "actions" }, React.createElement(Pagination, { activePage: _activePage, onPageChange: handlePaginationChange, totalPages: calculPaginationPages() }))); });
/** * Created by xuanjinliang on 2018/10/29. */ import Vue from 'vue' import Router from 'vue-router' Vue.use(Router) const router = new Router({ mode: 'history', routes: [ { path: '/', name: 'Main', component: () => import('@/views/main') }, { path: '/article', name: 'Article', redirect: '/article/template1', component: () => import('@/views/articleTemplate/article'), children: [ { name: 'Template1', path: 'template1', component: () => import('@/views/articleTemplate/content/template1') }, { name: 'Template2', path: 'template2', component: () => import('@/views/articleTemplate/content/template2') }, { name: 'Template3', path: 'template3', component: () => import('@/views/articleTemplate/content/template3') } ] } ] }) export default router
if ('NodeList' in window && !NodeList.prototype.forEach) { console.info('polyfill for IE11'); NodeList.prototype.forEach = function (callback, thisArg) { thisArg = thisArg || window; for (let i = 0; i < this.length; i++) { callback.call(thisArg, this[i], i, this); } }; } $(function() { const headerSearch = $('.header-search'); // <== Кешируем ноду $('.header-search-button').click(function(e) { if ( !headerSearch.hasClass('expanded') ) { e.preventDefault(); // <== Превентим сабмит на первый клип по иконке headerSearch.addClass('expanded'); $('.header-search-field').focus(); } else { headerSearch.submit(); } }); $('.select-lang').click(function() { $(this).addClass('expanded'); }); $('body').click(function(e) { const target = e.target.classList[0]; if (target !== 'header-search-button') { headerSearch.removeClass('expanded'); } if (target !== 'filter-hidden') { $('.filter-hidden').each(function() { $(this).prop('checked', false); }) } if (target !== 'select-lang-selected') { $('.select-lang').removeClass('expanded'); } if (target === 'modal-wrapper') { $('.modal-wrapper').removeClass('show'); $('body').removeClass('noflow'); } }); if ($('.page-slider').length) { $('.page-slider').slick({ arrows: false, dots: true, slidesToShow: 1, slidesToScroll: 1, appendDots: '.slider-dots-wrapper', dotsClass: 'slider-dots', cssEase: 'ease', fade: true, lazyload: 'ondemand' }); } $('.filter-options-item').click(function(e) { const label = $(this).parent().siblings('label'); label.text(e.target.innerHTML); // TODO Ajax call }); if ( $('.reviews-slider-item').length > 2 ) { $('.simple-slider').slick({ arrows: false, dots: true, slidesToShow: 2, lazyLoad: 'ondemand', appendDots: '.simple-slider-wrapper', dotsClass: 'slider-dots simple-slider-dots', responsive: [ { breakpoint: 1280, settings: { slidesToShow: 1 } } ] }) } const aboutSlider = $('.about-slider'); // <== Кешируем слайдер aboutSlider.slick({ arrows: false, dots: false, slidesToShow: 1, slidesToScroll: 1, lazyLoad: 'ondemand' }) $('.slider-btn').click(function() { const dir = $(this).data('dir'); aboutSlider.slick('slick'+dir); }) let allowHeaderToScroll = true; function detectVerticalScroll(e) { if (e.target.classList[0] === 'filter-options-item') return; if (e.target.classList[0] === 'modal-wrapper') return; if (e.target.classList[0] === 'modal') return; if(allowHeaderToScroll) { e.originalEvent.deltaY >= 0 ? $('.page-header').addClass('hide-up') : $('.page-header').removeClass('hide-up'); } } $('body').on('wheel mousewheel', detectVerticalScroll); $('.close-modal').click(function() { $('.modal-wrapper').removeClass('show'); $('body').removeClass('noflow'); }) $('.call-modal').click(function() { const vacancy = $(this).siblings('.card-big-title').text(); $('body').addClass('noflow'); $('.modal-wrapper').addClass('show'); $('.input-vacancy').attr('value', vacancy) $('.resume-modal form input[name="vacancy-name"]').focus(); }) $('.resume-modal form').submit(function(e) { e.preventDefault(); const data = $(this).serialize(); // TODO Ajax call }); $('.mailing-form').submit(function(e) { e.preventDefault(); $('body').addClass('noflow'); $('.modal-wrapper').removeClass('review show'); $('.modal-wrapper').addClass('subscription show'); }); $('.review-form').submit(function(e) { e.preventDefault(); $('body').addClass('noflow'); $('.modal-wrapper').removeClass('subscription show'); $('.modal-wrapper').addClass('review show'); }); $('.mobile-burger').click(function() { allowHeaderToScroll = !allowHeaderToScroll; $(this).toggleClass('is-active') $('body').toggleClass('noflow'); $('.mobile-menu-wrapper').toggleClass('move-left') }) const svgPath = document.querySelector('.letters'); const svgPath2 = document.querySelector('.background'); if (anime) { const tl = anime.timeline({ easing: 'easeInOutQuad', direction: 'alternate', duration: 2500, loop: true }) tl .add({ targets: svgPath2, loop: false, fill: ['rgba(255, 255, 255, 0)', '#d24a43'], easing: 'easeInOutQuad', duration: 800, }) .add({ targets: svgPath, loop: true, stroke: '#fff', // duration: 2000 }) .add({ targets: svgPath, loop: true, direction: 'normal', strokeDashoffset: [anime.setDashoffset, 0], easing: 'easeInOutQuad', // duration: 2000 }) .add({ targets: svgPath, fill: ['rgba(255, 255, 255, 0)', '#fff'], direction: 'normal', easing: 'linear', duration: 300, delay: (el, i) => { return i * 5000 } }) .add({ duration: 1500, }) .add({ duration: 1500, }) } if ( window.matchMedia('(max-width: 1280px)').matches ) { $('.timeline').slick({ slidesToScroll: 1, slidesToShow: 1, autoplay: true, autoplaySpeed: 2500, speed: 800 }); } else { if ( $('.timeline').hasClass('animated') ) { $('.timeline').removeClass('animated'); }; } console.log('The main script is ready') });
import React from "react"; import "./Profile.css"; // import { Link } from "react-router-dom"; const Profile = props => ( <p> This is your profile</p> ) export default Profile;
// import da classe Router do express import { Router } from 'express'; import multer from 'multer'; import multerConfig from './config/multer'; // import dos controllers import UserController from './app/controllers/UserController'; import SessionController from './app/controllers/SessionController'; import FileController from './app/controllers/FileController'; import CartController from './app/controllers/CartController'; import ProductController from './app/controllers/ProductController'; // import do middleware da autenticação import authMiddleware from './app/middleware/auth'; // instancia da classe Router const routes = new Router(); const upload = multer(multerConfig); // rota para criar um utilizador routes.post('/users', UserController.store); // rota para autenticação routes.post('/sessions', SessionController.store); // definir como middlware global // terá efeito somente para as rotas abaixo visto que foi declarado depois das // duas rotas em cima routes.use(authMiddleware); // rota para atualizar um utilizador routes.put('/users', UserController.update); routes.get('/users/:user_id/carts', CartController.index); routes.post('/users/:user_id/carts', CartController.store); routes.delete('/users/:user_id/carts/:id', CartController.delete); routes.post('/products', ProductController.store); routes.delete('/products/:id', ProductController.delete); routes.post('/files', upload.single('file'), FileController.store); // export do routes export default routes;
const bcrypt = require("bcryptjs"); const generateToken = require("../services/generateToken"); const db = require("../db/index"); const { validationResult } = require("express-validator"); // Created register account flow const registerPost = async (req, res) => { const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(400).json({ errors: errors.array() }); } try { // Destructure the request body const { user_name, user_email, password } = req.body; // check for user email existing const checkUser = await db.query( "SELECT * FROM users WHERE user_email = $1", [user_email]); // If it exists aka more than 0 rows exist, then return a failure if (checkUser.rowCount !== 0) { return res.status(400).json({ status: "Failure", msg: "Account already exists" }); } // If account doesnt exist continue with hashing the password const hashedPW = await bcrypt.hash(password, 11); // Insert into DB once hashed const user = await db.query( `INSERT INTO users (user_name, user_email, password) values($1, $2, $3) RETURNING *`, [user_name, user_email, hashedPW]); // Create payload for token const payload = { user: { id: user.rows[0].user_id } }; // Generate jwt token from user id const token = await generateToken(payload); return res.status(201).json({ status: "Success", msg: "User Created", token }); } catch (err) { console.log(err); return res.status(400).json({ error: err.message }); } }; module.exports = { registerPost };
const alias = require('./alias.config') const {getBabelLoader, withLoader} = require('playland/webpack') module.exports = { webpack(config) { Object.assign(config.resolve.alias, alias.resolve.alias) const babelLoader = getBabelLoader(config) babelLoader.options.plugins.push( '@babel/plugin-proposal-nullish-coalescing-operator', '@babel/plugin-proposal-optional-chaining' ) return config }, }
/* Copyright (c) 2014, Yahoo! Inc. All rights reserved. Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. */ (function (root, factory) { 'use strict'; // Intl and IntlMessageFormat are dependencies of this package. The built-in // `Intl` is preferred, but when not available it looks for the polyfill. var Intl = root.Intl || root.IntlPolyfill, lib = factory(root.JSON, Intl, root.IntlMessageFormat); /* istanbul ignore next */ if (typeof define === 'function' && define.amd) { define(lib); } if (typeof exports === 'object') { module.exports = lib; } root.HandlebarsHelperIntl = lib; })(typeof global !== 'undefined' ? global : this, function (JSON, Intl, IntlMessageFormat) { 'use strict'; if (!Intl) { throw new ReferenceError('Intl must be available.'); } if (!IntlMessageFormat) { throw new ReferenceError('IntlMessageFormat must be available.'); } var exports = {}; // Export utility function to register all the helpers. exports.registerWith = function registerWith(Handlebars) { var SafeString = Handlebars.SafeString, createFrame = Handlebars.createFrame, escape = Handlebars.Utils.escapeExpression; var helpers = { intl : intl, intlDate : intlDate, intlNumber : intlNumber, intlGet : intlGet, intlMessage : intlMessage, intlHTMLMessage: intlHTMLMessage }, name; for (name in helpers) { if (helpers.hasOwnProperty(name)) { Handlebars.registerHelper(name, helpers[name]); } } // -- Helpers ---------------------------------------------------------- function intl(options) { /* jshint validthis:true */ if (!options.fn) { throw new ReferenceError('{{#intl}} must be invoked as a block helper'); } // Create a new data frame linked the parent and create a new intl // data object and extend it with `options.data.intl` and // `options.hash`. var data = createFrame(options.data), intlData = extend({}, data.intl, options.hash); data.intl = intlData; return options.fn(this, {data: data}); } function intlDate(date, formatOptions, options) { date = new Date(date); // Determine if the `date` is valid. if (!(date && date.getTime())) { throw new TypeError('A date must be provided.'); } if (!options) { options = formatOptions; formatOptions = null; } var hash = options.hash, data = options.data, locales = data.intl && data.intl.locales; if (formatOptions) { if (typeof formatOptions === 'string') { formatOptions = intlGet('formats.date.' + formatOptions, options); } formatOptions = extend({}, formatOptions, hash); } else { formatOptions = hash; } return getFormat('date', locales, formatOptions).format(date); } function intlNumber(num, formatOptions, options) { if (typeof num !== 'number') { throw new TypeError('A number must be provided.'); } if (!options) { options = formatOptions; formatOptions = null; } var hash = options.hash, data = options.data, locales = data.intl && data.intl.locales; if (formatOptions) { if (typeof formatOptions === 'string') { formatOptions = intlGet('formats.number.' + formatOptions, options); } formatOptions = extend({}, formatOptions, hash); } else { formatOptions = hash; } return getFormat('number', locales, formatOptions).format(num); } function intlGet(path, options) { var intlData = options.data && options.data.intl, pathParts = path.split('.'), obj, len, i; // Use the path to walk the Intl data to find the object at the // given path, and throw a descriptive error if it's not found. try { for (i = 0, len = pathParts.length; i < len; i++) { obj = intlData = intlData[pathParts[i]]; } } finally { if (obj === undefined) { throw new ReferenceError('Could not find Intl object: ' + path); } } return obj; } function intlMessage(message, options) { if (!options) { options = message; message = null; } var hash = options.hash; // Support a message being passed as a string argument or pre-prased // array. When there's no `message` argument, ensure a message path // name was provided at `intlName` in the `hash`. // // TODO: remove support form `hash.intlName` once Handlebars bugs // with subexpressions are fixed. if (!(message || typeof message === 'string' || hash.intlName)) { throw new ReferenceError('{{intlMessage}} must be provided a message or intlName'); } var intlData = options.data.intl || {}, locales = intlData.locales, formats = intlData.formats; // Lookup message by path name. User must supply the full path to // the message on `options.data.intl`. if (!message && hash.intlName) { message = intlGet(hash.intlName, options); } // When `message` is a function, assume it's an IntlMessageFormat // instance's `format()` method passed by reference, and call it. // This is possible because its `this` will be pre-bound to the // instance. if (typeof message === 'function') { return message(hash); } // Assume that an object with a `format()` method is already an // IntlMessageFormat instance, and use it; otherwise create a new // one. if (typeof message.format !== 'function') { message = new IntlMessageFormat(message, locales, formats); } return message.format(hash); } function intlHTMLMessage() { /* jshint validthis:true */ var options = [].slice.call(arguments).pop(), hash = options.hash, key, value; // Replace string properties in `options.hash` with HTML-escaped // strings. for (key in hash) { if (hash.hasOwnProperty(key)) { value = hash[key]; // Escape string value. if (typeof value === 'string') { hash[key] = escape(value); } } } // Return a Handlebars `SafeString`. This first unwraps the result // to make sure it's not returning a double-wrapped `SafeString`. return new SafeString(String(intlMessage.apply(this, arguments))); } }; // -- Internals ------------------------------------------------------------ // Cache to hold NumberFormat and DateTimeFormat instances for reuse. var formats = { number: {}, date : {} }; function getFormat(type, locales, options) { var orderedOptions, option, key, i, len, id, format; // When JSON is available in the environment, use it build a cache-id // to reuse formats for increased performance. if (JSON) { // Order the keys in `options` to create a serialized semantic // representation which is reproducible. if (options) { orderedOptions = []; for (key in options) { if (options.hasOwnProperty(key)) { orderedOptions.push(key); } } orderedOptions.sort(); for (i = 0, len = orderedOptions.length; i < len; i += 1) { key = orderedOptions[i]; option = {}; option[key] = options[key]; orderedOptions[i] = option; } } id = JSON.stringify([locales, orderedOptions]); } // Check for a cached format instance, and use it. format = formats[type][id]; if (format) { return format; } switch (type) { case 'number': format = new Intl.NumberFormat(locales, options); break; case 'date': format = new Intl.DateTimeFormat(locales, options); break; } // Cache format for reuse. if (id) { formats[type][id] = format; } return format; } // -- Utilities ------------------------------------------------------------ function extend(obj) { var sources = Array.prototype.slice.call(arguments, 1), i, len, source, key; for (i = 0, len = sources.length; i < len; i += 1) { source = sources[i]; if (!source) { continue; } for (key in source) { if (source.hasOwnProperty(key)) { obj[key] = source[key]; } } } return obj; } return exports; });
var module = angular.module('ucms.app.setting'); module.controller("importexportCtrl", function ($scope, $xhttp, FileSaver, Blob) { $scope.exportOptions = { Folders: false, Workflows: false, ContentTypes: false, Activities: false, DataList: false, Settings: false, UsersAndProfiles: false } $scope.$watch('exportOptions', function(newObj) { if (newObj.Workflows) { newObj.Folders = true; newObj.Activities = true; } if (newObj.ContentTypes) { newObj.Folders = true; } }, true); $scope.export = function() { $xhttp.post(WEBAPI_ENDPOINT + '/api/setting/export', $scope.exportOptions).then(function(response) { var data = new Blob([JSON.stringify(response.data)], { type: 'text/plain;charset=utf-8' }); FileSaver.saveAs(data, new Date().getTime() + '.json'); }); } });
var express = require('express'); var router = express.Router(); //主頁 router.get('/', function(req, res, next) { var db = req.con; var data = ""; var userId = req.query.userId; var filter = ""; if (userId) { filter = 'WHERE userId = ?'; } var sql = "SELECT seqNo,userId,cKind,contact,remark,DATE_FORMAT(modifyTime, '%Y-%m-%d %H:%i:%S') as ModifyTime,ModifyEmp " + " FROM JBContact " + filter; db.query(sql, userId, function(err, rows) { if (err) { console.log(err); } var data = rows; res.render('index', { title: '帳號清單', data: data, userId: userId }); }); }); //新增帳號-1 router.get('/add', function(req, res, next) { // use userAdd.ejs res.render('userAdd', { title: '新增帳號'}); }); //新增帳號-2 router.post('/userAdd', function(req, res, next) { var db = req.con; var sql = { userId: req.body.userId, cKind: req.body.cKind, contact: req.body.contact, remark: req.body.remark, modifyTime: new Date(), modifyEmp: 'J1040083' }; //console.log(sql); var qur = db.query('INSERT INTO JBContact SET ?', sql, function(err, rows) { if (err) { console.log(err); } res.setHeader('Content-Type', 'application/json'); res.redirect('/'); }); }); //修改帳號-1 : 查詢明細 router.get('/userEdit', function(req, res, next) { var seqNo = req.query.seqNo; var db = req.con; var data = ""; db.query('SELECT * FROM JBContact WHERE seqNo = ?', seqNo, function(err, rows) { if (err) { console.log(err); } var data = rows; res.render('userEdit', { title: '帳號編輯', data: data }); }); }); //修改帳號-2 router.post('/userEdit', function(req, res, next) { var db = req.con; var seqNo = req.body.seqNo; var sql = { userId: req.body.userId, cKind: req.body.cKind, contact: req.body.contact, remark: req.body.remark, modifyTime: new Date(), modifyEmp: 'J1040083' }; var qur = db.query('UPDATE JBContact SET ? WHERE seqNo = ?', [sql, seqNo], function(err, rows) { if (err) { console.log(err); } res.setHeader('Content-Type', 'application/json'); res.redirect('/'); }); }); //刪除帳號 router.get('/userDelete', function(req, res, next) { var seqNo = req.query.seqNo; var db = req.con; var qur = db.query('DELETE FROM JBContact WHERE seqNo = ?', seqNo, function(err, rows) { if (err) { console.log(err); } res.redirect('/'); }); }); module.exports = router;
var express= require('express'); var app = express(); app.get('/test', function(req, res) { var retval = { "2016" : 12376123761, "2017" : 89398123782, "2018" : 26372361028, "2019" : 93837627262, }; res.json(retval); }); app.listen(3003); console.log("listening on port 3003");
import antInjectComp from './AntInjectComponent'; export default antInjectComp;
System.config({ transpiler: 'typescript', paths: { 'babel': 'node_modules/babel-core/browser.js', 'typescript': 'node_modules/typescript/lib/typescript.js', 'systemjs': 'node_modules/systemjs/dist/system.src.js', 'system-polyfills': 'node_modules/systemjs/dist/system-polyfills.js', 'es6-module-loader': 'node_modules/es6-module-loader/dist/es6-module-loader.js', 'phantomjs-polyfill': 'node_modules/phantomjs-polyfill/bind-polyfill.js', 'rxjs': 'node_modules/rxjs/bundles/Rx.js', '@angular': 'node_modules/@angular', '@uirouter/angular': 'src/index.ts' }, map: { '@uirouter/core': 'node_modules/@uirouter/core/lib', }, packages: { 'src': { defaultExtension: 'ts' }, '@uirouter/core': { main: 'index.js', defaultExtension: 'js' }, '@angular/core': { main: 'index.js', defaultExtension: 'js' }, '@angular/compiler': { main: 'index.js', defaultExtension: 'js' }, '@angular/common': { main: 'index.js', defaultExtension: 'js' }, '@angular/http': { main: 'index.js', defaultExtension: 'js' }, '@angular/testing': { main: 'index.js', defaultExtension: 'js' }, '@angular/platform-browser': { main: 'index.js', defaultExtension: 'js' }, '@angular/platform-browser-dynamic': { main: 'index.js', defaultExtension: 'js' } } });
import React, { Component } from 'react'; import BarNavigation from './../../components/BarNavigation' import Footer from './../../components/Footer' import mainLogo from './../../img/footer/mainLogoWhite.png' import SideHome from './../../components/SideHome' import Route from 'react-router-dom/Route' import TutorialContent from './../../pages/TutorialContent' import ModificarInformacion from './../../pages/ModificarInformacion/containers/update-info-client.js' import UpdatePassword from './../../pages/ModificarInformacion/containers/update-password.js' import SideHomeHorizontal from './../../pages/SideBarHorizontal/index.js' import InicioEstudiante from './InicioEstudiante/index.js' import { HashRouter } from 'react-router-dom' import SolicitarTutoria from './../../pages/SolicitarTutoria' import './styles.css' class PanelStudent extends Component { render() { return ( <div className='panelStudent'> <header> <div className='headerNav'> <BarNavigation mainLogo={mainLogo} classBar='barNavigation2'></BarNavigation> </div> </header> <section className='main'> <div className="navigatioSideHorizontal"> <SideHomeHorizontal /> </div> <div className='panelStudentContent'> <div className='navigationSideBar'> <SideHome/> </div> <div className='informationContent'> <HashRouter> <Route path='/panelEstudiante/tutorias' component={TutorialContent}></Route> <Route path='/panelEstudiante/tutorias/solicitarTutoria' component={SolicitarTutoria}/> <Route path='/panelEstudiante/informacion' component={ModificarInformacion}></Route> <Route path='/panelEstudiante/contraseña' component={UpdatePassword}></Route> <Route path='/panelEstudiante/inicioEstudiante' component={InicioEstudiante}></Route> </HashRouter> </div> </div> </section> <section className='footer'> <Footer classColor='black'/> </section> </div> ); } } export default PanelStudent;
export default "SELECTING_STYLE";
/*jslint node: true */ 'use strict'; var _ = require('underscore'); var sampleRequestJSON = require('./sample_request.json'); var sampleResponseJSON = require('./sample_response.json'); var constants = require('../../lib/constants'); /** * Test Data Provider */ var testData = (function () { return { sampleRequest: JSON.stringify(sampleRequestJSON), sampleResponse: JSON.stringify(sampleResponseJSON), emptyRequest: JSON.stringify({payload: []}), emptyResponse: JSON.stringify({response: []}), expectedJSONParseErrorMsg: JSON.stringify({error: constants.parseErrorMsg}), expectedNotFoundErrorMsg: JSON.stringify({error: constants.notFoundErrorMsg}) }; }()); exports = module.exports = testData;
const fetch = require('node-fetch') async function count(url) { return fetch(`${url}/count`, { method: "post", headers: { "Content-type": "application/json", "Accept": "application/json", "Accept-Charset": "utf-8" }, }) .then(response => response.json()) .then(json => { let str = json.data.players.length; return (`Players: ${str}/64`) }) .catch(err => { console.log(err) return ("Api error occured"); }) } module.exports = { count: count }
var express = require('express'); var router = express.Router(); var passport = require('passport'); /* GET home page. */ router.get('/', function(req, res, next) { res.render('index'); }); router.post('/login', function(req, res, next){ passport.authenticate('local', function(err, user, info) { //console.log("check index.js", err, "--", user, "--", info); if (err) {console.log("top err"); return next(err)} if(typeof info !== 'undefined' && info && info.code === 401) { return res.status(401).json(info); } if (!user) { return res.status(404).json({code: 404, message: 'User not found'}); } if(!user.active){ return res.status(401).json({code: 401, message: 'User is not active.'}); } req.logIn(user, function(err) { //console.log("in logIn callback"); //console.log(err); if (err) { return next(err); } return res.status(200).json({code: 200, message: 'User verified'}) }); })(req, res, next); }); router.get('/logout', function(req, res){ req.logout(); res.render('index'); }); module.exports = router;
import React from 'react' import TitleBanner from '../components/TitleBanner' import CardContainer from './CardContainer' import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom"; const TitlePage = props => { console.log(props) return ( <div> <Router> <Route exact path="/" component={TitleBanner} /> <Route exact path="/" render={(props) => ( <CardContainer {...props} allGames={props.allGames} /> )} /> <Route path="/allgames" render={(props) => (<CardContainer {...props} allGames={props.allGames}/>)} /> </Router> </div> ); } export default TitlePage
'use strict'; function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } var goods = document.getElementById('goods'); var data = sortByDateAdded(filterByWomen(window.catalog)); var leftSlider = document.getElementById('leftSlider'); var rightSlider = document.getElementById('rightSlider'); var totalPriceBO = document.getElementById('totalPriceBO'); var btnToBag = document.getElementById('btnToBag'); //isObjectEmpty function isObjectEmpty(obj) { for (var key in obj) { return; } return true; } function showPage() { renderGoods(); } //Filter goods By Women and Casual style function filterByWomen(arr) { return arr.filter(function (obj) { return obj.category == 'women' && obj.fashion == 'Casual style'; }); } //Sort goods by newest function sortByDateAdded(arr) { var newArr = [].concat(_toConsumableArray(arr)); newArr.sort(function (a, b) { return new Date(b.dateAdded) - new Date(a.dateAdded); }); return newArr; } /*Render goods on page*/ function renderGoods() { var VisibleQty = 4; var html = ''; //Rendering all Arrivals for (var i = 0; i < VisibleQty; i++) { var neww = data[i].hasNew ? 'new' : ''; var price = data[i].discountedPrice ? '<span class="old-price">' + currency + data[i].price.toFixed(2) + '</span>\n <span class="card__price">' + currency + data[i].discountedPrice.toFixed(2) + '</span>' : '<span class="card__price">' + currency + data[i].price.toFixed(2) + '</span>'; html += '\n <div class="card">\n <div class="card-inner ' + neww + '">\n <a href="./item.html" data-id="' + data[i].id + '">\n <div class="card__img">\n <img src="' + data[i].thumbnail + '" alt="' + data[i].title + '">\n </div>\n <h5 class="card__title">' + data[i].title + '</h5>\n ' + price + '\n </a>\n </div>\n </div>\n '; } goods.innerHTML = html; } //*********** //Best offer //*********** var lefts = sortByBestOffer(window.bestOffer.left); var rights = sortByBestOffer(window.bestOffer.right); var leftPrice = void 0; var rightPrice = void 0; var discountBO = window.bestOffer.discount; function sortByBestOffer(arr) { var newArr = []; arr.forEach(function (str) { for (var i = 0; i < window.catalog.length; i++) { if (window.catalog[i].id === str) { newArr.push(window.catalog[i]); break; } } }); return newArr; } leftPrice = parseFloat(lefts[0].price); rightPrice = parseFloat(rights[0].price); function renderLeftSlider(e) { var target = e.target; var index = +target.dataset.index; var direction = target.dataset.direction; if (!direction) return; var leftQty = window.bestOffer.left.length; var newIndexUp = void 0; var newIndexDown = void 0; leftPrice = parseFloat(lefts[index].price); renderPrice(); btnToBag.dataset.id_1 = lefts[index].id; if (direction === 'up') { newIndexUp = index - 1; newIndexDown = index - 1; } if (direction === 'down') { newIndexUp = index + 1; newIndexDown = index + 1; } if (newIndexUp > leftQty - 1) { newIndexUp = 0; } if (newIndexDown > leftQty - 1) { newIndexDown = 0; } if (newIndexUp < 0) { newIndexUp = leftQty - 1; } if (newIndexDown < 0) { newIndexDown = leftQty - 1; } var neww = lefts[index].hasNew ? 'new' : ''; var html = '\n <div class="slider__card ' + neww + '">\n <a href="./item.html" data-id="' + lefts[index].id + '">\n <img src="' + lefts[index].thumbnail + '" alt="' + lefts[index].title + '">\n <h5 class="card__title">' + lefts[index].title + '</h5>\n <span class="card__price">' + currency + lefts[index].price + '</span>\n </a>\n </div>\n <a class="slider-control slider-control_up" data-index="' + newIndexUp + '" data-direction="up"></a>\n <a class="slider-control slider-control_down" data-index="' + newIndexDown + '" data-direction="down"></a>'; leftSlider.innerHTML = html; } leftSlider.addEventListener('click', renderLeftSlider); function renderRightSlider(e) { var target = e.target; var index = +target.dataset.index; var direction = target.dataset.direction; if (!direction) return; var rightQty = window.bestOffer.right.length; var newIndexUp = void 0; var newIndexDown = void 0; rightPrice = parseFloat(rights[index].price); renderPrice(); btnToBag.dataset.id_2 = rights[index].id; if (direction === 'up') { newIndexUp = index - 1; newIndexDown = index - 1; } if (direction === 'down') { newIndexUp = index + 1; newIndexDown = index + 1; } if (newIndexUp > rightQty - 1) { newIndexUp = 0; } if (newIndexDown > rightQty - 1) { newIndexDown = 0; } if (newIndexUp < 0) { newIndexUp = rightQty - 1; } if (newIndexDown < 0) { newIndexDown = rightQty - 1; } var neww = rights[index].hasNew ? 'new' : ''; var html = '\n <div class="slider__card ' + neww + '">\n <a href="./item.html" data-id="' + rights[index].id + '">\n <img src="' + rights[index].thumbnail + '" alt="' + rights[index].title + '">\n <h5 class="card__title">' + rights[index].title + '</h5>\n <span class="card__price">' + currency + rights[index].price + '</span>\n </a>\n </div>\n <a class="slider-control slider-control_up" data-index="' + newIndexUp + '" data-direction="up"></a>\n <a class="slider-control slider-control_down" data-index="' + newIndexDown + '" data-direction="down"></a>'; rightSlider.innerHTML = html; } rightSlider.addEventListener('click', renderRightSlider); function renderPrice() { var price = leftPrice + rightPrice; var newPrice = price - discountBO; var html = '\n <div class="main-total-price__old-price old-price">\n <span>&pound;</span><span>' + price + '</span>\n </div>\n\n <div class="main-total-price__new-price">\n <span>' + currency + '</span>' + newPrice + '<span></span>\n </div>'; totalPriceBO.innerHTML = html; } /**********/ //Add to bag /**********/ var discounts = { left: [], right: [] }; //Check the discounts from the localStorage function checkDiscount() { if (!isObjectEmpty(JSON.parse(localStorage.getItem('discounts')))) { discounts = JSON.parse(localStorage.getItem('discounts')); } } btnToBag.onclick = function () { addToBag.call(this, this.dataset.id_1); addToBag.call(this, this.dataset.id_2); var leftId = this.dataset.id_1; var rightId = this.dataset.id_2; checkDiscount(); discounts.left.push(leftId); discounts.right.push(rightId); localStorage.setItem('discounts', JSON.stringify(discounts)); }; //Add the good to bag function addToBag(id) { id = id || this.dataset.id; var color = this.dataset.color; var size = this.dataset.size; var obj = { id: id, color: color, size: size }; if (!bag.length) { obj.count = 1; bag.push(obj); } else { /*Is there product with the same property*/ var isExist = bag.some(function (el) { return el.id === id && el.color === color && el.size === size; }); if (!isExist) { obj.count = 1; bag.push(obj); } else { bag.forEach(function (el) { if (el.id === id && el.color === color && el.size === size) { el.count++; } }); } } localStorage.setItem('bag', JSON.stringify(bag)); showMiniBag(); } //Initial renderPrice(); showPage();
export default{ item_master_id:0, item_master_name:'', hsn_code:'', description:'', gst_rate:0 }
import { createStore, combineReducers, applyMiddleware, compose } from 'redux' import reducers from './reducers' let reduxStore = null // Get the Redux DevTools extension and fallback to a no-op function let devtools = f => f if (process.browser && window.__REDUX_DEVTOOLS_EXTENSION__) { devtools = window.__REDUX_DEVTOOLS_EXTENSION__() } function create (apollo, initialState = {}) { return createStore( combineReducers({ // Setup reducers ...reducers, apollo: apollo.reducer() }), initialState, // Hydrate the store with server-side data compose( applyMiddleware(apollo.middleware()), // Add additional middleware here devtools ) ) } export default function initRedux (apollo, initialState) { // Make sure to create a new store for every server-side request so that data // isn't shared between connections (which would be bad) if (!process.browser) { return create(apollo, initialState) } // Reuse store on the client-side if (!reduxStore) { reduxStore = create(apollo, initialState) } return reduxStore }
"use strict"; const crypto = require('crypto'); function MessageValidator(logger, authToken) { this._logger = logger; this._authToken = authToken; } MessageValidator.prototype.validateMessage = function(serverSideSignature, message) { const calculatedHash = this._calculateHmacFromMessage(message); this._logger.debug("Validating signature '%s' == '%s'", serverSideSignature, calculatedHash); return serverSideSignature == calculatedHash; }; MessageValidator.prototype._calculateHmacFromMessage = function(message) { return crypto.createHmac("sha256", this._authToken).update(message).digest("hex"); }; module.exports = MessageValidator;
/* ====================================================================== NewsBar v1.2 (modified to Forum Images NewsFader 1.0) (c) 2002 VASIL DINKOV- PLOVDIV, BULGARIA Vasil Dinkov's NewsBar v1.2 is modified for use and distribution by forumimages.com with the author's kind permission. ====================================================================== Forum Images NewsFader 1.0 A Forum Images Production -- http://www.forumimages.us/ Authors: SamG, Daz License: FI Free to Use and Distribute - Please see the included licenses.html file before using this software. A copy of the license that applies to this script can be found on the Forum Images site should it not be included; http://www.forumimages.us/terms.html ====================================================================== */ // <![CDATA[ var loadImage = new Image(), regexpResult = null; for ( var i = 0; i < newsContent.length; i++ ) { if ( pauseOnMouseover ) newsContent[i] = newsContent[i].replace(/<a(\s\w+=".+")*>/gi, '<a$1 onmouseout="newsNew();" onmouseover="clearTimeout(newsEvent);">'); if ( regexpResult = newsContent[i].match(/<img[^<]+\/>/gi) ) { for ( var j = 0; j < regexpResult.length; j++ ) { loadImage.src = regexpResult[j].replace(/.+src="(.+)".+/i, '$1'); } } } defaultNewsTimeout *= 1000; newsTimeout *= 1000; var contentIndex = 0, text = null; if ( fade ) var b = startBlue, fadeEvent = null, g = startGreen, r = startRed; document.write(defaultNews); var newsEvent = window.setTimeout('newsNew()', defaultNewsTimeout); function newsNew() { text = newsContent[contentIndex]; contentIndex++; document.getElementById('finewsdisplay').innerHTML = text; if ( fade ) fadeNews(); if ( contentIndex == newsContent.length ) contentIndex = 0; newsEvent = window.setTimeout('newsNew()', newsTimeout); } function fadeNews() { if ( fadeToDark ) { if ( (r >= endRed) && (g >= endGreen) && (b >= endBlue) ) { document.getElementById('finewsdisplay').style.color = 'rgb(' + r + ', ' + g + ', ' + b + ')'; fadeEvent = setTimeout('fadeNews()', 1); b -= 7; g -= 7; r -= 7; return; } } else { if ( (r <= endRed) && (g <= endGreen) && (b <= endBlue) ) { document.getElementById('finewsdisplay').style.color = 'rgb(' + r + ', ' + g + ', ' + b + ')'; fadeEvent = setTimeout('fadeNews()', 1); b += 7; g += 7; r += 7; return; } } document.getElementById('finewsdisplay').style.color = 'rgb(' + endRed + ', ' + endGreen + ', ' + endBlue + ')'; b = startBlue; g = startGreen; r = startRed; } function newsPopUp(uri) { var newWindow = window.open(uri, newsPopUpName, newsPopUpFeatures); } // ]]>
import React from 'react'; import './App.css'; import BioContainer from './pages/bio/BioContainer'; function App() { return ( <BioContainer /> ); } export default App;
var searchData= [ ['setperiod',['setPeriod',['../class_m_d___r_encoder.html#a8ec925294ebb75ae551ce0a4892bb519',1,'MD_REncoder']]], ['speed',['speed',['../class_m_d___r_encoder.html#aaddbd62c5f93cca45e89a6819c3de514',1,'MD_REncoder']]] ];