text
stringlengths
7
3.69M
$('.burger-button, .menu__item').on('click',function(){ $('.menu__navigation').toggleClass('active'); $('.burger-button__first-serif, .burger-button__second-serif, .burger-button__third-serif').toggleClass('active'); $('body').toggleClass('lock'); $(this).toggleClass('active'); }); function appearing(){ var x = $(window).scrollTop(); console.log(x); if(x > 204){ $('.column__info').addClass('appear'); } } appearing(); $(window).on('scroll', appearing); // $(window).on('scroll', function(){ // $('.column__info').addClass('appear'); // }); function UpArrow(){ var scrollTop = $(window).scrollTop(); console.log(scrollTop); if(scrollTop > 900){ $('.up').addClass('visible'); } else{ $('.up').removeClass('visible'); } }; UpArrow(); $(window).on('scroll', UpArrow); $('.up').on('click', function(){ $('html').animate({ scrollTop: 0 }); });
/* * @lc app=leetcode id=133 lang=javascript * * [133] Clone Graph */ // @lc code=start /** * // Definition for a Node. * function Node(val, neighbors) { * this.val = val === undefined ? 0 : val; * this.neighbors = neighbors === undefined ? [] : neighbors; * }; */ /** * @param {Node} node * @return {Node} */ var cloneGraph = function (node) { if (!node) { return null; } function Node(val, neighbors) { this.val = val === undefined ? 0 : val; this.neighbors = neighbors === undefined ? [] : neighbors; } const nodeMap = {}; function copy(node) { if (nodeMap[node.val]) { return nodeMap[node.val]; } const copyNode = new Node(node.val, []); nodeMap[copyNode.val] = copyNode; for (const neiNode of node.neighbors) { copyNode.neighbors.push(copy(neiNode)); } return copyNode; } const result = copy(node); return result; }; // @lc code=end function Node(val, neighbors) { this.val = val === undefined ? 0 : val; this.neighbors = neighbors === undefined ? [] : neighbors; } const node1 = new Node(1); const node2 = new Node(2); const node3 = new Node(3); const node4 = new Node(4); node1.neighbors = [node2, node4]; node2.neighbors = [node1, node3]; node3.neighbors = [node2, node4]; node4.neighbors = [node1, node3]; cloneGraph(node1);
import React, { useState, useEffect } from 'react'; import { StyleSheet, Text, View, Button, Platform } from 'react-native'; import { createStackNavigator } from 'react-navigation-stack'; import { createBottomTabNavigator } from 'react-navigation-tabs'; import { createDrawerNavigator } from 'react-navigation-drawer'; import Colors from '../constants/colors'; import DefaultText from '../components/defaultText'; import MealListItem from '../components/mealListItem'; import MealList from '../components/mealList'; import { CATEGORIES } from '../data/dummyData'; import { useSelector } from 'react-redux'; const CategoryMealsScreen = (props) => { const catId = props.navigation.getParam('categoryId'); const availableMeals = useSelector((state) => state.meals.filteredMeals); const displayedMeals = availableMeals.filter((meal) => { return meal.categoryIds.indexOf(catId) >= 0; }); if (displayedMeals.length === 0) { return ( <View style={styles.content}> <DefaultText> Some filters are set which may be filtering these meals </DefaultText> </View> ); } return <MealList listData={displayedMeals} navigation={props.navigation} />; }; // apply title of screen to header based on category title CategoryMealsScreen.navigationOptions = (navigationData) => { const catId = navigationData.navigation.getParam('categoryId'); const selectedCategory = CATEGORIES.find((cat) => { return cat.id === catId; }); return { headerTitle: selectedCategory.title, }; }; const styles = StyleSheet.create({ container: { flex: 1, alignItems: 'center', justifyContent: 'center', }, content: { flex: 1, justifyContent: 'center', alignItems: 'center', }, }); export default CategoryMealsScreen;
const express = require("express"); const app = express(); // const fs = require("fs"); // const options = { // key: fs.readFileSync("./cert/key.pem"), // cert: fs.readFileSync("./cert/cert.pem"), // }; // let https = require("https").Server(options, app); let http = require("http").Server(app); // let io = require("socket.io")(https); let io = require("socket.io")(http); const port = process.env.PORT || 3000; app.use(express.static("public")); http.listen(port, () => { console.log("listening on port " + port); }); io.on("connection", (socket) => { console.log("A User Connected"); socket.on("createRoomOrJoin", ({ roomId, userName }) => { console.log("create or join room ", roomId); const myRoom = io.sockets.adapter.rooms[roomId + ""]; const numClients = myRoom ? myRoom.length : 0; console.log("room " + roomId + " has " + numClients + " connected clients"); if (numClients === 0) { socket.join(roomId); console.log(socket.id); socket.emit("roomCreated"); } else if (numClients >= 1 && numClients <= 49) { socket.join(roomId); console.log(myRoom); // To new Cleint socket.emit("roomJoined"); // To host Only io.to(Object.keys(myRoom.sockets)[0]).emit("newUserJoinedRoom", { clientId: socket.id, clientName: userName, }); } else { console.log(socket.adapter.rooms[roomId + ""]); socket.emit("roomFull", roomId); } }); // establishing RTC connection in 4 steps and server works as msg farworder only socket.on("ready", (event) => { console.log("ready called"); // Sending to HOST only io.to(Object.keys(socket.adapter.rooms)[0]).emit("ready", event); }); socket.on("ICEagentFromHost", (event) => { console.log("ICE agent data from "); io.to(event.roomId).to(event.clientId).emit("ICEagentFromHost", event); }); socket.on("ICEagentFromClient", (event) => { console.log("ICE agent data from "); io.to(event.roomId) .to(Object.keys(socket.adapter.rooms)[0]) .emit("ICEagentFromClient", event); }); socket.on("offer", (event) => { console.log("ready offer"); // Sending to Client io.to(event.clientId).emit("offer", event.sdp); }); socket.on("answer", (event) => { console.log("ready answer"); // Sending to Host only io.to(Object.keys(socket.adapter.rooms)[0]).emit("answer", event); }); socket.on("disconnect", (err) => { console.log("A user disconnected", err); if (socket.adapter.rooms) { console.log("sending host a user left"); io.to(Object.keys(socket.adapter.rooms)[0]).emit("AUserLeftRoom", { clientId: socket.id, }); } }); });
 eschar.footer = (function () { "use strict"; var initModule, setDocMap, setInfo, cfgMap = { "main_html": String() + "<div class='footer-info' id='footer-info-text-one'>" + "<span></span>" + "</div>" + "<div class='footer-info' id='footer-info-text-two'>" + "<span></span>" + "</div>" + "<div class='footer-info' id='footer-info-text-three'>" + "<span></span>" + "</div>" + "<div class='footer-info' id='footer-info-text-four'>" + "<span></span>" + "</div>" }, docMap = {}; setDocMap = function () { docMap.footer = {}; docMap.footer.one = document.getElementById("footer-info-text-one"); docMap.footer.two = document.getElementById("footer-info-text-two"); docMap.footer.three = document.getElementById("footer-info-text-three"); docMap.footer.four = document.getElementById("footer-info-text-four"); }; setInfo = function (_elem, _text) { docMap.footer[_elem].textContent = _text; }; initModule = function (_container) { _container.innerHTML = cfgMap.main_html; setDocMap(); return true; }; return { "initModule": initModule, "setInfo": setInfo }; }()); //eschar.footer.setInfo("one", "catgrp.handleClick"); //eschar.footer.setInfo( // "two", "Skills: " // + eschar.chassis.getGroupSkillCount(eschar.chassis.getSelectedGroup()) //); //eschar.footer.setInfo("three", "First: " + grpAbilities[0].name); //eschar.footer.setInfo( // "four", "Knowledge: " // + eschar.chassis.getCharacterGroupPoints(eschar.chassis.getSelectedGroup()._id) //);
