text
stringlengths
7
3.69M
import { vector, victor } from '../src/vector'; import { point, ipoint } from '../src/point'; import debug from '../src/debug'; import { cachedValueOf, cachedFactory, operatorCalc } from '../src/operator'; // create vector by numbers const pos = vector(5, 6, 7); const dir = vector(1, 0, 0); console.log(debug`pos:${pos}, dir: ${dir}`); // pos: { x: 5, y: 6, z: 7 } dir: { x: 1, y: 0, z: 0 } // or create vector by calculating other vectors and numbers with operator const offsetA = vector(() => dir * 30 + pos); console.log(debug`offsetA: ${offsetA}`); // offsetA: { x: 35, y: 6, z: 7 } let way = offsetA; try { way = offsetA + 1; } catch (e) { console.log('calculate outside of calc throw an error'); } // calculate outside of calc throw an error // calculate cross product const dir1 = vector(0, 1, 0); const dir2 = vector(-1, 0, 1); const cross = dir1.cross(dir2); console.log(debug`cross: ${cross}`); // cross: { x: 1, y: 0, z: 1 } // directly normalize the cross product const crossNorm = dir1.crossNormalize(dir2); console.log(debug`crossNorm: ${crossNorm}`); // crossNorm: { x: 0.7071, y: 0, z: 0.7071 } // cross product handling works also with operator handling const crossNormCalc = vector(() => dir1.crossNormalize(dir2) * 50); console.log(debug`crossNormCalc: ${crossNormCalc}`); // crossNormCalc: { x: 35.36, y: 0, z: 35.36 } // normalize only with arithmetic const norm = vector(() => offsetA / offsetA.length); console.log(debug`norm: ${norm}`); // norm: { x: 0.967, y: 0.1658, z: 0.1934 } // mutable 3D vector called Vector const v1 = vector(5, 6, 7); v1.x = 27; console.log(debug`v1: ${v1}`); // v1: { x: 27, y: 6, z: 7 } v1.calc(p => (p + 1) * 12); console.log(debug`v1: ${v1}`); // v1: { x: 336, y: 84, z: 96 } // immutable 3D vector called Victor const v2 = victor(5, 6, 7); try { v2.x = 27; } catch (error) { console.log('error:', error.toString()); // error: Error: set x() not implemented } // mutable 2D vector called Point const p1 = point(5, 6); p1.x = 27; console.log(debug`p1: ${p1}`); // p1: { x: 27, y: 6 } p1.calc(p => (p + 1) * 12); console.log(debug`v1: ${v1}`); // p1: { x: 336, y: 84 } // immutable 2D point called IPoint const p2 = ipoint(5, 6); try { p2.x = 27; } catch (error) { console.log('error:', error.toString()); // error: Error: set x() not implemented } // creating vector inside calculation works fine, // thanks to caching in factory function const inlineVec = victor(() => victor(25, 30, 0) / 2); console.log(debug`inlineVec: ${inlineVec}`); // inlineVec: { x: 12.5, y: 15, z: 0 } // mix 2D and 3D space const from2d = victor(() => point(25, 30) / 2); const from3d = ipoint(() => from2d.xy * 2); console.log(debug`from2d: ${from2d}`); console.log(debug`from3d: ${from3d}`); // from2d: { x: 12.5, y: 15, z: 0 } // from3d: { x: 25, y: 30 } // override valueOf in own class class Tuple { constructor(x, y, z) { this.x = x; this.y = y; this.z = z; } } cachedValueOf(Tuple); // write own factory function const tuple = (() => { const tupleFactory = cachedFactory(Tuple); return (x, y, z) => { if (typeof x === 'function') { return operatorCalc(x, new Tuple()); } return tupleFactory(x, y, z); }; })(); const t1 = tuple(3, 4, 5); const t2 = tuple(6, 7, 8); const t = tuple(() => t1 + t2 * 2); console.log(`t: ${JSON.stringify(t)}`); // t: {"x":15,"y":18,"z":21}
var searchData= [ ['armoury',['ARMOURY',['../class_ro_pa_sc_rules.html#ae1d3e82efce3aca085b03067d7794a37',1,'RoPaScRules']]] ];
//============================================================================== // initialisation //============================================================================== var EDITABLE_ID = "logoot"; var BEGIN_LINE_ID = LineId.getDocumentStarter().serialize(); var END_LINE_ID = LineId.getDocumentFinisher().serialize(); var CHARACTER_CLASS = "logoot_character"; var LIMIT_CLASS = "logoot_limit"; var TYPE_INSERTION = "logoot_insertion"; var TYPE_DELETION = "logoot_deletion"; var DOMAINE = "/r5a"; var REGISTER_URL = DOMAINE + "/r5a/networkServiceImplTwo?action=register"; var SEND_URL = DOMAINE + "/r5a/networkServiceImplTwo?action=send"; var PUSH_URL = DOMAINE + "/r5a/getDataTwo"; // generated in makeLogootEditor() var identifier = undefined; var logootPusher = undefined; function register() { var http; if (window.XMLHttpRequest) { // Mozilla, Safari, IE7 ... http = new XMLHttpRequest(); } else if (window.ActiveXObject) { // Internet Explorer 6 http = new ActiveXObject("Microsoft.XMLHTTP"); } http.open('GET', REGISTER_URL, true); http.onreadystatechange = function() { if (http.readyState == 4) { if (http.status == 200) { identifier = http.responseText; makeLogootEditor(EDITABLE_ID); } else { console.log('Pas glop pas glop'); } } } http.send(null); } function makeLogootEditor(divID) { var edit = document.getElementById(divID); edit.contentEditable = true; edit.addEventListener("keypress", insertion, false); edit.addEventListener("paste", paste, false); edit.addEventListener("keydown", deletion, false); edit.innerHTML = "<span class='" + LIMIT_CLASS + "' id='" + BEGIN_LINE_ID + "'></span><span class='" + LIMIT_CLASS + "' id='" + END_LINE_ID + "'></span>"; logootPusher = new EventSource(PUSH_URL); logootPusher.onmessage = onReceive; } //============================================================================== // events //============================================================================== function onReceive(event) { var message = JSON.parse(event.data); switch(message.type) { case TYPE_INSERTION: foreignInsertion(message.repID, message.keyCode, message.lineIdentifier, closestLineIdentifier(message.lineIdentifier)); break; case TYPE_DELETION: foreignDeletion(message.repId, message.lineIdentifier); break; } } function insertion(event) { var edit = document.getElementById(EDITABLE_ID); var selection = window.getSelection(); var range = selection.getRangeAt(0); var next = selection.anchorNode.parentNode.nextSibling; var span = document.createElement("span"); var data = String.fromCharCode(event.keyCode); // space if(event.keyCode==32) { data = "&nbsp;"; } // be sure that the next node is between the begin and the end span if(selection.baseOffset==0 || (selection.baseOffset==1 && selection.anchorNode.id == "logoot")) { next=document.getElementById(BEGIN_LINE_ID).nextSibling; } else if(next == document.getElementById(BEGIN_LINE_ID)) { next = next.nextSibling; } else if(next == null) { next = document.getElementById(END_LINE_ID); } var previousLineIdentifier = next.previousSibling.id; var nextLineIdentifier = next.id; // the previous or next span could be a cursor so the lineIdentifiers must be // changed while(document.getElementById(previousLineIdentifier).className != CHARACTER_CLASS && document.getElementById(previousLineIdentifier).className != LIMIT_CLASS) { previousLineIdentifier = document.getElementById(previousLineIdentifier).previousSibling.id; } while(document.getElementById(nextLineIdentifier).className != CHARACTER_CLASS && document.getElementById(nextLineIdentifier).className != LIMIT_CLASS) { nextLineIdentifier = document.getElementById(nextLineIdentifier).nextSibling.id; } // set the new span span.innerHTML = data; span.className = CHARACTER_CLASS; span.id = Logoot.generateLineId(LineId.unserialize(previousLineIdentifier), LineId.unserialize(nextLineIdentifier), 1, 10, identifier)[0].serialize(); // insert the added character edit.insertBefore(span, next); // move the caret to the end of the inserted character range.selectNode(span); range.collapse(false); selection.removeAllRanges(); selection.addRange(range); // notify other clients var message = {"type": TYPE_INSERTION, "repID": identifier, "keyCode": event.keyCode, "lineIdentifier": span.id} send(message); // cancel the event, then the character is not added twice event.returnValue = false; } function paste(event) { alert("Paste not supported."); event.returnValue = false; } function deletion(event) { switch(event.keyCode) { // <- case 8: var edit = document.getElementById(EDITABLE_ID); var selection = window.getSelection(); var range = document.createRange(); var span = selection.anchorNode.parentNode; // notify other clients var message = {"type": TYPE_DELETION, "repID": identifier, "lineIdentifier": span.id} send(message); if(span.id && span.className != LIMIT_CLASS) { // move the caret to the end of the previous character range.selectNode(span.previousSibling); range.collapse(false); selection.removeAllRanges(); selection.addRange(range); // delete the character edit.removeChild(span); } // cancel the event, then the character is not added twice event.returnValue = false; break; // del case 46: var edit = document.getElementById(EDITABLE_ID); var selection = window.getSelection(); var span = selection.anchorNode.parentNode; var next = span.nextSibling; // space if(selection.baseOffset==0 || (selection.baseOffset==1 && selection.anchorNode.id == "logoot")) { next=document.getElementById(BEGIN_LINE_ID).nextSibling; } // notify other clients var message = {"type": TYPE_DELETION, "repID": identifier, "lineIdentifier": next.id} send(message); // delete the character if(next && next.className != LIMIT_CLASS) { edit.removeChild(next); } // cancel the event, then the character is not added twice event.returnValue = false; break; } } //============================================================================== // utilities //============================================================================== function foreignInsertion(repID, keyCode, newLineIdentifier, previousLineIdentifier) { // do not process its own insertions if(repID != identifier) { var edit = document.getElementById(EDITABLE_ID); var selection = window.getSelection(); var range = selection.getRangeAt(0); var next = document.getElementById(previousLineIdentifier).nextSibling; var span = document.createElement("span"); var data = string.fromCharCode(keyCode); // space if(event.keyCode==32) { data = "&nbsp;"; } // set the new span span.innerHTML = data; span.id = newLineIdentifier; span.style = undefined; // insert the added character edit.insertBefore(span, next); } } function foreignDeletion(repID, lineIdentifier) { // do not process its own insertions if(repID != identifier) { var edit = document.getElementById(EDITABLE_ID); var span = document.getElementById(lineIdentifier); // delete the character edit.removeChild(span); } } function addCaretForRepID(repID, previousLineIdentifier) { // do not (re)display its own caret if(repID != identifier) { var edit = document.getElementById(EDITABLE_ID); var next = document.getElementById(previousLineIdentifier).nextSibling; var span = document.createElement("span"); // delete the old caret (if it exists) removeCaretForRepID(repID); // set the span to be a special caret span.className = CARET_CLASS; span.id = repID; span.hidden = false; span.innerHTML = "<font size=\"5\" face=\"arial\" style=\"color: " + caretColorForRepID(repID) + "\">|</font>"; // insert the caret edit.insertBefore(span, next); } } function removeCaretForRepID(repID) { // do not (re)display its own caret if(repID != identifier) { var edit = document.getElementById(EDITABLE_ID); var carets = document.getElementsByClassName(CARET_CLASS); for(var i = 0; i < carets.length; ++i) { if(carets[i].id = repID) { edit.removeChild(carets[i]); } } } } function caretColorForRepID(repID) { return "red"; // TODO generated with the repID } function closestSpan(newLineIdentifier) { var edit = document.getElementById(EDITABLE_ID); var span = edit.firstChild; var spanLineID = LineId.unserialize(span.id); var newLineID = LineId.unserialize(newLineIdentifier); var compareTo = spanLineId.compareTo(newLineID); while(compareTo == 1) { span = span.nextSibling; spanLineID = LineId.unserialize(span.id); compareTo = spanLineId.compareTo(newLineID); } return span; } function send(message) { var http; if (window.XMLHttpRequest) { // Mozilla, Safari, IE7 ... http = new XMLHttpRequest(); } else if (window.ActiveXObject) { // Internet Explorer 6 http = new ActiveXObject("Microsoft.XMLHTTP"); } http.open('GET', SEND_URL + '&message=' + JSON.stringify(message), true); //http.onreadystatechange = handleAJAXReturn; http.send(null); }
/** * Created by 柏大树 on 2017/4/5. */ var express = require('express'); var router = express.Router(); var Zif = require('../model').Zif; router.post('/add',function(req,res){ var ifs = req.body;//InterFaces Zif.create(ifs,function(err,docs){ res.send(ifs); }) }); module.exports = router;
var searchData= [ ['free_5fcalibri11x12',['free_calibri11x12',['../group___l_c_d___f_o_n_t_s.html#ga2558862b690208d8070c551c17815539',1,'ssd1306_fonts.c']]], ['free_5fcalibri11x12_5fcyrillic',['free_calibri11x12_cyrillic',['../group___l_c_d___f_o_n_t_s.html#gacceb4a5f5023dfc2417b9196c6de8904',1,'ssd1306_fonts.c']]], ['free_5fcalibri11x12_5flatin',['free_calibri11x12_latin',['../group___l_c_d___f_o_n_t_s.html#ga6476c7f5185fb5ec4f1270843a04d0e6',1,'ssd1306_fonts.c']]] ];
// 使用bind() // var that; class Tab { constructor(id) { //获取元素 // that = this; this.main = document.querySelector(id); this.add = this.main.querySelector('.tabadd'); //li的父元素 this.ul = this.main.querySelector('.firstnav ul:first-child'); //选项卡的父元素 this.fsetion = this.main.querySelector('.tabscon'); this.init(); } init() { this.getNode(); //init初始化操作让相关元素绑定事件 this.add.onclick = this.addTab.bind(this.add,this); for (var i = 0; i < this.lis.length; i++) { this.lis[i].index = i; this.lis[i].onclick = this.toggleTab.bind(this.lis[i],this);//这里通过bind()来改变,当我们点击了这个toggleTab后,一定不要修改这里的this指向,因为在toggleTab这个切换选项卡的函数是需要这个this的,即this.lis[i],即指向当前的这个小li,但是我们使用了constructor里面的this来当做参数传递给这个toggleTab函数的形参that作为实参,所以在调用函数的时候形参that存放的就是constructor的this。然后就可以使用constructor里面的this在函数toggleTab面调用that.clearStyle();这个方法,依次类推,其他bind()函数也是一样的方法。 this.removeButton[i].onclick = this.removeTab.bind(this.removeButton[i],this); this.spans[i].ondblclick = this.editTab; this.sections[i].ondblclick = this.editTab; } } //获取所有的li和section getNode() { this.lis = this.main.querySelectorAll('li'); this.sections = this.main.querySelectorAll('section'); this.removeButton = this.main.querySelectorAll('.wei'); this.spans = this.main.querySelectorAll('.firstnav li span:first-child'); } //切换功能 toggleTab(that) {//注意这里的that不是全局变量的that,而是constructor通过bind()传递来的形参this,指向的是constructor that.clearStyle(); //使用constructor调用 this.className = 'liactive'; that.sections[this.index].className = 'conactive'; //使用constructor调用 } //添加功能 addTab(that) { that.clearStyle(); //老方法 //创建新的选项卡 //将创建的选项卡添加到对应的父元素里 //新方法 //利用insertAdjacentHTML()可以直接把字符串格式的元素添加到父元素里 var rooud = Math.random(); var li = '<li class="liactive"><span>新建选项卡</span><span class="wei">✘</span>'; var sect = '<section class="conactive">新建内容' + rooud + '</section>'; that.ul.insertAdjacentHTML('beforeend', li); that.fsetion.insertAdjacentHTML('beforeend', sect); that.init(); } //删除功能 removeTab(that,e) { e.stopPropagation(); //阻止关闭按钮的父级li的冒泡事件,(li的点击切换事件) var index = this.parentNode.index; that.lis[index].remove(); //remove()方法可以直接删除指定元素 that.sections[index].remove(); that.init(); //删除元素之后再更新一次元素 //当我们删除一个未选中状态元素后,直接删除就可以 if (document.querySelector('.liactive')) { return; } //当我们删除一个选中状态元素后,让他的前一个元素处于选中状态 index--; that.lis[index] && that.lis[index].click(); } //修改功能,双击可以修改文字 editTab() { var star = this.innerHTML; //双击禁止选定文字 window.getSelection ? window.getSelection().removeAllRanges() : document.getSelection.empty(); this.innerHTML = '<input type="text"/>'; var input = this.children[0]; input.value = star; input.select(); //让文本框里的文字处于选中状态 //当我们离开文本框,就把文本框的值给span。 input.onblur = function () { this.parentNode.innerHTML = this.value; } //按下回车也可以将文本框的值给span input.onkeyup = function (e) { if (e.keyCode === 13) { this.blur(); } } } //清除所有li和section类样式 clearStyle() { for (var i = 0; i < this.lis.length; i++) { this.lis[i].className = ''; this.sections[i].className = ''; } } } new Tab('#tab');
import {useNavigation} from '@react-navigation/core'; import React from 'react'; import {StyleSheet, Text, TouchableOpacity, View} from 'react-native'; import BackArrowIcon from '../assets/BackArrow'; import CrossIcon from '../assets/CrossIcon'; import SearchIcon from '../assets/SearchIcon'; import StatisticsIcon from '../assets/StatisticsIcon'; import Colors from '../constants/Colors'; const CustomHeader = ({title, mode, canGoBack, isTest, goToStats}) => { const {headerContainer, headerTitle, friendsCont, leftIcon} = styles; const {goBack} = useNavigation(); return ( <> {!mode && ( <View style={[ headerContainer, goToStats && {justifyContent: 'space-between'}, ]}> {canGoBack && ( <TouchableOpacity style={leftIcon} onPress={goBack}> {isTest ? <CrossIcon /> : <BackArrowIcon />} </TouchableOpacity> )} <Text ellipsizeMode="clip" style={[ headerTitle, goToStats && {paddingLeft: 0}, isTest && {maxWidth: '90%'}, ]}> {title} </Text> {goToStats && ( <TouchableOpacity onPress={goToStats} style={{paddingRight: 20}}> <StatisticsIcon color={Colors.black2} /> </TouchableOpacity> )} </View> )} {mode === 'friends' && ( <View style={[headerContainer, friendsCont]}> <Text style={headerTitle}>{title}</Text> <TouchableOpacity> <SearchIcon /> </TouchableOpacity> </View> )} </> ); }; export default CustomHeader; const styles = StyleSheet.create({ headerTitle: { fontSize: 16, fontWeight: '700', paddingLeft: 20, maxWidth: '60%', }, headerContainer: { backgroundColor: 'white', paddingTop: 20, paddingBottom: 10, borderWidth: 1, borderColor: 'rgba(0,0,0,0.07)', flexDirection: 'row', alignItems: 'center', maxHeight: 80, }, leftIcon: { paddingLeft: 20, }, friendsCont: { flexDirection: 'row', justifyContent: 'space-between', paddingLeft: 0, paddingHorizontal: 16, alignItems: 'center', }, });
const axios = require("axios"); const connection = require("../infra/db/connection"); const repository = require("../repositories/appointment"); // const moment = require("moment"); class Appointment { async add(appointment) { // const date = moment(appointment.date).format("YYYY-MM-DD HH::MM::SS"); // const _appointment = { // ...appointment, // date: date, // }; return repository.add(appointment).then((results) => { return { ...appointment, id: results.insertId, }; }); } list() { return repository.list(); } async findById(id) { const results = await repository.findById(id); const appointment = results[0]; const cpf = appointment.client; const { data } = await axios.get(`http://localhost:8082/${cpf}`); appointment.client = data; return new Promise((resolve, _) => resolve(appointment)); } update(id, newAppointment) { return repository.update(id, newAppointment); } delete(id) { return repository.delete(id); } } module.exports = new Appointment();
import React, {useRef} from "react"; const App = () => { const videoRef = useRef(null) return <div> <video ref={videoRef} width="auto" height="auto"> <source src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" type="video/mp4"/> </video> <button onClick={() => videoRef.current.play()}>Play</button> <button onClick={() => videoRef.current.pause()}>Pause</button> </div> } export default App;
/* Task Description */ /* Write a function that sums an array of numbers: numbers must be always of type Number returns `null` if the array is empty throws Error if the parameter is not passed (undefined) throws if any of the elements is not convertible to Number */ function sum(arg) { var arr = arg, flag = 0, sumArr = 0, len, i; if (typeof arr === 'undefined'){ throw new Error(); } else if (arr.length === 0){ return null; } else if (!Array.isArray(arr)) { throw new Error(); } else { for (i = 0; len=arr.length, i < len; i++) { arr[i] = +arr[i]; } } for (var j = 0; j < len; j++) { if (isNaN(arr[j])) { throw new Error(); } else { sumArr+= arr[j]; } } if (sumArr!== 'undefined') { return sumArr; } } module.exports = sum;
import Carousel from './Carousel.svelte' export { Carousel }
import React from "react"; import "./style.css"; const Button = props => ( <button type={props.type ? props.type : "button"} className={"button" + (props.className ? " " + props.className : "")} onClick={props.click ? props.click : () => false} > {props.children} </button> ); export default Button;
const jwt = require('jsonwebtoken'); Author =require('../models/author'); var router = module.exports = require('express').Router(); router.use(function (req, res, next) { if (req.method === 'POST' || req.method === 'PUT' || req.method === 'DELETE' ) { console.log(req.headers['token']) try { var decoded = jwt.verify(req.headers['token'], 'secret'); } catch (error) { return res.status(401).json({ error: error }); } } next() }) router.get('/api/authors', (req, res) => { Author.getAuthors((err, authors) => { if(err){ throw err; } res.json(authors); }); }); router.post('/api/authors', (req, res) => { var author = req.body; console.log("api add author"); Author.addAuthor(author, (err, author) => { if(err){ throw err; } res.json(author); }); }); router.put('/api/authors/:_id', (req, res) => { var id = req.params._id; var author = req.body; Author.updateauthor(id, author, {}, (err, author) => { if(err){ throw err; } res.json(author); }); }); router.delete('/api/authors/:_id', (req, res) => { var id = req.params._id; Author.removeAuthor(id, (err, author) => { if(err){ throw err; } res.json(author); }); });
/******************************************************************************** * Compilation: node DecimalBinaryManipulation.js * * Purpose: This Program contains different methods to manipulate between Decimal * and Binary numbers. i.e Conversion b/w these two, swapping nibbles, etc. * * @author Nishant Kumar * @version 1.0 * @since 16-10-2018 * ********************************************************************************/ // Implementing the Readline module in this application. var readline = require('readline'); // Creating an Interface object of Readline Module by passing 'stdin' & 'stdout' as parameters. var rl = readline.createInterface(process.stdin, process.stdout); // Asking the user to input a Decimal Number. rl.question("\nEnter decimal number to convert into binary: ", function(ans1) { // Storing the input in 'num' variable as Number Type. var num = Number(ans1); // Validating if the input is greater than '0' or not. if (num > 0) { // If yes, then call 'swapNibbles()' function passing 'num' as the argument. swapNibbles(num); } else { // Else invalid number. console.log("Invalid number! Can't convert negative number to binary!"); } }); /** * Function used to convert decimal number into its binary form. Necessary * padding is done so that it represents the binary form in 4-byte String. * * @param {Number} num It is the number to be converted. * @returns {String} bin It is the string which stores the binary form of 'num' */ function toBinary(num) { var temp = num, n; var bin = ""; // Loop runs till temp is positive. Then number is converted into binary format. while (temp > 0) { n = temp % 2; bin = n + bin; temp = Math.floor(temp / 2); } /** * Check if length of bin is between 4 & 8, then adds zeroes before the numbers * to represent them into 4-Byte String format. */ if (bin.length < 8 && bin.length > 4) { while (bin.length <= 7) { bin = 0 + bin; } } /** * Check if length of bin is between 8 & 12, then adds zeroes before the numbers * to represent them into 4-Byte String format. */ if (bin.length < 12 && bin.length > 8) { while (bin.length <= 11) { bin = 0 + bin; } } /** * Check if length of bin is between 12 & 16, then adds zeroes before the numbers * to represent them into 4-Byte String format. */ if (bin.length < 16 && bin.length > 12) { while (bin.length <= 15) { bin = 0 + bin; } } // Print the binary form of the number. console.log("Binary of " + num + " is " + bin); // Return the binary value. return bin; } /** * Function to convert Binary to Decimal number. * * @param {String} st It is binary form of the number to be converted. */ function toDecimal(st) { // Converting String 'st' into an array & storing it into 'ch' array. var ch = st.split(''); // Initializing the 'sum' variable which'll store the Decimal value as '0'. var sum = 0, j = ch.length - 1; var temp; /** * This loop will run from 0 to half of the length of array. This loop will * swap the values of the array and reverse it. */ for (var i = 0; i < (ch.length) / 2; i++) { temp = ch[i]; ch[i] = ch[j]; ch[j] = temp; j--; } // This loop will determine the sum i.e the Decimal value of the Binary number passed. for (var i = 0; i < ch.length; i++) { if (ch[i] == '1') { sum += Math.pow(2, i); } } // Returning the Decimal value to the caller. return sum; } /** * Function user to swap the nibbles of a Binary Number, i.e swapping of the * 4-bit padding of binary number. * @param {Numbers} num */ function swapNibbles(num) { // Validating if the number is more than 2047 or not. if (num > 2047) { System.out.println("Please enter number b/w 0 & 2047 to swap nibbles"); } // Calling toBinary() function and storing it in 'bin' variable var bin = toBinary(num); // Converting 'bin' into array and storing it into 'ch' variable. var ch = bin.split(''); var temp = ''; // Initializing the Middle index of the array to swap nibbles. var j = (ch.length) / 2; // Loop to swap nibbles. for (var i = 0; i < (ch.length - 1) / 2; i++) { temp = ch[i]; ch[i] = ch[j]; ch[j] = temp; j++; } // Calling toDecimal() function and storing it into 'n' variable. var n = toDecimal(ch.join('')); // Printing the values. console.log("After swapping nibbles: " + ch.join('')); console.log("After conversion: " + n); // Calling isPowerOf2() function. isPowerOf2(n); rl.close(); } /** * Function to check if a given number is power of 2 or not. * * @param {Number} n It is the number to be checked for being power of 2. */ function isPowerOf2(n) { // 'temp' variable is to be compared with 'n' for being power of 2. var temp = 1, count = 1; // This loop will run till temp is less than or equal to n. while (temp <= n) { // multiplying temp by 2 everytime, i.e. finding count'th power of 2. temp = temp * 2; // Increasing the count variable to find which power of 2 is 'n'. count++; // if temp gets equal to 'n' that means it is a power of 2. if (temp == n) { console.log("It is a Power Of 2!!\n2^" + count + " = " + n + "\n"); return; } } // If not then it is not a power of 2. console.log("It is not a power of 2\n"); }
;(function(){ "use strict"; var app = angular.module("myApp", [ //third party modules 'ui.router', //in built module dependencies 'myApp.shared', 'myApp.home' ]); //global variables var templateBaseUrl = '/templates/'; var sharedObject = { header: { templateUrl: templateBaseUrl + 'shared/states/header-partial.html', controller: 'HeaderController' }, footer: { templateUrl: templateBaseUrl + 'shared/states/footer-partial.html', controller: 'FooterController' } }; app.config(['$stateProvider','$urlRouterProvider',function($stateProvider, $urlRouterProvider){ //routing $urlRouterProvider.otherwise('/home'); $stateProvider.state('home',{ url: '/home', views:{ header: sharedObject.header, footer: sharedObject.footer, content: { templateUrl: templateBaseUrl + 'home/states/home-partial.html', controller: 'HomeController' } } }); }]); })();
Router.configure({ layoutTemplate: 'register' }); Router.route('/1',{ name: 'animal' }); Router.route('../',{ name: 'register' });
$(document).ready(function() { new WOW().init(); $(function () { $('[data-toggle="tooltip"]').tooltip() }); $('#navbarSupportedContent-332').on('show.bs.collapse', function(){ $('#navbarSupportedContent-333').collapse('hide'); }); $('#navbarSupportedContent-333').on('show.bs.collapse', function(){ $('#navbarSupportedContent-332').collapse('hide'); }); let modalId = $('#image-gallery'); loadGallery(true, 'a.thumbnail'); //This function disables buttons when needed function disableButtons(counter_max, counter_current) { $('#show-previous-image, #show-next-image') .show(); if (counter_max === counter_current) { $('#show-next-image') .hide(); } else if (counter_current === 1) { $('#show-previous-image') .hide(); } } /** * * @param setIDs Sets IDs when DOM is loaded. If using a PHP counter, set to false. * @param setClickAttr Sets the attribute for the click handler. */ function loadGallery(setIDs, setClickAttr) { let current_image, selector, counter = 0; $('#show-next-image, #show-previous-image') .click(function () { if ($(this) .attr('id') === 'show-previous-image') { current_image--; } else { current_image++; } selector = $('[data-image-id="' + current_image + '"]'); updateGallery(selector); }); function updateGallery(selector) { let $sel = selector; current_image = $sel.data('image-id'); $('#image-gallery-title') .text($sel.data('title')); $('#image-gallery-image') .attr('src', $sel.data('image')); disableButtons(counter, $sel.data('image-id')); } if (setIDs == true) { $('[data-image-id]') .each(function () { counter++; $(this) .attr('data-image-id', counter); }); } $(setClickAttr) .on('click', function () { updateGallery($(this)); }); } // build key actions $(document) .keydown(function (e) { switch (e.which) { case 37: // left if ((modalId.data('bs.modal') || {})._isShown && $('#show-previous-image').is(":visible")) { $('#show-previous-image') .click(); } break; case 39: // right if ((modalId.data('bs.modal') || {})._isShown && $('#show-next-image').is(":visible")) { $('#show-next-image') .click(); } break; default: return; // exit this handler for other keys } e.preventDefault(); // prevent the default action (scroll / move caret) }); const snackbar = $("#snackbar"); snackbar.addClass("show"); setTimeout(function() { snackbar.removeClass("show"); }, 7000); const ratio = .3; const options = { root: null, rootMargin: '0px', threshold: ratio }; // // SEARCH USER FORM // const formResuslts = $('#form-resuslts'); const searchInput = $('input#search-user'); let currentRequest = null; $(document).on('click', function(){ formResuslts.fadeOut(); }); formResuslts.click(function(e){ e.stopPropagation(); }) searchInput.on('keyup', function(){ let value = searchInput.val(); if(value.length >= 3) { currentRequest = $.ajax({ type: "GET", dataType: "html", url: searchInput.data('url'), data: `terms=${value}`, beforeSend: function(){ if(currentRequest) { currentRequest.abort(); } }, success: function(data) { formResuslts.html(data); }, error: function(data) { console.log(data) } }); formResuslts.fadeIn(); } else { formResuslts.fadeOut(); } }); const handleIntersect = (entries, observer) => { entries.forEach(entry => { if(entry.intersectionRatio > ratio) { entry.target.classList.add('visible'); observer.unobserve(entry.target); } }); }; const observer = new IntersectionObserver(handleIntersect, options); document.querySelectorAll('[class*="reveal-"]').forEach(r => { observer.observe(r); }); const avatarInput = $('input[type="file"]'); const img = `<img class="img-circle img-150" src="#">`; avatarInput.change(function(){ $('.preview-container').html(img); readURL(this, '.avatar .img-preview img'); }); const galleryContainer = $('#gallery_gallery'); let indexImage = galleryContainer.find('div').length; const addImageBtn = $('#add-images'); addImageBtn.on('click', function (e) { addImage(galleryContainer); e.preventDefault(); return false; }); if (indexImage == 0) addImage(galleryContainer); else { galleryContainer.children('div').each(function () { addDeleteImageLink($(this)) }); } function addImage(container) { if(typeof container.attr('data-prototype') !== 'undefined') { const fileId = `gallery_gallery_${indexImage+1}_imageFile`; const img = $(`<img class="img-preview ${fileId}_preview">`); var prototype = $(container .attr('data-prototype') .replace(/<label class="required">__name__label__<\/label>/g, `<label for="${fileId}" class="file-label text-center aqua-gradient rounded text-white"><i class="fa fa-download"></i> Uploader</label>`) .replace(/__name__/g, `${(indexImage + 1)}`) ); addDeleteImageLink(prototype); img.insertBefore(prototype.find('label')); prototype.addClass('col-sm-3 mb-3 transition'); galleryContainer.append(prototype); indexImage++; $('#' + fileId).change(function(){ readURL(this, '.'+fileId+ '_preview'); }) } } function addDeleteImageLink(prototype) { const deleteLink = $(`<button class="btn delete-item text-danger"><i class="fas fa-trash"></i></button>`); const label = prototype.find('label'); deleteLink.insertBefore(label); deleteLink.on('click', function (e) { prototype.hide('normal', function () { prototype.remove(); }) e.preventDefault(); return false; }).hover(function () { prototype.addClass('bordered-red shadow'); }, function () { prototype.removeClass('bordered-red shadow'); }) } function readURL(input, src) { if (input.files && input.files[0]) { var reader = new FileReader(); reader.onload = function(e) { $(src).attr('src', e.target.result); } reader.readAsDataURL(input.files[0]); } } });
'use strict'; module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.createTable('Bugs', { id: { allowNull: false, autoIncrement: true, primaryKey: true, type: Sequelize.INTEGER }, status_correction: { allowNull: false, defaultValue: 'Ouvert', type: Sequelize.ENUM, values: ['Ouvert', 'Corrige', 'Annule'], }, date_creation: { type: Sequelize.DATE, defaultValue: Sequelize.NOW }, description: { allowNull: false, type: Sequelize.STRING }, criticite: { allowNull: false, type: Sequelize.ENUM, values: ['Mineur', 'Bloquant', 'Amelioration'], }, createdAt: { allowNull: false, type: Sequelize.DATE }, updatedAt: { allowNull: false, type: Sequelize.DATE } }); }, down: (queryInterface, Sequelize) => { return queryInterface.dropTable('Bugs'); } };
export default { activate_form_step: 0, sim_step_data: { card_number: '', card_bar_code: '' }, check_step_data: { user_name: '', password: '', general_terms: false }, data_step_data: { address: '', city: '', country_id: '', created_at: '', email: '', email_confirmation: '', gender_id: null, id: null, language_id: null, last_name: '', name: '', phone: '', state: '', status: '', updated_at: '', zip_code: null, user_name: '', password: '', general_terms_confirm: false, personal_data_confirm: false }, }
$.get("https://async-workshops-api.herokuapp.com/people", function(peopleResponse) { peopleResponse.forEach(function(person) { $.get("https://async-workshops-api.herokuapp.com/people/" + person.id, function(personResponse) { console.log(personResponse.favouriteMusic); }); }); });
const jwt = require('jsonwebtoken'); require('dotenv').config(); const { handleResponse, handleError, } = require('../middlewares/requestHandlers'); const { save, get, update, getUserProfileData, } = require('../dbServices/user'); const { requiredFeilds, passChk, chkUserExist, phoneNoRequired, emailRequired, } = require('../messages/error'); const generateJwtToken = async (user) => { const token = await jwt.sign(user._doc || user, process.env.APP_SECRET, {}); return token; }; module.exports.register = async ({ body }, res) => { try { const { phone, email } = body; const existingUserPhone = await get(phone, 'phone'); if (existingUserPhone) { return handleError({ res, msg: phoneNoRequired }); } const existingUserEmail = await get(email, 'email'); if (existingUserEmail) { return handleError({ res, msg: emailRequired }); } user = await save(body); delete user.password; const newToken = await generateJwtToken(user); user = await update(user._id, { token: newToken, }); return handleResponse({ res, data: user }); } catch (err) { console.log('err:::::::::::', err) return handleError({ res, err }); } }; module.exports.login = async ({ body: { email, phone, password, }, }, res, ) => { try { if ((!phone && !email) || !password) return handleResponse({ res, msg: requiredFeilds }); const bodyString = phone !== undefined ? 'phone' : 'email'; const body = phone !== undefined ? phone : email; let user = await get(body, bodyString); const msgString = phone !== undefined ? 'Phone number' : 'Email'; if (!user) { return handleError({ res, msg: `${msgString} entered is incorrect` });; } if (!(await user.verifyPassword(password))) { return handleError({ res, data: user }); passChk; } delete user._doc.password; const withoutToken = { ...user._doc }; delete withoutToken.token; user = await getUserProfileData(user._id); if (user.isDeleted) return handleError({ res, msg: chkUserExist }); const newToken = await generateJwtToken(withoutToken); user = await update(user._id, { token: newToken }); handleResponse({ res, data: user }); } catch (err) { handleError({ res, err }); } };
function newLifetime(kill_callback) { return {kill_callback: kill_callback}; }
module.exports = { JWT_SECRET: process.env.JWT_SECRET, PG_USER: process.env.PG_USER, PG_HOST: process.env.PG_HOST, PG_DATABASE: process.env.PG_DATABASE, PG_PASSWORD: process.env.PG_PASSWORD, PG_PORT: process.env.PG_PORT, };
import testFunction from "testFunction.js"; testFunction();
import React from 'react'; class Products extends React.Component { constructor(props) { super(props); this.submitHandler = this.submitHandler.bind(this); } submitHandler(inventory) { console.log(inventory) alert(inventory.inventoryType); } render() { return ( <div className="App"> <InventoryList /> <InventoryForm onSubmit={this.submitHandler}/> </div> ); } } class InventoryForm extends React.Component { constructor(props) { super(props); this.state = { addItem: true, inventoryType: '' }; this.handleInputChange = this.handleInputChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } handleInputChange(event) { const target = event.target; const value = target.type === 'checkbox' ? target.checked : target.value; const name = target.name; this.setState({ [name]: value }); } handleSubmit(event) { event.preventDefault(); this.props.onSubmit(this.state); } render() { return ( <form onSubmit={this.handleSubmit}> <label> Add Item: <input name="addItem" type="checkbox" checked={this.state.addItem} onChange={this.handleInputChange} /> </label> <br /> <label> inventory Type: <input name="inventoryType" type="text" value={this.state.inventoryType} onChange={this.handleInputChange} /> </label> <button>submit</button> </form> ); } } function InventoryItem(props) { return <li><p>{JSON.stringify(props.inventory)}</p></li> } class InventoryList extends React.Component { constructor(props) { super(props) this.state = { invetories: [ {id: 412, inventoryType: 'Books'}, {id: 543, inventoryType: 'Movies'}, ] } } render() { return ( this.state.invetories.length && <ul> {this.state.invetories.map(inventory => <inventoryItem key={inventory.id} inventory={inventory} />)} </ul> ) } } export default Products;
import styled from "styled-components"; export default styled.div` z-index: 1; position: relative; border: solid 1px #fff; padding: 2vh; background: rgba(0, 0, 0, 0.5); `;
/* Variávei globais */ let {mat4, vec4, vec3, vec2} = glMatrix; let SPEED = 0.1; const COS_45 = Math.cos(Math.PI * 0.25); let ku = false, kd = false, kl = false, kr = false, pos = [0,1,0]; pos2 = [20,0.5,15]; pos3 = [5,1,5]; snake = []; parede1v = [20,2,9]; parede1vp = [20,2,15]; parede2v = []; parede3v = []; parede4v = []; trail = 1; var sombra = new Array(200).fill({x:0,y:0,z:0}); let frame = 0, canvas, gl, vertexShaderSource, fragmentShaderSource, vertexShader, fragmentShader, shaderProgram, data, positionAttr, positionBuffer, normalAttr, normalBuffer, width, height, projectionUniform, projection, loc = [0, 0, 0], modelUniform, model, model2, model3, viewUniform, view, eye = [0, 0, 0], colorUniform, color1 = [1, 0, 0], color2 = [.79,.47,.79], color3 = [.92,.51,.23], color4 = [1, 0, 0], colorGold = [2.55, 2.55, 0], color5 = [.5,.5,.5], color6 = [0, 1, 1], colorTeste = [0,1,0], gameLoop = true, score = 0, lucky; function resize() { if (!gl) return; width = window.innerWidth; height = window.innerHeight; canvas.setAttribute("width", width); canvas.setAttribute("height", height); gl.viewport(0, 0, width, height); let aspect = width / height; let near = 0.001; let far = 1000; let fovy = 1.3; projectionUniform = gl.getUniformLocation(shaderProgram, "projection"); projection = mat4.perspective([], fovy, aspect, near, far); gl.uniformMatrix4fv(projectionUniform, false, projection); } function getCanvas() { return document.querySelector("canvas"); } function getGLContext(canvas) { let gl = canvas.getContext("webgl"); gl.enable(gl.DEPTH_TEST); return gl; } function compileShader(source, type, gl) { let shader = gl.createShader(type); gl.shaderSource(shader, source); gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) console.error("ERRO NA COMPILAÇÃO", gl.getShaderInfoLog(shader)); return shader; } function linkProgram(vertexShader, fragmentShader, gl) { let program = gl.createProgram(); gl.attachShader(program, vertexShader); gl.attachShader(program, fragmentShader); gl.linkProgram(program); if (!gl.getProgramParameter(program, gl.LINK_STATUS)) console.error("ERRO NA LINKAGEM"); return program; } function getData() { let p = { a: [-0.5, 0.5, -0.5], b: [-0.5, -0.5, -0.5], c: [0.5, 0.5, -0.5], d: [0.5, -0.5, -0.5], e: [-0.5, 0.5, 0.5], f: [0.5, 0.5, 0.5], g: [-0.5, -0.5, 0.5], h: [0.5, -0.5, 0.5] }; let faces = [ // FRENTE ...p.a, ...p.b, ...p.c, ...p.d, ...p.c, ...p.b, // TOPO ...p.e, ...p.a, ...p.f, ...p.c, ...p.f, ...p.a, // BAIXO ...p.b, ...p.g, ...p.d, ...p.h, ...p.d, ...p.g, // ESQUERDA ...p.e, ...p.g, ...p.a, ...p.b, ...p.a, ...p.g, // DIREITA ...p.c, ...p.d, ...p.f, ...p.h, ...p.f, ...p.d, //FUNDO ...p.f, ...p.h, ...p.e, ...p.g, ...p.e, ...p.h ]; let n = { frente: [0,0,-1], topo: [0,1,0], baixo: [0,-1,0], esquerda: [-1,0,0], direita: [1,0,0], fundo: [0,0,1], }; let faceNormals = { frente: [...n.frente, ...n.frente, ...n.frente, ...n.frente, ...n.frente, ...n.frente], topo: [...n.topo, ...n.topo, ...n.topo, ...n.topo, ...n.topo, ...n.topo], baixo: [...n.baixo, ...n.baixo, ...n.baixo, ...n.baixo, ...n.baixo, ...n.baixo], esquerda: [...n.esquerda, ...n.esquerda, ...n.esquerda, ...n.esquerda, ...n.esquerda, ...n.esquerda], direita: [...n.direita, ...n.direita, ...n.direita, ...n.direita, ...n.direita, ...n.direita], fundo: [...n.fundo, ...n.fundo, ...n.fundo, ...n.fundo, ...n.fundo, ...n.fundo], }; let normals = [ ...faceNormals.frente, ...faceNormals.topo, ...faceNormals.baixo, ...faceNormals.esquerda, ...faceNormals.direita, ...faceNormals.fundo ]; return { "points": new Float32Array(faces), "normals": new Float32Array(normals)}; } async function main() { // 1 - Carregar tela de desenho canvas = getCanvas(); // 2 - Carregar o contexto (API) WebGL gl = getGLContext(canvas); // 3 - Ler os arquivos de shader vertexShaderSource = await fetch("vertex.glsl").then(r => r.text()); console.log("VERTEX", vertexShaderSource); fragmentShaderSource = await fetch("fragment.glsl").then(r => r.text()); console.log("FRAGMENT", fragmentShaderSource); // 4 - Compilar arquivos de shader vertexShader = compileShader(vertexShaderSource, gl.VERTEX_SHADER, gl); fragmentShader = compileShader(fragmentShaderSource, gl.FRAGMENT_SHADER, gl); // 5 - Linkar o programa de shader shaderProgram = linkProgram(vertexShader, fragmentShader, gl); gl.useProgram(shaderProgram); // 6 - Criar dados de parâmetro data = getData(); // 7 - Transferir os dados para GPU positionAttr = gl.getAttribLocation(shaderProgram, "position"); positionBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer); gl.bufferData(gl.ARRAY_BUFFER, data.points, gl.STATIC_DRAW); gl.enableVertexAttribArray(positionAttr); gl.vertexAttribPointer(positionAttr, 3, gl.FLOAT, false, 0, 0); normalAttr = gl.getAttribLocation(shaderProgram, "normal"); normalBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, normalBuffer); gl.bufferData(gl.ARRAY_BUFFER, data.normals, gl.STATIC_DRAW); gl.enableVertexAttribArray(normalAttr); gl.vertexAttribPointer(normalAttr, 3, gl.FLOAT, false, 0, 0); // 7.1 - PROJECTION MATRIX UNIFORM resize(); window.addEventListener("resize", resize); // 7.2 - VIEW MATRIX UNIFORM eye = [0, 10, 10]; let up = [0, 1, 0]; let center = [0, 0, 0]; view = mat4.lookAt([], eye, center, up); viewUniform = gl.getUniformLocation(shaderProgram, "view"); gl.uniformMatrix4fv(viewUniform, false, view); // 7.3 - MODEL MATRIX UNIFORM model = mat4.create(); modelUniform = gl.getUniformLocation(shaderProgram, "model"); snake[0] = mat4.fromTranslation([], pos); model3 = mat4.fromScaling([],pos2); apple = mat4.fromTranslation([],pos3); parede1 = mat4.fromValues(16/*aqui mexe a E em x*/ ,0,0,0,0,1/*aqui mexe a E em Y*/,0,0,0,0,0.5/*aqui mexe a E em z*/,0,0/*aqui mexe a P em X*/,0.5/*aqui mexe a P em Y*/,7/*aqui mexe a E em Z*/,1); parede2 = mat4.fromValues(16/*aqui mexe a E em x*/ ,0,0,0,0,1/*aqui mexe a E em Y*/,0,0,0,0,0.5/*aqui mexe a E em z*/,0,0/*aqui mexe a P em X*/,0.5/*aqui mexe a P em Y*/,-7/*aqui mexe a E em Z*/,1); parede3 = mat4.fromValues(0.5/*aqui mexe a E em x*/ ,0,0,0,0,1/*aqui mexe a E em Y*/,0,0,0,0,14.5/*aqui mexe a E em z*/,0,-8/*aqui mexe a P em X*/,0.5/*aqui mexe a P em Y*/,0/*aqui mexe a E em Z*/,1); parede4 = mat4.fromValues(0.5/*aqui mexe a E em x*/ ,0,0,0,0,1/*aqui mexe a E em Y*/,0,0,0,0,14.5/*aqui mexe a E em z*/,0,8/*aqui mexe a P em X*/,0.5/*aqui mexe a P em Y*/,0/*aqui mexe a E em Z*/,1); console.log(model3); // 7.4 - COLOR UNIFORM colorUniform = gl.getUniformLocation(shaderProgram, "color"); //gl.uniform2f(locationUniform, loc[0], loc[1]); // 8 - Chamar o loop de redesenho init(); loop(); } function init(){ gl.uniformMatrix4fv(modelUniform, false, parede1); gl.uniform3f(colorUniform, color5[0], color5[1], color5[2]); gl.drawArrays(gl.TRIANGLES, 0, 36); gl.uniformMatrix4fv(modelUniform, false, parede2); gl.uniform3f(colorUniform, color5[0], color5[1], color5[2]); gl.drawArrays(gl.TRIANGLES, 0, 36); gl.uniformMatrix4fv(modelUniform, false, parede3); gl.uniform3f(colorUniform, color5[0], color5[1], color5[2]); gl.drawArrays(gl.TRIANGLES, 0, 36); gl.uniformMatrix4fv(modelUniform, false, parede4); gl.uniform3f(colorUniform, color5[0], color5[1], color5[2]); gl.drawArrays(gl.TRIANGLES, 0, 36); } function snakeCollision(){ for(let j = 2; j<snake.length;j++){ var testando = [sombra[j*10].x,sombra[j*10].z]; if(collide(pos[0],pos[2]/*primeira parte*/,testando[0], testando[1])){ gameLoop = false; } } } function loop() { frame ++; move(); let time = frame / 100; snake[0] = mat4.fromTranslation([],pos); apple = mat4.fromTranslation([], pos3); sombra = [{x: pos[0], y: pos[1], z: pos[2]}, ...sombra]; if(sombra.length > 200000){ sombra = sombra.slice(0,200000); } for(var i = 0; i<trail;i++){ var posSnake= [sombra[i*10].x,sombra[i*10].y,sombra[i*10].z]; snake[i] = mat4.fromTranslation([],posSnake); snakeCollision(); } eye = [Math.sin(time) * 5, 3, Math.cos(time) * 5]; gl.uniformMatrix4fv(viewUniform, false, view); gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); //redesenhar redraw(); //Saber se jogo continua, ou acabou, e caso acabou se ele deseja jogar dnv if(gameLoop==true){ window.requestAnimationFrame(loop); } else if (confirm("You lose! Press OK to play again or CANCEL to quit.")){ location.reload(); } else{ document.getElementById("Canvas").style.display = "none"; //document.getElementById("name").style.display = "none"; document.getElementById("score").style.display = "none"; document.getElementById("inst1").style.display = "none"; document.getElementById("inst2").style.display = "none"; document.getElementById("listra1").style.display = "none"; document.getElementById("listra2").style.display = "none"; document.getElementById("listra3").style.display = "none"; document.getElementById("inst3").style.display = "none"; document.getElementById("name").innerHTML = "Game Over!"; } } function follow(evt) { let locX = evt.x / window.innerWidth * 2 - 1; let locY = evt.y / window.innerHeight * -2 + 1; loc = [locX, locY]; } function keyDown(evt){ if(evt.key === "ArrowDown" && ku!= -1) { kd = 1; ku = 0; kl = 0; kr = 0; } if(evt.key === "ArrowUp" && kd !=1){ kd = 0; ku = -1; kl = 0; kr = 0; } if(evt.key === "ArrowLeft" && kr !=1){ kd = 0; ku = 0; kl = -1; kr = 0; } if(evt.key === "ArrowRight" && kl!=-1){ kd = 0; ku = 0; kl = 0; kr = 1; } } function move(){ let hor = (kl + kr) * SPEED; let ver = (ku + kd) * SPEED; if(hor !== 0 && ver !== 0){ hor *= COS_45; ver *= COS_45; } if(pos[0]>7.3){ pos[0] = -7.3; } if(pos[0]<-7.3){ pos[0] = 7.3; } if(pos[2]>6.3){ pos[2] = -6.3; } if(pos[2]<-6.3){ pos[2] = 6.3; } pos[0] += hor; pos[2] += ver; if(collide(pos[0],pos[2],pos3[0],pos3[2])){ if(lucky <=1){ trail +=2; score += 15; } else{ trail++; score += 5; } pos3 = randomApple(); lucky = Math.floor(Math.random()* 10); console.log(lucky) document.getElementById("score").innerHTML = "Score: " + score + ""; } } function collide(x,z,x2,z2){ return vec2.dist([x,z],[x2,z2]) < 1; } function redraw(){ // snake for(let i=0;i<trail;i++){ const atual = snake[i]; if(i%2==0){ gl.uniformMatrix4fv(modelUniform, false, atual); gl.uniform3f(colorUniform, color2[0], color2[1], color2[2]); gl.drawArrays(gl.TRIANGLES, 0, 36); } else{ gl.uniformMatrix4fv(modelUniform, false, atual); gl.uniform3f(colorUniform, colorTeste[0], colorTeste[1], colorTeste[2]); gl.drawArrays(gl.TRIANGLES, 0, 36); } } //apple if(lucky <= 1){ gl.uniformMatrix4fv(modelUniform, false, apple); gl.uniform3f(colorUniform, colorGold[0], colorGold[1], colorGold[2]); gl.drawArrays(gl.TRIANGLES, 0, 36); } else{ gl.uniformMatrix4fv(modelUniform, false, apple); gl.uniform3f(colorUniform, color4[0], color4[1], color4[2]); gl.drawArrays(gl.TRIANGLES, 0, 36); } //field gl.uniformMatrix4fv(modelUniform, false, model3); gl.uniform3f(colorUniform, color3[0], color3[1], color3[2]); gl.drawArrays(gl.TRIANGLES, 0, 36); gl.uniformMatrix4fv(modelUniform, false, parede1); gl.uniform3f(colorUniform, color5[0], color5[1], color5[2]); gl.drawArrays(gl.TRIANGLES, 0, 36); gl.uniformMatrix4fv(modelUniform, false, parede2); gl.uniform3f(colorUniform, color5[0], color5[1], color5[2]); gl.drawArrays(gl.TRIANGLES, 0, 36); gl.uniformMatrix4fv(modelUniform, false, parede3); gl.uniform3f(colorUniform, color5[0], color5[1], color5[2]); gl.drawArrays(gl.TRIANGLES, 0, 36); gl.uniformMatrix4fv(modelUniform, false, parede4); gl.uniform3f(colorUniform, color5[0], color5[1], color5[2]); gl.drawArrays(gl.TRIANGLES, 0, 36); } function randomApple(){ let X = 1, Z = 1; X = Math.floor(Math.random()* 10)-5; Z = Math.floor(Math.random()* 12)-6; return [X,1,Z] } // keypress, keydown, keyup window.addEventListener("load", main); window.addEventListener("mousemove", follow); //window.addEventListener("keyup", keyUp); window.addEventListener("keydown", keyDown);
const Sequelize = require('sequelize'); module.exports = function(sequelize, DataTypes) { return sequelize.define('CoreConfigData', { config_id: { autoIncrement: true, type: DataTypes.INTEGER.UNSIGNED, allowNull: false, primaryKey: true, comment: "Config ID" }, scope: { type: DataTypes.STRING(8), allowNull: false, defaultValue: "default", comment: "Config Scope" }, scope_id: { type: DataTypes.INTEGER, allowNull: false, defaultValue: 0, comment: "Config Scope ID" }, path: { type: DataTypes.STRING(255), allowNull: false, defaultValue: "general", comment: "Config Path" }, value: { type: DataTypes.TEXT, allowNull: true, comment: "Config Value" }, updated_at: { type: DataTypes.DATE, allowNull: false, defaultValue: Sequelize.Sequelize.fn('current_timestamp'), comment: "Updated At" } }, { sequelize, tableName: 'core_config_data', timestamps: false, indexes: [ { name: "PRIMARY", unique: true, using: "BTREE", fields: [ { name: "config_id" }, ] }, { name: "CORE_CONFIG_DATA_SCOPE_SCOPE_ID_PATH", unique: true, using: "BTREE", fields: [ { name: "scope" }, { name: "scope_id" }, { name: "path" }, ] }, ] }); };
/*------------------------------------------------------------------------------- * HomeService * * Purpose : Service to get data and parse for home page and search form. Uses * calls retrieved from external APIs. * * Dependencies * -- /app/shared/external/eBayAPI.js (Category information) * -- /app/shared/external/ZipCodeAPI.js (Location information) *-------------------------------------------------------------------------------*/ app.service('HomeService', [ 'eBayAPI', '$rootScope', '$timeout', function(eBayAPI, $rootScope, $timeout) { service = {}; // show loading animation while the calls are made var showLoading = true; // IDs for Cars & Trucks, Motorcycles, and RVs var topCategoryIDs = [6001, 6024, 50054]; // Get the top 3 Categories to choose from service.getTopCategories = function () { // array to hold the final list var topCategoryInfo = []; // loop through the list of ids for ( var i=0; i<topCategoryIDs.length; i++ ) { // get the info for each category var thisCategory = eBayAPI.getCategoryInfo(topCategoryIDs[i], false); // wait for the data to finish fetching and loading thisCategory.then( function (data) { // create new object and get only the info we need var categoryInfo = { name : data[0].CategoryName, id : data[0].CategoryID }; // create a class name by removing special characters and replacing spaces with dashes var className = categoryInfo.name.replace(/[^a-zA-Z ]/g, '').replace(/\s/g, '-'); categoryInfo.class = className; // add the info to the list topCategoryInfo.push(categoryInfo); }); } // stop show the loading animation showLoading = false; // list is ready, send it back to be displayed using ng-repeat return topCategoryInfo; }; // Get the next level of categories by clicking on a displayed category service.getSubCategories = function (parentID) { // Do not show these categories, they are not vehicles var categoryList = []; // get the immediate children of the selected category var theChildren = eBayAPI.getCategoryInfo(parentID, true); // wait for the data to finish fetching and loading theChildren.then( function (data) { //console.log(data); // loop through the results for ( var i=1; i<data.length; i++ ) { // object to contain information we want var tempObj = { id : data[i].CategoryID, name : data[i].CategoryName }; // add it to the array categoryList.push(tempObj); } }); //return the array return categoryList; }; // Get selected number of recent listings in each category for top and bottom bars service.getRecentListings = function (qty, set) { // create an array to hold all listings var allListings = []; // loop through each of the top categories and get the selected number of listings for ( var i=0; i<topCategoryIDs.length; i++ ) { var searchData = { categoryID : topCategoryIDs[i], makeID : 0, modelID : 0, keywords : '', minPrice : 0, maxPrice : 0, sendCategoryID : topCategoryIDs[i], qty : qty, set : set, sortBy : 'StartTimeNewest' }; // get the listings for the current category var categoryListings = eBayAPI.getListings(searchData); // wait for the data to finish fetching and loading categoryListings.then( function (data) { // get the array of listings var theListings = data.findItemsAdvancedResponse[0].searchResult[0].item; // loop through the listings for ( var i=0; i<theListings.length; i++ ) { // get the item ID var itemID = theListings[i].itemId[0]; // get the details of the item var itemDetails = eBayAPI.getItemDetails(itemID); // once the information has been received, capture what we need itemDetails.then( function (data) { //console.log(data[0]); // Grab only what we need var itemInfo = { id : data[0].ItemID, price : data[0].CurrentPrice.Value, photo : data[0].PictureURL[0], location : data[0].Location }; // parse the item specifics so we can find what we need var itemSpecifics = data[0].ItemSpecifics.NameValueList; // What we are looking for var detailList = ["Year", "Make", "Model"]; var itemDetails = {}; // loop through and build the item specifics we need for ( var i=0; i<itemSpecifics.length; i++ ) { var keyName = itemSpecifics[i].Name; // see if the name of the object is one of the items in our list if ( detailList.indexOf(keyName) > -1 ) { // remove spaces out of the key name keyName = keyName.replace(/\s/g, ''); // we found one! so lets add the name and value to our details itemDetails[keyName] = itemSpecifics[i].Value[0]; } } // add the detail to main item object itemInfo.details = itemDetails; //console.log(itemInfo); // add the item to the listings array allListings.push(itemInfo); }); } }); } return shuffle(allListings); }; var shuffle = function (array) { var currentIndex = array.length; while (0 !== currentIndex) { var randomIndex = Math.floor(Math.random() * currentIndex); currentIndex--; var tempValue = array[currentIndex]; array[currentIndex] = array[randomIndex]; array[randomIndex] = tempValue; } return array; } // Service to broadcast the search parameters to the listing page service.goToNext = function(data) { service.sendData = data; }; service.getData = function () { return service.sendData; }; //return service; return service; } ]);
export const Data = [ { topic: '', name: 'John Lee', }, { topic: '', name: 'John Lee', }, { topic: '', name: 'John Lee', }, { topic: '', name: 'John Lee', }, { topic: '', name: 'John Lee', }, { topic: '', name: 'John Lee', }, { topic: '', name: 'John Lee', }, { topic: '', name: 'John Lee', }, { topic: '', name: 'John Lee', }, { topic: '', name: 'John Lee', }, ];
/** * * OrdersList * * Orders.List page content scripts. Initialized from scripts.js file. * * */ class OrdersList { constructor() { // Initialization of the page plugins if (typeof Checkall !== 'undefined') { this._initCheckAll(); } else { console.error('[CS] Checkall is undefined.'); } } // Check all button initialization _initCheckAll() { new Checkall(document.querySelector('.check-all-container .btn-custom-control')); } }
import React, { Component } from "react"; import { Link, Redirect } from "react-router-dom"; import { connect } from "react-redux"; import { Field, reduxForm } from "redux-form"; import { register } from "../../actions/auth"; import Form from "react-bootstrap/Form"; import Button from "react-bootstrap/Button"; import Alert from "react-bootstrap/Alert"; import Container from "react-bootstrap/Container"; // Internationalization import { withTranslation } from "react-i18next"; class RegisterForm extends Component { renderField = ({ input, meta: { touched, error }, ...props }) => { return ( <Form.Group> <Form.Label>{props.label}</Form.Label> <Form.Control {...props} {...input} className={touched ? (error ? "is-invalid" : "is-valid") : ""} /> {touched && error && ( <Alert key="1" variant="danger"> {error} </Alert> )} </Form.Group> ); }; onSubmit = formValues => { this.props.register(formValues); }; render() { const { t } = this.props; if (this.props.isAuthenticated) { return <Redirect to="/" />; } return ( <Container style={{ marginTop: "2rem", border: "1px", marginBottom: "15px", background: "#f7f7f7", boxShadow: "0px 2px 2px rgba(0, 0, 0, 0.3)", padding: "30px", width: "340px" }} > <Form onSubmit={this.props.handleSubmit(this.onSubmit)}> <Field name="username" type="text" component={this.renderField} label={t("register-frm.username")} validate={[required, minLength3]} /> <Field name="email" type="email" component={this.renderField} label={t("register-frm.email")} validate={[required, minLength3]} /> <Field name="password" type="password" component={this.renderField} label={t("register-frm.password")} validate={required} /> <Field name="password2" type="password" component={this.renderField} label={t("register-frm.cnfrm-password")} validate={[required, passwordsMatch]} /> <Button variant="primary" type="submit"> {t("register-frm.register")} </Button> </Form> <p style={{ marginTop: "1rem" }}> {t("register-frm.have-account-msg")}{" "} <Link to="/login">{t("register-frm.login")}</Link> </p> </Container> ); } } const required = value => (value ? undefined : "Required"); const minLength = min => value => value && value.length < min ? `Must be at least ${min} characters` : undefined; const minLength3 = minLength(3); const maxLength = max => value => value && value.length > max ? `Must be ${max} characters or less` : undefined; const maxLength15 = maxLength(15); const passwordsMatch = (value, allValues) => value !== allValues.password ? "Passwords do not match" : undefined; const mapStateToProps = state => ({ isAuthenticated: state.auth.isAuthenticated }); RegisterForm = withTranslation()( connect( mapStateToProps, { register } )(RegisterForm) ); export default reduxForm({ form: "registerForm" })(RegisterForm);
import { Router } from 'express' const router = Router() import * as authController from '../controllers/auth.controller' import { authJwt } from '../middlewares' router.post('/registrarse', [authJwt.verifyToken, authJwt.permisoCrearUsuario], authController.signUp) router.post('/logearse', authController.signIn) export default router;
const Post = props => { return <h1>{props.title}</h1> } export const getServerSideProps = ctx => { const languages = { en: 'A blog in english', et: 'Eesti keeles blogi', } return { props: { title: languages[ctx.locale], }, } } export default Post
import axios from 'axios'; import _ from 'lodash'; import React, { useEffect, useState } from 'react'; import { makeStyles } from '@material-ui/core/styles'; import Card from '@material-ui/core/Card'; // import CardActionArea from '@material-ui/core/CardActionArea'; import CardHeader from '@material-ui/core/CardHeader'; import CardActions from '@material-ui/core/CardActions'; import CardContent from '@material-ui/core/CardContent'; import CardMedia from '@material-ui/core/CardMedia'; import Button from '@material-ui/core/Button'; import Typography from '@material-ui/core/Typography'; import Menu from './Menu'; import '../userdashboard/itemcard.css'; const useStyles = makeStyles((theme) => ({ card: { background: '#fffcfe', display: 'flex', flexDirection: 'column', justifyContent: 'space-between', width: '80vw', maxHeight: '130vh', marginLeft: 0, marginRight: 0, margin: 10, font: 'Lato', [theme.breakpoints.down(840)]: { width: '70vw', flexDirection: 'column', alignItems: 'center', }, [theme.breakpoints.down(600)]: { // height: '115vh', width: '70vw', flexDirection: 'column', alignItems: 'center', }, }, headerSpace: { display: 'flex', width: '100%', background: '#6A7933', boxShadow: '2px 2px 4px rgba(0, 0, 0, .5)', }, header: { display: 'flex', width: '100%', }, content: { display: 'flex', flexDirection: 'row', justifyContent: 'space-between', width: '100%', [theme.breakpoints.down(840)]: { width: '60vw', flexDirection: 'column', alignItems: 'center', }, [theme.breakpoints.down(600)]: { minHeight: '90vh', width: '70vw', flexDirection: 'column', alignItems: 'center', }, }, details: { display: 'flex', alignItems: 'center', flexDirection: 'row', justifyContent: 'left', marginLeft: '2%', width: '100%', [theme.breakpoints.down(840)]: { width: '60vw', flexDirection: 'column', alignItems: 'center', }, [theme.breakpoints.down(600)]: { minHeight: '50vh', width: '70vw', flexDirection: 'column', alignItems: 'center', }, }, paragraph: { display: 'flex', justifyItems: 'left', [theme.breakpoints.down(940)]: { margin: 3, }, }, image: { margin: 10, marginRight: 20, width: 151, height: 151, objectFit: 'scale-down', }, root: { fontFamily: 'Lato', marginBottom: '.2em', fontSize: '4vh', }, text: { fontFamily: 'Lato', fontSize: '2.5vh', [theme.breakpoints.down(940)]: { fontSize: '2.5vh', }, }, actions: { display: 'flex', justifyContent: 'flex-end', alignItems: 'flex-end', flexFlow: 'wrap', marginRight: '2%', width: '35vw', [theme.breakpoints.down(840)]: { flexDirection: 'column', alignItems: 'center', justifyContent: 'center', width: '35vw', }, [theme.breakpoints.down(600)]: { flexDirection: 'column', alignItems: 'center', justifyContent: 'center', width: '50vw', }, }, button: { fontFamily: 'Lato', }, })); const roastList = [ 'Light', 'Medium', 'Dark', 'Espresso', 'Decaf', 'Club Choice', ]; const beanStatusList = ['Whole', 'Ground']; const originList = ['Single', 'Blend']; const bagSizeList = ['12 oz', '4 oz']; const RoastListItem = (props) => { const classes = useStyles(); const alt = `${props.item.roaster} ${props.item.roastType} roast ${props.item.beanStatus} bean`; const customSelection = props.customSelection; const tastersTrio = props.tastersTrio; const [roasterList, setRoasterList] = useState([]); const [roasterData, setRoasterData] = useState({}); const [value, setValue] = useState({ roaster: props.item.roaster, roast: props.item.roast, bean: props.item.bean, origin: props.item.origin, size: props.item.size, logo: props.item.logo, }); const handleChange = (event) => { const property = event.target.name; console.log('property', event.target.name, '\n', event.target.value); setValue({ ...value, [property]: event.target.value }); console.log('property', props.item.logo); if (property === 'roaster') { setValue({ ...value, logo: roasterData[event.target.value]['logo'] }); props.item.logo = roasterData[event.target.value]['logo']; } props.item[property] = event.target.value; console.log('event value', event.target.value); console.log('what is item', props.item); updateStorage(); }; const updateStorage = () => { let storageItems = tastersTrio ? localStorage.getItem('orderTrio') : localStorage.getItem('orderChoice'); storageItems = JSON.parse(storageItems); storageItems.splice(props.index - 1, 1, value); tastersTrio ? localStorage.removeItem('orderTrio') : localStorage.removeItem('orderChoice'); tastersTrio ? localStorage.setItem('orderTrio', JSON.stringify(storageItems)) : localStorage.setItem('orderChoice', JSON.stringify(storageItems)); }; const host = 'http://localhost:8000'; useEffect(() => { axios.get(`${host}/api/roaster`).then((resp) => { console.log('what si resp?', resp); setRoasterList( _.map(resp.data, (el) => { return el.name; }) ); setRoasterData( _.reduce( resp.data, (acc, el, key) => { acc[el.name] = { logo: el.logo_url }; return acc; }, {} ) ); }); }, []); useEffect(() => { setValue(props.item); }, [value, props.item]); return ( <div> <Card className={classes.card}> <div className={classes.headerSpace}> <CardHeader className={classes.header} title={`Option ${props.index}:`} /> {customSelection ? ( <Button className={classes.button} size='medium' color='inherit' onClick={() => { props.removeItem(props.index - 1); }} > X </Button> ) : null} </div> <div className={classes.content}> <div className={classes.details}> <CardMedia className={classes.image} component='img' alt={alt} height='140' image={ roasterData[value.roaster] ? roasterData[value.roaster]['logo'] : 'https://lrcimages.s3.us-east-2.amazonaws.com/roasterlogos/lrclogo.svg' } // title={props.item.roaster} /> <CardContent className={classes.paragraph}> <div className={classes.text}> <p>Roaster: {value.roaster}</p> <p>Roast Type: {value.roast}</p> <p>Beans: {value.bean}</p> <p>Origin: {value.origin}</p> <p>Bag Size: {value.size}</p> </div> </CardContent> </div> <CardActions className={classes.actions}> <Menu value={value.roaster} handleChange={handleChange} name={'roaster'} list={roasterList} listName={'Roaster'} /> <Menu value={value.roast} handleChange={handleChange} name={'roast'} list={roastList} listName={'Roast'} /> <Menu value={value.bean} handleChange={handleChange} name={'bean'} list={beanStatusList} listName={'Bean Status'} /> <Menu value={value.origin} handleChange={handleChange} name={'origin'} list={originList} listName={'Origin'} /> {customSelection && props.index > 1 ? ( <Menu value={value.size} handleChange={handleChange} name={'size'} list={bagSizeList} listName={'Bag Size'} /> ) : null} </CardActions> </div> </Card> </div> ); }; export default RoastListItem;
// Conventions: // x > 0 is to the right // y > 0 is down var camera = { x0: 0, y0: 0, z: 32, focus: null, zoverride: 0, think: function (dt) { this.z = this.zoverride || Math.min(canvas.width, canvas.height) / (state.sun ? 26 : 18) if (this.focus) { var f = Math.min(10 * dt, 1) this.x0 += (this.focus.x - this.x0) * f this.y0 += (this.focus.y - this.y0) * f } this.ymin = this.y0 - canvas.height / this.z * 0.55 this.ymax = this.y0 + canvas.height / this.z * 0.55 this.xmin = this.x0 - canvas.width / this.z * 0.55 this.xmax = this.x0 + canvas.width / this.z * 0.55 }, transform: function () { UFX.draw("t", canvas.width/2, canvas.height/2, "z", this.z, -this.z, "t", -this.x0, -this.y0, "z 0.01 0.01") }, visible: function (x, y, r) { return x > this.xmin - r && x < this.xmax + r && y > this.ymin - r && y < this.ymax + r }, }
import loginReducer from "./login"; import postsReducer from "./posts"; import profileReducers from "./profile"; import chatsReducer from "./chat"; import messagesReducer from "./messages"; import commentsReducer from "./comments"; import followersReducer from "./followers"; import followingsReducer from "./followings"; import notificationsReducer from "./notifications"; import hashtagsReducer from "./hashtags"; import searchReducer from "./search"; import { combineReducers } from "redux"; const allReducers = combineReducers({ login: loginReducer, posts: postsReducer, followers: followersReducer, followings: followingsReducer, comments: commentsReducer, profile: profileReducers, chats: chatsReducer, messages: messagesReducer, notifications: notificationsReducer, hashtags: hashtagsReducer, search: searchReducer, }); export default allReducers;
import angular from 'angular'; import 'bootstrap/dist/css/bootstrap.css'; import angularMeteor from 'angular-meteor'; import template from './assetDepartment.html'; import { Departments } from '../../api/assets/departments.js'; class AssetDepartmentCtrl { constructor($scope) { $scope.viewModel(this); this.subscribe('departments'); this.helpers({ departments(){ return Departments.find({}, {sort:{id:-1}}); } }); } addDepartment(newDepartment) { Session.set("newDepartment", newDepartment); /* * Execute getMaxId method, we need to do this complex logic because Mocha need fake id as input. */ Meteor.call('departments.getMaxId', function(error, result){ /* * Get item object which store in session */ var department = Session.get("newDepartment"); department.id = (parseInt(result) + 1) + ''; department.name = newDepartment.name, department.description = newDepartment.description, department.createdAt = new Date(); /* * Execute insert method which will be a different scope again. */ Meteor.call('departments.insert', department); }); } removeDepartment(id) { console.log("Remove department id: " + id); Meteor.call('departments.remove', id); } } export default angular.module('assetDepartment', [ angularMeteor ]).component('assetDepartment', { templateUrl: 'imports/components/assetDepartment/assetDepartment.html', controller: ['$scope', AssetDepartmentCtrl] });
const selectedCardsReducer = (state = [], action) => { switch (action.type) { case 'ADD_SELECTED_CARD': return [...state, action.selectedCard]; case 'ADD_SELECTED_CARDS': return [...action.selectedCards]; case 'REMOVE_SELECTED_CARD': return state.filter(card => card.id !== action.selectedCard.id); case 'REMOVE_SELECTED_CARDS': return []; default: return state; } }; export default selectedCardsReducer;
const showHeader=(headers) =>{ const tableArr= headers; const tableMain= document.getElementById("main-table"); let tableRowEle= '<tr id="table_row">'; tableArr.forEach(tableRow=>{ tableRowEle+= `<th class='${String(tableRow)}'>`+String(tableRow)+'</th>'; }); tableRowEle+= '</tr>'; tableMain.innerHTML= tableRowEle; } const showTableOnLoad = (data,check=true) =>{ if(check) showHeader(Object.keys(data[0]).map((headerString)=>headerString.toUpperCase())); const tableArr= data; const tableMain= document.getElementById("main-table"); tableArr.forEach(tableRow=>{ let tableRowEle= '<tr>'; Object.entries(tableRow).forEach(entry =>{ const [key,value]= entry; tableRowEle+= `<td class="${key}">`+ value+'</td>'; }); tableRowEle+= '</tr>' tableMain.innerHTML+= tableRowEle; }); } ( function(){ fetch('http://localhost:8080/H2HBABBA1504/fetch') .then(response=>{ return response.json() }) .then(jsonResult =>{ showTableOnLoad(jsonResult) }) .catch(error =>{ console.log(error) }) } )();
$(function () { var myChart1 = echarts.init(document.getElementById('chartOne')); var myChart2 = echarts.init(document.getElementById('chartTwo')); var option1 = { title:{ text:"设计审核进度" }, angleAxis: { type: 'category', data: ['土建专业', '机电专业', '给排水', '空调通风', '设备', '通信专业', '机电专业'], z: 10 }, radiusAxis: { }, polar: { }, series: [{ type: 'bar', data: [1, 2, 3, 4, 3, 5, 1], coordinateSystem: 'polar', name: '待审核', stack: 'a' }, { type: 'bar', data: [2, 4, 6, 1, 3, 2, 1], coordinateSystem: 'polar', name: '审核中', stack: 'a' }, { type: 'bar', data: [1, 2, 3, 4, 1, 2, 5], coordinateSystem: 'polar', name: '审核通过', stack: 'a' }], legend: { show: true, data: ['待审核', '审核中', '审核通过'] } }; var option2 = { title: { text: '任务进度统计图', subtext: '数据根据公式进行比例计算' }, tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } }, legend: { data: ['土建专业', '机电专业','给排水专业'] }, grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true }, xAxis: { type: 'value', boundaryGap: [0, 0.01] }, yAxis: { type: 'category', data: ['一审中','二审中','专家评审','业主评审','已完毕'] }, series: [ { name: '土建专业', type: 'bar', data: [18203, 29034, 104970, 131744, 630230] }, { name: '机电专业', type: 'bar', data: [19325, 31000, 121594, 134141, 681807] }, { name: '给排水专业', type: 'bar', data: [19025, 31500, 121994, 154141, 687807] } ] }; myChart1.setOption(option1); myChart2.setOption(option2); });
/** *NPM import */ import React from 'react'; import PropTypes from 'prop-types'; /** * Local import */ import CvBuilder from '../CvBuilder'; import ProfileBuilder from '../ProfileBuilder'; /* * Code */ const BackOffice = () => ( <div className="backoffice"> <ProfileBuilder /> <CvBuilder /> </div> ); /* * Export */ export default BackOffice;
import React from 'react'; import './App.css'; export default class Language extends React.Component { state = { title:"", frameworks: "", content:"" } displayLanguages = (event) => { console.log(event.target.id) if (event.target.id == "one"){ this.setState({ title: "HTML/CSS", frameworks: `Frameworks: Bootstrap, Materialize, Bulma`, content: ` The basic knowledge of most developers. This is where most of us starts in. Knowing how your website would look like and seeing how each code does to each component. ` }) } else if (event.target.id == "two") { this.setState({ title:"JavaScript", frameworks: `Frameworks: JQuery`, content: `Used heavily for DOM manipulation and using AXIOS for API applications. Having knowledge of JavaScript is useful in creating more dynamic webpages and implementing API to your webpage. ` }) } else{ this.setState({ title:"Python", frameworks: `Frameworks: Flask, Django`, content:`Used as an intermediary code to communicate between webpage and database servers. Flask allows users to navigate to other pages with a dedicated URL. With more practice, users of Flask would be able to create a fully fleshed e-commerce platform. Django however, is a more complete framework. Users of Django would not have to worry much on the design aspect as it is built for 'plug and play'. ` }) } } render (){ return( <div> <div class="tile is-ancestor box"> <div class="tile is-vertical"> <div class="tile is-parent title">Languages</div> <div class="tile"> <div class="tile is-4 is-vertical is-parent"> <div class="tile is-child box" id="one" onMouseEnter={this.displayLanguages}> <p class="title one">HTML</p> </div> <div class="tile is-child box" id="two" onMouseEnter={this.displayLanguages}> <p class="title">JavaScript</p> </div> <div class="tile is-child box" id="three" onMouseEnter={this.displayLanguages}> <p class="title">Python</p> </div> </div> <div class="tile is-parent"> <div class="tile is-child box"> <p class="title">{this.state.title}</p> <p class="subtitle">{this.state.frameworks}</p> <p>{this.state.content}</p> </div> </div> </div> </div> </div> </div> )}; }
import React, { Fragment, useEffect, useState } from "react"; import { useParams, Link, useHistory } from "react-router-dom"; import {deleteCard, readDeck, listDecks, deleteDeck} from "../utils/api/index"; function ViewDeck() { const history = useHistory(); const {deckId} = useParams(); const [currentDeck, setCurrentDeck] = useState({}); const [cards, setCards] = useState([]); const [decks, setDecks] = useState([]); useEffect(() => { const abortController = new AbortController(); async function loadDecks() { const response = await listDecks(abortController.signal); setDecks(response); } loadDecks(); return () => abortController.abort(); }, []); const deleteDeckHandler = async () => { const result = window.confirm("Are you sure you want to delete this deck?"); if (result) { await deleteDeck(deckId); const newDecks = decks.filter(deck => parseInt(deck.id) !== deckId); setDecks(newDecks); history.push("/"); } } useEffect(() => { async function loadCurrentDeck() { const response = await readDeck(deckId); setCurrentDeck(response); setCards(response.cards); } loadCurrentDeck(); }, [deckId]); const listOfCards = cards.map((card, index) => { const id = card.id; const deleteCardHandler = async () => { const result = window.confirm("Are you sure you want to delete this card?"); if (result) { await deleteCard(id); const newCards = cards.filter(card => parseInt(card.id) !== id); setCards(newCards); } } return ( <div className="container"> <div className="col-auto mb-3"> <div key={index} className="card"> <div className="card-body"> <h5 className="card-text">{card.front}</h5> <p className="card-text">{card.back}</p> <Link to={`/decks/${deckId}/cards/${id}/edit`} className="btn btn-primary mr-2">Edit Card</Link> <button onClick={deleteCardHandler} className="btn btn-danger mx-2"> Delete Card </button> </div> </div> </div> </div> ) }); return ( <Fragment> <nav aria-label="breadcrumb"> <ol className="breadcrumb"> <li className="breadcrumb-item"> <Link to="/">Home</Link> </li> <li className="breadcrumb-item"> {currentDeck.name} </li> </ol> </nav> <main className="container"> <div className="col-auto mb-3"> <div className="card"> <div className="card-body"> <h4>{currentDeck.name}</h4> <p className="card-text">{currentDeck.description}</p> <Link className="btn btn-primary mr-2" to={`/decks/${deckId}/edit`}>Edit Deck</Link> <Link className="btn btn-primary mx-2" to={`/decks/${deckId}/study`}>Study Deck</Link> <Link className="btn btn-primary mx-2" to={`/decks/${deckId}/cards/new`}>+ Add Cards</Link> <button className="btn btn-danger mx-2" onClick={deleteDeckHandler}>Delete Deck</button> </div> </div> </div> <h3 className="ml-3">Cards</h3> <section className="row">{listOfCards}</section> </main> </Fragment> ); } export default ViewDeck;
var counter=(function(){ var count=0 return { "like":function(){return ++count;}, "dislike":function(){return --count} } })()
/** * @author zhixin wen <wenzhixin2010@gmail.com> * @version 0.0.1 * @github https://github.com/wenzhixin/side-menu * @blog http://wenzhixin.net.cn */ (function($) { 'use strict'; function SideMenu($el) { this.$el = $el; } SideMenu.prototype = { constructor: SideMenu, events: function() { if (this.maxHeight > 0) { this.$scroll.show(); this.$menu.off('mousewheel').on('mousewheel', $.proxy(this.wheel, this)); this.$up.off('click').on('click', $.proxy(this.scrollUp, this)); this.$down.off('click').on('click', $.proxy(this.scrollDown, this)); } $(window).off('scroll').on('scroll', $.proxy(this.checkPosition, this)); }, init: function(options) { this.options = options; this.initViews(); this.initDatas(); this.events(); }, initViews: function() { var that = this, counts = {}, preLevel = 0; this.$menu = $([ '<div class="side-menu">', '<div class="side-catalog menu">', '<ul></ul>', '<div>', '</div>' ].join('')); this.$top = this.$menu.find('.sidebar-top'); this.$bottom = this.$menu.find('.sidebar-bottom'); this.$scroll = this.$menu.find('.side-scroll'); this.$up = this.$menu.find('.side-scroll-up'); this.$down = this.$menu.find('.side-scroll-down'); this.$catalog = this.$menu.find('.side-catalog'); this.$list = this.$menu.find('ul'); this.$el.find(this.options.hs.join(',')).each(function(i) { var $this = $(this), $div, name = $this[0].localName, title = $this.text(), level = $.inArray(name, that.options.hs) + 1, nums = [], index; if (level - preLevel > 1) { return; } if (!counts.hasOwnProperty(name) || level - preLevel === 1) { counts[name] = 0; } counts[name]++; $.each(counts, function(i) { nums.push(counts[i]); if (nums.length === level) { return false; } }); index = nums.join('.'); var idName=$(this).parents('.mtarge-box').attr('id'); $div = $('<div id="sideMenuTitle' + index + '" class="side-menu-affix"></div>'); $div.insertAfter($this).append($this); that.$list.append([ '<li data-id="sideMenuTitle' + index + '" class="menu_'+i+'">', '<a href="#' + idName + '" title="#'+idName+'">', '</a>', '</li>' ].join('')); preLevel = level; }); $(this.options.container).append(this.$menu); }, initDatas: function() { this.iScroll = 0; this.maxHeight = this.$list.outerHeight(true) - this.$catalog.outerHeight(true); }, wheel: function(event) { var oEvent = event.originalEvent, iDelta = oEvent.wheelDelta ? oEvent.wheelDelta / 120 : -oEvent.detail / 3; this.iScroll -= iDelta * 40; this.scroll(); return false; }, scrollUp: function() { this.iScroll -= 40; this.scroll(); }, scrollDown: function() { this.iScroll += 40; this.scroll(); }, scroll: function() { //this.iScroll = Math.min(this.maxHeight, Math.max(0, this.iScroll)); //this.$list.css('top', -this.iScroll); this.$up.removeClass('disabled'); this.$down.removeClass('disabled'); if (this.iScroll === 0) { this.$up.addClass('disabled'); } if (this.iScroll === this.maxHeight) { this.$down.addClass('disabled'); } }, checkPosition: function() { var $affixs = this.$el.find('.side-menu-affix'), scrollHeight = $(window).outerHeight(true), maxScrollTop = $('body').outerHeight(true) - scrollHeight, id = $affixs.first().attr('id'); var scrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop; this.$el.find('.side-menu-affix').each(function() { var $this = $(this); if (~~$this.offset().top <= scrollTop+20) { id = $this.attr('id'); } else { return false; } }); if (scrollTop >= maxScrollTop) { id = $affixs.last().attr('id'); } this.$list.find('li').removeClass('active').filter('[data-id="' + id + '"]').addClass('active'); } /** public function **/ }; $.fn.sideMenu = function() { var option = arguments[0], args = arguments, value, allowedMethods = [];// public function this.each(function() { var $this = $(this), data = $this.data('sideMenu'), options = $.extend({}, $.fn.sideMenu.defaults, typeof option === 'object' && option); if ( typeof option === 'string') { if ($.inArray(option, allowedMethods) < 0) { throw "Unknown method: " + option; } value = data[option](args[1]); } else { if (!data) { data = new SideMenu($this); data.init(options, true); $this.data('sideMenu', data); } else { data.init(options); } } }); return value ? value : this; }; $.fn.sideMenu.defaults = { container: 'body', hs: ['h2', 'h3', 'h4'] }; })(jQuery);
// pages/txl/txl.js const app = getApp() Page({ /** * 页面的初始数据 */ data: { list: [] }, getData: function() { let _this = this; wx.showLoading({ title: '加载中...', mask: true }) wx.request({ url: `${app.globalData.serverPath}/api/archives/getClassInfoList`, method: 'POST', header: app.getHeader2(), success(res) { console.log(res.data) wx.hideLoading() if (res.data.errcode === '0') { _this.setData({ list: res.data.data }) app.globalData.classArray = res.data.data;//稳定的数据保存到全局变量中 } else { wx.showToast({ icon:'none', title: res.data.errmsg, }) } }, fail(res) { wx.hideLoading() //网络异常时,提示,点击确认后继续刷新数据 wx.showModal({ title: '提示', content: '请检查您的网络' + JSON.stringify(res), showCancel: false, confirmColor: '#41B65A', success: function(res) { if(res.confirm){ _this.getData() } } }) } }) }, /** * 生命周期函数--监听页面加载 */ onLoad: function(options) { this.getData() this.getWeiduList();//获取维度list,//以备排行页面使用 }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function() { }, /** * 生命周期函数--监听页面显示 */ onShow: function() { }, /** * 生命周期函数--监听页面隐藏 */ onHide: function() { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function() { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function() { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function() { }, /** * 用户点击右上角分享 */ onShareAppMessage: function() { }, toBj: function(e) { console.log(e.currentTarget.dataset.id) // wx.setStorage({//存classid // key: 'classid', // data: e.currentTarget.dataset.id, // }) wx.navigateTo({ url: `/pages/bj/bj?id=${e.currentTarget.dataset.id}`, }) }, getWeiduList: function () { //获取维度list let _this = this; // wx.showLoading({ // title: '加载中...', // mask: true // }) wx.request({ url: `${app.globalData.serverPath}/api/dimensionality/getDimensionalitys`, method: 'POST', header: app.getHeader2(), success(res) { console.log(res.data) wx.hideLoading() if (res.data.errcode === '0') { wx.setStorageSync('weiduList', res.data.data) } else { wx.showToast({ icon: 'none', title: res.data.errmsg, }) } }, fail(res) { wx.hideLoading() wx.showToast({ icon: 'none', title: JSON.stringify(res) }) } }) }, scanCode(){ let _this = this; wx.scanCode({ onlyFromCamera: false,//可从相册获取二维码 scanType: ['qrCode'], success: function(res) { console.log(res.result) console.log(res.result.substring(0, 10)) if (res.result && (res.result.substring(0, 10) === 'studentId=')){ _this.commentbyQrcode(res.result) }else{ wx.showModal({ title: '提示', content: '你扫描的二维码内容不正确,请确认是学生的二维码', showCancel: false, confirmColor: '#41B65A', success: function (res) { } }) } }, // fail: function(res) { // wx.showToast({ // icon: 'none', // title: JSON.stringify(res) // }) // } }) }, commentbyQrcode(e){ let _this = this; wx.showLoading({ title: '加载中...', mask: true }) let nameList = []; let idList = []; //通过studentId拿学生信息 wx.request({ url: `${app.globalData.serverPath}/api/student/getStudentInfo?${e}`, header: app.getHeader2(), success(res) { console.log(res.data) wx.hideLoading() if (res.data.errcode === '0') { idList.push(res.data.data.id); nameList.push(res.data.data.user_name); wx.setStorageSync('chooseidlist', idList) wx.setStorageSync('choosenamelist', nameList) wx.navigateTo({ url: `/pages/comment/comment?classId=${res.data.data.p_class_id}` }) } else { wx.showModal({ title: '提示', content: res.data.errmsg + '你扫描的二维码内容不正确,请确认是学生的二维码', showCancel: false, confirmColor: '#41B65A', success: function(res) { } }) } }, fail(res) { wx.hideLoading() wx.showToast({ icon: 'none', title: JSON.stringify(res) }) } }) } })
'use strict' const redis = require('redis');
import json from '@rollup/plugin-json' import resolve from '@rollup/plugin-node-resolve' import commonjs from '@rollup/plugin-commonjs' import typescript from 'rollup-plugin-typescript2' import { terser } from 'rollup-plugin-terser' import clear from 'rollup-plugin-clear' import babel from 'rollup-plugin-babel' const esmPackage = { input: 'src/index.ts', output: { file: 'dist/index.esm.js', format: 'esm', name: 'shatter', sourcemap: true }, plugins: [ resolve(), commonjs({ exclude: 'node_modules' }), json(), clear({ targets: ['dist'] }), typescript({ useTsconfigDeclarationDir: true, clean: true }), babel({ extensions: [".js", ".ts"], exclude: "node_modules/**" }) ] } const cjsPackage = { input: 'src/index.ts', output: { file: 'dist/index.js', format: 'cjs', name: 'shatter', sourcemap: true }, plugins: [ resolve(), commonjs({ exclude: 'node_modules' }), json(), typescript({ tsconfigOverride: { compilerOptions: { declaration: false } } }), babel({ extensions: [".js", ".ts"], exclude: "node_modules/**" }) ] } const localDebug = { input: 'src/index.ts', output: { file: `${process.cwd()}/dist/bundle.js`, format: 'esm', name: 'shatter' }, plugins: [ resolve(), commonjs({ exclude: 'node_modules' }), json(), typescript({ tsconfigOverride: { compilerOptions: { declaration: false } } }), babel({ extensions: [".js", ".ts"], exclude: "node_modules/**" }) ] } const iifePackage = { input: 'src/index.ts', output: { file: 'build/index.min.js', format: 'iife', name: 'shatter' }, plugins: [ resolve(), commonjs({ exclude: 'node_modules' }), json(), clear({ targets: ['build'] }), typescript({ tsconfigOverride: { compilerOptions: { declaration: false } } }), terser(), babel({ extensions: [".js", ".ts"], exclude: "node_modules/**" }) ] } const examplePackage = { input: 'src/index.ts', output: { file: 'examples/shatter.js', format: 'iife', name: 'shatter' }, plugins: [ resolve(), commonjs({ exclude: 'node_modules' }), json(), typescript({ tsconfigOverride: { compilerOptions: { declaration: false } } }), babel({ extensions: [".js", ".ts"], exclude: "node_modules/**" }) ] } const total = { esmPackage, iifePackage, examplePackage, localDebug, cjsPackage } let result = total const ignore = process.env.IGNORE const include = process.env.INCLUDE console.log(`ignore: ${ignore}, include: ${include}`) if (ignore) { delete total[ignore] result = total } if (include) { result = [total[include]] } export default [...Object.values(result)]
//Copyright 2012, John Wilson, Brighton Sussex UK. Licensed under the BSD License. See licence.txt function TileMap(mapdata,tilemapResource,screenDim,tileDim) { this._posmatrix = Matrix44.Create() ; this._mapdata = mapdata ; this._resource = tilemapResource ; this._screenDim = screenDim || {width:1024,height:720}; this._screenDimX = this._screenDim.width ; this._screenDimY = this._screenDim.height ; this._tileWidth = (tileDim && tileDim.width) || 64; this._tileHeight = (tileDim && tileDim.height) || this._tileWidth ; this._mapHeight = this._mapdata.length ; this._mapWidth = this._mapdata[0].length ; this._pixelWidth = this._mapWidth * this._tileWidth ; this._pixelHeight = this._mapHeight * this._tileHeight ; this._zeroPosTable = new Array() ; // calculate tiles needed to be rendered - round up to nearest tile. var tilesDisplayWidth = Math.ceil(this._screenDimX/this._tileWidth) ; var tilesDisplayHeight = Math.ceil(this._screenDimY/this._tileHeight) ; this.tilesDisplayWidth = tilesDisplayWidth ; this.tilesDisplayHeight = tilesDisplayHeight ; // calculate screen buffer position table var tileWidth = this._tileWidth ; var tileHeight = this._tileHeight ; for (var xc = 0 ; xc <= tilesDisplayWidth ; xc++) { var xstart = xc*tileWidth ; var xend = xstart + tileWidth ; for (var yc = 0; yc <= tilesDisplayHeight ; yc++) { var ystart = yc*tileHeight ; var yend = ystart + tileHeight ; this._zeroPosTable.push({xstart: xstart, xend: xend, ystart: ystart, yend: yend}) ; } } this._posData = this._zeroPosTable ; // Image must be loaded!!!! // alert(this._resource.isLoaded()) ; // Calculate UV offsets for each mapcell frame this._tilesAcross = Math.floor(this._resource.getWidth()/this._tileWidth) ; this._tilesDown = Math.floor(this._resource.getHeight()/this._tileHeight) ; var tilesAcross = this._tilesAcross ; var tilesDown = this._tilesDown ; var qw = (1/tilesAcross) ; var qh = (1/tilesDown) ; var numFrames = tilesAcross*tilesDown ; var uvblocks = new Array() ; for (var frame = 0 ; frame < numFrames ; frame++) { var x = (frame % tilesAcross) var y = Math.floor(frame / tilesAcross) // var px = consoleFix and 1/(64) or 0 // var zeroOff = px // var oneOff = 1 - px var lx = (x+0)*qw var rx = (x+1)*qw var ty = (y+0)*qh var by = (y+1)*qh uvblocks[frame] = { x: x*tileWidth, y: y*tileHeight, width: tileWidth, height: tileHeight, pt1: {x:lx, y:ty}, pt2: {x:rx, y:ty}, pt3: {x:rx, y:by}, pt4: {x:lx, y:by}, } } this._quadTable = uvblocks ; } TileMap.Create = function(mapdata,tilemapResource,screenDim,tileWidth,tileHeight) { return new TileMap(mapdata,tilemapResource,screenDim,tileWidth,tileHeight) } TileMap.prototype = { constructor: TileMap, GetMapIndex: function(x,y) { // return this._mapdata[y][x] ; return this._mapdata[y] && this._mapdata[y][x] || 0; }, GetDimensions: function() { var pixelWidth = this._pixelWidth ; var pixelHeight = this._pixelHeight ; return {X: function() {return pixelWidth}, Y: function() {return pixelHeight}} }, updateUVTables: function (mx,my) { var uvTable = new Array(); var quadTable = this._quadTable ; var GetMapIndex = this.GetMapIndex ; var tilesDisplayWidth = this.tilesDisplayWidth ; var tilesDisplayHeight = this.tilesDisplayHeight ; for (var x = 0 ; x <= tilesDisplayWidth ; x++) { var xpos = x + mx ; for (var y = 0 ; y <= tilesDisplayHeight ; y++) { var ypos = y + my ; var uvEntry = quadTable[this.GetMapIndex(xpos,ypos)] ; uvTable.push(uvEntry) ; } } this._uvData = uvTable ; }, Render: function(rHelper,tx,ty) { var newMapX = Math.floor(tx / this._tileWidth) ; var newMapY = Math.floor(ty / this._tileHeight) ; var fineX = tx % this._tileWidth ; var fineY = ty % this._tileHeight ; this.updateUVTables(newMapX,newMapY) ; this._posmatrix.SetTranslation(-fineX,-fineY,0,MATRIX_REPLACE) ; this._posmatrix.SetScale(1,1,1,1) ; rHelper.drawQuads2d(this._resource.getImage(),this._posmatrix,this._posData,this._uvData,fineX,fineY) ; }, toString: function() { return "TileMap" ; } }
var searchData= [ ['okienka',['okienka',['../namespaceokienka.html',1,'']]] ];
// !Levels Grid StudentCentre.grid.AttendanceLevels = function(config) { config = config || {}; Ext.applyIf(config,{ id: 'studentcentre-grid-attendance-levels' ,url: StudentCentre.config.connectorUrl ,baseParams: { action: 'mgr/attendance/scClassLevelGetList' ,sortByOrder: 1 } ,fields: ['id', 'class_level_category_id', 'category_name', 'name', 'description', 'hours_required', 'test_threshold', 'order', 'active'] ,paging: true ,remoteSort: true ,sortBy: 'category_name' ,anchor: '97%' ,autoExpandColumn: 'name' ,grouping: true ,groupBy: 'category_name' ,pluralText: 'Levels' ,singleText: 'Level' ,save_action: 'mgr/attendance/scClassLevelUpdateFromGrid' ,autosave: true ,columns: [{ header: _('studentcentre.id') ,hidden: true ,dataIndex: 'id' ,name: 'id' },{ header: _('studentcentre.id') ,hidden: true ,dataIndex: 'class_level_category_id' ,name: 'class_level_category_id' },{ header: _('studentcentre.att_level_category') ,dataIndex: 'category_name' ,name: 'category_name' ,sortable: true ,width: 100 },{ header: _('studentcentre.name') ,dataIndex: 'name' ,name: 'name' ,sortable: true ,width: 100 ,editor: { xtype: 'textfield' } },{ header: _('studentcentre.description') ,dataIndex: 'description' ,name: 'description' ,sortable: true ,width: 100 ,editor: { xtype: 'textfield' } },{ header: _('studentcentre.att_hours_required') ,dataIndex: 'hours_required' ,name: 'hours_required' ,sortable: true ,width: 100 ,editor: { xtype: 'numberfield' } },{ header: _('studentcentre.att_test_threshold') ,dataIndex: 'test_threshold' ,name: 'test_threshold' ,sortable: true ,width: 100 ,editor: { xtype: 'numberfield' } },{ header: _('studentcentre.order') ,dataIndex: 'order' ,name: 'order' ,sortable: true ,width: 100 ,editor: { xtype: 'numberfield' } },{ header: _('studentcentre.active') ,dataIndex: 'active' ,sortable: true ,width: 50 // below xtype defined in attendancelevelcategories.grid.js ,editor: { xtype: 'attendance-combo-active-status', renderer: true} }] ,tbar:[{ xtype: 'button' ,id: 'attendance-create-level-button' ,text: _('studentcentre.att_create_level') ,handler: { xtype: 'studentcentre-window-level-create', blankValues: true } },{ xtype: 'button' ,id: 'attendance-update-level-button' ,text: _('studentcentre.update') ,listeners: { 'click': {fn: this.updateLevel, scope: this} } },{ xtype: 'button' ,id: 'attendance-level-active-toggle-button' ,text: _('studentcentre.toggle_active_status') ,handler: function(btn,e) { this.toggleActive(btn,e); } ,scope: this },'->',{ // This defines the toolbar for the search xtype: 'textfield' // Here we're defining the search field for the toolbar ,id: 'level-search-filter' ,emptyText: _('studentcentre.search...') ,listeners: { 'change': {fn:this.search,scope:this} ,'render': {fn: function(cmp) { new Ext.KeyMap(cmp.getEl(), { key: Ext.EventObject.ENTER ,fn: function() { this.fireEvent('change',this); this.blur(); return true; } ,scope: cmp }); },scope:this} } },{ xtype: 'button' ,id: 'clear-level-search' ,text: _('studentcentre.clear_search') ,listeners: { 'click': {fn: this.clearSearch, scope: this} } }] }); StudentCentre.grid.AttendanceLevels.superclass.constructor.call(this,config) }; Ext.extend(StudentCentre.grid.AttendanceLevels,MODx.grid.Grid,{ search: function(tf,nv,ov) { var s = this.getStore(); s.baseParams.query = tf.getValue(); this.getBottomToolbar().changePage(1); this.refresh(); } ,clearSearch: function() { this.getStore().baseParams = { action: 'mgr/attendance/scClassLevelGetList' }; Ext.getCmp('level-search-filter').reset(); this.getBottomToolbar().changePage(1); this.refresh(); } ,getMenu: function() { // MODX looks for getMenu when someone right-clicks on the grid return [{ text: _('studentcentre.update') ,handler: this.updateLevel },'-',{ text: _('studentcentre.toggle_active_status') ,handler: this.toggleActive }]; } ,updateLevel: function(btn,e) { var selRow = this.getSelectionModel().getSelected(); if (selRow.length <= 0) return false; //console.log(selRow.data); if (!this.updateLevelWindow) { this.updateLevelWindow = MODx.load({ xtype: 'sc-window-level-update' ,record: selRow.data ,listeners: { 'success': { fn:function(r){ this.refresh(); this.getSelectionModel().clearSelections(true); },scope:this } } }); } this.updateLevelWindow.setValues(selRow.data); this.updateLevelWindow.show(e.target); } ,toggleActive: function(btn,e) { var selRow = this.getSelectionModel().getSelected(); if (selRow.length <= 0) return false; MODx.Ajax.request({ url: this.config.url ,params: { action: 'mgr/attendance/scClassLevelUpdate' ,id: selRow.data.id ,toggleActive: 1 } ,listeners: { 'success': {fn:function(r) { this.refresh(); Ext.getCmp('studentcentre-grid-attendance-levels').refresh(); },scope:this} } }); return true; } }); Ext.reg('studentcentre-grid-attendance-levels',StudentCentre.grid.AttendanceLevels); // !Level Category Name Active Combobox StudentCentre.combo.LevelGridCategoryName = function(config) { config = config || {}; Ext.applyIf(config, { id: 'attendance-combo-level-category-name' ,fieldLabel: _('studentcentre.att_level_category') ,name: 'name' ,width: 300 ,hiddenName: 'category_id' ,hiddenValue: '' ,emptyText: 'Select category...' ,typeAhead: true ,valueField: 'id' ,displayField: 'name' ,fields: ['id', 'name'] ,url: StudentCentre.config.connectorUrl ,baseParams: { action: 'mgr/attendance/scClassLevelCategoryGetList' ,activeOnly: 1 } }); StudentCentre.combo.LevelGridCategoryName.superclass.constructor.call(this, config); }; Ext.extend(StudentCentre.combo.LevelGridCategoryName, MODx.combo.ComboBox); Ext.reg('attendance-combo-level-category-name', StudentCentre.combo.LevelGridCategoryName); // !Create Level Window StudentCentre.window.CreateLevel = function(config) { config = config || {}; Ext.applyIf(config,{ title: _('studentcentre.att_create_level') ,width: '400' ,url: StudentCentre.config.connectorUrl ,labelAlign: 'left' ,baseParams: { action: 'mgr/attendance/scClassLevelCreate' } ,fields: [{ xtype: 'attendance-combo-level-category-name' ,id: 'attendance-combo-create-level-category-name' ,fieldLabel: _('studentcentre.att_level_category') ,name: 'class_level_category_id' ,hiddenName: 'class_level_category_id' ,anchor: '100%' },{ xtype: 'textfield' ,fieldLabel: _('studentcentre.name') ,name: 'name' ,anchor: '100%' },{ xtype: 'textfield' ,fieldLabel: _('studentcentre.description') ,name: 'description' ,anchor: '100%' },{ xtype: 'numberfield' ,fieldLabel: _('studentcentre.att_hours_required') ,name: 'hours_required' ,anchor: '100%' },{ xtype: 'numberfield' ,fieldLabel: _('studentcentre.att_test_threshold') ,name: 'test_threshold' ,anchor: '100%' },{ xtype: 'numberfield' ,fieldLabel: _('studentcentre.order') ,name: 'order' ,anchor: '100%' }] }); StudentCentre.window.CreateLevel.superclass.constructor.call(this,config); }; Ext.extend(StudentCentre.window.CreateLevel,MODx.Window); Ext.reg('studentcentre-window-level-create',StudentCentre.window.CreateLevel); // !Update Update Window StudentCentre.window.UpdateLevel = function(config) { config = config || {}; Ext.applyIf(config,{ title: _('studentcentre.att_update_level') ,width: '400' ,url: StudentCentre.config.connectorUrl ,labelAlign: 'left' ,baseParams: { action: 'mgr/attendance/scClassLevelUpdate' } ,fields: [{ xtype: 'hidden' ,name: 'id' },{ xtype: 'attendance-combo-level-category-name' ,id: 'attendance-combo-update-level-category-name' ,fieldLabel: _('studentcentre.att_level_category') ,name: 'class_level_category_id' ,hiddenName: 'class_level_category_id' ,anchor: '100%' ,baseParams: { action: 'mgr/attendance/scClassLevelCategoryGetList' } },{ xtype: 'textfield' ,fieldLabel: _('studentcentre.name') ,name: 'name' ,anchor: '100%' },{ xtype: 'textfield' ,fieldLabel: _('studentcentre.description') ,name: 'description' ,anchor: '100%' },{ xtype: 'numberfield' ,fieldLabel: _('studentcentre.att_hours_required') ,name: 'hours_required' ,anchor: '100%' },{ xtype: 'numberfield' ,fieldLabel: _('studentcentre.att_test_threshold') ,name: 'test_threshold' ,anchor: '100%' },{ xtype: 'numberfield' ,fieldLabel: _('studentcentre.order') ,name: 'order' ,anchor: '100%' },{ xtype: 'attendance-combo-active-status' ,fieldLabel: _('studentcentre.active') ,name: 'active' ,hiddenName: 'active' ,anchor: '100%' }] }); StudentCentre.window.UpdateLevel.superclass.constructor.call(this,config); }; Ext.extend(StudentCentre.window.UpdateLevel,MODx.Window); Ext.reg('sc-window-level-update',StudentCentre.window.UpdateLevel);
import React, {Component} from 'react'; import DialogTitle from "@material-ui/core/DialogTitle"; import DialogContent from "@material-ui/core/DialogContent"; import DialogContentText from "@material-ui/core/DialogContentText"; import Button from "@material-ui/core/Button"; import DialogActions from "@material-ui/core/DialogActions"; import withStyles from "../../../../node_modules/@material-ui/core/styles/withStyles"; import {styles} from "../../AdminRoom/AddingSection/addingSectionStyles-material-ui"; import TestDb from './TestDb.png'; import './TestQuestionForm.css'; import {Alert} from "react-bootstrap"; class TestQuestionForm extends Component { state = { input: '' }; render() { const {classes} = this.props; let input = ''; return ( <form className={classes.container} onSubmit={this.props.addTest}> <DialogTitle> Выберите файл в формате csv </DialogTitle> <DialogContent> <div className="ExplanationBox"> <DialogContentText margin="dense" > В файле должна быть таблица из одной колонки вопросов. В первой строке должно быть название колонки –– body. Примерно так: <label htmlFor="flat-button-file"> <Button variant="contained" component="file" > Выберите файл формата csv </Button> </label> <input id="flat-button-file" multiple type="file" accept=".csv" name={'data'} onChange={(event) => { this.props.fileChangeHandler(event); input = event.target.value; this.setState({input}) }} required={true} /> {this.state.input ? <Alert bsStyle="success">Вы выбрали файл! Спасибо)</Alert> : <Alert bsStyle="danger">Выберите файл!</Alert>} </DialogContentText> <img src={TestDb} alt={'Пример загружаемого файла'}/> </div> </DialogContent> <DialogActions> <Button size='large' variant="contained" color="primary" type="submit" className={classes.button} disabled={!this.state.input} > Далее </Button> </DialogActions> </form> ) } } export default withStyles(styles)(TestQuestionForm);
var functions________________f________8js____8js__8js_8js = [ [ "functions________f____8js__8js_8js", "functions________________f________8js____8js__8js_8js.html#a97edd0d6ca77fccb530997207ffa4106", null ] ];
import Jumbotron from 'react-bootstrap/Jumbotron' import 'bootstrap/dist/css/bootstrap.min.css'; import './App.css'; import { GamerTag } from './components' import axios from "axios"; const options = { method: 'GET', url: 'https://call-of-duty-modern-warfare.p.rapidapi.com/warzone/javim1224/psn', headers: { 'x-rapidapi-key': '366d011c92msh40d6527334090abp15e5cdjsn5aa2270f3b82', 'x-rapidapi-host': 'call-of-duty-modern-warfare.p.rapidapi.com' } }; axios.request(options).then(function (response) { console.log(response.data); }).catch(function (error) { console.error(error); }); function App() { return ( <div className="App"> <Jumbotron> <h1>Call of Duty Warzone Stat Tracker!</h1> </Jumbotron> <GamerTag /> </div> ); } export default App;
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ function validateNames() { document.getElementById("fNameErr").style.visibility = "hidden"; document.getElementById("lNameErr").style.visibility = "hidden"; var fname = document.getElementById("fName").value; var lname = document.getElementById("lName").value; var regex = /^[a-zA-Z][a-zA-Z ]{0,29}$/; if (!regex.test(fname)) { document.getElementById("fNameErr").style.visibility = "visible"; if(!regex.test(lname)) { document.getElementById("lNameErr").style.visibility = "visible"; } return false; } else if (!regex.test(lname)) { document.getElementById("lNameErr").style.visibility = "visible"; return false; } return true; } function validateEmail() { document.getElementById("eMailErr").style.visibility = "hidden"; var regex = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/; if (regex.test(document.getElementById("eMail").value)) { return true; } else { document.getElementById("eMailErr").style.visibility = "visible"; return false; } } function validateTel() { document.getElementById("telNoErr").style.visibility = "hidden"; var regex = /^\d{10}$/; var phoneNo = document.getElementById("telNo").value; if(phoneNo.match(regex)) { return true; } else { document.getElementById("telNoErr").style.visibility = "visible"; return false; } } function validatePass() { document.getElementById("pswdErr").style.visibility = "hidden"; var pass = document.getElementById("pswd").value; if(pass < 6) { document.getElementById("pswdErr").style.visibility = "visible"; return false; } else { return true; } } function validateEmail() { document.getElementById("EmailErr").style.visibility = "hidden"; var Email = document.getElementById("Email").value; if(!Email) { document.getElementById("EmailErr").style.visibility = "visible"; return false; } return true; } function superValidate() { var test = validateNames()& validateEmail() & validateTel() & validatePass() & validateEmail(); if(test) return true; else return false; }
'use strict'; angular.module('spedycjacentralaApp') .controller('TransporterInfoController', function ($scope, $state, $modal, TransporterInfo, ParseLinks) { $scope.transporterInfos = []; $scope.page = 0; $scope.loadAll = function() { TransporterInfo.query({page: $scope.page, size: 20}, function(result, headers) { $scope.links = ParseLinks.parse(headers('link')); $scope.transporterInfos = result; }); }; $scope.loadPage = function(page) { $scope.page = page; $scope.loadAll(); }; $scope.loadAll(); $scope.refresh = function () { $scope.loadAll(); $scope.clear(); }; $scope.clear = function () { $scope.transporterInfo = { type: null, model: null, make: null, year: null, id: null }; }; });
// import React from "react"; // import Footer from "../footer"; // const homeStyle = { // border: "2px black solid", // width: "50%", // margin: "0 auto", // marginBottom: "20px", // padding: "20px", // textAlign: "center", // borderRadius: "10px", // boxShadow: "10px 10px 10px black", // }; // export default function Home() { // return ( // <div> // <div style={homeStyle}> // <h1>Creating a Stronger Online Presence</h1> // <p> // We are a new kind of software company. The kind that focuses on your // business needs and goals. We focus on software solutions that generate // revenue, reduce costs, and increase overall productivity. We are // business first. Contact us for a free business evaluation. // </p> // </div> // <div> // <Footer /> // </div> // </div> // ); // }
import $ from 'jquery'; import paper from 'paper'; import {closePath} from './_shapes.js'; import {app, tool} from './_settings.js'; import {selectLayer} from './_layers.js'; import clearLayer from './_clear.js'; import remodal from 'remodal'; export default function shortcuts() { tool.onKeyDown = function(event) { event.preventDefault(); if (event.key === "backspace") { if (app.currentPath && !app.currentPath.isEmpty()) { app.currentPath.removeSegment(app.currentPath.lastSegment.index); } } else if (event.key === "space") { // console.log(paper.project.activeLayer); } else if (event.key === "enter") { closePath(); } else if (event.key === "1") { selectLayer('layer1'); } else if (event.key === "2") { selectLayer('layer2'); } else if (event.key === "3") { selectLayer('layer3'); } else if (event.key === "4") { selectLayer('layer4'); } else if (event.key === "0") { selectLayer('layerBg'); } else if (event.modifiers.shift && event.key === "n") { var clearAllConfirm = confirm("Are you sure you want to start new?"); if (clearAllConfirm == true) { clearLayer('layer1'); clearLayer('layer2'); clearLayer('layer3'); clearLayer('layer4'); selectLayer('layer4'); } } else if (event.modifiers.shift && event.key === "l") { var clearConfirm = confirm("Reset layer?"); if (clearConfirm == true) { clearLayer(paper.project.activeLayer.name); } } else if (event.modifiers.shift && event.key === "e") { canvasExport(); } else if (event.key === "q") { selectLayer('layer1'); $('[data-remodal-id=modal]').remodal().open(); } else if (event.key === "w") { selectLayer('layer2'); $('[data-remodal-id=modal]').remodal().open(); } else if (event.key === "e") { selectLayer('layer3'); $('[data-remodal-id=modal]').remodal().open(); } else if (event.key === "r") { selectLayer('layer4'); $('[data-remodal-id=modal]').remodal().open(); } else if (event.key === "p") { selectLayer('layerBg'); $('[data-remodal-id=modal]').remodal().open(); } else if (event.key === "c") { app.tool = "free"; $('.lassoPoly').removeClass("active"); $('.lassoFree').addClass("active"); } else if (event.key === "v") { app.tool = "poly"; $('.lassoFree').removeClass("active"); $('.lassoPoly').addClass("active"); } }; }
// https://js.checkio.org/station/library/ /* 20171116 SAY HI https://py.checkio.org/mission/say-history/ (NOT IN THE LIST OF JS EXERCISES) In this mission you should write a function that introduce a percone with a given parameters in attributes. Input: Two arguments. String and positive integer. Output: String. Example: say_hi("Alex", 32) == "Hi. My name is Alex and I'm 32 years old" say_hi("Frank", 68) == "Hi. My name is Frank and I'm 68 years old" */ //commas do not work in return. only in console.log. Solution with + function sayHi(name, int) { return("Hi, My name is " + name + " and I'm " + int.toString() + " years old") } //Solution with backticks `` function sayHi(name, int) { return(`Hi, My name is ${name}, and I'm, ${int.toString()} years old`); } /* 20171126 CORRECT SENTENCE https://py.checkio.org/mission/correct-sentence/ (NOT IN THE LIST OF JS EXERCISES) For the input of your function will be given one sentence. You have to return its fixed copy in a way so it’s always starts with a capital letter and ends with a dot. Pay attention to the fact that not all of the fixes is necessary. If a sentence already ends with a dot then adding another one will be a mistake. Input: A string. Output: A string. Example: correct_sentence("greetings, friends") == "Greetings, friends." correct_sentence("Greetings, friends") == "Greetings, friends." correct_sentence("Greetings, friends.") == "Greetings, friends." */ function correctSentence(str){ return str[str.length - 1] !== "." ? str[0].toUpperCase() + str.slice(1).toLowerCase() + "." : str[0].toUpperCase() + str.slice(1).toLowerCase() } /* 20171116 FIRST WORD https://py.checkio.org/mission/first-word/ You are given a string where you have to find its first word. When solving a task pay attention to the following points: There can be dots and commas in a string. A string can start with a letter or, for example, a dot or space. A word can contain an apostrophe and it's a part of a word. The whole text can be represented with one word and that's it. Input: A string. Output: A string. Example: first_word("Hello world") == "Hello" first_word("greetings, friends") == "greetings" How it is used: the first word is a command in a command line Precondition: the text can contain a-z A-Z , . ' */ function firstWord(str){ let punctuations = [",", ".", " "] while (punctuations.indexOf(str[0]) !== -1) str = str.slice(1); for(let i = 0; i < str.length; i++){ if (punctuations.indexOf(str[i]) !== -1) return str.slice(0, i); } return str; } // 20171206 function firstWord(str){ return str.remove(/[. ,]/g, " ").trim().split(" ")[0] } /* SECOND INDEX https://py.checkio.org/mission/second-index/ You are given two strings and you have to find an index of the second occurrence of the second string in the first one. Let's go through the first example where you need to find the second occurrence of "s" in a word "sims". It’s easy to find its first occurrence with a function index or find which will point out that "s" is the first symbol in a word "sims" and therefore the index of the first occurrence is 0. But we have to find the second "s" which is 4th in a row and that means that the index of the second occurrence (and the answer to a question) is 2. Input: Two strings. Output: Int or None Example: second_index("sims", "s") == 3 second_index("find the river", "e") == 12 second_index("hi", " ") == null second_index("hi mayor"," ") == null */ function secondIndex(str, symbol){ if(str.indexOf(symbol) === -1 || str.indexOf(symbol, str.indexOf(symbol) + 1) === -1) return null; return(str.indexOf(symbol, str.indexOf(symbol) + 1)); } //second parameter in the indexOf is for (from index) /* BETWEEN MARKERS https://py.checkio.org/mission/between-markers/ You are given a string and two markers (the initial and final). You have to find a substring enclosed between these two markers. But there are a few important conditions: The initial and final markers are always different. The text must be found only between the first instances of the marker. If there is no initial marker then the beginning should be considered as the beginning of a string. If there is no final marker then the ending should be considered as the ending of a string. If the initial and final markers are missing then simply return the whole string. If the final marker is standing in front of the initial one then return an empty string. Input: Three arguments. All of them are strings. The second and third arguments are the initial and final markers. Output: A string. Example: between_markers('What is >apple<', '>', '<') == 'apple' between_markers('No[/b] hi', '[b]', '[/b]') == 'No' How it is used: for parsing texts Precondition: can't be more than one marker */ function betweenMarkers(str, init, final) { if str.indexOf(init) !== -1 and str.indexOf(final) !== -1 return ""; let startStr = str.split(final)[0]; let endStr = startStr.split(init); return endStr[endStr.length - 1]; } /*20170731 FIZZ BUZZ https://js.checkio.org/mission/fizz-buzz/ "Fizz buzz" is a word game we will use to teach the robots about division. Let's learn computers. You should write a function that will receive a positive integer and return: "Fizz Buzz" if the number is divisible by 3 and by 5; "Fizz" if the number is divisible by 3; "Buzz" if the number is divisible by 5; The number as a string for other cases. Input: A number as an integer. Output: The answer as a string. Example: fizzBuzz(15) == "Fizz Buzz" fizzBuzz(6) == "Fizz" fizzBuzz(5) == "Buzz" fizzBuzz(7) == "7" */ function fizzBuzz(num) { let result = num % 3 === 0 && num % 5 === 0 ? "Fizz Buzz" : num % 3 === 0 ? "Fizz" : num % 5 === 0 ? "Buzz" : num.toString(); return result; } //20171111 function fizzBuzz(num) { return num % 3 === 0 && num % 5 === 0 ? "Fizz Buzz" : num % 3 === 0 ? "Fizz" : num % 5 === 0 ? "Buzz" : num.toString(); } /*20170731 EVEN THE LAST https://js.checkio.org/mission/even-last/ You are given an array of integers. You should find the sum of the elements with even indexes (0th, 2nd, 4th...) then multiply this summed number and the final element of the array together. Don't forget that the first element has an index of 0. For an empty array, the result will always be 0 (zero). Input: A list of integers. Output: The number as an integer. Example: evenLast([0, 1, 2, 3, 4, 5]) == 30 evenLast([1, 3, 5]) == 30 evenLast([6]) == 36 evenLast([]) == 0 */ function evenLast(array) { if (array.length === 0) return 0; let sumOfEvenIndexes = 0; for (var i = 0; i < array.length; i++) { i % 2 === 0 ? sumOfEvenIndexes += array[i] : null; } return sumOfEvenIndexes * array[array.length - 1]; } //20171115 function evenLast(arr){ if(arr.length === 0) return 0; return arr.reduce((accumulator, currentValue, currentIndex) => { return currentIndex % 2 === 0 ? accumulator + currentValue : accumulator }, 0) * arr[arr.length - 1]; } //solution from the internet function evenLast(data) { return data.filter((item, i) => i % 2 == 0).reduce((prev, cur) => prev + cur, 0) * data[data.length - 1] || 0; } /*20170731 SECRET MESSAGE https://js.checkio.org/mission/secret-message/ "Where does a wise man hide a leaf? In the forest. But what does he do if there is no forest? ... He grows a forest to hide it in." -- Gilbert Keith Chesterton Ever tried to send a secret message to someone without using the postal service? You could use newspapers to tell your secret. Even if someone finds your message, it's easy to brush them off and that its paranoia and a bogus conspiracy theory. One of the simplest ways to hide a secret message is to use capital letters. Let's find some of these secret messages. You are given a chunk of text. Gather all capital letters in one word in the order that they appear in the text. For example: text = "How are you? Eh, ok. Low or Lower? Ohhh.", if we collect all of the capital letters, we get the message "HELLO". Input: A text as a string (unicode). Output: The secret message as a string or an empty string. Example: findMessage("How are you? Eh, ok. Low or Lower? Ohhh.") == "HELLO" findMessage("hello world!") == "" */ function findMessage(string) { let secretMessage = ""; let alphabetCapitals = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']; for (let value of string) { alphabetCapitals.indexOf(value) !== -1 ? secretMessage += value : null; } return secretMessage; } function findMessage(string) { return string.replace(/[^A-Z]/g, ""); } //solution from the internet function findMessage(data) { return data.replace(/[^A-Z]/g, ''); } /*20170801 THREE WORDS https://js.checkio.org/mission/three-words/ Let's teach the Robots to distinguish words and numbers. You are given a string with words and numbers separated by whitespaces (one space). The words contains only letters. You should check if the string contains three words in succession. For example, the string "start 5 one two three 7 end" contains three words in succession. Input: A string with words. Output: The answer as a boolean. Example: threeWords("Hello World hello") == True threeWords("He is 123 man") == False threeWords("1 2 3 4") == False threeWords("bla bla bla bla") == True threeWords("Hi") == False */ function threeWords(string) { let splitString = string.toLowerCase().split(' '); let alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']; let counter = 0; for (let value of splitString) { alphabet.indexOf(value.slice(0,1)) !== -1 ? counter += 1 : counter = 0; if (counter >= 3) return true; } return false; } //online solution function threeWords(data) { return /\D+\s\D+\s\D+/.test(data); } /* 20170801 INDEX POWER https://js.checkio.org/mission/index-power/ You are given an array with positive numbers and a number N. You should find the N-th power of the element in the array with the index N. If N is outside of the array, then return -1. Don't forget that the first element has the index 0. Let's look at a few examples: - array = [1, 2, 3, 4] and N = 2, then the result is 32 == 9; - array = [1, 2, 3] and N = 3, but N is outside of the array, so the result is -1. Input: Two arguments. An array as a list of integers and a number as a integer. Output: The result as an integer. Example: indexPower([1, 2, 3, 4], 2) == 9 indexPower([1, 3, 10, 100], 3) == 1000000 indexPower([0, 1], 0) == 1 indexPower([1, 2], 3) == -1 */ function indexPower(arr, num) { if (num > arr.length - 1) return -1; return Math.pow(arr[num], num); } function indexPower(arr, num) { return num > arr.length - 1 ? -1 : Math.pow(arr[num], num); } //from the internet function indexPower(array, n){ return Math.pow(array[n],n) || -1; } /*20170802 THE MOST NUMBERS https://js.checkio.org/mission/most-numbers/ Let's work with numbers. You are given an array of numbers (floats). You should find the difference between the maximum and minimum element. Your function should be able to handle an undefined amount of arguments. For an empty argument list, the function should return 0. Floating-point numbers are represented in computer hardware as base 2 (binary) fractions. So we should check the result with ±0.001 precision. Think about how to work with an arbitrary number of arguments. Input: An arbitrary number of arguments as numbers (int, float). Output: The difference between maximum and minimum as a number (int, float). Example: mostNumbers(1, 2, 3) == 2 mostNumbers(5, -5) == 10 mostNumbers(10.2, -2.2, 0, 1.1, 0.5) == 12.4 mostNumbers() == 0 */ function mostNumbers(args) { let max = -Infinity; let min = +Infinity; if (arguments.length === 0) return 0; for (var i = 0; i < arguments.length; i++) { if (min > arguments[i]) min = arguments[i]; if (max < arguments[i]) max = arguments[i]; } return max - min; } function mostNumbers(args) { return arguments.length === 0 ? 0 : Math.max(...arguments) - Math.min(...arguments); } /*20170803 DIGITS MULTIPLICATION https://js.checkio.org/mission/digits-multiplication/ You are given a positive integer. Your function should calculate the product of the digits excluding any zeroes. For example: The number given is 123405. The result will be 1*2*3*4*5=120 (don't forget to exclude zeroes). Input: A positive integer. Output: The product of the digits as an integer. digitsMultip(123405) == 120 digitsMultip(999) == 729 digitsMultip(1000) == 1 digitsMultip(1111) == 1 */ function digitsMultip(num) { let numToArr = num.toString().split(''); console.log(numToArr); return numToArr .filter((ele) => { return Number(ele) !== 0 }) .reduce((product, value) => { return product * Number(value); }, 1); } function digitsMultip(num) { let numToArr = num.toString().split(''); let result = 1; for (let value of numToArr) { if (Number(value) !== 0) result *= value; } return result; } /*20170803 COUNT INVERSION https://js.checkio.org/mission/count-inversions/ In computer science and discrete mathematics, an inversion is a pair of places in a sequence where the elements in these places are out of their natural order. So, if we use ascending order for a group of numbers, then an inversion is when larger numbers appear before lower number in a sequence. Check out this example sequence: (1, 2, 5, 3, 4, 7, 6) and we can see here three inversions - 5 and 3; - 5 and 4; - 7 and 6. You are given a sequence of unique numbers and you should count the number of inversions in this sequence. Input: A sequence as a tuple of integers. Output: The inversion number as an integer. Example: countInversion([1, 2, 5, 3, 4, 7, 6]) == 3 countInversion([0, 1, 2, 3]) == 0 */ function countInversion(array) { let counter = 0; while (array.length > 1) { let compare = array.shift(); for (let value of array) { if (value < compare) counter += 1; } } return counter; } /*20170803 COMMON WORDS https://js.checkio.org/mission/common-words/ Let's continue examining words. You are given two string with words separated by commas. Try to find what is common between these strings. The words are not repeated in the same string. Your function should find all of the words that appear in both strings. The result must be represented as a string of words separated by commas in alphabetic order. Input: Two arguments as strings. Output: The common words as a string. Example: commonWords("hello,world", "hello,earth") == "hello" commonWords("one,two,three", "four,five,six") == "" commonWords("one,two,three", "four,five,one,two,six,three") == "one,three,two" */ function commonWords(str1, str2) { let str1Arr = str1.split(','); let str2Arr = str2.split(','); let result = []; for (let value of str1Arr){ if (str2Arr.indexOf(value) !== -1) result.push(value); } return result.sort().join(','); } function commonWords(str1, str2) { let str1Arr = str1.split(','); let str2Arr = str2.split(','); let result = []; for (let value of str1Arr){ if (str2Arr.includes(value)) result.push(value); } return result.sort().join(','); } //solution from the internet function commonWords(first, second) { return first.split(","). filter(x => second.split(",").includes(x)).sort().join(","); } /*20170807 ABSOLUTE SORTING https://js.checkio.org/mission/absolute-sorting/ Let's try some sorting. Here is an array with the specific rules. The array has various numbers. You should sort it, but sort it by absolute value in ascending order. For example, the sequence (-20, -5, 10, 15) will be sorted like so: (-5, 10, 15, -20). Your function should return the sorted list . Precondition: The numbers in the array are unique by their absolute values. Input: An array of numbers . Output: The list or tuple (but not a generator) sorted by absolute values in ascending order. Addition: The result of your function will be shown as a list in the tests explanation panel. Example: Note from Paris: These examples are typed like the arrays are for Java and not Javascript. Instead of absoluteSorting((-20, -5, 10, 15)) it should be absoluteSorting([-20, -5, 10, 15]) absoluteSorting((-20, -5, 10, 15)) == [-5, 10, 15, -20] # or (-5, 10, 15, -20) absoluteSorting((1, 2, 3, 0)) == [0, 1, 2, 3] absoluteSorting((-1, -2, -3, 0)) == [0, -1, -2, -3] */ function absoluteSorting(array) { return array.sort((a, b) => Math.abs(a) - Math.abs(b)); } /*20170807 NUMBER BASE https://js.checkio.org/mission/number-radix/ Do you remember the radix and Numeral systems from math class? Let's practice with it. You are given a positive number as a string along with the radix for it. Your function should convert it into decimal form. The radix is less than 37 and greater than 1. The task uses digits and the letters A-Z for the strings. Watch out for cases when the number cannot be converted. For example: "1A" cannot be converted with radix 9. For these cases your function should return -1. Input: Two arguments. A number as string and a radix as an integer. Output: The converted number as an integer. Example: numberRadix("AF", 16) == 175 numberRadix("101", 2) == 5 numberRadix("101", 5) == 26 numberRadix("Z", 36) == 35 numberRadix("AB", 10) == -1 Precondition: re.match("\A[A-Z0-9]\Z", str_number) 0 < len(str_number) ≤ 10 2 ≤ radix ≤ 36 */ //Incomplete solution function numberRadix(str, num) { return isNaN(parseInt(str, num)) ? -1 : parseInt(str, num); } /* The following solution is working after I added the if statement based on the following paragraph from MDN (for parseInt()): If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point. parseInt truncates numbers to integer values. Leading and trailing spaces are allowed. */ function numberRadix(str, num) { for (var i = 0; i < str.length; i++) { if (isNaN(parseInt(str[i], num))) return -1; } return isNaN(parseInt(str, num)) ? -1 : parseInt(str, num); } //online solution - In the return line, the guy returns the ps_int result IF // ps_int === true (if NaN it will return false) and // if the first parameter (str_number) equals the result of ps_int inverter to // a string ps_int.toString(radix) function numberRadix(str_number, radix){ const ps_int = parseInt(str_number, radix); const ts_int = ps_int.toString(radix); ​ return ps_int && str_number.toLowerCase() === ts_int ? ps_int : -1; }
import React, { Component } from 'react' class Project extends Component { render() { const { project } = this.props return ( <article className="pt5 w-100"> <a href={project.url} className="db f3 dark-gray lh-title underline-hover" target="_blank"> {project.title} </a> <p className="f5 mt2 mb4 mid-gray lh-copy">{project.description}</p> </article> ) } } export default Project
/* 输入链表,从尾到头打印链表每个节点值 */ /* function ListNode(x) { this.val = x; this.next = null; }*/ function printListFromTailToHead(head) { var arr = [] while (1) { if (!head) break; arr.push(head.val) head = head.next } return arr.reverse() } // console.log(printListFromTailToHead({})) // 16ms 5212k
const { checkSchema } = require('express-validator/check'); /** * Validation for the query, param or POST body */ /****************** * AUTH ***************/ export const Auth = { // POST /api/auth/login login: { email: { // The location of the field, can be one or more of body, cookies, headers, params or query. // If omitted, all request locations will be checked in: ['body'], errorMessage: 'User email is wrong', isEmail: true, // Sanitizers can go here as well toEmail: true }, password: { in: ['body'], errorMessage: 'User password must be defined', exists: true, isString: true, toString: true } } }; /****************** * STOPS ***************/ export const Stops = { // POST /api/stops/search getSearch: { by: { in: ['query'], isIn: { errorMessage: '"?by" can only be "stop_name" or "stop_id"', options: [['stop_id', 'stop_name']] }, toString: true }, term: { in: ['query'], // isLength: { // options: { min: 2 }, // errorMessage: '"?term" must be defined' // }, exists: true, errorMessage: '"?term" must be defined', toString: true } }, // GET /api/stops/proximity/:lat/:long getProximity: { lon: { in: ['query'], errorMessage: 'The value of the "lon" must be a number!', exists: true }, lat: { in: ['query'], errorMessage: 'The value of the "lat" must be a number!', exists: true } }, // POST /api/stops/:stop_id/inputs postInputs: { inputs: { in: ['body'], errorMessage: 'The inputs are misssing', exists: true, toString: true } } };
import React, { useRef, useEffect, useState } from "react"; import { Progress } from 'antd'; export default function Demo () { const [num, setNum] = useState(1); let intervalRef = useRef(); const decreaseNum = () => setNum((prev) => prev + 1); useEffect(() => { intervalRef.current = setInterval(decreaseNum, 1); return () => clearInterval(intervalRef.current); }, []); return( <> {num < 100 && <Progress type="circle" strokeColor={{ '0%': '#108ee9', '100%': '#87d068', }} percent={num} />} </> ) };
export { default as Header } from './Header'; export { default as PersonalInfo} from './PersonalInfo'
module.exports = function( dummy, anaConfig, req, res, callback) { var CustNum = req.body.result.parameters.CustNum; var CustName = req.body.result.parameters.CustName; CustName = CustName.replace(/[^\w\s]/gi, ''); var jde_attrib = req.body.result.parameters.jde_attrib; var qString = ""; var speech = ""; var text = ""; console.log("Cust Num = " + CustNum + "\nCust Name =" + CustName + "\njde_attrib =" + jde_attrib); if ((CustNum == "" || CustNum == null) && (CustName == "" || CustName == null)) { speech = "Please provide the Customer name or number."; text = "Please provide the Customer name or number. If you are not sure, please try to provide the first few letters of the Customer Name"; res.json({ speech : speech, displayText : text }); } else { if (CustNum == "" || CustNum == null) { qString = "Select * from jde WHERE CustName = '" + CustName + "'"; callback(qString); } else if (CustName == "" || CustName == null) { qString = "Select * from jde WHERE CustNum = " + CustNum; callback(qString); } else { speech = "Unable to process your request. Please try again later."; res.json({ speech : speech, displayText : speech }); } } }
import AccountManager from '../../account-manager/index.jsx' import Contact from '../../store/contact.jsx' import React from 'react' import Timeout from '../../util/timeout.jsx' import {extend, merge} from 'lodash' import {Status} from '../../app/config' function Queue(options) { extend(this, options) } Queue.prototype = { __proto__: Timeout, async execute() { this.timeoutDuration = skypeTimeout const count = await this.query() .count() if (count > 0) { const max = this.max < count ? this.max : count this.inform('busy', 'Входа в скайп') const skype = await AccountManager.get(this.account) this.inform('busy', 'Получение списка контактов') this.setTimeout(() => { const seconds = Math.round(this.timeoutDuration / 1000) this.inform('error', `Skype не отвечает в течении ${seconds} секунд`) }) const inform = i => this.inform('busy', this.success(i, count)) let i = 0 const pull = async() => { const contact = await this.query().first() if (!contact) { return } await this.work(skype, contact) inform(++i) this.updateTimeout() if (i < max) { await pull() } } inform(0) await pull() this.clearTimeout() Contact.emit('update') } else { this.inform('error', 'Не найдено ни одного котакта') } } } export default Queue
#!/usr/bin/env node /** * xloger command-line interface * use: * xloger --help to get help. * xloger start to start a daemon service. * xloger stop to stop the server. */ var pwd = __dirname , os = require('os') , fs = require("fs") , path = require('path') , program = require('commander') , jsonfile = require('jsonfile') , defs = require("../defaults.json") , pkg = require("../package") , forever = require('xforever') , execSync = require('child_process').execSync ; // detect the default config file: xloger.json // POSIX: /etc/xloger.json // Win32: SysDriver:\windows\system32\xloger.json var uconf = null; switch(os.platform().toLowerCase()){ case "win32": var sysdriver = path.parse(os.os.homedir())['root']; uconf = path.join(path.parse(os.os.homedir())['root'], "windows", "system32", "xloger.json"); break; default: uconf = "/etc/xloger.json"; } var runtime_file = path.join(pwd, "../runtime.json") , app_script = path.join(pwd, "../xloger.js"); // assign the version from package.json program.version(pkg.version); /** * start command */ program .command('start') .description('start xloger server with web gui.') .option("-p, --port", "the port xloger server listened, default: 9527") .option("-c, --config", "path to config file which format whith json.\n\t\t default:"+uconf) .option("-d, --debug", "debug mode, default to daemon mode.") .action(function(options){ var config = Object.assign({}, defs); // clone the default configuration if(!options.config){ options.config = uconf; } // load the user config file which exists. if(fs.existsSync(options.config)){ config = Object.assign(config, require(options.config)); } if(options.port) config.port = options.port; // write config to file jsonfile.writeFileSync(runtime_file, config); if(options.debug){ require(app_script); return; }else{ forever.getAllProcesses(function(err, processes){ var proc = forever.findByScript(app_script, processes); if(proc){ console.error('error: xloger has already run as pid:'+proc[0].pid+'.'); return; } var result = forever.startDaemon(app_script, { uid:"xloger", pidFile: config.pidfile, logFile: config.logfile }); if(result){ console.log("xloger started at http://:::"+config.port+"."); } }); } }); /** * stop command */ program .command('stop') .description('stop xloger server.') .action(function(){ forever.getAllProcesses(function(err, processes){ var proc = forever.findByScript(app_script, processes); if(!proc){ console.error('error: xloger does not running.'); return; } forever.stop(app_script); console.log("xloger stoped.") }); }); program.parse(process.argv);
var stdio = require('stdio'); var ops = stdio.getopt({ 'nomadip': {key: 'n', args: 1, mandatory: true, description: 'Nomad Server API IP Address'}, 'token': {key: 't', args: 1, mandatory: true, description: 'Circonus AP Token'}, 'plan': {key: 'p', args: 1, type: Boolean, description: 'Show Plan but do not delete'} }); const args = process.argv; var http = require("http"); var url = "http://" + ops.nomadip+ ":4646/v1/allocations"; var allocToDeactivate = []; var body = "", allocations; // get is a simple wrapper for request() // which sets the http method to GET var request = http.get(url, function (response) { // data is streamed in chunks from the server // so we have to handle the "data" event response.on("data", function (chunk) { body += chunk; }); response.on("end", function (err) { // finished transferring data // dump the raw data allocations = JSON.parse(body); //Parse into list of allocations console.log("Found", allocations.length, "allocations in total"); for (var item in allocations) { console.log("Allocation:", allocations[item].ID.substr(0,8), allocations[item].JobID, allocations[item].DesiredStatus, allocations[item].ClientStatus); if (allocations[item].ClientStatus == "lost") { console.log("Deactivate:", allocations[item].ID.substr(0,8)) allocToDeactivate.push(allocations[item].ID.substr(0,8)); if (ops.plan == true) { ShowMetricsTodDeactivate(ops.token, allocations[item].ID.substr(0,8)) } else { DoMetricDeactivation(ops.token, allocations[item].ID.substr(0,8)) } } } printalloc(allocToDeactivate.length); console.log("Will Deactivate: ", allocToDeactivate); }); }); function printalloc(alloc) { console.log("Found", alloc, "which are complete") } function ShowMetricsTodDeactivate(token, string) { const api = require('circonusapi2'); var metric_list = []; var metric_list_str = ""; var check_id_path = null; var endpoint = "/metric?search=(active:1)" + "*" + string +"*&size=100"; api.setup(ops.token, 'Nomad'); api.get(endpoint, null, (code, error, body) => { if (error !== null) { console.error(error); process.exit(1); } if (body.length > 0) { // console.log("Plan calls for the following", body.length, "metrics to be dactivated:"); for (var item in body) { var check_id_path = body[0]._check_bundle.replace('check_bundle', 'check_bundle_metrics'); metric_list.push('{"status": "available" , "name" : "' + body[item]._metric_name + '", "type": "' + body[item]._metric_type + '"}'); console.log("Metric:", body[item]._metric_name); } } } )}; function DoMetricDeactivation(token, string) { const api = require('circonusapi2'); var metric_list = []; var metric_list_str = ""; var check_id_path = null; var endpoint = "/metric?search=(active:1)" + "*" + string +"*&size=100"; api.setup(ops.token, 'Nomad'); api.get(endpoint, null, (code, error, body) => { if (error !== null) { console.error(error); process.exit(1); } if (body.length > 0) { console.log("Deactivating the following", body.length, "metrics:"); for (var item in body) { var check_id_path = body[0]._check_bundle.replace('check_bundle', 'check_bundle_metrics'); metric_list.push('{"status": "available" , "name" : "' + body[item]._metric_name + '", "type": "' + body[item]._metric_type + '"}'); console.log("Metric:", body[item]._metric_name); } if (ops.plan == true) { console.log("End of plan"); } console.log("Initating Deactivation of", body.length, " metrics..."); var metric_list_str = '{ "metrics" : [' + metric_list + ']}'; var metric_json = JSON.parse(metric_list_str); api.put(check_id_path, metric_json, (code, error, body) => { if (error !== null) { console.error(error); process.exit(1); } console.dir(body); }); } else console.log("No metrics were found"); }); };
import './App.scss'; import Register from "./pages/Register/Register" import Login from "./pages/Login/Login" import Home from "./pages/Home/Home" import NavbarComponents from "./Components/Navbar/Nav" import Footer from './pages/Footer/Footer' import ChatPage from "./pages/ChatPage/ChatPage" import { BrowserRouter as Router, Switch, Route, } from "react-router-dom"; import {useDispatch} from "react-redux" import firebase from "firebase" import "firebase/auth"; import Profile from './pages/Profile/Profile'; var firebaseConfig = { apiKey: process.env.REACT_APP_AUTH_API_KEY, authDomain: process.env.REACT_APP_AUTH_DOMAIN, projectId: process.env.REACT_APP_PROJECT_ID, storageBucket: process.env.REACT_APP_STORAGED_BUCKET, messagingSenderId: process.env.REACT_APP_MESSAGING_SENDER_ID, appId: process.env.REACT_APP_AUTH_APP_ID }; firebase.initializeApp(firebaseConfig); function App() { const dispatch = useDispatch() firebase.auth().onAuthStateChanged((user) => { if (user) { dispatch({type:"SignIn", payload:{userId: user}}) } else { dispatch({type:"SignIn", payload:{userId: ""}}) } }); return ( <div className="App"> <Router> <NavbarComponents/> <Switch> <Route path="/register" component={Register}/> <Route path="/login" component={Login}/> <Route path="/profile" component={Profile}/> <Route path="/chat" component={ChatPage}/> <Route exact path="/" component={Home}/> </Switch> </Router> <Footer/> </div> ); } export default App;
var express = require('express'); var app = express(); var bodyParser = require('body-parser'); var mongoose=require('mongoose'); var user = require('./user'); mongoose.connect('mongodb://localhost:27017/sensor_db'); app.use("/templates", express.static(__dirname + '/templates')); app.use(bodyParser.urlencoded({ extended: true })); app.listen(3000,function(){ console.log('server listening'); }); app.get('/', function(req, res){ res.sendFile(__dirname + '/templates/index.html'); }); app.post('/dst11',function(req,res){ var data = {} data.humidity = req.body.humidity data.temperature = req.body.temperature var newObj=new user(); newObj.temperature = req.body.temperature newObj.humidity = req.body.humidity newObj.save(function(err){}); res.send(JSON.stringify({data}, null, 3)); console.log(data.humidity, data.temperature ) }) app.get('/sensor-data',function(request, response) { userOne = new Object(); user.find({}, function(err, users) { userOne = users; response.json(userOne); }); });
const Chance = require('chance'); const expect = require('code').expect; const presetOptions = require('../../../src/preset-options'); describe('Given the yargs `commandDir` options object for katulong presets', () => { it('should only use the right extension', () => { const expectedExtensions = 1; const expectedExtensionName = 'js'; expect(presetOptions().extensions.length).number().equal(expectedExtensions); expect(presetOptions().extensions[0]).string().equal(expectedExtensionName); }); it('should only include a preset if it follows the preset directory and file format', () => { const chance = new Chance(); const expectedPreset = chance.hash(); const validPluginLocation = `${chance.hash()}\\katulong-preset-${expectedPreset}\\lib\\index.js`; const invalidPluginLocation = `${chance.hash()}\\${expectedPreset}\\lib\\index.js`; const presetsToCheck = [ expectedPreset ]; expect(presetOptions(presetsToCheck).include(validPluginLocation)).true(); expect(presetOptions(presetsToCheck).include(invalidPluginLocation)).false(); }); it('should look for subdirectories', () => { expect(presetOptions().recurse).true(); }); });
const express = require('express'); var bodyParser = require('body-parser'); const passport = require('passport'); const cookieSession = require('cookie-session'); const passportSetup = require('./config/passport-setup'); const fileUpload = require('express-fileupload'); const {google} = require('googleapis'); const fs = require('fs'); const app = express(); app.use(express.static('public')) // parse application/x-www-form-urlencoded app.use(bodyParser.urlencoded({ extended: false })) // parse application/json app.use(bodyParser.json()) app.use(fileUpload()); app.set('view engine', 'ejs'); app.use(cookieSession({ keys: ['secret123'] })); app.use(passport.initialize()); app.use(passport.session()); app.get('/', (req, res) => { res.render('home'); }) app.get('/upload', (req, res) => { console.log(req.user); if(!req.user) { res.redirect('/'); } else { let data = { id: req.user._id, name: req.user.name } if(req.query.status == 'successful') { data.file = 'file uploaded'; } else { data.file = 'file not uploaded'; } res.render('upload', data); } }); app.post('/uploadFile', (req, res) => { if(!req.user) { res.redirect('/'); } else { // config google drive with client token const oauth2Client = new google.auth.OAuth2() oauth2Client.setCredentials({ 'access_token': req.user.accessToken }); const drive = google.drive({ version: 'v3', auth: oauth2Client }); //move file to google drive let { name: filename, mimetype, data } = req.files.fileUpload let dataToDownload = { name: filename, mimeType: mimetype, location: req.user.name, date: Date(Date.now()).toString() } const driveResponse = drive.files.create({ requestBody: { name: filename, mimeType: mimetype }, media: { mimeType: mimetype, body: Buffer.from(data).toString() } }); driveResponse.then(data => { if (data.status == 200) { res.writeHead(200, { 'Content-Type': 'application/json-my-attachment', "content-disposition": "attachment; filename=\"download.json\"" }); res.end(JSON.stringify(dataToDownload)); res.redirect('/upload?status=successful'); // success } else { res.redirect('/upload?status=unsuccessful'); } }).catch(err => { throw new Error(err) }) } }); app.post('/login', (req, res) => { if(req.body.selectedNode == 1) { res.redirect('/login1'); } else if(req.body.selectedNode == 2) { res.redirect('/login2'); } else if(req.body.selectedNode == 3) { res.redirect('/login3'); } }) app.get('/login1',passport.authenticate('google', { scope: ['https://www.googleapis.com/auth/drive', 'profile'], })); app.get('/login2',passport.authenticate('google2', { scope: ['https://www.googleapis.com/auth/drive', 'profile'], })); app.get('/login3',passport.authenticate('google3', { scope: ['https://www.googleapis.com/auth/drive', 'profile'], })); app.get('/login/redirect', passport.authenticate('google'), (req, res) => { res.redirect('/upload'); }) app.get('/login2/redirect', passport.authenticate('google2'), (req, res) => { res.redirect('/upload') }) app.get('/login3/redirect', passport.authenticate('google3'), (req, res) => { res.redirect('/upload'); }) app.get('/logout', function(req, res){ req.logout(); res.redirect('/'); }); app.listen(3000, () => { console.log('Running server...') })
const extend = (a, b) => { return Object.assign({}, a, b); }; const getMovieRatingLevel = (rating) => { let level = ``; if ((rating >= 0) && (rating < 3)) { level = `Bad`; } if ((rating >= 3) && (rating < 5)) { level = `Normal`; } if ((rating >= 5) && (rating < 8)) { level = `Good`; } if ((rating >= 8) && (rating < 10)) { level = `Very good`; } if (rating === 10.0) { level = `Awesome`; } return level; }; export {extend, getMovieRatingLevel};
import Vue from 'vue'; import PieChart from '../components/PieChart.vue'; import BarChart from '../components/BarChart.vue'; import LineChart from '../components/LineChart.vue'; import ExportChartButton from '../components/ExportChartButton.vue'; Vue.component('vue-pie-chart', PieChart); Vue.component('vue-bar-chart', BarChart); Vue.component('vue-line-chart', LineChart); Vue.component('vue-export-chart-button', ExportChartButton);
#!/usr/bin/env node const dispatcher = require('./../lib/dispatcher'); // Parse given arguments to map to action to manager dispatcher.parse(process.argv);
var settings = require("./settings") exports.development = { port: 3000, cookieSecret: settings.cookieSecret } exports.production = { port: 3000, cookieSecret: settings.cookieSecret }
const express = require('express'); const router = express.Router(); const mysql = require('../mysql').pool; // retorna todos os produtos router.get('/', (req, res, next) => { mysql.getConnection((error, conn) => { if (error) { return res.status(500).send({ error: error }) } conn.query( 'SELECT * FROM produtos', (error, result, field) => { conn.release(); if (error) { return res.status(500).send({ error: error, response: "Aconteceu algo inesperado e não foi possível apresentar os produtos" }) } const response = { quantidade: result.length, descricao: 'Retorna todos os produtos', produtos: result.map(prod => { return { id_produto: prod.id_produto, nome: prod.nome, preco: prod.preco, request: { tipo: 'GET', descricao: 'aqui será inserida a descrição do Produto', url: 'http://localhost:3000/produtos/' + prod.id_produto } } }) } return res.status(200).send({ response }) } ) }); }); // insere um produto router.post('/', (req, res, next) => { mysql.getConnection((error, conn) => { if (error) { return res.status(500).send({ error: error }) } conn.query( 'INSERT INTO produtos (nome, preco) VALUES (?,?)', [req.body.nome, req.body.preco], (error, result, field) => { conn.release(); if (error) { return res.status(500).send({ error: error, response: "Aconteceu algo inesperado e não foi possível cadastrar o produto" }) } const response = { mensagem: 'Produto inserido com sucesso.', descricao: 'Insere um produtos', produtoCriado: { id_produto: result.id_produto, nome: req.body.nome, preco: req.body.preco, request: { tipo: 'POST', descricao: 'aqui será inserida a descrição do Produto', url: 'http://localhost:3000/produtos' } } } res.status(201).send({ response }) } ) }); }); // retorna um produtos router.get('/:id_produto', (req, res, next) => { mysql.getConnection((error, conn) => { if (error) { return res.status(500).send({ error: error }) } conn.query( 'SELECT * FROM produtos WHERE id_produto = ?', [req.params.id_produto], (error, result, field) => { conn.release(); if (error) { return res.status(500).send({ error: error, response: "Aconteceu algo inesperado e não foi possível apresentar o produto" }) } if (result.length == 0) { return res.status(404).send({ mensagem: 'Produto não encontrado' }) } const response = { descricao: 'Retorna um produto pelo seu ID', produto: { id_produto: result[0].id_produto, nome: result[0].nome, preco: result[0].preco, request: { tipo: 'GET', descricao: 'aqui será inserida a descrição do Produto', url: 'http://localhost:3000/produtos' } } } res.status(201).send({ response }) } ) }); }); // atualiza um produto router.patch('/:id_produto', (req, res, next) => { mysql.getConnection((error, conn) => { if (error) { return res.status(500).send({ error: error }) } conn.query( 'UPDATE produtos SET nome = ?, preco = ? WHERE id_produto = ?', [req.body.nome, req.body.preco, req.body.id_produto], (error, result, field) => { conn.release(); if (error) { return res.status(500).send({ error: error, response: "Aconteceu algo inesperado e não foi possível editar o produto" }) } const response = { mensagem: 'Produto atualizado com sucesso', produtoAtualizado: { id_produto: req.body.id_produto, nome: req.body.nome, preco: req.body.preco, request: { tipo: 'GET', descricao: 'aqui será inserida a descrição do Produto', url: 'http://localhost:3000/produtos/' + req.body.id_produto } } } res.status(202).send({ response }) } ) }); }); // deleta um produto router.delete('/:id_produto', (req, res, next) => { mysql.getConnection((error, conn) => { if (error) { return res.status(500).send({ error: error }) } conn.query( 'DELETE FROM produtos WHERE id_produto = ?', [req.body.id_produto], (error, result, field) => { conn.release(); if (error) { return res.status(500).send({ error: error, response: "Aconteceu algo inesperado e não foi possível deletar o produto" }) } const response = { mensagem: 'Produto deletado com sucesso', request: { tipo: 'GET', descricao: 'Retorna a lista de produtos', url: 'http://localhost:3000/produtos' } } res.status(202).send({ response }) } ) }); }); module.exports = router;
const path = require('path'); const webpack = require('webpack'); module.exports = { entry: { entry1: './entry1.js', entry2: './entry2.js', entry3: './entry3.js' }, output: { filename: 'bundle.[name].js', path: path.resolve(__dirname, 'dist') }, plugins: [ new webpack.optimize.CommonsChunkPlugin({ name: 'entry1', filename: 'vender.js' }), ] };
function twoStrings(s1, s2) { // n = |s1| m = |s2| // O(n + m) // take one string, put all these letters in a hash table, let set = new Set(); for (let letter of s1){ set.add(letter) } for (let letter of s2){ if (set.has(letter)){ return "YES"; } } return "NO"; // see if the second string has any characters in the hashtable // if we find one in the second string, return "YES" } // find the number of unique common substrings in the two strings // miss m, i, s, s, i, o, n // { // "m": [0], // "i": [1], // "s": [2,3] // } ["m", "i", "s", "mi", "is", "ss", "mis", "iss", "miss"] // kiss // i, s, n, is, si, iss, ssi, issi // 8 unique common substrings // Complete the commonSubstrings function below, returns the count of occurrences function commonSubstrings(s1, s2) { // loop over the first string, and add each letter to a map, pointing to the index // loop over the second string, if we find a match, then we look back at the first string // and advance in it, and compare that with the second string + 1 let map = {}; for (let i = 0; i < s1.length; i++) { map[s1[i]] = i; } console.log(map) let inCommon = 0; for (let i = 0; i < s2.length; i++) { if (map[s2[i]]) { s1Index = map[s2[i]]; s2Index = i; while (s1Index < s1.length && s2Index < s2.length) { if (s1[s1Index] == s2[s2Index]) { inCommon++; s1Index++; s2Index++; } else { break; } } } } return inCommon; // find all substrings of s1, put them in a set // find all substrings of s2, put them in a set // loop through s2 set, and check if the value exists in s1 set } let inCommon = commonSubstrings("mis", "kis") console.log(inCommon);
ds.BaseEmployee.count()
import { Component } from "react"; import Footer from './Footer'; export default { title : 'component/Footer', component : Footer } export const normal = () => <Footer/>
import React, { Component } from 'react'; import i18n from './i18n'; import { translate } from 'react-i18next'; import './App.css'; // var log = require('log4js');//.getLogger('App'); // log.debug("This is in App.js"); // const fs = require('fs'); // var Log = require('log') // , log = new Log('debug', fs.createWriteStream('app.log')); // // log.debug('preparing email app'); // log.info('sending email app'); // log.error('failed to send email app'); let button_center = { textAlign : "center", paddingTop : "10px", alignItem : "center" } function doLogin(){ let formData = { username : document.getElementById("username").value, password : document.getElementById('password').value } let a = fetch('http://localhost:9000/auth/', { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': '"application/json; charset=utf-8', }, dataType : 'json', body: JSON.stringify({ username : formData.username, password : formData.password }) }); let data = fetch('http://localhost:9000/auth', { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify(formData) }); console.log('data'); console.log(data); } const App = ({t}) =>( <div className="App"> <section className="hero is-info"> <div className="hero-body has-text-centered"> <div className="container"> <h1 className="title">{t('title')}</h1> <span>{t('lang_text')}</span> </div> </div> </section> <div className="container" > <div className="field"> <div className="column is-offset-one-third is-one-third"> <label className="label">{t('label_username')}</label> <div className="control"> <input className="input" type="text" id="username" name="username" placeholder={t('label_username')} /> </div> <label className="label">{t('label_password')}</label> <div className="control"> <input className="input" type="password" id="password" name="password" placeholder={t('label_password')} /> </div> <div className="column is-offset-one-fifth "> <div className="field is-grouped " style={button_center}> <div className="control"> <button className="button is-link" onClick={doLogin} id="login_button">{t('button_login')}</button> </div> <div className="control"> <button className="button is-danger is-outlined" id="register_button">{t('button_register')}</button> </div> </div> </div> </div> </div> </div> <footer className="footer"> {/*<div className="container">*/} {/*<div className="content has-text-centered">*/} <div className="column is-offset-two-fifths is-one-third"> <div className="has-text-centered " style={button_center}> <div className="container"> <div className="field is-grouped level-item"> <div className="control"> <button className="button is-link" onClick={() => { i18n.changeLanguage('th')}}>{t('button_change_lang_th')}</button> </div> <div className="control"> <button className="button is-warning" onClick={() => { i18n.changeLanguage('en')}}>{t('button_change_lang_en')}</button> </div> </div> </div> </div> </div> </footer> </div> ); export default translate()(App);
import React, { useEffect, useRef } from 'react' import Scroll from '../../../../components/Scroll' import PropTypes from 'prop-types' import './index.scss' function HorizontalList(props) { const listWrapper = useRef(null) const { list, selectedItem, title } = props const { handleClick } = props useEffect(() => { let totalWidth = 0 const spanEls = listWrapper.current.querySelectorAll('span') Array.from(spanEls).forEach(el => { totalWidth += el.offsetWidth }) listWrapper.current.style.width = `${totalWidth}px` }, []) return ( <Scroll direction='horizontal'> <div className="list-wrapper" ref={listWrapper}> <div className="list"> <span className='list-title'>{title}</span> { list.map(item => ( <span key={item.key} className={`list-item ${selectedItem === item.key ? 'selected' : ''}`} onClick={() => handleClick(item.key)} > {item.name} </span> )) } </div> </div> </Scroll> ) } HorizontalList.defaultProps = { list: [], selectedItem: '', title: '', handleClick: null }; HorizontalList.propTypes = { list: PropTypes.array, selectedItem: PropTypes.string, title: PropTypes.string, handleClick: PropTypes.func }; export default React.memo(HorizontalList)
export const AddFriendSchema = { id: '/AddFriendSchema', type: 'object', properties: { user_id: { type: 'number' }, friend_id: { type: 'number' } } }
import React from 'react'; import PropTypes from 'prop-types'; import CategoryConstants from '../../constants/categoryConstants'; import FilterItem from './filter-item'; /** * Handles filtering of category of products */ class CategoryFilter extends React.Component { constructor(props) { super(props); this.state = { filters: [], }; this.handleToggle = ::this.handleToggle; this.handleSelect = ::this.handleSelect; } handleToggle(e) { let categories = this.state.filters.slice(); // if checkbox is checked, add filter to array if (e.target.checked) { categories.push(e.target.value); // cache the filters for manipulation this.setState({ filters: categories }); } else { categories = categories.filter(category => category !== e.target.value); // cache the filters for manipulation this.setState({ filters: categories }); } // callback to pass state to parent this.props.setFilter(categories); } handleSelect() { this.setState({ filters: [], }); this.props.handleFilterSelect(); } render() { return ( <div id="category-filter-container"> <input type="radio" name="filter" id="cat-filter" onChange={this.handleSelect} checked={this.props.isDisplayed} /> <label htmlFor="cat-filter" className="list-title">Category</label> { (this.props.isDisplayed) ? <ul id="category-filter"> <FilterItem filter="cat-tools" text={CategoryConstants.tools} handleToggle={this.handleToggle} type="checkbox" /> <FilterItem filter="cat-brushes" text={CategoryConstants.brushes} handleToggle={this.handleToggle} type="checkbox" /> <FilterItem filter="cat-markup" text={CategoryConstants.markup} handleToggle={this.handleToggle} type="checkbox" /> </ul> : <div /> } </div> ); } } CategoryFilter.propTypes = { isDisplayed: PropTypes.bool.isRequired, setFilter: PropTypes.func.isRequired, handleFilterSelect: PropTypes.func.isRequired, }; export default CategoryFilter;
const LOAD_DATA = 'views/shoppingcar/load_data' const SET_DATA = 'views/shoppingcar/set_data' const INCREMENT = 'views/shoppingcar/increment' const DECREMENT = 'views/shoppingcar/decrement' const PUT_DATA = 'views/shoppingcar/put_data' const DELETE_DATA = 'views/shoppingcar/delete_data' export { LOAD_DATA, SET_DATA, INCREMENT, DECREMENT, PUT_DATA, DELETE_DATA, }
import {pageSize, pageSizeType, description, searchConfig} from '../../globalConfig'; const controls = [ {key: 'controllerExplain', title: '所属控制层说明', type: 'text', required: true}, {key: 'controllerName', title: '所属控制层名称', type: 'text', required: true}, {key: 'controllerUrl', title: '所属控制层路径', type: 'text', required: true}, {key: 'controllerPath', title: '所属控制层代码路径', type: 'text', required: true}, ]; const index = { pageSize, pageSizeType, description, searchConfig }; const edit = { controls, edit: '编辑', add: '新增', config: {ok: '确定', cancel: '取消'} }; const addController = { index, edit }; export default addController;
import React, { useEffect, useState } from "react"; import { Button, Col, Form, Row } from "react-bootstrap"; import { useDispatch, useSelector } from "react-redux"; import { createBook, deleteBook, listBooks } from "../actions/bookActions"; import { BOOK_CREATE_RESET } from "../actions/types"; import Book from "../components/Book"; import Loader from "../components/Loader"; import Message from "../components/Message"; const BookListPage = ({ history }) => { const [title, setTitle] = useState(""); const [subtitle, setSubTitle] = useState(""); const [author, setAuthor] = useState(""); const [description, setDescription] = useState(""); const [isbn, setISBN] = useState(""); const dispatch = useDispatch(); const bookList = useSelector((state) => state.bookList); const { loading, error, books } = bookList; const bookCreate = useSelector((state) => state.bookCreate); const { loading: loadingCreate, error: errorCreate, success: successCreate, book: createdBook, } = bookCreate; const bookDelete = useSelector((state) => state.bookDelete); const { loading: loadingDelete, error: errorDelete, success: successDelete, } = bookDelete; useEffect(() => { dispatch({ type: BOOK_CREATE_RESET }); if (successCreate) { history.push(`/books/${createdBook._id}`); } else { dispatch(listBooks()); } }, [dispatch, history, successCreate, successDelete, createdBook]); const createBookHandler = (e) => { e.preventDefault(); dispatch( createBook({ title, subtitle, description, author, isbn, }) ); }; const deleteHandler = (id) => { dispatch(deleteBook(id)); }; return ( <> {loadingCreate && <Loader />} {errorCreate && <Message variant="danger">{errorCreate}</Message>} {loadingDelete && <Loader />} {errorDelete && <Message variant="danger">{errorDelete}</Message>} <Row> <Col> <Form onSubmit={createBookHandler}> <Form.Group controlId="bookTitle"> <Form.Label>Book Title</Form.Label> <Form.Control type="text" value={title} onChange={(e) => setTitle(e.target.value)} placeholder="Enter Title" /> </Form.Group> <Form.Group controlId="bookSubTitle"> <Form.Label>Book Sub-Title</Form.Label> <Form.Control type="text" value={subtitle} onChange={(e) => setSubTitle(e.target.value)} placeholder="Enter Sub title" /> </Form.Group> <Form.Group controlId="bookAuthor"> <Form.Label>Author</Form.Label> <Form.Control type="text" value={author} onChange={(e) => setAuthor(e.target.value)} placeholder="Enter an Author" /> </Form.Group> <Form.Group controlId="bookDescription"> <Form.Label>Description</Form.Label> <Form.Control type="text" value={description} onChange={(e) => setDescription(e.target.value)} placeholder="Enter Description" /> </Form.Group> <Form.Group controlId="bookISBN"> <Form.Label>ISBN Number</Form.Label> <Form.Control type="text" value={isbn} onChange={(e) => setISBN(e.target.value)} placeholder="Enter ISBN Number" /> </Form.Group> <Button variant="warning" type="submit" onClick={createBookHandler} size="lg" block > <i className="fas fa-plus"></i> Create Book </Button> </Form> </Col> </Row> <Row> <Col className="p-5"> <h1>The Books in My Library </h1> </Col> </Row> {loading ? ( <Loader /> ) : error ? ( <Message variant="danger">{error}</Message> ) : ( <> <Row> {books.map((book) => ( <Col key={book._id} sm={12} md={6} lg={4}> <Book book={book} deleteHandler={deleteHandler} /> </Col> ))} </Row> </> )} </> ); }; export default BookListPage;
import React from 'react' const FourOhFour = () => ( <h1 style={{ color: 'white', fontSize: '500%' }}>404</h1> ) export default FourOhFour
var searchData= [ ['tutorial_94',['Tutorial',['../start.html',1,'']]], ['type_5ferror_95',['type_error',['../classoptionpp_1_1type__error.html',1,'optionpp::type_error'],['../classoptionpp_1_1type__error.html#a76c5ed432b1abe7e75c094beb48de26e',1,'optionpp::type_error::type_error()']]] ];
//var host = "http://192.168.1.107/"; var host = "http://localhost/"; var server = "MonopolyServer/web/app_dev.php/"; var app = "MonopolyClient/public_html/"; var modulo = ""; var usuario = {id: 0, nombre: "", personaje: "", personajeNombre: "", dinero: 1000, carcel: 0}; var sala; // Chema // Variables globales... antes estaban en tablero.js var listaUsuarios = new Array(); var posesionesCasillas = new Array(); var posicionesCasilla = new Array(); var turno = 0; var idPartida = 0; var contenido = ""; var reunirse = false; //var socket = io.connect("http://192.168.1.107:8585"); var socket = io.connect("http://localhost:8585"); $(document).ready(function() { contenido = $("#contenido"); modulo = "inicio"; cargarModulo(modulo); $.ajax({ url: host + server + "usuario/autenticado", method: "post", dataType: "json", success: function(datos) { // Chema // Si el usuario esta logado que lleve a la pantalla de partidas directamente if (datos.autenticado) { $("#usuario").text(datos.nombre); usuario.nombre = datos.nombre; usuario.id = datos.id; idPartida = datos.partida; if (datos.estado == "jugando") { console.log("Usuario logeado con partida empezada --> usuario: " + usuario.nombre + " partida: " + idPartida); cargarDatosPartida(); } else { modulo = "partidas"; cargarModulo(modulo); } } // if (usuario.nombre !== "") { // $("#usuario").text("Hola amo"); // } else { // $("#usuario").text("Logueate"); // } } }); $(".ir").off().on("click", function(e) { e.preventDefault(); if (modulo != $(this).attr("href")) { modulo = $(this).attr("href"); // if (modulo.match("/")) { // modulo = modulo.split("/"); // if (modulo[1] == "crear") { // unirse = false; // } else { // unirse = true; // } // cargarModulo(modulo[0]); // } else { if (modulo == "ajustes") { if (usuario.nombre !== "") { cargarModulo(modulo); } else { alert("Tienes que loguearte"); } } else { cargarModulo(modulo); } } }); $("#logout").off().on("click", function(e) { $.ajax({ url: host + server + "usuario/logout", method: "post", dataType: "json", success: function(datos) { if (!datos.autenticado) { $("#usuario").text("Logueatee!!"); $("#infoPartida").text(""); usuario.id = ""; usuario.nombre = ""; usuario.personaje = ""; modulo = "inicio"; cargarModulo(modulo); } } }); }); $("#volumen").off().on("click", function(e) { var oAudio = document.getElementById('audioBSO'); var jqAudio = $("#volumen"); if (oAudio.paused) { oAudio.play(); $("#volumen").removeClass("ui-icon-play"); $("#volumen").addClass("ui-icon-stop"); console.log($("#volumen").attr("class")); } else { oAudio.pause(); $("#volumen").removeClass("ui-icon-stop"); $("#volumen").addClass("ui-icon-play"); console.log($("#volumen").attr("class")); } }); $("#bajarVolumen").off().on("click", function(e) { var oAudio = document.getElementById('audioBSO'); if (oAudio.volume !== 0) { oAudio.volume -= 0.1; } }); $("#subirVolumen").off().on("click", function(e) { var oAudio = document.getElementById('audioBSO'); if (oAudio.volume !== 1) { oAudio.volume += 0.1; } }); }); // Chema // Funcion para cargar la informacion de la partida actual function cargarDatosPartida() { $.ajax({ url: host + server + "jugador/recuperarEstado/" + usuario.id + "/" + idPartida, method: "post", dataType: "json", success: function(datos) { console.log(datos); for (var i = 0; i < datos[1].length; i++) { var jug = datos[1][i]; var usu = jug.idUsuario; var objUsuario = {id: usu.id, nombre: usu.nombre, dinero: jug.dinero, carcel: 0, personaje: jug.idPersonaje.id, personajeNombre: jug.idPersonaje.nombre}; listaUsuarios.push(objUsuario); posicionesCasilla.push(datos[1][i].posicion); } // for(var i = 0; i < datos[2].length; i++) { // posicionesCasilla.push(datos[1][i]); // } var part = datos[0]["idPartida"]; bote = part.boteComun; sala = part.token; socket.emit("volver_unirse", {sala: sala}); reunirse = true; modulo = "tablero"; cargarModulo(modulo); } }); } function cargarModulo(modulo) { console.log(modulo); contenido.slideUp("slow", function() { $("#js").remove(); $("#css").remove(); contenido.load(host + app + modulo + ".html", function() { console.log(modulo); $("head").append('<script type="text/javascript" src="recursos/js/' + modulo + '.js" id="js"></script>'); $("head").append('<link type="text/css" rel="stylesheet" href="recursos/css/' + modulo + '.css" id="css"/>'); }); }); contenido.slideDown("slow"); } // Chema // Sirve para re-unirse en la sala socket.on("volver_unirse", function(datos) { datos.turno = turno; socket.emit("conf_volver_unirse", datos); }); socket.on("conf_volver_unirse", function(datos){ turno = datos.turno; }); //socket.on("solicitud", function(datos) { // $(".mensaje").append("<p>" + datos.usuario.nombre + " ha creado una partida en la sala <span class='sala'>" + datos.sala + "</span>, deseas unirte?<input type='button' class='bSi' value='Si'></p>"); // $(".bSi").on("click", function() { // $(this).parent().remove(); // unirse = true; // modulo = "partidas"; // cargarModulo(modulo); // }); //});
'use strict'; // Load modules const axios = require('axios').default; const instance = axios.create({ baseURL: 'https://service.formitize.com/api/rest/v2/', // timeout: 1000, headers: { 'Accept': 'application/json', 'Content-Type': 'application/json', 'User-Agent':process.env.FM_COMPANY }, auth:{ "username": process.env.FM_COMPANY_USER, "password": process.env.FM_USER_PASSWORD } }); exports.plugin = { name: 'AxiosFM', instance, }; // export default instance;
class RenderDeities { static $getRenderedDeity (deity) { return $$` ${Renderer.utils.getBorderTr()} ${Renderer.utils.getExcludedTr(deity, "deity")} ${Renderer.utils.getNameTr(deity, {suffix: deity.title ? `, ${deity.title.toTitleCase()}` : "", page: UrlUtil.PG_DEITIES})} ${RenderDeities._getDeityBody(deity)} ${deity.reprinted ? `<tr class="text"><td colspan="6"><i class="text-muted">Note: this deity has been reprinted in a newer publication.</i></td></tr>` : ""} ${Renderer.utils.getPageTr(deity)} ${deity.previousVersions ? ` ${Renderer.utils.getDividerTr()} ${deity.previousVersions.map((d, i) => RenderDeities._getDeityBody(d, i + 1)).join(Renderer.utils.getDividerTr())} ` : ""} ${Renderer.utils.getBorderTr()} ` } static _getDeityBody (deity, reprintIndex) { const renderer = Renderer.get(); const renderStack = []; if (deity.entries) { renderer.recursiveRender( { entries: [ ...deity.customExtensionOf ? [`{@note This deity is a custom extension of {@deity ${deity.customExtensionOf}} with additional information from <i title="${Parser.sourceJsonToFull(deity.source).escapeQuotes()}">${Parser.sourceJsonToAbv(deity.source)}</i>.}`] : [], ...deity.entries, ], }, renderStack, ); } if (deity.symbolImg) deity.symbolImg.style = deity.symbolImg.style || "deity-symbol"; return ` ${reprintIndex ? ` <tr><td colspan="6"> <i class="text-muted"> ${reprintIndex === 1 ? `這個神祇是再印版本。` : ""} 以下版本被印於較舊的出版品中 (${Parser.sourceJsonToFull(deity.source)}${Renderer.utils.isDisplayPage(deity.page) ? `-第${deity.page}頁` : ""}). </i> </td></tr> ` : ""} ${Renderer.deity.getOrderedParts(deity, `<tr><td colspan="6">`, `</td></tr>`)} ${deity.symbolImg ? `<tr><td colspan="6">${renderer.render({entries: [deity.symbolImg]})}<div class="mb-2"/></td></tr>` : ""} ${renderStack.length ? `<tr class="text"><td class="pt-2" colspan="6">${renderStack.join("")}</td></tr>` : ""} `; } }
const electron = require('electron'), { app , BrowserWindow } = electron, url = require('url'), path = require('path'); let mainWindow; app.on('ready',()=>{ mainWindow = new BrowserWindow({ width:1000, height:800 }); const startUrl = process.env.ELECTRON_START_URL || URL.format({ path: path.join(__dirname,'..','build','index.html'), protocol:'file:', slashes:true, }) mainWindow.loadURL(startUrl); mainWindow.on('closed',()=>{ app.quit(); mainWindow = null; }) });
let a = new WeakSet(), c = 123; // 错误 // 1.WeakSet只能存对象 a.add( c ); console.log( a.has( c ) );
export { Book } from './book.js'; export { Genre } from './models.js'; export { BookCollection, ProductCollection } from './book-collection.js'; export { Collection } from './collection.js'; export { Notepad } from './notepad.js'; export { getBookInfo } from './google-books.js'; import { Genre } from './models.js'; import { Book } from './book.js'; import { Notepad } from './notepad.js'; import { DateHelper } from './utils.js'; import { OzonProvider } from './store/providers/ozon/ozon-provider.js'; import { Author } from './store/domain/author.js'; import { Genre as ozonGenre } from './store/domain/genre'; const author = { firstName: 'J.K.', lastName: 'Rowling', rating: 4.7, }; const book = new Book('Harry Potter', Genre.fantasy, 380, author); const notepad = new Notepad('Notepad', 30); const products = [ book, notepad ]; const context = { user: { clientLevel: 1, }, cart: { items: products === null || products === void 0 ? void 0 : products.length, totalSum: products === null || products === void 0 ? void 0 : products.reduce((acc, curr) => acc + curr.price, 0), } }; console.log(`${book.getDiscountPrice(context)} instead of ${book.price}`, '\n', `${notepad.getDiscountPrice(context)} instead of ${notepad.price}`); const now = new Date(); const weekAfter = DateHelper.addDays(DateHelper.cloneDate(now), 7); console.log(now, weekAfter); const ozon = new OzonProvider(); const filter = { name: 'it', genre: ozonGenre.Horror, author: new Author('Stephen', 'King') }; function sortByPrice(one, two) { if (one.price > two.price) { return 1; } else if (one.price < two.price) { return -1; } else { return 0; } } Promise.all([ozon.find(filter)]) .then((result) => { if (result[0] !== undefined) { const allResults = [...result[0]]; // allResults.sort(sortByPrice); } }); const removeBook = (id) => Promise.resolve(id); removeBook.call(null, 5); function printBookSummary(printItalic = false) { let openingTag = ''; let closingTag = ''; if (printItalic) { openingTag = '<i>'; closingTag = '</i>'; } console.log(` ${openingTag} Book ${this.name} ${closingTag} `); } printBookSummary.call(book, true); try { throw new Error(); } catch (error) { if (error instanceof Error) { console.log(error.message); } } Promise.resolve({ id: '5', name: 'H', author: 'sdf', }).then((book) => { book['author'] !== undefined && book['genre'] !== undefined ? console.log(book.name, book['author'].toUpperCase(), book['genre'].toLowerCase()) : console.log(''); });
'use strict'; describe('Panel Self Test',function(){ it('open test page',function(){ browser.get('test/e2e/testee/panel/web/self.html') .then(function(){ browser.sleep(2000); }); }); it('显示默认标题',function(){ //标题 var i=element(by.css(".demo1 .panel-caption i")); // expect(i.getText()).toBe(" 标题"); expect(i.getText()).toMatch('标题'); }); it('显示自定义标题',function(){ var i=element(by.css(".demo2 .panel-caption i")); expect(i.getText()).toMatch('自定义'); }); it('图标显示',function(){ var i=element(by.css(".demo3 .panel-caption i")); expect(i.getAttribute('class')).toMatch('fa'); }); it('宽度默认200px',function(){ var panel=element(by.css(".demo4 .rdk-panel-module")); expect(panel.getCssValue("width")).toBe("200px"); }); it('设置宽度 高度',function(){ var panel=element(by.css(".demo5 .rdk-panel-module")); expect(panel.getCssValue("width")).toBe("250px"); expect(panel.getCssValue("height")).toBe("100px"); }); it('close关闭和befor_close',function(){ // var i=element(by.css(".demo6 .panel-caption i")); // //点击关闭后弹窗 和 处理 // i.click(); // //关闭完成 // var panel=element(by.css(".demo6 .rdk-panel-module")); // expect(panel.getAttribute("class")).toMatch("ng-hide"); }); });
//webpack默认配置 //module.exports: 对外暴露该文件, 使得其他文件取得访问权 module.exports = {};
//Program to draw mathematical rose patterns // Polar equation is: // r = cos(kθ) // OR can be a "pair of cartesian parametric equations" // x = cos(kθ)cos(θ) // y = cos(kθ)sin(θ) // Ref https://en.wikipedia.org/wiki/Rose_(mathematics) var denominator = 8; var numerator = 5; var sliderD; var sliderN; function setup() { createCanvas(500, 500); sliderD = createSlider(1, 10, 5, abs(0.02)); sliderN = createSlider(1, 10, 5, abs(0.02)); } function draw() { denominator = sliderD.value(); numerator = sliderN.value(); var k = numerator/denominator; //K is constant for how many petals there are in the rose background(51); translate(width/2, height/2); beginShape(); stroke(255); noFill(); strokeWeight(1); for(var a = 0; a < TWO_PI * denominator; a += 0.02){ var r = 200 * cos(k*a); var x = r * cos(a); var y = r * sin(a); vertex(x, y); } endShape(CLOSE); text("D:" + denominator, 20, 550); text("N:" + numerator, 40, 550); }