text
stringlengths
7
3.69M
'use strict' const PomodoroType = require('../models/pomodoro_type.model') // Create and save the new PromodoroType exports.create = (req, res) => { PomodoroType.create({ title: req.body.title || 'Untitle pomodoro', time: req.body.time || '25min' }, function(err, pomodoro_type) { if(err) { return res.status(500).send({ message: err.message || "Some error ocurred while createing the Pomodoro Type" }) } return res.send(pomodoro_type) }) } // Retrive and return all pomodoro_types from the database exports.findAll = (req, res) => { PomodoroType.find() .then(pomodoro_types => { return res.send(pomodoro_types) }).catch(err => { return res.status(500).send({ message: err.message || "Some error ocurred while retrieving pomodoro_types" }) }) } // Find a single pomodoro_type with a id exports.findOne = (req, res) => { PomodoroType.findById(req.params.id) .then(pomodoro_type => { if(!pomodoro_type) { return res.status(404).send({ message: "PomodoroType not found with id: " + req.params.id }) } return res.send(pomodoro_type) }).catch(err => { if(err.kind === 'ObjectId') { return res.status(404).send({ message: "PomodoroType not found with id: " + req.params.id }) } return res.status(500).send({ message: "Error retrieving pomodoro_type with id" + req.params.id }) }) } // Update a pomodoro_type indentified by id exports.update = (req, res) => { PomodoroType.findByIdAndUpdate(req.params.id, { title: req.body.title, time: req.body.time }, {new: true}) .then(pomodoro_type => { if(!pomodoro_type) { return res.status(400).send({ message: "PomodoroType not found with id: " + req.params.id }) } return res.send(pomodoro_type); }).catch( err => { if(err.kind === 'ObjectId') { return res.status(404).send({ message: "PomodoroType pomodoro_type found with id: " + req.params.id }) } return res.status(500).send({ message: "Error updating pomodoro_type with id: " + req.params.id }) }) } // Delete a pomodoro_type indentified by id exports.delete = (req, res) => { PomodoroType.findByIdAndRemove(req.params.id) .then(pomodoro_type => { if(!pomodoro_type) { return res.status(404).send({ message: "PomodoroType not found with id: " + req.params.id }) } return res.send(pomodoro_type) }).catch(err => { if(err.kind === 'ObjectId') { return res.status(404).send({ message: "PomodoroType not found with id:" + req.params.id }) } return res.status(500).send({ message: "Could not delete pomodoro_type with id: " + req.params.id }) }) }
import React from 'react'; import './App.css'; import 'typeface-lato'; import 'typeface-fira-code'; import 'aos/dist/aos.css'; import AOS from 'aos'; import FrontPage from "./Pages/FrontPage"; import FeaturedProjects from "./Pages/FeaturedProjects"; import NavBar from "./Components/NavBar"; import {useTransition, animated} from 'react-spring'; class App extends React.Component { constructor(props){ super(props); AOS.init({ duration : 1500 }) } render () { return ( <div> <NavBar/> <div data-aos={"fade-down"} > <FrontPage/> </div> </div> ) } } export default App;
/* * ISC License * * Copyright (c) 2018, Andrea Giammarchi, @WebReflection * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH * REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY * AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, * INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM * LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */ 'use strict'; const hyperHTML = require('viperhtml'); const {site} = require('../config.js'); const config = { title: 'hyperHTML', documentation: 'hyperhtml', github: 'https://github.com/WebReflection/hyperHTML', }; const content = () => { return hyperHTML` <div class="container"> <div class="tile is-ancestor"> <div class="tile is-parent is-4"> <article class="tile is-child has-text-centered"> <p class="title">hyper(HTML)</p> <p class="subtitle">Declarative Front End</p> <img src="${site.baseurl + '/img/hyperhtml.svg'}" alt="hyperHTML"> </article> </div> <div class="tile is-parent is-8"> <article class="tile is-child"> <div class="content"> <p> Created to <a href="https://medium.com/@WebReflection/hyperhtml-a-virtual-dom-alternative-279db455ee0e">simplify </a> DOM performance best practices, <a href="${config.github}">hyperHTML</a> is 100% ECMAScript compliant and it weights about 5Kb, featuring: </p> <ul> <li>best in class repeated renders and updates performance</li> <li>declarative and reactive UI via standard <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Template_literals">template literals</a></li> <li>an ideal solution via <a href="https://webpack.js.org/">Webpack</a> bundles</li> <li>auto sanitized text content when needed</li> <li>partial outputs between nodes</li> <li>asynchronous content, renders on demand</li> </ul> <p> <strong>Framework agnostic</strong>, <em>hyperHTML</em> can be used to render any view, including <a href="https://w3c.github.io/webcomponents/spec/custom/">Custom Elements</a> and Web Components. </p> <p style="min-height:32px;"> <img src="https://coveralls.io/repos/github/WebReflection/hyperHTML/badge.svg?branch=master" alt="code coverage"> <a class="github-button" href="${config.github}" data-icon="octicon-star" data-show-count="true" aria-label="Star WebReflection/hyperHTML on GitHub">Star</a> </p> </div> </article> </div> </div> </div>`; }; module.exports = { config, content, };
var Browser = require('browser'); module.exports.get = function (assert) { var browser = new Browser; var executed = 0; browser .get('https://192.168.0.5') .tap(function (storage, response, data) { executed++; assert.deepEqual(storage, {}); assert.ok(/cookies/.test(response.headers['set-cookie'])); }) .end(); setTimeout(function () { assert.equal(executed, 1) }, 2000); } module.exports['get with opts'] = function (assert) { var browser = new Browser; var executed = 0; browser .get({ url : 'https://192.168.0.5' }) .tap(function (storage, response, data) { executed++; assert.deepEqual(storage, {}); assert.ok(/cookies/.test(response.headers['set-cookie'])); }) .end(); setTimeout(function () { assert.equal(executed, 1) }, 2000); }
import React, { Component } from "react"; import { FaSmile } from "react-icons/fa"; import "./smile.css"; class Smile extends Component { render() { return ( <div className="bouncy-smile"> <FaSmile /> </div> ); } } export default Smile;
import { faAddressBook, faCalendar, faChevronDown, faSquare } from "@fortawesome/free-solid-svg-icons" import { FontAwesomeIcon } from "@fortawesome/react-fontawesome" import { useRef, useState } from "react" import DatePicker from './UI/DatePicker' import moment from 'moment' const CustomInput = ({post}) => { const [date, setDate] = useState(moment().valueOf()) const [dateIsOn, setDateIsOn] = useState(false) const changingDateFunc = (data) => { setDate(data) } const [focused, setFocused] = useState(false) const focus = (e) => { e.preventDefault() if(!focused){ setFocused(true) textArea.current.focus() document.addEventListener('mousedown',outSideClick) } } const outSideClick = (e) => { if(!refInput.current.contains(e.target)){ setFocused(false) textArea.current.blur() document.removeEventListener('mousedown',outSideClick) } } const refInput = useRef() const textArea = useRef() const [selectIsOpened, setSelectIsOpened] = useState(false) const [selectValue, setSelectValue] = useState({ _id: 0, value: 'No List' }) const handleChangeSelected = (e) => { setSelectValue({_id: e.currentTarget.getAttribute('data'), value: e.currentTarget.getAttribute('name')}) } const sendData = () => { if(text.length > 0) { setText('') setDate(moment().valueOf()) setSelectValue({ _id: 0, value: 'No List' }) textArea.current.innerText = '' post(text, date.value,selectValue.value) } } const hide = () => { } const [text,setText] = useState('') const handleText = (e) => { if(e.key=='Enter'){ e.preventDefault() console.log('enter') sendData() }else{ setText(e.target.innerText) } } return( <div ref={refInput} className={focused?'CustomInputBox active':'CustomInputBox'} onClick={focus}> <div className='quadrat'> <div className='iconBox'><FontAwesomeIcon icon={faSquare}></FontAwesomeIcon></div> </div> <span ref={textArea} onKeyDown={handleText} className='inputItem' role="textbox" contentEditable='true'> </span> <div className='rightSide'> <div className='calendarBox'> <FontAwesomeIcon icon={faCalendar} onClick={()=>setDateIsOn(!dateIsOn)}></FontAwesomeIcon> <div className={dateIsOn?'datePickerBoxDrop isOnDateSelect':'datePickerBoxDrop'}> <DatePicker onChange={changingDateFunc} hide={hide}></DatePicker> </div> </div> <div className='select' onClick={()=>{setSelectIsOpened(!selectIsOpened)}}> <div className='outLiendeCircle'></div> <p>{selectValue.value}</p> <FontAwesomeIcon icon={faChevronDown}></FontAwesomeIcon> {selectIsOpened?<div className='dropDown'> <ul> <li className={selectValue===1?'selectedList':''} onClick={handleChangeSelected} data='1' name='Contacts List'><FontAwesomeIcon icon={faAddressBook}></FontAwesomeIcon>Contacts List</li> <li className={selectValue===2?'selectedList':''} onClick={handleChangeSelected} data='2' name='Main List'><FontAwesomeIcon icon={faAddressBook}></FontAwesomeIcon>Main List</li> <li className={selectValue===3?'selectedList':''} onClick={handleChangeSelected} data='3' name='Not Main List'><FontAwesomeIcon icon={faAddressBook}></FontAwesomeIcon>Not Main List</li> <li className={selectValue===4?'selectedList':''} onClick={handleChangeSelected} data='4' name='Logic List'><FontAwesomeIcon icon={faAddressBook}></FontAwesomeIcon>Logic List</li> <li className={selectValue===5?'selectedList':''} onClick={handleChangeSelected} data='5' name='To do List'><FontAwesomeIcon icon={faAddressBook}></FontAwesomeIcon>To do List</li> </ul> </div>:''} </div> </div> </div> ) } export default CustomInput
//REDUCERS import {SET_NEW_GAME, SET_GUESS, TOGGLE_INFO} from '../actions'; export const initialState = { guesses: [], feedback: 'Make your guess!', correctAnswer: Math.floor(Math.random() * 100) + 1, showInfoModal: false } export const guessReducer = (state=initialState, action) => { if (action.type === SET_NEW_GAME) { return Object.assign({}, state, { correctAnswer: action.correctAnswer, guesses: action.guesses, feedback: action.feedback, }); } else if (action.type === SET_GUESS) { const guess = parseInt(action.guess, 10); if (isNaN(guess)) { return Object.assign({}, state, { feedback: 'Please enter a number' }); } const answer = state.correctAnswer; const difference = Math.abs(guess - answer); let feedback; if (difference >= 50) { feedback = 'You\'re Ice Cold...'; } else if (difference >= 30) { feedback = 'You\'re Cold...'; } else if (difference >= 10) { feedback = 'You\'re Warm'; } else if (difference >= 1) { feedback = 'You\'re Hot!'; } else { feedback = 'You got it!'; } return Object.assign({}, state, { feedback, guesses: state.guesses.concat(action.guess) }); } else if (action.type === TOGGLE_INFO) { return Object.assign({}, state, { showInfoModal: !state.showInfoModal }); } return state; }
// Model for current day's data const mongoose = require('mongoose'); const RecentDataSchema = new mongoose.Schema({ recordDate: { type: Date, required: true }, violationCount: { type: Number, required: true }, headcount: { type: Number, required: true }, recordLocation: { type: String, required: true } }); module.exports = mongoose.model('RecentData', RecentDataSchema);
var config = require('../../config'); var post = require('../../models/post'); var category = require('../../models/category'); // Show create page exports.showCreatePost = function(req, res, next) { // Fetch category data category.findAll() .then(function(categories) { res.render('admin/create_post', { config: config, categories: categories }); }); } // Create a new post exports.createPost = function(req, res, next) { var title = req.body.title; var keywords = req.body.keywords; var url = req.body.url; var category = req.body.category; var contents = req.body.contents; post.createOne({ title: title, contents: contents, url: url, category: category, keywords: keywords }).then(function(p) { console.log(p); res.redirect('/admin/post/view'); }).catch(function(err) { if (err) { res.redirect('/admin/post/create'); } }); // res.json('1') } // Show list of posts exports.viewPost = function(req, res, next) { post.findAll() .then(function(posts) { res.render('admin/view_post', { config: config, posts: posts }) }); } exports.removePost = function(req, res, next) { post.removeById(req.params.id) .then(function() { res.redirect('/admin/post/view'); }); } exports.showAlterPost = function(req, res, next) { var id = req.params.id; var p, categories; function GetCategories(ps) { var defer = Promise.defer(); p = ps; category.findAll() .then(function(cs) { categories = cs; defer.resolve(post); }); return defer.promise; } function Render() { res.render('admin/alter_post', { config: config, post: p, categories: categories }); } post.findOneById(id).then(GetCategories).then(Render); } exports.alterPost = function(req, res, next) { var id = req.params.id; var title = req.body.title; var keywords = req.body.keywords; var url = req.body.url; var category = req.body.category; var contents = req.body.contents; post.updateById(id, { title: title, contents: contents, url: url, category: category, keywords: keywords }).then(function(p) { console.log(p); res.redirect('/admin/post/view'); }).catch(function(err) { if (err) { res.redirect('/admin/post/alter/'+id); } }); }
module.exports = { // devServer: { // host: '0.0.0.0', // port: 8080, // publicPath: '/', //这里解决静态资源引用路径问题 // // 设置代理 // proxy: { // "/api": { // // 登录接口 账号admin 密码123456 // target: 'https://result.eolinker.com/AfMQniX89802140bb73e4e303e18a7abdaeda367dc9b244?uri=', // // http://timemeetyou.com:8889/api/private/v1/ crm项目接口 // ws: true, // 是否启用websockets // changOrigin: true, //开启代理 // secure: false, // 将安全设置为false,才能访问https开头的 // pathRewrite: { // '^/api': '' //这里理解成用‘/api’代替target里面的地址 // } // } // } // } configureWebpack: { externals: { 'AMap': 'AMap' // 高德地图配置 } } }
let day = prompt('Please enter the day: '); let message; if (day == 'monday' || day == 'wednesday' || day == 'thursday') { message = 'There is single session'; } else if (day == 'saturday') { message = 'There is double session'; } else if (day == 'sunday' ||day == 'tuesday' || day == 'friday') { message = 'There is no live session'; } else { message = 'Unvalid entry.'; } alert(message);
import React from 'react'; const DonateText = () => { return ( <> <p>freeCodeCamp is a highly efficient education nonprofit.</p> <p> In 2019 alone, we provided 1,100,000,000 minutes of free education to people around the world. </p> <p> Since freeCodeCamp's total budget is only $373,000, that means every dollar you donate to freeCodeCamp translates into 50 hours worth of technology education. </p> <p> When you donate to freeCodeCamp, you help people learn new skills and provide for their families. </p> <p> You also help us create new resources for you to use to expand your own technology skills. </p> </> ); }; DonateText.displayName = 'DonateText'; export default DonateText;
//参数说明: //nameContainer : 存放所选名称的容器的name //valueContainer : 存放所选值的容器的name //defaultState : 节点的默认开闭状态 1为开,其他值为闭合 function ShowPaymentTree(nameContainer, valueContainer, defaultState) { if ($("#dvMain_org").length == 0) { $("body").append('<div id="dvMain_org" style="padding:5px 5px 5px 5px;overflow-x:hidden;">' + '<div class="easyui-panel" style="height:26px;">' + '<a href="javascript:void(0)" class="easyui-linkbutton l-btn l-btn-small" data-options="iconCls:\'icon-ok\'" id="btnSel_org"><span class="l-btn-left l-btn-icon-left"><span class="l-btn-text">选择</span><span class="l-btn-icon icon-ok">&nbsp;</span></span></a>' + '</div>' + '<img id="loadingImage" class="progress" src="/Content/Images/loading.gif" />' + '<ul id="tt_org" style="width:300px; height:300px;display:none;"></ul>' + '</div>'); $("#dvMain_org").css("display", "none"); $("#btnSel_org").click(function () { var selectedNode = $('#tt_org').tree("getSelected"); if (selectedNode != null) { //鉴于配置中name的使用率远远大于id,因此这里用name进行筛选 $("input[name='" + nameContainer + "']").val(selectedNode.text); $("input[name='" + valueContainer + "']").val(selectedNode.id); $("#dvMain_org").dialog("close"); } else { $.messager.alert("提示", "请选择一个类型"); } }); $('#tt_org').tree({ url: '/bi_Payment/GetTree', onClick: function (node) {//单击事件 $(this).tree('toggle', node.target); }, onLoadSuccess: function () { $("#loadingImage").css("display", "none"); $(this).css("display", ""); if ($("input[name='" + valueContainer + "']").val() != "") { var leafnode = $('#tt_org').tree('find', $("input[name='" + valueContainer + "']").val()); var node = leafnode; while ($('#tt_org').tree('getParent', node.target) != null) { node = $('#tt_org').tree('getParent', node.target); $('#tt_org').tree('expand', node.target); } $('#tt_org').tree('select', leafnode.target); } } }); } else { $('#tt_org').tree('reload'); } $("#dvMain_org").css("display", "block"); $('#dvMain_org').dialog({ shadow: false, width: 400, height: 400, modal: true, title: "选择所属类别" }); } //function PaymentDelete(datagrid, title, msg, url, width, height) { // $.extend($.messager.defaults, { ok: "确定", cancel: "取消" }) // $.messager.confirm(title, msg, function (r) { // if (r) { // var ids = []; // var rows = $("#" + datagrid).datagrid('getSelections'); // getDeleteIDssss(ids, rows, url, datagrid) // $.ajax({ // url: url + "?keys=" + ids, // type: "post", // success: function (result) { // if (!result.HasError) { // for (var i = 0; i < rows.length; i++) { // var index = $("#" + datagrid).datagrid('getRowIndex', rows[i]); // $("#" + datagrid).datagrid('deleteRow', index); // } // $.messager.alert("提示", "已删除" + ids.length + "条记录"); // } // else { // $.messager.alert("提示", result.Error); // } // }, // error: function (xmlhttprequest, text, error) { // showError(error); // } // }); // } // else { // cancel(); // } // }); //} //function getDeleteIDssss(ids, rows, url, id) { // var selectCol = $("#" + id).datagrid('options').columns[0][0].field; // for (var i = 0; i < rows.length; i++) // { ids.push(rows[i][selectCol]) } // return ids; //}
import React from 'react'; import axios from 'axios'; import moment from 'moment'; import Tags from './Tag'; import '../css/info.css'; export default class Info extends React.Component { constructor() { super() this.state = { age: '', gender: '', orientation: '', latitude: '', longitude: '', address: '', lastConnection: '', tags: '' } } componentWillMount() { const { birthday, gender, orientation, location, lastConnection } = this.props.profile; const age = moment().diff(birthday, 'years'); const latitude = location.split(',')[0]; const longitude = location.split(',')[1]; this.setState({ age, birthday, gender, orientation, latitude, longitude, lastConnection }) } componentDidMount() { const url = `https://maps.googleapis.com/maps/api/geocode/json?latlng=${this.state.latitude},${this.state.longitude}&key=AIzaSyBhsxTkddjmFdZsCPq82usy-ASv1ATzpV0`; axios.get(url).then((data) => { return this.setState({address: data.data.results[0].formatted_address}); }).catch(err => console.error('Error: ', err)); } render() { return ( <div className="col-md-6 col-sm-12 col-xs-12"> <div className="panel panel-default"> <div className="panel-heading"> <h4 className="panel-title">Informations</h4> </div> <div className="panel-body"> <div className="col-md-12"> <table id='infos'> <tbody> <tr> <td><b>Age</b></td> <td>{this.state.age}</td> </tr> <tr> <td><b>Gender</b></td> <td>{this.state.gender}</td> </tr> <tr> <td><b>Orientation</b></td> <td>{this.state.orientation}</td> </tr> <tr> <td><b>Address</b></td> <td>{this.state.address}</td> </tr> <tr> <td><b>Last connection</b></td> <td>{this.state.lastConnection}</td> </tr> <tr> <td><b>Tags</b></td> <td> <Tags tags={this.state.tags} /> </td> </tr> </tbody> </table> </div> </div> </div> </div> ); } }
/* * productGroupSearchController.js * * Copyright (c) 2017 HEB * All rights reserved. * * This software is the confidential and proprietary information * of HEB. */ 'use strict'; /** * The controller for the product group search. * * @author vn75469 * @since 2.15.0 */ (function () { var app = angular.module('productMaintenanceUiApp'); app.controller('ProductGroupSearchController', ProductGroupSearchController); app.filter('propsFilter', function () { return function (items, props) { var out = []; if (angular.isArray(items)) { var keys = Object.keys(props); items.forEach(function (item) { var itemMatches = false; for (var i = 0; i < keys.length; i++) { var prop = keys[i]; var text = props[prop].toLowerCase(); if (item[prop].toString().toLowerCase().indexOf(text) !== -1) { itemMatches = true; break; } } if (itemMatches) { out.push(item); } }); } else { // Let the output be the input untouched out = items; } return out; }; }); app.constant('productGroupConstant', { CHANGE_MODE_EVENT: 'changeMode', CHANGE_MODE_EVENT_AFTER_DELETING: 'changeModeAfterDeleting', SEARCH_MODE: 'search-mode', DETAIL_MODE: 'detail-mode', CHANGE_PRODUCT_GROUP: 'reloadProductInfo', IMAGE_ENCODE: 'data:image/jpg;base64,', IMAGE_PRIORITY_CD_ALTERNATE: "A ", IMAGE_PRIORITY_CD_PRIMARY: "P ", SUCCESSFULLY_UPDATED: "Successfully Updated", }); /** * Directive for filter on textbox: input number only. */ app.directive('numbersOnly', function(){ return { require: 'ngModel', link: function(scope, element, attrs, modelCtrl) { modelCtrl.$parsers.push(function (inputValue) { // this next if is necessary for when using ng-required on your input. // In such cases, when a letter is typed first, this parser will be called // again, and the 2nd time, the value will be undefined if (inputValue == undefined) return ''; var transformedInput = inputValue.replace(/[^0-9]/g, ''); if (transformedInput!=inputValue) { modelCtrl.$setViewValue(transformedInput); modelCtrl.$render(); } return transformedInput; }); } }; }); ProductGroupSearchController.$inject = ['$rootScope', '$scope', 'ngTableParams', 'codeTableApi', 'productGroupApi', 'imageInfoApi', 'productGroupConstant', '$state', 'appConstants','CustomHierarchyApi','$http', 'ProductGroupService', 'customHierarchyService', 'DownloadImageService', 'ProductSearchService']; /** * Product Group Search controller definition. * @param $rootScope * @param $scope scope of the product group. * @param codeTableApi * @param ngTableParams * @param productGroupApi * @param imageInfoApi * @param productGroupConstant * @param productGroupService * @param customHierarchyApi * @param $http * @constructor */ function ProductGroupSearchController($rootScope, $scope, ngTableParams, codeTableApi, productGroupApi, imageInfoApi, productGroupConstant, $state, appConstants,customHierarchyApi, $http, productGroupService, customHierarchyService, downloadImageService, productSearchService) { var self = this; const FROM_PRODUCT_GROUP_SEARCH = "FROM_PRODUCT_GROUP_SEARCH"; /** * Flag for showing screen: PG Search or PG Details * @type {string} */ self.mode = productGroupConstant.SEARCH_MODE; /** * Messages. * @type {string} */ self.MESSAGE_CONFIRM_CLOSE = "Unsaved data will be lost. Do you want to save the changes before continuing?"; self.NO_PRODUCT_SELECTED = "<h6>No Product Group is selected.<br>" + "Please select Product Group Search criteria to view Product Group from the left pane “Product Group Search\".</h6>"; self.NO_MATCHES_FOUND = "<h6>No matches found.</h6>"; self.MESSAGE_CUSTOMER_HIERARCHY_ERROR = "Customer Hierarchy search only applies for lowest level. Please select a lowest level and try again."; /** * Define search type. * @type {number} */ const COMBINED_SEARCH = -1; const NOT_INPUT_KEYWORD = 0; const SEARCH_BY_ID = 1; const SEARCH_BY_NAME = 2; const SEARCH_BY_TYPE = 3; const SEARCH_BY_CUSTOMER_HIERARCHY = 4; const BROWSER_ALL = 5; /** * Whether or not the controller is waiting for data. * * @type {boolean} */ self.isWaiting = false; /** * Flag check if search by keyword or search all. * @type {boolean} */ self.isBrowserAll = false; /** * Contains error message. * @type {string|*} */ self.error = self.NO_PRODUCT_SELECTED; /** * Data product group id input. * @type {string} */ self.productGroupIdInput = ""; /** * Data product group name input. * @type {string} */ self.productGroupNameInput = ""; /** * Data product group type input. * @type {string} */ self.productGroupTypeInput = ""; /** * Data customer hierachy input input. * @type {string} */ self.customerHierarchyInput = ""; /** * List of all Product Group Types. * @type {Array} */ self.productGroupTypes = []; self.totalRecord = 0; /** * HEB hierarchy context * * @type {{id: string, description: string, parentEntityId: number, childRelationships: null, isCollapsed: boolean}} */ self.hierarchyContext = { "id" : "CUST", "description" : "HEB.Com", "parentEntityId" : 2864, "childRelationships" : null, "isCollapsed" : true }; /** * Contain type of search. */ self.searchType; /** * Contain search description show on header of result table. * * @type {string} */ self.searchDescription = "<strong>Search</strong>"; /** * Flag check for show/hide customer hierarchy. * @type {boolean} */ self.isShowCustomerHierarchy = false; /** * Flag wait load customer hierachy. * @type {boolean} */ self.isWaitingForLoadCustomerHierarchyResponse = false; /** * Customer hierachy context. * @type {Array} */ self.customerHierarchyContext = []; /** * Customer hierachy context root. * @type {Array} */ self.customerHierarchyContextRoot = []; /** * Customer hierachy search text. * @type {String} */ self.customHierarchySearchText = ""; /** * Flag searching for customer hierachy. * @type {boolean} */ self.searchingForCustomHierarchy = false; /** * Flag searching for customer hierachy. * @type {boolean} */ self.isSearchingOnClientSide = false; /** * Define for level of hierachy. */ var STRING_TAG = "#"; var ADD_CLICK_BACKGROUND_CLASS = "add-click-background"; var ADD_CLICK_BACKGROUND_CLASS_REFERENCE = ".add-click-background"; var FIRST_HIERARCHY_LEVEL_ELEMENT_ID_PREFIX = "firstLevel"; var SECOND_HIERARCHY_LEVEL_ELEMENT_ID_PREFIX = "secondLevel"; var THIRD_HIERARCHY_LEVEL_ELEMENT_ID_PREFIX = "thirdLevel"; var FOURTH_HIERARCHY_LEVEL_ELEMENT_ID_PREFIX = "fourthLevel"; var FIFTH_HIERARCHY_LEVEL_ELEMENT_ID_PREFIX = "fifthLevel"; var FIRST_HIERARCHY_LEVEL_ELEMENT_ID_PREFIX_POP_UP = "firstLevelPopUp"; var SECOND_HIERARCHY_LEVEL_ELEMENT_ID_PREFIX_POP_UP = "secondLevelPopUp"; var THIRD_HIERARCHY_LEVEL_ELEMENT_ID_PREFIX_POP_UP = "thirdLevelPopUp"; var FOURTH_HIERARCHY_LEVEL_ELEMENT_ID_PREFIX_POP_UP = "fourthLevelPopUp"; var FIFTH_HIERARCHY_LEVEL_ELEMENT_ID_PREFIX_POP_UP = "fifthLevelPopUp"; var STRING_HYPHEN = "-"; /** * Template for searching for custom hierachy. */ self.searchingForCustomHierarchyTextTemplate = "Searching HEB.Com custom hierarchy for: $searchText. Please wait..."; /** * Searching for custom hierachy text */ self.searchingForCustomHierarchyText = null; /** * Flag check if exist/ not exist product group. * * @type {boolean} */ self.isExistProduct = false; /** * The parameters passed to the application from ng-tables getData method. These need to be stored * until all the data are fetched from the backend. * * @type {null} */ self.dataResolvingParams = null; /** * The ngTable object that will be waiting for data while the report is being refreshed. * * @type {?} */ self.defer = null; /** * Selected edited row index. * * @type {null} */ self.selectedRowIndex = -1; /** * Default String of image data if image not found. * @type {string} */ self.IMAGE_NOT_FOUND = 'image-not-found'; /** * Map contains image data. * * @type {Map} */ self.cacheImages = new Map(); /** * Current image loading. * * @type {string} */ self.imageBytes = ''; /** * Start position of page that want to show on Product Group Search results. * * @type {number} */ self.PAGE = 1; /** * The number of records to show on the Product Group Search results. * * @type {number} */ self.PAGE_SIZE = 10; self.isShowDetailCustomerHierarchy = false; /** * call when initial. */ self.init = function(){ if(!customHierarchyService.getDisableReturnToList() || !productSearchService.getDisableReturnToList()){ customHierarchyService.setDisableReturnToList(true); productGroupService.setProductGroupId(null); } self.findAllProductGroupType(); self.buildResultDatatable(true); if(customHierarchyService.getFromPage() == FROM_PRODUCT_GROUP_SEARCH){ customHierarchyService.setFromPage(null); self.isBrowserAll = productGroupService.isBrowserAll(); if(self.isBrowserAll) { self.browserAll(); productGroupService.setProductGroupId(null); productGroupService.setProductGroupTypeCode(null); }else{ self.productGroupId = productGroupService.getProductGroupId(); productGroupService.setProductGroupId(null); self.productGroupNameInput = productGroupService.getProductGroupName(); self.productGroupTypeInput = productGroupService.getProductGroupTypeCode(); self.customerHierarchyInput = productGroupService.getCustomerHierarchy(); self.customHierarchySearchText = productGroupService.getCustomHierarchySearchText(); if(self.customerHierarchyInput!=null && self.customerHierarchyInput != undefined) { self.isSelectedCustomHierarchy = true; self.showHideCustomerHierarchy(); self.showHideDetailCustomerHierarchy(); } productGroupService.setProductGroupId(null); productGroupService.setProductGroupTypeCode(null); self.search(); } productGroupService.setBrowserAll(false); productGroupService.setCustomerHierarchy(null); productGroupService.setCustomHierarchySearchText(null); productGroupService.setProductGroupName(null); }else { if ((productGroupService.getReturnToListFlag() || productGroupService.getNavFromProdGrpTypePageFlag() || productGroupService.getNavigateFromCustomerHierPage()) && productGroupService.getProductGroupId() !== null && productGroupService.getProductGroupId() !== undefined) { self.productGroupIdInput = productGroupService.getProductGroupId(); productGroupService.setProductGroupId(null); self.search(); } } }; /** * get all product group types from api. */ self.findAllProductGroupType = function () { codeTableApi.findAllProductGroupTypes().$promise.then(function (response) { self.productGroupTypes = response; }); }; /** * Handle browser all button. */ self.browserAll = function(){ productGroupService.setBrowserAll(true); productGroupService.setListOfProducts(null); self.success = ''; self.error = ''; self.isBrowserAll = true; self.resetTable(); self.buildResultDatatable(); }; /** * Handle search button. */ self.search = function(){ self.success = ''; self.error = ''; self.isBrowserAll = false; self.searchType = self.getSearchType(); if (self.isCombinedSearch()){ $('#popupWarning').modal({backdrop: 'static', keyboard: true}); $('.modal-backdrop').attr('style', ' z-index: 100000; '); } else if(self.isNotInputKeyword()){ self.isExistProduct = false; self.error = self.NO_PRODUCT_SELECTED; } else if (!self.isNullOrEmpty(self.customerHierarchyInput)){ self.isLowestBranchOrHasNoRelationships(self.customerHierarchyInput) } else { self.resetTable(); self.buildResultDatatable(); } }; /** * Call api to search. */ self.callApiToSearch = function(){ self.isWaiting = true; productGroupApi.findProductGroup(self.getPaginationParams(), self.callApiSuccess, self.callApiError); }; /** * Get pagination params from ui. * * @returns {{page: number, pageSize: number, firstSearch: (boolean|*), productGroupId: null, productGroupName: null, productGroupType: null, customerHierarchy: null}} */ self.getPaginationParams = function(){ var page = (self.dataResolvingParams==null)?0:self.dataResolvingParams.page() - 1; var pageSize = (self.dataResolvingParams==null)?20:self.dataResolvingParams.count(); var paginationParams = { 'page': page, 'pageSize': pageSize, 'firstSearch': self.isFirstSearch(), 'productGroupId': null, 'productGroupName': null, 'productGroupType': null, 'customerHierarchyId': null }; if (!self.isBrowserAll){ if (self.searchType === SEARCH_BY_ID){ if(productGroupService.getReturnToListFlag() && productGroupService.getProductGroupId() !== null && productGroupService.getProductGroupId() !== undefined){ paginationParams.productGroupId = productGroupService.getProductGroupId(); productGroupService.setProductGroupId(null); }else{ paginationParams.productGroupId = self.productGroupIdInput; } } else if(self.searchType === SEARCH_BY_NAME){ paginationParams.productGroupName = self.productGroupNameInput; } else if(self.searchType === SEARCH_BY_TYPE){ paginationParams.productGroupType = self.productGroupTypeInput.productGroupTypeCode.trim(); } else if(self.searchType === SEARCH_BY_CUSTOMER_HIERARCHY){ paginationParams.customerHierarchyId = self.customerHierarchyInput.key.childEntityId; } } return paginationParams; }; /** * Check the status to get or not get the total records from server. * * @returns {boolean|*} true then get the total records or not. */ self.isFirstSearch = function () { return self.dataResolvingParams === null || self.dataResolvingParams.page() === 1; }; /** * Processing if call api success. * * @param response data response from api. */ self.callApiSuccess = function(response){ self.isExistProductSelected = false; self.isWaiting = false; if(self.isFirstSearch()){ self.totalRecord = response.recordCount; } if(self.totalRecord === 0){ self.isExistProduct = false; self.error = self.NO_MATCHES_FOUND; self.searchDescription = "<strong>Searched for \"" + self.getSearchTypeText() + "</strong>\""; } else if(self.totalRecord === 1) { self.resetTable(); self.error = null; var productGroupIds = []; productGroupIds.push(response.data[0].custProductGroupId); self.dataSent = { 'productGroup': response.data[0], 'productGroupIds': productGroupIds }; self.mode = productGroupConstant.DETAIL_MODE; //self.goToProductGroupDetail(response.data[0].custProductGroupId); } else { self.isExistProduct = true; self.error = null; self.dataResolvingParams.total(self.totalRecord); self.defer.resolve(response.data); self.findAllImage(self.getListImageUri(response.data)); if (self.getSearchTypeText() !== BROWSER_ALL){ self.searchDescription = "<strong>Searched for \"" + self.getSearchTypeText() + "</strong>\"" + " Result " + self.getRangeElementOfPage(self.totalRecord) + " of " + self.totalRecord; } else { self.searchDescription = "<strong>Search </strong>" + "Result " + self.getRangeElementOfPage(self.totalRecord) + " of " + self.totalRecord; } } }; /** * Show message error when call api failed. * * @param error error response from api. */ self.callApiError = function(error){ self.isWaiting = false; if (error && error.data) { if (error.data.message) { self.error = error.data.message; } else { self.error = error.data.error; } } else { self.error = "An unknown error occurred."; } }; /** * Build ResultDataTable. * * @param isInitial flag check for ignore call api if init screen. */ self.buildResultDatatable = function (isInitial) { self.resultTable = new ngTableParams( { page: self.PAGE, /* show first page */ count: self.PAGE_SIZE, /* count per page */ }, { counts: [], total: 0, paginationClass: 'min', getData: function ($defer, params) { self.defer = $defer; self.dataResolvingParams = params; self.selectedRowIndex = -1; if(isInitial){ isInitial = false; return; }{ self.callApiToSearch(); } } }); }; /** * Reset data of table. */ self.resetTable = function(){ self.resultTable = null; self.dataResolvingParams = null; self.defer = null; }; /** * Clear search form. */ self.clearSearchForm = function(){ self.productGroupIdInput = ""; self.productGroupNameInput = ""; self.productGroupTypeInput = " "; self.customerHierarchyInput = ""; self.isShowCustomerHierarchy = false; self.isShowDetailCustomerHierarchy = false; }; /** * Get search type to call api. * * @returns value of searchType. */ self.getSearchType = function(){ var returnValue; var countParams = 0; if (!self.isNullOrEmpty(self.productGroupIdInput) || (productGroupService.getReturnToListFlag() && productGroupService.getProductGroupId() !== null && productGroupService.getProductGroupId() !== undefined)){ countParams++; returnValue = SEARCH_BY_ID; } if(!self.isNullOrEmpty(self.productGroupNameInput)){ countParams++; returnValue = SEARCH_BY_NAME; } if(self.productGroupTypeInput !== undefined && self.productGroupTypeInput != null) { if (!self.isNullOrEmpty(self.productGroupTypeInput.productGroupTypeCode)) { countParams++; returnValue = SEARCH_BY_TYPE; } } if(!self.isNullOrEmpty(self.customerHierarchyInput)){ countParams++; returnValue = SEARCH_BY_CUSTOMER_HIERARCHY; } if(countParams === 0){ returnValue = NOT_INPUT_KEYWORD; } else if(countParams > 1){ returnValue = COMBINED_SEARCH; } return returnValue; }; /** * Get search type text: search by id, name or type. * * @returns {*} */ self.getSearchTypeText = function(){ if (!self.isBrowserAll){ if (self.searchType === SEARCH_BY_ID){ return "Product Group ID: " + self.productGroupIdInput; } else if(self.searchType === SEARCH_BY_NAME){ return "Product Group Name: " + self.productGroupNameInput; } else if(self.searchType === SEARCH_BY_TYPE){ return "Product Group Type: " + self.productGroupTypeInput.productGroupType.trim(); } else if(self.searchType === SEARCH_BY_CUSTOMER_HIERARCHY){ return "Customer Hierarchy: " + self.customerHierarchyInput.childDescription.shortDescription; } } else { return BROWSER_ALL; } }; /** * Get range of element to show on screen. * * @param totalRecords. * @returns String text of search range show on search description. */ self.getRangeElementOfPage = function(totalRecords){ var startRange = self.PAGE_SIZE*self.getPaginationParams().page + 1; var lastRange; //Check if page is a last page. if ((Math.ceil(totalRecords / self.PAGE_SIZE) - 1) === self.getPaginationParams().page){ lastRange = totalRecords; } else { lastRange = self.PAGE_SIZE*self.getPaginationParams().page + self.PAGE_SIZE; } //Check if page has only one item. if (startRange === lastRange){ return startRange; } else { return startRange + " - " + lastRange; } }; /** * Check if not input keyword to search * * @returns {boolean} true if user not input keyword */ self.isNotInputKeyword = function(){ return self.searchType === NOT_INPUT_KEYWORD; }; /** * Check if search type is combine search. * * @returns {boolean} */ self.isCombinedSearch = function(){ return self.searchType === COMBINED_SEARCH; }; /** * Check object null or empty * * @param object * @returns {boolean} true if Object is null/ false or equals blank, otherwise return false. */ self.isNullOrEmpty = function (object) { return object === null || !object || object === ""; }; /** * Handle button Show or hide CustomerHierarchy */ self.showHideCustomerHierarchy = function(){ self.isShowCustomerHierarchy = !self.isShowCustomerHierarchy; if (self.customerHierarchyContext.length === 0 ){ self.loadCustomerHierarchyContext(); } }; /** * Check object null or empty * * @param object * @returns {boolean} true if Object is null/ false or equals blank, otherwise return false. */ self.isNullOrEmpty = function (object) { return object === null || !object || object === "" || object === undefined; }; /** * Set selected index of selected row. * * @param index the index of selected row. */ self.setSelectedRowIndexAction = function (index) { if (self.selectedRowIndex == index) { self.selectedRowIndex = -1; } else { self.selectedRowIndex = index; } }; /** * Find image in list images. * * @param imageUri uri of image. * @returns {*} image data of image. */ self.findImageByUri = function(imageUri){ if (self.cacheImages.has(imageUri)) { return self.cacheImages.get(imageUri); } else { return ''; } }; /** * Get list image uri text of product group. * * @param data list images. * @returns {Array} list images uri of images. */ self.getListImageUri = function(data){ var listUri = []; angular.forEach(data,function (element) { if (element.primaryImage !== null){ listUri.push(element.primaryImage.uriText); } }); return listUri; }; /** * Call api to find all image. * * @param listUri */ self.findAllImage = function(listUri){ angular.forEach(listUri, function (uri) { if (!self.cacheImages.has(uri)) { imageInfoApi.getImages(uri , function (results) { if (results.data != null && results.data != '') { self.cacheImages.set(uri, productGroupConstant.IMAGE_ENCODE + results.data); } else { self.cacheImages.set(uri, self.IMAGE_NOT_FOUND); } } ); } }); }; /** * Show full product group image. * * @param uri uriText of image. */ self.showFullImage = function (productGroup) { self.imageFormat = productGroup.primaryImage.imageFormatCode; if (self.cacheImages.has(productGroup.primaryImage.uriText)) { self.imageBytes = self.cacheImages.get(productGroup.primaryImage.uriText); } $('#imageModal').modal({ backdrop: 'static', keyboard: true }); }; /** * Get list product group id and product group sent to detail page * * @param productGroup product group selected. */ self.goToProductGroupDetail = function(productGroup){ customHierarchyService.setDisableReturnToList(true); productGroupService.setNavFromProdGrpTypePageFlag(false); productGroupService.setCustomerHierarchyId(null); customHierarchyService.setEntityIdReceived(null); self.isWaiting = true; var paginationParams = {}; var productGroupIds = []; if (!self.isBrowserAll){ if (self.searchType === SEARCH_BY_ID){ paginationParams.productGroupId = self.productGroupIdInput; } else if(self.searchType === SEARCH_BY_NAME){ paginationParams.productGroupName = self.productGroupNameInput; } else if(self.searchType === SEARCH_BY_TYPE){ paginationParams.productGroupType = self.productGroupTypeInput.productGroupTypeCode.trim(); } else if(self.searchType === SEARCH_BY_CUSTOMER_HIERARCHY){ paginationParams.customerHierarchyId = self.customerHierarchyInput.key.childEntityId; } } productGroupApi.findProductGroupIds(paginationParams).$promise.then(function (response) { productGroupIds = response; self.dataSent = { 'productGroup': productGroup, 'productGroupIds': productGroupIds }; self.isWaiting = false; self.mode = productGroupConstant.DETAIL_MODE; }); }; /** * watcher scope navigate to customer hierarchy */ $scope.$on('goToCustomerHierarchy', function(event) { self.goToCustomerHierarchy(productGroupService.getCustomerHierarchyId()); }); /** * Handle when click on facing customer hierarchy link */ self.clickOnFacingCustomerHierarchy = function(customerHierarchyId) { customHierarchyService.setNavigatedFromOtherPage(true); customHierarchyService.setNavigatedForFirstSearch(true); customHierarchyService.setNotFacingHierarchyLink(false); customHierarchyService.setHierarchyContextId(null); customHierarchyService.setSelectedHierarchyContextForNavigation(null); customHierarchyService.setSelectedHierarchyContextRoot(null); customHierarchyService.setSelectedCustomHierarchyLevel(null); customHierarchyService.setEntityIdReceived(null); self.goToCustomerHierarchy(customerHierarchyId); } /** * Go to customer hierarchy */ self.goToCustomerHierarchy = function(customerHierarchyId){ customHierarchyService.setFromPage(FROM_PRODUCT_GROUP_SEARCH); customHierarchyService.setSelectedTab('PRODUCT_GROUP'); if(productGroupService.getNavigateFromCustomerHierPage()){ productGroupService.setNavigateFromCustomerHierPage(null); customHierarchyService.setDisableReturnToList(true); } else{ customHierarchyService.setDisableReturnToList(false); } productGroupService.setCustomerHierarchyId(customerHierarchyId); productGroupService.setBrowserAll(self.isBrowserAll); if (!self.isBrowserAll){ if (self.searchType === SEARCH_BY_ID){ if(productGroupService.getReturnToListFlag() && productGroupService.getProductGroupId() !== null && productGroupService.getProductGroupId() !== undefined){ }else{ productGroupService.setProductGroupId(self.productGroupIdInput); } //productGroupService.setProductGroupId(paginationParams.productGroupId); } else if(self.searchType === SEARCH_BY_NAME){ productGroupService.setProductGroupName(self.productGroupNameInput); } else if(self.searchType === SEARCH_BY_TYPE){ productGroupService.setProductGroupTypeCode(self.productGroupTypeInput); } else if(self.searchType === SEARCH_BY_CUSTOMER_HIERARCHY){ productGroupService.setCustomerHierarchy(self.customerHierarchyInput); productGroupService.setCustomHierarchySearchText(self.customHierarchySearchText); } } $state.go(appConstants.CUSTOM_HIERARCHY_ADMIN,{customerHierarchyId:customerHierarchyId}); }; /** * Handle clear result button. */ self.clearResults = function(){ self.searchDescription = "<strong>Search</strong>"; self.resetTable(); self.isExistProduct = false; self.error = self.NO_PRODUCT_SELECTED; }; /** * Get class message to setting style for it. * @param message text of message. * @returns {*} class of html element. */ self.getClassOfMessage = function(message){ if (message.length > 30){ return "col-md-12 col-md-push-0"; } else{ return "col-md-4 col-md-push-4 alert alert-danger text-center myfade" } }; /** * Get style of clear button. * * @returns {*} CSS setting of button. */ self.getStyleOfClearBtn = function(){ if (self.totalRecord > self.PAGE_SIZE){ return "margin-top: -32px;margin-bottom: 10px;" } else { return "margin-bottom: 10px;" } } /** * Listener event change mode. */ $scope.$on(productGroupConstant.CHANGE_MODE_EVENT, function(event, mode) { self.mode = mode; if(productGroupService.isBrowserAll()){ self.productGroupIdInput = null; self.browserAll(); } }); /** * Listener event change mode. */ $scope.$on(productGroupConstant.CHANGE_MODE_EVENT_AFTER_DELETING, function(event, mode){ self.mode = mode; self.success = productGroupConstant.SUCCESSFULLY_UPDATED; if(!self.isBrowserAll ){ if( self.totalRecord-1 > 0){ self.resetTable(); self.buildResultDatatable(); }else{ self.clearResults(); } }else{ self.resetTable(); self.buildResultDatatable(); } }); /** * Select custom hierarchy method. * * @param customHierarchyLevel */ self.selectCustomHierarchyLevel = function (customHierarchyLevel) { self.customerHierarchyInput = angular.copy(customHierarchyLevel); customHierarchyLevel.isCollapsed = !customHierarchyLevel.isCollapsed; } /** * Helper method to determine if a level in the product hierarchy should be collapsed or not. * * @param relationship * @returns {boolean} */ self.isLowestBranchOrHasNoRelationships = function(relationship){ if(relationship.childRelationships === null || relationship.childRelationships.length === 0) { var param = []; param.lowestLevelId = relationship.key.childEntityId; self.isWaiting = true; productGroupApi.checkLowestLevel(param).$promise.then(function (response) { if (!response.isLowestLevel){ self.isWaiting = false; $('#hierarchyErrorPopup').modal({backdrop: 'static', keyboard: true}); $('.modal-backdrop').attr('style', ' z-index: 100000; '); } else { self.resetTable(); self.buildResultDatatable(); } }); } else { $('#hierarchyErrorPopup').modal({backdrop: 'static', keyboard: true}); $('.modal-backdrop').attr('style', ' z-index: 100000; '); } }; /** * Method to show hide detail hierarchy context. */ self.showHideDetailCustomerHierarchy = function () { self.isShowDetailCustomerHierarchy = !self.isShowDetailCustomerHierarchy; } /** * Go to create Product Group page. */ self.goToCreateProductGroupPage = function (){ productGroupService.setBrowserAll(false); productGroupService.setNavFromProdGrpTypePageFlag(false); productGroupService.setNavigateFromCustomerHierPage(false); self.dataSent = undefined; self.mode = productGroupConstant.DETAIL_MODE; } /** * Load Customer Hierarchy Context. This method is used to search on client side at product group module. */ self.loadCustomerHierarchyContext = function(){ self.isWaitingForLoadCustomerHierarchyResponse = true; customHierarchyApi.loadCustomerHierarchyContext({}, function(hierarchyContext){ if(hierarchyContext != null){ if(self.isSelectedCustomHierarchy && hierarchyContext.childRelationships.length> 0 ){ self.setSelectedCustomHierarchy(hierarchyContext.childRelationships); } self.customerHierarchyContext.push(angular.copy(hierarchyContext)); self.customerHierarchyContextRoot.push(angular.copy(hierarchyContext)); if(!self.isSelectedCustomHierarchy) { self.customerHierarchyContext.isCollapsed = true; angular.forEach(self.customerHierarchyContext, function (element) { element.isCollapsed = true; }) angular.forEach(self.customerHierarchyContextRoot, function (element) { element.isCollapsed = true; }) } self.isSelectedCustomHierarchy = false; if(self.customHierarchySearchText != null && self.customHierarchySearchText.trim().length> 0){ self.searchOnClient(); } } self.isWaitingForLoadCustomerHierarchyResponse = false; }, function(error){ fetchError(error); self.isWaitingForLoadCustomerHierarchyResponse = false; }); } /** * Search hierarchy Context by id and search text and show the results on the tree. This method is used to search on client side at product group module. */ self.searchOnClient = function(){ initializeCustomHierarchySearchValues(); var searchText = self.customHierarchySearchText.trim().toLowerCase(); var results = []; var currentHierarchyContext = null; var childRelationshipMatches = null; angular.forEach(self.customerHierarchyContextRoot, function (hierarchyContext) { // By hierarchyContextId childRelationshipMatches = self.findChildRelationshipMatches(searchText, hierarchyContext.childRelationships); currentHierarchyContext = angular.copy(hierarchyContext); currentHierarchyContext.childRelationships = childRelationshipMatches; results.push(currentHierarchyContext); }); loadCustomHierarchySearch(results); } /** * Find child relationship matches with search text. This method is used to search on client side at product group module. * * @param searchText the text to search for. * @param childRelationships the list of child relationships. * @returns {Array} the list of relationships matches with search text. */ self.findChildRelationshipMatches = function(searchText, childRelationships){ var results = []; var currentChildRelationship; angular.forEach(childRelationships, function(childRelationship) { var matchingChildRelationships = []; if(!childRelationship.childRelationshipOfProductEntityType) { matchingChildRelationships = self.findChildRelationshipMatches( searchText, childRelationship.childRelationships); } if (matchingChildRelationships.length > 0 || (childRelationship.childDescription !== null && childRelationship.childDescription.shortDescription.trim().toLowerCase().indexOf(searchText) !== -1)) { currentChildRelationship = angular.copy(childRelationship); currentChildRelationship.childRelationships = matchingChildRelationships; results.push(currentChildRelationship); } }); return results; } /** * This function initializes the custom hierarchy search values by setting the search text, and setting * searching for custom hierarchy to true. */ function initializeCustomHierarchySearchValues(){ self.searchingForCustomHierarchy = true; setCurrentCustomHierarchySearchText(); } /** * This function sets the current search text based on the text the user has searched for. */ function setCurrentCustomHierarchySearchText(){ self.searchingForCustomHierarchyText = self.searchingForCustomHierarchyTextTemplate .replace("$searchText", self.customHierarchySearchText); } /** * This is the callback function for getting the custom hierarchy based on a search string. */ function loadCustomHierarchySearch(results){ self.customerHierarchyContext = results; expandAllCustomHierarchyValues(); self.searchingForCustomHierarchy = false; self.searchingForCustomHierarchyText = ''; self.isShowDetailCustomerHierarchy = true; } /** * This function sets the collapsed variable to false for all current levels of the product hierarchy. */ function expandAllCustomHierarchyValues(){ angular.forEach(self.customerHierarchyContext, function (hierarchyContext) { hierarchyContext.isCollapsed = false; // for each sub department in department's subDepartmentList angular.forEach(hierarchyContext.childRelationships, function (firstRelationshipLevel) { firstRelationshipLevel.isCollapsed = false; // for each item class in sub department's itemClasses angular.forEach(firstRelationshipLevel.childRelationships, function (secondRelationshipLevel) { secondRelationshipLevel.isCollapsed = false; // for each commodity in item class's commodityList angular.forEach(secondRelationshipLevel.childRelationships, function (thirdRelationshipLevel) { thirdRelationshipLevel.isCollapsed = false; // for each commodity in item class's commodityList angular.forEach(thirdRelationshipLevel.childRelationships, function (fourthRelationshipLevel) { fourthRelationshipLevel.isCollapsed = false; }); }); }); }); }); }; /** * This function clears the custom hierarchy search on client. This method is used to search on client side at product group module. * */ self.clearCustomHierarchySearchOnClientSide = function () { self.customHierarchySearchText = null; self.isShowDetailCustomerHierarchy = false; self.searchingForCustomHierarchy = false; if (self.customerHierarchyContext.length > 0) { self.customerHierarchyContext = angular.copy(self.customerHierarchyContextRoot); self.customerHierarchyContext.isCollapsed = true; self.searchingForCustomHierarchy = false; self.searchingForCustomHierarchyText = ''; } }; /** * Helper method to determine if a level in the product hierarchy should be collapsed or not. * * @param hierarchyLevel * @returns {boolean} */ self.isHierarchyLevelCollapsed = function(hierarchyLevel){ if(typeof hierarchyLevel.isCollapsed === undefined){ return true; }else { return hierarchyLevel.isCollapsed; } }; /** * This method removes the previous selected highlighted hierarchy level(if there is one), and then sets the * current selected level in a custom hierarchy to be highlighted, and . This is done by using the string * representation of the id tag (i.e. '#firstLevel') and the index of the current level and all indices of * parent levels. * * @param firstIndex The index of the first level in the custom hierarchy. * @param secondIndex The index of the second level in the custom hierarchy. * @param thirdIndex The index of the third level in the custom hierarchy. * @param fourthIndex The index of the fourth level in the custom hierarchy. * @param fifthIndex The index of the fifth level in the custom hierarchy. */ self.highlightCurrentSelectedHierarchyLevel = function(firstIndex, secondIndex, thirdIndex, fourthIndex, fifthIndex, isPopUp) { // remove any html elements with 'add-click-background' $(ADD_CLICK_BACKGROUND_CLASS_REFERENCE).removeClass(ADD_CLICK_BACKGROUND_CLASS); // add a '#' tag reference to the unique element id var elementIdTag = STRING_TAG + self.getUniqueElementIdFromIndices( firstIndex, secondIndex, thirdIndex, fourthIndex, fifthIndex, isPopUp); // add 'add-click-background' class to current selected hierarchy level $(elementIdTag).addClass(ADD_CLICK_BACKGROUND_CLASS); }; /** * This function clears the custom hierarchy search, and either: * if user has selected a hierarchy level, resets the view of that hierarchy expanded down to the level that * was being previously viewed. * else resets the custom hierarchy to the default non-filtered search. * */ self.clearCustomHierarchySearch = function () { self.customHierarchySearchText = ''; self.customerHierarchyContext = angular.copy(self.customerHierarchyContextRoot); }; /** * This method returns the string index of a given hierarchy level, which includes the string representation * of the level (i.e. 'firstLevel') and the index of the current level and all indices of parent levels * separated by a hyphen. The parent level indices and hyphen are required to guarantee a unique id per visible * hierarchy level. * * @param firstIndex The index of the first level in the custom hierarchy. * @param secondIndex The index of the second level in the custom hierarchy. * @param thirdIndex The index of the third level in the custom hierarchy. * @param fourthIndex The index of the fourth level in the custom hierarchy. * @param fifthIndex The index of the fifth level in the custom hierarchy. * @returns {string} Unique index for a hierarchy level. */ self.getUniqueElementIdFromIndices = function(firstIndex, secondIndex, thirdIndex, fourthIndex, fifthIndex, isPopUp) { var uniqueId; // first level if(secondIndex === null){ uniqueId = FIRST_HIERARCHY_LEVEL_ELEMENT_ID_PREFIX + firstIndex; } // second level else if(thirdIndex === null){ uniqueId = SECOND_HIERARCHY_LEVEL_ELEMENT_ID_PREFIX + firstIndex + STRING_HYPHEN + secondIndex; } // third level else if(fourthIndex === null){ uniqueId = THIRD_HIERARCHY_LEVEL_ELEMENT_ID_PREFIX + firstIndex + STRING_HYPHEN + secondIndex + STRING_HYPHEN + thirdIndex; } // fourth level else if(fifthIndex === null){ uniqueId = FOURTH_HIERARCHY_LEVEL_ELEMENT_ID_PREFIX + firstIndex + STRING_HYPHEN + secondIndex + STRING_HYPHEN + thirdIndex + STRING_HYPHEN + fourthIndex; } // fifth level else { uniqueId = FIFTH_HIERARCHY_LEVEL_ELEMENT_ID_PREFIX + firstIndex + STRING_HYPHEN + secondIndex + STRING_HYPHEN + thirdIndex + STRING_HYPHEN + fourthIndex + STRING_HYPHEN + fifthIndex; } if(isPopUp) { uniqueId = uniqueId + "PopUp"; } return uniqueId; }; /** * Helper method to determine if a level in the product hierarchy should be collapsed or not. * * @param relationship * @returns {boolean} */ self.checkLowestBranchOrHasNoRelationships = function(relationship){ if(relationship.lowestBranch){ return true; }else if(relationship.childRelationships === null || relationship.childRelationships.length === 0) { return true; } return false; }; /** * Set selected custom hierarchy when return to list from custom hierarchy. * @param childRelationships * @return {*} */ self.setSelectedCustomHierarchy = function(childRelationships) { var result = false; if (childRelationships == null || childRelationships == undefined || childRelationships.length == 0 || self.customerHierarchyInput == null || self.customerHierarchyInput == undefined || self.customerHierarchyInput.key == undefined || self.customerHierarchyInput.key == null) { return result; } var child = null; for (var i = 0; i < childRelationships.length; i++) { child = childRelationships[i]; if (child.key.childEntityId == self.customerHierarchyInput.key.childEntityId) { child.isCollapsed = false; return true; } if (child.childRelationships !== null && child.childRelationships !== undefined && child.childRelationships.length > 0) { if (self.setSelectedCustomHierarchy(child.childRelationships)) { child.isCollapsed = false; return true; } } } return result; } /** * Return selected css for selected row on custom hierarchy. * @param level * @return {string} */ self.getSelectedCustomHierarchyCss = function(level){ if(self.customerHierarchyInput!= null && self.customerHierarchyInput != undefined && self.customerHierarchyInput.key != undefined && self.customerHierarchyInput.key != null && level.key.childEntityId == self.customerHierarchyInput.key.childEntityId) { return ADD_CLICK_BACKGROUND_CLASS; } return ''; } /** * Download current image. */ self.downloadImage = function () { if (self.imageBytes !== ' ') { downloadImageService.download(self.imageBytes, self.imageFormat==''?'png':self.imageFormat.trim()); } }; /** * Check enable searching */ self.checkEnableSearching = function () { if((self.productGroupIdInput !== null && self.productGroupIdInput !== undefined && self.productGroupIdInput !== "") || (self.productGroupNameInput !== null && self.productGroupNameInput !== undefined && self.productGroupNameInput !== "") ||(self.productGroupTypeInput !== null && self.productGroupTypeInput !== undefined && self.productGroupTypeInput !== "") ||(self.customerHierarchyInput !== null && self.customerHierarchyInput !== undefined && self.customerHierarchyInput !== "")){ self.search(); } }; } })();
const connection = require('../database/connection'); class Usuario{ login(info){ const sql = `SELECT id FROM usuario WHERE login="${info.login}" AND senha="${info.password}"`; return new Promise ((resolve, reject) => { connection.query(sql,null, (error, results) => { if(error){ reject(error); } else { if(results.length == 0) { resolve({message: 'usuario ou senha não existem', id: false}); } else { resolve({message: 'login feito com sucesso', id: results[0].id}); } } }); }) } singin(usuario){ return new Promise((resolve, reject) => { const sql = `INSERT INTO usuario SET ?`; connection.query(sql, usuario, (error, results) =>{ if(error){ reject(error); } else { resolve(results); } }); }); } } module.exports = new Usuario();
import './OneCity.css'; import axios from 'axios'; import React, {useEffect, useState} from 'react'; import runtimeEnv from '@mars/heroku-js-runtime-env'; function OneCity (props) { const env = runtimeEnv(); const APIKEY = env.REACT_APP_APIKEY; const APIURL = "https://cors-anywhere.herokuapp.com/openweathermap.org/data/2.5/weather"; // for local cors proxy: const APIURL = "http://localhost:8010/proxy/data/2.5/weather"; const cityName = props.data; const [weather, setWeather] = useState({ temp : "(скоро будет)", humidity : "(скоро будет)", }); useEffect ( function () { axios.get(APIURL, { params: { 'q' : cityName, 'appid' : APIKEY } }) .then((response) => { setWeather({ temp: response.data.main.temp, humidity: response.data.main.humidity }); }).catch((err) => { props.onNotFound(); props.onDelete(cityName); }) }, [cityName]); return (<div className="smallDiv"> <p>Город: {props.data}</p> <p>Температура: {weather.temp} C</p> <p>Влажность: {weather.humidity}</p> <span className="delSpan" onClick={() => props.onDelete(cityName)}>X</span> </div>); } export default OneCity;
import axios from 'axios'; import { createAction, createActions } from '../common'; import * as actionTypes from './actionTypes'; // createAction 会返回一个 FSA 规范的 action,该 action 会是一个对象,而不是一个 function const setNews = createAction(actionTypes.NEWS_LIST_GET) //same as const setNews = createAction(actionTypes.NEWS_LIST_GET data => data) /*export const getNewsList = (params) => (dispatch) => { axios.get(`https://www.reddit.com/r/reactjs.json`) .then(result => { dispatch( setNews(result.data)) }) .catch(error => { debugger; }) }*/ const actionCreator = createActions({ getNewsList : { url: 'https://www.reddit.com/r/reactjs.json', method: 'get', handleError: true, actionType: actionTypes.NEWS_LIST_GET }, setNews : createAction(actionTypes.NEWS_LIST_GET) }) export default actionCreator;
const browser = require('./browser') // const I = getActor(); class CodeceptMochawesomeLog{ getDate(){ const d = new Date(); const hh = d.getHours() < 10 ? `0${d.getHours()}` : d.getHours(); const mm = d.getMinutes() < 10 ? `0${d.getMinutes()}` : d.getMinutes(); const ss = d.getSeconds() < 10 ? `0${d.getSeconds()}` : d.getSeconds(); return `[${hh}:${mm }:${ss}]` } FormatPrintJson(jsonObj,basePad){ basePad = basePad ? basePad : 0; const keys = Object.keys(jsonObj); let maxSize = 0; for(let key of keys){ maxSize = key.length > maxSize ? key.length : maxSize; } let startPadding = basePad + maxSize + 1; for (let key of keys) { try { browser.get_I().addMochawesomeContext(`${key.padEnd(startPadding)} : ${jsonObj[key]}`); } catch (err) { console.log("Error occured adding message to report. " + err.stack); } console.log(`${key.padEnd(startPadding)} : ${jsonObj[key]}`) } } LogTestDataInput(message){ browser.get_I().addMochawesomeContext(`>>>>>>> [ Test data input ]: ${message}`); } AddMessage(message, logLevel){ // if (!this._isLevelEnabled(logLevel)) return; try{ browser.get_I().addMochawesomeContext(this.getDate() + message); // browser.get_I().say( message) } catch(err){ console.log("Error occured adding message to report. "+err.stack); } console.log( message) } AddMessageToReportOnly(message, logLevel) { // if (!this._isLevelEnabled(logLevel)) return; browser.get_I().addMochawesomeContext(this.getDate() + message); // browser.get_I().say(this.getDate() + message) } AddJson(json, logLevel){ // if (!this._isLevelEnabled(logLevel)) return; try { browser.get_I().addMochawesomeContext(JSON.stringify(json, null, 2)); // browser.get_I().say(JSON.stringify(json, null, 2)) } catch(err) { console.log("Error occured adding message to report. " + err.stack); } console.log(JSON.stringify(json, null, 2)); } AddJsonToReportOnly(json, logLevel) { // if (!this._isLevelEnabled(logLevel)) return; I.addMochawesomeContext(JSON.stringify(json, null, 2)); } async AddScreenshot(onbrowser, logLevel){ // if (!this._isLevelEnabled(logLevel)) return; // const decodedImage = await this.getScreenshot(onbrowser); // await browser.get_I().addMochawesomeContext(decodedImage, 'image/png'); this.AddMessage(`!!! Add screenshot not implemented !!!`) } async getScreenshot(onbrowser){ const scrrenshotBrowser = onbrowser ? onbrowser : browser; const stream = await scrrenshotBrowser.takeScreenshot(); const decodedImage = new Buffer(stream.replace(/^data:image\/(png|gif|jpeg);base64,/, ''), 'base64'); return decodedImage; } reportDatatable(datatable){ const rows = datatable.parse().raw(); const topRow = rows[0] const rowsCount = rows.length; const columnsCount = topRow.length; const columnSizes = []; for (let i = 0; i < columnsCount; i++){ const columnValues = rows.map(row => row[i]) let columnSize = columnValues.sort((a,b) => a.length < b.length ? 1:-1)[0].length columnSize = columnSize + 3; columnSizes[i] = columnSize; } let totalTableLength = 0; columnSizes.forEach(colLength => totalTableLength += colLength ) this.AddMessage('=== BDD) ' + ''.padEnd(totalTableLength+1,'-') ) for (let row = 0; row < rowsCount; row++){ let tableRow = "" for (let col = 0; col < columnsCount ; col++){ tableRow += rows[row][col].padEnd(columnSizes[col], ' ') } this.AddMessage('=== BDD) |'+tableRow+'|') } this.AddMessage('=== BDD) ' + ''.padEnd(totalTableLength+1, '-')) } // _isLevelEnabled(msgLoglevel)`=== BDD) // msgLoglevel = msgLoglevel !== undefined ? msgLoglevel : LOG_LEVELS.Info; // return msgLoglevel >= this.logLevel; // } } module.exports = new CodeceptMochawesomeLog();
'use strict'; function userController($scope, $http) { $scope.message = 'Hello'; $http.get("/api/things") .then( function(r) { $scope.message = r.data; }); console.log($http); } angular.module('myangularApp') .controller('UserController', userController) .config(function($routeProvider) { $routeProvider .when('/user', { template: '<h1>111{{message}}</h1>', controller: 'UserController' }); }); console.log("done")
(function() { 'use strict'; angular .module('newlotApp') .factory('PasswordResetFinish', PasswordResetFinish); PasswordResetFinish.$inject = ['$resource', 'SERVER_BACKEND']; function PasswordResetFinish($resource, SERVER_BACKEND) { var service = $resource(SERVER_BACKEND + 'api/reset/finish', {}, {}); return service; } })();
import React, { Component } from 'react'; import { string } from 'prop-types'; import io from 'socket.io-client'; import Display from './Display'; const socket = io(); const generateId = () => { let id = ''; for (let i = 0; i < 10; i++) { const randomNumber = Math.floor(Math.random()*10); id += randomNumber; } return id; } export default class SendMessage extends Component { static propTypes = { author: string.isRequired, }; state = { messageContent: '' }; editMessageContent = evt => this.setState({ messageContent: evt.target.value }); sendMessage = () => { const { messageContent } = this.state; if (messageContent) { const message = { id: generateId(), content: messageContent, author: this.props.author, } socket.emit('message', message); this.setState({ messageContent: '' }); } }; render() { return ( <Display onInputChange={this.editMessageContent} inputValue={this.state.messageContent} onButtonClick={this.sendMessage} /> ); } }
import React, { Component } from 'react'; import { ButtonToolbar, DropdownButton, ButtonGroup, Dropdown, Button, Col, Row, Form } from 'react-bootstrap'; import '../Editor.css' class Toolbar extends Component { constructor(props) { super(props); this.state = {documentName: ''}; this.documentNameInput = React.createRef(); this.defaultDocumentName = 'Untitled Document'; } componentDidMount() { if (localStorage.getItem("documentName") !== null) { this.setState({documentName: localStorage.getItem("documentName")}); return; } this.setState({documentName: this.defaultDocumentName}); localStorage.setItem('documentName', this.defaultDocumentName); } setDocumentName() { this.setState({documentName: this.documentNameInput.current.value}); localStorage.setItem('documentName', this.documentNameInput.current.value); } downloadAsHtml(styled = false) { const text = this.props.htmlValue; const filename = `${this.state.documentName}.html`; const htmlDocument = ` <html> <head> ${styled ? '<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/github-markdown-css/3.0.1/github-markdown.min.css">' : ''} <title>${filename}</title> </head> <body> ${styled ? '<div class="markdown-body">' : ''} ${text} ${styled ? '</div>' : ''} </body> </html>`; this.downloadFile(htmlDocument, filename); } downloadAsMarkdown() { this.downloadFile(this.props.markdownValue, `${this.state.documentName}.md`); } downloadFile(text, filename) { let element = document.createElement('a'); element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text)); element.setAttribute('download', filename); element.style.display = 'none'; document.body.appendChild(element); element.click(); document.body.removeChild(element); } resetEditor() { this.props.setEditorState('', ''); this.setState({documentName: 'Untitled Document'}); localStorage.removeItem('markdownValue'); localStorage.setItem('documentName', this.defaultDocumentName); this.props.store.characterCount = 0; this.props.store.wordsCount = 0; } render() { return ( <Row> <Col> <ButtonToolbar className={'button-toolbar'}> <DropdownButton size="sm" as={ButtonGroup} title="Download as…" id="bg-nested-dropdown" variant="dark"> <Dropdown.Item eventKey="1" onClick={() => this.downloadAsMarkdown()}>Markdown</Dropdown.Item> <Dropdown.Item eventKey="2" onClick={() => this.downloadAsHtml()}>Plain HTML</Dropdown.Item> <Dropdown.Item eventKey="3" onClick={() => this.downloadAsHtml(true)}>Styled HTML</Dropdown.Item> </DropdownButton> <Button variant="outline-dark" size="sm" onClick={() => { this.resetEditor() }}> Reset </Button> </ButtonToolbar> </Col> <Col> <Form.Control type="text" value={this.state.documentName} onChange={() => { this.setDocumentName() }} ref={this.documentNameInput} className={'document-name'} /> </Col> </Row> ); } } export default Toolbar;
/******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { eval("module.exports = __webpack_require__(1);\n\n\n/*****************\n ** WEBPACK FOOTER\n ** multi app\n ** module id = 0\n ** module chunks = 0\n **/\n//# sourceURL=webpack:///multi_app?"); /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { eval("'use strict';\n\nvar _example = __webpack_require__(2);\n\nvar _example2 = _interopRequireDefault(_example);\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n/* eslint no-console: 0 */\nconsole.log(_example2.default); /**\n * Setup webpack public path\n * to enable lazy-including of\n * js chunks\n *\n */\n\n// silly example:\n\n\nconsole.log(jQuery);\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/js/app.js\n ** module id = 1\n ** module chunks = 0\n **/\n//# sourceURL=webpack:///./src/js/app.js?"); /***/ }, /* 2 */ /***/ function(module, exports) { eval("'use strict';\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\n/**\n * Example.\n * Just delete this file :)\n *\n */\n\nvar obj = {\n foo: 'Hello',\n bar: 'Cruel',\n baz: 'World'\n};\n\nexports.default = obj;\n\n/*****************\n ** WEBPACK FOOTER\n ** ./src/js/scripts/example.js\n ** module id = 2\n ** module chunks = 0\n **/\n//# sourceURL=webpack:///./src/js/scripts/example.js?"); /***/ } /******/ ]);
import { Link, } from "react-router-dom"; function MenuPrincipal() { return ( <nav> <h1>BurgerQueen</h1> <ul> <li> <Link to = "/">Login</Link> </li> <li> <Link to = "/mesero">Mesero</Link> </li> <li> <Link to = "/cocinero">Cocinero</Link> </li> <li> <Link to = "/administrador">Administrador</Link> </li> </ul> </nav> ); } export default MenuPrincipal;
const express = require('express'); const app = express(); const async = require('async'); const con = require('./index').con; const { create } = require('express-handlebars'); // TODO: for instructor.js function getMyCurrentlyTaughtClasses(id, con) { // TODO: Akbar, you can move this /* Purpose: Retrieves an array of all classes an instructor is teaching for the current semester Input: id: id of instructor [int] con: connection to DB (result of createConnection() method) Output: [Promise] If an error occurs, returns an array with only one element of false (i.e. [false]) If the id does not match an instructor id, returns [false, 'No matching instructor id'] If current semester is not assigned yet in the DB, returns an empty array. If the instructor is not teaching any classes yet for the current semester, returns an empty array. Otherwise, returns an array of objects that contain the classes' information in each object. */ return new Promise((resolve, reject) => { async.waterfall([ function verifyInstructor(callback) { con.query('SELECT Id FROM Instructor WHERE Id = ?', id, (err, result) => { if (result.length === 0) { callback(null, false); return resolve([false, 'No matching instructor id']); } callback(null, true); }); }, function getCurrentSemester(verification, callback) { if (!verification) return; con.query('SELECT Name, Year FROM CurrentSemester ORDER BY DateAdded DESC LIMIT 1', (err, result) => { if (result.length === 0) { callback(null, false, '', ''); return resolve([]); } callback(null, true, result[0]['Year'], result[0]['Name']); }); }, function execute(verification, year, semester) { if (!verification) return; let sql = 'SELECT Class.Id AS ClassId, Class.CourseId, Course.Title, Class.Section, Class.Year, Class.Semester, Department.Name AS Department, Course.Credits, Course.Cost \ FROM Class \ JOIN Course ON Class.CourseId = Course.Id \ JOIN Department ON Course.Dept = Department.Id \ WHERE Class.Instructor = ? AND Class.Year = ? AND Class.Semester = ?'; con.query(sql, [id, year, semester], (err, result) => { return err ? resolve([false]) : resolve(result); }); } ]) }); } // TODO: for instructor.js function getMyTaughtClasses(id, con) { // TODO: Akbar, you can move this /* Purpose: Retrieves an array of all classes an instructor has taught, is currently teaching, or will teach Input: id: id of instructor [int] con: connection to DB (result of createConnection() method) Output: [Promise] If an error occurs, returns an array with only one element of false (i.e. [false]) If the id does not match an instructor id, returns [false, 'No matching instructor id'] If the instructor has not taught classes in the past, is not currently teaching, and not yet teaching any class in the future, returns an empty array. Otherwise, returns an array of objects that contain the classes' information in each object. */ return new Promise((resolve, reject) => { async.waterfall([ function verifyInstructor(callback) { con.query('SELECT Id FROM Instructor WHERE Id = ?', id, (err, result) => { if (result.length === 0) { callback(null, false); return resolve([false, 'No matching instructor id']); } callback(null, true); }); }, function execute(verification) { if (!verification) return; let sql = 'SELECT Class.Id AS ClassId, Class.CourseId, Course.Title, Class.Section, Class.Year, Class.Semester, Department.Name AS Department, Course.Credits, Course.Cost \ FROM Class \ JOIN Course ON Class.CourseId = Course.Id \ JOIN Department ON Course.Dept = Department.Id \ WHERE Class.Instructor = ?'; con.query(sql, id, (err, result) => { return err ? resolve([false]) : resolve(result); }); } ]) }); } // TODO: for instructor.js function assignGrade(instructorId, classId, studentId, grade, con) { // TODO: Akbar, you can move this /* Purpose: Instructor assigns student's final grade for a class that they teach and student is current enrolled in Warning: grade must already be in Grade table's Name column // TODO: add a check for this (not immediately necessary) There must be a current semester assigned in the DB. // TODO: change this (not immediately necessary) Input: instructorId: ID of the instructor [int] classId: class ID for the class the instructor teaches and student is enrolled in [int] studentId: ID of the student [int] grade: grade the instructor assigns to student [string] con: connection to DB (result of createConnection() method) Output: [Promise] If there is no matching classId with enrolled students, returns [false, 'No matching classId']. If there is no matching instructorId, returns [false, 'No matching instructorId for this class']. If the class is taught by another instructor, returns [false, 'Can only assign grades for classes that you teach']. If the class is not taking place during the current semester, returns [false, 'Can only assign grades for classes taking place during the current semester']. If there is no matching studentId, returns [false, 'No matching studentId for this class']. If grade is already assigned, returns [false, 'Grade already assigned for this student']. If there is no error, returns an array with only one element of true (i.e. [true]) If there is an error, returns false with the SQL message in an array (i.e. [false, "Data too long for column 'Name' at row 1"]). */ return new Promise((resolve, reject) => { async.waterfall([ function verifyClassId(callback) { con.query('SELECT ClassId FROM Enrollment WHERE ClassId = ?', classId, (err, result) => { if (err | result.length === 0) { callback(null, false); return resolve([false, 'No matching classId']); } callback(null, true); }); }, function verifyInstructorId(verification, callback) { if (!verification) return; let sql = 'SELECT Class.Instructor \ FROM Enrollment \ JOIN Class ON Enrollment.ClassId = Class.Id \ WHERE Enrollment.ClassId = ? AND Class.Instructor = ?' con.query(sql, [classId, instructorId], (err, result) => { if (err | result.length === 0) { callback(null, false); return resolve([false, 'No matching instructorId for the class']); } callback(null, true); }); }, function verifyInstructorTeachesClass(verification, callback) { if (!verification) return; con.query('SELECT Instructor, Year, Semester FROM Class WHERE Id = ? AND Instructor = ?', [classId, instructorId], (err, result) => { if (err | result.length === 0) { callback(null, false, '', ''); return resolve([false, 'Can only assign grades for classes that you teach']); } callback(null, true, result[0]['Year'], result[0]['Semester']); }); }, function verifySemester(verification, year, semester, callback) { if (!verification) return; con.query('SELECT Name, Year FROM CurrentSemester ORDER BY DateAdded DESC LIMIT 1', (err, result) => { let currSem = result[0]['Name']; let currYear = result[0]['Year']; if (currSem !== semester || currYear !== year) { callback(null, false); return resolve([false, 'Can only assign grades for classes taking place during the current semester']); } callback(null, true); }); }, function verifyStudentId(verification, callback) { if (!verification) return; con.query('SELECT StudentId FROM Enrollment WHERE StudentId = ? AND ClassId = ?', [studentId, classId], (err, result) => { if (err || result.length === 0) { callback(null, false); return resolve([false, 'No matching studentId for this class']); } callback(null, true); }); }, function verifyNoPrevGrade(verification, callback) { if (!verification) return; con.query('SELECT Grade FROM Enrollment WHERE ClassId = ? AND StudentId = ?', [classId, studentId], (err, result) => { if (result[0]['Grade'] !== null) { callback(null, false); return resolve([false, 'Grade already assigned for this student']); } callback(null, true); }); }, function execute(verification, args) { if (!verification) return; let sql = 'UPDATE Enrollment \ SET Grade = ? \ WHERE ClassId = ? AND StudentId = ?'; con.query(sql, [grade, classId, studentId], (err, result) => { return err ? resolve([false, err.sqlMessage]) : resolve([true]); }); } ]); }); } // TODO: for instructor.js function registerAsInstructor(id, name, email, password, con) { /* Purpose: Instructor creates an account by specifying id, name, and email for verification and updates Login table with the instructor's email and password Input: id: ID number of the instructor [int] name: full name of the instructor [string] email: email address of the instructor [string] password: instructor's password of choice [string] // TODO: would be good to check that password contains some content and not null (not immediately necessary) con: connection to DB (result of createConnection() method) Output: [Promise] If email is not a valid email, returns [false, 'Email not valid']. If email is already used by an instructor account, returns [false, 'Email address already used by an instructor account']. If id, name, or email is incorrect, or a collection of these is incorrect, returns [false, 'No matching instructor information with id, name, and email given']. If there is no error, returns an array with only one element of true (i.e. [true]) If there is an error, returns false with the SQL message in an array (i.e. [false, "Data too long for column 'Name' at row 1"]). */ let emailValidator = /(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/; // TODO: not necessary to use regex return new Promise((resolve, reject) => { if (!emailValidator.test(email)) return resolve([false, 'Email not valid']); // TODO: update here after changing regex async.waterfall([ function verifyUniqueEmail(callback) { con.query("SELECT Email FROM Login WHERE Email = ? AND AccountType = 'Instructor'", email, (err, result) => { if (result.length > 0) { callback(null, false); return resolve([false, 'Email address already used by an instructor account']); } callback(null, true); }); }, function verifyInstructor(verification, callback) { if (!verification) return; let sql = "SELECT Id, Name, Email FROM Instructor WHERE Id = ? AND Name = ? AND Email = ?"; con.query(sql, [id, name, email], (err, result) => { if (err) { callback(null, false); return resolve([false, err.sqlMessage]); } if (result.length === 0) { callback(null, false); return resolve([false, 'No matching instructor information with id, name, and email given']); } callback(null, true); }); }, function executeLogin(verification) { if (!verification) return; let sql = 'INSERT INTO Login VALUES (?)'; con.query(sql, [[email, password, 'Instructor']], (err, result) => { return err ? resolve([false, err.sqlMessage]) : resolve([true]); }); } ]); }); } // TODO: for instructor.js function verifyInstructorLogin(email, password, con) { // TODO: Akbar, you can move this /* Purpose: Verifies instructor login Input: email: email of instructor [string] password: password of instructor [string] con: connection to DB (result of createConnection() method) Output: [Promise] If an error occurs, returns an array with only one element of false (i.e. [false]) If there is no matching instructor account with the email and password, returns [false, 'No matching account']. If there is a matching instructor account with the email and password, returns [true]. */ return new Promise((resolve, reject) => { let sql = "SELECT Email, Password FROM Login WHERE Email = ? AND Password = ? AND AccountType = 'Instructor'"; con.query(sql, [email, password], (err, result) => { if (err) return resolve([false]); if (result.length > 0) return resolve([true]); // TODO: result.length > 0 preferred so check other functions (not immediately necessary) return resolve([false, 'No matching account']); }) }); } // TODO: for instructor.js function getInstructorIdFromEmail(email, con) { /* Purpose: Gets the corresponding instructor ID number of an email address Input: email: email of instructor [string] con: connection to DB (result of createConnection() method) Output: [Promise] If an error occurs, returns an array with only one element of false (i.e. [false]) If no instructor is matched with the email address, returns [false, 'No matching instructor']. If an instructor is matched with the email address, returns an array where the second element contains the id of the instructor (i.e. [true, 123]). */ return new Promise((resolve, reject) => { con.query('SELECT Id FROM Instructor WHERE Email = ?', email, (err, result) => { // TODO: don't declare let sql where there are short queries if (err) return resolve([false]); if (result.length === 0) return resolve([false, 'No matching instructor']); return resolve([true, result[0]['Id']]); }); }); } module.exports = { getMyCurrentlyTaughtClasses, getMyTaughtClasses, verifyInstructorLogin, // added by Saiful getInstructorIdFromEmail, // added by Saiful registerAsInstructor, // added by Saiful assignGrade // added by Saiful };
// 1. Center Point // function coordinate(x1, y1, x2, y2) { // var diog1 = Math.sqrt(x1 * x1 + y1 * y1); // var diog2 = Math.sqrt(x2 * x2 + y2 * y2); // if (diog1 <= diog2) { // console.log("(" + x1 + " , " + y1 + ")"); // } // else { // console.log("(" + x2 + " , " + y2 + ")"); // } // } // coordinate(2, 4, -1, 2); // 2. Longer Line // function lines(x1, y1, x2, y2, x3, y3, x4, y4) { // var line1 = Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)); // var line2 = Math.sqrt((x4 - x3) * (x4 - x3) + (y4 - y3) * (y4 - y3)); // if (line1 >= line2) { // console.log("(" + x1 + " , " + y1 + " , " + x2 + " , " + y2 + ")"); // } // else { // console.log("(" + x3+ " ," + y3 +" , " + x4 + " , " + y4 +")"); // } // } // lines(2,4,-1,2,-5,-5,4,-3); // 3. Cube Properties // function cube(s, type) { // if (type == "face") { // var face = Math.sqrt(2 * (s * s)) // console.log(s, face); // } else if (type == "space") { // var space = Math.sqrt(3 * (s * s * s)) // console.log(s, space); // } else if (type == "volume") { // var volume = s * s * s // console.log(s, volume); // } else if (type == "area") { // var area = 6 * (s * s) // console.log(s, area); // }else{ // console.log("type is not correct"); // } // } // cube(5, "face"); function Geometry(figure, x, y) { if (figure == "triangle") { var triangle = x + y; console.log(triangle); } else if (figure == "squere") { var squere = x*x; console.log(squere); } else if (figure == "rectangle") { var rectangle = x * y; console.log(rectangle); } else if (figure == "circle") { var circle = x * 3.14; console.log(circle); } } Geometry("squere", 3, 6)
angular.module('PatientApp.init').controller('setupCtr', [ '$scope', 'App', 'Storage', '$ionicLoading', 'AuthAPI', 'CToast', 'CSpinner', 'LoadingPopup', function($scope, App, Storage, $ionicLoading, AuthAPI, CToast, CSpinner, LoadingPopup) { return $scope.view = { refcode: '', emptyfield: '', deviceOS: '', deviceUUID: '', verifyRefCode: function() { if (this.refcode === '' || _.isUndefined(this.refcode)) { return this.emptyfield = "Please Enter Valid Reference Code"; } else { this.deviceUUID = App.deviceUUID(); if (App.isAndroid()) { this.deviceOS = "Android"; } if (App.isIOS()) { this.deviceOS = "IOS"; } CSpinner.show('', 'Please wait...'); return AuthAPI.validateRefCode(this.refcode, this.deviceUUID, this.deviceOS).then((function(_this) { return function(data) { _this.data = data; return Storage.setData('hospital_details', 'set', _this.data.hospitalData); }; })(this)).then((function(_this) { return function() { return Storage.setData('refcode', 'set', _this.refcode); }; })(this)).then((function(_this) { return function() { if (_this.data.code === 'do_login') { return App.navigate("main_login"); } else if (_this.data.code === 'set_password') { return App.navigate("setup_password"); } else if (_this.data.code === 'limit_exceeded') { return _this.emptyfield = 'Cannot do setup more then 5 times'; } else { return _this.emptyfield = 'Please check reference code'; } }; })(this), (function(_this) { return function(error) { return _this.emptyfield = 'Please try again'; }; })(this))["finally"](function() { return CSpinner.hide(); }); } }, tologin: function() { Storage.setData('refcode', 'remove'); return App.navigate("main_login"); }, forgetRefcode: function() { return $ionicLoading.show({ scope: $scope, templateUrl: 'views/error-view/Error-Screen-2.html', hideOnStateChange: true }); }, HelpRefcode: function() { return $ionicLoading.show({ scope: $scope, templateUrl: 'views/error-view/RefCode-help-1.html', hideOnStateChange: true }); }, hide: function() { return $ionicLoading.hide(); }, clear: function() { return this.emptyfield = ""; } }; } ]);
// SCROLL DOWN FOR DIRECTIONS var user; document.addEventListener('DOMContentLoaded', function() { var loggedInUser = localStorage.getItem('username'); if (loggedInUser != null ){ document.getElementById('hello').innerText = `Hi, ${loggedInUser}!`; document.getElementById('hello').style.display = 'block'; user = loggedInUser; } else{ user = 'Anonymous'; } }, false); var nav = new Vue({ el: '#fake-nav', methods: { open: function(which, e) { e.preventDefault(); modal.active = which; console.log(modal.active); }, } }); var modal_submit_login = 'Login'; // var user = 'Anonymous'; var modal = new Vue({ el: '#login-modal', data: { active: null, submitted: null, loginSubmit: modal_submit_login, loginUser: '', }, methods: { close: function(e) { e.preventDefault(); if (e.target === this.$el) { this.active = null; } }, submit: function(which, e) { user = document.getElementById('username').value; localStorage.setItem('username', user); document.getElementById('hello').innerText = `Hi, ${user}!`; document.getElementById('hello').style.display = "block"; modal.active = null; } } }); // ADD CODE HERE TO CREATE A VUE INSTANCE
// MODULES is a mapping from strings to module records. // This map will be mutated by the compilation process. var MODULES = {};
export const RECEIVE_NODE = "RECEIVE_NODE"; export const RECEIVE_TRANSACTION = "RECEIVE_TRANSACTION"; export const RECEIVE_USER_NODE = "RECEIVE_USER_NODE"; export const RECEIVE_INITIAL = "RECEIVE_INITIAL"; export const receiveNode = (node) => ({ type: RECEIVE_NODE, node }); export const receiveTransaction = (txn) => ({ type: RECEIVE_TRANSACTION, txn }); export const receiveUserNode = (node) => ({ type: RECEIVE_USER_NODE, node }); export const receiveInitial = () => ({ type: RECEIVE_INITIAL, });
/****************** ROUTER *******************/ APP.router = (function () { function init() { routie({ 'home': function () { APP.render.home(); }, 'pullrefresh': function () { APP.render.pullrefresh(); }, 'books': function () { APP.render.books(); }, 'books/:id': function (id) { APP.render.books(id); }, 'search': function () { APP.render.search(); }, 'search/:query': function (query) { APP.render.search(query); }, '': function () { APP.render.home(); }, '*': function () { alert("404 page not found."); } }); // Add active class to #home at first visit if (!window.location.hash) { document.querySelector('#home').classList.add('active'); } else { toggleMenu(); } // If hash changes toggleMenu window.addEventListener("hashchange", toggleMenu, false); }; function toggleMenu() { // Get all menu items var links = Array.prototype.slice.call(document.querySelectorAll('nav li')), hash = window.location.hash.split('/'), link = document.querySelector(hash[0]), main = document.querySelector('main'); // Remove active class links.forEach(function (item) { item.classList.remove("active"); }); // Add active class to new hash link.classList.add('active'); // Main animation main.classList.add('grow'); }; return { init: init, toggleMenu: toggleMenu }; })();
(function () { appModule.controller('common.views.navigations.index', [ '$scope', '$modal', '$templateCache', 'abp.services.app.navigation', 'uiGridConstants', function ($scope, $modal, $templateCache, navService, uiGridConstants) { var vm = this; $scope.$on('$viewContentLoaded', function () { App.initAjax(); }); vm.loading = false; vm.permissions = { create: abp.auth.hasPermission('Pages.Setting.UI.Nav.Create'), edit: abp.auth.hasPermission('Pages.Setting.UI.Nav.Edit'), 'delete': abp.auth.hasPermission('Pages.Setting.UI.Nav.Delete') }; vm.navGridOptions = { enableHorizontalScrollbar: uiGridConstants.scrollbars.WHEN_NEEDED, enableVerticalScrollbar: uiGridConstants.scrollbars.WHEN_NEEDED, appScopeProvider: vm, columnDefs: [ { name: app.localize('Actions'), enableSorting: false, width: 120, cellTemplate: '<div class=\"ui-grid-cell-contents\">' + ' <div class="btn-group dropdown" dropdown="">' + ' <button class="btn btn-xs btn-primary blue" dropdown-toggle="" aria-haspopup="true" aria-expanded="false"><i class="fa fa-cog"></i> ' + app.localize('Actions') + ' <span class="caret"></span></button>' + ' <ul class="dropdown-menu">' + ' <li><a ng-if="grid.appScope.permissions.edit" ng-click="grid.appScope.editNav(row.entity)">' + app.localize('Edit') + '</a></li>' + ' <li><a ng-if="!row.entity.isStatic && grid.appScope.permissions.delete" ng-click="grid.appScope.deleteNav(row.entity)">' + app.localize('Delete') + '</a></li>' + ' </ul>' + ' </div>' + '</div>' }, { name: '菜单名称', field: 'localizableString', cellFilter: 'localizableStringFilter' }, { name: '状态url', field: 'stateUrl' }, { name: '菜单类型', field: 'navigationType', cellFilter: 'navTypeFilter' }, { name: app.localize('CreationTime'), field: 'creationTime', cellFilter: 'momentFormat:\'L\'' } ], data: [] }; if (!vm.permissions.edit && !vm.permissions.delete) { vm.navGridOptions.columnDefs.shift(); } vm.getNavs = function () { vm.loading = true; navService.getList({}).success(function (data) { vm.navGridOptions.data = data.navigations; }).finally(function () { vm.loading = false; }); }; vm.deleteNav = function (nav) { abp.message.confirm( app.localize('NavDeleteWarningMessage', nav.displayName), function (isConfirmed) { if (isConfirmed) { navService.delete({ id: nav.id }).success(function () { vm.getNavs(); abp.notify.success(app.localize('SuccessfullyDeleted')); }); } } ); }; vm.getNavs(); } ]); })();
export const PUSH_DATA_CARDS = 'cards/pushData'; export const ADD_TO_COMPARE_CARDS = 'cards/addToCompare'; export const FLIP_CARD = 'cards/flipCard';
const context = document.querySelector("canvas").getContext("2d"); context.canvas.height = 400; context.canvas.width = 1220; var character = new character(); const square = { height: 32, jumping: true, width: 32, x: 0, xVelocity: 0, y: 0, yVelocity: 0 };
import moment from 'moment'; import forge from 'node-forge'; import Global from '@/global'; import Encrypt from '@/modules/native/encrypt'; import Log from '@/modules/common/logger'; import FileManager from '@/modules/common/fileManager'; import _Request from '@/modules/common/request'; /** * 请求 * * @export * @class Request */ export default class Request { /** * 应用帐号 * * @static * @memberof Request */ static appId = '100002'; /** * SM2公钥 * * @static * @memberof Request */ static sm2Key = '045AA578FB91F19D8D79912C2C801200A00024C6F7AA105AA2BF2F9DACECE6E03E2D75AF650A960BD82811D46E8B2DF20B4A3D73958D2B5098A523A35DC528D392'; /** * SM2私钥 * * @static * @memberof Request */ static sm2PrivateKey = 'ECA07B47379833A5CEE7D3171EB3E715C558B626FD202D55D5DE77E94BE6261E'; /** * 构造函数 */ constructor() { this.request = new _Request(); } /** * 登录 * * @param {*} username 用户名 * @param {*} password 密码 * @returns 登录结果 * @memberof Request */ async login(username, password) { Global.setUserInfo({}); const protocol = { SERVICETYPE: 'confirmUserLogin', USER_ID: username, USER_PWD: forge.md.md5.create().update(password).digest().toHex().toUpperCase(), IMEI: '00000000-282b-7c98-0000-0000637546ee', MECHINE_COD: '0539', }; const response = await this._request(protocol); if (response.code !== 0) { return { code: response.code, message: response.message, }; } // 检查返回值 const data = response.data; if (typeof data.USER_ID === 'undefined' || typeof data.TOKEN === 'undefined' || typeof data.FTP_SERVICE_IP === 'undefined' || typeof data.FTP_SERVICE_USERNAME === 'undefined' || typeof data.FTP_SERVICE_USERPWD === 'undefined') { return { code: -1, message: '登录失败,请重试', }; } // 设置用户信息 await Global.setUserInfo({ userId: data.USER_ID, password: password, lastModifiedTime: new Date().getTime(), token: data.TOKEN, username: data.USER_NAME, departId: data.DEPT_ID, departName: data.DEPT_NAME, ftpServiceIP: data.FTP_SERVICE_IP, ftpServicePort: await Encrypt.ftpDecrypt(data.FTP_SERVICE_POST), ftpServiceUsername: await Encrypt.ftpDecrypt(data.FTP_SERVICE_USERNAME), ftpServiceUserPassword: await Encrypt.ftpDecrypt(data.FTP_SERVICE_USERPWD), sdnFtpServiceIp: data.SDN_FTP_SERVICE_IP, sdnFtpServicePort: await Encrypt.ftpDecrypt(data.SDN_FTP_SERVICE_POST), sdnFtpServiceUsername: await Encrypt.ftpDecrypt(data.SDN_FTP_SERVICE_USERNAME), sdnFtpServiceUserPassword: await Encrypt.ftpDecrypt(data.SDN_FTP_SERVICE_USERPWD), officeId: data.OFFICE_ID, officeName: data.OFFICE_NAME, }); return { code: 0, message: '登录成功', }; } /** * 更新令牌 * * @memberof Request */ async updateToken() { const { userId, password } = Global.getUserInfo(); const protocol = { SERVICETYPE: 'getTokenInfo', USER_ID: userId, USER_PWD: forge.md.md5.create().update(password).digest().toHex().toUpperCase(), }; const response = await this._request(protocol); if (response.code !== 0) { return; } // 检查返回值 const data = response.data; if (typeof data.TOKEN === 'undefined') { return; } // 更新令牌 await Global.updateToken(response.data.TOKEN); } /** * 获取任务列表 * * @param {*} parameters 查询条件 * @return {*} 结果 * @memberof Request */ async getTaskList(parameters) { const { userId } = Global.getUserInfo(); const { sortField, sortOrder, TOTAL_NUM, TASK_NUM_TO, TASK_NUM_FROM } = parameters || {}; const protocol = { SERVICETYPE: 'getIspTaskList', ifLegar: '1', isPdf: '2', TASK_DATABASE: '1', OPE_USER_ID: userId, ...parameters, sortField: sortField || '', sortOrder: sortOrder || '', TOTAL_NUM: TOTAL_NUM || '', TASK_NUM_TO: TASK_NUM_TO || '', TASK_NUM_FROM: TASK_NUM_FROM || '', }; const response = await this._request(protocol); if (response.code !== 0) { return { code: response.code, message: response.message, }; } return response; } /** * 获取任务当前状态 * * @param {*} ispId 检验ID * @return {*} 结果 * @memberof Request */ async getlogStatus(ispId) { const protocol = { SERVICETYPE: 'getlogStatus', ISP_ID: ispId, }; const response = await this._request(protocol); if (response.code !== 0) { return { code: response.code, message: response.message, }; } return response; } /** * 上传下载任务 TODO * * @param {*} ispId 检验ID * @return {*} 结果 * @memberof Request */ async getTestlog(ispId) { const protocol = { SERVICETYPE: 'getTestlog', ISP_ID: ispId, OPE_USER_ID: Global.getUserInfo().userId, IF_SUB_DOWN: '0', SUB_ISPID: '', IF_OCX: '', }; const response = await this._request(protocol); if (response.code !== 0) { return { code: response.code, message: response.message, }; } return response; } /** * 下载测试 * * @param {*} taskInfo 任务信息 * @return {*} 结果 * @memberof Request */ async downloadTasks(taskInfo) { if (!taskInfo) { return { code: -1, message: '任务不可为空', }; } const taskState = await this.getlogStatus(taskInfo[0].ID); const stateData = JSON.parse(taskState.data.BUSIDATA); if (stateData[0].CURR_NODE === '101') { const result = await this.getTestlog(taskInfo[0].ID); let descriptors = JSON.parse(result.data.D_RETURN_MSG); let descriptor = descriptors[0]; let loadData = JSON.parse(descriptor.ErrorDescriptor); if (typeof loadData.LOG_MODULE_CODS !== 'undefined' && loadData.LOG_MODULE_CODS !== '') { let downloadTaskInfo = taskInfo[0]; downloadTaskInfo.REPORT_COD = loadData.REPORT_COD; downloadTaskInfo.MAIN_FLAGS = loadData.MAIN_FLAGS; downloadTaskInfo.SUB_ISPIDS = loadData.SUB_ISPIDS; const tasks = [downloadTaskInfo]; let taskGroups = await FileManager.getFtpDownloadTemplateGroups('27.151.117.67', '10089', '11', '$350100$', tasks); // ip, port, username, password, tasks let backMessage = await FileManager.ftpDownloadGroups(taskGroups); let result = await FileManager.getDownloadTasks(); } } else { return { code: -1, message: '当前任务不可下载与上传', }; } } /** * 获取字典数据 * * @return {*} * @memberof Request */ async getDictData() { const protocol = { SERVICETYPE: 'getDictData', }; const response = await this._request(protocol); if (response.code !== 0) { return { code: response.code, message: response.message, }; } // 更新令牌 await Global.setDictArea(response.data.D_DICTAREA); await Global.setOpeType(response.data.D_OPETYPE); await Global.setEqpType(response.data.D_EQPTYPE); await Global.setInvcType(response.data.D_INVC_TYPE); } /** * 获取回退明细(回退原因) * * @return {*} * @memberof Request */ async getBackDictQuery(eqpType) { const protocol = { SERVICETYPE: 'getBackDictQuery', EQP_TYPE: eqpType, }; const response = await this._request(protocol); if (response.code !== 0) { return { code: response.code, message: response.message, }; } return response; } /** * 获取流转节点信息 * * @param {*} params 参数 * @return {*} * @memberof Request */ async getFlowNode(params) { const { DEPT_ID, EQP_TYPE, REP_TYPE, ISP_ID, SUB_ISPID, OPE_TYPE, CURR_NODE, ISP_TYPE, MAIN_FLAG, ISP_CONCLU, IFCAN_REISP } = params; const protocol = { SERVICETYPE: 'getFlowNode', DEPT_ID: DEPT_ID, EQP_TYPE: EQP_TYPE, REP_TYPE: REP_TYPE, ISP_ID: ISP_ID, SUB_ISPID: SUB_ISPID, OPE_TYPE: OPE_TYPE, CURR_NODE: CURR_NODE, ISP_TYPE: ISP_TYPE, MAIN_FLAG: MAIN_FLAG, ISP_CONCLU: ISP_CONCLU, IFCAN_REISP: IFCAN_REISP, }; const response = await this._request(protocol); if (response.code !== 0) { return { code: response.code, message: response.message, }; } return response; } /** * 获取回退人员默认值(回退时调用)TODO * * @param {*} currentNodeId * @param {*} ispId * @return {*} * @memberof Request */ async getBackDefMen(currentNodeId, ispId) { const protocol = { SERVICETYPE: 'getBackDefMen', CURR_NODEID: currentNodeId, ISP_ID: ispId, }; const response = await this._request(protocol); if (response.code !== 0) { return { code: response.code, message: response.message, }; } return response; } /** * TODO * * @param {*} params * @return {*} * @memberof Request */ async setIspFlow(params) { const { MAIN_FLAG, CURR_NODE, NEXT_NODE, IF_BACK, ISP_ID, EQP_COD, OPE_TYPE, NEXT_USER_ID, OPE_MEMO, NOTELIGIBLE_REASON, IMPORTCASE_TYPE, IMPORTCASE_ID, BACK_POINT_LIST } = params; const protocol = { SERVICETYPE: 'setIspFlow', MAIN_FLAG: MAIN_FLAG || '1', CURR_NODE: CURR_NODE, NEXT_NODE: NEXT_NODE, IF_BACK: IF_BACK, ISP_ID: ISP_ID, EQP_COD: EQP_COD, OPE_TYPE: OPE_TYPE, OPE_USER_ID: Global.getUserInfo().userId, OPE_DEPT_NAME: Global.getUserInfo().departName, OPE_USER_NAME: Global.getUserInfo().username, NEXT_USER_ID: NEXT_USER_ID, OPE_MEMO: OPE_MEMO, NOTELIGIBLE_REASON: NOTELIGIBLE_REASON, IMPORTCASE_TYPE: IMPORTCASE_TYPE || '', IMPORTCASE_ID: IMPORTCASE_ID || '', BACK_POINT_LIST: BACK_POINT_LIST || '', }; const response = await this._request(protocol); if (response.code !== 0) { return { code: response.code, message: response.message, }; } return response; } /** * 获取电子资料列表 * * @param {*} params 参数 * @return {*} * @memberof Request */ async getSdnList(params) { const { OPE_TYPE, EQP_COD, TASK_DATE } = params; const protocol = { SERVICETYPE: 'getSdnList', OPE_TYPE: OPE_TYPE, STATUS: '1,2', EQP_COD: EQP_COD, TASK_DATE: TASK_DATE, }; const response = await this._request(protocol); if (response.code !== 0) { return { code: response.code, message: response.message, }; } return response; } /** * 电子资料操作 * * @param {*} params 参数 * @return {*} * @memberof Request */ async opeSdnList(params) { const protocol = { SERVICETYPE: 'OpeSdnList', ...params, }; const response = await this._request(protocol); if (response.code !== 0) { return { code: response.code, message: response.message, }; } return response; } /** * 上传文件 * * @param {*} uploadGroups 上传文件组 * @return {*} * @memberof Request */ async uploadFile(uploadGroups) { //const userinfo = Global.getUserInfo(); // todo 通过 用户数据获取上传服务地址 const uploadList = await FileManager.getFtpUploadTasks('27.151.117.67', 10089, '11', '$350100$', uploadGroups); return await FileManager.ftpUpload(uploadList); } /** * 获取上传任务信息 * * @return {*} * @memberof Request */ async getUploadTasks(){ return await FileManager.getUploadTasks(); } /** * 获取上传结果 TODO * * @param {*} ispId 任务ID集合 * @return {*} * @memberof Request */ async putTestlog(ispId){ const user = Global.getUserInfo(); const protocol = { SERVICETYPE: 'putTestlog', ISP_ID:ispId, SUB_ISPID:'', OPE_USER_ID:user.userId, OPE_USER_NAME:user.username }; const response = await this._request(protocol); if (response.code !== 0) { return { code: response.code, message: response.message, }; } return response; } /** * 票款管理接口 * * @param {*} parameters * @return {*} * @memberof Request */ async getIspFee(parameters) { const protocol = { SERVICETYPE: 'getIspFee', ISP_IDS: parameters, }; const response = await this._request(protocol); if (response.code !== 0) { return { code: response.code, message: response.message, }; } return response; } /** * 获取电子票二维码 * * @param {*} parameters 查询条件 * @return {*} 结果 * @memberof Request */ async getBillQr(parameters) { const { TASK_ID } = parameters || {}; const protocol = { SERVICETYPE: 'getBillQr', TASK_ID: TASK_ID, }; const response = await this._request(protocol); if (response.code !== 0) { return { code: response.code, message: response.message, }; } return response; } /** * 设备历史数据 * * @param {*} eqpCod 设备号 * @returns * @memberof Request */ async getEqpHisIspDetail(eqpCod){ const protocol = { SERVICETYPE: 'getEqpHisIspDetail', EQP_COD: eqpCod }; const response = await this._request(protocol); if (response.code !== 0) { return { code: response.code, message: response.message, }; } return response; } /** * 请求 * * @param {*} data 参数 * @memberof Request */ async _request(data) { try { const businessData = JSON.stringify(data); const sm4Key = await Encrypt.generateSm4Key(); const date = moment(new Date()).format('YYYYMMDDHHmmss'); let sign = `${businessData}&${Request.appId}&${date}`; if (typeof Global.userInfo !== 'undefined' && typeof Global.userInfo.token !== 'undefined' && Global.userInfo.token !== '') { sign += `&${Global.userInfo.token}&${Global.userInfo.userId}`; } const protocol = { APPID: Request.appId, BUSIDATA: businessData, SIGN: await Encrypt.sm4Encrypt(sm4Key, sign), SM4KEY: await Encrypt.sm2Encrypt(Request.sm2Key, sm4Key), TIMESTAMP: date, USERID: Global.userInfo.userId, TOKEN: Global.userInfo.token, }; Log.debug(`[business request]: ${JSON.stringify(protocol)}`); const response = await this.request.post('', protocol); const decrypted = await this._decrypt(response); if (decrypted.code !== 0) { return decrypted; } else { const result = typeof decrypted.data.OPE_MSG === 'undefined' ? decrypted.data : JSON.parse(decrypted.data.OPE_MSG); return { code: parseInt(result.ErrorCode), message: result.ErrorDescriptor, data: decrypted.data }; } } catch (e) { return { code: -1, message: `请求出错: ${JSON.stringify(e)}`, }; } } /** * 数据解密并校验 * * @param {*} response 接收到的返回数据 * @memberof result 解密后的结果 */ async _decrypt(response) { const { APPID, BUSIDATA, SIGN, SM4KEY, TIMESTAMP, USERID, TOKEN } = response; const decryptSm4Key = await Encrypt.sm2Decrypt(Request.sm2PrivateKey, SM4KEY); const decryptSign = await Encrypt.sm4Decrypt(decryptSm4Key, SIGN); const data = JSON.parse(BUSIDATA); if (decryptSign === `${BUSIDATA}&${APPID}&${TIMESTAMP}` || decryptSign === `${BUSIDATA}&${APPID}&${TIMESTAMP}&${TOKEN}&${USERID}`) { return { code: 0, data: data }; } else { return { code: -1, message: '数据校验失败', data: data }; } } }
var maxNumberUtente; var numUtente; // BONUS var level= prompt("Scegli la difficoltà: 1,2 o 3"); switch(level){ case "3": maxNumberUtente= 50; break; case "2": maxNumberUtente = 80; break; default: maxNumberUtente =100; } listaNumUtente = maxNumberUtente - 16; // Il computer deve generare 16 numeri casuali tra 1 e 100. // I numeri non possono essere duplicati. var numCasualiPc= []; while (numCasualiPc.length < 16) { var numeroCasuale = Casuale(1,maxNumberUtente); var trovaNumero = in_array(numCasualiPc, numeroCasuale); if (trovaNumero == false) { numCasualiPc.push(numeroCasuale); } } console.log(numCasualiPc); var listaNumUtente = []; var numPresente = false; var punti = 0; // chiedere all’utente (100 - 16) volte di inserire un numero alla volta, // Se il numero è presente nella lista dei numeri generati, la partita termina, altrimenti si continua chiedendo all’utente un altro numero. while (listaNumUtente.length < maxNumberUtente && numPresente == false) { numUtente = parseInt(prompt("inserisci un numero da 1 a"+ " "+ maxNumberUtente)); NumRange(); // L’utente non può inserire più volte lo stesso numero. if (in_array(listaNumUtente, numUtente) == false) { listaNumUtente.push(numUtente); console.log(listaNumUtente); // La partita termina quando il giocatore inserisce un numero “vietato” if (in_array(numCasualiPc, numUtente) == true) { numPresente = true; console.log("Hai preso una mina!"); document.write("GAME OVER"+"<br>"+"Hai preso una mina!"+ "<br>"); // Al termine della partita il software deve comunicare il punteggio, cioè il numero di volte che l’utente ha inserito un numero consentito. } else { punti++; } } } console.log(punti + " "+"punti"); document.write("Punteggio:" + " "+ punti+"<br>" ); // La partita termina quando il giocatore raggiunge il numero massimo possibile di numeri consentiti. if (listaNumUtente.length == maxNumberUtente) { document.write("Congratulazioni, hai raggiunto il punteggio massimo!"); } // FUNZIONI: // funzione che genera i numeri casuali del pc function Casuale(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } // funzione che trova il duplicato nell'array function in_array (array,numero) { for(i = 0; i< array.length; i++) { if (array[i] == numero) { return true; } } return false; } // Controllo range numero utente function NumRange() { if (numUtente >= 1 && numUtente <= maxNumberUtente) { numUtente; } else{ alert("il numero inserito non è valido, riprova!") } }
define([ 'jquery', 'underscore', 'backbone', 'text!templates/alert.html', 'bootstrapAlert', ], function($, _, Backbone, alertTemplate) { var AlertView = Backbone.View.extend({ className: "row", alertTemplate: _.template(alertTemplate), events: { "click .close" : "close", }, initialize: function(options) { _.bindAll(this, 'render'); this.msg = options.msg; this.type = options.type; this.$el.alert(); }, render: function() { this.$el.html(this.alertTemplate({msg: this.msg, type: this.type})); return this; }, close: function() { this.remove(); this.undelegateEvents(); }, }); return AlertView; });
import { useState, useContext, useEffect } from "react"; import ConnectionContext from "../ConnectionContext"; import PublicGameItem from "./PublicGameItem"; import { FaUsers } from "react-icons/fa"; import "./PublicGames.scss"; function PublicGames({ setGameId, closeModal }) { const [publicGames, setPublicGames] = useState([]); const connection = useContext(ConnectionContext); useEffect(() => { connection.current.emit("get_public_games"); connection.current.on("public_games", (data) => { const { publicGames } = data; setPublicGames(publicGames); }); const oldConnection = connection.current; return () => { oldConnection.removeAllListeners("public_games"); }; }, [connection]); const output = publicGames.map((publicGame) => { return ( <PublicGameItem {...publicGame} setGameId={setGameId} closeModal={closeModal} /> ); }); return ( <div className="publicGame__box"> <h2 className="heading__primary"> <FaUsers className="user-icon" /> Public Games </h2> <h3 className="heading__seconday">Click to access the game ID!</h3> <h4 className="heading__tertiary"> Then enter your name and join the game room </h4> {output} </div> ); } export default PublicGames;
/** * Created by gavin on 16/4/12. */ 'use strict'; var account = require('./account.js'); var ipcEvents = require('./ipcEvents.js'); module.exports.init = function (settings) { ipcEvents.init(settings); account.init(settings); };
import React, { Component } from 'react'; import './App.css'; class App extends Component { constructor(props) { super(props) this.state = { items: [ { name: "name1", description: "description 1" }, { name: "name2", description: "description 2" }, { name: "name3", description: "description 3" }, { name: "name4", description: "description 4" } ] } } render() { return ( <div> <h2>Projects:</h2> <ol> {this.state.items.map(item => ( <ul key={item.id}> <label> <li>{item.name} </li> <li>{item.description}</li> <hr></hr> </label> </ul> ))} </ol> </div> ) } } // class App extends Component { // render() { // let myProject = [{name: "n1", summary: "d1"}, {name: "n2", summary: "s2"}, {name: "n3", summary: "s3"}]; // let projectName = ""; // let projectDesc = ""; // // for (let i=0; i < myProject.length; i++){ // projectName = myProject[i].name // projectDesc = myProject[i].summary // // // console.log(projectName); // console.log(projectDesc); // // } // // return ( // <div> // <h1>My Projects</h1> // <h3>{projectName}</h3> // <p>{projectDesc}</p> // </div> // ); // } // } export default App;
'use strict'; /* https://github.com/angular/protractor/blob/master/docs/toc.md */ describe('E2E: ngSeedApp', function() { var ptor; beforeEach(function() { browser.get('http://127.0.0.1:8000/app'); ptor = protractor.getInstance(); }); it('should load the home page', function() { var ele = by.id('app-container'); expect(ptor.isElementPresent(ele)).toBe(true); }); it('should have the right title', function() { expect(browser.getTitle()).toMatch("ngSeedApp | AngularJS + Node.js"); }); });
import React from 'react'; import { ScrollView, Dimensions, ActivityIndicator, Alert } from 'react-native'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { Container } from '../../components/container'; import { Trip } from '../../components/trip'; import { QuestionsList } from './components/questions-list'; import { Widget } from './components/widget'; import { Button } from '../../components/button'; import { ButtonsContainer, ActivityIndicatorContainer, HeaderTitle, HeaderTitleContainer, WidgetsContainer, Card, Label } from './styles'; import { getVehicleTypeText } from '../../utils/vehicle-utils'; import { Actions } from './actions'; import { QuestionModal } from './components/question-modal'; import { QuestionsListModal } from './components/questions-list-modal'; import { SuccessModal } from '../../components/success-modal'; import { CARRIER_USER_TYPE } from '../../utils/constants/users'; import { ORDER_TYPE_EXPRESS } from '../../utils/constants/orders'; class OrderDetail extends React.Component { static navigationOptions = { title: ' ', headerStyle: { backgroundColor: '#2A2E43', elevation: 0, borderBottomWidth: 0 } }; constructor(props) { super(props); this.state = { question: '', questionListVisible: false, successModal: true }; } componentDidMount() { const { actions, navigation, reducer } = this.props; const orderId = navigation.state.params.orderID; if (reducer.lastFetched !== orderId) { actions.orderDetailRequest({ orderId }); } actions.getQuestionsRequest({ orderId }); } onChangeQuestion = (text) => { this.setState({ question: text }); }; successModal = () => { const { navigation, reducer, actions } = this.props; const { successModal } = this.state; return ( <SuccessModal visible={reducer.performServiceSuccess && successModal} onAcceptPress={() => { this.setState({ successModal: false }); actions.clearState({}); navigation.push('OrderTracking', { orderId: navigation.state.params.orderID }); }} onRequestClose={() => { this.setState({ successModal: false }); actions.clearState({}); navigation.push('OrderTracking', { orderId: navigation.state.params.orderID }); }} title="¡Asignación del pedido correcta!" subtitle="Ahora podrás seguir el seguimiento del pedido precionando Aceptar." /> ); }; questionModal = () => { const { question } = this.state; const { actions, reducer, global, navigation } = this.props; return ( <QuestionModal visible={reducer.questionVisible} question={question} onRequestClose={() => actions.toggleQuestionModal()} onChangeQuestion={this.onChangeQuestion} onAskPress={() => { actions.makeQuestionRequest({ clientId: reducer.order.uid, orderTitle: reducer.order.title, question, orderId: navigation.state.params.orderID, carrierId: global.user.uid, carrierUsername: global.user.username }); }} loading={reducer.isSendingQuestion} /> ); }; questionsListModal = () => { const { questionListVisible } = this.state; const { reducer, global, actions, navigation } = this.props; return ( <QuestionsListModal visible={questionListVisible} onRequestClose={() => this.setState({ questionListVisible: false })} questions={reducer.questions} onPress={() => { actions.toggleQuestionModal(); this.setState({ questionListVisible: false }); }} usertype={global.user.type} orderID={navigation.state.params.orderID} onPressQuestion={(item) => { navigation.navigate('AnswerQuestion', item); this.setState({ questionListVisible: false }); }} /> ); }; render() { const { reducer, global, actions, navigation } = this.props; return ( <Container> <HeaderTitleContainer> <HeaderTitle>{reducer.order.title}</HeaderTitle> </HeaderTitleContainer> {reducer.isFetching ? ( <ActivityIndicatorContainer> <ActivityIndicator /> </ActivityIndicatorContainer> ) : ( <ScrollView> {/* <OrderSubtitleText>{`Para el ${reducer.order.order_date} a las ${reducer.order.since_time}`}</OrderSubtitleText> */} <WidgetsContainer> <Widget icon="ios-car" label="Vehiculo requerido" value={getVehicleTypeText(reducer.order.vehicleType)} /> <Widget icon="ios-cash" label="Ganancia" value={`$ ${reducer.order.value}`} /> <Widget value={reducer.order.order_date} label="Fecha a realizar" icon="ios-calendar" /> <Widget value={`${reducer.order.since_time} hs`} label="A partir de" icon="ios-navigate" /> <Widget value={ reducer.order.until_time === '' ? 'A elección' : `${reducer.order.until_time} hs` } label="Horario limite" icon="ios-timer" /> <Widget icon="ios-timer" label="Duración" value={reducer.order.duration} /> <Widget icon="ios-map" label="Recorrido" value={reducer.order.distance} /> <Widget icon="md-person" label="Con asistente" value={reducer.order.assistant ? 'Sí' : 'No'} /> <Widget icon="ios-return-left" label="Retorno" value={reducer.order.withReturn ? 'Sí' : 'No'} /> </WidgetsContainer> <Label>VIAJE</Label> <Card> {reducer.order.origin !== undefined && ( <Trip origin={reducer.order.origin} destinations={ reducer.order.type === ORDER_TYPE_EXPRESS ? [reducer.order.destination] : reducer.order.waypoints } /> )} </Card> <Label>PREGUNTAS</Label> <Card> <QuestionsList questions={reducer.questions} usertype={global.user.type} onPress={() => this.setState({ questionListVisible: true })} orderID={navigation.state.params.orderID} /> </Card> {global.user.type === CARRIER_USER_TYPE ? ( <ButtonsContainer> <Button width={Dimensions.get('window').width - 25} color="#665EFF" radius onPress={() => { Alert.alert( 'Información', 'Realizar el envío es un compromiso, en caso de no hacerlo, se aplicará una multa junto con el precio del pedido.', [ { text: 'Cancelar', onPress: () => console.log('Cancel Pressed'), style: 'cancel' }, { text: 'Aceptar', onPress: () => { actions.performServiceRequest({ value: reducer.order.value, orderID: navigation.state.params.orderID, carrier: global.user, clientUID: reducer.order.uid, orderTitle: reducer.order.title, vehicleType: reducer.order.vehicleType }); } } ] ); }} title="REALIZAR SERVICIO" loading={reducer.isSendingPerformService} /> </ButtonsContainer> ) : ( <ButtonsContainer> <Button width={Dimensions.get('window').width - 25} color="#665EFF" radius onPress={() => { navigation.navigate('OrderCancel', { orderID: navigation.state.params.orderID, trackingStatus: null }); }} title="CANCELAR PEDIDO" /> </ButtonsContainer> )} </ScrollView> )} {this.questionModal()} {this.questionsListModal()} {this.successModal()} </Container> ); } } function mapStateToProps(state) { return { reducer: state.orderDetailReducer, global: state.globalReducer }; } function mapDispatchToProps(dispatch) { return { actions: bindActionCreators({ ...Actions }, dispatch) }; } export default connect( mapStateToProps, mapDispatchToProps )(OrderDetail);
var a = 'a'; var b = function() {}; var c = () => {}; var d = async () => {}; module.e = 'e'; module.f = function() {}; module.g = async function() {}; module.h = () => {}; function i() { } class Person { static foo = bar; getName() { } } foo(function callback() { }) c(); module.e(); export function keywords() { do {} while (a); try {} catch (e) {} finally {} throw e } class A {} const ABC = 1 const AB_C1 = 2 const {AB_C2_D3} = x module.exports = function(one, two) { if (something()) { let module = null, one = 1; console.log(module, one, two); } console.log(module, one, two); }; console.log(module, one, two); function one({two: three}, [four]) { console.log(two, three, four) } //1. Variables let name = "Sourcegraph"; const age = 2; var skills = ["language model", "natural language processing"]; //2. Data types const number = 10; const float = 10.5; const string = "hello"; const boolean = true; const array = [1, 2, 3]; const object = {key: "value"}; const symbol = Symbol(); //3. Conditional statements if (age > 1) { console.log(`${name} is ${age} years old.`); } else { console.log(`${name} is a baby.`); } //4. Loop for (let i = 0; i < skills.length; i++) { console.log(skills[i]); } //5. Functions function greet(name) { return `Hello, ${name}!`; } console.log(greet(name)); //6. Arrow functions const multiply = (a, b) => a * b; console.log(multiply(2, 3)); //7. Object methods const person = { name: "John", age: 30, sayHello() { console.log(`Hello, my name is ${this.name}.`); } }; person.sayHello(); //8. Destructuring const { name: personName, age: personAge } = person; console.log(personName, personAge); //9. Spread operator const newSkills = [...skills, "JavaScript"]; console.log(newSkills); //10. Rest operator function sum(...numbers) { let result = 0; for (const number of numbers) { result += number; } return result; } console.log(sum(1, 2, 3, 4)); //11. Classes class Animal { constructor(name, type) { this.name = name; this.type = type; } sayHello() { console.log(`Hello, I am ${this.name} and I am a ${this.type}.`); } } const cat = new Animal("Tom", "cat"); cat.sayHello(); //12. Inheritance class Dog extends Animal { constructor(name, breed) { super(name, "dog"); this.breed = breed; } sayHello() { console.log(`Hello, I am ${this.name} and I am a ${this.breed} breed ${this.type}.`); } } const dog = new Dog("Max", "Labrador"); dog.sayHello(); //13. Template literals const message = `${name} is a ${age}-year-old ${skills[0]}.`; console.log(message); //14. Ternary operator const result = (age > 18) ? "Adult" : "Child"; console.log(result); //15. Map const numbers = [1, 2, 3, 4]; const doubledNumbers = numbers.map(number => number * 2);
var validate = require( LIB_DIR + 'validations/sessions' ); var Application = require( './application' ); var Controller = Application.extend( validate ); var locale_users = require( LANG_DIR + 'en/users' ); var User = Model( 'User' ); module.exports = Controller.extend({ init : function ( before, after ){ before( this.validate_create, { only : [ 'create' ]}); }, render_new : function ( args, res ){ res.render( 'session/new', { title : locale_users.login_page_title, email : args.email, locale : locale_users }); }, new : function ( req, res, next ){ this.render_new({}, res ); }, create : function ( req, res, next ){ var self = this; var login_args = { email : req.form.email, password : req.form.password }; var render_args = { email : req.body.email }; User.login( login_args, next, function (){ req.flash( 'error', locale_users.user_not_found_msg ); self.render_new( render_args, res ); }, function (){ req.flash( 'error', locale_users.login_failed_msg, next ); self.render_new( render_args, res ); }, function (){ req.flash( 'error', locale_users.user_not_verified_msg ); self.render_new( render_args, res ); }, function (){ req.flash( 'error', locale_users.user_locked_msg ); self.render_new( render_args, res ); }, function ( user ){ req.session.user_id = user._id; res.redirect( '/' ); }); }, destroy : function ( req, res, next ){ req.session.destroy(); res.redirect( '/' ); } });
import React from "react"; import { Link } from "react-router-dom"; const NotFound = () => { return( <div className="notfound"> <h1>Página não encontrada :(</h1> <h2>Sentimos muito pelo incoveniente</h2> <div> <p>Algumas razões para isso acontecer:</p> <ul> <li>A página pode ter sido removida;</li> <li>A página pode estar temporariamente indisponível;</li> <li>Você pode ter digitado o endereço errado.</li> </ul> </div> <p className="button-pri botaovoltarhome"> <Link to="/home">Voltar para Página inicial!<span/></Link> </p> </div> ) } export default NotFound;
/* eslint-env jest */ const { setupServer, setupModels, stopServer } = require('../test/integration-setup.js')() describe('Test include', () => { const STATUS_OK = 200 let server let instances let sequelize beforeEach(async () => { const { server: _server, sequelize: _sequelize } = await setupServer() server = _server sequelize = _sequelize instances = await setupModels(sequelize) }) afterEach(() => stopServer(server)) test('belongsTo /team?include=city', async () => { const { team1, city1 } = instances const path = `/team/${team1.id}?include=city` const { result, statusCode } = await server.inject(path) expect(statusCode).toBe(STATUS_OK) expect(result.id).toBe(team1.id) expect(result.City.id).toBe(city1.id) }) test('belongsTo /team?include=cities', async () => { const { team1, city1 } = instances const path = `/team/${team1.id}?include=cities` const { result, statusCode } = await server.inject(path) expect(statusCode).toBe(STATUS_OK) expect(result.id).toBe(team1.id) expect(result.City.id).toBe(city1.id) }) test('hasMany /team?include=player', async () => { const { team1, player1, player2 } = instances const path = `/team/${team1.id}?include=player` const { result, statusCode } = await server.inject(path) expect(statusCode).toBe(STATUS_OK) expect(result.id).toBe(team1.id) const playerIds = result.Players.map(({ id }) => id) expect(playerIds).toContain(player1.id) expect(playerIds).toContain(player2.id) }) test('hasMany /team?include=players', async () => { const { team1, player1, player2 } = instances const path = `/team/${team1.id}?include=players` const { result, statusCode } = await server.inject(path) expect(statusCode).toBe(STATUS_OK) expect(result.id).toBe(team1.id) const playerIds = result.Players.map(({ id }) => id) expect(playerIds).toContain(player1.id) expect(playerIds).toContain(player2.id) }) test('multiple includes /team?include=players&include=city', async () => { const { team1, player1, player2, city1 } = instances const path = `/team/${team1.id}?include=players&include=city` const { result, statusCode } = await server.inject(path) expect(statusCode).toBe(STATUS_OK) expect(result.id).toBe(team1.id) expect(result.City.id).toBe(city1.id) const playerIds = result.Players.map(({ id }) => id) expect(playerIds).toContain(player1.id) expect(playerIds).toContain(player2.id) }) test('multiple includes /team?include[]=players&include[]=city', async () => { const { team1, player1, player2, city1 } = instances const path = `/team/${team1.id}?include[]=players&include[]=city` const { result, statusCode } = await server.inject(path) expect(statusCode).toBe(STATUS_OK) expect(result.id).toBe(team1.id) expect(result.City.id).toBe(city1.id) const playerIds = result.Players.map(({ id }) => id) expect(playerIds).toContain(player1.id) expect(playerIds).toContain(player2.id) }) })
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); class SceneComponents extends SupCore.Data.Base.ListById { constructor(pub, sceneAsset) { super(pub, SceneComponents.schema); this.configsById = {}; this.sceneAsset = sceneAsset; const system = (this.sceneAsset.server != null) ? this.sceneAsset.server.system : SupCore.system; const componentConfigClasses = system.getPlugins("componentConfigs"); for (const item of this.pub) { const componentConfigClass = componentConfigClasses[item.type]; if (componentConfigClass == null) { if (sceneAsset != null) { const scenePath = sceneAsset.server.data.entries.getPathFromId(sceneAsset.id); throw new Error(`Could not find component config class for type ${item.type} in scene ${scenePath} ` + `of project ${sceneAsset.server.data.manifest.pub.name} (${sceneAsset.server.data.manifest.pub.id})`); } else { throw new Error(`Could not find component config class for type ${item.type}`); } } this.configsById[item.id] = new componentConfigClass(item.config, this.sceneAsset); } } add(component, index, callback) { super.add(component, index, (err, actualIndex) => { if (err != null) { callback(err, null); return; } const componentConfigClass = this.sceneAsset.server.system.getPlugins("componentConfigs")[component.type]; this.configsById[component.id] = new componentConfigClass(component.config, this.sceneAsset); callback(null, actualIndex); }); } client_add(component, index) { super.client_add(component, index); const componentConfigClass = SupCore.system.getPlugins("componentConfigs")[component.type]; this.configsById[component.id] = new componentConfigClass(component.config); } remove(id, callback) { super.remove(id, (err) => { if (err != null) { callback(err); return; } this.configsById[id].destroy(); delete this.configsById[id]; callback(null); }); } client_remove(id) { super.client_remove(id); delete this.configsById[id]; } } SceneComponents.schema = { type: { type: "string" }, config: { type: "any" }, }; exports.default = SceneComponents;
const mongoose = require('mongoose') const logger = require('./loggerLib') const Response = require('./generateResponseLib') const util = require('./utilityLib') const fs = require('fs') //Importing the models here const UserModel = mongoose.model('User') let putOrGetFilePath = (req, res, request_type) => { if (!req.query.userId) { let apiResponse = Response.generate(true, 'File/Image Retrieval Unsuccessful !! UserId field missing.', 400, null); res.send(apiResponse); return; } UserModel.findOne({ userId: req.query.userId }, (err, userDetails) => { let tempMsg = request_type === 'PUT' ? 'Upload' : 'Retrieval'; if (err) { logger.error(err.message, 'uploadFile: putOrGetFilePath()', 10) let apiResponse = Response.generate(true, `File/Image ${tempMsg} Unsuccessful !! Error occurred while querying`, 500, null) res.send(apiResponse) } else if (util.isEmpty(userDetails)) { let apiResponse = Response.generate(true, `File/Image ${tempMsg} Unsuccessful !! No User found`, 404, null) res.send(apiResponse) } else { if (request_type === 'GET') { let responseBody = { userId: userDetails.userId, avatarPath: userDetails.avatarPath, }; let apiResponse = Response.generate(false, 'File/Image Path Retrieved !!', 200, responseBody) res.send(apiResponse) return; } userDetails.avatarPath = req.file.path; userDetails.save((error, newUserDetails) => { if (error) { console.log(error) logger.error(error.message, 'uploadFile: putFilePath()', 10) let apiResponse = Response.generate(true, 'Failed To update Path', 500, null) res.send(apiResponse) } else { let responseBody = { userId: newUserDetails.userId, avatarPath: newUserDetails.avatarPath }; let apiResponse = Response.generate(false, 'File/Image Uploaded Successfully !!', 200, responseBody) res.send(apiResponse) } }) } }) } // END putFilePath() /** * Function to upload a File * @param {*} app */ let uploadFile = (app) => { const multer = require('multer'); const storage = multer.diskStorage({ // destination is wrt where 'app' is located(here it's index.js) destination: function (req, file, cb) { console.log('file = ', file) cb(null, './userAvatars') }, filename: function (req, file, cb) { cb(null, new Date().valueOf() + file.originalname) } }); let isFormatSupported = true; const fileFilter = (req, file, cb) => { // exclude a file if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png') cb(null, true); else { console.log('File Format not supported') isFormatSupported = false; cb(null, false); } } const upload = multer({ storage: storage, limits: { fileSize: 1024 * 1024 * 2 }, fileFilter: fileFilter }); /* Upload User Avatar */ app.post('/api/v1/users/uploadAvatar', upload.single('avatar'), function (req, res) { console.log('Uploaded file:', req.file) console.log('req.body:', req.body) console.log('req.query:', req.query) if (isFormatSupported === false) { let apiResponse = Response.generate(true, 'File/Image Upload Unsuccessful !! File Format not supported.', 400, null); res.send(apiResponse) } else if (req.file === undefined || req.file === null) { let apiResponse = Response.generate(true, 'File/Image Upload Unsuccessful !! Some Error Occurred.', 500, null); res.send(apiResponse) } else putOrGetFilePath(req, res, 'PUT') }); /* Get User Avatar */ app.get('/api/v1/users/getAvatar', function (req, res) { putOrGetFilePath(req, res, 'GET') }) } module.exports = { uploadFile: uploadFile }
import React from 'react'; import { AsyncStorage, View, Image, ToastAndroid, } from 'react-native'; import { Container, Content, Button, Text, H3, Icon, FooterTab, Footer } from 'native-base'; import { LogoTitle, Menu } from '../../../components/header'; import { addPicture, addArchive } from '../../../database/realm'; import Spinner from 'react-native-loading-spinner-overlay'; import Strings from '../../../language/fr'; import { reverseFormat } from '../../../utilities/index'; import { imagePickerOptions } from '../../../utilities/image-picker'; import { FilePicturePath, writePicture, toDate, toYM } from '../../../utilities/index'; var ImagePicker = require('react-native-image-picker'); export class TraceIndexScreen extends React.Component { static navigationOptions = ({ navigation }) => { return { drawerLabel: Strings.TRACEABILITY, drawerIcon: ({ tintColor }) => ( <Icon name='camera' style={{ color: tintColor, }} /> ), headerLeft: <Menu navigation={navigation} />, headerTitle: <LogoTitle HeaderText={Strings.TRACEABILITY} />, // headerRight: <Menu navigation={navigation} />, }; }; constructor(props) { super(props); this.state = { loading: 0, userId: null, source: '', date: toDate((new Date())), YM: toYM((new Date())), created_at: new Date(), }; this._bootstrapAsync(); } _bootstrapAsync = async () => { const userID = await AsyncStorage.getItem('userSessionId'); this.setState({ userId: userID, }); }; _showLoader() { this.setState({ loading: 1 }); } _hideLoader() { this.setState({ loading: 0 }); } componentDidMount() { this._loadItems(); }; componentDidFocus() { this._loadItems(); }; _loadItems = async () => { } _pickImage = () => { ImagePicker.launchCamera(imagePickerOptions, (response) => { if (response.data) { writePicture(response.data).then(filename => { this.setState({ source: filename }); }); } }); }; _confirm() { if (this.state.userId == null) { ToastAndroid.show("USER_ID_IS_NULL", ToastAndroid.LONG); return; } if (this.state.source.length == 0) { ToastAndroid.show(Strings.PLEASE_TAKE_A_PICTURE, ToastAndroid.LONG); return; } this._showLoader(); setTimeout(() => { addPicture(this.state.userId, { source: this.state.source, date: this.state.date, created_at: this.state.created_at, }).then(() => { addArchive(this.state.date, this.state.YM, true, this.state.userId); this.props.navigation.navigate('Home'); this._hideLoader(); ToastAndroid.show(Strings.PICTURE_SUCCESSFULL_SAVED, ToastAndroid.LONG); }).catch(error => { alert(error); }); }, 2000); } render() { return ( <Container style={{ alignItems: 'center', paddingTop: 110, }}> <Spinner visible={this.state.loading} textContent={Strings.LOADING} textStyle={{ color: '#FFF' }} /> <Content> <View style={{ width: 400, height: 300 }}> {this.state.source.length == 0 && <Button style={{ flex: 1, }} full light onPress={this._pickImage} > <Icon name='camera' fontSize={50} size={50} style={{ color: 'gray', fontSize: 80, }} /> </Button>} {this.state.source.length > 0 && <Image resizeMode={'contain'} style={{ flex: 1, }} source={{ uri: FilePicturePath() + this.state.source }} />} </View> <View style={{ alignItems: 'center', paddingTop: 40, }}> <H3>{reverseFormat(this.state.date)}</H3> </View> </Content> <Footer styles={{ height: 100 }}> <FooterTab styles={{ height: 100 }}> <Button light onPress={() => this.props.navigation.navigate('Home')}> <View style={{ flexDirection: 'row' }}> <Text style={{ paddingTop: 5, }}>{Strings.CANCEL}</Text> <Icon name='close' /> </View> </Button> <Button full success onPress={_ => this._confirm()} > <View style={{ flexDirection: 'row' }}> <Text style={{ color: 'white', paddingTop: 5, }}>{Strings.CONFIRM}</Text> <Icon name='checkmark' style={{ color: 'white', }} /> </View> </Button> </FooterTab> </Footer> </Container> ); } }
const { NODE_ENV } = process.env; const isDev = NODE_ENV !== 'production'; export const errorCodes = { USER_DATA_INVALID: 1, EXPENSE_DATA_INVALID: 2, BAD_REQUEST: 400, NOT_AUTHORISED: 401, FORBIDDEN: 403, NOT_FOUND: 404, INTERNAL_SERVER_ERROR: 500, }; export const createError = (code, title, detail, throwable) => ({ code, detail, title, ...( isDev && throwable ? { meta: { debug: throwable, }, } : {} ), }); export const joiToApiErrors = (code, joiError) => ( joiError.details.map(({ message, path }) => ({ ...createError(code, 'Validation error', message), path, })) ); export const notFound = () => createError( errorCodes.NOT_FOUND, 'Not found', 'The URI requested is invalid or the resource requested does not exist.', ); export const badRequest = err => createError( errorCodes.BAD_REQUEST, 'Bad request', 'The request was invalid or cannot be otherwise served.', err, ); export const notAuthorized = () => createError( errorCodes.NOT_AUTHORISED, 'Not authorized', 'Missing or incorrect authentication credentials.', ); export const internalServerError = err => createError( errorCodes.INTERNAL_SERVER_ERROR, 'Internal server error', 'Something is broken.', err, );
import React from 'react' import css from '../../../lib/css/' import styles from './styles.js' import Carousel from 'nuka-carousel' export default ({ involvementTitle = '', involvement = '', carousel = [], aboutTitle = '', about = '' }) => ( <article className={css(styles.root)}> <div className={css(styles.title)} dangerouslySetInnerHTML={{ __html: involvementTitle }} /> <div className={css(styles.content)} dangerouslySetInnerHTML={{ __html: involvement }} /> <Carousel className={css(styles.carousel)}> {carousel.map((item, i) => ( <div key={i}> <img className={css(styles.image)} src={item.image.url} /> </div> ))} </Carousel> <div className={css(styles.title)} dangerouslySetInnerHTML={{ __html: aboutTitle }} /> <div className={css(styles.content)} dangerouslySetInnerHTML={{ __html: about }} /> </article> )
/* * warehouseComponent.js * * Copyright (c) 2017 HEB * All rights reserved. * * This software is the confidential and proprietary information * of HEB. */ 'use strict'; /** * CasePack ->warehouse page component. * * @author s753601 * @since 2.8.0 */ (function () { angular.module('productMaintenanceUiApp').component('warehouse', { // isolated scope binding bindings: { itemMaster: '<' }, scope: '=', // Inline template which is binded to message variable in the component controller templateUrl: 'src/productDetails/productCasePacks/warehouse.html', // The controller that handles our component logic controller: WarehouseController }); WarehouseController.$inject = ['ProductFactory', 'PMCommons', '$scope', '$rootScope', 'ProductCasePackApi', '$timeout', 'ngTableParams', '$filter', 'ProductDetailAuditModal', 'ProductSearchService']; /** * Case Pack Warehouse component's controller definition. * @param $scope scope of the case pack info component. * @constructor */ function WarehouseController(productFactory, PMCommons, $scope, $rootScope, productCasePackApi, $timeout, ngTableParams, $filter, ProductDetailAuditModal, productSearchService) { /** All CRUD operation controls of Case pack Import page goes here */ var self = this; /** * Flags for wether or not a panel is open or closed. * @type {boolean} */ self.orderingInfoVisibility=true; self.weightVisibility = true; self.costVisibility = true; self.wHSTieTierSlotVisibility = true; self.changeLogVisibility = true; /** *Token that is used to keep track of the current request so that old requests will be ignored. * @type {number} */ self.latestRequest=0; /** * Array that holds the warehouse item locations * @type {Array} */ self.data=[]; /** * Array that to backup the warehouse item locations * @type {Array} */ self.dataOrig=[]; /** * Array that hold the current warehouse item location's remarks. * @type {Array} */ self.remarkData=[]; /** * Array that hold the original warehouse item location's remarks. * @type {Array} */ self.originalRemarkData=[]; /** * Array that holds the orderQuantityTypes * @type {Array} */ self.orderQuantityTypes=[]; /** * Array that holds the flow types * @type {Array} */ self.flowTypes=[]; /** * flag to state if there is a request for additional data * @type {boolean} */ self.isWaitingForResponse= false; /** * Because there are so many API calls on init and on changes these flags are set to insure everything is * present before the view is displayed. * @type {boolean} */ self.isWaitingForWarehouseLocationItems=true; self.isWaitingForFlows = true; self.isWaitingForOrderQuantity=true; /** * Flag used to state there is a request for comment data. * @type {boolean} */ self.isWaitingForCommentResponse = false; /** * Object warehouseLocationitem Selected. * @type {{}} */ self.warehouseLocationItemSeleted={}; /** * RegExp check number is integer type, and max value is 999999999 * @type {{}} */ self.regexInt = new RegExp("^[0-9]{1,9}$"); /** * RegExp check number is decimal type (#####.####), and max value is 99999.9999 * @type {{}} */ self.regexDecimal = new RegExp("^[0-9]{1,5}\.?([0-9]{1,4})?$"); /** * Component ngOnInit lifecycle hook. This lifecycle is executed every time the component is initialized * (or re-initialized). */ this.$onInit = function () { self.disableReturnToList = productSearchService.getDisableReturnToList(); self.isWaitingForFlows = true; self.isWaitingForOrderQuantity=true; productCasePackApi.getFlowTypes(self.loadFlowTypes, self.fetchError); productCasePackApi.getOrderQuantityTypes(self.loadOrderQuantityTypes, self.fetchError) }; /** * Component ngOnChanges lifecycle hook. Called whenever a binding variable is changed. */ this.$onChanges = function (){ self.success = ""; self.error = "" self.isWaitingForResponse=true; self.isWaitingForWarehouseLocationItems=true; var thisRequest = ++self.latestRequest; productCasePackApi.getWarehouseInfo({ itemCode: self.itemMaster.key.itemCode, itemType: self.itemMaster.key.itemType }, //success case function (results) { if (thisRequest === self.latestRequest) { self.loadData(results); } }, //error case function(results){ if(thisRequest === self.latestRequest){ self.fetchError(results) } }); }; /** * Component ngOnDestroy lifecycle hook. Called just before Angular destroys the directive/component. */ this.$onDestroy = function () { /** Execute component destroy events if any. */ }; /** * This method will allow the panels to toggle from visible to hidden. * @param segment which panel was clicked. */ self.toggleVisibility = function (panelNumber) { switch(panelNumber){ case 1: self.orderingInfoVisibility = !self.orderingInfoVisibility; break; case 2: self.weightVisibility = !self.weightVisibility; break; case 3: self.costVisibility = !self.costVisibility; break; case 4: self.wHSTieTierSlotVisibility = !self.wHSTieTierSlotVisibility; break; case 5: self.changeLogVisibility = !self.changeLogVisibility; default: break; } }; /** * Fetches the error from the back end. * @param error */ self.fetchError = function(error) { self.isWaitingForResponse = false; if(error && error.data) { self.isLoading = false; if (error.data.message) { self.setError(error.data.message); } else { self.setError(error.data.error); } } else { self.setError("An unknown error occurred."); } }; /** * Sets the controller's error message. * @param error The error message. */ self.setError = function(error) { self.error = error; }; /** * After getting the data from the API this method will begin the view construction. * @param results the warehouse location items from the API */ self.loadData = function (results) { self.isWaitingForWarehouseLocationItems = false; //Checking Whse Max Ship Qty#. if WHSE_LOC_ITM.MAX_SHP_WHSE_QTY = 99999 then the application will get the // value of ITEM_MASTER.MAX_SHIP_QTY. // It was confirmed by Girish as confirmed by Girish on PIM 1067 on 08/26/2015. angular.forEach(results, function(elm){ if(elm.whseMaxShipQuantityNumber === 99999){ elm.whseMaxShipQuantityNumber = angular.copy(self.itemMaster.maxShipQty); } }); self.data = results; self.dataOrig = angular.copy(results); self.setPanelWidths(); self.checkLoadStatus() }; /** * This method takes the order quantity types taken from the database and attaches them to the UI dropdown variable * @param results form requesting for the order quantity types from the api */ self.loadOrderQuantityTypes = function (results) { self.isWaitingForOrderQuantity=false; self.orderQuantityTypes=results; self.checkLoadStatus(); }; /** * This method takes the flow types taken from the database and attaches them to the UI dropdown variable * @param results form requesting for the flow types from the api */ self.loadFlowTypes= function (results) { self.isWaitingForFlows = false; self.flowTypes=results; self.checkLoadStatus(); }; /** * This method insures that all the data is present before displaying the results */ self.checkLoadStatus=function () { self.isWaitingForResponse=self.isWaitingForFlows||self.isWaitingForWarehouseLocationItems||self.isWaitingForOrderQuantity; }; /** * This method will see if the number of items will fit on the screen and if not it will extend the widths of * all the panels to fit all of the contents. */ self.setPanelWidths= function () { var panelWidth=""; var minWidth=200; if(self.data.length>8){ panelWidth = ((self.data.length +1)*minWidth) + "px" } else{ panelWidth="inherit" } document.getElementById("warehouseList").style.width=panelWidth; document.getElementById("orderingInfoPanel").style.width=panelWidth; document.getElementById("weightPanel").style.width=panelWidth; document.getElementById("costPanel").style.width=panelWidth; document.getElementById("wHSTieTierSlotPanel").style.width=panelWidth; document.getElementById("changeLogPanel").style.width=panelWidth; }; /** * This method will make a call to the API to get the remarks for the item at the warehouse * @param warehouseLocationItem warehouseLocationItem the item at the warehouse whose remarks your requesting. */ self.getCommentsAndRemarks=function(warehouseLocationItem){ self.isSaveRemarkSuccess = false; self.commentAndRemarkError = ""; self.commentAndRemarkSuccess = ""; self.warehouseLocationItemSeleted = angular.copy(warehouseLocationItem); self.currentLocation=warehouseLocationItem.location.displayName; self.currentComment=warehouseLocationItem.comment; self.originalComment=angular.copy(warehouseLocationItem.comment); self.currentWarehouseLocationNbr=warehouseLocationItem.key.warehouseNumber; self.isWaitingForCommentResponse = true; self.remarkData=[]; var param = { itemId: warehouseLocationItem.key.itemCode, itemType: warehouseLocationItem.key.itemType, warehouseNumber: warehouseLocationItem.key.warehouseNumber, warehouseType: warehouseLocationItem.key.warehouseType }; productCasePackApi.getRemarks(param, self.loadRemark, self.errorRemark); }; /** * This method will make a call to the API to get the remarks for the item at the warehouse after save Remark * @param warehouseLocationItem warehouseLocationItem the item at the warehouse whose remarks your requesting. */ self.getCommentsAndRemarksAfterSave=function(warehouseLocationItem){ self.commentAndRemarkError = ""; self.commentAndRemarkSuccess = ""; self.remarkData=[]; var param = { itemId: warehouseLocationItem.key.itemCode, itemType: warehouseLocationItem.key.itemType, warehouseNumber: warehouseLocationItem.key.warehouseNumber, warehouseType: warehouseLocationItem.key.warehouseType }; productCasePackApi.getRemarks(param, self.loadRemark, self.errorRemark); } /** * When successfully getting the remarks this method sets up the data to be displayed. * @param result the remarks for an item at a location. */ self.loadRemark = function (result) { self.itemWarehouseCommentsUpdate = []; self.remarkData=result; self.originalRemarkData = angular.copy(result); document.getElementById("remarksRow").rowSpan=(""+3*self.remarkData.length) ; self.isWaitingForCommentResponse = false; if(self.isSaveRemarkSuccess){ self.commentAndRemarkSuccess = "Updated successfully"; self.originalComment = self.currentComment; } }; /** * Fetches the error from the back end. * @param error */ self.errorRemark = function (error) { self.isWaitingForCommentResponse = false; if(error && error.data) { if (error.data.message) { self.setCommentError(error.data.message); } else { self.setCommentError(error.data.error); } } else { self.setCommentError("An unknown error occurred."); } }; /** * Sets the controller's error message. * @param error The error message. */ self.setCommentError = function(error) { self.isWaitingForCommentResponse = false; self.commentAndRemarkError = error; self.commentAndRemarkSuccess = ""; }; /** * Array contain Remark and Comment change. * @type {Array} */ self.itemWarehouseCommentsUpdate = []; /** * Add new row in Remark Comment. */ self.addNewRemarkComment = function () { if(self.remarkData != null && self.remarkData.length > 0){ var itemWarehouseComments = angular.copy(self.remarkData[self.remarkData.length - 1]); if(itemWarehouseComments.itemCommentContents != ""){ itemWarehouseComments.itemCommentContents = ""; itemWarehouseComments.key.itemCommentNumber += 1; self.remarkData.push(itemWarehouseComments); self.itemWarehouseCommentsUpdate.push(itemWarehouseComments); } }else{ var itemWarehouseCommentsNew = {}; itemWarehouseCommentsNew["key"] = {}; itemWarehouseCommentsNew["key"]["itemId"] = self.warehouseLocationItemSeleted.key.itemCode; itemWarehouseCommentsNew["key"]["itemType"] = self.warehouseLocationItemSeleted.key.itemType; itemWarehouseCommentsNew["key"]["warehouseNumber"] = self.warehouseLocationItemSeleted.key.warehouseNumber; itemWarehouseCommentsNew["key"]["warehouseType"] = self.warehouseLocationItemSeleted.key.warehouseType; itemWarehouseCommentsNew["key"]["itemCommentNumber"] = 1; itemWarehouseCommentsNew["itemCommentContents"] = ""; self.remarkData.push(itemWarehouseCommentsNew); self.itemWarehouseCommentsUpdate.push(itemWarehouseCommentsNew); document.getElementById("remarksRow").rowSpan=(""+3*self.remarkData.length) ; } } /** * Save data change in Remark Comment. */ self.saveRemarkComment=function(){ self.commentAndRemarkError = ""; self.commentAndRemarkSuccess = ""; if(self.checkChange()){ self.getItemWarehouseUpdate(); self.isWaitingForCommentResponse = true; var warehouseLocationItem = angular.copy(self.warehouseLocationItemSeleted); warehouseLocationItem["comment"] = self.currentComment; warehouseLocationItem["itemWarehouseCommentsList"] = self.itemWarehouseCommentsUpdate; console.log(angular.toJson(self.itemWarehouseCommentsUpdate)); productCasePackApi.updateRemarks(warehouseLocationItem, self.updateRemarksSuccess, self.setCommentError); }else{ self.commentAndRemarkError = "There are no change."; } }; /** * Save data change success. * @param results */ self.updateRemarksSuccess = function (results) { self.isWaitingForCommentResponse = false; self.getCommentsAndRemarksAfterSave(self.warehouseLocationItemSeleted); self.isSaveRemarkSuccess = true; } /** * Check different data after save. * @returns {boolean} */ self.checkChange = function () { var flagChangeData = false; if(self.currentComment.trim() != self.originalComment.trim()){ flagChangeData = true; }else{ if(self.remarkData.length == self.originalRemarkData.length){ for (var i = 0; i < self.remarkData.length; i++) { if(angular.toJson(self.remarkData[i]) != angular.toJson(self.originalRemarkData[i])){ flagChangeData = true; break; } } }else{ flagChangeData = true; } } return flagChangeData; } /** * Get data change after save. */ self.getItemWarehouseUpdate = function () { for (var i = 0; i < self.remarkData.length; i++) { var itemWarehouseCommentNew = angular.copy(self.remarkData[i]); for (var j = 0; j < self.originalRemarkData.length; j++) { var itemWarehouseCommentOrig = angular.copy(self.originalRemarkData[j]); if(itemWarehouseCommentNew.key.itemCommentNumber == itemWarehouseCommentOrig.key.itemCommentNumber){ if(angular.toJson(itemWarehouseCommentNew) != angular.toJson(itemWarehouseCommentOrig)) self.itemWarehouseCommentsUpdate.push(itemWarehouseCommentNew); } } } } /** * Reset data. */ self.resetRemarkComment=function(){ self.commentAndRemarkError = ""; self.commentAndRemarkSuccess = ""; self.remarkData = angular.copy(self.originalRemarkData); self.currentComment = angular.copy(self.originalComment); } /** * This method checks to see if any of the information of warehouse item locations have not been changed. * * @returns {boolean} Return true if any of the information of warehouse item locations have been changed. */ self.dataIsChanged = function () { if(angular.toJson(self.data) !== angular.toJson(self.dataOrig)){ $rootScope.contentChangedFlag = true; return true; } $rootScope.contentChangedFlag = false; return false; }; /** * This method to return back the value have been changed to old value. */ self.resetWarehouseItemLocation = function () { self.error = ''; self.success = ''; self.data = angular.copy(self.dataOrig); } /** * This method to return a list of warehouse location item, that have been changed. */ self.getDataChangedToSave = function () { var dataChanged = []; var lengthData = self.data.length; for(var i = 0; i< lengthData; i++){ if(angular.toJson(self.data[i]) != angular.toJson(self.dataOrig[i])){ dataChanged.push(angular.copy(self.data[i])); } } return dataChanged; } /** * Saves new information for the warehouse location item, that have been changed. After save successful * reload data. */ self.saveWarehouseItemLocation = function () { self.error = ''; self.success = ''; var dataChanged = self.getDataChangedToSave(); if(dataChanged){ var errorMessage = self.validation(dataChanged); if(errorMessage == null || errorMessage == ''){ self.isWaitingForResponse=true; self.isWaitingForWarehouseLocationItems=true; productCasePackApi.saveWarehouseItemLocation(dataChanged, //success case function (results) { self.isWaitingForResponse=false; self.isWaitingForWarehouseLocationItems=false; self.success = results.message; self.loadData(results.data); }, //error case function(results){ self.fetchError(results) } ); }else{ self.error = 'Case Pack - Warehouse:'; angular.forEach(errorMessage, function (value) { self.error += "<li>" +value + "</li>"; }) } } } /** * This method to validation data before call save. */ self.validation = function (dataChanged) { var errorMessage = []; for(var i = 0; i< dataChanged.length; i++){ var whsItemLocation = dataChanged[i]; if(whsItemLocation.whseMaxShipQuantityNumber && !self.regexInt.test(whsItemLocation.whseMaxShipQuantityNumber)){ if(errorMessage.indexOf("Whse Max Ship Qty must be number, and less than or equal to 999999999") == -1){ errorMessage.push("Whse Max Ship Qty must be number, and less than or equal to 999999999"); } } if(whsItemLocation.unitFactor1 && !self.regexDecimal.test(whsItemLocation.unitFactor1)){ if(errorMessage.indexOf("Unit Factor 1 must be number (#####.####), greater or equal 0 and less than or equal to 99999.9999") == -1){ errorMessage.push("Unit Factor 1 must be number (#####.####), greater or equal 0 and less than or equal to 99999.9999"); } } if(whsItemLocation.unitFactor2 && !self.regexDecimal.test(whsItemLocation.unitFactor2)){ if(errorMessage.indexOf("Unit Factor 2 must be number (#####.####), greater or equal 0 and less than or equal to 99999.9999") == -1){ errorMessage.push("Unit Factor 2 must be number (#####.####), greater or equal 0 and less than or equal to 99999.9999"); } } if(whsItemLocation.whseTie && !self.regexInt.test(whsItemLocation.whseTie)){ if(errorMessage.indexOf("Whse Tie must be number, and less than or equal to 999999999") == -1){ errorMessage.push("Whse Tie must be number, and less than or equal to 999999999"); } } if(whsItemLocation.whseTier && !self.regexInt.test(whsItemLocation.whseTier)){ if(errorMessage.indexOf("Whse Tier must be number, and less than or equal to 999999999") == -1){ errorMessage.push("Whse Tier must be number, and less than or equal to 999999999"); } } } return errorMessage; } /** * Show warehouse audit information modal */ self.showWarehouseAuditInfo = function () { self.warehouseAuditInfo = productCasePackApi.getWarehouseAudits; var title ="Warehouse"; var parameters = {'itemCode' :self.itemMaster.key.itemCode, 'itemType' :self.itemMaster.key.itemType}; ProductDetailAuditModal.open(self.warehouseAuditInfo, parameters, title); } /** * handle when click on return to list button */ self.returnToList = function(){ $rootScope.$broadcast('returnToListEvent'); }; } })();
/** * @namespace * @constructor * @param {vonline.Base array} object * @param {integer} x * @param {integer} y */ vonline.TranslateCommand = function(objects, x, y) { this.objects = objects; this.x = x; this.y = y; } vonline.TranslateCommand.prototype.execute = function() { for (var i = 0, len = this.objects.length; i < len; i++) { this.objects[i].setTranslation(this.x, this.y); } } vonline.TranslateCommand.prototype.undo = function() { for (var i = 0, len = this.objects.length; i < len; i++) { this.objects[i].setTranslation(-this.x, -this.y); } }
(function() { App.Controllers.UserProfiles = Ember.Namespace.create(); App.UserProfilesController = Ember.Table.TableController.extend({ hasHeader: true, hasFooter: false, numFixedColumns: 0, numRows: 2, rowHeight: 30, selection: null, selectionChanged: Ember.observer(function() { if(this.get('selection').length) { selection0 = this.get('selection')[0]; this.transitionToRoute('userProfile.edit', selection0); } }).observes('selection'), columns: Ember.computed(function() { var columnNames, columns, selectColumn, dateJoinedColumn, editColumn; columnNames = ['username', 'email_address']; selectColumn = Ember.Table.ColumnDefinition.create({ columnWidth: 20, contentPath: 'select', tableCellViewClass: 'Ember.Hukkster.Table.HtmlTableCell', getCellContent: function(row) { return '<input type="checkbox" />'; } }); dateJoinedColumn = Ember.Table.ColumnDefinition.create({ columnWidth: 100, headerCellName: 'Date_joined', tableCellViewClass: 'Ember.Hukkster.Table.DatePickerTableCell', getCellContent: function(row) { return row.get('date_joined'); }, setCellContent: function(row, value) { return row.set('date_joined', value); } }); editColumn = Ember.Table.ColumnDefinition.create({ columnWidth: 30, contentPath: 'edit', tableCellViewClass: 'Ember.Hukkster.Table.HtmlTableCell', getCellContent: function(row) { return ' '; }, }); columns = columnNames.map(function(key, index) { var name; name = key.charAt(0).toUpperCase() + key.slice(1).replace('_', ' '); return Ember.Table.ColumnDefinition.create({ columnWidth: 80, headerCellName: name, tableCellViewClass: 'Ember.Hukkster.Table.EditableTableCell', getCellContent: function(row) { return row.get(key); }, setCellContent: function(row, value) { return row.set(key, value); } }); }); columns.splice(5, 0, dateJoinedColumn); columns.unshift(selectColumn); columns.push(editColumn); return columns; }).property(), // content: Ember.computed(function() { // var _i, _ref, _results; // return (function() { // _results = []; // for (var _i = 0, _ref = this.get('numRows'); 0 <= _ref ? _i < _ref : _i > _ref; 0 <= _ref ? _i++ : _i--){ _results.push(_i); } // return _results; // }).apply(this).map(function(num, idx) { // return { // index: idx, // select: '<input type="checkbox" />', // TODO make this a view with contentPath // username: Ember.Hukkster.Utils.makeRandomString(8, 'abcdefghijklmnopqrstuvwxyz'), // email_address: Ember.Hukkster.Utils.makeRandomString(8, 'abcdefghijklmnopqrstuvwxyz') + '@gmail.com', // first_name: Ember.Hukkster.Utils.makeRandomString(5, 'abcdefghijklmnopqrstuvwxyz').capitalize(), // last_name: Ember.Hukkster.Utils.makeRandomString(5, 'abcdefghijklmnopqrstuvwxyz').capitalize(), // staff_status: 'N', // date_joined: Date.today().add({ // days: -idx // }), // last_login: Date.today().add({ // days: idx-2 // }), // approved: 'True', // email_status: (function() { e = ['invited', 'new']; return e[Math.floor(Math.random()*2)]; })(), // edit: '<a href="#" data-reveal-id="editModal">Edit</a>' // TODO make this a view with contentPath // }; // }); // }).property('numRows') content: null }); App.UserProfileController = Ember.ObjectController.extend({ content: null }); }).call(this);
var canvas = document.getElementById('gameCanvas'); var canvasCtx = canvas.getContext('2d'); canvas.width = 800; canvas.height = 600; var ballX = 50; var ballY = 50; var ballSpeedX = 5; var ballSpeedY = 5; var padOneY = 250; var padTwoY = 250; var padHeight = 100; var padWidth = 15; var playOne = 0; var playTwo = 0; function heading() { var text = document.getElementById('header'); var pos = 0; var id = setInterval(frame, 5); function frame() { if (pos < 640) { pos++; text.style.left = pos + 'px'; } else { // pos++; // text.style.left = pos + 'px'; } } } function startGame() { // Calling the function when window loads the page canvas; canvasCtx; var disappear = document.getElementById('button').style.display = "none"; var fps = 60; // frames per second setInterval(function() { moveObjects(); drawObjects(); }, 1000/fps); // Every one second after the page is loaded, it will call the draw function canvas.addEventListener('mousemove', function(evt) { var mousePosition = mousePos(evt); padOneY = mousePosition.y - (padHeight/2); // subtracting half the height of the paddle to move the paddle in the center }) } // 0, 0 would be top-left corner / width, 0 would be top-right / 0, height would be bottom-left / width, height would be bottom-right function ballReset() { ballSpeedX = -ballSpeedX; ballX = canvas.width / 2; ballY = canvas.height / 2; } function mousePos(evt) { // evt parameter is going to recieve the mouse coordinates var rect = canvas.getBoundingClientRect(); // The canvas size var root = document.documentElement; // HTML document var mouseX = evt.clientX - rect.left - root.scrollLeft; // Getting the the coordinates within the playable space var mouseY = evt.clientY - rect.top - root.scrollTop; // Getting the the coordinates within the playable space return { x: mouseX, y: mouseY } } function cpuMove() { var padTwoCenter = padTwoY + (padHeight / 2); if (padTwoCenter < ballY - 35) { // If ball is greater than paddle two center 35 px away, then shift it down 6 else shift up padTwoY += 4; } else if (padTwoCenter < ballY + 35) { padTwoY -= 4; } } function moveObjects() { cpuMove(); ballX += ballSpeedX; // Add 20 to the positionmof ballX ballY += ballSpeedY; // Add 20 to the positionmof ballX if (ballX < padWidth) { // If ball speed is less than zero send the ball the opposite direction if (ballY > padOneY && ballY < padOneY + padHeight) { // If ball is below the top of the paddle but above the bottom of the paddle then flip the ball ballSpeedX = -ballSpeedX; } else if (ballX < 0) { ballReset(); playTwo++; } } if (ballX > canvas.width - padWidth) { if (ballY > padTwoY && ballY < padTwoY + padHeight) { // If ball is below the top of the paddle but above the bottom of the paddle then flip the ball ballSpeedX = -ballSpeedX; } else if (ballX > canvas.width){ ballReset(); playOne++; } } if (ballY < 0) { // If ball speed is less than zero send the ball the opposite direction ballSpeedY = -ballSpeedY; } if (ballY > canvas.height) { ballSpeedY = -ballSpeedY; } } function drawObjects() { // Each time fuction is called canvasCtx.fillStyle = 'black'; // fill canvasCtx.fillRect(0, 0, canvas.width, canvas.height); // X axis, Y axis, width, height canvasCtx.fillStyle = 'white'; // fill canvasCtx.fillRect(0, padOneY, padWidth, padHeight); // X axis, Y axis, width, height canvasCtx.fillStyle = 'white'; // fill canvasCtx.fillRect(canvas.width - 15, padTwoY, padWidth, padHeight); // X axis, Y axis, width, height canvasCtx.beginPath(); canvasCtx.arc(ballX, ballY, 8, 0, Math.PI * 2, false); // Research arc method canvasCtx.fillStyle = "white"; canvasCtx.fill(); canvasCtx.fillText(playOne, 100, 100); // Score is 100 pixels from the top and start of the canvas canvasCtx.fillText(playTwo, canvas.width - 100, 100); // Score is 100 pixels from the top and width of the canvas canvasCtx.font = "30px Arial"; }
import React from 'react'; import { Form, Button, Row, Col } from 'antd'; import FormSwitch from './FormSwitch'; function Notifications() { const layout = { labelCol : { span: 16 }, wrapperCol : { span: 8 } }; const tailLayout = { wrapperCol : { offset: 8, span: 16 } }; return ( <Row justify="center"> <Col span={12}> <Row justify="center" className="notifyRow"> <Col span={12}> <Form {...layout}> <FormSwitch type="Send all alerts." /> <FormSwitch type="Alerts only task success." /> <FormSwitch type="Alerts only for failed tasks." /> <FormSwitch type="I dont want any alerts." /> <Form.Item {...tailLayout}> <Button type="danger" htmlType="button" style={{ margin: 2 }}> Cancel </Button> <Button id="submitBtn" htmlType="submit" style={{ margin: 2 }}> Submit </Button> </Form.Item> </Form> </Col> </Row> </Col> </Row> ); } export default Notifications;
'use strict' import express from 'express' import asyncify from 'express-asyncify' import chalk from 'chalk' import debug from 'debug' import db from './db' export default (opts) => { let services, Client const app = asyncify(express.Router()) app.use('*', async (req, res, next) => { if (!services) { debug(chalk.yellow('Connecting database')) try { services = await db(opts.DB) } catch (e) { return next(e) } Client = services.Client } next() }) app.get('/', async (req, res, next) => { debug(chalk.yellow('Request to get all clients')) let clients try { clients = await Client.findAll() } catch (e) { return next(e) } res.status(200).send(clients) }) app.get('/:id', async (req, res, next) => { const clientId = req.params.id let client debug(chalk.yellow(`Request to get client by Id ${clientId}`)) try { client = await Client.findByPk(clientId) } catch (e) { return next(e) } if (!client) { return next(new Error(`Cliente con id [${clientId}] no encontrado`)) } res.status(200).send(client) }) app.post('/', async (req, res, next) => { debug(chalk.yellow('Request to save client')) let clientCreated const client = req.body try { clientCreated = await Client.create(client) } catch (e) { return next(e) } res.status(201).send(clientCreated) }) app.put('/', async (req, res, next) => { debug(chalk.cyan('Request to update client')) let messageSuccess const client = req.body try { await Client.update(client) messageSuccess = `User [${client.name}] updated successfull` } catch (error) { return next(error) } res.status(200).send(messageSuccess) }) app.delete('/:id', async (req, res, next) => { debug(chalk.cyan('Request to delete Client')) let messageSuccess const clientId = req.params.id try { await Client.inactive(clientId) messageSuccess = 'Client deleted successfull' } catch (error) { return next(error) } res.status(200).send(messageSuccess) }) return app }
console.log("===================>>> script_6.js <<<===================") const entrepreneurs = [ { first: 'Steve', last: 'Jobs', year: 1955 }, { first: 'Bill', last: 'Gates', year: 1955 }, { first: 'Mark', last: 'Zuckerberg', year: 1984 }, { first: 'Jeff', last: 'Bezos', year: 1964 }, { first: 'Elon', last: 'Musk', year: 1971 }, { first: 'Larry', last: 'Page', year: 1973 }, { first: 'Jack', last: 'Dorsey', year: 1976 }, { first: 'Evan', last: 'Spiegel', year: 1990 }, { first: 'Brian', last: 'Chesky', year: 1981 }, { first: 'Travis', last: 'Kalanick', year: 1976 }, { first: 'Marc', last: 'Andreessen', year: 1971 }, { first: 'Peter', last: 'Thiel', year: 1967 } ]; let entrepreneursNew = entrepreneurs; function bornInTheUsa(entrepreneursNew) { let bornInThe70s = []; entrepreneursNew.forEach(entrepreneur => { if (entrepreneur['year'] >= 1970 && entrepreneur['year'] <= 1979){ bornInThe70s.push(entrepreneur); }; }); console.log("Né dans les 70's :"); console.log(bornInThe70s); }; bornInTheUsa(entrepreneursNew); function entrepreneursName(entrepreneursNew){ let name = []; entrepreneursNew.forEach(entrepreneur => { let tempName = []; tempName.push(entrepreneur['first']); tempName.push(entrepreneur['last']); tempName = tempName.join(" ") name.push(tempName); }); console.log("Noms et prénoms :"); console.log(name); }; entrepreneursName(entrepreneursNew); function entrepreneursAge(entrepreneursNew){ entrepreneursNew.forEach(entrepreneur => { let currentAge = 0; currentAge = 2019 - entrepreneur['year']; console.log(`${entrepreneur['first']} ${entrepreneur['last']} aurait eu ${currentAge} ans aujourd'hui`); }); }; entrepreneursAge(entrepreneursNew); // function entrepreneurLast(entrepreneursNew){ // let entrepreneurSort = entrepreneursNew; // entrepreneurSort.sort(function(a, b){ // return a['last'] - b["last"]; // }); // console.log(entrepreneurSort); // }; function entrepreneurSortByLast(entrepreneursNew){ let lastName = [], entrepreneurSorted = []; entrepreneursNew.forEach(entrepreneur => { lastName.push(entrepreneur['last']); }); lastName.sort(); lastName.forEach(name => { entrepreneursNew.forEach(entrepreneur => { if (name === entrepreneur['last']){ entrepreneurSorted.push(entrepreneur); }; }); }); console.log("Les entrepreneurs par ordre alphabétique :"); console.log(entrepreneurSorted); }; entrepreneurSortByLast(entrepreneursNew);
"use strict"; const mods = [ "shellfish/mid", "shellfish/high", "shell/mime-registry" ]; require(mods, function (mid, high, mimeReg) { var VC_PROPERTIES = ["SOURCE", "KIND", "FN", "N", "NICKNAME", "PHOTO", "BDAY", "ANNIVERSARY", "GENDER", "ADR", "TEL", "EMAIL", "IMPP", "LANG", "TZ", "GEO", "TITLE", "ROLE", "LOGO", "ORG", "MEMBER", "RELATED", "CATEGORIES", "NOTE", "PRODID", "REV", "SOUND", "UID", "CLIENTPIDMAP", "URL", "KEY", "FBURL", "CALADRURI", "CALURI", "XML"]; function viewVCard(href) { var amount = high.binding(0); var parts = href.split("/"); var name = decodeURI(parts[parts.length - 1]); var page = high.element(mid.Page); page .onClosed(page.discard) .onSwipeBack(function () { page.pop_(); }) .header( high.element(mid.PageHeader) .title(name) .subtitle(high.predicate([amount], function () { return amount.value() + " contacts"; })) .left( high.element(mid.Button).icon("arrow_back") .onClicked(function () { page.pop_(); }) ) ) .add( high.element(mid.ListView).id("listview") ); page.push_(); loadVCard(page.find("listview"), amount, href); } function loadVCard(listView, amountBinding, href) { var busyIndicator = high.element(mid.BusyPopup).text("Loading"); busyIndicator.show_(); $.ajax(href, { beforeSend: function (xhr) { xhr.overrideMimeType("text/vcard"); } }) .done(function (data, status, xhr) { var coll = new VCardCollection(data); var cards = coll.cards(); for (var i = 0; i < cards.length; ++i) { var card = cards[i]; var fn = card.prefOf("FN"); var org = card.prefOf("ORG"); var tel = card.prefOf("TEL"); var mail = card.prefOf("EMAIL"); var photo = card.prefOf("PHOTO"); var title = fn.value() + (org ? " (" + org.value().replace(";", " ") + ")" : ""); var subTitle = (tel ? "Phone: " + tel.value() + " " : "") + (mail ? "e-Mail: " + mail.value() + " " : ""); listView.add( high.element(mid.ListItem).title(title).subtitle(subTitle) ); if (photo) { listView.child(-1) .icon("data:image/jpeg;base64," + photo.value()) .fillMode("cover"); } else { listView.child(-1) .icon("/::res/icons/face.png") .fillMode("auto"); } } amountBinding.assign(cards.length); }) .complete(function () { busyIndicator.hide_(); }); } function VCProperty(group, name, parameters, value) { var that = this; var m_group = group; var m_name = name; var m_parameters = parameters; var m_value = value; that.group = function () { return m_group; } that.name = function () { return m_name; } that.value = function () { return m_value; } } function VCard() { var that = this; var m_properties = []; that.add = function (group, name, parameters, values) { name = name.toUpperCase(); for (var i = 0; i < values.length; ++i) { m_properties.push(new VCProperty(group, name, parameters, values[i])); } console.log("Add: " + name); for (i = 0; i < parameters.length; ++i) { console.log(" - parameter: " + parameters[i]); } for (i = 0; i < values.length; ++i) { console.log(" - value: " + values[i]); } }; that.properties = function () { m_properties.sort(function (a, b) { if (a.group() !== "" && b.group() === "") { return -1; } else if (a.group() === "" && b.group() !== "") { return 1; } else if (a.group() === b.group()) { return VC_PROPERTIES.indexOf(a.name()) - VC_PROPERTIES.indexOf(b.name()); } else { return a.group() < b.group() ? -1 : 1; } }); return m_properties; }; that.allOf = function (name) { var result = []; var props = that.properties(); for (var i = 0; i < props.length; ++i) { if (props[i].name() === name) { result.push(props[i]); } } return result; }; that.prefOf = function (name) { return that.allOf(name)[0]; }; } function VCardCollection(data) { var that = this; var m_vcards = []; that.cards = function () { return m_vcards; } function skipWhitespace(data, pos) { while (pos.value < data.length && '\t\n\r\v '.indexOf(data[pos.value]) !== -1) { ++pos.value; } } function next(data, pos, what) { return data.substr(pos.value, what.length) === what; } function expect(data, pos, what) { if (data.substr(pos.value, what.length) === what) { pos.value += what.length; } else { throw "Parse error @" + pos.value + ": '" + what + "' expected."; } } function readUntil(data, pos, chars) { var s = ""; while (pos.value < data.length && chars.indexOf(data[pos.value]) === -1) { s += data[pos.value]; ++pos.value; } return s; } function readUntilNewline(data, pos) { var s = readUntil(data, pos, "\r\n"); if (pos.value < data.length && data[pos.value] === "\r") { expect(data, pos, "\r"); expect(data, pos, "\n"); } else if (pos.value < data.length && data[pos.value] === "\n") { expect(data, pos, "\n"); } return s; } function readString(data, pos) { if (pos.value >= data.length) { return ""; } var delimiter = ""; if (data[pos.value] === "'") { delimiter = "'"; ++pos.value; } else if (data[pos.value] === "\"") { delimiter = "\""; ++pos.value; } var result = ""; while (pos.value < data.length) { if (delimiter !== "" && data[pos.value] === delimiter) { ++pos.value; break; } else if (delimiter === "" && '\t\n\r\v '.indexOf(data[pos.value]) !== -1) { break; } else if (data[pos.value] === "\\") { } else { result += data[pos.value]; } ++pos.value; } return result; } function parseVCards(data) { var pos = { "value": 0 }; skipWhitespace(data, pos); while (pos.value < data.length) { parseVCard(data, pos); skipWhitespace(data, pos); } } function parseVCard(data, pos) { var vcard = new VCard(); expect(data, pos, "BEGIN:VCARD"); skipWhitespace(data, pos); expect(data, pos, "VERSION:"); var version = readString(data, pos); console.log("VCard Version: " + version); while (pos.value < data.length) { skipWhitespace(data, pos); if (next(data, pos, "END:VCARD")) { break; } else { parseEntry(data, pos, vcard); } } expect(data, pos, "END:VCARD"); m_vcards.push(vcard); } function parseEntry(data, pos, vcard) { var prop = parseProperty(data, pos); expect(data, pos, ":"); var values = parseValues(data, pos); expect(data, pos, "\r\n"); vcard.add(prop.group, prop.name, prop.parameters, values); } function parseProperty(data, pos) { var group = ""; var parts = []; while (pos.value < data.length) { var s = readUntil(data, pos, ".;:"); if (next(data, pos, ".")) { group = s; s = ""; expect(data, pos, "."); } else if (next(data, pos, ";")) { parts.push(s); s = ""; expect(data, pos, ";"); } else if (next(data, pos, ":")) { parts.push(s); break; } } var name = parts[0]; var parameters = []; for (var i = 1; i < parts.length; ++i) { parameters.push(parts[i]); } return { "group": group, "name": name, "parameters": parameters }; } function parseValues(data, pos) { var values = []; var s = ""; while (pos.value < data.length) { s += readUntil(data, pos, "\\,\r"); if (next(data, pos, "\\")) { expect(data, pos, "\\"); if (next(data, pos, "n")) { expect(data, pos, "n"); s += "\n"; } else if (next(data, pos, "N")) { expect(data, pos, "N"); s += "\n"; } } else if (next(data, pos, ",")) { expect(data, pos, ","); values.push(s); s = ""; } else if (next(data, pos, "\r")) { values.push(s); break; } } return values; } console.log("Parsing VCards"); try { parseVCards(data.replace(/\r\n /g, "").replace(/\r\n\t/g, "")); } catch (err) { console.error(err); } } mimeReg.mimeRegistry.register("text/vcard", viewVCard); });
/** * @ngdoc service * @name navigationService * @module app * @description A service which holds the navigation items present in the application. */ (function (angular) { angular.module('app') .factory('navigationService', function () { return { navItems: [ { title: 'Daily Energy generation from Solar Panel PV arrays', icon: 'battery_charging_full', color: '#4CAF50', sref: 'daily_energy' }, { title: 'Home Office Flight Data', icon: 'flight_takeoff', color: '#00BCD4', sref: 'flight_data' }, { title: 'Council Spending Over £500', icon: 'account_balance', color: '#FF9800', sref: 'council_spending' } ] } }) })(angular);
const mongoose = require("mongoose"); const redis = require("redis"); const util = require("util"); const keys = require("../config/keys"); const client = redis.createClient({ host: keys.redisHost, port: keys.redisPort, retry_strategy: () => 1000 }); client.get = util.promisify(client.get); const exec = mongoose.Query.prototype.exec; mongoose.Query.prototype.exec = async function() { const key = JSON.stringify({ ...this.getQuery() }); const cacheValue = await client.get(key); if (cacheValue) { const doc = JSON.parse(cacheValue); console.log("Response from Redis"); return Array.isArray(doc) ? doc.map(d => new this.model(d)) : new this.model(doc); } const result = await exec.apply(this, arguments); client.set(key, JSON.stringify(result)); console.log("Response from MongoDB"); return result; };
// pages/product/product.js const requestUrl = 'https://gwserv.ddsoucai.com/ddsc-app/app/resource' Page({ /** * 页面的初始数据 */ data: { loading: false, RECOMMEND_HEADER: [], RECOMMEND_ACTIVITY: [], APP_HOME_BOTTOM: [], RECOMMEND_BANNER: [], RECOMMEND_NOTICE: [] }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { const self = this wx.showToast({ title: '加载中...', icon: 'loading' }) wx.request({ url: requestUrl, data: { keys: "RECOMMEND_NOTICE;RECOMMEND_ACTIVITY;RECOMMEND_BANNER;RECOMMEND_HEADER;APP_HOME_BOTTOM" }, success(result) { wx.hideToast() self.setData({ loading: false, RECOMMEND_HEADER: result.data.result.RECOMMEND_HEADER, RECOMMEND_ACTIVITY: result.data.result.RECOMMEND_ACTIVITY, APP_HOME_BOTTOM: result.data.result.APP_HOME_BOTTOM, RECOMMEND_BANNER: result.data.result.RECOMMEND_BANNER, RECOMMEND_NOTICE: result.data.result.RECOMMEND_NOTICE }) console.log('request success', result.data) }, fail({ errMsg }) { console.log('request fail', errMsg) self.setData({ loading: false }) } }) }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () { }, /** * 生命周期函数--监听页面显示 */ onShow: function () { }, /** * 生命周期函数--监听页面隐藏 */ onHide: function () { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function () { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { }, /** * 用户点击右上角分享 */ onShareAppMessage: function () { }, startRequest(){ const self = this self.setData({ loading: true }) wx.request({ url: requestUrl, data: { keys: "RECOMMEND_NOTICE;RECOMMEND_ACTIVITY;RECOMMEND_BANNER;RECOMMEND_HEADER;APP_HOME_BOTTOM" }, success(result) { wx.showToast({ title: "请求成功", icon: 'success', mask: true, duration: 3000, }) self.setData({ loading: false, RECOMMEND_HEADER: result.data.result.RECOMMEND_HEADER, RECOMMEND_ACTIVITY: result.data.result.RECOMMEND_ACTIVITY, APP_HOME_BOTTOM: result.data.result.APP_HOME_BOTTOM, RECOMMEND_BANNER: result.data.result.RECOMMEND_BANNER, RECOMMEND_NOTICE: result.data.result.RECOMMEND_NOTICE }) console.log('request success', result.data) }, fail({ errMsg }) { console.log('request fail', errMsg) self.setData({ loading: false }) } }) } })
// function PopIt() { // var popover = document.getElementById('popover'); // popover.style.display = 'block'; // return "Are you sure you want to leave?"; // } function UnPopIt() {} $(document).ready(function() { //window.onbeforeunload = PopIt; //$("input[type=submit] , a").click(function(){ window.onbeforeunload = UnPopIt; }); $.exitpop({ predict_amt: 0.02, fps: 1000, popCount: 1, tolerance: {x: 10, y: 10}, cta: "#form", callback: function() { $('#popover').fadeIn(); $('#pop-box').css({ 'top' : 0, 'opacity' : 1 }) } }); }); var spd = 100; var spdVal = 10; var cntDown = 5 * 60 * spdVal; setInterval(function () { var mn, sc, ms; cntDown--; if(cntDown < 0) { return false; } mn = Math.floor((cntDown / spdVal) / 60 ); mn = (mn < 10 ? '0' + mn : mn); sc = Math.floor((cntDown / spdVal) % 60); sc = (sc < 10 ? '0' + sc : sc); ms = Math.floor(cntDown % spdVal); ms = (ms < 10 ? '0' + ms : ms); var result = mn + ':' + sc ; try{ document.getElementById('stopwatch').innerHTML = result; }catch(e){ } }, spd); $(window).on('load', function(){ $('#reminder').delay(3350).animate({ 'bottom': -14 }); $('#reminder p').delay(3800).animate({ 'opacity': 1 }); });
function favImage (img) { var favorites = document.getElementById("favArea"); favorites.appendChild(img); var list = document.getElementById("bulletText"); var listElem = document.createElement("li"); var listItem = document.createTextNode(`Moved ${String(img.alt)} to favorites.`); listElem.appendChild(listItem); list.appendChild(listElem); img.onclick = false; }
export const globalReducer = (state, action) =>{ const { type, payload } = action; switch(type){ case 'ADD_TRANSACTION': console.log(payload); return{ ...state, transactions: [payload, ...state.transactions] } case 'REMOVE_TRANSACTION': return { ...state, transactions: state.transactions.filter(({id})=>{ return id !== payload }) } default: return state; } }
require('./TriviaChoice.styl'); import React, { PropTypes, Component } from 'react'; import { connect } from 'react-redux'; import { TriviasActions } from '../../actions/'; import { spring, Motion } from 'react-motion'; import { fastEaseOut, fastEaseOutElastic } from '../../constants/SpringPresets'; class TriviaChoice extends Component { static displayName = 'TriviaChoice'; static propTypes = { dispatch: PropTypes.func, id: PropTypes.string, triviaId: PropTypes.string.isRequired, choiceData: PropTypes.object.isRequired, active: PropTypes.bool.isRequired, }; constructor(props) { super(props); this.state = { isPressed: false, }; } handleEnd() { const { triviaId, id, active, dispatch } = this.props; if (active === true) { dispatch(TriviasActions.voteFor(triviaId, id)); } else { console.log('>>> Already voted!'); } } handleTouchStart() { this.setState({ isPressed: true }); } handleTouchEnd() { this.setState({ isPressed: false }, ::this.handleEnd); } render() { const { isPressed } = this.state; const { active, choiceData } = this.props; const { title, votes, assets } = choiceData; const buttonStyle = isPressed ? { scale: spring(1.1, fastEaseOutElastic) } : { scale: spring(1, fastEaseOutElastic) }; const votesStyle = active ? { hScale: spring(2, fastEaseOut), opacity: spring(0, fastEaseOut) } : { hScale: spring(1, fastEaseOut), opacity: spring(1, fastEaseOut) }; return ( <div className="ncss-col-sm-6 u-align-center avatar pl1-sm choice-col"> <Motion style={buttonStyle}> {({ scale }) => <div className="trivia-choice ncss-brand h1 u-va-m z0" onTouchStart={::this.handleTouchStart} onTouchEnd={::this.handleTouchEnd} style={{ transform: `translate3d(0, 0, 0) scale(${scale})`, WebkitTransform: `translate3d(0, 0, 0) scale(${scale})`, backgroundImage: `url('${assets.image}')`, }} > <Motion style={votesStyle}> {({ opacity, hScale }) => <div className="votes-number-wrapper" style={{ backgroundColor: `rgba(255, 255, 255, ${opacity / 2})` }} > <div className="votes-number ncss-brand u-align-center z9" style={{ opacity }} > <h1 style={{ transform: `translate3d(0, 0, 0) scale(${hScale})`, WebkitTransform: `translate3d(0, 0, 0) scale(${hScale})`, }} > {votes} </h1> </div> </div> } </Motion> </div> } </Motion> <div className="ncss-brand h3 text-color-dark-grey">{title}</div> </div> ); } } export default connect()(TriviaChoice);
(function() { 'use strict'; angular .module('bq') .directive('a', function(notify, dataService, $ionicPopup) { return { restrict: 'E', link: function(scope, elem, attrs) { //if (attrs.ngClick || attrs.href === '' || attrs.href === '#') { if (attrs.href && attrs.href.match(/(\d+) (\d+):(\d+)/)) elem.on('click', function(e) { e.preventDefault(); var parse = attrs.href.match(/(\d+) (\d+):(\d+)/); var bookId = parse[1], chapterId = parse[2], verseId = parse[3]; dataService.defaultModule.loadVerse(bookId, chapterId, verseId).then(function(verse) { var title = attrs.href; if (dataService.defaultModule.hasOwnProperty('books') && dataService.defaultModule.books.hasOwnProperty(bookId)) { title = dataService.defaultModule.books[bookId].long_name + ' ' + chapterId + ': ' + verseId; } $ionicPopup.alert({ template: verse, title: title, cssClass: 'modal-verse', buttons: [{ text: 'OK', type: 'button-positive' }] }); }); }); //} } }; }); })();
var originalText = ""; function storeOriginal() { originalText = document.forms["textAwesome"]["input"].value; } function getFonts(){ var fonts = ['Arial', 'Batang', 'Cursive', 'Courier', 'Monospace', 'Symbol','Times New Roman', 'Verdana']; var begin = '<option value=\"'; var middle = '\">'; var end = '</option>'; var options = ""; for(var i = 0; i < fonts.length; i++){ options += begin + fonts[i] + middle + fonts[i] + end; } document.getElementById("font").innerHTML = options; } function setTransparent(){ var textResult= $("#textResult"); var trans = document.forms["textAwesome"]["transparent"].value; textResult.css("opacity", trans/100); } function wordWrap(){ var textResult= $("#textResult"); var transform = document.forms["textAwesome"]["wrap"].value; textResult.css("word-wrap", document.forms["textAwesome"]["wrap"].checked? transform: "initial"); } function setText(){ var textToAwesome = document.forms["textAwesome"]["input"].value; document.getElementById("textResult").innerHTML = textToAwesome; } function setSize(){ var textResult= $("#textResult"); var size = document.forms["textAwesome"]["textSize"].value; textResult.css("font-size", size + "px"); } function setColor(){ var textResult= $("#textResult"); var textColor = document.forms["textAwesome"]["color"].value; textResult.css("color", textColor); } function setBgColor(){ var textResult= $("#product"); var textColor = document.forms["textAwesome"]["bgcolor"].value; textResult.css("background-color", textColor); } function randomColor(){ var textResult= $("#textResult"); var textColor = Math.round(0xffffff*Math.random()); textColor = "#" + textColor.toString(16); textResult.css("color", textColor); return false; } function randomSize(){ var textResult= $("#textResult"); var textSize = Math.round(492 * Math.random())+ 8; textResult.css("font-size", textSize + "px"); return false; } function setFont(){ var textResult= $("#textResult"); var font = document.forms["textAwesome"]["font"].value; textResult.css("font-family", font); } function setCapitalization(){ var textToAwesome = document.forms["textAwesome"]["input"].value; var capitalization = document.forms["textAwesome"]["capitalization"].value; var newText = ""; if(capitalization === "uppercase"){ newText = textToAwesome.toUpperCase(); }else if(capitalization === "lowercase"){ newText = textToAwesome.toLowerCase(); }else if(capitalization === "RaNDom"){ for (var index = 0; index < textToAwesome.length; index++) { var capitalize = Math.random() < .5; if(capitalize) newText += textToAwesome.charAt(index).toUpperCase(); else newText += textToAwesome.charAt(index).toLowerCase(); } }else{ newText = originalText; } $("input").val(newText); setText(); } function setShadow(){ var textResult= $("#textResult"); var shadow = document.forms["textAwesome"]["shadow"].value + "px "; textResult.css("text-shadow", shadow + shadow + "#000"); textResult.css("opacity", .7); } function setTextDeco(textType, id){ var textResult= $("#textResult"); var transform = document.forms["textAwesome"][id].value; textResult.css(textType, document.forms["textAwesome"][id].checked? transform: "initial"); } function setLineThrough(){ var textResult= $("#textResult"); var textToAwesome = document.forms["textAwesome"]["input"].value; var strike = document.forms["textAwesome"]["line-through"].value; var open = document.forms["textAwesome"]["line-through"].checked? "<strike>": ""; var close = document.forms["textAwesome"]["line-through"].checked? "</strike>": ""; document.getElementById("textResult").innerHTML = open + textToAwesome + close; }
// The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import App from './App' import router from './router' //配置mint-ui import MintUI from 'mint-ui' import 'mint-ui/lib/style.css' Vue.use(MintUI) import Axios from 'axios' //配置公共URL Axios.defaults.baseURL = "https://www.sinya.online/api" Vue.prototype.$axios = Axios //配置请求拦截器,显示loading图标 Axios.interceptors.request.use((config)=>{ MintUI.Indicator.open({ text: '拼命加载中', spinnerType: 'fading-circle' }); return config }); //配置响应拦截器,关闭loading图标 Axios.interceptors.response.use((response)=>{ //response.config类似上面 config MintUI.Indicator.close(); return response }); // 引入自己css import './assets/css/global.css' Vue.config.productionTip = false //引入自己的ul和li组件,并注册全局组件 import MyUi from "@/components/common/MyUi"; import MyLi from "@/components/common/MyLi"; Vue.component(MyUi.name,MyUi); Vue.component(MyLi.name,MyLi); import NavBar from "@/components/common/NavBar"; Vue.component(NavBar.name,NavBar) // 图片预览插件 import VuePreview from 'vue-preview' // defalut install Vue.use(VuePreview); //评论组件 import Comment from "@/components/common/Comment" Vue.component(Comment.name,Comment); //注册全局轮播组件 import MySwipe from "@/components/common/MySwipe" Vue.component(MySwipe.name,MySwipe) //全局组件结束 //定义moment全局日期过滤器 {{'xxx' | convertTime('yyyy-mm-dd')}} import Moment from "moment" Moment.locale('zh-cn'); //绝对时间 Vue.filter("convertTime",function (data, formatStr) { // console.log("data",data); // console.log(formatStr); return Moment(data).format(formatStr) }); //相对时间 Vue.filter("relativeTime",function (data, previousTime) { // console.log("data",data); // console.log(formatStr); return Moment(previousTime).fromNow(); }); //处理字符串过长的过滤器 Vue.filter('convertStr',function (str, count) { return str.substring(0,count) + '...' }); /* eslint-disable no-new */ new Vue({ el: '#app', router, components: { App }, template: '<App/>' })
import React from "react"; //CSS import "./Section3.css"; //Images import IllustrationLaptop from "../../../assets/images/illustration-laptop-mobile.svg"; const Section3 = () => { return ( <section className="section section3"> <div className="content-wrapper"> <img className="img-illustrationLaptop" src={IllustrationLaptop} alt="illustration laptop" /> <div className="text-block text-block-s3"> <h3>Free, open, simple</h3> <p> Blogr is a free and open source application backed by a large community of helpful developers. It supports features such as code syntax highlighting. RSS feeds, social media integration, third-party commenting tools, and works seamlessly with Google Analytics. The architecture is clean and is relatively easy to learn. </p> <h3>Powerful tooling</h3> <p> Batteries included. We built a simple and straightforward CLI tool that makes customization and deployment a breeze, but capable of producing even the most complicated sites. </p> </div> </div> </section> ); }; export default Section3;
// pages/register/bindVip.js const app = getApp(); const config = require("../../../utils/config.js"); const util = require("../../../utils/util.js"); const registerService = require("../../../service/registerService.js"); const intervalDuration = 60; Page({ /** * 页面的初始数据 */ data: { height: null, intervalID: null, // 定时器Id getCodeTitle: "获取验证码", // 获取验证码标题 ableGetCode: true, // 是否允许获得验证码 intervalCount: intervalDuration, // 倒计时 phone: null, // 手机号 code: null, // 验证码 tempCookie: null, // 临时cookie存储 // card: null, // 会员卡 }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { this.setData({ height: app.globalData.pageHeight }) }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () { }, /** * 生命周期函数--监听页面显示 */ onShow: function () { }, /** * 生命周期函数--监听页面隐藏 */ onHide: function () { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function () { clearInterval(this.data.intervalID); this.data.intervalID = null; }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { }, /** * 用户点击右上角分享 */ onShareAppMessage: function () { }, /** * 电话输入 */ inputPhone: function (e) { this.setData({ phone: e.detail.value }) }, /** * 短信验证码输入 */ inputCode: function (e) { this.setData({ code: e.detail.value }) }, /** * 会员卡输入 */ // inputCard: function (e) { // this.setData({ // card: e.detail.value // }) // }, /** * 获取验证码 */ getCode: function () { if (this.data.ableGetCode){ if (util.checkIsEmpty(this.data.phone) || !util.isPhoneAvailable(this.data.phone)) { wx.showToast({ title: '请输入正确手机号码!', icon: 'none', }) return; } console.log("开始倒计时"); this.interval(); let that = this; registerService.getSMSCode(this.data.phone, function successCallback(cookie){ that.setData({ tempCookie: cookie }) }) } console.log("正在倒计时"); }, /** * 倒计时 */ interval: function(e) { let that = this; clearInterval(this.data.intervalID); this.data.intervalID = setInterval(function () { let tempCount = that.data.intervalCount; tempCount--; if (tempCount > 0) { that.setData({ getCodeTitle: tempCount + '秒后获取', intervalCount: tempCount, ableGetCode: false }) console.log("倒计时===> " +tempCount); that.interval(); } else { that.setData({ getCodeTitle: "获取验证码", intervalCount: intervalDuration, ableGetCode: true }) console.log("倒计时结束"); clearInterval(that.data.intervalID); that.data.intervalID = null; } }, 1000); }, /** * 点击绑定 */ tapBind: function () { let that = this; registerService.queryUserWithPhone(this.data.phone,this.data.code,this.data.tempCookie, function querySuccessCallback(data){ console.log(JSON.stringify(data)); wx.navigateTo({ url: config.Page_Register_BindSelector + '?accounts=' + JSON.stringify(data) + '&cookie=' + that.data.tempCookie + '&code=' + that.data.code, }) } ) }, /** * 点击协议 */ tapAgreement: function () { }, })
var Util = require('../util'); var Base = require('../base'); var clsPrefix; var containerCls; var loadingContent = "Loading..."; var upContent = "Pull Up To Refresh"; var downContent = "Release To Refresh"; var PULL_UP_HEIGHT = 60; var HEIGHT = 40; /** * A pullup to load plugin for xscroll. * @constructor * @param {object} cfg * @param {number} cfg.height * @param {string} cfg.downContent * @param {string} cfg.upContent * @param {string} cfg.loadingContent * @param {string} cfg.clsPrefix class prefix which default value is "xs-plugin-pullup-" * @param {number} cfg.bufferHeight preload data before scrolling to the bottom of the boundry * @extends {Base} */ var PullUp = function(cfg) { PullUp.superclass.constructor.call(this); this.userConfig = Util.mix({ upContent: upContent, downContent: downContent, pullUpHeight: PULL_UP_HEIGHT, height: HEIGHT, loadingContent: loadingContent, bufferHeight:0, clsPrefix: "xs-plugin-pullup-" }, cfg); } Util.extend(PullUp, Base, { /** * a pluginId * @memberOf PullUp * @type {string} */ pluginId: "pullup", /** * plugin initializer * @memberOf PullUp * @override Base * @return {PullUp} */ pluginInitializer: function(xscroll) { var self = this; self.xscroll = xscroll.render(); clsPrefix = self.userConfig.clsPrefix; self.render(); return self; }, /** * detroy the plugin * @memberOf PullUp * @override Base * @return {PullUp} */ pluginDestructor: function() { var self = this; self.pullup && self.pullup.remove(); self.xscroll.off("scrollend", self._scrollEndHandler, self); self.xscroll.off("scroll", self._scrollHandler, self); self.xscroll.off("pan", self._panHandler, self); self.xscroll.boundry.resetBottom(); self.__isRender = false; self._evtBinded = false; delete self; }, /** * render pullup plugin * @memberOf PullUp * @return {PullUp} */ render: function() { var self = this; if (self.__isRender) return; self.__isRender = true; var containerCls = clsPrefix + "container"; var height = self.userConfig.height; var pullup = self.pullup = document.createElement("div"); pullup.className = containerCls; pullup.style.position = "absolute"; pullup.style.width = "100%"; pullup.style.height = height + "px"; pullup.style.bottom = -height + "px"; self.xscroll.container.appendChild(pullup); self.xscroll.boundry.expandBottom(self.userConfig.height); self.status = 'up'; Util.addClass(pullup, clsPrefix + self.status); pullup.innerHTML = self.userConfig[self.status + "Content"] || self.userConfig.content; self._bindEvt(); return self; }, _bindEvt: function() { var self = this; if (self._evtBinded) return; self._evtBinded = true; var pullup = self.pullup; var xscroll = self.xscroll; xscroll.on("pan", self._panHandler, self); //load width a buffer if (self.userConfig.bufferHeight > 0) { xscroll.on("scroll", self._scrollHandler, self); } //bounce bottom xscroll.on("scrollend", self._scrollEndHandler, self); return self; }, _scrollEndHandler: function(e) { var self = this, xscroll = self.xscroll; if (e.scrollTop == xscroll.containerHeight - xscroll.height + self.userConfig.height) { self._changeStatus("loading"); } return self; }, _scrollHandler: function(e) { var self = this, xscroll = self.xscroll; if (!self.isLoading && Math.abs(e.scrollTop) + xscroll.height + self.userConfig.height + self.userConfig.bufferHeight >= xscroll.containerHeight + xscroll.boundry._xtop + xscroll.boundry._xbottom) { self._changeStatus("loading"); } return self; }, _panHandler: function(e) { var self = this; var xscroll = self.xscroll; var offsetTop = -xscroll.getScrollTop(); if (offsetTop < xscroll.height - xscroll.containerHeight - self.userConfig.pullUpHeight) { self._changeStatus("down") } else { self._changeStatus("up"); } return self; }, _changeStatus: function(status) { if (status != "loading" && this.isLoading) return; var prevVal = this.status; this.status = status; Util.removeClass(this.pullup, clsPrefix + prevVal) Util.addClass(this.pullup, clsPrefix + status); this.pullup.innerHTML = this.userConfig[status + "Content"]; if (prevVal != status) { this.trigger("statuschange", { prevVal: prevVal, newVal: status }); if (status == "loading") { this.isLoading = true; this.trigger("loading"); } } return this; }, /** * notify pullup plugin to complete state after a remote data request * @memberOf PullUp * @return {PullUp} */ complete: function() { var self = this; var xscroll = self.xscroll; self.isLoading = false; self._changeStatus("up"); return self; } }); if (typeof module == 'object' && module.exports) { module.exports = PullUp; }else if(window.XScroll && window.XScroll.Plugins){ return XScroll.Plugins.PullUp = PullUp; }
export default function PersonalDetails(props) { const { user, nextStep, handleChange } = props; const handleNext = (e) => { e.preventDefault(); nextStep(); }; return ( <div className="w-full flex justify-center items-center"> <form> <div className="lg:grid grid-cols-2 lg:space-x-3"> <div> <input name="name" value={user.name} placeholder="Name" required onChange={handleChange} className="md:w-96 h-4 p-4 rounded mb-3 focus:outline-none focus:ring focus:ring-green-200" /> </div> <div> <input name="email" value={user.email} placeholder="Email" required onChange={handleChange} className="md:w-96 h-4 p-4 rounded mb-3 focus:outline-none focus:ring focus:ring-green-200" /> </div> </div> <div className="flex justify-center"> <button onClick={handleNext} className="w-full lg:w-[50%] hover:bg-green-700 px-3 py-1 text-center rounded text-white bg-green-500"> Next </button> </div> </form> </div> ); }
import React from "react"; import Users from "./users"; const DashboardProfile = () => ( <div className="container"> <div> <i className="fas fa-user-circle" /> <p>@no_name</p> </div> <table> <thead> <tr> <th>Tweets</th> <th>Following</th> <th>Followers</th> </tr> </thead> <tbody> <tr> <td>92</td> <td>80</td> <td>75</td> </tr> </tbody> </table> <Users /> <style jsx>{` .container { width: 25%; height: 200px; } `}</style> </div> ); export default DashboardProfile;
/*global beforeEach, afterEach, expect*/ 'use strict'; const path = require('path'); const sinon = require('sinon'); const AliyunProvider = require('../../provider/aliyunProvider'); const AliyunPackage = require('../aliyunPackage'); const Serverless = require('../../test/serverless'); describe('WriteFilesToDisk', () => { let serverless; let aliyunPackage; let writeFileSyncStub; beforeEach(() => { serverless = new Serverless(); serverless.service.package = {}; serverless.service.service = 'my-service'; serverless.service.provider = { compiledConfigurationTemplate: { foo: 'bar', }, }; serverless.config = { servicePath: 'foo/my-service', }; const options = { stage: 'dev', region: 'cn-shanghai', }; serverless.setProvider('aliyun', new AliyunProvider(serverless, options)); aliyunPackage = new AliyunPackage(serverless, options); writeFileSyncStub = sinon.stub(aliyunPackage.serverless.utils, 'writeFileSync'); }); afterEach(() => { aliyunPackage.serverless.utils.writeFileSync.restore(); }); describe('#saveCreateTemplateFile()', () => { it('should write the template file into the services .serverless directory', () => { const createFilePath = path.join( aliyunPackage.serverless.config.servicePath, '.serverless', 'configuration-template-create.json' ); aliyunPackage.saveCreateTemplateFile(); expect(writeFileSyncStub.calledWithExactly( createFilePath, aliyunPackage.serverless.service.provider.compiledConfigurationTemplate )).toEqual(true); }); }); describe('#saveUpdateTemplateFile()', () => { it('should write the template file into the services .serverless directory', () => { const updateFilePath = path.join( aliyunPackage.serverless.config.servicePath, '.serverless', 'configuration-template-update.json' ); aliyunPackage.saveUpdateTemplateFile(); expect(writeFileSyncStub.calledWithExactly( updateFilePath, aliyunPackage.serverless.service.provider.compiledConfigurationTemplate )).toEqual(true); }); }); });
import React from 'react'; import './index.css'; import { Typography } from 'antd'; const { Title } = Typography; class ShowImages extends React.Component { shouldComponentUpdate(newprops){ if (this.props.data===newprops.data){ return false; } return true; } render() { let data = []; let style = {}; let title = ''; let discription = ''; let textAlign = 'center'; if (this.props.data && this.props.data.cpdata){ data = this.props.data.cpdata.path || []; style = this.props.data.cpdata.style || {}; if (style.justify === 'flex-start') textAlign = 'left'; if (style.justify === 'flex-end') textAlign = 'right'; title = this.props.data.cpdata.title || ''; discription = this.props.data.cpdata.discription || ''; } return ( <div> { title && <Title level={5} style={{textAlign}}>{title}</Title> } <div className='images-show-box' style={{justifyContent:style.justify||'space-around'}} > { data.map((value, index) => { return ( <img src={value} key={index} width={style.width||''} style={{borderRadius:style.radius+'px'||'', maxWidth:'100%'}} /> ) }) } </div> { discription && <p className='images-show-footer' style={{textAlign}}>{discription}</p> } </div> ); } } ShowImages.elementName = 'ShowImages'; export default ShowImages;
'use strict'; import tabs from './modules/tabs'; import modal from './modules/modal'; import cards from './modules/cards'; import formSender from './modules/formsender'; import calculator from './modules/calculator'; import slider from './modules/slider'; import timer from './modules/timer'; import hamburger from './modules/hamburger'; import {modalOpen} from './modules/modal'; window.addEventListener('DOMContentLoaded', () => { const modalTimer = setTimeout(() => modalOpen('.modal', modalTimer), 5000); tabs('.tabheader__item', '.tabheader__items', '.tabcontent', 'tabheader__item_active'); modal('.modal', '[data-modal]', modalTimer); cards(); formSender(modalTimer); slider({ counter: '#current', container: '.offer__slider', prev: '.offer__slider-prev', next: '.offer__slider-next', slide: '.offer__slide', wrapper: '.offer__slider-wrapper', field: '.offer__slider-inner' }); calculator(); timer('2021-05-20'); hamburger(); });
const express = require('express'); const http = require('http'); const port = process.env.PORT || 3000 || 8080; const app = express(); app.use(express.static('view')); app.use(express.static('arquivos-css')); app.use(express.static('img')); app.use(express.static('fontes')); app.use(express.static('arquivos-js')); http.createServer(app) .listen(port, () => console.log(`Servidor rodando na porta ${port}`));
// Склейка вебпак конфигураций const merge = require('webpack-merge'); const baseConfig = require('./webpack.base.conf.js'); const devConfig = require('./webpack.dev.conf.js'); const buildConfig = require('./webpack.build.conf.js'); const prodConfig = require('./webpack.prod.conf.js'); const testConfig = require('./webpack.test.conf.js'); module.exports = (env, options) => { if(process.env.NODE_ENV === 'development') { return merge(baseConfig,devConfig); } else if (process.env.NODE_ENV === 'simple_build') { return merge(baseConfig,buildConfig); } else if (process.env.NODE_ENV === 'test') { return merge(baseConfig,testConfig); } else { return merge(baseConfig,prodConfig); } }
/* David Jensen SDI Section #3 Video: Ternary Operators 2015/01/20 */ //alert("Testing to see if the JS file is attached to the HTML."); //Syntax of Ternary Operators. /* if(condition){ do if true; }else{ do if false; } (condition) ? do if true : do if false; */ /* var gpa = 48; //if the gpa is over the min 2.0 score, the student can graduate if(gpa > 2.0){ console.log("You can Graduate!"); }else{ console.log("GPA is too low!"); } (gpa > 2.0) ? console.log("You can Graduate!") : console.log("GPA is too low!"); */ var age = 11; var book; //If the child is under 10, they get Green Eggs and Ham, otherwise they get The Time machine if(age < 10){ book = "Green Eggs and Ham"; }else{ book = "The Time Machine" } console.log(book); book = (age < 10) ? "Green Eggs and Ham" : "The Time Machine"; console.log(book);
const Vendor = require('./vendor') const errorHandler = require('../common/errorHandler') Vendor.methods(['get','post','put','delete']) Vendor.updateOptions({new: true, runValidators: true}) Vendor.after('post', errorHandler).after('put', errorHandler) module.exports = Vendor
const {Schema,model} = require('mongoose'); const MarketplaceSchema = Schema({ description:{ type:String, required :true }, status:{ type: Boolean, default : true, required : true }, type:{ type:String, required : ['true','Role is required.'], enum : ['SALE','BUY'] }, user:{ type: Schema.Types.ObjectId, ref: 'User', required :true }, amount:{ type:Number, default:0 }, price:{ type:Number, default:0 }, product:{ type: Schema.Types.ObjectId, ref: 'Product', required:true }, }); MarketplaceSchema.methods.toJSON = function(){ const {__v,_id,status, ...marketplace} = this.toObject(); marketplace.uid = _id; return marketplace; } module.exports = model('Marketplace',MarketplaceSchema);
$(document).ready(function(){ $.username = $("#username_").val(); $.token = $("#token_").val(); $.ws = 'core/helpers/Request.php'; $("#logout").click(function(e){ fnLogout(); }); fnLogout = function() { $.ajax({ url: $.ws, type: 'POST', data: {action: 'logout'}, dataType: 'json', success: function(response) { console.log("logout", response); if ( response != null ) { if ( response.status == 'success' ) { location.href = "?view=login"; } else { alert(response.message); } } } }); } fnValidateToken = function() { $.ajax({ url: $.ws, type: 'POST', data: { controller: 'Usuario', action: 'validateToken' }, dataType: 'json', beforeSend: function(xhr){ xhr.setRequestHeader ("Authorization", "Basic " + btoa($.username + ":" + $.token)); }, success: function(response) { console.log("validate", response); } }); } fnValidateToken(); });
const greedyMakeChange = (n, nominals = [25, 10, 5]) => { nominals.sort((a, b) => b - a) let res = []; if (n < nominals[0]) { return "There is no such answer" } let i = 0 while (n) { if (n - nominals[i] >= 0) { n -= nominals[i] res.push(nominals[i]) } else if (n === 0) { break } else { i++ } } return res } const bruteMakeChange = (n, nominals = [10, 6, 1]) => { if (n === 0) return 0; let minNrOfCoins; let curminNrOfCoins; nominals.forEach((v, i) => { if (n - v >= 0) { curminNrOfCoins = bruteMakeChange(n - v) if (minNrOfCoins === undefined || curminNrOfCoins < minNrOfCoins) { minNrOfCoins = curminNrOfCoins } } }) return minNrOfCoins + 1 } const cache = {} const dynamicMakeChange = (n, nominals = [10, 6, 1]) => { if (cache[n] === 0) return 0; let minNrOfCoins; let curminNrOfCoins; nominals.forEach((v, i) => { if (n - v >= 0) { curminNrOfCoins = bruteMakeChange(n - v) if (minNrOfCoins === undefined || curminNrOfCoins < minNrOfCoins) { minNrOfCoins = curminNrOfCoins } } }) cache[n] = minNrOfCoins + 1 return cache[n] } // console.log(makeChange(35)); console.log(bruteMakeChange(12)); console.log(dynamicMakeChange(12));
export const BASE_URL = "https://nodeshop97.herokuapp.com/";
/** * A cache storing shared resources associated with a device. The resources are removed * from the cache when the device is destroyed. * * @ignore */ class DeviceCache { /** * Cache storing the resource for each GraphicsDevice * * @type {Map<import('./graphics-device.js').GraphicsDevice, any>} */ _cache = new Map(); /** * Returns the resources for the supplied device. * * @param {import('./graphics-device.js').GraphicsDevice} device - The graphics device. * @returns {any} The resource for the device. */ get(device, onCreate) { if (!this._cache.has(device)) { this._cache.set(device, onCreate()); // when the device is destroyed, destroy and remove its entry device.on('destroy', () => { this.remove(device); }); // when the context is lost, call optional loseContext on its entry device.on('devicelost', () => { this._cache.get(device)?.loseContext?.(device); }); } return this._cache.get(device); } /** * Destroys and removes the content of the cache associated with the device * * @param {import('./graphics-device.js').GraphicsDevice} device - The graphics device. */ remove(device) { this._cache.get(device)?.destroy?.(device); this._cache.delete(device); } } export { DeviceCache };
var https = require("https"); //print out Message function printMessage(city, temp, summary) { var message = " Current temperature for " + city + " is " + temp + " and it is " + summary; console.log(message); } //Print out Error Messages function printError(error) { console.error(error.message); } function getWeather(latitude, longitude, city) { //Connenction to the API of weather URL (http//api.forecast.io/forecast/APIKEY/LATITUDE, LONGITUDE) var apikey = your apikey; request = https.get("https://api.forecast.io/forecast/" + apikey + "/" + latitude + "," + longitude, function(response) { var body = ""; //Read data response.on('data', function(chunk){ body += chunk; }); //Parse the data response.on('end', function(){ if(response.statusCode === 200){ try{ var weatherData = JSON.parse(body); //Print the data printMessage(city, weatherData.currently.temperature, weatherData.minutely.summary); }catch(error){ //Parse Error printError({message: "There was an error parsing the forecast data - " + error}); } }else { //Status Code Error printError({message: "There was an error getting the profile for " + ". (" + http.STATUS_CODES[response.statusCOde] + ")"}); } }) //Connection Error request.on("error", printError) }); }; module.exports.get = getWeather;
import {useState} from 'react'; import './App.css'; import axios from 'axios' function App() { const [location, setLocation] = useState(''); const [date, setDate] = useState('') const [description, setDescription] = useState(''); async function handleSubmit(e){ e.preventDefault(); let latitude, longitude; await axios.get(`https://api.mapbox.com/geocoding/v5/mapbox.places/${location}.json?access_token=sk.eyJ1Ijoic2luZXVzdyIsImEiOiJja3JmNzFhMnMwczhkMnBsampyd3J3c3oxIn0.tFe_kPK6gdvki2VgtXDiAg`) .then(({data}) => { latitude = data.features[0].center[1]; longitude = data.features[0].center[0]; }); const info = { latitude, longitude, date, description } console.log(info) } return ( <form onSubmit={handleSubmit}> <h3>UFO Sighting</h3> <div className="form-group"> <label>Location</label> <input type="text" className="form-control" placeholder="Location" onChange={e => setLocation(e.target.value)} /> </div> <div className="form-group"> <label>Date</label> <input type="date" className="form-control" placeholder="Date" onChange={e => setDate(e.target.value)} /> </div> <div className="form-group"> <label>Encounter Description</label> <input type="text" className="form-control" placeholder="Encounter Description" onChange={e => setDescription(e.target.value)} /> </div> <button type="submit">Submit</button> </form> ) } export default App;
/** * Created by Andrew on 9/13/2015. */ String.prototype.format = function() { var formatted = this; for( var arg in arguments ) { formatted = formatted.replace("{" + arg + "}", arguments[arg]); } return formatted; }; var utils = { isEmpty: function (str) { return (!str || 0 === str.length); }, isEqual: function(a, b) { return a === b; }, escapeRegExp: function (string) { return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1"); }, decodeHtml: function (str) { var decoded = $('<div/>').html(str).text(); return decoded; }, scaleSize: function(maxW, maxH, currW, currH) { var ratio = currH / currW; if(currW >= maxW && ratio <= 1){ currW = maxW; currH = currW * ratio; } else if(currH >= maxH){ currH = maxH; currW = currH / ratio; } return [currW, currH]; }, getImageMetaData: function(url) { $("<img/>").attr("src", url).load(function(){ var dimension = new Array(); if (this.width !== undefined) { dimension['width'] = this.width; dimension['height'] = this.height; return dimension; } else { dimension['width'] = 139; dimension['height'] = 139; return dimension; } }); }, replaceAll: function(string, find, replace) { return string.replace(new RegExp(utils.escapeRegExp(find), 'g'), replace); } };
"use strict"; const countryChina = "Китай"; const countryChili = "Чили"; const countryАustralia = "Австралия"; const countryIndia = "Индия"; const countryJamaica = "Ямайка"; let price; let message; const userCountry = prompt( "Введите страну, куда необходимо совершить доставку" ); if (userCountry === null) { alert("'Отменено пользователем!'"); } else if (!userCountry.trim()) { alert("'Введена пустая строка!'"); } else { const normalizedCountry = userCountry.toLowerCase(); switch (normalizedCountry) { case "китай": price = 100; message = `"Доставка в ${countryChina} будет стоить ${price} кредитов"`; console.log(message); break; case "чили": price = 250; message = `"Доставка в ${countryChili} будет стоить ${price} кредитов"`; console.log(message); break; case "австралия": price = 170; message = `"Доставка в ${countryАustralia} будет стоить ${price} кредитов"`; console.log(message); break; case "индия": price = 80; message = `"Доставка в ${countryIndia} будет стоить ${price} кредитов"`; console.log(message); break; case "ямайка": price = 120; message = `"Доставка в ${countryJamaica} будет стоить ${price} кредитов"`; console.log(message); break; default: alert('"В вашей стране доставка не доступна"'); } }
import AppError from '../errors/AppError'; class SessionController { constructor(user) { this.User = user; } async show(id) { const user = await this.User.findById(id); return user; } async store({ name, email }) { let user = await this.User.findOne({ email }); if (user) { return user; } user = await this.User.create({ name, email }); return user; } } export default SessionController;
function tables(n) { for(let i =1; i<=10; i++) console.log(`${n} * ${i} = ${n*i}` ) } tables(2)
import React from "react"; import "./Courses.css"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { faCartPlus } from "@fortawesome/free-solid-svg-icons"; const Courses = (props) => { const courseInfo = props.singleCourse; const { name, image, instructor, price, rating } = courseInfo; return ( <div className='col md-4'> <div className='card'> <img src={image} alt='' /> <div className='card-body'> <h5 className='course-name'> {name}</h5> <p> by <small className='instructor'>{instructor}</small> </p> <p> Price: <span className='price'>${price}</span> </p> <p> Rating: <span className='rating'>{rating}/5</span> </p> </div> <div className='card-footer'> <button onClick={() => props.handleEnrolement(courseInfo)} className='btn btn-danger' > <FontAwesomeIcon icon={faCartPlus} /> Enrole Now </button> </div> </div> </div> ); }; export default Courses;
 $(function () { init(); grid("#grid", "#toolbar"); //添加辅料事件 $("#addfl").on("click", function () { content("添加辅料", "insertRow", true); }) //搜索 $("#seek").on("click", function () { $('#grid').datagrid('load', { AccessoryName: $('#searchname').val(), AccessoryType: $("#searchtype").combobox("getValue"), AccessoryCode: $("#searchCode").combobox("getValue"), BrandId: $("#searchBrand").combobox("getValue") }); }) //删除选中 $('#remove').linkbutton({ iconCls: 'icon iconfont icon-icon_delete', onClick: function () { var row = $("#grid").datagrid('getSelections'); if (row.length > 0) { layer.alert("确定删除选中的辅料吗", { icon: 3, btn: ['确定', '取消'], yes: function (j) { var parm = new Array() for (var i = 0; i < row.length; i++) { //TODO 获取选中的行 id 传给后台 console.log("选中" + row[i].Id); parm.push(row[i].Id); var _index = $("#grid").datagrid("getRowIndex", row[i]); $("#grid").datagrid('deleteRow', _index); } $.ajax({ type: "Post", url: "/Bcm/DeleteAceessory", dataType: "json", data: JSON.stringify(parm), contentType: "application/json", success: function (data) { layer.close(j); } }); } }) } else { layer.alert('请选择要删除的辅料', { icon: 0, time: 2000 }); } } }) }) //添加或编辑表格的方法 function content(title, type, check, _index) { //type 添加表格或编辑表格的方法名 //check 添加表格为true layer.open({ type: 1, anim: 0, area: [], zIndex: 100, title: title, content: $("#dlg"), btn: ['确定', '取消'], yes: function (i) { var index = _index ? _index : 0; $("#ff").form("submit", { onSubmit: function () { if ($(this).form("validate")) { $("#grid").datagrid(type, { index: index, row: { AccessoryName: $(".AccessoryName").textbox("getText"), GroupName: $("#AccessoryCode").combobox("getText"), BrandName: $("#Brand").combobox("getText"), AccessoryFee: $(".AccessoryFee").textbox("getText"), AccessoryType: $(".AccessoryType").combobox("getText") } }) //todo 调用ajax var parm = { AccessoryName: $(".AccessoryName").textbox("getText"), AccessoryCode: $("#AccessoryCode").combobox("getValue"), BrandId: $("#Brand").combobox("getValue"), AccessoryFee: $(".AccessoryFee").textbox("getText"), AccessoryType: $(".AccessoryType").combobox("getValue"), Eid: type == "updateRow" ? $(".AccessoryId").textbox("getText") :"00000000-0000-0000-0000-000000000000" }; console.log(parm); $.ajax({ type: "Post", url: "/Bcm/Save", dataType: "json", data: JSON.stringify(parm), contentType: "application/json", success: function (data) { var rows = $("#grid").datagrid("getRows"); $("#grid").datagrid('loadData', rows); layer.close(i); } }); //var rows = $("#grid").datagrid("getRows"); //$("#grid").datagrid('loadData', rows); //layer.close(i); } else { layer.alert("信息填写不完整", { icon: 0, tiem: 1500 }); return false; } } }) }, success: function () { if (check) { $("#ff").form("reset"); brandInit(0); groupInit(0); } else { var row = $("#grid").datagrid("getSelected"); var BrandId = row.BrandId; var code = row.AccessoryCode; brandInit(BrandId); groupInit(code); $('#ff').form('load', { AccessoryName: row.AccessoryName, //AccessoryCode: row.AccessoryCode, AccessoryFee: row.AccessoryFee, AccessoryType: $(".AccessoryType").combobox('select',row.AccessoryType), AccessoryId: row.Id, }); } } }) } //实例化表格 function grid(id, toolbar) { $(id).datagrid({ url: '../Bcm/SearchAccessory', method: 'post', nowrap: true, height: "100%", width: "100%", autoRowHeight: true, fitColumns: true, pagination: true, toolbar: toolbar, scrollbarSize: 0, singleSelect: false, onLoadSuccess: function () { var s = $(id).datagrid('getPanel'); var rows = s.find('tr.datagrid-row'); var rows1 = s.find('tr.datagrid-row td[field!=ck]'); rows1.unbind('click').bind('click', function (e) { return false; }); //实例化编辑按钮 $(id).datagrid("getPanel").find("tr .edit").linkbutton({ iconCls: 'icon iconfont icon-bianji1', onClick: function () { var index = $(this).parents("tr").index(); console.log("编辑按钮"+index); $("#grid").datagrid("clearSelections"); $("#grid").datagrid("selectRow", index); var row = $("#grid").datagrid('getSelected'); console.log("编辑按钮,选中的id" + row.Id); content("编辑辅料", "updateRow", false, index) } }) //实例化删除按钮 $(id).datagrid("getPanel").find("tr .delete").linkbutton({ iconCls: 'icon iconfont icon-delete2', onClick: function () { var index = $(this).parents("tr").index(); layer.alert("确定删除此辅料吗", { icon: 3, btn: ['确定', '取消'], yes: function (j) { $(id).datagrid("deleteRow", index); layer.close(j); } }) } }) } }) } //formatter function fmsAccessoryType(value,row,index) { if (value == 0) { return '非防伪标'; } else { return '防伪标'; } return value; } function init() { $("#Brand").combobox({ width: 180, valueField: "id", textField: 'text', required: true, label: "品牌", panelHeight: true, panelMaxHeight: 200, data: [{ id: 0, text: "请选择", selected: true }] }); $("#AccessoryCode").combobox({ width: 180, valueField: "id", textField: 'text', required: true, label: "所属分组", panelHeight: true, panelMaxHeight: 200, data: [{ id: 0, text: "请选择", selected: true }] }); $.ajax({ type: "POST", url: "/Bcm/SearchBrand", async: true, success: function (res) { var data = [{ id: 0, text: "全部", selected: true }]; $.each(res.rows, function (i, e) { data.push({ id: e.Id, text: e.Name }) }) $("#searchBrand").combobox({ width: 180, valueField: "id", textField: 'text', required: true, label: "所属品牌", panelHeight: true, panelMaxHeight: 200, data: data }); } }) $.ajax({ type: "POST", url: "/Bcm/SearchAccessoryGroup", async: true, success: function (res) { var data = [{ id: 0, text: "全部", selected: true }]; $.each(res.rows, function (i, e) { data.push({ id: e.Code, text: e.Name }) }) $("#searchCode").combobox({ width: 180, valueField: "id", textField: 'text', required: true, label: "所属分组", panelHeight: true, panelMaxHeight: 200, data: data }); } }) } function brandInit(brandId) { $.ajax({ type: "POST", url: "/Bcm/SearchBrand", async: true, success: function (res) { console.log(brandId) if (brandId) { var data = []; } else { var data = [{ id: 0, text: "请选择", selected: true }]; } $.each(res.rows, function (i, e) { if (e.Id == brandId) { data.push({ id: e.Id, text: e.Name, selected: true }) } else { data.push({ id: e.Id, text: e.Name }) } }) $("#Brand").combobox("loadData", data); } }) } function groupInit(code) { $.ajax({ type: "POST", url: "/Bcm/SearchAccessoryGroup", async: true, success: function (res) { console.log(code) if (code) { var data = []; } else { var data = [{ id: 0, text: "请选择", selected: true }]; } $.each(res.rows, function (i, e) { if (e.Code == code) { data.push({ id: e.Code, text: e.Name, selected: true }) } else { data.push({ id: e.Code, text: e.Name }) } }) $("#AccessoryCode").combobox("loadData", data); } }) }
var TemplateCollection = Movie.extend(Movie.Collection, { name : 'template' });
import { combineEpics } from 'redux-observable' import counterEpics from '__counter/epics' export default combineEpics(counterEpics)
// Import the functions you need from the SDKs you need import { initializeApp } from "firebase/app"; import { getAnalytics } from "firebase/analytics"; import { initializeAppCheck, ReCaptchaV3Provider } from "firebase/app-check"; import { getAuth } from "firebase/auth"; import { getFirestore } from "firebase/firestore"; // TODO: Add SDKs for Firebase products that you want to use // https://firebase.google.com/docs/web/setup#available-libraries // Your web app's Firebase configuration // For Firebase JS SDK v7.20.0 and later, measurementId is optional const firebaseConfig = { apiKey: "AIzaSyAspe6DOvtD2wE5NwjcTX_HxLe5e4Lbj7A", authDomain: "mysite-1383.firebaseapp.com", projectId: "mysite-1383", storageBucket: "mysite-1383.appspot.com", messagingSenderId: "461237373348", appId: "1:461237373348:web:86a668bddcfcaafca39931", measurementId: "G-Q46QVHN6E8", }; // Initialize Firebase const app = initializeApp(firebaseConfig); const analytics = getAnalytics(app); const auth = getAuth(app); const db = getFirestore(app); if (process.env.NODE_ENV === "development") { const emulators = require("./firebaseEmulators.js"); emulators.connectFirestoreEmulator(db, "localhost", 8080); emulators.connectAuthEmulator(auth, "http://localhost:9099"); self.FIREBASE_APPCHECK_DEBUG_TOKEN = process.env.VUE_APP_CHECK; } const appCheck = initializeAppCheck(app, { provider: new ReCaptchaV3Provider("6LcOyLQdAAAAAML71Vv35GBYNIoXtrQnAAQudkvK"), // Optional argument. If true, the SDK automatically refreshes App Check // tokens as needed. isTokenAutoRefreshEnabled: true, }); export { analytics, appCheck, auth, db };
import React from 'react' import Up from 'react-icons/lib/fa/chevron-up' import Down from 'react-icons/lib/fa/chevron-down' const Table = ({ tableData, sortedBy, order, handleHeaderClick }) => <div id="table-show-container"> <table id="table-body"> <thead> <tr> { tableData[0].map((header, idx) => <th key={idx} value={header} name={header} onClick={() => { handleHeaderClick(header) }} > {header} { sortedBy === header && (order === 'asc' ? <Down /> : <Up />) } </th>) } </tr> </thead> {!tableData[1].length && <div style={{ textAlign: 'center' }}>No records matched the specified query</div>} <tbody> { tableData[1].map((subArray, idx) => <tr key={idx}> {subArray.map((value, idx) => <td key={idx}>{value}</td>)} </tr>) } </tbody> </table> </div> export default Table
import React, { Component } from "react"; import PropTypes from "prop-types"; import styled from "styled-components"; class Collapse extends Component { constructor(props) { super(props); this.state = { height: 0 }; } componentDidMount() { this.updateHeight(); } shouldComponentUpdate() { if (this.measure.clientHeight != this.state.height) return true; return false; } componentDidUpdate() { this.updateHeight(); } updateHeight() { this.setState({ height: this.measure.clientHeight }); } render() { const Collapse = styled.div` overflow: hidden; transition: height ${props => props.speed} ease; `; return ( <Collapse style={{ height: this.props.open ? this.state.height : 0 }} speed="1s" > <div ref={measure => (this.measure = measure)}> {this.props.children} </div> </Collapse> ); } } Collapse.propTypes = { speed: PropTypes.string }; Collapse.defaultProps = { speed: "1s" }; export default Collapse;