text
stringlengths
7
3.69M
import React from 'react'; import classes from "./BuyButton.module.css"; const BuyButton = (props) => ( <button className={classes.buyButton} type="primary" {...props} > Купить </button> ); export default BuyButton;
(function () { // connect to server and peers $.connect(); //$.state.p2p.broker.set($.lib.peer($.state.user.id())); // insert css first to prevent fouc var css = $.util.insertCss($.style); // start vdom main loop, initialize lazy image loader var view = $.lib.riko.V($.state, $.templates.app); //$.util.lazyLoader.init(); document.body.innerHTML = ""; document.body.appendChild(view.target); // bind scroll event window.onscroll = $.util.throttleRaf($.emit('scroll')); // auto-update when some files are changed Glagol.events.on('changed', function (node) { if (node.path === "/main.js") { window.location.reload(); } if (node.path === "/style.styl") { css.parentElement.removeChild(css); css = $.util.insertCss($.style); } if (node.path.indexOf('/templates') === 0) { view.update($.state()); } if (node.path === '/state.js') { $.connect(); } }) return view; })
export default function ({app, redirect, $config, $axios}, inject) { let admin = $axios.create() admin.setBaseURL($config.api) admin.onRequest(config => { if (app.$cookies.get('at')) { admin.setToken(app.$cookies.get('at'), 'Bearer') } }) admin.onError(error => { let code = parseInt(error.response && error.response.status) if (code === 404) { redirect('/admin/404') } }) inject('admin', admin) }
import Ember from 'ember'; export default Ember.Controller.extend({ show: false, actions: { presseddemo(){ this.toggleProperty('show'); } } });
const builder = require('botbuilder'); module.exports.createIntent = (intents, stringIntent) => { intents.matches(stringIntent, [ (session, args) => { const { entities } = args; if (entities.find(e => e.entity)) { session.send(entities.find(e => e.entity).entity); } else { const matchedRes = builder.EntityRecognizer.findEntity(entities); // const matchedRes = builder.EntityRecognizer.findBestMatch(entities); session.send(`args: ${JSON.stringify(args)} \n\n matchedRes: ${matchedRes}`); } }, ]); };
var wordBreak = function(s, wordDict, memo = {}) { if(memo[s] !== undefined) return memo[s] if(s === "") return true for(let i = 0; i < wordDict.length; i++){ if(s.substring(0, wordDict[i].length) === wordDict[i]){ let retrunValue = wordBreak(s.slice(wordDict[i].length, s.length), wordDict, memo) if(retrunValue === true){ memo[s] = true return memo[s] } } } memo[s] = false return memo[s] };
import { AsyncStorage } from 'react-native'; import { takeEvery, put, call } from 'redux-saga/effects'; import { Facebook } from 'expo'; import { FACEBOOK_LOGIN, FACEBOOK_LOGIN_SUCCESS, FACEBOOK_LOGIN_FAIL, } from './types'; function* doFacebookLogin() { console.log('doFacebookLogin() called'); const { type, token } = yield call(Facebook.logInWithReadPermissionsAsync, '214718879105945', { permissions: ['public_profile'] } ); if (type === 'cancel') { yield put({ type: FACEBOOK_LOGIN_FAIL }); } else { yield call(AsyncStorage.setItem, 'fb_token', token); yield put({ type: FACEBOOK_LOGIN_SUCCESS, payload: token }); } } function* facebookLogin() { console.log('facebookLogin() called'); const token = yield call(AsyncStorage.getItem, 'fb_token'); if (token) { yield put({ type: FACEBOOK_LOGIN_SUCCESS, payload: token }); } else { yield call(doFacebookLogin); } } export const authSagas = [ takeEvery(FACEBOOK_LOGIN, facebookLogin), ];
'use strict'; require('./window');
'use strict'; /* * Marks typing on/off if the adapter supports it. Defaults to marking as "on". */ module.exports = async function __executeActionMarkAsTyping (action, recUser) { if (!recUser) { throw new Error(`Cannot execute action "mark as typing" unless a user is provided.`); } const adapter = this.__dep(`adapter-${recUser.channel.name}`); const state = (typeof action.state === `undefined` ? true : action.state); const method = (state ? `markAsTypingOn` : `markAsTypingOff`); await adapter[method](recUser); };
import React, { useRef, useEffect } from "react"; import useSelectableCharactersNames from "../../character/useSelectableCharacterNames.hook"; export default function RandomCharacterName() { const display = useRef(); const names = useSelectableCharactersNames(); useEffect(() => { console.log("Total characters: ", names.length); let requestId; const chooseRandomName = () => { const name = names[Math.floor(Math.random() * names.length)]; display.current.innerHTML = name; requestId = window.requestAnimationFrame(chooseRandomName); }; chooseRandomName(); return () => { window.cancelAnimationFrame(requestId); }; }, [names]); return <span ref={display} />; }
$(function () { //从Cookies获取账号ID和密码 getMessage(); $(login).click(function () { var savePassword = trim($('[name="savePassword"]:checked').val()); var saveAccount = trim($('[name="saveAccount"]:checked').val()); console.log(); var user = { userName: trim($('[name="userName"]').val()), userPassword: trim($('[name="userPassword"]').val()), } var userFiled = { userName: '用户名', userPassword: '口令' } var s = [] for (var i in user) { if (user[i] == '') { s.push(userFiled[i]) } } if (s.length) { alert('请输入:' + s.join('、')); return; } else { user.saveAccount = saveAccount; user.savePassword = savePassword; var result = getAjax("/login", "POST", user) console.log(result) if (result.code == 100) { alert(result.resultMessage) } else { window.location.replace("http://localhost:8080/tableInfo.jsp"); } return false; } }) function getMessage() { var userName = getCookie("userName") var userPassword = getCookie("userPassword"); $('[name="userName"]').val(userName); $('[name="userPassword"]').val(userPassword); } //去掉空格 function trim(value) { if (value) { value = value.replace(/^\s*|\s*$/g, ""); } if (!value) { return ""; } else { return value; } } })
// The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import FastClick from 'fastclick' import VueRouter from 'vue-router' import Vuex from 'vuex' import store from './store/store' import App from './App' import index from './view/index' import dis from './view/discount' import choose from './view/choose' import member from './view/member' import nav from './view/nav' import { AjaxPlugin } from 'vux' Vue.use(VueRouter) Vue.use(Vuex) Vue.use(AjaxPlugin) const routes = [{ path: '/', component: index }, { path: '/d', component: dis }, { path: '/c', component: choose }, { path: '/m', component: member }, { path: '/n', component: nav }, { path: '/', component: index } ] const router = new VueRouter({ routes }) router.beforeEach(function (to, from, next) { store.commit('updateLoadingStatus', {isLoading: true}) next() }) router.afterEach(function (to) { store.commit('updateLoadingStatus', {isLoading: false}) }) FastClick.attach(document.body) Vue.config.productionTip = false /* eslint-disable no-new */ new Vue({ router, render: h => h(App) }).$mount('#app-box')
/* * Module code goes here. Use 'module.exports' to export things: * module.exports.thing = 'a thing'; * * You can import it from another modules like this: * var mod = require('role.pickup.structure'); * mod.thing == 'a thing'; // true */ var pickupStructure = { pickup: function(creep) { if(!creep.memory.pickupStructure) { console.log("Creep " + creep.name + " not properly configured to use pickupStructure behavior!"); return ERR_INVALID_TARGET; } //Transfer type logic: resourceType = creep.getResourceType(); //Pickup energy you find by you var maybeEnergy = _.filter(creep.room.lookForAt(LOOK_ENERGY, creep.pos), ((resource) => resource.resourceType == creep.getResourceType())); if(maybeEnergy.length > 0) { creep.pickup(maybeEnergy[0]); } // creep.say('dero'); var structureId = creep.memory.pickupStructure; var structure = Game.getObjectById(structureId); if(structure == null) { //Short circuit here to move to the appropriate room that we haven't been to yet creep.moveTo(new RoomPosition(25, 25, creep.memory.pickupRoom), {ignoreCreeps: false}); return; } result = creep.pickup(creep.room.lookForAt(resourceType,structure.pos)[0]); creep.say(_.sum(creep.carry) + "/" + creep.carryCapacity); if(creep.withdraw(structure, resourceType) == ERR_NOT_IN_RANGE){ creep.moveTo(structure, {ignoreCreeps: false}); } else if (result != OK) { return false; } return true; } } module.exports = pickupStructure;
import { Structure } from "@project_src/common/const/structures"; export default { createBoard({ commit, state, dispatch }, payload) { return new Promise((resolve) => { const board = { ...Structure.BOARD }; if (payload.name) { board.name = payload.name; } if (payload.columns) { board.columns = payload.columns; } board.id = payload.id; commit("createBoard", board); localStorage.setItem("board-list", JSON.stringify(state.list.board)); // * select created dispatch("selectBoard", board.id); resolve(board); }); }, selectBoard({ commit, state }, payload) { const board = state.list.board.find((item) => item.id === payload); if (board) { commit("selectBoard", board.id); localStorage.setItem("board", JSON.stringify(state.current.board)); } }, };
module.exports = app => { const Categories = app.db.models.Categories; app.route("/categories") /** * @api {get} /categories List the categories * @apiGroup Category * @apiPermission none * @apiSuccess {Object[]} categories Categories list * @apiSuccess {Number} id Category id * @apiSuccess {String} title Category title * @apiSuccess {String} description Category description * @apiSuccess {Date} created_at Category created date * @apiSuccess {Date} updated_at Category updated date * @apiSuccessExample {json} Success * HTTP/1.1 200 OK * [ * { * "id": 1, * "title": "Road", * "description": "Road problems", * "created_at": "2016-10-27T07:02:31.000Z", * "updated_at": "2016-10-27T07:02:31.000Z" * } * ] * @apiErrorExample {json} Categories not found error * HTTP/1.1 404 Not Found * @apiErrorExample {json} List error * HTTP/1.1 412 Precondition Failed */ .get((req, res) => { Categories.findAll() .then(result => { if (result) { res.json(result); } else { res.sendStatus(404); } }) .catch(error => { res.status(412).json({ msg: error.message }); }); }); };
import riot from 'riot' import './list.styl' import {CommentService} from 'services' import {notificationManager} from 'utils' riot.tag('comments-list', require('./list.jade')(), function (opts) { this.mixin('load-entities', 'auth-helpers') this.on('update', () => { // when project is null, path looks like /projects//comments if (opts.basePath.indexOf('//') !== -1) { return } this.loaded = true this.commentService = new CommentService(opts.basePath) if (!this.comments) { this.comments = [] this.count = opts.count this.loadComments() } }) this.loadComments = () => { if (!this.commentService || this.deleting) { return Promise.resolve() } const query = { offset: this.comments.length, } return this.loadEntities(this.commentService, {key: 'comments', query: query}) .then(() => $.material.init()) } this.handleSave = (_e) => { this.startLoading({key: 'saving'}) this.commentService.save({body: this.body.value}) .then((comment) => { this.count++ this.comments.push(comment) this.body.value = '' }) .catch(() => notificationManager.notify('Could not save comment', 'danger')) .finally(() => this.endLoading({key: 'saving', update: true})) } this.handleDelete = (options) => { this.count-- this.comments.splice(options.index, 1) this.update() } })
import {Dimensions, Platform, StyleSheet} from 'react-native' export default StyleSheet.create({ viewHeader: { display: 'flex', alignItems: 'center', marginTop: 20, marginBottom: 10 }, title: { fontSize: 18, color: '#D4A452' }, viewSubTitle: { display: 'flex', alignItems: 'center', marginTop: 5 }, subTitle: { fontSize: 15, color: '#9F9F9F' }, bodyText: { fontSize: 16, color: '#D4A452' } });
//app.js const express = require("express") const bodyParser = require("body-parser") const product = require("./routes/product.route") // Imports routes for the products const dbUserName = "remotefh94" const dbPassword = "pass" // Set up mongoose connection const mongoose = require("mongoose") mongoose.connect("mongodb+srv://"+dbUserName+":"+dbPassword+"@cluster0-jagvp.mongodb.net/test?retryWrites=true", {useNewUrlParser: true}) mongoose.Promise = global.Promise let db = mongoose.connection db.on("connected", console.info.bind(console, "Connected to MongoDB as "+dbUserName+"!")) db.on("error", console.error.bind(console, "MongoDB connection error:")) db.on("disconnected", console.info.bind(console, "Disconnected from MongoDB...")) //Create express App const app = express() let port = 1234 app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: false})); app.use("/products", product); //Start App app.listen(port, () => { console.log("Server is up and running on port numner " + port); })
function makeCounter() { var count = 1; return { getNext : function() { return count++; }, set : function(value) { count = value; }, reset : function () { count = 1; } } } var counter = makeCounter(); console.log(counter.getNext()); console.log(counter.getNext()); counter.set(7); console.log(counter.getNext()); console.log(counter.getNext()); counter.reset(); console.log(counter.getNext());
angular.module('sensors', []) .controller('Sensors', function($scope, $http, $interval) { var url = 'http://localhost:8080/REST/DHTSensor'; console.log(url); $scope.loadSensors = function(){ $http({ method: 'GET', url: '/REST/DHTSensor', headers: {'Content-Type': 'application/json'} }).then(function successCallback(response){ console.log("Loading Sensors Data"); console.log(response.data); $scope.sensors = response.data; console.log(response.status); }); } $interval(function(){ $scope.loadSensors(); },5000); });
// React import React, {Component} from 'react'; // CSS import './App.css'; // utlities // Custom Components import SelectStars from './SelectStars'; class SelectStarsContainer extends Component{ constructor(props){ super(props); this.state = { hasBeenRated: false, rating: null, fillStates: [0,0,0,0,0] }; this.handleHover = this.handleHover.bind(this); this.handleClick = this.handleClick.bind(this); } handleHover(syntheticEvent) { // index of star => change all fill states <= index to 1 let targetIndex = syntheticEvent.target.getAttribute('data-index'); this.setState = { fillStates: this.state.fillStates.map( (fillState, index) => { index <= targetIndex ? 1 : 0 } )}; } handleClick(syntheticEvent){ let targetIndex = syntheticEvent.target.getAttribute('data-index'); this.setState = { hasBeenRated: true, rating: targetIndex + 1, fillStates: this.state.fillStates.map( (fillState, index) => { index <= targetIndex ? 2 : 0 } ) }; this.props.onStarSelect(targetIndex + 1); } render(){ return ( <SelectStars fillStates={this.state.fillStates} handleHover={this.handleHover} handleClick={this.handleClick} /> ) } } export default SelectStarsContainer;
const path = require('path'); module.exports = { server: { // Configure the port or named pipe the server should listen for connections on. // process.env.PORT tries to resolve the port or pipe from the environment. // It should work out of the box for Azure AppServices or IIS running IISNode. portOrPipe: process.env.PORT || 3000, // This setting enables automatic generation of SSL certificates for development mode. // You should disable this setting in production. developerSSL: true, // The directory where log files are created. Note the process MUST have write permissions to this directory. logDir: path.resolve(__dirname, '../../logs'), // This is the folder where static assets (the client) should be served from. staticRoot: path.resolve(__dirname, '../../../dist/client'), }, auth: { sessionSecret: 'URJFhFZcg4E8tOhYjhJw6W7W6pEEboS2', redirectUrl: 'https://localhost:3000/auth', policyName: 'B2C_1A_SignInWithADFSIdp', scope: 'user.read', }, };
describe('pixi/core/Rectangle', function () { 'use strict'; var expect = chai.expect; var Rectangle = PIXI.Rectangle; it('Module exists', function () { expect(Rectangle).to.be.a('function'); }); it('Confirm new instance', function () { var rect = new Rectangle(); pixi_core_Rectangle_confirm(rect, 0, 0, 0, 0); }); });
import * as React from "react"; function GoogleForm(props) { return ( <> <iframe src="https://docs.google.com/forms/d/e/1FAIpQLScP5qjYvNSsm-AtHVm7uQOMXsrcvSoaRyJ9fuyJLF68fdqTNg/viewform?embedded=true" width="100%" height="2000px" > 読み込んでいます… </iframe> </> ); } export default GoogleForm;
import React, { Component } from 'react'; import logo from '../../public/img/logo.png'; class Header extends Component{ render(){ return ( <div> <h1 className="text-center">{this.props.header}</h1> <div className="text-center"> <img src={logo} alt="logo-donjon-jdr"/> </div> </div> ) } } export default Header;
module.exports.TIME_PERIOD = { short: '0', long: '1' };
import React from 'react'; import Isotope from 'isotope-layout'; import getGalleryData from '../../../utils/getGalleryData'; import getMediaData from '../../../utils/getMediaData'; export class Gallery extends React.Component { constructor (props) { super(props); this.state = { pluginsInit: false, src: [], full: [], alt: [], ids: '', filters: [], isLoading: true, isLoadingMedia: true, media: {}, active: 0 }; } componentDidMount () { const _this = this; getGalleryData('posts', 29, _this.successCallback.bind(_this), _this.errorCallback.bind(_this)); } handleClick (id, event) { if (event && typeof event.preventDeafult === 'function') { event.preventDefault(); } this.getMedia(id); } getMedia (id) { const medias = this.state.medias || {}; const _this = this; if (!medias[id]) { this.setState({ isLoadingMedia: true }); getMediaData(id, _this.successMediaCallback.bind(this, id), _this.errorMediaCallback.bind(this, id)); } } successCallback (data) { const alt = data.alt || []; // alt.unshift('All'); const filters = alt.filter((filter, index) => { return alt.indexOf(filter) === index; }); data.isLoading = false; data.filters = filters; if (!this.state.pluginsInit) { this.initPlugins(); data.pluginsInit = true; } this.setState(data); } errorCallback () { this.setState({ isLoading: false }); } successMediaCallback (id, data) { const medias = this.state.medias || {}; const state = { isLoadingMedia: false }; if (!medias[id]) { medias[id] = data; state.medias = medias; } this.setState(state); } errorMediaCallback () { this.setState({ isLoadingMedia: false }); } initGallery () { const _portfolio = this._portfolio; if (_portfolio) { const iso = new Isotope(_portfolio, { // options itemSelector: '.portfolio-item', masonry: { rowHeight: 280 } }); this.setState({ isotope: iso }); } } initModal () { const _this = this; $('.magnific-popup-inline').magnificPopup({ type: 'inline', callbacks: { open: function () { $('body').addClass('overIn'); }, close: function () { $('body').removeClass('overIn'); }, change: function () { const id = this.content.data('id'); _this.getMedia(id); } }, gallery: { enabled: true } }); } initPlugins () { const _this = this; setTimeout(() => { _this.initModal(); _this.initGallery(); }, 1000); } filterGallery (_thisa, filterId, index, event) { event.preventDefault(); const iso = _thisa.state.isotope; if (iso) { iso.arrange({ // item element provided as argument filter: (itemIndex, itemElem) => { const filters = itemElem.dataset.filters; return filters.indexOf(filterId) > -1; } }); } $('.filters li a').removeClass('active'); $(_thisa['_filter' + index]).addClass('active'); } renderFilter () { const _this = this; const filters = this.state.filters || []; return filters.map(function (filter, index) { const filterId = filter.replace(' ', '-').toLowerCase(); const _refLink = '_filter' + index; return ( <li key={'filter-' + index}> <a ref={(c) => (_this[_refLink] = c)} href="" onClick={_this.filterGallery.bind(this, _this, filterId, index)} >{filter}</a> </li> ); }); } renderFilters () { const _this = this; return ( <ul className="filters text-center mt25 mb50"> <li> <a className="active" onClick={_this.filterGallery.bind(this, _this, 'all', -1)} >All Projects</a> </li> {this.renderFilter()} </ul> ); } renderImages () { const images = []; const srcs = this.state.src || []; const _this = this; const ids = _this.state.ids || []; return srcs.map((src, index) => { const image = { thumbUrl: src, largeUrl: _this.state.full[index] || '/img/portfolio/preview/img-portfolio-preview-1.jpg', alt: _this.state.alt[index], id: ids[index] }; images.push(image); return _this.renderImage(image, index); }); } renderPlatforms (platforms) { return platforms.map((platform, index) => { return ( <span key={index} className="button-o button-xs button-square button-yellow mr15">{platform}</span> ); }); } renderImageLarge (image) { const id = image.id; const medias = this.state.medias || {}; const media = medias[id] || {}; const platform = media.platform || ''; let platforms = []; let description = ''; try { platforms = platform.split(',') || []; } catch(err) {} try { description = media.description.rendered; } catch(err) {} return ( <div id={'media-' + id} className="media-wrapper mfp-hide" data-id={id}> <img src={image.largeUrl} alt={image.alt} className="media-image" /> <div className="media-content"> <h2>{media.title}</h2> <h4>{this.renderPlatforms(platforms)}</h4> <div className="media-text" dangerouslySetInnerHTML={{__html: description}} /> </div> </div> ); } renderImage (image, index) { const alt = image.alt; let altArr; let filters = []; if (typeof alt === 'string') { altArr = alt.split(','); } altArr.forEach((altItem) => { const altClass = altItem.replace(' ', '-').toLowerCase(); filters.push(altClass); }); filters.unshift('all'); const id = image.id; return ( <div key={index} data-filters={filters} data-id={index} className={'portfolio-item col-lg-3 col-md-4 col-sm-6 col-xs-12 ' + filters.join(' ')} data-category="" > <a href={'#media-' + id} data-id={id} onClick={this.handleClick.bind(this, image.id)} className="magnific-popup-inline external-media" > <span className="glyphicon glyphicon-search hover-bounce-out"></span> </a> <img src={image.thumbUrl} alt={image.alt} className="img-responsive" /> {this.renderImageLarge(image)} </div> ); } render () { return ( <div id="portfolioGrid"> <div className="container-fluid bg-gray pt30"> <div className="row"> <div className="col-md-12"> {this.renderFilters()} <div className="portfolio center-block" ref={(c) => (this._portfolio = c)}> {this.renderImages()} </div> </div> </div> </div> </div> ); } } export default Gallery;
import React, { Component } from 'react' let {Provider,Consumer} =react.createContext(); export {Provider,Consumer};
//App Singleton Controller var MyTaskListApp = function () { //private data of the controller var tasks = []; var TASKS_KEY = "time_capture_tasks"; var currentTaskIndex = -1; //private methods var loadTasks = function () { if (localStorage) { var storedTasks = localStorage[TASKS_KEY]; if (!storedTasks) { syncStorage(); } else { tasks = JSON.parse(storedTasks); } } }; var syncStorage = function () { localStorage[TASKS_KEY] = JSON.stringify(tasks); }; var updateCurrentTask = function () { var currentTask = tasks[currentTaskIndex]; currentTask.title = $('#taskName').val(); currentTask.description = $('#taskDescription').val(); currentTask.done = ($('#taskCompleted').val() === "yes"); currentTask.dueDate = $('#taskDate').val(); currentTask.logNum = $('#taskLogNum').val(); currentTask.timeSpent = $('#taskEstimation').val(); }; var displayTasks = function () { var list = $('#taskList'); var index = 0; var count = 0; var task = null; var newLI = null; list.empty(); var createTapHandler = function (index) { return function () { console.log(index); MyTaskListApp.setCurrentTaskIndex(index); $.mobile.changePage('form.html'); }; }; //count = tasks.lenght on following line "caches" the length because JavaScript recalculates the length with every iteration for (index = 0, count = tasks.length; index < count; ++index) { task = tasks[index]; newLI = $('<li>'); newLI.on('tap', createTapHandler(index)); newLI.append(task.title); list.append(newLI); } //many objects need refresh at the end to display them correctly list.listview('refresh'); }; var fillForm = function () { var currentTask = tasks[currentTaskIndex]; $('#taskName').val(currentTask.title); $('#taskDescription').val(currentTask.description); $('#taskDate').val(currentTask.dueDate); $('#taskLogNum').val(currentTask.logNum); $('#taskEstimation').val(currentTask.timeSpent); var slider = $('#taskCompleted'); var value = (currentTask.done) ? 1 : 0; slider[0].selectedIndex = value; slider.slider('refresh'); }; //public interface of the controller return { init: function () { loadTasks(); }, Task: function () { this.done = false; this.title = "New Task"; this.description = "No description"; this.dueDate = new Date(); this.logNum = ""; this.timeSpent = 1; }, addTask: function (task) { console.log('adding a task'); currentTaskIndex = tasks.length; tasks.push(task); //add item to the array syncStorage(); }, refreshTasks: function () { displayTasks(); }, saveCurrentTask: function () { updateCurrentTask(); syncStorage(); $.mobile.changePage('index.html'); }, displayTask: function () { fillForm(); }, setCurrentTaskIndex: function (index) { currentTaskIndex = index; }, deleteCurrentTask: function () { tasks.splice(currentTaskIndex, 1); syncStorage(); $.mobile.changePage('index.html'); } }; } (); // jQueryMobile events $('#indexPage').live('pageinit', function () { MyTaskListApp.init(); //add event to task button $('#addTaskButon').on('tap', function () { var newTask = new MyTaskListApp.Task(); // somehow create a task MyTaskListApp.addTask(newTask); }); }); $('#indexPage').live('pageshow', function () { MyTaskListApp.refreshTasks(); }); $('#formPage').live('pageinit', function () { $('#saveButton').on('tap', function () { MyTaskListApp.saveCurrentTask(); }); }); $('#formPage').live('pagebeforeshow', function () { MyTaskListApp.displayTask(); }); $('#deletePage').live('pageinit', function () { $('#deleteButton').on('tap', function () { MyTaskListApp.deleteCurrentTask(); }); });
import Profile from "./profile/Profile"; import React from "react"; import "./profile/profile.css"; function App() { return ( <div className="App"> <Profile fullName="Martial YAO" bio="jeune informaticien, Dynamique" profession="Developpeur Fulstack JS"/> </div> ); } export default App;
$(document).ready(function() { $('.ingredients li').click(function() { $(this).toggleClass("bought"); }); $('.directions li').click(function() { for (i = 0; i < $('.directions li').length; i++) { if (i <= $(this).index()) { $('.directions li:nth-child(' + (i + 1) + ')').css('font-weight','bold'); } else { $('.directions li:nth-child(' + (i + 1) + ')').css('font-weight','normal'); } } }); $('img').click(function() { $('img').hide(); }); });
// 云函数入口文件 const cloud = require('wx-server-sdk') cloud.init() const db = cloud.database() // 云函数入口函数 // 返回前五篇文章 exports.main = async (event, context) => { return await db.collection('articles').limit(5).get() }
import { REMOVE, REPLACE, TEXT, ATTR } from './contants' import { Element, render, setAttr } from './element' let allPatches let index = 0 // 默认哪个需要打补丁 function patch(node, patches) { allPatches = patches dfsWalk(node) } function dfsWalk(node) { let current = allPatches[index++] let childNodes = node.childNodes // 先序深度,继续遍历递归子节点 childNodes.forEach(child => dfsWalk(child)) if (current) { doPatch(node, current) // 打上补丁 } } function doPatch(node, patches) { // 遍历所有打过的补丁 patches.forEach(patch => { switch (patch.type) { case ATTR: for (let key in patch.attr) { let value = patch.attr[key] if (value) { setAttr(node, key, value) } else { node.removeAttribute(key) } } break case TEXT: node.textContent = patch.text break case REPLACE: let newNode = patch.newNode newNode = newNode instanceof Element ? render(newNode) : document.createTextNode(newNode) node.parentNode.replaceChild(newNode, node) break case REMOVE: node.parentNode.removeChild(node) break default: break } }) } export default patch
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import 'antd-mobile/dist/antd-mobile.css'; import registerServiceWorker from './registerServiceWorker'; document.title = '健康宣传' ReactDOM.render(<App/>, document.getElementById('root')); registerServiceWorker();
/** * Created by tanmv on 19/05/2017. */ 'use strict'; const express = require('express'), client_sessions = require("client-sessions"), express_session = require('express-session'), redisStore = require('connect-redis')(express_session), methodOverride = require('method-override'), cookieParser = require('cookie-parser'), bodyParser = require('body-parser'), hogan = require('hogan-express'), compression = require('compression'), morgan = require('morgan'), path = require('path'), routes = require("./routes"), partials = require("./partials"); module.exports = (callback) => { let app = new express(); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({extended: false})); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'),{ maxAge: 129600000}));//1.5d app.use(methodOverride('X-HTTP-Method-Override')); app.use(compression()); //session config if(config.session.type=='client'){ app.use(client_sessions(config.session.client)); } else if(config.session.type=='redis'){ let session_config = config.session.redis; session_config.store = new redisStore(config.session.redis_store); app.use(express_session(session_config)); } switch (config.site_type) { case 1: app.set('views', path.join(__dirname, 'practice_views')); break; case 2: app.set('views', path.join(__dirname, 'answer_views')); break; case 3: app.set('views', path.join(__dirname, 'learn_views')); break; default: app.set('views', path.join(__dirname, 'views')); break; } app.engine('html', hogan); app.set('view engine', 'html'); partials(app); if(config.log_request){ app.use(morgan('dev')); } app.use(function(req, res, next){ res.locals.user = req.tndata.user; //set current user res.locals.publish = config.publish; res.locals.ads = config.ads; res.locals.server_static = config.server_static; res.locals.server_upload = config.server_upload; // res.locals.baseUrl = req.baseUrl; res.locals.pathname = req._parsedUrl.pathname; res.set('x-powered-by', 'MVTHP-2017'); next(); }); routes(app); if(typeof callback === "function") callback(app); return app; };
export const getCatFactsLoading = state => state.home.catFactsLoading; export const getCatFacts = state => state.home.catFacts; export const getCatFactsError = state => state.home.catFactsError;
import React from 'react' import './CartView.css' import CartItem from '../components/CartItem' function CartView() { return ( <div className='cartView'> <div className='cartView__left'> <h3>Shopping Cart</h3> <CartItem/> </div> <div className='cartView__right'> <div className='cartView__info'> <p>Subtotal (0) Items</p> <p>$499.99</p> </div> <div> <button>Proceed To Check</button> </div> </div> </div> ) } export default CartView
import React from 'react'; export class Username extends React.Component { render() { return ( <p> <input type="text" ref="username" style={this.props.style} value={this.props.username} onChange={this.props.onInput} /> </p> ); } }
var gulp = require('gulp'), path = require('path'), plugins = require('gulp-load-plugins')({ pattern: ['gulp-*', 'gulp.*', '*'], config: path.join(__dirname, 'package.json'), scope: ['dependencies', 'devDependencies', 'peerDependencies'], replaceString: /^gulp(-|\.)/, lazy: false }); console.log(Object.keys(plugins)); (function() { var childProcess = require("child_process"); var oldSpawn = childProcess.spawn; function mySpawn() { console.log('spawn called'); console.log(arguments); var result = oldSpawn.apply(this, arguments); return result; } childProcess.spawn = mySpawn; })(); var config = { paths: { html: { src: ["./*.html"], dist: "dist" }, javascript: { src: ["js/**/*.js"], dist: "dist/js" }, css: { src: ["css/**/*.css"], dist: "dist/css" }, fonts: { src: ["css/font/*.*"], dist: "dist/css/font" }, images: { src: ["img/**/*"], dist: "dist/img" } } }; //sftp gulp.task('sftp', function () { return gulp.src('dist/**/*') .pipe(plugins.sftp({ host: 'arturk01.ftp.ukraine.com.ua', user: 'arturk01_preview', pass: '72zrb79h' })) }); //fonts gulp.task('fonts', function() { gulp.src(config.paths.fonts.src) .pipe(gulp.dest(config.paths.fonts.dist)); }); //connect gulp.task('webserver', function() { gulp.src('dist') .pipe(plugins.serverLivereload({ livereload: true, //directoryListing: true, open: true })); }); //bower-js gulp.task('bower-js', function () { return gulp.src(plugins.wiredep().js) .pipe(gulp.dest(config.paths.javascript.dist)); }); gulp.task('bower-css', function () { return gulp.src(plugins.wiredep().css) .pipe(gulp.dest(config.paths.css.dist)); }); //inject gulp.task('inject', ['css', 'js', 'bower-js', 'bower-css'], function() { var target = gulp.src('./index.html'); var sources = gulp.src(['./dist/js/jquery.js', './dist/js/*.js', '!./dist/js/bundle.min.js', './dist/css/*.css'], { read: false }); return target .pipe(plugins.wait(2000)) .pipe(plugins.inject(sources, { addRootSlash: false, ignorePath: 'dist' })) .pipe(gulp.dest('./dist')); }); //html gulp.task("html", function(){ //.pipe(minifyHTML()) return gulp.src(config.paths.html.src) .pipe(gulp.dest(config.paths.html.dist)); }); //js gulp.task('js', function () { gulp.src(config.paths.javascript.src) .pipe(plugins.uglify()) .pipe(plugins.concat('bundle.min.js')) .pipe(gulp.dest(config.paths.javascript.dist)) .pipe(plugins.wait(2000)) .pipe(plugins.notify('Js Done!')); }); //css gulp.task('css', function () { gulp.src(config.paths.css.src) .pipe(plugins.concat('bundle.min.css')) .pipe(plugins.minifyCss()) .pipe(gulp.dest(config.paths.css.dist)) .pipe(plugins.notify('Css Done!')); }); //images gulp.task('images', function () { gulp.src(config.paths.images.src) .pipe(plugins.imagemin({ progressive: true, //svgoPlugins: [{removeViewBox: false}], use: [plugins.imageminPngquant(), plugins.imageminMozjpeg()] })) .pipe(gulp.dest(config.paths.images.dist)); }); //watch gulp.task('watch',function() { gulp.watch('index.html', ['html', 'inject']); //gulp.watch('index.html', ['html']); gulp.watch('css/*.css', ['css']); gulp.watch('img/*', ['images']); gulp.watch('js/*', ['js']); gulp.watch('bower.json', ['inject']); }); //default gulp.task('default', ['webserver', 'html', 'inject', 'fonts', 'watch']);
import './styles.css'; import LoadMoreBtn from './js/load-more-btn'; import updateMarkup from './js/update-markup'; import apiService from './js/apiService'; import refs from './js/refs'; import { data } from 'autoprefixer'; //=== const loadMoreBtn = new LoadMoreBtn('button[data-action="load-more"]'); refs.searchForm.addEventListener('submit', searchFormSubmitHandler); loadMoreBtn.refs.button.addEventListener('click', updateBtns); function searchFormSubmitHandler(evt) { evt.preventDefault(); const form = evt.currentTarget; apiService.query = form.elements.query.value; clearMarkup(); apiService.resetPage(); form.reset(); updateBtns(); } function updateBtns() { loadMoreBtn.disable(); apiService.fetchImages().then(hits => { updateMarkup(hits); loadMoreBtn.show(); loadMoreBtn.enable(); window.scrollTo({ top: document.documentElement.offsetHeight, behavior: 'smooth', }); }); } function clearMarkup() { refs.gallery.innerHTML = ''; }
const newNumbers = [1, 3, 5, 7]; const newSum = newNumbers.reduce((accumulator, currentValue) => { console.log('The value of accumulator: ', accumulator); //this displays the first number console.log('The value of currentValue: ', currentValue); // this displays the next number to be added to the first return accumulator + currentValue // this takes the first item in the array and adds it to the second and takes tha answer and adds it to the next an so on }/* a number can be added here to give another value added*/ ); console.log(newSum); // this displays '16' because 1+3+5+7=16 /* the entire dipaly should look like The value of accumulator: 1 The value of currentValue: 3 The value of accumulator: 4 The value of currentValue: 5 The value of accumulator: 9 The value of currentValue: 7 16 */
import axios from 'axios' import store from '@/vuex' import * as mutationTypes from '@/vuex/mutations/types' const axiosConfig = require('@/http/common/axiosConfig') const _axios = axios.create(axiosConfig.default) const http = {} // 请求拦截 _axios.interceptors.request.use(config => { // 显示loading store.commit(mutationTypes.IS_SHOW_LOADING, true) return config }, () => { // 隐藏loading store.commit(mutationTypes.IS_SHOW_LOADING, false) }) // // 响应拦截 _axios.interceptors.response.use(data => { // 隐藏loading store.commit(mutationTypes.IS_SHOW_LOADING, false) return data }, () => { // 隐藏loading store.commit(mutationTypes.IS_SHOW_LOADING, false) }) const fetchConfig = (url, opt) => { if (opt.type === 'POST') { return { url: url, method: opt.type || 'POST', data: opt.params || {} // post请求时 设置为data可以自定义 Content-Type } } else { return { url: url, method: opt.type || 'GET', params: opt.params || {} // 默认GIT } } } const fetch = (url, options) => { return new Promise((resolve, reject) => { let opt = options || {} _axios(fetchConfig(url, opt)) .then(res => { resolve(res) }) .catch(err => { // reject({ 'code': '-100', 'message': '网络异常或参数错误!' }); reject(err) }) }) } http.install = function (vue) { vue.prototype.$http = function (url, options) { return fetch(url, options) } } export { http, fetch }
import React, { Component } from 'react'; import cx from 'classnames'; import PropTypes from 'prop-types'; import { NavLink, Route } from 'react-router-dom'; import { Collapse } from 'reactstrap'; // import { Route } from 'react-router'; // import Icon from '../../Icon/Icon'; import s from './LinksGroup.module.scss'; function LinksGroup(props) { const { className, childrenLinks, headerLink, header } = props; // console.log(props); const [isOpen, setOpen] = React.useState(false); if (!childrenLinks) { return ( <li className={cx(s.headerLink, className)}> <NavLink to={headerLink} activeClassName={s.headerLinkActive} exact> <div> {/* {glyph && <Icon glyph={glyph} />} */} <span className={s.header}>{header}</span> </div> </NavLink> </li> ); } /* eslint-disable */ return ( <Route path={headerLink} children={({ match }) => { return ( <li className={cx(s.headerLink, className)}> <a className={cx({ [s.headerLinkActive]: !!match && match.url.indexOf(headerLink) !== -1, })} onClick={() => setOpen(!isOpen)} > <div> {/* {glyph && <Icon glyph={glyph} />} */} <span>{header}</span> </div> <b className={cx('fa fa-angle-left arrow', s.arrow, { [s.arrowActive]: isOpen, })} /> </a> {/* eslint-enable */} <Collapse className={s.panel} isOpen={isOpen}> <ul> {childrenLinks && childrenLinks.map((child) => ( <li key={child.name}> <NavLink to={child.link} exact // onClick={() => setOpen(false)} activeClassName={s.headerLinkActive} > {child.name} </NavLink> </li> ))} </ul> </Collapse> </li> ); }} /> ); // } } export default LinksGroup; /* eslint-disable */ LinksGroup.propTypes = { header: PropTypes.node.isRequired, headerLink: PropTypes.string, childrenLinks: PropTypes.array, // glyph: PropTypes.string, className: PropTypes.string, }; /* eslint-enable */ LinksGroup.defaultProps = { headerLink: null, childrenLinks: null, className: '', // glyph: null, };
// The SocketProvider component will expect to be rendered one time at a high // level in the component tree, much like the Redux Provider, wrapping our // entire application for more informations see: // https://medium.com/flatiron-labs/improving-ux-with-phoenix-channels-react-hooks-8e661d3a771e // // Usage : // // import SocketProvider from "./components/SocketProvider" // // ... // <SocketProvider url="ws://localhost/socket" options={{ token }}> // <App /> // </SocketProvider> // ... // import { Socket } from "phoenix" import SocketContext from "../contexts/SocketContext" import { useEffect, useMemo, useState } from "react" import PropTypes from "prop-types" import Spinner from "./Spinner" const SocketProvider = ({ url, options, children }) => { const [isConnected, setConnected] = useState(false) const socket = useMemo(() => new Socket(url, { params: options }), [ url, options, ]) useEffect(() => { socket.connect() socket.onOpen(() => setConnected(true)) }, [options, url, socket]) if (!isConnected) return <Spinner /> return ( <SocketContext.Provider value={socket}>{children}</SocketContext.Provider> ) } SocketProvider.defaultProps = { options: {}, } SocketProvider.propTypes = { url: PropTypes.string.isRequired, options: PropTypes.object, children: PropTypes.oneOfType([ PropTypes.arrayOf(PropTypes.node), PropTypes.node, ]), } export default SocketProvider
import express from 'express'; import {fetchJsonByNode, postOption} from '../../common/common'; import {host} from '../globalConfig'; import name from './name'; let api = express.Router(); const currencyHandler = async (options, req) => { const url = `${host}/charge_service/tenant_currency_type/tenant_guid/list`; const json = await fetchJsonByNode(req, url); if (json.returnCode === 0) { return json.result; } else { return options; } }; const queryGroupHandler = async (options) => { return options.length ? options : [{value: 'todo', title: '待办'}]; }; const yesOrNoHandler = async (options) => { if ((options.length === 2) && options[0].value === 'true_false_type_false') { return [options[1], options[0]]; } else { return options; } }; const HANDLERS = [ {name: name.CURRENCY, handler: currencyHandler}, {name: name.QUERY_GROUP, handler: queryGroupHandler}, {name: name.YES_OR_NO, handler: yesOrNoHandler} ]; const handle = async (result, req, res) => { for (const {name, handler} of HANDLERS) { if (result[name]) { result[name] = await handler(result[name], req, res); } } return result; }; api.post('/', async (req, res) => { const url = `${host}/dictionary_service/search/dictionary/list`; const json = await fetchJsonByNode(req, url, postOption(req.body.names)); if (json.returnCode !== 0) { res.send(json); } else { const result = await handle(json.result, req, res); res.send({returnCode: 0, result}); } }); export default api;
module.controller("parentCtrl", parentCtrl) // DI dependency injection - IOC function parentCtrl($scope) { $scope.x=5 this.x=7 }
import React, {Component} from 'react'; import { View, Text, StyleSheet, TextInput, Keyboard, Button, } from 'react-native'; import Modal from 'react-native-modal'; import {BLUE, GRAY} from '../config/constants'; export default class DiamondModel extends Component { constructor(props) { super(props); this.state = { inputs: [ {id: 'box1', text: '', isFocused: false}, {id: 'box2', text: '', isFocused: false}, {id: 'box3', text: '', isFocused: false}, {id: 'box4', text: '', isFocused: false}, {id: 'box5', text: '', isFocused: false}, {id: 'box6', text: '', isFocused: false}, {id: 'box7', text: '', isFocused: false}, {id: 'box8', text: '', isFocused: false}, {id: 'box9', text: '', isFocused: false}, {id: 'box10', text: '', isFocused: false}, ], modalVisible: false, }; } isNext = (arr, idx) => { const prevInputs = arr.slice(0, idx).filter(el => el.text === '').length; return prevInputs === 0; }; _onChangeText = (text, idx) => { let inputs = this.state.inputs.slice(); const next = this.isNext(inputs, idx); if (!next) { inputs[idx].text = ''; this.setState({inputs, modalVisible: true}); } else { inputs = this.state.inputs.slice(); inputs[idx].text = text; this.setState({inputs}); } }; _onFocus = idx => { let inputs = this.state.inputs.slice(); inputs[idx].isFocused = true; this.setState({inputs}); }; _onBlur = idx => { let inputs = this.state.inputs.slice(); inputs[idx].isFocused = false; this.setState({inputs}); }; setModalVisible = visible => { this.setState({modalVisible: visible}); }; clearModel = () => { let inputs = this.state.inputs.slice(); inputs.forEach(item => { item.text = ''; }); this.setState({inputs}); }; render() { return ( <View style={{flex: 1, flexDirection: 'column'}}> <Modal isVisible={this.state.modalVisible} animationInTiming={600} animationOutTiming={600} coverScreen={false} hasBackdrop={false} avoidKeyboard={true} style={styles.modal}> > <View style={{flex: 1, margin: 20}}> <Text>Please fill in the boxes in the right order...</Text> <View style={{margin: 30}}> <Button onPress={() => this.setModalVisible(!this.state.modalVisible)} title="OK" color={BLUE} /> </View> </View> </Modal> <View style={styles.row}> <TextInput ref={ref => { this._box1 = ref; }} placeholder={'Start Here'} multiline={true} onFocus={() => this._onFocus(0)} onBlur={() => this._onBlur(0)} style={[ styles.inputBox, this.state.inputs[0].isFocused ? {borderWidth: 2} : '', ]} onChangeText={text => this._onChangeText(text, 0)} returnKeyType="next" onSubmitEditing={() => this._box2 && this._box2.focus()} value={this.state.inputs[0].text} /> </View> <View style={styles.row}> <TextInput ref={ref => { this._box3 = ref; }} placeholder={'3'} multiline={true} onFocus={() => this._onFocus(2)} onBlur={() => this._onBlur(2)} style={[ styles.inputBox, this.state.inputs[2].isFocused ? {borderWidth: 2} : '', ]} returnKeyType="next" onSubmitEditing={() => this._box4 && this._box4.focus()} onChangeText={text => this._onChangeText(text, 2)} value={this.state.inputs[2].text} /> <TextInput ref={ref => { this._box2 = ref; }} placeholder={'2'} multiline={true} onFocus={() => this._onFocus(1)} onBlur={() => this._onBlur(1)} style={[ styles.inputBox, this.state.inputs[1].isFocused ? {borderWidth: 2} : '', ]} returnKeyType="next" onSubmitEditing={() => this._box3 && this._box3.focus()} onChangeText={text => this._onChangeText(text, 1)} value={this.state.inputs[1].text} /> </View> <View behavior="padding" style={styles.row}> <TextInput ref={ref => { this._box7 = ref; }} placeholder={'7'} multiline={true} onFocus={() => this._onFocus(6)} onBlur={() => this._onBlur(6)} style={[ styles.inputBox, this.state.inputs[6].isFocused ? {borderWidth: 2} : '', ]} returnKeyType="next" onSubmitEditing={() => this._box8 && this._box8.focus()} onChangeText={text => this._onChangeText(text, 6)} value={this.state.inputs[6].text} /> <TextInput ref={ref => { this._box6 = ref; }} placeholder={'6'} multiline={true} onFocus={() => this._onFocus(5)} onBlur={() => this._onBlur(5)} style={[ styles.inputBox, this.state.inputs[5].isFocused ? {borderWidth: 2} : '', ]} returnKeyType="next" onSubmitEditing={() => this._box7 && this._box7.focus()} onChangeText={text => this._onChangeText(text, 5)} value={this.state.inputs[5].text} /> <TextInput ref={ref => { this._box5 = ref; }} placeholder={'5'} multiline={true} onFocus={() => this._onFocus(4)} onBlur={() => this._onBlur(4)} style={[ styles.inputBox, this.state.inputs[4].isFocused ? {borderWidth: 2} : '', ]} returnKeyType="next" onSubmitEditing={() => this._box6 && this._box6.focus()} onChangeText={text => this._onChangeText(text, 4)} value={this.state.inputs[4].text} /> <TextInput ref={ref => { this._box4 = ref; }} placeholder={'4'} multiline={true} onFocus={() => this._onFocus(3)} onBlur={() => this._onBlur(3)} style={[ styles.inputBox, this.state.inputs[3].isFocused ? {borderWidth: 2} : '', ]} returnKeyType="next" onSubmitEditing={() => this._box5 && this._box5.focus()} onChangeText={text => this._onChangeText(text, 3)} value={this.state.inputs[3].text} /> </View> <View behavior="padding" style={styles.row}> <TextInput ref={ref => { this._box9 = ref; }} placeholder={'9'} multiline={true} onFocus={() => this._onFocus(8)} onBlur={() => this._onBlur(8)} style={[ styles.inputBox, this.state.inputs[8].isFocused ? {borderWidth: 2} : '', ]} returnKeyType="next" onSubmitEditing={() => this._box10 && this._box10.focus()} onChangeText={text => this._onChangeText(text, 8)} value={this.state.inputs[8].text} /> <TextInput ref={ref => { this._box8 = ref; }} placeholder={'8'} multiline={true} onFocus={() => this._onFocus(7)} onBlur={() => this._onBlur(7)} style={[ styles.inputBox, this.state.inputs[7].isFocused ? {borderWidth: 2} : '', ]} returnKeyType="next" onSubmitEditing={() => this._box9 && this._box9.focus()} onChangeText={text => this._onChangeText(text, 7)} value={this.state.inputs[7].text} /> </View> <View behavior="padding" style={styles.row}> <TextInput ref={ref => { this._box10 = ref; }} placeholder={'Your Gap'} multiline={true} onFocus={() => this._onFocus(9)} onBlur={() => this._onBlur(9)} style={[ styles.inputBox, this.state.inputs[9].isFocused ? {borderWidth: 2} : '', ]} returnKeyType="done" onSubmitEditing={() => Keyboard.dismiss()} onChangeText={text => this._onChangeText(text, 9)} value={this.state.inputs[9].text} /> </View> <View style={styles.btn}> <Button color={GRAY} onPress={this.clearModel} title="Clear" /> </View> </View> ); } } const styles = StyleSheet.create({ row: { margin: 7, flexDirection: 'row', justifyContent: 'center', }, inputBox: { backgroundColor: 'white', borderColor: BLUE, borderWidth: 1, margin: 10, paddingLeft: 10, paddingRight: 10, borderRadius: 6, textAlign: 'center', fontSize: 16, }, modal: { backgroundColor: 'white', borderColor: BLUE, borderRadius: 10, borderWidth: 3, padding: 22, }, btn: { marginRight: '25%', marginLeft: '25%', marginTop: 30, marginBottom: 30, }, });
var http = require('http') var assert = require('assert') var methods = require('..') describe('methods', function() { if (http.METHODS) { it('is lowercased http.METHODS', function() { var lowercased = http.METHODS.map(function(method) { return method.toLowerCase() }); assert.deepEqual(lowercased, methods) }); } });
import React from 'react' import Link from 'gatsby-plugin-transition-link/AniLink' import { graphql } from 'gatsby' import Img from 'gatsby-image' import Layout from '../components/layout' import { IoIosArrowRoundForward } from 'react-icons/io' import SEO from '../components/seo' const AboutPage = ({ data, location }) => ( <Layout> <SEO title="About" /> <div className="page container__content "> <div className="char__readable measure__default center"> <h4 className="">I learn, analyze, create, and iterate.</h4> <h5>The Method</h5> <p> My method is to immerse, discuss, ship, get feedback, and be patient because understanding and quality both take time and effort. </p> {/* {JSON.stringify(data, null, 4)} */} {/* <Img fluid={data.profile.childImageSharp.fluid} objectFit="contain" /> */} <h5>The Objective</h5> <p> I enjoy nothing more than building something efficient and competitive! The process itself is an addiction. I am energized by democratizing the creative process and exploring the unique, clever, strange, and sometimes hilarious solutions that open collaboration fosters. </p> <h5>The Tools</h5> <p className="margin__bottom--l"> I am a React and JavaScript developer with experience and comfort across the entire stack. On the backend I prefer Nodejs or Python. </p> <Link fade duration={1} to="/" className="icon__arrow link__primary--dark " > Project{''} <IoIosArrowRoundForward /> </Link> </div> </div> </Layout> ) export default AboutPage export const query = graphql` { profile: file(name: { eq: "profile-avatar-2020" }) { id childImageSharp { fluid { ...GatsbyImageSharpFluid } } } } `
import React, {Component} from 'react'; import { View, Text, ImageBackground, Image, TouchableOpacity, StyleSheet, TextInput, ScrollView, StatusBar, Dimensions } from 'react-native'; import mainStyle from '../src/styles/mainStyle'; export default class ThongTinKyThuat_Goi extends Component { render(){ return( <ImageBackground source = {require('../assets/backgroundImage4.png')} style = {mainStyle.container}> <View style = {mainStyle.content_goi_1}> <View> <Image source = {require('../assets/goi.png')} style = {{width:250, height:250, resizeMode:'contain'}}></Image> </View> </View> <View style = {mainStyle.content_goi_2}> <Text style = {{color:'#ffffff', fontWeight:'bold',fontSize:16}}>NGUYỄN BÍCH VÂN</Text> <Text style = {{color:'#ffffff'}}>Đang gọi...</Text> </View> <View style = {mainStyle.content_goi_3}> <View style = {mainStyle.content_goi_3a}> <TouchableOpacity style = {mainStyle.iconGoi}> <Image source={require('../assets/iconAdd.png')} style = {{width:30, height:30, resizeMode:'stretch'}}></Image> </TouchableOpacity> <View style = {{flex:2, marginTop:5}}> <Text style = {{textAlign:'center', fontSize:12, color:'rgba(255,255,255,0.6)'}}>Tăng âm lượng</Text> </View> </View> <View style = {mainStyle.content_goi_3b}> <TouchableOpacity style = {mainStyle.iconGoi}> <Image source={require('../assets/iconLoaNgoai.png')} style = {{width:30, height:30, resizeMode:'stretch'}}></Image> </TouchableOpacity> <View style = {{flex:2,marginTop:5}}> <Text style = {{textAlign:'center', fontSize:12, color:'rgba(255,255,255,0.6)'}}>Loa Ngoài</Text> </View> </View> <View style = {mainStyle.content_goi_3c}> <TouchableOpacity style = {mainStyle.iconGoi}> <Image source={require('../assets/iconTatTieng.png')} style = {{width:30, height:30, resizeMode:'stretch'}}></Image> </TouchableOpacity> <View style = {{flex:2,marginTop:5}}> <Text style = {{textAlign:'center', fontSize:12, color:'rgba(255,255,255,0.6)'}}>Tắt tiếng</Text> </View> </View> </View> <View style = {mainStyle.content_goi_4}> <TouchableOpacity style = {mainStyle.iconGoi2}> <Image source = {require('../assets/iconPhone3.png')} style = {{width:30, height:30, resizeMode:'contain'}}></Image> </TouchableOpacity> </View> </ImageBackground> ); } } const {height, width} = Dimensions.get('window'); const standarWidth = 360; const standarHeight = 592;
export default ({ require }) => () => { var lib = require('../lib/commonjs/upper'); return lib.testing; }
const questions = require('../src/questions'); it('should have four questions', () => { expect(questions.length).toBe(4); });
/** * Created by zhuo on 2017/9/3. */ var mainState = {//the main dialog & the game preload: function () { console.log('call::preload()'); // game.load.tilemap('tile_map', './js/assets/fuck.json', null, Phaser.Tilemap.TILED_JSON); // game.load.image('tiles1', './js/assets/west_rpg.png'); // game.load.image('tiles2', './js/assets/the_man_set.png'); // // game.load.tilemap('shop_map', './js/assets/home.json', null, Phaser.Tilemap.TILED_JSON); // game.load.image('poke_out', './js/assets/poke_out.png'); // // game.load.spritesheet('GM', './js/assets/the_man_set.png', 32, 32); }, create: function () { console.log('call::create()'); //初始化玩家函数之类的 initPlayer(); //加载存档,地图初始化 MyAchiveManager.loadArchives(); currentCustomState = mainState; cursor = game.input.keyboard.createCursorKeys(); //init dialogs // itemDialog.init(); // roleDialog.init(); // menuDialog.init(); // fightState.init(); // fightItemDialog.init(); // selectEnemyDialog.init(); // myAlertDialog.init(); // itemShowDialog.init(); // equipShowDialog.init(); }, render: function () { }, update: function () { }, init: function () { }, initPlayer: function () { initPlayer(); }, goLeft: function () { player.goLeft(); }, goRight: function () { player.goRight(); }, goUp: function () { player.goUp(); }, goDown: function () { player.goDown(); }, aDown: function () { //触发感兴趣事件 var x = player.tile.x; var y = player.tile.y; if (player.facing == 0) { y = y - 1; } else if (player.facing == 1) { y = y + 1; } else if (player.facing == 2) { x = x - 1; } else if (player.facing == 3) { x = x + 1; } map.playerInterestOn(x, y); }, bDown: function () { player.bDown(); }, fixCameraTo: function (x, y) { // game.camera.focusOnXY(x, y); }, reOpen: function () { map.reOpen(); }, close: function () { map.close(); }, setVisible: function (visible) { map.setVisible(visible); }, gameReset: function () { map.destroy();//清空地图group game.state.restart(false);//保留group信息,不需要重新创建 }, update: function () { current_cold_down_time--; if (current_cold_down_time > 0)return; if (game.input.keyboard.isDown(Phaser.Keyboard.A)) { currentCustomState.goLeft(); } else if (game.input.keyboard.isDown(Phaser.Keyboard.D)) { // console.log('D down'); currentCustomState.goRight(); } else if (game.input.keyboard.isDown(Phaser.Keyboard.W)) { currentCustomState.goUp(); } else if (game.input.keyboard.isDown(Phaser.Keyboard.S)) { currentCustomState.goDown(); } else if (game.input.keyboard.isDown(Phaser.Keyboard.J)) { currentCustomState.aDown(); } else if (game.input.keyboard.isDown(Phaser.Keyboard.K)) { currentCustomState.bDown(); } else return; current_cold_down_time = oper_cold_down_time; } }
define(["constants"], function(constants){ var ScoreManager = function(){ this.score = 0; this.lines = 0; this.level = 1; var linesToNextLevel = constants.LINES_PER_LEVEL; this.getScore = function(){return this.score;}; this.getLines = function(){return this.lines;}; this.getLevel = function(){return this.level;}; this.updateWithLines = function(lines){ console.log("updating score"); this.lines += lines; var multiplier = constants.LEVEL_SCORE_MULTIPLIERS[lines]; console.log("multiplier: " + multiplier); this.score += multiplier * this.level; linesToNextLevel -= lines; if (linesToNextLevel <= 0){ linesToNextLevel += constants.LINES_PER_LEVEL; this.level += 1; } console.log("score updated: "+this.score+", "+this.level+", "+this.lines); }; }; return ScoreManager; });
import { fromJS } from 'immutable'; import userInputContainerReducer from '../reducer'; describe('userInputContainerReducer', () => { it('returns the initial state', () => { expect(userInputContainerReducer(undefined, {})).toEqual(fromJS({})); }); });
import React, { useState ,useEffect} from 'react'; import { post ,get} from "@u/http"; import { NavBar, Icon,Modal } from 'antd-mobile'; import { useHistory } from 'react-router-dom' import { Wrap, Main } from './Login.styled.js' import back from '@a/images/iconku/u529.png' import headPic from '@a/images/iconku/u4996.png' import phone from '@a/images/iconku/u5000.png' import line from '@a/images/iconku/u4997.png' import lock from '@a/images/iconku/lock.png' import lock1 from '@a/images/iconku/lock1.png' import eyeC from '@a/images/iconku/eyeC.png' import eyeO from '@a/images/iconku/eyeO.png' import wechat from '@a/images/iconku/wechat.png' import qq from '@a/images/iconku/qq.png' import sina from '@a/images/iconku/sina.png' import { Toast, WhiteSpace, WingBlank, Button } from 'antd-mobile'; const alert = Modal.alert; const Login = (props) => { const [addClass, setAddClass] = useState(false); const history = useHistory(); const [countData, setCountData] = useState(); const showToast = () =>{ Toast.info('请填入账号信息', 2); } const showToast2 = () =>{ Toast.info('请填入正确的手机号', 2); } const showToast3 = () =>{ Toast.info('账号或密码错误', 2); } const open = () => { setAddClass(true) } const close = () => { setAddClass(false) } useEffect(() => { console.log(history.location); },[]) const loginClick = () =>{ if (!countData) { showToast(); return; } else { console.log(countData.user); if (!(/admin/.test(countData.user)) && !(/^1[3|4|5|6|7|8][0-9]{9}$/.test(countData.user)) ) { showToast2(); return } else { (async () => { let ru = await post(`http://39.97.248.187:8080/shop-1.0-SNAPSHOT/user/login`, { uname: countData.user, upwd: countData.password }) if (ru.code === 0) { localStorage.setItem('userState', JSON.stringify(ru)); Toast.info('登录成功,正在跳转...', 1); console.log(ru); setTimeout(() => { history.push('/home') }, 1000); } else { showToast3(); console.log(ru); } })() } } } return ( <Wrap> <img src={back} alt="" className="back" onClick={() => { history.push('/Home') }}/> <span className="create" onClick={() => { history.push('/SignIn') }}> 创建账号 </span> <div className="head"> <img src={headPic} alt="" className="headPic"/> </div> <form action="" className="form"> <img src={phone} alt="" className="phone"/> <img src={line} alt="" className="line"/> <input type="text" className="tel" placeholder='输入手机号码' onChange={ (e)=>{ let teleNum=e.target.value; setCountData({ ...countData, user:teleNum, })} }/> <img src={lock} alt="" className="lock"/> <img src={lock1} alt="" className="lock1"/> <img src={line} alt="" className="line1"/> <input type={addClass ? 'text' : 'password'} className="password" placeholder='输入密码' onChange={ (e)=>{ let passNum=e.target.value; setCountData({ ...countData, password:passNum, })}} /> <img src={eyeC} alt="" className="eyeC" style={{ display: `${addClass ? "none" : "block"}`, }} onClick={open}/> <img src={eyeO} alt="" className="eyeO" style={{ display: `${addClass ? "block" : "none"}`, }} onClick={close} /> <span className="forget">忘记密码</span> </form> <div className="button" onClick={ loginClick }>登录</div> <img src={wechat} alt="" className="wechat"/> <img src={qq} alt="" className="qq"/> <img src={sina} alt="" className="sina"/> <span className="weichat1">微信</span> <span className="qq1">QQ</span> <span className="sina1">微博</span> </Wrap> ); } export default Login;
import React from 'react' const Titulo = () => { return ( <h1 className='titulo titulo-principal'>ADMINISTRADOR DE PACIENTES</h1> ) } export default Titulo
import './styles.css' import {Todo, TodoList} from './js/classes' import { crearTodoHTML } from './js/componentes.js' export const todolist = new TodoList(); // todolist.todos.forEach(todo => crearTodoHTML( todo ) ); todolist.todos.forEach( crearTodoHTML ); console.log(todolist);
import React, { useState } from 'react'; import { StyleSheet } from 'react-native'; import { AppLoading } from 'expo'; import MainNavPage from './src/pages/main_nav/MainNavPage'; import OtherUserProfilePage from './src/pages/off-nav/OtherUserProfilePage'; import CorkboardPage from './src/pages/off-nav/CorkboardPage'; import HugInfoPage from './src/pages/off-nav/HugInfoPage'; import UserProfilePage from './src/pages/off-nav/UserProfilePage'; import LoginPage from './src/pages/onboarding/LoginPage'; import LaunchPage from './src/pages/onboarding/LaunchPage'; import SignupPage from './src/pages/onboarding/SignupPage'; import PicUploadPage from './src/pages/onboarding/PicUploadPage'; import NamePage from './src/pages/onboarding/NamePage'; import WelcomePage from './src/pages/onboarding/WelcomePage'; import ForgotPasswordPage from './src/pages/onboarding/ForgotPasswordPage'; import ResetPasswordPage from './src/pages/off-nav/ResetPasswordPage'; import SearchPage from './src/pages/off-nav/SearchPage'; import HugSearchPage from './src/pages/off-nav/HugSearchPage'; import EditProfilePage from './src/pages/off-nav/EditProfilePage'; import { NavigationContainer } from '@react-navigation/native'; import { createStackNavigator } from '@react-navigation/stack'; import CreateHugPage from './src/pages/off-nav/CreateHugPage'; import CatchHugPage from './src/pages/off-nav/CatchHugPage'; import { DimensionContextProvider } from './src/contexts/DimensionContext'; import UserContextProvider from './src/contexts/UserContext'; import { useFonts } from 'expo-font'; import { EBGaramond_400Regular, EBGaramond_500Medium, EBGaramond_600SemiBold, } from '@expo-google-fonts/eb-garamond'; import { Montserrat_400Regular, Montserrat_500Medium, Montserrat_600SemiBold } from '@expo-google-fonts/montserrat'; export default function App() { const Stack = createStackNavigator(); let [fontsLoaded] = useFonts({ EBGaramond_400Regular, EBGaramond_500Medium, EBGaramond_600SemiBold, Montserrat_400Regular, Montserrat_500Medium, Montserrat_600SemiBold }); if (!fontsLoaded) { return <AppLoading /> } else { return ( <UserContextProvider> <DimensionContextProvider> <NavigationContainer> <Stack.Navigator style={styles.appContainer} initialRouteName='Launch Page' /** * comment out the line below when you need the header for /* going back to the previous screen. Leave it to see what /* the app will actually look like * */ screenOptions={{ headerShown: false, gestureEnabled: false }} > <Stack.Screen name="Main Nav Page" component={MainNavPage} /> <Stack.Screen name="Create Hug" component={CreateHugPage}/> <Stack.Screen name="Friend Profile" component={OtherUserProfilePage} /> <Stack.Screen name="Corkboard" component={CorkboardPage}/> <Stack.Screen name="Hug Info" component={HugInfoPage} /> <Stack.Screen name='Login Page' component={LoginPage} /> <Stack.Screen name='Signup Page' component={SignupPage}/> <Stack.Screen name='Launch Page' component={LaunchPage}/> <Stack.Screen name='Pic Upload Page' component={PicUploadPage}/> <Stack.Screen name='Name Page' component={NamePage}/> <Stack.Screen name='Welcome Page' component={WelcomePage}/> <Stack.Screen name='User Profile Page' component={UserProfilePage}/> <Stack.Screen name='Reset Password Page' component={ResetPasswordPage}/> <Stack.Screen name='Catch Hug Page' component={CatchHugPage}/> <Stack.Screen name='Hug Search Page' component={HugSearchPage}/> <Stack.Screen name='Search Page' component={SearchPage}/> <Stack.Screen name='Edit Profile Page' component={EditProfilePage}/> <Stack.Screen name='Forgot Password' component={ForgotPasswordPage}/> </Stack.Navigator> </NavigationContainer> </DimensionContextProvider> </UserContextProvider> ); } } const styles = StyleSheet.create({ appContainer: { backgroundColor: 'transparent', } })
const ObjectId = require('mongoose').Types.ObjectId exports.checkMongoIdEql = (mongoId, str) => { if (ObjectId.isValid(mongoId)) { return (mongoId.toString() === str) } else { return false } }
#!/usr/bin/env node const cli = require('command-line-args') const json = require('prettyjson') const argumentsDefinition = [ { name: 'insert', alias: 'i', type: Boolean, description: 'Command to insert a new training model.' }, { name: 'status', alias: 's', type: Boolean, description: 'Command to check the training status of an existing model.' }, { name: 'project', alias: 'p', type: String, description: 'Project ID to use' }, { name: 'model', alias: 'm', type: String, description: 'Location of the model in Google Cloud Storage. Example: some_bucket/my_file.txt' }, { name: 'model-id', alias: 'o', type: String, description: "ID to associate with the model to create (can be any unique string that's easy to remember)" }, { name: 'help', alias: 'h', type: Boolean } ] const options = cli(argumentsDefinition) if (options.help || (!options.status && !options.insert)) { require('./lib/commands/help')(argumentsDefinition) process.exit() } if (options.status && options.insert) { console.log(json.render({ error: 'Can not insert and check status at the same time.' })) } else if (options.status) { require('./lib/commands/status')(options.project, options['model-id']) } else if (options.insert) { require('./lib/commands/insert')(options.project, options['model-id'], options.model) }
// Register custom input types for AutoForm AutoForm.addInputType('icon', { template: 'afInputIcon', valueOut: function () { return this[0].value; } }); AutoForm.addInputType('img', { template: 'afInputImg', valueOut: function () { // There appears to be a bug where the value of the input defaults to the current url // This ensures that it returns a blank value instead of the URL when there's not a valid // data URL (i.e. a picture) if (this[0].src.substring(0, 5) !== 'data:') { return ''; } else { return this[0].src; } } }); // After successfully saving a card, redirect to the account page and show confirmation AutoForm.hooks({ editCard: { onSuccess: function(formType, result) { Session.set('cardSaveSuccessfulAlert', true); Router.go('account'); }, formToModifier: function(modifier) { // Manually remove null values if array items were remove due to Autoform bug if (modifier.$set.squares) { modifier.$set.squares = _.compact(modifier.$set.squares); } return modifier; } } }); Template.card_edit.helpers({ hideSquares: function() { // If one of the picker's is active, hide the square inputs if (Session.get('image-picker') || Session.get('image-edit') || Session.get('icon-picker')) { return 'hidden'; } }, imagePicker: function() { return Session.get('image-picker'); }, imageEdit: function() { return Session.get('image-edit'); }, iconPicker: function() { return Session.get('icon-picker'); }, // Next several methods figure out what to send to autoform // If there's already data in the data context, we're updating an existing card isUpdate: function() { if (!$.isEmptyObject(this)) { return true; } }, formType: function() { if ($.isEmptyObject(this)) { return 'method'; } else { return 'method-update'; } }, formMethod: function() { if ($.isEmptyObject(this)) { return 'insertCard'; } else { return 'updateCard'; } }, formDoc: function() { if ($.isEmptyObject(this)) { return null; } else { return this; } }, formTitle: function() { if ($.isEmptyObject(this)) { return 'Add'; } else { return 'Edit'; } }, categoryOptions: function() { return [ {label: 'Travel', value: 'Travel'}, {label: 'Kids', value: 'Kids'}, {label: 'Events', value: 'Events'}, {label: 'Fashion', value: 'Fashion'}, {label: 'Sports', value: 'Sports'}, {label: 'Work', value: 'Work'}, {label: 'Wildlife', value: 'Wildlife'}, {label: 'TV/Movies', value: 'TV/Movies'}, {label: 'Misc', value: 'Misc'} ]; }, colorOptions: function() { return [ {label: 'White', value: 'white'}, {label: 'Yellow', value: 'yellow'}, {label: 'Black', value: 'black'}, {label: 'Blue', value: 'blue'}, {label: 'Green', value: 'green'}, {label: 'Red', value: 'red'}, ]; } }); Template.card_edit.onRendered(function() { // Clear any display session data to start from a clean slate Session.set('image-edit', false); Session.set('image-picker', false); Session.set('icon-picker', false); Session.set('current-image', ''); Session.set('current-icon', ''); }); Template.card_edit.events({ 'click #preview': function (event, template) { event.preventDefault(); // Initialize empty object to pass to modal var data = {}; // Make a new dummy player var p = new player; p.name = 'Preview'; // Construct preview squares from the data in the form var squares = []; $('.squares-entry-row').each(function(index, row) { // Compute the square number from the displayed index // Can't use actual index because delete rows remove that index # // Coerces to an int then back to string for the jQuery selector var squareNum = $(row).children().first().text().trim() - 1; // Skip the Add button row if (index !== $('.squares-entry-row').length) { var s = new square; s.text = $("[name='squares."+squareNum+".text']").val(); s.description = $("[name='squares."+squareNum+".description']").val(); s.icon = $("[name='squares."+squareNum+".icon']").val(); s.image = $("[name='squares."+squareNum+".image']").attr('src'); s.checked = false; squares.push(s); } }); // Add a free square var s = new square; s.text = ''; s.description = 'Free Square'; s.icon = 'icon-star'; s.image = ''; s.checked = true; s.free = true; // 9 instead of 8 because the autoform puts the "Add" button in a row if ($('.squares-entry-row').length <= 9) { squares.splice(4, 0, s); squares.length = 9; data.size = 3; } else { squares.splice(12,0,s); squares.length = 25; data.size = 5; } //Construct the data context and call the modal p.squares = squares; data.player = p; data.opponent = false; data.small = false; data.textColor = $("[name='textColor']").val(); Modal.show('card_preview_modal', data); }, 'click #export-card': function (event, template) { event.preventDefault(); // Create a JSON version of the card and download it var card = this; var json = JSON.stringify(card); download(json, this.title + '.json', 'text/plain'); } }); Template.afArrayField_squares.helpers({ indexForDisplay: function(x) { return x + 1; } }); Template.afObjectField_squaresObjectField.helpers({ thisName: function(field) { return this.name + field; } }); Template.afInputImg.helpers({ squareIcon: function() { if (this.value.substring(0, 4) === 'icon') { return this.value; } } }); Template.afInputIcon.helpers({ noIcon: function() { if (!this.value || this.value.substring(0, 4) !== 'icon') { return true; } } }); Template.afInputIcon.events({ 'click .open-icon-picker': function (event, template) { // Add a class to the chosen square so we know where to put the icon $(event.target).addClass('pending-icon'); // Show the icon picker with any existing icon for that square Session.set('current-icon', $('.pending-icon input').val()); Session.set('icon-picker', true); } }); Template.afInputImg.events({ 'click .open-image-picker': function (event, template) { // Add a class to the chosen square so we know where to put the image $(event.target).addClass('pending-image'); // Show the image picker with any existing image for that square Session.set('current-image', $(event.target).attr('src')); Session.set('image-picker', true); } });
export const API = "http://13.209.17.252:8000"; export const LOGIN = `${API}/user/signin`; export const SEND_AUTH_NUMBER = `${API}/user/signup/sms_request`; export const CHECK_AUTH_NUMBER = `${API}/user/signup/sms_authentication`; export const USER_SIGNUP = `${API}/user/signup`; export const GET_SUFING_DATA = `${API}/product/list?order=-price&category=8&offset=0&limit=10`; export const GET_MAIN_DATA = (order, category) => { return `${API}/product/list?order=${order}&category=${category}`; }; export const GET_RECOMMEND_DATA = (order) => { return `${API}/product/list?order=${order}`; }; export const HJ_Feed_API = "http://13.209.17.252:8000/board/feed_list?limit=20&offset=0"; export const Search_API = (query) => `${API}/product/list?order=-price&search_keyword=${query}`;
var supportedFileTypes = require('./supported-file-types'); var wmoUtils = require('./utils'); // Public API //module.exports = WebsocketMessageObject; //========================================================================================================= let wmoHeader = { FilesHeaderOffset:0, FilesHeaderSize:0, FilesTotalSize:0, JsonOffset:0, JsonSize:0, StringsOffset:0, StringsSize:0 }; function readWmoHeader(dataFromServer){ //NOTE: dataFromServer is expected to be an ArrayBuffer. //If not, first convert the dataFromServer into ArrayBuffer, then pass to this function. var BIGendian = false; var LITTLEendian = true; let dataView = new DataView(dataFromServer); //console.log("dataView.byteLength = "+dataView.byteLength); let wmoheader = { FilesHeaderOffset:Number(dataView.getUint32(0,BIGendian)), FilesHeaderSize:Number(dataView.getUint32(4,BIGendian)), FilesTotalSize:Number(dataView.getUint32(8,BIGendian)), JsonOffset:Number(dataView.getUint32(12,BIGendian)), JsonSize:Number(dataView.getUint32(16,BIGendian)), StringsOffset:Number(dataView.getUint32(20,BIGendian)), StringsSize:Number(dataView.getUint32(24,BIGendian)) }; return wmoheader; } function readFilesHeader(filesBytes, hedrSize){ //NOTE: dataFromServer is expected to be an ArrayBuffer. //If not, first convert the dataFromServer into ArrayBuffer, then pass to this function. var BIGendian = false; var LITTLEendian = true; //read the headers part from the whole binary stream that contains files data and meta info. let wmofHeaderBinary = new Uint8Array(filesBytes, 0, (hedrSize+1) ); let dataView = new DataView(wmofHeaderBinary.buffer); let noOfFiles = Number(dataView.getUint8(0, BIGendian)); //the object to be returned: let filezheader = { NumberOfFiles:noOfFiles, FilesOffsets:Array.from((new Uint32Array( filesBytes.slice(1, (4*noOfFiles)+1) )), ), FilesSizes:Array.from((new Uint32Array( filesBytes.slice(1+(4*noOfFiles), ((4*noOfFiles)*2)+1) )), ), FilesTypes:Array.from((new Uint32Array( filesBytes.slice(1+((4*noOfFiles)*2), ((4*noOfFiles)*3)+1) )), n=>Number(n) ) //FilesOffsets:Array.from((new Uint32Array( filesBytes.slice(1, (4*noOfFiles)+1) )), bits=>Number(bits) ), //FilesSizes:Array.from((new Uint32Array( filesBytes.slice(1+(4*noOfFiles), ((4*noOfFiles)*2)+1) )), bits=>Number(bits) ), //FilesTypes:Array.from((new Uint32Array( filesBytes.slice(1+((4*noOfFiles)*2), ((4*noOfFiles)*3)+1) )), bits=>Number(bits) ) }; //convert all elements of the above 3 arrays into BIG endian, then into numbers/integers. for (var k in filezheader.FilesOffsets){ filezheader.FilesOffsets[k] = Number((new DataView( filesBytes.slice(1, ((4*noOfFiles)+1)) )).getUint32((4*k), BIGendian)); filezheader.FilesSizes[k] = Number((new DataView( filesBytes.slice(1+(4*noOfFiles), ((4*noOfFiles)*2)+1) )).getUint32((4*k), BIGendian)); filezheader.FilesTypes[k] = Number((new DataView( filesBytes.slice(1+((4*noOfFiles)*2), ((4*noOfFiles)*3)+1) )).getUint32((4*k), BIGendian)); } console.log("wmo:___________________>>"); console.log("=filezheader.NumberOfFiles =", filezheader.NumberOfFiles); console.log("=filezheader.FilesOffsets[0] =", filezheader.FilesOffsets[0]); console.log("=filezheader.FilesSizes[0] =", filezheader.FilesSizes[0]); console.log("=filezheader.FilesTypes[0] =", filezheader.FilesTypes[0]); console.log("wmo: /__________________>>"); return filezheader; } function WebsocketMessageObject(objectname) { objectname = objectname || "wmo"; if (!(this instanceof WebsocketMessageObject)) { return new WebsocketMessageObject(); } this.Objectname = objectname; this.BinaryData = null //to be defined later as arrayBuffer with appropriate size this._filezLength = 0; this._jsonnLength = 0; this._stringzLength = 0; this.filez = []; //array of files. functions will keep appending until Build() is called this.jsonn = {}; //variable to hold jsob object. A function will set it before Build() is called this.stringz = []; //array of strings. functions will keep appending until Build() is called //--------Encoders-------- this.setFilesSize = function(size){ this._filezLength=size; } this.setJsonSize = function(size){ this._jsonnLength=size; } this.setStringsSize = function(size){ this._stringzLength=size; } this.addToFilesSize = function(size){if(!isNaN(size)){ if(typeof(size)==="string"){size=Number(size);} this._filezLength+=size; }else{ console.log("'"+size+"'"+" is not a number. The function: '"+this.Objectname+".addToFilesSize()' expects a number ");} } this.addToJsonSize = function(size){if(!isNaN(size)){ if(typeof(size)==="string"){size=Number(size);} this._jsonnLength+=size;}else{ console.log("'"+size+"'"+" is not a number. The function: '"+this.Objectname+".addToJsonSize()' expects a number. ");} } this.addToStringsSize = function(size){if(!isNaN(size)){ if(typeof(size)==="string"){size=Number(size);} this._stringzLength+=size;}else{ console.log("'"+size+"'"+" is not a number. The function: '"+this.Objectname+".addToStringsSize()' expects a number ");} } this.AddFile = function(file) { if(file.name){ this.filez.push(file); let file_size = file.size; if(supportedFileTypes.findFileTypeIndex(file.type)!=99){ this.addToFilesSize(file_size); } } }; this.AddFileFrom = function(fileInputId) { const file = document.getElementById(fileInputId).files[0]; if(file.name){ this.filez.push(file); let file_size = file.size; if(supportedFileTypes.findFileTypeIndex(file.type)!=99){ this.addToFilesSize(file_size); } } }; this.AddFiles = function(filesArray) { }; this.AddJson = function(myjson) { this.jsonn = myjson; let json_size = JSON.stringify(this.jsonn).length; this.setJsonSize(json_size); }; this.AddString = function(keyy,mystring) { if (typeof(mystring)==='string') { var str = keyy+'-'+mystring; this.stringz.push(str); //determine the size of the string we have just added, then increment the _stringzLength by that size. let str_size = str.length; this.addToStringsSize(str_size); }else{ this._error(new Error('The function AddString() expects a string')); return; } }; this.AddStringFrom = function(keyy, textInputId) { const strng = document.getElementById(textInputId).value; if (typeof(strng)==='string') { //append the string to stringz[] array of this object. var str = keyy+'-'+strng; this.stringz.push(str); //determine the size of the string we have just added, then increment the _stringzLength by that size. let str_size = str.length; this.addToStringsSize(str_size); }else{ this._error(new Error('The function AddStringFrom() expects a string')); return; } }; this.Encode = function() { /* 0 28 31 files-content json strings |--,--,--,--,--,--,--|-|~~|--,--,...,--,...|-----,-------,---,...|-------------------------------|-------| wmo-header files-header 0 # |<-----------------files-------------->| */ /* You can use the following function to determine the endianness of a platform. const BIG_ENDIAN = Symbol('BIG_ENDIAN'); const LITTLE_ENDIAN = Symbol('LITTLE_ENDIAN'); function getPlatformEndianness() { let arr32 = Uint32Array.of(0x12345678); let arr8 = new Uint8Array(arr32.buffer); switch ((arr8[0]*0x1000000) + (arr8[1]*0x10000) + (arr8[2]*0x100) + (arr8[3])) { case 0x12345678: return BIG_ENDIAN; case 0x78563412: return LITTLE_ENDIAN; default: throw new Error('Unknown endianness'); } } //---------- //convert arraybuffer to blob var array = new Uint8Array([0x04, 0x06, 0x07, 0x08]); var blob = new Blob([array]); //---------- */ var BIGendian = false; var LITTLEendian = true; //alternative way to check the endianness of this machine var isLittleEndian = (function() { var buffer = new ArrayBuffer(2); new DataView(buffer).setInt16(0, 256, true); //true -> littleEndian // Int16Array uses the platform's endianness. return new Int16Array(buffer)[0] === 256; })(); var logmessage = isLittleEndian?"The endianness of this machine is : LittleEndian":"The endianness of this machine is : bigEndian"; console.log(logmessage); this.AddString("ends","rightpadding"); var filez_start_point; var json_start_point; var stringz_start_point; var file_offsets = []; var file_sizes = []; var file_types = []; var total_size_of_files = 0; var wmo_offset_track = 31; //28 bytes (4*7) for the wmo header,1 for endianness, 2 for 'dont care' bytes, 1 byte for holding number of files var files_ofst_track = 0; var numberoffilez = supportedFileTypes.countSupportedFilesOnly(this.filez); var size_of_files_header=1+(numberoffilez*(4+4+4)); //1 byte holds No.of files, 4 bytes(size of uint32) for each file_sizes[element], 4 bytes for each file_offsets[element] and 4 bytes for each file_types[element] total_size_of_files += size_of_files_header; wmo_offset_track =31 + size_of_files_header; //increment the '*_track' by 'size_of_files_header' files_ofst_track = 0 + size_of_files_header; //ready to create the BinaryData this.BinaryData = new ArrayBuffer(31+size_of_files_header+this._filezLength+this._jsonnLength+this._stringzLength+8); //8 is some extra just in case we need it. //console.log("total size = "+(31+size_of_files_header+this._filezLength+this._jsonnLength+this._stringzLength+8)); let mainHeaderView = new Uint32Array(this.BinaryData, 0, 7); //Uint32Array(buffer, offset, size); where 'size' is the number of items with the specific size eg 32 bits in this case. let endiannessView = new Uint8Array(this.BinaryData, 28, 1); let dontCareView = new Uint8Array(this.BinaryData, 29, 2); let noOfFilesView = new Uint8Array(this.BinaryData, 31, 1); let fileOffsetsView = new Uint32Array(this.BinaryData, 32, numberoffilez); let fileSizesView = new Uint32Array(this.BinaryData, (32+(1*(4*numberoffilez))), numberoffilez); let fileTypesView = new Uint32Array(this.BinaryData, (32+(2*(4*numberoffilez))), numberoffilez); let filesDataView = new Uint8Array(this.BinaryData, (32+(3*(4*numberoffilez))), this._filezLength); let filesDataStart = (32+(3*(4*numberoffilez))); wmo_offset_track=filesDataStart; let jsonDataView = new Uint8Array(this.BinaryData,(filesDataStart+this._filezLength), this._jsonnLength); let jsonDataStart = (filesDataStart+this._filezLength); let stringsDataView = new Uint8Array(this.BinaryData,(jsonDataStart+this._jsonnLength), this._stringzLength); //console.log("strings offset = "+(jsonDataStart+this._jsonnLength)+" - size="+(this._stringzLength)); //loop through files to get info about each of them, //and write each into wmo.BinaryData. wmo_offset_track=filesDataStart; var fdataOffsett=0; for (var i in this.filez) { //transform a file into arraybuffer const freadr = new FileReader(); freadr.readAsArrayBuffer(this.filez[i]); //create a view of the arraybuffer let fileBytesView = new Uint8Array(freadr.result); //determine the bytelength of the typed array var fiLength = fileBytesView.byteLength; var fiType = supportedFileTypes.findFileTypeIndex(this.filez[i].type); if(fiType != 99){ //99 is for unsupported file types. file_offsets.push(files_ofst_track); file_sizes.push(fiLength); file_types.push(fiType); filesDataView.set(fileBytesView,fdataOffsett); total_size_of_files += fiLength; files_ofst_track += fiLength; wmo_offset_track += fiLength; fdataOffsett+=fiLength; } } //read everything that is in 'this.jsonn', stringfy & make it binary, //then add to this.BinaryData at appropriate offset. wmo_offset_track=jsonDataStart; json_start_point = wmo_offset_track; let jsonnstr = JSON.stringify(this.jsonn); let json_size = jsonnstr.length; for (var jchr in jsonnstr){ var ascii = jsonnstr.charCodeAt(jchr); jsonDataView[jchr]=ascii; } wmo_offset_track += json_size; //wmo_offset_track+=this._jsonnLength; //alternative to line above //read everything that is in 'wmo.stringz', make it binary, then //add to this.stringz at appropriate offset. let tmpStr = ""; for (var strIndex in this.stringz) { var oneStr = this.stringz[strIndex]; tmpStr = tmpStr+" "+oneStr; } var strAsciiValues = []; for (var chr in tmpStr){ var ascii = tmpStr.charCodeAt(chr); stringsDataView[chr]=ascii; } let all_strings_size = tmpStr.length+2; stringz_start_point = wmo_offset_track; wmo_offset_track += all_strings_size; //==writing headers== //now write files header info to the this.BinaryData filez_start_point = 31; //28+1+2=31, offset: beginning of 31st byte noOfFilesView.set([numberoffilez],0); //now write sizes and offsets of each file previously written to this.BinaryData for (var i in file_sizes) { let thisFilesize = file_sizes[i]; let thisfdataOffset = file_offsets[i]; let thisfdataType = file_types[i]; fileSizesView.set([thisFilesize],i); fileOffsetsView.set([thisfdataOffset],i); fileTypesView.set([thisfdataType],i); } //write all wmo header attributes at their known file_offsets mainHeaderView.set([filez_start_point],0); mainHeaderView.set([size_of_files_header],1); mainHeaderView.set([total_size_of_files],2); mainHeaderView.set([json_start_point],3); mainHeaderView.set([json_size],4); mainHeaderView.set([stringz_start_point],5); mainHeaderView.set([all_strings_size],6); endiannessView.set([(isLittleEndian?6:112)],0); } this.toString = function () { return '[object WebsocketMessageObject]'; }; //--------Decoders-------- this.DecodeJson = (dataFromServer) => { //NOTE: dataFromServer is expected to be an ArrayBuffer. //If not, first convert the dataFromServer into ArrayBuffer, then pass to this function. let wmoheader = readWmoHeader(dataFromServer); let jsonvieww = new Uint8Array(dataFromServer,wmoheader.JsonOffset, wmoheader.JsonSize); let jsonstr = wmoUtils.typedArrayToString(jsonvieww); let jsonObject = JSON.parse(jsonstr); return jsonObject; } this.ReadFilesBytes = (dataFromServer) => { //NOTE: dataFromServer is expected to be an ArrayBuffer. //If not, first convert the dataFromServer into ArrayBuffer, then pass to this function. let hedr = readWmoHeader(dataFromServer); let filesDataArr = dataFromServer.slice(hedr.FilesHeaderOffset, hedr.FilesTotalSize); //hedr.FilesHeaderOffset = 31 always. return filesDataArr; } this.DecodeFiles = (dataFromServer, returnDataUrls=false) => { //NOTE: dataFromServer is expected to be an ArrayBuffer. //If not, first convert the dataFromServer into ArrayBuffer, then pass to this function. let types = supportedFileTypes.filetypes; let preferDataUrls = returnDataUrls //if false is passed, file objects will be returned instead of data URLs var hedr = readWmoHeader(dataFromServer); let filesBytes = this.ReadFilesBytes(dataFromServer); let files_hedr = readFilesHeader(filesBytes, hedr.FilesHeaderSize); console.log("wmo: files_hedr = ", files_hedr); console.log("wmo: files_hedr.FilesOffsets = ", files_hedr.FilesOffsets); let filesWithKeys = []; for(var i in files_hedr.FilesOffsets){ console.log("=for-loop: files_hedr.FilesOffsets ... "); let oneFileTypedArr = new Uint8Array( filesBytes.slice(files_hedr.FilesOffsets[i], (files_hedr.FilesOffsets[i] + files_hedr.FilesSizes[i] + 1) ) ); //From the typedarray 'oneFileView', decode a single file and acquire its File object or image URL /* * The File constructor (as well as the Blob constructor) takes an array of parts. * A part doesn't have to be a DOMString. It can also be a Blob, File, or a typed array. * You can easily build a File out of a Blob like this: * let file = new File([blob], "filename"); * //--- */ var fyleDataType = types[files_hedr.FilesTypes[i]].type; let generateKey = (fyltype)=>{ var offset = files_hedr.FilesOffsets[i]; var sizze = files_hedr.FilesSizes[i]; if(!Date.now){ Date.now = function(){return new Date().getTime(); }} var currentTimestamp = Date.now(); return fyltype+"_"+offset+""+sizze+""+currentTimestamp; } //var blob = new Blob( [ oneFileTypedArr ], { type: "image/png" } ); //can use this, but var blob = new Blob( [ oneFileTypedArr ], { type: fyleDataType } ); //this is more dynamc var filename = "file"+files_hedr.FilesOffsets[i]+files_hedr.FilesSizes[i]; //var file = new File([blob], filename, {type:"image/png", lastModified:new Date()}); var file = new File([blob], filename, {type:fyleDataType, lastModified:new Date()}); var urlCreator = window.URL || window.webkitURL; var dataUrl = urlCreator.createObjectURL( blob ); //generate a unique key for this file //let newKey = generateKey(fyleDataType); console.log("wmo: file key = ", i); //add the file data into the reuturned array with its generated key specified (associative array). if(preferDataUrls){ filesWithKeys[i] = dataUrl; }else{ filesWithKeys[i] = file; } /* * let imageUrl = dataUrl; * var img = document.querySelector( "#photo" ); * img.src = imageUrl; * urlCreator.revokeObjectURL(); */ console.log("wmo: filesWithKeys.length : "); console.log(filesWithKeys.length); console.log("filesWithKeys[",i,"] : "); console.log(filesWithKeys[i]); } return filesWithKeys; } this.DecodeStringAll = (dataFromServer) => { //NOTE: dataFromServer is expected to be an ArrayBuffer. //If not, first convert the dataFromServer into ArrayBuffer, then pass to this function. let wmoheader = readWmoHeader(dataFromServer); let stringsview = new Uint8Array(dataFromServer,wmoheader.StringsOffset, wmoheader.StringsSize); let stringz = wmoUtils.typedArrayToString(stringsview); //split the 'stringz' content using dilimitors and create a map of strings with string keys. let strArray = stringz.split(" "); //splitting using spaces: stringz = 'key1-value1 key2-value2 key3-value3 ...' var newStrMap = []; strArray.forEach(function(val){ if(val.includes("-")){ let strkey = val.split('-')[0]; let strval = val.split('-')[1]; newStrMap[strkey] = strval; } }); return newStrMap } this.DecodeString = (dataFromServer,strkey) => { //NOTE: dataFromServer is expected to be an ArrayBuffer. //If not, first convert the dataFromServer into ArrayBuffer, then pass to this function. let newStrMap = this.DecodeStringAll(dataFromServer); return newStrMap[strkey]; } this.FindFileTypeIndex = (filetype)=>{ for(var i in supportedFileTypes.filetypes){ if(filetype==supportedFileTypes.filetypes[i].type){ return i; } } console.warn("Encoding/decoding of unsupported file type: '"+filetype+"' skipped."); return 99; //this will be used to indicate that file format is unsupported. }; this.toString = () => { return '[Object WebsocketMessageObject]'; } } //export const wmo = new WebsocketMessageObject(); //uncomment this line if you don't want to create an object yourself from your application. export WebsocketMessageObject; //use this if you want to create your own object like: let wmo = new WebsocketMessageObject(); //========================================================END========================================================
import modalhandler from '../Helper/Modal_plugin'; import fixSvTextHandler from '../Helper/fixSvTextHelper'; import questinfoHandler from '../components/doquestInfo'; const doQuestEventHandler = userid => { // bind functions let qinfohandler = questinfoHandler(); let mod = modalhandler(); let txtfix = fixSvTextHandler(); let mainappGame = ''; if (typeof mainbibblomongameapp === typeof Function) { mainappGame = mainbibblomongameapp(); } let hbtemplate = ''; let ModalcontcssID = '#bb_aj_GenericModalContainer'; let $bb_aj_GenericModalContainer = $(ModalcontcssID); //bind events $('body').on('click', '.bb_aj_QuestToDo', showquestmodal); $bb_aj_GenericModalContainer.on('click', '#bb_aj_dosubquest', dothesubquest); $bb_aj_GenericModalContainer.on( 'click', '#bb_aj_doinputsubquest', doInputsubquest ); $('body').on('click', '.bb_aj_QuestToDo', showquestmodal); $bb_aj_GenericModalContainer.on('click', '#bb_aj_dosubquest', dothesubquest); $bb_aj_GenericModalContainer.on( 'click', '#bb_aj_doinputsubquest', doInputsubquest ); $bb_aj_GenericModalContainer.on( 'click', '#bb_aj_doGamequest', dotheGameQquest ); // functions function showquestmodal() { let $QuestOption = $(this); let option = { Userid: $('#barnensbiblCurrentUserid').html(), QuestID: $QuestOption.attr('data-questid'), QTriggerID: $QuestOption.attr('data-triggerid'), hbtmpl: $QuestOption.attr('data-hbTempl') }; if (option.Userid > 0) { qinfohandler.showDoQuest(option, data => { mod.open(); }); } return false; } function showsubQuest(qid, Userid, triggerid, hbtmpl) { hbtemplate = hbtmpl; let option = { Userid: Userid, QuestID: qid, QTriggerID: triggerid, hbtmpl: hbtmpl }; let $bb_aj_doQuest = $('.bb_aj_QuestToDo[data-questid=' + qid + ']'); let $bb_aj_QuestRegister = $( '.bb_aj_QuestRegister[data-questid=' + qid + ']' ); let $bb_aj_QuestComplete = $( '.bb_aj_QuestComplete[data-questid=' + qid + ']' ); $bb_aj_QuestRegister.hide(); $bb_aj_QuestComplete.hide(); $bb_aj_doQuest.hide(); if (Userid > 0) { qinfohandler.getStatus(option, data => { switch (data.Statuscode) { case -1: $bb_aj_QuestRegister.show(); $bb_aj_QuestRegister.html('N&aring;got blev fel!'); break; case 0: $bb_aj_QuestRegister.show(); break; case 1: $bb_aj_QuestComplete.show(); break; case 2: $bb_aj_doQuest.show(); break; default: $bb_aj_QuestRegister.show(); } }); } else { console.log('ej inloggad'); } return false; } //////////////////// function dotheGameQquest() { let getval = $('#bb_aj_modalbody'); let option = { Userid: getval.attr('data-userid'), QuestID: getval.attr('data-questid'), QTriggerID: getval.attr('data-triggerid'), uQuestID: getval.attr('data-uquestid'), Svar: getval.attr('data-svar') }; $('#bb_aj_modalbody').attr('data-svar', 'gamestart'); let svarar = mainappGame.winorloose(); if (option.Svar == 'gamestart') { if (option.Userid > 0) { qinfohandler.DoTheQuest(option, () => { setTimeout(() => { mod.close(); showsubQuest( option.QuestID, option.Userid, option.QTriggerID, hbtemplate ); }, 3000); }); } } else { mainappGame.showbokdrakegame(option.Userid); $('#bb_aj_doGamequest').html('Game Over!'); mod.open(); } return false; } /////////////// function dothesubquest() { let getval = $('#bb_aj_modalbody'); let option = { Userid: getval.attr('data-userid'), QuestID: getval.attr('data-questid'), QTriggerID: getval.attr('data-triggerid'), uQuestID: getval.attr('data-uquestid'), Svar: getval.attr('data-svar') }; if (option.Userid > 0) { qinfohandler.DoTheQuest(option, () => { setTimeout(() => { mod.close(); showsubQuest( option.QuestID, option.Userid, option.QTriggerID, hbtemplate ); }, 3000); }); } return false; } function doInputsubquest() { let getval = $('#bb_aj_modalbody'); let getinputval = $('#bb_aj_subquest'); let correctsvar = getval.attr('data-svar'); let svarsMess = $('.bb_aj_Svarat'); let errMess = $('.bb_aj_ErrMess'); let svarsbutton = $('#bb_aj_doinputsubquest'); svarsMess.html(''); errMess.html(''); console.log('inne'); if (getinputval.val() != '') { let option = { Userid: getval.attr('data-userid'), QuestID: getval.attr('data-questid'), QTriggerID: getval.attr('data-triggerid'), uQuestID: getval.attr('data-uquestid'), Svar: getinputval.val() }; if (option.Userid > 0) { if (correctsvar.toLowerCase() == getinputval.val().toLowerCase()) { svarsMess.html( txtfix.fixtext('<h1 style="color:green;">JAAA! Rätt svar!</h1>') ); qinfohandler.DoTheQuest(option, data => { if (data.Statuscode != 2) { $bb_aj_doQuest.hide(); } setTimeout(() => { mod.close(); }, 3000); }); } else { svarsMess.html( txtfix.fixtext('<h1 style="color:red;">NEEJ!! du svarade fel!</h1>') ); setTimeout(() => { mod.close(); svarsMess.html(''); getinputval.val(''); }, 4000); } return false; } } else { errMess.html( txtfix.fixtext( '<h3 style="color:red;">Du måste förstås skriva nått!</h3>' ) ); return false; } return false; } return { showsubquest: showsubQuest }; }; export default doQuestEventHandler;
import React, { Component } from "react"; import "./Card.scss"; class Card extends Component { render() { let { avatar_url, login, score, id } = this.props.user; return ( <div className="gca-card" onClick={() => this.props.handleUserDetail(this.props.user.login, true)} > <div className="gca-card_avatar"> <img className="gca-card_avatar_img" src={avatar_url} alt="img" /> </div> <div className="gca-card_name">@{login}</div> <div className="as">Id: {id} </div> <div className="gca-card_score">Score: {score}</div> </div> ); } } export default Card;
const core = require('@actions/core'); const { promises: fs } = require('fs') async function main() { const path = core.getInput('path'); const changelog = process.env.CHANGELOG; let content = ''; try { content = await fs.readFile(path, 'utf8'); } catch (error) { core.setFailed(error.message); } const regex = /(?<before>^## \d+.\d+.\d+ \(Unreleased\)\n\n)[\s\S]+(?<after>\n\n## \d+.\d+.\d+)/gm let result = content.replace(regex, (...match) => { let groups = match.pop(); return `${groups.before}${changelog}${groups.after}`; }); try { await fs.writeFile(path, result, 'utf8'); } catch (error) { core.setFailed(error.message); } } try { main(); } catch (error) { core.setFailed(error.message); }
require('rootpath')(); const express = require('express'); const app = express(); const cors = require('cors'); const bodyParser = require('body-parser'); const errorHandler = require('_helpers/error-handler'); app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); app.use(cors()); app.options('*', cors()) var jwt = require('express-jwt'); var jwks = require('jwks-rsa'); var jwtCheck = jwt({ secret: jwks.expressJwtSecret({ cache: true, rateLimit: true, jwksRequestsPerMinute: 5, jwksUri: 'https://dev-bwkc1q2n.us.auth0.com/.well-known/jwks.json' }), audience: 'https://dev-bwkc1q2n.us.auth0.com/api/v2/', issuer: 'https://dev-bwkc1q2n.us.auth0.com/', algorithms: ['RS256'] }); // app.use(jwtCheck); app.post('/quiz', jwtCheck, function(req, res,next) { next() }); app.delete('/quiz', jwtCheck, function(req, res,next) { next() }); app.get('/quiz-all', jwtCheck, function(req, res, next) { next() }); const swaggerUi = require('swagger-ui-express') const swaggerFile = require('./swagger_output.json') app.use('/doc', swaggerUi.serve, swaggerUi.setup(swaggerFile)) // api routes app.use('/users', require('./users/users.controller')); app.use('/', require('./quiz/quizs.controller')); // global error handler app.use(errorHandler); // start server const port = process.env.NODE_ENV === 'production' ? (process.env.PORT || 80) : 4000; const server = app.listen(port, function () { console.log('Server listening on port ' + port); });
import React from 'react' import footerStyles from '../styles/components/footer.module.scss' const Footer = () => { return ( <footer className={footerStyles.footer}> <span>Created by Cristiano Crolla, Copyright 2019</span> </footer> ) } export default Footer
/** * Created by BenYin on 11/28/2016. */ exports.render = function (req, res) { if (req.session.lastVisit) { console.log('last session: ' + req.session.lastVisit); } req.session.lastVisit = new Date(); // res.send('Hello World'); res.render('index', { title: 'Hello World' }) };
export const EXAMPLE_CONSTANTS = { EXAMPLE_NAME: 'example', EXAMPLE_COPY: 'example copy' } export const EXAMPLE_CONSTANT = 'EXAMPLE'
$(document).ready(function(){ $("img.thumb").each(function(i){ $(this).css("cursor","pointer").mouseover(function(){ $(this).next(".showThumb").children("div").show(); }).mouseout(function(){ $(this).next(".showThumb").children("div").hide(); }).click(function(){ $(this).next(".showThumb").children("div").hide(); var site_id = $(this).attr('id'); var attach_type = $(this).attr('name'); var attach_ext = '.jpg'; showAttachEdit(this,site_id,attach_type,attach_ext); }); }); $("table td label").each(function(i){ //设置排序数字可编辑 setSortEditable(this,i); }); }); function showAttachEdit(obj,site_id,attach_type,attach_ext){ if(attach_type=='photo'){ var title = '上传形象照(JPG格式,宽150像素)'; } else{ var title = '上传公司Logo(JPG格式,宽150像素)'; } $(".editAttach").remove(); var html = '<span class="editAttach"><div>'; html += title+'<br />'; html += '<img id="loading" src="'+IMAGE_FOLDER+'loadingAnimation.gif" style="position:absolute;left:36px;top:60px;display:none;z-index:999;" aligh="middle">'; html += '<form name="form" action="" method="POST" enctype="multipart/form-data">'; html += '<input type="file" id="attach" class="file" name="attach" /><br />' html += '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="button" value="上传" class="submit"/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="button" value="取消" class="cancel"/>'; html += '</form>'; html += '</div></span>'; $(obj).after(html); $(".editAttach>div").show('slow'); $(".editAttach input.cancel").click(function(){ $(".editAttach>div").hide('slow'); }); $(".editAttach input.submit").click(function(){ if(checkFileExt($("#attach").val(),attach_ext)==false){ return false; } $("#loading").ajaxStart(function(){ $(this).show(); }).ajaxComplete(function(){ $(this).hide(); }); $.ajaxFileUpload({ url:_APP_+'/Attach/upload/t/'+attach_type+'/id/'+site_id, secureuri:false, fileElementId:'attach', dataType: 'text', success: function (data, status) { if(data=='1'){ myAlert('上传成功!'); $(".editAttach").remove(); if(attach_type!='logo'){ $(obj).attr('src',IMAGE_FOLDER+'picture.gif'); $(obj).next(".showThumb").show(); $(obj).next(".showThumb").children("div").hide(); obj = $(obj).next().children('div').children('img'); } $(obj).attr('src',_APP_+'/../Html/Attach/'+attach_type+'/'+site_id+attach_ext+'?'+Math.random()); myOK(1200); } else{ myAlert('上传失败!<br />'+data); } }, error: function (data, status, e) { myAlert(e); } }); }); $(document).keydown(function(e){ var keyCode=e.keyCode ||window.event.keyCode; if(keyCode==27)//取消健 { $(".editAttach>div").hide('slow'); } }); } function checkFileExt(filename,allowed_ext){ var fileext = filename.substr(filename.lastIndexOf('.')).toLowerCase(); if(fileext != allowed_ext){ myAlert("只能上传 "+allowed_ext+" 格式的图片!"); return false; } return true; } function setSortEditable(obj,n){//设置分类排序数字可编辑功能,公用 $(obj).mouseover(function(){ $(this).addClass("editable"); }).mouseout(function(){ $(this).removeClass("editable"); }).click(function(){ html0=$(this).html(); html1='<span><input class="quickedit" type="text" value="'+html0+'" size="'+html0.length+'"> <i class="submit"><img src="'+IMAGE_FOLDER+'accept.gif" alt="提交" align="absmiddle"/></i><i class="cancel"><img src="'+IMAGE_FOLDER+'cancel.gif" alt="取消" align="absmiddle"/></i></span>'; $(this).after(html1).hide(); $(this).next().children("input").select().keydown(function(e){ var keyCode=e.keyCode ||window.event.keyCode; if(keyCode==13)//回车键 { submit_sort(this,n); } else if(keyCode==27)//取消健 { cancel_sort(this,n); } }); $(this).next().children(".submit").css("cursor","pointer").click(function(){ submit_sort(this,n); }); $(this).next().children(".cancel").css("cursor","pointer").click(function(){ cancel_sort(this,n); }); }); } function submit_sort(obj,n){//提交新的分类排序,公用 $("#_iframe").attr("src", _URL_+"/update/id/"+$(obj).parent().prev().attr('id')+"/f/sort/v/"+$(obj).parent().children("input").val()); } function cancel_sort(obj,n){//取消更改分类排序,公用 $(obj).parent().prev().show(); $(obj).parent().remove(); }
import EventEmitter from 'events'; import {spy} from 'sinon'; import test from 'ava'; import {h, build, renderToString, render, Color} from 'ink'; import TextInput from '.'; test('default state', t => { t.is(renderToString(<TextInput/>), ''); }); test('display value', t => { t.is(renderToString(<TextInput value="Hello"/>), '*****'); }); test('display value with custom mask', t => { t.is(renderToString(<TextInput value="Hello" mask="x"/>), 'xxxxx'); }); test('display placeholder', t => { t.is(renderToString(<TextInput placeholder="Placeholder"/>), renderToString(<Color dim>Placeholder</Color>)); }); test.serial('attach keypress listener', t => { const stdin = new EventEmitter(); stdin.setRawMode = spy(); stdin.pause = spy(); const stdout = { write: spy() }; const setRef = spy(); const unmount = render(<TextInput ref={setRef}/>, {stdin, stdout}); const ref = setRef.firstCall.args[0]; t.is(process.stdin.listeners('keypress')[0], ref.handleKeyPress); unmount(); t.deepEqual(process.stdin.listeners('keypress'), []); }); test('ignore ansi escapes', t => { const setRef = spy(); const onChange = spy(); const onSubmit = spy(); build(<TextInput ref={setRef} onChange={onChange} onSubmit={onSubmit}/>); const ref = setRef.firstCall.args[0]; ref.handleKeyPress('', {sequence: '\u001B[H'}); t.false(onChange.called); t.false(onSubmit.called); }); test('handle return', t => { const setRef = spy(); const onChange = spy(); const onSubmit = spy(); build(<TextInput ref={setRef} value="Test" onChange={onChange} onSubmit={onSubmit}/>); const ref = setRef.firstCall.args[0]; ref.handleKeyPress('', {name: 'return'}); t.false(onChange.called); t.true(onSubmit.calledOnce); t.deepEqual(onSubmit.firstCall.args, ['Test']); }); test('handle change', t => { const setRef = spy(); const onChange = spy(); const onSubmit = spy(); build(<TextInput ref={setRef} value="A" onChange={onChange} onSubmit={onSubmit}/>); const ref = setRef.firstCall.args[0]; ref.handleKeyPress('B', {sequence: 'B'}); t.true(onChange.calledOnce); t.deepEqual(onChange.firstCall.args, ['AB']); t.false(onSubmit.called); });
// Do all grunt related stuff inside the grunt function here module.exports = function(grunt) { require('load-grunt-tasks')(grunt); grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), // 1. copy files copy: { main: { files: [{ expand: true, cwd: 'workfiles/', src: ['*.js'], dest: 'dist/copiedfiles/', filter: 'isFile' }, ], }, }, // 2. compile files babel: { options: { sourceMap: true, presets: ['@babel/preset-env'], }, dist: { files: { 'dist/compiled/foo.js': 'dist/copiedfiles/foo.js', 'dist/compiled/bar.js': 'dist/copiedfiles/bar.js' } } }, // 3. concatenate files concat: { options: { separator: ';', }, dist: { src: ['dist/compiled/foo.js', 'dist/compiled/bar.js'], dest: 'dist/compiled/scripts.js' } }, // 4. header and footer insertion header: { dist: { options: { text: '//header inserted in js file' }, files: { 'dist/compiled/headerscripts.js': 'dist/compiled/scripts.js' } } }, footer: { dist: { options: { text: '//footer inserted in js file' }, files: { 'dist/compiled/headerfooterscripts.js': 'dist/compiled/headerscripts.js' } } }, // 5. uglify / compress files uglify: { my_target: { files: { 'dist/compiled/finalscript.js': 'dist/compiled/headerfooterscripts.js' } } }, }); // grunt.loadNpmTasks('grunt-contrib-copy'); grunt.registerTask( 'default', ['copy', 'babel', 'concat', 'header', 'footer', 'uglify']); };
// public/scripts/CompaniesController.js (function() { 'use strict'; angular .module('touchpoint') .controller('CompaniesController', CompaniesController); function CompaniesController($http, $scope, $filter, Alertify, $sce, $state, $stateParams, $timeout, $interval, $document, $anchorScroll) { var vm = this; var entityId = $state.params.id; var apiUrl = '/api/companies'; var _page = 0; var companiesUrl = entityId ? apiUrl + '/' + $state.current.name + '/' + entityId : apiUrl; $scope.error; $scope.comments; $scope.master = {}; vm.choices = {}; vm.savedCompany = {}; $scope.companies = []; $scope.noteBox = {}; $scope.today = function() { $scope.dt = new Date(); }; $scope.today(); $scope.pickerToggle = function($event) { $scope.pickerStatus.opened = !$scope.pickerStatus.opened; }; $scope.timePickerToggle = function($event) { $scope.timePickerStatus.opened = !$scope.timePickerStatus.opened; }; $scope.pickerStatus = { opened: false }; $scope.timePickerStatus = { opened: false }; $scope.hstep = 1; $scope.mstep = 1; $http.get(companiesUrl).success(function(data) { $scope.companies = data; if(entityId){ $scope.entityName = data.entity; } }).error(function(error) { vm.error = error; }); $scope.moreCompanies = function() { _page++; $http.get(companiesUrl + '/page/' + _page).then(function(data) { vm.companies = vm.companies.concat(data); }); }; $scope.formatDate = function(date){ var dateOut = new Date(date.replace(' ', 'T') + 'Z'); return dateOut; }; } })();
import gql from "graphql-tag"; export default gql` mutation CreatePost($pictureUrl: String!, $caption: String!) { createPost(pictureUrl: $pictureUrl, caption: $caption) { id caption pictureUrl } } `;
function show(str) { console.log("Hello" + str); } var timedId = setTimeout(show, 2000, " Vitalik"); console.log(timedId); // clearTimeout(timedId); // setTimeout(function() { // console.log("Qaprosoft"); // }, 2000);
var React = require('react'), BookingIndexItem = require('./index_item'); module.exports = React.createClass({ render: function () { var bookingLis = this.props.bookings.map( function (item, index) { return <BookingIndexItem booking={item} key={index}/>; } ); return ( <div className="booking-index"> <h3>Current Tasks</h3> {bookingLis} </div> ); } });
define(['phaser', 'jquery'], function(Phaser, $) { var SkillsHandler = function(game, gameObject, skillsObject, skillsState) { this._game = game; this._gameObject = gameObject; this._skillsObject = skillsObject; this._text = undefined; this._price = []; this.skillsContainer = []; this.skillsContainerReadOnly = []; this.skillsContainerReadOnly = this.getAllSkills(); if(skillsState) { this.cleanPrice(); this.addButton(this._skillsObject); } }; /** * PARTIE BOUTON */ // Nettoyage de skillsContainer SkillsHandler.prototype.clearSkillsContainer = function() { for(let child in this.skillsContainer) { this.skillsContainer[child].destroy(); } }; //Affiche le nom de la compétence quand on passe la souris dessus SkillsHandler.prototype.overName = function(element){ if(element.alpha){ var style = {font: "23px Arial", fill: "#ffffff"}; this._text = this._game.add.text(this._game.world.centerX - 5, this._game.world.centerY - 20, element.realName, style); this._text.anchor.set(0.5); } }; //Efface le nom de la compétence quand la souris ne la survole pas SkillsHandler.prototype.cleanText = function(element){ if(this._text !== undefined) { this._text.destroy(); } }; //Affiche le prix des compétences non débloquées SkillsHandler.prototype.price = function(element) { var price; if(element.name === 'transEnerg'){ price = this._game.add.text(element.x, element.y - 40, element.cout, {font: "23px Arial", fill: "#ffffff"}); price.anchor.set(-5); } else if(element.name === 'campInfl'){ price = this._game.add.text(element.x, element.y - 40, element.cout, {font: "23px Arial", fill: "#ffffff"}); price.anchor.set(-1.82); } else if(element.name === 'energPol'){ price = this._game.add.text(element.x - 40, element.y + 20, element.cout, {font: "23px Arial", fill: "#ffffff"}); price.anchor.set(-2); } else if(element.alpha && element.alpha != 1){ price = this._game.add.text(element.x, element.y, element.cout, {font: "23px Arial", fill: "#ffffff"}); price.anchor.set(-0.25); } this._price.push(price); }; SkillsHandler.prototype.cleanPrice = function(){ for(let element of this._price) { if(element !== undefined) { element.destroy(); } } }; // Ajout récursif des boutons issus du JSON SkillsHandler.prototype.addButton = function(skillsObject){ for(let child of skillsObject) { if(child.hasOwnProperty('category')) { this.skillsContainer[child.name] = this._game.add.button(child.x, child.y, child.category); if(child.debloque === 0) { this.price(child); }else if(child.profondeur !== 1) { this.star = this._game.add.sprite(child.x, child.y, 'star'); } this.skillsContainer[child.name].alpha = child.alpha; this.skillsContainer[child.name].input.pixelPerfectOver = true; this.skillsContainer[child.name].input.pixelPerfectClick = true; this.skillsContainer[child.name].events.onInputDown.add(this.discovery.bind(this, child)); this.skillsContainer[child.name].events.onInputOver.add(this.overName.bind(this, child)); this.skillsContainer[child.name].events.onInputOut.add(this.cleanText.bind(this, child)); } if(child.hasOwnProperty('children')) { this.addButton(child.children); } } }; // Fonction de découverte de la compétence et affichage partiel de ses sous-compétences SkillsHandler.prototype.discovery = function(skillClickTarget) { var search = (values) => { $.each(values, (i, v) => { if (v.name === skillClickTarget.name && v.debloque === 0) { // On vérifie que l'on a assez de points pour acheter la compétence if(this._gameObject.point >= v.cout) { // Achat de la compétence this._gameObject.point -= v.cout; // Diminution du taux de pollution this._gameObject.barParam.PV -= 3.5; // Ajout des points this.addPoints(skillClickTarget); // Augmentation du prix des compétences voisinnes this.increaseSkillsCost(skillClickTarget); // Découverte de la compétence v.debloque = 1; v.alpha = 1; if(v.hasOwnProperty('children')) { for(let child of v.children) { child.alpha = 0.7; } } } } else { // Afficher un message ??? } if (v.children) { search(v.children); } }); }; search(this._skillsObject); this.clearSkillsContainer(); // Destruction de l'arbre de compétences this.cleanPrice(); this.addButton(this._skillsObject); // Reconstruction de l'arbre this._text.destroy(); }; /** * PARTIE CALCUL (TAUX DE POLLUTION / POINS) */ // On récupère tous les skills présents dans le JSON afin de faciliter l'accès aux propriétés des skills SkillsHandler.prototype.getAllSkills = function() { var skillsContainerReadOnly = []; // Parcours récursif du JSON var readJSON = object => { for(let child of object) { skillsContainerReadOnly.push(child); if(child.hasOwnProperty('children')) { readJSON(child.children); } } }; readJSON(this._skillsObject); return skillsContainerReadOnly; }; // Renvoie le skill qui correspond au nom passé en paramètre SkillsHandler.prototype.searchSkill = function(skillName) { return this.skillsContainerReadOnly.find(x => x.name === skillName); }; // Renvoie la valeur d'un skill s'il est débloqué ou 0 sinon SkillsHandler.prototype.valueSkill = function(skillName) { var skill = this.searchSkill(skillName); if(skill.debloque === 0) { return 0; } else { return skill.valeur; } }; // Renvoie un certain nombre de points à attribuer lors du déblocage d'une compétence de TransEnerg SkillsHandler.prototype.getPointsTransEnerg = function() { var gaz = this.valueSkill('gaz') * (this.valueSkill('biomasse') + this.valueSkill('biogaz')) ; var thermique = this.valueSkill('thermique') * (this.valueSkill('geothermie') + this.valueSkill('geothermieMers')); var hydraulique = this.valueSkill('hydraulique') * (this.valueSkill('centrale') + this.valueSkill('barrage') + this.valueSkill('hydrolienne')); var eolienne = this.valueSkill('eolienne'); var solaire = this.valueSkill('solaire'); var total = gaz + thermique + hydraulique + eolienne + solaire; return total; }; // Renvoie un certain nombre de points à attribuer lors du déblocage d'une compétence de EnergiePolluante SkillsHandler.prototype.getPointsEnergiePolluante = function() { var nucleaire = this.valueSkill('nucleaire') * (this.valueSkill('recyclDechet') + this.valueSkill('entretien') + this.valueSkill('destruction') + this.valueSkill('reconversion')); var pesticide = this.valueSkill('pesticide'); var total = nucleaire + pesticide; return total; }; // Renvoie un certain nombre de points à attribuer lors du déblocage d'une compétence de Campagne SkillsHandler.prototype.getPointsCampagne = function() { var transport = this.valueSkill('transport') * (this.valueSkill('tramway') + this.valueSkill('busEco')); var entreprise = this.valueSkill('entreprise'); var total = transport + entreprise; return total; }; // Ajoute un certain nombre de points en fonction de l'achat d'une compétence SkillsHandler.prototype.addPoints = function(skill){ var points; switch (skill.category) { case 'greenBullet': points = this.getPointsTransEnerg(); break; case 'orangeBullet': points = this.getPointsCampagne(); break; case 'redBullet': points = this.getPointsEnergiePolluante(); break; } // Si on ne débloque pas une des 3 compétences primaires alors... if(points !== undefined) { if (points === 0){ this._gameObject.point += 1; } else { this._gameObject.point += points; } } }; // Augmente le prix des compétences voisines lors de l'achat d'une compétence SkillsHandler.prototype.increaseSkillsCost = function(skill) { var arr; // Parcours récursif du JSON var readJSON = object => { for(let child of object) { if(child === skill) { arr = object; break; } if(child.hasOwnProperty('children')) { readJSON(child.children); } } }; readJSON(this._skillsObject); // On augmente le prix des compétences voisines en fonction de leur profondeur dans l'arbre for(let child of arr) { if(child !== skill && child.debloque === 0) { child.cout += skill.profondeur; } } }; return SkillsHandler; });
import React, { Component } from "react"; import { View, Text, TextInput, TouchableOpacity, Image } from "react-native"; import { DEVICE_OS, iOS } from "../../actions/constants"; class PasswordInput extends Component { state = { hidePass: true }; managePasswordVisibility = () => { this.setState({ hidePass: !this.state.hidePass }); }; render() { const { inputStyle, labelStyle, containerStyle, inputContainer } = styles; const { label, placeholder, value, onChangeText } = this.props; return ( <View style={containerStyle}> <Text style={[labelStyle, this.props.labelStyle]}>{label}</Text> <View style={styles.inputContainer}> <TextInput placeholderTextColor="#b6b9bf" placeholder={placeholder} secureTextEntry={this.state.hidePass} value={value} onChangeText={onChangeText} style={styles.input} /> <TouchableOpacity activeOpacity={0.8} style={styles.visibilityBtn} onPress={this.managePasswordVisibility} > <Image source={ this.state.hidePass ? require("../../images/hide.png") : require("../../images/view.png") } style={styles.btnImage} /> </TouchableOpacity> </View> </View> ); } } const styles = { inputContainer: { minHeight: 43, height: 40, flexDirection: "row", justifyContent: "center", alignItems: "center", }, input: { // placeholderTextColor: '#b6b9bf', fontFamily: "SFUIText-Regular", color: "#111", fontSize: 15, lineHeight: 18, flex: 1, paddingLeft: 0, }, containerStyle: { // backgroundColor:"#289", height: 63, marginLeft: 45, marginRight: 45, flex: 1, flexDirection: "column", justifyContent: "flex-start", alignItems: "flex-start", borderBottomWidth: 1, borderBottomColor: '#000', }, labelStyle: { // backgroundColor: '#283', // marginLeft: 4, marginBottom: 2, paddingTop: 0, height: 22, fontFamily: "SFUIText-Medium", fontSize: 14, color: "#423486", width: 160, }, visibilityBtn: { position: "absolute", right: 3, height: 30, width: 25, }, btnImage: { resizeMode: "contain", height: "100%", width: "100%", }, inputContainer: { height: 40, flexDirection: "row", justifyContent: "flex-start", alignItems: DEVICE_OS == iOS ? "center" : "flex-start", }, inputStyle: { // placeholderTextColor: '#b6b9bf', paddingTop: 0, marginTop: 0, fontFamily: "SFUIText-Regular", color: "#111", fontSize: 15, flex: 1, borderBottomWidth: 1, borderBottomColor: "#000", }, }; export { PasswordInput };
// //Test 1 function magic_multiply(x,y){ if (x == 0 && y==0){ return "All inputs 0"; } if (x.constructor === Array){ for(let i = 0; i<x.length; i++){ x[i] = x[i]*y } return x; } if (y.constructor === String){ return "Error: Can not multiply by string"; } if (x.constructor === String){ let newString = ""; for (var i =0; i < y; i++){ newString += x; } return newString; } return x*y; } let test1 = magic_multiply(5,2); console.log(test1); let test2 = magic_multiply(0,0); console.log(test2); let test3 = magic_multiply([1,2,3], 2) console.log(test3); let test4 = magic_multiply(7, "three") console.log(test4); let test5 = magic_multiply("Brendo", 4) console.log(test5);
import DS from 'ember-data'; import Ember from 'ember'; export default DS.Model.extend({ sampleDate: DS.attr('date'), probability: DS.attr('number'), candidate: DS.belongsTo('candidate'), formattedDate: Ember.computed('sampleDate', { get() { return moment(this.get('sampleDate')).format('YYYY-MM-DD'); } }), });
"use strict"; var React = require('react'); ; function FormLabel(_a) { var _b = _a.children, children = _b === void 0 ? null : _b, _c = _a.id, id = _c === void 0 ? '' : _c; return (<label id={id}> {children} </label>); } exports.__esModule = true; exports["default"] = FormLabel;
const postData = require("../../../data/posts-data.js"); Page({ onLoad: function(option) { this.setData({ ...postData.postList[option.id] }); } });
import React, { useState } from 'react'; import { Container, Row, Col } from 'react-bootstrap'; import 'bootstrap/dist/css/bootstrap.css'; import apple from '../images/apple.png'; import banana from '../images/banana.png'; import lemon from '../images/lemon.png'; import cherry from '../images/cherry.png'; import coin from '../images/coins.png'; function Slotgame(){ var [coins, setcoins] = useState(20); var [addedcoins, setaddedcoins] = useState(0); const [slotm1, setslotm1] = useState(''); const [slotm2, setslotm2] = useState(''); const [slotm3, setslotm3] = useState(''); const Reel1 = ["cherry", "lemon", "apple", "lemon", "banana", "banana", "lemon", "lemon"]; const Reel2 = ["lemon", "apple", "lemon", "lemon", "cherry", "apple", "banana", "lemon"]; const Reel3 = ["lemon", "apple", "lemon", "apple", "cherry", "lemon", "banana", "lemon"]; function loadslotImg(slot, reel){ if(reel[slot] === "apple"){ return apple; } else if(reel[slot] === "banana"){ return banana; } else if(reel[slot] === "cherry"){ return cherry; } else if(reel[slot] === "lemon"){ return lemon; } } function playGame(){ if(coins > 0){ setcoins(coins -=1); let slot1 = Math.floor(Math.random() * 8); let slot2 = Math.floor(Math.random() * 8); let slot3 = Math.floor(Math.random() * 8); setslotm1(loadslotImg(slot1, Reel1)); setslotm2(loadslotImg(slot2, Reel2)); setslotm3(loadslotImg(slot3, Reel3)); if(Reel1[slot1] === Reel2[slot2] && Reel2[slot2] === Reel3[slot3]){ if(Reel2[slot2] === 'cherry'){setcoins(coins +=50); setaddedcoins(addedcoins +=50);} else if(Reel2[slot2] === 'apple'){setcoins(coins +=20); setaddedcoins(addedcoins +=20);} else if(Reel2[slot2] === 'banana'){setcoins(coins +=15); setaddedcoins(addedcoins +=15);} else if(Reel2[slot2] === 'lemon'){setcoins(coins +=3); setaddedcoins(addedcoins +=3);} } else if(Reel1[slot1] === Reel2[slot2] || Reel2[slot2] === Reel3[slot3]){ if(Reel2[slot2] === 'cherry'){setcoins(coins +=40); setaddedcoins(addedcoins +=40);} else if(Reel2[slot2] === 'apple'){setcoins(coins +=10); setaddedcoins(addedcoins +=10);} else if(Reel2[slot2] === 'banana'){setcoins(coins +=5); setaddedcoins(addedcoins +=5);} } } } return( <Container> <Row><h1>Slot Game</h1></Row> <Row> <Col> <h3><img alt="coins" src={coin} className="coinimg"></img>: {coins} gained: {addedcoins}</h3> <input type="button" onClick={playGame} value="Push to play"></input> <Row> <Col> <img alt="" src={slotm1} className="slotimg"></img> </Col> <Col> <img alt="" src={slotm2} className="slotimg"></img> </Col> <Col> <img alt="" src={slotm3} className="slotimg"></img> </Col> </Row> </Col> </Row> </Container> ); } export default Slotgame;
import axios from 'axios'; import { firebaseClient, isFirebaseLoaded } from './firebase'; import morpheusMap from './morpheusMap'; export async function fetchInitial() { if (isFirebaseLoaded) { try { const gsUrl = await firebaseClient .storage() .ref('gamestates') .getDownloadURL(); const response = await axios.get(gsUrl); return response.data; } catch (error) { console.error('Failed to load gamestates', error); return []; } } return morpheusMap.filter(m => m.type === 'GameState').map(g => g.data) } export function lint() { }
const { User } = require('../models'); const jwt = require('../helpers/jwt'); const CustomError = require('../helpers/customError'); const bcrypt = require('../helpers/bcrypt'); const invalid = "invalid email / password!"; const { OAuth2Client } = require('google-auth-library'); const client = new OAuth2Client(process.env.GOOGLE_CLIENT_ID); class Controller { static login(req, res, next) { const { email, password } = req.body; User.findOne({ where: { email } }) .then((result) => { console.log(result); if (result) { console.log(password, result.password); console.log(bcrypt.compare(password, result.password)); if (bcrypt.compare(password, result.password)) { let payload = { id: result.id } payload = jwt.createToken(payload); res.status(201).json({ token: payload }) } else { throw new CustomError(400, invalid) } } else { throw new CustomError(400, invalid) } }).catch((err) => { console.log(err); next(err); }); } static loginGoogle(req, res, next) { let token = req.headers.token; let isNew = false; let email = ""; client.verifyIdToken({ idToken: token, audience: process.env.GOOGLE_CLIENT_ID }) .then((result) => { const payload = result.getPayload(); email = payload.email; return User.findOne({ where: { email } }) }) .then(result => { if(result) { // ketemu kirim token isNew = false; return result; } else { // ga ketemu register isNew = true; return User.create({ email, password: email + "g" }) } }) .then(result => { let payload = { id: result.id } payload = jwt.createToken(payload); let status = 200; if(isNew){ status = 201; } res.status(status).json({ token: payload }) }) .catch((err) => { err = new CustomError(500, "error in google!"); next(err); }); } static register(req, res, next) { const { email, password } = req.body; User.create({ email, password }) .then((result) => { let payload = { id: result.id } payload = jwt.createToken(payload); res.status(201).json({ token: payload }) }).catch((err) => { console.log(err); next(err); }); } } module.exports = Controller;
import React, { Component } from "react"; import { Link } from "react-router-dom"; import LikeCounter from "./LikeCounter"; export default class RandomQuote extends Component { state = { loading: false, data : [], error: false, } getQuote() { fetch("https://api.chucknorris.io/jokes/random") .then(res => res.json()) .then(myJson => { setTimeout(() => { console.log(myJson) this.setState({ data: myJson, loading: true, }); }, 1000) }) .catch(err => this.setState({ error: true, })) } componentDidMount(){ this.getQuote(); } newQuote(){ console.log('testing button', this); this.getQuote(); } render() { const errorMessage = <h1>OOPSADAISY, ERRRRRRORRRR!!!</h1> if (this.state.loading) { return <div> <h3>Random Quote!!</h3> {this.state.data.value} <div> {/* <button onClick={this.newQuote()}>Get another random quote!</button> */} <button onClick={() => {this.newQuote()}}>Get another random quote!</button> {/* Look! adding the arrowfunction solved it! */} </div> <LikeCounter/> <br/> <Link to={ `/searchQuotePage/` } style={{color: 'white'}}>Look up a quote</Link> </div>; } else if (this.state.error) { return <div>{errorMessage}</div>; } else { return <div>{'Loading.......Just give it one second!'}</div>; } } };
import React from 'react'; import {mount} from '@shopify/react-testing'; import wait from 'waait' import { act } from 'react-dom/test-utils'; import Posts from '../Posts'; import {MockedProvider} from '@apollo/client/testing' import POSTS_QUERY from '../PostsQuery' const mocks = { request: { query: POSTS_QUERY }, result: { data: { microposts: [{ id: "1", content: 'Content', createdAt: 'Yesterday', user: {name: 'Al'} }], }, }, }; describe('<Posts/>', () => { it('loads a series of posts from graphql endpoint', async ()=>{ const wrapper = mount( <MockedProvider mocks={[mocks]} addTypename={false}> <Posts /> </MockedProvider> ); // This act stuff prevents an error in the test console await act(async () => { // this wait function executes the loaded state. without this whole block you can test loading state await wait(0); }) await wrapper.update() //console.log(wrapper.debug()) expect(wrapper.find(Posts)).toBeDefined(); }); it('contains the expected data', async ()=>{ const wrapper = mount( <MockedProvider mocks={[mocks]} addTypename={false}> <Posts /> </MockedProvider> ); // This act stuff prevents an error in the test console await act(async () => { // this wait function executes the loaded state. without this whole block you can test loading state await wait(0); }) await wrapper.update() //console.log(wrapper.debug()) expect(wrapper.find('article').text()).toContain('Content'); }); });
export default function(state = {arrayvar:[]}, action){ switch (action.type) { case 'DISPLAY_ARRAY': console.log('reducer',action.payload) console.log('prevState',state) Object.assign({},state,{arrayvar:state.arrayvar.push(action.payload)}); console.log('state',state.arrayvar[0][0]) } return state; }
const express = require("express"); const Book = require("../models/book"); const router = new express.Router(); const validate = require("jsonschema").validate; // schema including ISBN const bookSchemaCreate = require("../schemas/bookSchemaCreating"); // schema not including ISBN (can't change ISBN number) const bookSchemaUpdate = require("../schemas/bookSchemaUpdating"); /** GET / => {books: [book, ...]} */ router.get("/", async function (req, res, next) { try { const books = await Book.findAll(req.query); return res.json({ books }); } catch (err) { return next(err); } }); /** GET /[id] => {book: book} */ router.get("/:id", async function (req, res, next) { try { const book = await Book.findOne(req.params.id); return res.json({ book }); } catch (err) { return next(err); } }); /** POST / bookData => {book: newBook} */ router.post("/", async function (req, res, next) { try { // validate schema const result = validate(req.body, bookSchemaCreate); if (!result.valid) { // map through each error in stack let listOfErrors = result.errors.map((error) => error.stack); return next({ status: 400, error: listOfErrors, }); } const book = await Book.create(req.body); return res.status(201).json({ book }); } catch (err) { return next(err); } }); /** PUT /[isbn] bookData => {book: updatedBook} */ router.put("/:isbn", async function (req, res, next) { try { if ("isbn" in req.body) { return next({ status: 400, error: "Not allowed to change ISBN.", }); } const result = validate(req.body, bookSchemaUpdate); if (!result.valid) { let listOfErrors = result.errors.map((error) => error.stack); return next({ status: 400, error: listOfErrors, }); } const book = await Book.update(req.params.isbn, req.body); return res.json({ book }); } catch (err) { return next(err); } }); /** DELETE /[isbn] => {message: "Book deleted"} */ router.delete("/:isbn", async function (req, res, next) { try { await Book.remove(req.params.isbn); return res.json({ message: "Book deleted" }); } catch (err) { return next(err); } }); module.exports = router;
/* See license.txt for terms of usage */ /** * This file defines Events APIs for test drivers. */ (function() { // ********************************************************************************************* // // Constants // ********************************************************************************************* // // Firebug UI API /** * Open/close Firebug UI. If forceOpen is true, Firebug is only opened if closed. * The method is asynchronous since it involves attaching to the backend that happens * over RDP. * * @param {Boolean} forceOpen Set to true if Firebug should stay opened. * @param {Object} target The target window for keyboard event * @param {Function} callback Executed when Firebug is connected to the backend * (attached to the current browser tab) */ this.pressToggleFirebug = function(forceOpen, target, callback) { var open = this.isFirebugOpen(); var attached = this.isFirebugAttached(); FBTest.sysout("pressToggleFirebug; forceOpen: " + forceOpen + ", is open: " + open + ", is attached: " + attached); // Don't close if it's open and should stay open. if (forceOpen && open) { if (attached) { callback(); return; } } else { // Toggle visibility FBTest.sendKey("F12", target); } FBTest.waitForTabAttach(callback); }; /** * Open Firebug UI. If it's already opened, it stays opened. */ this.openFirebug = function(callback) { this.pressToggleFirebug(true, undefined, callback); }; /** * Closes Firebug UI. if the UI is closed, it stays closed. */ this.closeFirebug = function() { if (this.isFirebugOpen()) this.pressToggleFirebug(); }; this.shutdownFirebug = function() { // TODO: deactivate Firebug }; /** * Returns true if Firebug UI is currently opened; false otherwise. This method doesn't * check if Firebug is connected to the backend. Use 'isFirebugAttached' instead if * it's what you need. Firebug connects to the back end immediately after opening for * the first time, but it happens asynchronously. */ this.isFirebugOpen = function() { var isOpen = FW.Firebug.chrome.isOpen(); FBTest.sysout("isFirebugOpen; isOpen: " + isOpen); return isOpen; }; this.getFirebugPlacement = function() { return FW.Firebug.getPlacement(); }; this.isFirebugActive = function() { var suspension = FW.Firebug.getSuspended(); return (suspension == "suspended") ? false : true; }; this.setBrowserWindowSize = function(width, height) { var tabbrowser = FBTestFirebug.getBrowser(); var currTab = tabbrowser.selectedTab; currTab.ownerDocument.defaultView.resizeTo(width, height); } this.setFirebugBarHeight = function(height) { var mainFrame = FW.Firebug.Firefox.getElementById("fbMainFrame"); mainFrame.setAttribute("height", height); }; this.setSidePanelWidth = function(width) { var sidePanelDeck = FW.Firebug.chrome.$("fbSidePanelDeck"); sidePanelDeck.setAttribute("width", width); }; // ********************************************************************************************* // this.isDetached = function() { return FW.Firebug.isDetached(); }; this.isMinimized = function() { return FW.Firebug.isMinimized(); }; this.isInBrowser = function() { return FW.Firebug.isInBrowser(); }; /** * Detach Firebug into a new separate window. */ this.detachFirebug = function(callback) { if (FW.Firebug.isDetached()) { callback(null); return; } this.openFirebug(function() { callback(FW.Firebug.detachBar(FW.Firebug.currentContext)); }); }; /** * Close detached Firebug window. */ this.closeDetachedFirebug = function() { if (!FW.Firebug.isDetached()) return false; // Better would be to look according to the window type, but it's not set in firebug.xul var result = FW.FBL.iterateBrowserWindows("", function(win) { if (win.location.href == "chrome://firebug/content/firebug.xul") { win.close(); return true; } }); return result; }; /** * Closes Firebug on all tabs */ this.closeFirebugOnAllTabs = function() { FBTest.progress("closeFirebugOnAllTabs"); var tabbrowser = FBTestFirebug.getBrowser(); for (var i = 0; i < tabbrowser.mTabs.length; i++) { var tab = tabbrowser.mTabs[i]; FBTest.sysout("closeFirebugOnAllTabs on tab "+tab); tabbrowser.selectedTab = tab; this.closeFirebug(); } }; // ********************************************************************************************* // // Toolbar API this.clickToolbarButton = function(chrome, buttonID) { if (!chrome) chrome = FW.Firebug.chrome; var doc = chrome.window.document; var button = doc.getElementById(buttonID); FBTest.sysout("Click toolbar button " + buttonID, button); // Do not use FBTest.click, toolbar buttons need to use sendMouseEvent. // Do not use synthesizeMouse, if the button isn't visible coordinates are wrong // and the click event is not fired. //this.synthesizeMouse(button); button.doCommand(); }; // ********************************************************************************************* // // xxxHonza: TODO this section needs to be revisited this.listenerCleanups = []; this.cleanUpListeners = function() { var c = FBTestFirebug.listenerCleanups; FBTest.sysout("ccccccccccccccccccccccccc cleaning listeners ccccccccccccccccccccccccccccccc"); while(c.length) c.shift().call(); }; this.UntilHandler = function(eventTarget, eventName, isMyEvent, onEvent, capturing) { var removed = false; function fn (event) { if (isMyEvent(event)) { eventTarget.removeEventListener(eventName, fn, capturing); removed = true; FBTest.sysout("UntilHandler activated for event "+eventName); onEvent(event); } else { FBTest.sysout("UntilHandler skipping event "+eventName, event); } } eventTarget.addEventListener(eventName, fn, capturing); FBTestFirebug.listenerCleanups.push( function cleanUpListener() { if (!removed) eventTarget.removeEventListener(eventName, fn, capturing); }); }; this.OneShotHandler = function(eventTarget, eventName, onEvent, capturing) { function isTrue(event) {return true;} FBTestFirebug.UntilHandler(eventTarget, eventName, isTrue, onEvent, capturing); }; // ********************************************************************************************* // // Backend /** * Returns true if Firebug is attached to the backend tab actor. This process starts * immediately after Firebug UI is opened and {@link TabContext} instance created for * the current page. The attach process is asynchronous (happens over RDP). */ this.isFirebugAttached = function() { var browser = FBTest.getCurrentTabBrowser(); return FW.Firebug.DebuggerClient.isTabAttached(browser); } this.waitForTabAttach = function(callback) { if (!callback) { FBTest.sysout("waitForTabAttach; ERROR no callback!"); return; } // If Firebug is already attached to a tab execute the callback directly and bail out. if (FBTest.isFirebugAttached()) { callback(); return; } var browser = FBTestFirebug.getCurrentTabBrowser(); var listener = { onTabAttached: function() { //xxxHonza: what if an existing tab is attached and not the test one? FBTest.sysout("waitForTabAttach; On tab attached"); DebuggerController.removeListener(browser, listener); callback(); } }; DebuggerController.addListener(browser, listener); } // ********************************************************************************************* // }).apply(FBTest);
window.onload = choosePic; function choosePic(){ var r = Math.floor(Math.random() * data.length); document.getElementById("immagine").src = data[r].src; document.getElementById("descrizione").innerHTML = data[r].caption; }
define("startGameService", [], function () { function doBlankSquare(id, squares) { var listClassOfSquares = squares[id].children[0].classList; if (listClassOfSquares.contains("fa-times")) { listClassOfSquares.remove("fa-times"); listClassOfSquares.remove("purple-text"); } else if (listClassOfSquares.contains("fa-circle-o")) { listClassOfSquares.remove("fa-circle-o"); listClassOfSquares.remove("blue-text"); } }; return { initBoard: function (squares, gameHistory) { [].forEach.call(squares, function (element, id) { doBlankSquare(id, squares); }); document.getElementById("start-button").disabled = true; document.getElementById("give-up-button").disabled = false; }, doBlankSquare: doBlankSquare }; });
const express = require('express'); const db = require('../db/mysql'); const { fetchCategories } = require('../models/categories'); const { fetchQuestion } = require('../models/questions'); const { fetchAnswers, addAnswer } = require('../models/answers'); const { fetchUsers } = require('../models/users'); const router = express.Router(); let errorsList = { 'TITLE_REQUIRED': 'Title is required', 'QUESTION_REQUIRED': 'Question text is required', 'SUBJECT_REQUIRED': 'Subject is required', }; router.get('/question', async function (req, res) { const {error_title, error_questionText, error_subject} = req.session; delete req.session.error_title; delete req.session.error_questionText; delete req.session.error_subject; const subj = await fetchCategories(); console.log(subj); res.render('homework-help/question', { error_title, error_questionText, error_subject, subj, }); }); router.post('/question', function (req, res) { const {title, 'question-text': questionText, subject, tags} = req.body; if (!title) { req.session.error_title = 'Title is required'; } if (!questionText) { req.session.error_questionText = 'Question text is required'; } if (!subject) { req.session.error_subject = 'Subject is required'; } if (title && questionText && subject) { let filePath = null; if (req.files && req.files.file) { filePath = '/uploads/' + req.files.file.name; req.files.file.mv(__dirname + '/../public/' + filePath); } db.query( 'INSERT INTO questions (title, description, category_id, tags, image_path) VALUES (?, ?, ?, ?, ?)', [title, questionText, subject, tags, filePath], (err, results) => { if (err) throw new Error(err); res.redirect('/'); } ); } else { res.redirect('/homework-help/question'); } }); router.post('/answer', async function (req, res) { const { user_id, answer_text, question_id } = req.body; if (!user_id || !answer_text || !question_id) { console.error('ALARMA!'); res.redirect(`/homework-help/question`); } else { await addAnswer({ user_id, answer_text, question_id }); res.redirect(`/homework-help/question/${question_id}`); } }); router.get('/question/:id', async function (req, res) { const questionId = req.params.id; const question = await fetchQuestion(questionId); const answers = await fetchAnswers(questionId); const users = await fetchUsers(); res.render('homework-help/question-preview', { question: question[0], answers, users, questionId }); }); module.exports = router;
// Initialize new array var names = ['Roopak', 'Brooke', 'David']; var years = new Array(1992, 1993, 1992); console.log(names[2]); console.log(names.length); // Mutate array data names[1] = 'Sarah'; names[names.length] = 'Ramesh'; console.log(names); // Different data types in array var roopak = ['Roopak', 'Kumar', 1992, 'student', true]; roopak.push('blue'); roopak.unshift('Mr.'); console.log(roopak); roopak.pop(); roopak.pop(); roopak.shift(); console.log(roopak);
import React, { Component } from 'react'; import styles from './services.scss'; import { Row, Col } from 'reactstrap'; import PropTypes from 'prop-types'; import { imagePath } from '../../utils/assetUtils'; // import SimpleCarousel from '../../components/simpleCarousel/simpleCarousel'; import TalkToWeddingPlanner from '../../components/TalkToWeddingPlanner/talkToWeddingPlanner'; import ImageFade from '../../components/ImageFade/imageFade'; class DetailComponent extends Component { state = { selectedIndex: 0 , fromServices: true}; changeSelection(index) { this.setState({ selectedIndex: index }); } render() { return ( <Row className={styles.detailBox} id={this.props.id}> {this.props.data.heading && <h2 dangerouslySetInnerHTML={{__html: this.props.data.heading}}></h2>} <Col md="12" className={styles.sectionWrap}> <div className={styles.imageCarouselWrap}> <img className={`${styles.imgIcon} tab-only`} src={imagePath(this.props.data.icon)} alt="vow icon" /> <img className={`${styles.imgIcon} mobile-only`} src={imagePath(this.props.data.mobileIcon)} alt="vow icon" /> <h3 className={`${styles.mobile} mobile-only`} dangerouslySetInnerHTML={{__html: this.props.data.title}}></h3> <ImageFade data={this.props.data.images} fromServices={this.state.fromServices}/> </div> <div className={styles.contentPart}> <h3 className="tab-only" dangerouslySetInnerHTML={{__html: this.props.data.title}}></h3> <ul> { this.props.data.listItems.map((item, index) => { return <li key={index} aria-hidden>{item}</li> }) } </ul> <TalkToWeddingPlanner buttonText={this.props.data.ctaText} type="services" /> </div> </Col> <Col md="12" className="text-center"> <img className={styles.vowIconLine} src={imagePath('about-vows.png')} alt="vow icon" /> </Col> </Row> ); } } DetailComponent.propTypes = { data: PropTypes.object, id: PropTypes.string }; export default DetailComponent;
/** * Created by c.su on 7/18/16. */ (function () { "use strict"; var assert = require("./assert.js"); var tabs = require("./tabs.js"); //Mocha-------------------------------------- describe("Tabs", function(){ it("set a new class when that element has no existing classes", function(){ //Arrage var element = addElement("div"); //Act tabs.initialize(element, "someClass"); //Assert assert.equal(getClass(element), "someClass"); //Reset //removeElement(element); }); it("set a new class when that element has existing classes", function(){ var element = addElement("div"); element.setAttribute("class", "existingClass"); tabs.initialize(element, "someClass"); assert.equal(getClass(element), "existingClass someClass"); //removeElement(element); }); function getClass(element){ return element.getAttribute("class"); } function addElement(tagName){ var newtag = document.createElement(tagName); document.body.appendChild(newtag); return newtag; } function removeElement(elem){ elem.parentNode.removeChild(elem); } }); }());
export const user = state => state.user; export const locations = state => state.locations; export const gMap = state => state.gMap; export const myLocation = state => state.locations.find(location => location.user_id === state.user.id);
import utils from './common/utils'; exports.getLastTimeStr = (time, friendly) => { if (friendly) { return MillisecondToDate(time); } else { return fmtDate(new Date(time), 'yyyy-MM-dd hh:mm'); } };