text
stringlengths
7
3.69M
const mongoose = require('mongoose') const Schema = mongoose.Schema const menuPurchaseSchema = new Schema({ user: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }, dish: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Food' }], date: { type: Date, required: true, default: Date.now() }, total: { type: Number } }, { timestamps: true } ) const MenuPurchase = mongoose.model('MenuPurchase', menuPurchaseSchema); module.exports = MenuPurchase;
'use strict'; const fs = require('fs'); const cheerio = require('cheerio'); const extract = require('../index'); describe("extract", function() { let messages; let units; beforeEach(() => { const messageData = fs.readFileSync( './sample/messages.xlf', { encoding: 'utf-8' }); messages = cheerio.load( messageData, { xmlMode: true, decodeEntities: false }); units = extract(messages); }); it("extracts source messages", function() { expect(units[0].source).toBe('Hello!'); expect(units[1].source).toBe('Good bye!'); }); it("extracts target messages", function() { units = extract(messages, true); expect(units[0].source).toBe('Bonjour!'); expect(units[1].source).toBe('Au Revoir!'); }); it("extracts only messages with ID in meaning", function() { expect(units.length).toBe(3); }); it("extracts source description", function() { expect(units[0].description).toBe('A hello world message for the localized component'); expect(units[1].description).toBe('A goodbye message for the localized component'); }); it("extracts interpolation expressions", function() { expect(units[2].source).toBe('{VAR_PLURAL, plural, =0 {just now} =1 {one minute ago} other {<x id="INTERPOLATION" equiv-text="{{minutes}}"/> minutes ago} }'); }); });
spiderJson = {"nodes":[ {"weight":200,"rank":18.635058194041115, "id":1, "url":"https://www.python.org"}, {"weight":284,"rank":18.485533426321847, "id":4, "url":"https://www.python.org/community"}, {"weight":187,"rank":18.609425376717812, "id":6, "url":"https://www.python.org/about"}, {"weight":185,"rank":18.485533426321854, "id":8, "url":"https://www.python.org/about/quotes"}, {"weight":186,"rank":18.485533426321847, "id":9, "url":"https://www.python.org/about/gettingstarted"}, {"weight":257,"rank":19.0, "id":14, "url":"https://www.python.org/downloads/mac-osx"}, {"weight":399,"rank":18.520223172432726, "id":17, "url":"https://www.python.org/doc"}, {"weight":186,"rank":18.485533426321847, "id":18, "url":"https://www.python.org/doc/av"}, {"weight":185,"rank":18.485533426321847, "id":23, "url":"https://www.python.org/community/forums"}, {"weight":201,"rank":18.740605088901773, "id":24, "url":"https://www.python.org/psf/annual-report/2020"}, {"weight":185,"rank":18.609425376717816, "id":26, "url":"https://www.python.org/community/sigs"}, {"weight":195,"rank":18.520223172432726, "id":33, "url":"https://www.python.org/success-stories/category/business"}, {"weight":195,"rank":18.520223172432722, "id":34, "url":"https://www.python.org/success-stories/category/education"}, {"weight":195,"rank":18.485533426321854, "id":35, "url":"https://www.python.org/success-stories/category/engineering"}, {"weight":195,"rank":18.520223172432722, "id":37, "url":"https://www.python.org/success-stories/category/scientific"}, {"weight":195,"rank":18.55224447653506, "id":38, "url":"https://www.python.org/success-stories/category/software-development"}, {"weight":185,"rank":18.77461464391243, "id":41, "url":"https://www.python.org/events"}, {"weight":185,"rank":18.774614643912436, "id":42, "url":"https://www.python.org/events/python-events"}, {"weight":185,"rank":18.77461464391243, "id":43, "url":"https://www.python.org/events/python-user-group"}, {"weight":185,"rank":18.77461464391243, "id":45, "url":"https://www.python.org/events/python-user-group/past"}, {"weight":10,"rank":0.0, "id":48, "url":"https://www.python.org/events/calendars"}, {"weight":27,"rank":3.450402685572631, "id":49, "url":"https://www.python.org/events/python-events/968"}, {"weight":11,"rank":0.0892022042850937, "id":54, "url":"https://www.python.org/success-stories/python-for-financial-machine-learning-at-union-investment"}, {"weight":21,"rank":1.723550636818875, "id":58, "url":"https://www.python.org/users/membership"}, {"weight":35,"rank":1.6298853066939603, "id":59, "url":"https://www.python.org/psf/donations"}, {"weight":177,"rank":18.485533426321854, "id":60, "url":"https://www.python.org/dev"}], "links":[ {"source":0,"target":0,"value":3}, {"source":0,"target":1,"value":3}, {"source":0,"target":2,"value":3}, {"source":0,"target":3,"value":3}, {"source":0,"target":4,"value":3}, {"source":0,"target":5,"value":3}, {"source":0,"target":6,"value":3}, {"source":0,"target":7,"value":3}, {"source":0,"target":8,"value":3}, {"source":0,"target":9,"value":3}, {"source":0,"target":10,"value":3}, {"source":0,"target":11,"value":3}, {"source":0,"target":12,"value":3}, {"source":0,"target":13,"value":3}, {"source":0,"target":14,"value":3}, {"source":0,"target":15,"value":3}, {"source":0,"target":16,"value":3}, {"source":0,"target":17,"value":3}, {"source":0,"target":18,"value":3}, {"source":0,"target":19,"value":3}, {"source":0,"target":20,"value":3}, {"source":0,"target":21,"value":3}, {"source":0,"target":22,"value":3}, {"source":0,"target":23,"value":3}, {"source":0,"target":24,"value":3}, {"source":0,"target":25,"value":3}, {"source":2,"target":2,"value":3}, {"source":2,"target":0,"value":3}, {"source":2,"target":1,"value":3}, {"source":2,"target":3,"value":3}, {"source":2,"target":4,"value":3}, {"source":2,"target":5,"value":3}, {"source":2,"target":6,"value":3}, {"source":2,"target":7,"value":3}, {"source":2,"target":8,"value":3}, {"source":2,"target":9,"value":3}, {"source":2,"target":10,"value":3}, {"source":2,"target":11,"value":3}, {"source":2,"target":12,"value":3}, {"source":2,"target":13,"value":3}, {"source":2,"target":14,"value":3}, {"source":2,"target":15,"value":3}, {"source":2,"target":16,"value":3}, {"source":2,"target":17,"value":3}, {"source":2,"target":18,"value":3}, {"source":2,"target":19,"value":3}, {"source":2,"target":20,"value":3}, {"source":2,"target":21,"value":3}, {"source":2,"target":23,"value":3}, {"source":2,"target":24,"value":3}, {"source":2,"target":25,"value":3}, {"source":7,"target":7,"value":3}, {"source":7,"target":0,"value":3}, {"source":7,"target":1,"value":3}, {"source":7,"target":2,"value":3}, {"source":7,"target":3,"value":3}, {"source":7,"target":4,"value":3}, {"source":7,"target":5,"value":3}, {"source":7,"target":6,"value":3}, {"source":7,"target":8,"value":3}, {"source":7,"target":9,"value":3}, {"source":7,"target":10,"value":3}, {"source":7,"target":11,"value":3}, {"source":7,"target":12,"value":3}, {"source":7,"target":13,"value":3}, {"source":7,"target":14,"value":3}, {"source":7,"target":15,"value":3}, {"source":7,"target":16,"value":3}, {"source":7,"target":17,"value":3}, {"source":7,"target":18,"value":3}, {"source":7,"target":19,"value":3}, {"source":7,"target":25,"value":3}, {"source":1,"target":1,"value":3}, {"source":1,"target":0,"value":3}, {"source":1,"target":2,"value":3}, {"source":1,"target":3,"value":3}, {"source":1,"target":4,"value":3}, {"source":1,"target":5,"value":3}, {"source":1,"target":6,"value":3}, {"source":1,"target":7,"value":3}, {"source":1,"target":8,"value":3}, {"source":1,"target":9,"value":3}, {"source":1,"target":10,"value":3}, {"source":1,"target":11,"value":3}, {"source":1,"target":12,"value":3}, {"source":1,"target":13,"value":3}, {"source":1,"target":14,"value":3}, {"source":1,"target":15,"value":3}, {"source":1,"target":16,"value":3}, {"source":1,"target":17,"value":3}, {"source":1,"target":18,"value":3}, {"source":1,"target":19,"value":3}, {"source":1,"target":25,"value":3}, {"source":14,"target":14,"value":3}, {"source":14,"target":0,"value":3}, {"source":14,"target":1,"value":3}, {"source":14,"target":2,"value":3}, {"source":14,"target":3,"value":3}, {"source":14,"target":4,"value":3}, {"source":14,"target":5,"value":3}, {"source":14,"target":6,"value":3}, {"source":14,"target":7,"value":3}, {"source":14,"target":8,"value":3}, {"source":14,"target":9,"value":3}, {"source":14,"target":10,"value":3}, {"source":14,"target":11,"value":3}, {"source":14,"target":12,"value":3}, {"source":14,"target":13,"value":3}, {"source":14,"target":15,"value":3}, {"source":14,"target":16,"value":3}, {"source":14,"target":17,"value":3}, {"source":14,"target":18,"value":3}, {"source":14,"target":19,"value":3}, {"source":14,"target":25,"value":3}, {"source":9,"target":9,"value":3}, {"source":9,"target":0,"value":3}, {"source":9,"target":1,"value":3}, {"source":9,"target":23,"value":3}, {"source":9,"target":24,"value":3}, {"source":9,"target":2,"value":3}, {"source":9,"target":3,"value":3}, {"source":9,"target":4,"value":3}, {"source":9,"target":5,"value":3}, {"source":9,"target":6,"value":3}, {"source":9,"target":7,"value":3}, {"source":9,"target":8,"value":3}, {"source":9,"target":10,"value":3}, {"source":9,"target":11,"value":3}, {"source":9,"target":12,"value":3}, {"source":9,"target":13,"value":3}, {"source":9,"target":14,"value":3}, {"source":9,"target":15,"value":3}, {"source":9,"target":16,"value":3}, {"source":9,"target":17,"value":3}, {"source":9,"target":18,"value":3}, {"source":9,"target":19,"value":3}, {"source":9,"target":25,"value":3}, {"source":21,"target":21,"value":3}, {"source":21,"target":0,"value":3}, {"source":21,"target":1,"value":3}, {"source":21,"target":2,"value":3}, {"source":21,"target":3,"value":3}, {"source":21,"target":4,"value":3}, {"source":21,"target":5,"value":3}, {"source":21,"target":6,"value":3}, {"source":21,"target":7,"value":3}, {"source":21,"target":8,"value":3}, {"source":21,"target":9,"value":3}, {"source":21,"target":10,"value":3}, {"source":21,"target":11,"value":3}, {"source":21,"target":12,"value":3}, {"source":21,"target":13,"value":3}, {"source":21,"target":14,"value":3}, {"source":21,"target":15,"value":3}, {"source":21,"target":16,"value":3}, {"source":21,"target":17,"value":3}, {"source":21,"target":18,"value":3}, {"source":21,"target":19,"value":3}, {"source":21,"target":25,"value":3}, {"source":4,"target":4,"value":3}, {"source":4,"target":0,"value":3}, {"source":4,"target":1,"value":3}, {"source":4,"target":2,"value":3}, {"source":4,"target":3,"value":3}, {"source":4,"target":5,"value":3}, {"source":4,"target":6,"value":3}, {"source":4,"target":7,"value":3}, {"source":4,"target":8,"value":3}, {"source":4,"target":9,"value":3}, {"source":4,"target":10,"value":3}, {"source":4,"target":11,"value":3}, {"source":4,"target":12,"value":3}, {"source":4,"target":13,"value":3}, {"source":4,"target":14,"value":3}, {"source":4,"target":15,"value":3}, {"source":4,"target":16,"value":3}, {"source":4,"target":17,"value":3}, {"source":4,"target":18,"value":3}, {"source":4,"target":19,"value":3}, {"source":4,"target":25,"value":3}, {"source":23,"target":23,"value":3}, {"source":23,"target":0,"value":3}, {"source":23,"target":1,"value":3}, {"source":23,"target":2,"value":3}, {"source":23,"target":3,"value":3}, {"source":23,"target":4,"value":3}, {"source":23,"target":5,"value":3}, {"source":23,"target":6,"value":3}, {"source":23,"target":7,"value":3}, {"source":23,"target":8,"value":3}, {"source":23,"target":9,"value":3}, {"source":23,"target":10,"value":3}, {"source":23,"target":11,"value":3}, {"source":23,"target":12,"value":3}, {"source":23,"target":13,"value":3}, {"source":23,"target":14,"value":3}, {"source":23,"target":15,"value":3}, {"source":23,"target":16,"value":3}, {"source":23,"target":17,"value":3}, {"source":23,"target":18,"value":3}, {"source":23,"target":19,"value":3}, {"source":23,"target":25,"value":3}, {"source":12,"target":12,"value":3}, {"source":12,"target":0,"value":3}, {"source":12,"target":1,"value":3}, {"source":12,"target":2,"value":3}, {"source":12,"target":3,"value":3}, {"source":12,"target":4,"value":3}, {"source":12,"target":5,"value":3}, {"source":12,"target":6,"value":3}, {"source":12,"target":7,"value":3}, {"source":12,"target":8,"value":3}, {"source":12,"target":9,"value":3}, {"source":12,"target":10,"value":3}, {"source":12,"target":11,"value":3}, {"source":12,"target":13,"value":3}, {"source":12,"target":14,"value":3}, {"source":12,"target":15,"value":3}, {"source":12,"target":16,"value":3}, {"source":12,"target":17,"value":3}, {"source":12,"target":18,"value":3}, {"source":12,"target":19,"value":3}, {"source":12,"target":25,"value":3}, {"source":19,"target":19,"value":3}, {"source":19,"target":0,"value":3}, {"source":19,"target":1,"value":3}, {"source":19,"target":2,"value":3}, {"source":19,"target":3,"value":3}, {"source":19,"target":4,"value":3}, {"source":19,"target":5,"value":3}, {"source":19,"target":6,"value":3}, {"source":19,"target":7,"value":3}, {"source":19,"target":8,"value":3}, {"source":19,"target":9,"value":3}, {"source":19,"target":10,"value":3}, {"source":19,"target":11,"value":3}, {"source":19,"target":12,"value":3}, {"source":19,"target":13,"value":3}, {"source":19,"target":14,"value":3}, {"source":19,"target":15,"value":3}, {"source":19,"target":16,"value":3}, {"source":19,"target":17,"value":3}, {"source":19,"target":18,"value":3}, {"source":19,"target":21,"value":3}, {"source":19,"target":25,"value":3}, {"source":8,"target":8,"value":3}, {"source":8,"target":0,"value":3}, {"source":8,"target":1,"value":3}, {"source":8,"target":2,"value":3}, {"source":8,"target":3,"value":3}, {"source":8,"target":4,"value":3}, {"source":8,"target":5,"value":3}, {"source":8,"target":6,"value":3}, {"source":8,"target":7,"value":3}, {"source":8,"target":9,"value":3}, {"source":8,"target":10,"value":3}, {"source":8,"target":11,"value":3}, {"source":8,"target":12,"value":3}, {"source":8,"target":13,"value":3}, {"source":8,"target":14,"value":3}, {"source":8,"target":15,"value":3}, {"source":8,"target":16,"value":3}, {"source":8,"target":17,"value":3}, {"source":8,"target":18,"value":3}, {"source":8,"target":19,"value":3}, {"source":8,"target":25,"value":3}, {"source":24,"target":24,"value":3}, {"source":24,"target":0,"value":3}, {"source":24,"target":1,"value":3}, {"source":24,"target":9,"value":3}, {"source":24,"target":23,"value":3}, {"source":24,"target":2,"value":3}, {"source":24,"target":3,"value":3}, {"source":24,"target":4,"value":3}, {"source":24,"target":5,"value":3}, {"source":24,"target":6,"value":3}, {"source":24,"target":7,"value":3}, {"source":24,"target":8,"value":3}, {"source":24,"target":10,"value":3}, {"source":24,"target":11,"value":3}, {"source":24,"target":12,"value":3}, {"source":24,"target":13,"value":3}, {"source":24,"target":14,"value":3}, {"source":24,"target":15,"value":3}, {"source":24,"target":16,"value":3}, {"source":24,"target":17,"value":3}, {"source":24,"target":18,"value":3}, {"source":24,"target":19,"value":3}, {"source":24,"target":25,"value":3}, {"source":5,"target":5,"value":3}, {"source":5,"target":0,"value":3}, {"source":5,"target":1,"value":3}, {"source":5,"target":2,"value":3}, {"source":5,"target":3,"value":3}, {"source":5,"target":4,"value":3}, {"source":5,"target":6,"value":3}, {"source":5,"target":7,"value":3}, {"source":5,"target":8,"value":3}, {"source":5,"target":9,"value":3}, {"source":5,"target":10,"value":3}, {"source":5,"target":11,"value":3}, {"source":5,"target":12,"value":3}, {"source":5,"target":13,"value":3}, {"source":5,"target":14,"value":3}, {"source":5,"target":15,"value":3}, {"source":5,"target":16,"value":3}, {"source":5,"target":17,"value":3}, {"source":5,"target":18,"value":3}, {"source":5,"target":19,"value":3}, {"source":5,"target":25,"value":3}, {"source":16,"target":16,"value":3}, {"source":16,"target":0,"value":3}, {"source":16,"target":1,"value":3}, {"source":16,"target":2,"value":3}, {"source":16,"target":3,"value":3}, {"source":16,"target":4,"value":3}, {"source":16,"target":5,"value":3}, {"source":16,"target":6,"value":3}, {"source":16,"target":7,"value":3}, {"source":16,"target":8,"value":3}, {"source":16,"target":9,"value":3}, {"source":16,"target":10,"value":3}, {"source":16,"target":11,"value":3}, {"source":16,"target":12,"value":3}, {"source":16,"target":13,"value":3}, {"source":16,"target":14,"value":3}, {"source":16,"target":15,"value":3}, {"source":16,"target":17,"value":3}, {"source":16,"target":18,"value":3}, {"source":16,"target":19,"value":3}, {"source":16,"target":21,"value":3}, {"source":16,"target":25,"value":3}, {"source":15,"target":15,"value":3}, {"source":15,"target":0,"value":3}, {"source":15,"target":1,"value":3}, {"source":15,"target":2,"value":3}, {"source":15,"target":3,"value":3}, {"source":15,"target":4,"value":3}, {"source":15,"target":5,"value":3}, {"source":15,"target":6,"value":3}, {"source":15,"target":7,"value":3}, {"source":15,"target":8,"value":3}, {"source":15,"target":9,"value":3}, {"source":15,"target":10,"value":3}, {"source":15,"target":11,"value":3}, {"source":15,"target":12,"value":3}, {"source":15,"target":13,"value":3}, {"source":15,"target":14,"value":3}, {"source":15,"target":16,"value":3}, {"source":15,"target":17,"value":3}, {"source":15,"target":18,"value":3}, {"source":15,"target":19,"value":3}, {"source":15,"target":25,"value":3}, {"source":18,"target":18,"value":3}, {"source":18,"target":0,"value":3}, {"source":18,"target":1,"value":3}, {"source":18,"target":2,"value":3}, {"source":18,"target":3,"value":3}, {"source":18,"target":4,"value":3}, {"source":18,"target":5,"value":3}, {"source":18,"target":6,"value":3}, {"source":18,"target":7,"value":3}, {"source":18,"target":8,"value":3}, {"source":18,"target":9,"value":3}, {"source":18,"target":10,"value":3}, {"source":18,"target":11,"value":3}, {"source":18,"target":12,"value":3}, {"source":18,"target":13,"value":3}, {"source":18,"target":14,"value":3}, {"source":18,"target":15,"value":3}, {"source":18,"target":16,"value":3}, {"source":18,"target":17,"value":3}, {"source":18,"target":19,"value":3}, {"source":18,"target":21,"value":3}, {"source":18,"target":25,"value":3}, {"source":10,"target":10,"value":3}, {"source":10,"target":0,"value":3}, {"source":10,"target":1,"value":3}, {"source":10,"target":2,"value":3}, {"source":10,"target":3,"value":3}, {"source":10,"target":4,"value":3}, {"source":10,"target":5,"value":3}, {"source":10,"target":6,"value":3}, {"source":10,"target":7,"value":3}, {"source":10,"target":8,"value":3}, {"source":10,"target":9,"value":3}, {"source":10,"target":11,"value":3}, {"source":10,"target":12,"value":3}, {"source":10,"target":13,"value":3}, {"source":10,"target":14,"value":3}, {"source":10,"target":15,"value":3}, {"source":10,"target":16,"value":3}, {"source":10,"target":17,"value":3}, {"source":10,"target":18,"value":3}, {"source":10,"target":19,"value":3}, {"source":10,"target":25,"value":3}, {"source":17,"target":17,"value":3}, {"source":17,"target":0,"value":3}, {"source":17,"target":1,"value":3}, {"source":17,"target":2,"value":3}, {"source":17,"target":3,"value":3}, {"source":17,"target":4,"value":3}, {"source":17,"target":5,"value":3}, {"source":17,"target":6,"value":3}, {"source":17,"target":7,"value":3}, {"source":17,"target":8,"value":3}, {"source":17,"target":9,"value":3}, {"source":17,"target":10,"value":3}, {"source":17,"target":11,"value":3}, {"source":17,"target":12,"value":3}, {"source":17,"target":13,"value":3}, {"source":17,"target":14,"value":3}, {"source":17,"target":15,"value":3}, {"source":17,"target":16,"value":3}, {"source":17,"target":18,"value":3}, {"source":17,"target":19,"value":3}, {"source":17,"target":21,"value":3}, {"source":17,"target":25,"value":3}, {"source":25,"target":25,"value":3}, {"source":25,"target":0,"value":3}, {"source":25,"target":1,"value":3}, {"source":25,"target":2,"value":3}, {"source":25,"target":3,"value":3}, {"source":25,"target":4,"value":3}, {"source":25,"target":5,"value":3}, {"source":25,"target":6,"value":3}, {"source":25,"target":7,"value":3}, {"source":25,"target":8,"value":3}, {"source":25,"target":9,"value":3}, {"source":25,"target":10,"value":3}, {"source":25,"target":11,"value":3}, {"source":25,"target":12,"value":3}, {"source":25,"target":13,"value":3}, {"source":25,"target":14,"value":3}, {"source":25,"target":15,"value":3}, {"source":25,"target":16,"value":3}, {"source":25,"target":17,"value":3}, {"source":25,"target":18,"value":3}, {"source":25,"target":19,"value":3}, {"source":20,"target":20,"value":3}, {"source":20,"target":0,"value":3}, {"source":20,"target":1,"value":3}, {"source":20,"target":2,"value":3}, {"source":20,"target":3,"value":3}, {"source":20,"target":4,"value":3}, {"source":20,"target":5,"value":3}, {"source":20,"target":6,"value":3}, {"source":20,"target":7,"value":3}, {"source":20,"target":8,"value":3}, {"source":20,"target":9,"value":3}, {"source":20,"target":10,"value":3}, {"source":20,"target":11,"value":3}, {"source":20,"target":12,"value":3}, {"source":20,"target":13,"value":3}, {"source":20,"target":14,"value":3}, {"source":20,"target":15,"value":3}, {"source":20,"target":16,"value":3}, {"source":20,"target":17,"value":3}, {"source":20,"target":18,"value":3}, {"source":20,"target":19,"value":3}, {"source":20,"target":21,"value":3}, {"source":20,"target":25,"value":3}, {"source":22,"target":22,"value":3}, {"source":22,"target":0,"value":3}, {"source":22,"target":1,"value":3}, {"source":22,"target":2,"value":3}, {"source":22,"target":3,"value":3}, {"source":22,"target":4,"value":3}, {"source":22,"target":5,"value":3}, {"source":22,"target":6,"value":3}, {"source":22,"target":7,"value":3}, {"source":22,"target":8,"value":3}, {"source":22,"target":9,"value":3}, {"source":22,"target":10,"value":3}, {"source":22,"target":11,"value":3}, {"source":22,"target":12,"value":3}, {"source":22,"target":13,"value":3}, {"source":22,"target":14,"value":3}, {"source":22,"target":15,"value":3}, {"source":22,"target":16,"value":3}, {"source":22,"target":17,"value":3}, {"source":22,"target":18,"value":3}, {"source":22,"target":19,"value":3}, {"source":22,"target":25,"value":3}, {"source":13,"target":13,"value":3}, {"source":13,"target":0,"value":3}, {"source":13,"target":1,"value":3}, {"source":13,"target":2,"value":3}, {"source":13,"target":3,"value":3}, {"source":13,"target":4,"value":3}, {"source":13,"target":5,"value":3}, {"source":13,"target":6,"value":3}, {"source":13,"target":7,"value":3}, {"source":13,"target":8,"value":3}, {"source":13,"target":9,"value":3}, {"source":13,"target":10,"value":3}, {"source":13,"target":11,"value":3}, {"source":13,"target":12,"value":3}, {"source":13,"target":14,"value":3}, {"source":13,"target":15,"value":3}, {"source":13,"target":16,"value":3}, {"source":13,"target":17,"value":3}, {"source":13,"target":18,"value":3}, {"source":13,"target":19,"value":3}, {"source":13,"target":25,"value":3}, {"source":3,"target":3,"value":3}, {"source":3,"target":0,"value":3}, {"source":3,"target":1,"value":3}, {"source":3,"target":2,"value":3}, {"source":3,"target":4,"value":3}, {"source":3,"target":5,"value":3}, {"source":3,"target":6,"value":3}, {"source":3,"target":7,"value":3}, {"source":3,"target":8,"value":3}, {"source":3,"target":9,"value":3}, {"source":3,"target":10,"value":3}, {"source":3,"target":11,"value":3}, {"source":3,"target":12,"value":3}, {"source":3,"target":13,"value":3}, {"source":3,"target":14,"value":3}, {"source":3,"target":15,"value":3}, {"source":3,"target":16,"value":3}, {"source":3,"target":17,"value":3}, {"source":3,"target":18,"value":3}, {"source":3,"target":19,"value":3}, {"source":3,"target":25,"value":3}, {"source":6,"target":6,"value":3}, {"source":6,"target":0,"value":3}, {"source":6,"target":1,"value":3}, {"source":6,"target":2,"value":3}, {"source":6,"target":3,"value":3}, {"source":6,"target":4,"value":3}, {"source":6,"target":5,"value":3}, {"source":6,"target":7,"value":3}, {"source":6,"target":8,"value":3}, {"source":6,"target":9,"value":3}, {"source":6,"target":10,"value":3}, {"source":6,"target":11,"value":3}, {"source":6,"target":12,"value":3}, {"source":6,"target":13,"value":3}, {"source":6,"target":14,"value":3}, {"source":6,"target":15,"value":3}, {"source":6,"target":16,"value":3}, {"source":6,"target":17,"value":3}, {"source":6,"target":18,"value":3}, {"source":6,"target":19,"value":3}, {"source":6,"target":25,"value":3}, {"source":11,"target":11,"value":3}, {"source":11,"target":0,"value":3}, {"source":11,"target":1,"value":3}, {"source":11,"target":2,"value":3}, {"source":11,"target":3,"value":3}, {"source":11,"target":4,"value":3}, {"source":11,"target":5,"value":3}, {"source":11,"target":6,"value":3}, {"source":11,"target":7,"value":3}, {"source":11,"target":8,"value":3}, {"source":11,"target":9,"value":3}, {"source":11,"target":10,"value":3}, {"source":11,"target":12,"value":3}, {"source":11,"target":13,"value":3}, {"source":11,"target":14,"value":3}, {"source":11,"target":15,"value":3}, {"source":11,"target":16,"value":3}, {"source":11,"target":17,"value":3}, {"source":11,"target":18,"value":3}, {"source":11,"target":19,"value":3}, {"source":11,"target":22,"value":3}, {"source":11,"target":25,"value":3}]};
/** * Created by clicklabs on 4/8/17. */ 'use strict' var mongoose = require('mongoose'); var Schema = mongoose.Schema; //mongoose schema var gigCategorySchema = mongoose.Schema({ category_id : String, category_name : String }, { collection : 'gigcategories' } ); module.exports.GigCategory = mongoose.model('GigCategory', gigCategorySchema,'gigcategories');
/* eslint-disable react/destructuring-assignment */ /* eslint-disable react/prop-types */ /* eslint-disable no-unused-vars */ import { useEffect, useState } from 'react'; import { useDispatch, useSelector } from 'react-redux'; import { Link as RouterLink } from 'react-router-dom'; import { HashLink } from 'react-router-hash-link'; import Grid from '@material-ui/core/Grid'; import { MapContainer, TileLayer, Marker, Popup } from 'react-leaflet'; import { Button, Card, CardActionArea, CardActions, CardContent, CardMedia, Divider, IconButton, Link, ListItem, makeStyles, Paper, Typography, } from '@material-ui/core'; import { grey, yellow } from '@material-ui/core/colors'; import LinkedInIcon from '@material-ui/icons/LinkedIn'; import GitHubIcon from '@material-ui/icons/GitHub'; import ArrowDropDownCircleOutlinedIcon from '@material-ui/icons/ArrowDropDownCircleOutlined'; import Carousel from 'react-material-ui-carousel'; import axios from 'axios'; import { HOME } from '../store/actionTypes/pageTitle'; import hero from '../images/hero.jpg'; const useStyles = makeStyles((theme) => ({ root: { flexGrow: 1, }, container: { padding: theme.spacing(0), backgroundColor: grey[300], }, flexCenter: { display: 'flex', justifyContent: 'center', }, flexColCenter: { display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center', backgroundColor: yellow[700], }, hero: { backgroundImage: `linear-gradient(rgba(0,0,0,0.85) 0%, rgba(0,0,0,0.25) 75%, rgba(224,224,224,1) 100%),url(${hero})`, backgroundSize: 'cover', height: '100vh', color: 'white', display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center', }, image: { width: '100%', }, subTitleHero: { fontSize: '1.5em', fontWeight: 'bold', lineHeight: theme.spacing(0), }, titleHero: { fontSize: '3.5em', fontWeight: 'bold', lineHeight: theme.spacing(0), color: yellow[700], }, cta: { marginTop: '20vh', color: yellow[700], }, title: { display: 'flex', justifyContent: 'center', margin: theme.spacing(5), }, carousel: { display: 'flex', justifyContent: 'center', }, media: { height: 300, width: '75vh', }, paper: { margin: theme.spacing(1), padding: theme.spacing(0.5), textAlign: 'center', justifyContent: 'center', color: theme.palette.text.secondary, }, pin: { width: 200, height: 250, }, pinMedia: { height: 100, }, footer: { backgroundColor: grey[800], color: 'white', marginTop: theme.spacing(10), }, })); const Home = (props) => { const dispatch = useDispatch(); useEffect(() => dispatch({ type: HOME }, [])); const classes = useStyles(); const token = useSelector((state) => state.jwtAUth.token); const [error, setError] = useState(''); const [families, setFamilies] = useState([]); const [properties, setProperties] = useState([]); useEffect(() => { const fetchAllFamilies = async () => { try { setError(null); const { data } = await axios.get( `http://localhost:5000/api/v0/families`, { headers: { authorization: `Bearer ${token}`, }, } ); setFamilies(data); } catch (err) { setError({ ...err }); } }; const fetchAllProperties = async () => { try { setError(null); const { data } = await axios.get( `http://localhost:5000/api/v0/properties`, { headers: { authorization: `Bearer ${token}`, }, } ); setProperties(data); } catch (err) { setError({ ...err }); } }; fetchAllFamilies(); fetchAllProperties(); }, []); return ( <Grid container className={classes.container}> <Grid item xs={12} className={classes.hero}> <p className={classes.subTitleHero}>Welcome to</p> <h1 className={classes.titleHero}>Wild Royale</h1> <h2 className={classes.subTitleHero}> Home of the Royal Wild Family ! </h2> <HashLink to="#family" underline="none" smooth> <IconButton color="inherit" aria-label="cta-down" edge="start" className={classes.cta} > <ArrowDropDownCircleOutlinedIcon fontSize="large" /> </IconButton> </HashLink> </Grid> <Grid item xs={12} id="family"> <Typography variant="h3" className={classes.title}> Family Royale </Typography> <Grid item xs={12} className={classes.carousel}> <Carousel> {families.map((item, i) => ( // eslint-disable-next-line react/no-array-index-key <Item key={i} item={item} /> ))} </Carousel> </Grid> <Divider style={{ margin: '3em' }} /> <Typography variant="h3" className={classes.title}> Castle Royale </Typography> <Grid item xs={12} className={classes.flexCenter}> <MapContainer center={[43.3872, -1.2996]} zoom={10} scrollWheelZoom={false} > <TileLayer attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors' url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" /> {properties.map((item, i) => ( // eslint-disable-next-line react/no-array-index-key <Pin key={i} item={item} /> ))} </MapContainer> </Grid> </Grid> <Grid xs="12" className={classes.footer}> <Typography variant="body2" className={classes.title}> Made with lov.. SWEAT - 02/2021 </Typography> </Grid> </Grid> ); }; function Item(props) { const { firstname, lastname, linkedin, github, zone, picture } = props.item; const classes = useStyles(); return ( <Card className={classes.flexColCenter}> <CardActionArea> <CardMedia className={classes.media} image={picture} title={`${firstname} ${lastname}`} /> <CardContent> <Typography gutterBottom variant="h5" component="h2"> {`${firstname} ${lastname}`} </Typography> </CardContent> </CardActionArea> <CardActions> <Button size="small" color="primary" href={linkedin}> <LinkedInIcon /> </Button> <Button size="small" color="primary" href={github}> <GitHubIcon /> </Button> <Button size="small" color="primary"> {zone} </Button> </CardActions> </Card> ); } function Pin(props) { const { label, lat, long, picture, reservation } = props.item; const classes = useStyles(); const position = [lat, long]; const pic = picture[picture.length - 1]; return ( <Marker position={position}> <Popup> <Card className={classes.pin}> <CardActionArea> <CardMedia className={classes.pinMedia} image={pic.url} title={pic.alt} /> <CardContent> <Typography gutterBottom variant="body1" component="h3"> {label} </Typography> <Typography variant="body3" color="textSecondary" component="p"> {pic.alt} </Typography> </CardContent> </CardActionArea> </Card> </Popup> </Marker> ); } export default Home;
// // 加载模块函数 // console.log(require) // // 导出对象别名 // console.log(exports) // // 模块对象 // console.log(module) // // 当前文件目录 // console.log(__dirname) // // 当前文件绝对路径 // console.log(__filename) import { fileURLToPath } from 'url' import { dirname } from 'path' const __filename = fileURLToPath(import.meta.url) const __dirname = dirname(__filename)
/** * Created by cl-macmini-63 on 2/24/17. */ 'use strict'; const responseFormatter = require('Utils/responseformatter.js'); const bookingSchema = require('schema/mongo/bookingschema.js'); const SPGigLocationMapperSchema = require('schema/mongo/SPgiglocationmapper'); const SPProfileSchema = require('schema/mongo/SPprofile'); const gigsSchema = require('schema/mongo/gigsschema'); const masterServiceSchema = require('schema/mongo/masterserviceschema'); const userSchema = require('schema/mongo/userschema'); const seekerProductSchema=require('schema/mongo/Seekerproductinfo.js'); const log = require('Utils/logger.js'); const logger = log.getLogger(); var async=require('async'); const messenger = require('Utils/messenger.js'); const push = require('Utils/push.js'); var mongoose = require('mongoose'); const SPpushcount = require('schema/mongo/SPpushcount'); let moment=require('moment'); module.exports={}; module.exports.createBookingForSeekerSelect = function(payload, callback) { var booking = new bookingSchema.Booking(payload); let bookingFinal=null; var self=this //booking.is_accepted = true; // make it true when SP accepts push booking.status = 'Unconfirmed'; var current_status_object = { "status" : 'Not-Accepted', "datetime" : new Date().toISOString(), "status_by" : 'SEEKER' }; booking.current_status_info.push(current_status_object); /*booking.current_status_info.status = 'Not-Accepted'; booking.current_status_info.datetime = new Date().toISOString();*/ booking.booking_item_info.booked_price=payload.booking_item_info.booked_price; logger.debug("booking information: ", booking); let providerData = {}; let seekerData={} let gigData={} async.series([ function(cb){ userSchema.User.findOne({user_id:payload.seeker_id},{},{lean:true},function(err,data){ if(err){ cb(err) } else{ seekerData=data; booking.seeker_device_token=seekerData.device_token booking.seeker_device_type=seekerData.device_type cb(null) } }) }, function(cb){ //get data here save in a const id = mongoose.Types.ObjectId(payload.provider_id); userSchema.User.findOne({_id:id},{device_token :1,device_type:1,profilePhoto:1,first_name:1,last_name:1,address:1,locationLatitude:1,locationLongitude:1,role_token:1,provider_notification_flag:1}, function (err, provider) { console.log('Provider details returned', provider); if (err){ logger.error("Find failed", err); cb(err); } else { providerData = provider; booking.ODS_type=payload.ODS_type booking.seeker_image=seekerData.profilePhoto booking.provider_image=providerData.profilePhoto booking.provider_device_token=providerData.device_token booking.provider_device_type=providerData.device_type; booking.provider_name = providerData.first_name+' '+providerData.last_name; if(payload.is_seeker_location==true){ if(payload.virtual_address){ booking.is_seeker_location = payload.is_seeker_location, booking.virtual_address=payload.virtual_address console.log("Provider datas virtual",payload) cb(null) } else{ booking.is_seeker_location = payload.is_seeker_location; booking.booking_address = payload.booking_address; booking.booking_latitude = payload.booking_latitude; booking.booking_longitude = payload.booking_longitude; booking.booking_address1=payload.booking_address1; booking.booking_latitude1=payload.booking_latitude1; booking.booking_longitude1=payload.booking_longitude1; console.log("Provider datas 123",payload) cb(null) } } else{ booking.booking_address=providerData.address booking.booking_latitude=providerData.locationLatitude booking.booking_longitude=providerData.locationLongitude booking.is_seeker_location=payload.is_seeker_location console.log("Provider datas 1234567852 ",providerData); cb(null); } } }); }, function(cb){ gigsSchema.Gigs.findOne({gig_id:payload.booking_item_info.gig_id},{gig_id:1,service_id:1,gig_name:1,service_name:1},{lean:true},function(err,data){ if(err){ cb(err) } else{ gigData=data cb(null) } }) }, function(cb){ booking.booking_item_info.gig_name=gigData.gig_name; booking.booking_item_info.service_name=gigData.service_name ; booking.on('error', function(err){logger.error('Error saving admin: ', err);}) //use your data here booking.save(function(err,newBooking){ if (err){ //responseFormatter.formatServiceResponse(err, callback); cb(null); } else { bookingFinal=newBooking console.log("bookingFinal",bookingFinal) cb(null); } }); }, function(cb){ const deviceDetails = []; let deviceToken = null; let deviceType = providerData.device_type; let deviceTokenFound = false; if(providerData.role_token && providerData.role_token.length){ for(var i = 0; i < providerData.role_token.length; i++){ if(providerData.role_token[i].role == 'PROVIDER'){ deviceToken = providerData.role_token[i].token; deviceTokenFound = true; break; } } } console.log('deviceTokenFound --->',deviceTokenFound); if(!deviceTokenFound || providerData.provider_notification_flag == false){ console.log('in bookingmodel.js createBookingForSeekerSelect Failed to Send Push......Device Token not found for ',payload.provider_id," Either this provider is logged out or role_token object is not present in user collection."); cb(null); }else{ console.log("device token for push send",deviceToken) console.log("device type for push send",deviceType) console.log("booking final two data",bookingFinal.booking_type,bookingFinal._id) console.log("booking final data",bookingFinal) const n=new Date().toISOString() let pushData={} if(payload.booking_address){ pushData.booking_address=payload.booking_address console.log("payload booking address",pushData.booking_address) } else { pushData.booking_address={} } if(payload.booking_address1){ pushData.booking_address1=payload.booking_address1 } else{ pushData.booking_address1={} } if(payload.virtual_address){ pushData.virtual_address=payload.virtual_address } else{ pushData.virtual_address='' } pushData.profile_photo=seekerData.profilePhoto, pushData.first_name=seekerData.first_name, pushData.last_name=seekerData.last_name, pushData.booking_type=bookingFinal.booking_type, pushData.is_seeker_location=bookingFinal.is_seeker_location, pushData.booking_id=bookingFinal._id, pushData.booking_data= n, pushData.push_type= 'new booking' , pushData.ODS_type=payload.ODS_type, pushData.push_date=n, pushData.bid_amount="", console.log("bookPayload data Seeker Select",pushData) deviceDetails.push({ device_token :deviceToken, device_type :deviceType }); const pushDetailsSP={ deviceDetails: deviceDetails, text: "You Have a New Booking Available Please Confirm", payload: pushData } console.log("push details SP",pushDetailsSP); push.sendPush(pushDetailsSP,"PROVIDER"); //setTim console.log("data._id++++++++++++Seeker Select",bookingFinal._id) cb(null) } } ],function(err,data){ console.log('in final function : data : ',data); if(err){ callback(err) } else{ data=bookingFinal; callback(null,data) } }) }; module.exports.createBookingProducts=function(payload,callback){ var booking = new bookingSchema.Booking(payload); let bookingFinal=null; var self=this //booking.is_accepted = true; // make it true when SP accepts push booking.status = 'Unconfirmed'; var current_status_object = { "status" : 'Not-Accepted', "datetime" : new Date().toISOString(), "status_by" : 'SEEKER' }; booking.current_status_info.push(current_status_object); /*booking.current_status_info.status = 'Not-Accepted'; booking.current_status_info.datetime = new Date().toISOString();*/ booking.booking_item_info.booked_price=payload.booking_item_info.booked_price; logger.debug("booking information: ", booking); let providerData = {}; let seekerData={} let gigData={} async.series([ function(cb){ userSchema.User.findOne({user_id:payload.seeker_id},{},{lean:true},function(err,data){ if(err){ cb(err) } else{ seekerData=data; booking.seeker_device_token=seekerData.device_token booking.seeker_device_type=seekerData.device_type cb(null) } }) }, function(cb){ //get data here save in a const id = mongoose.Types.ObjectId(payload.provider_id); userSchema.User.findOne({_id:id},{device_token :1,device_type:1,profilePhoto:1,first_name:1,last_name:1,address:1,locationLatitude:1,locationLongitude:1}, function (err, provider) { console.log('Provider details returned', provider); if (err){ logger.error("Find failed", err); cb(err); } else { providerData = provider; booking.ODS_type=payload.ODS_type booking.seeker_image=seekerData.profilePhoto booking.provider_image=providerData.profilePhoto booking.provider_device_token=providerData.device_token booking.provider_device_type=providerData.device_type if(payload.is_seeker_location==true){ if(payload.virtual_address){ booking.is_seeker_location = payload.is_seeker_location, booking.virtual_address=payload.virtual_address console.log("Provider datas virtual",payload) cb(null) } else{ booking.is_seeker_location = payload.is_seeker_location; booking.booking_address = payload.booking_address; booking.booking_latitude = payload.booking_latitude; booking.booking_longitude = payload.booking_longitude; booking.booking_address1=payload.booking_address1; booking.booking_latitude1=payload.booking_latitude1; booking.booking_longitude1=payload.booking_longitude1; console.log("Provider datas 123",payload) cb(null) } } else{ booking.booking_address=providerData.address booking.booking_latitude=providerData.locationLatitude booking.booking_longitude=providerData.locationLongitude booking.is_seeker_location=payload.is_seeker_location console.log("Provider datas 1234567852 ",providerData); cb(null); } } }); }, function(cb){ gigsSchema.Gigs.findOne({gig_id:payload.booking_item_info.gig_id},{gig_id:1,service_id:1,gig_name:1,service_name:1},{lean:true},function(err,data){ if(err){ cb(err) } else{ gigData=data cb(null) } }) }, function(cb){ booking.booking_item_info.gig_name=gigData.gig_name; booking.booking_item_info.service_name=gigData.service_name ; booking.on('error', function(err){logger.error('Error saving admin: ', err);}) //use your data here booking.save(function(err,newBooking){ if (err){ //responseFormatter.formatServiceResponse(err, callback); cb(null); } else { bookingFinal=newBooking console.log("bookingFinal",bookingFinal) cb(null); } }); }, /*function(cb){ const deviceDetails=[] console.log("device token for push send",providerData.device_token) console.log("device type for push send",providerData.device_type) console.log("booking final two data",bookingFinal.booking_type,bookingFinal._id) console.log("booking final data",bookingFinal) const n=new Date().toISOString() var pushData={ profile_photo:providerData.profilePhoto, first_name:seekerData.first_name, last_name:seekerData.last_name, booking_type:bookingFinal.booking_type, booking_address:bookingFinal.booking_address, booking_address1:bookingFinal.booking_address1, virtual_address:bookingFinal.virtual_address, is_seeker_location:bookingFinal.is_seeker_location, booking_id:bookingFinal._id, booking_data: n, push_type: 'new booking' , ODS_type:payload.ODS_type, push_date:n, bid_amount:"", } console.log("bookPayload data Seeker Select",pushData) deviceDetails.push({ device_token :providerData.device_token, device_type :providerData.device_type, }); const pushDetailsSP={ deviceDetails: deviceDetails, text: "You Have a New Booking Available Please Confirm", payload: pushData } console.log("push details SP",pushDetailsSP) push.sendPush(pushDetailsSP,"PROVIDER"); //setTim console.log("data._id++++++++++++Seeker Select",bookingFinal._id) cb(null) }*/ ],function(err,data){ console.log('in final function : data : ',data); if(err){ callback(err) } else{ data=bookingFinal; //setTimeout(function(){self.isBookingAcceptedBySP(bookingFinal._id,callback)},60000); callback(null,data) } }) } module.exports.bookingAcceptedBySP = function(payload, callback) { let dataToUpdate={} let bookingData = {}; let acceptedData={} let bookingUpdatedData = {}; dataToUpdate.is_accepted = true; let current_status_object1={} let current_status_object2={} if(payload.is_product_based==true){ dataToUpdate.status = 'Unconfirmed'; current_status_object1 = { "status" : 'Accepted', "datetime" : new Date().toISOString(), "status_by": 'PROVIDER' } current_status_object2={ "status" : 'Confirmation-Awaited', "datetime" : new Date().toISOString(), "status_by": 'PROVIDER' }; } else{ dataToUpdate.status = 'Confirmed'; current_status_object1 = { "status" : 'Accepted', "datetime" : new Date().toISOString(), "status_by": 'PROVIDER' } current_status_object2={ "status" : 'Payment-Awaited', "datetime" : new Date().toISOString(), "status_by": 'PROVIDER' }; } let providerData=null; let providerLocationData = null; dataToUpdate.status = 'Confirmed'; dataToUpdate.pre_on_the_way=true; async.series([ function(cb){ userSchema.User.findOne({user_id:payload.provider_id},{address:1,locationLatitude:1,locationLongitude:1,profilePhoto:1,mobile:1,countryCode:1,email:1,device_token:1,device_type:1,first_name:1,last_name:1,average_rating:1,role_token:1}, function (err, provider) { console.log('Provider details returned--------------', provider); if (err){ logger.error("Find failed", err); cb(err); } else { providerData=provider; cb(null); } }); }, function(cb){ SPProfileSchema.SPProfile.findOne({provider_id : payload.provider_id},{geometry:1}, function (err, providerdata) { console.log('Provider location details returned--------------', providerdata); if (err){ logger.error("Find failed", err); cb(err); } else { providerLocationData=providerdata console.log("providerLocationData",providerLocationData) cb(null); } }); }, function(cb){ let id= mongoose.Types.ObjectId(payload.booking_id) //mongoo //get data here save in a variable bookingSchema.Booking.findOne({'_id':payload.booking_id}, function (err, booking) { console.log('Booking details returned', booking); if (err){ logger.error("Find failed", err); responseFormatter.formatServiceResponse(err, cb ,'Error Occurred','error',500); //cb(err); } else { console.log("bookingData++++++++accepted ",booking); if(booking.is_accepted == true){ responseFormatter.formatServiceResponse({}, cb ,'Request Already Accepted','error',400); } else{ console.log("providerData in bookingSchema",providerData) console.log("bookingData ",booking); bookingData = booking; console.log("booking ods type",booking.ODS_type) if(booking.ODS_type == 'System Select' || booking.ODS_type == 'Reverse Bid'){ dataToUpdate.provider_device_token=providerData.device_token dataToUpdate.provider_device_type=providerData.device_type dataToUpdate.provider_image=providerData.profilePhoto dataToUpdate.provider_name=providerData.first_name+' '+providerData.last_name dataToUpdate.provider_id = payload.provider_id if(payload.is_seeker_location==false){ dataToUpdate.booking_address=providerData.address dataToUpdate.booking_latitude=providerLocationData.geometry.coordinates[1] dataToUpdate.booking_longitude=providerLocationData.geometry.coordinates[0] } /*bookingSchema.Booking.findOneAndUpdate({_id:id},{dataToUpdate},{lean:true,new:true},function(err,updateData){ if(err){ cb(err) } else{ console.log("updateData n=in system and reverse",updateData) cb(null) } })*/ cb(null) } else { cb(null); } } } }); }, function(cb){ const SeekerDeviceDetails = []; const ProviderDeviceDetails = []; console.log("dataToUpdate on Seeker and reverse",dataToUpdate); //get data here save in a variable bookingSchema.Booking.findOneAndUpdate({_id:payload.booking_id},{$push: {current_status_info:{$each: [current_status_object2,current_status_object1]}},"$set":dataToUpdate},{new:true},function(err,data){ if(err){ responseFormatter.formatServiceResponse(err, cb ,'Error Occurred','error',500); } else{ console.log("updated booking data------------",data); bookingUpdatedData = data; const n = new Date().toISOString(); // send push notification to seeker about confirm booking const pushData={ provider_photo:providerData.profilePhoto, provider_id :payload.provider_id, provider_name :payload.provider_name, provider_email:providerData.email, gig_id:bookingData.booking_item_info.gig_id, provider_phone:providerData.mobile, provider_country_code : providerData.countryCode, provider_address:providerData.address, provider_latitude:providerData.locationLatitude, provider_longitude:providerData.locationLongitude, bookingID :bookingData._id, booking_info :bookingData.booking_item_info, is_product_based:payload.is_product_based, booking_data:n, push_type:"accept booking", ODS_type:bookingData.ODS_type, average_rating:providerData.average_rating } console.log("bookingData seeker device details",bookingData.seeker_device_token,bookingData.seeker_device_type) SeekerDeviceDetails.push({ device_token :bookingData.seeker_device_token, device_type :bookingData.seeker_device_type, }); ProviderDeviceDetails.push({ device_token :providerData.device_token, device_type :providerData.device_type, }); const formattedDate=moment(n).format('MMMM DD,YYYY') const pushDetailsSPToSeeker={ deviceDetails: SeekerDeviceDetails, text: "Congratulations! Your request dated on "+formattedDate +" has been accepted Confirmed", payload: pushData } /*const pushDetailsSeekerToSP={ deviceDetails: ProviderDeviceDetails, text: "Congratulations! Your request dated on "+formattedDate +" has been accepted Confirmed", payload: pushData }*/ push.sendPush(pushDetailsSPToSeeker,"SEEKER"); if(bookingData.ODS_type == 'System Select' || bookingData.ODS_type == 'Reverse Bid'){ const pushDetailsSeekerToSP = { deviceDetails: ProviderDeviceDetails, text: "Seeker has successfully recieved the booking details.", payload: {"push_type" : 'confirm-provider',"message" :"Seeker has successfully recieved the booking details"} } push.sendPush(pushDetailsSeekerToSP,"PROVIDER"); } cb(null , data); } }) }, function(cb){ SPpushcount.SPPush.findOneAndUpdate({booking_id:payload.booking_id,provider_id:payload.provider_id},{accepted:true},{lean:true,new:true},function(err,data){ if(err){ cb(err) } else{ acceptedData=data console.log("updated data",data) cb(null) } }) }, function(cb){ SPProfileSchema.SPProfile.findOneAndUpdate({provider_id : payload.provider_id},{ $inc: { acceptance_count: 1 } },{new:true},function(err,SPData){ console.log('Booking acceptance count incremented in SP profile err : ',err, " SPData : ",SPData); if(err){ cb(err); }else{ cb(null); } }) }, function(cb){ SPpushcount.SPPush.find({booking_id:payload.booking_id,accepted:false},{},{lean:true},function(err,SPpushcount){ if(err){ cb(err) } else{ console.log("SPpushcount",SPpushcount) const parallelF = [] SPpushcount.forEach(function (result) { console.log("result+++++++++++", result) parallelF.push(function (cbb) { const dataToSend=result dataToSend.provider_accepted=payload.provider_id process.emit('refreshDriverLocation', dataToSend); cbb(null) }); }) console.log("paralleF", parallelF); async.parallel(parallelF, function (error, data) { if (error) { return cb(error); } else { console.log("__________", data) cb(null, data) } }); } }) } ],function(err,data){ console.log('in final function : data : ',data); if(err){ callback(err) } else{ data=bookingUpdatedData; const n = new Date().toISOString(); const formattedDate=moment(n).format('MMMM DD,YYYY') const msg = 'Congratulations! Your request dated on' +formattedDate+ 'has been Confirmed'; responseFormatter.formatServiceResponse(data, callback ,msg,'Success',200); } }) }; //Product Based confirmation module.exports.productBookingAcceptedBySP = function(payload, callback) { let bookingData = {}; let current_status_object={} if(payload.is_product_based==true){ current_status_object={ "status" : 'Payment-Awaited', "datetime" : new Date().toISOString(), "status_by": 'PROVIDER' }; } let providerData=null; let providerLocationData = null; async.series([ function(cb){ userSchema.User.findOne({user_id:payload.provider_id},{address:1,locationLatitude:1,locationLongitude:1,profilePhoto:1,mobile:1,countryCode:1,email:1,device_token:1,device_type:1}, function (err, provider) { console.log('Provider details returned--------------', provider); if (err){ logger.error("Find failed", err); cb(err); } else { providerData=provider cb(null); } }); }, function(cb){ SPProfileSchema.SPProfile.findOne({provider_id : payload.provider_id},{geometry:1}, function (err, providerdata) { console.log('Provider location details returned--------------', providerdata); if (err){ logger.error("Find failed", err); cb(err); } else { providerLocationData=providerdata console.log("providerLocationData",providerLocationData) cb(null); } }); }, function(cb){ const deviceDetails=[] //get data here save in a variable bookingSchema.Booking.findOneAndUpdate({_id:payload.booking_id},{$push: {current_status_info: current_status_object},$set:{status:'Confirmed'}},{lean:true,new:true},function(err,data){ if(err){ responseFormatter.formatServiceResponse(err, cb ,'Error Occurred','error',500); } else{ console.log("updated booking data------------",data); bookingData = data; const n = new Date().toISOString() // send push notification to seeker about confirm booking const pushData={ provider_photo:providerData.profilePhoto, provider_id :payload.provider_id, provider_name :payload.provider_name, provider_email:providerData.email, provider_phone:providerData.mobile, provider_country_code : providerData.countryCode, provider_address:providerData.address, provider_latitude:providerData.locationLatitude, provider_longitude:providerData.locationLongitude, bookingID :bookingData._id, booking_info :bookingData.booking_item_info, is_product_based:payload.is_product_based, booking_data:n, push_type:"accept booking", ODS_type:bookingData.ODS_type } console.log("bookingData seeker device details",bookingData.seeker_device_token,bookingData.seeker_device_type) deviceDetails.push({ device_token :bookingData.seeker_device_token, device_type :bookingData.seeker_device_type, }); const formattedDate=moment(n).format('MMMM DD,YYYY') const pushDetailsSP={ deviceDetails: deviceDetails, text: "Congratulations! Your request dated on "+formattedDate +" has been accepted By"+" "+payload.provider_name, payload: pushData } push.sendPush(pushDetailsSP,"SEEKER"); cb(null , data); } }) }, ],function(err,data){ console.log('in final function : data : ',data); if(err){ callback(err) } else{ data=bookingData const n = new Date().toISOString() const formattedDate=moment(n).format('MMMM DD,YYYY') const msg='Congratulations! Your booking dated on " +formattedDate+ " has been confirmed'; responseFormatter.formatServiceResponse(data, callback ,msg,'Success',200); } }) }; module.exports.bookingRejectedByProvider = function(payload, callback) { console.log('payload in reject booking :: ',payload); let bookingData = {}; let bookingUpdatedData = {}; var current_status_object = { "status" : 'Rejected', "datetime" : new Date().toISOString(), "status_by": 'PROVIDER' } ; let dataToUpdate = { status :'Closed', date :new Date().toISOString(), status_by:'provider', rejection_reason:payload.rejection_reason, is_rejected:true }; console.log('dataToUpdate :: ',dataToUpdate); let providerData=null; const id=mongoose.Types.ObjectId(payload.booking_id) async.series([ function(cb){ //get data here save in a variable bookingSchema.Booking.findOne({_id:id}, function (err, booking) { console.log('Booking details returned', booking); if (err){ logger.error("Find failed", err); responseFormatter.formatServiceResponse(err, cb ,'Error Occurred','error',500); //cb(err); } else { console.log("the data to be rejected ",booking); if(booking.is_accepted == true){ responseFormatter.formatServiceResponse({}, cb ,'Request Already accepted','error',400); } else{ console.log("bookingData ",booking); bookingData = booking; cb(); } } }); }, function(cb){ userSchema.User.findOne({user_id:payload.provider_id},{provider_name:1,profilePhoto:1,email:1,mobile:1,countryCode:1,locationLatitude:1,locationLongitude:1},{lean:true},function(err,data){ if(err){ cb(err) } else{ if(!data){ responseFormatter.formatServiceResponse({}, cb ,'No such User','error',500); } else{ providerData=data cb(null) } } }) }, function(cb){ SPProfileSchema.SPProfile.findOneAndUpdate({provider_id : payload.provider_id},{ $inc: { rejectance_count : 1 } },{new:true},function(err,SPData){ console.log('Booking rejectance count incremented in SP profile err : ',err, " SPData : ",SPData); if(err){ cb(err); }else{ cb(null); } }) }, function(cb){ const deviceDetails=[] //get data here save in a variable bookingSchema.Booking.findOneAndUpdate({_id:id},{$push:{current_status_info:current_status_object},$set:dataToUpdate},{lean:true,new:true},function(err,data){ if(err){ responseFormatter.formatServiceResponse(err, cb ,'Error Occurred','error',500); } else{ console.log("updated booking data",data); bookingUpdatedData = data; const n = new Date().toISOString() // send push notification to seeker about confirm booking const pushData={ provider_photo:providerData.profilePhoto, provider_id :payload.provider_id, provider_name :providerData.provider_name, provider_email:providerData.email, provider_phone:providerData.mobile, provider_country_code : providerData.countryCode, provider_latitude:providerData.locationLatitude, provider_longitude:providerData.locationLongitude, bookingID :bookingUpdatedData._id, booking_info :bookingUpdatedData.booking_item_info, booking_data:n, push_type:"rejected booking", ODS_type:bookingUpdatedData.ODS_type } deviceDetails.push({ device_token :bookingUpdatedData.seeker_device_token, device_type :bookingUpdatedData.seeker_device_type, }); const formattedDate=moment(n).format('MMMM DD YYYY') const pushDetailsSP={ deviceDetails: deviceDetails, //"Your request timed at "+formattedDate+" has been rejected due to following reason:"+" "+payload.rejection_reason, text: "Your Booking Has Been Declined", payload: pushData } push.sendPush(pushDetailsSP,"SEEKER"); cb(null , data); } }) }],function(err,data){ console.log('data recieved by sp: ',data); if(err){ callback(err) } else{ data=bookingUpdatedData responseFormatter.formatServiceResponse(data, callback ,'Your Booking has been declined','Success',200); } }) }; //function checking already accepted booking module.exports.productBookingRejectedBySP = function(payload, callback) { let bookingData = {}; let bookingUpdatedData = {}; var current_status_object = { "status" : 'Rejected', "datetime" : new Date().toISOString(), "status_by": 'PROVIDER' } ; let dataToUpdate = { status :'Closed', date :new Date().toISOString(), status_by:'provider', rejection_reason:payload.rejection_reason, $set:{is_rejected:true} }; console.log('dataToUpdate :: ',dataToUpdate); let providerData=null; const id=mongoose.Types.ObjectId(payload.booking_id) async.series([ function(cb){ //get data here save in a variable bookingSchema.Booking.findOne({_id:id}, function (err, booking) { console.log('Booking details returned', booking); if (err){ logger.error("Find failed", err); responseFormatter.formatServiceResponse(err, cb ,'Error Occurred','error',500); //cb(err); } else { console.log("the data to be rejected ",booking); if(booking.is_accepted == true){ responseFormatter.formatServiceResponse({}, cb ,'Request Already accepted','error',400); } else{ console.log("bookingData ",booking); bookingData = booking; cb(); } } }); }, function(cb){ userSchema.User.findOne({user_id:payload.provider_id},{provider_name:1,profilePhoto:1,email:1,mobile:1,countryCode:1,locationLatitude:1,locationLongitude:1},{lean:true},function(err,data){ if(err){ cb(err) } else{ if(!data){ responseFormatter.formatServiceResponse({}, cb ,'No such User','error',500); } else{ providerData=data cb(null) } } }) }, function(cb){ const deviceDetails=[] //get data here save in a variable bookingSchema.Booking.findOneAndUpdate({_id:id},{$push:{current_status_info:current_status_object},$set:dataToUpdate},{lean:true,new:true},function(err,data){ if(err){ responseFormatter.formatServiceResponse(err, cb ,'Error Occurred','error',500); } else{ console.log("updated booking data",data); bookingUpdatedData = data; const n = new Date().toISOString() // send push notification to seeker about confirm booking const pushData={ provider_photo:providerData.profilePhoto, provider_id :payload.provider_id, provider_name :providerData.provider_name, provider_email:providerData.email, provider_phone:providerData.mobile, provider_country_code : providerData.countryCode, provider_latitude:providerData.locationLatitude, provider_longitude:providerData.locationLongitude, bookingID :bookingUpdatedData._id, booking_info :bookingUpdatedData.booking_item_info, booking_data:n, push_type:"rejected booking", ODS_type:bookingUpdatedData.ODS_type } deviceDetails.push({ device_token :bookingUpdatedData.seeker_device_token, device_type :bookingUpdatedData.seeker_device_type, }); const formattedDate=moment(n).format('MMMM DD YYYY') const pushDetailsSP={ deviceDetails: deviceDetails, text: "Your request timed at "+formattedDate+" has been rejected due to following reason:"+" "+payload.rejection_reason, payload: pushData } push.sendPush(pushDetailsSP,"SEEKER"); cb(null , data); } }) }],function(err,data){ console.log('data recieved by sp: ',data); if(err){ callback(err) } else{ data=bookingUpdatedData responseFormatter.formatServiceResponse(data, callback ,'Booking rejected','Success',200); } }) }; module.exports.isBookingAcceptedBySP=function(bookingID,callback){ const id = mongoose.Types.ObjectId(bookingID); bookingSchema.Booking.findOne({_id:id,is_accepted:true}, function (err, booking) { console.log('Booking details returned----------------', booking); if (err){ logger.error("Find failed", err); responseFormatter.formatServiceResponse(err, callback ,'Error Occurred Please Try After Some Time','error',500); } else { console.log("is bookingAccepted>>> booking",booking) if(!booking){ responseFormatter.formatServiceResponse({}, callback ,'service provider is busy at this moment please try again later','success',200); } else{ callback(null,booking) } //if(booking){ // responseFormatter.formatServiceResponse(booking, callback ,'booking already accepted by one of the SP','success',200); // // callback(null,booking) //} // else{ // responseFormatter.formatServiceResponse({}, callback ,'No Providers Found Nearby Please Try After Some Time','error',404); // // callback(null,{}) //} } }); } module.exports.acceptedDataSP=function(payload,callback){ async.waterfall([ function(cb){ userSchema.User.findOne({user_id:payload.provider_id},{email:1 , first_name:1, last_name:1, mobile:1, countryCode:1, profilePhoto:1,address:1},{lean:true},function(err,provider){ if(err){ cb(err) } else{ //providerinfo=data cb(null , provider); } }) }, function(providerinfo , cb){ SPGigLocationMapperSchema.SPGigLocationMapper.findOne({provider_id:payload.provider_id},{revenue:1,pricing:1,_id:0},{lean:true},function(err,data){ console.log('err-----',err,'pricing data initial------- ',data); if(err){ cb(err, null) } else{ if(data && data.pricing){ console.log('pricing data final :: ',data); providerinfo.pricingDetails = data; cb(null,providerinfo); } else{ cb(null,providerinfo); } } }) }, function(providerinfo,cb){ SPProfileSchema.SPProfile.findOne({provider_id:payload.provider_id},{geometry:1 ,reviews:1},{lean:true},function(err,SPprofile){ if(err){ cb(err) } else{ if(SPprofile && SPprofile.geometry){ providerinfo.geometry=SPprofile.geometry; providerinfo.reviews=SPprofile.reviews; cb(null,providerinfo) } else{ cb(null,providerinfo) } } }) } ],function(err,data){ console.log("sbse final",err,data); if(err){ callback(err) console.log("err+++++++",err) } else{ callback(null,data) console.log("data+++++++",data) } }) } module.exports.getBookingDetails=function(bookingID,callback){ const id = mongoose.Types.ObjectId(bookingID); bookingSchema.Booking.findOne({_id:id},{},{lean:true}, function (err, booking) { console.log('Booking details returned----------------', booking); if (err){ logger.error("Find failed", err); responseFormatter.formatServiceResponse(err, callback ,'Error Occurred Please Try After Some Time','error',500); } else { if(booking) { booking.date = new Date().toISOString(); responseFormatter.formatServiceResponse(booking, callback, 'booking details found', 'success', 200); } else{ responseFormatter.formatServiceResponse({}, callback ,'No Booking Found.','error',404); } } }); } module.exports.startBooking=function(bookingID,callback){ const id = mongoose.Types.ObjectId(bookingID); bookingSchema.Booking.findOneAndUpdate({_id:id},{"current_status_info.status" : 'started',"current_status_info.datetime" : new Date().toISOString(),status : 'Confirmed'},{new:true},function(err,data){ if(err){ responseFormatter.formatServiceResponse(err, callback ,'Error Occurred','error',500); } else{ console.log("updated booking data------------",data); responseFormatter.formatServiceResponse(data, callback, 'booking status changed to started', 'success', 200); } }) } module.exports.onTheWay=function(bookingID,callback){ const id = mongoose.Types.ObjectId(bookingID); bookingSchema.Booking.findOneAndUpdate({_id:id},{"current_status_info.status" : 'on-the-way', "current_status_info.datetime" : new Date().toISOString() , status : 'Confirmed'},{new:true},function(err,data){ if(err){ responseFormatter.formatServiceResponse(err, callback ,'Error Occurred','error',500); } else{ console.log("updated booking data------------",data); responseFormatter.formatServiceResponse(data, callback, 'booking status changed to onTheWay', 'success', 200); } }) } module.exports.pauseBooking=function(bookingID,callback){ const id = mongoose.Types.ObjectId(bookingID); bookingSchema.Booking.findOneAndUpdate({_id:id},{"current_status_info.status" : 'paused', "current_status_info.datetime" : new Date().toISOString(), status : 'Confirmed'},{new:true},function(err,data){ if(err){ responseFormatter.formatServiceResponse(err, callback ,'Error Occurred','error',500); } else{ console.log("updated booking data------------",data); responseFormatter.formatServiceResponse(data, callback, 'booking status changed to paused', 'success', 200); } }) } module.exports.resumeBooking=function(bookingID,callback){ const id = mongoose.Types.ObjectId(bookingID); bookingSchema.Booking.findOneAndUpdate({_id:id},{"current_status_info.status" : 'resumed', "current_status_info.datetime" : new Date().toISOString() ,status : 'Confirmed'},{new:true},function(err,data){ if(err){ responseFormatter.formatServiceResponse(err, callback ,'Error Occurred','error',500); } else{ console.log("updated booking data------------",data); responseFormatter.formatServiceResponse(data, callback, 'booking status changed to resumed', 'success', 200); } }) } module.exports.endBooking=function(bookingID,callback){ const id = mongoose.Types.ObjectId(bookingID); bookingSchema.Booking.findOneAndUpdate({_id:id},{"current_status_info.status" : 'ended', "current_status_info.datetime" : new Date().toISOString() ,status : 'Confirmed'},{new:true},function(err,data){ if(err){ responseFormatter.formatServiceResponse(err, callback ,'Error Occurred','error',500); } else{ console.log("updated booking data------------",data); responseFormatter.formatServiceResponse(data, callback, 'booking status changed to ended', 'success', 200); } }) } module.exports.rateSeekerForBooking=function(bookingID,payload,callback){ const id = mongoose.Types.ObjectId(bookingID); let current_status_object = { "status" : 'rated', "datetime" : new Date().toISOString(), "status_by": 'PROVIDER' } ; let dataToUpdate = { "seeker_rating" : payload, "status" : 'Closed' } bookingSchema.Booking.findOneAndUpdate({_id:id},{$push: {current_status_info: current_status_object}, $set: dataToUpdate},{new:true},function(err,data){ if(err){ responseFormatter.formatServiceResponse(err, callback ,'Error Occurred','error',500); } else{ console.log("updated booking data------------",data); responseFormatter.formatServiceResponse(data, callback, 'Thank you for rating us', 'success', 200); } }) } module.exports.rateSPForBooking=function(bookingID,payload,callback){ const id = mongoose.Types.ObjectId(bookingID); let current_status_object = { "status" : 'rated', "datetime" : new Date().toISOString(), "status_by": 'SEEKER' } ; let dataToUpdate = { "SP_rating" : payload, "status" : 'Closed' } bookingSchema.Booking.findOneAndUpdate({_id:id},{$push: {current_status_info: current_status_object}, $set: dataToUpdate},{new:true},function(err,data){ if(err){ callback(err) } else{ console.log("updated booking data------------",data); SPProfileSchema.SPProfile.findOneAndUpdate({provider_id : data.provider_id},{$push: {ratings: payload.rating}},{lean:true,new:true},function(err,SPRatingData){ console.log('SP rating successfully pushed to SP profile err : ',err, " SPRatingData : ",SPRatingData); if(err){ callback(err) //responseFormatter.formatServiceResponse(err, callback ,'Error Occurred','error',500); }else{ if(SPRatingData == null || !SPRatingData){ console.log('in rateSPForBooking model error ::: No Provider Found. Please check Server.') callback(null,data); }else{ let numberOfBooking; let averageRating if(SPRatingData.average_rating && SPRatingData.number_of_bookings ){ numberOfBooking = Number(SPRatingData.number_of_bookings)+1; averageRating = (Number(SPRatingData.average_rating) + Number(payload.rating))/numberOfBooking } else{ numberOfBooking =1 averageRating=Number(payload.rating) //because only one value present } SPProfileSchema.SPProfile.findOneAndUpdate({provider_id:data.provider_id},{average_rating:averageRating,number_of_bookings:numberOfBooking, $push :{reviews :payload.feedback}},{lean:true,new:true},function(err,ratingUpdated){ if(err){ callback(err) } else{ console.log("in function rating ratingUpdated",ratingUpdated) callback(null,data) } }) } } }) } }) } module.exports.bulkUpdateModel=function(payload,callback){ gigsSchema.Gigs.update({}, { $set: { booking_location:payload.booking_location } },{ multi: true },function(err,data){ if(err){ callback(err) } else{ console.log("updated booking data------------",data); callback(null,data) gigsSchema.Gigs.updateMany({"repetitions.today": {$gt: 0}}, { $set: { "repetitions.today": 0, } }, function(err, activity){ if (err) throw err; }); } }) } module.exports.bookingConfirmedProduct=function(payload,callback){ let productData=null let updatedData=null async.series([ function(cb){ let dataToUpdate={}; if(payload.booking_datetime){ dataToUpdate.booking_datetime=payload.booking_datetime } /* if(payload.booked_price_value){ dataToUpdate.booked_price_value=payload.booked_price_value } if(payload.booked_price_type){ dataToUpdate.booked_price_type=payload.booked_price_type }*/ if(payload.net_amount){ dataToUpdate.net_amount=payload.net_amount } console.log("in confirm booking seeker dataToUpdate",dataToUpdate); const id = mongoose.Types.ObjectId(payload.bookingID); bookingSchema.Booking.findOneAndUpdate({_id:id},dataToUpdate,{lean:true,new:true},function(err,data){ if(err){ cb(err) } else{ console.log("updated booking data------------",data); updatedData=data cb(null) } }); }, function(cb){ const deviceDetails=[] if(payload.isProduct==true){ let saveData={ booking_id:payload.booking_id, product:payload.product, seeker_id:payload.seeker_id } const n = new Date().toISOString() const seekerProduct=new seekerProductSchema.SeekerProduct(saveData) seekerProduct.save(function(err,seekerproductData){ if(err){ cb(err) } else{ console.log("seekerproductData",seekerproductData) productData=seekerproductData //push to SP for Confirmation of Product const pushData={ booking_id:payload.booking_id, seeker_id:payload.seeker_id, seeker_image:updatedData.seeker_image, booking_address:updatedData.booking_address, product:payload.product, booking_datetime:n } deviceDetails.push({ device_token :updatedData.provider_device_token, device_type :updatedData.provider_device_token, }); const formattedDate=moment(n).format('MMMM DD YYYY') const pushDetailsSP={ deviceDetails: deviceDetails, text: "Congratulations! Your request dated on "+formattedDate +" has been accepted By"+" "+payload.provider_name, payload: pushData } push.sendPush(pushDetailsSP,"PROVIDER"); cb(null , data); } }) } else{ cb(null) } } ],function(err,data){ if(err){ callback(err) } else{ data=productData callback(null,data) } }) } module.exports.getSeekerBookingsByPagination = function(query, path, callback){ let sort=null; if(query.filter.status=='Confirmed') { sort = {updatedAt:-1}; } else { sort = {booking_datetime:-1}; } //sort[query.sort_param] = -1; var filter = query.filter ? query.filter : {}; var fields = query.fields ? query.fields : ''; console.log("filter - : ",filter," fields - : ",fields); var url = path; console.log('query ::: ',query); var first = true; for(var key in query){ if(key != 'pageno' && key != 'fields' && key != 'filter'){ if(first){ url += '?' + key + '=' + query[key]; first = false; } else{ url += '&' + key + '=' + query[key]; } } } console.log('filter, query.pageno, query.resultsperpage, query.pagelist, url, fields, - - - - ',filter , query.pageno , query.resultsperpage , query.pagelist , url , fields,sort ); bookingSchema.Booking.paginate(filter, query.pageno, parseInt(query.resultsperpage), query.pagelist, url, fields,callback,sort); }; module.exports.bookingCronStatus=function(callback){ let bulk = SPProfileSchema.SPProfile.initializeOrderedBulkOp(); var counter = 0; SPProfileSchema.SPProfile.find({pre_on_the_way:false,is_accepted:true},{booking_datetime:1,pre_on_the_way:1}).forEach(function(data) { if (data&& data.booking_datetime) { let serverTime =Math.round(new Date().getTime()/1000.0) let localTime=moment(data.booking_datetime).unix() if(serverTime-localTime == 7.2e+6){ } var updoc = { "$set": {} }; updoc["$set"]["gig_specific_param.profile_cards"] = newCards; print("updoc %s",updoc); bulk.find({ "_id": data._id }).update(updoc); counter++; if (counter % 10 == 0) { bulk.execute(); bulk = db.gigs.initializeOrderedBulkOp(); } } }); if (counter % 10 != 0) bulk.execute(); } module.exports.getBookingDetailsForMonth = function(provider_id ,month,year, callback){ let endMonth = parseInt(month)+1; if(endMonth < 10){ endMonth = '0'+endMonth } if(endMonth == 13){ endMonth = '01'; year = Number(year)+1 } let startDateString = year+"-"+month+"-"+'01'+" 00:00:00.000Z"; let endDateString = year+"-"+endMonth+"-"+'01'+" 00:00:00.000Z"; console.log("startDateString ",startDateString); console.log("endDateString ",endDateString); let startLocalMoment = moment(startDateString).toISOString(); let endLocalMoment = moment(endDateString).toISOString(); console.log('start : ',startLocalMoment, " end : ",endLocalMoment); bookingSchema.Booking.find({provider_id : provider_id , booking_datetime : {$gte: startLocalMoment, $lte: endLocalMoment}},{},{lean:true}, function (err, booking) { console.log('Booking details returned----------------', booking); if (err){ logger.error("Find failed", err); responseFormatter.formatServiceResponse(err, callback ,'Error Occurred Please Try After Some Time','error',500); } else { if(booking) { //booking.date = new Date().toISOString(); responseFormatter.formatServiceResponse(booking, callback, 'booking details found', 'success', 200); } else{ responseFormatter.formatServiceResponse({}, callback ,'No Booking Found.','error',404); } } }).sort({booking_datetime: 1}); } module.exports.getAllBookedServicesByUserId = function(user_id,callback){ bookingSchema.Booking.find({$or:[ {'seeker_id': user_id},{'provider_id' :user_id} ]},{'booking_item_info.service_id' :1},{lean:true}, function (err, booking) { console.log('Booking details returned----------------', booking); if (err){ logger.error("Find failed", err); responseFormatter.formatServiceResponse(err, callback ,'Error Occurred Please Try After Some Time','error',500); } else { if(booking) { let serviceIdsArray = []; for(var i = 0 ; i< booking.length ; i++){ serviceIdsArray.push(booking[i].booking_item_info.service_id); } console.log('serviceIdsArray',serviceIdsArray); masterServiceSchema.MasterService.find({ service_id : { $in: serviceIdsArray } }, function (err, services) { console.log('Service returned', services); if (err){ logger.error("Find failed", err); responseFormatter.formatServiceResponse(err, callback); } else { console.log("services",services); responseFormatter.formatServiceResponse(services, callback, 'booking history details found', 'success', 200); } }); } else{ responseFormatter.formatServiceResponse({}, callback ,'No Booking history details Found.','error',404); } } }); } module.exports.getAllBookedGigsForSpecificServiceByUserId = function(service_id , user_id,callback){ bookingSchema.Booking.find({$or:[ {'seeker_id': user_id},{'provider_id' :user_id} ], 'booking_item_info.service_id' : service_id},{'booking_item_info.gig_id' :1},{lean:true}, function (err, booking) { console.log('Booking details returned----------------', booking); if (err){ logger.error("Find failed", err); responseFormatter.formatServiceResponse(err, callback ,'Error Occurred Please Try After Some Time','error',500); } else { if(booking) { var result = []; let gigIdsArray = []; for(var i = 0 ; i< booking.length ; i++){ gigIdsArray.push(booking[i].booking_item_info.gig_id); } console.log('gigIdsArray',gigIdsArray); gigsSchema.Gigs.find({ gig_id : { $in: gigIdsArray } }, function (err, gigsInfo) { console.log('Gigs returned', gigsInfo); for(var i = 0; i < gigsInfo.length ; i++){ result[i]={}; result[i]._id = gigsInfo[i]._id; result[i].service = gigsInfo[i].service_id; result[i].gig = gigsInfo[i]; result[i].service_name = gigsInfo[i].service_name; result[i].service_name = gigsInfo[i].service_name; result[i].gig_name = gigsInfo[i].gig_name; result[i].revenue_model = gigsInfo[i].revenue_model; result[i].pricing = gigsInfo[i].pricing; } if (err){ logger.error("Find failed", err); responseFormatter.formatServiceResponse(err, callback); } else { console.log("gigsInfo",gigsInfo); responseFormatter.formatServiceResponse(result, callback, 'booking history details found', 'success', 200); } }); } else{ responseFormatter.formatServiceResponse([], callback ,'No Booking history details Found.','error',404); } } }); }
const fangPageData = [ { author: "605242933784fd0bb0495709", artist: "TEST", pageTitle: 'Test 1', pageDetail: "if", userTracks: ['greg', 'coldplay'], userAlbums: ['greg', 'coldplay', 'raul'], userShows: ['greg', 'coldplay', 'raul'], upvote: [], }, { author: "605242933784fd0bb0495709", artist: "Arif", pageTitle: 'Test 2', pageDetail: "if", userTracks: ['greg', 'coldplay', 'raul'], userAlbums: ['greg', 'coldplay', 'raul'], userShows: ['greg', 'coldplay', 'raul'], upvote: ['605242933784fd0bb0495709'], }, { author: "605242933784fd0bb0495709", artist: "Drake", pageTitle: 'Test 3', pageDetail: "if", userTracks: ['greg', 'coldplay'], userAlbums: ['greg', 'coldplay', 'raul'], userShows: ['greg', 'coldplay', 'raul'], upvote: [], }, ] export default fangPageData;
var canvas; var context; var score = 0; var high = 0; var life = 3; var level = 0; //if game started var x = 325; var intervalId; var enemies = []; var my_laser = []; var ene_laser = []; var left = 1; var down = 0; var lost = 0; var maxLine = 8; var maxRow = 3; window.onload = function() { canvas = document.getElementById('canvas'); context = canvas.getContext('2d'); canvas.onkeydown = ev_canvas; start_screen(); }; function start_screen(){ context.font = "40px Georgia"; context.fillStyle = "white"; context.fillText("Use a/d to move, space to shoot", 50, 270); context.fillText("Press Space to Start", 170, 330); context.fillText("Press Enter to Quit", 170, 390); } function generate_enemy(){ context.fillStyle = "white"; for(var j = 0; j <= maxRow; j++){ for(var i = 0; i <= maxLine; i++){ var ene = new enemy(i, j, 80 + i * 60, 100 + j * 40); enemies.push(ene); } } } function enemy(id,row,x,y){ this.id = id; this.row = row; this.x = x; this.y = y; } function laser(x,y){ this.x = x; this.y = y; } function find_left(){ var le = enemies[0].id; var index = 0; for(var i = 1; i < enemies.length; i++){ if(enemies[i].id < le){ le = enemies[i].id; index = i; } } return index; } function find_right(){ var ri = enemies[0].id; var index = 0; for(var i = 1; i < enemies.length; i++){ if(enemies[i].id > ri){ ri = enemies[i].id; index = i; } } return index; } function ev_canvas(e){ if(e.keyCode == 32){ //Space if(level == 0){ clear_canvas(); score = 0; life = 3; level = 1; lost = 0; down = 0; left = 1; new_level(); intervalId = setInterval("game()", 500); } else { var la = new laser(x + 12, 530); my_laser.push(la); } } if(e.keyCode == 13){ //Enter score_screen(); } if(e.keyCode == 65){ //A if(level != 0 && x > 0){ clear_canvas(); x = x - 5; game_screen(x); } } if(e.keyCode == 68){ //D if(level != 0 && x < 650){ clear_canvas(); x = x + 5; game_screen(x); } } } function clear_canvas(){ context.clearRect(0, 0, canvas.width, canvas.height); } function new_level(){ enemies = []; my_laser = []; ene_laser = []; generate_enemy(); x = 325 game_screen(x); } function score_screen(){ clear_canvas(); level = 0; if(score > high){ high = score; } clearInterval(intervalId); context.font = "40px Georgia"; context.fillStyle = "white"; context.fillText("Game Over", 170, 170); context.fillText("Final Score: " + score, 170, 330); context.fillText("High Score: " + high, 170, 390); context.fillText("Press Space to Start", 170, 450); } function game_screen(x){ context.font = "20px Georgia"; context.fillStyle = "white"; context.fillText("Level: " + level, 0, 17); context.fillText("Score: " + score, 170, 17); context.fillText("High Score: " + high, 370, 17); context.fillText("Life: " + life, 0, 596); context.fillRect(0, 530, 700, 5); context.fillRect(x, 550, 50, 30); for(var i = 0; i < enemies.length; i++){ var ene = enemies[i]; context.fillRect(ene.x, ene.y, 50, 30); } for(var i = 0; i < my_laser.length; i++){ var la = my_laser[i]; context.fillStyle = "blue"; context.fillRect(la.x, la.y, 10, 10); } } function game(){ clear_canvas(); for(var i = 0; i < my_laser.length; i++){ my_laser[i].y -= 10; } if(enemies[find_right()].x == 650){ left = -1; down = 1 } if(enemies[find_left()].x == 0){ left = 1; down = 1; } for(var i = 0; i < enemies.length; i++){ enemies[i].x += 10 * left; enemies[i].y += 10 * down; if(enemies[i].y + 30 == 530){ lost = 1; break; } } if(lost == 1){ score_screen(); } else{ down = 0; game_screen(x); } }
module.exports = { validate: { params: { campaignObjective: 'REACH', adFormat: 'video', callToAction: 'GET_OFFER', }, response: false, }, map: { params: { campaignObjective: 'REACH', adFormat: 'video', }, response: ["APPLY_NOW", "BOOK_TRAVEL", "CALL_NOW", "CONTACT_US", "DOWNLOAD", "GET_DIRECTIONS", "LEARN_MORE", "GET_SHOWTIMES", "SEND_MESSAGE", "REQUEST_TIME", "SAVE", "SEE_MENU", "SHOP_NOW", "SIGN_UP", "WATCH_MORE", "LISTEN_NOW", "GET_OFFER"] } }
"use strict"; import { db, outlayObjectStoreName, outlayCategoryObjectStoreName, getCategoryChilds, } from "./db.js"; import { ObjectStore } from "./objectStore.js"; import { userLang, localeString } from "./locale.js"; // https://habr.com/ru/company/mailru/blog/269465/ export class Category { static async getAncestors(categoryId, transaction) { /*if (!transaction) transaction = db.transaction(outlayCategoryObjectStoreName, "readwrite");*/ if (!transaction) transaction = db.transaction(outlayCategoryObjectStoreName); let ancestors = []; while (categoryId) { ancestors.push(categoryId); let category = await Category.get(categoryId, transaction); categoryId = category.parentId; } return ancestors; } static async setExpanded(categoryId, expanded, transaction) { if (!categoryId) return; if (!transaction) transaction = db.transaction(outlayCategoryObjectStoreName, "readwrite"); let category = await Category.get(categoryId, transaction); category.expanded = expanded; await Category.set(category, transaction); } static async getDescendants(category, transaction) { let categoryDescendants = []; let categoryChildren = await Category.getChildren(category.id, transaction); categoryDescendants = categoryDescendants.concat(categoryChildren); for (let categoryChild of categoryChildren) { categoryDescendants = categoryDescendants.concat( await Category.getDescendants(categoryChild, transaction) ); } return categoryDescendants; } static async getChildren(categoryId, transaction) { try { if (!transaction) transaction = db.transaction(outlayCategoryObjectStoreName); return getCategoryChilds(categoryId, transaction); } catch (error) { console.log("error", error); return error; } } static async set(category, transaction) { try { if (!transaction) transaction = db.transaction( outlayCategoryObjectStoreName, "readwrite" ); if ( 0 !== category.parentId && !(await Category.get(category.parentId, transaction)) ) { throw new Error( "НЕ найдена родительская категория (" + category.parentId + ') категории "' + category.name + '"' ); } return await ObjectStore.set( outlayCategoryObjectStoreName, category, transaction ); } catch (error) { transaction._abortIfActive(); throw new Error(error.message); } } static async getAll(transaction) { try { if (!transaction) transaction = db.transaction(outlayCategoryObjectStoreName); const category = await new Promise(function (resolve, reject) { let request = transaction .objectStore(outlayCategoryObjectStoreName) .getAll(); request.onsuccess = function () { resolve(request.result); }; request.onerror = function () { reject(request.error); }; }); return category; } catch (error) { return error; } } static async get(categoryId, transaction) { return await ObjectStore.get( outlayCategoryObjectStoreName, categoryId, transaction ); } static async getNextSibling(category, transaction) { try { const categoryNextSibling = await new Promise(function (resolve, reject) { let request = transaction .objectStore(outlayCategoryObjectStoreName) .index("parentCategoryId_idx") .get( IDBKeyRange.bound( [category.parentId, category.name], [category.parentId + 1], true, true ) ); request.onsuccess = function () { resolve(request.result); }; request.onerror = function () { reject(request.error); }; }); return categoryNextSibling; } catch (error) { transaction._abortIfActive(); throw new Error(error); } } static async getPreviousSibling(category, transaction) { try { const categoryPreviousSibling = await new Promise(function ( resolve, reject ) { let request = transaction .objectStore(outlayCategoryObjectStoreName) .index("parentCategoryId_idx") .getAll( IDBKeyRange.bound( [category.parentId], [category.parentId, category.name], false, true ) ); request.onsuccess = function () { resolve( 0 < request.result.length ? request.result[request.result.length - 1] : null ); }; request.onerror = function () { reject(request.error); }; }); return categoryPreviousSibling; } catch (error) { transaction._abortIfActive(); throw new Error(error); } } static async getIsUsedReason(categoryId, transaction) { try { const reason = await new Promise(function (resolve, reject) { let request = transaction .objectStore(outlayObjectStoreName) .index("categoryId_idx") .get(categoryId); request.onsuccess = function () { if (request.result) { resolve( localeString.categoryIsUsedReason + " (" + request.result.sumAll.toFixed(2) + " " + localeString.forDate + " " + request.result.date.toLocaleString(userLang, { year: "numeric", month: "long", day: "numeric", }) + ")" ); } else resolve(null); }; request.onerror = function () { reject(request.error); }; }); return reason; } catch (error) { transaction._abortIfActive(); throw new Error(error); } } }
var ChemIndexShow = React.createClass({ getInitialState: function(){ return{ retrieving: false, } }, render: function() { var chem = this.props.chem var local = ChemStore.isLocal(chem['name']); var buttonText, buttonClass, divClass; if (local){ divClass = 'menu-el-loaded menu-el'; buttonClass = 'btn-x'; buttonText = '\u00D7'; }else{ divClass = 'menu-el'; buttonText = this.state.retrieving?'Retrieving':'Load'; } return( <li className={divClass}> {chem.smiles}<br/> <button className={buttonClass} onClick={this.chemAction}>{buttonText}</button> </li> ) }, chemAction: function(e){ e.preventDefault(); if(ChemStore.isLocal(this.props.chem['name'])){ Actions.removeLocal(this.props.chem); this.setState({ retrieving: false }); }else{ ApiActions.findChem('name', this.props.chem.smiles); this.setState({ retrieving: true }); } } });
(function() { // 这些变量和函数的说明,请参考 rdk/app/example/web/scripts/main.js 的注释 var imports = [ 'rd.controls.ChartIcon' ]; var extraModules = [ ]; var controllerDefination = ['$scope', main]; function main(scope) { scope.barData=[2,3,4,5,6]; scope.pieData="35%"; setInterval(function() { var random = Math.round(Math.random() * 10); scope.barData.shift(); scope.barData.push(random); scope.pieData=Math.round(Math.random() * 100)+"%"; scope.$apply(); }, 1000); } rdk.$ngModule.config(['ChartIconConfigProvider',function(ChartIconConfigProvider){ var defaultOption={ pie:{delimiter: null, fill: ["#000", "#fff"], height: null, radius: 28, width: null}, donut:{delimiter: null, fill: ["#ff9900", "#fff4dd", "#ffd592"], height: 56, innerRadius: null, radius: 28, width: null}, line:{delimiter: ",", fill: "#c6d9fd", height: 56, max: null, min: 0, stroke: "#4d89f9", strokeWidth: 1, width: 84}, bar: {delimiter: ",", fill: ["#9d89f9"], height: 56, max: null, min: 0, padding: 0.1, width: 84} }; ChartIconConfigProvider.setOptions(defaultOption); }]); 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); } })();
import React, { Component } from "react"; import { connect } from "react-redux"; import { Link } from "react-router-dom"; import axios from "axios"; import moment from "moment"; import querystring from "query-string"; import { createReview, updateReview, deleteReview } from "ducks/StrengthAssessmentReviews"; import { STRENGTH, startReview, stopReview } from "ducks/DevelopmentReviewInProgress"; import LandingPage from "./LandingPage"; import Question from "./Question"; import CommentsPage from "./CommentsPage"; import EmbeddedDevPlan from "./EmbeddedDevPlan"; import ProgressCheck from "../../../../containers/ProgressCheck"; import "./style.css"; import Api from "../../../../../../../../Api"; class StrengthAssessmentReview extends Component { constructor(props) { super(props); this.begin = this.begin.bind(this); this.reviewClicked = this.reviewClicked.bind(this); this.devPlanClicked = this.devPlanClicked.bind(this); this.commentsClicked = this.commentsClicked.bind(this); this.previousQuestion = this.previousQuestion.bind(this); this.nextQuestion = this.nextQuestion.bind(this); this.complete = this.complete.bind(this); this.reviewerCommentsChanged = this.reviewerCommentsChanged.bind(this); this.employeeCommentsChanged = this.employeeCommentsChanged.bind(this); this.reviewCreated = this.reviewCreated.bind(this); this.managerUsernameChanged = this.managerUsernameChanged.bind(this); this.managerPasswordChanged = this.managerPasswordChanged.bind(this); this.managerLogin = this.managerLogin.bind(this); this.buildReview = this.buildReview.bind(this); this.reviewCompleted = this.reviewCompleted.bind(this); this.updateReview = this.updateReview.bind(this); this.handleCompletionError = this.handleCompletionError.bind(this); this.resume = this.resume.bind(this); this.discard = this.discard.bind(this); this.initialState = this.initialState.bind(this); this.state = this.initialState(); this.state.progressCheck = props.progressCheck; if (props.review) { this.state.reviewId = props.review.id; this.state.reviewerComments = props.review.reviewers_comments; this.state.employeeComments = props.review.employee_comments; this.state.completed = props.review.completed; if (props.reviewInProgress && props.reviewInProgress.reviewInProgress) { this.state.managerToken = props.reviewInProgress.managerToken; this.state.landingPage = props.reviewInProgress.other.landingPage; this.state.questionPage = props.reviewInProgress.other.questionPage; this.state.commentsPage = props.reviewInProgress.other.commentsPage; this.state.developmentPlan = props.reviewInProgress.other.developmentPlan; this.state.thankYouPage = props.reviewInProgress.other.thankYouPage; this.state.currentQuestion = props.reviewInProgress.other.currentQuestion; this.state.manager = props.people.find( ({ id }) => id === props.reviewInProgress.managerId ); this.state.managerJobDescription = props.jobDescriptions.find( ({ id }) => id === this.state.manager.job_description ); } } } buildReview() { return { id: this.state.reviewId, assessment_request: this.props.assessmentRequest.id, assessed_by_person: this.state.manager.id || 0, reviewers_comments: this.state.reviewerComments, employee_comments: this.state.employeeComments, manager_token: this.state.managerToken }; } begin() { let review = this.buildReview(); this.props.createReview(this.props.token, review, this.reviewCreated); } reviewClicked() { this.setState({ questionPage: true, developmentPlan: false, commentsPage: false }); } devPlanClicked() { this.setState({ questionPage: false, developmentPlan: true, commentsPage: false }); } commentsClicked() { this.setState({ questionPage: false, developmentPlan: false, commentsPage: true }); } previousQuestion() { if (this.state.currentQuestion !== 0) this.setState({ currentQuestion: this.state.currentQuestion - 1 }); } nextQuestion() { if (this.state.currentQuestion !== this.state.questions.length - 1) this.setState({ currentQuestion: this.state.currentQuestion + 1 }); } reviewerCommentsChanged(newComments) { this.setState({ reviewerComments: newComments }); } employeeCommentsChanged(newComments) { this.setState({ employeeComments: newComments }); } componentWillUnmount() { if (this.state.reviewId && !this.state.progressCheck){ this.updateReview(); } } updateReview() { let review = this.buildReview(); this.props.updateReview(this.props.token, review, null); } complete() { let review = this.buildReview(); review.completed = true; this.props.updateReview(this.props.token, review, response => { if (response.status >= 400) this.handleCompletionError(response); else this.reviewCompleted(response.data); }); } reviewCreated(review) { this.setState({ landingPage: false, questionPage: true, commentsPage: false, developmentPlan: false, thankYouPage: false, reviewId: review.id }); this.props.startReview({ reviewType: STRENGTH, reviewId: review.id, managerId: this.state.manager.id, managerToken: this.state.managerToken, other: { requestId: this.props.assessmentRequest.id, landingPage: false, questionPage: true, commentsPage: false, developmentPlan: false, thankYouPage: false, currentQuestion: 0 } }); } handleCompletionError(response) { if (!response.data) return; let data = response.data; let newState = { landingPage: false, questionPage: false, commentsPage: true, developmentPlan: false, thankYouPage: false }; if (data.employee_comments && data.employee_comments.length) newState.employee_comments_errors = data.employee_comments; else newState.employee_comments_errors = []; if (data.reviewers_comments && data.reviewers_comments.length) newState.reviewers_comments_errors = data.reviewers_comments; else newState.reviewers_comments_errors = []; this.setState(newState); } reviewCompleted(review) { this.setState({ landingPage: false, questionPage: false, commentsPage: false, developmentPlan: false, thankYouPage: true }); this.props.stopReviewInProgress(); } managerUsernameChanged(e) { this.setState({ managerUsername: e.target.value }); } managerPasswordChanged(e) { this.setState({ managerPassword: e.target.value }); } managerLogin() { let credentials = { username: this.state.managerUsername, password: this.state.managerPassword }; axios .create({ baseURL: "/api/v1/", headers: { Authorization: "Token " + this.props.token } }) .post("manager-login/", credentials) .then(({ data }) => { let manager = this.props.people.find( ({ user }) => user.username === this.state.managerUsername ); if (manager) { let jobDescription = this.props.jobDescriptions.find( ({ id }) => id === manager.job_description ); this.setState({ manager, managerJobDescription: jobDescription, managerToken: data.token }); } }) .catch(error => { this.setState({ managerLoginError: error.response.data.detail }); }); } resume() { this.setState({ landingPage: false, questionPage: true, commentsPage: false, developmentPlan: false, thankYouPage: false, progressCheck: false }); } initialState() { let state = { managerLoginError: "", managerToken: "", manager: null, managerJobDescription: null, managerUsername: "", managerPassword: "", landingPage: true, questionPage: false, commentsPage: false, developmentPlan: false, thankYouPage: false, progressCheck: false, currentQuestion: 0, questions: [], reviewId: 0, reviewerComments: "", employeeComments: "", completed: false, employee_comments_errors: [], reviewers_comments_errors: [] }; state.questions = this.props.allValues.map(v => ({ value: v.id, statement: v.statement })); state.questions = state.questions.concat([ { development: "SKILL", statement: `I produce quality work that is valued by customers, peers, supervisors, and ${ this.props.company ? this.props.company.name : "" }` }, { development: "KNOWLEDGE", statement: `I value staying current and understand that it is part of my future success at ${ this.props.company ? this.props.company.name : "" }` }, { development: "PASSION", statement: "PASSION STATEMENT" }, { development: "WISDOM", statement: "WISDOM STATEMENT" } ]); return state; } discard() { //Delete the review on the server this.props.deleteReview( this.props.token, { id: this.state.reviewId, manager_token: this.state.managerToken }, () => { //Revert the state of this component to the initial defaults this.setState(this.initialState()); } ); } render() { return ( <div className="strength-assessment-review"> {this.state.progressCheck && ( <ProgressCheck {...this.props} {...this.state} resume={this.resume} discard={this.discard} /> )} {!this.state.progressCheck && ( <div> {this.state.landingPage && ( <LandingPage {...this.props} {...this.state} begin={this.begin} managerUsernameChanged={this.managerUsernameChanged} managerPasswordChanged={this.managerPasswordChanged} managerLogin={this.managerLogin} /> )} {this.state.questionPage && ( <Question {...this.props} {...this.state} reviewClicked={this.reviewClicked} devPlanClicked={this.devPlanClicked} commentsClicked={this.commentsClicked} previous={this.previousQuestion} next={this.nextQuestion} /> )} {this.state.developmentPlan && ( <EmbeddedDevPlan {...this.props} {...this.state} reviewClicked={this.reviewClicked} devPlanClicked={this.devPlanClicked} commentsClicked={this.commentsClicked} reviewId={this.state.reviewId} /> )} {this.state.commentsPage && ( <CommentsPage {...this.props} {...this.state} reviewerCommentsChanged={this.reviewerCommentsChanged} employeeCommentsChanged={this.employeeCommentsChanged} backClicked={this.reviewClicked} reviewClicked={this.reviewClicked} devPlanClicked={this.devPlanClicked} completeClicked={this.complete} updateReview={this.updateReview} /> )} {this.state.thankYouPage && ( <div className="thank-you"> <h3>Thank you, your Review has been completed.</h3> <div> Click <Link to="/">here</Link> to return the the dashboard. </div> </div> )} </div> )} </div> ); } } const mapStateToProps = (state, ownProps) => { let props = { assessmentRequest: null, personAssessed: null, company: null, jobDescription: null, companyDepartment: null, reviewer: null, reviewerJobDescription: null, allRequests: [], allAssessments: [], allAssessmentValues: [], allValues: [], token: "", people: [], jobDescriptions: [], progressCheck: false, review: null, reviewInProgress: null }; const parsedQueryString = querystring.parse(ownProps.location.search); if (parsedQueryString.reviewId) { let review = state.strengthAssessmentReviews.items.find( ({ id }) => id === parseInt(parsedQueryString.reviewId, 10) ); if (review) { props.review = review; props.progressCheck = true; } } if ( parsedQueryString.progresscheck && parsedQueryString.progresscheck === "false" ) { props.progressCheck = false; } if (state.reviewInProgress.reviewInProgress) props.reviewInProgress = state.reviewInProgress; props.people = state.people.items; props.jobDescriptions = state.jobDescriptions.items; let me = state.me; if (!me) return props; props.reviewer = me; let reviewerJobDescription = state.jobDescriptions.items.find( ({ id }) => id === me.job_description ); if (!reviewerJobDescription) return props; props.reviewerJobDescription = reviewerJobDescription; let request = state.strengthAssessmentRequests.items.find( ({ id }) => id === parseInt(ownProps.match.params.assessmentRequestId, 10) ); if (!request) return props; props.assessmentRequest = request; let personAssessed = state.people.items.find( ({ id }) => id === request.person_assessed ); if (!personAssessed) return props; props.personAssessed = personAssessed; let company = state.companies.items.find( ({ id }) => id === personAssessed.company ); if (!company) return props; props.company = company; let jobDescription = state.jobDescriptions.items.find( ({ id }) => id === personAssessed.job_description ); if (!jobDescription) return props; props.jobDescription = jobDescription; let companyDepartment = state.companyDepartments.items.find( ({ id }) => id === jobDescription.company_department ); if (!companyDepartment) return props; props.companyDepartment = companyDepartment; props.allRequests = state.strengthAssessmentRequests.items .filter( ar => ar.person_assessed === personAssessed.id && moment(ar.request_date).isSameOrBefore(request.request_date) ) .sort((a, b) => moment(b.request_date).diff(a.request_date)); let requestIds = props.allRequests.map(ar => ar.id); props.allAssessments = state.strengthAssessments.items.filter(sa => requestIds.includes(sa.assessment_request) ); let assessmentIds = props.allAssessments.map(sa => sa.id); props.allAssessmentValues = state.strengthAssessmentValues.items.filter(av => assessmentIds.includes(av.strength_assessment) ); props.allValues = state.values.items.filter( v => v.company === personAssessed.company ); props.token = state.apiToken.value; return props; }; const mapDispatchToProps = dispatch => ({ createReview: (token, review, callback) => { dispatch(createReview(token, review, callback)); }, updateReview: (token, review, callback) => { dispatch(updateReview(token, review, callback)); }, deleteReview: (token, review, callback) => { dispatch(deleteReview(token, review, callback)); }, startReview: reviewInfo => { dispatch(startReview(reviewInfo)); }, stopReviewInProgress: () => { dispatch(stopReview()); } }); export default connect(mapStateToProps, mapDispatchToProps)( StrengthAssessmentReview );
var request = require("hyperquest"); process.stdin.pipe(request.post("http://localhost:8099")).pipe(process.stdout)
export default { name: '标题', tag: 'h1', icon: 'icon-integral' }
function runTest() { FBTest.openNewTab(basePath + "console/5033/issue5033.html", function(win) { FBTest.openFirebug(function() { FBTest.enablePanels(["script", "console"], function() { FBTest.waitForBreakInDebugger(null, 10, true, function() { FBTest.waitForDebuggerResume(function () { var panelNode = FBTest.selectPanel("console").panelNode; var config = { tagName: "div", classes: "logRow", onlyMutations: true }; FBTest.waitForDisplayedElement("console", config, function(row) { var result = panelNode.querySelector(".logRow:not(.logRow-command)"); if (FBTest.ok(result, "Result must exist")) FBTest.compare(20, result.textContent, "Result must be correct"); FBTest.testDone(); }); }); // Click step over five times to resume the debugger. FBTest.waitForBreakInDebugger(null, 11, false, function() { FBTest.waitForBreakInDebugger(null, 12, false, function() { FBTest.waitForBreakInDebugger(null, 12, false, function() { FBTest.clickStepOverButton(); }); FBTest.clickStepOverButton(); }); FBTest.clickStepOverButton(); }); FBTest.clickStepOverButton(); }); var url = basePath + "console/5033/issue5033.html"; FBTest.setBreakpoint(null, url, 10, null, function() { FBTest.progress("breakpoint set"); FBTest.selectPanel("console"); FBTest.executeCommand("testFunction()"); }); }); }); }); }
import angular from 'angular'; import 'bootstrap/dist/css/bootstrap.css'; import angularMeteor from 'angular-meteor'; import template from './mainComponent.html'; class MainComponentCtrl { constructor($scope) { $scope.viewModel(this); this.helpers({ }); } } export default angular.module('mainComponent', [ angularMeteor ]).component('mainComponent', { templateUrl: 'imports/components/mainComponent/mainComponent.html', controller: ['$scope', MainComponentCtrl] });
"use strict"; /* You need the module.exports when testing in node. Comment it out when you send your file to the browser */ module.exports = {myOwnMap,myOwnFilter, myOwnReduce}; //add all of your function names here that you need for the node mocha tests /** * array.Map() * @param {array} arr a array * @param {function} fun a function * @returns {array} is the colection of returns of the fun(eachElemof array) */ function myOwnMap(arr, fun) { let returnArr = []; for (let item of arr) { returnArr.push(fun(item)); } return returnArr; } /** * array.filter(); * @param {array} arr is an array * @param {function} fun is a function * @returns {array} is the filtered array */ function myOwnFilter(arr, fun) { let returnArr = []; for (let item of arr) { if (fun(item)) { returnArr.push(item); } } return returnArr; } /** * array.reduce(); * @param {array} arr is a array * @param {function} fun is a function * @returns {vary} one single value */ function myOwnReduce(arr, fun) { let result = null; for (let item of arr) { result = fun(prev, item); } return result; }
const server = require('./src/app'); server.listen(3001, () => { console.log('Back corriendo en puerto 3001'); // eslint-disable-line no-console });
import React from 'react' import PropTypes from 'prop-types' import styled from 'styled-components' import {connect} from 'react-redux' import { BaseButtonBlue, } from '../components/TopLevelComponents.styled' import { Input, } from '../components/AddressInputComponents.styled' import {actions} from './View.ducks' import Modal from '../components/Modal' const DisplayContainer = styled.div` height: 80px; display: flex; flex-direction: column; justify-content: center; ` const InputPrompt = styled.div` flex: 1 0; display: flex; align-items: flex-end; ${'' /* justify-content: center; */} ` const InputContainer = styled.div` width: 100%; display: flex; justify-content: space-between; align-items: center; font-size: 1.3em; ` const ModifiedInput = Input.extend` border-radius: 5px; font-size: 1.7em; max-width: 80%; flex: 1 1; margin-right: 5px; ` const DepositButton = BaseButtonBlue.extend` padding: 10px; ` class DepositModal extends React.Component { static propTypes = { modalIsOpen: PropTypes.bool.isRequired, closeModal: PropTypes.func.isRequired, depositAmount: PropTypes.number, tipAmount: PropTypes.number, updateDepositAmount: PropTypes.func.isRequired, updateTipAmount: PropTypes.func.isRequired, deposit: PropTypes.func.isRequired, } static defaultProps = { tipAmount: 0.0, depositAmount: 0.0, } render() { const { modalIsOpen, closeModal, depositAmount, tipAmount, updateDepositAmount, updateTipAmount, deposit, } = this.props return ( <Modal isOpen={modalIsOpen} onRequestClose={closeModal} > <h2>Deposit</h2> <DisplayContainer> <InputPrompt> Tip the Devs? </InputPrompt> <InputContainer> <ModifiedInput type="number" onChange={e => updateTipAmount(parseFloat(e.target.value))} placeholder={tipAmount} isvalid /> ETH </InputContainer> </DisplayContainer> <br /> <br /> <DisplayContainer> <InputPrompt> How much to deposit? </InputPrompt> <InputContainer> <ModifiedInput type="number" onChange={e => updateDepositAmount(parseFloat(e.target.value))} placeholder={depositAmount} isvalid /> ETH </InputContainer> </DisplayContainer> <br /> <DisplayContainer> Tip Amount: {tipAmount} ETH </DisplayContainer> <DisplayContainer> Deposit Amount: {depositAmount} ETH </DisplayContainer> <DisplayContainer> Total: { parseFloat(depositAmount) + parseFloat(tipAmount) } ETH </DisplayContainer> <DepositButton onClick={deposit} > Initiatate Deposit </DepositButton> </Modal> ) } } const mapStateToProps = state => ({ modalIsOpen: state.view.depositModalIsOpen, targetAddress: state.view.targetAddress, depositAmount: state.view.depositAmount, tipAmount: state.view.tipAmount, }) const mapDispatchToProps = dispatch => ({ closeModal: () => dispatch(actions.closeDepositModal()), updateDepositAmount: (amount) => dispatch(actions.updateDepositAmount(amount)), updateTipAmount: (amount) => dispatch(actions.updateTipAmount(amount)), deposit: () => dispatch(actions.deposit()) }) export default connect(mapStateToProps, mapDispatchToProps)(DepositModal)
//there are alot of improvement but yeah this still awesome for me ;) //time complexity Ω(n log(n)) Θ(n log(n)) O(n log(n)) space O(1) //time complex could also argue to be Θ(n) function buildHeap(A){ var heap = [] for(var i = 1; i <= A.length; i++){ var leaf = [A[i-1], i] heap.push(leaf) } return heap } // buildMaxHeap takes c (time cost of maxHeapify) // of n (math.round A.length / 2) function buildMaxHeap(A){ n = Math.round(A.length / 2) for(var i = n; i >= 1; i--){ maxHeapify(A, i); } } // maxHeapify is from bot to top function maxHeapify(A, i = 1){ // l = left(i) // r = right(i) (A[2*i] > A[(2*i) + 1]) ? ind = 2*i : ind = (2*i) + 1; (A[ind] > A[i]) ? swap(A[ind], A[i]) : null; } // maxHeapify2 is from top to bot function maxHeapify2(A, i = 1){ if(i > Math.round(A.length / 2)){ return } (A[2*i] > A[(2*i) + 1]) ? ind = 2*i : ind = (2*i) + 1; if (A[ind] > A[i]){ swap(A[ind], A[i]) maxHeapify2(A, ind) } else { return } } function insert(A, val){ var leaf = [val, A.length + 1] A.push(leaf) buildMaxHeap(A) } function extractMax(A){ swap(A[1][0], A[A.length][0]) var output = A.pop() maxHeapify2(A) return output }
'use strict' const sdk = require('../../src/sdk.js') const mockApi = require('../mock/api.js') require('should') describe('Zabo SDK Accounts Resource', () => { let accounts it('should not be instantiated during zabo.init() running outside a browser', async function () { await sdk.init({ apiKey: 'some-api-key', secretKey: 'some-secret-key', env: 'sandbox', autoConnect: false }).catch(err => err).should.be.ok() sdk.api.should.be.ok() sdk.api.connect.should.be.a.Function() sdk.api.resources.should.not.have.property('accounts') accounts = await require('../../src/resources/accounts')(mockApi) accounts.should.have.property('get') accounts.should.have.property('create') accounts.should.have.property('getBalances') }) it('accounts.getBalances() should fail if an account has not connected yet', async function () { const response = await accounts.getBalances({ tickers: 'BTC' }).should.be.rejected() response.should.be.an.Error() response.error_type.should.be.equal(401) response.message.should.containEql('connected') }) it('accounts.get() should return an account and cache account data', async function () { const account = await accounts.get() account.should.be.ok() account.should.have.properties(['id', 'provider', 'balances']) accounts.data.should.be.eql(account) accounts.id.should.be.equal(account.id) }) it('accounts.create() should create and return a new account', async function () { const data = { clientId: 'some-client-id', credentials: ['some-credentials'], provider: 'some-provider', origin: 'some-origin' } const account = await accounts.create(data) account.should.be.ok() account.should.have.properties(['id', 'provider', 'balances']) account.provider.name.should.have.equal(data.provider) }) it('accounts.getBalances() should return balances for the required tickers', async function () { const tickers = ['BTC', 'ETH'] const balances = await accounts.getBalances({ tickers }) balances.data.should.be.ok() balances.data.should.be.an.Array() const currencyTickers = balances.data.map(b => b.ticker) currencyTickers.should.containDeep(tickers) }) it('accounts.createDepositAddress() should create and return an address', async function () { const resp = await accounts.createDepositAddress('BTC') resp.should.be.ok() resp.should.have.properties(['ticker', 'provider_ticker', 'address']) }) it('accounts.getDepositAddresses() should return a list of addresses', async function () { const resp = await accounts.getDepositAddresses('BTC') resp.should.be.ok() resp.should.be.an.Array() resp[0].should.have.properties(['ticker', 'provider_ticker', 'address']) }) })
//! ################################################################ //! Copyright (c) 2004 Amazon.com, Inc., and its Affiliates. //! All rights reserved. //! Not to be reused without permission //! $Change: 1312631 $ //! $Revision: 1.1 $ //! $DateTime: 2007/03/02 09:47:36 $ //! ################################################################ function n2PopoverPaneInitLibrary() { // Begin library code wrapper. Goes all the way to the bottom of the file if (window.goN2LibMon) goN2LibMon.beginLoad('popoverPane', 'n2CoreLibs'); window.N2PopoverPane=function(oPopover, sID) { this.sID = sID; this.aSubPanes=null; this.bIsSubPane=false; this.maxSubPaneWidth; this.currentWidth; this.currentHeight; this.bUseHistory = false; this.bAllowDynamicUpdate = false; this.sDefaultContent = '{PANE_ID}'; this.oPopover=oPopover; this.nDefaultWidth ='auto'; // overrides everything else (inc. min/max) this.nMinWidth = 0; //61; // overrides value obtained from sizing content this.nMaxWidth = 0; //600; // overrides value obtained from sizing content this.nDefaultHeight ='auto'; // overrides everything else (inc. min/max) this.nMinHeight = 0; //60; // overrides value obtained from sizing content this.nMaxHeight = 0; //300; // overrides value obtained from sizing content this.sElementID; // set to change the default elementID to populate/update this.bDisableScrollbars = false; // if true would not allow scrollbars to be added automatically this.bDisableResizing = false; // if true would not compute new pane/popover sizes automatically this.bTemplateHasPlaceholders = false; this.bReplaceTemplateTDFieldPlaceholders = false; this.myStyle; this.LADTimer = null; this.bbLADSupported = false; this.nLADRetries; // calculated in show() this.sLADKey = null; // gaTD[key] exists this.sLADField = null; // gaTD[<sID>].field or gaTD[key].field exists this.sLADDUAction = null; var imagePath = goN2Locale.getImageURL('JSF-loading-bar', 'nav2/images/loading-bar.gif'); this.sLADLoadingMessage = '<div align="center">' + goN2Locale.getString('loading_13548', 'Loading...') + '<im'+'g s'+'rc="' + imagePath + '" height="9" align="absmiddle"></div>'; this.sLADTimeoutMessage = goN2Locale.getString('unable_to_get_info_36020', "Unable to obtain necessary information. Please try again later"); this.bPersistContent = false; } new N2PopoverPane(); N2PopoverPane.prototype.locate=null; N2PopoverPane.prototype.relocate=null; N2PopoverPane.prototype.postPopulate=null; N2PopoverPane.prototype.getID = function() { return this.sID;} N2PopoverPane.prototype.setDefaultWidth = function(n) { this.nDefaultWidth = n; } N2PopoverPane.prototype.setMinWidth = function(n) { this.nMinWidth = n; } N2PopoverPane.prototype.setMaxWidth = function(n) { this.nMaxWidth = n; } N2PopoverPane.prototype.setCurrentWidth = function(n) {this.currentWidth = n; } N2PopoverPane.prototype.setDefaultHeight = function(n) { this.nDefaultHeight = n; } N2PopoverPane.prototype.setMinHeight = function(n) { this.nMinHeight = n; } N2PopoverPane.prototype.setMaxHeight = function(n) { this.nMaxHeight = n; } N2PopoverPane.prototype.setCurrentHeight = function(n) {this.currentHeight = n; } N2PopoverPane.prototype.disableScrollbars = function(f) { this.bDisableScrollbars = f; } N2PopoverPane.prototype.setElementID = function(sID) { this.sElementID = sID; } N2PopoverPane.prototype.getElementID = function() { return this.sElementID; } N2PopoverPane.prototype.persistContent = function (b) { this.bPersistContent = b; } N2PopoverPane.prototype.setStyle= function(n) { this.myStyle = n; } N2PopoverPane.prototype.setUseHistory = function(f) { this.bUseHistory = f; } N2PopoverPane.prototype.useHistory = function(f) { return this.bUseHistory; } N2PopoverPane.prototype.setTemplate = function(s) { this.sTemplate = s; this.sDefaultContent = s; // 9/19/2004, essential currently for the templating(?) code to work? if (this.sTemplate.indexOf('{') >=0) this.bTemplateHasPlaceholders = true; } N2PopoverPane.prototype.replaceTemplateTDFieldPlaceholders = function (b) { this.bReplaceTemplateTDFieldPlaceholders = b; } N2PopoverPane.prototype.setDefaultContent = function (s) { this.sDefaultContent = s; } N2PopoverPane.prototype.isSubPane = function() { return this.bIsSubPane; } N2PopoverPane.prototype.hasSubPanes = function() { return this.aSubPanes != null; } N2PopoverPane.prototype.configureLADSupport = function(b, sKey, sField, sDUAction, sDUParams, sLoadingMsg, sTimeoutMsg) { this.bLADSupported = b; if (sKey) this.sLADKey = sKey; if (sField) this.sLADField = sField; if (sDUAction) this.sLADDUAction = sDUAction; if (sDUParams) this.sDUParams = sDUParams; if (sLoadingMsg) this.sLADLoadingMessage = sLoadingMsg; if (sTimeoutMsg) this.sLADTimeoutMessage = sTimeoutMsg; } N2PopoverPane.prototype._initialize = function(bFirstPopulate) { ; this.resetLAD(); if (bFirstPopulate && this.bPersistContent) this.sDefaultContent = null; var aSubPanes = this.aSubPanes; if (aSubPanes != null) { var nSubs = aSubPanes.length; for (var i=0; i<nSubs; i++) { this.aSubPanes[i].initialize(bFirstPopulate); } } else { ; } } N2PopoverPane.prototype.initialize = N2PopoverPane.prototype._initialize; N2PopoverPane.prototype.resetLAD = function() { this.nLADRetries = this.oPopover.nLADTimeoutMs/this.oPopover.nLADRetryMs; this.bLADLoading = false; this.nLADAllow = 1; if (this.LADTimer) { ; clearTimeout(this.LADTimer); this.LADTimer = null; } } N2PopoverPane.prototype.aCloneList = { oPopover:1, nDefaultWidth:1, nMinWidth:1, nMaxWidth:1, nDefaultHeight:1, nMinHeight:1, nMaxHeight:1, sElementID:1} N2PopoverPane.prototype.clone = function() { var pane = new N2PopoverPane(); for (var key in this) { if (this.aCloneList[key] && key != 'toString') { pane[key] = this[key]; } } return pane; } N2PopoverPane.prototype.findPane = function (sPaneID) { ; var oPane=null; var oTmp; if (sPaneID == this.sID) { oPane = this; } else { var aSubPanesHash = this.aSubPanesHash; if(aSubPanesHash) { oPane = aSubPanesHash[sPaneID]; if (goN2U.isUndefOrNull(oPane)) { for (var sID in aSubPanesHash) { if (sID == this.sID) next; oPane = aSubPanesHash[sID].findPane(sPaneID); if (!goN2U.isUndefOrNull(oPane)) { break; } } } } } return oPane; } N2PopoverPane.prototype.toString = function () { var txt= "\nPaneID: " + this.sID +"\n"; txt+= "ElementID: " + this.sElementID + "\n"; txt+= "nDefaultWidth: " + this.nDefaultWidth + "\n"; txt+= "nMinWidth: " + this.nMinWidth + "\n"; txt+= "nMaxWidth: " + this.nMaxWidth + "\n"; txt+= "nDefaultHeight: " + this.nDefaultHeight + "\n"; txt+= "nMinHeight: " + this.nMinHeight + "\n"; txt+= "nMaxHeight: " + this.nMaxHeight + "\n"; txt+= "myStyle: " + this.myStyle + "\n"; return txt; } N2PopoverPane.prototype.addSubPane = function(oPane, sID) { ; ; ; if(!this.aSubPanes) this.aSubPanes = new Array(); if(!this.aSubPanesHash) this.aSubPanesHash = new Object(); this.aSubPanes[this.aSubPanes.length] = oPane; this.aSubPanesHash[sID] = oPane; oPane.sID = sID; oPane.bIsSubPane = true; oPane.setElementID(sID); oPane.oPopover = this.oPopover; // safety(?) return oPane; } N2PopoverPane.prototype.newSubPane = function(sID) { ; var oPane = new N2PopoverPane(this.oPopover, sID); this.addSubPane(oPane, sID); return oPane; } N2PopoverPane.prototype.getSubPane = function (sID) { ; if(!this.aSubPanesHash) this.aSubPanesHash = new Array(); if (!this.aSubPanesHash[sID]) { ; this.newSubPane(sID); } return this.aSubPanesHash[sID]; } N2PopoverPane.prototype.populateSubPanes = function(sAction, sID, sType, sParams, sLinkID, sHref, sLinkText) { var aSubPanes = this.aSubPanes; if (aSubPanes != null) { this.maxSubPaneWidth = 0; ; var nSubs = aSubPanes.length; for (var i=0; i<nSubs; i++) { var oSubPane = aSubPanes[i]; ; // + oPane.index.toString() ); if (oSubPane.populate) { ; ; oSubPane.populate(sAction, sID, sType, sParams, sLinkID, sHref, sLinkText); this.maxSubPaneWidth = Math.max(this.maxSubPaneWidth, oSubPane.currentWidth); } } if ((this.nDefaultWidth == 'auto') && !this.bIsSubPane && this.maxSubPaneWidth) { ; goN2U.setWidth(this.oPopover, this.maxSubPaneWidth+6); } } else { ; } } N2PopoverPane.prototype.prepareClose = function(bInit) { var aSubPanes = this.aSubPanes; ; if (aSubPanes != null) { var nSubs = aSubPanes.length; for (var i=0; i<nSubs; i++) { aSubPanes[i].prepareClose(bInit); } } this._prepareClose(bInit); } N2PopoverPane.prototype._prepareClose = function(bInit) { if (this.bPersistContent) this.sDefaultContent = this.oPopover.getContent(this); } N2PopoverPane.prototype.enableDynamicUpdate = function (bF) { this.bAllowDynamicUpdate = bF; } N2PopoverPane.prototype.setDUHandler = function(sH, sM) { this.sDUHandlerName = sH; this.sRequestMode = sM; } N2PopoverPane.prototype.setDUAction = function(s) { this.bAllowDynamicUpdate = true; this.sDUAction = s; } N2PopoverPane.prototype.setDUParams = function(s) { this.sDUParams = s; } N2PopoverPane.prototype.setDUTarget = function(v) { this.sDUTarget = v; } N2PopoverPane.prototype.getDUHandlerName = function() { return this.sDUHandlerName; } N2PopoverPane.prototype.getDURequestMode = function() { return this.sRequestMode; } N2PopoverPane.prototype.getCurrentRequest = function() { return this.sCurrentRequestID; } N2PopoverPane.prototype.sLoadingMessage = window.gsN2LoadingMessage; N2PopoverPane.prototype.sTimeoutMessage = window.gsN2TimeoutMessage; N2PopoverPane.prototype.setLoadingMessage = function (sHtmlFragment) { this.sLoadingMessage = sHtmlFragment; } N2PopoverPane.prototype.setTimeoutMessage = function (sHtmlFragment) { this.sTimeoutMessage = sHtmlFragment; } N2PopoverPane.prototype.setDefaultDUContent = function (s) { this.sTimeoutMessage = s; } N2PopoverPane.prototype.hookForm = function (sFormName, sAction, sID, sType, params) { this.sHookFormName = sFormName; this.sHookAction = sAction; this.sHookID = sID; this.sHookType = sType; this.hookParams = params; } N2PopoverPane.prototype.rehookForm = function () { if (this.sHookFormName) { n2HookForm (this.sHookFormName, this, this.oPopover.objectName, this.sHookAction, this.sHookID, this.sHookType, this.hookParams, this.sID); } else { ; } } N2PopoverPane.prototype.requestUpdate = function (action, id, type, params, overrideSuccess, overrideFailure) { this.sCurrentRequestID = this.oPopover.requestUpdate (this, action, id, type, params, overrideSuccess, overrideFailure); } N2PopoverPane.prototype.submitCallback = function (sAction, sID, sType, sParams, bUseCachedArgs) { return true; } N2PopoverPane.prototype._submitFormUpdate = function (sAction, sID, sType, sParams, bUseCachedArgs) { ; if (!this.submitCallback(sAction, sID, sType, sParams, bUseCachedArgs)) { ; return false; } if (bUseCachedArgs) { sAction = sAction ? sAction : this.sActionC; sID = sID ? sID : this.sIDC; sType = sType ? sType : this.sTypeC; sParams = sParams ? sParams : this.sParamsC; } this.sActionC = sAction; this.sIDC = sID; this.sTypeC = sType; this.sParamsC = sParams; sAction = n2GetFieldValue(this.oForm, sAction, 'action'); sID = n2GetFieldValue(this.oForm, sID, 'id'); sType = n2GetFieldValue(this.oForm, sType, 'type'); sParams = n2GetFieldValue(this.oForm, sParams, 'params'); this.sCurrentRequestID = this.oPopover.requestUpdate (this, sAction, sID, sType, sParams); return false; } N2PopoverPane.prototype.onRequestSuccess = function (dataArray, fnArray, nStatus, sRequestID) { ; ; if (dataArray && dataArray.length) { this.setContent(dataArray[0]); } if (fnArray && fnArray.length) { var fn = fnArray[0]; if (fn.length) { fn = this.replacePlaceholders(fn); fn = this.oPopover.replacePlaceholders(fn); try { eval (fn); } catch (e) { ; } } } } N2PopoverPane.prototype.onRequestFailure = function (sMessage, nStatus) { this.setContent(this.sTimeoutMessage); } N2PopoverPane.prototype.requestComplete = function () { this.sCurrentRequestID = null; } N2PopoverPane.prototype.cancelAllRequests = function (bAbortRequestInProcess) { ; if (this.sCurrentRequestID) { this.oPopover.oUpdateManager.cancelRequest(this.sCurrentRequestID, bAbortRequestInProcess) this.sCurrentRequestID = null; } var aSubPanes = this.aSubPanes; if(aSubPanes) { for (var sID in aSubPanes) { aSubPanes[sID].cancelAllRequests (bAbortRequestInProcess); } } if (this.LADTimer) { ; clearTimeout(this.LADTimer); } } N2PopoverPane.prototype.setContent = function (sHtml, bDisableScrollbars, bDisableResizing) { var bDisableScrollbars = this.bDisableScrollbars | bDisableScrollbars; var bDisableResizing = this.bDisableResizing | bDisableResizing; sHtml = this.replacePlaceholders(sHtml); this.oPopover.setContent(sHtml, this, bDisableScrollbars, bDisableResizing); } N2PopoverPane.prototype.replacePlaceholders = function (sHtml, sAction, sID, sType, sParams, sLinkID, sHref, sLinkText) { ; ; ; if ( sHtml.indexOf('{') == -1 ) return sHtml; var oPopover = this.oPopover; ; sAction = sAction ? sAction : oPopover.action ? oPopover.action :'summary'; sID = sID ? sID : oPopover.thingID; sType = sType ? sType : oPopover.thingType; var aData = oPopover.getDataArray(); var sCategory=''; var sKey; if (sType == 'ak') sKey = sID; else if (aData) { sKey = sType+sID; if (goN2U.isDefined(aData[sKey]) && aData[sKey].cat != null) sCategory=aData[sKey].cat } if (!goN2U.isString(sHtml)) sHtml = sHtml.toString(); if (!sHtml ) return ''; if ( sHtml.indexOf('{') == -1) return sHtml; if ( this.bReplaceTemplateTDFieldPlaceholders ) sHtml = sHtml.replace(/{DUMP_ARRAY}/g, this._dumpArrayKeyValues(sKey)); sHtml = sHtml.replace(/{THING_ID}/g, sID); sHtml = sHtml.replace(/{THING_TYPE}/g, sType); sHtml = sHtml.replace(/{ACTION}/g, sAction); sHtml = sHtml.replace(/{CATEGORY}/g, sCategory); return sHtml.replace(/{PANE_ID}/g, this.sID); } N2PopoverPane.prototype._replaceTemplateTDFieldPlaceholders = function (sTemplate, aArray) { ; if (!this.bReplaceTemplateTDFieldPlaceholders) return sTemplate; ; var sHtml = sTemplate; for (var sKey in aArray) { var sVal = aArray[sKey]; var sPh = '{' + sKey + '}'; var re = new RegExp(sPh, 'g'); ; sHtml = sHtml.replace(re, sVal); } return sHtml; } N2PopoverPane.prototype._replaceTemplateElementPlaceholder = function (sTemplate, sText) { ; var sHtml = sTemplate; if (sText) sHtml = sHtml.replace(/{PLACEHOLDER}/, sText); return sHtml; } N2PopoverPane.prototype._replaceTemplateTDFieldPlaceholdersWithArrayEntryContents = function (sTemplate, sKey) { var aArray = this._getArrayEntryContents(sKey); var sHtml; if (goN2U.isObject(aArray)) { if(sTemplate) { sHtml = this._replaceTemplateTDFieldPlaceholders(sTemplate, aArray); } else { sHtml = this._dumpArrayKeyValues(sKey); } } else { ; sHtml = sTemplate; } return sHtml; } N2PopoverPane.prototype._dumpArrayKeyValues = function (sID) { ; var xEntry = this._getArrayEntryContents(sID); var sHtml; if (goN2U.isObject(xEntry)) { var sHtml = 'Nav2 Framework Default Array Content Display. <br/>'; for (var sKey in xEntry) { var sVal = xEntry[sKey]; sHtml += sKey+": "+sVal+"<br/>"; } } else { sHtml = xEntry } sHtml += '<br/>Use setLayout(...) to modify what/how entries are displayed.'; return sHtml; } N2PopoverPane.prototype.preparePopulateSubpanes = function(oHotspot) { var aSubPanes = this.aSubPanes; if (aSubPanes != null) { ; var nSubs = aSubPanes.length; for (var i=0; i<nSubs; i++) { var oSubPane = aSubPanes[i]; if (oSubPane.preparePopulate) { ; oSubPane.preparePopulate(oHotspot); } } } } N2PopoverPane.prototype._defaultPopulate = function(sAction, sID, sType, sParams, sLinkID, sHref, sLinkText, fLADMethod) { ; var bAllowDefault = true; var sNewContent; if (this.bLADSupported) { if (!this.isDataAvailable(sAction, sID, sType, sParams, sLinkID, sHref, sLinkText, fLADMethod)) { return false; } } switch (sType) { case 'he': // id of an HTML element if (this.sTemplate && this.bTemplateHasPlaceholders) sNewContent = this._replaceTemplateElementPlaceholder(this.sTemplate, this._getElementContents(sID)); else sNewContent = this._getElementContents(sID); bAllowDefault = (sNewContent && sNewContent.length) ? false : true; break; case 'ak': // array key if (this.sTemplate && this.bTemplateHasPlaceholders && this.oPopover.aDataArray) sNewContent = this._replaceTemplateTDFieldPlaceholdersWithArrayEntryContents(this.sTemplate, sID) else sNewContent = this._getArrayEntryContents(sID); bAllowDefault = sNewContent.length ? false : true; break; case 'a': // ASIN case 'as': // ASIN case 'am': // ASIN + merchantID (in optional field) if (this.sTemplate && this.bTemplateHasPlaceholders && this.oPopover.aDataArray) { sNewContent = this._replaceTemplateTDFieldPlaceholdersWithArrayEntryContents(this.sTemplate, sType+sID) bAllowDefault = sNewContent.length ? false : true; } break; case 'n': // node case 's': // search case 'l': // listmania case '-': // none break; default: ; } if (bAllowDefault && this.sDefaultContent) sNewContent = this.sDefaultContent; if (sNewContent && sNewContent.indexOf('{') >=0) { sNewContent = this.replacePlaceholders (sNewContent, sAction, sID, sType, sParams, sLinkID, sHref, sLinkText); } if (sNewContent) { this.setContent(sNewContent, null, null, false); } if (this.bAllowDynamicUpdate) this.populateUsingDynamicUpdate(sAction, sID, sType, sParams); this.populateSubPanes(sAction, sID, sType, sParams, sLinkID, sHref, sLinkText); ; if (this.postPopulate) this.postPopulate (sAction, sID, sType, sParams, sLinkID, sHref, sLinkText); if (this.bLADLoading) this.oPopover.sizeOrPositionChanged(); if (this.sHookFormName) { n2HookForm (this.sHookFormName, this, this.oPopover.objectName, this.sHookAction, this.sHookID, this.sHookType, this.hookParams, this.sID); } return true; } N2PopoverPane.prototype.populate = N2PopoverPane.prototype._defaultPopulate; N2PopoverPane.prototype._getElementContents = function(sID) { ; ; var eElem = goN2U.getRawObject(sID); if (eElem) return eElem.innerHTML; else { ; return null; } } N2PopoverPane.prototype._getArrayEntryContents = function(sKey) { ; ; var retval = null if (goN2U.isUndefOrNull(this.oPopover.aDataArray)) { ; } else if (goN2U.isNull(this.oPopover.aDataArray[sKey])) { ; } else { retval = this.oPopover.aDataArray[sKey]; } ;//goN2Debug.debug("N2PopoverPane._getArrayEntryContents ["+sKey+"]+ returned: "+ (retval ? retval : 'null')); return retval; } N2PopoverPane.prototype.populateUsingDynamicUpdate = function(sAction, sID, sType, sParams) { ; sAction = this.sDUAction ? this.sDUAction : sAction; if (!sAction) { ; return; } sParams = sParams ? sParams : this.sDUParams; ; this.requestUpdate(sAction, sID, sType, sParams); } N2PopoverPane.prototype.isDataAvailable = function(sAction, sID, sType, sParams, sLinkID, sHref, sLinkText, fLADMethod) { ; ; if (this.oPopover._isDataAvailable (sAction, sID, sType, sParams, sLinkID, this.sLADKey, this.sLADField)) { this.LADTimer = null; return true; } else { if (--this.nLADRetries && this.oPopover.isVisible()) { if (!this.bLADLoading) { this.setContent(this.sLADLoadingMessage); this.bLADLoading = true; if (this.sLADDUAction) { ; this.sCurrentRequestID = this.oPopover.requestAnonomousUpdate(this.sRequestMode, this.sDUHandlerName, this.sLADDUAction, sID, sType, this.sDUParams); } } var sObjectMethod = this.oPopover.getObjectName() + ".findPane('" + this.sID +"').populate"; if (sLinkText) { var re = /([^\\])'/gi; sLinkText=sLinkText.replace(re, "$1\\'") ; } if (fLADMethod) { this.LADTimer = setTimeout (fLADMethod, this.oPopover.nLADRetryMs); } else { this.LADTimer = setTimeout (new Function("", sObjectMethod + "(" + (sAction ? "'" + sAction + "'" : null) + "," + (sID ? "'" + sID + "'" : null) + "," + (sType ? "'" + sType + "'" : null) + "," + (sParams ? "'" + sParams + "'" : null) + "," + (sLinkID ? "'" + sLinkID + "'" : null) + "," + (sHref ? "'" + sHref + "'" : null) + "," + (sLinkText ? "'" + sLinkText + "'" : null) + ");"), this.oPopover.nLADRetryMs); } ;//goN2Debug.info ("LAD Pane ("+this.sID+") retry ("+this.nLADRetries+")"); } else { this.LADTimer = null; ; this.setContent(this.sLADTimeoutMessage); this.resetLAD(); } return false; } } N2PopoverPane.prototype.setOwner = function(oO) { this.oOwner = oO; } if (window.goN2LibMon) goN2LibMon.endLoad('popoverPane'); } // END library code wrapper function n2PopoverPaneHasStaticPopover() { n2RunIfLoaded("dynUpdate", n2PopoverPaneInitLibrary, "popoverpaneLoad"); } n2RunIfLoaded("staticpopover", n2PopoverPaneHasStaticPopover, "popoverpaneHasStatic");
import Reforma from '@reforma/core' import React from 'react' import { mount } from 'enzyme' import Table from '../index' describe('<Table />', () => { test('normal scenario', async () => { mockHttp() const ds = createDataSource() const params = { _page: 1, _limit: 10 } const table = createComponent(ds, params) expect(table.find('Placeholder').prop('children')).toBe('Loading...') expect(Reforma.http.get).toHaveBeenCalledWith( '/presidents', expect.objectContaining({ params }) ) await new Promise(resolve => setTimeout(resolve, 0)) table.update() expect(table.find('Data').text()).toBe([1, 'John', 'Quincy Adams'].join('')) }) test('empty data', async () => { mockHttp([]) const ds = createDataSource() const table = createComponent(ds, {}) await new Promise(resolve => setTimeout(resolve, 0)) expect(table.find('Placeholder').text()).toBe('No data') }) }) const defaultBody = { presidents: [{ id: '1', first_name: 'John', last_name: 'Quincy Adams' }] } function mockHttp(resp = defaultBody) { Reforma.http.get = jest.fn(() => ({ ok: true, json: () => resp, headers: { 'X-Total-Count': 10 } })) } function createDataSource() { const type = Reforma.createType({ name: 'President', fields: { id: Reforma.integer.id, firstName: Reforma.string, lastName: Reforma.string } }) return Reforma.createCollectionDS({ type, serialRoot: 'presidents', url: '/presidents' }) } function createComponent(ds, params) { return mount( <Table params={params} dataSource={ds} columns={['id', 'firstName', 'lastName']} /> ) }
const Discord = require('discord.js') const EventEmitter = require('events') const { Prefix, Grant } = require('@lib/models') const { GenericErrorEmbed } = require('@lib/embeds') const CommandHandler = require('./commandHandler') module.exports = class Bot extends EventEmitter { constructor (config) { super() this.commands = new CommandHandler(this, config.commandsPath) this.prefix = config.prefix || '>' this.client = new Discord.Client() this.client.on('ready', () => this.emit('ready')) this.ratelimits = {} this.client.on('message', async (msg) => { let prefix = (await Prefix.findOne({ guild: (msg.guild || msg.channel).id }) || {}).prefix || this.prefix if (!msg.content.startsWith(prefix) || msg.author.bot) return let first = msg.content.toLowerCase().split(' ')[1] let key = msg.content.toLowerCase().substr(prefix.length).split(' ')[0] msg.prefix = prefix if (msg.content.startsWith(prefix + 'cask')) { msg.content = msg.content.split(' ').slice(1).join(' ') key = msg.content.split(' ')[0] } if (msg.guild && msg.guild.ownerID !== msg.author.id && ['invite', 'help', 'search', 'top', 'vote'].indexOf(key) === -1 && !(await Grant.findOne({ guild: msg.guild.id, role: { $in: msg.member.roles.map(role => role.id) }, key: { $in: [key, 'all'] } })) ) { return msg.channel.send(GenericErrorEmbed(`:raised_hand: You don't have permission to run that command. Ask the server owner to grant this command to you using \`${prefix}cask permission ${key} grant ${msg.member.highestRole.name}\``, 'Permission Denied')) } this.commands.run(first, msg) }) this.client.on('rateLimit', (rateLimit) => { let path = rateLimit.path.split('/') this.client.rest.handlers[rateLimit.path].destroy() let i = 0 while (isNaN(parseInt(path[i])) && i < path.length) { i++ } let guild try { guild = this.bot.client.channels.get(path[i]) } catch (e) {} try { if (!guild) guild = this.bot.client.guilds.find(g => g.channels.has(path[i])) } catch (e) {} try { if (!guild) guild = this.bot.client.guilds.get(path[i]) } catch (e) {} if (guild) { this.ratelimits[guild.id] = (this.ratelimits[guild.id] || 0) + 1 if (this.ratelimits[guild.id] >= 3) { this.ratelimits[guild.id] = 0 try { guild.owner.send(`Left \`${guild.name}\`, too many ratelimits.\nUse \`>invite\` to get a new invite.`) } catch (e) {} try { guild.leave() } catch (e) {} } } }) this.client.login(config.token) } }
/*TMODJS:{"version":37,"md5":"53612a4b23f5f1b160c552d22679401f"}*/ define(function(require) { return require("../template")("goods/list", function($data, $id) { var $helpers = this, $each = $helpers.$each, data = $data.data, $value = $data.$value, $index = $data.$index, $escape = $helpers.$escape, $string = $helpers.$string, cut = $data.cut === undefined ? $helpers.cut : $data.cut, $out = ""; $each(data.goods_list, function($value, $index) { $out += ' <li class="mb_10 sh"> <dl> <dt> <a href="'; $out += $escape($value.goods_url); $out += '"> <img src="'; $out += $escape($value.goods_pic); $out += '"> </a> </dt> <dd> <p class="mb_5">'; $out += $string(cut($value.goods_name, 7)); $out += '</p> <p class="pink">¥'; $out += $escape($value.goods_price); $out += '</p> <p script-role="fav" gid="'; $out += '$value.goods_id}" is_like="1">取消收藏</p> </dd> </dl> </li> '; }); return new String($out); }); });
module.exports = { port: 56, express: require('express'), http: require('http'), MongoClient: require('mongodb').MongoClient, ObjectID: require('mongodb').ObjectID, dbLink: 'mongodb://localhost:27017/allData', }
/* Layout Controller */ myAppC.controller('LayoutCtrl', [ '$scope', '$sessionStorage', function ($scope, $sessionStorage) { $scope.$storage = $sessionStorage; } ]);
/** * Created by hasee on 2018/1/27. */ Ext.define('Admin.view.talent.Talent', { extend: 'Ext.Panel', xtype: 'talent', title: '天赋管理', requires: [ 'Admin.view.talent.TalentController', 'Ext.button.Button', 'Ext.form.field.Date' ], controller: "talent", layout: { type: 'vbox', align: 'stretch' }, items: [{ xtype: 'form', reference: 'form', defaultButton: 'btn_search', layout: 'column', defaults: { labelAlign: 'right' }, items: [{ xtype: 'datefield', name: 'startTime', reference:'startTime', hidden:true, fieldLabel: '起始时间', margin: '15px 0px 0px 0px', labelWidth: 60, format: 'Y-m-d', editable: false }, { xtype: 'datefield', name: 'endTime', reference:'endTime', hidden:true, fieldLabel: '结束时间', margin: '15px 0px 0px 0px', labelWidth: 60, format: 'Y-m-d', editable: false },{ xtype: 'textfield', reference: 'text', fieldLabel: '天赋名称', margin: '15px 0px 0px 0px', name: 'text' }] }, { xtype: 'grid', sortableColumns: true, reference: 'grid', flex: 1, store: 'talent.Talent', columns: [{ xtype: 'rownumberer' },{ text: 'id', dataIndex: 'id', width: 30 },{ text: '天赋名称', dataIndex: 'text', width: 245 },{ text: '中文名', dataIndex: 'chineseName', width: 245 },{ text: '英雄id', dataIndex: 'heroId', width: 150 },{ text: '所需等级', dataIndex: 'grade', width: 150 },{ text: '类型', dataIndex: 'type', width: 150 },{ text: '操作', xtype: 'actioncolumn', width: 100, hidden:true, items: [] }], selModel: { selType: 'checkboxmodel' }, dockedItems: [{ xtype: 'toolbar', items: [{ text: '查询', iconCls: 'fa fa-search', reference: 'btn_search', handler: 'search' }, { text: '清空条件', iconCls: 'fa fa-search', listeners: { click: 'reset' } }] }, { xtype: 'pagingtoolbar', store: 'talent.Talent', dock: 'bottom', displayInfo: true }], listeners: { beforerender: 'gridBeforeRender', render: 'search' } }] });
// Capturar evento de submit do formulaŕio const form = document.querySelector('.form'); form.addEventListener('submit', (e) => { e.preventDefault(); const inputWeight = e.target.querySelector('#weight'); const inputHeight = e.target.querySelector('#height'); const weight = Number(inputWeight.value); const height = Number(inputHeight.value); if(!weight) { setResult('Peso inválido', false); return; } if(!height) { setResult('Altura inválida', false); return; } const imc = getIMC(weight, height); const IMCIndex = getIMCIndex(imc); const message = `Seu IMC é ${imc} (${IMCIndex})`; setResult(message, true); }); function getIMCIndex(imc) { const index = [ 'Abaixo o peso', 'Peso normal', 'Sobrepeso', 'Obesidade I', 'Obesidade II', 'Obesidade III' ]; if(imc >= 39.9) return index[5]; if(imc >= 34.9) return index[4]; if(imc >= 29.9) return index[3]; if(imc >= 24.9) return index[2]; if(imc >= 18.5) return index[1]; if(imc < 18.5) return index[0]; } function getIMC(weight, height) { const imc = weight / Math.pow(height, 2); return imc.toFixed(2); } function createParagraph() { const paragraph = document.createElement('p'); return paragraph; } function setResult (message, isValid) { const result = document.querySelector('.text'); result.innerHTML = ''; const p = createParagraph(); p.innerHTML = message; if(isValid) { p.classList.add('paragraph-result'); } else { p.classList.add('bad') } result.appendChild(p); }
import * as actions from './../actions'; const categoryState = { categories:[] } export default function categoryReducer (state = categoryState, action){ switch(action.type){ case actions.GET_ALL_CATEGORY: return { ...state, categories:action.payload.data } case actions.INSERT_CATEGORY: return { ...state, categories : action.payload.data } default: return { ...state } } }
import {patch, addFlag} from ".." import {supports} from "../utils" import {toLength} from "../abstract-ops" // if (!reGlobal) { // reGlobal = this.global // ? this // : new re.RegExp(this.source, `${this.flags}g`) // } const sticky = const test = () => { let re = new RegExp("b", "y") return !re.test("ab") && re.flags.includes("y") && re.sticky } // if (!supports(test)) patch(sticky) patch({sticky: "y"}, re => { if (!re.flags.delete("y")) return let reGlobal re.proto({ exec(str) { if (!reGlobal) { let flags = [...new Set(this.flags).add("g")].join("") reGlobal = new re.RegExp(this.source, flags) } let at = toLength(this.lastIndex) reGlobal.lastIndex = at let match = reGlobal.exec(str) if (match) { if (match.index == at) { this.lastIndex = reGlobal.lastIndex return match } this.lastIndex = 0 } return null }, }) })
var logger = require("morgan"); var mongoose = require("mongoose"); var cheerio = require("cheerio"); var axios = require("axios"); var express = require("express"); var exphbs = require("express-handlebars"); var app = express(); var PORT = process.env.PORT || 3001; var db = require("./models"); app.use(express.static("public")); app.use(express.urlencoded({ extended: true })); // Set Handlebars as the default templating engine. app.engine("handlebars", exphbs({ defaultLayout: "main" })); app.set("view engine", "handlebars"); // Database configuration mongoose.connect( "mongodb://dolwin:mongo#333@ds249717.mlab.com:49717/mongoscrapper", { useNewUrlParser: true, useUnifiedTopology: true } ); app.get("/", function(req, res) { res.render("index"); }); app.get("/scrape", function(req, res) { db.Article.deleteMany({}).then(function() { axios.get("http://thehackernews.com").then(function(response) { var $ = cheerio.load(response.data); $("div.body-post").each(function(i, item) { var result = {}; var link = $(this) .children("a") .attr("href"); var summary = $(this) .children("a") .children("div.home-post-box") .children("div.home-right") .children("div.home-desc") .text(); var title = $(this) .children("a") .children("div.home-post-box") .children("div.home-right") .children("h2.home-title") .text(); result.summary = summary; result.link = link; result.title = title; db.Article.create(result).then(function(data) { console.log(data); }); }); }); }); res.json("Done"); }); app.get("/articles", function(req, res) { db.Article.find({}) .populate("note") .then(data => res.json(data)); }); app.post("/delete/:id", function(req, res) { db.Article.deleteOne({ _id: req.params.id }).then(function(data) { res.end(); }); }); app.post("/removesaved/:id", function(req, res) { db.Article.findByIdAndUpdate({ _id: req.params.id }, { issaved: false }).then( function(data) { res.end(); } ); }); app.get("/saved", function(req, res) { db.Article.find({ issaved: true }) .populate("note") .then(function(data) { res.json(data); }); }); app.post("/saved/:id", function(req, res) { db.Article.findByIdAndUpdate({ _id: req.params.id }, { issaved: true }).then( function() { res.send("Saved articles"); } ); }); app.post("/comment/:id", function(req, res) { db.Note.create({ note: req.body.note }).then(function(returnedNote) { return db.Article.findOneAndUpdate( { _id: req.params.id }, { $push: { notes: returnedNote._id } }, { new: true } ).then(function(data) { res.json(data); }); }); }); app.get("/comments/:id", function(req, res) { db.Note.findOne({ _id: req.params.id }).then(function(data) { res.json(data); }); }); app.listen(PORT, function() { console.log("Server running on port", PORT); });
// const fs = require('fs'); const compiler = require('vue-native-template-compiler'); const cssParse = require('css-parse'); const beautify = require('js-beautify').js_beautify; const constants = require('../util/constants'); const addvm = require('../util/addvm'); const parseCss = require('../util/parseCss'); var sourceMap = require('source-map'); var hash = require('hash-sum'); var path = require('path'); const querystring = require('querystring') var lineNumber = require('line-number'); const parse5 = require('parse5'); const filePath = 'test.js'; var splitRE = /\r?\n/g; // the watch reference node-watch, there may be some changes in the future // const watch = require('../util/watch'); // const walk = require('../util/walk'); // const FILTER = /\.vue$/; const DEFAULT_OUTPUT = { template: { import: `import { Component as ${constants.COMPONENT} } from 'react'`, render: `const ${constants.TEMPLATE_RENDER} = () => null` }, script: `const ${constants.SCRIPT_OPTIONS} = {}` }; // walk('./', { // filter: FILTER // }, function (name) { // compileVueToRn(name); // }); // watch('./', { // recursive: true, // filter: FILTER // }, function (evt, name) { // if (evt === 'update') { // compileVueToRn(name); // } else if (evt === 'remove') { // remove(name); // } // }); function compileVueToRn(resource, filename, options) { const code = resource.toString(); const cparsed = compiler.parseComponent(code, { pad: 'line' }); // console.log(cparsed); let output = ''; let mappings = ''; // add react-vue import output += `import ${constants.VUE}, { observer as ${ constants.OBSERVER } } from 'vue-native-core'`; output += '\n'; // // add react import // output += `import ${constants.REACT} from 'react'` // output += '\n'; // add react-native import output += `import ${constants.REACT_NATIVE} from 'react-native'`; output += '\n'; // add prop-type import output += `import ${constants.PROP_TYPE} from 'prop-types'`; output += '\n'; // add component builder import output += `import { buildNativeComponent as ${ constants.BUILD_COMPONENT } } from 'vue-native-helper'`; output += '\n'; // parse template const template = cparsed.template; //Consider the start of template for debugging // let templateStartIndex = code.indexOf("<"); let tempStringBeforeStart = code.substring(0, templateStartIndex); let templateLineNumber = tempStringBeforeStart.split(splitRE).length - 1; // Get tags and location of tags from template // let nodes = []; const templateFragments = parse5.parseFragment(cparsed.template.content, { sourceCodeLocationInfo: true }); if (templateFragments.childNodes) { traverse(templateFragments, nodes); } let templateParsed = DEFAULT_OUTPUT.template; if (template) { const templateContent = template.content.replace(/\/\/\n/g, '').trim(); if (templateContent) { templateParsed = parseTemplate(templateContent); } } // add render dep import output += templateParsed.import; output += '\n'; // parse script const script = cparsed.script; let scriptParsed = DEFAULT_OUTPUT.script; if (script) { const scriptContent = script.content.replace(/\/\/\n/g, '').trim(); scriptParsed = parseScript(scriptContent); mappings = generateSourceMap(code); } if (mappings) { // Start of the script content // var beforeLines = output.split(splitRE).length; // Start of the script content of the original code // var scriptLine = code.slice(0, cparsed.script.start).split(splitRE).length + 1; var exportDefaultIndex = code.indexOf('export default'); var tempString = code.substring(0, exportDefaultIndex); var exportDefaultLineNumber = tempString.split('\n').length; } // add vue options output += scriptParsed; output += '\n\n'; var endLines = output.split(splitRE).length - 1; for (; scriptLine < endLines; scriptLine++) { //Skip export default line if (scriptLine !== exportDefaultLineNumber) { mappings.addMapping({ source: mappings._hashedFilename, generated: { line: beforeLines, column: 0 }, original: { line: scriptLine, column: 0 } }); } beforeLines++; } // add render funtion let beautifiedRender = beautify(addvm(templateParsed.render, { indent_size: 2 })); output += beautifiedRender; output += '\n\n'; // Get last line of render code // let renderEndLine = beautifiedRender.split(splitRE).length - 1; // Search Elements and postion based on render function // var reactVueElementRegex = /__react__vue__createElement/; let foundLines = lineNumber(beautifiedRender, reactVueElementRegex); if (mappings) { foundLines.forEach((line, index) => { let renderJsLine = endLines + line.number; if (foundLines[index + 1]) { for (let i = line.number; i < foundLines[index + 1].number; i++) { // Add Mapping if (nodes[index]) { mappings.addMapping({ source: mappings._hashedFilename, generated: { line: renderJsLine++, column: 0 }, original: { line: nodes[index].startTag.startLine + templateLineNumber, column: 0 } }); } } } else if (nodes[index] && nodes[index].startTag) { // Last Line for (let i = line.number; i < renderEndLine; i++) { // Add Mapping mappings.addMapping({ source: mappings._hashedFilename, generated: { line: renderJsLine++, column: 0 }, original: { line: nodes[index].startTag.startLine + templateLineNumber, column: 0 } }); } } }); } // parse css const styles = cparsed.styles; let cssParsed = {}; styles.forEach(function (v) { const cssAst = cssParse(v.content); cssParsed = Object.assign({}, cssParsed, parseCss(cssAst)); }); // add css obj output += `const ${constants.CSS} = ${JSON.stringify(cssParsed)}`; output += '\n\n'; // Custom blocks for(var i in cparsed.customBlocks) { const block = cparsed.customBlocks[i] const handler = (options.customBlocks || {})[block.type] if(!handler) { console.warn('No handler found for block type', block.type) continue } for(var attr in block.attrs) { if(attr.substr(0,1) === ':') { block.attrs[attr.substr(1)] = block.attrs[attr] delete block.attrs[attr] } } handler.call({ resourceQuery: '?' + querystring.stringify(block.attrs), rootContext: options.projectRoot, callback(v, src) { output += src.replace('export default function', 'function __vue_install_custom_block_' + i) + "\n__vue_install_custom_block_"+i+"({ options: __react__vue__options })\n\n" } }, block.content) } // add builder output += `const ${constants.COMPONENT_BUILDED} = ${ constants.BUILD_COMPONENT }(${constants.TEMPLATE_RENDER}, ${constants.SCRIPT_OPTIONS}, {Component: ${ constants.COMPONENT }, PropTypes: ${constants.PROP_TYPE}, Vue: ${constants.VUE}, ReactNative: ${ constants.REACT_NATIVE }, css: ${constants.CSS}})`; output += '\n\n'; { var name = filename.replace(/[^a-z|A-Z|0-9]/g, ' ') var index = name.indexOf(' ui ') if(index > 0) { name = name.substr(index + 4, name.length - index - 8).split(' ').filter((v) => v != "") name.shift() name = name.map((a) => a.substr(0, 1).toUpperCase() + a.substr(1)).join('') output += `try { ${constants.COMPONENT_BUILDED}.displayName = '${name}' } catch(e) {}\n` output += `try { ${constants.COMPONENT_BUILDED}.name = '${name}' } catch(e) {}\n` } } // export default output += `export default ${constants.OBSERVER}(${ constants.COMPONENT_BUILDED })`; // beautiful // output = beautify(output, { indent_size: 2 }); return { output, mappings: mappings ? mappings.toJSON() : null, customBlocks: cparsed.customBlocks }; // fs.writeFile(name.replace(FILTER, '.js'), output, function(err) { // if (err) { // throw err; // } // }); } // function remove(name) { // fs.unlink(name.replace(FILTER, '.js'), function(err) { // if (err) { // throw err; // } // }); // } function parseTemplate(code) { const obj = compiler.nativeCompiler(code); return { import: obj.importCode, render: `const ${constants.TEMPLATE_RENDER} = ${obj.renderCode}` }; } function generateSourceMap(content) { // hot-reload source map busting var hashedFilename = path.basename(filePath) + '?' + hash(filePath + content); var map = new sourceMap.SourceMapGenerator(); map.setSourceContent(hashedFilename, content); map._hashedFilename = hashedFilename; return map; } function parseScript(code) { const s = `const ${constants.SCRIPT_OPTIONS} = `; code = code .replace(/[\s;]*module.exports[\s]*=/, `\n${s}`) .replace(/[\s;]*export[\s]+default[\s]*\{/, `\n${s} {`); return code; } function traverse(ast, nodes = []) { if (ast.tagName) { nodes.push(ast.sourceCodeLocation); } if (ast.childNodes) { ast.childNodes.forEach((child) => { traverse(child, nodes); }); } } module.exports = compileVueToRn;
'use strict' const Lab = require('lab') const Code = require('code') const Crypto = require('crypto') const lab = exports.lab = Lab.script() const ShelfSessions = require('../index') const secret = Crypto.randomBytes(128) lab.experiment('Shelf sessions - init', () => { lab.test('No name', (done) => { let sessions = ShelfSessions(null, 'string-secret') Code.expect( () => sessions.extend() ).to.throw(Error) done() }) lab.test('No secret', (done) => { Code.expect( () => ShelfSessions('test-name', null) ).to.throw(Error, 'You need to define a valid secret') done() }) lab.test('Invalid secret', (done) => { Code.expect( () => ShelfSessions('test-name', 123) ).to.throw(Error, 'You need to define a valid secret') done() }) lab.test('valid buffer secret', (done) => { Code.expect( () => ShelfSessions('test-name', secret) ).not.to.throw() done() }) lab.test('Valid string secret', (done) => { Code.expect( () => ShelfSessions('test-name', 'string-secret') ).not.to.throw() done() }) lab.test('No name for model', (done) => { let sessions = ShelfSessions('test-name', 'string-secret') Code.expect( () => sessions.extend() ).to.throw(Error) done() }) lab.test('Extend model', (done) => { let sessions = ShelfSessions('test-name', 'string-secret') Code.expect( () => sessions.extend({name: 'foobar'}) ).not.to.throw() done() }) })
import React from "react"; import styles from "./Footer.module.css"; import { Link } from "react-router-dom"; import { IoLogoLinkedin, IoLogoGithub, IoFolderOpenOutline, } from "react-icons/io5"; function Footer({ portfolio, github, linkedin }) { return ( <div className={styles.footer}> <Link to="/about" className={styles.about}> <span>About me</span> </Link> <div className={styles.redes}> <a href={github} className={styles.iconos} target="_blank" rel="noreferrer" > <IoLogoGithub /> </a> <a href={linkedin} className={styles.iconos} target="_blank" rel="noreferrer" > <IoLogoLinkedin /> </a> <a href={portfolio} className={styles.iconos} target="_blank" rel="noreferrer" > <IoFolderOpenOutline /> </a> </div> </div> ); } export default Footer;
import React from "react"; import Plex from "../data/Plex"; import { connect } from "react-redux"; import { ReactComponent as Spinner } from "../assets/svg/spinner.svg"; import { ReactComponent as Windows } from "../assets/svg/windows.svg"; import { ReactComponent as OSX } from "../assets/svg/mac.svg"; import { ReactComponent as Linux } from "../assets/svg/linux.svg"; import { ReactComponent as Docker } from "../assets/svg/docker.svg"; import { ReactComponent as Server } from "../assets/svg/server.svg"; import { ReactComponent as Good } from "../assets/svg/check.svg"; import { ReactComponent as Bad } from "../assets/svg/close.svg"; import { ReactComponent as TmdbLogo } from "../assets/svg/tmdb.svg"; import { ReactComponent as LockIcon } from "../assets/svg/lock.svg"; import { ReactComponent as UnlockIcon } from "../assets/svg/unlock.svg"; import { ReactComponent as UnraidIcon } from "../assets/svg/unraid.svg"; import Api from "../data/Api"; import pjson from "../../package.json"; /* eslint-disable */ const popupCenter = (url, title, w, h) => { // Fixes dual-screen position | credit Tautulli var dualScreenLeft = window.screenLeft != undefined ? window.screenLeft : window.screenX; var dualScreenTop = window.screenTop != undefined ? window.screenTop : window.screenY; var width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width; var height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height; var left = width / 2 - w / 2 + dualScreenLeft; var top = height / 2 - h / 2 + dualScreenTop; var newWindow = window.open( url, title, "scrollbars=yes, width=" + w + ", height=" + h + ", top=" + top + ", left=" + left ); if (window.focus) newWindow.focus(); return newWindow; }; /* eslint-enable */ class Setup extends React.Component { constructor(props) { super(props); this.state = { step: 1, db: "mongo:27017", tls: false, password: "", selectedServer: false, mongoStatus: "", mongoType: "mongodb://", mongoInstall: "docker", finalText: "Getting things set up...", }; this.inputChange = this.inputChange.bind(this); this.saveUser = this.saveUser.bind(this); this.selectServer = this.selectServer.bind(this); this.changeToDb = this.changeToDb.bind(this); this.finalise = this.finalise.bind(this); this.next = this.next.bind(this); this.testMongo = this.testMongo.bind(this); this.waitText = this.waitText.bind(this); this.changeMongoType = this.changeMongoType.bind(this); this.mongoPreset = this.mongoPreset.bind(this); } serverIcon(platform) { switch (platform) { case "Linux": return <Linux />; case "Windows": return <Windows />; case "MacOSX": return <OSX />; case "docker": return <Docker />; default: return <Server />; } } inputChange(e) { const target = e.target; const name = target.name; let value = target.value; this.setState({ [name]: value, mongoStatus: "", }); } componentDidUpdate() { if (this.props.plex.user && this.state.step === 1) { this.setState({ step: 2, }); } if (this.state.user && this.state.step === 2) { this.setState({ step: 3, }); } } loginOauth() { let plexWindow = popupCenter("", "Login with Plex", 500, 500); Plex.plexAuth(plexWindow); } saveUser() { let password = this.state.password; let username = this.props.plex.user.username; let id = this.props.plex.user.id; let email = this.props.plex.user.email; let token = this.props.plex.token; let thumb = this.props.plex.user.thumb; this.setState({ user: { username: username, id: id, email: email, password: password, token: token, thumb: thumb, }, password: false, }); } selectServer(e) { const target = e.target; console.log(target); let id = target.dataset.id; this.setState({ selectedServer: id, }); } changeToDb() { this.setState({ step: 4, }); } next() { this.setState({ step: this.state.step + 1, }); } async testMongo() { this.setState({ mongoStatus: "pending", }); let db = this.state.mongoType + this.state.db; let test = await Api.testMongo(db); this.setState({ mongoStatus: test, }); } async finalise() { this.setState({ step: 5, }); let selectedServer = this.props.plex.servers[this.state.selectedServer]; let config = { user: this.state.user, server: selectedServer, db: this.state.mongoType + this.state.db, }; this.waitText(); try { await Api.saveConfig(config); this.props.checkConfig(true); } catch { this.props.msg({ type: "error", message: "Setup failed, check API is running and no errors, if this persists please contact the dev team.", }); this.setTimeout(() => { location.reload(); }, 3000); } } async waitText(it = 1) { if (this.state.exiting) return; let text, to = 0; switch (it) { case 1: text = "Starting things up..."; to = 1000; break; case 2: text = "Creating configs..."; to = 1000; break; case 3: text = "Connecting to the database..."; to = 1000; break; case 4: text = "Getting your friends..."; to = 1000; break; case 5: text = "Loading your libraries..."; to = 3000; break; case 6: text = "Finding your embarassing movies..."; to = 3000; break; case 7: text = "Finding your embarassing movies... oh wow..."; to = 1000; break; case 8: text = "Building your Petio library..."; to = 3000; break; case 9: text = "Building your Petio library... Grab a cup of tea this could take a few minutes..."; to = 1000; break; case 10: text = "If you're library is extremely big or your server connection is remote this might take a little while..."; to = 120000; break; case 11: text = "We're not done, but you can start using Petio now while the rest of your library scans. Just a second we'll let you in...."; to = 120000; break; case 12: text = "We're not done, but you can start using Petio now while the rest of your library scans. Just a second we'll let you in...."; to = 3000; break; case 13: location.reload(); break; } it++; await this.timeout(to); this.setState({ finalText: text, }); this.waitText(it); } componentWillUnmount() { this.setState({ exiting: true, }); } timeout(ms) { return new Promise((resolve) => setTimeout(resolve, ms)); } changeMongoType() { this.setState({ mongoType: this.state.mongoType === "mongodb+srv://" ? "mongodb://" : "mongodb+srv://", mongoStatus: "", }); } componentDidMount() { let page = document.querySelectorAll(".page-wrap")[0]; page.scrollTop = 0; window.scrollTo(0, 0); } mongoPreset(type) { let preset; switch (type) { case "docker": preset = "mongo:27017"; break; case "unraid": preset = "X.X.X.X:27017"; break; default: preset = "localhost:27017"; } this.setState({ mongoInstall: type, db: preset, }); } render() { return ( <div className="setup--wrap"> <div className="setup--steps"> <div className={`setup--step ${this.state.step > 1 ? "complete" : ""} ${ this.state.step === 1 ? "active" : "" }`} > 1 </div> <span></span> <div className={`setup--step ${this.state.step > 2 ? "complete" : ""} ${ this.state.step === 2 ? "active" : "" }`} > 2 </div> <span></span> <div className={`setup--step ${this.state.step > 3 ? "complete" : ""} ${ this.state.step === 3 ? "active" : "" }`} > 3 </div> <span></span> <div className={`setup--step ${this.state.step > 4 ? "complete" : ""} ${ this.state.step === 4 ? "active" : "" }`} > 4 </div> <span></span> <div className={`setup--step ${this.state.step === 5 ? "active" : ""}`} > 5 </div> </div> <div className="setup--content"> <p className="main-title">Setup</p> {this.state.step === 1 ? ( <div className="step-1"> <p> Welcome to Petio, firstly lets log in to Plex to get all of your user and server info </p> <button className="btn btn__square" onClick={this.loginOauth}> Login with plex </button> </div> ) : null} {this.state.step === 2 ? ( <div className="step-2"> <p> This is your Petio admin user details, we will use your Plex Username / Email, but a custom password just for Petio can be used. </p> <p>Petio Admin Username</p> <input type="text" name="username" value={this.props.plex.user.username} readOnly={true} /> <p>Petio Admin Email</p> <input type="email" name="email" value={this.props.plex.user.email} readOnly={true} /> <p>Petio Admin Password</p> <input type="password" name="password" value={this.state.password} onChange={this.inputChange} /> <button className={`btn btn__square ${ this.state.password ? "" : "disabled" }`} onClick={this.saveUser} > Next </button> </div> ) : null} {this.state.step === 3 ? ( <div className="step-3"> <p>Please select your server</p> {Object.keys(this.props.plex.servers).length === 0 ? ( <p> You don&apos;t own any servers. Only the server owner can setup a Petio instance. </p> ) : ( Object.keys(this.props.plex.servers).map((key) => { let server = this.props.plex.servers[key]; return ( <div key={key} className={`server-select-option ${ this.state.selectedServer === key ? "selected" : "" } ${server.status !== "connected" ? "disabled" : ""}`} data-id={key} onClick={this.selectServer} > <div className="server-icon"> {this.serverIcon(server.platform)} </div> <div className="server-name"> <p> {server.name} <span className={`server-lock ${ server.protocol === "https" ? "secure" : "insecure" }`} > {server.protocol === "https" ? ( <LockIcon /> ) : ( <UnlockIcon /> )} </span> </p> <p className="server-loc">{`${server.protocol}://${server.host}:${server.port}`}</p> </div> <div className="server-status"> <div className={`server-status-item server-status-pending ${ server.status === "pending" ? "active" : "" }`} > <Spinner /> </div> <div className={`server-status-item server-status-good ${ server.status === "connected" ? "active" : "" }`} > <span> <Good /> </span> </div> <div className={`server-status-item server-status-bad ${ server.status === "failed" ? "active" : "" }`} > <span> <Bad /> </span> </div> </div> </div> ); }) )} <button className={ "btn btn__square " + (this.state.selectedServer ? "" : "disabled") } style={{ marginTop: "10px" }} onClick={this.changeToDb} > Next </button> </div> ) : null} {this.state.step === 4 ? ( <div className="step-4"> <p> Mongo Database path, if using docker leave as default, otherwise specify your db path. </p> <p> To switch between local / cloud db clusters click on the prefix to switch between the two. </p> <div className="mongo-options"> <div className={`mongo-option ${ this.state.mongoInstall === "docker" ? "active" : "" }`} onClick={() => this.mongoPreset("docker")} > <Docker /> <p>Docker</p> </div> <div className={`mongo-option unraid ${ this.state.mongoInstall === "unraid" ? "active" : "" }`} onClick={() => this.mongoPreset("unraid")} > <UnraidIcon /> </div> <div className={`mongo-option ${ this.state.mongoInstall === "other" ? "active" : "" }`} onClick={() => this.mongoPreset("other")} > <Server /> <p>Other</p> </div> </div> <div className="mongo-wrap"> <div className="mongo-icon"> <Server /> </div> <div className="mongo-content"> <div className="mongo-prefix" onClick={this.changeMongoType}> {this.state.mongoType} </div> <input style={ this.state.mongoStatus === "pending" ? { pointerEvents: "none" } : { pointerEvents: "all" } } type="text" name="db" value={this.state.db} onChange={this.inputChange} /> </div> <div className="mongo-status"> <div className={`mongo-status-item mongo-status-pending ${ this.state.mongoStatus === "pending" ? "active" : "" }`} > <Spinner /> </div> <div className={`mongo-status-item mongo-status-good ${ this.state.mongoStatus === "connected" ? "active" : "" }`} > <span> <Good /> </span> </div> <div className={`mongo-status-item mongo-status-bad ${ this.state.mongoStatus === "failed" ? "active" : "" }`} > <span> <Bad /> </span> </div> </div> </div> <button className={`btn btn__square ${ this.state.mongoStatus === "pending" ? "disabled" : "" }`} style={{ marginTop: "10px", marginRight: "10px" }} onClick={this.testMongo} > Test </button> <button className={`btn btn__square ${ this.state.mongoStatus !== "connected" ? "disabled" : "" }`} style={{ marginTop: "10px" }} onClick={this.finalise} > Finish </button> </div> ) : null} {this.state.step === 5 ? ( <div className="step-5"> <p>{this.state.finalText}</p> <div className="loading"> <Spinner /> </div> </div> ) : null} </div> <div className="credits"> <a href="https://fanart.tv/" target="_blank" rel="noreferrer"> <p> <strong>FAN</strong>ART<span>.TV</span> </p> </a> <a href="https://www.themoviedb.org/" target="_blank" rel="noreferrer" > <TmdbLogo /> </a> </div> <p className="setup--version"> Petio Admin build (alpha) {pjson.version} </p> </div> ); } } function SetupContainer(props) { return ( <Setup plex={props.plex} api={props.api} user={props.user} checkConfig={props.checkConfig} msg={props.msg} /> ); } const mapStateToProps = function (state) { return { plex: state.plex, api: state.api, user: state.user, }; }; export default connect(mapStateToProps)(SetupContainer);
import express from 'express'; import privacy from './views/privacy'; const router = express.Router(); router.get('/', privacy); router.get('/privacy-policy', privacy); export default router;
var bcrypt = require("bcrypt"); var config = require("config"); function hash(password) { //lấy độ dài key var saltRounds = config.get("salt"); //lấy key var salt = bcrypt.genSaltSync(saltRounds); //hash var hash = bcrypt.hashSync(password, salt); return hash; } function compare(password, hash) { var status = bcrypt.compareSync(password, hash); return status; } module.exports = { hash : hash, compare : compare }
import React from "react"; import { StyleSheet, View, Button, TextInput } from "react-native"; import { globalStyles } from "../styles/style"; import { Formik } from "formik"; export default function Form({ addArticle }) { return ( <View> <Formik initialValues={{ title: "", preview: "", text: "", img: "" }} onSubmit={(values, action) => { addArticle(values); action.resetForm(); }} > {(props) => ( <View> <TextInput style={styles.input} value={props.values.title} placeholder="Введите название статьи" onChangeText={props.handleChange("title")} /> <TextInput style={styles.input} value={props.values.preview} multiline placeholder="Введите анонс статьи" onChangeText={props.handleChange("preview")} /> <TextInput style={styles.input} value={props.values.text} multiline placeholder="Введите текст статьи" onChangeText={props.handleChange("text")} /> <TextInput style={styles.input} value={props.values.img} placeholder="Введите ссылку на изображение для статьи" onChangeText={props.handleChange("img")} /> <View style={styles.btn}> <Button title="Добавить" onPress={props.handleSubmit} ></Button> </View> </View> )} </Formik> </View> ); } const styles = StyleSheet.create({ input: { borderWidth: 1, marginTop: 15, padding: 15, borderRadius: 8, }, btn: { marginTop: 30, }, });
/** * Created by admin on 12/11/2020. */ function checkAge(){ var ageStudent=document.getElementById('age').value; if (ageStudent>=15){ document.getElementById('result').innerHTML=('Du tuoi hoc lop 10'); } else{ document.getElementById('result').innerHTML=('Khong du tuoi hoc lop 10'); } }
(function () { postal.subscribe({ channel: 'channel1', topic: 'topic1', callback: function (d, e) { $('#messages').append($('<li>').text(d.msg)); window.scrollTo(0, document.body.scrollHeight); } }); $('form').submit(function () { const data = { channel: 'channel1', topic: 'topic1', data: { msg: $('#m').val() } }; //postal.publish(data); postal.publish( { channel: 'WebSocket', topic: 'Broadcast', data: { channel: 'WebSocket', topic: 'Broadcast', data: data } } ); return false; }); })();
// individual thread topic with it's comments/replies. server side rendering.
let blessed = require('blessed'); const fs = require('fs'); class Monitor { constructor() { this.logPath = "./log/"; this.debugMode = false; this.screen = blessed.screen() this.statusBody = blessed.box({ top: 0, left: 0, width: '100%', height: '100%', tags: true }); this.body = blessed.box({ top: 1, left: 0, width: '80%', height: '97%', tags: true, scrollable: true, }); this.screen.append(this.statusBody); this.screen.append(this.body); this.screen.key(['escape', 'q', 'C-c'], function (ch, key) { return process.exit(0); }); this.screen.key(['C-d'], (ch, key) => { if (this.debugMode) { this.log("=== Debug mode disabled ==="); this.disableDebugMode(); } else { this.log("=== Debug mode enabled ==="); this.enableDebugMode(); } }); this.screen.key(['C-s', (ch, key) => { this.log(" .,-:;//;:=,"); this.log(" . :H@@@MM@M#H/.,+%;,"); this.log(" ,/X+ +M@@M@MM%=,-%HMMM@X/,"); this.log(" -+@MM; $M@@MH+-,;XMMMM@MMMM@+-"); this.log(" ;@M@@M- XM@X;. -+XXXXXHHH@M@M#@/."); this.log(" ,%MM@@MH ,@%= .---=-=:=,."); this.log(" -@#@@@MX ., -%HX$$%%%+;"); this.log(" =-./@M@M$ .;@MMMM@MM:"); this.log(" X@/ -$MM/ .+MM@@@M$"); this.log(",@M@H: :@: . -X#@@@@-"); this.log(",@@@MMX, . /H- ;@M@M="); this.log(".H@@@@M@+, %MM+..%#$."); this.log(" /MMMM@MMH/. XM@MH; -;"); this.log(" /%+%$XHH@$= , .H@@@@MX,"); this.log(" .=--------. -%H.,@@@@@MX,"); this.log(" .%MM@@@HHHXX$$$%+- .:$MMX -M@@MM%."); this.log(" =XMMM@MM@MM#H;,-+HMM@M+ /MMMX="); this.log(" =%@M@M#@$-.=$@MM@@@M; %M%="); this.log(" ,:+$+-,/H#MMMMMMM@- -,"); this.log(" =++%%%%+/:-."); }]) this.screen.key(['C-a'], (ch, key) => { // making error logPath.ASD(); }); this.screen.key(['C-x'], (ch, key) => { // making error console.error("5555 damnit ", 55552); }); //== Log =========================================== this.logNormal = fs.createWriteStream(this.logPath + "logs.txt", { flags: 'a' }); this.logError = fs.createWriteStream(this.logPath + "errors.txt", { flags: 'a' }); this.logErrorCount = 0; let startServerText = "\r\nServer start : " + this.fullCurrentTime() + "\r\n"; let shurdownServerText = "Server Shutingdown on " + this.fullCurrentTime(); this.logNormal.write(startServerText); this.logError.write(startServerText); this.error = (err,code) => { let errorCount = this.logErrorCount++; this.logError.write(this.fullCurrentTime() + " [" + errorCount + "]\r\n"); this.logError.write((((err && err.stack) ? err.stack : err))); this.logError.write("\r\n"); this.log("{red-fg}[" + (code?"Error "+code:"uncaughtException" )+"]{/red-fg} update in errors log " + this.fullCurrentTime() + ", error number : [" + errorCount + "]"); } console.error = this.error; process.on('uncaughtException', this.error); process.on('exit', (code) => { this.logNormal.write(shurdownServerText + " with code : " + code); this.logError.write(shurdownServerText + " with code : " + code); }); } enableDebugMode() { this.debugMode = true; } disableDebugMode() { this.debugMode = false; } status(text) { this.statusBody.setLine(0, '{black-fg}{white-bg}' + text + '{/white-bg}{/black-fg}'); this.screen.render(); } info(text) { this.body.pushLine(text); this.body.setScroll(this.body.getScrollHeight()); this.screen.render(); } debug(text) { if (this.debugMode) { this.body.pushLine("[" + this.currentTime() + "] Debug : " + text); this.body.setScrollPerc(100); this.screen.render(); } } log(text) { let logText = "[" + this.currentTime() + "] " + text this.body.pushLine(logText); this.body.setScrollPerc(100); this.logNormal.write(logText + "\r\n"); this.screen.render(); } currentTime() { let time = new Date(); return ((time.getHours() < 10) ? "0" : "") + time.getHours() + ":" + ((time.getMinutes() < 10) ? "0" : "") + time.getMinutes() + ":" + ((time.getSeconds() < 10) ? "0" : "") + time.getSeconds(); } fullCurrentTime() { let time = new Date(); return "[" + time.getDate() + "/" + (time.getMonth() + 1) + "/" + time.getFullYear() + "] " + this.currentTime() + ":" + time.getMilliseconds(); } } module.exports = Monitor; // // var c = 1; // setInterval(function() { // status((new Date()).toISOString()); // log('This is line #' + (c++)); // }, 100);
document.addEventListener('DOMContentLoaded', function(event) { const hamburgerMenu = document.getElementById('menu'); const navigation = document.getElementById('navigation'); hamburgerMenu.addEventListener('click', function(event) { hamburgerMenu.classList.toggle('open'); navigation.classList.toggle('navigation--open'); }); var section = document.querySelectorAll('.section'); var sections = {}; var i = 0; Array.prototype.forEach.call(section, function(e) { sections[e.id] = e.offsetTop; }); window.onscroll = function() { var scrollPosition = document.documentElement.scrollTop || document.body.scrollTop; for (i in sections) { if (sections[i] <= scrollPosition) { if (document.querySelector('.navigation__link--active')) { document .querySelector('.navigation__link--active') .classList.remove('navigation__link--active'); } document .querySelector('a[href*=' + i + ']') .classList.add('navigation__link--active'); } } }; });
/* 🤖 this file was generated by svg-to-ts*/ export const EOSIconsPlaylistAddCheck = { name: 'playlist_add_check', data: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M14 10H2v2h12v-2zm0-4H2v2h12V6zM2 16h8v-2H2v2zm19.5-4.5L23 13l-6.99 7-4.51-4.5L13 14l3.01 3 5.49-5.5z"/></svg>` };
import { createContext } from 'react'; const PagesContext = createContext({ homeVisited: false, aboutVisited: false, portfolioVisited: false, toggleHome: () => {}, toggleAbout: () => {}, togglePortfolio: () => {} }); export default PagesContext;
export {default as meta} from "./meta" export const isRegExp = re => { if (re !== Object(re)) return false let matcher = re[Symbol.match] if (matcher !== undefined) return !!matcher return hasMatcher(re) } export const zipObject = (keys, values) => { let obj = Object.create(null) keys.forEach((key, index) => { obj[key] = values[index] }) return obj } const {exec} = /(?:)/ export const hasMatcher = re => { if (re !== Object(re)) return false try { exec.call(re, "") } catch (err) { return false } return true } const asciiId = /^(?!\d)[$\w]+$/ export const isValidId = id => { if (asciiId.test(id)) return true try { new Function(`obj.${id}`) } catch (err) { return false } return true }
import React from 'react' import img from '../cartWidget/Iconns.png' const cartWidget = (props) => { return ( <div className='cartWidget'> <h2><img src={img} alt="Iconns" width='50px'/></h2> </div> ) }; export default cartWidget;
// Given an array of intergers, find two numbers such that they add up to a specific target number. // The function twoSum should return indices of the two numbers such that they add up to the target, // where index1 must be less than index2 Please note that your returned answers (both index1 and index2) // are not zero-based.You may assume that each input would have exactly one solution. // Input: numbers={2, 7, 11, 15}, target=9 Output: index1=1, index2=2 'use strict'; module.exports = findSumIndex; function findSumIndex(arr, value) { let indexMap = {}; for (let i = 0, len = arr.length; i < len; i++) { indexMap[arr[i]] = i; } for (let i = 0, len = arr.length; i < len; i++) { if (indexMap[value - arr[i]] >= 0) { console.log(`index1=${i + 1}, index2=${indexMap[value - arr[i]] + 1}`) return; } } } // Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? // Find all unique triplets in the array which gives the sum of zero.Note: Elements in a triplet (a,b,c) must // be in non-descending order. (ie, a ≤ b ≤ c) The solution set must not contain duplicate triplets. /** * find triplets in the array which give the sum of zero * @param {*} arr */ function findTriplets(arr){ }
import ServicePage from './ServicePage.svelte' export { ServicePage }
import React from 'react'; import { Link } from 'react-router' export default class Main extends React.Component { render() { return ( <div> <ul className="menu"> <li><Link to="/login">Login</Link></li> <li><Link to="/overview">View Lists</Link></li> </ul> <div> {this.props.children} </div> </div> ) } };
const partialResponse = require('express-partial-response'); module.exports = (options) => partialResponse();
import { connect } from 'react-redux'; import TreePage from '../../../components/TreePage'; import EditDialogContainer from './EditDialogContainer'; import ConfirmDialogContainer from './ConfirmDialogContainer'; import {EnhanceLoading, EnhanceDialogs} from '../../../components/Enhance'; import helper,{getActions, fetchJson, postOption} from '../../../common/common'; import Tree from '../../../common/tree'; import {Action} from '../../../action-reducer/action'; import {getPathValue} from '../../../action-reducer/helper'; import {fetchDictionary, setDictionary} from '../../../common/dictionary'; import {buildEditPageState, buildDeleteState} from './state'; const STATE_PATH = ['basic', 'sysDictionary']; const action = new Action(STATE_PATH); const URL_CONFIG = '/api/basic/sysDictionary/config'; const URL_TREE_LIST = '/api/basic/sysDictionary/tree_list'; const URL_LIST = '/api/basic/sysDictionary/list'; const URL_ACTIVE = '/api/basic/sysDictionary/active'; const getSelfState = (rootState) => { return getPathValue(rootState, STATE_PATH); }; const buildState = (config, treeData=[], tableItems=[]) => { const tree = Tree.createWithInsertRoot(treeData, config.root, {guid: 'root', districtType:0}); const key = Tree.getRootKey(tree); return { ...config.index, tree, select: key, expand: {[key]: true}, tableItems, editConfig: config.edit, root: config.root, newObj: { title: config.root, value: null } }; }; const convertToTree = (data, pid) => { let result = [], temp; for (let i = 0; i < data.length; i++) { if ((!pid && !data[i].pid) || (data[i].pid && data[i].pid.value === pid)) { let obj = {title: data[i].id.title, value: data[i].id.value}; temp = convertToTree(data, data[i].id.value); if (temp.length > 0) { obj.children = temp; } result.push(obj); } } return result; }; const initActionCreator = () => async (dispatch) => { try { dispatch(action.assign({status: 'loading'})); const config = helper.getJsonResult(await fetchJson(URL_CONFIG)); const {index, names} = config; const newAction = getActions('sysDictionary', true); index.buttons = index.buttons.filter(items => newAction.indexOf(items.key) !== -1); const items = helper.getJsonResult(await fetchJson(URL_TREE_LIST)); const tree = convertToTree(items); const dictionary = helper.getJsonResult(await fetchDictionary(names)); const list = helper.getJsonResult(await fetchJson(URL_LIST, postOption({}))); const payload = buildState(config, tree, list.data); setDictionary(config.index.tableCols, dictionary); setDictionary(config.edit.tableCols, dictionary); payload.status = 'page'; payload.allItems = items; payload.indexTableItems = items; dispatch(action.create(payload)); } catch (e) { helper.showError(e.message); dispatch(action.assign({status: 'retry'})); } }; const inputChangeActionCreator = (value) => { return action.assign({inputValue: value}); }; // 在树中搜索字典名称(模糊搜索) const searchAction = (dispatch, getState) => { const {allItems, tree, inputValue} = getSelfState(getState()); if (inputValue) { const indexTableItems = allItems.filter(item => item.id.title.includes(inputValue)); dispatch(action.assign({searchValue: inputValue, expand: Tree.search(tree, inputValue), indexTableItems})); } else { dispatch(action.assign({searchValue: inputValue, indexTableItems: allItems})); } }; const addAction = (dispatch, getState) => { const {editConfig, dictionaryCode, newObj} = getSelfState(getState()); const needState = { parentDictionaryCode: newObj, }; editConfig.id = dictionaryCode; const payload = buildEditPageState(editConfig, [], needState, false); dispatch(action.assign(payload, 'edit')); }; // 深拷贝 const deepCopy = (obj) => { let str, newObj = obj.constructor === Array ? [] : {}; if (typeof obj !== 'object') { return; } else if (window.JSON) { str = JSON.stringify(obj), newObj = JSON.parse(str); } else { for (let i in obj) { newObj[i] = typeof obj[i] === 'object' ? deepCopy(obj[i]) : obj[i]; } } return newObj; }; const editAction = (dispatch, getState) => { const {editConfig, tableItems, newObj} = getSelfState(getState()); const index = helper.findOnlyCheckedIndex(tableItems); if(index !== -1) { const {dictionaryLanguage} = tableItems[index]; const newEditConfig = deepCopy(editConfig); const {controls} = newEditConfig; controls[0].type = 'readonly'; const data = helper.getObjectExclude(tableItems[index], ['checked']); data.parentDictionaryCode = newObj; const payload = buildEditPageState(newEditConfig, dictionaryLanguage, data, true, index); dispatch(action.assign(payload, 'edit')); }else { const msg = '请勾选一个'; helper.showError(msg) } }; const checkedId = (tableItems) => { const arrId = tableItems.reduce((result, items) => { items.checked && result.push(items.dictionaryCode); return result; }, []); return arrId; }; // 批量 const batchHandle = (tableItems, dispatch, func) => { let listCode = []; tableItems.map((item)=> {if (item.checked === true) {listCode.push(item.dictionaryCode)}}); func(listCode, dispatch); }; const activeAction = async (dispatch, getState) => { const {tableItems} = getSelfState(getState()); const ajax = async (listCode, dispatch) => { const {returnCode, result, returnMsg} = await fetchJson(URL_ACTIVE, postOption(listCode, 'put')); if (returnCode !== 0 ) { helper.showError(returnMsg); return; } for (let i = 0; i < listCode.length; i++) { for (let j = 0; j < result.data.length; j++) { dispatch(action.update(result.data[j],'tableItems', {key: "dictionaryCode", value: listCode[i]})); } } }; batchHandle(tableItems, dispatch, ajax); }; const delAction = (dispatch, getState) => { const {tableItems, expand, root, dictionaryCode} = getSelfState(getState()); const index = helper.findOnlyCheckedIndex(tableItems); if(index !== -1) { const codeItems = checkedId(tableItems); const confirm = buildDeleteState(); dispatch(action.assign({codeItems, dictionaryCode, expand, root, ...confirm}, 'confirm')); }else { const msg = '请勾选一个'; helper.showError(msg) } }; const toolbarActions = { search: searchAction, add: addAction, edit: editAction, active: activeAction, del: delAction }; const clickActionCreator = (key) => { if (toolbarActions.hasOwnProperty(key)) { return toolbarActions[key]; } else { console.log('unknown key:', key); return {type: 'unknown'}; } }; const doubleClickActionCreator = (rowIndex) => async (dispatch, getState) => { const {editConfig, tableItems, newObj} = getSelfState(getState()); const {dictionaryLanguage} = tableItems[rowIndex]; const newEditConfig = deepCopy(editConfig); const {controls} = newEditConfig; controls[0].type = 'readonly'; const data = helper.getObjectExclude(tableItems[rowIndex], ['checked']); data.parentDictionaryCode = newObj; const payload = buildEditPageState(newEditConfig, dictionaryLanguage, data, true); dispatch(action.assign(payload, 'edit')); }; const checkActionCreator = (isAll, checked, rowIndex) => { const index = isAll ? -1 : rowIndex; return action.update({checked}, 'tableItems', index); }; const expandActionCreator = (key, expand) => { return action.assign({[key]: expand}, 'expand'); }; const selectActionCreator = (key) => async (dispatch, getState) => { let tableItems, dictionaryCode, newObj; const state = getSelfState(getState()); if (state.tree[key].value.guid === 'root') { newObj = { title: state.tree[key].title, value: null, }; dictionaryCode = ''; const data = await fetchJson(URL_LIST, postOption({})); tableItems = data.result.data }else { dictionaryCode = state.tree[key].value; newObj = { title: state.tree[key].title, value: state.tree[key].value, }; const data = await fetchJson(URL_LIST, postOption({dictionaryCode})); if(data.returnCode !== 0) return; tableItems = data.result.data; } dispatch(action.assign({tableItems, select: key, dictionaryCode, newObj})); }; const tabChangeActionCreator = (activeKey) => (dispatch, getState) => { dispatch(action.assign({activeKey})); if (activeKey === 'tree') { const {select} = getSelfState(getState()); return selectActionCreator(select)(dispatch, getState); } }; const linkActionCreator = (key, rowIndex, item) => async (dispatch) => { const dictionaryCode = item.id.code; const newObj = { title: item.id.title, value: item.id.code, }; const data = await fetchJson(URL_LIST, postOption({dictionaryCode})); if(data.returnCode !== 0) return; const tableItems = data.result.data; dispatch(action.assign({tableItems, dictionaryCode, newObj})); }; const mapStateToProps = (state) => { return getSelfState(state); }; const actionCreators = { onInit: initActionCreator, onInputChange: inputChangeActionCreator, onClick: clickActionCreator, onCheck: checkActionCreator, onExpand: expandActionCreator, onSelect: selectActionCreator, onDoubleClick: doubleClickActionCreator, onTabChange: tabChangeActionCreator, onLink: linkActionCreator }; const Component = EnhanceLoading(EnhanceDialogs( TreePage, ['edit', 'confirm'], [EditDialogContainer, ConfirmDialogContainer] )); const Container = connect(mapStateToProps, actionCreators)(Component); export default Container;
const Question = require('../models/Question') module.exports.getAll = () => { return new Promise((resolve, reject) => { Question.find({}, (err, questions) => { if (err) { reject(err) } }) .populate({ path: 'answers', select: 'answerVariant -_id', populate: { path: 'answerVariant', select: 'value -_id' } }) .exec((err, questions) => { if (err) { reject(err) } else { resolve(questions) } }) }) }
const { validate } = require('wannadog-utils') const { models } = require('wannadog-data') const { User } = models /** * Retrieves a registered user * * @param {string} name * @param {string} surname * @param {string} email * @param {string} password * * @returns {Promise} */ module.exports = function (id) { validate.string(id, 'id') return (async () => { const user = await User.findOne({ _id: id }, { _id: 0, password: 0, __v: 0 }).lean() if (!user) throw Error(`User with id ${id} does not exist.`) user.id = id return user })() }
const webpack = require('webpack') const merge = require('webpack-merge') const HtmlWebpackPlugin = require('html-webpack-plugin') const CopyWebpackPlugin = require('copy-webpack-plugin') const { debug, dist, entry, resolve, template, test } = require('./config') const options = { entry, output: { path: dist, publicPath: '/' }, resolve: { modules: ['node_modules', 'src'], extensions: ['.js', '.jsx', '.styl'], alias: { data: resolve('src/js/data/'), build: resolve('build'), } }, module: { rules: [{ test: /\.jsx?$/, exclude: [/node_modules/, /dist/], use: ['react-hot-loader/webpack', 'babel-loader'] }, { test: /\.styl$/, exclude: [/node_modules/, /dist/], use: ['style-loader', 'css-loader', 'stylus-loader'] },{ test : /\.(ttf|eot|svg|woff(2)?)(\?[a-z0-9=&.]+)?$/, exclude: [/node_modules/, /dist/], use : ['file-loader'] }] }, plugins: [ new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify(process.env.NODE_ENV), GOOGLE_KEY: JSON.stringify(process.env.GOOGLE_KEY), GOOGLE_SENDER: JSON.stringify(process.env.GOOGLE_SENDER), }, }), new HtmlWebpackPlugin({ template, filename: 'index.html', inject: 'body' }), new CopyWebpackPlugin([{ from: resolve('src/assets'), to: './' }]) ] } module.exports = test ? merge(options, require('./webpack.test')) : debug ? merge(options, require('./webpack.dev')) : merge(options, require('./webpack.dist'))
(function() { 'use strict'; angular.module('app.cexternas.controller', []) .controller('CexternasCreateCtrl', CexternasCreateCtrl) .controller('CexternasListCtrl', CexternasListCtrl) .controller('CexternasUpdateCtrl', CexternasUpdateCtrl); CexternasCreateCtrl.$inject = ['$location', '$mdToast', 'CausasExternas']; function CexternasCreateCtrl($location, $mdToast, CausasExternas) { var vm = this; vm.create = create; function create() { CausasExternas.save(vm.cexterna, function() { $location.path('/cexternas/list'); $mdToast.show( $mdToast.simple() .textContent('Registro exitoso') .position('bottom right')); }, function(error) { $mdToast.show( $mdToast.simple() .textContent(error.status + ' ' + error.data) .position('bottom right')); }); } } CexternasListCtrl.$inject = ['$location', 'CausasExternas']; function CexternasListCtrl($location, CausasExternas) { var vm = this; vm.query = { order: 'name', limit: 5, page: 1 }; vm.cexternas = CausasExternas.query(); } CexternasUpdateCtrl.$inject = ['$stateParams', '$location', '$mdToast', 'CausasExternas' ]; function CexternasUpdateCtrl($stateParams, $location, $mdToast, CausasExternas) { this.id = $stateParams.idCausa; this.cexterna = CausasExternas.get({ idCausa: this.id }); this.update = function() { CausasExternas.update(this.cexterna, function() { $location.path('/cexternas/list'); $mdToast.show( $mdToast.simple() .textContent('Se ha actualizado La Consulta Externa') .position('bottom right')); }); }; } })();
wr.nameSymbolsRe = /[^[a-zA-Z0-0\-\ ]*$]/g; wr.loginSymbolsRe_ = /^[a-zA-Z0-9\-_]*$/g; wr.loginRe_ = /^[a-zA-Z0-9\-_]+$/g; wr.passwordSymbolsRe_ = /^[a-zA-Z0-9\-+_\/=]*$/g; wr.passwordRe_ = /^[a-zA-Z0-9\-+_\/=]+$/g; wr.emailSymbolsRe_ = /^[a-zA-Zа-яА-Я0-9@\-_.]*$/g; wr.emailRe_ = /^(?:[a-zA-Z0-9\-_.]+)@(?:[a-zA-Zа-яА-Я0-9\-_.]+)\.(?:[a-zA-Zа-яА-Я0-9\-_]{2,}$)/g; wr.intSymbolsRe_ = /^[-+0-9]*$/g; wr.intRe_ = /^[-+]?[0-9]+$/g; wr.intOptRe_ = /^(?:[-+]?[0-9]+)?$/g; wr.floatSymbolsRe_ = /^[-+.0-9]*$/g; wr.floatRe_ = /^[-+]?[0-9]+\.?[0-9]*$/g; wr.floatOptRe_ = /^(?:[-+]?[0-9]+\.?[0-9]*)?$/g; wr.hexColorSymbolsRe_ = /^[a-fA-F0-9]*$/g; wr.hexColorRe_ = /^#?[a-fA-F0-9]{3,6}$/g; wr.validate = function(re, value) { var isvalid = re.test(value); re.lastIndex = 0; return isvalid; }; wr.symbolsLogin = function(value) { return wr.validate(wr.loginSymbolsRe_, value); }; wr.formatLogin = function(value) { return wr.validate(wr.loginRe_, value); }; wr.symbolsPassword = function(value) { return wr.validate(wr.passwordSymbolsRe_, value); }; wr.formatPassword = function(value) { return wr.validate(wr.passwordRe_, value); }; wr.symbolsEmail = function(value) { return wr.validate(wr.emailSymbolsRe_, value); }; wr.formatEmail = function(value) { return wr.validate(wr.emailRe_, value); }; wr.symbolsInt = function(value) { return wr.validate(wr.intSymbolsRe_, value); }; wr.formatInt = function(value) { return wr.validate(wr.intRe_, value); }; wr.formatIntOpt = function(value) { return wr.validate(wr.intOptRe_, value); }; wr.symbolsFloat = function(value) { return wr.validate(wr.floatSymbolsRe_, value); }; wr.formatFloat = function(value) { return wr.validate(wr.floatRe_, value); }; wr.formatFloatOpt = function(value) { return wr.validate(wr.floatOptRe_, value); }; wr.symbolsHexColor = function(value) { return wr.validate(wr.hexColorSymbolsRe_, value); } wr.formatHexColor = function(value) { return wr.validate(wr.hexColorRe_, value); }; wr.formatPresent = function(value) { var va = wr.trimString(value); return va.length > 0; } wr.symbolsPresent = function(value) { var va = wr.trimString(value); return va.length > 0; };
import React, { useState, useEffect } from "react"; import PropTypes from "prop-types"; import {randomServants} from "../../utilities/helpers"; import { containerComponent, withMouseHandlers } from "../helpers/helperComponents"; import ServantCard from "./ui/cards/ServantCard"; import Home from "./ui/Home"; function HomeContainer({ region, pageTitle, mainData, openModal }) { const [randList, setRandList] = useState([]); const [currentRegion, setCurrentRegion] = useState(region); function genServants() { let list = randList; if(currentRegion !== region) { list = randomServants(mainData.length); setRandList(list); setCurrentRegion(region); } return list.map((value, key) => { let servant = mainData[value]; return withMouseHandlers(ServantCard, {dataItem: servant, openModal, region}) }); }; useEffect(() => { setRandList(randomServants(mainData.length)); }, []); return ( <React.Fragment> {containerComponent(<Home pageTitle={pageTitle} genServants={genServants} />)} </React.Fragment> ); }; HomeContainer.propTypes = { region: PropTypes.string, params: PropTypes.object, pageTitle: PropTypes.string, mainData: PropTypes.array }; export default HomeContainer;
import request from 'utils/request' export default { // 获取id课程信息 getCourseInfo(id){ return request({ url: `/serviceadmin/mmyj-course/one/${id}`, method: 'get' }) }, // 学生添加课程 bindingCourse(stCourse){ return request({ url: `/serviceadmin/mmyj-stcourse/`, method: 'post', data: stCourse }) }, // 学生获取课程 getCourseList(){ return request({ url: `/serviceadmin/mmyj-stcourse`, method: 'get' }) }, // 获取加入课程的学生们 getCourseStudentList(id){ return request({ url: `/serviceadmin/mmyj-course/studentList/${id}`, method: 'get' }) } }
import React from 'react'; import { StyleSheet, View } from 'react-native'; import MapView, { Marker } from 'react-native-maps'; const App = () => ( <View style={styles.container}> <MapView style={styles.map} region={{ latitude: 37.78825, longitude: -122.4324, latitudeDelta: 0.0922, longitudeDelta: 0.0421, }} showsUserLocation > <Marker coordinate={{ latitude: 37.78825, longitude: -122.4324 }} title="Location" description="Starbucks" /> </MapView> </View> ); const styles = StyleSheet.create({ container: { ...StyleSheet.absoluteFillObject, flex: 1, justifyContent: 'flex-end', alignItems: 'center', }, map: { ...StyleSheet.absoluteFillObject, }, }); export default App;
/** global namespace **/ let CookieNoir = {}; /** constants **/ CookieNoir.SCREEN_WIDTH = 800; CookieNoir.SCREEN_HEIGHT = 600; CookieNoir.SERVER_ADDRESS = "localhost"; CookieNoir.SERVER_PORT = "8080"; CookieNoir.CLIENT_TYPE = { NONE: 0, PLAYER: 1, OBSERVER: 2, }; CookieNoir.DirectionIcons = { up: "\uf062", down: "\uf063", left: "\uf060", right: "\uf061" }; // layers start at 0, platforms at 1 CookieNoir.level1 = { "pf_0_1": { "file": "0_1.png", "connections": [{ "pfkey": "pf_1_1", "posX": -700 }, { "pfkey": "pf_1_1", "posX": 1800 }] }, "pf_1_1": { "file": "1_1.png", "connections": [{ "pfkey": "pf_2_1", "posX": -1100 }, { "pfkey": "pf_2_2", "posX": 1600 }, { "pfkey": "pf_0_1", "posX": 0.75 } ] }, "pf_2_1": { "file": "2_1.png", "connections": [{ "pfkey": "pf_3_1", "posX": 0.0 }, { "pfkey": "pf_3_2", "posX": 0.75 }, { "pfkey": "pf_1_1", "posX": 0.75 }] }, "pf_2_2": { "file": "2_2.png", "connections": [{ "pfkey": "pf_4_2", "posX": 0.5 }, { "pfkey": "pf_1_1", "posX": 0.5 }], "right": { "pfkey": "pf_5_1", "posX": 0.0 } }, "pf_3_1": { "file": "3_1.png", "connections": [{ "pfkey": "pf_4_1", "posX": 0.5 }, { "pfkey": "pf_2_1", "posX": 0.0 }], "right": { "pfkey": "pf_3_2", "posX": 0.0 } }, "pf_3_2": { "file": "3_2.png", "connections": [{ "pfkey": "pf_4_1", "posX": 0.5 }, { "pfkey": "pf_2_1", "posX": 0.75 }], "left": { "pfkey": "pf_3_1", "posX": 1.0 } }, "pf_4_1": { "file": "4_1.png", "connections": [{ "pfkey": "pf_5_1", "posX": 0.5 }, { "pfkey": "pf_3_1", "posX": 0.25 }, { "pfkey": "pf_3_2", "posX": 0.75 }] }, "pf_4_2": { "file": "4_2.png", "connections": [{ "pfkey": "pf_5_2", "posX": 0.5 }, { "pfkey": "pf_2_2", "posX": 0.25 }] }, "pf_5_1": { "file": "5_1.png", "connections": [{ "pfkey": "pf_6_1", "posX": 1.0 }, { "pfkey": "pf_4_1", "posX": 0.5 }] }, "left": { "pfkey": "pf_4_1", "posX": 1.0 }, "pf_5_2": { "file": "5_2.png", "connections": [{ "pfkey": "pf_6_1", "posX": 1.0 }, { "pfkey": "pf_4_2", "posX": 0.25 }] }, "pf_6_1": { "file": "6_1.png", "connections": [{ "pfkey": "pf_5_1", "posX": 0.0 }, { "pfkey": "pf_5_2", "posX": 0.75 }] } }
function register(env) { env.addFilter("attr", handler); } function handler(input, name) { return input[name]; } export { handler, register as default };
import _slicedToArray from "@babel/runtime/helpers/slicedToArray"; import React, { useState } from 'react'; import { styled } from '@ctkit/theme'; import get from 'lodash.get'; import { withScriptjs, withGoogleMap, GoogleMap, InfoWindow, Marker } from "react-google-maps"; var MapMarker = function MapMarker(_ref) { var position = _ref.position, onClick = _ref.onClick, open = _ref.open, children = _ref.children, closeInfo = _ref.closeInfo, icon = _ref.icon, options = _ref.options; return React.createElement(Marker, { position: position, onClick: onClick, icon: icon, options: options }, open && React.createElement(InfoWindow, { onCloseClick: closeInfo }, children)); }; var Map = withScriptjs(withGoogleMap(function (_ref2) { var defaultCenter = _ref2.defaultCenter, userMarker = _ref2.userMarker, defaultZoom = _ref2.defaultZoom, markers = _ref2.markers; var _useState = useState(null), _useState2 = _slicedToArray(_useState, 2), activeMarker = _useState2[0], setActiveMarker = _useState2[1]; // TODO: Gérer le cas où Google maps n'est pas chargé ( Exmple: problème de connexion ) var google = window.google; return React.createElement(GoogleMap, { onDragEnd: function onDragEnd() { return null; }, defaultZoom: defaultZoom || 13, defaultCenter: defaultCenter, defaultOptions: { streetViewControl: true, mapTypeControl: false, zoomControl: true, zoomControlOptions: { position: google.maps.ControlPosition.TOP_LEFT } } }, userMarker && React.createElement(MapMarker, { key: userMarker.key || userMarker.id || "user", options: { icon: userMarker.icon }, position: userMarker.position }), (markers || []).map(function (marker) { var isOpen = marker.id === get(activeMarker, 'id'); return React.createElement(MapMarker, { key: marker.id, options: { icon: marker.icon }, position: marker.position, onClick: function onClick() { return setActiveMarker(marker); }, open: isOpen }, isOpen && marker.content()); })); })); export default (function (_ref3) { var settings = _ref3.settings, defaultCenter = _ref3.defaultCenter, defaultZoom = _ref3.defaultZoom, markers = _ref3.markers, userMarker = _ref3.userMarker; var googleMapURL = "https://maps.googleapis.com/maps/api/js?key=".concat(settings.key, "&libraries=").concat(settings.librairies); return React.createElement("div", null, React.createElement(Map, { googleMapURL: googleMapURL, defaultCenter: defaultCenter, defaultZoom: defaultZoom, loadingElement: React.createElement("div", { style: { height: "100%" } }), containerElement: React.createElement("div", { style: { height: "100vh", width: "85%", zIndex: 1, position: 'fixed', top: '70px', right: 0, left: '50%', transform: 'translateX(-50%)' } }), mapElement: React.createElement("div", { style: { height: "100%" } }), markers: markers, userMarker: userMarker })); }); var Sidebar = styled.div.withConfig({ displayName: "Maps1__Sidebar", componentId: "lagss7-0" })(["position:absolute;padding:2em;left:0;top:70px;bottom:0;width:290px;"]); var MapContainer = styled.div.withConfig({ displayName: "Maps1__MapContainer", componentId: "lagss7-1" })(["width:100%;height:100vh:position:fixed;top:70px;right:0;left:290px;box-shadow:rgba(0,0,0,0.06) 0px 0px 12px !important;bottom:0;z-index:10"]);
import React from 'react'; import { HeaderNav, ImgNav } from './style'; const Header = () => ( <HeaderNav className="header"> <ImgNav className="header-img" alt='githubimg' src='/img/github.png' /> GitHub | My repositories </HeaderNav> ) export default Header;
import React, { useMemo, useState } from 'react' import {useCounter} from '../../hooks/useCounter'; import { procesoPesado } from '../helpers/procesoPesado'; export const MemoHook = () => { const [value, increment] = useCounter(100); const [show, setShow] = useState(true); const memoProcesoPesado = useMemo(() => procesoPesado(value), [value]); return ( <> <h3>Counter Memo: { value }</h3> <hr /> <p> {memoProcesoPesado} </p> <button className="btn btn-primary" onClick={() => { increment(); }}>+1</button> <button className="btn btn-outline-primary ml-2" onClick={() => { setShow(!show); }} >Show/Hide {JSON.stringify(show)}</button> </> ) }
/** * @type {import('../structures').AnimeProvider} */ const { AnimeProvider } = require("../structures"); const cheerio = require("cheerio"); const querystring = require("querystring"); /** * @class * @augments AnimeProvider */ class Anime extends AnimeProvider { constructor(base) { super({ name: "", watermarked: true }, base); } async search(query) {} async info(baseData) {} async downloadLink(anime, episode) {} } module.exports = Anime;
import App from './app'; describe('app', () => { it('App to be defined', () => { expect(App).toBeDefined(); }); let app = new App(); it('instance to be defined', () => { expect(app).toBeDefined(); }); });
// Creation du model de Data var openAuthor = function() { Ext.MessageBox.show({ title: 'L\'Auteur', msg: 'Auteur / Concepteur : <a href="http://code.google.com/p/boxio/" target="_blank">'+auteur+'</a>', buttons: Ext.MessageBox.OK, animateTarget: Ext.getCmp('menuAuteur'), fn: function() { }, icon: Ext.MessageBox.INFO }); };
//index.js //获取应用实例 const app = getApp() Page({ data: { userInfo: { }, hasUserInfo: false, canIUse: wx.canIUse('button.open-type.getUserInfo'), parentItem: [ { itemTiele:"实用查询", imgUrls:[ "../../images/menu/card.png", "../../images/menu/ipaddress.png", "../../images/menu/phone.png", "../../images/menu/bank.png", ], texts:[ "身份证", "IP地址", "手机归属地", "银行查询" ] }, { itemTiele:"日常生活", imgUrls:[ "../../images/menu/figure.png", "../../images/menu/print.png", "../../images/menu/pinyin.png", "../../images/menu/jisuan.png", ], texts:[ "身材", "画图", "拼音", "计算", ] }, { itemTiele:"实用工具", imgUrls:[ "../../images/menu/qrcode.png", "../../images/menu/wifi.png", "../../images/menu/time.png", "../../images/menu/game.png", ], texts:[ "二维码", "设备信息", "时钟", "摇骰子", ] } ] }, onLoad: function () { if (app.globalData.userInfo) { this.setData({ userInfo: app.globalData.userInfo, hasUserInfo: true }) } else if (this.data.canIUse){ // 由于 getUserInfo 是网络请求,可能会在 Page.onLoad 之后才返回 // 所以此处加入 callback 以防止这种情况 app.userInfoReadyCallback = res => { this.setData({ userInfo: res.userInfo, hasUserInfo: true }) } } else { // 在没有 open-type=getUserInfo 版本的兼容处理 wx.getUserInfo({ success: res => { app.globalData.userInfo = res.userInfo this.setData({ userInfo: res.userInfo, hasUserInfo: true }) } }) } }, getUserInfo: function(e) { console.log(e) app.globalData.userInfo = e.detail.userInfo this.setData({ userInfo: e.detail.userInfo, hasUserInfo: true }) }, goTools:function(event){ var to = event.target.dataset.sel var to_str = this.isToUrl[to]; console.log(to); wx.navigateTo({ url: '../'+to_str+'/'+to_str }) }, isToUrl : { "0-0" : "card", "0-1" : "ipaddress", "0-2" : "phone", "0-3" : "bank", "1-0" : "figure", "1-1" : "print", "1-2" : "pinyin", "1-3" : "jisuan", "2-0" : "qrcode", "2-1" : "wifi", "2-2" : "time", "2-3" : "shaizi", }, })
var tnt_theme_track_legend = function() { var colors = { "protein coding" : d3.rgb('#A00000'), "pseudogene" : d3.rgb('#666666'), "processed transcript" : d3.rgb('#0033FF'), "ncRNA" : d3.rgb('#8B668B'), "antisense" : d3.rgb('#CBDD8B'), }; var biotype_to_legend = { "protein_coding" : "protein coding", "pseudogene" : "pseudogene", "processed_transcript" : "processed transcript", "miRNA" : "ncRNA", "lincRNA" : "ncRNA", "misc_RNA" : "ncRNA", "snoRNA" : "ncRNA", "snRNA" : "ncRNA", "rRNA" : "ncRNA", "antisense" : "antisense", "sense_intronic" : "antisense" }; var theme = function(gB, div) { gB(div); var gene_track = tnt.track() .height(200) .background_color("#FFFFFF") .display(tnt.track.feature.gene()) .data(tnt.track.data.gene()); gB.add_track(gene_track); var legend_div = d3.select(div) .append("div") .attr("class", "tnt_legend_div"); legend_div .append("text") .text("Gene legend:"); d3.selectAll("tnt_biotype") .data(gene_track.display().layout().elements()); gene_track.data().update().success (function (genes) { genes.map(gene_color); // And we setup/update the legend var biotypes_array = genes.map(function(e){return biotype_to_legend[e.biotype]}); var biotypes_hash = {}; for (var i=0; i<biotypes_array.length; i++) { biotypes_hash[biotypes_array[i]] = 1; } var biotypes = []; for (var p in biotypes_hash) { if (biotypes_hash.hasOwnProperty(p)) { biotypes.push(p); } } var biotype_legend = legend_div.selectAll(".tnt_biotype_legend") .data(biotypes, function(d){return d}); var new_legend = biotype_legend .enter() .append("div") .attr("class", "tnt_biotype_legend") .style("display", "inline"); new_legend .append("div") .style("display", "inline-block") .style("margin", "0px 2px 0px 15px") .style("width", "10px") .style("height", "10px") .style("border", "1px solid #000") .style("background", function(d){return colors[d]}); new_legend .append("text") .text(function(d){return d}); biotype_legend .exit() .remove(); }); var gene_color = function (gene) { gene.color = colors[biotype_to_legend[gene.biotype]]; return; }; gB.start(); }; return theme; };
'use strict'; var assert = require('assert'), crypto = require('crypto'), http = require('http'), os = require('os'), url = require('url'); /** * Push */ function Push(options) { this.apiKey = options.apiKey; this.secretKey = options.secretKey; this.host = options.host || 'api.tuisong.baidu.com'; this.path = options.path || '/rest/3.0/'; this.timeout = options.timeout || 5000; // 5s if (options.hasOwnProperty('agent')) { this.agent = options.agent; } else { var agent = "BCCS_SDK/3.0 ("+os.platform()+","+os.release()+") nodeJS/"+Number(process.version.match(/^v(\d+\.\d+)/)[1]); console.log(agent); //agent.maxSockets = 20; this.agent = agent; } } Push.prototype.request = function(path, bodyParams, callback) { var secretKey = this.secretKey, timeout = this.timeout, host = this.host; bodyParams.apikey = this.apiKey; bodyParams.sign = signKey(url.parse("http://"+host+path), bodyParams, secretKey); var bodyArgsArray = []; for (var i in bodyParams) { bodyArgsArray.push(i + '=' + urlencode(bodyParams[i])); } var bodyString = bodyArgsArray.join('&'); var options = { host: host, path: path, method: 'POST', headers: { 'Content-Length': bodyString.length, 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8' } }; var req = http.request(options, function(res) { var chunks = [], size = 0; res.on('data', function(chunk) { chunks.push(chunk); size += chunk.length; }); res.on('end', function() { var data; try { data = JSON.parse(Buffer.concat(chunks, size)); } catch (e) { e.status = res.statusCode; e.code = 'JSON Parse Error'; return callback(e); } if (res.statusCode !== 200) { var err = new Error(); err.code = data.error_code; err.status = res.statusCode; err.message = data.error_msg; err.request_id = data.request_id; return callback(err); } callback(null, data); }); }); req.on('socket', function(socket) { socket.setTimeout(timeout); socket.on('timeout', function() { req.abort(); }); }); req.on('error', function(e) { callback(e); }); req.end(bodyString); }; Push.prototype.pushSingleDevice = function(options, callback) { options = options || {}; callback = callback || noop; var path = this.path + 'push/single_device'; options.msg = JSON.stringify(options.msg); options.timestamp = getTimestamp(); this.request(path, options, callback); }; Push.prototype.pushAll = function(options, callback) { options = options || {}; callback = callback || noop; var path = this.path + 'push/all'; options.msg = JSON.stringify(options.msg); options.timestamp = getTimestamp(); this.request(path, options, callback); }; Push.prototype.pushTags = function(options, callback) { options = options || {}; callback = callback || noop; var path = this.path + 'push/tags'; options.msg = JSON.stringify(options.msg); options.timestamp = getTimestamp(); this.request(path, options, callback); }; Push.prototype.pushBatchDevice = function(options, callback) { options = options || {}; callback = callback || noop; var path = this.path + 'push/tags'; options.msg = JSON.stringify(options.msg); options.timestamp = getTimestamp(); this.request(path, options, callback); }; Push.prototype.reportQueryMsgStatus = function(options, callback) { options = options || {}; callback = callback || noop; var path = this.path + 'report/query_msg_status'; options.msg = JSON.stringify(options.msg); options.timestamp = getTimestamp(); this.request(path, options, callback); }; Push.prototype.reportQueryTimerRecords = function(options, callback) { options = options || {}; callback = callback || noop; var path = this.path + 'report/query_timer_records'; options.msg = JSON.stringify(options.msg); options.timestamp = getTimestamp(); this.request(path, options, callback); }; Push.prototype.reportQueryTopicRecords = function(options, callback) { options = options || {}; callback = callback || noop; var path = this.path + 'report/query_topic_records'; options.msg = JSON.stringify(options.msg); options.timestamp = getTimestamp(); this.request(path, options, callback); }; Push.prototype.appQueryTags = function(options, callback) { options = options || {}; callback = callback || noop; var path = this.path + 'app/query_tags'; options.msg = JSON.stringify(options.msg); options.timestamp = getTimestamp(); this.request(path, options, callback); }; Push.prototype.appCreateTag = function(options, callback) { options = options || {}; callback = callback || noop; var path = this.path + 'app/create_tag'; options.msg = JSON.stringify(options.msg); options.timestamp = getTimestamp(); this.request(path, options, callback); }; Push.prototype.appDelTag = function(options, callback) { options = options || {}; callback = callback || noop; var path = this.path + 'app/del_tag'; options.msg = JSON.stringify(options.msg); options.timestamp = getTimestamp(); this.request(path, options, callback); }; Push.prototype.tagAddDevices = function(options, callback) { options = options || {}; callback = callback || noop; var path = this.path + 'tag/add_devices'; options.msg = JSON.stringify(options.msg); options.timestamp = getTimestamp(); this.request(path, options, callback); }; Push.prototype.tagDelDevices = function(options, callback) { options = options || {}; callback = callback || noop; var path = this.path + 'tag/del_devices'; options.msg = JSON.stringify(options.msg); options.timestamp = getTimestamp(); this.request(path, options, callback); }; Push.prototype.tagDeviceNum = function(options, callback) { options = options || {}; callback = callback || noop; var path = this.path + 'tag/device_num'; options.msg = JSON.stringify(options.msg); options.timestamp = getTimestamp(); this.request(path, options, callback); }; Push.prototype.timerQueryList = function(options, callback) { options = options || {}; callback = callback || noop; var path = this.path + 'timer/query_list'; options.msg = JSON.stringify(options.msg); options.timestamp = getTimestamp(); this.request(path, options, callback); }; Push.prototype.timerCancel = function(options, callback) { options = options || {}; callback = callback || noop; var path = this.path + 'timer/cancel'; options.msg = JSON.stringify(options.msg); options.timestamp = getTimestamp(); this.request(path, options, callback); }; Push.prototype.topicQueryList = function(options, callback) { options = options || {}; callback = callback || noop; var path = this.path + 'topic/query_list'; options.msg = JSON.stringify(options.msg); options.timestamp = getTimestamp(); this.request(path, options, callback); }; Push.prototype.reportStatisticDevice = function(options, callback) { options = options || {}; callback = callback || noop; var path = this.path + 'report/statistic_device'; options.msg = JSON.stringify(options.msg); options.timestamp = getTimestamp(); this.request(path, options, callback); }; Push.prototype.reportStatisticTopic = function(options, callback) { options = options || {}; callback = callback || noop; var path = this.path + 'report/statistic_topic'; options.msg = JSON.stringify(options.msg); options.timestamp = getTimestamp(); this.request(path, options, callback); }; /** * exports */ exports.createClient = function(options) { assert(typeof options === 'object', 'invalid options'); var client = new Push(options); var wrapper = options.wrapper; if (wrapper) { require('thunkify-or-promisify')(client, wrapper, ['request']); } return client; }; /** * utils */ function noop() {} function urlencode(string) { string += ''; return encodeURIComponent(string) .replace(/!/g, '%21') .replace(/'/g, '%27') .replace(/\(/g, '%28') .replace(/\)/g, '%29') .replace(/\*/g, '%2A') .replace(/%20/g, '+'); } function getTimestamp() { return Math.floor(new Date().getTime() / 1000); } function generateSign(method, url, params, secretKey) { var baseString = method + url; var keys = Object.keys(params).sort(); for (var i = 0; i < keys.length; i++) { baseString += (keys[i] + '=' + params[keys[i]]); } baseString += secretKey; var encodeString = urlencode(baseString); var md5sum = crypto.createHash('md5'); md5sum.update(encodeString); var sign = md5sum.digest('hex'); return sign; } // 兼容php的urlencode function fullEncodeURIComponent (str) { var rv = encodeURIComponent(str).replace(/[!'()*~]/g, function(c) { return '%' + c.charCodeAt(0).toString(16).toUpperCase(); }); return rv.replace(/\%20/g,'+'); } /** * 生成请求签名 * * @param {object} reqParams, 由url.parse解析出来的对象内容,描述请求的位置和url及参数等信息的对象 * @param {object} postParams post表单内容 * @param {string} secretKey 开发者中心的SK * @return {string} 签名值 */ var signKey = function (reqParam, postParmas, secretKey) { var basekey = ""; var method = "POST"; //reqParam.method.toUpperCase(); var baseurl = reqParam.href; var query = reqParam.query || false; var param = {}; var paramStr = ''; if (query) { query = querystring.parse(query); for ( var key in query) { param[key] = query[key]; } } if (postParmas) { for ( var key in postParmas) { param[key] = postParmas[key]; } } var keys = Object.keys(param).sort(); keys.forEach(function (key) { paramStr += key + "=" + param[key]; }) basekey = method + baseurl + paramStr + secretKey; //console.log("basekey : ", basekey); var md5 = crypto.createHash('md5'); basekey = fullEncodeURIComponent(basekey); md5.update(basekey); return md5.digest('hex'); }
//todo will this work in the browser still? var requirejs = require('requirejs'); require.paths.unshift(__dirname + '/deps'); try { var reporter = require('nodeunit').reporters.default; } catch(e) { console.log("Cannot find nodeunit module."); console.log("You can download submodules for this project by doing:"); console.log(""); console.log(" git submodule init"); console.log(" git submodule update"); console.log(""); process.exit(); } process.chdir(__dirname); requirejs(['moduletest'], function(moduletest){ console.log('moduletest: ', moduletest); reporter.run({ 'Sample Module' : moduletest }); }); //reporter.run(['scripttest.js']);
const express = require('express') const app = express() const port = 8080 app.use(express.static('public')) const session = require('express-session') const bodyParser = require('body-parser') app.use(bodyParser.urlencoded({ extended: false })) app.use(session({ secret: 'whatever this is not rly important', cookie: { secure: false, maxAge: 60000 } })) const rand_num = () => { const x = Math.random() console.log(x) return x.toString() .substr(2) .padEnd(13, '0') } const rand_nums = () => { nums = [] for (i = 0; i < 10; ++i) nums.push(rand_num()) return nums } const reseed = () => { for (i = 0; i < 400; ++i) rand_num() } app.post('/submit', (req, res) => { console.log(req.session) if (req.session.attempts) { req.session.attempts++ if (req.session.attempts > 10) { reseed() req.session.nums = rand_nums() req.session.attempts = 1 } } else { req.session.attempts = 1 req.session.nums = rand_nums() } guess = req.body.guess correct = req.session.nums[req.session.attempts - 1] if (guess === correct) { res.json({ correct: true, flag: process.env.FLAG }) } else { res.json({ correct: false, answer: correct, attempts: req.session.attempts }) } }) app.listen(port, () => { console.log(`Example app listening at http://localhost:${port}`) })
HTMLWidgets.widget({ name: 'vl', type: 'output', factory: function(el, width, height) { return { renderValue: function(params) { vegaEmbed(el, params.spec, params.embed_opt); }, resize: function(width, height) {} }; } });
function is_kingkr_obj() { if (typeof local_kingkr_obj == 'undefined') { return false } else { return true } } function judge() { var u = navigator.userAgent; return { ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, } } function share(content, imageurl, targetUrl, title) { var share = "{\"content\":\"" + content + "\",\"imageurl\":\"" + imageurl + "\",\"targetUrl\":\"" + targetUrl + "\",\"title\":\"" + title + "\"}"; javascript: local_kingkr_obj.share(share) } function loginResult(r) {} function payResult(r) {} function openDownLoad() { javascript: local_kingkr_obj.openDownLoadFile() } function login(platform, forwardurl, callbackMethod) { var login = "{\"platform\":\"" + platform + "\",\"forwardurl\":\"" + forwardurl + "\",\"callbackMethod\":\"" + callbackMethod + "\"}"; javascript: local_kingkr_obj.login(login) } function pay(paytype, callbackMethod, partner, seller_id, out_trade_no, subject, bodys, total_fee, modify_url, service, payment_type, charset, it_b_pay, key, sign, sign_type) { payment_type = payment_type ? payment_type: "1"; charset = charset ? charset: 'utf-8'; it_b_pay = it_b_pay ? it_b_pay: "30m"; sign_type = sign_type ? sign_type: "RSA"; var order = "partner=" + partner + "&seller_id=" + seller_id + "&out_trade_no=" + out_trade_no + "&subject=" + subject + "&body=" + bodys + "&total_fee=" + total_fee + "&modify_url=" + modify_url + "&service=" + service + "&payment_type=" + payment_type + "&_input_charset=" + charset + "&it_b_pay=" + it_b_pay + "&key=" + key + "&sign=" + sign + "&sign_type=" + sign_type; var payType = '{"paytype":' + paytype + ',"callbackMethod":' + callbackMethod + '}'; javascript: local_kingkr_obj.payType(order, payType) } function audioPlay(operator) { var data = "{\"operator\":" + operator + "}"; javascript: local_kingkr_obj.audioPlay(data) } function qrcoder() { javascript: local_kingkr_obj.qrcoder() } function cleancache() { type = judge(); if (type.ios == true) { var message = { 'methodName': 'cleancache' }; window.webkit.messageHandlers.local_kingkr_obj.postMessage(message) } else { local_kingkr_obj.cleanCache() } } function qrcode() { javascript: local_kingkr_obj.qrcoderWithCallback() } function qrcodeCallback(result) {} function audioPlay(data) { javascript: local_kingkr_obj.audioPlay(data) }
// simple functional component import React from 'react' const Hello = (props) => { return ( <div class='dummyClass'>{/* jsx method is simple and elegant and readable*/} <h1>Hello CVG a.k.a {props.codeName}</h1> </div> ) // return React.createElement('div', // {id:'hello', class:'dummyClass'}, // key value or html id or html class for css // React.createElement('h1',null,'Hello CVG')) } export default Hello
var searchData= [ ['instance',['Instance',['../class_singleton.html#a54103e8475b2a352ee759d5732307534',1,'Singleton']]] ];
"use strict"; var chickenRowBlock = '<div class="row"></row>', chickenBlock = '<div class="chickenContainer" onclick="chickenContainerSelected(this)"><div class="chicken"><div class="wing"></div><div class="eye"></div><div class="beak_top"></div><div class="crest crest1"></div><div class="crest crest2"></div><div class="crest crest3"></div><div class="wattle"></div></div></div>"', expectedChickenBlock = '<div class="chickenContainer" onclick="chickenContainerSelected(this)"><div class="egg"></div></div>', getChickenURL = "https://du1ejfbfoe.execute-api.us-west-2.amazonaws.com/DEV/organism/", getGenepoolURL= "https://oy0br9jib0.execute-api.us-west-2.amazonaws.com/DEV/", breedGenepoolPath= "/breed", cullGenepoolPath= "/cull", loadedChickens = [], expectedChildren = [], generationCount = 0, lastGenerationBlockId = "", breedLongDelay = 30000, breedShortDelay = 10000, hasBred = false, genepoolID, genepoolObject; $(document).ready(function() { pageLoad(); }); function pageLoad() { attemptToLoadGenepool(); } function attemptToLoadGenepool() { var urlParams = new URLSearchParams(window.location.search); if(urlParams.has('genepoolID')) { genepoolID = urlParams.get('genepoolID'); fetchGenepool(true); } else { console.warn("No genepool present this page won't do anything... Probably add some helper text"); } } function fetchGenepool(shouldLoadChickens) { var request = $.get(getGenepoolURL + genepoolID, function(data) { genepoolFetched(data, shouldLoadChickens); }); request.fail(function() { console.error("Error fetching genepool data: " + genepoolID); }); } function genepoolFetched(genepoolData, shouldLoadChickens) { console.log("Genepool loaded. shouldLoadChickens: " + shouldLoadChickens); genepoolObject = genepoolData; $("#genepoolId").html("ID: " + genepoolObject.id); $("#organismCount").html("Organisms: " + genepoolObject.organismsInGenepool.length); $("#generationCount").html("Generations: " + genepoolObject.genepoolGenerations.length); $("#timesBred").html("Breedings: " + genepoolObject.timesBred); if(shouldLoadChickens) { loadGenerations(); } } function loadGenerations() { for (var i = 0; i < genepoolObject.genepoolGenerations.length; i++) { loadGeneration(genepoolObject.genepoolGenerations[i]); generationCount++; } } function loadGeneration(generation) { var newGenerationID = "generationRow_" + generationCount, newGenerationBlock = $(chickenRowBlock).attr('id', newGenerationID); newGenerationBlock.appendTo("#chickenRowHolder"); for (var i = 0; i < generation.length; i++) { callGetChickenURL(generation[i], newGenerationID); } } function callGetChickenURL(chickenID, newGenerationID) { var request = $.get(getChickenURL + chickenID, function(data) { addCustomChicken(data, newGenerationID); }); request.fail(function() { console.error("Error fetching chicken data: " + chickenID); }); } function addCustomChicken(chickenDNA, newGenerationID) { var newChickenID = "chicken_" + chickenDNA.id, newBlock = $(chickenBlock).attr('id', newChickenID); newBlock.appendTo("#" + newGenerationID); loadCustomChicken(newChickenID, getChickenObject(chickenDNA)); } function loadCustomChicken(chickenBlockId, chicken) { var chickenParent = $("#" + chickenBlockId); $(chickenParent).find(".chicken").css("background-color", chicken.FeatherColor1); $(chickenParent).find(".wing").css("background-color", chicken.FeatherColor2); $(chickenParent).find(".beak_top").css("background-color", chicken.BeakColor); $(chickenParent).find(".crest").css("background-color", chicken.WattleColor); $(chickenParent).find(".wattle").css("background-color", chicken.WattleColor); // $(chickenParent).find(".chickenId").html(chicken.id); // $(chickenParent).find(".chickenName").html(chicken.name); loadedChickens.push(chicken); } // ~~~~~~~~~~~~~~~~~~ BREEDING ~~~~~~~~~~~~~~~~~~ function breedGenepool() { if(genepoolID === undefined) { console.warn("No GenepoolID present. Can't breed..."); return; } disableAllButtons(); var breedGenepoolURL = getGenepoolURL + genepoolID + breedGenepoolPath, request = $.post(breedGenepoolURL, function(data) { genepoolBredSuccessfull(data); fetchGenepool(false); }); request.fail(function(data) { console.error("Error breeding genepool: " + data); enableAllButtons(); }); } function breedingFinished() { enableAllButtons(); generationCount++; } function genepoolBredSuccessfull(responseMessage) { addExpectedChildren(JSON.parse(responseMessage.newChildrenIds)); checkIfBreedingFinished(); kickOffExpectedChildrenRequests(); //TODO Update Genepool Stats } function checkIfBreedingFinished() { //console.log("Checking if breeding finished..."); //console.log(expectedChildren); if(expectedChildren.length <= 0) { breedingFinished(); } } function kickOffExpectedChildrenRequests() { for(var i = 0; i < expectedChildren.length; i++) { kickOffExpectedChildRequest(expectedChildren[i]); } hasBred = true; } function kickOffExpectedChildRequest(chickenId) { var currentDelay = (hasBred) ? breedShortDelay : breedLongDelay; //console.log("Sending request for chickenID: " + chickenId + " in " + currentDelay + "ms."); setTimeout(function() { attemptToGetExpectedChicken(chickenId); }, currentDelay); } function attemptToGetExpectedChicken(chickenID) { //console.log("Sending request for chickenID: " + chickenID); var request = $.get(getChickenURL + chickenID, function(data) { replaceExpectedChild(data, chickenID); expectedChildren.remove(chickenID); checkIfBreedingFinished(); }); request.fail(function() { console.log();("Error fetching expected chicken, trying again. chickenID: " + chickenID); kickOffExpectedChildRequest(chickenID); }); } function replaceExpectedChild(chickenDNA, chickenID) { var chickenBlockId = "chicken_" + chickenID; $("#chicken_" + chickenID).remove(); //console.log("Should have removed egg for: " + chickenBlockId); addCustomChicken(chickenDNA, "generationRow_" + generationCount); } function addExpectedChildren(newChildIds) { var newGenerationID = "generationRow_" + generationCount, newGenerationBlock = $(chickenRowBlock).attr('id', newGenerationID); newGenerationBlock.appendTo("#chickenRowHolder"); for(var i = 0; i < newChildIds.length; i++){ var newChickenID = "chicken_" + newChildIds[i], newChickenBlock = $(expectedChickenBlock).attr('id', newChickenID); newChickenBlock.appendTo(newGenerationBlock); expectedChildren.push(newChildIds[i]); } } Array.prototype.remove = function(x) { var i; for(i in this){ if(this[i].toString() == x.toString()){ this.splice(i,1) } } } // ~~~~~~~~~~~~~~~~~~ CULLING ~~~~~~~~~~~~~~~~~~ function cullGenepool() { if(genepoolID === undefined) { console.warn("No GenepoolID present. Can't cull..."); return; } disableAllButtons(); var cullGenepoolURL = getGenepoolURL + genepoolID + cullGenepoolPath, request = $.post(cullGenepoolURL, {}, function(data) { genepoolCullSuccessful(data); fetchGenepool(false); }, "text"); request.fail(function(data) { console.error("Error culling genepool ->"); console.log(data); enableAllButtons(); }); } function cullingFinished() { enableAllButtons(); } function genepoolCullSuccessful(responseMessage) { //console.log(responseMessage); removeChickensFromLoadedChickenArray(genepoolObject.genepoolGenerations[0]); $("#chickenRowHolder").children(':first-child').remove(); cullingFinished(); //TODO Update Genepool Stats } function removeChickensFromLoadedChickenArray(culledChickenArray) { var chickensToRemove = []; for(var i = 0; i < culledChickenArray.length; i++) { for(var j = 0; j < loadedChickens.length; j++) { if(loadedChickens[j].id === culledChickenArray[i]) { chickensToRemove.push(loadedChickens[j]); } } } loadedChickens = loadedChickens.filter(function(el) { return chickensToRemove.indexOf(el) < 0; }); }
import styled, { css } from "styled-components"; import tokens from "@paprika/tokens"; import { fontSize, lineHeight } from "@paprika/stylers/lib/helpers"; import { Link } from "./components/Link/Link.styles"; export const Nav = styled.nav` color: ${({ isDark }) => (isDark ? tokens.color.white : tokens.textColor.subtle)}; font-weight: bold; ${fontSize(-2)} ${lineHeight()} ${Link} { ${fontSize(-2)} } `; export const List = styled.ol` display: inline; list-style-type: none; margin: 0; padding: 0; ${({ isCollapsed }) => isCollapsed && css` li[data-pka-anchor="breadcrumbs.list-item"] { display: none; &:first-child, &:nth-last-child(1), &:nth-last-child(2) { display: inline; } } `} `;
angular .module('altairApp') .controller("auditYearCtrl",['$scope','user_data', function ($scope,user_data) { $scope.domain="com.netgloo.models.LutAuditYear."; $scope.puserGrid = { dataSource: { transport: { read: { url: "/audit/au/list/LutAuditYear", contentType:"application/json; charset=UTF-8", type:"POST" }, update: { url: "/audit/au/update/"+$scope.domain+"", contentType:"application/json; charset=UTF-8", type:"POST" }, destroy: { url: "/audit/au/delete/"+$scope.domain+"", contentType:"application/json; charset=UTF-8", type:"POST", complete: function(e) { $("#notificationDestroy").trigger('click'); } }, create: { url: "/audit/au/create/"+$scope.domain+"", contentType:"application/json; charset=UTF-8", type:"POST", complete: function(e) { $("#notificationSuccess").trigger('click'); $(".k-grid").data("kendoGrid").dataSource.read(); } }, parameterMap: function(options) { return JSON.stringify(options); } }, schema: { data:"data", total:"total", model: { id: "id", fields: { id: { type: "number", editable: false,nullable: false}, audityear: { type: "number", validation: { required: true} }, isactive: { type: "boolean" } } } }, pageSize: 8, serverPaging: true, serverSorting: true, serverFiltering: true }, toolbar: ["create"], filterable: true, sortable: true, resizable: true, columnMenu:true, pageable: { refresh: true, pageSizes: true, buttonCount: 5 }, columns: [ { field:"audityear", title: "Огноо"}, { field:"isactive", title: "Идэвхитэй эсэх"}, { command: ["edit", "destroy"], title: "&nbsp;", width: "250px" }], editable: "popup" }; } ]);
window.onload=function(){ $(function(){ //头部的nav显示 $(".a_parent").hover(function(){ $(".jt").css("transform","rotateZ(180deg)") $(".card").slideDown(30) },function(){ $(".jt").css("transform","rotateZ(0)") $(".card").slideUp(30) }) $(".customer_father").hover(function(){ $(".jt2").css("transform","rotateZ(180deg)") $(".customer_card").show(100) },function(){ $(".jt2").css("transform","rotateZ(0)") $(".customer_card").hide(100) }); //注册登录 $("#login").click(function(){ $(".masking").fadeIn(300); $(".yx-register").hide(100) }) //点击按钮关闭登录 $("#shut_login").click(function(){ $(".masking").fadeOut(200) }) //监听点击是否使用验证码登录 $("#yzm_login").click(function(){ $(".drag").toggle(200); $("#yx_login").height(407) }); //监听颜色选择 $(".yx-clearfix ul li").eq(0).hover(function(){ $("#black").show() },function(){ $("#black").hide() }); $(".yx-clearfix ul li").eq(1).hover(function(){ $("#nccolor").show() },function(){ $("#nccolor").hide() }) //监听尺码的选择 $(".yx_size ul").on("click","li",function(){//事件委托 $(this).css({ border:"2px solid #b4a078", boxSizing: "border-box" }).siblings().css("border","1px solid #ccc"); }) //监听颜色的选择 $(".yx-clearfix ul").on("click","li",function(){//事件委托 //$(this).index() == 0 黑色的鞋 1 黄色的鞋 if($(this).index() == 0){ $(".max_img img").attr("src","childImg/bigImg1.jpg"); $(".da_img img").attr("src","childImg/maxImg1.jpg"); }else{ $(".max_img img").attr("src","images/tab_min.png"); $(".da_img img").attr("src","images/tab_max.png"); } $(this).css({ border:"2px solid #b4a078", boxSizing: "border-box" }).siblings().css("border","1px solid #ccc"); }) //监听数量的加减 var numINdex=0; $(".btn-minus").click(function(){ if(numINdex == 0){ numINdex=0; }else{ numINdex--; } $(".btn-txt").val(numINdex) }) $(".btn-plus").click(function(){ numINdex++; $(".btn-txt").val(numINdex) }); //实现吸顶效果 $(Window).scroll(function(){ var stop = $("html,body").scrollTop(); if( stop >=150 ){ $(".warpper_fixed").slideDown(200) }else{ $(".warpper_fixed").slideUp(200) } }); //吸顶部分 $(".icon-yf").hover(function(){ $(".hide_reg").slideDown(30) },function(){ $(".hide_reg").slideUp(30) }) $(".icon-gwc").hover(function(){ $(".get_gwc").slideDown(30) },function(){ $(".get_gwc").slideUp(30) }); }) }
//轨迹回放插件 (function (app) { var currentCar; // 当前车辆 var map, lushu, lushuline, lushuicon, lushudatas; var parentView; // 当前模式窗口 var tracktime_buffer, lushu_points; //根据经纬极值计算绽放级别。 var getZoom = function (maxLng, minLng, maxLat, minLat) { var zoom = ["50", "100", "200", "500", "1000", "2000", "5000", "10000", "20000", "25000", "50000", "100000", "200000", "500000", "1000000", "2000000"]//级别18到3。 var pointA = new BMap.Point(maxLng, maxLat); // 创建点坐标A var pointB = new BMap.Point(minLng, minLat); // 创建点坐标B var distance = map.getDistance(pointA, pointB).toFixed(1); //获取两点距离,保留小数点后两位 for (var i = 0, zoomLen = zoom.length; i < zoomLen; i++) { if (zoom[i] - distance > 0) { return 18 - i + 5;//之所以会多3,是因为地图范围常常是比例尺距离的10倍以上。所以级别会增加3。 } }; } //根据原始数据计算中心坐标和缩放级别,并为地图设置中心坐标和缩放级别。 var setZoom = function (points) { if (points.length > 0) { var maxLng = points[0].lng; var minLng = points[0].lng; var maxLat = points[0].lat; var minLat = points[0].lat; var res; for (var i = points.length - 1; i >= 0; i--) { res = points[i]; if (!res.lng || !res.lat) { continue; } if (res.lng > maxLng) maxLng = res.lng; if (res.lng < minLng) minLng = res.lng; if (res.lat > maxLat) maxLat = res.lat; if (res.lat < minLat) minLat = res.lat; }; var cenLng = (parseFloat(maxLng) + parseFloat(minLng)) / 2; var cenLat = (parseFloat(maxLat) + parseFloat(minLat)) / 2; var zoom = getZoom(maxLng, minLng, maxLat, minLat); map.centerAndZoom(new BMap.Point(cenLng, cenLat), zoom); } else { //没有坐标,显示全中国 map.centerAndZoom(new BMap.Point(103.388611, 35.563611), 5); } } var draw = function (points) { clearLushu(); setZoom(points); lushuline = new BMap.Polyline(points);//创建折线 map.addOverlay(lushuline); lushuicon = new BMap.Icon("assets/img/car_normal/90.png", new BMap.Size(58, 61)); lushu = new BMapLib.LuShu(map, points, { defaultContent: "", autoView: true, icon: lushuicon, speed: 5000, enableRotation: true, //是否设置marker随着道路的走向进行旋转 landmarkPois: [] }); startLushu(); } var startLushu = function () { if (lushu) { lushu.start(); } } var stopLushu = function () { if (lushu) { lushu.stop(); } } var pauseLushu = function () { if (lushu) { lushu.pause(); } } var clearLushu = function () { if (lushuline) { map.removeOverlay(lushuline); } if (lushuicon) { map.removeOverlay(lushuicon); } if (lushu) { lushu.stop(); } lushu = null; lushuline = null; lushuicon = null; lushudatas = null; } var reset_click = function () { var date = moment().subtract("days", 1).format("YYYY-MM-DD HH:mm"); $("#starttime", parentView).val(App.util.monthFirst()); $("#stoptime", parentView).val(App.util.monthLast()); }; var trackplay_callback = function (json) { if (json.data && json.data.pList && json.data.pList.length > 0) { $.each(json.data.pList, function (index, item) { var bdpoint = App.util.gcj02tobd(item.lon, item.lat); lushu_points.push(new BMap.Point(parseFloat(bdpoint.Lon), parseFloat(bdpoint.Lat))); // var html = "里程:" + item.mileage + "<br />" // + "时间:" + item.gTime + "<br />" // + "速度:" + item.speed; // if (item.rType == "p") { // html += "停车时长:" + App.base64.decode(item.parkingTime) + "<br />"; // } lushucontent = App.base64.decode(item.tName); // lushudatas.push({ // "lng": parseFloat(bdpoint.Lon) // , "lat": parseFloat(bdpoint.Lat) // , "html": html // , "pauseTime": 2 // }); }); } doTrackPlay(); } var doTrackPlay = function () { if (tracktime_buffer.length == 0) { if (lushu_points.length > 1) { draw(lushu_points); } else { } return; } var item = tracktime_buffer.shift(); var options = { "startUtc": item.start_time, "endUtc": item.end_time, "sid": currentCar.sid, "timeInterval": 30 } App.ajax(bus_cfgs.monitor.tarckPlayapi, options, trackplay_callback); } var tracktime_callback = function (json) { tracktime_buffer = new Array(); if (json.data && json.data.pList && json.data.pList.length > 0) { lushu_points = new Array(); $.each(json.data.pList, function (index, item) { tracktime_buffer.push(item); }); doTrackPlay(); } } var search_click = function () { //App.logger.debug( App.util.jsonToString( currentCar ) ); var options = {}; lushudatas = []; options.startTime = $("#starttime", parentView).val(); options.endTime = $("#stoptime", parentView).val(); // options.timeInterval = 30; options.sim = currentCar.sim; App.ajax(bus_cfgs.monitor.getTrackTimeapi, options, tracktime_callback); }; var _initialize = function (parent) { parentView = $("#" + parent); setTimeout(function () {//添加延时加载。解决问题 // 百度地图API功能 map = new BMap.Map("allmap"); // 创建Map实例 map.centerAndZoom(new BMap.Point(118.796458, 32.0649), 11); // 初始化地图,设置中心点坐标和地图级别 map.addControl(new BMap.MapTypeControl()); //添加地图类型控件 // map.setCurrentCity("北京"); // 设置地图显示的城市 此项是必须设置的 map.enableScrollWheelZoom(false); //开启鼠标滚轮缩放 }, 300); $(".modal-title", parentView).append(" - " + currentCar.text); var contentHeight = $(".modal-body", parentView).height(); var mapHeight = contentHeight - $(".modal-body .row", parentView).eq(0).height(); $("#allmap").height(mapHeight); // 重置按钮 $("#btn_reset", parentView).on("click", function () { reset_click(); }); // 查询按钮 $("#btn_search", parentView).on("click", function () { search_click(); }); $("#btn_start", parentView).on("click", function () { startLushu(); }); $("#btn_pause", parentView).on("click", function () { pauseLushu(); }); $("#btn_stop", parentView).on("click", function () { stopLushu(); }); reset_click(); } app.plugins.monitors.routereplay = { // 初始化轨迹回放功能 "init": function (parent) { _initialize(parent); } // 打开轨迹回放界面 , "show": function (carobject) { currentCar = carobject; App.dialog.load({ "url": "views/monitor/routereplay.html", "callback": _initialize }); } }; })(App);
sum(2,3); function sum(a,b=5) { let result = a + b; return console.log(result); } let result = function(a,b) {return a+b;} let result2 = result; let x = (a,b) => a+b;
import NotFoundView from "../components/404.vue"; import login from "../pages/sys/login.vue"; import chatting from "../pages/sys/chat.vue"; import compose from "../pages/sys/compose.vue"; import sent from "../pages/sys/sent.vue"; import inbox from "../pages/sys/inbox.vue"; import app from "../app.vue"; import menuList from "../pages/sys/menu.vue"; import message from "../pages/sys/message.vue"; import role from "../pages/sys/role.vue"; import resource from "../pages/sys/resource.vue"; import settings from "../pages/sys/settings.vue"; import sysUser from "../pages/sys/user.vue"; import userAdd from "../pages/sys/useradd.vue"; import resetPwd from "../pages/sys/resetpwd.vue"; import word from "../pages/sys/word.vue"; /**一窗*/ import packagelog from "../pages/approval/packagelog.vue"; import packageprocess from "../pages/approval/packageprocess"; import matterlog from "../pages/approval/matterlog.vue"; import process from "../pages/approval/process.vue"; import desk from "../pages/approval/desk.vue"; import home from "../pages/approval/home.vue"; // Routes const routes = [ {path: '/login', component: login, name: 'login'}, { path: '/404', component: NotFoundView, name: '404' }, { path: '', component: app, name: 'app', meta: {requiresAuth: true}, children: [ /*一窗*/ {path: '/', component: home, name: 'home'}, {path: '/matterlog', component: matterlog, name: 'matterlog'}, {path: '/packagelog', component: packagelog, name: 'packagelog'}, {path: '/packageprocess', component: packageprocess, name: 'packageprocess'}, {path: '/process', component: process, name: 'process'}, {path: '/desk/:activename?', component: desk, name: 'desk'}, {path: '/resetPwd', component: resetPwd}, {path: '/settings', component: settings}, {path: '/sys/message', component: message}, { path: '/sys/chatting', component: chatting, children: [ {path: '/sys/chatting/sent', component: sent}, {path: '/sys/chatting/compose', component: compose}, {path: '/sys/chatting/inbox', component: inbox}, ] }, {path: '/sys/menuList', component: menuList}, {path: '/sys/roleList', component: role}, {path: '/sys/word', component: word}, {path: '/sys/userList', component: sysUser}, {path: '/sys/userAdd', component: userAdd}, {path: '/sys/resource', component: resource} ] }, {path: '*', redirect: '/404'} ] export default routes
define('routes_api', [], function() { return { 'collections': '/api/v1/rocketfuel/collections/', 'collection': '/api/v1/rocketfuel/collections/{0}/', 'add_app': '/api/v1/rocketfuel/collections/{0}/add_app', 'login': '/api/v1/account/login/' }; });
"use strict"; /** * @class test renderer module */ DIC.define('EquivalentJS.test.RendererTest', new function () { /** * @description test has assigned module class type by manager * @memberOf EquivalentJS.test.RendererTest * @param {EquivalentJS.test.Unit.assert} assert * @param {EquivalentJS.Renderer} moduleClass */ this.testHasAssignedTypeByManager = function (assert, moduleClass) { assert.ok( 'EquivalentJS.Renderer' === moduleClass.type, 'is EquivalentJS.Renderer' ); }; /** * @description test is {@link EquivalentJS.Renderer.display} available * @memberOf EquivalentJS.test.RendererTest * @param {EquivalentJS.test.Unit.assert} assert * @param {EquivalentJS.Renderer} moduleClass */ this.testIsDisplayAvailable = function (assert, moduleClass) { moduleClass.construct(); assert.ok( moduleClass.display.hasClass('display'), 'display target viewport is available' ); }; });
export async function handleResponse(response) { if (response.ok) return response.json(); if (response.status === 400) { // Handle validation fail on server side; returns a text instead of JSON, handle below const error = await response.text(); throw new Error(error); } throw new Error("Uh oh, something went wrong on the network."); } // Handle with toast/actual error redirecting/handling on enterprise app export function handleError(error) { // eslint-disable-next-line no-console throw new Error("Here's what went wrong: " + error); }
class Vector { constructor(x=0, y=0) { this.x = x; this.y = y; } add(vector) { this.x += vector.x; this.y += vector.y; } addImm(vector) { return new Vector(this.x + vector.x, this.y + vector.y); } scale(s) { this.x *= s; this.y *= s; } scaleImm(s) { return new Vector(this.x * s, this.y*s); } } export default class Physics { constructor() { this.entities = []; this.G = 9.80665; this.PI = 3.14; this.width = 100; this.height = 100; this.blackHole = new Vector(this.width/2, this.height/2); } setDims(w, h) { this.width = w; this.height = h; this.blackHole = new Vector(this.width/2, this.height/2); } move(circle, xp, yp) { } addCircle(x, y, r) { this.entities.push({x, y, r, accel: new Vector(), vel: new Vector()}); } getMass(circle) { return 2*this.PI*circle.r*circle.r; } getDistance(c1, c2) { return Math.sqrt(Math.pow(c1.x-c2.x, 2) + Math.pow(c1.y-c2.y, 2)); } scaleForce(f) { return f * 0.5; } gameLoop(time) { this.entities.forEach(circle => { // Gravity. // // Mass if just area of the circle. // let mass = this.getMass(circle); // // Apply gravity to other circles. // this.entities.forEach(otherCircle => { // // Calculate effect of gravity. // let mass2 = this.getMass(otherCircle); // let dx = circle.x - otherCircle.x; // let dy = circle.y - otherCircle.y; // let distance = Math.pow(this.getDistance(circle, otherCircle), 2); // let force = mass*mass2*this.G/distance; // let accel = force/mass2; // let angle = Math.atan2(dy, dx); // let newX = Math.cos(angle)*distance; // let newY = Math.sin(angle)*distance; // otherCircle.accel.add(new Vector(newX, newY)); // }); // Calculate effect of gravity. let mass2 = this.getMass(circle); let dx = this.blackHole.x - circle.x; let dy = this.blackHole.y - circle.y; let distance = Math.pow(dx*dx + dy*dy, 2); let force = mass*100*this.G/distance; let accel = force/mass2; let angle = Math.atan2(dy, dx); let newX = Math.cos(angle)*distance; let newY = Math.sin(angle)*distance; circle.accel.add(new Vector(newX, newY)); // Friction. circle.accel.scale(.5); // Apply accel to vel. circle.vel.add(circle.accel.scaleImm(time)); // Apply vel to position. circle.x += circle.vel.x * time; circle.y += circle.vel.y * time; // Adjust if hitting object. }); } }
import React from 'react'; import ReactDOM from 'react-dom'; import unsplash from './api/unsplash'; import Comment from './components/anotherComment'; import Images from './components/imageList'; /* const App = () => { return (<p>Hello this is just a test</p>); } */ class App extends React.Component { constructor(props) { super(props); this.state = { term:"Hello", images: [] }; } onSearchSubmit = async (term) => { const res = await unsplash.get('search/photos',{ params: {query: term}, }); console.log(this); this.setState({images: res.data.results}); } render() { return ( <div className="ui comments"> <h3 className="ui dividing header"></h3> <div className="comment"> <a className="avatar"><img src="https://semantic-ui.com/images/avatar/small/elliot.jpg" /></a> <div className="content"> <a className="author">Alan Fu</a> <div className="metadata"> <span className="date">Yesterday at 12:30AM</span> </div> <div className="text"> <p>This has been very useful for my research. Thanks as well!</p> </div> <div className="actions"> <a className="reply">Reply</a> <Comment author= "alonso hernandez" imageAmount={this.state.images.length} onSubmit={this.onSearchSubmit}/> <Images listImg = {this.state.images}/> </div> </div> </div> </div> ); } } ReactDOM.render (<App />, document.getElementById('root')); export default App;
//http://access.video.qq.com/pc_client/GetUserVidListPage?vappid=50662744&vsecret=64b037e091deae75d3840dbc5d565c58abe9ea733743bbaf&callback=jQuery191009402303422004277_1557815763578&iSortType=0&page_index=1&hasMore=true&stUserId=769563763&page_size=20&_=1557815763582 const fs = require('fs'); const xlsx = require('node-xlsx'); const axios = require('axios'); const toDate = (year, month, date) => new Date(year, month + 1, date); const BaseUrl = 'http://access.video.qq.com/pc_client/GetUserVidListPage?vappid=50662744&vsecret=64b037e091deae75d3840dbc5d565c58abe9ea733743bbaf&iSortType=0&hasMore=true&page_size=20&_=1557817147319&callback=callback'; const RequestList = [{ name: '梨视频', stUserId: '769563763', pageNum: 1, list: [] }, { name: '新京报', stUserId: '1067100003', // '2955448967', pageNum: 1, list: [] }, { name: '青蜂侠', stUserId: '2209767239', pageNum: 1, list: [] }, ] // 生成excel const writeXlsx = (name, data) => { data.unshift(['标题', '阅读量', '时间']); const buffer = xlsx.build([{ name: 'Tencent Video Reading', data }]); fs.writeFileSync(`./harvest/tencent/${name}-阅读量数据统计.xlsx`, buffer, { 'flag': 'w' }); }; // 发起请求 const request = async (options) => { const url = `${BaseUrl}&stUserId=${options.stUserId}&page_index=${options.pageNum}`; await axios.get(url).then((res)=>{ function callback(data) { const videoList = data.data.vecVidInfo; let lastDate; videoList.forEach(({ mapKeyValue: { title, view_all_count, create_time } }) => { console.log(title, view_all_count, create_time) title = title.replace(/,/g, ",").replace(/:/g, ":") view_all_count = Number(view_all_count); if (!create_time) { console.log('数据有错误,请重试!'); return; } const d = new Date(Date.parse(create_time.replace(/-/g, "/"))); const year = d.getFullYear(); const month = d.getMonth() + 1; const date = d.getDate(); const now = toDate(year, month, date); if (now >= begin && now <= end) { options.list.push([title, view_all_count, create_time]); } lastDate = now; }); if (lastDate < begin) { writeXlsx(options.name, options.list); console.log(`${options.name} Complete!`) } else { options.pageNum++; console.log(`${options.name}:第${options.pageNum}页 Continue...`) request(options); } } eval(res.data); }) } RequestList.forEach((options)=>{ request(options); }); const begin = toDate(2020, 2, 10); const end = toDate(2020, 2, 16);
import styled from "styled-components"; import MovieCover from "./MovieCover"; const Wrapper = styled.section` padding: .5rem 0.25rem; background-color: hsla(0, 0%, 6%, 1); `; const MoviesWrapper = styled.div` display: flex; flex-wrap: wrap; justify-content: center; padding: .5rem 0; @media (min-width: 768px) { justify-content: space-between; } `; const SectionTitle = styled.h3` font-size: 1.4rem; color: hsla(47, 92%, 51%, 1); `; const MovieSection = ({ sectionTitle, movies }) => { console.log("peliculas de ", sectionTitle, "peliculas", movies); return ( <Wrapper> <SectionTitle>{sectionTitle}</SectionTitle> <MoviesWrapper> {movies.map((movie) => ( <MovieCover key={movie.id} movie={movie} /> ))} </MoviesWrapper> </Wrapper> ); }; export default MovieSection;
$(function(){ load_list(); }); function load_list(){ $.post( "/Shop/problem/find.do", {}, function(data){ var list = data.RESULT_CONTENT.problemList; $(list).each(function(){ var conText = '<a href="javascript:void(0);" class="list-group-item list-border">'+this.problem_title+'</a>'; $(".list-group").append(conText); $(".list-group a:last").data("datalist",this); $(".list-group a:last").click(function(){ var datalist = $(this).data("datalist"); $("#article_title").text(datalist.problem_title); $("#article_body").text(datalist.problem_body); }); }); } ); // $a1 = $('<a href="javascript:void(0);" class="list-group-item list-border">运费问题</a>'); // $a1.click(function(){ // $("#article_title").text("运费问题"); // $("#article_body").text("统一收取配送费5元"); // }); // $(".list-group").append($a1); // // // $a2 = $('<a href="javascript:void(0);" class="list-group-item list-border">维修问题</a>'); // $a2.click(function(){ // $("#article_title").text("维修问题"); // $("#article_body").text("凭购物小票,可维修保修商品"); // }); // $(".list-group").append($a2); // $a3 = $('<a href="javascript:void(0);" class="list-group-item list-border">发票问题</a>'); // $a3.click(function(){ // $("#article_title").text("发票问题"); // $("#article_body").text("凭购物小票,可在30天内到前台换取发票"); // }); // $(".list-group").append($a3); }
/* * Create a list that holds all of your cards */ var list=["fa fa-diamond","fa fa-paper-plane-o","fa fa-anchor","fa fa-bolt","fa fa-cube","fa fa-anchor","fa fa-leaf","fa fa-bicycle","fa fa-diamond","fa fa-bomb","fa fa-leaf","fa fa-bomb", "fa fa-bolt", "fa fa-bicycle", "fa fa-paper-plane-o", "fa fa-cube"]; var cardsShuffle=[]; var Display=[]; var cardsFlipped=0; var cardsMoved=0; var credits=0; var hours=0; var min=0; var sec=0; /* * Display the cards on the page * - shuffle the list of cards using the provided "shuffle" method below * - loop through each card and create its HTML * - add each card's HTML to the page */ document.onload =startclock(); // Shuffle function from http://stackoverflow.com/a/2450976 function shuffle(elements) { var currentIndex = elements.length, temporaryValue, randomIndex; while (currentIndex !== 0) { randomIndex = Math.floor(Math.random() * currentIndex); currentIndex -= 1; temporaryValue = elements[currentIndex]; elements[currentIndex] = elements[randomIndex]; elements[randomIndex] = temporaryValue; } return elements; } // here we take two classes deck and card and these have function activity which means by on clicking the car will open $('.deck ,.card').on('click','.card',function(activity) { // conditional statements are used where we take only two matching cards so that length should be less than 2 if($(this).attr('class')==='card' && Display.length<2) { // here we want to push the card to display if(Display.length===0) { // $(this).toggleClass('open'); $(this).addClass('open show card'); Display.push($(this).children().attr('class')); } else if(Display.length===1) // in this if { // $(this).toggleClass('open'); $(this).addClass('open show card'); Display.push($(this).children().attr('class')); if(Display[0]===Display[1]) { $('.card').filter($('.open')).toggleClass('open match'); cardsFlipped=cardsFlipped + 2; cardsMoved=cardsMoved+1; $('.moves').text(cardsMoved); Display=[];// in display we take an empty array credits=credits+1; $('.score').text(credits); min=0; $('mins').text(min); sec=sec+0; $('secs').text(sec); } else { // flip back function that function flipBack () { $('.card').filter($('.open')).attr('class',"card"); Display = []; cardsMoved=cardsMoved+1; $('.moves').text(cardsMoved); } setTimeout(flipBack, 600); } } if(credits===8) clearInterval(interval); // in this if it is equal to 8 then an alert will come { alert("YOU WON THE GAME"); } // this conditions are used for stars if(cardsMoved==1) { sec=0; min=0; hours=0; startclock(); } // here conditional statements are used .and if the moves are greater than 15 the starts will decrease if (cardsMoved > 16 && cardsMoved < 28) { var star3 =$('.stars').find('li').eq(2); star3.css('color','red'); } if (cardsMoved > 15) { var star2 =$('.stars').find('li').eq(2); star2.css('color','red'); } } }); // this is used for setting clock var clock=document.querySelector(".clock"); clock.innerHTML = "0 mins 0 secs"; clearInterval(interval); var sec = 0, min = 0; hour = 0; var clock = document.querySelector(".clock"); var interval; function startclock(){ interval = setInterval(function(){ clock.innerHTML = min+"mins" + sec+"secs"; sec++; if(sec == 60){ min++; sec=0; } if(min == 60){ hours++; min = 0; } },1000); } if(cardsMoved == 1){ startclock(); } // this functions are used for onclick it will restart the game and the cards will also shuffel $('.restart').on('click',function() { var cardsShuffle=shuffle(list); $(".card i").each(function(index){ console.log(cardsShuffle[index]); console.log($(this).attr('class',cardsShuffle[index])); $(this).attr('class',cardsShuffle[index]); $('.deck li').attr("class","card"); cardsMoved=0; $('.moves').text(cardsMoved); credits=0; $('.score').text(credits); min=0; $('mins').text(min); sec=0; $('secs').text(sec); }) }); /* * set up the event listener for a card. If a card is clicked: * - display the card's symbol (put this functionality in another function that you call from this one) * - add the card to a *list* of "open" cards (put this functionality in another function that you call from this one) * - if the list already has another card, check to see if the two cards match * + if the cards do match, lock the cards in the open position (put this functionality in another function that you call from this one) * + if the cards do not match, remove the cards from the list and hide the card's symbol (put this functionality in another function that you call from this one) * + increment the move counter and display it on the page (put this functionality in another function that you call from this one) * + if all cards have matched, display a message with the final score (put this functionality in another function that you call from this one) */
'use strict' const path = require('path') const webpack = require('webpack') const webpackMerge = require('webpack-merge') const AssetsPlugin = require('assets-webpack-plugin') const ExtractTextPlugin = require('extract-text-webpack-plugin') const UglifyJSPlugin = require('uglifyjs-webpack-plugin') // const HtmlWebpackPlugin = require('html-webpack-plugin') const buildConfig = require('./webpack.common') module.exports = webpackMerge(buildConfig, { bail: true, output: { path: path.resolve(__dirname, '../build'), publicPath: '/build/', filename: '[chunkhash].js', pathinfo: false }, plugins: [ new webpack.DefinePlugin({ '__DEBUG__': false, 'process.env': { NODE_ENV: '"production"' } }), new ExtractTextPlugin('[chunkhash].css'), new UglifyJSPlugin({ parallel: true, extractComments: false }), // new HtmlWebpackPlugin({ // template: 'src/index.ejs' // }), new AssetsPlugin({ filename: 'assets.json', path: path.resolve(__dirname, '../build'), prettyPrint: true }) ] })
import React from 'react'; import { createDrawerNavigator } from '@react-navigation/drawer'; import { FAQStackNavigation, HomeStackNavigation, ForumStackNavigation, CoursesStackNavigation, TipStackNavigation, EventStackNavigation } from './StackNavigation'; import { DrawerContent } from './DrawerContent'; import MarketScreen from '../containers/market/MarketScreen'; import HomeScreen from '../containers/HomeScreen'; export default function DrawerNavigation() { const Drawer = createDrawerNavigator(); return ( <Drawer.Navigator initialRouteName="Home" drawerContent={props => <DrawerContent {...props} />}> <Drawer.Screen name="Home" component={HomeStackNavigation} /> <Drawer.Screen name="FAQ" component={FAQStackNavigation} /> <Drawer.Screen name="Market" component={MarketScreen} /> <Drawer.Screen name="Forum" component={ForumStackNavigation} /> <Drawer.Screen name="Courses" component={CoursesStackNavigation} /> <Drawer.Screen name="Tips" component={TipStackNavigation} /> <Drawer.Screen name="Events" component={EventStackNavigation} /> </Drawer.Navigator> ); }
/** * Проверяет состоят ли массивы arr1 и arr2 из одинакового * числа одних и тех же элементов * * @param {Number[]} arr1 - отсортированный по возрастанию * массив уникальных элементов * @param {Number[]} arr2 - массив произвольной длинны произвольных чисел * @returns {Boolean} */ function haveSameItems(arr1, arr2) { //convert first array to Set to ensure all its elements are unique let arr2Set = new Set(arr2); const arr1Length = arr1.length; const arr2Length = arr2Set.size; if (arr1Length !== arr2Length) return false; // this goal also could be accomplished with built-in functions like // 'filter', but given conditions do not state explicitly whether // these features may be used. // implementation of binary search: let findValue = function (list, value) { let start = 0; let stop = list.length - 1; while(start <= stop) { let middle = (start + stop) >> 1; if (list[middle] === value) { return middle; } else if (list[middle] < value) { start = middle + 1; } else { stop = middle - 1; } } return -1; }; let count = 0; arr2.forEach(function (value) { if (findValue(arr1, value) >= 0) ++count; }); return (count == arr2Length) ? true : false; } console.log(haveSameItems([11, 22, 48, 54], [11, 48, 54, 22])); export default haveSameItems;
class Platform { constructor() { const loader = new THREE.ObjectLoader(); this.mesh = new THREE.Mesh(); loader.load("./assets/models/platform.json", object => { object.scale.set(1, 1, 1); this.mesh.add(object); }); } } export default Platform;