text
stringlengths
7
3.69M
import React from 'react'; // import { Header } from '../styles/app.styles'; import { HeaderContainer } from '../styles/app.styles'; const Header = (props) => { return ( <HeaderContainer>{props.text}</HeaderContainer> ) } export default Header;
import React, { Component, PropTypes } from 'react'; import styled from 'styled-components'; import {MLIcon} from '../index'; import Colors from '../colors.js'; const Button = styled.div` position: relative; display: inline-block; font-family: 'Source Sans Pro',sans-serif; font-size: 15px; line-height: 33px; color: ${props => props.primary ? Colors.pure_white : Colors.aqua}; height: 34px; padding: ${props => props.icon ? '0 15px 0 12px' : '0 15px'}; margin: 5px; background-color: ${props => props.primary ? Colors.aqua : 'transparent'} border: ${props => props.primary ? 'none' : '1px solid ' + Colors.aqua }; border-radius: 3px; text-decoration: none; cursor: pointer; &:hover { opacity: 0.8; } &:disabled { cursor: default } &:focus { outline: none; box-shadow: 0 0 6px rgba(0,117,142,1); } `; const Title = styled.span` line-height: 30px; margin-left: ${props => props.icon ? '8px' : '0'}; `; const Icon = styled.span` position: relative; top: 4px; vertical-align: middle; color: ${props => props.primary ? Colors.pure_white : Colors.aqua}; `; // const SpecialButton = styled.button` // ` // const MLButton = ({ title, btnClass, btnType, onClick, icon, style }) => { class MLButton extends Component { render() { const { onClick, icon, title, primary } = this.props; return ( <Button { ...this.props } onClick={ onClick } > { icon ? <Icon> <MLIcon title={ title } type={ icon } fill={ primary ? Colors.pure_white : Colors.aqua } /> </Icon> : null} <Title { ...this.props }>{ title }</Title> </Button> ); } } MLButton.defaultProps = { btnClass: 'default', btnType: '' }; MLButton.propTypes = { title: PropTypes.string.isRequired, btnClass: PropTypes.string, btnType: PropTypes.string, onClick: PropTypes.func, primary: PropTypes.bool, icon: PropTypes.string }; export default MLButton;
define(['SocialNetView','text!templates/menu/contacts.html'], function(SocialNetView,ContactsMenuTemplate) { var contactMenuView = SocialNetView.extend({ el: $('#Qcontacts'), initialize: function(options) { }, render: function() { this.$el.html(_.template(ContactsMenuTemplate,{model:this.model})); } }); return contactMenuView; });
export function initTexture(gl) { const texture = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, texture); const level = 0; const internalFormat = gl.RGBA; const width = 1; const height = 1; const border = 0; const srcFormat = gl.RGBA; const srcType = gl.UNSIGNED_BYTE; const pixel = new Uint8Array([0, 0, 255, 255]); gl.texImage2D(gl.TEXTURE_2D, level, internalFormat, width, height, border, srcFormat, srcType, pixel); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); return texture; } export function updateTexture(gl, texture, video) { const level = 0; const internalFormat = gl.RGBA; const srcFormat = gl.RGBA; const srcType = gl.UNSIGNED_BYTE; gl.bindTexture(gl.TEXTURE_2D, texture); gl.texImage2D(gl.TEXTURE_2D, level, internalFormat, srcFormat, srcType, video); }
'use strict'; import FamousEngine from 'famous-creative/scaffolding/FamousEngine'; FamousEngine.init(); require('babelify/polyfill'); require('./app/index');
import React from 'react' import { Modal, Header, Body, Footer } from 'bypass/ui/modal' import { Button } from 'bypass/ui/button' import { Text } from 'bypass/ui/text' const CreateWallet = ({ onCreate, onClose }) => ( <Modal onClose={onClose}> <Header> <Text size={19}> {__i18n('LANG.SERVICE.LOAD_OVER')} Bitcoin </Text> </Header> <Body alignCenter> <div style={{ padding: '0 20px' }}> {__i18n('BILLING.BTC.CREATE_WALLET')} </div> </Body> <Footer alignCenter> <Button onClick={onCreate}> {__i18n('LANG.SERVICE.CREATE_PURSE')} </Button> </Footer> </Modal> ) export default CreateWallet
const app = getApp(); Component({ data: { selected: 0, color: "#7A7E83", selectedColor: "#BAEFFF", list: [{ pagePath: "/pages/index/index", iconPath: "../static/images/home.png", selectedIconPath: "../static/images/home_actived.png", text: "首页", isSpecial: false }, { pagePath: "/pages/dynamic/dynamic", iconPath: "../static/images/dynamic.png", selectedIconPath: "../static/images/dynamic_actived.png", text: "动态", isSpecial: false }, { pagePath: "/pages/upload/upload", iconPath: "../static/images/add.png", text: "上传", isSpecial: true }, { pagePath: "/pages/message/message", iconPath: "../static/images/message.png", selectedIconPath: "../static/images/message_actived.png", text: "消息", isSpecial: false }, { pagePath: "/pages/mine/mine", iconPath: "../static/images/mine.png", selectedIconPath: "../static/images/mine_actived.png", text: "我的", isSpecial: false }], }, attached() {}, methods: { switchTab(e) { const dataset = e.currentTarget.dataset const path = dataset.path const index = dataset.index let currentPage = getCurrentPages() // 如果点击当前页面,则返回 if ('/' + currentPage[0].route === path) { console.log('-----------------'); return } //如果是特殊跳转界面 if (this.data.list[index].isSpecial) { wx.navigateTo({ url: path }) } else { //正常的tabbar切换界面 //使用switch会导致顶部自定义失效 this.setData({ selected: index }) wx.switchTab({ url: path }) } } } })
import React from 'react' import { Link, navigate } from '@reach/router' import { Grid, Button, Modal, Icon, Header, Label } from 'semantic-ui-react' import './AdminInspirationCard.css' const buttonStyle = { width: '145px', margin: '3px' } const AdminInspirationCard = ({ inspiration, deleteInspiration, remove, selectedId }) => <Grid.Column mobile={16} tablet={8} computer={4} className="inspiration" style={{ backgroundColor: `${inspiration.draftColor}` }}> {inspiration.isDraft ? <Label circular color='yellow'><Icon name='wrench' /></Label> : ''} {inspiration.publicationDate ? <Label circular color='olive'><Icon name='paper plane' /></Label> : ''} <Link to={`/inspirations/form/${inspiration.id}`}> <h2>{inspiration.draftTitle}</h2> <p>{inspiration.draftSmallDescription}</p> </Link> <div className="Btn"> <Link to={`/inspirations/form/${inspiration.id}`} > <Button color='violet' style={buttonStyle}> <Icon name='edit' />Éditer </Button> </Link><br /> <Link to={`/inspirations/${inspiration.id}`} > <Button color='blue' style={buttonStyle}> <Icon name='eye' />Aperçu </Button> </Link><br /> <React.Fragment> <Link to={`${inspiration.id}/remove`}> <Button color='red' style={buttonStyle}> <Icon name='archive' />SUPPRIMER </Button> </Link> <Modal open={remove && inspiration.id === selectedId} basic size='small' onClose={() => navigate('/my-inspirations')}> <Header icon='archive' content={`Es-tu sure de vouloir supprimer cette inspiration "${inspiration.title}" ?`} /> <Modal.Content> <p>Pour supprimer l'inspiration, clique sur 'Confirmer'. Sinon, clique sur 'Annuler'.</p> </Modal.Content> <Modal.Actions> <Button basic inverted onClick={() => navigate('/my-inspirations')}> <Icon name='remove' /> Annuler </Button> <Button inverted color='red' onClick={() => { deleteInspiration(inspiration) navigate('/my-inspirations') }}> <Icon name='checkmark' /> Confirmer </Button> </Modal.Actions> </Modal> </React.Fragment> </div> </Grid.Column> export default AdminInspirationCard
$(document).ready(function() {var formatter = new CucumberHTML.DOMFormatter($('.cucumber-report'));formatter.uri("src/test/resources/com/selenium/rediff/login.feature"); formatter.feature({ "name": "Logging in to Rediff Money", "description": "", "keyword": "Feature", "tags": [ { "name": "@Login" } ] }); formatter.scenarioOutline({ "name": "Logging into Rediff", "description": "", "keyword": "Scenario Outline", "tags": [ { "name": "@Login" } ] }); formatter.step({ "name": "I open \u003cBrowser\u003e", "keyword": "Given " }); formatter.step({ "name": "I go to loginURL", "keyword": "And " }); formatter.step({ "name": "I Login inside application", "keyword": "And ", "rows": [ { "cells": [ "thevarselvakumar@gmail.com", "Winter123!" ] } ] }); formatter.step({ "name": "Login should be \u003cResult\u003e", "keyword": "Then " }); formatter.examples({ "name": "", "description": "", "keyword": "Examples", "rows": [ { "cells": [ "Browser", "Result" ] }, { "cells": [ "chrome", "success" ] }, { "cells": [ "chrome", "success" ] } ] }); formatter.scenario({ "name": "Logging into Rediff", "description": "", "keyword": "Scenario Outline", "tags": [ { "name": "@Login" }, { "name": "@Login" } ] }); formatter.before({ "status": "passed" }); formatter.step({ "name": "I open chrome", "keyword": "Given " }); formatter.match({ "location": "GenericSteps.openBrowser(String)" }); formatter.result({ "status": "passed" }); formatter.step({ "name": "I go to loginURL", "keyword": "And " }); formatter.match({ "location": "GenericSteps.navigate(String)" }); formatter.result({ "status": "passed" }); formatter.step({ "name": "I Login inside application", "rows": [ { "cells": [ "thevarselvakumar@gmail.com", "Winter123!" ] } ], "keyword": "And " }); formatter.match({ "location": "ApplicationSteps.login(String\u003e)" }); formatter.result({ "status": "passed" }); formatter.step({ "name": "Login should be success", "keyword": "Then " }); formatter.match({ "location": "ApplicationSteps.validateLogin(String)" }); formatter.result({ "status": "passed" }); formatter.after({ "status": "passed" }); formatter.scenario({ "name": "Logging into Rediff", "description": "", "keyword": "Scenario Outline", "tags": [ { "name": "@Login" }, { "name": "@Login" } ] }); formatter.before({ "status": "passed" }); formatter.step({ "name": "I open chrome", "keyword": "Given " }); formatter.match({ "location": "GenericSteps.openBrowser(String)" }); formatter.result({ "status": "passed" }); formatter.step({ "name": "I go to loginURL", "keyword": "And " }); formatter.match({ "location": "GenericSteps.navigate(String)" }); formatter.result({ "status": "passed" }); formatter.step({ "name": "I Login inside application", "rows": [ { "cells": [ "thevarselvakumar@gmail.com", "Winter123!" ] } ], "keyword": "And " }); formatter.match({ "location": "ApplicationSteps.login(String\u003e)" }); formatter.result({ "status": "passed" }); formatter.step({ "name": "Login should be success", "keyword": "Then " }); formatter.match({ "location": "ApplicationSteps.validateLogin(String)" }); formatter.result({ "status": "passed" }); formatter.after({ "status": "passed" }); });
App.TooltopController = (function () { return { init: function () { var that = this; $(document).on('changeDevice', function (event, data) { switch (data.device) { case 'mobile': break; case 'tablet': break; default: // desktop functions } }); this.showFiltersTooltip(); }, showFiltersTooltip: function () { $('body').append('<span class="js-g-tooltip"></span>'); $('.js-g-tooltip').css({ 'display': 'none', 'position': 'absolute' }); $('.b-filters__block label').on('mousemove',function (e) { var hovertext; if($(this).hasClass('js-b-filters-not-active')){ hovertext = $(this).parents('ul').attr('data-tooltip'); } else if($(this).is('.b-filters__color-item-label') && !$('html').is('.is-mobile')){ hovertext = $(this).attr('data-tooltip'); } else{ return; } $('.js-g-tooltip') .text(hovertext) .stop(true, true) .fadeIn(50) .css({ 'left': e.pageX + 30, 'top': e.pageY - 15 }); }).on('mouseout',function () { $('.js-g-tooltip').fadeOut(50); }); } } }()); App.TooltopController.init();
class NomSlider extends HTMLElement { constructor() { super(); this.attachShadow({mode: 'open'}); this.mapToQuerySelector="notyet"; this.init(); } connectedCallback(){ } init() { const input = document.createElement('INPUT'); input.type = 'range'; input.value = .5; input.min =0; input.max = 1; input.step = .01; let label=document.createElement('label') label.innerHTML="lfo"; label.className="label"; let val=document.createElement('span') val.innerHTML="0 Hz"; val.className="rangeDisplay"; /* The "input" event is sent by a slider (i.e. input DOM element) that is a child of this NomSlider. Reach down into children to grab value of the slider (1) and set the value display of this slider to reflect current value. Should be via inputToValue(). Then send a custom event to the Mapper informing the mapper that this slider is changing. This is done by passing a custom object as the 'detail' item. The detail item is part of the DOM specification and is how NOM (node object model) objects are passed between componentents. */ this.addEventListener("input", (evt) => { // self reflection this.shadowRoot.children[2].innerHTML= this.shadowRoot.children[1].value; // mapToQuerySelector was set when another slider was created. // This is what we want mapper to call in the mapper listener. document.querySelector('#nom-mapper') .dispatchEvent( new CustomEvent('mapper', { detail: { id:evt.timeStamp, type:"mapValueToQuerySelector", data:this.value, mapToQuerySelector:this.mapToQuerySelector } })); }); this.shadowRoot.appendChild(label); // children[0] this.shadowRoot.appendChild(input); // children[1] this.shadowRoot.appendChild(val); // children[2] this.addEventListener( "slider.set", function() { this.shadowRoot[1].value=evt.detail.value; }); } set value(v) { this.shadowRoot.children[2].innerHTML=v }; set id(v) { this.setAttribute('id', v);} // set mapToQuerySelector(str) { // this.mapToQuerySelector=str; // } get value() { return this.shadowRoot.children[1].value; } set label(v) { this.shadowRoot.children[0].innerHTML=v; } } customElements.define('nom-slider', NomSlider);
/** * Created by wen on 2016/8/17. */ import React from 'react'; import search from './search'; import searchResult from './searchResult'; export default { path: '/search', children: [ search, searchResult ], async action({next}) { return await next(); } };
$(function() { $('#popup-open-btn').click(function () { $('body').addClass('popup-show'); }); $('#popup-video-open-btn').click(function () { $('body').addClass('popup-show'); $('.video-wrap .video-box').append('<iframe frameborder="0" allowfullscreen src="https://www.youtube.com/embed/UQ4ytWPE-HY?rel=0&autoplay=1&loop=1"></iframe>') }); $('.close-btn, .popup-close-btn').click(function () { $('body').removeClass('popup-show'); $('body').removeClass('popup-show-buy'); $('body').removeClass('popup-show-size'); $('body').removeClass('popup-shopping-userdata-show'); $('body').removeClass('popup-del-show'); $('body').removeClass('shopping-inventory-show'); }); $('.popup-bg').click(function () { $('body').removeClass('popup-show'); $('body').removeClass('popup-show-buy'); $('body').removeClass('popup-show-size'); $('body').removeClass('popup-shopping-userdata-show'); $('body').removeClass('popup-del-show'); $('body').removeClass('shopping-inventory-show'); }); // video $('.video-wrap .close-btn').click(function () { $('.video-wrap .video-box iframe').remove(); }); $('.video-wrap .popup-bg').click(function () { $('.video-wrap .video-box iframe').remove(); }); $('.btn-buy').click(function () { $('body').addClass('popup-show-buy'); }); // 尺寸表 $('.size-chart').click(function () { $('body').addClass('popup-show-size'); }); //product-peview-terms $('#popup-open-btn-guidelines').click(function () { $('body').addClass('popup-show'); $('.popup-wrap').show(); $('.popup-wrap.terms').hide(); }); $('#popup-open-btn-terms').click(function () { $('body').addClass('popup-show'); $('.popup-wrap').show(); $('.popup-wrap.guidelines').hide(); }); $('.popup-wrap.terms .popup-bg, .popup-wrap.guidelines .popup-bg').click(function () { $('body').removeClass('popup-show'); $('.popup-wrap').hide(); }); $('.popup-wrap.terms .close-btn, .popup-wrap.guidelines .close-btn').click(function () { $('body').removeClass('popup-show'); $('.popup-wrap').hide(); }); $('.popup-header.guidelines, .popup-main.guidelines').hide(); $('.btn-guidelines').click(function () { $('.popup-header.guidelines, .popup-main.guidelines').show(); }); //shopping $('.pdt-change-btn .pdt-del').click(function () { $('body').addClass('popup-del-show'); }); $('.shopping-inventory .popup-close-btn').click(function () { $('body').removeClass('shopping-inventory-show'); }); // shopping-userdata $('.popup-shopping-userdata').click(function () { $('body').addClass('popup-shopping-userdata-show'); }); $('.shopping-userdata .close-btn').click(function () { $('body').removeClass('popup-shopping-userdata-show'); }); // member-invoice 發票索取 $('.take-invoice').click(function () { $('body').addClass('popup-show'); $('.take-invoice-popup').show(); }); $('.close-btn, .popup-bg, .cancel-btn').click(function () { $('body').removeClass('popup-show'); // $('.popup-wrap').hide(); }); });
const fs=require('fs'); var dateFormat = require('dateformat'); var now = new Date(); const filelog=__dirname+"\\log.txt" var writeLog= async (data) => { var logTxt="["+dateFormat(now)+"] "+data; await fs.appendFileSync(filelog,logTxt+"\n"); return ; } module.exports.writeLog=writeLog;
'use strict'; // supplanting the mds_admin collection var Proprietor = { tableName: 'mds_proprietors', attributes: { email_address: { type: 'string' }, password: { type: 'string' }, is_proprietor: { type: 'boolean' }, proprietor: { type: 'json' }, last_login: { type: 'datetime' }, created_at: { type: 'datetime' } } } module.exports = Proprietor;
/** * Created by Administrator on 2016/8/31 0031. */ $(function () { $('#drag').draggable({ // axis:'y', containment:'parent', cursor:'wait', cursorAt:{top:100,left:100}, // delay:'1000', // distance:'100', // revert:true, // revertDuration:50, grid:[50,50], handle:'a', opacity:'0.6', helper:function (event) { return $('<div>重新定义当前div</div>') }, start:function (event,ui) { // console.log('start dragging'); // $(this).css('opacity','0.8'); },drag:function () { // console.log('dragging'); },stop:function () { // console.log('dragging over'); // $(this).css('opacity','1'); }}); $('#Accordion').accordion({ collapsible:true, icons:{ 'header':'ui-icon-triangle-1-w', 'activeHeader':'ui-icon-clock' } }); })
import styled from "styled-components"; import { theme, mq } from "constants/theme"; const { offWhite } = theme.colors; const Main = styled.main` margin-left: 2rem; margin-right: 2rem; display: flex; align-items: center; justify-content: center; min-height: calc(100% - 119px); min-height: -o-calc(100% - 119px); /* opera */ min-height: -webkit-calc(100% - 119px); /* google, safari */ min-height: -moz-calc(100% - 119px); /* firefox */ @media screen and (min-width: ${mq.tablet.wide.minWidth}) { background-color: ${offWhite}; min-height: calc(100%-160px); min-height: -o-calc(100% - 160px); /* opera */ min-height: -webkit-calc(100% - 160px); /* google, safari */ min-height: -moz-calc(100% - 160px); /* firefox */ } `; export default Main;
import React, {Component, PropTypes} from 'react'; import Helmet from 'react-helmet'; import {connect} from 'react-redux'; import * as productActions from 'redux/modules/products'; import {isLoaded, load as loadproducts} from 'redux/modules/products'; import {initializeWithKey} from 'redux-form'; import { asyncConnect } from 'redux-async-connect'; @asyncConnect([{ deferred: true, promise: ({store: {dispatch, getState}}) => { if (!isLoaded(getState())) { return dispatch(loadproducts()); } } }]) @connect( state => ({ widgets: state.widgets.data, editing: state.widgets.editing, error: state.widgets.error, loading: state.widgets.loading }), {...productActions, initializeWithKey }) export default class ProductsHeader extends Component { static propTypes = { widgets: PropTypes.array, error: PropTypes.string, loading: PropTypes.bool, initializeWithKey: PropTypes.func.isRequired, editing: PropTypes.object.isRequired, load: PropTypes.func.isRequired, editStart: PropTypes.func.isRequired }; render() { return( <div> <div className="header"> <div className="top-header"> <div className="container"> <div className="header-left"> <p>Take and Extra 20% OFF with order upto $99</p> </div> <div className="login-section"> <ul> <li><a href="login.html">Login</a> </li> | <li><a href="register.html">Register</a> </li> </ul> </div> <div className="search-box"> <div id="sb-search" className="sb-search"> <form> <input className="sb-search-input" placeholder="Enter your search term..." type="search" name="search" id="search" /> <input className="sb-search-submit" type="submit" value="" /> <span className="sb-icon-search"> </span> </form> </div> </div> <script src="js/classie.js"></script> <script src="js/uisearch.js"></script> <script> new UISearch( document.getElementById( 'sb-search' ) ); </script> <div className="clearfix"></div> </div> </div> <div className="bottom-header"> <div className="container"> <div className="logo"> <a href="index.html"><h1>sporty</h1></a> </div> <div className="header_bottom_right"> <div className="h_menu4"> <a className="toggleMenu" href="">Menu</a> <ul className="nav"> <li className="active"><a href="index.html">HOME</a></li> <li><a href="products.html" className="root">FOOTBALL</a> <ul> <li><a href="products.html">Accessories</a></li> <li><a href="products.html">Footwear</a></li> <li><a href="products.html">t-shirts</a></li> <li><a href="products.html">sporty dresses</a></li> <li><a href="products.html">balls</a></li> <li><a href="products.html">sales</a></li> </ul> </li> <li><a href="bikes.html">BIKES</a> <ul> <li><a href="bikes.html">Accessories</a></li> <li><a href="bikes.html">helmets</a></li> <li><a href="bikes.html">Footwear</a></li> <li><a href="bikes.html">spets</a></li> <li><a href="bikes.html">arms</a></li> <li><a href="bikes.html">sales</a></li> </ul> </li> <li><a href="products.html">GOLF</a> <ul> <li><a href="products.html">Accessories</a></li> <li><a href="products.html">Footwear</a></li> <li><a href="products.html">Apparel</a></li> </ul> </li> <li><a href="contact.html">CONTACT</a></li> </ul> <script type="text/javascript" src="js/nav.js"></script> </div> <div className="clearfix"></div> </div> </div> </div> </div> </div>); } }
// write a functio called minSubarrayLen which accepts two parameters - an array of positive integers // and a positive integer. This function should return the minimal length of a contigous sibarray of which // the sum is greater than or equal to the integer passed to the function. If, there isn't one, return 0 instead. //minSubarrayLen([2,3,1,2,4,3], 7) // 2 -> because [4,3] is the smallest subarray //minSubarrayLen([2,1,6,5,4], 9) // 2 -> because [5,4] is the smallest subarray //minSubarraLen([3,1,7,11,2,9,8,21,62,33,19], 52) // 1 -> because [62] is greater than 52 //minSubarrayLen([1,4,16,22,5,7,8,9,10], 39) // 3 //minSubarrayLen([1,4,16,22,5,7,8,9,10], 55) // 5 //minSubarrayLen([4,3,3,8,1,2,3], 11) // 2 //minSubarrayLen([1,4,16,22,5,7,8,9,10], 95) //0
Ext.require('Ext.panel.Panel'); Ext.require('Ext.Component'); Ext.define ( 'FPT.view.helper.Step' , { extend : 'Ext.panel.Panel' , alias : 'widget.step' , border : true , layout : 'fit' , collapsible: true , collapsed: true , animCollapse: true , title: "More Help" , bodyPadding: 5 , hidden: true , initComponent: function () { this.callParent(arguments); this.add (Ext.create ( 'Ext.Component' , { html: "<pre>" + this.data + "</pre>" } ) ); } });
var arrays = require("ringo/utils/arrays"); var objects = require("ringo/utils/objects"); var {EventEmitter} = require("ringo/events"); var Message = exports.Message = function(data, options) { EventEmitter.call(this); this.messageObject = { data: typeof(data) == "object" ? data : {message: data} } this.options = options; this.recipients = []; this.createtime = new Date(); this.delay = 0; if (!options) { return this; } for each (var prop in ["restricted_package_name", "collapse_key"]) { if (options[prop] == undefined) { continue; } this.messageObject[prop] = options[prop]; } if (options.delay_while_idle != undefined) { this.delayWhileIdle(options.delay_while_idle); } if (options.dry_run != undefined) { this.dryRun(options.dry_run); } if (options.time_to_live != undefined) { this.setTtl(options.time_to_live); } if (options.recipients != undefined) { this.addRecipients(options.recipients); } if (!isNaN(options.delay)) { this.delay = options.delay; } return this; }; Message.prototype.isSendable = function() { return this.recipients.length > 0; }; Message.prototype.getServiceType = function() { return "gcm"; }; Message.prototype.getDelay = function() { // add random amount of seconds to the delay to avoid flooding return this.delay > 0 ? this.delay + Math.round(Math.random() * 10) : 0; }; Message.prototype.getData = function() { return this.messageObject.data; }; /** * add the recipients in the given array to this GCMMessage's recipients * avoiding duplicates. * @param recipients array of recipients */ Message.prototype.addRecipients = function(recipients) { if (!Array.isArray(recipients)) { throw new Error("addRecipients expects an array "); } else if (recipients.length < 1) { throw new Error("addRecipeints called with empty array"); } this.recipients = arrays.union(this.recipients, recipients); return this; }; /** * set the time to live for this GCMMessage. if the ttl has been reached and the * GCMMessage has not been sent to GCM-Servers it will not be sent. Otherwise the * createtime of this GCMMessage-object will be taken to adjust the ttl for the * difference betweene actual sending and the creation. * @param ttl number of seconds after which there won't be a retry to deliver it to the client */ Message.prototype.setTtl = function(ttl) { if (isNaN(ttl) || typeof(ttl) != "number") { throw new Error("time_to_live has to be a number"); } if (ttl < 1) { throw new Error("time_to_live must be a positive number greater than zero"); } if (ttl > 2419200) { throw new Error("time_to_live must be lower than 2419200 (4 weeks)"); } this.ttl = ttl; return this; }; /** * Returns the time-to-live of this GCMMessage calculated by considering it's createtime */ Message.prototype.getTtl = function() { if (isNaN(this.ttl)) { return undefined; } var now = new Date(); var diff = Math.round((now.getTime() - this.createtime.getTime()) / 1000); var ttl = this.ttl - diff; if (ttl < 1) { return -1; } return ttl; }; /** * Set the number of retries to deliver this GCMMessage. * @param nr the number of retries to deliver this GCMMessage. */ Message.prototype.setRetries = function(nr) { if (isNaN(nr) || typeof(nr) != "number") { throw new Error("Retries has to be a number"); } else if (nr < 1) { throw new Error("Dare to try it once! Retries has to be greater than 0"); } this.retries = nr; return this; }; /** * Mark this GCMMessage as "dry run" meaning ther won't be sent anything to any client, * but the request to GCM-Servers will be handled as if it would. * See https://developer.android.com/google/gcm/server.html * "If included, allows developers to test their request without actually sending a * GCMMessage. Optional. The default value is false, and must be a JSON boolean." * @param bool boolean true if this GCMMessage should be treated as test-message */ Message.prototype.dryRun = function(bool) { if (typeof(bool) != "boolean") { throw new Error("dry_run has to be a boolean"); } this.messageObject.dry_run = bool; return this; }; /** * See https://developer.android.com/google/gcm/server.html * "If included, indicates that the message should not be sent immediately if the device is idle. * The server will wait for the device to become active, and then only the last message for each * collapse_key value will be sent. The default value is false, and must be a JSON boolean. Optional." */ Message.prototype.delayWhileIdle = function(bool) { if (typeof(bool) != "boolean") { throw new Error("delay_while_idle has to be a boolean"); } this.messageObject.delay_while_idle = bool; return this; }; /** * Returns an array holding objects ready to use for GCM-http-api. */ Message.prototype.getSendableObjects = function() { var result = []; var message = objects.clone(this.messageObject, {}, true); var ttl = this.getTtl(); if (ttl) { message.time_to_live = ttl; } for (var i = 0; i < this.recipients.length; i+=1000) { var msg = objects.clone(message, {}, true); msg.registration_ids = this.recipients.slice(i, Math.min(i+1000, this.recipients.length)); result.push(msg); } return result; }; /** * Creates a GCMMessage carrying the same data as the origin. * * The delay of the GCMMessage will be set to double the amount of seconds of the * origin message, but at least one second. (as demanded by google) * * Afterwards the remaining time_to_live will be calculated as follows: * origin.ttl - timediffInSeconds(origin.createtime, now) * * If the resulting ttl is lower than the delay it will return undefined * indicating the expiry of this message. * * Afterwards the retries will be reduced by one and if this results in zero * retries it will return undefined indicating the expiry of this message. */ Message.prototype.clone = function() { var msg = new Message(this.messageObject.data, this.options); msg.delay = Math.max(1, this.delay * 2); if (this.getTtl() != undefined) { if (msg.delay >= this.getTtl()) { return undefined; } msg.setTtl(this.getTtl()); } if (this.retries != undefined) { var retries = this.retries -1; if (retries < 1) { return undefined; } msg.setRetries(retries); } return msg; }; /** @ignore */ Message.prototype.toString = function() { return "[GCMMessage " + JSON.stringify(this.messageObject) + "]"; };
const Router = require('express-promise-router') const Ably = require('ably') const ably = new Ably.Realtime(process.env.ABLY_AKY_KEY) const { db } = require('./db') const isProduction = process.env.FLY_APP_NAME != null const READ_ONLY_SQL_TRANSACTION = 25006 const router = new Router() module.exports = router router.get('/', async (req, res) => { let result if (isProduction) { const { FLY_APP_NAME: appName, FLY_REGION: runningRegion } = process.env const edgeNodeRegion = req.get('Fly-Region') result = { env: 'prod', appName, runningRegion, edgeNodeRegion } } else { result = { env: 'dev' } } res.json(result) }) router.post('/replicache-pull', async (req, res) => { const pull = req.body const { list_id: listID } = req.query console.log(`Processing pull`, JSON.stringify(pull)) const t0 = Date.now() try { await db.tx(async (t) => { const lastMutationID = parseInt( ( await t.oneOrNone( 'select last_mutation_id from replicache_clients where id = $1', pull.clientID, ) )?.last_mutation_id ?? '0', ) const changed = await t.manyOrNone( 'select id, completed, content, ord, deleted, version from todos where list_id = $1', listID, ) const patch = [] const cookie = {} if (pull.cookie == null) { patch.push({ op: 'clear' }) } changed.forEach(({ id, completed, content, ord, version, deleted }) => { cookie[id] = version const key = `todo/${id}` if (pull.cookie == null || pull.cookie[id] !== version) { if (deleted) { patch.push({ op: 'del', key, }) } else { patch.push({ op: 'put', key, value: { id, completed, content, order: ord, }, }) } } }) res.json({ lastMutationID, cookie, patch }) res.end() }) } catch (e) { console.error(e) res.status(500).send(e.toString()) } finally { console.log('Processed pull in', Date.now() - t0) } }) router.post('/replicache-push', async (req, res) => { const { list_id: listID } = req.query const push = req.body console.log('Processing push', JSON.stringify(push)) const t0 = Date.now() try { await db.tx(async (t) => { let lastMutationID = await getLastMutationID(t, push.clientID) for (const mutation of push.mutations) { const t1 = Date.now() const expectedMutationID = lastMutationID + 1 if (mutation.id < expectedMutationID) { console.log( `Mutation ${mutation.id} has already been processed - skipping`, ) continue } if (mutation.id > expectedMutationID) { console.warn(`Mutation ${mutation.id} is from the future - aborting`) break } console.log('Processing mutation:', JSON.stringify(mutation)) switch (mutation.name) { case 'createTodo': await createTodo(t, mutation.args, listID) break case 'updateTodoCompleted': await updateTodoCompleted(t, mutation.args) break case 'updateTodoOrder': await updateTodoOrder(t, mutation.args) break case 'deleteTodo': await deleteTodo(t, mutation.args) break default: throw new Error(`Unknown mutation: ${mutation.name}`) } lastMutationID = expectedMutationID console.log('Processed mutation in', Date.now() - t1) } const channel = ably.channels.get(`todos-of-${listID}`) channel.publish('change', {}) console.log( 'setting', push.clientID, 'last_mutation_id to', lastMutationID, ) await t.none( 'UPDATE replicache_clients SET last_mutation_id = $1 WHERE id = $2', [lastMutationID, push.clientID], ) res.send('{}') }) } catch (e) { console.error(e) // This should be handled at the application level. // We only deal with it at this route for simplicity's reason and because only this route *write* to the db. if ((e.code = READ_ONLY_SQL_TRANSACTION)) { const { PRIMARY_REGION: primary, FLY_REGION: current } = process.env res.set('fly-replay', `region=${primary}`) const replayMessage = `replaying from ${current} to ${primary}` console.log(replayMessage) res.status(409).send(replayMessage) } else { res.status(500).send(e.toString()) } } finally { console.log('Processed push in', Date.now() - t0) } }) async function getLastMutationID(t, clientID) { const clientRow = await t.oneOrNone( 'SELECT last_mutation_id FROM replicache_clients WHERE id = $1', clientID, ) if (clientRow) { return parseInt(clientRow.last_mutation_id) } await t.none( 'INSERT INTO replicache_clients (id, last_mutation_id) VALUES ($1, 0)', clientID, ) return 0 } async function createTodo(t, { id, completed, content, order }, listID) { await t.none( `INSERT INTO todos ( id, completed, content, ord, list_id) values ($1, $2, $3, $4, $5)`, [id, completed, content, order, listID], ) } async function updateTodoCompleted(t, { id, completed }) { await t.none( `UPDATE todos SET completed = $2, version = gen_random_uuid() WHERE id = $1 `, [id, completed], ) } async function updateTodoOrder(t, { id, order }) { await t.none( `UPDATE todos SET ord = $2, version = gen_random_uuid() WHERE id = $1 `, [id, order], ) } async function deleteTodo(t, { id }) { await t.none( `UPDATE todos SET deleted = true, version = gen_random_uuid() WHERE id = $1 `, [id], ) }
const express = require('express'); const path = require('path'); const bodyParser = require('body-parser'); const cors = require('cors'); const {getItems} = require('../database/index.js'); const app = express(); const PORT = 3001; app.use(cors()); app.use(express.static(path.join(__dirname, '../client/dist'))); app.use(bodyParser.json()); app.get('/recently-viewed/:productId', (req, res) => { getItems((err, items) => { if (err) { console.log(err); res.status(400).send(); return; } res.status(200).send(items); }) }); app.use('/:productId', express.static(path.join(__dirname, '../client/dist'))); app.listen(PORT, () => console.log(`LISTENING ON PORT ${PORT}`));
function suma(){ s=$('#formulario').serialize(); $.get("/suma",s,function(data){ $("#resultado").html(data); }) } function multiplica(){ s=$('#formulario').serialize(); $.get("/multiplicar",s,function(data){ $("#resultado").html(data); }) } function divi(){ s=$('#formulario').serialize(); $.post("/div",s,function(data){ $("#resultado").html(data); }) } function sumar(){ n=prompt("ingrese la cantidad de numeros a sumar: "); html = ''; for (var i = 1; i <= parseInt(n); i++) { html += '<input type="number" class="form-control" name="suma[]" placeholder="numero '+i+'" />'; }; html += '<input type="button" class="btn btn-primary" onclick="suma()" value="sumar"/>'; $('#mostrar').html(html) } function multiplicar(){ n=prompt("ingrese la cantidad de numeros para saber su producto: "); html = ''; for (var i = 1; i <= parseInt(n); i++) { html += '<input type="number" class="form-control" name="multiplicar[]" placeholder="numero '+i+'" />'; }; html += '<input type="button" class="btn btn-primary" onclick="multiplica()" value="multiplicar"/>'; $('#mostrar').html(html) } function division(){ html = ''; html += '<input type="number" class="form-control" name="num1" placeholder="numero 1" />'; html += '<input type="number" class="form-control" name="num2" placeholder="numero 2" />'; html += '<input type="button" class="btn btn-primary" onclick="divi()" value="dividir"/>'; $('#mostrar').html(html) }
/** * @param {number[]} nums * @return {number[]} * @author sujiexin */ var sortArray = function(nums) { if(nums.length<2){ return nums; } var l = 0; var h = nums.length-1; return quicksort(nums,l,h); }; function quicksort(nums,l,h){ var low = l; var high = h; if(l>=h){ return ; } var key = nums[l]; while(low<high){ while(low<high&&nums[high]>key) high--; if(low<high){ nums[low] = nums[high]; low++; } while(low<high&&nums[low]<key) low++; if(low<high){ nums[high]=nums[low]; high--; } } nums[low] = key; quicksort(nums,l,low-1); quicksort(nums,low+1,h); return nums; }
import React from 'react'; const ScoreButton = (props) => { return ( <button onClick={() => props.handleScoreClick() }>Score BTN</button> ) } export default ScoreButton;
import React from 'react'; import './ForgotPassword.scss'; import { Form, Row, Col, Image } from 'react-bootstrap'; import Input from '@material-ui/core/Input'; import InputLabel from '@material-ui/core/InputLabel'; import { Button, FormControl } from '@material-ui/core'; import ClickAwayListener from '@material-ui/core/ClickAwayListener'; import { withRouter } from 'react-router-dom'; import { connect } from 'react-redux'; import Spinner from 'react-spinkit'; import Dialog from '@material-ui/core/Dialog'; import DialogTitle from '@material-ui/core/DialogTitle'; import DialogContent from '@material-ui/core/DialogContent'; import DialogActions from '@material-ui/core/DialogActions'; import Typography from '@material-ui/core/Typography'; import CircularProgress from '@material-ui/core/CircularProgress'; import * as actions from '../../redux/actions/index'; let variableEmailPhone; let variableEmailPhoneColor; let variableEmailPhoneText; let variableEmailPhoneTextColor; const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; //const remobile = /^[0-9]{9}$/; class ForgotPassword extends React.Component { constructor(props) { super(props); this.state = { width: 0, height: 0, emailPhoneValue: '', emailPhoneActive: false, emailPhoneSuccess: null, emailPhoneFinal: false }; this.inputEmailPhone = React.createRef(); this.updateWindowDimensions = this.updateWindowDimensions.bind(this); } componentDidMount() { this.updateWindowDimensions(); window.addEventListener('resize', this.updateWindowDimensions); if (window.performance) { if (performance.navigation.type === 1) { this.setState({ width: 0, height: 0, emailPhoneValue: '', emailPhoneActive: false, emailPhoneSuccess: null, emailPhoneFinal: false }); // this.props.forgotpasswordalertshowhidedangerdismiss('/signin'); // alert( "This page is reloaded" ); } else { // alert( "This page is not reloaded"); } } } componentWillReceiveProps() { if (this.props.forgotPasswordShow && !this.props.forgotPasswordLoading) { this.handleResetCick(); } } componentWillUnmount() { window.removeEventListener('resize', this.updateWindowDimensions); } updateWindowDimensions() { this.setState({ width: window.innerWidth, height: window.innerHeight }); } validateEmailPhone = () => { const { emailPhoneValue } = this.state; if (re.test(emailPhoneValue)) { this.setState({ emailPhoneSuccess: true, emailPhoneFinal: true }); } else { this.setState({ emailPhoneSuccess: false, emailPhoneFinal: false }); } }; onEmailPhoneChange(event) { const { emailPhoneValue } = this.state; this.setState( { emailPhoneValue: event.target.value }, function() { this.validateEmailPhone(); } ); } handleForgotPasswordSubmit = event => { event.preventDefault(); const { emailPhoneValue, emailPhoneFinal } = this.state; localStorage.setItem('forgotPasswordMainEmail', emailPhoneValue); if (emailPhoneFinal === null) { this.handleEmailPhoneClick(); } if (emailPhoneFinal === false) { this.handleEmailPhoneClick(); } if (emailPhoneFinal === true) { const payloads = { email: emailPhoneValue }; this.props.forgotPassword(payloads, '/verify-otp'); } }; handleResetCick = () => { this.setState({ emailPhoneValue: '', emailPhoneActive: false, emailPhoneSuccess: null, emailPhoneFinal: false }); }; handleEmailPhoneClick = () => { //const { emailPhoneValue } = this.state; this.setState( { emailPhoneActive: true }, function() { this.validateEmailPhone(); } ); }; handleEmailPhoneClickAway = () => { const { emailPhoneFinal } = this.state; if (emailPhoneFinal === true) { this.setState({ emailPhoneActive: false, emailPhoneSuccess: null }); } }; handleForgotPasswordBack = () => { this.props.history.push('/signin'); }; render() { const { width, height, emailPhoneSuccess, emailPhoneActive, emailPhoneValue } = this.state; console.log(`${width}---------------${height}------------------`); let forgotPasswordModalView; if (this.props.forgotPasswordShow && !this.props.forgotPasswordLoading) { forgotPasswordModalView = ( <Dialog onClose={() => this.props.forgotpasswordalertshowhidedanger()} aria-labelledby='customized-dialog-title' open={this.props.forgotPasswordShow} > <DialogTitle id='customized-dialog-title'>Error</DialogTitle> <DialogContent dividers> <Typography gutterBottom>{this.props.forgotPasswordError.Error.Message}</Typography> </DialogContent> <DialogActions> <Button onClick={() => this.props.forgotpasswordalertshowhidedangerdismiss('/signin')} color='primary'> Ok </Button> </DialogActions> </Dialog> ); } if (emailPhoneActive === false && emailPhoneSuccess === null) { variableEmailPhoneText = ''; variableEmailPhoneTextColor = ''; variableEmailPhoneColor = 'icon-gray'; variableEmailPhone = <Image src={require('../../assets/icons/svg/user-inactive.svg')} className='email' />; } if (emailPhoneActive === true && emailPhoneSuccess === false) { variableEmailPhoneText = '* Must be a valid and registered email id'; variableEmailPhoneColor = 'icon-danger'; variableEmailPhoneTextColor = 'danger-text'; variableEmailPhone = <Image src={require('../../assets/icons/svg/user-danger.svg')} className='email' />; } if (emailPhoneActive === true && emailPhoneSuccess === true) { variableEmailPhoneText = ''; variableEmailPhoneColor = 'icon-blue'; variableEmailPhoneTextColor = ''; variableEmailPhone = <Image src={require('../../assets/icons/svg/user-active.svg')} className='email' />; } if (emailPhoneActive === true && emailPhoneSuccess === null) { variableEmailPhoneText = ''; variableEmailPhoneColor = 'icon-blue'; variableEmailPhoneTextColor = ''; variableEmailPhone = <Image src={require('../../assets/icons/svg/user-active.svg')} className='email' />; } return ( <Row className='parent p-2'> <Col className='center-col-around'> <Row className='variable-margin-top-minor'> <Col> <Image onClick={this.handleForgotPasswordBack} src={require('../../assets/icons/svg/left-arrow.svg')} className='email' /> </Col> <Col className='right-col'> <Image src={require('../../assets/images/svg/grid_pvot.svg')} /> </Col> </Row> <Row className='variable-margin-top-minor'> <Col> <Form noValidate onSubmit={event => this.handleForgotPasswordSubmit(event)}> <Row> <Col> <div className='forgot-sub-heading'>Send OTP to</div> </Col> </Row> <Row className='mt-5'> <Col className={variableEmailPhoneColor}> <ClickAwayListener onClickAway={this.handleEmailPhoneClickAway}> <FormControl> {variableEmailPhone} <InputLabel style={{ marginLeft: '50px' }} htmlFor='standard-name'> Email ID </InputLabel> <Input id='standard-name' className='sigin-input' value={emailPhoneValue} autoComplete='off' onChange={event => this.onEmailPhoneChange(event)} fullWidth onClick={this.handleEmailPhoneClick} inputRef={this.inputEmailPhone} error={!emailPhoneSuccess} /> </FormControl> </ClickAwayListener> </Col> </Row> <Row className='mt-1'> <Col className='left-all-no-justify'> <div className='min-8-characters'> <div className={variableEmailPhoneTextColor}>{variableEmailPhoneText}</div> </div> </Col> </Row> <Row className='fixed-margin-top'> <Col className='center-col'> {this.props.forgotPasswordLoading ? ( <CircularProgress name='circle' color='primary' /> ) : ( <Button className='pointer' variant='contained' color='primary' type='submit' fullWidth> Verify </Button> )} </Col> </Row> </Form> </Col> </Row> <Row className='variable-margin-top-minor variable-margin-bottom-minor'> <Col className='left-col'> <Image src={require('../../assets/images/svg/grid_pvot.svg')} /> </Col> </Row> {forgotPasswordModalView} </Col> </Row> ); } } const mapStateToProps = state => ({ forgotPasswordLoading: state.auth.forgotPasswordLoading, forgotPasswordError: state.auth.forgotPasswordError, forgotPasswordData: state.auth.forgotPasswordData, forgotPasswordMessage: state.auth.forgotPasswordMessage, forgotPasswordShow: state.auth.forgotPasswordShow }); const mapDispatchToProps = dispatch => ({ forgotPassword: (params, path) => dispatch(actions.forgotPassword(params, path)), forgotpasswordalertshowhidedanger: () => dispatch(actions.forgotpasswordalertshowhidedanger()), forgotpasswordalertshowhidedangerdismiss: path => dispatch(actions.forgotpasswordalertshowhidedangerdismiss(path)) }); export default connect( mapStateToProps, mapDispatchToProps )(withRouter(ForgotPassword));
const fs = require('fs'); const path = require('path'); // Create a folder fs.mkdir(path.join(__dirname, 'test'), {}, err => { if (err) throw err; console.log('Folder created'); }); // Create and write to file fs.writeFile(path.join(__dirname, '/test/', 'hello.txt'), 'Hello, Trent, this is a file created with Node.js\n', err => { if (err) throw err; console.log('File written to'); }); // File Append fs.appendFile(path.join(__dirname, '/test/', 'hello.txt'), 'This is a lot of fun!', err => { if (err) throw err; console.log('File Appended to'); }); // Read File fs.readFile(path.join(__dirname, '/test/', 'hello.txt'), 'utf8', (err, data) => { if (err) throw err; console.log(data); }); // Rename a File fs.rename(path.join(__dirname, '/test/', 'hello.txt'), path.join(__dirname, '/test/', 'trentsmessage.txt'), (err) => { if (err) throw err; console.log('Renamed file'); });
'use strict'; /** * @workInProgress * @ngdoc service * @name angular.service.$xhr.bulk * @requires $xhr * @requires $xhr.error * @requires $log * * @description * * @example */ angularServiceInject('$xhr.bulk', function($xhr, $error, $log){ var requests = [], scope = this; function bulkXHR(method, url, post, success, error) { if (isFunction(post)) { error = success; success = post; post = null; } var currentQueue; forEach(bulkXHR.urls, function(queue){ if (isFunction(queue.match) ? queue.match(url) : queue.match.exec(url)) { currentQueue = queue; } }); if (currentQueue) { if (!currentQueue.requests) currentQueue.requests = []; var request = { method: method, url: url, data: post, success: success}; if (error) request.error = error; currentQueue.requests.push(request); } else { $xhr(method, url, post, success, error); } } bulkXHR.urls = {}; bulkXHR.flush = function(success, errorback) { assertArgFn(success = success || noop, 0); assertArgFn(errorback = errorback || noop, 1); forEach(bulkXHR.urls, function(queue, url) { var currentRequests = queue.requests; if (currentRequests && currentRequests.length) { queue.requests = []; queue.callbacks = []; $xhr('POST', url, {requests: currentRequests}, function(code, response) { forEach(response, function(response, i) { try { if (response.status == 200) { (currentRequests[i].success || noop)(response.status, response.response); } else if (isFunction(currentRequests[i].error)) { currentRequests[i].error(response.status, response.response); } else { $error(currentRequests[i], response); } } catch(e) { $log.error(e); } }); success(); }, function(code, response) { forEach(currentRequests, function(request, i) { try { if (isFunction(request.error)) { request.error(code, response); } else { $error(request, response); } } catch(e) { $log.error(e); } }); noop(); }); } }); }; this.$watch(function(){ bulkXHR.flush(); }); return bulkXHR; }, ['$xhr', '$xhr.error', '$log']);
var map_MM, reduce_M; map_MM= function() { var values =1; //var v1=this.genres.genres emit(this.year, values); }; reduce_M = function(k, values) { return Array.sum(values); }; db.full_info2.mapReduce( map_MM, reduce_M, { out: "map_reduce_example" }); //db.map_reduce_example.find() //db.map_reduce_example.drop() var map_MM, reduce_M; map_MM= function() { var values =1; var v1=this.rank emit(v1, values); }; reduce_M = function(k, values) { return Array.sum(values); }; db.full_info2.mapReduce( map_MM, reduce_M, { out: "map_reduce_example" ,query:{ 'year': 2000 , 'genres.genres':'Comedy'}});
var count = 0; var randomNum = Math.floor(Math.random() * 100) + 1; document.querySelector("#try").onkeypress = function (e){ if(e.keyCode == 13 || e.which == 13){ find(); return false; } }; function find(){ var userNum = document.querySelector("#try").value; var output = document.querySelector("#display"); var counter = document.querySelector("#counter"); if(userNum >= 1 && userNum <= 100){ if(randomNum > userNum){ output.innerHTML = "UP!"; }else if(randomNum < userNum){ output.innerHTML = "Down!"; }else{ output.innerHTML = "<span style='color:red'>정답입니다!</span>"; } }else{ alert("1에서 100사이에 숫자만 입력하세요."); } document.querySelector("#try").value =""; count += 1; counter.innerHTML = "시도회수 : " + count + " 회"; }
const { router } = require('../../../config/expressconfig') const User = require('../../models/user') let changeUserStatus = router.patch("/change-user-status", async (req, res) => { let { id, status } = req.body; let obj = { status }; const result = await User.findByIdAndUpdate(id,obj) if(result && result.length != 0) { return res.json({ msg: 'User Status updated successfully', data: result }) } else { return res.json({ msg: "User status can not be updated" }) } }); module.exports = { changeUserStatus }
import Vue from "vue" import Vuex from "vuex" Vue.use(Vuex) // initial state const state = { loading:false } // getters const getters = { } // actions const actions = { loading ({commit}, status) { commit("loading",status); } } // mutations const mutations = { loading (state, status) { state.loading = status } } export default new Vuex.Store({ state, getters, actions, mutations, modules: { } })
var searchData= [ ['light',['Light',['../classLight.html',1,'']]], ['linearsecondchild',['LinearSecondChild',['../unionBVHLinearNode_1_1LinearSecondChild.html',1,'BVHLinearNode']]], ['logarithm',['Logarithm',['../classsymcpp_1_1Logarithm.html',1,'symcpp']]] ];
import React from 'react' import ReactDOM from 'react-dom' import { Layout } from './components/layout' import registerServiceWorker from './services/service-worker' ReactDOM.render(<Layout />, document.getElementById('root')) registerServiceWorker()
const round = (number, abbr) => { let rounded; switch (abbr) { case 'T': rounded = number / 1e12 break case 'B': rounded = number / 1e9 break case 'M': rounded = number / 1e6 break case 'K': rounded = number / 1e3 break case '': rounded = number break } let test = new RegExp('\\.\\d{' + 1 + ',}$') if (test.test(('' + rounded))) { rounded = rounded.toFixed(2) } return rounded + abbr } const abbreviate = number => { let abbr; if (number >= 1e12) { abbr = 'T' } else if (number >= 1e9) { abbr = 'B' } else if (number >= 1e6) { abbr = 'M' } else if (number >= 1e3) { abbr = 'K' } else { abbr = '' } return round(number, abbr) } export default abbreviate;
// Require the friends file var friends = require("../data/friends.js"); var path = require("path"); // Routing module.exports = function (app) { // API GET Request for json data of all users app.get("/api/friends", function (req, res) { res.json(friends); }); // API POST Request of user data app.post("/api/friends", function (req, res) { // Object to hold best match data var bestMatch = { name: "", photo: "", friendDifference: 100 }; // Take the result of the user's survey POST and parse it var userData = req.body; var userScores = userData.scores; // To calculate the difference between the user's scores and the scores of each user in database var totalDifference = 0; // Loop through all users in database for (var i = 0; i < friends.length; i++) { totalDifference = 0; // Loop through the scores of all users for(var j = 0; j < friends[i].scores[j]; j++) { // Calculate the difference between scores and add them into the totalDifference totalDifference += Math.abs(parseInt(userScores[j]) - parseInt(friends[i].scores[j])); // Check if the sum is less than the differences of current best match if(totalDifference <= bestMatch.friendDifference) { bestMatch.name = friends[i].name; bestMatch.photo = friends[i].photo; bestMatch.friendDifference = totalDifference; } } } // Push new user data to the friends module friends.push(userData); // Response for the best match in json res.json(bestMatch); }); }
const calc = document.createElement('div'); const btns = document.createElement('div'); let numOne = document.createElement('input'); numOne.setAttribute('type', 'number'); numOne.setAttribute('placeholder', 'num 1'); let numTwo = document.createElement('input') numTwo.setAttribute('type', 'number'); numTwo.setAttribute('placeholder', 'num 2'); let btnAddition = document.createElement('button'); btnAddition.innerHTML = '+'; let btnSubtraction = document.createElement('button'); btnSubtraction.innerHTML = '-'; let btnMultiplication = document.createElement('button'); btnMultiplication.innerHTML = '*'; let btnDivision = document.createElement('button'); btnDivision.innerHTML = '/'; calc.appendChild(numOne) calc.appendChild(numTwo) btns.appendChild(btnAddition) btns.appendChild(btnSubtraction) btns.appendChild(btnMultiplication) btns.appendChild(btnDivision) calc.appendChild(btns) let out = document.querySelector('#root'); out.appendChild(calc) export default { numOne : numOne, numTwo : numTwo, btnAddition :btnAddition, btnSubtraction :btnSubtraction, btnMultiplication :btnMultiplication, btnDivision :btnDivision }
(function () { 'use strict'; angular .module('panel6') .config(config); function config($stateProvider) { $stateProvider .state('panel6', { url: '/6', templateUrl: 'panel6/views/panel6.tpl.html', controller: 'Panel6Ctrl', controllerAs: 'panel6' }); } }());
// # IsAdmin Helper // Usage: `{{#isAdmin}}` // Checks whether the user has admin or owner rule var _ = require('lodash'), isAdmin; isAdmin = function (options) { options = options || {}; var user = options.data.root.user; if (_.includes([user.role], 'owner', 'admin')) { return options.fn(this); } return options.inverse(this); }; module.exports = isAdmin;
const mongoose = require("mongoose"); const DonutStore = require("./DonutStore"); console.log("Looking for DonutStore in Bucketlist", DonutStore); const BucketlistSchema = new mongoose.Schema ({ userName: String, favDonut: String, bucketlist: [DonutStore.schema], visitedStores: [DonutStore.schema], }); const Bucketlist = mongoose.model("Bucketlist", BucketlistSchema); module.exports = Bucketlist;
const { I, loginSubdomainPage, loginAccountPage, createLeadPage, leadStatusPage } = inject(); module.exports = { logIntoZendeskSellWebApp(subDomainName, userEmail, userPassword) { loginSubdomainPage.goToSubdomainLoginPage(); loginSubdomainPage.acceptToUseCookies(); loginSubdomainPage.checkSubdomainPage(); loginSubdomainPage.fillSubdomainName(subDomainName); loginSubdomainPage.clickSignInButton(); loginAccountPage.checkAccountLoginPage(); loginAccountPage.fillAccountInformations(userEmail, userPassword); loginAccountPage.clickSignInButton(); loginAccountPage.checkIfSignedIn(); }, createNewLead(newLeadFirstName, newLeadLastName, newLeadCompanyName) { createLeadPage.clickAddButton(); createLeadPage.checkAddMenu(); createLeadPage.clickLeadButton(); createLeadPage.checkLeadAddForm(); createLeadPage.fillLeadInformations(newLeadFirstName, newLeadLastName, newLeadCompanyName); createLeadPage.clickSaveAndViewLeadButton(); }, changeLeadStatusToDifferentName(currentLeadStatus, newLeadStatus) { leadStatusPage.clickSettings(); leadStatusPage.checkSettingsPage(); leadStatusPage.clickCustomizeLeads(); leadStatusPage.clickLeadStatus(); leadStatusPage.changeStatusName(currentLeadStatus, newLeadStatus) }, checkLeadStatusName(leadFirstName, leadLastName, leadStatusName) { leadStatusPage.clickLeadsOnTopbar(); leadStatusPage.checkLeadsPage(); leadStatusPage.filterByLeadName(leadLastName); leadStatusPage.goToLead(leadFirstName, leadLastName); leadStatusPage.checkLeadStatus(leadStatusName); } }
// Code your solution in this file function findMatching(collection, string){ const newCollection = []; for (var i = 0; i < collection.length; i++) { if (collection[i].toUpperCase() === string.toUpperCase()) { newCollection.push(collection[i]); } } return newCollection; } function fuzzyMatch(collection, string) { const len = string.length; const newCollection = []; for (var i = 0; i < collection.length; i++) { if (collection[i].slice(0, len) === string) { newCollection.push(collection[i]); } } return newCollection; } function matchName(collection, n) { const newCollection = []; for (var i = 0; i < collection.length; i++) { if (collection[i]['name'] === n) { newCollection.push(collection[i]); } } return newCollection; }
// affiche le template du dashboard // l'action de ce controller est appelée par défaut module.exports = { load : function(req, res){ res.render('dashboard'); } };
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import classNames from 'classnames'; import { withStyles } from '@material-ui/core/styles'; import Drawer from '@material-ui/core/Drawer'; import AppBar from '@material-ui/core/AppBar'; import Toolbar from '@material-ui/core/Toolbar'; import CssBaseline from '@material-ui/core/CssBaseline'; import Typography from '@material-ui/core/Typography'; import Divider from '@material-ui/core/Divider'; import IconButton from '@material-ui/core/IconButton'; import MenuIcon from '@material-ui/icons/Menu'; import Fab from '@material-ui/core/Fab'; import ChevronLeftIcon from '@material-ui/icons/ChevronLeft'; import ChevronRightIcon from '@material-ui/icons/ChevronRight'; import { Circle, Layer, Line, Stage, useStrictMode, } from 'react-konva'; import Description from '../description/Description'; import SettingModal from '../description/cases/observing/SettingsModal'; import Styles from './Styles'; import AppState from '../../config/AppState'; const styles = Styles; class PersistentDrawerRight extends React.Component { state = AppState; componentDidMount() { useStrictMode(true); } handleDrawerOpen = () => { this.setState({ open: true }); }; handleDrawerClose = () => { this.setState({ open: false }); }; handleDragEnd = (e) => { const { circlePoints, blockSnapSize } = this.state; const newCirclePoints = [...circlePoints]; const newCircle = newCirclePoints.map(() => ({ x: Math.round(e.target.x() / blockSnapSize) * blockSnapSize, y: Math.round(e.target.y() / blockSnapSize) * blockSnapSize, })); this.setState({ circlePoints: newCircle }); } renderVerticalGrid = () => { const width = window.innerWidth; const height = window.innerHeight; const { blockSnapSize } = this.state; const lines = []; const grouped = width / blockSnapSize; for (let i = 0; i < grouped; i += 1) { lines.push( <Line key={i} points={[Math.round(i * blockSnapSize) + 1, 0, Math.round(i * blockSnapSize) + 1, height]} stroke="#CCC" strokeWidth={1} />, ); } return lines; } renderHorizontalGrid = () => { const width = window.innerWidth; const height = window.innerHeight; const { blockSnapSize } = this.state; const lines = []; const grouped = height / blockSnapSize; for (let j = 0; j < grouped; j += 1) { lines.push( <Line key={j} points={[0, Math.round(j * blockSnapSize), width, Math.round(j * blockSnapSize)]} stroke="#CCC" strokeWidth={1} />, ); } return lines; } render() { const { classes, theme, showTitle, themeColor, kind, isPolygonActive, isSquareActive, isTriangleActive, toggleLine, openModal, showGrid, showPoints, handleForm, handleView, onOpenModal, onCloseModal, mode, t, } = this.props; const { open, circlePoints } = this.state; return ( <div className={classes.root}> <CssBaseline /> { showTitle ? ( <AppBar position="fixed" className={classNames(classes.appBar, { [classes.appBarShift]: open, })} > <Toolbar disableGutters style={{ backgroundColor: themeColor }}> <IconButton color="inherit" aria-label="Open drawer" onClick={this.handleDrawerOpen} className={classNames(classes.menuButton, open && classes.hide)} style={{ outline: 'none' }} > <MenuIcon /> </IconButton> <Typography variant="h4" color="inherit" noWrap className={classes.title}> {t('Symmetrical Figures')} </Typography> </Toolbar> </AppBar> ) : '' } <main className={classNames(classes.content, { [classes.contentShift]: open, })} > { showTitle ? ( <div className={classes.drawerHeader} /> ) : '' } { showTitle ? '' : ( <Fab color="primary" aria-label="Add" onClick={open ? this.handleDrawerClose : this.handleDrawerOpen} className={classes.fab} style={{ backgroundColor: themeColor, outline: 'none' }} > { open ? <ChevronRightIcon /> : <MenuIcon style={{ color: 'white' }} /> } </Fab> ) } { showGrid ? ( <Stage width={window.innerWidth} height={window.innerHeight}> <Layer> {this.renderVerticalGrid()} {this.renderHorizontalGrid()} <Circle x={circlePoints[0].x} y={circlePoints[0].y} radius={15} stroke="rgb(255, 87, 34)" strokeWidth={5} shadowBlur={14} draggable onDragEnd={this.handleDragEnd} /> </Layer> </Stage> ) : '' } </main> <Drawer className={classes.drawer} variant="persistent" anchor="right" open={open} classes={{ paper: classes.drawerPaper, }} > <div className={classes.drawerHeader}> <IconButton onClick={this.handleDrawerClose} style={{ outline: 'none' }}> {theme.direction === 'rtl' ? <ChevronLeftIcon /> : <ChevronRightIcon />} </IconButton> <h3>{t('Observe')}</h3> </div> <Divider /> <Description handleForm={handleForm} showGrid={showGrid} showTitle={showTitle} showPoints={showPoints} handleView={handleView} kind={kind} isPolygonActive={isPolygonActive} isSquareActive={isSquareActive} isTriangleActive={isTriangleActive} toggleLine={toggleLine} t={t} /> { mode === 'default' ? ( <SettingModal openModal={openModal} onOpenModal={onOpenModal} onCloseModal={onCloseModal} t={t} /> ) : '' } </Drawer> </div> ); } } PersistentDrawerRight.propTypes = { classes: PropTypes.shape({}).isRequired, theme: PropTypes.shape({}).isRequired, themeColor: PropTypes.string.isRequired, showTitle: PropTypes.bool.isRequired, t: PropTypes.func.isRequired, kind: PropTypes.string.isRequired, isPolygonActive: PropTypes.bool.isRequired, isSquareActive: PropTypes.bool.isRequired, isTriangleActive: PropTypes.bool.isRequired, squareNodeA: PropTypes.shape({}).isRequired, squareNodeB: PropTypes.shape({}).isRequired, triangleNodeB: PropTypes.shape({}).isRequired, toggleLine: PropTypes.bool.isRequired, openModal: PropTypes.bool.isRequired, showGrid: PropTypes.bool.isRequired, showPoints: PropTypes.bool.isRequired, handleForm: PropTypes.func.isRequired, handleView: PropTypes.func.isRequired, onOpenModal: PropTypes.func.isRequired, onCloseModal: PropTypes.func.isRequired, mode: PropTypes.string.isRequired, }; const mapStateToProps = state => ({ themeColor: state.Setting.themeColor, showTitle: state.Setting.showTitle, }); const connectedComponent = connect(mapStateToProps)(PersistentDrawerRight); export default withStyles(styles, { withTheme: true })(connectedComponent);
import React, { PureComponent, Component, createRef } from 'react'; class Modal extends PureComponent { modalWrapper = createRef(); renderHeader = () => { const { useModalHeader, modalTitle, modalClosed } = this.props; const headerMarkup = ( <div className="modal-header"> <h4 className="modal-title">{modalTitle}</h4> <button className="close-modal" onClick={modalClosed}> X </button> </div> ); if (useModalHeader === false) { return; } return headerMarkup; }; renderFooter = () => { const { useModalFooter, modalClosed, footerBtnText, footerBtnListener } = this.props; const footerMarkup = ( <div className="modal-footer"> <button className="close-modal" onClick={() => { if (footerBtnListener) { footerBtnListener(); } modalClosed(); }} > {footerBtnText ? footerBtnText : "close"} </button> </div> ); if (useModalFooter === false) { return; } return footerMarkup; }; render() { const { show, modalClosed, children } = this.props; return ( <div className={`modal-window ${!show ? "inactive-modal" : ""}`} onClick={e => { if (e.target === this.modalWrapper.current) { modalClosed(); } }} > <div className="modal-wrapper" ref={this.modalWrapper}> <div className={`modal ${show ? "animate-modal" : ""}`}> {this.renderHeader()} <div className="modal-body">{children}</div> {this.renderFooter()} </div> </div> </div> ); } } export default Modal;
var con = require('../db'); // Retrieve data async function getData() { var rows; //Works for doadmin user rows = await dbQuery("SELECT questions.questionId, questions.question AS question, questions.answer AS answer, GROUP_CONCAT(options.optionValue SEPARATOR ', ' ) AS options FROM options JOIN questions ON questions.questionId = options.questionId GROUP by options.questionId"); rows = JSON.stringify(rows); let x = JSON.parse(rows); x.forEach(elm => { elmOptions = elm.options.split(", "); elm.options = elmOptions; }); //console.log( JSON.stringify(x)); return JSON.stringify(x); } function dbQuery(databaseQuery) { return new Promise(data => { con.query(databaseQuery, function (error, result) { if (error) { console.log(error); throw error; } try { data(result); } catch (error) { data({}); throw error; } }); }); } module.exports = { getData };
$(document).ready(function () { GetStudents(); }); function GetStudents() { $.ajax ({ url: "../api/Students", type: "GET", contentType: "application/json;charset=utf-8", dataType: "json", success: function (result) { var html = ''; $.each(result, function (key, student) { html += '<div class="row">'; html += '<div class="col-sm-3">' + student.Id + '</div>'; html += '<div class="col-sm-3">' + student.FirstName + '</div>'; html += '<div class="col-sm-3">' + student.LastName + '</div>'; html += '<div class="col-sm-3"><a href="#" onclick="return GetStudentById(' + student.Id + ')">Edit</a> | <a href="#" onclick="DeleteStudent(' + student.Id + ')">Delete</a></div>'; html += '</div>'; html += '<hr>'; }); $('#StudentTable').html(html); }, error: function (errormessage) { alert(errormessage.responseText); } }) } function GetStudentById(Id) { $.ajax ({ url: "../api/Students/" + Id, type: "GET", contentType: "application/json;charset=utf-8", dataType: "json", success: function (result) { $('#StudentId').val(result.Id); $('#FirstName').val(result.FirstName); $('#LastName').val(result.LastName); $('#StudentModal').modal('show'); $('#btnUpdate').show(); $('#btnAdd').hide(); }, error: function (errormessage) { alert(errormessage.responseText); } }); return false; } /*I didn't need contentType specified for the GET method, but when calling the POST endpoint the values of first and last name were being inserted as null without specifying contentType */ function AddStudent() { var validateResult = validate(); if (validateResult == false) { return false; } var student = { FirstName: $('#FirstName').val(), LastName: $('#LastName').val() }; $.ajax({ url: "../api/Students", data: JSON.stringify(student), type: "POST", contentType: "application/json;charset=utf-8", dataType: "json", success: function (result) { GetStudents(); $('#StudentModal').modal('hide'); }, error: function (errormessage) { alert(errormessage.responseText); } }); } /* We need to send the Id in the request because of the check in api controller function comparing the Id in the URL and in the body */ function UpdateStudent(Id) { var validateResult = validate(); if (validateResult == false) { return false; } var student = { Id: $('#StudentId').val(), FirstName: $('#FirstName').val(), LastName: $('#LastName').val() }; $.ajax({ url: "../api/Students/" + Id, data: JSON.stringify(student), type: "PUT", contentType: "application/json;charset=utf-8", dataType: "json", success: function (result) { GetStudents(); $('#StudentModal').modal('hide'); $('body').removeClass('modal-open'); $('.modal-backdrop').remove(); }, error: function (errormessage) { alert(errormessage.responseText); } }); } function DeleteStudent(Id) { $.ajax({ url: "../api/Students/" + Id, type: "DELETE", contentType: "application/json;charset=utf-8", dataType: "json", success: function (result) { GetStudents(); $('#StudentModal').modal('hide'); $('body').removeClass('modal-open'); $('.modal-backdrop').remove(); }, error: function (errormessage) { alert(errormessage.responseText); } }); } function clearModalFields() { $('#StudentId').val(""); $('#FirstName').val(""); $('#LastName').val(""); $('#btnUpdate').hide(); $('#btnAdd').show(); $('#FirstName').css('border-color', 'lightgrey'); $('#LastName').css('border-color', 'lightgrey'); } /* used to validate fields when trying to add a new student */ function validate() { var isValid = true; if ($('#FirstName').val().trim() == "") { $('#FirstName').css('border-color', 'Red'); isValid = false; } else { $('#FirstName').css('border-color', 'lightgrey'); } if ($('#LastName').val().trim() == "") { $('#LastName').css('border-color', 'Red'); isValid = false; } else { $('#LastName').css('border-color', 'lightgrey'); } return isValid; }
import React from 'react' import { Title } from 'bypass/ui/title' import { Container } from 'bypass/ui/page' import { AutoSizer, ColumnLayout, RowLayout, Layout } from 'bypass/ui/layout' import { Condition } from 'bypass/ui/condition' import { Button } from 'bypass/ui/button' import { Aside } from './aside' import { List } from './list' const Tablet = ({ columns, list, total, search, showSearch, showResult, hasSelected, allSelected, cart, onToggleDefault, onSaveSearch, onLoadSearch, onFastBuy, onAddToCart, onShowFilter, onSearch, onShowSearch, onHideSearch, onClearSearch, onLoad, onSelect, onSelectAll, }) => ( <AutoSizer> <ColumnLayout> <Layout> <Aside fill cart={cart} search={search} showSearch={showSearch} onShowFilter={onShowFilter} onSearch={onSearch} onShowSearch={onShowSearch} onHideSearch={onHideSearch} onClearSearch={onClearSearch} onSaveSearch={onSaveSearch} onLoadSearch={onLoadSearch} onToggleDefault={onToggleDefault} /> </Layout> <Layout grow={1} shrink={1}> <Condition match={showResult}> <Container> <AutoSizer> <RowLayout> <Layout> <Title size='medium'> {__i18n('LANG.SERVICE.SEARCH_RESULT')} </Title> </Layout> <Layout basis='20px' /> <Layout scrollX touch grow={1} shrink={1}> <List list={list} total={total} columns={columns} rowHeight={30} minWidth={980} allSelected={allSelected} onLoad={onLoad} onSelect={onSelect} onSelectAll={onSelectAll} onAddToCart={onAddToCart} /> </Layout> <Layout basis='20px' /> <Layout> <ColumnLayout> <Layout grow={1} /> <Layout> <Button disabled={!hasSelected} onClick={onAddToCart}> {__i18n('COM.ADD_TO_CART')} </Button> </Layout> <Layout basis='15px' /> <Layout> <Button disabled={!hasSelected} onClick={onFastBuy}> {__i18n('SEARCH.FAST_BUY.FAST')} </Button> </Layout> <Layout grow={1} /> </ColumnLayout> </Layout> <Layout basis='20px' /> </RowLayout> </AutoSizer> </Container> </Condition> </Layout> </ColumnLayout> </AutoSizer> ) export default Tablet
class RobinhoodApp { constructor() {} start() { // TODO: Get username and password from user, // then authenticate, // then get SMS from user // // This should only kick in when using a custom function, btw } }
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) // 例示用に非同期処理を行う関数 // 実際のアプリではサーバーからデータを取得する function getCountNum (type) { return new Promise(resolve => { // 1秒後にtypeに応じたデータを返す setTimeout(() => { let amount switch (type) { case 'one': amount = 1 break case 'two': amount = 2 break case 'ten': amount = 10 break default: amount = 0 } resolve({ amount }) }, 1000) }) } // カウンターモジュールを定義 const counter = { // ステート state: { count: 10 }, // ゲッター getters: { squared: state => state.count * state.count }, // ミューテーション mutations: { increment(state, amount) { state.count += amount } }, // アクション actions: { incrementAsync ({ commit }, payload) { return getCountNum(payload.type) .then(data => { commit('increment', { amount: data.amount }) }) } }, // モジュールは入れ子に定義することができます modules: { childModule: { // 入れ子モジュールの定義 } } } const store = new Vuex.Store({ // counterモジュールをストアに登録 modules: { counter } }) // ステートはモジュール名の下に登録される // `counter`モジュールであれば`store.state.counter` console.log(store.state.counter.count) // -> 10 // ゲッター、ミューテーション、アクションは // モジュールを使用しないときと同様に登録される console.log(store.getters.squared) // -> 100 store.commit('increment', 5) store.dispatch('incrementAsync', { type: 'two' }) console.log(store.state.counter.count) console.log(store.getters.squared)
$(document).ready(function() { $("#botao_teste").click(function(){ $nome = document.getElementById("nome").value; $senha = document.getElementById("senha").value; $.ajax({ url : "ServletLogin", data : {nome:$nome, senha:$senha, acao:"inserir"}, method : "POST", dataType : "xml", success : function(xml) { $("#resultado").html( $("valor", xml).text() ); }, error : function(xhr, status) { alert('Desculpe, aconteceu um problema!'); }, complete : function(xhr, status) { alert('A requisição está completa!'); } }); }); });
const titleGen = new ml5.charRNN('./models/titles'); const descriptionGen = new ml5.charRNN('./models/descriptions'); const meaningGen = new ml5.charRNN('./models/meanings'); const guideGen = new ml5.charRNN('./models/guide'); console.log('titlegen: ', titleGen); let cards = []; function setup() { generateButton = select("#generate"); downloadButton = select("#download"); //TODO: disable button until title and text are generated generateButton.mousePressed(generate); downloadButton.mousePressed(download); } function generate() { let card ={}; generateButton.attribute('disabled', true); // generate title from titles model let title = titleGen.generate({ seed: 'The', length: getRandomArbitrary(8, 25) , temperature: 0.5}, (e, r) => { card['title'] = 'The' + r.sample; }); // generate description from Guide to Tarot Meanings model let guide = guideGen.generate({ seed: 'A ', length: getRandomArbitrary(50, 400) , temperature: 0.5}, (e, r) => { card['desc'] = 'A ' + r.sample; cards.push(card); console.log('currentcard: ', card); console.log('cards: ', cards); // display card info select('#currentcard').html(`Title: ${card.title}<br><br> Description: ${card.desc}<br><br> Cards in Deck: ${cards.length}`); //dumb that p5 doesn't have this function but whatever document.getElementById('generate').removeAttribute('disabled'); }); } // Function to download data to a file function download() { var file = new Blob([JSON.stringify(cards)], {type: 'json'}); if (window.navigator.msSaveOrOpenBlob) // IE10+ window.navigator.msSaveOrOpenBlob(file, 'cards.json'); else { // Others var a = document.createElement("a"), url = URL.createObjectURL(file); a.href = url; a.download = 'cards.json'; document.body.appendChild(a); a.click(); setTimeout(function() { document.body.removeChild(a); window.URL.revokeObjectURL(url); }, 0); } } function getRandomArbitrary(min, max) { return Math.random() * (max - min) + min; }
import { defineMessages } from 'react-intl'; export const scope = 'app.containers.CreateAd'; export default defineMessages({ title: { id: `${scope}.title`, defaultMessage: 'Новое заявление', }, vacation: { id: `${scope}.vacation`, defaultMessage: 'Очередной отпуск', }, dayOff: { id: `${scope}.dayOff`, defaultMessage: 'Отпуск за свой счёт', }, dayError: { id: `${scope}.dayError`, defaultMessage: 'выберите корректный период', }, cancel: { id: `${scope}.cancel`, defaultMessage: 'Отмена', }, draft: { id: `${scope}.draft`, defaultMessage: 'Сохранить черновик', }, send: { id: `${scope}.send`, defaultMessage: 'Отправить на подпись', }, dayFrom: { id: `${scope}.dayFrom`, defaultMessage: 'С', }, dayTo: { id: `${scope}.dayTo`, defaultMessage: 'По', }, period: { id: `${scope}.period`, defaultMessage: 'Продолжительность:', }, departmentManager: { id: `${scope}.departmentManager`, defaultMessage: 'Руководитель отдела:', }, projectManager: { id: `${scope}.projectManager`, defaultMessage: 'Проектный менеджер:', }, });
"use strict"; require('choices.js/public/assets/scripts/choices.min.js'); exports.new = element => { return options => { // let opts = require('../../output/Chosen.Chosen').optionsToObject(options); let opts = {} return () => { console.log(Choices); let choices = new Choices(element, {addItems: true}); return choices; } } }; exports.destroy = element => { return () => { element.destroy(); }}; exports.init = element => { return () => { element.init(); }}; exports.highlightAll = element => { return () => { element.highlightAll(); }}; exports.unhighlightAll = element => { return () => { element.unhighlightAll(); }}; exports.removeActiveItemsByValue = element => { return value => { return () => { element.removeActiveItemsByValue(value); }}}; exports.removeActiveItems = element => { return excludedId => { return () => { element.removeActiveItems(excludedId); }}}; exports.removeHighlightedItems = element => { return () => { element.removeHighlightedItems(); }}; exports.showDropdown = element => { return () => { element.showDropdown(); }}; exports.hideDropdown = element => { return () => { element.hideDropdown(); }}; exports.clearChoices = element => { return () => { element.clearChoices(); }}; exports.getValueValue = element => { return () => { return element.getValue(true); }}; exports.getValueObject = element => { return () => { return element.getValue(); }}; exports.setValue = element => { return items => { return () => { element.setValue(items); }}}; exports.setChoiceByValue = element => { return value => { return () => { element.setChoiceByValue(value); }}}; exports.clearStore = element => { return () => { element.clearStore(); }}; exports.clearInput = element => { return () => { element.clearInput(); }}; exports.disable = element => { return () => { element.disable(); }}; exports.enable = element => { return () => { element.enable(); }}; exports.setChoices = element => { return choices => { return value => { return label => { return replaceChoices => { return () => { element.setChoices(choices, value, label, replaceChoices); } } } } }};
import uuid from 'uuid/v4'; import Note from '../models/note'; import Lane from '../models/lane'; export function addNote(req, res) { if (!req.body.task) { res.status(403).end(); } const newNote = new Note(req.body); newNote.id = uuid(); newNote.save((err, saved) => { if (err) { res.status(500).send(err); } Lane.findOne({ id: req.params.laneId }) .then(lane => { lane.notes.push(saved); return lane.save(); }) .then(() => { res.json(saved); }); }); } export function editNote(req, res) { if (!req.body.task) { res.status(403).end(); } Note.findOneAndUpdate({ id: req.params.noteId }, req.body, (err, old) => { if (err) { res.status(500).send(err); } res.json({ old }); }); } export function deleteNote(req, res) { Note.findOne({ id: req.params.noteId }, (err, note) => { if (err) { res.status(500).end(); } const mongoId = note._id; note.remove((err) => { if (err) { res.status(500).end(); } Lane.findOne({ id: req.params.laneId }) .then(lane => { lane.notes.remove(mongoId); lane.save(); }) .then(() => { res.json({ status: 'Note removed!' }); }); }); }); }
import React, { useState } from 'react'; import { Modal } from 'react-bootstrap'; import { useForm } from 'react-hook-form'; import bcrypt from 'bcryptjs'; import { useDispatch, useSelector } from 'react-redux'; import { updateUser } from '../../../redux/userReducers'; import LoadingSpinner from '../../Helpers/LoadingSpinner'; import { encrypt } from '../../Helpers/encryption'; const ChangePasswordModal = ({ show, setShow }) => { const { register, handleSubmit, formState: { errors } } = useForm() const dispatch = useDispatch() const { user, userErrors, isUserLoading } = useSelector(state => state.user) const [passwordErrors, setPasswordErrors] = useState(""); const updatePassword = ({ oldPassword, newPassword, confirmPassword }) => { setPasswordErrors("") if (newPassword === confirmPassword) { // Creating new form data const formData = new FormData() // Hashing the new password newPassword = bcrypt.hashSync(newPassword, 7) // Creating a new user object let newUser = { oldPassword, newPassword, username: user.username } // Encrypting the user obj newUser = encrypt(newUser) // Adding encrypted new user to the form data formData.append("user", newUser) // Dispatching update user action dispatch(updateUser(formData)) } else { setPasswordErrors("Passwords did not match.") } } return ( <Modal show={show} onHide={() => setShow(false)} backdrop="static" keyboard={false} centered > <Modal.Header closeButton> <Modal.Title>Change Password</Modal.Title> </Modal.Header> <Modal.Body> <form onSubmit={handleSubmit(updatePassword)}> {/* Old Password */} <div className="form-floating mt-4"> <input type="password" className="form-control" name="oldPassword" id="oldPassword" placeholder="#" {...register("oldPassword", { required: true })} /> <label htmlFor="oldPassword">Old Password</label> {errors.oldPassword?.type === "required" && <p className="alert alert-danger py-2 mt-2">Old Password is required</p>} </div> {/* New Password */} <div className="form-floating mt-4"> <input type="password" className="form-control" name="newPassword" id="newPassword" placeholder="#" {...register("newPassword", { required: true })} /> <label htmlFor="newPassword">New Password</label> {errors.newPassword?.type === "required" && <p className="alert alert-danger py-2 mt-2">New Password is required</p>} </div> {/* Confirm Password */} <div className="form-floating mt-4"> <input type="password" className="form-control" name="confirmPassword" id="confirmPassword" placeholder="#" {...register("confirmPassword", { required: true })} /> <label htmlFor="confirmPassword">Confirm Password</label> {errors.confirmPassword?.type === "required" && <p className="alert alert-danger py-2 mt-2"> Confirm Password is required</p>} </div> {userErrors && <p className="alert alert-danger w-50 text-center mx-auto py-2 mt-2">{userErrors}</p>} {passwordErrors && <p className="alert alert-danger py-2 mt-2">{passwordErrors}</p>} <div className="text-center mt-4"> {isUserLoading && <LoadingSpinner message=" Saving Changes..." />} <button type="submit" className="btn btn-danger mt-4">Update</button> <button className="btn btn-secondary ms-4 mt-4" onClick={() => setShow(false)}>Cancel</button> </div> </form> </Modal.Body> </Modal> ); } export default ChangePasswordModal;
const express = require('express'); const router = express.Router(); const users = require('../data/users.json') const fs = require('fs') router.post('/:id', (req, res) => { const { id } = req.params const { status } = req.body const userFind = users.find((user) => user.id === Number(id)); if (typeof (status) !== 'boolean') { res.status(401).send({ message: "status isn't a boolean" }) } if (!userFind) { res.send({ message: "user isn't found" }) } users[users.indexOf(userFind)].isActive = status fs.writeFile(__dirname+'/../data/users.json',JSON.stringify(users,null,' '),(err) => { if(err) { throw err } }) res.send({ message:status ? 'Usuario ativado' : 'Usuario desativado' }) }) module.exports = router;
import App from "./App"; window.customElements.define("the-app", App); const main = document.getElementById("main"); const app = document.createElement("the-app"); main.appendChild(app);
var _number_mngr_8cpp = [ [ "PagedArray", "class_paged_array.html", "class_paged_array" ], [ "ToQuickSort", "class_to_quick_sort.html", "class_to_quick_sort" ], [ "FileScanner", "class_file_scanner.html", "class_file_scanner" ], [ "main", "_number_mngr_8cpp.html#ae66f6b31b5ad750f1fe042a706a4e3d4", null ] ];
const cats = [ { name: "Blob", age: 10 }, { name: "Harold", }, { name: "Blurt", age: 21 } ]; /* Question 1 */ const cat = { complain: function () { console.log("Meow"); } } cat.complain(); /* Question 2 */ const heading = document.querySelector("h3"); heading.innerHTML = "Updated heading"; /* Question 3 */ heading.style.fontSize = "2em"; /* Question 4 */ heading.classList.add("subheading") /* Question 5 */ const paragraphs = document.querySelectorAll("p"); paragraphs.forEach(p => { p.style.color = "red"; }); /* Question 6 */ const resultsContainer = document.querySelector(".results"); resultsContainer.innerHTML = "<p>New paragraph</p>"; resultsContainer.style.backgroundColor = "yellow"; /* Question 7 */ function writeNames(list) { list.forEach(entry => { console.log(entry.name); }); } writeNames(cats); /* Question 8 */ const catContainer = document.querySelector(".cat-container"); function createCats(cats) { let catObj; for (let i = 0; i < cats.length; i++) { let cat = cats[i]; if (!cat.hasOwnProperty("age")) { cat.age = "Age unknown"; } catObj += `<div><h5>${cat.name}</h5><p>${cat.age}</p></div>`; } catContainer.innerHTML += catObj; } createCats(cats);
Eutil = require('ethereumjs-util'); EcommerceStore = artifacts.require("./EcommerceStore.sol"); module.exports = function(callback) { current_time = Math.round(new Date() / 1000); amt_1 = web3.toWei(1, 'ether'); EcommerceStore.deployed().then(function(contractInstance,error) {contractInstance.addProductToStore('iphone 5', 'Cell Phones & Accessories', 'QmXd9sgchuRFJvRdQJpjgg73R8JzSPtffKMJP8qj5iTAzA','desc',current_time,20000,0)}); EcommerceStore.deployed().then(function(i,error) {i.productIndex.call().then(function(f){console.log(f)})}); }
const apiUrl = `https://api.coindesk.com/v1/bpi/historical/close.json` axios .get(apiUrl) .then(responseFromAPI => { console.log(responseFromAPI); const BTCValue = responseFromAPI.data.bpi; const dates = Object.keys(BTCValue); const values = Object.values(BTCValue); const maxPrice = Math.max(...values); const minPrice = Math.min(...values); document.getElementById('max').innerText = maxPrice; document.getElementById('min').innerText = minPrice; printTheChart(dates, values); }) .catch(err => console.log(err)); const getBTCValue = () => { const startDate = document.getElementById('start').value; const endDate = document.getElementById('end').value; const currency = document.getElementById('currency').value; axios .get(`https://api.coindesk.com/v1/bpi/historical/close.json?start=${startDate}&end=${endDate}&currency=${currency}`) .then( responseFromAPI => { console.log(responseFromAPI); const BTCValue = responseFromAPI.data.bpi; const dates = Object.keys(BTCValue); const values = Object.values(BTCValue); const maxPrice = Math.max(...values); const minPrice = Math.min(...values); document.getElementById('max').innerText = maxPrice; document.getElementById('min').innerText = minPrice; printTheChart(dates, values); }) .catch(err => console.log(err)); } function printTheChart(dates, values) { const ctx = document.getElementById('bitcoin-canvas').getContext('2d'); ctx.clearRect(0, 0, 700, 400); const chart = new Chart(ctx, { type: 'line', data: { labels: dates, datasets: [ { label: 'BTC Chart', backgroundColor: 'rgb(255, 99, 132)', borderColor: 'rgb(255, 99, 132)', data: values } ] } }); } document.getElementById('canvas-update').addEventListener('click', () => { getBTCValue(); });
import React from "react"; import Grid from "@material-ui/core/Grid"; import InputLabel from "@material-ui/core/InputLabel"; import FormControl from "@material-ui/core/FormControl"; import Select2 from "react-select"; import withStyles from "@material-ui/core/styles/withStyles"; import isEqual from "lodash/isEqual"; import "react-select/dist/react-select.css"; import Snackbar from "@material-ui/core/Snackbar"; import GridItem from "../../../components/Grid/GridItem"; import Card from "../../../components/Card/Card"; import CardBody from "../../../components/Card/CardBody"; import CardHeader from "../../../components/Card/CardHeader"; import CardFooter from "../../../components/Card/CardFooter"; import CustomInput from "../../../components/CustomInput/CustomInput"; import BezopSnackBar from "../../../assets/jss/bezop-mkr/BezopSnackBar"; import Button from "../../../components/CustomButtons/Button"; import Validator from "../../../helpers/validator"; // The component Style const styles = theme => ({ root: { display: "flex", flexWrap: "wrap", }, formControl: { margin: theme.spacing.unit, width: "100%", }, selectEmpty: { marginTop: theme.spacing.unit * 2, }, input: { display: "none", }, fluidButton: { ...theme.button, width: "100%", }, }); class AddCategory extends React.Component { constructor(props) { super(props); // we use this to make the card to appear after the page has been rendered this.state = { categoryDetails: { name: "", description: "", parent: "0", kind: "", }, selectedCategoryKind: null, categoryKindSelect: "react-select-label-hidden", selectedCategoryParent: null, categoryParentSelect: "react-select-label-hidden", selectedCategoryCollection: null, categoryCollectionSelect: "react-select-label-hidden", snackBarOpen: false, snackBarMessage: "", }; } componentWillReceiveProps(newProps) { const { productCategory, onHandleModalClose } = this.props; if (Validator.propertyExist(newProps, "productCategory", "addCategory") && (isEqual(productCategory.addCategory, newProps.productCategory.addCategory) === false)) { if (typeof newProps.productCategory.addCategory === "string") { this.setState({ snackBarOpen: true, snackBarMessage: newProps.productCategory.addCategory, }); return false; } this.setState({ categoryDetails: { name: "", description: "", parent: "0", kind: "", collections: "", }, selectedCategoryKind: null, categoryKindSelect: "react-select-label-hidden", selectedCategoryParent: null, categoryParentSelect: "react-select-label-hidden", }); onHandleModalClose(); } return false; } onCloseHandler = () => { this.setState({ snackBarOpen: false }); } onOpenHandler = () => { this.setState({ snackBarOpen: false }); } // Setting the state of all input feilds setCategoryDetails = (type, value) => { const { categoryDetails } = this.state; const newcategoryDetails = JSON.parse(JSON.stringify(categoryDetails)); newcategoryDetails[type] = value; this.setState({ categoryDetails: newcategoryDetails, }); } // Get the value of Input Element handleChange = (event) => { this.setCategoryDetails(event.target.name, event.target.value); }; // This handles the categoryy select element handleCategoryKindChange = (selectedCategoryKind) => { this.setState({ selectedCategoryKind }); if (selectedCategoryKind !== null) { this.setCategoryDetails("kind", selectedCategoryKind.value); this.setState({ categoryKindSelect: "react-select-label-visible", }); } else { this.setState({ categoryKindSelect: "react-select-label-hidden", }); this.setCategoryDetails("kind", ""); this.setCategoryDetailsSpecialError("kind", null); } } handleCategoryParentChange = (selectedCategoryParent) => { this.setState({ selectedCategoryParent }); if (selectedCategoryParent !== null) { this.setCategoryDetails("parent", selectedCategoryParent.value); this.setState({ categoryParentSelect: "react-select-label-visible", }); } else { this.setState({ categoryParentSelect: "react-select-label-hidden", }); this.setCategoryDetails("parent", "0"); } } handleCategoryCollectionChange = (selectedCategoryCollection) => { this.setState({ selectedCategoryCollection }); if (selectedCategoryCollection !== null) { this.setCategoryDetails("collections", selectedCategoryCollection.value); this.setState({ categoryCollectionSelect: "react-select-label-visible", }); } else { this.setState({ categoryCollectionSelect: "react-select-label-hidden", }); this.setCategoryDetails("collections", null); } } // Create new Category createNewCategory = () => { const { categoryDetails } = this.state; const { addProductCategory } = this.props; addProductCategory(categoryDetails); } render() { const { classes, categories, collections } = this.props; const { categoryDetails, categoryKindSelect, selectedCategoryKind, categoryParentSelect, selectedCategoryParent, snackBarOpen, snackBarMessage, selectedCategoryCollection, categoryCollectionSelect, } = this.state; return ( <div> <Card> <CardHeader color="primary"> <div> <h4> Add New Product Category </h4> </div> <div> <p> Product Category Details </p> </div> </CardHeader> <CardBody> <Grid container> <GridItem xs={12} sm={12} md={4}> <CustomInput labelText="Category Name" id="name" inputProps={{ value: categoryDetails.name, name: "name", onChange: this.handleChange, }} formControlProps={{ fullWidth: true, required: true, }} /> </GridItem> <GridItem xs={12} sm={12} md={4}> <FormControl className={classes.formControl}> <InputLabel htmlFor="selectedCategoryKind" className={categoryKindSelect}> Type or Select Category Kind </InputLabel> <Select2 id="selectedCategoryKind" name="selectedCategoryKind" value={selectedCategoryKind} placeholder="Type or Select Category Kind" onChange={this.handleCategoryKindChange} options={[ { value: "digital", label: "Digital" }, { value: "physical", label: "Physical" }, ]} /> </FormControl> </GridItem> <GridItem xs={12} sm={12} md={4}> <FormControl className={classes.formControl}> <InputLabel htmlFor="selectedCategoryCollection" className={categoryCollectionSelect}> Type or Select Collection </InputLabel> <Select2 id="selectedCategoryCollection" name="selectedCategoryCollection" value={selectedCategoryCollection} placeholder="Type or Select Collection Category" onChange={this.handleCategoryCollectionChange} options={ collections .map(collection => ({ value: collection.id, label: collection.name.replace(/\^w/, c => c.toUpperCase()), }))} /> </FormControl> </GridItem> <GridItem xs={12} sm={12} md={4}> <FormControl className={classes.formControl}> <InputLabel htmlFor="selectedCategoryParent" className={categoryParentSelect}> Type or Select Parent Category </InputLabel> <Select2 id="selectedCategoryParent" name="selectedCategoryParent" value={selectedCategoryParent} placeholder="Type or Select Parent Category" onChange={this.handleCategoryParentChange} options={categories .filter(category => category.parent === "0") .map(category => ({ value: category.id, label: category.name }))} /> </FormControl> </GridItem> </Grid> <Grid container> <GridItem xs={12}> <CustomInput labelText="Description" id="description" formControlProps={{ fullWidth: true, }} inputProps={{ multiline: true, rows: 5, name: "description", onChange: this.handleChange, value: categoryDetails.description, }} /> </GridItem> </Grid> </CardBody> <CardFooter> <Grid container> <GridItem xs={12}> <Button variant="contained" color="primary" component="span" className={classes.fluidButton} onClick={this.createNewCategory}> Create Product Category </Button> </GridItem> </Grid> </CardFooter> </Card> <Snackbar anchorOrigin={{ vertical: "top", horizontal: "center" }} open={snackBarOpen} onClose={this.onCloseHandler} > <BezopSnackBar onClose={this.onCloseHandler} variant="error" message={snackBarMessage} /> </Snackbar> </div> ); } } export default withStyles(styles)(AddCategory);
function countingSort(list, minNum, maxNum) { var range = maxNum - minNum + 1, count = new Array(range); list.forEach(function (num) { count[num - minNum] = count[num - minNum] ? count[num - minNum] + 1 : 1; }); curr = 0; for (var i = 0; i < count.length; ++i) { while (count[i] > 0) { list[curr++] = i + minNum; count[i]--; } } return list; } console.log(countingSort([5,3,1,1,5,3,4,3,1,1], 1, 5));
const nameSelectJQuery = $(".node-select"); const typeSelectJQuery = $("#type-select"); const nodeQuery = $("#node-query"); const ignoreQuery = $("#ignore-query"); const allConnections = $("#all-connections-button button"); const minConnections = $("#min"); const nameSelectD3 = d3.select("#name-select"); const newNameSelectD3 = d3.select("#new-name-select"); const typeSelectD3 = d3.select("#type-select"); const auxNode = $("#aux-button button"); const nodes = []; const edges = []; const allNames = new Set(); const allNewNames = new Set(); const allTypes = new Set(); const selectedNames = new Set(); const selectedTypes = new Set(); const parseDate = d3.timeParse("%Y-%m-%d"); const formatDate = d3.timeFormat("%Y-%m-%d"); const formatDateTime = d3.timeFormat("%b %d %Y %H:%M:%S"); let dateRange = []; let dateExtent = null; let dataTable = null; /** * Parse query values, make request, and process query response. Initialize data structures and handlers for the plots. */ async function parseData() { let queryOptions = parseQueryOptions(); let rows try { rows = await makeRequest(queryOptions[0], queryOptions[1], queryOptions[2], queryOptions[3]); } catch(e) { window.alert(e); return; } let tempNames = new Set(); allNames.forEach(d => tempNames.add(d)); allNewNames.forEach(d => tempNames.add(d)); reset(); let tempNodes = {}; rows.forEach(d => { allNames.add(d.source); allNames.add(d.target); allTypes.add(d.type); // Create entry for node if it does not yet exist. Avoid duplicate entries. tempNodes[d.source] || (tempNodes[d.source] = {"name": d.source}); tempNodes[d.target] || (tempNodes[d.target] = {"name": d.target}); d.date = new Date(d.datetime); edges.push({"source": tempNodes[d.source], "target": tempNodes[d.target], "date": d.date, "type": d.type}); }); // Push all node objects into the nodes array. Object.values(tempNodes).forEach(d => nodes.push(d)); // Remove names that have previously appeared from allNames and add them to allNewNames. allNames.forEach(d => { if(!tempNames.has(d)) { allNames.delete(d); allNewNames.add(d); } }) initPlotData(rows); calculateTotals(); } /** * Make request to the server using the given query parameters. Retrieve and return query results. * @param nodes A list of the network nodes to include in the query request. * @param ignore A list of the network nodes to ignore in the query request. * @param min The minimum number of connections a node should have in the query request. * @param all Include all connections for all queried nodes if true. Else, only return connections chosen by the server. * @throws Throws an error if the server indicates too many interactions were returned by the query. * @returns {Promise<any>} The query results containing rows of network data. */ async function makeRequest(nodes, ignore, min, all) { let options = { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({'nodes': nodes, 'ignore': ignore, 'min': min, 'all': all}) }; let response = await fetch(fetchURL, options); if(response.status === 430) { throw "Too many interactions to display."; } return await response.json(); } /** * Extract query option values from the user interface. * @returns {(*|string)[]} */ function parseQueryOptions() { return [ nodeQuery.select2('data'), ignoreQuery.select2('data'), minConnections.val(), allConnections.hasClass('active') ]; } /** * Initialize data and data handlers from the queried network rows. * @param rows The queried network rows. */ function initPlotData(rows) { dateExtent = d3.extent(rows, d => parseDate(formatDate(d.date))); dateExtent[0] = d3.timeDay.offset(dateExtent[0], -7); dateExtent[1] = d3.timeDay.offset(dateExtent[1], 7); allNames.forEach(d => selectedNames.add(d)); allNewNames.forEach(d => selectedNames.add(d)); allTypes.forEach(d => selectedTypes.add(d)); // Create buttons for each queried node name and type. nameSelectD3.selectAll("button:not(.keep)").data(Array.from(allNames)).join("button") .on("click", updateNameSelect).attr("data-toggle", "button") .attr("class", "col btn btn btn-light active").attr("onclick", "this.blur();").text(d => d); newNameSelectD3.selectAll("button:not(.keep)").data(Array.from(allNewNames)).join("button") .on("click", updateNameSelect).attr("data-toggle", "button") .attr("class", "col btn btn btn-light active").attr("onclick", "this.blur();").text(d => d); typeSelectD3.selectAll("button:not(.keep)").data(Array.from(allTypes)).join("button") .on("click", updateTypeSelect).attr("data-toggle", "button") .attr("class", "col btn btn btn-light active").attr("onclick", "this.blur();").text(d => d); } /** * Reset all data structures. */ function reset() { allNames.clear(); allNewNames.clear(); allTypes.clear(); selectedNames.clear(); selectedTypes.clear(); nodes.length = 0; edges.length = 0; dateRange = []; brushSelection = null; dateExtent = null; dateScale = null; brush = null; filteredEdges = null; } /** * Toggle the selection of the given node name. * @param name The node name to toggle. */ function updateNameSelect(name) { selectedNames.has(name) ? selectedNames.delete(name) : selectedNames.add(name); calculateTotals(); } /** * Toggle the selection of the given node type. * @param type The node type to toggle. */ function updateTypeSelect(type) { selectedTypes.has(type) ? selectedTypes.delete(type) : selectedTypes.add(type); calculateTotals(); } function selectAllNames() { allNames.forEach(d => selectedNames.add(d)); allNewNames.forEach(d => selectedNames.add(d)); nameSelectJQuery.find("button:not(.active):not(.keep)").addClass("active"); calculateTotals(); } function selectAllTypes() { allTypes.forEach(d => selectedTypes.add(d)); typeSelectJQuery.find("button:not(.active):not(.keep)").addClass("active"); calculateTotals(); } function removeAllNames() { allNames.forEach(d => selectedNames.delete(d)); allNewNames.forEach(d => selectedNames.delete(d)); nameSelectJQuery.find("button.active").removeClass("active"); calculateTotals(); } function removeAllTypes() { allTypes.forEach(d => selectedTypes.delete(d)); typeSelectJQuery.find("button.active").removeClass("active"); calculateTotals(); } function updateTable() { let tableEdges = []; edges.forEach(function(d) { if(d.date >= dateRange[0] && d.date <= dateRange[1] && selectedTypes.has(d.type)) { let hasNode = auxNode.hasClass('active') ? selectedNames.has(d.source.name) || selectedNames.has(d.target.name) : selectedNames.has(d.source.name) && selectedNames.has(d.target.name); if(hasNode) { tableEdges.push([d.source.name, d.target.name, d.type, formatDateTime(d.date)]); } } }); dataTable.clear(); tableEdges.forEach(d => dataTable.row.add(d)); dataTable.draw(); } $(document).ready(function() { nodeQuery.select2({ ajax: { url: nodeURL, dataType: 'json', delay: 500, cache: true, }, minimumInputLength: 1, placeholder: 'Search for a node', cache: true }); ignoreQuery.select2({ ajax: { url: nodeURL, dataType: 'json', delay: 500, cache: true, }, minimumInputLength: 1, placeholder: 'Search for a node', cache: true }); auxNode.on("click", () => { auxNode.hasClass("active") ? auxNode.removeClass("active") : auxNode.addClass("active"); calculateTotals(); updateTable(); }); allConnections.on("click", () => { allConnections.hasClass("active") ? allConnections.removeClass("active") : allConnections.addClass("active"); }); forceOptions.on("input", updateForces); $.fn.dataTable.moment("MMM D YYYY H:m:s"); dataTable = $("#summary-table").DataTable({ columns: [{title: "Source"}, {title: "Target"}, {title: "Type"}, {title: "Datetime"}], order: [3, "asc"], bLengthChange: false, info: false, deferRender: true }); });
const test = require('tape'); const solveRPN = require('./solveRPN.js'); test('Testing solveRPN', (t) => { //For more information on all the methods supported by tape //Please go to https://github.com/substack/tape t.true(typeof solveRPN === 'function', 'solveRPN is a Function'); //t.deepEqual(solveRPN(args..), 'Expected'); //t.equal(solveRPN(args..), 'Expected'); //t.false(solveRPN(args..), 'Expected'); //t.throws(solveRPN(args..), 'Expected'); t.end(); });
// const obj = { // name:'Vikram', // getName(){ // return this.name; // } // }; // // console.log(obj.getName()); // const getNamme = obj.getName; // this actually broken the this.binding. when we create getNamme we created a refernce to obj.getName // console.log(getNamme()); // the same code will run just like if we run obj.getName() both of them will try to return this.name // //the problem is the CONTEXT that is run. // //obj.getName is in a context of an OBJECT so we have access to that Object as of this binding . but when we break it to a function we loose that context // //the context doesnt get transfered, now we just have a regular function, regular function have 'undefined' for their 'this' by default just like the following example // // const func =function (){ // console.log(this); // }; // // func(); // const getNamme = obj.getName.bind(obj); // bind gets as an argument the this.context. obj.getName.bind() and obj.getName are actually the same, it will return the function back // const getNamme = obj.getName.bind({Name: 'Vikram'}); // We forced the this.context for getNamme to be that Object ({Name: 'Vikram'}) class IndecisionApp extends React.Component{ constructor(props){ super(props); this.state = { options : props.options }; this.handleDeleteOptions = this.handleDeleteOptions.bind(this); this.handlePick = this.handlePick.bind(this); this.handleAddOption = this.handleAddOption.bind(this); this.handleDeleteOption = this.handleDeleteOption.bind(this); } componentDidMount(){ try{ const json = localStorage.getItem('options'); const options = JSON.parse(json); if(options){ this.setState(()=>({options})); console.log('fetching data'); } }catch(e){ //Do nothing at all } } componentDidUpdate(prevProps,prevState){ if(prevState.options.length !== this.state.options.length){ const json = JSON.stringify(this.state.options); localStorage.setItem('options',json) } } componentWillUnmount(){ console.log('componentWillUnmount'); } handleDeleteOption(optionToRemove){ this.setState((prevState) => ({ options : prevState.options.filter((option)=> optionToRemove !== option) })); } handleDeleteOptions (){ // this.setState(() => { // return { // options : [] // }; // }); this.setState(() => ({ options: [] })) } handlePick (){ const randomNum = Math.floor(Math.random() * this.state.options.length); const option = this.state.options[randomNum]; alert(option); } handleAddOption (option){ if(!option){ return 'Enter valid value to add item' }else if(this.state.options.indexOf(option) > -1){ return 'This option already exists' } this.setState((prevState)=>({ options: prevState.options.concat([option]) })); // this.setState((prevState) => { // console.log(`Option is ${option}`); // return{ // options: prevState.options.concat([option]) // // options: this.state.options.push(option) // } // }); console.log(option); } render(){ const title = 'Indecision' const subtitle = 'Put Your life in the hands of a computer'; //const options = ['Thing One','Thing Two','Thing Four']; return( <div> <Header title="Test Value" subtitle={subtitle}/> <Header title={title}/> <Action hasOptions={this.state.options.length > 0} handlePick={this.handlePick}/> {/*{this.state.options.length && <Action />}*/} {/*Options gets re render with a set of brand new set of props, handleDeleteOptions did not changed but the value for options did * so it is important to note that when our component like options cannot change its own 'props' new prop values can be passed down from the * parent and those will trigger re render in the child*/} <Options handleDeleteOptions={this.handleDeleteOptions} handleDeleteOption = {this.handleDeleteOption} options={this.state.options}/> <AddOption handleAddOption={this.handleAddOption}/> </div> ) } } IndecisionApp.defaultProps = { options: [] }; const Header = (props) => { return( <div> <h1>Indecision</h1> <h2>Put your life in the hands of a computer</h2> <h3>{props.title}</h3> </div> ); }; Header.defaultProps ={ title: 'Indecision' }; // class Header extends React.Component{ // render(){ // console.log(this.props); // return( // <div> // <h1>Indecision</h1> // <h2>Put your life in the hands of a computer</h2> // <h3>{this.props.title}</h3> // </div> // ); // } // } const Action = (props) => { return( <div> <button disabled={!props.hasOptions} onClick={props.handlePick}>What should i do?</button> </div> ) }; // class Action extends React.Component{ // // render(){ // return( // <div> // <button disabled={!this.props.hasOptions} onClick={this.props.handlePick}>What should i do?</button> // </div> // ) // } // } const Options = (props) => { return( <div> <button onClick={props.handleDeleteOptions}>Remove All</button> {props.options.length === 0 && <p>Please add an option to get started!</p>} { props.options.map((option) => ( <Option key={option} optionText={option} handleDeleteOption={props.handleDeleteOption} /> )) } </div> ) }; // class Options extends React.Component { // // constructor(props){ //its not an event callback like 'this.handleRemoveAll' so like 'render' the 'context' is correct by default // // super(props); // // this.handleRemoveAll = this.handleRemoveAll.bind(this); // by doing this we insure that whenever we call handleRemoveAll the context is correct // // } // render(){ // return( // <div> // <button onClick={this.props.handleDeleteOptions}>Remove All</button> // { // this.props.options.map((option) => <Option key={option} optionText={option}></Option>) // } // </div> // ) // } // } const Option =(props) => { return( <div> {props.optionText} <button onClick={(e) => { props.handleDeleteOption(props.optionText) }} >Remove</button> </div> ) }; // class Option extends React.Component { // render(){ // return( // <div> // {this.props.optionText} // </div> // ) // } // } class AddOption extends React.Component{ constructor(props){ super(props); this.state = { error: undefined }; this.handleAddOption = this.handleAddOption.bind(this); } handleAddOption(e){ //we dont have access to the const defined in the IndecisionApp class since we lost the bind in order to fix it we will pass to the handleAddOption with bind the 'this' e.preventDefault(); const option = e.target.elements.option.value.trim(); const error = this.props.handleAddOption(option); this.setState(() => ({ error })); if(!error){ e.target.elements.option.value = ''; } // if(error){ // this.setState(()=>({ // error // })); // // this.setState(()=>{ // // return{ // // // error:error // // error // // } // // // // }) // } } render(){ return( <div> {this.state.error && <p>{this.state.error}</p>} <form onSubmit={this.handleAddOption}> <input type="text" name="option" id="option"/> <button>Add Option</button> </form> </div> ) } } const User = (props) => { return ( <div> <p>Name: {props.name}</p> <p>Age: {props.age}</p> </div> ) } const jsxx = ( <div> <Header /> <Action /> <Options /> <AddOption/> </div> ); ReactDOM.render(<IndecisionApp/>,document.getElementById('app')); // ReactDOM.render(<IndecisionApp options={['Devils Den','Second District']}/>,document.getElementById('app'));
$(function(){$(".datepicker").datetimepicker({format:"DD MMM YYYY"})});
/** * General Handler for Controlling the modes of the Touchstrips * * @param {TrackBankContainer} mixerTrackBank * @param {TrackBankContainer} effectTrackBank * @param {int} numTracks * @param {ClipLaunchView} clipview * @param {Device} cursorDevice * @param {TrackHandler} trackHandler */ function SliderModeHandler(mixerTrackBank, effectTrackBank, numTracks, cursorDevice, trackHandler) { var levelButton = controls.createButton(ENCODERBUTTON.LEVEL); var auxButton = controls.createButton(ENCODERBUTTON.AUX); var deviceButton = controls.createButton(ENCODERBUTTON.CONTROL); var macrcoButton = controls.createButton(ENCODERBUTTON.MACRO); var deviceControl = new DeviceSliderControl(cursorDevice, trackHandler); var mixerControl = new MixerSliderControl("mixer", mixerTrackBank, host.createEffectTrackBank(8, 8)); var efxControl = new MixerSliderControl("effect", effectTrackBank); var sliderView = new SliderView(numTracks); transport.setParameterControl(deviceControl); var masterMode = mixerControl; var currentMode = mixerControl; var controlMode = ControlModes.VOLUME; mixerControl.setDisplay(sliderView); currentMode.setMode(controlMode); /** * Make Select the Touch Strip Slider Mode Butto according to current mode **/ function radioModes() { levelButton.sendValue(controlMode === ControlModes.VOLUME || controlMode === ControlModes.PAN ? 127 : 0); auxButton.sendValue(controlMode === ControlModes.AUX ? 127 : 0); deviceButton.sendValue(controlMode === ControlModes.DEVICE || controlMode === ControlModes.MIDI_CC ? 127 : 0); macrcoButton.sendValue(controlMode === ControlModes.MACRO ? 127 : 0); } radioModes(); this.updateTrackColor = function (color) { deviceControl.updateTrackColor(color); }; this.switchToEffectMode = function () { if (masterMode === efxControl) { return; } masterMode = efxControl; if (currentMode.isMixer()) { currentMode.setDisplay(null); currentMode = efxControl; currentMode.setDisplay(sliderView); if (controlMode === ControlModes.AUX) { controlMode = ControlModes.VOLUME; currentMode.setMode(controlMode); radioModes(); } refreshMixerMode(); } }; this.inEffectMode = function () { return masterMode !== mixerControl; }; this.switchToTrackMode = function () { if (masterMode === mixerControl) { return; } masterMode = mixerControl; if (currentMode.isMixer()) { currentMode.setDisplay(null); currentMode = mixerControl; currentMode.setDisplay(sliderView); refreshMixerMode(); } }; function getOffset(slider, value) { var offset = 0; if (slider.touched) { slider.touched = false; slider.downValue = value; } else { var diff = (value - slider.downValue); // Diff needs to be greater than 1 to adjust value in smaller increments if (Math.abs(diff) > 1) { offset = diff > 0 ? 1 : -1; slider.downValue = value; } } return offset; } function changeCCValue(value, slider, index) { noteInput.sendRawMidiEvent(0xB0, 45 + index, value); } function changeDeviceValue(value, slider, index) { var offset = getOffset(slider, value); if (modifiers.isShiftDown()) { if (offset === 0) return; } else { currentMode.setDeviceValue(index, value); } } function changeMacroValue(value, slider, index) { var offset = getOffset(slider, value); if (modifiers.isShiftDown()) { if (offset === 0) return; currentMode.setMacroValue(index, currentMode.getMacroValue(index) + offset); } else { currentMode.setMacroValue(index, value); } } function changeSendLevel(value, slider, index) { var offset = getOffset(slider, value); if (modifiers.isShiftDown()) { if (offset === 0) return; currentMode.setSendLevel(index, currentMode.getSendValue(index) + offset); } else { currentMode.setSendLevel(index, value); } } function handleSliderTouch(index, value) { if (value === 0) { var trackValues = currentMode.values(); currentMode.cleanUpView(index, trackValues[index].volume); } } function changeMixerLevels(value, slider, index) { var offset = getOffset(slider, value); var trackValues = currentMode.values(); if (modifiers.isShiftDown()) { if (offset === 0) return; currentMode.setVolume(index, trackValues[index].volume + offset); } else { currentMode.setVolume(index, value); } } function changePan(value, slider, index) { var offset = getOffset(slider, value); var trackValues = currentMode.values(); if (modifiers.isShiftDown()) { if (offset === 0) return; currentMode.setPan(index, trackValues[index].pan + offset); } else { currentMode.setPan(index, value); } } sliderView.assignSliderCallback(changeMixerLevels, handleSliderTouch); masterMode.setSendsToZeroListener(function () { setToVolumeMode(); }); function setToVolumeMode(showNotification) { switchToMixerMode(ControlModes.VOLUME); controlMode = ControlModes.VOLUME; currentMode.setMode(controlMode); barmode = BarModes.DUAL; sliderView.assignSliderCallback(changeMixerLevels, handleSliderTouch); var trackValues = currentMode.values(); sliderView.setStripValues(BarModes.DUAL, currentMode.getVolume, trackValues); radioModes(); if (showNotification) { host.showPopupNotification("Touchstrip controls Volume"); } } function setToPanMode(showNotification) { switchToMixerMode(ControlModes.PAN); controlMode = ControlModes.PAN; sliderView.assignSliderCallback(changePan); sliderView.setStripValues(BarModes.PAN, currentMode.getPan, currentMode.values()); radioModes(); if (showNotification) { host.showPopupNotification("Touchstrip controls Panning"); } } function refreshMixerMode() { switch (controlMode) { case ControlModes.VOLUME: setToVolumeMode(true); break; case ControlModes.PAN: setToPanMode(true); break; case ControlModes.AUX: setToAuxMode(true); break; } } function setToAuxMode(showNotification) { switchToMixerMode(ControlModes.AUX); controlMode = ControlModes.AUX; sliderView.assignSliderCallback(changeSendLevel); sliderView.setStripValues(BarModes.DOT, currentMode.getSendValue, currentMode.values()); radioModes(); currentMode.showSendIndex(); } function switchToMixerMode(newMode) { if (!currentMode.isMixer()) { currentMode.setDisplay(null); currentMode.setMode(newMode); currentMode = masterMode; currentMode.setDisplay(sliderView); } currentMode.setMode(newMode); } function switchToDeviceMode(newMode) { if (currentMode.isMixer()) { currentMode.setDisplay(null); currentMode.setMode(newMode); currentMode = deviceControl; currentMode.setDisplay(sliderView); } currentMode.setMode(newMode); } levelButton.setCallback(function (value) { if (value === 0) { return; } if (modifiers.isShiftDown()) { if (controlMode !== ControlModes.PAN) { setToPanMode(); } } else { if (controlMode !== ControlModes.VOLUME) { setToVolumeMode(); } } }); auxButton.setCallback(function (value) { if (value === 0 || masterMode.numberOfSends() === 0) { return; } if (controlMode !== ControlModes.AUX) { setToAuxMode(); } else { currentMode.incrementSendIndex(); } }); deviceButton.setCallback(function (value) { transport.notifyModButton(ENCODERBUTTON.CONTROL, value > 0); if (value === 0) { return; } if (modifiers.isShiftDown()) { if (controlMode !== ControlModes.MIDI_CC) { switchToDeviceMode(ControlModes.MIDI_CC); controlMode = ControlModes.MIDI_CC; sliderView.assignSliderCallback(changeCCValue); sliderView.refresh(); currentMode.updateSliders(); radioModes(); host.showPopupNotification("Touchstrip controls Midi CC"); } return; } else if (controlMode !== ControlModes.DEVICE) { if (!deviceControl.hasDevice()) { return; } switchToDeviceMode(ControlModes.DEVICE); controlMode = ControlModes.DEVICE; sliderView.assignSliderCallback(changeDeviceValue); sliderView.refresh(); currentMode.updateSliders(); radioModes(); cursorDevice.selectInEditor(); if (modifiers.isSelectDown()) { cursorDevice.isWindowOpen().toggle(); } host.showPopupNotification("Touchstrip controls Device"); } else if (modifiers.isSelectDown()) { cursorDevice.isWindowOpen().toggle(); } else if (modifiers.isClearDown()){ host.showPopupNotification("TODO clear device ... mit enter ?"); applicationControl.focusDevicePanel(); cursorDevice.selectInEditor(); applicationControl.getApplication().remove(); } currentMode.showParamAssignments(); }); macrcoButton.setCallback(function (value) { transport.notifyModButton(ENCODERBUTTON.MACRO, value > 0); if (value === 0) { return; } if (controlMode !== ControlModes.MACRO) { switchToDeviceMode(ControlModes.MACRO); controlMode = ControlModes.MACRO; sliderView.assignSliderCallback(changeMacroValue); sliderView.refresh(); currentMode.updateSliders(); radioModes(); applicationControl.showDevices(); host.showPopupNotification("Touchstrip controls Macros"); } }); this.exit = function () { host.getMidiOutPort(0).sendSysex("f000210915004d5000010500000000000000000000000000000000f7"); }; }
import {Link} from 'react-router-dom' import './Last.css' function Last(){ return( <div className='last'> <h2 style={{color:'white'}} >thank you for submitting the resume</h2> <h3 style={{color:'white'}} >submit another resume <Link to='/'>here</Link></h3> </div> ) } export default Last;
import React from 'react' const MCOM5332= (props) => { return ( <div> <h1>MCOM 5332</h1> <p>This bit of content comes fropm the {props.activeSection}.js component.</p> <p>MCOM 5332 arguments and content hard-coded here.</p> </div> ) } export default MCOM5332
// /* eslint-disable */ // const mongoose = require('mongoose'); // // 定义Account结构体 // module.exports = mongoose.model('Account', { // accountName: { // type: String, // default: '', // }, // passwd: { // type: String, // default: '', // }, // nickName: { // type: String, // default: '', // }, // balance: { // type: Number, // default: 0.0, // } // });
//this контекст вызова var user= { name: 'Ilya', surname: 'Polyakov', sayHI: function(){ console.log("hi "+ this.name); } fullname: function(){ console.log(this.name+this.surname); } } user.sayHI(); var user2= { ...user }; user2.name='Petya'; user2.fullname();
document.getElementById("channelSend").onkeydown = sendMessage; var calle = false; let localConnection; let remoteConnection; let sendChannel; let receiveChannel; const chatSend = document.getElementById('channelSend'); const wsClient = new WebSocket('ws://localhost:1234'); if (document.location.hash === "" || document.location.hash === undefined) { console.log("Checking for Calls"); var token = Date.now()+"-"+Math.round(Math.random()*10000); var call_token = "#"+token; wsClient.onopen = function() { wsClient.send( JSON.stringify({ token: call_token, type: "join", }) ); document.getElementById("loading_state").innerHTML = "Waiting for a call...ask your friend to visit:<br/><br/>"+document.location+call_token; } wsClient.onmessage = function(event) { var signal = JSON.parse(event.data); console.log("New message received."); if (signal.type === "joinanswer") { if (signal.callee === true) { console.log("Callee join: " + signal.token); document.location.hash = call_token; document.getElementById('dataChannelSend').disabled = true; } else { document.location.hash = signal.token; } } else if (signal.type === "message") { console.log("Message from callee received."); add_message("receive", signal.message); } else if (signal.type === "error_room") { console.log(signal.message); } } } else { call_token = document.location.hash; console.log("Entering in the room with token: " + call_token); wsClient.onopen = function () { wsClient.send( JSON.stringify({ token: call_token, type: "check_room", }) ); } wsClient.onmessage = function(event) { var signal = JSON.parse(event.data); console.log("Caller message received: " + signal.token); if (signal.type === "joinanswer") { if (signal.callee === true) { console.log("Entering the room."); document.location.hash = signal.token; } } else if (signal.type === "message") { console.log("Received message."); add_message("receive", signal.message); } } } function get_time() { var date = new Date(); var hour = date.getHours(); var minute = date.getMinutes(); var time = hour + ":" + minute; return time; } function add_message (type, message) { var text_div = document.createElement("div"); var p = document.createElement("p"); var time = document.createElement("span"); if (type === "send") { text_div.className = "container"; time.className = "time-right"; } else { text_div.className = "container darker"; time.className = "time-left"; } p.innerHTML = message; text_div.appendChild(p); time.innerHTML = get_time(); text_div.appendChild(time); document.body.insertBefore(text_div, document.getElementById("h2")); } function sendMessage(e) { if (e.keyCode == 13) { add_message("send", chatSend.value); wsClient.send( JSON.stringify({ type: "message", token: call_token, message: chatSend.value, }) ); chatSend.value = ""; // Supress the newline character from chatSend when press enter for sending the message. return false; } }
class Watcher { constructor(vm,expOrFn,cb,options){ this.cb = cb; this.vm = vm; Dep.target = this; this.cb.call(this.vm); } update(){ this.cb.call(this.vm); } } export default Watcher;
var Album = require('../models/album'); // POST /albums exports.postAlbums = function(req, res) { var album = new Album({ Title: req.body.Title, Id: req.body.Id, Authors: req.body.Authors, Narrator: req.body.Narrator, Description: req.body.Description, LastUpdateTime: Date.now(), IconUrl: req.body.IconUrl, SeqId: req.body.SeqId }); album.save(function (err) { if (err) { res.statusCode = 400; return res.send(err); } res.json({ message: 'Album created!' }); }); }; // GET /albums exports.getAlbums = function(req, res) { Album.find(function (err, albums) { if (err) { res.statusCode = 400; return res.send(err); } res.json(albums); }); }; // GET albums/:albumId exports.getAlbumByAlbumId = function(req, res) { Album.findById(req.params.albumId, function (err, album) { if (err) { res.statusCode = 400; return res.send(err); } res.json(album); }); }; // PUT albums/:albumId exports.putAlbumByAlbumId = function(req, res) { Album.findById(req.params.albumId, function (err, album) { if (err) { res.statusCode = 400; return res.send(err); } album.title = req.body.title; album.save(function (err) { if (err) { res.statusCode = 400; return res.send(err); } res.json({ message: 'Album updated!' }); }); }); }; // DELETE albums/:albumId exports.deleteAlbumByAlbumId = function(req, res) { Album.remove({ _id: req.params.albumId }, function (err, album) { if (err) { res.statusCode = 400; return res.send(err); } res.json({ message: 'Successfully deleted ' + album.title }); }); };
import { AsyncStorage } from 'react-native' import { Types } from '../reducer/Trips/trips' export const addTrips = (trips, newTrip) => { trips.push(newTrip) AsyncStorage.setItem('trips', JSON.stringify(trips)) return updateTrips(trips) } export const loadTrips = () => async dispatch => { const trips = await AsyncStorage.getItem('trips') if (trips) { dispatch(updateTrips(JSON.parse(trips))) } } export const deleteTrip = (trips, trip) => { const index = trips.map(t=>t.id).indexOf(trip.id) if (index !== -1) { trips.splice(index, 1) AsyncStorage.setItem('trips', JSON.stringify(trips)) } return updateTrips(trips) } export const newPoint = (trips, idTrip, point) => { const trip = trips.find(t => t.id === idTrip) if(trip) { trip.price += parseFloat(point.price) trip.places.push(point) } AsyncStorage.setItem('trips', JSON.stringify(trips)) return updateTrips(trips) } export const editTrip = (trips, trip) => { const index = trips.indexOf(t => t.id) if(index !== -1) { trips[index] = trip AsyncStorage.setItem('trips', JSON.stringify(trips)) } return updateTrips(trips) } const updateTrips = (trips) => ({ type: Types.UPDATE_TRIPS, payload: { trips } })
"use strict"; var Model = require('./../models/activity.model'); var CustomError = require('./../utils/custom-error'); var mongoose = require('mongoose'); // Get All function getAll(req, res, next){ Model.getAll((err, objects)=>{ if(err){return next(err);} if(!objects){return next(new CustomError('No data found',400));} res.status(200).json(objects); }); }; // Get single object by id function getOneById(req, res, next){ if(!mongoose.Types.ObjectId.isValid(req.params.id)){ return next(new CustomError('Invalid Id',400)); } Model.getById(req.params.id,(err, object)=>{ if(err){return next(err);} if(!object){return next(new CustomError('No data found', 400));} res.status(200).json(object); }); }; // Create new object function createObject(req, res, next){ const newObject = new Model({ nombreActividad: req.body.nombreActividad, detalle: req.body.detalle, duracion: req.body.duracion, repeticiones: req.body.repeticiones, peso: req.body.peso }); Model.createObject(newObject, (err, object)=>{ if(err){return next(err);} res.status(200).json(object); }); }; // Remove object function removeObject(req, res, next){ if(!mongoose.Types.ObjectId.isValid(req.params.id)){ return next(new CustomError('Invalid Id',400)); } Model.removeObject(req.params.id, (err, object)=>{ if(err){return next(err);} res.status(200).json(object); }) } // Update object function updateObject(req, res, next){ const data = { nombreActividad: req.body.nombreActividad, detalle: req.body.detalle, duracion: req.body.duracion, repeticiones: req.body.repeticiones, peso: req.body.peso }; Model.updateObject(req.params.id, data, (err, object)=>{ if(err){return next(err);} res.status(200).json(object); }) } module.exports = { getAll: getAll, getOneById: getOneById, createObject: createObject, removeObject: removeObject, updateObject: updateObject };
/* begin copyright text * * Copyright © 2016 PTC Inc., Its Subsidiary Companies, and /or its Partners. All Rights Reserved. * * end copyright text */ /*global module*/ /* jshint node: true */ /* jshint strict: global */ /* jshint camelcase: false */ 'use strict'; var Q = require('q'); var debug = require('debug')('arpublish:share.url'); var Resolutions = require('./../../vxs/resolutions'); var resolutions = new Resolutions(); var vxscontent = require('./../../vxs/vxscontent'); const qrCodeGenerator = require('qrcode'); var NOKEY_THINGMARK = 'urn:vuforia:nokey'; var RESOURCE_QUERY_PARAM_KEY = 'resourceLocation'; const HOLOLENS = 'hololens'; const MOBILE = 'mobile'; const SPATIAL_TRACKING = 'spatial-tracking'; const TM_TRACKING = 'tm-tracking'; const QUERY_PARAM_NAME ='aspect'; const HOLOLENS_PARAM_VALUE ='holographic'; const VUFORIA_VIEW_URL ='https://view.vuforia.com/command/view-experience'; const QM ='?'; const AND ='&'; const EQUAL ='='; module.exports = function(req, res, next) { var trackingType = req.query.trackingType; var deviceType = req.query.deviceType; var repuri = req.query.repuri; var repName = req.query.repname; debug('repuri: ' + repuri); debug('repname: ' + repName); debug('tracking-type: ' + trackingType); debug('device-type: ' + deviceType); if (trackingType === undefined) { res.status(400).send('Tracking type missing').end(); return; } if (deviceType === undefined) { res.status(400).send('Device type missing').end(); return; } var requestParams = getRequestParams(trackingType,deviceType); var experienceName = getExperienceName(trackingType,deviceType); if (experienceName === undefined) { debug('Unable to evaluate Experience Name from trackingType: ' + trackingType + ' deviceType: ' + deviceType); res.status(400).send('Unable to evaluate Experience Name').end(); return; } var constructedUrl =''; getExperienceUrl(req, experienceName, requestParams) .then(function (url) { constructedUrl = constructExperienceUrl(url,repuri,repName); return generateQRCodeImage(constructedUrl) }) .then(function (urlImgStr) { if (req.accepts('json') && !req.accepts('html')) { res.status(200).json({url: constructedUrl, QRImage: urlImgStr}).end(); } else { res.status(200).send(constructedUrl).end(); } }) .catch(function (err) { debug('Inside fail...'); console.error(err); next(err); }); } function constructExperienceUrl(url,repuri,repName){ debug('construct url from : ' + url); var queryParam =''; if (repuri !== undefined) { queryParam = encodeURIComponent(repuri); } else if (repName !== undefined) { queryParam = encodeURIComponent(vxscontent.getContentUri('reps', repName.toLowerCase())); } if(queryParam !== ''){ url = url + AND + RESOURCE_QUERY_PARAM_KEY + EQUAL + queryParam } url = VUFORIA_VIEW_URL + QM +'url'+ EQUAL + encodeURIComponent(url); return url; } function getRequestParams(trackingType,deviceType){ var extraParams =[]; if (deviceType == HOLOLENS){ extraParams.push({'paramName': QUERY_PARAM_NAME,'paramValue': HOLOLENS_PARAM_VALUE}); } if (trackingType == SPATIAL_TRACKING){ extraParams.push({'paramName': QUERY_PARAM_NAME,'paramValue': SPATIAL_TRACKING}); } return extraParams; } //TODO: Remove this hardcoding by having request parameters in such a way that they return only 1 experience function getExperienceName(trackingType,deviceType){ var experienceName = undefined; let expNameMap = []; expNameMap.push({deviceType:HOLOLENS,trackingType : SPATIAL_TRACKING,expName: 'designsharesteyeviewer'}); expNameMap.push({deviceType:HOLOLENS,trackingType : TM_TRACKING,expName: 'designsharetmeyeviewer'}); expNameMap.push({deviceType:MOBILE,trackingType : SPATIAL_TRACKING,expName: 'creospatialviewer'}); expNameMap.push({deviceType:MOBILE,trackingType : TM_TRACKING,expName: 'designsharetmviewer'}); var experienceMapping = expNameMap.filter(function(mapping) { return mapping.deviceType === deviceType && mapping.trackingType === trackingType; }); if( experienceMapping !== undefined && experienceMapping.length != 0){ experienceName = experienceMapping[0].expName; } return experienceName; } function generateQRCodeImage(url) { debug('In generateQR'); return Q.promise(function (resolve, reject) { var opts = { width: 200, errorCorrectionLevel: 'M', margin: 2 }; qrCodeGenerator.toDataURL(url, opts, function (error, url) { if (error) { debug('QRCode generation failed: ' + error); reject(error); } debug('QRCode generated successfully!'); resolve(url); }) }); } function getExperienceUrl(req, experienceName, requestParams) { // TODO: Currently the implementation is only for spatial tracking experience. // Need to enhance to support thingmark based experiences too. return resolutions.getResolutions(req, NOKEY_THINGMARK, 'Experience',requestParams) .then(function (pubMappings) { debug('Got ' + (pubMappings !== undefined ? pubMappings.length : '0') + ' original published mappings'); var publishedMapping; if (pubMappings !== undefined) { publishedMapping = pubMappings.find(function(mapping) { return mapping.resourcetype === 'Experience' && mapping.value.includes('projects/' + experienceName + '/'); }); } if (publishedMapping === undefined) { debug('Original published entry not found for experience ' + experienceName); console.error('Original published entry not found for experience ' + experienceName); throw new Error('Experience template not found'); } else { debug ('Found original published mapping for experience ' + experienceName); return publishedMapping.value; } }); }
import React, { Component } from 'react'; import { View, Button, ScrollView } from 'react-native'; import Header from '../header'; import Footer from '../footer'; import Category from './category'; import InputFiled from './inputFiled'; import UploudImage from './uploudImage'; export default class AddItem extends Component { constructor(props) { super(props); this.state = { userId: '', img: 'https://firebasestorage.googleapis.com/v0/b/mobishop-ffcff.appspot.com/o/items%2Fqury.png?alt=media&token=a30d14fe-888b-4158-b0d0-473a6f9f7f73', type: 'others', specficArr: [], specfic: '', checked: false, descrbtion: '', title: '', cost: '', showSpecfic: false }; } onClick() { this.Category.caro(); } //this part to send all the item info and save it in the database done() { fetch('http://192.168.0.14:3000/addMerc', { method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'application/json' }, body: JSON.stringify(this.state) }) .then((data) => data.json()) .then((data) => console.warn(data)); } render() { return ( <View style={{ flex: 1, justifyContent: 'space-around', flexDirection: 'column' }}> <ScrollView> <Header /> <View> <View style={{ flex: 1, flexDirection: 'column', alignItems: 'center' }}> <UploudImage UploudImage={this.props.UploudImage} /> <Category specficArr={this.props.specficArr} supCategory={this.props.supCategory} type={this.props.type} /> <InputFiled onChange1={this.props.onChange1} onChange2={this.props.onChange2} onChange3={this.props.onChange3} /> </View> <Button color="grey" title="done" onPress={() => this.props.done()} style={{ margin: 5, borderRadius: 100 }} /> </View> </ScrollView> <Footer /> </View> ); } }
/** * @flow */ import 'whatwg-fetch' // for browser compatibility import React, { Component, } from 'react' import ReactNative, { AppRegistry, } from 'react-native' import { Router, Route, Redirect, IndexRedirect, withRouter, browserHistory, // this is a singleton } from 'react-router' import { SampleAppMovies, SampleMovieDetail, } from './platform_independent_components' import constants from './platform_independent_components/constants' // Components class SoloOneself extends Component { render() { // Reference 1 https://facebook.github.io/react/docs/transferring-props.html // Reference 2 https://github.com/reactjs/react-router/issues/1531 const dict = { ListView: ReactNative.ListView, ListViewDataSourceInitValue: new ReactNative.ListView.DataSource({ rowHasChanged: (row1, row2) => row1 !== row2, }), HyperLink: React.createClass({ propTypes: { onPress: React.PropTypes.func.isRequired }, render: function() { const {onPress, ...other} = this.props; return ( <button onClick={onPress}> {this.props.children} </button> ); } }), View: ReactNative.View, Text: ReactNative.Text, Image: ReactNative.Image, StyleSheet: ReactNative.StyleSheet, goToSampleMovieDetail: function(sceneRef: Component, movieId: number) { const newLocation = { pathname: constants.ROUTE_PATHS.MOVIE + '/' + movieId }; sceneRef.props.router.push(newLocation); }, goBack: function(sceneRef: Component) { console.log('goBack'); sceneRef.props.router.goBack(); } }; return React.cloneElement( this.props.children, dict ) } } const routes = ( <Router history={browserHistory}> <Route path={constants.ROUTE_PATHS.ROOT} component={SoloOneself}> <IndexRedirect to={constants.ROUTE_PATHS.HOME} /> <Route path={constants.ROUTE_PATHS.HOME} component={withRouter(SampleAppMovies)} /> <Route path={constants.ROUTE_PATHS.MOVIE + constants.ROUTE_PARAMS.MOVIE_ID} component={withRouter(SampleMovieDetail)} /> </Route> </Router> ); // App registration and rendering AppRegistry.registerComponent('SoloOneself', () => () => routes) AppRegistry.runApplication('SoloOneself', { rootTag: document.getElementById('react-root') })
import Page from '../layouts/main' import Grid from '../components/grid' import PostItem from '../components/post-item' import PrimaryTitle from '../components/primary-title' import textEffect from '../styles/text-effect' const metaData = { title: 'Nipher - Blog', description: 'Articles about web development', url: 'https://nipher.io/blog' } const BlogPage = ({ posts }) => ( <Page meta={metaData}> <PrimaryTitle> <strong className='text-effect'>Knowledge</strong> worth sharing </PrimaryTitle> <Grid className='blog-page' posts={posts}> { posts.map((post, i) => ( <PostItem key={i} { ...post } /> )) } </Grid> <style jsx>{textEffect}</style> </Page> ) BlogPage.getInitialProps = async ({ query, req }) => { if (query.build && typeof window === 'undefined') return query const postEndpoint = `/api/posts.json` const fetch = await import('isomorphic-fetch') let res = null if (req) { res = await fetch(`${req.protocol}://${req.get('host')}${postEndpoint}`) } else { res = await fetch(`${location.origin}${postEndpoint}`) } return await res.json() } export default BlogPage
import React, { Component } from 'react' import s from './Controls.css' import SearchContainer from '@/containers/SearchContainer' import WaypointsContainer from '@/containers/WaypointsContainer' import DetailsContainer from '@/containers/DetailsContainer' class Controls extends Component { constructor(props) { super(props) this.state = { hidden: false, } } onToogleControls = () => this.setState({ hidden: !this.state.hidden }) render() { const { hidden } = this.state return ( <div className={`${s.controlsWrapper} ${hidden ? s.hidden : ''}`}> <div className={s.searchWrapper}> <SearchContainer isOpen={!hidden} onArrowClick={this.onToogleControls} /> </div> <WaypointsContainer /> <DetailsContainer /> </div> ) } } export default Controls
var wpi=require('node-wiring-pi') var exec = require('child_process').exec; wpi.setup('wpi') var pin=2; var result=0; // var i = new Date().getSeconds() // console.log(i) wpi.pinMode(pin, wpi.INPUT) setInterval(()=>{ result = wpi.digitalRead(pin); var date = new Date() if(result){ console.log('Take a picture') exec('raspistill -o /home/pi/apps/mysonic1/'+date.getMinutes()+'_'+date.getSeconds()+'.jpg') } },500)
const numbers = [1, 2, 3, 4] const vowels = ['a', 'e', 'i', 'o', 'u'] const people = [{ name: 'Bob' }, { name: 'Sally' }, { name: 'Mary' }]
// Specifically request an abstraction for MetaCoin var LimitedMintableNonFungibleToken = artifacts.require("LimitedMintableNonFungibleToken"); contract('LimitedMintableNonFungibleToken', function(accounts) { it("should implement ERC721 interface", function(){ return LimitedMintableNonFungibleToken.deployed().then(function(instance) { return instance.supportsInterface('0x80ac58cd'); }).then(result => { assert.equal(result.valueOf(), true, "Doesn't implement ERC721"); }); }); it("should be able to mint", function() { return LimitedMintableNonFungibleToken.deployed().then(function(instance) { return instance.isMinter(accounts[0]).then(result => { assert.equal(result.valueOf(), true, 'default account should be allowed to mint'); return instance.mint(accounts[0], 1, { from: accounts[0] }); }).then(function(result) { return instance.balanceOf(accounts[0]); }).then(function(balance) { assert.equal(balance.valueOf(), 1, "Token should be in the account"); }); }); }); it("should be able to mint with token uri", function() { return LimitedMintableNonFungibleToken.deployed().then(function(instance) { return instance.mintWithTokenURI(accounts[0], 2, "https://foo.bar", {from: accounts[0]}).then(function(result) { return instance.tokenURI(2); }).then(function(tokenURI) { assert.equal(tokenURI.valueOf(), "https://foo.bar", "Token should have correct URI"); }); }); }); it("should not be able to mint if not a minter", function() { return LimitedMintableNonFungibleToken.deployed().then(function(instance) { return instance.mint(accounts[1], 3, { from: accounts[1] }).catch(function(error){ assert.ok(error, "Should have returned an error"); return instance.balanceOf(accounts[1]); }).then(function(balance) { assert.equal(balance.valueOf(), 0, "Second account should not have any tokens"); }); }); }); it("should be able to add minter", function() { return LimitedMintableNonFungibleToken.deployed().then(instance => { return instance.addMinter(accounts[1], { from: accounts[0] }).then(() => { return instance.mint(accounts[0], 3, { from: accounts[1] }); }).then(result => { return instance.balanceOf(accounts[0]); }).then(result => { assert.equal(result.valueOf(), 3, "Should have minted token"); }); }); }); it("should be able to list tokens", function() { return LimitedMintableNonFungibleToken.deployed().then(function(instance) { return instance.getOwnerTokens(accounts[0]).then(tokens => { assert.ok(tokens.valueOf(), "should have returned a value"); assert.equal(tokens.valueOf().length, 3, "should have 2 token ids"); }); }); }); it("should not error when listing tokens for empty balance", function() { return LimitedMintableNonFungibleToken.deployed().then(function(instance) { return instance.getOwnerTokens(accounts[1]).then(tokens => { assert.ok(tokens.valueOf(), "should have returned a value"); assert.equal(tokens.valueOf().length, 0, "should have 2 token ids"); }); }); }); it("should properly return image id", function() { return LimitedMintableNonFungibleToken.deployed().then(function(instance) { return instance.mint(accounts[0], 9, { from: accounts[0] }).then(result => { return instance.imageId(9); }).then(imageId => { assert.equal(imageId.valueOf(), 5, "imageId should return proper value"); }); }); }); });
var myArray = [2.34, 3.98, 7.32, 6.51, 9.99]; var roundedArray = []; var randomArray = []; for(var i = 0; i < myArray.length ; i++){ var rNum = Math.round(myArray[i]); roundedArray.push(rNum); } function tenRandom(rdmArray){ var numOfNumbers = 10; for (var i = 0; i < numOfNumbers; i++){ var rdm = Math.floor(Math.random() * (100)+ 1); rdmArray.push(rdm); } } tenRandom(randomArray); setInterval( function showDate(){ // creates a variable with the the date properties var today = new Date(); var todayHour = today.getHours(); var todayMin = today.getMinutes(); var todaySec = today.getSeconds(); var todayMonth = today.getMonth(); var todayDate = today.getDate(); var todayYear = today.getFullYear(); var fT = formatTime(todayHour) + ":" + formatTime(todayMin) + ":" + formatTime(todaySec); var fD = formatTime(todayDate) + "/" + formatTime(todayMonth+1) + "/" + formatTime(todayYear); document.body.innerHTML = "<h1>time: " + fT + " Date: " + fD + "</h1>"; }, 1000); // formats time to include a 0 if under 10 function formatTime(timeDenom){ if(timeDenom < 10){ return "0" + timeDenom; } else { return timeDenom; } };
var timer; chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) { switch(true){ case request.type == 'video': console.clear(); if(timer){ clearInterval(timer); } timer = setInterval(function(){ video(request.type,request.selection,request.value); }, 1); break; case request.type == 'next-up': console.clear(); next(request.type,request.selection,request.value); break; case request.type == 'feed': console.clear(); feed(request.type,request.selection,request.value); break; case request.type == 'widget': console.clear(); widget(request.type,request.name,request.selection,request.value); break; case request.type == 'read-more': console.clear(); read_more(request.type,request.selection,request.value); break; case request.type == 'explore-more': console.clear(); explore_more(request.type,request.selection,request.value); break; case request.type == 'screenshot': console.clear(); screenshot(request.type,request.selection,request.value); break; case request.type == 'script': console.clear(); script(request.type,request.selection,request.value); break; } function video(t,s,v){ //video if(!document.getElementsByClassName('_cm-ad-active')[0] && !document.getElementsByClassName('_cm-os-slider')[0]){ return; } else if(document.getElementsByClassName('_cm-ad-active')[0]){ //feed slider switch(true){ case s == 'height': document.getElementsByClassName('_cm-ad-active')[0].style.cssText="margin-bottom: "+ v +"px;background-color: transparent;position: fixed;top: auto;left: auto;right: 0px;bottom: 0px;width: 400px;height: 225px;transition: none 0s ease 0s;z-index: 999 !important;"; document.getElementById('_cm-close-area').style.cssText="display: none;" document.getElementsByClassName('_cm-volume-border')[0].style.cssText="display: none;"; break; case s == 'length': document.getElementsByClassName('_cm-ad-active')[0].style.cssText="background-color: transparent;position: fixed;top: auto;left: auto;right: "+ v +"px;bottom: 0px;width: 400px;height: 225px;transition: none 0s ease 0s;z-index: 999 !important;"; document.getElementById('_cm-close-area').style.cssText="display: none;" document.getElementsByClassName('_cm-volume-border')[0].style.cssText="display: none;"; break; case s == 'z-index': document.getElementsByClassName('_cm-ad-active')[0].style.cssText="background-color: transparent;position: fixed;top: auto;left: auto;right: 0px;bottom: 0px;width: 400px;height: 225px;transition: none 0s ease 0s;z-index: "+ v +" !important;"; document.getElementById('_cm-close-area').style.cssText="display: none;" document.getElementsByClassName('_cm-volume-border')[0].style.cssText="display: none;"; break; case s == 'size': document.getElementsByClassName('_cm-ad-active')[0].style.cssText="background-color: transparent;position: fixed;top: auto;left: auto;right: 0px;bottom: 0px;width: "+ v +"px;height: "+ parseInt(v)/1.7 +"px;transition: none 0s ease 0s;z-index: 999 !important;"; document.getElementById('_cm-close-area').style.cssText="display: none;" document.getElementsByClassName('_cm-volume-border')[0].style.cssText="display: none;"; break; } } else if(document.getElementsByClassName('_cm-os-slider')[0]){ //slider tag document.getElementsByClassName('_cm-os-slider')[0].style.cssText="text-align: left;top: auto;bottom: "+ v +"px;left: auto;right: 0px;width: 400px;height: 225px;transition: right 1s ease 0s, left 1s ease 0s !important;"; } } function next(t,s,v){ //next-up switch(true){ case s == 'size': document.getElementById('tbl-next-up').style.width= v+'px'; break; case s == 'height': document.getElementById('tbl-next-up').style.bottom= v+'px'; break; case s == 'left': document.getElementById('tbl-next-up').style.left= v+'px'; break; case s == 'font_size': if(document.querySelectorAll('.blend-next-up-a .video-title')){ var nf =document.querySelectorAll('.blend-next-up-a .video-title'),i; for (i = 0; i < nf.length; ++i) { nf[i].style.fontSize = v + 'px'; } }else{ var nf =document.querySelectorAll('.next-up-a .video-title'),i; for (i = 0; i < nf.length; ++i) { nf[i].style.fontSize = v + 'px'; } } break; case s == 'font_color': if(document.querySelectorAll('.blend-next-up-a .video-title')){ var nc =document.querySelectorAll('.blend-next-up-a .video-title'),i; for (i = 0; i < nc.length; ++i) { nc[i].style.color = v; } }else{ var nc =document.querySelectorAll('.next-up-a .video-title'),i; for (i = 0; i < nc.length; ++i) { nc[i].style.color = v; } } break; } } function feed(t,s,v){ //feed switch(true){ case s == 'header_padding': document.getElementsByClassName('tbl-feed-header')[0].style.padding = v; break; case s == 'header_color': document.getElementsByClassName('tbl-feed-header')[0].style.backgroundColor = v; break; case s == 'header_margin': document.getElementsByClassName('tbl-feed-header')[0].style.margin = v; break; case s == 'title_color': var tc = document.querySelectorAll('.videoCube .video-label-box .video-title'),i; for (i = 0; i < tc.length; ++i) { tc[i].style.color = v; } break; case s == 'title_font': var tf = document.querySelectorAll('.videoCube .video-label-box .video-title'),i; for (i = 0; i < tf.length; ++i) { tf[i].style.fontSize = v+'px'; } break; case s == 'title_margin': var tm = document.querySelectorAll('.videoCube .video-label-box .video-title'),i; for (i = 0; i < tm.length; ++i) { tm[i].style.margin = v; } break; case s == 'branding_font': var bf = document.querySelectorAll('.videoCube .video-label-box .branding.composite-branding'),i; for (i = 0; i < bf.length; ++i) { bf[i].style.fontSize = v+'px'; } break; case s == 'branding_margin': var bm = document.querySelectorAll('.videoCube .video-label-box .branding.composite-branding'),i; for (i = 0; i < bm.length; ++i) { bm[i].style.margin = v; } break; case s == 'feed_ratio': var fr = document.querySelectorAll('.videoCube_aspect'),i; for (i = 0; i < fr.length; ++i) { fr[i].style.padding = v; } break; case s == 'feed_border': document.querySelectorAll('.trc_related_container.trc_spotlight_widget.tbl-feed-container.tbl-feed-frame-DIVIDER.render-late-effect')[0].style.padding = v; break; } } function widget(t,w,s,v){ switch(true){ case s == 'header_margin': var hm = document.querySelectorAll('.'+ w + ' .trc_rbox_header'),i; for (i = 0; i < hm.length; ++i) { hm[i].style.margin = v; } break; case s == 'header_padding': var hp = document.querySelectorAll('.'+ w + ' .trc_rbox_header'),i; for (i = 0; i < hp.length; ++i) { hp[i].style.padding = v; } break; case s == 'header_color': var hc = document.querySelectorAll('.'+ w + ' .trc_rbox_header'),i; for (i = 0; i < hc.length; ++i) { hc[i].style.backgroundColor = v; } break; case s == 'header_font': var hf = document.querySelectorAll('.'+ w + ' .trc_rbox_header'),i; for (i = 0; i < hf.length; ++i) { hf[i].style.fontSize = v + 'px'; } break; case s == 'thumbnails_width': var tw = document.querySelectorAll('.'+ w + ' .videoCube'),i; for (i = 0; i < tw.length; ++i) { tw[i].style.width = v + '%'; } break; case s == 'thumbnails_margin': var tm = document.querySelectorAll('.'+ w + ' .videoCube'),i; for (i = 0; i < tm.length; ++i) { tm[i].style.margin = v; } break; case s == 'thumbnails_padding': var tp = document.querySelectorAll('.'+ w + ' .videoCube'),i; for (i = 0; i < tp.length; ++i) { tp[i].style.padding = v; } break; case s == 'title_font': var tf = document.querySelectorAll('.'+ w + ' .video-title'),i; for (i = 0; i < tf.length; ++i) { tf[i].style.fontSize = v + 'px'; } break; case s == 'title_font_color': var tc = document.querySelectorAll('.'+ w + ' .video-title'),i; for (i = 0; i < tc.length; ++i) { tc[i].style.color = v; } break; case s == 'title_branding_height': var th = document.querySelectorAll('.'+ w + ' .video-title'),i; for (i = 0; i < th.length; ++i) { th[i].style.maxHeight = v + 'px'; } break; case s == 'title_margin': var tm = document.querySelectorAll('.'+ w + ' .video-title'),i; for (i = 0; i < tm.length; ++i) { tm[i].style.margin = v; } break; case s == 'branding_color': var bc = document.querySelectorAll('.'+ w + ' .branding'),i; for (i = 0; i < bc.length; ++i) { bc[i].style.color = v; } break; case s == 'branding_font': var bf = document.querySelectorAll('.'+ w + ' .branding'),i; for (i = 0; i < bf.length; ++i) { bf[i].style.fontSize = v + 'px'; } break; } } function read_more(t,s,v){ switch(true){ case s == 'read_height': document.getElementsByClassName('tbl-read-more-btn')[0].style.cssText="display: inline-block !important;margin: 48px 0 28px !important;line-height: 38px !important;text-align: center !important;white-space: nowrap !important;vertical-align: middle !important;cursor: pointer !important;touch-action: manipulation;color: #326891 !important;background: #edf2f5 none !important;border: 1px solid #93abbc !important;height: "+ v +"px !important;width: 250px !important;font-size: 15px !important;font-weight: bold !important;border-radius: 3px !important;font-family: sans-serif !important;"; break; case s == 'read_width': document.getElementsByClassName('tbl-read-more-btn')[0].style.cssText="display: inline-block !important;margin: 48px 0 28px !important;line-height: 38px !important;text-align: center !important;white-space: nowrap !important;vertical-align: middle !important;cursor: pointer !important;touch-action: manipulation;color: #326891 !important;background: #edf2f5 none !important;border: 1px solid #93abbc !important;height: 38px !important;width: "+ v +"px !important;font-size: 15px !important;font-weight: bold !important;border-radius: 3px !important;font-family: sans-serif !important;"; break; case s == 'read_border': document.getElementsByClassName('tbl-read-more-btn')[0].style.cssText="display: inline-block !important;margin: 48px 0 28px !important;line-height: 38px !important;text-align: center !important;white-space: nowrap !important;vertical-align: middle !important;cursor: pointer !important;touch-action: manipulation;color: #326891 !important;background: #edf2f5 none !important;border: "+ v +" !important;height: 38px !important;width: 250px !important;font-size: 15px !important;font-weight: bold !important;border-radius: 3px !important;font-family: sans-serif !important;"; break; case s == 'read_font': document.getElementsByClassName('tbl-read-more-btn')[0].style.cssText="display: inline-block !important;margin: 48px 0 28px !important;line-height: 38px !important;text-align: center !important;white-space: nowrap !important;vertical-align: middle !important;cursor: pointer !important;touch-action: manipulation;color: #326891 !important;background: #edf2f5 none !important;border: 1px solid #93abbc !important;height: 38px !important;width: 250px !important;font-size: "+ v +"px !important;font-weight: bold !important;border-radius: 3px !important;font-family: sans-serif !important;"; break; case s == 'read_font_color': document.getElementsByClassName('tbl-read-more-btn')[0].style.cssText="display: inline-block !important;margin: 48px 0 28px !important;line-height: 38px !important;text-align: center !important;white-space: nowrap !important;vertical-align: middle !important;cursor: pointer !important;touch-action: manipulation;color: "+ v +" !important;background: #edf2f5 none !important;border: 1px solid #93abbc !important;height: 38px !important;width: 250px !important;font-size: 15px !important;font-weight: bold !important;border-radius: 3px !important;font-family: sans-serif !important;"; break; case s == 'read_background': document.getElementsByClassName('tbl-read-more-btn')[0].style.cssText="display: inline-block !important;margin: 48px 0 28px !important;line-height: 38px !important;text-align: center !important;white-space: nowrap !important;vertical-align: middle !important;cursor: pointer !important;touch-action: manipulation;color: #326891 !important;background: "+ v +" none !important;border: 1px solid #93abbc !important;height: 38px !important;width: 250px !important;font-size: 15px !important;font-weight: bold !important;border-radius: 3px !important;font-family: sans-serif !important;"; break; } } function explore_more(t,s,v){ switch(true){ case s == 'margin': var e = document.getElementById("tbl-explore-more-container").childNodes[0]; e.style.margin = v; break; case s == 'padding': var e = document.getElementById("tbl-explore-more-container").childNodes[0]; e.style.padding = v; break; case s == 'background': var e = document.getElementById("tbl-explore-more-container").childNodes[0]; e.style.backgroundColor = v; break; case s == 'pop_up_text': document.getElementsByClassName('tbl-explore-more-popup-text')[0].innerText = v; break; case s == 'pop_up_background': document.querySelectorAll('.tbl-explore-more-popup.tbl-explore-more-popup-show')[0].style.backgroundColor = v; break; case s == 'pop_up_margin': document.querySelectorAll('.tbl-explore-more-popup.tbl-explore-more-popup-show')[0].style.margin = v; break; } } function screenshot(t,s,v){ if(s == 'screenshot'){ chrome.runtime.sendMessage({greeting: "screenshot request sent"}, function(response) { }); } } function script(t,s,v){ chrome.runtime.sendMessage({greeting: "script request sent",data: v}, function(response) { }); } });
module.exports = /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = require('../../../ssr-module-cache.js'); /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ var threw = true; /******/ try { /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ threw = false; /******/ } finally { /******/ if(threw) delete installedModules[moduleId]; /******/ } /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 12); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports) { module.exports = require("react"); /***/ }), /* 1 */ /***/ (function(module, exports) { module.exports = require("styled-components"); /***/ }), /* 2 */, /* 3 */ /***/ (function(module, exports) { module.exports = require("redux"); /***/ }), /* 4 */, /* 5 */ /***/ (function(module, exports) { module.exports = require("redux-thunk"); /***/ }), /* 6 */ /***/ (function(module, exports) { module.exports = require("redux-logger"); /***/ }), /* 7 */ /***/ (function(module, exports) { module.exports = require("antd"); /***/ }), /* 8 */ /***/ (function(module, exports) { module.exports = require("socket.io-client"); /***/ }), /* 9 */ /***/ (function(module, exports) { module.exports = require("react-redux"); /***/ }), /* 10 */, /* 11 */, /* 12 */ /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__(22); /***/ }), /* 13 */ /***/ (function(module, exports) { module.exports = require("redux-persist/integration/react"); /***/ }), /* 14 */ /***/ (function(module, exports) { module.exports = require("redux-persist"); /***/ }), /* 15 */ /***/ (function(module, exports) { module.exports = require("redux-persist/lib/storage"); /***/ }), /* 16 */, /* 17 */, /* 18 */, /* 19 */, /* 20 */, /* 21 */, /* 22 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); // EXTERNAL MODULE: external "react" var external_react_ = __webpack_require__(0); var external_react_default = /*#__PURE__*/__webpack_require__.n(external_react_); // EXTERNAL MODULE: external "redux-persist/integration/react" var react_ = __webpack_require__(13); // EXTERNAL MODULE: external "redux" var external_redux_ = __webpack_require__(3); // EXTERNAL MODULE: external "redux-persist" var external_redux_persist_ = __webpack_require__(14); // EXTERNAL MODULE: external "redux-thunk" var external_redux_thunk_ = __webpack_require__(5); var external_redux_thunk_default = /*#__PURE__*/__webpack_require__.n(external_redux_thunk_); // EXTERNAL MODULE: external "redux-persist/lib/storage" var storage_ = __webpack_require__(15); // CONCATENATED MODULE: ./redux/actions/types.js var SET_HAND = 'SET_HAND'; var SET_CARDS = 'SET_CARDS'; // CONCATENATED MODULE: ./redux/reducers/mainReducer.js function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } var initialState = { cards: "hey", hand: "HHIIII" }; function mainReducer() { var state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : initialState; var action = arguments.length > 1 ? arguments[1] : undefined; switch (action.type) { case SET_HAND: console.log("SET_HAND", d); return _objectSpread({}, state, { hand: action.data }); case SET_CARDS: console.log("SET_CARDS"); return _objectSpread({}, state, { cards: action.data }); default: return state; } } // CONCATENATED MODULE: ./redux/reducers/reducer.js /* harmony default export */ var reducer = (Object(external_redux_["combineReducers"])({ main: mainReducer })); // EXTERNAL MODULE: external "redux-logger" var external_redux_logger_ = __webpack_require__(6); // CONCATENATED MODULE: ./redux/store.js var logger = Object(external_redux_logger_["createLogger"])(); // const persistConfig = { // key: 'root', // storage, // blacklist: [] // }; // const persistedReducer = persistReducer(persistConfig, reducer); var store = Object(external_redux_["createStore"])(reducer, Object(external_redux_["applyMiddleware"])(external_redux_thunk_default.a, logger)); // export const persistor = persistStore(store); // EXTERNAL MODULE: external "styled-components" var external_styled_components_ = __webpack_require__(1); var external_styled_components_default = /*#__PURE__*/__webpack_require__.n(external_styled_components_); // CONCATENATED MODULE: ./components/cardGame/card.js function _templateObject6() { var data = _taggedTemplateLiteral(["\ndisplay:inline-block;\nposition:relative;\nwidth:", ";\nheight:", ";\nmargin: ", ";\nborder:1px solid #444;\nborder-radius:4px;\nz-index: ", ";\ntransition: all 0.15s;\nopacity: ", ";\ntransform: ", ";\n&:hover{\n\tz-index: 100;\n\topacity: ", ";\n\ttransform: ", ";\n\tbox-shadow: 0 15px 20px rgba(0, 0, 0, 0.3); \n};\nbackground:", ";\nbackground-size:cover;\nbackground-repeat: no-repeat;\nbox-shadow: ", "; \nfilter: ", ";\ntransform: ", ";\n"]); _templateObject6 = function _templateObject6() { return data; }; return data; } function _templateObject5() { var data = _taggedTemplateLiteral(["\n\tposition:absolute;\n\ttop:30%;\n\tright:0;\n"]); _templateObject5 = function _templateObject5() { return data; }; return data; } function _templateObject4() { var data = _taggedTemplateLiteral(["\n\tposition:absolute;\n\ttop:30%;\n\tleft:0;\n"]); _templateObject4 = function _templateObject4() { return data; }; return data; } function _templateObject3() { var data = _taggedTemplateLiteral(["\n\tposition:absolute;\n\tbottom:0;\n\tleft:36%;\n"]); _templateObject3 = function _templateObject3() { return data; }; return data; } function _templateObject2() { var data = _taggedTemplateLiteral(["\n\tposition:absolute;\n\ttop:0;\n\tleft:36%;\n"]); _templateObject2 = function _templateObject2() { return data; }; return data; } function _templateObject() { var data = _taggedTemplateLiteral(["\n\tposition:relative;\n\tborder: ", ";\n\tmargin:3px;\n\tz-index:20;\n\tbackground:#ffffffd1;\n\tuser-select:none;\n overflow: hidden;\n height: 40px;\n width:30px;\n"]); _templateObject = function _templateObject() { return data; }; return data; } function _taggedTemplateLiteral(strings, raw) { if (!raw) { raw = strings.slice(0); } return Object.freeze(Object.defineProperties(strings, { raw: { value: Object.freeze(raw) } })); } function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a 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); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var card_Card = /*#__PURE__*/ function (_Component) { _inherits(Card, _Component); function Card() { _classCallCheck(this, Card); return _possibleConstructorReturn(this, _getPrototypeOf(Card).apply(this, arguments)); } _createClass(Card, [{ key: "render", value: function render() { var _this$props = this.props, inGame = _this$props.inGame, card = _this$props.card, setHoverCard = _this$props.setHoverCard, index = _this$props.index, toggleCard = _this$props.toggleCard, setControlCard = _this$props.setControlCard, selected = _this$props.selected; return external_react_default.a.createElement(Edge, { onMouseOver: function onMouseOver() { return inGame ? setHoverCard(card) : null; }, onMouseOut: function onMouseOut() { return inGame ? setHoverCard(null) : null; }, onClick: function onClick() { return inGame ? setControlCard(card) : toggleCard(card); }, selected: selected, card: card, index: index, inGame: inGame }, external_react_default.a.createElement(Stats, { poss: card.poss }, external_react_default.a.createElement(Up, null, card.u), external_react_default.a.createElement(Down, null, card.d), external_react_default.a.createElement(Left, null, card.l), external_react_default.a.createElement(Right, null, card.r))); } }]); return Card; }(external_react_["Component"]); var Stats = external_styled_components_default.a.div(_templateObject(), function (p) { return p.poss < 1 ? '1px solid orange' : '1px solid blue'; }); var Up = external_styled_components_default.a.div(_templateObject2()); var Down = external_styled_components_default.a.div(_templateObject3()); var Left = external_styled_components_default.a.div(_templateObject4()); var Right = external_styled_components_default.a.div(_templateObject5()); var Edge = external_styled_components_default.a.div(_templateObject6(), function (p) { return p.inGame ? '120px' : '60px'; }, function (p) { return p.inGame ? '160px' : '80px'; }, function (p) { return p.inGame ? '0px -15px 0px -15px' : '10px 5px 10px 5px'; }, function (p) { return p.selected ? 200 : null; }, function (p) { return p.selected ? '0.9' : '1'; }, function (p) { return p.inGame ? "rotate(".concat(p.index < 3 ? -20 + p.index * 5 : p.index * 5, "deg)") : null; }, function (p) { return p.inGame && p.selected ? null : '1'; }, function (p) { return p.inGame && !p.selected ? 'translateY(-30px)' : !p.inGame ? 'scale(1.18)' : null; }, function (p) { return p.card ? 'url(/static/img/' + p.card.img + '/)' : null; }, function (p) { return p.inGame && p.selected ? '0 15px 20px rgba(0, 0, 0, 0.3)' : null; }, function (p) { return !p.inGame && p.selected ? 'opacity(50%) blur(0.1px) contrast(160%)' : p.inGame && p.selected ? null : null; }, function (p) { return p.inGame && p.selected ? 'translateY(-35px)' : null; }); // CONCATENATED MODULE: ./components/cardGame/playedCard.js function playedCard_templateObject6() { var data = playedCard_taggedTemplateLiteral(["\n\tposition:absolute;\n\ttop:30%;\n\tright:0;\n"]); playedCard_templateObject6 = function _templateObject6() { return data; }; return data; } function playedCard_templateObject5() { var data = playedCard_taggedTemplateLiteral(["\n\tposition:absolute;\n\ttop:30%;\n\tleft:0;\n"]); playedCard_templateObject5 = function _templateObject5() { return data; }; return data; } function playedCard_templateObject4() { var data = playedCard_taggedTemplateLiteral(["\n\tposition:absolute;\n\tbottom:0;\n\tleft:36%;\n"]); playedCard_templateObject4 = function _templateObject4() { return data; }; return data; } function playedCard_templateObject3() { var data = playedCard_taggedTemplateLiteral(["\n\tposition:absolute;\n\ttop:0;\n\tleft:36%;\n"]); playedCard_templateObject3 = function _templateObject3() { return data; }; return data; } function playedCard_templateObject2() { var data = playedCard_taggedTemplateLiteral(["\n\tposition:relative;\n\tmargin:3px;\n\tbackground:#ffffffd1;\n\tuser-select:none;\n overflow: hidden;\n height: 40px;\n width:30px;\n"]); playedCard_templateObject2 = function _templateObject2() { return data; }; return data; } function playedCard_templateObject() { var data = playedCard_taggedTemplateLiteral(["\nposition:absolute;\nmargin:auto;\nbackground:", ";\nbackground-size:cover;\nborder: ", "\nborder-radius:4px;\nwidth:89%;\nheight:89%;\n"]); playedCard_templateObject = function _templateObject() { return data; }; return data; } function playedCard_taggedTemplateLiteral(strings, raw) { if (!raw) { raw = strings.slice(0); } return Object.freeze(Object.defineProperties(strings, { raw: { value: Object.freeze(raw) } })); } function playedCard_typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { playedCard_typeof = function _typeof(obj) { return typeof obj; }; } else { playedCard_typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return playedCard_typeof(obj); } function playedCard_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function playedCard_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); } } function playedCard_createClass(Constructor, protoProps, staticProps) { if (protoProps) playedCard_defineProperties(Constructor.prototype, protoProps); if (staticProps) playedCard_defineProperties(Constructor, staticProps); return Constructor; } function playedCard_possibleConstructorReturn(self, call) { if (call && (playedCard_typeof(call) === "object" || typeof call === "function")) { return call; } return playedCard_assertThisInitialized(self); } function playedCard_assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function playedCard_getPrototypeOf(o) { playedCard_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return playedCard_getPrototypeOf(o); } function playedCard_inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) playedCard_setPrototypeOf(subClass, superClass); } function playedCard_setPrototypeOf(o, p) { playedCard_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return playedCard_setPrototypeOf(o, p); } var playedCard_PlayedCard = /*#__PURE__*/ function (_Component) { playedCard_inherits(PlayedCard, _Component); function PlayedCard() { playedCard_classCallCheck(this, PlayedCard); return playedCard_possibleConstructorReturn(this, playedCard_getPrototypeOf(PlayedCard).apply(this, arguments)); } playedCard_createClass(PlayedCard, [{ key: "render", value: function render() { var card = this.props.card; return external_react_default.a.createElement(Portrait, { card: card }, external_react_default.a.createElement(playedCard_Stats, null, external_react_default.a.createElement(playedCard_Up, null, card.u), external_react_default.a.createElement(playedCard_Down, null, card.d), external_react_default.a.createElement(playedCard_Left, null, card.l), external_react_default.a.createElement(playedCard_Right, null, card.r))); } }]); return PlayedCard; }(external_react_["Component"]); var Portrait = external_styled_components_default.a.div(playedCard_templateObject(), function (p) { return p.card ? 'url(/static/img/' + p.card.img + '/)' : null; }, function (p) { return p.card && p.card.poss === 1 ? '4px solid blue' : p.card && p.card.poss === 0 ? '4px solid orange' : null; }); var playedCard_Stats = external_styled_components_default.a.div(playedCard_templateObject2()); var playedCard_Up = external_styled_components_default.a.div(playedCard_templateObject3()); var playedCard_Down = external_styled_components_default.a.div(playedCard_templateObject4()); var playedCard_Left = external_styled_components_default.a.div(playedCard_templateObject5()); var playedCard_Right = external_styled_components_default.a.div(playedCard_templateObject6()); // CONCATENATED MODULE: ./components/cardGame/cardSlot.js function cardSlot_templateObject() { var data = cardSlot_taggedTemplateLiteral(["\ndisplay:inline-block;\njustify-content:center;\nposition:relative;\nwidth:70px;\nmaxWidth:70px;\nheight:95px;\nmargin:5px;\nborder-radius:4px;\nborder: 1px solid #303030;\ntransition: all 0.15s;\n&:hover{\n\tz-index:80px;\n\ttransform:", ";\n\tbackground:", ";\n\topacity:", ";\n\tbackground-size:cover;\n\tbackground-repeat: no-repeat;\n};\n"]); cardSlot_templateObject = function _templateObject() { return data; }; return data; } function cardSlot_taggedTemplateLiteral(strings, raw) { if (!raw) { raw = strings.slice(0); } return Object.freeze(Object.defineProperties(strings, { raw: { value: Object.freeze(raw) } })); } function cardSlot_typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { cardSlot_typeof = function _typeof(obj) { return typeof obj; }; } else { cardSlot_typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return cardSlot_typeof(obj); } function cardSlot_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function cardSlot_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); } } function cardSlot_createClass(Constructor, protoProps, staticProps) { if (protoProps) cardSlot_defineProperties(Constructor.prototype, protoProps); if (staticProps) cardSlot_defineProperties(Constructor, staticProps); return Constructor; } function cardSlot_possibleConstructorReturn(self, call) { if (call && (cardSlot_typeof(call) === "object" || typeof call === "function")) { return call; } return cardSlot_assertThisInitialized(self); } function cardSlot_assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function cardSlot_getPrototypeOf(o) { cardSlot_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return cardSlot_getPrototypeOf(o); } function cardSlot_inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) cardSlot_setPrototypeOf(subClass, superClass); } function cardSlot_setPrototypeOf(o, p) { cardSlot_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return cardSlot_setPrototypeOf(o, p); } /* eslint-disable no-unused-vars */ var cardSlot_CardSlot = /*#__PURE__*/ function (_Component) { cardSlot_inherits(CardSlot, _Component); function CardSlot() { cardSlot_classCallCheck(this, CardSlot); return cardSlot_possibleConstructorReturn(this, cardSlot_getPrototypeOf(CardSlot).apply(this, arguments)); } cardSlot_createClass(CardSlot, [{ key: "render", value: function render() { var _this$props = this.props, column = _this$props.column, row = _this$props.row, card = _this$props.card, controlCard = _this$props.controlCard, updateSlots = _this$props.updateSlots; return external_react_default.a.createElement(cardSlot_Edge, { row: row, controlCard: controlCard, card: card, column: column, onClick: function onClick() { return updateSlots(row, column, card); } }, card ? external_react_default.a.createElement(playedCard_PlayedCard, { card: card }) : null); } }]); return CardSlot; }(external_react_["Component"]); var cardSlot_Edge = external_styled_components_default.a.div(cardSlot_templateObject(), function (p) { return !p.card ? 'scale(1.18)' : null; }, function (p) { return p.controlCard ? 'url(/static/img/' + p.controlCard.img + '/)' : null; }, function (p) { return !p.card ? 0.4 : null; }); // EXTERNAL MODULE: external "antd" var external_antd_ = __webpack_require__(7); // CONCATENATED MODULE: ./components/cardGame/console.js function _templateObject8() { var data = console_taggedTemplateLiteral(["\nposition:absolute;\ndisplay:flex;\nflex-direction:column;\nz-index:10;\nright:59px;\ntop:6px;\ncolor:#eee;\n"]); _templateObject8 = function _templateObject8() { return data; }; return data; } function _templateObject7() { var data = console_taggedTemplateLiteral(["\ndisplay:block;\nmargin:5px;\nborder:1px solid #fff;\ncolor:#eee;\nwidth:100%;\npadding:10px;\n&:hover{\n\tcolor: #63de00;\n\tborder:1px solid #63de00;\n}\n"]); _templateObject7 = function _templateObject7() { return data; }; return data; } function console_templateObject6() { var data = console_taggedTemplateLiteral(["\ndisplay:inline-block;\npadding:2px;\nfont-weight:bold;\nwidth:fit-content;\n"]); console_templateObject6 = function _templateObject6() { return data; }; return data; } function console_templateObject5() { var data = console_taggedTemplateLiteral(["\nposition:absolute;\nleft:10px;\nbottom:10px;\ntext-align:center;\nborder:1px solid #f6f6f6;\npadding:10px;\nwidth:fit-content;\nheight:40px;\n"]); console_templateObject5 = function _templateObject5() { return data; }; return data; } function console_templateObject4() { var data = console_taggedTemplateLiteral(["\nwidth:200px;\nheight:200px;\nopacity:0.4;\nbackground:", ";\nbackground-size:cover;\nbackground-repeat: no-repeat;\n"]); console_templateObject4 = function _templateObject4() { return data; }; return data; } function console_templateObject3() { var data = console_taggedTemplateLiteral(["\nposition:relative;\nbackground:#000;\npadding:10px;\nborder-radius:4px;\ncolor:#f4f4f4;\nheight:calc(100% - 60px);\n"]); console_templateObject3 = function _templateObject3() { return data; }; return data; } function console_templateObject2() { var data = console_taggedTemplateLiteral(["\ndisplay:inline-block;\nmargin:5px;\nbackground:", ";\nwidth:30px;\nheight:30px;\nbackground-size:cover;\nbackground-repeat: no-repeat;\n"]); console_templateObject2 = function _templateObject2() { return data; }; return data; } function console_templateObject() { var data = console_taggedTemplateLiteral(["\ncolor:#f4f4f4;\n"]); console_templateObject = function _templateObject() { return data; }; return data; } function console_taggedTemplateLiteral(strings, raw) { if (!raw) { raw = strings.slice(0); } return Object.freeze(Object.defineProperties(strings, { raw: { value: Object.freeze(raw) } })); } function console_typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { console_typeof = function _typeof(obj) { return typeof obj; }; } else { console_typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return console_typeof(obj); } function console_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function console_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); } } function console_createClass(Constructor, protoProps, staticProps) { if (protoProps) console_defineProperties(Constructor.prototype, protoProps); if (staticProps) console_defineProperties(Constructor, staticProps); return Constructor; } function console_possibleConstructorReturn(self, call) { if (call && (console_typeof(call) === "object" || typeof call === "function")) { return call; } return console_assertThisInitialized(self); } function console_assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function console_getPrototypeOf(o) { console_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return console_getPrototypeOf(o); } function console_inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) console_setPrototypeOf(subClass, superClass); } function console_setPrototypeOf(o, p) { console_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return console_setPrototypeOf(o, p); } var console_CommandLine = /*#__PURE__*/ function (_Component) { console_inherits(CommandLine, _Component); function CommandLine() { console_classCallCheck(this, CommandLine); return console_possibleConstructorReturn(this, console_getPrototypeOf(CommandLine).apply(this, arguments)); } console_createClass(CommandLine, [{ key: "render", value: function render() { var _this$props = this.props, controlCard = _this$props.controlCard, editControlCard = _this$props.editControlCard; var buttons = []; var buffs = []; controlCard && controlCard.powups && controlCard.powups.map(function (o, i) { var disable = o.active === true || controlCard.pocket < o.price; buttons.push(external_react_default.a.createElement(external_antd_["Button"], { key: i, style: { margin: 5 }, disabled: disable, onClick: function onClick() { return editControlCard(o); } }, o.name, " ", external_react_default.a.createElement(Price, null, o.price))); if (o.active) buffs.push(external_react_default.a.createElement(BuffIcon, { key: i, img: o.img })); }); return external_react_default.a.createElement(Details, null, external_react_default.a.createElement(Image, { image: controlCard.img }), external_react_default.a.createElement(Pocket, null, controlCard.pocket, " Gob"), external_react_default.a.createElement(Bar, null, buttons), external_react_default.a.createElement(Buffs, null, buffs)); } }]); return CommandLine; }(external_react_["Component"]); var Buffs = external_styled_components_default.a.div(console_templateObject()); var BuffIcon = external_styled_components_default.a.div(console_templateObject2(), function (p) { return p.img ? 'url(/static/img/pow/' + p.img + '/)' : null; }); var Details = external_styled_components_default.a.div(console_templateObject3()); var Image = external_styled_components_default.a.div(console_templateObject4(), function (p) { return p.image ? 'url(/static/img/' + p.image + '/)' : null; }); var Pocket = external_styled_components_default.a.div(console_templateObject5()); var Price = external_styled_components_default.a.div(console_templateObject6()); var Buon = external_styled_components_default.a.div(_templateObject7()); var Bar = external_styled_components_default.a.div(_templateObject8()); // CONCATENATED MODULE: ./components/cardGame/commandLine.js function commandLine_templateObject() { var data = commandLine_taggedTemplateLiteral(["\nmargin:30px;\nwidth:380px;\nheight:330px;\ncursor:default;\nbackground:#222;\nborder-radius:4px;\ncolor:#f4f4f4;\n"]); commandLine_templateObject = function _templateObject() { return data; }; return data; } function commandLine_taggedTemplateLiteral(strings, raw) { if (!raw) { raw = strings.slice(0); } return Object.freeze(Object.defineProperties(strings, { raw: { value: Object.freeze(raw) } })); } function commandLine_typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { commandLine_typeof = function _typeof(obj) { return typeof obj; }; } else { commandLine_typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return commandLine_typeof(obj); } function commandLine_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function commandLine_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); } } function commandLine_createClass(Constructor, protoProps, staticProps) { if (protoProps) commandLine_defineProperties(Constructor.prototype, protoProps); if (staticProps) commandLine_defineProperties(Constructor, staticProps); return Constructor; } function commandLine_possibleConstructorReturn(self, call) { if (call && (commandLine_typeof(call) === "object" || typeof call === "function")) { return call; } return commandLine_assertThisInitialized(self); } function commandLine_assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function commandLine_getPrototypeOf(o) { commandLine_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return commandLine_getPrototypeOf(o); } function commandLine_inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) commandLine_setPrototypeOf(subClass, superClass); } function commandLine_setPrototypeOf(o, p) { commandLine_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return commandLine_setPrototypeOf(o, p); } var commandLine_CommandLine = /*#__PURE__*/ function (_Component) { commandLine_inherits(CommandLine, _Component); function CommandLine(props) { commandLine_classCallCheck(this, CommandLine); return commandLine_possibleConstructorReturn(this, commandLine_getPrototypeOf(CommandLine).call(this, props)); } commandLine_createClass(CommandLine, [{ key: "render", value: function render() { var _this$props = this.props, hoverCard = _this$props.hoverCard, controlCard = _this$props.controlCard, editControlCard = _this$props.editControlCard; return external_react_default.a.createElement(Command, null, "CONSOLE", controlCard ? external_react_default.a.createElement(console_CommandLine, { editControlCard: editControlCard, controlCard: controlCard }) : hoverCard ? external_react_default.a.createElement(console_CommandLine, { controlCard: hoverCard }) : null); } }]); return CommandLine; }(external_react_["Component"]); var Command = external_styled_components_default.a.div(commandLine_templateObject()); // EXTERNAL MODULE: external "socket.io-client" var external_socket_io_client_ = __webpack_require__(8); var external_socket_io_client_default = /*#__PURE__*/__webpack_require__.n(external_socket_io_client_); // CONCATENATED MODULE: ./redux/actions/api.js var socket = external_socket_io_client_default()('http://localhost:8000'); function updateGameboard(callback) { socket.on('updateGameboard', function (slots) { console.log('updateGameboard'); callback(null, slots); }); } function pushGameboard(slots) { console.log('pushGameboard', slots); socket.emit('pushGameboard', slots); } // CONCATENATED MODULE: ./components/cardGame/gameBoard.js function gameBoard_templateObject() { var data = gameBoard_taggedTemplateLiteral(["\nmargin:30px;\nwidth:380px;\nheight:330px;\nbackground:url(/static/img/timber.jpg/);\nbackground-size:cover;\nborder:1px solid #666;\nborder-radius:4px;\n"]); gameBoard_templateObject = function _templateObject() { return data; }; return data; } function gameBoard_taggedTemplateLiteral(strings, raw) { if (!raw) { raw = strings.slice(0); } return Object.freeze(Object.defineProperties(strings, { raw: { value: Object.freeze(raw) } })); } function gameBoard_typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { gameBoard_typeof = function _typeof(obj) { return typeof obj; }; } else { gameBoard_typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return gameBoard_typeof(obj); } function gameBoard_objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { gameBoard_defineProperty(target, key, source[key]); }); } return target; } function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } function gameBoard_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function gameBoard_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); } } function gameBoard_createClass(Constructor, protoProps, staticProps) { if (protoProps) gameBoard_defineProperties(Constructor.prototype, protoProps); if (staticProps) gameBoard_defineProperties(Constructor, staticProps); return Constructor; } function gameBoard_possibleConstructorReturn(self, call) { if (call && (gameBoard_typeof(call) === "object" || typeof call === "function")) { return call; } return gameBoard_assertThisInitialized(self); } function gameBoard_getPrototypeOf(o) { gameBoard_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return gameBoard_getPrototypeOf(o); } function gameBoard_inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) gameBoard_setPrototypeOf(subClass, superClass); } function gameBoard_setPrototypeOf(o, p) { gameBoard_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return gameBoard_setPrototypeOf(o, p); } function gameBoard_assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function gameBoard_defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } var gameBoard_GameBoard = /*#__PURE__*/ function (_Component) { gameBoard_inherits(GameBoard, _Component); function GameBoard() { var _this; gameBoard_classCallCheck(this, GameBoard); _this = gameBoard_possibleConstructorReturn(this, gameBoard_getPrototypeOf(GameBoard).call(this)); gameBoard_defineProperty(gameBoard_assertThisInitialized(gameBoard_assertThisInitialized(_this)), "turnPoss", function (poss) { return 1 - poss; }); gameBoard_defineProperty(gameBoard_assertThisInitialized(gameBoard_assertThisInitialized(_this)), "flipCard", function (ind, index, card) { var slots = _toConsumableArray(_this.state.slots); //flip possession between 1 and slots[ind][index].card.poss = _this.turnPoss(card.poss); var row = ind; var column = index; //ripple slots.map(function (r, i) { r.map(function (c, ii) { if (!c.card) return; if (c.card.poss === card.poss) return; //check left and right if (i === row) { if (ii === column - 1) { if (card.l > c.card.r) slots[i][ii].card.poss = _this.turnPoss(c.card.poss); } if (ii === column + 1) { if (card.r > c.card.l) slots[i][ii].card.poss = _this.turnPoss(c.card.poss); } } //check top and bottom if (ii === column) { if (i === row - 1) { if (card.u > c.card.d) slots[i][ii].card.poss = _this.turnPoss(c.card.poss); } if (i === row + 1) { if (card.d > c.card.u) slots[i][ii].card.poss = _this.turnPoss(c.card.poss); } } }); }); _this.setState({ slots: slots }); }); gameBoard_defineProperty(gameBoard_assertThisInitialized(gameBoard_assertThisInitialized(_this)), "updateBoard", function (slots, row, column, card) { slots.map(function (r, i) { r.map(function (c, ii) { if (!c.card) return; if (c.card.poss === card.poss) return; //check left and right if (i === row) { if (ii === column - 1) { if (card.l > c.card.r) _this.flipCard(i, ii, c.card); } if (ii === column + 1) { if (card.r > c.card.l) _this.flipCard(i, ii, c.card); } } //check top and bottom if (ii === column) { if (i === row - 1) { if (card.u > c.card.d) _this.flipCard(i, ii, c.card); } if (i === row + 1) { if (card.d > c.card.u) _this.flipCard(i, ii, c.card); } } }); }); }); gameBoard_defineProperty(gameBoard_assertThisInitialized(gameBoard_assertThisInitialized(_this)), "updateSlots", function (row, column, card) { if (card) return; var slots = _this.state.slots; var _this$props = _this.props, controlCard = _this$props.controlCard, updateHand = _this$props.updateHand; if (!controlCard) return; _this.updateBoard(slots, row, column, controlCard); slots[row][column] = gameBoard_objectSpread({}, slots[row][column], { card: gameBoard_objectSpread({}, controlCard) }); updateHand(controlCard); _this.setState({ slots: slots }); // websocket pushGameboard(slots); }); _this.state = { slots: null }; return _this; } gameBoard_createClass(GameBoard, [{ key: "componentWillMount", value: function componentWillMount() { var _this2 = this; //subscribe to websocket events here updateGameboard(function (err, slots) { console.log(slots); _this2.setState({ slots: slots }); }); var slots = []; for (var h = 0; h < 3; h++) { slots.push([]); for (var i = 0; i < 4; i++) { slots[h].push({ row: h, column: i, card: null }); } } this.setState({ slots: slots }); } }, { key: "render", value: function render() { var _this3 = this; var _this$props2 = this.props, controlCard = _this$props2.controlCard, hoverCard = _this$props2.hoverCard, updateHand = _this$props2.updateHand, editControlCard = _this$props2.editControlCard; var slots = this.state.slots; var gameBoard = slots && slots.map(function (o, i) { return o.map(function (card, ind) { return external_react_default.a.createElement(cardSlot_CardSlot, { key: Math.random(0, 20000), row: card.row, updateSlots: _this3.updateSlots, controlCard: controlCard, column: card.column, card: card.card }); }); }); return external_react_default.a.createElement("div", { style: { display: 'flex', flexDirection: 'row', justifyContent: 'center', flexWrap: 'nowrap' } }, external_react_default.a.createElement(Board, null, gameBoard), external_react_default.a.createElement(commandLine_CommandLine, { editControlCard: editControlCard, controlCard: controlCard, hoverCard: hoverCard })); } }]); return GameBoard; }(external_react_["Component"]); var Board = external_styled_components_default.a.div(gameBoard_templateObject()); // CONCATENATED MODULE: ./components/cardGame/gameTable.js function gameTable_templateObject2() { var data = gameTable_taggedTemplateLiteral(["\n\n"]); gameTable_templateObject2 = function _templateObject2() { return data; }; return data; } function gameTable_templateObject() { var data = gameTable_taggedTemplateLiteral(["\nwidth:100%;\n"]); gameTable_templateObject = function _templateObject() { return data; }; return data; } function gameTable_taggedTemplateLiteral(strings, raw) { if (!raw) { raw = strings.slice(0); } return Object.freeze(Object.defineProperties(strings, { raw: { value: Object.freeze(raw) } })); } function gameTable_typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { gameTable_typeof = function _typeof(obj) { return typeof obj; }; } else { gameTable_typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return gameTable_typeof(obj); } function gameTable_objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { gameTable_defineProperty(target, key, source[key]); }); } return target; } function gameTable_toConsumableArray(arr) { return gameTable_arrayWithoutHoles(arr) || gameTable_iterableToArray(arr) || gameTable_nonIterableSpread(); } function gameTable_nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } function gameTable_iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } function gameTable_arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } function gameTable_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function gameTable_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); } } function gameTable_createClass(Constructor, protoProps, staticProps) { if (protoProps) gameTable_defineProperties(Constructor.prototype, protoProps); if (staticProps) gameTable_defineProperties(Constructor, staticProps); return Constructor; } function gameTable_possibleConstructorReturn(self, call) { if (call && (gameTable_typeof(call) === "object" || typeof call === "function")) { return call; } return gameTable_assertThisInitialized(self); } function gameTable_getPrototypeOf(o) { gameTable_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return gameTable_getPrototypeOf(o); } function gameTable_inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) gameTable_setPrototypeOf(subClass, superClass); } function gameTable_setPrototypeOf(o, p) { gameTable_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return gameTable_setPrototypeOf(o, p); } function gameTable_assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function gameTable_defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } var gameTable_GameTable = /*#__PURE__*/ function (_Component) { gameTable_inherits(GameTable, _Component); function GameTable(props) { var _this; gameTable_classCallCheck(this, GameTable); _this = gameTable_possibleConstructorReturn(this, gameTable_getPrototypeOf(GameTable).call(this, props)); gameTable_defineProperty(gameTable_assertThisInitialized(gameTable_assertThisInitialized(_this)), "setControlCard", function (card) { var controlCard = _this.state.controlCard; if (controlCard === card) card = null; _this.setState({ controlCard: card }); }); gameTable_defineProperty(gameTable_assertThisInitialized(gameTable_assertThisInitialized(_this)), "setHoverCard", function (card) { var hoverCard = _this.state.hoverCard; if (hoverCard !== card) _this.setState({ hoverCard: card }); }); gameTable_defineProperty(gameTable_assertThisInitialized(gameTable_assertThisInitialized(_this)), "updateHand", function (card) { var hand = gameTable_toConsumableArray(_this.state.hand); var usedCardIndex = hand.findIndex(function (f) { return f.name === card.name; }); var newHand = hand.splice(usedCardIndex, 1); _this.setState({ hand: hand, controlCard: null }); }); gameTable_defineProperty(gameTable_assertThisInitialized(gameTable_assertThisInitialized(_this)), "editControlCard", function (powerup) { var controlCard = gameTable_objectSpread({}, _this.state.controlCard); controlCard.pocket -= powerup.price; controlCard.u += powerup.effect; controlCard.r += powerup.effect; controlCard.l += powerup.effect; controlCard.d += powerup.effect; controlCard.powups = controlCard.powups.map(function (p, ii) { if (p.id === powerup.id) { p = gameTable_objectSpread({}, p, { active: true }); } return p; }); _this.setState({ controlCard: controlCard }); }); _this.state = { controlCard: null, hoverCard: null, hand: props.hand }; return _this; } gameTable_createClass(GameTable, [{ key: "render", value: function render() { var _this2 = this; var _this$state = this.state, controlCard = _this$state.controlCard, hoverCard = _this$state.hoverCard, hand = _this$state.hand; var myHand = hand.map(function (o, i) { var selected = controlCard && controlCard.name === o.name; return external_react_default.a.createElement(card_Card, { key: i, card: o, setHoverCard: _this2.setHoverCard, selected: selected, index: i, inGame: true, setControlCard: _this2.setControlCard }); }); return external_react_default.a.createElement(Envelope, null, external_react_default.a.createElement(gameBoard_GameBoard, { controlCard: controlCard, hand: hand, editControlCard: this.editControlCard, hoverCard: hoverCard, updateHand: this.updateHand }), external_react_default.a.createElement(Hand, null, myHand)); } }]); return GameTable; }(external_react_["Component"]); var Envelope = external_styled_components_default.a.div(gameTable_templateObject()); var Hand = external_styled_components_default.a.div(gameTable_templateObject2()); // CONCATENATED MODULE: ./components/cardGame/ui/button.js function button_templateObject() { var data = button_taggedTemplateLiteral(["\ndisplay:inline-block;\nfont-size:28px;\ntext-align:center;\nbackground:#222;\ncolor:#eee;\nposition:relative;\nwidth:100px;\nheight:38px;\nmargin:5px;\nborder-radius:4px;\nborder: 2px solid #555;\ntransition: all 0.15s;\n&:hover{\n\ttransform:scale(1.18);\n};\n"]); button_templateObject = function _templateObject() { return data; }; return data; } function button_taggedTemplateLiteral(strings, raw) { if (!raw) { raw = strings.slice(0); } return Object.freeze(Object.defineProperties(strings, { raw: { value: Object.freeze(raw) } })); } function button_typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { button_typeof = function _typeof(obj) { return typeof obj; }; } else { button_typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return button_typeof(obj); } function button_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function button_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); } } function button_createClass(Constructor, protoProps, staticProps) { if (protoProps) button_defineProperties(Constructor.prototype, protoProps); if (staticProps) button_defineProperties(Constructor, staticProps); return Constructor; } function button_possibleConstructorReturn(self, call) { if (call && (button_typeof(call) === "object" || typeof call === "function")) { return call; } return button_assertThisInitialized(self); } function button_assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function button_getPrototypeOf(o) { button_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return button_getPrototypeOf(o); } function button_inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) button_setPrototypeOf(subClass, superClass); } function button_setPrototypeOf(o, p) { button_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return button_setPrototypeOf(o, p); } var button_Button = /*#__PURE__*/ function (_Component) { button_inherits(Button, _Component); function Button() { button_classCallCheck(this, Button); return button_possibleConstructorReturn(this, button_getPrototypeOf(Button).apply(this, arguments)); } button_createClass(Button, [{ key: "render", value: function render() { var _this$props = this.props, label = _this$props.label, action = _this$props.action; return external_react_default.a.createElement(B, { onClick: function onClick() { return action(); } }, label); } }]); return Button; }(external_react_["Component"]); var B = external_styled_components_default.a.div(button_templateObject()); // CONCATENATED MODULE: ./components/cardGame/cardSelect.js function cardSelect_templateObject3() { var data = cardSelect_taggedTemplateLiteral(["\nmargin:30px;\ntext-align:center;\n"]); cardSelect_templateObject3 = function _templateObject3() { return data; }; return data; } function cardSelect_templateObject2() { var data = cardSelect_taggedTemplateLiteral(["\ndisplay:flex;\nwidth:50%;\nbox-shadow: 0 15px 20px rgba(0, 0, 0, 0.3); \npadding:20px;\nborder:4px dotted #333;\nbackground: #d6d6d6;\nflex-flow: row wrap;\n"]); cardSelect_templateObject2 = function _templateObject2() { return data; }; return data; } function cardSelect_templateObject() { var data = cardSelect_taggedTemplateLiteral(["\ndisplay:flex;\nflex-direction:column;\npadding:50px;\nheight:100%;\nalign-items: center;\n"]); cardSelect_templateObject = function _templateObject() { return data; }; return data; } function cardSelect_taggedTemplateLiteral(strings, raw) { if (!raw) { raw = strings.slice(0); } return Object.freeze(Object.defineProperties(strings, { raw: { value: Object.freeze(raw) } })); } function cardSelect_typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { cardSelect_typeof = function _typeof(obj) { return typeof obj; }; } else { cardSelect_typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return cardSelect_typeof(obj); } function cardSelect_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function cardSelect_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); } } function cardSelect_createClass(Constructor, protoProps, staticProps) { if (protoProps) cardSelect_defineProperties(Constructor.prototype, protoProps); if (staticProps) cardSelect_defineProperties(Constructor, staticProps); return Constructor; } function cardSelect_possibleConstructorReturn(self, call) { if (call && (cardSelect_typeof(call) === "object" || typeof call === "function")) { return call; } return cardSelect_assertThisInitialized(self); } function cardSelect_getPrototypeOf(o) { cardSelect_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return cardSelect_getPrototypeOf(o); } function cardSelect_inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) cardSelect_setPrototypeOf(subClass, superClass); } function cardSelect_setPrototypeOf(o, p) { cardSelect_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return cardSelect_setPrototypeOf(o, p); } function cardSelect_assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function cardSelect_defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } var cardSelect_CardSelect = /*#__PURE__*/ function (_Component) { cardSelect_inherits(CardSelect, _Component); function CardSelect() { var _getPrototypeOf2; var _this; cardSelect_classCallCheck(this, CardSelect); for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = cardSelect_possibleConstructorReturn(this, (_getPrototypeOf2 = cardSelect_getPrototypeOf(CardSelect)).call.apply(_getPrototypeOf2, [this].concat(args))); cardSelect_defineProperty(cardSelect_assertThisInitialized(cardSelect_assertThisInitialized(_this)), "state", { selected: [] }); cardSelect_defineProperty(cardSelect_assertThisInitialized(cardSelect_assertThisInitialized(_this)), "toggleCard", function (card) { var selected = _this.state.selected; var exists = selected.findIndex(function (f) { return f.name === card.name; }); if (exists !== -1) { selected.splice(exists, 1); } else { // if (selected.length > 5) { // console.log('dont allow') // return // } selected.push(card); } _this.setState({ selected: selected }); }); return _this; } cardSelect_createClass(CardSelect, [{ key: "render", value: function render() { var _this2 = this; var selected = this.state.selected; var _this$props = this.props, cards = _this$props.cards, pickHand = _this$props.pickHand; var allCards = cards && cards.map(function (o, i) { var picked = selected.find(function (f) { return f.name === o.name; }); return external_react_default.a.createElement(card_Card, { key: i, card: o, toggleCard: _this2.toggleCard, selected: picked, index: i, inGame: false }); }); return external_react_default.a.createElement(cardSelect_Envelope, null, external_react_default.a.createElement("div", null, external_react_default.a.createElement("span", null, "Hand: ", selected.length, "/5")), external_react_default.a.createElement(Frame, null, allCards), external_react_default.a.createElement(Bottom, null, external_react_default.a.createElement(button_Button, { label: "Start", action: function action() { return pickHand(selected); } }))); } }]); return CardSelect; }(external_react_["Component"]); var cardSelect_Envelope = external_styled_components_default.a.div(cardSelect_templateObject()); var Frame = external_styled_components_default.a.div(cardSelect_templateObject2()); var Bottom = external_styled_components_default.a.div(cardSelect_templateObject3()); // CONCATENATED MODULE: ./components/data/cardData.js function cardData() { var cardData = []; function getRandomInt(max) { return Math.floor(Math.random() * Math.floor(max)) + 1; } var pups = ['hook', 'lamp', 'turkey', 'antimatter', 'bandana', 'buckle', 'comb', 'squeegee', 'pecan pie', 'neurobeam']; var powerups = function powerups() { var pu = []; var _loop = function _loop(i) { var item = getRandomInt(10) - 1; while (pu.find(function (f) { return f.name === pups[item]; })) { item = getRandomInt(10) - 1; } pu.push({ name: pups[item], img: "pow_".concat(item, ".png"), price: getRandomInt(3), active: false, effect: getRandomInt(3), id: i }); }; for (var i = 0; i < 7; i++) { _loop(i); } return pu; }; for (var i = 0; i < 21; i++) { cardData.push({ img: "p".concat(i, ".png"), id: i, name: "card".concat(i), u: getRandomInt(10), d: getRandomInt(10), l: getRandomInt(10), r: getRandomInt(10), powups: powerups(), poss: getRandomInt(2) - 1, pocket: getRandomInt(5) }); } return cardData; } // CONCATENATED MODULE: ./components/cardGame/gameWindow.js function gameWindow_typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { gameWindow_typeof = function _typeof(obj) { return typeof obj; }; } else { gameWindow_typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return gameWindow_typeof(obj); } function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } function gameWindow_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function gameWindow_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); } } function gameWindow_createClass(Constructor, protoProps, staticProps) { if (protoProps) gameWindow_defineProperties(Constructor.prototype, protoProps); if (staticProps) gameWindow_defineProperties(Constructor, staticProps); return Constructor; } function gameWindow_possibleConstructorReturn(self, call) { if (call && (gameWindow_typeof(call) === "object" || typeof call === "function")) { return call; } return gameWindow_assertThisInitialized(self); } function gameWindow_getPrototypeOf(o) { gameWindow_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return gameWindow_getPrototypeOf(o); } function gameWindow_inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) gameWindow_setPrototypeOf(subClass, superClass); } function gameWindow_setPrototypeOf(o, p) { gameWindow_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return gameWindow_setPrototypeOf(o, p); } function gameWindow_assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function gameWindow_defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } var defaultState = { cards: cardData(), hand: null }; var gameWindow_GameWindow = /*#__PURE__*/ function (_Component) { gameWindow_inherits(GameWindow, _Component); function GameWindow() { var _this; gameWindow_classCallCheck(this, GameWindow); _this = gameWindow_possibleConstructorReturn(this, gameWindow_getPrototypeOf(GameWindow).call(this)); gameWindow_defineProperty(gameWindow_assertThisInitialized(gameWindow_assertThisInitialized(_this)), "pickHand", function (hand) { _this.setState({ hand: hand }); }); gameWindow_defineProperty(gameWindow_assertThisInitialized(gameWindow_assertThisInitialized(_this)), "clearGame", function () { console.log('clear'); _this.setState(defaultState); }); _this.state = defaultState; return _this; } gameWindow_createClass(GameWindow, [{ key: "render", value: function render() { var _this2 = this; var _this$state = this.state, cards = _this$state.cards, hand = _this$state.hand; console.log("GAME WINDOW", this.props); return external_react_default.a.createElement("div", { style: { height: '100vh' } }, hand ? external_react_default.a.createElement("div", null, external_react_default.a.createElement(button_Button, { label: "Back", action: function action() { return _this2.clearGame(); } }), external_react_default.a.createElement(gameTable_GameTable, { hand: hand })) : external_react_default.a.createElement(cardSelect_CardSelect, _extends({}, this.props, { pickHand: this.pickHand, cards: cards }))); } }]); return GameWindow; }(external_react_["Component"]); // CONCATENATED MODULE: ./components/app.js function app_typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { app_typeof = function _typeof(obj) { return typeof obj; }; } else { app_typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return app_typeof(obj); } function app_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function app_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); } } function app_createClass(Constructor, protoProps, staticProps) { if (protoProps) app_defineProperties(Constructor.prototype, protoProps); if (staticProps) app_defineProperties(Constructor, staticProps); return Constructor; } function app_possibleConstructorReturn(self, call) { if (call && (app_typeof(call) === "object" || typeof call === "function")) { return call; } return app_assertThisInitialized(self); } function app_assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function app_getPrototypeOf(o) { app_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return app_getPrototypeOf(o); } function app_inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) app_setPrototypeOf(subClass, superClass); } function app_setPrototypeOf(o, p) { app_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return app_setPrototypeOf(o, p); } var app_App = /*#__PURE__*/ function (_Component) { app_inherits(App, _Component); function App() { app_classCallCheck(this, App); return app_possibleConstructorReturn(this, app_getPrototypeOf(App).apply(this, arguments)); } app_createClass(App, [{ key: "render", value: function render() { return external_react_default.a.createElement("div", { style: { height: '100vh', width: '100vw', background: '#d1d1d1', textAlign: 'center', justifyContents: 'center' } }, external_react_default.a.createElement(gameWindow_GameWindow, this.props)); } }]); return App; }(external_react_["Component"]); // EXTERNAL MODULE: external "react-redux" var external_react_redux_ = __webpack_require__(9); // CONCATENATED MODULE: ./pages/index.js /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "default", function() { return pages_default; }); function pages_typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { pages_typeof = function _typeof(obj) { return typeof obj; }; } else { pages_typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return pages_typeof(obj); } function pages_classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function pages_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); } } function pages_createClass(Constructor, protoProps, staticProps) { if (protoProps) pages_defineProperties(Constructor.prototype, protoProps); if (staticProps) pages_defineProperties(Constructor, staticProps); return Constructor; } function pages_possibleConstructorReturn(self, call) { if (call && (pages_typeof(call) === "object" || typeof call === "function")) { return call; } return pages_assertThisInitialized(self); } function pages_assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function pages_getPrototypeOf(o) { pages_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return pages_getPrototypeOf(o); } function pages_inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) pages_setPrototypeOf(subClass, superClass); } function pages_setPrototypeOf(o, p) { pages_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return pages_setPrototypeOf(o, p); } // import css from 'antd/dist/antd.min.css' var pages_default = /*#__PURE__*/ function (_Component) { pages_inherits(_default, _Component); function _default() { pages_classCallCheck(this, _default); return pages_possibleConstructorReturn(this, pages_getPrototypeOf(_default).apply(this, arguments)); } pages_createClass(_default, [{ key: "render", value: function render() { return external_react_default.a.createElement(external_react_redux_["Provider"], { store: store }, external_react_default.a.createElement(app_App, this.props)); } }]); return _default; }(external_react_["Component"]); /***/ }) /******/ ]);
// set up vector class class Vec { constructor(x = 0, y = 0) { this.x = x; this.y = y; } //set up length get len(){ return Math.sqrt(this.x *this.x + this.y* this.y) } set len(value) { const fact = value / this.len; this.x *= fact; this.y *= fact; } } // set up Rect class class Rect { constructor(w, h) { this.pos = new Vec; this.size = new Vec(w, h); } // setting the borders of the rectangle get left() { return this.pos.x - this.size.x / 2; } get right() { return this.pos.x + this.size.x / 2; } get top() { return this.pos.y - this.size.y / 2; } get bottom() { return this.pos.y + this.size.y / 2; } } // set up ball class extended from rect class Ball extends Rect { constructor() { //creates a 10 x 10 super(10, 10); //set up velocity this.vel = new Vec; } } // set up player class extended from Rect class Player extends Rect { constructor() { // creates a player bar 20 x 100 super(20, 100); // adds the score element to each player this.score = 0; } } //set up pong class class Pong { constructor(canvas) { this._canvas = canvas; this._context = canvas.getContext('2d'); this.ball = new Ball; // creates 2 players this.players = [ new Player, new Player, ] // set player 1 position this.players[0].pos.x = 40; // set player 2 position this.players[1].pos.x = this._canvas.width - 40; //centers the player bars this.players.forEach(player => { player.pos.y = this._canvas.height / 2; }); //declare callback variables and function let lastTime; //callback arrow function const callback = (millis) => { //converts to milliseconds to seconds if (lastTime) { this.update((millis - lastTime) / 1000); } lastTime = millis; requestAnimationFrame(callback); }; // call calback callback(); //call reset this.reset(); } // collide with ball collide(player, ball) { //check if the ball hits either player if (player.left < ball.right && player.right > ball.left && player.top < ball.bottom && player.bottom > ball.top) { const len = ball.vel.len; //reverse the ball velocity ball.vel.x = -ball.vel.x; ball.vel.y += 300 * (Math.random() - .5) // up ball velocity by5% 0n hit ball.vel.len = len *1.05; } } //draw function draw() { //draws canvas this._context.fillStyle = '#1c1d25'; this._context.fillRect(0, 0, this._canvas.width, this._canvas.height); this.drawRect(this.ball); //draws players this.players.forEach(player => this.drawRect(player)); } //draw rectangle function drawRect(rect) { //draws ball and players white this._context.fillStyle = 'orange'; this._context.fillRect(rect.left, rect.top, rect.size.x, rect.size.y); } //reset Ball reset(){ //creates new ball this.ball.pos.x = this._canvas.width / 2; this.ball.pos.y = this._canvas.height / 2; this.ball.vel.x = 0; this.ball.vel.y = 0; } start() { if (this.ball.vel.x === 0 && this.ball.vel.y === 0){ this.ball.vel.x =300 *(Math.random() > .5 ? 1 : - 1); this.ball.vel.y = 300 *(Math.random() * 2 -1); this.ball.vel.len = 400; } } //update function update(dt) { this.ball.pos.x += this.ball.vel.x * dt; this.ball.pos.y += this.ball.vel.y * dt; // change the x velocity of the ball if it collides with the borders if (this.ball.left < 0 || this.ball.right > this._canvas.width) { const playerId = this.ball.vel.x < 0 | 0; console.log(playerId); //increase player score this.players[playerId].score++; this.ball.vel.x = -this.ball.vel.x; this.reset(); } // change the Y velocity of the ball if it collides with borders if (this.ball.top < 0 || this.ball.bottom > this._canvas.height) { this.ball.vel.y = -this.ball.vel.y; } // make the CPU player follow the ball this.players[1].pos.y = this.ball.pos.y; // for each collision with player this.players.forEach(player => this.collide(player, this.ball)); // draw function call this.draw(); } } //variables for the canvas element const canvas = document.getElementById('pong'); const pong = new Pong(canvas); // add event lisnter for player 1 movement on mouse canvas.addEventListener('mousemove', event => { pong.players[0].pos.y = event.offsetY; }); // event listner for click to start / restart canvas.addEventListener('click', event => { pong.start(); });
function calPrice(){ if (typeof days !== 0) { Price("Mont-Blanc PackT", days); Price("alpinismShoes", days); Price("Crampons", days); Price("iceAxe", days); Price("helmet", days); Price("harness", days); Price("gaiters", days); Price("poles", days); Price("techIceAxes", days); Price("backpack", days); Price("climbShoes", days); Price("gailland", days); Price("kidClimbShoe", days); Price("stroller", days); Price("crashPad", days); Price("slackline", days); Price("shockAbs", days); Price("viaFerrata", days); Price("trekShoe", days); Price("cramponIce", days); }; };
"use strict"; (function () { const CLOUD_WIDTH = 420; const CLOUD_HEIGHT = 270; const CLOUD_X = 100; const CLOUD_Y = 10; const GAP = 10; const GAP_BAR = 50; const FONT_GAP = 18; const GREETING_X = 120; const GREETING_Y = 30; const MAX_BAR_HEIGHT = 150; const BAR_WIDTH = 40; const renderCloud = (ctx, x, y, color) => { ctx.fillStyle = color; ctx.fillRect(x, y, CLOUD_WIDTH, CLOUD_HEIGHT); }; const getMaxElement = (arr) => { let maxElement = arr[0]; for (let i = 1; i < arr.length; i++) { if (arr[i] > maxElement) { maxElement = arr[i]; } } return maxElement; }; window.renderStatistics = (ctx, players, times) => { renderCloud(ctx, CLOUD_X + GAP, CLOUD_Y + GAP, `rgba(0, 0, 0, 0.7)`); renderCloud(ctx, CLOUD_X, CLOUD_Y, `#fff`); ctx.fillStyle = `#000`; ctx.font = `16px PT Mono`; ctx.textBaseline = `hanging`; ctx.fillText(`Ура вы победили!`, GREETING_X, GREETING_Y); ctx.fillText(`Список результатов:`, GREETING_X, GREETING_Y + FONT_GAP); const maxTime = getMaxElement(times); players.forEach((player, i) => { // рисует score ctx.fillStyle = `#000`; ctx.fillText( (times[i]).toFixed(0), (CLOUD_X + GAP * 4) + (BAR_WIDTH + GAP_BAR) * i, CLOUD_HEIGHT - GAP * 4 - (MAX_BAR_HEIGHT * times[i]) / maxTime ); // меняет цвет bar if (player === `Вы`) { ctx.fillStyle = `rgba(255, 0, 0, 1)`; } else { const saturation = Math.round(Math.random() * 100); ctx.fillStyle = `hsl(240, ${saturation}%, 50%)`; } // рисует bar ctx.fillRect( (CLOUD_X + GAP * 4) + (BAR_WIDTH + GAP_BAR) * i, CLOUD_HEIGHT - GAP * 2 - (MAX_BAR_HEIGHT * times[i]) / maxTime, BAR_WIDTH, (MAX_BAR_HEIGHT * times[i]) / maxTime ); // рисует имя игрока ctx.fillStyle = `#000`; ctx.fillText( player, (CLOUD_X + GAP * 4) + (BAR_WIDTH + GAP_BAR) * i, CLOUD_HEIGHT - GAP ); }); }; })();
controllers .controller('canceledNotificationsController', function ($scope, $state, canceled) { console.log('canceledNotificationsController started'); var vm = this; $scope.consulta = canceled.data; vm.return = function () { $state.go('app.notifications.list'); }; });
function loadList() { var service = 'services/video.php' ; var method='GET'; var args = {"_": new Date().getMilliseconds()} //CallService(service,args,setview); utility.service(service,method,args,setview,settinglightSlider) } function loadvideomain(){ var service = 'services/video.php' ; var method='GET'; var args = {"_": new Date().getMilliseconds()} //CallService(service,args,setview); utility.service(service,method,args,setview,indexlightSlider) } function CallService(service,param,callback) { $.ajax({ url:service, type:'GET', data:param, dataType:'json', success : callback , error:function(xhr,status,err){ alert(err.message); } }); } function setview(data) { $('#list').html(""); setdefaultview(data.result[0]);//default first video $.each(data.result,function(i,val){ var itemview = ""; itemview += "<li data-link='"+val.link+"' >"; itemview += "<img src='"+val.thumbnail+"' class='img-responsive' />";//responsive itemview += "<div class='lightslider-desc' >"; itemview += "<label>"+val.title+"</label>"; itemview += "</div>"; itemview += "</li>"; $('#list').append(itemview); }); $('#list').find('li').click(function(){ var link = $(this).attr('data-link'); var title = $(this).children().find('label').text(); if(link != undefined){ //var url = link.replace("watch?v=", "v/"); $('#title').text(title); $('#mediaplayer').attr('src',link); } }); } function settinglightSlider(){ $("#list").lightSlider({ autoWidth: false ,adaptiveHeight:false ,loop:true ,keyPress:false ,item:3 }); /*http://sachinchoolur.github.io/lightslider/settings.html*/ } function indexlightSlider(){ $("#list").lightSlider({ autoWidth: false ,adaptiveHeight:true ,loop:true ,keyPress:false ,item:2 ,slideMargin:4 ,slideWidth:200 }); } function setdefaultview(item){ $('#title').text(item.title); $('#mediaplayer').attr('src',item.link); }
/* ** Copyright (c) Richard Uren 2012 - 2015 <richard@teleport.com.au> ** All Rights Reserved ** ** -- ** ** LICENSE: Redistribution and use in source and binary forms, with or ** without modification, are permitted provided that the following ** conditions are met: Redistributions of source code must retain the ** above copyright notice, this list of conditions and the following ** disclaimer. Redistributions in binary form must reproduce the above ** copyright notice, this list of conditions and the following disclaimer ** in the documentation and/or other materials provided with the ** distribution. ** ** THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED ** WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF ** MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN ** NO EVENT SHALL CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, ** INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, ** BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS ** OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ** ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR ** TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE ** USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH ** DAMAGE. ** */ class HDBase { constructor(tree) { this.tree = tree; this.detectedRuleKey = {}; this.reply = null; this.detectionConfig = { 'device-ua-order': ['x-operamini-phone-ua', 'x-mobile-ua', 'device-stock-ua', 'user-agent', 'agent'], 'platform-ua-order': ['x-operamini-phone-ua', 'x-mobile-ua', 'device-stock-ua', 'user-agent', 'agent'], 'browser-ua-order': ['user-agent', 'agent', 'device-stock-ua'], 'app-ua-order': ['user-agent', 'agent', 'device-stock-ua'], 'language-ua-order': ['user-agent', 'agent', 'device-stock-ua'], 'device-bi-order': { 'android': [ ['ro.product.brand','ro.product.model'], ['ro.product.manufacturer','ro.product.model'], ['ro-product-brand','ro-product-model'], ['ro-product-manufacturer','ro-product-model'], ], 'ios': [ ['utsname.brand','utsname.machine'] ], 'windows phone': [ ['devicemanufacturer','devicename'] ] }, 'platform-bi-order': { 'android': [ ['hd-platform', 'ro.build.version.release'], ['hd-platform', 'ro-build-version-release'], ['hd-platform', 'ro.build.id'], ['hd-platform', 'ro-build-id'] ], 'ios': [ ['uidevice.systemname','uidevice.systemversion'], ['hd-platform','uidevice.systemversion'] ], 'windows phone': [ ['osname','osversion'], ['hd-platform','osversion'] ] }, 'browser-bi-order': {}, 'app-bi-order': {} }; this.detectionLanguages = { 'af': 'Afrikaans', 'sq': 'Albanian', 'ar-dz': 'Arabic (Algeria)', 'ar-bh': 'Arabic (Bahrain)', 'ar-eg': 'Arabic (Egypt)', 'ar-iq': 'Arabic (Iraq)', 'ar-jo': 'Arabic (Jordan)', 'ar-kw': 'Arabic (Kuwait)', 'ar-lb': 'Arabic (Lebanon)', 'ar-ly': 'Arabic (libya)', 'ar-ma': 'Arabic (Morocco)', 'ar-om': 'Arabic (Oman)', 'ar-qa': 'Arabic (Qatar)', 'ar-sa': 'Arabic (Saudi Arabia)', 'ar-sy': 'Arabic (Syria)', 'ar-tn': 'Arabic (Tunisia)', 'ar-ae': 'Arabic (U.A.E.)', 'ar-ye': 'Arabic (Yemen)', 'ar': 'Arabic', 'hy': 'Armenian', 'as': 'Assamese', 'az': 'Azeri', 'eu': 'Basque', 'be': 'Belarusian', 'bn': 'Bengali', 'bg': 'Bulgarian', 'ca': 'Catalan', 'zh-cn': 'Chinese (China)', 'zh-hk': 'Chinese (Hong Kong SAR)', 'zh-mo': 'Chinese (Macau SAR)', 'zh-sg': 'Chinese (Singapore)', 'zh-tw': 'Chinese (Taiwan)', 'zh': 'Chinese', 'hr': 'Croatian', 'cs': 'Czech', 'da': 'Danish', 'da-dk': 'Danish', 'div': 'Divehi', 'nl-be': 'Dutch (Belgium)', 'nl': 'Dutch (Netherlands)', 'en-au': 'English (Australia)', 'en-bz': 'English (Belize)', 'en-ca': 'English (Canada)', 'en-ie': 'English (Ireland)', 'en-jm': 'English (Jamaica)', 'en-nz': 'English (New Zealand)', 'en-ph': 'English (Philippines)', 'en-za': 'English (South Africa)', 'en-tt': 'English (Trinidad)', 'en-gb': 'English (United Kingdom)', 'en-us': 'English (United States)', 'en-zw': 'English (Zimbabwe)', 'en': 'English', 'us': 'English (United States)', 'et': 'Estonian', 'fo': 'Faeroese', 'fa': 'Farsi', 'fi': 'Finnish', 'fr-be': 'French (Belgium)', 'fr-ca': 'French (Canada)', 'fr-lu': 'French (Luxembourg)', 'fr-mc': 'French (Monaco)', 'fr-ch': 'French (Switzerland)', 'fr': 'French (France)', 'mk': 'FYRO Macedonian', 'gd': 'Gaelic', 'ka': 'Georgian', 'de-at': 'German (Austria)', 'de-li': 'German (Liechtenstein)', 'de-lu': 'German (Luxembourg)', 'de-ch': 'German (Switzerland)', 'de-de': 'German (Germany)', 'de': 'German (Germany)', 'el': 'Greek', 'gu': 'Gujarati', 'he': 'Hebrew', 'hi': 'Hindi', 'hu': 'Hungarian', 'is': 'Icelandic', 'id': 'Indonesian', 'it-ch': 'Italian (Switzerland)', 'it': 'Italian (Italy)', 'it-it': 'Italian (Italy)', 'ja': 'Japanese', 'kn': 'Kannada', 'kk': 'Kazakh', 'kok': 'Konkani', 'ko': 'Korean', 'kz': 'Kyrgyz', 'lv': 'Latvian', 'lt': 'Lithuanian', 'ms': 'Malay', 'ml': 'Malayalam', 'mt': 'Maltese', 'mr': 'Marathi', 'mn': 'Mongolian (Cyrillic)', 'ne': 'Nepali (India)', 'nb-no': 'Norwegian (Bokmal)', 'nn-no': 'Norwegian (Nynorsk)', 'no': 'Norwegian (Bokmal)', 'or': 'Oriya', 'pl': 'Polish', 'pt-br': 'Portuguese (Brazil)', 'pt': 'Portuguese (Portugal)', 'pa': 'Punjabi', 'rm': 'Rhaeto-Romanic', 'ro-md': 'Romanian (Moldova)', 'ro': 'Romanian', 'ru-md': 'Russian (Moldova)', 'ru': 'Russian', 'sa': 'Sanskrit', 'sr': 'Serbian', 'sk': 'Slovak', 'ls': 'Slovenian', 'sb': 'Sorbian', 'es-ar': 'Spanish (Argentina)', 'es-bo': 'Spanish (Bolivia)', 'es-cl': 'Spanish (Chile)', 'es-co': 'Spanish (Colombia)', 'es-cr': 'Spanish (Costa Rica)', 'es-do': 'Spanish (Dominican Republic)', 'es-ec': 'Spanish (Ecuador)', 'es-sv': 'Spanish (El Salvador)', 'es-gt': 'Spanish (Guatemala)', 'es-hn': 'Spanish (Honduras)', 'es-mx': 'Spanish (Mexico)', 'es-ni': 'Spanish (Nicaragua)', 'es-pa': 'Spanish (Panama)', 'es-py': 'Spanish (Paraguay)', 'es-pe': 'Spanish (Peru)', 'es-pr': 'Spanish (Puerto Rico)', 'es-us': 'Spanish (United States)', 'es-uy': 'Spanish (Uruguay)', 'es-ve': 'Spanish (Venezuela)', 'es': 'Spanish (Traditional Sort)', 'es-es': 'Spanish (Traditional Sort)', 'sx': 'Sutu', 'sw': 'Swahili', 'sv-fi': 'Swedish (Finland)', 'sv': 'Swedish', 'syr': 'Syriac', 'ta': 'Tamil', 'tt': 'Tatar', 'te': 'Telugu', 'th': 'Thai', 'ts': 'Tsonga', 'tn': 'Tswana', 'tr': 'Turkish', 'uk': 'Ukrainian', 'ur': 'Urdu', 'uz': 'Uzbek', 'vi': 'Vietnamese', 'xh': 'Xhosa', 'yi': 'Yiddish', 'zu': 'Zulu' }; this.deviceUAFilter = /[ _\\#\-,\\.\/:"']/g; this.extraUAFilter = /[ ]/g; } /** * Error handling helper. Sets a message and an error code. * * @param status error code * @param msg message content * @return true if no error, or false otherwise. **/ setError(status, msg) { this.error = msg; this.reply.status = status; this.reply.nessage = msg; return status === 0; } /** * String cleanse for extras matching. * * @param string str * @return string Cleansed string **/ extraCleanStr(str) { str = str.replace(this.extraUAFilter, ''); str = str.toLowerCase().replace(/[^(\x20-\x7F)]*/g, ''); return str.trim(); } /** * Standard string cleanse for device matching * * @param string str * @return string cleansed string **/ cleanStr(str) { str = str.replace(this.deviceUAFilter, ''); str = str.toLowerCase().replace(/[^(\x20-\x7F)]*/g, ''); return str.trim(); } /** * Helper for determining if a header has BiKeys * * @param object header * @return platform name on success, false otherwise **/ hasBiKeys(headers) { let biKeys = this.detectionConfig['device-bi-order']; let dataKeys = Object.keys(headers).map(x => x.toLowerCase()); // Fast check if (dataKeys.includes('agent')) { return false; } if (dataKeys.includes('user-agent')) { return false; } for(let platform in biKeys) { let set = biKeys[platform]; for(let tuple of set) { let count = 0; let total = tuple.length; for(let item of tuple) { if (dataKeys.includes(item)) { count++; } if (count === total) { return platform; } } } } return false; } /** * The heart of the detection process * * @param string header The type of header we're matching against - user-agent type headers use a sieve matching, all others are hash matching. * @param string value The http header's sanitised value (could be a user-agent or some other x- header value) * @param string subtree The 0 or 1 for devices (isGeneric), category name for extras ('platform', 'browser', 'app') * @param string actualHeader Unused (optimized away) * @param string category : One of 'device', 'platform', 'browser' or 'app' * @return int node (which is an id) on success, false otherwise */ getMatch(header, value, subtree='0', actualHeader='', category='device') { actualHeader = ''; let f = 0; let r = 0; let treetag = header + subtree; // Fetch branch before validating params to confirm local files are installed correctly. let branch = this.getBranch(treetag); if (!branch || Object.keys(branch) === 0) { return false; } if (value.length < 4) { return false; } if (header === 'user-agent') { // Sieve matching strategy for(let [order, filters] of branch) { order; for(let [filter, matches] of filters) { ++f; if (typeof filter === 'string' && value.includes(filter)) { for(let [match, node] of matches) { ++r; if (typeof match === 'string' && value.includes(match)) { this.detectedRuleKey[category] = this.cleanStr(header) + ':' + this.cleanStr(filter) + ':' + this.cleanStr(match); return node; } } } } } } else { // Hash matching strategy for (let [key, node] of branch) { if (key === value) { return node; } } } return false; } /** * Find a branch for the matching process * * @param string branch The name of the branch to find * @return an assoc array on success, false otherwise. */ getBranch(branch) { return this.tree[branch]; } } module.exports = HDBase;
import React from "react"; import Banner from '../components/Banner'; import AboutUsHome from "../components/AboutUsHome"; import Testimonials from '../components/Testimonials'; const HomePage = () => { return( <> <Banner /> <AboutUsHome/> <Testimonials /> </> ) } export default HomePage
export const ARTIST = "spotify" export const objectCreator = value => ({ type: ARTIST, value })
import mongoose from 'mongoose'; const schema = new mongoose.Schema({ 'name': String, 'price': String, 'picture': String }); const Item = mongoose.model('item', schema); export function getListOfItems() { return Item.find(); }; export function saveItem(data) { if(!data._id) { delete data._id; return (new Item(data)).save(); } else { // update const id = data._id; delete data._id; return Item.findOneAndUpdate({_id: id}, {$set: data}, {upsert: true}).exec(); } }; export function deleteItem(id) { return Item.findByIdAndRemove({_id: id}).exec(); };
import React, {Component} from 'react'; import PropTypes from 'prop-types'; import svgLoader from '../img/svg-loader.svg'; import {Alert, Button, ButtonGroup, Col, Row} from 'reactstrap'; import {loadBig, loadHuge, loadSmall} from "../api/api"; class ToolsPanel extends Component { constructor(props) { super(props); this.state = { isLoading: false, errorMsg: '' }; this.handleClear = this.handleClear.bind(this); this.handleLoadBig = this.handleLoadBig.bind(this); this.handleLoadHuge = this.handleLoadHuge.bind(this); this.handleLoadSmall = this.handleLoadSmall.bind(this); this.handleNewData = this.handleNewData.bind(this); this.handleUILoad = this.handleUILoad.bind(this); this.handleLoadingIndicator = this.handleLoadingIndicator.bind(this); } handleLoadingIndicator() { this.setState((prevState) => { return { isLoading: !prevState.isLoading } }); } handleUILoad(msg) { this.setState({ errorMsg: msg }, () => this.handleLoadingIndicator()) } handleClear() { this.props.onLoad([]); this.setState({ errorMsg: '', isLoading: false }) } handleNewData(newData) { this.props.onLoad(newData); this.handleUILoad(''); } handleLoadBig() { this.handleUILoad(''); loadBig(this.handleNewData, this.handleUILoad); } handleLoadSmall() { this.handleUILoad(''); loadSmall(this.handleNewData, this.handleUILoad); } handleLoadHuge() { this.handleUILoad(''); loadHuge(this.handleNewData, this.handleUILoad); } render() { return ( <Alert color='secondary'> <Row style={{alignItems: 'center'}}> <Col md={{size: 5}} style={{alignItems: 'left'}}> <ButtonGroup> <Button disabled={this.state.isLoading} color='secondary' onClick={this.handleLoadHuge}> Load huge data </Button> <Button disabled={this.state.isLoading} color='secondary' onClick={this.handleLoadBig}> Load big data </Button> <Button disabled={this.state.isLoading} color='secondary' onClick={this.handleLoadSmall}> Load small data </Button> <Button disabled={this.state.isLoading} color='secondary' onClick={this.handleClear}> Clear </Button> </ButtonGroup> </Col> <Col md={{size: 2}} style={{alignItems: 'center'}}> {this.state.isLoading ? (<img src={svgLoader} alt='Loading...'/>) : (<div/>)} </Col> <Col> <div> <Alert color='danger' isOpen={this.state.errorMsg !== ''} style={{lineHeight: '50%', textAlign: 'centerLeft', marginBottom: 0}} > {this.state.errorMsg} </Alert> </div> </Col> </Row> </Alert> ); } } ToolsPanel.propTypes = { onLoad: PropTypes.func.isRequired }; export default ToolsPanel;