text
stringlengths
7
3.69M
var express = require('express'), path = require('path'), http = require('http'); // Initialize application var app = express(); // Configure application app.configure(function () { app.use(express.logger('dev')); /* 'default', 'short', 'tiny', 'dev' */ app.use(express.responseTime()), app.use(express.bodyParser()), app.use(express.static(path.join(__dirname, 'public'))); }); // Require routes var search = require('./routes/search'); var index = require('./routes/index'); // Initialize routers app.get('/2.0/', index.index); app.get('/2.0/search', search.search); // Create server http.createServer(app).listen(3000, function () { console.log("Server listening on port " + 3000); });
import React, { useState } from 'react'; import { Formik, Form, Field, ErrorMessage } from 'formik'; import { useHistory } from 'react-router-dom'; import './Register.scss'; import { registerSchema } from './register.schema'; import { UserService } from '../services/user.service'; function Register() { const history = useHistory(); const [showSuccess, setSuccess] = useState(false); function submit(values) { UserService.create(values) .then(res => { if (res.status === 201) { setSuccess(true); setTimeout(() => history.push('/login'), 2000); return; } console.log('failure!!!'); }); } return ( <div className="Register d-flex justify-content-center"> <div className="col col-lg-4 my-5"> <div className="text-center"> <h2 className="Register__title">Register</h2> <h3 className="Register__subtitle">It's quick and easy</h3> </div> <Formik initialValues={{username: '', password: '', email: '', agreeToTerms: false}} validationSchema={registerSchema} validateOnChange={true} onSubmit={submit}> {({ isSubmitting }) => ( <Form className="Register__form mt-5 px-0" noValidate> <div className="form-group my-3"> <label htmlFor="username">Username</label> <Field type="username" className="form-control" id="username" name="username" placeholder="2-16 characters" /> <ErrorMessage component="small" name="username" className="Register__form__error" /> </div> <div className="form-group my-3"> <label htmlFor="email">Email</label> <Field type="email" className="form-control" id="email" name="email" placeholder="Email address..." /> <ErrorMessage component="small" name="email" className="Register__form__error" /> </div> <div className="form-group my-3"> <label htmlFor="password">Password</label> <Field type="password" className="form-control" name="password" id="password" placeholder="6-16 characters" /> <ErrorMessage component="small" name="password" className="Register__form__error" /> </div> <div className="form-group my-3 form-check"> <div> <Field type="checkbox" id="agreeToTerms" name="agreeToTerms" className="form-check-input" /> <label htmlFor="agreeToTerms" className="form-check-label">Agree to terms</label> </div> <ErrorMessage component="small" name="agreeTerms" className="text-danger" /> </div> <div className="form-group my-3"> { showSuccess ? <div className="alert alert-success Register__success"><b>Success!</b> Wait for transfer...</div> : <button type="submit" className="mt-3 Register__submit-btn" disabled={isSubmitting}>Submit</button> } </div> </Form> )} </Formik> </div> </div> ); } export default Register;
const express = require('express'); const router = express.Router(); const tarjetaController = require('../controllers/tarjetaController'); router.get('/formularioTarjeta', tarjetaController.tarjeta); /*agregar ruta por post */ module.exports = router;
const express = require('express'); const app = express.Router(); const appDB = require("../model/productDB") // post data in frist tbl app.post("/api",(req,res)=>{ data = { product_name : req.body.product_name, imported : req.body.imported, category : req.body.category, price : req.body.price, quantity : req.body.quantity } appDB.insert_data(data) .then(()=>{ res.send("insert data") }).catch((err)=>{ console.log(err) }) }) // i inserted data in sec tbl app.get("/getapi/:id",(req,res)=>{ let id = req.params.id var data1 = appDB.get_by_id(id) data1.then((res_data)=>{ let product_name = res_data[0]["product_name"] let imported = res_data[0]["imported"] let category = res_data[0]["category"] let price = res_data[0]["price"] let quantity = res_data[0]["quantity"] let data = { "quantity" : quantity, "product_name" : product_name, "imported" : imported, "category" : category, "price" : price, "quantity_prise" : quantity * price } appDB.insert_data_cart(data) .then(()=>{ res.send("insert data") }).catch((err)=>{ console.log(err) }) }) }) // thid code app.get("/apidata/:cart_id",(req,res)=>{ let cart_id = req.params.cart_id let datastore = appDB.cart_get_by_id(cart_id) datastore.then((resp_data)=>{ let not_india_tax = 10 let indian_tax = 5 let imported = resp_data[0]["imported"] let category = resp_data[0]["category"] let price = resp_data[0]["price"] if (imported == "not_indian"){ var tax_data = price * not_india_tax/100 var price_tax = price + tax_data let data_dic = { "cart_id" : resp_data[0]["cart_id"], "quantity" : resp_data[0]["quantity"], "product_name" : resp_data[0]["product_name"], "imported" : resp_data[0]["imported"], "category" : resp_data[0]["category"], "price" : resp_data[0]["price"], "quantity_prise" : resp_data[0]["quantity_prise"], "price_tax" : tax_data, "price_with_tax " : price_tax } res.send(data_dic) } else if(imported == "indian"){ if (category == "general"){ var tax_amount = price * indian_tax/100 var price_with_tax = price + tax_amount let data_dic = { "cart_id" : resp_data[0]["cart_id"], "quantity" : resp_data[0]["quantity"], "product_name" : resp_data[0]["product_name"], "imported" : resp_data[0]["imported"], "category" : resp_data[0]["category"], "price" : resp_data[0]["price"], "quantity_prise" : resp_data[0]["quantity_prise"], "tax_data" : tax_amount, "price_with_tax_ind" : price_with_tax } res.send(data_dic) } else{ let data_dic = { "cart_id" : resp_data[0]["cart_id"], "quantity" : resp_data[0]["quantity"], "product_name" : resp_data[0]["product_name"], "imported" : resp_data[0]["imported"], "category" : resp_data[0]["category"], "price" : resp_data[0]["price"], "quantity_prise" : resp_data[0]["quantity_prise"] } res.send(data_dic) } } }) }); module.exports = app;
import React from 'react' // import emojiKeywords from 'emojis-keywords' // import emojiList from 'emojis-list' import SuggestionsPlugin from './slate-suggestions/index' import { Box, Avatar, Text } from 'rebass' import { blocks } from './elements/index' function getInput(value, regex = /([\w]*)/) { if (!value.startText) { return null } const startOffset = value.selection.start.offset const textBefore = value.startText.text.slice(0, startOffset) const result = regex.exec(textBefore) return result === null ? null : result[1] } let users = [] const getHCards = async () => { const res = await fetch('https://indieweb-directory.glitch.me/api/hcards') const cards = await res.json() return cards } ;(async () => { const hCards = await getHCards() users = hCards.map((hCard, i) => ({ hCard, key: `hcard-${i}`, value: `${hCard.properties.name[0]} ${hCard.properties.url[0]}`, suggestion: ( <MentionPreview name={hCard.properties.name[0]} photo={hCard.properties.photo[0]} /> ), })) })() const MentionPreview = ({ name, photo }) => ( <Box> <Avatar size={24} src={photo} style={{ display: 'inline-block', verticalAlign: 'middle', marginRight: 10, }} /> <Text style={{ display: 'inline-block', verticalAlign: 'middle' }}> {name} </Text> </Box> ) const mentionsPlugin = SuggestionsPlugin({ trigger: '@', capture: /@([\w]*)/, suggestions: search => search ? users.filter(user => user.value.toLowerCase().includes(search.toLowerCase()) ) : users, onEnter: (suggestion, editor) => { const value = editor.value const inputValue = getInput(value, /@([\w]*)/) // Delete the captured value, including the `@` symbol editor.deleteBackward(inputValue ? inputValue.length + 1 : 1) return editor .insertInline({ object: 'inline', type: 'mention', data: { hCard: suggestion.hCard, }, }) .moveToStartOfNextText() .focus() }, }) // This sort of works but it is really slow and shows all color variations and stuff. Want to make something smarter // const emoji = emojiList.map((icon, i) => ({ // key: emojiKeywords[i], // value: emojiKeywords[i], // suggestion: icon, // })) // const emojiPlugin = SuggestionsPlugin({ // trigger: ':', // capture: /:([\w]*)/, // suggestions: emoji, // onEnter: (suggestion, editor) => { // const { anchorText, selection } = editor.value // const { offset } = selection.anchor // const text = anchorText.text // let index = { start: offset - 1, end: offset } // if (text[offset - 1] !== ':') { // const spaceIndex = text.substring(0, index.end).lastIndexOf(' ') // if (spaceIndex > -1) { // index.start = spaceIndex + 1 // } else { // index.start = 0 // } // } // const newText = `${text.substring(0, index.start)}${suggestion.suggestion} ` // return editor // .deleteBackward(offset) // .insertText(newText) // .focus() // }, // }) const blockSuggestions = [] for (const blockKey in blocks) { if (blocks.hasOwnProperty(blockKey) && blocks[blockKey].showIcon) { const block = blocks[blockKey] blockSuggestions.push({ key: blockKey, value: block.name, keywords: block.keywords, suggestion: ( <span> {block.icon} {block.name} </span> ), }) } } const blockPlugin = SuggestionsPlugin({ trigger: '/', capture: /\/([\w]*)/, suggestions: search => search ? blockSuggestions.filter(block => block.keywords.find(keyword => keyword.toLowerCase().includes(search.toLowerCase()) ) ) : blockSuggestions, startOfParagraph: true, onEnter: (suggestion, editor) => { const block = blocks[suggestion.key] const { anchorText } = editor.value editor.deleteBackward(anchorText.text.length) editor.unwrapBlock(block.name) return block.onButtonClick(editor) }, }) export default [blockPlugin, mentionsPlugin]
import { LOGIN, LOGIN_FAIL, LOGIN_SUCCESS, LOGOUT, INCRCOUNTER, DECRCOUNTER, ADDTOCART, ITEMSINCART, SETCART, ITEMSREMOVED, REMOVESINGLEITEM, CUSTOMERINFO } from './actionType' import { BASE_URL } from '../static_data/constants' import axios from 'axios' // Async task export const loginUserAPI = ({email, password, custId}) => { return (dispatch) => { dispatch(loginUser()) axios.get(`${BASE_URL}user/login?email=${email}&password=${password}&id=${custId}`) .then(response => dispatch(loginUserSuccess(response.data.status, response.data.data[0]))) .catch(error => dispatch(loginUserFail(error))) }; } export const userLogout = (data) => { return(dispatch) => { dispatch(logout(data)) } } export const userLogin = (data) => { return(dispatch) => { dispatch(loginUserSuccess(data)) } } export const addToCartApi = ({prodId, custId, val, price, items}) => { return(dispatch) => { axios.get(BASE_URL + `add-into-cart?id=${custId}&prodId=${prodId}&type=${val}&price=${price}`) .then(response => { if(response.data.data.length > 0){ dispatch(increment(response.data.data)) } }) .catch(error => console.log(error)) } } export const getCartItems = ({custId}) => { return(dispatch) => { axios.get(BASE_URL + `get-cart-items?id=${custId}`) .then(response => { if(response.data.data.length > 0 || response.data.status === true){ dispatch(setCart(response.data.data, response.data.data.length)) }else{ } }) .catch(error => console.log(error)) } } export const addOrderHistory = ({custId, items}) => { return(dispatch) => { axios.get(BASE_URL + `order-history?id=${custId}&items=${items}`) .then(response => console.log(response)) .catch(error => console.log(error)) } } export const removeCartItems = ({custId, prodId}) => { return(dispatch) => { axios.get(BASE_URL + `remove-cart-item?id=${custId}&prodId=${prodId}`) .then(response => { if(response.data.status === true){ dispatch(itemsRemoved(custId, prodId)) } }) .catch(error => console.log(error)) } } export const getUserInfo = ({custId}) => { return(dispatch) => { axios.get(BASE_URL + `get-user?id=${custId}`) .then(response => { if(response.data.status === true){ dispatch(getUser(response.data.data)) } }) .catch(error => console.log(error)) } } const loginUser = () => { return { type: LOGIN, } } const loginUserSuccess = (data, userData='') => { return { type: LOGIN_SUCCESS, payload: data, id: userData.id, userdata: userData } } const loginUserFail = (error) => { return { type: LOGIN_FAIL, payload: error } } const logout = (data) => { return{ type: LOGOUT, payload: data.logout } } export const increment = (items) => { return{ type: INCRCOUNTER, item: items[0], } } export const decrement = (count) => { return{ type: DECRCOUNTER, count: count.quantity } } export const addToCart = (data) => { return{ type: ADDTOCART, prodId: data, countItems: data.count } } export const cartItems = (items) => { return{ type: ITEMSINCART, count: items } } const setCart = (data, count) => { return{ type: SETCART, data: data, itemCount: count } } const itemsRemoved = (custId, prodId) => { if(prodId > 0){ return{ type: REMOVESINGLEITEM, custId: custId, prodId: prodId } }else{ return{ type: ITEMSREMOVED, } } } const getUser = (data) => { return{ type: CUSTOMERINFO, data: data[0] } }
'use strict' const fs = require('fs') const path = require('path') module.exports = function(fixturesDir, expectationsDir, inline, run) { const files = fs.readdirSync(fixturesDir) for (const htmlFile of files) { const baseName = path.basename(htmlFile) if (!baseName.endsWith('.html') || baseName.startsWith('.')) continue const baseNameNoExt = baseName.slice(0, -5) const data = require( path.join(expectationsDir, baseNameNoExt + '.json')) const html = inline ? fs.readFileSync(path.join(fixturesDir, htmlFile), 'utf-8') : path.join(fixturesDir, htmlFile) run(baseNameNoExt, data.meta, html, data.expected) } }
//Global Javascript functions function updateFormTabs(currentStep, maxStep) { currentStep -= 1; maxStep -= 1; $j("#formTabs ul li").each(function(index) { if(index == currentStep) { $j(this).addClass("active"); } else if(index > maxStep) { $j(this).addClass("disabled"); } }); } function fillPermanentAddress(address1, address2, city, state, zipCode) { $j("#permanentAddress1").val(address1); $j("#permanentAddress2").val(address2); $j("#permanentCity").val(city); $j("#permanentState").val(state); $j("#permanentZipCode").val(zipCode); } function setupTimePicker(field) { $j(field).datetimepicker({ pickDate: false, minuteStepping: 10, defaultDate: moment().startOf("day") }); }
import Vue from 'vue'; import Vuex from 'vuex'; // 引入模块 import student from './modules/student.js'; import drinks from './modules/drinks.js'; // 启用 Vuex 插件 Vue.use(Vuex); // store 对象还是可以正常配置 state / mutations / actions/ getters export default new Vuex.Store({ state:{ fruits: ['苹果', '香蕉', '橘子'] }, mutations:{ addFruit(state, payload){ state.fruits.push(payload); } }, actions:{ addFruitAsync(context, payload){ setTimeout(()=>{ context.commit('addFruit', payload); }, 2000); } }, getters:{ fruitsCount(state){ return state.fruits.length; } }, // 我们可以把拆分出去的模块,在这里通过 modules 集中引入 // 引入的时候,一般需要给模块起个名称,这个名称将会作为此模块的命名空间 modules:{ student: student, drink: drinks } });
import * as Action from './actions'; export const OrganizationReducer = (state, action) => { switch (action.type) { case Action.GET_ORGANIZATIONS: return { ...state, isLoading: true, isError: false, organizations: null }; case Action.GET_ORGANIZATIONS_SUCCESS: return { ...state, isLoading: false, isError: false, organizations: action.payload, }; case Action.GET_ORGANIZATIONS_FAILED: return { ...state, isLoading: false, isError: true, error: action.payload }; default: return { isLoading: false, isError: false, organizations: null, ...state } } }
import {compose, createStore, applyMiddleware} from 'redux'; import thunk from 'redux-thunk'; import {createLogger} from 'redux-logger'; import {composeWithDevTools} from 'redux-devtools-extension'; import reducers from './src/modules'; const logger = createLogger({ collapsed: true, }); const enhancer = compose( applyMiddleware(thunk), applyMiddleware(logger), ); const store = createStore( reducers, composeWithDevTools(enhancer), ); export default store;
import React, { useEffect, useState } from 'react'; import Loader from 'react-loader-spinner'; import Details from './components/Details'; import List from './components/List'; import 'react-loader-spinner/dist/loader/css/react-spinner-loader.css'; import './App.css'; const { REACT_APP_USERS_URL } = process.env; function App() { const [isLoading, setIsLoading] = useState(false); const [selectedUserId, setSelectedUserId] = useState(null); const [users, setUsers] = useState([]); const handleUserClick = id => { if (id !== selectedUserId) { setSelectedUserId(id); } }; useEffect(() => { setIsLoading(true); fetch(REACT_APP_USERS_URL) .then(response => response.json()) .then(data => { setIsLoading(false); setUsers(data) }); }, []); return ( <div className="Users"> <List list={users}> {list => (isLoading ? ( <li className="List-loader"> <Loader type="Oval" color="#777" height={30} width={30} /> </li> ) : ( list.map(item => ( <li key={item.id} className={item.id === selectedUserId ? 'List-item--active' : null} onClick={() => handleUserClick(item.id)} > {item.name} </li> )) ))} </List> {!!selectedUserId && ( <Details info={users.find(user => user.id === selectedUserId)} /> )} </div> ); } export default App;
document.getElementById("btnLuong").onclick = function () { var luongMotNgay = 100000; var soNgayLam = document.getElementById("soNgayLam").value; var tongLuong = luongMotNgay*soNgayLam; var currentFormat = new Intl.NumberFormat("vn-VN"); var tongLuongFormat = currentFormat.format(tongLuong); document.getElementById("divShowInfo").innerHTML = "Tổng Lương Là: " + tongLuongFormat + "VND"; document.getElementById("divShowInfo").style.backgroundColor = "red"; document.getElementById("divShowInfo").style.color = "white"; document.getElementById("divShowInfo").style.fontSize = "30px"; };
import React from 'react' import { StyleSheet } from 'quantum' import { connect, hover as hoverState } from 'bypass/ui/state' import { Condition } from 'bypass/ui/condition' import { Tooltip } from 'bypass/ui/tooltip' import Column from './Column' const styles = StyleSheet.create({ self: { width: '100%', display: 'flex', justifyContent: 'center', }, }) const Chart = ({ tooltip, hover, onMouseEnter, onMouseLeave }) => ( <div className={styles()} onMouseEnter={onMouseEnter} onMouseLeave={onMouseLeave} > <Column /> <Condition match={hover}> <Tooltip align='top' offset='10px 0'> {tooltip} </Tooltip> </Condition> </div> ) export default connect([hoverState], Chart)
const language = { // 中文 cn: { add_btn: '添加按钮', add_title: '添加区域', del_btn: '删除按钮', del_title: '删除区域', next: '下一页', next_title: '下 page_size (→)', prev: '上一页', prev_title: '上 page_size (←)', first_title: '首页 (Shift + ←)', last_title: '尾页 (Shift + →)', get_all_btn: '获得全部 (↓)', get_all_alt: '(按钮)', close_btn: '关闭 (Tab键)', close_alt: '(按钮)', loading: '读取中...', loading_alt: '(读取中)', page_info: '第 page_num 页(共page_count页)', select_ng: '请注意:请从列表中选择.', select_ok: 'OK : 已经选择.', not_found: '无查询结果', ajax_error: '连接到服务器时发生错误!', clear: '清除内容', select_all: '选择当前页项目', unselect_all: '取消选择当前页项目', clear_all: '清除全部已选择项目', max_selected: '最多只能选择 max_selected_limit 个项目' }, // English en: { add_btn: 'Add button', add_title: 'add a box', del_btn: 'Del button', del_title: 'delete a box', next: 'Next', next_title: 'Next page_size (Right key)', prev: 'Prev', prev_title: 'Prev page_size (Left key)', first_title: 'First (Shift + Left key)', last_title: 'Last (Shift + Right key)', get_all_btn: 'Get All (Down key)', get_all_alt: '(button)', close_btn: 'Close (Tab key)', close_alt: '(button)', loading: 'loading...', loading_alt: '(loading)', page_info: 'Page page_num of page_count', select_ng: 'Attention : Please choose from among the list.', select_ok: 'OK : Correctly selected.', not_found: 'not found', ajax_error: 'An error occurred while connecting to server.', clear: 'Clear content', select_all: 'Select current page', unselect_all: 'Clear current page', clear_all: 'Clear all selected', max_selected: 'You can only select up to max_selected_limit items' }, // German de: { add_btn: 'Hinzufügen-Button', add_title: 'Box hinzufügen', del_btn: 'Löschen-Button', del_title: 'Box löschen', next: 'Nächsten', next_title: 'Nächsten page_size (Pfeil-rechts)', prev: 'Vorherigen', prev_title: 'Vorherigen page_size (Pfeil-links)', first_title: 'Ersten (Umschalt + Pfeil-links)', last_title: 'Letzten (Umschalt + Pfeil-rechts)', get_all_btn: 'alle (Pfeil-runter)', get_all_alt: '(Button)', close_btn: 'Schließen (Tab)', close_alt: '(Button)', loading: 'lade...', loading_alt: '(lade)', page_info: 'page_num von page_count', select_ng: 'Achtung: Bitte wählen Sie aus der Liste aus.', select_ok: 'OK : Richtig ausgewählt.', not_found: 'nicht gefunden', ajax_error: 'Bei der Verbindung zum Server ist ein Fehler aufgetreten.', clear: 'Löschen Sie den Inhalt', select_all: 'Wähle diese Seite', unselect_all: 'Diese Seite entfernen', clear_all: 'Alles löschen', max_selected: 'Sie können nur bis zu max_selected_limit Elemente auswählen' }, // Spanish es: { add_btn: 'Agregar boton', add_title: 'Agregar una opcion', del_btn: 'Borrar boton', del_title: 'Borrar una opcion', next: 'Siguiente', next_title: 'Proximas page_size (tecla derecha)', prev: 'Anterior', prev_title: 'Anteriores page_size (tecla izquierda)', first_title: 'Primera (Shift + Left)', last_title: 'Ultima (Shift + Right)', get_all_btn: 'Ver todos (tecla abajo)', get_all_alt: '(boton)', close_btn: 'Cerrar (tecla TAB)', close_alt: '(boton)', loading: 'Cargando...', loading_alt: '(Cargando)', page_info: 'page_num de page_count', select_ng: 'Atencion: Elija una opcion de la lista.', select_ok: 'OK: Correctamente seleccionado.', not_found: 'no encuentre', ajax_error: 'Un error ocurrió mientras conectando al servidor.', clear: 'Borrar el contenido', select_all: 'Elija esta página', unselect_all: 'Borrar esta página', clear_all: 'Borrar todo marcado', max_selected: 'Solo puedes seleccionar hasta max_selected_limit elementos' }, // Brazilian Portuguese 'pt-br': { add_btn: 'Adicionar botão', add_title: 'Adicionar uma caixa', del_btn: 'Apagar botão', del_title: 'Apagar uma caixa', next: 'Próxima', next_title: 'Próxima page_size (tecla direita)', prev: 'Anterior', prev_title: 'Anterior page_size (tecla esquerda)', first_title: 'Primeira (Shift + Left)', last_title: 'Última (Shift + Right)', get_all_btn: 'Ver todos (Seta para baixo)', get_all_alt: '(botão)', close_btn: 'Fechar (tecla TAB)', close_alt: '(botão)', loading: 'Carregando...', loading_alt: '(Carregando)', page_info: 'page_num de page_count', select_ng: 'Atenção: Escolha uma opção da lista.', select_ok: 'OK: Selecionado Corretamente.', not_found: 'não encontrado', ajax_error: 'Um erro aconteceu enquanto conectando a servidor.', clear: 'Limpe o conteúdo', select_all: 'Selecione a página atual', unselect_all: 'Remova a página atual', clear_all: 'Limpar tudo', max_selected: 'Você só pode selecionar até max_selected_limit itens' }, // Japanese ja: { add_btn: '追加ボタン', add_title: '入力ボックスを追加します', del_btn: '削除ボタン', del_title: '入力ボックスを削除します', next: '次へ', next_title: '次の page_size 件 (右キー)', prev: '前へ', prev_title: '前の page_size 件 (左キー)', first_title: '最初のページへ (Shift + 左キー)', last_title: '最後のページへ (Shift + 右キー)', get_all_btn: '全件取得 (下キー)', get_all_alt: '画像:ボタン', close_btn: '閉じる (Tabキー)', close_alt: '画像:ボタン', loading: '読み込み中...', loading_alt: '画像:読み込み中...', page_info: 'page_num 件 (全 page_count 件)', select_ng: '注意 : リストの中から選択してください', select_ok: 'OK : 正しく選択されました。', not_found: '(0 件)', ajax_error: 'サーバとの通信でエラーが発生しました。', clear: 'コンテンツをクリアする', select_all: '当ページを選びます', unselect_all: '移して当ページを割ります', clear_all: '選択した項目をクリアする', max_selected: '最多で max_selected_limit のプロジェクトを選ぶことしかできません' } }; export default language;
"use strict"; const SINE = "sine"; const SQUARE = "square"; const SAWTOOTH = "sawtooth"; const TRIANGLE = "triangle"; const CUSTOM = "custom"; const values = [ SINE, SQUARE, SAWTOOTH, TRIANGLE ]; const OscillatorType = { SINE, SQUARE, SAWTOOTH, TRIANGLE, CUSTOM, [Symbol.hasInstance](value) { return values.includes(value); } }; module.exports = OscillatorType;
const VERSION = 'v1' const BASE_URL = `https://mixd-server.herokuapp.com/api/${VERSION}` //const BASE_URL = `http://localhost:3000/api/${VERSION}` import { AsyncStorage } from 'react-native' const COCKTAIL_URL = BASE_URL + '/cocktails' const INGREDIENT_URL = BASE_URL + '/ingredients' const GARNISH_URL = BASE_URL + '/garnishes' const TASTE_URL = BASE_URL + '/tastes' const BASE_LIQUOR_URL = BASE_URL + '/bases' const GLASS_URL = BASE_URL + '/glasses' //================ AUTHORISED API CALLS ================// //Used to control access to authorised endpoint for signed up users only const authorizedFetch = async (url, options = {}) => { const token = await AsyncStorage.getItem('token') return fetch(url, { ...options, headers: { 'Content-Type': 'application/json', Authorization: token } }) } const validate = () => authorizedFetch(BASE_URL + '/validate').then(resp => resp.json()) const starCocktail = cocktailId => authorizedFetch(COCKTAIL_URL + '/star-cocktail', { method: 'POST', body: JSON.stringify({ cocktail_id: cocktailId }) }).then(resp => resp.json()) const getMyCreations = () => authorizedFetch(BASE_URL + '/mycreations').then(resp => resp.json()) const createCocktail = cocktailData => authorizedFetch(COCKTAIL_URL, { method: 'POST', body: JSON.stringify(cocktailData) }).then(resp => resp.json()) //================ OPEN API CALLS ================// const getCocktails = page => { if (!page) return fetch(COCKTAIL_URL).then(resp => resp.json()) return fetch(`${COCKTAIL_URL}?page=${page}`).then(resp => resp.json()) } const getAllIngredients = () => fetch(INGREDIENT_URL).then(resp => resp.json()) const getAllGarnishes = () => fetch(GARNISH_URL).then(resp => resp.json()) const getAllTastes = () => fetch(TASTE_URL).then(resp => resp.json()) const getAllBaseLiquors = () => fetch(BASE_LIQUOR_URL).then(resp => resp.json()) const getAllGlasses = () => fetch(GLASS_URL).then(resp => resp.json()) //================ TOKEN MANAGEMENT ================// const login = user => { return fetch(BASE_URL + '/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(user) }).then(resp => resp.json()) } const signUp = userData => { return fetch(BASE_URL + '/signup', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ user: userData }) }).then(resp => resp.json()) } export default { getCocktails, getAllIngredients, getAllGarnishes, getAllTastes, getAllBaseLiquors, getAllGlasses, login, signUp, validate, getMyCreations, createCocktail, starCocktail }
const logger = { log: function (e) { console.log('[', new Date(), ']:', e); } } module.exports = logger;
import React from 'react'; import PropTypes from 'prop-types'; import { Segment, Icon } from 'semantic-ui-react'; const Layout = ({ component: Component, props, user, logout }) => ( <div className="full-height container"> <div className="top-menu"> <span className="top-menu-company"> Askimovie </span> <div className="top-menu-right"> <div className="top-menu-item"> <Icon name="sign out" /> Déconnexion </div> <div className="top-menu-item"> <img alt="profil" src={user.thumb} className="user-thumb" /> </div> </div> </div> <div className="full-height content"> <Segment basic className="full-height"> <Component {...props} /> </Segment> </div> </div> ); Layout.propTypes = { component: PropTypes.func.isRequired, props: PropTypes.object.isRequired, }; export default Layout;
import React from 'react'; import { Text, View, StyleSheet, ViewPropTypes } from 'react-native'; import PropTypes from 'prop-types'; import { InputItem } from '@ant-design/react-native'; import CommonStyles from '@/commonStyles'; import BaseComponent from '@/components/common/baseComponent'; /** * 标签输入框 * * @export * @class LabelInput * @extends {BaseComponent} */ export default class LabelInput extends BaseComponent { static propTypes = { style: ViewPropTypes.style, labelStyle: ViewPropTypes.style, inputStyle: ViewPropTypes.style, label: PropTypes.string, defaultValue: PropTypes.string, placeholder: PropTypes.string, vo: PropTypes.object, vmodel: PropTypes.string, }; static defaultProps = { defaultValue: '', }; constructor(props) { super(props); const { vo, vmodel, defaultValue } = this.props; this.state = { value: typeof vo === 'undefined' ? defaultValue : vo.bind(vmodel, (_val, newVal) => this.setState({ value: newVal })), }; } _render() { const { vo, vmodel } = this.props; return ( <View style={[styles.container, this.props.style]}> {typeof this.props.label !== 'undefined' ? <Text style={[CommonStyles.primaryLabel, this.props.labelStyle]}>{this.props.label}</Text> : null} <View style={styles.inputContainer}> <InputItem style={[CommonStyles.primaryInput, this.props.inputStyle]} placeholder={this.props.placeholder} value={this.state.value} onChange={(value) => (typeof vo === 'undefined' ? this.setState({ value: value }) : (vo[vmodel] = value))} /> </View> </View> ); } } const styles = StyleSheet.create({ container: { height: 40, marginRight: 4, flexDirection: 'row', alignItems: 'center', justifyContent: 'center', }, inputContainer: { flex: 1, marginLeft: 4, marginTop: 4, }, });
/* function getContentAndReplace(){ $.get("/stockdata/bidu",function(data,status){ $(".starter-template").append(data); var myData = JSON.parse(data); alert(myData[0].Date); }); } */ function switcher(txt){ $(".nav.navbar-nav").children(".active").removeClass("active"); $(".nav.navbar-nav").children(":contains("+txt+")").addClass("active"); var stockRenderMatcher = new RegExp("Stock","i"); if(stockRenderMatcher.test(txt)) { // getContentAndReplace(); prepareJsonAndDraw("bidu","1y"); } } function naiveJson2chartJson(naiveJson){ var chartJson = []; alert(naiveJson[0].Date); for(var i in naiveJson){ var dateString = naiveJson[i].Date; var dateSplitArr = dateString.split("/"); chartJson.push({date: new Date(dateSplitArr[2],dateSplitArr[0]-1,dateSplitArr[1]), value: naiveJson[i].Close}); } return chartJson; } function loadChartJsSource(){ $("body").append('<script type="text/javascript" src="http://www.amcharts.com/lib/3/amcharts.js"></script> <script type="text/javascript" src="http://www.amcharts.com/lib/3/serial.js"></script> <script type="text/javascript" src="http://www.amcharts.com/lib/3/themes/dark.js"></script> <script type="text/javascript" src="http://www.amcharts.com/lib/3/amstock.js"></script>'); } /* Given a json that contains array of {date:xxx, value:xxx}, draw the stock chart */ function drawStockChart(chartJson){ $(".starter-template").append("<div id="chartDiv"></div>"); loadChartJsSource(); } /* stockSymbol: the stock symbol used in marketplace periodCode: 1m|3m|6m|1y|2y|3y */ function prepareJsonAndDraw(stockSymbol, periodCode){ $.get("/stockdata/"+stockSymbol, function(data,status){ var naiveJson = JSON.parse(data); var chartJson = naiveJson2chartJson(naiveJson); drawStockChart(chartJson); }); }
class Filter { constructor() { this.size = 3; this.step = 1; this.filter = [1, 0, 1, 0, 1, 0, 1, 0, 1]; } run(input){ let result = 0; input.forEach((value, index)=>{ result += value * this.filter[index]; }); //console.log('Filtered input [' + input.join(',') + '] to ' + result); return result / 9; } } export default Filter;
import React from 'react'; import Withdrawal from '../../components/setting/Withdrawal'; import Header from '../../components/main/Header'; const withdrawal = () => { return ( <> <Header type="white" backButton={true} title="회원탈퇴" /> <Withdrawal /> </> ); }; export default withdrawal;
import { addDecorator } from '@storybook/vue'; import vuetify from "../src/plugins/vuetify-manual"; addDecorator(() => ({ vuetify, template: '<v-app><v-content><story/></v-content></v-app>', })); //Gql Mock import mockGqlClient from '../gqlc-mock/gqlc-mock-data' //MOCK GQLC PROVIDERS import authProvider from '../src/providers/AuthProvider' import groupProvider from '../src/providers/GroupProvider' import userProvider from '../src/providers/UserProvider' import roleProvider from '../src/providers/RoleProvider' import sessionProvider from '../src/providers/SessionProvider' import recoveryProvider from '../src/providers/RecoveryProvider' authProvider.setGqlc(mockGqlClient) groupProvider.setGqlc(mockGqlClient) userProvider.setGqlc(mockGqlClient) roleProvider.setGqlc(mockGqlClient) sessionProvider.setGqlc(mockGqlClient) recoveryProvider.setGqlc(mockGqlClient)
module.exports = function(){ var express = require('express'); var router = express.Router(); router.get('/', function(req, res, next) { res.render('addroom', { title: 'Jing\'s Pets' }); }); router.post("/", function(req, res){ console.log("ADDING Room"); console.log(req.body); var mysql = req.app.get('mysql'); var sql = "INSERT INTO room (room.name, room.area) VALUES (?, ?);"; var inserts = [req.body.roomName, req.body.roomArea]; sql = mysql.pool.query(sql, inserts, function(err, results, fields){ if(err){ console.log(err); res.write(JSON.stringify(err)); res.end(); }else{ console.log(inserts); res.redirect('/viewroom'); } }); }); return router; }();
/* Copyright (c) 2010 Mike Desjardins Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // This is to simplify including the most common javascripts *in browsers*, // i.e., from an HTML file. Don't use this to include javascripts in XUL, // use the common-javascript.xul overlay instead (this method doesn't seem // to work for XUL files). // var Include = { files : ["account-manager.js", "utils.js", "aja.js", "oauth/oauth.js", "oauth/sha1.js", "social/social.js", "social/twitteresque.js", "social/twitter.js", "social/statusnet.js", "social/identica.js", "render.js", "jquery-1.4.2.js", "jquery.lazyload.js" ], addOne : function(element,filename) { script = document.createElement('script'); script.src = filename; script.type = 'text/javascript'; element.appendChild(script) }, all : function(id) { var element = document.getElementById(id); if (element) { for (var i=0,len=Include.files.length; i<len; i++) { Include.addOne(element,"chrome://buzzbird/content/js/" + Include.files[i]); } } } }
var s = null; /// when a clients video is ready to start easyrtc.setStreamAcceptor( function(callerEasyrtcid, stream) { var video = document.getElementById('caller'); easyrtc.setVideoObjectSrc(video, stream); console.log("accepted"); }); // when a client closes video easyrtc.setOnStreamClosed( function (callerEasyrtcid) { easyrtc.setVideoObjectSrc(document.getElementById('caller'), ""); }); function my_init(socket) { easyrtc.enableAudio(false); s = socket; easyrtc.useThisSocketConnection(socket); //easyrtc.setRoomOccupantListener( loggedInListener); var connectSuccess = function(myId) { console.log("My easyrtcid is " + myId); console.log("My socketid " + socket.id); //document.getElementById('userid').value = myId; } var connectFailure = function(errorCode, errText) { console.log("the ERROR!!"); console.log(errText); } easyrtc.initMediaSource( function(){ // success callback var selfVideo = document.getElementById("self"); easyrtc.setVideoObjectSrc(selfVideo, easyrtc.getLocalStream()); easyrtc.connect("sthlm",connectSuccess, connectFailure); }, connectFailure, JSON.stringify(socket.id) ); socket.on('send_id', function(ids){ console.log('Sendi'); for (var i = 0; i < ids.length; i++){ var temp = ids[i]; if(ids[i].socketid != socket.id){ performCall(ids[i].eid); break; } } }); } function performCall(easyrtcid) { easyrtc.call( easyrtcid, function(easyrtcid) { console.log("completed call to " + easyrtcid);}, function(errorCode, errorText) { console.log("err:" + errorText);}, function(accepted, bywho) { console.log((accepted?"accepted":"rejected")+ " by " + bywho); } ); } /*function loggedInListener(roomName, otherPeers) { var otherClientDiv = document.getElementById('otherClients'); var paragraph = $('#info-p'); paragraph.text("Easyrtcid: " + easyrtc.myEasyrtcid +"; socket id: " + s.id); }*/
var fs = require('fs'); var path = require('path'); var express = require('express'); const router = express.Router(); const controllerSuffix = "-controller.js"; var applyAPIDirectory = function(app, prefix, rootDir){ var files = fs.readdirSync(path.join(__dirname, "../"+rootDir) ); if (files == null){ return; } console.log(""); console.log("Initialising API directory '" + prefix + "' ..."); for(var i=0; i<files.length; i++) { if(files[i].includes(controllerSuffix)){ var requireName = "../" + rootDir + files[i].replace(".js", ""); var apiName = "/"+files[i].replace(controllerSuffix, ""); require(requireName)(apiName, router); console.log(" - "+prefix+apiName + " from file " + files[i]); } app.use(prefix, router); } } module.exports.applyAPIDirectory = applyAPIDirectory;
import {LOCATION_CHANGE} from 'react-router-redux'; import {del} from '../../../utils/http'; import {REDUCERS_GROUP_PREFIX, ENDPOINT_ACCOUNT} from './constants'; import {addInfoToast} from '../../../utils/notifications'; import {LOGOUT} from '../auth/session'; const REDUCER_NAME = `${REDUCERS_GROUP_PREFIX}/delete`; const DELETE_ACCOUNT_REQUEST_SUCCESS = `${REDUCER_NAME}/DELETE_ACCOUNT_REQUEST_SUCCESS`; const DELETE_ACCOUNT_REQUEST_ERROR = `${REDUCER_NAME}/DELETE_ACCOUNT_REQUEST_ERROR`; const DELETE_ACCOUNT_SUCCESS = `${REDUCER_NAME}/DELETE_ACCOUNT_SUCCESS`; const DELETE_ACCOUNT_ERROR = `${REDUCER_NAME}/DELETE_ACCOUNT_ERROR`; const initState = { successMessage: null, errorMessage: null }; export default (state = initState, action) => { switch (action.type) { case DELETE_ACCOUNT_REQUEST_SUCCESS: case DELETE_ACCOUNT_SUCCESS: return {...state, successMessage: action.message}; case DELETE_ACCOUNT_REQUEST_ERROR: case DELETE_ACCOUNT_ERROR: return {...state, errorMessage: action.error}; case LOCATION_CHANGE: return initState; default: return state; } }; export const deleteAccountRequest = () => { return dispatch => { del(ENDPOINT_ACCOUNT, null).then(response => { dispatch({type: DELETE_ACCOUNT_REQUEST_SUCCESS, message: response.message}); }).catch(response => { dispatch({type: DELETE_ACCOUNT_REQUEST_ERROR, error: response.message}); }); } }; export const deleteAccount = token => { return dispatch => { del(`${ENDPOINT_ACCOUNT}/${token}`, null).then(response => { dispatch({type: DELETE_ACCOUNT_SUCCESS, message: response.message}); addInfoToast(response.message); dispatch({type: LOGOUT}); }).catch(response => { dispatch({type: DELETE_ACCOUNT_ERROR, error: response.message}); }); } };
const express = require('express'); const logger = require('morgan'); const stocks = require('./routes/stocks') ; const users = require('./routes/users'); const bodyParser = require('body-parser'); const mongoose = require('./app/configurations/database'); //database configuration var jwt = require('jsonwebtoken'); var favicon = require('static-favicon'); var cookieParser = require('cookie-parser'); var path = require('path'); const app = express(); app.set('secretKey', 'myNodejsStockApp'); // connection to mongodb mongoose.connection.on('error', console.error.bind(console, 'MongoDB connection error:')); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'hbs'); app.use(favicon()); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded()); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); // please uncomment it to use jwt-auth /* app.use('/stocks', validateUser, stocks); function validateUser(req, res, next) { jwt.verify(req.headers['x-access-token'], req.app.get('secretKey'), function(err, decoded) { if (err) { res.json({status:"error", message: err.message, data:null}); }else{ // add user id to request req.body.userId = decoded.id; next(); } }); } */ app.get('/', function(req, res){ res.json({"Welcome" : "Stock Data View App"}); }); app.use('/users', users); /* Please uncomment it to use jwt-auth */ //app.use('/stocks', validateUser, stocks); app.use('/stocks', stocks); app.get('/favicon.ico', function(req, res) { res.sendStatus(204); }); function validateUser(req, res, next) { jwt.verify(req.headers['x-access-token'], req.app.get('secretKey'), function(err, decoded) { if (err) { res.json({status:"error", message: err.message, data:null}); }else{ // add user id to request req.body.userId = decoded.id; next(); } }); } /// catch 404 and forwarding to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); /// error handlers // development error handler // will print stacktrace if (app.get('env') === 'development') { app.use(function(err, req, res, next) { res.status(err.status || 500); res.json({status:"error 500", message: err.message, data:null}); }); } // production error handler // no stacktraces leaked to user app.use(function(err, req, res, next) { res.status(err.status || 500); res.json({status:"error 500", message: err.message, data:null}); }); module.exports = app;
import mutations from "../../../src/store/mutations"; describe("store mutations", () => { it("should be able to add food items to state", () => { const state = { foodItems: [], }; const foodItems = [ { hints: [ { foodId: "food_amqspy5ap567v6bun60usbgsaor7", label: "Nuts", nutrients: { ENERC_KCAL: 594.0, PROCNT: 17.3, FAT: 51.45, CHOCDF: 25.35, FIBTG: 9.0, }, }, ], }, ]; mutations.setFoodItemsAction(state, foodItems); expect(state).toEqual({ foodItems: [ { hints: [ { foodId: "food_amqspy5ap567v6bun60usbgsaor7", label: "Nuts", nutrients: { ENERC_KCAL: 594.0, PROCNT: 17.3, FAT: 51.45, CHOCDF: 25.35, FIBTG: 9.0, }, }, ], }, ], }); }); it("should be able to add nutrition details to state", () => { const state = { nutritionDetails: {}, }; const nutritionDetails = { ENERC_KCAL: 594.0, PROCNT: 17.3, FAT: 51.45, CHOCDF: 25.35, FIBTG: 9.0, }; mutations.setNutritionDetailsAction(state, nutritionDetails); expect(state).toEqual({ nutritionDetails: { ENERC_KCAL: 594.0, PROCNT: 17.3, FAT: 51.45, CHOCDF: 25.35, FIBTG: 9.0, }, }); }); it("should be able to add error to state", () => { const state = { error: null, }; const errors = "error"; mutations.setError(state, errors); expect(state).toEqual({ error: "error", }); }); });
import React from 'react'; import { bindActionCreators } from 'redux'; import {Link} from 'react-router'; import { connect } from 'react-redux'; // Action creators import actionCreators from '../actions/actionCreators' // Components import Head from '../components/Head'; const Main = React.createClass({ handleClick() { this.props.setBackground(); }, render() { document.body.style.background = this.props.background; return ( <main> <Head/> <header className='header flex items-center justify-center w-100 pv2'> <Link to='/' className='center' onClick={this.handleClick}> Home Link </Link> </header> {React.cloneElement({...this.props}.children, {...this.props})} </main> ) } }); function mapStateToProps(state) { return { ui: state.ui } } function mapDispachToProps(dispatch) { return bindActionCreators(actionCreators, dispatch); } export default connect(mapStateToProps, mapDispachToProps)(Main);
var app = angular.module('myApp.services', []); app.factory('UserService', ['$http', function($http){ var toReturn = {}; //does a GET request toReturn.get = function(){ return $http.get('/api/users'); } //does a POST request toReturn.create = function(data){ return $http.post('/api/users', data); } //does a 'DELETE' request toReturn.delete = function(uID){ return $http.delete('/api/users/'+id); } return toReturn; }]);
import { createAction, handleActions } from 'redux-actions'; import { Map, List } from 'immutable'; import iassign from 'immutable-assign'; const TEXT_WRITE = 'editor/TEXT_WRITE'; const INSERT_COMPONENT = 'editor/INSERT_COMPONENT'; const CHANGE_CURRENT = 'editor/CHANGE_CURRENT'; const CHANGE_STYLE = 'editor/CHANGE_STYLE'; const MERGE_STYLE = 'editor/MERGE_STYLE'; const SET_INNER = 'editor/SET_INNER'; export const textWrite = createAction(TEXT_WRITE, what => what); export const insertComponent = createAction( INSERT_COMPONENT, component => component ); export const changeCurrent = createAction(CHANGE_CURRENT, text => text); export const changeStyle = createAction(CHANGE_STYLE); export const mergeStyle = createAction(MERGE_STYLE); export const setInner = createAction(SET_INNER); const initialState = Map({ what: 'div', text: '', innerHTML: '', styles: Map({ position: '', display: '', width: '', height: '', backgroundColor: '', color: '', border: '', margin: '', padding: '', flexDirection: '', justifyContent: '', alignItems: '', flexWrap: '' }), currentComponent: '' }); export default handleActions( { [TEXT_WRITE]: (state, action) => state.set('text', action.payload), [INSERT_COMPONENT]: (state, action) => state.set('innerHTML', action.payload), [CHANGE_CURRENT]: (state, action) => state.set('currentComponent', action.payload), [CHANGE_STYLE]: (state, action) => { const data = action.payload; return state.setIn(['styles', data.attr], data.value); }, [MERGE_STYLE]: (state, action) => { console.log('스토어--------------------'); console.log(action.payload); console.log('스토어--------------------'); return state.set('styles', Map(action.payload)); }, [SET_INNER]: (state, action) => { console.log(action.payload); return state.set('innerHTML', action.payload); } }, initialState );
import { makeActionCreator } from '../../../utils/helpers/redux'; export const USER_RATE_REQUEST = 'rate/USER_RATE_REQUEST'; export const SET_USER_REQUEST = 'rate/SET_USER_REQUEST'; export const USER_RATE_SUCCESS = 'rate/USER_RATE_SUCCESS'; export const SET_USER_SUCCESS = 'rate/SET_USER_SUCCESS'; export const CLEAR_STATE = 'rate/CLEAR_STATE'; export const userRateRequest = makeActionCreator(USER_RATE_REQUEST, 'request'); export const setUser = makeActionCreator(SET_USER_REQUEST, 'request'); export const setUserSuccess = makeActionCreator(SET_USER_SUCCESS, 'response'); export const userRateSuccess = makeActionCreator(USER_RATE_SUCCESS, 'response'); export const clearState = makeActionCreator(CLEAR_STATE, ''); export const ActionsTypes = { USER_RATE_REQUEST, SET_USER_REQUEST, USER_RATE_SUCCESS, SET_USER_SUCCESS, CLEAR_STATE }; export const Actions = { userRateRequest, userRateSuccess, setUser, setUserSuccess, clearState };
let url = { get: function (key) { return getUrlValueByKey(key); }, add: function (param) { return addUrlParam(param); }, delete: function (params) { return deleteUrlParams(params); } }; /** * 根据参数名获取参数值 * @param key * @returns */ function getUrlValueByKey(key) { let query = window.location.search.substring(1); let vars = query.split("&"); for (let i = 0; i < vars.length; i++) { let pair = vars[i].split("="); if (pair[0] == key) { return decodeURI(pair[1]); } } return undefined; } /** * 增加参数 * @param param:{key: value, key: value} * @returns */ function addUrlParam(param) { //let url = window.location.href; let url = window.location.pathname; for (let key in param) { //console.log(key, param[key]); let value = param[key]; let reg = new RegExp("(^|)" + key + "=([^&]*)(|$)"); let tmp = key + "=" + value; if (url.match(reg) != null) { //更新参数 url = url.replace(eval(reg), tmp); } else { //增加参数 if (url.match("[\?]")) { url += "&" + tmp; } else { url += "?" + tmp; } } } return url; } /** * 删除参数 * @param params 字符串 或 字符串数组 * @returns */ function deleteUrlParams(params) { if ((typeof params) == "string") { //只删除一个参数 params = new Array(params) } // 获取参数,如:?id=1&name=test let search = window.location.search; //console.log("search", search); let searchArray = search.split("&"); if (searchArray.length > 0) { searchArray[0] = searchArray[0].replace("?", ""); } //console.log(searchArray); let indexArray = new Array(); for (let i = 0; i < searchArray.length; i++) { let array = searchArray[i].split("="); for (let j = 0; j < params.length; j++) { if (array[0] == params[j]) { //要删除该参数 indexArray.push(i); break; } } } //删除参数 for (let i = indexArray.length - 1; i >= 0; i--) { searchArray.splice(indexArray[i], 1); } let mix = ""; for (let i = 0; i < searchArray.length; i++) { mix += i == 0 ? "?" + searchArray[i] : "&" + searchArray[i]; } return window.location.pathname + mix; } export default url;
/*global define, App*/ define([ 'jquery', 'backbone', 'views/home/index', 'views/home/newsList', 'views/home/newsItem', 'views/home/eventsList', 'views/home/eventsItem', 'views/home/publicationsList', 'views/home/publicationsItem', 'collections/news', 'collections/events', 'collections/seminars', 'collections/publications', ], function ($, Backbone, HomeView, NewsListView, NewsItemView, EventsListView, EventsItemView, PublicationsListView, PublicationsItemView, NewsCollection, EventsCollection, SeminarsCollection, PublicationsCollection) { 'use strict'; /** * HomeController module. * @module HomeController * @see module:HomeController * * @version 1.0.0 * @summary: handle home view creation and behaviour handling */ var HomeController = Backbone.Router.extend({ /** * initialize - setup alert event listeners and handlers * * @author Andre Silva * @public * @function * @this HomeController */ initialize: function () { App.Vent.on('home:index', this._index, this); this._toggleHover(); }, /** * _index - create and render home page * * @private * @function */ _index: function () { App.Views.Active = new HomeView; requestAnimationFrame(function () { App.Container.html(App.Views.Active.render().el); }); this._news(); this._events(); this._publications(); }, /** * _news - create and render _news section @ home page * * @private * @function */ _news: function () { App.Collections.News = new NewsCollection; App.Collections.News.count = 3; App.Collections.News.isHome = true; App.Collections.News.fetch({ remove: false, success: function (response) { // setting isLarge attribute to n'th model of the collection to stylize. var index = App.Collections.News.indexOf(App.Collections.News.model); var indexSelected = App.Collections.News.at(index - 2); if (indexSelected) { indexSelected.set('isLarge', true); } else { indexSelected = App.Collections.News.at(index - 1); if (indexSelected) { if (indexSelected.get('thumbnail')) { indexSelected.set('isLarge', true); } } else { indexSelected = App.Collections.News.at(index); if (indexSelected.get('thumbnail')) { indexSelected.set('isLarge', true); } } } requestAnimationFrame(function () { App.Views.News = new NewsListView({ el: '#home-news', subview: NewsItemView, collection: App.Collections.News }).render(); App.Vent.trigger('global:scroll'); }); }, error: function (res, err) { requestAnimationFrame(function () { $('#home-news').html(App.Views.News.render().el); }); } }); }, /** * _events - create and render events section @ home page * * @private * @function */ _events: function () { App.Collections.Events = new EventsCollection; App.Collections.Events.count = 3; App.Collections.Events.isHome = true; App.Collections.Events.fetch({ remove: false, success: function () { requestAnimationFrame(function () { App.Views.Events = new EventsListView({ el: '#home-events', subview: EventsItemView, collection: App.Collections.Events }).render(); App.Vent.trigger('global:scroll'); }); }, error: function (res, err) { requestAnimationFrame(function () { $('#home-events').html(App.Views.Events.render().el); }); } }); }, /** * _publications - create and render publications section @ home page * * @private * @function */ _publications: function () { App.Collections.Publications = new PublicationsCollection; App.Collections.Publications.count = 3; App.Collections.Publications.isHome = true; App.Collections.Publications.fetch({ remove: false, success: function () { requestAnimationFrame(function () { App.Views.Publications = new PublicationsListView({ el: '#home-publications', subview: PublicationsItemView, collection: App.Collections.Publications }).render(); App.Vent.trigger('global:scroll'); }); }, error: function (res, err) { requestAnimationFrame(function () { $('#home-publications').html(App.Views.Publications.render().el); }); } }); }, /** * _toggleHover - toggle the ability to hover elements upon scrolling (to increase performance) * * @private * @function */ _toggleHover: function () { window.addEventListener('scroll', function () { clearTimeout(this.TIMER); if(!App.Body.hasClass('disable-hover')) { App.Body.addClass('disable-hover'); } this.TIMER = setTimeout(function(){ App.Body.removeClass('disable-hover'); },500); App.Vent.trigger('global:scroll'); }, false); }, }); return HomeController; });
'use strict' const express = require('express') const product = require('../controllers/productController') const api = express.Router() api.get('/products', product.listAll) api.get('/products/:productId', product.getByID) api.post('/products', product.addProduct) api.put('/products/:productId', product.updateProduct) api.delete('/products/:productId', product.deleteProduct) module.exports = api
import {combineReducers} from "redux" import list from './list' let reducer =combineReducers({ list }); export default reducer;
import Component from '@glimmer/component'; import debugLogger from 'ember-debug-logger'; import { action } from '@ember/object'; import { inject as service } from '@ember/service'; import { isBlank } from '@ember/utils'; export default class TwyrSidenavInnerComponent extends Component { // #region Services @service constants; @service twyrSidenav; // #endregion // #region Private Attributes debug = debugLogger('twyr-sidenav-inner'); // #endregion // #region Constructor constructor() { super(...arguments); this.debug(`constructor`); this.twyrSidenav.register(this.args.name, this); } // #endregion // #region Lifecycle Hooks willDestroy() { this.debug(`willDestroy`); this.twyrSidenav.unregister(this.args.name, this); super.willDestroy(...arguments); } // #endregion // #region DOM Event Handlers @action handleClick(event) { if(!this.args.closeOnClick || this.isLockedOpen) { this.debug(`handleClick: closeOnClick OR isLockedOpen`); return; } if(!this.args.onToggle) { this.debug(`handleClick: no onToggle`); return; } if(typeof this.args.onToggle !== 'function') { this.debug(`handleClick: onToggle not func`); return; } this.debug(`propagating click on sidenav-inner with event: `, event); this.toggle(false); } // #endregion // #region Public Methods open() { this.debug(`open`); if(this.args.closed && this.isLockedOpen) { this.toggle(true); } } close() { this.debug(`close`); if(!this.args.closed && !this.isLockedOpen) { this.toggle(false); } } toggle(toggleValue) { this.debug(`toggle::value: ${toggleValue}`); if(this.isLockedOpen) return; if(!this.args.onToggle) { this.debug(`toggle: no onToggle`); return; } if(typeof this.args.onToggle !== 'function') { this.debug(`toggle: onToggle not func`); return; } if(isBlank(toggleValue)) toggleValue = this.args.closed; this.debug(`propagating toggle on sidenav-inner with arguments: `, toggleValue); this.args.onToggle(toggleValue); } // #endregion // #region Computed Properties get isLockedOpen() { let isLockedOpen = this.args.lockedOpen; if(typeof isLockedOpen !== 'boolean') { const mediaQuery = this.constants.MEDIA[isLockedOpen] || isLockedOpen; isLockedOpen = window.matchMedia(mediaQuery).matches; } this.debug(`isLockedOpen? `, isLockedOpen); return isLockedOpen; } // #endregion }
import { RECEIVE_TRANSACTIONS } from '../actions/transactions'; export default (state = { transactions: [], error: null }, action) => { switch (action.type) { case RECEIVE_TRANSACTIONS: const isError = action.error; if (isError) { return { ...state, error: action.payload }; } else { return { ...state, transactions: action.payload, error: null }; } default: return state; } };
import React, { Component } from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import styles from './Signup.less'; import { signup } from '../redux/actions'; class Signup extends Component { constructor(props) { super(props); this.state = { email: '', password: '', confirmPassword: '', } this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } componentDidUpdate() { const { signedUp } = this.props; if(signedUp) { this.props.history.push('/'); } } handleChange(e) { this.setState({ [e.target.id]: e.target.value, }) } handleSubmit(e) { e.preventDefault(); const { signup } = this.props; const { email, password } = this.state; signup(email, password); this.props.history.push('/confirm'); } render() { return ( <div className={styles.signup}> <form onSubmit={this.handleSubmit}> <div> <label> E-mail: </label> <input onChange={this.handleChange} type="text" id="email" value={this.state.email} /> </div> <div> <label> Password: </label> <input onChange={this.handleChange} type="password" id="password" value={this.state.password} /> </div> <div> <label> Confirm password: </label> <input onChange={this.handleChange} type="password" id="confirmPassword" value={this.state.confirmPassword} /> </div> <button>Sign up</button> </form> </div> ); } } Signup.propTypes = { signup: PropTypes.func.isRequired, signedUp: PropTypes.bool, }; Signup.defaultProps = { signedUp: false, }; const mapStateToProps = state => ({ signedUp: state.runtime.get('currentUser').get('signedUp'), }); export default connect(mapStateToProps, { signup })(Signup);
// import something here import { JSONView } from 'vue-json-component' // "async" is optional export default async ({ Vue }) => { // something to do Vue.use(JSONView) }
// eslint-disable-next-line import/no-cycle import dataProvider from './dataProvider'; import { fetchJson } from './fetch'; import storage from '../utils/storage'; const httpClient = (url, options = {}) => { const token = storage.getToken(); const user = {}; if (token) { user.token = token; } return fetchJson(url, { user, ...options }); }; const { API_URL } = process.env; const Provider = dataProvider(API_URL, httpClient); export function create(endpoint, data) { return Provider.create(endpoint, { data }); } export function createOne(endpoint, data) { return Provider.createOne(endpoint, { data }); } export function deleteOne(endpoint, id, params) { return Provider.delete(endpoint, { id, queryParams: params, }); } export function getList(endpoint, params = {}) { return Provider.getList(endpoint, params); } export function resetPassword(endpoint, params = {}) { return Provider.resetPassword(endpoint, params); } export function getOne(endpoint, id, params) { return Provider.getOne(endpoint, { id, ...params }); } export function updateOne(endpoint, id, data) { return Provider.update(endpoint, { id, data }); }
module.exports = { testRunner: 'jest', runnerConfig: 'e2e/config.json', specs: 'e2e', behavior: { init: { exposeGlobals: true, }, }, configurations: { 'ios.sim.release': { type: 'ios.simulator', build: 'xcodebuild -workspace ios/SpaceSeek.xcworkspace -scheme SpaceSeek -configuration Release -sdk iphonesimulator -derivedDataPath ios/build/app -quiet', binaryPath: './ios/build/app/Build/Products/Release-iphonesimulator/SpaceSeek.app', device: { type: 'iPhone 11 Pro', }, artifacts: { pathBuilder: './e2e/detox.pathbuilder.ios.js', }, }, 'ios.sim.debug': { type: 'ios.simulator', build: 'xcodebuild -workspace ios/SpaceSeek.xcworkspace -UseNewBuildSystem=NO -scheme SpaceSeek -configuration Debug -sdk iphonesimulator -derivedDataPath ios/build -quiet', binaryPath: './ios/build/Build/Products/Debug-iphonesimulator/spaceseek.app', device: { type: 'iPhone 11 Pro', }, artifacts: { pathBuilder: './e2e/detox.pathbuilder.ios.js', }, }, 'android.emu.release': { type: 'android.emulator', build: 'cd android ; ./gradlew assembleRelease assembleAndroidTest -DtestBuildType=release ; cd -', binaryPath: './android/app/build/outputs/apk/release/app-release.apk', device: { avdName: 'emu', }, artifacts: { pathBuilder: './e2e/detox.pathbuilder.android.js', }, }, }, };
module.exports = function(app) { Ember.TEMPLATES['components/social-shareTw'] = require('./template.hbs'); const Share = require('../../../../lib/social-share.js'); app.SocialShareTwComponent = Ember.Component.extend({ classNames: ['social-shareTw', 'social-share'], size: 32, img: '', title: '', text: '', actions: { modal() { var options = this.getProperties('img', 'title', 'text'); var loc = window.location; if(options.img){ options.img = `${loc.origin}${options.img}`; } Share.twitter(options); } }, }); };
import React from 'react'; import { buildImageObj } from '../../lib/helpers'; import imageUrlFor from '../../lib/image-url'; const BlockContent = require('@sanity/block-content-to-react'); const Feature = ({ feature }) => { return ( <div className="feature-module__feature"> {feature.icon && feature.icon.asset && ( <img className="feature-module__image" src={imageUrlFor(buildImageObj(feature.icon)) .width(300) .url()} alt="feature icon" /> )} <h4 className="feature-module__heading"> {feature && feature.title && feature.title} </h4> <div className="feature-module__text"> {feature && feature.text && <BlockContent blocks={feature.text} />} </div> </div> ); }; export default Feature;
// Load dependencies (for their side effects) import 'bootstrap/dist/css/bootstrap.css'; import 'bootstrap-vue/dist/bootstrap-vue.css'; import '@fortawesome/fontawesome-free/css/all.css'; import * as Sentry from '@sentry/browser'; import * as Integrations from '@sentry/integrations'; import Vue from 'vue'; import { BootstrapVue } from 'bootstrap-vue'; import VueRouter from 'vue-router'; import '@/assets/common.css'; import About from '@/views/About.vue'; import Home from '@/views/Home.vue'; Vue.use(BootstrapVue); Vue.use(VueRouter); // Activate remote error monitoring (if a DSN is provided in the `.env` file that is shared by Flask and Vue) Sentry.init({ dsn: process.env.SENTRY_DSN, integrations: [new Integrations.Vue({ Vue, logErrors: true, attachProps: true })], }); const routes = [ { path: '/', name: 'home', component: Home, meta: { title: 'Home' }, }, { path: '/about', name: 'about', component: About, meta: { title: 'About' }, }, { path: '/variant/:variant/', name: 'variant', meta: { title: 'Variant' }, // route level code-splitting // this generates a separate chunk (variant.[hash].js) for this route // which is lazy-loaded when the route is visited. component: () => import(/* webpackChunkName: "variant" */ '../views/Variant.vue'), }, { path: '/region/', name: 'region', meta: { title: 'Region' }, component: () => import(/* webpackChunkName: "region" */ '../views/Region.vue'), }, { path: '/error/', name: 'error', meta: { title: 'Error' }, component: () => import(/* webpackChunkName: "errors" */ '../views/Error.vue'), }, { path: '*', name: '404', meta: { title: 'Not found' }, component: () => import(/* webpackChunkName: "errors" */ '../views/NotFound.vue'), }, ]; const router = new VueRouter({ mode: 'history', base: process.env.BASE_URL, routes, }); router.beforeEach((to, from, next) => { const base = to.meta.title || 'Explore'; document.title = `${base} | PheGET: eQTL browser`; next(); }); export default router;
import React from "react"; import Practitioner from "./Practitioner"; import ErrorBoundary from "./ErrorBoundary"; function PractitionerCaught(){ return( <ErrorBoundary> <Practitioner /> </ErrorBoundary> ) } export default PractitionerCaught
// (function() { var email = document.getElementById('email'); var password = document.getElementById('password'); var submitButton = document.getElementById('submit'); submitButton.onclick = function() { console.log(email.value); firebase.auth().signInWithEmailAndPassword(email.value, password.value).catch(function(error) { // Handle Errors here. var errorCode = error.code; var errorMessage = error.message; alert(error.code +": " + error.message) // ... }).then(function () { console.log("user logged in??"); var user = firebase.auth().currentUser; if (user) { window.location.href = "http://localhost:3000/profile.html"; } }) } // }) firebase.auth().onAuthStateChanged(function(user) { if (user) { window.location.href = "http://localhost:3000/profile.html"; } });
/* * Wraps the matrix-js-sdk to provide Extended CS API functionality as outlined * in http://matrix.org/docs/spec/#client-server-v2-api-extensions */ "use strict"; var extend = require("extend"); var request = require("request"); var matrixSdk = require("matrix-js-sdk"); var modelRequests = require("../models/requests"); var logger = require("../logging").get("matrix-js-sdk"); var baseClientConfig; var clients = { // request_id: { // user_id: Client // } }; var doRequest = function(opts, callback) { var req = modelRequests.findRequest(opts._matrix_opts._reqId); var log = (req ? req.log : logger); log.debug("%s %s %s Body: %s", opts.method, opts.uri, opts.qs.user_id ? "(" + opts.qs.user_id + ")" : "(AS)", opts.body ? JSON.stringify(opts.body).substring(0, 80) : ""); request(opts, function(err, response, body) { logResponse(log, opts, err, response, body); callback(err, response, body); }); }; matrixSdk.request(doRequest); // This section allows the caller to extract an SDK client for a given request // ID. This is much more useful because it means we can log outgoing requests // with the request ID. In order to do this though, we need to contort how an // sdk client is obtained. module.exports.getClientAs = function(userId, requestId) { requestId = requestId || "-"; // default request ID var userIdKey = userId || "bot"; // no user ID = the bot // see if there is an existing match var client = getClientForRequest(requestId, userIdKey); if (client) { return client; } // add a listener for the completion of this request so we can cleanup // the clients we've made var req = modelRequests.findRequest(requestId); if (req) { req.defer.promise.finally(function() { delete clients[requestId]; }); } // store a new client and return that client = matrixSdk.createClient(extend({ userId: userId, queryParams: { user_id: userId } }, baseClientConfig)); client._http.opts._reqId = requestId; setClientForRequest(requestId, userIdKey, client); return client; }; module.exports.setClientConfig = function(config) { baseClientConfig = config; // home server url, access token, etc setClientForRequest("-", "bot", matrixSdk.createClient(extend({ // force set access_token= so it is used when /register'ing queryParams: { access_token: baseClientConfig.accessToken } }, baseClientConfig ))); }; function setClientForRequest(requestId, userIdKey, sdkClient) { if (!clients[requestId]) { clients[requestId] = {}; } sdkClient.credentials._reqId = requestId; clients[requestId][userIdKey] = sdkClient; } function getClientForRequest(requestId, userIdKey) { if (clients[requestId] && clients[requestId][userIdKey]) { return clients[requestId][userIdKey]; } } function logResponse(log, opts, err, response, body) { var httpCode = response ? response.statusCode : null; var userId = opts.qs ? (opts.qs.user_id || null) : null; if (err) { log.error("%s %s %s HTTP %s Error: %s", opts.method, opts.uri, userId ? "(" + userId + ")" : "(AS)", httpCode, JSON.stringify(err)); return; } if (httpCode >= 300 || httpCode < 200) { log.error("%s %s %s HTTP %s Error: %s", opts.method, opts.uri, userId ? "(" + userId + ")" : "(AS)", httpCode, JSON.stringify(body)); } else { log.debug( // body may be large, so do first 80 chars "HTTP %s : %s", httpCode, JSON.stringify(body).substring(0, 80) ); } }
export const frontendContent = { description: "Frontend development is the part of coding that the user interacts with. This type of coding results in a UI (User Interface). For instance: Developing the code for this purple element, which you are looking at right now is part of the frontend", stack: `The basic stack for each and every frontend developer consists of the three mighty ones: HTML, CSS and Javascript. In addition to these three, I use a UI-library to facilitate the development process called React. On top of React, I often times use a framework called NextJS to enhance performance as well as SEO (Search Engine Optimization) of projects.`, images: ["HTML.svg", "CSS.svg", "Javascript.svg", "React.svg", "Nextjs.svg"] } export const backendContent = { description: "Everything that pertains to the coding of a Web server forms part of Backend development. Web servers are imperative for authentication and authorisation of users, for processing payments as well as database operations.", stack: "I like to maintain my entire code base in one programming language. Hence, I choose NodeJS to be able to write Javascript code on the backend as well. NextJS is also a suitable choice for me to build APIs.", images: ["Nodejs.svg", "Nextjs.svg"] } export const databaseContent = { description: "Databases are used to persist data. They are the permanent storage of your applications and websites data.", stack: "MongoDB is the document-based database management system that I use the most. Beyond that, I also use the google database Firebase as well as the relational database MySQL.", images: ["Mongodb.svg", "Mysql.svg", "Firebase.svg"] } export const designContent = { description: "Design tools ease the process of mocking up design drafts and final versions of websites.", stack: "Figma is the go-to software for designing websites for me.", images: ["Figma.svg"] }
import React from 'react'; import renderer from 'react-test-renderer'; import configureStore from 'redux-mock-store'; import notificationLogsReducer from '../../store/notificationLogs/notificationLogs.reducers'; const middlewares = []; const mockStore = configureStore(middlewares); const fetchNotificationLogsSuccess = () => ({ type: 'FETCH_NOTIFICATION_LOGS' }); const updateLastNotified = () => ({ type: 'UPDATE_LAST_NOTIFIED' }); describe('test actions notification logs', () => { it('should dispatch action fetchNotificationLogsSuccess', () => { const initialState = {} const store = mockStore(initialState) store.dispatch(fetchNotificationLogsSuccess()) const actions = store.getActions() const expectedPayload = { type: 'FETCH_NOTIFICATION_LOGS' } expect(actions).toEqual([expectedPayload]) }); it('should dispatch action updateLastNotified', () => { const initialState = {} const store = mockStore(initialState) store.dispatch(updateLastNotified()) const actions = store.getActions() const expectedPayload = { type: 'UPDATE_LAST_NOTIFIED' } expect(actions).toEqual([expectedPayload]) }); }); describe('test reducer notification logs', () => { it('reducers initialState', () => { let wrapper wrapper = notificationLogsReducer(undefined, {}) expect(wrapper).toEqual({ fectNotificationLogsLoading: false, logs: [], lastNotified: 0, fectNotificationLogsError: false, }) }); });
<script type="text/javascript"> function changeFrete(){ vtexjs.checkout.getOrderForm().done(function(orderForm) { var email = orderForm.clientProfileData.email; var state = orderForm.shippingData.address.state; var products_total = parseFloat((orderForm.totalizers[0].value)/100).toFixed(2); var sul_sudeste =["SP","MG","RJ","ES","PR","RS","SC"]; var valor_frete = 0; var percentual_regua = 0; var diferenca = 0; var mensagem =""; if(sul_sudeste.indexOf(state) > -1){ valor_frete = 97.00; }else{ valor_frete = 147.00; } if(products_total > valor_frete){ percentual_regua = 100; }else{ diferenca = parseFloat(valor_frete - products_total).toFixed(2); percentual_regua = parseFloat((products_total/valor_frete)*100).toFixed(0); } if(diferenca == 0){ mensagem = "Parabéns você possui frete grátis"; }else{ diferenca = diferenca.replace('.',','); mensagem = "Quase faltam R$"+diferenca+" para você ter frete grátis"; } console.log(mensagem + " " + percentual_regua); if(localStorage.getItem('vtex_user_email')!= email){ localStorage.setItem('vtex_user_email', email); } if(localStorage.getItem('vtex_user_state')!= state){ localStorage.setItem('vtex_user_state', state); } }); } $(document).ready(function(){ changeFrete(); }); $(document).bind("blur click dblclick change keydown keypress keyup", function(e){ setTimeout(function(){ changeFrete(); }, 2000); }); </script>
/* класс, описывающий студента */ class Student{ name; surname; lastName; faculty; speciality; listDisciplines; /*список дисциплин*/ constructor(name, surname, lastName, faculty, speciality) { this.name = name; this.surname = surname; this.lastName = lastName; this.faculty = faculty; this.speciality = speciality; this.listDisciplines = []; } } /* класс, описывающий дисциплину */ class Discipline{ nameDiscipline; listOfLaboratoryWork; constructor(nameDiscipline) { this.nameDiscipline = nameDiscipline; } } /* класс, описывающий лабораторную работу */ class LaboratoryWork { }
/* eslint-disable no-unused-vars */ /* eslint-disable import/no-unresolved */ import Vue from 'vue'; import VueSweetalert2 from 'vue-sweetalert2'; import { ValidationObserver, ValidationProvider, extend, localize, configure, } from 'vee-validate'; import TW from 'vee-validate/dist/locale/zh_TW.json'; import * as rules from 'vee-validate/dist/rules'; import Loading from 'vue-loading-overlay'; import 'vue-loading-overlay/dist/vue-loading.css'; import axios from 'axios'; import qs from 'qs'; import VueAxios from 'vue-axios'; import App from './App.vue'; import router from './router'; import store from './store'; import 'bootstrap'; Object.keys(rules).forEach((rule) => { extend(rule, rules[rule]); }); localize('zh_TW', TW); Vue.component('ValidationObserver', ValidationObserver); Vue.component('ValidationProvider', ValidationProvider); Vue.prototype.$qs = qs; Vue.component('Loading', Loading); configure({ classes: { valid: 'is-valid', invalid: 'is-invalid', }, }); Vue.config.productionTip = false; Vue.use(VueAxios, axios); Vue.use(VueSweetalert2); new Vue({ router, store, render: (h) => h(App), }).$mount('#app'); // beforeEach router.beforeEach((to, from, next) => { if (to.meta.requiresAuth) { if (JSON.parse(localStorage.getItem('status')) === true) { next(); } else { next({ path: '/Login' }); } } else { next(); } }); // 轉頁後回到Top // router.afterEach((to, from, next) => { // setTimeout(() => { // window.scrollTo(0, 0); // }, 1000); // });
/** * 教师的个人档案 */ $(function(){ var roleId=GetQueryString("roleId"); var id=GetQueryString("id"); $.ajax({ url:"../../gettecherListById.do", type:"post", dataType:"json", data:"id="+id, success:function(data){ if(data.teacher.accountStatus==1){ data.teacher.accountStatus="正常"; }else{ data.teacher.accountStatus="冻结"; } $("#accountStatus").text(data.teacher.accountStatus); $("#id").text(data.teacher.id); $("#department").text(data.teacher.department); $("#course").text(data.teacher.course); $("#workingWay").text(data.teacher.workingWay); $("#workingPlace").text(data.teacher.workingPlace); $("#email").text(data.teacher.email); $("#idCard").text(data.teacher.idCard); $(".name").text(data.teacher.name); $("#sex").text(data.teacher.sex); $("#phone").text(data.teacher.phone); $("#qq").text(data.teacher.qq); $("#nation").text(data.teacher.nation); $("#birthPlace").text(data.teacher.birthPlace); $("#political").text(data.teacher.political); $("#education").text(data.teacher.education); $("#school").text(data.teacher.school); $("#major").text(data.teacher.major); } }) }) /** * 通过上个页面传递过来的名字,获取上个页面传递过来的值 */ function GetQueryString(name) { var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)"); var r = window.location.search.substr(1).match(reg); if(r!=null)return unescape(r[2]); return null; }
import ProjectCard from "./ProjectCard"; export default function Projects({ projects }) { return ( <section className="pb-10"> <h1 className="mb-6 text-lg font-bold">My Projects</h1> <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4"> {projects.map((p) => { return <ProjectCard project={p} key={p.link} />; })} </div> </section> ); }
/* The ParkingMap object handles all the work of parsing the parking data and rendering the map */ function ParkingMap() { var _mapDivId = ""; // set in calling template, tells ParkingMap target div var _parkingData = null; // hold parking garage array from api var _map; // holds google map reference } /* "Public" method that gets it all started */ ParkingMap.prototype.renderMap = function(mapDivId, parkingData) { this._mapDivId = mapDivId; this._parkingData = parkingData; this.initializeMap(); this.setMapMarkers(); this.setCurrentLocationMarker(); }; ParkingMap.prototype.initializeMap = function() { var mapOptions = { zoom: 13, center: new google.maps.LatLng(43.0600417, -89.40123), mapTypeId: google.maps.MapTypeId.ROADMAP }; this._map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions); }; ParkingMap.prototype.setCurrentLocationMarker = function() { /* Set current location marker if browser supports it. Would like to get Geolocation.watchPosition() working at some point */ var browserSupportFlag = new Boolean(); var userLocation; var themap = this._map; // get map in scope for geolocate closure below if(navigator.geolocation) { browserSupportFlag = true; navigator.geolocation.getCurrentPosition(function(position) { userLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude); marker = new google.maps.Marker({ position: userLocation, map: themap, title: 'Your location', icon: 'img/bluedot.png' }); }, function() { this.handleNoGeolocation(browserSupportFlag); }); } // Browser doesn't support Geolocation else { browserSupportFlag = false; this.handleNoGeolocation(browserSupportFlag); } }; ParkingMap.prototype.handleNoGeolocation = function(errorFlag) { var initialLocation; if (errorFlag == true) { initialLocation = new google.maps.LatLng(43.0728, -89.3885); // default it to Madison } else { initialLocation = new google.maps.LatLng(60, 105); // put them in Siberia } this._map.setCenter(initialLocation); }; /* Invoked during the setMapMarkers loop, setting marker color based on available slots */ ParkingMap.prototype.setMarkerIcon = function(openSpots) { if (openSpots > 50) { return 'img/green.png'; } if (openSpots > 0) { return 'img/yellow.png'; } else { return 'img/red.png'; } }; /* setMapMarkers loops through the parkdingData, creates the markers, sets infowindow content and and adds the click event listener to each marker. A little ripe for refactor */ ParkingMap.prototype.setMapMarkers = function() { var infowindow = new google.maps.InfoWindow(); var geocoder = new google.maps.Geocoder(); var marker; /* if !this._parkingData, still load the map, but don't try to parse the this._parkingData */ if (!this._parkingData) { alert('There was an issue retrieving the parking data from Madison City Data. please reload or try back later.'); } else { for (var i = 0; i < this._parkingData.length; i++) { marker = new google.maps.Marker({ position: this._parkingData[i].coordinates, map: this._map, title: this._parkingData[i].name, icon: this.setMarkerIcon(this._parkingData[i].openSpots) }); // add click handler to each marker google.maps.event.addListener(marker, 'click', (function(marker, currIndex, parkingData, map) { return function() { infowindow.setContent(parkingData[currIndex].name + '<br/>' + parkingData[currIndex].address.street + '</br>' + parkingData[currIndex].openSpots + ' of ' + parkingData[currIndex].totalSpots + ' spots remaining' + '</br>' + '<a href="'+ parkingData[currIndex].webUrl + '">more info</a>' ); infowindow.open(map, marker); } })(marker, i, this._parkingData, this._map)); } // end for loop } };
Slingshot.fileRestrictions("myFileUploads", { allowedFileTypes: ["audio/wav", "video/webm", "image/png"], maxSize: 20 * 1024 * 1024 // 20 MB (use null for unlimited). });
"use strict"; var util = require( "util" ), path = require( "path" ), yeoman = require( "yeoman-generator" ), yosay = require( "yosay" ), chalk = require( "chalk" ); // TODO : generate jenez files (cf. http://yeoman.io/generators.html#writing-your-first-generator) var KrknJenezGenerator = yeoman.generators.Base.extend( { init: function() { this.pkg = require( "../package.json" ); this.on( "end", function() { if( !this.options[ "skip-install" ] ) { this.installDependencies(); } } ); }, askFor: function() { var done = this.async(); // Have Yeoman greet the user. this.log( yosay( "Welcome to the KRKN jenez generator." ) ); var prompts = [ { type: "confirm", name: "someOption", message: "Would you like to enable this option?", default: true } ]; this.prompt( prompts, function( props ) { this.someOption = props.someOption; done(); }.bind( this ) ); }, app: function () { this.mkdir( "app" ); this.mkdir( "app/templates" ); this.copy( "_package.json", "package.json" ); this.copy( "_bower.json", "bower.json" ); }, projectfiles: function () { this.copy( "editorconfig", ".editorconfig" ); this.copy( "jshintrc", ".jshintrc" ); } } ); module.exports = KrknJenezGenerator;
// Create a module that exports a function that takes a number // as a parameter and stores it in a list. The list should not be accessible // from outside the module. // Export another function that returns a version of the data list that // is sorted in ascending order. The function you use to sort the data correctly // should not be accessible from outside the module. (Think back to the Custom // Sorting Exercise when handling sorting) // Implement a Node.js script that imports the functionality of your module, // adds at least 5 different data points to the module's data list, and // outputs the sorted list. var list = require("./exportProg"); list.action(); console.log(list.sortedList) // invokes the function `pusher` // console.log(list.results)
const UserService = require("../services/user.service"); const getById = async (req, res) => { try { const id = req.params.id; const user = await UserService.getUserByIdFull(id); res.json({ user }); } catch (e) { console.log(e); res.status(500).json({ message: "Error on get user by id" }); } }; module.exports = { getById };
import React, { useState } from "react"; import { Link, useHistory } from "react-router-dom"; import axios from "axios"; import { TextField, Button } from "@material-ui/core"; import appLogo from '../../../assets/branding/logo.png'; import PasswordTextField from "../../../Components/PasswordTextField/PasswordTextField"; import SignImage from '../../../Components/SignImage/SignImage.js'; import AlertHelper from "../../../Components/Alert/Alert"; import "./SignInPage.scss"; const SignIn = () => { const history = useHistory(); const regexpEmail = /^(([^<>()[\]\\.,;:\s@']+(\.[^<>()[\]\\.,;:\s@']+)*)|('.+'))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const [openError, setError] = useState(false); const [errorText, setErrorText] = useState(false); const [alert, setAlert] = useState(""); const loginUser = async () => { try { const res = await axios.post( `${process.env.REACT_APP_SERVER_ENDPOINT}/login`, { email, password, } ); if (res && res.data && res.data.statusCode && res.data.statusCode === '200') { localStorage.clear(); localStorage.setItem("user", JSON.stringify(res.data.data)); localStorage.setItem("email", res.data.data?.email); history.push("/my/test"); } } catch (e) { setAlert("Warning"); setErrorText("Неправильный E-mail или пароль"); setError(true); } }; const checkEmail = (e) => { if (!email.match(regexpEmail)) { setAlert("error"); setErrorText(`Например: jsmith@example.com`); setError(true); } else { setAlert("success"); setErrorText(`Корректый E-mail`); setError(true); } }; let checkDisabled = !email.match(regexpEmail); return ( <div className='all'> <div className="left"> <div> <Link to='/' > <img className="image-header" src={appLogo} alt="logo"/> </Link> </div> <h2 className="header-text">Вход в личный кабинет</h2> <div className="sign-in"> <div className="input-fields"> <TextField label="Почта" className="input" variant="outlined" InputLabelProps={{ shrink: true, className: "label" }} value={email} onChange={(e) => setEmail(e.target.value)} onBlur={() => checkEmail()} /> </div> <div className="input-fields"> <PasswordTextField value={password} setValue={setPassword} /> </div> <div className='memory'> <div className="left-box"> <input type="checkbox" className='checkbox'/> <p className='left-text-checkbox'>Запомнить меня</p> </div> {/* <div className="forgot-password"> <Link to="/forgot_password"> Забыли пароль? </Link> </div> */} </div> <div className="login"> <Button className="login-btn" variant="outlined" disabled={checkDisabled} onClick={() => loginUser()} > Вход </Button> </div> </div> <div className="buttons"> <p>Нет аккаунта?</p> <Link to="/sign/up"> Создать аккаунт </Link> </div> <AlertHelper isOpen={openError} text={errorText} alertColor={alert} onClose={setError} /> </div> <div className='rigth'> <SignImage/> </div> </div> ); }; export default SignIn;
var fs = require("fs"); module.exports = function(app) { //========read db.json file and return all notes as json =========================== app.get("/api/notes", function (req, res) { fs.readFile("db/db.json", function(err, data) { if (err) throw err; // console.log(JSON.parse(data)); res.json(JSON.parse(data)); }); }); //=========receive new note to save on request body, add it to db.json, return new note to client======= app.post("/api/notes", function(req, res) { console.log(req.body); var notes = JSON.parse(fs.readFileSync("db/db.json")); var newNote = req.body; newNote.id = notes.length; console.log(notes) notes.push(newNote); console.log(notes); fs.writeFile("db/db.json",JSON.stringify(notes), function(err) { if (err) throw err; console.log("Saved"); }) res.json(req.body); }); //======= delete note given ID ====================== app.delete("/api/notes/:id", function(req, res) { var notes = JSON.parse(fs.readFileSync("db/db.json")); console.log(notes[req.params.id]); console.log(req.params.id); notes.splice(req.params.id, 1); // fix id for (i=0; i < notes.length; i++){ if(!notes[i].id == i){ notes[i].id = i; }; }; //rewrite db fs.writeFile("db/db.json",JSON.stringify(notes), function(err) { if (err) throw err; console.log("Saved"); }) }); }
/** * Created by user on 04.03.15. */ 'use strict'; angular.module('dotted-linechart-directive', []) .directive('crmDottedLinechart', function ($compile, $timeout, ChartInit) { return { scope: { options: '=' }, templateUrl: 'components/directives/COMMON/dottedLineChart/dottedLineChartTpl.html', link: function ($scope, $element, $attrs) { $scope.leftBlock = $scope.options.leftBlockDisabled ? false : true; $scope.addBlueBg = $scope.leftBlock ? 'blue-bg' : ''; $scope.height = $scope.options.bottomBlock ? '200' : '210'; $scope.height = $scope.options.height ? angular.copy($scope.options.height) : angular.copy($scope.height); $scope.paddingTop = $scope.options.bottomBlock ? '10' : '77'; $scope.activeBg = 'ActiveElementColor'; $scope.chartBg = 'GraphBackgroundColor'; var initChart = function () { var method = 'dottedLineChartInit'; if ($scope.options.universal) method = 'dottedLineChartInitUniversal'; ChartInit[method]($scope.options.chartID, $scope.options.chartData, $scope.options.tooltipLabel); }; $scope.$watchCollection('options.chartData', function (newVal, oldVal) { //console.log('$watch chartData', newVal); $timeout(function () { initChart(); }, 0); }); $timeout(function () { initChart(); }, 0); } }; });
import React, {Component} from "react"; import FontAwesome from "react-fontawesome" class Task extends Component { render() { return( <div> <div className="container"> <div className="row"> <div className="col-xs-6"> <div> <p style={{textAlign: 'center'}}> <br /> </p> </div> </div> <div className="col-xs-10"> <h4>Task Name</h4> <p>Notes.</p> </div> <div className="col-xs-1"> <div className="row" style={{paddingTop: "10px"}}> <div className="col-xs-6"> <FontAwesome name= "times"/> <FontAwesome name= "Check"/> </div> </div> </div> </div> </div> </div> ) } } export default Task
export default { SET_ADDRESS: 'SELECTED/SET_ADDRESS', SET_CONTACT: 'SELECTED/SET_CONTACT', SET_WALLET: 'SELECTED/SET_WALLET', };
/*global define*/ define([ 'jquery', 'underscore', 'backbone', 'templates', 'views/members/memberPublication', 'collectionview' ], function ($, _, Backbone, JST, MemberPublicationView) { 'use strict'; var MembersPublicationsView = Backbone.CollectionView.extend({ template: JST['app/scripts/templates/members/memberPublications.hbs'], tagName: 'section', id: 'posts-list-publications', className: 'posts-list posts-list--members', events: { }, subview: MemberPublicationView, }); return MembersPublicationsView; });
import Link from "next/link"; import { Container, makeStyles, Typography, List, ListItem, Box, Button, } from "@material-ui/core"; import { Alert, AlertTitle } from "@material-ui/lab"; import { Formik, Form } from "formik"; import * as Yup from "yup"; import TextInput from "../../Component/Form/TextInput"; import ThankYou from "../../Component/Reuseable/ThankYou"; import ProductGuide from "../../Component/Reuseable/ProductGuide"; import { NextSeo } from "next-seo"; const styles = makeStyles((theme) => ({ paper: { padding: theme.spacing(2), textAlign: "center", color: theme.palette.text.secondary, marginTop: theme.spacing(8), }, box: { marginTop: theme.spacing(2), }, listHeader: { fontWeight: 600, fontSize: "24px", }, list: { "& > * + *": { marginTop: theme.spacing(2), }, }, box: { width: "75%", margin: "15px auto", }, green: { background: "rgb(55, 158, 50)", background: "linear-gradient(45deg, rgba(55, 158, 50, 1) 0%,rgba(243, 230, 0, 1) 100% )", width: "25%", textDecoration: "none", borderRadius: "10px", margin: "20px auto", color: "#fff", }, rainbowText: { background: "linear-gradient(45deg, rgba(255, 0, 255, 1) 0%,rgba(0, 255, 255, 1) 100%)", WebkitBackgroundClip: "text", WebkitTextFillColor: "transparent", width: "100%", fontWeight: 600, [theme.breakpoints.up("lg")]: { fontSize: "24px", }, [theme.breakpoints.down("md")]: { fontSize: "20px", }, [theme.breakpoints.down("xs")]: { fontSize: "18px", }, }, })); function TechPage() { const classes = styles(); const [isSubmit, setSubmit] = React.useState(false); return ( <> <NextSeo title="Download our product guide | printIQ far more than just an MIS" description="The printIQ Core is made up of 8 modules that create a seamless, end‑to‑end estimating, ordering and production workflow encompassing everything needed for your future success in print." openGraph={{ url: "https://www.printiq.com/tech", title: "Download our product guide | printIQ far more than just an MIS", description: "The printIQ Core is made up of 8 modules that create a seamless, end‑to‑end estimating, ordering and production workflow encompassing everything needed for your future success in print.", images: [ { url: "https://iq-website.vercel.app/images/homepage/printIQ-Universe2020-map.jpg", width: 800, height: 600, alt: "printIQ product Map", }, ], site_name: "https://www.printiq.com/tech", locale: "en_US", }} twitter={{ handle: "https://printiq.com/tech", site: "@printIQGlobal", cardType: "summary_large_image", }} /> <Container> <Typography variant="h3" component="h1" gutterBottom={true}> Download our product Guide </Typography> <Typography variant="body1" component="p" gutterBottom={true}> The printIQ Core is made up of 8 modules that create a seamless, end-to-end workflow. However, with printIQ you also get the option to add an array of extra modules to the Core to create your perfect workflow. This includes a range of third party options that fully integrate with printIQ, removing those integration headaches. Our range of integrated modules are designed to connect to an array of options, from file verification, to VDP, web applications, and even other printers. </Typography> <Typography variant="body1" component="p" gutterBottom={true}> To get you started here’s a brief description of the core along with (some) of the extra options that you can add to create the perfect workflow: </Typography> <Alert severity="success"> <AlertTitle>What is printIQ?</AlertTitle> printIQ is a web based workflow system that integrates business rules and component inputs such as labour and materials, to provide real-time quoting to an estimator or online client. The data then maps the optimum process path through the factory whilst providing full production, scheduling, inventory, outsource, and dispatch data to the relevant workflow modules. <br /> <Box className={classes.box}></Box> <AlertTitle> <strong>TLDR</strong> </AlertTitle> Download our product guide&nbsp; <strong> <a href="#bookDemo">here!</a> </strong> or book a demo&nbsp; <strong> <Link href="/book-a-demo"> <a target="_blank">here!</a> </Link> </strong> </Alert> <Typography variant="body1" component="p" gutterBottom={true}> <Box className={classes.listHeader} component="span"> The printIQ core comprises 8 modules that allow you to run a business from end to end: </Box> <List className={classes.list}> <ListItem> The Quote Intelligence module differs from traditional estimating software in that it understands the entire production process so it will map out all possible alternatives for the job to pass through the factory. </ListItem> <ListItem> The Workflow Manager module is a dynamic tool that is used throughout the application to manage every aspect of your business. It is essentially a set of “to do” activities with assigned actions, alerts and updates that creates a transparent information network throughout the business. All information is centralised and accessible to all staff and offers seamless transition of work from one department to the next. </ListItem> <ListItem> The Factory Manager module provides a logical and easy to use communication framework for your staff to take control of the production process. Ultimately this ensures your staff can manage the production process without reliance on any particular individual, instead using a centralised and structured flow for jobs as they move through the process lifecycle. </ListItem> <ListItem> The Inventory Manager module is integrated seamlessly with the Quote Intelligence module to deliver a feature rich extension to the estimating and job management process. The module is fully integrated with the other core printIQ modules so that every job is inventory aware. With the Inventory Manager module, we make purchasing, invoicing, and reconciliation a seamless and simple process. </ListItem> <ListItem> The Outsource Manager module provides full tendering functionality within printIQ, allowing users to obtain a range of prices for all outwork in a simple co-ordinated workflow. The module offers the ability to tender each operation within the job, to multiple suppliers. The suppliers can enter their prices directly into their own automatically generated printIQ supplier portal without any visibility of their competitors. </ListItem> <ListItem> The Dispatch Manager comes complete with automated actions such as weight verification, multiple split delivery addresses, courier rate integration, and branded box labels, so your staff can easily perform the dispatch process saving both time and money. By creating the link between all the key aspects of the dispatch environment and automating within a common platform. </ListItem> <ListItem> The Job Track Module identifies milestones as the job travels through the quoting, production, and dispatch lifecycle, allowing complete tracking throughout the entire length of the production cycle. This includes the tracking of the job itself and any of the underlying components, through to scheduling and delivery data. We wrap this up in a great looking interface that you can share with sales staff and customers. </ListItem> </List> </Typography> </Container> <Container> {isSubmit ? ( <> <ThankYou pageVisited=" Click below to download our product guide" /> <ProductGuide /> </> ) : ( <> <Alert severity="info"> <AlertTitle>Download our product guide</AlertTitle> Fill in our the form below and download our product guide </Alert> <Box className={classes.box} id="bookDemo"> <Formik initialValues={{ firstName: "", lastName: "", company: "", email: "", }} validationSchema={Yup.object({ firstName: Yup.string().max( 15, "Must be 15 characters or less" ), lastName: Yup.string() .max(20, "Must be 20 characters or less") .required("Required"), email: Yup.string() .email("Invalid email addresss`") .required("Required"), company: Yup.string() .max(20, "Must be 20 characters or less") .required("Required"), })} onSubmit={async (values, { setSubmitting, resetForm }) => { const response = await fetch( "https://hooks.zapier.com/hooks/catch/89032/ofb0dcz/", { method: "POST", body: JSON.stringify(values), } ); if (response.status == 200) { setSubmitting(false); setSubmit(true); } else { setSubmit(false); } }} > <Form className={classes.spacing}> <TextInput label="First Name" name="firstName" type="text" placeholder="First name please" /> <TextInput label="Last Name" name="lastName" type="text" placeholder="Last name please" /> <TextInput label="Company*" name="company" type="text" placeholder="Company" /> <TextInput label="Email*" name="email" type="email" placeholder="email" /> <Button className={classes.green} variant="contained" type="submit" > Submit </Button> </Form> </Formik> </Box> </> )} </Container> </> ); } export default TechPage;
//First solution function greet(name){ if(name === "Johnny") return "Hello, my love!"; else return "Hello, " + name + "!"; } //Second solution function greet(name){ const greeting = (name === "Johnny") ? `Hello, my love!` : `Hello, ${name}!`; return greeting; } //Third solution function greet(name){ return greeting = (name === "Johnny") ? `Hello, my love!` : `Hello, ${name}!`; }
const express = require('express') const write = require('./write') const getFullURL = require('./get-full-url') const delay = require('./delay') const utils = require('../utils') module.exports = (db, name, opts) => { const router = express.Router() router.use(delay) function show(req, res, next) { let chain = db.get(name) let _field = req.query._field let _expand = req.query._expand let _embed = req.query._embed // Apply filters chain = utils.expand(chain, db, opts, _expand) chain = utils.embed(chain, name, db, opts, _embed) chain = utils.fields(chain, _field) res.locals.data = chain.value() next() } function create(req, res, next) { if (opts._isFake) { res.locals.data = req.body } else { db.set(name, req.body).value() res.locals.data = db.get(name).value() } res.setHeader('Access-Control-Expose-Headers', 'Location') res.location(`${getFullURL(req)}`) res.status(201) next() } function update(req, res, next) { if (opts._isFake) { if (req.method === 'PUT') { res.locals.data = req.body } else { const resource = db.get(name).value() res.locals.data = { ...resource, ...req.body } } } else { if (req.method === 'PUT') { db.set(name, req.body).value() } else { db.get(name) .assign(req.body) .value() } res.locals.data = db.get(name).value() } next() } const w = write(db) router .route('/') .get(show) .post(create, w) .put(update, w) .patch(update, w) return router }
const Database = require('better-sqlite3') const DEBUG = process.env.DEBUG || false const db = new Database(':memory:', { memory: true, verbose: DEBUG ? console.log : null, }) const userTableQuery = db.prepare(` CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT ) `) const exerciseTableQuery = db.prepare(` CREATE TABLE IF NOT EXISTS exercises ( id INTEGER PRIMARY KEY AUTOINCREMENT, description TEXT, duration INTEGER, date TEXT, user_id INTEGER, CONSTRAINT fk_users FOREIGN KEY (user_id) REFERENCES users(id) ON UPDATE CASCADE ON DELETE CASCADE ) `) userTableQuery.run() exerciseTableQuery.run() if (DEBUG) { const insertMockUsers = db.transaction(users => { const query = db.prepare( 'insert into users (id, username) values (@id, @username)' ) users.forEach((user, idx) => { query.run({ ...user, id: idx }) }) }) const insertMockExercises = db.transaction(exercises => { const query = db.prepare(` insert into exercises ( id, description, duration, date, user_id ) values ( @id, @description, @duration, @date, @userId )`) exercises.forEach((exercise, idx) => query.run({ id: idx, ...exercise }) ) }) insertMockUsers([ { username: 'uname', }, { username: 'melchiah', }, { username: 'drunvalo_melchizedek', }, { username: 'belphegor', }, ]) insertMockExercises([ { description: 'lorem ipsum dolor sit amet', duration: 266, date: '19-06-2019', userId: 1, }, { description: 'lorem ipsum dolor sit amet', duration: 447, date: '17-05-2019', userId: 1, }, ]) } module.exports = { getExercises(userId) { if (!userId) { const query = '' } }, getUsers() {}, getUserById() {}, createExercise() {}, createUser() {}, }
import React from "react"; import App from "next/app"; import { ThemeProvider } from "@material-ui/styles"; import theme from "../src/theme"; import Callback from "../components/Callback"; import { DefaultSeo } from "next-seo"; import "react-multi-carousel/lib/styles.css"; import "@fortawesome/fontawesome-svg-core/styles.css"; import { config } from "@fortawesome/fontawesome-svg-core"; config.autoAddCss = false; import { StateProvider } from "../components/StateProvider"; class MyApp extends App { constructor (props) { super(props); this.state = { open: false }; this.handleCallbackOpen = this.handleCallbackOpen.bind(this); this.handleCallbackClose = this.handleCallbackClose.bind(this); } handleCallbackOpen () { this.setState({ open: true }); } handleCallbackClose () { this.setState({ open: false }); } componentDidMount () { //Remove the server-side injected CSS const jssStyles = document.querySelector("#jss-server-side"); if (jssStyles) { jssStyles.parentNode.removeChild(jssStyles); } } // Only uncomment this method if you have blocking data requirements for // every single page in your application. This disables the ability to // perform automatic static optimization, causing every page in your app to // be server-side rendered. // // static async getInitialProps(appContext) { // // calls page's `getInitialProps` and fills `appProps.pageProps` // const appProps = await App.getInitialProps(appContext); // // return { ...appProps } // } render () { const { Component, pageProps, reqCountryCode } = this.props; return ( <React.Fragment> <DefaultSeo openGraph={{ type: "website", locale: "en_US", site_name: "Istanbul Smile Center Dental Clinic", images: [ { url: require("../public/favicon/open-graph-photo.jpg"), width: 1200, height: 668, alt: "Clinic Entrance Photo" } ] }} twitter={{ cardType: "summary_large_image" }} /> <ThemeProvider theme={theme}> <StateProvider reqCountryCode={reqCountryCode}> <Component {...pageProps} openCallback={this.state.open} handleCallbackOpen={this.handleCallbackOpen} handleCallbackClose={this.handleCallbackClose} /> <Callback openCallback={this.state.open} handleCallbackOpen={this.handleCallbackOpen} handleCallbackClose={this.handleCallbackClose} /> </StateProvider> </ThemeProvider> </React.Fragment> ); } } MyApp.getInitialProps = async (appContext) => { const appProps = await App.getInitialProps(appContext); let reqCountryCode = ""; if (appContext.ctx.req) { if (appContext.ctx.req.header("cf-ipcountry")) { reqCountryCode = appContext.ctx.req.header("cf-ipcountry"); if (reqCountryCode === "XX" || reqCountryCode === "T1") { reqCountryCode = ""; } } } return { ...appProps, reqCountryCode }; }; export default MyApp;
const fs = require('fs'); // From the node standard library // Simple cat // try { // // Dangerous code // const data = fs.readFileSync('flintstones.txxxt', 'utf-8'); // Blocking // console.log( data ); // } catch (err) { // console.log('there was an error'); // console.log( err ); // console.log('Exiting gracefully'); // } // Asynchronous file IO: // Better efficiency because it's non-blocking // Callback function will usually receive: // error param (first, so make sure handle it) // data param fs.readFile('flintstones.txt', 'utf-8', (error, data) => { if (error) { return console.error(error); // This is a bit wanky. } console.log( data ); }); // TODO: Rewrite this using Promises
'use strict'; var zmq = require('zmq'); var _ = require('lodash'); var debug = require('debug')('martinet:worker'); function Worker(port, options) { if (!(this instanceof Worker)) { return new Worker(port, options); } this.pushSocket = zmq.socket('push'); this.pullSocket = zmq.socket('pull'); var defaults = { martinet_url: '127.0.0.1', martinet_port: '8009' }; this.options = _.defaults(options || {}, defaults); var martinetConnection = 'tcp://' + this.options.martinet_url + ':' + this.options.martinet_port; var workerConnection = 'tcp://' + this.options.martinet_url + ':' + port; debug('Starting push socket on ' + martinetConnection); this.pushSocket.connect(martinetConnection); debug('Starting pull socket on ' + workerConnection); this.pullSocket.connect(workerConnection); this.handlers = {}; var self = this; this.pullSocket.on('message', function(data) { var msg = JSON.parse(data.toString()); var handler = self.handlers[msg.name]; if(handler) { self._handle(handler, msg); } }); } Worker.VERSION = require('../package.json').version; module.exports = Worker; Worker.prototype.on = function(name, f) { this.handlers[name] = f; }; Worker.prototype.setComplete = function(task) { this.pushSocket.send(JSON.stringify({task: task, set: 'complete'})); }; Worker.prototype.setError = function(task, error) { this.pushSocket.send(JSON.stringify({task: task, set: 'error', error: error})); }; Worker.prototype.setProgress = function(task, progress) { this.pushSocket.send(JSON.stringify({task: task, set: 'progress', progress: progress})); }; Worker.prototype._handle = function(handler, task) { var self = this; handler(task.id, task.data, function(err) { if(err) { return self.setError(task.id, err); } self.setComplete(task.id); }); };
import React, { useReducer } from "react"; export const Expenses = React.createContext(); const initialState = { expenses: JSON.parse(localStorage.getItem("expenses")) || [], }; function reducer(state, { type, payload, index }) { const { expenses } = state; console.log("reducer"); switch (type) { case "UPDATE_EXPENSE": const newExpenses = [...expenses]; newExpenses[index] = payload; console.log(newExpenses); localStorage.setItem("expenses", JSON.stringify(newExpenses)); return { expenses: newExpenses }; case "ADD_EXPENSE": { console.log(expenses); const newExpenses = [...expenses, payload]; localStorage.setItem("expenses", JSON.stringify(newExpenses)); return { expenses: newExpenses }; } default: return state; } } export function ExpensesProvider(props) { const [state, dispatch] = useReducer(reducer, initialState); const value = { state, dispatch }; console.log(value); return <Expenses.Provider value={value}>{props.children}</Expenses.Provider>; }
/** * DataTable */ (function () { /** * * @type {DataTable|{}} */ var events = {}; var default_field_options = { name: '', title: '', defaultContent: '' }; function DataTable(name) { Component.call(this); this.name = name; this.options = _.clone(DataTable.default); this.fieldIndex = 0; this.fields = {}; this.tool_column = null; this.button_groups_count = 0; this.render_handler = renderHandler; this.value_handler = null; init(this); } DataTable.prototype = Object.create(Component.prototype); DataTable.default = { classes: ['table table-hover'], tableToolbarSelector: '.table-toolbar.btn-toolbar', useTools: true, useSelectCheckbox: false, toolsTitle: 'Actions', toolsColumnName: 'tools', data: [], destroy: true, sortOptions: [], source: '', order: [], serverSide: false, processing: true, paging: true, responsive: true, autoAlertError: false, ajaxComplete: null, lengthMenu: [[15, 25, 50, 100], [15, 25, 50, 100]], buttons: [ 'copyHtml5', 'excelHtml5', 'csvHtml5', 'pdfHtml5', 'print' ], pagingType: "full_numbers", language: { search: '<div class="form-group has-feedback">_INPUT_<span class="fa fa-search form-control-feedback text-muted" aria-hidden="true"></span></div>', lengthMenu: 'Show _MENU_', info: '<strong class="text-info">_START_ - _END_</strong> of <strong class="text-danger">_TOTAL_</strong>', searchPlaceholder: "Search..." }, oClasses: { sWrapper: 'dataTables_wrapper dt-bootstrap', sFilterInput: 'form-control' }, dom: '<"row"<"col-sm-3 hidden-xs"f><"col-sm-9 text-right"<"table-toolbar btn-toolbar pull-right hidden-print"B>>><"row"<"col-sm-12"<"dt-table-wrapper" tr>>><"table-component hr-separator"><"row"<"col-sm-4 hidden-xs"<"inline-block table-component"l><"table-component separator"><"inline-block"i>><"col-sm-8 hidden-print"p>>' }; DataTable.Buttons = {}; DataTable.prototype.addField = function (detail) { detail = configField(detail); if (!detail.name) { detail.name = this.fieldIndex++; } this.fields[detail.name] = detail; this.trigger('add_field', _.clone(detail)); return this; }; DataTable.prototype.addFields = function () { var self = this, fields = _.flatten(arguments); fields.forEach(function (field) { self.addField(field); }); return this; }; /** * * @param {string|Array|null|{}} fields * @param {{}} options * @return {DataTable} */ DataTable.prototype.configFields = function (fields, options) { if (arguments.length == 0) { return; } var self = this; var thisId = this.id; var table_fields = Object.keys(this.fields); /** * @type {Array} * @private */ var _fields = []; if (arguments.length == 1) { options = fields; fields = null; } if (_.isNull(fields)) { _fields = _.clone(table_fields); } else { fields = _.castArray(fields); for (var i = 0, len = fields.length; i < len; i++) { if (_.has(this.fields, fields[i])) { _fields.push(fields[i]); } else { var field = parseInt(fields[i] + ''); if (_.isNumber(field) && (field === field)) { _fields.push(_.valueAt(table_fields, field)); } else { throw new Error('DataTableOption (#' + thisId + ') field not found: ' + fields[i]); } } } } _.each(_fields, function (field) { _.extend(self.fields[field], options); }); return this; }; DataTable.prototype.source = function (source) { this.options.source = source; return this; }; /** * * @param {bool} is_server_side */ DataTable.prototype.serverSide = function (is_server_side) { return this.option({ serverSide: Boolean(is_server_side || _.isUndefined(is_server_side)) }); }; /** * Set table sort by THIS column * @param column * @param dir */ DataTable.prototype.sortBy = function (column, dir) { this.options.sortOptions = [[column, getSortDir(dir)]]; }; DataTable.prototype.addTool = function (option) { make_dtw_tool_column(this); this.tool_column.addTool(option); return this; }; DataTable.prototype.addTools = function () { var self = this; make_dtw_tool_column(this); _.each(_.toArray(arguments), function (option) { self.tool_column.addTool(option); }); return this; }; DataTable.prototype.getAPI = function () { return this.api; }; DataTable.prototype.getSelectedRows = function () { return this.getAPI().rows({selected: true}).data(); }; DataTable.prototype.selectAll = function () { $('#' + this.check_all_checkbox_name).prop('checked', true).attr('checked', 'checked').change(); this.getAPI().rows().select(); }; DataTable.prototype.deselectAll = function () { $('#' + this.check_all_checkbox_name).prop('checked', false).removeAttr('checked').change(); this.getAPI().rows().deselect(); }; DataTable.prototype.reload = function (callback, reset_paging) { var api = this.getAPI(); if (api) { api.ajax.reload.apply(api.ajax, _.toArray(arguments)); } }; DataTable.prototype.getAPIContainer = function () { var api = this.getAPI(); if (api) { return $(api.table().container()); } return false; }; /** * Add button group holder * @param {string|number} [group_name] * @returns {*|jQuery|HTMLElement} */ DataTable.prototype.addButtonGroupHolder = function (group_name) { group_name = group_name || this.button_groups_count++; var group = $('<div class="btn-group btn-group-holder-' + group_name + '"></div>'); this.getAPIContainer().find(this.options.tableToolbarSelector).append(group); return group; }; DataTable.prototype.addButtonGroup = function (group_name, buttons) { group_name = group_name || this.button_groups_count++; buttons = _.castArray(buttons); new $.fn.dataTable.Buttons(this.getAPI(), { name: group_name, buttons: buttons }); var group_holder = this.addButtonGroupHolder(group_name); this.getAPI().buttons(group_name, null).containers().appendTo(group_holder); }; DataTable.prototype.addButtons = function (buttons, group_name) { buttons = _.castArray(buttons); group_name = group_name || 0; var api = this.getAPI(); _.each(buttons, function (button) { api.button().add(group_name, button); }); }; DataTable.prototype.getButton = function (buttonSelect, group) { return this.getAPI().button(group, buttonSelect); }; function renderHandler(component) { var options = component.getOptions(); return ['<table class="', _.castArray(options.classes).join(' '), '" id="', component.id, '">', '</table>'].join(''); } /** * * @param {{}} detail * @returns {*} */ function configField(detail) { if (!_.isObject(detail)) { detail = { title: detail.toString() } } detail = _.extend({}, default_field_options, detail); return detail; } /** * @param dir * @returns {string} */ function getSortDir(dir) { if (_.isUndefined(dir) || -1 === ['asc', 'desc'].indexOf(String(dir).toLowerCase())) { dir = 'asc'; } return String(dir).toLowerCase(); } function make_dtw_tool_column(component) { if (component.tool_column) { return; } component.tool_column = new DataTableToolColumn({ column_name: component.options.toolsColumnName, column_title: component.options.toolsTitle }); component.tool_column.attachTo(component); } function exportData(component) { var result = {}, self = component, columns = [], column_names = [], current_setting, options; if (self.options.useSelectCheckbox) { addSelectCheckbox(component); } _.each(self.fields, function (field, name) { field.name = name; columns.push(_.clone(field)); }); if (self.tool_column) { columns.push(_.clone(self.tool_column.export())); } if (!_.isEmpty(columns)) { result['columns'] = columns; column_names = _.map(columns, 'name'); } current_setting = component.getOptions(); options = _.omit(current_setting, 'source', 'useSelectCheckbox', 'sortOptions'); /** * Get order column */ if (!options.hasOwnProperty('order') && !_.isEmpty(current_setting.sortOptions)) { options.order = getSortOptions(current_setting.sortOptions, column_names); } if (current_setting.useSelectCheckbox && _.isEmpty(options.order)) { options.order = [[1, 'asc']]; } if (!_.isEmpty(current_setting.source)) { if (_.isArray(current_setting.source)) { options.data = current_setting.source; } else if (_.isString(current_setting.source) || _.isObject(current_setting.source)) { if (_.isString(current_setting.source)) { current_setting.source = { url: current_setting.source, type: 'GET' } } else { _.defaults(current_setting.source, { url: '', type: 'GET' }); } options.ajax = current_setting.source; options.serverSide = current_setting.serverSide; } else { throw new Error('DataTableOption (#' + self.id + ') invalid source'); } } var buttons = _.clone(options.buttons); _.defaults(result, options); result.buttons = buttons; return _.clone(result); } function addSelectCheckbox(component) { component.check_all_checkbox_name = _.uniqueId('check_all_checkbox_name_', true); var select_all_waiter_key, check_all_column = {}; select_all_waiter_key = Waiter.createFunc(function () { component.is_select_all_rows = $('#' + component.check_all_checkbox_name).is(':checked'); if (component.is_select_all_rows) { component.getAPI().rows().select(); } else { component.getAPI().rows().deselect(); } }, false); check_all_column[component.check_all_checkbox_name] = configField({ title: '<input type="checkbox" id="' + component.check_all_checkbox_name + '" class="i-blue-square check-all-devices" onchange="' + select_all_waiter_key + '()"/>', name: component.check_all_checkbox_name, className: 'select-checkbox i-blue-square', orderable: false, searchable: false }); component.fields = _.extend({}, check_all_column, component.fields); component.option({ select: { style: 'multi', selector: 'td:first-child' } }); component.configFields(component.check_all_checkbox_name, { width: "40px" }); } function getSortOptions(sortOptions, columns) { var orders = []; _.each(sortOptions, function (detail) { var index; if (_.isString(detail[0])) { index = columns.indexOf(detail[0]); if (-1 == index) { throw new Error('Sort by a non-exists column'); } } else { if (detail[0] < 0 || detail[0] >= columns.length) { throw new Error('Invalid sort column index'); } } orders.push([index, detail[1]]); }); return orders; } function destroy(component) { if (component.api) { component.api.destroy(); } } /** * @return {*} */ DataTable.prototype.exportOption = function () { return exportData(this); }; /** * * @param name * @param options */ DataTable.getButton = function (name, options) { if (!DataTable.Buttons.hasOwnProperty(name)) { throw new Error('DataTable button not found: ' + name); } return _.extend({}, DataTable.Buttons[name], options || {}); }; (function () { DataTable.Buttons.reload = { name: 'reload', text: function (dt) { return '<i class="fa fa-refresh"></i>'; }, action: function (event, api, dom, config) { var page_info = api.page.info(); if (page_info.serverSide) { api.ajax.reload(); } else { api.draw(false); } } } })(); (function () { function handler(api, component) { var current_options = component.getOptions(), search_setting = current_options.hasOwnProperty('search') ? current_options.search : {}; if (_.isString(search_setting)) { search_setting = { search: search_setting }; } search_setting.search = api.search(); component.option({ search: search_setting }); component.serverSide(false); component.reRender(); } DataTable.Buttons.load_all = { name: 'load_all', text: '<i class="fa fa-cloud-download"></i><span class="sr-only">Load all pages</span>', available: function (api) { var page_info = api.page.info(); return page_info.serverSide; }, action: function (event, api, node, config) { var page_info = api.page.info(), dataTable = config.dataTable; if (page_info.length * page_info.pages > 150) { swal({ title: 'Load all of pages', text: 'Do you want to load all of <strong class="text-danger">' + page_info.pages + '</strong> pages?', type: "warning", html: true, showCancelButton: true, confirmButtonColor: "#DD6B55", confirmButtonText: "Yes", closeOnConfirm: false }, function () { swal.close(); handler(api, dataTable); }); } else { handler(api, dataTable); } }, dataTable: null }; })(); /** * * @param options * @constructor * @example * var new_tool = new DataTableToolColumn({ * column_name: 'tool2', * column_title: 'Toool' * }); * * new_tool.attachTo(dataTable); * new_tool.addTool(DataTableToolColumn.rowActionViewLink()) * .addTool(DataTableToolColumn.rowActionDeleteButton(deleteDevice)); * deviceTable.addField(new_tool.export()); */ function DataTableToolColumn(options) { /** * * @type {DataTable} */ this.component = null; this.tools = {}; this.options = _.extend({ column_name: 'tools', column_title: 'Actions' }, options || {}); var self = this; this.handle_tool_key = Waiter.createFunc(function () { self.handleTool.apply(self, _.toArray(arguments)); }, false); } DataTableToolColumn.prototype.attachTo = function (dtw) { this.component = dtw; }; DataTableToolColumn.prototype.addTool = function (option) { _.defaults(option, { name: '', title: null, label: null, icon: '', type: 'info', showLabel: false, showTitle: true, active: true, handler: null, render: null, link: null, link_target: '_self', group: 1 }); if (!option.name) { option.name = _.uniqueId('datatable_tool_', true); } // option.active = true; this.tools[option.name] = option; return this; }; DataTableToolColumn.prototype.addTools = function () { var self = this; _.each(_.toArray(arguments), function (option) { self.addTool(option); }); return this; }; DataTableToolColumn.prototype.handleTool = function (name, row) { if (!this.tools.hasOwnProperty(name)) { alert('Tool not found: #' + this.id + '/' + name); return false; } if (this.tools[name].hasOwnProperty('handler') && _.isFunction(this.tools[name]['handler'])) { this.tools[name].handler(this.component.getAPI().row(row).data(), row, this); } return true; }; DataTableToolColumn.prototype.export = function () { if (!this.component) { throw new Error('This tool column does not attach to any DataTable component'); } var column = configField({ name: this.options.column_name, title: this.options.column_title, orderable: false, searchable: false, data: null }); column.render = this.renderHandler.bind(this); return column; }; DataTableToolColumn.prototype.renderHandler = function (data, type, row, meta) { var self = this; var button_groups = {}; var toolbar = ['<div class="btn-toolbar" role="toolbar">']; _.each(self.tools, function (tool_option, tool_name) { var active = tool_option.active; if (_.isFunction(active)) { active = active(data, row, meta); } if (active) { if (!button_groups.hasOwnProperty(tool_option.group)) { button_groups[tool_option.group] = []; } button_groups[tool_option.group].push((tool_option.render || default_tool_render)(self, tool_name, tool_option, row, meta)); } }); _.each(button_groups, function (buttons) { toolbar.push('<div class="btn-group btn-group-xs">' + buttons.join('') + '</div>'); }); toolbar.push('</div>'); return toolbar.join(''); }; function default_tool_render(tool_obj, name, options, row, meta) { var button = ['<a']; if (_.isFunction(options.handler)) { button.push([' onclick="', tool_obj.handle_tool_key, "('", name, "', ", meta.row, ')"'].join('')); } else { var link = options.link; if (_.isFunction(link)) { link = options.link(row); } button.push([' href="', link, '" target="', options.link_target, '"'].join('')); } button.push([' class="btn btn-', options.type, '"'].join('')); if (options.showTitle && options.title) { button.push([' title="', options.title, '"'].join('')); } button.push('>'); if (options.icon) { button.push(['<i class="', options.icon, '"></i>'].join('')); } if (options.showLabel && (options.label || options.title)) { button.push(options.label || options.title); } button.push('</a>'); return button.join(''); } DataTableToolColumn.toolButtonCreator = function (btn_options, custom_options, callback, as_link) { if (!_.isObject(custom_options)) { custom_options = {}; } return _.extend({}, btn_options, custom_options, callback ? (_.isString(callback) || as_link ? {link: callback} : {handler: callback}) : {}); }; DataTableToolColumn.rowActionViewButton = function (callback, option) { return this.toolButtonCreator({ name: 'view', title: 'View', icon: 'fa fa-fw fa-eye', active: function (data, row) { return !_.isEmpty(row.resource_url) && !_.isEmpty(row.resource_url.show); } }, option, callback, false); }; DataTableToolColumn.rowActionViewLink = function (link_creator, option) { return this.toolButtonCreator({ name: 'view', title: 'View', icon: 'fa fa-fw fa-eye', active: function (data, row) { return !_.isEmpty(row.resource_url) && !_.isEmpty(row.resource_url.show); }, link: function (row) { return row.resource_url.show; } }, option, link_creator, true); }; DataTableToolColumn.rowActionEditButton = function (callback, option) { return this.toolButtonCreator({ name: 'edit', title: 'Edit', icon: 'fa fa-pencil', type: 'warning', active: function (data, row) { return !_.isEmpty(row.resource_url) && !_.isEmpty(row.resource_url.edit) && !_.isEmpty(row.resource_url.update); } }, option, callback, false); }; DataTableToolColumn.rowActionEditLink = function (link_creator, option) { return this.toolButtonCreator({ name: 'edit', title: 'Edit', icon: 'fa fa-fw fa-pencil', type: 'warning', active: function (data, row) { return !_.isEmpty(row.resource_url) && !_.isEmpty(row.resource_url.edit) && !_.isEmpty(row.resource_url.update); }, link: function (row) { return row.resource_url.edit; } }, option, link_creator, true); }; DataTableToolColumn.rowActionDeleteButton = function (callback, option) { return this.toolButtonCreator({ name: 'delete', title: 'Delete', icon: 'fa fa-fw fa-trash-o', type: 'danger', active: function (data, row) { return !_.isEmpty(row.resource_url) && !_.isEmpty(row.resource_url.destroy); } }, option, callback, false); }; DataTableToolColumn.rowActionDeleteLink = function (link_creator, option) { return this.toolButtonCreator({ name: 'delete', title: 'Delete', icon: 'fa fa-fw fa-trash-o', type: 'danger', active: function (data, row) { return !_.isEmpty(row.resource_url) && !_.isEmpty(row.resource_url.destroy); }, link: function (row) { return row.resource_url.destroy; } }, option, link_creator, true); }; events.rendered = function () { var component = this; var dom = this.getContainer(); var export_data = exportData(this); if (_.isEmpty(export_data.columns)) { throw new Error('DataTable component has no columns defined'); } dom.on('preXhr.dt', function (event, setting) { //abort old AJAX request if (setting.jqXHR) { setting.jqXHR.abort(); } }); dom.on('init.dt', function () { // component.getButton('reload:name').node().appendTo(component.addButtonGroupHolder()); var right_buttons = []; right_buttons.push({ text: '<i class="fa fa-search"></i>', className: 'btn-info btn-flat text-white visible-xs-block', action: function () { var api = component.getAPI(); swal({ title: "Search", type: "input", inputValue: api.search(), showCancelButton: true, closeOnConfirm: false, animation: "slide-from-top" }, function (inputValue) { if (inputValue === false) return false; if (!_.isEmpty(inputValue)) { api.search(inputValue + '').draw(); } swal.close(); }); } }); right_buttons.push(DataTable.getButton('reload', { className: 'btn-flat btn-primary text-white' })); right_buttons.push(DataTable.getButton('load_all', { className: 'btn-flat btn-primary text-white', dataTable: component })); component.addButtonGroup('right', right_buttons); }); this.api = dom.DataTable(export_data); if (this.options.useSelectCheckbox) { this.api.on('draw', function () { if (this.is_select_all_rows) { this.api.rows().select(); } }.bind(this)); } if (_.isFunction(export_data.ajaxComplete)) { this.api.on('xhr', function () { var json = this.api.ajax.json(); export_data.ajaxComplete.apply(null, [json]); }.bind(this)); } if (export_data.autoAlertError) { this.api.on('xhr', function () { /** * @type {{}} */ var json = this.api.ajax.json(); if (json && json.hasOwnProperty('meta') && json.meta.hasOwnProperty('error')) { /** * @TODO: Apply dialog alert here */ alert(json.meta.error); } }.bind(this)); } }; events.before_re_render = function () { destroy(this); }; events.before_remove = function () { destroy(this); }; function init(component) { _.each(events, function (cb, name) { component.on(name, cb); }); } Component.register('DataTable', DataTable); window.DataTable = DataTable; window.DataTableToolColumn = DataTableToolColumn; })();
import 'intl' import * as React from 'react' import {render as rtlRender, screen} from '@testing-library/react' import {IntlProvider, FormattedDate} from 'react-intl' const FormatDateView = () => { return ( <div data-testid="date-display"> <FormattedDate value="2019-03-11" timeZone="utc" day="2-digit" month="2-digit" year="numeric" /> </div> ) } function render(ui, options) { function Wrapper({children}) { return <IntlProvider locale="pt">{children}</IntlProvider> } return { ...rtlRender(ui, {wrapper: Wrapper, ...options}), } } // this should work, but for some reason it's not able to load the locale // even though we have the IntlPolyfill installed // I promise it is. Just try console.log(global.IntlPolyfill) test('it should render FormattedDate and have a formated pt date', () => { render(<FormatDateView />) expect(screen.getByTestId('date-display')).toHaveTextContent('11/03/2019') })
export const LOGIN_USER = 'LOGIN_USER'; export const LOGOUT_USER = 'LOGOUT_USER'; export const FETCH_ME = 'FETCH_ME'; export const FETCH_USER = 'FETCH_USER'; export const CHANGE_STATUS = 'CHANGE_STATUS'; export const FETCH_BIRTHDAY_USERS = 'FETCH_BIRTHDAY_USERS'; export const SEARCH_USER_BY_FULL_NAME = 'SEARCH_USER_BY_FULL_NAME'; export const CURRENT_USER = 'CURRENT_USER'; export const FETCH_WORK_PLACE = 'FETCH_WORK_PLACE'; export const FETCH_WORK_PLACE_LIST_BY_FLOOR = 'FETCH_WORK_PLACE_LIST_BY_FLOOR'; export const RESERVE_WORK_PLACE = 'RESERVE_WORK_PLACE'; export const SEARCH_WORK_PLACE_BY_USER_ID = 'SEARCH_WORK_PLACE_BY_USER_ID'; export const SEARCH_WORK_PLACE_BY_PROPERTIES = 'SEARCH_WORK_PLACE_BY_PROPERTIES'; export const FETCH_PARKING = 'FETCH_PARKING'; export const FETCH_PARKING_LIST = 'FETCH_PARKING_LIST'; export const RESERVE_PARKING = 'RESERVE_PARKING';
import React, {Component} from 'react'; import {Tabs, Tab, Grid, Cell} from 'react-mdl'; import {Content} from 'react-mdl'; import {projectListData} from '../../Utilities/projectListData'; import ProjectList from './projectList'; class Projects extends Component{ constructor(props){ super(props); this.state={activeTab:7}; } toggleCategories(){ if(this.state.activeTab===7){ return( <div> <Content> <ProjectList projectListData={projectListData} activeTab={1} /> <ProjectList projectListData={projectListData} activeTab={2} /> <ProjectList projectListData={projectListData} activeTab={7} /> <ProjectList projectListData={projectListData} activeTab={3} /> <ProjectList projectListData={projectListData} activeTab={5} /> <ProjectList projectListData={projectListData} activeTab={4} /> <ProjectList projectListData={projectListData} activeTab={6} /> </Content> </div> ) } else{ return( <div> <Content> <ProjectList projectListData={projectListData} activeTab={this.state.activeTab+1} /> </Content> </div> ) } } render(){ return( <div> <Tabs activeTab={this.state.activeTab} onChange={(tabId)=>this.setState({activeTab:tabId})} ripple> <Tab><b>React</b></Tab> <Tab><b>ASP.NET</b></Tab> <Tab><b>Android</b></Tab> <Tab><b>Python</b></Tab> <Tab><b>Java</b></Tab> <Tab><b>Access</b></Tab> <Tab><b>Testing</b></Tab> <Tab><b>All</b></Tab> </Tabs> <section> <Grid> <Cell col={12}> <div className="content">{this.toggleCategories()}</div> </Cell> </Grid> </section> </div> ) } } export default Projects;
var LayoutSlot = function (top, left, width, height) { this.top = 0, this.left = 0, this.width = 0, this.height = 0, "undefined" != typeof top && (this.top = top), "undefined" != typeof left && (this.left = left), "undefined" != typeof width && (this.width = width), "undefined" != typeof height && (this.height = height); }; var Layout = function (name, width, height, length, slots, aspectRatio, ws) { this.name = "Unnamed", this.width = 0, this.height = 0, this.length = 0, this.slots = [], this.aspectRatio = 4 / 3, this.ws = false, "undefined" != typeof name && (this.name = name), "undefined" != typeof width && (this.width = width), "undefined" != typeof height && (this.height = height), "undefined" != typeof length && (this.length = length), "undefined" != typeof slots && (this.slots = slots), "undefined" != typeof aspectRatio && (this.aspectRatio = aspectRatio), "undefined" != typeof ws && (this.ws = ws); }; (function ($) { var layouts = []; layouts.push(new Layout("1 Camera Layout", 1, 1, 1, [new LayoutSlot(0, 0, 1, 1)], 4 / 3, !1)); layouts.push(new Layout("4 Camera Layout", 4, 4, 4, [new LayoutSlot(0, 0, 2, 2), new LayoutSlot(0, 2, 2, 2), new LayoutSlot(2, 0, 2, 2), new LayoutSlot(2, 2, 2, 2)], 4 / 3, !1)); layouts.push(new Layout("9 Camera Layout", 3, 3, 9, [new LayoutSlot(0, 0, 1, 1), new LayoutSlot(0, 1, 1, 1), new LayoutSlot(0, 2, 1, 1), new LayoutSlot(1, 0, 1, 1), new LayoutSlot(1, 1, 1, 1), new LayoutSlot(1, 2, 1, 1), new LayoutSlot(2, 0, 1, 1), new LayoutSlot(2, 1, 1, 1), new LayoutSlot(2, 2, 1, 1)], 4 / 3, !1)); layouts.push(new Layout("7 Camera Layout", 4, 4, 7, [new LayoutSlot(0, 0, 2, 2), new LayoutSlot(0, 2, 2, 2), new LayoutSlot(2, 0, 2, 2), new LayoutSlot(2, 2, 1, 1), new LayoutSlot(2, 3, 1, 1), new LayoutSlot(3, 2, 1, 1), new LayoutSlot(3, 3, 1, 1)], 4 / 3, !1)); layouts.push(new Layout("8 Camera Layout", 4, 4, 8, [new LayoutSlot(0, 0, 3, 3), new LayoutSlot(0, 3, 1, 1), new LayoutSlot(1, 3, 1, 1), new LayoutSlot(2, 3, 1, 1), new LayoutSlot(3, 0, 1, 1), new LayoutSlot(3, 1, 1, 1), new LayoutSlot(3, 2, 1, 1), new LayoutSlot(3, 3, 1, 1)], 4 / 3, !1)); var uuid = new Date().getTime(); $.fn.salvoViews = function (newLayouts, options) { if (!newLayouts) { newLayouts = []; } var allLayouts = $.merge($.merge([], layouts), newLayouts); return this.each(function () { uuid += 1; var viewContainer = $(this); var viewElems = $('<div id="viewer-menu">\ <div class="dropdown">\ <button type="button" class="btn btn-default dropdown-toggle" id="layout-menu"\ data-toggle="dropdown">\ <span data-bind="label" id="layout-icon"></span>&nbsp;\ <span id="layout-icon-text">View Layout</span>&nbsp;&nbsp;\ <span class="caret"></span>\ </button>\ <div class="dropdown-menu dropdown-menu-right" aria-labelledby="layout-menu">\ <div class="btn-group" role="group" aria-label="View Layout" id="' + uuid + '-layout-group"></div>\ </div>\ </div>\ </div>') .appendTo(viewContainer); var panelContainer = $('<div />') .attr({ id : uuid, class : 'layout-container' }) .insertAfter(viewElems); panelContainer.salvoLayout(newLayouts, options); var instId = panelContainer.prop('id'); var createSVGbutton = function (layout) { var svgElement = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); $(svgElement).width(30); $(svgElement).height(30); var widthRatio = 30 / layout.width; var heightRatio = 30 / layout.height; $.each(layout.slots, function (index, value) { var svgRect = document.createElementNS('http://www.w3.org/2000/svg', 'rect'); $(svgRect).attr({ x : (value.left * widthRatio), y : (value.top * heightRatio), width : (value.width * widthRatio), height : (value.height * heightRatio) }); $(svgElement).append($(svgRect)); $(svgRect).attr({ fill : 'white', stroke : 'black' }); }); return svgElement; }; var createLayoutMenu = function () { var layoutGroup = $('#' + instId + '-layout-group'); layoutGroup.empty(); $.each(allLayouts, function (index, value) { var layoutBtn = $('<button type="button" class="btn btn-layout"></button>'); layoutBtn.prop('id', instId + 'layout' + value.length); layoutBtn.prop('data-layoutId', value.length); layoutBtn.on('click', btnLayoutClick); layoutGroup.append(layoutBtn); var layoutDetail = $('<div class="layout-detail"></div>') .appendTo(layoutBtn); layoutDetail.append($(createSVGbutton(value))); }); }; var switchLayout = function (layoutId) { var layout = $.grep(allLayouts, function (element) { return element.length === layoutId; }); var eventName = "switchLayoutEvent"; panelContainer.trigger(eventName, [layout[0]]); }; var switchToDefaultLayout = function () { var defaultLayout = $('#' + instId + 'layout1'); defaultLayout.closest('.dropdown') .find('[data-bind="label"]') .empty() .append(defaultLayout.find('.layout-detail').clone()); switchLayout(1); }; var btnLayoutClick = function (e) { var tar = $(e.currentTarget); tar.closest('.dropdown') .find('[data-bind="label"]') .empty() .append(tar.find('.layout-detail').clone()) .end() .find('.dropdown-toggle') .dropdown('toggle'); var layoutId = tar.prop("data-layoutId"); switchLayout(layoutId); return false; }; createLayoutMenu(); switchToDefaultLayout(); }); }; $.fn.salvoLayout = function (options) { return this.each(function () { var container = $(this); var instId = container.prop('id'); var selectPanel = function (e) { var tar = $(e.currentTarget); tar.parent().children().each(function (index, value) { $(value).prop('style').removeProperty('outline') }); tar.css('outline', '2px solid black'); }; var defaults = { onPanelClicked : null, onPanelHovered : selectPanel, onPanelCreated : function () {}, panelAttrs : { ondrop : "drop(event)", ondragover : "allowDrop(event)", class : "default-salvo-panel" }, playerBoxAttrs : { class : 'jwplayerBox', } }; var settings = $.extend({}, defaults, options); var currentLayout; var calculateDimensionsForLayout = function (layout) { var availableHeight = container.height(); var availableWidth = container.width(); var height = availableHeight; var width = availableWidth; //width / layout.width / layout.aspectRatio > height / layout.height ? width = height / layout.height * layout.aspectRatio * layout.width : height = width / layout.width / layout.aspectRatio * layout.height; var slotHeight = height / layout.height; var slotWidth = width / layout.width; return { availableHeight : availableHeight, availableWidth : availableWidth, height : Math.round(height), width : Math.round(width), slotHeight : Math.round(slotHeight), slotWidth : Math.round(slotWidth), aspectRatio : layout.aspectRatio }; }; var panelDimensionsForLayout = function (layout) { var dimensions = calculateDimensionsForLayout(layout); var topOffset = (dimensions.availableHeight - dimensions.height) / 2; var panelDimensions = $.map(layout.slots, function (element) { var height = element.height * dimensions.slotHeight; var width = element.width * dimensions.slotWidth; var top = topOffset + element.top * dimensions.slotHeight; var left = element.left * dimensions.slotWidth; return { height : Math.round(height), width : Math.round(width), top : Math.round(top), left : Math.round(left) }; }); return panelDimensions; }; var setPanelEvents = function (panel) { if (settings.onPanelClicked) { panel.on('click', settings.onPanelClicked); } if (settings.onPanelHovered) { panel.on('mouseover', settings.onPanelHovered); } }; var createLayout = function (length) { var panels = container.children(); var start = 0; if (panels.length) { var delta = panels.length - length; if (delta > 0) { for (var i = length; i < panels.length; i++) { $(panels[i]).remove(); } return; } else { start = panels.length; } } for (var j = start; j < length; j++) { var panel = $("<div />") .prop('id', instId + 'playerid' + j) .attr(settings.panelAttrs) .appendTo(container); var playerBox = $("<div />") .attr(settings.playerBoxAttrs) .prop('id', instId + 'jwplayer' + j) .appendTo(panel); setPanelEvents(panel); } }; var getPanelById = function (panelId) { var panels = container.children(); if (panels.length && panelId < panels.length) { return panels[panelId]; } return -1; }; var onShowPanel = function (panelId, newHeight, newWidth, newTop, newLeft) { var panel = getPanelById(panelId); $(panel).css('top', newTop.toString() + "px"); $(panel).css('left', newLeft.toString() + "px"); $(panel).height(newHeight - 1); $(panel).width(newWidth - 1); }; var resizeContainer = function () { var i, panelDimensions = panelDimensionsForLayout(currentLayout); for (i = 0; i < panelDimensions.length; i++) { onShowPanel(i, panelDimensions[i].height, panelDimensions[i].width, panelDimensions[i].top, panelDimensions[i].left); } }; var switchLayout = function (layout) { currentLayout = layout; createLayout(layout.length); resizeContainer(); }; $(window).resize(resizeContainer); var eventName = "switchLayoutEvent"; container.on(eventName, function (event, arg1) { switchLayout(arg1); }); }); }; }(jQuery));
export const cities = [ { id: 1, city: 'Swampscott', humidity: 0.50 }, { id: 2, city: 'Marblehead', humidity: 0.55 }, { id: 3, city: 'Boston', humidity: 1.0 }, { id: 4, city: 'Woburn', humidity: 0.25 } ]
const sql = require('../db') const errorHandler = require('./helper') const Task = function (task) { this.id = task.id || null; this.name = task.name; this.description = task.description; this.workerId = task.workerId; this.groupId = task.groupId; } Task.create = (task, callback) => { sql.query( `INSERT INTO tasks VALUES (name, description, worker_id, group_id) VALUES (?,?,?,?)`, [ task.name, task.description, task.worker, task.groupId ], (err, data) => { if (errorHandler(err, callback)) return; console.log("Created task: " + { ...task, id: data.insertId }); callback(null, data); } ) } Task.update = (updatedTask, callback) => { sql.query( `UPDATE SET name=?, description=?, worker_id=?, group_id=? WHERE id=?`, [ updatedTask.name, updatedTask.description, updatedTask.workerId, updatedTask.groupId ], (err, data) => { if (errorHandler(err, callback)) return; console.log("Updated task: " + updatedTask); callback(null, data); } ) } Task.delete = (id, callback) => { sql.query( `DELETE FROM tasks WHERE id=?`, id, (err, data) => { if (errorHandler(err, callback)) return; console.log("Deleted task: " + id); callback(null, data); } ) } Task.findByGroup = (groupId, callback) => { sql.query( `SELECT * FROM tasks WHERE group_id=?`, groupId, (err, data) => { if (errorHandler(err, callback)) return; callback(null, data); } ) } Task.findByWorker = (workerId, callback) => { sql.query( `SELECT * FROM tasks WHERE worker_id=?`, workerId, (err, data) => { if (errorHandler(err, callback)) return; callback(null, data); } ) }
import { GraphQLNonNull, GraphQLInt, GraphQLError } from 'graphql' import DeleteUserType from './types' import {connect} from '../../connection' export default{ type:DeleteUserType, args:{ id:{ type:GraphQLNonNull(GraphQLInt) } }, async resolve(parentValue,args){ try{ const result = await connect('users').where('id',args.id).del() return result }catch(err){ throw new GraphQLError(err) } } }
import React from "react"; import { Link } from "react-router-dom"; import logo from "./logo.png"; import DrawerToggleButton from "../sideDrawer/drawerToggleButton"; const Header = props => ( <header className="toolbar_wrapper"> <div className="toolbar"> <nav className="toolbar_navigation"> <div className="toolbar_toggle-button"> <DrawerToggleButton click={props.drawerClickHandler} /> </div> <div className="toolbar_logo"> <Link to="/"> <img src={logo} alt="" width="120px" height="64px" /> </Link> </div> <div className="spacer" /> <div className="toolbar_navigation-items"> <ul> <li> <Link to="/">Home</Link> </li> <li> <Link to="/mirai">Mirai</Link> </li> <li> <Link to="/hydrogenFuel">Hydrogen Fuel</Link> </li> <li> <Link to="/about">About</Link> </li> </ul> </div> </nav> </div> </header> ); export default Header;
var express = require('express'); var mongoose = require('mongoose'); var config = require('config'); var path = require('path'); var passport = require('passport'); var BasicStrategy = require('passport-http').BasicStrategy; var bodyParser = require('body-parser'); var User = require('./models/user'); var app = express(); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); /** * Configure passport with http basic auth strategy */ passport.serializeUser(function(user, done) { done(null, user._id); }); passport.deserializeUser(function(id, done) { User.findById(id, function(err, user) { done(err, user); }); }); passport.use(new BasicStrategy( function(username, password, done) { User.findOne({ username: username }, function(err, user) { if (err) { return done(err); } else if (!user) { return done(undefined, false); } else { user.verifyPassword(password, function(err, valid) { if (!valid) { return done(undefined, false); } else { return done(undefined, user); } }) } }); } )); // Get routers and create API routes. const BASE_URL = '/api/:version/'; app.use(path.join(BASE_URL, 'user'), require('./routes/user')); app.use(path.join(BASE_URL, 'giphy'), require('./routes/giphy')); mongoose.connect(process.env.MONGOLAB_URI || config.get('db.uri'), function(err) { if (err) { throw new Error(err); // Fail fast if we can't connnect to MongoDB } else { var server = app.listen(process.env.PORT || config.get('port'), function() { console.log('hello-giphy is listening on port', server.address().port) }); } }); // Export the express app so we can use it for testing module.exports = app;
/** * Created at 17/6/22. * @Author Thunder King Star. * @Email 332793511@qq.com */ import { combineReducers } from 'redux' import counter from './counter' export default combineReducers({ counter })
document.addEventListener("DOMContentLoaded", () => { //prevent "Confirm Form Resubmission" dialog boxes if (window.history.replaceState) { window.history.replaceState(null, null, window.location.href); } //search-bar // TODO ajax const searchForm = document.querySelector("#search-form"); const userInput = document.querySelector("#search-bar"); searchForm.addEventListener("submit", () => { event.preventDefault(); window.location.href = `/user/${userInput.value}`; }); });
$(document).ready(function(){ $(document).foundation('equalizer', 'reflow'); $(document).foundation({ equalizer : { // Specify if Equalizer should make elements equal height once they become stacked. equalize_on_stack: true, // Allow equalizer to resize hidden elements act_on_hidden_el: false } }); });
import React, {Component} from 'react'; import {View, Text, TouchableOpacity} from 'react-native'; export default class Header extends Component{ render(){ return( <View style={{ flexDirection: 'row' }}> <TouchableOpacity style={{marginRight:310, marginLeft:10}} onPress={this.toggleDrawer.bind(this)}> <Icon name="ios-menu" size={36} /> </TouchableOpacity> <TouchableOpacity onPress={()=>{alert("ok day");}}> <Icon name="ios-contact" size={36} /> </TouchableOpacity> </View> ); } }
import Vue from 'vue' import iView from 'iview' //引入iview库 import 'iview/dist/styles/iview.css' //使用css Vue.use(iView)
import { ADD_MESSAGE, CLEAR_MESSAGES, DELETE_MESSAGE, } from "../constants/index"; const intialState = []; function messageReducers(state = intialState, action) { switch (action.type) { case ADD_MESSAGE: return [...state.slice(), action.payload]; case CLEAR_MESSAGES: return []; case DELETE_MESSAGE: state.splice(action.payload, 1); return [...state]; default: return state; } } export default messageReducers;
import { Well, Table, Panel, Col, Row } from 'react-bootstrap'; import React from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { getAllUsers } from '../actions/usersActions'; import { updateOneTick } from '../actions/graphActions'; import UserGenerateButton from './userGenerateButton'; import d3 from 'd3'; import '../../public/stylesheets/c3.min.css'; class C3UserDonut extends React.Component { componentWillReceiveProps(nextProps) { console.log(nextProps); let free = nextProps.latest[0].membership_eq_FREE; let enterprise = nextProps.latest[0].membership_eq_ENTERPRISE; let pro = nextProps.latest[0].membership_eq_PRO; this.chart.load({ columns: [ ['Free', free], ['Pro', pro], ['Enterprise', enterprise] ] }) } componentDidMount() { let free = [...this.props.latest[0].membership_eq_FREE]; let enterprise = [...this.props.latest[0].membership_eq_ENTERPRISE]; let pro = [...this.props.latest[0].membership_eq_PRO]; if (window === undefined) { return null; } else { const c3 = require('c3'); var self = this; self.chart = c3.generate({ bindto: '#donut', data: { columns: [ ['Free', 120], ['Pro', 130], ['Enterprise', 300] ], type: 'donut', onclick: function (d, i) { console.log("onclick", d, i); }, onmouseover: function (d, i) { console.log("onmouseover", d, i); }, onmouseout: function (d, i) { console.log("onmouseout", d, i); } }, donut: { title: "User Payment Dist." } }); } } render() { return ( <div id="donut" /> ) } } function mapStateToProps(state) { return { latest: state.graph.latest, } } function mapDispatchToProps(dispatch) { return bindActionCreators({ updateOneTick }, dispatch) } export default connect(mapStateToProps, mapDispatchToProps)(C3UserDonut);
({ loadContactList: function(component, event, helper) { // By Default make sort field is 'FirstName' of contact object // call the helper function with pass sortField Name debugger; helper.onLoad(component, event, 'FirstName'); }, openPrimaryFromNavigationAPI: function(component, event, helper) { var contactList = component.get('v.ListOfContact'); var target = event.target; while (target && !target.dataset.index) { target = target.parentNode; } if (target) { console.log(target.dataset.index); } var index = event.target.dataset.index; console.log('index ' + index); var recordId = component.get("v.ListOfContact")[index].AccountId; helper.openSobjectPrimSubTab(component, recordId, null); console.log('even' + event); }, opensobjectTabUsingEvent: function(component, event, helper) { var index = event.target.dataset.index; console.log('index ' + index); console.log('v.ListOfContact' + component.get("v.ListOfContact")); console.log('v.ListOfContact[index]' + component.get("v.ListOfContact")[index].AccountId); var recordId = component.get("v.ListOfContact")[index].AccountId; var navEvt1 = $A.get("e.force:navigateToSObject"); navEvt1.setParams({ "recordId": recordId }); navEvt1.fire(); }, opensubTabAPI: function(component, event, helper) { var index = event.target.dataset.index; var recordId = component.get("v.ListOfContact")[index].Id; var primaryrecordId = component.get("v.ListOfContact")[index].AccountId; console.log(recordId); console.log(primaryrecordId); // opens the record in subtab debugger; helper.openSobjectPrimSubTab(component, primaryrecordId, recordId); //helper.openSobjectSubTab(component, recordId); }, })
/** * Cluster-based worker queue. * * @package rij * @author Andrew Sliwinski <andrew@diy.org> */ /** * Dependencies */ var cluster = require('cluster'), events = require('events'), util = require('util'); var Redis = require('./redis'); /** * Constructor */ function Cluster (config) { var self = this; // Event Emitter self.setMaxListeners(0); // Helpers var exit = function () { setTimeout(process.exit, 2000); }; var work = function () { var redis = new Redis(config); redis.dequeue(function (err, obj) { if (err) throw err; if (typeof obj === 'undefined' || obj === null) return exit(); require(obj.worker)(obj.job, function (err, result) { process.send(JSON.stringify({ task: obj, error: err, result: result })); process.exit(); }); }); }; // Cluster if (cluster.isWorker) work(); if (cluster.isMaster) { // Create redis client var redis = new Redis(config); // Spawn workers for (var i = 0; i < config.concurrency; i++) { cluster.fork(); } // Process 'online' handler cluster.on('online', function (worker) { worker.on('message', function (msg) { msg = JSON.parse(msg); if (msg.error === null) return self.emit('complete', msg); redis.restore(worker.process.pid, function (err) { if (err) self.emit('fatal', err); self.emit('incomplete', msg); }); }); }); // Process 'exit' handler cluster.on('exit', function (worker, code) { if (code === 0) return cluster.fork(); redis.restore(worker.process.pid, function (err) { if (err) self.emit('fatal', err); cluster.fork(); }); }); } } /** * Inherit event emitter */ util.inherits(Cluster, events.EventEmitter); /** * Export */ module.exports = Cluster;
// Copyright (c) 2016-2018, BuckyCloud, Inc. and other BDT contributors. // The BDT project is supported by the GeekChain Foundation. // All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of the BDT nor the // names of its contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. "use strict"; const EventEmitter = require('events'); const baseModule = require('../base/base'); const BaseUtil = require('../base/util'); const blog = baseModule.blog; const packageModule = require('./package'); const BDTPackage = packageModule.BDTPackage; const BDT_ERROR = packageModule.BDT_ERROR; const BDTSendBuffer = require('./send_buffer'); const assert = require('assert'); const SequenceU32 = BaseUtil.SequenceU32; const TimeHelper = BaseUtil.TimeHelper; const _DEBUG = false; let md5 = null; if (_DEBUG) { md5 = buffer => { const Crypto = require('crypto'); let md5 = Crypto.createHash('md5'); md5.update(buffer); let md5Hash = md5.digest(); return md5Hash.readUInt32BE(0); } } const AckType = { ack: 1, data: 2, finalAck: 3, }; class BDTSendQueue { constructor(transfer) { this.m_transfer = transfer; this.m_connection = transfer.connection; this.m_ackSeq = this.sentSeq; this.m_pending = []; this.m_waitResend = []; this.m_waitAck = []; this.m_maxAckSeq = this.m_ackSeq; this.m_dumpAckCounter = 0; } get sentSeq() { return SequenceU32.sub(this.m_connection._nextSeq(0), 1); } get ackSeq() { return this.m_ackSeq; } get flightSize() { if (this.m_waitAck.length > 0) { return SequenceU32.delta(this.maxWaitAckSeq, this.m_ackSeq); } return 0; } get dumpCount() { return this.m_dumpAckCounter; } get maxWaitAckSeq() { return SequenceU32.sub(this.m_waitAck[this.m_waitAck.length - 1].package.nextSeq, 1); } allocDataPackage(buffers, fin=false) { assert(this.m_waitResend.length === 0 || fin, `waitResend:${this.m_waitResend.length},waitAck:${this.m_waitAck.length}`); let encoder = null; if (!fin) { encoder = this.m_connection._createPackageHeader(BDTPackage.CMD_TYPE.data); encoder.addData(buffers); } else { encoder = this.m_connection._createPackageHeader(BDTPackage.CMD_TYPE.fin); } encoder.header.seq = this.m_connection._nextSeq(encoder.dataLength + 1); let stub = { sentTime: TimeHelper.uptimeMS(), limitAckSeq: encoder.nextSeq, // 要在limitAckSeq被确认之前ack,否则应当择机重传 sackCount: 0, // 该包后续分包被ack的数量 package: encoder, }; this.m_pending.push(stub); if (this.m_waitResend.length > 0) { this.m_waitResend.push(stub); stub.sentTime = 0; return null; } else { this.m_waitAck.push(stub); } return encoder; } onAckPackage(ackSeq, ackType) { assert(this.m_waitAck.length === 0 || SequenceU32.compare(this.m_waitAck[0].package.header.seq, SequenceU32.add(this.m_ackSeq, 1)) >= 0, `waitAck.seq:${this.m_waitAck.length? this.m_waitAck[0].package.header.seq : 0},ackSeq:${this.m_ackSeq}`); assert(this.m_waitResend.length === 0 || SequenceU32.compare(this.m_waitResend[0].package.header.seq, this.m_waitAck[0].package.header.seq) > 0, `waitAck.seq:${this.m_waitAck.length? this.m_waitAck[0].package.header.seq : 0},waitResend.seq:${this.m_waitResend.length? this.m_waitResend[0].package.header.seq : 0}`); if (SequenceU32.compare(ackSeq, this.m_ackSeq) > 0) { // 比上一个收到的小时 不更新cwnd this.m_dumpAckCounter = 1; let stubIndex = null; for (let index = 0; index < this.m_pending.length; ++index) { let stub = this.m_pending[index]; if (SequenceU32.compare(stub.package.ackSeq, ackSeq) === 0) { stubIndex = index; break; } else if (SequenceU32.compare(ackSeq, stub.package.ackSeq) < 0) { break; } } if (stubIndex == null) { // 不存在这个seq return [0, null]; } let acked = SequenceU32.delta(ackSeq, this.m_ackSeq); this.m_ackSeq = ackSeq; let stubs = this.m_pending.splice(0, stubIndex + 1); if (SequenceU32.compare(ackSeq, this.m_maxAckSeq) > 0) { this.m_maxAckSeq = ackSeq; } let removeFromUnackedQueue = unackedQueue => { if (unackedQueue.length === 0) { return; } if (SequenceU32.compare(unackedQueue[unackedQueue.length - 1].package.ackSeq, ackSeq) <= 0) { unackedQueue.splice(0, unackedQueue.length); return; } for (let i = 0; i < unackedQueue.length; i++) { if (SequenceU32.compare(unackedQueue[i].package.ackSeq, ackSeq) > 0) { unackedQueue.splice(0, i); break; } else if (SequenceU32.compare(unackedQueue[i].package.ackSeq, ackSeq) === 0) { unackedQueue.splice(0, i + 1); break; } } } removeFromUnackedQueue(this.m_waitAck); removeFromUnackedQueue(this.m_waitResend); return [acked, stubs[stubs.length - 1]]; } else if (SequenceU32.compare(ackSeq, this.m_ackSeq) === 0) { if (this.m_pending.length) { // 连续收到3个相同的专用ack包,进入快速重传状态,这里需要计数 if (ackType === AckType.ack) { ++this.m_dumpAckCounter; return [0, this.m_pending[0]]; } else if (ackType === AckType.finalAck) { // 重发ack只要对第一个包重传一下好了 return [0, this.m_pending[0]]; } return [-1, null]; } else { this.m_dumpAckCounter = 1; return [-1, null]; } } else { return [-1, null]; } } onSACK(sack) { let _doSACK = unackedQueue => { let offset = 0; let fromSeq = 0; let toSeq = 0; let sendPkgIndex = 0; // 接收端返回的sack是从小到大顺序排列的 while (true) { if (sack.length - offset < 8 || sendPkgIndex >= unackedQueue.length) { return; } fromSeq = sack.readUInt32LE(offset); toSeq = sack.readUInt32LE(offset + 4); offset += 8; let toAckSeq = SequenceU32.sub(toSeq, 1); if (SequenceU32.compare(toAckSeq, this.m_maxAckSeq) > 0) { this.m_maxAckSeq = toAckSeq; } let ackCount = 0; while (sendPkgIndex < unackedQueue.length) { let stub = unackedQueue[sendPkgIndex]; // toSeq本身不被ack if (SequenceU32.compare(stub.package.header.seq, fromSeq) >= 0 && SequenceU32.compare(stub.package.header.seq, toSeq) < 0) { unackedQueue.splice(sendPkgIndex, 1); stub.sack = true; ackCount++; } else { sendPkgIndex++; } } // 更新乱序ack的数量 for (let i = 0; i < sendPkgIndex; i++) { let stub = unackedQueue[i]; if (SequenceU32.compare(stub.limitAckSeq, toAckSeq) < 0) { stub.sackCount += ackCount; } } } } _doSACK(this.m_waitAck); _doSACK(this.m_waitResend); } resendWaitAck(timeout, onResent) { let now = TimeHelper.uptimeMS(); let count = 0; let index = 0; let isTimeout = () => { for (; index < this.m_waitAck.length; index++) { let stub = this.m_waitAck[index]; assert(stub.sentTime > 0, `sentTime:${stub.sentTime}`); let diff = now - stub.sentTime; if (diff > timeout) { return true; } } return false; } if (!isTimeout()) { return 0; } // 一个包发生超时,重建整个发送窗口 let rtoMin = this.m_connection.stack._getOptions().rtoMin; for (index = 0; index < this.m_waitAck.length; index++) { let stub = this.m_waitAck[index]; assert(stub.sentTime > 0, `sentTime:${stub.sentTime}`); let diff = now - stub.sentTime; if (diff > rtoMin) { stub.lastSentTime = stub.sentTime; stub.sentTime = now; stub.limitAckSeq = stub.package.nextSeq; stub.sackCount = 0; stub.package.header.isResend = true; this.m_transfer._postPackage(stub.package); ++count; if (!onResent(stub)) { break; } } } let firstResendIndex = index + 1; if (firstResendIndex < this.m_waitAck.length) { let newResend = this.m_waitAck.splice(firstResendIndex, this.m_waitAck.length - firstResendIndex); if (this.m_waitResend.length === 0) { this.m_waitResend = newResend; } else if (SequenceU32.compare(newResend[newResend.length - 1].package.ackSeq, this.m_waitResend[0].package.ackSeq) < 0){ this.m_waitResend.unshift(...newResend); } else { this.m_waitResend.push(...newResend); } } return count; } resendWaitResend(onResent) { if (this.m_waitResend.length === 0) { return 0; } let now = TimeHelper.uptimeMS(); let lastResendIndex = 0; for (lastResendIndex = 0; lastResendIndex < this.m_waitResend.length; lastResendIndex++) { let stub = this.m_waitResend[lastResendIndex]; stub.lastSentTime = stub.sentTime; stub.sentTime = now; stub.limitAckSeq = stub.package.nextSeq; stub.sackCount = 0; stub.package.header.isResend = stub.lastSentTime > 0; this.m_transfer._postPackage(stub.package); if (onResent(stub)) { break; } } let resentPkgs = null; if (lastResendIndex < this.m_waitResend.length) { resentPkgs = this.m_waitResend.splice(0, lastResendIndex + 1); } else { resentPkgs = this.m_waitResend; this.m_waitResend = []; } if (resentPkgs.length > 0) { this.m_waitAck.push(...resentPkgs); } return resentPkgs.length; } resendNext(forceFirst) { let _send = stub => { stub.package.header.isResend = true; stub.lastSentTime = stub.sentTime; stub.sentTime = TimeHelper.uptimeMS(); stub.limitAckSeq = SequenceU32.add(this.maxWaitAckSeq, 1); stub.sackCount = 0; this.m_transfer._postPackage(stub.package); } if (this.m_waitAck.length === 0) { return 0; } if (forceFirst) { _send(this.m_waitAck[0]); return 1; } let sentCount = 0; for (let stub of this.m_waitAck) { if (stub.sackCount < 3) { break; } if (SequenceU32.compare(stub.limitAckSeq, this.m_maxAckSeq) < 0 && stub.sackCount === 3) { _send(stub); sentCount++; } } return sentCount; } } class BDTRecvQueue { constructor(connection) { const opt = connection.stack._getOptions(); this.m_connection = connection; this.m_pending = []; this.m_lastAckSeq = 0; this.m_quickAckCount = opt.quickAckCount; this.m_lastRecvTime = TimeHelper.uptimeMS(); this.m_ato = opt.ackTimeoutMax; } get nextSeq() { return this.m_connection._getNextRemoteSeq(); } get ackSeq() { return SequenceU32.sub(this.nextSeq, 1); } get waitAckSize() { return SequenceU32.delta(this.m_connection._getNextRemoteSeq(), this.m_lastAckSeq); } get isQuickAck() { let opt = this.m_connection.stack._getOptions(); return this.m_quickAckCount > 0 ||this.m_pending.length > 0 || this.waitAckSize >= opt.ackSize; } get ato() { return this.m_ato; } allocAckPackage(windowSize) { let encoder = this.m_connection._createPackageHeader(BDTPackage.CMD_TYPE.data); this.fillAckPackage(encoder, windowSize); if (this.m_pending.length > 0) { let sackBuffer = Buffer.allocUnsafe(this.m_pending.length * 8); let offset = 0; this.m_pending.forEach(stub => { // sack区间[seq, nextSeq),被ack的范围不包括nextSeq sackBuffer.writeUInt32LE(stub.seq, offset); sackBuffer.writeUInt32LE(stub.nextSeq, offset + 4); offset += 8; }); encoder.addData([sackBuffer]); encoder.header.sack = true; } return encoder; } fillAckPackage(encoder, windowSize) { encoder.header.ackSeq = this.ackSeq; encoder.header.windowSize = windowSize; this.m_lastAckSeq = encoder.header.ackSeq; if (this.m_quickAckCount > 0) { this.m_quickAckCount--; } return encoder; } addPackage(decoder) { let header = decoder.header; let pending = this.m_pending; this._updateAto(); let assertSeq = (queue, beginSeq) => { if (queue.length === 0) { return; } let nextSeq = beginSeq || queue[0].header.seq; queue.forEach(pkg => { assert(SequenceU32.compare(pkg.header.seq, nextSeq) === 0, `nextSeq:${nextSeq},pkg.seq:${pkg.header.seq}`); nextSeq = pkg.nextSeq; }); } if (SequenceU32.compare(header.seq, this.nextSeq) === 0) { let unpend = null; if (pending.length) { let stub = pending[0]; if (SequenceU32.compare(stub.seq, decoder.nextSeq) === 0) { pending.splice(0, 1); stub.packages.unshift(decoder); unpend = stub.packages; } else { unpend = [decoder]; } } else { unpend = [decoder]; } assertSeq(unpend, this.nextSeq); this.m_connection._setNextRemoteSeq(unpend[unpend.length - 1].nextSeq); return unpend; } else if (SequenceU32.compare(header.seq, this.nextSeq) > 0) { let isCached = false; for (let index = 0; index < pending.length; ++index) { let stub = pending[index]; if (SequenceU32.compare(stub.seq, decoder.nextSeq) > 0) { pending.splice(index, 0, { seq: header.seq, nextSeq: decoder.nextSeq, packages: [decoder] }); isCached = true; break; } if (SequenceU32.compare(stub.seq, decoder.nextSeq) === 0) { stub.seq = header.seq; stub.packages.unshift(decoder); isCached = true; assertSeq(stub.packages); if (index > 0) { let preStub = pending[index - 1]; if (SequenceU32.compare(preStub.nextSeq, stub.seq) === 0) { // 应该不能运行到这里,因为在前序序列的时候就会被处理 assert(false, `cannot reach here.`); preStub.nextSeq = stub.nextSeq; preStub.packages = preStub.packages.concat(stub.packages); pending.splice(index, 1); assertSeq(preStub.packages); } } break; } if (SequenceU32.compare(stub.nextSeq, header.seq) === 0) { stub.nextSeq = decoder.nextSeq; stub.packages.push(decoder); isCached = true; assertSeq(stub.packages); if (index < pending.length - 1) { let nextStub = pending[index + 1]; const d = SequenceU32.compare(stub.nextSeq, nextStub.seq); if (d === 0) { stub.nextSeq = nextStub.nextSeq; stub.packages = stub.packages.concat(nextStub.packages); pending.splice(index + 1, 1); assertSeq(stub.packages); } else if (d > 0) { // seq有重叠,可能有恶意节点冒名发送的包 assert(false, `${d}`); pending.splice(index + 1, 1); } } break; } if (SequenceU32.compare(header.seq, stub.seq) >= 0 && SequenceU32.compare(decoder.nextSeq, stub.nextSeq) <= 0) { isCached = true; break; } } if (!isCached) { pending.push({ seq: header.seq, nextSeq: decoder.nextSeq, packages: [decoder] }); } } return null; } _updateAto() { let now = TimeHelper.uptimeMS(); let lastRecvTime = this.m_lastRecvTime; const opt = this.m_connection.stack._getOptions(); const atoMin = opt.ackTimeoutMin; const atoMax = opt.ackTimeoutMax; this.m_lastRecvTime = now; const delta = now - lastRecvTime; const halfATOMin = atoMin / 2; if (delta <= halfATOMin) { this.m_ato = this.m_ato / 2 + halfATOMin; } else if (delta <= this.m_ato) { this.m_ato = Math.min(this.m_ato / 2 + delta, atoMax); } else { // 比ack周期还长,可能是丢包或者是发送窗口满,或者进入慢启动等 this.m_quickAckCount = opt.quickAckCount; } } } class Reno { constructor(connection) { this.m_connection = connection; const opt = connection.stack._getOptions(); this.m_mms = opt.udpMMS; this.m_cwnd = opt.udpMMS; this.m_rtoMin = opt.rtoMin; this.m_rtoMax = opt.rtoMax; this.m_ssthresh = opt.initRecvWindowSize; this.m_srtt = 0; this.m_rttvar = opt.initRTTVar; this.m_rto = this.m_srtt + 4*this.m_rttvar; // 进入fastRecover前的cwnd,待ack的seq this.m_frcwnd = 0; this.m_frSeq = 0; this.m_state = Reno.STATE.slowStart; } get mms() { return this.m_mms; } get cwnd() { return this.m_cwnd; } get rto() { return this.m_rto; } get srtt() { return this.m_srtt; } onAck(ackedSize, pkgStub, sendQueue, ackPkg) { if (ackedSize > 0) { let now = TimeHelper.uptimeMS(); if (!pkgStub.package.header.isResend || now - pkgStub.lastSentTime > this.m_rto) { let rtt = now - pkgStub.sentTime; const alpha = 1/8; const beta = 1/4; const gama = 4; if (rtt <= 0) { rtt = this.m_srtt || this.m_rtoMin; } else if (rtt > this.m_rtoMax) { rtt = this.m_rtoMax; } if (this.m_srtt === 0) { this.m_srtt = rtt; this.m_rttvar = rtt / 2; } else { let srtt = this.m_srtt; let rttvar = this.m_rttvar; this.m_rttvar = beta*(Math.abs(rtt - srtt)) + (1-beta)*rttvar; this.m_srtt = Math.floor(alpha*rtt + (1-alpha)*srtt); } let rto = Math.ceil(this.m_srtt + gama*this.m_rttvar); if (rto < this.m_rtoMin) { rto = this.m_rtoMin; } else if (rto > this.m_rtoMax) { rto = this.m_rtoMax; } this.m_rto = rto; blog.debug(`[BDT]: bdt transfer(id=${this.m_connection.id}) set rto to ${rto}`); } if (this.m_state === Reno.STATE.slowStart) { const inc = Math.max(ackedSize, this.m_mms); blog.debug(`[BDT]: bdt transfer(id=${this.m_connection.id}) increase cwnd with ${inc}`); this.m_cwnd += inc; if (this.m_cwnd >= this.m_ssthresh) { blog.debug(`[BDT]: bdt transfer(id=${this.m_connection.id}) enter congestion avoid state`); this.m_state = Reno.STATE.congestionAvoid; } } else if (this.m_state === Reno.STATE.congestionAvoid) { let inc = Math.ceil(this.m_mms*this.m_mms/this.m_cwnd); this.m_cwnd += inc; blog.debug(`[BDT]: bdt transfer(id=${this.m_connection.id}) increase cwnd with ${inc}`); } else if (this.m_state === Reno.STATE.fastRecover) { // 发生fastRecover时窗口中的所有包都被ack才恢复到拥塞避免 if (SequenceU32.compare(sendQueue.ackSeq, this.m_frSeq) < 0) { if (sendQueue.resendNext() === 0) { this.m_cwnd = sendQueue.flightSize + this.m_mms; } } else { this.m_ssthresh = Math.max(Math.ceil(this.m_frcwnd/2), 2*this.m_mms); this.m_cwnd = this.m_ssthresh; this.m_state = Reno.STATE.congestionAvoid; } blog.debug(`[BDT]: bdt transfer(id=${this.m_connection.id}) set cwnd with ${this.m_cwnd} from fast recover`); } } else if (ackedSize === 0) { if (sendQueue.dumpCount >= 3) { if (sendQueue.dumpCount === 3 && this.m_state !== Reno.STATE.fastRecover) { this.m_frcwnd = this.m_cwnd; this.m_frSeq = sendQueue.maxWaitAckSeq; this.m_state = Reno.STATE.fastRecover; blog.debug(`[BDT]: bdt transfer(id=${this.m_connection.id}) enter fast recover state`); } blog.debug(`[BDT]: bdt transfer(id=${this.m_connection.id}) set cwnd with ${this.m_cwnd} from fast recover`); } if (this.m_state === Reno.STATE.fastRecover || (ackPkg.header.finalAck && sendQueue.flightSize > 0)) { // 没有resend就发一个新包,保证一个ack后能有一个包进入网络 if (sendQueue.resendNext(ackPkg.header.finalAck) === 0) { this.m_cwnd = sendQueue.flightSize + this.m_mms; } } } } onOvertime() { this.m_ssthresh = Math.max(Math.ceil(this.m_cwnd/2), 2*this.m_mms); let rto = this.m_rto * 2; if (rto < this.m_rtoMin) { rto = this.m_rtoMin; } else if (rto > this.m_rtoMax) { rto = this.m_rtoMax; } this.m_rto = rto; blog.debug(`[BDT]: bdt transfer(id=${this.m_connection.id}) set rto to ${rto}`); this.m_cwnd = this.m_mms; this.m_state = Reno.STATE.slowStart; blog.debug(`[BDT]: bdt transfer(id=${this.m_connection.id}) set cwnd with ${this.m_cwnd} from slow start`); } } Reno.STATE = { quickStart: 0, slowStart: 1, congestionAvoid: 2, fastRecover: 3, }; class BDTTransfer { constructor(connection, lastAckCallback) { this.m_connection = connection; const opt = connection.stack._getOptions(); // 发送缓存 this.m_sendBuffer = new BDTSendBuffer(opt.defaultSendBufferSize, opt.drainFreeBufferSize); this.m_sendBuffer.on('drain', ()=>{ setImmediate(() => this.m_connection.emit('drain')); }); // 发送队列 this.m_sendQueue = new BDTSendQueue(this); // nagle 延时 this.m_nagling = { pending: null, timeout: opt.nagleTimeout }; // 雍塞窗口大小 this.m_cwnd = opt.initRecvWindowSize; // 接收窗口大小 this.m_rwnd = opt.initRecvWindowSize; // 对端通报的接收窗口大小 this.m_nrwnd = this.m_rwnd; // 接收窗口 this.m_recvQueue = new BDTRecvQueue(connection); this.m_ackTimeout = null; this.m_cc = new Reno(this.m_connection); this.m_resendTimer = setInterval(()=>{ let resendSize = 0; const count = this.m_sendQueue.resendWaitAck(this.m_cc.rto, stub => { if (resendSize === 0) { this._hasAck(); this.m_cc.onOvertime(); } resendSize += SequenceU32.delta(stub.package.nextSeq, stub.package.header.seq); if (resendSize > this.m_cc.cwnd) { return true; // 一次最多重发窗口大小 } }); }, opt.resendInterval); // send fin的callback,在收到fin ack 时触发 this.m_finAckCallback = null; this.m_finSent = false; // 第一次回复了fin的ack时触发 this.m_lastAckCallback = lastAckCallback; this.m_finalAck = this._finalAck(); } get connection() { return this.m_connection; } send(buffer) { let [err, sentBytes] = this.m_sendBuffer.push(buffer); if (sentBytes) { this._onWndGrow(); } return sentBytes; } sendFin(callback) { if (this.m_finAckCallback) { return ; } let allocFin = ()=>{ let encoder = this.m_sendQueue.allocDataPackage(null, true); this.m_finSent = true; if (encoder) { this._postPackage(encoder); } }; this.m_finAckCallback = callback; if (this.m_sendBuffer.curSize) { this.m_sendBuffer.once('empty', ()=>{ allocFin(); }); } else { allocFin(); } } close() { if (this.m_ackTimeout) { clearTimeout(this.m_ackTimeout); this.m_ackTimeout = null; } if (this.m_resendTimer) { clearInterval(this.m_resendTimer); this.m_resendTimer = null; } this.m_lastAckCallback = null; this.m_finalAck.close(); } _onPackage(decoder) { if (decoder.header.cmdType === BDTPackage.CMD_TYPE.data || decoder.header.cmdType === BDTPackage.CMD_TYPE.fin) { let _doAck = immediate => { if (immediate || decoder.header.isResend || decoder.header.cmdType === BDTPackage.CMD_TYPE.fin) { this._ackImmediately(); } else { this._willAck(); } } const header = decoder.header; let ackSeq = header.ackSeq; if (SequenceU32.compare(ackSeq, this.m_sendQueue.sentSeq) > 0) { // 比已经发出去的大 return ; } let ackType = AckType.data; let sack = null; if (header.cmdType === BDTPackage.CMD_TYPE.data) { if (decoder.header.finalAck) { ackType = AckType.finalAck; } else { if (!decoder.data || decoder.header.sack) { ackType = AckType.ack; } } if (decoder.header.sack) { sack = decoder.data; } } if (_DEBUG) { if (decoder.body && decoder.body.debug) { let now = Date.now(); blog.debug(`bdt transfer(id=${this.m_connection.id}) recv data: senttime:${decoder.body.debug.time},now:${now},consum:${now-decoder.body.debug.time},seq:${decoder.header.seq},ackType:${ackType}`); if (ackType !== AckType.data) { blog.debug(`bdt transfer(id=${this.m_connection.id}) recv data-ack: remote.cc:${JSON.stringify(decoder.body.debug)}`); } } } if (sack) { this.m_sendQueue.onSACK(sack); } let [acked, pkgStub] = this.m_sendQueue.onAckPackage(ackSeq, ackType); this.m_cc.onAck(acked, pkgStub, this.m_sendQueue, decoder); blog.debug(`bdt transfer(id=${this.m_connection.id}) acked:${acked},cc.state:${this.m_cc.m_state},cc.rto:${this.m_cc.rto},cc.cwnd:${this.m_cc.cwnd},sendQueue.flightSize:${this.m_sendQueue.flightSize}`); if (acked >= 0) { this.m_nrwnd = decoder.header.windowSize; this._onWndGrow(); if (!this.m_sendQueue.flightSize && this.m_finSent) { if (this.m_finAckCallback) { let finAckCallback = this.m_finAckCallback; finAckCallback(); } } } if (ackType !== AckType.data) { return ; } this.m_finalAck.onData(); let recvQueue = this.m_recvQueue; if (SequenceU32.compare(header.seq, recvQueue.nextSeq) < 0) { // 收到已经ack的重发包 _doAck(false); return ; } if (SequenceU32.delta(header.seq, recvQueue.nextSeq) > this.m_rwnd) { // 收到接收窗口之外的包 _doAck(true); return ; } if (_DEBUG) { if (decoder.body.debug && decoder.body.debug.length) { assert(decoder.data.length === decoder.body.debug.length, `${decoder.body.debug.length}|${decoder.data.length}`); } if (decoder.body.debug && decoder.body.debug.md5) { let data = decoder.data || Buffer.concat([]); let decoderMD5 = md5(data); assert(decoderMD5 === decoder.body.debug.md5, `${decoder.body.debug.md5}|${decoderMD5}|${data.toString('hex')}`); } } let unpend = recvQueue.addPackage(decoder); if (unpend) { _doAck(false); let recv = []; for (let pkg of unpend) { if (pkg.data && pkg.data.length > 0) { recv.push(pkg.data); } } if (recv.length) { setImmediate(() => this.m_connection.emit('data', recv)); } if (unpend[unpend.length - 1].header.cmdType === BDTPackage.CMD_TYPE.fin) { if (this.m_lastAckCallback) { setImmediate(() => { // C++的异步tcp模式,通知一个空包 this.m_connection.emit('data', [Buffer.allocUnsafe(0)]); // node.js模式,通知'end' this.m_connection.emit('end'); }); this.m_lastAckCallback(); this.m_lastAckCallback = null; } } } else { _doAck(true); } } } _willAck() { let opt = this.m_connection.stack._getOptions(); if (this.m_recvQueue.isQuickAck) { return this._ackImmediately(); } let delay = Math.min(this.m_recvQueue.ato, this.m_cc.rto); if (!this.m_ackTimeout) { this.m_ackTimeout = setTimeout(()=>{ this.m_ackTimeout = null; this._ackImmediately(); }, delay); } } _ackImmediately(isFinalAck) { let encoder = this.m_recvQueue.allocAckPackage(this.m_rwnd); if (isFinalAck) { encoder.header.finalAck = true; } if (_DEBUG) { encoder.body.debug = { cwnd: this.m_cc.cwnd, rto: this.m_cc.rto, srtt: this.m_cc.srtt, state: this.m_cc.m_state, ssthresh: this.m_cc.m_ssthresh, flightSize: this.m_sendQueue.flightSize, sentSeq: this.m_sendQueue.sentSeq, ackSeq: this.m_sendQueue.ackSeq, sendBuffer: this.m_sendBuffer.curSize, ato: this.m_recvQueue.ato, } } this._postPackage(encoder); } _hasAck() { this.m_finalAck.onAcked(); if (this.m_ackTimeout) { clearTimeout(this.m_ackTimeout); this.m_ackTimeout = null; } } _onWndGrow(isTimeout) { let sendBuffer = this.m_sendBuffer; const windowSize = Math.min(this.m_cc.cwnd, this.m_nrwnd); const expectPackageSize = Math.min(windowSize >> 2, this.m_cc.mms); let maySendBytes = windowSize - this.m_sendQueue.flightSize; let sentBytes = 0; this.m_sendQueue.resendWaitResend(stub => { sentBytes += stub.package.dataLength; return sentBytes >= maySendBytes; }); maySendBytes -= sentBytes; if (sendBuffer.curSize >= expectPackageSize) { isTimeout = false; if (this.m_nagling.pending) { clearTimeout(this.m_nagling.pending); this.m_nagling.pending = null; } } while (maySendBytes > 0) { let packageBytes = 0; if (maySendBytes >= expectPackageSize) { packageBytes = expectPackageSize; } else { // 剩余空间太小,等空间足够再发送,减少碎片数据块 break; } // 剩余数据量太小,等等看是否有新的追加数据 if (sendBuffer.curSize < expectPackageSize && !isTimeout && !this.m_finAckCallback) { if (!this.m_nagling.pending) { this.m_nagling.pending = setTimeout(() => { this.m_nagling.pending=null; this._onWndGrow(true); }, this.m_nagling.timeout); } break; } let buffers = sendBuffer.head(packageBytes); if (!buffers) { break; } let encoder = this.m_sendQueue.allocDataPackage(buffers); if (encoder) { this._postPackage(encoder); } maySendBytes -= encoder.dataLength; sentBytes += encoder.dataLength; if (!sendBuffer.curSize) { break; } } } // 保底ack,发送一个带reAck标记的ack包 // 避免对端一个发送窗口全部包丢失后只能等待定时重传,或者本端回复的最后一个ack丢失, // 不能直接发纯粹的ack,否则会触发对方进入fastRecover状态, // 优化逻辑,待查实标准TCP实现策略后再行改进 _finalAck() { const opt = this.m_connection.stack._getOptions(); let ackTimeout = Math.max(this.m_cc.srtt, opt.ackTimeoutMax); let lastAckTime = TimeHelper.uptimeMS(); let timer = setInterval(() => { let now = TimeHelper.uptimeMS(); if (now - lastAckTime >= ackTimeout) { ackTimeout <<= 1; lastAckTime = now; this._ackImmediately(true); } }, opt.ackTimeoutMax); const finalAck = { onData: () => { ackTimeout = Math.max(this.m_cc.srtt, opt.ackTimeoutMax); }, onAcked: () => { lastAckTime = TimeHelper.uptimeMS(); }, close: () => { if (timer) { clearInterval(timer); timer = null; } }, }; return finalAck; } _postPackage(pkg) { if (SequenceU32.compare(pkg.header.ackSeq, this.m_recvQueue.ackSeq) !== 0) { this.m_recvQueue.fillAckPackage(pkg, this.m_rwnd); pkg.change(); } // <TODO> DEBUG if (_DEBUG) { pkg.body.debug = pkg.body.debug || {}; pkg.body.debug.time = Date.now(); let data = pkg.data; pkg.body.debug.length = data.length; pkg.body.debug.md5 = md5(data); pkg.change(); } this.m_connection._postPackage(pkg); this._hasAck(); } } BDTTransfer.version = 'v2'; module.exports = BDTTransfer;
/** * Created by gautam on 12/12/16. */ import React from 'react'; import BookedMenu from './BookedMenu'; import ajaxObj from '../../data/ajax.json'; import $ from 'jquery'; import Base from './base/Base'; import Coupons from './common/Coupons'; import {couponApplied} from '../actions'; import {connect} from 'react-redux'; class ConfirmationList extends React.Component { constructor(props) { super(props); } render() { const then = this, {bookingDetails: {services, discount, complementaryOffer, total, subTotal}, userDetails : {details}} = this.props, refCount = details ? details.refCount : 0, objKeys = Object.keys(services), margin = { marginBottom: 60 }, padding = { paddingTop: 8 }, refDiscount = refCount ? 200 : 0; return ( <div className = 'col-md-offset-4 col-md-4 pad0'> <div className = 'col-xs-12 summary pad0 rr'> <div className = 'col-xs-12'> <div className = 'col-xs-8'> Sub Total </div> <div className = 'col-xs-4' style = { padding }> <i className = 'fa fa-inr'></i> { subTotal } </div> </div> <div className = 'col-xs-12'> <div className = 'col-xs-8'> Referral Discount </div> <div className = 'col-xs-4'> - <i className = "fa fa-inr"></i> { parseFloat(refDiscount).toFixed(2) } </div> </div> <div className = 'col-xs-12'> <div className = 'col-xs-8'> Discount ({discount}%)</div> <div className = 'col-xs-4' style = { padding }> - <i className = 'fa fa-inr'></i> { parseFloat(discount * (subTotal - refDiscount) / 100).toFixed(2) }</div> </div> {complementaryOffer ? <div className='col-xs-12' style={{border: '1px dashed #999', fontWeight: 200}}> <div className = 'col-xs-6'>Complimentary Offer</div> <div className = 'col-xs-6' style={{textAlign: 'right', paddingRight: 10}}>{complementaryOffer}</div> </div>: null} <div className = 'col-xs-12'> <div className = 'col-xs-8'> Total </div> <div className = 'col-xs-4' style = { padding }> <i className = 'fa fa-inr'></i> { parseFloat((subTotal - refDiscount) - (discount * (subTotal - refDiscount) / 100)).toFixed(2) } </div> </div> </div> <Coupons showNotification={this.props.showNotification} /> <div className = 'col-xs-12 pad0' style = { margin }> <header className = 's-heading full-width'> <div className = 'col-xs-12 pad0'> <div className = 'col-xs-7 pad0'> { 'Service Name' }<br/> </div> <div className = 'col-xs-3'>{ 'Price' }</div> <div className = 'col-xs-2 center'> { 'Qty' } </div> </div> </header> {complementaryOffer ? <div className='cm-offers'> {complementaryOffer} </div>: null} { objKeys.map( function(key) { return <BookedMenu key={key} list = {services[key]} count = { services[key] ? services[key].count : 0 } discount={discount}/> }) } </div> </div> ) } } function mapStateToProps(state) { return { userDetails: state.userDetails, bookingDetails: state.bookingDetails }; } function mapDispatchToProps(dispatch) { return { couponApplied: (data) => { dispatch(couponApplied(data)); } }; } export default connect(mapStateToProps, mapDispatchToProps)(ConfirmationList);
import React, {useState} from 'react'; import { Table, Button, Row, Col, Input, Form } from 'antd'; import axios from 'axios'; import infosubvenciones_columns from '../table_columnas/infosubvenciones'; import { DOMAIN } from '../utils'; const layout = { labelCol: { span: 8 }, wrapperCol: { span: 16 }, }; const tailLayout = { wrapperCol: { offset: 8, span: 16 }, }; function Extra(props) { const [infosubvenciones, setInfosubvenciones] = useState([]) const onFinishFailed = errorInfo => { console.log('Failed:', errorInfo); }; async function onBtnScrape(values) { console.log("click") // const url_request = `${DOMAIN}/scrapers/workana${pages ? "?pages=" + pages : "" }`; const { pages } = values const url_request = `${DOMAIN}/scrapers/extra${pages ? "?pages=" + pages : "" }`; axios.get(url_request) .then(response => { const { rows } = response.data console.log(rows) setInfosubvenciones(rows) }) } return( <> <h1 className="title">Extra</h1> <Row> <Col> <Form {...layout} name="basic" initialValues={{ remember: true }} onFinish={onBtnScrape} onFinishFailed={onFinishFailed} > <Form.Item label="Pages to scrap" name="pages" // rules={[{ required: true, message: 'Please input your username!' }]} > <Input /> </Form.Item> <Form.Item {...tailLayout}> <Button type="primary" htmlType="submit"> Submit </Button> </Form.Item> </Form> </Col> </Row> <Row> <Table dataSource={infosubvenciones} columns={infosubvenciones_columns} /> </Row> </> ); }; export default Extra;
var pool = ( function () { 'use strict'; var urls = []; var callback = null; var results = null; var inLoading = false; pool = { getResult : function(){ return results; }, load: function( Urls, Callback ){ if ( typeof Urls == 'string' || Urls instanceof String ) urls.push( Urls );// = [ Urls ]; else urls = urls.concat( Urls ); callback = Callback || function(){}; results = {}; inLoading = true; this.loadOne(); }, next: function () { urls.shift(); if( urls.length === 0 ){ inLoading = false; callback( results ); //console.log(results) } else this.loadOne(); }, loadOne: function(){ var link = urls[0]; var name = link.substring( link.lastIndexOf('/')+1, link.lastIndexOf('.') ); var type = link.substring( link.lastIndexOf('.')+1 ); //console.log( name, type ); if( type === 'jpg' || type === 'png' ) this.loadImage( link, name ); else this[ type + '_load' ]( link, name ); }, loadImage: function ( url, name ) { var img = new Image(); img.onload = function(){ results[name] = img; this.next(); }.bind( this ); img.src = url; }, sea_load: function ( url, name ) { var l = new THREE.SEA3D(); l.onComplete = function( e ) { results[name] = l.meshes; this.next(); }.bind( this ); l.load( url ); }, json_load: function ( url, name ) { var xml = new XMLHttpRequest(); xml.overrideMimeType( "application/json" ); xml.onload = function () { results[name] = JSON.parse( xml.responseText ); this.next(); }.bind( this ); xml.open( 'GET', url, true ); xml.send( null ); }, glsl_load: function ( url, name ) { var xml = new XMLHttpRequest(); xml.onload = function () { results[name] = xml.responseText; this.next(); }.bind( this ); xml.open( 'GET', url, true ); xml.send( null ); }, }; return pool; })();