text
stringlengths
7
3.69M
import React from 'react'; const SearchPanel = ({label, onFiltersChange}) => { return ( <input type="text" value={label} onChange={(e) => onFiltersChange('label', e.target.value)} className="form-control search-panel" placeholder="Type here to search" /> ); }; export default SearchPanel;
import React from "react"; import {Button, Card, message, Popconfirm} from "antd"; const text = 'Are you sure delete this task?'; const Placement = () => { function confirm() { message.info('Click on Yes.'); } return ( <Card title="Placement" className="gx-card"> <div className="gx-overflow-auto"> <div style={{marginLeft: 70, whiteSpace: 'nowrap'}}> <Popconfirm placement="topLeft" title={text} onConfirm={confirm} okText="Yes" cancelText="No"> <Button>TL</Button> </Popconfirm> <Popconfirm placement="top" title={text} onConfirm={confirm} okText="Yes" cancelText="No"> <Button>Top</Button> </Popconfirm> <Popconfirm placement="topRight" title={text} onConfirm={confirm} okText="Yes" cancelText="No"> <Button>TR</Button> </Popconfirm> </div> <div style={{width: 70, float: 'left'}}> <Popconfirm placement="leftTop" title={text} onConfirm={confirm} okText="Yes" cancelText="No"> <Button>LT</Button> </Popconfirm> <Popconfirm placement="left" title={text} onConfirm={confirm} okText="Yes" cancelText="No"> <Button>Left</Button> </Popconfirm> <Popconfirm placement="leftBottom" title={text} onConfirm={confirm} okText="Yes" cancelText="No"> <Button>LB</Button> </Popconfirm> </div> <div style={{width: 70, marginLeft: 304}}> <Popconfirm placement="rightTop" title={text} onConfirm={confirm} okText="Yes" cancelText="No"> <Button>RT</Button> </Popconfirm> <Popconfirm placement="right" title={text} onConfirm={confirm} okText="Yes" cancelText="No"> <Button>Right</Button> </Popconfirm> <Popconfirm placement="rightBottom" title={text} onConfirm={confirm} okText="Yes" cancelText="No"> <Button>RB</Button> </Popconfirm> </div> <div style={{marginLeft: 70, clear: 'both', whiteSpace: 'nowrap'}}> <Popconfirm placement="bottomLeft" title={text} onConfirm={confirm} okText="Yes" cancelText="No"> <Button>BL</Button> </Popconfirm> <Popconfirm placement="bottom" title={text} onConfirm={confirm} okText="Yes" cancelText="No"> <Button>Bottom</Button> </Popconfirm> <Popconfirm placement="bottomRight" title={text} onConfirm={confirm} okText="Yes" cancelText="No"> <Button>BR</Button> </Popconfirm> </div> </div> </Card> ); }; export default Placement;
'use strict'; const fns = {}; const noop = () => {}; fns.report = function(msg, next) { this.prior(msg, (nn, response) => { msg.origin_role = msg.role; msg.role = 'reporter'; msg.data = response.data; try { this.fire(msg, null); } catch (e) {} next(null, response); }); }; module.exports = fns;
//node 模块所以要用require 而不是import var path = require('path'); var webpack = require('webpack'); var ExtractTextPlugin = require("extract-text-webpack-plugin"); var HtmlWebpackPlugin = require('html-webpack-plugin'); var ROOT_PATH = path.resolve(__dirname); var APP_PATH = path.resolve(__dirname, './src/app'); var BUILD_PATH = path.resolve(__dirname, './build'); //把第三方代码和应用本身的代码一起打包是非常低效的。 //因为浏览器会根据缓存头来缓存资源文件, 如果文件没有被改变, //文件将会被缓存从而不用去再次请求 cdn。为了利用这一特性, //我们希望不管应用本身的代码如何改变, //vendor 文件的 hash 始终恒定不变 module.exports = { entry: { app: APP_PATH, common: [ "react", 'react-dom', 'react-router', 'redux', 'react-redux', 'redux-thunk', 'immutable' ] }, output: { path: BUILD_PATH, filename: '[chunkhash].[name].js' }, module: { rules: [{ test: /\.js?$/, exclude: /^node_modules$/, loaders: 'babel-loader' }, { test: /\.jsx?$/, exclude: /^node_modules$/, loaders: 'babel-loader' }, { test: /\.less$/, exclude: /^node_modules$/, use: ExtractTextPlugin.extract({ fallback: "style-loader", use: ["css-loader", "less-loader"] }) }, { test: /\.scss$/, exclude: /^node_modules$/, use: ExtractTextPlugin.extract({ fallback: "style-loader", use: ["css-loader", "sass-loader"] }) }, { test: /\.css$/, exclude: /^node_modules$/, use: ExtractTextPlugin.extract({ fallback: "style-loader", use: ["css-loader"] }) }, { test: /\.(png|jpg)$/, exclude: /^node_modules$/, loaders: 'url-loader?limit=8192&name=images/[hash:8].[name].[ext]', //注意后面那个limit的参数,当你图片大小小于这个限制的时候,会自动启用base64编码图片 }] }, devServer: { inline: true, port: 8000 }, plugins: [ new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify('development') //定义编译环境 } }), new ExtractTextPlugin('[chunkhash].[name].min.css'), new HtmlWebpackPlugin({ template: './src/temp/index.html' }), new webpack.optimize.CommonsChunkPlugin({ name: 'common' }), //new webpack.optimize.UglifyJsPlugin() ], resolve: { extensions: ['.js', '.jsx', '.less', '.scss', '.css'] } };
'use strict'; describe('Mq Service', function() { var mqService; beforeEach(module('FEF-Angular-UI')); var setUp = inject(function(MqService) { mqService = MqService; }); xit("should throw an error if Modernizr is not defined", function() { Modernizr = undefined; setUp(); expect(mqService.mq()).toThrow("Modernizr is not defined"); }); it("should return Modernizr.mq method", function() { setUp(); expect(mqService.mq).toEqual(Modernizr.mq); }); });
export const DOMAIN_API = 'http://localhost:5000/'; export const ENDPOINT_POST_URLS = 'api/urls'; export const ENDPOINT_KEY = 'api/'; //':key' export const ENDPOINT_DELETE = 'api/urls/'; //':key'; export const ENDPOINT_KEY_STATS = 'api/urls/:key/stats';
import firebase from 'firebase'; firebase.initializeApp({ apiKey: 'AIzaSyDcQKiqbyq0t8u1aXXBjEV0rX-UKaeevJc', authDomain: 'my-doctor-b6c56.firebaseapp.com', databaseURL: 'https://my-doctor-b6c56.firebaseio.com', projectId: 'my-doctor-b6c56', storageBucket: 'my-doctor-b6c56.appspot.com', messagingSenderId: '724125502006', appId: '1:724125502006:web:380e741831c0198d066697', }); const Firebase = firebase; export default Firebase;
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import John from './John'; import Anna from './Anna' import ListPeople from './ListPeople' import Feed from './Feed' import MyProfile from './MyProfile' import Messages from './Messages' import './App.css'; import { Row, Col, Icon, Menu, Badge } from 'antd'; import * as serviceWorker from './serviceWorker'; import Sidebar from "react-sidebar"; import { BrowserRouter as Router, Route, Link } from 'react-router-dom' import createBrowserHistory from 'history/createBrowserHistory' const SubMenu = Menu.SubMenu; const MenuItemGroup = Menu.ItemGroup; const customHistory = createBrowserHistory() class AppRouter extends React.Component { state = { expanded: false, isBackButton: false } toggleLeft = () => { this.setState({expanded: !this.state.expanded}) console.log("expanded") } goBack = () => { customHistory.goBack() this.setState({isBackButton: false}) console.log("aewjh") } setToBack = () => { this.setState({isBackButton: true}) } componentDidMount() { if (window.location.pathname === '/john' || window.location.pathname === '/anna') this.setState({isBackButton: true}); } render() { return ( <Router history={customHistory}> <div> {/* <Route path={`/john`} component={John}/> */} <div style={{position: 'fixed', height: 50, width: '100%', backgroundColor: '#fff', zIndex: 10}}> <Row style={{height: 50, paddingTop: 5, paddingBottom: 10, paddingLeft: 10, paddingRight: 10, borderBottom: '.5px solid grey'}}> {/* <Col span={2}></Col> */} <Col span={8} /> <Col span={8} style={{paddingTop: 0, textAlign: 'center'}}><span style={{color: '#91268F', fontWeight: 600, fontSize: 25, }}>Prospect</span></Col> </Row> </div> {/* {this.state.expanded && ( */} {/* <Menu */} {/* onClick={this.handleClick} */} {/* style={{ width: 256, position: 'absolute', zIndex: 10, height: '96%' }} */} {/* defaultSelectedKeys={['1']} */} {/* defaultOpenKeys={['sub1']} */} {/* mode="inline" */} {/* > */} {/* */} {/* </Menu> */} {/* )} */} <Sidebar sidebar={ <div style={{flex: 1, flexDirection: 'column', fontSize: 20, paddingTop: 50}}> <div key="messages" style={{paddingTop: 20}}><Link onClick={() => this.toggleLeft()} to={"messages"} style={{color: '#91268F'}}><Icon type="message" style={{paddingRight: 10}} /><span>Messages</span></Link><Badge count={1} style={{ backgroundColor: '#52c41a', marginTop: -20 }} /></div> <div key="feed" style={{paddingTop: 20}}><Link onClick={() => this.toggleLeft()} to={"/"} style={{color: '#91268F'}}><Icon type="align-left" style={{paddingRight: 10}} /><span>Feed</span></Link></div> <div key="connect" style={{paddingTop: 20}} ><Link onClick={() => this.toggleLeft()} to={"list"} style={{color: '#91268F'}}><Icon type="user-add" style={{paddingRight: 10}} /><span>Connect</span></Link></div> <div key="myprofile" style={{paddingTop: 20}}><Link onClick={() => this.toggleLeft()} to={"profile"} style={{color: '#91268F'}}><Icon type="idcard" style={{paddingRight: 10}} /><span>My Profile</span></Link></div> </div> } open={this.state.expanded} onSetOpen={this.toggleLeft} styles={{ sidebar: { background: "white",height: '100%', paddingRight: 20, paddingLeft: 20, width: '60%', position: 'fixed' } }} > {/* <button onClick={() => this.onSetSidebarOpen(true)}> */} <div> {this.state.isBackButton? <Icon onClick={() => this.goBack()} type="left" style={{zIndex: 10, paddingLeft: 10, position: 'fixed', fontSize: 20, marginTop: 15, color: '#91268F'}} /> : <Icon onClick={() => this.toggleLeft()} type="bars" style={{zIndex: 10, paddingLeft: 10, position: 'fixed', fontSize: 20, marginTop: 15, color: '#91268F'}} /> } </div> {/* </button> */} </Sidebar> <div className="App" style={{paddingTop: 50}}> <Route path="/john" component={John}/> <Route path="/anna" component={Anna}/> <Route path="/list" component={() => <ListPeople showBack={this.setToBack} />}/> <Route path="/profile" component={MyProfile}/> <Route path="/messages" component={Messages}/> <Route path="/" exact component={Feed}/> </div> </div> </Router> ); } } ReactDOM.render(<AppRouter />, document.getElementById('root')); // If you want your app to work offline and load faster, you can change // unregister() to register() below. Note this comes with some pitfalls. // Learn more about service workers: http://bit.ly/CRA-PWA serviceWorker.unregister();
var dir_90f0eba0315374579a2e79c7bff15e5c = [ [ "PDEDialog.java", "_p_d_e_dialog_8java.html", [ [ "PDEDialog", "classde_1_1telekom_1_1pde_1_1codelibrary_1_1ui_1_1components_1_1dialog_1_1_p_d_e_dialog.html", "classde_1_1telekom_1_1pde_1_1codelibrary_1_1ui_1_1components_1_1dialog_1_1_p_d_e_dialog" ] ] ], [ "PDEDialogActivity.java", "_p_d_e_dialog_activity_8java.html", [ [ "PDEDialogActivity", "classde_1_1telekom_1_1pde_1_1codelibrary_1_1ui_1_1components_1_1dialog_1_1_p_d_e_dialog_activity.html", "classde_1_1telekom_1_1pde_1_1codelibrary_1_1ui_1_1components_1_1dialog_1_1_p_d_e_dialog_activity" ] ] ], [ "PDEDialogConfig.java", "_p_d_e_dialog_config_8java.html", [ [ "PDEDialogConfig", "classde_1_1telekom_1_1pde_1_1codelibrary_1_1ui_1_1components_1_1dialog_1_1_p_d_e_dialog_config.html", "classde_1_1telekom_1_1pde_1_1codelibrary_1_1ui_1_1components_1_1dialog_1_1_p_d_e_dialog_config" ] ] ], [ "PDEEventDialog.java", "_p_d_e_event_dialog_8java.html", [ [ "PDEEventDialog", "classde_1_1telekom_1_1pde_1_1codelibrary_1_1ui_1_1components_1_1dialog_1_1_p_d_e_event_dialog.html", "classde_1_1telekom_1_1pde_1_1codelibrary_1_1ui_1_1components_1_1dialog_1_1_p_d_e_event_dialog" ] ] ] ];
/** * */ $(document).ready(function() { $("#button_submit").click(function() { var pas1 = $("#pas1").val(); var pas2 = $("#pas2").val(); var hasError = false; if (pas1 == '') { hasError = true; } else if (pas2 == '') { hasError = true; } else if (pas1 != pas2) { hasError = true; } if (hasError == true) { alert("Enter correct password"); }else { $("form").submit(); } }); });
import { Meteor } from 'meteor/meteor'; import { Template } from 'meteor/templating'; import { Products } from '../Collections/Products.js'; import { Carts } from '../Collections/Carts.js'; import '../client/layouts/BuyerHomeLayout.html'; import '../client/layouts/BuyerMainLayout.html'; import './buyervegansnacks.html'; Template.BuyerHomeLayout.onCreated(function () { Meteor.subscribe('products'); Meteor.subscribe('carts'); }); Template.buyervegansnacks.helpers({ 'Veganproducts': function() { return Products.find({Veganapproved: "Yes"}); } });
import React, { useContext } from "react"; import styled from "styled-components"; import { DispatchContext, StateContext } from "@home/Game"; import { ThemeContext } from "@common/Layout"; import { keyboard } from "@utils/constants"; import { SET_SCALE } from "@reducer/action-types"; import { FlexBox, StyledLabel } from "@common/Generic"; const { keyMargin, blackWidth, blackHeight, whiteHeight, whiteWidth } = keyboard; const isBlack = (keyIndex) => { const blackKeysIndexes = [1, 3, 6, 8, 10]; return blackKeysIndexes.includes(keyIndex); }; const KeysButtons = (props) => [...Array(12).keys()].map((keyIndex) => ( <NoteButtons colors={props.colors} key={keyIndex} isBlack={isBlack(keyIndex)} note={keyIndex} isNoteUsed={props.scale[keyIndex]} onClick={() => props.dispatch({ type: SET_SCALE, key: keyIndex })} ></NoteButtons> )); const NoteButtons = styled.div` box-sizing: border-box; height: ${({ isBlack }) => (isBlack ? blackHeight : whiteHeight)}; width: ${({ isBlack }) => (isBlack ? blackWidth : whiteWidth)}; margin-left: ${({ isBlack }) => (isBlack ? `calc(${blackWidth}/-2)` : `-${keyMargin}`)}; margin-right: ${({ isBlack }) => (isBlack ? `calc(${blackWidth}/-2)` : `-${keyMargin}`)}; z-index: ${({ isBlack }) => (isBlack ? 1 : 0)}; background-color: ${({ isNoteUsed, isBlack, colors }) => isNoteUsed ? colors.green : isBlack ? "black" : colors.grey}; border: ${() => `${keyMargin} solid black`}; transition: background-color 0.3s; `; export const Keyboard = () => { const { scale } = useContext(StateContext); const colors = useContext(ThemeContext); const dispatch = useContext(DispatchContext); return ( <> <StyledLabel color={colors.grey}>Notes to use:</StyledLabel> <FlexBox row align="flex-start" style={{ margin: "10px" }}> <KeysButtons colors={colors} scale={scale} dispatch={dispatch} /> </FlexBox> </> ); };
const titleWords = require('../src/algorithms/titleWords'); describe('titleWords', () => { it('should throw an error if the input is not a string', () => { const actual = titleWords(7); expect(actual).toBe('you need a string'); }); it('should capitalize ONLY the beginning of each word', () => { const actual = titleWords('this iS mY sTrInG'); expect(actual).toBe('This Is My String'); }); });
import React from 'react' import { Title } from '../../../Titles/Title/Title' export const WhoDie = (props) => { const { whoDie } = props return ( <> <Title title={`${whoDie.death}`} size="small" /> </> ) }
// @flow import * as React from "react"; import { Collapsible } from "../Collapsible/Collapsible"; import "./css/ListMultipleSelect.css"; type OptionType = { id: number, title: string }; type Props = { title?: string, value: Array<number>, options: Array<OptionType>, disabled?: boolean, isCollapsed?: boolean, collapseDisabled?: boolean, ulAdditionalClass?: string, showSelectAllCheckbox?: boolean, onChange: ( Array<number> ) => void }; type OptionProps = { id: number, title: string, active: boolean, onClick: () => void }; function Option( props: OptionProps ): React.Node { if( props.active ) return <li className="analytic-office__list-item-selected" onClick={ props.onClick }>{ props.title }</li>; return <li onClick={ props.onClick }>{ props.title }</li>; } export function ListMultipleSelect( props: Props ): React.Node { const onClick = ( id: number ) => { let newValue; if( props.disabled ) return; const index = props.value.indexOf( id ); if( index === -1 ) // Immutable add to array newValue = [ ...props.value, id ]; else // Immutable delete from array newValue = props.value.slice( 0, index ).concat( props.value.slice( index + 1 ) ); props.onChange( newValue ); }; const onSelectAllCheckboxChange = () => props.onChange( props.value.length === props.options.length ? [] : props.options.map( ( option: OptionType ) => option.id ) ); let selectAll = null; // By default select all checkbox is shown if( props.showSelectAllCheckbox === undefined || props.showSelectAllCheckbox ) selectAll = () => <span><input type="checkbox" className="analytic-office__select-all" disabled={ props.disabled } checked={ props.value.length === props.options.length ? "checked" : "" } onChange={ onSelectAllCheckboxChange } />Выделить все { props.value.length }/{ props.options.length }</span>; let ulClass = "analytic-office__container-list analytic-office__list"; if( props.ulAdditionalClass !== undefined ) ulClass += " " + props.ulAdditionalClass; let isCollapsed = props.isCollapsed || ( props.collapseDisabled && props.disabled ) || false; return ( <Collapsible title={ props.title } renderTitle={ selectAll } isOpen={ !isCollapsed }> <ul className={ ulClass }> { props.options.map( ( option: OptionType ): React.Node => <Option key={ option.id } { ...option } active={ props.value.indexOf( option.id ) !== -1 } onClick={ (): void => onClick( option.id ) } /> ) } </ul> </Collapsible> ); }
import React from 'react'; import { Grid, Responsive, Image, Segment, List, Icon } from 'semantic-ui-react'; import Layout from '../components/Layout/'; import Trio from '../components/Trio'; import DigitalImage from '../../public/static/images/digital-image.jpg'; import MapImage from '../../public/static/images/map.png'; import Helmet from 'react-helmet'; const centerContent = ( <div> <Image src={DigitalImage}/> </div> ); const sideContent = ( <Segment textAlign="center" padded> <a href="https://goo.gl/tbkkUH" target="_bank"> <Image src={MapImage} centered="true"/> </a> <h4><Icon name="time"/>Hours of Operation</h4> <List divided relaxed> <List.Item>Mon 8:00 AM - 5:00 PM</List.Item> <List.Item>Tue 8:00 AM - 5:00 PM</List.Item> <List.Item>Wed 8:00 AM - 5:00 PM</List.Item> <List.Item>Thur 8:00 AM - 5:00 PM</List.Item> <List.Item>Fri 8:00 AM - 5:00 PM</List.Item> </List> </Segment> ); const keywords = "Advanced Digital NYC, digital printing, printing,\ printing solutions, posters, brochures, ecofriendly"; class IndexPage extends React.Component { render() { return ( <> <Helmet title={"Advanced Digital NYC"} meta={[ { name: 'description', content: 'Advanced Digital NYC is your solution to all your digital printing needs.\ We offer various services such as printing of posters, brochures, business cards and more.\ We also offer products made with high quality, and ecofriendly material.', }, { name: 'keywords', content: keywords }, ]} /> <Layout> <Responsive {...Responsive.onlyMobile}> <Grid> <Grid.Row centered padded="true" columns={2}> <Grid.Column width={16} stackable="true"> {centerContent} {sideContent} </Grid.Column> </Grid.Row> </Grid> <Trio /> </Responsive> <Responsive minWidth={Responsive.onlyTablet.minWidth}> <Grid> <Grid.Row centered padded="true" columns={2}> <Grid.Column width={5} textAlign='left'> {sideContent} </Grid.Column> <Grid.Column width={11}> {centerContent} </Grid.Column> </Grid.Row> </Grid> <Trio /> </Responsive> </Layout> </> ); } } export default IndexPage
const name = { ACTIVE: 'active', // 激活状态 CHECK: 'check_status', // 审核状态 RECEIVE_ORDER_STATUS: 'order_receive_status', // 待接订单状态 INPUT_ORDER_STATUS: 'order_create_status', // 订单录入状态 SPLIT_ORDER_STATUS: 'order_split_status', // 订单拆分状态 JOB_ORDER_STATUS: 'order_maintain_status', // 订单维护状态 DIRECTION: 'goods_direction', //货物流向 CONSIGNMENT: 'consignment_note', //随货单据 SIGN_DOCUMENTS: 'sign_documents', //签收单证要求 PACKEGING_UNIT: 'packaging_unit', //包装单位 HANDOVER_MODE: 'HANDOVER_MODE', //货物交接方式 BONDED_TRADE_MODE: 'bonded_trade_mode', //保税贸易方式 BONDED_SUPERVISION_MODE: 'bonded_supervision_mode', //保税监管方式 CONTAINER_LOCATION: 'container_location', //集装箱摆货要求/摆尾要求 TRANSPORTATION_CLAUSE: 'air_transportation_clause',//客户运输条款 PAYMENT_METHOD: 'payment_method',//客户付款方式 VGM_WEIGH: 'vgm_weighing_method',//VGM过磅方式 GENERIC_WEIGH: 'weighing_method',//普通过磅方式 WEIGH: 'weighing_method',//普通过磅方式 CUSTOMS_TYPE: 'customs_type',//报关方式 QUARANTINE_MODE: 'quarantine_mode',//检疫方式 SEAMLESS: 'seamless_customs_clearance',//无缝清关 SIGN_SEND: 'sign_bill_send', //签收单送交 HIGHWAY: 'highway_manifest',//公路舱单 NUMBER_TYPE: 'csnum_type',//客户单号种类 TRANS_MODE_MAINLAND: 'mainland_transportation_mode', //国内运输模式 TRANS_MODE_PORT: 'port_transportation_mode', //港口运输模式 SEA_BILL_TYPE: 'SEA_BILL_TYPE', //客户提单类型 AIR_TRANSPORT_DIRECTION: 'air_transport_direction', //运输方向 AIR_FILE: 'air_file', //航空随机文件 AIR_TRANSPORTATION_CLAUSE: 'air_transportation_clause', //空运运输条款 PICKUP_DELIVERY: 'PICKUP_DELIVER', //提货/派送 SEA_TRANSPORTATION_CLAUSE: 'air_transportation_clause', //海运运输条款 IMPORT_EXPORT_TYPE: 'import_export_type', //进出口类型 AGENT_SERVICE_TYPE: 'agent_service_type', //代办服务类型 WAREHOUSE_TYPE: 'warehouse_type',//仓库操作 WAREHOUSE_OPERATION_TYPE: 'warehouse_operation_type', //库内操作类型 STATUS: 'status', //所有状态 YES_OR_NO: 'true_false_type', //是否 CHARGE_TYPE: 'charge_type', // 费用类型 TASK_TYPE: 'task_type', // 业务属性 TAX_TYPE: 'tax_rate_way', //计税方式 CHARGE_UNIT: 'charge_unit', //计量单位 RESPONSIBLE: 'responsible_party', // 责任方 REASON_TYPE: 'occurrence_class', // 发生类别 CHARGE_DIRECTION: 'chargeDirection', // 费用方向 TENANT_TYPE: 'tenant_type', // 租户类别 CONTAINER_TYPE: 'container_type', // 柜车类型 LANGUAGE: 'language_version', // 语言版本 ADDR_TYPE: 'place_type', // 运输地点类别 LOCATION_TYPE: 'location_type', // 地点联系人地点类别 BALANCE_WAY: 'balance_way', // 结算方式 BALANCE_CURRENCY: 'balance_currency_type', // 结算币种 CONTACT_TYPE: 'contact_type', // 联系人类型 SEX: 'sex_type', // 性别 STATUS_TYPE: 'status_type', // 费用状态 GOODS_TYPE: 'goods_category', // 货物类别 CANVASSION_MODE: 'canvassion_mode', // 揽货方式 CHANGE_SHEET_REASON: 'change_sheet_reason', // 改单原因 SUPPLIER_BUSINESS_TYPE: 'supplier_business_type', // 供应商业务类型 PLAN_STATUS: 'logistics_order_plan_status', // 物流计划状态 DISPATCH_STATUS: 'delivery_order_status', // 派单中心状态 HBL_MBL_TYPE: 'hbl_mbl_type', // 空运提单hbl方式 DELIVERY_TERMS: 'delivery_terms', //空运放货方式 TELEX_RELEASED_LADING_ORIGINAL_BILL: 'telex_released_lading_original_bill', // 电放或者正本 TRACE_TYPE: 'trace_type', // 跟踪单类型 OPERATION_CONDITION_TYPE: 'operation_condition_type', LLP_TRANSPORTATION_MODE: 'llp_transportation_mode', // LLP运输方式 BALANCE_CURRENCY_TYPE: 'balance_currency_type', // LLP结算币种 CUSTOMER_CONTACTS_CATEGORY: 'customer_contacts_category', // LLP客户联系人类别 SUPPLY_CONTACTS_CATEGORY: 'supply_contacts_category', // LLP供货商联系人类别 LLP_TRANSPORTATION_CLAUSE: 'llp_transportation_clause', // LLP贸易条款 PRODUCT_CATEGORY : 'product_category', // LLP品类 BOOK_MATCH_ORDER_TYPE: 'book_match_order_type', // 预约匹配类型 ORDER_FROM: 'order_from', // LLP订单来源 GOODS_CATEGORY:'goods_category', //货物类别 CHARGE_ID: 'charge_id', //费用名称 CHARGE_MEASURE_UNIT_ID: 'charge_measure_unit_id', //划分物流责任计量单位 COLLECT_REMIT_TYPE: 'collect_remit_type', //llp 划分物流责任费用类型 COMPONENT_TYPE: 'component_type',//数据类型 MATERIAL_ATTRIBUTE: 'materiel_attribute_label',//多语言标签 BUSINESS_ORDER: 'business_order_type',//商流订单类别 BOOKING_TYPE: 'order_booking_type',//预约订单类别 MATCH_MODEL: 'book_match_model',//匹配方式 SHIPMENT_SCHEDULE_STATUS_TYPE: 'shipment_schedule_status_type', // 出货预约状态 INVOICE_TYPE: 'invoice_type', // 发票类型 INVOICE_CATEGORY: 'invoice_category', // 发票种类 LOGISTICS_RESPONSIBILITY_TYPE: 'logistics_responsibility_type', // 物流责任 LLP_LOGISTICS_ORDER_TYPE: 'llp_Logistics_order_type',//llp物流订单类型 LLP_STATUS: 'status_type', //LLP订单状态 EXCEPTION_CATEGORY: 'exception_category', // 异常大类 EXCEPTION_OWNER: 'exception_owner', // 异常责任人 EXCEPTION_RELATION_TYPE: 'exception_relation_type', //异常关联单类型, FILE_TYPE: 'file_type', // 文件类型 VALUE_ADDED_SERVICE: 'value_added_service', //增值服务类型 FREIGHT_COLLECT_APPLICATION: 'freight_collect_application', // 到付申请状态 CHARGE_ORIGIN: 'charge_origin', // 费用来源 BARGE_TYPE: 'barge_type', //驳船类型 TRANSFER_MODE: 'transfer_mode', //驳船中转方式 BARGE_CONTAINER_TYPE: 'barge_container_type', //驳船货柜类别 CROSSDOCKING_TRANSPORT_TYPE: 'crossdocking_transport_type', //越库运输类型 BUSINESS_ORDER_TYPE: 'business_order_type', //商流订单类型 TABLE_NUMBER_TYPE: 'table_number_type', DISMANTLE_LOAD_TYPE: 'dismantle_load_type', //拆装卸类型 LOAD_WAY: 'load_way', //装船方式 JOB_WAY: 'job_way', //作业方式 RELEASE_STATUS: 'release_status', //放货状态 CURRENCY: 'currency', LOGISTICS_ORDER_TYPE: 'logistics_order_type', //订单类型,物流订单主单字段, OPERATION_TYPE: 'operation_type', // 运输模式 RELATION_TABLE: 'relation_table', //关联规则表 PREPAY_CURRENCY: 'prepay_currency', //代垫币种 PAYMENT_WAY: 'payment_way', //代垫付款方式 TASK_UNIT_STATUS: 'task_unit_status', //作业单元状态 REQUEST_METHOD:'requestMethod' ,//请求方式 REQUIRE_TYPE: 'special_require_type', //特殊要求类别 SPECIAL_CARGO_TYPE: 'special_cargo_type', //特殊货物类型 SPECIAL_CAR_TYPE: 'special_car_type', //特种车类型 BACK_ORDER: 'back_order', //推单 TENANT_LOCATION_TYPE: 'tenant_location_type', // 租户地点类型 GOODS_CLASSIFICATION: 'goods_classification', //货物分类 LEG_CLASSIFICATION: 'leg_classification', //作业环节 PICKUP_DELIVERY_MODE: 'pickup_delivery_mode', //提送货方式 RETAIL_BUSINESS_CLASSIFICATION: 'retail_business_classification', //业务分类 CUSTOMER_PAY_INTENTION:'customer_pay_intention',//客户支付意向 RULE_TYPE: 'rule_type', //规则类型 LOAD_UNLOAD_TYPE_RAILWAY: 'load_unload_type_railway', //装卸方式-火车 MECHANICAL_TYPE: 'mechanical_type', //机械类型 LOAD_UNLOAD_TYPE_TRUCK: 'load_unload_type_truck', //装卸方式-汽车 QUERY_GROUP: 'query_group', //查询组合 OPERATION_TEAM: 'operation_team', //作业班组 RENEWAL_MODE: 'renewal_mode', //改单类别 LOAD_UNLOAD_TYPE: 'load_unload_type', //装卸类型 SUPPLIER_TYPE: 'supplier_type',//供应商类型 CUSTOMER_TYPE: 'customer_type',//客户类型 BUSINESS_VARIETY: 'business_variety', //业务品种 OPERATION_WAY: 'operation_way',//操作方法 EXCEL_REPORT_GROUP: 'excel_report_group',//报表组 INTERFACE_STATUS: 'interface_status',//对接状态 REPORT_OUTPUT_TYPE:'report_output_type' ,//输出类型 INCOME_COST_TYPE: 'income_cost_type', //结算类型 OTHER_PRODUCT_TYPE: 'other_product_type', //单据类型 NOTIFY_TYPE: 'notify_type', //通知类型 UPLOAD_STATE: 'upload_state', //附件状态 FILE_STAUS: 'file_status', //文件状态 PORT_OPERATION_TEAM: 'port_operation_team', //码头作业班组 RECEIVE_STATE: 'receive_state', //资料回收 APPOINTMENT_QUERY_STATUS: 'appointment_query_status', //预约查询状态 MAIL_SEND_TYPE: 'mail_send_type', //发送方式 MODEL_TYPE: 'model_type', //模板类别 APPORTIONMENT_RULE: 'apportionment_rule', //分摊规则 SPLIT_TYPE: 'splitType', //货量拆分类别 SYNCHRONIZATION_STATUS: 'synchronization_status', //同步状态 PRICE_CATEGORY_TYPE:'priceCategoryType',//合同类别 SUB_TASK_UNIT: 'sub_Task_Unit' , //国内运输子任务 NODE_CLASSIFY_TYPE:'lifecycle_type', //节点类型, LIFE_STYLE_NODE_APP:"lifecycle_node_app", PRICE_MODE:'price_mode',//报价模式 HANDLE_GOODS_TYPE: "handle_goods_type", //货物处理方式 TRUE_FALSE_TYPE:"true_false_type", //是否 IS_MULTIPLE_GOODS: 'is_multiple_goods', //异常原因 WAREHOUSE_TYPE1: 'warehouse_attribution_type', //仓库类型 BARCODE_UNIT: 'barcode_unit', //条形码单位, SEASHUTTLEBUSTYPE: 'seaShuttlebustype', //海运穿梭巴士类型 UPLOAD_MODE: 'upload_mode', //导入模式, APP_TYPE: 'app_type', //App类型 LIFECYCLE_TYPE: 'lifecycle_multipoint_type', //装卸货类型 CHARGE_FROM: 'charge_from', // 改单额外费用来源 ENABLED_TYPE: 'enabled_type', //客户档案--状态 COMPANY_TYPE: 'company_type', //客户档案--类型 COMPANY_LEVEL: 'company_level', //客户档案--级别 Y_OR_N: 'zero_one_type', //是/否(0/1) LOGISTICS_COMPANY_TYPE: 'logistics_company_type', //物流公司档案档案--类型 COST_TYPE: 'cost_type', //付款单类型 INCOME_TYPE: 'income_type', //收款单类型 TABLE_PROPERTY_TYPE: 'table_property_type', //扩展备用字段表单 INBOUND_TYPE: 'inbound_type', //入库类型 OUTBOUND_TYPE: 'outbound_type', //入库类型 DELIVERY_TYPE: 'delivery_type', //采购退货单--交货方式 RETURN_TYPE: 'return_type', //采购退货单--退货方式 ZERO_ONE_TYPE: 'zero_one_type', //采购退货单--是否保价/险购买 PURCHASE_RESPONSIBILITY: 'purchase_responsibility', //采购退货单--物流/保险责任 SALE_RESPONSIBILITY: 'sale_responsibility', //销售退货单--物流/保险责任 APPOINTMENT_TYPE: 'appointment_type', //采购退货单--预约方式 COMMODITY_UNIT: 'commodity_unit', //采购退货单--基本单位 PAYMENT_TYPE: 'payment_type', //支付方式 SALE_ORDER_TYPE: 'sale_order_type', //订单类别 PACKAGE_UNIT: 'package_unit', //erp-包装单位, CONSIGNEE_CONSIGNOR_TYPE: 'consignee_consignor_type', //收发货人类型 BUSINESS_TYPE: 'business_type', //业务类型 TAX_RATE_WAY: 'tax_rate_way', //计税方式 ZERO_ONE: 'zero_one_type', //是否(0/1) TRANSPORT_TYPE: 'transport_type', //运输方式 RESPONSIBLE_PARTY: 'responsible_party', //责任方 TASK_TYPE_FILE: 'task_type_file', //文件任务 CAR_STATE: 'car_state', //车辆状态, FUEL_TYPE: 'fuel_type', //燃油种类, NUMBER_SOURCE: 'number_source', //数量源 CAR_STATE: 'car_state', //车辆状态 CUSTOMER_INFORMATION_FEEDBACK: 'customer_information_feedback', //客户信息反馈类型 CONTRACT_ROLES: 'contract_roles', //签署角色 EXPENSE_OUTPUT_TYPE: 'expense_output_type', //产值报销类型 SETTLEMENT_SYSTEM_STATUS: 'settlement_system_status', //对接状态 }; export default name;
/** * Call to action button * * Button that highlights common user needs. Appears on the homepage. Provides a link to a webpage where people can take action with the department. Includes a text label and link. Copy writing tip: Ideally starts with a verb. * */ (function (blocks, editor, i18n, element, components, _) { const __ = i18n.__; const el = element.createElement; const RichText = editor.RichText; const BlockControls = editor.BlockControls; const URLPopover = editor.URLPopover; blocks.registerBlockType('ca-design-system/card', { title: __('Call to action button', 'ca-design-system'), icon: 'format-aside', category: 'ca-design-system', description: __("Button that highlights common user needs. Appears on the homepage. Provides a link to a webpage where people can take action with the department. Includes a text label and link. Copy writing tip: Ideally starts with a verb.", "ca-design-system"), attributes: { title: { type: 'string' }, url: { type: 'string' } }, example: { attributes: { title: __('Card title', 'ca-design-system'), url: __('CardUrl', 'ca-design-system') } }, edit: function (props) { const attributes = props.attributes; const [isURLInputVisible, setIsURLInputVisible] = element.useState(false); const openURLInput = () => { if (isURLInputVisible) { setIsURLInputVisible(false); } else { setIsURLInputVisible(true); document.querySelector('.block-editor-url-popover__row input').focus(); } }; const closeURLInput = () => { setIsURLInputVisible(false); }; const onSubmitSrc = (event) => { event.preventDefault(); closeURLInput(); }; return [ el( BlockControls, { key: 'controls' }, el(components.ToolbarGroup, {}, el(components.ToolbarButton, { label: 'Enter card link URL', icon: 'admin-links', onClick: openURLInput, isPressed: isURLInputVisible }, el(URLPopover, { onClose: function () {} }, el('form', { className: isURLInputVisible ? 'block-editor-media-placeholder__url-input-form url-input-form' : 'disp-none', onSubmit: onSubmitSrc, onClick: function (event) { event.stopPropagation(); }, onClose: closeURLInput }, el(editor.URLInput, { className: 'block-editor-media-placeholder__url-input-field url-input-field--card', type: 'url', placeholder: 'Paste or type card URL', 'aria-label': 'Paste or type card URL', url: attributes.url, value: attributes.url, onChange: function (value) { props.setAttributes({ url: value }); }, onClose: closeURLInput, onSubmit: onSubmitSrc }), el(components.Button, { className: 'block-editor-media-placeholder__url-input-submit-button url-submit-button', icon: 'undo', label: 'Apply', 'aria-label': 'Submit', type: 'submit' }) ) ) ) ) ), el('div', { className: 'cagov-card cagov-stack' }, el(RichText, { tagName: 'span', inline: true, withoutInteractiveFormatting: true, className: 'card-text', placeholder: __( 'Write card title…', 'ca-design-system' ), value: attributes.title, onChange: function (value) { props.setAttributes({ title: value }); } }) ) ]; } }); })( window.wp.blocks, window.wp.blockEditor, window.wp.i18n, window.wp.element, window.wp.components, window._ );
'use strict'; /* App Module */ var diceApp = angular.module('diceApp', [ 'ngAnimate', 'diceControllers', ]); diceApp.factory('sheetFactory', function() { return new Sheet(); }); diceApp.factory('gameFactory', function() { return new DiceGame(); });
import React, { useState } from 'react'; import './App.css'; import axios from 'axios'; function App() { const [ handle, setHandle ] = useState(null); const [ codes, setCodes ] = useState([]); let [ message, setMessage ] = useState(''); const handleGetMessage = async (codes) => { let c = codes.join(" "); const response = await axios.get(`http://localhost:3333/api/?code=${c}`); const m = response.data.message; message = m; setMessage(message) return m; } const handleClick = async (code) => { if (code == 0) { clearTimeout(handle); if (codes.length > 0) { await handleGetMessage(codes); } codes.push(0); setCodes([...codes]); return; } if (handle) { const lastPosition = codes.length - 1; let lastCode = codes[lastPosition]; if (lastCode[0] != code) { await handleGetMessage(codes); clearTimeout(handle); let newHandle = setTimeout( async () => { await handleGetMessage(codes) setHandle(null); }, 1000) setHandle(newHandle); codes.push(code); setCodes([...codes]); } else { const newCode = `${lastCode}${code}`; codes[lastPosition] = newCode; setCodes([...codes]); clearTimeout(handle); let newHandle = setTimeout( async () => { await handleGetMessage(codes) setHandle(null); }, 1000) setHandle(newHandle); } } else { codes.push(code) setCodes([...codes]) let newHandle = setTimeout(async () => { await handleGetMessage(codes) setHandle(null); }, 1000) setHandle(newHandle); } } return ( <div className="box-phone"> <section className="box-display"> <h3 className="mark">Nokia</h3> <div className="visor"> {message} </div> </section> <section className="box-buttons"> <button className="button-action">1</button> <button className="button-action" onClick={() => handleClick('2')}> <span className="number">2</span> <span className="character">abc</span> </button> <button className="button-action" onClick={() => handleClick('3')}> <span className="number">3</span> <span className="character">def</span> </button> <button className="button-action" onClick={() => handleClick('4')}> <span className="number">4</span> <span className="character">ghi</span> </button> <button className="button-action" onClick={() => handleClick('5')}> <span className="number">5</span> <span className="character">jkl</span> </button> <button className="button-action" onClick={() => handleClick('6')}> <span className="number">6</span> <span className="character">mno</span> </button> <button className="button-action" onClick={() => handleClick('7')}> <span className="number">7</span> <span className="character">pqrs</span> </button> <button className="button-action" onClick={() => handleClick('8')}> <span className="number">8</span> <span className="character">tuv</span> </button> <button className="button-action" onClick={() => handleClick('9')}> <span className="number">9</span> <span className="character">wxyz</span> </button> <button className="button-action">*</button> <button className="button-action" onClick={() => handleClick('0')}> <span className="number">0</span> <span className="character">_</span> </button> <button className="button-action">#</button> </section> </div> ); } export default App;
import { listen } from 'popmotion'; import scroll from 'stylefire/scroll'; import React, { Component } from 'react'; import CommandBar from './CommandBar'; import ScrollBar from './ScrollBar'; import SystemBar from './SystemBar'; import Viewport from './Viewport'; import './index.module.css'; export default class About extends Component { constructor() { super(); this.state = { viewportScrollProgress: 0, viewportHeight: 0 }; } onScroll = scrollableHeight => scrollHeight => { if (!this.viewport) return; const progress = scrollHeight / scrollableHeight; this.viewportScroll.set('top', this.scrollableArea() * progress); return scrollHeight; }; scrollableArea = () => this.viewport.scrollHeight - this.state.viewportHeight; scrollProgress = () => this.viewportScroll.get('top') / this.scrollableArea(); onViewport = viewport => { if (!viewport) return; this.viewport = viewport; this.viewportScroll = scroll(viewport); }; startAnimation() { this.animation = listen(this.viewport, 'scroll').start(() => this.setState({ viewportScrollProgress: this.scrollProgress() }) ); } onResize() { if (!this.viewport) return; if (this.animation) this.animation.stop(); const { height } = this.viewport.getBoundingClientRect(); if (!height) setTimeout(() => this.onResize(), 100); this.setState({ viewportHeight: height }); requestAnimationFrame(() => this.startAnimation()); } componentDidMount() { if (!this.viewport) return; const { height } = this.viewport.getBoundingClientRect(); if (!height) setTimeout(() => this.onResize(), 100); this.setState({ viewportHeight: height }); listen(window, 'resize').start(() => this.onResize()); requestAnimationFrame(() => this.startAnimation()); } render() { return ( <section styleName="root" id="about" tabIndex="0"> <div styleName="window"> <SystemBar /> <CommandBar /> <div styleName="viewport"> <Viewport onViewport={this.onViewport} /> <ScrollBar onScroll={this.onScroll} viewportScrollProgress={this.state.viewportScrollProgress} /> </div> </div> </section> ); } }
import { getStyledSystemColors } from './getStyledSystemColors' import chroma from 'chroma-js' // colors: { // primary: "#000", // secondary: "#fff", // ... //} export function getColorsJSON(colors) { const colorsJSON = {} Object.entries(colors).forEach((colorObj) => { const styledSystemColors = getStyledSystemColors(chroma(colorObj[1])) colorsJSON[colorObj[0]] = {} styledSystemColors.forEach((styledSystemColor, idx) => { if (idx === 0) { colorsJSON[colorObj[0]]['50'] = styledSystemColor.hex() } else { colorsJSON[colorObj[0]][new String(idx * 100)] = styledSystemColor.hex() } }) }) return colorsJSON }
/* M:WoH Battle Simulator - Gary Longwith */ /* Initialization and Presentation Layer */ /* This file connects the page to the application logic */ requirejs.config({ baseUrl: 'assets/js', paths: { app: '../../src/modules' } }); requirejs(['jquery','app/simulator'], function ($, model) { $.fn.exists = function () { return this.length !== 0; } $.fn.center = function () { this.css("position","absolute"); this.css("top", Math.max(0, (($(window).height() - $(this).outerHeight()) / 2) + $(window).scrollTop()) + "px"); this.css("left", Math.max(0, (($(window).width() - $(this).outerWidth()) / 2) + $(window).scrollLeft()) + "px"); return this; } // one time load of cards from DB $.ajax({ url: "src/getcards.php", type: "post", success: function(output) { initialize(output); } }); function initialize(input) { /*** INITIALIZATION SCOPE FUNCTIONS ***/ // starts automated battles function initiateBattles() { var limit = $("#battleNumbers").val(); if (!isNaN(limit) && limit !== "") { if (simulator.offenseSession.battles < limit) { battleData(simulator.battle(false, false)); simulation = setTimeout(initiateBattles, 1); } else { simulator.offenseSession.clear(); simulator.defenseSession.clear(); $("#stopSample").trigger("click"); } } else { battleData(simulator.battle(false, false)); simulation = setTimeout(initiateBattles, 1); } } /*** INITIALIZATION ***/ var optionList = "", // html options for select lists (to be populated) output = JSON.parse(JSON.stringify(JSON.parse(input))), simulation, // will be a timeout for automated battles cardData; // object placeholder for the next bit... // build our card objects for application use, and populate optionList while we're at it. for (var o = 0; o < output.length; o++) { optionList += "<option id='"+output[o].id+"'>"+output[o].name+"</option>"; } $(".card, .support-deck select").not(".support-skill").each(function() { $(this).html(optionList); }); $("#oc1, #oc2, #oc3, #dc1, #dc2, #dc3").find("input[type='checkbox']").prop("checked", true); $("#oc4, #oc5, #dc4, #dc5").find("input[type='checkbox']").prop("checked", false).prop("disabled", true); $("#off-combo, #def-combo, #off-support, #def-support").prop("checked", true); $("#off-adapter, #def-adapter").find("option[value='1.07']").prop("selected", true); $("#scrapper, #off-position, #def-position").find("option[value='1']").prop("selected", true); // initialize the simulator simulator = model.initialize(output, ["oc1","oc2","oc3","oc4","oc5"], ["dc1","dc2","dc3","dc4","dc5"], ["off-support1", "off-support2", "off-support3"], ["def-support1", "def-support2", "def-support3"]); // load any existing presets into the view and register them if (window.localStorage.getItem("presets")) { var presets = JSON.parse(window.localStorage.getItem("presets")); var preset = "<option>Select Custom Preset...</option>"; for (var o = 0; o < presets.offense.length; o++) { preset += "<option id="+presets.offense[o].id+">"+presets.offense[o].name+"</option>"; } $("#off-presets").html(preset); preset = "<option>Select Custom Preset...</option>"; for (var d = 0; d < presets.defense.length; d++) { preset += "<option id="+presets.defense[d].id+">"+presets.defense[d].name+"</option>"; } $("#def-presets").html(preset); simulator.setPresets(presets.offense, presets.defense); } /* now let's link up the rest of our interface to the simulator */ // *note* event handler optimization incoming! // binding preset selection to deck card objects $("#off-presets, #def-presets").on("change", function(e) { if ($(this).find("option:selected").html() === "Select Custom Preset...") { return false; } var faction = ($(e.target).attr("id") === "off-presets") ? "offense" : "defense", cards = simulator.getPresets(faction, $(this).find("option:selected").attr("id")), cid; // reset card filtration to the "All" settings and refilter if (faction === "offense") { $("#off-alignment, #off-rarity").find("option[value='All']").prop("selected", true); } else { $("#def-alignment, #def-rarity").find("option[value='All']").prop("selected", true); } $("#"+faction+ " .rarity-filter").each(function() { var parent = ($(this).parents("div[id^='dc']").exists()) ? $(this).parents("div[id^='dc']") : $(this).parents("div[id^='oc']"); parent.find(".alignment-filter option[value='All']").prop("selected", true); parent.find(".rarity-filter option[value='All']").prop("selected", true); filterCardView(parent); }); // update views and card objects for (var i = 0; i < cards.length; i++) { simulator.adjustSkill(cards[i].view, cards[i].skill); $("#"+cards[i].view) .find(".card option[id='"+cards[i].data.id+"']").prop("selected", true).end() .find(".skill option[value='"+cards[i].skill+"']").prop("selected", true).end() .find(".card").trigger("change"); } battleLog(simulator.battle(false, true)); }); // binding card selections to and settings associated card objects and properties $(".deck").on("change", function(e) { var view = ($(e.target).parents("div[id^='dc']").exists()) ? $(e.target).parents("div[id^='dc']") : $(e.target).parents("div[id^='oc']"); switch ($(e.target).attr("class")) { case "card": // update view and associated card object var cid = simulator.changeCard(view.attr("id"), $(e.target).find("option:selected").attr("id")); updateCardView(view.attr("id"), cid); comboDetect(e.target); break; case "rarity-filter": case "alignment-filter": // filter and repopulate associated card selections filterCardView(view); // trigger card change view.find(".card").trigger("change"); break; case "skill": // update associated card object simulator.adjustSkill(view.attr("id"), $(e.target).find("option:selected").attr("value")); break; default: // must be unclassed checkbox buffLimiter(simulator.toggleCard(view.attr("id")), view); break; } $("#total-defense").val(simulator.defense.total("def")); $("#total-offense").val(simulator.offense.total("atk")); battleLog(simulator.battle(false, true)); }); $(".support-deck").on("change", function(e) { var view = $(e.target).attr("id"); simulator.changeCard(view, $(e.target).find("option:selected").attr("id")); battleLog(simulator.battle(false, true)); }); $(".deck").on("click", function(e) { var view = ($(e.target).parents("div[id^='dc']").exists()) ? $(e.target).parents("div[id^='dc']") : $(e.target).parents("div[id^='oc']"), prefix, viewNum, thatView; switch ($(e.target).attr("class")) { case "up-arrow": prefix = view.attr("id").substr(0,2); viewNum = parseInt(view.attr("id").charAt(2)); if (viewNum !== 1) { thatView = $("#"+prefix + (viewNum-1)); var id1 = view.find(".card option:selected").attr("id"); var id2 = thatView.find(".card option:selected").attr("id"); var skill1 = view.find(".skill option:selected").attr("value"); var skill2 = thatView.find(".skill option:selected").attr("value"); if (!view.find(".card option[id='"+id2+"']").attr("id")) { view.find(".alignment-filter option[value='All']").prop("selected", true); view.find(".rarity-filter option[value='All']").prop("selected", true); filterCardView(view); } view.find(".card option[id='"+id2+"']").prop("selected", true); view.find(".skill option[value='"+skill2+"']").prop("selected", true); view.find(".card").trigger("change"); if (!thatView.find(".card option[id='"+id1+"']").attr("id")) { thatView.find(".alignment-filter option[value='All']").prop("selected", true); thatView.find(".rarity-filter option[value='All']").prop("selected", true); filterCardView(thatView); } thatView.find(".card option[id='"+id1+"']").prop("selected", true); thatView.find(".skill option[value='"+skill1+"']").prop("selected", true); thatView.find(".card").trigger("change"); } break; case "down-arrow": prefix = view.attr("id").substr(0,2); viewNum = parseInt(view.attr("id").charAt(2)); if (viewNum !== 5) { thatView = $("#"+prefix + (viewNum+1)); var id1 = view.find(".card option:selected").attr("id"); var id2 = thatView.find(".card option:selected").attr("id"); var skill1 = view.find(".skill option:selected").attr("value"); var skill2 = thatView.find(".skill option:selected").attr("value"); if (!view.find(".card option[id='"+id2+"']").attr("id")) { view.find(".alignment-filter option[value='All']").prop("selected", true); view.find(".rarity-filter option[value='All']").prop("selected", true); filterCardView(view); } view.find(".card option[id='"+id2+"']").prop("selected", true); view.find(".skill option[value='"+skill2+"']").prop("selected", true); view.find(".card").trigger("change"); if (!thatView.find(".card option[id='"+id1+"']").attr("id")) { thatView.find(".alignment-filter option[value='All']").prop("selected", true); thatView.find(".rarity-filter option[value='All']").prop("selected", true); filterCardView(thatView); } thatView.find(".card option[id='"+id1+"']").prop("selected", true); thatView.find(".skill option[value='"+skill1+"']").prop("selected", true); thatView.find(".card").trigger("change"); } break; } }); function filterCardView(view) { var alignment = $(view).find(".alignment-filter option:selected").attr("value"), rarity = $(view).find(".rarity-filter option:selected").attr("value"), filtered = simulator.filterCards(alignment, rarity), optionList = ""; for (var a = 0; a < filtered.length; a++) { optionList += "<option id='"+filtered[a].id+"'>"+filtered[a].name+"</option>"; } $(view).find(".card").html(optionList); } function updateCardView(view, cid) { var alignment, parent, stat; if (view[0] === "o") { alignment = simulator.offense.cards[parseInt(view[2])-1].data.alignment; stat = simulator.offense.cards[parseInt(view[2])-1].base_stat; } else { alignment = simulator.defense.cards[parseInt(view[2])-1].data.alignment; stat = simulator.defense.cards[parseInt(view[2])-1].base_stat; } if (HD) { $("#"+view).css("background-image", "url(http://mwoh.thestratusquo.com/assets/images/"+cid+".jpg)"); switch (alignment) { case "Bruiser": alignment = "bruiserRed"; break; case "Speed": alignment = "speedGreen"; break; case "Tactics": alignment = "tacticsBlue"; break; } $("#"+view).find(".card-select").attr("class", "card-select "+alignment); } $("#"+view).find(".card-stats").html(stat); } // bind deck options to associated deck properties $(".deck-options").on("change", function(e) { switch ($(e.target).attr("id")) { case "off-adapter": if (parseFloat($(e.target).find("option:selected").attr("value")) > 1) { simulator.offense.use_adapter = true; simulator.offense.adapter = parseFloat($(e.target).find("option:selected").attr("value")); } else { simulator.offense.use_adapter = false; } break; case "def-adapter": if (parseFloat($(e.target).find("option:selected").attr("value")) > 1) { simulator.defense.use_adapter = true; simulator.defense.adapter = parseFloat($(e.target).find("option:selected").attr("value")); } else { simulator.offense.use_adapter = false; } break; case "off-position": simulator.offense.position = $(e.target).find("option:selected").attr("value"); break; case "def-position": simulator.defense.position = $(e.target).find("option:selected").attr("value"); break; case "scrapper": simulator.offense.scrapper = $(e.target).find("option:selected").attr("value"); break; case "off-combo": case "def-combo": simulator.comboToggle($(e.target).attr("id")); break; case "off-support": case "def-support": simulator.supportToggle($(e.target).attr("id")); break; } battleLog(simulator.battle(false, true)); }); // filter deck selections and trigger card changes $("#off-alignment, #off-rarity").on("change", function() { var rarity = $("#off-rarity").find("option:selected").attr("value"); var alignment = $("#off-alignment").find("option:selected").attr("value"); var newCards = simulator.filterCards(alignment, rarity); var newHTML = ""; for (var a = 0; a < newCards.length; a++) { newHTML += "<option id='"+newCards[a].id+"'>"+newCards[a].name+"</option>"; } $("#oc1, #oc2, #oc3, #oc4, #oc5").each(function() { $(this).find(".card").html(newHTML).trigger("change"); $(this).find(".alignment-filter option[value='"+alignment+"']").prop("selected", true); $(this).find(".rarity-filter option[value='"+rarity+"']").prop("selected", true); }); }); $("#def-alignment, #def-rarity").on("change", function() { var rarity = $("#def-rarity").find("option:selected").attr("value"); var alignment = $("#def-alignment").find("option:selected").attr("value"); var newCards = simulator.filterCards(alignment, rarity); var newHTML = ""; for (var a = 0; a < newCards.length; a++) { newHTML += "<option id='"+newCards[a].id+"'>"+newCards[a].name+"</option>"; } $("#dc1, #dc2, #dc3, #dc4, #dc5").each(function() { $(this).find(".card").html(newHTML).trigger("change"); $(this).find(".alignment-filter option[value='"+alignment+"']").prop("selected", true); $(this).find(".rarity-filter option[value='"+rarity+"']").prop("selected", true); }); }); // Automated Battles Controls $("#takeSample").on("click", function() { $("#takeSample").prop("disabled", true); $("#clearSample").prop("disabled", true); initiateBattles(); }); $("#stopSample").on("click", function() { $("#takeSample").prop("disabled", false); $("#clearSample").prop("disabled", false); clearTimeout(simulation); }); $("#clearSample").on("click", function() { simulator.offenseSession.clear(); simulator.defenseSession.clear(); $("#off-percent, #def-percent").html("0"); $(".win-ratio span").html("0"); $("#automated-results .stat-details span").html("0"); $("#automated-results .ability-details span").html("0"); $("#automated-results .card-details td + td span").html("0"); }); // Save A Preset $("#save-offense, #save-defense").on("click", function(e) { if (window.localStorage) { var name = prompt("Please name this preset:", "Preset Name"), newPreset, faction; if ($(e.target).attr("id") === "save-offense") { faction = "offense"; } else { faction = "defense"; } newPreset = simulator[faction].save(name); if (newPreset) { if (faction === "offense") { $("#off-presets").append(newPreset); } else { $("#def-presets").append(newPreset); } } } }); // Delete A Preset $("#off-presets + button, #def-presets + button").on("click", function(e) { var confirmDelete = false, faction, id, presets, deleted; if ($(e.target).prev("select").attr("id") === "off-presets") { faction = "offense"; presets = $("#off-presets"); } else { faction = "defense"; presets = $("#def-presets"); } if (presets.find("option:selected").html() !== "Select Custom Preset...") { confirmDelete = confirm("Are you sure you want to delete the selected preset?"); } else { $("#popup").html("Please select a preset to delete first.").center().fadeIn("fast", function() { setTimeout(function() { $("#popup").fadeOut("fast"); }, 2000); }); } if (confirmDelete) { id = presets.find("option:selected").attr("id"); if (simulator[faction].remove(id)) { presets.find("option:selected").remove(); $("#popup").html("You have successfully deleted the preset.").center().fadeIn("fast", function() { setTimeout(function() { $("#popup").fadeOut("fast") }, 1000); }); } else { $("#popup").html("There was a problem removing the preset.").center().fadeInt("fast", function() { settimeout(function() { $("#popup").fadeOut("fast") }, 2000); }); } } }); // Update A Preset $("#update-defense, #update-offense").on("click", function(e) { var targetID, faction, presets, name; if ($(e.target).attr("id") === "update-defense") { targetID = parseInt($("#def-presets").find("option:selected").attr("id")); faction = "defense"; name = $("#def-presets").find("option:selected").html(); } else { targetID = parseInt($("#off-presets").find("option:selected").attr("id")); faction = "offense"; name = $("#off-presets").find("option:selected").html(); } if (simulator[faction].update(targetID)) { $("#popup").html("You have successfully updated the preset: " + name).center().fadeIn("fast", function() { setTimeout(function() { $("#popup").fadeOut("fast") }, 1000); }); } else { $("#popup").html("You have not saved this deck as a preset before, you will be prompted to save it now.").center().fadeIn("fast", function() { setTimeout(function() { $("#popup").fadeOut("fast", function() { $("#save-offense").trigger("click"); }) }, 2000); }); } }); // Let's Begin // randomize first card selection, and link chosen cards with the simulator's offense and defense selected cards $(".card").each(function() { $(this).html(optionList); var art, $sel, $opt; $sel = $(this).children("option"); $opt = $sel.eq(Math.floor(Math.random() * $sel.length)); $opt.prop("selected", true); $(this).trigger("change"); }); } // limits selected buffs to 3 buffs and maintains track function buffLimiter(toggle, view) { var buffs; if ($(view).attr("id").charAt(0) === "o") { simulator.fixed_ob = (!toggle) ? simulator.fixed_ob-1 : simulator.fixed_ob+1; buffs = simulator.fixed_ob; } else { simulator.fixed_db = (!toggle) ? simulator.fixed_db-1 : simulator.fixed_db+1; buffs = simulator.fixed_db; } if (buffs === 3) { $(view).parents(".deck").find("input[type='checkbox']:not(:checked)").prop("disabled", true); } else { $(view).parents(".deck").find("input[type='checkbox']:not(:checked)").prop("disabled", false); } } function comboDetect(sender) { var parent; if ($(sender).parents("div[id^='oc']").exists()) { parent = $(sender).parents("div[id^='oc']"); } else if ($(sender).parents("div[id^='dc']").exists()) { parent = $(sender).parents("div[id^='dc']"); } else { parent = $(sender); } if (simulator.hasCombo(parent.attr("id"))) { parent.parent().parent().find(".combo").html("this deck has potential!"); } else { parent.parent().parent().find(".combo").html(""); } } function battleData(results) { var offense = results[0]; var defense = results[1]; $("#off-wins").html(offense.wins); $("#def-losses").html(offense.wins); $("#off-percent").html(offense.ratio()); $("#def-percent").html(defense.ratio()); $("#def-wins").html(defense.wins); $("#off-losses").html(defense.wins); $("#off-average").html(offense.average()); $("#off-mode").html(offense.mode()); $("#off-max").html(offense.peak); $("#off-min").html(offense.valley); $("#def-average").html(defense.average()); $("#def-mode").html(defense.mode()); $("#def-max").html(defense.peak); $("#def-min").html(defense.valley); $("#off-none").html(offense.procCount(0)); $("#off-one").html(offense.procCount(1)); $("#off-two").html(offense.procCount(2)); $("#off-three").html(offense.procCount(3)); $("#def-none").html(defense.procCount(0)); $("#def-one").html(defense.procCount(1)); $("#def-two").html(defense.procCount(2)); $("#def-three").html(defense.procCount(3)); $("#off-one-freq").html(offense.cardCount("oc1")); $("#off-two-freq").html(offense.cardCount("oc2")); $("#off-three-freq").html(offense.cardCount("oc3")); $("#off-four-freq").html(offense.cardCount("oc4")); $("#off-five-freq").html(offense.cardCount("oc5")); $("#def-one-freq").html(defense.cardCount("dc1")); $("#def-two-freq").html(defense.cardCount("dc2")); $("#def-three-freq").html(defense.cardCount("dc3")); $("#def-four-freq").html(defense.cardCount("dc4")); $("#def-five-freq").html(defense.cardCount("dc5")); } function battleLog(results) { var offense = results[0]; var defense = results[1]; var offProcs = results[0].getAbilities(); var defProcs = results[1].getAbilities(); var off_log = ""; var def_log = ""; if (!offense.win) { $("#off-result").html("Defeat").removeClass("victory").addClass("defeat"); $("#def-result").html("Victory").removeClass("defeat").addClass("victory"); } else { $("#off-result").html("Victory").removeClass("defeat").addClass("victory"); $("#def-result").html("Defeat").removeClass("victory").addClass("defeat"); } // Offense Log if (offense.adapter) off_log += "<span>Adapter Reaction: <span>"+offense.adapter+"</span></span>"; if (offense.position) off_log += "<span>Alliance Position Effect: <span>"+offense.position+"</span></span>"; if (offense.scrapper) off_log += "<span>Scrapper: <span>"+offense.scrapper+"</span></span>"; for (var i = 0; i < offProcs.length; i++) { switch (offProcs[i][2]) { case "!Bruiser": offProcs[i][2] = "Speed, Tactics"; break; case "!Speed": offProcs[i][2] = "Bruiser, Tactics"; break; case "!Tactics": offProcs[i][2] = "Bruiser, Speed"; break; default: break; } off_log += "<span>"+offProcs[i][0]+((offProcs[i][1]==="Degrade")?" degraded ":" boosted ")+offProcs[i][2]+": <span>"+offProcs[i][3]+"</span></span>"; } if (offense.combo && offense.combo[0] !== "No") off_log += "<span>"+offense.combo[0]+((offense.combo[1]==="Degrade")?" degraded ":" boosted ")+offense.combo[3]+": <span>"+offense.combo[2]+"</span></span>"; if (offense.supportAbility) { off_log += "<span>"+offense.supportAbility[0]+((offense.supportAbility[1]==="Degrade")?" support degraded ":" support boosted ")+offense.supportAbility[2]+": <span>"+offense.supportAbility[3]+"</span></span>"; } if (offense.supportBoost) { off_log += "<span>Support Deck Boosted All: <span>"+offense.supportBoost+"</span></span>"; } off_log += "<span>Total: <span>"+offense.total+"</span></span>"; // Defense Log if (defense.adapter) def_log += "<span>Adapter Reaction: <span>"+defense.adapter+"</span></span>"; if (defense.position) def_log += "<span>Alliance Position Effect: <span>"+defense.position+"</span></span>"; for (var j = 0; j < defProcs.length; j++) { switch (defProcs[j][2]) { case "!Bruiser": defProcs[j][2] = "Speed, Tactics"; break; case "!Speed": defProcs[j][2] = "Bruiser, Tactics"; break; case "!Tactics": defProcs[j][2] = "Bruiser, Speed"; break; default: break; } def_log += "<span>"+defProcs[j][0]+((defProcs[j][1]==="Degrade")?" degraded ":" boosted ")+defProcs[j][2] + ": <span>"+defProcs[j][3]+"</span></span>"; } if (defense.combo && defense.combo[0] !== "No") def_log += "<span>"+defense.combo[0]+((defense.combo[1]==="Degrade")?" degraded ":" boosted ")+defense.combo[3]+": <span>"+defense.combo[2]+"</span></span>"; if (defense.supportAbility) { def_log += "<span>"+defense.supportAbility[0]+((defense.supportAbility[1]==="Degrade")?" support degraded ":" support boosted ")+defense.supportAbility[2]+": <span>"+defense.supportAbility[3]+"</span></span>"; } if (defense.supportBoost) { def_log += "<span>Support Deck Boosted All: <span>"+defense.supportBoost+"</span></span>"; } def_log += "<span>Total: <span>"+defense.total+"</span></span>"; $("#off-log").html(off_log); $("#def-log").html(def_log); } });
test_score_1 = 0; test_score_2 = 0; test_score_3 = 0; /*if(!document.getElementById("below_three").checked | !(document.getElementById("from_three_to_four").checked) | !(document.getElementById("five_and_over").checked)) { window.alert("Please select your age before clicking on eyechart for the test or else, you'll face a black screen. To get out of the black screen, click anywhere and then select your age please."); document.getElementById("chart1").innerHTML = "<div class='modal fade' id='chart1' disabled='disabled'>"; } */ window.onload = document.getElementById("five_and_over").checked = true; function r2() { document.getElementById("chart1_6").style.display = ""; document.getElementById("chart1_7").style.display = "none"; document.getElementById("chart1_8").style.display = "none"; document.getElementById("chart3_9").style.display = "none"; document.getElementById("chart3_7").style.display = ""; document.getElementById("chart2_7").style.display = "none"; document.getElementById("chart2_6").style.display = "none"; /*document.getElementById("chart1_9").style.display = "none"; document.getElementById("chart1_10").style.display = "none"; document.getElementById("chart1_11").style.display = "none"; */ } function r3() { document.getElementById("chart1_6").style.display = ""; document.getElementById("chart1_7").style.display = ""; document.getElementById("chart1_8").style.display = ""; document.getElementById("chart2_6").style.display = ""; document.getElementById("chart2_7").style.display = ""; document.getElementById("chart3_6").style.display = ""; document.getElementById("chart3_7").style.display = ""; document.getElementById("chart3_8").style.display = ""; document.getElementById("chart3_9").style.display = ""; /* document.getElementById("chart1_9").style.display = "none"; document.getElementById("chart1_10").style.display = "none"; document.getElementById("chart1_11").style.display = "none"; */ } function submit3() { test_score_200 = 0; test_score_300 = 0; val21 = document.getElementById("chart3_1").value; val22 = document.getElementById("chart3_2").value; val23 = document.getElementById("chart3_3").value; val24 = document.getElementById("chart3_4").value; val25 = document.getElementById("chart3_5").value; val26 = document.getElementById("chart3_6").value; val27 = document.getElementById("chart3_7").value; val28 = document.getElementById("chart3_8").value; val29 = document.getElementById("chart3_9").value; if (document.getElementById("from_three_to_four").checked) { if (val21 == "H") { test_score_200 += 1; } if (val22 == "EZ") { test_score_200 += 1; } if (val23 == "LPOT") { test_score_200 += 1; } if (val24 == "DAFV") { test_score_200 += 1; } if (val25 == "NEUC") { test_score_200 += 1; } if (val26 == "VACB") { test_score_200 += 1; } if (val27 == "HLOPS") { test_score_200 += 1; } if (val28 == "ZFDAX") { test_score_200 += 1; } if (test_score_200 == 8) { window.alert("Your score was " + test_score_200 + " out of 8. Therefore, your eye health is very good. Although, remember it's always good to have a break from screen from time-to-time. Thank you for choosing Sharvil eye tests."); } if (test_score_200 >= 0 & test_score_200 <= 3) { window.alert("Your score was " + test_score_200 + " out of 8. I suggest that you consult with an ophthalmologist as soon as possible. Thank you for choosing Sharvil eye tests."); } if (test_score_200 >= 4 & test_score_200 <= 7) { window.alert("Your score was " + test_score_200 + " out of 8. Your eyesight is good however, you should take a break for some time or rest you eyes for now. Thank you for choosing Sharvil eye tests."); } window.location.reload(); } if (document.getElementById("five_and_over").checked) { if (val21 == "H") { test_score_300 += 1; } if (val22 == "EZ") { test_score_300 += 1; } if (val23 == "LPOT") { test_score_300 += 1; } if (val24 == "DAFV") { test_score_300 += 1; } if (val25 == "NEUC") { test_score_300 += 1; } if (val26 == "VACB") { test_score_300 += 1; } if (val27 == "HLOPS") { test_score_300 += 1; } if (val28 == "ZFDAX") { test_score_300 += 1; } if (val29 == "LVECNO") { test_score_300 += 1; } if (test_score_300 == 9) { window.alert("Your score was " + test_score_300 + " out of 9. Therefore, your eye health is very good. Although, remember it's always good to have a break from screen from time-to-time. Thank you for choosing Sharvil eye tests."); } if (test_score_300 >= 0 & test_score_300 <= 4) { window.alert("Your score was " + test_score_300 + " out of 9. I suggest that you consult with an ophthalmologist as soon as possible. Thank you for choosing Sharvil eye tests."); } if (test_score_300 >= 5 & test_score_300 <= 8) { window.alert("Your score was " + test_score_300 + " out of 9. You should really take a break for some time or rest you eyes for now. Thank you for choosing Sharvil eye tests."); } window.location.reload(); } } function submit2() { test_score_20 = 0; test_score_30 = 0; val11 = document.getElementById("chart2_1").value; val12 = document.getElementById("chart2_2").value; val13 = document.getElementById("chart2_3").value; val14 = document.getElementById("chart2_4").value; val15 = document.getElementById("chart2_5").value; val16 = document.getElementById("chart2_6").value; val17 = document.getElementById("chart2_7").value; if (document.getElementById("from_three_to_four").checked) { if (val11 == "TZ") { test_score_20 += 1; } if (val12 == "PTOC") { test_score_20 += 1; } if (val13 == "ZLPED") { test_score_20 += 1; } if (val14 == "ETODCF") { test_score_20 += 1; } if (val15 == "DPCZLFT") { test_score_20 += 1; } if (test_score_20 == 5) { window.alert("Your score was " + test_score_20 + " out of 5. Therefore, your eye health is very good. Although, remember it's always good to have a break from screen from time-to-time. Thank you for choosing Sharvil eye tests."); } if (test_score_20 >= 0 & test_score_20 <= 2) { window.alert("Your score was " + test_score_20 + " out of 5. I suggest that you consult with an ophthalmologist as soon as possible. Thank you for choosing Sharvil eye tests."); } if (test_score_20 >= 3 & test_score_20 <= 4) { window.alert("Your score was " + test_score_20 + " out of 5. Your eyesight is good however, you should take a break for some time or rest you eyes for now. Thank you for choosing Sharvil eye tests."); } window.location.reload(); } if (document.getElementById("five_and_over").checked) { if (val11 == "TZ") { test_score_30 += 1; } if (val12 == "PTOC") { test_score_30 += 1; } if (val13 == "ZLPED") { test_score_30 += 1; } if (val14 == "ETODCF") { test_score_30 += 1; } if (val15 == "DPCZLFT") { test_score_30 += 1; } if (val16 == "CFDTEOPL") { test_score_30 += 1; } if (val17 == "LDCZOTEP") { test_score_30 += 1; } if (test_score_30 == 7) { window.alert("Your score was " + test_score_30 + " out of 7. Therefore, your eye health is very good. Although, remember it's always good to have a break from screen from time-to-time. Thank you for choosing Sharvil eye tests."); } if (test_score_30 >= 0 & test_score_30 <= 3) { window.alert("Your score was " + test_score_30 + " out of 7. I suggest that you consult with an ophthalmologist as soon as possible.Thank you for choosing Sharvil eye tests."); } if (test_score_30 >= 4 & test_score_30 <= 6) { window.alert("Your score was " + test_score_30 + " out of 7. You should really take a break for some time or rest you eyes for now. Thank you for choosing Sharvil eye tests."); } window.location.reload(); } } function submit1() { test_score_2 = 0; test_score_3 = 0; val1 = document.getElementById("chart1_1").value; val2 = document.getElementById("chart1_2").value; val3 = document.getElementById("chart1_3").value; val4 = document.getElementById("chart1_4").value; val5 = document.getElementById("chart1_5").value; val6 = document.getElementById("chart1_6").value; val7 = document.getElementById("chart1_7").value; val8 = document.getElementById("chart1_8").value; /* val9 = document.getElementById("chart1_9").value; val10 = document.getElementById("chart1_10").value; val11 = document.getElementById("chart1_11").value; */ if (document.getElementById("from_three_to_four").checked) { if(val1 == "E"){ test_score_2 += 1; } if(val2 == "FP"){ test_score_2 += 1; } if(val3 == "TOZ"){ test_score_2 += 1; } if(val4 == "LPED"){ test_score_2 += 1; } if(val5 == "PECFD"){ test_score_2 += 1; } if(val6 == "EDFCZP"){ test_score_2 += 1; } if (test_score_2 == 6) { window.alert("Your score was " + test_score_2 + " out of 6. Therefore, your eye health is very good. Although, remember it's always good to have a break from screen from time-to-time. Thank you for choosing Sharvil eye tests."); } if (test_score_2 >= 0 & test_score_2 <= 2) { window.alert("Your score was " + test_score_2 + " out of 6. I suggest that you consult with an ophthalmologist as soon as possible. Thank you for choosing Sharvil eye tests."); } if (test_score_2 >= 3 & test_score_2 <= 5) { window.alert("Your score was " + test_score_2 + " out of 6. Your eyesight is good however, you should take a break for some time or rest you eyes for now. Thank you for choosing Sharvil eye tests."); } } if (document.getElementById("five_and_over").checked) { if(val1 == "E"){ test_score_3 += 1; } if(val2 == "FP"){ test_score_3 += 1; } if(val3 == "TOZ"){ test_score_3 += 1; } if(val4 == "LPED"){ test_score_3 += 1; } if(val5 == "PECFD"){ test_score_3 += 1; } if(val6 == "EDFCZP"){ test_score_3 += 1; } if(val7 == "FELOPZD"){ test_score_3 += 1; } if (val8 == "DEFPOTEC") { test_score_3 += 1; } if (test_score_3 == 8) { window.alert("Your score was " + test_score_3 + " out of 8. Therefore, your eye health is very good. Although, remember it's always good to have a break from screen from time-to-time. Thank you for choosing Sharvil eye tests."); } if (test_score_3 >= 0 & test_score_3 <= 3) { window.alert("Your score was " + test_score_3 + " out of 8. I suggest that you consult with an ophthalmologist as soon as possible. Thank you for choosing Sharvil eye tests."); } if (test_score_3 >= 4 & test_score_3 <= 7) { window.alert("Your score was " + test_score_3 + " out of 8. You should really take a break for some time or rest you eyes for now. Thank you for choosing Sharvil eye tests."); } } for (i=1;i<9;i++) { ValId="chart1_"+i; document.getElementById(ValId).value=""; } } function test() { test_score_vision_acuity = 0; if (document.getElementById("one").checked) { test_score_vision_acuity += 1; } if (document.getElementById("one_two").checked) { test_score_vision_acuity += 1; } if (document.getElementById("one_three").checked) { test_score_vision_acuity += 1; } if (document.getElementById("one_four").checked) { test_score_vision_acuity += 1; } if (test_score_vision_acuity < 2) { window.alert("Your score was " + test_score_vision_acuity + " out of 4. You should definitely have a break and then try this test again or else consult with an opthalmologist to check your eyesight. Thank you for choosing Sharvil eye tests."); } else { window.alert("Your score was " + test_score_vision_acuity + " out of 4. Good job, this proves that your eyesight is great and healthy, however don't forget to take breaks from a screen from time-to-time. Thank you for choosing Sharvil eye tests."); } window.location.reload(); } function store() { name = document.getElementById("name").value; console.log("Name = " + name); comment = document.getElementById("comment").value; console.log("Comment = " + comment); }
import { useEffect, useState } from 'react' import { checkGitIsInstalled } from '../utilities/gitLogic.js' export const useGitIsInstalled = () => { const [gitIsInstalled, setGitIsInstalled] = useState(false) useEffect(() => { checkGitIsInstalled().then(verdict => setGitIsInstalled(verdict)) }, []) return gitIsInstalled }
import React from "react" import styled from "styled-components" import { Container, HeadingWrapper, Heading } from "../../Common/Utility" const ContentWrapper = styled.div` position: relative; padding: 4rem 0; background: #d9be8f; ::before { content: ""; position: absolute; left: 50%; top: 0; transform: translateX(-50%); border-left: 180px solid transparent; border-right: 180px solid transparent; border-top: 80px solid white; z-index: 1; } ` const Left = styled.li` display: flex; justify-content: space-between; align-items: flex-end; p { color: white; max-width: 300px; font: italic 500 1.6rem/1.6 "Playfair Display", sans-serif; } div { margin-left: 1rem; } h3 { margin-top: 3rem; font: italic 700 3rem "Playfair Display", sans-serif; } h4 { color: #7f7d7e; margin: 1rem 0; text-transfrom: uppercase; } ` const Right = styled(Left)` flex-direction: row-reverse; text-align: end; ` export default function OurBrandSection() { return ( <> <HeadingWrapper> <Heading>Customer Says</Heading> </HeadingWrapper> <ContentWrapper> <Container as="ul"> <Left> <img src="assets/images/Testimonial1.png" alt="Sandra Dewi" /> <div> <p> Sel ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque </p> <h3>Sandra Dewi</h3> <h4>Fashion stylish</h4> </div> </Left> <Right> <img src="assets/images/Testimonial2.png" alt="Shaheer Sheikh" /> <div> <p> Sel ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque </p> <h3>Shaheer Sheikh</h3> <h4>Designer</h4> </div> </Right> </Container> </ContentWrapper> </> ) }
var gulp = require('gulp'); var watch = require('gulp-watch'); var less = require('gulp-less'); var path = require('path'); var svgSprite = require('gulp-svg-sprite'); var postcss = require('gulp-postcss'); var autoprefixer = require('autoprefixer'); var cssnano = require('cssnano'); gulp.task('default', function() { return gulp.src('./less/main.less') .pipe(watch('/less/**/*.less')) .pipe(less({ paths: [ path.join(__dirname, 'less', 'includes') ] })) .pipe(gulp.dest('./css')); }); gulp.task ('svg', function () { gulp.src('./img/icons/**/*.svg') .pipe(svgSprite({ svg: { namespaceClassnames: false }, mode: { symbol: { sprite: 'svg/sprite.svg' } } })).pipe(gulp.dest('./img/sprites')); }); // gulp.task('less', function () { // return gulp.src('./less/main.less') // .pipe(less({ // paths: [ path.join(__dirname, 'less', 'includes') ] // })) // .pipe(gulp.dest('./css')); // }); gulp.task('css', function () { var processors = [ autoprefixer({browsers: ['last 2 version']}), cssnano(), ]; return gulp.src('./less/main.less') .pipe(less({ paths: [ path.join(__dirname, 'less', 'includes') ] })) .pipe(postcss(processors)) .pipe(gulp.dest('./css')); });
export { default as Table } from "./reactResponsiveTable";
import React from "react"; export default class Project extends React.Component { render() { const image = this.props.imageURL; return ( <div className="project dark window"> <h3>{this.props.title}</h3> <img src={image} alt={this.props.alt} width="80%" /> <a href={this.props.liveLink} target="_blank" rel="noreferrer"> Live Link </a> <p>Tech Stack: {this.props.stack}</p> <p>Who this app is for: {this.props.whoFor}</p> <p>Description:</p> <p>{this.props.description}</p> <p>Purpose:</p> <p>{this.props.purpose}</p> <div> <a href={this.props.gitLink} target="_blank" rel="noreferrer"> GitHub </a> {" / "} <a href={this.props.apiLink} target="_blank" rel="noreferrer"> API </a> </div> <p>Technology used: {this.props.technology}</p> </div> ); } }
import React from 'react' import { Landing } from '../components/Landing' import { Navbar } from '../components/Navbar' export const index = () => { return ( <div> <Navbar/> <Landing/> </div> ) }
/* * bk-switch * https://github.com/lemonroot/bk-switch * * Copyright (c) 2013 lemonlwz * Licensed under the MIT license. */ (function($) { var method = { init: function(){ this.elem = $(this.options.elem); this.content = this.elem.find('.switch-content'); this.ul = this.content.find('ul') this.items = this.ul.find('li'); this.leftBtn = this.elem.find('.J_left'); this.rightBtn = this.elem.find('.J_right'); this.template = this.options.template; this.items.each(function(k, v){ $(v).attr({'data-index': k}); }); this.setWidth(); this.bind(); }, setWidth: function(){ var width = this.items.length * this.options.itemWidth; this.ul.width(width); }, bind: function(){ var _this = this; this.elem.on('click', '.J_left, .J_right', switchHandler); this.switchHandler = switchHandler; function switchHandler(evt){ if($(evt.currentTarget).hasClass('J_left')){ _this.switchLeftHandler(evt); } else { _this.switchRightHandler(evt); } }; //hover item this.elem.on('mouseover mouseleave', 'li, .bk-switch-detail', hoverHandler); this.hoverHandler = hoverHandler; function hoverHandler(evt){ var $target = $(evt.currentTarget); if($target.hasClass('bk-switch-detail')){ clearTimeout(_this.timer); if(evt.type === 'mouseleave'){ _this.timer = setTimeout(function(){ $target.hide(); }, 200); } return false; } var $item = $(evt.currentTarget); var $parent = _this.elem; var html, user, detail, index, left; index = $item.attr('data-index'); html = $parent.find('.J_bkSwitchDetail' + index); if(evt.type !== 'mouseleave'){ $('.J_bkSwitchDetail').hide(); if($item.attr('data-rendering') == 'rendering'){ return false; } if(html.length){ clearTimeout(_this.timer); html.show(); } else { //html = $('<div class="' + _this.options.itemCls + ' J_bkSwitchDetail J_bkSwitchDetail' + index + '">'); $item.attr('data-rendering', 'rendering'); if(_this.template.length){ var params = {}; $.each(_this.options.params, function(key, attr){ params[key] = $item.attr(attr); }); $.ajax({ url: _this.options.url, dataType: _this.options.dataType || 'jsonp', data: params, success: function(data){ html = $(_this.template).tmpl(data); render(); $item.attr('data-rendering', ''); } }); } else{ user = $item.attr('data-user'); detail = $item.attr('data-detail'); html = $([ '<div class="bk-switch-detail J_bkSwitchDetail' + index + '">', ' <i class="arrow"></i>', ' <label>' + user + ':</label>', ' <span>' + detail + '</span>', '</div>' ].join('')); render(); $item.attr('data-rendering', ''); } function render(){ var w = html.width(); var wl = $item.offset().left; var pw = $parent.width(); var pwl = $parent.offset().left; var xl = 0; if(wl + w > pwl + pw){ left = pw - w; xl = wl - pwl - left; } else { left = wl - pwl; } html.css({ left: left, zIndex: 10 }); html.find('.arrow').css({ left: xl + 30 }); html.addClass('J_bkSwitchDetail J_bkSwitchDetail' + index); html.css('position', 'absolute'); html.on('mouseover mouseleave', function(e){ if(e.type === 'mouseover'){ clearTimeout(_this.timer); $('.J_bkSwitchDetail').hide(); html.show(); } else { clearTimeout(_this.timer); _this.timer = setTimeout(function(){ $('.J_bkSwitchDetail').hide(); }, 200); } }); $parent.append(html); } } var w = html.width(); var wl = $item.offset().left; var pw = $parent.width(); var pwl = $parent.offset().left; var xl = 0; if(wl + w > pwl + pw){ left = pw - w; xl = wl - pwl - left; } else { left = wl - pwl; } html.css({ left: left }); html.find('.arrow').css({ left: xl + 30 }); } else { if(html.length){ clearTimeout(_this.timer); _this.timer = setTimeout(function(){ $('.J_bkSwitchDetail').hide(); }, 200); } } }; }, switchLeftHandler: function(evt){ var ul = this.ul; var width = this.options.width; var left = ul.get(0).offsetLeft - width; var maxLeft = ul.width() - width; if(left < -maxLeft){ left = -maxLeft; } ul.animate({ left: left }, 600); }, switchRightHandler: function(evt){ var ul = this.ul; var width = this.options.width; var left = ul.get(0).offsetLeft + width; var maxLeft = 0; if(left > 0){ left = maxLeft; } ul.animate({ left: left }, 600); }, unbind: function(){ this.elem.unbind('click', this.switchHandler); this.items.unbind('mouseenter mouseleave', this.options.hoverHandler); } }; // Collection method. //$.fn.bkSwitch = function() { // return this.each(function(i) { // // Do something bkSwitch to each selected element. // $(this).html('bkSwitch' + i); // }); //}; // Static method. $.bkSwitch = function(options) { // Override default options with passed-in options. options = $.extend({}, $.bkSwitch.options, options); // Return something bkSwitch. method.options = options; method.init(); return { unbind: function(){ method.unbind(); } }; }; // Static method default options. $.bkSwitch.options = { itemCls: 'bk-switch-detail', template: [] }; }(jQuery));
import {StyleSheet} from 'react-native'; export default StyleSheet.create({ textStyle: { fontFamily: 'SFUIText-Regular', alignSelf: 'center', color: '#fff', fontSize: 15, paddingTop: 10, paddingBottom: 10, }, buttonStyle: { flex: 1, alignSelf: 'stretch', backgroundColor: '#423486', borderWidth: 1, borderRadius: 22, borderColor: '#423486', justifyContent: 'center', alignItems: 'center', }, buttonWrapper: { width: '100%', height: 50, justifyContent: 'center', }, });
export const SAVE_DATA='SAVE_DATA'; export const saveData=(data)=> { return async (dispatch)=> { try { dispatch({ type:SAVE_DATA, data:data }) } catch(Err) { console.log('error at save data',Err) throw Err; } } }
var app = angular.module('app', ['ui.router', 'restangular', 'ui.bootstrap', 'ngAnimate', 'ngSanitize', 'ui.validate', 'ngTouch', 'SignInCtrl', 'MainCtrl', 'ListCtrl', 'DetailCtrl'], ['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterProvider) { $urlRouterProvider.otherwise('/'); $stateProvider .state('sign-in',{ url:'/', templateUrl:'app_modules/modules/sign-in/sign-in.html', controller:'SignInCtrl' }) .state('main',{ url:'/main', templateUrl:'app_modules/modules/main/main.html', controller:'MainCtrl' }) .state('main.list',{ url:'/list', templateUrl:'app_modules/modules/list/list.html', controller:'ListCtrl' }) .state('main.new-entry',{ url:'/new-entry', templateUrl:'app_modules/modules/detail/detail.html', controller:'DetailCtrl' }) .state('main.detail',{ url:'/detail', params: {rowData: null}, templateUrl:'app_modules/modules/detail/detail.html', controller:'DetailCtrl' }); }]);
import io from 'socket.io-client' import feathersClient from 'feathers/client' import socketio from 'feathers-socketio/client' import hooks from 'feathers-hooks' import authentication from 'feathers-authentication/client' import wings from 'wings-feathers' let socket = io('//localhost:3030') let feathers = feathersClient() .configure(socketio(socket)) .configure(hooks()) .configure(authentication({storage: window.localStorage})) let wingsJS = wings(feathers) wingsJS.serve('collection') // a collection service wingsJS.serve('chat') export default wingsJS
//words split var text="hello hai hello hai" var words=text.split(" ") var dict={} for(var word of words){ if(word in dict){ dict[word+=1] } else{ dict[word]=1 } } console.log(dict)
// Create a module that exports a function that takes a number as a parameter and stores it in a list. // The list should not be accessible from outside the module. // Export another function that returns a version of the data list that is sorted in ascending order. // The function you use to sort the data correctly should not be accessible from outside the module. // (Think back to the Custom Sorting Exercise when handling sorting) // Implement a Node.js script that imports the functionality of your module, // adds at least 5 different data points to the module's data list, and outputs the sorted list. module.exports = { list: function(para) { addList.push(para); }, data: function () { return sorting(); } } var addList = []; var sorting = function() { addList.sort(function(a, b) { return a - b; }); return addList.slice(); } // module.exports = { // list: function(num) { // list.push(num); // }, // sort: function() { // return ascending() // }, // } // var list = []; // var ascending = function() { // list.sort(function(a, b) { // return a-b; // }) // return list // } // console.log(module.exports.list([5,3,452,2])); // // console.log(module.exports.list(4)); // console.log(module.exports.data());
import React, { Component } from 'react' import { ScrollView, Text, View } from 'react-native' import PropTypes from 'prop-types' import { Query } from 'react-apollo' import Touchable from '@vivintsolar-oss/native-vs-touchable' import SearchLayout from '../../common/SearchBar' import get from 'lodash.get' import searchRepository from './repository.query' import searchUser from './user.query' import styles from './styles' import { Color } from '../../../constants' import UserList from '../../common/UserList' import RepoList from '../../common/RepoList' import Loading from '../../common/Loading' function propsToVariables(props, state) { console.log('props', props, 'state', state) const last = 100 const type = state.active.toUpperCase() const query = state.searchText return { type, last, query, } } export default class Search extends Component { static navigationOptions({ navigation }) { return { headerStyle: { display: 'none', }, } } constructor(props) { super(props) this.handleQueryChange = this.handleQueryChange.bind(this) this.state = { active: 'Repository', } } static getDerivedStateFromProps(props, state) { const searchTerm = get(props, 'navigation.state.params.topic', null) if (searchTerm) { return { searchTerm } } return null } toggleActive(active) { this.setState({ active }) } handleQueryChange(searchText) { this.setState({ searchText }) } componentWillUnmount() { this.setState({ searchTerm: null }) } render() { const { active, searchTerm } = this.state const query = active === 'Repository' ? searchRepository : searchUser const ListComponent = active === 'Repository' ? RepoList : UserList const activeTab = (type, active) => { const tabStyles = type === active ? styles.selected : styles.unSelected const textStyle = type === active ? styles.activeText : null return ( <Touchable onPress={() => { this.toggleActive(type) }} > <View style={[styles.tab, tabStyles]}> <Text style={[styles.tabText, textStyle]}>{type}</Text> </View> </Touchable> ) } return ( <SearchLayout headerBackgroundColor={Color.PRIMARY} headerTintColor={Color.WHITE} searchInputTintColor={Color.WHITE} searchInputUnderlineColorAndroid={Color.ACCENT_PRIMARY} searchInputSelectionColor={Color.ACCENT_PRIMARY} searchInputBackgroundColor={Color.PRIMARY_800} searchInputPlaceholderTextColor={Color.WHITE} searchInputIconColor={Color.WHITE} searchInputTextColor={Color.WHITE} placeholderTextColor={Color.WHITE} onChangeQuery={this.handleQueryChange} renderResults={q => ( <ScrollView> <View style={styles.tabContainer}> {activeTab('Repository', active)} {activeTab('User', active)} </View> {q || searchTerm ? ( // skip isn't quite working as the loading props still gets passed down <Query displayName="Search" query={query} variables={propsToVariables(this.props, { ...this.state, query: searchTerm, })} > {({ loading, error, data }) => { const search = get(data, 'search.nodes') if (loading) return ( <View style={styles.noDataWrapper}> <Loading /> </View> ) if (error) return <Text>Error :(</Text> return ( <ScrollView> <ListComponent data={search} navigation={this.props.navigation} /> </ScrollView> ) }} </Query> ) : ( <View style={styles.noDataWrapper}> <Text style={styles.noData}>No Data</Text> </View> )} </ScrollView> )} /> ) } }
const expect = require('chai').expect const server = require('../index'); describe('test', () => { it('should return a string', () => { expect('test ci with travis').to.equal('test ci with travis'); }); });
const Engine = Matter.Engine; const World = Matter.World; const Bodies = Matter.Bodies; const Body = Matter.Body; var hammer var ground var stone var iron function preload() { } function setup() { var canvas = createCanvas(1200, 400); engine = Engine.create(); world = engine.world; //Create the Bodies Here. hammer = new Hammer(801,120,100,50); ground = new Ground(600,400,1200,20); stone = new Stone(200,300); iron = new Iron(40,50) Engine. run(engine); } function draw() { rectMode(CENTER); background(0); hammer.display(); ground.display(); stone.display(); iron.display(); drawSprites(); }
define([ 'backbone' ], function(Backbone) { // To save us repeating ourselves. var BaseView = Backbone.View.extend({ initialize: function() { this.listenTo(this.model, 'change', this.render); }, render: function() { this.$el.html(this.template(this.model.toJSON())); return this; } }); var Views = {}; Views.Headerbar = BaseView.extend({ template: _.template('<h1 class="headerbar-title"><%- title %></h1>'), initialize: function() { this.listenTo(this.model, 'change', this.render); } }); Views.ListItem = BaseView.extend({ tagName: 'li', template: _.template('<a href="#!/animals/<%- id %>"><%- name %></a>') }); Views.List = BaseView.extend({ tagName: 'ul', className: 'list', attributes: { 'data-tap': 'list' }, initialize: function() { this.listenTo(this.collection, 'reset', this.render); }, render: function() { this.$el.empty(); this.collection.each(this.renderOne, this); return this; }, renderOne: function(item) { var itemView = new Views.ListItem({ model: item }); itemView.render(); this.$el.append(itemView.el); } }); Views.Detail = BaseView.extend({ className: 'detail', template: _.template('<div class="img-wrapper"><img src="<%- img %>"></div><p><%- description %></p>') }); return Views; });
$(document).ready(function() { /******************************************** * Navbar Class Swap * adapted from * @author rlewis37@cnm.edu * ********************************************/ /* on home page ONLY, swap out navabar classes if user scrolls down 50 px */ $(window).scroll(function() { if($(this).scrollTop() > 50) { $('.navbar').addClass('navbar-main').removeClass('navbar-transparent'); } /* when user scrolls back up, reset navbar*/ if($(window).scrollTop() <= 50) { $('.navbar').addClass('navbar-transparent').removeClass('navbar-main'); } }); function standby() { document.getElementById('wheel').src = 'images/sararuthfinkel-ceramics.jpg' } });
Presence.state = function() { if(Meteor.user()) { return { currentChartId: Session.get("chartId"), user: Meteor.user().profile.name, } } } Template.chartEditStatus.helpers({ manyConnections: function() { var count = Presences.find().fetch().length; if (count > 1) { return true; } }, connected: function() { return Presences.find({"state.currentChartId":Session.get("chartId") }); }, name: function() { return this.state.user; }, currentSession: function() { if (this.state.user === Meteor.user().profile.name) { return true; } } }); Template.chartEditStatus.events({ "click .help-editing": function(event) { sweetAlert({ title: "Who\u2019s editing my what now?", text: "Surprise! Chart Tool allows for multiple people to edit your chart at once.", type: "info", confirmButtonColor: "#fff" }); } })
let a = 5; let b = 10; console.log("a", a); // 5 console.log("b", b); // 10 /* Write your code here so that the values of "a" and "b" are swapped and console.log them again. */ let mainColor = "tomato"; let secondaryColor = "limegreen"; console.log("mainColor", mainColor); console.log("secondaryColor", secondaryColor); /* Write your code here to invert the colors, so that mainColor will be limegreen and secondaryColor tomato. */
const assert = require('assert'); const {encode,decode} = require('../main.js'); const json = { string: 'hello world', number: 100, arr: [1,6,"hello"], date: new Date(), buf: new Buffer('hello world') }; const jsonStr = encode(json); const obj = decode(jsonStr); assert.deepEqual(json,obj);
const bent = require('bent'); const fs = require('fs').promises; const path = require('path'); const docPath = "https://api.hubspot.com/cos-rendering/v1/hubldoc"; const getJSON = bent('json'); const nunjucksFilters = [ 'abs', 'batch', 'capatalize' ]; (async () => { let existingFilters = await getSupportedFiltersInNunjucks(); let existingTags = await getSupportedTagsInNunjucks(); let obj = await getJSON(docPath); const { filters, functions, tags } = obj; await buildFilters(filters, existingFilters); await buildFunctions(functions); await buildTags(tags, existingTags); })().catch( res => { console.log('Error occured', res); }) async function buildFilters(filters, existingFilters) { for (const filterTagName in filters) { const { name, desc ,aliasOf, deprecated, params } = filters[filterTagName]; if (deprecated) { continue; } if (existingFilters.includes(name)) { continue; } params.unshift({ name: 'input' }); //"name":"other","type":"object","desc":"Another object to compare against","defaultValue":"","required":true} const code = `function register(env) { env.addFilter("${ filterTagName }", handler); } ${ createBody(filterTagName, params) } module.exports = { handler, register }; `; await fs.writeFile(path.join(__dirname, 'src/filters', filterTagName + '.js'), code, "binary"); } } async function buildFunctions(functions) { for (const fnName in functions) { const { name, desc , aliasOf, deprecated, params } = functions[fnName]; if (deprecated) { continue; } let parsedParams = params.map( param => param.name.replace(/ /g, "_")); parsedParams = replaceReservedVariables(parsedParams); parsedParams = parsedParams.join(', '); const code = `function register(env) { env.addGlobal("${ fnName }", handler); } ${ createBody(fnName, params) } module.exports = { handler, register }; `; await fs.writeFile(path.join(__dirname, 'src/functions', fnName + '.js'), code, "binary"); } } async function buildTags(tags, existingTags) { for (const tagName in tags) { const { name, desc , aliasOf, deprecated, params } = tags[tagName]; if (deprecated) { continue; } if (existingTags.includes(name)) { continue; } let parsedParams = params.map( param => param.name.replace(/ /g, "_")); parsedParams = parsedParams.map( param => param.replace(/^default$/, "default_attr")); parsedParams = parsedParams.join(', '); const code = `function register(env) { env.addExtension("${ tagName }", new handler(env)); } ${createTagBody(tagName)} ` await fs.writeFile(path.join(__dirname, 'src/tags', tagName + '.js'), code, "binary"); } } async function getSupportedFiltersInNunjucks() { const url = 'https://raw.githubusercontent.com/mozilla/nunjucks/f91f1c3fd14fde683e71a61563e46b547c9160e4/nunjucks/src/filters.js'; const getBuffer = await bent('string'); const data = await getBuffer(url); const supportedMatches = data.matchAll(/function\s+([^\(]+)/g); const supported = []; for (const match of supportedMatches) { supported.push(match[1]); } supported.push('abs'); return supported; } async function getSupportedTagsInNunjucks() { const url = 'https://raw.githubusercontent.com/mozilla/nunjucks/f91f1c3fd14fde683e71a61563e46b547c9160e4/nunjucks/src/parser.js'; const getBuffer = await bent('string'); const data = await getBuffer(url); const supportedMatches = data.matchAll(/case '([^']+)'/g); const supported = []; for (const match of supportedMatches) { supported.push(match[1]); } return supported; } function replaceReservedVariables(arr) { const reserved = ['function', 'var', 'let', 'const', 'default', 'new']; return arr.map(item => { if (reserved.includes(item)) { return item + '_attr'; } return item; }) } function createBody(fnName, params) { params = params.map( param => param.name.replace(/ /g, "_")); params = replaceReservedVariables(params); params = params.join(', '); return `function handler(${params}) { } `; } function createTagBody(tagName) { const lowerCaseName = tagName.toLowerCase(); return `const Nunjucks = require('nunjucks'); function handler(env) { this.tags = ['${ lowerCaseName }']; this.parse = function (parser, nodes, lexer) { var tok = parser.nextToken(); var args = parser.parseSignature(null, true); parser.advanceAfterBlockEnd(tok.value); //var body = parser.parseUntilBlocks('end_${ lowerCaseName }'); let body = null; //parser.advanceAfterBlockEnd(); return new nodes.CallExtension(this, 'run', args, [body]); }; this.run = function(environment) { console.log(environment); let str = JSON.stringify(environment.ctx); return new Nunjucks.runtime.SafeString(str); } } module.exports = { handler, register } `; }
/* * Copyright 2018 ConsenSys AG. * * 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. */ /** * Finder_v1.sol tests with either no ERAs or no domains. * * The tests in this file check the behaviour of the Finder contract when not enough * information is supplied: either there are no ERAs to search in, or there are no domains * to search for. */ var Web3 = require("web3"); var web3 = new Web3(); contract("Finder: No Data Tests", function (accounts) { let common = require("./common"); const testDomainInfoAddress1 = "0x0000000000000000000000000000000000000011"; let testDomainHash; let testDomainHashP1; let testDomainHashP2; let testDomainHashP3; let eraAddress; let finderInterface; async function calculateDomainHashes() { testDomainHash = web3.utils.keccak256(common.TEST_DOMAIN); testDomainHashP1 = web3.utils.keccak256(common.TEST_DOMAIN_P1); testDomainHashP2 = web3.utils.keccak256(common.TEST_DOMAIN_P2); testDomainHashP3 = web3.utils.keccak256(common.TEST_DOMAIN_P3); } async function setupEras() { const domainOwner = accounts[1]; let eraInterface = await common.getDeployedERA(); const resultAddDomain = await eraInterface.addUpdateDomain( testDomainHash, common.DONT_SET, testDomainInfoAddress1, domainOwner ); } async function setupResolver() { finderInterface = await common.getNewFinder(); } beforeEach(async function () { if (testDomainHash == null) { await calculateDomainHashes(); await setupEras(); await setupResolver(); } }); it("resolveDomain: zero length eraAddress array", async function () { let eras = []; let resolvedDomainInfo = await finderInterface.resolveDomain.call( eras, testDomainHash, testDomainHashP1, testDomainHashP2, testDomainHashP3 ); assert.equal(0, resolvedDomainInfo); }); it("resolveDomains: zero length eraAddress array", async function () { let eras = []; let domainHashes = []; domainHashes[0] = testDomainHash; let p1DomainHashes = []; p1DomainHashes[0] = testDomainHashP1; let p2DomainHashes = []; p2DomainHashes[0] = testDomainHashP2; let p3DomainHashes = []; p3DomainHashes[0] = testDomainHashP3; let resolvedDomainInfos = await finderInterface.resolveDomains.call( eras, domainHashes, p1DomainHashes, p2DomainHashes, p3DomainHashes ); assert.equal(0, resolvedDomainInfos[0]); }); it("resolveDomains: zero length domainHash array", async function () { let eras = []; eras[0] = eraAddress; let domainHashes = []; let p1DomainHashes = []; let p2DomainHashes = []; let p3DomainHashes = []; let resolvedDomainInfos = await finderInterface.resolveDomains.call( eras, domainHashes, p1DomainHashes, p2DomainHashes, p3DomainHashes ); assert.equal(0, resolvedDomainInfos[0]); }); });
jQuery(function($){ $("#output").lunbo({ imgurl:["img/index/7d2f0da441884ab98365e768dfa61d5e.jpg", "img/index/ba40a2e1b72d40b99065cfe4419fe2bd.jpg", "img/index/65e3c6fd815645f497e2b35e12800a09.jpg", "img/index/8518fd4a74f443a896df10921bfcf905.jpg", "img/index/8702d80f5662476d92794ff04b7283ba.jpg", "img/index/b5a3ba84a4354702bce87068d5b59ec6.jpg", "img/index/4b089ae5e1c7472296fbbaae77bc0fad.jpg" ], type:"faded" }); var mySwiper = new Swiper ('.swiper-container', { direction: 'horizontal', navigation: { nextEl: '.swiper-button-next', prevEl: '.swiper-button-prev', }, }); $(".erji").show(); dl(); // jqajax(); jqajax2(".maotai",{type:0}); jqajax2(".laojiu",{type:1}); jqajax2(".zhekou",{type:2}); jqajax2(".chaozhi",{type:3}); jqajax2(".remai",{type:4}); jqajax3(".mthuodong",{type:0}); jqajax3(".ljhuodong",{type:1}); jqajax3(".zkhuodong",{type:2}); jqajax3(".czhuodong",{type:3}); jqajax3(".rmhuodong",{type:4}); jqajax4(5,render,7); jqajax4(1,render4,5); jqajax4(2,render5,5); function jqajax3(ele,a){ $.ajax({ url: "api/activity.php", data: a, success: function (res) { obj = JSON.parse(res); render3(ele,obj); } }); } function render3(ele,obj){ $(ele).html( $.map(obj, function (item, idx) { return `<a href=""> <img src="${item.com_img}" alt=""> </a>` }) ); } function jqajax2(ele,a){ $.ajax({ url: "api/commodity.php", data: a, success: function (res) { obj = JSON.parse(res); render2(ele,obj); } }); } function jqajax4(page,render,qty){ $.ajax({ url: "api/list.php", data: {page:page,qty:qty}, success: function (res) { obj = JSON.parse(res); render(obj.data); } }); } function render2(ele,obj){ $(ele).html( $.map(obj, function (item, idx) { return `<li data-id="${item.com_id}"> <a class="go_goods"> <div>${item.com_recom}</div> <img src="${item.com_img}" alt=""> <p>${item.com_name}</p> <span>${item.com_price}元</span> </a> </li>` }) ); tiaozhuang(); } // function jqajax(){ // $.ajax({ // url: "api/show_com.php", // success: function (res) { // obj = JSON.parse(res); // if(obj != ""){ // render(obj); // } // } // }); // } function tiaozhuang(){ $(".go_goods").on("click",function(){ var id = $(this).parents("li").attr("data-id"); location.href = "html/goods.html?comId="+id; }); } function render(obj){ $(".cont_ul").html( $.map(obj, function (item, idx) { return `<li data-id="${item.com_id}"> <a class="go_goods"> <img src="${item.com_img}" alt=""> <p> <span id="a_name">${item.com_name}</span> <span id="a_price">${item.com_price}元</span></p> </a> </li>` }) ); tiaozhuang(); } function render4(obj){ $(".slide1").html( $.map(obj, function (item, idx) { return `<li data-id="${item.com_id}"> <a class="go_goods"> <img src="${item.com_img}" alt=""> <p class="s_name">${item.com_name}</p> <p class="s_price">${item.com_price}元</p> <p class="s_pinglun">${item.com_eval} 人好评</p> </a> </li>` }) ); tiaozhuang(); } function render5(obj){ $(".slide2").html( $.map(obj, function (item, idx) { return `<li data-id="${item.com_id}"> <a class="go_goods"> <img src="${item.com_img}" alt=""> <p class="s_name">${item.com_name}</p> <p class="s_price">${item.com_price}元</p> <p class="s_pinglun">${item.com_eval} 人好评</p> </a> </li>` }) ); tiaozhuang(); } });
'use strict' import Axios from 'axios'; import { isEmpty, isEqual } from 'lodash'; import HttpStatus from 'http-status-codes'; const axios = Axios.create({ baseURL: 'https://slack.com/api', timeout: 20000, withCredentials: true }); const defaults = { token: undefined, channel: undefined, webhookURL: undefined }; const getHeaders = () => { return { Authorization: `Bearer ${defaults.token}` }; } const getChannelInfo = (channelId) => { return new Promise((resolve, reject) => { if (!channelId) { reject(); } let params = { channel: channelId }; axios.get('/channels.info', { headers: getHeaders(), params: params }).then(response => { if (isEqual(response.status, HttpStatus.OK)) { if (response.data.ok) { resolve(response.data.channel); } else { reject(); } } else { reject(); } }).catch(error => { reject(error); }); }); } const sendWebHookMessage = (channelId, params) => { return new Promise((resolve, reject) => { if (!channelId) { reject(); } params.channel = channelId; axios.post(this.webhookURL, params, { headers: getHeaders() }).then(response => { if (isEqual(response.status, HttpStatus.OK)) { resolve(); } else { reject(); } }).catch(error => { reject(error); }); }); } const sendPostMessage = (channelId, params) => { return new Promise((resolve, reject) => { if (!channelId) { reject(); } params.channel = channelId; axios.post('/chat.postMessage', params, { headers: getHeaders() }).then(response => { if (isEqual(response.status, HttpStatus.OK)) { resolve(); } else { console.log(response); reject(); } }).catch(error => { console.log(error); reject(error); }); }); } const makeSlackParams = (message, fields, actions) => { fields = fields || undefined; actions = actions || undefined; const DIVIDER = { type: 'divider', block_id: 'divider' }; const SECTION = { type: 'section', block_id: 'content', text: { type: 'mrkdwn', text: message }, fields: fields }; const FOOTER = { type: 'context', block_id: 'footer', elements: [ { 'type': 'mrkdwn', 'text': 'message by *coffee_bot*' } ] }; if (isEmpty(fields)) { delete SECTION.fields; } let blocks = makeSlackParamsBlocks(undefined, DIVIDER); blocks = makeSlackParamsBlocks(blocks, SECTION); blocks = makeSlackParamsBlocks(blocks, actions); blocks = makeSlackParamsBlocks(blocks, FOOTER); return { text: message, blocks: blocks }; } const makeSlackParamsBlocks = (blocks, block) => { blocks = blocks || []; if (!isEmpty(block)) { blocks.push(block); } return blocks; } module.exports = { defaults: defaults, getChannelInfo: getChannelInfo, sendWebHookMessage: sendWebHookMessage, sendPostMessage: sendPostMessage, makeSlackParams: makeSlackParams };
import React from 'react'; import PropTypes from 'prop-types'; import Button from '@material-ui/core/Button'; import { makeStyles } from '@material-ui/core/styles'; import './style.css'; const useStyles = makeStyles(() => ({ cancelbutton: { marginTop: 30, }, })); export const CancelButton = ({ onClick }) => { const classes = useStyles(); return ( <Button className={classes.cancelbutton} variant="contained" color="secondary" onClick={onClick} > Cancel </Button> ); }; CancelButton.propTypes = { onClick: PropTypes.func, };
import * as React from 'react'; import { DataGrid } from '@material-ui/data-grid'; import Card from '@material-ui/core/Card'; import CardContent from '@material-ui/core/CardContent'; import { useState, useEffect } from "react"; import { Link } from "react-router-dom"; import PrescriptionDataService from "../../../services/doctorPrescriptionService"; import "../../../components/staff-ui/ad_inventory/datecard.css" export default function ViewPrecription() { const [prescriptions, setPrescription] = useState([]); useEffect(() => { retrievePrescription(); }, []); const retrievePrescription = () => { PrescriptionDataService.getAll() .then(response => { setPrescription(response.data); //console.log(response.data); }) .catch(e => { console.log(e); }); }; const columns = [ { field: 'id', headerName: 'ID', width: 340 }, { field: 'patientName', headerName: 'PATIENT NAME', width: 340, editable: false, }, { field: 'diagnosis', headerName: 'Diagnosis', width: 240, editable: false, }, { field: 'action', headerName: 'Action', width: 150, sortable: false, editable: false, renderCell: (params) => { return ( <> <Link to={"/staff/pharmasist/drugdispense/" + params.row.id} > <button style={{ marginLeft: 40 }} className="userListEdit"> Bill </button> </Link> </> ); }, }, ]; let rows = []; for (const prescription of prescriptions) { rows.push( { id: prescription._id, patientName: prescription.dPName, diagnosis: prescription.dPDignosis, } ) } return ( <div style={{ marginBottom: 10 }} > <Card> <CardContent> <h3>Prescription List</h3> <br /> <div style={{ height: 400, width: '100%' }}> <DataGrid rows={rows} columns={columns} pageSize={5} disableSelectionOnClick style={{ backgroundColor: "#D9FAFF" }} /> </div> </CardContent> </Card> </div> ); }
var searchData= [ ['tearcontroller_2ecs_56',['TearController.cs',['../d7/d76/_tear_controller_8cs.html',1,'']]] ];
import React, { useContext, useState } from 'react' import { useHistory } from "react-router-dom" import { motion } from 'framer-motion' import { SweetConfirm, SweetError, SweetSuccess, SweetWrong } from '../../SweetAlert' import { Context } from '../../utils/context' import { notEmpty, ValidatePhone, validatePinCode } from '../../utils/functions' import api from '../../utils/api' import { PageAnimation } from '../../utils/PageAnimation' import StripeCard from './Components/StripeCard' const Checkout = () => { const [state, dispatch] = useContext(Context) const history = useHistory() const [checkOutDetails, setCheckOutDetails] = useState({ id:state.user.id, username:state.user.username, email:state.user.email, phone:'', address:'', city:'', pinCode:'', paymentMethod:'cod', TotalPrice:state.priceDetails.totalPrice, orders:state.cartItems }) const handleChange = (e) => { const {name ,value } = e.target setCheckOutDetails((prev) => { return { ...prev,[name]:value } }) } const handleSubmit = async (e) => { if(ValidatePhone(checkOutDetails.phone) && notEmpty(checkOutDetails.address,"Address") && notEmpty(checkOutDetails.city,"City") && validatePinCode(checkOutDetails.pinCode)){ try { const placeOrderDetails = { checkOutDetails, token: 0 } const res = await api.post('/placeorder',placeOrderDetails) SweetConfirm() const { success , error } = res.data if(success){ SweetSuccess(success) dispatch({type:'EMPTY_CART'}) history.push('/orders') } else SweetError(error) } catch (error) { SweetWrong() } } } return ( <motion.section className="flex justify-center items-center pt-10 md:pt-20 mb-10" initial='in' animate='out' exit='exit' variants={PageAnimation} transition={{ duration: 0.4 }}> <div className="w-full md:w-1/2"> <div className="bg-white mx-3 shadow-md rounded py-6 px-5 mb-4 grid md:gap-10 grid-cols-1 md:grid-cols-2"> <div> <div className="mx-3 mb-8"> <h1 className="text-2xl text-center md:text-left font-bold tracking-wider primary-text" htmlFor="name">Confirm Order</h1> </div> <div className="mb-4 mx-3"> <label className="input-label" htmlFor="username">Name</label> <input name="username" value={checkOutDetails.username} disabled className="input-box" type="text"/> </div> <div className="mb-4 mx-3"> <label className="input-label" htmlFor="email">Email</label> <input name="email" value={checkOutDetails.email} disabled className="input-box" type="text"/> </div> <div className="mb-4 mx-3"> <label className="input-label" htmlFor="phone">Phone</label> <input name="phone" value={checkOutDetails.phone} onChange={handleChange} className="input-box" maxLength="10" placeholder="Enter your phone number" autoComplete="none"/> </div> <div className="mb-4 mx-3"> <label className="input-label" htmlFor="address">Address</label> <input name="address" value={checkOutDetails.address} onChange={handleChange} className="input-box" type="text" placeholder="Enter your address"/> </div> </div> <div className="mt-0 md:mt-16"> <div className="mb-4 mx-3"> <label className="input-label" htmlFor="city">City</label> <input name="city" value={checkOutDetails.city} onChange={handleChange} className="input-box" type="text" placeholder="Enter your address"/> </div> <div className="mb-4 mx-3"> <label className="input-label" htmlFor="pinCode">Pin Code</label> <input name="pinCode" value={checkOutDetails.pinCode} onChange={handleChange} className="input-box" maxLength="6" placeholder="Enter your Pin Code"/> </div> <div className="mb-4 mx-4"> <label className="input-label">Payment Method</label> <select name="paymentMethod" onChange={handleChange} className="form-select text-sm shadow p-2 w-full"> <option value="cod">Cash On Delivery</option> <option value="card">Visa Card</option> </select> </div> { checkOutDetails.paymentMethod === "card" && <StripeCard checkOutDetails={checkOutDetails}/> } <div className="mb-4 mx-4"> <button onClick={handleSubmit} className={`${checkOutDetails.paymentMethod === "card" ? 'remove-btn':''} mt-11 w-full checkout-btn btn3`}> {`Pay ${checkOutDetails?.TotalPrice}`} </button> </div> </div> </div> </div> </motion.section>) } export default Checkout
/*global define*/ define([ 'underscore', 'backbone', 'models/user-model' ], function (_, Backbone, UserModel) { 'use strict'; var UsersCollection = Backbone.Collection.extend({ //Model used for this collection model: UserModel, //Default url to call to fetch this collection url: 'http://localhost:3000/users', parse: function(response) { /*if(!response.authenticated) { Backbone.history.navigate('login', true); }*/ return response; }, //Get a specific user from this collection getUser: function(login) { var log = parseInt(login); return this.findWhere({login: log}); }, //Test if a login number is already used isLoginAlreadyUsed: function(login) { var user = this.getUser(login); return user ? true : false; } }); return UsersCollection; });
/* See license.txt for terms of usage */ define([ "firebug/firebug", "firebug/lib/trace", "firebug/lib/object", "firebug/lib/domplate", "firebug/lib/events", "firebug/lib/dom", "firebug/lib/css", "firebug/lib/array", "firebug/dom/domBaseTree", "firebug/lib/locale", "firebug/debugger/clients/grip", "firebug/debugger/clients/scopeClient", "firebug/debugger/watch/watchExpression", "firebug/debugger/watch/watchProvider", ], function(Firebug, FBTrace, Obj, Domplate, Events, Dom, Css, Arr, DomBaseTree, Locale, Grip, ScopeClient, WatchExpression, WatchProvider) { // ********************************************************************************************* // // Constants var {domplate, FOR, TAG, DIV, TD, TR, TABLE, TBODY} = Domplate; var Trace = FBTrace.to("DBG_WATCH"); var TraceError = FBTrace.toError(); // ********************************************************************************************* // // DOM Tree Implementation function WatchTree(context, provider, memberProvider) { DomBaseTree.call(this, context, provider); this.memberProvider = memberProvider; } /** * @domplate This tree widget extends {@link DomBaseTree} and appends support for watch expressions. * The tree is responsible for rendering content within the {@link WatchPanel}. */ var BaseTree = DomBaseTree.prototype; WatchTree.prototype = domplate(BaseTree, /** @lends WatchTree */ { watchNewRowTag: TR({"class": "watchNewRow", level: 0}, TD({"class": "watchEditCell", colspan: 3}, DIV({"class": "watchEditBox a11yFocusNoTab", role: "button", tabindex: "0", "aria-label": Locale.$STR("a11y.labels.press enter to add new watch expression")}, Locale.$STR("NewWatch") ) ) ), tag: TABLE({"class": "domTable watchTable", cellpadding: 0, cellspacing: 0, _domPanel: "$domPanel", onclick: "$onClick", role: "tree"}, TBODY({role: "presentation"}, TAG("$watchNewRow|getWatchNewRowTag"), FOR("member", "$object|memberIterator", TAG("$member|getRowTag", {member: "$member"})) ) ), emptyTag: TR( TD({colspan: 3}) ), // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // getWatchNewRowTag: function(show) { return show ? this.watchNewRowTag : this.emptyTag; }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // getType: function(object) { // xxxHonza: this must be done through a decorator that can be also reused // in the DOM panel (applying types like: userFunction, DOM Function, domClass, etc.) // Checking the object type must be done after checking object instance (see issue 6953). // Customize CSS style for a memberRow. The type creates additional class name // for the row: 'type' + Row. So, the following creates "scopesRow" class that // decorates Scope rows. // Always use 'instanceof' when checking specific object properties. Even content // object can appear here. if (object instanceof ScopeClient) { return "scopes"; } else if (object instanceof WatchExpression) { return "watch"; } else if (object instanceof WatchProvider.FrameResultObject) { // Return a different class when the return value has already been emphasized. if (!object.alreadyEmphasized) return "frameResultValue"; else return "frameResultValueEmphasized"; } else if (object instanceof Grip) { if (object.getType() == "function") { return "userFunction"; } } return BaseTree.getType.apply(this, arguments); }, // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // // xxxHonza: we might want to move this into {@link DomBaseTree} to use the same logic // within the DOM panel. createMember: function(type, name, value, level, hasChildren) { var member = BaseTree.createMember.apply(this, arguments); // Disable editing for read only values. if (value instanceof Grip) member.readOnly = value.readOnly; member.deletable = true; return member; } }); // ********************************************************************************************* // // Registration return WatchTree; // ********************************************************************************************* // });
'use strict'; const routes = require('../../constants/routes.json'); const onSubmit = (bindActions) => { const { login, navigate } = bindActions; return (loginData) => { return login(loginData) .then(() => navigate(routes.tasks)); }; }; module.exports = { onSubmit };
'use strict'; module.exports = BigNumber; // jshint ignore:line
'use strict'; import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { FlatList, SectionList, Dimensions, Platform, Text, ViewPropTypes, View, ActivityIndicator, RefreshControl, StyleSheet, } from 'react-native'; import ListView from 'deprecated-react-native-listview'; import CommonStyles from '../common/Styles'; const { width, height } = Dimensions.get('window'); import SwipeRow from './SwipeRowS'; import ListEmptyCom from './ListEmptyCom'; /** * ListView that renders SwipeRows. */ class SwipeListView extends Component { constructor(props) { super(props); this._rows = {}; this.openCellKey = null; this.listViewProps = {}; if (Platform.OS === 'ios') { // Keep track of scroll offset and layout changes on iOS to be able to handle // https://github.com/jemise111/react-native-swipe-list-view/issues/109 this.yScrollOffset = 0; this.layoutHeight = 0; this.listViewProps = { onLayout: e => this.onLayout(e), onContentSizeChange: (w, h) => this.onContentSizeChange(w, h), }; } } setScrollEnabled(enable) { if (this.props.scrollEnabled === false) { return; } // Due to multiple issues reported across different versions of RN // We do this in the safest way possible... if (this._listView && this._listView.setNativeProps) { this._listView.setNativeProps({ scrollEnabled: enable }); } else if (this._listView && this._listView.getScrollResponder) { const scrollResponder = this._listView.getScrollResponder(); scrollResponder.setNativeProps && scrollResponder.setNativeProps({ scrollEnabled: enable }); } this.props.onScrollEnabled && this.props.onScrollEnabled(enable); } safeCloseOpenRow() { const rowRef = this._rows[this.openCellKey]; if (rowRef && rowRef.closeRow) { this._rows[this.openCellKey].closeRow(); } } rowSwipeGestureBegan(key) { if ( this.props.closeOnRowBeginSwipe && this.openCellKey && this.openCellKey !== key ) { this.safeCloseOpenRow(); } if (this.props.swipeGestureBegan) { this.props.swipeGestureBegan(key); } } onRowOpen(key, toValue) { if (this.openCellKey && this.openCellKey !== key) { this.safeCloseOpenRow(); } this.openCellKey = key; this.props.onRowOpen && this.props.onRowOpen(key, this._rows, toValue); } onRowPress() { if (this.openCellKey) { if (this.props.closeOnRowPress) { this.safeCloseOpenRow(); this.openCellKey = null; } } } onScroll(e) { if (Platform.OS === 'ios') { this.yScrollOffset = e.nativeEvent.contentOffset.y; } if (this.openCellKey) { if (this.props.closeOnScroll) { this.safeCloseOpenRow(); this.openCellKey = null; } } this.props.onScroll && this.props.onScroll(e); } onLayout(e) { this.layoutHeight = e.nativeEvent.layout.height; this.props.onLayout && this.props.onLayout(e); } // When deleting rows on iOS, the list may end up being over-scrolled, // which will prevent swiping any of the remaining rows. This triggers a scrollToEnd // when that happens, which will make sure the list is kept in bounds. // See: https://github.com/jemise111/react-native-swipe-list-view/issues/109 onContentSizeChange(w, h) { const height = h - this.layoutHeight; if (this.yScrollOffset >= height && height > 0) { this._listView && this._listView.getScrollResponder().scrollToEnd(); } this.props.onContentSizeChange && this.props.onContentSizeChange(w, h); } setRefs(ref) { this._listView = ref; this.props.listViewRef && this.props.listViewRef(ref); } renderCell(VisibleComponent, HiddenComponent, key, item, shouldPreviewRow) { if (!HiddenComponent) { return React.cloneElement(VisibleComponent, { ...VisibleComponent.props, ref: row => (this._rows[key] = row), onRowOpen: toValue => this.onRowOpen(key, toValue), onRowDidOpen: toValue => this.props.onRowDidOpen && this.props.onRowDidOpen(key, this._rows, toValue), onRowClose: _ => this.props.onRowClose && this.props.onRowClose(key, this._rows), onRowDidClose: _ => this.props.onRowDidClose && this.props.onRowDidClose(key, this._rows), onRowPress: _ => this.onRowPress(), setScrollEnabled: enable => this.setScrollEnabled(enable), swipeGestureBegan: _ => this.rowSwipeGestureBegan(key), }); } else { return ( <SwipeRow ref={row => (this._rows[key] = row)} key={key} swipeGestureBegan={_ => this.rowSwipeGestureBegan(key)} onRowOpen={toValue => this.onRowOpen(key, toValue)} onRowDidOpen={toValue => this.props.onRowDidOpen && this.props.onRowDidOpen(key, this._rows, toValue) } onRowClose={_ => this.props.onRowClose && this.props.onRowClose(key, this._rows) } onRowDidClose={_ => this.props.onRowDidClose && this.props.onRowDidClose(key, this._rows) } onRowPress={_ => this.onRowPress(key)} setScrollEnabled={enable => this.setScrollEnabled(enable)} leftOpenValue={ item.leftOpenValue || this.props.leftOpenValue } rightOpenValue={ item.rightOpenValue || this.props.rightOpenValue } closeOnRowPress={ item.closeOnRowPress || this.props.closeOnRowPress } disableLeftSwipe={ item.disableLeftSwipe || this.props.disableLeftSwipe } disableRightSwipe={ item.disableRightSwipe || this.props.disableRightSwipe } stopLeftSwipe={ item.stopLeftSwipe || this.props.stopLeftSwipe } stopRightSwipe={ item.stopRightSwipe || this.props.stopRightSwipe } recalculateHiddenLayout={this.props.recalculateHiddenLayout} style={this.props.swipeRowStyle} preview={shouldPreviewRow} previewDuration={this.props.previewDuration} previewOpenDelay={this.props.previewOpenDelay} previewOpenValue={this.props.previewOpenValue} tension={this.props.tension} friction={this.props.friction} directionalDistanceChangeThreshold={ this.props.directionalDistanceChangeThreshold } swipeToOpenPercent={this.props.swipeToOpenPercent} swipeToOpenVelocityContribution={ this.props.swipeToOpenVelocityContribution } swipeToClosePercent={this.props.swipeToClosePercent} > {HiddenComponent} {VisibleComponent} </SwipeRow> ); } } renderRow(rowData, secId, rowId, rowMap) { const key = `${secId}${rowId}`; const Component = this.props.renderRow(rowData, secId, rowId, rowMap); const HiddenComponent = this.props.renderHiddenRow && this.props.renderHiddenRow(rowData, secId, rowId, rowMap); const previewRowId = this.props.dataSource && this.props.dataSource.getRowIDForFlatIndex( this.props.previewRowIndex || 0 ); const shouldPreviewRow = (this.props.previewFirstRow || this.props.previewRowIndex) && rowId === previewRowId; return this.renderCell( Component, HiddenComponent, key, rowData, shouldPreviewRow ); } renderItem(rowData, rowMap) { const Component = this.props.renderItem(rowData, rowMap); const HiddenComponent = this.props.renderHiddenItem && this.props.renderHiddenItem(rowData, rowMap); let { item, index } = rowData; let { key } = item; if (!key && this.props.keyExtractor) { key = this.props.keyExtractor(item, index); } const shouldPreviewRow = this.props.previewRowKey === key; return this.renderCell( Component, HiddenComponent, key, item, shouldPreviewRow ); } ListEmptyComponent = () => { const { store,useFlatList ,type} = this.props; const { refreshing, loading, isFirstLoad } = useFlatList ? store:this.props; console.log('/////////////',refreshing && loading || isFirstLoad); return ( <View style={[styles.emptyView, this.props.emptyStyle,{width:this.props.style && this.props.style.width || width}]}> { refreshing && loading || isFirstLoad ? null: <ListEmptyCom type={type}/> } </View> ); } ListHeaderComponent = () => { return <View style={[styles.separator, styles.headerView]} />; }; ListFooterComponent = () => { const { store, data } = this.props; const { refreshing, hasMore, page } = store; // if (refreshing || data.length == 0 || page == 1) return null if (refreshing || data.length == 0) {return null;} return ( <View style={[styles.footerView, this.props.footerStyle]}> <Text style={styles.footerText}> {hasMore ? '加载中...' : data.length <= 10 ? '' : '已经到底啦'} </Text> </View> ); }; keyExtractor = (item, index) => { return index.toString(); }; ItemSeparatorComponent = () => { return <View style={styles.separator} />; }; // 返回顶部 scrollToTop = () => { console.log('%cscrollToTop', 'background: red; color: #fff'); this.flatListRef && this.flatListRef.scrollToOffset({ offset: 0 }); }; refresh = () => { const { refreshData } = this.props; if (!refreshData) {return;} // 刷新 console.log('%crefreshData', 'background: red; color: #fff'); refreshData(); }; loadMore = () => { const { store, data, loadMoreData } = this.props; const { refreshing, loading, hasMore } = store; console.log('%cloadMore-before', 'background: red; color: #fff'); if (refreshing || loading || !hasMore || data.length == 0 || !loadMoreData) {return}; // 请求更多 console.log('%cloadMoreData', 'background: red; color: #fff'); loadMoreData(); } render() { const { useFlatList, useSectionList, renderListView, type, ...props } = this.props; if (renderListView) { return renderListView( props, this.setRefs.bind(this), this.onScroll.bind(this), useFlatList || useSectionList ? this.renderItem.bind(this) : this.renderRow.bind(this, this._rows) ); } // if (useFlatList) { // return ( // <FlatList // {...props} // {...this.listViewProps} // ref={c => this.setRefs(c)} // onScroll={e => this.onScroll(e)} // renderItem={(rowData) => this.renderItem(rowData, this._rows)} // /> // ); // } if (useFlatList) { const { store, data, onScroll, ListEmptyComponent, ListHeaderComponent, ListFooterComponent, renderItem, ItemSeparatorComponent, refreshData, loadMoreData, numColumns, } = this.props; const { refreshing } = store; return ( <FlatList {...props} {...this.listViewProps} ref={c => this.setRefs(c)} // ref={(e) => { this.setRefs(e); return e && (this.flatListRef = e) }} style={[styles.flatList, this.props.style]} showsHorizontalScrollIndicator={false} showsVerticalScrollIndicator={false} onScroll={e => { this.onScroll(e); }} ListEmptyComponent={ ListEmptyComponent || this.ListEmptyComponent } ListHeaderComponent={ ListHeaderComponent || this.ListHeaderComponent } ListFooterComponent={ ListFooterComponent || this.ListFooterComponent } data={data} initialNumToRender={10} keyExtractor={this.keyExtractor} renderItem={rowData => this.renderItem(rowData, this._rows)} key={numColumns === 1 ? 'row' : 'column'} // 要动态改变numColumns必须设置key numColumns={numColumns || 1} ItemSeparatorComponent={ ItemSeparatorComponent || this.ItemSeparatorComponent } refreshControl={ <RefreshControl colors={['#2ba09d']} refreshing={refreshing} onRefresh={this.refresh} /> } onEndReached={this.loadMore} onEndReachedThreshold={1} /> ); } if (useSectionList) { return ( <SectionList {...props} {...this.listViewProps} ref={c => this.setRefs(c)} onScroll={e => this.onScroll(e)} renderItem={rowData => this.renderItem(rowData, this._rows)} /> ); } return ( this.props.data && this.props.data.length == 0 && this.props.isFirstLoad === false ? <View style={[styles.emptyView]}> <ListEmptyCom type={type}/> </View> : <ListView {...props} {...this.listViewProps} ref={c => this.setRefs(c)} onScroll={e => this.onScroll(e)} showsHorizontalScrollIndicator={false} showsVerticalScrollIndicator={false} renderRow={(rowData, secId, rowId) => this.renderRow(rowData, secId, rowId, this._rows) } /> ); } } SwipeListView.propTypes = { /** * To render a custom ListView component, if you don't want to use ReactNative one. * Note: This will call `renderRow`, not `renderItem` */ renderListView: PropTypes.func, /** * How to render a row in a FlatList. Should return a valid React Element. */ renderItem: PropTypes.func, /** * How to render a hidden row in a FlatList (renders behind the row). Should return a valid React Element. * This is required unless renderItem is passing a SwipeRow. */ renderHiddenItem: PropTypes.func, /** * [DEPRECATED] How to render a row in a ListView. Should return a valid React Element. */ renderRow: PropTypes.func, /** * [DEPRECATED] How to render a hidden row in a ListView (renders behind the row). Should return a valid React Element. * This is required unless renderRow is passing a SwipeRow. */ renderHiddenRow: PropTypes.func, /** * TranslateX value for opening the row to the left (positive number) */ leftOpenValue: PropTypes.number, /** * TranslateX value for opening the row to the right (negative number) */ rightOpenValue: PropTypes.number, /** * TranslateX value for stop the row to the left (positive number) */ stopLeftSwipe: PropTypes.number, /** * TranslateX value for stop the row to the right (negative number) */ stopRightSwipe: PropTypes.number, /** * Should open rows be closed when the listView begins scrolling */ closeOnScroll: PropTypes.bool, /** * Should open rows be closed when a row is pressed */ closeOnRowPress: PropTypes.bool, /** * Should open rows be closed when a row begins to swipe open */ closeOnRowBeginSwipe: PropTypes.bool, /** * Disable ability to swipe rows left */ disableLeftSwipe: PropTypes.bool, /** * Disable ability to swipe rows right */ disableRightSwipe: PropTypes.bool, /** * Enable hidden row onLayout calculations to run always. * * By default, hidden row size calculations are only done on the first onLayout event * for performance reasons. * Passing ```true``` here will cause calculations to run on every onLayout event. * You may want to do this if your rows' sizes can change. * One case is a SwipeListView with rows of different heights and an options to delete rows. */ recalculateHiddenLayout: PropTypes.bool, /** * Called when a swipe row is animating swipe */ swipeGestureBegan: PropTypes.func, /** * Called when a swipe row is animating open */ onRowOpen: PropTypes.func, /** * Called when a swipe row has animated open */ onRowDidOpen: PropTypes.func, /** * Called when a swipe row is animating closed */ onRowClose: PropTypes.func, /** * Called when a swipe row has animated closed */ onRowDidClose: PropTypes.func, /** * Called when scrolling on the SwipeListView has been enabled/disabled */ onScrollEnabled: PropTypes.func, /** * Styles for the parent wrapper View of the SwipeRow */ swipeRowStyle: ViewPropTypes.style, /** * Called when the ListView (or FlatList) ref is set and passes a ref to the ListView (or FlatList) * e.g. listViewRef={ ref => this._swipeListViewRef = ref } */ listViewRef: PropTypes.func, /** * Should the row with this key do a slide out preview to show that the list is swipeable */ previewRowKey: PropTypes.string, /** * [DEPRECATED] Should the first SwipeRow do a slide out preview to show that the list is swipeable */ previewFirstRow: PropTypes.bool, /** * [DEPRECATED] Should the specified rowId do a slide out preview to show that the list is swipeable * Note: This ID will be passed to this function to get the correct row index * https://facebook.github.io/react-native/docs/listviewdatasource.html#getrowidforflatindex */ previewRowIndex: PropTypes.number, /** * Duration of the slide out preview animation (milliseconds) */ previewDuration: PropTypes.number, /** * Delay of the slide out preview animation (milliseconds) // default 700ms */ prewiewOpenDelay: PropTypes.number, /** * TranslateX value for the slide out preview animation * Default: 0.5 * props.rightOpenValue */ previewOpenValue: PropTypes.number, /** * Friction for the open / close animation */ friction: PropTypes.number, /** * Tension for the open / close animation */ tension: PropTypes.number, /** * The dx value used to detect when a user has begun a swipe gesture */ directionalDistanceChangeThreshold: PropTypes.number, /** * What % of the left/right openValue does the user need to swipe * past to trigger the row opening. */ swipeToOpenPercent: PropTypes.number, /** * Describes how much the ending velocity of the gesture affects whether the swipe will result in the item being closed or open. * A velocity factor of 0 means that the velocity will have no bearing on whether the swipe settles on a closed or open position * and it'll just take into consideration the swipeToOpenPercent. */ swipeToOpenVelocityContribution: PropTypes.number, /** * What % of the left/right openValue does the user need to swipe * past to trigger the row closing. */ swipeToClosePercent: PropTypes.number, }; SwipeListView.defaultProps = { leftOpenValue: 0, rightOpenValue: 0, closeOnRowBeginSwipe: false, closeOnScroll: true, closeOnRowPress: true, disableLeftSwipe: false, disableRightSwipe: false, recalculateHiddenLayout: false, previewFirstRow: false, directionalDistanceChangeThreshold: 2, swipeToOpenPercent: 50, swipeToOpenVelocityContribution: 0, swipeToClosePercent: 50, }; export default SwipeListView; const styles = StyleSheet.create({ container: { ...CommonStyles.containerWithoutPadding, flexDirection: 'column', justifyContent: 'center', alignItems: 'center', }, flatList: { flex: 1, backgroundColor: '#fff', }, emptyView: { flexDirection: 'row', justifyContent: 'center', alignItems: 'center', width: width, marginTop: 50, }, emptyText: { fontSize: 16, color: '#666', }, headerView: { // }, footerView: { flexDirection: 'row', justifyContent: 'center', alignItems: 'center', width: width, height: 40, backgroundColor: CommonStyles.globalBgColor, }, footerText: { fontSize: 14, color: '#666', }, separator: { width: width, height: 10, backgroundColor: CommonStyles.globalBgColor, }, });
var World = require('./world'); var CRUISING = 0.00001; function Bullet(player, now) { var self = this; var p = player.get_actual(now); var name = p.name + "_bullet"; var type = "bullet"; var _id = p.id + "___" + now; var r = p.r; var dy = CRUISING * Math.cos(r); var dx = CRUISING * Math.sin(r); var x = p.x + dx * 100; var y = p.y + dy * 100; var _t = now; var player_id = p.id; self.player = player; World.addBullet(self); self.get_actual = function (t) { var dt = t - _t; return { x:x + dx * dt, y:y + dy * dt, dx:dx, dy:dy, r:r, player_id: player_id, name:name, type: type, id: _id}; }; self.get_id = function () { return _id; } setTimeout(function () { World.removeBullet(self); }, 5000); } module.exports = Bullet;
import React from 'react'; //import { Link} from "react-router-dom"; import 'bootstrap/dist/css/bootstrap.min.css'; import '../auth/Auth'; //import "../auth/Signup"; //import "../auth/Login"; const Home = (props) => { console.log(`HOME PROPS: `, props) return ( <div className="main"> <div className="mainDiv"> <div className="jumbotron fluid"> <div className="container"> <h1>{props.token}</h1> <h1>Welcome to Rescue!</h1> <p>Please sign in to see how you can help or need to request help!</p> <ul> <li>Looking for a pet?</li> <li>Need transport help?</li> <li>Need a rescue to help?</li> </ul> </div> <div className="container"> <div className="auth"></div> </div> </div> </div> </div> ) } export default Home;
var num1; var num2; num1 = prompt("Enter Number 1"); num2 = prompt("Enter Number 2"); var div = parseInt(num1)/parseInt(num2); document.write("Division of "+num1+" and "+num2+" is "+div);
'use strict'; System.register(['aurelia-framework', 'jquery', 'periscope-framework', 'lodash'], function (_export, _context) { var Container, Decorators, bindable, $, StringHelper, IntellisenceManager, GrammarTree, SearchBox, ExpressionParser, PermissionsCustomAttribute, _, _createClass, DefaultSearchBox; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } return { setters: [function (_aureliaFramework) { Container = _aureliaFramework.Container; Decorators = _aureliaFramework.Decorators; bindable = _aureliaFramework.bindable; }, function (_jquery) { $ = _jquery.default; }, function (_periscopeFramework) { StringHelper = _periscopeFramework.StringHelper; IntellisenceManager = _periscopeFramework.IntellisenceManager; GrammarTree = _periscopeFramework.GrammarTree; SearchBox = _periscopeFramework.SearchBox; ExpressionParser = _periscopeFramework.ExpressionParser; PermissionsCustomAttribute = _periscopeFramework.PermissionsCustomAttribute; }, function (_lodash) { _ = _lodash; }], execute: function () { _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); _export('DefaultSearchBox', DefaultSearchBox = function (_SearchBox) { _inherits(DefaultSearchBox, _SearchBox); function DefaultSearchBox(settings) { _classCallCheck(this, DefaultSearchBox); var _this = _possibleConstructorReturn(this, _SearchBox.call(this, settings)); _this._isValid = true; _this._caretPosition = 0; _this._separators = [" ", ","]; _this._specialSymbols = ["'", "(", ")", "\""]; _this._timer; _this._suggestionsListSettings = { title: '', suggestions: [], focusedSuggestion: -1, displaySuggestions: false, lastWord: '' }; return _this; } DefaultSearchBox.prototype.refresh = function refresh() { _SearchBox.prototype.refresh.call(this); var self = this; this.dataSource.transport.readService.getSchema().then(function (schema) { var allFields = _.map(schema.fields, "field"); var grammar = new GrammarTree(schema.fields); self.parser = new ExpressionParser(grammar.getGrammar()); self.expressionManager = new IntellisenceManager(self.parser, self.dataSource, allFields); self.restoreState(); if (self.state) self.suggestionsListSettings.displaySuggestions = false; }); }; DefaultSearchBox.prototype.attached = function attached() { var self = this; $(this.searchBox)[0].addEventListener("keydown", function (e) { if (e.keyCode == 40) { self.suggestionsListSettings.focusedSuggestion = 0; e.preventDefault(); e.stopPropagation(); } else { self.suggestionsListSettings.focusedSuggestion = -1; self._caretPosition = this.selectionEnd + 1; } if (e.keyCode == 27 || e.keyCode == 13) { self.suggestionsListSettings.displaySuggestions = false; } }, true); $(function () { $('[data-toggle="tooltip"]').tooltip(); }); }; DefaultSearchBox.prototype.populateSuggestions = function populateSuggestions(searchStr) { var _this2 = this; searchStr = searchStr.substring(0, this.caretPosition); var lastWord = this.getLastWord(searchStr); this.suggestionsListSettings.title = ''; this.expressionManager.populate(searchStr, lastWord).then(function (data) { _this2.suggestionsListSettings.suggestions = data; _this2.suggestionsListSettings.lastWord = lastWord; _this2.suggestionsListSettings.displaySuggestions = _this2.suggestionsListSettings.suggestions.length > 0; }); }; DefaultSearchBox.prototype.select = function select(suggestion) { var searchStr = this.searchString; var position = this.caretPosition; while (position < searchStr.length && searchStr[position] != " ") { position++; } var strLeft = searchStr.substring(0, position); var strRight = position < searchStr.length ? searchStr.substring(position, searchStr.length) : ''; var wordToReplace = this.getLastWord(searchStr); strLeft = strLeft.substring(0, strLeft.lastIndexOf(wordToReplace)); var value = suggestion.value; if (suggestion.type === 'string' || suggestion.type === 'array_string') value = "'" + value + "'"; if (suggestion.type === 'array_string') { var openBraceExsits = false; for (var i = strLeft.trim().length; i >= 0; i--) { if (strLeft[i] === "(") { openBraceExsits = true; break; } if (strLeft[i] === ")") break; } if (!openBraceExsits) value = "(" + value;else { var lastChar = strLeft.trim().charAt(strLeft.trim().length - 1); if (lastChar !== '(' && lastChar !== ',') value = "," + value; } } if (suggestion.type === 'operator' && suggestion.value === 'in') value += " (";else value += " "; this.caretPosition = (strLeft + value).length; this.searchString = strLeft + value + strRight; }; DefaultSearchBox.prototype.getLastWord = function getLastWord(searchStr) { var str = StringHelper.getPreviousWord(searchStr, this.caretPosition, this._separators); for (var _iterator = this._specialSymbols, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { var _ref; if (_isArray) { if (_i >= _iterator.length) break; _ref = _iterator[_i++]; } else { _i = _iterator.next(); if (_i.done) break; _ref = _i.value; } var s = _ref; str = StringHelper.replaceAll(str, "\\" + s, ""); }return str.trim(); }; DefaultSearchBox.prototype.notifySearchCriteriaChanged = function notifySearchCriteriaChanged() { this.saveState(); var self = this; window.clearTimeout(self._timer); self._timer = window.setTimeout(function () { if (self.isValid) { var astTree = void 0; if (self.searchString !== '') astTree = self.parser.parse(self.searchString); self.dataFilterChanged.raise(astTree); } }, 500); }; _createClass(DefaultSearchBox, [{ key: 'parser', get: function get() { return this._parser; }, set: function set(value) { this._parser = value; } }, { key: 'expressionManager', get: function get() { return this._expressionManager; }, set: function set(value) { this._expressionManager = value; } }, { key: 'selectedSuggestion', get: function get() { return this._selectedSuggestion; }, set: function set(value) { if (this._selectedSuggestion != value) { this._selectedSuggestion = value; this.select(this._selectedSuggestion); } } }, { key: 'suggestionsListSettings', get: function get() { return this._suggestionsListSettings; }, set: function set(value) { this._suggestionsListSettings = value; } }, { key: 'isValid', get: function get() { if (this.searchString === '' || !this.parser) return true; return this.parser.validate(this.searchString); } }, { key: 'searchString', get: function get() { return this._searchString; }, set: function set(value) { if (this._searchString != value) { this._searchString = value; this.populateSuggestions(value); if (this.isValid) { this.notifySearchCriteriaChanged(); } } } }, { key: 'caretPosition', get: function get() { return this._caretPosition; }, set: function set(value) { if (value != this._caretPosition) { var self = this; self._caretPosition = value; $(self.searchBox)[0].focus(); window.setTimeout(function () { $(self.searchBox)[0].setSelectionRange(value, value); }, 400); } } }]); return DefaultSearchBox; }(SearchBox)); _export('DefaultSearchBox', DefaultSearchBox); } }; });
import {Dimensions, Platform, StyleSheet} from 'react-native' export default StyleSheet.create({ container: { display: 'flex', alignItems: 'center' }, viewBody: { paddingTop: 20, }, textCongratulations: { color: '#D4A452', textAlign: 'center', fontSize: 22, fontWeight: '500' }, textBody: { textAlign: 'center', color: '#9F9F9F', fontSize: 16 }, image: { height: 100, width: 100, flex: 1, marginTop: 10 }, viewTextCupom: { display: 'flex', flexDirection: 'row' }, textCupom: { fontSize: 16, color: '#87A23D' }, textCupomCenter: { fontSize: 16, color: '#9F9F9F' }, lastView: { display: 'flex', flexDirection: 'row', paddingTop: 20, }, buttonSubmit: { backgroundColor: '#D4A452', marginTop: 20, marginLeft: 15, marginRight: 15 }, textButtonSubmit: { color: '#ffffff' } });
import express from 'express'; import pg from 'pg'; import cors from 'cors'; import dayjs from 'dayjs' const app = express(); app.use(cors()); app.use(express.json()); const { Pool } = pg; const connection = new Pool({ user: 'bootcamp_role', password: 'senha_super_hiper_ultra_secreta_do_role_do_bootcamp', host: 'localhost', port: 5432, database: 'boardcamp' }); let localizador = 0; let categorias = []; let jogos = []; let clientes = []; let alugueis = []; let existeCategoria = false; let existeIdCategoria = false; let existeNomeJogo = false; let dataValida = true; let existeCPF = false; loadCategorias(); async function loadCategorias(){ const result = await connection.query('SELECT * FROM categories'); if(result.row != []){ categorias = [...result.rows]; console.log(categorias); } return result.rows; } function verificarCategoria(categoria){ if(categorias.length != 0){ for(let i =0; i<categorias.length; i++){ if(categoria === categorias[i]){ existeCategoria = true; } } } else{ existeCategoria = false; } } function verificarIdCategoria(id){ if(categorias.length != 0){ for(let i =0; i<categorias.length; i++){ if(id === categorias[i].id){ existeIdCategoria = true; } } } else{ existeIdCategoria = false; } } function verificarNomeJogo (nome){ if(jogos.length != 0){ for(let i =0; i<jogos.length; i++){ if(nome === jogos[i].name){ existeNomeJogo = true; localizador = i; } } } else{ existeNomeJogo = false; } } function verificarCPF(cpf){ if(clientes.length != 0){ for(let i = 0; i < clientes.length; i++){ if(cpf == clientes[i].cpf){ existeCPF = true; } } } else{ existeCPF = false; } } function validarData(data){ if(data[5] != 1 && data[6] != 0){ dataValida = false; } if(data[8] != 1 && data[8]!= 0 && data[8]!= 2 && data[8]!= 3){ dataValida = false; } if(data[8]== 3){ if(data[9] != 0 && data[9] != 1){ dataValida = false; } } else{ dataValida = true; } } app.get('/categories', (req, res) => { const result = loadCategorias(); res.send(result); }); app.post('/categories', async (req, res) =>{ const {name} = req.body; verificarCategoria(name); if(name == '' || existeCategoria == true){ if(existeCategoria){ res.status(409).end(); } else{ res.status(400).end(); } } else{ try{ const result = await connection.query('INSERT INTO categories (name) VALUES ($1)', [name]); res.status(200).end(); }catch(error){ res.status(500).end(); } } }); app.get('/games', async (req, res) => { const result = await connection.query('SELECT * FROM games'); if(result.row != []){ jogos = [...result.rows]; console.log(jogos); } res.send(result.rows); }); app.post('/games', async (req, res) => { verificarIdCategoria(req.body.categoryId); verificarNomeJogo(req.body.name); if(req.body.name == '' || req.body.stockTotal < 0 || req.body.pricePerDay < 0){ console.log("N TEM CFUNDA"); res.status(400).end(); } else if(existeIdCategoria === false){ console.log("N TEM CATEGORIA"); res.status(400).end(); } else if(existeNomeJogo === true){ res.status(409).end(); } else{ try{ const result = await connection.query('INSERT INTO games (name , image , "stockTotal" , "categoryId", "pricePerDay") VALUES ($1 , $2 , $3 , $4 , $5)', [req.body.name, req.body.image, req.body.stockTotal, req.body.categoryId, req.body.pricePerDay]); res.status(200).end(); }catch(error){ console.log(error); res.status(500).end(); } } }); app.get('/customers', async (req, res) => { const result = await connection.query('SELECT * FROM customers'); if(result.row != []){ clientes = [...result.rows]; console.log(clientes); } res.send(result.rows); }); app.post('/customers', async (req, res) => { validarData(req.body.birthday); verificarCPF(req.body.cpf); if(req.body.cpf.length != 11 || req.body.name == '') { res.status(400).end(); } if(req.body.phone.length != 10 && req.body.phone.length != 11){ res.status(400).end(); } else if(dataValida == false){ res.status(400).end(); } else if(existeCPF == true){ res.status(409).end(); } else{ try{ const result = await connection.query('INSERT INTO customers (name, phone, cpf, "birthday") VALUES ($1 , $2 , $3 , $4 )', [req.body.name, req.body.phone, req.body.cpf, req.body.birthday]); res.status(200).end(); }catch(error){ console.log(error); res.status(500).end(); } } }); app.put('/customers/:id', async (req, res)=>{ validarData(req.body.birthday); if(req.body.cpf.length != 11 || req.body.name == '') { res.status(400).end(); } if(req.body.phone.length != 10 && req.body.phone.length != 11){ res.status(400).end(); } else if(dataValida == false){ res.status(400).end(); } else{ try{ const result = await connection.query('UPDATE customers SET name=$1, phone = $2, cpf=$3, "birthday"=$4 WHERE id= $5', [req.body.name, req.body.phone, req.body.cpf, req.body.birthday, req.params.id]); res.status(200).end(); }catch(error){ console.log(error); res.status(500).end(); } } }); app.get('/rentals', async (req, res) => { const result = await connection.query('SELECT * FROM rentals'); if(result.row != []){ alugueis = [...result.rows]; console.log(alugueis); } res.send(result.rows); }); app.post('/rentals', async (req, res) => { let now = dayjs(); const rentDate = now.format('YYYY-MM-DD'); console.log(rentDate); const originalPrice = 0; try{ const result = await connection.query('INSERT INTO rentals ("customerId", "gameId", "rentDate", "daysRented", "returnDate", "originalPrice", "delayFee") VALUES ($1 , $2 , $3 , $4 , $5, $6, $7)', [req.body.customerId, req.body.gameId, rentDate, req.body.daysRented, null, originalPrice, null]); res.status(200).end(); }catch(error){ console.log(error); res.status(500).end(); } }); app.listen(4000, () => { console.log('Server listening on port 4000.'); });
const { Stream: $ } = require('xstream') const Cycle = require('component') const dropRepeats = require('xstream/extra/dropRepeats').default const prop = require('ramda/src/prop') const lensProp = require('ramda/src/lensProp') const over = require('ramda/src/over') const unless = require('ramda/src/unless') const pipe = require('ramda/src/pipe') const path = require('ramda/src/path') const complement = require('ramda/src/complement') const { WithValidable, makeValidable } = require('components/Validable') const isPlainObject = require('lodash/isPlainObject') const isString = require('lodash/isString') const isFunction = require('lodash/isFunction') const { makeFieldInput } = require('./Input') const { makeFieldLabel } = require('./Label') const { makeFieldMessage } = require('./Message') const { WithView } = require('components/View') const { WithTransition } = require('component/operators/transition') const { WithFocusable } = require('components/Focusable') const isNonEmptyString = require('predicates/isNonEmptyString') const { Empty } = require('monocycle/component') const Factory = require('utilities/factory') const KindReducer = require('utilities/kind') const always = require('ramda/src/always') const parseOptions = pipe( unless(isPlainObject, Empty), over(lensProp('makeLabel'), unless(isFunction, always(makeFieldLabel))), over(lensProp('makeInput'), unless(isFunction, always(makeFieldInput))), over(lensProp('makeMessage'), unless(isFunction, always(makeFieldMessage))), over(lensProp('name'), unless(isNonEmptyString, () => Math.random().toString(36).substring(7)) ), over(lensProp('label'), unless(isNonEmptyString, always('')) ), over(lensProp('validableOptions'), unless(isPlainObject, Empty)), ) const WithField = options => { const { kind = 'Field', name, label, makeInput, makeLabel, makeMessage, getFocusEvent$, getBlurEvent$, validableOptions, ...viewOptions } = options = parseOptions(options) const classes = { Field: 'Field', ...options.classes } Cycle.log('WithField()', { ...options, kind, getFocusEvent$, getBlurEvent$, makeLabelIsDefault: makeFieldLabel === makeLabel // has }) validableOptions.lens = isFunction(validableOptions.lens) ? validableOptions.lens : lensProp(name) return pipe( WithFocusable({ getFocusEvent$, getBlurEvent$, }), WithTransition({ name: 'initField', from: (sinks, sources) => sources.onion.state$ .filter(complement(prop('isField'))) .filter(prop('isValidable')), reducer: () => pipe( KindReducer('Field'), state => ({ ...state, name: state.name && isString(state.name) ? state.name : name, label, value: state.value, viewValue: state.viewValue || state.value, isField: true }) ) }, Cycle), WithView({ classes, from: (sinks, sources) => sources.onion.state$ .filter(prop('isField')) .compose(dropRepeats((x, y) => x.viewValue === y.viewValue && x.value === y.value && x.isValid === y.isValid && x.isFocused === y.isFocused )) .map(({ isValid, isFocused, value, viewValue }) => { const isDirty = viewValue !== value return { class: { active: isFocused || viewValue, valid: isValid && isDirty, invalid: !isValid && isDirty }, } }), }), WithView({ classes, kind: `.${classes.Field}`, ...viewOptions, [Cycle.hasKey]: [ makeLabel({ classes, }), makeInput({ classes, }), makeMessage({ classes, }), ], }), WithValidable({ ...validableOptions, valueKey: 'viewValue', from: (sinks, sources) => (sources.viewValue$ || sources.DOM.events('input') .compose(sources.Time.debounce(100)) .map(path(['target', 'value'])) ).compose(dropRepeats()), }), ) } const makeField = Factory(WithField) module.exports = { default: makeField, makeField, WithField }
import { applyMiddleware, combineReducers, createStore } from 'redux' import profileReducer from './profile-reducer' import usersReducer from './users-reducer' import thunk from 'redux-thunk' import commensReducer from './comments-reduser' let reducers = combineReducers({ commetnsPage: commensReducer, profilePage: profileReducer, usersPage: usersReducer, }) let store = createStore(reducers, applyMiddleware(thunk)) window.store = store export default store
const PORT = 5000; const express = require ('express'); const app = express(); app.listen(PORT, () => { console.info('Express server listening on port ' + PORT) }); app.get('/', (req, res) => { res.send('Express server') });
var BaseComponent = /** @class */ (function (_super) { function BaseComponent(props, context) { var _this = _super.call(this, props, context) || this; return _this; } })(); export { BaseComponent };
import { combineReducers } from 'redux' import {showLoaderReducer, showDropzoneLoaderReducer} from './showLoader' import {notificationsReducer} from './notifications' import {currentUserReducer} from './currentUser' import {artGalleryReducer, updatingArtGalleryReducer} from './artGallery' import {artistGalleryReducer, updatingArtistGalleryReducer} from './artistGallery' import {currentArtReducer, updatingCurrentArtReducer} from './currentArt' import {currentArtistReducer, updatingCurrentArtistReducer} from './currentArtist' import {showArtOverlayReducer, showArtistOverlayReducer, showFullImageOverlayReducer, showDropZoneOverlayReducer, showPdfPreviewOverlayReducer} from './overlay' import {checkCardsReducer} from './floatingBar' import {sourceImageReducer, extraImagesReducer} from './sourceImage' import exportTemplatesReducer from './templates/reducer' import exportFileReducer from './exportFile/reducer' import exportPagesReducer from './exportPages/reducer' import exportCategoriesReducer from './exportCategories/reducer' import exportArtistsReducer from './exportArtists/reducer' import exportArtPiecesReducer from './exportArtPieces/reducer' const reducers = combineReducers({ showLoader: showLoaderReducer, showDropzoneLoader: showDropzoneLoaderReducer, notifications: notificationsReducer, currentUser: currentUserReducer, artGallery: artGalleryReducer, updatingArtGallery: updatingArtGalleryReducer, artistGallery: artistGalleryReducer, updatingArtistGallery: updatingArtistGalleryReducer, currentArt: currentArtReducer, updatingCurrentArt: updatingCurrentArtReducer, currentArtist: currentArtistReducer, updatingCurrentArtist: updatingCurrentArtistReducer, showArtOverlay: showArtOverlayReducer, showArtistOverlay: showArtistOverlayReducer, showFullImageOverlay: showFullImageOverlayReducer, checkCards: checkCardsReducer, sourceImage: sourceImageReducer, showDropZoneOverlay: showDropZoneOverlayReducer, extraImages: extraImagesReducer, exportTemplates: exportTemplatesReducer, exportFile: exportFileReducer, exportPages: exportPagesReducer, exportCategories: exportCategoriesReducer, exportArtists: exportArtistsReducer, exportArtPieces: exportArtPiecesReducer, showPdfPreviewOverlay: showPdfPreviewOverlayReducer }) export default reducers
import React from 'react'; import Wrapper from './Wrapper' import FeatureExcerpt from '../FeatureExcerpt' import { GridTile, GridList } from 'material-ui/GridList'; export default class FeatureList extends React.Component { static propTypes = { features: React.PropTypes.array }; renderFeatures(features) { const gridTileStyle = { padding: 2 }; return ( <GridList cellHeight="auto" padding={30}> {features.map( function(feature, index) { return ( <GridTile key={"feature_" + index} style={gridTileStyle}> <FeatureExcerpt title={feature.title} meta={feature.meta} image={feature.image} /> </GridTile> ); })} </GridList> ); } returnEmptySet() { return (<div>No Features Found</div>) } render() { let content = false; // We need a padding of two so the card border shows. let featuresToShow; if(this.props.filteredFeatures) { featuresToShow = this.props.filteredFeatures; } else { featuresToShow = this.props.features; } if(featuresToShow.length) { content = this.renderFeatures(featuresToShow); } else { content = this.returnEmptySet(); } return ( <Wrapper> {content} </Wrapper> ); } }
import thumbnail from "./images/iuCorps-thumb-optimized.jpg"; import hero from "./images/iuCorps-hero-optimized.jpg"; import postit1 from "./images/iuCorps-postit1.png"; import postit2 from "./images/iuCorps-postit2.png"; import postit3 from "./images/iuCorps-postit3.png"; import siteMap from "./images/iuCorps-sitemap-optimized.jpg"; import pic1 from "./images/slide1-about-optimized.jpg"; import pic2 from "./images//slide2-about-optimized.jpg"; import pic3 from "./images/slide3-what-is-optimized.jpg"; import pic4 from "./images/slide-4what-is-optimized.jpg"; import pic5 from "./images/slide5-getStarted-optimized.jpg"; import pic6 from "./images/slide6-partnerships-optimized.jpg"; import pic7 from "./images/slide7-partnerships-optimized.jpg"; import pic8 from "./images/slide8-support-optimized.jpg"; export default { id: 5, date: "2017-2018", title: "IU Corps", hero, thumbnail, subTitle: "IA / UX", blurb: `A newly formed organization needs a new website to connect the campus and community with service-learning opportunities.`, whiteBoardPics: [postit1, postit2, postit3], siteMap, slideshow: [pic1, pic2, pic3, pic4, pic5, pic6, pic7, pic8] };
import React, { Component } from 'react'; import styles from './createCheckInfo.styles'; import withStyles from "@material-ui/core/styles/withStyles"; import RequestResolver from "../../helpers/RequestResolver/RequestResolver"; import {connect} from "react-redux"; const BlindSignature = require('blind-signatures'); const NodeRSA = require('node-rsa'); class createCheckInfo extends Component { constructor(props) { super(props); this.state = { data: {}, isLoaded: false, noChecker: false, noCheckerInfo: false, FIO: '', success: false, decryptedObject: {}, createdCheck: false, }; this.backend = RequestResolver.getBackend(); } async componentDidMount() { const { id } = this.props.location.aboutProps; const { voterId, i, m, privateKey, vote_private_key_signed, myCheckKey } = this.props; const voteId = localStorage.getItem(`vote-${id}-myId${voterId}`); console.log(voteId); let myVoice = undefined; let checkVoice= undefined; try { const result = await this.backend().get(`election/${id}/vote/`); console.log('+data'); console.log(result.data); console.log('voteId'); console.log(voteId); for (let i = 0; i < result.data.length; i++){ if (result.data[i].id === Number(voteId)){ myVoice = result.data[i]; if (i % 2 === 0){ checkVoice = result.data[i+1]; } else { if (i + 1 <= result.data.length){ checkVoice = result.data[i-1]; } } } } console.log(checkVoice); console.log(myVoice); } catch (error) { this.setState({ isLoaded: false }); console.log(error); } if (!checkVoice){ this.setState({ noChecker: true, }); return; } console.log('i'); console.log(i); const keyPrivate = new NodeRSA(privateKey); const signedIM = keyPrivate.sign(JSON.stringify({i, m}), 'base64', 'utf8'); const checkerPublicKey = checkVoice.check_public_key; const publicKeyCheck = new NodeRSA(checkerPublicKey); const cryptedChecker = publicKeyCheck.encrypt(JSON.stringify({ i, m, signedIM }), 'base64', 'utf8'); const sendData = { v: { vote_id: voteId, vote_private_key_signed: vote_private_key_signed }, check_info_crypted: cryptedChecker}; if (!localStorage.getItem(`vote-${voteId}Check`)){ try { const result = await this.backend({ 'Content-Type': 'application/json' }).post( `election/${id}/check/`, sendData); const CheckSigned = result.data; // получен Check console.log(CheckSigned); localStorage.setItem(`vote-${voteId}Check`, 'было'); } catch (error) { console.log(error); return; } } let checkFoundVoice = undefined; try { const result = await this.backend().get(`election/${id}/check/list/`); for (let i = 0; i < result.data.length; i++){ if (result.data[i].v.id === checkVoice.id){ checkFoundVoice = result.data[i]; } } } catch (error) { this.setState({ isLoaded: false }); console.log(error); } if (!checkFoundVoice){ this.setState({ noCheckerInfo: true, }); return ; } console.log('--'); const checkInfoCrypted = checkFoundVoice.check_info_crypted; const myCheckKeyRsa = new NodeRSA(myCheckKey); const decryptedInfo = myCheckKeyRsa.decrypt(checkInfoCrypted, 'utf8' ); const decryptedObject = JSON.parse(decryptedInfo); console.log(decryptedObject); this.setState({ FIO: decryptedObject.i, success: true, decryptedObject }); } handleApprove = async (status) => { const { id } = this.props.location.aboutProps; const { voterId, privateKey } = this.props; const voteId = localStorage.getItem(`vote-${id}-myId${voterId}`); const keyPrivate = new NodeRSA(privateKey); const signedVoterId = keyPrivate.sign(voterId.toString(), 'base64', 'utf8'); const sendData = { vote_id: voteId.toString(), status, voter_id: voterId.toString(), voter_id_signed: signedVoterId.toString(), }; try { const result = await this.backend({ 'Content-Type': 'application/json' }).post( `election/${id}/vote/check/`, sendData); const sent = result.data; // получен Check console.log(sent); this.props.history.push(`/elections`); } catch (error) { console.log(error); } }; render() { const { noChecker, noCheckerInfo, success, FIO } = this.state; return ( <div> { noChecker && <div>Для вас нет проверяющего, обратитесь к избиркому</div>} { noCheckerInfo && <div>Проверяемый еще не предоставил данные для проверки</div>} { success && <div> Проверьте, что данный пользователь существует в публичном репозитории: <br/> {FIO} <br /> <a onClick={() => this.handleApprove(true)}> Подтвердить существование </a> <br /> <a onClick={() => this.handleApprove(false)}> Не существует </a> </div>} </div> ) } } const mapStateToProps = state => ({ voterId: state.election.voterId, i: state.election.K1.info, m: state.election.mVote.r, privateKey: state.election.ePrivate, vote_private_key_signed: state.election.vote_private_key_signed, myCheckKey: state.election.checkKeys.privateKey, }); export default withStyles(styles)(connect(mapStateToProps)((createCheckInfo)));
import { GET_HOT_CITYS, CHANGE_CITY, FIND_AIR_PORT, EMPTY_AIR_PORT} from '../actions/flightCitys.js' const inint = { tabs: [{ title: '国內' }, { title: '国际·港澳台' }], selectIndex:0, historyDomesticCitys: wx.getStorageSync('historyDomesticCitys')||[], historyInternationalCitys: wx.getStorageSync('historyInternationalCitys') || [], africa:[], america:[], asia:[], europe:[], hot:[], oceania:[] } export function flightCitys(state = inint, action) { let json = action.json switch (action.type) { case GET_HOT_CITYS: return Object.assign({},state,json.result) case CHANGE_CITY: let historyCitys=[] if (json.selectIndex==0){ historyCitys = wx.getStorageSync('historyDomesticCitys') || []; }else{ historyCitys = wx.getStorageSync('historyInternationalCitys') || []; } historyCitys = historyCitys.filter(item=>item.d !== json.d) if (historyCitys.length >= 5) { historyCitys.unshift(json) historyCitys = historyCitys.slice(0, 5) } else { historyCitys.push(json) } if (json.selectIndex == 0) { wx.setStorageSync("historyDomesticCitys", historyCitys) return Object.assign({}, state, { historyDomesticCitys: historyCitys }) }else{ wx.setStorageSync("historyInternationalCitys", historyCitys) return Object.assign({}, state, { historyInternationalCitys: historyCitys }) } default: return state } } export function airPort(state={code:-1,data:[]},action){ let json = action.json switch (action.type) { case FIND_AIR_PORT: json.result.map(item=>{ if(item.s){ let temp=[]; let temc=[]; item.s.map(i=>{ temp.push(i.d) temc.push(i.c) }) item.ds = temp.toString().replace(/,/g,"/") item.cs = temc.toString().replace(/,/g, "/") } }) return { code:0, data:json.result } case EMPTY_AIR_PORT: return { code:-1, data:[] } default: return state } }
var firstNum = ""; var secondNum = ""; var operator = ""; var isFirstNum = function(){ if ("" == operator) return true; return false; } $( ".numbers" ).click(function() { var isFirst = isFirstNum(); if (isFirst) firstNum = firstNum + $(this).html(); else secondNum = secondNum + $(this).html(); console.log(firstNum + " " + operator + " " + secondNum); $("#input").val(firstNum + " " + operator + " " + secondNum); }); $( ".operators" ).click(function() { if (("" != firstNum) && ("" == secondNum)) operator = $(this).html(); console.log(firstNum + " " + operator + " " + secondNum); $("#input").val(firstNum + " " + operator + " " + secondNum); }); $( "#clear" ).click(function() { firstNum = ""; secondNum = ""; operator = ""; $("#input").val(firstNum + " " + operator + " " + secondNum); }); $( "#equal" ).click(function() { var theData = {first: firstNum, second: secondNum, operator: operator}; $.ajax("/calculate", { method: "post", data: theData, success: function(data) { console.log("hi"); console.log(data.result); $('#input').html(data.result); }, error: function() { alert("something is wrong!"); } }); });
export default function nameFormatter(name) { if (name.length < 30) return name; const initial = name.slice(0, 20); const extension = name.split(".")[1]; if (extension) { return initial + "...." + extension; } return initial; }
// Generated by CoffeeScript 1.6.2 /* IDE Definition */ define(['ace/ace'], function(ace) { var Editor; Editor = (function() { function Editor() {} Editor._id = 0; Editor.$editors = []; Editor.$curEditor = null; Editor.$fontSize = parseInt(Settings.fontSize); Editor.increaseFont = function(key, value) { return $('.document').css('fontSize', ++this.$fontSize); }; Editor.decreaseFont = function(key, value) { return $('.document').css('fontSize', --this.$fontSize); }; Editor.add = function(elem, val) { var editor, id; if (val == null) { val = "<h1>Hello World!</h1>"; } id = ++this._id; editor = ace.edit(elem); $(editor.container).addClass('document').css('fontSize', this.$fontSize); this.$curEditor = editor; editor.setTheme(Settings.theme); editor.session.setMode(Settings.mode); editor.setValue(val); this.$editors[id] = editor; return id; }; Editor.remove = function(id) { $(this.editors[id].container).remove(); return delete this.$editors[id]; }; return Editor; })(); return window.IDE = IDE; });
import React from 'react'; import { Text, View, StyleSheet, TouchableOpacity } from 'react-native'; export const Todo = (props) => { return ( <TouchableOpacity activeOpacity={0.5} onLongPress={() => props.removeTodo(props.id)} onPress={() => props.openTodo(props.id)}> <View style={styles.todo}> <View style={styles.textBlock}> <Text style={styles.text}>{props.text}</Text> </View> <View> <Text style={styles.time}>{props.time}</Text> </View> </View> </TouchableOpacity> ) } const styles = StyleSheet.create({ todo: { flexDirection: 'row', alignItems: 'flex-start', padding: 15, borderWidth: 1, borderColor: 'black', borderStyle: 'solid', borderRadius: 10, marginHorizontal: 10, marginBottom: 10, justifyContent: 'space-between' }, textBlock: { textAlign: 'left', width: '85%' }, text: { fontSize: 20, // fontFamily: 'roboto-regular' }, time: { fontSize: 14 } })
import React, { Component } from 'react'; import Destiny from './components/Destiny'; class App extends Component { render() { return ( <div className="Destiny"> <Destiny /> </div> ); } } export default App;
import React from "react"; import { Link } from "react-router-dom"; import classes from "./MainNavigation.module.css"; import hostel_logo from "../images/hostel-logo.png"; import { useStateValue } from "../StateProvider"; import { auth } from "../firebase"; function MainNavigation() { const imageStyles = { backgroundPosition: "center", backgroundSize: "cover", backgroundRepeat: "no-repeat", width: "100px", height: "100px", borderRadius: "50%", }; const [{ user }, dispatch] = useStateValue(); function handleAuthentication() { if (user) { auth.signOut(); } } return ( <div> <header className={classes.header}> <Link to="/"> <div className={classes.logo_image}> <img style={imageStyles} src={hostel_logo} alt="logo" /> </div> </Link> <nav> <ul> <li> <Link to={!user ? "/account" : "/dashboard"}>Dashboard</Link> </li> <li> <Link to={!user ? "/account" : "/students-data"}>Students</Link> </li> <li> <Link to={!user ? "/account" : "/reports"}>Reports</Link> </li> <li> <Link to={!user && "/account"} onClick={handleAuthentication}> <div className={classes.user_message}> <span className={classes.optionLineOne}>{user ? `Hello ${user.email.split("@")[0]}` : "Hello guest"}</span> <span className={classes.optionLineTwo}>{user ? "Sign out" : "Sign in"}</span> </div> </Link> </li> </ul> </nav> </header> </div> ); } export default MainNavigation;
/** * Created by Lucifer on 2016/11/23. */ <? var content = $('#userid').html(); if(content !== "" && title1.value.length !== 0) { $.ajax( { type: "post", async:false, dataType: 'html', url: "http://localhost/EASYBUY/home/user/update", data: "content="+content, success: function(msg) { if(data.info == "成功") { alert("传值成功"); } else { alert("传值失败"); } }, error:function(msg) { alert("失败"); } }); ?>
import React, {useState, useEffect, useContext} from "react"; import { userContext } from "../../utils/Context.js"; import { Link } from "react-router-dom"; import logo from '../../assets/logo.svg' import "./style.css"; function Nav (props) { const [currentUser, setCurrentUser] = useContext(userContext); const [shelvesArray, setShelvesArray] = useState([]); useEffect(() => { setShelvesArray([]); console.log('nav use effect triggered') if (currentUser.shelves){ setShelvesArray(currentUser.shelves); } }, [currentUser]); return ( <nav className='navbar navbar-expand-lg fixed-top'> <div className='container'> <Link to="/"> <img className="navbar-brand" src={logo} alt='Book Journal logo'></img> </Link> <button className="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation"> <span className="fas fa-ellipsis-h"></span> </button> <div className='collapse navbar-collapse justify-content-end' id="navbarNavAltMarkup"> <Link to="/about" className='navlink nav-text'> About </Link> {props.user ? <Link to="/discover" className='navlink nav-text'> Discover </Link> :''} {props.user ? <div className="dropdown"> <div className="navlink nav-text dropdown-button dropdown-toggle" type="button" id="dropdownShelves" data-bs-toggle="dropdown" aria-expanded="false"> My Shelves </div> <ul className="dropdown-menu" aria-labelledby="dropdownShelves"> {shelvesArray ? shelvesArray.map((shelf, index)=> <li key={index}> <Link className="dropdown-item" to={`/shelves/${shelf._id}`}>{shelf.name}</Link> </li> ) : <li>no shelves to show</li>} <li key='addshelf'> <Link className="dropdown-item add-shelf" to='/addshelf'>Add a new shelf</Link> </li> </ul> </div> :''} {props.user ? <button className='navlink nav-text logout-btn' onClick={props.logout}>Log out</button> : <Link to="/login" className='navlink nav-text'> Log In </Link> } {props.user ? '' : <Link to="/signup" className='navlink nav-text'> Sign Up </Link> } </div> </div> </nav> ) } export default Nav;
import { firstLists } from "./firstState"; const list = (state, action) => { switch (action.type) { case "CREATE_LIST": return { title: action.title, }; default: return state; } }; const lists = (state = firstLists, action) => { switch (action.type) { case "CREATE_LIST": if (!state.find(s => s.title === action.title)) { return [...state, list(undefined, action)]; } else return state; case "DELETE_LIST": return state.filter(s => s.title !== action.title); default: return state; } }; export default lists;
const request = require('request'); //const serverUri = "http://rdkucs1.il.nds.com:57778/"; const serverUri = "http://localhost:9090/signaling/1.0/"; function getOffer(connectionId) { console.log("requesting offer for connection id: " + connectionId) request.get(serverUri + 'connections/' + connectionId + '/' + 'offer', (err, res, body) => { if (res.statusCode !== 200 || err) { console.log(err); setTimeout(getOffer, 2000, connectionId); } else { console.log("Got an offer from signaling server"); console.log(JSON.stringify(body)); sendOfferResponse(connectionId); } }); } function sendOfferResponse(connectionId) { const sdp ="v=0\r\no=- 5259690038522163586 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\na=group:BUNDLE 0\r\na=msid-semantic: WMS\r\nm=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\nc=IN IP4 0.0.0.0\r\nb=AS:30\r\na=ice-ufrag:sZ/d\r\na=ice-pwd:Dv79CJ5M1YutC8olkrbL1lMi\r\na=ice-options:trickle\r\na=fingerprint:sha-256 E8:0D:1B:4F:2B:DF:EB:55:A4:E7:8C:8B:9A:51:1A:FA:8A:5A:6C:71:46:22:67:66:42:F6:88:4A:82:A9:A2:E6\r\na=setup:active\r\na=mid:0\r\na=sctp-port:5000\r\na=max-message-size:262144\r\n"; var offer = {type: "answer", sdp: sdp}; request.post(serverUri + 'connections/' + connectionId + '/' + 'answer', { json: true ,body:offer}, (err, res, body) => { if (err) { setTimeout(getConnection, 5000, connectionId);return console.log(err); } else { console.log("start polling for candidate"); } console.log(connectionId); }); } function getConnection() { console.log("Looking for a connection to serve") request.get(serverUri + 'application/queue', (err, res, body) => { if (res.statusCode !== 200 || err) {setTimeout(getConnection, 2000); return console.log(body); } var response = JSON.parse(body) console.log("Got a connection id from the signaling server id: " + response.connectionId); setTimeout(getOffer, 2000, response.connectionId); }); } getConnection();
import express from 'express'; import {render} from 'mjml-react'; import * as email1 from './email'; import * as email2 from './email-second'; const port = 3000; const app = express(); app.get('/2', (req, res) => { const {html} = render(email2.generate(), {validationLevel: 'soft'}); res.send(html); }); app.get('*', (req, res) => { const {html} = render(email1.generate(), {validationLevel: 'soft'}); res.send(html); }); app.listen(port, () => console.log(`Listening on port ${port}!`));
function adduser(){ username=document.getElementById('username').value; localStorage.setItem('username',username); window.location='index2.html'; } const inputs = document.querySelectorAll(".input"); function addcl(){ let parent = this.parentNode.parentNode; parent.classList.add("focus"); } function remcl(){ let parent = this.parentNode.parentNode; if(this.value == ""){ parent.classList.remove("focus"); } } inputs.forEach(input => { input.addEventListener("focus", addcl); input.addEventListener("blur", remcl); });
/** * Created by TULGAA on 4/7/2017. */ angular .module('altairApp') .controller('indexController', [ '$scope','mainService','$filter','$rootScope','$http','$state', function ($scope,mainService,$filter,$rootScope,$http,$state) { $scope.searchForm = {}; $scope.searchInProgress = false; $scope.isSearched = false; $scope.searchResult = []; $scope.repstatuses = [{name:"Зөвшөөрөгдсөн",value:1, class:"uk-badge uk-badge-success"}, {name:"ААН-д засвартай байгаа",value:2, class:"uk-badge uk-badge-danger"}, {name:"АМГТГ-т хянагдаж байгаа",value:7, class:"uk-badge uk-badge-warning"}]; var authenticate = function(credentials, callback) { var headers = credentials ? { authorization : "Basic " + btoa(unescape(encodeURIComponent(credentials.username)) + ":" + unescape(encodeURIComponent(credentials.password))) } : {}; $http.get('user', { headers : headers }).then(function(response) { if (response.data.name) { //$rootScope.user=response.data; $rootScope.authenticated = true; } else { $rootScope.authenticated = false; } callback && callback($rootScope.authenticated); }, function() { $rootScope.authenticated = false; callback && callback(false); }); } //authenticate(); $scope.credentials = {}; $scope.login = function() { $rootScope.loggedout=false; authenticate($scope.credentials, function(authenticated) { if (authenticated) { console.log("Login succeeded"); var promise = $http.get("/defaultSuccess").success( function (data) { var response = data; $state.go(response.url); // $state.go(response); }) $rootScope.authenticated = true; } else { $scope.error="Хэрэглэгчийн нэр эсвэл нууц үг буруу байна!!!"; console.log("Login failed") $rootScope.authenticated = false; } }) }; $scope.setReporttype = function (reporttype) { $scope.searchForm.reporttype = reporttype; } //uk-icon-spinner uk-icon-spin $scope.doSearch = function () { $scope.searchInProgress = true; $scope.isSearched = true; //$rootScope.content_preloader_show(); $scope.searchResult = []; mainService.withdata("POST","/public/search",$scope.searchForm).then(function (data) { $scope.searchResult = data; $scope.searchInProgress = false; //$rootScope.content_preloader_hide(); }); } $scope.getRepStatus = function (id) { return $filter('filter')($scope.repstatuses, {value:id})[0]; } } ]);
import React, { Component } from 'react'; import FormInput from '../../components/FormInput' import Actions from '../../flux/Actions'; class RegisterStepOne extends Component { constructor(props) { super(props); this.continue = this.continue.bind(this); this.setValue = this.setValue.bind(this); this.birthdateChange = this.birthdateChange.bind(this); } componentDidMount() { this.setState({ fechaNacimiento: '' }); } birthdateChange(v, fv) { let object = {}; object['fechaNacimiento'] = v; this.setState(object); } setValue(event) { let object = {}; object[event.target.id] = event.target.value; if (event.target.className.indexOf("upperCase") >= 0) event.target.value = event.target.value.toUpperCase(); this.setState(object); } validate() { let errors = []; if (this.state.privacidad == null || this.state.privacidad != 'on') { errors.push({ field: 'privacidad', message: 'Debe firmar el acuerdo de privacidad' }); } if (this.state.nombre == null || this.state.nombre == '') errors.push({ field: 'nombre', message: 'El Nombre es requerido' }); if (this.state.apellidoPaterno == null || this.state.apellidoPaterno == '') errors.push({ field: 'apellidoPaterno', message: 'El Apellido Paterno es requerido' }); if (this.state.celular == null || this.state.celular == '') errors.push({ field: 'celular', message: 'El Número de celular es requerido' }); if (this.state.email == null || this.state.email == '') errors.push({ field: 'email', message: 'El Correo Electrónico es requerido' }); if (/^\d{10}$/.test(this.state.celular) == false) errors.push({ field: 'celular', message: 'El número de celular debe ser de 10 dígitos' }); if (this.state.celular == null || this.state.celular != this.state.celularConfirmacion) errors.push({ field: 'celular', message: 'Confirmación de Número de celular no coincide' }); if (this.state.email == null || this.state.email != this.state.emailConfirmacion) errors.push({ field: 'email', message: 'Confirmación de Correo Electrónico no coincide' }); if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(this.state.email) == false) errors.push({ field: 'email', message: 'El Correo Electrónico tiene un formato incorrecto' }); if (errors.length > 0) { Actions.error(errors.map((error) => <div>{error.message}</div> )); return false; } return true; } continue() { if (!this.validate()) return; Actions.registerStepOne( { cliente: { numCredencial: this.state.credencial, apellidoPaterno: this.state.apellidoPaterno, apellidoMaterno: this.state.apellidoMaterno, nombres: this.state.nombre, fechaNacimiento: this.state.fechaNacimiento.substring(0, 10), correoElectronico: this.state.email, telefono: { numeroTelefono: this.state.celular }, medioValidacion: 1, datosPrendarios: { numContrato: 0 } } } ); } onlyLetter(event) { var inputValue = event.which; if (!(inputValue >= 65 && inputValue <= 122) && (inputValue != 32 && inputValue != 0) && inputValue != 241 && inputValue != 209 && !(inputValue >= 193 && inputValue <= 250)) { event.preventDefault(); } return String.fromCharCode(inputValue).toUpperCase(); } onlyNumbers(event) { var inputValue = event.which; if (!(inputValue >= 48 && inputValue <= 57)) { event.preventDefault(); } } render() { return ( <div role="tabpanel" className="tab-pane fade in active" id="stp1"> <div className="row"> <div className="col-md-8 col-xs-12 col-md-offset-2"> <div className="bg-info pad-24 shadow">¡Bienvenido!<br />Te recordamos que para registrarte es necesario que tengas a la mano tu Tarjeta Monte. Por favor verifica que toda la información coincida con la de tu boleta de empeño.</div> </div> </div> <div className="row"> <div className="col-md-4"> <FormInput id="nombre" label="Nombre(s)" onChange={this.setValue} onLoad={this.setField} pattern="[A-Za-z]" onKeyPress={this.onlyLetter} upperCase={true} /> </div> <div className="col-md-4"> <FormInput id="apellidoPaterno" label="Apellido Paterno" onChange={this.setValue} pattern="[A-Za-z]" onKeyPress={this.onlyLetter} upperCase={true} /> </div> <div className="col-md-4"> <FormInput id="apellidoMaterno" label="Apellido Materno" onChange={this.setValue} pattern="[A-Za-z]" onKeyPress={this.onlyLetter} upperCase={true} /> </div> </div> <div className="spacer-24"></div> <div className="row"> <div className="col-md-4"> <FormInput id="fechaNacimiento" label="Fecha Nacimiento" onChange={this.birthdateChange} type="calendar" value={this.state ? this.state.fechaNacimiento : ''} /> </div> <div className="col-md-4"> <FormInput id="email" label="Correo Electr&oacute;nico" subLabel="(Este será tu usuario)" type="email" onChange={this.setValue} /> </div> <div className="col-md-4"> <FormInput id="emailConfirmacion" label="Confirma tu correo electr&oacute;nico" onChange={this.setValue} type="email" /> </div> </div> <div className="spacer-24"></div> <div className="row"> <div className="col-md-4"> <FormInput id="credencial" label="No. de Tarjeta Monte" onChange={this.setValue} maxLength="16" onKeyPress={this.onlyNumbers} /> </div> <div className="col-md-4"> </div> <div className="col-md-4"> <div className="spacer-24"></div> <p className="col-011">¿Aún no eres cliente?&nbsp;&nbsp;<a href="http://www.montepiedad.com.mx/portal/preregistro.html" target="_blank" className="cond col-003">PREREGÍSTRATE</a></p> </div> </div> <div className="spacer-24"></div> <div className="row"> <div className="col-md-4"> <FormInput id="celular" label="N&uacute;mero de celular a 10 d&iacute;gitos" onChange={this.setValue} type="format" options={{ numeral: true, numeralIntegerScale: 10, numeralPositiveOnly: true, numeralDecimalMark: '', delimiter: '' }} /> </div> <div className="col-md-4"> <FormInput id="celularConfirmacion" label="Confirma tu n&uacute;mero de celular" onChange={this.setValue} type="format" options={{ numeral: true, numeralIntegerScale: 10, numeralPositiveOnly: true, numeralDecimalMark: '', delimiter: '' }} /> </div> <div className="col-md-4"> <p className="col-005"><i className="material-icons left h0">error_outline</i> Te enviaremos un c&oacute;digo v&iacute;a SMS para verificar tu tel&eacute;fono.</p> </div> </div> <div className="spacer-24"></div> <div className="row"> <div className="col-md-4"> <div className=""> <input type="checkbox" id="privacidad" onChange={this.setValue} /> He le&iacute;do y aceptado el <a className="cond col-003" href="http://www.montepiedad.com.mx/portal/storage/Aviso-de-Privacidad-Jul-MiMonte.pdf" target="_blank">aviso de privacidad</a> </div> </div> <div className="col-md-4 text-center center-block"> <div className="g-recaptcha center-block" data-sitekey="6LdjGiMUAAAAAL4-XZ-ONukUQrA2OWaz3MUHWKcF"></div> </div> <div className="col-md-4 text-right"> <button className="btn btn-danger btn-raised btn-sm" onClick={this.continue}>Verificar Datos</button> </div> </div> </div> ) } } export default RegisterStepOne
/** * Created by py on 02/09/2018. */ module.exports = class ChainController { constructor(blockService) { this.blockService = blockService; } getChain(request, response) { let heightPromise = this.blockService.getBlockHeight(); let validChainPromise = this.blockService.validateChain(); Promise.all([heightPromise, validChainPromise]) .then(values => { response.json({ height: values[0], isValid: values[1] }); }) .catch(err => { response.json({ error: err.message }); }); } };
import React from 'react'; import {Component} from "react"; import user from '../asset/abdo.jpg'; import {NavLink} from "react-router-dom"; import {connect} from 'react-redux'; export class PostDetails extends Component { goToUserArticels = (name) =>{ this.props.history.push({ pathname: '/userArticle',userName: name}) } componentDidMount() { localStorage.setItem("post",this.props.location.post) // console.log(this.props.location.post) // console.log(localStorage.getItem("post")) } render() { return ( <div className="" style={{'width':'60%','margin':'auto','backgroundColor':' ','padding':'2%'}}> <p style={{'fontFamily':'Toke',fontWeight:'bolder',display:'inline',borderBottom:'3px solid gray'}}>{this.props.theCategory}</p> <hr/> <h1>{this.props.location.post.title}</h1> <hr/> <div className="row" style={{backgroundColor:"",padding:'0px'}}> <p style={{ margin: 'auto 10px', fontFamily:'Toke', fontWeight:'bolder' }}> <small> name </small>: {this.props.location.post.source.name.split('.com')} </p> <p style={{ margin: 'auto 10px', fontFamily:'Toke', fontWeight:'bolder' }}><small> Author </small>: {this.props.location.post.author ? this.props.location.post.author :"UnKnow"}</p> </div> <hr/> <div> <img src={this.props.location.post.urlToImage} style={{width:'100%',height:'80vh',borderRadius:'10px'}} alt=".."/> </div> <div style={{marginTop:'30px'}}> <h5 style={{ margin: 'auto', fontFamily:'Toke', fontWeight:'bolder', }}> {this.props.location.post.description} </h5> <hr/> <p style={{ margin: 'auto', fontFamily:'Toke', fontWeight:'bolder', }}>{this.props.location.post.content} </p> </div> <br/><br/><br/><br/><br/> <h5>TAGGED AS</h5> <div className="d-flex"> <div className="p-2"><NavLink className="btn btn-secondary" to={{}} >{this.props.theCategory}</NavLink> </div> </div> <br/><br/><br/><br/><br/> <div className='row' style={{boxShadow:'0px 0px 20px gray',padding:'30px'}}> <img className="" src={user} style={{ "width":'150px', "height":'150px', "borderRadius":'50%' }} alt=".."/> <section style={{width:'50%'}} className="offset-1"> <p style={{ fontFamily:'Toke', }}> Written by</p> <p style={{ fontFamily:'Toke', fontWeight:'bolder', fontSize:'30px' }}> {this.props.location.post.author ? this.props.location.post.author :this.props.location.post.source.name.split('.com') }</p> <p style={{ fontFamily:'Toke', fontWeight:'bold', }}>Deep thinker. Like talking about the world, religion and politics.</p> <button className="btn btn-primary" onClick={()=>this.goToUserArticels(this.props.location.post.source.name.split('.com'))}>View All Artical</button> </section> </div> </div> ); } } const reducerToMap = state =>{ return { theCategory: state.category }; } export default connect(reducerToMap) (PostDetails);
import React from "react"; import "../components/Register.scss"; import PhoneInput from 'react-phone-input-2' const initialState={ username:"", password:"", email:"", emailError:"", user:"", number:"", usernameError:"", passwordError:"", userError:"", numberError:"" } export default class Register extends React.Component { state=initialState handlelogin = () => { this.props.history.push("/Retailerpage"); } validate = () => { let usernameError = ""; let passwordError = ""; let emailError = ""; if (!this.state.username) { usernameError = "Username cannot be blank"; } if (!this.state.password) { passwordError = "Password cannot be blank"; } if (!this.state.user) { usernameError = "User info cannot be blank"; } if (!this.state.email.includes("@")) { emailError = "invalid email"; } if (!this.state.email.includes(".")) { emailError = "invalid email"; } if (passwordError || usernameError) { this.setState({ passwordError, usernameError }); return false; } return true; }; handleChange = event => { const isCheckbox = event.target.type === "checkbox"; this.setState({ [event.target.name]: isCheckbox ? event.target.checked : event.target.value }); }; handleSubmit = event => { event.preventDefault(); const isValid = this.validate(); if (isValid) { console.log(this.state); this.handlelogin(); // clear form this.setState(initialState); } }; render() { return ( <div className="base-container" ref={this.props.containerRef}> <div className="header">Register</div> <form > <div className="content"> <div className="image"> <img src={"https://raw.githubusercontent.com/vash-ashutosh/Project_SmartRetailer/9ea96ce060f477fafb3b297554477ab53eab561e/src/login.svg"} /> </div> <div className="form"> <div className="form-group"> <label htmlFor="username">Username*</label> <input type="text" name="username" required="True" placeholder="username" value={this.state.username} onChange={this.handleChange} /> <div style={{ fontSize: 12, color: "red" }}> {this.state.usernameError} </div> <div className="form-group"> <label htmlFor="email">Email*</label> <input type="text" name="email" required="True" placeholder="username" value={this.state.username} onChange={this.handleChange} /> <div style={{ fontSize: 12, color: "red" }}> {this.state.emailError} </div> </div> </div> <div className="form-group"> <label htmlFor="password">Password*</label> <input type="password" name="password" required="True" placeholder="password" value={this.state.password} onChange={this.handleChange}/> <div style={{ fontSize: 12, color: "red" }}> {this.state.passwordError} </div> </div> <div className="form-group"> {/*<label htmlFor="phone">Phone</label>*/} <PhoneInput name="number" country={''} value={this.state.number} onChange={phone => this.setState({ phone })} required='True' /> <div style={{ fontSize: 12, color: "red" }}> {/*{this.state.numberError}*/} </div> </div> <div className="form-group"> <label htmlFor="user">Retailer or Customer?*</label> <input type="user" name="user" required="True" placeholder="Customer/Retailer" value={this.state.user} onChange={this.handleChange}/> <div style={{ fontSize: 12, color: "red" }}> {this.state.userError} </div> </div> </div> </div> <div className="footer"> <button type="submit" className="btn" style={{color:'#2ECE7E'}} onClick={this.handleSubmit}> Register </button> </div> </form> </div> ); } }
/////////// //Client side of file controll ////////// const express = require('express'); const router = express.Router(); const mongoose = require('mongoose'); const File = require('../models/mfile'); //GET all files on the Client side router.get('/',(req, res, next) => { File.find({'user' : 'Client'}) .select('_id name size type') .exec() .then( docs => { if(docs.length >= 0){ const response = { count: docs.length, files: docs, } res.status(200).json(response); }else{ res.status(204).json({ message: 'No files found' }) } }) .catch(err =>{ console.log(err); res.status(500).json({ error : err }); }); }); //POST file to Client files router.post('/',(req, res, next) => { const file = new File({ _id: new mongoose.Types.ObjectId(), name : req.body.name, size : req.body.size, type : req.body.type, user : 'Client' }) file .save() .then( result => { console.log(result); res.status(201).json({ message : 'File added', AddedFile : { id: result._id, name: result.name, size: result.size, } }); }) .catch(err => { console.log(err) res.status(500).json({ errror : err }) }); }); //GET file by ID router.get('/:fileID', (req, res, next) => { const id = req.params.fileID; File.findById(id) .select('_id name size type') .exec() .then( doc => { console.log(doc); if(doc){ res.status(200).json(doc); }else{ res.status(404).json({ messsage: 'No valid entry for this id'}); } }) .catch(err => { console.log(err) res.status(500).json({error: err}) }); }); //Change a file parameter router.patch('/:fileID', (req, res, next) => { const id =req.params.fileID; const updateOps = {}; for(const ops of req.body){ updateOps[ops.propName] = ops.value; } File.update({_id : id},{$set: updateOps}) .exec() .then(result => { res.status(200).json({ message:'Altered successfully' }); }) .catch(err => { console.log(err); res.status(500).json({ error: err }); }); }); //DELETE a file from Client router.delete('/:fileID', (req, res, next) => { const id =req.params.fileID; File.deleteOne({_id: id}) .exec() .then(result => { console.log() res.status(200).json({ message: 'File deleted' }); }) .catch(err => { console.log(err); res.status(500).json({ error: err }); }); }); module.exports = router;
export const INCREMENT_COUNTER = 'INCREMENT_COUNTER'; export const DECREMENT_COUNTER = 'DECREMENT_COUNTER'; export const DECREMENT_COUNTER_SUCCESS = 'DECREMENT_COUNTER_SUCCESS'; export const ADD_FORM = 'ADD_FORM'; export const REMOVE_FORM = 'REMOVE_FORM'; export const UPDATE_FORM = 'UPDATE_FORM'; export const increment = () => ({ type: INCREMENT_COUNTER, }); export const decrement = () => ({ type: DECREMENT_COUNTER, }); export const decrementSuccess = (count) => ({ type: DECREMENT_COUNTER_SUCCESS, count }); export const incrementAsync = (delay = 1000) => dispatch => { setTimeout(() => { dispatch(increment()); }, delay); }; export const addForm = () => ({ type: ADD_FORM }) export const removeForm = (key) => ({ type: REMOVE_FORM, key }) export const updateForm = (key, value) => ({ type: UPDATE_FORM, key, value })
import { connect } from 'react-redux'; import EmailAccept from './EmailAccept'; import {EnhanceLoading} from '../../../components/Enhance'; import {buildOrderPageState} from '../../../common/orderAdapter'; import {postOption,fetchJson, showError} from '../../../common/common'; import {dealActions} from '../../../common/check'; import {Action} from '../../../action-reducer/action'; import {getPathValue} from '../../../action-reducer/helper'; import {fetchDictionary2, setDictionary} from '../../../common/dictionary'; import {search} from '../../../common/search'; const STATE_PATH = ['config', 'emailAccept']; const action = new Action(STATE_PATH); const URL_CONFIG = '/api/config/emailAccept/config'; const URL_EMAIL_LIST = '/api/config/emailAccept/email_list'; const URL_ACCEPT_LIST = '/api/config/emailAccept/accept_list'; const URL_LOG_LIST = '/api/config/emailAccept/log_list'; const getSelfState = (rootState) => { return getPathValue(rootState, STATE_PATH); }; const buildState = (config, data) => { const tabs = [ {key: 'email', title: config.emailBtn, close: false}, {key: 'accept', title: config.acceptBtn, close: false}, {key: 'log', title: config.logBtn, close: false} ]; return { tabs, ...config, activeKey: 'email', email: buildOrderPageState(data, config.EmailConfigurationConfig.index, {editConfig: config.EmailConfigurationConfig.edit}), accept: buildOrderPageState({}, config.EmailAcceptConfigurationConfig.index, {editConfig: config.EmailAcceptConfigurationConfig.edit}), log: buildOrderPageState({}, config.AcceptLogConfig.index, {}) }; }; const initActionCreator = () => async (dispatch) => { dispatch(action.assign({status: 'loading'})); let res, data, config; config = await fetchJson(URL_CONFIG); config.EmailConfigurationConfig.index.buttons = dealActions(config.EmailConfigurationConfig.index.buttons, 'emailAccept'); config.EmailAcceptConfigurationConfig.index.buttons = dealActions(config.EmailAcceptConfigurationConfig.index.buttons, 'emailAccept'); config.AcceptLogConfig.index.buttons = dealActions(config.AcceptLogConfig.index.buttons, 'emailAccept'); data = await fetchDictionary2(config.EmailConfigurationConfig.index.tableCols); if (data.returnCode !== 0) { showError(data.returnMsg); dispatch(action.assign({status: 'retry'})); return; } const dictionary = await fetchDictionary2(config.EmailAcceptConfigurationConfig.index.tableCols); if (dictionary.returnCode !== 0) { showError(dictionary.returnMsg); dispatch(action.assign({status: 'retry'})); return; } setDictionary(config.EmailConfigurationConfig.index.tableCols, data.result); setDictionary(config.EmailConfigurationConfig.edit.controls, data.result); setDictionary(config.EmailConfigurationConfig.edit.editControls, data.result); setDictionary(config.EmailAcceptConfigurationConfig.index.tableCols, dictionary.result); setDictionary(config.EmailAcceptConfigurationConfig.edit.tableCols, dictionary.result); setDictionary(config.EmailAcceptConfigurationConfig.edit.editControls, dictionary.result); setDictionary(config.EmailAcceptConfigurationConfig.edit.editControls1, dictionary.result); res = await fetchJson(URL_EMAIL_LIST, postOption({itemFrom:0, itemTo:10})); if (res.returnCode !== 0) { dispatch(action.assign({status: 'retry'})); return; } data = res.result; dispatch(action.create(Object.assign(buildState(config, data), {status: 'page'}))); }; const tabChangeActionCreator = (key) => async (dispatch,getState) => { let res, tableItems, maxRecords; if (key === 'email') { res = await search(URL_EMAIL_LIST, 0, 10, {}); tableItems = res.result.data; maxRecords = res.result.returnTotalItem; dispatch(action.assign({tableItems, maxRecords}, 'email')); } else if (key === 'accept') { res = await search(URL_ACCEPT_LIST, 0, 10, {}); tableItems = res.result.data; maxRecords = res.result.returnTotalItem; dispatch(action.assign({tableItems, maxRecords}, 'accept')); }else if (key === 'log') { res = await search(URL_LOG_LIST, 0, 10, {}); tableItems = res.result.data; maxRecords = res.result.returnTotalItem; dispatch(action.assign({tableItems, maxRecords}, 'log')); } dispatch(action.assign({activeKey: key})); }; const mapStateToProps = (state) => { return getSelfState(state); }; const actionCreators = { onInit: initActionCreator, onTabChange: tabChangeActionCreator }; const EmailAcceptContainer = connect(mapStateToProps, actionCreators)(EnhanceLoading(EmailAccept)); export default EmailAcceptContainer;
class CountriesTable { constructor(countries) { this.table = this.getCountriesAsTable(countries); } getTable() { return this.table; } getCountriesAsTable(countries) { var self = this; var table = $("<table></table>"); countries.forEach(function(country) { table.append(self.getCountryAsRow(country)); }); return table; } getCountryAsRow(country) { var row = $("<tr></tr>"); row.append($("<td>" + this.getImageHTML(country.flag, 300, 200) + "</td>")); var statsCell = $("<td></td>"); statsCell.append(this._getCountryAsRow_getStats(country)); row.append(statsCell); return row; } _getCountryAsRow_getStats(country) { var table = $("<table></table>"); table.append(this.getNameRow(country)); table.append(this.getAlphaCode2Row(country)); table.append(this.getAlphaCode3Row(country)); table.append(this.getRegionRow(country)); table.append(this.getSubRegionRow(country)); table.append(this.getLanguagesRow(country)); return table; } getNameRow(country) { var row = $("<tr></tr>"); row.append($("<td colspan='2'><h3>" + country.name + "</b></h3>")); return row; } getAlphaCode2Row(country) { var row = $("<tr></tr>"); row.append($("<td><i>" + "Alpha Code 2:" + "</i></td>")); row.append($("<td>" + country.alpha2Code + "</td>")); return row; } getAlphaCode3Row(country) { var row = $("<tr></tr>"); row.append($("<td><i>" + "Alpha Code 3:" + "</i></td>")); row.append($("<td>" + country.alpha3Code + "</td>")); return row; } getRegionRow(country) { var row = $("<tr></tr>"); row.append($("<td><i>" + "Region:" + "</i></td>")); row.append($("<td>" + country.region + "</td>")); return row; } getSubRegionRow(country) { var row = $("<tr></tr>"); row.append($("<td><i>" + "Subregion:" + "</i></td>")); row.append($("<td>" + country.subregion + "</td>")); return row; } getLanguagesRow(country) { var languagesString = country.languages.pop().name; country.languages.forEach(function (language) { languagesString += ", " + language.name; }); var row = $("<tr></tr>"); row.append($("<td><i>" + "Language(s):" + "</i></td>")); row.append($("<td>" + languagesString + "</td>")); return row; } getImageHTML(url, width, height) { return '<img src="' + url +'" alt="Flag" style="width:' + width +'px;height:' + height + 'px;">'; } }
const micro = require('micro') let router, port, server let prod = process.env.NODE_ENV === 'production' | process.env.NODE_ENV === 'PRODUCTION' const start = () => { if(server && prod) return false if(server && !prod) server.close() let index = require('./index.js')(start, stop) index.start() server = micro(index.router) server.listen(index.port, () => { console.log('Server started on port ' + index.port) }) } const stop = () => { if(prod) return false if(server) server.close() console.log('Server stopped') process.exit(0) } start()
import { css } from 'emotion'; const sliderWrapper = css` position: relative; width: calc(100vw - 18%); margin: 100px auto; overflow: hidden; padding: 40px 0; `; export default sliderWrapper;
import BaseModel from '../../../base/model/base'; export default class ForumoverviewModel extends BaseModel { }
var functions________________c________8js____8js__8js_8js = [ [ "functions________c____8js__8js_8js", "functions________________c________8js____8js__8js_8js.html#aca17726ead58ab78f0d294f74ede14db", null ] ];
import { Theme } from "../../model/theme" // pages/theme/index.js Page({ /** * 页面的初始数据 */ data: { _theme:null, recommend:null, _tName:"", rows:3, showLoading:true, showtitle:true }, /** * 生命周期函数--监听页面加载 */ onLoad: async function (options) { const tName = options.tName const _theme = await Theme.getThemeSpuByName(tName) const recommend = await Theme.getThemeSpuByName("t-6") const rows = _theme.spu_list.length wx.lin.renderWaterFlow(recommend.spu_list, true) this.setData({ _theme, recommend, _tName:_theme.tpl_name, rows, showLoading:false }) console.log(this.data._tName) }, /** * 生命周期函数--监听页面初次渲染完成 */ onReady: function () { }, /** * 生命周期函数--监听页面显示 */ onShow: function () { }, /** * 生命周期函数--监听页面隐藏 */ onHide: function () { }, /** * 生命周期函数--监听页面卸载 */ onUnload: function () { }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () { }, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () { }, /** * 用户点击右上角分享 */ onShareAppMessage: function () { } })
/** * 全局filters, 定义通用处理函数 */ export const str = val => { return val + parseInt(Date.parse(new Date()) / 1000); //当前时间戳 }