text
stringlengths
7
3.69M
'use strict' import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View, Image, TabBarIOS, } from 'react-native'; export default class Waimai extends React.Component{ static defaultProps = { autoPlay: false, maxLoops: 10, }; static propTypes = { autoPlay: React.PropTypes.bool.isRequired, maxLoops: React.PropTypes.number.isRequired, }; constructor(props){ super(props); this.state = { }; } componentWillMount() { } render() { return ( <View style = {styles.banners}> <Image style = {styles.bannerImg} source = {require('./images/waimai/bg-banner.png')} /> </View> ); } }; var styles = StyleSheet.create({ container: { flex: 1, }, bannerImg: { resizeMode: Image.resizeMode.stretch, }, });
import get from '../services/commands/get' import querystring from 'querystring' /** * Get a list of boards * @return {Promise<response>} The response from the server in json */ const getAll = () => { return get('/v2/boards.json') } const getOne = boardId => { return get(`/v2/boards/${querystring.escape(boardId)}.json`) } export { getAll, getOne }
let _ddRef; function setDdRef(navigatorRef) { _ddRef = navigatorRef; } function getDdRef() { return _ddRef; } export default { setDdRef, getDdRef, };
import { Route, Switch } from "react-router-dom"; import List from "../components/Books/List/List"; import Create from "../components/Books/Create/Create"; import Book from "../components/Books/Book/Book"; import React from "react"; import { checkAndRedirect } from "../utils/utils"; import Character from "../components/Characters/Character"; import CreateCharacter from "../components/Characters/CreateCharacter"; export const booksRoutes = <Switch> <Route path="/books/list"> { () => checkAndRedirect(<List/>) } </Route> <Route path="/books/create"> { () => checkAndRedirect(<Create/>) } </Route> <Route path="/books/:id/characters/create" render={ props => checkAndRedirect(<CreateCharacter bookid={props.match.params.id} />) } > </Route> <Route path="/characters/:id" render={ props => checkAndRedirect(<Character id={props.match.params.id}/>) } > </Route> <Route path="/books/:id" render={ props => checkAndRedirect(<Book id={props.match.params.id} />) } > </Route> </Switch>;
import React, {PureComponent} from "react"; import "../../style/chill.css"; import "./predit.css"; import Userlist from "./Userlist"; import ItemsList from "./ItemsList"; import Rating from "./Rating"; import RawData from "./RawData"; import FromTo from "./FromTo"; class NmfPredit extends PureComponent { constructor(props){ super(props) this.state={ selectUser:'', selectItem:'' } this.callbackUser = this.callbackUser.bind(this); this.callbackItem = this.callbackItem.bind(this); } callbackUser(value){ if(value !=='') this.setState({selectUser:value}); } callbackItem(value){ if(value !== ''){ this.setState({selectItem:value}); } } render(){ return( <div id="content"> <div className="preditContent"> <Userlist data={this.props.user} callbackFromUser={this.callbackUser}/> <ItemsList data={this.props.item} callbackFromItem={this.callbackItem}/> <Rating colUser={this.props.user} algorithm="SlopeOne" colItem={this.props.item} colRating={this.props.rating} selectItem={this.state.selectItem} selectUser={this.state.selectUser}/> <RawData colUser={this.props.user} colItem={this.props.item} colRating={this.props.rating}/> <FromTo algorithm="SlopeOne" colUser={this.props.user} colItem={this.props.item} colRating={this.props.rating}/> </div> </div> ) } } export default NmfPredit;
const mongoose = require('mongoose'); const rubriqueSchema = new mongoose.Schema({ name: { type: String, required: false }, pays: { type: String, required: false }, sRubrique: { type: String, required: false }, data: { type: String, required: false } }); module.exports = mongoose.model('Rubrique', rubriqueSchema);
import { LOAD, NEW_CHARGE } from "./actions"; import { MISERABLES } from "./sources"; import { initialState } from "./initialState"; import { download } from "../downloaders/download"; import miserables from "./data/miserables.json"; export const load = (dispatch, selectedSource) => { if (selectedSource === undefined) { dispatch({ type: LOAD, payload: initialState }); } else { if (selectedSource.url === MISERABLES) { dispatch({ type: LOAD, payload: miserables }); } else { download(dispatch, selectedSource.url, { episodesPath: selectedSource.episodesPath, episodeCharactersPath: selectedSource.episodeCharactersPath, episodeCategoryPath: selectedSource.episodeCategoryPath, }); } } }; export const changeCharge = (dispatch, charge) => { dispatch({ type: NEW_CHARGE, payload: charge }); };
var button = document.querySelector('.button') var inputValue = document.querySelector('.inputValue') var name = document.querySelector('.name') var desc = document.querySelector('.desc') var temp = document.querySelector('.temp') button.addEventListener('click', function () { fetch('https://api.openweathermap.org/data/2.5/weather?q=' + inputValue.value + '&appid=a2bd7213a39113727af6fff678a49f8d') .then(response => response.json()) .then(data => { console.log(inputValue) var tempValue = data['main']['temp']; var descValue = data['weather'][0]['description']; temp.innerHTML = Math.round(tempValue -273.15) + ' C'; desc.innerHTML = descValue; console.log(data); }) .catch(err => alert("wrong city name")) }) var cityList = ["https://api.openweathermap.org/data/2.5/weather?q=London&appid=a2bd7213a39113727af6fff678a49f8d", "https://api.openweathermap.org/data/2.5/weather?q=Moscow&appid=a2bd7213a39113727af6fff678a49f8d", "https://api.openweathermap.org/data/2.5/weather?q=Paris&appid=a2bd7213a39113727af6fff678a49f8d", "https://api.openweathermap.org/data/2.5/weather?q=New York,us&appid=a2bd7213a39113727af6fff678a49f8d", "https://api.openweathermap.org/data/2.5/weather?q=Pekin,cn&appid=a2bd7213a39113727af6fff678a49f8d" ] linkLondon = "https://api.openweathermap.org/data/2.5/weather?q=London&appid=a2bd7213a39113727af6fff678a49f8d"; var request = new XMLHttpRequest(); request.open('GET', linkLondon, true); request.onload = function () { var obj = JSON.parse(this.response); console.log(obj); document.getElementById('london-weather').innerHTML = obj.weather[0].description; document.getElementById('london-location').innerHTML = obj.name; document.getElementById('london-temp').innerHTML = Math.round(obj.main.temp - 273.15) + ' C'; document.getElementById('london-icon').src = "http://openweathermap.org/img/w/" + obj.weather[0].icon + ".png"; } request.send(); linkMoscow = "https://api.openweathermap.org/data/2.5/weather?q=Moscow&appid=a2bd7213a39113727af6fff678a49f8d"; var request = new XMLHttpRequest(); request.open('GET', linkMoscow, true); request.onload = function () { var obj = JSON.parse(this.response); console.log(obj); document.getElementById('moscow-weather').innerHTML = obj.weather[0].description; document.getElementById('moscow-location').innerHTML = obj.name; document.getElementById('moscow-temp').innerHTML = Math.round(obj.main.temp - 273.15) + ' C'; document.getElementById('moscow-icon').src = "http://openweathermap.org/img/w/" + obj.weather[0].icon + ".png"; } request.send(); linkParis = "https://api.openweathermap.org/data/2.5/weather?q=Paris&appid=a2bd7213a39113727af6fff678a49f8d"; var request = new XMLHttpRequest(); request.open('GET', linkParis, true); request.onload = function () { var obj = JSON.parse(this.response); console.log(obj); document.getElementById('paris-weather').innerHTML = obj.weather[0].description; document.getElementById('paris-location').innerHTML = obj.name; document.getElementById('paris-temp').innerHTML = Math.round(obj.main.temp - 273.15) + ' C'; document.getElementById('paris-icon').src = "http://openweathermap.org/img/w/" + obj.weather[0].icon + ".png"; } request.send(); linkNewYork = "https://api.openweathermap.org/data/2.5/weather?q=New York,us&appid=a2bd7213a39113727af6fff678a49f8d"; var request = new XMLHttpRequest(); request.open('GET', linkNewYork, true); request.onload = function () { var obj = JSON.parse(this.response); console.log(obj); document.getElementById('newYork-weather').innerHTML = obj.weather[0].description; document.getElementById('newYork-location').innerHTML = obj.name; document.getElementById('newYork-temp').innerHTML = Math.round(obj.main.temp - 273.15) + ' C'; document.getElementById('newYork-icon').src = "http://openweathermap.org/img/w/" + obj.weather[0].icon + ".png"; } request.send(); linkPekin = "https://api.openweathermap.org/data/2.5/weather?q=Pekin,cn&appid=a2bd7213a39113727af6fff678a49f8d"; var request = new XMLHttpRequest(); request.open('GET', linkPekin, true); request.onload = function () { var obj = JSON.parse(this.response); console.log(obj); document.getElementById('pekin-weather').innerHTML = obj.weather[0].description; document.getElementById('pekin-location').innerHTML = obj.name; document.getElementById('pekin-temp').innerHTML = Math.round(obj.main.temp - 273.15) + ' C'; document.getElementById('pekin-icon').src = "http://openweathermap.org/img/w/" + obj.weather[0].icon + ".png"; } request.send(); let user = localStorage.getItem('currenUser') var slideIndex = JSON.parse(localStorage.getItem('users')).user.find((f) => f.login == user).currentCity + 1; showSlides(slideIndex); function plusSlides(n) { showSlides(slideIndex += n); } function currentSlide(n) { showSlides(slideIndex = n); } function showSlides(n) { var i; var slides = document.getElementsByClassName("mySlides"); var dots = document.getElementsByClassName("dot"); if (n > slides.length) { slideIndex = 1 } if (n < 1) { slideIndex = slides.length } for (i = 0; i < slides.length; i++) { slides[i].style.display = "none"; } for (i = 0; i < dots.length; i++) { dots[i].className = dots[i].className.replace(" active", ""); } setCurrentCity(slideIndex-1); slides[slideIndex - 1].style.display = "block"; dots[slideIndex - 1].className += " active"; } function setCurrentCity(index) { let obj = localStorage.getItem('users') obj = JSON.parse(obj) let user = localStorage.getItem('currenUser') let i = obj.user.findIndex((f) => f.login == user) obj.user[i].currentCity = index localStorage.setItem(`users`, JSON.stringify(obj)) } window.onload = function () { document.body.classList.add('loaded_hiding'); window.setTimeout(function () { document.body.classList.add('loaded'); document.body.classList.remove('loaded_hiding'); }, 500); }
String.prototype.urlsafe = function () { return this.replace(/\+/g, "-").replace(/\//g, "_") } var CryptoJS = require("crypto-js") var AK = "WR1-2JkrICcpLvdw15L" var SK = "1blyh54_uoulFjMPPAt" var bucket = "jspt" var domain = "p5jdshw2w.bkt.clouddn.com" var deadline = Math.round(new Date().getTime() / 1000) + 1 * 3600 var params = { scope: bucket, deadline: deadline } var policy = JSON.stringify(params) var policyEncoded = $text.base64Encode(policy).urlsafe() var sign = CryptoJS.HmacSHA1(policyEncoded, SK) var signEncoded = sign.toString(CryptoJS.enc.Base64).urlsafe() var token = AK + ":" + signEncoded + ":" + policyEncoded function pickImage() { $photo.pick({ format: "image", handler: function (resp) { var image = resp.image image ? upload(image) : null } }) } function upload(image) { $http.upload({ url: "http://up-z1.qiniu.com/", form: { token: token }, files: [{ "image": image, "name": "file", "filename": "file" }], handler: function (resp) { if (resp.data.key) { var url = "http://" + domain + "/" + resp.data.key $clipboard.text = url $device.taptic(0) $ui.toast("链接已复制到剪贴板") } else { $ui.toast(resp.data.error) } } }) } pickImage()
export default class RemoveUserUseCase { constructor({database, logger}) { this.userDao = database.userDao(); this.logger = logger; } async execute(param) { const user = await this.userDao.removeUser(param.id) delete user.password return user } }
import React, { useState } from "react"; // ? Styles import "./styles/modal.css"; export const Modal = ({toggleModal, token, getJogs}) => { const [distance, setDistance] = useState('') const [time, setTime] = useState('') const [jogDate, setJogDate] = useState('') const onSave = async () => { if (distance && time && jogDate) { await fetch("https://jogtracker.herokuapp.com/api/v1/data/jog", { body: `date=${jogDate}&time=${time}&distance=${distance}`, headers: { Accept: "application/json", Authorization: `Bearer ${token}`, "Content-Type": "application/x-www-form-urlencoded" }, method: "POST" }) getJogs(); toggleModal(false); } else { alert("All fields are required"); } } return ( <div className="modal-wrapper"> <form className="modal" onSubmit={(e) => e.preventDefault()}> <div> <span>Distance</span> <input type="number" placeholder="km" value={distance} onChange={e => setDistance(e.target.value)}/> </div> <div> <span>Time</span> <input type="number" placeholder="min" value={time} onChange={e => setTime(e.target.value)}/> </div> <div> <span>Date</span> <input type="date" value={jogDate} onChange={e => setJogDate(e.target.value)}/> </div> <button className="save-btn" onClick={() => onSave()}>Save</button> <button className="close-btn" onClick={() => toggleModal(false)}><span></span><span></span></button> </form> </div> ) }
import React from "react"; import imageflat from "./images/01 (1).png"; import imagehouse from "./images/02 (1).png"; import imagepent from "./images/03 (1).png"; import imageduplex from "./images/04 (1).png"; import imageplot from "./images/05 (1).png"; import imagevilla from "./images/06 (1).png"; import { Router, Link } from "react-router-dom"; import{Row,Col}from 'react-bootstrap'; export default function Cards() { return ( <div> <div class="jumbotron"> <Row> <Col lg={3} xs={12} className="logo"> <Link to="/flat"><img src={imageflat} ></img></Link> <h1 class="numbers">01</h1> </Col> <Col lg={3} xs={12} className="text"> <h4>FLAT</h4> <p>Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs.</p> </Col> <Col lg={3} xs={12} className="logo"> <Link to="/house"><img src={imagehouse}></img></Link> <h1 class="numbers">02</h1> </Col> <Col lg={3} xs={12} className="text"> <h4>INDEPENDENT HOUSE</h4> <p>Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs.</p> </Col> </Row> <Row> <Col lg={3} xs={12} className="logo"> <Link to="/pent"><img src={imagepent} ></img></Link> <h1 class="numbers">03</h1> </Col> <Col lg={3} xs={12} className="text"> <h4>PENT HOUSE</h4> <p>Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs.</p> </Col> <Col lg={3} xs={12} className="logo"> <Link to="/duplex"><img src={imageduplex}></img></Link> <h1 class="numbers">04</h1> </Col> <Col lg={3} xs={12} className="text"> <h4>DUPLEX</h4> <p>Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs.</p> </Col> </Row> <Row> <Col lg={3} xs={12} className="logo"> <Link to="/plot"><img src={imageplot} ></img></Link> <h1 class="numbers">05</h1> </Col> <Col lg={3} xs={12} className="text"> <h4>PLOT</h4> <p>Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs.</p> </Col> <Col lg={3} xs={12} className="logo"> <Link to="/villa"><img src={imagevilla}></img></Link> <h1 class="numbers">06</h1> </Col> <Col lg={3} xs={12} className="text"> <h4>VILLA</h4> <p>Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs.</p> </Col> </Row> </div> </div> ) }
import mongoose from "mongoose"; const Schema = mongoose.Schema; const ObjectId = Schema.Types.ObjectId; const Novel = new mongoose.Schema({ type: { type: String, default: "Normal" }, name: { type: String, unique: true }, url: { type: String }, author: { type: String }, introduction: { type: String }, img: { type: String, default: "" }, updateTime: { type: String }, lastChapterTitle: { type: String }, countChapter: { type: String } }); Novel.statics = { test: function () { return this.find().exec(); } }; export default mongoose.model("novel", Novel);
import React,{useState,useEffect,useContext} from "react"; import AuthContext from "../context/Auth/AuthContext" import {Jumbotron,Spinner,Container,Card,Row,Col,Button} from "react-bootstrap" import ArticleContext from "../context/Article/ArticleContext"; import Main from "./Main" const Home = (props) => { const {userInfo}=useContext(AuthContext); const {getAllArticles,articleLoading,articles}=useContext(ArticleContext) useEffect(() =>{ getAllArticles() //eslint-disable-next-line },[]) const handleClick=(id) =>{ console.log(id) props.history.push(`/article/${id}`) } return ( <> {userInfo && userInfo.length > 0 ? <></> : <Main />} {articleLoading ? ( <></> ) : ( <Row style={{margin:"3vh 10vw 0 10vw"}}> {articles.length > 0 && articles.map((c) => { const id=c._id; return ( <Col md={4}> <Card style={{ width: "18rem" }}> {c.image ? <Card.Img variant="top" src={c.image} /> : <></>} <Card.Body> <Card.Title> <h3 style={{ fontWeight: "600", fontSize: "20px" }}> {c.title} </h3> </Card.Title> <Card.Text style={{ fontSize: "16px" }} > {c.description.substring(0, 50)}.... </Card.Text> <Button variant="success" onClick={() => { handleClick(c._id); }} > Read Article </Button> </Card.Body> </Card> </Col> ); })}{" "} </Row> )} </> ); }; export default Home;
const dbUtil = require('../utils/dbUtil') const { QueryTypes } = require('sequelize'); const AbstractUI = require('./AbstractUI') class EnrollmentScheduleUI extends AbstractUI { async getAutoComplete(request, callback) { const field = request.params.field; const code = request.params.code; if (field == "schoolScheduleCode") { const sequelize = await dbUtil.getConnection(); let sql = ` select sched.code 'key', concat(sched.subjectCode,' - ',' [',startTime,' to ',endTime,'] by ',fac.firstName,' ',fac.lastName) 'value' from SchoolSchedule sched join Person fac on sched.facultyEmail = fac.email ` if (code != null && code != "") { sql += ` and (subjectCode like '%${code}%') ` } sql += " order by sched.subjectCode" const records = await sequelize.query(sql, { type: QueryTypes.SELECT }); callback(records); } else { throw new Error(`AutoComplete for ${field} not implemented in ${this.constructor.name}`) } } async getAutoCompleteLabel(request, callback) { const field = request.params.field; const code = request.params.code; if (field == "schoolScheduleCode") { const sequelize = await dbUtil.getConnection(); const sql = ` select sched.code 'key', concat(sched.subjectCode,' - ',' [',startTime,' to ',endTime,'] by ',fac.firstName,' ',fac.lastName) 'value', 'schoolScheduleCode' fieldName from SchoolSchedule sched join Person fac on sched.facultyEmail = fac.email where sched.code = '${code}' ` const records = await sequelize.query(sql, { type: QueryTypes.SELECT }); callback(records[0]); } else { throw new Error(`AutoCompleteLabel for ${field} not implemented in ${this.constructor.name}`) } } getLeftMenu(user) { return { groupName: "School", group: "School", name: "EnrollmentScheduleUI", label: "Student Schedule" }; } } const enrollmentScheduleUI = new EnrollmentScheduleUI() module.exports = enrollmentScheduleUI;
const puppeteer = require('puppeteer'); const path = require('path') const http = require('http'); const fs = require('fs'); function download(url, dest, callback) { var file = fs.createWriteStream(dest); var request = http.get(url, function(response) { response.pipe(file); file.on('finish', function() { file.close(callback); }); }); } function sleep(ms) { return new Promise(resolve => { setTimeout(resolve, ms) }) } const configFile = process.argv[2] || 'config.json' if (!fs.existsSync(configFile)) { console.log(`Could not file configuration file ${configFile}.`) return } const config = JSON.parse(fs.readFileSync(configFile)); if (!config.username || !config.password) { console.log('Credentials not specified in configuration.') return } (async () => { console.log(path.resolve('.')) const browser = await puppeteer.launch({ headless: true }); const page = await browser.newPage(); page.setViewport({ width: 1600, height: 1000, isLandscape: 1600 > 1000 }) await page.goto('https://entre.stofast.se'); const usernameField = await page.waitForSelector("input[name='Username']") await usernameField.type(config.username) const passwordField = await page.waitForSelector("input[name='Password']") await passwordField.type(config.password) page.on('dialog', async dialog => { console.log('Dismissing pop-up window.'); await dialog.dismiss(); }); console.log(`Logging in as ${config.username}.`) page.click('#loginSubmitButton') const reportsLink = await page.waitForSelector("div[data-id='C12579AC0034E010C125826A003198F2'] > a") const p = new Promise(resolve => { browser.once("targetcreated", async (target) => { console.log('New window opened. Assume it is the Xpand report application.'); resolve(target); }) reportsLink.click(); }); const t = await p; const newPage = await t.page(); if (newPage) { const reportName = 'Boendeinformation' const reportLinkRow = await newPage.waitForXPath(`//tr[td/span/text()='${reportName}']`) reportLinkRow.click(); console.log('Choosing the correct report.') newPage.waitForSelector("#ctl00_UpdateProgress", { visible: true }); newPage.waitForSelector("#ctl00_UpdateProgress", { hidden: true }); const runLink = await newPage.waitForXPath("//div[@class='GroupContainer']//a[text()='Kör']") runLink.click(); console.log('Waiting for initial report to be generated.') //await newPage._client.send('Page.setDownloadBehavior', { behavior: 'allow', downloadPath: path.resolve('.') }) const excelLink = await newPage.waitForXPath("//div[contains(@id, 'pnlReport')]//a[contains(@id, 'lbtExcel')]", { visible: true }); console.log('Found link to download report as Excel file.') const e = new Promise(resolve => { newPage.on('response', async response => { const body = await response.text() const match = body.match(/[a-f0-9-]{36}\.xlsx/) if (match) { console.log('An http request returned a page containing the filename of an Excel file.') resolve(match[0]); } }) excelLink.click() }); const excelFileName = await e; const excelFileUrl = `http://tstxpandwebb.stofast.se/IncitXpandWeb16440_1/Temp/${excelFileName}` const downloader = new Promise(resolve => { const safeReportTitle = reportName.replace(/[^A-Za-z0-9]/, '') const excelFileLocal = `./${safeReportTitle}-${Date.now()}.xlsx` console.log(`Attempting to download ${excelFileUrl} to ${excelFileLocal}.`) download(excelFileUrl, excelFileLocal, () => { console.log('Download complete.') resolve(true); }) }) const downloadResult = await downloader console.log(`Download result: ${downloadResult}.`) await browser.close(); } })();
"use strict"; /* istanbul ignore next */ function create(api, EventTarget) { class Worker extends EventTarget { get onmessage() { void(this); } set onmessage(value) { void(this, value); } get onerror() { void(this); } set onerror(value) { void(this, value); } terminate() { void(this); } postMessage(message, transfer) { void(this, message, transfer); } } return Worker; } module.exports = { create };
const path = require('path'); const maxmind = require('maxmind'); const logger = require('../logger'); const config = require('../../config'); const geoDbPath = path.resolve(__dirname, 'GeoLite2-City.mmdb'); let dbIns; module.exports = { async getdbIns () { await maxmind.open(geoDbPath) .then(db => { dbIns = db; }) .catch(err => { console.error('maxmind open error', err); process.exit; }); }, getGeo (ip) { return new Promise((resolve, reject) => { try { const theip = (ip === '127.0.0.1' || /^(10|172.1[6-9]|172.2[0-9]|172.3[01]|192.168)\./.test(ip)) ? config.defaultIp : ip; let response = dbIns.get(theip); if (response) { if (response && response.subdivisions && response.subdivisions[0] && response.subdivisions[0] && response.subdivisions[0].names && response.subdivisions[0].names['zh-CN']) { var province = response.subdivisions[0].names['zh-CN'] || ''; } var city = (response.city && response.city.names['zh-CN']) || ''; city = city.replace('市', ''); var country = response.country ? response.country.names['zh-CN'] : ''; const result = { location: `${country || ''}${province || ''}${city || ''}`, lnglat: response.location ? `${response.location.longitude}-${response.location.latitude}` : '' }; resolve(result); } } catch (err) { console.error('exec get geo error ' + ip); console.error(err); resolve(null); } }); } };
import React, { useState } from 'react' import { withRouter} from 'react-router-dom'; import { Row, Col, ListGroup, Form } from 'react-bootstrap' function ProductCard({description, mantraListName, header, productId, history}) { const [qty, setQty] = useState(1) const addToCart = (e) => { const productId = e.target.attributes.product.nodeValue history.push(`/cart/${productId}?qty=${qty}`) } return ( <div className="card text-white bg-secondary mb-3" style={{maxWidth: '20rem'}}> <div className="card-header">{header}</div> <div className="card-body"> <h4 className="card-title">{mantraListName}</h4> <p className="card-text">{description}</p> <ListGroup.Item fluid='xs'> <Row > <Col md={6} >Qty</Col> <Col md={4} className="product-page-section"> <Form.Control as='select' value={qty} onChange={(e) => setQty(e.target.value)}> { [...Array(10).keys()].map(x => ( <option value={x + 1} key={x + 1} >{x + 1}</option> )) } </Form.Control> </Col> {/* </Row> */} <Col md={6} > <button product={productId} onClick={e => addToCart(e)} type="button" className="btn btn-info btn-sm">Add to Cart</button> </Col> </Row> </ListGroup.Item> </div> </div> ) } export default withRouter(ProductCard);
/** * JQuery functions * Called when HTML page is loaded * * @author ALBALADEJO Julie * @author NATIVO Nicolas */ $(document).ready(function () { /* MAP INITIALIZATION */ var map = L.map('map').setView([48.85776, 2.33939], 11); L.tileLayer('https://{s}.tiles.mapbox.com/v3/{id}/{z}/{x}/{y}.png', { maxZoom: 18, attribution: 'Map data &copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, ' + '<a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' + 'Imagery © <a href="http://mapbox.com">Mapbox</a>', id: 'examples.map-i875mjb7' }).addTo(map); var departements = []; var station = new Array(); var markers = []; /** * Fetch JSON data * @param {type} result */ $.getJSON("../json/sncf-gares-et-arrets-transilien-ile-de-france.json", function (result) { format: "json", $.each(result, function (i, field) { departements.push(field.fields.code_insee_commune.substr(0, 2)); station.push(field.fields.nom_gare); station.push(field.fields.code_insee_commune.substr(0, 2)); station.push(field.geometry.coordinates[0]); station.push(field.geometry.coordinates[1]); }); /* Table management */ departements.sort(); departements = departements.clearDoublon(); /* Add data to dropdown menu */ for (var i = 0; i < departements.length; i++) { $("#menu > #nav > .nav-primary > li").next(".sub-menu").append("<li id='d" + departements[i] + "''><a href='#'>" + departements[i] + "</a></li>"); /* Sub-menu event listeners */ document.getElementById("d" + departements[i]).addEventListener("mouseover", function () { $(this).css("color", "#f5f5f5"); $(this).css("text-shadow", "rgba(255,255,255,0.5) 0px 0px 5px"); }); document.getElementById("d" + departements[i]).addEventListener("mouseout", function () { $(this).css("color", "#a3abb0"); $(this).css("text-shadow", "none"); }); document.getElementById("d" + departements[i]).addEventListener("click", function () { for(var i=0;i<markers.length;i++) { map.removeLayer(markers[i]); } markers = []; var j = 0; for(var i=0;i<station.length/4;i=i+4) { if("d"+station[i+1]===$(this).attr("id")){ markers[j] = new L.marker([station[i+3], station[i+2]]).addTo(map).bindPopup(station[i]); j++; } } }); }//endfor }); /** * Menus events on mouse clic */ $("#menu > #nav > .nav-primary > li.level0 > a").click(function () { /* Opening sub-menu */ if ($(this).attr("id") !== "allStation") { if ($(this).attr("class") === "level0 active") { $(this).parents("li").next(".sub-menu").slideUp(); $(this).removeClass("active"); } /* Closing sub-menu */ else { $(this).parents("li").next(".sub-menu").slideDown(); $(this).addClass("active"); } } /* Display all stations */ else { for(var i=0;i<markers.length;i++) { map.removeLayer(markers[i]); } var j = 0; for (var i = 0; i < station.length / 4; i = i + 4) { markers[j] = new L.marker([station[i + 3], station[i + 2]]).addTo(map).bindPopup(station[i]); j++; } } }); /* Mouse clic menu effect */ $('#menu .nav-primary > li > a').mousedown(function (ev) { $(this).css('backgroundColor', '#1f2122'); }); $('#menu .nav-primary > li > a').mouseup(function (ev) { $(this).css('backgroundColor', '#282a2b'); }); /* Hover menu effect */ $('#menu .nav-primary > li > a').mouseover(function (ev) { $(this).css("backgroundColor", "#2f3336"); }); $('#menu .nav-primary > li > a').mouseout(function (ev) { $(this).css("backgroundColor", "#282a2b"); }); }); /** * * @param {type} Tab * @param {type} a * @returns {Boolean} */ function middlepop(Tab, a) { return (a > Tab.length) ? false : (Tab.slice(0, a).concat(Tab.slice(a + 1, Tab.length))); } /** * Deletes duplications * @returns {Array} with duplications cleared */ Array.prototype.clearDoublon = function () { ArrayLength = this.length; var TempArray = new Array(); TempArray = this; TempArray2 = this; var cleared = false; for (i = 0; i < ArrayLength; i++) { for (j = 0; j < TempArray.length; j++) { if (!cleared && (i === j)) j++; cleared = false; if (TempArray[i] === TempArray2[j]) { TempArray2 = middlepop(TempArray, j); TempArray = TempArray2; cleared = true; j--; } } } return TempArray; };
//Change "collectionName" and parameters of "createItem" and "edit" let service = (() => { let collectionName = 'flights'; function loadItems() { return requester.get('appdata', collectionName, 'kinvey'); } function loadPublicItems() { return requester.get('appdata', collectionName, 'kinvey'); } function loadItemDetails(itemId) { return requester.get('appdata', collectionName + '/' + itemId, 'kinvey'); } function createItem(destination, origin, departureDate, departureTime, seats, cost, img, isPublic) { let data = {destination, origin, departureDate, departureTime, seats, cost, img, isPublic}; return requester.post('appdata', collectionName, 'kinvey', data); } function edit(itemId, destination, origin, departureDate, departureTime, seats, cost, img, isPublic) { let data = {destination, origin, departureDate, departureTime, seats, cost, img, isPublic}; return requester.update('appdata', collectionName + '/' + itemId, 'kinvey', data); } function remove(itemId) { return requester.remove('appdata', collectionName + '/' + itemId, 'kinvey'); } // function joinTeam(adId) { // let userData = { // username: sessionStorage.getItem('username'), // adId: adId // }; // return requester.update('user', sessionStorage.getItem('userId'), 'kinvey', userData); // } // // function leaveTeam() { // let userData = { // username: sessionStorage.getItem('username'), // adId: '' // }; // // return requester.update('user', sessionStorage.getItem('userId'), userData, 'kinvey'); // } return { loadItems, loadItemDetails, createItem, edit, remove // joinTeam, // leaveTeam } })();
// 노드는 최대 2개의 자식노드를 갖는다. class Node { constructor(value) { this.value = value; this.left = null; this.right = null; } } // 이분탐색트리 // 음~~ 개인적으로 삽입정렬의 비선형구조로서의 업그레이드판이라고 생각하면 될듯. // 각각의 노드에 비교를 하여 작은 값은 왼쪽으로 큰값은 오른쪽으로 이동하여 저장. // 원하는 데이터를 찾기 쉽고 빠르다. class BinarySearchTree { constructor() { this.root = null; } // DFS // 트리 탐색의 한 종류로서 sibling노드를 모두 방문하기 전에 자식노드를 먼저 탐색한다. // 우선적으로 자식노드를 방문하지만 경우에 따라 부모를 먼저 탐색할지, 자식을 먼저 탐색할지, 가진 자식을 모두 탐색하는 방법으로 나뉜다. // 1 // 2 3 // 4 5 6 DFSPreOrder() { var data = []; function traverse(node) { data.push(node.value); if (node.left) traverse(node.left); if (node.right) traverse(node.right); } traverse(this.root); return data; } // 6 // 3 5 // 1 2 4 DFSPostOrder() { var data = []; function traverse(node) { if (node.left) traverse(node.left); if (node.right) traverse(node.right); data.push(node.value); } traverse(this.root); return data; } // 4 // 2 5 // 1 3 6 DFSInOrder() { var data = []; function traverse(node) { if (node.left) traverse(node.left); data.push(node.value); if (node.right) traverse(node.right); } traverse(this.root); return data; } }
'use strict'; const joi = require('joi'); module.exports = (api) => { api.addRoute({ path: '/hello', validation: { query: { name: joi.string().required() } }, handler: (req) => Promise.resolve(`Hello, ${req.query.name}!`) }); };
export { increment, decrement, addition, subtraction } from './counter'; export { storeResult, deleteResult } from './result'; export { INCREMENT, DECREMENT, ADDITION, SUBTRACTION, STORE_RESULT, DELETE_RESULT } from './actionTypes';
import React from 'react' import ArticleDetails from '../ArticleDetails'; import Footer from '../Footer'; import Navbar from '../Navbar'; const CourseDetailsPage = () => { return ( <> <Navbar/> <ArticleDetails/> <Footer style={{background:"#fff"}}/> </> ) } export default CourseDetailsPage
/* * Author: unscriptable * Date: Feb 22, 2009 */ dojo.provide('dojoc.dojocal.views.WeekView'); dojo.require('dojoc.dojocal.views.MultiDayViewBase'); (function () { // closure for local variables var djc = dojoc.dojocal; /** * dojoc.dojocal.views.WeekView */ dojo.declare('dojoc.dojocal.views.WeekView', dojoc.dojocal.views.MultiDayViewBase, { // overrides name: 'WEEK', headerDatePattern: 'EEE M/dd', dayCount: 7, // internal properties _startDate: null, // overrides setDate: function (/* Date|String? */ date) { var prevWeekStartDate = this._startDate; this.inherited(arguments); // calc week start date this._startDate = djc.getWeekStartDate(date, this.weekStartsOn); this._endDate = dojo.date.add(this._startDate, 'day', 7); // if the week changed if (!prevWeekStartDate || dojo.date.compare(prevWeekStartDate, this._startDate) != 0) { this._setHeaderDates(); this._setCornerHeaderDate(); this._setTimeColumnDates(); // TODO: does this really belong here (for DST)? this._checkDayHighlighting(); this._checkTodayHighlighting(); } }, _addEvent: function (eWidget) { this.inherited(arguments); function showTitle (widget, size) { // expand title to span all pseudo-widgets // dojo.style(widget.domNode, { // overflow: 'visible', // allows text to spread across cloned events // zIndex: '10' // overrides hovered/selected of other events which covers title text // }); dojo.addClass(widget.domNode, 'titleDay'); dojo.style(widget.titleNode, { //visibility: 'visible', width: size * 100 + '%'//, // span all sister-widgets in this row //left: -(size - 1) * 100 + '%', // position at first sister-widget //marginLeft: -(size - 2) +'px' // fine-tuning due to table cell borders / event padding. TODO: get the padding from computed style }); } if (eWidget.isAllDay()) { // check for event splitting due to multi-day events var startDate = eWidget.getDateTime(), endDate = eWidget.getEndDateTime(); if (startDate < endDate) { // loop through entire week and add pseudo widgets if needed var weekFirst = djc.maxDate(startDate, this._startDate), weekLast = djc.minDate(endDate, dojo.date.add(this._endDate, 'day', -1)), date = weekFirst, pos = this._dayOfWeekToCol(weekFirst.getDay()), visCount = 0, // count of visible widgets for this event currWidget = eWidget, root, // the first widget (set below) firstOfWeek; // the widgets that fall on the first day of each week do { if (!root) { root = currWidget; var node = eWidget.domNode, baseClasses = node.className; firstOfWeek = root; } else { currWidget = this._cloneEventWidget(eWidget); currWidget.startup(); node = currWidget.domNode; visCount++; } // if we are at the start of the week, show the title if (pos % 7 == 0) { // fix-up previous firstOfWeek if (firstOfWeek) showTitle(firstOfWeek, visCount); // set new one firstOfWeek = currWidget; visCount = 1; } this._addEventToAllDayLayout(currWidget, this._allDayLayouts[pos]); // check for first, last, or intra-day var isFirstDay = dojo.date.compare(date, startDate, 'date') == 0, isLastDay = dojo.date.compare(date, endDate, 'date') == 0, isIntraDay = !isFirstDay && !isLastDay, classes = [baseClasses, 'dojocalAllDay dojocalMultiday']; // add appropriate classes if (isFirstDay) classes.push('firstDay'); if (isLastDay) classes.push('lastDay'); if (isIntraDay) classes.push('middleDay'); if (currWidget != root) classes.push('pseudoDay'); dojo.addClass(node, classes.join(' ')); pos++; date = dojo.date.add(date, 'day', 1); } while (date <= weekLast); if (firstOfWeek) showTitle(firstOfWeek, visCount); } // otherwise, single-day event else { pos = this._dayOfWeekToCol(startDate.getDay()); dojo.addClass(currWidget.domNode, 'dojocalAllDay'); this._addEventToAllDayLayout(eWidget, this._allDayLayouts[pos]); } } else { // TODO: check for event splitting due to crossing of midnight pos = this._dayOfWeekToCol(eWidget.getDateTime().getDay()); this._addEventToDayLayout(eWidget, this._dayLayouts[pos]); } }, _updateEvent: function (eWidget) { // updates the view-specific visual representation of the event based on new data (e.g. time of day) // TODO: move event to correct layout / time of day } }); })(); // end of closure for local variables
export const LOCALES_WITH_SITEMAP = ['et-EE'] export const LOCALES_WITH_CHAT_BOT = [ 'en-IE', 'bg-BG', 'et-EE', 'el-GR', 'hr-HR', 'lv-LV', 'pt-PT', 'da-DK', 'lt-LT', 'it-IT', 'fi-FI', 'en-AU', 'sl-SI', 'en-US', 'hu-HU', 'nb-NO', 'sk-SK', 'cs-CZ', 'es-ES', 'ro-RO', 'en-GB', 'sv-SE', 'pl-PL', 'de-CH', 'fr-CH', 'fr-BE', 'nl-BE', 'de-AT', 'fr-FR', 'nl-NL', 'de-DE' ] export const PAGES_NAMES_WITH_SCROLLABLE_HEADER = ['checkout'] export const FUNNEL_PAGE_WITH_SCROLLABLE_HEADER = ['login', 'cart'] export const DELIVERY_TYPES = { home: 'home-delivery', parcel: 'parcel-shop-delivery' } export const ERROR_CODES = { timeout: 'ECONNABORTED', forbidden: 403, badRequest: 400, invalidToken: 'TokenInvalidError', resetPassTokenExist: 'active_reset_password_token_exists' } export const EXECUTED_POST_CODES = [ '2899', '6798', '6799', '7151' ] export const CHECKOUT_EVENT = { login: { label: 'Login', eventIndex: 0, eventData: { event: 'login', message: 'Customer complete login and land on checkout' } }, shipping: { label: 'Shipping', eventIndex: 1, eventData: { event: 'shipping', message: 'Customer choose shipping method' } }, payment: { label: 'Payment', eventIndex: 2, eventData: { event: 'payment', message: 'Customer choose payment method' } }, review: { label: 'Review', eventIndex: 3, eventData: { event: 'review', message: 'Customer reviewing the order details' } }, adyen: { label: 'Adyen', eventIndex: 4, eventData: { event: 'adyen', message: 'Go to payment' } } } export const ADYEN_CALLBACK_NONEMPTY_FIELD = [ 'billingAddress.city', 'billingAddress.country', 'billingAddress.postalCode', 'billingAddress.street', 'deliveryAddress.city', 'deliveryAddress.country', 'deliveryAddress.postalCode', 'deliveryAddress.street' ] export const ERROR_SHOULD_HAS_7_CHARCTERS = 2 export const ERROR_SHOULD_HAS_7_CHARCTERS_LETTER_NUMBER = 3 export const ERROR_SHOULD_HAS_7_CHARCTERS_LETTER_NUMBER_256_MAX = 3 export const MAX_PASSWORD_LENGTH = 256 export const CHECKOUT_METHODS = { customer: 'customer', guest: 'guest' } export const AUTH_TYPES = ['login', 'register'] export const MAX_COUNT_CROSS_SELL_PRODUCTS = 20 export const CATEGORIES_WITH_ICONS = [6392, 999999, 988, 922, 888, 772, 696, 6792, 6362, 6356, 6347, 6346, 632, 594, 537, 536, 5181, 500000, 469, 457, 443, 436, 2002, 166, 141, 1239, 111, 107, 1] export const PRINT_ORDER_IFRAME_ID = 'print-order' export const CASH_ON_DELIVERY_METHOD_NAME = 'COD' export const GA_CHECKOUT_TYPES = { PayPal: 'PayPal', Normal: 'Normal', Guest: 'Guest', NotSet: 'not set' } export const LS_PAYMENT_METHOD_KEY = 'checkedPaymentMethod' export const CMS_BLOCKS_IDS = { orderDelay: 'order_delay_block' }
/* This file is part of GeoRide-. * * GeoRide-Jeedom is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * GeoRide- is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Jeedom. If not, see <http://www.gnu.org/licenses/>. */ $("#table_cmd").sortable({ axis: "y", cursor: "move", items: ".cmd", placeholder: "ui-state-highlight", tolerance: "intersect", forcePlaceholderSize: true }); function addCmdToTable(_cmd) { if (!isset(_cmd)) { var _cmd = {configuration: {}}; } if (!isset(_cmd.configuration)) { _cmd.configuration = {}; } var tr = '<tr class="cmd" data-cmd_id="' + init(_cmd.id) + '">'; tr += '<td>'; tr += '<span class="cmdAttr" data-l1key="id" style="display:none;"></span>'; tr += '<input class="cmdAttr form-control input-sm" data-l1key="name" style="width : 140px;" placeholder="{{Nom}}">'; tr += '</td>'; tr += '<td>'; tr += '<span class="type" type="' + init(_cmd.type) + '">' + jeedom.cmd.availableType() + '</span>'; tr += '<span class="subType" subType="' + init(_cmd.subType) + '"></span>'; tr += '</td>'; tr += '<td>'; tr += '<span><input type="checkbox" class="cmdAttr checkbox-inline" data-l1key="isHistorized" /> {{Historiser}}<br/></span>'; tr += '<span><input type="checkbox" class="cmdAttr checkbox-inline" data-l1key="isVisible" /> {{Affichage}}<br/></span>'; tr += '</td>'; tr += '<td>'; if (is_numeric(_cmd.id)) { tr += '<a class="btn btn-default btn-xs cmdAction" data-action="configure"><i class="fa fa-cogs"></i></a> '; tr += '<a class="btn btn-default btn-xs cmdAction" data-action="test"><i class="fa fa-rss"></i> {{Tester}}</a>'; } tr += '<i class="fa fa-minus-circle pull-right cmdAction cursor" data-action="remove"></i>'; tr += '</td>'; tr += '</tr>'; $('#table_cmd tbody').append(tr); $('#table_cmd tbody tr:last').setValues(_cmd, '.cmdAttr'); if (isset(_cmd.type)) { $('#table_cmd tbody tr:last .cmdAttr[data-l1key=type]').value(init(_cmd.type)); } jeedom.cmd.changeType($('#table_cmd tbody tr:last'), init(_cmd.subType)); } /* * Get box on georide account */ function getGeorideBox(event, APIToken) { event.preventDefault(); $.ajax ({ type: "GET", url: "https://api.georide.fr/user/trackers", headers: { "Authorization": "Bearer " + APIToken }, error: function (XMLHttpRequest, textStatus, errorThrown) { alert('{{Erreur lors de la récupération des trackers, veuillez vérifier votre clée API ou le status de api.georide.fr.}} Code: ' + XMLHttpRequest.responseJSON.error); }, success: function (data) { var lines = ''; for (var i = 0; i < data.length; i++) { lines += '<tr style="cursor: pointer" class="lines-tracker" attr-id="' + data[i].trackerId + '"><td>' + data[i].trackerId + '</td><td>' + data[i].trackerName + '<td></tr>'; } $('#ListTrackers').html(lines); setTimeout(() => { $('.lines-tracker').click((e) => { $('.selected-tracker').css('color', 'black'); $('.selected-tracker').removeClass('selected-tracker'); $(e.target.parentNode).addClass('selected-tracker'); $('.selected-tracker').css('color', 'orange'); document.getElementById('TrackerID').value = e.target.parentNode.getAttribute('attr-id'); }); }, 500); } }); } /* * API Key */ function getAPIKey(event) { event.preventDefault(); $.ajax ({ type: "POST", url: "https://api.georide.fr/user/login", data: { email: document.getElementById('EmailGeoRide').value, password: document.getElementById('PasswordGeoRide').value }, error: function (XMLHttpRequest, textStatus, errorThrown) { alert('{{Erreur lors de la récupération de la clée API, veuillez vérifier vos données ou le status de api.georide.fr.}} Code: ' + XMLHttpRequest.responseJSON.error); }, success: function (data) { document.getElementById('APIToken').value = data.authToken; document.getElementById('EmailGeoRide').value = null; document.getElementById('PasswordGeoRide').value = null; } }); }
atom.declare("Game.Part_turret_1", Game.Part, { configure: function method() { this.textureMain = Controller.images.get("part2"); this.deadTexture = Controller.images.get("part2_broken"); this.HP = 30; this.target = null; this.targetSearchTime = 0; this.targetSearchTimeValue = 1000; this.attackDistance = this.getDefaultOrSettings("attackDistance", 500); this.attackHuntDistance = 100; this.rotationSpeed =this.getDefaultOrSettings("rotationSpeed", 0.01); this.attackCooldownValue = this.getDefaultOrSettings("attackCooldownValue", 600); this.attackCooldown = atom.number.random(0, this.attackCooldownValue); this.bulletLifeTime = this.getDefaultOrSettings("bulletLifeTime", 1500); this.bulletDamage = this.getDefaultOrSettings("bulletDamage", 10); this.bulletSize = this.getDefaultOrSettings("bulletSize", 3); this.type = "turret"; method.previous.call(this); }, getDefaultOrSettings: function(name, defaultValue) { var settings_value = this.settings.get(name); if (settings_value == null) return defaultValue; else return settings_value; }, searchTarget: function() { var targetList = []; for (var i=0; i<Controller.ships.length; i++) { var ship = Controller.ships[i]; if (ship.team == this.parent.team) continue; var distance = this.parent.shape.center.distanceTo(ship.shape.center); if (distance > this.attackDistance) continue; targetList.push(ship); } if (targetList.length == 0) return; var indx = atom.number.random(0, targetList.length - 1); this.target = targetList[indx]; }, validateTarget: function() { if (this.target.killed != null && this.target.killed == true) return false; var distance = this.parent.shape.center.distanceTo(this.target.shape.center); if (distance > this.attackDistance + this.attackHuntDistance) return false; return true; }, // c - коэффициент, если лево = -1, право = 1 rotate: function(time, c) { this.angle += c * this.rotationSpeed * time; this.parent.redraw(); }, piupiu: function(position, angle, time) { this.attackCooldown += time; if (this.attackCooldown > this.attackCooldownValue) { this.attackCooldown = 0; new Game.Bullet(Controller.layerShips, { position: position, angle: angle + (Math.random() - 0.5) / 4, speed: 0.4, lifeTime: this.bulletLifeTime, damage: this.bulletDamage, team: this.parent.team, bulletSize: this.bulletSize }); } }, updateFunc: function(time) { if (this.killed) return; if (this.target == null) { this.targetSearchTime += time; if (this.targetSearchTime > this.targetSearchTimeValue) { this.targetSearchTime = 0; this.searchTarget(); } return; } if (!this.validateTarget()) { this.target = null; this.attackCooldown = 0; return; } var position = this.parent.partRealPosition(this); var angle = this.parent.partRealAngle(this); var aimingCoef = Controller.Aim.calculate(position, angle, this.target); if (aimingCoef == 0) this.piupiu(position, angle, time); else this.rotate(time, aimingCoef); } });
var data = [ { Id:'bar', //实例化dom,每个图表必须唯一 lineTitle:'柱状图实例', //示例的标题 xAxisData:["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"], //示例的x轴数据 seriesName:'test', //数据的所有的标题 seriesType:'bar', //示例的类型 seriesData:[ //展示的数据 {value:25, name:'衬衫2',itemStyle: { color: '#041527' }}, {value:35, name:'羊毛衫21',itemStyle: { color: 'pink' }}, {value:23, name:'雪纺衫2',itemStyle: { color: 'cyan' }}, {value:5, name:'裤子22'}, {value:15, name:'高跟鞋2'}, {value:26, name:'袜子3'} ], },{ Id:'bar2', //实例化dom,每个图表必须唯一 lineTitle:'柱状图实例', //示例的标题 xAxisData:["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"], //示例的x轴数据 seriesName:'test', //数据的所有的标题 seriesType:'bar', //示例的类型 seriesData:[ //展示的数据 {value:25, name:'衬衫2',itemStyle: { color: '#041527' }}, {value:35, name:'羊毛衫21',itemStyle: { color: 'pink' }}, {value:23, name:'雪纺衫2',itemStyle: { color: 'cyan' }}, {value:5, name:'裤子22'}, {value:15, name:'高跟鞋2'}, {value:26, name:'袜子3'} ], },{ Id:'bar3', //实例化dom,每个图表必须唯一 lineTitle:'柱状图实例', //示例的标题 xAxisData:["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"], //示例的x轴数据 seriesName:'test', //数据的所有的标题 seriesType:'bar', //示例的类型 seriesData:[ //展示的数据 {value:25, name:'衬衫2',itemStyle: { color: '#041527' }}, {value:35, name:'羊毛衫21',itemStyle: { color: 'pink' }}, {value:23, name:'雪纺衫2',itemStyle: { color: 'cyan' }}, {value:5, name:'裤子22'}, {value:15, name:'高跟鞋2'}, {value:26, name:'袜子3'} ], },{ Id:'bar4', //实例化dom,每个图表必须唯一 lineTitle:'柱状图实例', //示例的标题 xAxisData:["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"], //示例的x轴数据 seriesName:'test', //数据的所有的标题 seriesType:'bar', //示例的类型 seriesData:[ //展示的数据 {value:25, name:'衬衫2',itemStyle: { color: '#041527' }}, {value:35, name:'羊毛衫21',itemStyle: { color: 'pink' }}, {value:23, name:'雪纺衫2',itemStyle: { color: 'cyan' }}, {value:5, name:'裤子22'}, {value:15, name:'高跟鞋2'}, {value:26, name:'袜子3'} ], },{ Id:'bar5', //实例化dom,每个图表必须唯一 lineTitle:'柱状图实例', //示例的标题 xAxisData:["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"], //示例的x轴数据 seriesName:'test', //数据的所有的标题 seriesType:'bar', //示例的类型 seriesData:[ //展示的数据 {value:25, name:'衬衫2',itemStyle: { color: '#041527' }}, {value:35, name:'羊毛衫21',itemStyle: { color: 'pink' }}, {value:23, name:'雪纺衫2',itemStyle: { color: 'cyan' }}, {value:5, name:'裤子22'}, {value:15, name:'高跟鞋2'}, {value:26, name:'袜子3'} ], },{ Id:'bar6', //实例化dom,每个图表必须唯一 lineTitle:'柱状图实例', //示例的标题 xAxisData:["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"], //示例的x轴数据 seriesName:'test', //数据的所有的标题 seriesType:'bar', //示例的类型 seriesData:[ //展示的数据 {value:25, name:'衬衫2',itemStyle: { color: '#041527' }}, {value:35, name:'羊毛衫21',itemStyle: { color: 'pink' }}, {value:23, name:'雪纺衫2',itemStyle: { color: 'cyan' }}, {value:5, name:'裤子22'}, {value:15, name:'高跟鞋2'}, {value:26, name:'袜子3'} ], },{ Id:'bar7', //实例化dom,每个图表必须唯一 lineTitle:'柱状图实例', //示例的标题 xAxisData:["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"], //示例的x轴数据 seriesName:'test', //数据的所有的标题 seriesType:'bar', //示例的类型 seriesData:[ //展示的数据 {value:25, name:'衬衫2',itemStyle: { color: '#041527' }}, {value:35, name:'羊毛衫21',itemStyle: { color: 'pink' }}, {value:23, name:'雪纺衫2',itemStyle: { color: 'cyan' }}, {value:5, name:'裤子22'}, {value:15, name:'高跟鞋2'}, {value:26, name:'袜子3'} ], },{ Id:'bar8', //实例化dom,每个图表必须唯一 lineTitle:'柱状图实例', //示例的标题 xAxisData:["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"], //示例的x轴数据 seriesName:'test', //数据的所有的标题 seriesType:'bar', //示例的类型 seriesData:[ //展示的数据 {value:25, name:'衬衫2',itemStyle: { color: '#041527' }}, {value:35, name:'羊毛衫21',itemStyle: { color: 'pink' }}, {value:23, name:'雪纺衫2',itemStyle: { color: 'cyan' }}, {value:5, name:'裤子22'}, {value:15, name:'高跟鞋2'}, {value:26, name:'袜子3'} ], },{ Id:'bar9', //实例化dom,每个图表必须唯一 lineTitle:'柱状图实例', //示例的标题 xAxisData:["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"], //示例的x轴数据 seriesName:'test', //数据的所有的标题 seriesType:'bar', //示例的类型 seriesData:[ //展示的数据 {value:25, name:'衬衫2',itemStyle: { color: '#041527' }}, {value:35, name:'羊毛衫21',itemStyle: { color: 'pink' }}, {value:23, name:'雪纺衫2',itemStyle: { color: 'cyan' }}, {value:5, name:'裤子22'}, {value:15, name:'高跟鞋2'}, {value:26, name:'袜子3'} ], },{ Id:'bar10', //实例化dom,每个图表必须唯一 lineTitle:'柱状图实例', //示例的标题 xAxisData:["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"], //示例的x轴数据 seriesName:'test', //数据的所有的标题 seriesType:'bar', //示例的类型 seriesData:[ //展示的数据 {value:25, name:'衬衫2',itemStyle: { color: '#041527' }}, {value:35, name:'羊毛衫21',itemStyle: { color: 'pink' }}, {value:23, name:'雪纺衫2',itemStyle: { color: 'cyan' }}, {value:5, name:'裤子22'}, {value:15, name:'高跟鞋2'}, {value:26, name:'袜子3'} ], } ]
import React, { Component } from 'react'; import axios from 'axios'; import { Jumbotron, Row, Col, Button, Alert } from 'react-bootstrap'; import { Link, Redirect } from 'react-router-dom'; import './Login.css'; import config from '../../../config.json'; class Login extends Component { constructor() { super(); this.state = { loginUser: [], error: null, login: -1 } } handleSubmit(e) { e.preventDefault(); axios.post(`http://172.24.125.116:8000/api/user/login`, { email_id: this.refs.Email.value, password: this.refs.Password.value }) .then(res => { axios.get(`http://172.24.125.116:8000/api/user/${res.data.message}`).then(res => { this.setState({ loginUser: res.data.message }); localStorage.setItem("admin", this.state.loginUser.isadmin); localStorage.setItem("user_id", this.state.loginUser._id); localStorage.setItem("email_id", this.state.loginUser.email_id); localStorage.setItem("user_name", this.state.loginUser.user_name); this.setState({ login: localStorage.getItem("admin"), error: null }); }) }) .catch(error => { this.setState({ error: error.response.data.error }); }); } reset() { this.setState({error: null}); } render() { console.log(); if (localStorage.getItem("admin")==="1") { return ( <Redirect to="/report" /> ); } else if (localStorage.getItem("admin")==="0") { return ( <Redirect to="/question" /> ); } return ( <div className="Login"> <Row> <Jumbotron> <Col xsOffset={5} smOffset={5}> <h1>Sign In</h1> </Col> </Jumbotron> <form onSubmit={this.handleSubmit.bind(this)}> <Row className="row-space"> <Col xs={8} xsOffset={2} sm={4} smOffset={4}> <input className="form-control" type="text" ref="Email" placeholder="Email" /> </Col> </Row> <Row className="row-space"> <Col xs={8} xsOffset={2} sm={4} smOffset={4}> <input className="form-control" type="password" ref="Password" placeholder="Password" /> </Col> </Row> <Col xsPush={1} xs={1} xsOffset={2} smOffset={3} sm={1}> <Button type="submit" bsStyle="primary">Login</Button> </Col> <Col xsPush={1} xs={1} xsOffset={2} smOffset={0} sm={1}> <Button type="reset" onClick={this.reset.bind(this)} bsStyle="primary">Reset</Button> </Col> </form> </Row> <div className="space"> <Col xsOffset={2} smOffset={4} > <strong> {config.data.signin} <Link to="/register"> Register now</Link> </strong> </Col> </div> { this.state.error!=null? <Col className="space" sm={4} smOffset={4}> <Alert bsStyle="danger"> <Col xsOffset={5} smOffset={5} > <strong>{this.state.error}</strong> </Col> </Alert> </Col> :null } </div> ); } } export default Login;
import {graphql} from 'graphql'; import adminSchema from '@/api-server/graphql-schemas/admin-schema'; import adminResolvers from '@/api-server/resolvers/admin-resolvers'; import accountSchema from '@/api-server/graphql-schemas/account-schema'; import accountResolvers from '@/api-server/resolvers/account-resolvers'; import {connect, disconnect, dropDatabase} from '@/api-server/mongo-db-driver'; const TEST_DB = 'store-demo-graphql-admin-test'; beforeAll(async () => await connect({dbName: TEST_DB})); beforeEach(async () => await dropDatabase()); afterAll(async () => { await dropDatabase(); await disconnect(); }); jest.setTimeout(30000); const createProduct = async ({name, price, description}) => { const query = ` mutation { createProduct (input: {name: "${name}", price: ${price}, description: "${description}"}) { id } } `; const response = await graphql(adminSchema, query, adminResolvers); return response.data.createProduct.id; }; describe('createProduct', () => { it('should create a product', async () => { const query = ` mutation { createProduct (input: {name: "my product", price: 12345.05, description: "test"}) { id } } `; const {data} = await graphql(adminSchema, query, adminResolvers); expect(data.createProduct.id).toBeTruthy(); }); it('should fail if the price is negative', async () => { const query = ` mutation { createProduct (input: {name: "my product", price: -19, description: "test"}) { id } } `; const {errors, data} = await graphql(adminSchema, query, adminResolvers); expect(errors).toBeTruthy(); expect(data.createProduct).toBeFalsy(); }); }); describe('findProductById', () => { it('should return a product', async () => { const id = await createProduct({ name: 'test item', price: 444, description: 'This is a test item.', }); const query = `{ findProductById (id: "${id}") { name, price } }`; const {data} = await graphql(adminSchema, query, adminResolvers); expect(data.findProductById). toEqual({ name: 'test item', price: 444, }); }); }); describe('getAllProducts', () => { it('should return an empty array when db is clean', async () => { const query = '{ getAllProducts { id } }'; const {data} = await graphql(adminSchema, query, adminResolvers); expect(data.getAllProducts).toHaveLength(0); }); it('should return a list of products', async () => { await createProduct({ name: 'my item 1', price: 123, description: 'This is Test Item 1.', }); await createProduct({ name: 'my item 2', price: 456, description: 'This is Test Item 2.', }); const query = '{ getAllProducts { name, price } }'; const {data} = await graphql(adminSchema, query, adminResolvers); expect(data.getAllProducts).toHaveLength(2); expect(data.getAllProducts[0]). toEqual({ name: 'my item 1', price: 123, }); expect(data.getAllProducts[1]). toEqual({ name: 'my item 2', price: 456, }); }); }); describe('updateProduct', () => { it('should update a product', async () => { const id = await createProduct({ name: 'soap', price: 3, description: 'This is Soap.', }); const newProduct = { name: 'shampoo', price: 6, description: 'This is Shampoo.', }; const mutation = ` mutation { updateProduct ( id : "${id}", input: {name: "${newProduct.name}", price: ${newProduct.price}, description: "${newProduct.description}" }) { id, name, price, description } } `; const {data: {updateProduct}} = await graphql(adminSchema, mutation, adminResolvers); expect(updateProduct.id).toBeTruthy(); expect(updateProduct.name).toBe(newProduct.name); expect(updateProduct.price).toBe(newProduct.price); expect(updateProduct.description).toBe(newProduct.description); const query = `{ findProductById (id: "${id}") { name, price, description } }`; const {data: {findProductById}} = await graphql(adminSchema, query, adminResolvers); expect(findProductById).toEqual(newProduct); }); }); describe('deleteProduct', () => { it('should delete a product', async () => { const id = await createProduct({ name: 'coffee', price: 10, description: 'This is coffee.', }); const mutation = ` mutation { deleteProduct (id : "${id}") { id, name, price, description } } `; const {data: {deleteProduct}} = await graphql(adminSchema, mutation, adminResolvers); expect(deleteProduct.id).toBeTruthy(); expect(deleteProduct.name).toBe('coffee'); expect(deleteProduct.price).toBe(10); const query = '{ getAllProducts { id } }'; const {data} = await graphql(adminSchema, query, adminResolvers); expect(data.getAllProducts).toHaveLength(0); }); }); const createUser = async ({name, password}) => { const query = ` mutation { createUser (input: {name: "${name}", password: "${password}"}) { id } } `; const response = await graphql(adminSchema, query, adminResolvers); return response.data.createUser.id; }; describe('createUser', () => { it('should create a user', async () => { const query = ` mutation { createUser (input: {name: "the+user", password: "password"}) { id } } `; const {data} = await graphql(adminSchema, query, adminResolvers); expect(data.createUser.id).toBeTruthy(); }); it('should fail when creating a user with a duplicated name', async () => { const query = ` mutation { createUser (input: {name: "the+user", password: "password"}) { id } } `; await graphql(adminSchema, query, adminResolvers); const {errors} = await graphql(adminSchema, query, adminResolvers); expect(errors).toBeTruthy(); }); }); describe('findUserById', () => { it('should return a user', async () => { const id = await createUser({ name: 'test&item', password: 'thisispassword', }); const query = `{ findUserById (id: "${id}") { name } }`; const {data, errors} = await graphql(adminSchema, query, adminResolvers); expect(data.findUserById).toEqual({name: 'test&item'}); expect(errors).toBeFalsy(); }); it('should not return a user with their password', async () => { const id = await createUser({ name: 'test*item', password: 'thisispassword', }); const query = `{ findUserById (id: "${id}") { name, password } }`; const {errors} = await graphql(adminSchema, query, adminResolvers); expect(errors).toBeTruthy(); }); }); describe('findUserByName', () => { it('should return a user', async () => { await createUser({ name: 'test&item', password: 'thisispassword', }); const query = '{ findUserByName (name: "test&item") { name } }'; const {data, errors} = await graphql(adminSchema, query, adminResolvers); expect(data.findUserByName).toEqual({name: 'test&item'}); expect(errors).toBeFalsy(); }); }); describe('getAllUsers', () => { it('should return a list of users', async () => { await createUser({ name: 'user1', password: 'password1', }); await createUser({ name: 'user2', password: 'password2', }); await createUser({ name: 'user3', password: 'password3', }); const query = '{ getAllUsers { name } }'; const response = await graphql(adminSchema, query, adminResolvers); expect(response.data.getAllUsers).toHaveLength(3); expect(response.data.getAllUsers[0]).toEqual({name: 'user1'}); expect(response.data.getAllUsers[1]).toEqual({name: 'user2'}); expect(response.data.getAllUsers[2]).toEqual({name: 'user3'}); }); }); describe('updateUser', () => { it('should update a user', async () => { const id = await createUser({ name: 'userA', password: 'password1', }); const newName = 'userB'; const mutation = ` mutation { updateUser ( id : "${id}", input: { name: "${newName}" } ) { id, name } } `; const response = await graphql(adminSchema, mutation, adminResolvers); expect(response.data.updateUser.id).toBeTruthy(); expect(response.data.updateUser.name).toBe(newName); const query = `{ findUserById (id: "${id}") { id, name } }`; const response2 = await graphql(adminSchema, query, adminResolvers); expect(response2.data.findUserById). toEqual({ id, name: newName, }); }); it('should return null if the old password is not sent.', async () => { const id = await createUser({ name: 'userA', password: 'password1', }); const mutation1 = ` mutation { updateUser ( id : "${id}", input: { password: "newPassword" } ) { id, name } } `; const response = await graphql(adminSchema, mutation1, adminResolvers); expect(response.data.updateUser).toBeNull(); }); it('should return null if the old password is wrong.', async () => { const id = await createUser({ name: 'userA', password: 'password1', }); const mutation1 = ` mutation { updateUser ( id : "${id}", input: { password: "newPassword", oldPassword: "wrongPassword" } ) { id, name } } `; const response = await graphql(adminSchema, mutation1, adminResolvers); expect(response.data.updateUser).toBeNull(); }); it('should return a user if succeeding to update the password.', async () => { const id = await createUser({ name: 'userA', password: 'password1', }); const mutation1 = ` mutation { updateUser ( id : "${id}", input: { password: "newPassword", oldPassword: "password1" } ) { id, name } } `; const response = await graphql(adminSchema, mutation1, adminResolvers); expect(response.data.updateUser). toEqual({ id, name: 'userA', }); }); }); describe('deleteUser', () => { it('should delete a user', async () => { const id = await createUser({ name: 'my_name', password: 'password1', }); const mutation = ` mutation { deleteUser (id : "${id}") { id, name } } `; const {data: {deleteUser}} = await graphql(adminSchema, mutation, adminResolvers); expect(deleteUser.id).toBeTruthy(); expect(deleteUser.name).toBe('my_name'); const query = '{ getAllUsers { id } }'; const {data} = await graphql(adminSchema, query, adminResolvers); expect(data.getAllUsers).toHaveLength(0); }); }); const placeOrder = async ({user, productId, quantity}) => { const query = ` mutation { placeOrder (input : [{productId: "${productId}", quantity: ${quantity}}]) { id } } `; return await graphql(accountSchema, query, accountResolvers, {user}); }; describe('getAllOrders', () => { it('should get all the orders', async () => { const userId = await createUser({ name: 'my_name', password: 'password1', }); const productId = await createProduct({ name: 'Glasses', price: 120, description: 'You\'ll be able to see better.', }); await placeOrder({ user: {id: userId}, productId, quantity: 3 }); await placeOrder({ user: {id: userId}, productId, quantity: 1 }); const query = '{ getAllOrders { id, userId, items { productId, quantity } } }'; const {data} = await graphql(adminSchema, query, adminResolvers); expect(data.getAllOrders[0].items[0].quantity).toBe(3); expect(data.getAllOrders[0].userId).toBe(userId); expect(data.getAllOrders[1].items[0].quantity).toBe(1); expect(data.getAllOrders[1].userId).toBe(userId); }); });
// stream用于node中流数据的交互接口 const fs = require('fs') // const stream = require('stream') const rs = fs.createReadStream('./conf.js');//读取流 const ws = fs.createWriteStream('./conf2.js');//写入流 rs.pipe(ws) //二进制友好:图片复制 const rs2 = fs.createReadStream('./assets/images/vue.jpg'); const ws2 = fs.createWriteStream('./assets/images/vue_copy.jpg') rs2.pipe(ws2)
/*$Rev: 1154 $ Revision number must be in the first line of the file in exactly this format*/ /* Copyright (C) 2009 Innectus Corporation All rights reserved This code is proprietary property of Innectus Corporation. Unauthorized use, distribution or reproduction is prohibited. $HeadURL: http://info.innectus.com.cn/innectus/trunk/loom/App/app/public/jscript_dev/components/looper.js $ $Id: looper.js 1154 2010-03-17 23:58:47Z gesanto $ */ /** * This class allows for running a while or for loop with pauses to free up the browser UI. * * @class * @param {Function} onDo The event to call each loop iteration. * @param {Number} [maxItr=1] The maximum iterations to do before pausing. * @param {Number} [sleepTime=1] The length of the pause in milliseconds. */ function Looper(onDo, maxItr, sleepTime) { /** * The event the looper calls for each iteration of the loop. * * @name Looper#onDo * @event * @param {Number} currentItr The current iteration count. * @returns {Boolean|undefined} False will end the loop, undefined or true will continue iterating. * @type Boolean */ this._onDo = onDo; this._maxItr = maxItr || 1; this._sleepTime = sleepTime || 1; /** * The event that the looper calls when it finishes. * * @name Looper#onFinished * @event */ this._onFinishedCb = null; } /** * This assigns a task monitor to the looper so that the progress can be tracked. * * @param {TaskMonitor} tm The task monitor object. * @type void */ Looper.prototype.setTaskMonitor = function(tm) { this._task = tm; }; /** * This sets an event to call when the looper is finished. * * @param {Function} onFinished The event to call. * @type void */ Looper.prototype.setOnFinishedCb = function(onFinished) { this._onFinishedCb = onFinished; }; /** * This start the loop. * * @param {Number} [start=0] The starting iteration. * @param {Number} [end=0] The ending iteration. If this is 0, the loop will run like a while loop. * @type void */ Looper.prototype.loop = function(start, end) { if(typeof(start) == "number" && typeof(end) == "number" && start == end) return; var that = this; // callback handle this._current = start || 0; this._end = end || 0; if (this._task) { if(this._end != 0) this._task.startProgress(this._end - this._current); else this._task.startProgress(); } this._timerId = setInterval(function() { that._loop(); }, this._sleepTime); }; /** * The internal loop that is run on a timed interval. Calling * this runs the loop maxItr times until it is complete. * * @private * @type void */ Looper.prototype._loop = function() { for (this._itr = 0; this._itr < this._maxItr; this._itr++) { if (this._end != 0) { if (this._current >= this._end) { this._finish(); return; } } if (this._onDo(this._current) === false) { this._finish(); return; } this._current++; } if (this._end != 0 && this._task) { this._task.incProgress(this._itr); } }; /** * This is what is called when the loop finished. * * @type void */ Looper.prototype._finish = function() { if (this._task) this._task.stopProgress(this._itr); clearInterval(this._timerId); this._timerId = null; if (this._onFinishedCb) this._onFinishedCb(); };
import React from 'react'; import { SafeAreaView, StyleSheet, ScrollView, TouchableOpacity, TextInput, View, Text, StatusBar, ImageBackground } from 'react-native'; import { Header, LearnMoreLinks, Colors, DebugInstructions, ReloadInstructions, } from 'react-native/Libraries/NewAppScreen'; import Svg, { Path } from "react-native-svg"; import { RadioButton } from 'react-native-paper'; import Amplify, { Auth } from 'aws-amplify'; import { Image } from 'react-native'; import Feather from 'react-native-vector-icons/Feather'; import AntDesign from 'react-native-vector-icons/AntDesign'; import FontAwesome from 'react-native-vector-icons/FontAwesome'; import Foundation from 'react-native-vector-icons/Foundation'; import FontAwesome5 from 'react-native-vector-icons/FontAwesome5'; import EvilIcons from 'react-native-vector-icons/EvilIcons'; import MaterialIcons from 'react-native-vector-icons/MaterialIcons'; import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons'; import Entypo from 'react-native-vector-icons/Entypo'; import FireBaseFunctions from "../APIs/FireBaseFunctions"; import firestore from '@react-native-firebase/firestore'; class Posts extends React.Component { services = services = new FireBaseFunctions(); posts = []; pictures = []; constructor(props,navigation ) { super(props); // change code below this line // alert(props.route.params.email); this.state = { email: '', password: '', isloading: true, IsActiveBtnEnable: 'Timeline', } this.getData(); //this.getAllPosts(); } // getAllPosts = async () => { // this.setState({ isLoading: true }); // const db = firestore(); // await db.collection('PostBlock').orderBy('CreatedTime', 'desc').limit(5) // .onSnapshot((snapshot) => { // snapshot.forEach(function (doc) { // this.posts.push(doc.data()); // }); // let count = 0; // this.posts.map((post) => { // (async () => { // console.log("1", count++); // count = count++ // post.Likes = await this.getAllPostLikesByPostId(post); // pictures = []; // item.ImageURL.map((img) => { // pictures.push(img.url); // }) // item.pictures = pictures; // console.log(this.post); // if (count == this.posts.length) { // this.setState({ isLoading: false, posts }); // } // })(); // }) // return posts; // }); // } // getAllPostLikesByPostId = async (postData) => { // let items = []; // return await firebase.firestore().collection("Likes").where("PostId", "==", postData.PostId).where("Type", "==", "POSTLIKE").get().then((querySnapshot) => { // querySnapshot.docs.forEach(doc => { // items.push(doc.data()); // }); // return items; // }); // } // getAllPosts = async () => { // this.setState({ isPostLayoutLoading: true }); // await firestore().collection('PostBlock').orderBy('CreatedTime', 'desc').limit(5) // .onSnapshot((snapshot) => { // posts = []; // snapshot.forEach(function (doc) { // posts.push(doc.data()); // }); // this.setState({ isPostLayoutLoading: false, posts }); // return posts; // }); // } getData = async () => { this.setState({ isLoading: true }) this.posts = await this.services.getAllData("PostBlock"); let pictures = []; this.posts.map(async (item) => { //item.Likes= await this.getAllLikesByPostId(item); //console.log(item.Likes); pictures = []; item.ImageURL.map((img) => { pictures.push(img.url); }) item.pictures = pictures; }) this.setState({ isLoading: false }) } //onPress = (url, index, event) => { // url and index of the image you have clicked alongwith onPress event. // } GoToMSG = (ItemId) => { this.props.navigation.navigate('Comments'); } GoToQuestion = (ItemId) => { this.props.navigation.navigate('Questions') } likeClick = async (postData) => { // this.setState({ userIP: await publicIp.v4() }) const likeId = this.services.getGuid(); var obj = { LikeId: likeId, Type: 'POSTLIKE', ParentId: postData.PostId, PostId: postData.PostId, UserId: "919642280029", UserimageURL: '', UserName: "hanuman", Timestamp: new Date().toLocaleString(), UserIPAddress: "175.101.108.22" } await this.addLike('Likes', postData, obj); } addLike = async (collectionName, postData, obj) => { await firestore().collection(collectionName).doc(obj.LikeId).set(obj); postData.Counts.likeCount = postData.Counts.likeCount + 1; await firestore().collection('PostBlock').doc(postData.PostId).set(postData); this.setState({ loading: true }); const result = await this.getAllLikesByPostId(obj); postData.Likes = result; this.setState({ loading: false }); } getAllLikesByPostId = async (postData) => { let items = []; return await firestore().collection("Likes").where("PostId", "==", postData.PostId).where("Type", "==", "POSTLIKE").get().then((querySnapshot) => { querySnapshot.docs.forEach(doc => { items.push(doc.data()); }); return items; }); } render() { // const { navigate } = this.props.navigation; let postsGrid; //console.log("render", this.posts); if (this.posts != undefined) { postsGrid = this.posts.map((item, index) => ( < View style={styles.PostsBlocks} > <View style={{ flexDirection: "row" }}> <View style={{ flexDirection: "row", width: "60%" }}> <View style={{ margin: 20 }}> <Image source={require('../Images/user.jpg')} style={{ height: 60, width: 60, borderRadius: 10, }} /> </View> <View style={{ margin: 20, marginLeft: 0 }}> <Text style={{ fontWeight: "bold", fontSize: 25, color: "black" }}>{item.UserName}</Text> <Text style={{ fontWeight: "bold", fontSize: 20 }}>5min ago</Text> </View> </View> <View style={{ width: "40%" }}> <TouchableOpacity onPress={ () => this.ChangePage('Friends') } style={{ borderColor: '#ea0f38', margin: 20, marginTop: 30, borderWidth: 3, borderRadius: 10, alignItems: 'center', }}> <Text style={{ margin: 5, color: "#ea0f38", fontSize: 20, fontWeight: "bold", }}>Follow</Text> </TouchableOpacity> </View> </View> <View style={{ width: "100%", }}> <Text style={styles.Msg}> {item.Message} </Text> </View> {/* <View style={{ width: "100%", alignItems: 'center', height: 200 }}> <FbGrid images={item.pictures} onPress={this.onPress} /> </View> */} {/* <View style={{ width: "100%", }}> <Text style={styles.HashTags}> #relax,#travel </Text> </View> */} <View style={{ width: "100%", flexDirection: "row", margin: 20, marginLeft: 10 }}> <TouchableOpacity onPress={ () => this.likeClick(item) } style={{ marginRight: 15 }}> <View style={{ flexDirection: "row", }}> {/* {item.Counts.likeCount > 0 && item.Likes.map(item1 => { if (item1.UserId == "919642280029") { return (<Text style={{ margin: 3 }}><AntDesign name="hearto" size={30} style={{ margin: 20, color: "red" }} /> </Text>) } else{ return ( <Text style={{ margin: 3 }}><AntDesign name="hearto" size={30} style={{ margin: 20, color: "#a7a7a7" }} /> </Text>) } }) } */} { (() => { if (item.Counts.likeCount > 0) { let likeDiv = <Text style={{ margin: 3 }}><AntDesign name="hearto" size={30} style={{ margin: 20, color: "#a7a7a7" }} /> </Text>; console.log(item) if(item.Likes!=undefined){ console.log(item.UserId) item.Likes.map(item1 => { console.log(item1.UserId) if (item1.UserId == '919642280029') { likeDiv=<Text style={{ margin: 3 }}><AntDesign name="hearto" size={30} style={{ margin: 20, color: "red" }} /> </Text> } }) }else{ likeDiv = <Text style={{ margin: 3 }}><AntDesign name="hearto" size={30} style={{ margin: 20, color: "#a7a7a7" }} /> </Text>; } return likeDiv } else { console.log(item.Counts.likeCount) return ( <Text style={{ margin: 3 }}><AntDesign name="hearto" size={30} style={{ margin: 20, color: "#a7a7a7" }} /> </Text> ) } })() } {/* <Text style={{ margin: 3 }}><AntDesign name="hearto" size={30} style={{ margin: 20, color: "#a7a7a7" }} /> </Text> */} <Text style={{ fontSize: 22, color: "black", fontWeight: "bold", }}>{item.Counts.likeCount} </Text> </View> </TouchableOpacity> <TouchableOpacity onPress={ () => this.GoToMSG(item.PostId) } style={{ marginRight: 15 }}> <View style={{ flexDirection: "row", }}> <Text style={{ margin: 3 }}><MaterialCommunityIcons name="message-text-outline" size={30} style={{ margin: 20, color: "#a7a7a7" }} /></Text> <Text style={{ fontSize: 22, color: "black", fontWeight: "bold", }}>{item.Counts.commentCount} </Text> </View> </TouchableOpacity> <TouchableOpacity onPress={ () => this.GoToQuestion(item.PostId) //() => navigate('Comments') } style={{ marginRight: 10 }}> <View style={{ flexDirection: "row", }}> <Text style={{ margin: 3 }}><AntDesign name="questioncircleo" size={25} style={{ margin: 20, color: "#a7a7a7" }} /></Text> <Text style={{ fontSize: 22, color: "black", fontWeight: "bold", }}>{item.Counts.questionCount}</Text> </View> </TouchableOpacity> <TouchableOpacity onPress={ () => this.ChangePage('Friends') } style={{}}> <View style={{ flexDirection: "row", }}> <Text style={{ margin: 3 }}><MaterialCommunityIcons name="share-outline" size={30} style={{ margin: 20, color: "black" }} /></Text> <Text style={{ fontSize: 22, color: "black", fontWeight: "bold", }}>Share </Text> </View> </TouchableOpacity> </View> </View > )) } else { postsGrid = <Text>No Posts</Text> } return ( <View> <ScrollView> <View> <View style={styles.Posts}> {postsGrid} {/* <View style={styles.PostsBlocks}> <View style={{ flexDirection: "row" }}> <View style={{ flexDirection: "row", width: "60%" }}> <View style={{ margin: 20 }}> <Image source={require('../Images/user.jpg')} style={{ height: 60, width: 60, borderRadius: 10, }} /> </View> <View style={{ margin: 20, marginLeft: 0 }}> <Text style={{ fontWeight: "bold", fontSize: 25, color: "black" }}>Hanuman</Text> <Text style={{ fontWeight: "bold", fontSize: 20 }}>5min ago</Text> </View> </View> <View style={{ width: "40%" }}> <TouchableOpacity onPress={ () => this.ChangePage('Friends') } style={{ borderColor: '#ea0f38', margin: 20, marginTop: 30, borderWidth: 3, borderRadius: 10, alignItems: 'center', }}> <Text style={{ margin: 5, color: "#ea0f38", fontSize: 20, fontWeight: "bold", }}>Follow</Text> </TouchableOpacity> </View> </View> <View style={{ width: "100%", }}> <Text style={styles.Msg}> Hi all good morning </Text> </View> <View style={{ width: "100%", alignItems: 'center', height: 200 }}> {postsGrid} </View> <View style={{ width: "100%", }}> <Text style={styles.HashTags}> #relax,#travel </Text> </View> <View style={{ width: "100%", flexDirection: "row", margin: 20,marginLeft:10 }}> <TouchableOpacity onPress={ () => this.ChangePage('Friends') } style={{ marginRight: 15 }}> <View style={{ flexDirection: "row", }}> <Text style={{ margin: 3 }}><AntDesign name="hearto" size={30} style={{ margin: 20, color: "#a7a7a7" }} /> </Text> <Text style={{ fontSize: 22, color: "black", fontWeight: "bold", }}>123 </Text> </View> </TouchableOpacity> <TouchableOpacity onPress={ () => this.ChangePage('Friends') } style={{ marginRight: 15 }}> <View style={{ flexDirection: "row", }}> <Text style={{ margin: 3 }}><MaterialCommunityIcons name="message-text-outline" size={30} style={{ margin: 20, color: "#a7a7a7" }} /></Text> <Text style={{ fontSize: 22, color: "black", fontWeight: "bold", }}>354 </Text> </View> </TouchableOpacity> <TouchableOpacity onPress={ () => this.ChangePage('Friends') } style={{ marginRight: 10 }}> <View style={{ flexDirection: "row", }}> <Text style={{ margin: 3 }}><AntDesign name="questioncircleo" size={25} style={{ margin: 20, color: "#a7a7a7" }} /></Text> <Text style={{ fontSize: 22, color: "black", fontWeight: "bold", }}>354 </Text> </View> </TouchableOpacity> <TouchableOpacity onPress={ () => this.ChangePage('Friends') } style={{}}> <View style={{ flexDirection: "row", }}> <Text style={{ margin: 3 }}><MaterialCommunityIcons name="share-outline" size={30} style={{ margin: 20, color: "black" }} /></Text> <Text style={{ fontSize: 22, color: "black", fontWeight: "bold", }}>Share </Text> </View> </TouchableOpacity> </View> </View> */} </View> </View> </ScrollView> </View> ); }; } const styles = StyleSheet.create({ Posts: { width: "100%", alignItems: 'center', //borderRadius: 25 }, PostsBlocks: { width: "100%", backgroundColor: '#ffffff', borderRadius: 25, marginBottom: 20 }, HashTags: { color: "#ea0f38", margin: 20, marginBottom: 10, fontSize: 20, fontWeight: "bold", }, Msg: { color: "black", margin: 20, marginTop: 0, fontSize: 20, fontWeight: "bold", } }); export default Posts;
exports.help = { name: "mimic", description: "Mimic a user using webhooks", usage: "mimic <@user>", type: "mod" }; exports.run = async(client, message, args) => { if (!message.member.hasPermission("MANAGE_MESSAGES")) return message.reply("Insufficient permissions.") if (!message.guild.me.hasPermission("MANAGE_WEBHOOKS")) return message.reply("I need permission to manage webhooks to do that.") if (!args[0]) return message.reply("You need to mention who you want to mimic and what you want to mimic") let user = message.mentions.members.first() || message.member; let avatar = user.user.displayAvatarURL({ dynamic: true, format: "png" }); let name = user.displayName const hook = await message.channel.createWebhook(name, { avatar: avatar }).catch(error => message.reply(error.message)) await hook.edit(name, { avatar: avatar }).catch(error => console.log(error)) hook.send(args.slice(1).join(" ")).then(() => hook.delete()) message.delete() }
import React from "react"; export const QuizQuestion = ({ question }) => { return <h2>{question}</h2>; };
const routes = [ { path: '/', component: () => import('layouts/MyLayout.vue'), children: [ { path: '', component: () => import('pages/Index.vue'), name: 'index', meta: {auth: true} }, ] }, { path: '/temas', component: () => import('pages/Temas/Index.vue'), name: 'temas.index', meta: {auth: true} }, { path: '/buscar-curso', component: () => import('pages/Curso/Search.vue'), name: 'curso.search', meta: {auth: true} }, { path: '/nuevo-curso', component: () => import('pages/Curso/Create.vue'), name: 'curso.create', meta: {auth: true} }, { path: '/editar-curso/:id', component: () => import('pages/Curso/Create.vue'), name: 'curso.edit', meta: {auth: true} }, { path: '/cursos', component: () => import('pages/Curso/Index.vue'),name: 'curso.index', meta: {auth: true} }, { path: '/curso/:id', component: () => import('pages/Curso/Show.vue'), name: 'curso.show', meta: {auth: true} }, { path: '/horario', component: () => import('pages/Horario/Index.vue'), name: 'horario', meta: {auth: true} }, { path: '/welcome', component: () => import('pages/Welcome.vue'), name: 'welcome', meta: {auth: true} }, { path: '/login', component: () => import('pages/Login.vue'), name: 'login' }, { path: '/register', component: () => import('pages/Register.vue'), name: 'register' }, { path: '/perfil', component: () => import('pages/Perfil.vue'), name: 'perfil', meta: {auth: true} }, ] // Always leave this as last one if (process.env.MODE !== 'ssr') { routes.push({ path: '*', component: () => import('pages/Error404.vue') }) } export default routes
import types from "./actionTypes"; import kidsnparty from "../apis/kidsnParty"; const index = () => { // const headers = makeHeader; return async function(dispatch) { // const response = kidsnparty.get("users", { // headers // }); const response = await kidsnparty.get("users", { params: { user_group: "customer" } }); dispatch({ type: types.fetchUsers, payload: response.data.users }); }; }; const sortDetails = (property, sortOrder, objects) => { const sortedList = objects.sort(dynamicSort(property, sortOrder)); return { type: types.fetchUsers, payload: sortedList }; }; export const dynamicSort = (property, sortOrder) => { return function(a, b) { var result = a[property] < b[property] ? -1 : a[property] > b[property] ? 1 : 0; return result * sortOrder; }; }; export default { index, sortDetails };
import {useEffect} from 'react'; const useScript = ({url, async, defer, crossorigin, nonce}) => { useEffect(() => { const script = document.createElement('script'); script.src = url; script.async = async; script.defer = defer; script.crossorigin = crossorigin; script.nonce = nonce; document.body.appendChild(script); return () => { document.body.removeChild(script); } }, [url, async, defer, crossorigin, nonce]); }; export default useScript;
const randomStr=function (len) { let str=''; const randomChar=function(){ const n=Math.floor(Math.random()*62); if(n<10) return n;//0-9 if(n<36) return String.fromCharCode(n+55);//A-Z return String.fromCharCode(n+61);//a-z }; while (str.length<len){ str+=randomChar(); } return str; }; const parseSearchStr=function(str){ const reg=/[^?&=]+/gim; const arr=str.match(reg); const result={}; if(arr.length>0){ arr.forEach((item,index)=>{ if(index % 2 === 0){ result[arr[index]]=arr[index+1] } }) } return result; }; module.exports={ randomStr, parseSearchStr };
module.exports = (err,req,res,next) => { console.log(err) let status = 500 let msgObj = { msg : 'internal errors' } if(err.name === 'SequelizeValidationError'){ status = 400 err.errors.forEach(el => { msgObj.msg = el.message }) } else if (err.name === 'JsonWebTokenError'){ status = 400 msgObj = { msg : err } } else if (err.name === 'TOKEN_NOT_FUND'){ status = 400 msgObj = { msg : err } } else if (err.name === 'DATANOTFOUND'){ status = 404 msgObj.msg = err.errors.message } res.status(status).json(msgObj) }
import { shallowMount, createLocalVue } from "@vue/test-utils"; import App from "../../src/App.vue"; describe("App Component", () => { let wrapper; beforeEach(() => { const localVue = createLocalVue(); wrapper = shallowMount(App, { localVue, }); }); afterEach(() => { wrapper.destroy(); }); it("is a vue instance", () => { expect(wrapper.isVueInstance).toBeTruthy(); }); it("should render the correct markup", () => { expect(wrapper.html()).toContain("<v-app>"); }); });
const mongoose = require('mongoose'); const { Schema } = mongoose; const sectionSchema = new Schema( { restaurantId: { type: Schema.Types.ObjectId, ref: 'Restaurant' }, menuId: { type: Schema.Types.ObjectId, ref: 'Menu' }, name: { type: String, required: true }, position: { type: Number, default: 1 }, } ); const section = mongoose.model('Section', sectionSchema); module.exports = section;
import React, { lazy } from 'react' const MoviePlaying = lazy(() => import('../Base/MoviePlaying')) const MovieNowPlayingPage = () => { return ( <> <div className="Container-main"> <MoviePlaying/> </div> </> ) } export default MovieNowPlayingPage
const connection = require("../config/mysql"); module.exports = { postProduct: (setData) => { return new Promise((resolve, reject) => { connection.query( "INSERT INTO product SET ?", setData, (error, result) => { if (!error) { const newResult = { product_id: result.insertId, ...setData, }; resolve(newResult); } else { reject(new Error(error)); } } ); }); }, getProductSorting: (limit, offset, sort) => { return new Promise((resolve, reject) => { connection.query( `SELECT * FROM product ORDER BY ${sort} LIMIT ${limit} OFFSET ${offset}`, (error, result) => { console.log(error); !error ? resolve(result) : reject(new Error(error)); } ); }); }, getProductByCategoryModel: (limit, offset, category_name) => { return new Promise((resolve, reject) => { connection.query( `SELECT * FROM product INNER JOIN category ON product.category_id = category.category_id WHERE category.category_name = '${category_name}' ORDER BY product.product_name LIMIT ${limit} OFFSET ${offset}`, (error, result) => { console.log(error); !error ? resolve(result) : reject(new Error(error)); } ); }); }, getProduct: (limit, offset) => { return new Promise((resolve, reject) => { connection.query( "SELECT * FROM product WHERE product_stock>0 LIMIT ? OFFSET ?", [limit, offset], (error, result) => { !error ? resolve(result) : reject(new Error(error)); } ); }); }, getProductSearching: (search) => { return new Promise((resolve, reject) => { connection.query( `SELECT * FROM product WHERE product_name LIKE '%${search}%' ORDER BY product_name`, (error, result) => { !error ? resolve(result) : reject(new Error(error)); } ); }); }, getProductCount: () => { return new Promise((resolve, reject) => { connection.query( "SELECT COUNT(*) AS total FROM product", (error, result) => { !error ? resolve(result[0].total) : reject(new Error(error)); } ); }); }, getProductCountCategory: (category_name) => { return new Promise((resolve, reject) => { connection.query( `SELECT COUNT(*) AS total FROM product JOIN category ON product.category_id = category.category_id WHERE category_name = '${category_name}'`, (error, result) => { !error ? resolve(result[0].total) : reject(new Error(error)); } ); }); }, getProductCountSearching: (search) => { return new Promise((resolve, reject) => { connection.query( `SELECT COUNT(*) AS total FROM product WHERE product_name LIKE '%${search}%'`, (error, result) => { !error ? resolve(result[0].total) : reject(new Error(error)); } ); }); }, getProductById: (id) => { return new Promise((resolve, reject) => { connection.query( "SELECT * FROM product WHERE product_id = ?", id, (error, result) => { !error ? resolve(result) : reject(new Error(error)); } ); }); }, patchProduct: (setData, id) => { return new Promise((resolve, reject) => { connection.query( "UPDATE product SET ? WHERE product_id = ?", [setData, id], (error, result) => { console.log(error); if (!error) { const newResult = { product_id: id, ...setData, }; resolve(newResult); } else { reject(new Error(error)); } } ); }); }, deleteProductProcess: (id) => { return new Promise((resolve, reject) => { connection.query( "DELETE FROM product WHERE product_id = ?", id, (error, result) => { console.log(error); !error ? resolve(result) : reject(new Error(error)); } ); }); }, };
import {FontAwesomeIcon} from "@fortawesome/react-fontawesome"; import {Input, InputAdornment} from "@material-ui/core"; import {useState} from "react"; import Button from "~/components/atoms/button/Button"; import IconButton from "~/components/atoms/iconButton/IconButton"; import TextField from "~/components/atoms/textfield/Textfield"; import useForm from "~/util/form"; import Configurable from "../Configurable"; import {StyledCurrencyRateTable} from "./CurrencyRateTable.style"; import CurrencyRateTableConfigurator from "./CurrencyRateTableConfigurator"; const CurrencyRateTable = function (props) { if (props.liveMode == false) { return ( <> <Configurable component={props.component} preview={false} title="Koers tabel" configurator={<CurrencyRateTableConfigurator />}> <Component {...props} /> </Configurable> </> ); } else { return <Component {...props} />; } }; const Component = function ({component, ...props}) { var data = component.data; const round = (input) => { input = parseFloat(input); if (input < 1000) return String(input.toFixed(2)).replace(".", ","); return ( Math.round(input) .toString() .replace(/\B(?=(\d{3})+(?!\d))/g, ".") + ",-" ); }; return ( <StyledCurrencyRateTable> {[1, 2.5, 5, 10, 25, 50, 75, 100].map((base, index) => { return ( <div className="row" key={index}> <div className="eur">€ {round(base)}</div> <div className="icon"> <FontAwesomeIcon icon={["fal", "exchange"]} /> </div> {!isNaN(data.conversionRate + 1) && ( <div className="value"> {data.currencySymbol} {round(base * data.conversionRate)} </div> )} {isNaN(data.conversionRate + 1) && <div className="value">₿ 1.000.000</div>} </div> ); })} </StyledCurrencyRateTable> ); }; export default CurrencyRateTable;
$(document).ready(function () { LoadData(); $("[datatype='date']").each(function () { $(this).html(new Date($(this).html().replace(/-/g, "/")).Format("yyyy-MM-dd")) $(this).removeAttr("datatype"); }); $("[datatype='datetime']").each(function () { $(this).html(new Date($(this).html().replace(/-/g, "/")).Format("yyyy-MM-dd hh:mm:ss")) $(this).removeAttr("datatype"); }); $("[convert]").each(function () { var converter = $(this).attr("convert").split("|"); var value = $(this).html(); $(this).html(""); for (var i = 0; i < converter.length; i++) { var item = converter[i].split(":"); if (value == $.trim(item[0])) { $(this).html($.trim(item[1])); break; } } $(this).removeAttr("convert"); }); $("[valueFrom]").each(function () { var value = $("#" + $(this).attr("valueFrom")).html(); $(this).html(value); }); $("[source]").each(function () { var htmlTable = this; var table = $(htmlTable).attr("source"); var keys = $(htmlTable).attr("keys").split(","); var keySet = new Array; for (var i = 0; i < keys.length; i++) { if ($("#" + keys[i]).get(0) != undefined) { var value = $("#" + keys[i]).html() if (isNaN(value)) { value = "'" + value + "'"; } keySet.push(keys[i] + "=" + value); } } $(htmlTable).removeAttr("keys"); //keySet.join(","); var fieldSet = new Array(); $(htmlTable).find("tr:first").children("[field]").each(function () { fieldSet.push($(this).attr("field")); }); //暂时只能用于绑定单表数据,多表数据要联合查询,最好使用视图,但是现在不能随便建立视图 $.ajax({ url: "/Approve/GetListByKey", async: false, data: { table: table, keys: keySet.join(","), fields: fieldSet.join(",") }, success: function (result) { if (!result.HasError) { var data = result.Data; for (var i = 0; i < data.length; i++) { var row = "<tr>"; for (var j = 0; j < fieldSet.length; j++) { var header = $(htmlTable).find("[field='" + fieldSet[j] + "']"); var converter = header.attr("valueConvert"); var db = ""; if (converter != undefined && converter != "") { db = " db=" + converter; } row += "<td" + db + ">" + data[i][fieldSet[j]] + "</td>"; } $(htmlTable).append(row); } $(htmlTable).find("[field]").removeAttr("field"); $(htmlTable).find("[valueConvert]").removeAttr("valueConvert"); } } }); $(this).removeAttr("source"); }); $("[db]").each(function () { var obj = $(this); var db = obj.attr("db").split(","); var value = obj.html(); $.ajax({ url: "/Approve/GetValueByID", async:false, data: { table: db[0], nameField: db[1], valueField: db[2], value: value }, success: function (data) { obj.html(data); obj.removeAttr("db"); } }) }); DynIframeSize($("#template", window.parent.document).get(0)); }); //function timespan(container, startDate, endDate, timeFormat) { // var start = $("#" + startDate).val(); // var end = $("#" + endDate).val(); // if (start != "" && end != "") { // $("#" + container).html(getOffDateTime(Date.parse(start), Date.parse(end), timeFormat)); // } //} //function getOffDateTime(startDate, endDate, timeFormat) { // var mmSec = (endDate - startDate); //得到时间戳相减 得到以毫秒为单位的差 // var offset = 0; // switch (timeFormat) { // case "d": offset = 86400000; break;//3600000 * 24 // case "h": offset = 3600000; break; // } // return (mmSec / offset).toFixed(1); //} function LoadData() { var json = eval("(" + $("#values", window.parent.document).val() + ")"); $("input").each(function () { var key = $(this).attr("name"); if (json.hasOwnProperty(key)) { $(this).val(json[key]); } }); $("span").each(function () { var key = $(this).attr("id"); if (json.hasOwnProperty(key)) { $(this).html(json[key]); } }); } function DynIframeSize(pTar) { //var pTar = null; //if (document.getElementById) { // pTar = document.getElementById(iframe_id); //} //else { // eval('pTar = ' + iframe_id + ';'); //} if (pTar && !window.opera) { //begin resizing iframe pTar.style.display = "block" if (pTar.contentDocument && pTar.contentDocument.body.offsetHeight) { //ns6 syntax pTar.height = pTar.contentDocument.body.offsetHeight + 10; //pTar.width = pTar.contentDocument.body.scrollWidth + 20; } else if (pTar.Document && pTar.Document.body.scrollHeight) { //ie5+ syntax pTar.height = pTar.Document.body.scrollHeight; //pTar.width = pTar.Document.body.scrollWidth; } } }
var express = require("express"); var url = require('url'); var bodyParser = require('body-parser') var app = express(); var mongoose = require("mongoose") mongoose.connect('mongodb://localhost/dojo_ninjas'); //setup mongodb with mongoose var ClientSchema = new mongoose.Schema({ location: {type: String}, name: {type: String}, phone_number: {type : String} }, {timestamps: true}) mongoose.model('Client', ClientSchema); var Client = mongoose.model('Client'); app.use(express.static(__dirname + "/static")); app.use(bodyParser.urlencoded({extended : true})); const server = app.listen(8000, function() { console.log("listening on port 8000"); }) app.set('views', __dirname + '/views'); app.set('view engine', 'ejs'); app.post('/clients', function(request, response){ console.log('request: ',request) let client = new Client() client.location = request.body.location client.name = request.body.name client.phone_number = request.body.phone_number client.save(function (err){ if(err){ response.redirect('/') console.log('Error submiting client:', err) }else{ console.log('client submission saved') response.redirect('/') } }) }) app.post('/clients/:client_id', function(request, response){ console.log('in post client id') console.log('request: ',request.body) Client.find({_id: request.params.client_id},function(err, clients){ if(err){ console.log('error finding client: ', err) }else{ let client = clients[0] client.location = request.body.location client.name = request.body.name client.phone_number = request.body.phone_number client.save(function (err){ if(err){ console.log('Error saving updates to client: ',err) }else{ console.log('client updated') response.redirect(`/`) } }) } }) }) app.get('/clients/destroy/:client_id', function(request, response){ console.log('in post destroy id') console.log('request: ',request) Client.findOneAndRemove({_id: request.params.client_id},function(err, client){ if(err){ console.log('error finding client: ', err) }else{ console.log('client deleted') response.redirect(`/`) } }) }) app.get('/', function(request,response){ console.log('in get /') Client.find({},function(err, clients){ if(err){ console.log('error loading clients: ', err) response.redirect('/') }else{ console.log('clients are: ',clients) response.render('dash', {'clients': clients}) } }) }) app.get('/clients/new', function(request,response){ console.log('in new clients') response.render('new') }) app.get('/clients/edit/:client_id', function(request,response){ console.log('in edit') Client.find({_id: request.params.client_id},function(err, client){ if(err){ console.log('error loading client: ', err) response.redirect('/') }else{ console.log(client) response.render('edit', {'client': client}) } }) })
'use strict'; const Q = require('@nmq/q/client'); const db = new Q('database'); db.subscribe('create', (payload) => { console.log('made a thing', payload); }) db.subscribe('delete', (payload) => { console.log('deleted stuff', payload); }) console.log('current subscriptions:', db.subscriptions());
Page({ /** * 页面的初始数据 */ data: { }, // bindtest: function(res) { // //请求code // wx.login({ // success(res) { // if (res.code) { // //发起网络请求 // wx.request({ // url: 'http://101.200.39.35:8080/New_war/wx', // data: { // //这里的data就是request对象携带的的请求参数 // code: res.code // } // }) // } else { // console.log('登录失败!' + res.errMsg) // } // } // }) // }, /** * 生命周期函数--监听页面加载 */ onLoad: function (res) { var that = this; //查看是否授权 wx.getSetting({ success: function (res) { if (res.authSetting['scope.userInfo']) { console.log("用户授权了"); } else { //用户没有授权 console.log("用户没有授权"); } } }); }, bindGetUserInfo: function (res) { if (res.detail.userInfo) { //用户按了允许授权按钮 var that = this; wx.request({ url: 'http://101.200.39.35:8080/New_war/wxUserInfo', data: { rawData: res.detail.userInfo, }, header: { 'content-type': 'application/json', // 默认值 'cookie': 'JSESSIONID=' + wx.getStorageSync("sessionId") }, success: function (res) { console.log(wx.getStorageSync("sessionId")); console.log(res); }, }) wx.redirectTo({ url: '../homepage/homepage', }) } else { //用户按了拒绝按钮 wx.showModal({ title: 'Tip', content: '您点击了拒绝授权,请授权之后再进入!!!', showCancel: false, confirmText: '好吧', success: function (res) { // 用户没有授权成功,不需要改变 isHide 的值 if (res.confirm) { console.log('用户点击了“返回授权”'); } } }); } }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () { }, /** * 生命周期函数--监听页面显示 */ onShow: function () { wx.hideHomeButton() }, /** * 生命周期函数--监听页面隐藏 */ onHide: function () { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function () { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { }, /** * 用户点击右上角分享 */ onShareAppMessage: function () { } })
/* jshint strict:false */ module.exports = { "grunt-config": { options: { title: 'Angular TeamRaiser Participant Center', message: 'Grunt config updated. You should restart Grunt.' } }, "src": { options: { title: 'Angular TeamRaiser Participant Center', message: 'Build complete.' } } }
import * as actionTypes from './actionType' export const tweetChanged = (value, inputName) => { return { type: actionTypes.TWEET_CHANGED, value, inputName } } export const submitTweet = () => { return { type: actionTypes.TWEET_SUBMIT } }
const { stringsRearrangement } = require('./string-problems/stringsRearrangement'); const s = stringsRearrangement(["abc", "bef", "bcc", "bec", "bbc", "bdc"]); console.log(s);
import translationsService from '../services/translations' import apiService from '../services/api-service' export default { subscribe(email) { const lang = translationsService.getNavigatorLanguage() return apiService.post('subscriptions', { email, lang }) }, fetchAll() { return apiService.get('apo/sub') }, delete(id) { return apiService.get(`apo/sub/del/${id}`) }, }
$(document).ready(function () { //set API URL to variable const URL_FOURSQUARE = 'https://api.foursquare.com/v2/venues/explore'; // Get city data from Foursquare API function getDataFromFourSquareAPI(city, category, callback) { const parameters = { near: `${city}`, section: `${category}`, query: 'recommended', radius: 150, client_id: 'N4TONANM1I0FXAJRPD414MFYR0BYIMLAEKRCLNMEUAMRJ0VR', client_secret: 'T52ACWBOFK2HZBRETGTM3XKQBUXN0W2R4I2CU3UKNTVCKI5N', v: 20180320, limit: 6, venuePhotos: 1, }; $.getJSON(URL_FOURSQUARE, parameters, callback); } let count = 0; let arrayOfVenueIds = []; //handle the JSON data from FourSquare/display results function displayFourSquareData(data) { console.log(data); count = 0; arrayOfVenueIds = []; // let results = data.response.groups[0].items.map(city => {renderResult(city)}); let results = ''; for (let i = 0; i < data.response.groups[0].items.length; i++) { results += renderResult(data.response.groups[0].items[i]); }; $('.results').html(results); $('.results').find('.venue-image').each(function (event) { let venueId = $(this).data('venue-id'); getPhoto(venueId); }); $('.results').prop('hidden', false); } function getPhoto(venueId) { const URL_PHOTOS = `https://api.foursquare.com/v2/venues/${venueId}/photos`; const parameters = { client_id: 'N4TONANM1I0FXAJRPD414MFYR0BYIMLAEKRCLNMEUAMRJ0VR', client_secret: 'T52ACWBOFK2HZBRETGTM3XKQBUXN0W2R4I2CU3UKNTVCKI5N', v: 20180320 } $.getJSON(URL_PHOTOS, parameters, function (data) { console.log('getPhoto data:', data); let venueImageContainer = $('.results').find(`img[data-venue-id="${venueId}"]`); $(venueImageContainer).attr('src', getImageURL(data.response)); }).then(function () { console.log("Finished with " + venueId); }); } // render the results, HTML function renderResult(result) { arrayOfVenueIds.push(result.venue.id); return ` <div class="col-4 ${hiddenElement(result.venue.photos.count)}"> <div class="venue-card"> <div class="venue-name"> <a href="${result.venue.url}">${result.venue.name}</a> </div> <a href="${result.venue.url}" target="_blank"><img class="venue-image" data-venue-id="${result.venue.id}" src=""></a> <div class="venue-info"> <div class="two-columns1"> <div class="venue-category"> <img class="venue-category-logo" src="${result.venue.categories[0].icon.prefix}bg_32${result.venue.categories[0].icon.suffix}" alt="category logo"> <p class="venue-category-name">${result.venue.categories[0].shortName}</p> </div> <div class="venue-address-container"> <p class="venue-rating"><u>Address:</u></p> <p class="venue-address-street ${hiddenElement(result.venue.location.formattedAddress[0])}">${result.venue.location.formattedAddress[0]}</p> </div> </div> <div class="two-columns2"> <p class="venue-rating"><u>Locale:</u></p> <p class="venue-address-street ${hiddenElement(result.venue.location.formattedAddress)}">${result.venue.location.formattedAddress[1]}</p> </div> </div> </div> </div>`; } // hide elements with no photos, ratings, etc. function hiddenElement(argument) { // if (argument === 0 || argument === undefined) { // return 'hidden-element'; // } else { // return ""; // }; } //get image URL function getImageURL(venue) { if (venue.photos.count === 1) { let photoObj = venue.photos.items[0]; let prefix = photoObj.prefix; let suffix = photoObj.suffix; return prefix + "250x250" + suffix; } } //category input based on which button you press function submitCategoryButtons() { $('#searchForm .buttons button').on('click', function (e) { e.preventDefault(); let inputTarget = $('#searchInput').val(); if (inputTarget === "") { alert('Please enter a city name'); } let category = $(e.currentTarget).data('4sq-category'); getDataFromFourSquareAPI(inputTarget, category, displayFourSquareData); }); } //function call submitCategoryButtons(); });
const Person = require('../models/person') Person.create([ { firstName: 'Gal', lastName: 'Gadot' } ])
import React from 'react'; export const IntervalSlider = (props) => { return( <input type='range' min='100' max='2000' value={props.intervalTime} onChange={props.change}/> ) }
var searchData= [ ['update',['update',['../classca_1_1mcgill_1_1ecse211_1_1odometer_1_1_odometer_data.html#a839fa365b183ea5e340370bee3b368b2',1,'ca::mcgill::ecse211::odometer::OdometerData']]], ['uslocalization',['USLocalization',['../classca_1_1mcgill_1_1ecse211_1_1project_1_1_localization.html#a028b28ca2b2de8885521b8c6c9cbf882',1,'ca::mcgill::ecse211::project::Localization']]] ];
import React from 'react'; import ReactDOM from 'react-dom'; import App from '../App'; import Input from '../Components/Input'; import RestartButton from '../Components/RestartButton'; import SplashScreen from '../Components/SplashScreen'; import SwatchButton from '../Components/SwatchButton'; import Swatches from '../Components/Swatches'; import SwatchPicker from '../Components/SwatchPicker'; const fakeFunc = () => { return; }; describe('The components mount with no errors', () => { it('<App /> renders without crashing', () => { const div = document.createElement('div'); ReactDOM.render(<App />, div); ReactDOM.unmountComponentAtNode(div); }); it('<Input /> renders without crashing', () => { const div = document.createElement('div'); ReactDOM.render(<Input useUploadedImage={fakeFunc} />, div); ReactDOM.unmountComponentAtNode(div); }); it('<RestartButton /> renders without crashing', () => { const div = document.createElement('div'); ReactDOM.render(<RestartButton handleRestart={fakeFunc} />, div); ReactDOM.unmountComponentAtNode(div); }); it('<SplashScreen /> renders without crashing', () => { const div = document.createElement('div'); ReactDOM.render(<SplashScreen useRandomImage={fakeFunc} />, div); ReactDOM.unmountComponentAtNode(div); }); it('<Swatches /> renders without crashing', () => { const div = document.createElement('div'); ReactDOM.render(<Swatches />, div); ReactDOM.unmountComponentAtNode(div); }); it('<SwatchButton /> renders without crashing', () => { const div = document.createElement('div'); ReactDOM.render(<SwatchButton actions={fakeFunc} />, div); ReactDOM.unmountComponentAtNode(div); }); it('<SwatchPicker /> renders without crashing', () => { const div = document.createElement('div'); ReactDOM.render(<SwatchPicker />, div); ReactDOM.unmountComponentAtNode(div); }); });
var users = require("../../app/controllers/users.server.controller.js"); var passport = require("passport"); module.exports = function (app) { app.route("/signup") .get(users.renderSignup) .post(users.signup); app.route("/signin") .get(users.renderSignin) .post(passport.authenticate("local", { successRedirect: "/", failureRedirect: "/signin", failureFlash: true }) ); app.get("/signout", users.signout); app.route("/users") .post(users.create) .get(users.list); app.route("/users/:userId") .get(users.read) .put(users.update) .delete(users.delete); app.param("userId", users.userByID); }; //ajax post test //var request = new XMLHttpRequest(); //request.open('POST', '/users', true); //request.setRequestHeader('Content-Type', 'application/json; charset=UTF-8'); //request.send('{"firstName":"First", "lastName":"Last", "email":"user@example.com", "username": "username", "password":"password"}');
import React from "react"; import styled from "styled-components"; import { IoIosArrowDropright } from "react-icons/io"; import pdf from "../images/resume.pdf"; import { Colors } from "../Global/Color"; import { BackgroundWaves } from "../Components/backgroundWaves"; import { NavBar } from "../Components/navBar"; import { Logo } from "../Components/logo"; import { LinkBar } from "../Components/linkBar"; export const Resume = () => { return ( <Wrapper> <NavBar /> <Logo /> <LinkBar /> <BackgroundWaves /> <TextContainer> <Text> " The technological universe fascinates me by the rigour it requires, but also by its multiple possibilities to solve problems. Becoming a Web developer was for me an aspiration to be professionally happy. I am a person who is curious, hard-working and persevering. I handle logistics and creativity very well. I used to work in the restaurant industry as a restaurant manager, which got me used to work under pressure." </Text> <Text> " I started learning Web development independently by watching several videos produced by Web developers, among others. I then took the CS 50 online course at Harvard University. This course confirmed my desire to work in the technology field and inspired me to expand my knowledge of computer sciences, such as data structures and how computers function under the hood. I then decided to officially register for a Full-Stack Web Development Bootcamp in Quebec (also known as DECODE) at Concordia University. Since the fall of 2020, I have learned immensely in Web Development, and I can now say that I can create entire web applications front to back, and I am very proud of it. " </Text> <Text> " I know that this is a field where I can continuously learn and develop my skills. That is what drives me: learning, creating, and solving problems with multiple solutions. " </Text> </TextContainer> <ResumePDF href={pdf} target="_blank"> Open my Resume{" "} <IconSpan> <IoIosArrowDropright /> </IconSpan> </ResumePDF> </Wrapper> ); }; const Wrapper = styled.div` z-index: 20; width: 100%; height: 100vh; `; const ResumePDF = styled.a` color: black; z-index: 20; width: 20.5vw; height: 6.5vh; position: absolute; top: 80%; left: 50%; transform: translate(-50%, -50%); background-color: whitesmoke; text-decoration: none; text-align: center; border: 3px solid ${Colors.blue}; font-size: 2vw; display: flex; justify-content: center; align-items: center; color: ${Colors.blue}; font-weight: bold; border-radius: 10px; box-shadow: 5px 5px 15px 2px #70767c; &:hover { background-color: ${Colors.blue}; color: whitesmoke; border: 3px solid whitesmoke; } @media (min-width: 1300px) { width: 18vw; height: 6.5vh; font-size: 1.5vw; } @media (max-width: 800px) { width: 18vw; height: 5vh; font-size: 1.5vw; } @media (max-width: 500px) { width: 25vw; height: 4vh; font-size: 2vw; } `; const TextContainer = styled.div` z-index: 25; width: 100%; height: 60%; position: absolute; top: 41%; left: 50%; transform: translate(-50%, -50%); display: flex; flex-direction: column; align-items: center; justify-content: space-around; `; const Text = styled.p` text-align: center; width: 90%; z-index: 125; font-size: 2vw; line-height: 1.1; @media (min-width: 1300px) { font-size: 1.8vw; } @media (max-width: 800px) { font-size: 2.5vw; } @media (max-width: 500px) { font-size: 3vw; } `; const IconSpan = styled.span` margin: 8px 0 0 4px; font-size: 2.5rem; @media (max-width: 800px) { font-size: 1.5rem; } @media (max-width: 500px) { margin: 4px 0 0 4px; font-size: 1.2rem; } `;
import { Dropdown } from 'bootstrap'; import React from 'react'; import {BsPeopleFill} from 'react-icons/bs' import DropDown from '../dropdown'; const Invitations = () => { return ( <div className='invitation'> <span className='count'>2</span> <DropDown> <BsPeopleFill size={24} /> <DropDown.Menu> <DropDown.Item>Item 1</DropDown.Item> </DropDown.Menu> </DropDown> </div> ); }; export default Invitations;
import React from 'react'; const LazyRender = React.createClass({ propTypes: { children: React.PropTypes.array.isRequired, maxHeight: React.PropTypes.number.isRequired, childHeight: React.PropTypes.number, className: React.PropTypes.string, itemPadding: React.PropTypes.number, extraChildHeight: React.PropTypes.number }, getDefaultProps() { return { itemPadding: 7, extraChildHeight: 0 }; }, getInitialState() { return { childrenTop: 0, childrenToRender: 10, scrollTop: 0, height: this.props.maxHeight }; }, componentDidMount() { this.onMount(); }, componentWillReceiveProps(nextProps) { const childrenTop = Math.floor(this.state.scrollTop / this.state.childHeight); let childrenBottom = (nextProps.children.length - childrenTop - this.state.childrenToRender); if (childrenBottom < 0) { childrenBottom = 0; } const height = this.getHeight( nextProps.children.length, this.state.childHeight, nextProps.maxHeight, nextProps.extraChildHeight ); let numberOfItems = Math.ceil(height / this.state.childHeight); if (height === this.props.maxHeight) { numberOfItems += this.props.itemPadding; } this.setState({ childrenTop, childrenBottom, childrenToRender: numberOfItems, height }); }, componentDidUpdate() { this.onUpdate(); }, onUpdate() { if (this.state.childHeight !== this.getChildHeight()) { this.setState({childHeight: this.getChildHeight()}); } }, onMount() { const childHeight = this.getChildHeight(); const height = this.getHeight( this.props.children.length, childHeight, this.props.maxHeight, this.props.extraChildHeight ); let numberOfItems = Math.ceil(height / childHeight); if (height === this.props.maxHeight) { numberOfItems += this.props.itemPadding; } this.setState({ childHeight, childrenToRender: numberOfItems, childrenTop: 0, childrenBottom: this.props.children.length - numberOfItems, height }); }, onScroll() { const container = this.refs.container; const scrollTop = container.scrollTop; const childrenTop = Math.floor(scrollTop / this.state.childHeight); let childrenBottom = (this.props.children.length - childrenTop - this.state.childrenToRender); if (childrenBottom < 0) { childrenBottom = 0; } this.setState({ childrenTop, childrenBottom, scrollTop }); }, getHeight(numChildren, childHeight, maxHeight, extraChildHeight = 0) { const fullHeight = (numChildren * childHeight) + extraChildHeight; return fullHeight < maxHeight ? fullHeight : maxHeight; }, getElementHeight(element) { let elmHeight; let elmMargin; const elm = element; if (document.all) { // IE elmHeight = elm.currentStyle.height; elmMargin = parseInt(elm.currentStyle.marginTop, 10) + parseInt(elm.currentStyle.marginBottom, 10); } else { // Mozilla elmHeight = parseInt(document.defaultView.getComputedStyle(elm, '').getPropertyValue('height'), 10); elmMargin = parseInt(document.defaultView.getComputedStyle(elm, '').getPropertyValue('margin-top'), 10) + parseInt(document.defaultView.getComputedStyle(elm, '').getPropertyValue('margin-bottom'), 10); } return (elmHeight + elmMargin); }, getChildHeight() { if (this.props.childHeight) { return this.props.childHeight; } if (this.props.children.length === 0) { return 0; } const firstChild = this.refs['child-0']; if (firstChild === null) { return this.props.maxHeight; } return this.getElementHeight(firstChild); }, render() { if (!this.props.children.length) { return <div />; } const end = this.state.childrenTop + this.state.childrenToRender; const childrenToRender = this.props.children.slice(0, end); const children = childrenToRender.map((child, index) => { if (index === 0) { return React.cloneElement(child, {ref: `child-${index}`, key: index}); } return child; }); let childHeightTop = this.state.childrenTop * this.state.childHeight; let childHeightBottom = this.state.childrenBottom * this.state.childHeight; if (isNaN(childHeightTop)) { childHeightTop = null; } if (isNaN(childHeightBottom)) { childHeightBottom = null; } children.push( <div style={ { height: childHeightBottom } } key="bottom"></div> ); const height = isNaN(this.state.height) ? null : this.state.height; return ( <div style={{ height, overflowY: 'auto' }} className={this.props.className} ref="container" onScroll={this.onScroll}> {children} </div> ); } }); module.exports = LazyRender;
const SignIn = React.createClass({ getInitialState () { var style = { } return({ style: style, }) }, componentDidMount () { }, signIn (e) { $.ajax({ url: '/session', type: 'POST', data: { authenticity_token: $('meta[name=csrf-token]').attr('content'), user: { email: this.state.email, password: this.state.password, } }, success: function (model, resp, object) { alert('Welcome Back!'); location.href = "/"; }, error: function (model, resp, object) { alert('Email/Password combination not found.'); } }) }, updateEmail (e) { this.setState({ email: e.currentTarget.value }) }, updatePassword (e) { this.setState({ password: e.currentTarget.value }) }, openModal () { $('.sign-in').modal({ detachable: false }).modal('show'); }, checkForEnter (e) { if (e.keyCode == 13) { e.preventDefault this.signIn(); } }, render () { return ( <div classNameName="" style={this.state.style}> <button onClick={this.openModal}> Sign In </button> <div className="ui modal small sign-in" onKeyDown={this.checkForEnter}> <i className="close icon"></i> <div className="header"> Sign In </div> <div className="image content"> <div className="description ui form"> <div className="field"> <input type="email" placeholder="Email" onChange={this.updateEmail} /> </div> <div className="field"> <input type="password" placeholder="Password" onChange={this.updatePassword} /> </div> </div> </div> <div className="actions"> <div className="ui black deny button"> Nope </div> <div className="ui green right labeled icon button" onClick={this.signIn}> Yep, that's me <i className="checkmark icon"></i> </div> </div> </div> </div> ) } });
import React from 'react'; import { withRouter } from 'react-router' import Butter from 'buttercms'; import ReactDisqusComments from 'react-disqus-comments'; import Highlight from 'react-highlight' import { connect } from 'react-redux' import { FacebookShareButton, FacebookIcon, TwitterShareButton, TwitterIcon, LinkedinShareButton, LinkedinIcon, } from 'react-share' import { createPostUrl } from 'helpers/disqus' import { createTextDate } from 'helpers/dates' import { PostTitle } from 'Components' const butter = Butter(process.env.BUTTERCMS_KEY); function browserSelector({browser}) { return {browser} } @connect(browserSelector) class PostComplete extends React.Component { constructor(props) { super(props); this.state = { loaded: false } } fetchPost(slug) { butter.post.retrieve(slug).then((resp) => { this.setState({ loaded: true, post: resp.data.data }) }); } componentWillMount() { const slug = this.props.slug; this.fetchPost(slug); } componentWillReceiveProps(nextProps) { this.setState({loaded: false}); const slug = nextProps.slug; this.fetchPost(slug) } render() { if (this.state.loaded) { const { post } = this.state; const { history } = this.props; const shortname = 'andrewgingrich'; const blogUrl = 'https://blog.andrewgingrich.com/#/'; const historyLocation = history && history.location.pathname.slice(1) const postLocation = blogUrl + historyLocation; return ( <div className="postBody"> <PostTitle postImage={post.featured_image} post={post} /> <Highlight innerHTML={true} languages={['javascript', 'C']}> {post.body} </Highlight> <div className="postFooter"> <div className="container"> <span className="publishedDate">Published on {createTextDate(post.published)}.</span> <div className="postFooterClearFix"></div> <span className="shareIcon"><i className="fa fa-share-alt fa-lg" /></span> <span className="shareDivider">|</span> <FacebookShareButton url={postLocation} className="shareButtons"> <FacebookIcon round size={32} /> </FacebookShareButton> <TwitterShareButton url={postLocation} className="shareButtons"> <TwitterIcon round size={32} /> </TwitterShareButton> <LinkedinShareButton url={postLocation} className="shareButtons"> <LinkedinIcon round size={32} /> </LinkedinShareButton> </div> </div> <ReactDisqusComments shortname={shortname} identifier={post.slug} title={post.title} url={createPostUrl(post.url)} onNewComment={this.handleNewComment} /> </div> ) } else { return ( <div> Loading... </div> ) } } } export default withRouter(PostComplete)
module.exports = { mongoURI: "mongodb://jeff:1234@ds161539.mlab.com:61539/reactpractice" };
/* * * Copyright (C) 2015 Giorgi Guliashvili * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * */ /** * Created by Alex on 6/18/2015. */ // Login management goes here. function createLogin() { $('#loginForm').submit(function () { if (!validateLoginForm()) return false; var formData = $("#loginForm").serialize(); $.ajax({ url: "/login", method: "post", data: formData, cache: false, success: function (data) { console.log("Logged in\n" + JSON.stringify(formData)); console.log(data); //$("#panel").load(data); $("footer").hide(); $("#panel").html(data); $("#loginModal").modal('hide'); $("#banner").hide(); }, error: function (data) { $("#loginError").removeClass("hidden"); console.error("Couldn't log in\n" + JSON.stringify(formData)); } }); return false; }); } function validateLoginForm() { $("#actionError").addClass("hidden"); $("#loginError").addClass("hidden"); if ($("#userLogin:checked").val() == undefined && $("#driverLogin:checked").val() == undefined && $("#companyLogin:checked").val() == undefined) { $("#actionError").removeClass("hidden"); return false; } return true; }
(function () { "use strict"; var hour = new Date().getHours(); var daylight = hour >= 7 && hour < 19; var elements = document.getElementsByClassName("daylight"); for (var i = 0; i < elements.length; i++) { elements[i].classList.add(daylight ? "on" : "off"); } })();
var enum_8c = [ [ "enum_string_set", "enum_8c.html#ad1cb9038cae3c2f18c23629b4a27592e", null ], [ "enum_string_get", "enum_8c.html#a78b8c3c203de744be9cc40185ecbb07f", null ], [ "enum_native_set", "enum_8c.html#a01cbc276c2c7236cdcc4c12c7a6dd299", null ], [ "enum_native_get", "enum_8c.html#a5e4bce191d544a8b0ce3c3df5a4d434f", null ], [ "enum_reset", "enum_8c.html#a29d0fea6326c950f32712265a9dd68dd", null ], [ "cst_enum", "enum_8c.html#aacad95f816cb5b6b87f3bcd0720b2c2e", null ] ];
import './GithubRepoCard.css'; export default function GithubRepoCard({repo}) { const {title, description, stars, issues, profileImg, userName} = repo; return ( <div className="box"> <span className="card-title">{title}</span> <img src={profileImg} alt="user-profile" className="image-box" /> <span className="card-description">{description}</span> <span className="card-stars">Stars: {stars}</span> <span className="card-issues">Issues: {issues}</span> <span className="card-username">Submited last month by {userName}</span> </div> ); }
import React, { Component } from "react"; import { Avatar } from "@material-ui/core"; class ItemRow extends Component { constructor(props) { super(props); this.state = {}; } componentDidUpdate(prevProps) { if (this.props != prevProps) { this.componentDidMount(); } } componentDidMount() {} isNumeric(num) { return !isNaN(num); } getImages(object) { if (!object) { return <div />; } return ( <div style={{ display: "flex", justifyContent: "row" }}> {object.hash.map(value => { if (this.isNumeric(value)) { return ( <Avatar src={require("../../../static/items/" + value + ".png")} width={50} height={50} /> ); } })} </div> ); } displayNumStats(stats) { const { palette } = this.props; if (stats) { return ( <div style={{ display: "flex", flexDirection: "column", alignItems: "center" }}> <div style={{ display: "flex", flexDirection: "row" }}> <div style={{ marginRight: 6 }}>{"Winrate "}</div> <div style={{ color: palette.LightVibrant }}> {(100 * stats.winrate).toFixed(2)}% </div> </div> <div style={{ display: "flex", flexDirection: "row" }}> <div style={{ marginRight: 6 }}>{"Games "}</div> <div style={{ color: palette.LightVibrant }}> {stats.count}</div> </div> </div> ); } } render() { const { data, title } = this.props; if (!data) { return <div />; } return ( <div style={{ display: "flex", flexDirection: "column", alignItems: "center" }}> <div style={{ color: "white", fontWeight: "bold" }}>{title}</div> <div style={{ display: "flex", flexDirection: "row", justifyContent: "space-evenly", width: "100%" }}> <div style={{ display: "flex", flexDirection: "column", alignItems: "center", color: "white" }}> <div style={{ marginBottom: 6 }}>Most Frequent</div> {this.getImages(data.highestCount)} {this.displayNumStats(data.highestCount)} </div> <div style={{ display: "flex", flexDirection: "column", alignItems: "center", color: "white" }}> <div style={{ marginBottom: 6 }}>Highest Winrate</div> {this.getImages(data.highestWinrate)} {this.displayNumStats(data.highestWinrate)} </div> </div> </div> ); } } export default ItemRow;
/** * Module dependencies. */ var o = require('dom'); var page = require('page'); var bus = require('bus'); var classes = require('classes'); var config = require('config'); page("*", function(ctx, next) { o('#content').empty(); o('.app-content').empty(); bus.emit("page:change", ctx.path); var body = classes(document.body) body.remove(/[^browser\-page|.*]/); body.add(config.env); next(); });
var path = require('path'); var webpack = require('webpack'); var JS_REGEX = /\.js$|\.jsx$|\.es6$|\.babel$/; module.exports = { devtool: 'eval', entry: [ 'webpack-hot-middleware/client', './example/src/scripts/App' ], output: { path: path.join(__dirname, 'example/build'), filename: 'app.js', publicPath: 'build/' }, plugins: [ new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin() ], resolve: { extensions: ['', '.js', '.jsx', '.sass'], modulesDirectories: ['node_modules', 'src'] }, module: { loaders: [ { test: JS_REGEX, include: [ path.resolve(__dirname, 'src'), path.resolve(__dirname, 'example/src') ], loader: 'babel?presets=airbnb' }, { test: /\.sass$/, loaders: [ 'style-loader', 'css-loader', 'autoprefixer-loader?browsers=last 2 version', 'sass-loader?indentedSyntax=sass&includePaths[]=' + path.resolve(__dirname, 'example/src') ] }, { test: /\.(jpe?g|png|gif|svg|woff|eot|ttf)$/, loader: 'file-loader', exclude: /node_modules/ } ] } };
function toInvert(str) { var x = str.length; var invertStr = ""; while (x>=0) { invertStr = invertStr + str.charAt(x); x--; } return invertStr; } function getAllPosibilities(name, path){ var allPath = new Array(); var bool = true; var concatPath = ""; var sizePath = path.lastIndexOf(name); while(bool){ var finalPath; var pos = path.indexOf(name); var invertPath = toInvert(path); var posIn = invertPath.lastIndexOf(toInvert(name)); var initialPath = path.substring(0, pos) + name; finalPath = concatPath + initialPath; var newPath = toInvert(invertPath.substring(0, posIn)); //console.log(initialPath + " ------------ " + newPath + " -------------- " + concatPath +" -------- " + finalPath); path = newPath; concatPath = finalPath; if(sizePath === finalPath.lastIndexOf(name)){ bool = false; } //console.log(sizePath + " / " +finalPath.length) allPath.push(finalPath); } //console.log(cadenas); return allPath; }
const fp = require('fastify-plugin'); const fastAls = require('fast-als'); const httpContext = { get: fastAls.get, set: fastAls.set }; const validHooks = [ 'onRequest', 'preParsing', 'preValidation', 'preHandler', 'preSerialization', 'onError', 'onSend', 'onResponse' ]; function plugin(fastify, opts, next) { const defaults = opts.defaults || {}; const hook = opts.hook || 'onRequest'; if (!validHooks.includes(hook)) { fastify.log.error(`${hook} is not a valid fastify hook. Please use one of the following ${validHooks}`); } fastify.addHook('onRequest', (req, res, done) => { fastAls.runWith(defaults, () => { done(); }); }); next(); } module.exports = { validHooks: validHooks, httpContext: httpContext, fastifyHttpContextPlugin: fp(plugin, { fastify: '2.x', name: 'fastify-http-context' }) };
import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View, Image, TouchableOpacity } from 'react-native'; import Dimensions from 'Dimensions'; var width = Dimensions.get('window').width; var LogoDetail = React.createClass({ render:function(){ return ( <View style={styles.container}> {this.renderDetail(100,"优惠券")} {this.renderDetail(12,"评价")} {this.renderDetail(50,"收藏",0)} </View> ); }, renderDetail:function(num,des,id){ if (id == 0) { return ( <TouchableOpacity activeOpacity={0.5}> <View style={styles.specialStyle}> <Text style={styles.txtStyle}>{num}</Text> <Text style={styles.txtStyle}>{des}</Text> </View> </TouchableOpacity> ); } return ( <TouchableOpacity activeOpacity={0.5}> <View style={styles.detailStyle}> <Text style={styles.txtStyle}>{num}</Text> <Text style={styles.txtStyle}>{des}</Text> </View> </TouchableOpacity> ); } }) var styles = StyleSheet.create({ container:{ height:45, flexDirection:"row" }, specialStyle:{ width:width/3, alignItems:"center", }, detailStyle:{ width:width/3, borderRightWidth:1, borderColor:"#fefefe", borderStyle:"solid", alignItems:"center", }, txtStyle:{ color:"#fefefe", fontSize:15, } }); module.exports = LogoDetail;
import React from "react"; import firebase from "firebase/app"; import "firebase/auth"; import Header from "./Header"; function ProfilePage() { const user = firebase.auth().currentUser; const name = user.displayName; return ( <div> <Header name={name} /> </div> ); } export default ProfilePage;
import "./App.css"; import { Grid } from "@material-ui/core"; import ProjectCard from "./components/ProjectCard"; import React from "react"; import { projectCardData } from "constants/ProjectCardData"; import img1 from "./assets/img1.jpg"; function App() { return ( <div className="App" style={{ fontSize: 20 }}> <Grid container direction="row" justifyContent="space-between"> {projectCardData.map((project) => { return <ProjectCard data={project} imgURL={img1} />; })} </Grid> </div> ); } export default App;
angular.module('palpite.megasena') .controller('PalpiteController', function($scope, $resource, PalpiteMesena) { //Variável para atribuir todo objeto dos palpites atribuidos; $scope.palpitesMegasena = []; //variavel de texto para avisos; $scope.mensagem = {textos: ''}; // Variavel para ativar funçao COLLAPSED em Angular.js $scope.active = true; //Função AngularJS para pegar todos palpites function sugerirPalpitesMegasena() { PalpiteMesena.query( function(palpites) { $scope.palpitesMegasena = palpites; $scope.mensagem = {}; }, function(erro) { console.log(erro); $scope.mensagem = { texto: 'Não foi possível obter Palpites da Megasena!' } } ); } $scope.exibir = function() { sugerirPalpitesMegasena(); $scope.sugerirPalpitesMegasena = sugerirPalpitesMegasena; } function hasClassName(inElement, inClassName) { var regExp = new RegExp('(?:^|\\s+)' + inClassName + '(?:\\s+|$)'); return regExp.test(inElement.className); } function addClassName(inElement, inClassName) { if (!hasClassName(inElement, inClassName)) inElement.className = [inElement.className, inClassName].join(' '); } function removeClassName(inElement, inClassName) { if (hasClassName(inElement, inClassName)) { var regExp = new RegExp('(?:^|\\s+)' + inClassName + '(?:\\s+|$)', 'g'); var curClasses = inElement.className; inElement.className = curClasses.replace(regExp, ' '); } } function toggleClassName(inElement, inClassName) { if (hasClassName(inElement, inClassName)) removeClassName(inElement, inClassName); else addClassName(inElement, inClassName); } function toggleShape() { var shape = document.getElementById('shape'); if (hasClassName(shape, 'ring')) { removeClassName(shape, 'ring'); addClassName(shape, 'cube'); } else { removeClassName(shape, 'cube'); addClassName(shape, 'ring'); } // Move the ring back in Z so it's not so in-your-face. var stage = document.getElementById('stage'); if (hasClassName(shape, 'ring')) stage.style.webkitTransform = 'translateZ(-200px)'; else stage.style.webkitTransform = ''; } function toggleBackfaces() { var backfacesVisible = document.getElementById('backfaces').checked; var shape = document.getElementById('shape'); if (backfacesVisible) addClassName(shape, 'backfaces'); else removeClassName(shape, 'backfaces'); } });
import React, {useState} from 'react' // import Aux from '../../Component/hoc/Aux' import Burger from '../../Component/Burger/Burger' import BuildControls from '../../Component/Burger/BuildControls/BuildControls' import Modal from '../../Component/Burger/UI/Modal/Modal' import OrderSummery from '../../Component/Burger/OrderSummery/OrderSummery' import axios from '../../../src/axios-orders' import Spinner from '../../Component/Burger/UI/Spinner/Spinner' import withErrorHandler from '../../Component/hoc/withErrorHandler/withErrorHandler' const INGREDIENT_PRICES={ salad:0.5, bacon:0.4, cheese:1.3, meat:0.7, } const BurgerBuilder = (props)=> { const [state, setState] = useState ( { ingredient:{ salad:0, bacon:0, cheese:0, meat:0, }, TotalPrice:4, purchaseAble:false, purchasing:false, loading:false } ) const {ingredient,TotalPrice,purchaseAble,purchasing,loading} = state; const updatePurchase = (ingredients,newprice)=>{ // console.log('IG',ingredients) const sum=Object.keys(ingredients) .map((igKey)=>{ // console.log(igKey) return ingredients[igKey] }).reduce((sum,el)=>{ return sum+el; },0) console.log(state) setState({...state,ingredient:ingredients,purchaseAble:sum>0,TotalPrice:newprice}) } const addIngredients=(type)=>{ const oldCount=ingredient[type]; const updateCount=oldCount + 1; const updatedIngredients={ ...ingredient } // console.log('Up ' + updatedIngredients) updatedIngredients[type]=updateCount; const priceAddition=INGREDIENT_PRICES[type] const oldPrice =TotalPrice; const newPrice=oldPrice + priceAddition; // console.log(newPrice) setState({...state, ingredient:updatedIngredients,TotalPrice:newPrice}) // console.log(state) updatePurchase(updatedIngredients,newPrice) } const removeIngredients=(type)=>{ const oldCount=state.ingredient[type]; if(oldCount <= 0){ return } const updateCount=oldCount - 1; const updatedIngredients={ ...state.ingredient } updatedIngredients[type]=updateCount; const priceAddition=INGREDIENT_PRICES[type] const oldPrice =state.TotalPrice; const newPrice=oldPrice - priceAddition; setState({...state,TotalPrice:newPrice, ingredient:updatedIngredients}) updatePurchase(updatedIngredients,newPrice) } const purchaseHandler=()=>{ setState({...state,purchasing:true}) } const purshaseCancledHandler=()=> { setState({purchasing:false}); } const purchaseContinueHandler=()=>{ const queryParems=[]; for(let i in state.ingredient) { queryParems.push(encodeURIComponent(i) + '=' + encodeURIComponent(state.ingredient[i])) } const queryString = queryParems.join('&'); props.history.push({ pathname:'./checkout', search:'?' + queryString, }) } const disableInfo={ ...state.ingredient } for(let key in disableInfo){ disableInfo[key]=disableInfo[key] <= 0; } let orderSummery=null; let p =TotalPrice console.log(p) orderSummery=<OrderSummery price={TotalPrice} purchaseCancled={purshaseCancledHandler} purchaseContinue={purchaseContinueHandler} ingredients={ingredient} /> if(loading){ orderSummery=<Spinner /> } return( <> <Modal show={purchasing} modalClosed={purshaseCancledHandler} > {orderSummery} </Modal> <Burger ingredient={ingredient} /> <BuildControls price={TotalPrice} ingredientAdded={addIngredients} ingredientDeleted={removeIngredients} disabled={disableInfo} purchaseAble={purchaseAble} order={purchaseHandler} /> </> ) } export default withErrorHandler(BurgerBuilder,axios);
import React from 'react'; import PropTypes from 'prop-types'; import '../styles/flashcard.css'; import editbtn from '../img/buttons/edit_FFFFFF.png'; import deletebtn from '../img/buttons/delete_FFFFFF.png'; const DeckListItemComp = (props) => { const { deck, onDeckDelete, onDeckSelect, onDeckEdit, } = props; function handleItemClick() { // console.log('in handleItemClick'); // do something, then onDeckSelect(deck.deck_id); } function handleEditClick() { // console.log('in handle edit click'); onDeckEdit(deck); } function handleDeleteClick() { // console.log('in handle delete click'); onDeckDelete(deck.deck_id); } return ( <div className="DeckListItemComp ItemBox AppListItem" role="button" tabIndex="0" > <span className="DeckListItemText DetailText" role="button" tabIndex="0" onClick={handleItemClick} onKeyPress={handleItemClick} >{deck.deck_name} </span> <button className="DeckListItemEdit AppBtn" type="button" onClick={handleEditClick}> <img className="btnImg" src={editbtn} alt="Edit" /> </button> <button className="DeckListItemDelete AppBtn Delete" type="button" onClick={handleDeleteClick}> <img className="btnImg" src={deletebtn} alt="Delete" /> </button> <hr /> </div> ); }; DeckListItemComp.defaultProps = { onDeckSelect: () => { }, onDeckEdit: () => { }, onDeckDelete: () => { }, }; DeckListItemComp.propTypes = { deck: PropTypes.shape({ deck_id: PropTypes.string.isRequired, deck_name: PropTypes.string.isRequired, }).isRequired, onDeckSelect: PropTypes.func, onDeckEdit: PropTypes.func, onDeckDelete: PropTypes.func, }; export default DeckListItemComp;
(function(){ var app = angular.module('collectionApp', ['elements-directives']); app.controller('collectionController', [ '$http', function($http){ var self = this; this.collectionSet = []; $http.get('json/elements.json').success(function(data){ self.collectionSet = data; }); /* Инициализация */ this.init = function(){ this.device = this.deviceDetect(); // Если не смартфон — показываем меню if(this.device != 'smartphone') this.sidebarClosed = false else this.sidebarClosed = true; // Устанавливаем для какого устройства коллекция this.deviceElements = 'desktop'; } /* Различные события на ресайз */ $( window ).resize(function() { self.device = self.deviceDetect(); }); /* Детектим девайс */ this.deviceDetect = function(){ // Возвращаем смартфон if (Modernizr.mq('(max-width: 768px)')) { return 'smartphone'; } else { // Возвращаем планшет if (Modernizr.mq('(min-width: 768px) and (max-width: 991px)')) { return 'tablet'; } else { // Возвращаем ноутбук if (Modernizr.mq('(min-width: 992px) and (max-width: 1199px)')) { return 'notebook'; } else { // Возвращаем десктоп if (Modernizr.mq('(min-width: 1200px)')) { return 'desktop'; } } } } } /* Работаем с тоглером */ this.sidebarToggler = function(){ this.sidebarClosed = !this.sidebarClosed; console.log(this.sidebarClosed); } /* Тогглим меню Групп */ this.groupMenuToggler = function(){ this.groupMenuClosed = !this.groupMenuClosed; this.sidebarClosed = false; } /* Инициализация */ this.init(); }]); })();
class Playmap2 extends Phaser.Scene { constructor() { super("playScene2"); } preload() { //this.load.audio('menubgm', './assets/Final_Game_BGM_Menu.mp3') //this.load.audio('bgm', './assets/Final_Game_BGM.mp3') this.load.path = "./assets/"; this.load.tilemapTiledJSON('tilemap2', 'tilemap2.json'); this.load.spritesheet("tileset", "tiles.png", { frameWidth: 28, frameHeight: 28, margin: 1, spacing: 2 }); } create() { //bgm added // let music = this.sound.add('bgm', { // mute: false, // volume: .3, // rate: 1, // detune: 0, // seek: 0, // loop: true, // delay: 0 // }); // music.play(); // tileset and map declarations const map = this.add.tilemap("tilemap2"); const tileset = map.addTilesetImage("Tileset", "tileset"); const groundLayer = map.createLayer("Ground", tileset, 0, 0); this.wallLayer = map.createLayer("Walls", tileset, 0, 0); groundLayer.setCollisionByProperty({ collides: false }); this.wallLayer.setCollisionByProperty({ collides: true }); // player spawn this.playerSpawn = map.findObject("Objects", obj => obj.name === "Spawn"); this.princess = new Princess(this, this.playerSpawn.x, this.playerSpawn.y, "tileset", 83); this.physics.add.collider(this.princess, this.wallLayer); // enemies spawn // this.enemy10 = new Enemy(this, this.playerSpawn.x + 56, this.playerSpawn.y, "tileset", 97); // test boi for easy viewing // this.addPhysics(this.enemy10); this.enemy0 = new Enemy(this, 1160, 1634, "tileset", 97); this.addPhysics(this.enemy0); this.enemy1 = new Enemy(this, 768, 1464, "tileset", 97); this.addPhysics(this.enemy1); this.enemy2 = new Enemy(this, 377, 873, "tileset", 97); this.addPhysics(this.enemy2); this.enemy3 = new Enemy(this, 1215, 627, "tileset", 97); this.addPhysics(this.enemy3); this.enemy4 = new Enemy(this, 2030, 903, "tileset", 97); this.addPhysics(this.enemy4); this.enemy5 = new Enemy(this, 740, 2102, "tileset", 97); this.addPhysics(this.enemy5); this.enemy6 = new Enemy(this, 1918, 1936, "tileset", 97); this.addPhysics(this.enemy6); this.enemy7 = new Enemy(this, 1413, 2497, "tileset", 97); this.addPhysics(this.enemy7); this.enemy8 = new Enemy(this, 2142, 2134, "tileset", 97); this.addPhysics(this.enemy8); this.enemy9 = new Enemy(this, 2254, 2556, "tileset", 97); this.addPhysics(this.enemy9); // Generate stones from map this.stones = map.createFromObjects("Objects", { name: "Stone", key: "tileset", frame: 95 }); document.getElementById("stoneDisplay").innerHTML = "Stones: " + this.princess.stoneBag; // attach physics to the stones this.physics.world.enable(this.stones, Phaser.Physics.Arcade.STATIC_BODY); this.stones.map((stone) => { stone.body.setCircle(4).setOffset(4,4); }); this.stoneGroup = this.add.group(this.stones); //Stairs spawn this.stairsSpawn = map.findObject("Objects", obj => obj.name === "Stairs"); this.stairs = new Stairs(this, this.stairsSpawn.x, this.stairsSpawn.y, "tileset", 78); //this.addPhysicsstairs(this.stairs); // this.physics.world.collide(this.princess, this.stairs, function(){ // game.scene.start('playScene2'); // }); // apply pickup and drop mechanics to stones generated from map this.physics.add.overlap(this.princess, this.stoneGroup, (obj1, obj2) => { if(Phaser.Input.Keyboard.JustDown(keySPACE)) { obj2.destroy(); this.sound.play('collect'); this.princess.stoneBag += 1; document.getElementById("stoneDisplay").innerHTML = "Stones: " + this.princess.stoneBag; } }); // nighttime filter this.night = this.add.rectangle(0, 0, 10000, 10000, 0x000022, 0.7); this.night.setDepth(5); // key declarations keySPACE = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.SPACE); keyLEFT = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.LEFT); keyRIGHT = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.RIGHT); keyUP = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.UP); keyDOWN = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.DOWN); keyD = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.D); keyS = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.S); // player animations this.anims.create({ key: 'idledown', defaultTextureKey: 'tileset', frames: [ { frame: 83 } ], repeat: -1 }); this.anims.create({ key: 'idleright', defaultTextureKey: 'tileset', frames: [ { frame: 86 } ], repeat: -1 }); this.anims.create({ key: 'idleleft', defaultTextureKey: 'tileset', frames: [ { frame: 89 } ], repeat: -1 }); this.anims.create({ key: 'idleup', defaultTextureKey: 'tileset', frames: [ { frame: 92 } ], repeat: -1 }); this.anims.create({ key: 'walkdown', defaultTextureKey: 'tileset', frames: [ { frame: 84 }, { frame: 83 }, { frame: 85 }, { frame: 83 } ], frameRate: 7, repeat: -1 }); this.anims.create({ key: 'walkright', defaultTextureKey: 'tileset', frames: [ { frame: 87 }, { frame: 86 }, { frame: 88 }, { frame: 86 } ], frameRate: 7, repeat: -1 }); this.anims.create({ key: 'walkleft', defaultTextureKey: 'tileset', frames: [ { frame: 90 }, { frame: 89 }, { frame: 91 }, { frame: 89 } ], frameRate: 7, repeat: -1 }); this.anims.create({ key: 'walkup', defaultTextureKey: 'tileset', frames: [ { frame: 93 }, { frame: 92 }, { frame: 94 }, { frame: 92 } ], frameRate: 7, repeat: -1 }); // Enemy Animations this.anims.create({ key: 'enwalkdown', defaultTextureKey: 'tileset', frames: [ { frame: 98 }, { frame: 97 }, { frame: 99 }, { frame: 97 } ], frameRate: 4, repeat: -1 }); this.anims.create({ key: 'enwalkleft', defaultTextureKey: 'tileset', frames: [ { frame: 101 }, { frame: 100 } ], frameRate: 4, repeat: -1 }); this.anims.create({ key: 'enwalkright', defaultTextureKey: 'tileset', frames: [ { frame: 103 }, { frame: 102 } ], frameRate: 4, repeat: -1 }); this.anims.create({ key: 'enwalkup', defaultTextureKey: 'tileset', frames: [ { frame: 105 }, { frame: 104 }, { frame: 106 }, { frame: 104 } ], frameRate: 4, repeat: -1 }); //sets camera to follow player this.cameras.main.setZoom(4); this.cameras.main.startFollow(this.princess); } update() { this.princess.update(); this.enemy0.update(); this.enemy1.update(); this.enemy2.update(); this.enemy3.update(); this.enemy4.update(); this.enemy5.update(); this.enemy6.update(); this.enemy7.update(); this.enemy8.update(); this.enemy9.update(); this.stairs.update(); // this.enemy10.update(); } addPhysics(enemy) { this.physics.add.collider(enemy, this.wallLayer, (obj1, obj2) => { obj1.direction = Math.floor(Math.random() * 4); }); this.physics.add.collider(enemy, this.princess, (obj1, obj2) => { obj2.x = this.playerSpawn.x; obj2.y = this.playerSpawn.y; }); } addPhysicsstairs(stairs){ this.physics.add.collider(this.stairs, this.princess, (obj1, obj2)=> { //this.scene.start('playScene2'); //this.sound.stopAll(); }) } }
import * as categoriesAPI from "./fakeCategoryService"; const plants = [ { _id: "5b21ca3eeb7f6fbccd471815", title: "Jade Plant", category: { _id: "5b21ca3eeb7f6fbccd471814", name: "Indoor Plants" }, imageURL: "https://images.unsplash.com/photo-1597334133882-7027ac9bd95e?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=600&q=60" }, { _id: "5b21ca3eeb7f6fbccd471816", title: "Peace Lily", category: { _id: "5b21ca3eeb7f6fbccd471818", name: "Hanging plants" }, imageURL: "https://images.unsplash.com/photo-1513347650-efb9c18ea41a?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=632&q=80" }, { _id: "5b21ca3eeb7f6fbccd471817", title: "Succelent", category: { _id: "5b21ca3eeb7f6fbccd471820", name: "Garden Plants" }, liked: true, imageURL: "https://images.unsplash.com/photo-1513347650-efb9c18ea41a?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=632&q=80" }, { _id: "5b21ca3eeb7f6fbccd47181a", title: "Hibiscus Plant", category: { _id: "5b21ca3eeb7f6fbccd471820", name: "Garden Plants" }, liked: true, imageURL: "https://images.unsplash.com/photo-1513347650-efb9c18ea41a?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=632&q=80" }, { _id: "5b21ca3eeb7f6fbccd47181b", title: "Snake Plant", category: { _id: "5b21ca3eeb7f6fbccd471814", name: "Indoor Plants" }, imageURL: "https://images.unsplash.com/photo-1513347650-efb9c18ea41a?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=632&q=80" }, { _id: "5b21ca3eeb7f6fbccd47181e", title: "Tulip", category: { _id: "5b21ca3eeb7f6fbccd471820", name: "Garden Plants" }, imageURL: "https://images.unsplash.com/photo-1513347650-efb9c18ea41a?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=632&q=80" }, { _id: "5b21ca3eeb7f6fbccd47181f", title: "Succelent", category: { _id: "5b21ca3eeb7f6fbccd471820", name: "Garden Plants" }, imageURL: "https://images.unsplash.com/photo-1513347650-efb9c18ea41a?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=632&q=80" }, { _id: "5b21ca3eeb7f6fbccd47182g", title: "Succelent", category: { _id: "5b21ca3eeb7f6fbccd471821", name: "Garden Plants" }, imageURL: "https://images.unsplash.com/photo-1513347650-efb9c18ea41a?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=632&q=80" }, { _id: "5b21ca3eeb7f6fbccd471821", title: "Aloe vera", category: { _id: "5b21ca3eeb7f6fbccd471818", name: "Indoor Plants" }, imageURL: "https://images.unsplash.com/photo-1567689265664-1c48de61db0b?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=676&q=80" } ]; export function getPlants() { return plants; } export function getPlant(id) { return plants.find((m) => m._id === id); }
import Feeds from './feed'; import FeedContainer from './feed-container'; import FeedHeader from './feed-header'; import FeedFooter from './feed-footer'; export { Feeds, FeedContainer, FeedHeader, FeedFooter, };
import React from 'react' import loader from '../../Images/loading-arrow.gif' export const Loading = () => { return ( <div> <img src={loader}/> </div> ) }
const app = "I don't do much." var kittens = ["Milo", "Otis", "Garfield"] function destructivelyAppendKitten (name) { kittens.push (name) return kittens } function destructivelyPrependKitten (name) { kittens.unshift (name) return kittens } function destructivelyRemoveLastKitten (name) { kittens.pop (name) return kittens } function destructivelyRemoveFirstKitten (name) { kittens.shift (name) return kittens } function appendKitten (name) { var theKittens = [...kittens] theKittens.push (name) return theKittens } function prependKitten (name) { var theKittens = [...kittens] theKittens.unshift (name) return theKittens } function removeLastKitten (name) { var theKittens = [...kittens] theKittens.pop (name) return theKittens } function removeFirstKitten (name) { var theKittens = [...kittens] theKittens.shift (name) return theKittens }
import React, { Component } from 'react'; import {socket} from '../Router'; import Prompt from "./Prompt"; import Voting from "./Voting"; class Game extends Component { constructor() { super(); this.state = { stage: 2 }; } render() { let component = null; switch (this.state.stage){ case 1: component = <Prompt/>; break; case 2: component = <Voting/>; break; } return ( <div> {component} </div> ); } } export default Game;
var gulp = require('gulp'); var usemin = require('gulp-usemin'); var uglify = require('gulp-uglify'); var minifyCss = require('gulp-minify-css'); var browserSync = require('browser-sync'); var reload = browserSync.reload; var sass = require('gulp-sass'); gulp.task('usemin', function() { return gulp.src('app/views/**/*.handlebars') .pipe(usemin({ js: [uglify()], css: [minifyCss()] })) .pipe(gulp.dest('dist/views/')); }); gulp.task('browser-sync', function() { browserSync({ proxy: 'localhost', browser: 'google-chrome', notify: false }); }); gulp.task('sass', function() { return gulp.src('app/scss/**/*.scss') .pipe(sass()) .pipe(gulp.dest('app/css')) .pipe(reload({ stream: true })); }); gulp.task('bs-reload', function() { browserSync.reload(); }); gulp.task('templates', function() { gulp.src('app/views/**/*.handlebars') .pipe(gulp.dest('dist/views')); }); gulp.task('default', ['sass', 'browser-sync'], function() { gulp.watch('app/scss/**/*.scss', ['sass']); gulp.watch('app/views/**/*.handlebars', ['bs-reload', 'templates']); });
Page({ data: { tabs: ["全部", "待收货", "已完成", "已取消"], activeIndex: 0, sliderWidth: 0, sliderOffset: 0, sliderLeft: 0, dataSet: { 0: { offset: "", infos: [] }, 1: { offset: "", infos: [] }, 2: { offset: "", infos: [] }, 3: { offset: "", infos: [] }, } }, onLoad: function () { var that = this; wx.getSystemInfo({ success: function (res) { var sliderWidth = res.windowWidth / that.data.tabs.length - 30; that.setData({ sliderWidth: sliderWidth, scrollHeight: res.windowHeight, sliderLeft: (res.windowWidth / that.data.tabs.length - sliderWidth) / 2, sliderOffset: res.windowWidth / that.data.tabs.length * that.data.activeIndex }); that.fetchData(0); } }); }, tabClick: function (e) { this.setData({ sliderOffset: e.currentTarget.offsetLeft, activeIndex: e.currentTarget.id }); this.fetchData(e.currentTarget.id) }, // 事件处理函数 goBookDetail: function (e) { var id = e.currentTarget.id; console.log(id); var url = '../bookDetail/bookDetail?id=' + id; wx.navigateTo({ url: url }) }, goOrderDetail: function (e) { var order_no = e.currentTarget.dataset.order; var url = '../orderDetail/orderDetail?order_no=' + order_no; wx.navigateTo({ url: url }) }, touchStartElement: function (e) { console.log("start", e); var id = e.currentTarget.id; this.setData({ activeHoverIndex: id }) }, touchEndElement: function (e) { console.log("end", e); var that = this; setTimeout(function () { that.setData({ //warnning undefined==""=="0"==0 activeHoverIndex: "none" }) }, 500) }, touchMoveElement: function (e) { console.log("move", e); this.setData({ activeHoverIndex: "none" }) }, onCancel: function (e) { var that = this; var order_no = e.currentTarget.dataset.order; console.log(order_no); var params = {} params["order_no"] = order_no getApp().doRequest({ method: 'POST', url: getApp().config.host + "/cancel_order_after_pay", header: { "Content-Type": "application/x-www-form-urlencoded", "token": getApp().globalData.userInfo.token }, data: params, success: function (res) { if (res.data.code != 0) { wx.showToast({ title: res.data.msg, icon: 'error', duration: 1000 }) return } wx.showToast({ title: res.data.msg, icon: 'error', duration: 1000 }) that.fetchData(that.data.activeIndex); } }); }, onConfirmReceive: function (e) { var that = this; var order_no = e.currentTarget.dataset.order; console.log(order_no); var params = {} params["order_no"] = order_no getApp().doRequest({ method: 'POST', url: getApp().config.host + "/confirm_receive", header: { "Content-Type": "application/x-www-form-urlencoded", "token": getApp().globalData.userInfo.token }, data: params, success: function (res) { if (res.data.code != 0) { wx.showToast({ title: res.data.msg, icon: 'error', duration: 1000 }) return } wx.showToast({ title: res.data.msg, icon: 'error', duration: 1000 }) that.fetchData(that.data.activeIndex); } }); }, fetchData: function (tab, callback) { var that = this; var params = {}; var data = []; var current_data = this.data.dataSet[tab] if (current_data.offset) { data = current_data.infos params["offset"] = current_data.offset } params["cat"] = that.data.activeIndex getApp().doRequest({ url: getApp().config.host + "/my_bought_list", header: { "Content-Type": "application/x-www-form-urlencoded", "token": getApp().globalData.userInfo.token }, data: params, success: function (res) { var datas = data.concat(res.data.data.infos); console.log(res, tab) if (tab == 0) { that.setData({ hidden: true, 'dataSet.0.infos': datas, 'dataSet.0.offset': res.data.data.offset, 'dataSet.0.hasMore': res.data.data.has_more, loadingBottom: false, }) } if (tab == 1) { that.setData({ hidden: true, 'dataSet.1.infos': datas, loadingBottom: false, 'dataSet.1.hasMore': res.data.data.has_more, 'dataSet.1.offset': res.data.data.offset, }) } if (tab == 2) { that.setData({ hidden: true, 'dataSet.2.infos': datas, loadingBottom: false, 'dataSet.2.hasMore': res.data.data.has_more, 'dataSet.2.offset': res.data.data.offset, }) } if (tab == 3) { that.setData({ hidden: true, 'dataSet.3.infos': datas, loadingBottom: false, 'dataSet.3.hasMore': res.data.data.has_more, 'dataSet.3.offset': res.data.data.offset, }) } if (callback) { callback(); } } }) }, scroll: function (e) { //必须先临时变量 不然滑动式 这里会并发 没发固定顺序 console.log("scroll", e.detail.scrollHeight, e.detail.scrollTop) if (e.detail.scrollHeight - e.detail.scrollTop < 1000) { if (this.data.loadingBottom==true) { console.log("isloading.....") return; } this.setData({ loadingBottom: true, }) this.fetchData(this.data.activeIndex); } }, goChooseBookList: function (e) { var bookIds = e.currentTarget.dataset.books; var url = '../chooseBookList/chooseBookList?user_book_ids=' + bookIds; wx.navigateTo({ url: url }) } });
import React from 'react'; import { Link } from 'react-router-dom'; import { connect } from 'react-redux'; import Flexbox from 'flexbox-react'; class Navbar extends React.Component { render() { return ( <Flexbox element="header" height="60px" > <button type="button" className="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false"> <span className="sr-only">Toggle navigation</span> <span className="icon-bar" /> <span className="icon-bar" /> <span className="icon-bar" /> </button> <Link className="navbar-brand" to="/">Code...</Link> </Flexbox> ); } } export default connect(null,null)(Navbar);
// select geometry volume blocker shader // select blocker from inject blocker(rsm) & inject blocker2(depth normal) var selectGvFragmentShader = " precision mediump float; \n" + " uniform sampler2D gv_from_rsm; \n" + " uniform sampler2D gv_from_visible_surface; \n" + " \n" + " varying vec2 tex_coord; \n" + " \n" + " void main() { \n" + " // if we have two blocking potentials in the same cell we have to select one \n" + " \n" + " // select based on magnitude \n" + " vec4 rsm_blocker = texture2D(gv_from_rsm, tex_coord); \n" + " float rsm_blocker_mag = dot(rsm_blocker, rsm_blocker); \n" + " \n" + " vec4 surface_blocker = texture2D(gv_from_visible_surface, tex_coord); \n" + " float surface_blocker_mag = dot(surface_blocker, surface_blocker); \n" + " \n" + " // check if rsm blocker is visible, surface blocker is visible because it comes from a surface in view space \n" + " float angle = dot(rsm_blocker, surface_blocker); \n" + " \n" + " vec4 blocker = rsm_blocker_mag > surface_blocker_mag ? rsm_blocker : surface_blocker; \n" + " blocker = angle > 0.0 ? blocker : surface_blocker; \n" + " \n" + " gl_FragColor = blocker; \n" + " } \n"; var selectGvVertexShader = " attribute vec2 position; \n" + " \n" + " varying vec2 tex_coord; \n" + " \n" + " void main() { \n" + " gl_Position = vec4(position, 0, 1); \n" + " vec2 clipPos = gl_Position.xy; \n" + " tex_coord = (clipPos * 0.5) + vec2(0.5); \n" + " } \n";
'use strict'; angular.module('teacherList', ['core.teacher']);
var snake = snake || {} snake.view = { init: function(){ gamesCentre.view.renderScore( 0 ); snake.view.setUpRowsAndSquares( 6, 6 ); snake.view.attachListeners(); }, // snakes.view.attachListeners attachListeners: function(){ // So we're going to record the next move via key press if it's right keys // and the direction isn't opposite of where the snake is going now. $(window).keydown(function(event){ if ( event.keyCode === 37 || event.keyCode === 38 || event.keyCode === 39 || event.keyCode === 40 ) { event.preventDefault(); if ( snake.model.nextDirectionIsPossible(event.keyCode) ) { snake.model.nextMove = event.keyCode;; }; }; }); $("#new-game").click(function(event){ clearInterval(myInterval); clearInterval(gameOverInterval); $("#game-over").remove(); $(window).off(); $("#new-game").off(); snake.controller.init(); }); }, // snake.view.setUpRowsAndSquares setUpRowsAndSquares: function( numberOfRows, numberOfSquaresPerRow ){ for (var r = 0; r < numberOfRows; r++ ){ var rowOfSquaresString = "<div class='game-row'>"; for (var s = 0; s < numberOfSquaresPerRow; s++){ rowOfSquaresString += "<div class='game-square'></div>" }; rowOfSquaresString += "</div>" $("#game-board").append( rowOfSquaresString ); }; }, // Adding and removing classes depending on snake.model.grid updateGrid: function(){ for (var rowNumber = 0; rowNumber < snake.model.grid.length; rowNumber++) { for (var columnNumber = 0; columnNumber < snake.model.grid[rowNumber].length; columnNumber++) { switch(snake.model.grid[rowNumber][columnNumber]) { case 0: var $head = $(".game-square").eq([rowNumber * 6 + columnNumber]); $head.attr("class","game-square").addClass("head"); snake.view.styleSnake($head, "head"); break; case "m": $(".game-square").eq([rowNumber * 6 + columnNumber]).attr("class","game-square").addClass("mouse"); break; case undefined: $(".game-square").eq([rowNumber * 6 + columnNumber]).attr("class","game-square"); break; default: var $body = $(".game-square").eq([rowNumber * 6 + columnNumber]); $body.attr("class","game-square").addClass("body"); snake.view.styleSnake($body, "body", rowNumber, columnNumber, snake.model.grid[rowNumber][columnNumber]); }; if(snake.model.lengthOfSnake >= 2 && snake.model.grid[rowNumber][columnNumber] === snake.model.lengthOfSnake - 1){ var $tail = $(".game-square").eq([rowNumber * 6 + columnNumber]); $tail.attr("class","game-square").addClass("tail"); snake.view.styleSnake($tail, "tail", rowNumber, columnNumber, snake.model.grid[rowNumber][columnNumber]); }; }; }; }, removeBorderForBodyPartAhead: function($square, rowNumber, columnNumber){ if (snake.model.directionOfNextBodyPart(rowNumber, columnNumber) === "up") { $square.addClass("body-up"); } else if (snake.model.directionOfNextBodyPart(rowNumber, columnNumber) === "down") { $square.addClass("body-down"); } else if (snake.model.directionOfNextBodyPart(rowNumber, columnNumber) === "left") { $square.addClass("body-left"); } else { $square.addClass("body-right"); }; }, removeBorderForBodyPartBehind: function($square, rowNumber, columnNumber){ if (snake.model.directionOfBodyPartBehindThisOne(rowNumber, columnNumber) === "up") { $square.addClass("body-up"); } else if (snake.model.directionOfBodyPartBehindThisOne(rowNumber, columnNumber) === "down") { $square.addClass("body-down"); } else if (snake.model.directionOfBodyPartBehindThisOne(rowNumber, columnNumber) === "left") { $square.addClass("body-left"); } else { $square.addClass("body-right"); }; }, styleSnake: function($square, type, rowNumber, columnNumber, value) { if (type === "head") { // Left if (snake.model.nextMove === 37) { $square.addClass("head-left"); // Top } else if (snake.model.nextMove === 38) { $square.addClass("head-up"); // Right } else if (snake.model.nextMove === 39) { $square.addClass("head-right"); } else { // Bottom $square.addClass("head-down"); }; } else if (type === "body") { snake.view.removeBorderForBodyPartAhead($square, rowNumber, columnNumber); snake.view.removeBorderForBodyPartBehind($square, rowNumber, columnNumber); } else { if (snake.model.directionOfNextBodyPart(rowNumber, columnNumber) === "up") { $square.addClass("tail-up"); } else if (snake.model.directionOfNextBodyPart(rowNumber, columnNumber) === "down") { $square.addClass("tail-down"); } else if (snake.model.directionOfNextBodyPart(rowNumber, columnNumber) === "left") { $square.addClass("tail-left"); } else { $square.addClass("tail-right"); }; }; } };
function painting() { const canvas = document.getElementById('canvas') if (canvas.getContext) { const audio = new Audio('路径') audio.loop = true audio.play() } }
var interface_c1_connector_create_complete_session_options = [ [ "login", "interface_c1_connector_create_complete_session_options.html#a8bbe655e267010f145efff59eb5675c1", null ], [ "password", "interface_c1_connector_create_complete_session_options.html#a580e61094dc0718af8767912ed54532b", null ], [ "serviceID", "interface_c1_connector_create_complete_session_options.html#acde4cd66b2ef5693a45999924e4915ad", null ] ];
var db = require('./db'); /** * 방 추가 * @param item_no * @param customer_no * @param callback */ exports.insert = function(consult_no, manager_no, title, params, callback) { db.pool.getConnection(function(err, conn) { if (err) callback(err); else { var sql = 'INSERT INTO room (consult_no, manager_no, title, params) ' + 'VALUES ?'; var values = [ consult_no, manager_no, title, params ]; conn.query(sql, [[values]], function(err, result) { if (err) callback(err); else { callback(null, result.insertId); } conn.release(); }); } }); }; /** * 상담번호로 방번호 찾음 * @param consult_no * @param callback */ exports.selectNoByConsultNo = function(consult_no, callback) { db.pool.getConnection(function (err, conn) { if (err) callback(err); else { var sql = 'SELECT no, title FROM room WHERE consult_no = ?'; conn.query(sql, [consult_no], function (err, rows) { if (err) callback(err); else { if (rows.length == 0) { callback(new Error('not exist rows')); } else { callback(null, rows[0].no, rows[0].title); } } conn.release(); }); } }); }; /** * 메시지 정보 업데이트 * @param roomNo * @param userType * @param callback */ exports.updateMessage = function(roomNo, userType, chatNo, callback) { db.pool.getConnection(function(err, conn) { if (err) callback(err); else { var sql = 'UPDATE room SET last_user = ?, last_update = now(), last_chat_no = ? WHERE no = ?'; conn.query(sql, [userType, chatNo, roomNo], function(err, result) { if (err) callback(err); else { callback(null, result.affectedRows); } conn.release(); }); } }); }; /** * 방 타입 확인 * @param consult_no * @param callback */ exports.selectType = function(no, callback) { db.pool.getConnection(function (err, conn) { if (err) { callback(err); } else { var sql = 'SELECT type FROM room WHERE no = ?'; conn.query(sql, [no], function (err, rows) { if (err) callback(err); else { if (rows.length == 0) { callback(new Error('not exist rows')); } else { callback(null, rows[0].type); } } conn.release(); }); } }); };
'use stricts'; module.exports.MessagesManager = require('./src/messagesManager.js'); module.exports.MessageBuffer = require('./src/buffer.js'); module.exports.Message = require('./src/message.js');
import React, {Component, PropTypes} from 'react'; import Select from 'react-select'; class ModuleSelectWrapper extends Component { constructor(props) { super(props); this.handleChange = this.handleChange.bind(this); } handleChange(value) { // react-select returns an empty string if nothing is selected const moduleIds = value ? value.split(',').map(Number) : []; this.props.onUpdateSelectedModuleIds(moduleIds); } createModuleSelectOptions(modules) { return modules.map((m) => { return { value: m.id || m.value, label: m.name || m.label }; }); } render() { return ( <div className="module-select"> <Select placeholder="No modules selected." className="module-select__input" name="moduleSelect" clearAllText="None" noResultsText="All modules have been selected." multi={true} value={this.props.selectedModuleIds.join(',')} options={this.createModuleSelectOptions(this.props.modules)} onChange={this.handleChange} /> </div> ); } } ModuleSelectWrapper.propTypes = { modules: PropTypes.array.isRequired, selectedModuleIds: PropTypes.arrayOf(PropTypes.number).isRequired, onUpdateSelectedModuleIds: PropTypes.func.isRequired }; export default ModuleSelectWrapper;