text
stringlengths
7
3.69M
/* Copyright 2017 - present Sean O'Shea Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ const fuzzyMatching = require('../dist/fuzzymatchingjs.cjs'); const min = require('../dist/fuzzymatchingjs.umd.js'); describe('Minified version', () => { test('should export the same functionality as the server-side version', () => { Object.keys(fuzzyMatching).forEach((key) => { expect(typeof fuzzyMatching[key]).toEqual(typeof min[key]); }); }); test('should be up to date', () => { expect(min.version).toEqual(fuzzyMatching.version); }); });
"use strict"; /* * * ============================ * ============================ * * Include lib: * * - webFontLoader.js; * - preventBehavior.js; * - svg4everybody.js; * * ============================ * ============================ * */ /** * @name initPreventBehavior * * @description */ var initPreventBehavior = function initPreventBehavior() { var link = document.querySelectorAll("a"); link.forEach(function (val, idx) { val.addEventListener("click", function (e) { if (val.getAttribute("href") === "#") { e.preventDefault(); } }); }); }; /** * @name initSvg4everybody * * @description SVG for Everybody adds external spritemaps support to otherwise SVG-capable browsers. */ var initSvg4everybody = function initSvg4everybody() { svg4everybody(); }; /** * @description Document DOM ready. */ $(document).ready(function (ev) { /** * * @type {*|jQuery|HTMLElement} * @private */ var _document = $(document), _window = $(window); /* * ============================================= * CALLBACK :: start * ============================================= */ var initGetStartedScreen = function initGetStartedScreen() { var _name = '', _id = 1; var backToMain = function backToMain() { $('.e-started__row').hide(); $('.e-started__row[e-started-screen="0"]').show(); $('.e-started-back').removeClass('is-active'); }; $('[started-btn-js]').on('click', function (ev) { var _elem = $(ev.currentTarget), _elemName = _elem.data('name'), _elemID = _elem.data('id'); _name = _elemName; _id = _elemID; var _btnBack = $('.e-started-back'); var nextScreen = function nextScreen(name, id) { $('.e-started__row--' + name + '[e-started-screen="' + id + '"]').fadeIn(425); }; var prevScreen = function prevScreen(name, id) { $('.e-started__row--' + name + '[e-started-screen="' + id + '"]').fadeIn(425); }; if (_elemID === 0) { backToMain(); } if (_elemID === 1) { _btnBack.addClass('is-active'); $('.e-started__row[e-started-screen="0"]').hide(); nextScreen(_elemName, _elemID); } else if (_elemName === 'back') { _elemName = _elem.data('subname'); $('.e-started__row[e-started-screen="' + (_elemID + 1) + '"]').hide(); prevScreen(_elemName, _elemID); } else { $('.e-started__row[e-started-screen="' + (_elemID - 1) + '"]').hide(); nextScreen(_elemName, _elemID); } _name = _elem.data('subname') !== undefined ? _elem.data('subname') : _elemName; }); $('.e-started-back').on('click', function (ev) { if (_id === 1) { backToMain(); } else { $('.e-started__row--' + _name + '[e-started-screen="' + _id + '"]').hide(); $('.e-started__row--' + _name + '[e-started-screen="' + (_id - 1) + '"]').fadeIn(425); _id--; } }); }; var initFaqsCollapse = function initFaqsCollapse() { $('[faqa-btn-js]').on('click', function (ev) { var _elem = $(ev.currentTarget), _parentNode = _elem.closest('.e-faqs__block'), _bodyNode = _elem.siblings('.e-faqs__block-body'); _parentNode.toggleClass('is-open'); _bodyNode.slideToggle(); }); }; var initStickyHeader = function initStickyHeader() { var _num = 1, _heightSection = 0, _scrollDirectionVal = '', _scrollDirection = 0; var scrollDirection = function scrollDirection() { if (document.body.getBoundingClientRect().top > _scrollDirection) { _scrollDirectionVal = 'down'; } else { _scrollDirectionVal = 'up'; } _scrollDirection = document.body.getBoundingClientRect().top; }; var isAnyPartOfElementInViewport = function isAnyPartOfElementInViewport(el) { var _elements = document.querySelectorAll(el); var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = _elements[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var _el = _step.value; var rect = _el.getBoundingClientRect(); var windowHeight = window.innerHeight || document.documentElement.clientHeight; var windowWidth = window.innerWidth || document.documentElement.clientWidth; var vertInView = rect.top <= windowHeight && rect.top + rect.height >= 0; var horInView = rect.left <= windowWidth && rect.left + rect.width >= 0; if (vertInView && horInView) { return _el.getAttribute('data-section-id'); } else if ($(el).offset().top - $(window).scrollTop() >= 0) { return 1; } else { return 6; } } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } } }; var changeTextOpacity = function changeTextOpacity(num) { var _elem = $('.e-how__body-right p'), _idx = num - 1; var _iteratorNormalCompletion2 = true; var _didIteratorError2 = false; var _iteratorError2 = undefined; try { for (var _iterator2 = _elem[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { var _el = _step2.value; _el.style.opacity = '0'; } } catch (err) { _didIteratorError2 = true; _iteratorError2 = err; } finally { try { if (!_iteratorNormalCompletion2 && _iterator2.return) { _iterator2.return(); } } finally { if (_didIteratorError2) { throw _iteratorError2; } } } switch (_idx) { case 0: _elem[_idx].style.opacity = '1'; _elem[_idx + 1].style.opacity = '0.25'; _elem[_idx + 2].style.opacity = '0.05'; break; case 1: _elem[_idx - 1].style.opacity = '0.25'; _elem[_idx].style.opacity = '1'; _elem[_idx + 1].style.opacity = '0.25'; _elem[_idx + 2].style.opacity = '0.05'; break; case 2: case 3: _elem[_idx - 2].style.opacity = '0.05'; _elem[_idx - 1].style.opacity = '0.25'; _elem[_idx].style.opacity = '1'; _elem[_idx + 1].style.opacity = '0.25'; _elem[_idx + 2].style.opacity = '0.05'; break; case 4: _elem[_idx - 2].style.opacity = '0.05'; _elem[_idx - 1].style.opacity = '0.25'; _elem[_idx].style.opacity = '1'; _elem[_idx + 1].style.opacity = '0.25'; break; case 5: _elem[_idx - 2].style.opacity = '0.05'; _elem[_idx - 1].style.opacity = '0.25'; _elem[_idx].style.opacity = '1'; break; default: break; } }; var offsetTextArr = function offsetTextArr() { var _elements = $('.e-how__body-right p'), _arr = []; var _iteratorNormalCompletion3 = true; var _didIteratorError3 = false; var _iteratorError3 = undefined; try { for (var _iterator3 = _elements[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { var _el = _step3.value; _arr.push($(_el).outerHeight(true)); } } catch (err) { _didIteratorError3 = true; _iteratorError3 = err; } finally { try { if (!_iteratorNormalCompletion3 && _iterator3.return) { _iterator3.return(); } } finally { if (_didIteratorError3) { throw _iteratorError3; } } } return _arr; }; var _resultAdditional = 0; var translateText = function translateText(num) { var _translateNode = $('.e-how__body-right'), _arrOffset = offsetTextArr(), _idx = num - 1; var _resOffsetUp = 0, _resOffsetDown = 0; // console.log(`_idx: ${_idx}`); if (_scrollDirectionVal === 'up') { for (var i = 0; i <= _idx; i++) { _resOffsetUp = _resOffsetUp + _arrOffset[i]; } _translateNode.css({ // 'transform' : 'translateY(-' + _resOffsetUp + 'px)' 'top': '-' + _resOffsetUp + 'px' }); _resultAdditional = _resOffsetUp; console.log("if _resultAdditional: " + _resultAdditional); } else { /* * idx === 5 * [115, 85, 205, 115, 85, 205] * [000, 01, 002, 003, 04, 005] * */ // console.log(`else`); // console.log(`_idx: ${_idx}`); console.log("_arrOffset[_idx]: " + (_arrOffset[_idx - 1] ? _arrOffset[_idx - 1] : _arrOffset[_idx])); // console.log(`_resultAdditional: ${_resultAdditional}`); _resOffsetDown = _arrOffset[_idx - 1] ? _arrOffset[_idx - 1] : _arrOffset[_idx]; // console.log(`_resOffsetDown: ${_resOffsetDown}`); _translateNode.css({ // 'transform' : 'translateY(-' + (_resultAdditional - _resOffsetDown) + 'px)' }); } }; $(window).on('load', function () { _heightSection = $('.e-how__section').height(); _num = isAnyPartOfElementInViewport('.e-how__section'); console.log("LOAD::"); console.log("_num: ", _num); // console.log(`offsetTextArr: `, offsetTextArr()); }); $(window).on('scroll', function () { console.log("SCROLL::"); scrollDirection(); changeTextOpacity(_num); translateText(_num); var _winScrollTop = $(window).scrollTop(), _minLen = 1, _maxLen = $('.e-how__body-right p').length; if (_scrollDirectionVal === 'up') { // console.log('up'); if ($('.e-how__section-' + _num).offset().top - _winScrollTop <= 0) { var _currentDiff = Math.abs($('.e-how__section-' + _num).offset().top - _winScrollTop); // console.log(`section ${_num} start`); if (_currentDiff > _heightSection) { // console.log(`section ${_num} end`); if (_num < _maxLen) { ++_num; } // console.log(`_num: ${_num}`); } } } else { // console.log('down'); if ($('.e-how__section-' + _num).offset().top - _winScrollTop >= 0) { var _currentDiff2 = Math.abs($('.e-how__section-' + _num).offset().top - _winScrollTop); // console.log(`section ${_num} start`); if (_currentDiff2 < _heightSection) { // console.log(`section ${_num} end`); if (_num > _minLen) { --_num; } // console.log(`_num: ${_num}`); } } } }); }; var initMainBgTransition = function initMainBgTransition() { var tlBg = new TimelineMax(); tlBg.fromTo(document.querySelector('.e-main__bg'), 7, { x: 100 }, { x: -100, repeat: -1, yoyo: true, ease: Power1.easeInOut }); }; /* * CALLBACK :: end * ============================================= */ /** * @description Init all method */ var initJquery = function initJquery() { // default // initWebFontLoader(); initPreventBehavior(); initSvg4everybody(); // ========================================== // lib // ========================================== // callback // ========================================== initGetStartedScreen(); initFaqsCollapse(); // initStickyHeader(); initMainBgTransition(); }; initJquery(); });
/** * === page === * * created at: Tue Jun 27 2017 18:27:29 GMT+0800 (CST) */ import { React, Page } from 'zola' export default class Index extends Page { render () { return ( <div> <div className="wrap"> <h1>404</h1> <h2>Not Found</h2> <p>The page you were trying to reach doesn't exist.</p> </div> <div className="footer">with <b>♥</b> by lianjia-fe</div> </div> ) } }
/** * 系统数据字典 * @class SystemDictionaryPanel * @extends Disco.Ext.CrudListPanel */ SystemDictionaryPanel = Ext.extend(Disco.Ext.CrudListPanel, { id: "systemDictionaryPanel", title: "字典分类管理", baseUrl: "systemDictionary.java", showView: false, createForm: function() { var formPanel = new Ext.form.FormPanel({ frame: true, labelWidth: 60, labelAlign: 'right', defaults: { anchor: "-40", xtype: "textfield" }, items: [{ xtype: "hidden", name: "id" }, { fieldLabel: "编号", name: 'sn', allowBlank: false, width: 300, helpText: '字典分类的唯一标识,程序中通过编号来选择字典值!' }, { fieldLabel: "名称", name: 'title', allowBlank: false }, { xtype: "textarea", fieldLabel: "简介", name: 'intro' }] }); return formPanel; }, createWin: function(callback, autoClose) { return this.initWin(438, 200, "字典分类管理", callback, autoClose); }, storeMapping: ["id", "sn", "title", "intro", "children"], initComponent: function() { this.cm = new Ext.grid.ColumnModel([{ header: "编码", sortable: true, width: 50, dataIndex: "sn" }, { header: "名称", sortable: true, width: 50, dataIndex: "title" }, { header: "简介", sortable: true, dataIndex: "intro" }]) SystemDictionaryPanel.superclass.initComponent.call(this); }, afterList: function() { this.searchField.hide(); } }); /** * 系统数据字典值 * @class SystemDictionaryDetailPanel * @extends Disco.Ext.CrudListPanel */ SystemDictionaryDetailPanel = Ext.extend(Disco.Ext.CrudListPanel, { id: "systemDictionaryDetailPanel", title: "字典值管理", baseUrl: "systemDictionaryDetail.java", pageSize: 20, showView: false, createForm: function() { var formPanel = new Ext.form.FormPanel({ frame: true, labelWidth: 80, labelAlign: 'right', defaults: { anchor: "-20", xtype: "textfield" }, items: [{ xtype: "hidden", name: "id" }, { xtype: "hidden", name: "parentSn" }, { fieldLabel: "名称", name: 'title', allowBlank: false }, { fieldLabel: "值", name: 'value', allowBlank: false }, { fieldLabel: "显示顺序", name: 'sequence' }] }); return formPanel; }, save: function(callback, autoClose, ignoreBeforeSave) { this.fp.form.baseParams = { parentId: this.parentId }; SystemDictionaryDetailPanel.superclass.save.call(this, callback, autoClose, ignoreBeforeSave); }, createWin: function(callback, autoClose) { return this.initWin(288, 160, "字典值管理", callback, autoClose); }, storeMapping: ["id", "title", "value", "sequence", "parent"], initComponent: function() { this.cm = new Ext.grid.ColumnModel([new Ext.grid.RowNumberer({ header: "序号", width: 40 }), { header: "名称", sortable: true, width: 300, dataIndex: "title" }, { header: "值", sortable: true, width: 300, dataIndex: "value" }, { header: "显示顺序", sortable: true, width: 300, dataIndex: "sequence" }]) this.gridButtons = [{ text: "上移", cls: "x-btn-text-icon", icon: "img/ria/up.gif", handler: this.swapSequence(""), scope: this }, { text: "下移", cls: "x-btn-text-icon", icon: "img/ria/down.gif", handler: this.swapSequence(true), scope: this }, "-"]; SystemDictionaryDetailPanel.superclass.initComponent.call(this); }, afterList: function() { this.searchField.setWidth(100); this.grid.on("render", function() { this.disableOperaterItem("btn_add"); }, this); this.store.on("load", function() { this.enableOperaterItem("btn_add"); }, this); } }); /** * 数据字典管理 * @class SystemDictionaryManagePanel * @extends Ext.Panel */ SystemDictionaryManagePanel = Ext.extend(Ext.Panel, { id: "systemDictionaryManagePanel", //title : "数据字典管理", closable: true, autoScroll: true, border: false, //hideBorders:true, layout: "border", defaults: { bodyStyle: 'border-top:none;' }, initComponent: function() { SystemDictionaryManagePanel.superclass.initComponent.call(this); this.dictionaryPanel = new SystemDictionaryPanel({ title: "字典分类" }); this.detailPanel = new SystemDictionaryDetailPanel({ title: "字典详情" }); this.add({ layout: "fit", region: "west", width: "45%", items: [this.dictionaryPanel.list()] }, { layout: "fit", region: "center", items: [this.detailPanel.list()] }); this.dictionaryPanel.grid.on("rowclick", function(grid, index) { this.detailPanel.store.removeAll(); var r = this.dictionaryPanel.store.getAt(index); this.detailPanel.store.reload({ params: { parentId: r.get("id"), start: 0 } }); this.detailPanel.parentId = r.get("id"); }, this, { buffer: 200 }); } })
const express = require('express'); const router = express.Router(); const storage = require('../middlewares/upload') const multer = require('multer'); const upload = multer({ storage: storage }); const food = require('../controller/food.controller'); const restaurant = require('../controller/restaurant.controller'); const user = require('../controller/user.controller'); const location = require('../controller/location.controller'); const merchant = require('../controller/merchant.controller'); const customer = require('../controller/customer.controller'); const auth = require("../controller/auth.controller"); const order = require("../controller/order.controller"); const orderItems = require("../controller/orderItems.controller"); const vehicle = require("../controller/vehicle.controller"); const discount = require("../controller/discount.controller"); //goods router.post('/food/list', food.list); router.get('/food/detail', food.detail); router.post('/food/save', food.save); router.post('/food/update', food.update); router.get('/food/delete', food.delete); router.get('/food-type/list', food.type); router.post('/food/uploadFiles', upload.single('file'), food.upload); //restaurant router.post('/restaurant/list', restaurant.list); router.get('/restaurant/detail', restaurant.detail); router.post('/restaurant/save', restaurant.save); router.post('/restaurant/update', restaurant.update); router.get('/restaurant/delete', restaurant.delete); router.get('/restaurant-type/list', restaurant.type); router.post('/restaurant-food/list', restaurant.item); router.get('/restaurant-food/detail', restaurant.detailItem); router.post('/restaurant-food/update', restaurant.updateItem); router.get('/restaurant-food/delete', restaurant.deleteItem); router.post('/restaurant-food/save', restaurant.saveItem); router.post('/restaurant-combo/list',restaurant.comboList); router.post('/restaurant-combo/save',restaurant.saveCombo); router.get('/restaurant-combo/delete',restaurant.deleteCombo); router.get('/restaurant-combo/detail',restaurant.detailCombo); router.post('/restaurant-combo/update',restaurant.updateCombo); router.get('/restaurant-location/list', restaurant.address); router.post('/restaurant-discount/list', restaurant.discount); router.post('/restaurant-discount/save', restaurant.saveDiscount); router.get('/restaurant-discount/delete', restaurant.deleteDiscount); router.post('/combo-food/save',restaurant.saveFoodCombo); router.get('/combo-food/list',restaurant.listFoodCombo); router.get('/combo-food/delete',restaurant.deleteComboFood); // discount router.post('/discount/list', discount.list); router.post('/discount/save', discount.save); router.get('/discount/delete', discount.delete); router.post('/discount/update', discount.update); router.get('/discount/detail', discount.detail); //user router.get('/user/list', user.list); router.get('/user/detail', user.detail); router.post('/user/save', user.save); router.post('/user/update', user.update); router.get('/user/delete', user.delete); //merchant router.post('/merchant/list', merchant.list); router.get('/merchant/detail', merchant.detail); router.post('/merchant/save', merchant.save); router.post('/merchant/update', merchant.update); router.get('/merchant/delete', merchant.delete); //customer router.post('/customer/list', customer.list); router.get('/customer/detail', customer.detail); router.post('/customer/save', customer.save); router.post('/customer/update', customer.update); router.get('/customer/delete', customer.delete); // location router.post('/location/list', location.list); router.post('/location/save', location.save); router.post('/location/update', location.update); router.get('/location/detail', location.detail); router.get('/location/delete', location.delete); router.get('/vie-province/list', location.province); router.get('/vie-district/list', location.district); router.get('/vie-ward/list', location.ward); //register router.post('/auth/register', auth.register); //login router.post('/auth/login', auth.login); //order router.post('/orders/list', order.list); router.post('/orders/save', order.save); router.post('/orders/update', order.update); router.get('/order/detail',order.detail); //vận đơn router.post('/lading-bill/list',order.ladingBillList); router.get('/lading-bill/detail',order.ladingBillDetail); router.post('/lading-bill/update',order.ladingBillUpdate); router.post('/lading-bill/save',order.ladingBillSave); //order-detail router.get('/order-item/list', orderItems.list); router.post('/order-item/save', orderItems.save); //danh sách tài xế router.get('/driver/list',vehicle.list); router.post('/driver/update',vehicle.update); // Báo cáo router.post('/report-revenue/report',order.report) module.exports = router;
const REACT_JS = 'REACT_JS'; const REACT_TS = 'REACT_TS'; const RN_JS = 'RN_JS'; const REACT_JS_DEPS = [ 'eslint', 'eslint-config-airbnb', 'eslint-config-prettier', 'eslint-plugin-import', 'eslint-plugin-jsx-a11y', 'eslint-plugin-prettier', 'eslint-plugin-react', 'eslint-plugin-react-hooks', 'prettier' ]; const REACT_TS_DEPS = [ '@typescript-eslint/eslint-plugin', '@typescript-eslint/parser', 'eslint', 'eslint-config-airbnb-typescript', 'eslint-config-prettier', 'eslint-import-resolver-typescript', 'eslint-plugin-import', 'eslint-plugin-jsx-a11y', 'eslint-plugin-prettier', 'eslint-plugin-react', 'eslint-plugin-react-hooks', 'prettier' ]; export const keys = {REACT_JS, REACT_TS, RN_JS}; export const isValidKey = (keyWanted) => { const isValid = Object.values(keys).some(key => key === keyWanted); if (isValid) { return true } else { console.log(`Enter a valid stack to 2° arg:\n\t${Object.values(keys).join('\n\t')}`); return false; } } export const getAllDepsByKey = (key) => { if (key === REACT_JS) { return REACT_JS_DEPS.join(' '); } if (key === REACT_TS) { return REACT_TS_DEPS.join(' '); } return ''; }
import React, {Component} from 'react'; import Header from './Header'; import './Why.css'; class Contact extends Component { render() { return ( <div className="whyContainer"> <Header /> <div className="backgroundImgOne"> <div className="whyHeader">Why</div> <div className="whyBackgroundContainer"> <div className="backgroundImgTwo" /> <div className="backgroundImgThree" /> <p className="whyParagraph"> In our daily lives we naturally fall into patterns of behaviour. This is why we for example, always pay attention to same house while walking down our street. You can make yourself change those patterns, but you will need to stay focused. If your attention wanders, you'll fall back into your accustomed pattern. We all carry so many of those patterns that we follow in our daily lives, without even noticing that we do. How can we bring attention to those patterns, because as darwin said, Attention, if sudden and close, graduates into surprise; and this into astonishment; and this into stupefied amazement. We want to turn our daily lives into magic, by bringing more consciousness and awareness into our daily routines. Shakespeare suggested All the world's a stage, And all the men and women merely players. According to this, all our lives are a performance. </p> </div> </div> </div> ); } } export default Contact;
import moment from 'moment' import 'moment-timezone' import { Command } from './command' export class SyncTimeCommand extends Command { template = { Locales: { DST: { DSTEnd: { Day: 0, Hour: 0, Month: 1, Week: 1 }, DSTStart: { Day: 0, Hour: 0, Month: 1, Week: 1 }, Enable: false, Offset: 60, }, TimeZone: 'GMT+09:00', }, } constructor({ id = 0 } = {}) { super() const time = moment().tz('Asia/Tokyo').format('YYYY-MM-DD HH:mm:ss') this.cmd = { id, method: 'specific.multicall', params: [ { id: 0, method: 'configCentre.setConfig', params: { name: 'Locales', content: this.template.Locales, }, }, { id: 0, method: 'global.setTime', params: { time }, }, ], } } }
import React from "react"; import "./BirthdayCard.css"; export default function BirthdayCard({ id, name, image, age }) { return ( <section className="birthday-card" key={id}> <article> <img src={image} alt="person image" className="person-image" /> </article> <article className="person-details"> <span className="person-name">{name}</span> <span className="person-age">{age} years</span> </article> </section> ); }
module.exports = function (config) { return { mode: 'development', resolve: { extensions: ['.js'] }, ...config } }
import axios from 'axios'; const baseUrl = "http://localhost:8888/api/quotes/"; export function fetch(quant){ return {type:"FETCH_TOP", payload: axios.get( baseUrl + "topquotes", {params:{ quant: quant }})}; } export function handlerLike(id) { if(localStorage.getItem(id)){ return { type:"PASS" } } return { type: "LIKE", payload: axios.put(baseUrl + "like/", { id: id}) } }
var SVGSprite = require('svg-sprite'); var fs = require('fs'); var path = require('path'); var mkdirp = require('mkdirp'); var phantomjs = require('phantomjs-prebuilt').path; var execFile = require("child_process").execFile; var async = require('async'); var sizeOf = require('image-size'); var datauri = require('datauri'); var exports = module.exports = {}; var split = function (uristring) { var parts = uristring.split(','); var content = parts[1]; var splitcontent = content.replace(/(.{76})/g, "$1\n"); return parts[0] + ',\n' + splitcontent; } exports.generate = function (options, callback) { options.mixintemplate = 'mixin.scss'; options.icontemplate = 'icon.scss'; options.iconfile = 'icon.scss'; options.mixinfile = 'mixin.scss'; exports.generateSVGSprite(options, function (error) { if (error) { callback(error); } callback(); }); } exports.generateSVGSprite = function (options, callback) { var templatePathMixin = path.join(path.dirname(__dirname), 'templates', options.mixintemplate); var templatePathIcon = path.join(path.dirname(__dirname), 'templates', options.icontemplate); if(options.templatePathMixin) { templatePathMixin = options.templatePathMixin; } if(options.templatePathIcon) { templatePathIcon = options.templatePathIcon; } var spriter = new SVGSprite({ dest: options.out, mode: { css: { dest: options.scssPath, sprite: options.spritePath, render: { scss: { template: templatePathIcon, dest: options.iconfile, scss: true } } } }, shape: { spacing: { padding: 0 } } }); var files = fs.readdirSync(options.iconsPathSvg); files.forEach(function (svg, index) { var svgPath = options.iconsPathSvg + '/' + svg; if (svg.indexOf('.svg') !== -1) { spriter.add( path.resolve(svgPath), svg, fs.readFileSync(svgPath, {encoding: 'utf-8'}) ); } }); spriter.compile(function(error, result, data) { var sprites = []; for (var type in result.css) { mkdirp.sync(path.dirname(result.css[type].path)); fs.writeFileSync(result.css[type].path, result.css[type].contents); if (type === 'sprite') { console.log(result.css[type].path + ' created'); sprites.push(result.css[type].path); } } fs.readFile(templatePathMixin, 'utf8', function (err, mixin) { if (err) { callback(err); } var spriteSVGPath = sprites[0]; var spritesSVGPathSplit = spriteSVGPath.split('/'); var spriteSVG = options.cssSpritePath + '/' + spritesSVGPathSplit[spritesSVGPathSplit.length - 1]; var dimensions = sizeOf(spriteSVGPath); mixin = mixin.split('{{svgSprite}}').join(spriteSVG); mixin = mixin.split('{{dimX}}').join(dimensions.width); mixin = mixin.split('{{dimY}}').join(dimensions.height); fs.writeFile(options.out + '/' + options.scssPath + '/' + options.mixinfile, mixin, function (err) { console.log(options.out + '/' + options.scssPath + '/' + options.mixinfile + ' created'); callback(err); }); }); }); };
import { useState, useEffect } from "react"; import { Accelerometer } from "expo-sensors"; const useAccelerometer = (options = {}) => { const [data, setData] = useState(options.initial); const [available, setAvailable] = useState(); const { availability, interval } = options; useEffect(() => { if (availability) { Accelerometer.isAvailableAsync().then(setAvailable(true)); } if (interval !== undefined) { Accelerometer.setUpdateInterval(interval); } return Accelerometer.addListener(accData => setData(accData)).remove; }, [availability, interval]); return [data, available]; }; export default useAccelerometer;
var inc = 0.05; function setup() { createCanvas(256, 256); pixelDensity(1); } function draw() { var xoff = 0; var yoff = 0; loadPixels(); for(var x = 0; x<width; x++) { yoff = 0; for(var y = 0; y<height; y++) { var index = (x+y*width)*4; var r = noise(xoff, yoff)*255; pixels[index] = r; pixels[index+1] = r; pixels[index+2] = r; pixels[index+3] = 255; yoff+=inc; } xoff+=inc; } updatePixels(); }
import 'isomorphic-fetch'; import React from 'react'; import ReactDOM from 'react-dom'; import { mount, shallow, render } from 'enzyme'; import { configure } from 'enzyme'; import Adapter from 'enzyme-adapter-react-16'; import QuestionsAndAnswers from '../client/app/components/questionsAndAnswers.jsx'; import Header from '../client/app/components/header.jsx'; import Question from '../client/app/components/question.jsx'; import Avatar from '../client/app/components/avatar.jsx'; import ShowAnswersButton from '../client/app/components/showAnswersButton.jsx'; import AnswerSubmissionForm from '../client/app/components/answerSubmissionForm.jsx'; import QuestionSubmissionForm from '../client/app/components/questionSubmissionForm.jsx'; import Answers from '../client/app/components/answers.jsx'; import Answer from '../client/app/components/answer.jsx'; import attractionsData from '../fakeData.js'; configure({ adapter: new Adapter() }); const database = require('../database/data'); describe('Tests client', () => { describe('Basic tests', () => { it('renders without crashing on initial page load', () => { const div = document.createElement('div'); ReactDOM.render(<QuestionsAndAnswers />, div); }); it('renders 1 component on inital page load', () => { const wrapper = shallow(<QuestionsAndAnswers />); expect(wrapper).toHaveLength(1); }); it('renders props correctly', () => { const wrapper = shallow(<QuestionsAndAnswers name="something"/>); expect(wrapper.instance().props.name).toBe('something'); }); }); describe('QuestionsAndAnswers', () => { const wrapper = mount(<QuestionsAndAnswers />); const data = attractionsData[0]; wrapper.setState({ realData: data }); wrapper.setState({ loading: false }); it('always renders a div with data', () => { const divs = wrapper.find("div"); expect(divs.length).toBeGreaterThan(0); }); it('renders Header component after fetching data', () => { expect(wrapper.find(Header).length).toBeGreaterThan(0); }); it('renders Question component after fetching data', () => { expect(wrapper.find(Question).length).toBeGreaterThan(0); }); it('renders Avatar component after fetching data', () => { expect(wrapper.find(Avatar).length).toBeGreaterThan(0); }); it('renders Answers component after fetching data', () => { expect(wrapper.find(Answers).length).toBeGreaterThan(0); }); it('renders Answer component after fetching data', () => { expect(wrapper.find(Answer).length).toBeGreaterThan(0); }); it('renders ShowAnswersButton component after fetching data', () => { expect(wrapper.find(ShowAnswersButton).length).toBeGreaterThan(0); }); it('renders QuestionSubmissionForm component after button click', () => { const button = wrapper.find('button.headerButton'); button.simulate('click'); expect(wrapper.find(QuestionSubmissionForm).length).toBeGreaterThan(0); }); it('does not render QuestionSubmissionForm component after second button click', () => { const button = wrapper.find('button.headerButton'); button.simulate('click'); expect(wrapper.find(QuestionSubmissionForm).length).toBe(0); }); it('renders AnswerSubmissionForm component after button click', () => { const button = wrapper.find('button.button').at(0); button.simulate('click'); expect(wrapper.find(AnswerSubmissionForm).length).toBeGreaterThan(0); }); it('does not render AnswerSubmissionForm component after second button click', () => { const button = wrapper.find('button.button').at(0); button.simulate('click'); expect(wrapper.find(AnswerSubmissionForm).length).toBe(0); }); }); describe('Header Component', () => { const wrapper = shallow(<Header />); it('should not show question submission form on initial page load', () => { expect(wrapper.find('QuestionSubmissionForm').length).toEqual(0); }); it('should change formIsDisplayed in component state to true on button click', () => { const button = wrapper.find('button.headerButton'); button.simulate('click'); expect(wrapper.state().formIsDisplayed).toEqual(true); }); it('should show question submission form once button is clicked', () => { expect(wrapper.find('QuestionSubmissionForm').length).toEqual(1); }); }); describe('Question Component', () => { const data = attractionsData[0].questions[0]; const wrapper = shallow(<Question question={data} />); it('renders 1 component', () => { expect(wrapper).toHaveLength(1); }); it('should display one answer from data on initial page load', () => { expect(wrapper.find('Answers').length).toEqual(1); }); it('should change answerFormDisplayed in component state to true on button click', () => { const button = wrapper.find('button.button'); button.simulate('click'); expect(wrapper.state().answerFormDisplayed).toEqual(true); }); }); }); // Testing for database describe('Tests database', () => { describe('Entries in database', () => { test('Should have 200 items corresponding to agreed upon number of attractions', (done) => { function callback(err, num) { if (err) { console.log('error getting count'); } expect(num).toEqual(200); done(); } database.QuestionModel.count(callback); }); test('Should return only one object when querying database by id', (done) => { function callback(err, data) { if (err) { console.log('error retreiving data'); } expect(typeof data).toEqual('object'); done(); } database.getById(0, callback); }); test('Fake Q&A data should contain at least one question per attraction', (done) => { function callback(err, data) { if (err) { console.log('error retreiving data'); } expect(data.questions.length >= 1).toEqual(true); done(); } database.getById(50, callback); }); test('Fake Q&A data should contain at least one answer per question', (done) => { function callback(err, data) { if (err) { console.log('error retreiving data'); } expect(data.questions[0].answers.length >= 1).toEqual(true); done(); } database.getById(100, callback); }); }); })
document.onload(function (event) { console.log("Page is loaded!"); }); function showMessage() { alert("Please read & follow the instructions..."); }
const AGM = require('agilemanager-api'); let options = { clientId: process.env.AGM_clientId, clientSecret: process.env.AGM_clientSecret, apiURL: process.env.AGM_apiUrl }; let agm = new AGM(options); function agmLogin (agm) { return new Promise(function(resolve, reject) { delete agm.token; agm.login(function (err, body) { if (err) { console.log('Error on login'); reject(err); } else { console.log('AGM Logged in.\n'); resolve(body); } }); }); } module.exports = { agm: agm, agmLogin: agmLogin }
var express = require('express'); var path = require('path'); var mysql = require('mysql'); var bodyParser = require('body-parser'); var port = process.env.port || 3000; var app = express(); app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'pug'); app.use(bodyParser.urlencoded({ extended: true })); var pool = mysql.createPool({ connectionLimit: 1, queueLimit: 10, aquireTimeout: 5000, host: 'localhost', user: 'root', password: 'qwerty', database: 'test' }); app.get('/', function(req, res) { pool.getConnection(function(err, conn){ if (err) { console.log(err.stack); return; } conn.query('SELECT * FROM `test_table`', function(err, rows) { if (err) console.log(err); res.render('index', {rows}); conn.release(); }); }); }); pool.getConnection(function(err, connection) { var query = `INSERT INTO test_table (NAME, INFO) VALUES ('new item name', 'new item value')`; connection.query(query, function(err) { if(err) { console.log(err); } connection.release(); }) }) app.listen(port, function() { console.log('app listening on port ' + port); });
Ext.define('AM.view.master.report.employee.WorkCustomer', { extend: 'Ext.Container', alias: 'widget.masterreportemployeeWorkCustomerReport', layout : { type : 'vbox', align : 'stretch' }, header: false, headerAsText : false, initComponent: function(){ var me = this; // me.buildToolbar(); // console.log("init component of masterreportemployeeWorkCustomerReport"); this.items = [ { xtype : 'masterreportuserList', // xtype : 'container', // html : "Awesome shite", flex: 2 }, me.buildChartInspect() ]; this.callParent(arguments); }, buildChartInspect: function(){ // console.log("build Chart Inspect called"); return { xtype : "chartInspect", chartStoreFields : [ 'name', 'data1', 'id' ], chartStoreUrl : 'api/work_customer_reports', listXType: 'workcustomerList', yAxisLabel : "Total Maintenance", xAxisLabel : "Customer", panelTitle: "Customer", flex: 7, chartListWrapperXType: 'masterreportemployeeWorkCustomerReport', autoChartLoad: false } }, });
import { createStackNavigator } from "react-navigation"; import { RegisterScreen, LoginScreen } from "@app/screens"; export default createStackNavigator( { Register: { screen: RegisterScreen, navigationOptions: { header: null } }, Login: { screen: LoginScreen, navigationOptions: { header: null } } }, { initialRouteName: "Login" } );
import{combineReducers} from "redux"; import storage from 'redux-persist/lib/storage'; import {persistReducer} from "redux-persist"; /** * reducer */ import opt from './opt'; import topbar from "./topbar"; import form from "./form"; import users from "./users"; import Admin from "./Admin"; import alert from "./alert"; const persistConfig = { key: "root", storage, whitelist:['modul'] } /** * * @type {Reducer<CombinedState<unknown>>} */ const rootReducers = combineReducers({ Admin, opt, topbar, alert, form, users }) export default persistReducer(persistConfig,rootReducers)
let resumeData = { // "imagebaseurl":"https://rbhatia46.github.io/", name: "Michael Bither", role: "Full Stack Web Developer", linkedinId: "https://www.linkedin.com/in/michaelbither/", // "skypeid": "Your skypeid", roleDescription: '"We build our computer (systems) the way we build our cities: over time, without a plan, on top of ruins." - Ellen Ullman', socialLinks: [ { name: "linkedin", url: "https://www.linkedin.com/in/michaelbither", className: "fa fa-linkedin" }, { name: "github", url: "http://github.com/bliff182", className: "fa fa-github" } // { // name: "skype", // url: "http://twitter.com/rbhatia46", // className: "fa fa-twitter" // } ], aboutme: "Full Stack Web Developer with several years of experience in the IT industry, transitioning from system administration to MERN development. Recently earned a certificate in Full Stack Development from Rutgers University, with newly developed skills in front end libraries frameworks including React, jQuery, Bootstrap, and responsive design, as well as back end technologies including Node, Express, MySQL, and MongoDB.", address: "michael.bither@gmail.com", website: "https://github.com/bliff182", education: [ { UniversityName: "Rutgers Coding Bootcamp", specialization: "Full Stack Web Development", MonthOfPassing: "March", YearOfPassing: "2020", Achievements: "Certificate earned with A+ average" }, { UniversityName: "Rutgers University", specialization: "B.S. in Marketing", MonthOfPassing: "May", YearOfPassing: "2012", Achievements: "Member of Delta Epsilon Iota Academic Honor Society" } ], work: [ { CompanyName: "Terra Holdings, LLC", specialization: "Junior System Administrator", MonthOfLeaving: "2014 - Present", // YearOfLeaving: "2018", Achievements: "- Maintains computer, server, and network health for enterprise consisting of over 1000 users" }, { CompanyName: "New Jersey Devils", specialization: "Promo Team Member", MonthOfLeaving: "2013 - 2014", // YearOfLeaving: "2018", Achievements: "Oversaw and supervised the execution of all pre/in-game fan activities and additional team events" } ], // skillsDescription: "Your skills here", skills: [ { skillname: "HTML5" }, { skillname: "CSS" }, { skillname: "JavaScript" }, { skillname: "SQL" }, { skillname: "React" }, { skillname: "jQuery" }, { skillname: "Bootstrap" }, { skillname: "Material-UI" }, { skillname: "Node.js" }, { skillname: "Express" }, { skillname: "MongoDB" }, { skillname: "MySQL" }, { skillname: "Firebase" } ], portfolio: [ { name: "MealMatch", description: "Discover and save nearby restaurants!", imgurl: "images/portfolio/discover.png", projurl: "https://github.com/bliff182/rinclusion" }, { name: "Arrested Development Clicky Game!", description: "Click on the characters, but don't click any more than once!", imgurl: "images/portfolio/movision.png", projurl: "https://github.com/bliff182/movision" }, { name: "Onion Peeler", description: "View and comment on the latest articles from The Onion", imgurl: "images/portfolio/o_s-home.png", projurl: "https://github.com/bliff182/banger" }, { name: "Bamazon", description: "Node CLI app for making purchases and updating inventory", imgurl: "images/portfolio/BC_initial.png", projurl: "https://github.com/bliff182/micate.js" } ], testimonials: [ { description: "This is a sample testimonial", name: "Some technical guy" }, { description: "This is a sample testimonial", name: "Some technical guy" } ] }; export default resumeData;
$(document).ready(function() { $('.product-options').hide(); $('content').on("click", ".mobilpay", function () { console.log('aaaa'); $('.mobilpay').hide(); $('.product-options').show(); }); });
// src/components/Title.js export default function Title(props) { return <h1>The Legendary Scoreboard App</h1>; }
import React from 'react' import Header from 'components/Header' import ToolsPanel from 'components/ToolsPanel' import Artboard from 'components/Artboard' const App = ({ currentArtboard }) => { return ( <div className="rtboard"> <Header /> <div className="is-marginless tile is-ancestor"> <div className="is-1 is-paddingless tile is-vertical is-parent"> <ToolsPanel /> </div> <div className="is-11 is-paddingless tile is-vertical is-parent"> <Artboard id={currentArtboard}/> </div> </div> </div> ) } export default App
import React, { Fragment } from 'react'; import { Typography } from '@material-ui/core'; import styled from 'styled-components'; import OldWeb from '../assets/img/giphy.gif'; export default function Motivation() { return ( <Fragment> <Typography className='title' variant='h5' color='secondary'>Motivation</Typography> <hr /> <Text> <Typography variant='body2' color='secondary'> Everyone has been tired of similar and boring websites. In the era of the growth of Artificial Intelligence, Electric cars, Rocket Launches - this is unacceptable. </Typography> <Typography variant='body2' color='secondary'> I see the point in my work when it is kind of art. Otherwise it's a routine. </Typography> </Text> <Img src={OldWeb} alt='' /> <Typography variant='caption' color='primary' style={{ marginBottom: 15, marginLeft: 5 }}>90% of web right now.</Typography> <Text> <Typography variant='body2' color='secondary'> My goal is using all af my possibilities to create the modern & creative products. Doesn`t matter what type of project you build. </Typography> <Typography variant='body2' color='secondary'> Also, it is very important to have a clear position on this matter and not follow the path of simplification and uniformity. </Typography> <Typography variant='body2' color='secondary'> In my opinion, web deserves to be more creative and interesting. </Typography> </Text> </Fragment> ) } const Text = styled.div` padding-left: 20px; p { margin-bottom: 10px; } `; const Img = styled.img` width: 100%; padding-left: 5px; `;
/* *= require html5shiv *= require selectivizr */
const express = require("express"); const router = express.Router(); router.use((req, res, next)=> { res.append('Access-Control-Allow-Origin', ['*']); res.append('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS'); res.append('Access-Control-Allow-Headers', 'Origin, Content-Type, X-Auth-Token'); res.append('Content-Type', 'application/json'); next(); }); router.get('/', (req, res) => { res.send('API made by Itay Eylon - Buses Analytics Page'); }); router.use('/drivers', require('./drivers')); router.use('/times', require('./times')); module.exports = router;
export default () => <div>Contact page</div>
import { GraphQLObjectType, GraphQLID, GraphQLList, GraphQLNonNull } from 'graphql' import imageType from '../types/image' import resolve from '../resolvers/image' const image = { name: 'image', type: imageType, args: { id: { type: new GraphQLNonNull(GraphQLID) } }, resolve } export default image
// eslint-disable-next-line unicorn/filename-case import React from "react"; import "./MapOpen.css"; import {Map, Marker, TileLayer, Popup} from "react-leaflet"; import Trees from "./data/arbustum.json"; import treepng from "./data/tree.png"; import MarkerClusterGroup from "react-leaflet-markercluster"; import leaf from "./data/leaf.png"; import TreePopup from "./TreePopup"; //Icon properties // eslint-disable-next-line no-undef const icon = L.icon({ iconUrl: treepng, iconSize: [50, 50], }); function MapOpen() { return ( <Map center={[50.64, 5.57]} zoom={14}> <TileLayer url={"https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"} attribution={ '&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors' } /> <MarkerClusterGroup disableClusteringAtZoom={15}> {Trees.map((tree) => ( <Marker icon={icon} key={tree.arbotag} position={[tree.y_phi, tree.x_lambda]}> <TreePopup name={tree.nom_complet} circonf={tree.circonf} /> </Marker> ))} </MarkerClusterGroup> </Map> ); } export default MapOpen;
"use strict"; module.exports = function(sequelize, DataTypes) { var Category = sequelize.define("Category", { id: { type: DataTypes.INTEGER, unique: false }, uuid: { type: DataTypes.UUID, defaultValue: DataTypes.UUIDV1, primaryKey: true }, title: DataTypes.STRING, description: DataTypes.TEXT }); Category.associate = function(models) { // Using additional options like CASCADE etc for demonstration // Can also simply do Task.belongsTo(models.User); Category.belongsTo(models.Area, { onDelete: "CASCADE", foreignKey: { allowNull: false } }); } Category.addNew = function(category){ var {AreaName, title = "", description = ""} = category; return sequelize.transaction(function(t) { return Category.max('id', {where: {AreaName}}, {transaction: t}) .then((id) => { if(isNaN(id)) id = 0; return Category.create({ id: id+1, AreaName, title, description }, {transaction: t}); }) }); } Category.edit = function(area, id, title, description){ return Category.find({ where: { id: id, areaName: area } }).then(category => { if(category){ return Category.upsert({ id: category.id, uuid: category.uuid, title, description }).then(() => { return { id: category.id, title, description } }) } }) } Category.delete = function(area, id){ return Category.destroy({ where: { id: id, areaName: area } }).then(() => { return {area, id}; }) } return Category; };
// app.js import express from 'express' import jade from 'jade' import http_module from 'http' import compression from 'compression' const config = { COSMIC_BUCKET: process.env.COSMIC_BUCKET || 'pflannery' } const app = express() app.use(compression()) app.set('view engine', 'jade'); app.set('views', __dirname + '/views') app.set('port', process.env.PORT || 3000) // app.use(express.static(__dirname + '/public')) const partials = {}; require('./controllers/index')(app, config, partials) const http = http_module.Server(app) http.listen(app.get('port'), () => { console.info('==> 🌎 Go to http://localhost:%s', app.get('port')); })
$(document).ready(function(){ function getQuote(){ var quotes = ["The World is a book and those who do not travel read only one page", "The greatest thing you'll ever learn is just to love and be loved in return", "I am someone who is looking for love. Real love. Ridiculous, inconvenient, consuming, can't-live-with-out-each-other love. And I don't think that love is here in this expensive suite in this lovely hotel."]; var author = ["- Saint Augustine", "- Toulouse Lautrec", "- Carrie Bradshaw"]; var randomNum = Math.floor((Math.random()*quotes.length)); var randomQuote = quotes[randomNum]; var randomAuthor = author[randomNum]; $(".quote").text(randomQuote); $(".author").text(randomAuthor); } $(".btn").on("click", function(){ getQuote(); }); });
import React, { useState, useEffect } from "react"; import LocationManager from "../../modules/LocationManager"; import EmployeeCard from "../employees/EmployeeCard"; import EmployeeManager from "../../modules/EmployeeManager" //component responsible for showing 1 location with employees that work there const LocationWithEmployees = props => { const [location, setLocation] = useState({}); const [employees, setEmployees] = useState([]); useEffect(() => { //making call to database to get the locationwithEmployees LocationManager.getWithEmployees(props.match.params.locationId) .then(APIResult => { setLocation(APIResult); setEmployees(APIResult.employees) }) }, []); const deleteEmployee = (id) => { EmployeeManager.deleteEmployee(id).then(() => { LocationManager.getWithEmployees(props.match.params.locationId) .then(APIResult => { setLocation(APIResult); setEmployees(APIResult.employees) }); }); }; return ( <div className="card"> <p>Location: {location.name}</p> {employees.map(employee => <EmployeeCard key={employee.id} employee={employee} deleteEmployee={deleteEmployee} {...props} /> )} </div> ); }; export default LocationWithEmployees
import React from 'react'; import { View, Text, Button, StyleSheet, TextInput } from 'react-native'; import { TouchableOpacity } from 'react-native-gesture-handler'; import Colors from '../constants/Colors'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; import { updateUserName, updatePassword, login, getUser } from '../actions/user'; class LoginScreen extends React.Component { res = {}; login = async () => { res = await this.props.login() // console.log(this.props.user) console.log(res) if(res.userID > 0) this.props.navigation.navigate('Categories') } componentDidMount = async () => { console.log(this.res) console.log(this.props.user) // console.log(await this.props.getUser(this.props.user.id,this.props.user.token)) if(Object.keys(this.props.user).length != 0) this.props.navigation.navigate('Categories') } render () { return ( <View style={styles.screen}> <TextInput style = {styles.border} value = {this.props.user.updateUserName} onChangeText = {(input) => this.props.updateUserName(input)} placeholder = 'Username' /> <TextInput style = {styles.border} value = {this.props.user.updatePassword} onChangeText = {(input) => this.props.updatePassword(input)} placeholder = 'Password' /> <TouchableOpacity color={'white'} style={styles.mainButton} onPress = {() => this.login()}> <Text style={{color: 'white'}}>Login</Text> </TouchableOpacity> <Text style = {{marginTop: 20}}>or</Text> <TouchableOpacity style = {styles.loginButton} onPress = {() => this.props.navigation.navigate('Signup')}> <Text>Signup</Text> </TouchableOpacity> </View> ); } }; const styles = StyleSheet.create({ screen: { flex: 1, //justifyContent: 'center', textAlignVertical: 'top', alignItems: 'center', paddingVertical: 10 }, mainButton: { marginTop: 20, paddingVertical: 10, alignItems: 'center', backgroundColor: Colors.accentColor, borderColor: 'white', borderWidth: 1, borderRadius: 5, width: 200 }, loginButton: { marginTop: 20, paddingVertical: 10, alignItems: 'center', borderColor: 'grey', borderWidth: 1, borderRadius: 5, width: 200 }, border: { width: '85%', margin: 10, padding: 15, fontSize: 16, borderColor: 'grey', borderBottomWidth: 1, textAlign: 'center' } }); const mapDispatchToProps = (dispatch) => { return bindActionCreators({ updateUserName, updatePassword, login, getUser }, dispatch) } const mapStateToProps = (state) => { return { user: state.user } } export default connect(mapStateToProps, mapDispatchToProps)(LoginScreen); // export default LoginScreen;
/** * Created by wen on 2016/8/17. */ import React from 'react'; import BMmodifyName from './BMmodifyName'; export default { path: '/bmmodifyName', async action() { return <BMmodifyName />; }, };
const { ApolloServer, gql, makeExecutableSchema } = require("apollo-server") const movieSchema = require("./schemas/movie") const seriesSchema = require("./schemas/series") const typeDefs = gql` type Query type Mutation ` const schema = makeExecutableSchema({ typeDefs: [typeDefs, movieSchema.typeDefs, seriesSchema.typeDefs], resolvers: [movieSchema.resolvers, seriesSchema.resolvers], }) const server = new ApolloServer({ schema }) server.listen().then(({ url }) => { console.log(`Apollo Server ready at ${url}`) })
const express = require('express'); const md5 = require('md5'); const Router = express.Router(); const mongoose = require('mongoose'); //mongoose操作mongodb // brew install mongodb const model = require('./model'); const User = model.getModel('user'); //登录 Router.post('/login',function(req,res){ const {phone,password} = req.body; User.findOne({phone},function(err,doc){ if(err){ return res.status(500).json('服务器内部错误'); } if(!doc){ return res.status(400).json('该手机号还没有注册') } const timestamp = Date.parse(new Date()); //获取时间戳 const accessToken = md5(phone + password + timestamp); //生成accessToken User.update({phone},{accessToken},function(e,d){ if(e) { return res.status(500).json('服务器内部错误'); } const {phone,_id:_id} = doc; const pwd = doc.password; if(password !== pwd) { return res.status(400).json('密码错误'); } res.cookie('Authorization',accessToken); return res.status(200).json({code:0,phone,accessToken,'userId':_id}); }) }) }); //注册 Router.post('/register',function(req,res){ const {phone,password} = req.body; User.findOne({phone},function(err,doc){ if(doc){ return res.status(400).json("用户名已经存在"); } let date = new Date(); const createTime = date.getFullYear() + '年' + date.getMonth() + '月' + date.getDate() + '日 ' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds() const timestamp = Date.parse(new Date()); //获取时间戳 const accessToken = md5(phone + password + timestamp); //生成accessToken const score = 100; //注册成功后,奖励100积分 const userModel = new User({phone,password,accessToken,score,avatar:'',balance:0,discount:0,username:'',signTime:'',createTime}); userModel.save(function(e,d){ if(e){ return res.status(500).json('服务器内部错误'); } const {phone,accessToken,_id:_id} = d; res.clearCookie('Authorization'); res.cookie('Authorization',accessToken); return res.status(200).json({code:0,phone,accessToken,'userId':_id}); }) }) }) //重置密码 Router.post('/resetPassword',function(req,res){ const {phone,password} = req.body; User.findOne({phone},function(err,doc){ if(!doc){ return res.status(400).json("该用户没有注册"); } const timestamp = Date.parse(new Date()); //获取时间戳 const accessToken = md5(phone + password + timestamp); //生成accessToken User.update({phone},{password,accessToken},function(e,d){ if(e) { return res.status(500).json('服务器内部错误'); } res.clearCookie('Authorization'); res.cookie('Authorization',accessToken); return res.status(200).json({code:0,phone,accessToken,'userId':doc._id}); }) }) }) // 获取用户个人信息 Router.get('/userInfo',function(req,res){ const {userId} = req.query; const accessToken = req.header('accessToken') User.findOne({'_id':userId,accessToken},function(err,doc){ if(err){ return res.status(500).json('服务器内部错误'); } if(!doc){ return res.status(401).json('会话过期,请重新登录'); } const date = new Date(); const currentTime = date.getFullYear() + '年' + date.getMonth() + '月' + date.getDate() + '日' const {phone,score,avatar,balance,discount,username,signTime} = doc; let isSign = (signTime == currentTime); return res.status(200).json({code:0,phone,score,avatar,balance,discount,username,isSign}); }) }); // 更新用户信息 Router.post('/update',function(req,res){ const {avatar,username,userId} = req.body; const accessToken = req.header('accessToken') User.findOne({'_id':userId,accessToken},function(err,doc){ if(err){ return res.status(500).json('服务器内部错误'); } if(!doc){ return res.status(401).json('会话过期,请重新登录'); } var params = {}; if(avatar != null) { params = {avatar}; }else if (username != null){ params = {username} }else if(username == null && avatar == null){ return res.status(400).json('请传入参数'); }else{ params = {username,avatar}; } User.update({'_id':userId},params,function(e,d){ if(e) { return res.status(500).json('服务器内部错误'); } User.findOne({'_id':userId,accessToken},function(er,dc){ const {username,avatar,phone} = dc; console.log(username); return res.status(200).json({code:0,username,avatar,phone}); }) }) }) }); //每日签到 Router.post('/sign',function(req,res){ //用户如果已经签到 const {userId} = req.body; const accessToken = req.header('accessToken') User.findOne({'_id':userId,accessToken},function(err,doc){ if(err){ return res.status(500).json('服务器内部错误'); } if(!doc){ return res.status(401).json('会话过期,请重新登录'); } let date = new Date(); const currentTime = date.getFullYear() + '年' + date.getMonth() + '月' + date.getDate() + '日' const {signTime,score} = doc; if(signTime == currentTime){ return res.status(200).json({code:1,msg:"今天已经签到"}); }else{ //签到成功,积分加50 User.update({'_id':userId},{'signTime':currentTime,'score':score+50},function(e,d){ if(e) { return res.status(500).json('服务器内部错误'); } return res.status(200).json({code:0,score:score+50}); }) } }) }); module.exports = Router;
import React,{Component} from 'react' import { View, Text, StyleSheet, StatusBar, Image, WebView, Platform, BackAndroid, TouchableOpacity, ToastAndroid, } from 'react-native' import SegmentedControlTab from 'react-native-segmented-control-tab' import NewsList from '../news/NewsList' import Information from '../news/Information' import TodayNews from '../news/TodayNews' export default class News_Tabs extends Component { constructor(props) { super(props) this.state = { selectedIndex: 0, selectedIndices: [0], customStyleIndex: 1, } } handleCustomIndexSelect = (index) => { this.setState({ ...this.state, customStyleIndex: index, }); } componentDidMount() { this.handleCustomIndexSelect(0); } componentWillMount() { this.setState({ customStyleIndex: 1, }); } render() { return ( <View style={styles.container}> <View style={styles.tab}> <SegmentedControlTab values={['头条','虎扑', '资讯']} selectedIndex={this.state.customStyleIndex} onTabPress={this.handleCustomIndexSelect} borderRadius={0} tabsContainerStyle={{ height: 30, backgroundColor: '#FFFFFF',width:360,alignSelf:'center'}} tabStyle={{ backgroundColor: '#FFFFFF',borderWidth:0.5,borderColor:'#DFDFDF' }} activeTabStyle={{ backgroundColor: 'white', marginTop: 0, }} tabTextStyle={{ color: '#000000'}} activeTabTextStyle={{ color: '#2979FF' }} /> </View> <View style={styles.container}> {this.state.customStyleIndex === 0 && <View style={styles.container}> <NewsList></NewsList> </View> } {this.state.customStyleIndex === 1 && <View style={styles.container}> <NewsList></NewsList> </View> } {this.state.customStyleIndex === 1 && <View style={styles.container}> <NewsList></NewsList> </View> } </View> </View> ); } } const styles = StyleSheet.create({ container: { flex:1, }, tab:{ flexDirection:'row', justifyContent:'center', backgroundColor:'#000000', }, tabViewText: { color: '#444444', fontWeight: 'bold', marginTop: 50, fontSize: 18 }, titleText: { color: '#444444', padding: 20, fontSize: 14, fontWeight: '500' }, headerText: { padding: 8, fontSize: 14, color: '#444444' }, tabContent: { backgroundColor: '#000000', flexGrow:1 }, })
function formValidation() { var passId = document.register.password; var rePass = document.register.repassword; var uName = document.register.username; var uEmail = document.register.emailId; var uPhone = document.register.phoneNo; var bankAcc = document.register.bankNo; console.log("srvaani heyy"); if(passid_validation(passId,7,12)) { if(allLetter(uName)) { if(ValidateEmail(uEmail)){ if(validatePhone(uPhone)){ if(validateBankAcc(bankAcc)){ if(passMatch(passId,rePass)) return true; } } } } } return false; } function passMatch(pass,rePass){ alert(pass) if(!(pass.match(rePass))){ alert("passwords do not match"); return false; } else return true; } function validateBankAcc(AccNum){ var cardNoFormat = /^(?:4[0-9]{12}(?:[0-9]{3})?)$/; if(AccNo.value.match(cardNoFormat)) return true; else{ alert("bank account format is wrong"); return false; } } function validatePhone(uPhone) { var phoneno = /^\d{10}$/; if((uPhone.value.match(phoneno))) return true; else return false; } function passid_validation(passid,mx,my){ var passid_len = passid.value.length; if (passid_len == 0 ||passid_len >= my || passid_len < mx){ alert("Password should not be empty / length be between "+mx+" to "+my); passid.focus(); return false; } return true; } function allLetter(uname){ var letters = /^[A-Za-z]+$/; if(uname.value.match(letters)) return true; else{ alert('Username must have alphabet characters only'); uname.focus(); return false; } } function ValidateEmail(uemail){ var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/; if(uemail.value.match(mailformat)) return true; else { alert("You have entered an invalid email address!"); uemail.focus(); return false; } }
let side1 = document.querySelector("#side-1"); let side2 = document.querySelector("#side-2"); let btnHypo = document.querySelector("#btn-hypo"); let showResult = document.querySelector("#output-hypo"); function calculateHypotenuse() { if (side1.value <= 0 || side2.value <= 0) { showResult.innerText = "Please enter a valid number"; } else { let a = side1.value * side1.value; let b = side2.value * side2.value; let c = Math.sqrt(a + b); let d = c.toFixed(2); showResult.innerText = `The length of hypotenuse is ${d}`; } } btnHypo.addEventListener("click", calculateHypotenuse);
$(document).ready(function() { $('#login').click(function() { var email = $('#email').val(); var password = $('#password').val(); // Checking for blank fields. if (email == '' || password == '') { $('input[type="text"],input[type="password"]').css( 'border', '2px solid red' ); $('input[type="text"],input[type="password"]').css( 'box-shadow', '0 0 3px red' ); } else { var headers = { authorization: 'Basic ' + btoa(email + ':' + password) }; $.ajax({ url: 'http://localhost:9000/login', method: 'GET', headers: headers, success: function(data, textStatus, xhr) { console.log('login successful ' + xhr.status); var token = xhr.getResponseHeader('x-auth-token'); console.log('x-auth-token ' + token); localStorage.setItem('x-auth-token', token); window.location.href = '/home.html'; }, error: function(xhr, textStatus, error) { console.log('login failed ' + xhr.status); $('#loginError').text('Login failed ' + xhr.status); } }); } }); });
import Img from "gatsby-image/withIEPolyfill" import React, { useState } from "react" import Modal from "react-responsive-modal" import { Button, Card, Flex } from "rebass" import styled from "styled-components" import Open from "../components/svg/open" import { theme } from "../utils/styles" import ProductCard from "./productcard" const modalStyles = { overlay: { // padding: 0, }, modal: { padding: 0, borderRadius: 12, maxWidth: `500px`, }, closeButton: { boxShadow: "0 0 0 transparent", outline: "none", cursor: "pointer", left: 20, }, } const Container = styled(Flex)` position: relative; ` const StyledCard = styled(Card).attrs({ width: [3 / 10], })` background: ${props => props.theme.colors.secondary}; ` const Image = styled(Img)` width: 100%; height: 30vw; border-top-left-radius: 8px; border-top-right-radius: 8px; background: white; @media (min-width: 1199px) { height: 25vw; } ` const ProductFeed = ({ products, location }) => { const [open, setOpen] = useState(false) const toggle = () => setOpen(!open) const [current, setIdx] = useState(0) const handleClick = i => { setIdx(i) toggle() } return ( <> <Container mb={4} flexWrap={"wrap"}> {products.map(({ category: { name }, image, productName }, index) => { return ( <StyledCard key={index} mx={"auto"} my={3} borderRadius={12} boxShadow={`0 2px 8px ${theme.colors.primaryBR4}`} > {image && ( <Image fluid={image.fluid} objectFit={name === "order" ? "cover" : "contain"} /> )} <Flex style={{ minHeight: 90 }} alignItems={"center"} justifyContent={"center"} > <Button onClick={() => handleClick(index)} style={{ fontWeight: 400 }} variant="clear" > {productName} <Open width={24} height={24} fill={theme.colors.primary} /> </Button> </Flex> </StyledCard> ) })} </Container> {products[current] && ( <Modal open={open} onClose={toggle} styles={modalStyles} closeIconSize={50} closeIconSvgPath={ <> <path fill={theme.colors.primary} d="M15.41 16.59L10.83 12l4.58-4.59L14 6l-6 6 6 6 1.41-1.41z" /> <path fill="none" d="M0 0h24v24H0V0z" /> </> } children={ <ProductCard product={products[current]} location={location} toggle={toggle} /> } /> )} </> ) } export default ProductFeed
const aFiresideChat = { didRun: false, didLie: false, start() { log("######################") log("Part One: A Fireside Chat") log("######################") space() log("You find yourself in a clearing.") log( "You cannot remember how you got there or how long you have been there." ) log("Night is beginning to fall, and it will be cold soon.") log( "You are starting to get hungry, and to be honest you could use a drink." ) log("At the far end of the clearing, you see a flicker of orange light.") log("A campfire, perhaps? Could be.") log("The hunger is starting to grow. Soon you will be ravenous.") act = { runToLight: () => this.enterCamp(), runFromLight: () => run(), } actPrmpt() return game.switchLog(game.cmds) }, run() { this.didRun = true log("You begin to run, run faster than you ever have before.") log("You're really making good time.") log( "You fly through the clearing, the long grass softly crunching under your feet" ) log("Who can say how long you run?") log("You run until your lungs burn and your legs feel like lead weights.") log( "Finally, you collapse in a heap. You're sweaty, hungry, tired and you feel very, very silly." ) log("'This is dumb' you think, 'why am I running from a campfire'?") log("You slowly make your way back through the clearing.") log( "Luckliy you're not nearly as fast a runner as you thought you were and it shouldn't take too long to reach the camp, and whoever may be there." ) space() return this.enterCamp() }, enterCamp() { if (this.didRun) { log("You enter the camp.") log( "You're sore, sweaty and you can't remember a time when you've been more hungry." ) } else { log( "Spurred on by your hunger, you quickly traverse the field and enter the camp." ) } log( "As you draw closer to the fire, you see a hunched figure with its back to you." ) log( "All in silhouette, you can't tell anything about how the figure might look." ) log("Placed on opposite sides of the fire, are two time worn logs.") if (this.didRun) { log( "When you come close enough for your footfalls to be heard, an old man's voice says in a rasping croak 'You certainly took your time didn't you?'" ) } else { log( "As you draw close enough for the figure to be aware of your presence, you hear 'Ah, you're right on time.'" ) log( "His voice, you're reasonably sure it's a he, sounds like it comes from far, far away." ) } log("He whirls around, with a speed that belies the age in his voice.") log("You see a wizened, stooping old man. Eighty if he's a day.") log( "Bald-pated, with a few strands of wispy hair desperately clinging to the sides of his skull, two impossibly bushy eyebrows leap from his forehead like agitated caterpillars." ) log( "Beneath those fuzzy monsters, two watery, sleepy eyes frame a bulbous nose." ) log( "He smiles and all at once his face is a mass of fine wrinkles. A few teeth are still fighting the good fight in his gummy mouth. Below that, you see a neck with a fleshy wattle that would put any turkey to shame." ) log( "He wears a thin, threadbare sweater and shabby grey trousers. There's a rip in one of his beaten up canvas shoes." ) if (this.didRun) { log( "'I prefer it when people keep their appointments promptly' he says, a thick spittle flying with every 'p' sound." ) } else { log( "'I like prompt people, well done.' he says. 'Just in time for our appointment'." ) } log( "'What are you talking about an appointment?' you say, 'I've made no appointment'." ) log( "'Of course you have an appointment, you just haven't made it yet' he quickly replies 'When you do, I'm sure I'll be the first to know'." ) space() space() space() log("...this guy may be crazy.") space() return this.sayYourName() }, sayYourName() { log("The strange man gestures to the logs 'Come, come, sit down!'") log( "As he moves to the far side of the fire, you notice that there is a large copper pot suspended over the blaze. A thick, brown, chunky liquid bubbles in it. Immediately your mouth begins to water." ) log( "The man's knees pop as he settles down on the ancient trunk. 'Stew should be ready soon, I reckon. Suppose we should get down to business before dinner'." ) log("'Ridiculous' you think, 'That stew is clearly ready NOW!'") log( "Ignoring the now audible rumble in your tum-tum, you gingerly sit on the log opposite the strange man." ) log("'What business?' you ask, 'Who are you and what am I doing here'?") log( "The man throws up his hands in a mock gesture of surrender. 'So many questions! So many questions! Let's not get ahead of ourselves. First things first. Yes, first things are usually best done first. So they are, so they are.'" ) log( "The strange man jabs his bony finger in your direction and says 'And the first thing that we should find out is what we're going to call each other. What's yer, waddaya call it? Yer name?'" ) log("HEY! That's an excellent question. What IS your name?") act = { sayName: (name) => storeNames(name), } space() if (parse(bag.illu)) { log(oldManIllo) } return "Please enter act.sayName() with your name between the parentheses, and using quotation marks. For example sayName('Frederick')" }, dinner(name) { const oldMan = bag.oldMansName log( `'My name is ${name}' you say calmly. Man, you would REALLY like some of that stew.` ) log( `'${name.toUpperCase()}?' the old man exclaims, 'What kind of name is that? Me, I'm called ${oldMan} and that's a proper name believe you me.'` ) log(`'Pfff, ${name}' sniffs ${oldMan} as he stirs the steaming kettle.`) log( "'In MY day we had proper names I can tell you, why I remember when...' he mutters to himself as you decide to tune him out." ) log( "What are you doing here you wonder. How did you get here? What were you doing before you got here?" ) log( "You realize with some alarm that you don't know the answer to any of those questions." ) log( `All you can say for sure is that you're ${name} and you're sitting with a crazy man named ${oldMan}, waiting for him to serve dinner.` ) space() log( `Suddenly your reverie is interrupted by ${oldMan} shouting 'DINNER'S READY'!!! at the top of his lungs.` ) log("'GIT IT WHILES ITS HOT'!!!") log( `${oldMan} produces a wooden bowl and ladle, seemingly from nowhere, and in one smooth motion scoops a generous portion of stew into the bowl and tosses it to you underhanded over the fire. You'd probably admire the grace and fluidity of it all if you weren't suddenly deathly afraid of molten hot stew splashing on you. Weren't you going to do your business first? Whatever that is.` ) log( "'HEY!' you yell, covering your face with one arm and stretching out the other, hoping to bat the bowl out of the air before it gets too close. You need to eat, but you need to not have second degree burns even more." ) log( "To your amazement, the bowl plops into your waiting hand without so much as a drop of the contents being spilled. You realize that there's a spoon in there too." ) log("How did he do that?") log( `'Nice moves' says ${oldMan} sarcastically. He's already going to town on his bowl of stew, eating faster than you have ever seen anyone eat anything...you think.` ) log( "'Maybe that's the normal speed that people around here eat' you think, as you blow on a biteful of the stew and then shovel it into your mouth." ) log( "A slightly sweet, earthy taste fills your mouth and it is so, so good. This is literally the best thing you can remember ever having tasted." ) log("'What's in this'? you ask after you're finished your bite.") log( `'Veggies, goatmeal n' some other stuff' sputters ${oldMan}. It looks like he's eaten half his bowl already.` ) log("Goatmeal? Surely he must have meant oatmeal right?") log( "You decide you don't care as you wolf down the bowl of stew, and then a second one afterwards." ) space() return this.downToBusinessFinally(name, oldMan) }, downToBusinessFinally(name, oldMan) { if (this.didRun) { log( "As you eat, the soreness from your muscles numbs and you begin to feel much better." ) } log(`After the stew is gone, you and ${oldMan} sit in silence for a time.`) log("After a bit, he breaks the silence with a loud belch.") log("'BRRRAAAAAAAPPPP'") log("'Well, I suppose we should get down to it then' he says.") log( "'I was asked to give you a certain item, yes a VERY certain item. It's...'" ) log("'Certainly...an item.'") log( `'You've forgotten what it is, haven't you?' you ask. ${oldMan}'s dithering, so annoying just a few minutes ago, is much more tolerable with a full belly.` ) log( `'No, No, I didn't. And I've got it right around here somewhere' ${oldMan} says as he begins to root around in a gunny sack placed just behind the log, in such a way that you could not see it previously.` ) log("'That must be where he kept the bowl and ladle' you think.") getInitialItems() log( `He roots around in the bag a bit, tossing out a few items on the ground, including a ${ Object.keys(items)[2] }, a ${Object.keys(items)[1]} and what appears to be a ${ Object.keys(items)[0] }.` ) log( "At length the old man finished his search and said 'Ah yes!, I knew I had it here'." ) log( `${oldMan} moves in front of you, still sitting on the log, clears his throat and says'Here we are ${name}, one very special bag'. In his right hand he is holding a decidedly un-special looking canvas drawstring bag, about eight inches wide by ten inches long, cinched with rawhide strings and with a leather loop to attach it to a belt.` ) log( "'I hope you'll pardon me for saying so' you say 'But there doesn't seem to be much of anything special about that bag.'" ) log( "'It's very special'! the old man says, seemingly hurt by your tone. 'Not that you deserve it, but I'll give you a demonstration'." ) log( `In what seems to be becoming a pattern, you have no idea what ${oldMan} is talking about. Before you can even ask him what he means by it, he has stuffed the ${ Object.keys(items)[1] } into the bag and is reaching toward the ${ Object.keys(items)[2] }. That's not a big deal, but when he stuffs the nearly 5 foot long ${ Object.keys(items)[0] } into the small bag, you are a bit surprised.` ) log( "Knocked out of your creeping food coma by the surprise, you stammer 'How did you do that'?" ) log( `${oldMan} shrugs and says 'I told you that the bag was special. It's a Bag of Holding. Bigger on the inside than on the outside. Not too many left these days.'` ) log("He moves to stand in front of you.") log( `'I was asked to give it to you, ${name}. But before I do, I want to ask you a question: how is it you came to be here? You never did tell me'.` ) log( "'Of course I never told you, you old loon' you think 'this is the first time we've met'!" ) log( "This is all a bit much. You've just seen something that shouldn't be possible, and you've no memory about how you came to be...wherever you are." ) act = { lie: () => this.lie(name, oldMan), tellTheTruth: () => this.tellTheTruth(name, oldMan), } actPrmpt() return game.switchLog(game.cmds) }, lie(name, oldMan) { // const oldMan = bag.oldMansName // const name = bag.name this.didLie = true log( `You think about it for a moment. You don't know this guy, not really. You don't know if he is going to believe you if you tell him that you have no recollection of how you came to be here. You decide to lie.` ) const lie = randomLie() log(`Better think of something quickly.'${lie}' you blurt out.`) log(`${oldMan} gets very quiet at this.`) log("An eerie silence grips the air for what seems like a long time.") log(`Finally, the old man says '${name}, do you think me a fool'?`) log("'I KNOW WHEN I'M BEING LIED TO!!'") log( `Once again displaying that uncanny speed of his, ${oldMan} dashes up and clocks you square on the side of the head before you even have a chance to put your fists up.` ) log("'I DON'T LIKE LIARS!!!'") log( "Pain explodes inside your skull and you reel to the side before collapsing down on the ground" ) log( "The last thing you remember before blacking out is the distinct feeling that the worst is yet to come." ) return this.end() }, tellTheTruth(name, oldMan) { // const oldMan = bag.oldMansName // const name = bag.name log("You remember hearing somewhere that honesty is the best policy.") log( "'Well,' you start 'To be honest I don't really know how I came to be here. Before I came to your camp I kind of just found myself standing in the field over there. I'm not sure of anything before that'" ) log(`${oldMan} gets very quiet at this.`) log(`'Thank you for telling me the truth ${name}. I appreciate honesty.'`) log( "He stretches out his arm to you 'Here, this belongs to you, and I have a feeling it will come in handy'." ) log(`You gladly accept the bag and loop it on your belt.`) log( "He continues 'The fire won't burn down for a while yet, and I think I've got another bedroll around here somewhere'." ) log("He does, and you sleep soundly through the night.") return this.end() }, end() { act = {} bag.level = "aDestinyMostFateful" bag.items = JSON.stringify(items) bag.lv1didLie = JSON.stringify(this.didLie) bag.lv1didRun = JSON.stringify(this.didRun) return aDestinyMostFateful.start() }, } const aDestinyMostFateful = { bigRoad: true, start() { items = parse(bag.items) log("######################") log("Part Two: A Destiny Most Fateful") log("######################") space() log("Morning comes, as it usually does.") if (parse(bag.lv1didLie)) { log( "Light stabs your eyes. You can feel a lump the size of a robin's egg grown on the side of your head." ) log("That old fella really packs a wallop.") log( "You lay for a while with your eyes closed. Once you've decided for certain the sun is not going to change its mind about rising, you decide you have to greet the day." ) log( "Slowly, haltingly, you open your eyes. You bring yourself up off your back onto your elbows." ) if (parse(bag.lv1didRun)) { log( "In addition to the pain in your head, a sore stiffness has set into your limbs. Running was not a great idea." ) } log( "You notice you're in a bedroll. The fire has gone out and the old man is nowhere to be seen." ) log( "'So he clocks me and then tucks me in'? you think, your right hand going to the pulsing protuberance on your head. The moment you graze it a sharp pain shoots through your head and neck." ) log("'This is NOT going to be my morning' you say out loud to no one.") log( "It's right about then you notice you are holding the Bag of Holding in your left hand." ) } else { log( "You awake from a blissful slumber to the sound of birds chirping and the sun shining brilliantly through the trees." ) log("'That may have been the best night's sleep I ever had' you think.") log( "The old man is nowhere to be seen.'Must have taken off early' you think." ) if (parse(bag.lv1didRun)) { log( "You're a little sore from your ill-advised run last night, but other than that you feel great!" ) } log("The bag is still hooked to your belt loop right where you left it.") } log("You get up, stretch, do your necessaries. Morning stuff") items.bedroll = true log( "For better or worse, it's time to go. You roll up the bedroll and stuff it into the Bag of Holding." ) log( "Somehow, the bag streches wide enough to allow you to fit the bedroll in. This bag is rad." ) space() log( "There is a small road that leads out of camp. Without anywhere else to go, you decide to take it." ) if (parse(bag.lv1didLie)) { log( "It's a nice enough walk, even with your aching head. Before too long you come to a fork in the path." ) } else { log( "It's a nice enough walk. Before too long you come to a fork in the path." ) } log( "The road to your right is wide and well maintained. You can tell it sees regular traffic. It is open and bright and you will be able to see anyone coming up to you for quite a ways." ) log( "The road on left is small and dark, overgrown with a canopy of scraggly trees. Barely enough room for two people to stand side by side, the path curves sharply about 60 feet from the fork. If there are many curves like that, you won't be able to tell what's coming up to greet you." ) act = { takeBigRoad: () => this.bigRoad(), takeSmallRoad: () => this.littleRoad(), } actPrmpt() return game.switchLog(game.cmds) }, bigRoad() { act = {} log( "You're not here to have an adventure. You may not know what you're here for, but it definitely is not that." ) log("You decide to take the main road.") const encounter = random(2) if (encounter === 0) { log("proceed peacefully") } else log("something else") return "you took the big road" }, littleRoad() { act = {} log("You decide to take the road less traveled by.") log("Slowly stalking down the shadowy path, you take the sharp turn.") log("Then another.") log("Then another.") log("You proceed for a while without incident.") log( "The further you walk down the path, the thicker the canopy above you becomes. You begin to feel uneasy." ) log( "After maybe 45 minutes, the light reaching you has dimmed to the point where it resembles early dusk." ) log( "All at once you realize that the normal forest sounds of birds and insects have fallen silent. All you hear as you plod along is the soft crunch of soil and nettles under your feet." ) log( "'I haven't even been going this very long' you say aloud to no one, in what may be a habit of yours 'Maybe I can just go back?'" ) if (parse(bag.lv1didLie)) log("The lump on your head throbs in silent reply.") const encounter = random(3) if (encounter === 0) { log("fight bandits") } else { log("Suddenly you hear a deep, slow voice:") log( "'You can't leave if you've already come in man, it doesn't work that way.'" ) log("You spin around on your heels toward the source of the noise.") log( "Through the gloom you can just make out a 5 foot tall frog, sitting on a rock wearing cargo shorts." ) log("'Maaaaannnnn, its never worked that way.' he says, with a chuckle.") log("'Great' you think, 'another weirdo who speaks in vagueries.'") log( "The giant frog reaches inside the right pocket of his shorts, pulls out a long wooden pipe and a leather pouch, knocks the pipe against the palm of his left hand and begins packing it." ) log( `As he carefully pulls out little bits of tobacco and pinches them into the pipe, the frog says 'So, I guess you must be ${parse( bag.name )} then? ${parse(bag.oldMansName)} said you might be coming along.` ) if (parse(bag.lv1didLie)) { log( "'You know that old nut?' you yelp, and pointing to your head continue 'He gave me this lump!'" ) log( "Not looking up from his work, the frog mutters 'Yeah. He really doesn't like liars, man.'" ) log("He continues:") } else log( `'Oh, you know ${parse( bag.oldMansName )}'' you ask, 'He put me up for the night. Kinda wish he'd stuck around a bit longer though'` ) log( `'Yeah, that sounds like ${parse( bag.oldMansName )}, bless his wacky old heart.'` ) log( "The pipe finally packed to his satisfaction, the frog strikes a match against the stone he's using as a seat, lights the pipe and takes a few slow draws. A thick smoke leaks from his nostrils as he closes his eyes in pleasure." ) log( "After a moment, he opens his eyes and says 'Like I was saying, the road only goes one way, even if you decide to go the other way. It's a lot like life that way, man." ) log( "'You can make it through okay though, you just need a friend to show you the way. I guess that's where I come in.'" ) log("'Oh, so now we're friends?' you say, 'We've only just met.'") log( "He thinks about this for a second and then shrugs. 'We might as well be friends. Being enemies is a lot of work, man.'" ) log("You can't argue with that.") log( "As you've been speaking, the giant frog has continued puffing away at his pipe. The thick smoke has wafted over to you and you smell a smelly smell halfway between tobacco and sweet, dry rot." ) log( "He continues 'So if you want to reach the end of the road, you gotta ask yourself whyyyyyyyy you wanna go down it in the first place.'" ) log("At that, a long pause falls between the two of you.") // fill this in some more log( "As he walks toward the bag, you say 'So I guess if we're gonna be traveling together, I should know your name.'" ) log("He replies 'What's in a name? You can just call me Frog, man.") log("Gotcha. It's a pleasure to be traveling with you Frogman.") log("At this, he stops and his brow furrows.") log("'No', he says flatly, 'Not Frogman. Just Frog, man.'") log( "You may have found something that actually bothers him. 'That's what I said, Frogman.'" ) log( "Frogman begins to protest again but, realizing that a fight would be a lot of effort, simply shrugs and says 'Surrrrreeee. Frogman it is. Call me when you need me, man. Or, you know, just to say hi.'" ) log( "With that, Frogman jumps into the Bag of Holding, a thin wisp of sweet smoke trailing after." ) //add frogman to items } return "you took the little road" }, }
var body = document.getElementById('body'); var enemies = document.getElementsByClassName('enemy') var svg = document.getElementById('svg'); let nodeListId var starttime var timestamp let stopAnimation37, stopAnimation38, stopAnimation39, stopAnimation40, stopAnimation65, stopAnimation87, stopAnimation68, stopAnimation83 let clickX, clickY let timer let stop let bulletColor = '#EB01A5' body.addEventListener("mousedown", (event)=> { event.preventDefault(); stop = false; clickX = event.clientX clickY = event.clientY createThing(event); timer = this.setInterval(() => { if (stop) return; createThing(event); }, 80); mouseMove = (event) => { clickX = event.clientX; clickY = event.clientY; } body.addEventListener("mousemove", mouseMove) body.addEventListener("mouseup", ()=> { stop = true; body.removeEventListener("mousemove", mouseMove) clearInterval(timer); }) }) body.addEventListener('keydown', (event)=> { handleKeyCodeDown(event.keyCode) }) body.addEventListener('keyup', (event)=> { handleKeyCodeUp(event.keyCode) }) generatePlayer(); generateEnemies(); // setInterval(() => { // }, 3000)
var _viewer = this; $("#TS_XMGL_KCAP_DAPCC .rhGrid").find("th[icode='del']").html("操作"); var xmId = _viewer.getParHandler()._pkCode; //得到当前机构代码 得到考场 var odeptCode = System.getVar("@ODEPT_CODE@"); //确认当前机构是总行/省级机构/市级机构 var level = System.getVar("@ODEPT_LEVEL@"); _viewer.getBtn("add").unbind("click").bind("click", function(event) { var param = {}; param["SOURCE"] = "KC_ID~KC_NAME~KC_ADDRESS~CTLG_PCODE"; param["TYPE"] = "multi"; param["HIDE"] = "KC_ID,CTLG_PCODE"; // param["EXTWHERE"] = "and KC_ODEPTCODE = '"+odeptCode+"'"; param["EXTWHERE"] = " and GROUP_ID in (select group_id from TS_KCZGL_GROUP b where serv_id = 'ts_kczgl_group' and b.kcz_id in (select kcz_id from TS_KCZGL a where serv_id = 'ts_xmgl_cccs_kczgl' and XM_ID = '"+xmId+"'))"; var configStr = "TS_XMGL_KCAP_DAPCC_UTIL_V,"+JsonToStr(param); var options = { "config" :configStr, "parHandler":_viewer, "formHandler":_viewer.form, "replaceCallBack":function(idArray) { var ids = idArray.KC_ID.split(","); var kcNames = idArray.KC_NAME.split(","); var ctlgpCodes = idArray.CTLG_PCODE.split(","); for(var i=0;i<ids.length;i++){ var data = {} data["XM_ID"] = xmId; data["KC_ID"] = ids[i]; data["KC_NAME"] = kcNames[i]; data["CTLG_PCODE"] = ctlgpCodes[i]; FireFly.doAct("TS_XMGL_KCAP_DAPCC", "save", data,false,false,function(result){ if(result._MSG_.indexOf("OK") == -1){ _viewer.listBarTipError("添加失败!"); }else{ var ccId = result.CC_ID; var kcId = result.KC_ID; FireFly.doAct("TS_KCGL_GLJG", "finds", {"_WHERE_":"and kc_id = '"+kcId+"'"},false,false,function(res){ for(var i=0;i<res._DATA_.length;i++){ var bean = {}; bean["CC_ID"] = ccId; bean["JG_CODE"] = res._DATA_[i].JG_CODE; bean["JG_FAR"] = res._DATA_[i].JG_FAR; bean["JG_NAME"] = res._DATA_[i].JG_NAME; bean["JG_TYPE"] = res._DATA_[i].JG_TYPE; bean["KC_ID"] = res._DATA_[i].KC_ID; FireFly.doAct("TS_XMGL_KCAP_GLJG","save",bean); } }); } }); } _viewer.refresh(); } }; //2.用系统的查询选择组件 rh.vi.rhSelectListView() var queryView = new rh.vi.rhSelectListView(options); queryView.show(event); }); /* * 删除前方法执行 */ _viewer.beforeDelete = function(pkArray) { showVerify(pkArray,_viewer); }; _viewer.getBtn("addOther").unbind("click").bind("click",function(event){ var param = {}; param["SOURCE"] = "KC_ID~KC_NAME~KC_ADDRESS~KC_ODEPTCODE~CTLG_PCODE"; param["TYPE"] = "multi"; param["HIDE"] = "KC_ID,KC_ODEPTCODE,CTLG_PCODE"; // param["EXTWHERE"] = "and KC_ODEPTCODE = '"+odeptCode+"'"; var configStr = "TS_KCGL,"+JsonToStr(param); var options = { "config" :configStr, "parHandler":_viewer, "formHandler":_viewer.form, "replaceCallBack":function(idArray) { var ids = idArray.KC_ID.split(","); var kcNames = idArray.KC_NAME.split(","); var ctlgpCodes = idArray.CTLG_PCODE.split(","); for(var i=0;i<ids.length;i++){ var data = {} data["XM_ID"] = xmId; data["KC_ID"] = ids[i]; data["KC_NAME"] = kcNames[i]; data["CTLG_PCODE"] = ctlgpCodes[i]; FireFly.doAct("TS_XMGL_KCAP_DAPCC", "save", data,false,false,function(result){ if(result._MSG_.indexOf("OK") == -1){ _viewer.listBarTipError("添加失败!"); } }); } _viewer.refresh(); } }; //2.用系统的查询选择组件 rh.vi.rhSelectListView() var queryView = new rh.vi.rhSelectListView(options); queryView.show(event); }); $("#TS_XMGL_KCAP_DAPCC .rhGrid").find("th[icode='scope']").html("操作"); //删除单行数据 _viewer.grid.getBtn("scope").unbind("click").bind("click",function() { var pk = jQuery(this).attr("rowpk");//获取主键信息 openMyCard(pk); }); //列表操作按钮 弹dialog function openMyCard(dataId,readOnly,showTab){ var height = jQuery(window).height()-200; var width = jQuery(window).width()-200; var temp = {"act":UIConst.ACT_CARD_MODIFY,"sId":_viewer.servId,"parHandler":_viewer,"widHeiArray":[width,height],"xyArray":[100,100]}; temp[UIConst.PK_KEY] = dataId; if(readOnly != ""){ temp["readOnly"] = readOnly; } if(showTab != ""){ temp["showTab"] = showTab; } var cardView = new rh.vi.cardView(temp); cardView.show(); }
import * as tf from '@tensorflow/tfjs' /* Implements basic conjugate gradient method. * Av is expected to be a function Av(v) should return the product of A and v * (this way it is not required to store A at any time). */ export default (_Av, b, tolerance=1e-05, max_iterations=5) => { let shape = b.shape b = b.reshape([-1]) let Av = (v) => _Av(v).reshape([-1]) let x = tf.zerosLike(b); // residual let r = b.sub(Av(x)) // search direction let p = tf.clone(r) // used multiple times let r_dot_r, r_dot_r_new r_dot_r = r.dot(r) let Ap, alpha, beta for (let i = 0; i < max_iterations; i++) { Ap = Av(p) alpha = r_dot_r.div(p.dot(Ap)) // update x and residual x = x.add(p.mul(alpha)) r = r.sub(Ap.mul(alpha)) r_dot_r_new = r.dot(r) // if tolerance is reached, terminate if (r_dot_r_new < tolerance) { break } // prepare for next iteration beta = r_dot_r_new.div(r_dot_r) // update search direction p = r.add(p.mul(beta)) // shortcut for next iteration r_dot_r = r_dot_r_new } return x.reshape(shape) }
import React, { Component } from "react"; import ReactLoading from 'react-loading'; import {withRouter} from 'react-router-dom'; let userid = localStorage.getItem("userid"); class Viewprofile extends Component { constructor(props) { super(props); ////console.log(this.props) this.state = { paramValue : this.props.match.params.id, loaded : false, user : {} } } componentDidMount() { ////console.log(this.state) if(this.state.loaded === true){ return; } this._asyncRequest = fetch("http://a1api.herokuapp.com/api/v1/user/"+ this.state.paramValue) .then((response) => { let promise = response.json(); promise.then( result => { if(result.status === "success"){ this.setState({loaded : true}); this.setState({user : result.user}); ////console.log(result); } else{ } } ) }); } render() { if(this.state.loaded == false) { return(<ReactLoading type={'spinningBubbles'} color={'blue'} height={'20%'} width={'20%'} />) } var html_text = '' ////console.log(this.state.user) for (const [key, value] of Object.entries(this.state.user)) { html_text = <div> {html_text} <div> <tr> <td>{key}</td> <td>{value}</td> </tr> </div> </div> } return ( <div className="container"> <table className="table"> {html_text} </table> </div> ); } } export default withRouter(Viewprofile);
import * as productsController from '../controllers/productsController' import { authJwt } from '../middlewares'; import { Router } from 'express'; const router = Router(); router.post('/', [authJwt.verifyToken, authJwt.isModerator], productsController.createProduct ); router.get('/', productsController.getProducts ); router.get('/:productId', productsController.getProductById ); router.put('/:productId', [authJwt.verifyToken, authJwt.isAdmin], productsController.updateProductById ); router.delete('/:productId', [authJwt.verifyToken, authJwt.isAdmin], productsController.deleteProductById ); export default router;
import React from 'react' import useStyle from './style' import { BrowserRouter as Router, Route, Switch } from 'react-router-dom' // components import Header from './components/Header/Header' import UserLogin from './components/Login/Login' import Feed from './components/Feed/Feed' import Sidebar from './components/Sidebar/Sidebar' import Paper from '@material-ui/core/Paper' import Grid from '@material-ui/core/Grid' import Container from '@material-ui/core/Container' export default function App() { const classes = useStyle() return ( <div className={classes.root}> <Router> <Header></Header> <div className='app-div'> <Switch> <Route path='/home' component={Home} /> <Route path='/login' component={UserLogin} /> </Switch> </div> </Router> </div> ) } const Home = () => { const classes = useStyle() return ( <Container className={classes.grid_root}> <Grid container spacing={3}> <Grid item xs={4}> <Paper className={classes.paper}> <Sidebar></Sidebar> </Paper> </Grid> <Grid item xs={8}> <Paper className={classes.paper}> <Feed></Feed> </Paper> </Grid> </Grid> </Container> ) }
export default { credits: 'a blog by <a target="_blank" href="https://eudes.es/" class="ani"><span>eudes ochoa</span></a>' }
import { Component, Event, Method, Prop, State, h } from '@stencil/core'; export class TraimAccordionPane { constructor() { this._isOpen = false; this.open = false; this.empty = false; } componentWillLoad() { this._isOpen = this.open; } async show() { this._isOpen = true; } async close() { this._isOpen = false; } toggle() { this._isOpen ? this.close() : this.show(); this.onToggle.emit(this._isOpen); } async isOpen() { return this._isOpen; } render() { const isOpenClass = this._isOpen ? 'is-active' : ''; const isEmptyClass = this.empty ? 'is-empty' : ''; return [ h("button", { role: "heading", "aria-expanded": this._isOpen.toString(), tabindex: !this.empty ? 0 : -1, class: `control ${isOpenClass} ${isEmptyClass}`, onClick: () => !this.empty && this.toggle(), innerHTML: this.header }), h("section", { "aria-hidden": !this._isOpen, class: `pane` }, h("slot", null)), ]; } static get is() { return "traim-accordion-pane"; } static get originalStyleUrls() { return { "$": ["traim-accordion-pane.scss"] }; } static get styleUrls() { return { "$": ["traim-accordion-pane.css"] }; } static get properties() { return { "open": { "type": "boolean", "mutable": false, "complexType": { "original": "boolean", "resolved": "boolean", "references": {} }, "required": false, "optional": false, "docs": { "tags": [], "text": "" }, "attribute": "open", "reflect": false, "defaultValue": "false" }, "empty": { "type": "boolean", "mutable": false, "complexType": { "original": "boolean", "resolved": "boolean", "references": {} }, "required": false, "optional": false, "docs": { "tags": [], "text": "" }, "attribute": "empty", "reflect": false, "defaultValue": "false" }, "header": { "type": "string", "mutable": false, "complexType": { "original": "string", "resolved": "string", "references": {} }, "required": false, "optional": false, "docs": { "tags": [], "text": "" }, "attribute": "header", "reflect": false } }; } static get states() { return { "_isOpen": {} }; } static get events() { return [{ "method": "onToggle", "name": "togglepane", "bubbles": true, "cancelable": true, "composed": true, "docs": { "tags": [], "text": "" }, "complexType": { "original": "any", "resolved": "any", "references": {} } }]; } static get methods() { return { "show": { "complexType": { "signature": "() => Promise<void>", "parameters": [], "references": { "Promise": { "location": "global" } }, "return": "Promise<void>" }, "docs": { "text": "", "tags": [] } }, "close": { "complexType": { "signature": "() => Promise<void>", "parameters": [], "references": { "Promise": { "location": "global" } }, "return": "Promise<void>" }, "docs": { "text": "", "tags": [] } }, "isOpen": { "complexType": { "signature": "() => Promise<boolean>", "parameters": [], "references": { "Promise": { "location": "global" } }, "return": "Promise<boolean>" }, "docs": { "text": "", "tags": [] } } }; } }
angular.module('app') .controller('BlockCtrl', function ($scope, BlockSvc) { $scope.addPost = function () { if ($scope.postBody) { BlockSvc.create({ body: $scope.blockBody }) .then(function () { $scope.blockBody = null }) } } $scope.$on('ws:new_block', function (_, block) { $scope.$apply(function () { $scope.unshift(post) }) }) BlockSvc.fetch() .then(function (posts) { $scope.posts = posts }) })
const createCalculator = require('../Add-Substract'); const assert = require('chai').assert; describe('returned object contains props', () => { it('add', () => { let obj = createCalculator(); let isContained = obj.add ? true : false; assert.equal(true, isContained); }); it('substract', () => { let obj = createCalculator(); let isContained = obj.subtract ? true : false; assert.equal(true, isContained); }); it('get', () => { let obj = createCalculator(); let isContained = obj.get ? true : false; assert.equal(true, isContained); }); }); describe('functions', () => { it('get', ()=>{ let obj=createCalculator(); let expected=0; assert.strictEqual(expected, obj.get()); }) it('add', () => { let obj=createCalculator(); let expected=15; obj.add(10); obj.add(5); assert.equal(obj.get(), expected); }) it('add parses', () => { let obj=createCalculator(); let expected=15; obj.add(10); obj.add("5"); assert.equal(obj.get(), expected); }) it('substract', () => { let obj=createCalculator(); let expected=99; obj.subtract(-100); obj.subtract(1); assert.equal(obj.get(), expected); }) it('substract parses', () => { let obj=createCalculator(); let expected=99; obj.subtract(-100); obj.subtract("1"); assert.equal(obj.get(), expected); }) })
'use strict' const RTM = require("satori-sdk-js") const octonode = require('octonode') const path = require('path') const examples = require('node-examples') const Rx = require('node-keyboard-rx')() function subscribeToGithubStars() { const endpoint = "wss://open-data.api.satori.com" const appKey = process.env.SATORI_ACCESS_TOKEN const rtm = new RTM(endpoint, appKey) const subscription = rtm.subscribe('gh-watch-events', RTM.SubscriptionMode.SIMPLE, { filter: 'select * from `github-events` where type=\'WatchEvent\'' }) rtm.start() return Rx.Observable.fromEvent(subscription, 'rtm/subscription/data').finally(() => rtm.stop()) } const github = module.exports = { _starred() { const starred = subscribeToGithubStars() const foundStars = [] return starred .flatMap(pdu => pdu.body.messages) .map(msg => { return { user: msg.actor.login, repo: msg.repo.name } }) .filter(({ user, repo }) => { if (foundStars.indexOf(user+repo) > -1 ) return false foundStars.push(user+repo) return true }) }, starredRepos() { const client = octonode.client(process.env.GITHUB_ACCESS_TOKEN) return github._starred() .concatMap(({ user, repo }) => { const context = client.repo(repo) return Rx.Observable.forkJoin( Rx.Observable.of({ user, repo }), Rx.Observable.bindNodeCallback(context.languages.bind(context))() ) }) .map(([{ user, repo }, [ languages ]]) => { const sum = Object.keys(languages).reduce((acc, key) => { return acc + languages[key] }, 0) languages = Object.keys(languages).reduce((acc, key) => { acc[key] = languages[key] / sum return acc }, {}) return { user, repo, languages } }) }, sourceSearch(query) { const client = octonode.client(process.env.GITHUB_ACCESS_TOKEN) return github._starred() .concatMap(({ user, repo }) => { const context = client.search() return Rx.Observable.forkJoin( Rx.Observable.of({ user, repo }), Rx.Observable.bindNodeCallback(context.code.bind(context))({ q: `${query}+repo:${repo}`, sort: 'created', order: 'asc' }) ) }) .map(([{ user, repo }, [ { items } ]]) => { return { user, repo, items } }) } } examples({ path: path.join(__dirname, 'examples'), prefix: 'github_example_', cache: false })
import '../css/reset.css' import '../css/page.css' import '../css/grid.css' import vars from '../config'
/** * REQUIRE ALL GULP FILES * Require all js files gulp directory */ var requireDir = require('require-dir'); // Require all tasks in gulp/tasks, including subfolders requireDir('./src/gulp/tasks', { recurse: true });
define(["exports", "react"], function (exports, _react) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.startRender = startRender; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } var _React = _interopRequireDefault(_react); var ReactCSSTransitionGroup = _React["default"].addons.CSSTransitionGroup; //import $ from 'jquery'; _React["default"].initializeTouchEvents(true); var Search = _React["default"].createClass({ displayName: "Search", generatePages: function generatePages() { var generatedResultPage = _React["default"].createElement( "div", { className: "resultPage", key: "resultPage" }, _React["default"].createElement(TopBarInResultPage, { clickHandler: this.handleClick }), _React["default"].createElement(Ads, null), _React["default"].createElement(ResultContainer, null) ); var generatedFilterPage = _React["default"].createElement( "div", { className: "filerPageContainer", key: "filerPageContainer" }, _React["default"].createElement( "div", { className: "filerPage", key: "filerPage" }, _React["default"].createElement(ControlBar, { clickHandler: this.handleClick }), _React["default"].createElement(FilterPicker, null) ) ); var generatedfilterMask = _React["default"].createElement("div", { className: "filerMask", key: "filerMask" }); return { //Result Pages "generatedResultPage": generatedResultPage, //Filter Pages "generatedFilterPage": generatedFilterPage, "generatedfilterMask": generatedfilterMask }; }, getInitialState: function getInitialState() { var generatedPages = this.generatePages(); return { generatedDOMPages: generatedPages, ifActiveResultPage: false, resultPage: [], ifActiveFilterPage: false, filterPage: [], filterMask: [] }; }, handleClick: function handleClick(sender) { //Start Page Clicks if (sender == "searchButton") { this.setResultPageDisplay(); } //Result Page Clicks else if (sender == "resultBackButton") { this.setResultPageDisplay(); } else if (sender == "resultFilterButton") { this.setFilterPageDisplay(); } //Filter Page Clicks else if (sender == "resultFilterCancel") { this.setFilterPageDisplay(); } else if (sender == "resultFilterConfirm") { this.setFilterPageDisplay(); } }, setResultPageDisplay: function setResultPageDisplay() { this.setState({ ifActiveResultPage: !this.state.ifActiveResultPage }, function () { this.setState({ resultPage: this.state.ifActiveResultPage ? this.state.generatedDOMPages.generatedResultPage : [] }); }); }, setFilterPageDisplay: function setFilterPageDisplay() { this.setState({ ifActiveFilterPage: !this.state.ifActiveFilterPage }, function () { this.setState({ filterPage: this.state.ifActiveFilterPage ? this.state.generatedDOMPages.generatedFilterPage : [], filterMask: this.state.ifActiveFilterPage ? this.state.generatedDOMPages.generatedfilterMask : [] }); }); }, render: function render() { return _React["default"].createElement( "div", { id: "container" }, _React["default"].createElement( "div", { className: "startPage", ref: "startPage" }, _React["default"].createElement(TopBarInStartPage, { clickHandler: this.handleClick }), _React["default"].createElement(HotSearches, null), _React["default"].createElement(SearchHistory, null) ), _React["default"].createElement( ReactCSSTransitionGroup, { transitionName: "resultPageTransition" }, this.state.resultPage ), _React["default"].createElement( ReactCSSTransitionGroup, { transitionName: "filterMaskTransition" }, this.state.filterMask ), _React["default"].createElement( ReactCSSTransitionGroup, { transitionName: "filterPageTransition" }, this.state.filterPage ) ); } }); //Render function startRender() { _React["default"].render(_React["default"].createElement(Search, null), document.getElementById('trSearchContent')); } /*--- Starting Page --*/ //Top Bar var TopBarInStartPage = _React["default"].createClass({ displayName: "TopBarInStartPage", handleClick: function handleClick(sender) { this.props.clickHandler(sender); }, render: function render() { var sender = null; return _React["default"].createElement( "div", { className: "searchTopBar" }, _React["default"].createElement( "div", { className: "textField" }, _React["default"].createElement("input", { type: "text", ref: "searchText" }) ), _React["default"].createElement( "div", { className: "searchButton", onClick: this.handleClick.bind(this, sender = "searchButton") }, _React["default"].createElement( "span", null, "搜索" ) ) ); } }); //Hot Searches var HotSearches = _React["default"].createClass({ displayName: "HotSearches", getInitialState: function getInitialState() { return { hotSearches: sampleData.hotSearches }; }, render: function render() { var hotSearchItemArray = []; for (var i = 0; i < this.state.hotSearches.length; i++) { var searchText = this.state.hotSearches[i]; //Key property keeps consistent. hotSearchItemArray.push(_React["default"].createElement(SearchSingleItem, { searchText: searchText, key: searchText })); } return _React["default"].createElement( "div", { className: "hotSearches" }, _React["default"].createElement( "div", { className: "title" }, _React["default"].createElement( "span", null, "热门搜索" ) ), _React["default"].createElement( "div", { className: "content" }, hotSearchItemArray ) ); } }); //Searches History var SearchHistory = _React["default"].createClass({ displayName: "SearchHistory", getInitialState: function getInitialState() { return { searchHistory: sampleData.searchHistory }; }, render: function render() { var SearchHistoryItemArray = []; for (var i = 0; i < this.state.searchHistory.length; i++) { var searchText = this.state.searchHistory[i]; SearchHistoryItemArray.push(_React["default"].createElement(SearchSingleItem, { searchText: searchText, key: searchText })); } return _React["default"].createElement( "div", { className: "SearchHistory" }, _React["default"].createElement( "div", { className: "title" }, _React["default"].createElement( "span", null, "历史搜索" ) ), _React["default"].createElement( "div", { className: "content" }, SearchHistoryItemArray ) ); } }); //Single Item var SearchSingleItem = _React["default"].createClass({ displayName: "SearchSingleItem", render: function render() { return _React["default"].createElement( "span", null, this.props.searchText ); } }); /*--- Result Page --*/ var TopBarInResultPage = _React["default"].createClass({ displayName: "TopBarInResultPage", render: function render() { var sender = null; return _React["default"].createElement( "div", { className: "resultTopBar" }, _React["default"].createElement("div", { className: "backButton", onClick: this.props.clickHandler.bind(this, sender = "resultBackButton") }), _React["default"].createElement( "div", { className: "textField" }, _React["default"].createElement("input", { type: "text", ref: "searchText", placeholder: "搜:电子输液泵" }) ), _React["default"].createElement("div", { className: "functions" }), _React["default"].createElement("div", { className: "resultFilter", onClick: this.props.clickHandler.bind(this, sender = "resultFilterButton") }) ); } }); var Ads = _React["default"].createClass({ displayName: "Ads", getInitialState: function getInitialState() { return { adsImageUrl: sampleData.ads }; }, render: function render() { return _React["default"].createElement( "div", { className: "ads" }, _React["default"].createElement("img", { src: this.state.adsImageUrl }) ); } }); var ResultContainer = _React["default"].createClass({ displayName: "ResultContainer", getInitialState: function getInitialState() { return { result: sampleData.searchResult, activeOption: 0, priceHighToLow: true, salesHighToLow: true }; }, handleClicks: function handleClicks(clickedOption) { if (clickedOption == this.state.activeOption) { if (clickedOption == 1) { this.setState({ priceHighToLow: !this.state.priceHighToLow }); } else if (clickedOption == 2) { this.setState({ salesHighToLow: !this.state.salesHighToLow }); } } else { this.setState({ activeOption: clickedOption }); } }, render: function render() { var sortMethods = { priceHighToLow: this.state.priceHighToLow, salesHighToLow: this.state.salesHighToLow }; return _React["default"].createElement( "div", { className: "resultContainer" }, _React["default"].createElement(SortOptions, { activeOption: this.state.activeOption, sortMethod: sortMethods, handleClicks: this.handleClicks }), _React["default"].createElement(ResultContent, { searchResult: this.state.result }) ); } }); var SortOptions = _React["default"].createClass({ displayName: "SortOptions", handleClick: function handleClick(i) { this.props.handleClicks(i); }, render: function render() { var i = 0; return _React["default"].createElement( "div", { className: "sortOptions" }, _React["default"].createElement( "div", { className: "sortByGeneral " + (this.props.activeOption == 0 ? "active" : "inactive"), onClick: this.handleClick.bind(this, i = 0) }, _React["default"].createElement( "span", null, "综合" ) ), _React["default"].createElement( "div", { className: "sortByPrice " + (this.props.activeOption == 1 ? "active" : "inactive"), onClick: this.handleClick.bind(this, i = 1) }, _React["default"].createElement( "span", null, "价格", this.props.sortMethod.priceHighToLow ? "↑" : "↓" ) ), _React["default"].createElement( "div", { className: "sortBySales " + (this.props.activeOption == 2 ? "active" : "inactive"), onClick: this.handleClick.bind(this, i = 2) }, _React["default"].createElement( "span", null, "销量", this.props.sortMethod.salesHighToLow ? "↑" : "↓" ) ), _React["default"].createElement( "div", { className: "sortByRating " + (this.props.activeOption == 3 ? "active" : "inactive"), onClick: this.handleClick.bind(this, i = 3) }, _React["default"].createElement( "span", null, "评价" ) ) ); } }); var ResultContent = _React["default"].createClass({ displayName: "ResultContent", render: function render() { var searchResult = this.props.searchResult; var resultItemArray = []; for (var i = 0; i < searchResult.length; i++) { resultItemArray.push(_React["default"].createElement(ResultItem, { productInfo: searchResult[i], key: i })); } return _React["default"].createElement( "div", { className: "resultContentWarper" }, _React["default"].createElement( "div", { className: "resultContent" }, resultItemArray ) ); } }); var ResultItem = _React["default"].createClass({ displayName: "ResultItem", render: function render() { var productInfo = this.props.productInfo; return _React["default"].createElement( "div", { className: "resultItem" }, _React["default"].createElement( "div", { className: "productImage" }, _React["default"].createElement("img", { src: productInfo.productImage }) ), _React["default"].createElement( "div", { className: "productName" }, _React["default"].createElement( "span", null, productInfo.productName ) ), _React["default"].createElement( "div", { className: "productPrice" }, _React["default"].createElement( "span", null, productInfo.productPrice ) ), _React["default"].createElement( "div", { className: "productRateCount" }, _React["default"].createElement( "span", null, productInfo.rateCount ) ) ); } }); /*--- Filter Page --*/ var ControlBar = _React["default"].createClass({ displayName: "ControlBar", handleClick: function handleClick(sender) { if (sender == "cancel") { this.props.clickHandler("resultFilterCancel"); } else if (sender == "confirm") { this.props.clickHandler("resultFilterConfirm"); } }, render: function render() { var sender = null; return _React["default"].createElement( "div", { className: "controlBar" }, _React["default"].createElement( "div", { className: "cancelButton", onClick: this.handleClick.bind(this, sender = "cancel") }, _React["default"].createElement( "span", null, "取消" ) ), _React["default"].createElement( "div", { className: "title" }, _React["default"].createElement( "span", null, "筛选" ) ), _React["default"].createElement( "div", { className: "confirmButton", onClick: this.handleClick.bind(this, sender = "confirm") }, _React["default"].createElement( "span", null, "确定" ) ) ); } }); var FilterPicker = _React["default"].createClass({ displayName: "FilterPicker", getInitialState: function getInitialState() { return { filterOptions: sampleData.filter.filterOptions, filterOptionsContents: sampleData.filter.filterOptionsContents }; }, render: function render() { var optionItems = []; var optionsArray = this.state.filterOptions; for (var i = 0; i < optionsArray.length; i++) { optionItems.push(_React["default"].createElement(FilterItem, { filterTitle: optionsArray[i], key: i })); } return _React["default"].createElement( "div", { className: "filterPicker" }, _React["default"].createElement( "div", { className: "filterPickerWarper" }, optionItems ), _React["default"].createElement( "div", { className: "clearFilterButton" }, _React["default"].createElement( "span", null, "清除选项" ) ) ); } }); var FilterItem = _React["default"].createClass({ displayName: "FilterItem", render: function render() { return _React["default"].createElement( "div", { className: "filterItem" }, _React["default"].createElement( "div", { className: "title" }, _React["default"].createElement( "span", null, this.props.filterTitle ) ), _React["default"].createElement( "div", { className: "picked" }, _React["default"].createElement( "span", null, "全部" ) ), _React["default"].createElement("div", { className: "arrow" }) ); } }); var sampleData = { hotSearches: ["包", "泵", "管", "针", "麻醉", "疼痛", "引流", "介入", "检验", "护理"], searchHistory: ["医用喉罩", "负压引流装置", "一次性使用麻醉穿刺包", "一次性使用静脉采血针"], ads: "./assets/ad3@2x.png", searchResult: [{ productName: "驼人电子输注入泵 1.03.04.118T 电子泵一托+275ml", productImage: "./assets/sampleProduct2@2x.png", productPrice: "¥228.00", rateCount: "600人评价" }, { productName: "驼人电子输注入泵 1.03.04.118T 电子泵一托+275ml", productImage: "./assets/sampleProduct2@2x.png", productPrice: "¥228.00", rateCount: "600人评价" }, { productName: "驼人电子输注入泵 1.03.04.118T 电子泵一托+275ml", productImage: "./assets/sampleProduct2@2x.png", productPrice: "¥228.00", rateCount: "600人评价" }, { productName: "驼人电子输注入泵 1.03.04.118T 电子泵一托+275ml", productImage: "./assets/sampleProduct2@2x.png", productPrice: "¥228.00", rateCount: "600人评价" }], filter: { filterOptions: ["商品分类", "品牌", "科室"], filterOptionsContents: { "1": ["全部"] } } }; });
var swiper = new Swiper(".mySwiper", { pagination: { el: ".swiper-pagination", type: "fraction", }, navigation: { nextEl: ".swiper-button-next", prevEl: ".swiper-button-prev", }, }); document.getElementById("button").addEventListener('click', function(){ // console.log('ok') Swal.fire({ title: 'AMAZING', text: 'sweetalert comes with interesting presets', imageUrl: './img/logo.png', imageWidth: 400, imageHeight: 200, imageAlt: 'Custom image', }) }); document.documentElement.style.setProperty('--animate-duration', '2s'); // const swiper = new Swiper('.swiper', { // // Optional parameters // direction: 'vertical', // loop: true, // // If we need pagination // pagination: { // el: '.swiper-pagination', // }, // // Navigation arrows // navigation: { // nextEl: '.swiper-button-next', // prevEl: '.swiper-button-prev', // }, // // And if we need scrollbar // scrollbar: { // el: '.swiper-scrollbar', // }, // });
import React, { Component } from 'react' import PropTypes from 'prop-types' import compose from 'recompose/compose' import { reduxForm, reset } from 'redux-form' import { withStyles } from 'material-ui/styles' import AddEventStepper from './form/components/AddEventStepper' import EventInformations from './form/components/EventInformations' import EventServices from './form/components/EventServices' import EventTags from './form/components/EventTags' import Grid from 'material-ui/Grid' import Card, { CardContent } from 'material-ui/Card' import Typography from 'material-ui/Typography' const styles = theme => ({}) class AddEvent extends Component { constructor(props) { super(props) this.state = { activeStep: 0, isActivated: { github: false, gitlab: false, slack: false, }, } } handleNext = () => { this.setState({ activeStep: this.state.activeStep + 1, }) } handleBack = () => { this.setState({ activeStep: this.state.activeStep - 1, }) } handleReset = () => { this.setState({ activeStep: 0, isActivated: false }) this.props.dispatch(reset('AddEventForm')) } handleServiceActivation = (service, value) => { switch (service) { case 'github': this.setState({ isActivated: { ...this.state.isActivated, github: value, gitlab: false, }, }) break case 'gitlab': this.setState({ isActivated: { ...this.state.isActivated, gitlab: value, github: false, }, }) break default: this.setState({ isActivated: { ...this.state.isActivated, [service]: value, }, }) } } render() { const { classes } = this.props const { activeStep, isActivated } = this.state return ( <div> <Grid container justify="center"> <Grid item xs={12} sm={12} md={4} lg={4} xl={2}> <Grid container spacing={16}> <Grid item xs={12}> <Card className={classes.card}> <CardContent> <Typography type="headline" component="h2"> Add a event </Typography> <AddEventStepper isActivated={isActivated} activeStep={activeStep} handleBack={this.handleBack} handleNext={this.handleNext} handleReset={this.handleReset} handleServiceActivation={this.handleServiceActivation} /> </CardContent> </Card> </Grid> </Grid> </Grid> <Grid item xs={12} sm={12} md={8} lg={8} xl={4}> <Grid container spacing={16}> <EventInformations />{' '} {activeStep > 0 && <EventServices activeStep={activeStep} isActivated={isActivated} />} {activeStep > 1 && <EventTags />} </Grid> </Grid> </Grid> </div> ) } } AddEvent.propTypes = { classes: PropTypes.object.isRequired, } export default compose( withStyles(styles), reduxForm({ form: 'AddEventForm', destroyOnUnmount: false, initialValues: { eventName: '', eventDescription: '', }, }) )(AddEvent)
import React from "react"; import { Route, IndexRedirect } from "react-router"; import App from "../containers/App"; import { LoginView, RegistrationView, WelcomeView, NotFoundView } from "../views"; import { requireAuthentication } from "../utils"; export default ( <Route path="/" component={App}> <IndexRedirect to="/login" /> <Route path="/login" component={LoginView}></Route> {/* <Route path="/registration" component={RegistrationView}></Route> */ } <Route path="/welcome" component={requireAuthentication(WelcomeView)} /> <Route path="*" component={NotFoundView} /> </Route> );
var url; function newServizio(){ $('#dlg_servizio').dialog('open').dialog('setTitle','NUOVO SERVIZIO'); $('#form_servizio').form('clear'); $('#idc').combobox({ formatter:function(row){ return row.nomecategoria; } }); url = 'data/servizi/newServizio.cfm'; } function editServizio(){ $('#form_servizio').form('clear'); $('#idc').combobox({ formatter:function(row){ return row.nomecategoria; } }); var row = $('#grid_servizi').datagrid('getSelected'); if (row){ $('#dlg_servizio').dialog('open').dialog('setTitle','SERVIZIO DA MODIFICARE'); $('#form_servizio').form('load', { idcategoria: row.idc, servizio: row.servizio, unita: row.unita, prezzo: row.prezzo }); url = 'data/servizi/editServizio.cfm?id=' + row.id; } } function saveServizio(){ $('#form_servizio').form('submit',{ url: url, onSubmit: function(){ return $(this).form('validate'); }, success: function(data){ $('#dlg_servizio').dialog('close'); $('#grid_servizi').datagrid('reload'); } }); } function removeServizio(){ var row = $('#grid_servizi').datagrid('getSelected'); if (row){ $.messager.confirm('Conferma','Sicuro di rimuovere il servizio selezionato?',function(r){ if(r){ $.post('data/servizi/removeServizio.cfm',{id:row.id},function(){ $('#grid_servizi').datagrid('reload'); }); } }); } } function cercaservizio() { $('#grid_servizi').datagrid('load',{ filtronomeservizio: $('#filtro_nomeservizio').val() }); } function pulisciservizio() { $('#filtro_nomeservizio').searchbox('clear'); $('#grid_servizi').datagrid('reload',{ url: 'data/servizi/readServizi.cfm' }); }
const R = require('ramda'); const round = number => number.toFixed(1); const calculate = ({ potential, effort, weight }) => // eslint-disable-next-line no-mixed-operators 2 * potential + 1 - effort + weight; module.exports = metrics => R.compose(round, calculate)(metrics);
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const sequelize_1 = __importDefault(require("sequelize")); const sequelize = new sequelize_1.default(`postgresql://admin:admin@localhost:5432/chat`); exports.default = sequelize;
import * as React from 'react'; import {Text, View, StyleSheet, Clipboard} from 'react-native'; import Icon from 'react-native-vector-icons/MaterialCommunityIcons'; import {styles as globalStyles} from '../../styles'; import {COLORS, FONT, HELPER} from '../../utils'; import {strings} from '../../utils/localization'; function TransactionDetailScreen({route}) { const [collapse, setCollapse] = React.useState(true); const {detail} = route.params; const info = [ { title: detail?.beneficiary_name.toUpperCase(), detail: detail?.account_number, }, { title: strings.nominal, detail: 'Rp' + HELPER.SeperatorNumber(detail?.amount), }, { title: strings.transferNews, detail: detail?.remark, }, { title: strings.uniqCode, detail: detail?.unique_code, }, { title: strings.createTime, detail: HELPER.dateTimeFormat(detail?.created_at), }, { title: strings.fee, detail: detail?.fee, }, { title: strings.completedTime, detail: HELPER.dateTimeFormat(detail?.completed_at), }, { title: strings.status, detail: detail?.status, }, ]; function _copyToClipboard(text) { Clipboard.setString(text); } return ( <View style={styles.containers}> <View style={styles.card}> <View style={[styles.header, {borderBottomWidth: 0.2}]}> <Text style={styles.title} onPress={() => _copyToClipboard('#' + detail?.id)}> {strings.transactionId} #{detail?.id}{' '} <Icon name="content-copy" size={18} color={COLORS.ORANGE} /> </Text> </View> <View style={[styles.header, styles.row, {marginVertical: 0}]}> <Text style={[styles.title, {width: '85%'}]}> {strings.transactionDetail} </Text> <Text style={styles.collapseText} onPress={() => setCollapse(!collapse)}> {collapse ? strings.close : strings.open} </Text> </View> {collapse && ( <View style={styles.content}> <Text style={styles.sectionLabel}> {detail?.sender_bank.toUpperCase()}{' '} <Icon name="arrow-right-thick" size={18} />{' '} {detail?.beneficiary_bank.toUpperCase()} </Text> <View style={[styles.row, {flexWrap: 'wrap'}]}> {info.map((item, index) => { return ( <View key={index.toString()} style={[ styles.col, { width: index % 2 == 0 ? '60%' : '40%', marginVertical: 15, }, ]}> {item?.title === strings.status ? ( item?.detail.toUpperCase() === 'SUCCESS' ? ( <View style={styles.statusSuccess}> <Text style={styles.textStatusSuccess}> {item?.detail} </Text> </View> ) : ( <View style={styles.statusOther}> <Text style={styles.textStatusOther}> {item?.detail} </Text> </View> ) ) : ( <> <Text style={styles.sectionTitle}>{item?.title}</Text> <Text style={styles.sectionDescription}> {item?.detail} </Text> </> )} </View> ); })} </View> </View> )} </View> </View> ); } const styles = StyleSheet.create({ card: { backgroundColor: COLORS.WHITE, marginVertical: 20, }, header: { borderBottomColor: COLORS.LIGHT_GREY, borderBottomWidth: 0.5, padding: 20, }, content: { backgroundColor: COLORS.WHITE, marginVertical: 10, paddingHorizontal: 20, borderBottomColor: COLORS.LIGHT_GREY, }, title: { fontSize: 16, color: COLORS.BLACK, fontFamily: FONT.BOLD, }, collapseText: { color: COLORS.ORANGE, fontSize: 16, fontFamily: FONT.MEDIUM, textAlign: 'right', }, ...globalStyles, }); export default TransactionDetailScreen;
import React from "react"; import TableHeader from "../components/tableheader"; import TableBody from "../components/tablebody"; import JSONData from "../../content/data.json"; class Table extends React.Component { // state1 = { // columns: Object.keys(JSONData.content[0].properties[0]).map(value => ({ // key: value // })), // data: JSONData // }; state = { columns: Object.keys(JSONData.content[0].properties), data: JSONData }; render() { //const obj = JSON.parse(JSONData); //document.getElementById('message').innerHTML = obj; {console.log("Printing keys")} {console.log(JSONData.content[0])} {console.log("Printing data")} {console.log(this.state.data)} {console.log("Printing columns")} {console.log(this.state.columns)} return (<> <p id = "message"></p> <p> json <script>JSON.parse(JSONData).title</script> </p> <table> <TableHeader columns={this.state.columns} /> <TableBody columns={this.state.columns} data={this.state.data} /> // {console.log(this.state.columns)} </table> </> ); } } export default Table;
import React, { AlertIOS, Component, StatusBar, StyleSheet, Text, TextInput, View } from 'react-native'; import Constants from './Constants'; import Session from './Session'; class Login extends Component { constructor(props) { super(props); this.state = { username: '', password: '', }; } handleChangeUsername(username) { this.setState({username}); } handleChangePassword(password) { this.setState({password}); } handleFocusPassword() { this.refs.password.focus(); } handleSubmit() { // TODO: loading state... Session.login(this.state.username, this.state.password, err => { if (err) { AlertIOS.alert('There was a problem logging in.'); } }); } render() { return ( <View style={styles.container}> <StatusBar hidden={true} /> <View style={styles.innerContainer}> <Text style={styles.title}>{Constants.TITLE}</Text> <TextInput autoCapitalize="none" autoCorrect={false} onChangeText={this.handleChangeUsername.bind(this)} value={this.state.username} style={styles.text} placeholder="name@email.com" onSubmitEditing={this.handleFocusPassword.bind(this)} /> <TextInput onChangeText={this.handleChangePassword.bind(this)} value={this.state.password} style={styles.text} placeholder="password" secureTextEntry onSubmitEditing={this.handleSubmit.bind(this)} ref="password" /> </View> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#eee', alignItems: 'center', justifyContent: 'center', }, title: { fontSize: 36, textAlign: 'center', marginBottom: 40 }, text: { flex: 1, fontSize: 20, height: 24, width: 200, backgroundColor: '#f8f8f8', marginBottom: 10, }, }); export default Login;
import React from 'react'; import Header from '../components/Header/customHeader'; import { Row, Col, Image } from 'react-bootstrap'; import * as actions from '../../redux/actions/index'; import { connect } from 'react-redux'; import SingleAnalyst from './SingleAnalyst'; import { CircularProgress } from '@material-ui/core'; import Grow from '@material-ui/core/Grow'; import Loading from '../Loading/Loading'; import './AnalystLeaderboard.scss'; const AnalystLeaderboard = props => { // console.log('###############################', props); return ( <div style={{ paddingTop: '1rem', paddingBottom: '1.5rem' }}> {props && props.analyst_leaderboard !== null ? ( props.analyst_leaderboard.length > 0 ? ( props.analyst_leaderboard.map((d, idx) => <SingleAnalyst data={d} idx={idx} key={idx} />) ) : ( <Row> <Col> <Image src={require('../../assets/images/svg/Investor_No_Activity.svg')} className='user-on-board-image' /> </Col> </Row> ) ) : ( <Loading /> )} </div> ); }; export default AnalystLeaderboard;
angular.module('starter.services',[]) .service('AppService',function(){ //收到通知调用 var onReceiveNotification = function(event){ try{ var alertContent if(device.platform == "Android"){ alertContent = window.plugins.jPushPlugin.receiveNotification.alert; }else{ alertContent = event.aps.alert; } console.log('document onReceiveNotification'); console.log(alertContent); }catch(exeption){ console.log(exception) } }; //打开通知调用 var onOpenNotification = function(event){ try{ var alertContent if(device.platform == "Android"){ alertContent=window.plugins.jPushPlugin.openNotification.alert; }else{ alertContent = event.aps.alert; } console.log('document receiveNotification'); console.log(alertContent); } catch(exception){ console.log("JPushPlugin:onOpenNotification"+exception); } }; //收到信息调用 var onReceiveMessage = function(event){ try{ var message if(device.platform == "Android"){ message = window.plugins.jPushPlugin.receiveMessage.message; }else{ message = event.content; } console.log('document openNotification'); console.log(message); } catch(exception){ console.log("JPushPlugin:onReceiveMessage-->"+exception); } }; var onTagsWithAlias = function(event){ try{ console.log("onTagsWithAlias"); var result="result code:"+event.resultCode+" "; result+="tags:"+event.tags+" "; result+="alias:"+event.alias+" "; console.log(result) } catch(exception){ console.log(exception) } }; this.initPush = function(){ try{ window.plugins.jPushPlugin.init(); //用于开启调试模式,可以查看集成JPush过程中的log,如果集成失败,可方便定位问题所在 window.plugins.jPushPlugin.setDebugMode (true) //用于android收到应用内消息的回调函数(请注意和通知的区别),该函数不需要主动调用 window.plugins.jPushPlugin.receiveMessageInAndroidCallback = function(data){ console.log('receiveMessageInAndroidCallback'); console.log(data); }; //当点击android手机的通知栏进入应用程序时,会调用这个函数,这个函数不需要主动调用,是作为回调函数来用的 window.plugins.jPushPlugin.openNotificationInAndroidCallback = function(data){ console.log('openNotificationInAndroidCallback'); console.log(data); } document.addEventListener("jpush.receiveNotification", onReceiveNotification, false); document.addEventListener("jpush.setTagsWithAlias", onTagsWithAlias, false); //若有 openNotificationInAndroidCallback 则此方法不调用 document.addEventListener("jpush.openNotification", onOpenNotification, false); //若有 receiveMessageInAndroidCallback 则此方法不调用 document.addEventListener("jpush.receiveMessage", onReceiveMessage, false); }catch(exception){ console.log("JPushPlugin:init-->"+exception); } }; //tags 为数组,alias 为字符串 this.setTagsWithAlias = function(tags,alias){ try{ window.plugins.jPushPlugin.setTagsWithAlias(tags,alias); }catch(exception){ console.log("JPushPlugin:setTagsWithAlias-->"+exception); } } });
shop. factory('Components', ['$rootScope', '$cookieStore', function ($rootScope, $cookieStore) { var userRoles = $cookieStore.get('roles'); var accessLevels = $cookieStore.get('accessLevels'); var user = $cookieStore.get('user') || {role: 1}; $cookieStore.remove('roles'); $cookieStore.remove('accessLevels'); $cookieStore.remove('user'); $rootScope.userRoles = userRoles; $rootScope.accessLevels = accessLevels; $rootScope.user = user; return { userRoles: function () { return userRoles; }, accessLevels: function () { return accessLevels; }, user: function () { return user; } }; }]);
export default [{ name: 'ram', age: 20, id: 1 }, { name: 'ram1', age: 20, id: 2 }, { name: 'ra', age: 20, id: 3 }];
var people = ["Jon", "Jacob", "Jingle", "Heimer", "Schmidt"]; var alphabet = "abcdefghijklmnopqrstuvwxyz"; function loopdyloop(people, alphabet) { var loopy = [] for (i = 0; i < people.length; i++) { loopy.push(people[i]) for (k = 0; k < alphabet.length; k++) { loopy.push(alphabet[k]) } } console.log(loopy) } loopdyloop(people, alphabet)
import React, { Component } from 'react'; import { StyleSheet, Text, Image, View } from 'react-native'; import reciprocity_logo from 'shared/img/reciprocity_logo.png'; class AboutPanel extends Component { static navigationOptions = { headerStyle: { backgroundColor: '#a044ff', }, }; render() { return ( <View style={styles.content}> <View style={{ flex: 1 }}> <Text style={styles.header}>About</Text> </View> <View style={{ flex: 12, justifyContent: 'center', alignItems: 'center' }}> <Image source={reciprocity_logo} style={styles.image} /> <Text style={styles.body_text}>Reciprocity Core</Text> <Text style={styles.body_text}>© 2019 Anthony Buckle, April Buckle</Text> </View> </View> ); } } const styles = StyleSheet.create({ content: { flex: 1, flexDirection: 'column', alignItems: 'center', justifyContent: 'center', backgroundColor: '#a044ff' }, header: { fontWeight: 'bold', fontSize: 20, color: "white", padding: 10 }, image: { width: 200, height: 200, padding: 5 }, body_text: { color: "white", fontSize: 18, padding: 5 } }); export default AboutPanel;
function solve(input) { let set = new Set(); for(let arr of input) { set.add(arr); } console.log(Array.from(new Set([...set])).sort().map(a => `[${a}]`).join('\n')) } solve(['[-3, -2, -1, 0, 1, 2, 3, 4]', '[10, 1, -17, 0, 2, 13]', '[4, -3, 3, -2, 2, -1, 1, 0]']);
'use strict'; /** * FUNCTION: getPDF( a, b ) * Returns a probability density function for a uniform distribution with parameters `a` and `b`. * * @private * @param {Number} a - minimum value * @param {Number} b - maximum value * @returns {Function} probability density function (PDF) */ function getPDF( a, b ) { /** * FUNCTION: pdf( x ) * Evaluates the probability distribution function at input value `x`. * * @private * @param {Number} x - input value * @returns {Number} evaluated PDF */ return function pdf( x ) { return ( a <= x && x <= b ) ? 1 / ( b - a ) : 0; }; } // end FUNCTION getPDF() // EXPORTS // module.exports = getPDF;
import _axios from "axios"; const axios = _axios.create({ baseURL: "http://hapi.fhir.org/baseR4", }); export const getPatients = (query=undefined) => { if(query){ let queryString = "?" for (const [key,value] of Object.entries(query)){ queryString += `${key}=${value},` } return axios.get("/Patient"+ queryString); } else{ return axios.get("/Patient"); } }; export const getPractitioners = () => { return axios.get("/Practitioner"); };
import React, {useState} from 'react'; import {Field, Control, Input, Button} from 'bloomer' import {withRouter} from 'react-router-dom'; function BooksSearchBar(props) { const [inputValue, setInputValue] = useState(""); function handleClick(){ props.history.push(`/bookList?q=${inputValue}`) } function handleKey(e){ if(e.which == 13) { handleClick(); } } return ( <Field hasAddons="fullwidth"> <Control> <Input onKeyPress={handleKey} isSize="medium" type="text" placeholder='eq. Harry Potter' onChange={(e) => setInputValue(e.target.value)} /> </Control> <Button isSize="medium" isColor="succes" onClick={handleClick}> Submit </Button> </Field> ) } export default withRouter(BooksSearchBar)
var express = require('express'); var router = express.Router(); const User = require('../models/User') const passport = require('passport') /* GET users listing. */ router.get('/', async function(req, res, next) { await User.find({}).then(doc => { res.json(doc) }) }); router.get('/add',(req,res) => { res.render("Registration") }) router.get('/:id', async function(req, res, next) { await User.findById({}).then(doc => { res.json(doc) }) }); // POST Routes router.post("/add",(req,res) => { console.log(req.session) let email = req.body.email; let username = req.body.username; let password = req.body.password let newUser = new User() newUser.email = email newUser.username = username newUser.password = newUser.genHash(password) newUser.save() .then((doc) => { res.json(doc) }) .catch(err => { console.log(err) }) }) router.post('/login',passport.authenticate('local',{ failureRedirect:'/login', successRedirect:'/blog/top' })) module.exports = router;
/*jshint strict:false, loopfunc:true*/ /*global beforeEach, describe, it*/ var ZSchema = require("../src/ZSchema"); var assert = require("chai").assert; describe("https://github.com/zaggino/z-schema/issues/13", function () { var schemaA; var schemaB; var mainSchema; beforeEach(function () { schemaA = {id: "schemaA", type: "integer"}; schemaB = {id: "schemaB", type: "string"}; mainSchema = { id: "mainSchema", type: "object", properties: { a: {"$ref": "schemaA"}, b: {"$ref": "schemaB"}, c: {"enum": ["C"]} } }; }); it("should add compilation marks to a schema if it passed compilation", function (done) { var schema = {id: "schemaA", type: "integer"}; var validator = new ZSchema(); validator.compileSchema(schema).then(function () { assert.isTrue(schema.__$compiled); done(); }).fail(function (err) { assert.isUndefined(err); done(); }).fail(function (e) { done(e); }); }); it("should erase compilation marks from schema if it failed to compile", function (done) { var schema = { $ref: "woohooo" }; var validator = new ZSchema(); validator.compileSchema(schema).then(function () { assert.isTrue(false); done(); }).fail(function () { assert.isUndefined(schema.__$compiled); done(); }).fail(function (e) { done(e); }); }); it("should add validation marks to a schema if it passed validation", function (done) { var schema = {id: "schemaA", type: "integer"}; var validator = new ZSchema(); validator.validateSchema(schema).then(function () { assert.isTrue(schema.__$validated); done(); }).fail(function (err) { assert.isUndefined(err); done(); }).fail(function (e) { done(e); }); }); it("should erase validation marks from schema if it failed to validate", function (done) { var schema = {id: "schemaA", type: "woohooo"}; var validator = new ZSchema(); validator.validateSchema(schema).then(function () { assert.isTrue(false); done(); }).fail(function () { assert.isUndefined(schema.__$validated); done(); }).fail(function (e) { done(e); }); }); it("mainSchema should fail compilation on its own", function (done) { var validator = new ZSchema(); validator.compileSchema(mainSchema).then(function (report) { assert.isFalse(report.valid); done(); }).fail(function (err) { assert.isDefined(err); done(); }).fail(function (e) { done(e); }); }); it("mainSchema should fail compilation with only one schema", function (done) { var validator = new ZSchema(); validator.compileSchema([mainSchema, schemaA], function (err) { try { assert.isDefined(err); done(); } catch (e) { done(e); } }); }); it("after compiling schemaA and schemaB, mainSchema compilation should pass", function (done) { var validator = new ZSchema(); validator.compileSchema(schemaA).then(function () { return validator.compileSchema(schemaB).then(function () { return validator.compileSchema(mainSchema).then(function () { done(); }); }); }).fail(function (err) { assert.isUndefined(err); done(); }).fail(function (e) { done(e); }); }); it("compile multiple schemas at once in correct order", function (done) { var validator = new ZSchema(); validator.compileSchema([schemaA, schemaB, mainSchema]).then(function () { assert.isTrue(schemaA.__$compiled); assert.isTrue(schemaB.__$compiled); assert.isTrue(mainSchema.__$compiled); done(); }).fail(function (e) { done(e); }); }); it("compile multiple schemas at once in any order", function (done) { var validator = new ZSchema(); validator.compileSchema([schemaA, mainSchema, schemaB]).then(function () { assert.isTrue(schemaA.__$compiled); assert.isTrue(schemaB.__$compiled); assert.isTrue(mainSchema.__$compiled); done(); }).fail(function (e) { done(e); }); }); it("compile multiple schemas should not run forever if not resolvable", function (done) { var validator = new ZSchema(); validator.compileSchema([schemaA, mainSchema]).catch(function (err) { assert.isTrue(err.errors.length > 0); done(); }); }); it("should validate with mainSchema", function (done) { var validator = new ZSchema(); validator.compileSchema([schemaA, schemaB, mainSchema]).then(function () { return validator.validate({a: 1, b: "b", c: "C"}, mainSchema).then(function (report) { assert.isTrue(report.valid); done(); }); }).fail(function (err) { assert.isUndefined(err); done(); }).fail(function (e) { done(e); }); }); it("should not validate with mainSchema", function (done) { var validator = new ZSchema(); validator.compileSchema([schemaA, schemaB, mainSchema]).then(function () { return validator.validate({a: "a", b: 2, c: "X"}, mainSchema).then(function () { assert.isTrue(false); }); }).fail(function (err) { assert.isTrue(err.errors.length === 3); done(); }).fail(function (e) { done(e); }); }); });
const path = require('path'); const dotenv = require('dotenv'); const webpack = require('webpack'); const merge = require('webpack-merge'); const UglifyJsPlugin = require('uglifyjs-webpack-plugin'); const MiniCssExtractPlugin = require('mini-css-extract-plugin'); const common = require('./webpack.common'); const env = dotenv.config().parsed; module.exports = merge(common, { output: { path: path.resolve(__dirname, '..', 'dist'), filename: 'index.js', }, module: { rules: [ // { // test: /\.css$/, // use: [ // MiniCssExtractPlugin.loader, // { // loader: 'css-loader', // }, // ] // }, // @TODO fix mini extract for prod.. shits broken right now. ], }, plugins: [ new MiniCssExtractPlugin({ filename: '[name].[hash].css', chunkFilename: '[id].[hash].css', }), new webpack.EnvironmentPlugin({ ...env, NODE_ENV: 'production', }), new UglifyJsPlugin({ sourceMap: true, }), ], });
// westore默认的change回调,res 更新的字段,比如是 userInfo.name userInfo.age userId // 如果是多个更新,会多个都回调过来 // Object.keys(params).forEach(key => { // console.log(key); // }); // 对westore的 onChange 进行细分。制作类似vue的watch方法 export default function(obj) { if (!obj) { this.log(`需要传入监听 watch 方法`); return; } this.onChange = (newVal) => { try { Object.keys(newVal).forEach(key => { const callBack = obj[key]; const isFun = Object.prototype.toString.call(callBack) == '[object Function]'; // 没有设置该值的监听 if (!isFun) { return; } const isHave = Object.prototype.toString.call(newVal[key]); if (isHave == '[object Undefined]' || isHave == '[object Null]') { this.log(`更新的值为 Undefined 或者 Null`); } // 监听回调 callBack(newVal[key]); }); } catch (error) { this.log(`监听出错 ${JSON.stringify(error)}`); } } }
// function printOdd1To255() { // for(let i = 0; i <= 255; i++) { // if(i % 2 !== 0) { // console.log(i) // } // } // } // printOdd1To255() function printOdd1To255() { i = 0; while(i <= 255) { if(i % 2 !== 0) { console.log(i) } i++; } } printOdd1To255()
console.log("Hello world"); // Простые типы var myNumber = 2345, myString = "Строка", myBool = true, myNull = null, myUndef = undefined; console.log(myNumber); console.log(myString); console.log(myBool); console.log(myNull); console.log(myUndef); console.log(""); console.log(typeof(myNumber)); console.log(typeof(myString)); console.log(typeof(myBool)); console.log(typeof(myNull)); console.log(typeof(myUndef)); console.log(""); //объектные типы var obj = {name: "Вася"}, array = [1, 2, 3], regexp = /\w+/g, func = function(){}; console.log(typeof(array)); console.log(array); console.log(""); console.log(myString.toUpperCase()); console.log(myString); console.log(""); var a, b, c, d; a = b = c = d = 5; console.log(a); console.log(b); console.log(c); console.log(d);
// let myArray: Array<number> = []; // function funcao(array: Array<number>) { // } function funcao(param) { return param; } var variable = funcao(2); var Lista = /** @class */ (function () { function Lista() { this.items = []; } Lista.prototype.add = function (item) { console.log("add " + item); }; Lista.prototype.remove = function (item) { console.log("remove " + item); }; return Lista; }()); var lista = new Lista(); lista.add(3); lista.remove(2);
import { useLocation, useParams } from "react-router-dom" const Post = () => { const { id } = useParams() const query = new URLSearchParams(useLocation().search) // console.log(query) return ( <> <h2>Id is = {id}</h2> {/* http://localhost:3000/tuturial/post/random?first=john&last=gray */} <h2>{query.get('first')}</h2> <h2>{query.get('last')}</h2> </> ) } export default Post
import { Dimensions, Platform } from 'react-native' export const BASE_URL = 'https://itunes.apple.com/'; export const API = { GET_SEARCH_ITUNE:BASE_URL + 'search?term=', } export const APP_PARAMS = { ROLE: "role", } export const KEY = { PARAMS_NAME: 'name', SUCCESS_: false, FAILED_: true } export const LOCALES = { ENGLISH: { id: 1, name: "en", label: "ENGLISH" }, HINDI: { id: 2, name: "hi", label: "हिंदी" } }; export const FONT_FAMILIY = { } export const DIMENS = { px_0: 0, px_05: 0.5, px_1: 1, px_2: 2, px_3: 3, px_5: 5, px_7: 7, px_8: 8, px_10: 10, px_12: 12, px_300: 300, px_14: 14, px_15: 15, px_15: 16, px_18: 18, px_20: 20, px_22: 22, px_23: 23, px_25: 25, px_28: 28, px_30: 30, px_32: 32, px_35: 35, px_40: 40, px_45: 45, px_50: 50, px_60: 60, px_65: 65, px_70: 70, px_75: 75, px_80: 80, px_90: 90, px_100: 100, px_110: 110, px_120: 120, px_130: 130, px_140: 140, px_150: 150, px_160: 160, px_180: 180, px_200: 200, px_220: 220, px_230: 230, px_250: 250, btn_font_size: 16, btn_h: 40, devider_h: 1, devider_h_half: 0.5, devider_h_1: 1, txt_size_small_small: 10, txt_size_small: 11, txt_size_small_12: 12, txt_size_min_small: 8, txt_size_min_small_9: 9, txt_size_medium: 13, txt_size_medium_14: 14, txt_size_medium_1: 15, txt_size_large: 16, txt_size_large_extra: 18, txt_size_large_extra_20: 20, txt_size_large_extra_26: 26, txt_size_large_extra_30: 30, txt_size_large_extra_40: 40, row_h: 50, minHeight: 50, row_img_w: 60, row_img_big: 70, row_img_w_2: 50, tab_width: 24, //Category Size cat_img_width: 55, cat_img_height: 55, cat_img_radius: 27.5 } export const SCREEN = { NAVIGATION_TAB: 'NavigationTab', SCREEN_ASSIGNMENT_ONE: 'AssignmentOne', SCREEN_ASSIGNMENT_TWO: 'AssignmentTwo', SCREEN_ASSIGNMENT_THREE: 'AssignmentThree', } //HEIGHT AND WIDTH export const WIDTH = Dimensions.get('screen').width export const HEIGHT = Dimensions.get('screen').height //API export const APP_ASIGN_TWO_ITUNE_SUCESS = 'APP_ASIGN_TWO_ITUNE_SUCESS' export const APP_ASIGN_TWO_ITUNE_FAIL = 'APP_ASIGN_TWO_ITUNE_FAIL' export const APP_ASIGN_TWO_ITUNE_REQUEST = 'APP_ASIGN_TWO_ITUNE_REQUEST' // Internet connection state export const APP_START = 'APP_START' export const APP_START_SUCCESS = 'APP_START_SUCCESS' export const APP_START_FAIL = 'APP_START_FAIL' export const CONNECTION_STATE_CHANGE = 'CONNECTION_STATE_CHANGE'
define([ 'jquery', 'jquery-ui', 'kendo', ], function ($) { $.widget('spacetimeinsight.siViewerChartLegend', $.spacetimeinsight.siViewerBaseWidget, { options: { chartLegendDataObj :"", }, //chartLegendData: "", pluginName: "siViewerChartLegend", GENERIC_DIV: kendo.template("<div id ='#= id #' style = 'width : 100%; height : 100%' > </div>"), _create: function () { this.options.chartLegendDataObj = this.options.chartLegendData; this._super(); }, _createControls: function () { this._super(); template = "<span class='legend-color-box' style='background-color:#: item.color #; 'alt=' #: item.seriesName #'></span><span class='legend-color-label'><span>#: item.displayName #</span></span>" $(this.element).append(this.GENERIC_DIV({ id: "chartLegendTreeview" })); this._buildTree(); }, _bindControls: function () { this._super(); }, _buildTree: function () { var $this = this; var treeview = this.element.find("#chartLegendTreeview"); treeview.kendoTreeView({ template: template, dataSource: { data: this.options.chartLegendDataObj }, select: function (e) { e.preventDefault(); var item = $(e.node); $this._changeLegendState(item,null); var itemIndex = $this.getSelectedLegendIndex(item); $this._trigger("onHideOrShowSeriesOnChart", null, { nodeName: item[0].textContent, nodeIndex: itemIndex, }); }, }); if (treeview.data("kendoTreeView") != null) { treeview.data("kendoTreeView").expand(".k-item"); } }, updateChartLegendState : function(data){ var $this = this; var treeView = $($this.element).find("#chartLegendTreeview").data("kendoTreeView"); for (var i = 0; i < data.series.length; i++) { var node = treeView.findByText(data.series[i].name); $this._changeLegendState(node,data.series[i].visible); } }, _changeLegendState : function(item,visible){ var node = $(item).find('.k-in'); if(visible == null){ if(node.hasClass("chartlegend-selected")){ node.removeClass("chartlegend-selected"); node.addClass("chartlegend-unselected"); }else if(node.hasClass("chartlegend-unselected")){ node.removeClass("chartlegend-unselected"); node.addClass("chartlegend-selected"); }else{ node.addClass("chartlegend-selected"); } }else if(visible){ node.removeClass("chartlegend-selected"); node.addClass("chartlegend-unselected"); }else if(!visible){ node.removeClass("chartlegend-unselected"); node.addClass("chartlegend-selected"); } }, getSelectedLegendIndex: function (item){ var legendContainer = item.parent(); var legendItems,itemIndex = -1 ; if(legendContainer){ legendItems = legendContainer.children(); itemIndex = $.inArray(item[0],legendItems); } return itemIndex; }, setLegendData : function(chartLegendData){ if(chartLegendData === undefined || chartLegendData == null) { chartLegendData = []; } this.options.chartLegendDataObj = chartLegendData; $("#chartLegendTreeview").data("kendoTreeView").setDataSource(chartLegendData); }, }); });
$(document).ready(function () { var uploadBase = "http://52.28.249.10:8898"; var corappUploadUrl = "/contractsSharing/cordapp"; var uploadurl = uploadBase + corappUploadUrl console.log("uploadurl :" + uploadurl) $('#uploadBtn').on('click', function () { var cordapp = $("#fileinputcordapp") var cordappFile = cordapp[0].files[0] var imageItem = $("#iconInput") var imageFile = imageItem[0].files[0] var nodesList = $("#nodesList").val() var cordappName = $("#cordappName").val() var auth = $("#authorization").val() // The Javascript var formData = new FormData(); formData.append('cordappFile', cordappFile); formData.append('cordappIcon', imageFile); formData.append('nodesList', nodesList); formData.append('cordappName', cordappName); // var formAction = form.attr('action'); $.ajax({ url: uploadBase + corappUploadUrl, data: formData, contentType: false, processData: false, type: 'POST', headers: { 'Authorization': auth }, success: function (data, textStatus, jqXHR) { console.log("succeess: " + data); }, error: function (req, status, error) { console.log(req); } }); }); $('#testBtn').on('click', function () { alert('here') $.ajax({ type: "GET", url: "http://52.28.249.10:8898/node/isBootstrapped", dataType: 'json', headers: { 'Authorization': "SafeXain SafeXain eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJ0ZXN0IiwiaXNzIjoibWFydHlkZXYxQG1haWxpbmF0b3IuY29tIiwiZXhwIjoxNTgxNjA0Mjk4fQ.H-vDoeOkTgN18jT8K-ZG_-u5TuAG8zm-wv9phd_LGlZk-K4ISYS_kfjvhHXJ8GvcV6CzcjRDd4huBLy4tv38eg" }, success: function () { console.log('Success ') }, error: function (req, status, error) { alert(error); } }); }); var canvas = document.getElementById('flatten'), context = canvas.getContext('2d'); make_base(); function make_base() { base_image = new Image(); base_image.src = 'img/image.jpg'; base_image.onload = function(){ context.drawImage(base_image, 0, 0); } } function postCanvasToURL() { // Convert canvas image to Base64 var img = snap.toDataURL(); // Convert Base64 image to binary var file = dataURItoBlob(img); } function dataURItoBlob(dataURI) { console.log('dataURItoBlob') // convert base64/URLEncoded data component to raw binary data held in a string var byteString; if (dataURI.split(',')[0].indexOf('base64') >= 0) byteString = atob(dataURI.split(',')[1]); else byteString = unescape(dataURI.split(',')[1]); // separate out the mime component var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]; // write the bytes of the string to a typed array var ia = new Uint8Array(byteString.length); for (var i = 0; i < byteString.length; i++) { ia[i] = byteString.charCodeAt(i); } return new Blob([ia], { type: mimeString }); } var snap = document.getElementById('flatten'); var flatten = snap.getContext('2d'); function postCanvasToURL() { console.log('postCanvasToURL') // Convert canvas image to Base64 var img = snap.toDataURL(); // Convert Base64 image to binary var file = dataURItoBlob(img); } $('#canvasUpload').on('click', function () { console.log('click canvas') // Convert canvas image to Base64 var img = snap.toDataURL(); // Convert Base64 image to binary var imageFile = dataURItoBlob(img); //------------ var cordapp = $("#fileinputcordapp") var cordappFile = cordapp[0].files[0] var imageItem = $("#iconInput") //var imageFile = imageItem[0].files[0] var nodesList = $("#nodesList").val() var cordappName = $("#cordappName").val() var auth = $("#authorization").val() // The Javascript var formData = new FormData(); formData.append('cordappFile', cordappFile); formData.append('cordappIcon', imageFile); formData.append('nodesList', nodesList); formData.append('cordappName', cordappName); // var formAction = form.attr('action'); $.ajax({ url: uploadBase + corappUploadUrl, data: formData, contentType: false, processData: false, type: 'POST', headers: { 'Authorization': auth }, success: function (data, textStatus, jqXHR) { console.log("succeess: " + data); }, error: function (req, status, error) { console.log(req); } }); }); $('#shareCordapp').on('click', function () { var cordapp = $("#fileinputcordapp") var cordappName = $("#cordappName").val() var cordappFile = cordapp[0].files[0] var imageItem = $("#iconInput") var imageFile = imageItem[0].files[0] var form = new FormData(); form.append("cordappFile", cordappFile); form.append("cordappIcon", imageFile); form.append("nodesList", "O=Martytest12, L=Warwickshire, C=GB"); form.append("cordappName", cordappName); console.log("before-----------------") console.log(form) var settings = { "async": true, "crossDomain": true, "url": "http://52.57.11.117:8898/contractsSharing/cordapp", "method": "POST", "headers": { "authorization": "SafeXain SafeXain eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJ0ZXN0IiwiaXNzIjoibWFydHl0ZXN0MTNAbWFpbGluYXRvci5jb20iLCJleHAiOjE1ODIwMzQxMTR9.PGt0JMfMLlrRauubqLMoqtVoJHUxuJ936w2PSn8izHK4kn1njGavOWJijd62CKMK8ZgecRxmo_bf1-Je3ELLGQ", // "cache-control": "no-cache", // "postman-token": "ec5a21c9-bf7f-0fc4-7167-4db7af01f923" }, "processData": false, "contentType": false, // "mimeType": "multipart/form-data", "data": form } $.ajax(settings).done(function (response) { console.log("=====response"); console.log(response); }); }); });
import React, { Component } from 'react'; import { connect } from 'react-redux'; import actions from '../../actions'; import Nav from './Nav'; import SavedUniversities from '../presentation/SavedUniversities'; import SelectedUniversities from "../presentation/SelectedUniversities"; import axios from "axios"; import superagent from 'superagent'; class University extends Component { constructor(props) { super(props); this.state = { shouldShowSavedUniversities: true } this.getSavedUniversities = this.getSavedUniversities.bind(this); this.toggleSavedSchools = this.toggleSavedSchools.bind(this); this.deleteSchool = this.deleteSchool.bind(this); } componentDidMount() { this.getSavedUniversities(); } getSavedUniversities() { axios.get("/api/universities/user/savedschools") .then(result => { this.props.savedUniversitiesReceived(result.data) // this is an array of universities }) .catch(err => { console.log("we have not got the data!"); }); } saveSchool(university) { this.props.savedUniversitiesReceived([university]); axios.put("/api/universities/savedschools", { data: university._id }).then(result => { const savedSchool = this.props.savedUniversities[this.props.savedUniversities.length - 1] console.log("HERE IS THE SAVED SCHOOL", savedSchool); axios.post("/newsfeed/tweets", { savedSchool }) }) .catch(err => { console.log("Error occured while saving school " + err); }); } deleteSchool(university_id) { this.props.removeUniversityFromSaved(university_id); axios.delete("/api/universities/savedschools/" + university_id) .then(result => { console.log("deleted school is ", result); }) .catch(err => { console.log("Error occured while deleting school " + err); }); } toggleSavedSchools() { this.setState({ shouldShowSavedUniversities: !this.state.shouldShowSavedUniversities }) } render() { const { shouldShowSavedUniversities = false } = this.state; let { selectedUniversities = [], savedUniversities = [] } = this.props; console.log("this.props.savedUniversities: ", this.props.savedUniversities); const saved_universities_visible = !!savedUniversities.length && shouldShowSavedUniversities; const see_saved_button_text = saved_universities_visible ? 'Hide saved' : 'See saved'; return( <div className='universities_section'> <div> { (selectedUniversities.length) ? <div className='row'> <h3> Found { selectedUniversities.length } { selectedUniversities.length == 1 ? 'result' : 'results'} </h3> <div> <SelectedUniversities removeUniversityFromSelected={this.props.removeUniversityFromSelected} savedUniversities={savedUniversities} saveSchool={this.saveSchool.bind(this)} selectedUniversities={selectedUniversities} deleteSchool={this.deleteSchool} /> </div> </div> : null } </div> <div> { <div className='row'> <div className="col-md-8"> { saved_universities_visible ? <h3>Saved Universities</h3> : null } </div> <div className="col-md-4"> { !!savedUniversities.length && <button href="#" onClick={this.toggleSavedSchools} className="btn btn-primary pull-right" role="button"> {see_saved_button_text} </button> } </div> { saved_universities_visible && <SavedUniversities savedUniversities={savedUniversities} shouldShowSavedUniversities={shouldShowSavedUniversities} getSavedUniversities={this.getSavedUniversities} deleteSchool={this.deleteSchool} toggleSavedSchools={this.toggleSavedSchools} /> } </div> } </div> </div> ); } } const mapStateToProps = (state) => { const { university = {} } = state; const { selectedUniversities = {}, savedUniversities = {} } = university; const selected_universities_list = Object.values(selectedUniversities); const saved_universities_list = Object.values(savedUniversities); return { selectedUniversities: selected_universities_list, savedUniversities: saved_universities_list, } } const mapDispatchToProps = (dispatch) => { return { schoolCardClosed: (index) => dispatch(actions.schoolCardClosed(index)), savedUniversitiesReceived: (universities) => dispatch(actions.savedUniversitiesReceived(universities)), removeUniversityFromSaved: (universities_id) => dispatch(actions.removeUniversityFromSaved(universities_id)), removeUniversityFromSelected: (universities_id) => dispatch(actions.removeUniversityFromSelected(universities_id)) } } export default connect(mapStateToProps, mapDispatchToProps)(University);
const initialState = { data: [], message: '', isLoading: false, isLogin: false } export default user = (state = initialState, action) => { switch(action.type) { case "GET_FULL_PRORILE_PENDING": return Object.assign({}, state, { isLoading: true }); case "GET_FULL_PRORILE_REJECTED": return Object.assign({}, state, { isLoading: false }); case "GET_FULL_PRORILE_FULFILLED": return Object.assign({}, state, { data: action.payload.data, isLoading: false }); case "UPDATE_PROFILE_PENDING": return Object.assign({}, state, { isLoading: true }); case "UPDATE_PROFILE_REJECTED": return Object.assign({}, state, { isLoading: false }); case "UPDATE_PROFILE_FULFILLED": return Object.assign({}, state, { data: action.payload.data, isLoading: false }); case 'REGISTER_USER_PENDING': return { ...state, isLoading: true } case 'REGISTER_USER_REJECTED': return { ...state, isLoading: false, isLogin: false } case 'REGISTER_USER_FULFILLED': alert('Register success') return { ...state, isLoading: false, message: action.payload.data } default: return state } }
require('dotenv').config() const app = require('./app') const socket = require('./socket') const port = process.env.PORT const server = app.listen(port, () => console.log('server running...')) socket(server)
/* eslint-disable import/no-anonymous-default-export */ export default { name: 'lesson', type: 'document', title: 'Lesson', fields: [ { name: 'title', type: 'string', title: 'Title', description: 'Titles should be catchy, descriptive, and not too long', validation: (Rule) => Rule.custom((field, context) => context.document.status && context.document.status === 'published' && (field === undefined || field.length < 1) ? 'Must have a title to publish' : true, ), }, { name: 'slug', type: 'slug', title: 'Slug', validation: (Rule) => Rule.required(), description: 'Some frontends will require a slug to be set to be able to show the post', options: { source: 'title', maxLength: 96, }, }, { name: 'resources', description: 'Attach a resource to this lesson (Video, Audio, Text, etc.)', title: 'Resources', type: 'array', of: [ { title: 'Video Resource', type: 'reference', to: [{type: 'videoResource'}], }, { title: 'Scrimba Resource', type: 'scrimbaResource', }, ], }, { name: 'description', type: 'markdown', title: 'Description', description: 'This can be used to provide a short description of the lesson.', }, { name: 'repoUrl', type: 'url', title: 'Github Repository Url', description: "A link to the Github repository where the lesson's code is hosted", }, { name: 'softwareLibraries', description: 'Versioned Software Libraries', title: 'NPM or other Dependencies', type: 'array', of: [ { type: 'versioned-software-library', }, ], }, { name: 'collaborators', description: 'Humans that worked on this resource and get credit for the effort.', title: 'Collaborators', type: 'array', of: [ { type: 'reference', to: [{type: 'collaborator'}], }, ], }, { title: 'Status', name: 'status', type: 'string', options: { list: [ {title: 'Needs Review', value: 'needs-review'}, {title: 'Approved', value: 'approved'}, {title: 'Published', value: 'published'}, {title: 'Archived', value: 'archived'}, ], }, }, { title: 'Access Level', name: 'accessLevel', type: 'string', options: { list: [ {title: 'Free', value: 'free'}, {title: 'Pro', value: 'pro'}, ], layout: 'radio', }, }, { name: 'thumbnailUrl', title: 'Thumbnail URL', type: 'url', }, { name: 'iconUrl', title: 'Icon URL', type: 'url', }, { name: 'codeUrl', title: 'Code URL', type: 'url', }, { name: 'displayedUpdatedAt', description: 'The last time this lesson was meaningfully updated', title: 'Displayed Updated At', type: 'date', }, { name: 'publishedAt', description: 'The date this lesson was published', title: 'Published At', type: 'date', }, { name: 'eggheadRailsCreatedAt', title: 'egghead Rails Created At', description: 'Date this lesson resource was created on egghead.io', type: 'datetime', }, { title: 'The lessons internal ID on egghead-rails', name: 'eggheadRailsLessonId', type: 'number', hidden: true, }, ], }
#!/usr/bin/env node import "colors" import { program } from "commander" import build from "./build" import serve from "./serve" import { rmdir } from "../fs" import globalInfo from "../globalInfo" import createProject from "../utils/cli-utils/create-project" const configs = globalInfo.configs program.version(require("../../package.json").version) program .command("build") .description("Build static files") .action(async () => { globalInfo.status = "building" console.log("\n>> Building static files".yellow) const startBuild = new Date().getTime() await build() const finishBuild = new Date().getTime() console.log( `>> Build finished in`.yellow, `${finishBuild - startBuild} ms`.yellow.bold ) }) program .command("serve [port]") .description("Creates live server and serve static sites") .action(async port => { globalInfo.status = "serving" globalInfo.configs.buildPath = ".debug" await build() await serve(port) }) program .command("create <projectName> [template]") .description("Generates ulka project") .action(createProject) program.parse(process.argv) const exit = () => { if (globalInfo.status === "serving") rmdir(configs.buildPath) process.exit() } process.on("exit", () => { if (globalInfo.status === "serving") rmdir(configs.buildPath) }) process.on("SIGINT", exit) process.on("SIGUSR1", exit) process.on("SIGUSR2", exit) process.on("uncaughtException", exit)
import React from 'react'; import ReactDOM from 'react-dom'; class The_Form extends React.Component{ constructor(props){ super(props) } render(){ return( <form className='form'> <label className='inputs'> <p className='input_title'>Woman's Name:</p> <input type="text" name="womans_name" id='female_name' className='field' /> <img src='/images/again.png' className='autofill_image' onClick={e => this.props.fill_for_me('female_name')}/> </label> <label className='inputs'> <p className='input_title'>Man's Name:</p> <input type="text" name="mans_name" id='male_name' className='field' /> <img src='/images/again.png' className='autofill_image' onClick={e => this.props.fill_for_me('male_name')}/> </label> <label className='inputs'> <p className='input_title'>Adjective:</p> <input type="text" name="adj_one" id='adjective_one' className='field' /> <img src='/images/again.png' className='autofill_image' onClick={e => this.props.fill_for_me('adjective_one')}/> </label> <label className='inputs'> <p className='input_title'>Profession:</p> <input type="text" name="job_one" id='job_one' className='field'/> <img src='/images/again.png' className='autofill_image' onClick={e => this.props.fill_for_me('job_one')}/> </label> <label className='inputs'> <p className='input_title'>Adjective:</p> <input type="text" name="adj_two" id='adjective_two' className='field'/> <img src='/images/again.png' className='autofill_image' onClick={e => this.props.fill_for_me('adjective_two')}/> </label> <label className='inputs'> <p className='input_title'>Nationality/Ethnicity:</p> <input type="text" name="nationality" id='nation' className='field'/> <img src='/images/again.png' className='autofill_image' onClick={e => this.props.fill_for_me('nation')}/> </label> <label className='inputs'> <p className='input_title'>Profession:</p> <input type="text" name="job_two" id='job_two' className='field'/> <img src='/images/again.png' className='autofill_image' onClick={e => this.props.fill_for_me('job_two')}/> </label> <label className='inputs'> <p className='input_title'>Mythical Creature:</p> <input type="text" name="myth" id='myth' className='field'/> <img src='/images/again.png' className='autofill_image' onClick={e => this.props.fill_for_me('myth')}/> </label> <input type="button" value="Generate Plot" className='submit_button' onClick={this.props.make_story}/> <button onClick= {e =>this.props.choice('main')} className='form_back_button'><img src='/images/book_two.png' className='form_again_image' />Home</button> </form> );} } export default The_Form; // <button onClick= {e =>this.props.choice('main')}>Back // if(this.state.mode === 'view') { // return ( // <div> // <p>Text: {this.state.text}</p> // <button onClick={this.handleEdit}> // Edit // </button> // </div> // ); // } else { // return ( // <div> // <p>Text: {this.state.text}</p> // <input // onChange={this.handleChange} // value={this.state.inputText} // /> // <button onClick={this.handleSave}> // Save // </button> // </div> // ); // } // } // }
var SwitchGroup = function(game) { Phaser.Group.call(this, game); this.enableBody = true; this.createMultiple(20, 'switches'); this.setAll('anchor.x', 0.0); this.setAll('anchor.y', 0.0); this.setAll('scale.x', 0.5); this.setAll('scale.y', 0.5); } SwitchGroup.prototype = Object.create(Phaser.Group.prototype); SwitchGroup.prototype.constructor = SwitchGroup; SwitchGroup.prototype.spawn = function(game,x,y) { var switchy = this.getFirstExists(false); switchy.reset(x,y); switchy.body.setSize(64, 64, 0, 0); switchy.body.immovable = true; switchy.frame = 0; switchy.touched = false; } SwitchGroup.prototype.update = function(layer) { // :P } SwitchGroup.prototype.isAllSwitchesPressed = function(layer) { var pressed = true; this.forEachExists(function(switchy){ if(!switchy.touched){ pressed = false; } }); return pressed; } SwitchGroup.prototype.touch = function(switchy) { if(!switchy.touched){ fx.play('button_click'); switchy.frame = 1; switchy.touched = true; } }
const Ticket=require('../models/Ticket') module.exports.list=(req,res)=>{ Ticket.find() .then((tickets)=>{ res.json(tickets) }) .catch((err)=>{ res.json(err) }) } module.exports.add=(req,res)=>{ const body=req.body const ticket=new Ticket(body) ticket.save() .then((tickets)=>{ if(tickets){ res.json(tickets) } else{ res.json({}) } }) .catch((err)=>{ res.json(err) }) } module.exports.show=(req,res)=>{ const id=req.params.id Ticket.findById(id) .then((tickets)=>{ if(tickets){ res.json(tickets) } else { res.json({}) } }) .catch((err)=>{ res.json(err) }) } module.exports.update=(req,res)=>{ const id=req.params.id const body=req.body Ticket.findByIdAndUpdate(id,body,{new:true,runValidators:true}) .then((tickets)=>{ if(tickets){ res.json(tickets) } else { res.json({}) } }) .catch((err)=>{ res.json(err) }) } module.exports.remove=(req,res)=>{ const id=req.params.id Ticket.findByIdAndDelete(id) .then((tickets)=>{ if(tickets){ res.json(tickets) } else { res.json({}) } }) .catch((err)=>{ res.json(err) }) }
kitty.Cookies = { create: function(name, value, days) { var expires = ""; if (days) { var date = days; if (!(date instanceof Date)) { date = new Date(); date.setDate(date.getDate() + (days || -1)); } expires = "expires=" + date.toGMTString(); } var cookie = name + "=" + value + ";expires=" + expires + ";path=/"; document.cookie = cookie; }, read: function(name) { var value = null; var cookies = document.cookie.split(";"); var cookie; var collection = {}; for (var i = cookies.length - 1; i >= 0; i--) { cookie = cookies[i].split("="); if (name === $.trim(cookie[0])) { value = cookie[1]; } } return value; }, remove: function(name) { this.create(name, "", -1); } };
import React, { useContext, useEffect } from "react"; import api from "../../api/index"; import "./Home.scss"; import { useForm } from "react-hook-form"; import ProfileContext from "../../Context/ProfileContext"; import Factory from "../../components/Factory/Factory"; const Home = () => { const { profile, setProfile } = useContext(ProfileContext); const { register, // formState: { errors }, handleSubmit, reset, } = useForm(); const onSubmit = async (formData) => { const activeProfileId = profile._id; const newProfile = await api.clearFactories(activeProfileId); try { for (let i = 0; i < formData.amount; i++) { const newFactory = await api.makeFactory(); console.log("This is a new factory", newFactory); api .updateProfile(activeProfileId, { id: newFactory.data._id, }) .then((data) => { console.log(data); setProfile(data.data); }); } reset(); } catch (error) { console.log("ERROR: ", error); } }; return ( <div className="homeContainer"> <section className="rootNode"> <div className="rootText"> <h1>Root</h1> </div> {profile ? ( <div className="rootFactoryGeneration"> <h3> Generate how many factories? <span> <form className="rootGenerationForm" onSubmit={handleSubmit(onSubmit)} noValidate > <input className="input is-primary" type="number" placeholder="Input a number." {...register("amount", { required: true, pattern: /^[0-9]+$/, })} ></input> <div className="buttonWrapper"> <button type="submit" className="button"> Generate </button> </div> </form> </span> </h3> </div> ) : ( <div className="rootFactoryGeneration"> <h3>Please make/choose a profile.</h3> </div> )} </section> <section className="factoriesContainer"> <div className="factoriesGrid"> {/* {profile ? (profile.factories.map((factory) => { const factoryObject = await api.getFactoryById(factory); console.log("what is this?", factoryObject.data); <Factory factory={factory} /> })) : ""} */} <Factory /> </div> </section> </div> ); }; export default Home;
import Behind from './body_parts/behind'; import Body from './body_parts/body'; import Feet from './body_parts/feet'; import Legs from './body_parts/legs'; import Torso from './body_parts/torso'; import Belt from './body_parts/belt'; import Head from './body_parts/head'; import Hands from './body_parts/hands'; import Weapon from './body_parts/weapon'; import createFrames from '../utils/create_frames'; import constants from '../config/constants'; class Character { constructor(scene, x, y, { behind = null, body = 'human', feet = null, legs = null, torso = null, belt = null, head = null, hands = null, weapon = null, } = {}) { this.scene = scene; this.sprites = this.scene.add.container(x, y); this.scene.physics.add.existing(this.sprites); this.sprites.body.setCircle(32); this.behind = new Behind(this, behind); this.body = new Body(this, body); this.feet = new Feet(this, feet); this.legs = new Legs(this, legs); this.torso = new Torso(this, torso); this.belt = new Belt(this, belt); this.head = new Head(this, head); this.hands = new Hands(this, hands); this.weapon = new Weapon(this, weapon); this.parts = [ this.behind, this.body, this.feet, this.legs, this.torso, this.belt, this.head, this.hands, this.weapon, ]; this.animate('walk', 'down'); } animate(animation, direction, loop = false) { this.parts.forEach(part => part.animate(animation, direction, loop)); } stopAnimation() { this.parts.forEach(part => part.stopAnimation()); } } Character.registerAnimations = (scene) => { const { animations } = scene.cache.json.get('kaidStats'); animations.forEach(([key, framesCount, isMulti]) => { const frameRate = constants.ANIMATION_FRAME_RATE; const repeat = key.startsWith('walk') ? -1 : 0; // isMulti: the animation has 4 directions (up/down/left/right) if (isMulti) { ['up', 'down', 'left', 'right'].forEach((direction) => { const dKey = `${key}/${direction}`; scene.anims.create({ key: dKey, frames: createFrames(dKey, 1, framesCount - 1), frameRate, repeat, }); }); } else { scene.anims.create({ key, frames: createFrames(key, 1, framesCount - 1), frameRate, repeat, }); } }); }; export default Character;