text
stringlengths
7
3.69M
import React from 'react'; import styled from '@emotion/styled'; import EntranceCheckForm from './EntranceCheckForm'; import EntranceWritePostcard from './EntranceWritePostcard'; import { Button } from '../style/commonCss'; const Wrapper = styled.div(() => ({ textAlign: 'center', })); const Title = styled.div(() => ({ fontSize: '24px', })); export default function Entrance({ entranceState: { sender, postcardCount, writtenCount, isPrivate, }, menuButtonHandlers: { onHandleClickWritePostcard, onHandleClickOtherPostcards, onHandleClickExpire, }, onHandleCheckPostcardClick, field, }) { return ( <Wrapper> <Title>{`${sender}님으로 부터 엽서가 도착했어요.`}</Title> <EntranceCheckForm isPrivate={isPrivate} field={field} onClick={onHandleCheckPostcardClick} /> <EntranceWritePostcard sender={sender} postcardCount={postcardCount} onHandleClickWritePostcard={onHandleClickWritePostcard} /> <p>{`현재 까지 ${writtenCount}명의 엽서가 작성 되었습니다.`}</p> <Button type="button" onClick={onHandleClickOtherPostcards} > 다른 사람 엽서 보러가기 </Button> <Button type="button" onClick={onHandleClickExpire} > 엽서 파기하기 </Button> </Wrapper> ); }
var expect = require('chai').expect; var request = require('request'); var Property = require('../src/property'); describe('Property', function() { var property beforeEach(function() { property = new Property('Mars', 'Very nice', '3000', 'Jan', 'https://image.ibb.co/mUUvX7/Space_House_by_night_node_full_image_2.jpg'); }); describe('#getDetails', function() { it('Should have a name', function() { expect(property.getDetails().name).to.equal('Mars') }); it('Should have a description', function() { expect(property.getDetails().desc).to.equal('Very nice') }); it('Should return a price', function() { expect(property.getDetails().price).to.equal('3000') }); it('Should return a date', function() { expect(property.getDetails().dates).to.equal('Jan') }); it('Should return a photo', function() { expect(property.getDetails().photo).to.equal( 'https://image.ibb.co/mUUvX7/Space_House_by_night_node_full_image_2.jpg') }); }); });
const bar = document.querySelector('#bar'); const modal = document.querySelector('.modal'); bar.addEventListener('click', () => { modal.classList.toggle('modal_activ') })
const NodeCache = require("node-cache") const myCache = new NodeCache({ stdTTL: 0, checkperiod: 0 }) exports.list = function (params) { const _keys = myCache.keys() const arr = [] _keys.map(item =>{ arr.push(myCache.get(item)) }) if ((params.color !== '') || (params.brand !== '')) { const result = [] arr.map(item => { if (((params.color !== '') && (params.color.toUpperCase() === item.color.toUpperCase())) || ((params.brand !== '') && (params.brand.toUpperCase() == item.brand.toUpperCase()))) { result.push(item) } }) return result } else { return arr } } exports.findById = async (params) => { const res = myCache.get(params.id) if (res == undefined) { return {} } else { return res } } exports.insert = async function (params) { const success = myCache.set(params.key, { id: params.key, license_plate: params.license_plate, color: params.color, brand: params.brand }, 0) return success } exports.update = async function (params) { myCache.take(params.id) const success = myCache.set(params.id, { id: params.key, license_plate: params.license_plate, color: params.color, brand: params.brand }, 0) return success } exports.delete = async function (params) { const res = myCache.take(params.id) return res }
const express = require('express'); const { check } = require("express-validator"); const { verifyToken, isAdmin } = require('../../middleware'); const router = express.Router(); const orderProductController = require("../../controllers/orderProducts"); router.get('/sell-in-day/:product_id/:day',[ verifyToken, ],orderProductController.sellInDay); module.exports = router
module.exports = require('bindings')('geos')
// Generated by CoffeeScript 1.7.1 var Robot, event, rand, rb, robots, x; robots = [redRobot, blueRobot]; rand = function(min, max) { return Math.floor(Math.random() * (max - min) + min); }; angular.module('challenge', []).directive('eqnGraph', function() { return { compile: function(element, attrs) { element.css({ width: '400px', height: '400px' }); return function(scope, element, attrs) { return scope.$watchCollection("[" + attrs.eqnConfig + ", " + attrs.eqnData + "]", function(_arg) { var cfg, data; cfg = _arg[0], data = _arg[1]; return $.plot(element, data, cfg); }); }; } }; }).filter('plusMinus', function() { return function(x, unary) { var x_; if (unary == null) { unary = false; } x_ = Math.abs(x); if (x >= 0) { if (unary || x === 0) { return x; } else { return "+ " + x_; } } else { if (unary) { return "-" + x_; } else { return "- " + x_; } } }; }).controller('Challenge', function($scope) { $scope.mockRobot = (Robot.mock != null) && Robot.mock; $scope.solnX = rand(-10, 10); return $scope.solnY = rand(-10, 10); }).controller('StandardEqns', function($scope) { var x, _ref; $scope.selected = [0, 0]; _ref = (function() { var _i, _results; _results = []; for (x = _i = 0; _i <= 5; x = ++_i) { _results.push(rand(-10, 10)); } return _results; })(), $scope.x1 = _ref[0], $scope.y1 = _ref[1], $scope.z1 = _ref[2], $scope.x2 = _ref[3], $scope.y2 = _ref[4], $scope.z2 = _ref[5]; $scope.a1 = $scope.a2 = $scope.b1 = $scope.b2 = 0; $scope.$watch(function() { return [$scope.x1, $scope.y1, $scope.z1, $scope.x2, $scope.y2, $scope.z2]; }, function() { $scope.a1 = -$scope.x1 / $scope.y1; $scope.b1 = $scope.z1 / $scope.y1; $scope.a2 = -$scope.x2 / $scope.y2; return $scope.b2 = $scope.z2 / $scope.y2; }, true); $scope.changeSelected = function(robot, left) { return $scope.$apply(function() { if (left) { if ($scope.selected[robot] > 0) { return $scope.selected[robot] -= 1; } } else { if ($scope.selected[robot] < 2) { return $scope.selected[robot] += 1; } } }); }; return $scope.incrementSelected = function(robot, up) { return $scope.$apply(function() { var coefficient, idx, sel; sel = $scope.selected[robot]; idx = robot + 1; coefficient = (sel === 0 ? "x" : sel === 1 ? "y" : "z") + idx; if (up) { return $scope[coefficient] += 1; } else { return $scope[coefficient] -= 1; } }); }; }).controller('InterceptEqns', function($scope) { var x, _ref; _ref = (function() { var _i, _results; _results = []; for (x = _i = 0; _i <= 3; x = ++_i) { _results.push(rand(-10, 10)); } return _results; })(), $scope.a1 = _ref[0], $scope.b1 = _ref[1], $scope.a2 = _ref[2], $scope.b2 = _ref[3]; $scope.selected = [0, 0]; $scope.changeSelected = function(robot, left) { return $scope.$apply(function() { if (left) { if ($scope.selected[robot] > 0) { return $scope.selected[robot] -= 1; } } else { if ($scope.selected[robot] < 1) { return $scope.selected[robot] += 1; } } }); }; return $scope.incrementSelected = function(robot, up) { return $scope.$apply(function() { var coefficient, idx, sel; sel = $scope.selected[robot]; idx = robot + 1; coefficient = (sel === 0 ? "a" : sel === 1 ? "b" : void 0) + idx; if (up) { return $scope[coefficient] += 1; } else { return $scope[coefficient] -= 1; } }); }; }).controller('Graph', function($scope, $element) { var chartCfg, mkSeries; $scope.chartCfg = chartCfg = { grid: { markings: [ { linewidth: 1, yaxis: { from: 0, to: 0 }, color: "#8A8A8A" }, { linewidth: 1, xaxis: { from: 0, to: 0 }, color: "#8A8A8A" } ] }, xaxis: { min: -10, max: 10, tickSize: 2, tickDecimals: 0 }, yaxis: { min: -10, max: 10, tickSize: 2, tickDecimals: 0 }, colors: ["black", "red", "blue"] }; mkSeries = function(a1, b1, a2, b2, solnX, solnY) { var a, b, s, x; s = (function() { var _i, _len, _ref, _ref1, _results; _ref = [[a1, b1], [a2, b2]]; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { _ref1 = _ref[_i], a = _ref1[0], b = _ref1[1]; _results.push((function() { var _j, _len1, _ref2, _results1; _ref2 = [-10, 10]; _results1 = []; for (_j = 0, _len1 = _ref2.length; _j < _len1; _j++) { x = _ref2[_j]; _results1.push([x, a * x + b]); } return _results1; })()); } return _results; })(); s.unshift({ data: [[solnX, solnY]], points: { show: true } }); return s; }; $scope.serieses = mkSeries($scope.a1, $scope.b1, $scope.a2, $scope.b2, $scope.solnX, $scope.solnY); return $scope.$watch(function() { return [$scope.a1, $scope.b1, $scope.a2, $scope.b2, $scope.solnX, $scope.solnY]; }, function(_arg) { var a1, a2, b1, b2, solnX, solnY; a1 = _arg[0], b1 = _arg[1], a2 = _arg[2], b2 = _arg[3], solnX = _arg[4], solnY = _arg[5]; return $scope.serieses = mkSeries(a1, b1, a2, b2, solnX, solnY); }, true); }); Robot = (function() { var _i, _j, _len, _len1, _ref, _ref1; if (Robot != null) { return Robot; } else { rb = { mock: true }; _ref = ["connectRobot", "disconnectRobot", "getRobotIDList", "moveNB", "printMessage", "setColorRGB", "setJointSpeeds", "stop"]; for (_i = 0, _len = _ref.length; _i < _len; _i++) { x = _ref[_i]; rb[x] = function() {}; } _ref1 = ["scrollUp", "scrollDown", "buttonChanged"]; for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) { event = _ref1[_j]; rb[event] = { connect: function() {} }; } return rb; } })(); $(function() { var _i, _len; for (_i = 0, _len = robots.length; _i < _len; _i++) { x = robots[_i]; Robot.connectRobot(x); } Robot.setColorRGB(robots[0], 255, 0, 0); return Robot.setColorRGB(robots[1], 0, 0, 255); }); Robot.buttonChanged.connect(function(id, btn) { var activeTab; activeTab = $(".tab-pane.active"); return activeTab.scope().changeSelected(robots.indexOf(id), btn === 0); }); Robot.scrollDown.connect(function(id) { var activeTab; activeTab = $(".tab-pane.active"); return activeTab.scope().incrementSelected(robots.indexOf(id), false); }); Robot.scrollUp.connect(function(id) { var activeTab; activeTab = $(".tab-pane.active"); return activeTab.scope().incrementSelected(robots.indexOf(id), true); });
let nums = [1,2,3,4,5,6,7]; // let part = nums.slice(1,4); // let removed = nums.splice(2,2,45,12); // console.log(removed); // console.log(nums); const together = nums.join(""); console.log(together);
import React, {useState, useEffect} from 'react' import axios from 'axios' import Course from "./course" const ShowCourse =({_addCourse})=>{ const [courses, setCourses] = useState([]); const courseFeatures = ['ID', 'Name', 'Professor','LectureTime'] useEffect( ()=>{ if(courses != []){ axios.get('/courses').then(res=>{ setCourses(res.data); }) } },[]) return ( <div id = 'grouplist_showCourse'> <table> <thead> <tr> {courseFeatures.map( feature =>{ return <th>{feature}</th> })} </tr> </thead> <tbody> {courses.map(course =>{ return ( <Course course = {course} onClick = {()=>{_addCourse(course)}}/> ) })} </tbody> </table> </div> ) } export default ShowCourse
const { MongoClient } = require('mongodb'); const url = process.env.MONGODB_URI; const connect = dbName => { return MongoClient.connect(url).then((client, err) => { if (err) return err; const db = client.db(dbName); return db; }); }; module.exports = connect;
import React, {Component} from 'react'; import DialogContent from '@material-ui/core/DialogContent'; import FormGroup from '@material-ui/core/FormGroup'; import Checkbox from '@material-ui/core/Checkbox'; import FormControlLabel from '@material-ui/core/FormControlLabel'; import FormControl from '@material-ui/core/FormControl'; import Typography from '@material-ui/core/Typography'; import withStyles from "@material-ui/core/styles/withStyles"; import {styles} from "./styles-material-ui"; class MultipleAnswers extends Component { render() { const {classes, title} = this.props; return ( <div className={classes.root}> <Typography style={{fontSize: '20px', margin: '15px 25px 0 0'}}> {title} </Typography> <form className={classes.container}> <DialogContent className={classes.DialogContent}> {this.props.options.length > 0 && <div className={classes.root}> <FormControl component="fieldset" required className={classes.formControl}> <FormGroup onChange={(event) => this.props.changed(event, this.props.id, this.props.type, title)} value={this.props.value} > {this.props.options.map((option, id) => ( //this.props.options = ['', '', '', ''] <FormControlLabel key={id} control={<Checkbox value={option}/>} label={option} /> )) } </FormGroup> </FormControl> </div> } </DialogContent> </form> </div> ); } } export default withStyles(styles)(MultipleAnswers);
import React from "react"; import {Route, Switch} from "react-router-dom"; import FullList from "./fullList"; import Suspends from "./suspends"; import Maintenance from "./maintenance"; const Accounts = ({match}) => ( <Switch> <Route path={`${match.url}/fullList`} component={FullList}/> <Route path={`${match.url}/suspends`} component={Suspends}/> <Route path={`${match.url}/maintenance`} component={Maintenance}/> </Switch> ); export default Accounts;
const express = require('express'); const router = express.Router(); const mongoose = require('mongoose'); const users = require("./users.js"); const User = users.model; const validUser = users.valid; const animals = require("./animals.js") const Animal = animals.model_Animal; // Configure multer so that it will upload to '../front-end/public/images' const multer = require('multer') const upload = multer({ dest: '../front-end/public/images/', limits: { fileSize: 10000000 } }); //Schema for Favorites const favoriteSchema = new mongoose.Schema({ animal: { type: mongoose.Schema.ObjectId, ref: 'Animal' }, user: { type: mongoose.Schema.ObjectId, ref: 'User' }, }) // Model for Favorites const Favorite = mongoose.model('Favorite',favoriteSchema); //add favorite animal for user router.post('/:animalID', validUser, async (req, res) => { try { let animal = await Animal.findOne({_id: req.params.animalID}); if (!animal) { console.log(animals) res.sendStatus(404) return; } //checks to see if animal is already a user's favorite let otherFavorite = await Favorite.findOne({ animal: animal, user: req.user, }); if (!otherFavorite) { let favorite = new Favorite({ animal: animal, user: req.user, }); await favorite.save(); return res.sendStatus(200); } else { return res.sendStatus(403); } } catch (error) { console.log(error); res.sendStatus(500); } }); // get all favorite animals of a user router.get('/', validUser, async (req, res) => { try { let favorites = await Favorite.find({ user: req.user._id, }).sort({ created: -1 }).populate('animal'); return res.send(favorites); } catch (error) { console.log(error); res.sendStatus(500); } }); //remove animal from favorites of a user router.delete('/:animalID', validUser, async (req, res) => { try { let animal = await Animal.findOne({_id: req.params.animalID}); let favorite = await Favorite.findOne({ user: req.user, animal: animal}); if (!favorite) { res.send(404); return; } await favorite.delete(); return res.sendStatus(200); } catch (error) { console.log(error); res.sendStatus(500); } }); module.exports = { model: Favorite, routes: router, }
const chai = require('chai'); const JSONSerializer = require('@pascalcoin-sbx/data-spec').Serializer.JSON; chai.expect(); const expect = chai.expect; describe('Serializer.JSON', () => { it('can serialize something to a json string', () => { const obj = {a: 'b'}; const s = new JSONSerializer(); expect(s.serialize(obj)).to.be.equal('{"a":"b"}'); }); it('can serialize something to a pretty json string', () => { const obj = {a: 'b'}; const s = new JSONSerializer(true); expect(s.serialize(obj)).to.be.equal("{\n \"a\": \"b\"\n}"); }); it('can deserialize a json string', () => { expect(JSONSerializer.deserialize('{"a":"b"}').a).to.be.equal('b'); }); });
import React, { useState, useRef } from "react"; import { SearchComponent } from "../SearchComponent/SearchComponent"; import { ChatComponent } from "../ChatComponent.jsx/ChatComponent"; import { ChatList } from "../ChatList/ChatList"; import { db } from "../../db"; import { addNewMessage } from "./utils/utils"; import { Page, LelfSidePage, TopOfLelfSidePage, PositionRelative, ProfilePicture, StatusPosition, Header, Scroll, RightSidePage, } from "../style"; import { STATUS } from "../../constants/status"; export function MainComponent(props) { const [chats, setChats] = useState(db); const [currentChatIdx, setCurrentChatIdx] = useState(0); const chat = chats[currentChatIdx]; const photoUrl = require("../../profile/user.png"); const [value, setValue] = useState(""); const scrollContainerRef = useRef(); function onChatClick(currentChatIdx) { setCurrentChatIdx(currentChatIdx); } function handleClick(event) { setValue(event.target.value); } // get data from Chuck Norris API async function getResponse() { const response = await fetch("https://api.chucknorris.io/jokes/random"); if (!response.ok) { console.log( "Looks like there was a problem. Status Code: " + response.status ); return; } const json = await response.json(); return json; } function sendMessage(event) { event.preventDefault(); if (value === "") return; // add new message to chat messages const chatWithNewMessage = addNewMessage( chats, currentChatIdx, value, false, scrollContainerRef.current ); setChats(chatWithNewMessage); setValue(""); // add answer to chat array with generated value from Chuck Norris API setTimeout(async () => { const json = await getResponse(); const chatWithNewAnswer = addNewMessage( chats, currentChatIdx, json.value, true, scrollContainerRef.current ); setChats(chatWithNewAnswer); }, 500); } return ( <> <Page> <LelfSidePage> <TopOfLelfSidePage> <PositionRelative> <ProfilePicture src={photoUrl} alt="Profile" /> <StatusPosition color={STATUS.online.color}> {STATUS.online.symbol} </StatusPosition> </PositionRelative> <SearchComponent /> </TopOfLelfSidePage> <Header>Chats</Header> <Scroll> <ChatList chats={chats} onChatClick={onChatClick} /> </Scroll> </LelfSidePage> <RightSidePage> <ChatComponent chat={chat} value={value} handleClick={handleClick} handleSubmit={sendMessage} scrollContainerRef={scrollContainerRef} /> </RightSidePage> </Page> </> ); }
import React from 'react' import './App.css'; import Landing from './components/pages/Landing'; import Cart from './components/pages/Cart'; import Checkout from './components/pages/Checkout'; import { UserProvider } from './UserContext'; import { BrowserRouter as Router, Switch, Route } from 'react-router-dom'; import ProductsArea from './components/pages/ProductsArea'; import UserPage from './components/pages/UserPage'; import Login from './components/utils/Login'; import ChatCommunity from './components/pages/ChatCommunity'; import MainAdmin from './components/admin2/pages/MainAdmin'; import AdminUser from './components/admin2/pages/AdminUser'; import AdminProducts from './components/admin2/pages/AdminProducts'; import AdminAddProducts from './components/admin2/pages/AdminAddProducts'; import AdminPurchases from './components/admin2/pages/AdminPurchases'; import PrivateRoute from "./components/utils/PrivateRoute"; function App() { return ( <div className="App"> <div className="first"></div> <div className="second"> <Router> <UserProvider> <Switch> <PrivateRoute path='/admin' component={MainAdmin} exact/> {/* <Route path='/admin'> <MainAdmin/> </Route> */} <Route path='/cart'> <Cart /> </Route> <Route path='/checkout'> <Checkout /> </Route> <Route path='/chat'> <ChatCommunity /> </Route> <Route path='/addadminproduct'> <AdminAddProducts/> </Route> <Route path='/adminproducts'> <AdminProducts/> </Route> <Route path='/users'> <AdminUser /> </Route> <Route path='/purchases'> <AdminPurchases/> </Route> <Route path='/product'> <ProductsArea/> </Route> <Route path='/signup'> <UserPage /> </Route> <Route path='/login'> <Login /> </Route> <Route path='/'> <Landing /> </Route> </Switch> </UserProvider> </Router> </div> </div> ); } export default App;
/** * */ import React from 'react'; import Carousel from './Carousel'; class PartWidget extends React.Component { constructor(props) { super(props); } render(){ const { name, notes, price, category, subcategory, images } = this.props; var settings = { dots: true }; return ( <div className="part"> <form> <div className="form-group"> <label htmlFor="inputName">name</label> <input type="text" className="form-control" id="inputName" aria-describedby="nameHelp" placeholder="Enter item name"/> <small id="nameHelp" className="form-text text-muted">a short name of the item</small> </div> <div className="form-group"> <label htmlFor="inputPrice">price</label> <input type="number" className="form-control" id="inputPrice" aria-describedby="priceHelp" placeholder="Enter item price"/> <small id="priceHelp" className="form-text text-muted">the price of the item</small> </div> <div className="form-group"> <label htmlFor="selectCategory">category</label> <select className="form-control" id="selectCategory"> <option>1</option> <option>2</option> </select> </div> <div className="form-group"> <label htmlFor="selectSubcategory">subcategory</label> <select className="form-control" id="selectSubcategory"> <option>1</option> <option>2</option> </select> </div> <div className="form-group"> <label htmlFor="textNotes">notes</label> <textarea className="form-control" id="textNotes" rows="3"></textarea> </div> <div className="form-group"> <input type="file" accept="image/*" multiple="true" className="form-control"></input> <Carousel auto={false}/> </div> <div className="form-row align-items-center"> <div className="col-auto"> <button type="submit" className="btn btn-primary mb-2">Delete</button> </div> <div className="col-auto"> <button type="submit" className="btn btn-primary mb-2">Submit</button> </div> </div> </form> </div> ) } }; export default PartWidget;
var p5Canvas; var myName; function setup() { p5Canvas = createCanvas(800, 600); p5Canvas.parent("#p5-canvas"); myName = select("#my-name"); myName.html("Teacher"); } /* full reference: https://p5js.org/reference/ line: https://p5js.org/reference/#/p5/line rectangle: https://p5js.org/reference/#/p5/rect ellipse: https://p5js.org/reference/#/p5/ellipse arc: https://p5js.org/reference/#/p5/arc background color: https://p5js.org/reference/#/p5/background shape color: https://p5js.org/reference/#/p5/fill line color, weight, etc: https://p5js.org/reference/#/p5/stroke */ // Write all your code inside the draw() function below! function draw() { background(0, 255, 0); // head fill(255, 204, 0); ellipse(width / 2, height / 2 - 100, 200, 200); // eyes fill(0, 100, 100); ellipse(width / 2 - 40, height / 2 - 110, 20, 20); ellipse(width / 2 + 40, height / 2 - 110, 20, 20); // mouth arc(width / 2, height / 2 - 60, 100, 60, radians(0), radians(180)); // body line(width / 2, height / 2, width / 2, height / 2 + 180); // arms line(width / 2, height / 2 + 60, width / 2 - 80, height / 2 - 20); line(width / 2, height / 2 + 60, width / 2 + 80, height / 2 - 20); // legs line(width / 2, height / 2 + 180, width / 2 - 80, height / 2 + 220); line(width / 2, height / 2 + 180, width / 2 + 80, height / 2 + 220); }
/** * Copyright © INOVUA TRADING. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import { useMemo, useState, useCallback, } from 'react'; import useProperty from '@inovua/reactdatagrid-community/hooks/useProperty'; import batchUpdate from '@inovua/reactdatagrid-community/utils/batchUpdate'; import clamp from '@inovua/reactdatagrid-community/utils/clamp'; import useActiveCell from './useActiveCell'; const getFirstSelectedCell = (cellSelection) => { return cellSelection.sort((cell1, cell2) => { if (cell1[0] < cell2[0]) { return -1; } else if (cell1[0] > cell2[0]) { return 1; } return cell1[1] < cell2[1] ? -1 : 1; })[0]; }; export const useCellSelection = (props, { rowSelectionEnabled, hasRowNavigation, listenOnCellEnter, }, computedPropsRef) => { const [cellSelection, setCellSelection] = useProperty(props, 'cellSelection'); let { computedActiveCell, getCellSelectionIdKey, getCellSelectionBetween, setActiveCell, getCellSelectionKey, incrementActiveCell, } = useActiveCell(props, computedPropsRef); const cellSelectionEnabled = !rowSelectionEnabled ? !!cellSelection : false; if (rowSelectionEnabled || hasRowNavigation) { computedActiveCell = undefined; } let cellNavigationEnabled = computedActiveCell !== undefined; if (cellSelection) { cellNavigationEnabled = props.enableKeyboardNavigation !== false && !hasRowNavigation ? true : computedActiveCell !== undefined || !!cellSelection; } if (props.enableKeyboardNavigation === false) { cellNavigationEnabled = false; } const cellMultiSelectionEnabled = cellSelectionEnabled && props.multiSelect !== false; const onCellEnter = useMemo(() => listenOnCellEnter ? (event, { columnIndex, rowIndex }) => { const { current: computedProps } = computedPropsRef; if (!computedProps) { return; } const data = computedProps.getItemAt(rowIndex); if (!data || data.__group) { return; } const col = computedProps.getColumnBy(columnIndex); if (col && col.cellSelectable === false) { return; } const groupBy = computedProps.computedGroupBy; const minCol = groupBy ? groupBy.length : 0; if (columnIndex < minCol) { return; } const range = computedProps.getCellSelectionBetween(computedProps.selectionFixedCell || computedProps.computedActiveCell || computedProps.lastSelectedCell, [rowIndex, columnIndex]); const queue = batchUpdate(); queue(() => { computedProps.setCellSelection(range); computedProps.setLastCellInRange(Object.keys(range).pop() || ''); }); const direction = computedProps.cellDragStartRowIndex != null ? rowIndex - computedProps.cellDragStartRowIndex : rowIndex; const sign = direction < 0 ? -1 : direction > 0 ? 1 : 0; const scrollToRowIndex = clamp(rowIndex + sign, 0, computedProps.count - 1); let visible = computedProps.isCellVisible({ columnIndex, rowIndex: scrollToRowIndex, }); if (visible !== true) { visible = visible; const left = visible.leftDiff < 0; const top = visible.topDiff < 0; computedProps.scrollToCell({ columnIndex, rowIndex: scrollToRowIndex }, { top, left, }); } queue.commit(); } : null, [listenOnCellEnter]); const getContinuousSelectedRangeFor = (selectionMap, cell) => { if (!cell) { return []; } selectionMap = selectionMap || {}; let [row, col] = cell; let key = getCellSelectionKey(row, col); const range = []; while (selectionMap[key]) { range.push([row, col]); key = getCellSelectionKey(row - 1, col - 1); if (selectionMap[key]) { row -= 1; col -= 1; continue; } if (!selectionMap[key]) { key = getCellSelectionKey(row - 1, col); } if (selectionMap[key]) { row -= 1; continue; } if (!selectionMap[key]) { key = getCellSelectionKey(row, col - 1); col -= 1; } } return range; }; const toggleActiveCellSelection = useCallback((fakeEvent) => { const { current: computedProps } = computedPropsRef; if (!computedProps) { return; } const computedActiveCell = computedProps.computedActiveCell; if (!computedActiveCell) { return; } const [rowIndex, columnIndex] = computedActiveCell; const column = computedProps.getColumnBy(columnIndex); if (column && column.cellSelectable === false) { return; } const selected = isCellSelected(rowIndex, columnIndex); const event = fakeEvent || { ctrlKey: selected }; computedProps.onCellClickAction(event, { rowIndex, columnIndex }); }, []); const isCellSelected = useCallback((row, col) => { if (row && typeof row === 'object') { col = row.columnIndex; row = row.rowIndex; } const { current: computedProps } = computedPropsRef; if (!computedProps) { return; } if (computedProps.computedCellSelection) { const key = computedProps.getCellSelectionKey(row, col); return !!computedProps.computedCellSelection[key]; } return false; }, []); const [cellDragStartRowIndex, setCellDragStartRowIndex] = useState(null); const onCellSelectionDraggerMouseDown = useMemo(() => { if (cellMultiSelectionEnabled && cellSelection) { let onCellSelectionDraggerMouseDown = (event, { columnIndex, rowIndex }, selectionFixedCell) => { const { current: computedProps } = computedPropsRef; if (!computedProps) { return; } const column = computedProps.getColumnBy(columnIndex); if (column && column.cellSelectable === false) { return; } if (!selectionFixedCell) { const currentCell = [rowIndex, columnIndex]; const groupBy = computedProps.computedGroupBy; const hasGroupBy = groupBy && groupBy.length; const currentRange = !hasGroupBy ? getContinuousSelectedRangeFor(computedProps.computedCellSelection, currentCell) : []; selectionFixedCell = !hasGroupBy ? getFirstSelectedCell(currentRange.length ? currentRange : [currentCell]) : // since in groupBy we are not guaranteed to have continous rows, for how // we leave the activeCell as the selection topmost cell computedProps.computedActiveCell || computedProps.lastSelectedCell; } // this.update({ // selectionFixedCell, // listenOnCellEnter: true, // cellDragStartRowIndex: rowIndex, // }); const fn = () => { computedProps.setListenOnCellEnter(false, fn); setCellDragStartRowIndex(null); computedProps.setSelectionFixedCell(null); }; const queue = batchUpdate(); queue(() => { setCellDragStartRowIndex(rowIndex); if (selectionFixedCell === undefined) { selectionFixedCell = null; } computedProps.setSelectionFixedCell(selectionFixedCell); computedProps.setListenOnCellEnter(true, fn); }); queue.commit(); }; return onCellSelectionDraggerMouseDown; } return null; }, [cellMultiSelectionEnabled, cellSelection]); return { onCellEnter, toggleActiveCellSelection, cellDragStartRowIndex, setCellDragStartRowIndex, onCellSelectionDraggerMouseDown, // getContinuousSelectedRangeFor, getCellSelectionBetween, computedActiveCell, incrementActiveCell, getCellSelectionIdKey, setActiveCell, getCellSelectionKey, cellSelectionEnabled, cellNavigationEnabled, cellMultiSelectionEnabled, computedCellSelection: cellSelection, setCellSelection, }; };
/* */ var wavesurfer = Object.create(WaveSurfer); //$(function(){ document.addEventListener('DOMContentLoaded', function(){ var options = { container : '#waveform', waveColor : 'black', loopSelection : false, cursorWidth : 0 }; // Init wavesurfer wavesurfer.init(options); // Init Microphone plugin var microphone = Object.create(WaveSurfer.Microphone); microphone.init({ wavesurfer: wavesurfer }); microphone.start(); }); //});
export default function getPosts(beforePostId) { let url = '/v2/posts?popular=true'; if (beforePostId) { url += `&before=${beforePostId}`; } return fetch(url, {}) .then(res => res.json()) .catch(() => []); }
import React from "react" import Ascending from "../components/asc" import Descending from "../components/desc" var fielter = "" var element_data = "" export default class PriceFielter extends React.Component { constructor(props){ super(props); this.state={ order:'asc' } } abc = (data) =>{ element_data = data.target fielter = data.target.value this.setState({ order:fielter }) } render(){ // if(this.state.order === 'asc'){ // //deleteElement() // return( // <div> // <div> // <div name ="select"> // <select onChange={this.abc} name="helloo"> // <option name = "asce" value="asc" selected>Ascending Order</option> // <option name = "desc" value="desc">Descending Order</option> // </select> // </div> // <Ascending/> // </div> // {/* <div> // <select onChange={this.abc}> // <option name = "asce" value="ASC">Ascending Order</option> // <option name = "desc" value="DESC">Descending Order</option> // </select> // </div> */} // </div> // ) // } // else if(this.state.order === 'desc') { // return( // <div> // <div name ="select"> // <select onChange={this.abc} name="helloo"> // <option name = "asce" value="asc">Ascending Order</option> // <option name = "desc" value="desc" selected>Descending Order</option> // </select> // </div> // <Descending/> // </div> // ) // } return( <div> <div> <select onChange={this.abc}> <option name = "asce" value="asc">Ascending Order</option> <option name = "desc" value="desc" >Descending Order</option> </select> </div> {this.state.order =='asc'?<Ascending/>:<Descending/>} </div>) } }
import React from 'react'; import { Link } from 'react-router-dom'; import './Navbar.css'; const Navbar = (props) => { const {cart}=props; const {user}=props; const {setuser}=props; const {setcart}=props; const signoutHandler=()=>{ setuser(null); setcart({cartItems: [],shippingAddress: {}}); localStorage.removeItem('user'); localStorage.removeItem('cart'); }; return ( <div className="pos-f-t"> <div className="collapse" id="navbarToggleExternalContent"> <div className="bg-dark p-4"> <ul className="navbar-nav me-auto mb-2 mb-lg-0"> <li className="nav-item"> <Link className="nav-link active" aria-current="page" to="/cart"> Cart{ (cart.cartItems.length>0)&&<span className="badge itemcount">{cart.cartItems.length}</span> } </Link> </li> <li className="nav-item" style={{marginRight: '1em'}}> { user?( <div className="dropdown"> <Link className="nav-link active" to='#'>{user.name} {' '}<i className="fa fa-caret-down"></i></Link> <div className="dropdown-content"> <div style={{padding: '0.5em'}}><Link className="signout" to="#signout" onClick={signoutHandler}>Sign-Out?</Link></div> <div style={{padding: '0.5em'}}><Link className="signout" to="/orderhistory">Order History</Link></div> <div style={{padding: '0.5em'}}><Link className="signout" to="/profile">User Profile</Link></div> </div> </div> ) :(<Link className="nav-link active" to="/signin">Sign In</Link>) } </li> </ul> </div> </div> <nav className="navbar navbar-expand-lg navbar-dark bg-dark"> <div className="container-fluid"> <Link className="navbar-brand m-2" to="/">Amazon</Link> <button className="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarToggleExternalContent" aria-controls="navbarToggleExternalContent" aria-expanded="false" aria-label="Toggle navigation"> <span className="navbar-toggler-icon"></span> </button> <div className="collapse navbar-collapse prop" id="navbarSupportedContent"> <ul className="navbar-nav me-auto mb-2 mb-lg-0"> <li className="nav-item"> <Link className="nav-link active" aria-current="page" to="/cart"> Cart{ (cart.cartItems.length>0)&&<span className="badge itemcount">{cart.cartItems.length}</span> } </Link> </li> <li className="nav-item" style={{marginRight: '1em'}}> { user?( <div className="dropdown"> <Link className="nav-link active" to='#'>{user.name} {' '}<i className="fa fa-caret-down"></i></Link> <div className="dropdown-content"> <div style={{padding: '0.5em'}}><Link className="signout" to="#signout" onClick={signoutHandler}>Sign-Out?</Link></div> <div style={{padding: '0.5em'}}><Link className="signout" to="/orderhistory">Order History</Link></div> <div style={{padding: '0.5em'}}><Link className="signout" to="/profile">User Profile</Link></div> </div> </div> ) :(<Link className="nav-link active" to="/signin">Sign In</Link>) } </li> </ul> </div> </div> </nav> </div> ); } export default Navbar;
import api from "../../services/api"; import { call, put } from "redux-saga/effects"; import { Creators as ProductDetails } from "../ducks/productDetails"; export function* getProductDetails(action) { try { const response = yield call(api.get, `/products/${action.payload.id}`); yield put(ProductDetails.getProductDetailsSuccess(response.data)); } catch (err) { console.log("não foi possivel listar os detalhes do produto."); } }
import React from 'react' import {useStaticQuery, graphql, Link} from 'gatsby' import uuid from 'uuid' import Layout from '../components/layout' import blogStyles from '../styles/pages/blog.module.scss' const BlogPage = () => { const data = useStaticQuery(graphql` query { allMarkdownRemark( sort: { fields: [frontmatter___date] order: DESC } ) { edges { node { frontmatter { title date(formatString: "DD MMMM, YYYY") description } fields { slug } } } } } `) return ( <Layout> <main className={blogStyles.main}> <div className={blogStyles.container}> <h1>Blog</h1> <ul > {data.allMarkdownRemark.edges.map(edge => ( <li key={uuid()} className={blogStyles.blog__item}> <Link to={`/blog/${edge.node.fields.slug}`}> <h2>{edge.node.frontmatter.title}</h2> <p>{edge.node.frontmatter.description}</p> <span>{edge.node.frontmatter.date}</span> </Link> </li> ))} </ul> </div> </main> </Layout> ) } export default BlogPage
import styled from "styled-components"; export const TabsWrapper = styled.div` display: inline-block; .header { width: 273px; height: 299px; display: flex; justify-content: center; align-items: center !important; padding-bottom: 50px; margin-top: 45px; border: 2px solid #EA7C69; .btn{ color: #EA7C69 !important; } } .card-container { height: 300px; width: 300px; } .card-wrapper { width: 221px; height: 299px; display: flex; flex-direction: column; text-align: center !important; border: 1px solid #323441; } .card-top { width: 100%; height: 2%; } .task-holder { width: 100%; height: 400px; padding: 10px 10px; display: flex; flex-direction: column; position: relative; } .card-header { /* margin-top: 10px; margin-bottom: 10px; */ margin: 0 auto; width: 80px; height: 30px; padding: 1px 1px !important; text-align: center; color: white; font-weight: bold; } .buFlex{ display: flex; } .task-container { height: 600px; width: 100%; display: flex; justify-content: center; flex-wrap: wrap; padding-top: 40px ; } .food{ width: 143px; height: 140px; object-fit: cover; margin: 0 auto; } .margin { right: 34%; background-color: #50343A; width: 100%; height: 50px; left: 1px; bottom: 0; i { margin: 15px; color: #9D5851 !important; } } @media screen and (max-width: 600px){ .header{ width: 200px; margin-left: 40px; } .buFlex{ display: flex; flex-direction: column; } } /* .task-container{ width: 100%; height: 400px; } li{ display: inline-block; list-style-type: none; background-color: yellow; margin: 20px; padding: 10px; } */ `;
import Background from './Background'; export default class CityWatch extends Background { constructor() { super('cityWatch'); } }
/* * @Descripttion: * @Author: jiegiser * @Date: 2020-02-10 16:16:06 * @LastEditors : jiegiser * @LastEditTime : 2020-02-10 16:17:11 */ const redis = require('redis') const { REDIS_CONF } = require('../config/db') // 创建客户端 const redisClient = redis.createClient(REDIS_CONF.port, REDIS_CONF.host) redisClient.on('error', err => { console.error(err) }) module.exports = redisClient
import { describe, it } from 'mocha'; import chai, { expect } from 'chai'; import chaiHttp from 'chai-http'; const mongoose = require('mongoose'); // import connection from '../src/utils/db'; import app from '../src/server'; chai.use(chaiHttp); describe('Authentication Routes', () => { before(function (done) { const uri = `mongodb+srv://${process.env.TEST_DB_USER}:${process.env.TEST_DB_PASS}@${process.env.TEST_DB_SERVER}/${process.env.TEST_DB_NAME}`; mongoose.connect( uri, { useNewUrlParser: true, useUnifiedTopology: true }, function () { mongoose.connection.db.dropDatabase(function () { console.log('database dropped'); done(); }); } ); }); describe('Handles sign up endpoint', () => { it('should fail if validation fails', (done) => { chai .request(app) .post('/auth/signup') .send({ username: 'popo', email: 'aigbefoephraim@yahoo.com', password: 'password' }) .end((err, res) => { expect(res.status).to.equal(422); expect(res.body.message).to.equal('validation failed'); if (err) return done(err); done(); }); }); it('should create a new user', (done) => { chai .request(app) .post('/auth/signup') .send({ name: 'Tester Tester', username: 'popo', email: 'aigbefoephraim@yahoo.com', password: 'password' }) .end((err, res) => { expect(res.status).to.equal(201); expect(res.body.message).to.equal('Sign up successful'); if (err) return done(err); done(); }); }); it('should fail if user exists', (done) => { chai .request(app) .post('/auth/signup') .send({ name: 'Tester Tester', username: 'popo', email: 'aigbefoephraim@yahoo.com', password: 'password' }) .end((err, res) => { expect(res.status).to.equal(400); expect(res.body.message).to.equal('user exists already'); if (err) return done(err); done(); }); }); }); describe('Handles Login endpoint', () => { it('should fail if validation fails', (done) => { chai .request(app) .post('/auth/login') .send({ username: 'popo' }) .end((err, res) => { expect(res.status).to.equal(422); expect(res.body.message).to.equal('validation failed'); if (err) return done(err); done(); }); }); it('should fail if user does not exist', (done) => { chai .request(app) .post('/auth/login') .send({ username: 'popo1', password: 'password' }) .end((err, res) => { expect(res.status).to.equal(404); expect(res.body.message).to.equal('user does not exist'); if (err) return done(err); done(); }); }); it('should fail if password is wrong', (done) => { chai .request(app) .post('/auth/login') .send({ username: 'popo', password: 'password1' }) .end((err, res) => { expect(res.status).to.equal(400); expect(res.body.message).to.equal('incorrect login details'); if (err) return done(err); done(); }); }); it('should login successfully', (done) => { chai .request(app) .post('/auth/login') .send({ username: 'popo', password: 'password' }) .end((err, res) => { expect(res.status).to.equal(200); expect(res.body.message).to.equal('login successful'); if (err) return done(err); done(); }); }); }); describe('Handles forgot password endpoint', () => { it('should fail if validation fails', (done) => { chai .request(app) .post('/auth/forgotPassword') .end((err, res) => { expect(res.status).to.equal(422); expect(res.body.message).to.equal('validation failed'); if (err) return done(err); done(); }); }); it('should fail if user does not exist', (done) => { chai .request(app) .post('/auth/forgotPassword') .send({ username: 'popo1' }) .end((err, res) => { expect(res.status).to.equal(404); expect(res.body.message).to.equal('user does not exist'); if (err) return done(err); done(); }); }); it('should fail if token does not exist', (done) => { chai .request(app) .post('/auth/changePassword') .send({ username: 'popo', token: '111111', newPassword: 'secret' }) .end((err, res) => { expect(res.status).to.equal(404); expect(res.body.message).to.equal('user does not have an otp'); if (err) return done(err); done(); }); }); it('should send token to email', (done) => { chai .request(app) .post('/auth/forgotPassword') .send({ username: 'popo' }) .end((err, res) => { expect(res.status).to.equal(200); expect(res.body.message).to.equal('email sent'); if (err) return done(err); done(); }); }); }); describe('Handles change password endpoint', () => { it('should fail if validation fails', (done) => { chai .request(app) .post('/auth/changePassword') .send({ username: 'popo' }) .end((err, res) => { expect(res.status).to.equal(422); expect(res.body.message).to.equal('validation failed'); if (err) return done(err); done(); }); }); it('should fail if user does not exist', (done) => { chai .request(app) .post('/auth/changePassword') .send({ username: 'popo1', token: '111111', newPassword: 'secret' }) .end((err, res) => { expect(res.status).to.equal(404); expect(res.body.message).to.equal('user does not exist'); if (err) return done(err); done(); }); }); it('should fail if token does not match', (done) => { chai .request(app) .post('/auth/changePassword') .send({ username: 'popo', token: '111112', newPassword: 'secret' }) .end((err, res) => { expect(res.status).to.equal(400); expect(res.body.message).to.equal('OTP does not match'); if (err) return done(err); done(); }); }); it('should succeed', (done) => { chai .request(app) .post('/auth/changePassword') .send({ username: 'popo', token: '111111', newPassword: 'secret' }) .end((err, res) => { expect(res.status).to.equal(200); expect(res.body.message).to.equal('password changed successfully'); if (err) return done(err); done(); }); }); }); });
function validarDatos() { var descripcion = document.getElementById("txtDescripcion").value; var modulo = document.getElementById("cboModulos").value; if (descripcion.trim() == "") { alert("La descripcion no debe estar vacio"); return; } else if (descripcion.length < 3 ) { alert("La descripcion debe contener al menos 3 caracteres"); return; } if(modulo == 0){ alert("Debe seleccionar el modulo"); return; } var form = document.getElementById("frmDatos"); form.submit(); }
process.env.TZ = "Asia/Shanghai"; const log4js = require('log4js'); const cluster = require('cluster'); const numCPUs = require('os').cpus().length; /** ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- **/ if (cluster.isMaster) { log4js.configure({ appenders: { file: {type: 'dateFile', filename: 'log/server.log', daysToKeep: 7, keepFileExt: true, layout: { type: 'pattern', pattern: '%d{yyyy-MM-dd hh:mm:ss} [%p] %X{real_name} - %m' } }, server: {type: 'tcp-server', host: '0.0.0.0', port: 5000} }, categories: { default: {appenders: ['file'], level: 'debug'} } }); for (i = 0; i < numCPUs; i++) { cluster.fork(); } }
import { ACTIONS } from './actionCreator' export const INIT_STATE = { name: '', userId: null, chatList: [ ], messages: [ ], selectedChatId: null, contacts: [], loading: false, waitingForMessages: false } // `chat/start/user/{userId}` export function reducer(state, action) { return (ACTION_HANDLERS[action.type] || (() => state))(state, action.payload) } const ACTION_HANDLERS = { [ACTIONS.CHAT_SELECTED]: handleChatSelected, [ACTIONS.MESSAGE_SUBMITTED]: handleMessageSubmitted, [ACTIONS.CHAT_CLOSED]: handleChatClosed, [ACTIONS.USER_SIGNED_IN]: handleSignIn, [ACTIONS.CONTACTS_LOADED]: handleContactsLoaded, [ACTIONS.CHATS_LOADED]: handleChatsLoaded, [ACTIONS.INIT_DATA_LOADED]: handleInitDataLoaded, [ACTIONS.CHAT_CREATED]: handleChatCreated, [ACTIONS.CHAT_MESSAGES_LOADED]: handleLoadChatMessages, [ACTIONS.CHAT_MESSAGES_PREPENDED]: handleChatMessagePrepended, [ACTIONS.NEW_USER_REGISTERED]: handleNewUserRegistered, [ACTIONS.NEW_MESSAGE_RECEIVED]: handleNewMessageReceived, [ACTIONS.LOADING]: handleLoading, [ACTIONS.WAITING_FOR_MESSAGE]: handleWaitingForMessage, } function handleChatSelected(state, payload) { const selectedChatIndex = state.chatList.findIndex(x => x.id === payload); return { ...state, selectedChatId: payload, chatList: [ ...state.chatList.slice(0, selectedChatIndex), { ...state.chatList[selectedChatIndex], unreadMessageCount: 0 }, ...state.chatList.slice(selectedChatIndex + 1) ] } } function handleMessageSubmitted(state, payload) { return { ...state, messages: [ ...state.messages, { chatId: state.selectedChatId, id: Math.random().toString(), text: payload, userId: state.userId } ] } } function handleChatClosed(state) { return { ...state, selectedChatId: null } } function handleSignIn(state, payload) { return { ...state, name: payload.name, userId: payload.id }; } function handleContactsLoaded(state, payload) { return { ...state, contacts: payload } } function handleChatsLoaded(state, payload) { return { ...state, chatList: payload } } function handleInitDataLoaded(state, payload) { const messages = [...state.messages]; payload.chats.forEach(chat => { if (chat.lastMessage) { messages.push({ chatId: chat.id, id: chat.lastMessage.id, text: chat.lastMessage.content, userId: chat.lastMessage.userId, time: chat.lastMessage.date }); } }) return { ...state, chatList: payload.chats.map(item => ( { ...item, avatar: '/avatar.png', time: item.lastMessage ? item.lastMessage.date : null } )), contacts: payload.contacts.filter(item => item.id !== state.userId), messages, loading: false } } function handleChatCreated(state, { chatId, name }) { let newChatList = state.chatList; if (!state.chatList.some(x => x.id === chatId)) { const newChat = { time: '', unreadMessageCount: 0, avatar: '/avatar.png', id: chatId, name }; newChatList = [newChat, ...state.chatList] } return { ...state, selectedChatId: chatId, chatList: newChatList } } function handleLoadChatMessages(state, { chatId, data }) { const newChatList = [...state.chatList] const index = state.chatList.findIndex(x => x.id === chatId); newChatList.splice( index, 1, { ...state.chatList[index], unreadMessageCount: 0 } ) return { ...state, messages: [ ...state.messages.filter(x => x.chatId !== chatId), ...(data.messages || []).map(msg => ({ chatId, id: msg.id, text: msg.content, userId: msg.userId, time: msg.date })) ], selectedChatId: chatId, chatList: newChatList, waitingForMessages: false } } function handleChatMessagePrepended(state, { chatId, data }) { return { ...state, messages: [ ...data.messages.map(msg => ({ chatId, id: msg.id, text: msg.content, userId: msg.userId })), ...state.messages ], selectedChatId: chatId } } function handleNewUserRegistered(state, user) { if (state.contacts.some(x => x.id === user.id)) { return state; } return { ...state, contacts: [ ...state.contacts, { id: user.id, title: user.name } ] } } function handleNewMessageReceived(state, { chatId, message }) { const newChatList = [...state.chatList]; if (!state.chatList.some(x => x.id === chatId)) { const newChat = { time: message.date, unreadMessageCount: 1, avatar: '/avatar.png', id: chatId, name: state.contacts.find(x => x.id === message.userId).title } newChatList.push(newChat); } else if (state.selectedChatId !== chatId) { const index = state.chatList.findIndex(x => x.id === chatId); newChatList.splice( index, 1, { ...state.chatList[index], unreadMessageCount: state.chatList[index].unreadMessageCount + 1, time: message.date } ) } const newMessages = [ ...state.messages, { chatId, id: message.id, text: message.content, userId: message.userId, time: message.date } ] return { ...state, messages: newMessages, chatList: newChatList } } function handleLoading(state) { return { ...state, loading: true }; } function handleWaitingForMessage(state) { return { ...state, waitingForMessages: true } }
import firebase from "./firebase-config"; import "firebase/messaging"; export const askForPermissioToReceiveNotifications = async () => { try { const messaging = firebase.messaging(); await messaging.requestPermission(); } catch (error) { console.error(error); } };
import React, { Component } from 'react'; class Button extends Component { state = { } componentWillMount() { this.setState({ value: this.props.value, onClick: this.props.onclick }) } render() { return ( <button style={{ width: "10vw", borderRadius: "5px", color: "white", backgroundColor: "darkgray", outline: "0", }} onClick={(e) => { this.state.onClick(this.state.value) }} > {this.state.value} </button> ); } } export default Button;
import { useContext } from "react"; import { DatosAmigosContext } from "../context/DatosAmigosContext"; export const Formulario = () => { const { setNombre, setApellido, setValoracion, nombre, apellido, valoracion, } = useContext(DatosAmigosContext); return ( <> <div className=" col-3"> <label className="form-text" htmlFor="nombre"> Nombre </label> <input id="nombre" className="form-control" value={nombre} onChange={(e) => setNombre(e.target.value)} /> </div> <div className="col-3" s> <label className="form-text" htmlFor="apellido"> Apellido </label> <input className="form-control" id="apellido" value={apellido} onChange={(e) => setApellido(e.target.value)} /> </div> <div className="col-3" s> <label className="form-text" htmlFor="valoración"> Valoración </label> <select className="form-control" id="valoración" value={valoracion} onChange={(e) => setValoracion(e.target.value)} > <option value="0">0</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> </select> </div> </> ); };
var express = require('express'); var router = express.Router(); var mysql = require('mysql'); var creds = require('../app'); var empid; router.get('/', function(req, res, next) { if(req.session.emp) { res.render('addVehicles',{title: 'Add Vehicles', value: 0}); } else { res.redirect('/login'); } }); router.post('/', function(req, res, next) { if(req.session.emp) { empid = req.session.id; var con = mysql.createConnection({ host: 'localhost', user: creds.creds[0].username, password: creds.creds[0].password, database: 'VEHICLE_RENTAL' }); con.connect(function(err) { if (err) throw err; console.log("Connected"); var sql = "SELECT * FROM VehicleDetails WHERE Plate_No = '" + req.body.plno + "';"; console.log(sql); con.query(sql, function(err, result) { if(err) throw err; console.log(result); console.log(result.length); if(result.length == 0) { sql = "INSERT INTO Vehicles VALUES ('" + req.body.modname + "', '" + req.body.compname + "', '" + req.body.vtype + "', '" + req.body.type + "', " + req.body.seats + ", 1, " + req.body.cost + ") ON DUPLICATE KEY UPDATE Units = Units + 1;"; console.log(sql); con.query(sql, function(err, result) { if(err) throw err; sql = "INSERT INTO VehicleDetails VALUES ('" + req.body.plno + "', '" + req.body.modname + "', '" + req.body.color + "', (SELECT G_ID FROM Employee WHERE User_ID = '" + empid + "'), 0);"; console.log(sql); con.query(sql, function(err, result) { if(err) throw err; console.log("Vehicle added"); // Show as SUCCESS // res.redirect('/homeEmp'); res.render('addVehicles',{title: 'Add Vehicles', value: 1}); }); }); } else { console.log("Duplicate"); res.render('addVehicles',{title: 'Add Vehicles', value: 2}); // Show as FAILED } }); }); } else { res.redirect('/login'); } }); module.exports = router;
import React from 'react'; import { StyleSheet, Text, View, TextInput } from 'react-native'; import Clock from './Clock' export default class App extends React.Component { render() { return ( <View style={styles.container}> <View style={{flex:1, backgroundColor: 'purple', alignItems: 'center', justifyContent: 'center'}} > <Clock/> </View> <View style={{flex:2, backgroundColor: 'white', alignItems: 'center', justifyContent: 'center'}}> <Clock/> <View style={{backgroundColor: 'lightgray', justifyContent:'center', height: 32, width: 122, alignItems:'center'}}> <TextInput placeholder="he" style={{height: 30, width: 120,backgroundColor:'white', paddingLeft: 10 }}/> </View> </View> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: 'yellow', // alignItems: 'center', // justifyContent: 'space-between', }, text: { color: '#ff0000' } });
function runTest() { FBTest.openNewTab(basePath + "html/4669/issue4669.xml", function(win) { FBTest.openFirebug(function() { var panel = FBTest.selectPanel("html"); FBTest.selectElementInHtmlPanel(win.document.documentElement, function(node) { // Press '*' twice and verify, that all tags are expanded afterwards FBTest.sendChar("*", panel.panelNode); FBTest.sendChar("*", panel.panelNode); var notExpandedNodes = panel.panelNode.querySelectorAll(".containerNodeBox:not(.open)"); FBTest.ok(notExpandedNodes.length == 0, "All nodes must be expanded"); FBTest.testDone(); }); }); }); }
// Get DOM elts const mainTemp = document.querySelector("#main"); const min = document.querySelector("#min"); const max = document.querySelector("#max"); const form = document.querySelector("form"); const cityElt = document.getElementById("city"); let city = ""; const isOk = (response) => response.ok ? response.json() : Promise.reject(new Error("Failed to load data from server")); const apiKey = "a1765436a53fce9de8bc00af314f1102"; form.addEventListener("submit", (e) => { const { search } = form.elements; city = search.value; const url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${apiKey}&units=metric`; // forecast fetch(url) .then(isOk) // <= Use `isOk` function here key a1765436a53fce9de8bc00af314f1102 .then((data) => { const { main, sys } = data; mainTemp.textContent = `${main.temp}°`; min.textContent = `^${main.temp_min}°`; max.textContent = `^${main.temp_max}°`; cityElt.textContent = `${city}, ${sys.country}`; console.log(data); // Prints result from `response.json()` }) .catch((error) => console.error(error)); e.preventDefault(); });
'use strict'; var should = require('should'); exports.perform = function (Element, mainProperty) { var element; beforeEach(function (done) { element = new Element(); element[mainProperty] = 'Test Value'; done(); }); describe('Method Save', function () { it('should be able to save without problems', function (done) { element.save(function (err) { should.not.exist(err); done(); }); }); it('should be able to show an error when try to save without name', function (done) { element[mainProperty] = ''; element.save(function (err) { should.exist(err); done(); }); }); }); afterEach(function (done) { element.remove(); done(); }); };
"use strict"; /** @type {import('@adonisjs/lucid/src/Schema')} */ const Schema = use("Schema"); class TaskSchema extends Schema { up() { this.create("tasks", table => { table.increments(); table .integer("project_id") .unsigned() // apenas valores positivos .notNullable() .references("id") .inTable("projects") .onUpdate("CASCADE") // caso este campo sofra alteração na tabela de usuários é necessario que ele tambem faça as alterações nesta tabela .onDelete("CASCADE"); //caso delete o projeto será necessario tambem que delete as tarefas table .integer("user_id") .unsigned() // apenas valores positivos .references("id") .inTable("users") .onUpdate("CASCADE") // caso este campo sofra alteração na tabela de usuários é necessario que ele tambem faça as alterações nesta tabela .onDelete("SET NULL"); //caso delete o usuário é necessario que não delete o projeto apenas coloque no user == null table .integer("file_id") .unsigned() // apenas valores positivos .references("id") .inTable("files") .onUpdate("CASCADE") .onDelete("SET NULL"); table.string("title").notNullable(); table.text("description"); table.timestamp("due_date"); table.timestamps(); }); } down() { this.drop("tasks"); } } module.exports = TaskSchema;
var authentication = require('./authentication'); var user = require('./user'); module.exports = { authentication: authentication, user: user }
define(['app'], function(app){ app.controller('popUpController', function($scope, $modalInstance, title, message, buttons){ $scope.title = title || 'Alerte'; $scope.content = message || 'Un message !!!!'; $scope.buttons = buttons || [ {classes : 'btn-success', label : 'ok', onClick : function(){console.log('OK');return false;}}, {classes : 'btn-warning', label : 'annuler', onClick : function(){console.log('annuler');return true;}} ]; $scope.close = function(dismiss){ if (dismiss) { $modalInstance.dismiss('cancel'); } else { $modalInstance.close(); } }; $scope.buttonClicked = function(callback) { var result = undefined; if (callback) { result = callback($modalInstance, $scope); } $scope.close(result === false); }; }) .factory('popUpManager', ['$modal', function($modal){ return service = { templateUrl : 'popUp.html', controller : 'popUpController', warning : function(title, message) { return $modal.open({ templateUrl: this.templateUrl, controller: this.controller, size: 'lg', resolve: { title : function(){return title || 'Alerte'}, message : function(){ return message }, buttons : function(){ return [{classes : 'btn-warning', label : 'ok'}]} } }); }, confirm : function(title, message, yes, no) { return $modal.open({ templateUrl: this.templateUrl, controller: this.controller, size: 'lg', resolve: { title : function(){return title || 'Alerte'}, message : function(){ return message }, buttons : function(){ return [ {classes : 'btn-success', label : 'Oui', onClick : yes}, {classes : 'btn-warning', label : 'Non', onClick : no} ]} } }); } }; return service; }]); var popUpManager = {}; return popUpManager; });
import React from 'react'; class MainVideo extends React.Component { constructor(props){ super(props); this.state = { videoURL: "./Cassette_Tape.mp419377.webm" } } render () { return ( <video id="background-video" loop autoPlay> <source src={this.state.videoURL} type="video/webm" /> <source src={this.state.videoURL} type="video/ogg" /> </video> ) } } export default MainVideo;
import AbstractDOMComponent from 'abstract/component.js'; class Header extends AbstractDOMComponent { constructor(props) { super(props); this.storeEvents = { 'app.location': (location, prevLocation) => this.setActiveLink(location, prevLocation), }; } initDOM() { this.$logo = this.el.querySelector('.logo'); this.$navItems = this.el.querySelectorAll('.menu li a'); } bindEvents() { this.$logo.addEventListener('click', this.handleClickLogo); } unbindEvents() { this.$logo.removeEventListener('click', this.handleClickLogo); } handleClickLogo = () => { console.log('clickHome'); }; setActiveLink(location) { this.resetCurrentNavItem(); let $currentNavItem = null; [...this.$navItems].forEach((navItem) => { if (navItem.dataset.page === location) $currentNavItem = navItem.parentNode; }); // if no nav item SKIP. this would happen when rendering legacy and 404. if ($currentNavItem === null) return; $currentNavItem.classList.add('active'); } resetCurrentNavItem() { [...this.$navItems].forEach((navItem) => { navItem.parentNode.classList.remove('active'); }); } } export default Header;
/** * * @authors Your Name (you@example.org) * @date 2018-07-28 18:16:41 * @version $Id$ */ /*自定义链接*/ import React from 'react'; import { BrowserRouter as Router, Route, Link } from 'react-router-dom' const RouterPage4 = ()=>{ return ( <Router> <div> <OldSchoolMenuLink activeOnlyWhenExact = {true} to = "/" label="Home"/> <OldSchoolMenuLink to = "/about" label="About"/> </div> <hr/> <Route exact path = "" component={home}/> <Route path = "/about" component={About}/> </Router> ) } const OldSchoolMenuLink = ({{label,to,activeOnlyWhenExact}}) => { return ( <Route path={to} exact={activeOnlyWhenExact} children = {({match}) => { return (<div className={match ? 'active' :''}> {match ? '>' : ''} <Link to = {to}>{label}</Link> </div>) }}></Route> ) } const Home = () =>{ return (<div> <h2>Home</h2> </div>) } const About = () =>{ return ( <div> <h2>About</h2> </div> ) } export default RouterPage4;
"use strict"; var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty")); var _objectSpread3 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread")); var _classCallCheck2 = _interopRequireDefault(require("@babel/runtime/helpers/classCallCheck")); var _createClass2 = _interopRequireDefault(require("@babel/runtime/helpers/createClass")); var _possibleConstructorReturn2 = _interopRequireDefault(require("@babel/runtime/helpers/possibleConstructorReturn")); var _getPrototypeOf2 = _interopRequireDefault(require("@babel/runtime/helpers/getPrototypeOf")); var _inherits2 = _interopRequireDefault(require("@babel/runtime/helpers/inherits")); var _react = _interopRequireWildcard(require("react")); var Flex = /*#__PURE__*/ function (_Component) { (0, _inherits2.default)(Flex, _Component); function Flex(props) { (0, _classCallCheck2.default)(this, Flex); return (0, _possibleConstructorReturn2.default)(this, (0, _getPrototypeOf2.default)(Flex).call(this, props)); } (0, _createClass2.default)(Flex, [{ key: "render", value: function render() { var _this$props = this.props, children = _this$props.children, vertical = _this$props.vertical, width = _this$props.width, height = _this$props.height, _this$props$style = _this$props.style, style = _this$props$style === void 0 ? {} : _this$props$style; return _react.default.createElement("div", { className: "an-layout", style: (0, _objectSpread3.default)({}, style, { display: 'flex', width: width || '100%', height: height || '100%', flexFlow: vertical ? 'column' : 'row', flexShrink: width || height ? 0 : 1 }) }, _react.default.Children.map(children, function (child) { var isFlex = child.type && child.type.name === Flex.name; //todo 有可能会受打包影响! var type = vertical ? 'height' : 'width'; if (isFlex) { return (0, _objectSpread3.default)({}, child, { props: (0, _objectSpread3.default)({}, child.props, (0, _defineProperty2.default)({ size: undefined }, type, child.props.size)) }); } return child; })); } }]); return Flex; }(_react.Component); exports.default = Flex;
self.__precacheManifest = (self.__precacheManifest || []).concat([ { "revision": "69c4d517c59a2073b127a127da986265", "url": "/index.html" }, { "revision": "d4c063663a7ef9274f5e", "url": "/static/css/main.edb7952c.chunk.css" }, { "revision": "879f345bd7fad6b87414", "url": "/static/js/2.4de3c545.chunk.js" }, { "revision": "d4c063663a7ef9274f5e", "url": "/static/js/main.8c9ffec0.chunk.js" }, { "revision": "42ac5946195a7306e2a5", "url": "/static/js/runtime~main.a8a9905a.js" } ]);
export const sendMessages = [ "Adam you are so great I love you so much.", "Hey there, handsome.", "Hey there, good looking", "Wow this app is so great haha I wish I was this funny", "Wow this app is hilarious haha I wish I was this funny but I'm not as funny as you, Adam Ginther.", "Wow this is the best April Fools ever", "Wow this app is so great I am going to share it with all my good looking friends right now", "Hello Adam Ginther have I ever told you how handsome you are?", "Hello Adam Ginther have I ever told you how good looking you are?", "Heyyyyyyyyyyyyyyyyyyyy...", "U up? I just wanted to chaaaaatttt...", "I’m not a photographer, but I can picture me and you together.", "Are you wearing space pants? Because you are out of this world.", "hhhhhhhhhheeyyyyyyyyyyyyyy tttttthhhhhheeeeeerreeeeeeeeeeee", "Hey handsome", "Hey good looking, what's cooking?", "Are you free for coffee sometime?", "Hey Adam, why don't we make like atoms and combine to make a molecule?", "lol wow you are so cool and funny and awesome I wish I was you", "Wow, it's that guy that men want to be and women want to be with", "Have I ever told you how good looking you are?", "Have I ever told you how good looking handsome you are?", "Wow this app is so good I guess it's time for me to delete my Tinder account", "I've been thinking about you all day, Adam Ginther", "Do I know you? ‘Cause you look a lot like my next boyfriend.", "They say Disneyland is the happiest place on earth. Well apparently, no one has ever been messaging you an an app like this.", "Are you religious? Because you’re the answer to all my prayers.", "I seem to have lost my phone number. Can I have yours?", "Are you a parking ticket? ‘Cause you’ve got fine written all over you.", "Are you sure you’re not tired? You’ve been running through my mind all day.", "Is there an airport nearby or is it my heart taking off?", "Would you please respond, so I can tell my friends I’ve talked to an angel?", "Plz respond", "Hi, how was heaven when you left it?", "Is your dad a terrorist? Cause you’re the bomb.", "Do you believe in love at first sight or should I swipe right again?", "Hey, you’re pretty and I’m cute. Together we’d be Pretty Cute.", "Can I follow you home? Cause my parents always told me to follow my dreams.", "Is your name Google? Because you have everything I’ve been searching for.", "You don’t need keys to drive me crazy.", "You remind me of a magnet, because you sure are attracting me over here!", "Is my phone overheating or are all the men on this app just way too hot?", "Do you like raisins? How do you feel about a date?", "If I could rearrange the alphabet, I’d put ‘U’ and ‘I’ together.", "Life without you is like a broken pencil…pointless." ];
import React, { Component } from 'react'; import { connect } from 'dva'; import { List, InputItem, Button, Checkbox } from 'antd-mobile'; import styles from './styles.scss'; const CheckboxItem = Checkbox.CheckboxItem; function TodoItem({ item, changeTodo }) { const Item = List.Item; const { id, title = 'Hello World!', checked } = item; const onChange = item => { changeTodo(item); }; return ( <CheckboxItem checked={checked} onChange={() => onChange(item)}> {title} </CheckboxItem> ); } class TodoList extends Component { constructor(props) { super(props); this.inputRef = {}; } addTodoHandler = () => { const { dispatch } = this.props; dispatch({ type: 'todoList/addTodo', payload: { id: Date.now(), title: this.inputRef.state.value, checked: false, }, }); this.inputRef.state.value = ''; }; fetchDataHandler = () => { const { dispatch } = this.props; dispatch({ type: 'todoList/fetchTodo', payload: { a: 1, b: 2, }, }); }; changeTodoHandler = item => { const { dispatch } = this.props; dispatch({ type: 'todoList/updateTodoChecked', payload: item, }); }; deleteTodoHandler = item => { const { dispatch } = this.props; dispatch({ type: 'todoList/deleteTodo', }); }; deleteAllHandler = () => { const { dispatch } = this.props; dispatch({ type: 'todoList/deleteAll', }); }; render() { const { data } = this.props.todoList; return ( <div> <List> <Button onClick={this.fetchDataHandler} type="primary"> Fetch todo </Button> <InputItem extra={ <Button onClick={this.addTodoHandler} className={styles.button} type="primary" size="small" > Add </Button> } placeholder="please input todo" data-seed="logId" ref={el => (this.inputRef = el)} > Todo Title </InputItem> {data && data.map((item, idx) => { return ( <TodoItem key={idx} item={item} changeTodo={this.changeTodoHandler}></TodoItem> ); })} </List> <Button inline size="small" type="primary" style={{ marginRight: '1rem' }} onClick={this.deleteTodoHandler} > Detele </Button> <Button inline size="small" type="primary" onClick={this.deleteAllHandler}> Detele All by Async </Button> </div> ); } } const mapStateToProps = ({ todoList }) => ({ todoList, }); export default connect(mapStateToProps)(TodoList);
// sequelize ============================ const Sequelize = require('sequelize'); const Op = Sequelize.Op; const sequelize = new Sequelize(process.env.database, process.env.appUser, process.env.password, { host: process.env.host, dialect: 'postgres' }) sequelize .authenticate() .then(() => { console.log('Successful database connection'); }) .catch(err => { console.error('Unsuccessful database connection', err); }); // database model definitions ========== const User = sequelize.define('user_accounts', { fullname: { type: Sequelize.TEXT }, email: { type: Sequelize.TEXT }, password: { type: Sequelize.TEXT, allowNull: false }, age: { type: Sequelize.INTEGER }, gender: { type: Sequelize.TEXT }, profile_img: { type: Sequelize.TEXT } }, { tableName: 'user_accounts', freezeTableName: true, timestamps: false }); const Cultinterests = sequelize.define('cultural_interests', { art: { type: Sequelize.BOOLEAN }, dance: { type: Sequelize.BOOLEAN }, theatre: { type: Sequelize.BOOLEAN }, music: { type: Sequelize.BOOLEAN } }, { tableName: 'cultural_interests', freezeTableName: true, timestamps: false }); const Cultcard = sequelize.define('cultcard', { museumcard: { type: Sequelize.BOOLEAN }, musicabo: { type: Sequelize.BOOLEAN }, wap: { type: Sequelize.BOOLEAN }, indie4t: { type: Sequelize.BOOLEAN }, stadspas: { type: Sequelize.BOOLEAN }, cineville: { type: Sequelize.BOOLEAN } }, { tableName: 'cultcard', freezeTableName: true, timestamps: false }); const Talkratio = sequelize.define('talkratio', { bla: { type: Sequelize.BOOLEAN }, blabla: { type: Sequelize.BOOLEAN }, blablabla: { type: Sequelize.BOOLEAN } }, { tableName: 'talkratio', freezeTableName: true, timestamps: false }); const Agepref = sequelize.define('age_pref', { '20-30': { type: Sequelize.BOOLEAN }, '31-40': { type: Sequelize.BOOLEAN }, '41-50': { type: Sequelize.BOOLEAN }, '51-60': { type: Sequelize.BOOLEAN }, '61-70': { type: Sequelize.BOOLEAN }, '71-80': { type: Sequelize.BOOLEAN }, '81-90': { type: Sequelize.BOOLEAN } }, { tableName: 'age_pref', freezeTableName: true, timestamps: false }); const Genderpref = sequelize.define('gender_pref', { male: { type: Sequelize.BOOLEAN }, female: { type: Sequelize.BOOLEAN }, transgender: { type: Sequelize.BOOLEAN } }, { tableName: 'gender_pref', freezeTableName: true, timestamps: false }); const Languages = sequelize.define('languages', { dutch: { type: Sequelize.BOOLEAN }, english: { type: Sequelize.BOOLEAN }, german: { type: Sequelize.BOOLEAN }, french: { type: Sequelize.BOOLEAN }, spanish: { type: Sequelize.BOOLEAN }, italian: { type: Sequelize.BOOLEAN }, russian: { type: Sequelize.BOOLEAN }, arabic: { type: Sequelize.BOOLEAN } }, { tableName: 'languages', freezeTableName: true, timestamps: false }); const Suggestion = sequelize.define('suggestion', { timedate: { type: Sequelize.TEXT }, type: { type: Sequelize.TEXT }, eventname: { type: Sequelize.TEXT }, location: { type: Sequelize.TEXT }, url: { type: Sequelize.TEXT } }, { tableName: 'suggestion', freezeTableName: true, timestamps: false }); // table associations ============= Cultinterests.belongsTo(User) // adds userAccountId to Interests (references id of User) User.hasOne(Cultinterests); Cultcard.belongsTo(User) // adds userAccountId to Cultcard (references id of User) User.hasOne(Cultcard); Talkratio.belongsTo(User) // adds userAccountId to Talkratio (references id of User) User.hasOne(Talkratio); Agepref.belongsTo(User) // adds userAccountId to Agepref (references id of User) User.hasOne(Agepref); Genderpref.belongsTo(User) // adds userAccountId to Genderpref (references id of User) User.hasOne(Genderpref); Languages.belongsTo(User) // adds userAccountId to Languages (references id of User) User.hasOne(Languages); User.hasMany(Suggestion) // adds userAccountId to Suggestion (references id of User) Suggestion.belongsToMany(User, { through: 'UserSuggestion', foreignKey: 'suggestionId', otherKey: 'userAccountId' }) module.exports = dbSeq = { User: User, Cultinterests: Cultinterests, Cultcard: Cultcard, Talkratio: Talkratio, Agepref: Agepref, Genderpref: Genderpref, Languages: Languages, Suggestion: Suggestion, sequelize: sequelize };
const plugins = ['@babel/plugin-syntax-dynamic-import']; if (process.env.NODE_ENV === 'development') { plugins.push('react-hot-loader/babel'); } if (process.env.NODE_ENV === 'test') { plugins.push('babel-plugin-dynamic-import-node'); } module.exports = { plugins, presets: ['@babel/preset-env', '@babel/preset-react'], };
import axios from 'axios'; import api from '../apiUrls'; import setAuthToken from '../utils/setAuthToken'; import { FRIENDS_LOADING, GET_FRIENDS, REMOVE_FRIEND, GET_ERRORS, } from './types'; export const getFriends = () => dispatch => { setAuthToken(localStorage.getItem("jwtToken")); dispatch({ type: FRIENDS_LOADING }); axios .get(api.friends.getAll) .then(res => { dispatch({ type: GET_FRIENDS, payload: res.data }); }) .catch(err => { dispatch({ type: GET_ERRORS, payload: err.response.data }); }); }; export const removeFriend = id => dispatch => { setAuthToken(localStorage.getItem("jwtToken")); axios .delete(api.friends.removeFriendById(id)) .then(res => { dispatch({ type: REMOVE_FRIEND, payload: id }); }) .catch(err => { dispatch({ type: GET_ERRORS, payload: err.response.data }); }); };
// Main export {default as HomePage} from "./HomePage"; export {default as Notes} from "./Notes"; export {default as Login} from "./Login"; export {default as NotFound} from "./NotFound"; export {default as Contact} from "./Contact"; export {default as Footer} from "./Footer"; export {default as Header} from "./Header/Header"; export {default as PrivacyPolicy} from "./PrivacyPolicy"; export {default as Register} from "./Register/Register.1"; export {default as Dashboard} from "./Dashboard"; export {default as About} from "./About"; export {default as TestsContainer} from "./Tests/TestsContainer"; // Common export {default as AuthInput} from "./common/AuthInput"; // ACT Forms export {default as ACTForm} from "./Tests/ACTForms/ACTForm"; // Assignments export {default as Assignments} from "./Assignments/Assignments"; // Profile export {default as Profile} from "./profiles/AppProfile";
import React from 'react'; import { browserHistory } from 'react-router'; import routes from '../../routes'; export default class ProfileContainer extends React.Component { constructor(props) { super(props); } render() { return ( <div className="page-container profile-container"> <div className="page-content"> <div className="content-wrapper"> <div className="profile-cover"> <div className="profile-cover-img"></div> <div className="media"> <div className="media-body"> <a href="#" className="profile-thumb"> <img src="../../assets/images/ron-carucci_avatar.jpg" className="img-circle" alt=""/> </a> <h1>Randy Shelton <small className="display-block">Assistant Professor</small> </h1> </div> </div> </div> </div> </div> </div> ); } }
import { storiesOf } from '@storybook/vue'; import TabNavigation from './TabNavigation'; storiesOf('Design System|Molecules/TabNavigation', module) .add('default', () => { return { components: { TabNavigation }, template: `<TabNavigation :tabs="this.tabs" :active="2"></TabNavigation>`, data: () => ({ tabs: [ {title: 'Adresse'}, {title: 'Lieferung'}, {title: 'Zahlung'}, {title: 'Bestätigung'} ] }), }; });
import { createMuiTheme, MuiThemeProvider } from '@material-ui/core/styles'; import React, { Component } from 'react'; import { create } from 'jss'; import rtl from 'jss-rtl'; import { jssPreset } from '@material-ui/core/styles'; const jss = create({ plugins: [...jssPreset().plugins, rtl()] }); const themeOptions = { typography: { useNextVariants: true, fontFamily: 'IRANSans', fontSize: 10 }, }; export default class ThemeProvider extends Component { componentDidMount() { } render() { const theme = createMuiTheme({ ...themeOptions }); return ( <MuiThemeProvider theme={theme} jss={jss}> {this.props.children} </MuiThemeProvider> ); } }
// @flow import type { Expr } from "./plain-expression-ast"; import { Plus, Times, Paren, Num, plus, times, paren, num } from "./plain-expression-ast"; export default function evalExpr (ex: Expr) : number { return ( ex instanceof Plus ? evalExpr(ex.left) + evalExpr(ex.right) : ex instanceof Times ? evalExpr(ex.left) * evalExpr(ex.right) : ex instanceof Paren ? evalExpr(ex.contents) : /* ex is a Num */ ex.value); } const expr = times(num(2), paren(times(plus(num(1), num(1)), times(num(4), num(3))))) console.log(evalExpr(expr));
let numeros = [2, 4, 6]; //Array let numerosDobrados = numeros.map(function(umNumero){ //Um novo array return umNumero * 2; }); console.log(numeros); //Array inicial console.log(numerosDobrados); //Novo Array
document.body.id = 'sandbox-demo'; const element = document.createElement('p'); element.id = 'vh'; element.innerHTML = `demo loaded! <slot name="slot-demo"><p>默认文本</p></slot>`; document.body.appendChild(element); const link = document.createElement('link'); link.rel = 'stylesheet'; link.href = '/examples/web-sandbox-element/demo.css'; document.head.appendChild(link); const template = document.createElement('template'); template.innerHTML = ` <style> ::slotted(div) { color: #FFF; background-color: #666; padding: 5px; } </style> <div class="tab-labels"><slot name="tab-label"></slot></div> <p class="tab-contents"><slot name="tab-content"></slot></p> `; // console.log(template); document.body.appendChild(template.content.cloneNode(true)); const script = document.createElement('script'); script.src = `/examples/web-sandbox-element/sub.js?v=${window.name}`; window.ENV = { debug: true }; document.body.appendChild(script); try { document.createElement(' s sf f'); } catch (e) { window.error = e; // console.error(e); } document.body.className = 'aaa bbb cc dd'; document.body.setAttribute('style', 'color: red'); window.__demo__ = true; const btn = document.createElement('nav'); btn.innerHTML = 'click'; btn.onclick = function() { console.log(this, 'click'); }; btn.addEventListener('click', () => { console.log('click', this); }); document.body.appendChild(btn); console.log('document.body >>>', document.body); const nav = document.createElement('nav-ssssss'); document.body.appendChild(nav);
import React from 'react'; import { Router } from 'react-router-dom'; import { createMemoryHistory } from 'history'; import { render, cleanup, fireEvent } from "@testing-library/react"; import '@testing-library/jest-dom/extend-expect'; import SearchBox from '../SearchBox'; afterEach(cleanup); test('Render component SearchBox', () => { const history = createMemoryHistory(); history.push('/'); const { getByAltText, getByPlaceholderText } = render( <Router history={history}> <SearchBox query="texto inicial" /> </Router> ); expect(getByAltText('Mercado Libre')).toBeInTheDocument(); expect(getByAltText('Buscar')).toBeInTheDocument(); const input = getByPlaceholderText('Nunca dejes de buscar'); expect(input.value).toBe('texto inicial'); fireEvent.change(input, { target: { value: 'texto ingresado' } }); expect(input.value).toBe('texto ingresado'); });
//utils import React from 'react'; import Modal from 'react-modal'; import ReactDOM from 'react-dom'; import createStore from './store/store'; //component views import MainView from './components/views/main_view'; document.addEventListener('DOMContentLoaded', () => { const store = createStore(); Modal.setAppElement('#root'); const root = document.getElementById('root'); ReactDOM.render(<MainView store={store} />, root); });
/** * Main application routes */ 'use strict'; const path = require('path'); const request = require("request"); module.exports = function (app) { // Instructions had two different naming conventions for the api (character for single result and characters for more than one result) // many apis tend to have the index and show functions under the same route, so just to cover my bases I made it so both work. app.use('/character', require('./api/character/character.routes')); app.use('/characters', require('./api/character/character.routes')); app.use('/planetResidents', require('./api/planetResident/planetResident.routes')); /*** This is code added to support the frontend test, this is irrelevant for the requirements listed in the backend test (I threw them under the same server so deploying my demo would be easier/cheaper)***/ app.get('/representatives/:state', findRepresentativesByState, jsonResponse ); app.get('/senators/:state', findSenatorsByState, jsonResponse ); function findRepresentativesByState(req, res, next) { const url = `http://whoismyrepresentative.com/getall_reps_bystate.php?state=${req.params.state}&output=json`; request(url, handleApiResponse(res, next)); } function findSenatorsByState(req, res, next) { const url = `http://whoismyrepresentative.com/getall_sens_bystate.php?state=${req.params.state}&output=json`; request(url, handleApiResponse(res, next)); } function handleApiResponse(res, next) { return (err, response, body) => { if (err || body[0] === '<') { res.locals = { success: false, error: err || 'Invalid request. Please check your state variable.' }; return next(); } res.locals = { success: true, results: JSON.parse(body).results }; return next(); }; } function jsonResponse(req, res, next) { return res.json(res.locals); } }
import express, { json, urlencoded } from 'express' import { errors } from 'celebrate' import morgan from 'morgan' import 'dotenv/config.js' import productRoutes from './routes/productRoutes.js' import customerRoutes from './routes/customerRoutes.js' import orderRoutes from './routes/orderRoutes.js' const app = express() app.use(json()) app.use(urlencoded({ extended: false })) app.use(morgan('dev')) app.set('port', process.env.PORT || 3333) app.use('/products', productRoutes) app.use('/customers', customerRoutes) app.use('/orders', orderRoutes) app.use(errors()) export { app }
import React, { Component } from 'react'; import { StyleSheet, Text, View, Image, TouchableOpacity, TextInput, Button, KeyboardAvoidingView, Alert } from 'react-native'; import FlatlistBasic from './FlatlistBasic' export default class Login extends Component { constructor(props) { super(props); this.state = { email: '', password: '', accessToken: null } } render() { if (this.state.accessToken == null) { return <View style={styles.container} > <View style={styles.logoContainer}> <Image style={styles.logo} source={require('../assets/recipe.png')}></Image> </View> <TextInput style={styles.input} placeholder='Email or Mobile Num' onChangeText={(email) => { this.setState({ email }) }} placeholderTextColor="black" returnKeyType='next' keyboardType="email-address" onSubmitEditing={() => this.passwordInput.focus()} autoCapitalize="none" autoCorrect={false} /> <TextInput style={styles.input} placeholder='Password' onChangeText={(password) => { this.setState({ password }) }} placeholderTextColor="black" secureTextEntry returnKeyType='go' ref={(input) => this.passwordInput = input} /> <TouchableOpacity style={styles.buttonContainer} > <Text style={styles.buttonText} onPress={this.onClick}>LOGIN</Text> </TouchableOpacity> </View > } else { console.log('----------dssdasasa') return <View style={[styles.mainContainer, styles.shadow]}> <FlatlistBasic token={this.state.accessToken} /> </View> } } onClick = async () => { // console.log(this.state); fetch('http://35.160.197.175:3006/api/v1/user/login', { method: 'POST', headers: { // Accept: 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ email: this.state.email, password: this.state.password, }), }).then(response => { if (response.status === 200) { return response.json(); } else { Alert.alert("Fail", 'Plese eneter valid credentails'); } }).then(response => { console.log(response); if (response) { this.setState({ accessToken: response.token }); Alert.alert("Success", "Welcome to Secret Recipe"); } }).catch(err => { // console.log(err); }); } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#F4C095', justifyContent: 'center', padding: 20 }, mainContainer: { flex: 1, }, input: { height: 40, backgroundColor: '#FFFFFB', marginBottom: 20, padding: 15, paddingHorizontal: 10, // color: '#fff' }, logoContainer: { justifyContent: "center", // flexGrow: 1, alignItems: "center", }, logo: { height: 100, width: 150, borderRadius: 50, marginBottom: 40 }, buttonContainer: { backgroundColor: '#2980b6', paddingVertical: 10 }, buttonText: { color: '#7ac5cd', textAlign: 'center', fontWeight: '800' } });
function g(x) { return x; } function h(f) { return f; } function f() { return h(function VICTIM() { var r = g(1); return r + 1; }); } const assert = require('assert'); assert(f()() === 2);
// @flow import styled from '@emotion/styled'; import type { Theme } from 'components/app.js'; type CssProps = $ReadOnly<{| alignment: 'left' | 'right', theme: Theme, |}>; export const Container = styled.div` margin-bottom: 25px; img { max-width: 100%; } ${({ theme }: CssProps) => theme.media.l` margin-bottom: 75px; `} `; export const Header = styled.div` margin-left: 0; ${({ theme, alignment }: CssProps) => theme.media.l` margin-left: ${alignment === 'right' ? '60%' : 0}; `} ${({ theme, alignment }: CssProps) => theme.media.xl` margin-left: ${alignment === 'right' ? '70%' : 0}; `} ${({ theme, alignment }: CssProps) => theme.media.xxl` margin-left: ${alignment === 'right' ? '80%' : 0}; `} `; export const Body = styled.div` position: relative; display: flex; flex-direction: column; ${({ theme, alignment }: CssProps) => theme.media.l` flex-direction: ${alignment === 'right' ? 'row' : 'row-reverse'}; `} `; export const ImageContainer = styled.div` position: relative; width: 100%; margin-bottom: 25px; img { max-width: 100%; } ${({ theme, alignment }: CssProps) => theme.media.l` width: 55%; margin-top: -135px; margin-right: ${alignment === 'right' ? '5%' : 0}; margin-left: ${alignment === 'left' ? '5%' : 0}; margin-bottom: 0; `} ${({ theme }: CssProps) => theme.media.xl` width: 65%; `} ${({ theme }: CssProps) => theme.media.xxl` width: 75%; `} `; export const Text = styled.div` width: 100%; p { margin: 0 0 25px; } ${({ theme }: CssProps) => theme.media.l` width: 40%; `} ${({ theme }: CssProps) => theme.media.xl` width: 30%; `} ${({ theme }: CssProps) => theme.media.xxl` width: 20%; `} `;
import React, { Component } from 'react'; import AppActions from '../../actions/AppActions'; import CheckboxSetting from './CheckboxSetting.react'; /* |-------------------------------------------------------------------------- | Child - UI Settings |-------------------------------------------------------------------------- */ export default class SettingsUI extends Component { static propTypes = { config: React.PropTypes.object, } constructor(props) { super(props); } render() { const config = this.props.config; return ( <div className='setting setting-interface'> <CheckboxSetting title='Dark Theme' description='Enable dark theme' defaultValue={ config.theme === 'dark' } onClick={ AppActions.settings.toggleDarkTheme } /> <CheckboxSetting title='Display Notifications' description='Allow the app to send native notifications' defaultValue={ config.displayNotifications } onClick={ AppActions.settings.toggleDisplayNotifications } /> <CheckboxSetting title='Use native frame' description='Run Museeks with default window controls (will restart the app)' defaultValue={ config.useNativeFrame } onClick={ AppActions.settings.toggleNativeFrame } /> <CheckboxSetting title='Sleep mode blocker' description='Prevent the computer from going into sleep mode' defaultValue={ config.sleepBlocker } onClick={ AppActions.settings.toggleSleepBlocker } /> <CheckboxSetting title='Minimize to tray' description='Minimize to tray when closing the app' defaultValue={ config.minimizeToTray } onClick={ AppActions.settings.toggleMinimizeToTray } /> <CheckboxSetting title='Auto update checker' description='Automatically check for update on startup' defaultValue={ config.autoUpdateChecker } onClick={ AppActions.settings.toggleAutoUpdateChecker } /> </div> ); } }
const Joke = require("../models/jokes.model") module.exports.helloWorld = (req, res) => { res.json({message: "Hello World"}); }; module.exports.findAllJokes = (req, res) => { console.log("Finding all jokes!") Joke.find() .then(allJokes => { res.json({results: allJokes}) }) .catch(err => { res.json({err: err}) }) } module.exports.findOneJoke = (req, res) => { console.log("Finding one joke by id --> ", req.params.id) Joke.findOne({ _id: req.params.id }) .then(foundJoke => res.json({results: foundJoke})) .catch(err => { res.json({err: err}) }) } module.exports.createJoke = (req, res) => { console.log("Creating new joke!") Joke.create(req.body) .then(newJokeObj => { res.json({results: newJokeObj}) }) .catch(err => { res.json({err: err}) }) } module.exports.updateJoke = (req, res) => { console.log("Updating joke with the id --> ", req.params.id) Joke.findOneAndUpdate( {_id: req.params.id}, // finding object by id req.body, // passing information from the form to update with {new: true, runValidators: true} // new: true displays the updated info and runValidators makes sure updated info conforms to validations ) .then(updatedJoke => { res.json({results: updatedJoke}) }) .catch(err => { res.json({err: err}) }) } module.exports.deleteJoke = (req, res) => { console.log("Deleting joke with the id --> ", req.params.id) Joke.deleteOne({_id: req.params.id}) .then(deletedJoke => { res.json({results: deletedJoke}) }) .catch(err => { res.json({err: err}) }) }
import React from 'react'; import SearchForm from "./SearchForm"; import SearchResponse from "./SearchResponse"; export default class SearchBox extends React.Component { constructor() { super(); this.state = { search: '', response: '' }; } search(search) { this.setState({search: search, response: search}); var xhr = new XMLHttpRequest(); xhr.open('GET', '/api/ask?q=' + search); xhr.responseType = 'json'; xhr.onload = function() { this.setState({response: xhr.response}); }.bind(this); xhr.onerror = function() { console.log("Error"); }; xhr.send(); } render() { // Conditional search result var responseBox; if (this.state.response) { responseBox = <SearchResponse response={this.state.response} />; } return ( <div> {responseBox} <SearchForm search={this.search.bind(this)} /> </div> ); } }
const axios = require("axios").default; const api_key = process.env.quandlApiKey; /** * * @param {*} bse_code BSE Code * @param {*} start_date starting date * @param {*} end_date ending date * */ module.exports = (bse_code, start_date, end_date) => axios.get( `https://www.quandl.com/api/v3/datasets/BSE/BOM${bse_code}/data.json`, { params: { start_date, end_date, api_key, }, } );
// 全局菜单 export default { webTitle: 'បណ្ដាញវេទិកាអ្នកជំនួញ​A9', zh: 'ចិន', en: 'អង់គ្លេស', km: 'ភាសាខ្មែរ', home: 'ទំព័រដើម', logout: 'ចេញពីគណនី', account: 'ឈ្មោះគណនី', mobile: 'លេខទរស័ព្ទ', password: 'ពាក្យសម្ងាត់', login: 'ចូលគណនី', shopMgr: 'ការគ្រប់គ្រងហាង', shopList: 'បញ្ជីហាង', trayMgr: 'ការគ្រប់គ្រងឧបករណ៏', trayList: 'បញ្ជីឧបករណ៏', userMgr: 'ការគ្រប់គ្រងអ្នកប្រើប្រាស', userFeedbackList: 'បញ្ជីមតិយោបល់', system: 'ការកំណត់', systemPrice: 'ការកំណត់មូលដ្ធាន', adminList: 'បញ្ជីឈ្មោះអ្នកគ្រប់គ្រង', userList: 'បញ្ជីអ្នកប្រើប្រាស់', userBalanceRecord: 'កំណត់ត្រាសមតុល្យ', appDownloadAddress: 'ការគ្រប់គ្រងកម្មវិធីAPP', couponConfigure: 'ការកំណត់ប័ណ្ណបញ្ចុះតម្លៃ', couponList: 'បញ្ជីប័ណ្ណបញ្ចុះតម្លៃ', activityMgr: 'ការគ្រប់គ្រងសកម្មភាព', withdrawalList: 'បញ្ជីដកលុយ', withdrawalMgr: 'ការគ្រប់គ្រងការដកសាច់ប្រាក់', robotMgr: 'សេវាកម្មអតិថិជនស្វ័យប្រវត្តិ', goodsEdit: 'បញ្ចេញទំនិញ', goodsMgr: 'ការគ្រប់គ្រងទំនិញ', goodsList: 'តារាងទំនិញ', shareGoods: 'ការចែកចាយផលិតផល', postageRule: 'វិន័យនៃតម្លៃដឹកជញ្ជូន', orderMgr: 'ការគ្រប់គ្រងការបញ្ជាទិញ', orderList: 'បញ្ជីការបញ្ជាទិញ', returnList: 'បង្វិលត្រលប់ / ផ្លាស់ប្ដូរ', returnGoods: 'បង្វិលត្រលប់', exchangeGoods: 'ផ្លាស់ប្ដូរ', evaluateMgr: 'ការគ្រប់គ្រងមតិយោបល់', operationMgr: 'ការគ្រប់គ្រងប្រតិបត្តិការ', adMgr: 'ការគ្រប់គ្រងការផ្សាយពាណិជ្ជកម្ម', redEnvelope: 'ការគ្រប់គ្រងអាំងប៉ាវ', panicBuys: 'បញ្ចុះតម្លៃក្នុងវិនាទីពិសេស', cobuy: 'ការទិញទំនិញជាក្រុម', coupon: 'ប័ណ្ណបញ្ចុះតម្លៃ', cutGoods: 'ការតថ្លៃដើម្បីទទួលបានទំនិញ', shopInfo: 'ពត៏មានផ្ទាល់របស់ហាង', financeMgr: 'ការគ្រប់គ្រងហិរញ្ញវត្ថុ', financeList: 'ព័ត៌មានលម្អិតអំពីគណនី', financeTixian: 'កំណត់ត្រាការដកប្រាក់', address: 'ការគ្រប់គ្រងអាស័យដ្ធាន', chatRobot: 'ការផ្ញើសារស្វ័យប្រវត្តិ', optLog: 'កំណត់ត្រាប្រតិបត្តិការប្រចាំថ្ងៃ', cardMgr: 'ការគ្រប់គ្រងកាតធនាគារ', liveBroadcast: 'ការគ្រប់គ្រងការផ្សាយផ្ទាល់', freeShipingSet: 'ការកំណត់ការដឹកជញ្ជូនដោយឥតគិតថ្លៃ', fullReductionSet: 'ការកំណត់ការកាត់បន្ថយពេញលេញ', warehouseMgr: 'ការគ្រប់គ្រងឃ្លាំង', warehouseList: 'បញ្ជីឃ្លាំង', suppliersMgr: 'អ្នកផ្គត់ផ្គង់', purchasesMgr: 'បញ្ជា​រ​ទិញ', totalinventory: 'ទំនិញក្នុងស្តុកសរុប', specialPermission: 'ការអនុញ្ញាតពិសេស', financialApproval: 'ផ្នែកហិរញ្ញវត្ថុយល់ព្រម', leadershipApproval: 'អ្នកដឹកនាំយល់ព្រម', journal: 'កំណត់ហេតុចូល និង​ ចេញឃ្លាំង', baseData: 'ទិន្នន័យមូលដ្ឋាន', ProcurementManagement: 'ការគ្រប់គ្រងលទ្ធកម្ម', procurementWarehouse: 'ឃ្លាំងនិងការទិញ', procurementPrice: 'តម្លៃបញ្ជាទិញ', combinebuys: 'ការទិញបញ្ចូលគ្នា', memorandum: 'អនុស្សរណៈ', AbnormalLogin: 'ការចូលមិនធម្មតា', ReminderSet: 'ការគ្រប់គ្រងអនុសរណៈ', overdraftSet: 'ការកំណត់ឥណទានលើស', selfPickStation: 'ចំណុចជ្រើសរើសដោយខ្លួនឯង' }
import Jsrsasign from 'jsrsasign' // Header import Mock from 'mockjs' import { formatMockData } from '../src/utils/format.js' const list = [] const count = 30 for (let i = 0; i < count; i++) { list.push(Mock.mock({ 'UserID': '@increment(1020)', 'UserName': '@first', 'CreatedAt': '@datetime()', 'UpdatedAt': '@datetime()', 'UUID': '@guid', 'UserHomeDir': /\w{4,8}/, 'GroupID': '@increment(120)', 'GroupName': /\w{3,6}/ })) } var oHeader = { alg: 'HS256', typ: 'JWT' } // Payload var oPayload = {} var tNow = Jsrsasign.KJUR.jws.IntDate.get('now') var tEnd = Jsrsasign.KJUR.jws.IntDate.get('now + 1day') oPayload.nbf = tNow oPayload.iat = tNow oPayload.exp = tEnd var sHeader = JSON.stringify(oHeader) var sPayload = JSON.stringify(oPayload) var sJWT = Jsrsasign.KJUR.jws.JWS.sign('HS256', sHeader, sPayload, { b64: 'MTIzNDU2Nzg=' }) export default [ // user login { url: '/users/login', type: 'post', response: config => { return { 'Success': true, 'Message': '', 'Code': '', 'Inventory': sJWT } } }, // user sync { url: '/users/sync', type: 'post', response: config => { return { 'Success': true, 'Message': '', 'Code': '', 'Inventory': { 'Message': '同步完成', 'Status': 'success' }} } }, // get user Info by userId { url: '/users/\d{1,10}', type: 'post', response: config => { return { 'Success': true, 'Msg': '', 'Code': '', 'Inventory': {}} } }, // get groups by userId { url: '/users/[0-9]+/groups', type: 'get', response: config => { const mockList = formatMockData(list, ['UpdatedAt', 'CreatedAt', 'UUID', 'GroupID', 'GroupName']) return { 'Success': true, 'Message': '', 'Code': '', 'Inventory': mockList[0] } } }, // get user chargedGroups by userId { url: '/users/[0-9]+/chargedGroups', type: 'get', response: config => { const mockList = formatMockData(list, ['UpdatedAt', 'CreatedAt', 'UUID', 'GroupID', 'GroupName']) return { 'Success': true, 'Message': '', 'Code': '', 'Inventory': mockList[0] } } }, // get user Info { url: '/users\?.*', type: 'get', response: config => { const { PageNumber, PageSize } = JSON.parse(config.query.page) const mockList = formatMockData(list, ['UpdatedAt', 'CreatedAt', 'UserID', 'UserName', 'UUID', 'UserHomeDir']) const pageList = mockList.filter((item, index) => index < PageNumber * PageSize && index >= PageSize * (PageNumber - 1)) return { 'Success': true, 'Message': '', 'Code': '', 'Inventory': { 'TotalNumber': mockList.length, PageNumber, PageSize, 'ResultData': pageList } } } } ]
const axios = require('axios').default; const { query } = require("./config"); const instruments = { 'piano': 1, 'guitar': 2, 'violin': 3, 'cello': 4, 'ukulele': 5, 'flute': 6, 'saxophone': 7, 'bass guitar': 8, 'viola': 9, 'voice': 10, 'trumpet': 11, 'drums': 12, 'bassoon': 13, 'trombone': 14, 'upright bass': 15 } const insertMusicalInstrument = (name) => { return new Promise((resolve, reject) => { query( `INSERT INTO instrument(name) VALUES($1) RETURNING *`, [name], (error, results) => { if (error) { console.log(error) reject(error) } else { resolve(results.rows[0].id) } } ) }) } const insertProfileTable = ({ first_name, last_name, pickup_line, about, background, experience, city, }) => { return new Promise((resolve, reject) => { query( ` INSERT INTO profile(first_name, last_name, pickup_line, about, background, experience, city) VALUES($1,$2,$3,$4,$5,$6,$7) RETURNING * `, [first_name, last_name, pickup_line, about, background, experience, city], (error, results) => { if (error) { console.log(error) reject(error) } else { resolve(results.rows[0]) } } ) }) } const insertSkillTable = async (profile_id, skills) => { let valuesStr = `VALUES` for (let i = 0; i < skills.length; i++) { const item = skills[i]; const ins = item.instrument; const level = item.level ? item.level : "advanced"; let instrument_id = instruments[`${ins}`] if (!instrument_id) { instrument_id = await insertMusicalInstrument(ins); instruments[`${ins}`] = instrument_id; } valuesStr += `(${profile_id}, ${instrument_id}, '${level}', 1),` } valuesStr = valuesStr.slice(0, -1); return new Promise((resolve, reject) => { query( ` INSERT INTO skill(profile_id, instrument_id, level, week_frequency) ${valuesStr} `, (error, results) => { if (error) { console.log(error) reject(error) } else { resolve(results) } } ) }) } const insertPriceTable = (profile_id, pricings) => { let valuesStr = `VALUES` pricings.forEach(item => { const gross = item.gross_price ? item.gross_price : 60; const duration = item.duration ? item.duration : "60_min" valuesStr += `(${profile_id}, ${gross}, '${duration}', true),` }) valuesStr = valuesStr.slice(0, -1); return new Promise((resolve, reject) => { query( ` INSERT INTO pricing(profile_id, gross_price, duration, enabled) ${valuesStr} `, (error, results) => { if (error) { console.log(error) reject(error) } else { resolve(results) } } ) }) } const insertMediaTable = (profile_id, medias) => { let valuesStr = `VALUES` medias.forEach(item => { const tag = item.tag; const type = item.type; const url = item.url; valuesStr += `(${profile_id},'${type}', '${tag}', '${url}'),` }) valuesStr = valuesStr.slice(0, -1); return new Promise((resolve, reject) => { query( ` INSERT INTO media(profile_id, type, tag, url) ${valuesStr} `, (error, results) => { if (error) { console.log(valuesStr) reject(error) } else { resolve(results) } } ) }) } const results = axios.get("https://homemuse.io/api/v1/teachers/profiles", { }).then(async results => { const data = results.data; if (data.status === 'OK') { const teachers = data.teachers; for (let i = 0; i < teachers.length; i++) { const profile = teachers[i]; const skills = profile.skills; const pricings = profile.pricings; const medias = profile.medias; const profileInserted = await insertProfileTable(profile); await insertSkillTable(profileInserted.id, skills) insertPriceTable(profileInserted.id, pricings) insertMediaTable(profileInserted.id, medias) } } })
const parser = require('freestyle-parser'); const fileIO = require('bozoid-file-grabber'); exports.eventGroup = 'onMessage'; exports.masterOnly = 'true'; exports.commands = ['addvocab', 'av'] exports.description = 'Add vocabulary'; exports.parameters = [ { input: true, description: 'phrase' } ]; exports.script = function(cmd, msg){ let phrase = parser.getFreestyle(msg.content, 0); fileIO.update("vocabulary.json", function(obj){ if(obj.list.indexOf(phrase) == -1){ obj.list.push(phrase); //msg.channel.send("Added to vocabulary: " + phrase); msg.react("👌"); } else{ //msg.channel.send("Already added"); msg.react("👎"); } }); }
const { RootEntity, ValidationError } = require('ddd-js') const LocationId = require('./ValueObject/LocationId') const LocationName = require('./ValueObject/LocationName') class ClimateData extends RootEntity { setup () { this.registerCommand('ClimateData.updateData', async command => this.updateData( command.payload.locationId, command.payload.locationName, command.payload.temperature, command.payload.humidity )) } /** * @param {string} rawLocationId * @param {string} rawLocationName * @param {number} temperature * @param {number} humidity * @returns {Promise<Event[]>} */ async updateData (rawLocationId, rawLocationName, temperature, humidity) { this.logger.info({ rawLocationId, rawLocationName, temperature, humidity }, 'Validating command . . .') const validationError = new ValidationError() let locationId try { locationId = new LocationId(rawLocationId) } catch (err) { validationError.addInvalidField('locationId', err.message) } let locationName try { locationName = new LocationName(rawLocationName) } catch (err) { validationError.addInvalidField('locationName', err.message) } if (!temperature && temperature !== 0) { validationError.addInvalidField('temperature', `Must be a number, got ${temperature}.`) } if (!humidity && humidity !== 0) { validationError.addInvalidField('humidity', `Must be a number, got ${humidity}.`) } if (validationError.hasErrors()) throw validationError return [this.createEvent('ClimateData.dataUpdated', { locationId: locationId.getValue(), locationName: locationName.getValue(), temperature, humidity })] } } module.exports = ClimateData
var express = require('express'); var router = express.Router(); const fs = require("fs"); /* GET home page. */ router.get('/', function(req, res, next) { res.render('index', { title: 'RM-RN' }); }); // обработка строки router.post("/", function (req, res, next) { //res.status = 200; var reqBody = ""; // извлечь данные req.on('data', (chunk) => { reqBody += chunk; }); // как только все прочитано, обработать и ответить req.on("end", function () { res.setHeader("Content-Type", "text/plain,charset=UTF-8") var result = reqBody.replace(/[\r\n]+/g, ' '); res.end(result); }); req.on("error", function (err) { next(err); }); }); module.exports = router;
var Modeler = require("../Modeler.js"); var className = 'TypeArrayOfErhistoryitem'; var TypeArrayOfErhistoryitem = function(json, parentObj) { parentObj = parentObj || this; // Class property definitions here: Modeler.extend(className, { erhistoryitem: { type: "Typeerhistoryitem", wsdlDefinition: { minOccurs: 0, maxOccurs: "unbounded", name: "erhistoryitem", nillable: true, type: "tns:erhistoryitem" }, mask: Modeler.GET | Modeler.SET | Modeler.ARRAY, required: false } }, parentObj, json); }; module.exports = TypeArrayOfErhistoryitem; Modeler.register(TypeArrayOfErhistoryitem, "TypeArrayOfErhistoryitem");
$(function(){ // 对外接口 window._ide = {}; var initConfigModal = function() { $("#property-table").hide(); $("#slider-width").on('slide', function(evt) { if(evt.value == "13") { $("#width-value").text("自定义"); } else { $("#width-value").text(evt.value + "/12"); } }); $('.rule-selector .list-group-item').on('click', function() { var ruleMenu = $("#rule ul li.active a").attr("data-id"); $('#'+ruleMenu+' .rule-selector .list-group-item').removeClass('active'); $(this).addClass('active'); }); $("#property-table tbody").sortable({ connectWith: 'tr', opacity : 0.35, handle: ".property-drag" }); $("#property-table tr").draggable({ connectToSortable: "#property-table tbody", handle: ".property-drag", }); $('#property-tab').on('show.bs.tab', function (e) { $("#propertyselect").selectpicker('show'); $("#property-table").hide(); }); $('#model-tab').on('show.bs.tab', function (e) { $("#propertyselect").selectpicker('hide'); $("#property-table").show(); }); $('#list-tab').on('show.bs.tab', function (e) { $("#propertyselect").selectpicker('hide'); $("#property-table").show(); }); $("#objectselect").on("change", function(e, callback) { showLoading(); var id = $(this).val(); var name = $("option:selected", this).attr("data-objectname"); $.ajax({ type: "POST", dataType: 'json', url: "/property/get.html", data: { objectid : id }, success: function(ps) { hideLoading(); var setting = $.grep(controls, function(c){ return c["control_identity"] == current.attr("control-identity"); })[0]; $("#property-table tbody tr").remove() for(var i in ps) { var p = ps[i]; var tr = "<tr><td class='readonly'><i class='glyphicon glyphicon-sort property-drag'></i></td>"; tr += "<td class='readonly' data-propertyname='" + p.name + "'>" + p.alias + "</td>"; tr += "<td>" + p.alias + "</td>"; tr += "<td class='readonly'><a href='#' onclick='$(this).parent().parent().remove();'><i class='glyphicon glyphicon-remove'></i></a></td></tr>"; $("#property-table tbody").append(tr); } $("#property-table").editableTableWidget(); $("#propertyselect option").remove(); $("#condition-table tbody tr").remove(); for(var i in ps) { var p = ps[i]; $("#propertyselect").append("<option value='" + p.name + "'>" + p.alias + "</option>"); } if($("#propertyselect option").length > 0) { $("#propertyselect").prop('disabled', false); $("#propertyselect").selectpicker('refresh'); } else { $("#propertyselect option").remove(); $("#propertyselect").append("<option value=''>选择属性</option>"); $("#propertyselect").prop('disabled', true); $("#propertyselect").selectpicker('refresh'); } if ( typeof callback === 'function' ){ callback(); } } }); }); $("#save-config").click(function(){ var cid = current.attr("control-identity"); var setting = $.grep(controls, function(c){ return c["control_identity"] == cid; })[0]; if(!setting) { setting = { "control_identity" : cid, "control_key" : current.attr("control-key"), "control_settings" : {}, "rule_key" : "", "rule_settings" : {} }; controls.push(setting); } rule_key = setting.rule_key; //保存规则配置 var ruleMenu = $("#rule ul li.active a").attr("data-id"); var ruleid = $("#"+ruleMenu+" .rule-selector .list-group-item.active").attr("rule-key"); var rule_type = $("#"+ruleMenu+" .rule-selector .list-group-item.active").attr("data-type"); ruleid = ruleid ? ruleid : ""; current.attr("rule-key", ruleid); if(ruleid && rule_key != ruleid) { setting["rule_key"] = ruleid; setting["rule_settings"] = { "input" : {}, "output" : {} }; $("#rule-input-table tbody tr").each(function() { var key = $("td:first", this).text().trim(); var value = $("td:last", this).text().trim(); if(rule_type == "remote") { if( key !="") setting["rule_settings"]["input"][key] = value; } else { if(key && value) { setting["rule_settings"]["input"][key] = value; } } }); $("#rule-output-table tbody tr").each(function() { var key = $("td:first", this).text().trim(); var value = $("td:last", this).text().trim(); if(key && value) { setting["rule_settings"]["output"][key] = value; } }); } //保存数据配置 if($("#objectselect").val()) { var objectname = $("#objectselect option:selected").attr("data-objectname"); var propertyname = $("#propertyselect").val(); var condition = { } $("#condition-table tbody tr").each(function() { var p = $("td:eq(0) select", this).val(); var o = $("td:eq(1) select", this).val(); var v = $("td:eq(2) input", this).val(); if(p) { try{ v = $.parseJSON(v); }catch(e){} if(o == "等于") { condition[p] = v; } else if(o == "大于") { condition[p] = { "$gt" : v } } else if(o == "小于") { condition[p] = { "$lt" : v } } else if(o == "不等于") { condition[p] = { "$ne" : v } } } }); var headers = [] $("#property-table tbody tr").each(function() { var key = $("td:eq(1)", this).attr("data-propertyname"); var value = $("td:eq(2)", this).text().trim(); if(key) { headers.push([key, value]) } }); var dt = $("#data .nav-tabs li.active a").text(); ruleid = $("#data .nav-tabs li.active a").attr("rule-key"); current.attr("rule-key", ruleid); if("rule_key" in setting && rule_key != ruleid && ruleid != setting["rule_key"]) { setting["rule_key"] = ruleid; setting["rule_settings"] = { "input" : {}, "output" : {} }; } if(dt == "对象属性") { setting["rule_settings"]["input"]["objectname"] = objectname; setting["rule_settings"]["input"]["propertyname"] = propertyname; setting["rule_settings"]["input"]["condition"] = condition; } else if(dt == "对象实体") { setting["rule_settings"]["input"]["objectname"] = objectname; setting["rule_settings"]["input"]["condition"] = condition; setting["rule_settings"]["output"]["headers"] = headers; } else if(dt == "对象列表") { setting["rule_settings"]["input"]["objectname"] = objectname; setting["rule_settings"]["input"]["condition"] = condition; setting["rule_settings"]["output"]["headers"] = headers; } else if(dt == "接口数据") { } } //保存模板配置 setting["control_settings"] = { "input" : {} } $("#control-input-table tbody tr").each(function() { var key = $("td:first", this).text().trim(); var value = $("td:last", this).text().trim(); if(key && value) { setting["control_settings"]["input"][key] = jQuery.parseJSON(value); } }); $("#config-modal").modal('hide'); }); } var initHtmlEditor = function() { editor = CodeMirror.fromTextArea($('#_ide_htmlsource textarea')[0], { mode: 'text/html', styleActiveLine: true, lineNumbers: true, lineWrapping: true, autoCloseTags: true, indentUnit: 4, extraKeys: {"Ctrl-Space": "autocomplete"}, onKeyEvent: function (e, s) { if (s.type == "keyup" && s.keyCode == 188) { CodeMirror.showHint(e); } } }); editor.setSize("100%", $(window).height()-53); } window._ide.openConfigModal = function(elm){ current = $(elm).parent(); var cid = current.attr("control-identity"); showRuleSelector(); var setting = $.grep(controls, function(c){ return c["control_identity"] == current.attr("control-identity"); })[0]; if(!setting) { setting = {}; } recommendRule(setting.control_key); $("#property-tab").tab('show'); window.setTimeout(function() { if("rule_key" in setting) { var key = "#data .nav-tabs li a[rule-key='" + setting.rule_key + "']"; $(key).tab('show'); // key_all = "#all .rule-selector .list-group-item[rule-key='" + setting.rule_key + "']"; // $("#all .rule-selector .list-group-item").removeClass("active"); // $(key_all).addClass("active"); var list = ["all","recommend","local","remote"]; for(var i=0;i<list.length;i++) { key = "#"+list[i]+" .rule-selector .list-group-item[rule-key='" + setting.rule_key + "']"; html = $(key).html(); if( html == "" || html == undefined) { $("#"+list[i]+" .rule-selector a").eq(0).addClass("active"); } else { $("#"+list[i]+" .rule-selector .list-group-item").removeClass("active"); $(key).addClass("active"); } } } }, 200); if("rule_settings" in setting && "input" in setting.rule_settings && "objectname" in setting.rule_settings.input) { key = "#objectselect option[data-objectname='" + setting.rule_settings.input.objectname + "']"; var v = $(key).attr("value"); if(v) { $("#objectselect").val(v); $("#objectselect").selectpicker("render"); $("#objectselect").trigger("change", function() { if("rule_settings" in setting && "input" in setting.rule_settings && "objectname" in setting.rule_settings.input && "propertyname" in setting.rule_settings.input && $(key).attr("data-objectname") == setting.rule_settings.input.objectname) { $("#propertyselect").val(setting.rule_settings.input.propertyname); $("#propertyselect").selectpicker("render"); } if("rule_settings" in setting && "input" in setting.rule_settings && "condition" in setting.rule_settings.input) { $.each(setting.rule_settings.input.condition, function(k, v){ newcondition($("#condition-table"), $("#propertyselect")); $("#condition-table tbody tr:last td:eq(0) select").val(k); $("#condition-table tbody tr:last td:eq(0) select").selectpicker("render"); if(typeof(v) == "object") { $.each(v, function(o, d){ if(o == "$gt") { $("#condition-table tbody tr:last td:eq(1) select").val("大于"); } else if(o == "$lt") { $("#condition-table tbody tr:last td:eq(1) select").val("小于"); } else if(o == "$ne") { $("#condition-table tbody tr:last td:eq(1) select").val("不等于"); } $("#condition-table tbody tr:last td:eq(1) select").selectpicker("render"); $("#condition-table tbody tr:last td:eq(2) input").val($.toJSON(d)); }); } else { $("#condition-table tbody tr:last td:eq(2) input").val(v); } }); } if("rule_settings" in setting && "output" in setting.rule_settings && "headers" in setting.rule_settings.output) { $("#property-table tbody tr").remove(); $.each(setting.rule_settings.output.headers, function(index, h) { key = "#propertyselect option[value='" + h[0] + "']"; var alias = $(key).text(); var tr = "<tr><td class='readonly'><i class='glyphicon glyphicon-sort property-drag'></i></td>"; tr += "<td class='readonly' data-propertyname='" + h[0] + "'>" + alias + "</td>"; tr += "<td>" + h[1] + "</td>"; tr += "<td class='readonly'><a href='#' onclick='$(this).parent().parent().remove();'><i class='glyphicon glyphicon-remove'></i></a></td></tr>"; $("#property-table tbody").append(tr); }); $("#property-table").editableTableWidget(); } }); } } $('#normal-tab').tab('show'); $("#config-modal").modal('show'); }; var bindRemoveEvent = function() { $('#_ide_workspace').delegate('.remove','click',function(event) { var elm = $(this).parent(); // 如果删除了layout惟一一个control,就恢复layout可接收control拖动 if ( elm.hasClass('control') && elm.siblings().length == 0 ){ parent.$(this).parent().parent().droppable( "option", "accept", ".layout, .control" ); } event.preventDefault(); handleRemoveControl(elm) elm.remove(); if(!$('#_ide_workspace .layout').length > 0) { clearWorkspace(); } }); } var bindCustomGirdEvent = function() { $('.layout .preview input').bind('keyup',function(){ var sum = 0; var src = ''; var invalidValues = false; var cols = $(this).val().split(" ",12); $.each(cols, function(index,value){ if(!invalidValues) { if(parseInt(value) <= 0) invalidValues = true; sum = sum + parseInt(value) src += '<div class="col-lg-'+value+' column"></div>'; } }); if(sum==12 && !invalidValues) { $(this).parent().next().children().html(src); $(this).parent().prev().show(); } else { $(this).parent().prev().hide(); } }); } var clearWorkspace = function() { $('#_ide_workspace').empty(); } var buildLayoutHtml = function() { var html = $('<div>').html($('#_ide_workspace').html()); //$('#_ide_html').html($('#_ide_workspace').html()); //var html = $('#_ide_html'); html.find(".control").each(function() { // TODO: 每个控件都会有 id 对应到 control_id $(this).attr('id', 'control_' + $(this).attr('control-identity')) $(this).attr("page-id", id); if(typeof($(this).attr('rule-key')) != 'undefined' && $(this).attr('rule-key') != '') { var src = "{% module Template('share/control/{0}.control', **get_control_context(context, '{1}')) %}"; src = String.format(src, $(this).attr('control-key'), $(this).attr('control-identity')); $(".view", this).html(src); $(this).attr('id', 'control_' + $(this).attr('control-identity')) } }); html.find('.preview, .config, .drag, .remove, .move, .designtool').remove(); html.find('.layout').addClass('removeClean'); html.find('.control').addClass('removeClean'); html.find('.layout .layout .layout .layout .layout .removeClean').each(function(){ cleanHtml(this) }); html.find('.layout .layout .layout .layout .removeClean').each(function(){ cleanHtml(this) }); html.find('.layout .layout .layout .removeClean').each(function(){ cleanHtml(this) }); html.find('.layout .layout .removeClean').each(function(){ cleanHtml(this) }); html.find('.layout .removeClean').each(function(){ cleanHtml(this) }); html.find('.removeClean').each(function(){ cleanHtml(this) }); $('.removeClean', html).removeClass('removeClean'); $('.ui-draggable', html).removeClass('ui-draggable'); $('.column', html).removeClass('ui-sortable'); $('.row', html).removeClass('clearfix').children().removeClass('column'); var firstchild = html.children(":first"); if($(html.children()).length == 1 && $(firstchild).is("div") && $(firstchild).hasClass("layout")) { html.html(firstchild.html()); } // TODO: 找时间换了这蛋疼的 HtmlClean //var formatSrc = html.html(); // try { // formatSrc = $.htmlClean($('#_ide_html').html(), { // format:true, // allowedAttributes:[ // ['id'], ["class"], ['data-toggle'], ['data-target'], ['data-parent'], ['role'], ['data-dismiss'], ['aria-labelledby'], // ['aria-hidden'], ['data-slide-to'], ['data-slide'], ['control-key'], ['control-identity'], ['rule-key'], ['data-id'], // ["page-id"], ['style'], // ] // }); // } catch( exception ) { // formatSrc = $("#_ide_html").html(); // } //if(!formatSrc) { // // 保存出问题啦... // alert("保存 html 出错,暂时用提示框,不要介意~"); // return; //} //html.html(formatSrc); return html.html(); } var cleanHtml = function(elm) { $(elm).html($(elm).children().html()); } var handleAddControl = function(control) { var id; do{ id = newGuid(); }while( $('[control-identity=' + id + ']').length > 0 ) $(control).attr("control-identity", id) var control_key = $(control).attr("control-key") controls.push({ "control_identity" : id, "control_key" : control_key, "control_settings" : {}, "rule_key" : "", "rule_settings" : {} }) } var handleRemoveControl = function(elm){ var id = elm.attr("control-identity"); if (id != undefined){ controls = $.grep(controls, function(c) { return c["control_identity"] != id }); } else { $.each(elm.find('.control'), function(index,dom){ handleRemoveControl($(dom)); }); } } var showRuleConfig = function(params) { var cid = current.attr("control-identity"); $("#rule-input-table tbody tr").remove(); $("#rule-output-table tbody tr").remove(); var grep = $.grep(controls, function(c){ return c["control_identity"] == cid; }); if(grep.length > 0) { if(params != "" && params.length > 2 && grep[0]["rule_key"] == "" ) { var str = params.split(","); for (var i=0 ; i < str.length ; i++) { $("#rule-input-table tbody").append("<tr><td>" + str[i] + "</td><td></td></tr>"); } } else { var input = grep[0]["rule_settings"].input; for (var i in input) { $("#rule-input-table tbody").append("<tr><td>" + i + "</td><td>" + $.toJSON(input[i]) + "</td></tr>"); } } var output = grep[0]["rule_settings"].output; for (var i in output) { $("#rule-output-table tbody").append("<tr><td>" + i + "</td><td>" + $.toJSON(output[i]) + "</td></tr>"); } } $("#rule-input-table tbody").append("<tr><td>&nbsp;</td><td>&nbsp;</td></tr>"); $("#rule-input-table").editableTableWidget(); $("#rule-input-table td").on("change", tdchange); $("#rule-output-table tbody").append("<tr><td>&nbsp;</td><td>&nbsp;</td></tr>"); $("#rule-output-table").editableTableWidget(); $("#rule-output-table td").on("change", tdchange); $(".rule-selector").hide(); $("#rule-config").fadeIn("slow"); } var showRuleSelector = function() { var au = $('#config-modal .rule-selector .active'); $("#rule-config").hide(); $(".rule-selector").fadeIn("show"); setTimeout(function () { au.addClass("active"); }, 50); } var saveLayout = function(callback){ var html = buildLayoutHtml(); // 删除selectpicker 自动生成的代码 // 不然下次select,还会生成一次 // 那样就有两个selectpicker 了 var tmp = $('#_ide_workspace').clone(); tmp.find('.bootstrap-select').remove(); // 可以自定义哪些应该要删除 tmp.find('.remove-design').remove(); $.ajax({ type: "POST", dataType: 'json', url: "save.html", data: {target : target, id : id, html : html, design : tmp.html(), settings : JSON.stringify(settings), controls : JSON.stringify(controls), options : JSON.stringify(options)}, success: function(result) { if(callback) { callback(result); } }, error: function (XHR, textStatus, errorThrown) { // TODO: 出错了就要有出错的处理...牛叉人写代码才只考虑成功... hideLoading(); } }); } var tdchange = function(evt, value) { var tb = $(this).parent().parent().parent(); if($("tr:last", tb).text().trim()) { $("tr:last", tb).after("<tr><td>&nbsp;</td><td>&nbsp;</td></tr>"); tb.editableTableWidget(); $("tr:last td", tb).on("change", tdchange); } if(!$(this).parent().text().trim()) { $(this).parent().remove(); } } var newcondition = function(tb, pss) { if (!pss.val()) { return; } var ops = "<select data-width='100px'><option>等于</option><option>大于</option><option>小于</option><option>不等于</option></select>"; var minus = "<a href='#' onclick='$( this).parent().parent().remove()'><i class='glyphicon glyphicon-minus'></i></a>"; $("tbody", tb).append("<tr><td></td><td>" + ops + "</td><td><input class='form-control' /></td><td style='padding-top:10px;'>" + minus + "</td></tr>"); var elm = $("<select data-width='100px'></select>"); $("option", pss).each(function() { elm.append($(this).clone()); }); $("tbody tr:last td:first", tb).append(elm); elm.selectpicker(); elm.next().css("margin", "0px"); $("tbody tr:last td:eq(1) select", tb).selectpicker(); $("tbody tr:last td:eq(1) select", tb).next().css("margin", "0px"); } var newGuid = function() { function G() { return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1) } var guid = (G() + G() + G() + G() + G() + G() + G() + G()).toUpperCase(); return guid } String.format = function() { if (arguments.length == 0) return null; var str = arguments[0]; for ( var i = 1; i < arguments.length; i++) { var re = new RegExp('\\{' + (i - 1) + '\\}', 'gm'); str = str.replace(re, arguments[i]); } return str; }; var trim = function(str) { str = str.replace(/^(\s|\u00A0)+/,''); for(var i=str.length-1; i>=0; i--){ if(/\S/.test(str.charAt(i))){ str = str.substring(0, i+1); break; } } return str; } var ruleMenuClick = function() { $("#rule-config").hide(); $(".rule-selector").fadeIn("slow"); } //获取相匹配的规则 controlId:模板ID var recommendRule = function(controlId) { showLoading(); $("#recommend div").html(""); var data = {"controlId": controlId}; $.ajax({ type: 'post', url: "/ide/recommendrule.html", dataType: 'json', data: data, timeout: 5000, success: function (results) { hideLoading(); if(results && results.status && results.status == "ok") { var result = results.result; var arr = jsonByValueSort(result); for(var i =0; i < arr.length ; i++) { var key = arr[i]; var html = "<a href='#' class='list-group-item' rule-key='"+ key +"' data-type='"+result[key][3]+"'><h4 class='list-group-item-heading'>"+result[key][0]+"<span class='pull-right' onclick='showRuleConfig(\""+result[key][1]+"\")'><i class='glyphicon glyphicon-cog'></i></span><span style='float:right;padding-right:30px'>匹配率:<strong style='color:red;'>"+ result[key][2] +"%</strong></span></h4></a>"; $("#recommend div").append($(html)); } $("#recommend div a").attr("onclick","recommendOnclick(this)"); } else { $("#recommend div").append('<h4 class="list-group-item-heading" style="color:red;">非常遗憾,没有找到你想要的规则</h4>'); } }, error: function (req, status, error) { hideLoading(); if (req.responseText) { $('#errormodal .modal-body').text(req.responseText); } $('#errormodal').modal('show'); }, }); } var recommendOnclick = function(obj) { $('#recommend .rule-selector .list-group-item').removeClass('active'); $(obj).addClass('active'); } // json根据value从大到小排序 返回array var jsonByValueSort = function(json) { length = getJsonLength(json); var item = new Array(); for(var i = 0; i < length; i++) //初始化数组 { item[i] = new Array(); for(var j=0; j < 2; j++) { item[i][j] = 0 ; } } var index = 0; for(var i in json) //将要排序的value放入array[index][0] , key放入 array[index][1] { item[index][0] = json[i][2]; item[index][1] = i ; index++; } item.sort(function(x, y) //根据 array[index][0] 排序 (desc) { return y[0] - x[0]; }); result = new Array(); for(var i = 0; i < length; i++) //排序后提取array[index][1] (key) { result[i] = item[i][1]; } return result } //获取json的length var getJsonLength = function(json) { var length = 0; for(var item in json) { length++; } return length; } var addScripts = function(control){ if( !scripts ) return $.each(scripts, function(key, value){ }) } var ScriptManager = { cache: [], add: function(uid){ if( !(uid in control_script_dict) ) return this._add_css(control_script_dict[uid].css); this._add_js(control_script_dict[uid].js); }, _add_css: function(keys){ var html = ''; for(x in keys){ var key = keys[x]; if( this.cache.indexOf(key) == -1 ){ html += '<link rel="stylesheet" href="/' + script_paths[key] + '">'; this.cache.push(key); } } if( html != '' ) $('head').append(html) }, _add_js: function(keys){ var html = ''; for(x in keys){ var key = keys[x]; if( this.cache.indexOf(key) == -1 ){ html += '<script type="text/javascript" src="/' + script_paths[key] + '"></script>'; this.cache.push(key); } } if( html != '' ) $('head').append(html) }, } var initScripts = function(){ $.each(controls, function(i, control){ ScriptManager.add(control.control_key); }) ScriptManager._add_css(default_script_paths.css); ScriptManager._add_js(default_script_paths.js); } var initSortable = function(){ $('#_ide_workspace').sortable({ connectWith: '.column', opacity: 0.35, handle: '.drag', }) } var initMoveable = function(){ var _selected = null; $('#_ide_workspace').on('click', '.control > .move, .layout > .move', function(event){ event.stopPropagation(); _selected = $(this).parent(); $(_selected).addClass("selected_moveable") $(".column").hover(function() { $(this).addClass("hoveing_col"); }, function() { $(this).removeClass("hoveing_col"); }); }) $('#_ide_workspace').on('click', '.column', function(event){ if ( _selected === null ){ return }else{ event.stopPropagation(); if ( !$(this).parents('.control:first, .layout:first').is(_selected) ){ _selected.appendTo($(this)); } $(_selected).removeClass("selected_moveable") $(".column").removeClass("hoveing_col").unbind("mouseenter mouseleave"); _selected = null; } }) } /* * 为了性能,在ide左侧,控件不会自动加载。而是转义为字符串 * 这里将$(control .view) 转为dom结构 */ var enableControl = function(elm){ var view = elm.find('.view'); view.html(view.text()); return elm } /* * 在右边设计区域,增加一个控件 * 这个方法一般由 /templates/ide/ide/index.html 调用 */ var addControl = function(elm){ elm = enableControl(elm); if ( elm.data('noidentity') ){ // 清掉 identity 才能绑定事件 $(elm).removeAttr("control-identity"); } else { handleAddControl(elm); } ScriptManager.add($(elm).attr("control-key")); replaceCurrentControl(elm); } /* * 在右边设计区域,替换一个控件 * 这个方法一般由 /templates/ide/ide/index.html 调用 */ var replaceControl = function(old_elm, new_elm){ var control_identity = old_elm.attr('control-identity'); new_elm = enableControl(new_elm); $.each(controls, function(i, control){ if ( control.control_identity == control_identity ){ old_elm.attr('control-key', new_elm.attr('control-key')); new_elm.attr('control-identity', old_elm.attr('control-identity')); control.control_key = new_elm.attr('control-key'); control.replaced = true; return false; } }) // 如果这个控件有绑定资源,自动加载 ScriptManager.add($(new_elm).attr("control-key")); replaceCurrentControl(new_elm); $(old_elm).html( new_elm.html() ); } var addLayout = function(container){ var elm = $(container).find('.column'); elm.sortable({ connectWith: '.column', opacity: 0.35, handle: '.drag', }) if (elm.hasClass("module") ){ var settings_dom = elm.find('div.settings') if(settings_dom){ category_id = settings_dom.attr('data-category'); $.each(jQuery.parseJSON(settings_dom.html()), function(i, c){ c['category_id'] = category_id; controls.push( c ); }); } } } var Control = function(control){ this.id = $(control).attr("identity"); this.control = control; this.btn_temp = '<a href="#" class="config label label-default remove-design"><i class="glyphicon glyphicon-cog"></i></a>' return this; } Control.prototype.addCustomBtn = function(func, title){ if ( typeof func != 'function' ){ throw func.toString() + ' not a function.'; } var btn = $(this.btn_temp), last = this.control.children('.config:last'), lastLocal = parseInt(last.css('right')), lastWidth = last.outerWidth(); if ( typeof title == 'string' ){ btn.text(title); } btn.css('right', lastLocal + lastWidth + 5); btn.on('click', func); last.after(btn); return this; } /* * 替换控件脚本里面的 current_control_identity * 让控件可以得到它所在的控件ID */ var replaceCurrentControl = function(control){ var scripts = control.find('script'); $.each(scripts, function(i, script){ $(script).text( $(script).text().replace(/{current_control_identity}/g, control.attr('control-identity')) ); }) } var _ide_before_saves = []; push_before_saves = function(func){ _ide_before_saves.push(func); } var setFieldMapping = function setFieldMapping(identity, data) { var propertyDict = propertys[identity] || {}, control = new window._ide.Control(get_control(identity)), $container = $('.field-map-modal'), $body = $(".modal-body table>.tbody", $container), setField = { showHtml :function(){ if($.isEmptyObject(data)){ return ; } var fields = []; for(var key in propertyDict) { if(key == '__parent_propertys__'){ continue; } fields.push(key); } $body.empty(); for(var key in data){ if ( !data.hasOwnProperty(key) ){ continue; } var description = data[key].description, $options = '', $trHtml = $('<tr><td>' + key + '</td><td class="select-td"></td><td>' + description + '</td></tr>'), $selectHtml = $('<select class="form-control select-field" value="'+ key +'"></select>'); $.each(fields, function(index, value) { $options += '<option>' + value + '</option>'; }); $selectHtml.html($options); $trHtml.find(".select-td").html($selectHtml); $('.select-field').last().selectpicker('render'); $body.append($trHtml); } }, saveField :function(){ var optionDict = options[identity] || {}, fieldMapping = {}; $("tr", $body).each(function(){ var attrName = $(this).find("td:first").html(), attrval = $(this).find("td:eq(1)").find('.select-field').val(); fieldMapping[attrval] = attrName; }); optionDict['fieldMapping'] = fieldMapping; options[identity] = optionDict }, showBeforeData:function(){ if (window.options[identity] && window.options[identity]['fieldMapping']) { var fieldData = window.options[identity]['fieldMapping']; for(var key in fieldData){ var currentSelect = $('select.select-field[value='+fieldData[key]+']'); currentSelect.val(key); currentSelect.selectpicker('refresh'); } } } }; if ($.isEmptyObject(propertyDict)) { return; } setField.showHtml(); $(".save-field", $container).on('click', setField.saveField); $container.on('shown.bs.modal',setField.showBeforeData); control.addCustomBtn(function(){ $(".field-map-modal").modal('show'); }, '字段映射'); }; // 对外接口 $.extend(window._ide, { model: function(type){ if( type == 'dev' ){ $('body').removeClass('source preview'); $('body').addClass('dev'); }else if( type == 'preview'){ $('body').removeClass('dev source'); $('body').addClass('preview'); }else if( type == 'source' ){ editor.setValue( buildLayoutHtml() ); $('body').removeClass('dev preview'); $('body').addClass('source'); editor.refresh(); editor.focus(); } }, clear: function(){ clearWorkspace(); }, save: function(){ showLoading(); $.each( _ide_before_saves, function(i, func){ // TODO 新的控件替换旧的控件会出现两个callback,其中属于旧控件的callback可能报错。因为html已经被替换 // 暂时没有好的办法解决。暂时就这样。 /* try{ func(); }catch(err){ } */ func(); }); saveLayout(function(result){ hideLoading(); if(result.status == "ok") { $('#result-modal .modal-body').html("保存成功!"); }else{ $('#result-modal .modal-body').html("保存失败!<br/> " + result.message); } $('#result-modal').modal('show'); }); }, // ide.configmodal.html showRuleConfig: showRuleConfig, showRuleSelector: showRuleSelector, newcondition: newcondition, addLayout: addLayout, addControl: addControl, replaceControl: replaceControl, Control: Control, setFieldMapping: setFieldMapping, init_control_layout: function(){ parent.init_control_layout.apply(this, arguments); } }); $(window).resize(function(){ editor.setSize("101%", $(window).height()-53); $('#_ide_workspace').css('min-height',$(window).height() - 70); }); var init = function(){ $('#_ide_workspace').css('min-height',$(window).height() - 70); $("#rule ul li a").bind("click",ruleMenuClick); $('#_ide_workspace').sortable({ connectWith: '.layout, #_ide_workspace', opacity: 0.35, handle: '.drag', }) initHtmlEditor(); initConfigModal(); bindRemoveEvent(); bindCustomGirdEvent(); initScripts(); initSortable(); initMoveable(); } /* * 外部api */ Designer = {} Designer.modal = $('#ide_page_modal'); Designer.modal.find('.ide_page_select').selectpicker().on('change', function(event){ event.preventDefault(); Designer.modal.modal('hide'); var pid = $(this).children(':selected').data('pageid'); if ( pid in pages ){ Designer.callback(pages[pid], Designer.callback_context); } }) Designer.getPages = function(){ return pages } Designer.selectPage = function(callback, callback_context){ this.callback = callback; this.callback_context = callback_context; this.modal.modal('show'); } Designer.getRelatePage = function(object, name){ } /* * 开始 */ init(); })
import axios from 'axios'; const esv = axios.create({ baseURL: 'https://api.esv.org/v3/passage/', headers: { Authorization: process.env.REACT_APP_CROSSWAY_API_KEY, }, }); export default esv;
import React from 'react'; import styled, {keyframes} from "styled-components"; const spin = keyframes` 0% { -webkit-transform: rotate(0deg); } 100% { -webkit-transform: rotate(360deg); } 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } } ` const Loader = styled.div` position: absolute; left: 50%; top: 50%; z-index: 1; width: 120px; height: 120px; margin: -76px 0 0 -76px; border: 16px solid #f3f3f3; border-radius: 50%; border-top: 16px solid ${(props) => (props.second ? "red" : "#3498db")}; animation: ${spin} 2s linear infinite; ` export default function StyleComponentPage() { return ( <div> <h3>Styled Component</h3> <Loader second></Loader> </div> ) }
/* global chai describe Rectangle it: true */ var expect = chai.expect; describe('矩形计算器面积计算功能测试', function(){ it('宽度和高度是整数', function(){ var r = new Rectangle(4, 5); expect(r.area()).to.be.equal(20); }); /* it('宽度和高度是小数', function() { }); */ it('宽度和高度是整数字符串', function() { var r = new Rectangle('4', '5'); expect(r.area()).to.be.equal(20); }); }); describe('矩形计算器周长计算功能测试', function(){ it('宽度和高度是整数', function(){ var r = new Rectangle(4, 5); expect(r.perimeter()).to.be.equal(18); }); /* it('宽度和高度是小数', function() { }); */ it('宽度和高度是整数字符串', function() { var r = new Rectangle('4', '5'); expect(r.perimeter()).to.be.equal(18); }); });
module.exports = { build: { src: ['_src/js/application.js'], dest: 'assets/js/application.min.js' } }
import React from 'react'; import { graphql } from 'react-apollo'; import { getMovieQuery } from '../queries/queries'; const MovieDetails = (props) => { const displayMovieDetails = () => { const { movie } = props.data; if (movie) { return ( <div> <h2> {movie.name} ({movie.year}) </h2> <p>Language: {movie.language.name} </p> <p>Genre: {movie.genre.name} </p> <p> Director: {movie.director.name} ({movie.director.country.name}) </p> <p>Other Movies by this director:</p> <ul className='other-movies'> {movie.director.movies.map((item) => { if (item.name !== movie.name) { return ( <li key={item.id}> {item.name} ({item.year}) </li> ); } else { return <div id='no-data'></div>; } })} </ul> </div> ); } else { return <div>No movie selected...</div>; } }; return ( <div className='movie-details' id='movie-details'> {displayMovieDetails()} </div> ); }; export default graphql(getMovieQuery, { options: (props) => { return { variables: { id: props.movieID, }, }; }, })(MovieDetails);
import React from 'react'; import { ThemeProvider, useMediaQuery, createMuiTheme, CssBaseline, } from '@material-ui/core'; import { StylesProvider } from '@material-ui/core/styles'; /** * Handles Top-Level Providers for Materials Theme and Style APIs. * Set's CSS baseline using Material's CSSBaseline Component */ const Provider = (props) => { const useDarkMode = useMediaQuery('(prefers-color-scheme: dark)'); // Set theme base on user dark mode preferences const theme = React.useMemo(() => createMuiTheme({ palette: { type: useDarkMode ? 'dark' : 'light', }, }), [useDarkMode], ); return ( <StylesProvider> <ThemeProvider theme={theme}> <CssBaseline /> {props.children} </ThemeProvider> </StylesProvider> ); }; export default Provider;
var searchData= [ ['reverse_5fiterator_218',['reverse_iterator',['../classoptionpp_1_1option__group.html#ab4cd57d16fa640b1d23ecf656c4bfb74',1,'optionpp::option_group::reverse_iterator()'],['../classoptionpp_1_1parser__result.html#a88faad791f285357247b056484e7cb13',1,'optionpp::parser_result::reverse_iterator()']]] ];
export const PROFILE_LIST_REQUEST = "PROFILE_LIST_REQUEST"; export const PROFILE_LIST_SUCCESS = "PROFILE_LIST_SUCCESS"; export const PROFILE_LIST_FAIL = "PROFILE_LIST_FAIL"; export const CLEAN_PROFILE_LIST = "CLEAN_PROFILE_LIST"; export const PROFILE_DETAILS_REQUEST = "PROFILE_DETAILS_REQUEST"; export const PROFILE_DETAILS_SUCCESS = "PROFILE_DETAILS_SUCCESS"; export const PROFILE_DETAILS_FAIL = "PROFILE_DETAILS_FAIL"; export const CLEAN_PROFILE_DETAILS = "CLEAN_PROFILE_DETAILS"; export const GET_MORE_PROJECTS_REQUEST = "GET_MORE_PROJECTS_REQUEST"; export const GET_MORE_PROJECTS_SUCCESS = "GET_MORE_PROJECTS_SUCCESS"; export const GET_MORE_PROJECTS_FAIL = "GET_MORE_PROJECTS_FAIL";
import React from 'react'; import {Col, Row} from 'antd'; import ProductItem from './ProductItem'; const ProductList = ({hits}) => { return ( <div id="product"> <Row> {hits.map(product => ( <Col xl={8} lg={12} md={12} sm={12} xs={24}> <ProductItem item={product} key={product.objectID}/> </Col> ))} </Row> </div> ); }; export default ProductList;
import React, { Component } from 'react'; import { G2, Chart, Geom, Axis, Tooltip, Coord, Label, Legend, View, Guide, Shape, Facet, Util } from "bizcharts"; import DataSet from "@antv/data-set"; import moment from 'moment'; export default class UnanswerBar extends Component{ render() { const data = this.props.nonResponseDow; const ds = new DataSet(); const dv = ds.createView().source(data); dv.transform({ type: "fold", fields: ["total_count", "processed_count"], key: "항목", value: "건수" }); return ( <div> <Chart height={220} data={dv} forceFit onTooltipChange={(ev)=>{ var items = ev.items; var total_count= items[0]; var processed_count= items[1]; total_count.name = '발생량' processed_count.name = '처리량' total_count.title = moment(total_count.title).format('MM월DD일') processed_count.title = moment(processed_count.title).format('MM월DD일') total_count.value = `${total_count.value} 건` processed_count.value = `${processed_count.value} 건` }} > <Axis name="datetime" label={{ formatter: val => moment(val).format('MM월 DD일') }} /> <Axis name="건수" label={{ formatter: val => `${val} 건` }} /> <Legend custom={true} allowAllCanceled={true} items={[ { value: "발생량", name: "total_count", marker: { symbol: "square", fill: "#f85032", radius: 5 } }, { value: "처리량", name: "processed_count", marker: { symbol: "square", fill: "#72D2EA", radius: 5, } } ]} /> <Tooltip crosshairs={{ type: "y" }} /> <Geom type="interval" position="datetime*건수" color={['항목', 항목=>{ if(항목 === 'total_count'){ return '#f85032' }else{ return '#72D2EA' } }]} size={10} adjust={[ { type: "dodge", marginRatio: 1 / 32 } ]} /> </Chart> </div> ); } }
import React from 'react'; import { Switch, Route, } from "react-router-dom"; import { default as Login } from './Login/LoginContainer.jsx'; import { default as Agree }from './Agree/AgreeContainer.jsx'; const Routes = () => ( <Switch> <Route path="/" component={Login} exact /> <Route path="/agree" component={Agree} exact /> </Switch> ); export default Routes;
import React from 'react'; const J = 11; const Q = 12; const K = 13; const A = 1; const HEARTS = 2; const CLUBS = 3; const DIAMONDS = 4; const SPADES = 1; export function decode (bytes) { let n = bytes.length; console.assert(n % 2 === 0, "Cards must be encoded with even number of bytes"); return [...Array(n / 2).keys()] .map(i => { return { nominal: bytes[i * 2], suit: bytes[i * 2 + 1] }}); } export function hidden () { return 'cards/back/bicycle_blue_mod.svg'; } export function image (card) { return `cards/${suit(card.suit)}/${nominal(card.nominal)}.svg`; } function nominal (byte) { console.assert(byte <= 13, "Nominal cannot be encoded with number greater that 13"); if (byte === J) { return "J"; } if (byte === Q) { return "Q"; } if (byte === K) { return "K"; } if (byte === A) { return "A"; } return byte.toString(); } function suit (byte) { if (byte === HEARTS) { return "hearts"; } if (byte === CLUBS) { return "clubs"; } if (byte === DIAMONDS) { return "diamonds"; } if (byte === SPADES) { return "spades"; } }
import './less/style.less'; alert('home');
import React, { Component } from 'react'; import './ClientComp.css'; import AddNewClient from './AddNewClient'; import ClientSummary from './ClientSummary'; class ClientComp extends Component { constructor(props){ super(props); this.updateclients = this.props.updateclients; } render() { if (this.props.clientsToShow) { return ( <div> <ListOfClients onClient={this.props.onClient} clientList = {this.props.clientsToShow} rmFunc={this.props.rmFunc} updateclients={this.props.updateclients} clientId={this.props.clientId} on={this.props.on} /> <AddNewClient updateClientsAdd={this.props.updateClientsAdd}/> <ClientSummary clientList = {this.props.clientsToShow}/> </div> ); } else { return ( <div> <h1>Loading</h1> </div> ); } } } // -------------------------------------------------------------- // class ListOfClients extends Component { constructor(props){ super(props); this.state = { updateId: "" }; } on = (e) => { if (!e) var e = window.event; e.cancelBubble = true; if (e.stopPropagation) e.stopPropagation(); console.log(e.target.id); this.setState({updateId: e.target.id}); document.getElementById("overlay").style.display = "block"; } render(){ if (this.props.clientList) { let clientArr = this.props.clientList; clientArr.sort(function(a, b) { return a.idnum - b.idnum; }); let clientsInList = clientArr.map((client,i) => <SingleClient key={clientArr[i].idnum} id={clientArr[i].idnum} name={clientArr[i].name} onClient={this.props.onClient} rmFunc={this.props.rmFunc} updateclients={this.props.updateclients} clientId={this.props.clientId} on={this.on} updateId={this.state.updateId} />, ); return ( <ul>{clientsInList}</ul> ); } else { return <p> No clients to show </p> } } } class SingleClient extends Component { constructor(props){ super(props); this.state = { name: " " }; this.updateClients = this.props.updateclients; this.id = this.props.id; this.updateId=this.props.updateId; } off = (e) => { document.getElementById("overlay").style.display = "none"; } handleChange = (event) => { this.setState({name: event.target.value}); } handleSubmit = (event) => { console.log('A name was submitted: ' + this.state.name +'with an id of ' + this.props.updateId); event.preventDefault(); let data = { id: this.props.updateId, name:this.state.name } fetch('http://localhost:5000/updateClient', { method: 'put', headers: {'Content-type':'application/json'}, body: JSON.stringify(data) }) .then(response => response.json()) .then(this.updateClients) .then(this.off) .then(this.setState({name: ""})) } render(){ let classType = ""; let id = this.props.id; let clientId = this.props.clientId; if(parseInt(id) === parseInt(clientId)){ classType = "card clientCard cardSelected" } else { classType = "card clientCard" } return( <div> <div> <div className={classType} id={this.props.id} value={this.props.name} onClick={this.props.onClient}> <div> <h2 className = "clientName">{this.props.name}</h2> </div> <div className="cardButtons"> <button id={this.props.id} onClick={this.props.rmFunc}>X</button> <button id={this.props.id} onClick={this.props.on}>Edit</button> </div> </div> <div id ="overlay"> <div className="modal"> <h1>Update Client</h1> <div className="form"> <form id={this.props.id} onSubmit={this.handleSubmit}> <label> Name: <input type="text" value={this.state.name} onChange={this.handleChange}/> </label> <input className="button" type="submit" value="Submit" /> </form> <button onClick={this.off}>Exit</button> </div> </div> </div> </div> </div> ); } } export default ClientComp;
function getIntTemps() { $.get('scripts/server/view/get_ten_latest.php', function (data) { var internal_temps = new Array(); //for (reading in data) //alert(reading.internal); //internal_temps.push(reading.internal); for (let iii = 0; iii < data.length; ++iii) //alert(data[iii].internal); internal_temps.push(data[iii].internal); alert(data[0].internal); alert(internal_temps[0]); return internal_temps; }, 'json'); //return internal_temps; } function setupGraph(canvas) { $.get('scripts/server/view/get_ten_latest.php', function (data) { var internal_temps = new Array(); var external_temps = new Array(); for (let iii = 0; iii < data.length; ++iii) { internal_temps.push(data[iii].internal); external_temps.push(data[iii].external); } let graph_data = { labels: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1], datasets: [{ label: 'internal', data: internal_temps }, { label: 'external', data: external_temps }] }; console.log(internal_temps); let line_chart = new Chart(canvas, { type: 'line', data: graph_data, options: { scales: { xAxes: { type: 'linear' } } } }); }, 'json'); } $(document).ready(function () { let canvas = $('#canvasGraph'); //let internals = getIntTemps(); //let chart = new Chart(canvas, { // type: 'line', // data: getIntTemps() //}); setupGraph(canvas); });
const anotherFunction = () =>{ for (let i = 0; i < 10; i++) { setTimeout(() =>{ console.log(i) }, 1000) } } anotherFunction() /* !Te lo resumo así nomás: En un loop nunca ocupes var, siempre utiliza let para valores que !irán cambiando dentro de la ejecución del scope. */
$(document).on("click", ".user-icon__wrapper", function(){ var icon_preview = $( '<div class="user-icon-preview__wrapper">'+ '<img class="user-icon-preview__img">'+ '</div>' ); $label = $(this).parents('.user-icon__label'); $(".user-icon__input").on('change', function(e){ var reader = new FileReader(); reader.readAsDataURL(e.target.files[0]); reader.onload = function(e){ $(icon_preview).find(".user-icon-preview__img").attr("src", e.target.result); }; icon_preview.prependTo($label); $('.user-icon__wrapper').css('display', 'none'); }); }); $(document).on("click", ".user-icon-preview__wrapper", function(){ var icon_preview = $( '<div class="user-icon-preview__wrapper">'+ '<img class="user-icon-preview__img">'+ '</div>' ); $label = $(this).parents('.user-icon__label'); $(".user-icon__input").on('change', function(e){ var reader = new FileReader(); reader.readAsDataURL(e.target.files[0]); reader.onload = function(e){ $(icon_preview).find(".user-icon-preview__img").attr("src", e.target.result); }; $('.user-icon-preview__wrapper').remove(); icon_preview.prependTo($label); }); });
import React, { useEffect, useState } from "react"; import styles from "./Countries.module.scss"; import Country from "./Country"; import { Pagination, Empty } from "components"; import useMedia from "Hooks/useMedia"; import { useSelector, getCountries, getRegion, getSearchKeyword, getPage, } from "context/selectors"; import { selectCountries, COUNTRIES_PER_PAGE, responsive } from "utils"; const Countries = (props) => { const allCountries = useSelector(getCountries); const region = useSelector(getRegion); const searchKeyword = useSelector(getSearchKeyword); const page = useSelector(getPage); const countriesPerPage = useMedia( // Media queries [`(max-width: ${responsive.small}px)`, `(min-width: ${responsive.small + 1}px)`], // Countries to show per page by query [5, COUNTRIES_PER_PAGE], ) // State const [countries, setCountries] = useState(allCountries); const count = Math.ceil(countries.length / countriesPerPage); useEffect(updateCountries, [region, searchKeyword, page]); function updateCountries() { const countries = selectCountries(allCountries, searchKeyword, region); setCountries(countries); } return ( !!countries.length ? ( <> <div className={styles.countries}> {countries .slice((page - 1) * countriesPerPage, page * countriesPerPage) .map((country, i) => ( <Country key={i} country={country} /> ))} </div> <Pagination boundaryCount={10} count={count} /> </> ) : (<Empty />) ); }; export default Countries;
describe('The Home Page', function() { it('successfully loads', function() { cy.visit('/') // change URL to match your dev URL }) it('successfully logs in using create new user', function() { cy.contains('Don\'t have an account').click(); // cy.url().should('include', '/newUrl'); cy.get('.email_input') .type('example@example.com') cy.get('.pw_input') .type('test') cy.get('.login_submit_btn').click(); }) //add test that sends req to server to check for email and password validation // it('successfully authorizes email/pw for existing user', function() { // }) })
import React from "react" import { HalfPrice, Header, Category, Container } from "./styled" import { withRouter } from 'react-router-dom' import HalfEach from "./half" import { connect } from "react-redux" import { mapStateToProps, mapDispatchToProps } from "./mapStore" @connect(mapStateToProps, mapDispatchToProps) @withRouter class Half extends React.Component { constructor(props) { // console.log( new Date().getHours()) super(props) // console.log(this.props.data.half,888) this.state = { activetime: "12" } } render() { let { half, halflist } = this.props.data.half let { activetime } = this.state return ( <HalfPrice> <Header> <i className="iconfont left" onClick={this.handleback.bind(this)}>&#xe605;</i> <div className="logo"><img src="https://cmsstatic.ffquan.cn//wap_new/ranking/images/halfday_title.svg?v=201908292038" /></div> <i className="iconfont right">&#xe63a;</i> </Header> <Category> <div className="flex"> { half ? half.map((item, index) => ( <li // className="item" key={index} onClick={this.handleClicktime.bind(this, item.time)} className={activetime === item.time ? "weight item" : "item"} > <a className={activetime === item.time ? "active" : ""}> <span>{item.time}.00</span> <p>{item.status === "before" ? "已开抢" : item.status === "current" ? "正在抢购" : "即将开始"}</p> </a> </li> )) : "" } </div> </Category> <Container> <div className="img"> <img src="https://img.alicdn.com/imgextra/i4/2053469401/O1CN01bxRFEY2JJhz5KNm0P_!!2053469401.png?v=752320" /> </div> <div className="content"> <HalfEach halflist={halflist} activetime={activetime} /> <div className="load">都是小编精心挑选的超值好货哦~(。・∀・)ノ゙</div> </div> </Container> </HalfPrice> ) } handleClicktime(time) { this.setState({ activetime: time }) this.componentDidMount(time ? time : "00") } componentDidMount(time) { // console.log(time,555) this.props.halfbanner() this.props.halflist(time ? time : "00") } handleback() { this.props.history.goBack() // alert(555) } } export default Half;
App.Router.map(function () { this.resource('locale', { path: '/:locale_id' }, function() { this.resource('page', { path: '/:page_id' }); }); }); //Debug App.routes = Ember.keys(App.Router.router.recognizer.names); App.Locale = Em.Object.extend(); App.Locale.reopenClass({ find: function(id) { if (id) { return App.FIXTURES.findBy('id', id); } else { return App.FIXTURES; } } }); App.ApplicationRoute = Em.Route.extend({ model: function() { return App.Locale.find(); }, /* afterModel: function(model, transition) { this.transitionTo('locale', model[0]); },*/ /* setupController: function(controller, model) { console.log(model); }*/ }); App.LocaleRoute = Em.Route.extend({ model: function(params) { return App.Locale.find(params.locale_id); }, afterModel: function(model, transition) { console.log("App.LocaleRoute:afterModel " + model); //this.transitionTo('page', model.pages[0]); } /* setupController: function(controller, model) { console.log(model); }*/ }); App.ApplicationController = Em.ArrayController.extend({ destinationRoute: 'target' }); App.LocaleController = Ember.ObjectController.extend({ needs: "page", page: Ember.computed.alias("controllers.page"), isVisible: true }); App.PageController = Ember.ObjectController.extend({ needs: "locale", locale: Ember.computed.alias("controllers.locale"), ready: function() { console.log('activate )' + model.toArray()); } }); App.PageRoute = Em.Route.extend({ model: function(params) { console.log("params.page_id: " + params.page_id); return this.modelFor('locale').pages.findBy('id', params.page_id); }, actions: { willTransition: function(transition) { console.log("destroy backstretch before transition"); $('body').backstretch("destroy", false); } }, afterModel: function(model, transition) { var backStrechArrayParam = []; for (var i = 0; i < model.pictures.length; i++) { backStrechArrayParam[i] = model.pictures[i].path; } var instance = $('body').data('backstretch'); if (instance != undefined) $('body').backstretch("destroy", true); $('body').backstretch(backStrechArrayParam, {duration: 3000, fade: 750}); var instance = $('body').data('backstretch'); if (instance != undefined) console.log("after: " + instance.images.toString()); } });