text
stringlengths
7
3.69M
'use strict'; // Register `availList` component, along with its associated controller and template angular. module('availList'). component('availList', { templateUrl: 'avail-list/avail-list.template.html', controller: ['Avail', '$scope', function AvailListController(Avail, $scope) { this.avails = Avail.query(); $scope.setFilter = function (key,value){ var filter = {}; filter[key] = value; return $scope.types = filter; }; $scope.resetFilter = function () { return $scope.types = ''; } } ] });
import Layout from '../views/layout/Layout' const finance = [{ path: '/finance', component: Layout, name: 'finance', redirect: '/finance/list', meta: { title: 'financeMgr', icon: 'el-icon-s-finance', code: '5' }, children: [{ path: 'list', name: 'financeList', meta: { title: 'financeList', icon: 'el-icon-s-finance', code: '5_1' }, component: () => import('@/views/finance/finance') }, { path: 'tixian', name: 'financeTixian', meta: { title: 'financeTixian', icon: 'el-icon-s-finance', code: '5_2' }, component: () => import('@/views/finance/tixian') }] }] export default finance
import React from "react"; import styles from "./MercuryParsed.css"; export default class MercuryParsed extends React.Component { render() { return <div> <div className={styles.background} onClick={this.props.close}> </div> <div className={styles.container}> <div className={styles.close} onClick={this.props.close}> <div className={styles.closeInner}>x</div> </div> <div className={styles.inner}> <div className={styles.header}> <div className={styles.title}> {this.props.children.title} </div> </div> <div className={styles.content} dangerouslySetInnerHTML={{__html: this.props.children.content}}> </div> </div> </div> </div>; }; };
import {createQueryBuilder, getRepository} from 'typeorm'; import {getConnection} from "typeorm"; import {Content} from '../entity/Content'; import {Provider} from '../entity/Provider'; import {Downloads} from '../entity/Downloads'; import {Category} from '../entity/Category'; import {Region} from '../entity/Region'; import {Client} from '../entity/Client'; import {ContentXType} from '../entity/ContentXType'; import {Country} from "../entity/Country"; import {ContentType} from '../entity/ContentType'; import {SubscriptionPlan} from "../entity/SubscriptionPlan"; import {User} from "../entity/User"; import {Calification} from "../entity/Calification"; import {IosCode} from "../entity/IosCode"; const IosCodeController = require('../controller/IosCodeController'); const MailController = require('../controller/MailController'); const auth = require('../config/auth'); async function upload(Title,Description,OwnerId,Price,Categorys,Regions,Subscriptions,Types,file,res) { try { if (file.originalname != "") { Title = Title + "." + file.originalname.split('.')[1]; } let newContent = new Content(); newContent.title = Title; newContent.description = Description; newContent.price = Price; let FullCategorys = []; for (var i = 0; i < Categorys.length; i+=1) { FullCategorys.push(await getRepository(Category).findOne({id: Categorys[i]})); } newContent.categories = FullCategorys; let FullRegions = []; for (var i = 0; i < Regions.length; i+=1) { FullRegions.push(await getRepository(Region).findOne({id: Regions[i]})); } newContent.regions = FullRegions; newContent.owner = await getRepository(Provider).findOne({id: OwnerId}); newContent.state = 0; newContent.location = file.path; newContent.size = file.size; await getRepository(Content).save(newContent); for (var i = 0; i < Types.length; i+=1) { let newContentXType = new ContentXType(); newContentXType.TypeId = Types[i]; newContentXType.ContentId = newContent.id; console.log(newContentXType); await getRepository(ContentXType).save(newContentXType); } for (var i = 0; i < Subscriptions.length; i+=1) { await getConnection() .createQueryBuilder() .insert() .into('subscription_plan_contents_content') .values([ { contentId: newContent.id, subscriptionPlanId: Subscriptions[i] } ]) .execute(); } return res.status(200).send(newContent); } catch (e) { return res.status(500).send({message:e.message}) } } async function getByState(req, res){ try { let list = await createQueryBuilder(Content, "content") .leftJoinAndSelect("content.categories","category") .where(`content.state = ${req.query.state}`) .getMany(); let newList = await Promise.all(list.map(async (item) => { let obj = item; obj.regions = await createQueryBuilder().select("rg").from("content_regions_region","crr") .from(Region,"rg") .where(`crr.contentId = ${item.id} and rg.id = crr.regionId`) .getRawMany(); obj.plans = await createQueryBuilder().select("sp").from("subscription_plan_contents_content","spcc") .from(SubscriptionPlan,"sp") .where(`spcc.contentId = ${item.id} and sp.id = spcc.subscriptionPlanId`) .getRawMany(); obj.types = await createQueryBuilder().select("type").from("content_x_type","cxt") .from(ContentType,"type") .where(`cxt.contentId = ${item.id} and type.id = cxt.typeId`) .getRawMany(); return obj; })); return res.status(200).send(newList); } catch (e) { return res.status(500).send(e.message) } } async function UploadFile(req, res){ try { return await getRepository(Content).find({where:{state:req.query.state}}); } catch (e) { return res.status(500).send(e.message) } } async function FileData(req, res){ try { let content = await getRepository(Content).findOne({id: req.contentid}); if(content){ let downloaded = await getRepository(Downloads).findOne({ where: { ClientId: req.clientid, ContentId: req.contentid } }); if(downloaded){ //ya se descargo antes console.log("already"); } else{ //actualizar tabla downloads console.log("registrar descarga"); let newDownload = new Downloads(); newDownload.ClientId = req.clientid; newDownload.ContentId = req.contentid; await getRepository(Downloads).save(newDownload); console.log(newDownload); } return content; } else{ return null; } } catch (e) { return res.status(500).send(e.message) } } async function respondRequest(req, res){ try { let content = await getRepository(Content).findOne({where:{id : req.body.contentId},relations:["owner"]}); console.log(content); let provider = await getRepository(Provider).findOne({where:{id:content.owner.id},relations:["user"]}); content.state = req.body.newState; await getRepository(Content).save(content); MailController.requestResponded(req.body.newState, content, provider.user ); return res.status(200).send(content); } catch (e) { return res.status(500).send(e.message); } } async function getAllContentCategory(req, res){ try { let newContents = {}; newContents.list = await getRepository(Content).find({ join: { alias: "content", leftJoinAndSelect: { category: "content.categories" } } }); newContents.categories = await getRepository(Category) .createQueryBuilder("category") .select("category.id") .addSelect("category.code") .addSelect("COUNT(*) AS count") .leftJoinAndSelect("category.contents", "content") .groupBy("category.id") .getRawMany(); //newContents.list = allCategories; //newContents.count = categoriesCount; return newContents; } catch (e) { return res.status(500).send(e.message) } } async function allContentLocation(req, res){ try { let countryId = req.ipInfo.country; let userCountry = await getRepository(Country).findOne({where:{code: countryId}, relations:["region"]}); let region = userCountry.region.id; let newContents = {}; newContents.list = await createQueryBuilder(Content, "content") .leftJoinAndSelect("content.categories","category") .leftJoin("content.regions", "region", "region.id = :regionId", { regionId:region }). where("content.state = 1") .getMany(); newContents.categories = await getRepository(Category) .createQueryBuilder("category") .select("category.id") .addSelect("category.code") .addSelect("COUNT(*) AS count") .leftJoinAndSelect("category.contents", "content") .groupBy("category.id") .getRawMany(); //newContents.list = allCategories; //newContents.count = categoriesCount; return res.status(200).send(newContents); } catch (e) { return res.status(500).send(e.message) } } async function findContent(contentId,clientId, res){ try { let content = await getRepository(Content).find({ relations: ["categories", "regions", "owner","payment"], where: {id: contentId} }); let suscripciones = await getConnection() .createQueryBuilder() .select() .from("subscription_plan_contents_content", "sus") .where("sus.contentId = :id", { id: contentId }) .getRawMany(); let client = await getRepository(Client).find({ relations: ["plan","user"], where: {id: clientId} }); let FlagPlan = false; let FlagDownload = false; let FlagBuy = false; let codeClientIos = null; if(clientId != 0) { for (var i = 0; i < suscripciones.length; i+=1) { if (suscripciones[i].subscriptionPlanId == client[0].plan.id){ FlagPlan = true; break; } } let downloaded = await getRepository(Downloads).findOne({ where: { UserId: client[0].user.id, ContentId: contentId } }); if (downloaded) FlagDownload = true; let comprados = await getConnection() .createQueryBuilder() .select() .from("user_contents_content", "cuu") .where("cuu.contentId = :id1", { id1: contentId }) .andWhere("cuu.userId = :id2", { id2: client[0].user.id }) .getRawMany(); console.log(comprados); if(comprados.length) FlagBuy = true; codeClientIos = await IosCodeController.getCodeUser(client[0].id,contentId); console.log(codeClientIos); } let calif = await getRepository(Calification).find({ContentId: contentId}); /* if(clientId != 0) { for (var j = 0; j < calif.length; j+=1) { let user = await getRepository(User).findOne({id: calif[i].UserId}); let client = await getRepository(Client).findOne({user: user}) calif[i].userinfo = { firstName: user.firstName, lastName: user.lastName, ClientId: client.id }; } } */ let CxT = await getRepository(ContentXType).find({ContentId: contentId}); let tipos = []; for (var j = 0; j < CxT.length; j+=1) { let cTypes = await getRepository(ContentType).findOne({id: CxT[j].TypeId}); if( CxT[j].TypeId === 4){ let count = await createQueryBuilder(IosCode, "ios").select("count(*)", "count") .where(`ios.assigned = 0 and ios.contentId = ${contentId}`).getRawMany(); console.log(count[0].count); cTypes.unassignedCodes = count[0].count; } tipos.push(cTypes); } var contenido = { FlagPlan : FlagPlan, FlagDownload : FlagDownload, FlagBuy : FlagBuy, info : content[0], types : tipos, calification: calif, iosCode:codeClientIos }; return res.status(200).send(contenido); } catch (e) { return res.status(500).send(e.message); } } async function FindAll(res){ try { let ListContent = await getRepository(Content).find({relations: ["categories", "regions", "owner","payment"]}); for (var i = 0; i < ListContent.length; i+=1) { let calif = await getRepository(Calification).find({ContentId: ListContent[i].id}); let CxT = await getRepository(ContentXType).find({ContentId: ListContent[i].id}); let tipos = []; for (var j = 0; j < CxT.length; j+=1) { tipos.push(await getRepository(ContentType).findOne({id: CxT[j].TypeId})); } ListContent[i].types = tipos; ListContent[i].calification = calif; let suscripciones = await getConnection() .createQueryBuilder() .select() .from("subscription_plan_contents_content", "sus") .where("sus.contentId = :id", { id: ListContent[i].id }) .getRawMany(); ListContent[i].suscripciones = suscripciones; } return res.status(200).send(ListContent); } catch (e) { return res.status(500).send(e.message) } } async function Calificate(userid,contentid,calification,description,res){ try { let newCalification = new Calification(); newCalification.UserId = userid; newCalification.ContentId = contentid; newCalification.calification = calification; newCalification.description = description; await getRepository(Calification).save(newCalification); return res.status(200).send(newCalification); } catch (e) { return res.status(500).send(e.message) } } async function Modificate(Id,Title,Description,Price,Categorys,Regions,Subscriptions,Types,res){ try { let content = await getRepository(Content).find({ relations: ["categories", "regions", "owner","payment"], where: {id: Id} }); content[0].title = Title + '.' + content[0].title.split('.')[1]; content[0].description = Description; content[0].price = Price; let FullCategorys = []; for (var i = 0; i < Categorys.length; i+=1) { FullCategorys.push(await getRepository(Category).findOne({id: Categorys[i]})); } content[0].categories = FullCategorys; let FullRegions = []; for (var i = 0; i < Regions.length; i+=1) { FullRegions.push(await getRepository(Region).findOne({id: Regions[i]})); } content[0].regions = FullRegions; let retorno = await getRepository(Content).save(content[0]); let ContentTypes = await getRepository(ContentXType).find({ where: {ContentId: Id} }); for (var i = 0; i < ContentTypes.length; i += 1){ await getRepository(ContentXType).remove(ContentTypes[i]); } for (var i = 0; i < Types.length; i+=1) { let newContentXType = new ContentXType(); newContentXType.TypeId = Types[i]; newContentXType.ContentId = Id; await getRepository(ContentXType).save(newContentXType); } await getConnection() .createQueryBuilder() .delete() .from('subscription_plan_contents_content') .where("contentId = :id", { id: Id }) .execute(); for (var i = 0; i < Subscriptions.length; i+=1) { await getConnection() .createQueryBuilder() .insert() .into('subscription_plan_contents_content') .values([ { contentId: Id, subscriptionPlanId: Subscriptions[i] } ]) .execute(); } content = await getRepository(Content).find({ relations: ["categories", "regions", "owner","payment"], where: {id: Id} }); return res.status(200).send(content); } catch (e) { return res.status(500).send({message:e.message}) } } async function findContentByOwner(OwnerId, res){ try { let Owner = await getRepository(Provider).findOne({id: OwnerId}); let ListContent = await getRepository(Content).find({ relations: ["categories", "regions", "owner"], where: {owner: Owner} }); for (var i = 0; i < ListContent.length; i+=1) { let calif = await getRepository(Calification).find({ContentId: ListContent[i].id}); let CxT = await getRepository(ContentXType).find({ContentId: ListContent[i].id}); let tipos = []; for (var j = 0; j < CxT.length; j+=1) { let cTypes = await getRepository(ContentType).findOne({id: CxT[j].TypeId}); if( CxT[j].TypeId === 4){ let count = await createQueryBuilder(IosCode, "ios").select("count(*)", "count") .where(`ios.assigned = 0 and ios.contentId = ${ListContent[i].id}`).getRawMany(); console.log(count[0].count); cTypes.unassignedCodes = count[0].count; } tipos.push(cTypes); } ListContent[i].types = tipos; ListContent[i].calification = calif; ListContent[i].plans = []; let suscripciones = await getConnection() .createQueryBuilder() .select() .from("subscription_plan_contents_content", "sus") .where("sus.contentId = :id", { id: ListContent[i].id }) .getRawMany(); ListContent[i].suscripciones = suscripciones; } return res.status(200).send(ListContent); } catch (e) { return res.status(500).send(e.message); } } //cuando se cree una nueva función que debe ser llamada por las rutas colocarlas caqui module.exports = { upload: upload, getByState: getByState, FileData: FileData, getAllContentCategory: getAllContentCategory, respondRequest: respondRequest, allContentLocation: allContentLocation, findContent: findContent, FindAll : FindAll, Calificate: Calificate, Modificate: Modificate, findContentByOwner: findContentByOwner };
module.exports = { fetchAllDrinks(success, source){ $.ajax({ url: "api/drinks", data: source, success(resp){ success(resp); } }); }, fetchSingleDrink(id, success){ $.ajax({ url: `api/drinks/${id}`, success(resp){ success(resp); } }); }, createDrink(form, data, success, error){ $.ajax({ url: "api/drinks", method: "POST", data: {drink: data}, success(resp){ success(resp); }, error(resp){ error(form, resp); } }); }, };
// packages installed const express = require("express"); const path = require("path"); const fs = require("fs"); const { v4: uuidv4 } = require("uuid"); // express app configured to port 3000 const app = express(); const PORT = process.env.PORT || 3000; app.use(express.urlencoded({ extended: true })); app.use(express.json()); // static files added to get rdata from public dir // https://expressjs.com/en/starter/static-files.html app.use(express.static(path.join(__dirname, "public"))); // routing app.get("/notes", (req, res) => res.sendFile(path.join(__dirname, "/public/notes.html")) ); // retrieve all note characters // https://expressjs.com/en/guide/routing.html app.get("/api/notes", (req, res) => { try { const data = fs.readFileSync(path.join(__dirname, "/db/db.json"), "utf8"); res.send(data); } catch (err) { console.error(err); } }); // deafault route added app.get("/", (req, res) => res.sendFile(path.join(__dirname, "/public/index.html")) ); app.get("*", (req, res) => res.sendFile(path.join(__dirname, "/public/index.html")) ); // new note building - body parsing middleware app.post("/api/notes", (req, res) => { const newNote = req.body; newNote.id = uuidv4(); try { // preData before processing let preData = fs.readFileSync(path.join(__dirname, "/db/db.json"), "utf8"); let noteArray = JSON.parse(preData); let uuid = uuidv4(); noteArray.push(newNote); const dataBaseFile = path.join(__dirname, "/db/db.json"); fs.writeFileSync(dataBaseFile, JSON.stringify(noteArray)); res.json(newNote); } catch (err) { console.error(err); } }); // delete note functionality app.delete("/api/notes/:id", (req, res) => { const id = req.params.id; let preData = fs.readFileSync(path.join(__dirname, "/db/db.json"), "utf8"); let noteArray = JSON.parse(preData); if (noteArray.length > 0) { // .some method to match id const search = noteArray.some((note) => note.id === id); if (search) { newNoteArray = noteArray.filter((note) => note.id !== id); const dataBaseFile = path.join(__dirname, "/db/db.json"); fs.writeFileSync(dataBaseFile, JSON.stringify(newNoteArray)); console.log(`Delete Note`); res.json(newNoteArray); } else { console.log(`Note Not Found`); res.json(`Note Not Found`); } } else { console.log(`No Data Stored`); res.json(`No Data Stored`); } }); // server init display listening port app.listen(PORT, () => console.log(`App listening on PORT ${PORT}`));
/*============================================ = Application / Global = ============================================*/ const RADIU = {}; // Alerts function alertUser(message, klass) { flash = $("<div></div>") .attr("class", "alert alert-" + klass) .attr("role", "alert") .text(message); $("#page-alerts").html(flash); } $(document).ready(function() { // Tables $(".table-sortable").stupidtable(); // Popovers $('[data-toggle="popover"]').popover(); }); /*===== End of Application / Global ======*/
sap.ui.jsview("root.view.App", { getControllerName: function () { return "root.view.App"; }, createContent: function (oController) { // to avoid scroll bars on desktop the root view must be set to block display this.setDisplayBlock(true); this.app = new sap.m.SplitApp(); //this.app.setMode(sap.m.SplitAppMode.StretchCompressMode); //this.app = new sap.m.App(); this.app.addMasterPage(sap.ui.jsview("emptyview", "root.view.Empty")); // load the login page var main = sap.ui.xmlview("mainview", "root.view.mainview"); main.getController().nav = this.getController(); this.app.addPage(main, false); this.app.setMode(sap.m.SplitAppMode.HideMode); // this.app.setMode(sap.m.SplitAppMode.StretchCompressMode); //this.app.hideMaster(); return this.app; } });
import React from 'react'; import Helmet from 'react-helmet'; const Services = () => { return ( <> <Helmet> <title>Services page</title> <meta name="description" content="services" /> <meta name="robots" content="INDEX,FOLLOW" /> </Helmet> <h2>Services page</h2> </> ) } export default Services;
var BaseUrl = "http://" + window.location.host; var SiteUrl = "http://" + window.location.host + "/shop"; // var ApiUrl = "http://121.196.201.195"; var ApiUrl = "http://" + window.location.host + "/mobile"; // var ApiUrl = "http://" + document.domain + "/mobile"; //121.196.201.195 var pagesize = 10; var WapSiteUrl = "http://" + window.location.host + "/wap"; var IOSSiteUrl = "http://" + window.location.host + "/app.ipa"; var AndroidSiteUrl = "http://" + window.location.host + "/app.apk"; // var BaseUrl = "<?php echo DATE?>"; // var SiteUrl = "http://192.168.0.99:8080/shop"; // var ApiUrl = "http://192.168.0.99:8080"; // //var ApiUrl = "http://" + window.location.host + "/mobile"; // // var ApiUrl = "http://" + document.domain + "/mobile"; // //121.196.201.195 // var pagesize = 10; // var WapSiteUrl = "http://192.168.0.99:8080/wap"; // var IOSSiteUrl = "http://192.168.0.99:8080/app.ipa"; // var AndroidSiteUrl = "http://192.168.0.99:8080/app.apk"; // auto url detection (function() { // var m = /^(https?:\/\/.+)\/wap/i.exec(location.href); var m = /^(https?:\/\/.+)\/wap/i.exec(location.href); if (m && m.length > 1) { SiteUrl = m[1] + '/shop'; ApiUrl = m[1] + '/mobile'; WapSiteUrl = m[1] + '/wap'; } })();
/** * HW 6-1 Write an aggregation query that will determine the number of unique companies with which an individual has been associated. **/ db.companies.aggregate( [ { $match: { "relationships.person": { $ne: null }}}, { $project: { name: 1, relationships: 1, _id: 0 } }, { $unwind: "$relationships" }, { $group: { _id: {person: "$relationships.person"}, unique: {$addToSet: "$name"}, count: {$sum: 1 } } }, { $project: { "_id": 1, unique_companies: {$size: "$unique"}, count: 1 }}, { $match: {"_id.person.permalink": "eric-di-benedetto"}}, { $sort: { count: -1 } } ]) /** * HW 6-2 There are documents for each student (student_id) across a variety of classes (class_id). Note that not all students in the same class have the same exact number of assessments. Some students have three homework assignments, etc. Your task is to calculate the class with the best average student performance. This involves calculating an average for each student in each class of all non-quiz assessments and then averaging those numbers to get a class average. To be clear, each student's average should include only exams and homework grades. Don't include their quiz scores in the calculation. **/ db.grades.aggregate([ { $match: {"class_id": {$ne: null}} }, { $project: { class_id: 1, scores: 1, student_id: 1, _id: 0}}, { $unwind: "$scores"}, { $match: {"scores.type": {$ne: "quiz"}} }, { $group: { _id: {class: "$class_id", student: "$student_id"}, average_per_student: {$avg: "$scores.score"} }}, { $group: { _id: {class: "$_id.class"}, average_per_class: {$avg: "$average_per_student"} }}, {$sort: { average_per_class: -1}} ]) /** * HW 6-3 For companies in our collection founded in 2004 and having 5 or more rounds of funding, calculate the average amount raised in each round of funding. Which company meeting these criteria raised the smallest average amount of money per funding round? You do not need to distinguish between currencies. **/ db.companies.aggregate([ {$match: { "founded_year": 2004}}, {$project: { _id: 0, name: 1, founded_year: 1, "funding_rounds.raised_amount": 1, num_rounds: { $size: "$funding_rounds"}} }, {$match: {"num_rounds": {$gte: 5}}}, {$unwind: "$funding_rounds"}, {$group: { _id: {name: "$name"}, average_per_round: {$avg: "$funding_rounds.raised_amount"} }}, {$sort: {average_per_round: 1}} ])
import React from "react"; const PersonForm = ({ onSubmit, newName, handleNameChange, newNum, handleNewNum, }) => { return ( <form onSubmit={onSubmit}> <h2>add a new</h2> <div> name: <input value={newName} onChange={handleNameChange} /> </div> <div> number: <input value={newNum} onChange={handleNewNum} /> </div> <div> <button type="submit">add</button> </div> </form> ); }; export default PersonForm;
import { Component, PropTypes } from 'react'; import { connect } from 'react-redux'; import Immutable from 'immutable'; import { getAuthorSelector } from './../../selectors/authors'; import { loadAuthorDetails } from './../../actions/authors'; class AuthorDetails extends Component { static propTypes = { author: PropTypes.instanceOf(Immutable.Map), loadAuthorDetails: PropTypes.func.isRequired, routeParams: PropTypes.object.isRequired, } componentWillMount() { this.props.loadAuthorDetails(this.props.routeParams.name); } render() { return ( <div> {'AuthorDetails'} </div> ); } } const mapStateToProps = (state, props) => ({ author: getAuthorSelector(state, props), }); export default connect(mapStateToProps, { loadAuthorDetails, })(AuthorDetails);
// common import Bridge from '../../common/sink/Bridge'; import Logger from '../../common/sink/Logger'; import DataRecorder from '../../common/sink/DataRecorder'; import SignalRecorder from '../../common/sink/SignalRecorder'; // client only import BaseDisplay from './BaseDisplay'; import BarChartDisplay from './BarChartDisplay'; import BpfDisplay from './BpfDisplay'; import MarkerDisplay from './MarkerDisplay'; import SignalDisplay from './SignalDisplay'; import SocketSend from './SocketSend'; import SpectrumDisplay from './SpectrumDisplay'; import TraceDisplay from './TraceDisplay'; import VuMeterDisplay from './VuMeterDisplay'; import WaveformDisplay from './WaveformDisplay'; export default { Bridge, Logger, DataRecorder, SignalRecorder, BaseDisplay, BarChartDisplay, BpfDisplay, MarkerDisplay, SignalDisplay, SocketSend, SpectrumDisplay, TraceDisplay, VuMeterDisplay, WaveformDisplay, };
var express = require('express'); var router = express.Router(); var company = require('../server/controllers/company'); /* GET company listing. */ router.get('/', function(req, res, next) { //console.log("first test"); company.getCompanyList(req,res); }); router.post('/', function(req, res, next){ //console.log("in company post"); //console.log(req.body); company.createCompany(req, res); /*if(req.user.type === "admin"){ //console.log("is an admin") company.createCompany(req,res); } else { res.status(401).json({code: 401, message: 'not authorized to create companies'}); }*/ }); router.get('/:companyname', function(req,res,next){ //console.log(req.user); //console.log(decodeURIComponent(req.params.companyname)); if(req.user.type === "contractor" || req.user.type === "admin"){ // user can get info on themselves or admin can see all companies company.getCompany(req,res); } else { res.status(401).json({code: 401, message: 'not authorized for requested info'}); } }); router.post('/:companyname', function(req,res,next){ if(req.user === req.params.username || req.user.type === 'admin'){ company.updateCompany(req,res); } else { res.status(401).json({code: 401, message: 'not authorized for the requested action'}); } }); /* router.delete('/:companyname', function(req, res, next){ company.deleteUser(req,res); }) */ module.exports = router;
import {Component} from "react"; import ReactDOM from "react-dom"; import {QueryString} from "../pack/util"; const List = class extends Component{ constructor(){ super(); this.getData = userClass => { $.ajax({ url : this.props.href, success : data => { userClass.setState({ currentIndex : this.props.index }); if(parseInt(QueryString("status")) !== this.props.index){ window.history.pushState({}, document.title, `/profit?status=${this.props.index}`); } userClass.props.callback(data, this.props.status); } }); }; } componentDidMount(){ let userClass = this.props.userClass; ReactDOM.findDOMNode(this).onclick = () => { if(this.props.index !== userClass.state.currentIndex){ this.getData(userClass); } }; } render(){ let userClass = this.props.userClass; return this.props.value + 0 ? ( <a className={this.props.index === userClass.state.currentIndex ? "current" : ""}> <h1> {this.props.name} </h1> <h2> {(this.props.value || 0).toFixed(2)} </h2> </a> ) : ( <a className={this.props.index === userClass.state.currentIndex ? "current" : ""}> {this.props.name} </a> ); } } const Tab = class extends Component{ constructor(props){ super(props); this.state = { currentIndex : props.currentIndex }; } componentDidMount(){ ReactDOM.findDOMNode(this.refs[`list${QueryString("status")}`]).click(); } shouldComponentUpdate(nextProps, nextState){ return this.state.currentIndex !== nextState.currentIndex; } render(){ let lists = [], setting = this.props.setting; setting.map((list, index) => { lists.push( <List userClass={this} ref={`list${index + 1}`} index={index + 1} name={list.name} value={list.value} href={list.href} status={index} key={index} /> ); }); return ( <menu className="tab"> {lists} </menu> ); } } Tab.defaultProps = { currentIndex : 0 }; export default Tab;
import React from 'react' import { Row, Col, Button } from 'react-bootstrap' export default function Footer() { return ( <Row style={{ backgroundColor: "#999", minHeight: '10vh', display: 'flex', alignItems: 'center' }}> <Col style={{ textAlign: "center" }}>Want to have a stall, contact or co-operate</Col> <Col style={{ textAlign: "center" }}> <Button variant="danger">GET IN TOUCH WITH US</Button> </Col> </Row> ) }
import React, { Component } from 'react' import { BigNumber } from 'bignumber.js'; export default class Index extends Component { componentDidMount() { /* * * 加 plus * 减 minus * 乘 multipliedBy * 除 dividedBy * */ /**decimalPlaces([dp[,rm]]) 精度调整 ** * dp 小数位数 * rm round mode: 0、1、4 * @return {BigNumber} 位数不够时,不补0; */ /**round mode * ROUND_UP 0 向远离0的方向舍入 * ROUND_DOWN 1 向零方向舍入 * ROUND_HALF_UP 4 两边距离相同时,远离0: 1.25->1.3 */ let x = new BigNumber(1.124); console.log(x.minus(new BigNumber(0.1))); x.plus(2); console.log(x.toNumber()); console.log(x > 2); console.log(x < 2); // console.log(typeof x); console.log(x.decimalPlaces(2, 0).toString()); // console.log(x.decimalPlaces(2, 1).toString()); // console.log(x.decimalPlaces(2, 4).toString()); /**toFixed(dp) * @return {string} 不会返回科学计数法;位数不够自动补零;dp不填时返回原数值 * @param dp 小数位数 */ // let y = new BigNumber(1e-7); // console.log(y.toFixed()); /**format */ console.log(new BigNumber('1e-9').abs().toFixed(8)); console.log(new BigNumber('-0.0001').abs()); console.log(new BigNumber(0.2).isGreaterThanOrEqualTo('0.1')); var aa = new BigNumber('0.01'); var bb = new BigNumber('0.01'); console.log(aa.comparedTo(bb)); console.log(bb.comparedTo(aa)); console.log(bb.isGreaterThanOrEqualTo(aa)); // comparedTo } render() { return ( <div> BigNumber </div> ) } }
import Vue from 'vue'; import swal from 'sweetalert2'; const DEFAULT_CONFIG = { confirmButtonText: 'OK', cancelButtonText: 'Cancel', reverseButtons: true, allowEnterKey: false, focusConfirm: false }; const WARNING_CONFIG = { type: 'warning', showCancelButton: true, titleText: '', text: '', confirmButtonColor: '#0269d9', }; const ERROR_CONFIG = { type: 'error', showCancelButton: false, titleText: 'Something went wrong', text: '', confirmButtonColor: '#0269d9' }; const SUCCESS_CONFIG = { type: 'success', showCancelButton: false, titleText: 'Something went wrong', text: '', confirmButtonColor: '#0269d9' }; Vue.prototype.$notify = (configuration = {}) => { const userConfiguration = { ...configuration, type: configuration.type || configuration.group, titleText: configuration.titleText || configuration.title, text: configuration.text }; const typeConfig = () => { switch (userConfiguration.type) { case 'warning': return WARNING_CONFIG; case 'error': return ERROR_CONFIG; case 'success': return SUCCESS_CONFIG; default: return {}; } }; return new Promise((resolve, reject) => { swal.fire({...DEFAULT_CONFIG, ...typeConfig(), ...userConfiguration}) .then(result => { if (result.value) { resolve(); } else { reject(new Error('Canceled')); } }); }); };
import React from 'react' function MemesGeneratorHeader() { return ( <header> <div className="container"> <h1 className="text-center">Memes Generator</h1> </div> </header> ) } export default MemesGeneratorHeader
class vec3 { constructor(x, y, z) { this.x = x; this.y = y; this.z = z; } get length() { return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z); } get sqrlen() { return this.x * this.x + this.y * this.y + this.z * this.z; } add(v) { return new vec3(this.x + v.x, this.y + v.y, this.z + v.z); } sub(v) { return new vec3(this.x - v.x, this.y - v.y, this.z - v.z); } mul(s) { return new vec3(this.x * s, this.y * s, this.z * s); } div(s) { return new vec3(this.x / s, this.y / s, this.z / s); } divv(v) { return new vec3(this.x / v.x, this.y / v.y, this.z / v.z); } mulv(v) { return new vec3(this.x * v.x, this.y * v.y, this.z * v.z); } dot(v) { return this.x * v.x + this.y * v.y + this.z * v.z; } cross(v) { return new vec3(this.y * v.z - this.z * v.y, this.z * v.x - this.x * v.z, this.x * v.y - this.y * v.x); } static norm(v) { let k = 1.0 / v.length; return new vec3(v.x * k, v.y * k, v.z * k); } static inv(v) { return new vec3(v.x, v.y, v.z); } static fromScalar(s) { return new vec3(s, s, s); } static zero() { return new vec3(0.0, 0.0, 0.0); } static unitX() { return new vec3(1.0, 0.0, 0.0); } static unitY() { return new vec3(0.0, 1.0, 0.0); } static unitZ() { return new vec3(0.0, 0.0, 1.0); } }
// Sample formController test // Inspired by the angular form directive tests at // https://github.com/angular/angular.js/blob/v1.2.x/test/ng/directive/formSpec.js // Load the app // Definition included in test for completeness var app = angular.module('FormApp', []); app.run(function($templateCache) { var form = []; form.push('<form name="myForm">'); form.push('<input name="input" ng-model="model" required ng-class="{invalid: myForm.input.$invalid}" />'); form.push('<input type="submit" ng-disabled="myForm.$invalid" />'); form.push('</form>'); var myForm = form.join(''); // This is equivalent to defining the template in html $templateCache.put('myForm.html', myForm); }); app.controller('formController', function() { // Empty controller body, we just need the definition }); describe('FormApp/formController', function() { var $compile, $rootScope, $templateCache; beforeEach(module('FormApp')); beforeEach(inject(function(_$compile_, _$rootScope_, _$templateCache_){ $compile = _$compile_; $rootScope = _$rootScope_; $templateCache = _$templateCache_; })); beforeEach(function() { this.scope = $rootScope.$new(); // Any html will do. For convenience we'll use the cache: var template = $templateCache.get('myForm.html'); // Save the angular.element to validate template behavior: this.element = $compile(template)(this.scope); // scope.myForm should now be a $formController expect(this.scope.myForm).toBeDefined(); // Run a digest to update formController state this.scope.$digest(); }); it('should invalidate form unless model value is set', function() { // Form is invalid without scope.model expect(this.scope.myForm.$valid).toBe(false); expect(this.scope.myForm.input.$valid).toBe(false); // with jqLite you can only select by tagname // var input = element.find('input').next(); // With jQuery you can use attribute selectors etc. var input = this.element.find('input[type="submit"]'); expect(input.attr('disabled')).toBeTruthy(); // Update model. Remember to run the digest for all changes this.scope.model = 'angular'; this.scope.$digest(); expect(this.scope.myForm.$valid).toBe(true); expect(this.scope.myForm.input.$valid).toBe(true); // And the DOM expect(input.attr('disabled')).toBeFalsy(); }); });
import React, { Component } from 'react'; import AutoForm from 'react-auto-form'; import styled from 'styled-components'; import { Box, Heading, Image, Text, Button, TextInput, Select, CheckBox, RadioButton, Anchor } from 'grommet'; import Layout from '../components/layout'; import Field from '../components/Field'; import NotifyLayer from '../components/NotifyLayer'; import { createPaste } from '../utils/api'; import { getVerifyHash } from '../utils/hash'; const EXPIRY_OPTIONS = { '10 minutes': '10M', '1 hour': '1H', '1 day': '1D', '1 week': '1W', '2 weeks': '2W', '1 month': '1M', }; export const BorderlessTextarea = styled.textarea` border: 0; font: inherit; padding: 16px 12px; min-height: 128px; outline: 0; &::placeholder { color: #aaa; } `; const CaptchaImage = styled(Image)` max-width: 180px; `; const NonPaddedAnchor = styled(Anchor)` padding: 0; `; export default class CreateForm extends Component { state = { loading: false, unlisted: true, expireSelect: true, expireNever: false, selectedExpiry: '1 day', } _onSubmit = async ({ title, text, captcha }) => { const { selectedExpiry, expireNever, unlisted } = this.state; const postBody = { title, text, privacy: unlisted === true ? 1 : 0, expiry: expireNever ? 'N' : EXPIRY_OPTIONS[selectedExpiry], captcha, }; try { const id = await createPaste(postBody); const hash = getVerifyHash(text); this.setState({ loading: false, notifySuccess: true, notifyMessage: ( <Text> <Heading level={3} margin={{ top: 'none' }}> Your paste has been created! </Heading> Use this link to share your paste:<br /> <Box margin={{ top: 'small' }}> <NonPaddedAnchor primary={true} href={`/p/${id}/${hash}`}> ➔ {id} </NonPaddedAnchor> </Box> </Text>), }); } catch (err) { this.setState({ loading: false, notifySuccess: false, notifyMessage: <Text>{(err && err.message) || 'Oops, an error occurred!'}</Text>, }); } } render() { const { notifyMessage, notifySuccess, loading } = this.state; const timezoneAbbr = new Date().toString().match(/\(([A-Za-z\s].*)\)/)[1]; return ( <Layout title='Create Paste'> <NotifyLayer message={notifyMessage} isSuccess={notifySuccess} onClose={() => { this.setState({ notifyMessage: null }); }} /> <AutoForm onSubmit={(ev, data) => { ev.preventDefault(); if (loading) return false; this._onSubmit(data); this.setState({ loading: true }); return false; }} trimOnSubmit > <Box> <Heading level={2} margin={{ top: 'none' }}> Create a new paste </Heading> <Box margin='none'> <Field label='Title'> <TextInput name='title' placeholder='Enter a fitting title' defaultValue={`Paste at ${new Date().toLocaleString()} ${timezoneAbbr}`} plain={true} /> </Field> <Field label='Content'> <BorderlessTextarea name='text' placeholder='The content of your paste goes here' /> </Field> <Field label='Expiry' direction='row'> <Box margin='small' direction='row'> <RadioButton label='' checked={this.state.expireSelect} onChange={() => { if (this.state.expireSelect) return; // already selected this.setState({ expireSelect: !this.state.expireSelect, expireNever: !this.state.expireNever, }); }} /> <Select size='medium' options={Object.keys(EXPIRY_OPTIONS)} value={this.state.selectedExpiry} onChange={({ option }) => { this.setState({ selectedExpiry: option, expireSelect: true, expireNever: false, }); }} /> </Box> <Box margin={{ horizontal: 'small', vertical: 'small', bottom: 'medium' }}> <RadioButton label='Never expire, keep it forever' checked={this.state.expireNever} onChange={() => { if (this.state.expireNever) return; // already selected this.setState({ expireNever: !this.state.expireNever, expireSelect: !this.state.expireSelect, }); }} /> </Box> </Field> <Field label='Privacy'> <Box pad='small' margin={{ bottom: 'small' }}> <CheckBox label='Do not list on Pastebin.com' checked={this.state.unlisted} onChange={() => { this.setState({ unlisted: !this.state.unlisted }); }} /> </Box> </Field> <Field label='Human check'> <CaptchaImage src='/captcha' /> <TextInput name='captcha' plain={true} placeholder='Enter the text displayed above' /> </Field> <Box margin={{ top: 'large' }}> <Button type={loading ? 'disabled' : 'submit'} label='Submit' primary={true} disabled={loading} /> </Box> </Box> </Box> </AutoForm> </Layout> ); } }
import React from "react" import axios from "axios" import { connect } from "react-redux" import FormContainer from "./Form/index" import Buttons from "./Buttons/index" import Joi from "joi-browser" import { Button, Modal, ModalHeader, ModalBody, ModalFooter } from "reactstrap" class CreatePartyPage extends React.Component { constructor(props) { super(props) this.state = { siteActive: '', eventLink: "", modal: false, errors: [] } this.errors = [] this.invalidForm = false this.checkIfSiteActive() this.createEvent = this.createEvent.bind(this) this.findNewEventAndSendConfirmation = this.findNewEventAndSendConfirmation.bind(this) this.validateAll = this.validateAll.bind(this) window.scrollTo(0, 0) this.schemaPartyEvent = { aTitle: Joi.string() .required() .error(errors => { return { message: "Rubrik saknas" } }), bName: Joi.string() .min(2) .max(20) .required() .error(errors => { return { message: "Namn måste innehålla minst 2 tecken" } }), cAge: Joi.number() .integer() .max(20) .required() .error(errors => { return { message: "Ålder måste vara mellan 1 och 20" } }) } this.schemaTimeAndPlace = { aDescription: Joi.string() .min(2) .max(280) .required() .error(errors => { return { message: "Information till de inbjudna måste innehålla 2-280 tecken." } }), bDate: Joi.date() .min(Date.now() + 604800000) .required() .error(errors => { return { message: "Ange datum för kalas - datumet måste vara en vecka framåt från dagens datum" } }), cTime: Joi.required().error(errors => { return { message: "Tid för kalaset saknas" } }), dStreet: Joi.string() .min(3) .max(30) .required() .error(errors => { return { message: "Adress för kalaset saknas" } }), eZip: Joi.string() .min(4) .max(5) .required() .error(errors => { return { message: "Postnumret för kalaset saknas" } }), fCity: Joi.string() .min(2) .max(40) .required() .error(errors => { return { message: "Stad för kalaset saknas" } }), gDeadline: Joi.date() .max(this.getDeadlineTime()) .required() .error(errors => { return { message: "Ange OSA - skriv när du senast vill ha svar om folk kan komma. Detta måste vara senast tre dagar innan kalaset" } }) } this.schemaAgreement = { userAgreement: Joi.boolean() .invalid(false) .required() .error(errors => { return { message: "Godkänn våra användaravtal" } }), gdprAgreement: Joi.boolean() .invalid(false) .required() .error(errors => { return { message: "Godkänn att vi hanterar dina personuppgifter" } }) } this.schemaGuestUser = { aFirstname: Joi.string() .min(2) .max(20) .required() .error(errors => { return { message: "Ange ditt förnamn" } }), bLastname: Joi.string() .min(2) .max(20) .required() .error(errors => { return { message: "Ange ditt efternamn" } }), eAddress: Joi.string() .min(3) .max(30) .required() .error(errors => { return { message: "Ange din adress" } }), fZipcode: Joi.string() .min(2) .max(20) .required() .error(errors => { return { message: "Ange ditt postnummer" } }), dPhonenumber: Joi.number() .integer() .required() .error(errors => { return { message: "Ange ditt telefonnummer" } }), gCity: Joi.string() .min(2) .max(20) .required() .error(errors => { return { message: "Ange din stad" } }), cEmail: Joi.string() .email({ minDomainSegments: 2 }) .error(errors => { return { message: "Ange din e-postadress" } }), password: Joi.string() .min(1) .max(30) .required() .error(errors => { return { message: "Fyll i ett lösenord, max 30 tecken" } }) } this.schemaSwish = { swishMoney: Joi.number() .integer() .min(50) .required() .error(errors => { return { message: "Beloppet för swish måste vara minst 50 kronor" } }) } } /** * Method to get correct validation for rsvp/deadline */ getDeadlineTime = () => { let deadline = new Date( this.props.birthdayTimeAndPlace.bDate ? this.props.birthdayTimeAndPlace.bDate : 0 ) deadline = deadline.getTime() - 172800001 return deadline } /** * Validation functions. * @param { * Data- Takes the data typed from the user. And validates it using Joi. * Errors- If any errors in validation it adds it to an array [] and displays it in the modal. * } */ validateBirthdayEvent = () => { const result = Joi.validate( this.props.birthdayEvent, this.schemaPartyEvent, { abortEarly: false } ) if (!result.error) return null //if there are errors: const errors = [] for (let item of result.error.details) { errors[item.path[0]] = item.message this.errors.push(item.message) } this.setState({ errors: this.errors }) } validateImageHandler = () => { let selectedImage = this.props.birthdayImage if (selectedImage) { } else { this.errors.push(["Välj bakgrundsbild till kalaset"]) this.setState({ errors: this.errors }) } } validateTimeAndPlace = () => { this.schemaTimeAndPlace.gDeadline = Joi.date() .min(Date.now()) .max(this.getDeadlineTime()) .required() .error(errors => { return { message: "Ange OSA - skriv när du senast vill ha svar om folk kan komma. Detta måste vara senast tre dagar innan kalaset" } }) const result = Joi.validate( this.props.birthdayTimeAndPlace, this.schemaTimeAndPlace, { abortEarly: false } ) if (!result.error) return null const errors = [] for (let item of result.error.details) { errors[item.path[0]] = item.message this.errors.push(item.message) } this.setState({ errors: this.errors }) } validatePresent = () => { let selectedPresent = this.props.present.id if (selectedPresent) { } else { this.errors.push(["Välj present"]) this.setState({ errors: this.errors }) } } validateFundraiser = () => { let isFundraiserSelected = this.props.fundraiser.buttonSelected if (isFundraiserSelected === true) { } else { this.errors.push(["Välj om du vill stötta en välgörenhet"]) this.setState({ errors: this.errors }) } } validateSwish = () => { const result = Joi.validate(this.props.swish, this.schemaSwish, { abortEarly: false }) if (!result.error) return null const errors = [] for (let item of result.error.details) { errors[item.path[0]] = item.message this.errors.push(item.message) } this.setState({ errors: this.errors }) } validateGuestUser = () => { const options = { abortEarly: false } const result = Joi.validate( this.props.guestUser, this.schemaGuestUser, options ) if (!result.error) return null const errors = [] for (let item of result.error.details) { errors[item.path[0]] = item.message this.errors.push(item.message) } this.setState({ errors: this.errors }) return errors } validateAgreement = () => { const result = Joi.validate(this.props.agreement, this.schemaAgreement, { abortEarly: false }) if (!result.error) return null const errors = [] for (let item of result.error.details) { errors[item.path[0]] = item.message this.errors.push(item.message) } this.setState({ errors: this.errors }) } /** * Checking all validation functions and showing a * modal (if validation did not pass) or proceeding to * Confirmation page */ async validateAll() { this.errors = [] this.validateBirthdayEvent() this.validateImageHandler() this.validateTimeAndPlace() this.validatePresent() this.validateSwish() this.validateFundraiser() this.validateGuestUser() this.validateAgreement() if (this.errors.length > 0) { this.toggle() await this.setState({ errors: this.errors }) } else { if (this.state.siteActive) { this.createEvent() } else { this.redirectTo('/tack-for-visat-intresse') } } } componentDidMount() { document.title = "Tojj - Skapa kalas" } checkIfSiteActive = () => { axios({ method: 'get', url: '/api/settings' }).then(data => this.setState({ siteActive: data.data.active })) } /** * Simple redirect function */ redirectTo = target => { this.props.history.push(target) } /** * Takes all the data thats written by the client. * If all validation passes it creates an event. (Birthday) * This using all the Redux data and sent it to the Backend and DB using Axios. */ async createEvent() { let link = await this.generateLink() let date = this.props.birthdayTimeAndPlace.bDate + " " + this.props.birthdayTimeAndPlace.cTime date = new Date(date).getTime() await axios({ method: "post", url: "/api/events", data: { title: this.props.birthdayEvent.aTitle, child: this.props.birthdayEvent.bName, age: this.props.birthdayEvent.cAge, image: "url('" + this.props.birthdayImage + "')", desc: this.props.birthdayTimeAndPlace.aDescription, date: date, rsvp: new Date(this.props.birthdayTimeAndPlace.gDeadline).getTime(), location: { street: this.props.birthdayTimeAndPlace.dStreet, zipcode: this.props.birthdayTimeAndPlace.eZip, city: this.props.birthdayTimeAndPlace.fCity }, swish: { number: "0708358158", amount: this.props.swish.swishMoney, color: "#4762b7" }, donate: this.props.fundraiser.donate, fundraiser: this.props.fundraiser.id, attending: [], product: this.props.present.id, link: link, guestUser: { firstName: this.props.guestUser.aFirstame, lastName: this.props.guestUser.bLastame, email: this.props.guestUser.cEmail, phoneNumber: this.props.guestUser.dPhonenumber, address: this.props.guestUser.eAddress, zipcode: this.props.guestUser.fZipcode, city: this.props.guestUser.gCity }, password: this.props.guestUser.password } }).then(data => { if (!data.name) { this.findNewEventAndSendConfirmation(link) this.redirectTo("/bekraftelse/" + link) } else { alert("ERROR:" + data.message, "please try again") } }) } async findNewEventAndSendConfirmation(eventLink) { let eventFromDb = await axios({ method: "get", url: `/api/events/populated/${eventLink}` }) await this.setContentAndSendEmail(eventFromDb.data) } /** * Long function with a template. * This to send emails to the client. */ setContentAndSendEmail = event => { const date = new Date(event.date).toLocaleDateString("sv-SE", { weekday: "short", day: "numeric", month: "long", hour: "numeric", minute: "numeric" }) const rsvp = new Date(event.rsvp).toLocaleDateString("sv-SE", { weekday: "short", day: "numeric", month: "long" }) const content = `<body style="margin: 0; padding: 30px 0; width: 100%; background-color: #fbf7ee; background-image: ${ event.image }"> <div style="padding: 30px 50px 50px; text-align: center; background: #fff; max-width: 600px; margin: 0 auto 15px; box-shadow: 0 0 5px 0px rgba(0,0,0,0.4)"> <img src="http://i.imgur.com/Rkdv6ca.png" alt="Välkommen på kalas" style="width: 80%; height: auto" /> <h1 style="font-weight: bold; color: #6C80C5; text-transform: uppercase">Hurra, ditt kalas <span style="text-transform: none;">${ event.link }</span> är nu skapat!</h1> <h4 style="font-weight: bold;">Klicka på knappen nedan för att gå direkt till kalaset eller klicka <a href="${window .location.origin + "/bekraftelse/" + event.link}">här</a> för att bjuda in gästerna.</h4> <h4 style="font-weight: bold; margin-bottom: 50px">Lösenord för kalaset: <span style="color: #6C80C5">${ this.props.guestUser.password }</span></h4> <a href="${window.location.origin + "/kalas/" + event.link}" style="word-wrap: none; text-decoration: none; font-size: 16px; font-weight: bold; background: #6C80C5; color: #fff; padding: 15px 30px; border-radius: 100px; opacity: 0.8; margin: 20px 0">TILL KALASET</a> </div> <div style="padding: 20px 50px; background: #fff; max-width: 600px; margin: 0 auto 15px; box-shadow: 0 0 5px 0px rgba(0,0,0,0.4)"> <h3 style="font-weight: bold; margin-bottom: 48px;">Sammanfattning</h3> <h4 style="font-weight: bold">Kalas</h4> <p>Rubrik: <span style="font-weight: bold;">${event.title}</span></p> <p>Födelsedagsbarn: <span style="font-weight: bold;">${ event.child }</span></p> <p>Fyller: <span style="font-weight: bold;">${event.age}</span> år</p> <p>Beskrivning: <span style="font-weight: bold;">${ event.desc }</span></p> <p>Datum & tid: <span style="font-weight: bold;">${date}</span></p> <p>OSA: <span style="font-weight: bold;">${rsvp}</span></p> <h4 style="font-weight: bold: margin-top: 48px;">Plats</h4> <p>Gata/plats: <span style="font-weight: bold;">${ event.location.street }</span></p> <p>Postkod: <span style="font-weight: bold;">${ event.location.zipcode }</span></p> <p>Stad: <span style="font-weight: bold;">${ event.location.city }</span></p> <h4 style="font-weight: bold: margin-top: 48px;">Present</h4> <p>Present: <span style="font-weight: bold;">${ event.product.name }</span></p> <p>Pris: <span style="font-weight: bold;">${ event.product.price }</span></p> <p>Swishbelopp: <span style="font-weight: bold;">${ event.swish.amount }</span></p> <p>Info: <span style="font-weight: bold;">${ event.product.desc }</span></p> ${ event.donate ? `<h4 style="font-weight: bold: margin-top: 48px;">Karma</h4> <p>Organisation: <span style="font-weight: bold;">${ event.fundraiser.name }</span></p> <p>Info: <span style="font-weight: bold;">${ event.fundraiser.desc }</span></p>` : "" } <h4 style="font-weight: bold: margin-top: 48px;">Personuppgifter</h4> <p>Förnamn: <span style="font-weight: bold;">${ event.guestUser.firstName }</span></p> <p>Efternamn: <span style="font-weight: bold;">${ event.guestUser.lastName }</span></p> <p>E-post: <span style="font-weight: bold;">${ event.guestUser.email }</span></p> <p>Telefonnummer: <span style="font-weight: bold;">${ event.guestUser.phoneNumber }</span></p> <p>Gata: <span style="font-weight: bold;">${ event.guestUser.address }</span></p> <p>Postnummer: <span style="font-weight: bold;">${ event.guestUser.zipcode }</span></p> <p>Stad: <span style="font-weight: bold;">${ event.guestUser.city }</span></p> </div> <div style="padding: 20px 50px; background: #fff; max-width: 600px; margin: 0 auto; box-shadow: 0 0 5px 0px rgba(0,0,0,0.4)"> <h4 style="font-weight: bold">Vad är Tojj?</h4> <p>Ingen mer stress kopplad till kalasfirande! Hos Tojj kan man skapa en digital kalasinbjudan och låta de inbjudna gästerna bidra till en bestämd present till födelsedagsbarnet. Enkelt för alla och som grädde på moset kan man välja att bidra till en välgörenhet.</p> <a href="${ window.location.origin }" style="text-decoration: none; color: #6C80C5">Läs mer ></a> </div> </body>` this.sendEmail(event.guestUser.email, content, event.title) } sendEmail = (email, message, subject) => { fetch("/api/send", { method: "POST", headers: { Accept: "application/json", "Content-Type": "application/json" }, body: JSON.stringify({ email: email, subject: `Bekräftelse för kalas: ${subject}`, message: message }) }) .then(res => res.json()) .then(res => { console.log("here is the response: ", res) }) .catch(err => { console.error("here is the error: ", err) }) } /** * Link will be equal to the first 2 letters of the * birthday child's name, uppercased. Followed by the age * they will turn and 3 random symbols. */ generateLink = () => { let link = [] const name = this.props.birthdayEvent.bName link.push(name.slice(0, 2).toUpperCase()) link.push(this.props.birthdayEvent.cAge) let saltArray = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890" saltArray = saltArray.split("") let salt = "" for (let i = 0; i < 3; i++) { let letter = saltArray[Math.floor(Math.random() * saltArray.length)] salt = salt + letter } link.push(salt) link = link.join("") this.setState({ eventLink: link }) return link } toggle = () => { this.setState(prevState => ({ modal: !prevState.modal })) } /** * Modal that is shown if there is any errors in the array. * The errors gets added from the validation. */ superModal = () => { const { errors } = this.state const allErrors = errors.map((error, i) => ( <li key={"validation_error_" + i}>{error}</li> )) return ( <div> <Modal isOpen={this.state.modal} toggle={this.toggle} className="validation-modal" > <ModalHeader className="modalHeader" toggle={this.toggle}> Fel har uppstått </ModalHeader> <ModalBody className="modalBody"> <ul>{allErrors}</ul> </ModalBody> <ModalFooter className="modalFooter"> <Button className="cpp-modal-button" color="secondary" onClick={this.toggle} > Stäng </Button> </ModalFooter> </Modal> </div> ) } render() { return ( <div className="createpartypage-wrapper"> <FormContainer /> <Buttons createEvent={this.validateAll} /> <div style={{ padding: "0 5vw" }}> <p style={{ position: "relative", width: "100%", maxWidth: "800px", fontWeight: "600", fontSize: "1.2rem", color: "#444655", fontFamily: "Montserrat", margin: "0 auto 80px", display: "block", padding: "30px", border: "5px dotted #B164B8" }} > Genom att klicka på "Godkänn" så ingår du i ett avtal med Tojj och pengarna som eventuellt samlas in kommer att hanteras av Tojj. Läs mer på{" "} <a href="/avtal" style={{ color: "#B164B8" }}> användaravtal och villkor </a> . </p> </div> {this.modalShow ? <Modal /> : ""} {this.superModal()} </div> ) } } const mapStateToProps = state => { return { birthdayEvent: state.birthday.birthdayEvent, birthdayImage: state.birthday.birthdayImage, birthdayTimeAndPlace: state.birthday.birthdayTimeAndPlace, fundraiser: state.birthday.fundraiser, present: state.birthday.present, swish: state.swish, guestUser: state.birthday.guestUser, agreement: state.agreement } } export default connect(mapStateToProps)(CreatePartyPage)
import React from 'react'; import { Layout, Menu } from 'antd'; import './App.css'; import { BrowserRouter, Route} from 'react-router-dom'; import { NavLink } from 'react-router-dom'; import Start from './components/Start/Start' import Introduction from './components/Introduction/Introduction' import Components from './components/Components/Components' import Props from './components/Props/Props' import ReactCreate from './components/ReactCreate/ReactCreate' import VirtualDOM from './components/VirtualDOM/VirtualDOM'; import Axios from './components/Axios/Axios' import Refs from './components/Refs/Refs' import Key from './components/Key/Key' import Events from './components/Events/Events' import LifeCycle from './components/LifeCycle/LifeCycle' import StateCom from './components/State/State' import ReactFragment from './components/ReactFragment/ReactFragment' import ReactMemo from './components/ReactMemo/ReactMemo' import useEffect from './components/useEffect/useEffect' import Router from './components/Router/Router' import Context from './components/Context/Context' import Forms from './components/Form/Form' import Task from './components/Task/Task'; const { Header, Content, Footer } = Layout; const App = () => { const list = ['Start','Task','Props', 'Axios','Refs','Key','Events', 'LifeCycle','State','ReactFragment', 'ReactMemo','useEffect','Router', 'Context', 'Form','VirtualDOM', 'Introduction','ReactCreate','Components']; const listComponents = [Start,Task,Props, Axios,Refs,Key,Events, LifeCycle,StateCom,ReactFragment, ReactMemo,useEffect,Router, Context, Forms,VirtualDOM, Introduction,ReactCreate,Components]; return <BrowserRouter> <Layout className="layout"> <Header> <div className="logo" /> <Menu theme="dark" mode="horizontal" defaultSelectedKeys={['0']}> {list.map((_, index) => { return <Menu.Item key={index}> <NavLink to={`/${_}`} >{_}</NavLink> </Menu.Item>; })} </Menu> </Header> <Content style={{ padding: '0 50px' }}> <div className="site-layout-content"> { list.map((el,i)=>{ return <Route key={i} path={`/${el}`} component={listComponents[i]}/> }) } </div> </Content> <Footer style={{ textAlign: 'center' }}>Ant Design ©2018 Created by Ant UED</Footer> </Layout> </BrowserRouter>}; export default App;
//Copyright 2012, John Wilson, Brighton Sussex UK. Licensed under the BSD License. See licence.txt function _3DEdge(startpoint,endpoint) { this.startpoint = Vector4.Create(startpoint) ; this.endpoint = Vector4.Create(endpoint) ; this.normal = Vector4.Create() ; this.vector = Vector4.Create() ; this.className = _3DEdge.className ; this.Init() ; } _3DEdge.className = "_3DEdge" ; _3DEdge.Create = function(startpoint,endpoint) { return new _3DEdge(startpoint,endpoint) ; } _3DEdge.prototype = { constructor: _3DEdge, Init: function() { this.vector.Subtract(this.endpoint,this.startpoint) ; }, SetNormal: function(normal) { this.normal.SetXyzw(normal.X(),normal.Y(),normal.Z(),0) }, Clone: function() { var newedge = _3DEdge.Create(this.startpoint,this.endpoint) ; newedge.SetNormal(this.normal) return newedge ; }, PointBehindEdge: function(point) { var v = Vector4.Create(point) ; v.Subtract(this.startpoint) ; return Vector4.Dot(v,this.normal) ; } }
import { headerView } from "../views.js" import DataServices from '../services/DataServices.js' export default class HeaderController { constructor(element) { this.element = element // header HTML element this.visitorname = DataServices.getAuthUserName() // obtengo el nombre del usuario registrado y que está viendo la web this.element.innerHTML = headerView(this.visitorname) // cargamos la estructura html del header this.tokenExists = DataServices.isAuthenticated() // ¿hay token almacenado? //console.log(this.tokenExists) if (this.tokenExists === true) { // si está autorizado... this.showLinks() } } showLinks() { document.getElementById("new-link").style.display = 'initial' // muestra el link "New Ad" document.getElementById("login-link").style.display = 'none' // oculta el link "Login/Registered" document.getElementById("profile-link").style.display = 'initial' // muestra el link para ir al profile dle } }
/* ------------------------ */ /* -- API Router -- */ /* ------------------------ */ exports.test = function(req,res) { db.Team.findAll({where: {status: 'active'}, attributes: ['short_name', 'id'] }).success(function(teams) { var picks = ["AFC-North-Bengals", "AFC-South-Colts", "AFC-East-Dolphins", "AFC-West-Chiefs", "NFC-North-Packers", "NFC-South-Saints", "NFC-East-Eagles", "NFC-West-49ers", "AFC-WC1-Browns", "AFC-WC2-Jaguars", "NFC-WC1-Vikings", "NFC-WC2-Buccaneers"] res.json({result: helpers.formatPicksForDB(teams, picks) }); }); }; exports.set_picks = function(req, res) { var picks = req.body.selections, week = req.body.week, lid = req.body.lid; var callback = function(err, picks) { if (err) { console.error("___ERROR___: createPicks callback - ",err); return res.json({success: false}); } else { console.log("___SUCCESS___: picks set - ",picks.values); return res.json({success: true }); } }; // If existing pick, destroy it, otherwise create new db.Pick.find({where: { week: CONSTANTS.WEEK_OF_SEASON, UserId: req.user.id }}).success(function(pick) { if (pick) { pick.destroy().success(function() { console.log("Destroyed old picks for [",req.user.fullName(),"] Week: ",CONSTANTS.WEEK_OF_SEASON); createPicks(picks, req.user, week, lid, callback); }); } else { createPicks(picks, req.user, week, lid, callback); } }); }; /* API - takes giant stringified odds object from admin and saves as entries in DB */ exports.set_odds = function(req, res) { var odds = JSON.parse(req.body.odds), teams = res.locals.teams; // fetched from middleware var ctr = teams.length; teams.forEach(function(team) { var odds_for_team = odds[team.id]; console.log('Odd for ',team.short_name,' -- ',odds_for_team," :: ",helpers.formatOddsForDB(odds_for_team)); db.Odd.find({where: { week: CONSTANTS.WEEK_OF_SEASON, TeamId: team.id }}).success(function(old_odd) { var callback = function() { console.log("Odd added for [",team.short_name,"]"); if (--ctr == 0) return res.json({success: true}); }, odd_data = { week: CONSTANTS.WEEK_OF_SEASON, odds: helpers.formatOddsForDB(odds_for_team), status: 'active', TeamId: team.id } if (old_odd) { old_odd.destroy().success(function() { console.log("Destroyed old odd for [",team.short_name,"]"); createOdd(odd_data, callback); }); } else createOdd(odd_data, callback); }); }); function createOdd(odd,callback) { db.Odd.create(odd).success(function(new_odd) { callback(); }); }; }; /* API - sets W/L record for all teams based on admin input */ exports.set_records = function(req, res) { var records = JSON.parse(req.body.records); console.log("Records:: ",records); db.Team.findAll().success(function(teams) { var counter = Object.keys(records).length; teams.forEach(function(team) { console.log(records[team.id].wins, records[team.id]) if (team.id in records) { team.updateAttributes({ wins: parseInt(records[team.id].wins), losses: parseInt(records[team.id].losses) }).success(function() { console.log("Updated W/L for [",team.short_name,"] ",team.record()); if (--counter == 0) return res.json({success: true}) }).error(function(err) { console.error("ERROR - saving records from admin - ",err); return res.json({success:false, error: "DB"}) }); } }); }); }; /* API - signs a user in (logic handled by passport middleware) */ exports.sign_in = function(req, res) { return res.redirect("/lobby") }; /* API - creates a new user + redirects */ exports.sign_up = function(req, res) { //var favoriteTeam = req.body.favoriteTeam, /* UNUSED */ var crypto = require('crypto'), hashed_pw = crypto.createHash('sha256').update(req.body.password.trim()).digest('hex'), in_onboarding = req.body.in_onboarding; function _error(err) { console.log("Err - ",err); return res.json({success:false, error: err.text}) }; function _createUser() { db.User.create({ first_name: req.body.firstName.trim(), last_name: req.body.lastName.trim(), password: hashed_pw, email: req.body.email.trim().toLowerCase(), // TODO : favorite team }).success(function(user) { req.logIn(user, function(err) { if (err) throw err; mailer.sendWelcomeEmail(user); if (in_onboarding === "true") { var makeSelections = function(err) { if (typeof err !== "undefined" && err) return res.json({success: false, error: err}); // Unparse stringified selections var selections = JSON.parse(req.body.selections); createPicks(selections, user, CONSTANTS.WEEK_OF_SEASON, req.body.league_id, function(err, picks) { if (err) { console.error("___ERROR___: createPicks callback - ",err); return res.json({success: false, error: { text: "Something went wrong saving your picks. Please try again."}}); } else { console.log("___SUCCESS___: picks set - ",picks.values); return res.json({success:true, next:'/dashboard/' + req.body.league_id}); } }) } // Create or join league if (req.body.is_commissioner) { createAndJoinLeague(user, req.body.league_id, makeSelections); } else { joinLeague(user, req.body.league_id, makeSelections); } } else { return res.json({success:true, next: '/lobby'}); } }); }); }; // Space validation if (req.body.firstName.length == 0 || req.body.lastName.length == 0 || req.body.password.length == 0 || req.body.email.length == 0) return _error({field:null, text:'No spaces, please.'}); db.User.find({where:{ email: req.body.email.trim().toLowerCase() }}).success(function(user) { if (user) return _error({field: "email", text: "There's already a Pony Up user registered with that email address, please use another."}) return _createUser(); }); }; /* API - creates a new league + redirects */ exports.create_league = function(req, res) { var name = req.body.title || null, password = req.body.password, user_exists = (typeof req.user !== "undefined") function _error(err) { return res.render("create_league", { errors: [err] }); }; if (!name) return _error({field: "title", text:"Missing title"}); db.League.find({where:{title: name}}).success(function(league) { if (league) return _error({field: "title", text:"A league with this title already exists. Please choose another."}) // Create league with or without user db.League.create({ title: name, password: password || null, UserId: (user_exists) ? req.user.id : null }).success(function(league) { if (user_exists) { league.addPlayer(req.user).success(function() { // Test league.getPlayers().success(function(players) { console.log("LEAGUE NOW HAS ",players.length," PLAYERS\n\n"); req.user.addLeague(league).success(function() { return res.redirect("/dashboard/" + league.id); }); }); }); } else { // Obfuscate league id var btoa = require('btoa'); return res.redirect("/sign_up?lid=" + btoa(league.id)); }; }); }); }; /* API - join league (from lobby) */ exports.join_league = function(req, res) { // ** note ** user may be undefined here, in which case just checking for password equality var league_id = req.body.league_id, password = req.body.password; if (password == "") password = null; // Dumb validation if (!league_id || isNaN(parseInt(league_id))) return res.json({success:false, error:"params"}); db.League.find({where:{id:league_id}}).success(function(league) { if (!league) return res.json({success:false, error:"missing league"}); if (league.password !== password) return res.json({success:false, error:"incorrect password"}); if (typeof req.user != "undefined") { league.addPlayer(req.user).success(function() { req.user.addLeague(league).success(function() { return res.json({ success: true }); }); }); } else { return res.json({ success: true }); } }); }; // API - creates match objects (all Redis) exports.set_matches = function(req, res) { var matches = JSON.parse(req.body.matches), new_match_ids = [], week_key = "week_" + CONSTANTS.WEEK_OF_SEASON + "_team_matches"; console.log("Adding Matches for [", week_key,"]::",matches); // Go clear_old_state(); function _error(msg) { return res.json({success: false, error: msg}); }; // 1. Delete any existing matches for this week if they exist function clear_old_state() { // Clear any existing matches db.client.del(week_key, function(err,reply) { if (err) return _error(err); return create_this_weeks_matches(); }); }; // 2. Delete to helper to create all matches function create_this_weeks_matches() { var counter = matches.length; matches.forEach(function(match) { db.client.incr("match_counter", function(err,reply) { if (err) return _error(err); create_single_match(parseInt(reply), match[0], match[1], function(err) { if (err) return _error(err); if (--counter == 0) { return append_match_ids_to_set() } }); }); }); }; // 3. Append all match ids to week list function append_match_ids_to_set() { db.client.sadd(week_key, new_match_ids, function(err,reply) { if (err) return _error(err); return res.json({success: true}); }); }; // Gets the ID needed function create_single_match(match_id, team_1, team_2, callback) { // Append ID to list new_match_ids.push(parseInt(match_id)) // Create match obj var match = { id: match_id, team1Id: team_1[0], team2Id: team_2[0], team1Points: team_1[1], team2Points: team_2[1], status: "pending", winnerId: null, week: CONSTANTS.WEEK_OF_SEASON }; db.client.hmset("match:" + match_id, match, function(err,reply) { if (err) return _error(); else console.log("Match Created: ",reply); callback(); }); }; }; exports.set_match_bets = function(req,res) { // Each bet takes the form of [match_id, team_id, points] var bets = JSON.parse(req.body.matches), new_bet_ids = [], week_key = "week_" + CONSTANTS.WEEK_OF_SEASON + "_team_bets"; if (!req.user) return res.json({success: false, error: "You must be signed in to place side-bets."}); // Go create_this_weeks_bets(); function _error(msg) { return res.json({success: false, error: msg}); }; // 1. Delegate to helper to create bets function create_this_weeks_bets() { var counter = bets.length; bets.forEach(function(bet) { db.client.incr("bet_counter", function(err,reply) { if (err) return _error(err); create_single_bet(parseInt(reply), bet, req.user.id, function(err) { if (err) return _error(err); if (--counter == 0) { return append_bet_ids_to_set() } }); }); }); }; // 3. Append all match ids to week list function append_bet_ids_to_set() { db.client.sadd(week_key, new_bet_ids, function(err,reply) { if (err) return _error(err); return res.json({success: true}); }); }; // Gets the ID needed function create_single_bet(bet_id, bet_data, user_id, callback) { // Append ID to list new_bet_ids.push(parseInt(bet_id)) // Create match obj var bet = { id: bet_id, userId: user_id, matchId: bet_data[0], teamId: bet_data[1], points: bet_data[2], week: CONSTANTS.WEEK_OF_SEASON, status: 'pending' }; db.client.hmset("bet:" + bet_id, bet, function(err,reply) { if (err) return _error(); else console.log("Bet Created: ",bet); callback(); }); }; }; /* --------------------------- */ /* --- PRIVATE HELPERS --- */ /* --------------------------- */ /* Inner Helper - create and join a league that is already stubbed */ function createAndJoinLeague(user, lid, callback) { db.League.find({where:{id: lid}}).success(function(league) { // TODO - error handling here... if (!league) callback("Missing league"); league.updateAttributes({UserId: user.id}).success(function() { league.addPlayer(user).success(function() { user.addLeague(league).success(function() { callback(); }); }); }); }); }; /* Inner Helper - join league */ function joinLeague(user, lid, callback) { db.League.find({where:{id: lid}}).success(function(league) { if (!league) callback("Missing league"); league.addPlayer(user).success(function() { user.addLeague(league).success(function() { callback(); }); }); }); }; /* Inner Helper - */ function createPicks(picks, user, week, lid, callback) { // TODO - ensure picks not already made this week -- if so, overwrite? db.Team.findAll({where: {status: 'active'}, attributes: ['short_name', 'id'] }).success(function(teams) { db.Pick.create({ picks: helpers.formatPicksForDB(teams, picks), status: 'active', week: week, UserId: user.id, // LeagueId: lid }).success(function(pick_set) { callback(null, pick_set); }).error(function(err) { callback(err); }); }); }
import React from "react" import styled from "styled-components" const NavbarC = (props) => ( <Wrapper className={props.className}> <MainWrap> <Header onClick={props.titleOnlick}>{props.title}</Header> <MenuWrap> {props.menus.map((v,i) => ( <MenuTitleWrap key={i} onClick={v.onClick}> <MenuTitle>{v.title}</MenuTitle> </MenuTitleWrap> ))} </MenuWrap> </MainWrap> </Wrapper> ) const Wrapper = styled.section` height: 60px; width: 100%; background-color: #24304e; display: flex; justify-content: center; align-items: center; @media (min-width: 0px) and (max-width: 960px) { justify-content: space-between; padding-left: 20px; padding-right: 20px; } `; const Header = styled.h2` color: white; margin: 0px; cursor: pointer; ` const MainWrap = styled.section` width: 960px; display: flex; justify-content: space-between; align-items: center; ` const MenuTitle = styled.p` margin: 0px; color: white; ` const MenuTitleWrap = styled.section` height: 4 0px; align-items: center; justify-content: center; display: flex; margin-left: 10px; padding: 10px; border-radius: 5px cursor: pointer; :hover{ background-color: #1e2842; } ` const MenuWrap = styled.section` display: flex; ` export default NavbarC
/* * grunt-mincer * https://github.com/pirxpilot/grunt-mincer * * Copyright (c) 2012 Damian Krzeminski * Licensed under the MIT license. */ var Mincer = require('mincer'); exports.init = function(grunt) { 'use strict'; var exports = {}; exports.mince = function(src, dest, include, helpers, engines, configure) { var environment, asset, err; function configureEngine(name) { var engine = Mincer[name + 'Engine'] || Mincer[name], opts = engines[name]; if (!engine || typeof engine.configure !== 'function') { err = 'Invalid Mincer engine ' + name.cyan; return true; } engine.configure(opts); } configure(Mincer); environment = new Mincer.Environment(process.cwd()); include.forEach(function(include) { environment.appendPath(include); }); Object.keys(helpers).forEach(function (key) { environment.registerHelper(key, helpers[key]); }); if (Object.keys(engines).some(configureEngine)) { return err; } asset = environment.findAsset(src); if (!asset) { return 'Cannot find logical path ' + src.cyan; } grunt.file.write(dest, asset.toString()); }; return exports; };
import React, { useState, useEffect } from 'react'; // TEMPORARY - Commenting out as this will be utilized once we render the implementation of the working activities display feature. Utilize components as necessary. // import { CurrentActivity } from './CurrentActivity'; // import { NextActivity } from './NextActivity'; export const CountDownTimer = () => { // This function will calculate difference between current and target times const calculateTimeRemaining = () => { let currTime = new Date(); // This variable will format current local time to pacific timezone (string) let pst = currTime.toLocaleString('en-US', { timeZone: 'America/Los_Angeles', weekday: 'short', month: 'short', day: '2-digit', year: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric', }); let endTime = new Date(); let today = new Date().getDay(); const countdownVar = { 0: 72, 1: 24, 2: 24, 3: 48, }; // Set endTime based on day of week (72, 48, 25 hour timers) endTime.setHours(countdownVar[today], 0, 0, 0); // parse var pst, changing it from string to number format, then subtract from endTime let timeDiff = endTime - Date.parse(pst); return timeDiff; }; // This function will convert the format for our time difference to HH:MM:SS const convertTimeFormat = time => { let timeVar = parseInt(time, 10); let hours = Math.floor(timeVar / (1000 * 60 * 60)); let minutes = Math.floor((timeVar / (1000 * 60)) % 60); let seconds = Math.floor(timeVar / 1000) % 60; return [hours, minutes, seconds] .map(v => (v < 10 ? '0' + v : v)) .filter((v, i) => v !== '00' || i > 0) .join(':'); }; const [timeRemaining, setTimeRemaining] = useState(calculateTimeRemaining()); useEffect(() => { const timer = timeRemaining > 0 && setTimeout(() => setTimeRemaining(calculateTimeRemaining()), 1000); return () => clearTimeout(timer); }, [timeRemaining]); return ( <div className="countdown-timer"> <div>Time Remaining: {convertTimeFormat(timeRemaining)}</div> </div> ); };
angular .module('altairApp') .controller("dataFormsController56", ['$scope', 'mainService', '$stateParams', function($scope, mainService,$stateParams) { /*mainService.withdomain("post", "/getPlanListByForm/181").then(function(data) { console.log(data); });*/ $scope.proleGrid1 = { dataSource: { transport: { read: { url: "/user/angular/DataExcelGeorep10", contentType: "application/json; charset=UTF-8", type: "POST", data:function(){ if ($stateParams.param != null && $stateParams.param != undefined && $stateParams.param > 0){ return {"custom":" where planid = " + $stateParams.param}; } }, }, parameterMap: function(options) { return JSON.stringify(options); } }, schema: { data: "data", total: "total", model: { id: "id", } }, pageSize: 1000, serverPaging: true, serverFiltering: true, scrollable: true, serverSorting: true, sort: [{ field: "id", dir: "asc" }, { field: "ordernumber", dir: "asc" }] }, filterable: false, sortable: true, resizable: true, pageable: { refresh: true, pageSizes: true, buttonCount: 5 }, columns:[ {field:"data1", title: "Д/д"}, {field:"data2", title: "Үзүүлэлт"}, {field:"data3", title: "Эхний үлдэгдэл"}, {field:"data4", title: "Нэмэгдсэн"}, {field:"data5", title: "Хасагдсан"}, {field:"data6", title: "Эцсийн үлдэгдэл"}, ], editable: false }; if ($stateParams.param == null || $stateParams.param == undefined){ $scope.proleGrid1.toolbar = ["excel", "pdf"]; $scope.proleGrid1.excel = {fileName: "Report.xlsx",allPages: true}; $scope.proleGrid1.dataSource.group = {field: "annualRegistration.lpName",dir: "desc"} } }]);
const path = require("path"); const router = require("express").Router(); const userRoutes = require("./userRoutes"); const projectRoutes = require("./projectRoutes"); const projectformRoutes = require("./projectformRoutes"); router.use("/users", userRoutes); router.use("/projects", projectRoutes); router.use("/projectForms", projectformRoutes); // For anything else, render the html page router.use(function(req, res) { res.sendFile(path.join(__dirname, "../../client/build/index.html")); }); module.exports = router;
const gulp = require('gulp'); const del = require('del'); gulp.task('clean-dev', function(cb) { del(['dist/dev/**']).then(function() { cb(); }); }); //clear all prod folders and tmp dir gulp.task('clean-prod', function(cb) { del(['.tmp/**', 'dist/prod/**']).then(function() { cb(); }); });
'use strict'; angular.module('app.channels') .controller('MessagesCtrl', ['$scope', 'ChannelMessages', 'Socket', 'Users', 'channel', 'messages', 'user', 'focus', function($scope, ChannelMessages, Socket, Users, channel, messages, user, focus) { var self = this; self.messages = messages; self.channelName = '# ' + channel.name; self.channel = channel; self.channels = $scope.channelsCtrl.channels; focus('message-box'); // Remove listenters that we may be subscribed to previously Socket.removeListener(); Socket.on('message', function(message) { if (message.channel == self.channel._id) { self.messages.push(message); } else { self.incrementMessageCount(message); } }); // Had to put this here since removal of listeners was nuking this // one from the channels controller Socket.on('channel:created', function(channel) { self.channels.push(channel); }); self.getCurrentChannel = function() { for (var i = 0; i < self.channels.length; i++) { var channel = self.channels[i]; if (channel._id == self.channel._id) { return channel; } } }; self.incrementMessageCount = function(message) { for (var i = 0; i < self.channels.length; i++) { var channel = self.channels[i]; if (channel._id == message.channel) { channel.messageCount = channel.messageCount !== undefined ? channel.messageCount + 1 : 1; } } }; var currentChannel = self.getCurrentChannel(); currentChannel.messageCount = null; self.message = ''; self.sendMessage = function() { var message = { user: user._id, body: self.message, channel: channel._id }; ChannelMessages.save({ channelId: channel._id }, { user: user._id, body: self.message }, function(data) { Users.get({ userId: message.user }, function(user) { message.user = user; message.created = Date.now(); Socket.emit('message', message); self.messages.push(message); }); self.message = ''; }); }; }]);
import React from 'react'; import FA from 'react-fontawesome'; import Tile from 'components/tiles/tile.js' import WebGL3D from './webGL3D.js'; import Cam from './cam.js'; export default class Print extends React.Component { constructor(props) { super(props); this.state = { } } static defaultProps = { showView: "overview" } render() { const showView = this.props.showView; var main = ( <Tile className="bg-success col-xs-12 col-sm-4 col-md-6" title="Druck • Übersicht" description="Vorgänge und aktuelle Situation beim Druck"> <a href="/admin/print" className="btn btn-success"> <FA name="print" className="px-1" size="3x"/> <FA name="list-alt" className="px-1" size="2x"/> </a> </Tile> ) switch (showView) { case "overview": return main; case "3d": return <WebGL3D />; case "cam": return <Cam />; default: console.log("FEHELER: Keine View Prop gesetzt. showView = " + showView); break; } } }
// let mainObject = { // a: 11, // b: 8, // c: { // x: 5, // y: { // g: 12, // h: 25, // i: 'опа-ча!', // j: null, // }, // }, // } // let mainObject = ['Привет', ['эта', 'хрень'], ['вроде', ['работает']]]; function copy(mainObject) { if(typeof mainObject !== 'object' || mainObject === null) { return mainObject; } else if (Array.isArray(mainObject)) { return mainObject.map((item) => copy(item)) } let newObject = {}; for (let key in mainObject) { newObject[key] = copy(mainObject[key]); } return newObject; }
/** * Created by nonesome on 16/3/31. */ ;(function(win) { var canvas=document.getElementById('canvas'); var ctx=canvas.getContext('2d'); var Round = { init: function() { Round._bind(); Round.canvas(); }, _bind: function() { var $sprite = $("#J_sprite"), $list = $("#J_btnList"); $list.on('click', '.btn', function() { var _this = $(this), id = Number(_this.attr("data-id")); $sprite.data('id', id); draw(id); }); $("#J_run").on('click', function() { var _this = $(this), id = Number($sprite.data("id")); var classArr = ['','line','parabola','round', 'ellipse']; $sprite[0].className = 'sprite'; setTimeout(function() { $sprite.addClass(classArr[id]); }, 0); }); function draw(id) { Round.canvas(); ctx.beginPath(); var x = 35, y = 35; switch (id) { case 1: ctx.moveTo(x, y); ctx.lineTo(x + 500, y + 200); break; case 2: ctx.moveTo(x, y); ctx.quadraticCurveTo(x + 500, y, x + 500, y + 200); break; case 3: ctx.moveTo(x + 100, y); ctx.arc(x + 100, y + 100, 100, -0.5*Math.PI, 1.5*Math.PI, true); break; case 4: x = x + 150; y = y + 100; var a = 150, b = 100; ctx.moveTo(x + a, y); //从椭圆的左端点开始绘制 var step = 1/a; for (var i = 0; i < 2 * Math.PI; i += step) { //参数方程为x = a * cos(i), y = b * sin(i), //参数为i,表示度数(弧度) ctx.lineTo(x + a * Math.cos(i), y + b * Math.sin(i)); } break; } ctx.stroke(); } }, canvas: function() { var x, y; ctx.clearRect(0, 0, 600, 600); ctx.beginPath(); ctx.moveTo(10, 10); ctx.lineTo(600, 10); ctx.lineTo(580, 0); ctx.moveTo(600, 10); ctx.lineTo(580, 20); ctx.moveTo(10, 10); ctx.lineTo(10, 300); ctx.lineTo(0, 280); ctx.moveTo(10, 300); ctx.lineTo(20, 280); for(var i = 0; i < 12; ++i) { x = 10 + i * 50; y = 0; ctx.moveTo(x, y); ctx.lineTo(x, 300); if(i < 6) { ctx.moveTo(y, x); ctx.lineTo(600, x); } } ctx.font = "40px Arial"; ctx.fillText("x", 580, 50); ctx.fillText("y", 20, 290); ctx.stroke(); } }; win.Round = Round; })(window);
AppController = FlowRouter.group({ triggersEnter: [function(context, redirect) { if(!Meteor.userId()) { Session.set("loginRedirectContext", "Redirect"); redirect('/'); } }] }); FlowRouter.route('/', { name: 'home', action() { BlazeLayout.render("HomeLayout", {main: "Home"}); } }); FlowRouter.route('/logout', { name: 'logout', action() { Accounts.logout(); FlowRouter.redirect('/'); } }); AppController.route('/products', { name: 'home', action() { BlazeLayout.render("HomeLayout", {main: "Products"}); } }); AppController.route('/recipes', { name: 'home', action() { BlazeLayout.render("HomeLayout", {main: "Recipes"}); } }); AppController.route('/new-recipe', { name: 'home', action() { BlazeLayout.render("HomeLayout", {main: "NewRecipes"}); } }); AppController.route('/menu', { name: 'home', action() { BlazeLayout.render("HomeLayout", {main: "Menu"}); } });
import { Link } from "react-router-dom"; function Welcome(props) { return ( <> <div className="heading"> <h1>Welcome to ScaffoldZoid</h1> </div> <div className="description"> <div className="image"> <img src="https://cdn.pixabay.com/photo/2014/08/01/08/31/oranges-407429_1280.jpg" alt="" /> </div> <div className="text"> <div className="about">About</div> <p> Orange is grown across the world in 41.96 lakh hectares with 684.75 lakh tonnes production which translates into 16.32 tonnes a hectare productivity according to FAO, 2009. It is the most commonly grown tree fruit in the world. <br /> India is the third largest producer of orange in the world. In India, specific cultivars of oranges are cultivated in different regions. For example, Coorg orange is typical to Coorg and Wayanad regions of Karnataka, whereas Nagpur orange is ideally suited for Vidarbha region. There is a need to ensure remunerative price to the orange producer and reduction in marketing cost. Marketing of oranges on cooperative basis can help the farmers in getting higher prices for their produce by eliminating intermediaries. Proper steps should be taken to link production, processing and marketing of oranges to avoid seasonal gluts. <br /> We provide a way to buisness out your oranges in market in a very convenient manner. Through our platform farmers, wholesalers, dealers can directly sell and purchase their product. </p> <h3>Grow Your Business With Our Unified Platform..</h3> </div> </div> <div className="button"> <b>You wanna :</b> <Link to="/sellerlogin"> <button className="btn">Sell Oranges</button> </Link> <Link to="/buyerlogin"> <button className="btn">Buy Oranges</button> </Link> </div> </> ); } export default Welcome;
$(document).ready(function() { var prewidth = 12; var windowHeight = $(window).height(); var menuBarHeight = $(".navbar-fixed-top").height() + $(".binMenuBar").height() + (($("section").outerHeight(true) - $("section").outerHeight()) / 2); var codeContainerHeight = windowHeight - menuBarHeight; $(".binCodeContainer").height(codeContainerHeight + "px"); $(".binToggle").click(function () { $(this).toggleClass("active"); var activeDiv = $(this).html(); activeDiv = activeDiv.slice(12, -4); $("#bin" + activeDiv + "Container").toggle(); var showingDivs = $(".binCodeContainer").filter(function () { return ($(this).css("display") != "none"); }).length; var width = 12 / showingDivs; $("#binHTMLContainer").removeClass("col-md-" + prewidth); $("#binCSSContainer").removeClass("col-md-" + prewidth); $("#binResultContainer").removeClass("col-md-" + prewidth); $("#binHTMLContainer").addClass("col-md-" + width); $("#binCSSContainer").addClass("col-md-" + width); $("#binResultContainer").addClass("col-md-" + width); prewidth = width; }); $("#binRunButton").click(function () { $("iframe").contents().find("html").html('<style>' + $("#binCssCode").val() + '</style>' + $("#binHtmlCode").val()); }); });
'use strict'; const debug = require('debug')('debug:new-user'); const User = require('../../model/user.js'); const testData = require('./test-data.js'); module.exports = function() { debug('creating new user'); return new User(testData.exampleUser) .generatePasswordHash(testData.exampleUser.password) .then(user => user.save()) .then(user => { return user.generateToken(); }); };
import React, { useState } from 'react' import PropTypes from 'prop-types' // import DrawerMenu from 'rc-drawer' import { Box, IconButton } from 'theme-ui' import { FaBars, FaTimes } from 'react-icons/fa' // import useScrollDisabler from '@components/useScrollDisabler' import Loadable from '@loadable/component' import './Drawer.css' const DrawerMenu = Loadable(() => import('rc-drawer')) const styles = { handler: { display: ['', '', 'none'], //to avoid ssr rehydration issue transition: `left 0.3s cubic-bezier(0.78, 0.14, 0.15, 0.86)`, left: -4 }, handlerOpen: { position: `fixed`, zIndex: 99999, left: 4, top: 4 }, content: { height: `full`, fontSize: 3, p: 4 } } const Drawer = ({ container, width, ...props }) => { const [open, setOpen] = useState(false) const handleSwitch = () => { setOpen(!open) } const handlerStyle = open ? { ...styles.handler, ...styles.handlerOpen } : styles.handler const handler = ( <IconButton onClick={handleSwitch} sx={handlerStyle} {...props}> {open ? <FaTimes /> : <FaBars />} </IconButton> ) return ( <> {/* {open && <ScrollDisabler />} */} {handler} <DrawerMenu width={width} open={open} getContainer={container} onHandleClick={handleSwitch} placement='right' > <Box sx={styles.content}>{props.children}</Box> </DrawerMenu> </> ) } export default Drawer Drawer.defaultProps = { width: 300, container: null } Drawer.propTypes = { width: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), container: PropTypes.instanceOf(PropTypes.element) }
class PointsBar extends HTMLElement{ constructor(){ super(); this.upvotes=0; this.downvotes=0; } static get observedAttributes(){ return ["vote","key",'upvotes','downvotes']; } connectedCallback() { this.upvotes=parseInt(this.getAttribute("upvotes")); this.downvotes=parseInt(this.getAttribute("downvotes")); this.vote=(this.getAttribute("vote")=="")?0:this.getAttribute("vote"); this.key=this.getAttribute("key"); this.innerHTML = ` <upvote-button></upvote-button> <p class="upvote-count">${bignumberkiller(this.upvotes)}</p> <downvote-button></downvote-button> <p class="downvote-count">${bignumberkiller(this.downvotes)}</p>`; $("upvote-button").attr('upvotes',this.upvotes); $("upvote-button").attr("clicked",(this.vote==1)?1:0); $("downvote-button").attr('downvotes',this.downvotes); $("downvote-button").attr("clicked",(this.vote==-1)?1:0); } } window.customElements.define("points-bar",PointsBar);
/* 🤖 this file was generated by svg-to-ts*/ export const EOSIconsFlightLand = { name: 'flight_land', data: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M2.5 19h19v2h-19zm7.18-5.73l4.35 1.16 5.31 1.42c.8.21 1.62-.26 1.84-1.06.21-.8-.26-1.62-1.06-1.84l-5.31-1.42-2.76-9.02L10.12 2v8.28L5.15 8.95l-.93-2.32-1.45-.39v5.17l1.6.43 5.31 1.43z"/></svg>` };
$(document).ready(function() { "use strict"; var av_name = "schematicRepCON"; var av = new JSAV(av_name); // Slide 1 av.umsg("Suppose that we have a regular expression $r$. We want to find a simple representation for the NFA that accepts $r$."); av.displayInit(); // Slide 2 av.umsg("The NFA should have a start state and a final state. (We can easily add a state to the NFA that all final states reach via a $\\lambda$ transition.)"); var leftMargin = 200; var topMargin = 0; var fa = new av.ds.FA({left: leftMargin, top: topMargin, width: 300, height: 200}); var startX = 50; var lambda = String.fromCharCode(955); var s = fa.addNode({value:"s", left: startX, top: 50}); var n1 = fa.addNode({value:" ",left: 100 + startX, top: 0}); var n2 = fa.addNode({value:" ",left: 100 + startX, top: 50}); var n3 = fa.addNode({value:" ",left: 100 + startX, top: 100}); var f = fa.addNode({value:"f", left: 200 + startX, top: 50}); fa.addEdge(n1, f,{weight: lambda}); fa.addEdge(n2, f,{weight: lambda}); fa.addEdge(n3, f,{weight: lambda}); toggleInitial(fa, s); toggleFinal(fa, f); av.step(); // Slide 3 av.umsg("To accept any regular exepression $r$, the NFA should start from $s$ and go through some inermediate states until it reaches the final state $f$."); var e1 = fa.addEdge(s, n1, {weight:" "}); e1.css({"stroke-dasharray": "."}); var e2 = fa.addEdge(s, n2, {weight:" "}); e2.css({"stroke-dasharray": "."}); var e3 = fa.addEdge(s, n3, {weight:" "}); e3.css({"stroke-dasharray": "."}); av.step(); // Slide 4 av.umsg("We can use this figure to represent the NFA that accepts the regular expression $r$."); fa.css({outline: "1px black solid", border: "10px transparent solid;"}); av.label("NFA that accepts $r$", {left: leftMargin + 80, top: 210}); av.recorded(); });
/* See license.txt for terms of usage */ define([ "firebug/firebug", "firebug/lib/trace", "firebug/lib/events", "firebug/lib/string", "firebug/debugger/debuggerLib", "firebug/debugger/script/sourceFile", "firebug/debugger/script/sourceLink", ], function(Firebug, FBTrace, Events, Str, DebuggerLib, SourceFile, SourceLink) { "use strict" // ********************************************************************************************* // // Constants var Cc = Components.classes; var Ci = Components.interfaces; var TraceError = FBTrace.toError(); var Trace = FBTrace.to("DBG_ERRORLOG"); // ********************************************************************************************* // // ErrorMessageObj Implementation /** * @object This object collects data about an error that happens in the content. It's used * by {@ErrorMessage} Domplate template as the data source. */ function ErrorMessageObj(message, href, lineNo, source, category, context, trace, msgId, colNumber) { this.message = message; this.href = href; this.lineNo = lineNo; this.source = source; this.category = category; this.context = context; this.trace = trace; this.msgId = msgId || this.getId(); this.colNumber = colNumber; this.sourceLoaded = !!source; } ErrorMessageObj.prototype = /** @lends ErrorMessageObj */ { getSourceLine: function(callback) { if (this.sourceLoaded) return this.source; var sourceFile = SourceFile.getSourceFileByUrl(this.context, this.href); if (!sourceFile) { TraceError.sysout("errorMessageObj.getSourceLine; ERROR no source file! " + this.href); return; } this.sourceLoading = true; return sourceFile.getLine(this.lineNo - 1, (line) => { this.sourceLoading = false; this.sourceLoaded = true; this.source = line; if (callback) callback(line); }); }, getSourceLink: function() { var ext = this.category == "css" ? "css" : "js"; return this.lineNo ? new SourceLink(this.href, this.lineNo, ext, null, null, this.colNumber) : null; }, resetSource: function() { if (this.href && this.lineNo != null) this.source = this.getSourceLine(); }, correctWithStackTrace: function(trace) { var frame = trace.frames[0]; if (frame) { this.href = frame.href; this.lineNo = parseInt(frame.line, 10); this.trace = trace; } }, getId: function() { return this.href + ":" + this.message + ":" + this.lineNo + ":" + (this.colNumber ? this.colNumber : ""); } }; // ********************************************************************************************* // // Helper Source Provider // xxxHonza: we might want to use tge {@link SourceProvider} if the following bug is fixed: // https://bugzilla.mozilla.org/show_bug.cgi?id=915433 /** * Helper source provider used to display source line for errors in case when * the Script panel is disabled. */ var SourceProvider = /** @lends SourceProvider */ { getSourceLine: function(context, url, lineNo, callback) { TraceError.sysout("errorMessageObj.SourceProvider.getSourceLine; " + url + " (" + lineNo + ")"); // Create debugger asynchronously, you can't start debugging when // a debuggee script is on the stack. context.setTimeout(this.onGetSourceLine.bind(this, context, url, lineNo, callback)); }, onGetSourceLine: function(context, url, lineNo, callback) { var line; DebuggerLib.withTemporaryDebugger(context, context.getCurrentGlobal(), function(dbg) { if (!dbg) { TraceError.sysout("errorMessageObj.SourceProvider.onGetSourceLine; " + "ERROR no debugger"); return; } var scripts = dbg.findScripts({url: url, line: lineNo}); if (!scripts.length) { Trace.sysout("errorMessageObj.SourceProvider.onGetSourceLine; " + "No script at this location " + url + " (" + lineNo + ")"); return; } // xxxHonza: sometimes the top level script is not found (only child script) :-( var script = scripts[0]; var startLine = script.startLine; var lines = Str.splitLines(script.source.text); Trace.sysout("errorMessageObj.SourceProvider.onGetSourceLine; scripts", scripts); // Don't forge to destroy the debugger. DebuggerLib.destroyDebuggerForContext(context, dbg); // Get particular line of the source code. var index = lineNo - startLine; if (index < 0 || index >= lines.length) { Trace.sysout("errorMessageObj.SourceProvider.onGetSourceLine; Line " + lineNo + " is out of range " + lines.length, source); return; } var line = lines[index]; Trace.sysout("errorMessageObj.SourceProvider.onGetSourceLine; " + "return source for line: " + lineNo + ", index: " + index + ", source start: " + script.startLine, script.source.text); if (callback) callback(line); // Dispatch event with fake sourceFile object as an argument, so the UI // (mainly the Console UI) can be updated and the source displayed. // See e.g. {@link ErrorMessageUpdater} var sourceFile = { context: context, href: url, loaded: true, lines: lines, isBlackBoxed: false, }; Events.dispatch(Firebug.modules, "onUpdateErrorObject", [sourceFile]); }); return line; }, } // ********************************************************************************************* // // Registration return ErrorMessageObj; // ********************************************************************************************* // });
var app = { initialize: function() { this.bindEvents(); }, bindEvents: function() { document.addEventListener('deviceready', this.onDeviceReady, false); }, onDeviceReady: function() { /*document.getElementById('myFetchBtn').addEventListener('click', app.checkForUpdate);*/ app.checkForUpdate() }, checkForUpdate: function() { chcp.fetchUpdate(this.fetchUpdateCallback); }, fetchUpdateCallback: function(error, data) { if (error) { console.log('错误代码: ' + error.code); console.log(error.description); return; } console.log('正则更新'); chcp.installUpdate(this.installationCallback); }, installationCallback: function(error) { if (error) { console.log('更新失败错误码 ' + error.code); console.log(error.description); } else { console.log('更新完成!'); } } }; app.initialize();
(function(){ "use strict"; angular .module("ngGamebase") .factory("gamesFactory", function($http){ function getGames(){ return $http.get('data/data.json') } return { getGames: getGames } }) })();
import { expect } from "chai"; import { render, cleanIt } from "reshow-unit"; import useMounted from "../useMounted"; describe("test useMounted", () => { afterEach(() => { cleanIt(); }); it("basic test", () => { let hackGlobal; const Foo = () => { hackGlobal = useMounted(); return null; }; const wrap = render(<Foo />); expect(hackGlobal()).to.be.true; wrap.unmount(); expect(hackGlobal()).to.be.false; }); });
import { RECIEVE_POST, NEW_POST } from "../actions/actionCreators"; export const initialState = { postscontent: { posts: [], newpost: [] }, postlistbtn: false, postdetailbtn: false, newpostbtn: false, npost: { title: "", body: "" } }; function posts(state = initialState.postscontent.posts, action) { switch (action.type) { case RECIEVE_POST: return [...state, ...action.posts]; case NEW_POST: return [...state, ...action.posts]; default: return state; } } export default posts;
head.load( {file:'node_modules/jquery/dist/jquery.min.js'}, {file:'node_modules/angular/angular.js'}, {file:'node_modules/angular-storage/dist/angular-storage.min.js'}, {file:'node_modules/angular-route/angular-route.min.js'}, {file:'node_modules/angular-filter/dist/angular-filter.min.js'}, {file:'node_modules/angular-sanitize/angular-sanitize.min.js'}, {file:'node_modules/angular-ui-bootstrap/ui-bootstrap-tpls.min.js'}, {file:'node_modules/ui-select/dist/select.min.js'}, {file:'node_modules/bootstrap/dist/js/bootstrap.min.js'}, // {file:'node_modules/blueimp-gallery/js/jquery.blueimp-gallery.min.js'}, // {file:'node_modules/blueimp-bootstrap-image-gallery/js/bootstrap-image-gallery.min.js'}, {file:'node_modules/underscore/underscore-min.js'}, {file:'node_modules/offline-js/offline.min.js'}, {file:'client/src/hotel/app/App.js'}, {file:'client/src/hotel/app/controllers/MainController.js'}, {file:'client/src/hotel/app/models/RoomModel.js'}, {file:'client/src/hotel/app/services/RoomService.js'}, {file:'client/src/hotel/login/Login.js'}, {file:'client/src/hotel/login/controllers/LoginController.js'}, {file:'client/src/hotel/user/User.js'}, {file:'client/src/hotel/user/controllers/TransferController.js'}, {file:'client/src/hotel/room/Room.js'}, {file:'client/src/hotel/room/controllers/RoomBoardController.js'}, {file:'client/src/hotel/room/controllers/AddRoomController.js'}, {file:'client/src/hotel/room/controllers/ExchangeRoomController.js'}, {file:'client/src/hotel/room/controllers/RoomManageController.js'}, {file:'client/src/hotel/room/controllers/CheckOutRoomController.js'}, {file:'client/src/hotel/room/controllers/CheckinRoomController.js'}, {file:'bower_components/angularPrint/angularPrint.js'}, {file:'client/src/hotel/hotel.js'} );
// pages/login/firstlogin/firstlogin.js var app = getApp(); Page({ /** * 页面的初始数据 */ data: { userinfo: null, image:null, index:"https://qczby.oss-cn-shenzhen.aliyuncs.com/others/login.jpg" }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () { }, /** * 生命周期函数--监听页面显示 */ onShow: function () { var that = this let url = "https://www.qczyclub.com/welcome/adver.png" wx.downloadFile({ url: url, success: (res) => { let temp = res.tempFilePath that.setData({ image: temp }) } }) }, /** * 生命周期函数--监听页面隐藏 */ onHide: function () { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function () { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { }, /** * 用户点击右上角分享 */ onShareAppMessage: function () { }, onGotUserInfo: function (e) { var that = this; wx.showToast({ title: '登录', icon: 'loading', duration:3000 }) //获取必要的变量 var userInfo = e.detail.userInfo; var appId = app.globalData.g_appID; var appSecret = app.globalData.g_appSecret; wx.login({ success: function (res) { console.log(res); wx.setStorage({ key: 'userInfo', data: userInfo }) console.log(userInfo) var code = res.code;//获取code这个code是实时变化的 if (code) { //userInfo是一个数组,这里会将这个数据发送到后台 console.log(code) that.getOpenId(code, appId, appSecret, userInfo); } }, fail: function () { console.log('登录失败!'); } }) }, getOpenId: function (code, appId, appSecret, userInfo) { var that = this; var url = 'https://www.qczyclub.com/code' wx.request({ url: url, data: { 'code': code }, method: 'POST', header: { 'content-type': 'application/x-www-form-urlencoded', }, success: function (res) { var openid = res.data.openid; if(openid){ console.log(openid); wx.setStorage({ key: 'openid', data: openid, }) that.sqluser(openid, userInfo) } else { console.log(res) wx.showToast({ title: '登陆失败,服务器故障请稍后重试', icon: 'none', duration: 1500 }) } }, fail: function (res) { console.log(res,'请求openID失败'); } }) }, sqluser: function (openid, userInfo) { var that = this; wx.request({ url: 'https://www.qczyclub.com/userqueryByid', method: 'POST', data: { "openid": openid }, header: { 'content-type': 'application/x-www-form-urlencoded' }, success: function (res) { // 寻找这个用户,如果没找到,就存入数据,作为注册用户使用 if (res.data.userbyid == 0) { that.sqlData(openid, userInfo); } else { wx.switchTab({ url: '../home/home', }) } }, fail: function (res) { console.log(res); } }) }, sqlData: function (openid, userInfo) { console.log(openid); console.log(userInfo); var that = this; wx.request({ url: 'https://www.qczyclub.com/userinsert', method: 'POST', data: { "openid": openid, "nickName": userInfo.nickName, "gender": userInfo.gender, "city": userInfo.city, "province": userInfo.province, "language": userInfo.language, "country": userInfo.country, "avatarUrl": userInfo.avatarUrl, }, header: { 'content-type': 'application/x-www-form-urlencoded' }, success: function (res) { console.log(res); console.log("上传数据成功"); wx.switchTab({ url: '../home/home', }) }, fail: function (res) { console.log(res); } }) }, })
import React from 'react'; // import { Link } from 'react-router-dom'; import './css/css/normalize.css'; import './css/css/bootstrap.min.css'; import './css/css/font-awesome.min.css'; import './css/css/main.css'; class Index extends React.Component{ render(){ return( <div> <p>Salom</p> </div> ) } } export default Index
document.getElementById("t1").innerHTML = test(); const createProfile = (name, age, gender) => ({ name, age, gender }); function test() { Object.keys(createProfile("test", 20, "M")); }
'use strict'; angular.module('reports') .config(function($stateProvider) { $stateProvider.state('reports.all', { url: '', templateUrl: 'app/reports/all/all.html', controller: 'ReportsAllCtrl', controllerAs: 'reportsAllCtrl', data: { label: 'Reports' } }); });
var searchData= [ ['main_20page',['Main Page',['../index.html',1,'']]], ['md_5frencoder',['MD_REncoder',['../class_m_d___r_encoder.html',1,'MD_REncoder'],['../class_m_d___r_encoder.html#af6c2681d275807aa35d05c77bbfcab7a',1,'MD_REncoder::MD_REncoder()']]], ['md_5frencoder_2ecpp',['MD_REncoder.cpp',['../_m_d___r_encoder_8cpp.html',1,'']]], ['md_5frencoder_2eh',['MD_REncoder.h',['../_m_d___r_encoder_8h.html',1,'']]] ];
import axios from 'axios' class AuthService { constructor() { this.app = axios.create({ baseURL: `${process.env.REACT_APP_BASE_URL}`, withCredentials: true }) } login = (mail, pwd) => this.app.post('/login', { mail, pwd }) signup = (mail, pwd, name) => this.app.post('/signup', { mail, pwd, name }) logout = () => this.app.get('/logout') isLoggedIn = () => this.app.post('/isLoggedIn') } export default AuthService
const Slider = ` <!-- ##### Hero Area Start ##### --> <section class="hero-area hero-post-slides owl-carousel"> <!-- Single Hero Slide --> <div class="single-hero-slide bg-img bg-overlay d-flex align-items-center justify-content-center" style="background-image: url(img/bg-img/front1.jpg);"> <!-- Post Content --> <div class="container"> <div class="row"> <div class="col-12"> <div class="hero-slides-content"> <h2 data-animation="fadeInUp" data-delay="100ms">Ý Cầu Nguyện của Đức Thánh Cha tháng 2/2019</h2> <p data-animation="fadeInUp" data-delay="300ms">Cầu xin cho mọi người có quảng đại đón tiếp những nạn nhân của việc buôn bán người,<br/> của việc cưỡng bức mại dâm và của bạo động.</p> <a href="#" class="btn crose-btn" data-animation="fadeInUp" data-delay="500ms">About Us</a> </div> </div> </div> </div> </div> <!-- Single Hero Slide --> <div class="single-hero-slide bg-img bg-overlay d-flex align-items-center justify-content-center" style="background-image: url(img/bg-img/interior2.jpg);"> <!-- Post Content --> <div class="container"> <div class="row"> <div class="col-12"> <div class="hero-slides-content"> <h2 data-animation="fadeInUp" data-delay="100ms">Giờ Lễ</h2> <p data-animation="fadeInUp" data-delay="400ms">Thứ Hai - Thứ Bảy: 8:00<br/> Thứ Năm - Thứ Sáu: 19:00<br/> Thứ Bảy: Lễ Vọng Chủ Nhật 17:30 <br/> Chủ Nhật: 7:30 ; 9:30 ; 11:30 và 13:30 <br/><br/> <b>Giải Tội:</b> Ngày thường: Sau thánh Lễ 8:00 - Thứ Bảy: 16:30 - 17:15 <br/> <b>Rửa tội trẻ em: </b>Lớp Giáo Lý: CN tuần thứ I 9:30 - 10:30 - Rửa Tội: Tuần II sau lễ 8:00 <br/> <b>Xức dầu bệnh nhân: </b>Hàng tháng sau Lễ CN thứ III<br/> <b>KHẨN CẤP: 770-910-2443</b> </p> <a href="#" class="btn crose-btn" data-animation="fadeInUp" data-delay="500ms">Contact Us</a> </div> </div> </div> </div> </div> </section> <!-- ##### Hero Area End ##### --> ` export default Slider
// hello.test.js, again import React from "react"; import { render, unmountComponentAtNode } from "react-dom"; import { act } from "react-dom/test-utils"; import pretty from "pretty"; import Login from "./login"; let container = null; beforeEach(() => { // setup a DOM element as a render target container = document.createElement("div"); document.body.appendChild(container); }); afterEach(() => { // cleanup on exiting unmountComponentAtNode(container); container.remove(); container = null; }); it("should render login form", () => { act(() => { render(<Login />, container); }); expect(pretty(container.innerHTML)).toMatchInlineSnapshot(` "<form class=\\"\\"> <div class=\\"form-group\\"><label class=\\"form-label\\" for=\\"formBasicEmail\\">Email address</label><input name=\\"email\\" placeholder=\\"Enter email\\" type=\\"email\\" id=\\"formBasicEmail\\" class=\\"form-control form-control-sm\\"><small class=\\"form-text\\">We'll never share your email with anyone else.</small></div> <div class=\\"form-group\\"><label class=\\"form-label\\" for=\\"formBasicPassword\\">Password</label><input name=\\"password\\" placeholder=\\"Password\\" type=\\"password\\" id=\\"formBasicPassword\\" class=\\"form-control\\"></div> <div class=\\"form-group\\"> <div class=\\"form-check\\"><input type=\\"checkbox\\" id=\\"formBasicCheckbox\\" class=\\"form-check-input\\"><label title=\\"\\" for=\\"formBasicCheckbox\\" class=\\"form-check-label\\">Check me out</label></div> </div><button type=\\"submit\\" class=\\"btn btn-primary\\">Submit</button> </form>" `); /* ... gets filled automatically by jest ... */ });
'use strict'; const bcrypt = require('bcrypt'); const User = require('../models/user'); const jwt = require('jsonwebtoken'); const config = require('../../config'); module.exports.create = (req, res, next) => { const query = User.findOne({ email: req.body.email }).exec(); query.then(function(user) { if(user) { const samePassword = bcrypt.compareSync(req.body.password, user.password); if(samePassword) { const userInfo = { email: user.email }; const token = jwt.sign(userInfo, config.secret, { expiresIn: '365d' }); res.json({ success: true, token: token }); } else { res.json({ success: false, message: 'Invalid credentials!' }); } } else { res.json({ success: false, message: 'Invalid credentials!' }); } }).catch(function(err){ let message = ''; for(let errName in err.errors) { message += err.errors[errName].message + ' ' } res.json({ success: false, message: message }); }); }
import React from 'react'; import style from './product-description.css'; import Heading from '../../tags/heading/heading.jsx'; import Poster from '../../tags/poster/poster.jsx'; import Button from '../../tags/button/button.jsx'; export default ({ title, href, className, children }) => ( <div className={['product-description', className].join(' ')}> <Heading tagName="h1">{title}</Heading> <p>{children}</p> <Button href={href}>Learn More</Button> </div> )
(function() { // 这些变量和函数的说明,请参考 rdk/app/example/web/scripts/main.js 的注释 var imports = [ 'rd.controls.Table','css!base/css/table3.0Style','css!rd.styles.IconFonts','rd.attributes.theme' ]; var extraModules = [ ]; var controllerDefination = ['$scope', main]; function main(scope) { scope.setting = { "columnDefs" :[ { title : "操作", targets:6, render : '<i class="iconfont iconfont-e8b7"></i>' } ] } } var controllerName = 'DemoController'; //========================================================================== // 从这里开始的代码、注释请不要随意修改 //========================================================================== define(/*fix-from*/application.import(imports)/*fix-to*/, start); function start() { application.initImports(imports, arguments); rdk.$injectDependency(application.getComponents(extraModules, imports)); rdk.$ngModule.controller(controllerName, controllerDefination); } })();
var RoboHydraHead = require("robohydra").heads.RoboHydraHead; var RoboHydraJsonHead = require("../robohydra-json-head").RoboHydraJsonHead; var find = require("lodash/fp").find; var cvs = require("./cvs"); exports.getBodyParts = function(conf) { return { heads: [ RoboHydraJsonHead('/cv', () => cvs), RoboHydraJsonHead('/cv/:id', (req,) => find({id: req.params.id}, cvs) ) ], scenarios: { serverProblems: { instructions: "Return a 500 to all queries", heads: [ new RoboHydraHead({ path: '/.*', handler: function(req, res) { res.statusCode = 500; res.send("500 - (Synthetic) Internal Server Error"); } }) ] }, slowHeads: { instructions: "Slow down all queries by 2 sec", heads: [ new RoboHydraHead({ path: '/.*', handler: function(req, res, next) { setTimeout(function() { next(req, res); }, 2000); } }) ] }, } }; };
import React from 'react'; import styled from 'styled-components'; import {FormattedMessage } from 'react-intl'; const H2 = styled.h2` text-align: center; margin: 20px auto; font-size: 2em; `; export default () => ( <H2><FormattedMessage id="PAGE_NOTFOUNT_VALUE"/> (404)</H2> );
export default (r, f, s) => { /** * @return {number} residence time */ const residence = () => { if (r) return r if (!f) throw new Error('Flow not defined.') return s / f } /** * @return {number} flow rate */ const flow = () => { if (f) return f if (!r) throw new Error('Residence not defined.') return s / r } /** * @return {number} stock */ const stock = () => { return s ? s : f * r } return { residence, flow, stock, } }
import React from "react"; import "./Featured.css"; const Featured = () => { return ( <div className="featured-wrapper"> <div className="featured-bottle"> <div className="featured-bottle-img"></div> <div className="featured-bottle-blob"></div> <div className="featured-bottle-ring"></div> <div className="featured-bottle-text"></div> </div> <div className="featured-details"> <h6>Best For:</h6> <ul> <li> <i class="fas fa-cannabis"></i> This is one of the most important benefits of CBD </li> <li> <i class="fas fa-cannabis"></i>This is one of the most important benefits of CBD </li> <li> <i class="fas fa-cannabis"></i>This is one of the most important benefits of CBD </li> </ul> <button>View Item</button> </div> <div className="featured-bg-overlay"></div> </div> ); }; export default Featured;
import React, {Component} from 'react'; import Country from './country'; require('../scss/style.scss'); class App extends Component { constructor() { super(); this.state = { search: '', imageSrc: '', country: '', countries: [] } } handleChange (event) { this.setState({search: event.target.value}); this.createList() } createList () { let sok = this.refs.searchInput.value let filteredCountries = this.props.countries.filter( (country) => { return country.country.toLowerCase().indexOf(sok.toLowerCase()) !== -1; } ) let topCountry = filteredCountries[0]; this.setState({ country: topCountry }) this.setState({ countries: filteredCountries }) this.getBackgroundImage(topCountry) } getBackgroundImage (topcountry) { if(topcountry) { let takeCountry = topcountry.country let Flickurl = "https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=376b144109ffe90065a254606c9aae3d&"; let tags = "&tags=" + takeCountry; let tagmode = "&tagmode=any"; let jsonFormat = "&format=json&nojsoncallback=1"; let FinalURL = Flickurl + tags + tagmode + jsonFormat; $.getJSON(FinalURL, function(photos) { let photo = photos.photos.photo[0]; if(photo) { let photoUrl = "https://farm" + photo.farm + ".staticflickr.com/" + photo.server + "/" + photo.id + "_" + photo.secret + ".jpg"; this.setState({ imageSrc: photoUrl }) } }.bind(this)); } } render() { if(this.state.search) { var containerStyle = { backgroundImage: 'url(' + this.state.imageSrc + ')', backgroundRepeat: 'no-repeat center center fixed', backgroundSize: 'cover', } } return ( <div className="container-fluid" style={containerStyle}> <div className="overlay"> <div className="container"> <div className="row"> <div className="col-sm-6 col-sm-offset-3"> <div id="search_container"> <h1 className="text-center">LAND</h1> <div className="input-group stylish-input-group"> <input type="text" ref="searchInput" value={this.state.search} onChange={this.handleChange.bind(this)} className="form-control" placeholder="Type country" /> <span className="input-group-addon"> <button type="submit"> <span className="glyphicon glyphicon-search"></span> </button> </span> </div> <div className={(!this.state.search ? 'hidden' : 'show')}>{this.state.countries.map((country) => { return <Country country={country} key={country.id} /> })} </div> </div> </div> </div> </div> </div> </div> ); } } export default App;
export const MSG = { INPUT_PLAYER: '자동자 이름을 입력해주세요.', MAX_PLAYER: '자동차 이름은 최소 1자에서 최대 5자까지 입력할 수 있습니다.', INPUT_COUNT: '시도 횟수를 입력해주세요.', FORWARD: '⬇️', CONGRATULATIONS: '🎇🎇🎇🎇축하합니다!🎇🎇🎇🎇', }; export const PLAYER_STATE = { FORWARD: 'forward', STOP: 'stop', };
import * as ActionTypes from '../redux/ActionTypes'; // const initialState = { // items: [], // item: {} // } export const FaReducer = (state = { isLoading: true, errMess: null, data: {} }, action) => { switch (action.type) { case ActionTypes.SUCCESS: return { ...state, isLoading: false, errMess: null, data: action.payload }; case ActionTypes.PENDING: return { ...state, isLoading: true, errMess: null, data: {} } case ActionTypes.ERROR: return { ...state, isLoading: false, errMess: action.payload }; default: return state; } };
var moduloT=angular.module("T",[]); var moduloA=angular.module("A",["T"]); var moduloB=angular.module("B",[]); var app=angular.module("app",["A","B"]); app.value("tamanyoInicialRectangulo",{ ancho:5, alto:3 }); function Rectangulo(tamanyoInicial) { this.ancho=tamanyoInicial.ancho; this.alto=tamanyoInicial.alto; this.setAncho=function(ancho) { this.ancho=ancho; } this.setAlto=function(alto) { this.alto=alto; } this.getArea=function() { return this.ancho * this.alto; } } app.service("rectangulo",['tamanyoInicialRectangulo',Rectangulo]); moduloB.value("matematicas_simples",{ sumar:function(a,b) { return a+b; }, restar:function(a,b) { return a-b; } }); moduloT.constant("miServicioConstante","Hola mundo desde constante"); var seguro= { nif:"", nombre:"nombre", coberturas : false }; var llamadahttps = function ($http,$scope){ $http({ method: 'GET', url: 'pruebaGet' }).success(function(data, status, headers, config) { $scope.trabajador = data; }).error(function(data, status, headers, config) { alert("Ha fallado la petición. Estado HTTP:"+status); }); } var pruebaModulos = function($scope) { $scope.cambioEnModulos =function () { $scope.mensaje = "cambio en modulos "; } }; var trabajador = { age : 1, name : "" }; app.factory("idioma",function() { return "es-es"; }); app.factory("matematicasSimplesFactory",function() { return { sumar:function(a,b) { return a+b; }, restar:function(a,b) { return a-b; } } }); app.factory("radio",function() { return 10; }); app.factory("area",function() { return function(radio) { return 3.1416*radio*radio; } }); app.constant("algoritmo","MD5"); function HashProvider () { var _algoritmo=""; this.setAlgoritmo=function(algoritmo) { _algoritmo=algoritmo; }; this.metodo= function (hash){ return hash + "haseando mi string"; } this.$get=function() { var funQueDevolveraMiProvider; if (_algoritmo==="MD5") { hashFunction=this.metodo; } else {//aqui podriamos meter mas tipos de funciones throw Error("El tipo de algoritmo no es válido:"+_algoritmo); } var funQueDevolveraMiProvider=function(message) { return hashFunction(message); } return funQueDevolveraMiProvider; } } app.provider("hash",HashProvider); app.config(["hashProvider","algoritmo",function(hashProvider,algoritmo) { hashProvider.setAlgoritmo(algoritmo); }]); var provincias=[ { idProvincia:2, nombre:"Castellón" }, { idProvincia:3, nombre:"Alicante" }, { idProvincia:1, nombre:"Valencia" }, { idProvincia:7, nombre:"Teruel" }, { idProvincia:5, nombre:"Tarragona" } ]; var pruebaController = function($scope,$log,$http,$timeout,miServicioConstante,matematicas_simples,rectangulo,matematicasSimplesFactory,area,radio,hash,provedorHttp){ $scope.mensaje = "ddsadsadsadsa"; $scope.trabajador = trabajador; $scope.aIncluir="/crm/resources/aIncluir.html"; $scope.provincias =provincias; $scope.cambiarMensaje = function () { $scope.mensaje = "12332113211321321"; $log.debug("cambiando cosas"); } $scope.llamada = function () { llamadahttps($http,$scope); } $scope.seguro = seguro; $timeout(function() { $scope.producidoEvento="2"; },2); $log.debug(miServicioConstante); $log.debug(matematicas_simples.sumar(4,5)); $log.debug(rectangulo.getArea()); $log.debug("-------------------------------------------------------------"); matematicasSimplesFactoryAUsar = matematicasSimplesFactory.sumar(3,2); $log.debug(matematicasSimplesFactoryAUsar); matematicasSimplesFactoryComplicado = area(radio); $log.debug(matematicasSimplesFactoryComplicado); $log.debug("-------------------------------------------------------------"); $log.debug("provider: "+ hash("metodoParaHash-")); var datos = provedorHttp( {method: "GET", url: "usuario/array"}, function(data, status, headers, config) { alert("entro"); return "HOLA"; //{error: false , data}; },function(data, status, headers, config) { alert("entro2"); return "HOLA1"; //{error: true ,data,status}; }); $log.debug("http "+ datos); } /* * * Servicio de get con provider configurado con un config * * */ app.constant("urlbase","/crm/"); function HttpProvider () { var _baseURL; this.setBaseURL = function(baseURL) { _baseURL=baseURL; }; this.$get=['$http',function ($http){ return function(datos, dataOK,dataError) { return $http({ method: datos.method, url: _baseURL + datos.url}) .success(function (data, status, headers, config){ return dataOK(data, status, headers, config); }) .error(function (data, status, headers, config){ return dataError(data, status, headers, config); }) ; } }]; }; moduloT.provider("provedorHttp",HttpProvider); app.config(["provedorHttpProvider","urlbase",function(provedorHttpProvider,urlbase) { provedorHttpProvider.setBaseURL(urlbase); }]); app.controller("PruebaController", pruebaController); moduloT.controller("PruebaModulos",pruebaModulos);
import React from "react" import '../index.css' function MyInfo(){ return ( <div id="myinfo"> <h1>Masnoon Junaid</h1> <p>All I do is a flex</p> <p>I don't need a reason</p> <ul > <li className="list">Japan</li> <li className="list">Turkey</li> <li className="list">Egypt</li> <li className="list">Maldive</li> </ul> </div> ) } export default MyInfo
import React from "react"; import ReactDOM from "react-dom"; import App from "./App"; import { BrowserRouter } from "react-router-dom"; import UserDataProvider from "./context/userDataProvider"; import MusicDataProvider from "./context/musicDataProvider"; ReactDOM.render( <BrowserRouter> <UserDataProvider> <MusicDataProvider> <App /> </MusicDataProvider> </UserDataProvider> </BrowserRouter>, document.getElementById("root") );
'use strict'; const dataAccessLayer = require('../sdk/db/dataAccessLayer.js'); const constants = require('../utilities/constants'); class Resolvers { constructor(dbLayer = dataAccessLayer) { this.dataAccessLayer = dbLayer; this.getDevice = this.getDevice.bind(this); this.getDevices = this.getDevices.bind(this); } async getDevice(args, context) { if (args.id){ args._id = args.id; delete args['id']; } let options = {index: 0, count: 1, query: args}; let res = await this.dataAccessLayer.getDocs(options, constants['DEVICE_COLLECTION']); return res[0]; } async getDevices(args) { let options = {index: args.index || 0, count: args.pageSize || 30}; let res = await this.dataAccessLayer.getDocs(options, constants['DEVICE_COLLECTION']); return res; } } // Resolvers.dataAccessLayer = dataAccessLayer; module.exports = new Resolvers();
import React,{ Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from './resource/connect'; class SwitchButton extends Component{ static propTypes = { themeColor: PropTypes.string, onSwitchColor: PropTypes.func } handleSwitch(color){ if(this.props.onSwitchColor){ this.props.onSwitchColor(color) } } render(){ return( <div> <button style = {{color: this.props.themeColor}} onClick = {this.handleSwitch.bind(this,'red')}>red</button> <button style = {{color: this.props.themeColor}} onClick = {this.handleSwitch.bind(this,'blue')}>blue</button> </div> ) } } const mapStateToProps = (state) => ({ themeColor: state.themeColor }) const mapDispatchToProps = (dispatch) => ({ onSwitchColor: (color) => { dispatch({ type: 'CHANGE_BUTTON_COLOR', themeColor: color }) } }) export default connect(mapStateToProps,mapDispatchToProps)(SwitchButton);
/* author:黄浩华 * date:2014年8月27日 15:57:29 * ver:0.3 * * 使用前:必须在引用jq后引用此js * * 使用案例: * var popup=new H.showpopup({ title:"欢迎", text:"欢迎使用红棉", vertical:"bottom", Horizontal:"right", width:200, color:"red", closeEvent:"delet", isBlack:false, }); */ var H=function(){ this.showpopup; return this; } H.showpopup=function(atrs){ this.title=atrs.title?atrs.title:"欢迎";//类型:string; 标题 this.text=atrs.text?atrs.text:"欢迎使用红棉";//类型:string; 正文 this.vertical=atrs.vertical?atrs.vertical:"center";//类型:string;值:top/center/bottom; 纵向位置 this.Horizontal=atrs.Horizontal?atrs.Horizontal:"center";//类型:string;横向位置:left/center/right; 横向位置 this.width=atrs.width?atrs.width:200;//类型:number; 弹窗宽度 this.color=atrs.color?atrs.color:false;//类型:string;值:red/white 弹窗颜色 this.closeEvent=atrs.closeEvent?atrs.closeEvent:false;//类型:string; 关闭弹窗后调用的的方法,这个方法必须在主页面上,而且不能在其它function里 this.isBlack=atrs.isBlack?atrs.isBlack:false;//类型:boolean; 是否用暗色透明的蒙版挡住页面原内容 var messagerbubble = "<div id='h_message' style='position:fixed;z-index:1002;'>" + "<div class='popup' style='position:fixed;width:370px; border:3px solid #8c8c8c; background-color: #ffffff; z-index:1002;'><div style='height: 34px;background: url(images/img/alert_bg.png) repeat-x;'>" + "<i style='padding-left:15px; font-style:normal; line-height:32px;'>" + this.title + "</i>" + "<p class='close_p' style='float: right;margin: 6px 8px auto auto;width: 25px;height: 25px;background: url(images/img/close.png) no-repeat;display: block;cursor: pointer;'></p>" + "</div>" + "<span style='padding: 10px 15px 10px 15px;text-indent:2em;display: inline-block;'>" + this.text + "</span></div>"; if(this.isBlack){ messagerbubble += "<div id='fade2' style='position: fixed;top: 0%;left: 0%;width: 100%;height: 100%;background-color: black;z-index: 1001;-moz-opacity: 0.3;opacity: 0.3;filter: alpha(opacity=30);'></div>"; } messagerbubble+= "</div>"; $(document.body).prepend(messagerbubble); resizePopup("#h_message",this.vertical,this.Horizontal,this.width); if(this.color){changeColor(this.color);} killPopup("#h_message",this.closeEvent); return this; } function resizePopup(target,vertical,Horizontal,popupWidth){ h_target = $(target+" .popup"); if(popupWidth){h_target.css("width",popupWidth + "px");} if(vertical=="top"){h_target.css("top","0");} else if(vertical=="bottom"){h_target.css("bottom","0");} else{ var top = ($(window).height()-h_target.height())/2*0.8; h_target.css("top",top); } if(Horizontal=="left"){h_target.css("left","0");} else if(Horizontal=="right"){h_target.css("right","0");} else{ var left = ($(window).width()-h_target.width())/2; h_target.css("left",left); } } function killPopup(target,goFunction){ h_target = $(target); $(target+" p.close_p,#fade2").click(function killPop(){ h_target.css("display","none"); if(goFunction){eval("window.parent."+goFunction+"()");} h_target.remove(); }); } function changeColor(color){ if(color=="red"){ $("#h_message .popup div").css("background","url(/res/img/login/alert_red_bg.png)"); $("#h_message .close_p").css("background","url(/res/img/login/close_red.png)"); $("#h_message div i").css("color","white"); $("#h_message p a").css("color","red"); } }
/** * Copyright 2013, 2015 IBM Corp. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ RED.sidebar.perf = (function() { marked.setOptions({ renderer: new marked.Renderer(), gfm: true, tables: true, breaks: false, pedantic: false, sanitize: true, smartLists: true, smartypants: false }); var content = document.getElementById("tab-perf"); content.style.paddingTop = "4px"; content.style.paddingLeft = "4px"; content.style.paddingRight = "4px"; function show() { if (!RED.sidebar.containsTab("perf")) { RED.sidebar.addTab("perf",content,false); } RED.sidebar.show("perf"); } function jsonFilter(key,value) { if (key === "") { return value; } var t = typeof value; if ($.isArray(value)) { return "[array:"+value.length+"]"; } else if (t === "object") { return "[object]" } else if (t === "string") { if (value.length > 30) { return value.substring(0,30)+" ..."; } } return value; } function refresh(node) { $("#tab-perf").show(); } return { show: show, refresh:refresh, clear: function() { $("#tab-perf").hide(); } } })();
const superKey = "name"; const superValue = "Bruce"; const obj = { [superKey] : superValue } obj.value = 'fsdfsd'
var dauQuery = function(){ // get jql script params for active users query, return result is daus this month var newDAUActiveUserScript = $('#jql-dau-active-users').html(); newDAUActiveUserScript = $.trim(newDAUActiveUserScript); //placeholders for graph var DAUs = {} var dauData ={} MP.api.jql(newDAUActiveUserScript).done(function(results) { var dauToday = results.length - 1 dauToday = results[dauToday].value $('#dau-header').text(addCommas(dauToday)); _.each(results, function(value, key){ DAUs[value.key[0]] = value.value }) dauData.DAUs = DAUs var mdauChart = $('#dau-chart').MPChart({chartType: 'line', highchartsOptions: { // Create a line chart legend: { enabled: true, y:-7 }, }}); mdauChart.MPChart('setData', dauData); // Set the chart's data $("#dau-chart-header").show() //display chart header }) setTimeout(dauQuery,3600000) } dauQuery();
import React, { Component } from 'react' import {Breadcrumb} from 'sub-antd'; import './sysBreadCrumbsNav.scss' export default class SysBreadCrumbsNav extends Component { constructor(props){ super(props); } render() { return ( <div className='navigator'> <Breadcrumb separator="/"> {this.props.paths.map((item,i)=>{ if(i==this.props.paths.length-1){ return <Breadcrumb.Item key={i} className="current-path">{item.name}</Breadcrumb.Item> }else{ if(item.url){ return <Breadcrumb.Item key={i}>{item.name}</Breadcrumb.Item>; }else{ return <Breadcrumb.Item key={i} >{item.name}</Breadcrumb.Item>; } } })} </Breadcrumb> </div> ) } }
var simpletree = require('../'), assert = require('assert'); var tree = new simpletree.Tree(); assert.equal(tree.getData('/'), null); tree.createNode('/node1', { data: 1 }); var result = tree.getData('/node1'); assert.ok(result); assert.ok(result.data); assert.equal(result.data, 1); tree.setData('/node1', { data: 2 }); result = tree.getData('/node1'); assert.ok(result); assert.ok(result.data); assert.equal(result.data, 2); tree.createNode('/node1/subnode2', { data: 3 }); result = tree.getData('/node1/subnode2'); assert.ok(result); assert.ok(result.data); assert.equal(result.data, 3);
(function(){ 'use strict'; angular.module('yrzb.controllers') .controller('AppCtrl', function($rootScope, $scope, $util, $api, $publicApi, $ui, $state, $ionicHistory, $sessionStorage, $location) { // 用于controller之间传参数的全局对象 $scope.rootTransferParams = {}; // 跳转方法 $scope.toPage = $util.toPage; // 企业注册获取行业ajax $scope.corpgetTradeAjax = function($scope) { var id = $rootScope.rootUploadAttachForm.trade_id, path = $location.path(), step = parseInt(path.charAt(path.length - 1)) || 1; // 在非第一步的时候刷新就跳到第一步 if(step > 1 && !$rootScope.rootUploadAttachForm.trade_id) { $state.go('app.corpTrade'); return; } $api.trade({id: id}, function(data) { if(data.boolen) { var arr = data.data || []; if(!arr.length) { $scope.isHasList = false; return ; } $scope.items = arr; $scope.isHasList = true; } }) } // 点击行业入出子分类 $scope.corpTradeChild = function($chileScope) { var path = $location.path(), step = parseInt(path.charAt(path.length - 1)) || 1, item = $chileScope.item, label = item.trade_name_cn, isLast = item.last_level; $rootScope.rootUploadAttachForm.trade_label = label; // 保存行业名字 if(isLast == '1') { $ui.tip('亲,没有下一级啦,可以点确认了呀!!') } else { $state.go('app.corpTrade' + (++step)); } } // 提交数据 $scope.corpTradeConfirm = function() { var id = $rootScope.rootUploadAttachForm.trade_id || $rootScope.rootUploadAttachForm.old_trade_id, provider = $rootScope.rootUploadAttachForm.provider || 'app.corpRegister'; if(id == null) { $ui.tip('请选择行业'); return; } $state.go(provider); } // 企业审核失败 $util.newFormData('rootCorpFailureForm', $rootScope); // 客户经理 $util.newFormData('rootManagerDatum', $rootScope); // 上传资料表单数据 $util.newFormData('rootUploadAttachForm', $rootScope); // 企业变更 $util.newFormData('rootCorpChangeForm', $rootScope); // 企业资料查看 $util.newFormData('rootReadCorpAttach', $rootScope); //融资需求表单数据 $util.newFormData('rootAddDemandForm', $rootScope); // 验证表单中该填的是否已填 $scope.validForm = function(selector){ var result = true; selector = selector ? selector : 'ion-view'; var ionViews = document.querySelectorAll(selector); var inputs, tipMsg, input; angular.forEach(ionViews, function(ionView){ // 筛选出当前页的表单进行验证 if(ionView && angular.element(ionView).attr('nav-view') == 'active'){ inputs = ionView.querySelectorAll('input, select'); for(var i = 0; i < inputs.length; i++){ input = inputs[i]; tipMsg = input.getAttribute('required'); var ngNovalid = (input.getAttribute('ng-novalid') || '').trim(); // 如果有required 且 ng-novalid 为false if(tipMsg !== null && (ngNovalid === 'false' || !ngNovalid)){ tipMsg = tipMsg || "此项必填"; if(!angular.element(input).val()){ // 表单没有值 $ui.tip(tipMsg); result = false; return false; } } } } }) return result; } // 验证表单 如果通过 退回上一个页面 $scope.confirmForm = function(selector){ var result = $scope.validForm(selector); if(result){ window.history.go(-1);//防止刷新后退键无效 //$ionicHistory.goBack(); } } // 本地储存用户信息 $scope.getSessionObj = function(key) { key = key || 'userinfo'; var obj = $scope.rootSession; if(!obj) { obj = $sessionStorage.getObject(key); } return obj; }; $scope.setSessionObj = function(obj) { $scope.rootSession = obj; $sessionStorage.setObject('userinfo', obj); }; $scope.getUserInfo = function(cb) { $api.get_user_info(function(data) { if(data.boolen) { var obj = data.data; $scope.setSessionObj(obj); cb && cb(obj); } }) } // 获取参数对象,并清空rootTransferParams的值 $scope.rootGetParams = function(){ var cloneParams = angular.copy($scope.rootTransferParams); $scope.rootTransferParams = {}; return cloneParams; }; //登出 $scope.logout = function(){ $api.logout(function(data){ // 清除localStorage、sessionStorage及rootFormData $util.clearCache(); $state.go('app.login'); }); }; // }) .controller('PagesCtrl', function($scope) { $scope.pagelist = [ { title: '系统功能示例', name: 'addon' }, { title: '框架重构', name: 'standard' }, { title: '关于云融资', name: 'about' }, { title: 'E百万', name: 'yibaiwan'}, { title: 'E百万-企业资料提交成功', name: 'yibaiwan-succ'}, { title: 'E百万-提交企业资料', name: 'yibaiwan-corp-message'}, { title: '我的融资', name: 'myfinance'}, { title: '我的融资-企业资料', name: 'corp-message'}, { title: '我的融资-提交融资需求', name: 'sub-demand'}, { title: '我的融资-审批中-审批不通过-待还款-查看明细', name: 'view-details'}, { title: '融资产品', name: 'financing-products'}, { title: '融资产品-产品搜索', name: 'financing-products-search'}, { title: '账户概况', name: 'account' }, { title: '登录', name: 'login' }, { title: '(完)企业绑定', name: 'enterprise-binding' }, { title: '(完)企业库', name: 'enterprise-library' }, { title: '(完)企业库-搜索失败', name: 'enterprise-library-search-failure' }, { title: '(完)企业绑定-验证', name: 'enterprise-validate' }, { title: '(完)企业绑定-失败', name: 'enterprise-failure' }, { title: '(完)注册', name: 'register'}, { title: '(完)注册成功', name: 'registersuc'}, { title: '找回密码', name: 'backpassword'}, { title: '设置密码', name: 'setpassword'}, { title: '设置密码成功', name: 'setpasswordsuc'}, { title: '个人资料-法人信息', name: 'personal-legal'}, { title: '个人资料-营业执照', name: 'personal-license'}, { title: '个人资料-提交', name: 'personal-submit'}, { title: '企业资料-经办人-信息', name: 'enterprise-attn-info'}, { title: '企业资料-提交-经办人', name: 'enterprise-submit-attn'}, { title: '(完)注册成功(客户经理)完善资料', name: 'performation'}, { title: '(完)注册成功(客户经理)资料提交成功', name: 'formationsuc'}, { title: '(完)客户经理提交资料身份证信息', name: 'photoid'}, { title: '(完)企业登记', name: 'business'}, { title: '(完成)企业登记-失败', name: 'business-failure'}, { title: '(完)城市选择', name: 'city'}, { title: '(完)主营业务', name: 'main-business'}, { title: '账户概况', name: 'account'}, { title: '账户概况-我的融资', name: 'account-finance'}, { title: '账户概况-我的融资-已还款', name: "has-repayment"}, { title: '账户概况-我的融资-待还款', name: 'for-repayment'}, { title: '账户概况-我的融资-待还款-还款', name: 'repayment'}, { title: '账户概况-我的融资-待还款-还款-成功', name: 'repayment-succ'}, { title: '账户概况-我的理财', name: 'account-my-money'}, { title: '账户概况-我的理财_投资记录', name: 'account-my-money-record'}, { title: '账户概况-我的理财_还款列表', name: 'account-my-money-repayment'}, { title: '账户概况-资金提现', name: 'cash'}, { title: '账户概况-资金提现-提现', name: 'cash-mention-now'}, { title: '账户概况-资金提现-提现-成功', name: 'cash-mention-now-suc'}, { title: '账户概况-消息中心', name: 'message-center'}, { title: '个人融资-个人资料', name: 'personaldata'}, { title: '个人融资-个人资料-企业变更', name: 'personaldata-changeenterprise'}, { title: '个人融资-个人资料-企业变更提交成功', name: 'personaldata-enterprise-suc-submit'}, { title: '个人融资-个人资料-企业变更审核中', name: 'personaldata-enterprise-ing'}, { title: '个人融资-个人资料-企业变更通过', name: 'personaldata-enterprise-offer'}, { title: '个人融资-个人资料-已绑定的企业', name: 'personaldata-enterprise-over'}, { title: '个人融资-个人资料-营业执照', name: 'personaldata-personal-license'}, { title: '个人融资-个人资料-绑定银行卡', name: 'personaldata-bank-binding'}, { title: '个人融资-个人资料-绑定银行卡成功', name: 'personaldata-bank-bindingSuc'}, { title: '个人融资-个人资料-银行卡管理', name: 'personaldata-bank-manage'}, { title: '个人融资-个人资料-资金充值', name: 'funds-recharge-recharge'}, { title: '个人融资-个人资料-资金充值', name: 'funds-recharge'}, { title: '个人融资-个人资料-充值成功', name: 'funds-recharge-success'}, { title: '个人融资-个人资料-资金记录', name: 'financial-record'}, { title: '客户管理', name: 'customer-management'}, { title: '客户管理-登记客户(已绑定企业)', name: 'customer-management-register'}, { title: '客户管理-登记客户(已注册未绑定企业)', name: 'customer-management-noregister'}, { title: '客户管理-登记客户-成功提示', name: 'customer-management-suc'}, { title: '客户管理-登记客户-资料上传成功', name: 'customer-management-upsuc'}, { title: '客户管理-个人客户待审核', name: 'customer-management-wait'}, { title: '客户管理-个人客户-客户过户', name: 'customer-personal-transfer'}, { title: '客户管理-个人客户-客户过户确认', name: 'customer-personal-transferaffirm'}, { title: '客户管理-个人客户-过户成功', name: 'customer-personal-transfersuc'}, { title: '客户管理-个人客户-客户资料审核通过', name: 'customer-personal-transferpass'}, { title: '客户管理-个人客户-客户资料审核不通过', name: 'customer-personal-transfernotpass'}, { title: '客户管理-个人融资', name: 'customer-personal-financing'}, { title: '客户管理-企业融资', name: 'customer-enterprise-financing'}, { title: '客户管理-提示', name: 'customer-management-pop'}, { title: '客户管理-企业登记(个人)', name: 'customer-enterprise-register'}, { title: '图片预览', name: 'personal-license-picture'}, { title: 'photoswipe图片预览', name: 'photo-swipe'} ]; }) .controller('PageDetailCtrl', function($scope, $api, $ui, $ionicHistory, $sce, $ionicScrollDelegate, $timeout, $location, $state) { $scope.back = function(){ $ionicHistory.goBack(); }; $scope.clearView = function(){ $ionicHistory.clearHistory(); $ui.alert('已清除浏览历史'); }; //call api $scope.userInfo = '点击按钮获取用户信息'; $scope.callApi = function(){ $api.userInfo({id: 16}, function(data){ $scope.userInfo = JSON.stringify(data); }); }; //pop $scope.alert = function(){ $ui.alert({title: '警告警告!', content: '请先输入用户名!'}); }; $scope.confirm = function(){ $ui.confirm({ content: '确认要吃掉这颗苹果吗?', onCancel: function(){ $ui.alert('你不想吃苹果!') }, onOk: function(){ $ui.alert('你吃掉了苹果!') } }); }; $scope.prompt = function(){ $ui.prompt({ subTitle: '请先输入用户名!', onClose: function(val){ $ui.alert(val !== undefined ? '你输入了' + val : '你取消了输入!'); } }) }; //action sheet $scope.actionSheet = function(){ $ui.actionSheet({ buttons: [{text: '分享我吧'}], ondelete: function(){ $ui.alert('删除!'); }, onclick: function(index){ if(index === 0){ $ui.alert('你点击了分享'); } } }); }; //loading $scope.showLoading = function(){ $ui.showLoading('Loading: 自定义的加载提示'); }; $scope.hideLoading = $ui.hideLoading; //modal $scope.name = 'shaman'; $ui.createModal($scope, function(modal){ $scope.demoModal = modal; }, 'test-modal.html'); $scope.showDemoModal = function(){ $scope.demoModal.show(); }; $scope.closeDemoModal = function(){ $scope.demoModal.hide(); }; //protocol modal $ui.createModal($scope, function(modal){ $scope.protocolModal = modal; }, false); $scope.showProtocolModal = function(){ $api.viewRegisterProtocol(function(data) { if(data.boolen) { $scope.modalTitle = data.message.name; $scope.modalContent = $sce.trustAsHtml(data.message.tpl); $scope.protocolModal.show(); } else { $ui.tip(data.message) } }); }; $scope.closeModal = function(){ $scope.protocolModal.hide(); }; //expander $scope.cityList = [ {name: '杭州市西湖区', data: ['文一西路', '西湖', '文三路'], active: true}, {name: '杭州市西湖区', data: ['文一西路', '西湖', '文三路']} ]; $scope.selectCity = function(city, area){ console.log([city, area].join(',')); }; //about yrzb $scope.targets = [ {label: '平台简介', cur: true}, {label: '业务模式'}, {label: '企业使命'}, {label: '集团背景'} ]; $scope.scrollTo = function(index){ angular.forEach($scope.targets, function(obj, index){ obj.cur = false; }); $scope.targets[index].cur = true; $location.hash('scrollStep_' + index); $ionicScrollDelegate.anchorScroll(true); }; //message center $scope.subNav = [ {label: '全部消息', action: 'app.login', icon: 16}, {label: '放款提醒', action: 'app.login', icon: 12}, {label: '借款提醒', action: 'app.login', icon: 10}, {label: '还款提醒', action: 'app.login', icon: 14}, {label: '开标提醒', action: 'app.login', icon: 25}, {label: '投资成功', action: 'app.login', icon: 11} ]; $scope.viewAllRoutes = function(){ var data = $state.get(); console.table(data); }; $scope.images = [ '/images/about-yrz.png', '/images/logo.png', 'https://farm4.staticflickr.com/3894/15008518202_c265dfa55f_h.jpg' ]; $scope.previewImg = function(index){ $ui.viewImg($scope, { index: index }); }; $scope.swipeImages = [ {title: 'Image caption 美女啊', src: '/images/temp/22.png', w: 640, h: 340}, {title: 'Image caption 又一个美女啊', src: '/images/temp/11.png', w: 648, h: 336}, {title: 'Image caption 效果图', src: '/images/temp/33.png', w: 672, h: 1081} ]; $ui.createModal($scope, function(modal){ $scope.swipeModal = modal; }, '/templates/common/swipe-modal.html'); $scope.viewImages = function(index){ $scope.swipeIndex = index; $scope.swipeModal.show(); $ui.callSwipe($scope); }; }) .controller('DynamicCtrl', function($scope) { $scope.dynList = [ { title: '登录', url: '#/login' }, { title: '注册', url: '#/register'}, { title: '注册-成功', url: '#/account/registerSuccess'}, { title: '绑定公司', url: '#/account/corpBinding'}, { title: '绑定公司--失败', url: '#/account/bindingFailure'}, { title: '企业库', url: '#/account/corpLibrary'}, { title: '企业登记', url: '#/account/corpRegister'}, { title: '企业登记--失败', url: '#/account/registerFailure'}, { title: '企业登记-选城市', url: '#/account/corpCity'}, { title: '企业登记-选行业', url: '#/account/corpTrade'}, { title: '客户经理--完善资料', url: '#/account/managerDatum'}, { title: '个人融资', url: '#/account/personalInfo'}, { title: '上传资料', url: '#/account/uploadAttach'} ]; }) .controller('SelectTradeCtrl', function ($scope, $ionicHistory, $state) { }); }());
/* home/scripts.js Copyright (C) 2012 David Yamnitsky 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. */ // SlideToUnlock Plugin (function($) { $.fn.slidetounlock = function (method) { var methods = { init : function (options) { var settings = $.extend( { 'background-src' : '', 'slider-src' : '', }, options); return this.each(function() { $(this).find('.slidetounlock-slider').css('background-image','url("' + settings['slider-src'] + '")'); $(this).find('.slidetounlock-slider').draggable({ axis: 'x', containment: 'parent', drag: function(event, ui) { if (ui.position.left > 202) { ui.position.left = 202; } else if (ui.position.left < 0) { ui.position.left = 0; } var val = Math.max(0.0, Math.min(1.0, 1.0 - (ui.position.left / 100.0))); $(this).parent().find('.slidetounlock-label').css( 'opacity', val ); }, stop: function(event, ui) { if ( ui.position.left >= 202 ) { $(this).parent().trigger('unlock'); } else { $(this).animate({ left: 0 }); $(this).parent().find('.slidetounlock-label').animate({ opacity: 1.0 }); } } }); }); }, reset : function (callback) { $(this).find('.slidetounlock-slider').animate({ left: 0 }); $(this).find('.slidetounlock-label').animate({ opacity: 1.0 }, function() { if (callback) callback.call($(this).parent()); }); } }; if (methods[method]) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === 'object' || ! method) { return methods.init.apply(this, arguments); } else { $.error('method ' + method + ' does not exist in ' + 'jQuery.slidetounlock'); } }; })( jQuery ); // TapToLoad Plugin (function($){ $.fn.taptoload = function (method) { var methods = { init : function (options) { var settings = $.extend( { }, options); return this.each(function() { var $this = $(this); if (!touch_device && ($this.attr('data-force') != 'yes')) { var imageObj = new Image(); imageObj.className += 'taptoload-image'; imageObj.style.display = 'inherit'; imageObj.src = $this.attr('data-image-src'); $this.append(imageObj); $this.find('.taptoload-label').css('display','none'); $this.css('max-width','none'); $this.find('img').css('visibility','visible'); } else { $this.addClass('taptoload-background'); var ttlOuter = document.createElement('div'); ttlOuter.className += 'taptoload-outer'; $this.append(ttlOuter); var ttlInner = document.createElement('div'); ttlInner.className += 'taptoload-inner'; $this.find('.taptoload-outer').append(ttlInner); $this.find('.taptoload-label').moveElementTo($this.find('.taptoload-inner')); $this.find('.taptoload-label').css('visibility','visible'); spinnerObj = new Image(); spinnerObj.className += 'taptoload-spinner'; $this.find('.taptoload-inner').append(spinnerObj); $this.find('.taptoload-spinner').attr('src',$this.attr('data-spinner-src')); $this.on('click', function() { if ($this.attr('data-tapped') != 'yes') { $this.attr('data-tapped', 'yes'); var imageObj = new Image(); imageObj.className += 'taptoload-image'; $this.find('.taptoload-outer').append(imageObj); $this.find('.taptoload-image').attr('src',$this.attr('data-image-src')); $this.find('.taptoload-image').attr('onload', displayImage ); var timerFired = false; setTimeout( function(){ timerFired = true; }, 1000 ); $this.find('.taptoload-spinner').css( {opacity:0.0, visibility:'visible'} ).animate( { opacity:1.0 }, 'slow' ); $this.find('.taptoload-inner').find('.taptoload-label').fadeOut('slow'); function displayImage() { if (!timerFired) { setTimeout( displayImage_internal, 1000 ); } else { displayImage_internal(); } function displayImage_internal() { $this.css('max-width','none'); $this.css('width','100%'); $this.find('.taptoload-image').css( {display: 'inherit', opacity:0.0, visibility:'visible'} ).animate( { opacity:1.0 }, 'slow' ); $this.find('.taptoload-inner').fadeOut('slow'); $this.removeClass('taptoload-background'); $this.find('.taptoload-image').on('click', function() { window.location.href = $this.attr('data-image-src'); }); } } } }); } }); } }; if (methods[method]) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === 'object' || ! method) { return methods.init.apply(this, arguments); } else { $.error('method ' + method + ' does not exist in ' + 'jQuery.taptoload'); } }; $.fn.moveElementTo = function(selector){ return this.each(function(){ var cl = $(this).clone(); $(cl).appendTo(selector); $(this).remove(); }); }; touch_device = ('ontouchstart' in document.documentElement); })( jQuery ); $(function(){ //On touch devices, make the navbar not follow scrolling, //because this looks bad when the user pinches to zoom. if (jQuery.browser.touch) $('.navbar-fixed-top').addClass('navbar-stay'); //Setup subnav processScroll(); $(window).scroll(function() { processScroll() }); //Setup taptoload views $('.taptoload').taptoload(); //Setup pretty print window.prettyPrint && prettyPrint(); }); $('.carousel-inner').on('click', function() { if ($('.carousel').find('.carousel-control').css('display') != 'none') $('.carousel').find('.carousel-control').fadeOut(); else $('.carousel').find('.carousel-control').fadeIn(); }); $(function () { $('[rel=tooltiptop]').tooltip({placement:'top'}); $('[rel=tooltipbottom]').tooltip({placement:'bottom'}); $('[rel=tooltipleft]').tooltip({placement:'left'}); $('[rel=tooltipright]').tooltip({placement:'right'}); $('[rel=popovertop]').popover({placement:'top'}); $('[rel=popoverbottom]').popover({placement:'bottom'}); $('[rel=popoverleft]').popover({placement:'left'}); $('[rel=popoverright]').popover({placement:'right'}); }); var navTop = $('.subnav').length && $('.subnav').offset().top - 38; var subnavFixed = 0; function subnavClicked(anchor) { var offset = 5; if ($('#navbar').hasClass('navbar-stay')) offset = 3; else if (window.innerWidth <= 558) offset = 3; else if (jQuery.browser.touch && window.innerWidth > 979) offset = 50; else if (window.innerWidth > 979) offset = subnavFixed ? 85 : 89; $('html,body').animate({scrollTop: $("#"+anchor).offset().top - offset},'slow'); } function processScroll() { if (jQuery.browser.touch) return; var i, scrollTop = $(window).scrollTop(); if (scrollTop >= navTop && !subnavFixed) { subnavFixed = 1; $('.subnav').addClass('subnav-fixed'); $('.subnav-placeholder').removeClass('display-none'); } else if (scrollTop <= navTop && subnavFixed) { subnavFixed = 0; $('.subnav').removeClass('subnav-fixed'); $('.subnav-placeholder').addClass('display-none'); } }; $(document).ready(function() { $(".copycat").keyup(function() { $(".copycat").not($(this)).val($(this).val()); }); }); (function($){ jQuery.browser.touch = ('ontouchstart' in document.documentElement); })( jQuery );
module.exports = angular.module('stf.uixml-analysis', [ require('stf/filter-string').name, require('stf/socket').name ]) .factory('UiXmlAnalysisService', require('./uixml-analysis-service'))
const inquirer = require('inquirer'); const fs = require('fs'); const Manager = require('./Manager'); const Engineer = require('./Engineer'); const Intern = require('./Intern'); function init(){ initHTML(); makeManager(); } function makeManager(){ inquirer .prompt([ { type:'input', message: 'Managers Name?', name: 'name', }, { type:'input', message:'Managers Id?', name: 'id', }, { type:'input', message:'Managers Email?', name:'email', }, { type:'input', message:'Managers Office Number?', name:'officeNum', } ]) .then((response)=>{ topDog = new Manager(response.name,response.id,response.email,response.officeNum); const manHtml = ` <div class="col-md-4"> <div class="card text-dark bg-info mb-3" style="border: 3px solid rgb(137, 190, 207); border-radius:15px; margin-bottom:8px"> <div class="card-header text-center"><h4>${topDog.name}</h4></div> <div class="card-header text-center"><h4>${topDog.getRole()} ☕️</h4></div> <div class="card-body"> <ul class="list-group list-group-flush"> <li class="list-group-item"><strong>ID:</strong> ${topDog.id}</li> <li class="list-group-item"><strong>Email:</strong> <a href="mailto:${topDog.email}"> ${topDog.email}</a></li> <li class="list-group-item"><strong>Office Number:</strong> ${topDog.officeNum}</li> </div> </div> </div> ` fs.appendFile('teamprofile.html',manHtml,function(err){ if(err){ console.log(err); } }) console.log('Manager Added'); addMore(); }); } function addMore(){ inquirer .prompt([ { type:'list', message:'Add another employee?', choices:['Yes','No'], name:'confirm', } ]) .then((response)=> { if(response.confirm === 'Yes'){ inquirer .prompt([ { type:'list', message:'Which kind of employee?', choices:['Engineer','Intern'], name:'eOI', } ]) .then((response) => { if(response.eOI === 'Engineer'){ inquirer .prompt([ { type:'input', message: 'Engineers Name?', name: 'name', }, { type:'input', message:'Engineers Id?', name: 'id', }, { type:'input', message:'Engineers Email?', name:'email', }, { type:'input', message:'Github Name?', name:'github', } ]) .then((response) => { newGuy = new Engineer(response.name,response.id,response.email,response.github); const engHtml = ` <div class="col-md-4"> <div class="card text-dark bg-info mb-3" style="border: 3px solid rgb(137, 190, 207); border-radius:15px; margin-bottom:8px"> <div class="card-header text-center"><h4>${newGuy.name}</h4></div> <div class="card-header text-center"><h4>${newGuy.getRole()} 🛠</h4></div> <div class="card-body"> <ul class="list-group list-group-flush"> <li class="list-group-item"><strong>ID:</strong> ${newGuy.id}</li> <li class="list-group-item"><strong>Email:</strong> <a href="mailto:${newGuy.email}"> ${newGuy.email}</a></li> <li class="list-group-item"><strong>Github:</strong> <a href="https://github.com/${newGuy.github}"> ${newGuy.github}</a></li> </div> </div> </div> ` fs.appendFile('teamprofile.html',engHtml,function(err){ if(err){ console.log(err); } }) console.log('Engineer Added'); addMore(); }) } else if (response.eOI === 'Intern'){ inquirer .prompt([ { type:'input', message: 'Interns Name?', name: 'name', }, { type:'input', message:'Interns Id?', name: 'id', }, { type:'input', message:'Interns Email?', name:'email', }, { type:'input', message:'School Name?', name:'school', } ]) .then((response) => { newGuy = new Intern(response.name,response.id,response.email,response.school); const intHtml = ` <div class="col-md-4"> <div class="card text-dark bg-info mb-3" style="border: 3px solid rgb(137, 190, 207); border-radius:15px; margin-bottom:8px"> <div class="card-header text-center"><h4>${newGuy.name}</h4></div> <div class="card-header text-center"><h4>${newGuy.getRole()} 🎓</h4></div> <div class="card-body"> <ul class="list-group list-group-flush"> <li class="list-group-item"><strong>ID:</strong> ${newGuy.id}</li> <li class="list-group-item"><strong>Email:</strong> <a href="mailto:${newGuy.email}"> ${newGuy.email}</a></li> <li class="list-group-item"><strong>School:</strong> ${newGuy.school}</li> </div> </div> </div> ` fs.appendFile('teamprofile.html',intHtml,function(err){ if(err){ console.log(err); } }) console.log('Intern Added'); addMore(); }) } }) } else if (response.confirm === 'No'){ console.log('Team Built'); endHtml(); } }) } function initHTML(){ const html = ` <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title></title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous"> </head> <body> <header class="text-center border-bottom bg-info"> <h1>Team Profiles</h1> </header> <div class="row row-cols-1 row-cols-md-2 g-4"> <div class="col"> `; fs.writeFile('teamprofile.html',html,function(err){ if (err){ console.log(err); } }); console.log("HTML Initialized"); } function endHtml(){ const finishedHtml = ` </div> </div> </body> </html> `; fs.appendFile('teamprofile.html',finishedHtml,function(err){ if (err){ console.log(err); } }); console.log('Html Complete'); } init();
const { src, dest, series, } = require('gulp'); const rename = require('gulp-rename'); const imageResize = require('gulp-image-resize'); const plumber = require('gulp-plumber'); const notify = require('gulp-notify'); const config = require('./config.js'); function buildIcons(cb) { config.iconSizes.forEach(function (size) { return src('icon/*') .pipe( plumber({ errorHandler: notify.onError('Error: <%= error.message %>'), }), ) .pipe(imageResize({ imageMagick: true, width: size.width, height: size.heigth, })) .pipe(rename((path) => { path.basename = `${path.basename}@${size.width}x${size.heigth}`; })) .pipe( dest(`images/`), ); }); cb(); } exports.buildIcons = buildIcons; const build = series( buildIcons, ); exports.build = build;
import {types} from "mobx-state-tree"; import {v4 as uuidv4} from 'uuid' const Error = types.model('Todo',{ id: types.optional(types.identifier, () => uuidv4()), type: types.string, content: types.string, show: types.optional(types.boolean, true), }) export default Error
'use strict'; require("angular"); require("angular-route"); require("angular-cookies"); require("angular-resource"); require("angular-loading-bar"); require("./core/core.module.js"); require("./manager-list/manager-list.module.js"); require("./manager-detail/manager-detail.module.js"); require("./client-list/client-list.module.js"); require("./client-detail/client-detail.module.js"); require("./tour-list/tour-list.module.js"); require("./tour-detail/tour-detail.module.js"); require("./order-list/order-list.module.js"); require("./order-detail/order-detail.module.js"); require("./transaction-list/transaction-list.module.js"); require('expose?$!expose?jQuery!jquery'); require("bootstrap-webpack"); angular.module('agencyApp', [ 'ngRoute', 'ngCookies', 'angular-loading-bar', 'core', 'managerList', 'managerDetail', 'clientList', 'clientDetail', 'tourList', 'tourDetail', 'orderList', 'orderDetail', 'transactionList' ]);
var express = require('express'); var app = express(); var server = require('http').Server(app); var path = require('path'); var Food = require('./models/foodSchema').Food; var Component = require('./models/componentSchema').Component; var cors = require('cors'); var bodyParser = require('body-parser'); var port = process.env.PORT || 8080; app.use(cors()); app.use(bodyParser.json());// get information from html forms app.use(bodyParser.urlencoded()); app.get('/food', function (req, res) { Food.find(function (err, objs) { res.json(JSON.stringify(objs)); }); }); app.options('/food', cors()); app.put('/food', cors(), function (req, res) { var food = new Food(req.body); food.save(); res.statusCode = 200; res.send(); }); app.get('/component', function (req, res) { Component.find(function (err, objs) { res.json(JSON.stringify(objs)); }); }); app.options('/component', cors()); app.put('/component', cors(), function (req, res) { var component = new Component(req.body); component.save(); res.statusCode = 200; res.send(); }); server.listen(port, function () { console.log('listening on port ' + port); });
'use strict' const faker = require('faker') module.exports = function createCustomer () { const addresses = [] const amount = Math.ceil(Math.random() * 3) for (let i = 0; i < amount; i++) { addresses.push({ address: faker.address.streetAddress(), addressId: faker.random.uuid() }) } return { id: faker.random.uuid(), email: faker.internet.email(), firstName: faker.name.firstName(), lastName: faker.name.lastName(), middleName: faker.name.firstName(), customerGroup: faker.commerce.department(), companyName: faker.company.companyName(), address: addresses } }
export default router => { router.get('test', async(ctx,next) => { ctx.body = "test"; await next(); }) }
// Retrieve info from the create form document.querySelector('#email').value = localStorage.getItem('mail'); function login() { let userValid = (localStorage.getItem('mail') == document.querySelector('#email').value); let passValid = (localStorage.getItem('psw') == document.querySelector('#pass').value); if (userValid && passValid) { alert('Welcome to Hantang school'); return true; } else { alert('Wrong email or passwords'); } return false; } // Validation // There are fewer ways to pick a DOM node with legacy browsers const form = document.getElementsByTagName('form')[0]; const email = document.getElementById('email'); // I don't fully understand how siblings work so I can't give explenation, but the idea is clear let error = email; while ((error = error.nextSibling).nodeType != 1); //Email validation format const emailRegExp = /(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/ function addEvent(element, event, callback) { let previousEventCallBack = element["on" + event]; element["on" + event] = function(e) { const output = callback(e); // A callback that returns `false` stops the callback chain // and interrupts the execution of the event callback. if (output === false) return false; if (typeof previousEventCallBack === 'function') { output = previousEventCallBack(e); if (output === false) return false; } } }; // Because there is no CSS pseudo-class, we have to // explicitly set the valid/invalid class on our email field addEvent(window, "load", function() { // Here, we test if the field is empty (remember, the field is not required) // If it is not, we check if its content is a well-formed e-mail address. const test = email.value.length === 0 || emailRegExp.test(email.value); email.className = test ? "valid" : "invalid"; }); // This defines what happens when the user types in the field addEvent(email, "input", function() { const test = email.value.length === 0 || emailRegExp.test(email.value); if (test) { email.className = "valid"; error.innerHTML = ""; error.className = "error"; } else { email.className = "invalid"; } }); // This defines what happens when the user tries to submit the data addEvent(form, "submit", function() { const test = email.value.length === 0 || emailRegExp.test(email.value); if (!test) { email.className = "invalid"; error.innerHTML = "Wrong email format! someone@example.com"; //Will fix this error message in the future error.className = "error active"; // Some legacy browsers do not support the event.preventDefault() method return false; } else { email.className = "valid"; error.innerHTML = ""; error.className = "error"; } });
const mongoose = require('mongoose'); const Schema = mongoose.Schema; const diplomasSchema = new Schema({ title: { type: String, required: true }, beschrijving: { type: String, required: true }, school: {type: String, required: true}, startDatum: { type: String, required: true }, endDatum: { type: String, required: true }, id: {type: String , require: true, uniq:true}, logoschoolUrl: { type: String, required: true }, },{ timestamps: true, }); const Diplomas = mongoose.model('Diplomas', diplomasSchema); module.exports = Diplomas;
/** * Copyright: Daniel Bunzendahl * License: MIT * * Koa Sub-Domain Constructor. * @param {Object} sub Subdomain can be also a FQDN or a wildcard like *.example.com * œparam {Object} r Can be a generator function or a Koa-router * @api public */ function Subdomain(sub, r){ if (!(this instanceof Subdomain)){ var instance = new Subdomain(sub, r); return instance; } if(!sub || !r || typeof sub !== 'string' || (typeof r !== "object" && typeof r !== "function")){ throw new Error('Missing or wrong params! Expected first param a STRING (is '+(typeof sub)+') and second a GENERATOR-Object or a function (is '+(typeof r)+')'); } /** * steps to test: * 1) sub === this.hostname * 2) this.subdomain[0] === sub * 3) typeof this.subdomain[1] === 'string' // or wildcard => sub sub domain ? */ return function *(next){ // for the case someone enters a complete domain name // e.g. 'sub.example.com' // instead of 'sub' or '*' if(sub === this.hostname){ if(typeof r.routes === "function") { yield r.routes(); } else { yield r; }; } var subdomain = this.subdomains[0] || ''; if (subdomain === sub && sub[0] !== '*' && !this.subdomains[1]) { if(typeof r.routes === "function") { yield r.routes(); } else { yield r; }; } else if(typeof this.subdomains[1] === 'string' || sub[0] === "*"){ var subdomainsstring = ""; var length = this.subdomains.length; for(var i=length; i > 0; i-- ){ if(subdomainsstring === ""){ subdomainsstring += this.subdomains[i-1]; }else { subdomainsstring += "."+this.subdomains[i-1]; } } // wildcard subdomain at most left in "sub" string var splittedSub = sub.split("."); if(splittedSub[0] === "*"){ var subdomains = this.subdomains; var hostname = this.hostname.split("."); var hostnamelength = hostname.length; // reverse lookup arrays against each other for(var s=hostnamelength; s > 0; s--){ var hostnamepop = hostname.pop(); if(subdomains.length > 0){ var shift = subdomains.shift(); } var pop = splittedSub.pop(); if(shift === pop || hostnamepop === pop){ continue; } else { if(pop === "*"){ if(typeof r.routes === "function") { yield r.routes(); } else { yield r; }; break; } else { yield next; break; } } } } // NOTE: app.subdomainOffset is the base! if(subdomainsstring === sub){ if(typeof r.routes === "function") { yield r.routes(); } else { yield r; }; } else { yield next; } } else{ yield next; } }; } module.exports = Subdomain;
$(document).ready(function() { $("form#sentence").submit(function(event) { var sentArray = $("input#sentence").val().split([" "]); var newArray = []; sentArray.forEach(function(word) { if (word.length >= 3){ newArray.push(word); }; }); var reverseArray = newArray.reverse().join(" "); $(".output").text(reverseArray); console.log(sentArray); console.log(newArray); console.log(reverseArray); event.preventDefault(); }); });
describe('P.views.programs.schedule.DateEdit', function() { 'use strict'; var View = P.views.programs.schedule.DateEdit; describe('render', function() { beforeEach(function() { this.model = new Backbone.Model(); this.view = new View({ model: this.model }); }); it('must not throw an exception when "start" not set', function() { this.view.render(); // implicit pass }); }); describe('changeDate', function() { beforeEach(function() { this.model = new Backbone.Model({ start: moment('2015-03-10', 'YYYY-MM-DD') }); this.view = new View({ model: this.model }); this.view.render(); }); it('must show an error when invalid dates are entered', function() { spyOn(P.common.forms.Input, 'invalid'); this.view.$('.js-date').val('2014-99-99'); this.view.changeDate(); expect(P.common.forms.Input.invalid).toHaveBeenCalled(); }); it('should clear existing errors when valid dates are entered', function() { spyOn(P.common.forms.Input, 'valid'); this.view.$('.js-date').val('2015-01-01'); this.view.changeDate(); expect(P.common.forms.Input.valid).toHaveBeenCalled(); }); }); describe('submit', function() { beforeEach(function() { this.model = new Backbone.Model({ start: moment('2015-03-10', 'YYYY-MM-DD') }); this.view = new View({ model: this.model }); this.view.render(); }); it('must update the "start" moment when the date is valid', function() { var date = '2015-04-02', target = moment(date, 'YYYY-MM-DD'); expect(this.model.get('start').isSame(target, 'day')).toBe(false); this.view.$('.js-date').val(date); this.view.submit(); expect(this.model.get('start').isSame(target, 'day')).toBe(true); }); it('must display errors if date is not valid', function() { spyOn(P.common.forms.Input, 'invalid'); this.view.$('.js-date').val('2014-99-99'); this.view.submit(); expect(P.common.forms.Input.invalid).toHaveBeenCalled(); }); }); describe('calendar clicks', function() { beforeEach(function() { this.model = new Backbone.Model({ start: moment('2015-03-10', 'YYYY-MM-DD') }); this.view = new View({ model: this.model }); this.view.render(); }); it('must update the .js-date value', function() { expect(this.view.$('.js-date').val()).toBe('2015-03-10'); this.view.$('.js-day[data-date="2015-03-12"]').click(); expect(this.view.$('.js-date').val()).toBe('2015-03-12'); }); }); });
import React, { useState } from "react" import { useDispatch } from "react-redux" import { Form, Button } from "react-bootstrap" import { loginByCredentials } from "../reducers/loginReducer" const Login = () => { const [username, setUsername] = useState("") const [password, setPassword] = useState("") const dispatch = useDispatch() function handleLogin(event) { event.preventDefault() console.log("logging in with", username, password) dispatch(loginByCredentials(username, password)) setUsername("") setPassword("") } return ( <div> <h2>Login</h2> <Form onSubmit={handleLogin}> <Form.Group> <div> <Form.Label>username</Form.Label> <Form.Control id="username" type="text" value={username} name="Username" onChange={(e) => setUsername(e.target.value)} /> </div> <div> <Form.Label>password</Form.Label> <Form.Control id="password" type="password" value={password} name="Password" onChange={(e) => setPassword(e.target.value)} /> </div> <Button variant="primary" id="submit" type="submit"> login </Button> </Form.Group> </Form> </div> ) } export default Login
'use strict'; // Import chai. let chai = require('chai'), path = require('path'); // Tell chai that we'll be using the "should" style assertions. chai.should(); // Import the various creatures class. let Animal = require(path.join(__dirname, '../lib', 'animal')); let Dragon = require(path.join(__dirname, '../lib', 'dragon')); let Unicorn = require(path.join(__dirname, '../lib', 'unicorn')); let Trex = require(path.join(__dirname, '../lib', 'trex')); let Wearwolf = require(path.join(__dirname, '../lib', 'wearwolf')); describe('Dragon', () => { describe('fights magical battles', () => { let animal; let enemy; let dragon; let unicorn; let trex; let wearwolf; beforeEach(() => { // Create a new creature objects before every test. animal = new Animal(); enemy = new Animal(); dragon = new Dragon(); unicorn = new Unicorn(); trex = new Trex(); wearwolf = new Wearwolf(); }); it('is an dragon', () => { // This will fail if "dragon.name" does not equal "Dragon". dragon.name.should.equal("Dragon"); }); it('Dragons beat everything except wearwolves', () => { dragon.battle(animal).should.equal(true); dragon.battle(unicorn).should.equal(true); dragon.battle(wearwolf).should.equal(false); dragon.battle(trex).should.equal(true); }); }); });
/****************************************************************************** * Compilation: node AddressBook.js * * Purpose: Program which is used to maintain an address book. An address * book holds a collection of entries, each recording a person's * first and last names, address, city, state, zip, and phone no. * * @author Nishant Kumar * @version 1.0 * @since 01-11-2018 * ******************************************************************************/ // Implementing the File System module in this application. var fs = require("fs"); // Implementing the Radline module in this application. var rl = require('readline'); // Creating an Interface object of Readline Module by passing 'stdin' & 'stdout' as parameters. var r = rl.createInterface(process.stdin, process.stdout); /** * Function to start the program & register User. */ function registration() { // Asking if user is new or existing. r.question("Enter 1 if you're new, or 2 if you're existing: ", function(ans1) { // If 1, then register the user. if (ans1.trim() == 1) { registerUser(); } // Else existing, so ask for his purpose. else { purposeUser(); } }); } /** * This method helps to convert any object or data passed into * JSON format and write that JSON string to a file. * * @param {any} data It is the array of addresses passed by the caller. */ function writeInJson(data) { // Converting into string. var j = JSON.parse(fs.readFileSync('./JsonFiles/AddressBook.json')); // Concatenating 'j' & 'data' arrays and storing into 'arr'. var a = { "address": j.address.concat(data) }; // Writing the 'data' in the AddressBook file. fs.writeFileSync('./JsonFiles/AddressBook.json', JSON.stringify(a)); console.log("JSON File Saved!"); r.close(); } // Array to store address objects. var addr = []; /** * Function to register a user. */ function registerUser() { // Asking the user it's first name. r.question("Enter your First Name: ", function(ans) { // Asking the user it's Last name. r.question("Enter your Last Name: ", function(ans1) { // Asking user to enter it's address r.question("Enter your address: ", function(ans2) { // Asking the user to enter name of the city. r.question("Enter city: ", function(ans3) { // Asking the user to enter name of the state. r.question("Enter state: ", function(ans4) { // Asking the user to enter zip/pin code. r.question("Enter PIN/ZIP code: ", function(ans5) { // Asking the user to enter mobile number. r.question("Enter mobile number: ", function(ans6) { // Creating an object storing the properties of address book. var data = { firstName: ans.trim(), lastName: ans1.trim(), address: ans2.trim(), city: ans3.trim(), state: ans4.trim(), zip: ans5.trim(), phone: ans6.trim() } // Pushing that data into 'addr' array. addr.push(data); // Asking the user if there's any more entry. r.question("\nIs there anyone else? ", function(ans7) { // If yes, then calling registerUser() function. if (ans7.startsWith('y')) { console.log(); registerUser(); } // If no, then writing the addr into JSON file. else { writeInJson(addr); console.log("Address Book Updated!"); r.close(); } }); }); }); }); }); }); }); }); } /** * Function to check for purpose of the user. */ function purposeUser() { // Asking the user to enter his mobile number for verification. r.question("Enter your mobile number: ", function(ans1) { // Checking if the mobile number is present or not. if (checkUser(Number(ans1.trim()))) { // Askint user if he want to delete or edit the data. r.question("Do you want to 'delete'/'edit' your data? ", function(ans2) { // If user has entered delete, call deleteUser() function. if (ans2.trim().startsWith('d')) { deleteUser(Number(ans1.trim())); } // If user has entered edit, call editUser() function. else { editUser(Number(ans1.trim())); } }); } else { // If number is not present, ask the user to enter again. console.log("Sorry, number is not found in the AddressBook. Try again! "); purposeUser(); } }); } /** * Function to check if a number passed is prsenet in the address book or not. * * @param {String} number It contains the phone number to check. * * @returns {Boolean} It returns true/false based on if number is present. */ function checkUser(number) { // Reading from JSON file. var j = JSON.parse(fs.readFileSync('./JsonFiles/AddressBook.json')); // For loop to run till the number is found. for (var i = 0; i < j.address.length; i++) { // If the number is found, return true; if (j.address[i].phone == number) { return true; } } // If the number is not found, return false. return false; } /** * Function to delete an entire entry of the user based on phone number. * * @param {String} number It contains the phone number to delete. */ function deleteUser(number) { // Reading from JSON file. var j = JSON.parse(fs.readFileSync('./JsonFiles/AddressBook.json')); var i = 0; // For loop to run till the number is found. for (i = 0; i < j.address.length; i++) { // If the number is found, break the loop. if (j.address[i].phone == number) { break; } } // Confirmint the user if he wants to delete his entry. r.question(JSON.stringify(j.address[i], " ", 2) + "\nDo you want to delete this entry? ", function(ans1) { // Checking if user has entered yes. if (ans1.trim().startsWith('y')) { // If yes, then remove entry present at 'i' index. j.address.splice(i, 1); // Write & Save the file in JSON. fs.writeFileSync('./JsonFiles/AddressBook.json', JSON.stringify(j)); console.log("Deleted Successfully!"); r.close(); } else { // If no, then close the program. r.close(); } }); } /** * Function to edit the properties of the user. * * @param {String} number It is the phone number of the user. */ function editUser(number) { // Reading JSON file. var j = JSON.parse(fs.readFileSync('./JsonFiles/AddressBook.json')); var i = 0; // For loop will run till the Number is found. for (i = 0; i < j.address.length; i++) { // If the number is found, break the loop. if (j.address[i].phone == number) { break; } } // Asking the user to enter what he wants to change. r.question(JSON.stringify(j.address[i], " ", 2) + "\nEnter what you'd like to edit: ", function(ans1) { // Checking if the property name entered by user is present in that entry or not. if (ans1.trim() in j.address[i]) { // Asking user to enter a replaced string for that property's value. r.question(`What would you like to change ${ans1.trim()} to? `, function(ans2) { // Replacing that property's value with the new one. j.address[i][ans1.trim()] = ans2.trim(); // Writing it into JSON file. fs.writeFileSync('./JsonFiles/AddressBook.json', JSON.stringify(j)); console.log("Changed Successfully!"); // Asking the user if he will change anything else. r.question("Would you like to change anything else? ", function(ans3) { // If yes, then calling editUser() function again. if (ans3.trim().startsWith('y')) { editUser(number); } else { // Else closing the program. r.close(); } }); }); } else { // If property is not present, callint this method again to take input again. console.log("No such property found!! Try again, write exact property name."); editUser(number); } }); } // Calling registration method to start the program. registration();
//=:======pour le bouton Post=:=======:=======:=======:=======:=======:=======:=======:=======:=======:====== (avant on le mettait dans un autre js genre highchart.js var index = {}; index.start = function () { document.addEventListener("keydown", index.on_click);// pour evenment quand on appui sur une touche document.addEventListener("click", index.on_click); // pour êvenement quand on clique sur la souris window.setInterval(index.nb_caract,500);//pour le nombre de caractère restant }; index.nb_caract = function (){ var longueur = document.getElementById("content-message").value.length; var rest = 150 - longueur; var ala= document.getElementById("mess_info"); ala.style.color="#3c763d"; ala.innerHTML="Vous pouver encore écrire "+rest+" caractères"; if (rest<0){ var allow = rest*(-1); ala.innerHTML="Please stop writing, you are allow to write 150 caract. So the message won't be posted. Please delete "+allow+" caract!"; ala.style.color="#a94442"; return; } }; index.on_click = function (ev) { var src = ev.target; if (src.has_class("post-message")) { //si on clique sur le bouton Post index.post_btn(); } if (ev.keyCode == 13 && document.getElementById("content-message").value != ""){ // si on appuie sur enter ET que le message n'est pas vide index.post_btn(); } }; index.post_btn = function () { var messageContent = (document.getElementById("content-message").value); if (messageContent.length>150){ var ala= document.getElementById("mess_info"); ala.innerHTML="Your message is too long. Please enter a message lower than 150 characters"; ala.style.color="#a94442"; return; } else{ var pseudo = document.getElementById("nom_client").innerHTML; // var b = new Date().valueOf(); var data = {ac: "post-btn", id: pseudo, content: messageContent, date: dateoftheday() }; // objet data à transmettre index.post(data, index.log_callback); } }; index.log_callback = function () { if (this.readyState == 4 && this.status == 200) { var r = JSON.parse(this.responseText); if (r.message == "ok"){ console.log("message posté"); //window.location.reload(); document.getElementById("content-message").value=""; } else if (r == "ko"){ console.log("erreur message posté"); }else{ console.log("refait ca encore une fois et tu te mange un LOW-KIK"); } } }; index.post = function (data, callback) { var xhr = new XMLHttpRequest(); xhr.open("POST", "/"); xhr.onreadystatechange = callback; xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); xhr.send(JSON.stringify(data)); }; //=:=======:=======:=======:=====pour récupérer les message====:=======:=======:=======:=======:=======:====== var content2 = {}; content2.get_content = function () { var data = {ac: "get-content"}; content2.post(data, content2.log_callback); }; dateoftheday = function() { Today = new Date; // création d'un objet Date appelé "Today" var heure = Today.getHours(); var minute = Today.getMinutes(); var seconde = Today.getSeconds(); var jour = Today.getDate(); var moi = Today.getMonth()+1; var annee = Today.getFullYear(); var DateDuJour = ("posté le " + jour + "/" +moi+"/"+annee+ " à " +heure+ ":" +minute + ":" +seconde); return DateDuJour; } content2.log_callback = function () { if (this.readyState == 4 && this.status == 200) { var r = JSON.parse(this.responseText); var lengthr = r[0].length; /*var a = r[0][lengthr-1]; var b = r[0][lengthr-2]; var c = r[1][lengthr-1]; var d = r[1][lengthr-2]; */ // Début de la boucle qui efface et recréé RAPIDEMENT la chat if (r != "ko") { document.getElementById("message-of-forum").innerHTML = ""; // On efface le contenu avant de recréer le chat // pour le titre var newLine1 = document.createElement('TR'); // pour creer une nouvelle ligne qui contiendra le titre "id" et "messages" // ID var newRow01 = document.createElement('TH');// pour creer une nouvelle colonne avec le titre ID newRow01.style.width="100px"; newRow01.style.minWidth="100px"; newRow01.style.maxWidth="100px"; var newRowText01 = document.createTextNode('ID'); // qui contient la chaine de caractere 'ID' newRow01.appendChild(newRowText01); // On ajoute le titre à TD newLine1.appendChild(newRow01); // On ajoute 'TD' à 'TR' // Messages var newRow02 = document.createElement('TH');// pour creer une nouvelle colonne avec le titre ID newRow02.style.minWidth="50px"; newRow02.style.maxWidth="100px"; var newRowText02 = document.createTextNode('Messages'); // qui contient la chaine de caractere 'ID' newRow02.appendChild(newRowText02); // On ajoute le titre à TD newLine1.appendChild(newRow02); // On ajoute 'TD' à 'TR' // date var newRow03 = document.createElement('TH');// pour creer une nouvelle colonne avec le titre ID newRow03.style.minWidth="50px"; newRow03.style.maxWidth="100px"; var newRowText03 = document.createTextNode('Date'); // qui contient la chaine de caractere 'ID' newRow03.appendChild(newRowText03); // On ajoute le titre à TD newLine1.appendChild(newRow03); // On ajoute 'TD' à 'TR' document.getElementById("message-of-forum").appendChild(newLine1); // On ajoute TR au tableau for(i=lengthr-1; i>lengthr-20; i--) {// pour parcourir du plus récent au plus vieux var newLine = document.createElement('TR'); // pour creer une nouvelle ligne qui contien id + message newLine.style.height="30px"; if(i%2==0){ newLine.style.background="#eee"; } // pour les id var newRow1 = document.createElement('TD');// pour creer une nouvelle colonne avec l'id var newRowText1 = document.createTextNode(r[0][i]);// qui contien lid newRow1.appendChild(newRowText1);// on ajoute le texte à TD newLine.appendChild(newRow1);// on ajoute TD à TR // pour les message // pour creer une nouvelle colonne avec le message var str = r[1][i]; if (str.length > 75){ var newRow2 = document.createElement('td'); var ell = str.substring(0,75); var ell2 = str.substring(76, 150); var newRowText2 = document.createTextNode(ell +"\n" + ell2);// qui contient le message newRow2.appendChild(newRowText2);// on ajoute le message à TD newLine.appendChild(newRow2);// on ajoute TD à TR }else{ var newRow2 = document.createElement('td'); var newRowText2 = document.createTextNode(str);// qui contient le message newRow2.appendChild(newRowText2);// on ajoute le message à TD newLine.appendChild(newRow2);// on ajoute TD à TR } // Pour la date /* var now = new Date(); var annee = now.getFullYear(); var mois = now.getMonth() + 1; var jour = now.getDate(); var heure = now.getHours(); var minute = now.getMinutes(); var seconde = now.getSeconds(); var DateDuJour = ("posté le "+jour+"/"+mois+"/"+annee+" à "+heure+" : "+minute+" : "+seconde+" :" ); // Résultat: Nous sommes le 2/11/2012 et il est 19 heure 57 minutes 37 secondes */ var newRow3 = document.createElement('TD');// pour creer une nouvelle colonne avec la date console.log(r[2][i]); var newRowText3 = document.createTextNode((r[2][i]));// qui contien la date newRow3.style.color ="purple"; newRow3.appendChild(newRowText3);// on ajoute le texte à TD newLine.appendChild(newRow3);// on ajoute TD à TR //on ajoute TR à table document.getElementById("message-of-forum").appendChild(newLine); } //document.getElementById("nom_client").innerHTML=/*"signed as " + */r.id; }}}; content2.post = function (data, callback) { var xhr = new XMLHttpRequest(); xhr.open("POST", "/"); xhr.onreadystatechange = callback; xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); xhr.send(JSON.stringify(data)); }; //=:=======:=======:=======:=======:=======:pour recup ID=======:=======:=======:=======:=======:=======:====== var contentID = {}; contentID.get_content = function () { var data = {ac: "get-id-chat"}; contentID.post(data, contentID.log_callback); }; contentID.log_callback = function () { if (this.readyState == 4 && this.status == 200) { var r = JSON.parse(this.responseText); longueur = r.length; document.getElementById("display-number-id").innerHTML=longueur; var elm = document.getElementById("display-id"); elm.innerHTML=" "; for (i=0;i<longueur;i++){ var newLink = document.createElement('p'); var newLinkText = document.createTextNode(r[i]); newLink.appendChild(newLinkText); elm.appendChild(newLink); } }}; contentID.post = function (data, callback) { var xhr = new XMLHttpRequest(); xhr.open("POST", "/"); xhr.onreadystatechange = callback; xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); xhr.send(JSON.stringify(data)); }; //=:=======:=======:=======:=======:=======:=======:=======:=======:=======:=======:=======:=======:====== HTMLElement.prototype.has_class = function (c) { return (this.className.indexOf(c) >= 0); }; //=:=======:=======:=======:=======:=======:=======:=======:=======:=======:=======:=======:=======:====== window.onload = function () { setTimeout(id.get_id, 1); setTimeout(logout_process.start, 1); setTimeout(index.start, 1); content2.get_content(); contentID.get_content(); }; window.setInterval(content2.get_content,2000); window.setInterval(contentID.get_content,5000); HTMLElement.prototype.has_class = function (c) { return (this.className.indexOf(c) >= 0); }; //=:=======:=======:=======:=======:=======:=======:=======:=======:=======:=======:=======:=======:======