text
stringlengths
7
3.69M
import { showHideQuests, showQuests } from '../showHideQuests.js'; import KillQuest from './quests/KillQuest.js'; import { newImage } from '../nonMathHelpers.js'; import { ctxSpriteMap } from '../maps.js'; // import { backgroundMap } from '../maps.js'; //spider creature, jumps up to 3 spaces, slowly and randomly //worth 1 point || strength 0.5 || max life 1 //level 1+ const stats = { img: 'images/quest-giver.png', pngWidth: 948, pngHeight: 1101, spriteWidth: 43, spriteHeight: 50, x: 150, y: 150, type: 'quest-giver', levelShowUp: 1 }; class QuestGiver { constructor(stats) { this.image = newImage(stats.img); this.xFrame = 0; // x starting point of src img for sprite frame this.yFrame = 0; // y starting point of src img for sprite frame this.pngWidth = stats.pngWidth; // width of src img sprite size this.pngHeight = stats.pngHeight; // height of src img sprite size this.spriteWidth = stats.spriteWidth; // width of sprite on canvas this.spriteHeight = stats.spriteHeight; // height of sprite on canvas this.x = stats.x; // x point of enemy on canvas this.y = stats.y; // y point of enemy on canvas this.availableQuests = [new KillQuest()]; }; draw() { ctxSpriteMap.drawImage(this.image, this.xFrame, this.yFrame, this.pngWidth, this.pngHeight, this.x, this.y, this.spriteWidth, this.spriteHeight); }; click(player) { let aq = this.availableQuests; if (player.quests[0]) { // placeholder quest stuff...clean up later if (player.quests[0].kills >= player.quests[0].killsToComplete) { // player.xp += player.quests[0].xp; // $('#player-xp').text(player.xp); player.gainXP(player.quests[0].xp); player.quests.splice(player.quests[0]); $('#quests-div ul').empty(); this.availableQuests.push(new KillQuest()); showQuests(); } } else { if (aq.length > 0) { // placeholder for now...ugly...clean up to be actual quest player.quests.push(aq.splice(aq.indexOf(aq[0]), 1)[0]); } if (showHideQuests.showing()) { showQuests(); } } } }; let questGiverInstance = new QuestGiver(stats); // class Tektite extends Enemy { // constructor() { // super( // stats.img, // stats.pngWidth, // stats.pngHeight, // stats.spriteWidth, // stats.spriteHeight, // stats.xStart, // stats.yStart, // stats.speed, // stats.type, // stats.maxLife, // stats.strength, // stats.points, // stats.levelShowUp // ); // this.numberOfSpaces = [0, 1, 2, 3]; // }; // // }; export { QuestGiver, questGiverInstance };
const mix = require('laravel-mix'); /* |-------------------------------------------------------------------------- | Mix Asset Management |-------------------------------------------------------------------------- | | Mix provides a clean, fluent API for defining some Webpack build steps | for your Laravel application. By default, we are compiling the Sass | file for the application as well as bundling up all the JS files. | */ // mix.js('resources/js/app.js', 'public/js') // .sass('resources/sass/app.scss', 'public/css'); mix.scripts([ "public/assets/vendor/jquery/jquery.min.js", "public/assets/vendor/jquery-migrate/jquery-migrate.min.js", "public/assets/vendor/popper.js/popper.min.js", "public/assets/vendor/bootstrap/bootstrap.min.js", "public/assets/vendor/appear.js", "public/assets/vendor/slick-carousel/slick/slick.js", "public/assets/js/hs.core.js", "public/assets/js/components/hs.header.js", "public/assets/js/helpers/hs.hamburgers.js", "public/assets/js/components/hs.scroll-nav.js", "public/assets/js/components/hs.carousel.js", "public/assets/js/components/hs.go-to.js", "public/assets/js/custom.js", ], 'public/js/all.js') .styles([ "public/assets/vendor/bootstrap/bootstrap.min.css", "public/assets/vendor/icon-awesome/css/font-awesome.min.css", "public/assets/vendor/icon-line/css/simple-line-icons.css", "public/assets/vendor/icon-hs/style.css", "public/assets/vendor/hamburgers/hamburgers.min.css", "public/assets/vendor/animate.css", "public/assets/vendor/slick-carousel/slick/slick.css", "public/assets/css/styles.op-business.css", "public/assets/css/custom.css", ], 'public/css/all.css')
Ext.namespace("Ext.xxr"); Ext.xxr.Teacher = function(cfg) { if (cfg == null) { cfg = {} } Ext.apply(this, cfg); } Ext.extend(Ext.xxr.Teacher, Ext.xxr.Person, { job : "教师", print : function() { alert(String.format("{0}是一位{1}{2}", this.name, this.sex, this.job)); } })
import {modulo} from '@danehansen/math'; import {RADIANS_IN_CIRCLE} from 'util/constants'; function flipRadiansVertically(radians) { return Math.atan2(-Math.sin(radians), Math.cos(radians)); } export default function fillSlice(canvas, color, diameter, startRadians, endRadians, outerRadius, holeRadius, isInKey) { const center = diameter / 2; const isCircle = modulo(startRadians, RADIANS_IN_CIRCLE) === modulo(endRadians, RADIANS_IN_CIRCLE); canvas.beginPath(); canvas.fillStyle = typeof color === 'object' ? `rgb(${color.r}, ${color.g}, ${color.b})` : color; if (isCircle) { canvas.arc(center, center, center * outerRadius, 0, RADIANS_IN_CIRCLE); } else { // clockwise straight edge let cos = Math.cos(startRadians); let sin = Math.sin(startRadians); canvas.moveTo(center + cos * center * holeRadius, center + sin * -center * holeRadius); canvas.lineTo(center + cos * center * outerRadius, center + sin * -center * outerRadius); // outer arc canvas.arc(center, center, center * outerRadius, flipRadiansVertically(startRadians), flipRadiansVertically(endRadians), true); // anticlockwise straight edge cos = Math.cos(endRadians); sin = Math.sin(endRadians); canvas.moveTo(center + cos * center * outerRadius, center + sin * -center * outerRadius); canvas.lineTo(center + cos * center * holeRadius, center + sin * -center * holeRadius); // inner arc canvas.arc(center, center, center * holeRadius, flipRadiansVertically(endRadians), flipRadiansVertically(startRadians), false); } canvas.fill(); if (isCircle) { canvas.beginPath(); canvas.globalCompositeOperation = 'destination-out'; canvas.arc(center, center, center * holeRadius, 0, RADIANS_IN_CIRCLE); canvas.fill(); canvas.globalCompositeOperation = 'source-over'; } }
const { User } = require('database').models; /** * Make any changes you need to make to the database here */ exports.up = async (done) => { try { const res = await User.updateMany( { 'user_metadata.notifications_last_timestamp': null }, { $set: { 'user_metadata.notifications_last_timestamp': 0 } }, ); console.log(res); } catch (error) { console.error(error); } done(); }; /** * Make any changes that UNDO the up function side effects here (if possible) */ exports.down = async (done) => { done(); };
/*** dir:javascripts; ***/
"use strict" const activeTabs = { HOME: 0, DEPOSIT: 1, WITHDRAW: 3, SEND: 4, LOGIN: 5, REGISTER: 6, PROFILE: 7, LOGOUT: 8 } const transactionType = { DEPOSIT: 0, WITHDRAW: 1, SEND: 2 }
import { Meteor } from 'meteor/meteor'; import { check } from 'meteor/check'; import { Foods } from '../../api/foods/foods'; const getMockFoods = () => { return [ { name: 'food1', price: 2.4, description: 'description 1' }, { name: 'food2', price: 1.2, description: 'description 2' }, { name: 'food3', price: 3.57, description: 'description 3' }, { name: 'food4', price: 5.99, description: 'description 4' }, { name: 'food1', price: 11.3, description: 'description 5' }, ]; }; const createDefaultFoods = () => { if (Foods.find().count() === 0) { const mockFoods = getMockFoods(); mockFoods.forEach(food => Foods.insert(food)); } }; Meteor.startup(() => { createDefaultFoods(); process.env.MAIL_URL = "smtp://postmaster@pizzaday.folizyuk.com:9fc194a81d801e48269d682d5daaab03-2b4c5a6c-b9164ea8@smtp.mailgun.org:587"; Meteor.methods({ sendEmail(to, from, subject, html) { check([to, from, subject, html], [String]); this.unblock(); Email.send({ to, from, subject, html }); } }); });
import React, { useEffect } from 'react' import {useDispatch, useSelector} from'react-redux' import {useHistory} from 'react-router-dom' import {getTrendingToday,getTrendingWeek} from '../../actions/TMDBapi' import moment from 'moment' const TrendingFilm = () => { let dispatch = useDispatch() let history = useHistory() let films = useSelector(state=>state.trending) let selectedTrendingFilm = useSelector(state=>state.selectedTrendingFilm) useEffect(()=>{ dispatch(getTrendingToday()) dispatch(getTrendingWeek()) setTimeout(()=>{ dispatch({type:"changeTrendingSelected", payload:"day"}) },2000) // eslint-disable-next-line react-hooks/exhaustive-deps },[]) return ( <> {films.length === 0 ? "loading..." : <div> <div className="Title-container"> <div className="Main-page-title">Trending Film</div> <div className="Active-container"> <div className="Active" style={{backgroundColor: selectedTrendingFilm === "day" ? "blue" : "white", color: selectedTrendingFilm === "day" ? "white" : "black"}} onClick={()=>dispatch({type:"changeTrendingSelected", payload:"day"})}>Today</div> <div className="Active" style={{backgroundColor: selectedTrendingFilm === "week" ? "blue" : "white", color: selectedTrendingFilm === "week" ? "white" : "black"}} onClick={()=>dispatch({type:"changeTrendingSelected", payload:"week"})}>This Week</div> </div> </div> <div className="Film-table"> <table> <tbody> <tr className="Card-container"> { films.map(film=>{ return( <td key={film.id} className="Card"> <div className="Poster-Container" onClick={()=>history.push(`/${film.media_type}/details/${film.id}`)}> <div className="Poster" style={{backgroundImage:`url(https://image.tmdb.org/t/p/original${film.poster_path})`}}> </div> <div className="Rating"> {film.vote_count === 0 ? "NR": <div>{film.vote_average*10}<sup>%</sup></div>} </div> </div> <div className="Card-title-cont"> <div className="Card-title"><strong>{film.title}</strong></div> <div>{moment(film.release_date).format("MMM Do, YYYY")}</div> </div> </td> ) }) } </tr> </tbody> </table> </div> </div> } </> ) } export default TrendingFilm
import React, { Component } from 'react'; class Feature extends Component { render() { return ( <div> <div className="columns featureCard"> <div className="column is-one-third-mobile is-one-third-mobile-centered is-offset-one-quarter is-one-quarter-tablet is-gapless featureImgCol"> {/*img src and alt will need to be replaced with state or props or whatever*/} <img src="./img/igp2.png" alt="TITLE HERE" /> </div> <div className="featureContent column is-one-third-mobile is-one-third-mobile-centered is-one-quarter-tablet is-gapless"> {/*h3, description, and price will need to be replaced with state or props or whatever*/} <h3 className="featureTitle">Led Zeppelin</h3> <p className="featureDescription">A classic Led Zeppelin patch, perfect for the gnarliest of Zep Heads.</p> <p className="featurePrice"><span className="dollarSign">$</span>12</p> </div> </div> </div> ); } } export default Feature;
import {Random} from "meteor/random"; import * as Graphs from "/imports/api/graphs/graphs.js"; import {getGraph, getNodeEdgeMap} from "/imports/api/graphs/methods.js"; export const TYPE = "type"; export const ID = "id"; export const NODE_TYPE_PROCESS = "process"; export const NODE_TYPE_TERMINATOR = "terminator"; export const NODE_TYPE_VIRTUAL = "virtual"; export const NODE_TYPE_FIRST = "first"; export const OPTIONS = "options"; export const OPTION_NAME = Graphs.EDGE_NAME; export const OPTION_DETAILS = Graphs.EDGE_DETAILS; export const OPTION_PARENT_NODE_ID = "parentNode"; export const EDGE_NODE_SOURCE = "nodeSource"; /** * Converts a JSPlumb Graph back into the MongoDB format. * This involves: * - Merging options with the outgoing edges * - Removing unused options * - Removing unused nodes * - Setting firstNode to the node with TYPE_FIRST_NODE * - Converting id to _id * - Ensuring all objects conform the schema * - Validating the graph (graphs/methods/validateGraph) * @param jgraph graph in JSPlumb format */ export const getJSPlumbAsGraph = function (jgraph, graphId) { let jnodes = jgraph.getNodes(); let owner = Meteor.userId(); if (!owner) { throw new Error("The user must be logged in to do this"); } let firstNode = getFirstNodeIDFromJSPlumb(jnodes); if (!firstNode) { throw new Error("There is not exactly 1 first node"); } let edges = getEdgesFromJSPlumb(jnodes); let nodes = getNodesFromJSPlumb(jnodes); let graph = {}; graph[Graphs.OWNER] = owner; graph[Graphs.FIRST_NODE] = firstNode; graph[Graphs.EDGES] = edges; graph[Graphs.NODES] = nodes; graph[Graphs.GRAPH_ID] = graphId; return graph; }; /** * Gets the node ID with type TYPE_FIRST, or null if there is not exactly 1 result * @param jnodes */ function getFirstNodeIDFromJSPlumb(jnodes) { let typeFirstNodes = _.filter(_.pluck(jnodes, "data"), function (node) { return node[TYPE] == NODE_TYPE_FIRST; }); if (typeFirstNodes.length != 1) { return null; } return typeFirstNodes[0][ID]; } function getNodesFromJSPlumb(jnodes) { let nodes = []; _.each(jnodes, function (jnode) { // Copy node data let node = {}; _.each(_.keys(jnode.data), function (key) { node[key] = jnode.data[key]; }); node[Graphs.NODE_ID] = node[ID]; // Clean the node with the MongoDB Schema Graphs.Graphs.schema.nodeSchema.clean(node); nodes.push(node); }); return nodes; } /** * Gets all edges in the MongoDB format from the JSPlumb nodes * @param jnodes * @param edges */ function getEdgesFromJSPlumb(jnodes) { let edges = []; _.each(jnodes, function (jnode) { // Find all the edges that are outgoing // getAllEdges includes incoming edges let outgoingEdges = _.filter(jnode.getAllEdges(), function (jnodeEdge) { // source is a Port, get the parent node and compare to the node return jnodeEdge.source.getNode()[ID] == jnode[ID]; }); // Make proper edges out of outgoing edges _.each(outgoingEdges, function (outEdge) { let port = outEdge.source; let edge = {}; _.each(_.keys(port.data), function (key) { edge[key] = port.data[key]; }); edge[Graphs.EDGE_ID] = port[ID]; edge[Graphs.EDGE_SOURCE] = port.getNode()[ID]; edge[Graphs.EDGE_TARGET] = outEdge.target[ID]; // target is just a node // Clean the edge with the MongoDB Schema Graphs.Graphs.schema.edgeSchema.clean(edge); edges.push(edge); }); }); return edges; } /** * Retrieves a graph from the graphs collection and * transforms it into a format expected by the JSPlumb library. * Changes in the JSPlumb form: * - Different ID key * - Outgoing edge information is stored in the node in the form of options (ports) * - Edges are just source and target containers * - Edge source is extended to be nodeId.optionId * - Nodes have a new TYPE field * @param graphId */ export const getGraphAsJSPlumb = new ValidatedMethod({ name: "getGraphAsJSPlumb", validate: function (id) { }, run(graphId){ let graph = getGraph.call(graphId); if (!graph) { return newGraph; } let newGraph = {}; newGraph[Graphs.FIRST_NODE] = graph[Graphs.FIRST_NODE]; newGraph[Graphs.NODES] = graph[Graphs.NODES]; newGraph[Graphs.EDGES] = graph[Graphs.EDGES]; newGraph = labelJSPlumbNodeOptions(graph, newGraph); newGraph = labelJSPlumbNodeTypes(graph, newGraph); newGraph = cleanJSPlumbEdges(newGraph); newGraph = convertIdsToJSPlumb(newGraph); return newGraph; } }); /** * Convert the _id field to id for nodes, edges, and options. * TODO: convert comment IDs * @param newGraph * @returns {*} */ function convertIdsToJSPlumb(newGraph) { _.each(newGraph[Graphs.NODES], function (node) { node[ID] = node[Graphs.NODE_ID]; delete node[Graphs.NODE_ID]; _.each(node[OPTIONS], function (opt) { // option was made from an edge opt[ID] = opt[Graphs.EDGE_ID]; delete opt[Graphs.EDGE_ID]; }) }); _.each(newGraph[Graphs.EDGES], function (edge) { edge[ID] = edge[Graphs.EDGE_ID]; delete edge[Graphs.EDGE_ID]; }); return newGraph; } /** * Extend the edge sources and remove every other attribute since it's * now a part of the option. * @param newGraph * @returns {*} */ function cleanJSPlumbEdges(newGraph) { // JSPlumb edges are strictly source to target, // the other information is in the options as a part // of the node let oldEdges = newGraph[Graphs.EDGES] let newEdges = _.map(oldEdges, function (edge) { let e = {}; // New source is the port, save for node source for layout purposes e[EDGE_NODE_SOURCE] = edge[Graphs.EDGE_SOURCE]; e[Graphs.EDGE_SOURCE] = edge[Graphs.EDGE_SOURCE] + "." + edge[Graphs.EDGE_ID]; e[Graphs.EDGE_TARGET] = edge[Graphs.EDGE_TARGET]; return e; }); newGraph[Graphs.EDGES] = newEdges; return newGraph; } /** * Convert outgoing edges into options by copying the edge, sans source and target * @param graph * @param newGraph * @returns {*} */ function labelJSPlumbNodeOptions(graph, newGraph) { // All outgoing edges are transformed into node options, which will become // the ports. Each option has all of the edge information, with the ID // being the old edge ID, and no source and targets. let nodeMap = getNodeEdgeMap(graph); _.each(newGraph[Graphs.NODES], function (node) { node[OPTIONS] = []; _.each(nodeMap[node[Graphs.NODE_ID]].outgoingEdges, function (edge) { let opt = _.omit(edge, Graphs.EDGE_SOURCE, Graphs.EDGE_TARGET); opt[OPTION_PARENT_NODE_ID] = node[Graphs.NODE_ID]; node[OPTIONS].push(opt); }); }); return newGraph; } /** * Label node types * @param graph * @param newGraph * @returns {*} */ function labelJSPlumbNodeTypes(graph, newGraph) { _.each(newGraph[Graphs.NODES], function (node) { if (graph[Graphs.FIRST_NODE] == node[Graphs.NODE_ID]) { node[TYPE] = NODE_TYPE_FIRST; } else if (node[Graphs.NODE_CHART_ID]) { node[TYPE] = NODE_TYPE_VIRTUAL; } else if (node[OPTIONS].length >= 1) { node[TYPE] = NODE_TYPE_PROCESS; } else { node[TYPE] = NODE_TYPE_TERMINATOR; } }); return newGraph; } /** * Returns a new empty node object in JSPlumb format. * A random ID is assigned * @param name * @returns {{}} */ export const getJSPlumbNodeObject = function (name) { let node = {}; node[ID] = Random.id(); node[Graphs.NODE_NAME] = name || ""; node[Graphs.EDGE_DETAILS] = ""; node[TYPE] = NODE_TYPE_PROCESS; node[OPTIONS] = []; node[Graphs.NODE_RESOURCES] = []; node[Graphs.NODE_IMAGES] = []; node[Graphs.NODE_COMMENTS] = []; return node; }; /** * Returns a new option object with a randomly assigned ID * and the given parentId * @param optionText * @param parentId * @returns {{}} */ export const getOptionObject = function (optionText, parentId) { let opt = {}; opt[OPTION_NAME] = optionText || ""; opt[OPTION_DETAILS] = ""; opt[ID] = Random.id(); opt[OPTION_PARENT_NODE_ID] = parentId; return opt; };
import React, { useState } from 'react'; import { connect } from 'react-redux'; import { withRouter } from 'react-router-dom'; import NewThreadButton from '../../Components/Threads/NewThread/NewThreadButton'; import NewThreadModal from '../../Components/Threads/NewThread/NewThreadModal'; const CreateThread = (props) => { const [showModal, setShowModal] = useState(false); function redirectToThread(thread) { setShowModal(false); const redirectionUrl = `/${thread.category.slug}/${thread.slug}`; props.history.push(redirectionUrl); props.dispatch({type: "SHOW_FLASH", value: { message: "Your thread has been created successfully ! "}}); } let JsxElement = ''; if(props.auth.loggedIn) { JsxElement = ( <> <NewThreadButton onPressed={() => setShowModal(true) } /> <NewThreadModal auth={props.auth} show={showModal} onClosed={() => setShowModal(false) } onSaved={ redirectToThread } /> </> ) } return JsxElement; }; const mapStateToProps = (state) => ({ auth : state.auth, flash: state.flash }); export default connect(mapStateToProps)( withRouter(CreateThread) );
function block(details) { return {cancel: true}; } function run() { var urlsArray = JSON.parse(localStorage.getItem("urlsFormatted")); for (var i = 0; i < urlsArray.length; i++){ chrome.webRequest.onBeforeRequest.addListener( block, {urls: [urlsArray[i]]}, ["blocking"]); } } function stop() { chrome.webRequest.onBeforeRequest.removeListener( block ); } chrome.storage.onChanged.addListener(function runOrStop(changes, area) { var changedItems = Object.keys(changes); for (let item of changedItems) { if (item === "running") { if (changes[item].newValue === "true"){ run(); } else { stop(); } } } })
'use strict'; const chai = require('chai'); const should = chai.should(); const expect = chai.expect; const testUtils = new (require('../../../TestUtils'))(__dirname); const Workspace = require('../../../../index').libs.Workspace; const FileWriter = require('../../../../src/util/FileWriter'); const TEST_NAME = 'Workspace.isMonoRepo()'; describe(TEST_NAME, function () { before(async function () { await testUtils.cleanUpWorkingDirs(); }); it('should detect presences of mono repo project ', async function () { //Test .isMonoRepo() with an empty folder const testDir = await testUtils.createUniqueTestDir(); const noLernaJsonResult = await Workspace.isMonoRepo(testDir); noLernaJsonResult.should.be.false; //Test .isMonoRepo() with a folder only containing a lerna.json no package.json const testDir2 = await testUtils.createUniqueTestDir(); await FileWriter.writeFiles({ 'lerna.json': '{}' }, testDir); const noPackageJsonResult = await Workspace.isMonoRepo(testDir2); noPackageJsonResult.should.be.false; //Test .isMonoRepo() with mono repo containing 0 packages const testDir3 = await testUtils.createUniqueTestDir(); await Workspace.createMonoRepo({},{},testDir3); const noPackagesResult = await Workspace.isMonoRepo(testDir3); noPackagesResult.should.be.true; //Test .isMonoRepo() with mono repo containing packages const testDir4 = await testUtils.createUniqueTestDir(); await Workspace.createMonoRepo({ '@aucfro/srvc-lib': { packageJson: { version: '1.0.2', private: true }, packageLocation: 'packages/backend/libs/srvc-lib', packageFiles: { 'changes.txt': '' } } },{},testDir4); const withPackagesResult = await Workspace.isMonoRepo(testDir4); withPackagesResult.should.be.true; }); });
// Import all the third party stuff import 'sanitize.css/sanitize.css'; // Load the favicon /* eslint-disable import/no-unresolved, import/extensions */ import '!file-loader?name=[name].[ext]!./images/favicon.ico'; import 'dayjs/locale/ru'; import { ConnectedRouter } from 'connected-react-router'; import dayjs from 'dayjs'; import FontFaceObserver from 'fontfaceobserver'; import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; // Import root app import Root from '@/pages/Root'; import history from '@/utils/history'; /* eslint-enable import/no-unresolved, import/extensions */ import configureStore from './configureStore'; // Observe loading of Open Sans (to remove open sans, remove the <link> tag in // the index.html file and this observer) const openSansObserver = new FontFaceObserver('Open Sans', {}); // When Open Sans is loaded, change font family css variable openSansObserver.load().then(() => { document.documentElement.style.setProperty( '--ff', `'Open Sans', 'Helvetica Neue', Helvetica, Arial, sans-serif` ); }); // Observe loading of Roboto Condensed (to remove Roboto Condensed, remove the <link> tag in // the index.html file and this observer) const robotoCondensedObserver = new FontFaceObserver('Roboto Condensed', {}); // When Open Sans is loaded, change font family css variable robotoCondensedObserver.load().then(() => { document.documentElement.style.setProperty('--dff', `'Roboto Condensed', Arial, sans-serif`); }); // Use Russian locale by default dayjs.locale('ru'); // Create redux store with history const initialState = {}; const store = configureStore(initialState, history); const MOUNT_NODE = document.getElementById('app'); const render = () => { ReactDOM.render( <Provider store={store}> <ConnectedRouter history={history}> <Root /> </ConnectedRouter> </Provider>, MOUNT_NODE ); }; if (module.hot) { // Hot reloadable React components and translation json files // modules.hot.accept does not accept dynamic dependencies, // have to be constants at compile-time module.hot.accept(['pages/Root'], () => { ReactDOM.unmountComponentAtNode(MOUNT_NODE); render(); }); } render(); // Install ServiceWorker and AppCache in the end since // it's not most important operation and if main code fails, // we do not want it installed if (process.env.NODE_ENV === 'production') { require('offline-plugin/runtime').install(); // eslint-disable-line global-require } if (process.env.NODE_ENV !== 'production') { const whyDidYouRender = require('@welldone-software/why-did-you-render'); // eslint-disable-line global-require whyDidYouRender(React, { exclude: [/^with*/] }); }
const killerCard = document.getElementById("killerCard"); const weaponCard = document.getElementById("weaponCard"); const roomCard = document.getElementById("roomCard"); const killerImage = document.getElementById("killerImage"); const favouriteWeapon = document.getElementById("favouriteWeapon"); const killerAge = document.getElementById("killerAge"); const killerName = document.getElementById("killerName"); const weaponImage = document.getElementById("weaponImage"); const weaponName = document.getElementById("weaponName"); const weaponWeight = document.getElementById("weaponWeight"); const roomName = document.getElementById("roomName"); const roomImage = document.getElementById("roomImage"); // STEP 1 - CREATE OBJECTS FOR ALL THE SUSPECTS, SOMETHING LIKE THIS: const mrGreen = { firstName: "Jacob", lastName: "Green", color: "MediumSeaGreen", description: "He has a lot of connections", age: 45, image: "assets/green.png", occupation: "Entrepreneur", favouriteWeapon: "axe" }; const professorPlum = { firstName: "Victor", lastName: "Plum", color: "plum", description: "He would be the smartest man on the planet if he wasn't so scatterbrained.", age: 50, image: "assets/plum.png", occupation: "Professor", favouriteWeapon: "rope" }; const missScarlet = { firstName: "Cassandra", lastName: "Scarlet", color: "Indianred", description: "She always has to be the center of attention.", age: 24, image: "assets/scarlet.png", occupation: "Actress", favouriteWeapon: "candlestick" }; const mrsPeacock = { firstName: "Eleanor", lastName: "Peacock", color: "Royalblue", description: "She's proper and has excellent manners", age: 60, image: "assets/peacock.png", occupation: "None", favouriteWeapon: "dumbbell" }; const colonelMustard = { firstName: "Jack", lastName: "Mustard", color: "lightyellow", description: "He loves to challenge people to a duel if they cross him, and he isn't afraid to speak his mind.", age: 57, image: "assets/mustard.png", occupation: "Colonel", favouriteWeapon: "knife" }; const mrsWhite = { firstName: "Blanche", lastName: "White", color: "white", description: "She owns nothing to her name and takes her domestic duties very seriously.", age: 55, image: "assets/white.png", occupation: "Maid", favouriteWeapon: "poison" }; // CREATE OBJECTS FOR ALL THE WEAPONS, ADD MORE CHARACTERISTICS TO THE WEAPONS IF YOU LIKE. const rope = { name: "rope", color: "brown", weight: 10, image: "assets/rope.svg", id: "rope" }; const knife = { name: "knife", color: "grey", weight: 11, image: "assets/knife.svg", id: "knife" }; const candlestick = { name: "candlestick", color: "silver", weight: 12, image: "assets/candlestick.svg", id: "candlestick" }; const dumbbell = { name: "dumbbell", color: "lightblue", weight: 13, image: "assets/gym.svg", id: "dumbbell" }; const poison = { name: "poison", color: "lightgreen", weight: 14, image: "assets/potion.svg", id: "poison" }; const axe = { name: "axe", color: "darkgreen", weight: 15, image: "assets/axe.svg", id: "axe" }; const bat = { name: "bat", color: "pink", weight: 16, image: "assets/baseballBat.svg", id: "bat" }; const trophy = { name: "trophy", color: "gold", weight: 17, image: "assets/award.svg", id: "trohpy" }; const pistol = { name: "pistol", color: "orange", weight: 18, image: "assets/gun.svg", id: "pistol" }; //OBJECTS FOR THE ROOMS const diningRoom = { name: "Dining Room", image: "assets/diningRoom.svg", color: "darkred" }; const conservatory = { name: "Conservatory", image: "assets/door.svg", color: "BlanchedAlmond" }; const kitchen = { name: "Kitchen", image: "assets/kitchen.svg", color: "Coral" }; const study = { name: "Study", image: "assets/work.svg", color: "Chocolate" }; const library = { name: "Library", image: "assets/library.svg", color: "CadetBlue" }; const billiardRoom = { name: "Billiard Room", image: "assets/snooker.svg", color: "DarkCyan" }; const lounge = { name: "Lounge", image: "assets/lounge.svg", color: "DarkGoldenRod" }; const ballroom = { name: "Ballroom", image: "assets/chandelier.svg", color: "DarkSlateBlue" }; const hall = { name: "Hall", image: "assets/hanger.svg", color: "Khaki" }; const spa = { name: "Spa", image: "assets/beauty.svg", color: "HotPink" }; const livingRoom = { name: "Living Room", image: "assets/lamp.svg", color: "LavenderBlush" }; const observatory = { name: "Observatory", image: "assets/telescope.svg", color: "LightSalmon" }; const theater = { name: "Theater", image: "assets/doorStar.svg", color: "NavajoWhite" }; const guestHouse = { name: "Guest House", image: "assets/realEstate.svg", color: "PeachPuff" }; const patio = { name: "Patio", image: "assets/outdoor.svg", color: "Olive" }; // NOW GROUP ALL SUSPECTS, WEAPONS AND ROOMS IN ARRAYS LIKE THIS: const suspects = [ mrGreen, mrsWhite, professorPlum, missScarlet, mrsPeacock, colonelMustard ]; const weapons = [ rope, knife, candlestick, dumbbell, poison, axe, bat, trophy, pistol ]; const rooms = [ diningRoom, conservatory, kitchen, study, library, billiardRoom, lounge, ballroom, hall, spa, livingRoom, observatory, theater, guestHouse, patio ]; // THIS FUNCTION WILL RANDOMLY SELECT ONE ITEM FROM THE ARRAY THAT YOU PASS IN TO THE FUNCTION. // YOU DON'T NEED TO CHANGE THIS, JUST TRY TO UNDERSTAND IT. AND HOW TO USE IT. const randomSelector = array => { return array[Math.floor(Math.random() * array.length)]; }; const mystery = { killer: undefined, weapon: undefined, room: undefined }; // FUNCTIONS const pickKiller = () => { mystery.killer = randomSelector(suspects); killerImage.style.display = "block"; favouriteWeapon.style.display = "block"; killerAge.style.display = "block"; killerName.style.display = "block"; killerCard.style.background = mystery.killer.color; document.getElementById("loadingKillerAnimation").style.display = "none"; killerName.innerHTML = `${mystery.killer.firstName} ${mystery.killer.lastName}`; killerImage.src = `${mystery.killer.image}`; killerAge.innerHTML = `Age: ${mystery.killer.age}`; favouriteWeapon.innerHTML = `Favourite Weapon: ${mystery.killer.favouriteWeapon}`; }; const pickWeapon = () => { mystery.weapon = randomSelector(weapons); weaponName.style.display = "block"; weaponWeight.style.display = "block"; weaponImage.style.display = "block"; document.getElementById("loadingWeaponAnimation").style.display = "none"; weaponCard.style.background = mystery.weapon.color; weaponName.innerHTML = `${mystery.weapon.name}`; weaponWeight.innerHTML = `${mystery.weapon.weight}`; weaponImage.src = `${mystery.weapon.image}`; }; const pickRoom = () => { mystery.room = randomSelector(rooms); roomName.style.display = "block"; roomImage.style.display = "block"; document.getElementById("loadingRoomAnimation").style.display = "none"; roomCard.style.background = mystery.room.color; roomName.innerHTML = `${mystery.room.name}`; roomImage.src = `${mystery.room.image}`; }; const startKillerAnimation = () => { killerImage.style.display = "none"; favouriteWeapon.style.display = "none"; killerAge.style.display = "none"; killerName.style.display = "none"; document.getElementById("loadingKillerAnimation").style.display = "block"; setTimeout(pickKiller, 1500); }; const startWeaponAnimation = () => { weaponName.style.display = "none"; weaponWeight.style.display = "none"; weaponImage.style.display = "none"; document.getElementById("loadingWeaponAnimation").style.display = "block"; setTimeout(pickWeapon, 1500); }; const startRoomAnimation = () => { roomName.style.display = "none"; roomImage.style.display = "none"; document.getElementById("loadingRoomAnimation").style.display = "block"; setTimeout(pickRoom, 1500); }; // CALL FUNCTIONS WHEN CLICK ON CARDS killerCard.onclick = startKillerAnimation; weaponCard.onclick = startWeaponAnimation; roomCard.onclick = startRoomAnimation; // FINAL FUNCTION const revealMystery = () => { const answerMystery = document.getElementById("mysteryAnswer") if (mystery.killer === undefined || mystery.weapon === undefined || mystery.room === undefined) { answerMystery.innerHTML = ("Please choose a killer, a weapon and a room."); } else { answerMystery.innerHTML = (`The murder was committed by ${mystery.killer.firstName} ${mystery.killer.lastName}, in the ${mystery.room.name} with a ${mystery.weapon.name}.`); document.getElementById("revealButton").style.display = "none"; document.getElementById("newGameButton").style.display = "block"; } };
define([], function () { require.config({ paths: { 'async': '../addons/example/js/async', 'BMap': ['//api.map.baidu.com/api?v=2.0&ak=mXijumfojHnAaN2VxpBGoqHM'], }, shim: { 'BMap': { deps: ['jquery'], exports: 'BMap' } } }); require.config({ paths: { 'bootstrap-markdown': '../addons/markdown/js/bootstrap-markdown.min', 'hyperdown': '../addons/markdown/js/hyperdown.min', 'pasteupload': '../addons/markdown/js/jquery.pasteupload' }, shim: { 'bootstrap-markdown': { deps: [ 'jquery', 'css!../addons/markdown/css/bootstrap-markdown.css' ], exports: '$.fn.markdown' }, 'pasteupload': { deps: [ 'jquery', ], exports: '$.fn.pasteUploadImage' } } }); require(['form', 'upload'], function (Form, Upload) { var _bindevent = Form.events.bindevent; Form.events.bindevent = function (form) { _bindevent.apply(this, [form]); try { if ($(".editor", form).size() > 0) { require(['bootstrap-markdown', 'hyperdown', 'pasteupload'], function (undefined, undefined, undefined) { $.fn.markdown.messages.zh={Bold:"粗体",Italic:"斜体",Heading:"标题","URL/Link":"链接",Image:"图片",List:"列表","Unordered List":"无序列表","Ordered List":"有序列表",Code:"代码",Quote:"引用",Preview:"预览","strong text":"粗体","emphasized text":"强调","heading text":"标题","enter link description here":"输入链接说明","Insert Hyperlink":"URL地址","enter image description here":"输入图片说明","Insert Image Hyperlink":"图片URL地址","enter image title here":"在这里输入图片标题","list text here":"这里是列表文本","code text here":"这里输入代码","quote here":"这里输入引用文本"}; var parser = new HyperDown(); window.marked = function (text) { return parser.makeHtml(text); }; //粘贴上传图片 $.fn.pasteUploadImage.defaults = $.extend(true, $.fn.pasteUploadImage.defaults, { fileName: "file", appendMimetype: false, ajaxOptions: { url: Fast.api.fixurl(Config.upload.uploadurl), beforeSend: function (jqXHR, settings) { $.each(Config.upload.multipart, function(i,j ){ settings.data.append(i, j); }); return true; } }, success: function (data, filename, file) { var ret = Upload.events.onUploadResponse(data); $(this).insertToTextArea(filename, Config.upload.cdnurl + data.data.url); return false; }, error: function (data, filename, file) { console.log(data, filename, file); } }); //手动选择上传图片 $(document).on("change", "#selectimage", function () { $.each($(this)[0].files, function (i, file) { $("").uploadFile(file, file.name); }); //$("#message").pasteUploadImage(); }); $(".editor", form).each(function () { $(this).markdown({ resize: 'vertical', language: 'zh', iconlibrary: 'fa', autofocus: false, savable: false }); $(this).pasteUploadImage(); }); }); } } catch (e) { } }; }); require.config({ paths: { 'simditor': '../addons/simditor/js/simditor.min', }, shim: { 'simditor': [ 'css!../addons/simditor/css/simditor.min.css' ] } }); if ($(".editor").size() > 0) { //修改上传的接口调用 require(['upload', 'simditor'], function (Upload, Simditor) { var editor, mobileToolbar, toolbar; Simditor.locale = 'zh-CN'; Simditor.list = {}; toolbar = ['title', 'bold', 'italic', 'underline', 'strikethrough', 'fontScale', 'color', '|', 'ol', 'ul', 'blockquote', 'code', 'table', '|', 'link', 'image', 'hr', '|', 'indent', 'outdent', 'alignment']; mobileToolbar = ["bold", "underline", "strikethrough", "color", "ul", "ol"]; $(".editor").each(function () { var id = $(this).attr("id"); editor = new Simditor({ textarea: this, toolbarFloat: false, toolbar: toolbar, pasteImage: true, defaultImage: Fast.api.cdnurl('/assets/addons/simditor/images/image.png'), upload: {url: '/'} }); editor.uploader.on('beforeupload', function (e, file) { Upload.api.send(file.obj, function (data) { var url = Fast.api.cdnurl(data.url); editor.uploader.trigger("uploadsuccess", [file, {success: true, file_path: url}]); }); return false; }); editor.on("blur", function () { this.textarea.trigger("blur"); }); Simditor.list[id] = editor; }); }); } require.config({ paths: { 'summernote': '../addons/summernote/lang/summernote-zh-CN.min' }, shim:{ 'summernote': ['../addons/summernote/js/summernote.min', 'css!../addons/summernote/css/summernote.css'], } }); require(['form', 'upload'], function (Form, Upload) { var _bindevent = Form.events.bindevent; Form.events.bindevent = function (form) { _bindevent.apply(this, [form]); try { //绑定summernote事件 if ($(".summernote,.editor", form).size() > 0) { require(['summernote'], function () { $(".summernote,.editor", form).summernote({ height: 250, lang: 'zh-CN', fontNames: [ 'Arial', 'Arial Black', 'Serif', 'Sans', 'Courier', 'Courier New', 'Comic Sans MS', 'Helvetica', 'Impact', 'Lucida Grande', "Open Sans", "Hiragino Sans GB", "Microsoft YaHei", '微软雅黑', '宋体', '黑体', '仿宋', '楷体', '幼圆', ], fontNamesIgnoreCheck: [ "Open Sans", "Microsoft YaHei", '微软雅黑', '宋体', '黑体', '仿宋', '楷体', '幼圆' ], toolbar: [ ['style', ['style', 'undo', 'redo']], ['font', ['bold', 'underline', 'strikethrough', 'clear']], ['fontname', ['color', 'fontname', 'fontsize']], ['para', ['ul', 'ol', 'paragraph', 'height']], ['table', ['table', 'hr']], ['insert', ['link', 'picture', 'video']], ['view', ['fullscreen', 'codeview', 'help']] ], dialogsInBody: true, callbacks: { onChange: function (contents) { $(this).val(contents); $(this).trigger('change'); }, onInit: function () { }, onImageUpload: function (files) { var that = this; //依次上传图片 for (var i = 0; i < files.length; i++) { Upload.api.send(files[i], function (data) { var url = Fast.api.cdnurl(data.url); $(that).summernote("insertImage", url, 'filename'); }); } } } }); }); } } catch (e) { } }; }); });
/*Search*/ $(document).ready(function(){ $("#nav-search-in-content").text("Library Resources"); $("#searchDropdownBox").change(function(){ var Search_Str = $(this).val(); //replace search str in span value $("#nav-search-in-content").text(Search_Str); }); }); //Show / Hide Text $(document).ready(function(){ var slideDiv = $(".slidingDiv"); var showMore = $(".show_text"); var hideMore = $(".hide_text"); /*Show Text*/ $(".show_text").click(function(e) { e.preventDefault(); if (slideDiv.hasClass("hide")) { //showMore.html("> show less"); showMore.addClass('hide'); //slideDiv.slideUp(0,function(){ // slideDiv.removeClass('hide') // slideDiv.addClass('show_div') // .slideDown('fast'); // }); slideDiv.removeClass('hide'); slideDiv.addClass('show_div'); } }); /*Hide Text*/ $(".hide_text").click(function(e) { e.preventDefault(); if (slideDiv.hasClass("show_div")) { //showMore.html("> show less"); showMore.removeClass('hide'); // slideDiv.slideDown(0,function(){ slideDiv.removeClass('show_div') slideDiv.addClass('hide') // .slideUp('slow'); // }); } }); }); //Show / Hide Description Text $(document).ready(function(){ $(".show_desc_info_content").addClass("hide"); //Show/Hide Links $(".show_desc_info").click(function(e) { e.preventDefault(); var $this = $(this); //capture clicked link var show_desc_info_content = $this.parent().find(".show_desc_info_content"); //get the div parent of the clicked .show_hide link if (show_desc_info_content.hasClass("hide")) { $this.html("> hide information"); // show_desc_info_content.slideUp(0,function(){ show_desc_info_content.removeClass('hide') // .slideDown('fast'); // }); }else{ $this.html("show information >"); // show_desc_info_content.slideUp('fast',function(){ show_desc_info_content.addClass('hide') // .slideDown(0); // }); } }); var show_desc_info_content = $('.show_desc_info_content'); $('.show_all_desc').click(function(e) { e.preventDefault(); $('.show_desc_info').html("> hide information"); //show_desc_info_content.slideUp(0,function(){ show_desc_info_content.removeClass('hide') // .slideDown('fast'); //}); }); $('.hide_all_desc').click(function(e) { e.preventDefault(); $('.show_desc_info').html("show information >"); //show_desc_info_content.slideUp(0,function(){ show_desc_info_content.addClass('hide') // .slideDown('fast'); // }); }); }); //Show / Hide database tables $(document).ready(function(){ var alpha_id = $('#pager-alpha .nav a'); alpha_id.click(function(e){ e.preventDefault(); $('.page').removeClass('hide'); if(this.id == "all"){ $('.show_desc_info_content').addClass('hide'); $('.show_desc_info').html("show information >"); }else{ $('.page').not('.database-' + this.id).addClass('hide'); $('.show_desc_info_content').removeClass('hide'); $('.show_desc_info').html("> hide information"); } }); }); //Show / Hide Login Information $(document).ready(function(){ $(".login_info").addClass('hide'); $('.login_text').click(function(e){ e.preventDefault(); $('.login_text').removeClass('login_selected'); $(".login_info").addClass('hide'); $(".login_info").removeClass('show_login_info'); $(this).next('.login_info').addClass('show_login_info'); $(this).next('.login_info').removeClass('hide'); $(this).addClass('login_selected'); }); }); //Show / Hide - FAQs All Answers $(document).ready(function(){ $('.show_all_faq').click(function(){ $('div.accordion a.icon').addClass('on'); $('div.accordion div').addClass('show'); }); $('.hide_all_faq').click(function(){ $('div.accordion a.icon').removeClass('on'); $('div.accordion div').removeClass('show'); }); }); //Contact Show form $(document).ready(function(){ $(".someone_else_request").addClass('hide'); $('.someone_else_request').find('input,select,textarea,button').attr('tabindex', '-1'); $("input[value='someone_else']").change(function () { $(".someone_else_request").removeClass('hide'); $('.someone_else_request').find('input,select,textarea,button').attr('tabindex', '0'); }); $("input[value='me']").change(function () { $(".someone_else_request").addClass('hide'); $('.someone_else_request').find('input,select,textarea,button').attr('tabindex', '-1'); }); }); //*****************************/ //* ALPHA PAGER SCRIPT */ //*****************************/ $(document).ready(function(){ var $alphaPager = $("#pager-alpha"), $alphaPagerNav = $(".nav", $alphaPager), $alphaPagerPages = $(".page", $alphaPager), $pageAnchor = window.location.hash; $("a[name]", $alphaPager).each(function () { $(this).attr("id", $(this).attr("name")); }); if ($pageAnchor) { var $elemID = $($pageAnchor), $elemContainer = $elemID.closest("div.page"), $elemIndex = $elemContainer.index() - 1; $elemContainer.show(); $("a", $alphaPagerNav).eq($elemIndex).addClass("active"); } $("a", $alphaPagerNav).on("click", function (e) { e.preventDefault(); var alphaID = $(this).attr("href").replace("#", ""); $("a", $alphaPagerNav).removeAttr("class"); $alphaPagerPages.hide(); $(this).addClass("active"); $(".page:eq(" + alphaID + ")", $alphaPager).show(); $(".page:visible a:first", $alphaPager).focus(); }) }); //Database Table Accordion $(function() { //New function Toggle Attribute //https://gist.github.com/mathiasbynens/298591 $.fn.toggleAttr = function(attr, attr1, attr2) { return this.each(function() { var self = $(this); if (self.attr(attr) == attr1) self.attr(attr, attr2); else self.attr(attr, attr1); }); }; var $database = $('.database-table'); $database.find("thead tr").show(); $database.find("tbody").show(); $database.find("thead").click(function(){ $(this).siblings().toggleClass('hide'); $(this).find("th").toggleClass('table_hide'); }) $database.find("thead").bind("keydown", function (e) { if (e.keyCode == 13) { e.stopPropagation(), e.preventDefault(); $(this).siblings().toggleClass('hide'); $(this).find("th").toggleClass('table_hide'); $(this).siblings().find("tr td a").toggleAttr('tabindex', '-1', '0'); }; }); }); //Favorite - Add and Remove to My Resources //Script is needed & used on all pages with a favorite folder $(document).ready(function(){ //Get resource name and populate inline for accessibility $(".favorite-id").each(function(index) { var favorite_id = $(this).text(); $(".favorite-id-title").each(function(i) { if(index == i){ $(this).html(favorite_id); } }); }); //Add and Remove favorites to and from My Resources var favorite = $('.favorite'); //By Keyboard favorite.bind("keydown", function (e) { if (e.keyCode == 13) { e.stopPropagation(), e.preventDefault(); $(this).toggleClass('favorite_on'); var favorite_id = $(this).find('.favorite-id-title').text(); if ($(this).hasClass('favorite_on')){ $(this).attr('title', 'Remove ' + favorite_id + ' from My Resources'); } else{ $(this).attr('title', 'Add ' + favorite_id + ' to My Resources'); }; }; if (e.keyCode == 27) { //return if ESC is pressed }; }); //By Click favorite.click(function(e){ e.stopPropagation(), e.preventDefault(); $(this).toggleClass('favorite_on'); var favorite_id = $(this).find('.favorite-id-title').text(); if ($(this).hasClass('favorite_on')){ $(this).attr('title', 'Remove ' + favorite_id + ' from My Resources'); } else{ $(this).attr('title', 'Add ' + favorite_id + ' to My Resources'); }; }); //Populate Add or Remove inline depending on the state of the favorite $('.favorite').each(function(index) { if($(this).hasClass('favorite_on')){ $(this).prepend("Remove"); } else{ $(this).prepend("Add"); } }); }); //CONTACT form $(function() { $('.contact_option').addClass("hide"); $('#option8').removeClass("hide"); $('.contact_option').find('input,select,textarea,button').attr('tabindex', '-1'); $('#option8').find('input,select,textarea,button').attr('tabindex', '0'); //$('.contact_option').children().attr('tabindex', '-1'); //$('#option8').children().attr('tabindex', '0'); $('#contact_subject').change(function () { $('.contact_option').addClass("hide"); $('#'+$(this).val()).removeClass("hide"); $('.contact_option').find('input,select,textarea,button').attr('tabindex', '-1'); $('#'+$(this).val()).find('input,select,textarea,button').attr('tabindex', '0'); }); });
'use strict' const eventsUtil = require('../utils/events-util') const usersUtil = require('../utils/users') const moment = require('moment') const _ = require('lodash') let renderFns = { memberOks: renderMember, memberIfk: renderMember } function renderMember (user, member) { if (!member) { return null } if (user.isLoggedIn) { return member } return { firstName: member.firstName, lastName: member.lastName } } function updated (event) { return event.updated || null } function format (user, event) { const fields = ['date', 'name', 'host', 'type', 'typeLength', 'memberOks', 'memberIfk'] let fixed = {} fields.forEach(function (field) { let val = event[field] || null let renderFn = renderFns[field] fixed[field] = renderFn ? renderFn(user, val) : val }) return fixed } let eventsController = { get: function (req, res) { eventsUtil.getEventsWithMembers(function (events) { let eventsUpdated = (_.max(events, updated) || {}).updated moment.locale('sv') res.render('events.ejs', { title: 'OK Roxen - Tävlingsansvariga', events: events, page: 'events', user: usersUtil.getCurrentUser(req), eventsUpdated: eventsUpdated && moment(eventsUpdated).format('LLL') || '-' }) }) }, getData: function (req, res) { eventsUtil.getEventsWithMembers(function (events) { events = events || [] res.json({ draw: 1, recordsTotal: events.length, recordsFiltered: events.length, data: events.map(format.bind(null, usersUtil.getCurrentUser(req))) }) }) } } module.exports = eventsController
// @ts-check import * as React from "react"; const { useEffect, useState, useCallback, useRef } = React; import smoothScrollTo from "smooth-scroll-to"; import getOffset, { OffsetType } from "getoffset"; import callfunc from "call-func"; import { doc } from "win-doc"; import { getAnchorPath } from "reshow-url"; import { ScrollReceiver } from "../../index"; import scrollStore from "../../stores/scrollStore"; import fastScrollStore from "../../stores/fastScrollStore"; let scollTimer = null; const resetTimer = () => { if (scollTimer) { clearTimeout(scollTimer); scollTimer = null; } }; /** * @typedef {object} SmoothScrollLinkProps */ /** * @param {SmoothScrollLinkProps} props */ const useSmoothScrollLink = (props) => { const { targetId, scrollRefLoc = "bottom", scrollRefId = "", scrollMargin, style, preventDefault = true, noDelay = false, onClick, ...restProps } = props; /** * @type {[scrollRefElement, setScrollRefElement]} */ const [scrollRefElement, setScrollRefElement] = useState(); /** @type {any} */ const lastScroll = useRef(); /** * @param {number=} duringTime */ const scrollTo = (duringTime) => { const getStore = () => (noDelay ? fastScrollStore : scrollStore); const offset = getStore().scroller.getOffset(targetId); if (offset) { const margin = getMargin(); const to = offset.top - margin; /** * Let user could cancel scroll with different direction. */ if (lastScroll.current === to) { return; } setTimeout(() => (lastScroll.current = to)); smoothScrollTo(to, duringTime, undefined, () => { resetTimer(); scollTimer = setTimeout(() => scrollTo(duringTime), 800); }); } }; useEffect(() => { const dom = doc().getElementById(scrollRefId); if (dom) { setScrollRefElement(dom); } if (getAnchorPath().anchor.substring(1) === targetId) { setTimeout(() => scrollTo(1)); } return () => { resetTimer(); }; }, []); /** * When modify getMargin number, should also take care store isActive logic. * * https://github.com/react-atomic/organism-react-scroll-nav/blob/main/src/stores/scrollStore.js#L119 */ const getMargin = useCallback(() => { let margin = 0; if (scrollRefElement) { const refOffset = /**@type OffsetType*/ (getOffset(scrollRefElement)); switch (scrollRefLoc) { case "bottom": margin += refOffset.bottom - refOffset.top; break; default: case "top": break; } } if (!isNaN(scrollMargin)) { margin += scrollMargin; } margin -= 2; return margin; }, [scrollRefLoc, scrollMargin, scrollRefElement]); const handler = { /** * @param {object} e */ click: (e) => { lastScroll.current = null; if (preventDefault) { e.preventDefault(); } callfunc(onClick); scrollTo(); }, }; return { restProps, handler, targetId, margin: getMargin(), style, }; }; /** * @param {SmoothScrollLinkProps} props */ const SmoothScrollLink = (props) => { const { restProps, handler, margin, style, targetId } = useSmoothScrollLink(props); return ( <ScrollReceiver atom="a" {...restProps} targetId={targetId} scrollMargin={margin} style={{ ...Styles.link, ...style }} onClick={handler.click} /> ); }; export default SmoothScrollLink; const Styles = { link: { cursor: "pointer", }, };
import React from 'react'; import withStore from '~/hocs/withStore'; function delCancel(props) { let {active, cancel, remove} = props; let ICONS = props.stores.icons; let TEXT = props.stores.textsStore; let btn; if (active) { btn = <button className="btn btn-secondary" onClick={() => cancel()} title={TEXT.btn_cancel}>{ICONS.iconCancel}</button>; } else { btn = <button className="btn btn-danger" onClick={() => remove()} title={TEXT.btn_remove}>{ICONS.iconRemove}</button>; } return btn; } export default withStore(delCancel);
import Track from './Track'; import Mixer from './Mixer'; import InputSource from './InputSource'; class Engine { constructor() { console.log('Engine', this); this._updateListeners = []; this._pingListeners = []; this.isReady = false; this.isRecording = false; for(let key of Object.getOwnPropertyNames(Object.getPrototypeOf(this))) { let fn = this[key]; if (typeof fn === 'function') { this[key] = fn.bind(this); } } } onUpdate(callback) { this._updateListeners.push(callback); return () => { const index = this._updateListeners.indexOf(callback); if (index !== -1) { this._updateListeners.splice(index, 1); } else { console.warn('Attempted unbind of unbound onUpdate handler'); } }; } _triggerUpdate() { clearTimeout(this._updateTimeout); const timecode = this.getCurrentTime(); this._updateTimeout = setTimeout(() => { this._updateListeners.forEach((listener) => listener(timecode)); }, 0); } onPing(callback) { this._pingListeners.push(callback); return () => { const index = this._pingListeners.indexOf(callback); if (index !== -1) { this._pingListeners.splice(index, 1); } else { console.warn('Attempted unbind of unbound onPing handler'); } }; } _triggerPing() { clearTimeout(this._pingTimeout); const timecode = this.getCurrentTime(); this._pingListeners.forEach((listener) => listener(timecode)); requestAnimationFrame(this._triggerPing); } async init() { this.context = new AudioContext(); this.tracks = []; this.mixer = new Mixer(this); this.devices = await this.listDevices(); this.isReady = true; this.sources = await this.setupInputSources(); await this.createTracks(this.sources); this._triggerUpdate(); this._triggerPing(); return this; } getCurrentTime() { return this.context.currentTime; } async setupInputSources() { return this.devices.input.map((inputDevice) => this.addInputSource(inputDevice)); } async createTracks(sources) { return await Promise.all(sources.map((source) => this.addTrack(source))); } addInputSource(inputDevice) { const source = new InputSource({ engine: this, device: inputDevice }); source.init(); this._triggerUpdate(); return source; } async listDevices() { const devices = await navigator.mediaDevices.enumerateDevices(); const input = devices.filter((device) => device.kind === 'audioinput'); const output = devices.filter((device) => device.kind === 'audiooutput'); return { input, output, }; } async addTrack(source) { const track = new Track(this); await track.pickSource(source); this.tracks.push(track); this._triggerUpdate(); return track; } startRecording() { this.tracks.forEach((track) => { track.startRecording(); }); this.isRecording = true; this._triggerUpdate(); return this; } stopRecording() { this.tracks.forEach((track) => { track.stopRecording(); }); this.isRecording = false; this._triggerUpdate(); return this; } startPlayback() { console.log('Start playback'); this.tracks.forEach(async (track) => { const buffer = await track.getBuffer(); const bufferSource = this.context.createBufferSource(); bufferSource.buffer = buffer; bufferSource.connect(track.channel.volume); bufferSource.start(this.getCurrentTime()); }) } } export default Engine;
MyControls = function ( object, domElement ) { this.object = object; // this.target = new THREE.Vector3( 0, 10, -50 ); this.domElement = ( domElement !== undefined ) ? domElement : document; this.movementSpeed = 30.0; this.lookSpeed = 0.2; this.mouseX = 0; this.mouseY = 0; this.moveForward = false; this.moveBackward = false; this.moveLeft = false; this.moveRight = false; this.mouse_movement = false; this.mouseDragOn = false; this.viewHalfX = 0; this.viewHalfY = 0; if ( this.domElement !== document ) { this.domElement.setAttribute( 'tabindex', -1 ); } this.handleResize = function () { if ( this.domElement === document ) { this.viewHalfX = window.innerWidth / 2; this.viewHalfY = window.innerHeight / 2; } else { this.viewHalfX = this.domElement.offsetWidth / 2; this.viewHalfY = this.domElement.offsetHeight / 2; } }; this.onMouseMove = function ( event ) { if ( this.domElement === document ) { this.mouseX = event.pageX - this.viewHalfX; this.mouseY = event.pageY - this.viewHalfY; } else { this.mouseX = event.pageX - this.domElement.offsetLeft - this.viewHalfX; this.mouseY = event.pageY - this.domElement.offsetTop - this.viewHalfY; } this.mouse_movement = true; }; this.onKeyDown = function ( event ) { //event.preventDefault(); switch ( event.keyCode ) { case 38: /*up*/ case 87: /*W*/ this.moveForward = true; break; case 37: /*left*/ case 65: /*A*/ this.moveLeft = true; break; case 40: /*down*/ case 83: /*S*/ this.moveBackward = true; break; case 39: /*right*/ case 68: /*D*/ this.moveRight = true; break; } }; this.onKeyUp = function ( event ) { switch( event.keyCode ) { case 38: /*up*/ case 87: /*W*/ this.moveForward = false; break; case 37: /*left*/ case 65: /*A*/ this.moveLeft = false; break; case 40: /*down*/ case 83: /*S*/ this.moveBackward = false; break; case 39: /*right*/ case 68: /*D*/ this.moveRight = false; } }; this.update = function( delta ) { var actualMoveSpeed = delta * this.movementSpeed; if ( this.moveForward ) this.object.position.setZ( this.object.position.z - actualMoveSpeed); if ( this.moveBackward ) this.object.position.setZ( this.object.position.z + actualMoveSpeed ); if ( this.moveLeft ) this.object.position.setX(this.object.position.x - actualMoveSpeed ); if ( this.moveRight ) this.object.position.setX(this.object.position.x + actualMoveSpeed ); if (this.mouse_movement == true) { this.object.rotation.x = Math.max(-this.mouseY / this.viewHalfY, -.6) * this.lookSpeed; this.object.rotation.y = -this.mouseX / this.viewHalfX * this.lookSpeed * 2; this.mouse_movement = false; } }; this.domElement.addEventListener( 'contextmenu', function ( event ) { event.preventDefault(); }, false ); this.domElement.addEventListener( 'mousemove', bind( this, this.onMouseMove ), false ); // this.domElement.addEventListener( 'mousedown', bind( this, this.onMouseDown ), false ); // this.domElement.addEventListener( 'mouseup', bind( this, this.onMouseUp ), false ); window.addEventListener( 'keydown', bind( this, this.onKeyDown ), false ); window.addEventListener( 'keyup', bind( this, this.onKeyUp ), false ); function bind( scope, fn ) { return function () { fn.apply( scope, arguments ); }; }; this.handleResize(); };
import jwt from "jsonwebtoken"; import { LOGIN_USER_START, LOGIN_USER_SUCCESS, LOGIN_USER_FAILURE, LOGOUT_USER, REGISTER_USER_START, REGISTER_USER_SUCCESS, REGISTER_USER_FAILURE, UPDATE_USER_START, UPDATE_USER_SUCCESS, UPDATE_USER_FAILURE, } from "../actions/userActions.js"; export const initState = { currentUser: "", token: localStorage.getItem("token"), userId: localStorage.getItem("token") ? jwt.decode(localStorage.getItem("token")).sub : "", isLoading: false, error: "", newUser: {}, }; export const userReducer = (state = initState, action) => { switch (action.type) { case LOGIN_USER_START: return { ...state, isLoading: true, error: "", }; case LOGIN_USER_SUCCESS: return { ...state, currentUser: action.payload.user, token: action.payload.token, userId: action.userId, isLoading: false, error: "", }; case LOGIN_USER_FAILURE: return { ...state, isLoading: false, error: action.payload, }; case LOGOUT_USER: return { ...state, currentUser: "", token: "", userId: "", }; case REGISTER_USER_START: return { ...state, isLoading: true, error: "", }; case REGISTER_USER_SUCCESS: return { ...state, isLoading: false, error: "", newUser: action.payload, }; case REGISTER_USER_FAILURE: return { ...state, isLoading: false, error: action.payload, }; case UPDATE_USER_START: return { ...state, isLoading: true, error: "", }; case UPDATE_USER_SUCCESS: return { ...state, currentUser: action.payload.user, token: action.payload.token, userId: action.userId, isLoading: false, error: "", }; case UPDATE_USER_FAILURE: return { ...state, isLoading: false, error: action.payload, }; default: return state; } };
const ADD_MESSAGE = "ADD-MESSAGE"; const UPDATE_NEW_MESSAGE_TEXT = "UPDATE-NEW-MESSAGE-TEXT"; const initialState = { dialogs: [ { id: 1, name: "Kirill", avatar: "https://i.pinimg.com/originals/0c/a9/e2/0ca9e28dcb12dc698cfd2beda6d6fa64.jpg", lastMessage: "How are you doing?", timeLastMessage: "12:45 PM", }, { id: 2, name: "Valera", avatar: "https://dthezntil550i.cloudfront.net/kg/latest/kg1802132010216500004834729/1280_960/557d644f-12f3-49e1-bb66-23c16400540d.png", lastMessage: "Hi", timeLastMessage: "12:45 PM", }, { id: 3, name: "Maxim", avatar: "https://pm1.narvii.com/6857/8a2d4a8fe31b643fdc79925b12d36ef3b5d427cfv2_hq.jpg", lastMessage: "YO", timeLastMessage: "12:45 PM", }, ], messages: [ { id: 1, message: "Hi" }, { id: 2, message: "How are you doing?" }, { id: 3, message: "YO" }, ], }; function dialogsReducer(state = initialState, action) { switch (action.type) { case ADD_MESSAGE: const message = { id: state.messages.length + 1, message: action.text, }; return { ...state, messages: [...state.messages, message], newMessageText: "", }; default: return state; } } export function addNewMessage(text) { return { type: ADD_MESSAGE, text }; } export function updateNewMessageTextActionCreator(text) { return { type: UPDATE_NEW_MESSAGE_TEXT, message: text, }; } export default dialogsReducer;
export const splitSkills = skills => skills.split(',').reduce((acc, skill) => { acc.push({ name: skill.trim() }); return acc; }, []);
const aaa = require('./aaa.js'); const addMethod = (a,b) => { return a + b } console.log(addMethod(1,1)) console.log('this is search')
let webpack = require('webpack'); let HtmlWebpackPlugin = require('html-webpack-plugin') let path = require('path') module.exports = function makeWebpackConfig() { /** * Config * Reference: http://webpack.github.io/docs/configuration.html * This is the object where all configuration gets set */ let config = {}; /** * Resolve Path */ config.resolve = { modules: [__dirname, 'node_modules'], extensions: ['.js', '.jsx', '.ts', '.tsx', '.json'] } /** * Entry * Reference: http://webpack.github.io/docs/configuration.html#entry * Should be an empty object if it's generating a test build * Karma will set this when it's a test build */ config.entry = { main: './example/demo.ts' }; /** * Output * Reference: http://webpack.github.io/docs/configuration.html#output * Should be an empty object if it's generating a test build * Karma will handle setting it up for you when it's a test build */ config.output = { // Absolute output directory path: __dirname + '/../dist', // Output path from the view of the page // Uses webpack-dev-server in development publicPath: '/static/', filename: '[name].[hash].js', chunkFilename: '[name].[hash].js', }; /** * Devtool * Reference: http://webpack.github.io/docs/configuration.html#devtool * Type of sourcemap to use per build type */ config.devtool = false /** * Loaders * Reference: http://webpack.github.io/docs/configuration.html#module-loaders * List: http://webpack.github.io/docs/list-of-loaders.html * This handles most of the magic responsible for converting modules */ // Initialize module config.module = { rules: [ { test: /\.tsx?$/, use: [ {loader: 'ts-loader'} ], exclude: [/node_modules/] }, { test: /\.yaml/, use: [ {loader: 'json-loader'}, {loader: 'yaml-loader'} ] } ] } /** * Externals * Reference: https://webpack.github.io/docs/configuration.html#externals * Speed! */ config.externals = {} /** * Plugins * Reference: http://webpack.github.io/docs/configuration.html#plugins * List: http://webpack.github.io/docs/list-of-plugins.html */ config.plugins = []; config.plugins.push( // Reference: https://github.com/ampedandwired/html-webpack-plugin // Render index.html new HtmlWebpackPlugin({ template: './example/index.html', inject: 'body' }) ) return config }
var modal = document.getElementById("settings"); var settingsbtn = document.getElementById("settings-button"); var spans = document.getElementsByTagName("span"); // settingsbtn.onclick = function() { // modal.style.display = "block"; // } // span.onclick = function() { // modal.style.display = "none"; // } // window.onclick = function(event) { // if (event.target == modal) { // modal.style.display = "none"; // } // } // TODOLIST STUFF // selectors const todoInput = document.querySelector('.todo-input'); var ul = document.querySelector("ul"); // var tasksList = new Array(); // chrome.storage.local.get('tasklist', function(val) { // if (val.tasklist.length > 0) { // tasksList = val.list1; // } // for (var i = 0; i < tasksList.length; i++) { // addTodo(tasksList[i]); // } // }) function deleteTodo() { for (let span of spans) { span.addEventListener("click", function (){ span.parentElement.remove(); event.stopPropagation(); }) } } function loadTodo() { if (localStorage.getItem('todoList')) { ul.innerHTML = localStorage.getItem('todoList'); deleteTodo(); } } todoInput.addEventListener("keypress", function(keyPressed){ if (keyPressed.which === 13) { var li = document.createElement("li"); var spanElement = document.createElement("span"); var icon = document.createElement("i"); var newTodo = todoInput.value; todoInput.value = ""; icon.classList.add('fas', 'fa-trash-alt'); spanElement.append(icon); ul.appendChild(li).append(spanElement, newTodo); deleteTodo(); localStorage.setItem('todoList', ul.innerHTML); } }); ul.addEventListener('click', function(ev) { if (ev.target.tagName === 'LI') { ev.target.classList.toggle('checked'); } }, false); deleteTodo(); loadTodo(); // function addTodo(event) { // event.preventDefault(); // // todo DIV // const todoDiv = document.createElement('div'); // todoDiv.classList.add('todo'); // // todo LI // const newTodo = document.createElement('li'); // newTodo.innerText = todoInput.value; // newTodo.classList.add('todo-item'); // todoDiv.appendChild(newTodo); // if (todoInput.value === "") { // return null; // } // // check mark button // const completedButton = document.createElement('button'); // completedButton.innerHTML = '<i class"fas fa-check"></i>'; // completedButton.classList.add('complete_btn'); // todoDiv.appendChild(completedButton); // // append to list // todoList.appendChild(todoDiv); // // clear todo input value // todoInput.value = ''; // chrome.storage.local.set({ // 'tasklist': tasksList // }) // } // function deleteCheck(e) { // const item = e.target; // // delete item // if (item.classList[0] === "complete_btn") { // const todo = item.parentElement; // todo.classList.add("fall") // todo.addEventListener('transitionend', function () { // todo.remove(); // }) // } // }
// todo remove suppression on multiple exports export const EN_SYMETRIC_WORD = 'symmetrical'; export const TRI_COORD_A = [{ x: 2, y: 13 }]; export const TRI_COORD_B = [{ x: 5, y: 12 }]; export const TRI_COORD_C = [{ x: 3, y: 10 }]; export const TRI_COORD_A_PRIM = [{ x: 10, y: 5 }]; export const TRI_COORD_B_PRIM = [{ x: 7, y: 6 }]; export const TRI_COORD_C_PRIM = [{ x: 9, y: 8 }]; export const SQ_COORD_A = [{ x: 1, y: 12 }]; export const SQ_COORD_B = [{ x: 1, y: 8 }]; export const SQ_COORD_C = [{ x: 5, y: 8 }]; export const SQ_COORD_D = [{ x: 5, y: 12 }]; export const SQ_COORD_A_PRIM = [{ x: 11, y: 12 }]; export const SQ_COORD_B_PRIM = [{ x: 11, y: 8 }]; export const SQ_COORD_C_PRIM = [{ x: 15, y: 8 }]; export const SQ_COORD_D_PRIM = [{ x: 15, y: 12 }]; export const POLY_COORD_A = [{ x: 9, y: 13 }]; export const POLY_COORD_B = [{ x: 12, y: 11 }]; export const POLY_COORD_C = [{ x: 11, y: 7.5 }]; export const POLY_COORD_D = [{ x: 7, y: 7.5 }]; export const POLY_COORD_E = [{ x: 6, y: 11 }];
//Shuffle function- I don't really understand whats happening here function shuffle(arra1) { var ctr = arra1.length, temp, index; // While there are elements in the array while (ctr > 0) { // Pick a random index index = Math.floor(Math.random() * ctr); // Decrease ctr by 1 ctr--; // And swap the last element with it temp = arra1[ctr]; arra1[ctr] = arra1[index]; arra1[index] = temp; } return arra1; } var companyNames = ["Uber", "Netflix", "Postmates", "Tinder", "Dropbox", "Spotify"] var animals = ["cats", "hamsters", "dogs", "snakes", "bees", "wombats"] shuffle(companyNames) for (var i=0; i < animals.length; i++){ console.log("My company is like " + companyNames[i] + " for " + animals[i]) } $( ".company-pitch" ).append( "<p>" + "My company is like " + companyNames[0] + " for " + animals[3] + "</p>" );
export { default } from './MonikimmersContainer';
export default `'Open Sans', 'Helvetica Neue', Helvetica, 'Segoe UI', Arial, sans-serif` export const primarySize = '32px' export const primaryWeight = 200 export const secondarySize = '14px' export const secondaryWeight = 600
import React from 'react'; import { withUrqlClient } from 'next-urql'; // https://nextjs.org/docs/advanced-features/custom-app function MyApp({ Component, pageProps }) { return <Component {...pageProps} /> } const url = 'http://localhost:4001/graphql'; // https://formidable.com/open-source/urql/docs/advanced/server-side-rendering/#nextjs export default withUrqlClient((_ssrExchange, ctx) => ({ // ...add your Client options here url }), { ssr: true })(MyApp);
(function () { 'use strict'; angular.module('app').controller('indexCtrl', func); func.$inject = ['$scope', '$state', '$rootScope']; function func($scope, $state, $rootScope) { console.info('这是index页面'); $rootScope.goHomePage = function () { $state.go('home'); } } })();
import { ADD_TODO, LOAD_TODO, EDIT_TODO, REMOVE_TODO, UPDATE_FILTER } from '../../actions/typeTodo' const INITIAL_STATE = { all: [], todoFiltered: [], filter: 0 } const handlerTodos = (state = INITIAL_STATE, action) => { switch(action.type) { case ADD_TODO: return addTodo(state, action) case LOAD_TODO: return loadTodo(state, action) case EDIT_TODO: return editTodo(state, action) case REMOVE_TODO: return removeTodo(state, action) case UPDATE_FILTER: return updateFilter(state, action) default: return { ...state } } } const addTodo = (state, action) => { const all = [ ...state.all, action.payload ] let todoFiltered if (!state.filter) { todoFiltered = [ ...all ] } else if (state.filter === 1) { todoFiltered = [...state.all.filter(todo => !todo.completed)] } else { todoFiltered = [...state.all.filter(todo => todo.completed)] } return { ...state, all, todoFiltered } } const loadTodo = (state, action) => { const todos = [...action.payload] return { ...state, all: todos, todoFiltered: todos, filter: 0 } } const editTodo = (state, action) => { const mState = { ...state } const index = mState.all.map(todo => todo.id).indexOf(action.payload.id) if (index !== -1) { mState.all[index] = action.payload } let todoFiltered if (!mState.filter) { todoFiltered = [ ...mState.all ] } else if (mState.filter === 1) { todoFiltered = [...mState.all.filter(todo => !todo.completed)] } else { todoFiltered = [...mState.all.filter(todo => todo.completed)] } return { ...mState, todoFiltered, all: [...mState.all] } } const updateFilter = (state, action) => { const filter = action.payload let todoFiltered if (!filter) { todoFiltered = [ ...state.all ] } else if (filter === 1) { todoFiltered = [ ...state.all.filter(todo => !todo.completed) ] } else { todoFiltered = [ ...state.all.filter(todo => todo.completed) ] } return { ...state, todoFiltered, filter } } const removeTodo = (state, action) => { const callback = todo => todo.id !== action.payload.id return { ...state, all: [...state.all.filter(callback)], todoFiltered: [...state.todoFiltered.filter(callback)] } } export default handlerTodos
'use strict'; var app = angular.module('routerApp', ['ui.router', 'oitozero.ngSweetAlert']); app.config(function($stateProvider, $urlRouterProvider) { $stateProvider .state('home', { url: '/', templateUrl: '/html/home.html', controller: 'homeCtrl' }) .state('about', { url: '/about', templateUrl: '/html/about.html', controller: 'aboutCtrl' }) .state('list', { url: '/list/:num', templateUrl: '/html/list.html', controller: 'listCtrl', resolve: { pageObj: function(People, $stateParams) { // return a promise which will resolve to the pageObj console.log('$stateParams.num in list: ', $stateParams.num ); return People.getByPage($stateParams.num); } } }) .state('detail', { url: '/detail/:id', templateUrl: '/html/detail.html', controller: 'detailCtrl', resolve: { person: function(People, $stateParams) { console.log('$stateParams in detail: ', $stateParams); var res = People.getById($stateParams.id); console.log('getById', res ); return res; } } }) $urlRouterProvider.otherwise('/'); });
import React from "react"; import { Card, Image, Segment, Grid } from "semantic-ui-react"; import { UserConsumer, } from "./UserProvider"; const User = () => ( <UserConsumer> {value => { return ( <Segment> <Grid columns={2}> <Grid.Row> <Grid.Column> <Card> <Image src={value.avatar} /> </Card> </Grid.Column> <Grid.Column> <Card> <Card.Content> <Card.Header>Name</Card.Header> <Card.Meta> {value.f_Name}{value.l_Name} </Card.Meta> </Card.Content> <Card.Content> <p>Email: {value.email}</p> </Card.Content> <Card.Content> <p>Phone: {value.phone}</p> </Card.Content> </Card> </Grid.Column> </Grid.Row> </Grid> </Segment> ) }} </UserConsumer > ) export default User;
import './index.css' const EachSearchItem = props => { const {eachObje, deleteClickedOne} = props const {timeAccessed, id, logoUrl, title, domainUrl} = eachObje const itemDeleted = () => { console.log(id) deleteClickedOne(id) } return ( <li className="eachListItem"> <div className="logoContent"> <p className="time">{timeAccessed}</p> <div className="logoWesiteTitle"> <img src={logoUrl} alt="domain logo" className="logo" /> <p className="title">{title}</p> <p className="domineUrl">{domainUrl}</p> </div> </div> <button type="button" onClick={itemDeleted} testid="delete" className="deleteBtn" > <img src="https://assets.ccbp.in/frontend/react-js/delete-img.png" alt="delete" className="deleteIcon" /> </button> </li> ) } export default EachSearchItem
import React from 'react'; const MyPage = ({ AuthState, PostState }) => { console.log(AuthState, PostState); return ( <div> 내가 쓴 글을 보고 수정할 수 있습니다. </div> ); }; export default MyPage;
import { Toast } from "native-base"; export const error = msg => { Toast.show({ text: msg, position: "center", duration: 400 }); };
export const AUTH_SERVER_URL = 'http://localhost:8887'; export const API_SERVER_URL = 'http://localhost:3050/api';
/** * Copyright (c) 2017 Laura Taylor (https://github.com/techstreams) * * 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'; // Configuration - Cloud Functions const functions = require('firebase-functions') // Configuration - Express const express = require('express') const app = express() // Configuration - Markdown Parser const marked = require('marked') const highlightjs = require('highlight.js') // Request Method Validation Middleware const allowMethods = (req, res, next) => { const methods = ['POST'] if (methods.indexOf(req.method.toUpperCase()) === -1) { res.header('Allow', methods.join(', ')) res.status(405).send('Request Method Not Allowed') return } next() } // Required Fields Middleware const requiredFields = (req, res, next) => { const validActions = ['RENDER', 'LEX'] if (!req.is('application/json')) { res.status(400).send('Invalid Content-Type') return } else if (!req.body.content) { res.status(400).send('No Content') return } else if (!req.body.action || validActions.indexOf(req.body.action.toUpperCase()) === -1) { res.status(400).send('Invalid Action') return } else { next() } } // Set marked parser options const setMarkedOptions = (options) => { const highlighter = (code) => { return highlightjs.highlightAuto(code).value } marked.setOptions({ gfm: options.gfm ? options.gfm : true, tables: options.tables ? options.tables : true, breaks: options.breaks ? options.breaks : false, pedantic: options.pedantic ? options.pedantic : false, sanitize: options.sanitize ? options.sanitize : false, smartLists: options.smartLists ? options.smartLists : true, smartypants: options.smartypants ? options.smartypants : false, highlight: options.highlight ? highlighter : null }) } // Use Middleware app.use(allowMethods) app.use(requiredFields) // Handle Post Request app.post('/', (req, res) => { try { if (req.body.options) { setMarkedOptions(req.body.options) } if (req.body.action.toUpperCase() === 'RENDER') { res.status(200).send(marked(req.body.content)) } else if (req.body.action.toUpperCase() === 'LEX') { res.status(200).send(marked.lexer(req.body.content)) } else { throw new Error('Invalid Action') } } catch(err) { res.status(500).send(`Error Rendering Markdown: ${err.message}`) } }) // Send a 400 for non-matching post requests app.post('*', (req, res) => { res.status(400).send('Bad Request') }) // Export Function exports.markdown = functions.https.onRequest(app)
import React, { Component } from 'react'; import { Upload, Button, Icon, message, Row } from 'antd'; import PropTypes from 'prop-types'; import { connect } from 'dva'; import { isEqual } from 'lodash'; import { Upload_Response, Upload_Request, Upload_Model, InsertFile_Response, InsertFile_Request, InsertFile_Model } from '@/DTO'; import { file } from '@babel/types'; const Dragger = Upload.Dragger; @connect(({ FileManager }) => ({ Upload_Response: FileManager.Upload_Response, InsertFile_Response: FileManager.InsertFile_Response })) class UploadMedia extends Component { static propTypes = { Upload_Response: PropTypes.object, InsertFile_Response: PropTypes.object.isRequired, ParentId: PropTypes.number, onUploaded: PropTypes.func.isRequired }; static defaultProps = { Upload_Response: new Upload_Response(), InsertFile_Response: new InsertFile_Response(), onUploaded: () => { } }; constructor(props) { super(props); this.__isMounted = false; this.isLoading = false; this.state = { file: null, fileList: [], uploading: false, }; } shouldComponentUpdate = (nextProps) => { const { InsertFile_Response } = this.props; if (isEqual(InsertFile_Response.Result, nextProps.InsertFile_Response.Result)) { this.props.onUploaded instanceof Function && this.props.onUploaded(nextProps.InsertFile_Response.Success === 1); return false; } else { this.setState({ uploading: false }); return true; } }; handleUpload = (info) => { const { fileList } = this.state; const { dispatch } = this.props; var formdata = new FormData(); formdata.append("user_id", '612'); formdata.append("brand", '1'); formdata.append("media", info.file); dispatch({ type: 'FileManager/uploadMedia', payload: { formdata: formdata, ParentId: this.props.ParentId }, }); }; beforeUpload = (file) => { this.setState(state => ({ fileList: [...state.fileList, file], uploading: true })); }; render() { const { uploading, fileList } = this.state; const uploadConfig = { accept: '.doc, .docx, .docm, .dotx, .dotm, .docb, .xls, .xlsb, .xlsm, .xlsx, .sldx, .pptx, .pptm, .potx, .potm, .ppam, .ppsx, .ppsm, .png, .jpg, .jpeg, .txt, .pdf', multiple: true, fileList, beforeUpload: this.beforeUpload, customRequest: this.handleUpload } return ( <Row> <Dragger {...uploadConfig}> <p className="ant-upload-drag-icon"> <Icon type="inbox" /> </p> <p className="ant-upload-text">Click or drag file to this area to upload</p> </Dragger> {/* <Upload {...uploadConfig}> <Button> <Icon type="upload" /> Select File </Button> </Upload> */} <Button type="primary" onClick={this.handleUpload} disabled={fileList.length === 0} loading={uploading} style={{ marginTop: 16 }} > {uploading ? 'Uploading' : 'Start Upload'} </Button> </Row> ); } } export default UploadMedia;
import React from 'react' export default function Recipe() { console.log("This is Recipe") return ( <div> Hello World </div> ) }
import React from 'react'; import {BrowserRouter as Router, Switch,Route} from 'react-router-dom'; import Login from './components/auth/Login'; import VistaCliente from './components/usuario/VistaCliente'; import ClienteState from './context/cliente/clienteState'; import MedicoState from './context/medico/medicoState'; import NuevaCuenta from './components/auth/NuevaCuenta'; import AuthState from './context/autenticacion/authState'; import tokenAuth from './config/tokenAuth'; import RutaPrivada from './components/rutas/RutaPrivada'; function App() { //Revisamos si tenemos un token const token = localStorage.getItem('token') if(token){ tokenAuth(token); } return ( <MedicoState> <ClienteState> <AuthState> <Router> <Switch> <RutaPrivada exact path="/Agenda" component={VistaCliente}/> <Route exact path="/" component={Login}/> <Route exact path="/Registro" component={NuevaCuenta}/> </Switch> </Router> </AuthState> </ClienteState> </MedicoState> ); } export default App;
function authInterceptor(JWT, AppConstants, $window, $q) { 'ngInject'; return { // Attach authorization header automatically to every request that hits the API url request: function(req) { if (req.url.indexOf(AppConstants.api) === 0 && JWT.get()) { req.headers.authorization = 'Token ' + JWT.get(); } return req; }, // On validation failure, destroy any existing token and do a hard refresh responseError: function(rejection) { if (rejection.status === 401) { JWT.destroy(); $window.location.reload(); } return $q.reject(rejection); } } } export default authInterceptor;
import { on, off } from 'element-ui/src/utils/dom'; export default { name: 'ElAffix', props: { offsetTop: { type: Number }, offsetBottom: { type: Number }, useCapture: { type: Boolean, default: false }, target: { type: Function, default: () => window } }, data() { return { styles: {}, affix: false, slot: false, slotStyle: {} }; }, computed: { el() { return this.target(); } }, render(h) { return h('div', [ h('div', { class: this.affix ? 'el-affix' : '', style: this.styles }, [this.$slots.default]), this.affix ? h('div', { style: this.slotStyle }) : '' ]); }, mounted() { on(window, 'resize', this.handleScroll, this.useCapture); if (Array.isArray(this.el)) { for (let i = 0; i < this.el.length; i++) { on(this.el[i], 'scroll', this.handleScroll, this.useCapture); } } else { on(this.el, 'scroll', this.handleScroll, this.useCapture); } this.$nextTick(() => { this.handleScroll(); }); }, beforeDestroy() { off(window, 'resize', this.handleScroll, this.useCapture); if (Array.isArray(this.el)) { for (let i = 0; i < this.el.length; i++) { off(this.el[i], 'scroll', this.handleScroll, this.useCapture); } } else { off(this.el, 'scroll', this.handleScroll, this.useCapture); } }, methods: { handleScroll() { if (!this.el || !this.$el) { return; } const offsetTop = this.getOffsetTop(); const offsetBottom = this.getOffsetBottom(); const rect = this.$el.getBoundingClientRect(); const targetRect = this.getTargetRect(this.el); const fixedTop = this.getFixedTop(rect, targetRect, offsetTop); const fixedBottom = this.getFixedBottom(rect, targetRect, offsetBottom); if (fixedTop === undefined && fixedBottom === undefined) { if (this.affix) { this.slot = false; this.slotStyle = {}; this.affix = false; this.styles = null; this.$emit('change', false); } return; } if (fixedTop !== undefined) { // Fixed Top if ((this.affix && this.styles.top !== `${fixedTop}px`) || !this.affix) { this.slotStyle = { width: rect.width + 'px', height: rect.height + 'px' }; this.styles = { position: 'fixed', top: `${fixedTop}px`, width: rect.width + 'px', height: rect.height + 'px' }; } } else if (fixedBottom !== undefined) { // Fixed Bottom if ((this.affix && this.styles.bottom !== `${fixedBottom}px`) || !this.affix) { this.slotStyle = { width: rect.width + 'px', height: rect.height + 'px' }; this.styles = { position: 'fixed', bottom: `${fixedBottom}px`, width: rect.width + 'px', height: rect.height + 'px' }; } } if (!this.affix) { this.slot = true; this.affix = true; this.$emit('change', true); } }, getTargetRect(target) { return target !== window ? target.getBoundingClientRect() : ({ top: 0, bottom: target.innerHeight, left: 0 }); }, getOffsetTop() { return this.offsetBottom === undefined && this.offsetTop === undefined ? 0 : this.offsetTop; }, getOffsetBottom() { return this.offsetBottom; }, getFixedTop(rect, targetRect, offsetTop) { if (offsetTop !== undefined && targetRect.top > rect.top - offsetTop) { return offsetTop + targetRect.top; } return undefined; }, getFixedBottom(rect, targetRect, offsetBottom) { if (offsetBottom !== undefined && targetRect.bottom < rect.bottom + offsetBottom) { const targetBottomOffset = window.innerHeight - targetRect.bottom; return offsetBottom + targetBottomOffset; } return undefined; } } };
import s from '../../components/ProductTabs/ProductTabs.module.scss'; export const ProductTabs = () => { return ( <div className={s.tabs}> <button className={s.tabsLink}>запчасти</button> <button className={s.tabsLink}>моторы</button> <button className={s.tabsLink}>шины</button> <button className={s.tabsLink}>электроника</button> <button className={s.tabsLink}>инструменты</button> <button className={s.tabsLink}>аксессуары</button> </div> ); };
module.exports = { home: (req,res) => { res.send('hello world'); } }
var PORT = 3001; var http = require('http'); var qs = require('qs'); var TOKEN = 'jiangye'; function checkSignature(params, token){ //1.将token密钥、timestamp时间戳、 nonce随机数三个参数进行字典序排序 //2.将三个参数字符串拼接成一个字符串进行sha1加密 //3.开发者获得加密后的字符串可与signature对比,标识该请求来源于微信 var key = [token, params.timestamp, params.nonce].sort().join(''); var sha1 = require('crypto').createHash('sha1'); sha1.update(key); return sha1.digest('hex') == params.signature; } var server = http.createServer(function (request , response) { //解析URL中的query部分,用qs模板(npm install qs)将query解析成json var query = require('url').parse(request.url).query; var params = qs.parse(query); console.log(params); console.log("token-->", TOKEN); if(checkSignature(params, TOKEN)){ response.end(params.echostr); }else{ response.end('signature fail'); } }); server.listen(PORT); console.log("Server running at port: " + PORT + ".");
/** * Auth */ export const DEVICE_TOKEN = 'DEVICE_TOKEN'; export const USER_AUTH_START = 'USER_AUTH_START'; export const USER_AUTH = 'USER_AUTH'; export const USER_AUTH_SUCCESS = 'USER_AUTH_SUCCESS'; export const USER_AUTH_FAILURE = 'USER_AUTH_FAILURE'; export const USER_AUTH_MID = 'USER_AUTH_MID'; export const USER_AUTH_ALERT_SHOW_HIDE_DANGER = 'USER_AUTH_ALERT_SHOW_HIDE_DANGER'; export const USER_AUTH_ALERT_SHOW_HIDE_DANGER_DISMISS = 'USER_AUTH_ALERT_SHOW_HIDE_DANGER_DISMISS'; export const SWITCH_TO_OTP = 'SWITCH_TO_OTP'; export const SIGNIN_START = 'SIGNIN_START'; export const SIGNIN = 'SIGNIN'; export const SIGNIN_SUCCESS = 'SIGNIN_SUCCESS'; export const SIGNIN_FAILURE = 'SIGNIN_FAILURE'; export const SIGNIN_MID = 'SIGNIN_MID'; export const SIGNIN_ALERT_SHOW_HIDE_DANGER = 'SIGNIN_ALERT_SHOW_HIDE_DANGER'; export const SIGNIN_ALERT_SHOW_HIDE_DANGER_DISMISS = 'SIGNIN_ALERT_SHOW_HIDE_DANGER_DISMISS'; export const SET_GROUP = 'SET_GROUP'; export const SIGNUP_START = 'SIGNUP_START'; export const SIGNUP = 'SIGNUP'; export const SIGNUP_SUCCESS = 'SIGNUP_SUCCESS'; export const SIGNUP_FAILURE = 'SIGNUP_FAILURE'; export const SIGNUP_MID = 'SIGNUP_MID'; export const SIGNUP_ALERT_SHOW_HIDE_DANGER = 'SIGNUP_ALERT_SHOW_HIDE_DANGER'; export const SIGNUP_ALERT_SHOW_HIDE_DANGER_DISMISS = 'SIGNUP_ALERT_SHOW_HIDE_DANGER_DISMISS'; export const VERIFY_OTP_START = 'VERIFY_OTP_START'; export const VERIFY_OTP = 'VERIFY_OTP'; export const VERIFY_OTP_SUCCESS = 'VERIFY_OTP_SUCCESS'; export const VERIFY_OTP_FAILURE = 'VERIFY_OTP_FAILURE'; export const VERIFY_OTP_MID = 'VERIFY_OTP_MID'; export const VERIFY_OTP_ALERT_SHOW_HIDE_DANGER = 'VERIFY_OTP_ALERT_SHOW_HIDE_DANGER'; export const VERIFY_OTP_ALERT_SHOW_HIDE_DANGER_DISMISS = 'VERIFY_OTP_ALERT_SHOW_HIDE_DANGER_DISMISS'; export const RESEND_OTP_START = 'RESEND_OTP_START'; export const RESEND_OTP = 'RESEND_OTP'; export const RESEND_OTP_SUCCESS = 'RESEND_OTP_SUCCESS'; export const RESEND_OTP_FAILURE = 'RESEND_OTP_FAILURE'; export const RESEND_OTP_MID = 'RESEND_OTP_MID'; export const RESEND_OTP_ALERT_SHOW_HIDE_DANGER = 'RESEND_OTP_ALERT_SHOW_HIDE_DANGER'; export const RESEND_OTP_ALERT_SHOW_HIDE_DANGER_DISMISS = 'RESEND_OTP_ALERT_SHOW_HIDE_DANGER_DISMISS'; export const FORGOT_PASSWORD_START = 'FORGOT_PASSWORD_START'; export const FORGOT_PASSWORD = 'FORGOT_PASSWORD'; export const FORGOT_PASSWORD_SUCCESS = 'FORGOT_PASSWORD_SUCCESS'; export const FORGOT_PASSWORD_FAILURE = 'FORGOT_PASSWORD_FAILURE'; export const FORGOT_PASSWORD_MID = 'FORGOT_PASSWORD_MID'; export const FORGOT_PASSWORD_ALERT_SHOW_HIDE_DANGER = 'FORGOT_PASSWORD_ALERT_SHOW_HIDE_DANGER'; export const FORGOT_PASSWORD_ALERT_SHOW_HIDE_DANGER_DISMISS = 'FORGOT_PASSWORD_ALERT_SHOW_HIDE_DANGER_DISMISS'; export const RESET_PASSWORD_START = 'RESET_PASSWORD_START'; export const RESET_PASSWORD = 'RESET_PASSWORD'; export const RESET_PASSWORD_SUCCESS = 'RESET_PASSWORD_SUCCESS'; export const RESET_PASSWORD_FAILURE = 'RESET_PASSWORD_FAILURE'; export const RESET_PASSWORD_MID = 'RESET_PASSWORD_MID'; export const RESET_PASSWORD_ALERT_SHOW_HIDE_DANGER = 'RESET_PASSWORD_ALERT_SHOW_HIDE_DANGER'; export const RESET_PASSWORD_ALERT_SHOW_HIDE_DANGER_DISMISS = 'RESET_PASSWORD_ALERT_SHOW_HIDE_DANGER_DISMISS'; export const LOGOUT_START = 'LOGOUT_START'; export const LOGOUT = 'LOGOUT'; export const LOGOUT_SUCCESS = 'LOGOUT_SUCCESS'; export const LOGOUT_FAILURE = 'LOGOUT_FAILURE'; export const LOGOUT_MID = 'LOGOUT_MID'; export const LOGOUT_ALERT_SHOW_HIDE_DANGER = 'LOGOUT_ALERT_SHOW_HIDE_DANGER'; export const LOGOUT_ALERT_SHOW_HIDE_DANGER_DISMISS = 'LOGOUT_ALERT_SHOW_HIDE_DANGER_DISMISS'; export const CHANGE_HOME_STATE = 'CHANGE_HOME_STATE'; export const CHANGE_PASSWORD = 'CHANGE_PASSWORD'; export const CREATE_SUBSCRIPTION_PLAN = 'CREATE_SUBSCRIPTION_PLAN'; export const RESET_ERROR_CREATE_SUBSCRIPTION = 'RESET_ERROR_CREATE_SUBSCRIPTION'; export const CREATE_BANK_ACCOUNT = 'CREATE_BANK_ACCOUNT'; export const SAVE_BANK_ACCOUNT = 'SAVE_BANK_ACCOUNT'; export const ERROR_CREATE_BANK_ACCOUNT = 'ERROR_CREATE_BANK_ACCOUNT'; export const SET_LOADER = 'SET_LOADER'; export const SET_MESSAGE = 'SET_MESSAGE'; export const GET_BANK_DETAILS = 'GET_BANK_DETAILS'; /** * Account */ export const UPDATE_NAME = 'UPDATE_NAME'; export const SET_UPDATED_NAME = 'SET_UPDATED_NAME'; export const UPDATE_EMAIL = 'UPDATE_EMAIL'; export const SET_UPDATED_EMAIL = 'SET_UPDATED_EMAIL'; export const UPDATE_PROFILE_IMAGE = 'UPDATE_PROFILE_IMAGE'; export const SET_UPDATED_PROFILE_IMAGE = 'SET_UPDATED_PROFILE_IMAGE'; export const GET_ANALYST_DETAILS = 'GET_ANALYST_DETAILS'; export const SET_ANALYST_DETAILS = 'SET_ANALYST_DETAILS'; export const GET_SUBSCRIPTION_PLAN_LIST = 'GET_SUBSCRIPTION_PLAN_LIST'; export const SET_SUBSCRIPTION_PLAN_LIST = 'SET_SUBSCRIPTION_PLAN_LIST'; export const GET_TRADE_LIST = 'GET_TRADE_LIST'; export const SET_TRADE_LIST = 'SET_TRADE_LIST'; export const DELETE_SUBSCRIPTION_PLAN = 'DELETE_SUBSCRIPTION_PLAN'; export const CANCEL_TRADE = 'CANCEL_TRADE'; export const SET_TRADE_ITEM = 'SET_TRADE_ITEM'; export const GET_PROFILE_IMAGE = 'GET_PROFILE_IMAGE'; export const DOCUMENT_UPDATED = 'DOCUMENT_UPDATED'; export const GET_TRADE_COUNTS = 'GET_TRADE_COUNTS'; export const SET_TRADE_COUNTS = 'SET_TRADE_COUNTS'; export const GET_FEED = 'GET_FEED'; export const SET_FEED = 'SET_FEED'; export const GET_SUB_FEED = 'GET_SUB_FEED'; export const SET_SUB_FEED = 'SET_SUB_FEED'; export const GET_FEED_IMAGES = 'GET_FEED_IMAGES'; export const SET_FEED_IMAGES = 'SET_FEED_IMAGES'; export const GET_COMMENTS = 'GET_COMMENTS'; export const SET_COMMENTS = 'SET_COMMENTS'; export const POST_COMMENT = 'POST_COMMENT'; export const GET_SUBSCRIPTION = 'GET_SUBSCRIPTION'; export const SET_SUBSCRIPTION = 'SET_SUBSCRIPTION'; export const GET_PREFERENCES = 'GET_PREFERENCES'; export const GET_PREFERENCES_SUCCESS = 'GET_PREFERENCES_SUCCESS'; export const SET_PREFERENCES = 'SET_PREFERENCES'; export const SET_PREFERENCES_SUCCESS = 'SET_PREFERENCES_SUCCESS'; export const GET_RISK_PROFILE_QUESTIONS = 'GET_RISK_PROFILE_QUESTIONS'; export const GET_RISK_PROFILE_QUESTIONS_SUCCESS = 'GET_RISK_PROFILE_QUESTIONS_SUCCESS'; export const SEND_RISK_PROFILE_ANSWERS = 'SEND_RISK_PROFILE_ANSWERS'; export const SEND_RISK_PROFILE_ANSWERS_SUCCESS = 'SEND_RISK_PROFILE_ANSWERS_SUCCESS'; export const GET_RISK_PROFILING_SCORE_SUCCESS = 'GET_RISK_PROFILING_SCORE_SUCCESS'; export const UPDATE_DEMAT_ACCOUNTS = 'UPDATE_DEMAT_ACCOUNTS'; export const SET_DEMAT_ACCOUNTS = 'SET_DEMAT_ACCOUNTS'; export const SET_UPDATED_DEMAT_ACCOUNTS = 'SET_UPDATED_DEMAT_ACCOUNTS'; /** * Place trade */ export const PLACE_TRADE = 'PLACE_TRADE'; export const GET_AVAILABLE_TRADE_BALANCE = 'GET_AVAILABLE_TRADE_BALANCE'; export const SET_AVAILABLE_TRADE_BALANCE = 'SET_AVAILABLE_TRADE_BALANCE'; export const FETCH_INSTRUMENT_TOKENS = 'FETCH_INSTRUMENT_TOKENS'; export const SAVE_INSTRUMENT_TOKENS = 'SAVE_INSTRUMENT_TOKENS'; export const CLEAR_INSTRUMENT_TOKENS = 'CLEAR_INSTRUMENT_TOKENS'; /** * Upload Document */ export const UPLOAD_DOCUMENT = 'UPLOAD_DOCUMENT'; /** * Analyst update */ export const UPDATE_ANALYST_BASIC_DETAILS = 'UPDATE_ANALYST_BASIC_DETAILS'; export const GET_ANALYST_FOLLOWERS = 'GET_ANALYST_FOLLOWERS'; export const SET_ANALYST_FOLLOWERS = 'SET_ANALYST_FOLLOWERS'; export const GET_ANALYST_SUBSCRIBERS = 'GET_ANALYST_SUBSCRIBERS'; export const SET_ANALYST_SUBSCRIBERS = 'SET_ANALYST_SUBSCRIBERS'; /** * Analyst Portfolio */ export const CREATE_ANALYST_PORTFOLIO = 'CREATE_ANALYST_PORTFOLIO'; export const SET_ANALYST_PORTFOLIO = 'SET_ANALYST_PORTFOLIO'; export const GET_ANALYST_PORTFOLIO = 'GET_ANALYST_PORTFOLIO'; /** * ********************************** GET WEBINAR LIST ****************************************** */ export const GET_WEBINAR_LIST = 'GET_WEBINAR_LIST'; export const SAVE_WEBINAR_LIST = 'SAVE_WEBINAR_LIST'; /** * ********************************** USER ACTIONS ****************************************** */ export const FETCH_ANALYSTS_FOR_SUBSCRIPTION = 'FETCH_ANALYSTS_FOR_SUBSCRIPTION'; export const SAVE_ANALYSTS_FOR_SUBSCRIPTION = 'SAVE_ANALYSTS_FOR_SUBSCRIPTION'; export const APPLY_ANALYST_BROWSE_FILTER = 'APPLY_ANALYST_BROWSE_FILTER'; export const SET_ANALYST_BROWSE_LIST = 'SET_ANALYST_BROWSE_LIST'; export const SET_FILTER_VALUES = 'SET_FILTER_VALUES'; export const FETCH_PERFORMANCE_AND_TRANSACTIONS_DATA = 'FETCH_PERFORMANCE_AND_TRANSACTIONS_DATA'; export const SAVE_PERFORMANCE_AND_TRANSACTIONS_DATA = 'SAVE_PERFORMANCE_AND_TRANSACTIONS_DATA'; export const FETCH_USER_CARDS = 'FETCH_USER_CARDS'; export const SAVE_USER_CARDS = 'SAVE_USER_CARDS'; export const FETCH_ALL_WEBINARS = 'FETCH_ALL_WEBINARS'; export const SAVE_ALL_WEBINARS = 'SAVE_ALL_WEBINARS'; export const GET_ANALYST_SUBSCRIPTION_PLAN = 'GET_ANALYST_SUBSCRIPTION_PLAN'; export const SET_ANALYST_SUBSCRIPTION_PLAN = 'SET_ANALYST_SUBSCRIPTION_PLAN'; export const GET_PAYMENT_SUBSCRIPTION_LINK = 'GET_PAYMENT_SUBSCRIPTION_LINK'; export const SET_PAYMENT_SUBSCRIPTION_LINK = 'SET_PAYMENT_SUBSCRIPTION_LINK'; export const GET_RECENTLY_CLOSED_TRADES = 'GET_RECENTLY_CLOSED_TRADES'; export const SET_RECENTLY_CLOSED_TRADES = 'SET_RECENTLY_CLOSED_TRADES'; export const SET_USER_INFO = 'SET_USER_INFO'; export const SET_KYC_DETAILS = 'SET_KYC_DETAILS'; export const SET_KYC_DETAILS_SUCCESS = 'SET_KYC_DETAILS_SUCCESS'; export const SET_ANALYST_MESSAGE = 'SET_ANALYST_MESSAGE'; export const GET_REFERRAL_CODE = 'GET_REFERRAL_CODE'; export const SET_REFERRAL_CODE = 'SET_REFERRAL_CODE'; export const CHECK_REFERRAL_CODE = 'CHECK_REFERRAL_CODE'; export const GET_REFERRED_BY = 'GET_REFERRED_BY'; export const GET_BLOG_LIST = 'GET_BLOG_LIST'; export const SET_BLOG_LIST = 'SET_BLOG_LIST'; export const GET_BLOG_LIST_DESKTOP = 'GET_BLOG_LIST_DESKTOP'; export const SET_BLOG_LIST_DESKTOP = 'SET_BLOG_LIST_DESKTOP'; export const GET_BLOG_DETAIL = 'GET_BLOG_DETAIL'; export const SET_BLOG_DETAIL = 'SET_BLOG_DETAIL'; export const GET_BLOG_COMMENTS = 'GET_BLOG_COMMENTS'; export const SET_BLOG_COMMENTS = 'SET_BLOG_COMMENTS'; export const SEND_BLOG_COMMENT = 'SEND_BLOG_COMMENT'; // follow and feed export const FOLLOW = 'FOLLOW'; export const UNFOLLOW = 'UNFOLLOW'; export const LIKE = 'LIKE'; export const UNLIKE = 'UNLIKE'; export const TOGGLE_BLOG_LIKE = 'TOGGLE_BLOG_LIKE'; /** * ********************************** Allow Trade Entry ****************************************** */ export const ALLOW_ENTRY = 'ALLOW_ENTRY'; export const SET_ALLOW_ENTRY = 'SET_ALLOW_ENTRY'; /** * ********************************** Analyst Leaderboard ****************************************** */ export const GET_ANALYST_LEADERBOARD = 'GET_ANALYST_LEADERBOARD'; export const SET_ANALYST_LEADERBOARD = 'SET_ANALYST_LEADERBOARD'; /** * ********************************** SET LOADING ****************************************** */ export const SET_LOADING = 'SET_LOADING'; /** * ********************************** Page Switch ****************************************** */ export const SWITCH_TO_PROFILE_DISPLAY = 'SWITCH_TO_PROFILE_DISPLAY'; export const SWITCH_TO_ACCOUNT_DISPLAY = 'SWITCH_TO_ACCOUNT_DISPLAY';
import React, { Component } from 'react' import { Link } from 'react-router-dom' import moment from 'moment' import axios from 'axios' import SingleInput from '../SingleInput/SingleInput' import DatePicker from '../DayPicker/DayPicker' import TextArea from '../TextArea/TextArea' import MultipleInputs from '../MultipleInputs/MultipleInputs' import TimedMultipleInputs from '../TimedMultipleInputs/TimedMultipleInputs' import BathroomTimes from '../BathroomTimes/BathroomTimes' import SuppliesList from '../SuppliesList/SuppliesList' import Button from '../Button/Button' import UserInfo from '../UserInfo/UserInfo' class ToddlersForm extends Component { constructor (props) { super(props) this.state = { today: moment().format('MM-DD-YYYY'), name: '', day: '', meals: [ {id: 'breakfast', time: 'Breakfast', food: ''}, {id: 'amSnack', time: 'AM Snack', food: ''}, {id: 'lunch', time: 'Lunch', food: ''}, {id: 'pmSnack', time: 'PM Snack', food: ''} ], bathroom: { times: '', type: '' }, naps: [ {id: 'Morning', time: '', length: ''}, {id: 'Afternoon', time: '', length: ''} ], activities: '', bringItems: [ {type: 'Diapers', isChecked: false}, {type: 'Wipes', isChecked: false}, {type: 'Forumla', isChecked: false}, {type: 'Change of clothes', isChecked: false}, {type: 'Ointment', isChecked: false} ], other: '', providerEmail: '', providerUsername: '', providerPassword: '', parentEmail: '', step: 1 } this.handleDateChange = this.handleDateChange.bind(this) this.handleInputChange = this.handleInputChange.bind(this) this.handleMealChange = this.handleMealChange.bind(this) this.handleBathroomChange = this.handleBathroomChange.bind(this) this.handleNapsChange = this.handleNapsChange.bind(this) this.handleNapsTimeChange = this.handleNapsTimeChange.bind(this) this.handleBringItemsChange = this.handleBringItemsChange.bind(this) this.handleSubmit = this.handleSubmit.bind(this) this.prevStep = this.prevStep.bind(this) this.nextStep = this.nextStep.bind(this) } handleDateChange (selectedDate) { this.setState({today: selectedDate}) } handleInputChange (event) { // Learning application of computed object keys this.setState({ [event.target.name]: event.target.value }) } handleMealChange (meal, index) { // Learning application of ES6 spread operator let newMeals = [ ...this.state.meals ] newMeals[index] = { ...newMeals[index], food: meal } this.setState({meals: newMeals}) } handleBathroomChange (e) { // Learning application of Object.assign() const bathroom = Object.assign({}, this.state.bathroom) if (e.target.name === 'times') { bathroom.times = e.target.value this.setState({bathroom}) } else { bathroom.type = e.target.value this.setState({bathroom}) } } handleNapsChange (nap, index) { let newNaps = [ ...this.state.naps ] newNaps[index] = { ...newNaps[index], length: nap } this.setState({naps: newNaps}) } handleNapsTimeChange (time, index) { let newNaps = [ ...this.state.naps ] newNaps[index] = { ...newNaps[index], time: time } this.setState({naps: newNaps}) } handleBringItemsChange (item, isChecked, index) { let newBringItems = [ ...this.state.bringItems ] newBringItems[index] = { ...newBringItems[index], type: item, isChecked: isChecked } this.setState({bringItems: newBringItems}) } handleSubmit (event) { event.preventDefault() console.log(this.state) // axios.post('http://localhost:3000/sendmail/toddler', this.state) // .then(function(response) { // console.log(response) // }) // .catch(function(error) { // console.log(error) // }) // this.props.history.push('/') } prevStep () { this.setState({ step: this.state.step - 1 }) } nextStep () { this.setState({ step: this.state.step + 1 }) } formStep (currentStep) { switch (this.state.step) { case 1: return ( <div> <DatePicker id='today' type='text' label="Today\'s Date: " date={this.state.today} onChangeDateTime={this.handleDateChange} /> <SingleInput id='name' type='text' label='Name: ' onChange={this.handleInputChange} /> <SingleInput id='parentEmail' type='email' label='Parent Email: ' onChange={this.handleInputChange} /> <Button id='next' text='Next' onClick={this.nextStep} /> </div> ) case 2: return ( <div> <TextArea label='My day was: ' name='myDay' rows='4' cols='40' onChange={this.handleInputChange} /> </div> ) case 3: return ( <div> <MultipleInputs title='Meals' items={this.state.meals} onChange={this.handleMealChange} /> <BathroomTimes bathroom={this.state.bathroom} onChange={this.handleBathroomChange} /> <Button id='previous' text='Previous' onClick={this.prevStep} /> <Button id='next' text='Next' onClick={this.nextStep} /> </div> ) case 4: return ( <div> <TimedMultipleInputs title='Nap Times' id='naps' items={this.state.naps} onChange={this.handleNapsChange} onChangeDateTime={this.handleNapsTimeChange} /> <Button id='previous' text='Previous' onClick={this.prevStep} /> <Button id='next' text='Next' onClick={this.nextStep} /> </div> ) case 5: return ( <div> <TimedMultipleInputs title='Nap Times' id='naps' items={this.state.naps} onChange={this.hanMultipleChange} onChangeDateTime={this.handleMultipleTimeChange} /> <Button id='previous' text='Previous' onClick={this.prevStep} /> <Button id='next' text='Next' onClick={this.nextStep} /> </div> ) } render () { return ( <div> <h1>Toddlers</h1> <Link to='/'>Start Over</Link> <form onSubmit={this.handleSubmit}> {this.formStep(this.state.step)} </form> </div> ) } } export default ToddlersForm
let handlers = (() => { function displayHome(ctx) { ctx.loggedIn = sessionStorage.getItem("authtoken") !== null; ctx.username = sessionStorage.getItem("username"); ctx.loadPartials({ header: "./templates/common/header.hbs", footer: "./templates/common/footer.hbs" }).then(function () { this.partial("./templates/home/home.hbs") }) } function getLogin(ctx) { ctx.loggedIn = sessionStorage.getItem("authtoken") !== null; ctx.username = sessionStorage.getItem("username"); ctx.loadPartials({ header: "./templates/common/header.hbs", footer: "./templates/common/footer.hbs", loginForm: "./templates/login/loginForm.hbs" }).then(function () { this.partial("./templates/login/loginPage.hbs") }) } function postLogin(ctx) { let username = ctx.params.username; let password = ctx.params.password; if (username.length < 3) { notifications.showError("Username must be at least 3 symbols"); } else if (password.length < 6) { notifications.showError("Password must be at least 6 symbols"); } else if (username === "") { notifications.showError("Username should be non-empty"); } else if (password === "") { notifications.showError("Password should be non-empty"); } else { auth.login(username, password) .then(function (userInfo) { auth.saveSession(userInfo); notifications.showInfo("Login successful."); ctx.redirect("#/home"); }).catch(notifications.handleError); } } function logout(ctx) { auth.logout() .then(function () { sessionStorage.clear(); notifications.showInfo("Logout successful."); ctx.redirect("#/home"); // getLogin(ctx); }).catch(notifications.handleError) } function getRegister(ctx) { ctx.loggedIn = sessionStorage.getItem("authtoken") !== null; ctx.username = sessionStorage.getItem("username"); this.loadPartials({ header: "./templates/common/header.hbs", footer: "./templates/common/footer.hbs", registerForm: "./templates/register/registerForm.hbs" }).then(function () { this.partial("./templates/register/registerPage.hbs") }) } function postRegister(ctx) { let username = ctx.params.username; let password = ctx.params.password; if (username.length < 3) { notifications.showError("Username must be at least 3 symbols"); } else if (password.length < 6) { notifications.showError("Password must be at least 6 symbols"); } else if (username === "") { notifications.showError("Username should be non-empty"); } else if (password === "") { notifications.showError("Password should be non-empty"); } else { auth.register(username, password) .then(function (userInfo) { auth.saveSession(userInfo); notifications.showInfo("User registration successful."); ctx.redirect("#/home"); }).catch(notifications.handleError); } } function getCreate(ctx) { ctx.loggedIn = sessionStorage.getItem("authtoken") !== null; ctx.username = sessionStorage.getItem("username"); ctx.loadPartials({ header: "./templates/common/header.hbs", footer: "./templates/common/footer.hbs", createForm: "./templates/create/createForm.hbs" }).then(function () { this.partial("./templates/create/createPage.hbs") }) } function postCreate(ctx) { let name = ctx.params.name; let description = ctx.params.description; let imageURL = ctx.params.imageURL; let category = ctx.params.category; service.createItem(name, description, imageURL, category, 0) .then(function (adInfo) { notifications.showInfo("Pet created."); ctx.redirect("#/home"); // displayCatalog(ctx); }) .catch(notifications.handleError); } function getEdit(ctx) { ctx.loggedIn = sessionStorage.getItem("authtoken") !== null; ctx.username = sessionStorage.getItem("username"); let itemId = ctx.params.id.substr(1); service.loadItemDetails(itemId) .then(function (itemInfo) { ctx.itemId = itemId; ctx.description = itemInfo.description; ctx.name = itemInfo.name; ctx.category = itemInfo.category; ctx.likes = itemInfo.likes; ctx.imageURL = itemInfo.imageURL; ctx.loadPartials({ header: "./templates/common/header.hbs", footer: "./templates/common/footer.hbs", editForm: "./templates/edit/editForm.hbs" }).then(function () { this.partial("./templates/edit/editPage.hbs") }) }) .catch(notifications.handleError); } function postEdit(ctx) { let itemId = ctx.params.id.substr(1); let description = ctx.params.description; let name = ctx.params.name; let category = ctx.params.category; let likes = ctx.params.likes; let imageURL = ctx.params.imageURL; service.edit(itemId, name, description, imageURL, category, likes) .then(function (adInfo) { notifications.showInfo("Updated successfully!"); ctx.redirect("#/viewCatalog"); }) .catch(notifications.handleError); } function getRemove(ctx) { ctx.loggedIn = sessionStorage.getItem("authtoken") !== null; ctx.username = sessionStorage.getItem("username"); let itemId = ctx.params.id.substr(1); service.loadItemDetails(itemId) .then(function (itemInfo) { ctx.itemId = itemId; ctx.description = itemInfo.description; ctx.name = itemInfo.name; ctx.category = itemInfo.category; ctx.likes = itemInfo.likes; ctx.imageURL = itemInfo.imageURL; ctx.loadPartials({ header: "./templates/common/header.hbs", footer: "./templates/common/footer.hbs", deleteForm: "./templates/delete/deleteForm.hbs" }).then(function () { this.partial("./templates/delete/deletePage.hbs") }) }) .catch(notifications.handleError); } function postRemove(ctx) { let itemId = ctx.params.id.substr(1); let description = ctx.params.description; let name = ctx.params.name; let category = ctx.params.category; let likes = ctx.params.likes; let imageURL = ctx.params.imageURL; service.remove(itemId) .then(function (itemInfo) { notifications.showInfo("Pet removed successfully!"); ctx.redirect("#/viewCatalog"); }) .catch(notifications.handleError); } function displayCatalog(ctx) { ctx.loggedIn = sessionStorage.getItem("authtoken") !== null; ctx.username = sessionStorage.getItem("username"); service.loadItems() .then(function (items) { ctx.items = items.filter(item => item._acl.creator !== sessionStorage.getItem("userId")); ctx.loadPartials({ header: "./templates/common/header.hbs", footer: "./templates/common/footer.hbs", itemBox: "./templates/catalog/items/itemBox.hbs", itemsCatalog: "./templates/catalog/items/itemsCatalog.hbs" }).then(function () { this.partial("./templates/catalog/items/itemsPage.hbs"); }) }); } function displayCatalogCats(ctx) { ctx.loggedIn = sessionStorage.getItem("authtoken") !== null; ctx.username = sessionStorage.getItem("username"); service.loadItems() .then(function (items) { ctx.items = items.filter(item => item._acl.creator !== sessionStorage.getItem("userId") && item.category === "Cat") .sort((a,b) => b.likes - a.likes); ctx.loadPartials({ header: "./templates/common/header.hbs", footer: "./templates/common/footer.hbs", itemBox: "./templates/catalog/items/itemBox.hbs", itemsCatalog: "./templates/catalog/items/itemsCatalog.hbs" }).then(function () { this.partial("./templates/catalog/items/itemsPage.hbs"); }) }); } function displayCatalogDogs(ctx) { ctx.loggedIn = sessionStorage.getItem("authtoken") !== null; ctx.username = sessionStorage.getItem("username"); service.loadItems() .then(function (items) { ctx.items = items.filter(item => item._acl.creator !== sessionStorage.getItem("userId") && item.category === "Dog") .sort((a,b) => b.likes - a.likes); ctx.loadPartials({ header: "./templates/common/header.hbs", footer: "./templates/common/footer.hbs", itemBox: "./templates/catalog/items/itemBox.hbs", itemsCatalog: "./templates/catalog/items/itemsCatalog.hbs" }).then(function () { this.partial("./templates/catalog/items/itemsPage.hbs"); }) }); } function displayCatalogParrots(ctx) { ctx.loggedIn = sessionStorage.getItem("authtoken") !== null; ctx.username = sessionStorage.getItem("username"); service.loadItems() .then(function (items) { ctx.items = items.filter(item => item._acl.creator !== sessionStorage.getItem("userId") && item.category === "Parrot") .sort((a,b) => b.likes - a.likes); ctx.loadPartials({ header: "./templates/common/header.hbs", footer: "./templates/common/footer.hbs", itemBox: "./templates/catalog/items/itemBox.hbs", itemsCatalog: "./templates/catalog/items/itemsCatalog.hbs" }).then(function () { this.partial("./templates/catalog/items/itemsPage.hbs"); }) }); } function displayCatalogReptiles(ctx) { ctx.loggedIn = sessionStorage.getItem("authtoken") !== null; ctx.username = sessionStorage.getItem("username"); service.loadItems() .then(function (items) { ctx.items = items.filter(item => item._acl.creator !== sessionStorage.getItem("userId") && item.category === "Reptile") .sort((a,b) => b.likes - a.likes); ctx.loadPartials({ header: "./templates/common/header.hbs", footer: "./templates/common/footer.hbs", itemBox: "./templates/catalog/items/itemBox.hbs", itemsCatalog: "./templates/catalog/items/itemsCatalog.hbs" }).then(function () { this.partial("./templates/catalog/items/itemsPage.hbs"); }) }); } function displayCatalogOther(ctx) { ctx.loggedIn = sessionStorage.getItem("authtoken") !== null; ctx.username = sessionStorage.getItem("username"); service.loadItems() .then(function (items) { ctx.items = items.filter(item => item._acl.creator !== sessionStorage.getItem("userId") && item.category === "Other") .sort((a,b) => b.likes - a.likes); ctx.loadPartials({ header: "./templates/common/header.hbs", footer: "./templates/common/footer.hbs", itemBox: "./templates/catalog/items/itemBox.hbs", itemsCatalog: "./templates/catalog/items/itemsCatalog.hbs" }).then(function () { this.partial("./templates/catalog/items/itemsPage.hbs"); }) }); } function displayItemDetailsPage(ctx) { ctx.loggedIn = sessionStorage.getItem("authtoken") !== null; ctx.username = sessionStorage.getItem("username"); let itemId = ctx.params.id.substr(1); service.loadItemDetails(itemId) .then(function (itemInfo) { ctx.itemId = itemId; ctx.name = itemInfo.name; ctx.likes = itemInfo.likes; ctx.imageURL = itemInfo.imageURL; ctx.description = itemInfo.description; ctx.loadPartials({ header: "./templates/common/header.hbs", footer: "./templates/common/footer.hbs", itemDetails: "./templates/catalog/itemDetails/itemDetails.hbs" }).then(function () { this.partial("./templates/catalog/itemDetails/itemDetailsPage.hbs") }) }).catch(notifications.handleError); } function displayMyItems(ctx) { ctx.loggedIn = sessionStorage.getItem("authtoken") !== null; ctx.username = sessionStorage.getItem("username"); service.loadItems() .then(function (items) { ctx.items = items.filter(item => item._acl.creator === sessionStorage.getItem("userId")); ctx.loadPartials({ header: "./templates/common/header.hbs", footer: "./templates/common/footer.hbs", myItemBox: "./templates/catalog/myItems/myItemBox.hbs", myItemsCatalog: "./templates/catalog/myItems/myItemsCatalog.hbs" }).then(function () { this.partial("./templates/catalog/myItems/myItemsPage.hbs"); }) }); } function petAPet(ctx) { // let itemId = ctx.params.id.substr(1); // let description = ctx.params.description; // let name = ctx.params.name; // let category = ctx.params.category; // let likes = +ctx.params.likes + 1; // let imageURL = ctx.params.imageURL; // // service.edit(itemId, name, description, imageURL, category, likes) // .then(function (adInfo) { // ctx.redirect("#/viewCatalog"); // }) // .catch(notifications.handleError); } return { displayHome, getLogin, postLogin, logout, getRegister, postRegister, getCreate, postCreate, getEdit, postEdit, getRemove, postRemove, displayCatalog, displayCatalogCats, displayCatalogDogs, displayCatalogParrots, displayCatalogReptiles, displayCatalogOther, displayItemDetailsPage, displayMyItems, petAPet } })();
import React from "react"; import "./normalPost.css"; import {BiComment} from 'react-icons/bi' import { Link, useLocation, } from "react-router-dom"; import { url } from "../../../baseHost"; export const NormalPost = (props) => { return ( <Link key={props.post._id} to={`/article/${props.post._id}`} className="Normal_post_cont"> <div className='Normal_post_cont_image' style={{ backgroundImage: `url("${url}/${props.post.image}")` }}></div> <div className='Normal_post_text_cont'> <h3>{props.post.Title}</h3> <div> <div>{props.post.Date}</div> <div><BiComment/>200</div> </div> </div> </Link> ); };
/********************************************************************************* * WEB322 – Assignment 03 * I declare that this assignment is my own work in accordance with Seneca Academic Policy. No part * of this assignment has been copied manually or electronically from any other source * (including 3rd party web sites) or distributed to other students. * * Name: Anh-Bang Truong (Ethan) Student ID: 124753179 Date: Feb 12, 2019 * * Online (Heroku) Link: https://web322-assignment-3.herokuapp.com/ * ********************************************************************************/ var HTTP_PORT = process.env.PORT || 8080; var express = require("express"); var data = require('./data-service.js'); var path = require('path'); var multer = require('multer'); var bodyParser = require('body-parser'); var fs = require('fs'); var app = express(); // home page app.get("/", (req, res) => { res.sendFile(path.join(__dirname+'/views/home.html')); }); // about page app.get("/about", (req, res) => { res.sendFile(path.join(__dirname+'/views/about.html')); }); // add employee app.get("/employees/add", (req, res) => { res.sendFile(path.join(__dirname+'/views/addEmployee.html')); }); // add image app.get("/images/add", (req, res) => { res.sendFile(path.join(__dirname+'/views/addImage.html')); }); // employees url app.get("/employees", (req, res) => { if(req.query.status){ data.getEmployeesByStatus(req.query.status).then((data)=>{ res.json(data); }).catch((err)=>{ res.json(err); }); } else if(req.query.department){ data.getEmployeesByDepartment(req.query.department).then((data)=>{ res.json(data); }).catch((err)=>{ res.json(err); }); } else if(req.query.manager){ data.getEmployeesByManager(req.query.manager).then((data)=>{ res.json(data); }).catch((err)=>{ res.json(err); }); } else{ data.getAllEmployees().then((data)=>{ res.json(data) }).catch((err) => { res.json(err); }); } }); // value route app.get('/employee/:value', (req,res)=>{ data.getEmployeeByNum(req.params.value).then((data)=>{ res.json(data) }).catch((err) => { res.json(err); }); }); // mangers url app.get("/managers", (req, res) => { data.getManagers().then((data)=>{ res.json(data) }).catch((err) => { res.json(err); }); }); // departments url app.get("/departments", (req, res) => { data.getDepartments().then((data)=>{ res.json(data) }).catch((err) => { res.json(err); }); }); // add multer const storage = multer.diskStorage({ destination: "./public/images/uploaded", filename: function (req, file, cb) { cb(null, Date.now() + path.extname(file.originalname)); } }); const upload = multer({ storage: storage }); // post image app.post("/images/add", upload.single('imageFile'), (req,res) => { res.redirect("/images"); }); app.get("/images", (req,res)=>{ // get image using fs module fs.readdir("./public/images/uploaded", (err, items) => { res.json({"images" : items}); }); }); // body parser app.use(bodyParser.urlencoded({extended: true})); // add employee app.post("/employees/add", (req, res) =>{ data.addEmployee(req.body).then((data) =>{ res.redirect("/employees"); }).catch((err) => { res.json(err); }); }); // no matching route app.use((req,res) => { res.status(404).send("Page Not Found"); }); // setup http server to listen on HTTP_PORT data.initialize().then(() => { app.listen(HTTP_PORT, onHttpStart); }). catch((err)=>{ console.log(err); }) function onHttpStart() { console.log("Express http server listening on: " + HTTP_PORT); }
(function (){ var div = document.querySelector(".banner") var img = div.getElementsByTagName('img'); /*选中div下所有的图片*/ var ul = document.getElementsByTagName('ul')[0]; var li = ul.getElementsByTagName('li'); var prev= document.getElementsByTagName('div')[1].getElementsByTagName('div')[1]; var next = document.getElementsByTagName('div')[1].getElementsByTagName('div')[0]; var len = img.length; var count = 0; /*设置count来显示当前图片的序号*/ function run(){ /*将定时器里的函数提取到外部*/ count++; count = count==len?0:count; /*当图片加载到最后一张时,使其归零*/ for(var i=0;i<len;i++){ img[i].style.display = 'none'; /*利用for循环使除当前count位其他图片隐藏*/ } img[count].style.display = 'block'; /*显示当前count的值所代表的图片*/ for(var i=0;i<li.length;i++){ li[i].style.backgroundColor = "#fff"; /*原理同上*/ } li[count].style.backgroundColor = "rgb(43, 255, 0)"; } var timer = setInterval(run,3500); /*定义定时器,使图片每隔3.5s更换一次*/ div.onmouseover = function(){ clearInterval(timer); prev.style.display="block"; next.style.display="block"; } div.onmouseleave = function(){ /*定义鼠标移出事件,当鼠标移出div区域,轮播继续*/ timer = setInterval(run,3500); prev.style.display="none"; next.style.display="none"; } for(var i=0;i<len;i++){ li[i].index = i; /*定义index记录当前鼠标在li的位置*/ li[i].onmouseenter = function(){ /*定义鼠标经过事件*/ for(var i=0;i<len;i++){ /*通过for循环将所有图片隐藏,圆点背景设为白色*/ li[i].style.background = '#fff'; img[i].style.display = 'none'; } this.style.background = 'rgb(43, 255, 0)'; /*设置当前所指圆点的背景色*/ img[this.index].style.display = 'block'; /*使圆点对应的图片显示*/ } } prev.onclick = function(){ /*因为span没有设置宽高,直接把事件添加到他的父级*/ run(); /*直接调用现成的run函数*/ } function reverse(){ count--; count = count==-1?2:count; for(var i=0;i<len;i++){ img[i].style.display = 'none'; /*利用for循环使除当前count位其他图片隐藏*/ } img[count].style.display = 'block'; /*显示当前count的值所代表的图片*/ for(var i=0;i<li.length;i++){ li[i].style.backgroundColor = "#fff"; /*原理同上*/ } li[count].style.backgroundColor = "rgb(43, 255, 0)"; } next.onclick = function(){ reverse(); /*重新设置函数*/ } //1. 查找触发事件的元素 var tab=document.querySelectorAll( "#tab>[data-toggle=tab]" ); //2. 绑定事件处理函数 (function(){ for(var li of tab){ li.onclick=function(){ var li=this; // span切换 var spans=document.querySelectorAll("#tab>span"); for(var span of spans){ span.className="tab_item"; } li.className+=" active"; // 底部的ul图片 var id=li.getAttribute("data-id"); var ul=document.querySelector(id); var uls=document.querySelectorAll(".tab-container>ul"); for(var d of uls){ d.style.display="none"; } ul.style.display="block"; } } })(); })();
import { FETCH_USER_FAILURE, FETCH_USER_REQUEST, FETCH_USER_SUCCESS } from "./userTypes" const initialState = { loading : false, users : [], error : false } const userReducer = (state=initialState,action)=>{ switch(action.type){ case FETCH_USER_REQUEST: return { ...state, loading : true } case FETCH_USER_SUCCESS: return{ error : '', loading:true, users : action.payload } case FETCH_USER_FAILURE: return{ loading : false, users : [], error : action.payload } default:return state } } export default userReducer
function save_options() { var api = document.getElementById('api').checked; var server = document.getElementById('server').checked; var local = document.getElementById('local').checked; var timinit = document.getElementById('timinit').checked; var disable = document.getElementById('disable').checked; chrome.storage.sync.set({ "mockApi": api, "mockServer": server, "local": local, "timinit": timinit, "disable": disable }); } // Restores select box and checkbox state using the preferences // stored in chrome.storage. function restore_options() { chrome.storage.sync.get(['mockApi', 'mockServer', 'local', 'timinit', 'disable'], function(items) { document.getElementById('api').checked = items.mockApi; document.getElementById('server').checked = items.mockServer; document.getElementById('local').checked = items.local; document.getElementById('timinit').checked = items.timinit; document.getElementById('disable').checked = items.disable; }); } document.addEventListener('DOMContentLoaded', restore_options); document.getElementById('api').addEventListener('change', save_options); document.getElementById('server').addEventListener('change', save_options); document.getElementById('local').addEventListener('change', save_options); document.getElementById('timinit').addEventListener('change', save_options); document.getElementById('disable').addEventListener('change', save_options);
// 要拼接路径 public/uploads/avatar // 引入系统模块path const path = require('path'); const finalPath = path.join('public', 'uploads', 'avatar'); // 它会根据你所在的系统来拼接路径 由于本系统是windows系统 所以拼接的路径就是:public\uploads\avatar console.log(finalPath); //public\uploads\avatar
var isok=false;//开关,用来判断是否能登录 //______________________________________________ //验证用户名 $("#username").blur(function(){ var username=$("#username").val(); if(username==""){ isok=false; $("#l_usernamecue").text("* 不能为空"); $("#l_usernamecue").css("color","red"); } else{ $("#l_usernamecue").text(""); //正则 if(/^1[3456789]\d{9}$/.test(username)||/^\w+@\w+(\.\w+)+$/.test(username)){ $("#l_usernamecue").text(""); isok=true;//改变开关 } else{ isok=false;//改变开关 $("#l_usernamecue").text("* 用户名格式不正确"); $("#l_usernamecue").css("color","red"); } } }); //______________________________________________ //验证用户名 $("#password").blur(function(){ var password=$("#password").val(); if(password==""){ isok=false; $("#l_pwd").text("* 不能为空"); $("#l_pwd").css("color","red"); } else{ isok=true; $("#l_pwd").text(""); } }); //______________________________________________ //登录 function login(){ var username=$("#username").val(); var password=$("#password").val(); $.ajax({ type:"post", url:"../api/login.php", async:true,//异步 data:{//传过去的数据 "mate":"login",//匹配参数 "username":username, "password":password }, success:function(str){//成功的回调 if(str!="no"){ var data = JSON.parse(str); alert("登录成功!"); setCookie("user_id",data[0].user_id,1,"/"); window.location.href="../index.html"; var s=document.cookie console.log(123) } else{ alert("登录失败,用户名与密码不匹配!") } } }); } $("#login_btn").click(function(){ login(); }); $(document).keydown(function(e){ if(e.keyCode==13){ login(); } });
import React from 'react'; import { makeStyles } from '@material-ui/core/styles'; import Card from '@material-ui/core/Card'; import CardActions from '@material-ui/core/CardActions'; import CardContent from '@material-ui/core/CardContent'; import Button from '@material-ui/core/Button'; import Typography from '@material-ui/core/Typography'; import Countdown from 'react-countdown-now'; import ServiceButton from '../ServiceButton'; const useStyles = makeStyles({ card: { minWidth: 275, }, bullet: { display: 'inline-block', margin: '0 2px', transform: 'scale(0.8)', }, title: { fontSize: 14, }, pos: { marginBottom: 12, }, }); export default function TechCard(tech) { let time = tech.props.timer; console.log(tech) const classes = useStyles(); if(!tech.props.isWorking) { return ( <Card className={classes.card}> <CardContent> <Typography variant="h3" color="textPrimary" gutterBottom> {tech.props.name} </Typography> </CardContent> <CardActions> {tech.props.services.map(service => { return( <ServiceButton id={tech.props.id} position={tech.props.position} key={service} props={service} method={tech.method}/> ) })} </CardActions> </Card> ); } else { return( <Card className={classes.card}> <CardContent> <Typography variant="h3" color="textPrimary" gutterBottom> {tech.props.name} </Typography> <Typography className={classes.title} color="textSecondary" gutterBottom> <Countdown // https://www.npmjs.com/package/react-countdown-now#api-reference date={Date.now() + time} intervalDelay={1000} precision={3} renderer={props => <span>{props.minutes}:{props.seconds}</span>} onComplete={function() {console.log("onComplete called")}} /> </Typography> </CardContent> <CardActions> <Button size="small">Working</Button> </CardActions> </Card> ) }; };
const InfoRoute = require('./info'); const UsersRoute = require('./users'); module.exports = [ InfoRoute, UsersRoute ]
var FbYouTube = new Class({ Extends:FbElement, initialize: function(element, options) { this.plugin = 'fabrikyoutube'; this.parent(element, options); } });
class Despesa{ constructor(ano, mes, dia, tipo, descricao, valor){ this.ano = ano this.mes = mes this.dia = dia this.tipo = tipo this.descricao = descricao this.valor = valor } validarDodos(){ for(let i in this){ if(this[i] == undefined || this[i] == '' || this[i] == null){ return false } } return true } } class Bd{ constructor(){ let id = localStorage.getItem('id') if(id === null){ localStorage.setItem('id', 1) } } getProxId(){ let proxId = localStorage.getItem('id')//null return parseInt(proxId) + 1 } gravar(d){ let id = this.getProxId() localStorage.setItem(id, JSON.stringify(d)) localStorage.setItem('id', id) } recuperarTododsRegistros(){ //array de despesas let despesas = Array() let id = localStorage.getItem('id') //recuperar todas as despesas cadastradas em localstorage for(let i = 1; i<=id; i++){ let despesa = Json.parse(localstorage.getItem(i)) //pular caso if(despesa === null){ continue } despesas.push(despesa) } return despesas } pesquisar(despesa){ let despesasFiltradas = Array() despesasFiltradas = this.recuperarTododsRegistros() if (despesa.ano !=''){ despesasFiltradas.filter(d => d.ano == despesa.ano) } if (despesa.mes !=''){ despesasFiltradas.filter(d => d.ano == despesa.mes) } if (despesa.dia !=''){ despesasFiltradas.filter(d => d.ano == despesa.dia) } if (despesa.tipo !=''){ despesasFiltradas.filter(d => d.ano == despesa.tipo) } if (despesa.descricao !=''){ despesasFiltradas.filter(d => d.ano == despesa.descricao) } if (despesa.valor !=''){ despesasFiltradas.filter(d => d.ano == despesa.valor) } return despesasFiltradas } } pesquisarDespesa let bd = new Bd() function cadastrarDespesa(){ let ano = document.getElementById('ano').value let mes = document.getElementById('mes').value let dia = document.getElementById('dia').value let tipo = document.getElementById('tipo').value let descricao= document.getElementById('descricao').value let valor = document.getElementById('valor').value let despesa = new Despesa( ano, mes, dia, tipo, descricao, valor ) if(despesa.validarDodos()) { bd.gravar(despesa) $(sucessoGravacao).modal('show') ano.value = '' mes.value = '' dia.value = '' tipo.value = '' descricao.value = '' valor.value = '' } else{ $(erroGravacao).modal('show') bd.gravar(Despesa) } } function carregaListaDespesas(despesas = Array(),filtro = false) { if(despesas.length == 0 && filtro==false){ despesas = bd.recuperarTododsRegistros() } let listaDespesas = document.getElementById('listaDespesas') listaDespesas.innerHTML = '' //percorrer o array despesas,listando cada despesa dinamicamente despesas.forEach(function(d){ //criando a linha (tr) listaDespesas.insertRow() //criando colunas (td) linha.insertCell(0).innerHTML = d.dia + '/' + d.mes + '/' +d.ano //ajustando o tipo switch(d.tipo){ case '1': d.tipo = 'Alimentação' break case '2' :d.tipo ='Educação' break case '3': d.tipo ='Lazer' break case '4': d.tipo ='Saúde' break case '5': d.tipo ='Transporte' break } linha.insertCell(1).innerHTML = d.tipo linha.insertCell(2).innerHTML = d.descricao linha.insertCell(3).innerHTML = d.valor }) } function pesquisarDespesa(){ let ano = document.getElementById('ano').value let mes = document.getElementById('mes').value let dia = document.getElementById('dia').value let tipo = document.getElementById('tipo').value let descricao = document.getElementById('descricao').value let valor = document.getElementById('valor').value let despesa = new Despesa (ano, mes, dia, tipo, descricao, valor) let despesas = bd.pesquisar(despesa) carregaListaDespesas(despesas, true) }
const config = { 'port': 3010, 'get': false, 'gpio': { // GPIO pin number https://www.raspberrypi.org/documentation/usage/gpio/ // used for 433MHz transmitter and receiver 'transmitter': 2, // unused 'receiver': 3 } } module.exports = config;
const path = require("path"); // For addresses that should give index.html, for example ["/", "/admin", "/news" ] const routes = [ "/" ]; const indexPath = path.resolve(__dirname, "..", "public","index.html"); module.exports = function(req, res, next) { const idx = routes.findIndex(x => x === req.path); if(idx !== -1) { return res.sendFile(indexPath); } if( !req.path.startsWith("/api") ) { return res.status(404).send('404: Page Not Found'); } return next(); };
import { Advantage } from "../../../db/models/"; const advantageQueries = { advantageRandom: async () => { const Qty = await Advantage.find().countDocuments(); const random = Math.floor(Math.random() * Qty); return await Advantage.findOne().skip(random); } }; export default advantageQueries;
describe('CorporaNewController', function(){ var createController, $controller, $scope, $rootScope, $httpBackend, $upload, $state; beforeEach(module('linguine')); beforeEach(inject(function($injector){ $rootScope = $injector.get('$rootScope'); $scope = $rootScope.$new; $httpBackend = $injector.get('$httpBackend'); $controller = $injector.get('$controller'); $upload = $injector.get('$upload'); $state = $injector.get('$state'); createController = function(){ return $controller('CorporaNewController', { $scope: $scope, $uplaod: $upload, $state: $state }); } $httpBackend.whenGET('/templates/home/index').respond(200, ''); $httpBackend.whenGET('/templates/corpora/index').respond(200, ''); $httpBackend.whenGET('/api/logged_in').respond(200, { loggedIn: true, user: { dce: 'jd1234', name: 'John Doe', _id: 1 } }); })); //describe('onCreateCorpus', function(){ //it('should work', function(done){ //createController(); //$scope.corpus = { //fileName: 'Thing', //fileSize: 100, //fileType: 'text' //}; //$scope.onCreateCorpus(); //$httpBackend.expectPOST('/api/corpora').respond(201, {}); //$httpBackend.flush(); //done(); //}); //}); });
"use strict"; require("run-with-mocha"); const assert = require("assert"); const testTools = require("./_test-tools") const AudioBufferFactory = require("../../src/factories/AudioBufferFactory"); describe("AudioBufferFactory", () => { it("should defined all properties", () => { const AudioBuffer = AudioBufferFactory.create({}, class {}); const properties = testTools.getPropertyNamesToNeed("AudioBuffer"); const notDefined = properties.filter((name) => { return !Object.getOwnPropertyDescriptor(AudioBuffer.prototype, name); }); assert(notDefined.length === 0); }); describe("instance", () => { describe("constructor", () => { it("audioContext.createBuffer()", () => { const api = testTools.createAPI(); const context = new api.AudioContext(); const buffer = context.createBuffer(2, 128, 44100); assert(buffer instanceof api.AudioBuffer); }); it("new instance", () => { const api = testTools.createAPI(); const buffer = new api.AudioBuffer({ numberOfChannels: 2, length: 128, sampleRate: 44100 }); assert(buffer instanceof api.AudioBuffer); assert(buffer.length === 128); }); it("new instance with context", () => { const api = testTools.createAPI({ "/AudioBuffer/context": true }); const context = new api.AudioContext(); const buffer = new api.AudioBuffer(context, { numberOfChannels: 2, length: 128, sampleRate: 44100 }); assert(buffer instanceof api.AudioBuffer); assert(buffer.length === 128); }); it("new instance, but @protected", () => { const api = testTools.createAPI({ protected: true }); assert.throws(() => { return new api.AudioBuffer({ numberOfChannels: 2, length: 128, sampleRate: 44100 }); }, TypeError); }); it("throws error when without AudioContext", () => { const api = testTools.createAPI({ "/AudioBuffer/context": true }); assert.throws(() => { return new api.AudioBuffer({ numberOfChannels: 2, length: 128, sampleRate: 44100 }); }, TypeError); }); it("throw error", () => { const api = testTools.createAPI({}); assert.throws(() => { return new api.AudioBuffer({ numberOfChannels: 0, length: 128, sampleRate: 44100 }); }, TypeError); assert.throws(() => { return new api.AudioBuffer({ numberOfChannels: 2, length: 0, sampleRate: 44100 }); }, TypeError); assert.throws(() => { return new api.AudioBuffer({ numberOfChannels: 2, length: 128, sampleRate: 0 }); }, TypeError); }); it("default parameters", () => { const api = testTools.createAPI(); const buffer = new api.AudioBuffer({ numberOfChannels: 2, length: 128, sampleRate: 44100 }); assert(buffer.numberOfChannels === 2); assert(buffer.length === 128); assert(buffer.duration === 128 / 44100); assert(buffer.sampleRate === 44100); }); }); describe("getChannelData", () => { it("works", () => { const api = testTools.createAPI(); const buffer = new api.AudioBuffer({ numberOfChannels: 2, length: 8, sampleRate: 44100 }); assert(buffer.getChannelData(0) instanceof Float32Array); assert(buffer.getChannelData(0).length === 8); }); it("throw error", () => { const api = testTools.createAPI(); const buffer = new api.AudioBuffer({ numberOfChannels: 2, length: 8, sampleRate: 44100 }); assert.throws(() => { return buffer.getChannelData(2); }, TypeError); }); }); describe("copyFromChannel", () => { it("works", () => { const api = testTools.createAPI(); const buffer = new api.AudioBuffer({ numberOfChannels: 2, length: 8, sampleRate: 44100 }); const destination = new Float32Array(4); buffer.getChannelData(1).set([ 0, 0, 1, 2, 3, 4, 0, 0 ]); buffer.copyFromChannel(destination, 1, 2); assert.deepEqual(destination, [ 1, 2, 3, 4 ]); }); it("throws", () => { const api = testTools.createAPI(); const buffer = new api.AudioBuffer({ numberOfChannels: 2, length: 8, sampleRate: 44100 }); const destination = new Float32Array(4); assert.throws(() => { buffer.copyFromChannel(destination, 2, 0); }, TypeError); assert.throws(() => { buffer.copyFromChannel(destination, 0, 10); }, TypeError); }); }); describe("copyToChannel", () => { it("works", () => { const api = testTools.createAPI(); const buffer = new api.AudioBuffer({ numberOfChannels: 2, length: 8, sampleRate: 44100 }); const source = new Float32Array([ 1, 2, 3, 4 ]); buffer.copyToChannel(source, 1, 2); assert(buffer.getChannelData(1), [ 0, 0, 1, 2, 3, 4, 0, 0 ]); }); it("throws", () => { const api = testTools.createAPI(); const buffer = new api.AudioBuffer({ numberOfChannels: 2, length: 8, sampleRate: 44100 }); const source = new Float32Array([ 1, 2, 3, 4 ]); assert.throws(() => { buffer.copyToChannel(source, 2, 0); }, TypeError); assert.throws(() => { buffer.copyToChannel(source, 0, 10); }, TypeError); }); }); }); describe("@deprecated", () => { describe("gain", () => { it("works", () => { const api = testTools.createAPI(); const buffer = new api.AudioBuffer({ numberOfChannels: 2, length: 128, sampleRate: 44100 }); assert(buffer.gain === 1); buffer.gain = 0.5; assert(buffer.gain === 0.5); }); }); }); });
const os = require('os'); //let cpu = os.cpus(); let hostname = os.hostname(); let version = os.version(); let homedir = os.homedir(); let platform = os.platform(); console.log("Hello world!"); //console.log("CPUs:") //console.log(cpu); console.log("Hostname: " + hostname ); console.log("Platform: " + platform); //console.log(hostname); console.log("Version: " + version); //console.log(version); console.log("Home directory:" + homedir); //console.log(homedir);
export const addPhoto = imageURL => ({ type: "ADD_PHOTO", payload: { imageURL } }); export const hasVotedAction = (id) => ({ type: "HAS_VOTED", payload: { id } }); export const init = () => ({ type: "INIT" });
var express = require("express"); var app = express(); app.get("/", function(req, res){ res.send("<h1>You are end the slashing zone!</h1>"); }); app.get("/speak/:animal", function(req, res){ var animal = req.params.animal.toLowerCase(); var animalSay = "grrr."; var sounds = { pig: "\"Oink!\"", cow: "\"Moo!\"", dog: "\"Woof!\"", cat: "\"Meow!\"", elk: "\"errrr\"", unicorn: "\"No, do that slowly\"", goldfish: "..." } var sound = sounds[animal]; res.send("<h1>The " + animal + " says " + sound + "</h1>"); }); app.get("/repeat/:somePhrase/:numberOfTimes", function(req, res){ var somePhrase = req.params.somePhrase; var number = Number(req.params.numberOfTimes); var message = ""; for(var i = 0; i < number; i++){ message += "<h1>" + somePhrase + " </h1>"; } res.send(message); }); app.get("*", function(req, res){ res.send("<h1>There are no animals to be found here! What are you doing with your life?</h1>"); }); app.listen(process.env.PORT, process.env.IP, function(){ console.log("Server has started. Yay!!!"); });
const zeromq = require("zeromq"); const Promise = require("bluebird"); const Protocol = require(__dirname + "/protocol"); function Client(broker_address, service_name, opt) { this.address = broker_address; this.service_name = service_name; this.promise_objects = {}; this.log = opt && opt.log; this.socket = zeromq.socket("dealer").connect(this.address); socketListener(this.socket, this.promise_objects, {log: this.log}); process.on("SIGINT", () => { if(this.socket) { this.socket.close(); this.socket = undefined; } this.promise_objects = undefined; }); }; Client.prototype.invoke = function(fn, params) { return new Promise((resolve, reject) => { const req = Protocol.createReqObj(this.service_name, fn, params); this.log && this.log("client-input", req); const req_id = req.header.id; this.promise_objects[req_id] = { resolve, reject }; const delimiter = Buffer.alloc(0); this.socket.send([ delimiter, Protocol.encodeReq(req) ]); }); }; const socketListener = function(socket, promise_objects, opt) { socket.on("message", (...outputs) => { try { const [delimiter, msg] = outputs; if(Buffer.byteLength(delimiter) !== 0) { return; } const req = Protocol.decodeReq(msg); opt.log && opt.log("client-output", req); const req_id = req.header.id; promise_objects[req_id].resolve(req.output); promise_objects[req_id] = undefined; delete promise_objects[req_id]; } catch(err) { console.log("Error: ", err); } }) }; module.exports = Client;
import chai from 'chai'; import request from 'supertest'; import app from '../../src/app'; import { ADMINISTRATOR } from '../../src/auth/constants'; import { loadFixtures, createAuthorization } from '../helpers'; chai.should(); const headers = { Authorization: createAuthorization(ADMINISTRATOR) }; describe('Product API', () => { describe('List all products', () => { beforeEach(() => loadFixtures()); it('should list all products', done => { request(app) .get('/products/') .set(headers) .expect('Content-Type', /json/) .expect(200) .end((err, res) => { if (err) return done(err); const products = res.body; products.length.should.equal(3); products[0].id.should.equal(1); products[0].name.should.equal('Test product 1'); done(); }); }); }); describe('List active products', () => { beforeEach(() => loadFixtures()); it('should list active products', done => { request(app) .get('/products/?active=true') .set(headers) .expect('Content-Type', /json/) .expect(200) .end((err, res) => { if (err) return done(err); const products = res.body; products.length.should.equal(3); done(); }); }); }); describe('List all active products of type', () => { beforeEach(() => loadFixtures()); it('should list active products', done => { request(app) .get('/products/?productGroupId=1&active=true') .set(headers) .expect('Content-Type', /json/) .expect(200) .end((err, res) => { if (err) return done(err); const products = res.body; products.length.should.equal(1); products[0].productGroupId.should.equal(1); done(); }); }); }); describe('List a single product', () => { beforeEach(() => loadFixtures()); it('should return a product from a current system', done => { request(app) .get('/products/1') .set(headers) .expect('Content-Type', /json/) .expect(200) .end((err, res) => { if (err) return done(err); res.body.name.should.equal('Test product 1'); done(); }); }); it("should return 404 on product that doesn't exist", done => { request(app) .get('/products/1337') .set(headers) .expect(404, done); }); it('should return 404 on product that exists, but are not in the current system.', done => { request(app) .get('/products/4') .set(headers) .expect(404, done); }); }); describe('Create products', () => { beforeEach(() => loadFixtures()); it('should create a product', done => { request(app) .post('/products') .send({ type: 'Created Type', price: 1337.99, internalPrice: 1337.0, name: 'Created Product', active: true, stock: 0 }) .set(headers) .expect(201, done); }); }); describe('Destroy product', () => { beforeEach(() => loadFixtures()); it('should delete an existing product', done => { request(app) .delete('/products/1') .set(headers) .expect(204, done); }); it('should return not found if product not found', done => { request(app) .delete('/products/4') .set(headers) .expect(404, done); }); }); });
/*jslint browser: true, indent: 2 */ /*global jQuery */ (function ($) { 'use strict'; // Refresh delay in milliseconds var delay, refreshed, parameter; delay = 2000; refreshed = new Date().getTime(); parameter = 'CSSynch'; $('link[rel="stylesheet"]').each(function () { var uri, last, update; // Original css is the last version last = $(this); // Uri, prepared to inject uniqid query parameter uri = last.attr('href').replace(/\?|$/, '?&'); // Refresh only url of type: (//, http://, https://, no sheme) if (uri.match(/^(?:https?:)?\/\/|^(?:.(?!\:\/\/))+$/)) { update = function () { refreshed++; // Create new version $('<link rel="stylesheet"/>') .insertAfter(last) .on('load', function () { // Remove previous version last.remove(); last = $(this); // program next refresh setTimeout(update, delay); }) .attr('href', uri.replace(/\?/, '?' + parameter + '=' + refreshed)); }; setTimeout(update, delay); } }); }(jQuery));
const test = require('tape'); const digitize = require('./digitize.js'); test('Testing digitize', (t) => { //For more information on all the methods supported by tape //Please go to https://github.com/substack/tape t.true(typeof digitize === 'function', 'digitize is a Function'); t.deepEqual(digitize(123), [1, 2, 3], "Converts a number to an array of digits"); //t.deepEqual(digitize(args..), 'Expected'); //t.equal(digitize(args..), 'Expected'); //t.false(digitize(args..), 'Expected'); //t.throws(digitize(args..), 'Expected'); t.end(); });
/** * Root Sagas */ import { all } from 'redux-saga/effects'; // sagas import authSagas from './Auth'; import localAsync from "./LocalAsync"; import profileSagas from './Profile'; import dashboardSagas from "./SegmentDashboard" import commsSagas from "./Comms" export default function* rootSaga(getState) { yield all([ authSagas(),localAsync(),profileSagas(),dashboardSagas(), commsSagas() ]); }
var data = require('../data.json'); exports.view = functions(req, res){ console.log(data); res.render('index'); }
const mongoose = require("mongoose") class Common{ constructor(){} //连接数据库 connect(){ mongoose.connect("mongodb://127.0.0.1:27017/Cosmetology",{ useNewUrlParser: true,useUnifiedTopology: true }) .then( ()=>{ console.log('数据库连接成功') }, err=>{ console.log('数据库连接失败',err) } ) } //封装新增数据的接口 async add(ctx,ModelName){ const doc=new ModelName(ctx.request.body) let result await doc.save() .then(data=>{ result={ code:0, msg:'新增成功', data:data } }) ctx.body=result } //封装查看详情的接口 async detail(ctx,ModelName,...popArray){ const _id=ctx.request.query._id let result await ModelName.find({_id:_id}) .populate(popArray[0]) .populate(popArray[1]) .populate(popArray[2]) .populate(popArray[3]) .then(data=>{ result={ code:0, msg:'查看详情', data:data } }) ctx.body=result } //封装查询数据的接口,接口参数只有page和limit async check(ctx,ModelName){ //分页参数 const query=ctx.request.query const skipNum=(query.page-1)*query.limit*1 const limitNum=query.limit*1 let result delete query['limit'] delete query['page'] //查询条件总数 let num=0; await ModelName.find(query).countDocuments().then(data=>{ num=data; }) await ModelName.find(query).skip(skipNum).limit(limitNum) .then(data=>{ result={ code:0, count:num, msg:'分页条件查询', data:data } }) ctx.body=result } //封装删除的接口,参数是_id,多个以逗号相隔 async del(ctx,ModelName){ const idArray=ctx.request.query._id.split(',') let result await ModelName.remove({_id:{$in:idArray}}) .then(data=>{ result={ code:0, msg:'删除成功', data:data } }) ctx.body=result } //封装修改的接口,参数是_id和其它参数 async change(ctx,ModelName){ const body=ctx.request.body let result await ModelName.update({_id:body._id},body) .then(data=>{ result={ code:0, msg:'修改成功', data:data } }) ctx.body=result } /* //封装查看详情的接口 门店详情 //其它接口 登陆shops/login 修改密码shops/password 充值members/investments 新增预约 修改预约 重点:如何发通知? */ } module.exports = new Common();
const PRECACHE = 'v1.0.0'; const RUNTIME = 'runtime'; // Service-Worker wird einmalig installiert, dann nur noch wenn Unterschiede zu vorherigem Service-Worker self.addEventListener('install', event => { // Event soll warten bis... event.waitUntil( // erstellt einen neuen Cache mit dem Namen PRECACHE caches.open(PRECACHE) // Promise welches ein CacheObject returned, zu cachende files werden übergeben .then(cache => cache.addAll([ 'https://cdn.jsdelivr.net/npm/bootstrap-dark-5@1.0.1/dist/css/bootstrap-night.min.css', 'https://cdn.jsdelivr.net/npm/marked/marked.min.js', '/app.js', '/app/html.js', '/app/proxy.js', '/app/store.js', '/app/components/login.js', '/app/components/logout.js', '/app/components/note.js', '/app/components/noteeditor.js', '/app/components/notelist.js', '/css/style.css', '/css/fontawesome-free-5.15.3-web/css/all.css', 'index.html', './' ])) // nicht auf die Antwort antworten .then(self.skipWaiting()) ); }); //wird aufgerufen beim aktivieren eines neuen Service-Workers , zum updaten self.addEventListener('activate', event => { const currentCaches = [PRECACHE, RUNTIME]; // Event soll warten bis... event.waitUntil( // gibt Promise(Array) zurück mit allen Cache Items caches.keys().then(cacheNames => { // gibt ein neues Array zurück mit allen veralteten Cache-Items return cacheNames.filter(cacheName => !currentCaches.includes(cacheName)); }).then(cachesToDelete => { // erzeugt Promise und geht das Array der veralteten Cache-Items durch return Promise.all(cachesToDelete.map(cacheToDelete => { // löscht das veraltete Cache-Item gibt Promise mit true zurück wenn erfolgreich return caches.delete(cacheToDelete); })); // alle Seiten akzeptieren den neuen Service-Worker ohne neuzuladen }).then(() => self.clients.claim()) ); }); // wird jedesmal aufgerufen wenn im Code fetch verwendet wird self.addEventListener('fetch', event => { if (event.request.method !== 'GET') { return; } if (!event.request.url.startsWith(self.location.origin)) { return; } event.respondWith( caches.match(event.request).then(cachedResponse => { if (cachedResponse) { return cachedResponse; } return caches.open(RUNTIME).then(cache => { return fetch(event.request).then(response => { return cache.put(event.request, response.clone()).then(() => { return response; }); }); }); }) ); });
/* * @Author: cash * @Date: 2021-08-31 16:20:11 * @LastEditors: cash * @LastEditTime: 2021-11-05 17:19:31 * @Description: file content * @FilePath: \hdl-try\src\api\api.js */ import http from '../utils/http' // /** * @parms request 请求地址 例如:http://197.82.15.15:8088/request/... * @param '/testIp'代表vue-cil中config,index.js中配置的代理 */ let userAuth = '/basis-footstone' let request = '/basis-footstone/mgmt' let community = '/community-footstone' let door = '/community-wisdom' // smart-footstone =>https://test-gz.hdlcontrol.com/smart-footstone // 登录接口 export function getListAPI (params) { return http.post(`${userAuth}/mgmt/user/oauth/login`, params) } // 登出接口 export function loginOut (params) { return http.post(`${request}/account/login/out`, params) } // 修改密码 export function moditifyPsd (params) { return http.post(`${request}/user/manage/updatePassword`, params) } // 发送验证码 export function sendCode (params) { return http.post(`${request}/main/verification/send`, params) } // 忘记密码 export function findPsd (params) { return http.post(`/basis-footstone/mgmt/user/oauth/forgetPwd`, params) } // 获取手机号或者邮箱 export function getUserInfoByAccont (params) { return http.post(`/basis-footstone/mgmt/user/oauth/getUserInfoByAccont`, params) } // 角色权限 export function roleAuth (params) { return http.post(`${request}/user/manage/getCompanyParterMenu`, params) } // 操作日志 export function logList (params) { return http.post(`${request}/main/operationLog/listByPage`, params) } export function systemList (params) { return http.post(`${request}/company/manage/getSysList`, params, false) } // 判断当前子系统是否有权限 export function checkoutSysAuth (params) { return http.post(`${request}/user/manage/checkCompanyParterSysInfo`,params,false) } // 产品分类 export function categoryList (params) { return http.post('/smart-footstone/mgmt/product/category/list', params, false) }
import React from 'react'; import { CardBody, CardTitle, CardText, CardSubtitle } from 'reactstrap'; import { withRouter } from 'react-router-dom'; const ChoreCard = (props) => { const handleClick = (event) => { props.history.push(`/chore/post/${props._id}`) } return( <CardBody style={{cursor: 'pointer'}} onClick={handleClick} data-index={props.index}> <CardTitle>{props.title}</CardTitle> <CardSubtitle>{props.schedules[0].date}</CardSubtitle> <CardText> {props.description} </CardText> </CardBody> ) } export default withRouter(ChoreCard)
import React, { useState } from "react"; import "./App.css"; import { BrowserRouter as Router, Switch, Route } from "react-router-dom"; import Offers from "./containers/Offers"; import Offer from "./containers/Offer"; import Header from "./components/Header"; import Footer from "./components/Footer"; import LogIn from "./components/LogIn"; import Cookies from "js-cookie"; const App = () => { // Nous allons initialiser l'état user à partir de ce qui se trouve dans les cookies // L'état `user` servira à sauvegarder l'utilisateur qui sera authentifié //on crée une variable const userCookie qui est égale à la valeur du cookie. Si user=Farid, Cookies.get("user")=Farid. const userCookie = Cookies.get("user"); console.log(userCookie); // Lorsque le cookie n'existe pas, la valeur vaut undefined const [user, setUser] = useState(userCookie); const [showModal, setShowModal] = useState(false); return ( <Router> <Header // on transmet des infos à l'enfant Header (user et fonctions logIn et logOut) user={user} // en cas de déconnection, on supprime le cookie "user", le useState passe de "userCookie" (valeur de user) => à "null" logOut={() => { Cookies.remove("user"); setUser(null); }} //en cas de déconnection, on enregistre le cookie pour la persistance des données logIn={obj => { Cookies.set("user", obj.name); //puis on sauvegarde l'état "user" pour déclencher un raffraichissement : setUser(obj); //l'obj est dans Header => name: "Claire" setShowModal(true); }} ></Header> {showModal === true && <LogIn></LogIn>} <Switch> <Route path="/offer/:identifiant"> <Offer user={user} /> </Route> <Route path="/"> <Offers user={user} /> </Route> </Switch> <Footer></Footer> </Router> ); }; export default App;
import React from 'react'; import RenderUsers from './renderusers' import UserProfile from './userprofile' import {connect} from 'react-redux' class AllUsers extends React.Component { state={ allusers:[], copiedArray:[], profile: false, user:[], search:'Search here for users with perticular skills' } componentDidMount(){ this.props.removeusers() fetch("https://handy-dandy-app.herokuapp.com/users",{ headers:{ 'Authorization': `${localStorage.token}` } }) .then(res => res.json()) .then(allusers => { allusers.map(user => { if (this.props.currentUser.id !== user.id){ this.props.addallusers(user) this.setState({allusers: [...this.state.allusers , user]}) this.setState({copiedArray: [...this.state.copiedArray , user]}) } }) }) } profile = (user) => { this.setState({profile:true, user: user}) } allusers = () => { this.setState({profile:false}) } searchBarClicked = () => { this.setState({search:''}) } filter = (e) => { this.setState({search:e.target.value}) this.setState({copiedArray:this.state.allusers.filter(user => ((user.skills.filter(skill=>skill.name.includes(e.target.value))).length) > 0 ? true : false)}) } render() { return ( !this.state.profile? <div className="AllUsersOnHomePage"> <div className="searchbar"> <input type='text' value={this.state.search} onChange={this.filter} onClick={this.searchBarClicked} /> </div> <RenderUsers allusers={this.state.copiedArray} profile={this.profile} history={this.props.history} /> </div> : <div className="UserProfileDiv"> <UserProfile user={this.state.user} allusers={this.allusers} backButton={this.allusers} /> </div> ) } } const mapStateToProps = (state) => { return { currentUser: state.currentUser, allUsersFromReducers: state.allUsers } } const mapDispatchToProps = (dispatch) => { return { addallusers: (user) => {dispatch({type : "allusers", payload:user })}, removeusers: (user) =>{dispatch({type:"removeusers", payload:user })} } } export default connect(mapStateToProps , mapDispatchToProps)(AllUsers);
import React from 'react'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import PropType from 'prop-types'; import '../../fontawesome'; export default function FirstDoctorCard({ name, specialty, workplace, address, email, phone, }) { return ( <div className="container flex flex-col items-center px-5 py-16 mx-auto md:flex-row"> <div className="w-5/6 lg:max-w-lg lg:w-full md:mb-0"> <img className="object-cover object-center rounded" src="https://cdn.benchmark.pl/uploads/article/72855/MODERNICON/4f91fb01300b74ba42dcf080665285f3f56bd4ff.jpg" alt="Sunset in the mountains" /> </div> <div className="flex flex-col items-center text-center lg:flex-grow lg:pl-24 md:pl-16 md:items-start md:text-left"> <div className="px-6 py-4 text-left "> <div className="mb-2 text-2xl font-bold"> <span>{name}</span> </div> <p className="text-xl text-gray-700"> <span>Specialty :</span> {specialty} </p> <p className="text-xl text-gray-700"> <span>Work Place :</span> {workplace} </p> <p className="text-xl text-gray-700"> <span>Address :</span> {address} </p> <p className="text-xl text-gray-700"> <span>Email :</span> {email} </p> <p className="text-xl text-gray-700"> <span>Phone :</span> {phone} </p> </div> <div className="px-6 pt-4 pb-2"> <FontAwesomeIcon className="text-lg text-black" icon={['fab', 'twitter']} /> <FontAwesomeIcon className="mx-3 text-lg" icon={['fab', 'facebook']} /> <FontAwesomeIcon className="mx-3 text-lg" icon={['fab', 'linkedin']} /> <FontAwesomeIcon className="mx-3 text-lg" icon={['fab', 'instagram']} /> </div> </div> </div> ); } FirstDoctorCard.propTypes = { name: PropType.string.isRequired, specialty: PropType.string.isRequired, workplace: PropType.string, address: PropType.string, email: PropType.string, phone: PropType.number, }; FirstDoctorCard.defaultProps = { workplace: 'dose not add work place yet', address: 'dose not add address yet', email: 'dose not add email yet', phone: 555555555555, };
const Generator = require('yeoman-generator'); const S = require('string'); const mkdirp = require('mkdirp'); const shell = require('shelljs'); module.exports = class extends Generator { constructor(args, opts) { super(args, opts); this.option('name', { type: String, required: true, desc: 'Package name', }); this.option('app', { type: String, required: true, desc: 'App name', }); } writing() { const app = this.options.app; const name = this.options.name; const capital = S(app).capitalize().s; const allcaps = app.toUpperCase(); this.fs.copy( this.templatePath('app/management/__init__.py'), this.destinationPath(`${app}/management/__init__.py`)); this.fs.copy( this.templatePath('app/management/commands/__init__.py'), this.destinationPath(`${app}/management/commands/__init__.py`)); this.fs.copy( this.templatePath('app/migrations/__init__.py'), this.destinationPath(`${app}/migrations/__init__.py`)); this.fs.copy( this.templatePath('app/models/__init__.py'), this.destinationPath(`${app}/models/__init__.py`)); this.fs.copy( this.templatePath('app/serializers/__init__.py'), this.destinationPath(`${app}/serializers/__init__.py`)); this.fs.copy( this.templatePath('app/staticapp/src/main.app.js'), this.destinationPath(`${app}/staticapp/src/main.app.js`)); this.fs.copy( this.templatePath('app/staticapp/src/theme/base.scss'), this.destinationPath(`${app}/staticapp/src/theme/base.scss`)); this.fs.copy( this.templatePath('app/staticapp/eslintrc.json'), this.destinationPath(`${app}/staticapp/.eslintrc.json`)); this.fs.copy( this.templatePath('app/staticapp/gitignore'), this.destinationPath(`${app}/staticapp/.gitignore`)); this.fs.copyTpl( this.templatePath('app/staticapp/package.json'), this.destinationPath(`${app}/staticapp/package.json`), { app }); this.fs.copyTpl( this.templatePath('app/staticapp/webpack-dev.config.js'), this.destinationPath(`${app}/staticapp/webpack-dev.config.js`), { app }); this.fs.copyTpl( this.templatePath('app/staticapp/webpack-prod.config.js'), this.destinationPath(`${app}/staticapp/webpack-prod.config.js`), { app }); this.fs.copy( this.templatePath('app/tasks/__init__.py'), this.destinationPath(`${app}/tasks/__init__.py`)); this.fs.copyTpl( this.templatePath('app/tasks/aws.py'), this.destinationPath(`${app}/tasks/aws.py`), { app }); this.fs.copy( this.templatePath('app/templates/app/home.html'), this.destinationPath(`${app}/templates/${app}/home.html`)); this.fs.copy( this.templatePath('app/templatetags/__init__.py'), this.destinationPath(`${app}/templatetags/__init__.py`)); this.fs.copy( this.templatePath('app/utils/__init__.py'), this.destinationPath(`${app}/utils/__init__.py`)); this.fs.copyTpl( this.templatePath('app/utils/api_auth.py'), this.destinationPath(`${app}/utils/api_auth.py`), { app }); this.fs.copyTpl( this.templatePath('app/utils/auth.py'), this.destinationPath(`${app}/utils/auth.py`), { app }); this.fs.copyTpl( this.templatePath('app/utils/aws.py'), this.destinationPath(`${app}/utils/aws.py`), { app }); this.fs.copy( this.templatePath('app/utils/importers.py'), this.destinationPath(`${app}/utils/importers.py`)); this.fs.copy( this.templatePath('app/views/__init__.py'), this.destinationPath(`${app}/views/__init__.py`)); this.fs.copyTpl( this.templatePath('app/views/home.py'), this.destinationPath(`${app}/views/home.py`), { app }); this.fs.copy( this.templatePath('app/viewsets/__init__.py'), this.destinationPath(`${app}/viewsets/__init__.py`)); this.fs.copyTpl( this.templatePath('app/__init__.py'), this.destinationPath(`${app}/__init__.py`), { app, capital }); this.fs.copy( this.templatePath('app/admin.py'), this.destinationPath(`${app}/admin.py`)); this.fs.copyTpl( this.templatePath('app/apps.py'), this.destinationPath(`${app}/apps.py`), { app, capital }); this.fs.copy( this.templatePath('app/celery.py'), this.destinationPath(`${app}/celery.py`)); this.fs.copyTpl( this.templatePath('app/conf.py'), this.destinationPath(`${app}/conf.py`), { app, capital, allcaps }); this.fs.copyTpl( this.templatePath('app/exceptions.py'), this.destinationPath(`${app}/exceptions.py`), { capital }); this.fs.copy( this.templatePath('app/signals.py'), this.destinationPath(`${app}/signals.py`)); this.fs.copyTpl( this.templatePath('app/urls.py'), this.destinationPath(`${app}/urls.py`), { app }); this.fs.copyTpl( this.templatePath('README.md'), this.destinationPath('README.md'), { name, app, allcaps }); mkdirp(`${app}/static/${app}/js`); mkdirp(`${app}/static/${app}/css`); } install() { shell.exec('yarn', { cwd: `${this.options.app}/staticapp/`, silent: true, }); } };
import * as Ons from 'react-onsenui'; import React, { Component } from "react"; const GListItem = ({onClick, img, id, title, desc, price, hasMinPrice = false}) => { return ( <Ons.ListItem key={id} onClick={onClick}> <div className="left" > <img src={img} className='list-item__thumbnail' /> </div> <div className="center"> <div style={{'width': '100%'}}> {title} </div> <div style={{'maxWidth': '100%', 'color': 'gray', 'fontSize': '11px'}}> {desc} </div> </div> <div className="right"> <div > { hasMinPrice && ( <div>от</div> ) } <div>{price}Р</div> </div> </div> </Ons.ListItem> ); } export default GListItem
import React, { Component } from 'react'; import { AsyncStorage, Alert } from 'react-native'; import AddItem from './addItem'; export default class AddItem2 extends Component { constructor(props) { super(props); this.state = { userId: '1', img: 'https://firebasestorage.googleapis.com/v0/b/mobishop-ffcff.appspot.com/o/items%2Fadd.png?alt=media&token=149c9514-d41c-47eb-a775-28f09c46a984', type: 'others', specficArr: [], specfic: '', checked: false, descrbtion: '', title: '', cost: '', showSpecfic: false }; } componentWillMount() { //this part to have the user id before the page render AsyncStorage.getItem('userId') .then((value) => { this.setState({ userId: value }); }) .catch((error) => { console.warn(error); }); } //this part save the changes in the input field onChange1(text) { this.setState({ descrbtion: text }); } //this part save the changes in the input field onChange2(text) { this.setState({ title: text }); } //this part save the changes in the input field onChange3(text) { this.setState({ cost: text }); } specficArr(arr) { this.setState({ specficArr: arr }); } supCategory(v) { this.setState({ specfic: v }); } //this part to save the new URL image for the user and show it UploudImage(imgUrl) { this.setState({ img: imgUrl }); } //this part to send all the item info and save it in the database done() { fetch('http://192.168.0.14:3000/addMerc', { method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'application/json' }, body: JSON.stringify(this.state) }) .then((data) => data.json()) .then((data) => Alert.alert(done)); } //this part to save the new URL image for the user and show it type(va) { this.setState({ type: va }); } render() { return ( <AddItem onChange1={this.onChange1.bind(this)} onChange2={this.onChange2.bind(this)} onChange3={this.onChange3.bind(this)} specficArr={this.specficArr.bind(this)} supCategory={this.supCategory.bind(this)} UploudImage={this.UploudImage.bind(this)} done={this.done.bind(this)} type={this.type.bind(this)} /> ); } }
/** * Created by uzer on 31.03.2017. */ require('./main.less');
import {useSelector} from 'react-redux' import './App.css'; import Product from './product/product'; import Filter from './filter/filter'; import Search from './search/search'; import Sort from './sort/sort'; import Basket from './basket/basket'; import Pages from './pages/pages'; import ApproveModal from './approveModal/approveModal' import logo from './assets/logo.png' function App() { const searchText = useSelector((state) => state.productSlice.searchText) return ( <div className="App"> <div className="head-grid"> <div className="logo"> <img className="logoImg" src={logo} alt="logo"/> </div> <div className="search"> <Search /> </div> <div className="basket"> <Basket /> </div> </div> <div className="sub-head-grid"> <div className="headText"> <h2>Telefon</h2> <div className="sameLine"> <p className="searchTitle">Aranan Kelime:</p> <p className="searchText">{searchText}</p> </div> </div> <div className="sort"> <Sort /> </div> </div> <div className="body-grid"> <ApproveModal/> <div className="filter"> <Filter /> </div> <div className="products"> <Product /> </div> </div> <div className="footer-grid"> <div className="pages"> <Pages /> </div> </div> </div> ); } export default App;
const josh1 = require("./assets/josh.jpg") const josh2 = require("./assets/josh2.jpg") const josh3 = require("./assets/josh3.jpg") const josh4 = require("./assets/josh4.jpg") const josh5 = require("./assets/josh5.jpg") const josh6 = require("./assets/josh6.jpg") const thoughtBubble = require ("./assets/clipart1425245.png") export const arr = [josh1, josh2, josh3, josh4, josh5, josh6] export const thought = thoughtBubble;
function createHeading(){ var Heading = { title: null, date: null, description: null }; return Heading; }
import { get } from 'lodash'; const getAddress = state => get(state, 'receiveFunds.address', ''); const getAmount = state => get(state, 'receiveFunds.amount', ''); const getPreSelectedReceiver = state => get(state, 'receiveFunds.preSelectedReceiver', null); export { getAddress, getAmount, getPreSelectedReceiver, };
import React, {Component} from 'react'; import { Link } from 'react-router'; const api = require('../utils/api.js'); const ReactGA = require('react-ga'); class Verify extends Component { constructor(props) { super(props); this.state = { message: ( <p data-qa="verify-text-pending">Verifying...</p> ) }; var email = this.props.location.query.email var verify = this.props.location.query.verify if(!email || !verify) { this.state = { message: ( <p data-qa="verify-text-failed">Unable to extract email and token from url</p> ) }; return } ReactGA.event({ category: 'Signup', action: 'User Verified' }); const _this = this; fetch(api.getApiAddress() + '/v1/auth/verifyUser', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ email: email, verify: verify }) }).then(function (response) { return response.json() }).then(function (json) { console.log('parsed json', json) if(json.verified) { _this.setState({ message: ( <div> <p data-qa="verify-text-confirmation">User verified.</p> <p>You may now <Link to="/login">Login</Link> and start using Dashvid.io</p> </div> ) }); } else { _this.setState({ message: ( <p data-qa="verify-text-failed">User verification failed.</p> ) }); } }).catch(function (ex) { console.log('parsing failed', ex) }) } render() { return this.state.message; } } export default Verify
function palindromeRearranging(inputString) { let h = {}; for (let i = 0; i < inputString.length; i++) { let char = inputString[i]; if (!h[char]) h[char] = 0; h[char]++; } if (inputString.length % 2 === 0) { return Object.values(h).every(val => val % 2 === 0) } else { let used = false; let vals = Object.values(h); for (let i = 0; i < vals.length; i++) { if (vals[i] % 2 !== 0) { if (used) return false; used = true; } } } return true; }
import Ember from 'ember'; export default Ember.Route.extend({ setupController: function(controller, model) { controller.set('model', model); controller.set('isSaving', false); controller.set('courses', this.store.all('course')); controller.set('selectedCourse', model.get('course.id')); controller.set('model.selectedWeight', model.get('weight.id')); }, deactivate: function() { this.get('controller.model').rollback(); } });
function insertion(A, N) { for (let i = 0; i < N; i++) { v = A[i]; j = i - 1; while (j >= 0 && A[j] > v) { A[j + 1] = A[j]; j--; } A[j + 1] = v; } return A; } insertion([5, 3, 2, 1], 4); console.log(insertion([5, 3, 2, 1], 4));
import React from 'react' //Import todos os componentes do './style' import * as S from './Header.styles'; import logo from '../../assets/paw.png'; const Header = (props) => { return ( <S.Container> <S.Logo> <img src={ logo } alt="" /> <S.Link href="/"> <h1>Pet Love</h1> </S.Link> </S.Logo> <S.Nav> <S.Link href="/Pets"> PETS </S.Link> <S.Link href="/QuemSomos">QUEM SOMOS</S.Link> <S.Link href="/Contato">CONTATO</S.Link> </S.Nav> </S.Container> ) } export default Header
/** * @author: @AngularClass */ 'use strict'; // Look in ./config for karma.conf.js const config = require('./.ng2-config'); config.src = '/'; module.exports = require('ng2-webpack-config').karma(config);