text
stringlengths
7
3.69M
import React, { Component } from 'react'; import { compose } from 'redux'; import { connect } from 'react-redux'; import store from 'store'; import * as actions from 'actions'; import { common } from '../../helper/common_function'; class Item extends Component { constructor(props) { super(props); } changeLock = async () => { // const axios = require('axios'); // await axios.get('http://10.0.4.110:3000/door/' + this.props.item.address); await this.props.item.instance.methods.changeLock().send({ from: this.props.tomo.account }); let res = await fetch('http://10.0.4.110:3000/door/' + this.props.item.address, { method: 'GET', credentials: 'include', headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'Access-Control-Allow-Credentials': true } }); await store.dispatch(actions.getMyDoors()); }; render() { const door = this.props.item.lock ? require('assets/img/close.jpg') : require('assets/img/open.jpg'); return ( <div className='col-lg-3 col-md-3 col-xs-12 mb-2'> <div className='card'> <img className='card-img-top' src={door} alt='Foo eating a sandwich.' style={{ height: '200px' }} /> <div className='card-body'> <h5 className='card-title'>room</h5> <p className='row'> <p className='card-text text-left col-6 col-sm-12'> From: {common.timeConverter(this.props.item.startDate)} </p> <p className='card-text text-left col-6 col-sm-12'> To: {common.timeConverter(this.props.item.endDate)} </p> </p> <div className='row'> <div className='col-12'> {this.props.item.lock ? ( <button className='btn btn-success' onClick={this.changeLock}> Open </button> ) : ( <button className='btn btn-dark' onClick={this.changeLock}> Close </button> )} </div> </div> </div> </div> </div> ); } } const mapStateToProps = (state) => { return { tomo: state.tomo }; }; export default compose(connect(mapStateToProps))(Item);
import {pageSize, pageSizeType, paginationConfig, searchConfig} from '../../globalConfig'; const filters = [ {key: 'carNumber', title: '车牌号码', type: 'text'}, {key: 'carModeId', title: '车型', type: 'search', searchType: 'car_mode'}, ]; const tableCols = [ {key: 'carNumber', title: '车牌号'}, {key: 'driverName', title: '司机名称'}, {key: 'carModeId', title: '车型'}, {key: 'transportOrderId', title: '操作中运单', link: true}, {key: 'carState', title: '使用状态', dictionary: 'car_state'}, {key: 'position', title: '车辆位置'}, {key: 'longitude', title: '经度'}, {key: 'latitude', title: '纬度'}, {key: 'province', title: '省份'}, {key: 'city', title: '城市'}, {key: 'district', title: '行政区'}, {key: 'gpsSimNumber', title: 'GPS设备SIM卡号'}, {key: 'gpsEquipmentBrand', title: 'GPS设备品牌'}, {key: 'positionTime', title: '位置更新时间'}, {key: 'totalOutputValue', title: '总产值'}, {key: 'firstTransportOrderId', title: '待执行运单', link: true}, {key: 'lastFinishTime', title: '最后一单完成时间'}, {key: 'reason', title: '变更说明'}, ]; const menu = [ {key:'webExport',title:'页面导出'}, {key:'allExport',title:'查询导出'}, {key:'templateManager', title:'模板管理'} ]; const commonButtons = [{key: 'export', title: '导出', menu}]; const config = { tabs: [{key: 'index', title: '车辆管理', close: false}], subTabs: [ {key: 'use', title:'使用中', status: 'car_state_user'}, {key: 'unuse', title:'闲置中', status: 'car_state_unuser'}, {key: 'repair', title:'维修中', status: 'car_state_repair'}, {key: 'accident', title:'事故中', status: 'car_state_accident'}, {key: 'stop', title:'禁用', status: 'car_state_stop'} ], filters, tableCols, initPageSize: pageSize, //每页显示条数初始值 pageSizeType, paginationConfig, searchConfig, activeKey: 'index', subActiveKey: 'use', urlExport: '/tms-service/car_manager/list/search', //后端查询导出api配置 isTotal: true, //页签是否需要统计符合条件的记录数 //以下属性没有时可不写 searchData: {},//默认搜索条件值-若有需同步配置searchDataBak searchDataBak: {},//初始搜索条件值-若有则与searchData相同 fixedFilters: {//各tab页签列表搜索时的固定搜索条件 use: {carState: 'car_state_user'}, unuse: {carState: 'car_state_unuser'}, repair: {carState: 'car_state_repair'}, accident: {carState: 'car_state_accident'}, stop: {carState: 'car_state_stop'}, }, buttons: { //各tab页签操作按钮 use:[ {key: 'clear', title: '清空运单', bsStyle: 'primary', confirm: '是否确认将勾选记录清空运单?'}, ].concat(commonButtons), unuse: [ {key: 'change', title: '变更状态', bsStyle: 'primary'}, ].concat(commonButtons), repair: [ {key: 'change', title: '变更状态', bsStyle: 'primary'}, ].concat(commonButtons), accident: [ {key: 'change', title: '变更状态', bsStyle: 'primary'}, ].concat(commonButtons), stop: commonButtons } }; export default config;
import React, {useState, useEffect} from 'react' import {connect} from 'react-redux'; import { setEvent } from '../../actions/eventActions'; import Header from "../Header"; const PickEventItem = props => { console.log(props); let [items, setItems] = useState(props.EventItems); const handleClick = (v) => { let item = items.filter(o => o.ItemNo ===v).length > 0 ? items.filter(o => o.ItemNo ===v)[0] : null; if (item !== null) { props.setEvent(props.history, item); } else { console.log("ERROR: No item with value" + v); } } return ( <React.Fragment> <Header /> <div className="container"> <div className="row"> <article className="col-12"> <div className="row"> <div className="col-4 d-none"> <img className="img-fluid" src="/images/registration-emea-2019.png" alt="" /> </div> <div className="col-8 col-12 d-flex align-items-center flex-wrap"> <div> <h2 className="h2 font-weight-light text-primary">Welcome to Directions EMEA registration process.</h2> <p className="">In order to continue please select an event item.</p> {items.map((o,i)=> {return(<button type="button" ke={i} onClick={() => handleClick(o.ItemNo)} className="btn btn-primary px-5">{o.ItemDescription}</button>)})} </div> </div> </div> </article> </div> </div> </React.Fragment> ) } const mapStateToProps = (state /*, ownProps*/) => { return { EventItems: state.event.EventItems } } const mapDispatchToProps = {setEvent} export default connect( mapStateToProps, mapDispatchToProps, )(PickEventItem)
document.getElementById('home').onclick = function(event){ window.location.href = "/main" } var min; var sec; document.getElementById('timeSub').onclick = function(event){ var inputElements = document.getElementById("getTime"); var timeString = inputElements[0]; var intTime = timeString.split(":"); min = intTime[0]; sec = intTime[1]; takeTime(min, sec); } function takeTime(min, sec){ var curMin = min; var curSec = sec; while(curMin > 0){ while(curSec > 0){ document.getElementById("timer").innerHTML = curMin + ":" + curSec; curSec--; } curSec = 60; curMin--; } }
import Ember from 'ember'; import C from 'ui/utils/constants'; export default Ember.Route.extend({ catalog: Ember.inject.service(), model() { return Ember.RSVP.hash({ catalogInfo: this.get('catalog').fetchTemplates({templateBase: C.EXTERNAL_ID.KIND_INFRA, category: C.EXTERNAL_ID.KIND_ALL}), }).then((hash) => { let existing = this.modelFor('settings.projects').projectTemplates; let def = existing.find((tpl) => (tpl.get('name')||'').toLowerCase() === C.PROJECT_TEMPLATE.DEFAULT); if ( def ) { let tpl = def.cloneForNew(); tpl.isPublic = false; tpl.name = ''; tpl.description = ''; hash.projectTemplate = tpl; } else { hash.projectTemplate = this.get('userStore').createRecord({ type: 'projectTemplate', stacks: [], isPublic: false, }); } hash.originalProjectTemplate = hash.projectTemplate; return hash; }); } });
const gio = require('./gio-minp/index.js').default; const gioConfig = { projectId: 'ae08570d515c7766', appId: 'wxa090d3923fde0d4b', version: '1.0', }; function gioInit() { gio('setConfig', gioConfig); }; module.exports = { gioInit, gio, }
import React from 'react'; import {Layout, Icon} from 'antd'; const {Header} = Layout; const HeaderUI = props => { const {collapsed, toggle} = props; return( <Header style={{ background: '#fff', padding: 0 }}> <Icon className="trigger" type={collapsed ? 'menu-unfold' : 'menu-fold'} onClick={toggle} /> </Header> ) } export { HeaderUI }
const db = require('../../config/db')
//import { AssertionError } from "assert"; // Test if a new solution can be added for contract - SolnSquareVerifier // Test if an ERC721 token can be minted for contract - SolnSquareVerifier var SolnSquareVerifier = artifacts.require('SolnSquareVerifier'); var Verifier = artifacts.require('Verifier'); contract('SolnSquareVerifier', accounts => { const account_one = accounts[0]; const account_two = accounts[1]; let correctProof = { 'A': ['0x26357ccd1c3f9ecb4e80f396e685195a2e041a7ba5f65302d411c39220bca251', '0x1887d364fa3c29a030876cb5682718334301bd38377c6ed3fc3448f80045b15f'], 'B': [['0x0775a2b4a1747e013c3039d68e0b753409b24eb8c2c8888090a353d93841223a', '0x14409ef4805c40c5594e70d7a796336aef25d4ee5b9f95332276f49b65c76617'], ['0x0a76b21d33e851a8e5305b58ac9de7cc6e8d306a4c97419cefea3633220477e2', '0x06de0c61f33bbd877fa5eb8e175a26ad0ef9665e7ea96ecd573fdf19911acfad']], 'C': ['0x2a5c6ed912aa04c9fb07ff0d6e3f22f850bb39c1ec9dde613ba24efb2ec2bd30','0x090c36ee572f23770b9fd2a0d6ef58a041c2464856d22f47b2472ea1246aa937'], 'input': ["0x0000000000000000000000000000000000000000000000000000000000000004","0x0000000000000000000000000000000000000000000000000000000000000000"] } describe('Mint tokens with verifier', function(){ beforeEach(async function(){ this.Verifier = await Verifier.new({from: account_one}); this.contract = await SolnSquareVerifier.new(Verifier.address,'Token2', 'tk2', {from: account_one}); }) // it('Should get token balance', async function(){ // for(let i = 0; i < 5; i++){ // await this.contract.mint(accounts[5],i, "token"); // } // let balance = await this.contract.balanceOf(accounts[5]); // assert.equal(balance, 5, "Balance should return 5"); // }) it('Test if an ERC721 token can be minted for contract -SolnSquareVerifier', async function(){ try{ await this.contract.minNFT(account_two, 2, correctProof.A, correctProof.B, correctProof.C, correctProof.input); }catch(err){ console.log(err); } let owner = await this.contract.ownerOf(2); assert.equal(owner, account_two, "Owner should be acc1"); let expectedURI = 'https://s3-us-west-2.amazonaws.com/udacity-blockchain/capstone/2'; let URI = ''; try{ URI = await this.contract.tokenURI(2); }catch(err){ console.log(err); } assert.equal(expectedURI, URI, "Token URI incorrect"); try{ balance = await this.contract.balanceOf(account_two); }catch(err){ console.log(err); } assert.equal(balance, 1, "Balance should return 1"); }) it('Test if a new solution can be added for contract - SolnSquareVerifier', async function(){ let result = false; try{ await this.contract.minNFT(account_two, 3, correctProof.A, correctProof.B, correctProof.C, correctProof.input); }catch(err){ console.log(err); } try{ result = await this.contract.checkSolution.call(correctProof.A, correctProof.B, correctProof.C, correctProof.input); }catch(err){ console.log(err); } assert.equal(result, true, "Solution does exist"); }) it('mint a token with existed solution', async function(){ try{ await this.contract.minNFT(account_two, 2, correctProof.A, correctProof.B, correctProof.C, correctProof.input); }catch(err){ console.log(err); } let mintAgain = true; try { await this.contract.minNFT(account_two, 2, correctProof.A, correctProof.B, correctProof.C, correctProof.input); } catch (err) { //console.log(err); mintAgain = false; } assert.equal(mintAgain, false, "Solution already exist"); }); }); });
/* * Copyright (c) 2014. * * @Author Andy Tang */ (function ClassScope(window) { 'use strict'; /** * A map containing all generated classes, this is necessary for looking up the Super class * @type {Object} * @key {String} ClassName * @value {Function} OriginalClass */ var registeredClasses = {}; var registeredEnoFJSClasses = {}; /** * A class factory, the new class will be stripped of * [this.extend, this.private, this.protected, this.public] * * The variables will then be attached with the correct privacy * * @param NewClass The Class that has to be generated * @returns {EnoFJSClass} A generated class */ window.clazz = function clazz(NewClass) { var className = extractClassName(NewClass); registeredClasses[className] = NewClass; /** * A wrapper class * @constructor */ function EnoFJSClass() { var newClass = new NewClass(); var instanceScope = generateClassScope(this, newClass); newClass.constructor.apply(instanceScope, arguments); } var instance = new NewClass(); if (instance.extend !== undefined) { EnoFJSClass.prototype = new registeredEnoFJSClasses[instance.extend](); } registeredEnoFJSClasses[className] = EnoFJSClass; return EnoFJSClass; }; /** * Generate the Class on the instance scope * * @param scope the scope these members has to be applied to * @param newClass the instance of the class that has to be generated * @returns {Object} the class scope */ function generateClassScope(scope, newClass) { var instanceScope = getExtend(newClass); generateInstanceScopeMembers(instanceScope, instanceScope.private, newClass.private); generateInstanceScopeMembers(instanceScope, instanceScope.protected, newClass.protected); generateInstanceScopeMembers(instanceScope, instanceScope.public, newClass.public); generateInstanceScopeMembers(instanceScope, scope, newClass.public); return instanceScope; } function normalizeInstance(instance) { instance.private = instance.private || {}; instance.protected = instance.protected || {}; instance.public = instance.public || {}; instance.super = instance.super || {}; } function getExtend(instance) { normalizeInstance(instance); if (instance.extend !== undefined) { var parent = getExtend(new registeredClasses[instance.extend]()); extendParent(instance, parent); } return instance; } function extendParent(childScope, parentInstance) { var parentInstanceScope = { private: parentInstance.private, protected: parentInstance.protected, public: parentInstance.public, super: parentInstance.super }; generateInstanceScopeMembers(parentInstanceScope, parentInstanceScope.private, parentInstance.private, childScope.super); generateInstanceScopeMembers(parentInstanceScope, parentInstanceScope.protected, parentInstance.protected, childScope.super); generateInstanceScopeMembers(parentInstanceScope, parentInstanceScope.public, parentInstance.public, childScope.super); childScope.super.constructor = modifyFunctionScope(parentInstanceScope, parentInstance.constructor); mergeAndOverrideParent(childScope, childScope.protected, parentInstanceScope.protected); mergeAndOverrideParent(childScope, childScope.public, parentInstanceScope.public); } /** * Extract the class name from a function * @param NewClass the new class to be generated * @returns {String} */ function extractClassName(NewClass) { var NewClassName = NewClass.toString(); NewClassName = NewClassName.substr('function '.length); NewClassName = NewClassName.substr(0, NewClassName.indexOf('(')); return NewClassName; } /** * Generate the members of the provided class onto the generated class * * @param scope The scope that will be available for the functions to use * @param thisInstanceScope The instance scope where the new member will be applied to * @param members The members which has to be applied on the new instance scope * @param isPublic Indicate if the members should be publicly available * @param superScope If the superScope is provided, the members will also be applied * on the super scope */ function generateInstanceScopeMembers(scope, thisInstanceScope, members, superScope) { for (var member in members) { if (!members.hasOwnProperty(member)) { continue; } if (typeof members[member] === 'function') { thisInstanceScope[member] = modifyFunctionScope(scope, members[member]); } else { thisInstanceScope[member] = members[member]; } if (superScope instanceof Object) { superScope[member] = thisInstanceScope[member]; } } } /** * Modifies the scope of an function * * @param scope The scope that is available for this function * @param memberFunction The function that has to be modified * @returns {modifiedScopeFunction} */ function modifyFunctionScope(scope, memberFunction) { return function modifiedScopeFunction() { return memberFunction.apply(scope, arguments); }; } /** * Merge an object with an other object. The child object will * override any attribute with the same name from the parent * * @param child {Object} * @param parent {Object} */ function mergeAndOverrideParent(scope, child, parent) { for (var member in parent) { if (parent.hasOwnProperty(member) && !child.hasOwnProperty(member)) { child[member] = parent[member]; } else if (parent.hasOwnProperty(member) && child.hasOwnProperty(member)) { parent[member] = modifyFunctionScope(scope, child[member]); } } } }(window));
import {Component, createElement as E} from 'react'; import {connect} from 'react-redux'; import Code from './Code'; import Registers from './Registers'; // import Stack from './Stack'; class App extends Component { constructor(props) { super(props); } render() { return E('div', { id: 'wrapper' }, E(Code), E(Registers), // E(Stack) ); } } const mapStateToProps = ({mainReducer}) => ({ }); const mapDispatchToProps = dispatch => { return { }; }; export default connect(mapStateToProps, mapDispatchToProps)(App);
export const rootQuery = ` type RootQuery { signIn(email: String!, password: String!): AuthData } `
const {app, BrowserWindow} = require('electron'); let mainWindow = null; app.on('ready', () => { console.log('Hello from Electron'); // https://github.com/electron-in-action/bookmarker/issues/1 // https://qiita.com/umamichi/items/8781e426e9cd4a88961b mainWindow = new BrowserWindow({ webPreferences: { nodeIntegration: true } }); // mainWindow.webContents.loadFile('index.html'); <- This doesn't work! mainWindow.webContents.loadFile('app/index.html'); });
import Vue from 'vue' import Vuex from 'vuex' import api from './api/axios' Vue.use(Vuex); export default new Vuex.Store({ state: { userName: null, userPass: null }, mutations: { login_success(state, payload){ state.userName = payload.userName; state.password = payload.password; console.log('login_sucess in store.js') }, }, actions: { login({ commit }, { userName, password }) { return new Promise((resolve, reject) => { api.login(userName, password).then(response => { console.log(response) if( response.data == 'success'){ commit('login_success', { userName: userName, password: password }); console.log('response is expected in store.js') } resolve(response) }) .catch( error => { console.log("Error: " + error); reject("Invalid credentials!"); }) }) } } })
import React, { useState } from "react"; import { useFirebase, useFirestore } from "react-redux-firebase"; import { Link, useHistory } from "react-router-dom"; import images from "../../utils/ImageHelper"; import Footer from "../Layout/Footer"; import '../../assets/css/slick-theme.css'; import '../../assets/css/slick.css'; import '../../assets/css/bootstrap.min.css'; //import '../../assets/css/bootstrap-grid.min.css'; import '../../assets/css/style.css'; import Slider from "react-slick"; import { toast } from "react-toastify"; import Login from "../Auth/Login/Login"; import CompanyRegister from "../Company/CompanyRegister"; import ForgotPassword from "../Auth/ForgotPassword"; import $ from "jquery"; const initialState = { description: "", postCode: "", email: "", title: "", files: [] } export default function Home() { const firebase = useFirestore(); const firebaseStorage = useFirebase(); const [formData, setFormData] = useState(initialState); const [formError, setErrors] = useState(initialState); const [isLoginModal, setOpenLoginModal] = useState(false); const [isRegisterModal, setOpenRegisterModal] = useState(false); const [isShowForgotModal, setOpenForgotModal] = useState(false); const userInfo = JSON.parse(localStorage.getItem('userDetails')) || {} let history = useHistory(); React.useEffect(() => { let src = `//code.tidio.co/f5r4orp8oauizt5gqbxrfiv0v64xqtuu.js`; const script = document.createElement("script"); script.async = true; script.src = src; script.id = "tidiochat"; document.head.appendChild(script); }, []); // React.useEffect(() => { // return () => { // $("#tidiochat").remove(); // $("#tidio-chat").remove(); // }; // }); const handleSubmit = (e) => { e.preventDefault(); let validationErrors = {}; Object.keys(formData).forEach(name => { const error = formValidate(name, formData[name]); if (error && error.length > 0) { validationErrors[name] = error; } }); if (Object.keys(validationErrors).length > 0) { setErrors(validationErrors); return; } console.log(formData.email); const emailId = formData.email && formData.email.toLowerCase() firebase.collection("tblUser").where("Email", "==", emailId).get() .then(function (querySnapshot) { if (querySnapshot.empty) { setFormData(initialState) firebase.collection("tblUser").add({ Email: emailId, UserName: formData.email, PostCode: formData.postCode, Name: '', telephone: '', Password: '', UserType: 'private', FullName: "", AboutUs: "", ProfileImage: "", OrganizationNo: "", Address: "", IsActivated: false, IsLogin: false, LoginIp: "", CompanyName: '' }).then(async docRef => { let response = await fetch(`${process.env.REACT_APP_API_SENDMAIL}?dest=${emailId}&emailName=newuserregister&docId=${window.location.origin}/create-password/${docRef.id}`, { method: "GET", }); response.json().then((res) => { console.log("res", res) }).catch((e) => { console.log("e", e) }) let imageList = []; (formData.files || []).forEach((x) => { const storageRef = firebaseStorage.storage().ref(`image`); const mainImage = storageRef.child(x.name); mainImage.put(x).then((snapshot) => { mainImage.getDownloadURL().then((url) => { imageList.push(url); if ((formData.files && formData.files.length) === (imageList && imageList.length)) { firebase.collection("tblProjectMaster").add({ UserId: docRef.id, description: formData.description, Title: formData.title, PostCode: formData.postCode, Files: imageList, CreatedDate: new Date(), UpdatedDate: new Date(), UpdatedBy: docRef.id, }).then((result) => { setFormData(formData => ({ ...formData, description: '', title: '', location: '', files: [], })); toast.success("Record create successfully"); }).catch((error) => { toast.error("Something went wrong please try again"); }); } }) }) }) }).catch((error) => { toast.error("Something went wrong please try again"); }); } else { let imageList = [] querySnapshot.forEach(function (doc) { const data = doc.data(); if (data.Email === emailId) { (formData.files || []).forEach((x) => { const storageRef = firebaseStorage.storage().ref(`image`); const mainImage = storageRef.child(x.name); mainImage.put(x).then((snapshot) => { mainImage.getDownloadURL().then((url) => { imageList.push(url); if ((formData.files && formData.files.length) === (imageList && imageList.length)) { firebase.collection("tblProjectMaster").add({ description: formData.description, Title: formData.title, Files: imageList, PostCode: formData.postCode, CreatedDate: new Date(), UpdatedDate: new Date(), UpdatedBy: querySnapshot.docs[0].id, UserId: querySnapshot.docs[0].id, }).then((result) => { setFormData(formData => ({ ...formData, description: '', title: '', location: '', files: [], })); toast.success("Record create successfully"); }).catch((error) => { toast.error("Something went wrong please try again"); }); } }) }) }) setFormData(initialState) } }); } }) .catch(function (error) { console.error("Error getting documents: ", error); }); // window.location = "/Dashboard"; }; const formValidate = (name, value) => { switch (name) { case "description": if (!value || value.trim() === "") { return "Description is required"; } else { return ""; } case "postCode": if (!value || value.trim() === "") { return "Post code is required"; } else { return ""; } case "title": if (!value || value.trim() === "") { return "Title is required"; } else { return ""; } case "email": if (!value || value.trim() === "") { return "Email is required"; } else if (!value.match(/^\w+([.-]?\w+)*@\w+([.-]?\w+)*(\.\w{2,3})+$/)) { return "Enter a valid email address"; } else { return ""; } default: { return ""; } } }; const imageUpload = (event) => { const data = [...formData.files, ...event.target.files] setFormData(formData => ({ ...formData, files: data })); } const onRemoveImage = (x) => { const index = formData.files.findIndex((y) => y.name === x.name) formData.files.splice(index, 1) setFormData(formData => ({ ...formData, })); } const handleInputChange = (event) => { const { name, value } = event.target if (name === "postCode") { const re = /^[0-9\b]+$/; if (value === '' || re.test(value)) { setFormData(formData => ({ ...formData, [name]: value })); } } else { setFormData(formData => ({ ...formData, [name]: value })); } setErrors(formError => ({ ...formError, [name]: formValidate(name, value) })); } const handleLoginModal = (login, signup) => { setOpenLoginModal(login) setOpenRegisterModal(signup) } const handleLoginRegister = (login, signup) => { setOpenLoginModal(login) setOpenRegisterModal(signup) } const logout = () => { firebase.collection("tblUser").doc(userInfo.id).set({ ...userInfo, IsLogin: false, }).then((res) => { window.location.reload() localStorage.removeItem("userId"); localStorage.removeItem("userDetails"); }).catch((e) => { }) } const settings = { infinite: false, slidesToShow: 3, slidesToScroll: 3, arrows: true, dots: true, }; const handleForgot = () =>{ setOpenForgotModal(true) setOpenLoginModal(false) } const onRedirect = (url) => { window.location.replace(url) //history.push(url) } // console.log("111",userInfo) // const userType = (userInfo && userInfo.UserType) return ( <div className="App homescroll" id="tidiochat"> {/*<header id="header" className="header_main">*/} {/* <div className="container">*/} {/* <div className="row">*/} {/* <nav className="navbar navbar-expand-lg navbar-light bg-light">*/} {/* <a className="navbar-brand" href="#top">*/} {/* <img src={images.logosvg} alt="logo-img" />*/} {/* </a>*/} {/* </nav>*/} {/* </div>*/} {/* </div>*/} {/*</header>*/} <div className="password_header"> <div className="container"> <div className="row align-items-center"> <div className="col-sm-2 col-10"> <div className="password_header_logo"> <a><img alt="img" src={images.logosvg} /></a> </div> </div> <div className="col-sm-10 col-10"> <div className="header_menu"> { userInfo.id ? <ul> <li><a href="/get-help">Publicera ett jobb</a></li> <li onClick={() => onRedirect('/job-list')}><a>Uppdrag</a></li> <li onClick={() => onRedirect('/company/dashboard')}><a>Välkommen {userInfo.FullName}</a></li> <li><a onClick={logout}>Logga ut</a></li> </ul> : <ul> <li><a href="/get-help">Publicera ett jobb</a></li> <li onClick={() => onRedirect('/job-list')}><a>Uppdrag</a></li> <li onClick={() => handleLoginModal(true, false)}><a>LOGGA IN</a></li> <li onClick={() => handleLoginRegister(false, true)}><a>ANSLUT FORETAG</a></li> </ul> } </div> </div> </div> </div> </div> { isLoginModal && <Login isModalOpen={isLoginModal} onClose={handleLoginModal} onForgotPassword={handleForgot}/> } { isRegisterModal && <CompanyRegister isRegisterModal={isRegisterModal} onClose={handleLoginRegister} /> } { isShowForgotModal && <ForgotPassword open={isShowForgotModal} onClose={()=>setOpenForgotModal(false)} /> } <div className="banner"> <div className="container"> <div className="row"> <div className="col-lg-6 col-md-6 col-sm-12 col-xs-12"> <div className="banner_text"> <div className="banner_text_inner"> <span className="banner_star_text"> <img src={images.bannerStar} alt="banner" /> SVAR SAMMA DAG </span> <h2>Anlita trädgårdsproffs nära dig</h2> <p> Behöver du hjälp med trädgårdsarbete? Fyll i formuläret så matchar vi dig med trädgårdsproffs nära dig. Snabb, smidigt & säkert! </p> <div className="banner_btn"> <a href="#top"> <img src={images.playIcon} alt="play" /> </a> <span>SE VÅR FILM</span> </div> </div> </div> </div> <div className="col-lg-6 col-md-6 col-sm-12 col-xs-12"> <div className="banner_form_main"> <div className="banner_form dn"> <div className="banner_form_title"> <h3>BOKA TRÄDGÅRDSPROFFS IDAG</h3> <p> Fyll i formuläret och din förfrågan kopplas till relevanta företag nära dig </p> </div> <div className="banner_form_inner"> <div id="emailMsg"></div> <form id="emailFrom" method="post"> <div className="form-group"> <label>Postnummer</label> <input value={formData.postCode} onChange={handleInputChange} type="text" className="form-control" name="postCode" id="postnummer" aria-describedby="emailHelp" placeholder="Postnummer" /> {formError.postCode && <p className="text-danger">{formError.postCode}</p>} </div> <div className="form-group"> <label>Rubrik</label> <input value={formData.title} onChange={handleInputChange} name="title" id="kort_beskrivning" className="form-control" placeholder="Rubrik" /> {formError.title && <p className="text-danger">{formError.title}</p>} </div> <div className="form-group"> <label>Kort beskrivning</label> <textarea value={formData.description} onChange={handleInputChange} name="description" id="kort_beskrivning" className="form-control" placeholder="Kort beskrivning" /> {formError.description && <p className="text-danger">{formError.description}</p>} </div> <div className="form-group"> <label htmlFor="Email">Email</label> <input value={formData.email} onChange={handleInputChange} type="email" className="form-control" name="email" id="email" aria-describedby="emailHelp" placeholder="Email" /> {formError.email && <p className="text-danger">{formError.email}</p>} </div> <div className="form-group choose_file"> <label>Ladda upp bild</label> <div className="inputfileupload"><input onChange={imageUpload} accept="image/*" name="files" type="file" multiple /> <div> <p><span> Ladda upp fil </span> Ingen fil vald</p> </div> </div> <div id="result"> <Slider {...settings}> { (formData.files || []).map((x, i) => { let url = URL.createObjectURL(x) return ( <div className="img-inner" key={i}> <a onClick={() => onRemoveImage(x, i)}>x</a> <img src={url} className="thumbnail" alt={url} /> </div> ) }) } </Slider> </div> </div> <button onClick={handleSubmit} type="submit" name="submit" className="btn btn-primary"> Publicera </button> </form> </div> </div> </div> </div> </div> </div> </div> <div className="services"> <div className="container"> <div className="row"> <div className="col-lg-12 col-md-12"> <div className="section_title"> <h2>TRE FÖRDELAR MED FixWeDo</h2> </div> </div> </div> <div className="row"> <div className="col-lg-4 col-md-4"> <div className="services_box"> <div className="services_icon"> <img src={images.services1} alt="services" /> </div> <div className="services_text"> <h3> <a href="#top">Få kontakt idag</a> </h3> <p> Publicera ett jobb på 30 sekunder, och få kontakt med proffs idag! </p> </div> </div> </div> <div className="col-lg-4 col-md-4"> <div className="services_box"> <div className="services_icon"> <img src={images.services2} alt="services2" /> </div> <div className="services_text"> <h3> <a href="#top">Smidig kommunikation</a> </h3> <p> Kommunicera direkt med dina hantverkare på smidigare sätt! </p> </div> </div> </div> <div className="col-lg-4 col-md-4"> <div className="services_box"> <div className="services_icon"> <img src={images.services3} alt="services3" /> </div> <div className="services_text"> <h3> <a href="#top">Verifierade trädgårdsproffs</a> </h3> <p> Med kontrollerade företag & ömsesidiga omdömen står trygghet i fokus! </p> </div> </div> </div> </div> </div> </div> <div className="how-it-work"> <div className="container"> <div className="row"> <div className="col-lg-12 col-md-12"> <div className="section_title"> <h2 className="text-white">SÅ FUNGERAR DET</h2> </div> </div> </div> <div className="row"> <div className="col-lg-4 col-md-4 half_round_shape"> <div className="how_it_box"> <div className="how_it_num"> <span>1</span> </div> <div className="how_it_text"> <h3> Publicera ditt <br></br>uppdrag </h3> <p> Glöm krångliga formulär. Du publicerar ditt uppdrag på under 30 sekunder och får kontakt samma dag. </p> </div> </div> </div> <div className="col-lg-4 col-md-4 half_round_shape"> <div className="how_it_box"> <div className="how_it_num"> <span>2</span> </div> <div className="how_it_text"> <h3> Smidig <br></br> kommunikation </h3> <p> Kommunikation som det borde vara. Red ut alla frågor på ett smidigt sätt. Bestäm tid, plats & pris för jobbet. </p> </div> </div> </div> <div className="col-lg-4 col-md-4 half_round_shape"> <div className="how_it_box"> <div className="how_it_num"> <span>3</span> </div> <div className="how_it_text"> <h3>Luta dig tillbaka & njut av väl utfört jobb</h3> <p> När jobbet är utfört och alla parter är nöjda betalas pengarna ut till hantverkaren. Nu ges även möjlighet att ge ett omdöme för jobbet. </p> </div> </div> </div> </div> </div> </div> <div className="app"> <div className="container"> <div className="row"> <div className="col-lg-12 col-md-12"> <div className="section_title d-lg-none d-md-none d-sm-block"> <h2 className="text-center"> Publicera och hantera dina uppdrag ännu enklare i FixWeDo appen. Kommer snart! </h2> </div> </div> </div> <div className="row align-items-center"> <div className="col-lg-6 col-md-6"> <div className="mobile_img"> <img src={images.phoneImg} alt="phone_img" /> </div> </div> <div className="col-lg-6 col-md-6"> <div className="section_title app-title-responsive"> <h2 className="text-left"> Publicera och hantera dina uppdrag ännu enklare<br></br> i FixWeDo appen.<br></br> Kommer snart! </h2> </div> <div className="app_icon"> <a href="#top"> <img src={images.appstoreBtn} alt="appstoreBtn" /> </a> <a href="#top"> <img src={images.googlePlayIcon} alt="googlePlayIcon" /> </a> </div> </div> </div> </div> </div> <Footer /> </div> ); }
import axios from 'axios'; const API_URL = process.env.REACT_APP_API_URL; const USER_BASEPATH = '/api/user'; export const FETCHINGUSER = 'FETCHINGUSER'; export const CREATINGUSER = 'CREATINGUSER'; export const UPDATINGUSER = 'UPDATINGUSER'; export const LOGGINGOUTUSER = 'LOGGINGOUTUSER'; export const LOGGEDOUTUSER = 'LOGGEDOUTUSER'; export const COMPLETE = 'COMPLETED ACTION'; export const ERROR = 'ERROR'; export const FETCHINGCART = 'FETCHINGCART'; export const ADDINGITEMTOCART = 'ADDINGITEMTOCART'; export const ADDEDITEMTOCART = 'ADDEDITEMTOCART'; export const UPDATINGCARTITEM = 'UPDATINGCARTITEM'; export const UPDATEDCARTITEM = 'UPDATEDCARTITEM'; export const MOVEDITEMTOWISHLIST = 'MOVEDITEMTOWISHLIST'; export const DELETINGCARTITEM = 'DELETINGCARTITEM'; export const DELETEDCARTITEM = 'DELETEDCARTITEM'; export const FETCHINGPURCHASEHISTORY = 'FETCHINGPURCHASEHISTORY'; export const FETCHEDPURCHASEHISTORY = 'FETCHEDPURCHASEHISTORY'; export const MAKINGPURCHASE = 'MAKINGPURCHASE'; export const login = userDetails => { const promise = axios.post(`${API_URL}${USER_BASEPATH}/login`, userDetails); return dispatch => { dispatch({ type: FETCHINGUSER }); promise .then(res => { localStorage.setItem('jwt', res.data.token); return dispatch({ type: COMPLETE, payload: res.data.user }); }) .catch(err => dispatch({ type: ERROR, payload: err })); }; }; export const register = form => { const config = { user: form }; const promise = axios.post(`${API_URL}${USER_BASEPATH}/register`, config); return dispatch => { dispatch({ type: CREATINGUSER }); promise .then(res => dispatch({ type: COMPLETE, payload: res.data.user })) .catch(err => dispatch({ type: ERROR, payload: err })); }; }; export const logout = token => { const headers = { headers: { Authorization: token } }; const promise = axios.get(`${API_URL}${USER_BASEPATH}/logout`, headers); return dispatch => { dispatch({ type: LOGGINGOUTUSER }); promise .then(res => dispatch({ type: LOGGEDOUTUSER })) .catch(err => dispatch({ type: ERROR, payload: err })); }; }; export const moveItemToWishList = (userId, productId, token) => { const config = { headers: { Authorization: token } }; const promise = axios.get( `${API_URL}${USER_BASEPATH}/${userId}/cart/${productId}`, config, ); return dispatch => { dispatch({ type: UPDATINGCARTITEM }); promise .then(res => dispatch({ type: MOVEDITEMTOWISHLIST, payload: res.data })) .catch(err => dispatch({ type: ERROR, payload: err })); }; }; export const addToCart = (user_id, quantity = 1, product_id) => { const token = localStorage.getItem('jwt'); const config = { headers: { Authorization: token } }; const data = { product: { quantity, product_id } }; const promise = axios.post( `${API_URL}${USER_BASEPATH}/${user_id}/cart`, data, config, ); return dispatch => { dispatch({ type: ADDINGITEMTOCART }); promise .then(res => dispatch({ type: ADDEDITEMTOCART, payload: res.data })) .catch(err => dispatch({ type: ERROR, payload: err })); }; }; export const deleteFromCart = (user_id, product_id) => { const token = localStorage.getItem('jwt'); const config = { headers: { Authorization: token } }; const promise = axios.delete( `${API_URL}${USER_BASEPATH}/${user_id}/cart/${product_id}`, config, ); return dispatch => { dispatch({ type: DELETINGCARTITEM }); promise .then(res => dispatch({ type: DELETEDCARTITEM, payload: res.data })) .catch(err => dispatch({ type: ERROR, payload: err })); }; }; export const updateCartItem = (user_id, product_id, quantity) => { const token = localStorage.getItem('jwt'); const config = { headers: { Authorization: token } }; const data = { quantity }; const PREFIX = `${API_URL}${USER_BASEPATH}/${user_id}/cart/${product_id}`; const promise = axios.put(PREFIX, data, config); return dispatch => { promise .then(res => dispatch({ type: UPDATEDCARTITEM, payload: res.data })) .catch(err => dispatch({ type: ERROR, payload: err })); }; }; export const getPurchaseHistory = userId => { const token = localStorage.getItem('jwt'); const config = { headers: { Authorization: token } }; const promise = axios.get( `${API_URL}${USER_BASEPATH}/${userId}/purchase`, config, ); return dispatch => { dispatch({ type: FETCHINGPURCHASEHISTORY }); promise .then(res => dispatch({ type: FETCHEDPURCHASEHISTORY, payload: res.data }), ) .catch(err => dispatch({ type: ERROR, payload: err })); }; }; export const makePurchase = (userId, purchase) => { const token = localStorage.getItem('jwt'); const config = { headers: { Authorization: token } }; const promise = axios.post( `${API_URL}${USER_BASEPATH}/${userId}/purchase`, purchase, config, ); return dispatch => { dispatch({ type: MAKINGPURCHASE, }); promise.then(res => dispatch({ type: MAKINGPURCHASE, payload: res.data }).catch(err => dispatch({ type: ERROR, payload: err }), ), ); }; };
"use strict" const express = require('express'); const router = express.Router(); const fiesta = require('../../service/fiesta'); const holder = require('../../service/holder'); router.post('/', (req, res) => { const name = req.body.name; if (name === null || name === '') { res.status(412).json({}); return; } holder.addHolders(name) .then((data) => { res.status(204).json(data); return; }) .catch((e) => { res.status(500).json({}); return; }); }); router.put('/:id', (req, res) => { const id = parseInt(req.params.id); const name = req.body.name; if (name === null || name === '' || id === null || id === 0) { res.status(412).json({}); return; } holder.modifyHolders(id, name) .then((data) => { if (data === null) { res.status(404).json({}); return; } else { res.status(200).json(data); return; } }) .catch((e) => { res.status(500).json({}); return; }); }); router.delete('/:id', (req, res) => { const id = parseInt(req.params.id); if (id === null || id === 0) { res.status(412).json({}); return; } holder.deleteHolders(id) .then((data) => { if (data === null) { res.status(404).json({}); return; } res.status(204).json({}); return; }) .catch((e) => { res.status(500).json({}); return; }); }); module.exports = router;
import * as axios from 'axios' const BASE_URL = 'https://nimebox-api.herokuapp.com/' const BEARER_TOKEN = 'c0366e6f04436200b9998419134e4c3216b08daf' export default axios.create({ baseURL: BASE_URL, headers: { Authorization: `Bearer ${BEARER_TOKEN}`, 'Content-Type': 'application/json' }, withCredentials: true })
const express = require('express'); const SmwgController = require('../controllers/smwgs.js'); const SmwgItemController = require('../controllers/smwg_items.js'); const { isAuthorizedAs } = require('../helpers/AuthUtils'); const router = express.Router(); router.get('/', isAuthorizedAs('ADMIN'), SmwgController.findAll); router.get('/:smwgId', isAuthorizedAs('ADMIN'), SmwgController.findOne); router.post('/', isAuthorizedAs('ADMIN'), SmwgController.create); router.put('/:smwgId', isAuthorizedAs('ADMIN'), SmwgController.update); router.delete('/:smwgId', isAuthorizedAs('ADMIN'), SmwgController.destroy); router.get('/:smwgId/items', SmwgItemController.findAll); module.exports = router;
var fs = require("fs"); //Constructor function Peer() { // always initialize all instance properties this.config = {}; this.available = false; this.peer_id = null; } Peer.prototype.load = function(_id, callback) { var self = this; console.log("In peer class and load id: " + _id); this.peer_id = _id; var filename = "./peers/" + this.peer_id + ".json"; fs.exists(filename, function (exists) { if (exists) { fs.readFile(filename, function(err,datas) { console.log(datas + " peer found in conf file"); self.config = JSON.parse(datas); console.log(self.config); return callback(); }); } else { // TODO : The peer ID don't exist in local, we should lookup on the Peers Server return callback(); } }); } Peer.prototype.save = function(callback) { json_str = JSON.stringify(this.config); console.log("Saving peer data: " + json_str); console.log("Saving peer id: " + this.peer_id); var filename = "peers/" + this.peer_id + ".json"; console.log("Writing to : " + filename); fs.writeFile(filename, json_str, function(err) { if(err) { console.log(err); return callback(err); } console.log("The peer file was saved!"); return callback(null); }); } // export the class module.exports = Peer;
let datePattern = /^[0-9]{2}:[0-9]{2}$/; export default function add(time, task, id){ if(!datePattern.test(time)){ return { type: "SET_ERROR", payload: { time : "Time is invalid" } } } if(!task.length){ return{ type: "SET_ERROR", payload: { task :"Task field is empty" } } } return{ type: "ADD_TASK", payload:{ id: id, time: time, task: task } } }
// jscs:disable jsDoc module.exports = function () { return function deleteOne (Model, instance, callback) { var key = this.createEphemeralKey(Model, instance.getPrimaryKey()) this.client.del(key, function (err) { callback(err, (!err && instance) || null) }) } }
/** * This module is forked from https://github.com/ratehub/check-prop-types * to make it work for production mode too. * * Forked from this commit (v1.1.2): * https://github.com/ratehub/check-prop-types/commit/b257ae58664dae93d5be31753c1e954ee4440f90 * * License: * MIT * https://github.com/ratehub/check-prop-types/blob/b257ae58664dae93d5be31753c1e954ee4440f90/LICENSE */ import ReactPropTypesSecret from './_secret' export const checkPropTypes = (model, value, location, componentName, getStack) => { const name = componentName ? `${componentName}: ` : '' if (typeof model !== 'function') return ( `${name}${location} type is invalid; ` + 'it must be a function, usually one of PropTypes.' ) // Prop type validation may throw. // In case they do, catch and save the exception as the error. let error try { error = model({'': value}, '', componentName, location, null, ReactPropTypesSecret) } catch (ex) { error = ex } if (error && !(error instanceof Error)) return ( `${name}type specification of ${location} is invalid; ` + 'the type checker function must return `null` or an `Error` but returned a ' + `${typeof error}. You may have forgotten to pass an argument to the type checker ` + 'creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and ' + 'shape all require an argument).' ) if (error instanceof Error) { const stack = getStack ? getStack() : '' return `Failed ${location} type: ${error.message}${stack || ''}` } }, // Throws an exception instead of just returning an error message as `checkPropTypes` does. assertPropTypes = (...args) => { const error = checkPropTypes(...args) if (error) throw new Error(error) }
const arc = require("@architect/f"un"ctions"); const { DB_MAP } = require("../src/http/post-graphql/db-schema"); const teams = [ { pk: "T#t_01", sk: "#", "gsi1pk": "Team", "gsi1sk": "Team One", tn: "Team One", "_tp": "Team", }, ]; const users = [ { "pk": "U#u_01", "sk": "#", "gsi1pk": "User", "gsi1sk": "John Smith", "gsi2pk": "T#t_01", "gsi2sk": "#", "un": "John Smith", "_tp": "User", }, { "pk": "U#u_02", "sk": "#", "gsi1pk": "User", "gsi1sk": "Jane Doe", "gsi2pk": "T#t_01", "gsi2sk": "#", "un": "Jane Doe", "_tp": "User", }, { "pk": "U#u_03", "sk": "#", "gsi1pk": "User", "gsi1sk": "John Doe", "gsi2pk": "T#t_01", "gsi2sk": "#", "un": "John Doe", "_tp": "User", }, { "pk": "U#u_04", "sk": "#", "gsi1pk": "User", "gsi1sk": "Jane Smith", "gsi2pk": "T#t_01", "gsi2sk": "#", "un": "Jane Smith", "_tp": "User", }, ]; const certifications = [ { "pk": "C#c_01", "sk": "#", "gsi1pk": "Certification", "gsi1sk": "Rock Certification", "cn": "Rock Certification", "_tp": "Certification", }, { "pk": "C#c_02", "sk": "#", "gsi1pk": "Certification", "gsi1sk": "Hiking Certification", "cn": "Hiking Certification", "_tp": "Certification", }, ]; const credentials = [ { "pk": "U#u_01", "sk": "C#c_01", "gsi1pk": "C#c_01", "gsi1sk": "U#u_01", "cn": "Rock Certification", "un": "John Smith", "exp": "June,2021", "_tp": "Credential", }, { "pk": "U#u_01", "sk": "C#c_02", "gsi1pk": "C#c_02", "gsi1sk": "U#u_01", "cn": "Hiking Certification", "un": "John Smith", "exp": "April,2022", "_tp": "Credential", }, ]; async f"un"ction seedDb() { const data = await arc.tables(); return Promise.all( [...teams, ...users, ...certifications, ...credentials].map((item) => data.singletable.put(item)) ); } seedDb() .then(() => console.log("local database seeded")) .catch((err) => console.log("error:" + err.message));
if ("serviceWorker" in navigator) { navigator.serviceWorker.register("/sw.js"); } let pwaInstallPrompt = null; const installPWAHTML = ` <div id='installationPrompt' class="position-fixed bottom-0 end-0 p-3 mx-3 my-1" style="z-index: 5;right:0px;"> <div class="toast" role="alert" aria-live="assertive" aria-atomic="true"> <div class="toast-header" style='background-color:black;border:none;'> <img src="/logo.png" class="rounded me-2" alt="logo" style="margin:0px;"> <strong class="me-auto">Install myCODEnotein Now : (PWA)</strong> <button type="button" class="bg-light btn-close" data-bs-dismiss="toast" aria-label="Close"></button> </div> <div class="toast-body bg-dark"> <button id="installPWA" class="btn btn-outline-light mr-5">Install Our App (PWA)</button> </div> </div> </div> `; document.body.innerHTML += installPWAHTML; let toastElement = document.querySelector('.toast'); let toastBody = toastElement.querySelector('.toast-body'); let toast = null; window.addEventListener('beforeinstallprompt',e=>{ pwaInstallPrompt = e; toast = new bootstrap.Toast(toastElement,{autohide:false}); toast.show() }); document.getElementById('installPWA').addEventListener('click',async (e)=>{ if(pwaInstallPrompt===null){ return; } pwaInstallPrompt.prompt(); toast.hide(); const userChoice = await pwaInstallPrompt.userChoice; if(userChoice.outcome==='dismissed'){ return; } }); window.addEventListener('appinstalled',(e)=>{ document.getElementById('installationPrompt').innerHTML = `<div class="toast align-items-center text-white bg-success border-0" role="alert" aria-live="assertive" aria-atomic="true"> <div class="d-flex"> <div class="toast-body fw-bold"> Successfully Installed The App. </div> <button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button> </div></div>`; toastElement = document.querySelector('.toast'); toast = new bootstrap.Toast(toastElement); toast.show() })
#!/usr/bin/env node process.title = 'elemez2csv'; var elemez2csv = require('../lib/elemez2csv'); return elemez2csv(process.argv, function(e) { if(e) { console.error(e); return process.exit(1); } return process.exit(0); });
/* Copyright (C) 2018 Jon Moore * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ var slides_per_show = 5; var secs_per_slide = 15; var local_images = [ "./imgs/contortionist.jpg", "./imgs/stormtroopers.jpg", "./imgs/possum.jpg", "./imgs/biceps.jpg", "./imgs/skeleton.jpg", "./imgs/giraffe.jpg", "./imgs/pirate-mice.jpg", "./imgs/spout.jpg", "./imgs/bubblehead.jpg", "./imgs/calisthenics.jpg", "https://i.ytimg.com/vi/daoTiDaCLg8/maxresdefault.jpg", "https://static1.squarespace.com/static/57b31fb45016e16882ac0fc9/57d932fff7e0ab1129481fe3/5b92b7dd0ebbe83ee1a1c97e/1540902265645/TonyMarrese.jpg?format=2500w", "https://pbs.twimg.com/profile_images/821849411991044096/lQFa_Vly_400x400.jpg", "https://imgnooz.com/sites/default/files/wallpaper/animals/55900/funny-dog-wallpapers-55900-4496266.jpg", "https://www.nationalgeographic.com/content/dam/animals/2018/09/comedy-wildlife-awards-photos/comedy-wildlife-awards-squirel-stop.ngsversion.1537203605960.adapt.1900.1.jpg", "https://kids.nationalgeographic.com/content/dam/kids/photos/articles/Other%20Explore%20Photos/R-Z/Wacky%20Weekend/Funny%20Animal%20Faces/ww-funny-animal-faces-goat.adapt.945.1.jpg", "https://worldwideinterweb.com/wp-content/uploads/2017/10/most-ridiculous-photo-ever-taken.jpg", "https://hairstyleonpoint.com/wp-content/uploads/2017/03/horse-hair-ridiculous-haircuts.jpg", "https://worldwideinterweb.com/wp-content/uploads/2017/10/ridiculous-photo-ever.jpg", "https://rabbitroom.com/wp-content/uploads/2018/02/3044182-poster-p-1-ridiculous-by-design-where-designs-craziest-inventor-gets-his-ideas.gif.jpeg", "https://assets.classicfm.com/2013/33/king-chicken-opera-1377248295.jpeg", "https://bobcat.grahamdigital.com/83b806ce781a4c14f92a666000ecacf2f2fd99cd/crop-640x360-000.jpg", "http://games.snimai.com/images/photos/top-10-most-ridiculous-and-dummy-photos-of-animals/thumbs/top-10-most-ridiculous-and-dummy-photos-of-animals-2.jpg", "http://visionad.artefactdesign.com/wp-content/uploads/2017/07/The-Good-the-Bad-and-the-Ridiculous-Stock-Photos.jpg", "https://yumnatarian.files.wordpress.com/2014/03/ridiculous-fashion-balloon.jpg", "http://www.comediva.com/wp-content/uploads/2014/12/15-Ridiculous-Skymall-Products-What-on-Earth-Beard-Hat.png", "https://www.dailydot.com/wp-content/uploads/2016/10/funny-ridiculous-halloween-costumes-centaur-280x400.png", "https://i.ytimg.com/vi/aGSlt0CnFr4/hqdefault.jpg", "https://66.media.tumblr.com/504abb90a59f169000fa21615c725f87/tumblr_inline_mfo94hDH2A1qiv1zz.jpg", "https://i.pinimg.com/originals/0d/04/7a/0d047a0904ac5d7835b1899fd1bfa1e8.jpg", "https://static.boredpanda.com/blog/wp-content/uploads/2018/03/ugly-medieval-cats-art-115-5aafbd8c8ffe9__700.jpg", "https://waitbutwhy.com/wp-content/uploads/2013/07/FEATURE-2.png", "https://memegenerator.net/img/images/2729805/willy-wonka.jpg", "https://memegenerator.net/img/images/2485/the-most-interesting-man-in-the-world.jpg", "https://memegenerator.net/img/images/84688/futurama-fry.jpg", "https://memegenerator.net/img/images/1031/success-kid.jpg", "https://memegenerator.net/img/images/6541210/grumpy-cat.jpg", "https://memegenerator.net/img/images/42/joseph-ducreux.jpg", "https://memegenerator.net/img/images/1232401/disaster-girl.jpg", "https://memegenerator.net/img/images/2475876/koala-cant-believe-it.jpg", "https://memegenerator.net/img/images/4290013/sudden-realization-ralph.jpg", "https://memegenerator.net/img/images/627067/ancient-aliens.jpg", "https://memegenerator.net/img/images/1119726/chemistry-cat.jpg", "https://memegenerator.net/img/images/2606719/1889-10-guy.jpg", "https://memegenerator.net/img/images/6881887/evil-toddler-kid2.jpg", "https://memegenerator.net/img/images/1236/angry-arnold.jpg", "https://cdn-images-1.medium.com/max/2000/1*kZ5haMH3Au_Y9xoSZScZjw.png", "https://bfmbrainfall.files.wordpress.com/2016/04/how_silly_are_you_pomelo_cat.jpg?w=376", "https://www.awesomeinventions.com/wp-content/uploads/2018/04/photoshop-man-riding-chicken-silly-things-bored-people-do.jpg", "https://ministryofhappiness.files.wordpress.com/2014/06/19.jpg", "https://i.imgur.com/EbJMP.jpg", "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQO2qc0lmuwkmxap4AOCsjSJwg4EQKA1mFfvxlgPWVax18RR8Db", "http://www.mykidsite.com/wp-content/uploads/2013/03/Silly-Baby.jpg", "https://si.wsj.net/public/resources/images/BN-QC226_bonds1_H_20161003175622.jpg", "https://www.maxpixel.net/static/photo/1x/Love-Frog-Animal-Nature-Heart-Sculpture-Silly-3363217.jpg", "https://sadanduseless.b-cdn.net/wp-content/uploads/2014/10/silly-dog-hat1.jpg", "https://cdn0.wideopencountry.com/wp-content/uploads/2015/09/cow1-FEATURED-793x516.jpg", "https://memestatic.fjcdn.com/pictures/Silly+animal+pictures_6bbd26_6229985.jpg", "https://static.jeffbullas.com/wp-content/uploads/2015/04/How-to-Grow-an-Email-List-3-Case-Studies-on-How-Silly-Online-Quizzes-Produce-Serious-Business-Leads1.jpg", "https://www.thoughtco.com/thmb/jOkozEy57aMiecuw3dPrPALFQPQ=/798x734/filters:no_upscale():max_bytes(150000):strip_icc()/norman-58b8aa3b5f9b58af5c51f5ee.jpg", "https://i.ytimg.com/vi/GHhFtkGfaWU/hqdefault.jpg", "https://i.pinimg.com/originals/85/03/0d/85030dacda1b1f91b92ff77056b17648.jpg", "https://www.thoughtco.com/thmb/NVdH2OxJFm83YXLAF0WS_FEaMxA=/767x640/filters:no_upscale():max_bytes(150000):strip_icc()/roughday-58b8aa1c5f9b58af5c51c9b0.png", "http://www.dumpaday.com/wp-content/uploads/2013/01/funny-pretty-animals.jpg", "https://vignette.wikia.nocookie.net/animaljam/images/3/30/Omg-funny-animals-dog-1.jpg/revision/latest?cb=20140719215428", "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRFLLegjy_vW6CooP-6wHiXAaKXGQOmFEchgI4CeRyki60NInb4Tg", "http://cdn.icepop.com/wp-content/uploads/2018/02/pawsome-topix-com-7-Funny-animals.jpg", "https://amazinganimalphotos.com/wp-content/uploads/2014/11/artist-animals-funny-memes.jpg", "https://2.bp.blogspot.com/-Oz9tTxpw6Qk/WqLPVFXfLfI/AAAAAAAB41Q/Y2jyYo1QuhUstXG2Z3TZ06LOqRmys_sKwCLcBGAs/s1600/funny-animals-307-01.jpg", "https://mmehappy.com/wp-content/uploads/2017/11/top-30-funny-animal-memes-and-quotes-hilarious.jpg" ]; function pick5() { var num_images = local_images.length; var indices = []; var urls = []; for(var i=0; i<slides_per_show; i++) { var idx = Math.floor(Math.random() * num_images); while(indices.includes(idx) || idx >= num_images) { idx = Math.floor(Math.random() * num_images); }; indices.push(idx); } for(var j=0; j<slides_per_show; j++) { urls.push(local_images[indices[j]]); } return urls; } function showSplash() { $("#content").html("<div class='container'>" + "<div class='jumbotron'>" + " <h1>Ignite Karaoke</h1>" + " <p class='lead'>An Ignite talk is a 5-minute talk format "+ " consisting of 20 slides that <em>auto-advance</em> every "+ " 15 seconds. Can you give a 5-slide Ignite talk <b>when you "+ " haven't seen the slides before?</b>" + " </p>" + " <p><a class='btn btn-lg btn-success' href='#' role='button' onClick='launchIgnite();'>Go!</a></p>" + "</div></div>"); }; function showSlide(urls) { if (urls.length == 0) { showSplash(); return; } var url = urls.pop(); $("#content").html("<div class='slide'><img src='" + url + "'/></div>"); var imgWidth = $(".slide img").width(); var imgHeight = $(".slide img").height(); var slideWidth = $(window).width(); var slideHeight = $(window).height(); if (imgHeight >= imgWidth) { $(".slide img").addClass("portrait"); $(".slide img").height(slideHeight); } else { $(".slide img").addClass("landscape"); $(".slide img").width(slideWidth); } setTimeout(function() { showSlide(urls); }, secs_per_slide * 1000); } function launchIgnite() { showSlide(pick5()); } showSplash();
exports.navbarDirective = require('./navbar.js'); exports.navbarDirective = require('./searchcontainer.js');
const app = getApp(); const config = require('./config.js'); const request = (method, options) => { let authToken = wx.getStorageSync('authToken'); let { url } = options; if (options.path) { url = config.baseUrl + options.path; if (options.cache) { const key = options.cacheKey || options.path; const cachedData = wx.getStorageSync(key); if (cachedData) { options.success({ data: cachedData }); } } } wx.request({ url, data: options.data, method, header: { 'X-Toyhouse-Token': authToken }, success(res) { if (res.statusCode === 401) { if (app) { app.resetAuthenticationInfo(); app.login(() => { // retry console.log('retrying...'); authToken = wx.getStorageSync('authToken'); request(options); }); } } else if (res.statusCode === 429) { wx.showToast({ title: '你的操作太快了,休息,休息一会', icon: 'none' }); } else if (res.statusCode === 404 || res.statusCode === 403) { options.fail(res); } else { if (options.cache) { const key = options.cacheKey || options.path; wx.setStorage({ key, data: res.data }); } options.success(res); } } }); }; const get = (options) => { request('get', options); }; const post = (options) => { request('post', options); }; const DELETE = (options) => { request('delete', options); }; const put = (options) => { request('put', options); }; module.exports = { get, post, put, delete: DELETE };
//--------------------------------------以下为表体部分----------------------------------------- function list_change(va,vb){ if (parent.list.form1.elements[va].value!=parent.list.form1.elements[vb].value){ parent.head.form1.biaoti_change.value="yes"; } } //表体页面控制函数 function chukou_list_enter(first,second,value_str) { var focus_str; focus_str=1; switch (first) { case "shouce_contr_item": //手册编号 list_change("shouce_contr_item","shouce_contr_item_old"); if (parent.func.fucCheckNUM(value_str)==0) { alert ("手册序号 项只能输入数字,请重新输入!"); second=first; } else if (value_str != parent.list.form1.shouce_contr_item_old.value) { parent.func.sel_shouce_contr_item (value_str,second); focus_str=0; } break; case "g_name": //品名-- g_name list_change("g_name","g_name_old"); if (value_str.length == 0) { if (g_name_alert.value=="yes"){ alert ("商品名称 项不能为空,请重新输入!"); } else{g_name_alert.value="yes";} second=first; focus_str=0; } break; case "code_t": //税号-- code_t,code_s,unit_1_str,unit_2_str list_change("code_t","code_t_old"); if (parent.func.fucCheckNUM(value_str)==0 && value_str.length != 8) { alert ("商品税号 项只能输入 8 位数字,请重新输入!"); second=first; } else if (value_str != parent.list.form1.code_t_old.value) { parent.func.sel_code_t (value_str,second); focus_str=0; } break; case "code_s": //附加编号 list_change("code_s","code_s_old"); if (value_str != parent.list.form1.code_s_old.value) { parent.func.sr_code_s (value_str,second); focus_str=0; } break; case "g_model": //商品规格/型号-- g_model .replace(/(^\s*)|(\s*$)/g,""); list_change("g_model","g_model_old"); parent.list.form1.g_model.value=value_str; break; case "origin_country_name": //目的地-- origin_country_str list_change("origin_country_name","origin_country_name_old"); if (value_str.length < 2) { alert ("目的国 项只能输入 3 位数国家编码或国家全称!"); second=first; } else if (value_str != parent.list.form1.origin_country_name_old.value ) { parent.func.sel_origin_country_name (value_str,second); focus_str=0; } break; case "g_unit_name": //第一单位-- qty_1 list_change("g_unit_name","g_unit_name_old"); if (value_str.length == 0) { alert ("成交单位 项不能为空,请重新输进境入!"); second=first; } else if (value_str != parent.list.form1.g_unit_name_old.value) { parent.func.sel_g_unit_name (value_str,second); focus_str=0; } break; case "g_qty": //判断第一单位及法定单位-- g_qty list_change("g_qty","g_qty_old"); if (value_str == 0 || parent.func.fucCheckNUM(value_str) ==0 ) { alert ("成交单位数量 项只能输入不为零的数字,请重新输入!"); second=first; } else { if (parent.list.form1.g_qty_old.value=="0") { parent.list.form1.g_qty_old.value=parent.list.form1.g_qty.value; } if (parent.list.form1.g_qty.value!=parent.list.form1.g_qty_old.value) { parent.list.form1.g_qty_old.value=parent.list.form1.g_qty.value; var selvalue = prompt("选择 1 更新单价,选择 2 更新总价","1"); if (selvalue=="1") { //parent.list.form1.decl_price.value=parent.list.form1.trade_total.value/parent.list.form1.g_qty.value; parent.func.sel_trade_total (parent.list.form1.trade_total.value); } else if (selvalue=="2") { //parent.list.form1.trade_total.value=parent.list.form1.decl_price.value*parent.list.form1.g_qty.value; parent.func.sel_decl_price (parent.list.form1.decl_price.value); } } //alert(parent.list.form1.g_qty_old.value+"/"+parent.list.form1.g_qty.value); parent.func.sel_g_qty (value_str,second); focus_str=0; } break; case "qty_1": list_change("qty_1","qty_1_old"); if (parent.list.form1.unit_1.value != 0) if (value_str == 0 || parent.func.fucCheckNUM(value_str) ==0 ) { alert ("法定单位数量 项只能输入不为零的数字,请重新输入!"); second=first; } else { if (value_str != parent.list.form1.qty_1_old.value) { parent.list.form1.qty_1.value=parent.func.format_num(value_str,3); parent.list.form1.qty_1_old.value=parent.func.format_num(value_str,3); } if (parent.list.form1.unit_2.value == 0) second="trade_curr_name"; else { parent.list.form1.qty_2.disabled=false; second="qty_2"; } } break; case "qty_2": //第二数量-- qty_2 list_change("qty_2","qty_2_old"); if (parent.list.form1.unit_2.value != 0) if (value_str == 0 || parent.func.fucCheckNUM(value_str) ==0 ) { alert ("第二单位数量 项只能输入不为零的数字,请重新输入!"); second=first; } else if (value_str != parent.list.form1.qty_2_old.value) { parent.list.form1.qty_2.value=parent.func.format_num(value_str,3); parent.list.form1.qty_2_old.value=parent.func.format_num(value_str,3); } break; case "trade_curr_name": list_change("trade_curr_name","trade_curr_name_old"); if (value_str.length == 0) { alert ("贸易币制 项不能为空,请重新输入!"); second=first; } else if (value_str != parent.list.form1.trade_curr_name_old.value) { parent.func.sel_trade_curr_name (value_str,second); focus_str=0; } break; case "decl_price": //单价-- decl_price list_change("decl_price","decl_price_old"); if (parent.func.fucCheckNUM(value_str) ==0) { alert ("单价 项只能输入数字,请重新输入!"); second=first; } else if (value_str != parent.list.form1.decl_price_old.value) { parent.func.sel_decl_price (value_str); focus_str=0; } break; case "trade_total": //总价-- trade_total list_change("trade_total","trade_total_old"); if ((parent.func.fucCheckNUM(value_str) ==0 || parent.list.form1.decl_price.value == 0 ) && value_str == 0) { alert ("总价 项只能输入数字,请重新输入!"); second=first; } else if (value_str != parent.list.form1.trade_total_old.value) { parent.func.sel_trade_total (value_str); focus_str=0; } break; case "use_to_name": //生产厂家-- use_to_str list_change("use_to_name","use_to_name_old"); if (value_str.length == 0) { alert ("用途 项不能为空,请重新输入!"); second=first; } else if (value_str != parent.list.form1.use_to_name_old.value) { parent.func.sel_use_to_name (value_str,second); focus_str=0; } break; case "duty_mode_name": //征免性质-- duty_mode_str list_change("duty_mode_name","duty_mode_name_old"); if (value_str.length == 0) { alert ("征免性质 项不能为空,请重新输入!"); second=first; } else if (value_str != parent.list.form1.duty_mode_name_old.value) { parent.func.sel_duty_mode_name (value_str,second); focus_str = 0; } else if (parent.list.form1.per_weight.type=="hidden") parent.list.form1.elements[second].focus(); parent.list.form1.elements[second].select(); break; case "per_weight": //重量 list_change("per_weight","per_weight_old"); if (value_str.length == 0 || parent.func.fucCheckNUM(value_str) == 0) { alert ("重量 项不能为空,请重新输入!"); second=first; } else if (value_str != parent.list.form1.per_weight_old.value) { parent.list.form1.per_weight_old.value=parent.list.form1.per_weight.value; parent.list.form1.work_usd.focus(); focus_str = 0; } break; case "list_print": //打印报关单 if (value_str.length == 0 ) { alert ("报关单号码为空!"); second=first; } else{ focus_str = 0; main_win = window.open('../bgdprint/print_type.asp?pre_entry_id='+value_str,'_blank'); } break; case "list_print_jzx": //打印集装箱 if (value_str.length == 0 ) { alert ("报关单号码为空!"); second=first; } else{ focus_str = 0; main_win = window.open('../bgdprint/jzxprint.asp?pre_entry_id='+value_str,'_blank'); } break; case "work_usd": //工缴费 list_change("work_usd","work_usd_old"); parent.list.form1.work_usd.value=value_str; break; case "prdt_no": //成品版本 list_change("prdt_no","prdt_no_old"); if(parent.func.fucCheckNUM3(value_str) == 0) { value_str=""; focus_str=0; alert("成品版本输入有误,请重新输入"); } parent.list.form1.prdt_no.value=value_str; break; default: alert ("发生未知错误,请与技术员取得联系"); } if (focus_str == 1) { parent.list.form1.elements(second).select(); parent.list.form1.elements(second).focus(); } }
'use strict' let chalk = require('chalk'); module.exports = [{ type: 'input', name: 'name', message: 'Enter name', default: 'my-module' }, { type: 'input', name: 'targetDir', message: 'Enter folder directory', default: './modules' }]
const assert = require('assert'); function bar() { while (false) {}; } function Foo() { while(false) {}; var a = {b: 1} bar(); return a } assert.equal((new Foo()).b, 1)
// pages/pt_dz/pt_dz.js const app = getApp(); var bcode; var detail_id; var token; var cid; var province_id = ''; var city_id = ''; var citys = []; var areas = []; var towns = []; var area_id = ''; var town_id = ''; Page({ /** * 页面的初始数据 */ data: { addres:[], prov:[], citys:[], names:'', phones:'', provinces: '', addresss: '', provinceId:'', cityId:'', areaId:'', townId:'', address:'', province: [], poindex: 0, city: [], cindex: 0, area: [], aindex: 0, town: [], tindex: 0, isDefault:0, checked:false, isDefaults:false, iscity:true, isqu: true, isjie: true, }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { var that = this; // 获取所有省 var province = [{ id: '', name: '请选择所在省' }] wx.request({ url: app.data.urlmall + "/apparea/nextlist.do", data: { grade: "1", }, method: 'POST', header: { 'content-type': 'application/x-www-form-urlencoded' }, dataType: 'json', success: function (res) { console.log(res.data.data) if (res.data.status === 100) { for (var i in res.data.data) { province.push(res.data.data[i]) } that.setData({ province: province }) } else { wx.showToast({ title: res.data.msg, icon: 'none' }) } } }) }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () { }, /** * 生命周期函数--监听页面显示 */ onShow: function () { wx.getStorage({ key: 'userinfo', success: function (res) { bcode = res.data.user_id; //console.log(bcode + "----") }, }) }, /** * 生命周期函数--监听页面隐藏 */ onHide: function () { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function () { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { }, /** * 用户点击右上角分享 */ onShareAppMessage: function () { console.log(wx.getStorageSync("userinfo").is_actor) var isactor = wx.getStorageSync("userinfo").is_actor; var isleagure = wx.getStorageSync("userinfo").shareIdentityType; var hasdiol = wx.getStorageSync("userinfo").idol_id; var bcode; var scode; if (isactor == 2) { bcode = wx.getStorageSync("userinfo").user_id; scode = wx.getStorageSync("userinfo").user_id; } else if (isleagure != 0 && hasdiol == null) { bcode = wx.getStorageSync("userinfo").user_id; scode = wx.getStorageSync("userinfo").user_id; } else if (isleagure != 0 && hasdiol != null) { bcode = wx.getStorageSync("userinfo").idol_id; scode = wx.getStorageSync("userinfo").user_id; } else if (hasdiol != null || hasdiol != "") { bcode = wx.getStorageSync("userinfo").idol_id; scode = wx.getStorageSync("userinfo").user_id; } else { bcode = wx.getStorageSync("userinfo").user_id; scode = wx.getStorageSync("userinfo").user_id; } return { title: '一手明星资源,尽在娱乐世界!', path: '/pages/pt_mall/pt_mall?bindcode=' + bcode + "&scode=" + scode } }, getaddress: function () { var that = this; wx.request({ url: app.data.urlmall + "/appuseraddress/add.do", data: { name: that.data.names, phone: that.data.phones, provinceId: province_id, cityId: city_id, areaId: area_id, townId: town_id, address: that.data.addresss, token: wx.getStorageSync("ptoken"), isDefault:that.data.isDefault, }, method: 'POST', header: { 'content-type':'application/x-www-form-urlencoded' }, dataType: 'json', success: function (res) { console.log(res.data.data) if (res.data.status === 100) { wx.showToast({ title: '添加成功', icon: 'success', duration: 1000 }) setTimeout(function () { wx.navigateBack({ delta: 1, }) }, 1000) } else { wx.showToast({ title: res.data.msg, icon: 'none' }) } } }) }, bindname:function(e){ this.setData({ names: e.detail.value }) }, bindphone: function (e) { this.setData({ phones: e.detail.value }) }, bindregion: function (e) { this.setData({ provinces: e.detail.value }) }, binddetail: function (e) { this.setData({ addresss: e.detail.value }) }, submit:function(e){ var that = this; var phonereg = that.data.phones; var namereg = that.data.names; var province_idreg = province_id; var city_idreg = city_id; var area_idreg = area_id; var town_idreg = town_id; var addressreg = that.data.addresss var phonetel = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1})|(17[0-9]{1}))+\d{8})$/; if (namereg == '') { wx.showToast({ title: '请输入用户名', icon: 'none', duration: 1000, mask: true }) return false } else if (phonereg == '') { wx.showToast({ title: '手机号不能为空', icon:'none' }) return false } else if (phonereg.length != 11) { wx.showToast({ title: '手机号长度有误!', icon: 'none', duration: 1500 }) return false; } else if (province_idreg == '') { wx.showToast({ title: '请输入所在省', icon: 'none', duration: 1500 }) return false; } else if (city_idreg == '') { wx.showToast({ title: '请输入所在市', icon: 'none', duration: 1500 }) return false; } else if (area_idreg == '') { wx.showToast({ title: '请输入所在区', icon: 'none', duration: 1500 }) return false; } else if (town_idreg == '') { wx.showToast({ title: '请输入所在街道', icon: 'none', duration: 1500 }) return false; } else if (addressreg == '') { wx.showToast({ title: '请输入详细地址', icon: 'none', duration: 1500 }) return false; } if (!phonetel.test(phonereg)) { wx.showToast({ title: '手机号有误!', icon: 'none', duration: 1500 }) return false; } return that.getaddress(); }, // 省跳市 getprov:function(e){ var that = this; console.log(e) that.setData({ //给变量赋值 poindex: e.detail.value, cindex: 0, aindex: 0, tindex: 0 }) province_id = that.data.province[e.detail.value].id; city_id = ''; area_id = ''; town_id = ''; console.log(province_id); citys = [{ id: '', name: '请选择所在市' }] // 获取所有市 wx.request({ url: app.data.urlmall + "/apparea/nextlist.do", data: { grade:'2', id: province_id }, method: 'POST', header: { 'content-type': 'application/x-www-form-urlencoded' }, dataType: 'json', success: function (res) { console.log(res.data.data) if (res.data.status == 100) { for (var i in res.data.data) { citys.push(res.data.data[i]) } that.setData({ city: citys, iscity: false }) } else { wx.showToast({ title: res.data.msg, icon: 'none', duration: 500 }) } } }) }, // 市跳区 getcity: function(e){ var that = this; that.setData({ //给变量赋值 cindex: e.detail.value, aindex: 0, tindex: 0 }) city_id = that.data.city[e.detail.value].id; area_id = 0; town_id = 0; console.log(city_id); areas = [{ id: '', name: '请选择所在区' }] that.setData({ isqu: false }) // 获取所有区 wx.request({ url: app.data.urlmall + "/apparea/nextlist.do", data: { grade: '3', id: city_id }, method: 'POST', header: { 'content-type': 'application/x-www-form-urlencoded' }, dataType: 'json', success: function (res) { console.log(res.data.data) if (res.data.status == 100) { for (var i in res.data.data) { areas.push(res.data.data[i]) } that.setData({ area: areas }) } else { wx.showToast({ title: res.data.msg, icon: 'none', duration: 500 }) } } }) }, // 区跳街道 getarea: function (e) { var that = this; that.setData({ //给变量赋值 aindex: e.detail.value, tindex: 0 }) area_id = that.data.area[e.detail.value].id; town_id = ''; console.log(area_id); towns = [{ id: '', name: '请选择所在街道' }] that.setData({ isjie: false }) // 获取街道 wx.request({ url: app.data.urlmall + "/apparea/nextlist.do", data: { grade: '4', id: area_id }, method: 'POST', header: { 'content-type': 'application/x-www-form-urlencoded' }, dataType: 'json', success: function (res) { console.log(res.data.data) if (res.data.status == 100) { for (var i in res.data.data) { towns.push(res.data.data[i]) } that.setData({ town: towns }) } else { wx.showToast({ title: res.data.msg, icon: 'none', duration: 500 }) } } }) }, gettown: function (e) { var that = this; that.setData({ //给变量赋值 tindex: e.detail.value, }) town_id = that.data.town[e.detail.value].id; console.log(town_id); }, //设置默认地址 checkedTap:function(e){ var that = this; var checked = that.data.checked; var isDefaults = that.data.isDefaults console.log(isDefaults) that.setData({ checked: !checked, isDefaults: !isDefaults }) if (!isDefaults) { that.setData({ isDefault: 1 }) console.log(that.data.isDefault) } else { that.setData({ isDefault: 0 }) console.log(that.data.isDefault) } } })
import React, { Component } from 'react'; import { View, StyleSheet, Text } from 'react-native'; export default class Header extends Component { render() { return ( <View style={ [styles.container, this.props.data.isPro && styles.wrapperPro] }> <View style={ styles.wrapperName }> <Text style={ [styles.textName, this.props.data.isPro && styles.textNamePro] }>{ this.props.data.nom }</Text> <Text style={ [styles.textName, this.props.data.isPro && styles.textNamePro] }>{ this.props.data.prenom }</Text> </View> <Text style={ [styles.textStatut, this.props.data.isPro && styles.textStatutPro] }>{ this.props.data.statut }</Text> </View> ) } } const styles = StyleSheet.create({ container: { display: 'flex', alignItems: 'center', padding: 8, backgroundColor: '#2ab5b5', width: "100%" }, wrapperName: { display: 'flex', flexDirection: 'row' }, wrapperPro: { backgroundColor: '#333', }, textStatut: { fontSize: 12, fontWeight: '300', color: '#333', fontFamily: 'roboto-regular' }, textStatutPro: { color: '#fff' }, textName: { fontSize: 24, color: '#333', fontWeight: '600', marginRight: 8, fontFamily: 'roboto-bold' }, textNamePro: { color: '#fff' }, wrapperPro: { backgroundColor: '#333', }, });
export class Navigation extends HTMLElement { static get observedAttributes() { return Object.keys(this.onAttributeChanged); } static get onAttributeChanged() { return { loggedin: Navigation.prototype.onLoggedinAttributeChanged, } } constructor() { super(); const template = document.getElementById("Navigation"); const fragment = document.importNode(template.content, true); this.appendChild(fragment); this.$loggedout = $('.navigation-loggedout'); this.$loggedin = $('.navigation-loggedin'); this.$loggedin.css('display', 'none'); } attributeChangedCallback(attrName, oldVal, newVal) { const handler = Navigation.onAttributeChanged[attrName]; if (handler) { handler.call(this, oldVal, newVal); } } onLoggedinAttributeChanged(oldVal, newVal) { if (newVal !== null) { this.$loggedout.css('display', 'none'); this.$loggedin.css('display', ''); } else { this.$loggedout.css('display', ''); this.$loggedin.css('display', 'none'); } } }
define(function() { if(!Element.prototype.triggerEvent) { Element.prototype.triggerEvent = function(type) { var event; if (document.createEvent) { event = new Event(type); this.dispatchEvent(event); } else { event = document.createEventObject(); this.fireEvent('on' + type, event); } }; } });
import axios from 'axios'; import {history} from '../../History'; export const login_success = (data) => ({ type: 'LOGIN_SUCCESS', data }); export const login_error = () => ({ type: 'LOGIN_ERROR' }); export const login_request = (username,password) => { const form_data = { username: username, password: password }; return function(dispatch) { console.log(form_data); axios({ method: 'post', url: 'http://icv2.mordorintelligence.com:81/login', data: form_data }) .then(response => { console.log(response); dispatch(login_success(response.data.user)); history.push('/protected'); }) .catch((error) => { console.log(error); dispatch(login_error()); }) } }; export const logout = () => ({ type: 'LOGOUT' }); export const startLogout = () => { return function(dispatch) { dispatch(logout()); history.push('/'); } };
import QUnit from 'qunit'; export default function setupFastbootRootElement({ beforeEach, afterEach }) { beforeEach(function() { Object.defineProperty(QUnit.assert.dom, 'rootElement', { get: function() { return document.querySelector('#ember-testing [data-test-fastboot-container]'); }, enumerable: true, configurable: true, }); }); afterEach(function() { Object.defineProperty(QUnit.assert.dom, 'rootElement', { get: function() { return document.querySelector('#ember-testing'); }, enumerable: true, configurable: true, }); }); }
angular.module('ngApp.breakBulk').controller("selectCustomersController", function ($scope, $uibModal, ModalService, config) { $scope.check = false; $scope.breakbulkCollapse = function () { $scope.breakbulkShow = !$scope.breakbulkShow; }; $scope.addressCollapse = function () { $scope.addressShow = !$scope.addressShow; }; $scope.customerInfoClick=function(){ $scope.customerInfo = true; $scope.purchaseOrderInfo = false; $scope.saveInfo = false; }; $scope.purchaseOrderInfoClick = function () { $scope.purchaseOrderInfo = true; $scope.customerInfo = false; $scope.saveInfo = false; }; $scope.saveOrderInfoClick = function () { $scope.saveInfo = true; $scope.customerInfo = false; $scope.purchaseOrderInfo = false; }; $scope.gridCheck = function () { $scope.grid = !$scope.grid; }; $scope.checkClick = function () { $scope.check = !$scope.check; }; //add-edit purchase order code $scope.addEditPurchaseOrder = function () { ModalInstance = $uibModal.open({ Animation: true, controller: 'breakbulkBookingAddEditPurchaseOrderController', templateUrl: 'breakbulk/breakbulkPurchaseOrder/breakbulkBookingAddEditPurchaseOrder.tpl.html', keyboard: true, windowClass: 'CustomerAddress-Edit', size: 'lg', backdrop: 'static' }); }; //end //confirm code $scope.confirmClick = function () { ModalInstance = $uibModal.open({ Animation: true, //controller: 'customerAddressBookAddEditController', templateUrl: 'breakbulk/confirmationPopup/confirmationPopup.tpl.html', keyboard: true, windowClass: '', size: 'md', backdrop: 'static' }); }; //end //data code here $scope.companyName = [ { id: 1, companyName: 'Irays SoftTech Pvt Ltd.', customerName: 'Pushkar Thapliyal', check:true }, { id: 2, companyName: 'Hindustan Pvt Ltd.', customerName: 'Manish Jadli', check: false }, { id: 3, companyName: 'Bharat Heavy Electronic Ltd.', customerName: 'Ram Ramacharya', check: false }, { id: 4, companyName: 'Dabur Pvt Ltd.', customerName: 'Raman Thundr', check: false }, { id: 5, companyName: 'Whytelcliff Pvt Ltd.', customerName: 'Jack Sam', check: false }, { id: 6, companyName: 'Cliff Premiums Pvt Ltd.', customerName: 'Alex Ratherford', check: false }, { id: 7, companyName: 'FRAYTE Logistics Ltd.', customerName: 'John Peterson', check: false }, { id: 8, companyName: 'Lionstar Manufacturing Ltd.', customerName: 'Max Wilermuth', check: false }, { id: 9, companyName: 'Star Jin Hui Garment Company Ltd.', customerName: 'Marshal Stepherd', check: false }, { id: 10, companyName: 'Vytal Support (Hong Kong) Ltd.', customerName: 'Alex Brooke', check: false }, { id: 11, companyName: 'Vytal Support (Thailand) Ltd.', customerName: 'Jack Karlis', check: false }, { id: 12, companyName: 'Whytelcliff Consultants Ltd.', customerName: 'Stepherd Johnson', check: false }, { id: 13, companyName: 'Whytelcliff Group Ltd.', customerName: 'Trnyp Hook', check: false }, { id: 14, companyName: 'Childs Own Ltd.', customerName: 'Illena Dcruze', check: false }, { id: 15, companyName: 'Irays SoftTech Pvt Ltd.', customerName: 'Berlin Zrerk', check: false } ]; //end function init() { $scope.ImagePath = config.BUILD_URL; $scope.customerInfo = true; $scope.breakbulkShow = false; $scope.addressShow = false; //$scope.check = false; } init(); });
const user = { id: 1, friends: [], name: 'Hugo', url: 'https://codewithhugo.com' }; test('should have right id and name', () => { expect(user.id).toEqual(1); expect(user.name).toEqual('Hugo'); });
var num1; var num2; num1 = prompt("Enter Number 1"); num2 = prompt("Enter Number 2"); var mod = parseInt(num1)%parseInt(num2); document.write("Modulus of "+num1+" and "+num2+" is "+mod);
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) // Использовал до записи в хранилище export default new Vuex.Store({ state: { greenOn: false, handlechange: false, stopTimeout: false }, getters: { greenFlag(state) { return state.greenOn }, getHandleChange(state) { return state.handlechange } }, mutations: { setGreenOn(state) { state.greenOn = true }, setGreenOff(state) { state.greenOn = false }, setHandleChange(state) { state.handlechange = true } } })
// Single responsibility // https://github.com/johnpapa/angular-styleguide#style-y001 // https://github.com/johnpapa/angular-styleguide#style-y010 (function() { 'use strict'; // https://github.com/johnpapa/angular-styleguide#style-y024 angular .module('crud') .controller('PersonController', PersonController); function PersonController() { // https://github.com/johnpapa/angular-styleguide#style-y032 var vm = this; vm.personEmail; vm.personName; vm.persons = [ {personName: 'Diego Gaulke', personEmail: 'insonix@gmail.com'} , {personName: 'Theodore Roosevelt', personEmail: 'roosevelt@whitehouse.com'} ]; // https://github.com/johnpapa/angular-styleguide#style-y033 vm.addPerson = addPerson; vm.removePerson = removePerson; /** According to https://github.com/johnpapa/angular-styleguide#style-y035 the logic of addPerson() and removePerson() should be in a service. I prefer to leave the logic here for better understanding of the code. **/ function addPerson() { vm.persons.push({personName: vm.personName, personEmail: vm.personEmail} ); vm.personName = ''; vm.personEmail = ''; } function removePerson(person) { var index = vm.persons.indexOf(person); if (index > -1) { vm.persons.splice(index, 1); } } } })();
{ clicked = false; //elementen aanmaken const $ratingMsg = document.createElement(`p`); document.querySelector(`.rating`).appendChild($ratingMsg); $ratingMsg.className = `rating__text`; const ratingPicked = () => { //toon tekst bij click const $ratingMsg = document.querySelector(`.rating__text`); $ratingMsg.textContent = `Bedankt voor uw beoordeling.`; clicked = true; console.log(`clicked = ${clicked}`); }; const sterClicked = event => { let sterClassAsArray = event.target.classList[1].split(``); // split om de class in letters op te splitsen : ["s", "t", "a", "r", "_", "_", "1"] // console.log(sterClassAsArray); let index = sterClassAsArray[sterClassAsArray.length - 1]; let teller = 0; //opvullen if (clicked === true) { //als clicked true is zet hem dan op false zodat je een nieuwe kan aanklikken clicked = false; } resetStars(); for (let ster of $sterren.children) { if (teller < index) { ster.src = "/assets/img/svg/star_filled.svg"; teller++; clicked = true; //meegeven dat er op een ster geklikt is ratingPicked(); } } }; const sterHovered = event => { //ster invullen wnr hover if (clicked === false) { let sterClassAsArray = event.target.classList[1].split(``); // console.log(sterClassAsArray); let index = sterClassAsArray[sterClassAsArray.length - 1]; let teller = 0; //opvullen resetStars(); for (let ster of $sterren.children) { if (teller < index) { ster.src = "/assets/img/svg/star_filled.svg"; teller++; } } } }; const resetStars = () => { if (clicked === false) { //als er nog nergens op geklikt is reset dan for (let ster of $sterren.children) { ster.src = "/assets/img/svg/star.svg"; } } }; const init = () => { $sterren = document.querySelector(`.stars`); console.log($sterren.children); for (let ster of $sterren.children) { ster.addEventListener(`click`, sterClicked); ster.addEventListener(`mouseover`, sterHovered); ster.addEventListener(`mouseleave`, resetStars); } }; init(); }
//** intro - login, register router **// module.exports = function(app){ var express = require('express'); var router = express.Router(); //mysql module var mysql = require('mysql'); var conn = mysql.createConnection({ host : 'localhost', user : 'root', port : 3308, password : '123147', database : 'smart_sns' }); conn.connect(); var fileName = ""; // file system module var fs = require('fs'); // file upload module var multer = require('multer'); // resize image module var gm = require('gm'); // set file path & file name var _storage = multer.diskStorage( { destination: function(req, file, cb){ cb(null, 'public/profile_image'); }, filename: function(req, file, cb){ console.log('into multer function :::'); fileName =file.originalname; console.log('original name' + fileName); cb(null, fileName); } }); router.post('/login', function(req, res){ console.log('# post/login'); console.log(req.body); var query = 'select * from user where user_id = ? and user_pw = ?'; conn.query(query, [req.body.user_id, req.body.user_pw], function(err, rows){ if(err){ console.log(err); res.status(500).send(); // status code 500 : 내부 서버 오류 (여기서 db오류) }else{ if(rows[0]){ console.log('-> login OK'); res.status(200).send(JSON.stringify(rows[0])); }else{ console.log(req.body.user_id +", " + req.body.user_pw); console.log('-> login failure'); res.status(401).send(); // status code 401 : 권한없음 } } }); }); router.post('/regist', function(req, res){ console.log('# post/regist'); console.log('regist request body : '+req.body); var upload = multer({storage: _storage}).single('profile_image'); upload(req, res, function(err){ if(err){ console.log(err); } else { console.log('-> save the profile image!!'); gm('./public/profile_image/'+fileName).resize(460, null).write('./public/profile_image/'+fileName, function(err){ // resize : 920 -> 460 if(err){ console.log(err); }else{ console.log('-> profile image resize success!'); var query = 'insert into user (user_id, user_pw, user_name, user_age, user_gender,'+ 'user_interest_bighash1, user_interest_bighash2, user_interest_bighash3, user_profile_url) values (?, ?, ?, ?, ?, ?, ?, ?, ?)'; conn.query(query, [req.body.id, req.body.pw, req.body.name, req.body.user_age, req.body.gender, req.body.bighash1, req.body.bighash2, req.body.bighash3, fileName], function(err, rows){ if(err){ console.log('-> '+err); res.status(505).send(); }else{ console.log('-> regist OK'); res.status(200).send(); } }); } }); } }); }); return router; };
export const apiKey = 'aa398662a381f77f9063d6d33e5b8a2e';
import createRootContainer from './RootContainer'; import createOrderPageContainer from './OrderPageContainer'; import createEditDialogContainer from './EditPageContainer'; const createBusiness = (urls, statePath, unique='id', onSearch, importCode, jurisdictionKey) => { const {Container, afterEditActionCreator} = createOrderPageContainer(urls, statePath, unique, importCode); const EditDialogContainer = createEditDialogContainer(urls, statePath.concat('edit'), afterEditActionCreator, onSearch); return createRootContainer(urls, statePath, Container, EditDialogContainer, importCode, jurisdictionKey); }; export default createBusiness;
import React from 'react'; const Munro = ({munro}) => ( <div> <h3>{munro.name}</h3> <p>Height: {munro.height}</p> <p>Meaning: {munro.meaning}</p> </div> ); export default Munro;
import firebase from '@react-native-firebase/app'; import '@react-native-firebase/auth'; import firestore from '@react-native-firebase/firestore'; import ReduxSagaFirebase from 'redux-saga-firebase'; import {call, put} from 'redux-saga/effects'; import {fetchEventsSuccess, fetchEventsFailed} from '../actions/events'; const firebaseApp = firebase.apps[0]; const rsf = new ReduxSagaFirebase(firebaseApp); export function* fetchEvents() { try { const data = []; const snapshot = yield call( rsf.firestore.getCollection, firestore().collection('Events').orderBy('time_begin', 'desc'), ); snapshot.forEach((querySnapshot) => { data.push(Object.assign(querySnapshot.data(), {id: querySnapshot.id})); }); yield put(fetchEventsSuccess(data)); } catch (error) { console.log('FETCH EVENTS', error); yield put(fetchEventsFailed(error)); } }
import React from 'react' import { Switch, Route } from 'react-router-dom' import ComponentA from './components/ComponentA'; import ComponentB from './components/ComponentB'; import ComponentC from './components/ComponentC'; import ComponentD from './components/ComponentD'; import Shop from './components/Shop'; // COMP 42F 42G export default ( <Switch> <Route exact path='/' component={ComponentA} /> <Route path='/componentB' component={ComponentB} /> <Route path='/componentC' component={ComponentC} /> <Route path='/componentD/:id' component={ComponentD} /> <Route path='/shop' component={Shop} /> </Switch> )
import React from "react"; const HomeView = () => { return ( <div> <h3>Anasayfa ! </h3> </div> ); }; export default HomeView;
import React from "react"; import "./TodoItem.css"; export const TodoItem = ({toggleTodo, todo: {id, text, done}}) => { return <li className={done ? 'done' : ''} onClick={() => toggleTodo(id)} >{text}</li> }
import React, { Component } from 'react'; import { Row, Col, form, FormGroup, FormControl, InputGroup, Glyphicon, ControlLabel, HelpBlock } from 'react-bootstrap'; import Dropzone from 'react-dropzone' import DatePicker from 'react-datepicker'; import moment from 'moment'; import { FormattedMessage } from 'react-intl'; import verifApi from '../api' import 'react-day-picker/lib/style.css'; import 'react-datepicker/dist/react-datepicker.css'; import { AlertList, Alert, AlertContainer } from "react-bs-notifier"; class Indent extends Component { constructor(props, context) { super(props, context); this.handleChange = this.handleChange.bind(this); this.state = { value: '', frontSidePhoto: [], backSidePhoto: [], documentTypeId: null, idDocumentTypes: [], documentNumber: null, issueDate: null, expiryDate: null, message: '' }; } componentWillMount = () => { let self = this verifApi.getIdDocumentTypes().then(function (data) { self.setState({ idDocumentTypes: data.items }); }) verifApi.getIdentificationVerification().then(function (data) { self.setState({ frontSidePhoto: data.frontSidePhoto == null ? [] : [data.frontSidePhoto], backSidePhoto: data.backSidePhoto == null ? [] : [data.backSidePhoto], documentNumber: data.documentNumber, documentTypeId: data.documentTypeId, issueDate: data.issueDate == null ? null : moment(data.issueDate), expiryDate: data.expiryDate == null ? null : moment(data.expiryDate) }); }) } getValidationState() { const length = this.state.value.length; if (length > 10) return 'success'; else if (length > 5) return 'warning'; else if (length > 0) return 'error'; return null; } handleChange(e, key) { this.setState({ [key]: e.target.value }); } setIssueDate(d) { this.setState({ issueDate: d }); } setExpiryDate(d) { this.setState({ expiryDate: d }); } onDrop(side, files) { this.setState({ [side]: files }); } uploadDocumentSignature() { const formData = new FormData(); formData.append('frontSidePhoto', this.state.frontSidePhoto[0]) formData.append('backSidePhoto', this.state.backSidePhoto[0]) formData.append('documentNumber', this.state.documentNumber) formData.append('documentTypeId', this.state.documentTypeId) if (this.state.issueDate != null) { formData.append('issueDate', this.state.issueDate.format()) } if (this.state.expiryDate != null) { formData.append('expiryDate', this.state.expiryDate.format()) } verifApi.uploadIdentificationVerification(formData).then((data) => { this.setState({message: 'Update successfully.'}) }) } onMessageDismiss(){ this.setState({message: ''}) } render() { return ( <Row className="ver-indent of no-margin"> <Col mdOffset={2} md={8} xsOffset={1} xs={10} className='app-card'> <Row className="no-margin"> <Col className="b-text black left m-bottom-40"> <FormattedMessage id='iv.title' defaultMessage='Identification Verification' /> </Col> </Row> <Row> <Col md={6} xs={12}> <Col className='left p-r-50 m-bottom-20' > <FormGroup controlId="formControlsFile"> <ControlLabel className='grey m-bottom'> <FormattedMessage id='iv.frontId' defaultMessage='FRONT SIDE PHOTO ID DOCUMENT' /> </ControlLabel> <section> <div className="dropzone"> <Dropzone onDrop={this.onDrop.bind(this, 'frontSidePhoto')}> <div className='app-dz-text'> <FormattedMessage id='verif.dz' defaultMessage='Try dropping some files here, or click to select files to upload.' /> </div> </Dropzone> </div> <aside> <h5 className='bold'> <FormattedMessage id='verif.dropFile' defaultMessage='Dropped files' /> </h5> <ul> { this.state.frontSidePhoto.map(f => <li className='blue bold' key={f.name}><a href={f.path} target='_blank'>{f.name}</a> - {f.size} bytes</li>) } </ul> </aside> </section> </FormGroup> </Col> <Col className='left p-r-50 m-bottom-20' > <FormGroup controlId="formControlsFile"> <ControlLabel className='grey m-bottom'> <FormattedMessage id='iv.backId' defaultMessage='BACK SIDE PHOTO ID DOCUMENT' /> </ControlLabel> <section> <div className="dropzone"> <Dropzone onDrop={this.onDrop.bind(this, 'backSidePhoto')}> <p className='app-dz-text'> <FormattedMessage id='verif.dz' defaultMessage='Try dropping some files here, or click to select files to upload.' /> </p> </Dropzone> </div> <aside> <h5 className='bold'> <FormattedMessage id='verif.dropFile' defaultMessage='Dropped files' /> </h5> <ul> { this.state.backSidePhoto.map(f => <li className='blue bold' key={f.name}><a href={f.path} target='_blank'>{f.name}</a> - {f.size} bytes</li>) } </ul> </aside> </section> </FormGroup> </Col> <Col className='left p-r-50 m-bottom-20' > <FormGroup controlId="formBasicText"> <ControlLabel className='grey m-bottom'> <FormattedMessage id='iv.idType' defaultMessage='ID DOCUMENT TYPE' /> </ControlLabel> <FormControl componentClass="select" className='input-noaddon' value={this.state.documentTypeId} onChange={(e) => this.handleChange(e, 'documentTypeId')}> <option value="select"> <FormattedMessage id='verif.select' defaultMessage='select' /> </option> { this.state.idDocumentTypes.map((c) => { return <option value={c.id}>{c.term}</option> }) } </FormControl> </FormGroup> </Col> <Col className='left p-r-50 m-bottom-20' > <FormGroup controlId="formBasicText" validationState={this.getValidationState()}> <ControlLabel className='grey m-bottom'> <FormattedMessage id='iv.idNum' defaultMessage='ID DOCUMENT NUMBER' /> </ControlLabel> <FormControl type="text" value={this.state.documentNumber} placeholder="ID DOCUMENT NUMBER" onChange={(e) => this.handleChange(e, 'documentNumber')} className='input-noaddon' /> </FormGroup> </Col> <Col className='left m-bottom-20' > <FormGroup controlId="formBasicText"> <ControlLabel className='grey m-bottom '> <FormattedMessage id='iv.issueDate' defaultMessage='ISSUE DATE' /> </ControlLabel> <DatePicker peekNextMonth showMonthDropdown showYearDropdown dropdownMode="select" selected={this.state.issueDate} onChange={(d) => this.setIssueDate(d)} className="form-control" /> </FormGroup> </Col> <Col className='left m-bottom-40' > <FormGroup controlId="formBasicText"> <ControlLabel className='grey m-bottom '> <FormattedMessage id='iv.expiryDate' defaultMessage='EXPIRY DATE' /> </ControlLabel> <DatePicker peekNextMonth showMonthDropdown showYearDropdown dropdownMode="select" selected={this.state.expiryDate} onChange={(e) => this.setExpiryDate(e)} className="form-control" /> </FormGroup> </Col> </Col> <Col md={6} xs={12} className='black'> <p className='left m-bottom-20'> <FormattedMessage id='iv.other1' defaultMessage='Valid Government-Issued Identification Documents include:' /> </p> <p className='left m-bottom-20'> <FormattedMessage id='iv.other2' defaultMessage='High Quality Photos Or Scanned Images Of These Documents Are Acceptable (less than 10MB each).' /> </p> <p className='left m-bottom-20'> <FormattedMessage id='iv.other3' defaultMessage='HIGH QUALITY (colour images, 300dpi resolution or higher). VISIBLE IN THEIR ENTIRETY (watermarks are permitted). VALID, with the expiry date clearly visible.' /> </p> <p className='left m-bottom-20'> <FormattedMessage id='iv.other4' defaultMessage='Limitations On Acceptable Document Types May Apply.' /> </p> </Col> </Row> </Col> <Col mdOffset={7} md={3} xsOffset={1} xs={10}> <div className='verif-save-btn app-btn white m-bottom-40' onClick={this.uploadDocumentSignature.bind(this)}> <FormattedMessage id='verif.save' defaultMessage='SAVE SECTION' /> </div> </Col> { this.state.message.length > 0 ? ( <AlertContainer> <Alert type="info" timeout={3000} onDismiss={this.onMessageDismiss.bind(this)}>{this.state.message}</Alert> </AlertContainer> ) : '' } </Row> ) } } export default Indent
$(document).ready(function() { $("#form_clear_histo").formrpc({ success: function() { $("#tbl_histo tbody").empty(); return false } }) });
function show_msg(id, msg) { $("#"+id).html(msg); } function hide_msg(id, intval) { if(intval=='') { intval = 2000; } setTimeout(function() { $("#"+id).html(""); }, intval); } function myAlert(msg) { $.prompt(msg); } function myOK(intval) { if(intval=='') { intval = 2000; } setTimeout(function() { $("#cleanbluebox").remove(); }, intval); } function myLocation(loc, intval) { if(intval=='') { intval = 2000; } setTimeout(function() { window.location.href= (loc==''? window.location.href : loc); },intval); } function myConfirm(str, url) { $.prompt(str, { submit: function(v, m) { if (v) { $("#_iframe").attr("src", url); } return true; }, buttons: {'确定':true, '取消':false} }); return true; } $(document).ready(function() { if ($(".kf54kefuqqbottom").length > 0) { // $(".kf54kefuqqbottom").html($(".kf54kefuqqbottom a").html()); } });
import React, { Component } from "react"; import { Button } from "reactstrap"; class NavBar extends Component { render() { return ( <div className="Navbar"> <nav className="nav"> <Button className="btn-simple" color="primary" onClick={this.handleAuth}> Log In </Button> <Button color="primary" onClick={this.handleAuth}> Sign Up </Button> </nav> </div> ); } } export default NavBar;
/** * Created by ahmed aj on 10/04/2018. */ var mongoose =require('mongoose'); // User schema var CandidatSchema=mongoose.Schema({ nom: String, email: String, passwd: String, dateNaissance: Date, numtel: Number, adress: String, url_img: String, genre: String, language: [ { nom_langue: String, niveau: String } ], projet: [ { nom_project: String, date_debut:Date, date_fin: Date, description: String, tache_realiser: String } ], education: [ { nom_etablissement: String, date_entrer: Date, date_sortie: Date, diplome: String } ], skills: [ { nom_skill: String, niveau: String } ], experience_professionel: [ { nom_entreprise: String, titre_occuper: String, tache_realiser: String, date_entrer: Date, date_sortie: Date } ], Myoffers:[{ _id:String, statu:String, date_application:Date }] }); var candidat=module.exports=mongoose.model('Candidat',CandidatSchema,'Candidat'); //get user module.exports.getCandidats=function (callback,limet) { candidat.find(callback).limit(limet).pretty; } //Add Cadidat module.exports.AddCandidat=function(Candidat,callback){ candidat.create(Candidat,callback); } //update candidat module.exports.updateCandidat=function(id,Candidat,option,callback){ var query={_id:id}; var update= { nom: Candidat.nom, email: Candidat.email, passwd: Candidat.passwd, dateNaissance: Candidat.dateNaissance, numtel: Candidat.numtel, adress: Candidat.adress, url_img: Candidat.url_img, genre: Candidat.genre, language: Candidat.language, projet: Candidat.projet, education: Candidat.education, skills: Candidat.skills, experience_professionel: Candidat.experience_professionel, Myoffers:Candidat.Myoffers } candidat.findOneAndUpdate(query,update,option,callback); } //delete Candidat module.exports.DeleteCandidat=function(id,callback){ var query={_id:id}; candidat.remove(query,callback); } //get Candidat by email module.exports.getCandByemail=function (email,callback) { candidat.findOne({"email":email},callback); } //add offer to Candidat module.exports.addOfferToCandidat=function(id,offer,option,callback){ candidat.findById(id,function(err,cand){ if(err)throw err; cand.Myoffers.push(offer); candidat.findOneAndUpdate({"_id":id},cand,option,callback); }) } //change candidat offre statu module.exports.changeStatus=function(id,offer,option,callback){ candidat.findById(id,function(err,cand){ if(err)throw err; Array.prototype.changeObjValueAfterFind = function(key, value) { return this.filter(function(item) { if(item[key] === value){ console.log("this item statu is:"+item["statu"]) item["statu"]=offer.statu;} }); } cand.Myoffers.changeObjValueAfterFind("_id",offer._id); candidat.findOneAndUpdate({"_id":id},cand,option,callback); }) } //Supprimer offre from canddiat module.exports.dropCandidatOffer=function(id,offer,option,callback){ var i=0; candidat.findById(id,function(err,cand){ if(err)throw err; Array.prototype.deleteObjValueAfterFind = function(key, value) { return this.filter(function(item) { i=i+1; if(item[key] === value){ console.log("this item index is:"+i) Array.prototype.splice(i,1); } }); } cand.Myoffers.deleteObjValueAfterFind("_id",offer._id); candidat.findOneAndUpdate({"_id":id},cand,option,callback); }) } //get all My Offers module.exports.getCandidatOffers=function (id,callback) { candidat.findById(id,callback); }
const closePreloader = () => { const mainContainer = document.querySelector('.content'); mainContainer.style.opacity = 1; }; export default closePreloader;
#!/usr/bin/env node "use strict"; var actions = require('../lib/index'); var commander = require('commander'); commander .command("build") .option("-a, --all", "build All") .option("-m,--mode [mode]", "which mode to build") .action(function (options) { actions.buildModules(options.mode); }); commander .command("publish") .option("-m,--mode [mode]", "which mode to publish") .option("-a, --all", "build All") .action(function (options) { actions.publishModules(options.mode); }); commander .command("build:publish") .option("-m,--mode [mode]", "which mode to build and publish") .option("-a, --all", "build All") .action(function (options) { actions.buildAndPublish(options.mode); }); commander.parse(process.argv);
var PkrToDollar = 155; var PkrToRiyal = 41; var Dollars = prompt("How much dollars do you have?"); var Riyals = prompt("How much Riyals do you have?"); var PKR = (Dollars*PkrToDollar)+(Riyals*PkrToRiyal); document.write("<br>"); document.write("<br>");document.write("<br>"); document.write("Total Currency in PKR: "+PKR);
({ onFullDetails : function (component, event, helper) { var boatrec = component.get("v.boat"); var navEvt = $A.get("e.force:navigateToSObject"); navEvt.setParams({ "recordId": boatrec.Id }); navEvt.fire(); } })
// Distributed under the Open BSV software license, see the accompanying file LICENSE. /** * This test aims to verify a basic communication between the Script, Miner ID Generator & Node. * * * Prerequisities: * * 1. BSV Node. * * Set up and run a node connected to the regtest (see config/default.json configuration file). * (a) Add 'standalone=1' to bitcoin.conf. * (b) Make sure that funds to spend are available (generate 101) * (c) Configure the node to be capable to sign miner-info transactions: * (c1) Create a BIP-32 signing key to sign a miner-info tx: * bitcoin-cli makeminerinfotxsigningkey * (c2) Get the miner-info funding address: * bitcoin-cli getminerinfotxfundingaddress * (c3) Send some minimal BSV amount (0.1) to the generated miner-info funding address, e.g., using: * bitcoin-cli sendtoaddress "address" "amount" * (c4) Configure the node to use the miner-info funding outpoint: * bitcoin-cli setminerinfotxfundingoutpoint "txid" "n" * * 2. Miner ID Generator. * * Set up and run the web server. * (a) create a new 'testMiner' alias via CLI interface (npm run cli -- generateminerid --name testMiner) * (b) check if 'config/default.json' settings are correctly configured to allow rpc connection to the Node. * (b1) change the default port to 9003 and disable authentication * (for instance use: export NODE_CONFIG='{"port": 9003, "authentication": {"enabled": false}}') * (c) (optional step) enable dataRefs support * (c1) to enable a dataRefs tx creation add the 'dataRefsTxData' data file with a sample configuration, e.g.: * { * "dataRefs": { * "refs": [ * { * "brfcIds": ["62b21572ca46", "a224052ad433"], * "data": { * "62b21572ca46": { * "alpha": 1 * }, * "a224052ad433": { * "omega": 800 * } * }, * "vout": 0 * } * ] * } * } * * Note: * 1. The expected location of this file is: ~/.minerid-client/testMiner/dataRefsTxData. * 2. The example above allows to test a datarefs tx creation by this script. * 3. The outcome of the 'dataRefsTxData' configuration is a new 'dataRefs' data file created by the Generator. * * (c2) to enable only datarefs re-usage add the 'dataRefs' data file with a sample configuration, e.g.: * { * "dataRefs": { * "refs": [ * { * "brfcIds": [ * "62b21572ca46", * "a224052ad433" * ], * "txid": "140a4ae78ae06ff24655be3c0d748ba8d8969ef492a411a700cdad45d9b780bf", * "vout": 0 * } * ] * } * } * * Note: The expected location of this file is: ~/.minerid-client/testMiner/dataRefs. * * (d) npm start * Note: Start the server in the same terminal where the (b) step has been configured. * * The testing script performs the following operations: * 1. Calls the MID Generator and the Node to create a datarefs tx if the alias was configured to enable datarefs cretation. * 2. Calls the MID Generator to create a new miner-info output script for the given block height. * 3. Calls the Node to create a new miner-info tx containing the output script from the point 2. * 4. Calls the Node to get a mining candidate. * 5. Creates a coinbase transaction. * 6. Calls the MID Generator to update the coinbase2 part of the coinbase tx. * 7. Updates the coinbase tx and prints out its raw representation. * 8. Finds PoW for the miner ID block and sends it to the Node. * * Note: To run the test use: 'node examples/testMiner.js' */ const bsv = require('bsv') var BlockHeader = bsv.BlockHeader var Transaction = bsv.Transaction var Script = bsv.Script const config = require('config') const rp = require('request-promise') const mi = require('../utils/minerinfo') const { RPCClient } = require("@iangregsondev/rpc-bitcoin") // Generator's configuration. const network = config.get('network') ALIAS = 'testMiner' PORT_NUMBER = 9003 /** * Generator's Web API used in the test. */ async function executeRequest(requestOptions) { const res = await rp(requestOptions) if (res.statusCode === 200) { return res.body } else { throw new Error(`Status code: ${res.statusCode}`) } } async function getMinerInfoOutputScript (alias, height, dataRefsTxId) { let uri = `http://localhost:${PORT_NUMBER}/opreturn/${alias}/${height}/` if (dataRefsTxId !== undefined) { uri += `${dataRefsTxId}` } const requestOptions = { method: 'GET', uri: uri, resolveWithFullResponse: true } return await executeRequest(requestOptions) } async function getDataRefsOutputScripts (alias) { const requestOptions = { method: 'GET', uri: `http://localhost:${PORT_NUMBER}/datarefs/${alias}/opreturns`, resolveWithFullResponse: true } return await executeRequest(requestOptions) } async function modifyCoinbase2 (alias, minerInfoTxId, prevhash, merkleProof, coinbase2) { const requestOptions = { method: 'POST', uri: `http://localhost:${PORT_NUMBER}/coinbase2`, json: true, body: { alias: alias, minerInfoTxId: minerInfoTxId, prevhash: prevhash, merkleProof: merkleProof, coinbase2: `${coinbase2}` }, resolveWithFullResponse: true } return await executeRequest(requestOptions) } /** * Utility functions used in the test. */ function makeCoinbaseTx() { // Create a random private key and address... const privateKey = new bsv.PrivateKey.fromRandom() const publicKey = new bsv.PublicKey.fromPrivateKey(privateKey) const address = new bsv.Address.fromPublicKey(publicKey) // Create a standard coinbase TX const coinbaseInput = new Transaction.Input({ prevTxId: '0000000000000000000000000000000000000000000000000000000000000000', outputIndex: 0xFFFFFFFF, script: new Script() }) return new Transaction() .uncheckedAddInput(coinbaseInput) .to(address, 1250000000) } function getCoinbase2(tx) { return Buffer.from(tx.toString().substring(84)) // the coinbase2 part starts at the index 84 } function createTxOutput(minerInfoOutputScript) { return new Transaction.Output({ satoshis: 0, script: new Script(minerInfoOutputScript) }) } function getMinerInfoJSONDocument(minerInfoOutputScript) { const minerInfoOutput = createTxOutput(minerInfoOutputScript) return JSON.parse(Buffer.from(minerInfoOutput.script.toASM().split(' ')[4], 'hex').toString()) } function getMinerInfoDocSignature(minerInfoOutputScript) { const minerInfoOutput = createTxOutput(minerInfoOutputScript) return Buffer.from(minerInfoOutput.script.toASM().split(' ')[5], 'hex').toString('hex') } function getMinerInfoTxidFromMinerIDCoinbaseTxOutput(minerIdCoinbaseTx) { return (Buffer.from(minerIdCoinbaseTx.outputs[1].script.toASM().split(' ')[4], 'hex')).reverse().toString('hex') } /** * The main function. */ ; (async () => { if (network !== 'regtest') { console.error('Connect to the "regtest" is required.') return } try { /** * Connect to BSV Node RPC. */ const url = 'http://' + config.get('bitcoin.rpcHost') const user = config.get('bitcoin.rpcUser') const pass = config.get('bitcoin.rpcPassword') const port = config.get('bitcoin.rpcPort') const timeout = 10000 // Initiate connection. const client = new RPCClient({ url, port, timeout, user, pass }) if (client === undefined) { throw new Error("RPClient: connection error") } // Check if regtest meets required conditions. const blockCount = await client.getblockcount() console.log(`Current block count: ${blockCount}`) if (blockCount < 101) { throw new Error(`Make sure that the node has sufficient funds in the wallet (bitcoin-cli generate ${101 - blockCount})`) } else { const balance = await client.getbalance() console.log('Funds available in the wallet: ', balance) if (!(balance > 0)) { throw new Error("Insufficient funds to proceed.") } } /** * Create a datarefs tx if the alias was configured to create one. * * Interactions: * (1) The testing script calls the MID Generator. * (2) The testing script calls the Node. */ let dataRefsOutputScripts try { console.log('\n#1. The script queries the MID Generator to get datarefs output scripts.') dataRefsOutputScripts = JSON.parse(await getDataRefsOutputScripts(ALIAS)) } catch (e) { console.error('MID Generator: ', e) return } let dataRefsTxId if (Array.isArray(dataRefsOutputScripts) && dataRefsOutputScripts.length) { dataRefsTxId = await client.createdatareftx({scriptPubKeys: dataRefsOutputScripts}) console.log(`dataRefsTxId= ${dataRefsTxId} created`) console.log(`dataRefsOutputScripts= ${dataRefsOutputScripts}`) } else { console.log('DataRefs configuration doesn\'t exist') } /** * Create a miner-info document with the correct block height. * * Interaction: The testing script calls the Miner ID Generator. */ let minerInfoOutputScript try { console.log('\n#2. The script queries the MID Generator to get a new miner-info output script.') minerInfoOutputScript = await getMinerInfoOutputScript(ALIAS, blockCount+1, dataRefsTxId) console.log(`minerInfoOutputScript= ${minerInfoOutputScript}`) console.log('\nMinerInfo Document: ', JSON.stringify(getMinerInfoJSONDocument(minerInfoOutputScript))) console.log('\nsig(MinerInfo Document): ', getMinerInfoDocSignature(minerInfoOutputScript)) } catch (e) { console.error('MID Generator: ', e) return } /** * Create a miner-info tx with the miner-info output script. * * Interaction: The testing script calls the Node. */ console.log('\n#3. The script queries the Node to create a new miner-info tx with the miner-info output script.') const minerInfoTxId = await client.createminerinfotx({hexdata: minerInfoOutputScript}) if (!minerInfoTxId) { throw new Error("createminerinfotx has failed!") } console.log(`minerInfoTxId= ${minerInfoTxId} created`) // Check that the node returns a valid miner-info txid. const returnedMinerInfoTxId = await client.getminerinfotxid() if (minerInfoTxId != returnedMinerInfoTxId) { throw new Error(`Incorrect miner-info txid= ${returnedMinerInfoTxId} returned, expected-txid= ${minerInfoTxId}`) } /** * Check if the Node's mempool contains expected miner ID transactions. */ const rawMempool = await client.getrawmempool() if (minerInfoTxId && !rawMempool.includes(minerInfoTxId)) { throw new Error("Mempool is missing a minerInfo transaction !") } if (dataRefsTxId && !rawMempool.includes(dataRefsTxId)) { throw new Error("Mempool is missing a dataRefs transaction !") } console.log('\nMempool transactions : ', await client.getrawmempool()) /** * Get a mining candidate from the node. * * Interaction: The testing script calls the Node. */ console.log('\n#4. The script queries the Node to get a mining candidate.') const mc = await client.getminingcandidate() console.log(`\nmc= ${JSON.stringify(mc)}`) /** * Make a coinbase transaction. */ console.log('\n#5. Make a coinbase transaction.') const coinbaseTx = makeCoinbaseTx() /** * Update coinbase2. * * Interaction: The testing script calls the Miner ID Generator. */ let updatedCoinbase2 try { console.log('\n#6. The script queries the MID Generator to update the coinbase2') updatedCoinbase2 = await modifyCoinbase2(ALIAS, minerInfoTxId, mc.prevhash, mc.merkleProof, getCoinbase2(coinbaseTx)) console.log(`updatedCoinbase2= ${updatedCoinbase2}`) } catch (e) { console.error('MID Generator: ', e) return } /** * Make the miner ID coinbase transaction (combine cb1 & modified cb2) */ console.log('\n#7. RAW miner ID coinbase transaction:') const minerIdCoinbaseTx = new Transaction(mi.placeholderCB1 + updatedCoinbase2) console.log('txid= ', minerIdCoinbaseTx.id.toString()) console.log('raw= ', minerIdCoinbaseTx.toString()) const cbTxOutput1MinerInfoTxid = getMinerInfoTxidFromMinerIDCoinbaseTxOutput(minerIdCoinbaseTx) if (minerInfoTxId !== cbTxOutput1MinerInfoTxid) { throw new Error(`Miner-info txid linked with the Miner ID Coinbase tx output is incorrect: ${cbTxOutput1MinerInfoTxid}`) } /** * Mine the miner ID block and submit the mining solution to the Node. */ console.log('\n#8. Find PoW for the miner ID block and send it to the Node.') let nNonce = 0 let bh = {} do { bh = new BlockHeader({ version: mc["version"], prevHash: mc["prevhash"], merkleRoot: mi.buildMerkleRootFromCoinbase(minerIdCoinbaseTx.id, mc["merkleProof"]), time: mc["time"], bits: 0x207fffff, // the expected number of bits on regtest nonce: ++nNonce }) } while (!bh.validProofOfWork(bh)); console.log(`bh.hash= ${bh.hash}, nNonce: ${nNonce}`) await client.submitminingsolution({id: mc["id"], nonce: nNonce, coinbase: minerIdCoinbaseTx.toString(), time: mc["time"], version: mc["version"]}) if (await client.getblockcount() !== mc["height"]) { throw new Error('The last submitted block has been rejected by the node !') } else { console.log(`The miner ID block ${bh.hash} has been accepted.`) } } catch (e) { console.error(`${network} error!`, e) return } console.log('\nThe script has been executed successfully.') })()
(_=>{ let loginForm = document.getElementById('login-form'); loginForm.addEventListener('submit', e => { e.preventDefault(); let loginFormData = new FormData(loginForm); ajaxCom('POST', loginForm.action, loginFormData).then(json => { if(json.status !== true){ awAlert.error(json.msg); return false; } window.location = loginForm.dataset.successDirect; }); }); })();
var User = require('../models/User'); var jwt = require('jwt-simple'); var secret = require('../config/config').tokenSecret module.exports = function(req, res, next){ if(req.token){ } }
var WINW = 0; var WINH = 0; function reziseWN(){ WINW = $(window).width(); WINH = $(window).height(); } $(window).resize(function() { reziseWN(); }); reziseWN(); var CDATA = null; var app = angular.module('app', []); app.controller('mainController', function mainController($scope, $interval) { $scope.data = ""; $scope.cr = [ ]; $scope.energia = 100; $interval(function() { if (CDATA != null) { $scope.data = CDATA; $scope.cr = cleanArray(CDATA.cr); var cube = cars[IDCAR].cube; var angu = cube.rotation.z; var x0 = cube.position.x; var y0 = cube.position.y; $scope.titop = parseInt(WINH / 4); $scope.cr.forEach(function(elem){ var x1 = x0 + Math.cos(angu); var y1 = y0 + Math.sin(angu); var x2 = elem.x; var y2 = elem.y; elem.pt = null; if(x0 != x2 && y0 != y2){ elem.pt = ajustarAngulo(angulo2P(x0, y0, x2,y2, x1,y1) + Math.PI/2); elem.ang = parseInt((WINW/4) * WINW/WINH * elem.pt + WINW/2 -100); } }); var energia = Math.round(CDATA.cr[CDATA.me].e); if (energia < 0) { energia = 0; } if($scope.energia != energia){ if($scope.energia < energia) $scope.energia += 5; if($scope.energia > energia){ $scope.energia += -1; if(energia == 0 && $scope.energia > 30){ $scope.energia += -10; } } $("#energia").css("background-color", "rgba(" + Math.round( 255 * (100 - $scope.energia)/100 ) + ",0,0,0.8)"); } } }, 50); }); // ---- function angulo(x,y){ if(x==0){ return y>=0?Math.PI/2:-Math.PI/2; } var a = Math.atan(y/x); if(x >= 0){ return ajustarAngulo(a); } if( y > 0){ return ajustarAngulo(Math.PI + a); }else{ return ajustarAngulo(Math.PI + a); } } function angulo2(x1,y1, x2,y2){ return ajustarAngulo(angulo(x2, y2) - angulo(x1, y1)); } function angulo2P(x0, y0, x1,y1, x2,y2){ return angulo2(x1 - x0, y1 - y0, x2 - x0 , y2 - y0); } function ajustarAngulo(a){ while(a < -Math.PI){ a += 2*Math.PI; } while(a > Math.PI){ a -= 2*Math.PI; } return a; } function cleanArray(r) { var rs = []; r.forEach(function(a){ if(a != null){ rs.push(a); } }); rs.sort(function(a,b){ return b.p - a.p; }); return rs; };
import React from "react"; import {Card, Switch} from "antd"; const SwitchLoading = () => { return ( <Card className="gx-card" title="Switch Loading"> <div className="gx-mb-3"><Switch loading defaultChecked/></div> <div className="gx-mb-0"><Switch size="small" loading/></div> </Card> ); }; export default SwitchLoading;
import {SCROLLING_UP, SCROLLING_DOWN} from "../constants"; export default function scrollingPage({currentOffset, oldOffset}) { return (dispatch => { if (currentOffset > oldOffset) { dispatch( {type: SCROLLING_DOWN, payload: {currentOffset, oldOffset}} ); } else if (currentOffset < oldOffset) { dispatch( {type: SCROLLING_UP, payload: {currentOffset, oldOffset}} ); } }); }
import '@babel/polyfill' // 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 './plugins/vuetify' import App from './App' import router from './router' import Vuetify from 'vuetify' import VueCircleSlider from 'vue-circle-slider' import 'vuetify/dist/vuetify.min.css' import 'material-design-icons-iconfont/dist/material-design-icons.css' Vue.use(Vuetify) Vue.use(VueCircleSlider) Vue.config.productionTip = false Vue.directive('hljs', { inserted: function (el) { window.hljs.highlightBlock(el) } }) /* eslint-disable no-new */ new Vue({ el: '#app', router, components: { App }, template: '<App/>' })
(function() { 'use strict'; var Products = []; angular .module('Product.api.module') .factory('ProductManager', ProductManager); ProductManager.$inject = ['ProductDispatcher', 'ProductSchema', 'storage']; function ProductManager(ProductDispatcher, ProductSchema, storage) { var service = { Products : Products, transformProducts: transformProducts, createProduct: createProduct, removeProducts: removeProducts, getProducts: getProducts, updateProduct: updateProduct, deleteProduct: deleteProduct, findById: findById }; var Schema = { status: 0, products: [], qty: [], total: 0 }; return service; //////////////// function findById(id) { var prod; for (var i = 0; i < service.Products.length; i++) { prod = service.Products[i]; if (prod._id == id) { return prod; } } return false; } function transformProducts(arr) { if (!Array.isArray(arr)) { return new ProductSchema(arr); } var Products = []; for (var i = 0; i < arr.length; i++) { Products.push(newProduct(arr[i], i)); } return Products; } function newProduct(product, index) { return new ProductSchema(product, index); } function createProduct(product) { ProductDispatcher.post(product) } function updateProduct(product, updates) { var index = product._index; return ProductDispatcher.update(product, updates).then(function(newProduct) { newProduct = newProduct(newProduct, index); service.Products[index] = new ProductSchema(newProduct, index); return newProduct; }) } function deleteProduct(product) { return ProductDispatcher.destroy(product).then(function(done) { return done }) } function setProducts(Products) { writeProducts(Products); service.Products = Products; return service.Products; } function writeProducts(Products) { // TODO: change this to Product Storage system using namespaces instead of localStorage localStorage.setItem('Products', JSON.stringify(Products)); } function getProducts() { service.Products = ProductDispatcher.get().then(transformProducts).then(setProducts); return service.Products; } function removeProducts(Products) { for (var i = 0; i < service.Products.length; i++) { var checkProducts = service.Products[i]; if (checkProducts == Products) { service.Products.splice(i, 1); return service.Products; } } // console.error('Error locating Products', Products); return service.Products; } } })();
//首次加载文章内容 $.getJSON("/carousel/get_list?page=1&num="+5,function(jsondata){ console.log("jsondata.date.items"+ jsondata.data.items); console.log(jsondata); if (jsondata.code!=0) { alert("系统繁忙,请稍后再试~~"); } else{ onePageItems(jsondata.data); } }); //根据第几页和每页的页数加载 function getPageData(){ $.getJSON("/carousel/get_list?page=" + page + "&num="+5,function(jsondata){ console.log("jsondata.date.items"+ jsondata.data.items); console.log(jsondata); if (jsondata.code!=0) { alert("系统繁忙,请稍后再试~~"); } else{ onePageItems(jsondata.data); } }); } function buildItem(carousel){ var tr=document.createElement("tr"); var td=document.createElement("td"); td.setAttribute("class","js_td"); var left=carouselPic(carousel); var right=buidRight(carousel); tr.appendChild(td); td.appendChild(left); td.appendChild(right); return tr; } function buidRight(carousel){ var right=document.createElement("div"); right.setAttribute("class","col-xs-3 box2"); var carousel_id=document.createElement("div"); carousel_id.setAttribute("class","col-xs-12"); carousel_id_txt=document.createTextNode("轮播id: "+carousel.id); carousel_id.appendChild(carousel_id_txt); var build_time=document.createElement("div"); build_time.setAttribute("class","col-xs-12"); var full_time=carousel.create_time; build_time_txt=document.createTextNode("创建时间:"+ full_time.substring(0,4) + "/" +full_time.substring(5,7) + "/" +full_time.substring(8,10)); build_time.appendChild(build_time_txt); right.appendChild(carousel_id); right.appendChild(build_time); return right; } // <tr> // <td class="js_td"> // <a href=""> // <div class="col-xs-7 col-xs-offset-2 carousel_pic"> // <img src="/front.1/resource/1.jpg" class="img-responsive" alt="Image"> // <div class="img_info visible-md visible-lg"> // <div class="writer_name">泥石流</div> // <div class="writer_info visible-lg">泥石流</div> // <h4>奥运会泥石流</h4> // <div class="detile">泥石流女神泥石流,女神泥石流女神泥石流女,神泥石流女神泥石流女神泥石流女神泥石流女神。</div> // </div> // </div> // </a> // <div class="col-xs-3 box2"> // <div class="col-xs-12">轮播id: 1</div> // <div class="col-xs-12">创建时间:2016/06/01</div> // </div> // </td> // </tr> function carouselPic(carousel){ var link=document.createElement("a"); var carousel_pic=document.createElement("div"); carousel_pic.setAttribute("class","col-xs-7 carousel_pic col-xs-offset-2"); var img=document.createElement("img"); img.setAttribute("src",carousel.img_url); img.setAttribute("class","img-responsive"); img.setAttribute("alt","Image"); var img_info=imgInfo(carousel); link.appendChild(carousel_pic); carousel_pic.appendChild(img); carousel_pic.appendChild(img_info); return link; } // <div class="col-xs-7 col-xs-offset-2 carousel_pic"> // <img src="/front.1/resource/1.jpg" class="img-responsive" alt="Image"> // <div class="img_info visible-md visible-lg"> // <div class="writer_name">泥石流</div> // <div class="writer_info visible-lg">泥石流</div> // <h4>奥运会泥石流</h4> // <div class="detile">泥石流女神泥石流,女神泥石流女神泥石流女,神泥石流女神泥石流女神泥石流女神泥石流女神。</div> // </div> // </div> function imgInfo(carousel){ var img_info=document.createElement("div"); img_info.setAttribute("class","img_info "); var writer_name=document.createElement("div"); writer_name.setAttribute("class","writer_name"); var writer_name_text=document.createTextNode(carousel.author); writer_name.appendChild(writer_name_text); var title=document.createElement("h4"); title_text=document.createTextNode(carousel.title); title.appendChild(title_text); var detial=document.createElement("div"); var detial_text=document.createTextNode(carousel.summary.substring(0,30) + "~ ~ ~"); detial.appendChild(detial_text); img_info.appendChild(writer_name); img_info.appendChild(title); img_info.appendChild(detial); return img_info; }
'use strict'; const response = require('../res'); const connection = require('../conn'); exports.listPengajuan = function(req, res) { connection.query('SELECT * FROM v_pengajuan', function (error, rows, fields){ if(error){ console.log(error) } else{ response.ok(rows, res) } }); }; exports.livePengajuan = function(req, res) { connection.query('SELECT * FROM v_livekegiatan', function (error, rows, fields){ if(error){ console.log(error) } else{ response.ok(rows, res) } }); }; exports.countPengajuan = function(req, res) { connection.query('SELECT * from v_countpengajuan', function (error, rows, fields){ if(error){ console.log(error) } else{ response.ok(rows, res) } }); }; exports.listPengajuanbkd = function(req, res) { var bkdId = req.params.bkdId; connection.query('SELECT * FROM v_pengajuan where bkd = ?', [ bkdId ], function (error, rows, fields){ if(error){ console.log(error) } else{ response.ok(rows, res) } }); }; exports.listApprove = function(req, res) { connection.query('SELECT * FROM v_approve', function (error, rows, fields){ if(error){ console.log(error) } else{ response.ok(rows, res) } }); }; exports.listApprovekabupaten = function(req, res) { connection.query('SELECT * FROM v_approvekabupaten', function (error, rows, fields){ if(error){ console.log(error) } else{ response.ok(rows, res) } }); }; exports.findApprovekabupaten = function(req, res) { const bkdId = req.params.bkdId; connection.query('SELECT * FROM v_approvekabupaten where bkd = ?', [ bkdId ], function (error, rows, fields){ if(error){ console.log(error) } else{ response.ok(rows, res) } }); }; exports.createPengajuan= function(req, res) { const idBkd = req.body.idBkd; const namaKegiatan = req.body.namaKegiatan; const jmlPeserta = req.body.jmlPeserta; const tglKegiatan = req.body.tglKegiatan; const tempatpengajuan = req.body.tempatpengajuan const filepengajuan = req.body.filepengajuan const angkatan = req.body.angkatan connection.query('INSERT INTO pengajuan (bkd, namakegiatan, jmlpeserta, tglkegiatan, tempatpengajuan, filepengajuan, namaangkatan) values (?,?,?,?,?,?,?)', [ idBkd, namaKegiatan, jmlPeserta, tglKegiatan, tempatpengajuan, filepengajuan, angkatan ], function (error, rows, fields){ if(error){ console.log(error) } else{ response.ok("Berhasil menambahkan pengajuan ", res) } }); }; exports.createReject= function(req, res) { const idPengajuan = req.body.idPengajuan; const alasan = req.body.alasan; const dokumenreject = req.body.dokumenreject; connection.query('INSERT INTO reject (idpengajuan, alasan, dokumenreject) values (?,?,?)', [ idPengajuan, alasan, dokumenreject ], function (error, rows, fields){ if(error){ console.log(error) } else{ response.ok("Berhasil tolak pengajuan ", res) } }); }; exports.findApprove = function(req, res) { var pengajuanId = req.params.pengajuanId; connection.query('SELECT * FROM v_approve where id = ?', [ pengajuanId ], function (error, rows, fields){ if(error){ console.log(error) } else{ response.ok(rows, res) } }); }; exports.findApprovebkd = function(req, res) { var bkdId = req.params.bkdId; var pengajuanId = req.params.pengajuanId; connection.query('SELECT * FROM v_approve where bkd = ? and id= ?', [ bkdId, pengajuanId ], function (error, rows, fields){ if(error){ console.log(error) } else{ response.ok(rows, res) } }); }; exports.listApprovebkd = function(req, res) { var bkdId = req.params.bkdId; connection.query('SELECT * FROM v_approve where bkd = ?', [ bkdId ], function (error, rows, fields){ if(error){ console.log(error) } else{ response.ok(rows, res) } }); }; exports.findPengajuan = function(req, res) { var pengajuanId = req.params.pengajuanId; connection.query('SELECT * FROM v_pengajuan where id = ?', [ pengajuanId ], function (error, rows, fields){ if(error){ console.log(error) } else{ response.ok(rows, res) } }); }; exports.setApprove = function(req, res) { var pengajuanId = req.body.pengajuanId; var statusPengajuan = req.body.statusPengajuan; connection.query('UPDATE pengajuan SET status = ? where id = ?', [ statusPengajuan, pengajuanId ], function (error, rows, fields){ if(error){ console.log(error) } else{ response.ok(rows, res) } }); }; exports.setReject = function(req, res) { var pengajuanId = req.body.pengajuanId; var statusPengajuan = req.body.statusPengajuan; connection.query('UPDATE pengajuan SET status = ? where id = ?', [ statusPengajuan, pengajuanId ], function (error, rows, fields){ if(error){ console.log(error) } else{ response.ok(rows, res) } }); };
import React from "react"; import NoMatches from "./NoMatches"; const NoPostsInFavourites = ({ category }) => { return ( <NoMatches title="Sorry!" category={category.text} subtitle={ <p> At the moment there are no posts in the Favourites list. <br />{" "} Continue to browse posts and save the best listings. </p> } /> ); }; export default NoPostsInFavourites;
"use strict"; function runCalc() { var textField = document.getElementById("textField"); let pPrinciple = document.getElementById('princText').value; let intPrinc = parseFloat(pPrinciple); let origPrinc = intPrinc; let pRate = document.getElementById('intstText').value; let intRate = parseFloat(pRate); let pMonthlyPayment = document.getElementById('mnthPmtText').value; let intPmt = parseFloat(pMonthlyPayment); let monthsToPay = 0; let yearsToPay = 0; if (!checkInputs(pPrinciple, pRate, pMonthlyPayment)) { alert("Please enter valid numberical values, without dollar signs, percentage marks, commas, or other characters."); } else { intRate = intRate / 100.0; textField.value = intPrinc; // Calculates amount of time in months/years needed to pay off loan with specific payment amount. // Calculation based on common percentage rates drawn by banks and loan institutions ~ interest is added // on a daily basis, therefore interest rate must be divided by 365, then multiplied by average days per month while (intPrinc > 0) { intPrinc = intPrinc - (intPmt); let tempPrinc = intPrinc + (intPrinc * ((intRate / 365) * 30.42)); if (tempPrinc > origPrinc) { document.getElementById("output").innerHTML = "Payment amount is too small to pay off loan"; break; } else { intPrinc = tempPrinc; } monthsToPay = monthsToPay + 1; yearsToPay = monthsToPay / 12; if (intPrinc > 0) { textField.value += ", " + intPrinc.toFixed(2); } } document.getElementById("output").innerHTML = "It will take " + monthsToPay + " months to pay off the loan, or " + yearsToPay.toFixed(1) + " years."; } } function clearFields() { var textField = document.getElementById("textField"); var princText = document.getElementById("princText"); var intstText = document.getElementById("intstText"); var mnthPmtText = document.getElementById("mnthPmtText"); textField.value = ""; princText.value = ""; intstText.value = ""; mnthPmtText.value = ""; document.getElementById("output").innerHTML = ""; } function checkInputs(pPrinciple, pRate, pMonthlyPayment) { let inputCheck = false; if (isNaN(parseFloat(pPrinciple)) || isNaN(parseFloat(pRate)) || isNaN(parseFloat(pMonthlyPayment))) { inputCheck = false; } else { if ((pPrinciple.indexOf(",") < 0) && (pRate.indexOf(",") < 0) && (pMonthlyPayment.indexOf(",") < 0)) { inputCheck = true; } } return inputCheck; } // Allows 'Enter' key to trigger 'Run Calculator' button document.onkeydown = function (e) { e = e || window.event; switch (e.which || e.keyCode) { case 13 : runCalc(); break; } }
window.addEventListener("load", function() { clientTypeSelect.value === individPred; saveClientButton.disabled = true; addNewFounderFormButton.disabled = true; });
import React from 'react'; import { Card, Button, Row, Col, Spinner } from 'react-bootstrap'; import FileUpload from './sub-components/FileUpload.js'; import AdjustSettings from './sub-components/AdjustSettings.js'; import ConfirmUpload from './sub-components/ConfirmUpload.js'; import CustomProgressBar from './sub-components/CustomProgressBar.js'; import UploadService from './services/UploadService.js'; import Papa from 'papaparse'; import './App.css'; class App extends React.Component { constructor() { super(); this.state = { step: 1, // which step user is at selectedFile: null, // uploaded file tableHeaders: [], // all headers system parsed from the selected file excludedHeaders: [], // a boolean array to keep track of excluded headers assignedHeaders: [], // keeping track of assigned headers to the ID, Timestamp and Name assigned: { // before sending request to the backend collecting assigned headers in one object id: null, name: null, timestamp: null }, resultsLoading: false, // when we make request this for displaying loading icon on the button loadResponseInfo: false, // this prop is passed to the child component(ConfirmUpload) to render the message we got from the backend convertingFile: false, // when we convert excel files on frontend this prop is used show loading icon asString: false, // when we send excel files to the backend we send them as a string so this is used indicate whether we are sending string or an actual file } this.uploadService = new UploadService(this) // setting up the class for communicating with our backend - concept is called "Dependency Injection" this.config = { // this object is passed as an argument to the JS CSV parser method delimiter: "", // auto-detect newline: "", // auto-detect quoteChar: '"', escapeChar: '"', header: false, transformHeader: undefined, dynamicTyping: false, preview: 1, // for getting the headers encoding: "", worker: false, comments: false, step: undefined, complete: this.parseComplete, error: undefined, download: false, downloadRequestHeaders: undefined, downloadRequestBody: undefined, skipEmptyLines: false, chunk: undefined, chunkSize: undefined, fastMode: undefined, beforeFirstChunk: undefined, withCredentials: undefined, transform: undefined, delimitersToGuess: [',', '\t', '|', ';', Papa.RECORD_SEP, Papa.UNIT_SEP] } this.unparseConfig = { // this object is passed as an argument to the JS CSV unParser method quotes: false, //or array of booleans quoteChar: '"', escapeChar: '"', delimiter: ",", header: true, newline: "\r\n", skipEmptyLines: false, //other option is 'greedy', meaning skip delimiters, quotes, and whitespace. columns: null //or array of strings } } parseComplete = (results, parser) => { // call-back function, called when parsing operation is complete if(results.errors.length > 0) { // didn't add error handling for this one // error handling } else { // load start this.setState({tableHeaders: results.data[0], excludedHeaders: results.data[0].map(el => true)}, function(){ // we are assigning the first row of the parsed file as the headers and then we create the boolean array for excludedHeaders initially all values are true this.setState({step: 2}, function() { // When parsing is complete and we have the necessary files we move onto second step // load end }) }) } } onChangeHandler = event => { // this function handles changes made on the File Input if(event.target.files[0].name.substr(-4) === "xlsx") { //if file is .xlsx window.parseExcelXLSX(event.target.files[0], this) } else if(event.target.files[0].name.substr(-3) === "xls") { //if file is .xls window.parseExcelXLS(event.target.files[0], this) } else if(event.target.files[0].name.substr(-3) === "csv" || event.target.files[0].name.substr(-3) === "tsv") { //if file is .csv or .tsv this.setState({selectedFile: event.target.files[0]}) } else { //if file is not supported window.alert("Our system doesn't support the file. Please convert it to one of the supported file type and then try again.") event.target.value = "" } } onChangeCheckbox = event => { // this function handles when user includes or excludes headers in the second step const newArr = this.state.excludedHeaders.slice() newArr[event.target.id] = !newArr[event.target.id] for(let val in this.state.assigned) { if(this.state.assigned[val] === this.state.tableHeaders[event.target.id]) { let availableHeaders = this.availableHeaders() let idx = availableHeaders.indexOf(this.state.tableHeaders[event.target.id]) let newAssHeaders = this.state.assignedHeaders.filter(el => parseInt(el) === idx ? false : true) let targetFormInput = 0 switch(val) { case "id": targetFormInput = 0 break; case "name": targetFormInput = 1 break; case "timestamp": targetFormInput = 2 break; default: targetFormInput = 0 break; } let input = document.getElementsByClassName("list-form-input")[targetFormInput] input.children[1].value = -1 this.setState({ assigned: {...this.state.assigned, [val]: null}, assignedHeaders: newAssHeaders }) } } this.setState({excludedHeaders: newArr}) } syncAssHeadersState = () => { // this function is called when we have changes on the headers to make sure our double-source is synced with each other let currentAssHeaders = [] for(let val in this.state.assigned) { let i = this.availableHeaders().indexOf(this.state.assigned[val]) if(i > -1) currentAssHeaders.push(i) } this.setState({assignedHeaders: [...new Set(currentAssHeaders)]}) } onChangeList = event => { // this function handles the dropdown list for assigning columns let val = parseInt(event.target.value) if(val > -1) { // debugger if(this.state.assignedHeaders.includes(val)) { window.alert("You already assigned this column.") let idx = this.availableHeaders().indexOf(this.state.assigned[event.target.parentElement.children[0].textContent.toLowerCase()]) event.target.value = idx return; } this.state.assignedHeaders.push(val) this.setState({assigned: {...this.state.assigned, [event.target.parentElement.firstElementChild.textContent.toLowerCase()]: this.availableHeaders()[val]}}, this.syncAssHeadersState) } else { //remove the value from assigned let header = this.state.assigned[event.target.parentElement.firstElementChild.textContent.toLowerCase()] let idx = this.availableHeaders().indexOf(header) let newAssHeaders = this.state.assignedHeaders.filter((el) => parseInt(el) !== idx ? true : false) this.setState({assigned: {...this.state.assigned, [event.target.parentElement.firstElementChild.textContent.toLowerCase()]: null}, assignedHeaders: newAssHeaders}) } } nextButtonHandler = event => { // this function handles clicks for next button which is located right-bottom on the ui switch(this.state.step) { case 1: // in first step we check if we have an actual file or string and we act depending on that if(!this.state.selectedFile) { window.alert("Please select a file to move forward.") } else { // move forward if(this.state.asString) { const headers = [] for (const [key, value] of Object.entries(this.state.converted[0])) {headers.push(key)} //eslint-disable-line this.setState({tableHeaders: headers, excludedHeaders: headers.map(el => true)}, function(){ this.setState({step: 2}, function() { // load end }) }) } else { Papa.parse(this.state.selectedFile, this.config) } this.setState({step: 2}) } break; case 2: // we don't have to do anything on second step this.setState({step: 3}) break; case 3: // this where we make the request to the backend if(!this.state.errorType && !this.state.successfullyCompleted) { // send the request // start loading icon this.setState({resultsLoading: !this.state.resultsLoading}) const form = new FormData() // creating the form object for request body form.append("file", this.state.selectedFile) form.append("table_headers", this.availableHeaders()) form.append("id", this.state.assigned.id) form.append("name", this.state.assigned.name) form.append("timestamp", this.state.assigned.timestamp) form.append("as_string", this.state.asString) this.uploadService.uploadFileToParse(form) // end loading icon } else { // upload another, reset the state this.setState({ step: 1, selectedFile: null, tableHeaders: [], excludedHeaders: [], assignedHeaders: [], assigned: { id: null, name: null, timestamp: null }, resultsLoading: false, loadResponseInfo: false, successfullyCompleted: false, errorType: null, errorLists: null, convertingFile: false, asString: false, fileUrl: null, converted: null, }) } break; default: console.log(this.state.step) } } // Changing page title according to the current step renderPageTitle = () => { switch(this.state.step) { case 1: return "Upload Dataset" case 2: return "Adjust Settings" case 3: return "Confirm & Upload" default: console.log(this.state.step) } } // Filtering exlcuded headers from all headers availableHeaders = () => { return this.state.tableHeaders.filter((el, idx) => { if(this.state.excludedHeaders[idx]) { return true } return false }) } // If user clicks cancel this function resets every state property to its initial value cancelUpload = event => { // cancel upload this.setState({ step: 1, selectedFile: null, tableHeaders: [], excludedHeaders: [], assignedHeaders: [], assigned: { id: null, name: null, timestamp: null }, resultsLoading: false, loadResponseInfo: false, successfullyCompleted: false, errorType: null, errorLists: null, convertingFile: false, asString: false, fileUrl: null, converted: null, }) } renderContent = () => { // this function renders the main content on UI based on the step value we have in the state switch(this.state.step) { case 1: return <FileUpload onChangeHandler={this.onChangeHandler} fileLoading={this.state.convertingFile} /> case 2: return <AdjustSettings availableHeaders={this.availableHeaders()} tableHeaders={this.state.tableHeaders} onChangeCheckbox={this.onChangeCheckbox} onChangeList={this.onChangeList} /> case 3: return <ConfirmUpload selectedHeaders={this.availableHeaders()} assignedInfo={this.state.assigned} loadResponseInfo={this.state.loadResponseInfo} errorType={this.state.errorType} errorLists={this.state.errorLists} fileUrl={this.state.fileUrl} /> default: return <FileUpload onChangeHandler={this.onChangeHandler} /> } } stepToProgress = () => { // this function returns the appropiate percentage for the progress bar based on step value switch(this.state.step) { case 1: return 0 case 2: return 50 case 3: return 100 default: return 0 } } nextButtonEnabled = () => { // this function returns boolean to disable or enable or next button depending on provided inputs from the user switch(this.state.step) { case 1: if(this.state.selectedFile) return true break; case 2: if(this.state.assigned.id && this.state.assigned.name && this.state.assigned.timestamp && this.state.excludedHeaders.includes(true)) return true break; case 3: if(this.state.assigned.id && this.state.assigned.name && this.state.assigned.timestamp && this.state.excludedHeaders.includes(true)) return true break; default: return false } } render() { return( <> <Card className="main-container"> <Card.Header as="div"> <Row> <Col lg={4}> <h5 className="card-title">{this.renderPageTitle()}</h5> </Col> <Col lg={8}> <CustomProgressBar activatedStep={this.state.step} successfullyCompleted={this.state.successfullyCompleted} /> </Col> </Row> </Card.Header> <Card.Body> {this.renderContent()} </Card.Body> <Card.Footer> {this.state.step > 1 && !this.state.successfullyCompleted ? <Button className="cancel-button" variant="secondary" onClick={this.cancelUpload}>Cancel</Button> : null} { !this.state.resultsLoading ? <Button className="move-forward-button" variant="primary" onClick={this.nextButtonHandler} disabled={!this.nextButtonEnabled()}>{this.state.step === 3 ? this.state.errorType || this.state.successfullyCompleted ? "Upload Another" : "Upload" : "Next"}</Button> : <Button className="move-forward-button" variant="primary" disabled> <Spinner as="span" animation="border" size="sm" role="status" aria-hidden="true" /> <span className="sr-only">Loading...</span> </Button> } </Card.Footer> </Card> <p className="text-muted" style={{fontSize: '11px', textAlign: 'center', width: '100%'}}>created by emirhan kaplan in 2020.</p> </> ) } } export default App; // .TXT Conversion - Not Working! Because there is a lot different formats we can get from the user // else if(event.target.files[0].name.substr(-3) === "txt") { // var reader = new FileReader(); // var component = this // reader.onload = function(event) { // var cells = event.target.result.split('\n').map(function (el) { return el.split(/\s+/); }); // var headings = cells.shift(); // var json_object = cells.map(function (el) { // var obj = {}; // for (var i = 0, l = el.length; i < l; i++) { // obj[headings[i]] = isNaN(Number(el[i])) ? el[i] : +el[i]; // } // return obj; // }); // component.setState({converted: json_object}, function() { // //after loaded // const convertedToString = Papa.unparse(json_object, this.unparseConfig) // component.setState({convertingFile: false, selectedFile: convertedToString, asString: true}) // console.log(convertedToString) // }) // }; // reader.readAsText(event.target.files[0]); // }
var express = require('express'), fs = require('fs'), path = require('path'), Lara = exports = {}; global.Lara = Lara; Lara.app = express(); Lara.models = {}; Lara.controllers = {}; Lara.middlewares = {}; function existsSyncFolder(folder) { return fs.existsSync(folder) && fs.lstatSync(folder).isDirectory(); }; function existsSyncFile(file) { return fs.existsSync(file) && fs.lstatSync(file).isFile(); }; function loadJS(file, callback) { if (file.indexOf('.js') && existsSyncFile(file)) { var obj = require(file); if (typeof callback !== typeof undefined) callback(obj, path.basename(file, '.js')); } }; function loadJSFromDirectory(folder, callback) { if (existsSyncFolder(folder)) { fs.readdirSync(folder).forEach(function(name) { if (name.indexOf('.js')) { var urlFile = path.resolve(folder, name); var obj = require(urlFile); if (typeof callback !== typeof undefined) callback(obj, path.basename(urlFile, '.js')); } }); } }; Lara.start = function(base) { Lara.appPath = typeof base === typeof undefined ? path.resolve(__dirname, './../../../app/') : base; loadJSFromDirectory(path.resolve(Lara.appPath, './config')); loadJSFromDirectory(path.resolve(Lara.appPath, './controllers'), function(ctrl, name) { if (ctrl.hasOwnProperty('name')) Lara.controllers[ctrl.name] = ctrl; else Lara.controllers[name] = ctrl; }); loadJSFromDirectory(path.resolve(Lara.appPath, './models'), function(model, name) { if (model.hasOwnProperty('name')) Lara.models[model.name] = model; else Lara.models[name] = model; }); loadJSFromDirectory(path.resolve(Lara.appPath, './middlewares'), function(middleware, name) { if (middleware.hasOwnProperty('name')) Lara.middlewares[middleware.name] = middleware; else Lara.middlewares[name] = middleware; }); loadJS(path.resolve(Lara.appPath, './filters.js')); loadJS(path.resolve(Lara.appPath, './routes.js')); loadJS(path.resolve(Lara.appPath, './start.js')); } Lara.config = function(key, value) { var val = Lara.app.get(key); return typeof val !== typeof undefined ? val : value; }
import Note from "./Container"; export default Note;
import React, { Component } from 'react'; import { Row, Col, Steps } from 'antd'; import { AboutOraclesStep, SelectDataSourceStep, SetQueryStep, QueryResultStep } from './Steps'; const Step = Steps.Step; const parentColLayout = { lg: { span: 16 }, sm: { span: 24 }, xs: { span: 24 } }; class TestQueryForm extends Component { constructor(props) { super(props); this.state = { step: 0, oracleDataSource: 'URL', oracleQuery: '' }; } onInputChange(event) { this.setState({ [event.target.id]: event.target.value }); } onDataSourceChange(dataSources) { this.setState({ oracleDataSource: dataSources }); } onQueryChange(query) { this.setState({ oracleQuery: query }); } onQuerySubmit() { this.toNextStep(); this.props.onTestQuery(this.state); } toNextStep() { this.setState({ step: this.state.step + 1 }); } toPrevStep() { this.setState({ step: this.state.step - 1 }); } onRestart() { this.setState({ step: 1 // <-- Select Datasource Step }); } render() { const currentStep = this.state.step; const steps = [ <AboutOraclesStep key="0" onNextClicked={this.toNextStep.bind(this)} />, <SelectDataSourceStep key="1" dataSource={this.state.oracleDataSource} onChange={this.onDataSourceChange.bind(this)} onPrevClicked={this.toPrevStep.bind(this)} onNextClicked={this.toNextStep.bind(this)} />, <SetQueryStep key="2" dataSource={this.state.oracleDataSource} onPrevClicked={this.toPrevStep.bind(this)} onChange={this.onQueryChange.bind(this)} onSubmit={this.onQuerySubmit.bind(this)} />, <QueryResultStep key="3" loading={this.props.loading} result={this.props.results} error={this.props.error} onRestartClicked={this.toPrevStep.bind(this)} />, ]; return ( <Row type="flex" justify="center"> <Col {...parentColLayout}> <Steps current={currentStep}> <Step title="Introduction"/> <Step title="Oracle Data Source" /> <Step title="Oracle Query" /> <Step title="Result" /> </Steps> <br/> {steps.filter((step, index) => currentStep === index )} </Col> </Row> ); } } export default TestQueryForm;
var ChemAdvEntryNavEl = React.createClass({ render: function(){ var classes = 'Adv-entry-nav-el ' + this.props.tab; if(this.props.tabs[this.props.level] === this.props.tab){ classes += ' menu-el-loaded'; } return ( <li data-tab={this.props.tab} className={classes} onClick={this.changeTab}> {this.props.text} </li> ); }, changeTab: function(event){ Actions.changeTab({ level: this.props.level, tab: event.target.dataset.tab }) } });
import C from '../constants/actions'; export default function openOrders(state = [], action) { switch (action.type) { case C.SET_USER_OPEN_ORDERS: return action.payload || []; case C.ADD_USER_ORDER: return [action.payload, ...state]; case C.REMOVE_USER_ORDER: return state.filter(item => item.id !== action.payload); default: return state; } }
import React from 'react'; import image404 from './404.png'; const NotFound = () => { return ( <section className="not-found hero is-primary is-bold is-fullheight"> <div className="hero-body"> <div className="container"> <h1 className="title is-1">Uh Oh!</h1> <img src={image404} alt="404 image" /> <p className="subtitle">The page you've requested was not found.</p> <a href="/" className="button is-medium is-info is-inverted is-outlined is-rounded">Back Home</a> </div> </div> </section> ); } export default NotFound;
import React from 'react' import Square from './Square' function Board (props) { let {matrixType, matrix, gapWidth, handleClick, handleTouchStart, handleTouchMove, handleTouchEnd} = props return ( <div className="board" style={{ // width: (matrixType * 100 + (matrixType - 1) * gapWidth) + 'px', // height: (matrixType * 100 + (matrixType - 1) * gapWidth) + 'px', // padding: gapWidth + 'px' }}> { matrix.map((rowArray, rowIndex) => { return rowArray.map((num, columnIndex) => ( <Square key={num} value={num} index={[rowIndex, columnIndex]} gapWidth={gapWidth} matrixType={matrixType} handleClick={handleClick} handleTouchStart={handleTouchStart} handleTouchMove={handleTouchMove} handleTouchEnd={handleTouchEnd} /> )) }) } </div> ) } export default Board
window.onload=function(){ const decorationButton= document.getElementById("myDecorationButon"); //decorationButton.onclick=showAlert; function showAlert(){ alert("Hello, World!"); } decorationButton .addEventListener("click",function(){ document.getElementById("myTextArea").className="textAreaChanged"; console.log(parseInt(x)); }); const ch=document.getElementById("myCheckBox"); const text =document.getElementById("myTextArea"); const pageBody =document.getElementById("bd"); ch.addEventListener("click",function(){ if(ch.checked==true){ text.className="myCheckBox"; pageBody.className="myBody"; } else{ text.className="none"; pageBody.className=""; } }); }
$(document).ready(function() { $("#wordCloud").jQWCloud({ words: [ {word: 'Prashant', weight: 40}, {word: 'Sandeep', weight: 39}, {word: 'Ajinkya', weight: 11, color: 'green'}, {word: 'Rishi', weight: 27}, {word: 'Kuldeep', weight: 36}, {word: 'Vivek', weight: 39}, {word: 'Saheer', weight: 12, color: 'green'}, {word: 'Lohit', weight: 27}, {word: 'Anirudh', weight: 36}, {word: 'Raj', weight: 22}, {word: 'Mohan', weight: 40}, {word: 'Yadav', weight: 39}, {word: 'India', weight: 11, color: 'green'}, {word: 'USA', weight: 27}, {word: 'Sreekar', weight: 36}, {word: 'Ram', weight: 39}, {word: 'Deepali', weight: 12, color: 'green'}, {word: 'Kunal', weight: 27}, {word: 'Rishi', weight: 80}, {word: 'Chintan', weight: 22} ], //cloud_color: 'yellow', minFont: 10, maxFont: 50, //fontOffset: 5, //cloud_font_family: 'Owned', //verticalEnabled: false, padding_left: 1, //showSpaceDIV: true, //spaceDIVColor: 'white', word_common_classes: 'WordClass', word_mouseEnter :function(){ $(this).css("text-decoration","underline"); }, word_mouseOut :function(){ $(this).css("text-decoration","none"); }, word_click: function(){ alert("You have selected:" +$(this).text()); }, beforeCloudRender: function(){ date1=new Date(); }, afterCloudRender: function(){ var date2=new Date(); console.log("Cloud Completed in "+(date2.getTime()-date1.getTime()) +" milliseconds"); } }); });
const AV = require('lib/leancloud-storage'); AV.init({ appId: '03kfWtO56pCUw6bmPTJREwTA-gzGzoHsz', appKey: 'RY8S4ezaMJ9bMGGG45unyyEX', }); var Promise = require("lib/es6-promise.min"); var util = require('lib/util') var getUserInfoPromisified = util.wxPromisify(wx.getUserInfo); App({ onLaunch: function () { this.initUserInfo(); }, onShow: function () { // this.initUserInfo(); }, //初始化用户信息 //返回用户类型:'教师'/'学生' initUserInfo: function () { var that = this; AV.User.loginWithWeapp() .then(function () { var user = AV.User.current(); if (user.get('register') !== true) { // 首次登陆需要初始化身份数据 that.register(); } else { //用户已经注册过 that.updateUserInfo() .then(function () { wx.hideToast(); }) .catch(console.error); } }) .catch(console.error); }, //更新、从云端下载用户信息,对app.global.data赋值 updateUserInfo: function () { var that = this; var user = AV.User.current(); return new Promise(function (resolve, reject) { // 调用小程序 API,得到用户信息 getUserInfoPromisified({}) .then(function (res) { // 更新当前用户的信息 user.set(res.userInfo).save() .then(function (user) { // 成功,此时可在控制台中看到更新后的用户信息 var userQuery = new AV.Query('_User'); userQuery.include('leaves');//是否要在初始化时加载请假数据??? userQuery.include('coursesChosen');//是否要在初始化时加载选课数据??? userQuery.include('courses');//是否要在初始化时加载选课数据??? userQuery.get(user.id).then(function (user) { that.globalData.user = user.toJSON(); that.globalData.debug && console.log("Update userinfo on leanCloud success, that.globalData.user:", that.globalData.user) resolve(); }); }) .catch(function (err) { reject(err); }); }) .catch(function () { that.globalData.user = user.toJSON(); resolve(); }); }); }, onHide: function () { }, //注册 register: function () { wx.redirectTo({ url: 'pages/login/login', success: function (res) { that.globalData.debug && console.log("page.login redirected..") }, fail: function () { that.globalData.debug && console.log('redirect fail!') }, complete: function () { // complete } }) }, globalData: { user: null, signInTag: [], leaveTag: [], debug: true } })
let code = {}; code.base = ` \`\`\`javascript <template> <mod-select v-model="selectValue"> <mod-select-item :value="1" label="测试1">测试1</mod-select-item> <mod-select-item :value="2" label="测试2">测试2</mod-select-item> </mod-select> <p>绑定v-model: {{ selectValue }}</p> </template> \`\`\` `; code.style = ` \`\`\`javascript <mod-select :customStyle="{width: '500px', height: '40px', backgroundColor: '#ff5a00', color: '#fff'}" placeholderColor="#fff" openedBorderColor="#fa0" v-model="selectValue"> <mod-select-item :value="1" label="测试1">测试1</mod-select-item> <mod-select-item :value="2" label="测试2">测试2</mod-select-item> </mod-select> \`\`\` `; code.event = ` \`\`\`javascript <mod-select v-model="selectValue3" @change="onChange"> <mod-select-item :value="1" label="测试1">测试1</mod-select-item> <mod-select-item :value="2" label="测试2">测试2</mod-select-item> </mod-select> \`\`\` `; code.change = ` \`\`\`javascript <mod-select v-model="selectValue4" > <mod-select-item :value="1" label="测试1">测试1</mod-select-item> <mod-select-item :value="2" label="测试2">测试2</mod-select-item> </mod-select> <a @click="selectValue4 = 2" href="javascript:void(0)">改变 {{ selectValue4 }}</a> \`\`\` `; code.disabled = ` \`\`\`javascript <mod-select :disabled="true" v-model="selectValue4" > <mod-select-item :value="1" label="测试1">测试1</mod-select-item> <mod-select-item :value="2" label="测试2">测试2</mod-select-item> </mod-select> <a @click="selectValue4 = 2" href="javascript:void(0)">改变 {{ selectValue4 }}</a> \`\`\` `; export default code;
function initializer(carouselSlides, slideCaption, carouselNum) { console.log(carouselSlides.length); console.log(carouselSlides); console.log(document.querySelector(".carousel")); window.currentImage = 0; for (var i = 0; i < carouselSlides.length; i++) { var imageDad = document.createElement("div"); imageDad.setAttribute("class", "carSlide"); var imageSon = document.createElement("img"); imageSon.setAttribute("class", "carPic"); var imageCaption = document.createElement("div"); imageSon.setAttribute("src", carouselSlides[i]); imageCaption.setAttribute("id", "caption"); imageCaption.innerHTML = slideCaption[i]; //make contents of p whatever's in slideCaption array, slideCaption[i]); imageDad.appendChild(imageSon); imageDad.appendChild(imageCaption); document.querySelector(carouselNum).appendChild(imageDad); } showImage(0, carouselNum); } function showImage(imageIndex, carouselNum) { $(carouselNum + " .carSlide") .toArray() .forEach((imgEl) => { $(imgEl).hide(); }); $($(carouselNum + " .carSlide").toArray()[imageIndex]).show(); currentImage = imageIndex; } function showNext(carouselNum, carouselSlides) { if (currentImage >= carouselSlides.length - 1) { showImage(0, carouselNum); } else { showImage(currentImage + 1, carouselNum); } } function showPrev(carouselNum, carouselSlides) { if (currentImage == 0) { showImage(carouselSlides.length - 1, carouselNum); } else { showImage(currentImage - 1, carouselNum); } }
document.addEventListener("deviceready", init, false); function init() { //相机 function onSuccess(imageData) { console.log('success'); var image = document.getElementById('myImage'); image.src = imageData; var options = { onError: function() { alert('ERROR'); } }; var effect = { vignette: 0.6, sepia: true }; new VintageJS(image, options, effect); } function onFail(message) { alert('Failed because: ' + message); } //Use from Camera document.querySelector("#takePicture").addEventListener("touchend", function() { navigator.camera.getPicture(onSuccess, onFail, { quality: 50, sourceType: Camera.PictureSourceType.CAMERA, destinationType: Camera.DestinationType.FILE_URI }); }); //Use from Library document.querySelector("#usePicture").addEventListener("touchend", function() { navigator.camera.getPicture(onSuccess, onFail, { quality: 50, sourceType: Camera.PictureSourceType.PHOTOLIBRARY, destinationType: Camera.DestinationType.FILE_URI }); }); //二维码 document.querySelector("#startScan").addEventListener("touchend", startScan, false); var resultDiv = document.querySelector("#results"); function startScan() { cordova.plugins.barcodeScanner.scan( function (result) { var s = "Result: " + result.text + "<br/>" + "Format: " + result.format + "<br/>" + "Cancelled: " + result.cancelled; resultDiv.innerHTML = s; }, function (error) { alert("Scanning failed: " + error); } ); } }
module.exports = { "rootpath": "/api/method/", "description": "模块功能管理", "mapping": { "default": { "description": "通过查询条件筛选,返回经过分页处理的模块功能列表。" }, "insert": { "description": "新增一个模块功能" }, "update": { "description": "修改模块功能详细信息" }, "delete": { "description": "删除一个模块功能" } }, "entity": { "table": "methodinfo", "columns": [ { "name": "methodid", "caption": "功能编号", "primary": true, "filter": "like" }, { "name": "methodname", "caption": "功能名称", "filter": "like", "requid": true }, { "name": "remark", "caption": "功能描述" }, ] } };
export const ADD_TO_CART='ADD_TO_CART' export const REMOVE_CART='REMOVE_CART' export const addToCart=key=>{ return{ type:ADD_TO_CART,key } } export const removeFromCart=key=>{ return{ type:REMOVE_CART,key } }
// Timer delay var waitTime = 3000; console.log("Wait for it"); //Intervals var currentTime = 0; var waitInterval = 500; //Percent waited var percentWaited = 0; // USING STANDARD OUT function writeWaitingPercent(p){ //Clears last line in the terminal process.stdout.clearLine(); //Move cursor back to the start of the line process.stdout.cursorTo(0); process.stdout.write(`Waiting... ${p}`); } var interval = setInterval(function(){ currentTime += waitInterval; // Wait time in percentage percentWaited = Math.floor((currentTime/waitTime) * 100); writeWaitingPercent(percentWaited); //console.log("\n\n\n"); //Waited time In seconds //console.log(`waiting ${currentTime/1000} seconds...`); }, waitInterval); setTimeout(function(){ clearInterval(interval); writeWaitingPercent(100); console.log("Done"); }, waitTime); process.stdout.write("\n\n"); writeWaitingPercent(percentWaited);
import React, { useState } from "react"; import { useDispatch, useSelector } from "react-redux"; import styled from "styled-components"; import { useHistory } from "react-router-dom"; import { Search } from "@styled-icons/fluentui-system-filled/Search"; import { clearListProfiles } from "../redux/actions/profileActions"; // Components import VerticalLogo from "../assets/logo-vertical.svg"; import TogglerDarkTheme from "../components/TogglerDarkTheme"; const HomeScreen = () => { const [inputText, setInputText] = useState(""); const [msg, setMsg] = useState(""); const [error, setError] = useState(false); const history = useHistory(); const dispatch = useDispatch(); const { darkMode } = useSelector((state) => state.darkMode); const changeHandler = (e) => { setInputText(e.target.value); setError(false); }; const submitHandler = (e) => { e.preventDefault(); if (inputText !== "") { dispatch(clearListProfiles()); history.push(`/search?q=${inputText}`); } else { setError(true); setMsg("Please, enter some value"); } }; return ( <Main darkMode={darkMode}> <TogglerDarkTheme /> <Container darkMode={darkMode}> <div> <img src={VerticalLogo} alt="Logo" /> </div> <form onSubmit={submitHandler}> <div className="form-control"> <input type="text" placeholder="Enter user name" onChange={changeHandler} autoCorrect="off" value={inputText} /> {error ? <span className="msg">{msg}</span> : ""} </div> <div> <button type="submit" value="Search"> Search <span> <SearchIcon /> </span> </button> </div> </form> </Container> </Main> ); }; export default HomeScreen; const Main = styled.main` display: flex; flex-direction: column; width: 100%; align-items: center; justify-content: center; min-height: 100vh; margin: 0 auto; input { background: transparent; border: none; outline: none; } `; const Container = styled.div` width: 300px; max-width: 95%; display: flex; align-items: center; justify-content: center; flex-direction: column; form { width: 100%; max-width: 95%; .form-control { color: ${(props) => (props.error ? "red" : "transparent")}; } div { position: relative; .msg { position: absolute; left: 2px; bottom: -22px; color: #d64646de; font-size: 0.85rem; font-style: italic; animation-duration: 0.3s; animation-name: error; } @keyframes error { 0% { } 20% { transform: translateX(-20px); } 40% { transform: translateX(20px); } 60% { transform: translateX(-20px); } 80% { transform: translateX(20px); } 100% { transform: translateX(0); } } &:nth-of-type(1) { margin: 30px 0 55px; } input { padding: 10px 0; width: 100%; margin: 0 auto; border: none; border-bottom: 4px solid; border-color: #8752cc; color: ${(props) => (props.darkMode ? "#232324" : " white")}; caret-color: #535353; font-size: 18px; font-weight: 700; position: relative; &:focus { border-bottom: 2px solid; padding-bottom: 12px; border-color: #8752cc; } ::placeholder { color: ${(props) => (props.darkMode ? "white" : "#535353 ")}; font-size: 18px; text-align: center; } } button { width: 100%; font-family: inherit; font-weight: 700; font-size: inherit; background: #8752cc; color: white; padding: 12px 0; border-radius: 5px; border: none; cursor: pointer; display: flex; align-items: center; justify-content: center; &:hover { background: #64418c; } } } } `; const SearchIcon = styled(Search)` width: 22px; font-weight: bold; margin-left: 6px; `;
const express = require('express') const Router = express.Router() Router.get('/login',(req,res)=>{ res.send({ a:1 }) }) Router.post('/login',(req,res)=>{ res.send({ name:'aaa', type:'boss' }) }) Router.post('/register',(req,res)=>{ res.send({ aa:1 }) }) module.exports = Router
/* eslint-env mocha */ /* eslint-disable no-unused-vars */ const { assert } = require('chai'); const { resetDB } = require('../../src/db'); const Subscription = require('../../src/models/subscription'); const { ValidationError } = require('../../src/services/validators'); // Define some dummy valid addresses. const wtIndex = '0x7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b7b', resourceType = 'hotel', resourceAddress = '0x6a4a4a4a4a4a4a4a4a4a4a4a4a4a4a4a4a4a4a4a'; describe('models - subscription', () => { describe('create', () => { it('should create a new subscription and return its representation', async () => { const subscription = await Subscription.create({ wtIndex, resourceType, resourceAddress, action: 'create', subjects: ['description', 'ratePlans'], url: 'http://example.com/callback', }); assert.property(subscription, 'id'); assert.equal(subscription.id.length, 32); assert.propertyVal(subscription, 'wtIndex', wtIndex); assert.propertyVal(subscription, 'resourceType', resourceType); assert.propertyVal(subscription, 'resourceAddress', resourceAddress); assert.propertyVal(subscription, 'action', 'create'); assert.propertyVal(subscription, 'url', 'http://example.com/callback'); assert.property(subscription, 'subjects'); assert.deepEqual(subscription.subjects, ['description', 'ratePlans']); assert.propertyVal(subscription, 'active', true); }); it('should work without optional attributes', async () => { const subscription = await Subscription.create({ wtIndex, resourceType, url: 'http://example.com/callback', }); assert.property(subscription, 'id'); assert.propertyVal(subscription, 'wtIndex', wtIndex); assert.propertyVal(subscription, 'resourceType', resourceType); assert.propertyVal(subscription, 'url', 'http://example.com/callback'); assert.propertyVal(subscription, 'active', true); assert.equal(subscription.hotel, undefined); assert.equal(subscription.action, undefined); assert.equal(subscription.subjects, undefined); }); }); describe('get', () => { it('should get a previously created subscription', async () => { const data = { wtIndex, resourceType, resourceAddress, action: 'delete', subjects: ['ratePlans'], url: 'http://example.com/callback', }, { id } = await Subscription.create(data), subscription = await Subscription.get(id); assert.deepEqual(subscription, Object.assign({ id, active: true }, data)); }); it('should normalize falsy values', async () => { const data = { wtIndex, resourceType, resourceAddress: undefined, action: null, subjects: [], url: 'http://example.com/callback', active: false, }, { id } = await Subscription.create(data), subscription = await Subscription.get(id); assert.deepEqual(subscription, { id, wtIndex, resourceType, url: 'http://example.com/callback', active: false, }); }); it('should return undefined if no such account exists', async () => { const subscription = await Subscription.get(9923448); assert.equal(subscription, undefined); }); }); describe('deactivate', () => { it('should deactivate an existing Subscription', async () => { let subscription = await Subscription.create({ wtIndex, resourceType, url: 'http://example.com/callback', }); assert.propertyVal(subscription, 'active', true); await Subscription.deactivate(subscription.id); subscription = await Subscription.get(subscription.id); assert.propertyVal(subscription, 'active', false); }); it('should return boolean based on whether the deactivation was successful or not', async () => { const subscription = await Subscription.create({ wtIndex, resourceType, url: 'http://example.com/callback', }); let deactivated = (await Subscription.deactivate(subscription.id)); assert.equal(deactivated, true); deactivated = (await Subscription.deactivate(subscription.id)); assert.equal(deactivated, false); // Second deactivation did noting. deactivated = (await Subscription.deactivate('nonexistent')); assert.equal(deactivated, false); }); }); describe('getURLs', () => { const address1 = '0x6a4a4a4a4a4a4a4a4a4a4a4a4a4a4a4a4a4a4a4a', address2 = '0x6b4b4b4b4b4b4b4b4b4b4b4b4b4b4b4b4b4b4b4b'; let s1, s2, s3, s4, s5, s6, s7, s8, s9, s10; before(async () => { await resetDB(); const base = { wtIndex, resourceType }; s1 = await Subscription.create(Object.assign({ resourceAddress: address1, url: 'http://example1.com', }, base)); s2 = await Subscription.create(Object.assign({ resourceAddress: address2, url: 'http://example2.com', action: 'create', }, base)); s3 = await Subscription.create(Object.assign({ // Intentionally duplicate resourceAddress: address2, url: 'http://example2.com', action: 'create', }, base)); s4 = await Subscription.create(Object.assign({ resourceAddress: address2, url: 'http://example3.com', action: 'update', }, base)); s5 = await Subscription.create(Object.assign({ resourceAddress: address2, url: 'http://example4.com', action: 'update', subjects: ['ratePlans', 'description'], }, base)); s6 = await Subscription.create(Object.assign({ resourceAddress: address2, url: 'http://example5.com', action: 'update', subjects: ['availability'], }, base)); s7 = await Subscription.create(Object.assign({ url: 'http://example6.com', }, base)); s8 = await Subscription.create(Object.assign({ action: 'update', url: 'http://example7.com', }, base)); s9 = await Subscription.create(Object.assign({ action: 'delete', url: 'http://example8.com', }, base)); s10 = await Subscription.create(Object.assign({ action: 'create', url: 'http://example9.com', active: false, }, base)); }); it('should return the set URLs with corresponding IDs based on the given criteria', async () => { const urls = await Subscription.getURLs({ wtIndex, resourceType, resourceAddress: address2, action: 'update', subjects: ['ratePlans'], }); assert.deepEqual(urls, { urls: { 'http://example3.com': [s4.id], 'http://example4.com': [s5.id], 'http://example6.com': [s7.id], 'http://example7.com': [s8.id], }, next: null, }); }); it('should work with multiple subjects', async () => { const urls = await Subscription.getURLs({ wtIndex, resourceType, resourceAddress: address2, action: 'update', subjects: ['ratePlans', 'availability'], }); assert.deepEqual(urls, { urls: { 'http://example3.com': [s4.id], 'http://example4.com': [s5.id], 'http://example5.com': [s6.id], 'http://example6.com': [s7.id], 'http://example7.com': [s8.id], }, next: null, }); }); it('should work without subject', async () => { const urls = await Subscription.getURLs({ wtIndex, resourceType, resourceAddress: address2, action: 'delete', }); assert.deepEqual(urls, { urls: { 'http://example6.com': [s7.id], 'http://example8.com': [s9.id], }, next: null, }); }); it('should return all IDs belonging to a given URL', async () => { const urls = await Subscription.getURLs({ wtIndex, resourceType, resourceAddress: address2, action: 'create', }); assert.deepEqual(urls, { urls: { 'http://example2.com': [s2.id, s3.id].sort(), 'http://example6.com': [s7.id], }, next: null, }); }); it('should limit the number of returned objects, if requested', async () => { const urls = await Subscription.getURLs({ wtIndex, resourceType, resourceAddress: address2, action: 'update', subjects: ['ratePlans'], }, 3); assert.deepEqual(urls, { urls: { 'http://example3.com': [s4.id], 'http://example4.com': [s5.id], 'http://example6.com': [s7.id], }, next: { url: 'http://example7.com', id: s8.id }, }); }); it('should start from the specified offset, if any', async () => { const urls = await Subscription.getURLs({ wtIndex, resourceType, resourceAddress: address2, action: 'update', subjects: ['ratePlans'], }, 3, { url: 'http://example6.com', id: s7.id }); assert.deepEqual(urls, { urls: { 'http://example6.com': [s7.id], 'http://example7.com': [s8.id], }, next: null, }); }); }); });
import React from 'react'; import { shallow } from 'enzyme'; import WeatherDisplay from './WeatherDisplay'; it('should match the snapshot with all data passed in correctly', () => { const mockProps = { weatherCurrentData: {desc: 'current weather info'}, weatherDaysData: {desc: 'five days weather info'}, searchCity: 'Denver' } const block = shallow( <WeatherDisplay {...mockProps} /> ); expect(block).toMatchSnapshot(); });
'use strict'; class InscribedRepository { constructor(repository) { this.repository = repository; } createInscribed(inscribedData) { return this.repository.createInscribed(inscribedData); } deleteInscribed(inscribedData) { return this.repository.deleteInscribed(inscribedData); } getListInscribed(ExamId) { return this.repository.getListInscribed(ExamId); } getInscribed(UserId) { return this.repository.getInscribed(UserId); } isInscribed(inscribedData) { return this.repository.isInscribed(inscribedData); } } module.exports = InscribedRepository;
import Vue from 'vue' import ElementUI from 'element-ui' import elementZhLocale from 'element-ui/lib/locale/lang/zh-CN'// element-ui lang i18n console.log(process.env) import { mockXHR } from './mock' if(process.env.NODE_ENV == 'development'){ mockXHR(); } import '@/styles/index.scss' // global css import App from './App' import router from './router' import store from './store' //import '@/filter' import waves from "@/directive/waves" Vue.use(waves) import hasPermission from '@/directive/permission' hasPermission.install(Vue) // import and init directive `hasPermission` for global Vues import '@/icons' // icon import '@/permission' // permission control Vue.use(ElementUI, { elementZhLocale }) import Vant from 'vant'; import 'vant/lib/index.css'; Vue.use(Vant); Vue.config.productionTip = false // 设置为false以阻止vue在启动时生成生产提示 import moment from 'moment' // moment Object.defineProperty(Vue.prototype, '$moment', { value: moment }) import auth from '@/utils/auth' // auth Object.defineProperty(Vue.prototype, '$auth', { value: auth }) import CommonUtil from '@/utils/commonUtil' Object.defineProperty(Vue.prototype, '$phSpt', { value: CommonUtil.placeholderSupport() }) // Object.defineProperty(Vue.prototype, '$ifJfw2Jportal', { value: process.env.NODE_ENV === 'production' }) // true-不展示nav和header, false-正常展示 Object.defineProperty(Vue.prototype, '$ifJfw2Jportal', { value: true }) // 统一样式 Object.defineProperty(Vue.prototype, '$FormInputSize', { value: 'mini' }) Object.defineProperty(Vue.prototype, '$FormBtnSize', { value: 'medium' }) import dataService from '@/utils/request'; Vue.prototype.$dataService = dataService; new Vue({ el: '#app', router, store, template: '<App/>', components: { App } })
// @ts-check import { useRef, useState } from "react"; import callfunc from "call-func"; /** * @template ValueType * @param {ValueType|function():ValueType} [value] * @return {React.MutableRefObject<ValueType|undefined>} */ const useRefInitCallback = (value) => { /** * @type {React.MutableRefObject<ValueType|undefined>} */ const last = useRef(); useState(()=> { last.current = callfunc(value) }); return last; }; export default useRefInitCallback;
import React, { Component } from 'react'; export default class Pad extends Component { constructor(props) { super(props); this.state = { isPlaying: this.props.isPlaying, showEdit: false }; this.showEditFields = this.showEditFields.bind(this); } showEditFields() { let divID = "editFields" + this.props.ID; let showEditFields = document.getElementById(divID); if (!this.state.showEdit) { showEditFields.style.display = "block"; } else { showEditFields.style.display = "none"; } this.setState({ showEdit: !this.state.showEdit }); } render() { let textColor = this.state.isPlaying ? "text-warning" : "text-secondary"; return ( <div class="col-4 p-1"> <div class="bg-white rounded shadow"> <h1 class="display-1 text-success justify-content-center align-items-center">Pad {this.props.ID + 1}</h1> </div> </div> ) } }
import React from "react" import styled from "styled-components" import FourteenDayTrialForm from "../../Forms/FourteenDayTrialForm" import Headline3 from "../../Headlines/Headline3" const FormSection = () => { return ( <FormContainer> <div id="fill-out-fourteen-form" /> <Headline3>Get Your Guides & Get Your 14 Day Trial:</Headline3> <FourteenDayTrialForm /> </FormContainer> ) } export default FormSection const FormContainer = styled.div` margin: 80px 0 80px 0; padding: 0 12px; display: grid; grid-template-columns: 1fr; gap: 12px; justify-items: center; width: 100%; max-width: 800px; `