text
stringlengths
7
3.69M
[ { "creatDate": "2018-09-07", "id": "11035", "image": "/d/file/fuli/pr/2018-09-07/d8db996d4b0c4077db0e2ae961728376.jpg", "longTime": "00:03:40", "title": "網紅少女私人玩物魅惑風情之就是要撩你", "video": "https://play.cdmbo.com/20180906/fXZdSpIL/index.m3u8" } ]
var router = $.net.urlRouter(); module.exports = router; var toolkit = require('../toolkit.js')(); router .handle('', require('./_.js')(toolkit)) .handle('process', require('./process.js')(toolkit)) ;
const assert = require('assert'); const ganache = require('ganache-cli'); const Web3 = require('web3'); const web3 = new Web3(ganache.provider()); const compiledHotOrNotFactory = require('../ethereum/build/HotOrNotFactory.json'); const compiledHotOrNot = require('../ethereum/build/HotOrNot.json'); const imageURL = 'https://upload.wikimedia.org/wikipedia/commons/thumb/b/bf/Mona_Lisa-restored.jpg/1200px-Mona_Lisa-restored.jpg'; let accounts; let hotOrNot; let factory; let hotOrNotAddress; beforeEach(async () => { accounts = await web3.eth.getAccounts(); factory = await new web3.eth.Contract(JSON.parse(compiledHotOrNotFactory.interface)) .deploy({ data: compiledHotOrNotFactory.bytecode }) .send({ from: accounts[0], gas: '1000000' }); await factory.methods.createHotOrNot('100', '2', imageURL).send({ from: accounts[0], gas: '1000000' }); [hotOrNotAddress] = await factory.methods.getDeployedHotOrNots().call(); hotOrNot = await new web3.eth.Contract( JSON.parse(compiledHotOrNot.interface), hotOrNotAddress ); }); describe('Hot or Not', async () => { it('deploys successfully', () => { assert.ok(hotOrNot.options.address); assert(hotOrNot.options.address.indexOf('0x') == 0); }); it('sets the image url', async () => { const result = await hotOrNot.methods.imageURL().call(); assert.equal(result, imageURL); }); it('votes yes', async () => { await hotOrNot.methods.voteYes().send({ from: accounts[0], value: '101' }); const result = await hotOrNot.methods.yesAmount().call(); assert.equal(result, '101'); }); it('votes no', async () => { await hotOrNot.methods.voteNo().send({ from: accounts[0], value: '201' }); const result = await hotOrNot.methods.noAmount().call(); assert.equal(result, '201'); }); it('requires minimum', async () => { let e; try { await hotOrNot.methods.voteYes().send({ from: accounts[0], value: '88' }); await hotOrNot.methods.voteNo().send({ from: accounts[0], value: '88' }); } catch(err) { e = err; } assert(e); }); it('has a balance', async () => { }); it('closes on max votes', async () => { await hotOrNot.methods.voteYes().send({ from: accounts[0], value: '101' }); await hotOrNot.methods.voteYes().send({ from: accounts[0], value: '101' }); const isClosed = await hotOrNot.methods.isClosed().call(); assert(isClosed); }); it('stays open on less than max votes', async () => { await hotOrNot.methods.voteYes().send({ from: accounts[0], value: '101' }); const isClosed = await hotOrNot.methods.isClosed().call(); assert(!isClosed); }); it('does not allow votes when closed', async () => { let e; try { await hotOrNot.methods.voteYes().send({ from: accounts[0], value: '101' }); await hotOrNot.methods.voteYes().send({ from: accounts[0], value: '101' }); const isClosed = await hotOrNot.methods.isClosed().call(); assert(isClosed); await hotOrNot.methods.voteYes().send({ from: accounts[0], value: '101' }); } catch(err) { e = err; } assert.ok(e); }); it('transfers a balance', async () => { const balanceBefore = await web3.eth.getBalance(accounts[0]); await hotOrNot.methods.voteYes().send({ from: accounts[1], value: '101' }); await hotOrNot.methods.voteYes().send({ from: accounts[2], value: '101' }); const balanceAfter = await web3.eth.getBalance(accounts[0]); assert(balanceBefore < balanceAfter); }); });
import React from 'react'; import * as model from '../model/Model.js'; import NewMeasurement from "./NewMeasurement"; import Measurement from "./Measurement"; import './Frame.css' class Frame extends React.Component { constructor(props){ super(props); model.callbacks.push(this); this.state = { count: 0 } ; } update() { this.setState((prevState) => { return {count: prevState.count + 1} }); } render() { return ( <div> <h1>BIG data-analyzer</h1> <div id="frame"> <div id="measurements"> { model.measurements.map((measurement) => ( <Measurement key={measurement.id} id={measurement.id} measurement={measurement}/> )) } <NewMeasurement/> </div> </div> </div> ); } } export default Frame;
$(document).ready(function() { createSlideBlog(); createSlidePortfolio(); }); $('.rolagem').click(function(){ $('html,body').animate({scrollTop:$('#'+$(this).attr("data-href")).offset().top - 50}, 1200); }); $("#btnFormContato").click(function() { $("#formContato").submit(); console.log('ok'); }); function createSlideBlog(){ var windowWidth = window.innerWidth; var qntSlide = 1; if (windowWidth >= 668) { qntSlide = 2; } if (windowWidth >= 992) { qntSlide = 3; } if (windowWidth >= 1200) { qntSlide = 4; } $('.posts-blog').slick({ slidesToShow: qntSlide, slidesToScroll: 1, autoplay: true, autoplaySpeed: 5000, dots: true, arrows: false, }); } function createSlidePortfolio(){ $('.slide-portfolio').slick({ autoplay: true, autoplaySpeed: 5000, dots: true, arrows: true, }); } function muteVideo(){ var video = document.getElementById("video-bg"); if (video.muted) { video.muted = false; $("#text-btn-mute").html('Desligar'); $("#icon-btn-mute").removeClass('fa-volume-off'); $("#icon-btn-mute").addClass('fa-volume-up'); } else { video.muted = true; $("#text-btn-mute").html('Ligar'); $("#icon-btn-mute").removeClass('fa-volume-up'); $("#icon-btn-mute").addClass('fa-volume-off'); } }
import mongoose from 'mongoose'; const Schema = mongoose.Schema; const developerSchema = new Schema({ name: String, link: String, }); module.exports = mongoose.model('Developer', developerSchema); // import mongoose from 'mongoose'; // export const Developer = mongoose.model('Developer', { // name: { // type: String, // }, // link: { // type: String, // }, // });
// Library allows logging data to the local filesystem // Constructor creates file if it does not exist // // // detector object is the configuration model, an example is // // config.detector = {}; // config.detector.name = "Lloyd Wright"; // config.detector.description = "First three paddle detector."; // config.detector.alias = "lloydWright"; // config.detector.apiKey = "a3e68f42-03f6-4570-85bd-cc5f66c2da96"; // config.detector.tags = "Three Paddle, Humidity, GPS"; // config.detector.location = "Atlanta, GA"; // config.detector.public = "true"; // config.detector.fields = {"Zero":"int(11)"} // // var logToFile = require("./logToFile"); // var file = new logToFile(config.logDir, config.detector); // file.log({"Zero":5}); // // Imports const fs = require('fs'); //Acsess the filesystem module.exports = class logToFile { constructor(logDir, detector) { // Log directory reletive to current direcory this.logDir = logDir; // Detector configuration object this.detector = detector; //If logDir directory does not exist, create it if (!fs.existsSync(logDir)) { fs.mkdirSync(logDir); } this._createFile(detector); } log(data) { var logLine = new Date().toISOString() + ","; for(var entry in data){ logLine += data[entry]; logLine += ","; } logLine += "\n"; // Append the line to the file fs.appendFile(this.logDir + "/" + this.fileName, logLine, function (err) { }); } _createFile(detector) { // File is uniquely named by start time and the alias var fileName = this.detector.alias + "-" + new Date().toISOString() + ".log"; // Header is created through fields, prepended with date append with newline var header = "date,"; for (var field in detector.fields) { header += field; header += ","; } header += "\n"; //Write just the header to the file creating it in the process fs.writeFile(this.logDir + "/" + fileName, header, function (err) { if (err) { throw err; } console.log("Logging started in " + fileName); }); this.fileName = fileName; } }
const etherlime = require('etherlime'); const CryptoColor = require('../build/CryptoColor.json'); describe('Crypto color contract', () => { let accountZero; let accountThree; let deployer; let deployerContractWrapper; let cryptoColorContract; beforeEach(async () => { deployer = new etherlime.EtherlimeGanacheDeployer(); deployerContractWrapper = await deployer.deploy(CryptoColor); cryptoColorContract = deployerContractWrapper.contract; accountZero = await accounts[0].wallet.connect(deployer.provider); accountThree = await accounts[3].wallet.connect(deployer.provider); }); it('the account should have 0 balance', async () => { const balanceBefore = await cryptoColorContract.balanceOf(accountZero.address); assert(balanceBefore.eq(0), 'The balance is not zero'); }); it('the account should have 1 token balance', async () => { await cryptoColorContract.mint(); const balanceAfter = await cryptoColorContract.balanceOf(accountZero.address); assert(balanceAfter.eq(1), 'Invalid balance. It is not 1'); }) it('getting real color by id', async () => { await cryptoColorContract.mint(); const rgbColor = await cryptoColorContract.getColorFromId(0); assert.isArray(rgbColor, 'The result rgbColor is not array'); assert.isNumber(rgbColor[0], 'The first element of the array is not number'); assert.isNumber(rgbColor[1], 'The second element of the array is not number'); assert.isNumber(rgbColor[2], 'The third element of the array is not number'); }) it('non-owner should not be able to mint', async () => { const nonOwnerContractInstance = await cryptoColorContract.connect(accountThree); await assert.revert(nonOwnerContractInstance.mint()); const balanceAfter = await nonOwnerContractInstance.balanceOf(accountThree.address); assert(balanceAfter.eq(0), 'Invalid balance. It is not 0'); }) });
var searchData= [ ['deterministicexception',['DeterministicException',['../structfsml_1_1DeterministicException.html',1,'fsml']]] ];
/**File created beautifully by Praful Prasad */ chrome.runtime.onMessage.addListener(function(request,sender,callback){ console.log("received requestttt",request); chrome.downloads.download({url: request.url,filename:request.name}); })
import React, { useEffect, useState, useContext } from "react"; import { Accordion, AccordionItem, AccordionItemHeading, AccordionItemButton, AccordionItemPanel } from "react-accessible-accordion"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import ContextInventory from "../ContextInventory"; import { findUser } from "../helper"; import "./AdminUsers.css"; //polyfills import Promise from "promise-polyfill"; import "whatwg-fetch"; export default function AdminUser() { const { users, addUser, deleteUser } = useContext(ContextInventory); const [confirmation, updateConfirmation] = useState({}); const [confirmationForm, updateConfirmationForm] = useState(""); const [addIcon, updateAddIcon] = useState("plus"); const [addId, updateAddId] = useState(""); const [removeIcon, updateRemoveIcon] = useState("plus"); const [removeId, updateRemoveId] = useState(""); function handleClick(uuid) { if (uuid[0] === "add") { updateRemoveId("rotateDown"); updateRemoveIcon("plus"); updateAddId("rotateUp"); return updateAddIcon("minus"); } if (uuid[0] === "remove") { updateAddId("rotateDown"); updateAddIcon("plus"); updateRemoveIcon("minus"); return updateRemoveId("rotateUp"); } else { updateAddId("rotateDown"); updateAddIcon("plus"); updateRemoveId("rotateDown"); updateRemoveIcon("plus"); } } const userNames = users.map(user => { return ( <option key={user.id} value={user.id}> {user.name} </option> ); }); const addUserSubmit = e => { e.preventDefault(); updateConfirmationForm(null); const name = e.target.addUser.value; if (name.trim().length === 0) { return confirmationText("addUser", "Enter a name to add user"); } const userData = { name: name }; const url = "https://boiling-bayou-06844.herokuapp.com/api/users"; e.target.reset(); fetch(url, { method: "POST", credentials: "same-origin", body: JSON.stringify(userData), headers: { "content-type": "application/json" } }) .then(response => { if (!response.ok) { return response.json().then(error => { throw error; }); } return response.json(); }) .then(response => { const newUser = { id: response.id, name: response.name, checkedOut: {} }; addUser(newUser); confirmationText("addUser", `${newUser.name} added`); }) .catch(error => { confirmationText("addUser", error.message); }); }; const deleteUserSubmit = e => { e.preventDefault(); updateConfirmationForm(null); const id = e.target.user.value; const user = findUser(users, id); let checkout = false; e.target.reset(); if (Object.keys(user.checkedOut).length > 0) { checkout = true; } const url = `https://boiling-bayou-06844.herokuapp.com/api/users?id=${user.id}&clearCheckOut=${checkout}`; fetch(url, { method: "DELETE", credentials: "same-origin", headers: { "content-type": "application/json" } }) .then(response => { if (!response.ok) { return response.json().then(error => { throw error; }); } deleteUser(id); confirmationText("removeUser", `${user.name} removed`); }) .catch(error => { confirmationText("removeUser", error.message); }); }; let timer; function confirmationText(form, text) { clearTimeout(timer); updateConfirmation(() => { return ( <p className="confirmation" role="alert"> {text} </p> ); }); updateConfirmationForm(form); timer = setTimeout(() => { updateConfirmation(""); }, 5000); } useEffect(() => { return clearTimeout(timer); }, [timer]); return ( <Accordion allowZeroExpanded="true" className="userAccordion" onChange={uuid => handleClick(uuid)} > <AccordionItem uuid="add"> <AccordionItemHeading className="accordion2"> <AccordionItemButton> Add User <FontAwesomeIcon icon={addIcon} id={addId} className="angleIcon plus" /> </AccordionItemButton> </AccordionItemHeading> <AccordionItemPanel> <form onSubmit={addUserSubmit}> <input type="text" name="addUser" id="addUser" placeholder="Enter name..." /> <button type="submit" className="user"> Add User </button> </form> {confirmationForm === "addUser" && confirmation} </AccordionItemPanel> </AccordionItem> <AccordionItem uuid="remove"> <AccordionItemHeading className="accordion2"> <AccordionItemButton> Remove User <FontAwesomeIcon icon={removeIcon} id={removeId} className="angleIcon plus" /> </AccordionItemButton> </AccordionItemHeading> <AccordionItemPanel> <form onSubmit={deleteUserSubmit}> <select id="user" defaultValue="" required> <option value="" disabled> Select name... </option> {userNames} </select> <button type="submit" className="user"> Delete User </button> </form> {confirmationForm === "removeUser" && confirmation} </AccordionItemPanel> </AccordionItem> </Accordion> ); }
import React, { Component } from 'react'; import { Popover, PopoverBody } from 'reactstrap'; import PropTypes from 'prop-types'; import EditListForm from './EditListForm'; import './styles/ListHeader.css'; class ListHeader extends Component { state = { showPopover: false, editListClicked: false }; toggleClick = () => { this.setState({ editListClicked: !this.state.editListClicked }); }; togglePopover = () => { this.setState({ showPopover: !this.state.showPopover }); }; renderPopover = () => { const { listId, authToken, deleteList } = this.props; return ( <Popover placement="bottom" isOpen={this.state.showPopover} target={`PopoverList${listId}`} toggle={this.togglePopover} className="list-popover" > <PopoverBody> <div className="toolbar-item" onClick={() => deleteList(listId, authToken)}> <div>Delete list...</div> <img className="pull-right" src={require('../../../images/delete.png')} alt="" /> </div> </PopoverBody> </Popover> ); }; render() { const { dragHandleProps, title, listId } = this.props; return ( <header {...dragHandleProps}> <div className="header-title"> {this.state.editListClicked ? ( <EditListForm value="title" form={`EditListForm-${listId}`} listId={listId} initialValues={{ title }} onEdit={this.toggleClick} /> ) : ( <h6 id="list-title" onClick={this.toggleClick}> {title} </h6> )} </div> <div className="header-toolbar" id={`PopoverList${listId}`} onClick={this.togglePopover}> <img src={require('../../../images/toolbar.png')} alt="" /> </div> {this.renderPopover()} </header> ); } } ListHeader.propTypes = { title: PropTypes.string.isRequired, listId: PropTypes.string.isRequired, authToken: PropTypes.string.isRequired, dragHandleProps: PropTypes.object.isRequired, deleteList: PropTypes.func.isRequired }; export default ListHeader;
'use strict'; const path = require('path'); const fs = require('fs'); const tmp = require('tmp'); const _ = require('lodash'); const Util = require('../util'); class Builder { constructor(deployment) { this.deployment = deployment; } get workdir() { return path.resolve(path.join(__dirname, '..', '..', 'nix')); } eval(args) { args = args || {}; const tmpFile = tmp.fileSync(); fs.write(tmpFile.fd, JSON.stringify(_.extend(this.deployment.args, args))); return Util.run( `nix-build --arg configuration ${this.deployment.file} --arg args ${tmpFile.name} --no-out-link ${this.workdir}/default.nix` ).then(result => { tmpFile.removeCallback(); // remove new lines from file const path = _.trimEnd(result); this.deployment.loadSpec(path); // construct new specs model return this.deployment; }); } } module.exports = Builder;
import React from 'react'; import './styles/PageHeader.css'; const PageHeader = (props) => { return ( <div className='PageHeader'> <h2>Occupation Overview</h2> <h5>{props.occupationTitle} in {props.msa}</h5> </div> ) }; export default PageHeader;
import React, { Component } from "react"; import Todos from "./Components/todoList/todos.jsx"; import AddToDo from "./Components/addTodo/addToDo.jsx"; import Heading from "./Components/heading/heading.jsx"; import "./App.scss"; class App extends Component { constructor(props) { super(props); this.state = { todos: [] }; } deleteToDo = id => { const todos = this.state.todos.filter(todo => { return todo.id !== id; }); this.setState({ todos }); }; completeToDo = todo => { todo.complete = !todo.complete; this.setState({ todo }); }; addToDo = todo => { let todos = [...this.state.todos, todo]; todo.id = todo.content; this.setState({ todos }); }; render() { return ( <div className="App"> <Heading /> <AddToDo addTodo={this.addToDo} previousTodos={this.state.todos} /> <Todos todos={this.state.todos} deleteTodos={this.deleteToDo} completeToDos={this.completeToDo} /> </div> ); } } export default App;
var rotation = 0; var timeout; (function() { var divs = document.getElementsByClassName('rotation'); var mouseover = function() { var el = this; rotate(el); } for (var i = 0; i < divs.length; i++) { divs[i].addEventListener('click', mouseover, true); } })(); function rotate(element) { if(rotation==360) { rotation=0; window.clearInterval(timeout); element.style.transform = 'rotate'+rotation_axis+'('+rotation+'deg)'; element.style.webkitTransform = 'rotate'+rotation_axis+'('+rotation+'deg)'; return false; } rotation = rotation + 5 ; console.log(rotation); element.style.transform = 'rotate'+rotation_axis+'('+rotation+'deg)'; element.style.webkitTransform = 'rotate'+rotation_axis+'('+rotation+'deg)'; timeout = window.setTimeout(function(){ rotate(element); }, rotation_speed); }
controllers .controller('loginController', function ($state, $cordovaBarcodeScanner, LoopBackAuth, Account, AccountManager, PushNotificationService, User) { console.log('loginController started'); var vm = this; vm.data = {}; if(AccountManager.isAuthenticated()){ return $state.go('app.home'); } vm.login = function () { console.log(JSON.stringify(vm.data)); Account.login(vm.data).$promise .then(function () { AccountManager.getPaciente() .then(function(p){ AccountManager.lsSetPaciente(p); PushNotificationService.register(); $state.go('app.home.agendadas'); }); //var isAndroid = ionic.Platform.isAndroid(); }) .catch(function (err) { console.log('error ' + JSON.stringify(err)); }); }; vm.qrScanner = function () { document.addEventListener("deviceready", function () { $cordovaBarcodeScanner .scan() .then(function (barcodeData) { var code = JSON.parse(atob(barcodeData.text)); console.log(code); LoopBackAuth.setUser(code.tokenId, code.userId, null); Account.findById({id: code.userId}).$promise .then(function (account) { LoopBackAuth.setUser(code.tokenId, code.userId, account); if (account.status === 'active') { $state.go('app.home'); } else { $state.go('app.register.message'); } }) .catch(function (err) { console.error(err); }); }, function (err) { console.error('scanner', err); }); }, false); } });
export const CALENDAR = [ { id: 0, title: 'Calendar Title', description: 'Calendar Details', featured: true } ]
import React from 'react' const Section = (props) => { const section = props.section return ( <div className="section"> <p className="section__text">{section}</p> <button className="button" onClick={() => { props.handleBeginSection(section) }}> Begin </button> </div> ) } export default Section
import React, { Component } from "react"; import { connect } from "react-redux"; import { Route, Redirect } from "react-router-dom"; import './Moviedetails.css'; class Moviedetails extends Component { constructor(){ super() this.state={ redirect: false } } toggle = () => { this.setState({ redirect: !this.state.redirect }) } render(){ if (this.state.redirect) return <Redirect to={'/'} /> const poster = this.props.poster_path const path = `https://image.tmdb.org/t/p/w185/${poster}` return ( <div className="movie-details-box"> <button onClick={this.toggle}>go back</button> <img src={path}></img> <div className="text-area"> <h3>{this.props.title}</h3> <p>{this.props.overview}</p> <p>Rating: {this.props.vote_average} /10</p> </div> </div> ) } } export const mapStateToProps = (state) => ({ nowPlaying: state.nowPlayingMovies, topRatedMovies: state.topRatedMovies, popularMovies: state.popularMovies }) export default connect(mapStateToProps)(Moviedetails)
import React from 'react'; import * as firebase from "firebase/app"; import "firebase/auth"; import firebaseConfig from "./firebaseConfig"; import { useState } from "react"; import { createContext } from 'react'; import { useContext } from 'react'; import { useEffect } from 'react'; firebase.initializeApp(firebaseConfig); const AuthContext = createContext(); export const AuthContextProvider =(props)=>{ const auth= Auth(); return <AuthContext.Provider value={auth}>{props.children}</AuthContext.Provider> } export const useAuth =()=> useContext(AuthContext); //after onchanges , user k update korar jnno ekta funtion use kora hocce const getUser =user=>{ const {displayName, email, photoURL} = user; return {name : displayName, email, photo:photoURL}; } const Auth=()=>{ const [user,setUser]= useState(null); const signInWithGoogle=()=>{ var provider = new firebase.auth.GoogleAuthProvider(); //after placing return return firebase.auth().signInWithPopup(provider) .then(res=>{ const singedInUser = getUser(res.user) setUser(singedInUser); return res.user }) .catch(err=>{ // console.log(err); setUser(null) return err.message; }) } const signOut=()=>{ //after placing return return firebase.auth().signOut().then(function() { setUser(null) return true; }).catch(function(error) { return false; }); } //set later for using auth hook to another place useEffect(()=>{ firebase.auth().onAuthStateChanged(function(usr) { if (usr) { const currUser = getUser(usr) setUser(currUser); } else { // No user is signed in. } }); },[]) return{ user, signInWithGoogle , signOut } } export default Auth;
// Breadcrumb component class Breadcrumb extends React.Component { render() { return ( <div className="row"> <nav className="breadcrumb night-full-width"> {this.props.crumbs.map(function(crumb) { if (crumb.url) { return ( <a key={'bca' + crumb.name} className="breadcrumb-item" href={crumb.url}> {crumb.name} </a> ); } else { return ( <span key={'bcs' + crumb.name} className="breadcrumb-item active"> {crumb.name} </span> ); } })} </nav> </div> ); } }
console.log('Задание 5. Площадь круга.'); var r = 5, p = 3.14; var SKruga = p * (r * r) + ' ' + 'кв.см.'; console.log('Ответ: ' + SKruga); console.log('');
const _ = require("lodash"); const fs = require("fs"); const path = require("path"); const stringCaseUtil = require("./string_utils"); /** * 映射dir下的文件内容归档成一个js对象 * @param dir 当前路径 * @param alias 文件别名 值码对 * @returns {} */ const mappingFiles2Obj = dir => { const tree = {}; // 获得当前文件夹下的所有的文件夹和文件 const [dirs, files] = _(fs.readdirSync(dir)).partition(p => fs.statSync(path.join(dir, p)).isDirectory() ); // 映射文件夹 dirs.forEach(dir => { tree[stringCaseUtil.camelCase(dir)] = mappingFiles2Obj(path.join(dir, dir)); }); // 映射文件 files.forEach(file => { if (path.extname(file) === ".js") { tree[ stringCaseUtil.camelCase(path.basename(file, ".js")) ] = require(path.join(dir, file)); } }); return tree; }; // 默认导出当前文件夹下的映射 module.exports = mappingFiles2Obj;
import axios from "axios"; const serverApi = "http://localhost:5002/api"; export const getRoomExists = async (roomId) => { const response = await axios.get(`${serverApi}/room-exists/${roomId}`); return response.data; }
import express from 'express'; import cors from 'cors'; import bodyParser from 'body-parser'; import { defaultState } from './defaultState'; let port = 7777; let app = express(); const authorizationTokens = []; app.use( cors(), bodyParser.urlencoded({ extended: true }), bodyParser.json() ); app.get('/user/:id', (req, res) => { let user = defaultState.users.find(user => user.id === req.params.id); if (!user) { res.status(500).send(); } else { res.json(user); } }); app.post(`/task/new`, (req, res) => { let { task } = req.body; res.status(200).send(); }); app.post(`/task/update`, (req, res) => { let { task } = req.body; res.status(200).send(); }); app.post(`comment/new`, (req, res) => { res.status(200).send(); });
/* test.js - test script The MIT License (MIT) Copyright (c) 2015-2016 Dale Schumacher Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ "use strict"; var test = module.exports = {}; var log = console.log; //var log = function () {}; var tart = require('tart-tracing'); var PEG = require('../PEG.js'); var input = require('../input.js'); // name, value ==> value var transformValue = (name, value) => { log('transformValue:', name, value); var result = value; log('Value:', result); return result; }; test['right recursion is right-associative'] = function (test) { test.expect(2); var tracing = tart.tracing(); var sponsor = tracing.sponsor; var pf = PEG.factory(sponsor); var ns = pf.namespace(/*log*/); // List <- Item ',' List / Item ns.define('List', pf.choice([ pf.sequence([ ns.call('Item'), pf.terminal(','), ns.call('List') ]), ns.call('Item') ]) ); ns.transform('List', transformValue); // Item <- [a-z] ns.define('Item', pf.predicate(token => /[a-z]/.test(token)) ); ns.transform('Item', transformValue); var ok = sponsor(function (m) { var v = m.value; log('OK.value:', JSON.stringify(v, null, 2)); test.deepEqual(v, [ 'a', ',', [ 'b', ',', [ 'c', ',', 'd' ] ] ]); }); var fail = sponsor(function (m) { console.log('FAIL:', m); }); var matcher = pf.matcher(ns.call('List'), ok, fail); var stream = input.fromString(sponsor, 'a,b,c,d'); stream(matcher); test.ok(tracing.eventLoop({ count: 1000 }), 'Exceeded message limit'); test.done(); }; test['left recursion fails safely'] = function (test) { test.expect(2); var tracing = tart.tracing(); var sponsor = tracing.sponsor; var pf = PEG.factory(sponsor); var ns = pf.namespace(/*log*/); // Expr <- Expr [-+] Term / Term ns.define('Expr', pf.choice([ pf.sequence([ ns.call('Expr'), pf.predicate(token => /[-+]/.test(token)), ns.call('Term') ]), ns.call('Term') ]) ); ns.transform('Expr', transformValue); // Term <- [a-z] ns.define('Term', pf.predicate(token => /[a-z]/.test(token)) ); ns.transform('Term', transformValue); var ok = sponsor(function (m) { var v = m.value; log('OK.value:', JSON.stringify(v, null, 2)); test.deepEqual(v, 'a'); }); var fail = sponsor(function (m) { console.log('FAIL:', m); }); var matcher = pf.matcher(ns.call('Expr'), ok, fail); var stream = input.fromString(sponsor, 'a-b-c-d'); stream(matcher); test.ok(tracing.eventLoop({ count: 1000 }), 'Exceeded message limit'); test.done(); }; test['suffix iteration should be left-associative (foldl)'] = function (test) { test.expect(2); var tracing = tart.tracing(); var sponsor = tracing.sponsor; var pf = PEG.factory(sponsor); var ns = pf.namespace(/*log*/); // Expr <- Term ([-+] Term)* ns.define('Expr', pf.sequence([ ns.call('Term'), pf.zeroOrMore( pf.sequence([ pf.predicate(token => /[-+]/.test(token)), ns.call('Term') ]) ) ]) ); ns.transform('Expr', transformValue); // Term <- [a-z] ns.define('Term', pf.predicate(token => /[a-z]/.test(token)) ); ns.transform('Term', transformValue); var ok = sponsor(function (m) { var v = m.value; log('OK.value:', JSON.stringify(v, null, 2)); test.deepEqual(v, [ 'a', [ [ '-', 'b' ], [ '-', 'c' ], [ '-', 'd' ] ] ]); }); var fail = sponsor(function (m) { console.log('FAIL:', m); }); var matcher = pf.matcher(ns.call('Expr'), ok, fail); var stream = input.fromString(sponsor, 'a-b-c-d'); stream(matcher); test.ok(tracing.eventLoop({ count: 1000 }), 'Exceeded message limit'); test.done(); }; test['prefix iteration should be right-associative (foldr)'] = function (test) { test.expect(2); var tracing = tart.tracing(); var sponsor = tracing.sponsor; var pf = PEG.factory(sponsor); var ns = pf.namespace(/*log*/); // List <- (Item ',')* Item ns.define('List', pf.sequence([ pf.zeroOrMore( pf.sequence([ ns.call('Item'), pf.terminal(',') ]) ), ns.call('Item') ]) ); ns.transform('List', transformValue); // Item <- [a-z] ns.define('Item', pf.predicate(token => /[a-z]/.test(token)) ); ns.transform('Item', transformValue); var ok = sponsor(function (m) { var v = m.value; log('OK.value:', JSON.stringify(v, null, 2)); test.deepEqual(v, [ [ [ 'a', ',' ], [ 'b', ',' ], [ 'c', ',' ] ], 'd' ]); }); var fail = sponsor(function (m) { console.log('FAIL:', m); }); var matcher = pf.matcher(ns.call('List'), ok, fail); var stream = input.fromString(sponsor, 'a,b,c,d'); stream(matcher); test.ok(tracing.eventLoop({ count: 1000 }), 'Exceeded message limit'); test.done(); }; test['star expansion is right-associative'] = function (test) { test.expect(2); var tracing = tart.tracing(); var sponsor = tracing.sponsor; var pf = PEG.factory(sponsor); var ns = pf.namespace(/*log*/); // G* <- G G* // | var star = function star(G) { var G_star = pf.choice([ pf.sequence([ G, sponsor(function delay(m) { G_star(m); // this will be bound before it is called }) ]), pf.empty ]); return G_star; }; // Path <- Name star('.' Name) ns.define('Path', pf.sequence([ ns.call('Name'), star( pf.sequence([ pf.terminal('.'), ns.call('Name') ]) ) ]) ).transform = transformValue; // Name <- [a-z] ns.define('Name', pf.predicate(token => /[a-z]/.test(token)) ).transform = transformValue; var ok = sponsor(function (m) { var v = m.value; log('OK.value:', JSON.stringify(v, null, 2)); test.deepEqual(v, [ 'a', [ [ '.', 'b' ], [ [ '.', 'c' ], [ [ '.', 'd' ], [] ] ] ] ]); }); var fail = sponsor(function (m) { console.log('FAIL:', m); }); var matcher = pf.matcher(ns.call('Path'), ok, fail); var stream = input.fromString(sponsor, 'a.b.c.d'); stream(matcher); test.ok(tracing.eventLoop({ count: 1000 }), 'Exceeded message limit'); test.done(); };
import React, { useEffect, useState } from 'react' import { useDispatch, useSelector } from 'react-redux' import { Link } from 'react-router-dom' import { singleProduct, addReview, removeReview } from '../../actions/product' import Loader from '../../components/Loader' import Message from '../../components/Message' const Product = ({ match, history }) => { const [qty, setQty] = useState(1) const [rating, setRating] = useState(0) const [comment, setComment] = useState('') const dispatch = useDispatch() const getSingleProduct = useSelector(state => state.getSingleProduct) const { loading, error, product } = getSingleProduct const createReview = useSelector(state => state.createReview) const { loading:loadingReview, error:errorReview, success } = createReview const userLogin = useSelector(state => state.userLogin) const { userInfo } = userLogin const deleteReview = useSelector(state => state.deleteReview) const { success:successReview } = deleteReview useEffect(() => { dispatch(singleProduct(match.params.id)) }, [dispatch, match, success, successReview]) const addToCartHandler = (id) => { history.push(`/cart/${product._id}?qty=${qty}`) } const submitHandler = (e) => { e.preventDefault() dispatch(addReview(match.params.id, { rating, comment })) } return ( <section className="py-5"> <div className="container"> <Link to="/products" className="btn btn-dark mb-4">Go Back To Product</Link> {loading ? <Loader /> : error ? <Message variant="danger"> {error} </Message> : ( <div className="row"> <div className="col-md-6"> <img src={product.image} className="img-fluid w-100 post-img" /> </div> <div className="col-md-3 mt-4"> <h3 className=""> {product.name} </h3> <p><i className="fas fa-star text-warning"></i> {Number(product.rating).toFixed(1)} stars ({ product.numReviews }) reviews </p> <h4>Price: <strong> ${product.price} </strong></h4> <p className="text-muted">Created At: {Date(product.createdAt).substring(0, 15)} </p> </div> <div className="col-md-3 card card-body h-100"> <h4>Price: <h4 className="d-inline float-right"> ${product.price} </h4></h4> <hr /> <h4>Status: <h4 className="d-inline float-right"> {product.countInStock > 0 ? 'In Stock' : 'Out Of Stock'}</h4> </h4> <hr /> {product.countInStock > 0 && ( <> <div className="row"> <div className="col"> <h4>Qty:</h4> </div> <div className="col"> <select className="form-control" value={qty} onChange={e => setQty(e.target.value)}> {[...Array(product.countInStock).keys()].map(x => ( <option key={x + 1} value={x + 1}> {x + 1} </option> ))} </select> </div> </div> <hr /> </> )} <button onClick={addToCartHandler} disabled={product.countInStock === 0 || !userInfo} className="btn btn-dark btn-block p-2">Add To Cart</button> {!userInfo && <p>You need to <Link to="/login">Login</Link> first</p>} </div> </div> )} <div className="row"> <div className="col-md-6"> <h3 className="py-2">Reviews <span><i className="fas fa-star text-warning"></i> {Number(product.rating).toFixed(1)} Stars </span><span> ({product.numReviews}) reviews </span> </h3> {product.reviews.length === 0 && <h6 className="text-primary">No Reviews</h6>} <div className="list-group"> {product.reviews.map(review => ( <div className="list-group-item" key={review._id}> <p className="m-0 p-0 mb-1"><strong> {review.name}</strong> {userInfo === null ? <></> : userInfo && userInfo.user._id === review.user.toString() && (<button onClick={() => dispatch(removeReview(match.params.id, review._id))} className="btn float-right"><i className="fas fa-trash text-danger"></i></button>)} </p> <p className="m-0 p-0"> {review.rating.toFixed(1)} <i className="fas fa-star text-warning mx-1"></i>Stars</p> <p className="m-0 p-0"> {review.comment} </p> </div> ))} </div> {userInfo && product.reviews.find(r => r.user.toString() === userInfo.user._id) ? ( <p className="text-success">You have Reviewed in this</p> ) : ( <> {errorReview && <Message variant="danger"> {errorReview} </Message>} {userInfo && ( <> <h3 className="mt-4">Write A Customer Review</h3> <form onSubmit={submitHandler}> <label className="p-0 m-0">Rating</label> <div className="form-group"> <select className="form-control" value={rating} onChange={e => setRating(e.target.value)}> <option value="">Select...</option> <option value="1">1 = VERY POOR</option> <option value="2">2 = POOR</option> <option value="3">3 = GOOD</option> <option value="4">4 = VERY GOOD</option> <option value="5">5 = EXCELLENT</option> </select> </div> <div className="form-group"> <textarea className="form-control" rows="4" placeholder="Say Something About This Product..." value={comment} onChange={e => setComment(e.target.value)}></textarea> </div> <button type="submit" className="btn btn-dark">Submit</button> </form> </> )} {loadingReview && <Loader />} </> )} </div> </div> </div> </section> ) } export default Product
// "use strict" tells the browser to enforce some rules about what can be in our JavaScript. "use strict"; let my_name = "Bonnie"; let your_name = "Kyle"; if (my_name === "Ben") { renderOutput("That's Ben!"); } else if (my_name === "Bonnie") { renderOutput("Yep, that's me!"); } else { renderOutput("I must be someone else"); } function helloWorld() { renderOutput("Hello World!"); } function helloName(name) { renderOutput("Hello " + name); } helloName("Bonnie"); function todaysHours(days_hours) { renderOutput(days_hours); } hours.forEach(todaysHours);
/* eslint no-console:0 */ const path = require('path'); const chalk = require('chalk'); const MiniCssExtractPlugin = require('mini-css-extract-plugin'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin'); const ScriptExtHtmlWebpackPlugin = require('script-ext-html-webpack-plugin'); const CleanWebpackPlugin = require('clean-webpack-plugin'); const CopyWebpackPlugin = require('copy-webpack-plugin'); const WeinreWebpackPlugin = require('weinre-webpack-plugin'); const DEV_MODE = process.env.NODE_ENV === 'development'; const WEINRE_MODE = DEV_MODE && process.env.WEINRE; console.log(chalk.bgGreen.black('process.env.NODE_ENV', process.env.NODE_ENV)); const toFilename = name => (DEV_MODE ? `${name}.js` : `${name}-[chunkhash].js`); const toCSSFilename = name => (DEV_MODE ? `${name}.css` : `${name}-[contenthash].js`); const getLocalhostIPAddress = () => { const ifs = require('os').networkInterfaces(); // eslint-disable-next-line const host = `${Object.keys(ifs).map(x => ifs[x].filter(x => x.family === 'IPv4' && !x.internal)[0]).filter(x => x)[0].address}`; return host || 'localhost'; }; const config = { mode: process.env.NODE_ENV, context: path.resolve('src'), entry: { app: ['./index.js'], }, output: { filename: toFilename('assets/js/[name]'), chunkFilename: toFilename('assets/js/[name]-chunk'), path: path.resolve('dist'), publicPath: '', }, devtool: DEV_MODE ? 'inline-source-map' : false, resolve: { modules: [ path.resolve('src'), path.resolve('src/assets'), path.resolve('node_modules'), ], alias: { '~': path.resolve('src'), '@': path.resolve('src'), img: path.resolve('src/assets/img'), }, extensions: ['.js', '.jsx'], }, }; config.module = { rules: [ { test: /\.js(x?)$/, use: ['babel-loader'], include: path.resolve('src'), exclude: /node_modules/, }, { test: /\.(png|jpg|gif|svg|ico)$/, use: { loader: 'url-loader', options: { limit: 1024, name: '[path][name].[ext]?[hash:8]', }, }, include: path.resolve('src/assets/img'), exclude: /node_modules/, }, { test: /\.(styl|stylus)$/, use: [ 'css-hot-loader', { loader: MiniCssExtractPlugin.loader, options: { publicPath: '../../', }, }, { loader: 'css-loader', options: { sourceMap: true, minimize: true, }, }, { loader: 'postcss-loader', options: { sourceMap: true, plugins: () => [ require('postcss-flexbugs-fixes'), require('autoprefixer')({ browsers: [ 'last 5 versions', 'iOS >=10', 'not ie <= 11', '>3%', ], flexbox: 'no-2009', }), ], }, }, { loader: 'stylus-loader', options: { paths: 'src/css/', sourceMap: true, }, }, ], include: [ path.resolve('src'), ], exclude: /node_modules/, }, { test: /\.pug$/, use: { loader: 'pug-loader', options: { self: true, pretty: DEV_MODE, }, }, include: path.resolve('src/html'), exclude: /node_modules/, }, ], }; config.performance = { maxEntrypointSize: 300000, hints: !DEV_MODE ? 'warning' : false, }; config.plugins = [ new HtmlWebpackPlugin({ template: 'html/index.pug', filename: 'index.html', data: { DEV_MODE, weinreScript: WEINRE_MODE ? `http://${getLocalhostIPAddress()}:8000/target/target-script-min.js#anonymous` : false, }, }), new CopyWebpackPlugin([ { from: 'assets/copy', to: './', ignore: ['.*'] }, ]), new ScriptExtHtmlWebpackPlugin({ defaultAttribute: 'defer', }), new MiniCssExtractPlugin({ filename: toCSSFilename('assets/css/[name]'), chunkFilename: toCSSFilename('assets/css/[name]-chunk'), }), /* new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify(DEV_MODE ? 'development' : 'production'), }, }), */ ...DEV_MODE ? [ new FriendlyErrorsPlugin(), ] : [ new CleanWebpackPlugin('./dist'), ], ]; config.optimization = { splitChunks: { chunks: 'all', automaticNameDelimiter: '-', cacheGroups: { vendors: { // name: 'vendors', chunks: 'all', test: /[\\/]node_modules[\\/]/, priority: -10, }, }, }, }; config.devServer = { historyApiFallback: true, noInfo: true, hot: true, port: 3000, stats: { chunks: false, chunkModules: false, colors: true, hash: false, }, host: '0.0.0.0', disableHostCheck: true, /* proxy: { '/socket.io/*': { // 這個一定要加,不然 socket.io 開三個視窗就會咬死 target: 'http://localhost:3002', ws: true, }, }, */ }; if (DEV_MODE) { Object.keys(config.entry).forEach((key) => { config.entry[key].unshift('react-hot-loader/patch'); }); } if (WEINRE_MODE) { config.plugins.push(new WeinreWebpackPlugin({ httpPort: 8000, boundHost: '0.0.0.0', verbose: false, debug: false, readTimeout: 5, })); } module.exports = config;
importApi("ui"); importApi("nav"); importClass("com.efurture.glue.ui.XmlViewLoadListener") importClass("android.widget.BaseAdapter"); importClass("com.efurture.gule.hybrid.adapter.StickyRecycleAdapter"); importClass("com.efurture.gule.hybrid.adapter.RecycleAdapter"); importClass("android.widget.PopupWindow"); importClass("android.view.View.OnClickListener"); var homeUrl = "./friends.xml"; var lifeCommunityItemXml = require('raw!./friends/lifeCommunityItem.xml'); var normalCellTopXml = require('raw!./friends/normalCellTop.xml'); var normalCellMiddleXml = require('raw!./friends/normalCellMiddle.xml'); var normalCellBottomXml = require('raw!./friends/normalCellBottom.xml'); var recycleView; // var page = { bindTabEvent : function(tabName){ if(tabName != 'home'){ var homeTabIcon = ui.find("homeTabTextIcon"); homeTabIcon.setOnClickListener(new OnClickListener(function () { nav.toUrl('./alipay.js', 'com.efurture.hybrid.demo.AlipayHomeActivity', true); })); var homeTabText = ui.find("homeTabText"); homeTabText.setOnClickListener(new OnClickListener(function () { nav.toUrl('./alipay.js', 'com.efurture.hybrid.demo.AlipayHomeActivity', true); })); } if(tabName != 'koubei'){ var koubeiTabIcon = ui.find("koubeiTabTextIcon"); koubeiTabIcon.setOnClickListener(new OnClickListener(function () { nav.toUrl('./koubei.js', 'com.efurture.hybrid.demo.AlipayHomeActivity', true); })); var koubeiTabText = ui.find("koubeiTabText"); koubeiTabText.setOnClickListener(new OnClickListener(function () { nav.toUrl('./koubei.js', 'com.efurture.hybrid.demo.AlipayHomeActivity', true); })); } if(tabName != 'friends'){ var friendsTabIcon = ui.find("friendsTabTextIcon"); friendsTabIcon.setOnClickListener(new OnClickListener(function () { nav.toUrl('./friends.js', 'com.efurture.hybrid.demo.AlipayHomeActivity', true); })); var friendsTabText = ui.find("friendsTabText"); friendsTabText.setOnClickListener(new OnClickListener(function () { nav.toUrl('./friends.js', 'com.efurture.hybrid.demo.AlipayHomeActivity', true); })); } if(tabName != 'wealth'){ var wealthTabIcon = ui.find("wealthTabTextIcon"); wealthTabIcon.setOnClickListener(new OnClickListener(function () { nav.toUrl('./wealth.js', 'com.efurture.hybrid.demo.AlipayHomeActivity', true); })); var wealthTabText = ui.find("wealthTabText"); wealthTabText.setOnClickListener(new OnClickListener(function () { nav.toUrl('./wealth.js', 'com.efurture.hybrid.demo.AlipayHomeActivity', true); })); } }, onLoadXml : function(){ var _self = this; //初始化listview var jsAdapter = { getItemCount : function() { return 30; }, onCreateView : function(parent, viewType){ var view = null; if(viewType == 'LifeCommunityItem'){ view = ui.fromXml(lifeCommunityItemXml, parent, false); }else if(viewType == 'NormalCellTop'){ view = ui.fromXml(normalCellTopXml, parent, false); }else if(viewType == 'NormalCellMiddle'){ view = ui.fromXml(normalCellMiddleXml, parent, false); }else if(viewType == 'NormalCellBottom'){ view = ui.fromXml(normalCellBottomXml, parent, false); }else{ view = ui.fromXml(lifeCommunityItemXml, parent, false); } print("getView js " + viewType ); return view; }, onBindView : function(view, position){ }, getItemViewType : function(position){ if(position == 0){ return 'LifeCommunityItem'; } if(position == 1){ return 'NormalCellTop'; } if(position == 29){ return 'NormalCellBottom'; } return 'NormalCellMiddle'; } }; recycleView = hybridView.findViewWithTag("recycleView"); recycleView.setAdapter(new RecycleAdapter(jsAdapter)); _self.bindTabEvent('friends'); } }; hybridView.onLoad = function(result){ page.onLoadXml(); }; hybridView.loadUrl(homeUrl);
export { ThemeProvider, Block, Section, Header, Footer, Button, Input, Label, SelectNative, MultiselectNative, Textarea, Toggle, Checkbox, Radio, FlexRow, FlexColumn, Area, Areas, Column, Columns, Grid, Halves, Thirds, Link, LinkEmail, LinkPhone, ListItem, LI, ListOrdered, OL, ListUnordered, UL, Typography, T, P, Pre, Heading, SubHeading, } from './components'
define( [ 'zepto' ], function ($) { var ajax = $.ajax; $.extend($, { isBlank: function (val) { return (val == null || val == "" || val == 'undefined'); }, getQueryString: function (name) { var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); var r = window.location.search.substr(1).match(reg); if (r != null)return unescape(r[2]); return null; }, isNumber: function (val) { var reg = /^\d+$/; if (!val.match(reg)) { return false; } return true; }, isPhone: function (val) { var reg = /^(13[0-9]|14\d{1}|15\d{1}|17\d{1}|18\d{1})\d{8}$/; return reg.test(val); }, ajax: function (param) { var loadMask = typeof(param.loadMask) !== 'undefined' ? param.loadMask : true; //是否支持遮罩层 var success = param.success || function () { }; var beforeSend = param.beforeSend || function () { }; var onError = param.onError || null; return ajax({ type: param.type || 'GET', url: param.url || "", dataType: param.dataType || null, data: param.data || {}, crossDomain: true, beforeSend: function (request) { beforeSend(request); //设置header请求 request.setRequestHeader("version", "1.0"); request.setRequestHeader("source", "weixin"); request.setRequestHeader("openid", storage.get("wxOpenid")); //设置openid //request.setRequestHeader("openid", "oLmqVt-1kevEVE36XHBehFGo1B-o"); //设置openid request.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); //request.setRequestHeader('Content-Type', 'application/json'); request.setRequestHeader('Request-Hash', window.location.href); if (loadMask) { $.Dialog.loading('show'); } }, success: function (data) { /** * 状态为1时,登录重定向 */ if (data.code == 1) { window.location.href = window.LOGIN_REDIRECT_URL; } /** * 状态不等于0时, 接口异常 */ if (data.err_code != 0) { if (data.err_code == 20001) { //状态为20001时,缺少access_token; //重新登陆; storage.remove("loginSuccess"); //window.location.href = window.LOGIN_REDIRECT_URL storage.set("loginSuccessBack", window.location.hash); //window.location.href = window.ctx + "/login.html"; window.location.href = window.LOGIN_REDIRECT_URL; } if (data.err_code == 20002) { //storage.remove("loginSuccess"); //状态为20002时,无效的accessToken //刷新接口访问凭证access_token 不报错 } else if (data.err_code == 20003) { //无效的refresh_token 重新登陆 //window.location.href = window.LOGIN_REDIRECT_URL storage.set("loginSuccessBack", window.location.hash); //window.location.href = window.ctx + "/login.html"; storage.remove("loginSuccess"); window.location.href = window.LOGIN_REDIRECT_URL; } else { if (data.err_code != 51002) {//解决夺宝详情中弹出“本期夺宝活动已经结束”问题 $.message("warning", { content: data.err_msg }); } } if (typeof param.onError == 'function') { param.onError(data); } } else { success(data); } }, error: param.error || function () { }, complete: param.complete || function (xhr, status) { //TODO 完成处理 if (loadMask) { $.Dialog.loading('hide'); } } }); }, message: function (type, param, callback) { var type = type || 'info'; var content = param.content || "数据请求失败,请重试!"; var stayTime = param.stayTime || 1500; var callback = callback || function () { }; var toast = $("#message-mask"); if (toast.length == 0) { $("body").append('<div id="message-mask"></div>'); toast = $("#message-mask"); } toast.empty().append('<div class=message-' + type + '>' + content + '</div>').show(); setTimeout(function () { toast.hide(); callback(); toast = null; }, stayTime); }, // 对话框 Dialog: { success: function () { var msg = typeof arguments[0] == 'string' ? arguments[0] : '已完成'; var expire = 1200; if (typeof arguments[1] == "number") { expire = arguments[1]; } else if (typeof arguments[0] == "number") { expire = arguments[0]; } var toast = "<div id=\"toast\"><div class=\"weui_mask_transparent\"></div><div class=\"weui_toast\"><i class=\"weui_icon_toast\"></i><p class=\"weui_toast_content\">" + msg + "</p></div></div>"; $("body").append(toast); setTimeout(function () { $("body").children("#toast").remove(); }, expire); }, warn: function (msg) { $.Dialog.alert(msg); }, error: function (msg) { $.Dialog.alert(msg); }, alert: function () { //var title = "警告"; var title = "夺宝号码"; var msg = ""; var callback = function () { }; if (arguments.length < 1) { throw new Error("Missing parameter!"); } else if (arguments.length == 1) { msg = arguments[0]; } else if (arguments.length == 2) { if (typeof arguments[0] == "string" && typeof arguments[1] == "string") { title = arguments[0]; msg = arguments[1]; } else if (typeof arguments[0] == "string" && typeof arguments[1] == "number") { msg = arguments[0]; callback = arguments[1]; } else { throw new Error("Invalid parameters!"); } } else if (arguments.length == 3) { if (typeof arguments[0] == "string" && typeof arguments[1] == "string" && typeof arguments[2] == "function") { title = arguments[0]; msg = arguments[1]; callback = arguments[2]; } else { throw new Error("Invalid parameters!"); } } var template = "<div class=\"weui_dialog_alert\" id=\"dialog_alert\">" + "<div class=\"weui_mask\"></div><div class=\"weui_dialog\">" + "<div class=\"weui_dialog_hd\"><strong class=\"weui_dialog_title\">" + title + "</strong></div><div class=\"weui_dialog_bd\">" + msg + "</div><div class=\"weui_dialog_ft\"><a href=\"javascript:;\" class=\"weui_btn_dialog btn_dialog_confirm primary\">确定</a></div></div></div>"; $("body").append(template); var $alert = $("body").children(".weui_dialog_alert"); $alert.find(".btn_dialog_confirm").click(function () { $alert.remove(); callback(); }); }, confirm: function () { if (typeof arguments[0] != "string" || typeof arguments[1] != "string" || typeof arguments[2] != "function") { throw new Error("Invalid parameters!"); } var title = arguments[0]; var msg = arguments[1]; var callback = arguments[2]; var cancelName = typeof arguments[3] == "string" ? arguments[3] : "取消"; var sureName = typeof arguments[4] == "string" ? arguments[4] : "确定"; var template = "<div class=\"weui_dialog_confirm\" id=\"dialog_confirm\"><div class=\"weui_mask\"></div><div class=\"weui_dialog\"><div class=\"weui_dialog_hd\"><strong class=\"weui_dialog_title\">" + title + "</strong></div><div class=\"weui_dialog_bd\">" + msg + "</div><div class=\"weui_dialog_ft\"><a href=\"javascript:;\" class=\"weui_btn_dialog btn_dialog_cancel default\">" + cancelName + "</a><a href=\"javascript:;\" class=\"weui_btn_dialog btn_dialog_confirm primary\">" + sureName + "</a></div></div></div>"; $("body").append(template); var $confirm = $("body").children(".weui_dialog_confirm"); $confirm.find(".btn_dialog_confirm").on('tap', function () { callback(); $confirm.remove(); }); $confirm.find(".btn_dialog_cancel").on("tap", function () { $confirm.remove(); }); }, loading: function () { var status = arguments[0] == 'show' ? 'show' : 'hide'; var loading = "<div id=\"loadingToast\" class=\"weui_loading_toast\"><div class=\"weui_mask_transparent\"></div><div class=\"weui_toast\"><div class=\"weui_loading\"><div class=\"weui_loading_leaf weui_loading_leaf_0\"></div><div class=\"weui_loading_leaf weui_loading_leaf_1\"></div><div class=\"weui_loading_leaf weui_loading_leaf_2\"></div><div class=\"weui_loading_leaf weui_loading_leaf_3\"></div><div class=\"weui_loading_leaf weui_loading_leaf_4\"></div><div class=\"weui_loading_leaf weui_loading_leaf_5\"></div><div class=\"weui_loading_leaf weui_loading_leaf_6\"></div><div class=\"weui_loading_leaf weui_loading_leaf_7\"></div><div class=\"weui_loading_leaf weui_loading_leaf_8\"></div><div class=\"weui_loading_leaf weui_loading_leaf_9\"></div><div class=\"weui_loading_leaf weui_loading_leaf_10\"></div><div class=\"weui_loading_leaf weui_loading_leaf_11\"></div></div><p class=\"weui_toast_content\">数据加载中</p></div></div>"; if (status == 'show') { $("body").append(loading); } else { $("body").children("#loadingToast").remove(); } }, info: function (msg) { $.message("warning", { content: msg, stayTime: 2000 }); } } }); var getLoginUrl = function (appId, redirectUri) { var url = redirectUri; if (isWeiXin()) { url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appId + "&redirect_uri=" + encodeURIComponent(redirectUri) + "&response_type=code&scope=snsapi_base&state=mxep#wechat_redirect"; } return url; }; var goBack = function (param) { var jumpHash = param.jumpHash || ""; var jumpUrl = param.jumpUrl || ""; $(".page").on("tap", ".he-header .he-header-left", function (e) { if ($(e.currentTarget).hasClass('btn-custom')) { return; } if (!$.isBlank(jumpHash)) { window.location.hash = jumpHash; return; } if (!$.isBlank(jumpUrl)) { window.location.href = jumpUrl; return; } history.back(); }); } var showHeader = function (param) { var jumpHash = param.jumpHash || ""; var jumpUrl = param.jumpUrl || ""; var title = param.title || ""; var showSearch = param.showSearch || false; var $wxHead = $(".wx-head"); $wxHead.show(); $(".he-footer").show(); $(".wx-head p").text(title); $(".wx-head button").off("tap").on("tap", function () { if ($.isBlank(jumpUrl)) { history.back(); return; } if (!$.isBlank(jumpHash)) { window.hash = jumpHash; } if (!$.isBlank(jumpUrl)) { window.location = jumpUrl; } }); if (showSearch) { $wxHead.find(".wx-he-search").removeClass("eh-hide"); } else { $wxHead.find(".wx-he-search").addClass("eh-hide"); } } var showPage = function (obj, callback) { obj.siblings(".page").empty().addClass("eh-hide"); obj.removeClass("eh-hide"); if (typeof callback == 'function') { callback(); } } /** * web存储 */ var storage = { set: function (key, value) { return localStorage.setItem(key, value); }, get: function (key) { return localStorage.getItem(key); }, remove: function (key) { return localStorage.removeItem(key); } }; /** * 激活菜单 */ var activeMenu = function (sort) { var obj; switch (sort) { case 5: obj = $("#menu-page #my"); break; case 4: obj = $("#menu-page #shoppingCart"); break; case 3: obj = $("#menu-page #find"); break; case 2: obj = $("#menu-page #announced"); break; case 1: obj = $("#menu-page #homepage"); default: break; } //obj.addClass("active").siblings(".ui-col").removeClass("active"); // obj.siblings().removeClass("highlight"); // obj.addClass("highlight"); obj.siblings().removeClass("active"); obj.addClass("active"); }; var flyToCart = function (e, url) { var $this = $(e.currentTarget); var offset = $('#he-shoppingcart').offset(), flyer = $("<img class=\"u-flyer\" src='" + url + "' />"); flyer.fly({ start: { left: e.touches[0].pageX, top: e.touches[0].pageY }, end: { left: offset.left + 22, top: offset.top, width: 20, height: 20 }, onEnd: function () { $(".u-flyer").remove(); } }); }; /** * 显示菜单 */ var showMenu = function () { //debugger var $menuPage = $("#menu-page"); if (storage.get("has_goods") == 1) { var $a = $menuPage.find(".he-btn-shoppingcart").find("a"); if ($a.find(".point").length <= 0) { $a.append("<p class=\"point\"></p>"); } } $menuPage.removeClass("eh-hide"); }; /** * 隐藏菜单 */ var hideMenu = function () { $("#menu-page").addClass("eh-hide"); //$("#menu-page").removeClass("eh-show"); }; var getParam = function (paramName) { //获取当前URL var local_url = document.location.href; //获取要取得的get参数位置 var get = local_url.indexOf(paramName + "="); if (get == -1) { return false; } //截取字符串 var get_par = local_url.slice(paramName.length + get + 1); //判断截取后的字符串是否还有其他get参数 var nextPar = get_par.indexOf("&"); if (nextPar != -1) { get_par = get_par.slice(0, nextPar); } return get_par; }; var Navigator = { currentPosition: function (success, error) { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function (position) { var coords = position.coords; console.info(coords.latitude + ', ' + coords.longitude); if (typeof success == 'function') { success(coords.longitude, coords.latitude); // callback('120.73301925701467', '31.25901492308543'); } }, function (error) { switch (error.code) { case error.TIMEOUT: console.info("A timeout occured! Please try again!"); break; case error.POSITION_UNAVAILABLE: console.info('We can\'t detect your location. Sorry!'); break; case error.PERMISSION_DENIED: console.info('Please allow geolocation access for this to work.'); break; case error.UNKNOWN_ERROR: console.info('An unknown error occured!'); break; } if (typeof error == 'function') { error(error.code); } }, { enableHighAccuracy: true, timeout: 6000, maximumAge: 3000 }); } else { alert("Your browser does not support Geolocation!"); } } }; // 判断对象内容是否为空 var isEmpty = function ($obj) { return $obj.html() ? false : true; }; // 最长字符串 var maxLength = function (str, length) { var s = str; if (str.length > length) { s = str.substring(0, length) + "..."; } return s; }; var showShareMask = function ($page) { var mask = '<div class="mask-title"><img src="assets/image/share_menu.png" alt=""/></div>'; $page.find(".mask-title").remove(); $page.append(mask); $page.find(".mask-title").on("tap", function () { $page.find(".mask-title").remove(); }); }; /** * 登陆成功后 loginSuccesss 置为 param(yes) */ var loginSuccess = function () { //var ta = param || "yes"; storage.set("loginSuccess", "yes"); }; /** * 判断是否登陆 */ var isLogined = function () { if (storage.get("loginSuccess") == "yes") { return true; } else { return false; } }; /** *获取倒计时时间 * @param {type} self [] * @param {type} position [位置] "秒杀" * @param {type} status [状态] * @param {type} flag [] */ var timeCountDown = function (self, position, status, flag) { //debugger // status var start = $(self).attr("data-starttime");//开始时间 var end = $(self).attr("data-endtime");//结束时间 var now = $(self).attr("data-currenttime");//当前系统时间 if (!now) { return } if (start) { start = start.replace(/\-/g, "/"); } if (end) { end = end.replace(/\-/g, "/"); } if (now) { now = now.replace(/\-/g, "/"); } var currentTime = new Date(now).getTime(); var startTime = new Date(start).getTime(); var endTime = new Date(end).getTime(); var intDiff; if (flag) { intDiff = flag - 1; } else { switch (position) { case "flashSale"://秒杀页面 if (status == 1) {//即将开始 intDiff = (startTime - currentTime) / 1000; } else if (status == 2) {//抢购中 intDiff = (endTime - currentTime) / 1000; } else {//已结束 } break; case "main"://首页 intDiff = (endTime - currentTime) / 1000; break; case "annouced"://揭晓 intDiff = (endTime - currentTime) / 1000; } } // time = new Date(time).getTime(); // var now = new Date().getTime(); if (intDiff > 0) { var second = Math.floor(intDiff % 60); var minute = Math.floor((intDiff / 60) % 60); var hour = Math.floor((intDiff / 3600)); hour = hour < 10 ? "0" + hour : hour; minute = minute < 10 ? "0" + minute : minute; second = second < 10 ? "0" + second : second; var count_down = hour + ":" + minute + ":" + second; $(self).html(count_down); } else { //$(self).html("时间截止"); $(self).html(""); return } setTimeout(function () { timeCountDown(self, position, status, intDiff); }, 1000) }; //分,秒,毫秒倒计时 var MSCountDown = function (self, toEnd) { var current_time = $(self).data("currenttime");//当前时间 var expire_time = $(self).data("expiretime");//结束时间 var currentTime = new Date(current_time).getTime(); var expireTime = new Date(expire_time).getTime(); var intDiff = expireTime - currentTime; var handler = window.setInterval(function () { intDiff = intDiff - 20; if (intDiff > 0) { var ms = Math.floor(intDiff % 1000 / 10); // console.log(ms); var sec = Math.floor(intDiff / 1000 % 60); var min = Math.floor(intDiff / 1000 / 60 % 60); var hour = Math.floor(intDiff / 1000 / 60 / 60 % 24); hour = hour < 10 ? "0" + hour : hour; min = min < 10 ? "0" + min : min; sec = sec < 10 ? "0" + sec : sec; ms = ms < 10 ? "0" + ms : ms; //var count_down = hour + ":" + min + ":" + sec + ":" + ms; var count_down = min + ":" + sec + ":" + ms; $(self).html(count_down); } else { $(self).html("时间结束"); // $(".btn_pay").removeClass("bg-ff6e2b").removeClass("btn_pay").addClass("ba-bfbfbf-css"); window.clearInterval(handler); typeof toEnd == 'function' && toEnd(1); return; } }, 20) }; //json格式转换为字符串 var jsonParseParam = function (param, key) { var paramStr = ""; if (param instanceof String || param instanceof Number || param instanceof Boolean) { paramStr += "&" + key + "=" + encodeURIComponent(param); } else { $.each(param, function (i) { var k = key == null ? i : key + (param instanceof Array ? "[" + i + "]" : "." + i); paramStr += '&' + jsonParseParam(this, k); }); } return paramStr.substr(1); }; //获取地址栏 参数 var getUrl = function (message) {//http://mxep:91/#sign?access_token=444 //debugger var url; if (message) { url = message; } else { url = location.href; } if (url.indexOf("?") > -1) { var params = url.substr(url.indexOf("?") + 1, url.length).split("&"); for (var i = 0; i < params.length; i++) { var param = params[i].split("="); storage.set(param[0], param[1]); } } }; //解决 fz.Scroll冲突 var clearTab = function (id) { var ids = new Array("my-mxb-page", "my-package-page", "my-integral-page", "my-announced-record-page", "my-order-page"); for (var i = 0; i < ids.length; i++) { if (ids[i] != id) { $("#" + ids[i]).empty(); } } }; return { showPage: showPage, showHeader: showHeader, storage: storage, activeMenu: activeMenu, getParam: getParam, showMenu: showMenu, goBack: goBack, hideMenu: hideMenu, Navigator: Navigator, isEmpty: isEmpty, maxLength: maxLength, flyToCart: flyToCart, showShareMask: showShareMask, getLoginUrl: getLoginUrl, loginSuccess: loginSuccess, isLogined: isLogined, timeCountDown: timeCountDown, MSCountDown: MSCountDown, jsonParseParam: jsonParseParam, getUrl: getUrl, clearTab: clearTab, }; } );
class body{ constructor(_x,_y){ this.x=_x; this.y=_y; } draw(){ rect(this.x*blockSize,this.y*blockSize,blockSize-1,blockSize-1); } };
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); module.exports = { original: 'out of the scope', }
console.log("Is 42 an Integer: " + Number.isInteger(42)); console.log(`Is 3.43 an Integer: ${Number.isInteger(3.43)}`);
import React from 'react'; const Footer = () => { return ( <footer> <p>Telkom Digital Incubator &#169; 2019, PT.Telkom Indonesia</p> </footer> ); }; export default Footer;
const router = require("express").Router() const storage = require("../libs/storage") const fileupload = require("express-fileupload") router.use(fileupload()) router.get("/upload", (req, res)=>{ res.sendFile(__dirname + "/plantillaSubida.html") }) router.post("/upload", (req, res)=> { if(!req.files || Object.keys(req.files).length === 0) { return res.status(400).send("No files uploaded.") } let file = req.files.foto //foto debe ser el campo nombre del input field en el form // console.log("Me enviaron " + req.files.foto.name); // console.log("Me enviaron " + req.files.OtraFoto.name); file.mv(`${storage}/${file.name}`, err => { if (err) { console.log(err) return res.status(500).send({ message : `Error during saving process: ${err}` }) } // res.redirect("/a") const time = new Date() return res.status(200).send({ message : "Upload successfully.", date: `${time.toDateString()}, ${time.getHours()}:${time.getMinutes()}` }) }) }) module.exports = router
import './AboutMe.css'; function AboutMe () { return ( <div className='AboutMe'> <body className='aboutMe-body'> <main className='aboutMe-main'> <h1> About Me </h1> </main> <p> Hello, my name is Veronica. I am a 2nd year CS major. I am a big fan of sweets, tea, hikes, birds, embroidery, movies, games, and christmas. </p> </body> </div> ); } export default AboutMe;
// main.js // Modules to control application life and create native browser window const { app, BrowserWindow, ipcMain, dialog, shell, Menu } = require('electron') const path = require('path') let mainWindow const template = [ { label: 'DB', submenu: [ { label: 'Change Database' } ] }, { label: 'Info', submenu: [ { label: 'GitHub', click(){ shell.openExternal("https://github.com/RiccardoZuninoJ/StockTaker") } }, { label: 'Developer', click(){ shell.openExternal("https://github.com/RiccardoZuninoJ") } } ] } ] const menu = Menu.buildFromTemplate(template) Menu.setApplicationMenu(menu) function createWindow () { // Create the browser window. mainWindow = new BrowserWindow({ width: 800, height: 600, webPreferences: { nodeIntegration: true, contextIsolation: false, }, menu: menu }) // and load the index.html of the app. mainWindow.loadFile('pages/index.html') // Open the DevTools. // mainWindow.webContents.openDevTools() } // This method will be called when Electron has finished // initialization and is ready to create browser windows. // Some APIs can only be used after this event occurs. app.whenReady().then(() => { createWindow() app.on('activate', function () { // On macOS it's common to re-create a window in the app when the // dock icon is clicked and there are no other windows open. if (BrowserWindow.getAllWindows().length === 0) createWindow() }) }) // Quit when all windows are closed, except on macOS. There, it's common // for applications and their menu bar to stay active until the user quits // explicitly with Cmd + Q. app.on('window-all-closed', function () { if (process.platform !== 'darwin') app.quit() }) // In this file you can include the rest of your app's specific main process // code. You can also put them in separate files and require them here. ipcMain.on("connect", (event, data) => { mainWindow.loadFile("pages/connect.html") }) ipcMain.on("remove", (event, data) => { let options = { buttons: ["Yes","No"], message: "Are you sure you want to remove product #" + data + "?" } let response = dialog.showMessageBoxSync(options) console.log(response) if(response == 0) { mainWindow.webContents.send("remove_from_db", data) } }) ipcMain.on("refresh", (event, data) => { mainWindow.reload() }) ipcMain.on("goto", (event, data) => { mainWindow.loadFile('pages/'+data) }) ipcMain.on("openlink", (event, data) => { shell.openExternal(data) })
import Chart from 'chart.js'; import { isEqual, round } from 'lodash'; import PropTypes from 'prop-types'; import React, { Component } from 'react'; import injectStyles from '@/utils/injectStyles'; import { COLORS } from '@/utils/styleConstants'; import styles from './styles'; class BarChart extends Component { constructor(props) { super(props); this.barChartRef = React.createRef(); this.chartInstance = undefined; } componentDidMount() { this.renderChart(); } componentDidUpdate(prevProps) { if (!isEqual(prevProps.values, this.props.values)) { this.chartInstance.destroy(); this.renderChart(); } } componentWillUnmount() { this.chartInstance.destroy(); } shouldComponentUpdate(nextProps) { const { height, width, values } = this.props; return ( !isEqual(values, nextProps.values) || width !== nextProps.width || height !== nextProps.height ); } getMiddle = () => { const { values: { min, max } } = this.props; return round((max + min) / 2, 2); }; getMinMax = () => { const { values: { min, max } } = this.props; return { min: round(min - ((max - min) * 33) / 17, 2), max: round(max + ((max - min) * 50) / 17, 2) }; }; getTicks = () => { const { values: { min, max } } = this.props; return [min, this.getMiddle(), max]; }; getDatasets = () => { const { values: { min, max, value } } = this.props; const middle = this.getMiddle(); const mainProps = { backgroundColor: '#4D4F4F', borderWidth: 1, borderColor: 'white' }; const middleProps = { ...mainProps, backgroundColor: '#979797' }; const datasets = []; const { min: axisMin } = this.getMinMax(); // Fill an empty space before the zero point if (axisMin < 0 && value > 0) { datasets.push({ data: [axisMin], ...mainProps }); } if (value <= min) { datasets.push({ data: [value], ...mainProps }); } if (value > min && value <= max) { datasets.push({ data: [min], ...mainProps }); if (value <= middle) { datasets.push({ data: [value - min], ...middleProps }); } else { datasets.push( { data: [round(middle - min, 2)], ...middleProps }, { data: [round(value - middle, 2)], ...middleProps } ); } } if (value > max) { datasets.push( { data: [min], ...mainProps }, { data: [round(middle - min, 2)], ...middleProps }, { data: [round(max - middle, 2)], ...middleProps }, { data: [round(value - max, 2)], ...mainProps } ); } return datasets; }; renderChart = () => { const { values: { value: currentValue } } = this.props; const datasets = this.getDatasets(); const node = this.barChartRef.current; const ticks = this.getTicks(); this.chartInstance = new Chart(node, { type: 'horizontalBar', data: { datasets }, options: { legend: { display: false }, scales: { xAxes: [ { stacked: true, // @see https://www.chartjs.org/docs/latest/axes/styling.html#tick-configuration ticks: { autoSkip: false, callback(value) { if (!ticks.includes(value)) { return undefined; } return value; }, fontColor: COLORS.CHARTS.TICK, fontFamily: 'Open Sans', fontSize: 10, maxRotation: 0, stepSize: 0.01, ...this.getMinMax() } } ], yAxes: [ { stacked: true } ] }, title: { display: true, position: 'right', text: round(currentValue, 2), fontSize: 17, fontFamily: 'Roboto Condensed', fontColor: '#4D4F4F', fontStyle: 'bold' }, tooltips: { enabled: false } } }); }; render() { const { className, height, width } = this.props; return ( <div className={className}> <canvas ref={this.barChartRef} height={height} width={width} /> </div> ); } } BarChart.propTypes = { className: PropTypes.string.isRequired, height: PropTypes.number, values: PropTypes.shape({ max: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), min: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), value: PropTypes.oneOfType([PropTypes.number, PropTypes.string]) }).isRequired, width: PropTypes.number }; BarChart.defaultProps = { height: 60, width: 426 }; BarChart.displayName = 'BarChartComponent'; // BarChart.whyDidYouRender = true; export default injectStyles(BarChart, styles);
const QrcodeTerminal = require('qrcode-terminal'); const { ScanStatus } = require('wechaty-puppet') /** * @method onScan 当机器人需要扫码登陆的时候会触发这个事件。 建议你安装 qrcode-terminal(运行 npm install qrcode-terminal) 这个包,这样你可以在命令行中直接看到二维码。 * @param {*} qrcode * @param {*} status */ const onScan = async (qrcode, status) => { try { if (status === ScanStatus.Waiting) { console.log(`========================👉二维码状态:${status}👈========================\n\n`) QrcodeTerminal.generate(qrcode, { small: true }) } } catch (error) { console.log('onScan', error) } } module.exports = { onScan }
import React, { useState, useEffect } from 'react'; import Form from './components/PhonebookForm'; import ContactList from './components/ContactList'; import Filter from './components/Filter'; import PropTypes from 'prop-types'; import { wrapper, title, subtitle } from './App.module.scss'; const App = ({ initialValue }) => { const [contacts, setContacts] = useState(initialValue); const [filter, setFilter] = useState(''); // Записывает значения инпута в стейт const handleInputFilter = e => setFilter(e.target.value); // Добавляет новый контакт в стейт const handleSubmit = newContact => contacts.find( ({ name }) => name.toLowerCase() === newContact.name.toLowerCase(), ) ? alert(`${newContact.name} is already in contacts.`) : setContacts(prevState => [newContact, ...prevState]); // Фильтрация контактов const normalizedFilter = filter.toLowerCase(); const filteredContacts = contacts.filter(contact => contact.name.toLowerCase().includes(normalizedFilter), ); // Deletes contact const handleDeleteContact = id => setContacts(contacts.filter(contact => contact.id !== id)); // Получает контакты из localStorage useEffect(() => { setContacts(JSON.parse(localStorage.getItem('contacts'))); }, []); // Добавляет контакты в localStorage useEffect(() => { localStorage.setItem('contacts', JSON.stringify(contacts)); }, [contacts]); return ( <div className={wrapper}> <h1 className={title}>Phonebook</h1> <Form onInputChange={handleInputFilter} onSubmit={handleSubmit} /> <h2 className={subtitle}>Contacts</h2> <Filter value={filter} onChange={handleInputFilter} /> <ContactList contacts={filteredContacts} filter={filter} onInputChange={handleInputFilter} onDeleteContact={handleDeleteContact} /> </div> ); }; App.defaultProps = { initialValue: [], }; App.propTypes = { initialValue: PropTypes.arrayOf( PropTypes.shape({ id: PropTypes.string.isRequired, name: PropTypes.string.isRequired, number: PropTypes.string.isRequired, }), ), }; export default App;
var defaultState = { latitude:'', longitude:'' } const userLocationReducer = (state = defaultState,action)=>{ switch(action.type){ case 'SET_CURRENT_LOCATION': return { latitude:action.latitude, longitude:action.longitude }; default: return state; } } export default userLocationReducer;
/* Given a string, find the length of the longest substring in it with no more than K distinct characters. Input: String="araaci", K=2 Output: 4 Explanation: The longest substring with no more than '2' distinct characters is "araa". Input: String="araaci", K=1 Output: 2 Explanation: The longest substring with no more than '1' distinct characters is "aa". Input: String="cbbebi", K=3 Output: 5 Explanation: The longest substrings with no more than '3' distinct characters are "cbbeb" & "bbebi". */ str = "araaci"; K = 3; function sizeKsumStrK(str, K) { let charCount = {}; let windowStart = 0; let longestLength = 0; for(let windowEnd = 0; windowEnd < str.length; windowEnd++) { if(charCount[str[windowEnd]]) { charCount[str[windowEnd]] += 1; } else { charCount[str[windowEnd]] = 1; } while(Object.keys(charCount).length > K) { charCount[str[windowStart]] -= 1; if(charCount[str[windowStart]] === 0) { delete charCount[str[windowStart]]; } windowStart++; } const windowLength = windowEnd - windowStart + 1; longestLength = Math.max(longestLength, windowLength) } return console.log(longestLength); } sizeKsumStrK(str, K);
import React, { Component } from "react"; import PropTypes from "prop-types"; import InputGroup from "./InputGroup"; export default class Input extends Component { componentDidUpdate() { this.adjustTextareaHeight(this.component); } componentDidMount() { this.adjustTextareaHeight(this.component); if (this.props.focus) { this.component && this.component.focus(); } } adjustTextareaHeight(textarea) { if (textarea && textarea.tagName === "TEXTAREA") { textarea.style.height = 0; textarea.style.height = textarea.scrollHeight + "px"; } } getId = () => { return `input-${this.props.name}`; }; renderInputField = () => { const { type } = this.props; const id = this.getId(); return type === "textarea" ? ( <textarea id={id} {...this.props} ref={component => { this.component = component; }} /> ) : ( <input id={id} {...this.props} ref={component => { this.component = component; }} /> ); }; render() { return ( <InputGroup label={this.props.label} inputId={this.getId()}> {this.renderInputField()} </InputGroup> ); } } Input.propTypes = { name: PropTypes.string.isRequired, value: PropTypes.string.isRequired, type: PropTypes.string, maxLength: PropTypes.number, onChange: PropTypes.func.isRequired }; Input.defaultProp = { type: "text" };
const express = require('express'); const app = express(); const http = require('http').createServer(app); const cors = require('cors'); const io = require('socket.io')(http,{ cors:{ origin:'http://localhost:3000', methods:['GET','POST'], } }) app.use(cors()); require('./sockets/index')(io); app.get('/' ,(req,res) => { res.sendFile(__dirname + '/public/index.html'); }) app.use(express.static(__dirname + '/public')); http.listen(3000, () => { console.log('servidor rodando') })
'use strict'; describe('Service: BatchData', function () { // load the service's module beforeEach(module('batchUtilApp')); // instantiate service var BatchData; beforeEach(inject(function (_BatchData_) { BatchData = _BatchData_; })); /*it('should do something', function () { expect(!!BatchData).toBe(true); });*/ });
import Markdown from 'pagedown-with-extra-bootstrap/pagedown.js'; import hljs from 'highlightjs/highlight.pack.js' export default function initiate_editor(){ $('textarea.wmd-input').each(function(i, input) { var attr, converter, editor; attr = $(input).attr('id').split('wmd-input')[1]; converter = new Markdown.Converter(); Markdown.Extra.init(converter, {highlighter: "highlight"}); editor = new Markdown.Editor(converter, attr); return editor.run(); }); $('pre code').each(function(i, block) { hljs.highlightBlock(block); }); };
export default function reducer(state, action) { switch (action.type) { case 'PhoneInputAction': return { ...state, phone_no: action.payload }; case 'passwordInputAction': return { ...state, password: action.payload }; case 'GET_DATA': return { ...state, userType: action.payload } case 'SHOWLOGINUPDATE': return { ...state, showLogin: action.payload }; default: return state; } }
/** * @Author - Mochamad Yudi Sobari * @contact - myudisobari12@gmail.com * @version - 0.0.1 * @type - Development */ const express = require("express"); const router = express.Router(); const { check, validationResult } = require("express-validator"); /** * @Access - Private * @Method - POST * @define - Create Cart */ router.post('/'); /** * @Access - Private * @Method - GET * @define - Get Cart * @desc - Get Token if Login */ router.get('/me'); module.exports = router
exports.createPages = async function ({ actions, graphql }) { const { data } = await graphql(` query { allMdx { edges { node { frontmatter { published slug } } } } } `); data.allMdx.edges.forEach((edge) => { const { published, slug } = edge.node.frontmatter; if (!!published) { actions.createPage({ path: `article/${slug}`, component: require.resolve("./src/templates/ArticleLayout.jsx"), context: { slug: slug }, }); } }); }; // Leaflet expects window to be defined exports.onCreateWebpackConfig = ({ stage, loaders, actions }) => { if (stage === "build-html" || stage === "develop-html") { actions.setWebpackConfig({ module: { rules: [ { test: /leaflet/, use: loaders.null(), }, ], }, }); } };
const knexService = require('feathers-knex') const { fastJoin, discard, disallow } = require('feathers-hooks-common') module.exports = function () { const app = this; const db = app.get('db') const web3 = app.get('web3') const paginate = app.get('paginate') const options = { id: 'eth_address', name: 'users', Model: db, paginate }; const profileJoins = { // This is currently 1+N queries. profile_image: () => async profile => profile.profile_image = (await db('uploads').where('id', profile.profile_image_id))[0] } // Initialize our service with any options it requires app.use('/api/profiles', knexService(options)) // Get our initialized service so that we can register hooks and filters const service = app.service('api/profiles') service.hooks({ before: { get: function(hook) { hook.id = hook.id.toLowerCase() }, remove: disallow(), update: disallow(), patch: disallow() }, after: { get: async function(hook) { // hook.result.uploads = await db('uploads').whereIn('id', JSON.parse(hook.result.upload_ids)) delete hook.result.email }, all: [fastJoin({joins: profileJoins})] } }); // if (service.filter) { // service.filter(filters); // } };
const express = require('express'); const Api = require('./my_utils/api'); const dbModel = require('./my_utils/dbModel'); const app = express(); const port = 3000; var bodyParser = require('body-parser') app.use(bodyParser.urlencoded({ extended: false })) // parse application/json app.use(bodyParser.json()); app.get('/_status', (req, res) => res.send('Success')) app.post('/portfolio/metrics',dbModel.getMetricsPortfolio); app.post('/pairwise/metrics', dbModel.getMetricsPair); app.listen(port, () => console.log(`Example app listening on port ${port}!`))
import { createSelector } from 'reselect'; export const getApplication = state => state.application; export const getSurveys = createSelector( getApplication, application => application.surveys ); export const getSelectedSurvey = createSelector( getApplication, application => application.selectedSurvey );
import React from 'react'; import { Link } from 'react-router-dom'; import Like from '../containers/Like' import '../css/userCard.css' export default class UserCard extends React.Component { render() { const { avatar, username, popularity } = this.props.user.member; const urlProfile = '/members/'+username; return ( <div className="card col-md-6 col-sm-6 col-xs-6"> <div className="card-body text-center"> <Link to={urlProfile}><img className="card-img-top col-md-6 col-sm-6 col-xs-6" src={avatar} alt='' /></Link> <h4 className="card-title"><Link to={urlProfile}>{username}</Link></h4> <h5 className="card-text">{popularity} points</h5> <Like user={this.props.user.member} /> </div> </div> ); } }
/** * The module ‘hujirequestparser’ which exposes one method: * parse(string) return HttpRequest object. */ var httpobj = require('./httpobj'); /* * Read the rest of the line in a string, starting from a given index. * Note that it does no checks - assumes validity of the string, * assumes string.length > startIndex and assumes the last * character of a line is \n (as well as the last character of the * string if a body exists, two if not) */ function readLine(string, startIndex) { var line; line = /[^\n]*\n/.exec(string.toString().substring((startIndex ? startIndex : 0))); return line ? line[0] : ""; } function trimString(str) { return str.replace(/^\s\s*/, '').replace(/\s\s*$/, ''); // trim beginning and end } /* * extracts the headers and fills the header object */ function parseNameValuePairsLine(obj, line, pairsDelim, nameValDelim) { var pairs, lhPair, lhName, lhVal, idx; pairsDelim = pairsDelim || ';'; nameValDelim = nameValDelim || '='; pairs = line.split(pairsDelim); // search all occurrences of the type "someName=someValue" // (allow spaces after the first real character) for (lhPair in pairs) { if (pairs.hasOwnProperty(lhPair) && pairs[lhPair]) { idx = pairs[lhPair].search(nameValDelim); lhName = trimString(pairs[lhPair].substring(0, idx)); lhVal = trimString(pairs[lhPair].substring(idx + 1)); obj[lhName] = lhVal; } } } function extractHeadersAndCookies(string, cursor, headers, cookies) { var currLine, currHeader, headerName, headerVal; currHeader = ""; do { currLine = readLine(string, cursor); cursor += currLine.length; if (currHeader === "" || (/^\s/.test(currLine) && /[^\s]/.test(currLine))) { currHeader += currLine; } else { // parse current header headerName = (/[^:]+:/.exec(currHeader))[0]; headerVal = ((/[^\s].*/.exec(currHeader.substring(headerName.length))))[0]; headerName = headerName.substring(0, headerName.length - 1).toLowerCase(); if (headerName == "cookie") { parseNameValuePairsLine(cookies, headerVal); } else { headers[headerName] = headerVal; } currHeader = currLine; } } while (/[^\s]/.test(currLine) && cursor < string.length); return cursor; } function extractQuery(query, req) { query = query.split('?'); var pairs = {}; req.path = query[0]; if (query.length > 2) { throw Error("Bad request - more than one question mark" + query[1]); } if (query[1]) { if (query[1].search(/(&&)|(==)|(=&)|(&=)/) >= 0) { throw Error("Bad request - illegal query form: " + query[1]); } parseNameValuePairsLine(pairs, query[1], '&'); var val; for (val in pairs) { if (pairs.hasOwnProperty(val)) { var objVal = pairs[val].replace(/\+/gm, ' '); // if contains an object like "shoes[color]=blue" if (/[^\s\[]+\[.+]/.test(val)) { var idx = val.search(/\[/); var objName = val.substring(0, idx); if (!req.query[objName]) { req.query[objName] = {}; } req.query[objName][val.substring(idx + 1, val.length -1)] = objVal; } else { req.query[val] = objVal; } } } } } function parseReqBody(req, body) { if (!body) { req.body = ""; return; } if (req.is('application/x-www-form-urlencoded')) { req.body = {}; parseNameValuePairsLine(req.body, body, '&'); } else if (req.is('json')) { try { req.body = JSON.parse(body); } catch (e) { req.body = body.toString(); console.log("Exception while parsing json: " + e); } } else { req.body = body.toString(); } } /** * Parse a single http request and returns an * httpRequest instance with it's data * assumes a valid http request! undefined behavior * if not (might throw exceptions) */ module.exports = { parse : function(string) { var cursor, currLine, header, headers, cookies; cursor = 0; // current location in the string headers = {}; cookies = {}; // Get initial line header = readLine(string, cursor); cursor += header.length; header = header.split(" "); // Get headers cursor = extractHeadersAndCookies(string, cursor, headers, cookies); // getting one more line down currLine = readLine(string, cursor); cursor += currLine.length; // build and return the httpRequest instance var req = httpobj.request(); req.method = header[0]; extractQuery(header[1], req); // Parse path and query var protocol = header[2].replace(/\s/g, ""); protocol = protocol.split('/'); req.protocol = protocol[0].toLowerCase(); req.version = protocol[1]; req.headers = headers; var body = string.toString().substring(cursor); parseReqBody(req, body); req.cookies = cookies; req.host = headers['host']; return req; } };
$(document).ready(() => { console.log(localStorage.getItem('testObject')); document.getElementById("result").innerHTML =localStorage.getItem('testObject'); document.getElementById("result").style.color="white"; $.get('/api/transactions/propPending',function(res){ console.log("props"+res); let x=""; x+="<tr><th> registration_no </th>" +"<th> owner_id </th>" +"<th> owner_name </th>" +"<th> locality_id </th>" +"<th> current_status </th>" +"<th> address </th>" +"<th> area </th>" +"<th> status </th></tr>"; for(let i=0;i<res.length;i++) { x+="<tr><td>"+res[i].registration_no+"</td>" +"<td>"+res[i].owner_id+"</td>" +"<td>"+res[i].owner_name+"</td>" +"<td>"+res[i].locality_id+"</td>" +"<td>"+res[i].current_status+"</td>" +"<td>"+res[i].address+"</td>" +"<td>"+res[i].area+"</td>" +"<td>"+res[i].status+"</td></tr>"; } document.getElementById("table_2").innerHTML=x; }); $.get('/api/transactions/landPending',function(res){ console.log("props"+res); let x=""; x+="<tr><th> Registration_no </th>" +"<th> Registration Date </th>" +"<th> Seller </th>" +"<th> Locality ID </th>" +"<th> Property_ID </th>" +"<th> Deed ID </th>" +"<th> Subdeed ID </th>" +"<th> SRO Office ID </th>" +"<th> Book No.</th>" +"<th> Mode of Payment </th>" +"<th>Buyer </th>" +"<th> Status </th>" +"<th> Property_of </th>" +"<th> price </th></tr>"; for(let i=0;i<res.length;i++) { x+="<tr><td>"+res[i].registration_number+"</td>" +"<td>"+res[i].reg_date+"</td>" +"<td>"+res[i].first_party_1+"</td>" +"<td>"+res[i].locality_id+"</td>" +"<td>"+res[i].prop_id+"</td>" +"<td>"+res[i].deed_id+"</td>" +"<td>"+res[i].subdeed_id+"</td>" +"<td>"+res[i].sro_office_id+"</td>" +"<td>"+res[i].book_no+"</td>" +"<td>"+res[i].mode_of_payment+"</td>" +"<td>"+res[i].second_party_id+"</td>" +"<td>"+res[i].status+"</td>" +"<td>"+res[i].property_of+"</td>" +"<td>"+res[i].property_price+"</td>" +"</tr>"; } document.getElementById("table_1").innerHTML=x; }); $('#validate').click(() => { console.log("Reached"); $.post('/api/transactions/validateTransferLand', {id: $('#id').val()},function (res) { // $.post('/validateTransferLandTransaction',{index: $('#id').val()},function (res) { //writeCookie("govt",$('#email').val(),10); alert("VALIDATED"); window.location.href = "/"; // }); }); }); $('#validate1').click(() => { console.log("Reached"); $.post('/api/transactions/validateAddLand', {id: $('#id1').val()},function (res) { //writeCookie("govt",$('#email').val(),10); // $.post('/validateAddLandTransaction',{index: $('#id1').val()},function (res) { //writeCookie("govt",$('#email').val(),10); alert("VALIDATED"); window.location.href = "/"; // }); }); }); $('#register').click(() => { window.location.href = "/register_govt_official" }); });
str = "2+5*2+4"; function express(str) { let stack = []; let temp = 0; let val; for (let i = 0; i < str.length; i++) { if (!isNaN(str[i])) { stack.push(str[i]); } if (str[i] == "*") { let pop = stack.pop(str[i]); //console.log(pop) let current = stack.pop(); //console.log(current) stack.push(pop * current); } } for (let i = 0; i < stack.length; i++) { val = stack.pop(stack[i]); val += val; } console.log(stack); } express(str);
console.log('loaded'); document.addEventListener("DOMContentLoaded", function(event) { console.log('DOMContentLoaded'); document.querySelector('#b') .addEventListener('click', e => { console.log('posting'); fetch('api/run',{ method: 'post', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: JSON.stringify({data:42}) }).then(resp => { console.log('got response', resp); return resp.json(); }) .then(j => { console.log('got json', j); }); }); });
const path = require("path"); const webpack = require("webpack"); const { CleanWebpackPlugin } = require('clean-webpack-plugin'); //清除 const vendor = [ "vue-router/dist/vue-router.esm.js", "vuex/dist/vuex.esm.js", "axios", "nprogress", "element-ui", "vue-schart" ]; var groupVendor = {}; let num = 2; //分组个数 let key = 1; for(var i=0;i<vendor.length;i+=num){ groupVendor['vendor'+key] = vendor.slice(i,i+num); key +=1; } module.exports = { entry: groupVendor, output: { path: path.join(__dirname, "public/dll"), filename: "[name].dll.js", library: "[name]_[hash]" // vendor.dll.js中暴露出的全局变量名 }, plugins: [ new CleanWebpackPlugin(), new webpack.DllPlugin({ path: path.join(__dirname, "public/dll", "[name]-manifest.json"), name: "[name]_[hash]", context: process.cwd() }) ] };
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // @ts-nocheck /** * Simulate long task. * @param duration */ function longTask(duration) { const start = new Date().getTime(); // Busy countdown. while (new Date().getTime() - start < duration); } window.addEventListener('load', (e) => { // eslint-disable-line longTask(5000); const gpt = document.createElement('script'); // eslint-disable-line gpt.setAttribute('src', 'http://www.googletagservices.com/tag/js/gpt.js'); document.querySelector('body').appendChild(gpt); // eslint-disable-line });
var express = require('express'); var router = express.Router(); // var connection = require("../../enregistrement/bd/connection") /* GET home page. */ router.get('/', function (req, res, next) { res.render('index', { title: 'Express', host: req.hostname }); }); router.get('/parrainage', function (req, res, next) { res.render('parrainage', { title: 'Express', host: req.hostname }); }); /* router.post('/record', function (req, res, next) { console.log(req.body.nom) connection.query(`INSERT INTO presence_winter_night (nom, prenoms, matricule, telephone, email) VALUES ("${req.body.nom}", "${req.body.prenoms}", "${req.body.matricule}", "${req.body.tel}", "${req.body.email}")`, function (err, result) { if (err) { throw err } else { res.redirect("/") } }) }); */ module.exports = router;
import React, { Component } from 'react'; import { AuthService, GameService } from '../../service'; import Game from './singleGame'; class Games extends Component { constructor(props) { super(props); console.log(this.props.display) if (props.display === 'dev') { this.loadGames = this.loadDevGames; } else if (props.display === 'owned') { this.loadGames = this.loadOwnedGames; } else if (props.display === 'genre') { this.loadGames = this.loadGamesByGenre; } else if (props.display === 'search') { this.loadGames = this.searchGames } else { console.log('hereAll') this.loadGames = this.loadAllGames; } this.state = { games: [], show: 5, }; } render() { return ( <div className={'text-white bg-dark'}> <div className={'container-fluid bg-dark p-3'}>{this.listGames()}</div> <div onClick={() => this.increaseShow()} className={ 'text-center text-white font-weight-bold d-flex align-self-center justify-content-center border-top btn btn-dark' } > More </div> </div> ); } listGames = () => { return this.state.games.length === 0 ? ( <h1 className={'p4'}>No games to display</h1> ) : ( this.state.games .filter((v, i, arr) => i < this.state.show) .map((game) => { return ( <Game handleCartOrWishlistAdd={this.handleCartOrWishlistAdd} handleGameSelect={this.props.handleGameSelect} game={game} /> ); }) ); }; increaseShow = () => { if (this.state.show < this.state.games.length) { this.setState({ show: this.state.show + 5, }); } }; componentDidMount() { this.loadGames(this.props.criteria); } handleCartOrWishlistAdd = () => { this.loadGames(this.props.criteria); }; loadAllGames = () => { GameService.fetchGames().then((response) => { this.setState({ games: response.data, }); }); }; loadOwnedGames = () => { let user = AuthService.getCurrentUser(); if (user) { GameService.fetchOwnedGames(user.username, user.email).then( (response) => { this.setState({ games: response.data, }); } ); } }; searchGames = (search) => { GameService.fetchGamesBySearchTerm(search).then((response) => { this.setState({ games: response.data, }) }) } loadGamesByGenre = (genre) => { GameService.fetchGamesByGenre(genre).then((response) => { this.setState({ games: response.data, }); }); }; loadDevGames = (devId) => { GameService.fetchDevGames(devId).then((response) => { this.setState({ games: response.data, }); }); }; } export default Games;
import Async from 'async' import Info from './info' import Stats from './stats' import Moment from 'moment' import Badges from './badges' import Quests from './quests' import Effects from './effects' import Visits from './roomvisits' import Clothing from './clothing' import Searches from './searches' import Wardrobe from './wardrobe' import Favorites from './favorites' import Group from '../permissions/group' import Database from '../../../server' import Articles from '../../cms/articles' import Achievements from './achievements' import Relationships from './relationships' import Error from '../../../../libraries/error' class Users extends Database.Model { get tableName () { return 'users' } rank () { return this.hasOne(Group, 'id', 'rank') } duplicates () { return this.hasMany(Users, 'ip_last', 'ip_last').query(qb => { qb.where('ip_last', '!=', '127.0.0.1') }) } badges () { return this.hasMany(Badges) } articles () { return this.hasMany(Articles, 'author') } toJSON () { const values = Database.Model.prototype.toJSON.apply(this); values.account_created = Moment.unix(values.account_created).format("MMM D, YYYY"); if (values.last_online == '0') { values.last_online = 'Never'; } else { values.last_online = Moment.unix(values.last_online).format("MMM D, YYYY"); } return values; } static delete (id, username) { Async.parallel([ // Self function (callback) { Users.where('id', id).destroy() .then (s => { callback(null) }) .catch (e => { callback(e) }) }, // Achievements function (callback) { Achievements.where('userid', id).destroy() .then (s => { callback(null) }) .catch (e => { callback(e) }) }, // Badges function (callback) { Badges.where('user_id', id).destroy() .then (s => { callback(null) }) .catch (e => { callback(e) }) }, // Clothing function (callback) { Clothing.where('user_id', id).destroy() .then (s => { callback(null) }) .catch (e => { callback(e) }) }, // Effects function (callback) { Effects.where('user_id', id).destroy() .then (s => { callback(null) }) .catch (e => { callback(e) }) }, // Favorites function (callback) { Favorites.where('user_id', id).destroy() .then (s => { callback(null) }) .catch (e => { callback(e) }) }, // Info function (callback) { Info.where('user_id', id).destroy() .then (s => { callback(null) }) .catch (e => { callback(e) }) }, // Quests function (callback) { Quests.where('user_id', id).destroy() .then (s => { callback(null) }) .catch (e => { callback(e) }) }, // Relationships function (callback) { Relationships.where('user_id', id).destroy() .then (s => { Relationships.where('target', id).destroy() .then (s => { callback(null) }) .catch (e => { callback(e) }) }) .catch (e => { callback(e) }) }, // Room Visits function (callback) { Visits.where('user_id', id).destroy() .then (s => { callback(null) }) .catch (e => { callback(e) }) }, // Stats function (callback) { Stats.where('id', id).destroy() .then (s => { callback(null) }) .catch (e => { callback(e) }) }, // Wardrobe function (callback) { Wardrobe.where('user_id', id).destroy() .then (s => { callback(null) }) .catch (e => { callback(e) }) }, ], ((errors, results) => { if (errors) { new Error('normal', errors) } })) } } export default Users
import React from "react"; import MovieHeader from "../headerMovie"; import Grid from "@material-ui/core/Grid"; import { makeStyles } from "@material-ui/core/styles"; import GridList from "@material-ui/core/GridList"; import GridListTile from "@material-ui/core/GridListTile"; import { getMovieImages } from "../../api/tmdb-api"; import { useQuery } from "react-query"; import Spinner from '../spinner'; const useStyles = makeStyles((theme) => ({ root: { display: "flex", flexWrap: "wrap", justifyContent: "space-around", }, gridList: { width: 450, height: '100vh', }, })); const TemplateMoviePage = ({ movie, children }) => { const classes = useStyles(); const { data , error, isLoading, isError } = useQuery( ["images", { id: movie.id }], getMovieImages, ); if (isLoading) { return <Spinner /> } if(isError) { return <h1>{error.message}</h1> } const images = data.posters; return ( <> <MovieHeader movie={movie} /> <Grid container spacing={5} style={{ padding: "15px" }}> <Grid item xs={3}> <div className={classes.root}> <GridList cellHeight={500} className={classes.gridList} cols={1}> {images.map((image) => ( <GridListTile key={image.file_path} className={classes.gridListTile} cols={1}> <img src={`https://image.tmdb.org/t/p/w500/${image.file_path}`} alt={image.poster_path} /> </GridListTile> ))} </GridList> </div> </Grid> <Grid item xs={9}> {children} </Grid> </Grid> </> ); }; export default TemplateMoviePage;
import React from 'react' class Base extends React.Component { render(){ return <cite>Soy un componente base...</cite> } } export default Base
import React, {useState, useEffect} from 'react'; import ExpandLessIcon from '@material-ui/icons/ExpandLess'; import { useWindowScroll } from 'react-use'; const ScrollToTop = () => { const {y : pageYOffset} = useWindowScroll(); const [visible, setVisible] = useState(false); useEffect(() => { if (pageYOffset >= 600){ setVisible(true); } else{ setVisible(false); } }, [pageYOffset]) if (!visible) { return false; } const ScrollTop = () => { window.scrollTo({top:0, behavior:'smooth'}) } return ( <> <div className="scrollToTop" onClick={ScrollTop}> <div className="scrollIcon"> <ExpandLessIcon /> </div> </div> </> ) } export default ScrollToTop
// Eventクラス // -------------- function EveEve() { this.cbs = []; } _.extend(EveEve.prototype, { on: function(ev, cb) { var self = this; var evs = ev.split(' '); for (var i = 0; i < evs.length; i++) { var name = evs[i]; if (!self.cbs[name]) self.cbs[name] = []; self.cbs[name].push(cb); } return this; }, once: function(ev, cb) { var self = this; self.on(ev, function(){ self.off(ev, arguments.callee); cb.apply(this, arguments); }); return this; }, trigger: function() { var self = this; var args = Array.prototype.slice.call(arguments); var ev = args.shift(); var list = null; if (self.cbs[ev]) { list = self.cbs[ev]; } else { return; } for (var i = 0, len = list.length; i < len; i++) { var cb = list[i]; if (!cb.apply(this, args)) break; } return this; }, off: function(ev, cb) { var self = this; var list = null; if (!ev) { self.cbs = {}; return this; } if (self.cbs[ev]) { list = self.cbs[ev]; } else { return this; } if (!cb) { delete self.cbs[ev]; return this; } for (var i = 0, len = list.length; i < len; i++) { var _cb = list[i]; if (_cb === cb) { list = list.slice(); list.splice(i, 1); self.cbs[ev] = list; break; } } return this; } });
//IN ES6 THERE 2 WAYS TO DECLARE A VARIABLE - let AND const //ES5 var name5 = 'Kunal' name5 = 'hello' //can be changed console.log(name5) //ES6 let name6 = 'Tony' const age = 23 // CAN'T BE CHANGED ,. CAN BE DECLARED ONLY ONCE name6 = 'bye' //IT CAN BE CHANGED ALSO //-----age = 20 // IT **CANNOT** BE CHANGED console.log(name6+age) function anything5(t){ if(t){ var nameAgain = 'Chris' //console.log(nameAgain) } console.log(nameAgain) } function anything6(t){ if(t){ let nameOnceAgain = 'Scarlett' //console.log(nameOnceAgain) } console.log(nameOnceAgain) //LET AND CONST CAN ONLY BE USED IN SCOPE CHAIN -- NOT AFTER OR BEFORE. } anything5(true) anything6(true)
$('input[name=service]').click(function(){ //Get the label element that comes immediately after this radio button var label = $(this).next(); //From the label element extract the inner HTML var service = label.html(); //Place info in the display if (service==morning) { $('#service-selection').html(Morning Prayer is a service of ); } else if (service==evening) { //code } else if (service==compline) { //code } else { //Error message } }); object.onclick=function(){SomeJavaScriptCode};
// soal 1 // const person = { // name: "person A", // age: 100, // favDrinks: [ // "coffee", // "jamu temulawak", // "tea" // ], // greeting: function() { // console.log("hello world") // } // } // /// EDIT HERE // function // /// STOP // console.log(person.name); // console.log(person.age); // console.log(person.favDrinks); // console.log(person.greeting("John Watson")); // soal 2 function getObjectValue(obj, path) { let source = path.split ('.') cosole.log(source , '----- source split'); let result = obj console.log(result , '-----result dari obj'); for (let a = 0; a < source.lenght; a++){ if result === null){ break } let value = source[a] console.log(value, '======= value source[a]'); let object = result [value] consle.log(object, '<<, object result[value]'); if (object !== undefined) { result = object } else { return null } } return null } const milkBasedCoffee = { name: "latte", ingredients: { espresso: { origin: "lampung", roastProfile: "medium to dark" ratio: 1 }, milk: { brand: "susu murni", isVegan: false, ratio: 5 } }, } const espresso = getObjectValue(milkBasedCoffee, "ingredients.espresso.origin"); const coffeeBrand = getObjectValue(milkBasedCoffee, "ingredients.espresso.brand"); const isMilkVegan = getObjectValue(milkBasedCoffee, "ingredients.milk.isVegan"); console.log(espresso); console.log(coffeeBrand); console.log(isMilkVegan) // soal 3
import conButton from './src/conButton'; conButton.install = function(Vue) { Vue.component(conButton.name, conButton); }; export default conButton;
class State { constructor() { if (this.constructor === State) { throw new TypeError('Abstract class cannot be instantiated directly.'); } } on_enter() { throw new TypeError('Class missing method from extended abstract class.'); } on_exit() { throw new TypeError('Class missing method from extended abstract class.'); } update() { throw new TypeError('Class missing method from extended abstract class.'); } }
export default { namespaced: true, state: { userId: null, name: '', orgId:'', headImage:'', titles:'', }, mutations: { updateId (state, id) { state.userId = id }, updateName (state, name) { state.name = name }, updateOrgId(state,orgId){ state.orgId = orgId }, updateHeadImage(state,headImage){ state.headImage = headImage }, updateTitles(state,titles){ state.titles = titles } } }
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import './index.css'; import App from './components/App'; import registerServiceWorker from './registerServiceWorker'; import setUpStore from './set-up-store'; import { load_contacts } from './actions/contact-actions'; let store = setUpStore(); store.dispatch(load_contacts()); ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.getElementById('root')); registerServiceWorker();
"use strict"; // // back.js // // Created by Alezia Kurdis, May 2nd, 2021. // Copyright 2021 Vircadia and contributors. // // 3d portals to go back. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // (function(){ var ROOT = Script.resolvePath('').split("back.js")[0]; var teleporterSoundFileUrl = ROOT + "tpsound.mp3"; var teleportSound; function playSound() { Audio.playSound(teleportSound, { volume: 0.3, localOnly: true }); }; this.preload = function(entityID) { teleportSound = SoundCache.getSound(teleporterSoundFileUrl); } this.enterEntity = function(entityID) { playSound(); var timer = Script.setTimeout(function () { location.goBack(); }, 3000); }; this.leaveEntity = function(entityID) { //do nothing. }; })
app.controller('aregister',['$scope','$localStorage','$http',function($scope,$localStorage,$http){ $scope.names=[{value:"admin"}]; //$scope.position=[{value:"Teaching"},{value:"Non-teaching"}]; $scope.college=[{value:"K.S.Rangasamy College of Technology"}]; $scope.status=[{value:"active"},{value:"inactive"}]; $scope.adminInfo={ adminId:$localStorage.data_value, firstname:undefined, lastname:undefined, email:undefined, department:undefined, mobile:undefined } $scope.adminRegister=function(){ var data={ aadminId:$scope.adminInfo.adminId, afirstname:$scope.adminInfo.firstname, alastname:$scope.adminInfo.lastname, aemail:$scope.adminInfo.email, amobile:$scope.adminInfo.mobile, acollege:$scope.selectedcollegeValue, astatus:$scope.selectedstatusValue, adesignation:$scope.selecteddesignationValue } console.log(data); if(data.aadminId==undefined || data.afirstname==undefined || data.alastname==undefined || data.aemail==undefined || data.amobile==undefined || data.acollege==undefined || data.astatus==undefined || data.adesignation==undefined){ alert("please fill all input field...") } else{ $http({ method:'POST', url:'php/aregister.php', data:data }).then(function (response){ $scope.demo=JSON.stringify(response); console.log($scope.demo); alert("updated Successfully"); }),function (error){ console.log(error); } } } $scope.adminClear=function(){ $scope.adminInfo={ firstname:undefined, lastname:undefined, email:undefined, department:undefined, mobile:undefined } } }]);
/** * Created by MACHENIKE on 2017/2/19. */ import * as types from '../actionTypes.js' import api from '../../api/api' const allActions = { getProduct(){ return dispatch =>{ api.getProducts().then(function(res){ console.log(res) dispatch({ type:types.GET_PRODUCTS, products:res }) }); } }, addProduct(id){ return { type:types.ADD_PRODUCTS, id:id } } } export default allActions
import { setTimeout } from "node:timers/promises"; import got from "got"; export const SOURCE = { RUCAPTCHA: "RUCAPTCHA", ANTIGATE: "ANTIGATE", CAPTCHA24: "CAPTCHA24", }; const _SOURCE = { [SOURCE.RUCAPTCHA]: { baseUrl: "http://rucaptcha.com", soft_id: 768, }, [SOURCE.ANTIGATE]: { baseUrl: "http://anti-captcha.com", soft_id: 720, }, [SOURCE.CAPTCHA24]: { baseUrl: "http://captcha24.com", soft_id: 921, }, }; export default class Recognize { constructor(sourceCode, options) { if (!options || !options.key) throw new Error("not key"); const source = _SOURCE[sourceCode]; if (!source) throw new Error("invalid type"); this.rp = got.extend({ prefixUrl: source.baseUrl, resolveBodyOnly: true, responseType: "json", }); this._options = { ...options, soft_id: source.soft_id, }; } async _waitResult(id) { await setTimeout(1000); const { status, request } = await this.rp.get("res.php", { searchParams: { key: this._options.key, action: "get", id, json: 1 }, }); if (request === "CAPCHA_NOT_READY") return this._waitResult(id); else if (status === 0) return Promise.reject(request); return request; } async balanse() { const { request } = await this.rp.get("res.php", { searchParams: { key: this._options.key, action: "getbalance", json: 1 }, }); return request; } async solvingImage(buff, options = {}) { const { status, request } = await this.rp.post("in.php", { json: { ...options, soft_id: this._options.soft_id, method: "base64", key: this._options.key, body: buff.toString("base64"), json: 1, }, }); if (status === 1) { return { result: await this._waitResult(request), id: request }; } return Promise.reject(request); } async solvingRecaptcha2(url, googleKey, options = {}) { const { status, request } = await this.rp.post("in.php", { json: { ...options, soft_id: this._options.soft_id, method: "userrecaptcha", key: this._options.key, pageurl: url, googlekey: googleKey, json: 1, }, }); if (status === 1) { return { result: await this._waitResult(request), id: request }; } return Promise.reject(request); } async solvingRecaptcha3(url, googleKey, action, score = "0.3", options = {}) { const { status, request } = await this.rp.post("in.php", { json: { ...options, soft_id: this._options.soft_id, method: "userrecaptcha", version: "v3", action, min_score: score, key: this._options.key, pageurl: url, googlekey: googleKey, json: 1, }, }); if (status === 1) { return { result: await this._waitResult(request), id: request }; } return Promise.reject(request); } async reportBad(id) { const { status, request } = await this.rp.get("res.php", { searchParams: { key: this._options.key, action: "reportbad", id, json: 1, }, }); if (status === 0) return false; return true; } async reportGood(id) { const { status, request } = await this.rp.get("res.php", { searchParams: { key: this._options.key, action: "reportgood", id, json: 1, }, }); if (status === 0) return false; return true; } }
import wx from 'weixin-js-sdk'; export function setWechatConfig(options) { wx.config({ debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。 appId: options.appId, // 必填,公众号的唯一标识 timestamp: options.timestamp, // 必填,生成签名的时间戳 nonceStr: options.nonceStr, // 必填,生成签名的随机串 signature: options.signature,// 必填,签名 jsApiList: [ 'updateAppMessageShareData', 'updateAppMessageShareData', 'onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareWeibo', 'onMenuShareQZone', 'checkJsApi' ] // 必填,需要使用的JS接口列表 }); return new Promise((resolve, reject) => { wx.ready(function () { //需在用户可能点击分享按钮前就先调用 resolve(true); wx.error(function(res){ // config信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,对于SPA可以在这里更新签名。 console.error("errorMSG:"+JSON.stringify(res)); reject(res); }); }); }); } export function updateTimelineShareData(title = '', desc = '', link = '', imgUrl = '') { // console.log('updateTimelineShareData():', title, desc, link, imgUrl); return new Promise((resolve, reject) => { wx.updateTimelineShareData({ title: title, // 分享标题 desc: desc, // 分享描述 link: link, // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致 imgUrl: imgUrl, // 分享图标 success: function () { resolve(true)// 设置成功 console.log('设置updateTimelineShareData()成功!'); }, fail: function(err) { reject(err); console.error(err); console.log('设置updateTimelineShareData()失败!'); } }); }) } export function updateAppMessageShareData(title = '', desc = '', link = '', imgUrl = '') { // console.log('updateAppMessageShareData():', title, desc, link, imgUrl); return new Promise((resolve, reject) => { wx.updateAppMessageShareData({ title: title, // 分享标题 desc: desc, // 分享描述 link: link, // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致 imgUrl: imgUrl, // 分享图标 success: function () { resolve(true)// 设置成功 console.log('设置updateAppMessageShareData()成功!'); }, fail: function(err) { reject(err); console.error(err); console.log('设置updateAppMessageShareData()失败!'); } }); }) } export function onMenuShareTimeline(title = '', desc = '', link = '', imgUrl = '') { // console.log('onMenuShareTimeline():', title, desc, link, imgUrl); return new Promise((resolve, reject) => { wx.onMenuShareTimeline({ title: title, // 分享标题 // desc: desc, // 分享描述 link: link, // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致 imgUrl: imgUrl, // 分享图标 success: function () { resolve(true)// 设置成功 console.log('设置onMenuShareTimeline()成功!'); }, fail: function(err) { reject(err); console.error(err); console.log('设置onMenuShareTimeline()失败!'); } }); }) } export function onMenuShareAppMessage(title = '', desc = '', link = '', imgUrl = '') { // console.log('onMenuShareAppMessage():', title, desc, link, imgUrl); return new Promise((resolve, reject) => { wx.onMenuShareAppMessage({ title: title, // 分享标题 desc: desc, // 分享描述 link: link, // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致 imgUrl: imgUrl, // 分享图标 success: function () { resolve(true)// 设置成功 console.log('设置onMenuShareAppMessage()成功!'); }, fail: function(err) { reject(err); console.error(err); console.log('设置onMenuShareAppMessage()失败!'); } }); }) } export function onMenuShareQQ(title = '', desc = '', link = '', imgUrl = '') { // console.log('onMenuShareQQ():', title, desc, link, imgUrl); return new Promise((resolve, reject) => { wx.onMenuShareQQ({ title: title, // 分享标题 desc: desc, // 分享描述 link: link, // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致 imgUrl: imgUrl, // 分享图标 success: function () { resolve(true)// 设置成功 console.log('设置onMenuShareQQ()成功!'); }, fail: function(err) { reject(err); console.error(err); console.log('设置onMenuShareQQ()失败!'); } }); }) } export function onMenuShareWeibo(title = '', desc = '', link = '', imgUrl = '') { // console.log('onMenuShareWeibo():', title, desc, link, imgUrl); return new Promise((resolve, reject) => { wx.onMenuShareWeibo({ title: title, // 分享标题 desc: desc, // 分享描述 link: link, // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致 imgUrl: imgUrl, // 分享图标 success: function () { resolve(true)// 设置成功 console.log('设置onMenuShareWeibo()成功!'); }, fail: function(err) { reject(err); console.error(err); console.log('设置onMenuShareWeibo()失败!'); } }); }) } export function onMenuShareQZone(title = '', desc = '', link = '', imgUrl = '') { // console.log('onMenuShareQZone():', title, desc, link, imgUrl); return new Promise((resolve, reject) => { wx.onMenuShareQZone({ title: title, // 分享标题 desc: desc, // 分享描述 link: link, // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致 imgUrl: imgUrl, // 分享图标 success: function () { resolve(true)// 设置成功 console.log('设置onMenuShareQZone()成功!'); }, fail: function(err) { reject(err); console.error(err); console.log('设置onMenuShareQZone()失败!'); } }); }) }
'use strict'; const fs = require('fs'); const path = require('path') const webpack = require('webpack') const CopyWebpackPlugin = require('copy-webpack-plugin') const HtmlWebpackPlugin = require('html-webpack-plugin') const ExtractTextPlugin = require('extract-text-webpack-plugin') const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin') const HtmlWebpackPugPlugin = require('html-webpack-pug-plugin'); //const OfflinePlugin = require('offline-plugin'); const wpMerge = require('webpack-merge') const webpackBaseConfig = require('./webpack.base.conf'); module.exports = function webpackProdConfig(config) { const isProd = config.env === 'production'; let staticCopyPluginConfig = config.clientConfig._entries .map(entry => Object.assign({ staticPath: path.join(entry.path, 'static') }, entry)) .filter(entry => fs.existsSync(entry.staticPath)) .map(entry => { return { from: entry.staticPath, to: 'assets', ignore: ['.*'] } }); let pugViewPlugins = config.clientConfig._entries .filter(entry => entry.indexView) .map(entry => { return new HtmlWebpackPlugin({ filename: path.relative(config.publicDistPath, entry.indexView.viewPath), template: entry.indexView.templatePath, inject: true, filetype: 'pug', chunksSortMode: 'dependency', chunks: ['manifest', 'vendor', entry.name], cache: false }); }); return wpMerge(webpackBaseConfig(config), { output: { filename: 'assets/js/[name].[hash].js', }, devtool: isProd ? false : '#source-map', plugins: [ // Uglify new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false }, sourceMap: true }), // extract css into its own file new ExtractTextPlugin({ filename: 'assets/css/[name].[contenthash].css' }), // Compress extracted CSS. We are using this plugin so that possible // duplicated CSS from different components can be deduped. new OptimizeCSSPlugin({ cssProcessorOptions: { safe: true } }), // generate dist index.html with correct asset hash for caching. // you can customize output by editing /index.html // see https://github.com/ampedandwired/html-webpack-plugin ...pugViewPlugins, new HtmlWebpackPugPlugin(), // split vendor js into its own file new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', minChunks: function (module, count) { // any required modules inside node_modules are extracted to vendor return ( module.resource && /\.js$/.test(module.resource) && module.resource.indexOf( path.join(__dirname, '../node_modules') ) === 0 ) } }), // extract webpack runtime and module manifest to its own file in order to // prevent vendor hash from being updated whenever app bundle is updated new webpack.optimize.CommonsChunkPlugin({ name: 'manifest', chunks: ['vendor'] }), // copy custom static assets new CopyWebpackPlugin(staticCopyPluginConfig), // new OfflinePlugin({ // caches: { // main: [ // '**/*.css', // '**/*.js', // '**/*.png', // '**/*.jpg' // ], // additional: [ // ':externals:' // ], // optional: [ // ':rest:' // ] // }, // externals: [ // '/', // '/manifest.json' // ], // ServiceWorker: { // events: true, // output: './sw.js', // navigateFallbackURL: '/' // }, // AppCache: { // directory: './', // disableInstall: false // } // }) ] }); }
const int = require('./int'); module.exports = input => { let instructions = input.split(',').map(Number); for (let noun = 0; noun <= 99; noun++) { for (let verb = 0; verb <= 99; verb++) { instructions[1] = noun; instructions[2] = verb; if (int(instructions)[0] == 19690720) { return 100 * noun + verb; } } } }
// Code Goes Here import React from "react"; import Order from "./components/order";
import Map from './Map' import React, { Component } from 'react'; import { bindActionCreators } from 'redux'; import { getEvents } from '../actions/events' import { connect } from 'react-redux'; class MapWrapper extends Component { state = { isMarkerShown: false, } componentDidMount() { this.delayedShowMarker() this.props.getEvents() } delayedShowMarker = () => { setTimeout(() => { this.setState({ isMarkerShown: true }) }, 1000) } render() { return ( <Map isMarkerShown={this.state.isMarkerShown} formValues={this.props.formValues} events={this.props.events} /> ) } } const mapStateToProps = ({ events, formValues }) => ({ events: events.all, formValues }) const mapDispatchToProps = (dispatch) => { return bindActionCreators({ getEvents }, dispatch) } export default connect(mapStateToProps, mapDispatchToProps)(MapWrapper)
import React, { Component } from 'react'; import { createStore, applyMiddleware, combineReducers } from 'redux'; import { Provider, connect } from 'react-redux'; import thunk from 'redux-thunk'; import { Scene, Router } from 'react-native-router-flux'; import * as reducers from '../reducers'; import Main from './main'; import About from './about'; const createStoreWithMiddleware = applyMiddleware(thunk)(createStore); const reducer = combineReducers(reducers); const store = createStoreWithMiddleware(reducer); const RouterRedux = connect()(Router) export default class App extends Component { render() { return ( <Provider store={store}> <RouterRedux hideNavBar={true}> <Scene key="main" component={Main} title="Main"/> <Scene key="about" component={About} title="About"/> </RouterRedux> </Provider> ); } }
const peterEmails = "benjamin@gmail.com|peter@gmail.com|hans@gmail.com|ahmad@gmail.com|sana@gmail.com|virgeen@gmail.com|mohammed@gmail.com"; function sendEmailTo(recepient) { console.log('email sent to ' + recepient); } let emailArray = peterEmails.split("|"); for (i=0; i<emailArray.length; i++) { sendEmailTo(emailArray[i]); }
$('.m-chat__main .edit-msg').on('click', function(e) { e.preventDefault(); $(this).parent().children('.edit-wrapper').toggleClass('closed'); }); $('.m-chat__current').hide(); $('.edit-wrapper .delete').on('click', function() { $(this).parent().parent().toggleClass('closed'); $(this).parent().parent().parent().children('.delete-msg').removeClass('closed'); }); $('.m-chat__main-item .img').on('click', function() { $('.m-chat__current').show(); }); $('.m-chat__main-item .info').on('click', function() { $('.m-chat__current').show(); }); $('.message__header .back').on('click', function() { $('.m-chat__current').hide(); }); $('.edit-wrapper .full').on('click', function() { $(this).parent().parent().toggleClass('closed'); }); $('.edit-current .delete').on('click', function() { $('.delete-msg-cerrnt-all').removeClass('closed'); }); $('.delete-msg-cerrnt-all .delete-btn').on('click', function() { $('.delete-msg-cerrnt-all').addClass('closed'); }); $('.delete-msg .delete-btn.yes').on('click', function() { $(this).parent().parent().toggleClass('closed'); let itemId = $(this).parent().parent().parent().attr('data-chatId'); alert(itemId); $(this).parent().parent().parent().hide(); }); $('.delete-msg .delete-btn.no').on('click', function() { $(this).parent().parent().toggleClass('closed'); }); $('.m-chat__header-clrd .clear').on('click', function() { $('.delete-msg-all').removeClass('closed'); }); $('.delete-msg-all .delete-btn.yes').on('click', function() { $(this).parent().parent().toggleClass('closed'); $('.m-chat__main-item').hide(); }); $('.delete-msg-all .delete-btn.no').on('click', function() { $(this).parent().parent().toggleClass('closed'); }); $('.m-chat__header-btns .notice').on('click', function() { $(this).toggleClass('notice-off'); }); $('.m-chat__header-btns .close').on('click', function() { $('.m-chat').addClass('closed'); $('.m-chat-btn').show(); }); $('.m-chat-btn').on('click', function() { $(this).hide(); $('.m-chat').removeClass('closed'); }); $('.message__header .edit-current').on('click', function() { $('.edit-list').removeClass('closed'); $('.edit-item').on('click', function() { setTimeout(function (){ $('.edit-list').addClass('closed'); }, 10); }); }); $(document).mouseup(function (e) { var container = $('.edit-list'); if (container.has(e.target).length === 0){ container.addClass('closed'); } }); $(document).mouseup(function (e) { var container = $('.message-list'); if (container.has(e.target).length === 0){ container.addClass('closed'); } }); $('.message-in .add').on('click', function() { $('.message-list').addClass('closed'); $(this).children('.message-list').removeClass('closed'); }); if ($(window).width() > 766) { $('textarea').each(function () { this.setAttribute('style', 'height:' + (this.scrollHeight) + 'px;overflow-y:hidden;'); }).on('input', function () { this.style.height = 'auto'; this.style.height = (this.scrollHeight) + 'px'; }); } $('.toBottom').on('click', function() { window.hashName = window.location.hash; window.location.hash = '#lastMessage'; $('.message__main').animate({scrollTop: $('#lastMessage').offset().top}, 10, function() { window.location.hash = window.hashName; }); }); var countOfMessages = document.querySelectorAll('.message-in').length; $('.message-send-btn').on('click', function() { var messageText = $('#message').val(); var fullDate = new Date(); var twoDigitMonth = ((fullDate.getMonth().length+1) === 1)? (fullDate.getMonth()+1) : '0' + (fullDate.getMonth()+1); var currentDate = fullDate.getDate() + "." + twoDigitMonth + '.' + fullDate.getFullYear(); currentDate = currentDate + ', ' + fullDate.getHours() + '.' + fullDate.getMinutes() + '.' + fullDate.getSeconds(); if (messageText) { $('#lastMessage').removeAttr("id"); $('.message-in.out').removeAttr("id"); var newMessageBlock = $('<div class="message-in out" id="#lastMessage"> ' + '<div class="message-info">' + '<div class="date">' + currentDate + '</div> '+ '<div class="add">'+ '<ul class="message-list closed"><li class="message-item">Пункт меню</li><li class="message-item">Удалить сообщение</li><li class="message-item">Пункт меню</li></ul>' + '</div> '+ '</div> '+ '<div class="message-text">' + messageText + '</div>' + '<div class="status send">' + '</div>' + ' </div>'); $('.message__main-date.last').append(newMessageBlock); $('#message').val(""); $('#message').height('46'); var scroll = $('.message__main').height(); $('.message__main').animate({ scrollTop: scroll }, 1000); $('html,body').stop().animate({ scrollDown: scroll }, 1000); } }); $('.m-chat__find-allbase').hide(); $('.m-chat__find').hide(); $('#findChat').on('input', function() { var value = $('#findChat').val().length; if (value) { $('.m-chat__find-main .letter').hide(); $('.m-chat__find-allbase').show(); } else { $('.m-chat__find-main .letter').show(); $('.m-chat__find-allbase').hide(); } }); $('.m-chat__find-header .back').on('click', function() { $('.m-chat__find').hide(); }); $('.m-chat__header-find .new-message').on('click', function() { $('.m-chat__find').show(); });
require('dotenv').config(); const express = require('express'); const cors = require('cors'); const { dbConnection } = require('../database/config'); const fileUpload = require('express-fileupload'); class Server{ constructor(){ this.app = express(); this.port = process.env.PORT; this.paths = { authPath : '/api/auth', categoryPath: '/api/category', commentPath: '/api/comment', marketplacePath:'/api/marketplace', productPath: '/api/product', publicationPath: '/api/publication', searchPath: '/api/search', userPath : '/api/user', uploadPath : '/api/upload', } //connect database this.dbConnect(); //middlewars this.middlewars(); //routes my app this.routes(); } async dbConnect(){ await dbConnection(); } middlewars(){ // CORS this.app.use(cors()); //Lectura y parseo del json this.app.use(express.json()); // Directorio publico this.app.use(express.static('public')); // upload files this.app.use(fileUpload({ useTempFiles : true, tempFileDir : '/tmp/', createParentPath: true, })); } routes(){ this.app.use(this.paths.authPath,require('../routes/auth')); this.app.use(this.paths.categoryPath,require('../routes/category')); this.app.use(this.paths.commentPath,require('../routes/comment')); this.app.use(this.paths.marketplacePath,require('../routes/marketplace')); this.app.use(this.paths.productPath,require('../routes/product')); this.app.use(this.paths.publicationPath,require('../routes/publication')); this.app.use(this.paths.searchPath,require('../routes/search')); this.app.use(this.paths.uploadPath,require('../routes/upload')); this.app.use(this.paths.userPath,require('../routes/user')); } listen(){ this.app.listen(this.port,()=>{ console.log('Deploying in the port ',this.port); }) } } module.exports = Server;
const level = require('level'); class LevelProvider { constructor({ path }) { this.client = level(path, { valueEncoding: 'json' }); } store(key, value) { return this.client.put(key, value); } get(key) { return this.client.get(key); } delete(key) { return this.client.del(key); } } module.exports = LevelProvider;
const mongoose = require('mongoose'); const connectionString = process.env.MONGODB_URI || "mongodb://localhost:27017/task-bite" const configOptions = { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true, useFindAndModify: false, }; mongoose.connect(connectionString, configOptions) .then(() => console.log('MongoDB successfully connected...')) .catch(err => console.log(`MongoDB connection: ${err}`)); module.exports = { Project: require('./project'), Task: require('./task'), User: require('./user') };
const express = require('express') const app = express() const port = 3000 const mongoose = require('mongoose') const path = require('path') const UserSchema = new mongoose.Schema({ nameCard: {type:String, required:true}, breedCard: {type:String, required:true}, levelCard: {type:Number, required:true}, EffectOrDescription: {type:String, required:true}, attackpower: {type:Number, required:true}, DefensePower: {type:Number, required:true} }) const AnunnakiModel = mongoose.model('Anunnaki', UserSchema) mongoose.connect('mongodb://localhost/CardsAnunnaki',{ useUnifiedTopology: true, useNewUrlParser: true }) let db = mongoose.connection db.on('error', ()=>{ console.log(error)}) db.once('open', ()=>{ console.log('banco carregado')}) app.use('/', express.static(path.join(__dirname, 'public'))) app.post('/',express.urlencoded({extended:true}), async(req,res)=>{ let OtherCard = new AnunnakiModel(req.body) try{ doc = await OtherCard.save() res.redirect('/') console.log('carta adicionada') }catch{ res.redirect("/error.html") } }) app.listen(port, async()=>{ try{ await console.log(`Server running in port ${port}`) }catch{ console.log('Erro 500, Server Off') } })
import OtpInputs from './OtpInputs'; export { OtpInputs };
$(document).ready(function () { $(document).on('click', 'a[href^="#"]', function(e) { e.preventDefault(); $('html, body').animate({ scrollTop: $($.attr(this, 'href')).offset().top - 100 }, 500); }); $('h2.-with-toggle').click(function () { $(this).toggleClass('-collapsed'); $(this).next().slideToggle(); $(this).parent().next('.expandable-block').slideToggle(); }); $('.day-evening-switcher img').click(function () { $('.day-evening-switcher img').removeClass('-active'); $(this).addClass('-active'); $('.schema-tab-day, .schema-tab-evening').hide().filter('.' + $(this).data('tab')).fadeIn(); }); $('.timing_nav a').click(function (e) { $('.timing_nav a').removeClass('-active'); $(this).addClass('-active'); if ($(this).data('scheme') === 'timing_diagnostic') { $('.timing_diagnostic_only').show(); $('.timing_surgery_only').hide(); } else { $('.timing_diagnostic_only').hide(); $('.timing_surgery_only').show(); } $('.mv-section-samples .tab_elem').hide().filter('.' + $(this).data('scheme')).fadeIn(); e.preventDefault(); return false; }); $('.faq-list').on('click', '.list-question a', function (e) { $(this).parent().toggleClass('-collapsed').next().slideToggle(); e.preventDefault(); return false; }); var videoSlider = new Swiper ('.mv-video-slider .swiper-container', { slidesPerView: 2, spaceBetween : 25, navigation: { nextEl: '.mv-video-slider .swiper-button-next', prevEl: '.mv-video-slider .swiper-button-prev', }, }); var newsSlider = new Swiper ('.mv-news-slider .swiper-container', { slidesPerView: 3, spaceBetween : 30, navigation: { nextEl: '.mv-news-slider .swiper-button-next', prevEl: '.mv-news-slider .swiper-button-prev', }, }); setTimeout(function() { $("#map").length ? DG.then(function() { return DG.plugin("https://2gis.github.io/mapsapi/vendors/Leaflet.markerCluster/leaflet.markercluster-src.js") }).then(function() { e = DG.map("map", { center: [55.76, 37.64], zoom: 9, fullscreenControl: !1, zoomControl: !1 }), myIcon = DG.icon({ iconUrl: "/local/assets/img_moviprep/map_icon.png", iconSize: [32, 35] }); var t = DG.markerClusterGroup({ showCoverageOnHover: !1 }); $.ajax({ url: "/local/assets/json/moviprep_map.json", success: function(n) { //array = JSON.parse(n); array = n; for (var r = 0; r < array.features.length; r++) { var i = DG.marker([array.features[r].geometry.coordinates[0], array.features[r].geometry.coordinates[1]], { icon: myIcon }).bindPopup(array.features[r].properties.balloonContent); t.addLayer(i) } e.addLayer(t) } }), e.locate({ setView: !0, watch: !0 }).on("locationfound", function(t) { DG.marker([t.latitude, t.longitude]).addTo(e).bindPopup("Ваше местоположение!") }) }) : DG.then(function() { return DG.plugin("https://2gis.github.io/mapsapi/vendors/Leaflet.markerCluster/leaflet.markercluster-src.js") }).then(function() { e = DG.map("map2gis", { center: [65.76, 95.64], zoom: 3, fullscreenControl: !1, zoomControl: !1 }), myIcon = DG.icon({ iconUrl: "/local/assets/img_moviprep/clinic_map_icon.png", iconSize: [34, 41] }); var t = DG.markerClusterGroup({ showCoverageOnHover: !1 }); $.ajax({ url: "/excel-pharm", success: function(n) { array = JSON.parse(n); for (var r = 0; r < array.features.length; r++) { var i = DG.marker([array.features[r].geometry.coordinates[0], array.features[r].geometry.coordinates[1]], { icon: myIcon }).bindPopup(array.features[r].properties.balloonContent); t.addLayer(i) } e.addLayer(t) } }), e.locate({ setView: !0, watch: !0 }).on("locationfound", function(t) { DG.marker([t.latitude, t.longitude]).addTo(e).bindPopup("Ваше местоположение!") }) }) }, 1000); });
import React from 'react' import styled from 'styled-components' const TitleContainer = styled.div` height: 100vh; width: 100vw; display: flex; flex-direction: column; align-items: center; justify-content: center; background-color: ${({ theme }) => theme.colors.dark}; ` const Title = styled.h1` font-size: 6rem; margin: 0; padding: 0; color: ${({ theme }) => theme.colors.light}; ` const Symbol = styled.span` font-size: 9rem; line-height: 1em; color: ${({ theme }) => theme.colors.green}; text-shadow: 0px 0px transparent; transition: all 250ms; &:hover { text-shadow: 0px 0px 1px ${({ theme }) => theme.colors.light}; } ` export default () => ( <TitleContainer> <Symbol>⬢</Symbol> <Title>.CL</Title> <Title>2020</Title> </TitleContainer> )
const test = require('tape'); const isNull = require('./isNull.js'); test('Testing isNull', (t) => { //For more information on all the methods supported by tape //Please go to https://github.com/substack/tape t.true(typeof isNull === 'function', 'isNull is a Function'); t.equal(isNull(null), true, "passed argument is a null"); t.equal(isNull(NaN), false, "passed argument is a null"); //t.deepEqual(isNull(args..), 'Expected'); //t.equal(isNull(args..), 'Expected'); //t.false(isNull(args..), 'Expected'); //t.throws(isNull(args..), 'Expected'); t.end(); });
var Geometry = require("../geometry"); var Vector = Geometry.Vector; var Attributes = require("../attribute"); var Component = require("../component"); var General = require("../general"); var EventHandler = require("../handlers/eventhandler"); var init = function(life) { life.attribute_table.set_base_value(Attributes.HEALTH_MAX, 100); life.attribute_table.set_base_value(Attributes.HEALTH, 80); life.attribute_table.set_base_value(Attributes.HEALTH_REG, 10); life.attribute_table.set_base_value(Attributes.MANA_MAX, 100); life.attribute_table.set_base_value(Attributes.MANA, 20); life.attribute_table.set_base_value(Attributes.MANA_REG, 10); life.attribute_table.set_base_value(Attributes.SHIELD, 0); life.attribute_table.set_base_value(Attributes.SHIELD_MAGICAL, 0); life.attribute_table.set_base_value(Attributes.SHIELD_PHYSICAL, 10); life.attribute_table.set_base_value(Attributes.ARMOR, 10); life.attribute_table.set_base_value(Attributes.MAGIC_RESIST, 10); life.on_update = function(delta_time) { var health = life.attribute_table.get_value(Attributes.HEALTH); var health_max = life.attribute_table.get_value(Attributes.HEALTH_MAX); var health_reg = life.attribute_table.get_value(Attributes.HEALTH_REG); health = health + (health_reg * delta_time); if (health > health_max) { health = health_max; } life.attribute_table.set_base_value(Attributes.HEALTH, health); }; life.apply_damage = function(damage_event) { if (health <= 0) { return false; } var health = life.attribute_table.get_value(Attributes.HEALTH); health = health - damage_event.amount.total(); if (health <= 0) { var f = life.system.eventhandler.new_event_functions[EventHandler.KILL]; var event = new f(life.system, damage_event.killer, damage_event.victim, damage_event.reason); life.system.eventhandler.add_event(event); } else { life.attribute_table.set_base_value(Attributes.HEALTH, health); } return true; }; life.pack = function() { var dict = {}; dict["val"] = life.attribute_table.pack(); return dict; } }; module.exports = { init: init };
/** * Created by Waruwu on 04/04/2017. */ $(function() { $('.form-addproduct form').form({ name : { identifier : 'name', rules: [ { type: 'empty', prompt: 'Nama tidak boleh kosong' } ] }, price: { identifier: 'price', rules: [ { type: 'empty', prompt: 'Price tidak boleh kosong' }, { type: 'number', prompt: 'Price tidak boleh angka bulat' } ] }, stock: { identifier: 'stock', rules: [ { type: 'empty', prompt: 'Price tidak boleh kosong' }, { type: 'integer', prompt: 'Price harus bilangan bulat' } ] } }); });
//正文第一部分图片滑动特效 $(function(){ var zong1= $('#bao1 .pic').size(); var dx1=0; var dy1=zong1-4; $("#lhua1").click(function(){ if (dx1 < 1) { alert("已经是左边最后一页"); return; } dx1--; dy1++; $("#bao1").animate({left:'+=300px'}, 1000); }); $("#rhua1").click(function(){ if (dy1< 1){ alert("已经是右边最后一页"); return; } dx1++; dy1--; $("#bao1").animate({left:'-=300px'}, 1000); }); }); //正文第二部分图片滑动特效 $(function(){ var zong2=$('#bao2 .pic').size(); var dx2=0; var dy2=zong2-4; $("#lhua2").click(function(){ if (dx2 < 1) { alert("已经是左边最后一页"); return; } dx2--; dy2++; $("#bao2").animate({left:'+=300px'}, 1000); }); $("#rhua2").click(function(){ if (dy2< 1){ alert("已经是右边最后一页"); return; } dx2++; dy2--; $("#bao2").animate({left:'-=300px'}, 1000); }); }); //正文第三部分图片滑动特效 $(function(){ var zong3=$('#bao3 .pic').size(); var dx3=0; var dy3=zong3-4; $("#lhua3").click(function(){ if (dx3 < 1) { alert("已经是左边最后一页"); return; } dx3--; dy3++; $("#bao3").animate({left:'+=300px'}, 1000); }); $("#rhua3").click(function(){ if (dy3< 1) { alert("已经是右边最后一页"); return; } dx3++; dy3--; $("#bao3").animate({left:'-=300px'}, 1000); }); }); //正文第四部分图片滑动特效 $(function(){ var zong4=$('#bao4 .pic').size(); var dx4=0; var dy4=zong4-4; $("#lhua4").click(function(){ if (dx4 < 1) { alert("已经是左边最后一页"); return; } dx4--; dy4++; $("#bao4").animate({left:'+=300px'}, 1000); }); $("#rhua4").click(function(){ if (dy4< 1) { alert("已经是右边最后一页"); return; } dx4++; dy4--; $("#bao4").animate({left:'-=300px'}, 1000); }); });
var firebase = require('firebase'); require('firebase/auth'); require('firebase/firestore'); var db = require('../routes/firebase'); //get reference to firebase config file var database = firebase.firestore(db.app); //declare database using app initialization in firebase.js const stripe = require('stripe')('sk_test_lS2QxRwja9PCY1KlEDOOOUXU002RHOQJpJ'); exports.createPayment = async function(req, res, next) { var amount = req.body.amount; var guest_num = req.body.guest_num; var cost = req.body.cost; try { if ((guest_num * cost) == amount) { const paymentIntent = await stripe.paymentIntents.create({ amount: amount * 100, currency: 'usd', // Verify your integration in this guide by including this parameter metadata: {integration_check: 'accept_a_payment'}, }); var res_object = {client_secret: paymentIntent.client_secret, intent_id: paymentIntent.id}; res.send(res_object); } else { console.log('failure'); } } catch { console.log('failure'); } }