text
stringlengths
7
3.69M
import React from 'react'; import PropTypes from 'prop-types'; import {ImCheckmark} from "react-icons/im"; const Icon = ({item, onClick, showV}) => { return ( <div className='image rounded rounded-circle shadow me-2' onClick={onClick} style={{cursor: 'pointer'}}> <img src={item.image} alt={item.name}/> {showV && <ImCheckmark className='icon w-100 h-100 p-2'/>} </div> ); }; Icon.propTypes = { }; export default Icon;
import map from "./map.json"; import * as PIXI from "pixi.js"; import { useRef, useEffect } from "react"; import { Sprite } from "pixi.js"; import Keyboard from "./keyboard"; const App = () => { const rootRef = useRef(); const app = useRef(); const player = useRef(); const tileTextures = useRef([]); const playerTextures = useRef([]); const kb = useRef(new Keyboard()); const scale = 2; const playerScale = scale * 1.5; const tileOptions = { size: 16, xCount: 6, yCount: 10, }; PIXI.settings.SCALE_MODE = PIXI.SCALE_MODES.NEAREST; useEffect(() => { app.current = new PIXI.Application({ width: 256 * scale, height: 160 * scale, }); app.current.loader.onError.add((...args) => console.error(args)); rootRef.current.appendChild(app.current.view); // add element focusable to trigger keyboard events app.current.view.setAttribute("tabindex", 0); kb.current.watch(app.current.view); drawStage(); return () => { app.current.destroy(app.current.view); }; }, []); const drawStage = () => { app.current.loader .add("tiles", "./assets/tileset.png") .add("character", "./assets/character.png") .load((loader, resource) => { generateWorldTiles(resource); generatePlayerTiles(resource); const bg = new PIXI.Container(); bg.scale.set(scale); for (let y = 0; y < map.height; y++) { for (let x = 0; x < map.width; x++) { const tile = map.tiles[y * map.width + x]; const sprite = new Sprite(tileTextures.current[tile]); sprite.x = x * tileOptions.size; sprite.y = y * tileOptions.size; bg.addChild(sprite); } } player.current = new PIXI.Sprite(playerTextures.current[0]); player.current.scale.set(scale); player.current.x = app.current.renderer.width / 2; player.current.y = app.current.renderer.height / 2; app.current.stage.addChild(bg); app.current.stage.addChild(player.current); app.current.ticker.add((delta) => gameLoop(delta)); }); }; const generatePlayerTiles = (resource) => { const sizeX = 16; const sizeY = 32; for (let i = 0; i < 8; i++) { let x = i % 8; let y = Math.floor(i / 8); const texture = new PIXI.Texture( resource.character.texture, new PIXI.Rectangle(x * sizeX, y * sizeY, sizeX, sizeY) ); playerTextures.current.push(texture); } }; const generateWorldTiles = (resource) => { const { size, xCount, yCount } = tileOptions; for (let i = 0; i < xCount * yCount; i++) { let x = i % xCount; let y = Math.floor(i / xCount); const texture = new PIXI.Texture( resource.tiles.texture, new PIXI.Rectangle(x * size, y * size, size, size) ); tileTextures.current.push(texture); } }; const hasCollided = (worldX, worldY) => { let mapX = Math.floor(worldX / tileOptions.size / scale); let mapY = Math.floor(worldY / tileOptions.size / scale); return map.collision[mapY * map.width + mapX]; }; const character = { x: 0, y: 0, vx: 0, vy: 0 }; const gameLoop = () => { player.current.x = character.x; player.current.y = character.y; // set max falling velocity for player character.vy = Math.min(2 * scale, character.vy + 1); let touchingGound = hasCollided(character.x, character.y + 32 * scale + 1); // console.log(touchingGound); if (character.vy > 0) { for (let i = 0; i < character.vy; i++) { let testX = character.x + 2; let testX2 = character.x + tileOptions.size * scale - 3; let testY = character.y + tileOptions.size * scale * 2; if (hasCollided(testX, testY) || hasCollided(testX2, testY)) { character.vy = 0; break; } character.y = character.y + 1; } } if (character.vy < 0) { character.y += character.vy; } if (character.vx > 0) { character.x = character.vx; } // Jump up if (kb.current.pressed.ArrowUp) { character.vy = -7; } // Move right if (kb.current.pressed.ArrowRight) { character.vx += 3; } if (!touchingGound) { player.current.texture = playerTextures.current[1]; } else { player.current.texture = playerTextures.current[0]; } }; return <div ref={rootRef} />; }; export default App;
/* eslint-disable class-methods-use-this */ import React, { Component } from 'react'; import { Checkbox } from '@material-ui/core'; import InputMaskCnpj from 'react-number-format'; import { Container, Text, Button, Term, Form, Input } from './styles'; class Home extends Component { state = { document: '', verify: '', }; handleChange = e => { this.setState({ document: e.target.value.replace(/[^0-9]+/g, '') }); }; handleCheck = e => { this.setState({ verify: e.target.checked }); }; render() { const { document, verify } = this.state; const If = props => (props.check ? props.children : null); return ( <Container> <Text> <div> <strong>Veja seus boletos DAS na hora com a DicasMEI!</strong> </div> <div> <span> Preencha as informações abaixo e veja todo o histórico de boletos. </span> </div> </Text> <Form onChange={this.handleSubmit}> <InputMaskCnpj name="cnpj" required placeholder="CNPJ" format="##.###.###/####-##" customInput={Input} value={document} onChange={this.handleChange} /> <div> <Checkbox type="checkbox" required value={verify} onChange={this.handleCheck} /> <span> Li e aceito os <Term to="/termodeuso">termos de uso</Term> </span> </div> <If check={document.length === 14}> <If check={verify}> <Button type="button" to={`/boleto/extrato/${document}`}> Iniciar Agora </Button> </If> </If> </Form> </Container> ); } } export default Home;
/** * @author 王集鹄(wangjihu,http://weibo.com/zswang) */ AceCore.addModule("MessageBox", function(sandbox){ /** * 事件集合 */ var events = sandbox.getConfig("Events"); /** * 类库 */ var lib = sandbox.getLib(); /** * 消息列表 */ var messageTree; /** * 登录信息 */ var passportInfo = {}; /** * 获取房间当前状态成功 * @param {Object} data */ function pickSuccess(data) { lib.each(data, function(item) { switch(item.type) { case "passport": passportInfo = item.info; break; case "messageAll": messageTree.loadChilds(item.messages); scrollBottom(); break; case "messageAdd": messageTree.appendChilds(item.messages); scrollBottom(); break; } }); } /** * 滚动到底部 */ function scrollBottom() { var parent = messageTree.parent.parentNode; parent.scrollTop = parent.scrollHeight; } /** * 格式化时间 * @param {Date} time */ function formatTime(time) { time = new Date(time); var timeStr = lib.date.format(time, "HH:mm:ss"); var dateStr = lib.date.format(time, "yyyy-MM-dd"); return lib.date.format(new Date, "yyyy-MM-dd") == dateStr ? timeStr : [dateStr, timeStr].join(" "); } /** * 处理多行文本 * @param {String} text 文本 */ function mutiline(text) { return lib.encodeHTML(text).replace(/\n/g, "<br/>"); } function html2Text(html) { return String(html) .replace(/<br\s*\/>/g, "\n") .replace(/&amp;/g, "&") .replace(/&quot;/g, "\"") .replace(/&lt;/g, "<") .replace(/&gt;/g, ">") .replace(/&nbsp;/g, " "); } return { init: function() { AceUbb.addPlugin('code', function(text){ return String(text).replace(/(\[code\])(.*?)(\[\/code\])/ig, function($0, $1, $2) { return "<pre><code>" + AceHighlight.exportHtml(html2Text($2)).replace(/\[/g, "&#91;").replace(/\[/g, "&#93;") + "</code></pre>"; }); }); AceUbb.addPlugin('color', function(text){ return String(text).replace(/\[(red|orange|yellow|green|blue|indigo|violet|beige|black|brown|gray|navy|silver|tan)\]([\s\S]*?)\[\/\1\]/g, function(all, color, text){ return '<span style="color:' + color + ';">' + text + '</span>'; }); }); AceUbb.addPlugin('weibo', function(text){ var dict = { '[bm做操]': '09/bmzuocao_thumb.gif', '[bm抓狂]': '60/bmzhuakuang_thumb.gif', '[bm中枪]': 'ff/bmzhongqiang_thumb.gif', '[bm震惊]': '63/bmzhenjing_thumb.gif', '[bm赞]': 'c9/bmzan_thumb.gif', '[bm喜悦]': '47/bmxiyue_thumb.gif', '[bm醒悟]': '8f/bmxingwu_thumb.gif', '[bm兴奋]': 'a7/bmxingfen_thumb.gif', '[bm血泪]': '0d/bmxielei_thumb.gif', '[bm挖鼻孔]': 'bd/bmwabikong_thumb.gif', '[bm吐舌头]': '8f/bmtushetou_thumb.gif', '[bm吐槽]': '73/bmtucao_thumb.gif', '[bm投诉]': '04/bmtousu_thumb.gif', '[bm跳绳]': '2a/bmtiaosheng_thumb.gif', '[bm调皮]': 'da/bmtiaopi_thumb.gif', '[bm讨论]': '20/bmtaolun_thumb.gif', '[bm抬腿]': '86/bmtaitui_thumb.gif', '[bm思考]': '0f/bmsikao_thumb.gif', '[bm生气]': '8f/bmshengqi_thumb.gif', '[bm亲吻]': 'a4/bmqinwen_thumb.gif', '[bm庆幸]': '6c/bmqingxing_thumb.gif', '[bm内涵]': '66/bmneihan_thumb.gif', '[bm忙碌]': '18/bmmanglu_thumb.gif', '[bm乱入]': 'a9/bmluanru_thumb.gif', '[bm卖萌]': 'ba/bmluanmeng_thumb.gif', '[bm流泪]': 'd6/bmliulei_thumb.gif', '[bm流口水]': 'a4/bmliukoushui_thumb.gif', '[bm流鼻涕]': '4f/bmliubiti_thumb.gif', '[bm路过]': '75/bmliguo_thumb.gif', '[bm咧嘴]': '3e/bmliezui_thumb.gif', '[bm啦啦队]': '4e/bmlaladui_thumb.gif', '[bm哭诉]': '9b/bmkusu_thumb.gif', '[bm哭泣]': 'a8/bmkuqi_thumb.gif', '[bm苦逼]': 'dc/bmkubi_thumb.gif', '[bm口哨]': '0c/bmkoushao_thumb.gif', '[bm可爱]': '95/bmkeai_thumb.gif', '[bm紧张]': '4c/bmjinzhang_thumb.gif', '[bm惊讶]': '03/bmjingya_thumb.gif', '[bm惊吓]': 'be/bmjingxia_thumb.gif', '[bm焦虑]': '4e/bmjiaolv_thumb.gif', '[bm会心笑]': '7e/bmhuixinxiao_thumb.gif', '[bm坏笑]': 'ec/bmhuaixiao_thumb.gif', '[bm花痴]': '4b/bmhuachi_thumb.gif', '[bm厚脸皮]': '61/bmhoulianpi_thumb.gif', '[bm好吧]': '16/bmhaoba_thumb.gif', '[bm害怕]': '6c/bmhaipa_thumb.gif', '[bm鬼脸]': '15/bmguilian_thumb.gif', '[bm孤独]': 'e4/bmgudu_thumb.gif', '[bm高兴]': '85/bmgaoxing_thumb.gif', '[bm搞怪]': '4b/bmgaoguai_thumb.gif', '[bm干笑]': 'b4/bmganxiao_thumb.gif', '[bm感动]': '34/bmgandong_thumb.gif', '[bm愤懑]': 'fc/bmfenmen_thumb.gif', '[bm反对]': 'b6/bmfandui_thumb.gif', '[bm踱步]': '54/bmduobu_thumb.gif', '[bm顶]': '34/bmding_thumb.gif', '[bm得意]': '7a/bmdeyi_thumb.gif', '[bm得瑟]': '7d/bmdese_thumb.gif', '[bm大笑]': '37/bmdaxiao_thumb.gif', '[bm蛋糕]': 'f8/bmdangao_thumb.gif', '[bm大哭]': 'dc/bmdaku_thumb.gif', '[bm大叫]': '83/bmdajiao_thumb.gif', '[bm吃惊]': 'b0/bmchijing_thumb.gif', '[bm馋]': 'd9/bmchan_thumb.gif', '[bm彩色]': '7e/bmcaise_thumb.gif', '[bm缤纷]': '15/bmbinfen_thumb.gif', '[bm变身]': 'b7/bmbianshen_thumb.gif', '[bm悲催]': '77/bmbeicui_thumb.gif', '[bm暴怒]': '12/bmbaonu_thumb.gif', '[bm熬夜]': 'a4/bmaoye_thumb.gif', '[bm暗爽]': 'bc/bmanshuang_thumb.gif', '[月儿圆]': '3d/lxhyueeryuan_thumb.gif', '[招财]': 'a9/lxhzhaocai_thumb.gif', '[微博三岁啦]': '1e/lxhweibo3yr_thumb.gif', '[复活节]': 'd6/lxhfuhuojie_thumb.gif', '[挤火车]': '09/lxhjihuoche_thumb.gif', '[愚人节]': '21/lxhyurenjie_thumb.gif', '[收藏]': '83/lxhshoucang_thumb.gif', '[喜得金牌]': 'a2/lxhhappygold_thumb.gif', '[夺冠感动]': '69/lxhduoguan_thumb.gif', '[冠军诞生]': '2c/lxhguanjun_thumb.gif', '[传火炬]': 'f2/lxhchuanhuoju_thumb.gif', '[奥运金牌]': '06/lxhgold_thumb.gif', '[奥运银牌]': '43/lxhbronze_thumb.gif', '[奥运铜牌]': 'fd/lxhsilver_thumb.gif', '[德国队加油]': '12/germany_thumb.gif', '[西班牙队加油]': 'be/spain_thumb.gif', '[葡萄牙队加油]': 'f8/portugal_thumb.gif', '[意大利队加油]': '03/italy_thumb.gif', '[耍花灯]': 'be/lxhshuahuadeng_thumb.gif', '[元宵快乐]': '83/lxhyuanxiaohappy_thumb.gif', '[吃汤圆]': '52/lxhchitangyuan_thumb.gif', '[金元宝]': '9b/lxhjinyuanbao_thumb.gif', '[红包拿来]': 'bd/lxhhongbaonalai_thumb.gif', '[福到啦]': 'f4/lxhfudaola_thumb.gif', '[放鞭炮]': 'bd/lxhbianpao_thumb.gif', '[发红包]': '27/lxhhongbao_thumb.gif', '[大红灯笼]': '90/lxhdahongdenglong_thumb.gif', '[拜年了]': '0c/lxhbainianle_thumb.gif', '[龙啸]': 'cd/lxhlongxiao_thumb.gif', '[光棍节]': '5b/lxh1111_thumb.gif', '[蛇年快乐]': '5f/lxhshenian_thumb.gif', '[过年啦]': '94/lxhguonianla_thumb.gif', '[圆蛋快乐]': 'eb/lxhyuandan_thumb.gif', '[发礼物]': '24/lxh_santa_thumb.gif', '[要礼物]': 'd2/lxh_gift_thumb.gif', '[平安果]': '0f/lxh_apple_thumb.gif', '[吓到了]': 'fa/lxhscare_thumb.gif', '[走你]': 'ed/zouni_thumb.gif', '[吐血]': '8c/lxhtuxue_thumb.gif', '[好激动]': 'ae/lxhjidong_thumb.gif', '[没人疼]': '23/lxhlonely_thumb.gif', '[转发]': '02/lxhzhuanfa_thumb.gif', '[笑哈哈]': '32/lxhwahaha_thumb.gif', '[得意地笑]': 'd4/lxhdeyidixiao_thumb.gif', '[噢耶]': '3b/lxhxixi_thumb.gif', '[偷乐]': 'fa/lxhtouxiao_thumb.gif', '[泪流满面]': '64/lxhtongku_thumb.gif', '[巨汗]': 'f6/lxhjuhan_thumb.gif', '[抠鼻屎]': '48/lxhkoubishi_thumb.gif', '[求关注]': 'ac/lxhqiuguanzhu_thumb.gif', '[真V5]': '3a/lxhv5_thumb.gif', '[群体围观]': 'a8/lxhweiguan_thumb.gif', '[hold住]': '05/lxhholdzhu_thumb.gif', '[羞嗒嗒]': 'df/lxhxiudada_thumb.gif', '[非常汗]': '42/lxhpubuhan_thumb.gif', '[许愿]': '87/lxhxuyuan_thumb.gif', '[崩溃]': 'c7/lxhzhuakuang_thumb.gif', '[好囧]': '96/lxhhaojiong_thumb.gif', '[震惊]': 'e7/lxhchijing_thumb.gif', '[别烦我]': '22/lxhbiefanwo_thumb.gif', '[不好意思]': 'b4/lxhbuhaoyisi_thumb.gif', '[纠结]': '1f/lxhjiujie_thumb.gif', '[拍手]': 'e3/lxhguzhang_thumb.gif', '[给劲]': 'a5/lxhgeili_thumb.gif', '[好喜欢]': 'd6/lxhlike_thumb.gif', '[好爱哦]': '74/lxhainio_thumb.gif', '[路过这儿]': 'ac/lxhluguo_thumb.gif', '[悲催]': '43/lxhbeicui_thumb.gif', '[不想上班]': '6b/lxhbuxiangshangban_thumb.gif', '[躁狂症]': 'ca/lxhzaokuangzheng_thumb.gif', '[甩甩手]': 'a6/lxhshuaishuaishou_thumb.gif', '[瞧瞧]': '8b/lxhqiaoqiao_thumb.gif', '[同意]': '14/lxhtongyi_thumb.gif', '[喝多了]': 'a7/lxhheduole_thumb.gif', '[啦啦啦啦]': '3d/lxhlalalala_thumb.gif', '[杰克逊]': 'e5/lxhjiekexun_thumb.gif', '[雷锋]': '7a/lxhleifeng_thumb.gif', '[带感]': 'd2/lxhdaigan_thumb.gif', '[亲一口]': '88/lxhqinyikou_thumb.gif', '[飞个吻]': '8a/lxhblowakiss_thumb.gif', '[加油啊]': '03/lxhjiayou_thumb.gif', '[七夕]': '9a/lxhqixi_thumb.gif', '[困死了]': '00/lxhkunsile_thumb.gif', '[有鸭梨]': '7e/lxhyouyali_thumb.gif', '[右边亮了]': 'ae/lxhliangle_thumb.gif', '[撒花]': 'b3/lxhfangjiala_thumb.gif', '[好棒]': '3e/lxhhaobang_thumb.gif', '[想一想]': 'e9/lxhxiangyixiang_thumb.gif', '[下班]': 'f2/lxhxiaban_thumb.gif', '[最右]': 'c8/lxhzuiyou_thumb.gif', '[丘比特]': '35/lxhqiubite_thumb.gif', '[中箭]': '81/lxhzhongjian_thumb.gif', '[互相膜拜]': '3c/lxhhuxiangmobai_thumb.gif', '[膜拜了]': '52/lxhmobai_thumb.gif', '[放电抛媚]': 'd0/lxhfangdianpaomei_thumb.gif', '[霹雳]': '41/lxhshandian_thumb.gif', '[被电]': 'ed/lxhbeidian_thumb.gif', '[拍砖]': '3b/lxhpaizhuan_thumb.gif', '[互相拍砖]': '5b/lxhhuxiangpaizhuan_thumb.gif', '[采访]': '8b/lxhcaifang_thumb.gif', '[发表言论]': 'f1/lxhfabiaoyanlun_thumb.gif', '[江南style]': '67/gangnamstyle_thumb.gif', '[牛]': '24/lxhniu_thumb.gif', '[玫瑰]': 'f6/lxhrose_thumb.gif', '[赞啊]': '00/lxhzan_thumb.gif', '[推荐]': 'e9/lxhtuijian_thumb.gif', '[放假啦]': '37/lxhfangjiale_thumb.gif', '[萌翻]': '99/lxhmengfan_thumb.gif', '[吃货]': 'ba/lxhgreedy_thumb.gif', '[大南瓜]': '4d/lxhpumpkin_thumb.gif', '[赶火车]': 'a2/lxhganhuoche_thumb.gif', '[立志青年]': 'f9/lxhlizhiqingnian_thumb.gif', '[得瑟]': 'ca/lxhdese_thumb.gif', '[草泥马]': '7a/shenshou_thumb.gif', '[神马]': '60/horse2_thumb.gif', '[浮云]': 'bc/fuyun_thumb.gif', '[给力]': 'c9/geili_thumb.gif', '[围观]': 'f2/wg_thumb.gif', '[威武]': '70/vw_thumb.gif', '[熊猫]': '6e/panda_thumb.gif', '[兔子]': '81/rabbit_thumb.gif', '[奥特曼]': 'bc/otm_thumb.gif', '[囧]': '15/j_thumb.gif', '[互粉]': '89/hufen_thumb.gif', '[礼物]': 'c4/liwu_thumb.gif', '[呵呵]': 'ac/smilea_thumb.gif', '[嘻嘻]': '0b/tootha_thumb.gif', '[哈哈]': '6a/laugh.gif', '[可爱]': '14/tza_thumb.gif', '[可怜]': 'af/kl_thumb.gif', '[挖鼻屎]': 'a0/kbsa_thumb.gif', '[吃惊]': 'f4/cj_thumb.gif', '[害羞]': '6e/shamea_thumb.gif', '[挤眼]': 'c3/zy_thumb.gif', '[闭嘴]': '29/bz_thumb.gif', '[鄙视]': '71/bs2_thumb.gif', '[爱你]': '6d/lovea_thumb.gif', '[泪]': '9d/sada_thumb.gif', '[偷笑]': '19/heia_thumb.gif', '[亲亲]': '8f/qq_thumb.gif', '[生病]': 'b6/sb_thumb.gif', '[太开心]': '58/mb_thumb.gif', '[懒得理你]': '17/ldln_thumb.gif', '[右哼哼]': '98/yhh_thumb.gif', '[左哼哼]': '6d/zhh_thumb.gif', '[嘘]': 'a6/x_thumb.gif', '[衰]': 'af/cry.gif', '[委屈]': '73/wq_thumb.gif', '[吐]': '9e/t_thumb.gif', '[打哈欠]': 'f3/k_thumb.gif', '[抱抱]': '27/bba_thumb.gif', '[怒]': '7c/angrya_thumb.gif', '[疑问]': '5c/yw_thumb.gif', '[馋嘴]': 'a5/cza_thumb.gif', '[拜拜]': '70/88_thumb.gif', '[思考]': 'e9/sk_thumb.gif', '[汗]': '24/sweata_thumb.gif', '[困]': '7f/sleepya_thumb.gif', '[睡觉]': '6b/sleepa_thumb.gif', '[钱]': '90/money_thumb.gif', '[失望]': '0c/sw_thumb.gif', '[酷]': '40/cool_thumb.gif', '[花心]': '8c/hsa_thumb.gif', '[哼]': '49/hatea_thumb.gif', '[鼓掌]': '36/gza_thumb.gif', '[晕]': 'd9/dizzya_thumb.gif', '[悲伤]': '1a/bs_thumb.gif', '[抓狂]': '62/crazya_thumb.gif', '[黑线]': '91/h_thumb.gif', '[阴险]': '6d/yx_thumb.gif', '[怒骂]': '89/nm_thumb.gif', '[心]': '40/hearta_thumb.gif', '[伤心]': 'ea/unheart.gif', '[猪头]': '58/pig.gif', '[ok]': 'd6/ok_thumb.gif', '[耶]': 'd9/ye_thumb.gif', '[good]': 'd8/good_thumb.gif', '[不要]': 'c7/no_thumb.gif', '[赞]': 'd0/z2_thumb.gif', '[来]': '40/come_thumb.gif', '[弱]': 'd8/sad_thumb.gif', '[蜡烛]': '91/lazu_thumb.gif', '[钟]': 'd3/clock_thumb.gif', '[话筒]': '1b/m_thumb.gif', '[蛋糕]': '6a/cake.gif', '[挤眼]': 'c3/zy_thumb.gif', '[亲亲]': '8f/qq_thumb.gif', '[怒骂]': '89/nm_thumb.gif', '[太开心]': '58/mb_thumb.gif', '[懒得理你]': '17/ldln_thumb.gif', '[打哈欠]': 'f3/k_thumb.gif', '[生病]': 'b6/sb_thumb.gif', '[书呆子]': '61/sdz_thumb.gif', '[失望]': '0c/sw_thumb.gif', '[可怜]': 'af/kl_thumb.gif', '[黑线]': '91/h_thumb.gif', '[吐]': '9e/t_thumb.gif', '[委屈]': '73/wq_thumb.gif', '[思考]': 'e9/sk_thumb.gif', '[哈哈]': '6a/laugh.gif', '[嘘]': 'a6/x_thumb.gif', '[右哼哼]': '98/yhh_thumb.gif', '[左哼哼]': '6d/zhh_thumb.gif', '[疑问]': '5c/yw_thumb.gif', '[阴险]': '6d/yx_thumb.gif', '[顶]': '91/d_thumb.gif', '[钱]': '90/money_thumb.gif', '[悲伤]': '1a/bs_thumb.gif', '[鄙视]': '71/bs2_thumb.gif', '[拜拜]': '70/88_thumb.gif', '[吃惊]': 'f4/cj_thumb.gif', '[闭嘴]': '29/bz_thumb.gif', '[衰]': 'af/cry.gif', '[愤怒]': 'bd/fn_thumb.gif', '[感冒]': 'a0/gm_thumb.gif', '[酷]': '40/cool_thumb.gif', '[来]': '40/come_thumb.gif', '[good]': 'd8/good_thumb.gif', '[haha]': '13/ha_thumb.gif', '[不要]': 'c7/no_thumb.gif', '[ok]': 'd6/ok_thumb.gif', '[拳头]': 'cc/o_thumb.gif', '[弱]': 'd8/sad_thumb.gif', '[握手]': '0c/ws_thumb.gif', '[赞]': 'd0/z2_thumb.gif', '[耶]': 'd9/ye_thumb.gif', '[最差]': '3e/bad_thumb.gif', '[打哈气]': 'f3/k_thumb.gif', '[可爱]': '14/tza_thumb.gif', '[嘻嘻]': '0b/tootha_thumb.gif', '[汗]': '24/sweata_thumb.gif', '[呵呵]': 'ac/smilea_thumb.gif', '[困]': '7f/sleepya_thumb.gif', '[睡觉]': '6b/sleepa_thumb.gif', '[害羞]': '6e/shamea_thumb.gif', '[泪]': '9d/sada_thumb.gif', '[爱你]': '6d/lovea_thumb.gif', '[挖鼻屎]': 'a0/kbsa_thumb.gif', '[花心]': '8c/hsa_thumb.gif', '[偷笑]': '19/heia_thumb.gif', '[心]': '40/hearta_thumb.gif', '[哼]': '49/hatea_thumb.gif', '[鼓掌]': '36/gza_thumb.gif', '[晕]': 'd9/dizzya_thumb.gif', '[馋嘴]': 'a5/cza_thumb.gif', '[抓狂]': '62/crazya_thumb.gif', '[抱抱]': '27/bba_thumb.gif', '[怒]': '7c/angrya_thumb.gif', '[右抱抱]': '0d/right_thumb.gif', '[左抱抱]': '54/left_thumb.gif'}; return String(text).replace(/\[([^\]]*)\]/g, function(all){ return dict[all] ? '<img width="22" height="22" src="http://img.t.sinajs.cn/t4/appstyle/expression/ext/normal/' + dict[all] + '" alt="' + all + '">' : all; }); }); messageTree = AceTree.create({ parent: lib.g("messageListTemplate").parentNode, oninit: function(tree){ tree.eventHandler = AceEvent.on(tree.parent, function(command, element, e){ var node = tree.node4target(element); node && tree.oncommand(command, node, e); }); }, onreader: function(node){ return AceTemplate.format('messageListTemplate', node.data, { node: node, formatTime: formatTime, mutiline: mutiline, markdown: function(text){ return markdown.toHTML(text); }, ubb: function(text){ return AceUbb.exportHtml(text); } }); }, oncommand: function(command, node, e){ switch (command) { case "letter": sandbox.fire(events.letterDialog, { nick: node.data.nick, to: node.data.from }); break; } }, statusClasses: /^(focus|hover|select|expand|self)$/, oncreated: function(node) { node.setStatus("self", node.data.from == passportInfo.id, true); } }); sandbox.on(events.pickSuccess, pickSuccess); } }; });
// LinkSpec var clickData = [ '_trackEvent', 'Links', 'Click', '{"location":{"hostname":"www.lib.umn.edu", "pathname":"/"},"mouse":{"pageX":200, "pageY":400}, "href":"/services/borrowing","text":"Borrowing Privileges","parents":"jasmine-fixtures|header-nav|primary-nav|services-nav","date":1396971582012}' ]; describe("Links", function() { describe("when a link has been clicked", function() { beforeEach(function() { loadFixtures('links.html'); }); it("should capture event", function() { var spyEvent = spyOnEvent($('a#borrowing'), 'click'); $('a#borrowing').click(function(event){ event.preventDefault(); expect(spyEvent).toHaveBeenTriggered(); }); }); it("should push event to GA", function(){ // ga should be a function expect(typeof ga === 'function').toBe(true); // click event should populate $linkData var $linkData = GaEventTrack.LinkClick($('a#borrowing').click()); expect($linkData).not.toEqual([]); }); }); describe("link data", function() { beforeEach(function() { loadFixtures('links.html'); var $linkData = GaEventTrack.LinkClick($('a#borrowing').click()); // Parse JSON data labelHash = JSON.stringify($linkData); clickHash = JSON.parse(clickData[3]); }); it("should capture label data", function(){ // Parse JSON data var $labelHash = JSON.parse(labelHash); var $clickHash = JSON.parse(clickData[3]); // Should have same array length expect($labelHash.length).toEqual($clickHash.length); // Are Hash keys the same? expect(Object.keys($labelHash)).toEqual(Object.keys($clickHash)); }); it("should match example data", function(){ labelHash = JSON.parse(labelHash); delete(labelHash['date']); // never the same delete(labelHash['location']); // hash delete(labelHash['mouse']); // hash $.each(labelHash, function(key,value){ expect(labelHash[key]).toContain(clickHash[key]); }); }); }); });
function solve(firstLetter, secondLetter){ let firstCharToInt = firstLetter.charCodeAt(0); let secondCharToInt = secondLetter.charCodeAt(0); let biggerValue = Math.max(firstCharToInt, secondCharToInt); let smallerValue = Math.min(firstCharToInt, secondCharToInt); let result = getResultStringWithCharacters(biggerValue, smallerValue); console.log(result); function getResultStringWithCharacters(biggerValue, smallerValue){ let result = ''; for (let i = smallerValue + 1; i < biggerValue; i++) { result += String.fromCharCode(i) + ' '; } return result; } } solve('#', ':');
import React from 'react'; import Paper from "@material-ui/core/Paper"; import {makeStyles} from "@material-ui/core/styles"; import TableContainer from "@material-ui/core/TableContainer"; import Table from "@material-ui/core/Table"; import TableHead from "@material-ui/core/TableHead"; import TableRow from "@material-ui/core/TableRow"; import TableCell from "@material-ui/core/TableCell"; import TableBody from "@material-ui/core/TableBody"; import Typography from "@material-ui/core/Typography"; import Card from "@material-ui/core/Card"; import CardActionArea from "@material-ui/core/CardActionArea"; import CardContent from "@material-ui/core/CardContent"; import {useRecoilValue} from "recoil"; import {userState} from "../App"; const useStyles = makeStyles((theme) => ({ card: { marginTop: theme.spacing(2), }, title: { margin: theme.spacing(2, 2), backgroundColor: theme.palette.primary.main, }, results: { marginLeft: theme.spacing(2), color: theme.palette.info.contrastText } })); const Results = () => { const classes = useStyles(); const user = useRecoilValue(userState); return ( <Card className={classes.card}> <CardActionArea> <div className={classes.title}> <Typography variant="h6" className={classes.results}> {'Results'} </Typography> </div> <CardContent> <TableContainer component={Paper}> <Table className={classes.table} aria-label="simple table"> <TableHead> <TableRow> <TableCell align="center">Image</TableCell> <TableCell align="center">Img Processed</TableCell> <TableCell align="center">Prediction</TableCell> <TableCell align="center">Accuracy</TableCell> </TableRow> </TableHead> <TableBody> {user.results.slice(0, 5).map((row) => ( <TableRow key={row.image}> <TableCell align="center"><img width="28" height="28" src={row.image} alt={"saved"}/></TableCell> <TableCell align="center"><img width="28" height="28" src={row.imgProcessed} alt={"processed"}/></TableCell> <TableCell align="center">{row.prediction}</TableCell> <TableCell align="center">{row.accuracy}%</TableCell> </TableRow> ))} </TableBody> </Table> </TableContainer> </CardContent> </CardActionArea> </Card> ); }; export default Results;
'use strict'; var noopLogger = require('./noop-logger'); var levels = Object.keys(noopLogger); module.exports = function assertLogger(logger) { levels.forEach(function(level) { if (typeof logger[level] !== 'function') { throw new TypeError( 'Invalid logger passed, must be compatible with bunyan log levels' + ' (' + levels.join(', ') + ') - missing `' + level + '()`' ); } }); return logger; };
(function(_, $) { function orderSideBar() { var header = $('.tygh-top-panel'), sideBar = $('.cp-order-info__sidebar'), heightHeader = header.height(), positionBlock = sideBar.position().left; sideBar.css({'left': positionBlock}); if ($("div").is(".cp-order-info__sidebar")) { $(window).scroll(function(){ if ($(document).scrollTop() > (heightHeader + 150)) { sideBar.css({ 'position': 'fixed', 'top': '-140px' }); }else{ sideBar.css({ 'position': 'static', }); } }); $(window).resize(function() { positionBlock = sideBar.position().left; sideBar.css({'left': positionBlock}); }); } } function scrollInit() { $(".cp-order-info__product-list").mCustomScrollbar({ theme:"dark-3", alwaysShowScrollbar: 0 }); } scrollInit(); $(document).ready(function() { orderSideBar(); }); }(Tygh, Tygh.$));
'use strict' const path = require('path') const queue = require(path.join(__dirname, '../queue')) const action = {} /** * Require user * @type {boolean} */ action.requireUser = true /** * Execute the action * @param {WebSocketUser} user * @param {*} message * @param {function} callback */ action.execute = function (user, message, callback) { queue.transferNext() } module.exports = action
/* Liste les branches d'un projet */ function listBranch(idProject,idCreator, idUser){ var url = "/api/git/"+ idUser + "/" + idCreator + "/" + idProject + "/branches"; ApiRequest('GET',url,"",function(json){ console.log("Liste des branch de " + idProject + ": " + JSON.stringify(json)); $('#selectBranch').empty(); $.each(json["branches"], function(index, element) { $('#selectBranch').append('<option project="'+ idProject+'" creator="'+ idCreator +'">' + element.name.substr(element.name.lastIndexOf('/') + 1) + '</option>'); }); }); } /* Liste des commits */ function listCommit(idProject,idCreator, idUser,branch){ var url = "/api/git/" + idUser + "/" + idCreator + "/" + idProject + "/listCommit/" + branch; ApiRequest('GET',url,"",function(json){ console.log("Liste des commits de " + branch + ": " + JSON.stringify(json)); $('#listCommit').empty(); $.each(json["commits"], function(index, element) { $('#listCommit').append( '<li class="list-group-item ligneCommit" creator="'+ idCreator + '" project="'+ idProject+'" revision="' + element.id + '" branch="' + branch + '"> \ <span class="open-revision"> Révision: ' + element.id + '</span> \ <span> Date: ' + element.date + '</span> \ <span> Message: ' + element.message + '</span> \ <span> Utilisateur: ' + element.user + '</span> \ <span> Email: ' + element.email + '</span> \ <button type="button" id="diffButton" class="btn btn-primary btn-sm" creator="'+ idCreator + '" project="'+ idProject+'" revision="' + element.id + '" branch="' + branch + '">DIFF</button>\ </li>'); }); }); } /* Récupère le contenu d'un fichier */ function getFile(idProject,idCreator, idUser,revision,path, temporary){ if(temporary == "true"){ Cookies.set('temporary', "true"); }else{ Cookies.set('temporary', "false"); } var url = "/api/git/"+ idUser+ "/"+ idCreator + "/" + idProject + "/" + revision +"?path=" + path; ApiRequest('GET',url,"",function(json){ console.log("Contenu du fichier " + revision + ": " + JSON.stringify(json)); setEditeur(json["content"]); Cookies.set('path',path); $("#file-breadcrumb").text(path); }); } /* Récupère l'arborescence du commit courant */ function getArborescence(idProject,idCreator, idUser,revision){ var url = "/api/git/"+ idUser +"/"+ idCreator + "/" + idProject + "/tree/" + revision+"/true"; ApiRequest('GET',url,"",function(json){ console.log("Arborescence de " + revision + ": " + JSON.stringify(json)); $("#arborescenceFichier").tree('destroy'); $('#arborescenceFichier').tree({ data: json.root, onCreateLi: function(node, $li) { $li.find('.jqtree-title').attr({"path":node.path.replace("root/",""),"revision":revision, "temporary":node.temporary}); } }); // Handle a click on the edit link $('#arborescenceFichier').on('dblclick', function(e) { // Get the id from the 'node-id' data property alert($(e.target).attr("path"),$(e.target).attr("revision")); getFile(idProject,idCreator,idUser,$(e.target).attr("revision"),$(e.target).attr("path"),$(e.target).attr("temporary")) } ); }); } function createFile(idProject,idCreator, idUser,path,branch){ var url = "/api/git/"+ idUser+ "/"+ idCreator + "/" + idProject + "/create/file/" + branch +"?path=" + path; ApiRequest('GET',url,"",function(json){ console.log("Fichier: " + JSON.stringify(json)); getArborescence(Cookies.get('project'),Cookies.get('creator'),Cookies.get('idUser'),Cookies.get('revision')); }); } /** Créer un commit */ function makeCommit(idProject,idCreator, idUser,branch,message){ var url = "/api/git/"+ idUser+ "/"+ idCreator + "/" + idProject + "/makeCommit/" + branch +"?message=" + message; ApiRequest('POST',url,"",function(json){ console.log("Commit: " + JSON.stringify(json)); Cookies.set('revision', json["new_commit_id"]); refreshPage(); }); } /** Créer une branche */ function createBranch(branch, idProject, idCreator, idUser){ var url = "/api/git/"+ idUser +"/"+ idCreator + "/" + idProject + "/create/branch/" + branch; ApiRequest('POST',url,"",function(json){ console.log("Branche crée: " + JSON.stringify(json)); BootstrapDialog.show({ title: 'Branches', message: 'La branche ' + branch + ' a été créee.', type: BootstrapDialog.TYPE_SUCCESS, closable: true, draggable: true }); refreshPage(); }); } function changeBranch(idProject, idCreator, idUser, branch){ // TODO test s'il y a des temporary file en cours var url = "/api/git/"+ idUser +"/" + idCreator + "/" + idProject + "/listCommit/" + branch; ApiRequest('GET',url,"",function(json){ console.log("Dernier commit de "+branch+ ": " + json["commits"][0].id); Cookies.set('project', idProject); Cookies.set('branch', branch); Cookies.set('revision', json["commits"][0].id); refreshPage(); }); } function diffCommit(idProject,idCreator,idUser,revision){ var url = "/api/git/"+ idUser +"/" + idCreator + "/" + idProject + "/showCommit/" + revision; ApiRequest('GET',url,"",function(json){ console.log("Diff commit " + JSON.stringify(json)); var test = Diff2Html.getPrettyHtml(json.result, { // the format of the input data: 'diff' or 'json', default is 'diff' inputFormat: 'diff', // the format of the output data: 'line-by-line' or 'side-by-side' outputFormat: 'line-by-line', // show a file list before the diff: true or false, showFiles: false }); $("#divDiff").empty().append(test); }); } function getArchive(idProject,idCreator,idUser,branch){ var url = "/api/git/"+ idUser +"/" + idCreator + "/" + idProject + "/archive/" + branch; ApiRequest('GET',url,"",function(json){ console.log("Get archive " + JSON.stringify(json)); var fileUrl = "/api/zipFiles/" + json["file"]; window.open(fileUrl, '_blank'); }); }
/** * Created by Anthony M Bonafide on 8/22/2016. */ import React from 'react' class CommentBox extends React.Component{ constructor(props) { super(props); this._onchange = this.onchange.bind(this); } componentWillMount() { this.setState({ data: {}, validation: { errors: [] } }); } render(){ return( <textarea className={`${this.state.validation.errors.length > 0 ? 'error': ''}`} placeholder="Enter Comment Here"/> ); } /** * * @param {Event} event javascript onChange event object */ onchange(event){ this._update(this._validateName(event.target.value)); } /** * * @param newValue event to generate new state from * @returns {String} copy of an updated next state * @private */ _validateName(newValue){ if(newValue.length < 3){ return Object.assign({}, this.state, {validation : {errors: this.state.validation.errors.concat('MIN') }}); } return Object.assign({},this.state,{validation: {errors:[]}}); } /** * * @param state the state to be used to update component * @private */ _update(state){ this.setState(Object.assign({}, state)); } } export default CommentBox;
import randomString from './randomString'; import pathname from './pathname'; import Notification from './notification'; import format from './format'; import defaultIcon from './defaultIcon'; import momentToString from './momentToString'; import delay from './delay'; export { // 随机字符串 randomString, // 获取path pathname, // 信息提示 Notification, // 时间戳转年月日 时分秒 format, // 默认图片 图片加载错误 defaultIcon, // moment对象转年月日 时分秒 momentToString, // 延迟函数 避免重复触发 delay, }
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.login = void 0; const mysql_1 = require("../db/mysql"); const cryp_1 = require("../utils/cryp"); const login = (username, password) => { // 输入用户名为:zhangsan'-- 后面有一个空格,会成功登入 /* * 输入用户名为:zhangsan'-- 后面有一个空格,会成功登入 * 输入 zhangsan';delete from users;-- ,非常危险 * */ username = (0, mysql_1.escape)(username); // 生成加密密码 password = (0, cryp_1.getPassword)(password !== null && password !== void 0 ? password : ""); password = (0, mysql_1.escape)(password); // 用 escape 函数包裹,在 sql 中可以省略 '' const sql = ` select username, realname from users where username=${username} and password=${password}; `; console.log('sql is: ', sql); return (0, mysql_1.exec)(sql).then(userInfoList => { var _a; return (_a = userInfoList[0]) !== null && _a !== void 0 ? _a : {}; }); }; exports.login = login;
import { FETCH_FLOW, FETCH_FLOW_SUCCESS, FETCH_FLOW_ERROR, ADD_FLOW, ADD_FLOW_SUCCESS, ADD_FLOW_ERROR, UPDATE_FLOW, UPDATE_FLOW_SUCCESS, UPDATE_FLOW_ERROR, DELETE_FLOW, DELETE_FLOW_SUCCESS, DELETE_FLOW_ERROR } from './actionTypes'; import { Auth } from 'aws-amplify'; import { notification } from 'antd'; import environment from "../environment"; const FLOW_API_URL = environment.api.FLOWS_ENDPOINT; /* * FETCH FLOW ACTIONS */ export function fetchFlows() { return async (dispatch) => { dispatch(fetchFlowRequest()) const headers = await getHeaders(); return fetch(FLOW_API_URL, { method: 'GET', headers: headers }) .then((response) => response.json()) .then((json) => { dispatch(fetchFlowSuccess(json)); }) .catch((error) => dispatch(fetchFlowError(error))); }; } function fetchFlowRequest() { return { type: FETCH_FLOW }; } export function fetchFlowSuccess(data) { return { type: FETCH_FLOW_SUCCESS, data: data }; } export function fetchFlowError(error) { return { type: FETCH_FLOW_ERROR, error: error }; } /* * ADD FLOW ACTIONS */ export function addFlow(flow) { return async (dispatch) => { dispatch(addFlowRequest()) const headers = await getHeaders(); return fetch(FLOW_API_URL, { method: 'POST', headers: headers, body: JSON.stringify(flow) }) .then((response) => response.json()) .then((json) => dispatch(addFlowSuccess(json))) .catch((error) => dispatch(addFlowError(error + ': Could not add flow. '))); }; } function addFlowRequest() { return { type: ADD_FLOW }; } export function addFlowSuccess(data) { notification.success({ "message": "Flow added!" }); return { type: ADD_FLOW_SUCCESS, data: data }; } export function addFlowError(error) { notification.error({ "message": "Uhoh :(", "description": "We couldn't add the flow. The api might be under attack 👾" }); return { type: ADD_FLOW_ERROR, error: error }; } /* * UPDATE FLOW ACTIONS */ export function updateFlow(flow) { return async (dispatch) => { dispatch(updateFlowRequest()) const headers = await getHeaders(); return fetch(FLOW_API_URL + '/' + flow.id, { method: 'PUT', headers: headers, body: JSON.stringify(flow) }) .then((response) => response.json()) .then((json) => dispatch(updateFlowSuccess(json))) .catch((error) => updateFlowError(error + ': Could not update flow. ')); }; } function updateFlowRequest() { return { type: UPDATE_FLOW }; } export function updateFlowSuccess(data) { (data.flowStatus === "COMPLETED") ? notification.success({ "message": "Flow completed!", "description": "Congrats! We've stored your work if you ever want to review it 🎉" }) : notification.info({ "message": "Flow updated!", "description": "Flow: " + data.title + " has been updated." }); return { type: UPDATE_FLOW_SUCCESS, data: data }; } export function updateFlowError(error) { notification.error({ "message": "Uhoh :(", "description": "We couldn't update the flow. The api might be under attack 👾" }); return { type: UPDATE_FLOW_ERROR, error: error }; } /* * DELETE FLOW ACTIONS */ export function deleteFlow(id) { return async (dispatch) => { dispatch(deleteFlowRequest()); const headers = await getHeaders(); return fetch(FLOW_API_URL + '/' + id, { method: 'DELETE', headers: headers, }) .then((response) => { response.status === 200 ? dispatch(deleteFlowSuccess(id)) : dispatch(deleteFlowError(response.status + ': Could not delete flow. ')) }) .catch((error) => dispatch(deleteFlowError(error))); }; } function deleteFlowRequest() { return { type: DELETE_FLOW }; } export function deleteFlowSuccess(id) { notification.success({ "message": "Flow deleted!", }); return { type: DELETE_FLOW_SUCCESS, data: id }; } export function deleteFlowError(error) { notification.error({ "message": "Uhoh :(", "description": "We couldn't delete the flow. The api might be under attack 👾" }); return { type: DELETE_FLOW_ERROR, error: error }; } async function getHeaders() { const headers = new Headers(); const token = await getIdToken(); headers.append('Authorization', 'Bearer ' + token); headers.append('Content-Type', 'application/json'); headers.append('Accept', 'application/json, text/plain, */*'); return headers; } async function getIdToken() { const session = await Auth.currentSession(); return session.getIdToken().getJwtToken(); }
// Functions for merkling const sha3 = require('solidity-sha3').default; function buildMerkleTree(nodes, layers=[]) { layers.push(nodes); if (nodes.length < 2) { return layers; } let newNodes = []; for (let i = 0; i < nodes.length - 1; i += 2) { newNodes.push(hash(nodes[i], nodes[i+1])); } return buildMerkleTree(newNodes, layers); } exports.buildMerkleTree = buildMerkleTree; exports.getMerkleRoot = function(leaves) { const tree = buildMerkleTree(leaves); return tree[tree.length - 1][0]; } function hash(left, right) { return sha3(`0x${left.slice(2)}${right.slice(2)}`); }
import { connect } from 'react-redux' import { select, selectAll, remove, editComment } from '../actions/list' import * as List from '../components/List' const connector = connect( state => ({ list: state.check.list.get('data'), hasSelected: state.check.list.get('hasSelected'), allSelected: state.check.list.get('allSelected'), }), dispatch => ({ onSelect: row => dispatch(select(row)), onSelectAll: () => dispatch(selectAll()), onRemove: () => dispatch(remove()), onEditComment: () => dispatch(editComment()), }), ) export const Desktop = connector(List.Desktop) export const Tablet = connector(List.Tablet) export const Mobile = connector(List.Mobile)
import React, { Component } from 'react'; import axios from 'axios'; import Link from 'react-router-dom/Link'; //引入wow import {WOW} from 'wowjs'; import TeamStyle from './Team.css' import inTu from './img/inTu.png' import tiTu from './img/tiTu.png' /* 各种背景及点缀星球浮动元素 */ class EmbellishLists extends Component{ render(){ let showsBall = []; let showsBJ = []; for (let i = 0; i < 13; i++){ showsBall.push(<EmbellishListsBall key={i} EmqClass={TeamStyle.posBall}/>) } for(let i = 0 ; i< 3;i++){ showsBJ.push(<EmbellishListsBJ key={i} EmbClass={TeamStyle.posBJ}/>) } return ( <div className={TeamStyle.ControlF}> {/* 虚线及阴影背景 */} {showsBJ} {/* 球球背景及特效 */} <div className={`${TeamStyle.BallF}`}> {showsBall} </div> </div> ) } } class EmbellishListsBJ extends Component{ render(){ return ( <div className={this.props.EmbClass}> </div> ) } } /* 球球背景及特效 */ class EmbellishListsBall extends Component{ render(){ return ( <div className={this.props.EmqClass}> </div> ) } } class Embellish extends Component{ render(){ return ( <div> <EmbellishLists /> </div> ) } } /* 产品列表展示区域 */ class ProductLists extends Component{ LinkHref(linkF){ window.open(linkF) } render(){ return ( <li className={TeamStyle.teamListClass}> <h3 className="wow flipInX" data-wow-duration="1s" data-wow-delay="0.2s" data-wow-offset="10" data-wow-iteration="1"></h3> <p className="wow fadeInUp" data-wow-duration="1s" data-wow-delay="0.2s" data-wow-offset="10" data-wow-iteration="1">{this.props.item.teamListName}</p> <h4 className="wow fadeInUp" data-wow-duration="1s" data-wow-delay="0.2s" data-wow-offset="10" data-wow-iteration="1">{this.props.item.teamListPosition}</h4> <h5 className="wow fadeInUp" data-wow-duration="1s" data-wow-delay="0.2s" data-wow-offset="10" data-wow-iteration="1"><img onClick={this.LinkHref.bind(this,this.props.item.LinkteamList)} src={this.props.item.teamListImg1} alt=""/><img onClick={this.LinkHref.bind(this,this.props.item.LinkteamList)} src={this.props.item.teamListImg2} alt=""/></h5> <h6 className="wow fadeInUp" data-wow-duration="1s" data-wow-delay="0.2s" data-wow-offset="10" data-wow-iteration="1">{this.props.item.teamListCon}</h6> </li> ) } } /* 加入JoinEgretia */ class JoinEgretia extends Component{ LinkHref(linkF){ window.open(linkF) } render(){ const Lang = window.Intl; return ( <div className={`${TeamStyle.JoinEgretia} wow fadeInUp`} data-wow-duration="1s" data-wow-delay="0.2s" data-wow-offset="10" data-wow-iteration="1"> <h3>{Lang.get("Team_JoinEgretia")}</h3> <p onClick={this.LinkHref.bind(this,Lang.get("LinkTeam_recruit"))}>{Lang.get("Team_recruit")}</p> </div> ) } } class TeamRoot extends Component { render() { const Lang = window.Intl; const ProductListsJson = [ { "teamListName" : Lang.get("Team_name"), "teamListPosition" : Lang.get("Team_position"), "teamListImg1" : inTu, "teamListImg2" : tiTu, "teamListCon" : Lang.get("Team_content"), "LinkteamList" : Lang.get("LinkTeam_in1"), }, { "teamListName" : Lang.get("Team_name1"), "teamListPosition" : Lang.get("Team_position1"), "teamListImg1" : inTu, "teamListImg2" : tiTu, "teamListCon" : Lang.get("Team_content1"), "LinkteamList" : Lang.get("LinkTeam_in2"), }, { "teamListName" : Lang.get("Team_name2"), "teamListPosition" : Lang.get("Team_position"), "teamListImg1" : inTu, "teamListImg2" : tiTu, "teamListCon" : Lang.get("Team_content2"), "LinkteamList" : Lang.get("LinkTeam_in3"), }, { "teamListName" : Lang.get("Team_name3"), "teamListPosition" : Lang.get("Team_position"), "teamListImg1" : inTu, "teamListImg2" : tiTu, "teamListCon" : Lang.get("Team_content3"), "LinkteamList" : Lang.get("LinkTeam_in4"), }, { "teamListName" : Lang.get("Team_name4"), "teamListPosition" : Lang.get("Team_position"), "teamListImg1" : inTu, "teamListImg2" : tiTu, "teamListCon" : Lang.get("Team_content4"), "LinkteamList" : Lang.get("LinkTeam_in5"), } ] /* 顾问JSON列表 */ const AdviserListsJson = [ { "teamListName" : Lang.get("Team_name5"), "teamListPosition" : Lang.get("Team_position"), "teamListImg1" : inTu, "teamListImg2" : tiTu, "teamListCon" : Lang.get("Team_content5"), }, { "teamListName" : Lang.get("Team_name6"), "teamListPosition" : Lang.get("Team_position"), "teamListImg1" : inTu, "teamListImg2" : tiTu, "teamListCon" : Lang.get("Team_content6"), }, { "teamListName" : Lang.get("Team_name7"), "teamListPosition" : Lang.get("Team_position"), "teamListImg1" : inTu, "teamListImg2" : tiTu, "teamListCon" : Lang.get("Team_content7"), }, { "teamListName" : Lang.get("Team_name8"), "teamListPosition" : Lang.get("Team_position"), "teamListImg1" : inTu, "teamListImg2" : tiTu, "teamListCon" : Lang.get("Team_content8"), } ] return ( <div> <div className={TeamStyle.bannerBJ}> </div> <div className= {`contain`}> <div className={TeamStyle.teamList}> <h3>{Lang.get("Team_tit1")}</h3> <ul> {ProductListsJson.map((item , index) => <ProductLists key={index} item={item}/> )} </ul> <h3>{Lang.get("Team_tit2")}</h3> <ul> {AdviserListsJson.map((item , index) => <ProductLists key={index} item={item}/> )} </ul> </div> {/* 加入Egretia 先期隐藏 */} {/* <JoinEgretia /> */} </div> <Embellish /> </div> ) } } class Team extends Component { constructor(props){ super(props) } componentDidMount(){ new WOW({ live: false }).init(); } render() { return ( <TeamRoot/> ) } } export default Team;
import firebase from 'firebase/app'; import 'firebase/app'; import 'firebase/database'; import 'firebase/auth'; import 'firebase/storage'; //const instead of variable cause we are using esx const config = { apiKey: "AIzaSyCG63lGH9M29MysYyl5HJaC5WHoeaR39HU", authDomain: "knick-city.firebaseapp.com", databaseURL: "https://knick-city.firebaseio.com", projectId: "knick-city", storageBucket: "knick-city.appspot.com", messagingSenderId: "1063888746689" }; firebase.initializeApp(config); const firebaseDB = firebase.database(); //starting point of gathering data for matches const firebaseKnickSchedule = firebaseDB.ref("knickgames/league/standard"); const firebaseTeams = firebaseDB.ref("_internal"); const firebasePlayers = firebaseDB.ref('league/league/standard') //const firebaseMatches = firebaseDB.ref("exampledata/matches") //a variable to host promotions const firebasePromotions = firebaseDB.ref('exampledata/promotions'); export{ firebase, firebaseDB, //firebaseMatches, firebaseKnickSchedule, firebaseTeams, firebasePlayers, firebasePromotions } //snapshot is firebase lingo // firebaseDB.ref('exampledata/matches').once("value").then ((snapsnot)=>{ // console.log(snapsnot.val()); // })
'use strict' const Tags = require('../../../ext/tags') const { TEXT_MAP } = require('../../../ext/formats') const { ERROR } = require('../../../ext/tags') const kinds = require('./kinds') const { addMethodTags, addMetadataTags, getFilter } = require('./util') function createWrapMakeClientConstructor (tracer, config) { config = config.client || config return function wrapMakeClientConstructor (makeClientConstructor) { return function makeClientConstructorWithTrace (methods) { const ServiceClient = makeClientConstructor.apply(this, arguments) const proto = ServiceClient.prototype if (typeof methods !== 'object') return ServiceClient Object.keys(methods) .forEach(name => { const originalName = methods[name] && methods[name].originalName proto[name] = wrapMethod(tracer, config, proto[name], methods[name]) if (originalName) { proto[originalName] = wrapMethod(tracer, config, proto[originalName], methods[name]) } }) return ServiceClient } } } function wrapMethod (tracer, config, method, definition) { if (typeof method !== 'function' || method._datadog_patched || !definition) { return method } const filter = getFilter(config, 'metadata') const methodWithTrace = function methodWithTrace () { const args = ensureMetadata(this, arguments) const length = args.length const metadata = args[1] const callback = args[length - 1] const scope = tracer.scope() const span = startSpan(tracer, config, definition) if (metadata) { addMetadataTags(span, metadata, filter, 'request') inject(tracer, span, metadata) } if (!definition.responseStream) { if (typeof callback === 'function') { args[length - 1] = wrapCallback(span, callback) } else { args[length] = wrapCallback(span) } } const call = scope.bind(method, span).apply(this, args) wrapStream(span, call, filter) return scope.bind(call) } Object.assign(methodWithTrace, method) methodWithTrace._datadog_patched = true return methodWithTrace } function wrapCallback (span, callback) { const scope = span.tracer().scope() const parent = scope.active() return function (err) { err && span.setTag(ERROR, err) if (callback) { return scope.bind(callback, parent).apply(this, arguments) } } } function wrapStream (span, call, filter) { if (!call || typeof call.emit !== 'function') return const emit = call.emit call.emit = function (eventName, ...args) { switch (eventName) { case 'error': span.setTag(ERROR, args[0] || 1) break case 'status': if (args[0]) { span.setTag('grpc.status.code', args[0].code) addMetadataTags(span, args[0].metadata, filter, 'response') } span.finish() break } return emit.apply(this, arguments) } } function startSpan (tracer, config, definition) { const path = definition.path const methodKind = getMethodKind(definition) const scope = tracer.scope() const childOf = scope.active() const span = tracer.startSpan('grpc.request', { childOf, tags: { [Tags.SPAN_KIND]: 'client', 'resource.name': path, 'service.name': config.service || `${tracer._service}-grpc-client`, 'component': 'grpc' } }) addMethodTags(span, path, methodKind) return span } function ensureMetadata (client, args) { if (!client || !client._datadog) return args const normalized = [args[0]] if (!args[1] || !args[1].constructor || args[1].constructor.name !== 'Metadata') { normalized.push(new client._datadog.grpc.Metadata()) } for (let i = 1; i < args.length; i++) { normalized.push(args[i]) } return normalized } function inject (tracer, span, metadata) { if (typeof metadata.set !== 'function') return const carrier = {} tracer.inject(span, TEXT_MAP, carrier) for (const key in carrier) { metadata.set(key, carrier[key]) } } function getMethodKind (definition) { if (definition.requestStream) { if (definition.responseStream) { return kinds.bidi } return kinds.client_stream } if (definition.responseStream) { return kinds.server_stream } return kinds.unary } module.exports = [ { name: 'grpc', versions: ['>=1.13'], patch (grpc, tracer, config) { if (config.client === false) return grpc.Client.prototype._datadog = { grpc } }, unpatch (grpc) { delete grpc.Client._datadog } }, { name: 'grpc', versions: ['>=1.13'], file: 'src/client.js', patch (client, tracer, config) { if (config.client === false) return this.wrap(client, 'makeClientConstructor', createWrapMakeClientConstructor(tracer, config)) }, unpatch (client) { this.unwrap(client, 'makeClientConstructor') } } ]
import React from "react"; import { AppearanceProvider } from "react-native-appearance"; import { StyleSheet, View } from "react-native"; import { ThemeProvider, useTheme } from "./contexts/ThemeContext"; import * as SplashScreen from "expo-splash-screen"; import useDatabase from "./hooks/DatabaseHook"; import { TeamsProvider } from "./contexts/TeamsContext"; import MainRoutes from "./Router/Routes"; export default function App() { SplashScreen.preventAutoHideAsync(); const isDBLoadingComplete = useDatabase(); const teams = [ { id: 1, name: "Us", wins: 0, losses: 0 }, { id: 2, name: "Them", wins: 0, losses: 0 }, ]; if (isDBLoadingComplete) { SplashScreen.hideAsync(); return ( <AppearanceProvider> <ThemeProvider> <TeamsProvider teams={teams}> <MainRoutes /> </TeamsProvider> </ThemeProvider> </AppearanceProvider> ); } else { return null; } }
import {app} from '../app' const configPath = '/api'; export class Utils { get (url, data = {}) { url = configPath + url; return new Promise((resolve, reject) => { app.$http.get(url, {params: data}).then((response) => { resolve(response.body) }).catch((response) => { this.checkResponse(response); reject(response.data); }) }) } post (url, body = {}) { url = configPath + url; return new Promise((resolve, reject) => { app.$http.post(url, body).then((response) => { resolve(response.body) }).catch((response) => { this.checkResponse(response); reject(response.data); }) }) } put (url, body = {}) { url = configPath + url; return new Promise((resolve, reject) => { app.$http.put(url, body).then((response) => { resolve(response.body) }).catch((response) => { this.checkResponse(response); reject(response.data); }) }) } deleteApi (url, body = {}) { url = configPath + url; return new Promise((resolve, reject) => { app.$http.delete(url, body).then((response) => { resolve(response.body) }).catch((response) => { this.checkResponse(response); reject(response.data); }) }) } // 设置cookie // ex大于1000表示设置毫秒,否则设置天数 setCookie (cname, cvalue, ex) { let d = new Date(); if (ex < 1000) { d.setTime(d.getTime() + (ex * 24 * 60 * 60 * 1000)); } else { d.setTime(d.getTime() + ex); } let expires = 'expires=' + d.toUTCString(); document.cookie = cname + '=' + cvalue + '; ' + expires; } getCookie (cname) { var name = cname + '='; var ca = document.cookie.split(';'); for (var i = 0; i < ca.length; i++) { var c = ca[i]; while (c.charAt(0) === ' ') c = c.substring(1); if (c.indexOf(name) !== -1) { let rs = c.substring(name.length, c.length); if (rs && rs !== 'undefined') { return rs; } } } return false; } clearCookie (name) { this.setCookie(name, '', -1); } checkResponse (response) { if (response.status === 500) { if (response.data) { response.data.message = '服务器发生错误,请稍后重试'; } } if (response.status === 0) { console.log(response.status); response.data = '当前网络条件不好,您现在无法提交.'; } return response; } }
// Strict Mode On (엄격모드) "use strict"; "use warning"; var EntryScene = new function() { var INSTANCE = this; var iframe; var loading; var btn_start; var logo; var all; var frameCnt = 0; var isLoadTitle = false; var onClicked = false; var gotoTutorial = false; var setResource = function(onload) { btn_start = []; var imgParam = [ [iframe = new Image(), ROOT_IFRAME + "back" + EXT_IFRAME], [loading = new Image(), ROOT_IMG + "entry/loading" + EXT_PNG], [btn_start = [], HTool.getURLs(ROOT_IMG, "entry/btn_start_", EXT_PNG, 2)], [logo = new Image(), ROOT_IMG + "entry/logo" + EXT_PNG], [all = new Image(), ROOT_UPDATE + "loading/all" + EXT_PNG] ]; ResourceMgr.makeImageList(imgParam, function () { imgParam = null; PlayResManager.setResourceForMoney(onload); }, function (err) { appMgr.openDisconnectPopup("setReosurce fail!!"); }); }; var entryLoading = function() { try { NetManager.Req_EntryLoading(function(response) { if (NetManager.isSuccess(response)) { ItemManager.setCashProductInfo(NetManager.getResult(response, 0)); MyInfo.Rev_MyLevel(NetManager.getResult(response, 1)[0]); ItemManager.Rev_AllItem(NetManager.getResult(response, 2), response.dateTime, true); NoticeManager.Rev_setNotice(NetManager.getResult(response, 3)); MyInfo.Rev_MyInfo(NetManager.getResult(response, 4)); StageManager.Rev_setStageMgntInfo(NetManager.getResult(response, 5)); StageManager.Rev_setStageInfo(NetManager.getResult(response, 6)); QuestManager.Rev_QuestInfo(NetManager.getResult(response, 9)); POPUP.POP_DAILYITEMMONTH.getInstance().Rev_Info(NetManager.getResult(response, 10)); if (QuestManager.getCurrentValue()[0] == "0") { QuestManager.questUpdt(0, function() { if (TutorialManager.getTutorial()) { appMgr.changeLayer(SCENE.SC_TUTORIAL, false, "main"); } else { appMgr.changeLayer(SCENE.SC_TITLE, false, "main"); } }); } else { if (TutorialManager.getTutorial()) { appMgr.changeLayer(SCENE.SC_TUTORIAL, false, "main"); } else { appMgr.changeLayer(SCENE.SC_TITLE, false, "main"); } } // if (appMgr.getFirstConn()) { // QuestManager.questUpdt(0, function() { // if (TutorialManager.getTutorial()) { // appMgr.changeLayer(SCENE.SC_TUTORIAL, false, "main"); // } else { // appMgr.changeLayer(SCENE.SC_TITLE, false, "main"); // } // }); // } else { // if (TutorialManager.getTutorial()) { // appMgr.changeLayer(SCENE.SC_TUTORIAL, false, "main"); // } else { // appMgr.changeLayer(SCENE.SC_TITLE, false, "main"); // } // } } else { appMgr.openDisconnectPopup("Req_EntryLoading Fail!!", this); } }); } catch (e) { HLog.err(e); appMgr.openDisconnectPopup("Req_EntryLoading Fail!!", this); } }; return { toString: function() { return "EntryScene"; }, init: function(onload) { setResource(onload); }, start: function() { // BTV 에서 인트로화면이 끝나면 인트로 이미지를 없앤다. android.introInvisible(); appMgr.loopNetSound(ROOT_SOUND + "title" + EXT_MP3); }, run: function() { frameCnt++; UIMgr.repaint(); }, paint: function() { g.drawImage(iframe, 0, 0); g.drawImage(logo, 275, 41); if (isLoadTitle) { g.drawImage(loading, 574, 591); } else { g.drawImage(btn_start[Math.floor(frameCnt / 2 % 2)], 521, 566); } g.drawImage(all, 1150, 30); }, stop: function() { iframe = null; loading = null; btn_start = null; logo = null; all = null; }, dispose: function() { }, onKeyPressed: function(key) { switch(key) { // case KEY_DOWN: // NetManager.Req_TUTOTEST(); // break; case KEY_PREV: POPUP.POP_MSG_2BTN.getInstance().setMessage("게임을 종료하시겠습니까?"); PopupMgr.openPopup(POPUP.POP_MSG_2BTN, function (code, data) { PopupMgr.closeAllPopup(); if( data==0 ) android.exitGame(); // BTV에서 이전키 눌렀을때 게임이 종료되는 메소드로 변경 appMgr.goGniPortal(); }); break; case KEY_ENTER: isLoadTitle = true; entryLoading(); break; } }, onKeyReleased: function(key) { switch(key) { case KEY_ENTER: break; } }, getInstance: function() { return INSTANCE; } }; };
export const MOCKED_POKEMONS = [ { id: 5, name:"ivysaur", imageUrl:"https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/5.png", abilities: [ { ability: { name: "solar-power" }}, { ability: { name: "blaze" }}, ], base_experience: 142 }, { id: 1, name: 'bulbazavr', imageUrl: "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/1.png", abilities: [ { ability: { name: "chlorophyll" }}, { ability: { name: "overgrow" }}, ], base_experience: 64 }, { id: 3, name: 'blastoise', imageUrl: "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/10.png", abilities: [ { ability: { name: "chlorophyll" }}, { ability: { name: "overgrow" }}, ], base_experience: 212 }, { id: 4, name: 'bulbazavr', imageUrl: "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/7.png", abilities: [ { ability: { name: "chlorophyll" }}, { ability: { name: "overgrow" }}, ], base_experience: 64 }, { id: 5, name:"ivysaur", imageUrl:"https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/5.png", abilities: [ { ability: { name: "solar-power" }}, { ability: { name: "blaze" }}, ], base_experience: 142 }, { id: 1, name: 'bulbazavr', imageUrl: "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/1.png", abilities: [ { ability: { name: "chlorophyll" }}, { ability: { name: "overgrow" }}, ], base_experience: 64 }, { id: 3, name: 'blastoise', imageUrl: "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/10.png", abilities: [ { ability: { name: "chlorophyll" }}, { ability: { name: "overgrow" }}, ], base_experience: 212 }, { id: 4, name: 'bulbazavr', imageUrl: "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/7.png", abilities: [ { ability: { name: "chlorophyll" }}, { ability: { name: "overgrow" }}, ], base_experience: 64 }, ] /* [ {"name":"bulbasaur","url":"https://pokeapi.co/api/v2/pokemon/1/"}, {"name":"ivysaur","url":"https://pokeapi.co/api/v2/pokemon/2/"}, {"name":"venusaur","url":"https://pokeapi.co/api/v2/pokemon/3/"}, {"name":"charmander","url":"https://pokeapi.co/api/v2/pokemon/4/"}, {"name":"charmeleon","url":"https://pokeapi.co/api/v2/pokemon/5/"}, {"name":"charizard","url":"https://pokeapi.co/api/v2/pokemon/6/"}, {"name":"squirtle","url":"https://pokeapi.co/api/v2/pokemon/7/"}, {"name":"wartortle","url":"https://pokeapi.co/api/v2/pokemon/8/"}, {"name":"blastoise","url":"https://pokeapi.co/api/v2/pokemon/9/"}, {"name":"caterpie","url":"https://pokeapi.co/api/v2/pokemon/10/"} ] */
import React from 'react' import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider' import * as AuthActions from '../../Actions/AuthActions' import * as scanTypeActions from '../../Actions/ScanTypeActions' import {bindActionCreators} from 'redux' import {connect} from 'react-redux' import {ValidatorForm} from 'react-form-validator-core' import {TextValidator} from 'react-material-ui-form-validator' import {toastr} from 'react-redux-toastr' import {Button, FormGroup,} from 'react-bootstrap' const underlineFocusStyle = { borderColor: "#7cc576" }; const floatingLabelFocusStyle = { color: "#7cc576" } const errorStyle = { color: "#f44336" } class Form extends React.Component { constructor(props) { super(props) this.state = { username: '', email: '', password: '', confirmationPassword: '', }; this.state = {} this.handleSubmit = this .handleSubmit .bind(this) this.handleChange = this .handleChange .bind(this) } static contextTypes = { router: React.PropTypes.object } handleChange(event) { this.setState({ [event.target.name]: event.target.value }) } componentWillMount() { if (this.props.auth.authenticated) { var sourceCodeScanType = this .props .fetchedScanTypes .find((scanType) => scanType.isStatic === true); this .context .router .history .push("/excutive_dashboard/" + this.props.ownerType.id + "/" + sourceCodeScanType.id, {state: 'state'}); } ValidatorForm.addValidationRule('isPasswordMatch', (value) => { if (value !== this.state.password) { return false; } return true; }); } handleSubmit(event) { event.preventDefault(); var payload = { 'name': this.state.username, 'email': this.state.email, 'password': this.state.password, }; this .props .actions .signup(payload) } renderNameField() { var validationRules = ['required']; var errorMessages = ['this field is required']; return (<TextValidator validators={validationRules} errorMessages={errorMessages} name="username" value={this.state.username} floatingLabelText="Username" floatingLabelFocusStyle={floatingLabelFocusStyle} onChange={this.handleChange} fullWidth={true} underlineFocusStyle={underlineFocusStyle} floatingLabelFocusStyle={floatingLabelFocusStyle} errorStyle={errorStyle}/>); } renderEmailField() { var validationRules = ['required', 'isEmail',]; var errorMessages = ['this field is required', 'email is not valid',]; return (<TextValidator validators={validationRules} errorMessages={errorMessages} name="email" value={this.state.email} floatingLabelText="Email" floatingLabelFocusStyle={floatingLabelFocusStyle} onChange={this.handleChange} fullWidth={true} underlineFocusStyle={underlineFocusStyle} floatingLabelFocusStyle={floatingLabelFocusStyle} errorStyle={errorStyle}/>); } renderPasswordField() { var validationRules = ['required']; var errorMessages = ['this field is required']; return (<TextValidator type="password" validators={validationRules} errorMessages={errorMessages} name="password" value={this.state.password} floatingLabelText="Password" onChange={this.handleChange} fullWidth={true} underlineFocusStyle={underlineFocusStyle} floatingLabelFocusStyle={floatingLabelFocusStyle}/>); } renderConfirmationPasswordField() { var validationRules = ['isPasswordMatch', 'required',]; var errorMessages = ['password mismatch', 'this field is required',]; return (<TextValidator type="password" validators={validationRules} errorMessages={errorMessages} name="confirmationPassword" value={this.state.confirmationPassword} floatingLabelText="Confirmation Password" onChange={this.handleChange} fullWidth={true} underlineFocusStyle={underlineFocusStyle} floatingLabelFocusStyle={floatingLabelFocusStyle}/>); } componentWillReceiveProps(nextProps) { console.log("nextProps.auth.error", nextProps.auth.error); if (nextProps.auth.authenticated && nextProps.fetchedScanTypes.length === 0) { var scanTypes = []; var ownerTypes = []; var currentActions = this.props.actions; currentActions.fetchAllScanTypes({limit: -1}); toastr.info("You have been successfully logged in."); } else if (nextProps.auth.error) { toastr.error(nextProps.auth.error.data.message); } else if (nextProps.auth.authenticated && nextProps.fetchedScanTypes.length > 0) { var sourceCodeScanType = nextProps .fetchedScanTypes .find((scanType) => scanType.isStatic === true); var ownerTypes = nextProps.auth.currentUser.ownerTypes; var corporateOwner = ownerTypes.find((ownerType) => ownerType.name === 'Corporate'); var teamOwner = ownerTypes.find((ownerType) => ownerType.name === 'Team'); var personalOwner = ownerTypes.find((ownerType) => ownerType.name === 'Personal'); if (nextProps.auth.currentUser.allowedExecutiveDashboard) { this .context .router .history .push("/excutive_dashboard/" + nextProps.ownerType.id + "/" + sourceCodeScanType.id, {state: 'state'}); } else if (nextProps.auth.currentUser.allowedCorporateDashboard) { this .context .router .history .push("/dashboard/" + corporateOwner.id + "/" + sourceCodeScanType.id, {state: 'state'}); } else if (nextProps.auth.currentUser.allowedTeamDashboard) { this .context .router .history .push("/dashboard/" + teamOwner.id + "/" + sourceCodeScanType.id, {state: 'state'}); } else { this .context .router .history .push("/dashboard/" + personalOwner.id + "/" + sourceCodeScanType.id, {state: 'state'}); } } } render() { return ( <MuiThemeProvider> <ValidatorForm onSubmit={this.handleSubmit}> {this.renderNameField()} {this.renderEmailField()} {this.renderPasswordField()} {this.renderConfirmationPasswordField()} <FormGroup class="sign-in-form-group"> <Button block bsSize="large" class="btn btn-success signup-button" type="submit"> Get Started </Button> </FormGroup> </ValidatorForm> </MuiThemeProvider> ) } } function mapDispatchToProps(dispatch) { return { actions: bindActionCreators(Object.assign({}, AuthActions, scanTypeActions), dispatch) }; } const mapStateToProps = (state) => ({auth: state.auth, fetchedScanTypes: state.scanTypes.fetchedScanTypes, ownerType: state.scanTypes.ownerType}); export default connect(mapStateToProps, mapDispatchToProps)(Form)
import WebpackDevServer from 'webpack-dev-server' import webpack from 'webpack' import webpackConfig from './dev.config' import config from '../src/config' const compiler = webpack(webpackConfig) let server = new WebpackDevServer(compiler) const port = (Number(config.port) + 1) || 3001 server.listen(port, 'localhost', function onAppListening (err) { if (err) { console.error(err) } else { console.info('==> 🚧 Webpack development server listening on port %s', port) } })
/** * * 所有工具方法都从这里统一导出 * * */ import requestPayment from './function/requestPayment.js' import toast from './function/toast.js' export default { pay: requestPayment,//uni支付封装 toast,//消息提示uni.showToast封装 }
import {h} from '../lib/h.js' import './DatePicker.less'; const MONTH_NAMES = ['', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; const NBSP = '\u00a0'; // unicode for entity &nbsp; function genId() { return Math.random().toString(36).substr(2, 9); } function pad(d) { return ('0' + d).substr(-2); } function formatDate(dt, formatStr = 'YYYY-MM-DD') { if (!(dt && dt instanceof Date)) return ''; const yyyy = dt.getFullYear(); const mm = pad(dt.getMonth() + 1); const dd = pad(dt.getDate()); const mon = MONTH_NAMES[dt.getMonth() + 1]; return formatStr.replace('YYYY', yyyy).replace('MMM', mon).replace('MM', mm).replace('DD', dd); } function compareDates(a, b) { const s1 = formatDate(a); const s2 = formatDate(b); return (s1 > s2) ? 1 : (s1 < s2) ? -1 : 0; } function isSameDate(a, b) { // return compareDates(a, b) === 0; return (a.getFullYear() === b.getFullYear()) && (a.getMonth() === b.getMonth()) && (a.getDate() === b.getDate()); } // console.log('compare GT', compareDates(new Date(2016, 7, 30), new Date(2016, 7, 28))); // console.log('compare LT', compareDates(new Date(2016, 7, 30), new Date(2016, 8, 28))); // console.log('compare EQ', compareDates(new Date(2016, 7, 21), new Date(2016, 7, 21))); // console.log('compare GT', compareDates(new Date(2016, 7, 30), new Date(2016, 7, 28))); // console.log('compare LT', compareDates(new Date(2016, 7, 30), new Date(2016, 8, 28))); // console.log('compare EQ', compareDates(new Date(2016, 7, 21), new Date(2016, 7, 21))); function buildState(props, state) { const dt = props.value ? props.value : new Date(); const year = dt.getFullYear(); const month = dt.getMonth() + 1; return { show: false, year, month }; } export class DatePicker extends React.Component { constructor(props) { super(props); this.state = buildState(props); this.rootRef = React.createRef(); this.onDocumentClick = this.onDocumentClick.bind(this); this.onInputFocus = this.onInputFocus.bind(this); this.onClear = this.onClear.bind(this); } componentDidMount() { } // Do NOT blindly call setState. It should be conditional. Otherwise, we will endup in infinite loop // Read more: https://reactjs.org/docs/react-component.html componentDidUpdate(prevProps, prevState, snapshot) { if (prevProps.value === this.props.value) return; if (prevProps.value && this.props.value && isSameDate(this.props.value, prevProps.value)) return; console.log('componentDidUpdate', this.props.id, formatDate(prevProps.value), formatDate(this.props.value)); const state = buildState(this.props, this.state); this.setState(state); } // componentWillReceiveProps lifecycle is deprecated // use componentDidUpdate lifecyle to conditionally update the state from props changes (check above) __componentWillReceiveProps(nextProps) { console.log('componentWillReceiveProps', nextProps.id, nextProps.value); if (this.props.value === nextProps.value) return; if (this.props.value && nextProps.value && isSameDate(this.props.value, nextProps.value)) return; const state = buildState(nextProps, this.state); this.setState(state); } show() { if (this.props.value) { const dt = this.props.value; const year = dt.getFullYear(); const month = dt.getMonth() + 1; this.setState({ year, month }); } document.addEventListener('click', this.onDocumentClick); this.setState({show: true}); } hide() { document.removeEventListener('click', this.onDocumentClick); this.setState({show: false}); } onDocumentClick(e) { const $root = this.rootRef.current; if ($root && !$root.contains(e.target)) { this.hide(); } } onInputFocus() { this.show(); } onClear() { this.props.onChange(null, this.props.id); } move(year, month) { this.setState({year, month}); }; choose(day) { if (!day) return const dt = new Date(this.state.year, this.state.month - 1, day); this.hide(); this.props.onChange(dt, this.props.id); } chooser(val) { return e => this.choose(val); }; formatValue() { if (!this.props.value) return ''; return formatDate(this.props.value, this.props.displayFormat); }; renderTable(year, month) { const grid = []; const mon = month - 1; let i, j, k, d; for (i = 0; i < 6; i += 1) { for (j = 0; j < 7; j += 1) { k = i * 7 + j; grid[k] = NBSP; } } const firstDate = new Date(year, mon, 1); const firstDay = firstDate.getDay(); let lday = 32; let lastDate; do { lday -= 1; lastDate = new Date(year, mon, lday); } while (lastDate.getMonth() !== mon) for (d = 1, k = firstDay; d <= lastDate.getDate(); d += 1, k += 1) { grid[k] = d; } // console.log('grid', year, month, grid); const selDate = this.props.value ? this.props.value.getDate() : 0; const rows = []; for (i = 0; i < 6; i += 1) { const cols = []; for (j = 0; j < 7; j += 1) { k = i * 7 + j; const val = grid[k]; const css = []; if (val !== NBSP) { let dt = new Date(this.state.year, this.state.month - 1, val); css.push('enabled'); if (this.props.value && isSameDate(dt, this.props.value)) css.push('selected'); } cols[j] = h('td', {key: 'c' + j, className: css.join(' '), onClick: this.chooser(val)}, val); } rows.push( h('tr', {key: 'r' + i}, cols) ); } return h('table', {className: 'date-picker__calendar'}, h('thead', null, h('tr', null, h('th', null, 'S'), h('th', null, 'M'), h('th', null, 'T'), h('th', null, 'W'), h('th', null, 'T'), h('th', null, 'F'), h('th', null, 'S') ) ), h('tbody', {onClick: this.onDayClick}, rows) ); } render() { const {show, year, month} = this.state; const {id, value, clearable, className, placeholder, zIndex} = this.props; const calHide = show ? '' : 'hide'; const clear = clearable && value ? h('span', {className: 'date-picker__input-icox', onClick: this.onClear}, '\u2715') : null; return h('div', {id, ref: this.rootRef, className: 'date-picker ' + className, style: {zIndex}}, h('div', {className: 'date-picker__input'}, h('input', {className: 'date-picker__input-txt', type: 'text', value: this.formatValue(), placeholder: placeholder, onFocus: this.onInputFocus}), clear ), h('div', {className: ['date-picker__panel ', calHide].join(' ') }, h('div', {className: 'date-picker__nav'}, h('span', {className: 'date-picker__nav-ico fa fa-angle-double-left', onClick: e => this.move(year - 1, month)}), h('span', {className: 'date-picker__nav-ico fa fa-angle-left', onClick: e => this.move(year, month - 1)}), h('span', {className: 'date-picker__nav-mnyr'}, MONTH_NAMES[month], ' ', year), h('span', {className: 'date-picker__nav-ico fa fa-angle-right', onClick: e => this.move(year, month + 1)}), h('span', {className: 'date-picker__nav-ico fa fa-angle-double-right', onClick: e => this.move(year + 1, month)}) ), this.renderTable(year, month) ) ); } }; DatePicker.defaultProps = { value: null, // null | Date object className: '', displayFormat: 'DD-MM-YYYY', // options: YYYY=FullYear, MMM=MonthName, MM=Month, DD=Day placeholder: 'Select...', zIndex: 1, clearable: true, onChange: function(){} // (value, id) };
import React from 'react'; import '../../CSS/Results.css'; class Negative extends React.Component { render() { return ( <div id="negativeDiv" className="slantLeft slantDiv"> <div id="negTitle" className="sectionTitle"> <h2>Most Negative Comment</h2> </div> <div id="mostNegativeParent" className="dataDiv"> <p>Jane Doe</p> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse bibendum enim ac lectus consequat finibus. Ut lacus ipsum, varius mollis placerat et, finibus vel lectus.</p> </div> </div> ); } } export default Negative;
import React, {Component} from "react" import Form from "./form" class FormContainer extends Component { constructor(props) { super(props) } render() { return ( <div className="form-container"> <h2><span>用户登录</span></h2> <div className="form-box"><Form /></div> </div> ) } } export default FormContainer;
#!/usr/bin/env node var inireader = require("inireader"), prompt = require("prompt"), colors = require("colors"), fs = require("fs"), cp = require("child_process"), pivotal = require("pivotal"), chagama = require("../lib/chagama"), ini = loadGitConfig(); // Command definition function loadGitConfig(ini){ var path = process.env.HOME + "/.gitconfig"; try{ try{ fs.statSync(path) } catch(e){ fs.writeFileSync(path, ""); } var ini = new inireader.IniReader(); ini.load(path) return ini; } catch(e) { console.log(e.message); console.log(""); console.error(" !!! You do not seem to have a git config, or it is not readable. Please make sure it is present in your home directory".red); console.log(""); process.exit(); } } function setCredentials(cb){ var callAgain = arguments.callee; console.log(" Please enter your PivotalTracker User name and password to generate you PT API token.".green); console.log(""); prompt.message = " PivotalTracker".green; prompt.delimiter = " //" . blue.bold; prompt.start(); prompt.get([ { name : 'name', validator : /^[a-zA-Z\@\._\-]+$/, warning : 'username', message : 'User name', empty : false }, { name : 'pass', hidden : true, message : 'Password', empty : false } ], function(err, user){ prompt.pause(); pivotal.getToken(user.name, user.pass, function(token){ if(token){ console.log(""); console.log(" ✔ Your user token was retrieved successfully. Writing it in you .gitconfig for later uses...".green); ini.param("pivotal.token", token); ini.write(); cb(); } else{ console.log(); console.log(" ✖ Oops! Wrong username and/or password it would seem. Mind to try again?".red); callAgain(cb); } }); }); } function init(){ var cmd = process.argv[2]; var args = process.argv.slice(3); var argsPosItr = 0; runCommand = function(){ pivotal.useToken(ini.param("pivotal.token")); chagama.pivotal = pivotal; // Make sure the command is defined if(!chagama.commands[cmd]){ console.error((" ✖ Command not found: " + cmd).red); chagama.showHelp(); process.exit(1); } /// Make sure the argCount is correct for(var a in chagama.commands[cmd].args){ if(!chagama.commands[cmd].args[a].optional && !args[argsPosItr]) { console.log(""); console.error((" ✖ Missing argument: " + a).red); chagama.showHelp(cmd); process.exit(1); } argsPosItr++; } chagama.commands[cmd].func.apply(null, args); } if(!cmd){ chagama.showSign(); chagama.showHelp(); process.exit(1); } if(!ini.param("pivotal")){ chagama.showSign(); console.log(" "); console.log(" ", "☺".green, "Oh, here you are! You seem to be new around here, why don't you let me help you to set up chagama?".magenta) console.log(" "); setCredentials(runCommand); } else runCommand(); } init(process.argv);
import React from 'react' import PropTypes from 'prop-types' import { table } from '../../../macros' import { useID, useRowIDs } from '../../../hooks' import Overflow from '../overflow' import * as Styled from './styles' const Table = ({ children, height, minWidth, rowData }) => { const [tableID] = useID() const [rowIDs] = useRowIDs(rowData) if (rowData && rowData.length > 0) { return ( <Overflow height={height} x="scroll"> <Styled.Table minWidth={minWidth}> <thead> <tr> {Object.keys(rowData[0]).map(colName => ( <th key={`table-${tableID}-${colName}`}>{colName}</th> ))} </tr> </thead> <tbody> {rowData.map((row, rowIndex) => { const rowKey = rowIDs.length ? `table-${tableID}-row-${rowIDs[rowIndex]}` : `table-${tableID}-row-${rowIndex}` return ( <tr key={rowKey}> {Object.keys(row).map(colName => ( <td key={`${rowKey}-${colName}`}>{row[colName]}</td> ))} </tr> ) })} </tbody> </Styled.Table> </Overflow> ) } return ( <Overflow height={height} x="scroll"> <Styled.Table minWidth={minWidth}>{children}</Styled.Table> </Overflow> ) } Table.propTypes = { ...table.propTypes(), rowData: PropTypes.arrayOf(PropTypes.object), } Table.defaultProps = { ...table.defaultProps(), rowData: [], } export default Table
const physicianName =['ADIB, KEENAN', 'ALOKA, FERAS', 'ALPERT, BARRY L', 'AZIZ, ABDULRAB', 'CASTIGLIONE, ANGELO', 'CULIG, MICHAEL', 'DUA, AASHISH', 'HOUDA, JOSEPH', 'HUSSEIN, STEVEN', 'JOHNSON, ANTHONY', 'KELLEY, MICHAEL P', 'KLEIST, PAUL', 'MAGOVERN, GEORGE', 'MCGAFFIN, KENNETH', 'MUSSELMAN, KIRK', 'PELLEGRINI, RONALD', 'POGOZELSKI, ANDREW', 'REDDY, RAGOOR', 'SCHUMACHER, LANA', 'SHAH, DIPESH', 'SHARMA, PARMINDER', 'SWAMY, RAJIV', 'TAUBERG, STUART', 'VAN DEUSEN, MATHEW', 'VIJAYKUMAR, PUVALAI', 'VISWANATHAN, PERINKULAM' ]; export default physicianName;
/* * Javascript Router.js * * Written By Bart Dority - October, 2017 * * This is a Javascript based router that allows you to build a "Single Page App" * Using just a little Javascript and a little PHP. The Navigation Links are * built dynamically from an array using PHP. The links are responded to in * javascript, using JQuery -- and then an AJAX request is sent to the server * to load in the corresponding HTML page. We use JQuery again to update * the DOM. * * */ $(document).ready( function() { /* Wait until the page is done loading before we start listening for navigation clicks */ $(".navBar li").on('click', linkMe ); routeMe('home'); }); /* LinkMe * * parameter: Take in a jQuery object of the link that made the request for navigation * */ var linkMe = function() { var linker = $(this); /* update the style of the link on the page so the user knows we are in this section now */ $(".navBar li").removeClass('navSelected'); $(linker).addClass('navSelected'); /* Push this navigational choice to the browser history so that the URL actually changes */ var selection = $(this).data('selection'); var stateObj = { page: "selection" }; history.pushState(stateObj, "?page="+selection, "?page="+ selection); routeMe(selection); } /* * RouteMe * * Open an XMLHTTP Request (Ajax call) to dynamically load in an html page * * parameter: pagename: string of the filename we want loaded * */ var routeMe = function( pagename ) { var contentArea = $('#contentArea'); /* Make an AJAX call to load in the new content file */ var client = new XMLHttpRequest(); var pagepath = './pages/'+ pagename +'.html'; client.open('GET', pagepath); /* When the file is done loading, we get notified here */ client.onreadystatechange = function() { /* If we're done and everything went as planned, then update the content area */ if (client.readyState === XMLHttpRequest.DONE) { if (client.status === 200) { updateContent( client.responseText ); } else { alert('There was a problem with the request.'); } } } client.send(); } /* LinkMe * * parameters: the response from the Ajax Request * */ var updateContent = function( response ) { /* Use JQuery to update the html of the content div in the DOM */ $('#contentArea').html( response ); }
/* eslint-env browser */ // Dependencies import React from 'react' import ReactDOM from 'react-dom' import ApolloClient from 'apollo-client' import ReactGA from 'react-ga' import { onError } from 'apollo-link-error' import { ApolloProvider } from 'react-apollo' import { createHttpLink } from 'apollo-link-http' import { InMemoryCache } from 'apollo-cache-inmemory' import { Router } from 'react-router-dom' // import { StripeProvider } from 'react-stripe-elements' // App components import config from './config' import history from './history' import App from './components/App' import AppContainerComponent from './components/AppContainer/AppContainer' import Error from './components/Error/Error' // Styles import './style/style.css' // Config const { GA_TRACKING_CODE, GRAPHQL_PATH, HOST, PROTOCOL, SERVER_PORT, } = config /** * General error handling. * @type {Object} */ const generalError = onError(({ networkError }) => { if (networkError) { ReactDOM.render( <Error error={networkError ? networkError.message : ''} /> , document.querySelector('#app'), ) } }) /** * Set up link to GraphQL server. * @type {HttpLink} */ const link = createHttpLink({ uri: `${PROTOCOL}://${HOST}:${SERVER_PORT}/${GRAPHQL_PATH}`, credentials: 'include', }) /** * Set up Apollo (GraphQL interface). * @type {ApolloClient} */ const client = new ApolloClient({ link: generalError.concat(link), cache: new InMemoryCache(), dataIdFromObject: o => o.id, }) /** * Initialize Google Analytics */ ReactGA.initialize(GA_TRACKING_CODE, { debug: config.GA_DEBUG, titleCase: false, }) /** * Create the root element to contain the app. Router handles the app routes * while ApolloProvider enables graphQL functionality in all sub-components. */ const Root = () => ( <ApolloProvider client={client}> <Router history={history}> <AppContainerComponent> <App /> </AppContainerComponent> </Router> </ApolloProvider> ) // TODO: pay me button // <StripeProvider apiKey="pk_test_K4i3N250qcdeJ9sIy0a09jqY"> // </StripeProvider> /** * Render the element to the page. */ ReactDOM.render( <Root />, document.querySelector('#app'), )
import React, { Component } from 'react'; import { View, Text, SafeAreaView, StyleSheet, Dimensions, StatusBar } from 'react-native'; import { connect } from 'react-redux'; import { selectTheme } from '../actions'; import settings from '../appSettings'; const fontFamily = settings.fontFamily const width = Dimensions.get('screen').width const height = Dimensions.get("window").height const screenHeight = Dimensions.get("screen").height const lightTheme = settings.lightTheme const darkTheme = settings.darkTheme import { VictoryBar, VictoryChart, VictoryTheme, VictoryZoomContainer} from "victory-native"; import { LineChart, BarChart, PieChart, ProgressChart, ContributionGraph, StackedBarChart } from "react-native-chart-kit"; import { ScrollView } from 'react-native-gesture-handler'; import * as Animatable from 'react-native-animatable'; const data = [ { subject: "Tamil", marks: 80,fill:"red"}, { subject: "English", marks: 90,fill:'orange'}, { subject: "Maths", marks: 10, fill: 'green' }, { subject: "Science", marks: 50, fill: 'gray' }, { subject: "Social", marks: 50, fill: '#fafa' }, { subject: "Geology", marks: 50, fill: '#ede' }, { subject: "chemistry", marks: 80, fill: "#F4F" }, { subject: "bio", marks: 90, fill: "#F4F" }, ]; const data2 = { labels: ["January", "February", "March", "April", "May", "June","july","aug","sep","oct","nov","dec","iii"], datasets: [ { data: [20, 45, 28, 80, 99, 43,90,65,78,90,20,70,90] } ] }; const chartConfig = { backgroundGradientFrom: "#000", backgroundGradientFromOpacity: 0, backgroundGradientTo: "#f1f1ff", backgroundGradientToOpacity: 0.5, color: (opacity = 1) => `rgba(255, 0, 0, ${opacity})`, strokeWidth: 2, // optional, default 3 barPercentage: 0.5, useShadowColorFromDataset: false, // optional }; class Statistics extends React.PureComponent { constructor(props) { super(props); this.state = { }; } render() { let theme; if (this.props.theme == "dark") { theme = darkTheme } else { theme = lightTheme } return ( <> <StatusBar backgroundColor={theme.backgroundColor} barStyle={this.props.theme == "dark" ? "light-content" : "dark-content"} /> <SafeAreaView style={[styles.topSafeArea, { backgroundColor: theme.backgroundColor }]} /> <SafeAreaView style={[styles.bottomSafeArea, { backgroundColor: theme.backgroundColor }]}> <View style={{ backgroundColor: theme.backgroundColor,alignItems:"center",justifyContent:"center",flex:1}}> {/* <ScrollView horizontal ={true} > <VictoryChart width={width*1} theme={VictoryTheme.material} height={height * 0.6} domainPadding={40} domainPadding={{ x: 0}} > <VictoryBar style={{ data: { fill: ({ datum }) => datum.fill, } }} barWidth={({ index }) => index * 2 + 8} labels={({ datum }) => `${datum.marks}`} data={data} x="subject" y="marks" animate={{ duration: 2000, onLoad: { duration: 1000 } }} /> </VictoryChart> </ScrollView> */} <ScrollView contentContainerStyle={{alignItems:'center',justifyContent:"center"}} horizontal={true} > <BarChart showValuesOnTopOfBars={true} style={{}} data={data2} width={width*1.5} chartConfig={{ backgroundColor: "#000000", decimalPlaces: 0, color: (opacity = 1) => `rgba(255, 255, 255, ${opacity})`, labelColor: (opacity = 1) => `rgba(255, 255, 255, ${opacity})`, style: { borderRadius: 0, borderWidth: 1, borderColor: '#fff' }, propsForDots: { r: "2", strokeWidth: "2", stroke:"#fff", }, propsForBackgroundLines: { color: (opacity = 1) => `rgba(255, 255, 255, ${opacity})`, }, fillShadowGradient: "#0090F8", fillShadowGradientOpacity: 1, }} height={height * 0.6} verticalLabelRotation={90} /> </ScrollView> </View> </SafeAreaView> </> ); } } const styles = StyleSheet.create({ text: { fontFamily }, topSafeArea: { flex: 0, }, bottomSafeArea: { flex: 1, }, }) const mapStateToProps = (state) => { return { theme: state.selectedTheme, } } export default connect(mapStateToProps, { selectTheme })(Statistics)
'use strict' const Menu = require('../models/Menu.model') module.exports = { getMenus, getMenu, createMenu, removeMenu, updateMenu } function getMenus(req, res) { Menu.find({}) .populate('dishes') .exec(function (err, result) { if (err) throw err res.json(result) }) } function getMenu(req, res) { Menu.findById(req.params.id) .populate('dishes') .exec(function (err, result) { if (err) throw err res.json(result) }) } function createMenu(req, res) { if (!req.body && (!req.body.name || req.body.length === 0)) { return res.status(400).send('Bad request. Missing Menu details.') } Menu.create(parseMenuData(req.body), function (err, result) { if (err) throw err; if (result && result.length > 0) { console.log('Menu added', result) res.json(result) } }) } function removeMenu(req, res) { Menu.findByIdAndRemove(req.params.id, function (err, result) { if (err) throw err console.log('Menu removed', result); res.json({ success: true }); }) } function updateMenu(req, res) { if (!req.body && (!req.body.name || req.body.length === 0)) { return res.status(400).send('Bad request. Missing Menu details.') } const menu = parseMenuData(req.body) Menu.findByIdAndUpdate(req.params.id, menu, function (err, result) { if (err) throw err if (result && result.length > 0) { console.log('Menu updated') res.json(result) } }) } function parseMenuData(requestBody) { return { name: requestBody.name, dishes: requestBody.dishes } }
import React, { Component,Fragment } from 'react'; import { Container} from 'react-bootstrap'; import {Link} from "react-router-dom"; class freelanceRecruiter extends Component { render() { return ( <Fragment> <Container> <p className="freelance__title">Freelance Recruiter</p> <p className="greyBar"></p> <p className="freelance__des mt-5"> This is platform created by TalenTracker with an aim to facilitate professionals and individuals to exercise their people understanding and sourcing skills. Under this platform, Recruiters’ will be able to create their profile with TalenTracker website and recommend candidates’ profiles from their own network or sourcing against specific job openings. Recruiters’ have to screen profiles at their own matching with the specific job and upload in the internal portal of TalenTracker. <br /><br /> Recruiters will be eligible for financial reward at a certain rate if their recommended candidates are hired against the specific job. </p> <Link to="/FreelanceRecruiterRegPage"> <button className="talentTracker__btn freelance__btn mt-5 mb-5">join us</button> </Link> </Container> </Fragment> ); } } export default freelanceRecruiter;
module.exports={ ensureAuthenticated:function(request,response,next){ if(request.isAuthenticated()){ return next(); } response.redirect("/"); } }
"use strict"; /** * Object Short Syntax -> Quando o nome da variável for o mesmo nome da propriedade do objeto, podemos utilizar a 'Sintaxe curta de Objeto' */ var nome = 'Ricardo'; var idade = 30; // Ao invés de atribuir dessa forma var usuario1 = { nome: nome, idade: idade, empresa: 'Desempregados SA' }; console.log(usuario1); // Utilizamos o 'Object Short Syntax' var usuario2 = { nome: nome, idade: idade, empresa: 'Desempregados SA', Endereco: { rua: 'Forte do Calvário', cidade: 'São Paulo', uf: 'SP' } }; console.log(usuario2);
'use strict'; /** * @ngdoc function * @name NaturalSoftApp.controller:IndexController * @description * # IndexController * Controller of the NaturalSoftApp */ angular.module('NaturalSoftApp') .controller('IndexController', ['$scope', 'subgroupsFactory','$state', 'customCache', '$http','appConfig','$rootScope','$uibModal', function($scope,subgroupsFactory, $state, customCache, $http, appConfig,$rootScope,$uibModal) { function getData(id){ if(customCache.get('index-' + id)){ $scope.showContent = true; $scope.subgroups = customCache.get('index-' + id); } else { $http({ method :'GET', url : appConfig.baseURL + appConfig.phpHandler, params:{ action : 'getsubcategories', category : id }, cache: false }).then( function(response) { $scope.showContent = true; customCache.put('index-' + id,response.data); $scope.subgroups = response.data; }, function(response) { $scope.showResponseMessage = true; $scope.responseMessage = 'Status: ' + response.status + ' ' + 'Message: ' + response.data; }); } } function compareNumeric(a, b) { //функция сортировки return a.position - b.position; }; var id = subgroupsFactory.detectCid($state.params.type); // error messages $scope.showError = false; $scope.showSucces = false; $scope.showResponseMessage = false; $scope.showContent = false; $scope.dismissError = function (v) { console.log(v); $scope.showError = false; }; $scope.dismissSuccess = function () { $scope.showSucces = false; }; $scope.dismissResponseMessage = function () { $scope.showResponseMessage = false; }; $scope.collapseMenu = subgroupsFactory.collapseMenu; //-----// $scope.edit = { data: null, }; $scope.$on('showError', function(e,args){ $scope.showError = args; }); $scope.run = function(action,data){ if (data === null){ $scope.showError = true; } else { switch(action){ case 'delete': var deleteModal = $uibModal.open({ animation: true, templateUrl: 'views/deleteModal.html', scope: $scope, size: 'sm', resolve: { data: function () {return data;}}, controller: ['$scope','$uibModalInstance','data', function($scope,$uibModalInstance, data) { console.log(data); $scope.cancel = function(){ $uibModalInstance.dismiss(false,false); }; $scope.delete = function(){ subgroupsFactory.sendData('deletesubcategory',null, null, id, data.id, null ) .then(function(response) { $uibModalInstance.close(response); }, function(response) { $uibModalInstance.dismiss(true,response); }); }; }] }); deleteModal.result.then(function(){ var needle = subgroupsFactory.binarySearch(data.id, $scope.subgroups); // обновить категории if(~needle){ $scope.subgroups.splice(needle, 1); } customCache.removeAll(); },function(reason,response){ if(reason){ $scope.showResponseMessage = true; $scope.responseMessage = 'Status: ' + response.status + ' ' + 'Message: ' + response.data;} }); /* subgroupsFactory.sendData('deletesubcategory',null, null, id, data.id, null ) .then(function(response) { var needle = subgroupsFactory.binarySearch(data.id, $scope.subgroups); // обновить категории if(~needle){ $scope.subgroups.splice(needle, 1); } customCache.removeAll(); }, function(response) { $scope.showResponseMessage = true; $scope.responseMessage = 'Status: ' + response.status + ' ' + 'Message: ' + response.data;}); $scope.edit = { data: null, }; */ break; case 'up': if (+data.position !== $scope.subgroups.length){ subgroupsFactory.changePosition('changepositionsubcategory','up',null,id,data.id) .then(function() { if(+data.position){ var position = subgroupsFactory.binarySearchP((+data.position + 1), $scope.subgroups); if (~position && $scope.subgroups[position]['position']) { $scope.subgroups[position]['position'] = +$scope.subgroups[position]['position'] - 1; }} //обновить параметрв массиве субкатегории var needle = subgroupsFactory.binarySearch(data.id, $scope.subgroups); if (~needle) { $scope.subgroups[needle]['position'] = +$scope.subgroups[needle]['position'] + 1; } }, function(response) { $scope.showResponseMessage = true; $scope.responseMessage = 'Status: ' + response.status + ' ' + 'Message: ' + response.data;}); } break; case 'down': if (+data.position !== 1){ console.log(data) subgroupsFactory.changePosition('changepositionsubcategory','down',null,id,data.id) .then(function() { var position = subgroupsFactory.binarySearchP((+data.position - 1), $scope.subgroups); console.log(position) if (~position && $scope.subgroups[position]) { $scope.subgroups[position]['position'] = +$scope.subgroups[position]['position'] + 1; } //обновить параметрв массиве субкатегории var needle = subgroupsFactory.binarySearch(data.id, $scope.subgroups); if (~needle) { $scope.subgroups[needle]['position'] = +$scope.subgroups[needle]['position'] - 1; } }, function(response) { $scope.showResponseMessage = true; $scope.responseMessage = 'Status: ' + response.status + ' ' + 'Message: ' + response.data;}); } break; } } return true; }; $scope.subgroups = []; getData(id); }]);
import React from 'react'; import {IndexRoute, Route} from 'react-router'; import { isLoaded as isAuthLoaded, load as loadAuth } from 'redux/modules/auth'; import { viewdetail as detail} from 'redux/modules/products'; import { App, Categories, Chat, Home, Widgets, About, Login, LoginSuccess, Survey, Products, PlaceUploader, Detail, Cart, Votings, NotFound, PackageBuilder, } from 'containers'; export default (store) => { const requireLogin = (nextState, replace, cb) => { function checkAuth() { const { auth: { user }} = store.getState(); if (!user) { // oops, not logged in, so can't be here! replace('/'); } cb(); } if (!isAuthLoaded(store.getState())) { store.dispatch(loadAuth()).then(checkAuth); } else { checkAuth(); } }; const loadDetails3 = (nextState, replace, cb) => { function checkAuth() { const { auth: { user }} = store.getState(); if (!user) { // oops, not logged in, so can't be here! replace('/'); } cb(); } var prodid=qs('id'); store.dispatch({type:'DETAIL', result:{id:prodid}}); return true; }; function loadDetails(nextState, replace) { var prodid=qs('id'); store.dispatch({type:'DETAIL', result:{id:prodid}}); replace(); // } } function loadCategories(nextState, replace) { var category=qs('categories'); var value = qs('search'); store.dispatch({type:'CATEGORIES', result:{ SEARCHBY:category, VALUE:value }}); } /** * Please keep routes in alphabetical order */ return ( <Route path="/" component={App}> { /* Home (main) route */ } <IndexRoute component={Home}/> { /* Routes requiring login */ } <Route onEnter={requireLogin}> <Route path="chat" component={Chat}/> <Route path="loginSuccess" component={LoginSuccess}/> </Route> { /* Routes */ } <Route path="/about" component={About}/> <Route path="/categories:id/search:id" component={Categories} onEnter={loadCategories}/> <Route path="/login" component={Login}/> <Route path="/survey" component={Survey}/> <Route path="/contests" component={Votings}/> <Route path="/widgets" component={Home}/> <Route path="/products" component={Products}/> <Route path="/upload" component={PlaceUploader}/> <Route path="/detail/id:productid" component={Detail} onEnter={loadDetails} /> <Route path="/cart" component={Cart}/> <Route path="/packagebuilder" component={PackageBuilder}/> //onEnter={loadDetails} { /* Catch all route */ } <Route path="*" component={NotFound} status={404} /> </Route> ); }; const onRouteEnter = async (nextState, replaceState, done) => { try { await fetchComponentData({ dispatch: store.dispatch, components: nextState.routes.map(route => route.component), params: Object.assign({}, nextState.params), location: nextState.location, deferred: false, }); } catch (err) { if (!__PROD__) { debugger; // window.console.log(err); } } done(); try { fetchComponentData({ dispatch: store.dispatch, components: nextState.routes.map(route => route.component), params: Object.assign({}, nextState.params), location: nextState.location, }); } catch (err) { if (!__PROD__) { window.console.log(err); } } }; function qs(key) { var vars = [], hash; var hashes; // = window.location.href.slice(window.location.href.indexOf('/') + 1).split('/'); if( typeof window!= "undefined") { hashes = window.location.href.slice(window.location.href.indexOf('/') + 1).split('/'); } else { hashes = 'id:57413ffe7a1d3a001111b3ec'; } for(var i = 0; i < hashes.length; i++) { hash = hashes[i].split(':'); vars.push(hash[0]); vars[hash[0]] = hash[1]; } return vars[key]; }
import styled from 'styled-components'; export const CardContainer = styled.View` flex: 1; margin: 8px; background-color: white; shadow-color: #000; shadow-offset: { 7, 0 }; shadow-opacity: 0.1; shadow-radius: 7px; elevation: 7; border-radius: 15px; `; export const CardLabel = styled.Text` text-align: left; font-size: 11px; padding: 8px 8px 0px 8px; font-weight: 700; text-transform: uppercase; `;
//const s = "abcde"; const s = "qwer"; function solution(s) { let answer = ""; if (s.length % 2 == 1) { answer = s[parseInt(s.length / 2)]; } else { answer = s[parseInt(s.length / 2) - 1] + s[parseInt(s.length / 2)]; } return answer; } console.log(solution(s));
import React from "react"; import PropTypes from "prop-types"; import { connect } from "react-redux"; import { deleteUser } from "../../redux/reducers/user"; const ConfirmDeleteModal = props => { const { toggleModal, onDeleteButtonClicked } = props; return ( <div className="container"> <button className="close" onClick={() => toggleModal(false)}> CLOSE </button> <p>Really wanna Delete your account?</p> <button className="close" onClick={onDeleteButtonClicked}> DELETE YOUR ACCOUNT </button> <style jsx>{` .container { position: absolute; top: 20rem; right: 10rem; width: 10rem; height: 10rem; background: gray; } button.close { marginbottom: 1rem; } `}</style> </div> ); }; const mapDispatchToProps = dispatch => { return { onDeleteButtonClicked: () => dispatch(deleteUser()) }; }; ConfirmDeleteModal.propTypes = { toggleModal: PropTypes.func.isRequired, onDeleteButtonClicked: PropTypes.func.isRequired }; export default connect( null, mapDispatchToProps )(ConfirmDeleteModal);
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ $(function () { var validator = $("#contact").validate({ rules: { fname: { required: true, minlength: 4, maxlength: 20 }, email: { required: true, }, mobile: { required: true, digits: true, minlength: 11 }, comment: "required" }, messages: { fname: { required: " *Enter You Name (Required)", }, email: { required: " *Enter Your Email Address (Required)", email: "Please Enter Your Valid Email Address", }, mobile: { required: "*Please Enter Your Mobile Number", minlength: "*Please Enter at least 11 Digit. " } } }); $.validator.methods.email = function (value, element) { return this.optional(element) || /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i.test(value); }; var i = 100; $("textarea").keyup(function () { var txt = $("#txt").val().length; var rem = i - txt; $("span.ts").text(rem + " characters remaining"); $("span.ts").css("color", "red"); $("span.ts").css("font-weight", "bold"); if (rem == 0) { $("span.ts").text("Sorry! You can't enter more than 100 Characters"); } }); });
const añadirExperienciaSchema = require('./añadirExperienciaSchema'); const buscarExperienciaSchema = require('./buscarExperienciaSchema'); const loginRegistroSchema = require('./loginregistroSchema'); module.exports = { añadirExperienciaSchema, buscarExperienciaSchema, loginRegistroSchema }
// console.log('Client side js loaded'); $(function() { //ask the server for songs, and then draw them getSongs(); //listen for submit envents and send new songs to the server // for the first 3 will be post $('form').on('submit', function(event) { event.preventDefault(); var formData = $(this).serialize(); $.ajax({ type: 'POST', url: '/songs', data: formData, success: getSongs }); $(this).find('input[type=text]').val(''); // $('form').submit(function() { // $(this).children('.blank').remove(); // }); }); }); //the last one #4 will be GET (from assignment) //add a gitignore file to homework file// do not add node_modules function getSongs() { $.ajax({ type: 'GET', url: '/songs', success: function(songs) { $('#songs').empty(); songs.forEach(function(song) { var $li = $('<li></li>'); $li.append('<p>' + song.title + '</p>'); $li.append('<p>by: ' + song.artist + '</p>'); $li.append('<p>' + 'date ' + song.dateAdded + '</p>'); $('#songs').append($li); }); } }); }
import React from 'react'; import './Contact.scss'; class Contact extends React.Component { render() { return ( <section id='contact-section'> <h1 className='section-title'>Contact</h1> <hr /> </section> ); } } export default Contact;
const EventEmitter = require('events') const startServer = require('./server') const initDeepspeech = require('./ds') const myEmitter = new EventEmitter() const audioStreamCb = initDeepspeech(myEmitter) startServer(audioStreamCb, myEmitter)
// @ts-check // Note: type annotations allow type checking and IDEs autocompletion const lightCodeTheme = require('prism-react-renderer/themes/github') const darkCodeTheme = require('prism-react-renderer/themes/dracula') /** @type {import('@docusaurus/types').Config} */ const config = { title: 'version-checker', tagline: '🔍 Simple version checker working with GitHub releases and the GitHub API.', url: 'https://axelrindle.github.io', baseUrl: '/github-version-checker/', onBrokenLinks: 'throw', onBrokenMarkdownLinks: 'warn', favicon: 'img/favicon.ico', // GitHub pages deployment config. // If you aren't using GitHub pages, you don't need these. organizationName: 'axelrindle', // Usually your GitHub org/user name. projectName: 'github-version-checker', // Usually your repo name. deploymentBranch: 'main', trailingSlash: true, // Even if you don't use internalization, you can use this field to set useful // metadata like html lang. For example, if your site is Chinese, you may want // to replace "en" with "zh-Hans". i18n: { defaultLocale: 'en', locales: ['en'], }, presets: [ [ 'classic', /** @type {import('@docusaurus/preset-classic').Options} */ ({ docs: { sidebarPath: undefined, versions: { current: { label: '🔜 Next' } }, async sidebarItemsGenerator({ defaultSidebarItemsGenerator, ...args }) { const sidebarItems = await defaultSidebarItemsGenerator(args) const result = sidebarItems.map((item) => { if (item.type === 'category' && item.customProps?.reverse) { return { ...item, items: item.items.reverse() } } return item }) return result }, }, blog: false, theme: { customCss: require.resolve('./src/css/custom.css'), }, }), ], ], plugins: [ [ '@cmfcmf/docusaurus-search-local', { indexBlog: false } ], [ '@docusaurus/plugin-content-docs', { id: 'changelog', path: 'changelog', routeBasePath: 'changelog', async sidebarItemsGenerator({ defaultSidebarItemsGenerator, ...args }) { const sidebarItems = await defaultSidebarItemsGenerator(args) const result = sidebarItems.map((item) => { if (item.type === 'category') { return { ...item, items: item.items.reverse() } } return item }) return result }, }, ], ], themeConfig: /** @type {import('@docusaurus/preset-classic').ThemeConfig} */ ({ navbar: { title: 'version-checker', logo: { alt: 'version-checker logo', src: 'img/logo.svg', }, items: [ { type: 'doc', docId: 'index', position: 'left', label: 'Documentation', }, { type: 'doc', docId: 'index', position: 'left', label: 'Changelog', docsPluginId: 'changelog', }, { type: 'docsVersionDropdown', position: 'right', dropdownItemsAfter: [{ to: '/versions', label: 'All versions' }], }, { href: 'https://github.com/axelrindle/github-version-checker', position: 'right', className: 'nav-icon-link nav-github-link', 'aria-label': 'GitHub', }, { href: 'https://www.npmjs.com/package/@version-checker/core', position: 'right', className: 'nav-icon-link nav-npm-link', 'aria-label': 'npm', }, ], }, footer: { style: 'light', logo: { alt: 'version-checker logo', src: 'img/logo.svg', href: '/', height: 32, }, copyright: `Copyright © ${new Date().getFullYear()} Axel Rindle & Contributors. Built with <a href="https://docusaurus.io/">Docusaurus</a>. Illustrations by <a href="https://undraw.co/">Katerina Limpitsouni</a>.`, }, prism: { theme: lightCodeTheme, darkTheme: darkCodeTheme, }, }), } module.exports = config
let ws = new WebSocket('wss://stream.binance.com:9443/ws/ethusdt@trade'); let cryptoPrice = document.getElementById('crypto-price'); ws.onmessage = (event) => { let crypto = JSON.parse(event.data); cryptoPrice.innerText ='$'+parseFloat(crypto.p) } let wsbtc = new WebSocket('wss://stream.binance.com:9443/ws/btcusdt@trade'); let cryptoPriceBTC = document.getElementById('btc-price'); wsbtc.onmessage = (event) => { let cryptoBtc = JSON.parse(event.data); cryptoPriceBTC.innerText ='$'+parseFloat(cryptoBtc.p) } let wssol = new WebSocket('wss://stream.binance.com:9443/ws/solusdt@trade'); let cryptoPriceSol = document.getElementById('sol-price'); wssol.onmessage = (event) => { let cryptoSol = JSON.parse(event.data); console.log(event.data) cryptoPriceSol.innerText ='$'+parseFloat(cryptoSol.p) } let wsdoge = new WebSocket('wss://stream.binance.com:9443/ws/dogeusdt@trade'); let cryptoPriceDoge = document.getElementById('doge-price'); wsdoge.onmessage = (event) => { let cryptoDoge = JSON.parse(event.data); console.log(event.data) cryptoPriceDoge.innerText ='$'+parseFloat(cryptoDoge.p) } let wscake = new WebSocket('wss://stream.binance.com:9443/ws/cakeusdt@trade'); let cryptoPriceCake = document.getElementById('cake-price'); wscake.onmessage = (event) => { let cryptoCake = JSON.parse(event.data); console.log(event.data) cryptoPriceCake.innerText ='$'+parseFloat(cryptoCake.p) } let wsada = new WebSocket('wss://stream.binance.com:9443/ws/adausdt@trade'); let cryptoPriceAda = document.getElementById('ada-price'); wsada.onmessage = (event) => { let cryptoAda = JSON.parse(event.data); console.log(event.data) cryptoPriceAda.innerText ='$'+parseFloat(cryptoAda.p) }
/* eslint no-console:0 */ import 'chartkick/chart.js' import '../../vendor/assets/javascripts/parallax.min' import '../../vendor/assets/javascripts/jquery.mousewheel' import '../../vendor/assets/javascripts/chosen.jquery' import '../../vendor/assets/javascripts/blowup' import './js/add_child' import './js/buildings' import './js/cell_renderers' import './search/AdvancedSearch' import './js/census_form' import './js/home_page' import './js/terms' import Rails from '@rails/ujs' import './controllers' import './forge' import './miniforge' import { Notifier } from '@airbrake/browser' Rails.start() if (window.airbrakeCreds && window.env === 'production') { const airbrake = new Notifier({ projectId: window.airbrakeCreds.app_id, projectKey: window.airbrakeCreds.api_key, host: window.airbrakeCreds.host }) window.addEventListener('error', (error) => { airbrake.notify({ error }) }) } document.addEventListener('DOMContentLoaded', () => { window.alertifyInit = alertify.init $('[rel=tooltip]').tooltip() pageLoad() }) window.showSubmitButton = function() { document.getElementById('contact-submit-btn').style.display = 'block' } const pageLoad = function() { window.alerts = window.alerts || [] window.alertifyInit() alertify.set({ delay: 10000 }) window.alerts.forEach(function(alert) { alertify[alert[0]](alert[1]) }) window.alerts = [] } jQuery(document).on('click', '.dropdown-item.checkbox', function(e) { e.stopPropagation() }) jQuery(document).on('click', '#search-map', function() { const $form = jQuery(this).closest('form') if (document.location.toString().match(/building/)) { $form.append('<input type="hidden" name="buildings" value="1">') } else { const year = jQuery(this).data('year') $form.append(`<input type="hidden" name="people" value="${year}">`) } $form.attr('action', '/forge') $form.submit() }) function getBuildingList() { let house = $('#census_record_street_house_number').val() if (house === '') house = null let locality_id = jQuery('#census_record_locality_id').val() let street = jQuery('#street_name').val() if (street === '') street = null let prefix = jQuery('#census_record_street_prefix').val() if (street === '') prefix = null let suffix = jQuery('#street_suffix').val() if (street === '') suffix = null if (locality_id && street) { const params = { locality_id, street, prefix, suffix, house } const year = document.location.pathname.split("/")[2] jQuery.getJSON(`/census/${year}/building_autocomplete`, params, function (json) { const building = jQuery('#building_id, #census_record_building_id') const current_value = building.val() let html = '<option value="">Select a building</option>' json.forEach(function (item) { html += `<option value="${item.id}">${item.name}</option>` }) building.html(html) building.val(current_value) $('.census_record_ensure_building').toggle(!building.val().length) }) } } // When the user fills address on census form, this refills the building_id dropdown jQuery(document) .on('change', '#census_record_locality_id, #street_name, #street_suffix, #street_prefix, #street_house_number', getBuildingList) jQuery(function() { const building = jQuery('#building_id, #census_record_building_id') if (building.length) { getBuildingList() $('.census_record_ensure_building').toggle(!building.val().length) } }) .on('change', '#building_id, #census_record_building_id', function() { $('.census_record_ensure_building').toggle(!$(this).val().length) }) let buildingNamed = false jQuery(document).on('ready', function() { buildingNamed = jQuery('#building_name').val() }) jQuery(document).on('change', '#building_address_house_number, #building_address_street_prefix, #building_address_street_name, #building_address_street_suffix', function() { if (buildingNamed) return const buildingName = [jQuery('#building_address_house_number').val(), jQuery('#building_address_street_prefix').val(), jQuery('#building_address_street_name').val(), jQuery('#building_address_street_suffix').val()].join(' ') jQuery('#building_name').val(buildingName) }) window.addEventListener("trix-file-accept", function(event) { event.preventDefault() alert("File attachment not supported!") })
import React from "react"; import styled from "styled-components"; import GetWindowDimensions from "../../../utils/hooks/getWindowDimensions"; const Wrapper = styled.div` position: absolute; width: 569px; height: 569px; user-select: none; transform: translate(2020px, 1645px); border-radius: 20px; border-top: 5px solid #00a666; border-left: 5px solid #00a666; border-bottom: 11px solid #00a666; border-right: 11px solid #00a666; `; const Inner = styled.div` display: flex; flex-direction: column; justify-content: center; align-items: center; width: 100%; height: 100%; border-radius: 15px; background-color: #ffffff; `; const Circle = styled.div` position: absolute; width: 4px; height: 4px; border-radius: 50%; border: 4px solid #00a666; `; const TitleText = styled.div` font-family: "Fredoka One", cursive; color: #00a666; font-size: 240px; border-bottom: 12px solid #fff018; border-radius: 4px; padding-bottom: 16px; padding: 0px 5px; `; const FullText1 = styled.div` font-family: "Fredoka One", cursive; color: #00a666; font-size: 58px; border-bottom: 12px solid #fff018; border-radius: 4px; padding-top: 12px; padding-bottom: 12px; letter-spacing: 11px; padding-left: 11px; `; const FullText2 = styled.div` font-family: "Fredoka One", cursive; color: #00a666; font-size: 58px; padding-top: 16px; letter-spacing: 80px; margin-left: 80px; `; const CenterBox = () => { const { windowWidth, windowHeight } = GetWindowDimensions(); // const { storeName, category, storeImage } = data; // const categoryText = category.replaceAll("|", " / "); // let rank = ""; // if (dataIndex <= 8) { // rank = "0" + (dataIndex + 1); // } else { // rank = dataIndex + 1; // } const onClickHandler = () => { // dispatch({ type: "TOGGLE_POPUP_BOX", dataIndex }); }; return ( <Wrapper onClick={onClickHandler}> <Inner windowWidth={windowWidth} windowHeight={windowHeight}> <Circle style={{ top: 15, left: 20 }}></Circle> <Circle style={{ top: 15, right: 20 }}></Circle> <Circle style={{ bottom: 15, left: 20 }}></Circle> <Circle style={{ bottom: 15, right: 20 }}></Circle> <TitleText>D D</TitleText> <FullText1>DELICIOUS</FullText1> <FullText2>DATA</FullText2> </Inner> </Wrapper> ); }; export default CenterBox;
// const rp = require('request-promise'); // const cheerio = require('cheerio'); // String.prototype.replaceAll = function(search, replacement) { // var target = this; // return target.split(search).join(replacement); // }; // const handler = { // async exec({ m, args }) { // let req = 10; // if (args.length >= 1) req = Number(args[0]); // if (args.length < 1) req = 10 // const url = 'https://www.imdb.com/search/keyword/?keywords=anime%2Cbased-on-manga&ref_=kw_ref_key&sort=moviemeter,asc&mode=detail&page=1'; // try { // const request = await rp(url); // const $ = cheerio.load(request); // let titles = []; // let rates = []; // let genres = []; // $('div[class="lister-list"] > .lister-item > .lister-item-content > .lister-item-header > a').each((i, el) => { // return titles.push($(el).text()) // }); // $('div[class="lister-list"] > .lister-item > .lister-item-content > .ratings-bar > .ratings-imdb-rating').each((i, el) => { // return rates.push($(el).text()) // }); // $('div[class="lister-list"] > .lister-item > .lister-item-content > .text-muted > .genre').each((i, el) => { // return genres.push($(el).text()) // }); // let content = [] // let hr = '\n+============================+\n' // for (let i = 0; i < req; i++) { // content.push(`*Title* : _*${titles[i]}*_\n*Genre* : _*${genres[i].replaceAll('\n', '').replaceAll(' ', '').replaceAll(',', ' | ')}*_\n*Rate* : ⭐_${rates[i].replaceAll('\n', '').replaceAll(' ', '')}_`) // } // m.reply(content.join(hr)) // } catch (err) { // console.log(err) // } // }, // commands: ['', 'list'].map(v => 'anime' + v), // help: ['', 'list'].map(v => '#anime' + v + ' <limit (Max 50, Default 10)>'), // tag: 'Anime' // }; // module.exports = handler
import isPlainObject from 'lodash.isplainobject'; import proxyHandler from './proxy'; if (typeof Proxy === 'undefined') { throw new Error(`Domainer requires the Proxy object. Please consider using the 'proxy-polyfill' package.`) } // function isObject(obj) { // return obj === Object(obj) && !Array.isArray(obj); // } // options: // - plain: doesn't consider the input a domain descriptor export default class Domainer { constructor(input, { plain } = {}) { const proxies = {}; const middleware = []; if (!input) { throw new Error('You must define the `input` of the domain.'); } this._store = { middleware, }; if (!plain && isPlainObject(input)) { for (const name of Object.keys(input)) { proxies[name] = new Proxy(input[name], proxyHandler(middleware)); } this._store.output = proxies; } else { this._store.output = new Proxy(input, proxyHandler(middleware)); } } get export() { // const models = {} // // for (const name of Object.keys(this._store.models)) { // models[name] = new Proxy(this._store.models[name], { // get: proxyHandler(this, CLASS).get, // }); // } // // return models; return this._store.output; } // proxyGetter(target, name) { // const [head, next] = this.middleware; // // return head(next, target, { field: name }); // TODO! missing `context` & `info` // } use(middleware) { // if (typeof middleware !== 'function') { // TODO! check if instanceof Transmutter/Middleware // throw new TypeError('middleware must be a function!'); // } this._store.middleware.push(middleware); return this; } // context(data) { // return new Context(this, data); // } } // resolve(next, root, args, context, info) {
const main_socket = io('/') main_socket.on('ssh', function (ssh_list) { vm.$data.ssh_list = ssh_list }) function export_csv(export_data, filename) { if (!export_data) return; const ssh_list = export_data.map(info => Object.values(info).join('|')) const blob = new Blob([ssh_list.join('\n')], {type: "text/plain;charset=utf-8"}) saveAs(blob, filename) } function import_ssh_text(ssh_text) { vm.$data.ssh_list = ssh_text.split('\n').map(line => { const splitted = line.split('|') return { ip: splitted[0], username: splitted[1], password: splitted[2] } }).filter(ssh => ssh.ip && ssh.username && ssh.password) main_socket.emit('ssh', vm.$data.ssh_list) }
/* * @Author: xiaoguang_10@qq.com * @LastEditors: xiaoguang_10@qq.com * @Date: 2021-06-30 16:16:18 * @LastEditTime: 2021-06-30 19:47:09 */ const { spawn } = require('child_process'); const child = spawn('pwd'); // // 返回ChildProcess对象,默认情况下其上的stdio不为null // const ls = spawn("ls", ["-lh"]); // ls.stderr.on("data", data => { // console.error(`stderr: ${data}`); // }); // ls.stdout.on("data", data => { // console.log(`stdout: ${data}`); // }); // ls.on("close", code => { // console.log(`子进程退出,退出码 ${code}`); // }); // const find = spawn('find', ['.', '-type', 'f']); // const wc = spawn('wc', ['-l']); // find.stdout.pipe(wc.stdin); // wc.stdout.on('data', (data) => { // console.log(`Number of files ${data}`); // }); setTimeout(() => { console.log('timeout'); }, 0); setImmediate(() => { console.log('immediate'); }); Promise.resolve().then(res=>{ console.log('resolve') }) process.nextTick(()=>{ console.log('nextTick') })
//var app = app || {}; app.util = { randomizeBounds : function(upper, lower){ return (Math.random() * (upper-lower) )+lower; }, randomize : function(val){ return Math.random()*val; }, randomizeSigned : function(val){ var num = Math.random()*val; // this will get a number between 1 and 99; num *= Math.floor(Math.random()*2) == 1 ? 1 : -1; return num; }, makeShaderMaterial : function(){ } };
const mobileSlider = document.querySelector('.mobile-slider'); const bannerSlider = document.querySelector('.banner-slider'); function slider() { if (bannerSlider.classList.contains('slick-initialized')) {} else { $('.banner-slider').slick({ centerMode: true, slidesToShow: 1, fade: true, zIndex: 1, dots: true }); } if (window.innerWidth <= 768) { if (mobileSlider.classList.contains('slick-initialized')) { } else { $('.mobile-slider').slick({ centerMode: true, centerPadding: '10px', slidesToShow: 1, arrows: false, variableWidth: true, infinite: false, swipeToSlide: true }); } } else if ((window.innerWidth > 768) && mobileSlider.classList.contains('slick-initialized')) { $('.mobile-slider').slick('unslick'); } } $(document).ready(function() { window.addEventListener('resize', slider); slider(); });
import React, { Component } from 'react'; import './Log.css'; import {Link,Redirect} from "react-router-dom"; class SignUp extends Component { constructor(props) { super(props); this.state = { file: '', imagePreviewUrl: '', fullname:'', email:'', password:'', repass:'', success:'' }; } _handleImageChange(e) { e.preventDefault(); let reader = new FileReader(); let file = e.target.files[0]; reader.onloadend = () => { this.setState({ file: file, imagePreviewUrl: reader.result }); } reader.readAsDataURL(file) } handleName= e => { this.setState({fullname: e.target.value}); }; handleEmail= e => { this.setState({email: e.target.value}); }; handlePassword= e => { this.setState({password: e.target.value}); }; handleRePassword= e => { this.setState({repass: e.target.value}); }; handleRegister=()=>{ if(this.state.fullname!=='' && this.state.email!=='' && this.state.password!=='' && this.state.password===this.state.repass && this.state.file!==''){ let formData = new FormData(); formData.append('email', this.state.email); formData.append('password',this.state.password); formData.append('role_id',1); formData.append('fullname',this.state.fullname); formData.append('gender_id',1); formData.append('avatar_link',this.state.file); fetch("http://0.0.0.0:5000/register", { headers: { "access-control-allow-origin" : "*"}, method: 'POST', body:formData, redirect: 'follow' }) .then((response) => { return response.json(); }) .then((json) => { this.setState({ success:json }); alert(json.message); }); console.log(); }else{alert("Thiếu thông tin hoặc mật khẩu không khớp hoặc thiếu avatar!")} } render() { let { imagePreviewUrl } = this.state; let $imagePreview = null; const isLoggedIn = this.state.success; if (isLoggedIn.message==="Create user successfully." ) { console.log("iamhere") return <Redirect to="/login"/>; } if (imagePreviewUrl) { $imagePreview = (<div className="uploadImg" onChange={(e) => this._handleImageChange(e)}> <img src={imagePreviewUrl} /> <input className="fileInput" type="file" onChange={(e) => this._handleImageChange(e)} /> </div>); } else { $imagePreview = ( <div className="uploadImg" onChange={(e) => this._handleImageChange(e)}> <div className="upload_content"> <i className="fa fa-camera-retro fa-3x"></i> <input className="fileInput" type="file" onChange={(e) => this._handleImageChange(e)} /> </div> </div>); } return ( <div className="container_signup"> <div className="signup-content"> <div className="signup-image"> <div className="previewComponent"> <form onSubmit={(e) => this._handleSubmit(e)}> {$imagePreview} {/* <input className="fileInput" type="file" onChange={(e) => this._handleImageChange(e)} /> */} </form> </div> <p className="signup-question">Bạn đã có tài khoản?</p> <a href="/login" className="signup-image-link">Đăng nhập với tài khoản của bạn</a> <a href="/" className="signup-image-link">Tiếp tục sử dụng ẩn danh</a> </div> <div className="signup-form"> <h2 className="form-title">Đăng Ký</h2> <form method="POST" className="register-form" id="register-form"> <div className="form-group"> <label for="name"><i className="fa fa-user"></i></label> <input className="login" type="text" name="name" id="name" placeholder="Họ và tên" onChange={this.handleName}/> </div> <div className="form-group"> <label for="email"><i className="fa fa-envelope"></i></label> <input className="login" type="email" name="email" id="email" placeholder="Email" onChange={this.handleEmail}/> </div> <div className="form-group"> <label for="pass"><i className="fa fa-lock"></i></label> <input className="login" type="password" name="pass" id="pass" placeholder="Mật khẩu" onChange={this.handlePassword} /> </div> <div className="form-group"> <label for="re-pass"><i className="fa fa-lock"></i></label> <input className="login" type="password" name="re_pass" id="re_pass" placeholder="Xác nhận lại mật khẩu" onChange={this.handleRePassword}/> </div> <div className="form-group"> <input className="login" type="checkbox" name="agree-term" id="agree-term" className="agree-term" /> <label for="agree-term" className="label-agree-term"><span><span></span></span> Bạn chấp nhận với tất cả <a href="#" className="term-service">điều khoản dịch vụ</a></label> </div> <div className="form-group form-btn"> <input className="login" name="signup" id="signup" className="form-submit btn" value="Đăng ký" onClick={this.handleRegister}/> </div> </form> </div> </div> </div> ) } } export default SignUp;
import headerImage from "../assets/img/header-image.jpg"; const RestaurantPresentation = ({ restInfo }) => { return ( <div className="Restaurant-presentation container"> <div className="Restaurant-description"> <h1>{restInfo.name}</h1> <p>{restInfo.description}</p> </div> <div className="Restaurant-image"> <img src={headerImage} alt="table-restaurant" /> </div> </div> ); }; export default RestaurantPresentation;
export default function solitary(PrivateClass) { // stores const pvtMap = new WeakMap(); const pubMap = new WeakMap(); return { pvt: (pubObj) => { // check if we have pvtObj in map already if(!pvtMap.has(pubObj)) { // create pvtObj from PrivateClass const pvtObj = new PrivateClass(pubObj); // update maps pvtMap.set(pubObj, pvtObj); pubMap.set(pvtObj, pubObj); } // get pvtObj from map return pvtMap.get(pubObj); }, pub: (pvtObj) => { // bail out if there is no public object if(!pubMap.has(pvtObj)) { throw new Error('no public object available'); } // get pubObj from map return pubMap.get(pvtObj); } }; };
import React from 'react' import ReactDOM from 'react-dom' import TestUtils from 'react-dom/test-utils' import Plugins from '../../pages/plugins.js' describe('Plugins', () => { it('renders the page', () => { let page = TestUtils.renderIntoDocument(<Plugins />) let body = ReactDOM.findDOMNode(page).textContent expect(body).toContain('robust ecosystem') }) })
const commonFunction = require("../../functions/commonFunctions") const videoModel = require("../../models/videos") const movieModel = require("../../models/movies") const playlistModel = require("../../models/playlists") const blogModel = require("../../models/blogs") const userModel = require("../../models/users"), fieldErrors = require('../../functions/error'), bcrypt = require('bcryptjs'), errorCodes = require("../../functions/statusCodes"), constant = require("../../functions/constant"), globalModel = require("../../models/globalModel"), channelModel = require("../../models/channels"), privacyModel = require("../../models/privacy"), recurringModel = require("../../functions/ipnsFunctions/channelSupportSubscriptions"), dateTime = require("node-datetime"), videoMonetizationModel = require("../../models/videoMonetizations"), { validationResult } = require('express-validator'), socketio = require("../../socket") uniqid = require('uniqid'), {readS3Image} = require('../../functions/upload') exports.browse = async (req,res) => { const queryString = req.query const limit = 21 const data = {} let page = 1 if (req.params.page == '') { page = 1; } else { //parse int Convert String to number page = parseInt(req.body.page) ? parseInt(req.body.page) : 1; } let offset = (page - 1) * (limit - 1) data.limit = limit data.offset = offset if(queryString.type) data['type'] = queryString.type if (queryString.q && !queryString.tag) { data['title'] = queryString.q } if (queryString.sort == "latest") { data['orderby'] = "users.user_id desc" } else if (queryString.sort == "favourite" && req.appSettings['member_favourite'] == 1) { data['orderby'] = "userdetails.favourite_count desc" } else if (queryString.sort == "view") { data['orderby'] = "userdetails.view_count desc" } else if (queryString.sort == "like" && req.appSettings['member_like'] == "1") { data['orderby'] = "userdetails.like_count desc" } else if (queryString.sort == "dislike" && req.appSettings['member_dislike'] == "1") { data['orderby'] = "userdetails.dislike_count desc" } else if (queryString.sort == "rated" && req.appSettings['member_rating'] == "1") { data['orderby'] = "userdetails.rating desc" } else if (queryString.sort == "commented" && req.appSettings['member_comment'] == "1") { data['orderby'] = "userdetails.comment_count desc" } if (queryString.type == "featured" && req.appSettings['member_featured'] == 1) { data['is_featured'] = 1 } else if (queryString.type == "sponsored" && req.appSettings['member_sponsored'] == 1) { data['is_sponsored'] = 1 } else if (queryString.type == "hot" && req.appSettings['member_hot'] == 1) { data['is_hot'] = 1 } let members = {} //get all members await userModel.getMembers(req, data).then(result => { let pagging = false if (result) { pagging = false if (result.length > limit - 1) { result = result.splice(0, limit - 1); pagging = true } members = { pagging: pagging, members: result } } }).catch(err => { console.log(err) }) res.send(members) } exports.language = async(req,res,next) => { let language = req.body.code; if(req.user){ await globalModel.update(req, { language: language }, "userdetails", 'user_id', req.user.user_id).then(result => { }); } res.send(true) } exports.adult = async(req,res,next) => { let adult = req.body.adult == 1 ? true : false; if(req.user){ await globalModel.update(req, { adult: adult ? 1 : 0 }, "users", 'user_id', req.user.user_id).then(result => { }); } req.session.adult_allow = adult res.send(true) } exports.stripekey = async(req,res) => { return res.send({stripekey:req.appSettings['payment_stripe_publish_key']}) } exports.mode = async(req,res) => { req.session.siteMode = req.body.mode == 'dark' ? "dark" : "white"; res.send(true) } exports.newsletter = async (req,res) => { const errors = validationResult(req); if (!errors.isEmpty()) { return res.send({ error: fieldErrors.errors(errors), status: errorCodes.invalid }).end(); } userModel.newsletter({email:req.body.email},req).then(result => { if(result){ return res.send({ message: constant.member.NEWSLETTERSUCCESS, status: errorCodes.ok }).end(); }else{ return res.send({ error: constant.general.DATABSE, status: errorCodes.invalid }).end(); } }) } exports.createWithdraw = async(req,res) => { const errors = validationResult(req); if (!errors.isEmpty()) { return res.send({ error: fieldErrors.errors(errors), status: errorCodes.invalid }).end(); } let user_id = parseInt(req.body.owner_id) let data = {} data.limit = 1 data.owner_id = user_id data.status = "0" var isExists = false await videoMonetizationModel.getWithdraw(req, data).then(result => { if (result && result.length > 0) { isExists = true } }) if(isExists){ return res.send({ error: fieldErrors.errors([{ msg: constant.video.WITHDRAWREQPREVIOUSERROR }], true), status: errorCodes.invalid }).end(); } let user = req.item let isValid = true let monetization_threshold_amount = req.levelPermissions['member.monetization_threshold_amount'] if(req.user.user_id != user_id){ const permissionModel = require("../models/levelPermissions") await permissionModel.findBykey(req,"member",'monetization',user.level_id).then(result => { if(result && result == 1){ isValid = true } }) await permissionModel.findBykey(req,"member",'monetization_threshold_amount',user.level_id).then(result => { monetization_threshold_amount = result }) }else{ if(req.levelPermissions["member.monetization"] == 1){ isValid = true } } let balance = req.item.balance let amount = req.body.amount if(!isValid){ //error return res.send({ error: fieldErrors.errors([{ msg: constant.general.INVALIDREQUEST }], true), status: errorCodes.invalid }).end(); } if(parseFloat(balance) < parseFloat(amount) || parseFloat(monetization_threshold_amount) > parseFloat(amount)){ return res.send({ error: fieldErrors.errors([{ msg: constant.video.WITHDRAWREQERROR }], true), status: errorCodes.invalid }).end(); } await globalModel.create(req, {owner_id:parseInt(req.body.owner_id),email:req.body.paypal_email,amount:amount,status:0, creation_date: dateTime.create().format("Y-m-d H:M:S") }, "video_monetizations_withdrawals").then(result => { if (result) { return res.send({ message: constant.member.VERIFICATIONREQUESTSEND, status: errorCodes.ok }).end(); } }).catch(error => { return res.send({ error: constant.general.DATABSE, status: errorCodes.invalid }).end(); }); } exports.withdrawDelete = async(req,res) => { const owner_id = req.body.user_id globalModel.custom(req,"DELETE FROM video_monetizations_withdrawals WHERE withdraw_id = ? AND owner_id = ?",[req.body.withdraw_id,owner_id]).then(result => { if(result){ return res.send({ message: constant.video.WITHDRAWREQDELETE, status: errorCodes.ok }).end(); }else{ return res.send({ error: constant.general.DATABSE, status: errorCodes.invalid }).end(); } }) }; exports.withdraws = async(req,res) => { const owner_id = parseInt(req.body.owner_id) if (!owner_id) { return res.send({}) } let LimitNum = 21; let page = 1 if (req.params.page == '') { page = 1; } else { //parse int Convert String to number page = parseInt(req.body.page) ? parseInt(req.body.page) : 1; } let offset = (page - 1) * (LimitNum - 1) let video = {} let data = {} data.limit = LimitNum data.offset = offset data.owner_id = owner_id if (req.query.status) { if(req.query.status > 2 && req.query.status < 0){ req.query.status = ""; } data['status'] = req.query.status } await videoMonetizationModel.getWithdraw(req, data).then(result => { let pagging = false if (result) { pagging = false if (result.length > LimitNum - 1) { result = result.splice(0, LimitNum - 1); pagging = true } video = { pagging: pagging, items: result } } }) res.send(video) } exports.monetization = async(req,res) => { let monetization = req.body.monetization if(typeof monetization == "undefined"){ monetization = 0 } if(req.item){ if(req.appSettings['autoapprove_monetization'] == 0 && req.item.monetization == 0){ await globalModel.update(req, { monetization_request: 1 }, "users", 'user_id', req.item.user_id).then(result => { return res.send({ message: constant.member.MONETIZATIONREQUESTSEND,request:1, status: errorCodes.ok }).end(); }); }else{ await globalModel.update(req, { monetization: monetization }, "users", 'user_id', req.item.user_id).then(result => { return res.send({ message: constant.member.MONETIZATIONREQUEST, status: errorCodes.ok }).end(); }); } }else{ res.send({}) } } exports.repositionCover = async (req, res) => { const user_id = req.body.user_id if (user_id) { userModel.findById(user_id, req, res).then(async member => { if (member) { if (member.cover) { const path = require("path") const imageName = "resize_"+uniqid.process('c')+path.basename(member.cover) let image = member.cover; if (req.appSettings.upload_system == "s3" || req.appSettings.upload_system == "wisabi") { //image = "https://" + req.appSettings.s3_bucket + ".s3.amazonaws.com"+image; const imageS = req.serverDirectoryPath const newimage = imageS+"/public/upload/"+imageName await readS3Image(req,member.cover,newimage).then(result => { image = result }).catch(err => { }) }else{ image = req.serverDirectoryPath+"/public"+member.cover } let data = {} data['type'] = "members" data['imageName'] = imageName data['y'] = Math.abs(req.body.position) data['path'] = "/upload/images/cover/members/"+data.imageName data['screenWidth'] = req.body.screenWidth ? req.body.screenWidth : 1200 const coverReposition = require("../../functions/coverCrop") coverReposition.crop(req,data,image).then(result => { if(result){ globalModel.update(req, { cover_crop: data['path'] }, "userdetails", 'user_id', user_id).then(result => { if (member.cover_crop) { commonFunction.deleteImage(req, res, member.cover_crop, 'member/cover'); } if (req.appSettings.upload_system == "s3" || req.appSettings.upload_system == "wisabi") { const fs = require("fs") fs.unlink(image, function (err) { }); } socketio.getIO().emit('userCoverReposition', { "user_id": user_id, "message": constant.member.COVERREPOSITION, image: data['path'] }); }); } }).catch(err => { console.log(err,'Reposition image errror') }) } } }) } res.send({}) } exports.uploadCover = async (req, res) => { if (req.imageError) { return res.send({ error: fieldErrors.errors([{ msg: req.imageError }], true), status: errorCodes.invalid }).end(); } const user_id = req.body.user_id if (user_id) { userModel.findById(user_id, req, res).then(member => { if (member) { if (req.fileName) { let image = "" let cover = "" if (req.file && req.appSettings.upload_system != "s3" && req.appSettings.upload_system != "wisabi") { image = "/upload/images/cover/members/" + req.originalUrl; cover_crop = "/upload/images/cover/members/" + req.fileName; }else{ image = "/" + req.originalUrl; cover_crop = "/" + req.fileName; } globalModel.update(req, { cover: image,cover_crop:cover_crop }, "userdetails", 'user_id', user_id).then(result => { if (member.cover_crop) { commonFunction.deleteImage(req, res, member.cover_crop, 'member/covercrop'); } if (member.usercover) { commonFunction.deleteImage(req, res, member.cover, 'member/cover'); } socketio.getIO().emit('userCoverUpdated', { "user_id": user_id, "message": constant.member.COVERUPLOADED, image: image, cover_crop:cover_crop }); }); } } }) } res.send({}) } exports.uploadMainPhoto = async (req, res) => { if (req.imageError) { return res.send({ error: fieldErrors.errors([{ msg: req.imageError }], true), status: errorCodes.invalid }).end(); } const user_id = req.body.user_id if (user_id) { userModel.findById(user_id, req, res).then(member => { if (member) { if (req.fileName) { let image = "/upload/images/members/" + req.fileName; globalModel.update(req, { avtar: image }, "userdetails", 'user_id', user_id).then(result => { if (member.userimage) { commonFunction.deleteImage(req, res, member.avtar, 'member/image'); } socketio.getIO().emit('userMainPhotoUpdated', { "user_id": user_id, "message": constant.member.MAINPHOTOUPLOADED, image: image }); }); } } }) } if(!req.headersSent) res.send({}) } exports.verification = async (req, res) => { if (req.imageError) { return res.send({ error: fieldErrors.errors([{ msg: req.imageError }], true), status: errorCodes.invalid }).end(); } if (!req.fileName) { return res.send({ error: constant.member.UPLOADVERIFICATIONIMAGE, status: errorCodes.invalid }).end(); } const user_id = req.body.user_id if (user_id) { await userModel.findById(user_id, req, res).then(async member => { if (member) { if (req.fileName) { let image = "/upload/images/members/verifications/" + req.fileName; await globalModel.create(req, { name: member.displayname, media: image, description: req.body.description, owner_id: user_id, creation_date: dateTime.create().format("Y-m-d H:M:S") }, "verification_requests").then(result => { if (result) { return res.send({ message: constant.member.VERIFICATIONREQUESTSEND, status: errorCodes.invalid }).end(); } }).catch(error => { return res.send({ error: constant.general.DATABSE, status: errorCodes.invalid }).end(); }); } } }) } if(!req.headersSent) res.send({}) } exports.password = async (req, res) => { const id = req.body.user_id if (!req.item) { res.send({}) } const password = req.body.old_password const newpass = req.body.new_password bcrypt .compare(password, req.item.password) .then(doMatch => { if (doMatch) { bcrypt .hash(newpass, 12) .then(async hashedPassword => { await globalModel.update(req, { password: hashedPassword }, "users", 'user_id', id).then(result => { if (result) { return res.send({ message: constant.member.PASSWORDCHANGED, status: errorCodes.ok }).end(); } else { return res.send({ error: constant.general.DATABSE, status: errorCodes.invalid }).end(); } }); }) } else { return res.send({ error: fieldErrors.errors([{ msg: constant.member.PASSWORDNOTMATCH }], true), status: errorCodes.invalid }).end(); } }).catch(error => { return res.send({ error: fieldErrors.errors([{ msg: constant.member.PASSWORDNOTMATCH }], true), status: errorCodes.invalid }).end(); }); if(!req.headersSent) res.send({}) } exports.delete = async (req, res) => { const id = req.body.user_id if (!req.item) { res.send({}) } if (!req.item) { res.send({}) } const errors = validationResult(req); if (!errors.isEmpty()) { return res.send({ error: fieldErrors.errors([{ msg: constant.auth.VALID_PASSWORD }], true), status: errorCodes.invalid }).end(); } const password = req.body.password bcrypt .compare(password, req.item.password) .then(async doMatch => { if (doMatch) { await userModel.delete(req, id).then(result => { if (result) { if (req.item.cover_crop ) { commonFunction.deleteImage(req, res, req.item.cover_crop, 'member/covercrop'); } if (req.item.usercover) { commonFunction.deleteImage(req, res, req.item.cover, 'member/cover'); } if (req.item.userimage) { commonFunction.deleteImage(req, res, req.item.avtar, 'member/avtar'); } if (req.session.user && req.user.user_id == req.item.user_id) { res.clearCookie('SESSIONUUID'); } socketio.getIO().emit('userDeleted', { "user_id": id, "message": constant.member.DELETED, }); } return res.send({}) }) } else { return res.send({ error: fieldErrors.errors([{ msg: constant.member.PASSWORDINVALID }], true), status: errorCodes.invalid }).end(); } }).catch(error => { return res.send({ error: fieldErrors.errors([{ msg: constant.member.PASSWORDINVALID }], true), status: errorCodes.invalid }).end(); }); } exports.edit = async (req, res) => { const id = req.body.user_id if (!req.item) { res.send({}) } const errors = validationResult(req); if(typeof req.body.first_name == "undefined"){ if (!errors.isEmpty()) { return res.send({ error: fieldErrors.errors(errors), status: errorCodes.invalid }).end(); } } if(req.body.profile == 1){ if(!req.body.first_name && (req.body.first_name && !req.body.first_name.trim())){ return res.send({ error: fieldErrors.errors([{ msg: "First Name should not be empty!" }], true), status: errorCodes.invalid }).end(); } } let data = {} let userData = {} if (req.body.username) { data.username = req.body.username } if (req.body.email) { userData.email = req.body.email } if (req.body.gender) { data.gender = req.body.gender } if (typeof req.body.active != "undefined" && req.user.level_id == 1) { userData.active = req.body.active } if(typeof req.body.first_name == "undefined"){ if(req.body.whitelist_domain){ userData.whitelist_domain = req.body.whitelist_domain }else{ userData.whitelist_domain = null; } if(req.body.phone_number){ userData.phone_number = req.body.phone_number }else{ userData.phone_number = null } } if (req.body.paypal_email) { userData.paypal_email = req.body.paypal_email const pattern = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; if (!pattern.test(userData.paypal_email)) { //invalid email return res.send({ error: constant.member.INVALIDPAYPALEMAIL, status: errorCodes.invalid }).end(); } } if(req.body.email){ userData.email = req.body.email } if (req.body.level_id && req.user.level_id == 1) { userData.level_id = req.body.level_id } if (typeof req.body.verified != "undefined" && req.user.level_id == 1) { data.verified = req.body.verified } if (typeof req.body.search != "undefined") { if (req.body.search) data.search = req.body.search else data.search = 0 } if (req.body.age) { data.age = req.body.age } let userTitle = [] userTitle['first_name'] = req.item.first_name userTitle['last_name'] = req.item.last_name ? req.item.last_name : "" if (req.body.first_name) { data.first_name = req.body.first_name userTitle['first_name'] = req.body.first_name } if (req.body.last_name) { data.last_name = req.body.last_name userTitle['last_name'] = req.body.last_name }else if(req.body.profile == 1){ if(!req.body.last_name){ data.last_name = "" userTitle['last_name'] = "" } } data.displayname = userTitle['first_name']+" "+userTitle['last_name'] if(req.body.profile == 1){ if (req.body.about) { data.about = req.body.about }else{ data.about = "" } if (req.body.facebook) { data.facebook = req.body.facebook }else{ data.facebook = "" } if (req.body.instagram) { data.instagram = req.body.instagram }else{ data.instagram = "" } if (req.body.pinterest) { data.pinterest = req.body.pinterest }else{ data.pinterest = "" } if (req.body.twitter) { data.twitter = req.body.twitter }else{ data.twitter = "" } }else{ if(req.body.timezone) userData.timezone = req.body.timezone } if(typeof req.body.comments != "undefined"){ data['autoapprove_comments'] = parseInt(req.body.comments) } if(Object.keys(userData).length){ await globalModel.update(req, userData, "users", 'user_id', id).then(result => { if (!result) { return res.send({ error: constant.general.DATABSE, status: errorCodes.invalid }).end(); } else { } }); } await globalModel.update(req, data, "userdetails", 'user_id', id).then(result => { if (result) { return res.send({ message: constant.member.PROFILEUPDATED, status: errorCodes.ok }).end(); } else { return res.send({ error: constant.general.DATABSE, status: errorCodes.invalid }).end(); } }); if(!res.headersSent) res.send({}) } exports.deletePlan = async (req,res) => { const plan_id = parseInt(req.body.plan_id) let sql = "DELETE FROM member_plans WHERE member_plan_id = ?" let condition = [plan_id] if(req.user.level_id != 1){ condition.push(req.user.user_id) sql += " AND owner_id = ?" } globalModel.custom(req,sql,condition).then(async result => { if(result.affectedRows == 1){ //get plan subscriptions await globalModel.custom(req,"SELECT * FROM subscriptions WHERE package_id = ? AND type = ?",[plan_id,"user_subscribe"]).then(async result => { let subscriptions = JSON.parse(JSON.stringify(result)); if(subscriptions && subscriptions.length){ //update all plan subscriptions await globalModel.custom(req,"UPDATE subscriptions SET status = 'cancelled' WHERE package_id = ? AND type = ?",[plan_id,"user_subscribe"]).then(res => {}) subscriptions.forEach(sub => { recurringModel.cancelParticular(sub,"cancelled"); }); } }) } res.send({ member_plan_id: plan_id,type:"delete", message: constant.member.PLANDELETE }); }) } exports.getSubscribers = async (req,res) => { const owner_id = parseInt(req.body.owner_id) if (!owner_id) { return res.send({}) } let LimitNum = 12; let page = 1 if (req.params.page == '') { page = 1; } else { //parse int Convert String to number page = parseInt(req.body.page) ? parseInt(req.body.page) : 1; } let offsetArtist = (page - 1) * LimitNum let member = {} await userModel.getSubscribers(req,{user_id:owner_id, limit: LimitNum, offset:offsetArtist,member_plan_id:req.body.plan_id}).then(result => { let pagging = false if (result) { pagging = false if (result.length > LimitNum - 1) { result = result.splice(0, LimitNum - 1); pagging = true } member = { pagging: pagging, members: result } } }).catch(error => { console.log(error) }) res.send(member) } exports.getVideos = async (req, res) => { const owner_id = parseInt(req.body.owner_id) if (!owner_id) { return res.send({}) } let LimitNum = 21; let page = 1 if (req.params.page == '') { page = 1; } else { //parse int Convert String to number page = parseInt(req.body.page) ? parseInt(req.body.page) : 1; } let offset = (page - 1) * (LimitNum - 1) let video = {} let data = {} data.limit = LimitNum data.offset = offset data.owner_id = owner_id if(req.body.paidVideos){ data.user_sell_home_content = true; } if(req.body.liveVideos){ data.is_live_videos = true; } await videoModel.getVideos(req, data).then(result => { let pagging = false if (result) { pagging = false if (result.length > LimitNum - 1) { result = result.splice(0, LimitNum - 1); pagging = true } video = { pagging: pagging, videos: result } } }) res.send(video) } exports.getMovies = async (req, res) => { const owner_id = parseInt(req.body.owner_id) if (!owner_id) { return res.send({}) } let LimitNum = 21; let page = 1 if (req.params.page == '') { page = 1; } else { //parse int Convert String to number page = parseInt(req.body.page) ? parseInt(req.body.page) : 1; } let offset = (page - 1) * (LimitNum - 1) let movies = {} let data = {} data.limit = LimitNum data.offset = offset data.owner_id = owner_id req.contentType = req.body.type await movieModel.getMovies(req, data).then(result => { let pagging = false if (result) { pagging = false if (result.length > LimitNum - 1) { result = result.splice(0, LimitNum - 1); pagging = true } movies = { pagging: pagging, movies: result } } }) res.send(movies) } exports.getChannels = async (req, res) => { const owner_id = parseInt(req.body.owner_id) if (!owner_id) { return res.send({}) } let LimitNum = 21; let page = 1 if (req.params.page == '') { page = 1; } else { //parse int Convert String to number page = parseInt(req.body.page) ? parseInt(req.body.page) : 1; } let offset = (page - 1) * (LimitNum - 1) let channel = {} let data = {} data.limit = LimitNum data.offset = offset data.owner_id = owner_id await channelModel.getChannels(req, data).then(result => { let pagging = false if (result) { pagging = false if (result.length > LimitNum - 1) { result = result.splice(0, LimitNum - 1); pagging = true } channel = { pagging: pagging, channels: result } } }) res.send(channel) } exports.otp = async (req,res) => { let email = req.body.email let phone = req.body.phone let type = req.body.type ? req.body.type : "signup" if(req.appSettings['twillio_enable'] != 1){ return res.send({}) } var isValid = true let condition = [] condition.push(phone) let sql = "SELECT phone_number from users where phone_number = ?" if(req.body.user_id){ condition.push(req.body.user_id) sql += " AND user_id != ?" } if(type != "delete"){ //check phone exists await globalModel.custom(req,sql,condition).then(result => { if(type != "forgot"){ if(result && result.length){ isValid = false } }else{ if(!result || result.length == 0){ isValid = false } } }) }else{ isValid = true } if(!isValid && type != "login" && type != "verification"){ socketio.getIO().emit('otpCode', { "error": req.i18n.t(type != "forgot" ? "Phone Number already taken." : "A user account with that phone number was not found."), "email": email, "phone" :phone }); res.send({}) return } if(phone){ await commonFunction.otp(req,{type:type,phone:phone}).then(async message => { let insertObj = {} insertObj["code"] = message.code insertObj["phone_number"] = phone insertObj["type"] = type await globalModel.create(req, insertObj, 'otp_code').then(async result => {}) if(process.env.NODE_ENV != "production") console.log(message) socketio.getIO().emit('otpCode', { "code": message.code, "email": email, "phone" :phone }); }).catch(err => { console.log(err,"errrrr") }) res.send({}) }else{ res.send({}) } } exports.createPlan = async (req , res) => { if (req.imageError) { return res.send({ error: fieldErrors.errors([{ msg: req.imageError }], true), status: errorCodes.invalid }).end(); } let plan_id = req.body.plan_id const errors = validationResult(req); if (!errors.isEmpty()) { return res.send({ error: fieldErrors.errors(errors), status: errorCodes.invalid }).end(); } // all set now let insertObject = {} let planObject = {} if (parseInt(plan_id) > 0) { //uploaded await globalModel.custom(req, "SELECT * FROM member_plans WHERE member_plan_id = ?", plan_id).then(async result => { if (result) { planObject = JSON.parse(JSON.stringify(result))[0]; await privacyModel.permission(req, 'member', 'edit', planObject).then(result => { if(!result){ plan_id = null planObject = null } }).catch(err => { plan_id = null }) } }).catch(err => { plan_id = null }) } else { insertObject["owner_id"] = req.user.user_id; } insertObject["title"] = req.body.title insertObject["description"] = req.body.description ? req.body.description : "" insertObject["video_categories"] = req.body.video_categories ? req.body.video_categories : null if (req.fileName) { insertObject['image'] = "/upload/images/plans/" + req.fileName; if(Object.keys(planObject).length && planObject.image) commonFunction.deleteImage(req, res, planObject.image, 'plan/image'); }else if(!req.body.planImage){ insertObject['image'] = ""; if(Object.keys(planObject).length && planObject.image) commonFunction.deleteImage(req, res, planObject.image, 'plan/image'); } var dt = dateTime.create(); var formatted = dt.format('Y-m-d H:M:S'); if (!plan_id) { insertObject["creation_date"] = formatted insertObject['price'] = parseFloat(req.body.price) } insertObject["modified_date"] = formatted if (plan_id) { await globalModel.update(req, insertObject, "member_plans", 'member_plan_id', plan_id).then(async result => { let item = {} await userModel.getPlans(req,{member_plan_id:plan_id}).then(result => { if(result){ item = result[0] } }) res.send({ member_plan_id: plan_id,type:"edit", message: constant.member.PLANEDIT, item: item }); }).catch(err => { return res.send({ error: fieldErrors.errors([{ msg: constant.general.DATABSE }], true), status: errorCodes.invalid }).end(); }) } else { await globalModel.create(req, insertObject, "member_plans").then(async result => { if (result) { let item = {} await userModel.getPlans(req,{member_plan_id:result.insertId}).then(result => { if(result){ item = result[0] } }) res.send({ member_plan_id: result.insertId,type:"create", message: constant.member.PLANCREATE, item: item }); } else { return res.send({ error: fieldErrors.errors([{ msg: constant.general.DATABSE }], true), status: errorCodes.invalid }).end(); } }).catch(err => { return res.send({ error: fieldErrors.errors([{ msg: constant.general.DATABSE }], true), status: errorCodes.invalid }).end(); }) } } exports.bankdetails = async(req,res) => { const errors = validationResult(req); if (!errors.isEmpty()) { return res.send({ error: fieldErrors.errors(errors), status: errorCodes.invalid }).end(); } if (!req.fileName) { return res.send({ error: "Please upload file.", status: errorCodes.invalid }).end(); } let resource_type = req.body.resource_type let insertData = {} insertData['price'] = req.body.price insertData['currency'] = req.appSettings.payment_default_currency insertData['resource_id'] = req.body.resource_id insertData['resource_type'] = resource_type insertData['type'] = req.body.type insertData['status'] = 0 insertData['owner_id'] = req.user.user_id insertData['creation_date'] = dateTime.create().format("Y-m-d H:M:S") insertData['approve_date'] = dateTime.create().format("Y-m-d H:M:S") if(req.body.package_id){ insertData['package_id'] = req.body.package_id } if (req.fileName) { insertData['image'] = "/upload/images/members/bankdetails/" + req.fileName; } await globalModel.create(req, insertData, "bankdetails").then(result => { if (result) { res.send({status:1}); }else{ return res.send({ error: constant.general.DATABSE, status: errorCodes.invalid }).end(); } }); } exports.redeemPoints = async(req,res) => { let points = req.body.points let userPoints = req.user.points if(parseFloat(points) == 0 || parseFloat(userPoints) == 0 || parseFloat(points) > parseFloat(userPoints)){ return res.send({ error: constant.general.POINTSINVALID, status: errorCodes.invalid }).end(); } let balance = parseFloat(points) / parseFloat(req.appSettings['points_value']); await globalModel.custom(req, "SELECT wallet FROM users WHERE user_id = ?", [req.user.user_id]).then(async result => { if (result) { const walletData = (parseFloat(JSON.parse(JSON.stringify(result))[0].wallet) + balance).toFixed(2); let currentDate = dateTime.create().format("Y-m-d H:M:S") //update user points balance await globalModel.update(req, { points: userPoints - points }, "users", "user_id", req.user.user_id).then(async result => {}) //update user wallet amount await globalModel.update(req, { wallet: walletData }, "users", "user_id", req.user.user_id).then(async result => { if (result) { return res.send({ success: constant.general.POINTSTRANSFER }).end(); // await globalModel.create(req, {order_id:0,subscription_id:0,type:"point_transfer",id:req.user.user_id,package_id:0,admin_commission:0, gateway_transaction_id: 0, owner_id: req.user.user_id, state: "active", price: parseFloat(balance).toFixed(2), currency: req.appSettings.payment_default_currency, creation_date: currentDate, modified_date: currentDate }, "transactions").then(async result => { // //update order table // }) } else { return res.send({ error: constant.general.DATABSE, status: errorCodes.invalid }).end(); } }) } else { return res.send({ error: constant.general.DATABSE, status: errorCodes.invalid }).end(); } }) } exports.getPlaylists = async (req, res) => { const owner_id = parseInt(req.body.owner_id) if (!owner_id) { return res.send({}) } let LimitNum = 17; let page = 1 if (req.params.page == '') { page = 1; } else { //parse int Convert String to number page = parseInt(req.body.page) ? parseInt(req.body.page) : 1; } let offset = (page - 1) * (LimitNum - 1) let playlist = {} let data = {} data.limit = LimitNum data.offset = offset data.owner_id = owner_id await playlistModel.getPlaylists(req, data).then(result => { let pagging = false if (result) { pagging = false if (result.length > LimitNum - 1) { result = result.splice(0, LimitNum - 1); pagging = true } playlist = { pagging: pagging, playlists: result } } }) res.send(playlist) } exports.getBlogs = async (req, res) => { const owner_id = parseInt(req.body.owner_id) if (!owner_id) { return res.send({}) } let LimitNum = 21; let page = 1 if (req.params.page == '') { page = 1; } else { //parse int Convert String to number page = parseInt(req.body.page) ? parseInt(req.body.page) : 1; } let offset = (page - 1) * (LimitNum - 1) let blog = {} let data = {} data.limit = LimitNum data.offset = offset data.owner_id = owner_id await blogModel.getBlogs(req, data).then(result => { let pagging = false if (result) { pagging = false if (result.length > LimitNum - 1) { result = result.splice(0, LimitNum - 1); pagging = true } blog = { pagging: pagging, blogs: result } } }) res.send(blog) }
/** * @ngdoc module * @module app * @name app * * @description * Main Application Module */ (function (angular) { 'use strict'; angular.module('app', [ 'ui.router', 'ngMaterial', 'ngMessages', 'shared' ]) .run(['$rootScope', '$state', '$stateParams', function ($rootScope, $state, $stateParams) { $rootScope.$state = $state; $rootScope.$stateParams = $stateParams; }]) // Location configuration .config(['$locationProvider', function ($locationProvider) { $locationProvider.html5Mode(true); //enabling html5 mode }]) .config(['$mdThemingProvider', function ($mdThemingProvider) { $mdThemingProvider.theme('default') .primaryPalette('light-blue') .accentPalette('orange'); }]) .config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) { // Configuration of URL routes $urlRouterProvider.otherwise("/login"); $stateProvider .state('main', { url: '/', component: 'main' }) .state('flight_data', { url: '/flight-data?limitAirlines&noOfFlights', params: { limitAirlines: null, noOfFlights: null }, component: 'flightDetails' }) .state('daily_energy', { url: '/daily-energy', component: 'dailyEnergy' }) .state('council_spending', { url: '/council-spending', component: '' }) } ]) })(angular);
/** * Area-地区 */ Ext.define('ESSM.model.dict.Area',{ extend: 'Ext.data.Model', fields: [ {name: 'code', type: 'int'}, {name: 'name', type: 'string'}, {name: 'parentCode', type: 'int'}, {name: 'level', type: 'int'} ] });
import React, { useEffect } from 'react'; import { Container, Button, Row, Col } from 'react-bootstrap'; import { useConfig } from '../../utils/useConfig'; import { useSocket } from '../../utils/useSocket'; import GameAreaActions from './GameAreaActions'; import Collapsable from './Collapsable'; import ForbiddenAreaActions from './ForbiddenAreaActions'; import PlayerActions from './PlayerActions'; import FlagActions from './FlagActions'; import ItemActions from './ItemActions'; import ResetAction from './ResetAction'; /** * Composant Sidebar : * Menu latéral */ function Sidebar() { const { config } = useConfig(); const { socket } = useSocket(); useEffect(() => { socket.emit('getItemModels'); }, []); const endGame = () => socket.emit('endGame'); return ( <Container className="py-3"> <h3 className="mb-5 text-center"> {`${config.name} - ${config.gameMode}`} </h3> <ResetAction /> <Collapsable title="Zone de jeu" defaultOpen={false}> <GameAreaActions /> </Collapsable> <Collapsable title="Zones interdites" defaultOpen={false}> <ForbiddenAreaActions /> </Collapsable> <Collapsable title="Joueurs" defaultOpen={false}> <PlayerActions /> </Collapsable> <Collapsable title="Cristaux" defaultOpen={false}> <FlagActions /> </Collapsable> <Collapsable title="Items" defaultOpen={false}> <ItemActions /> </Collapsable> <Row className="mt-5 justify-content-end"> <Col xs="auto"> <Button variant="danger" onClick={endGame}> Terminer la partie </Button> </Col> </Row> </Container> ); } export default Sidebar;
// 输入框支持类型 :'select','multiSelect','cascader','input','number','date', // 下拉选阈值接口需要特定的返回格式 var pageConfig = { ifHideSearch:false, privilegeCode: ['bt_add', 'bt_select', 'bt_update', 'bt_delete'], searchPath: '/jdbc/commonData/project/getPage.do', deletePath: '/jdbc/commonData/project/delete.do', detailPath: '/jdbc/commonData/project/get.do', savePath: '/jdbc/commonData/project/save.do', updatePath: '/jdbc/commonData/project/update.do', searchFields: [ 'name', 'code', ], tableFields: [ 'name', 'engineeringname', 'code', 'mediumtypeCodeName', 'constructname', 'remarks', 'ordernum' ], addFields: [{ title: '项目信息', fields: [ "engineeringoid", "name", "code", 'mediumtype', 'construct', 'ordernum' ] }], detailFields: [{ title: '项目信息', fields: [ "engineeringname", "name", "code", "mediumtypeCodeName", "constructname", "ordernum" ] }, { title: '其他信息', fields: [ 'remarks' ] }], fieldsConfig: { engineeringoid: { type: 'select', name: '工程名称', optionUrl: 'jdbc/commonData/engineering/getEngineeringOfUser.do', isRequired: true, disabled: true, }, engineeringname: { name: '工程名称', }, name: { name: '项目名称', type: 'input', isRequired: true }, code: { name: '项目编码', type: 'input', isRequired: true }, construct: { type: 'cascader', name: '建设单位', optionUrl: '/jasframework/privilege/unit/getUnitTree.do?isroot=true', props:{ value:'id', label:'text', }, disabled: true }, constructname: { name: '建设单位', }, mediumtypeCodeName: { name: '介质' }, mediumtype: { type: 'select', name: '介质', domainName: 'project_mediumtype' }, remarks: { name: "备注", type: "textarea" }, ordernum: { name: '序号', type: 'input' } }, methods: { approve: function () { console.log(this) // this指向当前的vue实例,此处可操作vue的实例 var that = this; var url = jasTools.base.rootPath + '/jasmvvm/pages/module-template/base-template-new/dialogs/add.html?pageCode=' + 'madian-stake'; top.jasTools.dialog.show({ width: '800px', height: '80%', title: '审核', src: url, cbForClose: function (param) { that.$refs.table.refresh(); } }); } } };
import md5 from 'md5'; const makeMd5 = (password) => { let ts = new Date().toLocaleDateString().replace(/\//g, '-'); return md5(password + ts); } export default makeMd5;
'use strict' const action = require('./type') module.exports = action
// const array = [ // 'senin', // 'selasa', // 'rabu', // 'kamis', // 'jumat', // 'sabtu', // 'minggu', // ]; const array = [ 6, 2, 5, 4, 3, 1, 7, ]; //foreach // array.forEach(function(e, i) { // console.log("hari ke-"+(i+1)+" adalah "+e); // }); array.sort(); //map var angka = array.map(function(e, i) { return e * 2; }); console.log(angka);
/** * Created by jojoldu@gmail.com on 2017-01-12 * Blog : http://jojoldu.tistory.com * Github : http://github.com/jojoldu */ const fs = require('fs'); const path = require('path'); const toMarkdown = require('to-markdown'); const parseString = require('xml2js').parseString; const showdown = require('showdown'), converter = new showdown.Converter(); const request = require('request'); const infoManager = require('./info-manager'); const jsonPath = path.join(__dirname, "../"); const url = 'https://www.tistory.com/apis/post/read'; const xml = '<?xml version="1.0" encoding="utf-8"?> <tistory> <status>200</status> <item><url>http://oauth.tistory.com</url><secondaryUrl></secondaryUrl><id>1</id><title><![CDATA[티스토리 OAuth2.0 API 오픈!]]></title><content><![CDATA[안녕하세요 Tistory API 입니다.<br /><br />이번에 Third-party Developer 용 <b>Tistory OAuth 2.0 API</b> 가 오픈됩니다.<br />Tistory 회원이라면, 여러분의 모든 app에 자유롭게 활용하실 수 있습니다.<br /><br /><div class="imageblock center" style="text-align: center; clear: both;"> <img alt="이미지" src="http://cfile10.uf.tistory.com/image/156987414DAF9799227B34" ></div><br /><p></p>많은 기대와 사랑 부탁드립니다.&nbsp;<br />&nbsp;]]></content><categoryId>0</categoryId><postUrl>http://oauth.tistory.com/1</postUrl><visibility>0</visibility><acceptComment>1</acceptComment><acceptTrackback>1</acceptTrackback><tags><tag>open</tag><tag>api</tag></tags><comments>0</comments><trackbacks>0</trackbacks><date>1303352668</date></item></tistory>'; const writeMarkdownById = function (postId) { getPostById(postId, writeMarkdown); }; const getPostById = function (postId, callback) { infoManager.getBlogInfo(function (blogInfo) { infoManager.getAccessToken(function (accessToken) { const options = { url : url+'?output=json&access_token='+accessToken+'&blogName='+blogInfo.blogName+'&targetUrl='+blogInfo.targetUrl+'&postId='+postId, method : 'get' }; request(options, function (error, response, body) { if(error){ throw error; } const result = JSON.parse(body).tistory; if(result.status != 200){ console.log(result['error_message']); process.exit(); } const html = result.item.content; callback(html); }) }); }); }; const writeMarkdown = function (html) { const markdown = toMarkdown(html); fs.writeFile(jsonPath+'blog.md', JSON.stringify(markdown), 'utf8', function(err){ if(err){ console.log('An error occurred while writing markdown file '); throw err; } console.log('Completed markdown\n'); process.exit(); }); }; writeMarkdownById(70); exports.writeMarkdownById = writeMarkdownById;
'use strict'; module.exports = (sequelize, DataTypes) => { const Schedule = sequelize.define('schedule', { weekday: DataTypes.STRING, open: DataTypes.TINYINT, is_hh: DataTypes.TINYINT, hour: DataTypes.TIME, notes: DataTypes.TEXT, created_by: DataTypes.INTEGER, created_at: DataTypes.DATE, updated_by: DataTypes.INTEGER, updated_at: DataTypes.DATE, is_active: DataTypes.TINYINT, }, { timestamps: false }); Schedule.associate = function(models) { Schedule.belongsTo(models.bar, { foreignKey: 'bars_id', }); }; return Schedule; };
const c25 = 'abcdefghijklmnopqrstuvwxy'; const c100 = c25 + c25 + c25 + c25; const c125 = c100 + c25; const a10k = []; for (let i = 0; i < 100; i++) { a10k.push(c100); } const c10k = a10k.join(''); class Test { constructor() { this.fetcher = new Fetcher(); const urlInput = document.getElementById('targetUrl'); this.url = urlInput.value; console.log(this.url); } async doTestExec(event, logger) { const unixtime = Date.now(); const gropeNameLimit = 'grp' + c125; const fileNameLimit = 'fil' + c125; const fileNameLimit1 = 'fi1' + c125; const fileNameLimit2 = 'fi2' + c125; const fileNameLimit3 = 'fi3' + c125; const hashLimit = 'has' + c125; const dataLimit = '123' + c10k; const gropeNameOrver = 'grop' + c125; const fileNameOrver = 'file' + c125; const hashOrver = 'hash' + c125; const dataOrver = '123' + c10k; await this.getLogA(logger, '', '', '', '', ''); await this.postLogA(logger, 'a', 'a', 'ax.a', 'aa', 'aaaa'); await this.postLogA(logger, 'a', 'a', 'aa1.a', 'aaa1', 'aa1aaaaaaaaaaaa'); await this.postLogA(logger, 'a', 'a', 'aa2.a', 'aaa2', 'aa2aaaaaaaaaaaa'); await this.getLogA(logger, 'get', 'a', 'aa2.a', 'aa2aaaaaaaaaaaa', ''); await this.postLogA(logger, 'a', 'a', 'aa3.a', 'aaa3', 'aa3aaaaaaaaaaaa'); await this.postLogA(logger, 'a', 'a', 'aa4.a', 'aaa4', 'aa4aaaaaaaaaaaa'); await this.postLogA(logger, 'a', 'a', 'aa5.a', 'aaa5', 'aa5aaaaaaaaaaaa'); await this.postLogA(logger, 'a', 'a', 'aa6.a', 'aaa6', 'aa6aaaaaaaaaaaa'); await this.postLogA(logger, 'a', 'a', 'aa7.a', 'aaa7', 'aa7aaaaaaaaaaaa'); await this.postLogA(logger, 'a', 'a', 'aa8.a', 'aaa8', 'aa8aaaaaaaaaaaa'); await this.postLogA(logger, 'a', gropeNameLimit, fileNameLimit, hashLimit, dataLimit); await this.postLogA(logger, 'a', gropeNameOrver, fileNameLimit1, hashLimit, dataLimit); await this.postLogA(logger, 'a', gropeNameLimit, fileNameOrver, hashLimit, dataLimit); await this.postLogA(logger, 'a', gropeNameLimit, fileNameLimit2, hashOrver, dataLimit); await this.postLogA(logger, 'a', gropeNameLimit, fileNameLimit3, hashLimit, dataOrver); this.getLogA(logger, 'b', 'b', 'b', 'null'); this.getLogA(logger, 'get', 'b', 'b', 'null'); this.getLogA(logger, 'get', 'a', 'b', 'null'); this.getLogA(logger, 'get', gropeNameLimit, fileNameLimit, dataLimit); this.getLogA(logger, 'get', gropeNameLimit, fileNameLimit1, 'null'); this.getLogA(logger, 'get', gropeNameLimit, fileNameLimit2, 'null'); this.getLogA(logger, 'get', gropeNameLimit, fileNameLimit3, 'null'); this.getLogA(logger, 'get', 'a', 'aa3.a', 'aa3aaaaaaaaaaaa'); this.getLogA(logger, 'get', 'a', 'aa2.a', 'aa2aaaaaaaaaaaa'); this.getLogA(logger, 'get', 'a', 'aa4.a', 'aa4aaaaaaaaaaaa'); this.getLogA(logger, 'last', gropeNameLimit, '', dataLimit); this.getLogA(logger, 'hash', 'a', 'aa2.a', 'aaa2'); this.getLogA(logger, 'next', 'a', 'aa2.a', 'aa3aaaaaaaaaaaa'); console.log('-A-----'); this.currentLogger = logger; this.oneGetUnitTest('a1a'); this.oneGetUnitTest('a2a'); this.oneGetUnitTest('a3a'); this.oneGetUnitTest('a4a'); this.oneGetUnitTest('a5a'); this.oneGetUnitTest('a6a'); this.oneGetUnitTest('a7a'); this.oneGetUnitTest('a8a'); this.oneGetUnitTest('a9a'); this.oneGetUnitTest('a10a'); this.oneGetUnitTest('a11a'); this.oneGetUnitTest('a12a'); this.oneGetUnitTest('a13a'); this.oneGetUnitTest('a14a'); this.oneGetUnitTest('a15a'); console.log('--B----'); } async oneGetUnitTest(key, group = 'a') { const waitTime = Math.ceil(Math.random() * 1000); const current = Date.now(); const groupA = group + '_' + current; const fileName = key + '_' + current + '.file'; const hash = key + '_' + current + '.hash'; const data = key + '_' + current + '_' + c125; const logger = this.currentLogger; let count = 0; while (count < 10) { await this.postLogA(logger, 'a', groupA, fileName, hash, data); await new Promise((resolve) => { setTimeout(() => { resolve(); }, waitTime); }); count++; const result = await this.getLogA(logger, 'get', groupA, fileName, data); if (result === data) { break; } } setTimeout(async () => { this.getLogA(logger, 'hash', groupA, fileName, hash); }, waitTime); } init() { this.setEventListern('getButton'); this.setEventListern('nextButton'); this.setEventListern('hashButton'); this.setEventListern('lastButton'); this.setEventListern('planeButton'); this.setEventListern('postButton'); this.setEventListern('testButton', 'click', this.doTest); } setEventListern(className, eventName = 'click', funcSeed) { console.log('aaa'); const elns = document.getElementsByClassName(className); if (elns && elns[0]) { console.log('aaa'); const target = elns[0]; const eventListener = this.creatEventListner(target, funcSeed); target.addEventListener(eventName, eventListener); } } creatEventListner(targetElm, funcSeed) { const parent = targetElm.parentNode.parentNode; const superParent = parent.parentNode; const result = superParent.getElementsByClassName('result'); const ResultDom = result && result[0] ? result[0] : null; const logger = new Logger(ResultDom); const func = funcSeed ? funcSeed(this, logger) : null; return async (event) => { console.log(targetElm); const params = {}; for (let k = 0; k < parent.children.length; k++) { const childLi = parent.children[k]; for (let i = 0; i < childLi.children.length; i++) { const child = childLi.children[i]; console.log(child); if (child !== targetElm) { console.log(child.tagName); if (child.tagName === 'INPUT') { const name = child.getAttribute('name'); const value = child.value; params[name] = value; } } } } console.log(params); if (func) { func(event); return; } if (params.command === 'post') { await this.postLog(logger, params); } else { console.log(params); await this.getLog(logger, params); } }; } async post(params) { return await this.fetcher.postAsSubmit(this.url, params, true); } async get(params) { return await this.fetcher.getTextCors(this.url, params); } async postLog(logger, params) { return logger.add(await this.post(params)); } async getLog(logger, params) { return logger.add(await this.get(params)); } async postLogA(logger, command, group, fileName, hash, dataString) { const params = this.createData(command, group, fileName, hash, dataString); const result = await this.post(params); return logger.add('POST req:' + JSON.stringify(params) + '\n/res:' + JSON.stringify(result)); } async getLogA(logger, command, group, fileName, expect) { const params = this.createData(command, group, fileName); const result = await this.get(params); console.log('getLogA result:' + result + '/!!result:' + !!result + '/' + typeof result); console.log(result); const asert = expect ? result === expect : false; logger.add('GET req:' + JSON.stringify(params) + '\n/res:' + JSON.stringify(result) + '\n[' + asert + ']'); return result; } doTest(self, logger) { return (event) => { if (confirm('execute Test!' + event)) { self.doTestExec(event, logger); } }; } createData(command, group, fileName, hash, dataString) { const data = {}; if (command) { data.command = command; } if (group) { data.group = group; } if (fileName) { data.fileName = fileName; } if (hash) { data.hash = hash; } if (dataString) { data.data = dataString; } return data; } } class Logger { constructor(domObj) { this.domObj = domObj; this.domObj.style.whiteSpace = 'pre'; } add(msg) { const current = this.domObj.textContent; console.log(msg); this.domObj.textContent = current + '\n' + msg; return msg; } } class UrlUtil { constructor() {} static convertObjToQueryParam(data) { if (data && typeof data === 'object') { return Object.keys(data) .map((key) => key + '=' + encodeURIComponent(data[key])) .join('&'); } return data; } } class Fetcher { constructor(headerKeys) { this.headerKeys = headerKeys; } async postAsSubmit(path, data, isCors = true) { const submitData = UrlUtil.convertObjToQueryParam(data); return await this.exec(path, submitData, true, 'application/x-www-form-urlencoded', isCors); } async postJsonCors(path, data) { return await this.post(path, data, 'application/json', true); } async post(path, data, contentType, isCors) { return await this.exec(path, data, true, contentType, isCors); } async exec(path, data = {}, isPost = false, contentType = 'application/json', isCORS = false) { const requestData = { method: isPost ? 'POST' : 'GET', mode: isCORS ? 'cors' : 'no-cors', cache: 'no-cache', credentials: 'omit', redirect: 'follow', referrer: 'no-referrer', headers: { 'Content-Type': contentType, }, }; const isObj = typeof data === 'object'; if (isPost) { requestData.body = isObj ? JSON.stringify(data) : data; } else if (contentType === 'application/json') { const json = isObj ? JSON.stringify(data) : data; path += '?q=' + encodeURIComponent(json); } else if (isObj) { path += '?' + UrlUtil.convertObjToQueryParam(data); } else { path += '?q=' + encodeURIComponent(data); } console.log(path); console.log(requestData); return await fetch(path, requestData); } // async getBlob(path, data = {}, isPost = false, contentType = 'application/json', isCORS = false) { // const res = await this.exec(path, data, isPost, contentType, isCORS); // return await res.blob(); // } // async getJson(path, data = {}, isPost = false, contentType = 'application/json', isCORS = false) { // const res = await this.exec(path, data, isPost, contentType, isCORS); // return await res.json(); // } async getTextCors(path, data = {}, isPost = false, contentType = 'application/x-www-form-urlencoded; charset=utf-8') { return await this.getText(path, data, isPost, contentType, true); } async getText(path, data = {}, isPost = false, contentType = 'application/json', isCORS = false) { const res = await this.exec(path, data, isPost, contentType, isCORS); return await res.text(); } } if (window) { const test = new Test(); test.init(); }
var data= require("data/star-data.js") App({ globalData: { indexBg:"../../images/background.jpg", detailBg: "../../images/bg.jpg", dataUrl:"http://api.jisuapi.com/astro/fortune", appkey:"461a2c345d98b34c", stars: data.stars }, })
'use strict'; const express = require('express'); const router = express.Router(); const uuid = require('uuid').v4; const Dealer = require('../dealer'); const dealers = []; const logger = require('../middleware/logger'); router.get('/next/:dealerID', logger, nextHandler); router.get('/next/:dealerID/:verb', logger, nextVerbHandler); router.post('/join/:dealerID/:playerID', logger, joinHandler); router.post('/leave/:dealerID/:playerID', logger, leaveHandler); router.get('/game', logger, newGameHandler); function newGameHandler(req, res) { var id = uuid(); const dealerObj = { id, dealer: new Dealer() }; const minimizedDealer = getMinimizedDealer(dealerObj); dealers.push(dealerObj); res.status(200).json(minimizedDealer); } async function joinHandler(req, res) { let dealerContainer = getDealer(req); let playerID = req.params.playerID; await dealerContainer.dealer.addPlayer(playerID); res.status(200).json(getMinimizedDealer(dealerContainer)); } async function leaveHandler(req, res) { let dealerContainer = getDealer(req); let id = req.params.playerID; await dealerContainer.dealer.removePlayer(id); res.status(200).json(getMinimizedDealer(dealerContainer)); } async function nextHandler(req, res) { let dealerContainer = getDealer(req); await dealerContainer.dealer.next(); res.status(200).json(getMinimizedDealer(dealerContainer)); } async function nextVerbHandler(req, res) { let dealerContainer = getDealer(req); var verb = req.params.verb; //if the verb is bet, check if we also have an amount var amount = req.query.amount; await dealerContainer.dealer.next(verb, amount ? amount : null); res.status(200).json(getMinimizedDealer(dealerContainer)); } function getMinimizedDealer(dealerContainer) { return { id: dealerContainer.id, dealer: { currentState: dealerContainer.dealer.currentState, currentPlayerIndex: dealerContainer.dealer.currentPlayerIndex, players: dealerContainer.dealer.players, round: dealerContainer.dealer.round } }; } function getDealer(req) { var dealerID = req.params.dealerID; var dealerContainer = dealers.find((dealer) => { return dealer.id === dealerID; }) return dealerContainer; } module.exports = router;
/** * Definition for singly-linked list. * function ListNode(val) { * this.val = val; * this.next = null; * } */ /** * @param {ListNode} head * @param {number} x * @return {ListNode} */ var partition = function(head, x) { if (!head) { return head; } let node = head; const left = []; const right = []; while (node) { node.val < x ? left.push(node) : right.push(node); node = node.next; } const arr = [...left, ...right]; const newHead = arr[0]; for (let i = 0; i < arr.length - 1; i++) { arr[i].next = arr[i + 1]; } arr[arr.length - 1].next = null; return newHead; }; const a = [1,4,3,2,5,2] function arrToList(arr) { let head; let pre; for (let i of arr) { let n = { val: i, next: null }; !head && (head = n); if (!pre) { pre = n } else { pre.next = n; pre = n; } } return head; } console.log(arrToList(a)); partition(arrToList(a), 3);
/** * Copyright (c), 2013-2014 IMD - International Institute for Management Development, Switzerland. * * See the file license.txt for copying permission. */ define([ 'nav/NavContext', 'nav/LineEndComparator', ], function (NavContext, LineEndComparator) { 'use strict'; /** * The context within which the navigation takes place. */ var LineEndContext = function (isDown) { this.isDown = isDown; // this.comparator = new NavComparator(isDown); this.comparator = new LineEndComparator(isDown); }; LineEndContext.prototype = new NavContext(); LineEndContext.prototype.setBest = function (newBest) { this.best = newBest; }; LineEndContext.prototype.getBest = function () { return this.best; }; LineEndContext.prototype.process = function () { if (this.result) { this.result.selectToBound(!this.isDown); } return this.result; }; /** * Selects the navigation best fit if no better navigation end point was found. */ LineEndContext.prototype.checkSelectBest = function () { if (!this.result && this.best) { this.result = this.best; this.best = null; this.result.selectToBound(!this.isDown); } }; LineEndContext.prototype.shouldSetXAnchor = function () { return true; }; return LineEndContext; });
/* global describe, beforeEach, it, browser, expect */ 'use strict'; var Panel4PagePo = require('./panel4.po'); describe('Panel4 page', function () { var panel4Page; beforeEach(function () { panel4Page = new Panel4PagePo(); browser.get('/#/panel4'); }); it('should say Panel4Ctrl', function () { expect(panel4Page.heading.getText()).toEqual('panel4'); expect(panel4Page.text.getText()).toEqual('Panel4Ctrl'); }); });
import React, { Component } from 'react'; import styled from 'styled-components'; import { Route } from "react-router-dom"; import { ApolloProvider } from 'react-apollo'; import ChannelDetails from './views/channels-list/ChannelDetails'; import ChannelsList from './views/channels-list'; import client from './apollo-client'; const Root = styled.div` color: #FFFFFF; height: 100vh; background-image: linear-gradient(175deg, #2b3658 0%, #523e5b 100%); `; const Hearder = styled.div` background-color: #333; color: #fff; padding: 10px 30px; text-align: left; font-weight: 200; font-size: 20px; line-height: 30px; display: flex; align-items: center; `; class App extends Component { render() { return ( <ApolloProvider client={client}> <Root> <Hearder> React + GraphQL Tutorial </Hearder> <ChannelsList /> <Route path="/example1/channel/:channelId" component={ChannelDetails} /> </Root> </ApolloProvider> ); } } export default App;
/** * 该服务提供了向服务端获取数据,并且缓存经常访问的数据(该数据不会经常变化),例如busType 类型 * 可以设置刷新的次数,但其他的服务调用了多少次以后可以进行远程刷新 */ app.factory("modelDataCacheService",['$http','$q',function($http,$q){ /** * 全局变量@1 */ var busTypeTreeData = null;//缓存自定义指令ui-busTypeTree.js所需的数据 var busTypeTreeDataFlushTimes = 5;//当其他的应用调用该数据五次以后,就进行远程服务端访问,获取最新的数据 var busTypeTreeDataNowTimes = 0;//数据已经被获取几次了,每次获取数据将该次数加一 /** * 全局变量@2 */ var busTypeZtreeData = null;//该数据主要是为了业务ztree提供的缓存数据 var busTypeZtreeDataFlushTimes = 5; var busTypeZtreeDataNowTimes = 0; /** * 全局变量@3 组织不存在部门 */ var orgNoDeptZtreeData = null;//该数据主要是为了业务ztree提供的缓存数据 var orgNoDeptZtreeDataFlushTimes = 5; var orgNoDeptZtreeDataNowTimes = 0; /** * 全局变量@3.1 组织存在部门 */ var orgHasDeptZtreeData = null;//该数据主要是为了业务ztree提供的缓存数据 var orgHasDeptZtreeDataFlushTimes = 5; var orgHasDeptZtreeDataNowTimes = 0; /** * 全局变量@3.2组织存在部门 和存在商铺信息 */ var orgHasDeptAndCarShopZtreeData = null;//该数据主要是为了业务ztree提供的缓存数据 var orgHasDeptAndCarShopZtreeDataFlushTimes = 5; var orgHasDeptAndCarShopZtreeDataNowTimes = 0; /** * 全局变量@4 */ var provinceData = null;//该数据主要是为了业务ztree提供的缓存数据 var provinceDataFlushTimes = 5; var provinceDataNowTimes = 0; serviceInstance = { /** * 使用全局变量 @1 * 获取自定义指令ui-busTypeTree.js所需的数据 * @Param needFlush 是否需要立即向服务器刷新数据,获取最新的数据,true是立即从服务器中刷新数据 */ BusTypeTreeDataService : function(needFlush){ var deferred = $q.defer(); if(needFlush || !busTypeTreeData || (busTypeTreeDataNowTimes > busTypeTreeDataFlushTimes)){ //需要从网上刷新最新的数据 $http({ url:"base/busTypeAction!listBusType.action", method : "get" }).then(function(resp){ if(resp.data.code==1){ busTypeTreeData = resp.data.rows ; busTypeTreeDataNowTimes = 0; } console.info("从网上获取数据"); busTypeTreeData.push({ busTypeCode:"", busTypeName:"所有类型", parentId:"", simpleName:"所有类型", }); deferred.resolve(busTypeTreeData); }); }else{ busTypeTreeDataNowTimes ++; console.info("缓存数据中读取数据"); deferred.resolve(busTypeTreeData); } return deferred.promise; }, /** * 使用全局变量 @2 * 获取自定义指令ui-busTypeZtree.js 中所需的数据 * @Param needFlush 是否需要立即向服务器刷新数据,获取最新的数据,true是立即从服务器中刷新数据 */ busTypeZtreeDataService:function(needFlush){ var deferred = $q.defer(); if(needFlush || !busTypeZtreeData || (busTypeZtreeDataNowTimes > busTypeZtreeDataFlushTimes)){ //需要从网上刷新最新的数据 $http({ url:"base/busTypeAction!busTypeTree.action", method : "get" }).then(function(resp){ if(resp.data.code==1){ busTypeZtreeData = resp.data.busTypes ; busTypeZtreeDataNowTimes = 0; } console.info("从网上获取数据@2"); deferred.resolve(busTypeZtreeData); }); }else{ busTypeZtreeDataNowTimes ++; console.info("缓存数据中读取数据@2"); deferred.resolve(busTypeZtreeData); } return deferred.promise; }, /** * 组织架构的选择树,在这个选择树中不能出现部门,其他的的组织都可以出现 * @3 */ orgNoDeptZtreeDataService:function(needFlush){ var deferred = $q.defer(); if(needFlush || !orgNoDeptZtreeData || (orgNoDeptZtreeDataNowTimes > orgNoDeptZtreeDataFlushTimes)){ //需要从网上刷新最新的数据 $http({ url:"basedata/orgAction!listOrgNoDept.action", method : "get" }).then(function(resp){ if(resp.data.code==1){ orgNoDeptZtreeData = resp.data.orgNoDept ; orgNoDeptZtreeDataNowTimes = 0; } console.info("从网上获取数据@3"); deferred.resolve(orgNoDeptZtreeData); }); }else{ orgNoDeptZtreeDataNowTimes ++; console.info("缓存数据中读取数据@3"); deferred.resolve(orgNoDeptZtreeData); } return deferred.promise; }, /** * 组织架构的树,可以存在部门 */ orgHasDeptTreeDataService:function(needFlush){ var deferred = $q.defer(); if(needFlush || !orgHasDeptZtreeData || (orgHasDeptZtreeDataNowTimes > orgHasDeptZtreeDataFlushTimes)){ //需要从网上刷新最新的数据 $http({ url:"basedata/orgZAction!listOrgHasDeptTreeByLoginUser.action", method : "get" }).then(function(resp){ if(resp.data.code==1){ orgHasDeptZtreeData = resp.data.data ; orgHasDeptZtreeDataNowTimes = 0; } console.info("从网上获取数据@3.1"); deferred.resolve(orgHasDeptZtreeData); }); }else{ orgHasDeptZtreeDataNowTimes ++; console.info("缓存数据中读取数据@3.1"); deferred.resolve(orgHasDeptZtreeData); } return deferred.promise; }, /** * 组织架构的树,可以存在部门/可以存在商铺 */ orgHasDeptAndCarShopTreeDataService:function(needFlush){ var deferred = $q.defer(); if(needFlush || !orgHasDeptAndCarShopZtreeData || (orgHasDeptAndCarShopZtreeDataNowTimes > orgHasDeptAndCarShopZtreeDataFlushTimes)){ //需要从网上刷新最新的数据 $http({ url:"basedata/orgZAction!listOrgHasDeptAndCarShopByLoginUser.action", method : "get" }).then(function(resp){ if(resp.data.code==1){ orgHasDeptAndCarShopZtreeData = resp.data.data ; orgHasDeptAndCarShopZtreeDataNowTimes = 0; } console.info("从网上获取数据@3.2"); deferred.resolve(orgHasDeptAndCarShopZtreeData); }); }else{ orgHasDeptAndCarShopZtreeDataNowTimes ++; console.info("缓存数据中读取数据@3.2"); deferred.resolve(orgHasDeptAndCarShopZtreeData); } return deferred.promise; }, //以上是方法定义 /** * 从服务端获取省份的所有数据 */ provinceDataService:function(needFlush){ var deferred = $q.defer(); if(needFlush || !provinceData || (provinceDataNowTimes > provinceDataFlushTimes)){ //需要从网上刷新最新的数据 $http({ url:"base/baseProvinceAction!listBaseProvinceNoCitys.action", method : "get" }).then(function(resp){ if(resp.data.code==1){ provinceData = resp.data.data ; provinceDataNowTimes = 0; } console.info("从网上获取数据@4"); deferred.resolve(provinceData); }); }else{ provinceDataNowTimes ++; console.info("缓存数据中读取数据@4"); deferred.resolve(provinceData); } return deferred.promise; }, /** * 根据省份的编码查询所有的城市 */ cityDataService:function(code){ var deferred = $q.defer(); if(code){ //需要从网上刷新最新的数据 $http({ url:"base/baseProvinceAction!listCityByProvinceCode.action", method : "post", data:{ code:code } }).then(function(resp){ if(resp.data.code==1){ cityData = resp.data.data ; } deferred.resolve(cityData); }); } return deferred.promise; }, /** * 根据城市的编码查询所有的区域 */ areaDataService:function(code){ var deferred = $q.defer(); if(code){ //需要从网上刷新最新的数据 $http({ url:"base/baseCityAction!listAreaByCityCode.action", method : "post", data:{ cellCode:code } }).then(function(resp){ if(resp.data.code==1){ var areaData = resp.data.data ; } deferred.resolve(areaData); }); } return deferred.promise; }, /** * 根据城市的编码查询所有的区域 */ smallAreaDataService:function(code){ var deferred = $q.defer(); if(code){ //需要从网上刷新最新的数据 $http({ url:"base/baseAreaAction!listSmallAreaByAreaCode.action", method : "post", data:{ cellCode:code } }).then(function(resp){ if(resp.data.code==1){ var areaData = resp.data.data ; } deferred.resolve(areaData); }); } return deferred.promise; }, /** * 从服务端获取所有菜单的 */ menuDataService:function(){ var deferred = $q.defer(); //需要从网上刷新最新的数据 $http({ url:"sys/sys/menuAction!listMenu.action", method : "post" }).then(function(resp){ if(resp.data.code==1){ var menuData = resp.data.data ; } deferred.resolve(menuData); }); return deferred.promise; } //对象定义结束 }; return serviceInstance; }]);
/* * Format numbers as float * @param {float} d * @returns {float} float formated number */ function formatAsFloat(d) { if (d % 1 !== 0) { return d3.format('.2f')(d); } else { return d3.format('.0f')(d); } }
import React from "react"; import { makeStyles } from "@material-ui/core/styles"; import Paper from "@material-ui/core/Paper"; import { Typography } from "@material-ui/core"; import Grid from "@material-ui/core/Grid"; import DocPic from "../../assets/document.svg"; import Download from "../../assets/download.svg"; const useStyles = makeStyles((theme) => ({ root: { display: "flex", flexDirection: "row", width: "100%", margin: "0.5rem", marginBottom: "1rem", }, grid: { display: "flex", margin: "1rem", }, title: { display: "flex", flexDirection: "row", fontWeight: 600, }, text: { display: "flex", flexDirection: "column", }, })); const DocumentList = (props) => { const classes = useStyles(); const [download, setDownload] = React.useState(0); const handleDownload = () => { setDownload(download + 1); }; return ( <div className={classes.root}> <Paper elevation={3} style={{ width: "100%" }}> <div className={classes.grid}> <Grid sm={2}> <img src={DocPic} /> </Grid> <Grid sm={10} className={classes.text}> <div className={classes.title}> <Typography style={{ fontWeight: 600 }}> {props.title} </Typography> <img src={Download} style={{ marginLeft: "auto", marginRight: "1rem", }} onClick={handleDownload} /> <Typography>{download}</Typography> </div> <div> <Typography> {props.username} | {props.university} </Typography> </div> <div> <Typography> Description... {props.description} </Typography> </div> <div style={{ marginTop: "auto" }}> <Typography> {props.academicTerm} {props.academicYear} </Typography> </div> </Grid> </div> </Paper> </div> ); }; export default DocumentList;
import React, {Component} from 'react' import TopNabar from '../Common/TopNavbar' import FilterList from './FilterList' import Breadcrumb from '../Common/Breadcrumb' import {connect} from 'react-redux' class Index extends Component { static contextTypes = { router: React.PropTypes.object } render() { const {ownerType, scanType,} = this.props.match.params; const {currentOwnerType, currentScanType} = this.props; var searchParams = new URLSearchParams(this.context.router.history.location.search); var severity = searchParams.get("severity"); var vulnerableType = searchParams.get("vulnerableType"); return ( <div class="page-wrapper"> <div class="page-wrapper"> <TopNabar scanType={scanType} ownerType={ownerType} page="filters"/> <Breadcrumb scanType={currentScanType} ownerType={currentOwnerType} severity={severity} vulnerableType={vulnerableType} page="filters" iconClass="fa fa-filter"/> <FilterList scanType={scanType} ownerType={ownerType} severity={severity} vulnerableType={vulnerableType}/> </div> </div> ) } } const mapStateToProps = (state) => ({currentScanType: state.filters.currentScanType, currentOwnerType: state.filters.currentOwnerType,}); export default connect(mapStateToProps)(Index);
import RestService from './base/rest-service' const url = 'client-documents' export default class ClientDocumentService extends RestService { constructor (apiClient) { super(url, apiClient) this.getDocumentsByClientId = this.getDocumentsByClientId.bind(this) this.getMyIncompleteDocuments = this.getMyIncompleteDocuments.bind(this) } getDocumentsByClientId (clientId) { const documentsUrl = `${url}?clientId=${clientId}` return this.apiClient.get(documentsUrl) } getMyIncompleteDocuments () { const documentsUrl = `${url}/my-incomplete/list` return this.apiClient.get(documentsUrl) } }
import util from '@/libs/util.js'; import config from '@/config/config'; // 验证是否是[0-1]的小数 const isInteger = (rule, value, callback)=> { setTimeout(() => { if (!Number(value)) { callback(new Error('请输入正整数')); } else { const re = /^[0-9]*[1-9][0-9]*$/; const rsCheck = re.test(value); if (!rsCheck) { callback(new Error('请输入正整数')); } else { callback(); } } }, 0); } const isOneToNinetyNine =(rule, value, callback) =>{ if(value){ setTimeout(() => { if (!Number(value)) { callback(new Error('请输入正整数')); } else { const re = /^[1-9][0-9]{0,1}$/; const rsCheck = re.test(value); if (!rsCheck) { callback(new Error('请输入正整数,值为【1,99】')); } else { callback(); } } }, 0); }else{ callback(); } } //行政编码校验 const checkMax900000 = (rule, value, callback)=> { if (value == '' || value == undefined || value == null) { callback(); } else if (!Number(value)) { callback(new Error('请输入合法的行政编码')); } else if (value < 100000 || value > 900000) { callback(new Error('请输入合法的行政编码')); } else { callback(); } } //校验是否合法字符 const isValidCode = (rule, value, callback) =>{ const reg =/^[a-zA-Z0-9]+$/; if(value==''||value==undefined||value==null){ callback(new Error('不能为空')); } else { if (!reg.test(value)){ callback(new Error('仅由英文字母、数字组成')); }else{ callback(); } } } //校验应用编码的唯一性 const checkAppCode = (rule, value, callback) =>{ if(value==''||value==undefined||value==null){ callback(new Error('不能为空')); } else { util.ajax.get(config.acServerContext+"/manage/acApp/checkCode", { params: { appCode:value } }).then(function(resp){ var result = resp.data.data; if(result && result.appCode != '' && result !='null'){ callback(new Error('该应用编码已存在,请重新输入')); }else{ callback(); } }).catch(function(err) { callback(new Error('应用编码校验异常')); }); } } export default { isInteger, isOneToNinetyNine, checkMax900000, isValidCode, checkAppCode }
import React from "react"; import styled from "styled-components"; import { Colors } from "../Global/Color"; import { NavBar } from "../Components/navBar"; import { Logo } from "../Components/logo"; import { LinkBar } from "../Components/linkBar"; import { Globe } from "../Components/globe"; import { ProjectDeckOfCards } from "../Components/Cards/projectDeckOfCard"; export const Projects = () => { return ( <Wrapper> <NavBar /> <Logo /> <MainContainer> <ProjectsContainer> <Title>Some projects that I have completed recently</Title> <ProjectDeckOfCards /> </ProjectsContainer> <Globe /> </MainContainer> <LinkBar /> </Wrapper> ); }; const Wrapper = styled.div` padding-top: 80px; width: 100%; min-height: 100vh; background: linear-gradient( 326deg, rgba(139, 160, 199, 1) 0%, rgba(223, 233, 243, 1) 41%, rgba(139, 160, 199, 1) 100% ); @media (max-width: 500px) { } `; const MainContainer = styled.div` width: 80%; margin: 45px auto auto auto; height: 850px; display: flex; justify-content: space-around; align-items: center; @media (max-width: 1440px) { height: 750px; margin: 0px auto; } @media (max-width: 1024px) { height: 700px; margin: 20px auto; width: 90%; } @media (max-width: 770px) { height: 700px; margin: 0px auto; width: 95%; } @media (max-width: 500px) { width: 450px; height: 600px; width: 95%; margin: 10px auto auto auto; } `; const Title = styled.p` margin: auto auto 10px auto; font-size: 2.5rem; font-weight: bold; color: ${Colors.blue}; text-shadow: 4px 3px 2px ${Colors.hoverBlue}; font-family: "Indie Flower", cursive; @media (max-width: 1440px) { font-size: 2rem; margin: auto auto 60px auto; } @media (max-width: 1024px) { font-size: 1.5rem; margin: -30px auto 60px auto; } @media (max-width: 770px) { font-size: 1.5rem; margin: -30px auto 70px auto; } @media (max-width: 500px) { font-size: 1.3rem; margin: -60px auto 90px auto; } `; const ProjectsContainer = styled.div` box-sizing: border-box; display: flex; justify-content: left; align-items: center; flex-direction: column; @media (max-width: 500px) { } `;
'use strict'; var logger = require('./util/noop-logger'); module.exports = { url: 'amqp://localhost', reconnect: { limit: 5, timeout: 50 }, socket: { timeout: 1000 }, assert: { queues: [], exchanges: [], binds: [] }, log: logger };
const chalk = require('chalk'); const fs = require('fs'); const minimist = require('minimist'); const mkdirp = require('mkdirp'); const path = require('path'); const { getGlobalScripts, getCampaignScripts, getVariants } = require('./inc/generate'); const { inline } = require('./inline'); const appDirectory = fs.realpathSync(process.cwd()); async function build(dir, minify) { const srcDir = path.resolve(dir, 'src'); const distDir = path.resolve(dir, 'dist'); function buildIt(fileObject) { let { ext, filePath } = fileObject; let fullFilePath = path.resolve(appDirectory, filePath); var file = path.relative(srcDir, filePath); try { let code = ''; inline(filePath, '', minify); var outFile = path.resolve(distDir, file); mkdirp(path.dirname(outFile), function(writeErr) { if (writeErr) { console.log(chalk.red(fullFilePath, writeErr)); } else { console.log( chalk.green( `Writing: ${file} → ${path.basename(outFile)}` ) ); fs.writeFileSync(outFile, code); } }); } catch (err) { console.log(chalk.red(fullFilePath, err)); } } let globalFiles = await getGlobalScripts(appDirectory, srcDir); let campaignFiles = await getCampaignScripts(appDirectory, srcDir); const variants = await getVariants(appDirectory, srcDir); [...globalFiles, ...campaignFiles].forEach(buildIt); Object.entries(variants).forEach(function([variant, files]) { let snippet = files.reduce((text, fileObject) => { let { ext, filePath } = fileObject; let code = inline(filePath, ext, true); switch (ext) { case 'js': text += `<script>${code}</script>\n`; break; case 'scss': text += `<style>${code}</style>\n`; break; case 'html': text += code + '\n'; break; default: break; } return text; }, ''); var outFile = path.resolve(distDir, `variants/${variant}.html`); mkdirp(path.dirname(outFile), function(writeErr) { if (writeErr) { console.log(chalk.red(outFile, writeErr)); } else { console.log( chalk.green( `Writing: ${variant} → ${path.basename(outFile)}` ) ); fs.writeFileSync(outFile, snippet); } }); }); } const helpText = ` Useage: $0 [options] Options: -h, --help Print usage Information. --minify Minify scripts (defaults to true). `; const args = process.argv.slice(2); const argv = minimist(args, { boolean: ['help', 'minify'], alias: { h: 'help' }, default: { help: false, minify: true } }); if (argv.help) { console.log(helpText); } else { build(appDirectory, argv.minify); }
_ = require ('lodash') var Record = require('../records'); var RecordShop = require('../record_shop'); var assert = require('chai').assert; describe( "RecordShop", function() { beforeEach( function() { surfaceNoise = new RecordShop("Surface Noise", "Newcastle"); loveless = new Record("Loveless", "My Bloody Valentine", 9.99); crooked = new Record("Crooked Rain, Crooked Rain", "Pavement", 7.99); theWayItIs = new Record("The Way It Is", "Bruce Hornsby and the Range", 4.99); vivaHate = new Record("Viva Hate", "Morrissey", 5.99); tanglewoodNumbers = new Record("Tanglewood Numbers", "Silver Jews", 11.99); }) it ("record shop has a title", function(){ assert.equal("Surface Noise", surfaceNoise.name) }) it ("record shop has a location", function(){ assert.equal("Newcastle", surfaceNoise.location) }) it ("record shop has NO stock", function(){ assert.equal(0, surfaceNoise.stock.length) }) it ("book record in to stock", function() { surfaceNoise.addRecord(loveless); surfaceNoise.addRecord(vivaHate); assert.equal(2, surfaceNoise.stock.length) }) it ("lists all the stock in inventory", function(){ surfaceNoise.addRecord(loveless); surfaceNoise.addRecord(theWayItIs); surfaceNoise.addRecord(crooked); surfaceNoise.addRecord(vivaHate); assert.deepEqual([theWayItIs, vivaHate, loveless, crooked], surfaceNoise.listInventory()) }) it ("Removed a copy of loveless", function(){ surfaceNoise.addRecord(loveless); surfaceNoise.addRecord(theWayItIs); surfaceNoise.addRecord(crooked); surfaceNoise.addRecord(vivaHate); surfaceNoise.soldRecord(loveless); assert.equal(3, surfaceNoise.stock.length) }) it ("added the value of removed item to till", function(){ surfaceNoise.addRecord(loveless); surfaceNoise.addRecord(tanglewoodNumbers); surfaceNoise.soldRecord(loveless); surfaceNoise.soldRecord(tanglewoodNumbers); assert.equal(21.98, surfaceNoise.till) }) it ("added more value of removed item to till", function(){ surfaceNoise.addRecord(loveless); surfaceNoise.addRecord(tanglewoodNumbers); surfaceNoise.addRecord(theWayItIs); surfaceNoise.soldRecord(loveless); surfaceNoise.soldRecord(tanglewoodNumbers); surfaceNoise.soldRecord(theWayItIs); assert.equal(26.97, surfaceNoise.till) }) it ("found value of stock", function(){ surfaceNoise.addRecord(loveless); surfaceNoise.addRecord(theWayItIs); surfaceNoise.addRecord(crooked); surfaceNoise.addRecord(vivaHate); assert.equal(28.96, surfaceNoise.totalCash(surfaceNoise.stock)) }) it ("found value of till", function(){ surfaceNoise.addRecord(loveless); surfaceNoise.addRecord(tanglewoodNumbers); surfaceNoise.addRecord(vivaHate); surfaceNoise.soldRecord(loveless); surfaceNoise.soldRecord(vivaHate); surfaceNoise.soldRecord(tanglewoodNumbers); assert.equal(27.97, surfaceNoise.totalCash(surfaceNoise.till)) }) })
/** * This library provides emoji that give extra flair to commodity names */ const emoji = { Cereals: "🌾", Fruit: "🍒", Furs: "🧥", //Hides: "", Livestock: "🐑", Meats: "🍖", //Soya: "", Spices: "🧄", Textiles: "👘", Woods: "🌲", //Alloys: "", Clays: "🧱", Crystals: "💎", Gold: "🥇", Monopoles: "🧲", //Nickel: "", //Petrochemicals: "", Radioactives: "☢️", //Semiconductors: "", //Xmetals: "", Explosives: "💣", Generators: "⚡", //LanzariK: "", LubOils: "🛢️", Mechparts: "⚙️", //Munitions: "", //Nitros: "", Pharmaceuticals: "💊", //Polymers: "", //Propellants: "", RNA: "🧬", //AntiMatter: "", Controllers: "🎮", Droids: "🤖", //Electros: "", //GAsChips: "", //Lasers: "", //NanoFabrics: "", //Nanos: "", Powerpacks: "🔋", //Synths: "", Tools: "🛠️", TQuarks: "📞", // TQuarks are tangled quarks, used for FTL communication Vidicasters: "📺", Weapons: "🔫", //BioChips: "", BioComponents: "🦠", Clinics: "🏥", Laboratories: "🔬", MicroScalpels: "🔪", //Probes: "", //Proteins: "", Sensors: "📡", ToxicMunchers: "☣️", //Tracers: "", Artifacts: "🏺", Firewalls: "🔥", Games: "🕹️", //Holos: "", Hypnotapes: "🥱", Katydidics: "🦗", Libraries: "📚", Musiks: "🎸", Sensamps: "🔊", //Simulations: "", Studios: "🎬", //Univators: "" } module.exports = { /** * Formats a commodity's name for output. Tacks on an emoji if one is available. * * @param {String} commod */ formatCommod: (commod) => { if(emoji[commod]) { return commod + " " + emoji[commod] + " " } else { return commod } } }
let date = new Date(); document.getElementById("date").innerHTML = date.toLocaleDateString(); let list = document.querySelector("#list") let input = document.querySelector("#input"); let button = document.querySelector("#button") let i=0; button.addEventListener("click", function(){ var checkbox = document.createElement('input'); checkbox.type = "checkbox"; checkbox.name = "name"; checkbox.value = "value"; checkbox.id = "id"; list.appendChild(checkbox); const color = ['primary', 'secondary', 'success', 'danger', 'warning', 'info'] let li = document.createElement('li'); li.classList.add('list-group-item'); li.classList.add('list-group-item-'+color[i%7]); li.textContent=input.value; list.appendChild(li); input.value = ""; i++; //creating checkbox element // Assigning the attributes // to created checkbox }); let newclass = document.querySelector ("body>div>div>h2") newclass.classList.add("myDay", "second"); newclass.classList.remove("second"); console.log(newclass.classList);
const fastify = require('fastify')(); const md = require('markdown-it')({ html: true, }); fastify.register(require('@fastify/static'), { root: require('path').join(__dirname, 'static') }); fastify.addHook('preHandler', async (req, res) => { res.header('Content-Security-Policy', [ "default-src 'self'", "base-uri 'self'", "frame-ancestors 'none'", "img-src 'none'", "object-src 'none'", "script-src 'self' 'unsafe-eval'", "script-src-attr 'none'", "style-src 'self' 'unsafe-inline'" ].join(';')); res.header('X-Content-Type-Options', 'nosniff'); }); fastify.get('/render', { schema: { query: { type: 'object', properties: { content: { type: 'string', maxLength: 1000 } }, required: ['content'] } } }, (req, res) => { res.type('text/html').send(md.render(req.query.content)); }); fastify.listen(process.env.PORT || 3000, '::', () => console.log('listening'));
import config from '../config'; import wepy from 'wepy' function FetchHttpResource(host, actions) { var resource = {}; Object.keys(Object.assign(actions)).forEach(function (actionName) { resource[actionName] = function (param) { var configs = {}; var action = actions[actionName]; var method = action.method; let url = host + action.url; let header = { 'Content-type': action.contentType || 'application/x-www-form-urlencoded', // 默认值 'authorization': '4444_dfa5ae132ecd4e23a6625013800295e2' }; let params = Object.assign(action.params || {}, param); console.log("url", url) return new Promise((resolve, reject) => { let res = wepy.request({ url: url, method: method, header: header, data: params, success(data) { if(data.statusCode == 404) { wx.showToast({ title: '页面不存在', }) } else { resolve(data.data); } }, fail(data) { } }); }); } }); return resource; } const Api = new FetchHttpResource(config.host, { //getActivtiyallType: {method: "POST", url: "getActivtiyallType", params: {"id": 'f7262293-2f60-468f-8f9e-63fa6ddeda5e'}}, //addActivtiyOrder:{method: "POST", url: "addActivtiyOrder",contentType:"application/json" }, getinitLb:{method: "POST", url: "wx/main/lblist",params: {"jtStartIndex":0,"jtPageSize":10} },//首页初始化 轮播图 getinitPd:{method: "POST", url: "wx/main/pdlist",params: {"jtStartIndex":0,"jtPageSize":3} },//首页品读 getinitGsh:{method: "POST", url: "wx/main/userstory",params: {"jtStartIndex":0,"jtPageSize":6} },//首页品读 userZPlist:{method: "POST", url: "wx/main/userZPlist",params: {"jtStartIndex":0,"jtPageSize":4} },//首页品读 userSearchlist:{method: "POST", url: "wx/main/userlist",params: {"jtStartIndex":0,"jtPageSize":10} },//首页匠人搜索 人员搜索 getnewUserstory:{method: "POST", url: "wx/article/getNewUserstory",params: {"jtStartIndex":0,"jtPageSize":6} },//得到最新故事 getAlluserstory:{method: "POST", url: "wx/article/allUserstory",params: {"jtStartIndex":0,"jtPageSize":6}},//得到所有故事 getPingdu:{method: "POST", url: "wx/article/getTypeWz",params: {"jtStartIndex":0}},//品读页面 getZuoping:{method: "POST", url: "wx/zuoping/getTypeZp",params: {"jtStartIndex":0}},//作品页面 getZuopingDetail:{method: "POST", url: "wx/zuoping/productDetial"},//作品详情页面 getYishujia:{method: "POST", url: "wx/artist/list",params: {"jtStartIndex":1,"jtPageSize":4}},//匠人列表 showSearchPage:{method: "POST", url: "wx/artist/searchPage",params: {"jtStartIndex":1,"jtPageSize":10}},//匠人搜索页面 searchYsj:{method: "POST", url: "wx/artist/search",params: {"jtStartIndex":0,"jtPageSize":10}},//匠人名称搜索 ysjHome:{method: "POST", url: "wx/artist/homePage",params: {"zp_pageSize":4,wz_pageSize:4}},//匠人首页 ysjHomezp:{method: "POST", url: "wx/artist/getJrByUserZp",params: {zp_pageSize:4}},//匠人首页-作品分页 ysjHomewz:{method: "POST", url: "wx/artist/getJrByUserWz",params: {wz_pageSize:4}},//匠人首页-文章分页 findArticle:{method: "POST", url: "wx/article/find"}, getToken:{method: "POST", url: "/wx/main/getToken"}, saveToyuYueOrder:{method: "POST", url: "/wx/zuoping/saveOrder"} }) export default Api;
/* * Copyright 2018 Cognitive Scale, Inc. All Rights Reserved. * * 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 debug = require('debug')('cortex:cli'); const co = require('co'); const _ = require('lodash'); const prompt = require('co-prompt'); const chalk = require('chalk'); const Auth = require('../client/auth'); const { readConfig, defaultConfig } = require('../config'); const { printSuccess, printError } = require('./utils'); const DEFAULT_CORTEX_URL = 'https://api.cortex.insights.ai'; module.exports.ConfigureCommand = class { constructor(program) { this.program = program; } execute(options) { const config = readConfig(); const profileName = options.profile || _.get(config,'currentProfile','default'); const profileUrl = this.program.url || _.get(config,'url'); const profileAccount = this.program.account || _.get(config ,'account'); const profileUsername = this.program.username || _.get(config,'username'); const profilePassword = this.program.password || undefined; debug('configuring profile: %s', profileName); const profile = (config && config.getProfile(profileName)) || {}; const cmd = this; co(function*(){ const defaultCortexUrl = profile.url || DEFAULT_CORTEX_URL; const defaultAccount = profile.account || ''; const defaultUsername = profile.username || ''; console.log(`Configuring profile ${chalk.green.bold(profileName)}:`); let cortexUrl = (profileUrl) ? profileUrl : yield prompt(`Cortex URL [${defaultCortexUrl}]: `); let account = (profileAccount) ? profileAccount : yield prompt(`Account [${defaultAccount}]: `); let username = (profileUsername) ? profileUsername : yield prompt(`Username [${defaultUsername}]: `); const password = (profilePassword) ? profilePassword : yield prompt.password('Password: '); cortexUrl = cortexUrl || defaultCortexUrl; cortexUrl = cortexUrl.replace(/\/$/, ''); // strip any trailing / account = account || defaultAccount; username = username || defaultUsername; debug('cortexUrl: %s', cortexUrl); debug('account: %s', account); debug('username: %s', username); if (!cortexUrl.match(/^[a-zA-Z]+:\/\//)) { cortexUrl = 'http://' + cortexUrl; } if (!cortexUrl) { console.error(chalk.red('Cortex URL must be provided')); return; } if (!account) { console.error(chalk.red('Cortex account name must be provided')); return; } if (!username) { console.error(chalk.red('Cortex username must be provided')); return; } const auth = new Auth(cortexUrl); try { const authResp = yield auth.login(account, username, password); if (! _.has(authResp,'jwt') ) { console.error(chalk.red(`LOGIN FAILED: ${authResp.message || 'No token returned'}`)); } else { const token = authResp.jwt; debug('token: %s', authResp); cmd.saveConfig(config, profileName, cortexUrl, account, username, token); console.log(`Configuration for profile ${chalk.green.bold(profileName)} saved.`); } } catch (e) { console.error(chalk.red(`LOGIN FAILED: ${e.message}`)); } }); } saveConfig(config, profileName, url, account, username, token) { if(!config) config = defaultConfig(); config.setProfile(profileName, {url, account, username, token}); config.currentProfile = profileName; config.save(); } }; module.exports.SetProfileCommand = class { constructor(program) { this.program = program; } execute(profileName, options) { const config = readConfig(); const profile = config.getProfile(profileName); if (profile === undefined) { printError(`No profile named ${profileName}. Run cortex configure --profile ${profileName} to create it.`, options); return; } config.currentProfile = profileName; config.save(); console.log(`Current profile set to ${chalk.green.bold(profileName)}`); } }; module.exports.DescribeProfileCommand = class { constructor(program) { this.program = program; } execute(options) { const config = readConfig(); if (config === undefined) { printError(`Configuration not found. Please run "cortex configure".`); return; } const profileName = options.profile || config.currentProfile; debug('describing profile: %s', profileName); const profile = config.getProfile(profileName); if (profile === undefined) { printError(`No profile named ${profileName}. Run cortex configure --profile ${profileName} to create it.`, options); return; } printSuccess(`Profile: ${profile.name}`, options); printSuccess(`Cortex URL: ${profile.url}`, options); printSuccess(`Account: ${profile.account}`, options); printSuccess(`Username: ${profile.username}`, options); } }; module.exports.ListProfilesCommand = class { constructor(program) { this.program = program; } execute(options) { const config = readConfig(); if (config === undefined) { printError(`Configuration not found. Please run "cortex configure".`,options); return; } const profiles = Object.keys(config.profiles); for (let name of profiles) { if (name === config.currentProfile) { if (options.color === 'on') { console.log(chalk.green.bold(name)); } else { console.log(`${name} [active]`); } } else { console.log(name); } } } };
/** * @param {number[]} nums * @param {number} target * @return {number[]} */ var twoSum = function (nums, target) { const res = []; for (let i = 0; i < nums.length - 1; i++) { for (let j = i + 1; j < nums.length; j++) { if (nums[i] + nums[j] == target) { res[0] = i; res[1] = j; return res; } } } };
import React from "react"; import styled from "styled-components"; import { Text, Link, Screen } from "../../../global/styles/styles"; import { formatInt } from "../../../global/utils/utils"; import Copy from "../../../global/locales/en_us"; const SimilarBroadcastsContainer = styled.div` padding: 12px 8px; @media ${Screen.largeQuery} { max-width: 552px; } `; const SimilarBroadcastsTitle = styled(Text)` font-size: 13px; font-weight: 700; letter-spacing: 0.5px; text-transform: uppercase; margin-bottom: 12px; @media ${Screen.largeQuery} { font-size: 16px; } `; const BroadcastContainer = styled.div` display: inline-flex; padding-bottom: 12px; @media ${Screen.largeQuery} { display: -webkit-box; } `; const BroadcastImg = styled.img` width: 180px; height: 100px; object-fit: cover; border-radius: 4px; box-shadow: 2px 6px 18px 0 rgba(183, 183, 183, 0.5); @media ${Screen.largeQuery} { width: 220px; height: 124px; } `; const BroadcastTextContainer = styled.div` padding-left: 8px; display: flex; flex-direction: column; /* justify-content: space-evenly; */ justify-content: center; @media ${Screen.largeQuery} { max-width: 300px; } `; const BroadcasterName = styled(Text)` font-weight: 700; text-transform: uppercase; overflow: hidden; text-overflow: ellipsis; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; `; const BroadcastTitle = styled(Text)` font-weight: 600; padding-top: 6px; overflow: hidden; text-overflow: ellipsis; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; `; const ViewerContainer = styled.div` display: flex; padding-top: 6px; `; const Viewers = styled(Text)` font-size: 12px; font-weight: 600; letter-spacing: 0.5px; align-self: center; `; const ViewersText = styled(Text)` font-size: 11px; font-weight: 600; padding-top: 1px; letter-spacing: 0.5px; align-self: center; `; const SimilarBroadcasts = props => { const { similarBroadcasts } = props; return ( <SimilarBroadcastsContainer> <SimilarBroadcastsTitle>{Copy.similarBroadcasts}</SimilarBroadcastsTitle> {similarBroadcasts.map(broadcast => { const { id, imageUrl, title, viewerCount, live, broadcaster } = broadcast; return ( <Link to={{ pathname: "/watch", search: `?broadcastId=${id}`, broadcast: { ...broadcast } }} key={id} > <BroadcastContainer> <BroadcastImg src={imageUrl} /> <BroadcastTextContainer> <BroadcasterName>{broadcaster.displayName}</BroadcasterName> <BroadcastTitle>{title}</BroadcastTitle> <ViewerContainer> <Viewers>{formatInt(viewerCount)}</Viewers> <ViewersText> &nbsp; {live ? Copy.viewers : Copy.views} </ViewersText> </ViewerContainer> </BroadcastTextContainer> </BroadcastContainer> </Link> ); })} </SimilarBroadcastsContainer> ); }; export default SimilarBroadcasts;
/** * General Transitive utilities library */ import SphericalMercator from 'sphericalmercator' const TOLERANCE = 0.000001 function fuzzyEquals(a, b, tolerance = TOLERANCE) { return Math.abs(a - b) < tolerance } function distance(x1, y1, x2, y2) { return Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)) } function getRadiusFromAngleChord(angleR, chordLen) { return chordLen / 2 / Math.sin(angleR / 2) } /* * CCW utility function. Accepts 3 coord pairs; result is positive if points * have counterclockwise orientation, negative if clockwise, 0 if collinear. */ function ccw(ax, ay, bx, by, cx, cy) { const raw = ccwRaw(ax, ay, bx, by, cx, cy) return raw === 0 ? 0 : raw / Math.abs(raw) } function ccwRaw(ax, ay, bx, by, cx, cy) { return (bx - ax) * (cy - ay) - (cx - ax) * (by - ay) } /* * Compute angle formed by three points in cartesian plane using law of cosines */ function angleFromThreePoints(ax, ay, bx, by, cx, cy) { const c = distance(ax, ay, bx, by) const a = distance(bx, by, cx, cy) const b = distance(ax, ay, cx, cy) return Math.acos((a * a + c * c - b * b) / (2 * a * c)) } function pointAlongArc(x1, y1, x2, y2, r, theta, ccw, t) { ccw = Math.abs(ccw) / ccw // convert to 1 or -1 let rot = Math.PI / 2 - Math.abs(theta) / 2 const vectToCenter = normalizeVector( rotateVector( { x: x2 - x1, y: y2 - y1 }, ccw * rot ) ) // calculate the center of the arc circle const cx = x1 + r * vectToCenter.x const cy = y1 + r * vectToCenter.y let vectFromCenter = negateVector(vectToCenter) rot = Math.abs(theta) * t * ccw vectFromCenter = normalizeVector(rotateVector(vectFromCenter, rot)) return { x: cx + r * vectFromCenter.x, y: cy + r * vectFromCenter.y } } function getVectorAngle(x, y) { let t = Math.atan(y / x) if (x < 0 && t <= 0) t += Math.PI else if (x < 0 && t >= 0) t -= Math.PI return t } function rayIntersection(ax, ay, avx, avy, bx, by, bvx, bvy) { const u = ((by - ay) * bvx - (bx - ax) * bvy) / (bvx * avy - bvy * avx) const v = ((by - ay) * avx - (bx - ax) * avy) / (bvx * avy - bvy * avx) return { intersect: u > -TOLERANCE && v > -TOLERANCE, u: u, v: v } } function lineIntersection(x1, y1, x2, y2, x3, y3, x4, y4) { const d = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4) if (d === 0) { // lines are parallel return { intersect: false } } return { intersect: true, x: ((x1 * y2 - y1 * x2) * (x3 - x4) - (x1 - x2) * (x3 * y4 - y3 * x4)) / d, y: ((x1 * y2 - y1 * x2) * (y3 - y4) - (y1 - y2) * (x3 * y4 - y3 * x4)) / d } } /** * Parse a pixel-based style descriptor, returning an number. * * @param {String/Number} */ function parsePixelStyle(descriptor) { if (typeof descriptor === 'number') return descriptor return parseFloat(descriptor.substring(0, descriptor.length - 2), 10) } /** * Whether vector is projected into positive xy quadrant. */ function isOutwardVector(vector) { return !fuzzyEquals(vector.x, 0) ? vector.x > 0 : vector.y > 0 } /** * vector utilities */ function normalizeVector(v) { const d = Math.sqrt(v.x * v.x + v.y * v.y) return { x: v.x / d, y: v.y / d } } function rotateVector(v, theta) { return { x: v.x * Math.cos(theta) - v.y * Math.sin(theta), y: v.x * Math.sin(theta) + v.y * Math.cos(theta) } } function negateVector(v) { return { x: -v.x, y: -v.y } } function addVectors(v1, v2) { return { x: v1.x + v2.x, y: v1.y + v2.y } } /** * GTFS utilities */ function otpModeToGtfsType(otpMode) { switch (otpMode) { case 'TRAM': return 0 case 'SUBWAY': return 1 case 'RAIL': return 2 case 'BUS': return 3 case 'FERRY': return 4 case 'CABLE_CAR': return 5 case 'GONDOLA': return 6 case 'FUNICULAR': return 7 } } // Rendering utilities function renderDataToSvgPath(renderData) { return renderData .map((d, k) => { if (k === 0) return `M${d.x} ${d.y}` if (d.arc) { return `A${d.radius} ${d.radius} ${d.arc} 0 ${d.arc > 0 ? 0 : 1} ${ d.x } ${d.y}` } return `L${d.x} ${d.y}` }) .join(' ') } // An instance of the SphericalMercator converter const sm = new SphericalMercator() /** * @param {*} fontSize A CSS font size or a numerical (pixel) font size. * @returns A CSS font size ending with the provided CSS unit or 'px' if none provided. */ function getFontSizeWithUnit(fontSize) { return fontSize + (isFinite(fontSize) ? 'px' : '') } export { fuzzyEquals, distance, getRadiusFromAngleChord, ccw, ccwRaw, angleFromThreePoints, pointAlongArc, getVectorAngle, rayIntersection, lineIntersection, parsePixelStyle, isOutwardVector, normalizeVector, rotateVector, negateVector, addVectors, otpModeToGtfsType, renderDataToSvgPath, sm, getFontSizeWithUnit }
var connect = require('connect'), http = require('http'), bodyParser = require('body-parser'), calc = require('./lib/math'); var app = connect(); app.use(bodyParser()); app.use(bodyParser.json()); app.use(bodyParser.urlencoded()); app.use(function (req, res, next) { //log the request console.log('INCOMING REQUEST [' + req.method + '] TO ' + req.url + ': ' + req.body.data); next(); }); //the meat of the function app.use('/math', function (req, res, next) { if (req.method === 'POST') { var mathOper; try { mathOper = JSON.parse(req.body).data; } catch (e) { mathOper = req.body.data; } calc.calculate(mathOper, function (err, result) { if (err) { console.log('ERROR: ' + err); res.writeHead(400, { 'Content-Type': 'text/plain' }); return res.end(err.message); } res.end(JSON.stringify(result)); }); } else { next(); } }); //handle other routes app.use(function (req, res, next) { res.writeHead(404, { 'Content-Type': 'text/plain' }); res.end('Page not found!!'); }); http.createServer(app).listen(3000, function () { console.log('Server started on port:', 3000); });