text
stringlengths
7
3.69M
/** * 复制目录中的所有文件包括子目录 * @param{ String } src需要复制的目录 * @param{ String } dst复制到指定的目录 * */ const fs = require('fs') const stat = fs.stat; const copyFiles = function (src, dst) { return new Promise(((resolve, reject) => { // 读取目录中的所有文件/目录 console.log('读取指定部署目录的所有文件', src) fs.readdir(src, function (err, paths, callback) { if (err) { reject(err); return } console.log('读取到的', paths) paths.forEach(function (path) { const _src = src + '/' + path const _dst = dst + '/' + path let readable; let writable; stat(_src, function (err, st) { if (err) { reject(err); return } // 判断是否为文件 if (st && st.isFile()) { // 创建读取流 readable = fs.createReadStream(_src); // 创建写入流 writable = fs.createWriteStream(_dst); // 通过管道来传输流 readable.pipe(writable); resolve() } // 如果是目录则递归调用自身 else if (st && st.isDirectory()) { existToDest(_src, _dst, copyFiles); } }); }); }); })) }; // 在复制目录前需要判断该目录是否存在,不存在需要先创建目录 const existToDest = function (src, dst, callback) { return new Promise((resolve, reject)=> { fs.stat(dst, function (err, stats) { // 文件夹是否已存在 console.log('判断目标目录是否存在', dst) if (stats && stats.isDirectory()) { callback(src, dst).then(()=> { console.log('已存在目标目录拷贝成功结果') resolve() }).catch((e)=> { reject(e) }); } // 不存在 else { fs.mkdir(dst, function () { callback(src, dst).then(()=> { console.log('不存在目标目录拷贝成功结果') resolve() }).catch((e)=> { reject(e) }); }); } }); }) }; exports.copyFiles = copyFiles; exports.existToDest = existToDest;
import React, {useState} from 'react'; import Icon from 'react-native-vector-icons/MaterialIcons'; import {View, TextInput, ScrollView, Text} from 'react-native'; import firestore from '@react-native-firebase/firestore'; import {doc} from 'prettier'; import {Buttons, NavigationDrawer, SafeArea} from '../../components'; import { BoxAction, BoxForm, BoxHeader, BoxImage, BoxInput, BoxNav, BoxText, Container, TextButton, TextDesc, TextHeader, TextImage, TextTitle, } from './styles'; const CadastroPessoal = () => { // Declarando variáveis para acomodarem as entradas de texto const [namePerson, setNamePerson] = useState(''); const [agePerson, setAgePerson] = useState(-1); const [emailPerson, setEmailPerson] = useState(''); const [statePerson, setStatePerson] = useState(''); const [cityPerson, setCityPerson] = useState(''); const [cepPerson, setCepPerson] = useState(''); const [phonePerson, setPhonePerson] = useState(''); const [username, setUsername] = useState(''); const [password, setPassword] = useState(''); const [passwordConfirmation, setPasswordConfirmation] = useState(''); const AddPersonData = async () => { if (password === passwordConfirmation) { await firestore() .collection('person') .doc(username) .get() .then((documentSnapshot) => { if (documentSnapshot.exists) { console.log('User already exists'); } else { firestore() .collection('person') .doc(username) .set({ age: agePerson, email: emailPerson, name_person: namePerson, state: statePerson, city: cityPerson, CEP: cepPerson, phone: phonePerson, password_user: password, }) .then(() => { console.log('User added!'); }); } }); } else { console.log('Passwords are not the same'); } }; return ( <> <SafeArea color="#cfe9e5" /> <BoxNav /> <BoxAction> <NavigationDrawer color="#434343" backgroundColor="#cfe9e5" /> <TextTitle>Cadastro Pessoal</TextTitle> </BoxAction> <ScrollView> <BoxText> <Text> {namePerson} {agePerson} </Text> </BoxText> <Container> <View style={{justifyContent: 'center', alignItems: 'center'}}> <BoxText> <TextDesc> As informações preenchidas serão divulgadas apenas para a pessoa com a qual você irá realizar o processo de adoção e/ou apadrinhamento, após a formalização do processo. </TextDesc> </BoxText> </View> <BoxForm> <BoxHeader> <TextHeader>INFORMAÇÕES PESSOAIS</TextHeader> </BoxHeader> <BoxInput> <TextInput placeholder="Nome completo" fontFamily="Roboto-Regular" onChangeText={(text) => setNamePerson(text)} /> </BoxInput> <BoxInput> <TextInput placeholder="Idade" fontFamily="Roboto-Regular" onChangeText={(text) => setAgePerson(text)} /> </BoxInput> <BoxInput> <TextInput placeholder="E-mail" fontFamily="Roboto-Regular" onChangeText={(text) => setEmailPerson(text)} /> </BoxInput> <BoxInput> <TextInput placeholder="Estado" fontFamily="Roboto-Regular" onChangeText={(text) => setStatePerson(text)} /> </BoxInput> <BoxInput> <TextInput placeholder="Cidade" fontFamily="Roboto-Regular" onChangeText={(text) => setCityPerson(text)} /> </BoxInput> <BoxInput> <TextInput placeholder="CEP" fontFamily="Roboto-Regular" onChangeText={(text) => setCepPerson(text)} /> </BoxInput> <BoxInput> <TextInput placeholder="Telefone" fontFamily="Roboto-Regular" onChangeText={(text) => setPhonePerson(text)} /> </BoxInput> <BoxHeader> <TextHeader>INFORMAÇÕES DE PERFIL</TextHeader> </BoxHeader> <BoxInput> <TextInput placeholder="Nome de usuário" fontFamily="Roboto-Regular" onChangeText={(text) => setUsername(text)} /> </BoxInput> <BoxInput> <TextInput placeholder="Senha" secureTextEntry fontFamily="Roboto-Regular" onChangeText={(text) => setPassword(text)} /> </BoxInput> <BoxInput> <TextInput placeholder="Confirmação de senha" secureTextEntry fontFamily="Roboto-Regular" onChangeText={(text) => setPasswordConfirmation(text)} /> </BoxInput> <BoxHeader> <TextHeader>FOTO DE PERFIL</TextHeader> </BoxHeader> </BoxForm> <View style={{justifyContent: 'center', alignItems: 'center'}}> <BoxImage> <Icon name="control-point" size={30} color="#757575" /> <TextImage>adicionar foto</TextImage> </BoxImage> </View> <View style={{justifyContent: 'center', alignItems: 'center'}}> <Buttons.Rectangular color="#88c9bf" marginTop="32px" marginBottom="24px" onPress={() => AddPersonData()}> <TextButton>FAZER CADASTRO</TextButton> </Buttons.Rectangular> </View> </Container> </ScrollView> </> ); }; export default CadastroPessoal;
import React from 'react'; import ActivityList from './activityList'; import {serverFetch} from '../../../utils/clientFetch'; export default { path: '/', async action({cookie}) { let result =await serverFetch(cookie,'/activitys/findlist',{page: 1,pagesize: 10}); if(result.code !== 200) result = {code:200,data: {list:[]}}; return <ActivityList list={{...result}} />; }, };
(function() { var ctrls = angular.module(MyAppConfig.controllers); ctrls.controller('ManageUserInfoCtrl', ['$scope', '$log','DataService','DialogService', ManageUserInfoCtrl]); function ManageUserInfoCtrl($scope, $log,DataService,DialogService) { $log.debug('ManageUserInfoCtrl init...'); // 处理scope销毁 $scope.$on('$destroy', function() { $log.debug('ManageUserInfoCtrl destroy...'); }); $scope.queryUser=function(){ DataService.send('/adminuser/getUserInfo',{},function(data){ $scope.userinfo=data.datas.user; }); }; $scope.queryUser(); $scope.logout=function(){ DialogService.showWait('安全退出中,请稍后...'); DataService.send('/adminuser/logout',{},function(data){ DialogService.hideWait(); DialogService.showAlert(data.message,function(){ //不推荐使用原始方式跳转 location='/#!/route/page/manage/index'; }); }); }; } })();
var searchData= [ ['towntile',['TownTile',['../class_game_1_1_town_tile.html',1,'Game']]] ];
$(document).ready(function() { if (window.DeviceMotionEvent) { var speed = 10; var x = y = z = lastX = lastY = lastZ = 0; var flag = 0; window.addEventListener('devicemotion', function() { var acceleration = event.accelerationIncludingGravity; x = acceleration.x; y = acceleration.y; z = acceleration.z; if (Math.abs(x - lastX) > speed || Math.abs(y - lastY) > speed || Math.abs(z - lastZ) > speed) { if (!flag) { flag = 1; var $yaoyiyao = $('.yaoyiyao') var $chouqian = $('.chouqian') var $chouqian_img = $('.chouqian_img') var $load = $('.load') var $result = $('.result') var $bg = $('.bg') $yaoyiyao.hide() $chouqian.show() $chouqian_img.show() setTimeout(function() { $chouqian_img.hide() $load.show() } , 1000) setTimeout(function() { $chouqian.hide() $load.hide() $bg.addClass('bg_result') $result.show() alert('one') }, 2500) } } lastX = x; lastY = y; lastZ = z; }, false); } });
const knex = require('../../../database/database'); async function getUsers(request, response, next) { try { const users = await knex('users'); return response.status(200).send({ status: 200, data: users }); } catch (err) { next(err); } } module.exports = getUsers;
angular .module('myApp.services') .service('TestService', testService); function testService() { var testVar = {}; testVar.name="test"; testVar.testFunction = function(){ console.log("Inside test service."); return testVar.name; } return testVar; } // end of testService()
import mongoose from 'mongoose'; import uniqueValidator from 'mongoose-unique-validator'; const Schema = mongoose.Schema; let UserSchema = new Schema({ username: {type: String, required: [true, "can't be blank"], unique: true, lowercase: true, index: true}, email: {type: String, required: [true, "can't be blank"], unique: true, lowercase: true, index: true}, password: {type: String, required: false}, createdOn: {type: Date, required: true}, lastModifiedOn: {type: Date, required: true}, lastLoginOn: {type: Date, required: true} }, { timestamps: false }); UserSchema.plugin(uniqueValidator, { message: "is already taken" }); export { UserSchema };
const mongoose = require("mongoose"); const Schema = mongoose.Schema; //Option to not delete posts, this is why we're using this const RoomSchema = new Schema({ user: { type: Schema.Types.ObjectId, ref: "users" }, name: { type: String }, description: { type: String }, images: { type: Array, default: [] }, limit: { type: Number, default: 1 }, price: { type: Number }, tipeKamar: { type: String }, info_kamar: { luas_kamar: { type: Number, default: 0 }, tamu: { type: Number, default: 0 } }, fasilitas_kamar_mandi: { air_panas: { type: Boolean, default: false }, shower: { type: Boolean, default: false }, hair_driyer: { type: Boolean, default: false }, pribadi: { type: Boolean, default: false } }, fasilitas: { ac: { type: Boolean, default: false }, tv: { type: Boolean, default: false }, bedtype: { type: String, default: false }, wifi: { type: Boolean, default: false }, other: { type: Array, default: [] } }, wishList: [ { user: { type: Schema.Types.ObjectId, ref: 'users' } } ], rating: { data: [ { user: { type: Schema.Types.ObjectId, ref: 'users' } } ] }, date: { type: Date, default: Date.now } }) module.exports = Room = mongoose.model("room", RoomSchema);
'use strict'; const utils = require('../../utils'); const config = require('../../../../database/config'); const querys = require('./query'); const sql = require('mssql'); const getMessage = async () => { try { let pool = await sql.connect(config.sql); // const sqlQueries = await utils.loadSqlQueries('message'); const eventsList = await pool.request().query(querys.eventMessage); return eventsList.recordset; } catch (error) { console.log(error.message); } } const getSliderMessage = async () => { try { let pool = await sql.connect(config.sql); // const sqlQueries = await utils.loadSqlQueries('message'); const eventsList = await pool.request().query(querys.eventSliderMessage); return eventsList.recordset; } catch (error) { console.log(error.message); } } module.exports = { getMessage, getSliderMessage }
function mostrar() { var edad; edad = parseInt(document.getElementById('edad').value); if(edad >= 18 && edad < 100){ alert("Es mayor de edad"); } else if(edad < 18 && edad >= 0){ alert("Es menor de edad"); } else if(edad > 100 || edad < 0){ alert("ME TAS JODIENDO"); } } /* Al ingresar una edad debemos informar si la persona es mayor de edad, sino informar que es un menor de edad. */
const iconsInvitationCardsCopy = { "en": { "INVITATIONCARDS": {} }, "kr": { "INVITATIONCARDS": {} }, "ch": { "INVITATIONCARDS": {} }, "jp": { "INVITATIONCARDS": {} } } export default iconsInvitationCardsCopy;
app.factory("playerInfoDbService", ["$http", function ($http) { var playerInfoDbService = {}; playerInfoDbService.get = function(players) { var body = { players: JSON.stringify(players) }; return $http({ method: 'POST', url: 'api/current-user/player-info', data: $.param(body), headers: {'Content-Type': 'application/x-www-form-urlencoded'} }) .then(function(playerInfoDbs) { return playerInfoDbs.data; }); }; return playerInfoDbService; }]);
import React from "react"; import { HashRouter as Router, Switch, Route } from "react-router-dom"; import Provider from "./components/Context"; // Main Page import Main from "./components/Main/Index"; // Search import Search from "./components/Search/Index"; // Course import Course from "./components/Course/Index"; // User // Login import Login from "./components/User/Login"; // Register import Register from "./components/User/Register"; // Forgot Password import ForgotPassword from "./components/User/ForgotPassword"; // Forgot Password import ResetPassword from "./components/User/ResetPassword"; export default function App() { window.APIUrl = "https://portfolio-server-vl.herokuapp.com/vault"; return ( <Provider> <Router> <Switch> <Route exact path="/" component={Main} /> <Route exact path="/search/:query" component={Search} /> <Route exact path="/course/:courseUrl" component={Course} /> <Route exact path="/login" component={Login} /> <Route exact path="/register" component={Register} /> <Route exact path="/forgotpassword" component={ForgotPassword} /> <Route exact path="/resetpassword/:token" component={ResetPassword} /> </Switch> </Router> </Provider> ); }
import React, { Component } from 'react' import {InputGroup, Button, FormControl} from 'react-bootstrap'; import './ButtonSelection.css'; export default class InputWithSubmit extends Component { constructor(props){ super(props); this.textInput = React.createRef(); } handleApply(e){ let data = { key: this.props.title, value: this.textInput.current.value }; this.props.applyCB(data); } render() { return ( <InputGroup size="sm" className="mb-3 btn-group-sm inBox"> <InputGroup.Prepend> <InputGroup.Text className="logName">{this.props.title}</InputGroup.Text> </InputGroup.Prepend> <FormControl placeholder={this.props.placeholder} aria-label={this.props.title} aria-describedby="basic-addon2" ref={this.textInput} type={this.props.type} /> <InputGroup.Append> <Button variant="outline-secondary" onClick={(e)=>{this.handleApply(e)}}>Apply</Button> </InputGroup.Append> </InputGroup> ) } }
import React, {PureComponent} from 'react'; import {Modal} from 'antd'; import styles from '../../common/global.less'; const omService = require('../../services/om'); const errorCode = require('../../common/errorCode'); class OmModal extends PureComponent { state = { visible: false, log: '', }; componentDidMount() { this.props.onRef(this); } componentDidUpdate() { if (this.log) { this.log.scrollTop = this.log.scrollHeight; } } onShow(opId) { this.setState({ visible: true, log: '', }, () => this.askOmLog(opId, 0)); } askOmLog(opId, index) { if (!this.state.visible) { return; } omService.askOmLog({opId:opId, index:index}).then(response => { if (response.result === errorCode.SUCCESS) { const logs = response.logs; if (logs.length > 0) { index += logs.length; let log = this.state.log + logs.join('\n') + '\n'; this.setState({ log: log, }); } if (response.opResult === undefined) { setTimeout(this.askOmLog.bind(this), 1000, opId, index); } } }) } onCancel = () => { this.setState({ visible: false, }); }; render() { const {visible, log} = this.state; return ( <Modal width={800} title='操作进度' wrapClassName="vertical-center-modal" visible={visible} footer={null} onCancel={this.onCancel} > <pre className={styles.modalContent} ref={ele => this.log = ele}> {log} </pre> </Modal> ); } } export default OmModal;
import request from '@/utils/request' export function getAll(query) { return request({ url: '/salesManagement/list', method: 'get', params: query }) }
(function() { /** * Constant variable for search term. */ var SEARCH_TERM = 'tf_allow_load=yeah'; /* * Cache to reduce access to localStorage. * @type {boolean} */ var tfEnabled = undefined; /** * A list of urls that users explicitly allow to load */ var urlWhiteList = []; var isEnabled = function() { if (tfEnabled === undefined) { // Be careful, in localStorage, it's all string. tfEnabled = localStorage['TF_ENABLED'] === 'true'; } return tfEnabled; }; var setEnabled = function(enabled) { localStorage['TF_ENABLED'] = enabled; tfEnabled = enabled; }; var toggleEnabled = function() { setEnabled(isEnabled() ? false : true); }; var updateIcon = function() { if (isEnabled()) { chrome.browserAction.setIcon({path: 'icon-on-19x19.png'}); } else { chrome.browserAction.setIcon({path: 'icon-19x19.png'}); } }; var onBeforeRequestUrl = function(details) { var url = details.url; if (url === chrome.extension.getURL('bg-loading.png') || url === chrome.extension.getURL('bg.png')) { return {}; } for (var i = 0; i < urlWhiteList.length; i = i + 1) { if (url === urlWhiteList[i]) { return {}; } } var parser = document.createElement('a'); parser.href = url; if (parser.search.indexOf(SEARCH_TERM) !== -1) { // Don't send the search term to server var search = parser.search; var startIndex = search.indexOf(SEARCH_TERM) - 1; var endIndex = startIndex + SEARCH_TERM.length; var newSearch = search.substring(0, startIndex) + search.substring(endIndex + 1, search.length); parser.search = newSearch.length == 0 ? null : newSearch; urlWhiteList.push(parser.href); return {redirectUrl: parser.href}; } return {redirectUrl: chrome.extension.getURL('bg.png')}; }; var updateListeners = function() { if (isEnabled()) { chrome.webRequest.onBeforeRequest.addListener( onBeforeRequestUrl, { urls: ['<all_urls>'], types: ['image']}, ['blocking']); chrome.webRequest.onBeforeRequest.addListener( onBeforeRequestUrl, { urls: ['<all_urls>'], types: ['object']}, ['blocking']); // No need to send a message to all tabs // to add a 'addTextFirstClickListener' listener } else { chrome.webRequest.onBeforeRequest.removeListener(onBeforeRequestUrl); chrome.webRequest.onBeforeRequest.removeListener(onBeforeRequestUrl); // Send a message to all tabs // to remove a 'addTextFirstClickListener' listener chrome.tabs.query({currentWindow: true}, function(tabs) { for (var i = 0; i < tabs.length; i = i + 1) { chrome.tabs.sendMessage( tabs[i].id, {method: 'removeTextFirstClickListener'} ); } }); } }; chrome.runtime.onMessage.addListener( function(request, sender, sendResponse) { if (request.method === 'doAddTextFirstClickListener') { if (isEnabled()) { chrome.tabs.sendMessage( sender.tab.id, {method: 'addTextFirstClickListener'} ); } else { chrome.tabs.sendMessage( sender.tab.id, {method: 'removeTextFirstClickListener'} ); } } } ); chrome.browserAction.onClicked.addListener(function(tab) { toggleEnabled(); updateIcon(); updateListeners(); urlWhiteList = []; }); updateIcon(); updateListeners(); }());
import { black, white, blue2, alert, completion, grey1 } from './private/palette'; export default { '.black': { color: black }, '.white': { color: white }, '.critical': { color: alert }, '.positive': { color: completion }, '.secondary': { color: grey1 }, '.formAccent': { color: blue2 }, '.neutral': { color: black } };
import React, { useState, useRef, useImperativeMethods, forwardRef, } from 'react' import PropTypes from 'prop-types' const TextBox = forwardRef(({ name, initialValue, label, type }, ref) => { const [value, setValue] = useState(initialValue) const handleChange = e => setValue(e.target.value) const inputRef = useRef() useImperativeMethods(ref, () => ({ getValue: () => inputRef.current.value, })) return ( <div className="form-row_container"> <label> {label || ''} <input ref={inputRef} name={name} onChange={handleChange} value={value} type={type} /> </label> </div> ) }) TextBox.displayName = 'ReactFormElements(TextBox)' export default TextBox TextBox.propTypes = { name: PropTypes.string, initialValue: PropTypes.string, label: PropTypes.string, type: PropTypes.string, } TextBox.defaultProps = { name: 'TextBox', initialValue: '', type: 'text', label: 'label', }
import { pick } from 'lodash'; export const SET_MODE = 'EDITOR/SET_MODE'; export const setMode = (mode) => ({ type: SET_MODE, mode, }); export const SET_SHAPE = 'EDITOR/SET_SHAPE'; export const setShape = (shape) => ({ type: SET_SHAPE, shape, }); export const SET_STYLE = 'EDITOR/SET_STYLE'; export const setStyle = (style) => ({ ...pick(style, [ 'fill', 'fillColor', 'fontSize', 'stroke', 'strokeColor', 'strokeWidth', ]), type: SET_STYLE, }); export const SET_SNAP = 'EDITOR/SET_SNAP'; export const setSnap = (snap) => ({ type: SET_SNAP, snap, }); export const BEGIN_EDIT = 'EDITOR/BEGIN_EDIT'; export const beginEdit = ({ x, y, id }) => ({ type: BEGIN_EDIT, x, y, id, }); export const UPDATE_EDIT = 'EDITOR/UPDATE_EDIT'; export const updateEdit = ({ x, y }) => ({ type: UPDATE_EDIT, x, y, }); export const END_EDIT = 'EDITOR/END_EDIT'; export const endEdit = () => ({ type: END_EDIT, }); export const CANCEL_EDIT = 'EDITOR/CANCEL_EDIT'; export const cancelEdit = () => ({ type: CANCEL_EDIT, }); export const BEGIN_MOVE = 'EDITOR/BEGIN_MOVE'; export const beginMove = (id) => ({ type: BEGIN_MOVE, id, }); export const UPDATE_MOVE = 'EDITOR/UPDATE_MOVE'; export const updateMove = (x, y) => ({ type: UPDATE_MOVE, x, y, }); export const END_MOVE = 'EDITOR/END_MOVE'; export const endMove = () => ({ type: END_MOVE, }); export const PUSH_HISTORY = 'EDITOR/PUSH_HISTORY'; export const pushHistory = () => ({ type: PUSH_HISTORY, });
function initTab(){ // Proprietes fonctionnelles du tableau PSDR var rows = document.getElementsByTagName('tr'); var nbRows = rows.length; var jEntete; var notfound = true; var j = 0; //recherche de la premiere ligne entete while(notfound & j<nbRows){ if(rows[j].cells[0].className == 'EnteteTab'){ notfound = false; jEntete = j; } else{ j++; } } var nbCols = rows[jEntete].cells.length; //parcours du tableau for(j=jEntete; j<nbRows; j++){ for(i=0; i<nbCols; i++) { var cellule = rows[j].cells[i]; switch(cellule.className) { case 'EnteteTab': // cellule.style.backgroundColor = 'red'; break; case 'TabGauche': if (i==3){ // cellule.style.backgroundColor = 'blue'; cellule.id = "NRA-"+j; cellule.onclick = function(){LeftPartClick(this)}; cellule.onmouseenter = function(){LeftPartMouseOver(this)}; } else{ // cellule.style.backgroundColor = 'blue'; cellule.id = ""+j+"-"+i; cellule.onclick = function(){LeftPartClick(this)}; cellule.onmouseenter = function(){LeftPartMouseOver(this)}; } break; case 'TabDroite': // cellule.style.backgroundColor = 'green'; cellule.id = ""+j+"-"+i; cellule.ondblclick = function(){RightPartDbClick(this)}; cellule.onmouseenter = function(){RightPartMouseOver(this)}; break; } } } } //Fonctionnalitées par parties function RightPartDbClick(monid) { var partsArray = monid.id.split('-'); var j = partsArray[0]; var i = partsArray[1]; var CodeNRA = document.getElementById('NRA-'+j).innerHTML; var OPDSLAM = document.getElementsByClassName('EnteteTab')[i].getElementsByTagName('div')[0].innerHTML; ///////////////////////////////////////////// RECUP Données //////////////////////////////////////// //// Valeur /// document.getElementById('Valeur').value = document.getElementById(monid.id).innerHTML; ///////// CHamp COmmentaire /////////////////////// ///// OMAR : $.ajax({ type: "GET", url: "CommentaireOMAR.php?Nra="+CodeNRA+"&OP="+OPDSLAM+"", dataType : "text", error:function(msg, string){ alert( "Error !: " + string ); }, success:function(data){ document.getElementById('OMAR').value = data; } }); //// PROG : $.ajax({ type: "GET", url: "CommentaireProg.php?Nra="+CodeNRA+"&OP="+OPDSLAM+"", dataType : "text", error:function(msg, string){ alert( "Error !: " + string ); }, success:function(data){ document.getElementById('Prog').value = data; } }); //////////////////Ouvre la fenetre OP DSLAM ////////////////////////////////////// $( "#FenetreOPDslam" ).dialog( "open" ); //////////////////////////UPDATE //////////////////////////////////////////////////////// document.getElementById('Valeur').onchange = function(){ var Valeur = document.getElementById('Valeur').value; // Update valeur $.ajax({ type: "POST", url: "ModifBD.php?Nra="+CodeNRA+"&OP="+OPDSLAM+"&Valeur="+Valeur+"", dataType : "text", error:function(msg, string){ alert( "Error !: " + string ); }, success:function(data){ document.getElementById(monid.id).innerHTML = Valeur; } }); }; //On change OMAR document.getElementById('OMAR').onchange = function(){ var Valeur = document.getElementById('OMAR').value; // Update OMAR $.ajax({ type: "POST", url: "ModifBDCommentaire.php?Nra="+CodeNRA+"&OP="+OPDSLAM+"&OMAR="+Valeur+"", dataType : "text", error:function(msg, string){ alert( "Error !: " + string ); }, success:function(data){ //nothing //alert(Valeur); } }); }; //On change Prog document.getElementById('Prog').onchange = function(){ var Valeur = document.getElementById('Prog').value; // Update Prog $.ajax({ type: "POST", url: "ModifBDCommentaire.php?Nra="+CodeNRA+"&OP="+OPDSLAM+"&Prog="+Valeur+"", dataType : "text", error:function(msg, string){ alert( "Error !: " + string ); }, success:function(data){ //nothing //alert(Valeur); } }); }; } function LeftPartClick(monid) { //Ouvre la fenetre NRA var partsArray = monid.id.split('-'); var j = partsArray[0]; var i = partsArray[1]; var CodeNRA; if(monid.id == "NRA-"+i){ CodeNRA = monid.innerHTML; } else{ CodeNRA = document.getElementById('NRA-'+j).innerHTML; } $.ajax({ type: "GET", url: "Fenetre_nra.php?nra="+CodeNRA+"", dataType : "text", error:function(msg, string){ alert( "Error !: " + string ); }, success:function(data){ /////////////////////SI SUCCES //////////////////// document.getElementById('fenetre_nra').innerHTML = data, $( "#fenetre_nra" ).dialog( "open" ); document.getElementById('create-user').onclick = function(){OuvertureFentreFormulaire(CodeNRA)}; ////////////////Param Tableau ////////////////////////////OuvertureFentreFormulaire var TabOP = document.getElementsByClassName("TabNRA"); var ligneTab = TabOP.length; var ColTab = TabOP[0].cells.length; //Parcours de lignes for(n=0; n<ligneTab; n++){ //Parcours des colonees for(k=0; k<ColTab; k++){ // TabOP[n].cells[k].style.backgroundColor = 'green'; TabOP[n].cells[k].onclick = function(){OuvertureFentreOPTrans(this)}; } } /////////////////////////// Recupere donnée COmmentaire NRA $.ajax({ type: "GET", url: "CommentaireTRANS.php?Nra="+CodeNRA+"", dataType : "text", error:function(msg, string){ alert( "Error !: " + string ); }, success:function(data){ //alert(data); document.getElementById('ComNra').value = data; } }); ///////////////// Update du commentaire /////////////////////////// document.getElementById('ComNra').onchange = function(){ alert("detection changement"); var Valeur = document.getElementById('ComNra').value; // Update Prog $.ajax({ type: "POST", url: "ModifBDCommentaire.php?Nra="+CodeNRA+"&ComNra="+Valeur+"", dataType : "text", error:function(msg, string){ alert( "Error !: " + string ); }, success:function(data){ //nothing alert(Valeur); alert(data); } }); }; //////////////FIN SUCCES ////////////// } //FIn ajax }); } function RightPartMouseOver(monid) { //Au passage de la souris var partsArray = monid.id.split('-'); var j = partsArray[0]; var i = partsArray[1]; var CodeNRA = document.getElementById('NRA-'+j).innerHTML; var OPDSLAM = document.getElementsByClassName('EnteteTab')[i].getElementsByTagName('div')[0].innerHTML; $.ajax({ type: "GET", url: "CommentaireDSLAM.php?Nra="+CodeNRA+"&OP="+OPDSLAM+"", dataType : "text", error:function(msg, string){ alert( "Error !: " + string ); }, success:function(data){ // color(); document.getElementById(monid.id).title = data; } }); } function LeftPartMouseOver(monid) { //Au passage de la souris var partsArray = monid.id.split('-'); var j = partsArray[0]; var i = partsArray[1]; var CodeNRA; if(monid.id == "NRA-"+i){ CodeNRA = monid.innerHTML; } else{ CodeNRA = document.getElementById('NRA-'+j).innerHTML; } $.ajax({ type: "GET", url: "CommentaireTRANS.php?Nra="+CodeNRA+"", dataType : "text", error:function(msg, string){ alert( "Error !: " + string ); }, success:function(data){ document.getElementById(monid.id).title = data; } }); } function OuvertureFentreOPTrans(monid){ // Traitement pour passer en parametre l'ID OP Trans. $.ajax({ type: "GET", url: "fenetre_DetailOPtrans.php?Type=WDM", dataType : "text", error:function(msg, string){ alert( "Error !: " + string ); }, success:function(data){ /////////////////////SI SUCCES //////////////////// document.getElementById('FenetreDetailOPtrans').innerHTML = data, $( "#FenetreDetailOPtrans" ).dialog( "open" ); } }); } function OuvertureFentreFormulaire(monid){ $.ajax({ type: "GET", url: "Fenetre_Nouvelle_Op.php?nra="+monid, dataType : "text", error:function(msg, string){ alert( "Error !: " + string ); }, success:function(data){ /////////////////////SI SUCCES //////////////////// document.getElementById('dialog-form').innerHTML = data, $( "#dialog-form" ).dialog( "open" ); $(document).ready(function(){ // On cache le div $("#form_FO").hide(); $("#form_FH").hide(); $("#form_WDM").hide(); //un datepicker pour chaque div $(".DateFO").datepicker({ dateFormat: 'yy-dd-mm' }); $(".DateFH").datepicker({ dateFormat: 'yy-dd-mm' }); $(".DateWDM").datepicker({ dateFormat: 'yy-dd-mm' }); $(function(value) { $("#NomFO").autocomplete({ source : 'autocomplet.php?type=fo&nomfo='+value, minLength: 1, dataType : 'json', error:function(msg, string){ alert( "Error !: " + string ); }, success:function(data){ document.getElementById('NomFO').innerHTML = data; } }); }); $(function(value) { $("#NomFH").autocomplete({ source : 'autocomplet.php?nomfh='+value, minLength: 1, dataType : 'json', error:function(msg, string){ alert( "Error !: " + string ); }, success:function(data){ document.getElementById('NomFH').innerHTML = data; } }); }); $(function(value) { $("#NomWDM").autocomplete({ source : 'autocomplet.php?nomwdm='+value, minLength: 1, dataType : 'json', error:function(msg, string){ alert( "Error !: " + string ); }, success:function(data){ document.getElementById('NomWDM').innerHTML = data; } }); }); $(function(value) { $("#op_declencheuse").autocomplete({ source : 'autocomplet.php?op_declencheuse='+value+'&codenra='+monid, minLength: 1, dataType : 'json', error:function(msg, string){ alert( "Error !: " + string ); }, success:function(data){ document.getElementById('op_declencheuse').innerHTML = data; } }); }); }); } }); } function find_caract_FO(value){ $(document).ready(function(){ $.ajax({ type: "GET", url: "parametre_operation.php?NomOp=" + value, dataType : 'json', error:function(msg, string){ alert( "Error ! : " + string ); }, success:function(data){ document.getElementById('NbFO').value = data[0]; document.getElementById('Km_FO').value = data[1]; document.getElementById('RPL_FO').value = data[2]; document.getElementById('Cout_FO').value = data[3]; document.getElementById('Date_FO').value = data[4]; } }); }); } function find_caract_FH(value){ $(document).ready(function(){ $.ajax({ type: "GET", url: "parametre_operation.php?NomOp=" + value, dataType : 'json', error:function(msg, string){ alert( "Error ! : " + string ); }, success:function(data){ document.getElementById('NbFH').value = data[0]; document.getElementById('NbBonds_FH').value = data[1]; document.getElementById('RPL_FH').value = data[2]; document.getElementById('Cout_FH').value = data[3]; document.getElementById('Date_FH').value = data[4]; } }); }); } function find_caract_WDM(value){ $(document).ready(function(){ $.ajax({ type: "GET", url: "parametre_operation.php?NomOp=" + value, dataType : 'json', error:function(msg, string){ alert( "Error ! : " + string ); }, success:function(data){ document.getElementById('NbCreation').value = data[0]; document.getElementById('NbExtensions').value = data[1]; document.getElementById('NbBonds_WDM').value = data[2]; document.getElementById('RPL_WDM').value = data[3]; document.getElementById('Cout_WDM').value = data[4]; document.getElementById('Date_WDM').value = data[5]; } }); }); } function reset_all(){ //A compléter pour que cela fonctionne pour une recherche nra et boucle... fonctionnel uniquement pour un dr sélect en premier ! $(document).ready(function(){ var param1 = document.getElementById("liste_dr").value; $.ajax({ type: "GET", url: "tab.php?param1=" + param1, dataType : "html", error:function(msg, string){ alert( "Error !: " + string ); }, success:function(data){ document.getElementById('test').innerHTML = data; $('#tbl_MytableID').princeFilter(); } }); }); } /* TRES LENT ... AJOUT/SUPRESSION CLASSE HOVER... TRAITEMENT LONG DU AU NOMBRE DE LIGNE function color(){ var allCells = $("td, th"); allCells.on("mouseover", function() { var el = $(this),pos = el.index(); el.parent().find("th, td").addClass("hover"); allCells.filter(":nth-child(" + (pos+1) + ")").addClass("hover"); }) .on("mouseout", function() { allCells.removeClass("hover"); }); }; */
const Admin = require('../models/adminModel'); require('dotenv').config(); const superadmin = (req, res, next) => { Admin.findOne({ email: req.admin_email }, (err, admin) => { if (admin.role !== 1) return res.json({ success: false, message: 'Anda tidak memiliki akses' }); else { next(); } }); }; module.exports = { superadmin };
import { Navbar } from 'react-bootstrap'; import { Link } from 'react-router'; import React, { Component } from 'react'; import './Nav.css'; export default class Navigation extends Component { render() { return (<Navbar> <Navbar.Header> <Navbar.Brand> <Link className="link" href="/">Список заметок</Link> <Link className="link" href="/setting">Настройка сериалов</Link> <Link className="link" href="/spoiler">Добавить спойлер</Link> <Link className="link" href="/login">Вход</Link> <Link className="link" href="/register">Регистрация</Link> </Navbar.Brand> </Navbar.Header> </Navbar> ); } }
import React, { Component } from "react"; import "./App.css"; import ContactForm from "./components/ContactForm"; import Contacts from "./components/Contacts"; class App extends Component { state = { contacts: [ { id: 1, firstName: "Jan", lastName: "Nowak", email: "jan.nowak@example.com" }, { id: 2, firstName: "Adam", lastName: "Kowalski", email: "adam.kowalski@example.com" }, { id: 3, firstName: "Zbigniew", lastName: "Koziol", email: "zbigniew.koziol@example.com" }, { id: 4, firstName: "Mirek", lastName: "Dresler", email: "m.dresler@wp.pl" } ] }; render() { return ( <div className="app"> <React.Fragment> <main className="container"> <ContactForm /> <Contacts contacts={this.state.contacts} /> </main> </React.Fragment> </div> ); } } export default App;
const mongoose = require("mongoose"); const validator = require("validator") const { ObjectId } = mongoose.Schema.Types; const propertySchema = new mongoose.Schema({ name:{ type:String, required:true, }, location:{ type:String, required:true, }, BHK:{ type:String, required:true, }, price:{ type:Number, required:true, }, state_of_property:{ type:String, required:true, }, img:{ type:String, // required:true, }, img2:{ type:String, // required:true, }, img3:{ type:String, // required:true, }, img4:{ type:String, // required:true, }, userId:{ type:ObjectId, ref:"usertables" }, about:{ type:String, required:true, }, floor:{ type:String, required:true, }, launch_date:{ type:String, required:true, }, property_type:{ type:String, required:true, }, project_area:{ type:String, required:true, }, pin_code:{ type:String, required:true, // maxlength:6, }, full_address:{ type:String, required:true, // minlength:20, }, highlight1:{ type:String, required:true, }, highlight2:{ type:String, // required:true, }, highlight3:{ type:String, // required:true, }, disclaimer:{ type:String, required:true, }, total_towers:{ type:Number, }, possession_by:{ type:String, }, total_unit:{ type:Number, }, occupancy_certificate:{ type:Boolean, required:true, }, commencement_certicate:{ type:Boolean, }, price_trends:{ type:Number, // required:true, }, near_by:{ type:String, required:true, minlength:10, }, detail:{ type:String, required:true, minlength:20, }, reviewed:{ type:String, enum:["Rejected","Approved","Not Set","Sold Out"], default:"Not Set" }, latitude:{ type:Number, required:true, }, longitude:{ type:Number, required:true, }, }) const propertyModel = mongoose.model("propertytables", propertySchema); module.exports = propertyModel;
import React, {Component, PropTypes} from 'react'; import {findWhere, bindAll} from 'underscore'; import Toggle from 'react-toggle'; import Icon from '../shared/Icon.jsx'; import SettingsActions from '../../actions/settingsActions'; class NotificationsList extends Component { constructor(props) { super(props); bindAll(this, 'toggleNotificationSetting'); } toggleNotificationSetting(event) { const {notifications, channel} = this.props; const channelNotifications = findWhere(notifications, {channelName: channel}); channelNotifications[event.target.id] = !channelNotifications[event.target.id]; SettingsActions.updateNotification(channelNotifications); } renderDefault() { return ( <div className="notifications__list--empty"> <Icon type="fa" name="bell-slash-o" /> <p> No channels configured for notifications. </p> <p> Add your first one here. </p> </div> ); } renderNotificationsList() { const {notifications, channel} = this.props; if (channel === undefined || !notifications.length) { return this.renderDefault(); } const channelNotifications = findWhere(notifications, {channelName: channel}); if (!channelNotifications) { return null; } return ( <div> <div className="notifications__setting"> <div className="notifications__setting-title"> <span> On Failure </span> </div> <div className="notifications__setting-description"> <span> Send a notification every time this build fails </span> </div> <div className="notifications__setting-toggle"> <Toggle id="onFail" onChange={this.toggleNotificationSetting} checked={channelNotifications.onFail} /> </div> </div> <div className="notifications__setting"> <div className="notifications__setting-title"> <span> On Success </span> </div> <div className="notifications__setting-description"> <span> Send a notification every time this build succeeds </span> </div> <div className="notifications__setting-toggle"> <Toggle id="onFinish" onChange={this.toggleNotificationSetting} checked={channelNotifications.onFinish} /> </div> </div> <div className="notifications__setting"> <div className="notifications__setting-title"> <span> On Status Change </span> </div> <div className="notifications__setting-description"> <span> Send a notification when this build breaks or recovers </span> </div> <div className="notifications__setting-toggle"> <Toggle id="onChange" onChange={this.toggleNotificationSetting} checked={channelNotifications.onChange} /> </div> </div> </div> ); } render() { return ( <div className="notifications__list"> {this.renderNotificationsList()} </div> ); } } NotificationsList.propTypes = { notifications: PropTypes.array.isRequired, channel: PropTypes.string }; export default NotificationsList;
//////////////////////////////////////////////////////////////////////////// //系统务接口start /////////////////////////////////////////////////////////////////////////// /*************************************************************/ /** * 功能:发送心跳包,根据客户端的活跃度(最后收到服务器,或者发送到服务器的时间),在一定的时间内发生心跳给服务器,用以验证连接是否正常<br> * "action": "1.000" * "method": "1.1.0001" */ var request = { "head" : { "name" : "", "action" : "1.000", "method" : "1.1.0001", "version" : "1", "time" : 0 }, "body" : {} }; var response = { "head" : { "resultCode" : "1", "resultMessage" : "", "name" : "", "action" : "1.000", "method" : "1.1.0001", "version" : "1", "time" : 1519378409028 }, "info" : { "success" : true, "errors" : [], "warnings" : [] }, "body" : {} };
import React from "react"; import "./SideNav.css"; import { imagePath } from "../../Services"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { faTachometerAlt } from "@fortawesome/free-solid-svg-icons"; import { faFileAlt } from "@fortawesome/free-solid-svg-icons"; import { faTruck } from "@fortawesome/free-solid-svg-icons"; import { faDatabase } from "@fortawesome/free-solid-svg-icons"; import { faIdCard } from "@fortawesome/free-solid-svg-icons"; import { Link, NavLink } from "react-router-dom"; export default function SideNav() { return ( <div> <div className="d-flex flex-column flex-shrink-0 p-3 sidebar"> <Link to="/dashboard"> <a href="/" className="d-flex align-items-center mb-3 mb-md-0 me-md-auto text-white text-decoration-none" > <div className="d-flex justify-content-center"> <img src={imagePath + `logo.png`} alt="" className="logo-sidebar" /> </div> <span className="fs-4"></span> </a> </Link> <hr /> <ul className="nav nav-pills flex-column mb-auto"> <li> <NavLink to="/dashboard" activeClassName="active" className="nav-link mt-2 mb-2 text-white" > <div className="row"> <div className="col-4"> <FontAwesomeIcon icon={faTachometerAlt} size="2x" /> </div> <div className="col-8 text-start mt-2 ">Dashboard</div> </div> </NavLink> </li> <li className="nav-item"> <NavLink to="/orderList" activeClassName="active" className="nav-link mt-2 mb-2 text-white" > <div className="row"> <div className="col-4"> <FontAwesomeIcon icon={faFileAlt} size="2x" /> </div> <div className="col-8 text-start mt-2">Orders</div> </div> </NavLink> </li> <li> <NavLink to="/inventoryList" activeClassName="active" className="nav-link mt-2 mb-2 text-white" > <div className="row"> <div className="col-4"> <FontAwesomeIcon icon={faDatabase} size="2x" /> </div> <div className="col-8 text-start mt-2">Inventory</div> </div> </NavLink> </li> <li> <NavLink to="/deliveryList" activeClassName="active" className="nav-link mt-2 mb-2 text-white" > <div className="row"> <div className="col-4"> <FontAwesomeIcon icon={faTruck} size="2x" /> </div> <div className="col-8 text-start mt-2">Deliveries</div> </div> </NavLink> </li> <li> <NavLink to="/driverList" activeClassName="active" className="nav-link mt-2 mb-2 text-white" > <div className="row"> <div className="col-4"> <FontAwesomeIcon icon={faIdCard} size="2x" /> </div> <div className="col-8 text-start mt-2">Drivers</div> </div> </NavLink> </li> </ul> <hr /> </div> </div> ); }
import React from 'react' import LoginForm from 'components/pages/login-page/login-form/login-form' import styles from './login.module.scss' import SiteTitle from "components/ui-components/site-title/site-title"; const Login = props => { return ( <div className={styles.page}> <SiteTitle>OurWorkout Admin Panel</SiteTitle> <LoginForm history={props.history} /> </div> ) } export default Login
import React, { Component } from 'react'; import { View } from 'react-native'; import DopeMV from '../../../components/molecules/dope-mv'; class DopeSection extends Component { prepareDope() { var dopeViews = this.props.dopeItems.map( (dope) => <DopeMV key={dope} title={dope}/> ); return dopeViews } render() { return ( <View style={{flexDirection: 'row', flexWrap: 'wrap', marginTop: 16, paddingHorizontal: 0, justifyContent: 'space-around'}}> <View style={{justifyContent: 'space-around', flexDirection: 'row', width: '100%', flexWrap: 'wrap'}}> {this.prepareDope()} </View> </View> ) } } export default DopeSection;
"use strict"; //Variable declarations const menuNav = document.getElementById("menu-main"); const menuToggle = document.getElementById("mobile-button"); //Hamburger navigation //add event listener to menu menuToggle.addEventListener("click", toggleMenu); function toggleMenu() { //toggle between showing and hiding the menu menuNav.classList.toggle("displayMenu"); } //History page collapsible //Add event listener to all instances of button document.querySelectorAll('.btnAbout').forEach(button => { button.addEventListener('click', event => { //grab the content of the div directly below the button clicked let details = button.nextElementSibling; //show/hide if (details.style.maxHeight) { details.style.maxHeight = null; } else { details.style.maxHeight = details.scrollHeight + "em"; } }) })
const directiveLib = require('./directiveLib'); /** * 模拟计算机的出拳 * @returns {number} */ const createComputerAction = () => Math.floor(Math.random() * 3); /** * 对决规则 * @param {number} user1 用户1出拳 * @param {number} user2 用户2出拳 * @returns {string} */ const rules = (user1, user2) => { if (user1 === user2) { return '平'; } else if (user1 - user2 === 1 || user2 - user1 === directiveLib.size - 1) { return '赢'; } return '输'; } /** * 游戏对决 * @param {number} userAction 用户出拳 * @returns {object | string} */ const battle = (userAction) => { if (directiveLib.has(userAction)) { const computerAction = createComputerAction(); const result = rules(userAction, computerAction); const getDec = (directive) => directiveLib.get(directive).dec; const userActionDec = getDec(userAction) const computerActionDec = getDec(computerAction); return { userActionDec, computerActionDec, result, }; } else { return '你作弊,不能这么出拳'; } } module.exports = battle;
'use strict'; module.exports = { up: (queryInterface, Sequelize) => { const { STRING: stringSequelize } = Sequelize; return queryInterface.createTable('weets', { id: { type: Sequelize.INTEGER, autoIncrement: true, primaryKey: true }, content: { type: stringSequelize(140), allowNull: false }, user_id: { allowNull: false, type: Sequelize.INTEGER, references: { model: 'users', key: 'id' } }, created_at: { type: Sequelize.DATE }, updated_at: { type: Sequelize.DATE } }); }, down: queryInterface => queryInterface.dropTable('weets') };
import initDebug from 'debug'; import { findBySlackId } from 'src/modules/shopbacker'; import slackShopbackerProfile from '../templates/slackShopbackerProfile'; import createProfileInquiry from '../templates/createProfileInquiry'; const debug = initDebug('happy:slack:skill:shopbacker'); export default (bot, message) => { debug(message); const user = message.match[1] || message.user; findBySlackId(user) .then((result) => { if (!result) { bot.reply(message, createProfileInquiry(user)); } else { bot.reply(message, slackShopbackerProfile(result)); } }) .catch((err) => { debug('fetch shobpacker error: ', err); }); };
const express = require("express"); const router = express.Router(); const NewsFeedController = require("../controllers/NewsFeedController"); // /news/all router.get("/all", function (req, res, next) { NewsFeedController.fetchAllNewsEntries(req, res); }); // /news/last7days router.get("/last7days", function (req, res, next) { NewsFeedController.fetchLast7Days(req, res); }); router.post("/update", function (req, res, next) { NewsFeedController.updateNews(req, res); }); module.exports = router;
import React from 'react'; import paul from '../../images/IMG_20200330_141645_174.jpg' import benedict from '../../images/benedict.jpeg' import morris from '../../images/IMG-20200412-WA0000.jpg' let about = props => { location.href = "#aboutBox" return ( <React.Fragment> <div className="aboutBox" id="aboutBox"> <div className="backIco2" onClick={props.click}> <i className="material-icons" >keyboard_backspace</i> </div> {props.type === "about" ? <React.Fragment> <div className="about"> <h3>ABOUT US</h3> <p>Fortune Auction started as a result to create a bid platform that people can win items during this pandemic. We are a group of passionate youths with the desire to build a world where you can get your wants & needs without pain & hustle <br/> We believe that creating a community of people with desire to meet their wishes and help others meet theirs will build a better world. Join Us Today! </p> </div> <div className="about"> <h3>TEAM</h3> <div className="grid-three"> <div> <div className=""> <img width="230px" height="230px" src={benedict} alt="" className="cirke2"/> </div> <div className="textMed">Benedict Okolie</div> </div> <div> <div className=""> <img width="230px" height="230px" src={morris} alt="" className="cirke2"/> </div> <div className="textMed">Morris Mwitti</div> </div> <div> <div className=""> <img width="230px" height="230px" src={paul} alt="" className="cirke2"/> </div> <div className="textMed">Paul Mahoro</div> </div> </div> </div> </React.Fragment> : <React.Fragment> <div className=""> <h3> ABOUT VENDORS </h3> <p>We designed this platform to enable vendors/sellers with both used & new items to auction, get bids and sell the item. Item type Such as Cars, Computer/Gadgets, Clothes & Home Electronics. <br/> You too our registered user can also sell any of your used items. Just Request! Have your legal proof of ownership (receipt, papers etc.) Auction and get bids. </p> <button className="btn blue" onClick={() => { props.click() props.openRequest() }}>Request Now </button> <h5>FEES & CHARGES</h5> <p> We charge a commission fee on every item sold both new and used at the following rate </p> <ol className="fees"> <li>New Items: 9%</li> <li>Used items from users: 10%</li> </ol> <p>Contact us for inquiries</p> </div> </React.Fragment> } </div> </React.Fragment> ) } export default about;
import Vue from "vue"; import Router from "vue-router"; import AddOrder from "@/views/AddOrder"; import Staff from "@/views/Staff"; Vue.use(Router); export default new Router({ routes: [ { path: "/", name: "clients", component: AddOrder, }, { path: "/staff", name: "staff", component: Staff, }, ], });
import request from '@/utils/request' import { urlChannel } from '@/api/commUrl' const url = urlChannel + 'channelrest/' const listChannelUrl = url + 'list' const deleteBatchUrl = url + 'deleteBatch' const getByIdUrl = url + 'getById' const updateChannelUrl = url + 'update' const saveChannelUrl = url + 'save' const updateStatusBatchUrl = url + 'updateStatusBatch' saveChannel // 列表 export function listChannel(params) { console.log(params) return request({ url: listChannelUrl, method: 'post', data: params }) } // 批量删除 export function deleteBatch(params) { console.log(params) return request({ url: deleteBatchUrl, method: 'post', data: params }) } // 编辑回显 export function getById(params) { console.log(params) return request({ url: getByIdUrl, method: 'post', data: params }) } // 更新 export function updateChannel(params) { console.log(params) return request({ url: updateChannelUrl, method: 'post', data: params }) } // 新增 export function saveChannel(params) { console.log(params) return request({ url: saveChannelUrl, method: 'post', data: params }) } // 启用 或禁用 export function updateStatusBatch(params) { console.log(params) return request({ url: updateStatusBatchUrl, method: 'post', data: params }) }
import { BoxStates } from './helpers/Box'; import GamePhases from './helpers/GamePhases'; export const initialLevel = 3; const CORE_GAME = 'CORE_GAME'; export const mapPlayers = new Map([ ['1', { id: '1', name: 'Anonymous', level: initialLevel, password: '' }] ]); const getTable = () => { const table = []; [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].forEach((i) => { [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].forEach((j) => { table.push({ i, j, key: i * 10 + j, state: BoxStates.EMPTY }); }); }); return table; }; const initialState = { table: getTable(), gamePhase: GamePhases.WAITING_FOR_FIRST_CLICK, startPosition: [], level: initialLevel, players: [], currentPlayerId: '1', disperseMode: false, disperseAway: true, popoverOpen: false, popoverCompleted: true, signInDlgOpen: false, logInDlgOpen: false }; function strMapToObj(strMap) { const obj = {}; strMap.forEach((v, k) => { obj[k] = v; }); return obj; } function isWebStorageSupported() { return 'localStorage' in window } export const saveStorage = (s) => { localStorage.setItem(CORE_GAME, JSON.stringify({ objPlayers: strMapToObj(mapPlayers), currentPlayerId: s.currentPlayerId, level: s.level, disperseMode: s.disperseMode, disperseAway: s.disperseAway })); }; // localStorage.removeItem(CORE_GAME); if (isWebStorageSupported) { const sCoreGame = localStorage.getItem(CORE_GAME); if (sCoreGame !== null) { console.log('localStorage:', sCoreGame); const storage = JSON.parse(sCoreGame); mapPlayers.clear(); Object.entries(storage.objPlayers).forEach(([key, value]) => { mapPlayers.set(key, value); }); initialState.level = storage.level; initialState.currentPlayerId = storage.currentPlayerId.toString(); initialState.disperseMode = storage.disperseMode; initialState.disperseAway = storage.disperseAway; } } mapPlayers.forEach((v, k) => { initialState.players.push(Object.assign({}, { id: k, level: v.level })); }); export default initialState;
import React, { useEffect, useState } from "react"; import styled from "styled-components"; import useChar from "../hooks/useChar"; import { useHistory } from "react-router-dom"; const StyledInput = styled.input` color: ${(props) => (props.isNotAvailable ? "red" : "white")}; `; const FinishBuild = () => { const { yourRace, yourProf, yourSpecs, yourBackstory, yourChars, getAllCharacters, createCharacter, initCharCreationPage, selectTitle } = useChar(); const [buildName, setBuildName] = useState(""); const history = useHistory(); const changeName = (e) => { setBuildName(e.target.value); }; useEffect(() => { getAllCharacters() //buildname checkolás miatt // eslint-disable-next-line }, []) const buildNameAlreadyExist = yourChars.map( (char) => char.buildName === buildName ); const isAnythingMissing = yourRace === "" || yourProf === "" || buildName === "" || yourSpecs.length === 0 || yourBackstory === ""; const raceIsMissing = yourRace === "" ? "Race " : ""; const profIsMissing = yourProf === "" ? "Profession " : ""; const specIsMissing = yourSpecs.length === 0 ? "Specializations " : ""; const backstoryIsMissing = yourBackstory === "" ? "Backstory " : ""; const submit = async (e) => { e.preventDefault(); //karakter adatainak átmozgatása My Character fülre createCharacter(yourRace, yourProf, yourSpecs, yourBackstory, buildName) initCharCreationPage() history.push("/mycharacter"); }; return ( <form onSubmit={submit}> {selectTitle("Name your character", buildName)} {buildName === "" ? ( "" ) : ( <div> {buildNameAlreadyExist.includes(true) ? ( <h5> Character name is{" "} <text is="x3d" style={{ color: "red" }}> NOT </text>{" "} available </h5> ) : ( <h5>Character name is available</h5> )} </div> )} <StyledInput isNotAvailable={buildNameAlreadyExist.includes(true)} onChange={changeName} placeholder="Character's name" value={buildName} /> <button style={{ width: "250px" }} type="submit" disabled={isAnythingMissing || buildNameAlreadyExist.includes(true)} > Create Character </button> <h4 style={{ color: "red", textDecorationLine: "underline" }}> {isAnythingMissing && buildName.length !== 0 ? "Missing: " + raceIsMissing + backstoryIsMissing + profIsMissing + specIsMissing : ""} </h4> </form> ); }; export default FinishBuild;
// Agency Theme JavaScript (function($) { "use strict"; // Start of use strict // jQuery for page scrolling feature - requires jQuery Easing plugin $('a.page-scroll').bind('click', function(event) { var $anchor = $(this); $('html, body').stop().animate({ scrollTop: ($($anchor.attr('href')).offset().top - 50) }, 1250, 'easeInOutExpo'); event.preventDefault(); }); // Offset for Main Navigation $('#mainNav').affix({ offset: { top: 100 } }) /* COMMANDS */ $('.article-cmd').on('click', function(e) { var $link = $(this) var href = $link.attr('href') e.preventDefault() $.get(href, function(data) { if (data) { $.messager.popup(data) } }) }) })(jQuery); /*编辑博客时*/ (function() { var $editArticleForm = $('#editArticleForm'); if ($editArticleForm.size() < 1) { return } // var localStorage = window.localStorage // if (!ARTICLE.content) { // var oldModel = localStorage.getItem('blog.model') // oldModel && $editArticleForm.view(oldModel) // } var confirmExit = false var $contentEditor = $('.content-editor') var $filePath = $('[name=file]') var $fileChoose = $('.file-choose') var $fileClear = $('.file-clear') var initContentFile = function() { $fileChoose.on('click', function() { OnceDoc.ChooseFile.chooseFile(function(chooseObj) { $filePath.val(chooseObj.path) $contentEditor.hide() }, { path: ARTICLE.file }) }) $fileClear.on('click', function() { $filePath.val('') $contentEditor.show() }) ARTICLE.file ? $contentEditor.hide() : $contentEditor.show() } var init = function() { $editArticleForm.on('submit', function(e) { e.preventDefault(); var model = $editArticleForm.view() var editUrl = $editArticleForm.attr('action') // localStorage.setItem('blog.model', model) $.post(editUrl, model, function(json) { if (json && json.error) { $.messager.popup(json.error) return } var url = $.qs.get('url') if (url) { confirmExit = true location.href = url return } url = json.url // localStorage.removeItem('blog.model') if (url) { confirmExit = true location.href = url return } $.messager.popup(FE_LOCAL.SAVED_SUCCESSFULLY) }) return false }) window.onbeforeunload = function (e) { if (confirmExit) { return } e = e || window.event; if (e) { e.returnValue = FE_LOCAL.LEAVE_DOCUMENT_EDITING_WARNING_MESSAGE } return FE_LOCAL.LEAVE_DOCUMENT_EDITING_WARNING_MESSAGE }; } init() initContentFile() })();
/** * Created by Administrator on 2016/8/15 0015. */ $(function(){ $("#closeButton").on("touchend",finish); }); function finish(){ history.go(-1); }
var pgp_8h = [ [ "pgp_use_gpg_agent", "pgp_8h.html#ab97e1713bb20da422b5a71b68747edf9", null ], [ "pgp_class_check_traditional", "pgp_8h.html#ac3696b27c886e803d5d249760aef9062", null ], [ "pgp_this_keyid", "pgp_8h.html#a927e11bf8d412f23bbe265dde26da978", null ], [ "pgp_keyid", "pgp_8h.html#a7bdf66d17368047199f6fde6f75acb0a", null ], [ "pgp_short_keyid", "pgp_8h.html#ac3d880a312dfbc688f318f97212e18b5", null ], [ "pgp_long_keyid", "pgp_8h.html#a601c1b63edd63064e681212ea73b9c29", null ], [ "pgp_fpr_or_lkeyid", "pgp_8h.html#a089d10f372b05a8b976d63592d535996", null ], [ "pgp_class_decrypt_mime", "pgp_8h.html#aa949718827381a0e6229ef3eb2abc928", null ], [ "pgp_class_find_keys", "pgp_8h.html#a32a1948b5d4d3cf41c817b98f7c445d0", null ], [ "pgp_class_application_handler", "pgp_8h.html#aa55c76c8d08b0720d97cdb6360440f78", null ], [ "pgp_class_encrypted_handler", "pgp_8h.html#a548644e4ab9c58ef526d8b1725f02bf6", null ], [ "pgp_class_extract_key_from_attachment", "pgp_8h.html#a9d568f942b2e467bbc94b89dd4ede4ac", null ], [ "pgp_class_void_passphrase", "pgp_8h.html#a5f22ad399cd8c0e467f61969e762aba0", null ], [ "pgp_class_valid_passphrase", "pgp_8h.html#a0e9e718dd04065013a56713bc7b0eae4", null ], [ "pgp_class_verify_one", "pgp_8h.html#a2d07667a924f2576457cb64e4ec2bc64", null ], [ "pgp_class_traditional_encryptsign", "pgp_8h.html#ac131bc7b36afa45cd86e864a66baee6f", null ], [ "pgp_class_encrypt_message", "pgp_8h.html#a670a77cb262550ce2a37b6eb3b5b5c88", null ], [ "pgp_class_sign_message", "pgp_8h.html#aa81f893b89783abadf1ba1f9a59f31c7", null ], [ "pgp_class_send_menu", "pgp_8h.html#a563518f9cdac5ec697065b7c49ce37c6", null ] ];
import React,{Component } from 'react'; import { StyleSheet,View,Text,TextInput,ImageBackground,Image,TouchableOpacity, Button, KeyboardAvoidingView,Alert,Keyboard,ToastAndroid } from 'react-native'; //import Icon from 'react-native-vector-icons/FontAwesome'; import { Input,Icon } from 'react-native-elements'; import AsyncStorage from '@react-native-community/async-storage'; import SwitchButton from 'switch-button-react-native'; const Toast = (props) => { if (props.visible) { ToastAndroid.showWithGravityAndOffset( props.message, ToastAndroid.LONG, ToastAndroid.TOP, 25, 400, ); return null; } return null; }; class SignupScreen extends Component { constructor(props) { super(props); this.state = { userEmail:'', userPassword:'', visible: false, emailvisible:false, userData:{}, activeSwitch: 1, userName:'', phone:'', university:'', repassword:'', keyboardStatus:true, msg:'' }; } async storeToken(user) { try { await AsyncStorage.setItem("userData",JSON.stringify(user)); } catch (error) { console.log("Something went wrong", error); } } async storeUserID(user) { try { await AsyncStorage.setItem("userID",JSON.stringify(user)); } catch (error) { console.log("Something went wrong", error); } } async storeLocation(user) { try { await AsyncStorage.setItem("locationID",JSON.stringify(user)); } catch (error) { console.log("Something went wrong", error); } } UserLoginFunction = () =>{ const { userEmail } = this.state ; const { userPassword } = this.state ; // Alert.alert(userPassword + this.state.repassword) if(this.state.repassword == userPassword) { if(this.state.username == '' || userEmail == '') { Alert.alert('All the Fields are required'); } else { // Alert.alert(userEmail + userPassword); return fetch('https://teammotivation.in/onlinetest/appmotivenew/ac-logincrt.php', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ username:this.state.userName, university:this.state.university, type:this.state.activeSwitch, phone:this.state.phone, email: userEmail, password: userPassword }) }).then((response) => response.json()) .then((responseJson) => { console.log(responseJson); // If server response message same as Data Matched if(responseJson === 1) { this.setState( { visible: true, msg:'Email ID Already Exist!' }, () => { this.hideToast(); }, ); } else { this.setState( { visible: true, msg:'Thank you for Successfully Registered!' }, () => { this.hideToast(); }, ); setTimeout(() => { this.props.navigation.navigate('Login'); this.setState({timePassed: true})}, 5000) } }).catch((error) => { console.error(error); }); Keyboard.dismiss(); } } else { Alert.alert('not smae'); } } hideToast = () => { this.setState({ visible: false, }); }; render() { return ( <> <KeyboardAvoidingView style={styles.body} behavior="padding" enabled> <View style={ styles.container}> <Image source={require('../assets/src/logo.png')} style={{width: 300, height:48}} /> </View> <View></View> <View style={styles.inputContainer}> {/* <View style={{width:'100%', marginBottom:8, alignContent:'center'}}> <View style={{width:'50%',marginLeft:50}} > <SwitchButton onValueChange={(val) => this.setState({ activeSwitch: val })} // this is necessary for this component text1 = 'Free' text2 = 'Premium' // optional: first text in switch button --- default ON // optional: second text in switch button --- default OFF switchWidth = {200} // optional: switch width --- default 44 switchHeight = {44} // optional: switch height --- default 100 switchdirection = 'ltr' // optional: switch button direction ( ltr and rtl ) --- default ltr switchBorderRadius = {100} // optional: switch border radius --- default oval switchSpeedChange = {500} // optional: button change speed --- default 100 switchBorderColor = '#d4d4d4' // optional: switch border color --- default #d4d4d4 switchBackgroundColor = '#fff' // optional: switch background color --- default #fff btnBorderColor = '#00a4b9' // optional: button border color --- default #00a4b9 btnBackgroundColor = '#00bcd4' // optional: button background color --- default #00bcd4 fontColor = '#b1b1b1' // optional: text font color --- default #b1b1b1 activeFontColor = '#fff' // optional: active font color --- default #fff /> { this.state.activeSwitch === 0 ? console.log('view1') : console.log('view2') } </View> </View> */} <View style={styles.userInput }> <Input style ={ styles.textInput} placeholder='Username' leftIcon={ <Icon name='user' size={24} color='black' type='font-awesome' /> } onChangeText={userName => this.setState({userName})} /> </View> <View style={styles.userInput }> <Input style ={ styles.textInput} placeholder='Email' leftIcon={ <Icon name='email' type='material' size={24} color='black' /> } onChangeText={userEmail => this.setState({userEmail})} /> </View> <View style={styles.userInput }> <Input style ={ styles.textInput} placeholder='Phone' leftIcon={ <Icon name='phone' type='material' size={24} color='black' /> } onChangeText={phone => this.setState({phone})} /> </View> <View style={styles.userInput }> <Input style ={ styles.textInput} placeholder="University Name" onChangeText={university => this.setState({university})} /> </View> <View style={styles.userInput }> <Input style ={ styles.textInput} placeholder='Password' leftIcon={ <Icon name='lock' size={24} color='black' type='font-awesome' /> } onChangeText={userPassword => this.setState({userPassword})} keyboardType={"numeric"} /> </View> <View style={styles.userInput }> <Input style ={ styles.textInput} placeholder='Re Password' leftIcon={ <Icon name='lock' size={24} color='black' type='font-awesome' /> } onChangeText={repassword => this.setState({repassword})} keyboardType={"numeric"} /> </View> <View style={styles.userInput} > <TouchableOpacity> <Button title="Sign Up " color="#f194ff" onPress={this.UserLoginFunction}/> </TouchableOpacity> </View> <Toast visible={this.state.visible} message={this.state.msg} /> </View> </KeyboardAvoidingView> </> ); } } SignupScreen.navigationOptions = { header:null } const styles = StyleSheet.create({ body: { flex:1, backgroundColor:'#2758d4', alignItems:'center' }, container: { width:'100%', height:90, backgroundColor:'white', borderBottomLeftRadius:60, borderBottomRightRadius:60, alignItems:'center', justifyContent:'center' }, textInput: { borderBottomColor:'black', borderBottomWidth:0.3, backgroundColor:'white', height:40 }, userInput: { width:'100%', backgroundColor:'white', marginVertical:5 }, inputContainer: { width:'100%', maxWidth:'80%', alignItems:'center', justifyContent:'center', // shadowOffset: { width:0, height:2}, // shadowRadius:5, // shadowOpacity:0.26, // backgroundColor:'white', // elevation:5, marginTop:25 } }); export default SignupScreen;
import React from 'react'; import { Container } from 'components/Containers'; export const MotionChild = ({ children, className = '', selectStyle, ...props }) => style => { const _style = selectStyle(style); return ( <Container {...props} className={className} style={_style}> {children} </Container> ); }; export default MotionChild;
'use strict'; var util = require('util'); var path = require('path'); var yeoman = require('yeoman-generator'); var UltimateGenerator = module.exports = function UltimateGenerator(args, options, config) { yeoman.generators.Base.apply(this, arguments); this.on('end', function () { this.installDependencies({ skipInstall: options['skip-install'] }); }); this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json'))); }; util.inherits(UltimateGenerator, yeoman.generators.Base); UltimateGenerator.prototype.askFor = function askFor() { // have Yeoman greet the user. console.log(this.yeoman); }; UltimateGenerator.prototype.app = function app() { this.expandFiles('**/*', { cwd: this.sourceRoot(), dot: true }).forEach(function (file) { if ([ '.git' ].indexOf(file) !== -1) { return; } this.copy(file, file); }, this); }; UltimateGenerator.prototype.projectfiles = function projectfiles() { };
import React, {Component} from 'react'; import RootNavigator from './src/navigation' import EStyleSheet from 'react-native-extended-stylesheet'; import store from './src/redux/store' import {Provider} from 'react-redux'; import theme from './theme'; console.disableYellowBox = true; EStyleSheet.build(theme); type Props = {}; export default class App extends Component < Props > { render() { return ( <Provider store={store}> <RootNavigator/> </Provider> ); } }
module.exports = function (app) { var ctrl = app.controllers.usuarios; app.get('/api/', function (req, res) { res.send('Salgados Sirius'); }); app.post('/api/login', function (req, res) { var credenciais = req.body; ctrl.getBySenha(app.HmacSHA1(credenciais.senha.toString()), function (err, result) { if (err) { res.status(500).json(err); } else if (!result || result.length == 0) { res.status(404).send('Usuário não cadastrado!'); } else { var usuario = result[0]; req.session.usuario = { email: usuario.email, nome: usuario.nome, perfil: usuario.perfil, autorizado: true }; res.json(req.session.usuario); } }); /*ctrl.getByEmail(credenciais.email, function (err, result) { if (err) { res.status(500).json(err); } else if (!result || result.length == 0) res.status(404).send('Usuário não cadastrado!'); else { var usuario = result[0]; if (usuario.hasOwnProperty('senha') || !usuario.senha) { res.status(404).send('Ainda não foi cadastrada uma senha para esse usuário!'); return; } if (usuario.senha === app.HmacSHA1(credenciais.senha)) { req.session.usuario = { email: usuario.email, nome: usuario.nome, perfil: usuario.perfil, autorizado: true }; res.json(req.session.usuario); } else res.status(400).send('Senha incorreta!'); } }); res.json(req.session.usuario);*/ }); app.post('/api/cadastrarsenha', function (req, res) { var credenciais = req.body; ctrl.getByEmail(credenciais.email, function (err, result) { if (err) { res.status(500).json(err); } else if (!result || result.length == 0) res.status(404).send('Usuário não cadastrado!'); else { var usuario = result[0]; if (usuario.senha) { res.status(400).send('Já existe uma senha cadastrada para essa usuário!'); return; } usuario.senha = credenciais.senha; ctrl.put(usuario._id, usuario, function (err, result) { if (err) { res.status(500).json(err); } else { res.status(200).send(result); } }) } }); }); app.get('/api/usuario', function (req, res) { if (req.session) res.json(req.session.usuario); else res.json(null); }); app.post('/api/resetsenha', function (req, res) { var id = req.body.id; ctrl.resetSenha(id, function (err, result) { if (err) { res.send(err); return; } res.status(200).send({ msg: 'A senha do usuário foi redefinida!' }); }); }); }
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { faList } from '@fortawesome/free-solid-svg-icons'; import { faChartBar } from '@fortawesome/free-solid-svg-icons'; function Other (props){ return ( <div className="right-wrapper"> <div className="icon-wrapper"> <FontAwesomeIcon className="right-icon " icon={faList} onClick={props.setOpenpage}/> </div> <div className="title-wrapper"> <p>POMODORO</p> </div> </div> ); } export default Other;
require "./models"; // データのモデル定義 const tasks = new Task({ id: 1, content: "", layer: 2, doneFlag: false, childIds: [2, 3], }); // console.log(tasks); // tasks.countChildTasks(); // [パターン1: taskの追加]tasksドキュメントをデータベースに保存 tasks.save().then(() => console.log("here comes datas!!!")); // [パターン2: 全件一致] Task.find().exec((err, task) => { console.log(task); }); // [パターン3: キー指定] Task.find({ layer: 2 }).exec((err, task) => { console.log(task); }); // https://mongoosejs.com/docs/guide.html#statics
//to be downloaded from database :S var globalPrices={ pizza:10, greenpeppers:1, pepperonni:1, mushrooms:1, sauce:3, crust:5, }; $(document).ready(function () { gpSections = $("section.green-pepper"); mSections = $("section.mushroom"); pSections = $("section.pep"); crustSection = $("#pizza>section:last"); sauceSection = $("#pizza>section>section:last"); gpSections.hide(); $("button.btn-green-peppers").removeClass("active"); $("aside.price li:contains('green peppers')").css("display","none"); mSections.hide(); $("button.btn-mushrooms").removeClass("active"); $("aside.price li:contains('mushrooms')").css("display","none"); pSections.hide(); $("button.btn-pepperonni").removeClass("active"); $("aside.price li:contains('pepperonni')").css("display","none"); crustSection.removeClass("crust-gluten-free"); $("button.btn-crust").removeClass("active"); $("aside.price li:contains('gluten-free crust')").css("display","none"); sauceSection.removeClass("sauce-white"); $("button.btn-sauce").removeClass("active"); $("aside.price li:contains('white sauce')").css("display","none"); updatePrices(); //////////////////////////// ////button callbacks //////////////////////////// $("button.btn-green-peppers").click(function () { $(".green-pepper").fadeToggle(500); $(this).toggleClass("active"); $("aside.price li:contains('green peppers')").fadeToggle(500); updatePrices(); }); $("button.btn-mushrooms").click(function () { $(".mushroom").fadeToggle(500); $(this).toggleClass("active"); $("aside.price li:contains('mushrooms')").fadeToggle(500); updatePrices(); }); $("button.btn-pepperonni").click(function () { $(".pep").fadeToggle(500); $(this).toggleClass("active"); $("aside.price li:contains('pepperonni')").fadeToggle(500); updatePrices(); }); $("button.btn-sauce").click(function () { sauceSection.toggleClass("sauce-white"); $(this).toggleClass("active"); $("aside.price li:contains('white sauce')").fadeToggle(500); updatePrices(); }); $("button.btn-crust").click(function () { crustSection.toggleClass("crust-gluten-free"); $(this).toggleClass("active"); $("aside.price li:contains('gluten-free crust')").fadeToggle(500); updatePrices(); }); }); //////// price calc var updatePrices=function(){ let p= globalPrices.pizza + ($("button.btn-green-peppers").hasClass("active")? globalPrices.greenpeppers : 0) + ($("button.btn-mushrooms").hasClass("active")? globalPrices.mushrooms : 0) + ($("button.btn-pepperonni").hasClass("active")? globalPrices.pepperonni : 0) + ($("button.btn-crust").hasClass("active")? globalPrices.crust : 0) + ($("button.btn-sauce").hasClass("active")? globalPrices.sauce : 0); $("aside.price strong").text("$" + p.toString()); }
'use strict'; /* * new Date('2015-10-3') 这样的调用,产生的是伦敦格林威治时间的2015-10-3凌晨0分0秒,误用就会坏了。 * 服务器端代码应该使用moment,浏览器端代码应该使用common.new_date() */ var assert = require('assert'), nativeDateRegex = /\bDate\b/, error_message = 'Instead of Date(), please use moment() in node.js code, ' + 'or use common.new_date() in browser-side javascript.'; module.exports = function() {}; module.exports.prototype = { configure: function(disallowNativeDate) { assert( disallowNativeDate === true || disallowNativeDate === 'ignoreProperties', 'requireCamelCaseOrUpperCaseIdentifiers option requires true value or `ignoreProperties` string' ); this._ignoreProperties = (disallowNativeDate === 'ignoreProperties'); }, getOptionName: function() { return 'disallowNativeDate'; }, check: function(file, errors) { file.iterateNodesByType([ 'CallExpression', 'NewExpression' ], function(node) { if(nativeDateRegex.test(node.callee.name) && node.arguments.length) { errors.add( error_message, node.loc.start.line, node.loc.start.column ); } }.bind(this)); } };
import React, { useState,useEffect } from "react"; import './Pokemon.css'; const Pokemon = ({pokemon , viewPokemon}) => { //console.log(pokemon); return( <div className="pokemon"> { pokemon.map(p =>( <div className="container-item" key={p.name} value={p.name}> <p>{p.name}</p> <button onClick={() => viewPokemon(p.name)}>view</button> </div> )) } </div> ) } export default Pokemon;
// Constants: const REQUEST_ERROR = 400; // Dependencies: import { TractorError } from '@tractor/error-handler'; import { File } from '@tractor/file-structure'; import escapeRegExp from 'lodash.escaperegexp'; import path from 'path'; import { generate } from '../generator/generate-step-definition-files'; import { lex } from '../lexer/lex-feature-file'; export class FeatureFile extends File { read () { // Hack to fix coverage bug: https://github.com/gotwarlost/istanbul/issues/690 /* istanbul ignore next */ let read = super.read(); return read.then(content => setTokens(this, content)) .then(() => getReferences.call(this)) .catch(() => { throw new TractorError(`Lexing "${this.path}" failed.`, REQUEST_ERROR); }); } move (update, options) { // Hack to fix coverage bug: https://github.com/gotwarlost/istanbul/issues/690 /* istanbul ignore next */ let move = super.move(update, options); return move.then(newFile => { let { oldPath, newPath } = update; if (oldPath && newPath) { let oldName = path.basename(oldPath, this.extension); let newName = path.basename(newPath, this.extension); return refactorName(newFile, oldName, newName); } }); } save (data) { // Hack to fix coverage bug: https://github.com/gotwarlost/istanbul/issues/690 /* istanbul ignore next */ let save = super.save(data); return save.then(content => { setTokens(this, content); return generate(this); }) .then(() => this.content) .catch(() => { throw new TractorError(`Saving "${this.path}" failed.`, REQUEST_ERROR); }); } serialise () { // Hack to fix coverage bug: https://github.com/gotwarlost/istanbul/issues/690 /* istanbul ignore next */ let serialised = super.serialise(); serialised.tokens = this.tokens; return serialised; } } function getReferences () { if (this.initialised) { this.clearReferences(); } // TODO: Convert each step in feature to .step.js name and // create the reference link: // let reference = this.fileStructure.referenceManager.getReference(referencePath); // if (reference) { // this.addReference(reference); // } this.initialised = true; } function refactorName (newFile, oldName, newName) { let escapedOldName = escapeRegExp(oldName); let oldNameRegExp = new RegExp(`(Feature:\\s)${escapedOldName}(\\r\\n|\\n)`); return newFile.save(newFile.content.replace(oldNameRegExp, `$1${newName}$2`)); } function setTokens (file, content) { file.tokens = lex(content); return content; } FeatureFile.prototype.extension = '.feature';
const graphql = require('graphql') const mongoose = require('mongoose') const EpisodeType = require('./types/episode') const UserType = require('./types/user') const WatchListItemType = require('./types/watchListItem') const AuthService = require('../services/auth') const Episode = mongoose.model('episode') const WatchListItem = mongoose.model('watchListItem') const { GraphQLObjectType, GraphQLString, GraphQLNonNull, GraphQLID, } = graphql /** * The mutations object, containing all mutations for the aplication. * @type {GraphQLObjectType} */ module.exports = new GraphQLObjectType({ name: 'Mutation', fields: { addItem: { // Add a new item to the watchlist (TV Show or Movie) type: WatchListItemType, args: { tmdbID: { type: new GraphQLNonNull(GraphQLString) }, type: { type: GraphQLNonNull(GraphQLString) }, }, resolve(parentValue, { tmdbID, type }, req) { if (!req.user) { return null // throw error } return (new WatchListItem({ tmdbID, type, user: req.user._id }).save()) }, }, login: { type: UserType, args: { email: { type: GraphQLString }, password: { type: GraphQLString }, }, resolve(parentValue, { email, password }, req) { return AuthService.login({ email, password, req }) }, }, logout: { type: UserType, resolve(parentValue, args, req) { const { user } = req req.logout() return user }, }, register: { type: UserType, args: { email: { type: GraphQLString }, password: { type: GraphQLString }, }, resolve(parentValue, { email, password }, req) { return AuthService.register({ email, password, req }) }, }, removeItem: { type: WatchListItemType, args: { id: { type: new GraphQLNonNull(GraphQLString) }, }, resolve(parentValue, { id }) { Episode.remove({ watchListItem: { _id: id } }) // First remove all episodes, if any .then(() => WatchListItem.remove({ _id: id })) // Remove the item itself }, }, toggleItemWatched: { // Toggle whether a watchlist item has been watched or not type: WatchListItemType, args: { id: { type: new GraphQLNonNull(GraphQLID) }, }, resolve(parentValue, { id }) { return WatchListItem.toggleWatched(id) }, }, toggleEpisodeWatched: { // Toggle whether a TV Show episode has been watched or not type: EpisodeType, args: { id: { type: new GraphQLNonNull(GraphQLID) }, }, resolve(parentValue, { id }) { return Episode.toggleWatched(id) }, }, }, })
//获取传参 function GetRequest() { var url = location.search; //获取url中"?"符后的字串 var theRequest = new Object(); if (url.indexOf("?") != -1) { var str = url.substr(1); strs = str.split("&"); for (var i = 0; i < strs.length; i++) { theRequest[strs[i].split("=")[0]] = decodeURIComponent(strs[i].split("=")[1]); } } return theRequest; } var t_param = GetRequest(); console.log(t_param) var pt_id = t_param[`pt_id`] , pt_company_id = parseInt(t_param[`pt_company_id`]) , user_id = parseInt(t_param[`user_id`]) , item_id = parseInt(t_param[`item_id`]) , temp_choose = t_param[`temp`]; //参数 var difficulty = 6 , pt_company_teacher_len = 0 , pt_company_teacher_id = []; var GetCompanyTeacherURL = "http://42.159.228.113:8081/BackCode_war/GetCompanyTeacherByCompanyIdServlet" , CreateNewProjectURL = "http://42.159.228.113:8081/BackCode_war/CreateProjectServlet"; var checked_company_teacher = []; window.localStorage.new_item_difficulty = 6 //区 layui.use(['form', 'jquery', 'layer', 'rate', 'table'], function () { var form = layui.form , $ = layui.jquery , layer = layui.layer , rate = layui.rate , table = layui.table; //评分 rate.render({ elem: '#new_item_difficulty' , value: 3 , text: true , half: true , theme: '#1E9FFF' , setText: function (value) { //自定义文本的回调 var arrs = { '0.5': 1 , '1': 2 , '1.5': 3 , '2': 4 , '2.5': 5 , '3': 6 , '3.5': 7 , '4': 8 , '4.5': 9 , '5': 10 }; this.span.text(arrs[value] || (value + "星")); } , choose: function (value) { difficulty = value * 2; window.localStorage.new_item_difficulty = value * 2; } }) function renderStar(id, score) { layui.use('rate', function () { var rate = layui.rate; //渲染 var ins1 = rate.render({ elem: '#' + id //绑定元素 , length: 5 , value: score , half: true //, readonly: true , setText: function (value) { //自定义文本的回调 var arrs = { '0.5': 1 , '1': 2 , '1.5': 3 , '2': 4 , '2.5': 5 , '3': 6 , '3.5': 7 , '4': 8 , '4.5': 9 , '5': 10 }; this.span.text(arrs[value] || (value + "星")); } , choose: function (value) { layer.alert("当前难度:" + value * 2) } }); }) } function renderStar_d(id, score) { layui.use('rate', function () { var rate = layui.rate; //渲染 var ins1 = rate.render({ elem: '#' + id //绑定元素 , length: 5 , value: score , half: true , readonly: true , setText: function (value) { //自定义文本的回调 var arrs = { '0.5': 1 , '1': 2 , '1.5': 3 , '2': 4 , '2.5': 5 , '3': 6 , '3.5': 7 , '4': 8 , '4.5': 9 , '5': 10 }; this.span.text(arrs[value] || (value + "星")); } , choose: function (value) { layer.alert("当前难度:" + value * 2) } }); }) } if (item_id) { console.log("has item_id") var GetTeamInfoURL = "http://42.159.228.113:8081/BackCode_war/GetProjectInformationServlet" $.ajax({ type: "POST", url: GetTeamInfoURL, async: true, data: JSON.stringify({ "reqId": "111", "reqParam": item_id }), dataType: "json", success: function (res) { console.log(res); document.getElementById("new_item_name").value = res.resData.name; document.getElementById("new_item_type").value = res.resData.type; document.getElementById("new_item_introduce").value = res.resData.introduce; document.getElementById("new_item_base_content").value = res.resData.baseContent; document.getElementById("new_item_extend_content").value = res.resData.extendContent ? res.resData.extendContent : "暂无"; document.getElementById("new_item_advance_content").value = res.resData.advanceContent ? res.resData.advanceContent : "暂无"; window.localStorage.new_item_name = res.resData.name; window.localStorage.new_item_type = res.resData.type; window.localStorage.new_item_introduce = res.resData.introduce; window.localStorage.new_item_base_content = res.resData.baseContent; window.localStorage.new_item_extend_content = res.resData.extendContent ? res.resData.extendContent : "暂无"; window.localStorage.new_item_advance_content = res.resData.advanceContent ? res.resData.advanceContent : "暂无"; window.localStorage.new_item_difficulty = res.resData.difficulty; if (temp_choose == "edit") { console.log("edit") //评分 rate.render({ elem: '#new_item_difficulty' , value: res.resData.difficulty / 2 , text: true , half: true , theme: '#1E9FFF' , setText: function (value) { //自定义文本的回调 var arrs = { '0.5': 1 , '1': 2 , '1.5': 3 , '2': 4 , '2.5': 5 , '3': 6 , '3.5': 7 , '4': 8 , '4.5': 9 , '5': 10 }; this.span.text(arrs[value] || (value + "星")); } , choose: function (value) { difficulty = value * 2; window.localStorage.new_item_difficulty = value * 2; } }) for (var i = 0; i < res.resData.companyTeachers.length; i++) { console.log(res.resData.companyTeachers[i]) checked_company_teacher.push(res.resData.companyTeachers[i].id) } console.log(checked_company_teacher) window.localStorage.checked_company_teacher = checked_company_teacher; var param_company_teacher = function (res) { return { elem: '#ni_company_teacher_table' , url: GetCompanyTeacherURL , title: '企业老师' , toolbar: '#toolbar_company_teacher' , defaultToolbar: ['filter'] , contentType: 'application/json' , method: "POST" , where: { "reqId": "", "reqParam": pt_company_id } , deal: function (res) { console.log(res) pt_company_teacher_len = res.resData.length; for (var i = 0; i < pt_company_teacher_len; i++) { pt_company_teacher_id.push(res.resData[i].id) for (var j = 0; j < checked_company_teacher.length; j++) { if (res.resData[i].id == checked_company_teacher[j]) { res.resData[i].LAY_CHECKED = true; } } } return { code: 0 , msg: "" , count: 1000 , data: res.resData } } , cols: [[ { type: 'checkbox' } , { field: 'id', width: 75, title: 'ID', hide: true } , { field: 'name', title: '名称' } , { field: 'sex', title: '性别' } ]] } } table.render(param_company_teacher(1)) } else if (temp_choose == "detail") { console.log("detail") document.getElementById("new_item_name").disabled = "disabled"; document.getElementById("new_item_type").disabled = "disabled"; renderStar_d("new_item_difficulty", res.resData.difficulty / 2); document.getElementById("new_item_introduce").disabled = "disabled"; document.getElementById("new_item_base_content").disabled = "disabled"; document.getElementById("new_item_extend_content").disabled = "disabled"; document.getElementById("new_item_advance_content").disabled = "disabled"; document.getElementById("new_item_advance_content").disabled = "disabled"; document.getElementById("ni_company_teacher_table").style.display = "none"; var temptemp = "<pre style='padding-top:11px'>"; for (var i = 0; i < res.resData.companyTeachers.length; i++) { temptemp += res.resData.companyTeachers[i].name; temptemp += " " } temptemp += "</pre>" document.getElementById("teacher_info").innerHTML += temptemp; } }, error: function (res) { console.log("error"); console.log(res); } }); } else { var param_company_teacher = function (res) { return { elem: '#ni_company_teacher_table' , url: GetCompanyTeacherURL , title: '企业老师' , toolbar: '#toolbar_company_teacher' , defaultToolbar: ['filter'] , contentType: 'application/json' , method: "POST" , where: { "reqId": "", "reqParam": pt_company_id } , deal: function (res) { console.log(res) pt_company_teacher_len = res.resData.length; for (var i = 0; i < pt_company_teacher_len; i++) { pt_company_teacher_id.push(res.resData[i].id) } return { code: 0 , msg: "" , count: 1000 , data: res.resData } } , cols: [[ { type: 'checkbox' } , { field: 'id', width: 75, title: 'ID', hide: true } , { field: 'name', title: '名称' } , { field: 'sex', title: '性别' } ]] } } table.render(param_company_teacher(1)) } //监听复选框 table.on('checkbox(ni_company_teacher_table)', function (obj) { console.log(obj.checked); //当前是否选中状态 console.log(obj.data); //选中行的相关数据 console.log(obj.type); //如果触发的是全选,则为:all,如果触发的是单选,则为:one if (obj.type == "all") { if (obj.checked) { checked_company_teacher = [] for (var i = 0; i < pt_company_teacher_len; i++) { checked_company_teacher.push(pt_company_teacher_id[i]) } } else { checked_company_teacher = []; } } else { if (obj.checked) { checked_company_teacher.push(obj.data.id) } else { var i = 0; for (i = 0; i < checked_company_teacher.length; i++) { if (checked_company_teacher[i] == obj.data.id) break; } checked_company_teacher.splice(i, 1); } } window.localStorage.checked_company_teacher = checked_company_teacher; console.log(window.localStorage.checked_company_teacher) }); //监听input document.getElementById('new_item_name').onchange = function () { console.log(document.getElementById('new_item_name').value) window.localStorage.new_item_name = document.getElementById('new_item_name').value }; document.getElementById('new_item_type').onchange = function () { console.log(document.getElementById('new_item_type').value) window.localStorage.new_item_type = document.getElementById('new_item_type').value }; document.getElementById('new_item_introduce').onchange = function () { console.log(document.getElementById('new_item_introduce').value) window.localStorage.new_item_introduce = document.getElementById('new_item_introduce').value }; document.getElementById('new_item_base_content').onchange = function () { console.log(document.getElementById('new_item_base_content').value) window.localStorage.new_item_base_content = document.getElementById('new_item_base_content').value }; document.getElementById('new_item_extend_content').onchange = function () { console.log(document.getElementById('new_item_extend_content').value) window.localStorage.new_item_extend_content = document.getElementById('new_item_extend_content').value }; document.getElementById('new_item_advance_content').onchange = function () { console.log(document.getElementById('new_item_advance_content').value) window.localStorage.new_item_advance_content = document.getElementById('new_item_advance_content').value }; });
import { combineReducers } from 'redux'; import { routerReducer } from 'react-router-redux'; import app from '../app'; import data from '../data'; export default combineReducers({ app: app.reducer, data: data.reducer, routing: routerReducer, });
import React, { Component, } from 'react'; import { View, Text,ImageBackground, Image,} from 'react-native'; import { connect, } from 'react-redux'; import NavigationUtil from '../../util/NavigationUtil'; export default class SplashPage extends Component { componentDidMount() { this.timer = setTimeout(() => { NavigationUtil.resetToMainPage({ navigation: this.props.navigation, }); }, 200); } componentWillUnmount() { this.timer && clearTimeout(this.timer); } render() { return ( <Image source={require('../../res/drawable/app_splash.webp')} style={{ width: '100%', height: '100%',}} > </Image> ); } }
import React, {Component} from 'react'; import {StatusBar} from 'react-native'; import Routes from './routes'; export default class App extends Component { render = () => { return ( <> <StatusBar backgroundColor="#B12D30" animated barStyle="light-content" /> <Routes /> </> ); }; }
var searchData= [ ['thursday',['THURSDAY',['../class_action_settings.html#af4382214fc4cb662884ba314009ed4d6',1,'ActionSettings']]], ['tuesday',['TUESDAY',['../class_action_settings.html#a387ace15273bbc582a7debc2fc158693',1,'ActionSettings']]] ];
//var name = "Kirk"; //var age = 49; //var message = "Hi, my name is " + name + " and I am " + age + " years old."; var sum = 10+ 23; var div = 10 / 3; var mod = 10 % 3; var msg = "10 / 3 = 3 and remander of " + mod; var result = 10 * ((5 + 17) + 67); console.log(result);
import React from 'react' import { Table, Badge, Select, Button } from 'evergreen-ui' export default function OrdersPage(props) { return ( <> <Table> <Table.Head> <Table.TextHeaderCell flexGrow={2}> Product </Table.TextHeaderCell> <Table.TextHeaderCell flexGrow={0.5}> Quantity </Table.TextHeaderCell> <Table.TextHeaderCell flexGrow={2}> Weigth/Piece </Table.TextHeaderCell> <Table.TextHeaderCell flexGrow={0.5}> Price </Table.TextHeaderCell> <Table.TextHeaderCell flexGrow={0.5}> Total price </Table.TextHeaderCell> <Table.TextHeaderCell flexGrow={2}> Status </Table.TextHeaderCell> <Table.TextHeaderCell flexGrow={0.5}> Order ID </Table.TextHeaderCell> </Table.Head> <Table.Body height='auto'> {props.orders.map(order => { if (order.status === 'pending') { return ( <Table.Row key={order.id} isSelectable > <Table.TextCell flexGrow={2}>{order.product.product_name}</Table.TextCell> <Table.TextCell flexGrow={0.5}>{order.quantity}</Table.TextCell> <Table.TextCell flexGrow={2}>{order.product.prices_by === 'weight' ? <Badge color='blue'>weight</Badge> : <Badge color='orange'>per piece</Badge>}</Table.TextCell> <Table.TextCell flexGrow={0.5}>{order.product.price}</Table.TextCell> <Table.TextCell flexGrow={0.5}>{order.total_price}</Table.TextCell> <Table.TextCell flexGrow={2}> <Select onChange={props.onChange} className="orderline-status" name={order.id}> <option value="pending">pending</option> <option value="ready for pickup">ready for pickup</option> </Select> </Table.TextCell> <Table.TextCell flexGrow={0.5}>{order.orderId}</Table.TextCell> </Table.Row> )} } )} </Table.Body> <Table.Head> <Table.TextHeaderCell>Orderhistory</Table.TextHeaderCell> <Button style={{background: "green", color: "white"}} onClick={props.onClick}>SAVE</Button> </Table.Head> <Table.Body height='auto'> {props.orders.map(order => { if (order.status !== 'pending') { return ( <Table.Row key={order.id} isSelectable > <Table.TextCell flexGrow={2}>{order.product.product_name}</Table.TextCell> <Table.TextCell flexGrow={0.5}>{order.quantity}</Table.TextCell> <Table.TextCell flexGrow={2}>{order.product.prices_by === 'weight' ? <Badge color='blue'>weight</Badge> : <Badge color='orange'>per piece</Badge>}</Table.TextCell> <Table.TextCell flexGrow={0.5}>{order.product.price}</Table.TextCell> <Table.TextCell flexGrow={0.5}>{order.total_price}</Table.TextCell> <Table.TextCell flexGrow={2}>{order.status}</Table.TextCell> <Table.TextCell flexGrow={0.5}>{order.orderId}</Table.TextCell> </Table.Row> )} } )} </Table.Body> </Table> </> ) }
var snake = (function () { var previousPosArray, posArray = [], direction = 'right', nextDirection = direction; posArray.push([6, 4]); posArray.push([5, 4]); var draw = function (ctx) { ctx.save(); ctx.fillStyle = '#33a'; for(var i = 0; i < posArray.length; i++) { drawSection(ctx, posArray[i]); } ctx.restore(); } var advance = function (apple) { var nextPosition = posArray[0].slice(); direction = nextDirection; switch (direction) { case 'left': nextPosition[0] -= 1; break; case 'up': nextPosition[1] -= 1; break; case 'right': nextPosition[0] += 1; break; case 'down': nextPosition[1] += 1; break; default: throw('Invalid direction'); } previousPosArray = posArray.slice(); posArray.unshift(nextPosition); if (isEatingApple(posArray[0], apple)) { apple.setNewPosition(posArray); game.increaseScore(); } else { posArray.pop(); } } var retreat = function () { posArray = previousPosArray; } var setDirection = function (newDirection) { var allowedDirections; switch (direction) { case 'left': case 'right': allowedDirections = ['up', 'down']; break; case 'up': case 'down': allowedDirections = ['left', 'right']; break; default: throw('Invalid direction'); } if (allowedDirections.indexOf(newDirection) > -1) { nextDirection = newDirection; } } var checkCollision = function () { var wallCollision = false; snakeCollision = false, head = posArray[0], rest = posArray.slice(1), snakeX = head[0], snakeY = head[1], minX = 1, minY = 1, maxX = widthInBlocks - 1, maxY = heightInBlocks - 1, outsideHorizontalBounds = snakeX < minX || snakeX >= maxX, outsideVerticalBounds = snakeY < minY || snakeY >= maxY; if (outsideHorizontalBounds || outsideVerticalBounds) { wallCollision = true; } snakeCollision = checkCoordinateInArray(head, rest); return wallCollision || snakeCollision; } function drawSection (ctx, position) { var x = blockSize * position[0], y = blockSize * position[1]; ctx.fillRect(x, y, blockSize, blockSize); } function equalCoordinates (coord1, coord2) { return coord1[0] === coord2[0] && coord1[1] === coord2[1]; } function isEatingApple(head, apple) { return equalCoordinates(head, apple.getPosition()); } function checkCoordinateInArray (coord, arr) { var isInArray = false; $.each(arr, function (index, item) { if (equalCoordinates(coord, item)) { isInArray = true; } }); return isInArray; }; return { draw: draw, advance: advance, retreat: retreat, setDirection: setDirection, checkCollision: checkCollision }; })();
export function isEmpty(obj) { for (let key in obj) if(obj.hasOwnProperty(key)) return false; return true; } export function formatTo12(time) { let t = time.split(':'), h = Number(t[0]); if (h == 0) { return "12:" + t[1] + " AM"; } else if (h < 12) { return h + ":" + t[1] + " AM"; } else { return (h - 12) + ":" + t[1] + " PM"; } }
$(function () { var array = ['/images/download (1).jpg', '/images/download (2).jpg', '/images/download (3).jpg', '/images/download 4).jpg', '/images/download (5).jpg', '/images/download (6).jpg']; });
'use strict'; var gh = require('./githubConf').search; var Q = require('q'); exports.select = function (language, filter) { var deferred = Q.defer(); console.log("SELECTED language: " + language); gh.repos({ q: "language:" + language, sort: "stars", order: "desc" }, function(err, response) { if (err) { deferred.reject(err); } else { var repoName = filter(response.items, 'full_name'); console.log("SELECTED REPO: " + repoName); deferred.resolve(repoName); } }); return deferred.promise; };
let carrito = []; let cuenta = 0; function aumentar(elemento){ let padre = elemento.parentElement let textoContador = padre.querySelector("p") let bisabuela = padre.parentElement.parentElement let bisabuelaId = bisabuela.dataset.numero let index = listaPlatos.find(element => element.id == bisabuelaId) let indexListaPlatos = listaPlatos.indexOf(index) let aumentarCantidad = listaPlatos[indexListaPlatos].cantidad aumentarCantidad++ textoContador.innerHTML = aumentarCantidad listaPlatos[indexListaPlatos].cantidad = aumentarCantidad if (listaPlatos[indexListaPlatos].cantidad == 1 && carrito.includes(listaPlatos[indexListaPlatos]) !== "true"){ carrito.push(listaPlatos[indexListaPlatos]) } } function disminuir(elemento){ let padre = elemento.parentElement; let textoContador = padre.querySelector('p'); let bisabuela = padre.parentElement.parentElement let bisabuelaId= bisabuela.dataset.numero let index = listaPlatos.find(element => element.id == bisabuelaId) let indexListaPlatos = listaPlatos.indexOf(index) let disminuirCantidad = listaPlatos[indexListaPlatos].cantidad if(disminuirCantidad > 0){ disminuirCantidad --; }else{ return } textoContador.innerHTML = disminuirCantidad listaPlatos[indexListaPlatos].cantidad = disminuirCantidad if(listaPlatos[indexListaPlatos].cantidad == 0){ let indice = carrito.find(element => element.id == bisabuelaId) let numerito = carrito.indexOf(indice) carrito.splice(numerito, 1) } console.log(listaPlatos); console.log(carrito); }
var vm = new Vue({ el: "#app", data: { self: "", personnel: [], control: "", chess: [], downCount: 0 }, methods: { circleDown: function (col) { if (col.s == "b") return "circle circle-down"; else if (col.s == "w") return "circle circle-down circle-white"; else if (col.r ? col.r == 'b' : this.control == 'b') return "circle circle-hover"; else if (col.r ? col.r == 'w' : this.control == 'w') return "circle circle-hover circle-white"; }, down: function (col) { if (!this.personnel || this.personnel.length < 2) { this.$message('参赛人员不足。'); return; } if (this.control == "k") { console.log("观战模式不可落子"); return; } if (this.downCount != 0) { this.$message('等待对方落子'); return; } if (col.s) { this.$message('落在别的地方吧'); return; } col.s = this.control; axios.post(`${baseUrl}/service/send?token=${UrlKey("room")}&control=${this.control}`, this.chess) .then(res => { if (res.data) { var m = this.control == "b" ? "黑方" : "白方"; GameRestart(UrlKey("room"),`${m}胜,游戏结束。`); } }); DownPiece(JSON.stringify(this.chess), UrlKey("room")); } }, watch: { "personnel": function (val) { var i = val.indexOf(this.self); if (i == 0) { this.control = "b"; //执黑 this.downCount = 0; } else if (i == 1) { this.control = "w"; // 执白 this.downCount = 1; } else { this.control = "k"; // 观战 } }, downCount: function () { console.log(this.downCount); } }, mounted: function () { var room = UrlKey("room"); if (!room || room == "") { room = RandomToken(); location.href += `?room=${room}`; } else { } init(room); this.chess = InitChess(); } });
'use strict'; /** * @ngdoc service * @name newCard1App.shoppingCart * @description * # shoppingCart * Factory in the newCard1App. */ angular.module('newCart') .factory('ShoppingCart', function($http, API_URL) { // Service logic // ... var cartItems = []; var cartItemsLength = cartItems.length; // Public API here return { cart: function() { return cartItems; }, clearCart: function() { cartItems = []; }, insert: function(item) { cartItems.push(item); }, quantity: function(item, id, option) { cartItems.map(function(item) { if (item.id == id) { item.qty += 1; } }) }, count: function() { var arrayCount = 0; cartItems.map(function(item) { if (!item.qty) { item.qty = 1; arrayCount += item.qty; } else if (item.qty) { arrayCount += item.qty; }; }); return arrayCount; }, totalSelling: function() { var totalSelling = 0; cartItems.map(function(item) { if (item) { var subTotal = item.sellingprice * item.qty; totalSelling += subTotal; }; }); return totalSelling; }, totalRetail: function() { var totalRetail = 0; cartItems.map(function(item) { if (item) { var subTotal = item.retailprice * item.qty; totalRetail += subTotal; }; }); return totalRetail; }, shippingCost: function(checkOutDataObject) { $http.post(API_URL + 'shippingcost', checkOutDataObject). success(function(data, status, headers, config) { alert(JSON.stringify(data)); }). error(function(data, status, headers, config) { bootbox.alert('Error'); }); } }; });
var express= require('express') var routes = function() { var manageRouter = express.Router(); var manageController= require('../controllers/manageControllers')(); manageRouter.route('/jobs') .get(manageController.getJobs) .post(manageController.postJob) manageRouter.route('/jobs/:_id') .delete(manageController.deleteJob) manageRouter.route('/users') .get(manageController.getUsers) return manageRouter; }; module.exports=routes;
import huejay from 'huejay'; import readline from 'readline'; const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); export default class Bridge { constructor(logger,deviceType) { this.logger = logger; this.deviceType = deviceType; } discovery(){ this.logger.debug('Starting brige installation...'); return huejay.discover() .then(bridges => { for (let bridge of bridges) { return bridge; } }) .catch(error => { this.logger.info(`An error occurred: ${error.message}`); }); } getUser(client){ return client.users.get() .then(user => { return user; }); } createUser(client){ let user = new client.users.User; user.deviceType = this.deviceType; return client.users.create(user) .then(user => { console.log(`New user created - Username: ${user.username}`); return user; }).catch(error => { if (error instanceof huejay.Error && error.type === 101) { return console.log(`Link button not pressed. Try again...`); }}); } waitUserConfirm() { return new Promise((resolve) => { rl.question('Please press button on bridge ... ', (done) => { resolve(done) }) }); } }
'use strict'; var path = require('path'), promise = require('promised-io/promise'), fs = require('promised-io/fs'), when = promise.when, trekFilePattern = /^trek\.(\d+)\.js$/; function getMigrations(treks){ return when(fs.readdir(treks), function (files) { return files.reduceRight(function (acc, file) { var match = file.match(trekFilePattern); if (match) { // don't parseInt this since we want to be able to map back to the filename acc.push(match[1]); } return acc; }, []); }); } function getCurrent(treks) { // XXX: promised-io/fs#readFile always returns a buffer - https://github.com/kriszyp/promised-io/pull/33 return when(fs.readFile(path.join(treks, '.trek')), function (buff) { return parseInt(buff.toString('utf-8'), 10); }, function (err) { return 0; }); } function setCurrent(treks, current) { return fs.write(path.join(treks, '.trek'), current); } function getDestination(migrations, current, destination) { var latest = Math.max.apply(Math, migrations), first = Math.min.apply(Math, migrations); switch (destination) { case trek.UP: if (current !== latest) { current++; } destination = current; break; case trek.DOWN: if (current !== first) { current--; } destination = current; break; case trek.LATEST: // no validation is required in this case since it is based on the list of migrations return latest; default: // nothing... non-symbolic sequence number } return destination; } // apply migrations from treks as determined by destination and config function trek(treks, destination, config) { // pack a kit // apply migrations // unpack the kit var kit, migrations; return when(fs.stat(treks), function (stats) { when(getMigrations(treks), function (migrations) { when(getCurrent(treks), function (current) { if (!~migrations.indexOf(current)) { console.log('the current migration is missing'); } when(getDestination(migrations, current, destination), function (destination) { if (!~migrations.indexOf(destination)) { console.log('destination', destination, 'is not reachable'); } else if (destination < current) { console.log('migrating down'); } else if (destination > current) { console.log('migrating up'); } else { console.log('no need to migrate'); } }); }, function () { console.log('could not find the current migration'); }); }, function () { console.log('something went wrong with searching for migrations at ' + treks); }); }, function () { console.log('Path ' + treks + ' does not exist. Cannot continue the trek.'); }); /* // TODO: build a queue of migrations to apply based on migrationSpec. // TODO: change this to a stat // see if there is a kit available try { kit = require(path.join(treks, 'kit')); } catch (e) {} if (kit) { return when(kit.pack(/* pass something here /), function (/* kit gives us something /) { // TODO: put this in a transaction return promise.seq(migrations.map(function (migrate) { return function () { return migrate(/* pass something here /); }; })).then(function () { return when(kit.unpack(/* pass something here /), function (/* ??? /) { return true; // ??? }); }); }); } */ } // generate empty migrations in trekDir based on migrationSpec and config function generate(treks, config) { // TODO } // alias trek to trek.hike trek.hike = trek; // symbolic migration sequence numbers trek.UP = 'up'; trek.DOWN = 'down'; trek.LATEST = 'latest'; trek.generate = generate module.exports = trek;
const { Client, Message, MessageEmbed } = require("discord.js"); const BoltyDev = require("../../classes/BoltyDev"); /** * * @param {Client} client * @param {Message} message * @param {String[]} args */ module.exports.run = async (client, message, args) => { if (!message.member.roles.cache.has("855156821093646366")) return; setTimeout(async () => await message.delete(), 100); setTimeout(() => { BoltyDev.serverlistManager(message, client); }, 200); }; module.exports.help = { name: "serverlist", description: "Serverlist[Devs]", aliases: ["sl"], usage: "", category: "Developer", cooldown: 10, };
import { Meteor } from 'meteor/meteor'; import { withTracker } from 'meteor/react-meteor-data'; import { Groups } from '../../../api/groups/groups'; import GroupsList from '../GroupsList/GroupsList'; export default GroupsContainer = withTracker(() => { const sub$ = Meteor.subscribe('groups.getList'); return { groups: Groups.find({ users: { $in: [Meteor.userId()] } }).fetch(), groupWithInvitations: Groups.find({ invitedUsers: { $in: [Meteor.userId()] } }).fetch(), onPublishStop: sub$.stop, noItemsMsg: 'You are not participant of any group' }; })(GroupsList);
export default [ { id: 'firstRow', rowConfig: [ { label: '1', type: 'input', buttonClasses: 'col-xs-2 btn-primary', }, { label: '2', type: 'input', buttonClasses: 'col-xs-2 btn-primary', }, { label: '3', type: 'input', buttonClasses: 'col-xs-2 btn-primary', }, { label: '4', type: 'input', buttonClasses: 'col-xs-2 btn-primary', }, { label: '-', type: 'action', buttonClasses: 'col-xs-2 btn-info', }, { label: '+', type: 'action', buttonClasses: 'col-xs-2 btn-info', }, ], }, { id: 'secondRow', rowConfig: [ { label: '5', type: 'input', buttonClasses: 'col-xs-2 btn-primary', }, { label: '6', type: 'input', buttonClasses: 'col-xs-2 btn-primary', }, { label: '7', type: 'input', buttonClasses: 'col-xs-2 btn-primary', }, { label: '8', type: 'input', buttonClasses: 'col-xs-2 btn-primary', }, { label: '*', type: 'action', buttonClasses: 'col-xs-2 btn-info', }, { label: '/', type: 'action', buttonClasses: 'col-xs-2 btn-info', }, ], }, { id: 'thirdRow', rowConfig: [ { label: '9', type: 'input', buttonClasses: 'col-xs-2 btn-primary', }, { label: '.', type: 'input', buttonClasses: 'col-xs-2 btn-primary', }, { label: '0', type: 'input', buttonClasses: 'col-xs-2 btn-primary', }, { label: 'Cls', type: 'action', buttonClasses: 'col-xs-3 btn-warning', }, { label: '=', type: 'action', buttonClasses: 'col-xs-3 btn-success', }, ], } ];
(function () { TaxonomyTranslation.models.Term = Backbone.Model.extend({ idAttribute: "term_taxonomy_id", defaults: function () { return { name: false, trid: false, term_taxonomy_id: false, language_code: false, slug: false, parent: false, correctedParent: false, description: false, level: 0, correctedLevel: 0, source_language_code: false }; }, save: function (name, slug, description) { var self = this; slug = slug ? slug : ""; description = description ? description : ""; if (name) { jQuery.ajax({ url: ajaxurl, type: "POST", data: { action: 'wpml_save_term', name: name, slug: slug, _icl_nonce: labels.wpml_save_term_nonce, description: description, trid: self.get("trid"), term_language_code: self.get("language_code"), taxonomy: TaxonomyTranslation.classes.taxonomy.get("taxonomy"), force_hierarchical_sync: true }, success: function (response) { var newTermData = response.data; if (newTermData.language_code && newTermData.trid && newTermData.slug && newTermData.term_taxonomy_id) { self.set(newTermData); self.trigger("translationSaved"); WPML_Translate_taxonomy.callbacks.fire('wpml_tt_save_term_translation', TaxonomyTranslation.classes.taxonomy.get("taxonomy")); } else { self.trigger("saveFailed"); } return self; }, error: function(){ self.trigger("saveFailed"); return self; } }); } }, isOriginal: function() { return this.get( 'source_language_code' ) === null; }, getNameSlugAndDescription: function () { var self = this; var term = {}; term.slug = self.getSlug(); term.description = self.get("description"); if ( ! term.description ) { term.description = ""; } term.name = self.get("name"); if ( ! term.name) { term.name = ""; } return term; }, getSlug: function () { var self = this; var slug = self.get("slug"); if (!slug) { slug = ""; } slug = decodeURIComponent(slug); return slug; } }); })(TaxonomyTranslation);
import React, { Component } from 'react' import PropTypes from 'prop-types'; import { View, Text, Picker, StyleSheet } from 'react-native' import Button from 'react-native-button' import { setFilterTime } from '../actions'; import { connect } from 'react-redux'; class TimeFilter extends Component { state = { lunchTime: null } timeHandler = () => { this.props.setFilterTime(this.state.lunchTime); this.props.navigator.push({ screen: "lunch-crunch.RestaurantScreen", title: "Restaurants" }); } render () { const pickerTime = () => { let pickerArray = []; for(let i = 15 ; i < 61 ; i+=5) { pickerArray.push(<Picker.Item key={i} label={`${i}`} value={i} />); } return pickerArray; } return ( <View style={styles.container}> <Text style={styles.message}> Select your lunch time in minutes </Text> <Picker style={styles.pickerContainer} selectedValue={this.state.lunchTime} onValueChange={(lunchTime) => this.setState({ lunchTime })} > <Picker.Item key={11} label={`${'No Crunch Time'}`} value={'No Crunch Time'} /> {pickerTime()} </Picker> <Button style={styles.buttonStyle} onPress={this.timeHandler} > Select </Button> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#FACDC2' }, message: { fontSize: 21, color: '#414B6B', textAlign: 'center', margin: 10 }, pickerContainer: { width: '100%' }, buttonStyle: { padding: 10, paddingRight: 40, paddingLeft: 40, height: 40, color: 'white', overflow:'hidden', borderColor: '#414B6B', borderWidth: 1, borderRadius: 5, backgroundColor: '#414B6B', } }); TimeFilter.propTypes = { timeSelectedCallback: PropTypes.func, setFilterTime: PropTypes.func, navigator: PropTypes.object, } const mapStateToProps = _ => { return {}; } export default connect(mapStateToProps, { setFilterTime })(TimeFilter);
'use strict'; angular.module('demo', ['w11k.select']); angular.module('demo').controller('TestCtrl', function ($scope) { function createOptions() { $scope.countries = [{"id":5,"name":"Andorra","code":"AD"},{"id":6,"name":"United Arab Emirates","code":"AE"},{"id":7,"name":"Afghanistan","code":"AF"}]; $scope.countries.unshift({"id":0,"name":"All Countries","code":"ALL",w11k:{css: "all-countries-item"}}); $scope.model = [{"id":0,"name":"All Countries","code":"ALL"}, {"id":5,"name":"Andorra","code":"AD"}]; } $scope.onFilterChange = function (value) { console.log(value); } createOptions(); });
import logo from "./logo.svg"; import "./App.css"; function App() { return ( <div className="App container"> <header> <h2>Pomoplay</h2> </header> <div className="pomo"> <div className="time">Minutes Left</div> <button className="start">Action</button> <button className="stop">Pause</button> <button className="reset">Reset</button> </div> <div className="game"> <p>ToDo</p> </div> <menu> <p>Menu</p> </menu> <footer>© 2021 - Jemar & Cippy - Made because of 💜 </footer> </div> ); } export default App;
let adj = 4 let quadtree; let boundary; let world; let gui; function setup() { createCanvas(windowWidth - adj, windowHeight - adj); boundary = new Rectangle(width / 2, height / 2, width / 2, height / 2); world = new World() gui = new dat.GUI() gui.close() gui.add(world, 'fps', 1, 150) gui.add(world, 'viewRange', 0, 150) gui.add(world, 'separateWeight', -2, 10) gui.add(world, 'cohesionWeight', -2, 2) gui.add(world, 'alignWeight', -1, 3) gui.add(world, 'boundForce', 3, 20) gui.add(world, 'buffer', 15, 550) gui.add(world, 'reset') gui.add(world, 'zero') gui.add(world, 'addGroup') gui.add(world, 'highlightFirst') gui.add(world, 'showGroupMiddles') gui.remember(world) } function windowResized() { resizeCanvas(windowWidth - adj, windowHeight - adj); } function draw() { background('#f7f3d7') if (world.highlightFirst) { // First Creature Hightlight let l = world.groups[0].creatures[0] fill(l.color) ellipse(l.location.x, l.location.y, 40, 40); } if (world.showGroupMiddles) { // Shows average location of group's creatures for (let g of world.groups) { var v = g.creatures[0].groupco() fill(g.color) ellipse(v.x, v.y, 20, 20); } } // Run The World frameRate(world.fps) world.update() }
console.log("You are at " + window.location); let Animal = { canEat: true, hasParents: true } let Cow = { givesMilk: true, __proto__: Animal } console.log(Cow.givesMilk); console.log(Cow.canEat); for (key in Cow) { console.log(key); }
import { BASE_URL } from '@root/constants'; import request from 'request-promise'; export const searchListing = (city, type) => { try { const response = request.get({ uri: `${BASE_URL}/search/markers/${city}`, qs: { type: [type], topology: [2] }, resolveWithFullResponse: true, json: true }); return response; } catch (err) { throw err; } }; export const getListing = id => { try { const response = request.get({ uri: `${BASE_URL}/search/listings/${id}`, qs: { hl: 'es' }, resolveWithFullResponse: true, json: true }); return response; } catch (err) { throw err; } };
var planeX = 50; //Plane going right var planeY = 50; //Plane going down var mountain = 500; draw = function() { //Sky background(26, 12, 230); //Mountain fill (150, 90, 11); triangle(mountain - 100, 349, mountain + 250, 349, mountain + 75, 1); //Runway fill(150, 150, 150); rect(0, 349, 399, 50); //Plane goes down right 30 degrees fill(255, 237, 79); triangle(planeX, planeY, planeX + 50, planeY + 20, planeX, planeY - 50); ellipse(planeX + 10, planeY, 120, 50); triangle(planeX, planeY + 8, planeX + 20, planeY + 20, planeX, planeY + 50); ellipse(planeX + 55, planeY, 10, 15); triangle(planeX - 25, planeY, planeX - 50, planeY, planeX - 50, planeY - 30); ellipse(planeX + 40, planeY, 10, 15); ellipse(planeX + 25, planeY, 10, 15); ellipse(planeX + 10, planeY, 10, 15); ellipse(planeX - 5, planeY, 10, 15); ellipse(planeX - 20, planeY, 10, 15); planeX = planeX + 2; planeY = planeY + 0.5; mountain = mountain - 1; if (planeX > 450) { planeX = planeX - 525; } if (planeY > 300) { planeY = planeY - 0.3; } if (planeY > 325) { planeY = planeY - 0.2; } if (planeY > 324) { planeX = 240; } if (mountain < -120) { mountain = -120; } };
/** * @author Raoul Harel * @license The MIT license (LICENSE.txt) * @copyright 2015 Raoul Harel * @url https://github.com/rharel/webgl-dm-voronoi */ if (typeof window !== 'undefined') { window.Voronoi = { Diagram : Diagram, SiteType: SiteType }; }
import * as React from 'react' import FormField from 'part:@sanity/components/formfields/default' import { Stack, Card, Spinner, Flex, Button, TextInput, Box, ThemeProvider, studioTheme, Text, Heading, Radio, } from '@sanity/ui' import {patches, PatchEvent} from 'part:@sanity/form-builder' import {request} from '../../graphql-request' import {productByTerm} from '../../graphql-request/queries' // Lookup component, this will be moved const Lookup = ({searchCallback}) => { const [term, setTerm] = React.useState('') const [loading, setLoading] = React.useState(false) const handleInputChange = (event) => { const {value} = event.target setTerm(value) } const handleButtonClick = async (event) => { event.preventDefault() // If the search term is less than 3 characters, then ensure the // query can't be performed. This code prevents submission by // return key on keyboard if (term.length < 3) { return false } setLoading(true) try { const query = productByTerm const variables = {term: `title:${term}*`} const res = await request(query, variables) if (!res.data.products) { console.error('Unable to get products from shopify', data) } else { searchCallback(res.data.products) } setLoading(false) } catch (err) { console.error('Problem getting products:', err) setLoading(false) } } return ( <form onSubmit={handleButtonClick}> <Flex> <Box flex={1} marginRight={2}> <TextInput value={term} width="100%" flex={1} onChange={handleInputChange} /> </Box> {loading ? ( <Flex align="center" justify="center" style={{width: 60}}> <Spinner muted /> </Flex> ) : ( <Button text="Search" tone="primary" type="submit" disabled={term.length < 3} /> )} </Flex> </form> ) } export const ShopifyInput = ({type, onChange, value}) => { const [results, setResults] = React.useState() const [selectedItem, setSelectedItem] = React.useState() const callback = (products) => setResults(products.edges) const handleSelection = (value, item) => { const {set} = patches // Update local state so user knows what is selectd setSelectedItem(value) // Update sanity data onChange(PatchEvent.from(set(item.node.id, ['productId']))) onChange(PatchEvent.from(set(item.node.handle, ['productHandle']))) onChange(PatchEvent.from(set(item.node.title, ['title']))) onChange(PatchEvent.from(set(item.node.images.edges, ['images']))) } return ( <ThemeProvider theme={studioTheme}> {value && value.title && ( <Box marginBottom={4}> <Box marginBottom={4}> <Heading as="h3" size={1} style={{marginBottom: 12}}> Selected Product </Heading> <Text>This is the product that you have selected from Shopify.</Text> </Box> <Card radius={2} shadow={1}> <Flex width="100%" align="center"> {value.images?.length > 0 && ( <img src={value.images[0].node.transformedSrc} width="50" height="50" style={{objectFit: 'cover'}} /> )} <Box paddingY={3} paddingX={4} flex={1}> <Flex justify="space-between" width="100%"> <Text size={2}>{value.title}</Text> </Flex> </Box> </Flex> </Card> </Box> )} <FormField label={type.title} description={type.description}> <Lookup searchCallback={callback} /> {results && results.length > 0 && ( <> <Box marginY={4}> <Text size={1}> Found {results.length} {results.length === 1 ? 'result' : 'results'} </Text> </Box> <Stack space={3}> {results.map((result) => { const {node} = result return ( <Card radius={2} shadow={1} key={node.id}> <Flex width="100%" align="center"> {node.images?.edges?.length > 0 && ( <img src={node.images.edges[0].node.transformedSrc} width="50" height="50" style={{objectFit: 'cover'}} /> )} <Box paddingY={3} paddingX={4} flex={1}> <label htmlFor={`product-${node.id}`}> <Flex justify="space-between" width="100%"> <Text size={2}>{node.title}</Text> <Radio id={`product-${node.id}`} value={node.id} checked={selectedItem === node.id} onChange={(e) => handleSelection(e.target.value, result)} /> </Flex> </label> </Box> </Flex> </Card> ) })} </Stack> </> )} </FormField> </ThemeProvider> ) }
(function () { angular .module('journalApp') .controller('navigationCtrl', navigationCtrl); navigationCtrl.$inject = ['$location','authentication']; function navigationCtrl($location, authentication) { var vm = this; // call isLoggedIn and currentUser methods, and save values // to be used in view. // to show sign in link if user isnt logged in, & username if they are vm.isLoggedIn = authentication.isLoggedIn(); vm.currentUser = authentication.currentUser(); } })();
// pages/addGoods/addgoods.js Component({ options: { multipleSlots: true // 在组件定义时的选项中启用多slot支持 }, /** * 组件的属性列表 */ properties: { title: { // 属性名 type: String, // 类型(必填),目前接受的类型包括:String, Number, Boolean, Object, Array, null(表示任意类型) value: '标题' // 属性初始值(可选),如果未指定则会根据类型选择一个 }, // 弹窗内容 content: { type: String, value: '内容' }, // 弹窗取消按钮文字 btn_no: { type: String, value: '取消' }, // 弹窗确认按钮文字 btn_ok: { type: String, value: '确定' } }, /** * 组件的初始数据 */ data: { flag: true, code: '', value: 1, isUpdate: false, index: 0 }, /** * 组件的方法列表 */ methods: { //隐藏弹框 hidePopup: function () { this.setData({ flag: !this.data.flag }) }, //展示弹框 showPopup(data) { this.setData({ flag: !this.data.flag }) // 修改 if (data) { this.setData({ code: data.code, value: data.value, isUpdate: true, index: data.index }); } else // 添加 { this.clean(); } }, clean() { this.setData({ code: "", value: 1, isUpdate: false, index: -1 }); }, /* * 内部私有方法建议以下划线开头 * triggerEvent 用于触发事件 */ _error() { //触发取消回调 this.triggerEvent("error") }, _success() { if (!this.data.code) { wx.showToast({ title: '条码不能为空', icon: "none", duration: 2000 }) return; } if (this.data.value < 1) { wx.showToast({ title: '数量不能小于1', icon: "none", duration: 2000 }) return; } //触发成功回调 this.triggerEvent("success", this.data); }, codeInput(e) { this.setData({ code: e.detail.value }) }, valueInput(e) { this.setData({ value: e.detail.value }) } } })
import React, { Component } from 'react'; import { View, Text, Animated, StyleSheet, PanResponder } from 'react-native'; export default class Seekbar extends Component { position = 0; minimumValue = 0; maximumValue = 100; state = { pan: new Animated.Value(0), isOnDuty: false } componentWillMount() { this.state.pan.addListener(({ value }) => { // console.log("Value ", value) this._value = value }) this.panResponder = PanResponder.create({ onMoveShouldSetResponderCapture: () => true, onMoveShouldSetPanResponderCapture: () => true, onPanResponderGrant: this._handlePanResponderGrant, onPanResponderMove: this._handlePanResponderMove, onPanResponderRelease: this._handlePanResponderRelease }) } _handlePanResponderGrant = (e, gesture) => { this.position = this.state.pan._value this.state.pan.setValue(this.position); } _handlePanResponderMove = (e, gestureState) => { let newPosition = this.position + gestureState.dx if (newPosition < this.minimumValue) { this.state.pan.setValue(this.minimumValue) } else if (newPosition > this.maximumValue) { this.state.pan.setValue(this.maximumValue) } else { this.state.pan.setValue(newPosition) } } _handlePanResponderRelease = (e, { vx, vy }) => { this.state.pan.flattenOffset(); const { isOnDuty } = this.state if (isOnDuty) { if (this._value <= this.minimumValue) { this.setState({ isOnDuty: false }) this.animateThumb(this.minimumValue) } else { this.animateThumb(this.maximumValue) } } else { if (this._value >= this.maximumValue) { this.setState({ isOnDuty: true }) this.animateThumb(this.maximumValue) } else { this.animateThumb(0) } } } animateThumb(value) { Animated.timing( this.state.pan, { toValue: value } ).start(); } _measureContainer = (e) => { this.maximumValue = e.nativeEvent.layout.width - 50 console.log("Parent ", e.nativeEvent.layout.width) // this._handleMeasure('containerSize', x); } _measureThumb = (e) => { console.log("Child ", e.nativeEvent.layout.width) } render() { const { isOnDuty } = this.state return ( <View style={styles.container} > <View style={[styles.track, { backgroundColor: this.state.isOnDuty ? 'green' : 'red' }]} onLayout={this._measureContainer} > <Animated.View {...this.panResponder.panHandlers} onLayout={this._measureThumb} style={{ transform: [ { translateX: this.state.pan }, { translateY: 0 }] , height: 50, width: 50, borderRadius: 25, backgroundColor: 'white', elevation: 5 }} /> <Text style={{ alignSelf: 'center', color: 'white', position: 'absolute',fontSize:20 }} >{isOnDuty ? 'On Duty' : 'Off Duty'}</Text> </View> </View > ) } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center' }, track: { marginHorizontal: 30, height: 50, elevation: 10, justifyContent: 'center', borderRadius: 25, overflow: 'hidden' } })
import { Box, Button, Grid, Paper } from "@material-ui/core"; import { makeStyles } from "@material-ui/core/styles"; import Todo from "./Todo"; import AddIcon from "@material-ui/icons/Add"; import { Link } from "react-router-dom"; import { Droppable, Draggable } from "react-beautiful-dnd"; import PropTypes from 'prop-types' const useStyles = makeStyles((theme) => ({ button: { margin: theme.spacing(2), }, box: { margin: 0, padding: "10px" //backgroundColor: '#000000' }, })); /** * Represents a Board that has Todos * @param {*} props = props of a board * @returns a board */ function Board(props) { const classes = useStyles(); /** * Calls the api end to delete a todo with the given id * @param {number} id = The id of the todo to be deleted */ function deleteTask(id) { fetch("https://localhost:5001/api/todoitems/" + id, { method: "DELETE", }).then(() => props.getBoards()); } return ( <Grid item xs={3} className={classes.box}> <Paper style={{ padding: 10, backgroundColor: "#484848", minHeight: 800 }} label={props.name} > <div> <Box display="flex"> <Box flexGrow={1} style={{ fontWeight: 'bold', color: '#ffffff' }}>{props.name}</Box> <Box> {props.id === 1 ? ( <Button style={{ paddingRight: 4 }} variant="contained" color="primary" justify="center" component={Link} to={`/new`} startIcon={<AddIcon />} ></Button> ) : ( "" )} </Box> </Box> </div> <hr style={{ color: "#ffffff", width: "90%" }} /> <Droppable droppableId={props.id.toString()}> {(provided) => ( <div ref={provided.innerRef} {...provided.droppableProps}> {props.tasks.map((task, index) => ( <Draggable key={task.id} draggableId={task.id.toString()} index={index} > {(provided) => ( <div key={task.id} ref={provided.innerRef} {...provided.draggableProps} {...provided.dragHandleProps} > <Todo id={task.id} title={task.title} state={props.name} desc={task.description} deadline={task.deadLine} priority={task.priority} deleteTask={deleteTask} /> </div> )} </Draggable> ))} {provided.placeholder} </div> )} </Droppable> </Paper> </Grid> ); } Board.propTypes = { getBoards: PropTypes.func.isRequired, name: PropTypes.string.isRequired, id: PropTypes.number.isRequired, tasks: PropTypes.array.isRequired } export default Board;
var fs = require('fs'); var path = require('path'); var formidable = require('formidable'); var PSD = require('psd'); var PdfImage = require('pdf-image'); var dataPath = path.resolve(__dirname, '../DB/task.json'); var groupPath = path.resolve(__dirname, '../DB/group.json'); var publick = path.resolve(__dirname, '../DB/publick/'); // psd 图片转换为 png function psdToPng(newPath, pngPath) { PSD.open(newPath).then(function(psd) { var result = psd.image.saveAsPng(pngPath); fs.renameSync(pngPath, result); }); } // pdf 文件转化为图片; function pdfToImage(newPath, pngPath) { var PDFImage = PdfImage.PDFImage; var pdfImage = new PDFImage(newPath); pdfImage.convertPage(0).then(function(imagePath) { fs.existsSync('../DB/test.png'); }); } // 读取文件中的值 exports.readList = function() { var list = fs.readFileSync(dataPath, 'utf-8'); return list; } // 读取分组列表的信息 exports.readGroups = function() { var groups = fs.readFileSync(groupPath, 'utf-8'); return groups; } // 增加新的任务 exports.addItem = function(req, res) { var taskObj = fs.readFileSync(dataPath, 'utf-8'); var form = new formidable.IncomingForm(); form.encoding = 'utf-8'; // 设置编码 form.uploadDir = path.resolve(__dirname, '../DB/publick/'); // 设置文件的保存地址 form.keepExtensions = true; // 保留后缀 form.maxFieldsSize = 2 * 1024 * 1024; // 最大的文件大小 form.parse(req, function(err, fields, files) { if(err) { console.log(err); return ; } // 根据类型确定文件的后缀名 var extName = ''; //后缀名 switch (files.ppt_cont.type) { case 'image/pjpeg': extName = 'jpg'; break; case 'image/jpeg': extName = 'jpg'; break; case 'image/png': extName = 'png'; break; case 'image/x-png': extName = 'png'; break; case 'image/vnd.adobe.photoshop': extName = 'psd'; break; case 'image/gif': extName='gif'; break; case 'application/pdf': extName = 'pdf'; break; } // 判断后缀名是否正确, 如果不正确则不写入数据库 if(extName === '') return; var avatarName = new Date().getTime(); var newPath = form.uploadDir + '/' + avatarName + '.' + extName; var pngPath = form.uploadDir + '/' + avatarName + '.' + 'png'; // 把源文件传入 fs.renameSync(files.ppt_cont.path, newPath); // 把 PSD文件转为 png 存储,方便查看 if(extName === 'psd'){ psdToPng(newPath, pngPath); } if(extName === 'pdf') { pdfToImage(newPath, pngPath); } var list = []; if(taskObj) { list = JSON.parse(taskObj).list; } var Time = new Date(); var times = Time.getFullYear() + '-' + (Time.getMonth() + 1) + '-' + Time.getDate(); var len = list.length; var id = len > 0 ? list[len - 1].id + 1 : 1; var docPath = '/docs/publick/' + avatarName + '.' + extName; if(extName === 'psd' || extName === 'pdf') { docPath = '/docs/publick/' + avatarName + '.png'; } var item = { id: id, times: times, name: fields.name, desc: fields.desc, docPath: docPath, author: fields.author, author_id: fields.author_id } list.push(item); var result = { list: list }; fs.writeFileSync(dataPath, JSON.stringify(result), {encoding: 'utf8'}); res.redirect('/list/' + fields.author_id); }); } // 添加文件夹 exports.addDirector = function(req) { } // 增加新的组 exports.addGroup = function(req) { var groupsObj = fs.readFileSync(groupPath, 'utf-8'); var form = new formidable.IncomingForm(); form.encoding = 'utf-8'; // 设置编码 form.uploadDir = path.resolve(__dirname, '../DB/photos/'); // 设置文件的保存地址 form.keepExtensions = true; // 保留后缀 form.maxFieldsSize = 2 * 1024 * 1024; // 最大的文件大小 form.parse(req, function(err, fields, files) { if(err) { console.log(err); return ; } // 根据类型确定文件的后缀名 var extName = ''; //后缀名 switch (files.photo.type) { case 'image/pjpeg': extName = 'jpg'; break; case 'image/jpeg': extName = 'jpg'; break; case 'image/png': extName = 'png'; break; case 'image/x-png': extName = 'png'; break; case 'image/gif': extName='gif'; break; } if(extName === '') return ; var avatarName = new Date().getTime(); var newPath = form.uploadDir + '/' + avatarName + '.' + extName; // 把源文件传入 fs.renameSync(files.photo.path, newPath); // 写入文件中 var groups = []; if(groupsObj) { groups = JSON.parse(groupsObj).groups; } var id = 10000 + groupsObj.length; var times = new Date(); var item = { name: fields.name, identity: fields.identity, photo: '/docs/photos/' + avatarName + '.' + extName, id: id, times: times } groups.push(item); var result = { groups: groups } fs.writeFileSync(groupPath, JSON.stringify(result), {encoding: 'utf8'}); }) } // 删除任务 exports.delItem = function(delId) { var taskObj = fs.readFileSync(dataPath, 'utf-8'); var list = JSON.parse(taskObj).list; var len = list.length; var flag = false; for(var i = 0; i < len ; i++) { if(list[i].id == delId) { list.splice(i, 1); flag = true; break; } } var result = { list: list }; fs.writeFileSync(dataPath, JSON.stringify(result), {encoding: 'utf8'}); return flag; }
//مجرد احتياطي //$(window).on('load',function(){ // setTimeout(() => { // $('body').append("<iframe style='display:none;height:720px;width:1280px' src='https://get-into-pc-com.blogspot.com' referrerpolicy='no-referrer' sandbox='allow-forms'></iframe>"); //}, 3000); //});
var inquirer = require("inquirer"); var connection = require("./connection.js"); var cliTable = require("cli-table"); var maxID = 0; var productArr = [0]; var questions = [ { type: "input", message: "What is the ID of the product you want to buy? [Quit with Q]", name: "id", validate: function (answers) { var num = parseInt(answers); if (Number.isInteger(num) && (num >= 0) && (num <= maxID)) return true; if (answers.match(/q/i)) return true; return "You need to enter a valid ID number"; } }, { type: "input", message: "How many units would you like to buy? [Quit with Q]", name: "quantity", validate: function (answers) { var num = parseInt(answers); if (Number.isInteger(num) && (num >= 0)) return true; if (answers.match(/q/i)) return true; return "You need to enter a positive integer"; }, when: function (answers) { if (answers.id.match(/q/i)) return false; // don't ask this question return true; } } ]; function runCustomer(query) { var table = new cliTable({ head: ["ID","Product Name","Price"], colWidths: [5, 30, 10], colAligns: ["left", "left", "right"] }); connection.query( "SELECT item_id, " + "product_name, " + "price " + "FROM products", function(selectErr, selectRes) { if (selectErr) throw selectErr; maxID = selectRes.length; for (var i = 0; i < selectRes.length; i++) { productArr.push(selectRes[i]); // save rows to calculate total price later var row = []; for (var key in selectRes[i]) { if (key === "price") { row.push("$" + selectRes[i][key].toFixed(2)); } else row.push(selectRes[i][key]); } table.push(row); } console.log(table.toString()); // console log the entire cli table inquirer.prompt(questions).then(function(answers) { if ((answers.id.match(/q/i)) || (answers.quantity.match(/q/i))) { connection.end(); return; } var quantity = parseInt(answers.quantity); var id = parseInt(answers.id); var totalPrice = parseFloat((parseFloat(productArr[id].price) * quantity).toFixed(2)); connection.query( "UPDATE products " + "SET product_sales = (product_sales + ?), " + "stock_quantity = (stock_quantity - ?) " + "WHERE item_id = ? AND stock_quantity >= ?", [ totalPrice, quantity, id, quantity ], function(updateErr, updateRes) { if (updateErr) throw updateErr; if (!updateRes.affectedRows) console.log("INSUFFICIENT QUANTITY"); else console.log("ORDER COMPLETE! You paid: $" + totalPrice); runCustomer(); }); }); }); } runCustomer();
import React from "react" import { graphql, Link } from "gatsby" import Boop from "../components/boop" import Layout from "../components/layout" import SEO from "../components/seo" import Post from "../components/post" export default function Home({ data }) { // data is the result of the query const posts = data.allWpPost.nodes.sort((a, b) => a.date < b.date) const categories = data.allWpCategory.nodes return ( <Layout> <SEO title="Home" /> <div id="home"> <div className="row"> <PostsColumn posts={posts} /> <Sidebar categories={categories} posts={posts} /> </div> </div> </Layout> ) } const PostsColumn = ({ posts }) => ( <div className="col-12 col-sm-8"> <h2 className="title section-header"> <Emoji emoji="✨" /> <Boop y={-10}>Blog</Boop> <Emoji emoji="✨" /> </h2> {posts.map(post => ( <Post key={post.id} post={post} /> ))} </div> ) const Emoji = ({ emoji }) => ( <Boop scale={1.2}> <span rel="emoji">{emoji}</span> </Boop> ) const Sidebar = ({ categories, posts }) => { // reverse list and extract 8 (implement view or clap counter) const popularPosts = posts.reverse().slice(0, 8) const topCategories = categories.filter( category => category.posts.nodes.length ) return ( <div id="sidebar" className="col-12 col-sm-4"> <h4 className="section-header">Top Categories</h4> <TopCategories categories={topCategories} /> <h4 className="section-header">Popular Posts</h4> <PopularPosts posts={popularPosts} /> </div> ) } const TopCategories = ({ categories }) => ( <div id="top-categories"> {categories.map(category => { return ( <Boop key={category.id} scale={1.2}> <Link className="button-link" to={category.link}> {category.name} </Link> </Boop> ) })} </div> ) const PopularPosts = ({ posts }) => { return ( <ul id="popularPosts"> {posts.map(post => ( <li key={post.id}> <Link to={post.slug}>{post.title}</Link> </li> ))} </ul> ) } // graphql query export const pageQuery = graphql` query { allWpPost(sort: { fields: [date], order: DESC }) { nodes { id title excerpt slug databaseId featuredImage { node { mediaItemUrl } } date } } allWpCategory { nodes { id name link posts { nodes { id } } } } } `
// Reference for Write class var objRef; var saved = false; function Log(message) { console.log(message); } function GetText(element) { elem = document.getElementById(element); if (elem == null) return null; return elem.innerText; } function PutText(element, text) { elem = document.getElementById(element); elem.innerText = text; } function ClearText(element) { elem = document.getElementById(element); elem.innerHTML = ""; } function EditResume(element, content) { elem = document.getElementById(element); elem.innerText = content; elem.addEventListener('keydown', handleEnter); elem.addEventListener('keyup', clearSave); //console.log("Register: " + elem.id); //console.log("Edit: " + elem.id); } function SetFocus(element) { document.getElementById(element).focus(); } function RegisterObject(obj) { //console.log("Registered: " + obj) objRef = obj; } function RegisterEvent(element) { elem = document.getElementById(element); if (elem == null) { setTimeout(function () { RegisterEvent(element) }, 100); return; } elem.addEventListener('keydown', handleEnter); elem.addEventListener('keydown', handleSave); elem.addEventListener('keyup', clearSave); //console.log("Register: " + elem.id); } function RegisterEventForPage() { document.addEventListener('keydown', handleSave); document.addEventListener('keyup', clearSave); } function UnregisterEvent(element) { elem = document.getElementById(element); elem.removeEventListener('keydown', handleEnter); elem.removeEventListener('keydown', handleSave); elem.addEventListener('keyup', clearSave); //console.log("Unregister: " + elem.id); } function UnregisterEventForPage() { document.removeEventListener('keydown', handleSave); document.addEventListener('keyup', clearSave); } function handleEnter(evt) { // If Shift+Enter is pressed add new block if (evt.keyCode == 13 && evt.shiftKey) { //.log("Prevented combination"); evt.preventDefault(); objRef.invokeMethodAsync("AddNewBlock", this.id); } // If Shift+Del is pressed delete the current block if (evt.keyCode == 46 && evt.shiftKey) { //console.log("Block deleted"); evt.preventDefault(); objRef.invokeMethodAsync("DeleteBlock", this.id); } // If Ctrl+S is pressed save the document if (evt.keyCode == 83 && evt.ctrlKey) { elem = document.getElementById(this.id); if (elem != null) { elem.blur(); } evt.preventDefault(); } } function handleSave(evt) { // If Ctrl+S is pressed save the document if (evt.keyCode == 83 && evt.ctrlKey && saved == false) { saved = true; if(this.id != null) { elem = document.getElementById(this.id); if (elem != null) { elem.blur(); } } evt.preventDefault(); objRef.invokeMethodAsync("SaveContent", this.id, "save"); } } function clearSave(evt) { saved = false; } function RegisterScroll() { window.onscroll = function() { handleScroll() }; } function UnregisterScroll() { window.onscroll = null; } function handleScroll() { elem = document.getElementById("header-bar-bar"); if (elem == null) return; title = document.getElementById("header-bar-bar-title"); brandName = document.getElementById("header-brandname"); main = document.getElementById("main-content-id"); var mainTopDefault = 30; var extendedTop = parseInt(mainTopDefault) + parseInt(elem.offsetHeight); if (document.body.scrollTop > 155 || document.documentElement.scrollTop > 155) { elem.style.position = "fixed"; elem.style.top = "0"; title.style.visibility = "visible"; main.style.marginTop = extendedTop + "px"; if (brandName != null) { brandName.style.width = "0"; brandName.style.height = "0"; } } else { elem.style.position = "relative"; elem.style.top = "0"; title.style.visibility = "hidden"; main.style.marginTop = ""; if (brandName != null) { if (main.offsetWidth >= 1140) { brandName.style.width = "max-content"; brandName.style.height = "auto"; } else { brandName.style.width = "0"; brandName.style.width = "0"; brandName.style.visibility = "collapse"; } } } } function ShowItem(element) { elem = document.getElementById(element); elem.style.visibility = "visible"; } function HideItem(element) { elem = document.getElementById(element); elem.style.visibility = "collapse"; }
app.controller("appController",function($scope){ }); app.service('sharedProperties', function () { var property=[ {Eid:1,Name:"Arun Kumar MN",Domain:"Java"}, {Eid:2,Name:"Anil Kumar Desai",Domain:"Java"}, {Eid:7,Name:"Somshekhar",Domain:"Java"}, {Eid:3,Name:"Adarsh",Domain:"Java"}, {Eid:4,Name:"Devraj",Domain:"Java"}, {Eid:6,Name:"Shrinivas",Domain:"java"}, {Eid:5,Name:"Hemanth",Domain:"Java"}, {Eid:5,Name:"MSA",Domain:"Java"} ]; return { getProperty: function () { return property; }, setProperty: function(value) { property = value; } }; });
const express = require('express'); const router = express.Router(); const {FindByCompany, FindByCompanyAndId} = require('./model'); const verifyMiddleWare = require('../../middleware/verify-middleware'); router.post('/get-plans-by-company', verifyMiddleWare, async (req, res) => { if (req.body.header === 'GET_PLANS_BY_COMPANY') { let index = globalState.nodes.findIndex(node => { return node.pubKeyHash === req.body.pubKeyHash; }); if (index >= 0) { res.json(await FindByCompany(req.body.company)); } else { res.end('Invalid node'); } } else { res.end('Invalid header'); } }); router.post('/get-plan-by-company-and-id', verifyMiddleWare, async (req, res) => { if (req.body.header === 'GET_PLAN_BY_COMPANY_AND_ID') { let index = globalState.nodes.findIndex(node => { return node.pubKeyHash === req.body.pubKeyHash; }); if (index >= 0) { res.json(await FindByCompanyAndId(req.body.company, req.body.id)); } else { res.end('Invalid node'); } } else { res.end('Invalid header'); } }); module.exports = router;
import { RemoteMongoClient } from "mongodb-stitch-browser-sdk"; import { app } from "./app"; const mongoClient = app.getServiceClient( RemoteMongoClient.factory, "mongodb-atlas" ); export const ticketDetails = mongoClient.db("users").collection("tickets"); export const items = mongoClient.db("users").collection("details");
export default /* glsl */` attribute vec4 vertex_boneWeights; attribute vec4 vertex_boneIndices; uniform highp sampler2D texture_poseMap; uniform vec4 texture_poseMapSize; void getBoneMatrix(const in float index, out vec4 v1, out vec4 v2, out vec4 v3) { float i = float(index); float j = i * 3.0; float dx = texture_poseMapSize.z; float dy = texture_poseMapSize.w; float y = floor(j * dx); float x = j - (y * texture_poseMapSize.x); y = dy * (y + 0.5); // read elements of 4x3 matrix v1 = texture2D(texture_poseMap, vec2(dx * (x + 0.5), y)); v2 = texture2D(texture_poseMap, vec2(dx * (x + 1.5), y)); v3 = texture2D(texture_poseMap, vec2(dx * (x + 2.5), y)); } mat4 getSkinMatrix(const in vec4 indices, const in vec4 weights) { // get 4 bone matrices vec4 a1, a2, a3; getBoneMatrix(indices.x, a1, a2, a3); vec4 b1, b2, b3; getBoneMatrix(indices.y, b1, b2, b3); vec4 c1, c2, c3; getBoneMatrix(indices.z, c1, c2, c3); vec4 d1, d2, d3; getBoneMatrix(indices.w, d1, d2, d3); // multiply them by weights and add up to get final 4x3 matrix vec4 v1 = a1 * weights.x + b1 * weights.y + c1 * weights.z + d1 * weights.w; vec4 v2 = a2 * weights.x + b2 * weights.y + c2 * weights.z + d2 * weights.w; vec4 v3 = a3 * weights.x + b3 * weights.y + c3 * weights.z + d3 * weights.w; // add up weights float one = dot(weights, vec4(1.0)); // transpose to 4x4 matrix return mat4( v1.x, v2.x, v3.x, 0, v1.y, v2.y, v3.y, 0, v1.z, v2.z, v3.z, 0, v1.w, v2.w, v3.w, one ); } `;