text
stringlengths
7
3.69M
const Router = require('express').Router; const userController = require('../controllers/userController')(); module.exports = Router({mergeParams: true}) .post("/company/user/", async (req, res ,next) => userController.addUser(req, res, next)) .get("/company/:id/users/", async (req, res, next) => userController.getUsers(req, res, next)) .put("/company/user/", async (req, res, next) => userController.editUser(req, res, next)) .delete("/company/user/", async (req, res, next) => userController.removeUser(req, res, next));
/** * Created by M. Yegorov on 2015-01-23. */ tinng.class.Router = function(){ tinng.funcs.bind(this); var that = this; this.params = {}; if (location.hash) { var pairs = location.hash.replace('#', '').split('&'); _(pairs).each(function(pair){ var keyval = pair.split('='); that.params[keyval[0]] = keyval[1] || true; }); } }; tinng.class.Router.prototype = { $push:function(){ var pairs = []; _(this.params).each(function(val, key){ pairs.push(key + '=' + val); }); location.hash = pairs.join('&'); }, // todo - make this func also accept a key-value object pairs note:function(key, val){ if (val === '' || val === null || typeof val == 'undefined'){ delete this.params[key]; } else { this.params[key] = val; } this.$push(); }, // to avoid undefined check get:function(key){ if (this.params[key]){ return this.params[key]; } else { return false; } } };
import React from "react"; import {Link} from 'react-router-dom' export const LeagueLayout = ({ id, title, image }) => { return ( <div className="row"> <div className="offset-lg-3 col-lg-6 mt-2 mb-2"> <div className="card"> <div className="card-header h3">{title}</div> <div className="card-body text-center"> <img src={image?image:"https://upload.wikimedia.org/wikipedia/commons/0/0a/No-image-available.png"} alt="" className="img-fluid mb-3" style={{maxHeight:200}} /> <br></br> <Link to={`leagues/${id}`} className="btn btn-outline-primary"> More Details </Link> </div> </div> </div> </div> ); };
var Faker = function(bar) { this._foo = bar; };
// Get the HTML Elements let carSelectBox = document.querySelector('#car-select'); let modelSelectBox = document.querySelector('#model-select'); let cars=[{id:1,name:'Maruthi Suzuki'}, {id:2,name:'Suzuki NEXA'}, {id:3,name:'Hyundai Motors'}]; let models=[{id: 1,car_id:1,name:'Swift'},{id:2,car_id:1,name:'DZire'}, {id: 3,car_id:1,name:'Brezza'},{id:4,car_id:1,name:'Waganor'}, {id: 5,car_id:2,name:'Baleno'},{id:6,car_id:2,name:'Ignis'}, {id: 7,car_id:2,name:'Ciaz'},{id:8,car_id:2,name:'SCross'}, {id: 9,car_id:3,name:'Grand i10'},{id:10,car_id:3,name:'i20 Sports'}, {id: 11,car_id:3,name:'Creta'},{id:12,car_id:3,name:'Verna'}]; // Populate Options let populateOptions = (selectBox,array,options) => { for(let elem of array){ options += `<option value="${elem.id}">${elem.name}</option>` } selectBox.innerHTML = options; }; // Populate Car Select with Options let carOptions = `<option>Select a Car</option>`; populateOptions(carSelectBox,cars,carOptions); // When a Car is Selected carSelectBox.addEventListener('change',function() { let selectedId = Number(carSelectBox.value); let selectedModels = models.filter((model) => { return model.car_id === selectedId; }); // populate Model Select with Options let modelOptions = `<option>Select a Model</option>`; populateOptions(modelSelectBox,selectedModels,modelOptions); });
import { createSlice } from '@reduxjs/toolkit'; const setStoreVariable = (key) => (state, action) => { state[key] = action.payload; }; const mainSlice = createSlice({ name: 'main', initialState: { tracks: null, loading: false, accessToken: null, audioProperties: { valence: 0.5, energy: 0.5, }, selectedGenres: [], playlistId: null, }, reducers: { setTracks: setStoreVariable('tracks'), setAccessToken: setStoreVariable('accessToken'), setLoading: setStoreVariable('loading'), setAudioProperties: setStoreVariable('audioProperties'), setSelectedGenres: setStoreVariable('selectedGenres'), setPlaylistId: setStoreVariable('playlistId'), }, }); export const { setTracks, setAccessToken, setLoading, setAudioProperties, setSelectedGenres, setPlaylistId, } = mainSlice.actions; export default mainSlice.reducer;
// Chess + Engine // Samein Dorazahi // 26/07/21 let pieces = []; let rows = 8; let cols = 8; let grid, cellWidth, cellHeight, backGrid, pnum, pnumr, my, mx, myr, mxr; function setup() { createCanvas(windowWidth, windowHeight); backGrid = createEmptyGrid(cols, rows); grid = createEmptyGrid(cols, rows); cellWidth = width / cols; cellHeight = height / rows; //add pawn to grid for (let y=0; y<rows; y++) { for (let x=0; x<cols; x++) { if (y === 6) { let pawns = new Piece(x, y, "pawn", "white", "blue"); pieces.push(pawns); } else if (y === 1) { let pawns = new Piece(x, y, "pawn", "black", "red"); pieces.push(pawns); } else { pieces.push(0); } } } } class Piece { constructor(x, y, type, side) { this.x = x; this.y = y; this.type = type; this.side = side; } display() { if (this.type === "pawn" && this.side === "black") { grid[this.y][this.x] = 9; } else if (this.type === "pawn" && this.side === "white") { grid[this.y][this.x] = 8; } } move() { pieces[pnumr] = pieces[pnum]; this.x = mxr; this.y = myr; if (pnumr !== pnum) { pieces[pnum] = 0; grid[my][mx] = 0; } } } function draw() { displayBackGrid(); displayGrid(); strokeWeight(13); noFill(); rect(mx * cellWidth, my * cellHeight, cellWidth, cellHeight); strokeWeight(1); for (let i=0; i<pieces.length; i++) { if (pieces[i] !== 0) { pieces[i].display(); } } } function mouseReleased() { mxr = Math.floor(mouseX / cellWidth); myr = Math.floor(mouseY / cellHeight); pnumr = myr*8 + mxr; console.log(myr, mxr, grid[myr][mxr], "pr", pnumr); pieces[pnum].move(); } function mousePressed() { mx = Math.floor(mouseX / cellWidth); my = Math.floor(mouseY / cellHeight); pnum = my*8 + mx; console.log(my, mx, grid[my][mx], "p", pnum); } function displayGrid() { for (let y=0; y<rows; y++) { for (let x=0; x<cols; x++) { if (grid[y][x] === 9) { fill("red"); rect(x*cellWidth, y*cellHeight, cellWidth, cellHeight); } else if (grid[y][x] === 8) { fill("blue"); rect(x*cellWidth, y*cellHeight, cellWidth, cellHeight); } else if (grid[y][x] === 37) { fill("gray"); rect(x*cellWidth, y*cellHeight, cellWidth, cellHeight); } } } } function displayBackGrid() { for (let y=0; y<rows; y++) { for (let x=0; x<cols; x++) { if (backGrid[y][x] === 0) { fill("white"); // image(grassImage, x * cellWidth, y * cellHeight, cellWidth, cellHeight); } else if (backGrid[y][x] === 1) { fill("black"); // image(wallImage, x * cellWidth, y * cellHeight, cellWidth, cellHeight); } rect(x*cellWidth, y*cellHeight, cellWidth, cellHeight); } } } function createEmptyGrid(cols, rows) { let empty = []; let turn = 1; for (let y=0; y<rows; y++) { empty.push([]); turn++; for (let x=0; x<cols; x++) { turn++; if (turn % 2 === 0) { empty[y].push(1); } else { empty[y].push(0); } } } return empty; }
angular.module('gApp.ic', [ 'ui.router' ]) .config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) { $stateProvider .state('ic', { url: '/ic', views:{ 'mainContainer':{ templateUrl: 'templates/ic/ic.html', controller: 'ic-mainCtrl' }, 'rightContainer':{ templateUrl: 'templates/ic/Imarset-c.html', controller: 'ic-rightCtrl' } } }) } ] );
import React, { Component } from 'react'; import { StyleSheet, css } from 'aphrodite'; import Button from '@material-ui/core/Button'; import { getHighScore } from '../config/SaveScore'; const styles = StyleSheet.create({ container: { display: 'flex', flex: 1, flexDirection: 'column', textAlign: 'center', justifyContent: 'center', alignItems: 'center', }, }); export default class About extends Component { render() { return ( <div className={css(styles.container)}> <h3>{`Score : ${this.props.score}`}</h3> <h3>{`High Score: ${getHighScore()}`}</h3> <h4>How To play?</h4> <div>Make words using letters</div> <div>Select letters by clicking and then click destroy button(leave it for 2 second it wil happen automatically), if it is a valid word then it will disappear</div> <Button href="https://www.youtube.com/watch?v=qvoL5J-jsFA&feature=youtu.be"> Here is game play video. </Button> <h4>Check out github repo here</h4> <a className="github-button" href="https://github.com/abhishekcode/word-tetris" data-size="large" data-show-count="true" aria-label="Star abhishekcode/word-tetris on GitHub">Github Repo</a> </div> ); } }
import React from 'react'; function Titolo({ text, size }) { return ( <h1 style={{ fontWeight: "bolder", fontSize: size || "2rem", fontFamily: "'Raleway', sans-serif" }} > { text } </h1> ) } export default Titolo;
//阻止时间传递 function stopPropagation(e){ if(e.stopPropagation){ e.stopPropagation(); }else{ e.cancelBuddle=true; } }
// mucko-ui test_waveform_control.js var mucko = require("mucko") var Test = mucko.Test var Base = mucko.Base function inbrowser_waveform(UI) { function getJSONFakeData(n) { return { "length": n, "bits": 8, "sample_rate": 48000, "samples_per_pixel": 512, "data": [ 0, 0, -10, 10, 0, 0, -5, 7, -5, 7, 0, 0, 0, 0, 0, 0, 0, 0, -2, 2 ] } } n = 10 data = getJSONFakeData(n) UI.WaveformControl.Waveform("svg#waveform1", data) data.data = [0, 0, 8, 8, -5, 7, 0, 0, 0, 0, 0, 0, 0, 0, -2, 2, 0, 0, 0, 0, 0, 0, 0, 0] UI.WaveformControl.Waveform("svg#waveform2", data) } Test.test_waveform = function () { if (Base.Sys.isbrowser()) { // inbrowser_waveform(UI) } else { UI = require("../index.js") assert_true(Base.Meta.isa(UI.WaveformControl, Object)) } } if (Base.Sys.isbrowser()) { UI = require("mucko-ui") //code = Base.Meta.body(inbrowser_waveform) //eval(code) inbrowser_waveform(UI) }
import Vue from 'vue' import Router from 'vue-router' import msite from '@/pages/msite/msite' import login from '@/pages/login/login' import order from '@/pages/order/order' import shopStroe from '@/pages/shop/shop' import foodType from '@/pages/foodType/foodType' import shopDetail from '@/pages/shopDetail/shopDetail' import search from '@/pages/search/search'; import user from '@/pages/user/user'; import coupon from '@/pages/coupon/coupon' import balance from '@/pages/balance/balance' import point from '@/pages/point/point' import userInfo from '@/pages/userInfo/userInfo' import address from '@/pages/userInfo/children/address' import editName from '@/pages/userInfo/children/editName' import addAddress from '@/pages/userInfo/children/children/addAddress' import searchAddress from '@/pages/userInfo/children/children/searchAddress' Vue.use(Router); export default new Router({ routes: [ { path: '/', name: 'msite', component: msite }, { path:'/login', name:login, component:login }, { path:'/shopStroe', name:shopStroe, component:shopStroe, }, { path:'/order', name:order, component:order }, { path:'/shopDetail', name:shopDetail, component:shopDetail }, { path:'/foodType', name:foodType, component:foodType }, { path:'/search', name:search, component:search }, { path:'/user', name:user, component:user }, { path:'/coupon', name:coupon, component:coupon }, { path:'/balance', name:balance, component:balance }, { path:'/point', name:point, component:point }, { path:'/userInfo', name:userInfo, component:userInfo, children:[ { path:'editName', name:editName, component:editName }, { path:'address', name:address, component:address, children: [ { path:'addAddress', name:addAddress, component:addAddress, children:[ { path:'searchAddress', name:searchAddress, component:searchAddress } ] } ] } ] } ] })
function VehicleConstructor(name, wheelNumber, passNumber){ // private variables var name = name; var wheelNumber = wheelNumber; var passNumber = passNumber; var vehicle = {}; // public properties vehicle._name = name; vehicle._wheelNumber = wheelNumber; vehicle.passNumber = passNumber; // public methods /*none*/ //private methods : vehicle.makeNoise = function makeNoise(){ console.log('(*loud vehicle noise*)'); } return vehicle; } var Bike = VehicleConstructor("Bike", 2, 1); Bike.makeNoise() Bike.makeNoise = function(){ console.log('ring ring!'); } Bike.makeNoise(); var Sedan = VehicleConstructor("Sedan", 4, 3); Sedan.makeNoise(); Sedan.makeNoise = function(){ console.log('Honk Honk!'); } Sedan.makeNoise(); var Bus = VehicleConstructor("Bus", 8, 9); Bus.pickUpPassengers = function(passPicked){ this.passNumber += passPicked; } console.log(Bus.passNumber); Bus.pickUpPassengers(5); console.log('Bus picked up 5 passangers'); console.log(Bus.passNumber);
var interface_c1_connector_get_service_session_options = [ [ "isActivity", "interface_c1_connector_get_service_session_options.html#afcf55fb3c432c60db1643332bee9560f", null ] ];
ItemList = React.createClass({ mixins: [ReactMeteorData, React.addons.LinkedStateMixin], getInitialState: function () { return { }; }, getMeteorData() { return { items: this.props.module.collection.find({}, {sort: {createdAt: -1}}).fetch() }; }, newItem() { if (this.props.module.itemFactory) { this.props.module.itemFactory(); } else if (this.props.module.schemas) { Meteor.call('newItemFromSchema', this.props.module.name, function (error) { if (error) { throw(error); } }) } else { this.props.module.collection.insert({name: "New Item"}); } }, addItem(e) { if (this.props.module.schemas) { Meteor.call('newItemFromSchema', this.props.module.name, this.state.newItemName, function (error) { if (error) { throw(error.reason); } }) } else { let obj = { name: this.state.newItemName, createdAt: new Date(), } if (this.props.module.newItemTemplate) { _.extend(obj, this.props.module.newItemTemplate) console.log('obj extended: ' + obj); } this.props.module.collection.insert(obj); } }, deleteItem(e) { if (confirm("Are you sure?")) { console.log('delete: ' + e.target.value); this.props.module.collection.remove(e.target.value); } }, renderAddCustom() { const AddCustom = React.createClass({ newCustomItem() { console.log('AddCustom newCustomItem: '); this.props.module.collection.insert(JSON.parse(this.state.value)); }, edit(e) { console.log('AddCustom edit: '); this.setState({value: e.target.value}) }, render() { console.log('AddCustom render: '); return <div> New Doc: <textarea onChange={this.edit} defaultValue='{"name": "Untitled"}' /> <button onClick={this.newCustomItem}>Create</button> </div> } }) const MyModal = ModalWrapper(AddCustom); return <MyModal {...this.props} name='AddCustom' label='AddCustom'/> }, renderListItem(item) { //console.log('ListItemComp: ' + ListItemComp); if (this.props.module.schemas) { const s = this.props.module.schemas[0] const title = item[s][0].value return title ? title : "No title" } else { return item.name } }, render() { //render add box const addItem = <li className="list-group-item"> <div> <input type='text' valueLink={this.linkState('newItemName')} /> </div> <button onClick={this.addItem}>Add</button> </li> //render items const items = this.data.items.map(i => { console.log('ItemList render: ' + Object.keys(i)); return <li className="list-group-item"> <div> <a href={'/'+this.props.module.name+'/' + i._id + '/main'} className="tooltip" > {this.renderListItem(i)} </a> <div className="right grayedSmall">{i._id} <button value={i._id} onClick={this.deleteItem}>Delete</button> </div> </div> </li> }) return <div> {this.props.renderNav && Celestial.getNavItems(this.props.module.listRoute, this.props.module, null, null)} <h3>{this.data.items.length} {this.props.module.pluralName} found </h3> {this.renderAddCustom()} <ul className="list"> {addItem} {items} </ul> </div> } }); //<input type='button' onClick={this.newItem} // value={'Create new ' + this.props.module.singularName}/> //{this.renderAddCustom()}
import React, {Component} from 'react' export class Buscador extends Component{ render(){ return( <div className="buscador"> <input placeholder="Buscar un producto..." className="buscador-position"> </input> </div> ) } }
var mutt_2slist_8c = [ [ "slist_new", "mutt_2slist_8c.html#af779a2c5318dd880bb34fc2632fd0997", null ], [ "slist_add_list", "mutt_2slist_8c.html#a52e930a7c9662bda29b33e33b3768a1c", null ], [ "slist_add_string", "mutt_2slist_8c.html#a56a8eca5b8c63f928ae9944661a208bd", null ], [ "slist_compare", "mutt_2slist_8c.html#a63d0a7363816cc60c6af191b09039a55", null ], [ "slist_dup", "mutt_2slist_8c.html#a24ef1f205d23bbc703828e916f571a98", null ], [ "slist_empty", "mutt_2slist_8c.html#a4b5f2f52bfd6861100d9da4fa653044a", null ], [ "slist_free", "mutt_2slist_8c.html#ac97fc48f98ea9286a7e58db0289725e0", null ], [ "slist_is_member", "mutt_2slist_8c.html#a7c69d305defed93b70403c325461ef9b", null ], [ "slist_parse", "mutt_2slist_8c.html#a1b92bcbee7fe26d262459c9fcf109c9f", null ], [ "slist_remove_string", "mutt_2slist_8c.html#a8469647e63483c367daa8ce05b02de31", null ], [ "slist_to_buffer", "mutt_2slist_8c.html#a92e22106a8bd5410cc7efa26c892d863", null ] ];
var customShinyInputBinding = new Shiny.InputBinding(); $.extend(customShinyInputBinding, { // This initialize input element. It extracts data-value attribute and use that as value. initialize: function(el) { var val = $(el).attr('data-value'); $(el).val(val); }, // This returns a jQuery object with the DOM element. find: function(scope) { return $(scope).find('.shiny-custom-input'); }, // Returns the ID of the DOM element. getId: function(el) { return el.id; }, // Given the DOM element for the input, return the value as JSON. getValue: function(el) { var value = $(el).val(); var value_type = $(el).attr('data-value-type'); switch (value_type) { case 'JSON': return JSON.stringify(value); case 'text': return value; default: throw new Error("Unrecognized value type of custom shiny input: " + value_type); } }, // Given the DOM element for the input, set the value. setValue: function(el, value) { el.value = value; }, // Set up the event listeners so that interactions with the // input will result in data being sent to server. // callback is a function that queues data to be sent to // the server. subscribe: function(el, callback) { $(el).on('keyup change', function () { callback(true); }); }, // TODO: Remove the event listeners. unsubscribe: function(el) { }, // This returns a full description of the input's state. getState: function(el) { return { value: el.value }; }, // The input rate limiting policy. getRatePolicy: function() { return { // Can be 'debounce' or 'throttle': policy: 'debounce', delay: 500 }; }, receiveMessage: function(el, data) { if (data.hasOwnProperty('value')) this.setValue(el, data.value); if (data.hasOwnProperty('label')) { var input = $(el).closest(".ui"); if (data.label === "") { input.dropdown('remove selected') } else { input.dropdown('set selected', data.label) } } $(el).trigger('change'); } }); Shiny.inputBindings.register(customShinyInputBinding, 'shiny.customShinyInput');
self.__precacheManifest = [ { "revision": "42ac5946195a7306e2a5", "url": "/static/js/runtime~main.a8a9905a.js" }, { "revision": "5181a65923def710a6da", "url": "/static/js/main.cbb6456b.chunk.js" }, { "revision": "4b53cda33f940ebe9eaf", "url": "/static/js/2.8dcc74a1.chunk.js" }, { "revision": "5181a65923def710a6da", "url": "/static/css/main.4a164635.chunk.css" }, { "revision": "c1267c7bae2c6a2ea1a1a56e448265ed", "url": "/index.html" } ];
export default [ { title: "Home", text: "Home", icon: "fa-home" }, { title: "Signout", text: "Signout", icon: "fa-sign-out-alt" }, { title: "Productlist", text: "My Products", icon: "fa-cart-arrow-down" }, { title: "Search", text: "Search", icon: "fa-search" } ];
$(function(){ var banner=$("#banner"); var pic=$(".banner-Pic");//背景图 var imgs=$(".banner-pic");//banner图 var bannerBox=$(".banner-box")[0]; var list=$(".list"); var bannerLeft=$(".bannerleft")[0]; var bannerRight=$(".bannerright")[0]; var n=0; var t=setInterval(move,2000); function move(){ n++; if(n>=imgs.length){ n=0; } for(var i=0;i<imgs.length;i++){ animate(imgs[i],{opacity:0},2000) animate(pic[i],{opacity:0},2000) list[i].style.background='#3E3E3E' } animate(imgs[n],{opacity:1},2000) animate(pic[n],{opacity:1},2000) list[n].style.background='#B61B1F' } bannerBox.onmouseover=function(){ clearInterval(t); bannerRight.style.display='block'; bannerLeft.style.display='block'; } bannerBox.onmouseout=function(){ t=setInterval(move,2000); bannerRight.style.display='none'; bannerLeft.style.display='none'; } bannerRight.onclick=function(){ move(); } bannerLeft.onclick=function(){ n--; if(n<=0){ n=imgs.length-1; } for(var i=0;i<imgs.length;i++){ animate(imgs[i],{opacity:0},2000) animate(pic[i],{opacity:0},2000) list[i].style.background='#3E3E3E' } animate(imgs[n],{opacity:1},2000) animate(pic[n],{opacity:1},2000) list[n].style.background='#3E3E3E' } for(var i=0;i<list.length;i++){ list[i].index=i; list[i].onmouseover=function(){ if(this.index>n){ n++; if(n>=imgs.length){ n=0; } for(var i=0;i<imgs.length;i++){ animate(imgs[i],{opacity:0},2000); animate(pic[i],{opacity:0},2000); list[i].style.background='#3E3E3E'; } animate(imgs[this.index],{opacity:1},2000); animate(pic[this.index],{opacity:1},2000); list[this.index].style.background='#B61B1F'; n=this.index; }else if(this.index<n){ n--; if(n<=0){ n=imgs.length-1; } for(var i=0;i<imgs.length;i++){ animate(imgs[i],{opacity:0},2000); list[i].style.background='#3E3E3E'; } animate(imgs[this.index],{opacity:1},2000); list[this.index].style.background='#B61B1F'; n=this.index; } } } //banner下拉框 var menu=$(".menu"); for(var i=0;i<menu.length;i++){ hover(menu[i],function(){ var bannerhidden=$(".banner-hidden",this)[0]; this.style.background="#E5004F"; bannerhidden.style.display="block"; },function(){ var that=this; var bannerhidden=$(".banner-hidden",this)[0]; that.style.background="#333333"; bannerhidden.style.display="none"; }) } function dalunbo(now,n){ var now=now; var zuo=$('.draw-left')[now]; var you=$('.draw-right')[now]; var smallcircle=$('.circle')[now]; var firstcircle=getClass('cir',smallcircle); var bigbox=$('.drawing')[n]; var picture=getClass('draw-pic',bigbox); // console.log(picture); var nub=0; var nub1=0; you.onclick=function(){ nub1=nub+1; if(nub1>=picture.length){ nub1=0; } picture[nub1].style.left=388+"px"; animate(picture[nub],{left:-388},500) animate(picture[nub1],{left:0},500) firstcircle[nub].style.background="#ccc"; firstcircle[nub1].style.background="#E4145A"; nub=nub1; } zuo.onclick=function(){ nub1=nub-1; if(nub1<0){ nub1=picture.length-1; } picture[nub1].style.left=-388+"px"; animate(picture[nub],{left:388},500) animate(picture[nub1],{left:0},500) firstcircle[nub].style.background="#ccc"; firstcircle[nub1].style.background="#E4145A"; nub=nub1; } bigbox.onmouseover=function(){ zuo.style.display="block" you.style.display="block" } bigbox.onmouseout=function(){ zuo.style.display="none" you.style.display="none" } zuo.onmouseover=function(){ zuo.style.background="#E4145A" } zuo.onmouseout=function(){ zuo.style.background="rgba(0,0,0,0.5)" } you.onmouseover=function(){ you.style.background="#E4145A" } you.onmouseout=function(){ you.style.background="rgba(0,0,0,0.5)" } } dalunbo(0,0); dalunbo(1,3); dalunbo(2,4); dalunbo(3,5); dalunbo(4,6); //top下拉 var sy=$(".sy wx")[0]; hover(sy,function(){ var down=$(".down",this)[0]; down.style.display='block'; this.style.width="124px"; this.style.background="#fff"; },function(){ var that=this; var down=$(".down",this)[0]; down.style.display='none'; that.style.width="77px"; that.style.background=""; }) var indent=$(".indent YT")[0]; hover(indent,function(){ var select=$(".select",this)[0]; select.style.display="block"; this.style.background="#fff"; },function(){ var select=$(".select")[0]; select.style.display="none"; this.style.background=""; }) //wx下拉 var sy1=$(".sy sjyt")[0]; hover(sy1,function(){ var down1=$(".down1",this)[0]; down1.style.display='block'; this.style.width="148px"; this.style.background="#fff"; },function(){ var that=this; var down1=$(".down1",this)[0]; down1.style.display='none'; that.style.width="100px"; that.style.background=""; }) //选项卡 var hot=$(".HOT"); var remen=$(".remen"); var sanjiao4=$(".sanjiao4"); for(var a=0;a<hot.length;a++){ hot[a].index=a; hot[a].onmouseover=function(){ for(var b=0;b<remen.length;b++){ hot[b].style.borderBottom="3px solid #000"; remen[b].style.display="none"; sanjiao4[b].style.display="none"; } hot[this.index].style.borderBottom="3px solid #E70050"; remen[this.index].style.display='block'; sanjiao4[this.index].style.display="block"; } } //超值特卖选项卡 function select(){ var obj=obj; var cz=$(".CZ",obj); var cztm=$(".CZTM",obj); var sanjiao=$(".sanjiao",obj); for(var d=0;d<cz.length;d++){ cz[d].index=d; cz[d].onmouseover=function(){ // alert(1) for(var e=0;e<cztm.length;e++){ cz[e].style.borderBottom='5px solid #333333'; cztm[e].style.display="none"; sanjiao[e].style.display="none"; } cz[this.index].style.borderBottom='5px solid #E5004F'; cztm[this.index].style.display="block"; sanjiao[this.index].style.display="block"; } } } select($("#merchandise")) //小轮播 function xiaolunbo(obj){ var categorybot=$(".category-bot",obj)[0] var scroller=$(".scroller",obj); var boultleft=$(".boult",obj)[0]; var boultright=$(".boult-right",obj)[0]; var bot_box=$(".xiaolunbo",obj)[0]; var width=parseInt(getStyle(bot_box,"width")); var N=0; var NEXT=0; boultright.onclick=function(){ NEXT=N+1; if(NEXT>scroller.length-1){ NEXT=0 } scroller[NEXT].style.left=width+"px"; animate(scroller[N],{left:-width},1000); animate(scroller[NEXT],{left:0},1000); N=NEXT; } boultleft.onclick=function(){ NEXT=N-1; if(NEXT<0){ NEXT=scroller.length-1 } scroller[NEXT].style.left=-width+"px"; animate(scroller[N],{left:width},1000); animate(scroller[NEXT],{left:0},1000); N=NEXT; } } xiaolunbo($(".fashion-box-bot")[0]) xiaolunbo($(".fashion-box-bot")[1]) xiaolunbo($(".fashion-box-bot")[2]) xiaolunbo($(".fashion-box-bot")[3]) xiaolunbo($(".fashion-box-bot")[4]) xiaolunbo($(".fashion-box-bot")[5]) xiaolunbo($(".fashion-box-bot")[6]) xiaolunbo($(".fashion-box-bot")[7]) xiaolunbo($(".fashion-box-bot")[8]) xiaolunbo($(".fashion-box-bot")[9]) // 超值特卖的边框 function border(bb){ var bb=bb; var nav=$(".nav",bb); var top=$(".border-top",bb); var bottom=$(".border-bottom",bb); var left=$(".border-left",bb); var right=$(".border-right",bb); for(var i=0;i<nav.length;i++){ nav[i].index=i; nav[i].onmouseover=function(){ animate(top[this.index],{width:218},500); animate(left[this.index],{height:258},500); animate(right[this.index],{height:258},500); animate(bottom[this.index],{width:218},500); } nav[i].onmouseout=function(){ animate(top[this.index],{width:0},500); animate(left[this.index],{height:0},500); animate(right[this.index],{height:0},500); animate(bottom[this.index],{width:0},500); } } } border($(".CZTM")[0]); border($(".CZTM")[1]); // 本周推荐的边框 function BORDER(){ var aa=aa; var tj=$(".tj",aa); var Top=$(".borderTop",aa); var Left=$(".borderLeft",aa); var Right=$(".borderRight",aa); var Bottom=$(".borderBottom",aa); for(var i=0;i<tj.length;i++){ tj[i].index=i; tj[i].onmouseover=function(){ animate(Top[this.index],{width:196},500); animate(Left[this.index],{height:248},500); animate(Bottom[this.index],{width:196},500); animate(Right[this.index],{height:248},500); } tj[i].onmouseout=function(){ animate(Top[this.index],{width:0},500); animate(Left[this.index],{height:0},500); animate(Bottom[this.index],{width:0},500); animate(Right[this.index],{height:0},500); } } } BORDER($(".remen-box")[0]) var floor_nav=$('.floorNav')[0]; var floor=$('.floor'); var floor_lis=$('.floor_lis');//返回属性 var back=$('.back')[0]; //获取属性‘返回’ var Cheight=document.documentElement.clientHeight; var Cwidth=document.documentElement.clientWidth; var nownode; var floor_flag=true; var floor_flag1=true; for(var i=0;i<floor.length;i++){ //获取每一楼层距离浏览器的高度 floor[i].h=floor[i].offsetTop; } window.onscroll=function(){ var obj=document.body.scrollTop?document.body:document.documentElement; var top=obj.scrollTop; //取滚动条的高度 if(top>=floor[0].h-500){ floor_nav.style.display='block'; back.style.display='block'; // animate(top_hidden,{height:60},100); var nHeight=floor_nav.offsetHeight; floor_nav.style.top=(Cheight-nHeight)/2+'px'; // if(floor_flag){ floor_flag=false; }floor_flag=true; } if(top<floor[0].h-500){ floor_nav.style.display='none'; back.style.display='none'; if(floor_flag1){ floor_flag1=false; }floor_flag1=true; } for(var i=0;i<floor.length;i++){ if(top>=floor[i].h-200){ for(var j=0;j<floor_lis.length;j++){ floor_lis[j].style.background=''; floor_lis[j].style.lineHeight=999+'px'; } floor_lis[i].style.background='#F6004F' floor_lis[i].style.lineHeight=20+"px"; nownode=i; } } } for(var i=0;i<floor_lis.length;i++){ floor_lis[i].index=i; floor_lis[i].onclick=function(){ animate(document.body,{scrollTop:floor[this.index].h}); animate(document.documentElement,{scrollTop:floor[this.index].h}); } floor_lis[i].onmouseover=function(){ this.style.background='#F6004F'; this.style.lineHeight=20+'px'; } floor_lis[i].onmouseout=function(){ if(nownode==this.index){ return; } this.style.background=''; this.style.lineHeight=999+'px'; } } back.onclick=function(){ animate(document.body,{scrollTop:0}) } animate(document.documentElement,{scrollTop:0}) function Border(obj){ var jy=obj; hover(jy,function(){ var ah=jy.offsetHeight-2; var aw=jy.offsetWidth-2; var bl=$('.border-left1',this)[0] var br=$('.border-right1',this)[0] var bt=$('.border-top1',this)[0] var bb=$('.border-bottom1',this)[0] animate(bt,{width:aw},500,function(){ this.style.width=aw; }) animate(bb,{width:aw},500,function(){ this.style.width=aw; }) animate(bl,{height:ah},500,function(){ this.style.height=ah; }) animate(br,{height:ah},500,function(){ this.style.height=ah; }) //边框出现 },function(){ var bl=$('.border-left1',this)[0] var br=$('.border-right1',this)[0] var bt=$('.border-top1',this)[0] var bb=$('.border-bottom1',this)[0] that=this; animate(bt,{width:0},500,function(){ this.style.width=0; }) animate(bb,{width:0},500,function(){ this.style.width=0; }) animate(bl,{height:0},500,function(){ this.style.height=0; }) animate(br,{height:0},500,function(){ this.style.height=0; }) //边框消失 }) } for(var g=0;g<36;g++){ Border($('.jy')[g]); } //鼠标悬停效果 // function weChat(){ // var wechat=$('.sy wx')[0] // var a=$('a',wechat)[0] // var div=$('.down',a)[0] // var img=$('img',div)[0] // // var span=$('span',a)[0] // var bot=$('.bot',a)[0] // hover(wechat,function(){ // a.style.width=89+'px' // div.style.display='block' // span.style.display='block' // bot.style.transform='rotate(360deg)' // },function(){ // a.style.width=52+'px' // div.style.display='none' // span.style.display='none' // bot.style.transform='rotate(0deg)' // }) // } // weChat() })
//HEADER SECTION - again abandoning const express = require('express'); var cors = require('express-cors'); const MongoClient = require('mongodb').MongoClient; var mongoose = require('mongoose'); var Schema = mongoose.Schema, ObjectId = Schema.ObjectId; // Connection URL var url = 'mongodb://127.0.0.1:27017/stockSloth'; mongoose.connect(url); const router = express.Router(); //HEADER SECTION router.get('/users', (req, res) => { MongoClient.connect(url, function(err, db) { db.collection('users', function(err, collection) { collection.find().toArray(function(err, results) { res.json(results); }) }); }); }); var userSchema = new Schema({ id: { type: String }, name: { type: String } }); router.get('/user/:id', (req, res) => { var id = req.params.id; var userModel = mongoose.model('user', userSchema); console.log(id); userModel.findOne({ '_id': id }, {}, function (err, user) { if (err) return handleError(err); console.log(user) // Space Ghost is a talk show host. res.json(user); }); });
import React, { Component } from 'react' import { connect } from 'react-redux' import styles from './ChannelList.scss' import { listChannels, joinChannel } from '../../redux/actions/channels' @connect( state => ({ channels: state.channels }), dispatch => ({ listChannels: () => dispatch(listChannels()), joinChannel: (channelId) => dispatch(joinChannel(channelId)) }) ) export default class ChannelList extends Component { componentWillMount() { this.props.listChannels() } onJoinChannel(channelId) { this.props.joinChannel(channelId) } render() { const content = this.props.channels !== undefined && this.props.channels.list !== undefined ? <ul> { Object.keys(this.props.channels.list).map( (channelId) => <li key={channelId} onClick={this.onJoinChannel.bind(this, channelId)}>{this.props.channels.list[channelId].name} ({this.props.channels.list[channelId].member_count})</li> )} </ul> : <p>Lade Channels</p> return ( <div className={styles.container}> <div className={styles.list}> {content} </div> </div> ) } }
let weather; let a = 0.0; let s = 0.0; let a2 = 0.0; let s2 = 0.0; let osc; const proxy = ""; let sound; let url = "https://cors-anywhere.herokuapp.com/http://api.openweathermap.org/data/2.5/weather?q=Stockholm&units=metric&appid=b48c7729bd6c5816e8c6fb60c20264a6"; function setup() { createCanvas(windowWidth, windowHeight); loadJSON(url, gotData); noStroke(); fill(255, 204, 0); noFill(); stroke(255, 204, 0); background(0); sound = loadSound("assets/rain.mp3"); } function gotData(data) { weather = data; console.log(weather); } function draw() { background("rgba(0,0,0,0.01)"); a = a + 0.01; s = cos(a) * 3; a2 = a2 + 0.02; s2 = sin(a2) * 2; if (weather) { var temp = weather.main.temp * 30; var humidity = weather.main.humidity * 2; title = weather.name; tempTitle = weather.main.temp + " °C"; feelsLikeTitle = "Feels like: " + weather.main.feels_like + " °C"; feelsLike = weather.main.feels_like * 20; humidityTitle = weather.main.humidity + "%"; descriptionTitle = weather.weather[0].main; // console.log(typeof descriptionTitle); // Title push(); stroke(255, 0, 204); textSize(64); text(title, 400, 200); pop(); // Temp Title push(); textSize(32); stroke(0, 204, 250); text(tempTitle, 400, 250); pop(); // Feels Like Title push(); textSize(32); stroke(200, 04, 250); text(feelsLikeTitle, 400, 300); pop(); //Humidity Title textSize(32); push(); stroke(255, 204, 0); text(humidityTitle, 400, 350); pop(); //Description Title textSize(32); push(); stroke(250, 100, 100); text(descriptionTitle, 400, 400); pop(); translate(width / 2, height / 2); push(); scale(s); // Temp ellipse push(); stroke(0, 204, 250); ellipse(100, 0, temp, temp); pop(); pop(); scale(s2); // Feels like ellipse push(); stroke(200, 04, 250); ellipse(100, 100, feelsLike, feelsLike); pop(); // Humidity ellipse push(); stroke(255, 204, 0); ellipse(200, 0, humidity, humidity); pop(); } } function mousePressed() { if (sound.isPlaying() == false) { sound.play(); } else if (sound.isPlaying() == true) { sound.stop(); } } function keyPressed() { if (noLoop() == false) { noLoop(); } else if (noLoop() == true) { reset(); } }
/* * Copyright (C) 2021 Radix IoT LLC. All rights reserved. */ SystemPermissionFactory.$inject = ['$http', 'maRqlBuilder']; function SystemPermissionFactory($http, maRqlBuilder) { const permissionsUrl = '/rest/latest/system-permissions'; class SystemPermission { constructor(options) { Object.assign(this, options); } static query(queryObject) { const params = {}; if (queryObject) { const rqlQuery = queryObject.toString(); if (rqlQuery) { params.rqlQuery = rqlQuery; } } return $http({ url: permissionsUrl, method: 'GET', params: params }).then(response => { const items = response.data.items.map(item => { return new this(item); }); items.$total = response.data.total; return items; }); } static buildQuery() { const builder = new maRqlBuilder(); builder.queryFunction = (queryObj) => { return this.query(queryObj); }; return builder; } get() { return $http({ method: 'GET', url: permissionsUrl + '/' + encodeURIComponent(this.name), }).then((response) => { Object.assign(this, response.data); return this; }); } save() { return $http({ method: 'PUT', url: permissionsUrl + '/' + encodeURIComponent(this.name), data: this }).then((response) => { Object.assign(this, response.data); return this; }); } } return SystemPermission; } export default SystemPermissionFactory;
import React, { PropTypes, Component } from 'react'; import styles from './ScheduleList.module.scss'; import cssModules from 'react-css-modules'; import { ScheduleTable } from 'components'; const parseOfflineData = (data) => ({ departureTime: data.aimed_departure_time, arrivalTime: data.aimed_arrival_time, duration: data.duration || '0:00' }); const parseOnlineData = (data) => ({ departureTime: data.departure_time, arrivalTime: data.arrival_time, duration: data.duration }); class ScheduleList extends Component { constructor(props) { super(props); this.parseItems = this.parseItems.bind(this); } parseItems() { const { isOffline, items } = this.props; /* eslint-disable no-confusing-arrow */ return items.map((item) => isOffline ? parseOfflineData(item) : parseOnlineData(item) ); /* eslint-enable no-confusing-arrow */ } render() { return ( <div className={styles.container}> <ScheduleTable {...this.props} items={this.parseItems()} /> </div> ); } } ScheduleList.propTypes = { items: PropTypes.array, onSelection: PropTypes.func.isRequired, selectedItemIndex: PropTypes.number, isOffline: PropTypes.bool.isRequired }; export default cssModules(ScheduleList, styles);
// Project an array of videos into an array of {id,title} pairs using forEach() var newReleasesMov = [ { "id": 1, "title": "Hard", "boxart": "Hard.jpg", "uri": "http://vikask/movies/1", "rating": [4.0], "bookmark": [] }, { "id": 2, "title": "Bad", "boxart": "Bad.jpg", "uri": "http://vikask/movies/2", "rating": [5.0], "bookmark": [{ id: 1, time: 2 }] }, { "id": 3, "title": "Cham", "boxart": "Cham.jpg", "uri": "http://vikask/movies/3", "rating": [4.0], "bookmark": [] }, { "id": 4, "title": "Fra", "boxart": "Fra.jpg", "uri": "http://vikask/movies/4", "rating": [5.0], "bookmark": [{ id: 4, time: 6 }] } ] newReleasesMov1.map(video => { console.log({ id: video.id, title: video.title, boxart: video.boxart, uri: video.uri }); });
(function($){ $.whenAll = function(deferreds){ var defs = deferreds.map(function(def) { var deferred = $.Deferred(); $.when(def).always(deferred.resolve); return deferred; }); return $.when.apply($, defs); }; })(jQuery);
import React,{ Component } from 'react'; import { makeStyles, withStyles } from "@material-ui/core/styles"; import TextField from '@material-ui/core/TextField'; import PropTypes from 'prop-types'; import Grid from '@material-ui/core/Grid'; import Fab from '@material-ui/core/Fab'; import AddIcon from '@material-ui/icons/Add'; import NavigationIcon from '@material-ui/icons/Navigation'; import FormLabel from '@material-ui/core/FormLabel'; import FormControl from '@material-ui/core/FormControl'; import FormGroup from '@material-ui/core/FormGroup'; import FormControlLabel from '@material-ui/core/FormControlLabel'; import FormHelperText from '@material-ui/core/FormHelperText'; import Checkbox from '@material-ui/core/Checkbox'; import Table from '@material-ui/core/Table'; import TableBody from '@material-ui/core/TableBody'; import TableCell from '@material-ui/core/TableCell'; import TableHead from '@material-ui/core/TableHead'; import TableRow from '@material-ui/core/TableRow'; import Web3 from 'web3'; //Factory Contract Address Ropsten Factory = 0xd770fa5b25ce0c48ccfbd925b753322c1f69bcb3 // var contractFactoryAddress = '0x42ae2b89472aa0c5085eaaf6a3efdb261a33e68e'; var contractFactoryAddress = '0x021012d534b0fF59E524339245C19f0a7eB0D7CE'; const rows = [ createData('Simply', '0x0D31C381c84d94292C07ec03D6FeE0c1bD6e15c1', 'afc6b2cf33f04bd3a355839e23335b34'), createData('Honeycomb', '0x4a3fbbb385b5efeb4bc84a25aaadcd644bd09721', '9e4ac334bca643389460f47076f43a8b'), createData('Chainlink', '0xc99B3D447826532722E41bc36e644ba3479E4365', '3cff0a3524694ff8834bda9cf9c779a1'), createData('LinkPool', '0x83f00b902cbf06e316c95f51cbeed9d2572a349a', 'c179a8180e034cf5a341488406c32827'), ]; const withErrorHandling = WrappedComponent => ({ showError, children }) => { return ( <WrappedComponent> {showError && <div className="error-message">Oops! Something went wrong! Install MetaMask or try again.</div>} {children} </WrappedComponent> ); }; //var web3 = new Web3(); //const web3 = new Web3(window.web3.currentProvider); //Use provider from MetaMask var web3; const DivWithErrorHandling = withErrorHandling(({children}) => <div>{children}</div>) const abiHoneyDex = [ { "constant": false, "inputs": [ { "name": "_buyerEthAddress", "type": "address" }, { "name": "_amountTarget", "type": "uint256" }, { "name": "_sellerTargetCryptoAddress", "type": "string" }, { "name": "_buyerTargetCryptoAddress", "type": "string" }, { "name": "_jobIds", "type": "string[]" }, { "name": "_oracles", "type": "address[]" } ], "name": "createAgreement", "outputs": [], "payable": true, "stateMutability": "payable", "type": "function" }, { "anonymous": false, "inputs": [ { "indexed": false, "name": "AgreementAddress", "type": "address" } ], "name": "contractDeployed", "type": "event" }, { "constant": true, "inputs": [ { "name": "", "type": "address" }, { "name": "", "type": "uint256" } ], "name": "AgreementAddressesBuyer", "outputs": [ { "name": "", "type": "address" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [ { "name": "", "type": "address" }, { "name": "", "type": "uint256" } ], "name": "AgreementAddressesSeller", "outputs": [ { "name": "", "type": "address" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [], "name": "getAgreementAddressesBuyer", "outputs": [ { "name": "", "type": "address[]" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [], "name": "getAgreementAddressesSeller", "outputs": [ { "name": "", "type": "address[]" } ], "payable": false, "stateMutability": "view", "type": "function" } ] const abiAgreement = [ { "constant": true, "inputs": [], "name": "falseCount", "outputs": [ { "name": "", "type": "uint8" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [], "name": "getChainlinkToken", "outputs": [ { "name": "", "type": "address" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [], "name": "trueCount", "outputs": [ { "name": "", "type": "uint8" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": false, "inputs": [ { "name": "_requestId", "type": "bytes32" }, { "name": "coinPrice", "type": "uint256" } ], "name": "fullfillCoinPrice", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": true, "inputs": [], "name": "returnNewID", "outputs": [ { "name": "", "type": "uint256" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [ { "name": "", "type": "uint256" } ], "name": "jobIds", "outputs": [ { "name": "", "type": "string" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [], "name": "marketPrice", "outputs": [ { "name": "", "type": "uint256" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [], "name": "getjobIds", "outputs": [ { "name": "", "type": "string[]" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [], "name": "getLinkBalance", "outputs": [ { "name": "", "type": "uint256" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [ { "name": "", "type": "uint256" } ], "name": "oracles", "outputs": [ { "name": "", "type": "address" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": false, "inputs": [ { "name": "coinnumber", "type": "string" } ], "name": "requetMarketPrice", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": true, "inputs": [], "name": "sellerEthAddress", "outputs": [ { "name": "", "type": "address" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [], "name": "returnedtxid", "outputs": [ { "name": "", "type": "uint256" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [], "name": "sellerTargetCryptoAddress", "outputs": [ { "name": "", "type": "string" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [], "name": "amountTarget", "outputs": [ { "name": "", "type": "uint256" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": false, "inputs": [], "name": "withdrawLink", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": true, "inputs": [], "name": "released", "outputs": [ { "name": "", "type": "bool" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [], "name": "getoracles", "outputs": [ { "name": "", "type": "address[]" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [], "name": "amountEth", "outputs": [ { "name": "", "type": "uint256" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [ { "name": "", "type": "address" } ], "name": "linkbalances", "outputs": [ { "name": "", "type": "uint256" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [], "name": "buyerEthAddress", "outputs": [ { "name": "", "type": "address" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": false, "inputs": [], "name": "withdrawETH", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": true, "inputs": [], "name": "buyerTargetCryptoAddress", "outputs": [ { "name": "", "type": "string" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": false, "inputs": [ { "name": "_requestId", "type": "bytes32" }, { "name": "txid", "type": "uint256" } ], "name": "fulfillNodeRequest", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": true, "inputs": [], "name": "apiAddress", "outputs": [ { "name": "", "type": "string" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [], "name": "deploymentTime", "outputs": [ { "name": "", "type": "uint256" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": false, "inputs": [ { "name": "tx_hash", "type": "string" } ], "name": "requestConfirmations", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "_amount", "type": "uint256" } ], "name": "depositLink", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "inputs": [ { "name": "_sellerEthAddress", "type": "address" }, { "name": "_buyerEthAddress", "type": "address" }, { "name": "_amountEth", "type": "uint256" }, { "name": "_amountTarget", "type": "uint256" }, { "name": "_sellerTargetCryptoAddress", "type": "string" }, { "name": "_buyerTargetCryptoAddress", "type": "string" }, { "name": "_jobIds", "type": "string[]" }, { "name": "_oracles", "type": "address[]" } ], "payable": true, "stateMutability": "payable", "type": "constructor" }, { "anonymous": false, "inputs": [ { "indexed": false, "name": "success", "type": "bool" } ], "name": "successNodeResponse", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": false, "name": "coinPrice", "type": "uint256" } ], "name": "NewPriceEmiited", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": true, "name": "id", "type": "bytes32" } ], "name": "ChainlinkRequested", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": true, "name": "id", "type": "bytes32" } ], "name": "ChainlinkFulfilled", "type": "event" }, { "anonymous": false, "inputs": [ { "indexed": true, "name": "id", "type": "bytes32" } ], "name": "ChainlinkCancelled", "type": "event" } ]; function createData(operator, oracle, job) { return { operator, oracle, job }; }; var HoneyDexFactory; export default class ContractInteraction extends React.Component { state ={ account : '', eth_amount: null, invoice_id: '', eth_address: '', options:[], oracles : [], job_ids : [], oracleCount: 0, showError:false, loading: false, createDisabled: false, createBtnMessage: 'Submit contract', newHoneyDexAddress: null }; getAccounts = () =>{ web3.eth.getAccounts().then(accounts => { this.setState({ account: accounts[0]}); console.log(accounts); });} //Loads the web3 Metamask confirmations and Checks for Events async loadBlockChain() { //this.props.toggleNextEnabled(); // Modern DApp Browsers if (window.ethereum) { web3 = new Web3(window.ethereum); try { window.ethereum.enable().then(function() { this.getAccounts(); //Set State When recieve Emission from Event from Smart Contract HoneyDexFactory = new web3.eth.Contract(abiHoneyDex, contractFactoryAddress); HoneyDexFactory.events.contractDeployed(function(error, result){ if (!error){ var HoneyDexAddress = result.returnValues.AgreementAddress; this.setState({ newHoneyDexAddress: HoneyDexAddress }); this.props.createHandler(HoneyDexAddress,this.state.oracleCount); // this.props.toggleNextEnabled(); } else { console.log(error); } }.bind(this)); }.bind(this)); } catch(e) { // User has denied account access to DApp... } } // Legacy DApp Browsers else if (window.web3) { web3 = new Web3(window.web3.currentProvider); this.getAccounts(); } // Non-DApp Browsers else { this.toggleError(); } } toggleError = () => { this.setState((prevState, props) => { return { showError: true } }) }; handleChangeChk(e) { // current array of options const options = this.state.options let index // check if the check box is checked or unchecked if (e.target.checked) { // add the numerical value of the checkbox to options array options.push(+e.target.value) } else { // or remove the value from the unchecked checkbox from the array index = options.indexOf(+e.target.value) options.splice(index, 1) } // update the state with the new array of options this.setState({ options: options }) } async componentWillMount() { this.loadBlockChain() } onSubmit = async (event) =>{ var oracles = [] var job_ids = [] for (let i = 0; i < this.state.options.length; i++) { oracles.push(rows[this.state.options[i]].oracle); job_ids.push(rows[this.state.options[i]].job); } event.preventDefault(); this.setState({ oracleCount: oracles.length, loading: true, errorMessage: ''}); try{ console.log('Get all accounts') console.log('CHECK THIS CONSOLE') this.setState({ loading: false, createDisabled:true, createBtnMessage:'Processing...'}); await HoneyDexFactory.methods.createAgreement(this.state.eth_address, this.state.btc_amount,this.state.seller_btc_address,this.state.buyer_btc_address, job_ids, oracles).send({from:this.state.account,value:web3.utils.toWei(this.state.eth_amount,'ether')}); }catch(err){ console.log(err) this.toggleError(); } // this.setState({createBtnMessage:'Complete'}); // const accounts = await web3.eth.getAccounts(); // const driverCd = await factory.methods.getDeployedContract(this.state.driver).call(); } render(){ return( <DivWithErrorHandling showError={this.state.showError}> <h5>Enter the details required for creating a HoneyDex contract: </h5> {/* <div className={classes}> */} <div > <Grid container justify = "center" spacing={1} alignItems="flex-end"> <Grid item> <TextField onChange ={event => this.setState({ eth_amount: event.target.value})} id="filled-textarea" label="ETH Amount" placeholder="eg. 12.34" multiline style = {{width: 430}} margin="normal" variant="filled" /> </Grid> </Grid> </div> <div > <Grid container justify = "center" spacing={1} alignItems="flex-end"> <Grid item> <TextField onChange ={event => this.setState({ btc_amount: event.target.value})} id="filled-textarea" label="BTC Amount To Receive" placeholder="eg. 1.234" multiline style = {{width: 430}} margin="normal" variant="filled" /> </Grid> </Grid> </div> <div> <Grid container justify = "center" spacing={1} alignItems="flex-end"> <Grid item> <TextField onChange ={event => this.setState({ eth_address: event.target.value})} id="filled-textarea" label="Buyer ETH Address" placeholder="eg. 0xA1B2C3D4E5F6G..." multiline style = {{width: 430}} margin="normal" variant="filled" /> </Grid> </Grid> </div> <div> <Grid container justify = "center" spacing={1} alignItems="flex-end"> <Grid item> <TextField onChange ={event => this.setState({ seller_btc_address: event.target.value})} id="filled-textarea" label="Your BTC Address to receive BTC" placeholder="eg. 147SwRQd..." multiline style = {{width: 430}} margin="normal" variant="filled" /> </Grid> </Grid> </div> <div> <Grid container justify = "center" spacing={1} alignItems="flex-end"> <Grid item> <TextField onChange ={event => this.setState({ buyer_btc_address: event.target.value})} id="filled-textarea" label="Buyer's BTC Address" placeholder="eg. 147SwRQd..." multiline style = {{width: 430}} margin="normal" variant="filled" /> </Grid> </Grid> </div> <div> <h5>Select 1 or more Chainlink data providers: </h5> <Grid container justify = "center" spacing={1} alignItems="flex-end"> <Grid item> <Table aria-label="simple table"> <TableHead> <TableRow> <TableCell></TableCell> <TableCell><b>Operator</b></TableCell> <TableCell align="center"><b>Oracle</b></TableCell> </TableRow> </TableHead> <TableBody> {rows.map((row,index) => ( <TableRow> <TableCell padding="checkbox"> <Checkbox value={index} onChange={event => this.handleChangeChk(event)} /> </TableCell> <TableCell component="th" scope="row"> {row.operator} </TableCell> <TableCell align="center">{row.oracle}</TableCell> </TableRow> ))} </TableBody> </Table> </Grid> </Grid> </div> <div> <Grid container justify = "center" spacing={1} alignItems="flex-end"> <Grid item> <br/> <Fab variant="extended" padding={5} disabled={this.state.createDisabled} onClick={this.onSubmit} aria-label="like"> <NavigationIcon /> {this.state.createBtnMessage} </Fab> </Grid> </Grid> </div> </DivWithErrorHandling> ) } }
import React from 'react' import './RuneStar.scss' class RuneStar extends React.Component { constructor(props) { super(props) this.state = { 1: false, 2: false, 3: false, 4: false, 5: false, 6: false } this.onClick1 = this.onClick.bind(this, '1') this.onClick2 = this.onClick.bind(this, '2') this.onClick3 = this.onClick.bind(this, '3') this.onClick4 = this.onClick.bind(this, '4') this.onClick5 = this.onClick.bind(this, '5') this.onClick6 = this.onClick.bind(this, '6') } onClick(rune) { let data = {} data[rune] = !this.state[rune] if (this.props.onChange) { this.props.onChange(rune, data[rune]) } this.setState(data) } render() { return ( <div className='sm-runestar'> <div className='sm-runestar-container'> <img src={'assets/images/runes_star/rune_background.png'}/> <div className={'sm-runestar-pos sm-runestar-pos-top' + (this.state[1] ? ' sm-runestar-selected' : '')} onClick={this.onClick1}/> <div className={'sm-runestar-pos sm-runestar-pos-top-right' + (this.state[2] ? ' sm-runestar-selected' : '')} onClick={this.onClick2}/> <div className={'sm-runestar-pos sm-runestar-pos-bottom-right' + (this.state[3] ? ' sm-runestar-selected' : '')} onClick={this.onClick3}/> <div className={'sm-runestar-pos sm-runestar-pos-bottom' + (this.state[4] ? ' sm-runestar-selected' : '')} onClick={this.onClick4}/> <div className={'sm-runestar-pos sm-runestar-pos-bottom-left' + (this.state[5] ? ' sm-runestar-selected' : '')} onClick={this.onClick5}/> <div className={'sm-runestar-pos sm-runestar-pos-top-left' + (this.state[6] ? ' sm-runestar-selected' : '')} onClick={this.onClick6}/> </div> </div> ) } } export default RuneStar
import { Template } from 'meteor/templating' import { addBootstrap4Class } from './utils/addBootstrap4Class' /* * Template helpers for "bootstrap4" templates */ Template.registerHelper('attsPlusFormControlClass', function attsPlusFormControlClass () { return addBootstrap4Class(this.atts, 'form-control') }) Template.registerHelper('attsPlusBtnClass', function attsPlusBtnClass () { return addBootstrap4Class(this.atts, 'btn') }) export const AutoFormBootstrap4 = { template: 'bootstrap4', async load () { return Promise.all([ import('./templates/bootstrap4'), import('./templates/bootstrap4-inline/bootstrap4-inline') ]) } }
import React from "react" import Insta1 from "./insta1" import Insta2 from "./insta2" import Insta3 from "./insta3" import Insta4 from "./insta4" import Insta5 from "./insta5" import InstaIcon from "./instagram-icon.inline.svg"; import "./instagram.scss" const Instagram = () => ( <div className="instagram-block"> <div className="instagram-intro head"> <h2>Get Social</h2> <h5 className="instagram-headline">FOLLOW US ON INSTAGRAM</h5> </div> <div className="instagram-pics"> <a className="insta-link" href="https://www.instagram.com/eventsbymosaic/" target="_blank" rel="noopener noreferrer"> <div className="hero-img-tint" /> <Insta1 /> </a> <a className="insta-link" href="https://www.instagram.com/eventsbymosaic/" target="_blank" rel="noopener noreferrer"> <div className="hero-img-tint" /> <Insta2 /> </a> <a className="insta-link" href="https://www.instagram.com/eventsbymosaic/" target="_blank" rel="noopener noreferrer"> <div className="hero-img-tint" /> <Insta3 /> </a> <a className="insta-link" href="https://www.instagram.com/eventsbymosaic/" target="_blank" rel="noopener noreferrer"> <div className="hero-img-tint" /> <Insta4 /> </a> <a className="insta-link" href="https://www.instagram.com/eventsbymosaic/" target="_blank" rel="noopener noreferrer"> <div className="hero-img-tint" /> <Insta5 /> </a> </div> <div className="instagram-intro foot"> <a href="https://www.instagram.com/eventsbymosaic/" target="_blank" rel="noopener noreferrer"> <div className="insta-link"> <div className="insta-icon"> <InstaIcon /> </div> <h4 className="insta-profile">eventsbymosaic</h4> </div> </a> </div> </div> ) export default Instagram
// view, itemEditView.js define([ 'underscore', 'jquery', 'backbone', 'collections/items', 'text!templates/itemEditViewTemplate.html', 'text!templates/itemEditViewTemplate--attr.html'], function(_,$,Backbone,stokItems,itemEdit,itemAttrEdit) { var itemEditView = Backbone.View.extend({ tagName: 'div', className: 'modal', newTemplate: _.template(itemEdit), editTemplate: _.template(itemAttrEdit), events: { 'click .collect-submit' : 'updateItem', 'click .collect-close' : 'closeEditView', 'click .collect-delete' : 'deleteItem' }, initialize: function(id) { this.render(id); }, render: function(id) { if (this.model) { this.$el.html(this.editTemplate(this.model.attributes)); } else { // render without model this.$el.html(this.newTemplate({list: id})); } return this; }, updateItem: function(e) { e.preventDefault(); var inputs = this.getInputs(); if (this.model) { this.model.set(inputs); } else { stokItems.add(inputs); } this.remove(); window.history.back(); }, getInputs: function() { var fields = this.$('form')[0].elements, // this is hacky keys = ["name", "manufacturer", "price", "url", "img", "list"] values = {}; _.forEach(keys, function(key) { if (fields[key] && fields[key].value.length !== 0) { values[key] = fields[key].value; } }); return values; }, deleteItem: function(e) { e.preventDefault(); if (this.model) { stokItems.remove(this.model); } this.remove(); window.history.back(); }, closeEditView: function(e) { e.preventDefault(); $('body').remove('.modal'); this.remove(); window.history.back(); } }); return itemEditView; });
(function (routeConfig) { 'use strict'; routeConfig.init = function (app) { // *** routes *** // const routes = require('../routes/index'); const events = require('../routes/events'); const attendees = require('../routes/attendees'); const venues = require('../routes/venues'); // *** register routes *** // app.use('/', routes); app.use('/events', events); app.use('/attendees', attendees); app.use('/venues', venues); }; })(module.exports);
/*global alert: false, confirm: false, console: true, Debug: false, opera: false, prompt: false, WSH: false */ /*jslint plusplus: true */ var jQuery, $ = jQuery; (function ($) { "use strict"; var toggleClass = $(".toggle"); // ============================================== // DROPDOWN and NAVBAR // ============================================== toggleClass.on("click", function () { var the = $(this), theParent = the.closest(".toggle__parent"), theSibling = theParent.siblings().find(".toggle"); the.toggleClass("active"); if (the.hasClass("active")) { theSibling.removeClass("active"); } }); // ------------------------------------------- $(document).mouseup(function (event) { var $container = $('.dropdown *'), $btn = $('.toggle'); if (!$container.is(event.target) && $container.has(event.target).length === 0 && !$btn.is(event.target)) { $btn.removeClass('active'); } }); // // ------------------------------------------- // navToggle.on("click", function () { // var the = $(this), // theContainer = the.siblings(".nav"); // if (the.hasClass("active")) { // theContainer.show(100); // } else { // theContainer.hide(100); // } // }); // // ------------------------------------------- // $(window).on("resize", function () { // var the = $(this); // if (the.width() > 660) { // navToggle.addClass("active"); // nav.css({ // "display": "block" // }); // } else { // navToggle.removeClass("active"); // nav.css({ // "display": "none" // }); // } // }); // ============================================== // CAROSEL - http://kenwheeler.github.io/slick/ // ============================================== $('.carousel').slick({ autoplaySpeed: 1000, dots: true, infinite: true, speed: 300, slidesToScroll: 1, centerMode: true, autoplay: true, variableWidth: true }); // ============================================== // TABS - http://vdw.github.io/Tabslet/ // ============================================== $('.tab').tabslet(); console.log("module.js"); }(jQuery));
(function () { 'use strict'; var stats = { 'el': document.getElementById('stats') }; stats.controller = function () { var ctrl = this; ctrl.data = {}; stats.el.addEventListener('stats', function (event) { ctrl.data = event.detail; m.render(stats.el, stats.view(ctrl)); }); }; stats.view = function (c) { if (Object.keys(c.data).length === 0) { return m('p', 'Waiting for data'); } return [ m('h1', 'Dagens forbruk'), m('table', [ m('tr.fade', [ m('th', 'Drikke'), m('th', 'Antall') ]), m('tr', [ m('td', 'Kaffe'), m('td', [ m('span', c.data.stats.coffee), m('span.fade', ' / ' + c.data.max.coffee) ]) ]), m('tr', [ m('td', 'Øl'), m('td', [ m('span', c.data.stats.beer), m('span.fade', ' / ' + c.data.max.beer) ]) ]) ]), m('p', {'class': 'fade updated-at'}, 'Sist oppdatert: ' + c.data.updatedAt) ]; }; if (stats.el !== null) { m.module(stats.el, stats); } })();
import React from 'react'; import SignUpForm from './signUpForm'; import './styles/banner.css'; export default class Banner extends React.Component { toggleBanner(event) { event.preventDefault(); if(this.props.toggleBanner) { this.props.toggleBanner(); } } render() { return( <article className="banner col-6 center mw7 ph3 ph5-ns tc pv4 clear-float"> <header> <h1 className="fw6 f3 f2-ns lh-title mv4">Welcome to Joystick Informer</h1> <h2 className="fw2 f4 lh-copy mt2 mb3">This is a place to find, compare, favorite, and buy console games. Search by title, view tags, and keep up to date with new and old titles.</h2> </header> <p className="f5 mt0 mb3 b">Complete the form below to sign up for a free account, or just jump right in by pressing the <span className="ba b--white pa1 nowrap">Let's Get Started</span> button at the bottom of the page.</p> <p className="f5 mt0 b">Feel free to use a provided demo account as well: <span className="db fw2">Username: JoystickTest</span><span className="db fw2"> Password: JoystickPassword</span></p> <SignUpForm banner={true} /> <div className="skip"> <button className="f6 js-button ba grow dib" onClick={e => this.toggleBanner(e)}>Let's Get Started</button> </div> </article> ) } }
const x = -0.2; const y = -0.5; const a11 = -1 +(Math.sin(y)/ (Math.cos(x)*Math.sin(y) - 2))*Math.cos(x); const a12 = -Math.sin(y)/ (Math.cos(x)*Math.sin(y) - 2); const a21 = (1 / (Math.cos(x)*Math.sin(y)-2)) *Math.cos(x); const a22 = -1 / (Math.cos(x)*Math.sin(y)-2); const f1= (x, y)=> Math.cos(y+0.5)+x-0.8; const f2 = (x,y)=>Math.sin(x) -2*y-1.6; const fi1=(x,y)=>x + a11*f1(x,y) + a12*f2(x,y); const fi2=(x,y)=>y + a21*f1(x, y) + a22*f2(x, y); function Newton (){ let xi=x, yi=y,k=0; do { k++; xi = fi1(xi, yi); yi = fi2(xi, yi); } while (f1(xi, yi) >= 0.0001 && f2(xi, yi) >= 0.0001); console.log(xi); console.log(yi); console.log(k); } Newton();
import React, { Component } from 'react'; import { View, Text, StyleSheet, TouchableOpacity, Keyboard} from 'react-native'; import { FontAwesome, MaterialCommunityIcons, MaterialIcons, SimpleLineIcons, Entypo, Fontisto, Feather, Ionicons } from '@expo/vector-icons'; import { connect } from 'react-redux'; import { selectTheme, selectVideo } from '../actions'; import settings from '../appSettings'; import { Appearance, useColorScheme } from 'react-native-appearance'; const lightTheme = settings.lightTheme const darkTheme =settings.darkTheme class MyTabBar extends React.Component { constructor(props) { super(props); this.state = { showTab: true }; } componentDidMount(){ Keyboard.addListener('keyboardDidShow', this._keyboardDidShow); Keyboard.addListener('keyboardDidHide', this._keyboardDidHide); } componentWillUnmount() { Keyboard.removeListener('keyboardDidShow', this._keyboardDidShow); Keyboard.removeListener('keyboardDidHide', this._keyboardDidHide); } _keyboardDidShow = () => { this.setState({ showTab: false }) }; _keyboardDidHide = () => { this.setState({ showTab: true }) }; icon = (label, isFocused,theme) => { if (label == "universal") { return ( <Entypo name="globe" size={20} color={isFocused?theme.secondaryColor:"gray"}/> ) } if(label == "Media"){ return ( <MaterialIcons name="perm-media" size={20} color={isFocused ? theme.secondaryColor : "gray"}/> ) } if (label == "QuestionPapers") { return ( <FontAwesome name="newspaper-o" size={20} color={isFocused ? theme.secondaryColor : "gray"} /> ) } if (label == "Sports") { return ( <MaterialCommunityIcons name="tennis" size={20} color={isFocused ? theme.secondaryColor : "gray"} /> ) } if (label == "Admissions") { return ( <FontAwesome name="institution" size={20} color={isFocused ? theme.secondaryColor : "gray"} /> ) } if (label == "Profile") { return ( <Ionicons name="md-person-circle" size={24} color={isFocused ? theme.secondaryColor : "gray"} /> ) } if (label == "Institute") { return ( <FontAwesome name="institution" size={20} color={isFocused ? theme.secondaryColor : "gray"} /> ) } if (label == "Class") { return ( <MaterialCommunityIcons name="google-classroom" size={24} color={isFocused ? theme.secondaryColor : "gray"} /> ) } } render() { let theme const { state, descriptors, navigation,selectedTheme} =this.props if(this.props.theme =="dark"){ theme = darkTheme }else{ theme =lightTheme } if(this.state.showTab){ return ( <View style={{ backgroundColor: theme.backgroundColor, height: 50, flexDirection: "row" }}> {state.routes.map((route, index) => { const { options } = descriptors[route.key]; const label = options.tabBarLabel !== undefined ? options.tabBarLabel : options.title !== undefined ? options.title : route.name; const isFocused = state.index === index; const onPress = () => { const event = navigation.emit({ type: 'tabPress', target: route.key, }); if (!isFocused && !event.defaultPrevented) { navigation.navigate(route.name); } }; const onLongPress = () => { navigation.emit({ type: 'tabLongPress', target: route.key, }); }; return ( <TouchableOpacity key={index} accessibilityRole="button" accessibilityStates={isFocused ? ['selected'] : []} accessibilityLabel={options.tabBarAccessibilityLabel} testID={options.tabBarTestID} onPress={onPress} onLongPress={onLongPress} style={{ flex: 0.2, alignItems: "center", justifyContent: "center", borderTopWidth: isFocused ? 5 : 0, borderColor: theme.secondaryColor }} > { this.icon(label, isFocused, theme) } <Text style={[{ color: isFocused ? theme.secondaryColor : 'gray', fontFamily: "openSans", fontSize: label == "QuestionPapers" ? 10 : 12 }, styles.text]}> {label} </Text> </TouchableOpacity> ); })} </View> ); }else{ return null } } } const styles = StyleSheet.create({ text:{ fontFamily:"openSans", lineHeight: 22, fontWeight:'bold' }, }) const mapStateToProps = (state) => { return { theme: state.selectedTheme, selectedVideo: state.selectedVideo } } export default connect(mapStateToProps, { selectTheme})(MyTabBar)
import styled from "styled-components"; export const BoxCenter = styled.div` position: relative; display: flex; justify-content: space-evenly; flex-wrap: wrap; margin: 0 auto; margin-top: ${(props) => props.marginTop}; text-align: center; a { text-decoration: none; color: red; } @media (max-width: 768px) { margin-top: 2vh; } `; export const RedPunkt = styled.span` color: red; font-size: 3rem; line-height: 1; `; export const Button = styled.button` padding: 15px 30px; margin: 10px; background: red; font-size: 1.2rem; font-weight: 600; border: none; border-radius: 5px; a { text-decoration: none; color: white; } &:hover { transform: scale(1.05); /* transition: all 0.3s ease; */ } `; export const TextWrap = styled.div` font-family: var(--font-body); font-size: 1.2rem; width: 100%; padding: 30px; max-width: 600px; margin: 0 auto; @media (max-width: 768px) { text-align: center; } `; export const SvgAbout = styled.div` position: absolute; bottom: 0; right: 0; z-index: -888; @media (max-width: 768px) { opacity: 0.2; bottom: -10%; } `; export const ProjectStyling = styled.div` width: 300px; height: 300px; padding: 30px; border-radius: 50%; margin: 50px; background: whitesmoke; box-shadow: 0 6px 4px 2px #ccc; position: relative; img { opacity: 1; display: block; width: 100%; height: 100%; transition: 0.5s ease; backface-visibility: hidden; } &:hover img { opacity: 0.2; } &:hover > * { opacity: 1; } `; export const Overlay = styled.div` position: absolute; transition: 0.5s ease; opacity: 0; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); -ms-transform: translate(-50%, -50%); text-align: center; p { background-color: black; color: white; border-radius: 10px; font-size: 16px; padding: 8px 10px; } `;
let Totalprice = 0; let quantity = []; let countOfitem = []; let cart; function OpenTheCart() { quantity = JSON.parse(localStorage.getItem('quantityArray')); Totalprice = JSON.parse(localStorage.getItem('totalprice')); countOfitem = JSON.parse(localStorage.getItem('countOfitem')); let key = ''; let list = '<tr class="output"><th>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Order</th><th>Price</th><th>Quantity</th></tr>\n'; let i = 0; for (i = 0; i < localStorage.length; i++) { key = localStorage.key(i); if ( key == 'quantityArray' || key == 'cUser' || key == 'members' || key == 'totalprice' || key == 'countOfitem' || key == 'background-color' || key == 'bgColor' ) continue; console.log(localStorage.getItem(key), quantity[localStorage.getItem(key)]); list += '<tr><td>' +'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' + key + '</td>\n<td>' + '&nbsp;&nbsp;' + localStorage.getItem(key) + '</td>\n<td>' + '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' + quantity[localStorage.getItem(key)] + '</td></tr>\n'; } if (list == '<tr class="output"><th>Order</th><th>Price</th></tr>\n') { list += '<tr class="output"><td><i>empty</i></td>\n<td><i>empty</i></td></tr>\n'; } document.getElementById('list').innerHTML = list; } function addtocart(TypeOfFood, price) { if (localStorage.getItem('quantityArray') != null) quantity = JSON.parse(localStorage.getItem('quantityArray')); if (localStorage.getItem('totalprice') != null) Totalprice = JSON.parse(localStorage.getItem('totalprice')); if (localStorage.getItem('countOfitem') != null) countOfitem = JSON.parse(localStorage.getItem('countOfitem')); if (localStorage.getItem(TypeOfFood) == null) { localStorage.setItem(TypeOfFood, price); Totalprice += price; quantity[price] = 1; countOfitem[price] = 1; } else if (localStorage.getItem(TypeOfFood) != null) { countOfitem[price]++; Totalprice += price; quantity[price] = countOfitem[price]; } let quantity_sterialized = JSON.stringify(quantity); let totalPrice_sterialized = JSON.stringify(Totalprice); let countOfitem_sterialized = JSON.stringify(countOfitem); localStorage.setItem('quantityArray', quantity_sterialized); localStorage.setItem('totalprice', totalPrice_sterialized); localStorage.setItem('countOfitem', countOfitem_sterialized); alert('Item has been addded to your cart'); } function ClearAll() { Totalprice = 0; localStorage.clear(); document.getElementById('list').innerHTML = Totalprice; } function TotalPrice() { Totalprice = JSON.parse(localStorage.getItem('totalprice')); document.getElementById('list').innerHTML = Totalprice; } function goToHome() { window.location = 'index.html'; } function goToLogin() { window.location = 'login.html'; } function goToPayment() { window.location = 'paymentBycredit.html'; }
import React from 'react'; import { Container } from './style'; export default function Divisor() { return ( <Container> <div></div> <div></div> </Container> ) }
'use strict'; module.exports = { name: 'ember-uuid' };
import type from '../type'; import { fetchData, } from '../../util/FetchUtil'; import UserService from '../../api/service/UserService'; import NavigationUtil from '../../util/NavigationUtil'; import { AsyncStorage, } from 'react-native'; import Constants from '../../Constants'; /** |-------------------------------------------------- | 获取用户登录状态,如果为登录状态,拉取用户信息 |-------------------------------------------------- */ export function checkLogin() { return (dispatch) => { fetchData(UserService.ISLOGIN) .then(isLogin => { if (isLogin === 1) { onUserInfoUpdate(dispatch); } else { dispatch({ type: type.USER_UPDATE, userInfo: null, }); } }); }; } /** * 获取用户信息 */ export function onUserInfoUpdate(dispatch) { return fetchData(UserService.GETUSERINFO) .then((userInfo) => { dispatch({ type: type.USER_UPDATE, userInfo: userInfo, }); }); } /** * 登录 * @param {*} params */ export function login(params, navigation) { return (dispatch) => { const { userName, } = params; _storeUsername(userName).then(() => { fetchData(UserService.LOGIN, params).then((token) => { /** |-------------------------------------------------- | 保存token |-------------------------------------------------- */ _storeUsername(); AsyncStorage.setItem(Constants.TOKEN, token) .then(onUserInfoUpdate(dispatch)); }).then(() => NavigationUtil.goBack(navigation)); } ); }; } const _storeUsername = async (username) => { await AsyncStorage.setItem(Constants.USERNAME, username); }; export function logout(navigation) { return (dispatch) => { fetchData(UserService.LOGOUT) .then(() => { NavigationUtil.goBack(navigation); dispatch({ type: type.USER_UPDATE, userInfo: null, }); }); }; }
import express from 'express'; import Product from '../controller/product'; import Buy from '../controller/buy'; import Sort from '../controller/sort' const router = express.Router(); router.post('/release', Product.publicProduct); router.get('/getProducts', Product.getProducts); router.get('/getAllProducts', Product.getAllProducts); router.get('/getDetail', Product.getDetail); router.get('/searchProduct', Product.searchProduct); router.delete('/delProduct/:user_id/:product_id', Product.delProduct); router.post('/updateProduct/:product_id', Product.updateProduct); router.get('/getOrderInfo', Product.getOrderInfo); router.post('/confirmOrder', Buy.confirmOrder); router.get('/getMyBuy', Buy.getMyBuy); router.get('/getMySold', Buy.getMySold); router.get('/getBuyOrderDetail', Buy.getBuyOrderDetail); router.get('/getSorts', Sort.getSorts); export default router;
import { createGlobalStyle } from "styled-components"; export default createGlobalStyle ` *{ margin:0; padding: 0; box-sizing:border-box; color: var(--white); } html, border-style, #root { max-height:100vh; max-width:100vw; width:100%; height:100%; background-image:url('https://image.freepik.com/vetores-gratis/fundo-de-desenho-abstrato-com-gradiente-de-azul-e-roxo_1048-13167.jpg'); background-repeat:no-repeat; background-size:cover; font-family: 'Roboto', sans-serif; } *, button, input { border:0; background:none; } `;
// Private Ansible playbook // // Copyright (C) 2018 T. Himmelstoss // // This software may be freely distributed under the MIT license. You should // have received a copy of the MIT License along with this program. // Restore the last session user_pref("browser.startup.page", 3); // Always ask for download directory user_pref("browser.download.useDownloadDir", false); // Do not save form data user_pref("browser.formfill.enable", false); // Custom history setting user_pref("privacy.history.custom", true); // Allow DRM media playback user_pref("media.eme.enabled", true); // Block third party cookies used for tracking user_pref("network.cookie.cookieBehavior", 4); // Allways send the Do Not Track header user_pref("privacy.donottrackheader.enabled", true); // Allways block tracking content user_pref("privacy.trackingprotection.enabled", true); // Do not save passwords user_pref("signon.rememberSignons", false); // Do not send health reports user_pref("datareporting.healthreport.uploadEnabled", false);
/*global describe: true, expect: true, it: true */ describe("path", function() { // TODO: more tests var path = require('path'); var pathChunks = [ "foo", "bar", "baz", "qux.html" ]; var joinedPath = path.join.apply(this, pathChunks); describe("basename", function() { it("should exist", function() { expect(path.basename).toBeDefined(); }); it("should be a function", function() { expect(typeof path.basename).toEqual("function"); }); it("should work correctly without an 'ext' parameter", function() { expect( path.basename(joinedPath) ).toEqual( pathChunks[pathChunks.length - 1] ); }); it("should work correctly with an 'ext' parameter", function() { var fn = pathChunks[pathChunks.length - 1], ext = Array.prototype.slice.call( fn, fn.indexOf(".") ).join(""); bn = Array.prototype.slice.call( fn, 0, fn.indexOf(".") ).join(""); expect( path.basename(joinedPath, ext) ).toEqual(bn); }); }); });
import * as types from '../constants/actionTypes'; import { call, put, take, select, fork, } from 'redux-saga/effects'; import { takeLatest } from 'redux-saga'; import { postReq } from '../utils/request' import NavigationService from '../utils/navigationService' import { storeData } from '../utils/storage' function *login () { while (1) { const { payload } = yield take(types.LOGIN_SUBMIT_REQUEST) try { yield call(postReq, { url: '/v1.0/auth/login', params: payload }) console.log(payload) const { username } = payload; yield storeData('username', username) NavigationService.replaceRouter('search') } catch (e) { console.log(e); } } } export default function *() { yield fork(login); }
var convert = new Interface('../pdfinfo-worker.js'); var output = "" convert.on_stdout = function(txt) { output += txt; }; convert.on_stderr = function(txt) { console.log(txt); }; var test_result = function(contents) { var expected_output = "Title: freiesMagazin 03/2013\n" + "Subject: Magazin rund um Linux und Open Source\n" + "Keywords: freiesMagazin, freies, Magazin, Linux, Open Source\n" + "Author: Dominik Wagenführ\n" + "Creator: Dominik Wagenführ\n" + "Producer: pdfTeX-1.40.13\n" + "CreationDate: D:20130303093415+01'00'\n" + "ModDate: D:20130303093415+01'00'\n" + "Tagged: no\n" + "Form: none\n" + "Pages: 49\n" + "Encrypted: no\n" + "Page size: 841.89 x 595.276 pts (A4)\n" + "Page rot: 0\n" + "File size: 2479159 bytes\n" + "Optimized: no\n" + "PDF version: 1.4\n"; testResult(output === expected_output); } convert.addUrl('tests/test.pdf', '/'); convert.allDone().then( convert.run.curryPromise('/test.pdf').then(test_result) );
// import actions import { GET_SMURF_DATA, POST_SMURF, REMOVE_SMURF, ADD_NUMBER } from "../actions" // initial const initialState = { smurfs: [ { name: "", height: "", age: "", id: null } ] } const reducer = (state = initialState, action) => { switch (action.type) { case GET_SMURF_DATA: return { smurfs: action.payload } case POST_SMURF: return { ...state, smurfs: [...state.smurfs, { name: action.payload.name, height: action.payload.height + "cm", age: action.payload.age, id: action.payload.id }] } case REMOVE_SMURF: return { ...state, smurfs: state.smurfs.filter(smurfs => smurfs.id !== action.payload ) } case ADD_NUMBER: return { ...state, number: action.payload } default: return state } } export default reducer
// @flow /* ********************************************************** * File: tests/factories/factories.js * * Brief: Factory definitions for tests. * Author: Craig Cheney * * 2017.09.23 CC - Moved action creators to actionFactories.js * 2017.09.22 CC - Document Created * ********************************************************* */ import faker from 'faker'; import { moduleNames } from '../../app/utils/mica/micaConstants'; import type { idType, channelsT } from '../../app/types/paramTypes'; import type { moduleNameType, } from '../../app/types/metaDataTypes'; /* Factory for creating an device id */ export function deviceIdFactory(): idType { /* Return a 128 bit uuid with no dashes */ return faker.random.uuid().replace(/-/g, ''); } /* Returns the ID of a sensor */ export function sensingIdFactory(): idType { return faker.random.arrayElement(['1', '2']); } /* Returns the name of one of the six modules */ export function moduleNameFactory(): moduleNameType { return faker.random.arrayElement(moduleNames); } /* Returns a channel obj based on an array of active channels */ export function channelArrayToObj(chanArray: number[]): channelsT { /* default */ const channels = { '0': { active: false, name: 'X', offset: 0 }, '1': { active: false, name: 'Y', offset: 0 }, '2': { active: false, name: 'Z', offset: 0 }, }; /* Set the sensors active */ for (let i = 0; i < chanArray.length; i++) { const chanId = chanArray[i]; channels[chanId].active = true; } return channels; } // TODO: Implement // export function deviceStateFactory( // devId?: idType, // sensId?: idType // ): devicesStateType { // const deviceId = devId || deviceIdFactory(); // const sensingId = sensId || sensingIdFactory(); // } /* [] - END OF FILE */
'use strict' const operators = { "+": (a, b) => a + b, "-": (a, b) => a - b, "*": (a, b) => a * b, "/": (a, b) => a / b }; const doOp = (left, ope, right, callback) => { if (operators[ope] == undefined) { callback(`Error: ${ope} : unknow operator`); return; } else if (ope == "/" && right == 0) { callback("Logical error: division by zero"); return; } else callback(undefined, operators[ope](left, right)); }; const testDoop = () => { let a = Number(process.argv[2]); let ope = process.argv[3]; let b = Number(process.argv[4]); doOp(a, ope, b, (err, res) => { if (err != undefined) console.error(err); else console.log(res); }); };
import React from 'react' function Header() { const date = new Date(); const hours = date.getHours(); let timeOfDay; let colorOfDay; if (hours<12) { timeOfDay = "morning"; colorOfDay = "white"; } else if (hours < 17) { timeOfDay = "afternoon"; colorOfDay = "orange"; } else if (hours < 22){ timeOfDay = "evening"; colorOfDay = "purple"; } else{ timeOfDay = "night"; colorOfDay = "black"; } const styles = { color: colorOfDay } return ( <header className="navbar" style={styles}>Hey! Good {timeOfDay}</header> ); } export default Header;
import React, { useRef } from "react"; import { isEmpty } from "underscore"; import d3 from "d3"; // css styles import "assets/css/d3/timeseries.css"; const DEFAULT_WIDTH = 700; const DEFAULT_HEIGHT = 500; const DEFAULT_MARGIN = { top: 20, right: 30, bottom: 65, left: 90 }; const TimeSeriesChart = ({ width, height, margin, data }) => { const ref = useRef(); const width_ = width || DEFAULT_WIDTH; const height_ = height || DEFAULT_HEIGHT; const margin_ = margin || DEFAULT_MARGIN; const innerHeight = height_ - margin_.top - margin_.bottom; const innerWidth = width_ - margin_.left - margin_.right; const svg = d3 .select(ref.current) .append("g") .attr("transform", `translate(${margin_.left}, ${margin_.top})`); const xScale = d3 .scaleTime() .domain(d3.extent(data, (d) => new Date(d.time))) .range([0, innerWidth]); const xAxis = svg .append("g") .attr("class", "x axis") .attr("transform", "translate(0," + innerHeight + ")") // .attr("transform", `translate(${margin_.left}, ${margin_.top})`) .call(d3.axisBottom(xScale)); const yScale = d3 .scaleLinear() .domain(d3.extent(data, (d) => d.value)) // .domain([0, 100]) // .domain([22.8, 69.45]) .range([innerHeight, 0]) .nice(); const yAxis = svg .append("g") .attr("class", "y axis") // .attr("transform", `translate(${margin_.left}, ${margin_.top})`) .call(d3.axisLeft(yScale)); const dataNest = d3 .nest() .key((d) => d.name) .entries(data); const color = d3.scaleOrdinal().range(d3.schemeCategory10); const legendSpace = innerWidth / dataNest.length; // Define the line const priceline = d3 .line() // .curve(d3.curveLinearClosed) // .curve(d3.curveBasis) .curve(d3.curveCatmullRom) // .curve(d3.curveMonotoneX) .x((d) => xScale(new Date(d.time))) .y((d) => yScale(d.value)); dataNest.forEach((d, i) => { const id = `tag-${Math.random() .toString(16) .slice(2)}-${Math.random().toString(16).slice(2)}-${i}`; svg .append("path") .attr("class", "timeseries-path line") .style("stroke", () => (d.color = color(d.key))) .attr("id", id) // assign ID .attr("d", priceline(d.values)); // Add the Legend svg .append("text") .attr("x", legendSpace / 2 + i * legendSpace) // space legend .attr("y", innerHeight + margin_.bottom / 2 + 5) .attr("class", "legend") // style the legend .style("fill", () => { // mark path as active d.active = true; // Add the colours dynamically return (d.color = color(d.key)); }) .style("cursor", "pointer") .on("click", function () { // Determine if current line is visible const active = !!d.active; const newOpacity = active ? 0 : 1; d3.select(`#${id}`) .transition() .duration(100) .style("opacity", newOpacity); // Update whether or not the elements are active d.active = !active; }) .text(d.key); }); return ( <svg width={width_} height={height_} ref={ref} style={{ border: "1px solid red" }} /> ); }; export default TimeSeriesChart;
import { Alert, Checkbox, Form, Input, Button, Icon, message } from 'antd'; import React, { useState } from 'react'; import { router } from 'umi'; import { connect } from 'dva'; import styles from './style.less'; import { login } from '../../../services/login'; import { getPageQuery } from '@/utils/utils'; const Login = props => { const [username, setUsername] = useState('admin'); const [password, setPassword] = useState('password'); const handleSubmit = async () => { const res = await login({ username, password }); if (!res) { return } if (res.loginSuccess) { localStorage.setItem("token", res.token) const urlParams = new URL(window.location.href); const params = getPageQuery(); let { redirect } = params; if (redirect) { const redirectUrlParams = new URL(redirect); if (redirectUrlParams.origin === urlParams.origin) { redirect = redirect.substr(urlParams.origin.length); if (redirect.match(/^\/.*#/)) { redirect = redirect.substr(redirect.indexOf('#') + 1); } } else { window.location.href = '/'; return; } } router.replace(redirect || '/'); } else { message.error('用户名密码错误'); } }; return ( <div className={styles.main}> <Form className="login-form"> <Form.Item> <Input // prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />} value={username} onChange={e => setUsername(e.target.value)} placeholder="请输入用户名" /> </Form.Item> <Form.Item> <Input value={password} onChange={e => setPassword(e.target.value)} // prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />} type="password" placeholder="请输入密码" /> </Form.Item> <Form.Item> <Button type="primary" size="large" htmlType="submit" className="login-form-button" onClick={handleSubmit} > 登录 </Button> </Form.Item> </Form> </div> ); }; export default Login;
(function () { "use strict"; angular.module("vcas").controller("AddEntitlementModalCtrl", AddEntitlementModalCtrl); /* @ngInject */ function AddEntitlementModalCtrl($modalInstance, ContentsService, EntitlementsService, chosenEntity, AlertsService, ResultsHandlerService) { var vm = this; vm.chosenEntity = chosenEntity; vm.packages = undefined; vm.filter = ""; vm.dismissModal = dismissModal; vm.closeModal = closeModal; vm.addPackages = addPackages; vm.anySelected = anySelected; initialize(); function initialize() { vm.timePeriodRule = { startTime: null, endTime: null }; ContentsService.getPackages().then(setPackages); function setPackages(response) { vm.packages = ResultsHandlerService.toArray(response.packages); } } function addPackages () { /** * Add the selected packages to the Device */ // Detect the type of Entity: var selectedPackages = ResultsHandlerService.getSelected(vm.packages), selectedEntity = (vm.chosenEntity.hasOwnProperty("smsDeviceId")) ? {type: "DEVICE", id: vm.chosenEntity.smsDeviceId} : {type: "DOMAIN", id: vm.chosenEntity.smsDomainId}; EntitlementsService.addEntitlements(selectedPackages, selectedEntity, vm.timePeriodRule).then(successAdded); function successAdded (response) { var results = ResultsHandlerService.groupResultsByCode(response.data.resultList.result); _.each(results.success, function (result) { AlertsService.addSuccess("Successfully added Entitlement " + result.resultId); }); _.each(results.error, function (result) { AlertsService.addErrors("Could not add Entitlement " + result.resultId + ": " + result.resultText + ". (Error code: " + result.resultCode + ")"); }); if (!results.error) { vm.closeModal(); } } } function dismissModal() { $modalInstance.dismiss(); } function closeModal() { $modalInstance.close(); } function anySelected() { return ResultsHandlerService.anySelected(vm.packages); } } }());
import {ErrorMessagedException} from 'nt-portal-framework/src/utils/exceptions'; async function accountRecharge(param, ctx) { if (param===1) { //正常返回 return { statusCode: '2000000', data: { hello: 'world' } }; } else if(param===-1) { //返回,未声明的异常代码 return { statusCode: '2030000', data: { hello: 'world' } }; } else if (param===2) { //返回,声明的异常代码 throw new ErrorMessagedException('这个错误交给系统处理', { statusCode: '4020001', data: { hello: 'world' } }); } } export const account = { accountRecharge };
// A generic function for checking to see if an input element has // had information entered into it function checkRequired(elem) { if (elem.type == "checkbox" || elem.type == "radio") return getInputsByName(elem.name).numChecked; else return elem.value.length > 0 && elem.value != elem.defaultValue; } // Find all input elements that have a specified name (good for finding // and dealing with checkboxes or radio buttons) function getInputsByName(name) { // The array of input elements that will be matched var results = []; // Keep track of how many of them were checked results.numChecked = 0; // Find all the input elements in the document var input = document.getElementsByTagName("input"); for (var i = 0; i < input.length; i++) { // Find all the fields that have the specified name if (input[i].name == name) { // Save the result, to be returned later results.push(input[i]); // Remember how many of the fields were checked if (input[i].checked) results.numChecked++; } } // Return the set of matched fields return results; } // Wait for the document to finish loading window.onload = function () { // Get the form and watch for a submit attempt. document.getElementsByTagName("form")[0].onsubmit = function () { // Get an input element to check var elem = document.getElementById("age"); // Make sure that the required age field has been checked if (!checkRequired(elem)) { // Display an error and keep the form from submitting. alert("Required field is empty – " + "you must be over 13 to use this site."); return false; } // Get an input element to check var elem = document.getElementById("name"); // Make sure that some text has been entered into the name field if (!checkRequired(elem)) { // Otherwise display an error and keep the form from submitting alert("Required field is empty – please provide your name."); return false; } }; }; // A generic function for checking to see if an input element // looks like an email address function checkEmail(elem) { // Make sure that something was entered and that it looks like // a valid email address return elem.value == '' || /^[a-z0-9_+.-]+\@([a-z0-9-]+\.)+[a-z0-9]{2,4}$/i.test(elem.value); } // Get an input element to check var elem = document.getElementById("email"); // Check to see if the field is valid, or not if (!checkEmail(elem)) { alert("Field is not an email address."); } // A generic function for checking to see if an input element has // a URL contained in it function checkURL(elem) { // Make sure that some text was entered, and that it's // not the default http:// text return elem.value == '' || !elem.value == 'http://' || // Make sure that it looks like a valid URL /^https?:\/\/([a-z0-9-]+\.)+[a-z0-9]{2,4}.*$/.test(elem.value); } // Get an input element to check var elem = document.getElementById("url"); // Check to see if the field is a valid URL if (!checkURL(elem)) { alert("Field does not contain a URL."); } // A generic function for checking to see if an input element has // a Phone Number entered in it function checkPhone(elem) { // Check to see if we have something that looks like // a valid phone number var m = /(\d{3}).*(\d{3}).*(\d{4})/.exec(elem.value); // If it is, seemingly, valid - force it into the specific // format that we desire: (123) 456-7890 if (m !== null) { elem.value = "(" + m[1] + ") " + m[2] + "-" + m[3]; } return elem.value == '' || m !== null; } // Get an input element to check var elem = document.getElementById("phone"); // Check to see if the field contains a valid phone number if (!checkPhone(elem)) { alert("Field does not contain a phone number."); } // A generic function for checking to see if an input element has // a date entered into it function checkDate(elem) { // Make sure that something is entered, and that it // looks like a valid MM/DD/YYYY date return !elem.value || /^\d{2}\/\d{2}\/\d{2,4}$/.test(elem.value); } // Get an input element to check var elem = document.getElementById("date"); // Check to see if the field contains a valid date if (!checkDate(elem)) { alert("Field is not a date."); } // 通用处理 var errMsg = { // Checks for when a specified field is required required: { msg: "This field is required.", test: function (obj, load) { // Make sure that there is no text was entered in the field and that // we aren't checking on page load (showing 'field required' messages // would be annoying on page load) return obj.value.length > 0 || load || obj.value == obj.defaultValue; } }, // Makes sure that the field s a valid email address email: { msg: "Not a valid email address.", test: function (obj) { // Make sure that something was entered and that it looks like // an email address return !obj.value || /^[a-z0-9_+.-]+\@([a-z0-9-]+\.)+[a-z0-9]{2,4}$/i.test(obj.value); } }, // Makes sure the field is a phone number and // auto-formats the number if it is one phone: { msg: "Not a valid phone number.", test: function (obj) { // Check to see if we have something that looks like // a valid phone number var m = /(\d{3}).*(\d{3}).*(\d{4})/.exec(obj.value); // If it is, seemingly, valid - force it into the specific // format that we desire: (123) 456-7890 if (m) obj.value = "(" + m[1] + ") " + m[2] + "-" + m[3]; return !obj.value || m; } }, // Makes sure that the field is a valid MM/DD/YYYY date date: { msg: "Not a valid date.", test: function (obj) { // Make sure that something is entered, and that it // looks like a valid MM/DD/YYYY date return !obj.value || /^\d{2}\/\d{2}\/\d{2,4}$/.test(obj.value); } }, // Makes sure that the field is a valid URL url: { msg: "Not a valid URL.", test: function (obj) { // Make sure that some text was entered, and that it's // not the default http:// text return !obj.value || obj.value == 'http://' || // Make sure that it looks like a valid URL /^https?:\/\/([a-z0-9-]+\.)+[a-z0-9]{2,4}.*$/.test(obj.value); } } }; // A function for validating all fields within a form. // The form argument should be a reference to a form element // The load argument should be a boolean referring to the fact that // the validation function is being run on page load, versus dynamically function validateForm(form, load) { var valid = true; // Go through all the field elements in form // form.elements is an array of all fields in a form for (var i = 0; i < form.elements.length; i++) { // Hide any error messages, if they're being shown hideErrors(form.elements[i]); // Check to see if the field contains valid contents, or not if (!validateField(form.elements[i], load)) { valid = false; } } // Return false if a field does not have valid contents // true if all fields are valid return valid; } // Validate a single field's contents function validateField(elem, load) { var errors = []; // Go through all the possible validation techniques for (var name in errMsg) { // See if the field has the class specified by the error type var re = new RegExp("(^|\\s)" + name + "(\\s|$)"); // Check to see if the element has the class and that it passes the // validation test if (re.test(elem.className) && !errMsg[name].test(elem, load)) // If it fails the validation, add the error message to list errors.push(errMsg[name].msg); } // Show the error messages, if they exist if (errors.length) showErrors(elem, errors); // Return false if the field fails any of the validation routines return errors.length > 0; } // Hide any validation error messages that are currently shown function hideErrors(elem) { // Find the next element after the current field var next = elem.nextSibling; // If the next element is a ul and has a class of errors if (next && next.nodeName == "UL" && next.className == "errors") // Remove it (which is our means of 'hiding') elem.parenttNode.removeChild(next); } // Show a set of errors messages for a specific field within a form function showErrors(elem, errors) { // Find the next element after the field var next = elem.nextSibling; // If the field isn't one of our special error-holders. if (next && (next.nodeName != "UL" || next.className != "errors")) { // We need to make one instead next = document.createElement("ul"); next.className = "errors"; // and then insert into the correct place in the DOM elem.paretNode.insertBefore(next, elem.nextSibling); } // Now that we have a reference to the error holder UL // We then loop through all the error messages for (var i = 0; i < errors.length; i++) { // Create a new li wrapper for each var li = document.createElement("li"); li.innerHTML = errors[i]; // and insert it into the DOM next.appendChild(li); } } // 提交时进行validation function watchForm(form) { // Watch the form for submission addEvent(form, 'submit', function () { // make sure that the form's contents validate correctly return validateForm(form); }); } // Find the first form on the page var form = document.getElementsByTagName("form")[0]; // and watch for when its submitted, to validate it watchForm(form);
exports.up = async function(knex, Promise) { await knex.schema.hasTable("admin") return await knex.schema.createTable('admin', tbl=>{ tbl.increments('adminId'); tbl.string('admin_username'); tbl.string('admin_password'); }) }; exports.down = function(knex, Promise) { return knex.schema.dropTable('admin'); };
define(['SocialNetView', 'text!templates/profession/listprofession.html'], function(SocialNetView, ProfessionTemplate, ProfessionView) { var professionView = SocialNetView.extend({ myTarget : '', isDraggable:false, tagName : 'li', className : '', initialize: function(options) { this.model.bind('change', this.render, this); }, setupDrop: function(){ var that = this; $('#p-profesions').droppable({ accept: '.profession-li', activeClass:'ui-state-drop-profession', drop: function(event,ui){ var draggable = ui.draggable; var isProfession = draggable.hasClass('profession-li'); if(isProfession){ that.deleteProfession(draggable,'#p-profesions ul'); } } }); }, deleteProfession: function(item,theDropped){ item.css({left:'0px',top:'0px',width:'40%', border:'none', height:'60px'}); item.fadeOut(function() { item.appendTo(theDropped).fadeIn(function(){ item.addClass('shake delete').removeClass('profession-li'); var id = item.attr('id'); var parameter = { _id: id } $.post('/accounts/me/savemyprofession',{ parameter: parameter, collection: 'professions' }); }); }); }, render: function() { if(this.model.get('_id')!=undefined){ this.$el.html(_.template(ProfessionTemplate,{ model:this.model.toJSON() })); if(this.options.isDraggable){ $(this.$el.html()).appendTo(this.options.myTarget).hide().fadeIn('slow'); $('.profession-li').draggable({revert:'invalid'}); this.setupDrop(); //Configurar el Drop }else { $(this.$el.html()).addClass('shake delete').removeClass('profession-li').appendTo(this.options.myTarget).hide().fadeIn('slow'); } } return this; } }); return professionView; });
/** * @file san-xui/x/forms/builtins/Switch.js * @author leeight */ import Switch from '../../components/Switch'; const tagName = 'ui-form-switch'; export default { type: 'switch', tagName, Component: Switch, builder(item, prefix) { return ` <${tagName} s-if="!preview" checked="{=formData.${item.name}=}" /> <span s-else>{{formData.${item.name} === true ? 'ON' : 'OFF'}}</span>`; } };
//数组的解构 let [a, a1, a2] = [1, 2, 3]; console.log('a, a1, a2= ', a, a1, a2); let [b, [b1, b2], b3] = [1, [2.1, 2.2], 3]; console.log('b, b1, b2, b3= ', b, b1, b2, b3); let [c, c1 = 'c1'] = ['c']; //赋值g的默认值为'g' console.log('c, c1= ', c, c1); let [d, d1 = 'd1', d2 = 'd2', d3 = 'd3'] = ['d', undefined, null,]; //ES6 内部使用严格相等运算符(===),判断一个位置是否有值。所以,只有当一个数组成员严格等于undefined,默认值才会生效 console.log('d,d1,d2,d3=', d, d1, d2, d3); let [e, e1 = foo1()] = ['e', undefined]; function foo1() { console.log('赋值的解构默认缺省函数'); return 'default'; } console.log('e, e1=', e, e1); //对象的解构 let { bar, foo } = { foo: 'foo', bar: 'bar' }; //顺序可打乱,识别对象的key console.log('{ bar, foo }:', bar, foo); let { foo2: baz2 } = { foo2: 'aaa', baz2: 'bbb' }; console.log('baz2,foo2=', baz2/* , foo2 */); let obj = { p: [ 'Hello', { y: 'World' } ] }; let { p, p: [x, { y }] } = obj; console.log(`let obj = { p: [ 'Hello', { y: 'World' } ] }; p,x,y`, p, x, y); let arr = [1, 2, 3]; let { 0: first, [arr.length - 1]: last } = arr; console.log(`first:${first},last:${last}`); //字符串的解构赋值 const [s1, s2, s3, s4, s5] = 'hello'; console.log('s1, s2, s3, s4, s5:', s1, s2, s3, s4, s5); //解构赋值时,如果等号右边是数值和布尔值,则会先转为对象。 let { toString: s } = 123; console.log(`s:`, s); console.log(`s===Number.prototype.toString:`, s === Number.prototype.toString); let { toString: s11 } = true; console.log(`s11:`, s11); console.log(`s11===Boolean.prototype.toString:`, s11 === Boolean.prototype.toString); //函数解构 function add([x, y]) { return x + y; } add([1, 2]); // 3 //--------------- function move({ x = 0, y = 0 } = {}) { return [x, y]; } move({ x: 3, y: 8 }); // [3, 8] move({ x: 3 }); // [3, 0] move({}); // [0, 0] move(); // [0, 0] let m1 = [1, undefined, 3]; let m2 = m1.map((x = 'yes') => x); //可以圆括号解析 console.log(`m1:${m1},m2"${m2}`);
import axios from '../../components/interceptor' export default { roleList: async(pid) => { const rest = await axios.get(`/api/organizations/actions/query/${pid}`) return rest.data }, sections: async() => { const rest = await axios.get(`/api/organizations/actions/queryAll`) return rest.data }, create: async(form) => { console.log(form) const rest = await axios.post('/api/organizations', form) return rest.data }, remove: async(id) => { const rest = await axios.delete(`/api/organizations/${id}`) return rest.data }, update: async(editdata) => { const rest = await axios.put('/api/organizations', editdata) return rest.data } }
import colors from './colors'; export default { primary: { main: colors.teal, }, secondary: { main: colors.lightBlue, }, error: { main: colors.red, }, success: { main: colors.green, }, background: { default: colors.backgroundGray, header: colors.white, }, divider: colors.divider, common: { ...colors, }, };
/* Bu problemde bize bir array veriliyor bu array'de birisi hariç her elemandan iki tane oluyor ve bizden tek olanı bulmamız isteniyor. Example 2: Input: [4,1,2,1,2] Output: 4 */ var singleNumber = function(nums) { let x = {}; for(let i = 0; i < nums.length; i++) { x[nums[i]] = x[nums[i]] ? false : true; } for(let key in x) { if(x[key]) return key; } };
const path = require('path'); const fs = require('fs'); const koaCompose = require('koa-compose'); const Router = require('koa-router'); const views = require('koa-views'); const bodyParser = require('koa-bodyparser'); const middlewares = require('../../server/middleware/index'); const main = (app) => { // 中间件 app.use(koaCompose(middlewares)); // 目标引擎 app.use(views(path.resolve(__dirname, '../../'), { map: { html: 'ejs', }, })); // 解析请求报文体body app.use(bodyParser()); // 收集 ./router 文件夹中的所有router, 并且用registerRouter函数注册 const collectRouter = (registerRouter) => { const routerPath = path.resolve(__dirname, '../router'); fs.readdirSync(routerPath).filter(filename => filename.endsWith('.js')).forEach((filename) => { const subRouter = require(`${routerPath}/${filename}`); if (registerRouter) return registerRouter(subRouter, filename); }); }; // 所有path为/api/* 的http请求路由 const apiRouter = new Router({ prefix: '/api' }); // 所有path不为/api/* 的http请求路由,与react客户端路由同步 const pagesRouter = new Router(); collectRouter((subRouter, filename) => { if (filename !== 'pages.js') { apiRouter.use(subRouter.routes()).use(subRouter.allowedMethods()); } else if (filename === 'pages.js') { pagesRouter.use(subRouter.routes()).use(subRouter.allowedMethods()); } }); app.use(apiRouter.routes()).use(apiRouter.allowedMethods()); app.use(pagesRouter.routes()).use(pagesRouter.allowedMethods()); }; module.exports = main;
import React, { useContext } from 'react'; import NotesContext from '../context/notes'; import useMousePosition from '../hooks/useMousePosition'; const Note = ({ note }) => { // Return the notesDispatch action from the current context value // https://reactjs.org/docs/hooks-reference.html#usecontext const { notesDispatch } = useContext(NotesContext); // Create a variable for useMousePosition() hook. // https://reactjs.org/docs/hooks-custom.html#using-a-custom-hook const position = useMousePosition(); // Dispatch REMOVE_NOTE action on button click const removeNote = title => { notesDispatch({ type: 'REMOVE_NOTE', title, }); }; return ( <div> <h3>{note.title}</h3> <p>{note.body}</p> <p> {position.x}, {position.y} </p> <button onClick={() => { removeNote(note.title); }}> X </button> </div> ); }; export { Note as default };
const mongoose = require("mongoose"); const Schema = mongoose.Schema; const ProductRequestSchema = new Schema({ id: String, emp_id: String, quantity: Number, request_type:String }); module.exports = mongoose.model("product_request", ProductRequestSchema);
import React from 'react'; import { Box } from '@sparkpost/matchbox'; function InlineCode(props) { return ( <Box as="code" display="inline-block" fontFamily="monospace" lineHeight="100" fontSize="0.65em" px="100" py="100" bg="gray.200" borderRadius="200" color="magenta.700" > {props.children} </Box> ); } export default InlineCode;
export function camelCaseToDashCase(str) { return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase(); } export function dashCaseToCamelCase(str) { return str.replace(/\W+(.)/g, (x, chr) => chr.toUpperCase()); }
import React from 'react'; import { useParams } from 'react-router'; const RegisterEvent = () => { const {idRegister} = useParams() return ( <div> <h2>This is Deatail Register Event</h2> <h4>{idRegister}</h4> </div> ); }; export default RegisterEvent;
import React from 'react'; import { connect } from 'react-redux'; import { Redirect } from 'react-router-dom'; function mapStateToProps(state) { return { authenticated: state.auth.token !== null }; } const Auth = (props) => { if (props.authenticated !== null) { return props.children; } return ( <Redirect to="/login" /> ); }; export default connect(mapStateToProps)(Auth);
/* * favorItemDescriptionComponent.js * * Copyright (c) 2019 HEB * All rights reserved. * * This software is the confidential and proprietary information * of HEB. */ 'use strict'; /** * Component to support the page that allows users to show product description. * * @author vn70529 * @since 2.31.0 */ (function () { angular.module('productMaintenanceUiApp').component('favorItemDescriptionComponent', { bindings: { currentTab: '<', productMaster: '<', eCommerceViewDetails: '=', changeSpellCheckStatus: '&', isEditText: '=', callbackfunctionAfterSpellCheck: '=' }, require: { parent: '^^eCommerceView' }, // Inline template which is binded to message variable in the component controller templateUrl: 'src/productDetails/product/eCommerceView/favorItemDescription.html', // The controller that handles our component logic controller: favorItemDescriptionController }); favorItemDescriptionController.$inject = ['$timeout', 'ECommerceViewApi', '$scope', '$sce', 'VocabularyService', 'VocabularyApi', 'ngTableParams']; function favorItemDescriptionController($timeout, eCommerceViewApi, $scope, $sce, vocabularyService, vocabularyApi, ngTableParams) { var self = this; /** * The default error message. * * @type {string} */ self.UNKNOWN_ERROR = "An unknown error occurred."; /** * Favor item attribute attribute id. * * @type {number} */ const FAVOR_ITEM_DESCRIPTION_LOG_ATTR_ID = 3989; /** * Edit favor item description physical attribute id. * * @type {number} */ const EDIT_FAVOR_ITEM_DESCRIPTION_PHY_ATTR_ID = 3989; /** * System source id for edit mode. * * @type {number} */ const SRC_SYS_ID_EDIT = 4; /** * Reload eCommerce view key. * @type {string} */ const RELOAD_ECOMMERCE_VIEW = 'reloadECommerceView'; /** * Reset eCommerce view. * @type {string} */ const RESET_ECOMMERCE_VIEW = 'resetECommerceView'; /** * Reload after save popup. * @type {string} */ const RELOAD_AFTER_SAVE_POPUP = 'reloadAfterSavePopup'; /** * Validate warning eCommerce view key. * @type {string} */ const VALIDATE_WARNING = 'validateWarning'; /** * Holds the Editable status for favor item description. * * @type {boolean} */ self.editableFavorItemDescription = false; /** * Define trust as HTML copy from $sce to use in ui. */ self.trustAsHtml = $sce.trustAsHtml; /** * Flag to show type of format favor item description field. * @type {boolean} */ self.isShowingHtml = false; /** * HTML Tab Pressing flag. * @type {boolean} */ self.isPressingHtmlTab = false; /** * Constant order by asc. * * @type {String} */ const ORDER_BY_ASC = "asc"; /** * Constant order by desc. * * @type {String} */ const ORDER_BY_DESC = "desc"; /** * Component will reload the data whenever the item is changed in. */ this.$onChanges = function () { self.isWaitingForResponse = true; self.loadFavorItemDescription(); }; /** * Destroy component. */ this.$onDestroy = function () { self.parent = null; }; /** * Get product description. */ self.loadFavorItemDescription = function () { self.editableFavorItemDescription = false; self.editableFavorItemDescriptionOrg = false; eCommerceViewApi.findFavorItemDescription( { productId: self.productMaster.prodId, upc: self.productMaster.productPrimaryScanCodeId, }, //success case function (results) { if(results.content === null){ results.content = ""; } self.eCommerceViewDetails.favorItemDescription = results; self.eCommerceViewDetails.favorItemDescriptionOrg = angular.copy(self.eCommerceViewDetails.favorItemDescription); if(self.eCommerceViewDetails.favorItemDescription != null) { self.editableFavorItemDescription = self.isEditMode(); self.editableFavorItemDescriptionOrg = angular.copy(self.editableFavorItemDescription); //validate spell check of favor Item Description. self.validateFavorItemDescriptionTextForView(); } self.isWaitingForResponse = false; }, self.handleError); }; /** * Callback for when the backend returns an error. * * @param error The error from the back end. */ self.handleError = function (error) { self.isWaitingForResponse = false; self.error = self.getErrorMessage(error); }; /** * Returns error message. * * @param error * @returns {string} */ self.getErrorMessage = function (error) { if (error && error.data) { if (error.data.message) { return error.data.message; } return error.data.error; } return self.UNKNOWN_ERROR; }; /** * Check edit status or not. * * @returns {boolean} */ self.isEditMode = function () { return (self.eCommerceViewDetails.favorItemDescription.sourceSystemId === SRC_SYS_ID_EDIT && self.eCommerceViewDetails.favorItemDescription.physicalAttributeId === EDIT_FAVOR_ITEM_DESCRIPTION_PHY_ATTR_ID); }; /** * Show edit mode of favor item description. */ self.showEditText = function () { if (!self.editableFavorItemDescription) { self.editableFavorItemDescription = true; vocabularyService.createSuggestionMenuContext($scope, $scope.suggestionsOrg); } }; /** * Show popup to edit description source. */ self.showDescriptionEditSource = function () { self.isEditText = self.editableFavorItemDescription; self.parent.getECommerceViewDataSource(self.productMaster.prodId, self.productMaster.productPrimaryScanCodeId, FAVOR_ITEM_DESCRIPTION_LOG_ATTR_ID, 0, 'Favor Item Description', null); }; /** * Disable validate spell check of Romance Copy when open suggestions popup. */ $scope.$on('context-menu-opened', function (event, args) { self.openSuggestionsPopup = true; }); /** * Enable validate spell check of Romance Copy when close suggestions popup. */ $scope.$on('context-menu-closed', function (event, args) { self.openSuggestionsPopup = false; }); /** * Validate text for view mode. It will call after loaded favor item description. */ self.validateFavorItemDescriptionTextForView = function () { if (!self.isEmpty(self.eCommerceViewDetails.favorItemDescription.content)) { self.isWaitingForCheckSpellingResponse = true; vocabularyService.validateRomancyTextForView(self.eCommerceViewDetails.favorItemDescription.content, function (newText, suggestions) { if (self.editableFavorItemDescription) {//load data of edit mode // Use $timeout and space char to clear cache on layout. self.eCommerceViewDetails.favorItemDescription.content = self.eCommerceViewDetails.favorItemDescription.content + ' '; $timeout(function () { self.eCommerceViewDetails.favorItemDescription.content = angular.copy(newText);//color text self.favorItemDescriptionContent = angular.copy(newText); self.favorItemDescriptionContentOrg = angular.copy(newText); $scope.suggestionsOrg = angular.copy(suggestions); $timeout(function () { vocabularyService.createSuggestionMenuContext($scope, suggestions); self.isWaitingForCheckSpellingResponse = false; }, 1000); }, 100); } else {//load data of view mode self.favorItemDescriptionContent = angular.copy(newText); self.favorItemDescriptionContentOrg = angular.copy(newText); self.eCommerceViewDetails.favorItemDescription.content = angular.copy(newText);//color text $scope.suggestionsOrg = angular.copy(suggestions); self.isWaitingForCheckSpellingResponse = false; } }); } else { self.favorItemDescriptionContent = ''; self.favorItemDescriptionContentOrg = ''; } }; /** * Validate text for edit mode of favor item description. */ self.validateFavorItemDescriptionTextForEdit = function () { if (self.isPressingHtmlTab) { self.isPressingHtmlTab = false; return; } if (!self.openSuggestionsPopup) {//avoid conflict with suggestion popup if (!self.isEmpty(self.eCommerceViewDetails.favorItemDescription.content)) { var callbackFunction = self.getAfterSpellCheckCallback(); self.isWaitingForCheckSpellingResponse = true; self.changeSpellCheckStatus({status: true}); var contentHtml = $('#favorItemDescriptionDiv').html(); contentHtml = contentHtml.split("<br>").join("<div>"); contentHtml = contentHtml.split("</p>").join("<div>"); var contentHtmlArray = contentHtml.split("<div>"); var contentNoneHtml = ''; if (contentHtmlArray.length > 1) { for (var i = 0; i < contentHtmlArray.length; i++) { if (contentHtmlArray[i] != null && contentHtmlArray[i] != '') { contentNoneHtml = contentNoneHtml.concat(self.convertHtmlToPlaintext(contentHtmlArray[i])); if (i < (contentHtmlArray.length - 1)) { contentNoneHtml = contentNoneHtml.concat(" <br> "); } } } self.eCommerceViewDetails.favorItemDescription.content = contentNoneHtml.split("&nbsp;").join(" "); } var response = vocabularyApi.validateRomanceCopySpellCheck({textToValidate: self.eCommerceViewDetails.favorItemDescription.content}); response.$promise.then( function (result) { // Use $timeout and space char to clear cache on layout. self.eCommerceViewDetails.favorItemDescription.content = self.eCommerceViewDetails.favorItemDescription.content + ' '; $timeout(function () { self.eCommerceViewDetails.favorItemDescription.content = angular.copy(result.validatedText);//normal text vocabularyService.validateRomancyTextForView(self.eCommerceViewDetails.favorItemDescription.content, function (newText, suggestions) { self.favorItemDescriptionContent = angular.copy(newText); self.eCommerceViewDetails.favorItemDescription.content = angular.copy(newText);//color text $scope.suggestionsOrg = angular.copy(suggestions); $timeout(function () { vocabularyService.createSuggestionMenuContext($scope, suggestions); }, 1000); self.isWaitingForCheckSpellingResponse = false; self.changeSpellCheckStatus({status: false}); $timeout(function () { // Save or publish if event occurs from save or publish button. self.processAfterSpellCheck(callbackFunction); }, 500); }); }, 100); }, function (error) { } ); } } }; /** * Check empty value. * * @param val * @returns {boolean} */ self.isEmpty = function (val) { if (val == null || val == undefined || val.trim().length == 0) { return true; } return false; }; /** * Reload ECommerceView. */ $scope.$on(RELOAD_ECOMMERCE_VIEW, function () { self.$onChanges(); }); /** * Reset eCommerce view. */ $scope.$on(RESET_ECOMMERCE_VIEW, function () { self.isShowingHtml = false; self.editableFavorItemDescription = angular.copy(self.editableFavorItemDescriptionOrg); self.favorItemDescriptionContent = angular.copy(self.favorItemDescriptionContentOrg); self.eCommerceViewDetails.favorItemDescription.content = angular.copy(self.favorItemDescriptionContentOrg); if (self.editableFavorItemDescription) {//edit mode $timeout(function () { vocabularyService.createSuggestionMenuContext($scope, $scope.suggestionsOrg); }, 1000); } }); /** * Reload after save popup. */ $scope.$on(RELOAD_AFTER_SAVE_POPUP, function (event, attributeId, status) { if (attributeId === FAVOR_ITEM_DESCRIPTION_LOG_ATTR_ID) { self.editableFavorItemDescription = false; if (status === true) { self.$onChanges(); } else { self.isWaitingForResponse = true; } } }); /** * Init data eCommerce View Audit. */ self.initECommerceViewAuditTable = function () { $scope.filter = { attributeName: '', }; $scope.sorting = { changedOn: ORDER_BY_DESC }; $scope.eCommerceViewAuditTableParams = new ngTableParams({ page: 1, count: 10, filter: $scope.filter, sorting: $scope.sorting }, { counts: [], data: self.eCommerceViewAudits }); }; /** * Change sort orientation. */ self.changeSortOrientation = function () { if ($scope.sorting.changedOn === ORDER_BY_DESC) { $scope.sorting.changedOn = ORDER_BY_ASC; } else { $scope.sorting.changedOn = ORDER_BY_DESC; } }; /** * Remove all tag html in text * @param text the text to convert. * @returns the string after converted. */ self.convertHtmlToPlaintext = function (text) { return text ? String(text).replace(/<[^>]+>/gm, '') : ''; }; /** * Returns the function to do (save or publish) after spell check success. * @return callback function */ self.getAfterSpellCheckCallback = function () { var callbackFunction = self.callbackfunctionAfterSpellCheck; self.callbackfunctionAfterSpellCheck = null; return callbackFunction; }; /** * Call the function for save or publish after spell check is success. * @param callback */ self.processAfterSpellCheck = function (callback) { if (callback != null && callback !== undefined) { callback(); } }; /** * Set type of text for favor item description field * @param isShowingHtml true show it or hide it. */ self.showFormatDescriptionField = function (isShowingHtml) { self.isShowingHtml = isShowingHtml; self.eCommerceViewDetails.favorItemDescription.htmlSave = isShowingHtml; self.isPressingHtmlTab = false; }; /** * Prepare callback function for after spell check is success. */ self.onHtmlTabClicked = function () { self.isPressingHtmlTab = true; }; } })();
var inquirer = require('inquirer') inquirer.registerPrompt('multiDir', require('../src/inquirer-extensions').multiDir) inquirer.prompt([{ type: 'multiDir', name: 'multiDir', message: 'Which directories do you want to include', basePath: './' }], function (answers) { console.log(JSON.stringify(answers, null, ' ')) })
var ac, accordions = { settings: { accItem: $('.acc-item'), accContent: $('.acc-item .acc-content'), title: $('.acc-item .title') }, init: function() { ac = this.settings; this.bindUIActions(); // Optional - Expose scoped vars to global $. Use in console with $.expose $.expose.ac = ac; $.expose.accordions = accordions; console.log('accordions loaded!'); if(ac.accContent.length > 0){ ac.accContent.addClass('hide'); } }, bindUIActions: function() { ac.title.on('click', function() { $(this).closest('.acc-item').find('.acc-content').slideToggle( '3000', function() { // Animation complete. }); }); } }; var navac, navAccordions = { settings: { accItem: $('.nav-acc-item, #mobile-menu .menu-item-has-children'), accContent: $('.nav-acc-item .nav-acc-content, #mobile-menu .menu-item-has-children .sub-menu'), title: $('.nav-acc-item .title, #mobile-menu .menu-item-has-children > a') }, init: function() { navac = this.settings; this.bindUIActions(); // Optional - Expose scoped vars to global $. Use in console with $.expose $.expose.navac = navac; $.expose.navAccordions = navAccordions; console.log('nav accordions loaded!'); }, bindUIActions: function() { navac.title.on('click', function(evt) { evt.preventDefault(); // close all navAccordions navac.title.not(this).closest('.nav-acc-item').find('.nav-acc-content').slideUp( '3000', function() { // Animation complete. }); navac.title.not(this).closest('.menu-item-has-children').find('.sub-menu').slideUp( '3000', function() { // Animation complete. }); // once all are closed then toggle the clicked item $(this).closest('.nav-acc-item').find('.nav-acc-content').slideToggle( '3000', function() { // Animation complete. }); $(this).closest('.menu-item-has-children').find('.sub-menu').slideToggle( '3000', function() { // Animation complete. }); }); } }; var side, sidebarNav = { settings: { navEls: $('.sidebar-nav-item'), contentEls: $('.sidebar-content-item'), dropdownTitle: $('.dropdown-item .title'), dropdownContent: $('.dropdown-content') }, init: function() { side = this.settings; this.bindUIActions(); // Optional - Expose scoped vars to global $. Use in console with $.expose $.expose.side = side; $.expose.sidebarNav = sidebarNav; // side.dropdownContent.addClass('hide'); console.log('Sidebar Loaded!'); }, bindUIActions: function() { var windowSize = $(window).width(); // Get width of window on load or resize $(window).on('load resize', function() { windowSize = $(window).width(); // side.dropdownTitle.on('click', function() { // if ( windowSize >= 769 ) { // // do nothing // } else { // $(this).closest('.dropdown-item').find('.dropdown-content').slideToggle( '3000', function() { // // Animation complete. // }); // } // }); if(side.dropdownContent.length > 0){ if ( windowSize >= 769 ) { document.querySelector('.dropdown-content').style.display = "block"; } else { document.querySelector('.dropdown-content').style.display = "none"; } } }); // Dropdown toggle side.dropdownTitle.on('click', function () { if ( windowSize >= 769 ) { // do nothing } else { $(this).closest('.dropdown-item').find('.dropdown-content').slideToggle( '3000', function() { // Animation complete. }); } }); // side.navEls.on('click', function () { var parentElement = sidebarNav.getClosest(this, '.content'); // Remove active classes var navElements = parentElement.querySelectorAll('.sidebar-nav-item'); var contentElements = parentElement.querySelectorAll('.sidebar-content-item'); for ( var i = 0; i < navElements.length; i++ ) { navElements[i].classList.remove('active'); contentElements[i].classList.remove('active'); } // Add active classes to nav item clicked and corresponding content this.classList.add('active'); var selectedItem = this.dataset.sidebar - 1; contentElements[selectedItem].classList.add('active'); }); }, getClosest: function (elem, selector) { // Element.matches() polyfill if (!Element.prototype.matches) { Element.prototype.matches = Element.prototype.matchesSelector || Element.prototype.mozMatchesSelector || Element.prototype.msMatchesSelector || Element.prototype.oMatchesSelector || Element.prototype.webkitMatchesSelector || function(s) { var matches = (this.document || this.ownerDocument).querySelectorAll(s), i = matches.length; while (--i >= 0 && matches.item(i) !== this) {} return i > -1; }; } // Get the closest matching element for ( ; elem && elem !== document; elem = elem.parentNode ) { if ( elem.matches( selector ) ) return elem; } return null; } };
var mongoose = require('mongoose'); // configure mongoose's promise promise we know mongoose.Promise = global.Promise; mongoose.connect('mongodb://localhost:27017/TodoApp'); // ES6 syntax mongoose.exports = {mongoose}; // old syntax // mongoose.exports = { // mongoose : mongoose // };
/** * CartController * * @description :: Server-side actions for handling incoming requests. * @help :: See https://sailsjs.com/docs/concepts/actions */ module.exports = { checkcart : function(req,res,next){ Cart.findOne({user_id : req.param('user_id')}).where({id_game : req.param('id_game')}).exec(function(err, usercart){ if(usercart){ console.log('itemfound') res.redirect('/'); } else{ console.log('item not found') Cart.create(req.body).exec(function(err, newcart){ if(err){ return res.serverError(err); } else{ console.log('cart added') res.redirect('/'); } }) } }) }, checkcartsearch : function(req,res,next){ Cart.findOne({user_id : req.param('user_id')}).where({id_game : req.param('id_game')}).exec(function(err, usercart){ if(usercart){ var current_url = req.param('current_url'); console.log('itemfound') res.redirect(current_url); console.log(current_url) } else{ var current_url = req.param('current_url'); console.log('item not found') Cart.create(req.body).exec(function(err, newcart){ if(err){ return res.serverError(err); } else{ console.log('cart added') res.redirect(current_url); } }) } }) }, remove : function(req,res,next){ Cart.destroy({id : req.param('id')}).exec(function(err, deleteitem){ if(err){ return res.serverError(err); } else{ var geturl = req.param('current_url'); console.log(geturl) console.log('cart deleted') res.redirect('/'); } }) }, removesearch : function(req,res,next){ Cart.destroy({id : req.param('id')}).exec(function(err, deleteitem){ if(err){ return res.serverError(err); } else{ var current_url = req.param('current_url') console.log('cart deleted') res.redirect(current_url); } }) }, checkout: function(req,res,next){ Cart.find({user_id : req.session.User.id}).exec(function(err,updatecart){ if(err){ return res.serverError(err); } else{ User.findOne({id:req.session.User.id}).exec(function(err,user){ res.view('user/checkout',{ status : 'OK', title : 'Check Out', updatecart : updatecart, user : user, }) }) } }) }, getCartmobile : function(req,res){ User.findOne({email : req.param('email')}).exec(function(err,user){ if(err){ return res.serverError(err) } else{ Cart.find({user_id : user.id}).exec(function(err,cart){ if(err){ return res.serverError(err); } else{ res.json(cart) } }) } }) }, addcartmobile : function(req,res){ Cart.create(req.allParams()).exec(function(err, newcart){ if(err){ return res.serverError(err); } else{ console.log('cart added') res.json(newcart) } }) }, checkcartmobile : function(req,res){ User.findOne({email : req.param('email')}).exec(function(err,user){ Cart.findOne({user_id : user.id}).where({id_game : req.param('id_game')}).exec(function(err,added){ if(!added){ res.status(204); res.send('game not in cart'); } else{ res.json(added); } }) }) }, checkowngamemobile : function(req,res){ Owngame.findOne({user_id : req.param('user_id')}).where({game_id : req.param('game_id')}).exec(function(err, owned){ console.log(owned) if(!owned){ res.status(204); res.send('game already owned'); } else{ res.json(owned) } }) }, removecartmobile : function(req,res,next){ Cart.destroy({id : req.param('id')}).exec(function(err, deleteitem){ if(err){ return res.serverError(err); } else{ res.json(deleteitem) } }) }, };
var FacebookTokenStrategy = require("passport-facebook-token"); var UserRecord = require("../models/userRecord"); var User = require("../models/user"); var configAuth = require("./auth"); module.exports = function(passport){ passport.use(new FacebookTokenStrategy({ clientID: configAuth.facebookAuth.clientID, clientSecret: configAuth.facebookAuth.clientSecret, }, function(accessToken, refreshToken, profile, done) { // ADDING status code here screws everythign up User.findOne({'facebook.id': profile.id}, function(err, user){ if(err) { //res.status(500); return done(err); } if(user) { //res.status(200); user.facebook.token = accessToken; user.save(function() { return done(null, user); }) } else { var newUser = new User(); newUser.facebook.id = profile.id; newUser.facebook.token = accessToken; newUser.facebook.firstName = profile.name.givenName; newUser.facebook.lastName = profile.name.familyName; newUser.facebook.email = profile.displayName; // BUGGGGG newUser.points = 10; var date= new Date(); var currentTime = date.toUTCString(); newUser.time = currentTime; newUser.save(function(err){ if(err){ //res.status(500); throw err; } else { var newUserId = newUser._id.toString(); var newUserFbId = newUser.facebook.id.toString(); var newUserRecord = { userId: newUserId, userFbId: newUserFbId, likeRecord: [], spreadRecord: [], commentRecord: [], blockedUsers: [] }; UserRecord.create(newUserRecord, function(err, newRecordCreation) { if(err) { res.json({error: "Creation failed."}); // // // NEED TO DO SOMETHING HERE TO AVOID ANY PROBLEMS // // } else { return done(null, newUser); } }); } }) } }); }) ); }
const mongoose = require('mongoose'); const {Schema} = mongoose; const PurchaseSchema = new Schema({ proveedor: String, ruc: String, numero: String, productos: [{type: Schema.ObjectId, ref: 'Product'}, { cantidad: Number, precio: Number }], fecha: Date }); module.exports = mongoose.model('Purchase', PurchaseSchema)
import { ROL_ADMIN, ROL_PACIENTE, ROL_PROFESIONAL } from "../constants.js"; import { getPacientebyUserId } from "../services/pacienteService.js"; import { getProfesionalbyUserId } from "../services/profesionalService.js"; export const session = localStorage.getItem("session") ? JSON.parse(localStorage.getItem("session")) : null; export const logOut = () => { localStorage.removeItem("session"); window.location.href = window.origin; }; export const sessionUserMenu = () => { $(function () { $('[data-toggle="tooltip"]').tooltip(); }); const sessionNav = document.getElementById("sessionNav"); sessionNav.innerHTML = ` ${session.usuario.rolId == ROL_PROFESIONAL ? especialidadSelect() : ""} <li class="nav-item border-right px-2"> <span class="user-info align-middle pr-1"> <span class="user-fullname text-capitalize"> ${session.usuario.nombres} ${session.usuario.apellidos} </span> <span class="user-role text-muted small"> ${rolString(session.usuario.rolId)} </span> </span> <span class="user-av align-middle"> <i class="fas fa-user-circle text-muted"></i> </span> </li> <li class="nav-item"> <a class="nav-link text-secondary" href="/usuario/logout" data-toggle="tooltip" data-placement="bottom" title="Cerrar sesión"><i class="fas fa-sign-out-alt"></i></a> </li> `; if (session.usuario.rolId == ROL_PROFESIONAL) { let especialidadSelectDOM = document.getElementById("especialidadSelect"); if (especialidadSelectDOM) { especialidadSelectDOM.addEventListener("change", (event) => { let found = session.profesional.especialidades.find( (element) => element.especialidadId == event.target.value ); session.especialidadSelected = found; localStorage.setItem("session", JSON.stringify(session)); window.location.reload(); }); } } }; const especialidadSelect = () => { let especialidades = session.profesional.especialidades.map( (e) => `<option value="${e.especialidadId}">${e.tipoEspecialidad}</option>` ); return `<li class="nav-item px-2"> <small class="small text-muted font-weight-light" style="font-size: 0.7em">Especialidad:</small> <select id="especialidadSelect" class="custom-select custom-select-sm font-weight-light" style="font-size: 0.7em; width: 100px"> <option selected>${ session.especialidadSelected != null ? session.especialidadSelected.tipoEspecialidad : "-" }</option> ${especialidades} </select> </li>`; }; const rolString = (num) => { switch (num) { case ROL_ADMIN: return "Administrador"; case ROL_PROFESIONAL: return "Profesional"; case ROL_PACIENTE: return "Paciente"; } }; export const loadPacienteIntoSession = async () => { let paciente = await getPacientebyUserId(session.usuario.id); if (paciente) { // cargo datos en la respuesta session.paciente = paciente; localStorage.setItem("session", JSON.stringify(session)); } else { // no existe, redirecciono a que complete los datos. localStorage.setItem("session", JSON.stringify(sessionLogIn)); window.location.assign("/paciente/registrar"); } }; export const loadInfoUserIntoSession = async () => { // CASE PACIENTE if (session.usuario.rolId == ROL_PACIENTE && !session.paciente) { let paciente = await getPacientebyUserId(session.usuario.id); if (paciente) { // cargo datos en la respuesta session.paciente = paciente; localStorage.setItem("session", JSON.stringify(session)); window.location.reload(); } } // CASE PROFESIONAL if (session.usuario.rolId == ROL_PROFESIONAL && !session.profesional) { let profesional = await getProfesionalbyUserId(session.usuario.id); if (profesional) { session.profesional = profesional; if (session.profesional.especialidades.length > 0) { session.especialidadSelected = session.profesional.especialidades[0]; } localStorage.setItem("session", JSON.stringify(session)); window.location.reload(); } } };
/** * Booking Info Widget */ import React, { Component } from 'react'; import { Card, CardTitle } from 'reactstrap'; import List from '@material-ui/core/List'; import ListItem from '@material-ui/core/ListItem'; import Button from '@material-ui/core/Button'; // intl messages import IntlMessages from 'Util/IntlMessages'; export default class BookingInfo extends Component { render() { return ( <Card className="rct-block"> <List className="p-0 fs-14"> <ListItem className="d-flex justify-content-between border-bottom align-items-center p-15"> <span> <i className="material-icons mr-25 fs-14 text-primary">add_to_photos</i> <IntlMessages id="widgets.booking" /> </span> <span>1450</span> </ListItem> <ListItem className="d-flex justify-content-between align-items-center border-bottom p-15"> <span> <i className="material-icons mr-25 text-success fs-14">check_box</i> <IntlMessages id="widgets.confirmed" /> </span> <span>1000</span> </ListItem> <ListItem className="d-flex justify-content-between align-items-center p-15"> <span> <i className="material-icons mr-25 text-danger fs-14">access_time</i> <IntlMessages id="widgets.pending" /> </span> <span>450</span> </ListItem> </List> </Card> ); } }
import axios from "axios"; import { baseURL } from "../utils"; import { PRODUCT_FILTERS_RESPONSE, PRODUCT_LIST_FAIL, PRODUCT_LIST_REQUEST, PRODUCT_LIST_SUCCESS, PRODUCT_PAGINATION_COUNT, PRODUCT_PAGINATION_PAGE, PRODUCT_PAGINATION_PAGES, } from "../constants/productConstants"; export const listProducts = ({ page, filterCategory, filterType, filterBrand, filterRating, filterPrice, filterName, orderBy, }) => async (dispatch, getState) => { dispatch({ type: PRODUCT_LIST_REQUEST, }); let url = `${baseURL}/products?`; if (page >= 2) { url += `&pageNumber=${page}`; } if (filterName) { url += `&name=${filterName}`; } if (orderBy) { url += `&order=${orderBy}`; } if (filterCategory.length > 0) { filterCategory.forEach((category) => (url += `&category=${category}`)); } if (filterType.length > 0) { filterType.forEach((type) => (url += `&type=${type}`)); } if (filterBrand.length > 0) { filterBrand.forEach((brand) => (url += `&brand=${brand}`)); } if (filterRating > 0) { url += `&rating=${filterRating}`; } if (filterPrice.min || filterPrice.max) { for (const key in filterPrice) { url += `&${key}=${filterPrice[key]}`; } } try { const { data } = await axios.get(url); dispatch({ type: PRODUCT_LIST_SUCCESS, payload: data.productList.products, }); dispatch({ type: PRODUCT_PAGINATION_PAGE, payload: data.productList.page, }); dispatch({ type: PRODUCT_PAGINATION_PAGES, payload: data.productList.pages, }); dispatch({ type: PRODUCT_PAGINATION_COUNT, payload: data.productList.totalRows, }); dispatch({ type: PRODUCT_FILTERS_RESPONSE, payload: data.filters }); } catch (error) { dispatch({ type: PRODUCT_LIST_FAIL, payload: error.message }); } };
export { default as Header } from './Header'; export {default as UserPosts} from './UserPosts'; export {default as UserTodos} from './UserTodos';
import { PieceFactory } from './modules/factory'; import { searchNextMoves } from './modules/searchMoves' import { checkDir, getPieceColor, getPieceName, getEnemyColor, handlePinLine, handleStalemate } from './modules/helpers' import { searchNextMovesForBishop, searchNextMovesForRook } from './modules/searchMoves'; let board = document.querySelector('.board'); for (let i = 0; i < 8; i++) { for (let j = 0; j < 8; j++) { let square = document.createElement('div'); square.classList.add('square'); board.appendChild(square); } } let y = 8; let x = 1; let squares = document.querySelectorAll('.square') let checker = false; for (let i = 0; i < squares.length; i++) { if (x > 8) { y-- x = 1 checker = !checker } squares[i].setAttribute('posY', y) squares[i].setAttribute('posX', x) if (checker === false) { squares[i].style.backgroundColor = '#f1f1f1' checker = !checker } else { squares[i].style.backgroundColor = '#85aa53' checker = !checker } x++ } // draw pieces login starts here let factory = new PieceFactory(); const blackPieces = [ factory.create('pawn', 'black'), factory.create('rook', 'black'), factory.create('horse', 'black'), factory.create('bishop', 'black'), factory.create('queen', 'black'), factory.create('king', 'black') ] const drawPieces = (pieces) => { let color = pieces[0].color; pieces.forEach(piece => { piece.startPos.forEach(pos => { let node = document.querySelector(`[posX="${pos.x}"][posY="${pos.y}"]`); node.setAttribute('piece', `${color}-${piece.name}`); node.classList.add(`${color}-${piece.name}`); if (piece.name === 'pawn') { node.setAttribute('firstMove', true) } if (piece.name === 'king') { node.setAttribute('is-checked', 0) } }) }) } function addPiecesForBlack(blackPieces) { drawPieces(blackPieces) } addPiecesForBlack(blackPieces); const whitePieces = [ factory.create('pawn', 'white'), factory.create('rook', 'white'), factory.create('horse', 'white'), factory.create('bishop', 'white'), factory.create('queen', 'white'), factory.create('king', 'white'), ] function addPiecesForWhite(whitePieces) { drawPieces(whitePieces) } addPiecesForWhite(whitePieces) // draw pieces logic ends here const checkInfo = { checkLines: [], saveMoves: [], pinLine: [], pinedPiece: null, isCheckmate: false, isStalemate: false, kingInCheck: null, } let currentTurnText = document.querySelector('.current-turn'); let history = []; let CURRENT_TURN = 'white'; currentTurnText.innerHTML = `CURRENT TURN: ${CURRENT_TURN}`; const movePiece = (history) => { let prev = history[0]; let next = history[1]; let color = getPieceColor(prev) next.classList.remove(next.getAttribute('piece')); next.removeAttribute('piece'); if (prev.getAttribute('firstMove' !== null)) { prev.removeAttribute('firstMove') } if (getPieceName(prev) === 'pawn' && (+next.getAttribute('posY') === 1 || +next.getAttribute('posY') === 8)) { next.classList.add(`${color}-queen`) next.setAttribute('piece', `${color}-queen`) } else { next.classList.add(prev.getAttribute('piece')) next.setAttribute('piece', prev.getAttribute('piece')) } prev.classList.remove(prev.getAttribute('piece'), 'current') prev.removeAttribute('piece') } const filterMoves = (piece) => { let checkedList = []; let enemyColor = getEnemyColor(piece); //diagonal pins if (getPieceName(piece.current) === 'bishop' || getPieceName(piece.current) === 'queen') { handlePinLine(piece, searchNextMovesForBishop, checkInfo) } // vertical and horizontal pins if (getPieceName(piece.current) === 'rook' || getPieceName(piece.current) === 'queen') { handlePinLine(piece, searchNextMovesForRook, checkInfo) } piece.nextMoves.flat().forEach(move => { if (move) { if (getPieceName(piece.current) === 'king' && !move.getAttribute(`${enemyColor}-attack`) && (move.getAttribute('piece') !== null && getPieceColor(move) !== piece.color || move.getAttribute('piece') === null)) { return checkedList.push(move) } if (move.getAttribute('piece') !== null && getPieceName(move) === 'king' && getPieceColor(move) !== piece.color) { piece.nextMoves.forEach(moves => { if (moves.length > 0) { moves.forEach(move => { if (move && move.classList.value.includes(`${enemyColor}-king`)) { let isContainSameLine = checkInfo.checkLines.some(line => getPieceName(line[0]) === getPieceName(piece.current)) !isContainSameLine && checkInfo.checkLines.push([piece.current, ...moves.slice(0, moves.indexOf(move) + 1)]); checkInfo.kingInCheck = enemyColor; } }) } }) move.setAttribute('is-checked', 1), move.classList.add('red') return } if (move.getAttribute('piece') === null && getPieceName(piece.current) !== 'king') { return checkedList.push(move); } if (move.getAttribute('piece') !== null && getPieceColor(move) !== piece.color && getPieceName(move) !== 'king' && getPieceName(piece.current) !== 'king') { return checkedList.push(move); } } }) if (checkInfo.pinedPiece === piece.current) { checkedList = [] piece.nextMoves.flat().forEach(move => { if (!checkInfo.kingInCheck) { checkInfo.pinLine.forEach(pinedSquare => { if (pinedSquare === move) { checkedList.push(move) } }) } }) return checkedList } if (checkInfo.checkLines.length === 1 && checkInfo.kingInCheck) { checkedList.forEach(move => { checkInfo.checkLines.forEach(line => { line.forEach(square => { if (piece.color === checkInfo.kingInCheck && square === move && getPieceName(piece.current) !== 'king') { checkInfo.saveMoves.push(move); } else if (piece.color === checkInfo.kingInCheck && getPieceName(piece.current) === 'king') { checkInfo.saveMoves.push(move) } }) }) }) return checkInfo.saveMoves; } else if (checkInfo.checkLines.length === 2 && checkInfo.kingInCheck) { checkedList.forEach(move => { if (getPieceName(piece.current) === 'king' && piece.color === checkInfo.kingInCheck) { checkInfo.saveMoves.push(move); } }) return checkInfo.saveMoves } return checkedList; } const checkForDiagonalAttacks = (piece, color) => { let currentPiece = piece.current; let dir = checkDir(currentPiece); let enemyColor = getEnemyColor(piece); let diagonalAttacks = [document.querySelector(`[posY="${+currentPiece.getAttribute('posY') - dir}"][posX="${+currentPiece.getAttribute('posX') - 1}"]`), document.querySelector(`[posY="${+currentPiece.getAttribute('posY') - dir}"][posX="${+currentPiece.getAttribute('posX') + 1}"]`)] diagonalAttacks.forEach(attack => { if (attack) { attack.setAttribute(`${color}-attack`, true) if (attack.getAttribute('piece') && getPieceName(attack) === 'king' && getPieceColor(attack) !== color) { attack.setAttribute('is-checked', 1); attack.classList.add('red'); checkInfo.kingInCheck = enemyColor; let test = checkInfo.checkLines.some(line => getPieceName(line[line.length - 1]) === getPieceName(piece.current)) !test && checkInfo.checkLines.push([piece.current]); } } }) piece.nextMoves = diagonalAttacks.filter(attack => attack && attack.getAttribute('piece') !== null && getPieceColor(attack) !== color && getPieceName(attack) !== 'king'); return piece; } const movesForAllPieces = (squares) => { let allPieces = []; squares.forEach(square => square.getAttribute('piece') !== null ? ( allPieces.push({ current: square, nextMoves: searchNextMoves(square), color: getPieceColor(square) }) ) : null) allPieces.forEach(piece => getPieceName(piece.current) !== 'pawn' && piece.nextMoves.flat().forEach(move => move && move.setAttribute(`${piece.color}-attack`, true))) let restarted = false; for (let i = 0; i < allPieces.length; i++) { if (!restarted && checkInfo.kingInCheck) { i = 0; restarted = true } checkInfo.saveMoves = []; let piece = allPieces[i]; if (piece && getPieceName(piece.current) === 'pawn') { piece.nextMoves = [...filterMoves(piece), ...filterMoves(checkForDiagonalAttacks(piece, piece.color))] } else { let filtredMoves = filterMoves(piece); piece.nextMoves = filtredMoves } } !allPieces.find(piece => piece.nextMoves.length) ? checkInfo.isCheckmate = true : null; handleStalemate(allPieces, checkInfo, CURRENT_TURN, 'black'); handleStalemate(allPieces, checkInfo, CURRENT_TURN, 'white'); if (checkInfo.isStalemate) return setTimeout(() => alert('stalemate sorry')) if (checkInfo.isCheckmate) return setTimeout(() => alert('checkmate sorry')) return allPieces; } const triggerPiece = (e, squares) => { let possibleMoves = []; let currentPiece = e.target; currentPiece !== null && currentPiece.getAttribute('piece') ? currentPiece.classList.add('current') : null; if (history.length < 2) { history.push(currentPiece); } if (history.length === 2) { if (history[1].classList.contains('next')) { movePiece(history) CURRENT_TURN = CURRENT_TURN === 'white' ? 'black' : 'white'; currentTurnText.innerHTML = `CURRENT TURN: ${CURRENT_TURN}`; } history = []; currentPiece = null; checkInfo.checkLines = []; checkInfo.pinLine = []; checkInfo.pinedPiece = null; checkInfo.kingInCheck = null; squares.forEach(square => { square.removeAttribute('white-attack') square.removeAttribute('black-attack') square.removeAttribute('is-checked') square.classList.remove('red', 'next', 'current') }) } let allMoves = movesForAllPieces(squares) allMoves.length > 0 && allMoves.forEach(square => { if (square.current === currentPiece) { possibleMoves.push(...square.nextMoves); } }) possibleMoves.forEach(move => { move !== null && getPieceColor(currentPiece) === CURRENT_TURN ? move.classList.add('next') : null }) } squares.forEach(square => { square.addEventListener('click', (e) => { triggerPiece(e, squares) }) });
"use strict" var singleGamesStarted = 0; var ga = ga || function () {}; var duoGamesStarted = 0; var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); ctx.fillStyle = 'rgb(0, 0, 0)'; ctx.fillRect(0, 0, 800, 400); function Pong (ctx) { var lastUpdate = Date.now(), bol, bol2, player1, player2, showinstructions, pong = this, state = 0, paused = false; document.addEventListener('keypress', function (event) { var pressedKey = event.keyCode || event.which || event.charCode; console.log(pressedKey); if (!this.levens) { if (pressedKey === 49 || pressedKey === 38) { this.startpong1(); event.preventDefault(); } else if (pressedKey === 50 || pressedKey === 233) { this.startpong2(); event.preventDefault(); } else if (pressedKey === 109) { state = 0; } } if (pressedKey === 112) { paused = !paused; } }.bind(this), false); this.keydown = function (event) { var pressedKey = event.keyCode || event.which || event.charCode; if (pressedKey === 73) { showinstructions = true; } }; this.keyup = function (event) { var pressedKey = event.keyCode || event.which || event.charCode; if (pressedKey === 73) { showinstructions = false; } }; document.addEventListener("keydown", this.keydown, false); document.addEventListener("keyup", this.keyup, false); this.showinstructions = function (ctx){ ctx.font = '20px calibri'; ctx.fillStyle = 'white'; ctx.fillText('1 player: arrows to move', 300 , 320 ); ctx.fillText('2 players: left player: w and s / right player: o and l', 300 , 350 ); }; function Muur () { this.x = 790; this.y = 0 this.height = 400; this.draw = function (ctx) { ctx.fillStyle = 'rgb(255, 255, 255)'; ctx.fillRect(this.x, this.y, 10, this.height); }; this.update = function () { }; }; function Balkje (x, upkeynumber, downkeynumber) { this.height = 80; this.x = x; this.y = 200; this.yVelocity = 0.2; var upkey = false, downkey = false; this.draw = function (ctx) { ctx.fillStyle = 'rgb(255, 255, 255)'; ctx.fillRect(this.x, this.y, 10, this.height); }; this.update = function (deltaTime) { if (upkey) { if (this.y - deltaTime * this.yVelocity > 0) { this.y -= deltaTime * this.yVelocity; } } if (downkey) { if (this.y + deltaTime * this.yVelocity < 400 - this.height) { this.y += deltaTime * this.yVelocity; } } }; this.keydown = function (event) { if (event.keyCode === upkeynumber) { upkey = true; if (state && !paused) { event.preventDefault(); //Don't scroll when game is playing } } else if (event.keyCode === downkeynumber) { downkey = true; if (state && !paused) { event.preventDefault(); //Don't scroll when game is playing } } } this.keyup = function (event) { if (event.keyCode === upkeynumber) { upkey = false; } else if (event.keyCode === downkeynumber) { downkey = false; } } document.addEventListener('keydown', this.keydown.bind(this), false); document.addEventListener('keyup', this.keyup.bind(this), false); }; function Bol (xVelocity, yVelocity) { this.x = 400; this.y = 75 + Math.random() * 250; this.xVelocity = xVelocity; this.yVelocity = yVelocity; this.colour = 'rgb(255 ,255 ,255)'; this.update = function (deltaTime) { var x = this.x + this.xVelocity * deltaTime; var y = this.y + this.yVelocity * deltaTime; if (y + 10 > 400){ this.yVelocity *= -1; } else if (y < 0) { this.yVelocity *= -1; } if (x > player2.x) { if ((player2.y > this.y + 10) || (player2.y + player2.height < this.y)) { this.xVelocity = 0; this.yVelocity = 0; this.x = 400; this.y = 200; this.colour = 'black'; pong.levens--; } else { if (state === 2) { pong.score2++ } this.xVelocity *= -1.05; if (state === 1 && pong.levens > 1){ // pong = reference to Pong } } } if (x < player1.x + 10){ if ((player1.y > this.y + 10) || (player1.y + player1.height < this.y)) { this.xVelocity = 0; this.yVelocity = 0; this.x = 400; this.y = 200; this.colour = 'black'; pong.levens--; } else { this.xVelocity *= -1.05; if (state === 1 && pong.levens > 1) { pong.score += 2; // pong = reference to Pong player2.x -= 4; player1.height -= 1; } else if (state === 1) { pong.score++; player2.x -= 2; player1.height -= 1; } if (state === 2) { pong.score1++ } if (player1.height < 30) { player1.height = 30; } } } this.x += this.xVelocity * deltaTime; this.y += this.yVelocity * deltaTime; } this.draw = function (ctx) { ctx.fillStyle = this.colour; ctx.fillRect(this.x, this.y, 10, 10); } }; this.loop = function loop () { this.update(); this.draw(); requestAnimationFrame(this.loop.bind(this)); }; this.update = function () { var deltaTime = Date.now() - lastUpdate; if (state && !paused) { bol.update(deltaTime); bol2.update(deltaTime); player1.update(deltaTime); player2.update(deltaTime); } lastUpdate += deltaTime; }; this.drawScoreAndLife = function (ctx) { if (state === 1) { ctx.font = '20px calibri'; ctx.fillStyle = 'white'; ctx.fillText('Score: ' + this.score, 356, 25) ctx.fillText('Life: ' + this.levens, 290, 25); } if (state === 2) { ctx.font = '20px calibri'; ctx.fillStyle = 'white'; ctx.fillText('Score: ' + this.score1, 40, 25) ctx.fillText('Score: ' + this.score2, 700, 25); ctx.fillText('Total score: ' + (this.score1 + this.score2), 350, 25); } }; this.drawGame = function (ctx) { bol.draw(ctx); bol2.draw(ctx); player1.draw(ctx); player2.draw(ctx); this.drawScoreAndLife(ctx); if (state === 1) { if (pong.levens === 0) { ctx.font = '20px calibri'; ctx.fillStyle = 'white'; ctx.fillText('You lose', 310, 200); ctx.fillText('Press \'1\' to try again', 265, 230); ctx.fillText('High score: 92', 285, 260); } } if (state === 2) { if (pong.levens === 0) { ctx.font = '20px calibri'; ctx.fillStyle = 'white'; ctx.fillText('Press \'2\' to play again', 310, 230); ctx.fillText('High score: 59', 330, 260); } } }; this.drawMenu = function (ctx) { ctx.font = '20px calibri'; ctx.fillStyle = 'white'; ctx.fillText('Press \'m\' for menu', 300, 170); ctx.fillText('Press \'1\' for 1 player', 300, 200); ctx.fillText('Press \'2\' for 2 players', 300, 230); ctx.fillText('Press i for instructions', 300, 260); ctx.fillText('Press p to pause', 300, 290); }; this.draw = function () { ctx.fillStyle = 'rgb(0, 0, 0)'; ctx.fillRect(0, 0, 800, 400); if (state){ this.drawGame(ctx); } else { this.drawMenu(ctx); } if (showinstructions) { this.showinstructions(ctx); } }; this.startpong1 = function () { if (ga) { singleGamesStarted++; ga("send", "event", "pong", "startpong1", "start", singleGamesStarted); } state = 1; player1 = new Balkje(20, 38, 40); bol = new Bol(0.2, 0.2); bol2 = new Bol(-0.2, -0.2); player2 = new Muur(); this.score = 0; this.levens = 2; }; this.startpong2 = function () { if (ga) { duoGamesStarted++; ga("send", "event", "pong", "startpong2", "start", duoGamesStarted); } state = 2; player1 = new Balkje(20, 87, 83); player2 = new Balkje(770, 79, 76); bol = new Bol(0.2, 0.2); bol2 = new Bol(-0.2, -0.2); this.score1 = 0; this.score2 = 0; this.levens = 2; }; }; var pong = new Pong(ctx); pong.loop();
$.ajax({ type:"post", url:"http://localhost/api_demo/session.php", data:{ action: 'get_session' }, dataType:"json", success:function(response){ console.log(response); $("#post_form").submit(function(e){ var token=response; $title=$("title").val(); $body=$("textarea").val(); $.ajax({ type:"post", url:"http://localhost/api_demo/api/manage_post.php", dataType:"json", data:{ action: 'save_post', title: $title, body: $body, token: token }, success:function(response){ alert("insertion successful"); }, error:function(xhr, status, msg){ console.log(msg); } }); }); }, error:function(xhr, status, msg){ console.log(msg); } });
import React from 'react' import base64 from 'base-64' import { Row, Col, Input, Button } from 'reactstrap' import Axios from 'axios' class Edit extends React.Component { constructor(props) { super(props) this.state = { status: "In", productName: "", product: {}, history: {}, amount: 0, id: this.props.match.params.id } this.handleChangeAmount = this.handleChangeAmount.bind(this) this.onSubmit = this.onSubmit.bind(this) } handleChangeAmount = e => { this.setState({ amount: e.target.value }) } componentDidMount = async () => { await this.get_history(this.state.id); } get_history = async (id) => { var token = base64.decode(localStorage.getItem("admin_login")); token = JSON.parse(token) token = token.token const history = await Axios({ method: "GET", url: `${process.env.REACT_APP_BASE_URL}/histories/${id}`, headers: { "Authorization": token } }) await this.setState({ history: history.data.history, productName: history.data.history.product_id.product_name, amount: history.data.history.history_amount }) console.log(this.state.history.product_id.product_name) } onSubmit = async (e) => { try { e.preventDefault(); var token = base64.decode(localStorage.getItem("admin_login")); token = JSON.parse(token) token = token.token const history = { history_amount: this.state.amount, product_id: this.state.history.product_id._id, } console.log(history) const res = await Axios({ method: "PATCH", url: `${process.env.REACT_APP_BASE_URL}/histories/${this.state.id}`, data: history, headers: { "Authorization": token } }) if (res.status === 200) { alert("Tracking Product History Successfull") this.setState({ name: "" }) } console.log(res) } catch (err) { alert('Tracking Product History Failure !') } } render() { return ( <> <h3>Edit Tracking Product {this.state.history.history_status}</h3> <hr /> <Row> <Col md={{ size: 6 }}> <form onSubmit={this.onSubmit}> <Row> <Col md={{ size: 12 }} sm={{ size: 12 }} className="mb-3"> <label>Nama Product</label> <Input value={this.state.productName} disabled /> </Col> <Col md={{ size: 12 }} sm={{ size: 12 }} className="mb-3"> <label>Amount</label> <Input onChange={this.handleChangeAmount} id="amount" value={this.state.amount} type="number" placeholder="ex: Technology" required /> </Col> <Col md={{ size: 12 }} sm={{ size: 12 }} className="mb-3 mt-3"> <Button className="btn btn-block btn-info" type="submit">Track Product In</Button> </Col> </Row> </form> </Col> </Row> </> ) } } export default Edit;
$(document).ready(function(){ //document.addEventListener('deviceready', function(){ $(document).on("click", ".menu, .menu_principal_bg", function(){ $(".menu").toggleClass("menu_ativo"); $(".menu_principal").toggleClass("menu_principal_ativo"); $(".menu_principal_bg").toggleClass("menu_principal_bg_ativo"); }).on("mousedown touchstart", "#content", function(e){ $("#content").one("touchend", function(ev){ if(e.changedTouches && ev.changedTouches){ if(Number(e.changedTouches[e.changedTouches.length-1].pageX)<=Number(Number(ev.changedTouches[ev.changedTouches.length-1].pageX)-150)) $(".menu").click(); } }); }).on("touchstart", ".lupa_pesquisar", function(){ $(".lupa_pesquisar").toggleClass(".lupa_pesquisar_ativo"); }); //}, false); });
import './index.css'; function FBPost (props) { const likeImg = 'https://cdn.iconscout.com/icon/premium/png-256-thumb/like-1614278-1368980.png'; const commentImg = 'https://www.freeiconspng.com/thumbs/comment-png/comment-png-17.png'; const shareImg = 'https://www.shareicon.net/data/512x512/2017/02/09/878628_send_512x512.png'; return ( <div className='header'> <div className='icon-container'> <img className="profileImg" src={props.data.avatar}/> <div className='status-circle'></div> </div> <div className='setAlignment'> <h4 className='profileName'> {props.data.createdBy} </h4> <span className='dateAndTime'><br />{props.data.createdAt.toLocaleString()}</span> <hr className='lineSpace'/> <p className='setPara'>{props.data.description}</p> <br /> <div className='setImg'> {props.data.images} </div> <div className='setButton'> <div className='button'> <img className='like' src={likeImg}/> <p className='likes' >Like</p> </div> <div className='button'> <img className='comment' src={commentImg} /> <p className='comments' >Comment</p> </div> <div className='button'> <img className='share' src={shareImg} /> <p className='shares' >Share</p> </div> </div> </div> </div> ) } export default FBPost; // {props.data.description}
import React from 'react'; import Dialog from '@material-ui/core/Dialog'; import { Row, Col, Image } from 'react-bootstrap'; import moment from 'moment'; import ShareIcon from '@material-ui/icons/Share'; import htmlToImage from 'html-to-image'; const ShareVirtualTrade = ({ data, id, showDialog, setDialog }) => { const handleShare = () => { if (data.status === 'CLOSED') { console.log(data.analyst); console.log(data); let node = document.getElementById(id); htmlToImage.toBlob(node).then(blob => { let file = new File([blob], 'trade.png', { type: 'image/png' }); if (navigator.share) { navigator .share({ text: `Check out this trade by ${data.analyst.name}!\nTo get such trades live, sign up on Pvot app from Play store.\n\n`, files: [file], url: 'https://play.google.com/store/apps/details?id=in.pvot' }) .then(() => console.log('success')) .catch(err => console.log(err)); } else { console.log('browser not supported'); } }); } }; return ( <> <Dialog fullWidth={true} open={showDialog} onClose={() => setDialog(false)}> <div id={id} style={{ backgroundColor: 'white' }}> <Row className='py-2'> <Col className='col-2 py-2'> <Image width='100%' src={require('../../../assets/images/svg/Logo.svg')} /> </Col> <Col className='col-10'> <div className='small'> <Row style={{ display: 'flex', justifyContent: 'space-between' }}> <div className='col-9 p-0 pr-2 m-0 mr-auto'> <p style={{ color: '#212121', fontSize: '14px', padding: '2px', marginBottom: '0px' }}> <strong>{data.instrument && data.instrument.trading_symbol}</strong> &nbsp; </p> <p style={{ color: '#616161', fontSize: '10px', padding: '2px', marginBottom: '0px' }}> {data.segment && data.segment.name.toUpperCase()} {' | '} {data.trade_type && data.trade_type.toUpperCase()} {' | '} {data.order_type && data.order_type.toUpperCase()} {' | '} {data.complexity && data.complexity.toUpperCase()} </p> </div> <div className='col-3 m-0 p-0'> {data.status === 'CLOSED' && ( <div className='row' style={{ color: '#101010', padding: '5px', backgroundColor: '#B1AEC1', borderRadius: '3px', fontSize: '12px', textAlign: 'center', marginBottom: '3px' }} > <p className='mb-0 mx-auto'> <span style={{ fontSize: '10px' }}>{data.status}</span> </p> </div> )} <div className='text-center'> <p style={{ color: '#212121', fontSize: '10px' }}> {moment(data.order_placement_time).format('DD/MM' + ' ' + 'HH:mm')} </p> </div> </div> </Row> <Row style={{ display: 'flex', justifyContent: 'space-between', marginTop: '10px' }}> <div> <p style={{ color: '#9e9e9e', padding: '2px', marginBottom: '0px', fontSize: '10px' }}> Order Price </p> <p style={{ color: '#212121', padding: '2px', marginBottom: '0px', fontSize: '10px' }}> {data.price} </p> <p style={{ color: '#9e9e9e', padding: '10px 2px 2px', marginBottom: '0px', fontSize: '10px' }}> Target Price </p> <p style={{ color: '#212121', padding: '2px', marginBottom: '0px', fontSize: '10px' }}> {data.target} </p> </div> <div> <p style={{ color: '#9e9e9e', padding: '2px', marginBottom: '0px', fontSize: '10px' }}>Quantity</p> <p style={{ color: '#212121', padding: '2px', marginBottom: '0px', fontSize: '10px' }}> {data.quantity} </p> <p style={{ color: '#9e9e9e', padding: '10px 2px 2px', marginBottom: '0px', fontSize: '10px' }}> Stop Loss </p> <p style={{ color: '#212121', padding: '2px', marginBottom: '0px', fontSize: '10px' }}> {data.stop_loss} </p> </div> <div> <div> <p style={{ color: '#9e9e9e', padding: '2px', marginBottom: '0px', fontSize: '10px', textAlign: 'center' }} > {data.gains >= 0 ? <>Gain</> : <>Loss </>} </p> <p style={{ color: data.gains >= 0 ? '#038C33' : '#F44336', padding: '5px', padding: '2px', marginBottom: '0px', // backgroundColor: data.gains >=0 ? '#C0FEE0': '#FED7D4', borderRadius: '3px', fontSize: '12px' }} className='text-center' > {Number(data.gains).toFixed(2)}({Number(data.gains_percentage).toFixed(2) + '%'}) </p> </div> <p style={{ color: '#9e9e9e', padding: '10px 2px 2px', marginBottom: '0px', fontSize: '12px', textAlign: 'center' }} > <>Risk : Reward</> </p> <p style={{ color: data.reward === data.risk ? '#f0880a' : data.reward > data.risk ? '#038C33' : data.reward < data.risk ? '#F44336' : '#9e9e9e', padding: '5px', padding: '2px', marginBottom: '0px', borderRadius: '3px', fontSize: '12px' }} className='text-center' > {`1: ${(data.reward / data.risk).toFixed(2)}`} </p> </div> </Row> {/* <Row className='mt-3'> <Col> <ClickAwayListener onClickAway={()=> setEdit(false)} > <Input onClick={()=> setEdit(true)} disableUnderline={!isEdit} name='check' placeholder='Additional Info' fullWidth /> </ClickAwayListener> </Col> </Row> */} </div> </Col> </Row> <Row className='mt-2 py-2 center-row'> <Col className='center-col'> <Row className='center-row'> <span className='ml-2' style={{ fontSize: '10px', fontWeight: 'bold' }}> {data.analyst.name} </span> </Row> </Col> <Col className='center-col'> <span style={{ fontWeight: 'bold', color: '#2962ff', fontSize: '16px' }}>pvot.in</span> </Col> <Col className='center-col'> <Image width='95%' src={require('../../../assets/images/GooglePlay.png')} /> </Col> </Row> </div> <Row className='mt-1' style={{ boxShadow: '0 0 8px 0' }}> <Col onClick={handleShare} className='center-col py-2'> <ShareIcon color='primary' /> </Col> </Row> </Dialog> </> ); }; export default ShareVirtualTrade;
import { Typography } from '@material-ui/core'; import React from 'react'; export function ConfirmDescription() { return ( <Typography color={'primary'}> Congratulations! Your <strong>MobX-infused</strong> order is on its way. </Typography> ); }
/**======================================================== * Module: clearicon.js * Created by wjwong on 9/8/15. =========================================================*/ angular.module('angle').directive('clearIcon', ['$compile', function($compile) { return { restrict : 'A', link : function(scope, elem, attrs) { var model = attrs.ngModel; //form-control-feedback var template = '<span ng-show="'+model+'" ng-click=\"' + model + '=\'\'\" class="form-control-feedback fa fa-times-circle" style="pointer-events: auto; top: 5px; left: -4px;"></span>'; elem.parent().append($compile(template)(scope)); var clearIconToggle = function(toggleParam) { if(elem.val().trim().length) elem.next().css("display", "inline"); else { if(elem.next().css("display") == "inline") elem.next().css("display", "none"); } }; /*var clearText = function(clearParam) { elem.val(''); clearIconToggle(clearParam); };*/ elem.on("focus", function(event) { clearIconToggle(model); }); elem.on("keyup", function(event) { clearIconToggle(model); }); elem.next().on("click", function(event) { console.warn('click', event); elem.val(''); elem.next().css("display", "none"); }); } }; }]);
function queryGroup() { $('#encourageTable').hide(); $("#hintinfo").html(""); var regular = /^0?1[3|4|5|7|8][0-9]\d{8}$/; var phone = $("#phonenumber").val(); if(!regular.test(phone)){ $("#hintinfo").html("<font color='red'>请输入一个正确的手机号</font>"); return ; } queryMyData(phone, 1); showAftertext(); } function queryMyData(phone, whichHint) { AV.Query.doCloudQuery(" select * from Encourage where mobile = '" + phone + "' order by createdAt desc limit 1 ", { success: function(result){ //results 是查询返回的结果,AV.Object 列表 var results = result.results; //do something with results… if(results != null && results.length > 0){ var object = results[0]; var resultHtml = ""; resultHtml = resultHtml + "姓名:" +object.get('username')+ "<br/>"; $('#encourageTbody').html(resultHtml); //执行查询组政策操作 findGroupPolicy2(phone); $("#encourageTbody").addClass("box"); $('#encourageTable').show(); }else{ if(whichHint == 3){ $("#hintinfo3").html("<font color='red'>暂无数据或者非uber用户</font>"); } if(whichHint == 1){ $("#hintinfo").html("<font color='red'>暂无数据或者非uber用户</font>"); } } }, error: function(error){ //查询失败,查看 error if(whichHint == 3){ $("#hintinfo3").html("<font color='red'>"+error.message+"</font>"); } if(whichHint == 1){ $("#hintinfo").html("<font color='red'>"+error.message+"</font>"); } } }); } function findGroupPolicy2(phone){ var cql="select * from _User where username='"+phone+"' "; AV.Query.doCloudQuery(cql,{ success: function(result){ var obj = result.results; var groupCode = obj[0].get("groupCode"); //alert(groupCode); //把该组对应的政策查询出来 var cql="select * from userGroup where groupCode='"+groupCode+"' "; AV.Query.doCloudQuery(cql,{ success: function(result){ var obj = result.results; var groupPolicy = obj[0].get("groupPolicy"); //alert(groupPolicy); $('#encourageTbody').html( $('#encourageTbody').html()+"用户组:"+obj[0].get("groupName")+"<br/>"+ "奖励政策:"+groupPolicy+"<br/><br/>"); }, error: function(error){ $("#hintinfo").html("<font color='red'>请刷新试试</font>"); } }); }, error: function(error){ $("#hintinfo").html("<font color='red'>请刷新试试</font>"); } }); }
/******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // 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] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = 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; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ({ /***/ 0: /***/ function(module, exports, __webpack_require__) { "use strict"; importApi("ui"); importClass("android.view.View.OnClickListener"); importClass("android.widget.Toast"); var helloXml = __webpack_require__(9); var page = { onLoad: function onLoad() { var imageView = hybridView.findViewWithTag("imageView"); imageView.setOnClickListener(new OnClickListener(function () { //Toast.makeText(activity, "原生API调用", Toast.LENGTH_SHORT).show(); ui.alert('原生API调用对话框封装'); })); /** ui.click("imageView", function(view){ ui.toast(view); view.setOnClickListener(new OnClickListener(function(){ Toast.makeText(activity, "原生API调用", Toast.LENGTH_SHORT).show(); })); });*/ } }; hybridView.onLoad = function () { page.onLoad(); }; hybridView.loadXml(helloXml); /***/ }, /***/ 9: /***/ function(module, exports) { module.exports = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<View\n width=\"750\"\n height=\"100%\"\n screenUnit=\"750\">\n <ImageView\n width=\"750\"\n height=\"300\"\n imageUrl=\"https://img.alicdn.com/tfs/TB1Pth5mcLJ8KJjy0FnXXcFDpXa-520-280.jpg\"\n scaleType=\"fitXY\"\n tag=\"imageView\"/>\n <TextView\n y=\"300\"\n width=\"750\"\n textAlign=\"center\"\n height=\"100\"\n text=\"Hello World 手机淘宝\"\n tag=\"helloTextField\"/>\n</View>\n" /***/ } /******/ });
function ProductosService(){ } ProductosService.prototype.getProductos = function(callback){ $.ajax({ type: "GET", url: "http://localhost:8080/inventarios/Products/", success: function(data){ callback(data); }, error: function(){ alert("Ocurrió un error al intentar obtener los productos."); } }); };
import { useQuery } from '@apollo/client'; import PropTypes from 'prop-types'; import { GET_OPERATOR_STATUS } from './requests'; const DataOperatorStatus = ({ id, children }) => { const { data, loading, error } = useQuery(GET_OPERATOR_STATUS, { variables: { id } }); return children(loading || error ? null : data.operator); }; DataOperatorStatus.propTypes = { id: PropTypes.string.isRequired, children: PropTypes.func.isRequired }; export default DataOperatorStatus;
import React, { Component } from "react"; import axios from "axios"; export const Context = React.createContext(); export class Provider extends Component { state = { poster_list: [], currentQuery: "", limit: 6, offset: 0 }; getPostersList = async ( query, limit = this.state.limit, offset = this.state.offset ) => { this.setState({ currentQuery: query, limit, offset }); const { data } = await axios.get( `http://cors-anywhere.herokuapp.com/https://staging-ng.morressier.com/events_manager/v3/posters/search?query=${query}&limit=${limit}&offset=${offset}` ); this.setState({ poster_list: data.posters, offset: offset + 6 }); }; getNextPage = () => { const { currentQuery, limit, offset } = this.state; this.getPostersList(currentQuery, limit, offset); }; getPreviousPage = () => { const { currentQuery, limit, offset } = this.state; this.getPostersList(currentQuery, limit, offset - 6); }; render() { return ( <Context.Provider value={{ posters: this.state.poster_list, getPostersList: this.getPostersList, getNextPage: this.getNextPage, getPreviousPage: this.getPreviousPage }} > {this.props.children} </Context.Provider> ); } } export const Consumer = Context.Consumer;
/** * @mixin */ let Form = (superclass) => class Form extends superclass { get form() { } get formAction() { } get formEnctype() { } get formMethod() { } get formNoValidate() { } get formTarget() { } } export default Form;