var apiBasepath = 'https://api.github.com'; function getUserAndIdFromRepoURL(url) { url = url.split('/'); if (url[2] === 'github.com') { return { "id": url[4], "user": url[3] }; } else { return {"error" : "That's not a GitHub URL… :("} }; } // Maybe not needed. Hm. function getRepoOwnerWithIdByUser(id, user) { var apiEndpath = '/repos/' + user + '/' + id; $.ajax(apiBasepath + apiEndpath) .done(function(data) { return(data['owner']['login']); }) .fail(function() { alert( "error" ); }); } function getRepoStatsWithOwnerAndId(owner, id) { var apiEndpath = '/repos/' + owner + '/' + id + '/stats/contributors'; $.ajax(apiBasepath + apiEndpath) .done(function(data) { buildingTowers(data); }) .fail(function() { alert( "error" ); }); }
export const SET_TEST = 'SET_TEST' export const SET_FINDBULLETIN_PAGE = 'SET_FINDBULLETIN_PAGE' export const SET_ALL_SYSTEM_MSG_LIST = 'SET_ALL_SYSTEM_MSG_LIST' export const SET_ALL_COURSE_MSG_LIST = 'SET_ALL_COURSE_MSG_LIST' export const SET_COURSE_MSG_LIST_GONG_GAO = 'SET_COURSE_MSG_LIST_GONG_GAO' export const GET_ALL_ADVER_TI_SING_LIST = 'GET_ALL_ADVER_TI_SING_LIST' export const GET_FIND_STUDENT_NUMBERLIST = 'GET_FIND_STUDENT_NUMBERLIST'
import angular from 'angular' import resource from 'angular-resource' class pokedexService { constructor($resource) { this.pokedex = $resource('http://pokeapi.co/api/v2/pokemon/', {}, { get: { cached: true, method: 'get' } }) } } pokedexService.$inject = ['$resource'] export default angular .module('pokedex.service', [ resource ]) .service('pokedexService', pokedexService) .name
/* * Copyright 2018 Cognitive Scale, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the “License”); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an “AS IS” BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ const fs = require('fs'); const yeoman = require('yeoman-environment'); const debug = require('debug')('cortex:cli'); const { loadProfile } = require('../config'); const Environments = require('../client/environments'); const Content = require('../client/content'); const { printSuccess, printError, filterObject, parseObject, printTable } = require('./utils'); const _ = require('lodash/object'); module.exports.ListEnvironments = class ListEnvironments { constructor(program) { this.program = program; } execute(options) { const profile = loadProfile(options.profile); debug('%s.listEnvironment()', profile.name); const envs = new Environments(profile.url); envs.listEnvironments(profile.token).then((response) => { if (response.success) { let result = _.get(response,'result.environments',[]); if (options.query) result = filterObject(result, options); if (options.json) { printSuccess(JSON.stringify(result, null, 2), options); } else { let tableSpec = [ { column: 'Name', field: 'name', width: 25 }, { column: 'Title', field: 'title', width: 50 }, { column: 'Region', field: 'regionRef', width: 25 } ]; printTable(tableSpec, result); } } else { printError(`Failed to list environments: ${response.status} ${response.message}`, options); } }) .catch((err) => { debug(err); printError(`Failed to list environments: ${err.status} ${err.message}`, options); }); } }; module.exports.SaveEnvironmentCommand = class SaveEnvironmentCommand { constructor(program) { this.program = program; } execute(environmentDefinition, options) { const profile = loadProfile(options.profile); debug('%s.executeSaveDefinition(%s)', profile.name, environmentDefinition); const envDefStr = fs.readFileSync(environmentDefinition); const envObj = parseObject(envDefStr, options); debug('%o', envObj); const environment = new Environments(profile.url); environment.saveEnvironment(profile.token, envObj) .then((response) => { if (response.success) { printSuccess(`Environment \'${envObj.name}\' saved`, options); } else { printError(`Failed to save environment: ${response.status} ${response.message}`, options); }}) .catch((err) => { printError(`Failed to save environment: ${err.response.body.message}`, options); }); } }; module.exports.DescribeEnvironmentCommand = class DescribeEnvironmentCommand { constructor(program) { this.program = program; } execute(environmentName, options) { const profile = loadProfile(options.profile); debug('%s.executeDescribeEnvironment(%s)', profile.name, environmentName); const environment = new Environments(profile.url); environment.describeEnvironment(profile.token, environmentName).then((response) => { if (response.success) { let result = filterObject(response.result, options); printSuccess(JSON.stringify(result, null, 2), options); } else { printError(`Failed to describe environment ${environmentName}: ${response.message}`, options); } }) .catch((err) => { printError(`Failed to describe environment ${environmentName}: ${err.status} ${err.message}`, options); }); } }; module.exports.ListInstancesCommand = class ListInstancesCommand { constructor(program) { this.program = program; } execute(environmentName, options) { const profile = loadProfile(options.profile); debug('%s.executeListInstances(%s)', profile.name, environmentName); const environment = new Environments(profile.url); environment.listInstances(profile.token, environmentName).then((response) => { if (response.success) { let result = _.get(response,'result.instances',[]); if (options.query) result = filterObject(result, options); if (options.json) { printSuccess(JSON.stringify(result, null, 2), options); } else { let tableSpec = [ { column: 'Instance Id', field: 'id', width: 26 }, { column: 'Status', field: 'status', width: 15 }, { column: 'Snapshot Id', field: 'snapshotId', width: 40 }, { column: 'Agent Name', field: 'agentName', width: 50 }, { column: 'Agent Version', field: 'agentVersion', width: 15 }, { column: 'Environment', field: 'environmentName', width: 26 }, { column: 'Created At', field: 'createdAt', width: 26 }, ]; printTable(tableSpec, result); } } else { printError(`Failed to list instances in environment ${environmentName}: ${response.message}`, options); } }) .catch((err) => { printError(`Failed to list instances in environment ${environmentName}: ${err.status} ${err.message}`, options); }); } }; module.exports.PromoteEnvironmentCommand = class PromoteEnvironmentCommand { constructor(program) { this.program = program; } execute(promoteDefinition, options) { const profile = loadProfile(options.profile); debug('%s.executePromoteDefinition(%s)', profile.name, promoteDefinition); let promObj; if ( promoteDefinition ) { const promStr = fs.readFileSync(promoteDefinition); promObj = parseObject(promStr, options); } else if ( _.get(options,'snapshotId','').length > 0 && _.get(options,'environmentName','').length > 0) { promObj = { snapshotId: options.snapshotId, environmentName: options.environmentName } } else { printError(`Either --snapshotId <..> and --environmentName <..> or a promotion definition file must be provided`, options); return; } debug('%o', promObj); const environment = new Environments(profile.url); environment.promoteEnvironment(profile.token, promObj) .then((response) => { if (response.success) { printSuccess(`Snapshot \'${promObj.snapshotId}\' successfully promoted to \'${promObj.environmentName}\' environment. Instance \'${response.message.instanceId}\' created.`, options); } else { let errMsg = `Failed to promote to environment: ${response.status} ${response.message}\n`; if (response.details) { response.details.forEach(d => errMsg = errMsg + `${d.resource} ${d.name} - ${d.error}\n`); } printError(errMsg, options); }}) .catch((err) => { printError(`Failed to promote to environment: ${err.response.body.message}`, options); }); } };
var fs = require('fs'), path = require('path'), _ = require('underscore'); // sync way of creating directories recursively var recMkdirSync = function (directory) { var pathArray = directory.replace(/\/$/, '').split('/'); var segment; for (var i = 1; i <= pathArray.length; i++) { segment = pathArray.slice(0, i).join('/'); !fs.existsSync(segment) ? fs.mkdirSync(segment) : null; } }; // ansync way of creating directories recursively var recMkdirAsync = function (directory, cb) { var pathArray = directory.replace(/\/$/, '').split('/'); var segment, aggPath = '/'; _.each(pathArray, function (pathElement) { segment = path.join(pathElement, '/'); aggPath += segment; fs.exists(aggPath, function (exists) { console.log(exists); if (!exists) { fs.mkdir(segment, function (err) { if (!err) { cb(err); } else { cb(); } }); } else { null; } }); }); }; module.exports.recMkdirSync = recMkdirSync; module.exports.recMkdirAsync = recMkdirAsync;
/* eslint-disable react-hooks/exhaustive-deps */ import React, {useEffect,useState} from 'react'; import "./style.css" const Stock = (props) => { const [div,setDiv] = useState(""); const Sym = props.symInfo[props.stk] const close =()=>{ document.querySelector("#stock-view-container").classList.toggle("on") document.querySelector("#blank").style.display = "none" } useEffect(() => { /* const Plotly = window.Plotly; var trace1 = { type: "scatter", mode: "lines", name: 'AAPL High', x: ['2013-10-04 22:23:00', '2013-10-05 22:23:00','2013-10-06 22:23:00','2013-10-07 22:23:00','2013-10-08 22:23:00','2013-10-09 22:23:00',], y: [1, 3,5,10,33,32], line: {color: '#17BECF'} } var graph = document.getElementById('stk-graf'); var data = [trace1]; var layout = { title: 'Basic Time Series', }; Plotly.newPlot("stk-graf", data); */ setDiv(()=>{ if(Sym != null) return( <div > <div name="stockInfo" onClick={close} className="close">X</div> <div className="stock-name-container"> <label className="stk-name"> {Sym.name.toUpperCase()} </label> <label className="stk-price"> {Sym.price} <label className="stk-change"> {Sym.change} ({Sym.percent}) </label> </label> </div> <div id="stk-graf" className="stk-graf"> </div> {/*} <div className="stk-btn-container"> <div className="stk-btn">Compare</div> <div className="stk-btn">Analise</div> <div className="stk-btn">Add to list</div> </div> {*/} <div className="stk-info-container"> <div className="stk-statics"> <p name="info"> <label>Open: </label> <label name="info">{Sym.open}</label></p> <p name="info"> <label>prev. Close: </label> <label name="info"> {Sym.prevClose}</label></p> <p name="info"> <label>Current Eps: </label> <label name="info">{Sym.eps}</label></p> <p name="info"> <label>shares Outstanding: </label> <label name="info">{Sym.sharesOutstanding}</label></p> <p name="info"> <label>Earnings Date: </label> <label name="info">{Sym.earningsTimestamp}</label> </p> </div> </div> </div> )}) }, [Sym]) return( <div> <div id="blank" > <div id="stock-view-container" className="stock-view-container"> {div} </div> </div> </div> ) } export default Stock;
/* eslint-disable no-unused-vars */ import Vue from 'vue' import Vuex from 'vuex'; import actions from './State/actions'; import getters from './State/getters'; import mutations from './State/mutations'; Vue.use(Vuex); export default new Vuex.Store({ state:{ showingLogs:true, AccountData:{ InstagramAccounts:[], Information:{}, Profiles:[], Library:{ MediaLibrary:[], CaptionLibrary:[], HashtagLibrary:[], MessagesLibrary:[] }, TimelineData:[], TimelineLogData:[], ProfileConfg:{}, }, status:'', token: localStorage.getItem('token') || '', user: localStorage.getItem('user') || '', role: localStorage.getItem('role') || '', }, mutations, getters, actions });
import homePage from './pages/home-page.js' import aboutPage from './pages/about-page.js' // import misterEmail from './apps/mail/pages/mail-app.js' import mailDetails from './apps/mail/pages/mail-details.js' import mailCompose from './apps/mail/pages/mail-compose.js' // import missKeep from './apps/keep/pages/keep-app.js' const routes = [{ path: '/', component: homePage }, { path: '/misterEmail', component: misterEmail }, { path: '/misterEmail/newMail', component: mailCompose }, { path: '/misterEmail/:id?', component: mailDetails }, { path: '/missKeep', component: missKeep }, { path: '/about', component: aboutPage }, ] export const router = new VueRouter({ routes })
import React, {Component} from 'react'; import { Platform, StyleSheet, Text, View, Modal, Alert, TextInput, ScrollView, TouchableWithoutFeedback, Image } from 'react-native'; import Header from "../CommonModules/Header"; import px2dp from "../tools/px2dp"; import {feach_request, Toast,getStorage} from "../tools/public"; import constant from '../tools/constant'; export default class EventProcess extends Component{ static navigationOptions = { header: null }; constructor(props){ super(props); this.state = { offer: '', msgData:{}, msg:{}, userInfo:{} } } componentDidMount(){ let msg = this.props.navigation.state.params.msg; getStorage('userInfo') .then(data=>{ this.setState({ userInfo:data }) }).catch(err=>{ console.log(err) }); feach_request(`/activity/query?act_id=${msg.act_id}`,'GET') .then((data)=>{ console.log(data) if(data.code==0){ this.setState({ msgData:data.data, msg:msg }); } }) .catch((err)=>{ console.log(err); Toast('网络错误~'); }) } //处理事件 dealEvent(methods){ var data = {req:{ack:this.state.offer},act_id:this.state.msg.act_id}; data = JSON.stringify(data); feach_request(`/activity/run`,'POST',data) .then((data)=>{ Toast('提交成功~'); }) .catch((err)=>{ console.log(err); Toast('网络错误~'); }) } render(){ let msg = this.props.navigation.state.params.msg; return( <View style={{flex:1,backgroundColor: '#fcfcfc'}}> <Header title={'事务处理'} navigate={this.props.navigation}/> <ScrollView style={styles.flex}> <View style={styles.padding_15}> { this.state.msgData.avatar?( <Image style={{width: 150,height:150,marginBottom:px2dp(10)}} source={{uri: `${ constant.url}${this.state.msgData.avatar}`}} /> ):(null) } <View style={styles.msg_wrap}> <Text style={styles.msg_title}>消息主题:</Text> <Text style={[styles.msg_content]}>{this.state.msgData.hint?this.state.msgData.hint:'无'}</Text> </View> <View style={styles.msg_wrap}> <Text style={styles.msg_title}>消息类型:</Text> <Text style={styles.msg_content}>{this.state.msgData.event_class==0?'陌生人消息':(this.state.msgData.event_class==1?'出行消息':(this.state.msgData.event_class==3?'布控消息':'部库消息'))}</Text> </View> <View style={styles.msg_wrap}> <Text style={styles.msg_title}>开始时间:</Text> <Text style={styles.msg_content}>{this.state.msgData.event_time}</Text> </View> <View style={styles.msg_wrap}> <Text style={styles.msg_title}>截止时间:</Text> <Text style={styles.msg_content}>{this.state.msgData.dead_time}</Text> </View> <View style={styles.mt_20}> <TextInput ref='TextInput' multiline = {true} style={styles.input_style} placeholder={'请输入处理意见...'} onChangeText={(text) => this.setState({offer:text})}/> <View style={styles.flex_space_between}> {/*{*/} {/*this.state.userInfo.user_id == msg.owner_id && msg.methods.indexOf('r')!==-1?(*/} {/*<TouchableWithoutFeedback onPress={()=>this.dealEvent('r')}>*/} {/*<View style={[styles.submit_btn,styles.gray_bg]}>*/} {/*<Text style={[styles.submit_btn_font,styles.blue_color]}>取消事件</Text>*/} {/*</View>*/} {/*</TouchableWithoutFeedback>*/} {/*):(null)*/} {/*}*/} {/*{*/} {/*this.state.userInfo.user_id == msg.guy_id && msg.methods.indexOf('c')!==-1?(*/} {/*<TouchableWithoutFeedback onPress={()=>this.dealEvent('c')}>*/} {/*<View style={[styles.submit_btn,styles.gray_bg]}>*/} {/*<Text style={[styles.submit_btn_font,styles.blue_color]}>不同意</Text>*/} {/*</View>*/} {/*</TouchableWithoutFeedback>*/} {/*):(null)*/} {/*}*/} <TouchableWithoutFeedback onPress={()=>this.dealEvent('')}> <View style={styles.submit_btn}> <Text style={styles.submit_btn_font}>同意</Text> </View> </TouchableWithoutFeedback> </View> </View> </View> </ScrollView> </View> ) } } const styles = StyleSheet.create({ flex:{ flex:1 }, flex_space_between:{ flexDirection: 'row', justifyContent: 'space-around', alignItems:'center' }, padding_15:{ padding:px2dp(15) }, msg_wrap:{ flexDirection: 'row', paddingVertical:px2dp(8) }, msg_title:{ fontSize:px2dp(15), color:'#333', flex:1, marginRight:px2dp(15) }, msg_content:{ fontSize:px2dp(14), lineHeight:px2dp(20), flex:4 }, input_style:{ height: px2dp(100), borderWidth:px2dp(1), borderColor:'#e0e0e0', borderRadius:px2dp(5), textAlignVertical: 'top', padding: px2dp(10) }, submit_btn:{ flex:1, height:px2dp(45), borderRadius: px2dp(40), backgroundColor: '#32bbff', marginTop:px2dp(20), justifyContent: 'center', alignItems:'center', marginHorizontal:px2dp(10) }, submit_btn_font:{ color: '#fff', fontSize:px2dp(15), letterSpacing:px2dp(2) }, mt_20:{ marginTop: px2dp(20) }, gray_bg:{ backgroundColor:'#fff', borderWidth: px2dp(1), borderColor: '#32bbff' }, blue_color:{ color:'#32bbff' }, flex_center:{ justifyContent: 'center', alignItems:'center' } });
/* * jQuery Modal Lite * * Copyright 2011, Pedro Gil Candeias (http://pedrogilcandeias.com) * Licensed under the MIT license. * * https://github.com/pgscandeias/jq-modal-lite */ /* ---------------- EVENTS ---------------- */ $(document).ready(function() { // Open a modal window $("a.openmodal").live("click", modal.open); // Close a modal window $("#modalmask").live("click", modal.close); $("a.closemodal").live("click", modal.close); }); /* ---------------- FUNCTIONS ---------------- */ var modal = { active: null, // Open modal open: function() { // Modal ID modal.id = $(this).attr("id").replace("open", ""); // Lay down the mask $("body").append("<div id='modalmask' style='height: "+$(document).height()+";'></div>"); // Pull up the modal div $("#"+modal.id).show(); // Add a little close button if ($("#jqmcb"+modal.id).length == 0) { $("#"+modal.id).prepend("<a href='javascript:void(0);' " +"id='jqmcb"+modal.id+"' class='jqmcb closemodal'>close</a>"); } return false; }, // Close modal close: function() { // Remove the mask $("#modalmask").remove(); // Hide the modal window $("#"+modal.id).hide(); // Reset ID modal.id = null; return false; } };
const withDisplayName = (component, displayName) => { const componentWithDisplayName = component; componentWithDisplayName.displayName = displayName; return component; }; export default withDisplayName;
const jwt = require('jsonwebtoken'); require('dotenv').config(); const auth = (req, res, next) => { const authHeader = req.headers.authorization; if(!authHeader) res.status(400).send('Sorry the token was not sent !'); const parts = authHeader.split(' '); const [scheme, token] = parts; jwt.verify(token, process.env.TOKEN_KEY, (err, decoded)=>{ if(err) res.status(400).send('Invalid Token !') console.log(decoded.id) req.userId = decoded.id; return next(); }) } module.exports= { auth }
'use strict'; module.exports = (sequelize, DataTypes) => { const user = sequelize.define('user', { userEmail: { type: DataTypes.STRING, unique: true, allowNull: false }, userPassword: { type: DataTypes.STRING, allowNull: false }, userName: { type: DataTypes.STRING, allowNull: false }, role: { type: DataTypes.ENUM, values: ["ADMIN", "MANAGER", "USER"], defaultValue: "USER", allowNull: false } }, { /** hooks */ }); user.associate = function(models) { // associations can be defined here /** User Have Many Web_Board */ user.hasMany(models.web_board, { foreignKey: 'writer', sourceKey: 'userEmail', }); /** User Have Many Web_reply */ user.hasMany(models.web_reply, { foreignKey: "replyer", sourceKey: "userEmail" }); }; return user; };
const express = require('express') const router = express.Router() const mongoose =require('mongoose') const User =mongoose.model('User') const bcrypt =require('bcrypt') const jwt= require('jsonwebtoken') const {JWT_SECRET} =require('../keys') const requireLogin =require('../middleware/requireLogin') router.get('/',(req,res)=>{ res.send("hello") }) router.get('/protected',requireLogin,(req,res)=>{ res.send("Hello User") }) router.post('/signup',(req,res)=>{ const {name,email,password} = req.body if(!name||!email||!password){ res.json({error:"please fill all details"}) } User.findOne({email:email}).then((savedUser)=>{ if(savedUser){ res.json({error:"User exists"}) } bcrypt.hash(password,12) .then(hashedPass=>{ const user=new User({ email:email, password:hashedPass, name:name }) user.save().then(user=>{ res.json({message:"saved use"}) }).catch(err=>{console.log(err);}) }) }).catch(err=>{ console.log("something went wrong"); }) }) router.post('/signin',(req,res)=>{ const {email,password}=req.body; if(!email||!password){ return res.json({message:"enter email oir passord"}) } else{ User.findOne({email:email}).then(savedUser=>{ if(!savedUser){ return res.json("not exists") } else{ bcrypt.compare(password,savedUser.password).then(user=>{ if(!user){ return res.json("wrong pass") } else{ const token =jwt.sign({_id:savedUser._id},JWT_SECRET) return res.json({token}) } }).catch(err=>{console.log(err);}) } }) } }) module.exports =router
// Title: Project Initial file // Description: A RESTFul API to monitor up or down time of user defined links // Author: Mohiuddin Mazumder // Date: 19/06/2021 //Dependencies const server = require('./lib/server'); const workers = require('./lib/worker'); //app object = module scaffolding const app = {}; app.init = () => { // start the server server.init(); // start the worker workers.init(); } app.init(); module.exports = app;
const HTTPServer = require('express') const compression = require('compression'); const ErrorHandler = require('errorhandler') const BodyParser = require('body-parser'); const palpite = require('./app/palpite/palpite.module') const app = HTTPServer() app.use(compression()); app.use(HTTPServer.static('./public')); app.use(BodyParser.urlencoded({extend: true})); app.use(ErrorHandler()) // -- LISTANDO PALPITES app.get('/api/v1/palpites/megasena', (req, res) => { palpite.modelo.PalpiteMegasena .findAll({ where: { palpitado_em: null, }, limit: 1 }) .then(palpitesMegasena => { for(i=0; i< palpitesMegasena.length; i++){ palpitesMegasena[i].destroy() } res.json(palpitesMegasena) }) .catch(err => { throw err }) }); // -- DELETANDO PALPITES app.delete('/api/v1/palpites/megasena/:id', (req, res) => { console.info(req.query) let _id = []; try { _id = req.query.id.split(',').map(parseInt) } catch (e) { return res.status(400).json({ message: `por favor verifique o paramentro id. ex: ?id1 ou ?id=1,2,3. Valor informado: ${req.params.id}`, err }); } const filtros = { id: _id, } palpite.modelo.PalpiteMegasena.destroy({ where: filtros }).then((numberInstances) => { return res.status(204).send() }).catch(err => { // TODO: Enviar para o ErroHandler return res.status(500).json(err) }) }); const SERVICE_PREFIX = process.env.SERVICE_PREFIX; const PORT = process.env.PORT || process.env[`${SERVICE_PREFIX}_PORT`] || 8080, HOST = process.env.HOST || process.env[`${SERVICE_PREFIX}_HOST`] || '0.0.0.0'; app.listen(PORT, HOST, function() { console.log(`Example app listening on port ${PORT}!`); })
import React from "react"; import {List, Avatar, Icon, Button} from "antd"; const IconText = ({ type, text }) => ( <span> <Icon type={type} style={{ marginRight: 8 }} /> {text} </span> ); class Tests extends React.Component { constructor(props) { super(props) this.state = { confirmed: false, } } examCreate = () => { this.setState({ confirmed: true, }) } testFunction = (e) => { console.log(e.title); } render(){ return ( <List itemLayout="vertical" size="large" pagination={{ onChange: page => { console.log(page); }, pageSize: 3, }} dataSource={this.props.data} renderItem={item => ( <List.Item key={item.title} actions={[ <IconText type="star-o" text="156" key="list-vertical-star-o" />, <IconText type="like-o" text="156" key="list-vertical-like-o" />, <IconText type="message" text="2" key="list-vertical-message" />, ]} extra={ <div> <Button onClick={this.examCreate}> Create An Exam </Button> <br></br><br></br> <Button onClick={() => this.testFunction(item)}> See Test </Button> </div> } > Code: {item.code} <List.Item.Meta avatar={<Avatar src={item.avatar} />} title={<a href={`/${item.id}`}>{item.title}</a>} description={item.description} /> {item.content} </List.Item> )} /> ) } } export default Tests
import logo from './logo.svg'; import './App.css'; import SubmitShift from './components/Submit-shift' function App() { return ( <div className="App"> <SubmitShift></SubmitShift> </div> ); } export default App;
import logo from "./logo.svg"; import "./App.css"; import Body from "./components/Body"; import Qpaper from "./components/qpaper"; import Submitted from "./components/submitted"; import Admin from "./components/admin"; import { useStateValue } from "./components/StateProvider"; import Loading from "./components/Loading"; import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom"; function App() { return ( <Router> {/* <Body/> */} <Switch> <Route exact path="/"> <Body /> </Route> <Route path="/loading"> <Loading /> </Route> <Route path="/qpaper"> <Qpaper /> </Route> <Route path="/submitted"> <Submitted /> </Route> <Route path="/admin"> <Admin /> </Route> </Switch> </Router> ); } export default App;
import React, { Component, Fragment } from 'react' import { connect } from 'dva'; import { Table, Pagination, Icon } from 'antd' import styles from './style.less' @connect(({ orderF, loading }) => ({ orderF, loading: loading.models.orderF })) export default class TableC extends Component { state = { // 开始默认请求待审核的 taskStatus:4, // 4进行中 任务进行中 columns4:[ {title: '任务编号',dataIndex: 'taskCode',key: 'taskCode'}, {title: '任务类型',dataIndex: 'taskType',key: 'taskType',render:text=>{ if (text === 0) {return '销售发货';} if (text === 1) {return '生产领料';} if (text === 2) {return '生产补料';} if (text === 3) {return '采购退货';} if (text === 4) {return '其他领料';} if (text === 6) {return '采购收货';} if (text === 7) {return '生产收货';} if (text === 8) {return '销售退货';} if (text === 9) {return '生产退料';} }}, {title: '执行人',dataIndex: 'pdaName',key: 'pdaName',}, {title: '任务节点',dataIndex: 'taskNode',key: 'taskNode',}, ], // 表格数据 data:{ loading:true, TotalPage: 1, current: 1, list: [], pageNum: 1, pageSize: 10, total: 10, totalSize: 10, }, //title title:"任务进行中", } constructor(props){ super(props) } componentDidMount(){ this.start() } start = (parmas) => { this.state.data.loading=true; const { dispatch } = this.props; let payload = { taskStatus:this.state.taskStatus, ...parmas }; dispatch({ type: 'orderF/getTasksC', payload, callback: res => { if(res.code === 1000){ res.rst.loading = false; res.rst.list.map((item,index)=>{item.key=index}) this.state.data = res.rst; } }, }); } render() { const { getTaskCountByStatus } = this.props; const { data, columns4 } = this.state; return (<div className={ styles.table1 }> <div className={ styles.tit }>{ this.state.title } ( {getTaskCountByStatus.startCount} )</div> <Table style={{ width:'98%',margin:'auto' }} loading={data.loading} columns={columns4} dataSource={data.list} bordered size="middle" pagination={false} /> {/* 分页器 */} <Pagination size="small" showSizeChanger showQuickJumper style={{ marginTop: '20px' }} current={data.current} pageSize={data.pageSize} total={data.total} onChange={(page, pageSize) => { let parmas ={}; parmas.pageNum = page; //请求头数据放置在payload中 this.start(parmas); //分页器获取数据 }} onShowSizeChange={(current, size) => { let parmas = {}; parmas.pageSize = size; // 孙子的分页 this.start(parmas); //分页器获取数据 }} /> </div>) }}
(function process( /*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) { var pollId = request.pathParams.poll_id; var pollHelper = new x_snc_polls.PollData_Creator(); // Validate if poll record exists var pollRecord = new GlideRecordSecure("x_snc_polls_poll"); pollRecord.get(pollId); if (!pollRecord.isValidRecord()) { throw new sn_ws_err.NotFoundError("Poll Not found"); } var voteData = request.body.data.votes; // Verify if already voted var pollResponseRecord = new GlideRecordSecure("x_snc_polls_poll_response"); pollResponseRecord.addQuery("poll", pollId); pollResponseRecord.addQuery("sys_created_by", gs.getUserName()); pollResponseRecord.query(); if (pollResponseRecord.next()) { throw new sn_ws_err.ConflictError("Already voted"); } // Record votes pollHelper.voteInPoll(voteData, pollId); // Set response details response.setStatus(201); response.setContentType("application/json"); var responseBody = '{"message":"Voting successful"}'; response.getStreamWriter().writeString(responseBody); })(request, response);
export {default as Screen} from './Screen'; export {default as HomeScreen} from './HomeScreen'; export {default as FleetCodeScreen} from './FleetCodeScreen'; export {default as PhoneNumberScreen} from './PhoneNumberScreen'; export {default as VerificationCodeScreen} from './VerificationCodeScreen'; export {default as MyTripsScreen} from './MyTripsScreen'; export {default as ReportsScreen} from './ReportsScreen'; export {default as MoreScreen} from './MoreScreen'; export {default as TripDetailsScreen} from './TripDetailsScreen';
"use strict"; var name = "Max", surname = "Bulygin", age = 24, isMarried = false; // One line comment /** It's a new line comment, try ot repeate it! **/ //case sensitive var a = 1; var A = 2; console.log(a); console.log(A); //code block {//block calc console.log("calc: ", 1+2+3); } {//block greeting console.log("Hello, dear friend!"); } //primitive data-types, value-types var a1, // undefined a2 = null, // null a3 = false, // boolean a4 = 3.5, // number a5 = "bu-ga-ga"; // string console.log(a1, a2, a3, a4, a5); //object based types, reference types var list = [ 'banana', 'potato', 'tomate' ], ref_list = list, duplicated_list = [ 'banana', 'potato', 'tomate' ]; console.log('1st step: ', list, ref_list, duplicated_list); console.log('equal list & ref_list: ', list === ref_list); // true console.log('equal list & duplicated_list: ', list === duplicated_list); // false // additional data-types var resultInfinity = 3/0; console.log(resultInfinity === Infinity); console.log(Number.isFinite(resultInfinity)); //better var resultNaN = Number("string"); console.log(resultNaN === NaN); console.log(Number.isNaN()); console.log("exponent value: ", Math.pow(2, 99)); // availble e-char in console // string quotes var doubleQuotes = "capital", singleQuotes = 'capital'; console.log(doubleQuotes === singleQuotes); //type conversions /** Ordering (if type has no availble operation handler): - boolean - number - string **/ //operators console.log(!true); //unary console.log(1 + 1); // binary console.log(1 < 2 ? 'truth' : 'error will never shown');
(function(jQuery){ jQuery.fn.timelineslider = function(options) { var defaults = { autoplay:false, pauseTime:5, transition:'slide', numberOfPhotos:'morethanone', //'always', 'no' desc:'onhover', quicknav:'onhover', xofy:'always', moretext:'More' }; var options = jQuery.extend(defaults, options); return this.each(function() { var _this = this; var me = jQuery(this); var log = jQuery("#log"); var instanceName = 'jQuery("#'+me.attr("ID")+'")[0]'; var onhover = false; var slidesouter = me.find(".slidesouter"); var slides = me.find(".slides"); var slide = me.find(".slide"); var markers = me.find(".markers"); var CURRENT_Z_INDEX = 10; slidesouter.hover(function(){ onhover = true; }, function(){ onhover = false; }); var descouter = me.find(".descouter"); var desc = me.find(".desc"); if (options.desc == "onhover") { descouter.hide(); me.hover(function(){ descouter.show(); },function(){ descouter.hide(); }); } else if (options.desc == "no") { descouter.hide(); } var xofy = me.find(".xofyouter"); if (options.xofy == "onhover") { xofy.hide(); me.hover(function(){ xofy.show(); },function(){ xofy.hide(); }); } else if (options.xofy == "no") { xofy.hide(); } //implement draggable slider var dragstate = 0; var dragstart = 0; var sliderx; var draggable = me.find(".draggable"); var dragarea = draggable.parent(); var timeline = dragarea.parent(); var jdoc = jQuery(document); function draggable_down() { if (dragstate == 1) { return; } dragstate = 1; log.append("<p>down</p>"); } function draggable_move(x) { if (dragstate == 1) { dragstate = 2; dragstart = x; sliderx = draggable.position().left; log.append("<p>detected first move</p>"); } if (dragstate == 2) { var newx = sliderx + x - dragstart; if (newx < 0) { newx = 0; } else if (newx > dragarea.width()) { newx = dragarea.width(); } draggable.css("left", newx+"px"); //log.append("<p>slider to "+newx+", "+sliderx+"/"+x+"/"+dragstart+"</p>"); } } function draggable_up() { if (dragstate == 2) { dragstate = 0; var newx = draggable.position().left; var percentage = newx / dragarea.width(); moveToTime(percentage); log.append("<p>released at "+percentage+"%,("+newx+"/"+sliderx+")</p>"); } } draggable.bind("mousedown", function(e){ if (dragstate == 2) { draggable_up(); return; } if (e.preventDefault()) { e.preventDefault(); } draggable_down(); }); jdoc.bind("mousemove", function(e){ draggable_move(e.pageX); }); jdoc.bind("mouseup", function(e){ draggable_up(); }); //handle touch events if (document.addEventListener) { draggable.get(0).addEventListener('touchstart', function(e) { //draggable.bind("touchstart", function(e){ e.preventDefault(); draggable_down(); }); document.addEventListener('touchmove', function(e) { //jdoc.bind("touchmove", function(e){ e.preventDefault(); draggable_move(e.touches[0].pageX); }); document.addEventListener('touchend', function(e) { //jdoc.bind("touchend", function(e){ e.preventDefault(); draggable_up(); }); } //handle markers var times = new Array(); var timelabels = new Array(); var counts = new Array(); var currentPhoto = 0; var timeIsNumber = true; for (var i=0;i<slide.length ;i++ ) { var slidei = jQuery(slide[i]); var time = slidei.data("time"); var timelabel = slidei.data("timelabel"); if (!time) { time = timelabel; timeIsNumber = false; } var timeindex = jQuery.inArray(timelabel,timelabels); if (timeindex == -1) { times.push(time); timelabels.push(timelabel); counts.push(1); } else { //already in array! counts[timeindex] += 1; } } if (timelabels.length ==0) { return; } var minX; var maxX; if (times.length ==1) { minX = times[0]; maxX = times[0]; } else { minX = times[0]; maxX = times[times.length-1]; } var duration = maxX - minX; for (var i=0;i<times.length ;i++ ) { var photoCount = counts[i]; var position; if (timeIsNumber) { position = (times[i]-minX) / duration; } else { if (times.length > 1) { position = i / (times.length - 1); } else { position = 0.5; } } var timeToDisplay = timelabels[i]; if (options.numberOfPhotos == 'always' || (options.numberOfPhotos == 'morethanone' && photoCount > 1)) { timeToDisplay += " ("+photoCount+")"; } var marker = jQuery("<a href='javascript:void(0);' class='marker'><span>"+timeToDisplay+"</span></a>"); marker.data("time", times[i]); marker.data("timelabel", timelabels[i]); marker.data("percentage", position); markers.append(marker); marker.css("width", marker.width()); marker.css("left", (position * 100) + "%"); //check to see if there is enough place to show this marker marker.css("margin-left", marker.width() / -2); } var marker = markers.children(); setActiveMarker(0); //hide text of markers that overlaps previous item var marker0 = jQuery(marker[0]); var lastitemx = marker0.position().left + marker0.width() / 2; for (var i=1;i<=marker.length - 1 ;i++ ) { var markeri = jQuery(marker[i]); var itemx = markeri.position().left - markeri.width() / 2; //alert(i+"/"+marker.length+"/"+itemx +"/"+ lastitemx); if (itemx < lastitemx) { markeri.addClass("expended"); //markeri.html(""); } else { lastitemx = markeri.position().left + markeri.width() / 2; } } var marker = me.find(".marker"); marker.click(function(){ //marker.removeClass("active"); //jQuery(this).addClass("active"); var totime = jQuery(this).data("timelabel"); for (var i=0;i<slide.length ;i++ ) { var time = jQuery(slide[i]).data("timelabel"); if (time == totime) { moveToSlide(i); return; } } }); function moveToTime(percentage) { var index = 0; var offset = 1; for (var i=0;i<marker.length ;i++ ) { var markerpercentage = jQuery(marker[i]).data("percentage") * 1; if (Math.abs(markerpercentage - percentage) < offset) { offset = Math.abs(markerpercentage - percentage); index = i; } } jQuery(marker[index]).click(); } function moveToSlide(index) { if ((index == currentPhoto+1) || (index==0 && currentPhoto==slide.length-1)) { slideTimePassed = 0; } else { //stopAutoPlay(); //log.append("stopAutoPlay"); } if (index < 0) { index = slide.length - 1; } else if (index > slide.length - 1) { index = 0; } if (options.transition == 'slide') { var slidesx = slidesouter.width() * index * -1; slides.animate({"margin-left":slidesx}, "slow"); } else//fade { var currentslide, nextslide; for (var i=0;i<slide.length ;i++ ) { if (i == currentPhoto) { currentslide = jQuery(slide[i]); } else if (i == index) { nextslide = jQuery(slide[i]); } else { jQuery(slide[i]).css("z-index", CURRENT_Z_INDEX-2); } } currentslide.css("z-index", CURRENT_Z_INDEX); nextslide.css("z-index", CURRENT_Z_INDEX-1); currentslide.css("position", "absolute"); nextslide.css("position", "absolute"); //nextslide.fadeTo(0.1, 0); currentslide.fadeTo("slow", 0); nextslide.fadeTo("slow", 1, function(){currentslide.css("z-index", CURRENT_Z_INDEX);nextslide.css("z-index", CURRENT_Z_INDEX-1);}); } currentPhoto = index; setActiveMarker(index); postMove(); } function postMove() { var deschtml = jQuery(slide[currentPhoto]).data("desc"); var link = jQuery(slide[currentPhoto]).data("link"); if (link) { deschtml += "<a href='"+link+"' class='readmore'>"+options.moretext+"</a>"; } desc.html(deschtml); var x = currentPhoto+1; /*if (slide.length >= 10 && x < 10) { x = "0" + x; }*/ me.find(".xofy .x").html(x); me.find(".xofy .y").html(slide.length); } postMove(); function setActiveMarker(index) { marker.removeClass("active"); var time = jQuery(slide[index]).data("timelabel"); for (var i=0;i<marker.length ;i++ ) { var totime = jQuery(marker[i]).data("timelabel"); if (time == totime) { jQuery(marker[i]).addClass("active"); var newx = jQuery(marker[i]).css("left"); draggable.stop().animate({"left": newx}, "fast"); //draggable.css("left", newx); return; } } } //handle slides slide.css("width", slidesouter.width()); slides.css("width", slide.length * slidesouter.width()); var bestHeight = slidesouter.height(); for (var i=0;i<slide.length ;i++ ) { //vertical center var slidei = jQuery(slide[i]); var slideheight; if (slidei.find("img").length > 0) { slideheight = slidei.height(); } else { slidei.css("height", "100%"); return; } var offset = (bestHeight-slideheight) / 2; slidei.css("margin-top", offset); } slide.find("img").load(function(){ var slidei = jQuery(this).parent(); var offset = (bestHeight-slidei.height()) / 2; slidei.css("margin-top", offset); }); //handle auto play var slideTimePassed=0; var autoPlayHandler; var prev = me.find(".previtem"); var next = me.find(".nextitem"); var prevnext = prev.parent(); if (options.quicknav == "onhover") { prevnext.hide(); slidesouter.hover(function(){ prevnext.show(); }, function(){ prevnext.hide(); }); } else if (options.quicknav == "no") { prevnext.hide(); } prev.bind("click touchend", function(){ moveToSlide(currentPhoto - 1); }); next.bind("click touchend", function(){ moveToSlide(currentPhoto + 1); }); if (options.autoplay) { autoPlay(); } function autoPlay() { if (autoPlayHandler > 0) { stopAutoPlay(); } else { autoPlayHandler = window.setInterval(instanceName + ".onInterval()", 1000); } } function stopAutoPlay() { if (autoPlayHandler < 0) return; window.clearInterval(autoPlayHandler); autoPlayHandler = -1; slideTimePassed = 0; } this.onInterval = function() { if (onhover) { return; } slideTimePassed += 1; if (slideTimePassed >= options.pauseTime) { slideTimePassed = 0; if (currentPhoto < slide.length - 1) { moveToSlide(currentPhoto + 1); } else { //reached last item moveToSlide(0); } } } //handle touch events of slides if (options.transition == 'slide') { var slidedragstate = 0; var slidedragstart = 0; var slidesx; if (document.addEventListener) { slidesouter.get(0).addEventListener('touchstart', function(e) { e.preventDefault(); if (slidedragstate == 1) { return; } slidedragstate = 1; }); slidesouter.get(0).addEventListener('touchmove', function(e) { e.preventDefault(); if (slidedragstate == 1) { slidedragstate = 2; slidedragstart = e.touches[0].pageX; slidesx = parseInt(slides.css("margin-left")); } if (slidedragstate == 2) { var newx = slidesx + e.touches[0].pageX - slidedragstart; slides.css("margin-left", newx+"px"); } }); slidesouter.get(0).addEventListener('touchend', function(e) { e.preventDefault(); if (slidedragstate == 2) { slidedragstate = 0; var min = (slide.length-1) * slidesouter.width() * -1; var newx = parseInt(slides.css("margin-left")); if (newx > 0) { slides.stop().animate({"margin-left": 0}, "fast"); return; } else if (newx < min) { slides.stop().animate({"margin-left": min}, "fast"); return; } if (Math.abs(newx-slidesx) / (slidesouter.width() > .25)) { if (newx > slidesx) { moveToSlide(currentPhoto - 1); } else { moveToSlide(currentPhoto + 1); } } else { slides.stop().animate({"margin-left": slidesx}, "fast"); } } }); } } }); }; })(jQuery);
class ClaseBase{ constructor(x,y,width,height,angle){ var option_box = { 'restitution': 0.8, 'friction': 0.4, 'density':1.0 } this.body = Bodies.rectangle(x,y,width,height,option_box); this.width = width; this.height = height; this.image = loadImage("sprites/base.png"); World.add(world,this.body); } display(){ var p = this.body.position; var a = this.body.angle; push(); translate(p.x,p.y); rotate(a); imageMode(CENTER); image(this.image,0,0,this.width,this.height); pop(); } }
Ext.define('Admin.view.modules.grupos.gridGruposController', { extend: 'Ext.app.ViewController', alias: 'controller.modules-grupos-gridgrupos' });
'use strict'; const axios = require('axios'); async function fetchDockerTags(registryUrl) { return axios.get(registryUrl) .then(function (response) { return response.data; }) .catch(function (error) { console.error(error); return []; }); }; module.exports = fetchDockerTags;
console.log("it works"); const nav = document.querySelector(".menu-resp"); console.log(nav); nav.addEventListener("click", () => { console.log("ici"); document.body.classList.toggle("open"); }); const shipping = document.querySelector(".shipping-bar svg"); shipping.addEventListener("click", () => { document.body.classList.toggle("open-shipping"); });
import React from "react"; import { Link } from "react-router-dom"; import "../App.css"; const Landing = () => ( <section className="landing"> <div className="Main-photo"> <Link to="/adopt"> <button className="Button-orange">ADOPT</button> </Link> </div> <div className="Main-text"> <h1>Animal Shelter and Adoption Information</h1> <p> We are very fortunate to live in a community that supports its Animal Control and Shelter and that takes pet responsibility seriously. Due to the shelter’s commitment to promoting spaying and neutering of pets to prevent unwanted litters, we have been successful at reducing the amount of animals that end up in our shelter, thereby, reducing the number of animals that must be euthanized due to a lack of homes. We are extremely fortunate to be a shelter that only euthanizes animals because of serious health or behavior issues rather than lack of space. The Animal Shelter provides the following services: </p> <ul> <li>• Pet Adoptions</li> <li>• Pet impound redemptions</li> <li>• Lost and found animal tracking</li> <li>• License sales</li> <li>• Live trap rentals</li> <li>• Pet cremation</li> <li>• Humane education</li> </ul> <hr /> <div className="Annual-report"> <h1>Annual Report</h1> <p> The{" "} <a href="http://co-summitcounty2.civicplus.com/DocumentCenter/View/14611"> Summit County Animal Control and Shelter Annual Report (pdf) </a>{" "} provides information and data on intakes and outcomes for all our shelter animals. Our shelter live release rate for dogs and cats is 98%. <br />* * Shelter Live Release Rate = (Adoption+Return to Owner+Transfer+ Owner Requested Euthanasia)/(Adoption+Return to Owner+Transfer+Owner Requested Euthanasia+Shelter Euthanasia) </p> </div> </div> </section> ); export default Landing;
/// <autosync enabled="true" /> /// <reference path="js/knockout.js" /> /// <reference path="js/ordersaction.js" /> /// <reference path="js/profileaction.js" /> /// <reference path="js/searchaction.js" /> /// <reference path="js/site.js" /> /// <reference path="js/viewcartaction.js" /> /// <reference path="lib/bootstrap/dist/js/bootstrap.js" /> /// <reference path="lib/jquery/dist/jquery.js" /> /// <reference path="lib/jquery-validation/dist/jquery.validate.js" /> /// <reference path="lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js" />
var time = new Date().getTime() var data2 = '{"client_id":"u5vHzE9yBqw", "client_secret":"s8aOW4vlM4Q" ,"grant_type":"http://www.moxtra.com/auth_uniqueid" ,"uniqueid" :"kev5", "timestamp":"' + time + '"}'; console.log(data2); var data1 = JSON.parse(data2); console.log(time); $.ajax({ type: 'POST', url: "https://apisandbox.moxtra.com/oauth/token", data: data1, contentType: "application/x-www-form-urlencoded", success: function(json) { console.log(json); var options = { mode: "sandbox", //for production environment change to "production" client_id: "u5vHzE9yBqw", access_token: json.access_token, //valid access token from user authentication invalid_token: function(event) { alert("Access Token expired for session id: " + event.session_id); } }; Moxtra.init(options); console.log() var options = { iframe: true, extension: { "show_dialogs": { "meet_invite": true } }, tagid4iframe: "container", iframewidth: (window.innerWidth / 2) + "px", iframeheight: (window.innerHeight - 81) + "px", video: true, start_meet: function(event) { alert("session key: " + event.session_key + " session id: " + event.session_id + " binder id: " + event.binder_id); }, error: function(event) { alert("error code: " + event.error_code + " message: " + event.error_message); }, resume_meet: function(event) { alert("session key: " + event.session_key + " session id: " + event.session_id + " binder id: " + event.binder_id); }, end_meet: function(event) { alert("Meet end event"); } }; Moxtra.meet(options); $('iframe', parent.document).css("margin-top", "81px"); }, error: function(e) { console.log(e) // alert("Failure"+ JSON.stringify(e)); } }); var myFirebaseRef = new Firebase("https://hackchair.firebaseio.com/"); var leaning; var blinks = 0; // var blinkCo myFirebaseRef.child("lean").on("value", function(snapshot) { if (snapshot.val() != null) { $("#image").rotate(snapshot.val() * -1); $("#degree .big-text").html((Math.round(snapshot.val() * 100) / 100)); if (snapshot.val() > 15) { swal({ title: "Too much tilt", text: "You're leaning your chair back a lot! Try out a different chair model?", type: "warning", showCancelButton: true, confirmButtonColor: "#8CD4F5", confirmButtonText: "Ok sure", closeOnConfirm: false }, function() { var urlthing = "249-05-0250"; var rand = Math.random(); if (rand < 0.2) { urlthing = "249-08-1152"; } else if (rand < 0.4) { urlthing = "249-14-0381"; } else if (rand < 0.6) { } $.ajax({ type: 'GET', url: 'http://api.target.com/items/v3/' + urlthing + '?key=1Kfdqvy6wHmvJ4LDyAVOl7saCBoKHcSb&id_type=dpci&fields=descriptions,brand', crossDomain: true, async: false, jsonpCallback: 'jsonpCallback', dataType: 'jsonp', contentType: 'application/json', success: function(data) { console.log(data); var item = data.product_composite_response.items[0]; swal({ title: "<a href='" + item.data_page_link + "'>" + item.general_description + "</a>", text: "by " + item.online_brand_name, html: true }); } }); }); } } }); myFirebaseRef.child("blinks").on("value", function(snapshot) { console.log(snapshot.val()); $("#blinks .big-text").html(snapshot.val()); blinks = blinks + snapshot.val(); if (snapshot.val() > 3) { swal({ title: "Sleeping!", text: "stop sleeping dude its class", type: "error", confirmButtonText: "ok fine" }); } }); myFirebaseRef.child("sitting").on("value", function(snapshot) { console.log(snapshot.val()); if (snapshot.val()) { $("#sitting .big-text").html("Good"); } else { $("#sitting .big-text").html("Bad"); } }); // console.print("asd")
import React, { Component } from "react"; import { StyleSheet, Button, FlatList, SafeAreaView, Platform, Text, View, Image, TextInput, TouchableOpacity } from "react-native"; import { ListItem, Divider } from "react-native-elements"; import { primary as firebase, addFood, getFoods, readKey, FoodChange, deleteItemById, getKey } from "../FirebaseApi"; import SwipeView from "react-native-swipeview"; import uuid from "uuid"; export default class FoodList extends Component { colors = []; state = { foodList: [], currentFoodItem: null, email: "", displayName: "", key: "" }; foodItem = (id, name) => { return { id: id, name: name }; }; onFoodAdded = food => { console.log("Food Added"); }; onFoodsReceived = foodList => { //console.log("why called multiple times " + foodList); this.setState(prevState => ({ foodList: (prevState.foodList = foodList) })); // this.setState(prevState => ({ // foodList: (prevState.foodList = foodList) // })); }; onFoodAdded = food => { this.setState(prevState => ({ currentFoodItem: null })); }; signOutUser = () => { console.log("logging out now"); firebase.auth().signOut(); }; getKeyV = keyvalue => { console.log("vvvv" + keyvalue); this.setState({ key: keyvalue }); return keyvalue; }; key = async () => { return await readKey; }; constructor() { super(); console.ignoredYellowBox = ["Setting a timer"]; } componentDidMount() { getFoods(this.onFoodsReceived); getKey(this.getKeyV); const { email, displayName } = firebase.auth().currentUser; this.setState({ email, displayName }); } render() { function img2() { if (Platform.OS === "android") return; return ( <Image source={require("../assets/eha.jpg")} style={{ width: 150, height: 150, alignContent: "center" }} /> ); } const swipeSettings = { autoClose: true, onClose: (secId, rowId, direction) => {}, onOpen: (secId, rowId, direction) => {} }; return ( <SafeAreaView style={{ backgroundColor: Platform.OS == "web" ? "yellow" : "white", width: Platform.OS == "web" ? 650 : 400, alignSelf: "center" }} > {img2()} <View style={styles.row}> <Text>Hi {this.state.email}!</Text> <TouchableOpacity onPress={this.signOutUser} style={{ marginTop: 32 }} > <Text>Logout</Text> </TouchableOpacity> </View> <View style={styles.row}> <TextInput style={styles.formInput} placeholder="Add Food" value={this.state.currentFoodItem} onChangeText={text => this.setState(prevState => ({ currentFoodItem: (prevState.currentFoodItem = text) })) } /> <Button title="Submit" style={styles.button} onPress={() => { addFood( this.state.currentFoodItem, this.state.key, this.onFoodAdded ); }} /> </View> <FlatList data={this.state.foodList} ItemSeparatorComponent={() => ( <Divider style={{ backgroundColor: "black" }} /> )} keyExtractor={(item, index) => index.toString()} renderItem={({ item }) => ( <View> <SwipeView renderVisibleContent={() => ( <Text style={styles.ingredientItemText}>{item.name}</Text> )} onSwipedLeft={() => deleteItemById( this.onFoodsReceived, this.state.foodList, item, this.state.key ) } /> </View> )} /> </SafeAreaView> ); } } const styles = StyleSheet.create({ container2: { flex: 1, justifyContent: "center", alignItems: "center" }, row: { justifyContent: "space-between", alignSelf: "stretch", flexDirection: "row", alignItems: "center", marginBottom: 32, padding: 10 }, container: { width: 200, alignSelf: "center", alignItems: "center", marginTop: 32 }, formInput: { borderColor: "#B5B4BC", borderWidth: 1, padding: 8, height: 50, color: "black", width: "75%", marginBottom: 16, marginTop: 16 }, validationText: { color: "red" }, longFormInput: { width: "100%", height: 50, color: "black", borderColor: "#B5B4BC", borderWidth: 1, padding: 8, margin: 16 }, ingredientItemText: { fontSize: 16, alignSelf: "center", marginBottom: 16, marginTop: 16 } });
import { config } from "dotenv"; const { parsed } = config(); export const { DB, PORT, BASE_URL, URL = `${BASE_URL + PORT}`, JWT_SECRET, } = parsed;
const nome = document.getElementById('NomeCompleto'); const comentario = document.getElementById('ComentarioText'); document.getElementById('enviarComentario').addEventListener('click',(event)=>{ event.preventDefault(); const tabela = document.getElementById('ComentariosFeitos'); // Validações if(nome.value===""||comentario.value===""){ alert("Preencha todos os campos para realizar um comentário"); return; } // Monta a tabela com os dados var html = ''; html += '<tr>'; html += ` <td>${nome.value}</td>`; html += ` <td>${comentario.value}</td>`; html += ` <td><button class="btn btn-danger" type="button" onClick="ApagarComentario(this)">Apagar</button></td>`; html += '</tr>'; tabela.innerHTML+=html; }); function ApagarComentario(target){ target.parentElement.parentElement.remove(); } function focoCampo(event){ event.target.style.borderColor = 'green'; } function perdeFoco(event){ event.target.style.borderColor = 'black'; } nome.addEventListener('focus',focoCampo.bind(this)); comentario.addEventListener('focus',focoCampo.bind(this)); nome.addEventListener('blur',perdeFoco.bind(this)); comentario.addEventListener('blur',perdeFoco.bind(this));
import styled from "styled-components"; import { Link } from "react-router-dom"; export const Wrapper = styled.header` position: fixed; z-index: 500; top: 0; left: 0; width: 100%; height: 50px; background: ${props => props.theme.darkBlue}; box-sizing: border-box; padding: 0 ${props => props.theme.sidePadding}; display: flex; justify-content: space-between; `; export const LeftSection = styled.div` display: flex; align-items: center; & > * { display: inline-block; padding-right: 1rem; } svg { height: 30px; } `; export const SearchInput = styled.div` position: relative; input { border: none; height: 30px; padding: 0 0 0 1.7rem; background: #E1E9EE; border-radius: 2px; width: 17rem; } i { position: absolute; top: 50%; left: .3rem; transform: translateY(-50%); } `; export const NavSection = styled.nav` display: flex; align-content: center; align-items: baseline; `; export const NavItem = styled(Link)` position: relative; display: flex; flex-direction: column; align-items: center; color: ${props => props.theme.lightGrey}; text-decoration: none; height: 100%; padding: 0 .6rem; &:hover { color: white !important; } ${props => !!props.selected && ` color: white; &::after { content: ""; position: absolute; bottom: -1px; width: 100%; height: 4px; background: ${props.theme.lightGrey}; } `} i { order: 1; flex-grow: 2; font-size: 1.2rem; &::before { top: .4rem; position: relative; } } p { font-family: sans-serif, Arial, Helvetica; font-size: .7rem; order: 2; margin: 0 0 10px 0; } `; export const Header = styled.h2` font-family: "neotericbold" !important; color: rgb(21, 67, 104); font-size: 2em; `;
$(document).ready(function() { firebase.auth().onAuthStateChanged(function(user) { if (user) { profilePage(user.uid); getProfileName(user, function (name) { var profileName = document.querySelector("#profile-name"); profileName.innerHTML = name; }); var logo = document.querySelector(".Logo"); logo.onclick = function () { window.location.href = "http://localhost:3000/" } } else { window.location.href = "http://localhost:3000/"; } }); var buttonDiv = document.querySelector("#logout"); buttonDiv.onclick = logout; }); profilePage = function (userId) { loadProgression(userId, function (progressions) { // size right div divSizer(progressions); // make progression names var currentName; var currentProgression; var div = document.querySelector("#progressions") for (var i = 0; i < progressions.length; i++) { currentName = progressions[i].name; var newDiv = document.createElement("BUTTON"); newDiv.classList.add("mui-btn"); newDiv.classList.add("mui-btn--raised") newDiv.classList.add("progressionBut") newDiv.classList.add("progression-"+i) var newDivNode = document.createTextNode(currentName); newDiv.appendChild(newDivNode) div.appendChild(newDiv); // event listener newDiv.addEventListener("click", function (event) { // makes so only one can be selected at a time var div = document.querySelector("."+event.target.classList[3]); for (var j = 0; j < progressions.length; j++) { var testing = document.querySelector(".progression-"+j); if ((testing.classList[4]) && (testing.classList[1] != event.target.className)) { testing.classList.remove("mui-btn--primary"); testing.classList.remove("selected"); } } // make selection work console.log(event.target.classList[4]); if (div.classList[4]) { console.log("remove") div.classList.remove("mui-btn--primary"); div.classList.remove("selected"); } else { console.log("add") div.classList.add("mui-btn--primary"); div.classList.add("selected"); var name = document.querySelector("#name"); name.innerHTML = event.target.innerHTML.toUpperCase(); } }); // end of event listener } }); // playbutton stuff var playButton = document.querySelector("#play"); playButton.addEventListener("click", function (event) { var user = firebase.auth().currentUser.uid; loadProgression(user, function (progressions) { var progressionClass; var progressionIndex = ""; for (var j = 0; j < progressions.length; j++) { var testing = document.querySelector(".progression-"+j); if (testing.classList[5]) { progressionClass = testing.classList[3]; } } if (!(progressionClass)) { alert("Select a progression first.") } for (var i = 12; i < progressionClass.length; i++) { progressionIndex += progressionClass[i]; } SoundManager(progressions[progressionIndex].progression[0]); }); }); // play button number 2 var playButton2 = document.querySelector(".playbutton") playButton2.addEventListener("click", function (event) { var prog = document.querySelector("#generated-progression").innerHTML; if (prog === "") { alert("Please generate a progression first!"); return; } var array = prog.split(" "); array.pop(); SoundManager(array); }); // delete button stuff var deleteButton = document.querySelector("#delete"); deleteButton.addEventListener("click", function (event) { var user = firebase.auth().currentUser.uid; loadProgression(user, function (progressions) { var progressionClass; var progressionIndex = ""; for (var j = 0; j < progressions.length; j++) { var testing = document.querySelector(".progression-"+j); if (testing.classList[5]) { progressionClass = testing.classList[3]; } } if (!(progressionClass)) { alert("Select a progression first.") } for (var i = 12; i < progressionClass.length; i++) { progressionIndex += progressionClass[i]; } progressions[progressionIndex].deleteProgression(); location.reload(); }); }); // save button stuff var saveButton = document.querySelector("#save"); saveButton.addEventListener("click", function (event) { var prog = document.querySelector("#generated-progression").innerHTML; if (prog === "") { alert("Please generate a progression first!"); return; } var array = prog.split(" "); array.pop(); var user = firebase.auth().currentUser.uid; var name = document.querySelector("#name-insert").value; if (name === "") { name = undefined; } createProgression(prog, user, name); location.reload(); }); var classical = document.querySelector("#classical"); classical.addEventListener("click", function (event) { var genre = document.querySelector(".genre-span"); genre.innerHTML = 'Classical'; }); var rock = document.querySelector("#rock"); rock.addEventListener("click", function (event) { var genre = document.querySelector(".genre-span"); genre.innerHTML = 'Rock'; }); var blues = document.querySelector("#blues"); blues.addEventListener("click", function (event) { var genre = document.querySelector(".genre-span"); genre.innerHTML = 'Blues'; }); var major = document.querySelector("#major"); major.addEventListener("click", function (event) { var mode = document.querySelector(".mode-span"); mode.innerHTML = 'Major'; }); var minor = document.querySelector("#minor"); minor.addEventListener("click", function (event) { var mode = document.querySelector(".mode-span"); mode.innerHTML = 'Minor'; }); var a = document.querySelector("#a"); a.addEventListener("click", function (event) { var key = document.querySelector(".key-span"); key.innerHTML = 'A'; }); var b = document.querySelector("#b"); b.addEventListener("click", function (event) { var key = document.querySelector(".key-span"); key.innerHTML = 'B'; }); var c = document.querySelector("#c"); c.addEventListener("click", function (event) { var key = document.querySelector(".key-span"); key.innerHTML = 'C'; }); var d = document.querySelector("#d"); d.addEventListener("click", function (event) { var key = document.querySelector(".key-span"); key.innerHTML = 'D'; }); var e = document.querySelector("#e"); e.addEventListener("click", function (event) { var key = document.querySelector(".key-span"); key.innerHTML = 'E'; }); var f = document.querySelector("#f"); f.addEventListener("click", function (event) { var key = document.querySelector(".key-span"); key.innerHTML = 'F'; }); var g = document.querySelector("#g"); g.addEventListener("click", function (event) { var key = document.querySelector(".key-span"); key.innerHTML = 'G'; }); var generator = document.querySelector("#generate") generator.addEventListener("click", function (event) { var genre = document.querySelector(".genre-span"); var mode = document.querySelector(".mode-span"); var key = document.querySelector(".key-span"); var flag = false; if (genre.innerHTML === "Genre") { alert("Please select a Genre!"); flag = true; } if ((mode.innerHTML === "Mode") && !(flag)) { alert("Please select a Mode!"); flag = true; } if ((key.innerHTML === "Key") && !(flag)) { alert("Please select a Key!"); flag = true; } if (flag) { return; } // generation var target = document.querySelector("#generated-progression"); var array = initalizeGenerators(genre.innerHTML, mode.innerHTML, key.innerHTML); var string = ""; for (var i = 0; i < array.length; i++) { string += array[i] + " "; } target.innerHTML = string; }); }; logout = function() { firebase.auth().signOut() } getProfileName = function (user, callback) { fetch("http://localhost:3000/users").then(function (response) { return response.json(); }).then(function (data) { data.forEach(function (entry) { if (entry.id === user.uid) { callback(entry.email); } }); }); }; divSizer = function(progressionList) { var baseHeight = 502; var listDiff = progressionList.length - 7; var pastDiv = document.querySelector("#past"); var progressionsDiv = document.querySelector("#progressions-div"); if (listDiff > 0) { pastDiv.style.height += baseHeight+listDiff*52; progressionsDiv.style.height += baseHeight + listDiff*52; } else { pastDiv.style.height = baseHeight; progressionsDiv.style.height = baseHeight; } } // for testing 5967d6b8b91cd3039b3c57e3
(function($) { "use strict"; // PreLoader $(window).on('load',function() { $("#loading").delay(4000).fadeOut(2000); // $("#loading").fadeOut(10000); }) /* TOP Menu Stick */ $(window).on('scroll',function() { var scroll = $(window).scrollTop(); if (scroll < 600) { $(".menubar-area").removeClass("sticky-header"); }else{ $(".menubar-area").addClass("sticky-header"); } }); // Slick SLider $('.Brands').slick({ dots: false, arrows:false, lazyLoad:'ondemand', infinite: true, speed: 300, slidesToShow: 8, slidesToScroll: 1, autoplay:true, autoplaySpeed:1000, responsive: [ { breakpoint: 1024, settings: { slidesToShow: 4, slidesToScroll: 3, } }, { breakpoint: 800, settings: { slidesToShow:3, slidesToScroll: 1 } } ] }); // delegate: 'a', // child items selector, by clicking on it popup will open // type: 'image' //Portfolio data filter var $sam = $('.port-active').isotope({ itemSelector: '.grid-item', percentPosition: true, masonry: { columnWidth:1, } }); $('.filter-button-group').on( 'click', 'button', function() { var filterValue = $(this).attr('data-filter'); $sam.isotope({ filter: filterValue }); }); $('.filter-button-group .btn').on('click', function(event) { $(this).siblings('.active').removeClass('active'); $(this).addClass('active'); event.preventDefault(); }); $('.port-active').magnificPopup({ delegate: 'a', // child items selector, by clicking on it popup will open type: 'image', gallery: { enabled: true }, type: 'image' // this is default type }); // ScrollUp Plugin $(function () { $.scrollUp({ scrollName: 'scrollUp', // Element ID scrollDistance: 300, // Distance from top/bottom before showing element (px) scrollFrom: 'top', // 'top' or 'bottom' scrollSpeed: 600, // Speed back to top (ms) easingType: 'linear', // Scroll to top easing (see http://easings.net/) animation: 'fade', // Fade, slide, none animationSpeed: 200, // Animation speed (ms) scrollTrigger: false, // Set a custom triggering element. Can be an HTML string or jQuery object scrollTarget: false, // Set a custom target element for scrolling to. Can be element or number scrollText: '<i class="fas fa-angle-up"></i>', // Text for element, can contain HTML scrollTitle: false, // Set a custom <a> title if required. scrollImg: false, // Set true to use image activeOverlay: false, // Set CSS color to display scrollUp active point, e.g '#00FFFF' zIndex: 2147483647 // Z-Index for the overlay }); // wow js new WOW().init(); }); })(jQuery);
import React from "react"; import {GoogleApiWrapper} from "google-maps-react"; import Map from "./Map"; class MapContainer extends React.Component{ render(){ // if(!this.props.loaded){ // return <div>Loading</div> // } return( <div> <Map google={this.props.google} /> </div> ) } } // export the container within the GoogleApiWrapper export default GoogleApiWrapper({ apiKey: "AIzaSyAJQ__z06-Y3H9TYepxUNOicjA-CEwGJsw", libraries: ['places'] })(MapContainer)
X.define("modules.user.userList", ["model.userModel", "modules.common.routerHelper"], function (userModel, routerHelper) { //初始化视图对象 var view = X.view.newOne({ el: $(".xbn-content"), url: X.config.user.tpl.userList }); //初始化控制器 var ctrl = X.controller.newOne({ view: view }); ctrl.rendering = function () { view.render({}, function () { activeTabLiInfo = route.getRoute() || activeTabLiInfo; ctrl.initPage(); }); }; ctrl.load = function (para) { ctrl.rendering(); }; var header = (function () { return { "tabAll": [ { field: { name: "userId", title: "ID", type: "int" }, width: "3%", className: "tL" }, { field: { name: "mobile", title: "手机号", type: "string" }, width: "12%" }, { field: { name: "userName", title: "姓名", type: "string" }, itemRenderer: { render: function (data, field, index, grid) { if (data.userName.length > 5) { return data.userName.substr(0, 6) + "..."; } else { return data.userName } } }, width: "9%" }, { field: { name: "companyNameCn", title: "所属公司", type: "string" }, width: "20%" }, { field: { name: "createDate", title: "注册时间", type: "string" }, itemRenderer: { render: function (data, field, index, grid) { var arr = data.createDate.split(':'); arr.pop(); str = arr.join(':'); return str; } }, width: "14%" }, { field: { name: "status", title: "状态", type: "string" }, itemRenderer: { render: function (data, field, index, grid) { var result = ''; if (data.status === '0') { result = userModel.statusconst.status.PENDING.text; } else if (data.status === '1') { result = userModel.statusconst.status.PASS.text; } else if (data.status === '2') { result = userModel.statusconst.status.REJECT.text; } return result; } }, width: "8%" }, { field: { name: "status", title: "操作", type: "operation" }, itemRenderer: { render: function (data, field, index, grid) { var result = ''; if (data.status === '0') { result = '<a class="colBlue curp">审核</a>'; } else if (data.status === '1' || data.status === '2') { result = '<a class="colBlue curp">详情</a>'; } return result; } }, width: "10%", className: "operation_main" } ], "pending": [ { field: { name: "userId", title: "ID", type: "int" }, width: "3%", className: "tL" }, { field: { name: "mobile", title: "手机号", type: "string" }, width: "12%" }, { field: { name: "userName", title: "姓名", type: "string" }, width: "9%" }, { field: { name: "companyNameCn", title: "所属公司", type: "string" }, width: "20%" }, { field: { name: "createDate", title: "注册时间", type: "string" }, width: "14%" }, { field: { name: "status", title: "状态", type: "string" }, itemRenderer: { render: function (data, field, index, grid) { var result = ''; if (data.status === '0') { result = userModel.statusconst.status.PENDING.text; } else if (data.status === '1') { result = userModel.statusconst.status.PASS.text; } else if (data.status === '2') { result = userModel.statusconst.status.REJECT.text; } return result; } }, width: "8%" }, { field: { name: "", title: "操作", type: "operation" }, itemRenderer: { render: function (data, field, index, grid) { var result = ''; if (data.status === '0') { result = '<a class="colBlue curp">审核</a>'; } else if (data.status === '1' || data.status === '2') { result = '<a class="colBlue curp">详情</a>'; } return result; } }, width: "10%", className: "operation_main" } ], "adopted": [ { field: { name: "userId", title: "ID", type: "int" }, width: "3%", className: "tL" }, { field: { name: "mobile", title: "手机号", type: "string" }, width: "12%" }, { field: { name: "userName", title: "姓名", type: "string" }, width: "9%" }, { field: { name: "companyNameCn", title: "所属公司", type: "string" }, width: "20%" }, { field: { name: "createDate", title: "注册时间", type: "string" }, width: "14%" }, { field: { name: "status", title: "状态", type: "string" }, itemRenderer: { render: function (data, field, index, grid) { var result = ''; if (data.status === '0') { result = userModel.statusconst.status.PENDING.text; } else if (data.status === '1') { result = userModel.statusconst.status.PASS.text; } else if (data.status === '2') { result = userModel.statusconst.status.REJECT.text; } return result; } }, width: "8%" }, { field: { name: "", title: "操作", type: "operation" }, itemRenderer: { render: function (data, field, index, grid) { var result = ''; if (data.status === '0') { result = '<a class="colBlue curp">审核</a>'; } else if (data.status === '1' || data.status === '2') { result = '<a class="colBlue curp">详情</a>'; } return result; } }, width: "10%", className: "operation_main" } ], "rejected": [ { field: { name: "userId", title: "ID", type: "int" }, width: "3%", className: "tL" }, { field: { name: "mobile", title: "手机号", type: "string" }, width: "12%" }, { field: { name: "userName", title: "姓名", type: "string" }, width: "9%" }, { field: { name: "companyNameCn", title: "所属公司", type: "string" }, width: "20%" }, { field: { name: "createDate", title: "注册时间", type: "string" }, width: "14%" }, { field: { name: "status", title: "状态", type: "string" }, itemRenderer: { render: function (data, field, index, grid) { var result = ''; if (data.status === '0') { result = userModel.statusconst.status.PENDING.text; } else if (data.status === '1') { result = userModel.statusconst.status.PASS.text; } else if (data.status === '2') { result = userModel.statusconst.status.REJECT.text; } return result; } }, width: "8%" }, { field: { name: "", title: "操作", type: "operation" }, itemRenderer: { render: function (data, field, index, grid) { var result = ''; if (data.status === '0') { result = '<a class="colBlue curp">审核</a>'; } else if (data.status === '1' || data.status === '2') { result = '<a class="colBlue curp">详情</a>'; } return result; } }, width: "10%", className: "operation_main" } ] } })(); var getRoute = function () { var route = {panel: activeTabLiInfo, ldata: lists[activeTabLiInfo].val()}; return route; }; var schemas = (function () { var schemas = { "tabAll": { searchMeta: { schema: { simple: [ { name: "companyNameCn", inputName: "companyNameCn", title: "所属公司", ctrlType: "TextBox", placeholder: "请输入所属公司" }, { name: "mobile", inputName: "mobile", title: "手机号码", ctrlType: "TextBox", placeholder: "请输入11位手机号码" }, { name: "status", inputName: "status", title: "状态", ctrlType: "ComboBox", dataSource: userModel.statusconst.cases }, { name: "userId", inputName: "userId", title: "用户ID", ctrlType: "TextBox", placeholder: "请输入用户ID" } ] }, search: { onSearch: function (data, searcher, click) { if (click) { route.setRoute(getRoute()); } if(data.query.userId && isNaN(data.query.userId)){ data.query.userId = -1; } data.query.tabType = '0'; return data; } }, selector: "tabAll", reset: { show: false } }, gridMeta: { columns: header["tabAll"], orderMode: 1, primaryKey: "userId", afterRowRender: function (row, data) { $(row.dom).find('.operation_main').on("click", function () { X.router.run("m=user.userDisplay&userId=" + data["userId"]); }); } }, pageInfo: { pageSize: '10', totalPages: '10', pageNo: '1', smallPapogation: { isShow: false, elem: '.js_small_papogation1' } }, url: X.config.user.api.userlistByPage, toolbar: { items: [ { ctrlType: "ToolbarButton", name: "add", title: "新增用户", icon: "icon-add", click: function (item) { X.router.run("m=user.userEdit", ""); } } ] } }, "pending": { searchMeta: { schema: { simple: [ { name: "companyNameCn", inputName: "companyNameCn", title: "所属公司", ctrlType: "TextBox", placeholder: "请输入所属公司" }, { name: "mobile", inputName: "mobile", title: "手机号码", ctrlType: "TextBox", placeholder: "请输入11位手机号码" }, { name: "userId", inputName: "userId", title: "用户ID", ctrlType: "TextBox", placeholder: "请输入用户ID" } ] }, search: { onSearch: function (data, searcher, click) { if (click) { route.setRoute(getRoute()); } if(data.query.userId && isNaN(data.query.userId)){ data.query.userId = -1; } data.query.tabType = '3'; return data; } }, selector: "pending", reset: { show: false } }, gridMeta: { columns: header["pending"], orderMode: 1, primaryKey: "userId", afterRowRender: function (row, data) { $(row.dom).find('.operation_main').on("click", function () { X.router.run("m=user.userDisplay&userId=" + data["userId"]); }); } }, pageInfo: { pageSize: '10', totalPages: '10', pageNo: '1', smallPapogation: { isShow: false, elem: '.js_small_papogation1' } }, url: X.config.user.api.userlistByPage, toolbar: { items: [ { ctrlType: "ToolbarButton", name: "add", title: "新增用户", icon: "icon-add", click: function (item) { X.router.run("m=user.userEdit", ""); } } ] } }, "adopted": { searchMeta: { schema: { simple: [ { name: "companyNameCn", inputName: "companyNameCn", title: "所属公司", ctrlType: "TextBox", placeholder: "请输入所属公司" }, { name: "mobile", inputName: "mobile", title: "手机号码", ctrlType: "TextBox", placeholder: "请输入11位手机号码" }, { name: "userId", inputName: "userId", title: "用户ID", ctrlType: "TextBox", placeholder: "请输入用户ID" } ] }, search: { onSearch: function (data, searcher, click) { if (click) { route.setRoute(getRoute()); } if(data.query.userId && isNaN(data.query.userId)){ data.query.userId = -1; } data.query.tabType = '1'; return data; } }, selector: "adopted", reset: { show: false } }, gridMeta: { columns: header["adopted"], orderMode: 1, primaryKey: "userId", afterRowRender: function (row, data) { $(row.dom).find('.operation_main').on("click", function () { X.router.run("m=user.userDisplay&userId=" + data["userId"]); }); } }, pageInfo: { pageSize: '10', totalPages: '10', pageNo: '1', smallPapogation: { isShow: false, elem: '.js_small_papogation1' } }, url: X.config.user.api.userlistByPage, toolbar: { items: [ { ctrlType: "ToolbarButton", name: "add", title: "新增用户", icon: "icon-add", click: function (item) { X.router.run("m=user.userEdit", ""); } } ] } }, "rejected": { searchMeta: { schema: { simple: [ { name: "companyNameCn", inputName: "companyNameCn", title: "所属公司", ctrlType: "TextBox", placeholder: "请输入所属公司" }, { name: "mobile", inputName: "mobile", title: "手机号码", ctrlType: "TextBox", placeholder: "请输入11位手机号码" }, { name: "userId", inputName: "userId", title: "用户ID", ctrlType: "TextBox", placeholder: "请输入用户ID" } ] }, search: { onSearch: function (data, searcher, click) { if (click) { route.setRoute(getRoute()); } if(data.query.userId && isNaN(data.query.userId)){ data.query.userId = -1; } data.query.tabType = '2'; return data; } }, selector: "rejected", reset: { show: false } }, gridMeta: { columns: header["rejected"], orderMode: 1, primaryKey: "userId", afterRowRender: function (row, data) { $(row.dom).find('.operation_main').on("click", function () { X.router.run("m=user.userDisplay&userId=" + data["userId"]); }); } }, pageInfo: { pageSize: '10', totalPages: '10', pageNo: '1', smallPapogation: { isShow: false, elem: '.js_small_papogation1' } }, url: X.config.user.api.userlistByPage, toolbar: { items: [ { ctrlType: "ToolbarButton", name: "add", title: "新增用户", icon: "icon-add", click: function (item) { X.router.run("m=user.userEdit", ""); } } ] } } }; return schemas; })(); var lists = {}; var activeTabLiInfo = "tabAll"; function initTabPage($elem, schema, tabPage) { var list = X.controls.getControl("List", $elem, schema); list.init(); lists[tabPage] = list; } ctrl.initPage = function () { var tabPannel = X.controls.getControl("TabPanel", $('.js_tabPannel1'), { activeTabInfo: activeTabLiInfo, beforeChangeTab: function (tabLiInfo, targetLi, index, tabPage) { activeTabLiInfo = tabLiInfo; // 刊登状态 不同 var page = $(tabPage); if (!page.data("hasInited")) { var schema = schemas[tabLiInfo]; if (schema) { initTabPage(page, schema, tabLiInfo); } page.data("hasInited", true); } // 为了样式效果,把当前选中的前一个加上样式名 targetLi.prev().removeClass('tab_lineNone'); return true; }, afterChangeTab: function (tabLiInfo, targetLi, index, tabPage, oldTab) { activeTabLiInfo = tabLiInfo; activeTabLi = targetLi; // 为了样式效果,把当前选中的前一个加上样式名 targetLi.prev().addClass('tab_lineNone'); if (tabLiInfo != oldTab) { route.setRoute({panel: tabLiInfo}); } } }); }; var route = new routerHelper("user.userList", schemas, getRoute); return ctrl; });
import React, { useState } from "react"; import AddCategory from "./AddCategory"; import CategoryListItem from "./CategoryListItem"; const CategoryList = () => { const [isOpen, setIsOpen] = useState(false); const toggleIsOpen = () => { setIsOpen(!isOpen); }; return ( <section className=""> {/* Title */} <section onClick={toggleIsOpen} className={`transition-all duration-200 p-6 flex items-center justify-between cursor-pointer hover:bg-gray-700 ${ isOpen ? "border-b-2 border-gray-600" : "" }`} > <h2 className="text-lg font-semibold">Categories</h2> <svg xmlns="http://www.w3.org/2000/svg" className={`h-4 w-4 transition-all duration-200 text-gray-400 ${ isOpen ? "-rotate-90" : "" }`} fill="none" viewBox="0 0 24 24" stroke="currentColor" > <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" /> </svg> </section> {/* Category List Items */} {isOpen && ( <section> {/* Add Category */} <AddCategory /> {/* List */} <CategoryListItem title="All" /> <CategoryListItem title="Home" /> <CategoryListItem title="School" /> <CategoryListItem title="Work" /> </section> )} </section> ); }; export default CategoryList;
import React from 'react'; import {Switch,Route,Redirect} from 'react-router-dom'; import {NavLink} from 'react-router-dom'; import './style.css'; import HandWrittenNotesComponent from './hand-written-notes'; import PreviousYearPapersComponent from './previous-year-papers'; import RecommendedBooksComponent from './recommended-books'; export default class StudyMatrialComponent extends React.Component{ render(){ return <div className="study-matrial-container container-fluid"> <div className="row navigation-row"> <div className="flex-grow-1 navigation-col"> <ul className="study-matrial-list"> <li className="study-matrial-item"> <NavLink to={`${this.props.match.url}/previous-year-papers`} >Previous Year Papers</NavLink> </li> <li className="study-matrial-item"> <NavLink to={`${this.props.match.url}/recommended-books`}>Recommended Books</NavLink> </li> <li className="study-matrial-item"> <NavLink to={`${this.props.match.url}/hand-written-notes`} >Hand Written Notes</NavLink> </li> </ul> </div> </div> <div className="row"> <button className="btn btn-primary" onClick={this.props.history.goBack}>Back</button> </div> <div className="row"> <Switch> <Route path={`${this.props.match.url}/hand-written-notes`} render ={()=>{ return <HandWrittenNotesComponent {...this.props}/>; }}/> <Route path={`${this.props.match.url}/previous-year-papers`} render ={()=>{ return <PreviousYearPapersComponent {...this.props}/>; }}/> <Route path={`${this.props.match.url}/recommended-books`} render ={()=>{ return <RecommendedBooksComponent {...this.props}/>; }}/> <Route render ={()=>{ return <Redirect to={`${this.props.match.url}/previous-year-papers`}/>; }}/> </Switch> </div> </div>; } }
import firebase from 'firebase'; import '@firebase/firestore'; import { ADD_NEW_ORDER_SUCCESS, FETCH_ORDER_SUCCESS } from './types'; export const fetchListOrders = () => dispatch => { const { currentUser } = firebase.auth(); let db = firebase.firestore(); let data = []; db.collection('users').doc(`${currentUser.uid}`).collection('orders').get() .then((querySnapshot) => { querySnapshot.forEach((doc) => { data.push({ id: doc.id, customer: doc.data().customer, date: doc.data().date, list_detail: doc.data().list_detail, total: doc.data().total }) }); dispatch({ type: FETCH_ORDER_SUCCESS, payload: data }); }) .catch((err) => { console.log(err); }); }
function backupTimeEstimator(startTimes, backupDuration, maxThreads) { var estimations = [[],[], []]; // start, end, backupDurationLeft var activeThreads = 0; var queue = []; var queueCandidate = null; var smallestBackup = Infinity; var time = startTimes[0]; while (true) { // Time it will take to perform one more step of backup time += activeThreads; // Perform that one more step of backup on any active threads for (s in startTimes) { if (estimations[0].includes(startTimes[s]) && estimations[2][estimations[0].indexOf(startTimes[s])] > 0) { estimations[1][estimations[0].indexOf(startTimes[s])] += time; // New end time estimate estimations[2][estimations[0].indexOf(startTimes[s])] } } // See what's done // Add new for (t in startTimes) { if (startTimes[t] <= time && !estimations[0].includes(startTimes[t]) && !queue.includes(t)) { queue.push(t); } } while (activeThreads < maxThreads) { for (i in queue) { if (backupDuration[queue[i]] < smallestBackup) { smallestBackup = backupDuration[i]; queueCandidate = queue[i]; // Index of particular backup start time and duration } } estimations[0].push(startTimes[queueCandidate]); estimations[1].push(time+backupDuration); queue.splice(indexOf(queueCandidate),1); activeThreads++; smallestBackup = Infinity; } // Advance everything 1 step queue = startTimes.filter(t => !estimations[0].includes(t) && t <= time && ) break; } var time = startTimes[0]; var nTimes = startTimes.length; var completionPercents = [[], [], []]; var timeLeft = null; while (estimations.length < nTimes) { for (var i = 0; i <= activeThreads; i++) { } //add to queue //check if complete // for (t in startTimes) { // Add backup to queue if ( time >= startTimes[t] && !completionPercents[0].includes(startTimes[t]) && activeThreads < maxThreads ) { backupDuration activeThreads++; completionPercents[0].push(startTimes[t]); completionPercents[1].push(backupDuration[t]); completionPercents[2].push(0); } } time += 1*activeThreads for (a in completionPercents) { // Garbage-collecting if (completionPercents[a][2] >= 1) { estimations.push(time); completionPercents.splice(a, 1); } } // Account for backup time in completion time for (i in completionPercents) { timeLeft = completionPercents[i][1]*(1-completionPercents[i][2]); timeLeft -= 1/activeThreads; completionPercents[i][2] = 1 - timeLeft/backupDuration; } take away when done time++ } for (var i = 1; i < startTimes.length; i++) { for (j in completionPercents) { completionPercents[j][] completionPercents[j][1]--; } if (activeThreads startTimes[i] } in startTimes) { if (activeThreads <= maxThreads) { activeThreads++; } else { completionPercents = [[startTimes[i], backupDuration[i], 0]]; } } //tofixed }
(function() { 'use strict'; angular .module('iconlabApp') .config(stateConfig); stateConfig.$inject = ['$stateProvider']; function stateConfig($stateProvider) { $stateProvider .state('projet', { parent: 'entity', url: '/projet?page&sort&search', data: { authorities: ['ROLE_ADMIN'], pageTitle: 'Projets' }, views: { 'content@': { templateUrl: 'app/entities/projet/projets.html', controller: 'ProjetController', controllerAs: 'vm' } }, params: { page: { value: '1', squash: true }, sort: { value: 'id,asc', squash: true }, search: null }, resolve: { pagingParams: ['$stateParams', 'PaginationUtil', function ($stateParams, PaginationUtil) { return { page: PaginationUtil.parsePage($stateParams.page), sort: $stateParams.sort, predicate: PaginationUtil.parsePredicate($stateParams.sort), ascending: PaginationUtil.parseAscending($stateParams.sort), search: $stateParams.search }; }], } }) .state('projet-detail', { parent: 'entity', url: '/projet/{id}', data: { authorities: ['ROLE_USER','ROLE_CEO','ROLE_DO','ROLE_PMO'], pageTitle: 'Projet' }, views: { 'content@': { templateUrl: 'app/entities/projet/projet-detail.html', controller: 'ProjetDetailController', controllerAs: 'vm' } }, resolve: { entity: ['$stateParams', 'Projet', function($stateParams, Projet) { return Projet.get({id : $stateParams.id}).$promise; }] } }) .state('app.projetcompte.newuser', { parent: 'app.projetcompte', url: '/new', data: { authorities: ['ROLE_USER','ROLE_CEO','ROLE_DO','ROLE_PMO'] }, onEnter: ['$stateParams', '$state', '$uibModal', function($stateParams, $state, $uibModal) { $uibModal.open({ templateUrl: 'app/entities/projet/projet-dialogC.html', controller: 'ProjetDialogController', controllerAs: 'vm', backdrop: 'static', windowClass:'center-modal', size: 'md', resolve: { entity: function () { return { name: null, code: null, description: null, fichierProjet: null, fichierProjetContentType: null, fromt: null, tot: null, actif: null, sortable: null, classes: null, height: null, color: null, parent: null, tooltips: null, id: null }; } } }).result.then(function() { $state.go('app.projetcompte', null, { reload: true }); }, function() { $state.go('app.projetcompte'); }); }] }) .state('projet.newadmin', { parent: 'projet', url: '/new', data: { authorities: ['ROLE_ADMIN'] }, onEnter: ['$stateParams', '$state', '$uibModal', function($stateParams, $state, $uibModal) { $uibModal.open({ templateUrl: 'app/entities/projet/projet-dialog.html', controller: 'ProjetDialogController', controllerAs: 'vm', backdrop: 'static', windowClass:'center-modal', size: 'md', resolve: { entity: function () { return { name: null, code: null, description: null, fichierProjet: null, fichierProjetContentType: null, fromt: null, tot: null, actif: null, sortable: null, classes: null, height: null, color: null, parent: null, tooltips: null, id: null }; } } }).result.then(function() { $state.go('projet', null, { reload: true }); }, function() { $state.go('projet'); }); }] }) .state('projet.editadmin', { parent: 'projet', url: '/{idp}/edit', data: { authorities: ['ROLE_ADMIN'] }, onEnter: ['$stateParams', '$state', '$uibModal', function($stateParams, $state, $uibModal) { $uibModal.open({ templateUrl: 'app/entities/projet/projet-dialog.html', controller: 'ProjetDialogController', controllerAs: 'vm', backdrop: 'static', windowClass:'center-modal', size: 'md', resolve: { entity: ['Projet', function(Projet) { return Projet.get({id : $stateParams.idp}).$promise; }] } }).result.then(function() { $state.go('projet', null, { reload: true }); }, function() { $state.go('^'); }); }] }) .state('app.projetcompte.edituser', { parent: 'app.projetcompte', url: '/{idprojet}/edituser', data: { authorities: ['ROLE_USER','ROLE_CEO','ROLE_DO','ROLE_PMO'] }, onEnter: ['$stateParams', '$state', '$uibModal', function($stateParams, $state, $uibModal) { $uibModal.open({ templateUrl: 'app/entities/projet/projet-dialogC.html', controller: 'ProjetDialogController', controllerAs: 'vm', backdrop: 'static', windowClass:'center-modal', size: 'md', resolve: { entity: ['Projet', function(Projet) { return Projet.get({id : $stateParams.idprojet}).$promise; }] } }).result.then(function() { $state.go('app.projetcompte', null, { reload: true }); }, function() { $state.go('^'); }); }] }) .state('app.tacheprojet.detailuser', { parent: 'app.tacheprojet', url: '/projetdesc/{idprojet}', data: { authorities: ['ROLE_USER','ROLE_CEO','ROLE_DO','ROLE_PMO'] }, onEnter: ['$stateParams', '$state', '$uibModal', function($stateParams, $state, $uibModal) { $uibModal.open({ templateUrl: 'app/entities/projet/detailprojet.html', controller: 'ProjetDetailController', controllerAs: 'vm', backdrop: 'static', windowClass:'center-modal', size: 'md', resolve: { entity: ['Projet', function(Projet) { return Projet.get({id : $stateParams.idprojet}).$promise; }] } }).result.then(function() { $state.go('app.tacheprojet', null, { reload: true }); }, function() { $state.go('^'); }); }] }) .state('app.projetcompte.editmessage', { parent: 'app.projetcompte', url: '/{idedtmess}/editmessage', data: { authorities: ['ROLE_USER','ROLE_CEO','ROLE_DO','ROLE_PMO'] }, onEnter: ['$stateParams', '$state', '$uibModal', function($stateParams, $state, $uibModal) { $uibModal.open({ templateUrl: 'app/entities/message-hierachique/message-hierachiqueU.html', controller: 'MessageHierachiqueDialogController', controllerAs: 'vm', backdrop: 'static', windowClass:'center-modal', size: 'md', resolve: { entity: ['MessageHierachique', function(MessageHierachique) { return MessageHierachique.get({id : $stateParams.idedtmess}).$promise; }] } }).result.then(function() { $state.go('app.projetcompte', null, { reload: true }); }, function() { $state.go('^'); }); }] }) .state('app.projetcompte.editdocument', { parent: 'app.projetcompte', url: '/{idedtdoc}/editDoc', data: { authorities: ['ROLE_USER','ROLE_CEO','ROLE_DO','ROLE_PMO'] }, onEnter: ['$stateParams', '$state', '$uibModal', function($stateParams, $state, $uibModal) { $uibModal.open({ templateUrl: 'app/entities/documents/documents-dialogU.html', controller: 'DocumentsDialogController', controllerAs: 'vm', backdrop: 'static', windowClass:'center-modal', size: 'md', resolve: { entity: ['Documents', function(Documents) { return Documents.get({id : $stateParams.idedtdoc}).$promise; }] } }).result.then(function() { $state.go('app.projetcompte', null, { reload: true }); }, function() { $state.go('^'); }); }] }) .state('projet.delete', { parent: 'projet', url: '/{id}/delete', data: { authorities: ['ROLE_ADMIN'] }, onEnter: ['$stateParams', '$state', '$uibModal', function($stateParams, $state, $uibModal) { $uibModal.open({ templateUrl: 'app/entities/projet/projet-delete-dialog.html', controller: 'ProjetDeleteController', controllerAs: 'vm', windowClass:'center-modal', size: 'md', resolve: { entity: ['Projet', function(Projet) { return Projet.get({id : $stateParams.id}).$promise; }] } }).result.then(function() { $state.go('projet', null, { reload: true }); }, function() { $state.go('^'); }); }] }); } })();
/* |-------------------------------------------------------------------------- | Action types as constants |-------------------------------------------------------------------------- **/ /** * A user action type. */ export const GET_USER_BEGIN = 'GET_USER_BEGIN'; export const GET_USER_SUCCESS = 'GET_USER_SUCCESS'; export const GET_USER_FAILURE = 'GET_USER_FAILURE'; /** * Determine if action is an API call or not */ export const API = 'API'; export const API_GET = 'get'; export const API_POST = 'post'; export const API_PUT = 'put'; export const API_DELETE = 'del';
var gulp = require("gulp"), annotate = require("gulp-ng-annotate"), concat = require("gulp-concat"), uglify = require("gulp-uglify"); gulp.task("default", ["build"], function (){ gulp.watch(["client/**/*", "server/**/*"], ["build"]); }); gulp.task("build", ["views", "ngapp", "vendors", "static"], function () { console.log("Build completo"); }); gulp.task("ngapp", function (){ return gulp.src("client/ngapp/**/*.js") .pipe(annotate()) .pipe(concat("app.js")) .pipe(uglify()) .pipe(gulp.dest("dist/client")); }); gulp.task("vendors", function (){ return gulp.src("bower_components/**/*") .pipe(gulp.dest("dist/client/static/vendors")) }); gulp.task("static", function (){ return gulp.src("client/static/**/*") .pipe(gulp.dest("dist/client/static")); }); gulp.task("views", function (){ gulp.src("client/index.html") .pipe(gulp.dest("dist/client/")); gulp.src("client/ngapp/views/**/*.html") .pipe(gulp.dest("dist/client/static/views/")); }); gulp.task("server", function (){ return gulp.src("server/**/*") .pipe(gulp.dest("dist/server")); });
export default class GetMenuItemsUseCase { constructor({database, logger}) { this.menuItemDao = database.menuItemDao(); this.logger = logger; } async execute(param) { return await this.menuItemDao.getMenuItems(param); } }
import React, { useEffect, useState, useRef } from 'react'; import Konva from 'konva'; import { Stage, Layer, Rect, Circle, Line, Text, Image } from "react-konva"; import useImage from 'use-image'; import tileBackground from '../assets/SVGS/pink_tiled_background.svg' const ShowerPowerDisplay = ({getContext, engageDisengage, handleChannelGainChange, handleWetDryChange, handlePreDelayChange, handleCompChange, handleEQChange, chooseReverb, audioContext}) => { const [stageWidth, setStageWidth] = useState(window.innerWidth); const [stageHeight, setStageHeight] = useState(window.innerHeight); const [tiles] = useImage(tileBackground); const [engaged, setEngaged] = useState(false); let engagedLine = useRef(); let volumeLine = useRef(); const [volumeDragAmount, setVolumeDragAmount] = useState(0); const [volumeAmount, setVolumeAmount] = useState(1); let wetDryLine = useRef(); const [wetDryDragAmount, setWetDryDragAmount] = useState(0); const [wetDryAmount, setWetDryAmount] = useState([]); const [reverb, setReverb] = useState('one'); const [reverbDragAmount, setReverbDragAmount] = useState(); let reverbLine = useRef(); let wetDry = useRef(); let volume = useRef(); let preDelayLine = useRef(); const [preDelayDragAmount, setPreDelayDragAmount] = useState(); const [preDelayAmount, setPreDelayAmount] = useState(0.01); let compressionLine = useRef(); const [compressionDragAmount, setCompressionDragAmount] = useState(); const [compressionSpeed, setCompressionSpeed] = useState('fast'); let eqBoostLine = useRef(); const [eqBoostDragAmount, setEQBoostDragAmount] = useState(0); const [eqBoostSetting, setEQBoostSetting] = useState('none'); const stageRefOne = useRef(); const engagedLight = useRef(); const [engagedHelper, setEngagedHelper] = useState(false) const updateWidthAndHeight = () => { setStageWidth(window.innerWidth); setStageHeight(window.innerHeight); } useEffect(() => { window.addEventListener('resize', updateWidthAndHeight) return () => { window.removeEventListener('resize', updateWidthAndHeight); } }); useEffect(() => { if(!engaged){ return; } let period = 300; let animation = new Konva.Animation(frame => { engagedLight.current.opacity((Math.sin(frame.time / period) + 1) / 2); }, engagedLight.current.getLayer()); animation.start(); return () => { animation.stop(); }; }) useEffect(() => { chooseReverb(reverb) }, [reverb]) useEffect(() => { handleChannelGainChange(volumeAmount) }, [volumeAmount]); useEffect(() => { handleWetDryChange(wetDryAmount); }, [wetDryAmount]) useEffect(() => { handlePreDelayChange(preDelayAmount); }, [preDelayAmount]) useEffect(() => { handleCompChange(compressionSpeed) }, [compressionSpeed]); useEffect(() => { handleEQChange(eqBoostSetting); }, [eqBoostSetting]) const widthPercentage = (width) => { return Math.floor(stageWidth / (100 / width)) } const heightPercentage = (height) => { return Math.floor(stageHeight / (100 / height)) } const hadleEngaged = () => { if(!audioContext){ window.alert('You must enable User Audio before you can enable Audio effects') return ; } setEngaged(!engaged); engageDisengage(); if(engaged){ engagedLine.current.rotation(90) } else if(!engaged){ engagedLine.current.rotation(-90) } } const getReverbAmount = () => { if(!audioContext){ window.alert('You must enable User Audio before you can enable Audio effects') return ; } if(reverbDragAmount === 90){ setReverb('two') }else if(reverbDragAmount === -90){ setReverb('one') } } const rotateReverb = () => { if(reverbDragAmount > 0){ reverbLine.current.rotation(90) } else if(reverbDragAmount < 0){ reverbLine.current.rotation(-90) } } const getReverbDragMove = (e) => { const difference = (e.currentTarget.attrs.x - e.evt.clientX) if(difference > 90){ setReverbDragAmount(90) } else if(difference < -90){ setReverbDragAmount(-90) } else { setReverbDragAmount(difference); } rotateReverb(); } const getVolumeAmount = () => { if(!audioContext){ window.alert('You must enable User Audio before you can enable Audio effects') return ; } setVolumeAmount(((Math.floor(volumeDragAmount/9))/10) + 1) } const rotateVolume = () => { if(volumeDragAmount > 90){ volumeLine.current.rotation(90) } else if(volumeDragAmount < -90){ volumeLine.current.rotation(-90) } else { volumeLine.current.rotation(volumeDragAmount) } } const getVolumeDragMove = (e) =>{ const difference = (e.currentTarget.attrs.x - e.evt.clientX) if(difference > 90){ setVolumeDragAmount(90) } else if(difference < -90){ setVolumeDragAmount(-90) } else { setVolumeDragAmount(difference); } rotateVolume(); } const getWetDryAmount = () => { if(!audioContext){ window.alert('You must enable User Audio before you can enable Audio effects') return ; } setWetDryAmount([(2 - (((Math.floor(wetDryDragAmount/9))/10) + 1)), (((Math.floor(wetDryDragAmount/9))/10) + 1)]); } const rotateWetDry = () => { if(wetDryDragAmount > 90){ wetDryLine.current.rotation(90) } else if(wetDryDragAmount < -90){ wetDryLine.current.rotation(-90) } else { wetDryLine.current.rotation(wetDryDragAmount) } } const getWetDryDragMove = (e) => { const difference = (e.currentTarget.attrs.x - e.evt.clientX) if(difference > 90){ setWetDryDragAmount(90) } else if(difference < -90){ setWetDryDragAmount(-90) } else { setWetDryDragAmount(difference); } rotateWetDry(); } const getCompressionSpeed = () => { if(!audioContext){ window.alert('You must enable User Audio before you can enable Audio effects') return ; } if(compressionDragAmount >= 0 || compressionDragAmount > 90){ setCompressionSpeed('slow'); } else if(compressionDragAmount <= -1 || compressionDragAmount < -90){ setCompressionSpeed('fast'); } } const compressionSnapDrag = () => { if(compressionDragAmount >= 0 || compressionDragAmount > 90){ compressionLine.current.rotation(90); } else if(compressionDragAmount <= -1 || compressionDragAmount < -90){ compressionLine.current.rotation(-90) } } const getCompressionDragMove = (e) => { const difference = (e.currentTarget.attrs.x - e.evt.clientX) if(difference >= 0 || difference > 90){ setCompressionDragAmount(90) } else if(difference <= -1 || difference < -90){ setCompressionDragAmount(-90) } compressionSnapDrag(); } const getEQBoostSetting = () => { if(!audioContext){ window.alert('You must enable User Audio before you can enable Audio effects') return ; } if(eqBoostDragAmount >= 45 || eqBoostDragAmount >= 90){ setEQBoostSetting('treble') } else if(eqBoostDragAmount <= -45 || eqBoostDragAmount <= -90){ setEQBoostSetting('bass') } else { setEQBoostSetting('none') } } const eqBoostSnapDrag = () =>{ if(eqBoostDragAmount >= 45 || eqBoostDragAmount >= 90){ eqBoostLine.current.rotation(90) } else if(eqBoostDragAmount <= -45 || eqBoostDragAmount <= -90){ eqBoostLine.current.rotation(-90) } else { eqBoostLine.current.rotation(0) } } const getEQBoostDragMove = (e) => { const difference = (e.currentTarget.attrs.x - e.evt.clientX) if(difference >= 45 || difference > 90){ setEQBoostDragAmount(90) } else if(difference <= -45 || difference < -90){ setEQBoostDragAmount(-90) } else { setEQBoostDragAmount(0) } eqBoostSnapDrag(); } const getPreDelayAmount = () => { if(!audioContext){ window.alert('You must enable User Audio before you can enable Audio effects') return ; } setPreDelayAmount(Math.floor((preDelayDragAmount + 90)/18)/100); } const rotatePreDelay = () => { if(preDelayDragAmount > 90){ preDelayLine.current.rotation(90) } else if(preDelayDragAmount < -90){ preDelayLine.current.rotation(-90) } else { preDelayLine.current.rotation(preDelayDragAmount) } } const getPreDelayDragMove = (e) => { const difference = (e.currentTarget.attrs.x - e.evt.clientX); if(difference > 90){ setPreDelayDragAmount(90) } else if(difference < -90){ setPreDelayDragAmount(-90) } else { setPreDelayDragAmount(difference); } rotatePreDelay(); } const handleContext = () => { if(audioContext){ return; } getContext(); } const handleEngagedMouseEnter = () => { setEngagedHelper(true) } const handleEngagedMouseLeave = () => { setEngagedHelper(false) } return ( <div> <Stage ref={stageRefOne} width={stageWidth} height={stageHeight}> <Layer> <Rect width={stageWidth} height={stageWidth} fill="#93b8f5" zIndex={-100}/> <Image image={tiles} width={stageWidth} height={stageHeight}/> <Text text="SHOWER" x={widthPercentage(1)} y={heightPercentage(4)} fontSize={widthPercentage(7)} fontFamily={'Major Mono Display'}/> <Text text="POWER" x={widthPercentage(70)} y={heightPercentage(4)} fontSize={widthPercentage(7)} fontFamily={'Major Mono Display'}/> <Circle x={widthPercentage(50.5)} y={heightPercentage(12)} radius={widthPercentage(5)} fill="black" shadowBlur={7}/> <Circle ref={engagedLight} x={widthPercentage(50.5)} y={heightPercentage(12)} radius={widthPercentage(3)} fill="red" shadowBlur={7} opacity={engaged ? 0 : 1}/> <Circle x={widthPercentage(50.5)} y={heightPercentage(12)} radius={widthPercentage(5)} fill="black" shadowBlur={7} opacity={engaged ? 0 : 1}/> <Text text="ON" x={widthPercentage(39)} y={heightPercentage(56)} fontSize={widthPercentage(3)} fontFamily={'Major Mono Display'}/> <Circle x={widthPercentage(50.5)} y={heightPercentage(60)} radius={widthPercentage(2)} fill="grey" onClick={hadleEngaged} onMouseEnter={handleEngagedMouseEnter} onMouseLeave={handleEngagedMouseLeave}/> <Circle x={widthPercentage(50.5)} y={heightPercentage(60)} radius={widthPercentage(1)} fill="black" onClick={hadleEngaged} onMouseEnter={handleEngagedMouseEnter} onMouseLeave={handleEngagedMouseLeave}/> <Line ref={engagedLine} x={widthPercentage(50.5)} y={heightPercentage(60)} points={[0,0,0,- widthPercentage(2)]} stroke={'black'} strokeWidth={5} closed={true} lineCap={"round"}/> <Text text="OFF" x={widthPercentage(57)} y={heightPercentage(56)} fontSize={widthPercentage(3)} fontFamily={'Major Mono Display'}/> <Text text='Click To Engage' x={widthPercentage(50)} y={heightPercentage(65)} fontSize={widthPercentage(1)} fontFamily={'Major Mono Display'} opacity={engagedHelper && !engaged ? 1 : 0}/> <Text text="WET" x={widthPercentage(3)} y={heightPercentage(56)} fontSize={widthPercentage(3)} fontFamily={'Major Mono Display'}/> <Circle ref={wetDry} x={widthPercentage(15)} y={heightPercentage(60)} radius={widthPercentage(3)} fill="grey" draggable onDragMove={getWetDryDragMove} onDragEnd={getWetDryAmount} dragBoundFunc={function(pos){return{x: this.absolutePosition().x, y: this.absolutePosition().y}}}/> <Circle x={widthPercentage(15)} y={heightPercentage(60)} radius={widthPercentage(1)} fill="black" draggable onDragMove={getWetDryDragMove} onDragEnd={getWetDryAmount} dragBoundFunc={function(pos){return{x: this.absolutePosition().x, y: this.absolutePosition().y}}}/> <Line ref={wetDryLine} x={widthPercentage(15)} y={heightPercentage(60)} points={[0,0,0,- widthPercentage(3)]} stroke={'black'} strokeWidth={5} closed={true} lineCap={"round"}/> <Text text="DRY" x={widthPercentage(21)} y={heightPercentage(56)} fontSize={widthPercentage(3)} fontFamily={'Major Mono Display'}/> <Text text="-60DB" x={widthPercentage(68)} y={heightPercentage(56)} fontSize={widthPercentage(3)} fontFamily={'Major Mono Display'}/> <Circle ref={volume} x={widthPercentage(85)} y={heightPercentage(60)} radius={widthPercentage(3)} fill="grey" draggable onDragMove={getVolumeDragMove} onDragEnd={getVolumeAmount} dragBoundFunc={function(pos){return{x: this.absolutePosition().x, y: this.absolutePosition().y}}}/> <Circle x={widthPercentage(85)} y={heightPercentage(60)} radius={widthPercentage(1)} fill="black" draggable onDragMove={getVolumeDragMove} onDragEnd={getVolumeAmount} dragBoundFunc={function(pos){return{x: this.absolutePosition().x, y: this.absolutePosition().y}}}/> <Line ref={volumeLine} x={widthPercentage(85)} y={heightPercentage(60)} points={[0,0,0,- widthPercentage(3)]} stroke={'black'} strokeWidth={5} closed={true} lineCap={"round"}/> <Text text="0DB" x={widthPercentage(91)} y={heightPercentage(56)} fontSize={widthPercentage(3)} fontFamily={'Major Mono Display'}/> <Text text="REVERB" x={widthPercentage(24)} y={heightPercentage(25)} fontSize={widthPercentage(4)} fontFamily={'Major Mono Display'}/> <Text text="1" x={widthPercentage(25)} y={heightPercentage(35)} fontSize={widthPercentage(4)} fontFamily={'Major Mono Display'}/> <Circle x={widthPercentage(33.5)} y={heightPercentage(39)} radius={widthPercentage(2)} fill="grey" draggable onDragMove={getReverbDragMove} onDragEnd={getReverbAmount} dragBoundFunc={function(pos){return{x: this.absolutePosition().x, y: this.absolutePosition().y}}}/> <Circle x={widthPercentage(33.5)} y={heightPercentage(39)} radius={widthPercentage(1)} fill="black" draggable onDragMove={getReverbDragMove} onDragEnd={getReverbAmount} dragBoundFunc={function(pos){return{x: this.absolutePosition().x, y: this.absolutePosition().y}}}/> <Line ref={reverbLine} x={widthPercentage(33.5)} y={heightPercentage(39)} points={[0,0,0,- widthPercentage(2)]} stroke={'black'} strokeWidth={5} closed={true} lineCap={"round"}/> <Text text="2" x={widthPercentage(39)} y={heightPercentage(35)} fontSize={widthPercentage(4)} fontFamily={'Major Mono Display'}/> <Text text="PRE-DELAY" x={widthPercentage(55)} y={heightPercentage(25)} fontSize={widthPercentage(4)} fontFamily={'Major Mono Display'}/> <Text text="0.01" x={widthPercentage(53)} y={heightPercentage(35)} fontSize={widthPercentage(3)} fontFamily={'Major Mono Display'}/> <Circle x={widthPercentage(67.5)} y={heightPercentage(39)} radius={widthPercentage(2)} fill="grey" draggable onDragMove={getPreDelayDragMove} onDragEnd={getPreDelayAmount} dragBoundFunc={function(pos){return{x: this.absolutePosition().x, y: this.absolutePosition().y}}}/> <Circle x={widthPercentage(67.5)} y={heightPercentage(39)} radius={widthPercentage(1)} fill="black" draggable onDragMove={getPreDelayDragMove} onDragEnd={getPreDelayAmount} dragBoundFunc={function(pos){return{x: this.absolutePosition().x, y: this.absolutePosition().y}}}/> <Line ref={preDelayLine} x={widthPercentage(67.5)} y={heightPercentage(39)} points={[0,0,0,- widthPercentage(2)]} stroke={'black'} strokeWidth={5} closed={true} lineCap={"round"}/> <Text text="0.1" x={widthPercentage(75)} y={heightPercentage(35)} fontSize={widthPercentage(3)} fontFamily={'Major Mono Display'}/> <Text text="COMPRESSION" x={widthPercentage(22)} y={heightPercentage(73)} fontSize={widthPercentage(3)} fontFamily={'Major Mono Display'}/> <Text text="FAST" x={widthPercentage(23)} y={heightPercentage(85)} fontSize={widthPercentage(2)} fontFamily={'Major Mono Display'}/> <Circle x={widthPercentage(33.5)} y={heightPercentage(87)} radius={widthPercentage(2)} fill="grey" draggable onDragMove={getCompressionDragMove} onDragEnd={getCompressionSpeed} dragBoundFunc={function(pos){return{x: this.absolutePosition().x, y: this.absolutePosition().y}}}/> <Circle x={widthPercentage(33.5)} y={heightPercentage(87)} radius={widthPercentage(1)} fill="black" draggable onDragMove={getCompressionDragMove} onDragEnd={getCompressionSpeed} dragBoundFunc={function(pos){return{x: this.absolutePosition().x, y: this.absolutePosition().y}}}/> <Line ref={compressionLine} x={widthPercentage(33.5)} y={heightPercentage(87)} points={[0,0,0,- widthPercentage(2)]} stroke={'black'} strokeWidth={5} closed={true} lineCap={"round"}/> <Text text="SLOW" x={widthPercentage(38)} y={heightPercentage(85)} fontSize={widthPercentage(2)} fontFamily={'Major Mono Display'}/> <Text text="EQ BOOST" x={widthPercentage(60)} y={heightPercentage(73)} fontSize={widthPercentage(3)} fontFamily={'Major Mono Display'}/> <Text text="NONE" x={widthPercentage(64.5)} y={heightPercentage(79.5)} fontSize={widthPercentage(1.5)} fontFamily={'Major Mono Display'}/> <Text text="BASS" x={widthPercentage(59)} y={heightPercentage(86)} fontSize={widthPercentage(1.5)} fontFamily={'Major Mono Display'}/> <Circle x={widthPercentage(66.5)} y={heightPercentage(88)} radius={widthPercentage(2)} fill="grey" draggable onDragMove={getEQBoostDragMove} onDragEnd={getEQBoostSetting} dragBoundFunc={function(pos){return{x: this.absolutePosition().x, y: this.absolutePosition().y}}}/> <Circle x={widthPercentage(66.5)} y={heightPercentage(88)} radius={widthPercentage(1)} fill="black" draggable onDragMove={getEQBoostDragMove} onDragEnd={getEQBoostSetting} dragBoundFunc={function(pos){return{x: this.absolutePosition().x, y: this.absolutePosition().y}}}/> <Line ref={eqBoostLine} x={widthPercentage(66.5)} y={heightPercentage(88)} points={[0,0,0,- widthPercentage(2)]} stroke={'black'} strokeWidth={5} closed={true} lineCap={"round"}/> <Text text="TREBLE" x={widthPercentage(69.5)} y={heightPercentage(86)} fontSize={widthPercentage(1.5)} fontFamily={'Major Mono Display'}/> <Text text="Click To" x={widthPercentage(3)} y={heightPercentage(26)} fontSize={widthPercentage(1)} fontFamily={'Major Mono Display'} opacity={audioContext ? 0 : 1}/> <Text text="Enable" x={widthPercentage(3)} y={heightPercentage(28)} fontSize={widthPercentage(1)} fontFamily={'Major Mono Display'} opacity={audioContext ? 0 : 1}/> <Circle x={widthPercentage(7)} y={heightPercentage(35)} radius={widthPercentage(2)} fill="grey" onClick={handleContext} opacity={audioContext ? 0 : 1}/> <Circle x={widthPercentage(7)} y={heightPercentage(35)} radius={widthPercentage(1)} fill="black" onClick={handleContext} opacity={audioContext ? 0 : 1}/> <Text text="User Audio" x={widthPercentage(1)} y={heightPercentage(40)} fontSize={widthPercentage(2)} fontFamily={'Major Mono Display'} opacity={audioContext ? 0 : 1}/> </Layer> </Stage> </div> ) } export default ShowerPowerDisplay;
import React from 'react'; import PropTypes from 'prop-types'; import Slider from 'react-rangeslider' import { Statistic } from 'semantic-ui-react' export default class GraphicLevel extends React.Component { constructor (props) { super(props) this.state = { value: this.props.graphicLevel, newGraphicLevel: this.props.newGraphicLevel } } handleChange = value => { this.setState({ value: value }) this.state.newGraphicLevel(value) }; render () { const { value } = this.state return ( <div className='slider'> <Slider min={1} orientation="vertical" max={3} value={value} onChange={this.handleChange} /> <Statistic value={value} /> </div> ) } } GraphicLevel.PropTypes = { graphicLevel: PropTypes.number.isRequired, newGraphicLevel: PropTypes.func.isRequired }
//8 Kata 10/3/20 //given a boolean if true return "Yes" string if false return "No" function boolToWord(bool) { return bool ? "Yes" : "No"; } ///// function boolToWord(bool) { if (bool) { return "Yes"; } else { return "No"; } } ///// let boolToWord = (bool) => (bool ? "Yes" : "No"); ///// var boolToWord = function boolToWord() { //compile var result = compile(Array.prototype.slice.call(arguments, 0)[0]); //finish return result; }; function compile(input) { var iterator = 0, input = input.toString(), output = []; for (; iterator < input.length; iterator++) { output[iterator] = input[iterator]; } switch (output.join("")) { case "true": return "Yes"; break; case "false": return "No"; break; case "maybe": return "Maybe"; break; default: throw new Error("Input was not recognized"); } }
SONO_ILO = { sonoj: {}, nunKanto: null, Komenco: function() { SONO_ILO.sonoj.bati = new Audio( "assets/bfxr_hit.wav" ); SONO_ILO.sonoj.bati.volume = 0.5; SONO_ILO.sonoj.bati.estasMuziko = false; SONO_ILO.sonoj.pasi = new Audio( "assets/bfxr_powerup.wav" ); SONO_ILO.sonoj.pasi.volume = 0.5; SONO_ILO.sonoj.bati.estasMuziko = false; SONO_ILO.sonoj.butono = new Audio( "assets/bfxr_button.wav" ); SONO_ILO.sonoj.butono.volume = 0.5; SONO_ILO.sonoj.butono.estasMuziko = false; SONO_ILO.sonoj.ludoMuziko = new Audio( "assets/Forest_tgfcoder.mp3" ); SONO_ILO.sonoj.ludoMuziko.volume = 0.5; SONO_ILO.sonoj.ludoMuziko.loop = true; SONO_ILO.sonoj.ludoMuziko.estasMuziko = true; SONO_ILO.sonoj.menuoMuziko = new Audio( "assets/HappyMenu_tgfcoder.mp3" ); SONO_ILO.sonoj.menuoMuziko.volume = 0.5; SONO_ILO.sonoj.menuoMuziko.loop = true; SONO_ILO.sonoj.menuoMuziko.estasMuziko = true; }, LudiSonon: function( titolo ) { if ( SONO_ILO.sonoj[ titolo ] != null ) { if ( SONO_ILO.sonoj[ titolo ].estasMuziko == false ) { SONO_ILO.sonoj[ titolo ].play(); } } }, LudiMuzikon: function( titolo ) { if ( SONO_ILO.sonoj[ titolo ] != null ) { if ( SONO_ILO.sonoj[ titolo ].estasMuziko && SONO_ILO.nunKanto != titolo ) { SONO_ILO.nunKanto = titolo; SONO_ILO.HaltuMuzikon(); SONO_ILO.sonoj[ titolo ].play(); } } }, HaltuMuzikon: function() { for ( var i in SONO_ILO.sonoj ) { // Stop it if this is an Audio item if ( SONO_ILO.sonoj[ i ].estasMuziko ) { SONO_ILO.sonoj[ i ].pause(); SONO_ILO.nunKanto = null; } } } };
export const DESCRIPTION = 'Представленные ниже утверждения используются профессиональными спортсменами при описании их переживаний. Пожалуйста, внимательно прочитайте каждое утверждение и оцените, как часто у вас бывает тот же опыт. Неправильных ответов здесь нет. Не задерживайтесь долго на одном утверждении. Пожалуйста, выберите ответ, который соответствует тому, как часто в спорте вы сталкиваетесь с подобными переживаниями.'; export const OPTIONS = [ { id: 0, title: 'Редко', value: 0 }, { id: 1, title: 'Иногда', value: 1 }, { id: 2, title: 'Часто', value: 2 }, { id: 3, title: 'Почти всегда', value: 3 } ]; export const QUESTIONS = [ { id: 0, title: 'Ежедневно или еженедельно я ставлю строго определенные цели, которые направляют меня в моих делах.' }, { id: 1, title: 'Я в полной мере использую свои способности и навыки.' }, { id: 2, title: 'Когда тренер делает мне замечание, я обычно анализирую это и следую его рекомендациям.' }, { id: 3, title: 'Занимаясь спортом, я могу сфокусировать внимание и не обращать внимания на отвлекающие моменты.' }, { id: 4, title: 'Во время соревнований я остаюсь позитивным (-ой) и сохраняю энтузиазм, вне зависимости от того, насколько плохо идут дела.' }, { id: 5, title: 'Обычно, испытывая психологическое давление, я выступаю лучше, потому что это позволяет мне мыслить более хладнокровно.' }, { id: 6, title: 'Я слегка переживаю о том, что думают другие о моем выступлении.' }, { id: 7, title: 'Обычно я стараюсь тщательно планировать шаги к достижению своих целей.' }, { id: 8, title: 'Я уверен (-а) в том, что покажу хороший результат.' }, { id: 9, title: 'Критика тренера расстраивает меня, но всегда помогает.' }, { id: 10, title: 'Мне с легкостью удаётся не давать отвлекающим мыслям мешать мне воспринимать то, что я смотрю или слушаю.' }, { id: 11, title: 'Мое напряжение в основном связано с тем, что я волнуюсь, как я выступлю.' }, { id: 12, title: 'Я устанавливаю собственные определенные цели для каждой тренировки.' }, { id: 13, title: 'Меня не нужно заставлять выкладываться на тренировках, я и без этого усердно работаю.' }, { id: 14, title: 'Если мой тренер критикует или кричит на меня, я исправляю ошибку, не расстраиваясь из-за его реакции.' }, { id: 15, title: 'В спорте я хорошо справляюсь с непредвиденными ситуациями.' }, { id: 16, title: 'Когда у меня что-то плохо получается, я говорю себе: сохраняй спокойствие! – и мне это помогает.' }, { id: 17, title: 'Чем сильнее напряжение во время соревнований, тем больше мне это нравится.' }, { id: 18, title: 'На соревнованиях я переживаю из-за того, что мне придется преодолевать последствия своих ошибок или провалов.' }, { id: 19, title: 'Задолго до того, как начинаются соревнования, у меня в голове уже есть собственный выработанный план действий.' }, { id: 20, title: 'Когда я чувствую, что слишком напряжен (-а), я могу быстро расслабить мышцы и успокоиться.' }, { id: 21, title: 'Для меня стрессовые ситуации – это вызов, который я принимаю.' }, { id: 22, title: 'Я обдумываю и представляю себе, что случится, если я проиграю или допущу ошибку.' }, { id: 23, title: 'Я контролирую свои эмоции, как бы ни складывались обстоятельства.' }, { id: 24, title: 'Для меня не составляет труда концентрировать свое внимание на каком-то одном предмете или человеке.' }, { id: 25, title: 'Когда у меня не получается достичь своих целей, это заставляет меня пробовать снова, прилагая еще больше усилий.' }, { id: 26, title: 'Следуя советам тренера, я обычно совершенствую свои навыки.' }, { id: 27, title: 'Я делаю меньше ошибок в условиях стресса, ведь так я лучше концентрируюсь.' } ]; export const COPING_STRATEGIES_SAVE_INTERPRETATION = `athleteTests/CopingStrategiesQuiz/COPING_STRATEGIES_SAVE_INTERPRETATION`; export const COPING_STRATEGIES_SAVE_INTERPRETATION_ERROR = `athleteTests/CopingStrategiesQuiz/COPING_STRATEGIES_SAVE_INTERPRETATION_ERROR`; export const COPING_STRATEGIES_SAVE_INTERPRETATION_SUCCESS = `athleteTests/CopingStrategiesQuiz/COPING_STRATEGIES_SAVE_INTERPRETATION_SUCCESS`;
export default [ 'grid-cell', 'grid-cell cyan', 'grid-cell blue', 'grid-cell orange', 'grid-cell yellow', 'grid-cell green', 'grid-cell pink', 'grid-cell red', ];
import axios from 'axios' var myaixos = {} myaixos.install = function (Vue) { axios.defaults.baseURL = 'http://cangdu.org:8001/' axios.defaults.withCredentials = true // 请求后带上cookie axios.interceptors.request.use(function (config) { return config }) Vue.prototype.$http = axios } export default myaixos
'use strict'; var objectUtils = require('../utils/common-utils/object-utils'), boardUtils = require('../utils/chess-utils/board-utils'), Color = require('./color'), Move = require('./move'), pieces = require('./pieces'), arrayUtils = require('../utils/common-utils/array-utils'), isPieceMixin = require('./is-piece-mixin'); function createPieceConstructors(pieces) { return objectUtils.map(pieces, function (piecePrototype) { var PieceConstructor = objectUtils.inherit(function () { this.super.constructor.apply(this, arguments); }, Piece); objectUtils.extend(PieceConstructor.prototype, piecePrototype); return PieceConstructor; }); } var constructors = createPieceConstructors(pieces); function Piece(color, square) { this.color = color; this.square = square; square.piece = this; } Piece.create = function (fenToken, square) { var pieceToken = fenToken.toLowerCase(), color = Color.getByFlag(pieceToken !== fenToken), PieceConstructor = constructors[pieceToken]; return new PieceConstructor(color, square); }; var piecePrototype = { getFenToken: function () { var fenToken = this.token; if (this.color.isWhite()) { fenToken = fenToken.toUpperCase(); } return fenToken; }, /* * This implemetation use by rook, bishop and queen. * For pawn, knight and king used implementation placed in corresonding module */ forEachTargetSquare: function (callback) { var self = this; this.offsets.forEach(function (offset) { var targetSquareIndex = self.square.index + offset, targetSquare; while (boardUtils.isSquareOnBoard(targetSquareIndex)) { targetSquare = self.square.chess.squares[targetSquareIndex]; if (targetSquare.isOccupied()) { if (targetSquare.piece.color !== self.color) { callback.call(self, targetSquare); } return; } callback.call(self, targetSquare); targetSquareIndex += offset; } }); }, forEachTargetSquareName: function (callback) { this.forEachTargetSquare(function (targetSquare) { var targetSquareName = targetSquare.getName(); callback.call(this, targetSquareName); }); }, calculateMoveCount: function () { var moveCount = 0; this.forEachTargetSquare(function () { ++moveCount; }); return moveCount; }, mapTargetSquares: function (callback) { var results = []; this.forEachTargetSquare(function (targetSquare) { var result = callback.call(this, targetSquare); results.push(result); }); return results; }, generateTargetSquareNames: function () { return this.mapTargetSquares(function (square) { return square.getName(); }); }, generateMoves: function () { return this.mapTargetSquares(function (square) { return this.createMove(square); }); }, generateSanMoves: function () { return this.mapTargetSquares(function (targetSquare) { var move = this.createMove(targetSquare); return move.toSAN(); }); }, move: function (squareName) { var square = this.square.chess.getSquareByName(squareName), move = this.createMove(square); move.execute(); }, createMove: function (targetSquare) { return new Move(this, targetSquare); }, remove: function () { var playerPieces = this.square.chess.pieces[this.color.name]; delete this.square.piece; // TODO throw error if piece already removed ? arrayUtils.remove(playerPieces, this); } }; objectUtils.extend(Piece.prototype, piecePrototype, isPieceMixin); module.exports = Piece;
import axios from "axios"; import { useEffect, useState } from "react"; import { useParams } from "react-router-dom"; import BlogCard from "../components/BlogCard"; import Header from "../components/Header"; import { allCategoriesPath } from "../constants/endpoints"; import { capitalise } from "../constants/functions"; const CategoryPage = () => { const { categoryName } = useParams(); const [categoryPosts, setCategoryPosts] = useState([]); const getIndividualCategory = async () => { try { const response = await axios.get(`${process.env.REACT_APP_BACKEND_URL}${allCategoriesPath}${categoryName}`); setCategoryPosts(response.data.blogentries); } catch (err) { console.log(err.response); } }; useEffect(() => { getIndividualCategory(); }, [categoryName]); return ( <> <Header header={capitalise(categoryName)} /> <main className="container"> <div className="row mb-2"> {categoryPosts[0] ? ( categoryPosts.map((post) => { return <BlogCard {...post} key={post.id} />; }) ) : ( <h1 className="display-4 fst-italic">No Posts Yet...</h1> )} </div> </main> </> ); }; export default CategoryPage;
const pino = require("./pino") let bytesReceived = 0 let initTime = Date.now() let addBytes = bytes => { pino.trace("bandwidthMonitor.addBytes +%dB. Now %dkB",bytes,Math.round(bytesReceived / 1000)) bytesReceived += bytes } let startNewCycle = () => { let now = Date.now() let elapsedSeconds = (now - initTime) / 1000 let kBPerSecond = (bytesReceived / 1000 / elapsedSeconds).toFixed(2) pino.info("bandwidthMonitor.startNewCycle average bandwidth during last cycle was %dkB/s",kBPerSecond) initTime = now bytesReceived = 0 } module.exports = { addBytes, startNewCycle }
import {Component} from "react"; import Parser from 'html-react-parser'; import Chip from '@material-ui/core/Chip'; import Button from '@material-ui/core/Button'; import blue from '@material-ui/core/colors/blue'; import red from '@material-ui/core/colors/red'; import green from '@material-ui/core/colors/green'; import deepOrange from '@material-ui/core/colors/deepOrange'; import { createMuiTheme } from '@material-ui/core/styles'; import toastr from "toastr"; /* cms_common.js isSameTimezone toTzDate getTimezoneLabel getTimezone _l loadAppsViewScript */ const dateToString = function (date, hour, minute, showTime){ var strYear = date.getFullYear(); var strMonth = ("00" + (date.getMonth() + 1)).slice(-2); var strDate = ("00" + date.getDate()).slice(-2); var strHour = ("00" + date.getHours()).slice(-2); var strMimute = ("00" + date.getMinutes()).slice(-2); var result = strYear + "/" + strMonth + "/" + strDate; if(showTime){ strHour = ("00" + hour).slice(-2); strMimute = ("00" + minute).slice(-2); result += " " + strHour + ":" + strMimute; } return result; } const createStringFromDateAndRange = function(baseTime, range){ if(baseTime == null){ baseTime = new Date(); } baseTime = toTzDate().year(baseTime.getFullYear()).month(baseTime.getMonth()).date(baseTime.getDate()).hour(0).minutes(0).second(0).millisecond(0); let timeRange = range.split(' '); var startTime = toTzDate(baseTime); var endTime = toTzDate(baseTime); if(timeRange[1] == 'month'){ startTime.add(0-parseInt(timeRange[0]), 'months'); endTime.add(parseInt(timeRange[0]), 'months'); }else if(timeRange[1] == 'day'){ startTime.add(0-parseInt(timeRange[0]), 'days'); endTime.add(parseInt(timeRange[0]), 'days'); } startTime = startTime.valueOf(); endTime = endTime.valueOf() + (24*3600-1)*1000; return {startTime: startTime, endTime: endTime}; } const fetchJsonData = function(url, method, data, success, fail){ var meta = {method: method, headers: {'Content-Type': 'application/json', cache: "no-cache"}} if(method === "POST"){ meta['body'] = data; }else{ url += '?' + data + '&_='+Math.random(); } fetch(url, meta).then(response => { if (response.status != "200") { return {error: true, data: response}; } else { return {error: false, data: response.json()}; } }).then(json => { if(json.error === true) { if(fail){ fail(json.data); } }else{ return json.data; } }).then(data => { if(success) { success(data); } }); } const fetchCommonData = function(url, method, data, success, fail){ var meta = {method: method, headers: {'Content-Type': 'application/json', cache: "no-cache"}} if(method === "POST"){ meta['body'] = data; }else{ url += '?' + data + '&_='+Math.random(); } fetch(url, meta).then(response => { if (response.status != "200") { return {error: true, data: response}; } else { return {error: false, data: response.text()}; } }).then(json => { if(json.error === true) { if(fail){ fail(json.data); } }else{ return json.data; } }).then(data => { if(success) { success(data); } }); } const CustomTheme = createMuiTheme({ typography: { useNextVariants: true, }, palette: { primary: { main: blue[600], light: blue[100], }, secondary: { main: green[600], }, error: { main: red[500], }, thirdcolor: { light: red[300], main: red[600], dark: red[700], contrastText: "#FFFFFF", } }, overrides:{ MuiTypography: { h6:{ fontSize: "18px", }, }, } }); const CustomTheme2 = createMuiTheme({ typography: { useNextVariants: true, }, palette: { primary: { main: blue[600], }, secondary: { main: red[500], }, } }); const calendarTheme = createMuiTheme({ typography: { useNextVariants: true, }, palette: { primary: { main: blue[600], }, secondary: { main: red[500], }, }, overrides: { MuiPickerDTHeader: { hourMinuteLabel: { flexDirection: 'row', } }, MuiTypography: { body1: { fontSize: "14px", }, caption:{ fontSize: "14px", }, subtitle1:{ fontSize: "20px", }, h4:{ fontSize: "24px", }, }, MuiPickersToolbarButton:{ toolbarBtn:{ paddingTop: "10px", } }, MuiIconButton:{ label:{ fontSize: "14px", } }, MuiIcon:{ root:{ fontSize: "18px", } }, MuiButton:{ label:{ fontSize: "14px", }, }, MuiInput:{ input:{ paddingLeft: "0px", }, }, MuiPickersYear:{ selected:{ fontSize: "24px", } }, MuiPickersDay: { selected: { backgroundColor: blue['600'], color: "white", }, current: { backgroundColor: red['500'], color: "white", }, }, weekEndDay: { backgroundColor: deepOrange['200'], color: red['500'], }, }, }); class ThirdColorButton extends Component { constructor(props){ super(props); this.state = { bkColor: CustomTheme.palette.thirdcolor.main, textColor: CustomTheme.palette.thirdcolor.contrastText, }; } render(){ const {showHTML, style, ...rest} = this.props; const {bkColor, textColor} = this.state; return ( <Button variant="contained" {...rest} onMouseOver={()=>{this.setState({bkColor: CustomTheme.palette.thirdcolor.dark})}} onMouseOut ={()=>{this.setState({bkColor: CustomTheme.palette.thirdcolor.main})}} style={{backgroundColor: bkColor, color: textColor, ...style}}> {showHTML} </Button> ); } } class TagIcon extends Component{ render(){ const {text, className, ...rest} = this.props; return( <span className={"tagIcon " + className} {...rest}>{text}</span> ); } } const getAlertMessage = function(response){ if (!response.status) { // FileUploadの場合、iframeのbodyが取得できない場合 return {type: "text", msg: _l('%em_error%')}; }else if (response.status == -1) { return {type: "text", msg: _l('%em_time_out%') + '\n' + _l('%m_once_again%')}; }else if (response.status == 301) { var href = response.getResponseHeader['Location'] || response.getResponseHeader['location']; if(typeof response.getResponseHeader === "function"){ href = response.getResponseHeader('Location'); } return{type: "text", msg: _l('%m_error_session_re_login%'), href: href}; }else if (response.status == 409) { return {type: "text", msg : response.responseText}; }else if (response.status == 404){ return {type: "text", msg : response.statusText}; }else{ var retObj = {}; var href = response.getResponseHeader['Location'] || response.getResponseHeader['location']; var contentType = response.getResponseHeader['Content-Type'] || response.getResponseHeader['content-type']; if(typeof response.getResponseHeader === "function"){ href = response.getResponseHeader('Location'); contentType = response.getResponseHeader('Content-Type'); } if(contentType && contentType.startsWith("text/html")){ retObj.type = "text"; retObj.msg = response.responseText; }else{ retObj.type = "html"; var parts = response.responseText.split(":"); retObj.title = parts.shift(); retObj.msg = Parser('<div class="dialog-msg">' + (parts.join(":") || "") + '</div>'); } if(response.status== 200 || href == ""){ href = "/error"; } retObj[href] = href; return retObj; } } class SelectedItem extends Component { constructor(props){ super(props); this.inputKeyUp = this.inputKeyUp.bind(this); this.changeInputWidth = this.changeInputWidth.bind(this); this.lostFocus = this.lostFocus.bind(this); this.savePreviousValue = this.savePreviousValue.bind(this); this.state = {inputWidth: "12px"}; } inputKeyUp(event){ const {listParent} = this.props; if(event.keyCode == 40){ //down key if(listParent.state.showmenu){ listParent.moveMenuItemFocus(1); }else{ listParent.showPopupMenu(event); } }else if(event.keyCode == 38){ //up key listParent.moveMenuItemFocus(-1); }else if(event.keyCode == 13){ //enter key listParent.onInputEnterKey(); }else if(event.keyCode == 8){ //back key if(event.target.value === ""){ this.setState({inputWidth: "12px"}); } if(this.props.oldValue === ""){ listParent.removeLastOneSelectedItem(); } listParent.showPopupMenu(event); }else{ listParent.showPopupMenu(event); } listParent.filterPopupMenu(event.target.value); } changeInputWidth(event){ var width = event.target.parentElement.parentElement.offsetWidth - event.target.offsetLeft; if(event.target.scrollLeft > 0 && event.target.selectionStart !== 1){ width = event.target.parentElement.parentElement.offsetWidth; } this.setState({inputWidth: width}); } lostFocus(){ const {listParent} = this.props; listParent.textInput.value = ""; this.setState({inputWidth: "12px"}); listParent.filterPopupMenu(""); listParent.setState({inputFocus: false}); } savePreviousValue(event){ this.props.oldValue = event.target.value; } render(){ const {itemKey, items1, items2, listParent, placeholder, isLastItem} = this.props; const appendStyle = {float: "left", listStyle:"none"} var element = ""; if(isLastItem){ var text = ""; element = ( <li className="show-menu-flag" style={appendStyle}> <input className={"show-menu-flag taglist-input "} placeholder={text} ref={(input) => { listParent.textInput = input; }} autoComplete="off" autoCorrect="off" autoCapitalize="off" spellCheck="false" style={{width: this.state.inputWidth, marginTop: "5px", marginLeft:"0px"}} autoFocus={false} onKeyUp={this.inputKeyUp} onChange={this.changeInputWidth} onKeyDown={this.savePreviousValue} onBlur={this.lostFocus}></input> </li> ) }else{ var itemText = ""; var itemFill = ""; if(items2 && items2[itemKey]){ itemText = items2[itemKey]; }else{1 itemText = items1[itemKey]; itemFill = "outlined"; } element = ( <li style={{paddingLeft: "2px", ...appendStyle}}> <Chip label={itemText} onDelete={()=>{listParent.removeSelectedItem(itemKey)}} style={{height: "24px", marginBottom: "4px"}} color="primary" variant={itemFill} /> </li> ) } return element; } } class CustomSelectComponent extends Component { constructor(props){ super(props); this.showPopupMenu = this.showPopupMenu.bind(this); this.removeSelectedItem = this.removeSelectedItem.bind(this); this.filterPopupMenu = this.filterPopupMenu.bind(this); this.removeLastOneSelectedItem = this.removeLastOneSelectedItem.bind(this); this.moveMenuItemFocus = this.moveMenuItemFocus.bind(this); this.onInputEnterKey = this.onInputEnterKey.bind(this); this.continueMouse = this.continueMouse.bind(this); this.setInputFocus = this.setInputFocus.bind(this); this.state = { showmenu: false, filter: "", itemFocusIndex: 0, isMouseVisible:true, inputFocus: false, selectedItems: [] } } setInputFocus(){ setTimeout(()=>{ this.textInput.focus(); this.setState({inputFocus: true}); }, 20); } showPopupMenu(event){ if(event.target.className.indexOf('show-menu-flag') !== -1){ this.state.showmenu = true; this.setInputFocus(); } } onInputEnterKey(){ const {items1, items2, onChange} = this.props; const {showmenu, selectedItems, itemFocusIndex} = this.state; if(showmenu){ var index = itemFocusIndex; const {leftItems1, leftItems2} = this.extractLeftItems(items1, items2); const leftItems1Count = Object.keys(leftItems1).length; const leftItems2Count = Object.keys(leftItems2).length; if(leftItems2Count + leftItems1Count > 0){ if(index < leftItems1Count){ //in the range of Users var keyword = ""; Object.keys(leftItems1).forEach((key, id)=>{ if(index === id){ keyword = key; } }); var value = [...selectedItems, keyword]; }else{ //in the range of Team index -= leftItems1Count; var keyword = ""; Object.keys(leftItems2).forEach((key, id)=>{ if(index === id){ keyword = key; } }); var value = [...selectedItems, keyword]; } if(onChange && this.state.selectedItems != value){ onChange(value); } this.state.selectedItems = value; } this.state.itemFocusIndex = 0; this.state.showmenu = false; this.textInput.value = ""; this.setInputFocus(); } } closePopuMenu(event){ const {selectedItems} = this.state; const {onChange} = this.props; this.state.showmenu = false; if(event && event !== "null"){ var value = [...selectedItems, event]; if(onChange && selectedItems != value){ onChange(value); } this.state.selectedItems = value; this.setInputFocus(); } this.setState({itemFocusIndex: 0}); } removeSelectedItem(selectedId){ const {selectedItems} = this.state; const {onChange} = this.props; var index = selectedItems.indexOf(selectedId); selectedItems.splice(index, 1); if(onChange){ onChange(selectedItems); } this.state.selectedItems = selectedItems; this.setInputFocus(); } filterPopupMenu(filterData){ const {filter} = this.state; if(filterData !== filter){ this.setState({filter: filterData}); } } removeLastOneSelectedItem(){ const {selectedItems} = this.state; const {onChange} = this.props; var data = selectedItems; data.pop(); if(onChange){ onChange(data); } this.state.selectedItems = data; this.setInputFocus(); } moveMenuItemFocus(step){ const {items1, items2} = this.props; const {itemFocusIndex} = this.state; const {leftItems1, leftItems2} = this.extractLeftItems(items1, items2); const showItemsCount = Object.keys(leftItems1).length + Object.keys(leftItems2).length; if(itemFocusIndex + step < 0){ return; }else if(itemFocusIndex + step >= showItemsCount){ return; } this.setState({itemFocusIndex: itemFocusIndex+step, isMouseVisible:false}); this.refs["popup-menu"].refs["menu-item-"+(itemFocusIndex+step)].refs['menu-item'].scrollIntoView({block: 'nearest', behavior: 'smooth'}); } continueMouse(){ const {isMouseVisible} = this.state; if(!isMouseVisible){ this.setState({isMouseVisible:true}); } } changeMenuItemFocusByMouse(index){ const {isMouseVisible} = this.state; if(isMouseVisible) { this.setState({itemFocusIndex: index}); } } extractLeftItems(items1, items2){ const {selectedItems, filter} = this.state; var leftItems1 = Object.assign({}, items1); var leftItems2 = Object.assign({}, items2); Object.keys(selectedItems).forEach((key)=>{ if(leftItems2 && leftItems2[selectedItems[key]]){ delete leftItems2[selectedItems[key]]; }else{ delete leftItems1[selectedItems[key]]; } }); if(filter !== ""){ Object.keys(leftItems1).forEach((key) => { if(leftItems1[key].indexOf(filter) === -1){ delete leftItems1[key]; } }) Object.keys(leftItems2).forEach((key) => { if(leftItems2[key].indexOf(filter) === -1){ delete leftItems2[key]; } }) } return {leftItems1: leftItems1, leftItems2:leftItems2}; } render(){ const {items1, items2, className, errorCheck, placeholder, style, labelClassName} = this.props; const {showmenu, itemFocusIndex, inputFocus, selectedItems} = this.state; var menuFrame = ""; if(showmenu){ var isGroup = (items2 !== undefined); const {leftItems1, leftItems2} = this.extractLeftItems(items1, items2); if(isGroup){ menuFrame = <PopupMenu ref={"popup-menu"} items={leftItems1} items2={leftItems2} listParent={this} isGroupMode={true} focusIndex={itemFocusIndex}/> }else{ menuFrame = <PopupMenu ref={"popup-menu"} items={leftItems1} listParent={this} isGroupMode={false} focusIndex={itemFocusIndex}/> } } var buttonTags = []; Object.keys(selectedItems).forEach((itemId) => { buttonTags.push(<SelectedItem key={itemId} itemKey={selectedItems[itemId]} items1={items1} items2={items2} listParent={this} />); }); buttonTags.push(<SelectedItem key={"last"} isLastItem={true} placeholder={placeholder} listParent={this}/>); var errorDivColor = {}; var errorMark =""; var labelClass = "taglist-label "; var labelColor = ""; var divClass = "taglist show-menu-flag select2-container select2-container-multi "; if(selectedItems.length === 0 && errorCheck){ errorMark = <div className={"error-mark-inline "} style={{paddingTop: "12px"}}><i className="icon-warning-sign"></i></div> errorDivColor = {borderBottom: "solid 2px "+ CustomTheme.palette.error.main}; labelColor = CustomTheme.palette.error.main; } if(showmenu || selectedItems.length > 0){ labelClass += "taglist-label-over"; }else{ labelClass += labelClassName + " show-menu-flag"; } if(inputFocus){ divClass += "taglist-over "; } return( <div className={divClass + className} onClick={this.showPopupMenu} style={{...style, ...errorDivColor}}> <label className={labelClass} style={{color: labelColor}}>{placeholder}</label> <ul className={"select2-choices show-menu-flag"} style={{border: "none", marginTop:"10px"}}> {buttonTags} </ul> {menuFrame} {errorMark} </div> ); } } class MenuItem extends Component{ constructor(props){ super(props); } render(){ const {isCategory, keyword, text, isFocus, index, listParent} = this.props; var divStyle= {pointerEvents: "none"}; var spanStyle = {marginRight: '5px', fontWeight: "bold"}; var title = ""; var strClass = "no-click"; if(!isCategory){ divStyle = {backgroundColor: "white"}; if(isFocus){ divStyle = {backgroundColor: "#fcfce2"}; } spanStyle = {marginLeft: "20px", marginRight: '5px'}; title = "menuItem-" + keyword; strClass = "menu-item"; } return( <div className="div-menu-item" ref={"menu-item"} id={"item-"+index} title={title} style={divStyle} onMouseOver={()=>{listParent.changeMenuItemFocusByMouse(index)}} onMouseMove={listParent ? listParent.continueMouse : null}> <span className={strClass} title={title} style={spanStyle}>{text}</span> </div> ); } } class PopupMenu extends Component { constructor(props){ super(props); this.onClickEvent = this.onClickEvent.bind(this); } componentDidMount(){ document.addEventListener('mousedown', this.onClickEvent); } componentWillUnmount(){ document.removeEventListener('mousedown', this.onClickEvent); } onClickEvent(event){ const {listParent} = this.props; if(event.target.className == "no-click" || event.target.className == "popup-menu-show"){ return; }else if(event.target.className.indexOf('div-menu-item') != -1 || event.target.className.indexOf('menu-item') != -1){ listParent.closePopuMenu(event.target.title.replace('menuItem-', '')); }else{ listParent.closePopuMenu(null); } } render(){ var {items, items2, focusIndex, isGroupMode, listParent} = this.props; let menuItems = []; if(isGroupMode && Object.keys(items).length != 0){//show menu by group format menuItems.push(<MenuItem isCategory={true} text={"Users"} />); } var index = -1; Object.keys(items).forEach((key) => { index ++; var isFocus = index===focusIndex; menuItems.push(<MenuItem key={key} ref={"menu-item-"+index} isCategory={false} keyword={key} text={items[key]} isFocus={isFocus} listParent={listParent} index={index}/>); }); if(isGroupMode && Object.keys(items2).length != 0){ //team data menuItems.push(<MenuItem isCategory={true} text={"Team"}/>); Object.keys(items2).forEach(subIndex => { index ++; var isFocus = index===focusIndex; menuItems.push(<MenuItem key={key} ref={"menu-item-"+index} isCategory={false} keyword={subIndex} text={items2[subIndex]} isFocus={isFocus} listParent={listParent} index={index}/>); }); } if(menuItems.length == 0){ menuItems.push( <div className="div-menu-item" title={"menuItem-null"}> <span title={"menuItem-null"} style={{marginLeft: "20px", marginRight: '5px'}}>{_l("%em_no_matches_found%")}</span> </div> ) } return( <div> <div className={"popup-menu-show"} style={{width: "100%", overflow: "auto", maxHeight: "200px", marginTop: "4px"}}> {menuItems} </div> </div> ); } } function findChildComponentById(currentNode, idName){ var result = null; if(currentNode.props){ if(currentNode.props.id === idName){ result = currentNode; }else if(currentNode.props.children && (currentNode.props.children instanceof Array)){ for(var i=0; i<currentNode.props.children.length; i++){ result = findChildComponentById(currentNode.props.children[i], idName); if(result){ break; } } }else if(currentNode.props.children && (currentNode.props.children instanceof Object)){ result = findChildComponentById(currentNode.props.children, idName); } } return result; } function findChildComponentByClassName(currentNode, className){ if(!className || className.length ===0){ return null; } var result = null; if(currentNode.props){ var curClassName = currentNode.props.className; var count = 0; if(curClassName){ curClassName = curClassName.split(' '); className.forEach(item=>{ if(curClassName.indexOf(item) !== -1){ count ++; } }) } if(count === className.length){ result = currentNode; }else if(currentNode.props.children && (currentNode.props.children instanceof Array)){ for(var i=0; i<currentNode.props.children.length; i++){ result = findChildComponentByClassName(currentNode.props.children[i], className); if(result){ break; } } }else if(currentNode.props.children && (currentNode.props.children instanceof Object)){ result = findChildComponentByClassName(currentNode.props.children, className); } } return result; } function showToastInformation(type, msg){ toastr.options = {"showDuration": 1000, "hideDuration": 1000, "timeOut": 2000}; switch (type){ case "ok": toastr.success(msg, ""); break; case "error": toastr.error(msg, ""); break; case "info": toastr.info(msg, ""); break; case "warning": toastr.warning(msg, ""); break; } } export {dateToString,createStringFromDateAndRange,fetchJsonData,fetchCommonData, CustomTheme,CustomTheme2,calendarTheme,ThirdColorButton,TagIcon,getAlertMessage,CustomSelectComponent, findChildComponentById, findChildComponentByClassName, showToastInformation};
import Ember from 'ember'; const computed = Ember.computed; export default Ember.Service.extend({ filteredList: {}, userDetails: [], emailList: computed.filter('userDetails', function(detail) { return detail.get('detailType') === 'email' && !detail.get('isDeleted'); }), phoneNumberList: computed.filter('userDetails', function(detail) { return detail.get('detailType') === 'phone_number' && !detail.get('isDeleted'); }), dobList: computed.filter('userDetails', function(detail) { return detail.get('detailType') === 'birthday' && !detail.get('isDeleted'); }), addressList: computed.filter('userDetails', function(detail) { return detail.get('detailType') === 'address' && !detail.get('isDeleted'); }), urlList: computed.filter('userDetails', function(detail) { return detail.get('detailType') === 'url' && !detail.get('isDeleted'); }), socialHandleList: computed.filter('userDetails', function(detail) { return detail.get('detailType') === 'social_handle' && !detail.get('isDeleted'); }), noteList: computed.filter('userDetails', function(detail) { return detail.get('detailType') === 'note' && !detail.get('isDeleted'); }), datesList: computed.filter('userDetails', function(detail) { return detail.get('detailType') === 'date' && !detail.get('isDeleted'); }), nicknameList: computed.filter('userDetails', function(detail) { return detail.get('detailType') === 'nickname' && !detail.get('isDeleted'); }), companyList: computed.filter('userDetails', function(detail) { return detail.get('detailType') === 'company' && !detail.get('isDeleted'); }), setProfile(profile) { this.set('profile', profile); this.set('userDetails', this.get('profile.userDetails')); } });
const jwt = require('jsonwebtoken'); const moment = require('moment'); let secret = '/#escom/#2019/#key/#secret/#token' exports.createToken = function(user) { let payload ={ sub: user._id, name: user.name, username: user.username, email: user.email, role: user.role, avatar: user.avatar, // iat: moment().unix(), // exp: moment().add(30, 'days').unix() } return jwt.sign(payload, secret) }
import React, { useState} from 'react'; import logo from './logo.svg'; import './App.css'; import data from '../../data.json'; const Members = () => { const [people, setPeople] = useState(data); const [likedUsers, setLikedUsers] = useState([]); const [superLikedUsers, setSuperLikedUsers] = useState([]); const [dislikeUsers, setDislikedUsers] = useState([]); const activeUser = 0; const modifySuperficialChoices = (userId, action) => { const newPeople = [...person]; const newLikedUsers = [...likedUsers]; const newSuperLikedUsers = [...superLikedUsers]; const newDislikedUsers = [...dislikedUsers]; } switch (action) { case 'ADD_TO _LIKED_USERS': if (!people[activeUser].likedUsers.includes(userid)) { newPeople[activeUser].likedUsers.push(userId); setLikedUsers(newLikedUsers); setPeople(removedPersonFromDataSrc(people, userId)); } break; case 'ADD_TO _DISLIKED_USERS': if (!people[activeUser].dislikedUsers.includes(userid)) { newPeople[activeUser].dislikedUsers.push(userId); dislikedUsers(newDislikedUsers); setPeople(removedPersonFromDataSrc(people, userId)); } break; case 'ADD_TO _SUPERLIKED_USERS': if (!people[activeUser].superLikedUsers.includes(userid)) { newPeople[activeUser].supeLikedUsers.push(userId); superLikedUsers(newSuperLikedUsers); setPeople(removedPersonFromDataSrc(people, userId)); } break; } return ( <div className="members"> <Header /> {people[1] ? ( <Person key={person[1].id} person={people[1]} modifySuperficialChoices={modifySuperficialChoices} likedUsers={likedUsers} /> ): ( <Lonely activeUserImage={people[activeUser].image} likedUsers={likedUsers} superLikedUsers={superLikedUsers} /> )} </div> ) } export default Members;
'use strict'; angular.module('pageCalcs') .controller('ctrlCalcs', [ '$scope', ($s) => { angular.element('[ng-view]').attr('ng-view', 'page-calcs') Number.isNumeric=function(n){return !Number.isNaN(Number.parseFloat(n))&&isFinite(n)}; Number.isFinite=Number.isFinite||function(n){return typeof n==='number'&&isFinite(n)}; String.prototype.padLeft = function (p) { return String(p + this).slice(-p.length); }; String.prototype.padRight = function (p) { return String(this + p).slice(0, p.length); }; Math.round10 = function(v,e) { if (typeof e === 'undefined' || +e === 0) return Math.round(v) v = +v e = +e if (Number.isNaN(v) || !Number.isInteger(e)) return NaN v = v.toString().split('e') v = Math.round(+(v[0]+'e'+(v[1]?(+v[1]-e):-e))) v = v.toString().split('e') v = (+(v[0]+'e'+(v[1]?(+v[1]+e):e))+'').split('.') return v[0] + '.' + (v.length > 1 ? v[1].padRight('00') : '00') }; Number.Currency=Number.Currency||{}; Number.Percent=Number.Percent||{}; String.toFloat = function(n) { if (typeof n == 'string') { if (!Number.isNumeric(n)) return '&empty;' n = +n } if (Number.isNaN(n)) return '&empty;' if (!Number.isFinite(n)) return '&infin;' return n } Number.Currency.format = function(n) { n = String.toFloat(n) return typeof n == 'number' ? '$' + Math.round10(n, -2) : n }; Number.Percent.format = function(n) { n = String.toFloat(n) return typeof n == 'number' ? Math.round10(n * 100, -2) + '%' : n }; Date.intMon = function(n) { n = String.toFloat(n) return typeof n == 'number' ? Math.ceil(n) + ' months' : n }; // Uniform Calculator Input Validation and Calculation Start $(document).on('input', 'input,select', function(e) { let _t = $(this) if (_t.attr('type') == 'number' && !Number.isNumeric(_t.val())) { $(e.target).parents('section').find('output').html('&#x26a0;') return false } $(e.target).parents('section').trigger({ target:e.target, type:'calc' }) // Uniform Event Fire }).on('click', '[data-action]', function(e) { $(e.target).parents('section').trigger({ calc: $(e.target).closest('section'), type:$(e.target).attr('data-action'), target:e.target }) }) // Uniform Calculator Resource Gathering $('section').on('calc', function(e) { e.calc = $(e.target).closest('section') e.$o = e.calc.find('output') e.out = [] }).on('save', function(e) { if (!e.calc.children('table').length) return e.$o = e.calc.find('output') }) // Uniform Calculator Results Output $('section').on('output', function(e) { if (e.out.length && e.out.length <= e.$o.length) e.out.forEach(function(o, i) { let el = $(e.$o[i]) if (el.is('.money')) o = Number.Currency.format(o) else if (el.is('.months')) o = Date.intMon(o) else if (el.is('.percent')) o = Number.Percent.format(o) el.html(o) }) }) $('section.loan').on('calc', function(e) { let pmt = e.calc.find('input[name="payment"]').val() || 0, p = e.calc.find('input[name="principal"]').val() || 0, r = e.calc.find('input[name="interest"]').val() || 0, t = e.calc.find('input[name="period"]').val() || 0 r /= 1200 switch (e.calc.attr('id')) { case 'total': e.out.push(r * p * t / (1 - Math.pow(1 + r, -t))) e.out.unshift(e.out[0] - p) break; case 'monthly': if (r > 0) { e.out.push(r * p / (1 - Math.pow(1 + r, -t))) } else { e.out.push(p / t) } break; case 'period': if (!Number.isNumeric(r)) e.out.push('&empty;') else if (r !== 0) e.out.push((Math.log(pmt / p) - Math.log(pmt / p - r)) / Math.log(1 + r)) else e.out.push(p / pmt) break; } e.type = 'output' $(this).trigger(e) }).on('save', function(e){ let pmt = e.calc.find('input[name="payment"]').val() || 0, p = e.calc.find('input[name="principal"]').val() || 0, r = e.calc.find('input[name="interest"]').val() || 0, t = e.calc.find('input[name="period"]').val() || 0, row = $('<tr>') r /= 1200 switch (e.calc.attr('id')) { case 'total': row.append('<td>' + p) row.append('<td>' + $(e.$o[0]).val()) break; } if (row.children('td,th').length) $(e.calc.children('table')[0]).append(row).show() }) $('section.finance').on('calc', function(e) { let inf = e.calc.find('input[name="inflation"]').val() || 0, pmt = e.calc.find('input[name="payment"]').val() || 0, inc = e.calc.find('input[name="income"]').val() || 0, t = e.calc.find('input[name="period"]').val() || 0 inf /= 100 switch (e.calc.attr('id')) { case 'leverage': e.out.push(pmt * 12 / inc) e.$o.css('color', e.out[0] > 1/3 ? 'red' : 'black') break; case 'realreturn': e.out.push(inc / pmt / (1 + inf) - 1) break; case 'annuity': if (inf != 0) { e.out.push(pmt * (1 / inf - 1 / (inf * Math.pow(1 + inf, t)))) e.out.push(pmt * (Math.pow(1 + inf, t) - 1) / inf) } else { e.out.push(pmt * t) e.out.push(pmt * t) } break; } e.type = 'output' $(this).trigger(e) }) $('section.invest').on('calc', function(e) { let commission = e.calc.find('input[name="commission"]').val() || 0, sellPrice = e.calc.find('input[name="sell_price"]').val() || 0, buyPrice = e.calc.find('input[name="buy_price"]').val() || 0, shares = e.calc.find('input[name="shares"]').val() || 0, roi = e.calc.find('input[name="roi"]').val() || 0, totalBuy = 0 commission = Number.parseFloat(commission) buyPrice = Number.parseFloat(buyPrice) shares = Number.parseInt(shares, 10) roi = Number.parseFloat(roi) / 100 switch (e.calc.attr('id')) { case 'roi': totalBuy = buyPrice * shares + commission e.out.push(totalBuy) if (shares > 0) { sellPrice = (2 + roi) * totalBuy / shares } else { sellPrice = '&empty;' } e.out.push(sellPrice) break; } e.type = 'output' $(this).trigger(e) }) $('section, #ge, #le').each(function(){ $(this).trigger({ target:this, type:'calc' }) }) }])
var User = require('../models/user'); var ChatUList = require('../models/chatUsers'); var Chat = require('../models/chat'); var config = require('../../config'); var jsonwebtoken = require('jsonwebtoken'); var secretKey = config.secretKey; function createToken(user){ var token = jsonwebtoken.sign({ id: user._id, name: user.name, username: user.username, password: user.password }, secretKey,{ expiresInMinute: 1440 }); return token; } module.exports = function (app,express,io) { var api = express.Router(); api.post('/signup',function (req,res) { var user = new User({ name: req.body.name, username: req.body.username, password: req.body.password }); var token = createToken(user); user.save(function (err,user) { if(err){ res.send(err); console.error(err); return; } /*console.log(req.body.name); console.log(req.body.username); console.log(req.body.password); console.dir(user); */ res.json({success: true, message: 'User has been created',token: token,user: req.body.username}); }); }); api.get('/users',function (req,res) { User.find({},function (err,users) { if(err){ res.send(err); return; } console.log("res = "+ res); console.log("Name = "+users[0].username); res.json(users); }); }); api.post('/login',function (req,res) { User.findOne({username: req.body.username}).select('name username password').exec(function(err,user){ if(err) throw err; if(!user){ res.send({message: "User does not exist!"}); }else if(user){ var validPassword = user.comparePassword(req.body.password); if(!validPassword){ res.send({message: "Invalid password entered"}); }else { var token = createToken(user); res.json({ success: true, message: "Successfully logged in", token: token, UN: req.body.username }); } } }); }); api.post('/logout',function (req,res) { User.findOne({username: req.body.username}).select('_id').exec(function(err,user){ Chat.remove({Creator: user._id,Status: false},function (err) { if(err){ res.send(err); console.log(err); return; } res.json({ success: true, message: "Successfully logged out" }) }); }); }); api.use(function (req,res,next) { var token = req.body.token || req.param('token') || req.headers['x-access-token']; if(token){ jsonwebtoken.verify(token,secretKey,function(err,decoded) { if(err){ res.status(403).send({success: false, message: "Failed to authenticate the user"}); }else { req.decoded = decoded; next(); } }); }else{ res.status(403).send({success: false, message: "No token has been provided"}); console.log("No Token Provided"); } }); /*********To get the users list************/ api.get('/me',function(req,res){ res.send(req.decoded); }); /******************************************/ /*api.get('/',function (req,res) { res.json("Hello World Response!") });*/ /* Below are the routes called once after the user logged in */ api.route('/') .post(function (req,res) { //var user_arr = req.body.userGroup; var user_arr = req.body.selectedUserList; //['kchinnap1','kchinnap2']; console.log("Selection = "+req.body.selectedUserList); console.log("body = "+req.body); // To send the chat message to each selected users if(user_arr.length){ var len = user_arr.length; var id_arr = []; for(var i=0;i<len;i++){ User.findOne({username: user_arr[i]}).select('_id').exec(function(err,user_id){ if(!err){ var chat_for_all = new Chat({ Creator: user_id, Message: req.body.Message, Target_Users: [], fromUser: req.decoded.username }) chat_for_all.save(function (err,newMsg) { if(err) { res.send(err); return; } }) } else { console.log("Error occured while reading the users collection"); } }) } } user_arr.push(req.decoded.username); var chat = new Chat({ Creator: req.decoded.id, Message: req.body.Message, Target_Users: user_arr, fromUser: req.decoded.username }); chat.save(function(err,newMsg){ if(err) { res.send(err); return; } io.emit('chat',newMsg); res.json({message: "New chat message created"}); }); }) .get(function(req,res){ Chat.find({Creator: req.decoded.id},function (err,chat_msg) { if(err){ res.send(err); return; }else { Chat.update({Creator: req.decoded.id},{$set:{Status:false}},{multi: true},function (err) { if(err) console.log("Message status could not be set"); }) } res.send(chat_msg); }); }); api.route('/AddChatUser') .post(function (req,res) { var uName = req.body.userName; console.log("uname = "+uName); //chatUsers.find({Creator: req.decoded.id},function (err,Chat_User_List) { ChatUList.findOne({Creator: req.decoded.id}).select('ChatUsers').exec(function(err,user_list){ var uList = []; if(user_list != null) { console.log("Userlst = "+ user_list.ChatUsers); uList = user_list.ChatUsers; uList.push(uName); console.log("UserlstUPD = "+ uList); ChatUList.update({Creator: req.decoded.id},{$set:{ChatUsers:uList}},function (err) { if(err){ res.send(err); console.error(err); return; } res.json({message: "New chat user created"}); }); } else { console.log("Null userlist"); console.log("chatuser list = "+user_list); uList.push(uName); console.log(uList); /*user_list.push(uName); console.log(user_list);*/ var chat_Users = new ChatUList({ Creator: req.decoded.id, ChatUsers: uList }) chat_Users.save(function (err,user) { if(err){ res.send(err); console.error(err); return; } res.json({message: "New chat user created"}); }); } }); }); api.route('/GetChatUser') .get(function(req,res){ //chatUsers.find({Creator: req.decoded.id},function (err,Chat_User_List) { ChatUList.findOne({Creator: req.decoded.id}).select('ChatUsers').exec(function(err,user_list){ if(user_list != null){ console.log("ser = "+user_list.ChatUsers); res.json(user_list); } else { res.json({ChatUsers:''}); } }); }); api.route('/DelChatUser') .post(function(req,res){ //chatUsers.find({Creator: req.decoded.id},function (err,Chat_User_List) { ChatUList.findOne({Creator: req.decoded.id}).select('ChatUsers').exec(function(err,user_list){ if(user_list != null){ var uList = []; for(var i =0;i<user_list.ChatUsers.length;i++){ if(user_list.ChatUsers[i] != req.body.uName) uList.push(user_list.ChatUsers[i]); } ChatUList.update({Creator: req.decoded.id},{$set:{ChatUsers:uList}},function (err) { if(err){ res.send(err); console.error(err); return; } }); console.log("ser = "+uList); res.json({message: "Chat user has been deleted"}); } else { res.json({message: "No chat user to be deleted"}); } }); }); return api; }
// Creating 10 random IDs for the rectangles between 1 and 100 const ids = [] while(ids.length < 10){ const r = Math.floor(Math.random()*100) + 1; if(ids.indexOf(r) === -1) ids.push(r); } // Defining all the possible letters inside hexcode const letters = "0123456789ABCDEF"; // Function to generate random hexcode function generateHexCode() { // html color code starts with # let color = '#'; // generating 6 times as HTML color code consist // of 6 letter or digits for (let i = 0; i < 6; i++) color += letters[(Math.floor(Math.random() * 16))]; return color; } // Randomly creating 10 random colors (hexcodes) const colors = new Array(); for(let i = 0; i < 10; i++){ colors.push(generateHexCode()); } function logIds() { console.log(`Here are the rectangle IDs: ${ids.join(', ')}`); } // Editing the DOM document.addEventListener("DOMContentLoaded", () => { const rectangleWrapper = document.getElementById('rectangleWrapper'); for (i = 0; i < 10; i++) { const colorDiv = document.createElement('div'); colorDiv.style.width = Math.floor(Math.random()*100) + 1 + 'px'; colorDiv.style.height = Math.floor(Math.random()*100) + 1 + 'px'; colorDiv.id = ids[i]; colorDiv.className = 'rectangle'; colorDiv.style.backgroundColor = colors[i]; rectangleWrapper.appendChild(colorDiv); const colorText = document.createElement('p'); colorText.innerText = colors[i]; rectangleWrapper.appendChild(colorText); } });
import verifyToken from "../middleware/authJwt.js"; import express from "express"; const router = express.Router(); import db from "../models/index.js"; // Get all users registered router.get("/users", (req, res) => { db.users .find() .then((allUsers) => { res.json(allUsers); }) .catch((err) => { res.send(err); }); }); router.post("/welcome", verifyToken, (req, res) => { res.send({ message: "Welcome!" }); }); router.get("/test/all", (req, res) => { res.send("all access"); }); router.get("/test/user", (req, res) => { res.send("user access"); }); router.get("/test/mod", (req, res) => res.send("moderato access")); router.get("/test/admin", (req, res) => { res.send("admin access"); }); export default router;
import React, { Component } from 'react'; class OrderContentsList extends Component { render() { return( <React.Fragment> <div className="order-image-holder"> <div className="order-img-and-title"> <div className="order-image m-t-20"> <img src={`http://localhost:8080/images?item_id=${this.props.itemId}&user_id=${this.props.userId}`} alt=""/> </div> <span className="order-img-description"> <strong>{this.props.itemTitle}</strong> </span> </div> <div className="quantity"> <strong>Qty.</strong> {this.props.quantity} </div> </div> <hr /> </React.Fragment> ) } } export default OrderContentsList;
const chalk = require('chalk'); module.exports = function(){ console.log(chalk.yellow( ` 1) Try googling along the lines of "concatenate strings in javascript" or "how to add strings js" 2) Make sure that the final value of the square is stated on the same line after the "return" keyword ` )); process.exit(); };
config({ 'editor/plugin/font-size/cmd': {requires: ['editor','editor/plugin/font/cmd']} });
import React, { Component } from 'react'; import '../App.css'; import { bindActionCreators } from 'redux' import * as programsActions from '../actions/programsActions' import PropTypes from 'prop-types' import { connect } from 'react-redux' import Programs from './Programs' import CurrentCourse from './CurrentCourse' import Average from './Average' import Years from './Years' class App extends Component { // Initialize state // Fetch passwords after first mount componentDidMount() { this.getPrograms(); this.getYears(); } getPrograms = () => { // Get the passwords and store them in state fetch('/api/programs') .then(res => res.json()) .then(programs => this.props.addPrograms(programs)); } getYears = () => { fetch('/api/years') .then(res => res.json()) .then(years => this.props.addYears(years)); } render() { return ( <div className="App"> {!this.props.readyToCalculate && <div> <Programs addPrograms={this.props.addPrograms} programs={this.props.programs} selectProgram={this.props.selectProgram} /> <Years years={this.props.years} selectYear={this.props.selectYear} /> <button disabled={(!this.props.selectedYear || !this.props.selectedProgram)} onClick={()=>this.props.setReadyToCalculate()}>OK </button> </div> } {this.props.readyToCalculate && <div> <CurrentCourse selectedCourse={this.props.currentCourse} setCourseInfo={this.props.setCourseInfo} courseInfo={this.props.courseInfo} currentCourse={this.props.currentCourse} selectedYear={this.props.selectedYear} selectedProgram={this.props.selectedProgram} getCourses={this.props.getCourses} getSpecialisations={this.props.getSpecialisations} courses={this.props.courses} selectCourse={this.props.setCurrentCourse} addHp={this.props.addHp} addHpGradeMultiply={this.props.addHpGradeMultiply} points={this.props.hp} addMasterCourse={this.props.addMasterCourse} masterCourses={this.props.masterCourses} index={this.props.index} increaseIndex={this.props.increaseIndex} specialisations={this.props.specialisations} addToSpecialisations={this.props.addToSpecialisations} /> {this.props.courseInfo && <Average average={this.props.hp === 0 ? 0: (this.props.hpGradeMultiply/this.props.hp).toFixed(2)}/> } </div> } </div> ); } } function mapStateToProps (state) { return { programs: state.programs.programs, selectedProgram: state.programs.selectedProgram, courses: state.programs.courses, currentCourse: state.programs.currentCourse, courseInfo: state.programs.courseInfo, hp: state.programs.hp, hpGradeMultiply: state.programs.hpGradeMultiply, masterCourses: state.programs.masterCourses, years: state.programs.years, selectedYear: state.programs.selectedYear, readyToCalculate: state.programs.readyToCalculate, index: state.programs.index, specialisations: state.programs.specialisations, } } function mapDispatchToProps (dispatch) { return bindActionCreators( { ...programsActions, }, dispatch) } App.propTypes = { programs: PropTypes.arrayOf(PropTypes.any), selectedProgram: PropTypes.string, courses: PropTypes.arrayOf(PropTypes.any), currentCourse: PropTypes.string, courseInfo: PropTypes.object, masterCourses: PropTypes.arrayOf(PropTypes.any), years: PropTypes.arrayOf(PropTypes.any), readyToCalculate: PropTypes.bool, selectedYear: PropTypes.arrayOf(PropTypes.any), index: PropTypes.Integer, specialisations: PropTypes.arrayOf(PropTypes.any), } App.defaultProps = { } export default connect(mapStateToProps, mapDispatchToProps)(App)
import * as EASE from './easing.js'; let Vrender = (index) => { if(index === Control.graphs.length) { ISANIMATING = 0; // 结束动画 return; } if(index === 0) { ctx.clearRect(0, 0, oW, oH); } let Curve = Control.graphs[index]; let timeout = Curve.timeout || 100; let temp = 0 let ease = EASE[Curve.ease]; // 动画 起始时间 let start = Date.now(); Curve.t = 0; Curve.isAnimating = true; Curve.isEdit = false; requestAnimationFrame(render); function render () { let now = Date.now(); let percent = (now - start) / timeout; // 当前运动百分比 let easePercent = ease(percent) // 时间线已经 到达的百分比 if (easePercent >= 1) { easePercent = 1; } Curve.t = easePercent; Curve.draw(); if (easePercent < 1) { requestAnimationFrame(render); } else { Curve.isAnimating = false; Vrender(index+1); } } } export default Vrender;
import AmountField from "~/components/Fields/AmountField"; import NumberField from "~/components/Fields/NumberField"; import TextField from "~/components/Fields/TextField"; import SelectField from "~/components/Fields/SelectField"; import _ from "lodash"; export const REQUEST_HEADER_INFO = { MODEL_VENDOR_INFO: { header: "Vendor", fields: [ { title: "Code", key: "vendorNumber" }, { title: "Name", key: "vendorName" }, { title: "Tax ID", key: "vendorTaxNumber" }, { title: "Branch", key: "vendorBranchCode" }, { title: "Address", key: "vendorAddress" }, { title: "Tel.", key: "vendorTelephone" } ], lang: "request-edit" }, MODEL_COMPANY_INFO: { header: "Company", fields: [ { title: "Code", key: "companyCode" }, { title: "Name", key: "companyName" }, { title: "Tax ID", key: "companyTaxNumber" }, { title: "Branch", key: "companyBranchCode" }, { title: "Address", key: "companyAddress" }, { title: "Tel.", key: "companyTelephone" } ], lang: "request-edit" }, MODEL_REQUEST_INFO: { header: "Request Information", fields: [ { title: "Request Type", key: "type" }, { title: "Sub Type", key: "subType" }, { title: "Reference Type", key: "referenceType" }, { title: "Reference Number", key: "referenceNumber" }, { title: "Buyer Attachments", key: "requestAttachment", type: "files", download: true }, { title: "Request Reason", key: "requestReason", type: "textArea", classInput: "col-7" } ], lang: "request-edit" }, MODEL_REFERENCE: { header: "Reference", fields: [ { title: "Reference 1", key: "referenceField1", type: "text", classInput: "row col-8" }, { title: "Reference 2", key: "referenceField2", type: "text", classInput: "row col-8" }, { title: "Reference 3", key: "referenceField3", type: "text", classInput: "row col-8" }, { title: "Reference 4", key: "referenceField4", type: "text", classInput: "row col-8" }, { title: "Reference 5", key: "referenceField5", type: "text", classInput: "row col-8" } ], lang: "request-edit" }, MODEL_DOCUMENT_INFO_LEFT: { fields: [ { title: "Document Date", key: "documentDate", type: "date", classInput: "row col-8", maxDate: new Date().toISOString() }, { title: "Document Type", key: "documentType", type: "select", placeholder: "", classInput: "col-7" }, { title: "Document No.", key: "documentNumber", type: "text", classInput: "col-7" }, { title: "Document Attachments", key: "documentAttachment", type: "files", download: true }, { title: "Documents Reason", key: "documentReason", type: "textArea", classInput: "col-7" } ], lang: "request-edit" }, MODEL_DOCUMENT_INFO_RIGHT: { fields: [ { title: "Payment Due Date", key: "paymentDueDate", type: "date", classInput: "row col-8" }, { title: "Sub Total", key: "subTotal", type: "number", classInput: "row col-8", classUnit: "col-4", onBlur: null, format: { thousand: true, decimal: 2 }, currency: true }, { title: "Tax Total", key: "vatTotal", type: "number", classInput: "row col-8", classUnit: "col-4", onBlur: null, format: { thousand: true, decimal: 2 }, currency: true }, { title: "Total Amount (Inc. Tax)", key: "total", type: "number", classInput: "row col-8", classUnit: "col-4", onBlur: null, format: { thousand: true, decimal: 2 }, currency: true }, { title: "WHT Total", key: "withholdingTaxAmount", type: "number", classInput: "row col-8", classUnit: "col-4", onBlur: null, format: { thousand: true, decimal: 2 }, currency: true } ], lang: "request-edit" } }; export var REQUEST_ITEM_INFO = [ { name: "No.", width: "5%", selector: "externalId", center: true }, { name: "Description", selector: "description", center: true, cell: r => ( <span className="d-inline-flex"> <TextField datas={r} field={{ canEdit: r.descriptionEditable, key: "description", disabled: _.findIndex(!!r.permission ? r.permission : [], { field: "description", editable: false }) >= 0, placeholder: "", onChange: event => r.onChange.call(this, event) }} /> </span> ) }, { name: "Quantity", width: "10%", selector: "quantityInitial", center: true, cell: r => ( <span className="d-inline-flex"> <AmountField datas={r} field={{ canEdit: r.quantityEditable, maxLength: "13", key: "quantityInitial", disabled: _.findIndex(!!r.permission ? r.permission : [], { field: "quantity", editable: false }) >= 0, placeholder: r.placeholder ? r.placeholder : "", format: { thousand: true, decimal: 3 }, onBlur: event => r.onBlur.call(this, event) }} /> </span> ) }, { name: "Unit", width: "10%", selector: "quantityUnit", center: true, cell: r => ( <span className="d-inline-flex"> <TextField datas={r} field={{ canEdit: r.unitEditable, key: "quantityUnit", disabled: _.findIndex(!!r.permission ? r.permission : [], { field: "quantityUnit", editable: false }) >= 0, placeholder: r.placeholder ? r.placeholder : "", onChange: event => r.onChange.call(this, event) }} /> </span> ) }, { name: "Unit Price", width: "10%", selector: "unitPrice", center: true, cell: r => ( <span className="d-inline-flex"> <NumberField datas={r} field={{ canEdit: r.unitPriceEditable, maxLength: "13", key: "unitPrice", disabled: _.findIndex(!!r.permission ? r.permission : [], { field: "unitPrice", editable: false }) >= 0, placeholder: r.placeholder ? r.placeholder : "", format: { thousand: true, decimal: 3 }, onBlur: event => r.onBlur.call(this, event) }} /> </span> ) }, { name: "TAX", width: "10%", selector: "vatCode", center: true, type: "text", cell: r => { return ( <span className="d-inline-flex"> <SelectField datas={r} field={{ defaultValue: "-", canEdit: r.vatCodeEditable, key: "vatCode", placeholder: r.placeholder ? r.placeholder : "", disabled: _.findIndex(!!r.permission ? r.permission : [], { field: "vatCode", editable: false }) >= 0, onChange: event => r.onChange.call(this, event) }} /> </span> ); } }, { name: "Sub Total", width: "15%", selector: "subTotal", center: true, type: "text", cell: r => ( <span className="d-inline-flex"> <NumberField datas={r} field={{ canEdit: r.subTotalEditable, maxLength: "13", key: "subTotal", disabled: _.findIndex(!!r.permission ? r.permission : [], { field: "subTotal", editable: false }) >= 0, placeholder: r.placeholder ? r.placeholder : "", format: { thousand: true, decimal: 2 }, onBlur: event => r.onBlur.call(this, event) }} /> </span> ) }, { name: "Currency", width: "8%", selector: "currency", center: true, type: "text", cell: r => ( <span className="d-inline-flex"> <TextField datas={r} field={{ canEdit: r.currencyEditable, key: "currency", disabled: _.findIndex(!!r.permission ? r.permission : [], { field: "currency", editable: false }) >= 0, placeholder: r.placeholder ? r.placeholder : "", onChange: event => r.onChange.call(this, event) }} /> </span> ) }, { name: "Site", width: "10%", selector: "site", center: true, type: "text", cell: r => ( <span className="d-inline-flex"> <TextField datas={r} field={{ canEdit: r.siteEditable, key: "site", disabled: _.findIndex(!!r.permission ? r.permission : [], { field: "site", editable: false }) >= 0, placeholder: r.placeholder ? r.placeholder : "", onChange: event => r.onChange.call(this, event) }} /> </span> ) }, { name: "", width: "5%", selector: "delete", center: true, type: "text", cell: r => ( <a // hidden={!r.requestItemEditable} href="javasctip:void(0)" id={r.linearId} onClick={event => r.onClick.call(this, r.externalId)} > <span className="d-inline-flex"> <i className="fa fa-times" /> </span> </a> ) } ];
function Renderer_Puntobici() { }; Renderer_Puntobici.prototype.reset = function(container) { if (container == undefined) { container = containerPuntobici; } container.empty(); }; Renderer_Puntobici.prototype.render = function(add, data, container) { if (add) { var li = $("#" + data['id']); if (li.length == 0) { li = $('<tr></tr>').addClass('elements'); li.attr('id', data['id']); var span = $('<span></span>'); span.text(data['name']); var action = $('<a></a>'); action.append($('<img></img>').attr('src', 'imgs/details.ico')) .attr('alt', 'dettagli').attr('title', 'dettagli'); action.attr('href', '#'); action.click(function() { map.setCenter(new google.maps.LatLng(data['geometry']['lat'], data['geometry']['lng']), zoomToLevel); rendererPuntobici.popup(false,data,puntobiciGeo[data['id']]); }); li.append($('<td></td>').attr('width', '90%').append(span)); li.append($('<td></td>').attr('width', '10%').append(action)); if (container == undefined) { container = containerPuntobici; } container.append(li); } else { li.children('td:first').children('span').text(data['name']); } } else { var li = $("#" + data); li.remove(); } $("tr.elements:even").css("background-color", "#6eb4e9"); $("tr.elements:odd").css("background-color", "#add6f5"); }; Renderer_Puntobici.prototype.updatePopup = function(modeEdit, data) { if (!!infowindow) { rendererPuntobici.popup(modeEdit, data, infowindow.getPosition()); } }; // RENDER SAMPLE // <li id="#id"><span>Puntobici 1<a href="">dettagli</a></span> // </li> Renderer_Puntobici.prototype.popup = function(modeEdit, data, marker) { var renderPopup = function(modeEdit, data) { var popup = ''; if(modeEdit){ popup='<div style="width:200px;">' + 'Nome <label id="puntobici_name_msg" class="errorMsg"></label><input name="puntobici_name" type="text" value="' + ((data['name'] != undefined) ? data['name'] : "") + '"/>' + ' Numero bici <label id="puntobici_bikeNumber_msg" class="errorMsg"></label><input name="puntobici_bikeNumber" type="text" value="' + ((data['bikeNumber'] != undefined) ? data['bikeNumber'] : "") + '"/>' + 'Numero posti bici <label id="puntobici_slotNumber_msg" class="errorMsg"></label><input name="puntobici_slotNumber" type="text" value="' + ((data['slotNumber'] != undefined) ? data['slotNumber'] : "") + '"/>' + '<br/><input name="puntobici_id" type="hidden" value="' + ((data['id'] != undefined) ? data['id'] : "") + '"/>' + '<input name="puntobici_tempId" type="hidden" value="' + ((data['tempId'] != undefined) ? data['tempId'] : "") + '"/>' + '<input name="puntobici_coord" type="hidden" value="' + data['geometry']['lat'] + ',' + data['geometry']['lng'] + '"/>' + '<hr/><a href="#" onclick="savePuntobici();">Salva</a>' + ' <a href="#" onclick="removePuntobici();">Elimina</a>'; + '</div>'; }else{ popup = '<div style="width:200px;">' + '<p class="title-popup">Nome</p>' + data['name'] + '<p class="title-popup">Numero bici</p>' + data['bikeNumber'] +'<p class="title-popup">Numero posti bici</p>' + data['slotNumber'] + '</div><input name="puntobici_id" type="hidden" value="' + ((data['id'] != undefined) ? data['id'] : "") + '"/>' + '<hr/><a href="#" onclick="editPuntobici();">Modifica</a>' + '</div>'; } return popup; }; if (!!infowindow) { infowindow.close(); } infowindow = new google.maps.InfoWindow( { content: renderPopup(modeEdit, data) }); infowindow.open(map, marker); }; Renderer_Puntobici.prototype.updateGeo = function(marker, data) { marker.setMap(null); rendererPuntobici.renderGeo(false, data, false); }; Renderer_Puntobici.prototype.renderGeo = function(modeEdit, data, open) { var width = 16; var height = 26; var position = new google.maps.LatLng(((data != null) ? data['geometry']['lat'] : lat), ((data != null) ? data['geometry']['lng'] : lng)); var marker = new google.maps.Marker({ icon: { url: baseUrl + '/rest/marker/' + company + '/puntobici', ancor: new google.maps.Point(width / 2, height) }, position: position, draggable: modeEdit, map: map }); // var icon = new GIcon(); // icon.image = baseUrl + '/rest/marker/' + company + '/puntobici'; // icon.shadowSize = new GSize(Math.floor(width * 1.6), height); // icon.iconAnchor = new GPoint(width / 2, height); // icon.infoWindowAnchor = new GPoint(width / 2, Math.floor(height / 12)); // var marker = new GMarker(new GLatLng( // ((data != null) ? data['geometry']['lat'] : lat), // ((data != null) ? data['geometry']['lng'] : lng)), { // draggable : modeEdit, // icon : icon // }); if (data['id'] != null) { puntobiciGeo[data['id']] = marker; } else { tempGeo[tempIndex] = marker; data['tempId'] = tempIndex; tempIndex++; } if (modeEdit) { google.maps.event.addListener(marker, 'dragstart', function() { if (!!infowindow) { infowindow.close(); } }); } google.maps.event.addListener(marker, 'click', function() { rendererPuntobici.popup(modeEdit,((data['id']) ? puntobici[data['id']] : data), marker); }); if (modeEdit) { google.maps.event.addListener(marker, "dragend", function() { var info; if (data['id'] != null) { info = puntobici[data['id']]; } else { info = data; } info['geometry']['lat'] = marker.getPosition().lat(); info['geometry']['lng'] = marker.getPosition().lng(); google.maps.event.trigger(marker, 'click'); }); } marker.setMap(map); if (open) { google.maps.event.trigger(marker, 'click'); } };
// resultsInj = document.querySelector("#results-section") // let foodInfo = (value) => { // console.log("my log", value) // if (value.length === 0) { // alert("There are no foods for this category today") // } else { // htmlBuilder.clearContainer(resultsInj) // for (let i = 0; i < 5 &&) { // }
import { USER_HOME_REQUESTED, USER_HOME_SUCCESS, USER_HOME_FAILED, USER_ADD_TO_LIKE_REQUESTED, USER_ADD_TO_LIKE_SUCCESS, USER_ADD_TO_LIKE_FAILED, HOME_SEARCH, HOME_PULL_TO_REFRESH } from "./types"; export const userHomeSuccess = ({ access_token, feed_type, page }) => ({ types: [ USER_HOME_REQUESTED, USER_HOME_SUCCESS, USER_HOME_FAILED ], payload: { client: "default", request: { method: "GET", url: `/Products-List/${feed_type || 'Latest'}/${page || 1}`, headers: { access_token, }, } } }); export const toggleLikeStatus = ({ access_token, product_id, status }) => ({ types: [ USER_ADD_TO_LIKE_REQUESTED, USER_ADD_TO_LIKE_SUCCESS, USER_ADD_TO_LIKE_FAILED, ], payload: { client: "default", request: { headers: { access_token, }, method: "POST", url: "/Add-To-Like", data: { product_id, status } } } }); export const homeSearch = ({ title }) => ({ type: HOME_SEARCH, payload: { title, } }); export const pullToRefresh = () => ({ type: HOME_PULL_TO_REFRESH });
import Vue from "vue"; import Router from "vue-router"; import Home from "./views/Home.vue"; import store from "./store"; Vue.use(Router); export default new Router({ mode: "history", base: process.env.BASE_URL, routes: [ { path: "/", component: Home }, { path: "/about", // route level code-splitting // this generates a separate chunk (about.[hash].js) for this route // which is lazy-loaded when the route is visited. component: () => import("./views/About.vue") }, { path: "/test", component: () => import("./views/Test.vue") }, { path: "/pic", beforeEnter: (to, from, next) => { // ... // console.log("to:" + JSON.stringify(to)); // if(from){ // console.log("from:"+JSON.stringify(from)); // } next(); }, component: () => import("./views/pic.vue") }, { path: "/table", component: () => import("./views/table.vue") }, { path: "/login", beforeEnter: (to, from, next) => { if (sessionStorage.getItem("user") == null) next(); else { console.log("???"); next("/"); } }, component: () => import("./views/login.vue") }, { path: "/register", component: () => import("./views/register.vue") }, { path: "/user", component: () => import("./views/user.vue") }, { path: "/message", component: () => import("./views/message.vue") }, { path: "/admin", beforeEnter: (to, from, next) => { if (store.state.user == null) next("/login"); else if ( store.state.user.members.some(e => (e.role.roleName = "管理员")) ) { next(); } else { next("/auth"); } }, component: () => import("./views/admin.vue") }, { path: "/auth", component: () => import("./views/auth.vue") }, { path: "/template", component: () => import("./views/template.vue") }, { path: "/workflow", component: () => import("./views/workflow.vue") }, { path: "/file", component: () => import("./views/file.vue") }, { path: "/config", component: () => import("./views/config.vue") }, { path: "/calendar", component: () => import("./views/calendar.vue") } ] });
import React, { useState } from 'react' import { render, fireEvent } from '@testing-library/react' import UsernameField from '../index' const TestComponent = () => { const [value, setValue] = useState('') const onChange = e => setValue(e.target.value) return <UsernameField onChange={onChange} value={value} /> } const buildComponent = () => { const utils = render(<TestComponent />) const input = utils.getByLabelText('Usuário') return { input, ...utils } } describe('<UsernameField />', () => { it('Render the component without crashing', () => { const { asFragment } = buildComponent() expect(asFragment()) .toMatchSnapshot() }) it('Types a value in the input', () => { const { input } = buildComponent() expect(input) .toHaveProperty('value', '') fireEvent.change(input, { target: { value: 'username' } }) expect(input) .toHaveProperty('value', 'username') }) })
import Header from '../components/Header'; function Solve() { return <div className="bg-custom text-alice-blue"> <Header /> <p className="flex justify-center h-50"> COMING SOON! The Tactics Ninja Tactics Samurai Dojo Trainer </p> </div>; } export default Solve;
document.addEventListener('DOMContentLoaded', function () { var quizz; var score = 0; var x = 0; const allowedDiff = ["easy", "medium", "hard"]; var allowedSubjs = { "books": 10, "films": 11, "music": 12 }; goButton = document.getElementById('go') var allErrorMess = document.getElementsByClassName("errorMess"); function showErrorMessage(caller, inputIndex) { caller.classList.add("error"); allErrorMess[inputIndex].style.display = "block"; caller.focus(); } function hideErrorMessage(caller, inputIndex) { caller.classList.remove("error"); elem = document.getElementsByClassName("errorMess")[inputIndex]; elem.style.display = "none"; } difficulty.oninput = function () { if (isValidDifficulty(this.value)) { hideErrorMessage(this, 0); } else { showErrorMessage(this, 0); } setGo(); }; quantity.oninput = function () { if (isValidNumberOfQuestions(this.value)) { hideErrorMessage(this, 1); } else { showErrorMessage(this, 1); } }; subject.oninput = function () { if (isValidSubject(this.value)) { hideErrorMessage(this, 2); } else { showErrorMessage(this, 2); } setGo(); }; function isValidDifficulty(value) { value = value.toLowerCase().trim(); return allowedDiff.includes(value); } function isValidNumberOfQuestions(value) { value = Math.floor(value) return (value > 0 && value <= 5) } function isValidSubject(value) { value = value.toLowerCase().trim(); return allowedSubjs.hasOwnProperty(value); } function setGo() { if ((difficulty.className !== "error") && (quantity.className !== "error") && (subject.className !== "error") && difficulty.value !== "" && quantity.value !== "" && subject.value !=="") { goButton.style.backgroundColor = "#4040a1"; goButton.disabled = false; } else { goButton.style.backgroundColor = "gray"; goButton.disabled = true; } } function display(x) { if (x >= 0 && x < quizz.results.length) { document.getElementById('question1').style.display = 'block'; document.getElementById('trues').style.display = 'block'; document.getElementById('falses').style.display = 'block'; document.getElementById("question1").innerHTML = (x + 1) + "." + quizz.results[x].question; document.getElementById("trues").innerHTML = quizz.results[x].correct_answer; document.getElementById("falses").innerHTML = quizz.results[x].incorrect_answers[0]; }//end if statement else { document.body.innerHTML = "THE END. YOUR SCORE is " + score + " of " + quizz.results.length; document.body.setAttribute("style", "width: 100%; margin:0 auto; font-weight:bold; font-size: 100px; color: white; background-image: url('https://upperarlingtonoh.gov/wp-content/uploads/2018/06/Fireworks.jpg'); background-repeat: no-repeat; background-size:cover"); setInterval(function(){ location.reload(); }, 3000); } }; function beautify(value) { return value.toLowerCase().trim(); } function getElemValue(id) { value = document.getElementById(id).value; return beautify(value); } function setComplex() { var difficulty = getElemValue("difficulty"); var quantity = getElemValue("quantity"); var subject = allowedSubjs[getElemValue("subject")]; var xhr = new XMLHttpRequest(); xhr.onload = function () { if (xhr.status === 200) { console.log(xhr.status); quizz = JSON.parse(xhr.responseText); console.log(quizz); console.log(quizz.results); x = 0; display(x); } } var difPath = "https://opentdb.com/api.php?amount=" + quantity + "&category=" + subject + "&difficulty=" + difficulty + "&type=boolean"; console.log(difPath); xhr.open('GET', difPath, true); xhr.responseType = 'text'; xhr.send(); } document.getElementById("go").addEventListener("click", () => { document.getElementById("settings").style.display = "none"; setComplex(); }); document.getElementById("falses").addEventListener("click", () => { alert("NO, sorry"); display(++x); }); document.getElementById("trues").addEventListener("click", () => { alert("Correct! + 1 score") ++score; display(++x); console.log(score); }); });// end of DOM function
const { eslint } = require('@packages/devtools'); eslint.extends.push('plugin:react/recommended') module.exports = eslint;
import React, { useContext} from 'react'; import { Route, Redirect } from "react-router-dom"; import Context from '../context'; export default ({ children, ...rest }) => { const { userContext } = useContext( Context ); return ( <Route {...rest} render={({ location }) => userContext && userContext.isAuthenticated ? ( children ) : ( <Redirect to={{ pathname: "/login", state: { from: location } }} /> ) } /> ); }
const config = require('./config.json'); const getEvent = require('./getEvent'); module.exports = function login (req, res) { getEvent(config.NARMS, 'workstations/', function(error, resp){ if (error) { console.log(error); } var workstations = JSON.parse(resp.body).workstations; res.status(resp.statusCode) .json(workstations); }); };
/** * @file demos/xui-monthview.js * @author leeight */ import moment from 'moment'; import {defineComponent} from 'san'; import {Row, MonthView} from 'san-xui'; /* eslint-disable */ const template = `<template> <x-row label="[default]"> <xui-monthview value="{=monthview.value=}" range="{{monthview.range}}"/> <strong class="large"> Value is: {{monthview.value | datetime('YYYY-MM-DD')}} </strong> </x-row> <x-row label="value type is string: 1985-03-08T01:44:48Z"> <xui-monthview value="1985-03-08T01:44:48Z"/> </x-row> <x-row label="time"> <xui-monthview time value="{=monthview.value=}" /> <strong class="large"> Value is: {{monthview.value | datetime('YYYY-MM-DD HH:mm:ss')}} </strong> </x-row> </template>`; /* eslint-enable */ export default defineComponent({ template, components: { 'x-row': Row, 'xui-monthview': MonthView }, filters: { datetime(value, f = 'YYYY-MM-DD HH:mm:ss') { return moment(value).format(f); } }, initData() { return { monthview: { value: new Date(), range: { begin: new Date(2014, 4, 1), end: new Date() } } }; } });
const decToHex = (value) => { if (value > 255) { return "FF"; } else if (value < 0) { return "00"; } else { return value.toString(16).padStart(2, "0"); } }; const rgbToHex = (r, g, b) => { return decToHex(r) + decToHex(g) + decToHex(b); }; const rgbToDec = (r, g, b) => { return parseInt(rgbToHex(r, g, b), 16); }; module.exports = { decToHex, rgbToHex, rgbToDec };
var circleModule = require("./circleModule.js");//得到的值是第三方模块的一个对象 var r = process.argv[2]; var circleObj = circleModule.cirFun(r); console.log(circleObj.circumference()); console.log(circleObj.area());
/** * 数组的分块 * @param arr 需要分块的数组 * @param size 分块的数量 */ const chunk = (arr, size) => Array.from({ length: Math.ceil(arr.length / size) }, (v, i) => arr.slice(i * size, i * size + size) ); /** * 给浏览器添加css前缀 * @return 各种浏览器的css前缀 */ let elementStyle = document.createElement('div').style let vendor = (() => { let transformNames = { 'webkit':'webkitTransform', 'Moz':'MozTransform', 'O':'OTransform', 'ms':'msTransform', 'standard':'transform' } for(let k in transformNames) { if (elementStyle[transformNames[k]] !== undefined) { return k } } return false })() const prefix = (style) => { if (!vendor) { //如果供应商有问题,直接return return false } if(vendor === 'standard') { return style } return vendor + style.charAt(0).toUpperCase() + style.substr(1) } /** * 数组随机打乱(洗牌函数) * @param arr 需要打乱的数组 * @return Array 最终打乱的数组 */ const shuffle = function(arr) { let _arr = arr.slice() //不修改原数组 for (let i = 0; i < _arr.length; i++) { let j = getRandomInt(0,i) // 变量的交换 let t = _arr[i] _arr[i] = _arr[j] _arr[j] = t } return _arr } /** * 获取多少道多少之间的随机整数 * @param min 最小数字 * @param max 最大数字 * @return 随机数 */ const getRandomInt = function(min,max) { return (Math.random() * (max - min + 1) + min) | 0 } /** * 函数节流方法 * @param Function fn 延时调用函数 * @param Number delay 延迟多长时间 * @param Number atleast 至少多长时间触发一次 * @return Function 延迟执行的方法 */ // atleast要大于dalay const throttle = (fn,dalay,atleast=0) => { let timer = null let previous = null return (...args) =>{ let now = +new Date() //获取当前时间戳 !previous ? now : previous if (atleast && now - previous > atleast ) { fn.apply(this,args) // 重置上一次开始时间为本次结束时间 previous = now clearTimeout(timer) } else { clearTimeout(timer) timer = setTimeout(() => { fn.apply(this,args) previous = null },dalay) } } } /** * 函数去抖方法 * @param Function fn 延时调用函数 * @param Number delay 延迟多长时间 * @return Function 延迟执行的方法 */ const debounce = (fn,dalay) => { let timer = null return (...args) => { if (timer) { clearTimeout(timer) } timer = setTimeout(() => { fn.apply(this,args) }, dalay); } }                          /** * 搜索关键词高亮显示 * @param String str 要替换的关键词 * @param String value 搜索框里面的内容 * @return Function 替换后的内容 */ const keyWord = (str,value) => { const replaceReg = new RegExp(value, 'g'); const replaceString = `<span style='color:red'>${value}</span>` str = str.replace(replaceReg, replaceString); return str } export { chunk, //数组分块 throttle, //函数节流 debounce, //函数防抖 prefix, //各种浏览器的css前缀 getRandomInt, //获取多少道多少之间的随机整数 shuffle, //数组随机打乱(洗牌函数) keyWord, //搜索关键词高亮显示 }
import { useState } from "react"; import Navbar from "./components/navbar/navbar-component"; import CardList from "./components/card-list/card-list.component"; const App = () => { const [movies, setMovies] = useState([]); const [heading, setHeading] = useState("Please insert a movie title!"); const [formValue, setFormValue] = useState("Point Break"); const [decadeValue, setDecadeValue] = useState("All"); const [sortType, setSortType] = useState("Rating"); async function getFromApi() { console.log("fetch"); setHeading("Loading"); let searchLenght = "?l=20"; const omdbURL = "https://movie-api-bt.herokuapp.com/" + formValue + searchLenght; const res = await fetch(omdbURL); const json = await res.json(); const data = await json; setHeading("Movies like " + formValue); let filteredData = data.filter((movie) => !movie.Error); if (filteredData.length === 0) { setHeading("No result"); return; } setMovies(filteredData); } function orderByType(data) { switch (sortType) { case "Title": data.sort((a, b) => (a.Title > b.Title ? 1 : -1)); break; case "Rating": data.sort((a, b) => (a.imdbRating > b.imdbRating ? -1 : 1)); break; case "Year": data.sort((a, b) => (a.Year > b.Year ? -1 : 1)); break; // no default } return data; } const filteredMovies = movies.filter((movie) => { if (decadeValue === "All") { return true; } return +decadeValue < movie.Year && movie.Year < +decadeValue + 9; }); const orderedMovies = orderByType(filteredMovies); console.log(orderedMovies); return ( <> <Navbar getFromApi={getFromApi} formValue={formValue} setFormValue={setFormValue} setDecadeValue={setDecadeValue} decadeValue={decadeValue} setSortType={setSortType} /> <main className="container d-flex align-items-center flex-column"> <h1 className="mt-4 mb-5">{heading}</h1> <CardList movies={orderedMovies}></CardList> </main> </> ); }; export default App;
import { Button, makeStyles, TextField } from '@material-ui/core' import React from 'react' import { Controller, useForm } from 'react-hook-form' import { useDispatch } from 'react-redux' import { useHistory } from 'react-router' const useStyles = makeStyles((theme) => ({ root: { margin: '10% auto', padding: 25 }, form: { textAlign: 'center', '& .MuiTextField-root': { margin: theme.spacing(2), minWidth: 500 } }, buttonWrapper: { width: '100%', justifyContent: 'center' }, button: { maxWidth: 225, padding: '7px 15px', margin: theme.spacing(1), borderRadius: 9999 }, })); export const ReplyForm = ({ replyPostId, func, onCloseWindow }) => { const classes = useStyles() const dispatch = useDispatch() const { handleSubmit, control, formState: { errors, isDirty } } = useForm() const handelSubmit = ({ body }) => { dispatch(func({ body, replyPostId })) onCloseWindow() } const handleError = (errors) => { console.log(errors) } const registerOptions = { body: { required: "Body is required" } } const showInputForm = (params) => { const { name, type, rules, isMultiline } = params return <div> <Controller name={name} control={control} defaultValue="" rules={rules} render={({ onChange, value }) => <TextField error={!!errors[name]} helperText={!!errors[name] && errors[name].message} onChange={onChange} value={value} label={name} multiline={isMultiline} type={type} variant="outlined" />} /> </div> } return <form className={classes.form} onSubmit={handleSubmit(handelSubmit, handleError)} > {showInputForm({ name: 'body', rules: registerOptions.body, type: 'text', isMultiline: true })} <div className={classes.buttonWrapper}> <Button className={classes.button} type='submit' variant='contained' color='primary' disabled={!isDirty}> Submit </Button> </div> </form > }
async function getImage(){ const image = await axios.get(" https://api.nasa.gov/planetary/apod?api_key=CT0rIlDfBRbdwXlYVIUoEN1VdYMh7iDO0G9wj7I8"); const img = document.createElement('img'); img.src = image.data.hdurl; const container = document.querySelector('#img'); container.append(img); } const button = document.querySelector('button'); button.addEventListener('click', function (){ try{ getImage(); button.disabled = true; } catch(e){ alert('Something is wrong...try again later!'); }; });
// Vue.component('gym-player', { template: ` <div style="display: flex; flex-direction: row; align-items: center; justify-content: center;"> <div id="btnPlays" style="padding: 0px 2px 15px 2px; flex: 1;" :style="{height: (rows.length == 0 && $isAdmin() ? '60px' : 'auto')}" > <i-button v-for="(item, index) in rows" :key="index" :type="active == index || prev == index ? 'warning' : 'default'" :ghost="prev == index" @click.native="onClickPlay(index)"> {{item.title}} </i-button> </div> <i-button type="success" v-if="$isAdmin() && videoId.length > 0" @click.native="onClickEdit()" icon="md-create" shape="circle" style="margin: 0px 5px; 20px 5px" /> </div> `, props: { // title: String }, data() { return { rows: [], active: -1, prev: -1, videoId: "" }; }, created(){ }, mounted () { this.broadcast.$on('onPlayerReady', this.onPlayerReady); window.addEventListener('keydown', this.onKeydown, false); }, destroyed() { window.removeEventListener('keydown', this.onKeydown, false); this.broadcast.$off('onPlayerReady', this.onPlayerReady); }, destroyed() { }, methods: { async play(item){ // console.log(JSON.stringify(item)) this.active = -1; this.rows = Array.isArray(item.children) ? item.children : []; this.videoId = item.id; let m = window.localStorage["gym-" + this.videoId]; if(typeof m == "string") { let x = this.rows.findIndex((item)=>{ return item.title == m; }); if(x > -1) this.prev = x; else this.prev = 0; } else if(this.rows.length > 0) { this.prev = 0; } let el = document.getElementById("btnPlays"); el.style.visibility = "hidden"; }, onPlayerReady(){ setTimeout(() => { let el = document.getElementById("btnPlays"); el.style.visibility = "visible"; // if(this.rows.length > 0) { // player.seekTo(this.rows[this.prev].start); // } }, 300); }, onClickPlay(index) { this.$emit('on-click-play', this.rows[index]); this.active = index; this.prev = -1; window.localStorage["gym-" + this.videoId] = this.rows[index].title; }, onKeydown(event){ let o = document.activeElement; // let pk = navigator.userAgent.indexOf('Macintosh') > -1 ? event.metaKey : event.ctrlKey; // let ak = navigator.userAgent.indexOf('Macintosh') > -1 ? event.ctrlKey : event.altKey; // let sk = event.shiftKey, code = event.keyCode; // let char = (event.keyCode >=48 && event.keyCode <=122) ? String.fromCharCode(event.keyCode).toUpperCase() : ""; // console.log(event.keyCode + ", " + this.active) // console.log(o.id) if(this.rows.length == 0) return; if(o.tagName == "INPUT") return; if(event.keyCode == 32) { if(this.prev > -1) this.onClickPlay(this.prev) if(this.active > -1) this.onClickPlay(this.active) } else if(event.keyCode == 37) { if(this.active > 0) { this.onClickPlay(this.active - 1) } } else if(event.keyCode == 39) { if(this.active < this.rows.length - 1) { this.onClickPlay(this.active + 1) } } }, onClickEdit(){ this.$emit('on-click-edit'); } }, computed: { }, watch: { } });
var searchData= [ ['account_2ec',['account.c',['../account_8c.html',1,'']]], ['account_2eh',['account.h',['../account_8h.html',1,'']]], ['address_2ec',['address.c',['../address_2address_8c.html',1,'(Global Namespace)'],['../config_2address_8c.html',1,'(Global Namespace)']]], ['address_2eh',['address.h',['../address_2address_8h.html',1,'(Global Namespace)'],['../config_2address_8h.html',1,'(Global Namespace)']]], ['alias_2ec',['alias.c',['../alias_8c.html',1,'']]], ['alias_2eh',['alias.h',['../alias_8h.html',1,'']]], ['array_2ec',['array.c',['../array_8c.html',1,'']]], ['array_2eh',['array.h',['../array_8h.html',1,'']]], ['attach_2ec',['attach.c',['../attach_8c.html',1,'']]], ['attach_2eh',['attach.h',['../attach_8h.html',1,'']]], ['auth_2ec',['auth.c',['../imap_2auth_8c.html',1,'(Global Namespace)'],['../pop_2auth_8c.html',1,'(Global Namespace)']]], ['auth_2eh',['auth.h',['../auth_8h.html',1,'']]], ['auth_5fanon_2ec',['auth_anon.c',['../auth__anon_8c.html',1,'']]], ['auth_5fcram_2ec',['auth_cram.c',['../auth__cram_8c.html',1,'']]], ['auth_5fgss_2ec',['auth_gss.c',['../auth__gss_8c.html',1,'']]], ['auth_5flogin_2ec',['auth_login.c',['../auth__login_8c.html',1,'']]], ['auth_5foauth_2ec',['auth_oauth.c',['../auth__oauth_8c.html',1,'']]], ['auth_5fplain_2ec',['auth_plain.c',['../auth__plain_8c.html',1,'']]], ['auth_5fsasl_2ec',['auth_sasl.c',['../auth__sasl_8c.html',1,'']]], ['autocrypt_2ec',['autocrypt.c',['../autocrypt_8c.html',1,'']]] ];
import common from './common' import year2016 from './2016/messages' import year2017 from './2017/messages' export default { common, year2016, year2017 }
import React from 'react'; export default function SubmitButton({isMessageSending, onClick}) { if (isMessageSending === true) { return null; } return <button onClick={onClick}>Send</button> }
import React from 'react'; import './Contact.scss' const Contact = props => ( <div className="information"> { props.userData.firstName === undefined || props.userData.lastName === undefined ? null : <span> Выбран пользователь <b>{props.userData.firstName} {props.userData.lastName}</b> </span> } { props.userData.description === undefined ? null : <span> <br /> Описание: <br /> <textarea defaultValue={props.userData.description} disabled></textarea> </span> } { props.userData.address === undefined ? null : <div> <br /> Адрес проживания: <b>{props.userData.address.streetAddress}</b> <br /> Город: <b>{props.userData.address.city}</b> <br /> Провинция/штат: <b>{props.userData.address.state}</b> <br /> Индекс: <b>{props.userData.address.zip}</b> </div> } </div> ) export default Contact
import { put, take, takeEvery, takeLatest, all, call, select } from 'redux-saga/effects' import { delay } from 'redux-saga' import { push } from 'connected-react-router' import { getDateId, filterOfDate } from '../utils' import { launchModal, closeModal, launchLoader, closeLoader, } from '../actions' const filterExerciseList = (dataList, filter) => { let idList = [] dataList.map( exercise => { if (exercise.category == filter) idList.push(exercise.id) }) return Promise.resolve(idList) } function* exerciseListFilter(action) { const filter = action.filter yield put({type: 'EXERCISE_LIST_FILTER_START', filter}) const dataList = yield select(state => { return state.exerciseData.dateList[state.exerciseUI.dateId].map( key => state.exerciseData.data[key] ) }) const filteredList = yield call(filterExerciseList, dataList, filter) yield put({ type: 'EXERCISE_LIST_FILTER_END', filter: action.filter, list: filteredList }) } const getExerciseDateList = (state, dateId) => state.exerciseData.dateList[dateId] || [] export function* exerciseTimeChange(action) { yield put({type: 'EXERCISE_TIME_CHANGE_START'}) yield put(launchLoader()) const { filter, date } = action const dateId = getDateId(date) const newDataList = yield select(state => { console.log(getExerciseDateList(state, dateId)) return getExerciseDateList(state, dateId)//.map( exerciseId => state.exerciseData.data[exerciseId] ) }) const nextDay = new Date(date.getFullYear(), date.getMonth(), date.getDate()+1) const prevDay = new Date(date.getFullYear(), date.getMonth(), date.getDate()-1) const nextDayList = yield select(state => getExerciseDateList(state,getDateId(nextDay))) const prevDayList = yield select(state => getExerciseDateList(state,getDateId(prevDay))) yield put({ type: 'EXERCISE_TIME_CHANGE_END', dateTime: action.date.getTime(), dateId, hasNextDay: nextDayList.length, hasPrevDay: prevDayList.length, filter, list: newDataList }) yield put(closeLoader()) } export default function* exerciseSaga() { yield all([ takeLatest('EXERCISE_LIST_FILTER', exerciseListFilter), takeLatest('EXERCISE_TIME_CHAGNE', exerciseTimeChange), ]) }
'use strict' const path = require('path') const tap = require('tap') const getFullPageTests = require('../lib/getFullPageTests') const baseDir = path.join(__dirname, 'simple') const validFixturesDir = path.join(baseDir, 'fixtures') const validExpectationsDir = path.join(baseDir, 'expectations') const expectedTests = { 'simple-1': { 'meta': { 'name': 'Simple 1' }, 'fixture': path.join(validFixturesDir, 'simple-1.html'), 'expected': { 'expectation': 1 } }, 'simple-2': { 'meta': { 'name': 'Simple 2' }, 'fixture': path.join(validFixturesDir, 'simple-2.html'), 'expected': { 'expectation': 2 } } } tap.strictSame( getFullPageTests(validFixturesDir, validExpectationsDir), expectedTests, 'Full-page tests are returned, with paths to the HTML files')