text
stringlengths
7
3.69M
(function() { 'use strict'; angular .module('app.math') .directive('fcMathQuestionBlock', fcMathQuestionBlock); fcMathQuestionBlock.$inject = ["mathService"]; /* @ngInject */ function fcMathQuestionBlock (mathService) { var directive = { bindToController: true, controller: MathQuestionBlockController, controllerAs: 'question', restrict: 'E', scope: { config: '=' }, templateUrl: './main/math/fc-math-question-block.html' }; return directive; /////////////// /* @ngInject */ function MathQuestionBlockController() { var vm = this; vm.config = mathService.getConfig(); console.log(vm.config); } } })();
import { useNavigation } from "@react-navigation/native"; import React, { useState } from "react"; import { ActivityIndicator, Image, ScrollView, StyleSheet, Text, TouchableOpacity, View, } from "react-native"; import StarRating from "react-native-star-rating-new"; import { PRIMARY_FONT } from "../../constants"; import SearchArea from "../components/SearchArea"; import TopBar from "../components/TopBar"; import useSearch from "../hooks/useSearch"; const Search = () => { const [value, setValue] = useState(""); const [isMongolianBook, setIsMongolianBook] = useState(true); const [ loading, searchedBook, foreignBooks, searchMongolianBook, searchForeignBook, onIconPress, ] = useSearch(); const navigation = useNavigation(); const onSearch = () => { try { if (isMongolianBook) { searchMongolianBook(value); } else { searchForeignBook(value); } } catch (error) { console.log("error->", error); } }; const onCloseIconPress = () => { setValue(""); onIconPress(); }; const pressCircle = (value) => { setIsMongolianBook(value); }; return ( <> <TopBar leftIconName="arrow-back-outline" middleText="Хайх" leftIconEvent={() => navigation.goBack()} /> <ScrollView> <View style={css.container}> <SearchArea value={value} onChangeText={setValue} onSearch={onSearch} onIconPress={onCloseIconPress} pressCircle={pressCircle} /> {loading ? ( <View style={css.loader}> <ActivityIndicator size="large" color="##3A8096" /> </View> ) : isMongolianBook ? ( searchedBook.map((el) => { return ( <TouchableOpacity onPress={() => navigation.navigate("Detail", { item: el })} key={el._id} > <View style={css.itemWrapper}> <Image source={{ uri: `${el.cover}` }} style={css.itemImage} resizeMode="center" /> <View style={css.itemRight}> <Text style={css.title}>{el.title}</Text> <Text style={css.publisher}>{el.publisher.name}</Text> <View style={css.itemStar}> <StarRating disabled={true} rating={el.rating} fullStarColor={"#E8BD0D"} starSize={20} /> </View> </View> </View> </TouchableOpacity> ); }) ) : ( foreignBooks.map((el) => { return ( <TouchableOpacity onPress={() => navigation.navigate("Detail", { item: el, isForeign: true, }) } key={el._id} > <View style={css.itemWrapper}> <Image source={{ uri: `${el.cover}` }} style={css.itemImage} resizeMode="center" /> <View style={css.itemRight}> <Text style={css.title}>{el.title}</Text> <Text style={css.publisher}>{el.publisher.name}</Text> <View style={css.itemStar}> <StarRating disabled={true} rating={el.rating} fullStarColor={"#E8BD0D"} starSize={20} /> </View> </View> </View> </TouchableOpacity> ); }) )} </View> </ScrollView> </> ); }; export default Search; const css = StyleSheet.create({ container: { flex: 1, padding: 10, }, itemWrapper: { flexDirection: "row", padding: 20, }, itemImage: { width: 50, height: 100, marginRight: 20 }, itemRight: { width: "80%" }, itemStar: { alignItems: "flex-start", marginTop: 20 }, title: { fontFamily: PRIMARY_FONT, fontSize: 15, paddingVertical: 5, }, publisher: { fontSize: 11, }, loader: { marginTop: "50%", }, });
const prisma = require('../../prisma'); const Command = require('../../structures/Command'); const Util = require('../../util'); module.exports = class SetMaxWebhooks extends Command { get name() { return 'setmaxwebhooks'; } get _options() { return { aliases: ['smw', 'smwh'], permissions: ['elevated'], minimumArgs: 1, listed: false, }; } async exec(message, { args, _ }) { const emojiFallback = Util.emojiFallback({ client: this.client, message }); const idRegex = /^\d{17,18}$/; const targetID = args[0]; if (!idRegex.test(targetID)) return message.channel.createMessage(_('setmaxwebhooks.invalid')); const webhookLimit = parseInt(args[1]) || 5; await prisma.server.upsert({ where: { serverID: targetID }, create: { serverID: targetID, maxWebhooks: webhookLimit, prefix: this.client.config.prefix, locale: this.client.config.sourceLocale }, update: { maxWebhooks: webhookLimit } }); const doneEmoji = emojiFallback('632444546684551183', '✅'); return message.channel.createMessage(`${doneEmoji} ` + _('setmaxwebhooks.set', { serverID: targetID, value: webhookLimit })); } get metadata() { return { category: 'categories.dev', }; } };
var mutt__mailbox_8h = [ [ "MUTT_MAILBOX_CHECK_FORCE", "mutt__mailbox_8h.html#ae62751826fa9f9b4ea0502a8595ea235", null ], [ "MUTT_MAILBOX_CHECK_FORCE_STATS", "mutt__mailbox_8h.html#aa10f1093422ec4cbd542f54e759c99aa", null ], [ "mutt_mailbox_check", "mutt__mailbox_8h.html#a699c8af5931c0e7156efb889a6e43738", null ], [ "mutt_mailbox_cleanup", "mutt__mailbox_8h.html#abf8c2a3fe001e431c5f0dd76e7e4e114", null ], [ "mutt_mailbox_list", "mutt__mailbox_8h.html#ab9927df6282aeabd032cfca3332f4907", null ], [ "mutt_mailbox_next", "mutt__mailbox_8h.html#a4a77c0185d4129b0a7ab77c30481b9ef", null ], [ "mutt_mailbox_notify", "mutt__mailbox_8h.html#a9e2e89628d0b2ac8cb68e6a07e0e04f3", null ], [ "mutt_mailbox_set_notified", "mutt__mailbox_8h.html#a7b979f11bcd9c44ae5779c0a432fcb8f", null ], [ "C_MailCheck", "mutt__mailbox_8h.html#a3074a610356328c230d6c145b424e2dd", null ], [ "C_MailCheckStats", "mutt__mailbox_8h.html#aa3ddf22cf6aef4c49cc0f883b3f748c5", null ], [ "C_MailCheckStatsInterval", "mutt__mailbox_8h.html#a8d950eec7f2bfa0f7b5f7e054589e5b0", null ] ];
import { combineReducers } from 'redux'; import themeKey from './themeKey'; import memberList from './memberList' import winner from './winner' export default combineReducers({ themeKey, memberList, winner });
const passwordValidator = require("password-validator"); const validator = require("email-validator"); const validatePassword = (password) => { // Create a schema var schema = new passwordValidator(); // Add properties to it schema .is() .min(5) // Minimum length 5 .has() .uppercase() // Must have uppercase letters .has() .lowercase() // Must have lowercase letters .has() .not() .spaces() // Should not have spaces .is() .not() .oneOf(["Passw0rd", "Password123"]); // Blacklist these values return schema.validate(password); }; const validateEmail = (email) => { return validator.validate(email); }; exports.validateEmail = validateEmail; exports.validatePassword = validatePassword;
const render = (element, container) => { const { type, props } = element; const { children } = props; const node = type === 'TEXT_ELEMENT' ? document.createTextNode('') : document.createElement(element.type); const keysOfAttributes = Object.keys(props).filter( (key) => key !== 'children', ); keysOfAttributes.forEach((key) => (node[key] = props[key])); container.appendChild(node); if (children.length) return children.forEach((child) => render(child, node)); }; export default render;
var searchData= [ ['caissier',['Caissier',['../classCaissier.html',1,'']]], ['client',['Client',['../classClient.html',1,'']]], ['compareevenement',['CompareEvenement',['../classCompareEvenement.html',1,'']]] ];
let str = '-121'; let mRegExp = new RegExp(/^-?[1-9]\d*$/.source); console.log(mRegExp.test(str));
import React, {useState} from 'react' import Button from '@material-ui/core/Button' export default function Counter(){ const [counter, setCounter] = useState(0) const incrementCounter = () => setCounter(counter + 1) const decrementCounter = () => setCounter(counter - 1) return ( <div> counter : {counter} <Button variant="fab" color="primary" onClick={incrementCounter} disabled={counter >= 10}> + </Button> <Button variant="fab" color="primary" onClick={decrementCounter} disabled={counter <= 0}> - </Button> </div> ) }
<% if (i === 1 && type == "house"){ %> \ <div class="clear_all"></div> \ <% } else if((i + 3) % 4 === 0){ %> \ <div class="clear_all"></div> \ <% } %> \
function setup() { // set the width & height of the sketch createCanvas(600,400) // print the time to the console once at the beginning of the run. try opening up the // web inspector and poking around to see the various values the clock function gives you } function draw() { // check the clock for the current time and unpack some of its fields to generate a time-string var now = clock() var x1, y1 background(200); for (y1=height;y1>0;y1=y1-1/4*height) { for (x1=0;x1<width;x1=x1+1/6*width){ stroke(100); strokeWeight(2); line(0,y1,width,y1); line(x1,0,x1,height); } } var h= now.hours; var m= now.progress.hour; if (h<7){ rect(100*h,0,m*100,100); } else if (7<=h && h<13){ rect(100*(h-7),100,m*100,100); } else if (13<=h && h<19){ rect(100*(h-13),200,m*100,100); } else { rect(100*(h-19),300,m*100,100); } }
import React from 'react'; const Index = () => { return ( <div className="four-o-four text-center"> <h1>404 test</h1> </div> ); }; export default Index;
import Transaction from './src/transaction' import Blockchain from './src/blockchain' import { ec as EC } from 'elliptic' const ec = new EC('secp256k1') const privateKey = ec.keyFromPrivate("0fca665ee300c79df2b5a838831c753aeead536b0224af0f7e0fd5de83138213") const walletAddress = privateKey.getPublic('hex') const buttCoin = new Blockchain() const tx1 = new Transaction(walletAddress, 'to1', 250) const tx2 = new Transaction(walletAddress, 'to1', 25) tx1.signTransaction(privateKey) tx2.signTransaction(privateKey) buttCoin.addTransaction(tx1) buttCoin.addTransaction(tx2) console.log('Starting mining operation...') buttCoin.minePendingTransactions(walletAddress) console.log(`Balance of ${walletAddress}: ${buttCoin.getBalanceOfAddress(walletAddress)}`) console.log(`Balance of to1: ${buttCoin.getBalanceOfAddress('to1')}`) console.log("Is chain valid?", buttCoin.isChainValid()) buttCoin.chain[1].transactions[1].amount = 5 console.log("Is chain valid?", buttCoin.isChainValid())
/** @type {import('@adonisjs/lucid/src/Schema')} */ const Schema = use('Schema'); class EventSchema extends Schema { up() { this.create('events', table => { table.uuid('id').primary(); table .uuid('trip_id') .unsigned() .references('id') .inTable('trips') .onUpdate('CASCADE') .onDelete('SET NULL'); table.string('name').notNullable(); table.text('description').notNullable(); table.text('photo_reference'); table.string('start_date').notNullable(); table.string('end_date').notNullable(); table.string('location').notNullable(); table.string('reservation_code'); table.text('notes'); table .enu('type', [ 'flight', 'lodging', 'car_rental', 'meeting', 'activity', 'bus', 'train', 'restaurant', 'tour', 'theater', 'cinema', ]) .notNullable(); table.decimal('lat', 9, 6); table.decimal('lng', 9, 6); table.timestamps(); }); } down() { this.drop('events'); } } module.exports = EventSchema;
$(document).ready(function(){ var $commentBox = $('.commentBox'); $('.commentArea').on('submit', function(event){ //stops page from refreshing event.preventDefault(); //gets the data from the form var data = $(this).serializeArray(); // new empty object var newComment = {}; for (var i=0; i < data.length; i++)[ if(data[i].name ===) ] $.ajax({url: '/comments', type: 'post', data: newComment }).done(function(data){ }); // END $.ajax }); // END on submit }); //END document.ready
import React, { Component } from 'react'; import { connect } from 'react-redux'; class NoteItem extends Component { twoActionButton = () => { this.props.changeEditStaus() // action 1 //ham lay noi dung truyen vao trong store, de store update vao du lieu -- action 2 // console.log(this.props.note) this.props.getEditData(this.props.note) } deleteData = ()=> { this.props.getDeleteData(this.props.note.key) this.props.alertOn('Xoa mon ' + this.props.note.noteTitle + ' thanh cong', 'warning') } render() { return ( <div className="card"> <div className="card-header" role="tab" id="note1"> <h5 className="mb-0"> <a data-toggle="collapse" data-parent="#noteList" href={'#number' + this.props.i} aria-expanded="true" aria-controls="noteContent2"> {this.props.noteTitle} </a> </h5> <div className='btn-group float-right'> <button className='btn btn-outline-info' onClick={() => this.deleteData()}>Xoa</button> <button className='btn btn-outline-info' onClick = { () => this.twoActionButton()}>Sua</button> </div> </div> <div id={'number' + this.props.i} className="collapse in" role="tabpanel" aria-labelledby="note1"> <div className="card-body"> {this.props.noteContent} </div> </div> </div> ); } } const mapStateToProps = (state, ownProps) => { return { // khong can them cung duoc nhung ma trong cong thuc co state thi phia thuc hien // isEdit: state.isEdit } } const mapDispatchToProps = (dispatch, ownProps) => { return { changeEditStaus: () => { dispatch({type: 'CHANGE_EDIT_STATUS'}) }, alertOn: (AlertContent, AlertStatus) => { dispatch({type: 'ALERT_ON', AlertContent, AlertStatus}) }, getEditData: (editObject) => { dispatch({ type: 'GET_EDIT_DATA', editObject }) }, getDeleteData: (deleteId) => { dispatch({ type: 'DELETE', deleteId }) } } } export default connect(mapStateToProps, mapDispatchToProps)(NoteItem)
import React, { useState, useEffect } from 'react' import { format } from 'date-fns' import { FiArrowLeft } from 'react-icons/fi' import { Link } from 'react-router-dom' import api from '../../services/api' import { Container, Header, HeaderContent, BackTo, Content, Card, } from './styles' const Entities = () => { const [entities, setEntities] = useState([]) useEffect(() => { async function fetchData() { const response = await api.get('/user') const { data } = response const { volunteers } = data const filtered = volunteers.filter( (volunteer) => volunteer.role === 'entity' ) setEntities(filtered) } fetchData() }, []) if (!entities) return <h1>Carregando...</h1> return ( <Container> <Header> <HeaderContent> <BackTo> <Link to="/painel"> <FiArrowLeft /> <div> <div> <span>Voltar para</span> <strong>Menus</strong> </div> </div> </Link> </BackTo> </HeaderContent> </Header> <Content> <h2>Lista de Entidades</h2> <div> {entities.length > 0 ? ( entities.map((entity) => ( <Link to={`/painel/perfil/${entity._id}`} key={entity._id}> <Card> <img src={ entity.avatarUrl ? `https://euvoluntario.s3.amazonaws.com/users/${entity.avatarUrl}` : 'https://api.hello-avatar.com/adorables/186/abott@adorable.io.png' } alt={entity.name} /> <span>{entity.name}</span> <p>Local - {entity.address}</p> <p>Contato - {entity.phone}</p> <p> {`Desde - ${format( new Date(entity.createdAt), 'dd/MM/yy' )}`} </p> </Card> </Link> )) ) : ( <p>Ainda não existem entidades cadastradas.</p> )} </div> </Content> </Container> ) } export default Entities
/* * https://www.google.com/calendar/render * ?action=TEMPLATE * &dates=20161129T230000Z/20161203T100000Z * &location=somewhere * &text=some+title * &details=some+descr */ export default function (calendarium) { const base = 'https://www.google.com/calendar/render?' // with time const _makeDateTime = function (datetime) { return datetime.toISOString().replace(/\.\d+Z$/, 'Z').replace(/[-:]/g, '') } // only day to trigger "googles" full-day representation const _makeDateDay = function (datetime) { return datetime.toISOString().split('T')[0].replace(/[-:]/g, '') } const _makeLink = function (data) { let dates = [data.start, data.stop] let dMaker = _makeDateTime if (data.mode && data.mode === 'day') { dMaker = _makeDateDay const endplus1 = new Date(data.stop) endplus1.setTime(endplus1.getTime() + (24 * 60 * 60 * 1000)) dates = [data.start, endplus1] } return base + $.param({ action: 'TEMPLATE', dates: dates.map(dMaker).join('/'), location: data.location, text: data.title, details: data.description }) } return { name: 'googlecalendar', title: { 'de': 'Bei Google Kalender eintragen', 'en': 'Add to Google Calendar' }, text: { 'de': 'Google Kalender', 'en': 'Google Calendar' }, link: _makeLink(calendarium.getEventData()) } }
import React, { Component } from 'react'; import styled from 'styled-components'; import Typist from 'react-typist'; import { Zoom } from 'react-reveal'; import { Link } from 'react-router-dom'; const MainIntro = styled.h1` font-family: ${props => props.theme.fonts.openSansSemiBold}; font-weight: 800; font-size: 88px; color: #ffffff; width: 100%; text-shadow: 2px 2px #000; ${props => props.theme.breakpoints.maxTablet} { font-size: 30px; } `; const Wrapper = styled.div` display: flex; align-items: center; flex-direction: column; width: 100%; `; const JoinButton = styled(Link)` display: flex; align-items: center; justify-content: center; padding: 12px; border-radius: 0.2em; box-sizing: border-box; text-decoration: none; font-family: 'Roboto',sans-serif; font-weight: 400; color: #FFFFFF; box-shadow: inset 0 -0.6em 1em -0.35em rgba(0,0,0,0.17),inset 0 0.6em 2em -0.3em rgba(255,255,255,0.15),inset 0 0 0em 0.05em rgba(255,255,255,0.12); text-align: center; position: relative; cursor: pointer; font-size: 45px; margin-top: 50%; ${props => props.theme.breakpoints.maxTablet} { font-size: 25px; margin-top: 30%; } top: 0; background: rgba( 0, 0, 0, 1 ); transform: translateZ(0); transition: all 0.2s ease; :hover { top: -10px; box-shadow: 5px 10px 10px rgba( 0, 0, 0, 0.2 ); transform: rotateX(20deg); color: #fff; background: black; } :active { top: 0px; box-shadow: 0px 0px 0px rgba( 0, 0, 0, 0.0 ); background: rgba( 0, 0, 0, 0.5 ); `; export default class MyComponent extends Component { render() { return ( <MainIntro> <Wrapper> <Typist> <span>Be The Generation</span> <Typist.Backspace count={10} delay={2000} /> <span>Movement</span> <Typist.Backspace count={8} delay={8000} /> <span>Generation</span> <Typist.Backspace count={10} delay={2000} /> <span>Movement</span> </Typist> <Zoom> <JoinButton to='/join'> <span style={{fontSize: '1.3em', fontFamily:'Comic Sans MS', borderRight: '1px solid rgba(255,255,255,0.5)', paddingRight:'0.3em', marginRight: '0.3em', verticalAlign: 'middle'}}>J</span> Join Private Group </JoinButton> </Zoom> </Wrapper> </MainIntro> ); } }
var rec = require('node-record-lpcm16'), request = require('request'); rec.start()
import { call, apply, put, takeEvery } from 'redux-saga/effects' import web3 from '../../ethereum/web3' import { betWizardActionTypes, betWizardUIStates } from '../actions/index.js' const compiledMatchContract = require('../../ethereum/build/Match.json') export function* betSaga(action) { yield put({ type: betWizardActionTypes.SHOW_SENDING_BET_MESSAGE, UIState: betWizardUIStates.SENDING_BET, match: action.payload.match, tie: action.payload.tie, winnerIndex: action.payload.team_id }) const accounts = yield call(web3.eth.getAccounts) const matchContract = new web3.eth.Contract( JSON.parse(compiledMatchContract.interface)) const transaction = matchContract.deploy({ data:compiledMatchContract.bytecode, arguments:[action.payload.match.teams[0].id, action.payload.match.teams[1].id] }) const deployedContract = yield call( transaction.send, {from:accounts[0], gas:'1000000'} ) yield put({ type: betWizardActionTypes.SHOW_SUCCESS_MESSAGE, UIState: betWizardUIStates.BET_COMPLETE, }) } export function* watchBetAction() { yield takeEvery(betWizardActionTypes.BET, betSaga) }
var dbName = function(){ if(process.env.NODE_ENV === "test") return "testdb"; else return "dbrest"; }; exports.mongodb = { uri: 'mongodb://localhost:27017/'+dbName() }; exports.secret = 'lifeiseasyifyouthinkso'
import React from 'react'; import {Image, StyleSheet, Text, View} from 'react-native'; import Icon from 'react-native-vector-icons/FontAwesome'; //config import color from '../config/color'; import font from '../config/font'; const Rating = ({rating}) => { var element = []; var tot = 0; var count = 1; for (let index = 0; index < 5; index++) { if (rating > tot) { element.push(<Icon name="star" size={25} color="#F3B431" key={count} />); tot += 1; count += 1; } else { element.push( <Icon name="star-o" size={25} color="#F3B431" key={count} />, ); count += 1; } } return ( <View style={styles.container}> <Image source={{ uri: 'https://www.pinclipart.com/picdir/big/457-4576580_nhtsa-5-star-overall-safety-rating-emblem-clipart.png', }} style={styles.image} /> <View style={styles.ratingContainer}> <Text style={styles.ratingText}>Safety Rating</Text> <View style={styles.ratingStar}>{element}</View> </View> </View> ); }; export default Rating; const styles = StyleSheet.create({ container: { flexDirection: 'row', paddingVertical: 10, alignItems: 'center', justifyContent: 'flex-start', paddingHorizontal: 10, }, image: { width: 39, height: 45, }, ratingContainer: { marginLeft: 10, flexDirection: 'row', flex: 1, }, ratingStar: { paddingHorizontal: 20, alignItems: 'center', justifyContent: 'flex-end', flexDirection: 'row', flex: 1, }, ratingText: { fontFamily: font.primary, fontSize: 17, color: color.medium, fontWeight: 'bold', }, });
import React, { useEffect, useState } from "react"; import { Display } from "./Display"; import "../styles/css/styles.css"; const TranslatedDisplay = (props) => { const [toText, setToText] = useState(""); const [translatedText, setTranslatedText] = useState(""); useEffect(() => { setToText(props.editorState.getCurrentContent().getPlainText()); }, [props.editorState.getCurrentContent().getPlainText()]); // eslint-disable-line react-hooks/exhaustive-deps useEffect(() => { console.log("text: " + toText); const setUpdated = async () => { const result = await fetch("/translate/", { method: "POST", body: JSON.stringify({ foreign: toText, }), headers: new Headers({ "Content-Type": "application/json", }), }).then((res) => res.json()); setTranslatedText(result.translated); }; setUpdated(); }, [toText]); return ( <div className="TranslatedDisplay"> <h2>Result:</h2> <Display text={translatedText}></Display> </div> ); }; export default TranslatedDisplay;
import React from 'react' import {Link} from 'react-router-dom' import moment from 'moment' const NoteListItem = ({note}) => { if(!note) return <div>No Note</div> return ( <Link className="note-list-item" to={`/notes/${note.id}`}> <h4>{note.name}</h4> <p>{moment(note.timestamp).format("Do MMMM YYYY - h:mm A")}</p> <p>{note.strokeCount} Strokes, {note.pointCount} Points</p> </Link> ) } export default NoteListItem;
const express = require("express"); const router = express.Router(); const app = express(); var bodyParser = require("body-parser"); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); const routes = require("./routes/routes"); //const read = require("./routes/read"); /* let movies = require("./model"); console.log(movies); */ app.use(router); routes.mount(app); //app.use("/", mount); app.listen(3000, () => console.log("Listening in port 3000"));
import {Component} from 'react' import './index.css' const imgResource = 'https://assets.ccbp.in/frontend/react-js/speedometer-img.png' class Speedometer extends Component { state = { speed: 0, } increaseSpeed = () => { const {speed} = this.state if (speed < 200) { this.setState(prevState => ({speed: prevState.speed + 10})) } } decreaseSpeed = () => { const {speed} = this.state if (speed >= 1) { this.setState(prevState => ({speed: prevState.speed - 10})) } } render() { const {speed} = this.state return ( <div className="speed-meter-container"> <h1 className="heading">SPEEDOMETER</h1> <img className="speedometer-img" src={imgResource} alt="speedometerImg" /> <h1 className="speed-display">{`Speed is ${speed}mph`}</h1> <p>Min Limit is 0mph, Max Limit is 200mph</p> <div className="buttons-container"> <button onClick={this.increaseSpeed} className="accelerate-button" type="button" > Accelerate </button> <button onClick={this.decreaseSpeed} className="apply-break-button" type="button" > Apply Brake </button> </div> </div> ) } } export default Speedometer
import React, {Component} from 'react' import {StackNavigator} from 'react-navigation' /** * Screens */ console.disableYellowBox = true import Home from './src/Home' import Cadastrar from './src/Cadastrar' import Interno from './src/Interno' import Preload from './src/preload' import Receita from './src/receita' import Despesa from './src/despesa' const Navegador = StackNavigator({ Preload: { screen: Preload }, Home: { screen: Home }, Cadastrar: { screen: Cadastrar }, Interno: { screen: Interno }, Receita: { screen:Receita }, Despesa: { screen: Despesa } }) export default Navegador
function StartDropDown(Obj, Length){ } function movedown(Obj, Ypos){ Obj.style.top = parseInt(Obj.style.top) + 1 + 'px'; if (parseInt(Obj.style.top) < Ypos) { setTimeout(movedown(Obj, Ypos), 20); } }
// The functionality of Objects const obj = { firstName:'Arman', age:31, greet(){ console.log('Hello '+this.firstName) } } //console.log(obj) //console.log(obj.greet()) obj.lastName = 'Enzo' //console.log(obj) delete obj.lastName console.log(obj) // To iterate we use For in loop
import axios from 'axios'; import { ACTIVITY_URI, ALL_DEVICES_URI, ADD_MAINTENANCE_LOGS_URI, DEPLOY_DEVICE_URI, EDIT_DEVICE_URI, DELETE_DEVICE_URI, DELETE_DEVICE_PHOTO, EVENTS, RECALL_DEVICE_URI, SITES, AIRQLOUDS, DECRYPT, QRCODE, REFRESH_AIRQLOUD, SOFT_EDIT_DEVICE_URI, DASHBOARD_AIRQLOUDS, ALL_DEVICE_HOSTS, CREATE_DEVICE_HOST, UPDATE_DEVICE_HOST, SEND_DEVICE_HOST_MONEY, GET_TRANSACTION_HISTORY } from 'config/urls/deviceRegistry'; import { DEVICE_MAINTENANCE_LOG_URI } from 'config/urls/deviceMonitoring'; import { DEVICE_RECENT_FEEDS } from 'config/urls/dataManagement'; import { GET_DEVICE_IMAGES, SOFT_EDIT_DEVICE_IMAGE } from '../../config/urls/deviceRegistry'; import { BASE_AUTH_TOKEN } from '../../utils/envVariables'; export const getAllDevicesApi = async (networkID) => { return await axios .get(ALL_DEVICES_URI, { params: { network: networkID, token: BASE_AUTH_TOKEN } }) .then((response) => response.data); }; export const softCreateDeviceApi = async (data, ctype) => { return await axios .post(SOFT_EDIT_DEVICE_URI, data, { params: { ctype, token: BASE_AUTH_TOKEN } }) .then((response) => response.data); }; export const getFilteredDevicesApi = async (params) => { return await axios .get(ALL_DEVICES_URI, { params: { ...params, token: BASE_AUTH_TOKEN } }) .then((response) => response.data); }; export const getDeviceMaintenanceLogsApi = async (deviceName) => { return await axios .get(DEVICE_MAINTENANCE_LOG_URI + deviceName, { params: { token: BASE_AUTH_TOKEN } }) .then((response) => response.data); }; export const getActivitiesApi = async (params) => { return await axios .get(ACTIVITY_URI, { params: { ...params, token: BASE_AUTH_TOKEN } }) .then((response) => response.data); }; export const getActivitiesSummaryApi = async (params) => { return await axios .get(ACTIVITY_URI, { params: { ...params, token: BASE_AUTH_TOKEN } }) .then((response) => response.data); }; export const addMaintenanceLogApi = async (deviceName, logData) => { return await axios .post(ADD_MAINTENANCE_LOGS_URI, logData, { params: { deviceName, token: BASE_AUTH_TOKEN } }) .then((response) => response.data); }; export const recallDeviceApi = async (deviceName, requestData) => { return await axios .post(RECALL_DEVICE_URI, requestData, { params: { deviceName, token: BASE_AUTH_TOKEN } }) .then((response) => response.data); }; export const deployDeviceApi = async (deviceName, deployData) => { return axios .post(DEPLOY_DEVICE_URI, deployData, { params: { deviceName, token: BASE_AUTH_TOKEN } }) .then((response) => response.data); }; export const getDeviceRecentFeedByChannelIdApi = async (channelId) => { return await axios .get(DEVICE_RECENT_FEEDS, { params: { channel: channelId, token: BASE_AUTH_TOKEN } }) .then((response) => response.data); }; export const updateDeviceDetails = async (id, updateData) => { return await axios .put(EDIT_DEVICE_URI, updateData, { params: { id, token: BASE_AUTH_TOKEN } }) .then((response) => response.data); }; export const softUpdateDeviceDetails = async (deviceId, updateData) => { return await axios .put(SOFT_EDIT_DEVICE_URI, updateData, { params: { id: deviceId, token: BASE_AUTH_TOKEN } }) .then((response) => response.data); }; export const deleteDeviceApi = async (deviceName) => { return axios .delete(DELETE_DEVICE_URI, { params: { device: deviceName, token: BASE_AUTH_TOKEN } }) .then((response) => response.data); }; export const updateMaintenanceLogApi = async (deviceId, logData) => { return axios .put(ACTIVITY_URI, logData, { params: { id: deviceId, token: BASE_AUTH_TOKEN } }) .then((response) => response.data); }; export const deleteMaintenanceLogApi = (deviceId) => { return axios .delete(ACTIVITY_URI, { params: { id: deviceId, token: BASE_AUTH_TOKEN } }) .then((response) => response.data); }; export const deleteDevicePhotos = async (deviceId, urls) => { return await axios .delete(DELETE_DEVICE_PHOTO, { params: { id: deviceId, token: BASE_AUTH_TOKEN }, data: { photos: urls } }) .then((response) => response.data); }; export const getEventsApi = async (params) => { return await axios .get(EVENTS, { params: { ...params, token: BASE_AUTH_TOKEN } }) .then((response) => response.data); }; export const getSitesApi = async (params) => { return await axios .get(SITES, { params: { ...params, token: BASE_AUTH_TOKEN } }) .then((response) => response.data); }; export const getSitesSummaryApi = async (params) => { return await axios .get(`${SITES}/summary`, { params: { ...params, token: BASE_AUTH_TOKEN } }) .then((response) => response.data); }; export const getSiteDetailsApi = async (site_id) => { return await axios .get(SITES, { params: { id: site_id, token: BASE_AUTH_TOKEN } }) .then((response) => response.data); }; export const updateSiteApi = async (site_id, siteData) => { return await axios .put(SITES, siteData, { params: { id: site_id, token: BASE_AUTH_TOKEN } }) .then((response) => response.data); }; export const createSiteApi = async (siteData) => { return await axios .post(SITES, siteData, { params: { token: BASE_AUTH_TOKEN } }) .then((response) => response.data); }; export const deleteSiteApi = async (siteId) => { return await axios .delete(SITES, { params: { id: siteId, token: BASE_AUTH_TOKEN } }) .then((response) => response.data); }; export const getAirQloudsApi = async (params) => { return await axios .get(AIRQLOUDS, { params: { ...params, token: BASE_AUTH_TOKEN } }) .then((response) => response.data); }; export const getDashboardAirQloudsApi = async (params) => { return await axios .get(DASHBOARD_AIRQLOUDS, { params: { ...params, token: BASE_AUTH_TOKEN } }) .then((response) => response.data); }; export const decryptKeyApi = async (encrypted_key) => { return await axios .post(DECRYPT, { encrypted_key }, { params: { token: BASE_AUTH_TOKEN } }) .then((response) => response.data); }; export const QRCodeApi = async (params) => { return await axios .get(QRCODE, { params: { ...params, token: BASE_AUTH_TOKEN } }) .then((response) => response.data); }; export const refreshAirQloudApi = async (params) => { return await axios .put(REFRESH_AIRQLOUD, {}, { params: { ...params, token: BASE_AUTH_TOKEN } }) .then((response) => response.data); }; export const softCreateDevicePhoto = async (data) => { return await axios .post(SOFT_EDIT_DEVICE_IMAGE, data, { params: { token: BASE_AUTH_TOKEN } }) .then((response) => response.data); }; export const getDevicePhotos = async (params) => { return await axios .get(GET_DEVICE_IMAGES, { params: { device_id: params, token: BASE_AUTH_TOKEN } }) .then((response) => response.data); }; export const getAllDeviceHosts = async () => { return await axios.get(ALL_DEVICE_HOSTS).then((response) => response.data); }; export const createDeviceHost = async (params) => { return await axios .post(CREATE_DEVICE_HOST, params, { params: { token: BASE_AUTH_TOKEN } }) .then((response) => response.data) .catch((error) => error.response.data); }; export const updateDeviceHost = async (id, params) => { return await axios .put(`${UPDATE_DEVICE_HOST}/${id}`, params, { params: { token: BASE_AUTH_TOKEN } }) .then((response) => response.data) .catch((error) => error.response.data); }; export const sendMoneyToHost = async (id, amount) => { return await axios .post( `${SEND_DEVICE_HOST_MONEY}/${id}/payments`, { amount }, { params: { token: BASE_AUTH_TOKEN } } ) .then((response) => response.data) .catch((error) => error.response.data); }; export const getTransactionDetails = async (id) => { return await axios .get(`${GET_TRANSACTION_HISTORY}/${id}`) .then((response) => response.data) .catch((error) => error.response.data); };
import React, { useEffect, useState } from 'react'; import { Text, View, RefreshControl, StyleSheet, Image, FlatList, Dimensions } from 'react-native'; import { connect } from 'react-redux'; import { TouchableOpacity } from 'react-native-gesture-handler'; import { getAllProducts } from '../store/actions/product'; import { BASE_URL, PRIMARY_COLOR, SECONDARY_COLOR } from '../utils/constants'; import ProductItem from './ProductItem'; import { PlayfairDisplay_500Medium } from '@expo-google-fonts/playfair-display'; const numColumns = 1; const ProductList = (props) => { const [ refreshing, setRefreshing ] = useState(false); useEffect(() => { // Update the document title using the browser API props.getAllProducts('createdAt', 'desc', 10); }, []); renderItem = ({ item }) => { if (item.empty === true) { return <View style={[ styles.item, styles.itemInvisible ]} />; } return <View style={styles.item}></View>; }; const refreshData = () => { setRefreshing(true); try { props.getAllProducts('createdAt', 'desc', 10).then(() => { setRefreshing(false); }); } catch (err) { console.log(err); } }; return ( <> <View style={styles.header}> <Text style={styles.categoryTitle}>Most Popular</Text> </View> <FlatList style={styles.container} // data={formatData(props.products, numColumns)} data={props.products} numColumns={numColumns} keyExtractor={item => item._id} renderItem={itemData => ( <ProductItem key={itemData.item._id} item={itemData.item} {...props} /> )} horizontal refreshControl={<RefreshControl refreshing={refreshing} onRefresh={refreshData} />} /> </> ); }; const styles = StyleSheet.create({ container: { borderColor: '#fff', borderTopLeftRadius: 50, backgroundColor: '#fff' }, header:{ backgroundColor: SECONDARY_COLOR, position: 'relative', top: 0, left: 0, right: 0, borderBottomRightRadius: 50, height: 40, textAlign: 'center', alignItems: 'center' }, categoryTitle: { fontFamily: "PlayfairDisplay_500Medium", fontSize: 22, color: '#fff' }, item: { justifyContent: 'center', flex: 1, }, itemInvisible: { backgroundColor: 'transparent' }, itemText: { color: '#fff' }, price: { marginTop: 5, flexDirection: 'column', fontSize: 12, color: PRIMARY_COLOR } }); const formatData = (data, numOfColumns) => { const numberofRows = Math.floor(data.length / numOfColumns); let numberOfElementsLastRow = data.length - numberofRows * numOfColumns; while (numberOfElementsLastRow !== numOfColumns) { data.push({ _id: `blank-${numberOfElementsLastRow}`, empty: true }); numberOfElementsLastRow = numberOfElementsLastRow + 1; } return data; }; const mapStateToProps = (state) => ({ products: state.products.products, loading: state.products.loading }); export default connect(mapStateToProps, { getAllProducts })(ProductList);
import React, { Fragment } from 'react'; import Header from '../../components/Header'; import ArtworkList from '../../components/ArtworkList'; import { urlEnv, configEnv } from '../../utils/urlEnv'; import Head from '../../components/Head'; import sortBy from 'lodash.sortby'; import wretch from 'wretch'; import configContents from '../../utils/configContents'; import URL from 'url-parse'; class Gallery extends React.Component { state = { artwork: [], isOwner: false, title: null, description: null, siteError: false }; async componentDidMount() { window.scrollTo(0, 0); try { const { title = '', description = '', isOwner = false, isDat = false } = await this.loadArchiveInfo(); const artwork = await this.loadHttpArtwork(); this.setState({ isOwner, artwork, title, description, isDat }); } catch (error) { console.log('Error:', error); this.setState({ siteError: true }); } } loadArchiveInfo = async () => { try { const archive = await new global.DatArchive(urlEnv()); const { title, description, isOwner } = await archive.getInfo(); return { title, description, isOwner, isDat: true }; } catch (error) { const { title, description } = await wretch('dat.json') .get() .json(); return { title, description, isDat: false }; } }; loadHttpArtwork = async () => { const api = await wretch(`${configEnv(true)}/gallery-manifest.json`) .get() .json(json => json); const promises = await api.works.map(async artwork => { const artworkResponse = await wretch( `${configEnv(true)}/art/${artwork}.json` ) .get() .json() .catch(error => console.log('Error:', error)); return artworkResponse; }); const results = await Promise.all(promises); return results; }; removeFromGallery = async pathname => { const archive = await new global.DatArchive(urlEnv()); const works = await archive.readFile(`/gallery-manifest.json`); await archive.unlink(`/gallery-manifest.json`); const oldWorks = await JSON.parse(works); const newWorks = await oldWorks.works; const promises = await newWorks.filter(item => { const path = URL(pathname) .pathname.substr(URL(pathname).pathname.lastIndexOf('/') + 1) .split('.'); return item !== path[0]; }); const newAdjusted = await Promise.all(promises); await archive.unlink(pathname); await archive.writeFile( `/gallery-manifest.json`, configContents(newAdjusted) ); const artwork = await this.loadHttpArtwork(); this.setState({ artwork }); }; setArtworkState = artwork => { this.setState({ artwork }); }; render() { return ( <Fragment> <Head title={this.state.title} /> <Header title={this.state.title} description={this.state.description} isOwner={this.state.isOwner} loadArtwork={this.loadHttpArtwork} setArtworkState={this.setArtworkState} isDat={this.state.isDat} /> <ArtworkList artwork={sortBy(this.state.artwork, ['dateTime']).reverse()} isOwner={this.state.isOwner} removeFn={this.removeFromGallery} /> {this.state.siteError && ( <Fragment> <div style={{ padding: '40px' }}> <p>Looks like there was an error.</p> </div> </Fragment> )} </Fragment> ); } } export default Gallery;
"use strict"; function __export(m) { for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; } Object.defineProperty(exports, "__esModule", { value: true }); const Data = require("./Data"); exports.Data = Data; function setSystemsPath(path) { exports.systemsPath = path; } exports.setSystemsPath = setSystemsPath; __export(require("./systems")); function log(message) { const date = new Date(); const text = `${date.toLocaleDateString()} ${date.toLocaleTimeString()} - ${message}`; console.log(text); return; } exports.log = log; class LocalizedError { constructor(key, variables) { this.key = key; this.variables = variables; } } exports.LocalizedError = LocalizedError;
import ArBasicExample from "./ar-basic"; import ArHitTestExample from "./ar-hit-test"; import VrBasicExample from "./vr-basic"; import VrControllersExample from './vr-controllers'; import VrHandsExample from "./vr-hands"; import VrMovementExample from "./vr-movement"; import XrPickingExample from "./xr-picking"; export { ArBasicExample, ArHitTestExample, VrBasicExample, VrControllersExample, VrHandsExample, VrMovementExample, XrPickingExample };
import request from '@/utils/request' export function scoreList(query) { return request({ url: '/input/list', method: 'get', params: query }) } export function updateStatOne(row) { return request({ url: '/input/updateOne', method: 'post', row }) } export function updateStatAll(rows) { return request({ url: '/input/updateAll', method: 'post', rows }) }
//Declarando Variáveis var btnContact = document.querySelector('.vg-btn-contact'); var toggleMenu = document.querySelectorAll('.vg-toggle-menu'); var menuMobile = document.querySelector('.vg-menu-mob'); var btnMenuMobIcon = document.querySelector('.vg-btn-menu-mob ion-icon'); //Page Preloader window.addEventListener('load', function () { var pagePreloader = document.querySelector('.vg-preloader'); pagePreloader.classList.add('vg-fade-out'); setTimeout(function () { pagePreloader.style.display = 'none'; }, 2000); }); //Abrindo e Fechando Informações de Contato btnContact.addEventListener('click', function () { var boxContact = document.querySelector('.vg-contact-info'); boxContact.classList.toggle('vg-is-open'); this.classList.toggle('vg-change-icon'); }); //Abrindo e Fechando o Menu Mobile for (var m = 0; m < toggleMenu.length; m++) { toggleMenu[m].addEventListener('click', function () { var overlay = document.querySelector('.vg-menu-overlay'); overlay.classList.toggle('vg-is-open'); menuMobile.classList.toggle('vg-menu-is-closed'); menuMobile.classList.toggle('vg-menu-is-open'); var icon = btnMenuMobIcon.getAttribute('name'); if (icon === 'menu-outline') { btnMenuMobIcon.setAttribute('name', 'close-outline'); } else { btnMenuMobIcon.setAttribute('name', 'menu-outline'); } }); } //Animando Elementos da TopBar var triggerTopbar = document.querySelector('.vg-trigger-topbar'); var topBar = document.querySelector('.vg-topbar'); var logo = document.querySelector('.vg-logo'); var waypoint = new Waypoint({ element: triggerTopbar, handler: function () { topBar.classList.toggle('vg-topbar-bg'); logo.classList.toggle('vg-logo-shorten'); logo.classList.toggle('vg-logo-big'); }, offset: '50px' });
require("/javascripts/foo"); var FakeAjax = new Object(); $.ajax = FakeAjax;
function getNumbers(str) { let splitString, numbers = []; const minNumber = 1, maxNumber = 9; splitString = str.split(''); for(let i = 0; i < splitString.length; i++) { if(splitString[i] >= minNumber && splitString[i] <= maxNumber) { numbers.push(parseInt(splitString[i])); } } return numbers; } function findType() { let typeCounter = {}; for(let i = 0; i < arguments.length; i++) { if(typeCounter.hasOwnProperty(typeof arguments[i])) { typeCounter[typeof arguments[i]] += 1; } else { typeCounter[typeof arguments[i]] = 1; } } return typeCounter; } function executeforEach(inputArray, functionForEach) { for(let i = 0; i < inputArray.length; i++) { functionForEach(inputArray[i]); } } function mapArray(inputArray, inputFunction) { let outputArray = []; executeforEach(inputArray, function(arr) { inputFunction(arr) ? outputArray.push(inputFunction(arr)) : false; }); return outputArray; } function filterArray(inputArray, inputFunction) { let filteredArray = []; executeforEach(inputArray, function(arr) { inputFunction(arr) ? filteredArray.push(arr) : false; }); return filteredArray; } function showFormattedDate(dateObject) { let formattedDate, startPosition = 3; formattedDate = 'Date:' + dateObject.toDateString().substr(startPosition); return formattedDate; } function canConvertToDate(dateString) { let dataObject, canConvert; dataObject = new Date(dateString); canConvert = !isNaN(dataObject.getTime()); return canConvert; } function daysBetween(startDate, endDate){ let msStartDate, msEndDate, msBetween, daysBetween; const MS_IN_SECOND = 1000, SEC_IN_MINUTES = 60, MINUTES_IN_HOURS = 60, HOURS_IN_DAY = 24; msStartDate = new Date(startDate).getTime(); msEndDate = new Date(endDate).getTime(); msBetween = Math.abs(msStartDate - msEndDate); daysBetween = Math.round(msBetween/(MS_IN_SECOND * SEC_IN_MINUTES * MINUTES_IN_HOURS * HOURS_IN_DAY)); return daysBetween; } function getAmountOfAdultPeople(data) { let birthDays = [], currentDate, dayDifference = [], adultBirthdays = []; const ADULT_YEAR = 18, DAYS_IN_YEAR = 365; currentDate = new Date(); for(let i = 0; i < data.length; i++) { birthDays[i] = data[i][' birthday ']; dayDifference[i] = daysBetween(birthDays[i], currentDate); } adultBirthdays = filterArray(dayDifference, function(arr) { return arr > ADULT_YEAR * DAYS_IN_YEAR; }); return adultBirthdays.length; } function keys(obj) { let objectKeys = [], i = 0; for(let prop in obj) { if(obj.hasOwnProperty(prop)) { objectKeys[i] = prop; i++; } } return objectKeys; } function values(obj) { let objectValues = [], i = 0; for(let prop in obj) { if(obj.hasOwnProperty(prop)) { objectValues[i] = obj[prop]; i++; } } return objectValues; }
import React, { useContext } from 'react'; export const ListBook = (props) => { return ( < li key = { props.id } > { props.text } < span > { props.amount } < /span> < button onClick = { null } > * < /button > < / li > ) }
new Vue({ el: '#app', //dentro de este id se trabajara con vue data: { valorA: 908526, valorB: 0, transporte: 106000 }, methods:{ suma:function(){ return (this.valorA + this.valorB); }, descuento:function(){ return ((this.valorA + this.valorB) * 0.04); }, descuentototal:function(){ return ((this.valorA + this.valorB) * 0.08); }, netoapagar:function(){ return (((this.valorA + this.valorB) - ((this.valorA + this.valorB) * 0.08))); } }, })
var Game = function(token) { this.token = token; this.playersCount = 0; this.tiles = []; this.players = []; this.hasStarted = false; this.turn = 'W'; this.lastMoveWasBeat = undefined; // for (var i = 0; i < Game.tilesCount; ++i) { // this.tiles[i] = []; // for (var j = 0; j < Game.tilesCount; ++j) { // if ((i + j) % 2 === 0) // this.tiles[i][j] = 'N'; //TODO enum instead of char? +RETHINK // else if (j < 4) // this.tiles[i][j] = 'B'; // else if (j < 6) // this.tiles[i][j] = 'E'; // else { // this.tiles[i][j] = 'W'; // } // } // } //FOR QUICK TESTING: for (var i = 0; i < Game.tilesCount; ++i) { this.tiles[i] = []; for (var j = 0; j < Game.tilesCount; ++j) { if ((i + j) % 2 === 0) this.tiles[i][j] = 'N'; //TODO enum instead of char? +RETHINK else if (j === 2 || j === 4 || j === 0) this.tiles[i][j] = 'B'; else if (j === 5 || j === 7 || j === 9) this.tiles[i][j] = 'W'; else { this.tiles[i][j] = 'E'; } } } }; Game.tilesCount = 10; //TODO array[color] +REFACTOR Game.prototype.join = function(player) { console.log('Player ' + player.username + ' joined ' + this.token + ' game'); ++this.playersCount; this.players.push(player); player.game = this; }; Game.prototype.changeTurn = function() { this.turn = this.oppositeColor(this.turn); }; Game.prototype.leave = function(player) { --this.playersCount; if (this.hasStarted) player.disconnected = true; else this.players = []; }; Game.prototype.rejoin = function(color) { if (this.players[color].disconnected) { console.log('Player ' + this.players[color].username + ' rejoined ' + this.token + ' game'); ++this.playersCount; this.players[color].disconnected = false; return this.players[color]; } }; Game.prototype.start = function() { console.log('Game ' + this.token + ' commenced'); var rand = Math.floor(Math.random() * 2); this.players.white = this.players[rand]; this.players.white.color = 'W'; this.players.black = this.players[1 - rand]; this.players.black.color = 'B'; this.players[rand] = this.players[1 - rand] = undefined; this.hasStarted = true; }; Game.prototype.makeMove = function(move, player) { //validate move if (!this.isDataValid(move)) return false; var steps = this.isStepValid(move); if (!steps) return false; var pos = this.isMoveAllowed(move, player); if (!pos) return false; if (!this.isDirectionValid(steps, player)) return false; if (!this.isNextBeatValid(move, steps)) return false; var opp = this.isBeatValid(move, steps, player); if (!opp) return false; //if everything's allright -> apply move var moveProcessed = this.applyMove(move, steps, opp, player); return moveProcessed; }; Game.prototype.isDataValid = function(move) { if (move && move.from && move.from.x !== undefined && move.from.y !== undefined && move.to.x !== undefined && move.to.y !== undefined && +move.from.x >= 0 && +move.from.x <= 9 && +move.from.y >= 0 && +move.from.y <= 9 && +move.to.x >= 0 && +move.to.x <= 9 && +move.to.y >= 0 && +move.to.y <= 9 && +move.from.x !== +move.to.x && +move.from.y !== +move.to.y) { move.from.x = +move.from.x; move.from.y = +move.from.y; move.to.x = +move.to.x; move.to.y = +move.to.y; return true; } return false; }; Game.prototype.isStepValid = function(move) { var steps = {}; steps.x = move.to.x - move.from.x; steps.y = move.to.y - move.from.y; steps.xAbs = Math.abs(steps.x); steps.yAbs = Math.abs(steps.y); if (steps.xAbs > 2 || steps.yAbs > 2 || steps.xAbs !== steps.yAbs) return false; return steps; }; Game.prototype.isMoveAllowed = function(move, player) { if (this.turn === player.color && this.tiles[move.from.x][move.from.y] === player.color && this.tiles[move.to.x][move.to.y] === 'E') { var pos = {}; pos.from = this.tiles[move.from.x][move.from.y]; pos.to = this.tiles[move.to.x][move.to.y]; return pos; } return undefined; }; Game.prototype.isDirectionValid = function(steps, player) { if ( (steps.yAbs === 1 && player.color === 'W' && steps.y === -1) || (steps.yAbs === 1 && player.color === 'B' && steps.y === 1) || (steps.yAbs === 2) ) return true; return false; }; Game.prototype.isNextBeatValid = function(move, steps) { if (this.lastMoveWasBeat) { if (move.from.x === this.lastMoveWasBeat.x && move.from.y === this.lastMoveWasBeat.y && steps.xAbs === 2) return true; } else return true; return false; }; Game.prototype.isBeatValid = function(move, steps, player) { var opp; if (steps.xAbs === 2) { opp = {}; opp.x = move.from.x + steps.x / 2; opp.y = move.from.y + steps.y / 2; opp.tile = this.tiles[opp.x][opp.y]; if ( (player.color === 'W' && opp.tile !== 'B') || (player.color === 'B' && opp.tile !== 'W') ) return false; return opp; } return true; }; Game.prototype.applyMove = function(move, steps, opp, player) { var man = this.tiles[move.from.x][move.from.y]; this.tiles[move.from.x][move.from.y] = 'E'; this.tiles[move.to.x][move.to.y] = man; if (steps.xAbs === 1) { this.changeTurn(); move.changeTurn = true; } else if (steps.xAbs === 2) { this.tiles[opp.x][opp.y] = 'E'; if (this.moreMovesAvailable(move.to.x, move.to.y, player.color) > 0) { this.lastMoveWasBeat = { x: move.to.x, y: move.to.y, color: player.color }; } else { this.changeTurn(); move.changeTurn = true; this.lastMoveWasBeat = undefined; } move.manToBeat = { x: opp.x, y: opp.y }; } return move; }; Game.prototype.moreMovesAvailable = function(x, y, color) { var relativePosBeat = [ [-2, -2], [-2, 2], [2, -2], [ 2, 2] ]; //always the same var allowed = 0; for (var i in relativePosBeat) { var tileToCheck = { 'x': +x + relativePosBeat[i][0], 'y': +y + relativePosBeat[i][1] }; var oppTileToCheck = { 'x': +x + relativePosBeat[i][0] / 2, 'y': +y + relativePosBeat[i][1] / 2, }; if (this.areCoordsValid(tileToCheck) && this.canBeat(tileToCheck, oppTileToCheck, color)) ++allowed; } return allowed > 0; }; Game.prototype.canBeat = function(tile, oppTile, color) { var res = this.tiles[tile.x][tile.y] === 'E' && this.tiles[oppTile.x][oppTile.y] === this.oppositeColor(color); return res; }; Game.prototype.oppositeColor = function(color) { return (color === 'W' ? 'B' : 'W'); }; Game.prototype.areCoordsValid = function(tile) { var res = (tile.x >= 0 && tile.x < 10 && tile.y >= 0 && tile.y < 10); return res; }; module.exports = Game;
exports.seed = function(knex) { // Deletes ALL existing entries return knex('tasks').truncate() .then(function () { // Inserts seed entries return knex('tasks').insert([ { task_description: "home page", task_notes: "do it", task_complete: false, project_id: 1 }, { task_description: "about page", task_notes: "do it", task_complete: false, project_id: 1 }, { task_description: "contact page", task_notes: "do it", task_complete: false, project_id: 1 }, { task_description: "build database", task_notes: "do it", task_complete: false, project_id: 2 }, { task_description: "build frontend", task_notes: "do it", task_complete: true, project_id: 2 }, { task_description: "build backend", task_notes: "do it", task_complete: false, project_id: 2 }, { task_description: "tweet feed", task_notes: "do it", task_complete: false, project_id: 3 }, { task_description: "search bar", task_notes: "do it", task_complete: false, project_id: 3 }, { task_description: "direct messages", task_notes: "do it", task_complete: false, project_id: 3 }, ]); }); };
import OrderTable from "./orderTable"; import ProductTable from "./productTable"; export default class TableFactory { db; constructor(db) { this.db = db; } createTable(tableName) { switch (tableName) { case "orders": return new OrderTable(this.db.collection("orders"), this.db); break; case "products": return new ProductTable(this.db.collection("products"), this.db); break; } } }
import { pad } from '../utils/padding'; export function sliceBeats(data, peaks) { const indices = calculateSliceIndices(data, peaks); const slices = []; for(let i = 0; i < indices.length; i++) { const padded = pad(data.slice(indices[i][0], indices[i][1]), 360); slices.push(padded); } return slices; } function calculateSliceIndices(data, peaks) { let results = []; let cursor = 0; let cr1, cr2; while(cursor < peaks.length) { // Create a "cardiac cycle" between two R-R peaks, choose next neighbors if not exist if(cursor == 0) { cr1 = (peaks[cursor] - ((peaks[cursor + 2] - peaks[cursor + 1]) >> 1)) cr2 = (peaks[cursor] + peaks[cursor + 1]) >> 1 } else if(cursor == peaks.length - 1) { cr1 = (peaks[cursor] - ((peaks[cursor] - peaks[cursor - 1]) >> 1)) cr2 = (peaks[cursor] + ((peaks[cursor - 1] - peaks[cursor - 2]) >> 1)) } else { cr1 = (peaks[cursor] - ((peaks[cursor] - peaks[cursor - 1]) >> 1)) cr2 = (peaks[cursor] + peaks[cursor + 1]) >> 1 } // Prevent out of bounds if(cr1 < 0) cr1 = 0 if(cr2 >= data.length) cr2 = data.length - 1 // Push slice indices as tuple results.push([cr1, cr2]); cursor += 1; } return results; }
import React from 'react'; import {updateFilters} from '../../services/filters/actions.js'; import {connect} from 'react-redux'; const availableSizes = ['XS', 'S', 'M', 'ML', 'L', 'XL', 'XXL']; const CreateCheckBox = (props)=>{ return ( <div class="form-check mb-2 mr-sm-2"> <label class="form-check-label"> <input class="form-check-input" type="checkbox" onChange={()=>{ props.onCheckBoxChange(props.name); }} value={props.name}/> {props.name} </label> </div>); } class Filter extends React.Component{ componentDidMount() { this.selectedCheckboxes = new Set(); } onCheckBoxChange=(label)=>{ if (this.selectedCheckboxes.has(label)) { this.selectedCheckboxes.delete(label); } else { this.selectedCheckboxes.add(label); } this.props.updateFilters(Array.from(this.selectedCheckboxes)); }; render(){ const onCheckBoxChange = this.onCheckBoxChange; return (<div class="card mt-2"> <div class="card-header">Filter By Size</div> <div class="card-body">{availableSizes.map((elm)=>{ return <CreateCheckBox name={elm} onCheckBoxChange = {onCheckBoxChange} /> })}</div> </div>); } } const mapDisptachToProp = { updateFilters } export default connect(null,mapDisptachToProp)(Filter);
'use strict'; import React, {Component} from 'react'; import { View, Modal, ScrollView, TouchableHighlight,Text,SafeAreaView, StatusBar, Image, TouchableOpacity, StyleSheet,} from 'react-native'; import {DisplayText, SubmitButton, InputField} from '../../components'; import styles from './styles'; import colors from '../../assets/colors'; import { ProgressDialog } from 'react-native-simple-dialogs'; import { postWithToken, CreateSupport, getProfile, } from '../Utils/Utils'; import {Input, Icon} from 'native-base' import DropdownAlert from 'react-native-dropdownalert'; export default class CreateIssue extends Component { constructor(props) { super(props); this.state ={ token : '', showAlert : false, message : '', title : '', showAlert : false, showLoading : false, messageIssue : '', isValidIssue : false, userId: '', channel: 'Payment', channelModalVisible: false, isValidChannel: false } } async componentDidMount(){ let profile = await getProfile(); this.setState({ token : profile.access_token, }); } handleBack = () => { return this.props.navigation.goBack(); } // Show Loading Spinner showLoadingDialogue =()=> { this.setState({ showLoading: true, }); } // Hide Loading Spinner hideLoadingDialogue =()=> { this.setState({ showLoading: false, }); } // Show Dialog message showNotification = (type, title, message,) => { this.hideLoadingDialogue(); return this.dropDownAlertRef.alertWithType(type, title, message); } handleCloseNotification = () => { return this.setState({ showAlert : false }) } setChannelPicker = (newValue) => { this.setState({ channel: newValue, isValidChannel: true }); this.closeChannelModal(); } handleChannel = () => { this.toggleChannelModal(true); }; toggleChannelModal = (visible) => { this.setState({ channelModalVisible : visible }); }; closeChannelModal = () => { this.toggleChannelModal(!this.state.channelModalVisible); }; handleCreateTicket = async() => { const {messageIssue, channel, token} = this.state; await this.showLoadingDialogue(); let data = { 'subject': messageIssue, 'channel': channel, }; await postWithToken (CreateSupport, data, token) .then((res) => { if (typeof res.message !== 'undefined' ) { return this.showNotification('error', 'Message', res.message); } else { this.hideLoadingDialogue(); return this.props.navigation.navigate('Message', { 'id' : res.data.id }); } }).catch(error=>this.showNotification('error', 'Message', error.toString())); } handleaIssueChange = (issue) => { if(issue.length > 0) { this.setState({ isValidIssue: true, messageIssue : issue, }); } else { if (issue.length < 1) { this.setState({ isValidIssue : false }); } } } toggleButtonState = () => { const { isValidIssue } = this.state; if ( isValidIssue ) { return true; } else { return false; } } render () { const pickerChannel = [ {title: 'Payments', value: 'Payments'}, {title: 'Report', value: 'Report'}, {title: 'Subscriptions', value: 'Subscriptions'}, {title: 'Suggestions', value: 'Suggestions'}, {title: 'Others', value: 'Others'}, ]; const {showLoading,channel} = this.state; return( <SafeAreaView style={styles.container}> <StatusBar barStyle="default" /> <DropdownAlert ref={ref => this.dropDownAlertRef = ref} /> <View style = {styles.navBar}> <TouchableOpacity onPress={this.handleBack} style = {styles.headerImage}> <Image onPress={this.handleBack} source = {require('../../assets/images/back.png')} style = {StyleSheet.flatten(styles.headerIcon)} /> </TouchableOpacity> <View style = {styles.nameView}> <DisplayText text={'Support Desk'} styles = {StyleSheet.flatten(styles.txtHeader)} /> </View> </View> <View style ={styles.supportViewBody}> <View style = {styles.inputView}> <DisplayText styles={StyleSheet.flatten(styles.textIssues)} text = {'Have an issue,'} /> <DisplayText styles={StyleSheet.flatten(styles.textIssues)} text = {'Create a ticket to talk to support'} /> <View style = {styles.formView}> <DisplayText text={'Any Issue?'} styles = {styles.formHeaderTxt} /> <InputField textColor={colors.darkGray} inputType={'name'} keyboardType={'default'} onChangeText = {this.handleaIssueChange} autoCapitalize = "none" height = {40} borderWidth = {0.5} borderColor={colors.darkSilver} borderRadius={4} paddingLeft = {8} /> </View> <View style = {styles.formContainer}> <DisplayText text={'Channel *'} styles = {styles.formHeaderTxt} /> <TouchableOpacity underlayColor={colors.white} onPress = {this.handleChannel} style = {styles.textBoder}> <View style = {styles.viewTxtChannel}> <Text style = {styles.channelTxt}> {channel} </Text> <Icon active name='md-arrow-dropdown' style={styles.iconStyle} /> </View> </TouchableOpacity> </View> <Modal animationType="fade" transparent={true} visible = {this.state.channelModalVisible} onRequestClose={() => {console.log('Request was closed')}}> <View style={styles.modalContainer}> <View style={styles.modalStyle}> <ScrollView showsVerticalScrollIndicator={false} contentContainerStyle={{ padding: 16}}> <View style={{ justifyContent: 'center'}}> <DisplayText style={styles.textHeaderStyle} text ={'Channel'} /> {pickerChannel.map((value, index) => { return <TouchableHighlight key={index} onPress={() => this.setChannelPicker(value.value)}> <Text style={styles.modalTxt}>{value.title}</Text> </TouchableHighlight>; }) } </View> </ScrollView> </View> </View> </Modal> </View> <View style = {styles.btnView}> <SubmitButton title={'Create Ticket'} disabled={!this.toggleButtonState()} onPress={this.handleCreateTicket} titleStyle={styles.btnText} btnStyle = {styles.btnStyle} /> <ProgressDialog visible={showLoading} title="Processing" message="Please wait..."/> </View> </View> </SafeAreaView> ) } }
import React, { Component, PropTypes } from 'react' import CSSModules from 'react-css-modules' import { Link, IndexLink } from 'react-router' import styles from './button-group.scss' function getStyleName(props) { const isLink = props.to || props.href let style = `btn btn-${props.bsStyle}` if (props.outline) style += `-outline` if (props.bsSize) style += ` btn-${props.bsSize}` if (props.block) style += ' btn-block' if (props.active) style += ' active' if (props.disabled && isLink) style += ' disabled' if (props.pullRight) style += ` pull-${props.pullRight}-right` if (props.margin) style += ` m-a-${props.margin}` if (props.marginTop) style += ` m-t-${props.marginTop}` if (props.marginRight) style += ` m-r-${props.marginRight}` if (props.marginBottom) style += ` m-b-${props.marginBottom}` if (props.marginLeft) style += ` m-l-${props.marginLeft}` return style } class Button extends Component { static propTypes = { to: PropTypes.string, href: PropTypes.string, onClick: PropTypes.func, bsStyle: PropTypes.string.isRequired, bsSize: PropTypes.oneOf([null, 'sm', 'lg']), outline: PropTypes.bool.isRequired, block: PropTypes.bool.isRequired, active: PropTypes.bool.isRequired, disabled: PropTypes.bool.isRequired, pullRight: PropTypes.oneOf([null, 'xs', 'sm', 'md', 'lg', 'xl']), margin: PropTypes.number, marginTop: PropTypes.number, marginRight: PropTypes.number, marginBottom: PropTypes.number, marginLeft: PropTypes.number } static defaultProps = { bsStyle: 'secondary', outline: false, block: false, active: false, disabled: false } constructor(props) { super(props) this.state = { styleName: getStyleName(props) } } renderReactRouterLink() { const Class = this.props.to === '/' ? IndexLink : Link return ( <Class role="button" to={this.props.to} styleName={this.state.styleName}> {this.props.children} </Class>) } renderElement() { return this.props.href ? // Render anchor element <a role="button" href={this.props.href} styleName={this.state.styleName}> {this.props.children} </a> : // Render button element <button type="button" disabled={this.props.disabled} onClick={this.props.onClick} styleName={this.state.styleName}> {this.props.children} </button> } render() { return this.props.to ? // Render React-Router Link this.renderReactRouterLink() : this.renderElement() } } export default CSSModules(Button, styles, {allowMultiple: true})
/** * Copyright 2016 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ goog.provide('audioCat.state.editMode.SelectionChangedEvent'); goog.require('audioCat.state.editMode.Events'); goog.require('audioCat.utility.Event'); /** * Fired when the selected sections changes. * @param {!Array.<!audioCat.state.editMode.MoveSectionEntry>} selectedSections * The list of selected sections. * @constructor * @extends {audioCat.utility.Event} */ audioCat.state.editMode.SelectionChangedEvent = function(selectedSections) { goog.base(this, audioCat.state.editMode.Events.SELECTION_CHANGED); /** * A list of selected sections. * @private {!Array.<!audioCat.state.editMode.MoveSectionEntry>} */ this.selectedSections_ = selectedSections; }; goog.inherits( audioCat.state.editMode.SelectionChangedEvent, audioCat.utility.Event); /** * @return {!Array.<!audioCat.state.editMode.MoveSectionEntry>} The list of * selected sections. */ audioCat.state.editMode.SelectionChangedEvent.prototype.getSelectedSections = function() { return this.selectedSections_; };
const chalk = require("chalk"); async function logMSG(m, command, from, prefix) { let mediaType = '' if (m.hasMedia) { let _mediaType = await m.downloadMedia() mediaType = await _mediaType.mimetype } let numFrom = from.split('@')[0]; let d = new Date(); let _is = command.includes(m.body.toLowerCase().slice(1).split(/ +/)[0]) && prefix.includes(m.body.charAt(0)) let date = `${d.toLocaleDateString('id-ID').replace(new RegExp('/', 'g'), ' : ')} | ${d.toLocaleTimeString('id-ID').replace('.', ' : ').replace('.', ' : ')}`; const format = `${chalk.cyanBright('[ RECEIVED ]')} ${chalk.green('~' + numFrom)} ${chalk.white.bgYellow(date)} ${m.hasMedia ? `${mediaType.includes('webp') ? chalk.bgYellow.black(' STICKER ') : chalk.bgYellow.black(' MEDIA ')}` : ``}\n${_is ? `${chalk.yellow(m.body)}` : `${m.body}`}` console.log(format); } module.exports = logMSG
const bcrypt = require("bcrypt"); // bcrypt.hash() or bcrypt.hashSync() // ---------------------------------------------------------------------------- // ENCRYPT or HASH a string // 1. Encrypt password for sign-up feature // 2. Encrypt password for seed file that inserts users // 3. Encrypt password for update password feature const encryptedCoucou = bcrypt.hashSync("coucou", 10); console.log(encryptedCoucou); const encryptedEmpty = bcrypt.hashSync("", 10); console.log(encryptedEmpty); const encryptedLong = bcrypt.hashSync( "RV^zBsg4}wUHtq*azMM$dM362DDJFuBA?73#H7B^no", 10 ); console.log(encryptedLong); // bcrypt.compare() or bcrypt.compareSync() // ---------------------------------------------------------------------------- // Compare a string to an encrypted string to see if the match // 1. Compare strings for long-in feature // 2. Compare strings for password confirmation console.log(bcrypt.compareSync("coucou", encryptedCoucou)); // true console.log(bcrypt.compareSync("CouCou", encryptedCoucou)); // false console.log(bcrypt.compareSync("password", encryptedCoucou)); // false
import { context as entry } from '../resources/entry'; import { context as project } from '../resources/project'; import { context as client } from '../resources/client'; import { context as activity } from '../resources/activity'; import { context as employee } from '../resources/employee'; import { context as totals } from '../resources/totals'; import execQ from './db'; const context = { activity, client, project, entry, employee, totals, execQ, }; export default context;
Ext.define('Assessmentapp.assessmentapp.shared.com.viewmodel.assessmentcontext.survey.AssessmentQuestionSheetLoaderUIViewModel', { 'extend': 'Ext.app.ViewModel', 'alias': 'viewmodel.AssessmentQuestionSheetLoaderUIViewModel', 'model': 'AssessmentQuestionSheetLoaderUIModel' });
'use strict' import puppeteer from 'puppeteer' import cheerio from 'cheerio' import fetch from 'node-fetch' import buildQueryString from './buildQueryString' export default async (config) => { const queryString = config.queryVars ? buildQueryString(config.queryVars) : '' const url = `https://news.google.com/search?${queryString}&q=${config.searchTerm} when:${config.timeframe || '7d'}` //console.log(`SCRAPING NEWS FROM: ${url}`) const puppeteerConfig = { headless: true, args: puppeteer.defaultArgs().concat(config.puppeteerArgs).filter(Boolean) } const browser = await puppeteer.launch(puppeteerConfig) const page = await browser.newPage() page.setViewport({ width: 1366, height: 768 }) page.setUserAgent('Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36') page.setRequestInterception(true) page.on('request', request => { if (!request.isNavigationRequest()) { request.continue() return } const headers = request.headers() headers['Accept'] = 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3' headers['Accept-Encoding'] = 'gzip' headers['Accept-Language'] = 'en-US,en;q=0.9,es;q=0.8' headers['Upgrade-Insecure-Requests'] = 1 headers['Referer'] = 'https://www.google.com/' request.continue({ headers }) }) await page.setCookie({ name: "CONSENT", value: `YES+cb.${new Date().toISOString().split('T')[0].replace(/-/g,'')}-04-p0.en-GB+FX+667`, domain: ".google.com" }); await page.goto(url, { waitUntil: 'networkidle2' }) const content = await page.content() const $ = cheerio.load(content) const articles = $('a[href^="./article"]').closest('div[jslog]') let results = [] let i = 0 const urlChecklist = [] $(articles).each(function() { const link = $(this).find('a[href^="./article"]').attr('href').replace('./', 'https://news.google.com/') || false link && urlChecklist.push(link) const mainArticle = { "title": $(this).find('h3').text() || false, "link": link, "image": $(this).find('figure').find('img').attr('src') || false, "source": $(this).find('div:last-child svg+a').text() || false, "datetime": new Date($(this).find('div:last-child time').attr('datetime')) || false, "time": $(this).find('div:last-child time').text() || false, "related": [] } const subArticles = $(this).find('div[jsname]').find('article') $(subArticles).each(function() { const subLink = $(this).find('a').first().attr('href').replace('./', 'https://news.google.com/') || false if (subLink && !urlChecklist.includes(subLink)) { mainArticle.related.push({ "title": $(this).find('h4').text() || $(this).find('h4 a').text() || false, "link": subLink, "source": $(this).find('div:last-child svg+a').text() || false, "time": $(this).find('div:last-child time').text() || false }) } }) results.push(mainArticle) i++ }) if (config.prettyURLs) { results = await Promise.all(results.map(article => { return fetch(article.link).then(res => res.text()).then(data => { const _$ = cheerio.load(data) article.link = _$('c-wiz a[rel=nofollow]').attr('href') return article }) })) } await page.close() await browser.close() return results.filter(result => result.title) }
var vt = vt = vt || {}; vt.LogicClass_500120 = cc.Class.extend({ m_view: null, ctor: function () {}, setTableView: function (view) { this.m_view = view; }, refreshTableView: function () { //this.m_view.reloadData(); }, setVar: function (key, value) { this[key] = value; }, run: function (context, targetObject) { var _this = this; var localVar={}; //add by wang_dd var logicName = ""; // 发送消息到游戏 var sendData = (function(){ var value = '经验库'; return value; })(); var scene = vt.sceneManager.getCurrentScene(); var _obj = ""; var objId; if(parseInt(78)) { objId=parseInt(78); } else { objId=600000; } scene.enumerateChildren('//' + objId, function (node) { if(objId == parseInt(node.getName())) { _obj = node; return true; } }); var clientLogicId = _obj.clientLogicId; var data = { id:_obj.logicId, sendData:sendData }; var netManager = vt.NetManager.getInstance(); var _msg = vt.MSG_Client.ClientMsgRes netManager.sendMsg([0x6], data,true,function(msg){ if(msg.isTimeOut){ console.log("timeOut :" +msg.isTimeOut+"S" +"&&uuid:" + msg.uuid); }else if(msg.Code && msg.Code == 201){ console.log("is error 201 :",msg.data); }else if(msg && clientLogicId){ vt.NetDataCache.getInstance().addOneMsgByKey(msg,msg.uuid); context.msguuid = msg.uuid; var logic = new vt["LogicClass_" + clientLogicId](); context.addLogic(clientLogicId, logic); logic.run(context); } }); } });
import './app4.css' import $ from 'jquery' const localKey = 'app3.active2' const eventBus = $({}) const m = { data: { bool: localStorage.getItem(localKey) || 'no' }, creat() {}, delete() {}, update(data) { Object.assign(m.data, data) eventBus.trigger('m:update') localStorage.setItem(localKey, data.bool) }, get() {} } const v = { el: null, html: (bool) => { return ` <div> <div class="circle"></div> </div> ` }, init(container){ v.el = $(container) }, render(bool) { if (v.el.children().length !== 0) v.el.empty() $(v.html(bool)).appendTo(v.el) } } const c = { init(container){ v.init(container) v.render(m.data.bool) // view = render(data) c.autoBindEvents() eventBus.on('m:update', () => { v.render(m.data.bool) }) }, events:{ 'mouseenter .circle': 'change' }, change() { console.log(m.data.bool) const bool = m.data.bool === 'no' ? 'yes' : 'no' m.update({bool : bool}) }, autoBindEvents() { for ( let key in c.events) { if ( c.events.hasOwnProperty(key) ) { const spaceIndex = key.indexOf(' ') const part1 = key.slice(0, spaceIndex) const part2 = key.slice(spaceIndex + 1) const value = c[c.events[key]] v.el.on(part1, part2, value) } } } } export default c
import React from 'react'; import DisplayEvent from "./containers/DisplayEvents" import { Header, Modal, Button, Icon } from "semantic-ui-react" import Welcome from './presentational/Welcome' import EditUserModal from './components/EditUserModal'; import { api } from './services/api'; export default class UserShow extends React.Component { constructor(props) { super(props) this.state = { edit: false, upcomingEvents: [], pastEvents: [], today: new Date(), user : { name: "", email: "", } } } componentDidMount() { this.fetchUserInfo() } fetchUserInfo = () => { api.auth.getCurrentUser() .then(this.readJson) } readJson = (json) => { const { attendees, events, name, email } = json if (json.error) { console.log(json) } else { this.setState({ user: { name: name, email: email }, ...this.segmentEvents([...events, ...attendees]) }) } } segmentEvents = (events) => { let bifurcated = { upcomingEvents: [], pastEvents: [], } for (let i = 0; i < events.length; i++) { let eventDate = new Date(`${events[i].date}T01:00`) if (this.state.today <= eventDate) { bifurcated.upcomingEvents.push({...events[i], date: eventDate }) } else { bifurcated.pastEvents.push({...events[i], date: eventDate }) } } return bifurcated } toggleEditModal = () => { this.setState({ edit: !this.state.edit }) } handleEditUser = (edited) => { console.log(edited) api.auth.editCurrentUser({user: edited}) .then(json => { this.setState({ edit: false, user: { name: json.name, email: json.email } }) }) } handleDeleteUser = () => { api.auth.deleteCurrentUser() .then(json => { this.props.handleLogout() }) } handleDeleteEvent = (eventId) => { api.event.deleteEvent(eventId) .then(json => { this.setState({ pastEvents: this.state.pastEvents.filter(event => event.id != eventId), upcomingEvents: this.state.upcomingEvents.filter(event => event.id != eventId) })}) } render() { return ( <> <Welcome name={this.state.user.name} /> <div> <Header>Upcoming Events</Header> <DisplayEvent events={this.state.upcomingEvents} handleDeleteEvent={this.handleDeleteEvent}/> </div> <div> <Header>Your Past events</Header> <DisplayEvent events={this.state.pastEvents} handleDeleteEvent={this.handleDeleteEvent}/> </div> <br/> <Button onClick={this.toggleEditModal} >Edit Your Info</Button> <Modal open={this.state.edit} handletoggle={this.toggleEditModal}> <Modal.Header><Icon name="times" onClick={this.toggleEditModal}/>Edit Your Info</Modal.Header> <Modal.Content> <EditUserModal user={this.state.user} handleEditUser={this.handleEditUser} handleDeleteUser={this.handleDeleteUser}/> </Modal.Content> </Modal> </> ) } }
import React from 'react'; import styled from 'styled-components'; import { AboutSection } from './aboutSection'; import { FooterSection } from './footer'; import { SectionUp } from './LandingPageContent'; import { SectionSlide } from './simpleReactCarousel'; const HomeContainer = styled.div` width: 100%; height: 100%; display: flex; flex-direction: column; `; export function LandingPage(props){ return ( <HomeContainer> <SectionUp /> <AboutSection /> <SectionSlide /> <FooterSection /> </HomeContainer> ); }
export {default as Card} from './Card' export {default as Loading} from './Loading' export {default as Navigation} from './Navigation' export {default as Footer} from './Footer'
module.exports = function(app) { Ember.TEMPLATES['components/header-site'] = require('./template.hbs'); app.HeaderSiteComponent = Ember.Component.extend({ tagName: 'header', classNames: ['header-site', 'noselect'], // some cool header logic ... }); };
import firebase from './index'; export default function getAllDoc(coll) { var db = firebase.firestore(); let temp = []; return new Promise((resolve) => { db.collection(coll) .get() .then(function (querySnapshot) { querySnapshot.forEach(function (doc) { // doc.data() is never undefined for query doc snapshots // console.log(doc.id, " => ", doc.data()); temp.push({ docId: doc.id, docData: doc.data() }); }); resolve(temp); }) .catch(function (error) { console.log("Error getting documents: ", error); resolve(temp); }); }) }
const ModalReducer = (state = {}, action) => { if(action.type === "openModal"){ var modals = Object.assign({}, state); modals[action.modal] = true; return modals; } else if(action.type === "closeModal"){ var modals = Object.assign({}, state); modals[action.modal] = false; return modals; } else if(action.type === "addAreaSuccess" || action.type === "addCategorySuccess"){ var modals = Object.assign({}, state); for(var key in modals){ if(modals.hasOwnProperty(key)){ modals[key] = false; } } return modals; } else { return state; } } export default ModalReducer;
(function(){ //popup part var btn_popup = document.getElementById("btn_popup"); var popup = document.getElementById("popup"); var popup_bar = document.getElementById("popup_bar"); var btn_close = document.getElementById("btn_close"); var btnCall = document.getElementById("btnCall"); var btnHangUp = document.getElementById("btnHangUp"); var offset = {x: 0, y: 0}; popup_bar.addEventListener('mousedown', mouseDown, false); window.addEventListener('mouseup', mouseUp, false); function mouseUp() { window.removeEventListener('mousemove', popupMove, true); } function mouseDown(e) { offset.x = e.clientX - popup.offsetLeft; offset.y = e.clientY - popup.offsetTop; window.addEventListener('mousemove', popupMove, true); } function popupMove(e) { popup.style.position = 'fixed'; var top = e.clientY - offset.y; var left = e.clientX - offset.x; popup.style.top = top + 'px'; popup.style.left = left + 'px'; } window.onkeydown = function (e) { if (e.keyCode == 27) { // if ESC key pressed btn_close.click(e); } } btn_popup.onclick = function (e) { // reset div position popup.style.top = Math.round($(window).height() * 40 / 100) + "px"; popup.style.left = Math.round($(window).width() * 70 / 100) + "px"; popup.style.width = "200px"; popup.style.height = "220px"; popup.style.display = "block"; // register //register(); } btn_close.onclick = function (e) { popup.style.display = "none"; } }()); //sipml5 part var sTransferNumber; var oRingTone, oRingbackTone; var oSipStack, oSipSessionRegister, oSipSessionCall, oSipSessionTransferCall; var videoRemote, videoLocal, audioRemote; //var bFullScreen = false; var oNotifICall; var bDisableVideo = true; var viewVideoLocal, viewVideoRemote, viewLocalScreencast; // <video> (webrtc) or <div> (webrtc4all) var oConfigCall; var oReadyStateTimer; var txtDisplayName; var txtPrivateIdentity; var txtPublicIdentity; var txtPassword; var txtRealm; var txtPhoneNumber; //кому звоним var txtWebsocketServerUrl; var txtIceServers; var server_addr = "192.168.0.105"; txtDisplayName = "103"; txtPrivateIdentity = "103"; txtPublicIdentity = "sip:103@" + server_addr; txtPassword = "103pas"; txtRealm = server_addr; txtPhoneNumber = "101"; txtWebsocketServerUrl = "ws://" + server_addr + ":8088/ws"; txtIceServers="[{ url: 'stun:stun.l.google.com:19302'}]"; //txtIceServers=""; window.onload = function () { if(window.console) { window.console.info("location=" + window.location); } //videoLocal = document.getElementById("video_local"); //videoRemote = document.getElementById("video_remote"); audioRemote = document.getElementById("audio_remote"); // set debug level SIPml.setDebugLevel((window.localStorage && window.localStorage.getItem('org.doubango.expert.disable_debug') == "true") ? "error" : "info"); //loadCredentials(); //loadCallOptions(); // Initialize call button uiBtnCallSetText("Call"); var getPVal = function (PName) { var query = window.location.search.substring(1); var vars = query.split('&'); for (var i = 0; i < vars.length; i++) { var pair = vars[i].split('='); if (decodeURIComponent(pair[0]) === PName) { return decodeURIComponent(pair[1]); } } return null; } var preInit = function() { // set default webrtc type (before initialization) var s_webrtc_type = getPVal("wt"); var s_fps = getPVal("fps"); var s_mvs = getPVal("mvs"); // maxVideoSize var s_mbwu = getPVal("mbwu"); // maxBandwidthUp (kbps) var s_mbwd = getPVal("mbwd"); // maxBandwidthUp (kbps) var s_za = getPVal("za"); // ZeroArtifacts var s_ndb = getPVal("ndb"); // NativeDebug if (s_webrtc_type) SIPml.setWebRtcType(s_webrtc_type); // initialize SIPML5 SIPml.init(postInit); // set other options after initialization if (s_fps) SIPml.setFps(parseFloat(s_fps)); if (s_mvs) SIPml.setMaxVideoSize(s_mvs); if (s_mbwu) SIPml.setMaxBandwidthUp(parseFloat(s_mbwu)); if (s_mbwd) SIPml.setMaxBandwidthDown(parseFloat(s_mbwd)); if (s_za) SIPml.setZeroArtifacts(s_za === "true"); if (s_ndb == "true") SIPml.startNativeDebug(); //console.log(s_mvs); //TODO //var rinningApps = SIPml.getRunningApps(); //var _rinningApps = Base64.decode(rinningApps); //tsk_utils_log_info(_rinningApps); } oReadyStateTimer = setInterval(function () { if (document.readyState === "complete") { clearInterval(oReadyStateTimer); // initialize SIPML5 preInit(); } }, 500); sipRegister(); }; window.onbeforeunload = function () { sipUnRegister(); //return "Do you really want to close?"; }; function postInit() { // check webrtc4all version if (SIPml.isWebRtc4AllSupported() && SIPml.isWebRtc4AllPluginOutdated()) { // TODO if (confirm("Your WebRtc4all extension is outdated (" + SIPml.getWebRtc4AllVersion() + "). A new version with critical bug fix is available. Do you want to install it?\nIMPORTANT: You must restart your browser after the installation.")) { window.location = 'http://code.google.com/p/webrtc4all/downloads/list'; return; } } // check for WebRTC support if (!SIPml.isWebRtcSupported()) { // is it chrome? if (SIPml.getNavigatorFriendlyName() == 'chrome') { if (confirm("You're using an old Chrome version or WebRTC is not enabled.\nDo you want to see how to enable WebRTC?")) { window.location = 'http://www.webrtc.org/running-the-demos'; } else { window.location = "index.html"; } return; } // for now the plugins (WebRTC4all only works on Windows) if (SIPml.getSystemFriendlyName() == 'windows') { // Internet explorer if (SIPml.getNavigatorFriendlyName() == 'ie') { // Check for IE version if (parseFloat(SIPml.getNavigatorVersion()) < 9.0) { if (confirm("You are using an old IE version. You need at least version 9. Would you like to update IE?")) { window.location = 'http://windows.microsoft.com/en-us/internet-explorer/products/ie/home'; } else { window.location = "index.html"; } } // check for WebRTC4all extension if (!SIPml.isWebRtc4AllSupported()) { if (confirm("webrtc4all extension is not installed. Do you want to install it?\nIMPORTANT: You must restart your browser after the installation.")) { window.location = 'http://code.google.com/p/webrtc4all/downloads/list'; } else { // Must do nothing: give the user the chance to accept the extension // window.location = "index.html"; } } // break page loading ('window.location' won't stop JS execution) if (!SIPml.isWebRtc4AllSupported()) { return; } } else if (SIPml.getNavigatorFriendlyName() == "safari" || SIPml.getNavigatorFriendlyName() == "firefox" || SIPml.getNavigatorFriendlyName() == "opera") { if (confirm("Your browser don't support WebRTC.\nDo you want to install WebRTC4all extension to enjoy audio/video calls?\nIMPORTANT: You must restart your browser after the installation.")) { window.location = 'http://code.google.com/p/webrtc4all/downloads/list'; } else { window.location = "index.html"; } return; } } // OSX, Unix, Android, iOS... else { if (confirm('WebRTC not supported on your browser.\nDo you want to download a WebRTC-capable browser?')) { window.location = 'https://www.google.com/intl/en/chrome/browser/'; } else { window.location = "index.html"; } return; } } // checks for WebSocket support if (!SIPml.isWebSocketSupported() && !SIPml.isWebRtc4AllSupported()) { if (confirm('Your browser don\'t support WebSockets.\nDo you want to download a WebSocket-capable browser?')) { window.location = 'https://www.google.com/intl/en/chrome/browser/'; } else { window.location = "index.html"; } return; } // FIXME: displays must be per session // attachs video displays // if (SIPml.isWebRtc4AllSupported()) { // viewVideoLocal = document.getElementById("divVideoLocal"); // viewVideoRemote = document.getElementById("divVideoRemote"); // viewLocalScreencast = document.getElementById("divScreencastLocal"); // WebRtc4all_SetDisplays(viewVideoLocal, viewVideoRemote, viewLocalScreencast); // FIXME: move to SIPml.* API // } else { // viewVideoLocal = videoLocal; // viewVideoRemote = videoRemote; // } if (!SIPml.isWebRtc4AllSupported() && !SIPml.isWebRtcSupported()) { if (confirm('Your browser don\'t support WebRTC.\naudio/video calls will be disabled.\nDo you want to download a WebRTC-capable browser?')) { window.location = 'https://www.google.com/intl/en/chrome/browser/'; } } document.body.style.cursor = 'default'; oConfigCall = { audio_remote: audioRemote, //video_local: videoLocal, //video_remote: videoRemote, video_local: undefined, video_remote: undefined, screencast_window_id: 0x00000000, // entire desktop bandwidth: {audio: undefined, video: undefined}, video_size: {minWidth: undefined, minHeight: undefined, maxWidth: undefined, maxHeight: undefined}, events_listener: {events: '*', listener: onSipEventSession}, sip_caps: [ {name: '+g.oma.sip-im'}, {name: 'language', value: '\"en,fr\"'} ] }; } //// TODO: load from vtiger //function loadCredentials() { // TODO: org.doubango.identity.... replace with vtiger // if (window.localStorage) { // // IE retuns 'null' if not defined // var s_value; // if ((s_value = window.localStorage.getItem('org.doubango.identity.display_name'))) // //txtDisplayName.value = s_value; // txtDisplayName = ""; // window.console.log(s_value); // if ((s_value = window.localStorage.getItem('org.doubango.identity.impi'))) // //txtPrivateIdentity.value = s_value; // txtPrivateIdentity = ""; // if ((s_value = window.localStorage.getItem('org.doubango.identity.impu'))) // //txtPublicIdentity.value = s_value; // txtPublicIdentity = ""; // if ((s_value = window.localStorage.getItem('org.doubango.identity.password'))) // //txtPassword.value = s_value; // txtPassword = ""; // if ((s_value = window.localStorage.getItem('org.doubango.identity.realm'))) // //txtRealm.value = s_value; // txtRealm = ""; // } else { // // FIXME //// txtDisplayName.value = "005"; //// txtPrivateIdentity.value = "005"; //// txtPublicIdentity.value = "sip:005@sip2sip.info"; //// txtPassword.value = "005"; //// txtRealm.value = "sip2sip.info"; //// txtPhoneNumber.value = "701020"; // } //}; // //function saveCredentials() { // TODO: org.doubango.identity.... replace with vtiger // if (window.localStorage) { // window.localStorage.setItem('org.doubango.identity.display_name', txtDisplayName.value); // window.localStorage.setItem('org.doubango.identity.impi', txtPrivateIdentity.value); // window.localStorage.setItem('org.doubango.identity.impu', txtPublicIdentity.value); // window.localStorage.setItem('org.doubango.identity.password', txtPassword.value); // window.localStorage.setItem('org.doubango.identity.realm', txtRealm.value); // } //}; // //function loadCallOptions() { // TODO: org.doubango..... replace with vtiger // if (window.localStorage) { // var s_value; // if ((s_value = window.localStorage.getItem('org.doubango.call.phone_number'))) // //txtPhoneNumber.value = s_value; // txtPhoneNumber = ""; // bDisableVideo = (window.localStorage.getItem('org.doubango.expert.disable_video') == "true"); // // txtCallStatus.innerHTML = '<i>Video ' + (bDisableVideo ? 'disabled' : 'enabled') + '</i>'; // } //} // //function saveCallOptions() { // TODO: org.doubango..... replace with vtiger // if (window.localStorage) { // window.localStorage.setItem('org.doubango.call.phone_number', txtPhoneNumber.value); // window.localStorage.setItem('org.doubango.expert.disable_video', bDisableVideo ? "true" : "false"); // } //} //some my func from https://www.doubango.org/sipml5/docgen/index.html?svn=241#ProgramingwiththeAPI // register sipml5 //function register() //{ // SIPml.init( // function (e) { // var stack = new SIPml.Stack({realm: 'example.org', impi: 'bob', impu: 'sip:bob@example.org', password: 'mysecret', // events_listener: {events: 'started', listener: function (e) { // var callSession = stack.newSession('call-audiovideo', { // video_local: document.getElementById('video-local'), // video_remote: document.getElementById('video-remote'), // audio_remote: document.getElementById('audio-remote') // }); // callSession.call('alice'); // } // } // }); // stack.start(); // } // ); //} // sends SIP REGISTER request to login function sipRegister() { // catch exception for IE (DOM not ready) try { if (!txtRealm || !txtPrivateIdentity || !txtPublicIdentity) { txtRegStatus.innerHTML = '<b>No data about SIP account</b>'; return; } var o_impu = tsip_uri.prototype.Parse(txtPublicIdentity); if (!o_impu || !o_impu.s_user_name || !o_impu.s_host) { txtRegStatus.innerHTML = "<b>[" + txtPublicIdentity + "] is not a valid Public identity</b>"; return; } // enable notifications if not already done if (window.webkitNotifications && window.webkitNotifications.checkPermission() != 0) { window.webkitNotifications.requestPermission(); } // save credentials //TODO //saveCredentials(); // update debug level to be sure new values will be used if the user haven't updated the page SIPml.setDebugLevel((window.localStorage && window.localStorage.getItem('org.doubango.expert.disable_debug') == "true") ? "error" : "info"); // create SIP stack oSipStack = new SIPml.Stack({ realm: txtRealm, impi: txtPrivateIdentity, impu: txtPublicIdentity, password: txtPassword, display_name: txtDisplayName, //websocket_proxy_url: (window.localStorage ? window.localStorage.getItem('org.doubango.expert.websocket_server_url') : null), websocket_proxy_url: txtWebsocketServerUrl, outbound_proxy_url: (window.localStorage ? window.localStorage.getItem('org.doubango.expert.sip_outboundproxy_url') : null), //ice_servers: (window.localStorage ? window.localStorage.getItem('org.doubango.expert.ice_servers') : null), ice_servers: txtIceServers, enable_rtcweb_breaker: (window.localStorage ? window.localStorage.getItem('org.doubango.expert.enable_rtcweb_breaker') == "true" : false), events_listener: { events: '*', listener: onSipEventStack }, enable_early_ims: (window.localStorage ? window.localStorage.getItem('org.doubango.expert.disable_early_ims') != "true" : true), // Must be true unless you're using a real IMS network enable_media_stream_cache: (window.localStorage ? window.localStorage.getItem('org.doubango.expert.enable_media_caching') == "true" : false), bandwidth: (window.localStorage ? tsk_string_to_object(window.localStorage.getItem('org.doubango.expert.bandwidth')) : null), // could be redefined a session-level video_size: (window.localStorage ? tsk_string_to_object(window.localStorage.getItem('org.doubango.expert.video_size')) : null), // could be redefined a session-level sip_headers: [ //TODO from site { name: 'User-Agent', value: 'IM-client/OMA1.0 sipML5-v1.2015.03.18' }, { name: 'Organization', value: 'Doubango Telecom' } ] } ); if (oSipStack.start() != 0) { txtRegStatus.innerHTML = '<b>Failed to start the SIP stack</b>'; } else return; } catch (e) { txtRegStatus.innerHTML = "<b>2:" + e + "</b>"; } } // sends SIP REGISTER (expires=0) to logout function sipUnRegister() { if (oSipStack) { oSipStack.stop(); // shutdown all sessions } } // makes a call (SIP INVITE) function sipCall(s_type) { console.log("sipCall log = "+s_type); if (oSipStack && !oSipSessionCall && !tsk_string_is_null_or_empty(txtPhoneNumber)) { // if(s_type == 'call-screenshare') { // if(!SIPml.isScreenShareSupported()) { // alert('Screen sharing not supported. Are you using chrome 26+?'); // return; // } // if (!location.protocol.match('https')){ // if (confirm("Screen sharing requires https://. Do you want to be redirected?")) { // sipUnRegister(); // window.location = 'https://ns313841.ovh.net/call.htm'; // } // return; // } // } btnCall.disabled = true; btnHangUp.disabled = false; // if(window.localStorage) { // oConfigCall.bandwidth = tsk_string_to_object(window.localStorage.getItem('org.doubango.expert.bandwidth')); // already defined at stack-level but redifined to use latest values // oConfigCall.video_size = tsk_string_to_object(window.localStorage.getItem('org.doubango.expert.video_size')); // already defined at stack-level but redifined to use latest values // } // create call session oSipSessionCall = oSipStack.newSession(s_type, oConfigCall); // make call if (oSipSessionCall.call(txtPhoneNumber) != 0) { oSipSessionCall = null; txtCallStatus = 'Failed to make call'; btnCall.disabled = false; btnHangUp.disabled = true; return; } //saveCallOptions(); } else if (oSipSessionCall) { txtCallStatus.innerHTML = '<i>Connecting...</i>'; oSipSessionCall.accept(oConfigCall); } } // terminates the call (SIP BYE or CANCEL) function sipHangUp() { if (oSipSessionCall) { txtCallStatus.innerHTML = '<i>Terminating the call...</i>'; oSipSessionCall.hangup({events_listener: { events: '*', listener: onSipEventSession }}); } } function startRingTone() { try { ringtone.play(); } catch (e) { } } function stopRingTone() { try { ringtone.pause(); } catch (e) { } } function startRingbackTone() { try { ringbacktone.play(); } catch (e) { } } function stopRingbackTone() { try { ringbacktone.pause(); } catch (e) { } } function showNotifICall(s_number) { // permission already asked when we registered if (window.webkitNotifications && window.webkitNotifications.checkPermission() == 0) { if (oNotifICall) { oNotifICall.cancel(); } oNotifICall = window.webkitNotifications.createNotification('images/sipml-34x39.png', 'Incaming call', 'Incoming call from ' + s_number); oNotifICall.onclose = function () { oNotifICall = null; }; oNotifICall.show(); } } function uiOnConnectionEvent(b_connected, b_connecting) { // should be enum: connecting, connected, terminating, terminated //btnRegister.disabled = b_connected || b_connecting; //btnUnRegister.disabled = !b_connected && !b_connecting; btnCall.disabled = !(b_connected && tsk_utils_have_webrtc() && tsk_utils_have_stream()); btnHangUp.disabled = !oSipSessionCall; } function uiBtnCallSetText(s_text) { switch(s_text) { case "Call": { //var bDisableCallBtnOptions = (window.localStorage && window.localStorage.getItem('org.doubango.expert.disable_callbtn_options') == "true"); //btnCall.value = btnCall.innerHTML = bDisableCallBtnOptions ? 'Call' : 'Call <span id="spanCaret" class="caret">'; btnCall.value = btnCall.innerHTML = "Call"; //btnCall.setAttribute("class", bDisableCallBtnOptions ? "btn btn-primary" : "btn btn-primary dropdown-toggle"); //btnCall.onclick = bDisableCallBtnOptions ? function(){ sipCall(bDisableVideo ? 'call-audio' : 'call-audiovideo'); } : null; btnCall.onclick = function(){ sipCall('call-audio'); }; //ulCallOptions.style.visibility = bDisableCallBtnOptions ? "hidden" : "visible"; // if(!bDisableCallBtnOptions && ulCallOptions.parentNode != divBtnCallGroup){ // divBtnCallGroup.appendChild(ulCallOptions); // } // else if(bDisableCallBtnOptions && ulCallOptions.parentNode == divBtnCallGroup) { // document.body.appendChild(ulCallOptions); // } break; } default: { btnCall.value = btnCall.innerHTML = s_text; //btnCall.setAttribute("class", "btn btn-primary"); btnCall.onclick = function(){ sipCall('call-audio'); }; //btnCall.disabled = true;//todo // ulCallOptions.style.visibility = "hidden"; // if(ulCallOptions.parentNode == divBtnCallGroup){ // document.body.appendChild(ulCallOptions); // } break; } } } function uiCallTerminated(s_description){ uiBtnCallSetText("Call"); btnHangUp.value = 'HangUp'; //btnHoldResume.value = 'hold'; //btnMute.value = "Mute"; btnCall.disabled = false; btnHangUp.disabled = true; //if (window.btnBFCP) window.btnBFCP.disabled = true; oSipSessionCall = null; stopRingbackTone(); stopRingTone(); txtCallStatus.innerHTML = "<i>" + s_description + "</i>"; //uiVideoDisplayShowHide(false); //divCallOptions.style.opacity = 0; if (oNotifICall) { oNotifICall.cancel(); oNotifICall = null; } //uiVideoDisplayEvent(false, false); //uiVideoDisplayEvent(true, false); setTimeout(function () { if (!oSipSessionCall) txtCallStatus.innerHTML = ''; }, 2500); } // Callback function for SIP Stacks function onSipEventStack(e /*SIPml.Stack.Event*/) { tsk_utils_log_info('==stack event = ' + e.type); switch (e.type) { case 'started': { // catch exception for IE (DOM not ready) try { // LogIn (REGISTER) as soon as the stack finish starting oSipSessionRegister = this.newSession('register', { expires: 200, events_listener: { events: '*', listener: onSipEventSession }, sip_caps: [ { name: '+g.oma.sip-im', value: null }, //{ name: '+sip.ice' }, // rfc5768: FIXME doesn't work with Polycom TelePresence { name: '+audio', value: null }, { name: 'language', value: '\"en,fr\"' } ] }); oSipSessionRegister.register(); } catch (e) { txtRegStatus.value = txtRegStatus.innerHTML = "<b>1:" + e + "</b>"; //btnRegister.disabled = false; } break; } case 'stopping': case 'stopped': case 'failed_to_start': case 'failed_to_stop': { console.log("newer"); var bFailure = (e.type == 'failed_to_start') || (e.type == 'failed_to_stop'); oSipStack = null; oSipSessionRegister = null; oSipSessionCall = null; uiOnConnectionEvent(false, false); stopRingbackTone(); stopRingTone(); //uiVideoDisplayShowHide(false); //divCallOptions.style.opacity = 0; txtCallStatus.innerHTML = ''; txtRegStatus.innerHTML = bFailure ? "<i>Disconnected: <b>" + e.description + "</b></i>" : "<i>Disconnected</i>"; break; } case 'i_new_call': { if (oSipSessionCall) { // do not accept the incoming call if we're already 'in call' e.newSession.hangup(); // comment this line for multi-line support } else { oSipSessionCall = e.newSession; // start listening for events oSipSessionCall.setConfiguration(oConfigCall); uiBtnCallSetText('Answer'); btnHangUp.value = 'Reject'; btnCall.disabled = false; btnHangUp.disabled = false; startRingTone(); var sRemoteNumber = (oSipSessionCall.getRemoteFriendlyName() || 'unknown'); txtCallStatus.innerHTML = "<i>Incoming call from [<b>" + sRemoteNumber + "</b>]</i>"; showNotifICall(sRemoteNumber); } break; } case 'm_permission_requested': { //divGlassPanel.style.visibility = 'visible'; break; } case 'm_permission_accepted': case 'm_permission_refused': { //divGlassPanel.style.visibility = 'hidden'; if(e.type == 'm_permission_refused'){ uiCallTerminated('Media stream permission denied'); } break; } case 'starting': default: break; } }; // Callback function for SIP sessions (INVITE, REGISTER, MESSAGE...) function onSipEventSession(e /* SIPml.Session.Event */) { tsk_utils_log_info('==session event = ' + e.type); switch (e.type) { case 'connecting': case 'connected': { var bConnected = (e.type == 'connected'); if (e.session == oSipSessionRegister) { uiOnConnectionEvent(bConnected, !bConnected); txtRegStatus.innerHTML = "<i>" + e.description + "</i>"; } else if (e.session == oSipSessionCall) { btnHangUp.value = 'HangUp'; btnCall.disabled = true; btnHangUp.disabled = false; //btnTransfer.disabled = false; //if (window.btnBFCP) window.btnBFCP.disabled = false; if (bConnected) { stopRingbackTone(); stopRingTone(); if (oNotifICall) { oNotifICall.cancel(); oNotifICall = null; } } txtCallStatus.innerHTML = "<i>" + e.description + "</i>"; //divCallOptions.style.opacity = bConnected ? 1 : 0; if (SIPml.isWebRtc4AllSupported()) { // IE don't provide stream callback //uiVideoDisplayEvent(false, true); //uiVideoDisplayEvent(true, true); } } break; } // 'connecting' | 'connected' case 'terminating': case 'terminated': { if (e.session == oSipSessionRegister) { uiOnConnectionEvent(false, false); oSipSessionCall = null; oSipSessionRegister = null; txtRegStatus.innerHTML = "<i>" + e.description + "</i>"; } else if (e.session == oSipSessionCall) { uiCallTerminated(e.description); } break; } // 'terminating' | 'terminated' case 'm_stream_video_local_added': { if (e.session == oSipSessionCall) { //uiVideoDisplayEvent(true, true); } break; } case 'm_stream_video_local_removed': { if (e.session == oSipSessionCall) { //uiVideoDisplayEvent(true, false); } break; } case 'm_stream_video_remote_added': { if (e.session == oSipSessionCall) { //uiVideoDisplayEvent(false, true); } break; } case 'm_stream_video_remote_removed': { if (e.session == oSipSessionCall) { //uiVideoDisplayEvent(false, false); } break; } case 'm_stream_audio_local_added': case 'm_stream_audio_local_removed': case 'm_stream_audio_remote_added': case 'm_stream_audio_remote_removed': { break; } case 'i_ect_new_call': { oSipSessionTransferCall = e.session; break; } case 'i_ao_request': { if(e.session == oSipSessionCall){ var iSipResponseCode = e.getSipResponseCode(); if (iSipResponseCode == 180 || iSipResponseCode == 183) { startRingbackTone(); txtCallStatus.innerHTML = '<i>Remote ringing...</i>'; } } break; } case 'm_early_media': { if(e.session == oSipSessionCall){ stopRingbackTone(); stopRingTone(); txtCallStatus.innerHTML = '<i>Early media started</i>'; } break; } case 'm_local_hold_ok': { if(e.session == oSipSessionCall){ if (oSipSessionCall.bTransfering) { oSipSessionCall.bTransfering = false; // this.AVSession.TransferCall(this.transferUri); } //btnHoldResume.value = 'Resume'; //btnHoldResume.disabled = false; txtCallStatus.innerHTML = '<i>Call placed on hold</i>'; oSipSessionCall.bHeld = true; } break; } case 'm_local_hold_nok': { if(e.session == oSipSessionCall){ oSipSessionCall.bTransfering = false; //btnHoldResume.value = 'Hold'; //btnHoldResume.disabled = false; txtCallStatus.innerHTML = '<i>Failed to place remote party on hold</i>'; } break; } case 'm_local_resume_ok': { if(e.session == oSipSessionCall){ oSipSessionCall.bTransfering = false; //btnHoldResume.value = 'Hold'; //btnHoldResume.disabled = false; txtCallStatus.innerHTML = '<i>Call taken off hold</i>'; oSipSessionCall.bHeld = false; if (SIPml.isWebRtc4AllSupported()) { // IE don't provide stream callback yet //uiVideoDisplayEvent(false, true); //uiVideoDisplayEvent(true, true); } } break; } case 'm_local_resume_nok': { if(e.session == oSipSessionCall){ oSipSessionCall.bTransfering = false; //btnHoldResume.disabled = false; txtCallStatus.innerHTML = '<i>Failed to unhold call</i>'; } break; } case 'm_remote_hold': { if(e.session == oSipSessionCall){ txtCallStatus.innerHTML = '<i>Placed on hold by remote party</i>'; } break; } case 'm_remote_resume': { if(e.session == oSipSessionCall){ txtCallStatus.innerHTML = '<i>Taken off hold by remote party</i>'; } break; } case 'm_bfcp_info': { if(e.session == oSipSessionCall){ txtCallStatus.innerHTML = 'BFCP Info: <i>'+ e.description +'</i>'; } break; } case 'o_ect_trying': { if(e.session == oSipSessionCall){ txtCallStatus.innerHTML = '<i>Call transfer in progress...</i>'; } break; } case 'o_ect_accepted': { if(e.session == oSipSessionCall){ txtCallStatus.innerHTML = '<i>Call transfer accepted</i>'; } break; } case 'o_ect_completed': case 'i_ect_completed': { if(e.session == oSipSessionCall){ txtCallStatus.innerHTML = '<i>Call transfer completed</i>'; //btnTransfer.disabled = false; if (oSipSessionTransferCall) { oSipSessionCall = oSipSessionTransferCall; } oSipSessionTransferCall = null; } break; } case 'o_ect_failed': case 'i_ect_failed': { if(e.session == oSipSessionCall){ txtCallStatus.innerHTML = '<i>Call transfer failed</i>'; //btnTransfer.disabled = false; } break; } case 'o_ect_notify': case 'i_ect_notify': { if(e.session == oSipSessionCall){ txtCallStatus.innerHTML = "<i>Call Transfer: <b>" + e.getSipResponseCode() + " " + e.description + "</b></i>"; if (e.getSipResponseCode() >= 300) { if (oSipSessionCall.bHeld) { oSipSessionCall.resume(); } //btnTransfer.disabled = false; } } break; } case 'i_ect_requested': { if(e.session == oSipSessionCall){ var s_message = "Do you accept call transfer to [" + e.getTransferDestinationFriendlyName() + "]?";//FIXME if (confirm(s_message)) { txtCallStatus.innerHTML = "<i>Call transfer in progress...</i>"; oSipSessionCall.acceptTransfer(); break; } oSipSessionCall.rejectTransfer(); } break; } } }
'use strict'; angular.module('myShoppinglistApp') .controller ( 'StoresCtrl' , function ($http) { var vm = this; vm.allStores = []; vm.selectedStore = {}; vm.updateMode = false; vm.Add_Update = Add_Update; vm.SelectStore = SelectStore; vm.DeleteStore = DeleteStore; Init(); function Init() { GetAllStores(); } function Add_Update() { vm.updateMode ? UpdateStore(vm.selectedStore) : AddStore(vm.selectedStore); vm.selectedStore = {}; } function AddStore(store) { $http.post('/api/stores', store) .success ( function() { GetAllStores(); } ); }; function UpdateStore(store) { $http.put('/api/stores/' + store._id, store) .success ( function() { GetAllStores(); vm.updateMode = false; } ); }; function GetAllStores () { $http.get('/api/stores') .success ( function(allStores) { vm.allStores = allStores; } ); } function SelectStore(store) { vm.selectedStore = store; vm.updateMode = true; } function DeleteStore(store) { $http.delete('/api/stores/' + store._id) .success ( function() { GetAllStores(); } ); } } );
/** @jsx React.DOM */ var React = require('react'), Router = require('react-router'); var Util = require('../../util'), Actions = require('../../actions'), AuthService = require('../../services/auth'), Validator = require('validator'); var Header = require('./header'); // React-router variables var Link = Router.Link; var steps = [ // First Step function (component) { return( <div> <div>Enter your email address and we’ll send you a link to reset your password. <br /></div> <div className="form"> <div className="label">Email</div> <input type="text" className="textbox" ref="email" id="email-textbox" value={component.state.email} onChange={component.onEmailUpdated} disabled={component.state.waiting}/> </div> <div className={'flash' + (component.state.toastMessage ? ' visible' : '')}> {component.state.toastMessage} </div> <div className="divider"/> <button type="submit" id="request-password-button" onClick={component.onSubmitClicked} disabled={component.state.waiting}>Request new password</button> </div> ); }, // Second Step function (component) { return ( <div className="wrapper">Help is on the way.</div> ); } ]; var Forgot = React.createClass({ getInitialState: function() { return { toastMessage: undefined, step: 0, email: '', waiting: false }; }, componentDidMount: function() { Actions.changePageTitle('Reset Password'); }, componentWillUnmount: function() { }, onEmailUpdated: function(event) { this.setState({ email: event.target.value, toastMessage: undefined }); }, onEnterKeyPress: function(event) { if (event.keyCode === 13) { // Enter was pressed - submit the form this.submitRequest(); } }, onSubmitClicked: function() { this.submitRequest(); }, submitRequest: function() { var email = this.state.email; var component = this; if (!Validator.isEmail(email)) { this.setState({ toastMessage: 'Must be a correctly formatted email address' }); } else { AuthService.requestResetPassword(email, function(res) { if (res.ok) { // This means everything went just fine if (res.body.Result){ component.setState({ step: 1 }); } else { component.setState({ toastMessage: res.body.InfoMessages[0].Text }); } console.log('Response from requestResetPassword: ', JSON.stringify(res.body)); } else { console.log('Error from requestResetPassword: ', res.text); } }); } }, render: function() { return ( <div id="reset-password" className="page"> <Header /> <div className="spotlight"/> <div id="content"> <div className="card"> <div className="wrapper"> <h1> <span className={this.state.waiting ? 'hidden' : ''}>Reset Password</span> <i className={'fa fa-refresh fa-spin' + (this.state.waiting ? '' : ' hidden')}></i> </h1> <div className="divider"/> {(steps[this.state.step])(this)} </div> </div> </div> </div> ); } }); module.exports = Forgot;
angular.module('starter.controllers', []) .controller('DashCtrl', function($scope, $cordovaGeolocation, uiGmapGoogleMapApi, uiGmapIsReady, ngGPlacesAPI) { var posOptions = {timeout: 10000, enableHighAccuracy: false}; // get user location with ngCordova geolocation plugin $cordovaGeolocation .getCurrentPosition(posOptions) .then(function (position) { $scope.lat = position.coords.latitude; $scope.long = position.coords.longitude; // get nearby places once we have user loc in lat & long ngGPlacesAPI.nearbySearch({ latitude: $scope.lat, longitude: $scope.long }).then( function(data){ console.log('returned with places data', data); $scope.places = data; return data; }); // create new map with your location uiGmapGoogleMapApi.then(function(maps){ $scope.control = {}; $scope.myMap = { center: { latitude: $scope.lat, longitude: $scope.long }, zoom : 14 }; $scope.myMarker = { id: 1, coords: { latitude: $scope.lat, longitude: $scope.long }, options: {draggable:false} }; }); }, function(err) { // error }); $scope.getMap = function() { var map1 = $scope.control.getGMap(); console.log('map is:', map1); console.log('with places:', $scope.places); }; uiGmapIsReady.promise(1).then(function(instances) { instances.forEach(function(inst) { var map = inst.map; var uuid = map.uiGmap_id; var mapInstanceNumber = inst.instance; // Starts at 1. console.log('from map is ready:', map, uuid, mapInstanceNumber); }); }); }) .controller('ChatsCtrl', function($scope, Chats) { $scope.chats = Chats.all(); $scope.remove = function(chat) { Chats.remove(chat); } }) .controller('ChatDetailCtrl', function($scope, $stateParams, Chats) { $scope.chat = Chats.get($stateParams.chatId); }) .controller('AccountCtrl', function($scope) { $scope.settings = { enableFriends: true }; });
var books = localStorage.getItem("books"); if (!books) { books = []; } else { books = JSON.parse(books); } var BookManager = /** @class */ (function () { function BookManager() { this.table = document.getElementById("myTable"); } BookManager.prototype.searchBooks = function (searchparam, books, paramType) { if (paramType === "bookId") { return books[paramType].indexOf(searchparam) >= 0; } return books[paramType].toLowerCase().indexOf(searchparam) >= 0; }; BookManager.prototype.display = function (searchparam, paramType) { if (searchparam === void 0) { searchparam = ""; } if (paramType === void 0) { paramType = ""; } this.table.innerHTML = "<tr>\n <th> Book ID</th><th> Title</th><th>Author</th><th>Rating</th><th>Action</th></tr>"; for (var i = 0; i < books.length; i++) { var row = void 0; var disFlag = true; if (searchparam.length > 0 && paramType.length > 0 && paramType !== "selected") { if (!this.searchBooks(searchparam, books[i], paramType)) { disFlag = false; } } if (disFlag) { row = "<tr>\n <td>" + books[i].bookId + "</td>\n <td>" + books[i].title + "</td>\n <td>" + books[i].author + "</td>\n <td>" + books[i].rating + "</td>\n <td>\n <button class=\"delete\" id=\"deleteId\" style=\"border:none;background-color:inherit;\">\n \n <span id=\"span\" class=\"material-icons\" style=color:red;\">delete</span></button>\n \n </td>\n\n </tr>"; this.table.innerHTML += row; } } }; BookManager.prototype.searchResult = function () { var optionSelected = document.getElementById("drop"); var paramType = optionSelected.value; var searchText = document.getElementById("textSearch"); this.display(searchText.value, paramType); }; BookManager.prototype.delete = function (item) { books.splice(item.rowIndex - 1, 1); localStorage.setItem("books", JSON.stringify(books)); this.display(); }; BookManager.prototype.addBook = function () { var temp = books.length + 1; /* let id:string=temp.toString(); */ var id = document.getElementById("bookId"); var name = document.getElementById("bookName"); var author = document.getElementById("author"); var rating = document.getElementById("rating"); if (id.value !== "" && name.value !== "" && author.value !== "" && rating.value !== "") { var item = { bookId: id.value, title: name.value.toUpperCase(), author: author.value.toUpperCase(), rating: rating.value }; books.push(item); localStorage.setItem("books", JSON.stringify(books)); } else { return; } }; return BookManager; }()); export { BookManager };
var images = ["f.jpg", "p.jpg", "m.jpg", "d.jpg", "pu.jpg"]; var names = ["Lunawat Family", "Paresh Lunawat", "Smital Lunawat", "Diveet Lunawat", "Purab Lunawat"]; var i = 0; function update() { i++; if(i > 4 ) { i = 0; } var updatedImage = images[i]; var updatedName = names[i]; document.getElementById("family").src = updatedImage; document.getElementById("Family_name").innerHTML = updatedName; }
function lookerFetchData(url) { url = url.replace(/(\/\w+\.)txt|html|csv(\?.*)?/, "$1csv$2"); var csvString = UrlFetchApp.fetch(url).getContentText(); var dataIn = Utilities.parseCsv(csvString); var dataOut = dataIn.map(function(row) { return row.map(function(val) { if (val == '') return ''; var timeMatch = /(\d{4})\-(\d{2})-*(\d{0,}) (\d{2}):(\d{2}):(\d{2})/.exec(val); while (timeMatch != null) { return timeMatch[1].concat("-").concat(timeMatch[2]).concat("-").concat(timeMatch[3]).concat(" ").concat(timeMatch[4]).concat(":").concat(timeMatch[5]).concat(":").concat(timeMatch[6]); }; var dateMatch = /(\d{4})\-(\d{2})-*(\d{0,})/.exec(val); while (dateMatch != null) { if (dateMatch[2] == null || dateMatch[2] == "" ) { // for YYYY return dateMatch[1]; } else if (dateMatch[3] == null || dateMatch[3] == "" ) { // for YYYY-MM return dateMatch[1].concat("-").concat(dateMatch[2]); } else { // for YYYY-MM-DD return dateMatch[1].concat("-").concat(dateMatch[2]).concat("-").concat(dateMatch[3]); } }; if (val.match(/[-a-zA-Z]/)) { return String(val) }; val = val.replace(/[^\d.]/g, ''); if (val.match(/[0-9.]+/)) return Number(val); return Number(parseInt(val)); }); }); return dataOut; }
const express = require('express'); const path = require('path'); const app = express(); /* ******* routes* ******* */ const rindex = require('./routes/index'); const rinvest = require('./routes/investor'); const renterpreneur = require('./routes/enterpreneur'); const rbank = require('./routes/bank'); const rhost_competetion = require('./routes/host_competetion'); app.set('views',path.join(__dirname,'views')); app.set('view engine','ejs'); app.use(express.static(path.join(__dirname,'static'))); app.use(rindex); app.use(rinvest); app.use(renterpreneur); app.use(rbank); app.use(rhost_competetion); app.listen(3100,()=>{ console.log('API up and running'); })
import React, { useState } from "react"; import SQUARE from "./components/square"; const App = () => { const [square, setSquare] = useState(Array(9).fill(null)); const [content, setContent] = useState(true); const calculateWin = (square) => { const win = [ [0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6], ]; for (let i = 0; i < win.length; i++) { const [a, b, c] = win[i]; if (square[a] && square[a] === square[b] && square[b] === square[c]) return square[a]; } }; const handleClick = (i) => { // const squares = [...square]; if (winner || square[i]) return; square[i] = content ? "X" : "O"; setContent(!content); setSquare(square); }; const winner = calculateWin(square); const status = winner ? `${winner} wins press f5 to restart` : content ? "X's turn" : "O's turn"; return ( <div className="app"> <div className="status">{status}</div> <div className="box"> {square.map((squr, i) => { return ( <SQUARE key={i} value={squr} onclick={() => { handleClick(i); }} /> ); })} </div> </div> ); }; export default App;
export const COLUMN_INVOICE_ITEMS = [ { header: "", data: "selected", targets: [0], orderable: false, sortable: false, width: "60px" }, { header: "Invoice Item No.", data: "invoiceItemNo", targets: [1], width: "80px", orderable: true, className: "text-center" }, { header: "Material Description", data: "materialDescription", targets: [2], width: "300px", orderable: true, className: "text-center" }, { header: "PO No.", data: "poNo", targets: [3], width: "100px", orderable: true, className: "text-center" }, { header: "PO Item No.", data: "poItemNo", targets: [4], width: "80px", orderable: true, className: "text-center" }, { header: "Invoice Amount", data: "amount", targets: [5], width: "80px", orderable: true, className: "text-center" }, { header: "Adjusted Amount", data: "adjustedAmount", targets: [6], width: "80px", orderable: true, className: "text-center" }, { header: "Currency", data: "currency", targets: [7], width: "80px", orderable: true, className: "text-center" } ];
const router = require('express').Router(); const choreSchema = require('../models/chores.js'); const authCheck = require('../middleware/authCheck'); const mongoose = require('mongoose'); const User = require('../models/users.js'); const io_client = require('socket.io-client') const nodemailer_transporter = require('../config/nodemailer/setup.js') router.post('/chore/create', authCheck, (req, res) => { let chore = new choreSchema({ title: req.body.choreName, description: req.body.description, posterFname: req.user.fname, posterLname: req.user.lname, posterId: req.user.id, state: req.body.state, schedules: req.body.schedules, zip: req.body.zip, address: req.body.address, refer: req.body.refer, city: req.body.city, phone: req.body.phone, studentAmt: req.body.studentAmt, }); chore.save( (err, createdChore) => { if(err){ return err } res.send({ success: true, choreId: createdChore._id }) }) }); router.post('/chore/apply', (req, res) => { const { choreId } = req.body choreSchema.findById(choreId, (err, retreivedChore) => { retreivedChore.applicants.push({ fname: req.user.fname, lname: req.user.lname, applicantId: req.user._id, }) retreivedChore.save((err, savedChore) => { if(err) console.log(err); User.findById(retreivedChore.posterId, (err, foundUser) => { const mailOptions = { from: 'will.neighboring@gmail.com', to: foundUser.email, subject: 'A student has applied to your chore!', html: `<h1>A student has applied to your chore</h1><a href="http://localhost/chore/post/${retreivedChore._id}" >Click here to see your listing</a>` } nodemailer_transporter.sendMail(mailOptions, (err, info) => { if(err) console.log(err) }) res.send({success: true}) }) }); } ) }) router.post('/chore/apply/check', (req, res) => { const { choreId } = req.body choreSchema.findById(choreId, (err, retreivedChore) => { let found = false for (let i = 0; i < retreivedChore.applicants.length; i++){ if(retreivedChore.applicants[i].applicantId.toString() === req.user._id.toString()){ found = true } } res.send({applied: found}) }) }) router.post('/chore/apply/cancel', (req, res) => { const { choreId } = req.body choreSchema.findById(choreId, (err, retreivedChore) => { for( let i = 0; i < retreivedChore.applicants.length; i++ ){ if(retreivedChore.applicants[i].applicantId.toString() == req.user._id.toString()){ retreivedChore.applicants.splice(i,1); } } retreivedChore.save(); res.send({success: true}) } ) }) router.post('/chore/requestStudent/fetch', (req, res) => { const {chore_id} = req.body choreSchema.findById(chore_id, (err, foundChore) => { if(err){ console.log(err); res.send({success: false, msg: 'Error!'}) } res.send(foundChore.requestedWorkers) }) }) router.post('/chore/requestStudent', (req, res) => { const { chore_id, worker_id} = req.body choreSchema.findById(chore_id, ( err, foundChore) => { if(err){ console.log(err); res.send({success : false, msg: 'Error!'}) } for(let i = 0; i < foundChore.requestedWorkers.length; i++){ if(foundChore.requestedWorkers[i] === worker_id){ foundChore.requestedWorkers.splice(i, 1); } } foundChore.requestedWorkers.push(worker_id) foundChore.save((err, savedChore) => { User.findById(worker_id, (err, foundUser) => { const mailOptions = { from: 'will.neighboring@gmail.com', to: foundUser.email, subject: 'A student has applied to your chore!', html: `<h1>A student has applied to your chore</h1><a href="http://localhost/chore/post/${foundChore._id}" >Click here to see your listing</a>` } nodemailer_transporter.sendMail(mailOptions, (err, info) => { if(err) console.log(err) }) res.send({ success: true, requestedWorkers: savedChore.requestedWorkers }); }) }); }) }) router.post('/chore/requestStudent/remove', (req, res) => { const { chore_id, worker_id} = req.body choreSchema.findById(chore_id, ( err, foundChore) => { if(err){ console.log(err); res.send({success : false, msg: 'Error!'}) } for(let i = 0; i < foundChore.requestedWorkers.length; i++){ if(foundChore.requestedWorkers[i] === worker_id){ foundChore.requestedWorkers.splice(i, 1); } } foundChore.save((err, savedChore) => { res.send({ success: true, requestedWorkers: savedChore.requestedWorkers }); }); }) }) router.post('/chore/deselectStudent', (req, res) => { const {choreId, worker} = req.body choreSchema.findById(choreId, (err, foundChore) => { if(err) console.log(err); console.log(foundChore); }) }) router.post('/chore/complete', (req, res) => { const {choreId} = req.body; choreSchema.findById(choreId, (err, foundChore) => { if(err) console.log(err); foundChore.completed = true; foundChore.save((err, savedChore) => { if(err) console.log(err); res.send({success: true}) }) }) }) router.post('/chore/rate', (req, res) => { const { chore_id, review } = req.body choreSchema.findById(chore_id, (err, foundChore) => { if(err){ console.log(err) res.send({ success: false }) } for(let i = 0; i < foundChore.requestedWorkers.length; i++){ User.findById(foundChore.requestedWorkers[i], (err, foundUser) => { foundUser.reviews.push(review); foundUser.save() }) } res.send({ success: true }) }) }) module.exports = router;
/// <reference types="Cypress" /> context('Verify that web app works correctly', () => { before(() => { cy.visit('https://web.mvoterapp.com/',{timeout:90000}) }) it("Check the candidates menu is correct",()=>{ cy.get('.col-lg-3 > .Navigation > ul > :nth-child(2) > :nth-child(1) > div.active > .text',{timeout:1000}).click() cy.location('pathname').should('include', 'candidates') cy.go('back') }) it("Check the parties menu is correct",()=>{ cy.get('.col-lg-3 > .Navigation > ul > :nth-child(3) > :nth-child(1) > .inactive > .text',{timeout:800}).click() cy.location('pathname').should('include','parties') cy.go('back') }) it("Check the how_to_vote menu is correct",()=>{ cy.get('.col-lg-3 > .Navigation > ul > :nth-child(4) > :nth-child(1) > .inactive > .text',{timeout:800}).click() cy.location('pathname').should('include','vote') cy.go('back') }) it("Check the faq menu is correct",()=>{ cy.get('.col-lg-3 > .Navigation > ul > :nth-child(5) > :nth-child(1) > .inactive > .text',{timeout:800}).click() cy.location('pathname').should('include','faq') cy.go('back') }) it("Check the news menu is correct",()=>{ cy.get('.col-lg-3 > .Navigation > ul > :nth-child(6) > :nth-child(1) > .inactive > .text',{timeout:800}).click() cy.location('pathname').should('include','news') cy.go('back') }) it("Navigate the candidates list by filtering location",()=>{ cy.get('.color-primary > [href="/location"] > .Button > .material-icons').click() cy.get(':nth-child(4) > span > .material-icons').click() cy.get(':nth-child(9) > .Collapsible__trigger').click() cy.get('.Collapsible__contentInner > :nth-child(11)').click() cy.get(':nth-child(5) > span > .material-icons').click() cy.wait(200) cy.get('.ReactModal__Content > :nth-child(17)').click() cy.get('.Location__done').click() cy.get(':nth-child(1) > .cursor-pointer > .text-center').click() cy.wait(50) cy.get(':nth-child(2) > .cursor-pointer > .text-center').click() cy.wait(50) cy.get(':nth-child(3) > .cursor-pointer > .text-center').click() cy.wait(500) cy.get(':nth-child(3) > .cursor-pointer > .text-center').click() cy.get(':nth-child(2) > :nth-child(2) > :nth-child(2) > .no-style > .Card > .CandidateList__avatar').click() cy.get('.Candidate__partyName > .material-icons').click() }) })
var productCardMarkup = ` {{#products}} <tr class="wishlist-container text-center"> <td class="wishlist-selected p-4 "> <input type="checkbox" name="" value="{{epi}}" data-product-id="{{empi}}" data-url="{{du}}" data-title="{{dt}}"> </td> <td class="p-4 "> <img class="max-w-100px" src="{{iu}}" data-variant-id="{{epi}}" /> </td> <td class="p-4 "> <p>{{ct}}</p> </td> <td class="p-4 "> <a class="max-w-100px" href="{{du}}"> <span class="visually-hidden">{{dt}}</span> </a> </td> <td class="p-4 "> <p class="variantinfo">{{variantinfo}}</p> </td> <td class="p-4 "> <p>{{pr}}</p> </td> <td class="p-4 "> <p class="wspc">In Stock</p> </td> </tr> {{/products}} `; function getVariantInfo(variants){ try { let variantKeys = ((variants && variants != "[]") ? Object.keys(JSON.parse(variants)[0]) : []) , variantinfo; if(variantKeys.length > 0){ variantinfo = variantKeys[0]; if(variantinfo == "Default Title"){ variantinfo = ""; } } else { variantinfo = ""; } return variantinfo; } catch(err){ return variants; } } function swymCallbackFn(){ // gets called once Swym is ready var wishlistContentsContainer = document.getElementById("account-wishlist-items-container"); _swat.fetchWrtEventTypeET( function(products) { // Get wishlist items var formattedWishlistedProducts = products.map(function(p){ p = SwymUtils.formatProductPrice(p); // formats product price and adds currency to product Object p.isInCart = _swat.platform.isInDeviceCart(p.epi) || (p.et == _swat.EventTypes.addToCart); p.variantinfo = (p.variants ? getVariantInfo(p.variants) : ""); return p; console.log(p) });productCardsMarkup var productCardsMarkup = SwymUtils.renderTemplateString(productCardMarkup, {products: formattedWishlistedProducts}); wishlistContentsContainer.innerHTML = productCardsMarkup; wishlistContentsContainer.innerHTML = wishlistContentsContainer.innerHTML.replace('<p class="variantinfo"></p>', 'N/A'); // attachClickListeners(); attachDelButton(); attachAddToCartButton(); }, window._swat.EventTypes.addToWishList ); } if(!window.SwymCallbacks){ window.SwymCallbacks = []; } window.SwymCallbacks.push(swymCallbackFn); setTimeout(function(){ // SELECT ALL ITEMS IN WISHLIST $('.wl-selectall').click(function(){ $('.wishlist-selected input[type=checkbox]').prop('checked', true); }) // DESELECT ALL ITEMS IN WISHLIST $('.wl-deselectall').click(function(){ $('.wishlist-selected input[type=checkbox]').prop('checked', false); }) }, 1000); function attachDelButton(){ // DELETE SELECTED ITEMS IN WISHLIST $(".wl-delete").click(function(e){ $.each($(".wishlist-selected input[type=checkbox]:checked"), function(){ var variantId = $(this).val(); window._swat.removeFromWishList( { "epi": variantId }, function(r) { location.reload(); } ); }); }); } function attachAddToCartButton(){ $(".wl-addtobag").click(function(e){ var cartObj = "", total = $(".wishlist-selected input[type=checkbox]:checked").length, result = null, OOSValidate = ""; // INCLUDE THIS IF BUFFER NEEDED // var bsMinus = 5; // var regMinus = 3; // var noMinus = 0; // var subStk = 0; // END INCLUDE THIS IF BUFFER NEEDED var totalStk = 0; $.each($(".wishlist-selected input[type=checkbox]:checked"), function(index){ var variantId = $(this).val(), productId = $(this).data('product-id'), productUrl = $(this).data('url'), cartData = "updates["+variantId+"]=1", totalstock = 0; let $t = $(this), url = $t.data('url') + '?view=variantjson' // MINUS PRODUCT INCART QUANTITY // incartQty = $('.mini-shopping-cart-wrapper').children('.mini-cart-products[data-incartid="'+variantId+'"]').data('incart'); // incartQty = (isNaN(incartQty) ? 0 : incartQty); // END OF MINUS PRODUCT INCART QUANTITY if (index === total - 1) { cartObj+= cartData } else { cartObj+= (cartData + "&") } $.ajax({ url: url, method: "GET", success: function(data){ let obj = JSON.parse(data); // totalstock = obj[variantId] - incartQty; totalstock = obj[variantId]; var pTags = obj.product_tag; totalStk = totalstock; // FOR BUFFER WITH SPECIFIC TAG // if(pTags.indexOf('Bestseller') > -1) { // totalStk = totalstock - bsMinus; // }else if(pTags.indexOf('regular') > -1){ // totalStk = totalstock - regMinus; // }else{ // totalStk = totalstock - noMinus; // } // END BUFFER WITH SPECIFIC TAG // OUT OF STOCK VALIDATOR if(totalStk < 1 ){ OOSValidate +=false + " "; }else{ OOSValidate +=true + " "; } // END OUT OF STOCK VALIDATOR } }); }); setTimeout(function(){ if(OOSValidate.includes("false")){ alert('please uncheck out of stock items') } else { jQuery.post('/cart/update.js', cartObj); // REMOVING ITEM AFTER ADD TO CART // $.each($(".wishlist-selected input[type=checkbox]:checked"), function(index){ // var removeId = $(this).val(); // window._swat.removeFromWishList( // { // "epi": removeId // }, // function(r) { // } // ); // }); // END OF REMOVING ITEM AFTER ADD TO CART // RELOAD AFTER ADD TO CART setTimeout(function(){ // window.location.reload(); window.location = 'https://lookatme.com.ph/cart' }, 1000); // END OF RELOAD AFTER ADD TO CART } }, 1000); }); } function forOutOfStock(){ $('#account-wishlist-items-container tr input').each(function(i,e){ let $t = $(this), url = $t.data('url') + '?view=variantjson', variantId = $(this).val(); // var bsMinus = 5; // var regMinus = 3; // var noMinus = 0; // var subStk = 0; var totalStk = 0; // var incartQty = $('.mini-shopping-cart-wrapper').children('.mini-cart-products[data-incartid="'+variantId+'"]').data('incart'); // incartQty = (isNaN(incartQty) ? 0 : incartQty); $.ajax({ url: url, method: "GET", success: function(data){ let obj = JSON.parse(data); // var totalstock = obj[variantId] - incartQty; var totalstock = obj[variantId]; var pTags = obj.product_tag; totalStk = totalstock; // if(pTags.indexOf('Bestseller') > -1) { // totalStk = totalstock - bsMinus; // }else if(pTags.indexOf('regular') > -1){ // totalStk = totalstock - regMinus; // }else{ // totalStk = totalstock - noMinus; // } if(totalStk < 1){ $t.closest('.wishlist-container').find('.wspc').empty().append("Out of Stock"); } } }); }); }; window.addEventListener('load', function() { setTimeout(function(){ forOutOfStock(); }, 1000); })
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.defineConfig = void 0; function defineConfig(config) { return Object.assign({ protocol: 'ftp' }, config); } exports.defineConfig = defineConfig; exports.default = {};
import TreeList from './ui.tree_list.base'; export default TreeList; import './ui.tree_list.state_storing'; import './ui.tree_list.column_chooser'; import './ui.tree_list.master_detail'; import './ui.tree_list.editing'; import './ui.tree_list.editing_row_based'; import './ui.tree_list.editing_form_based'; import './ui.tree_list.editing_cell_based'; import './ui.tree_list.validating'; import './ui.tree_list.virtual_scrolling'; import './ui.tree_list.filter_row'; import './ui.tree_list.header_filter'; import './ui.tree_list.filter_sync'; import './ui.tree_list.filter_builder'; import './ui.tree_list.filter_panel'; import './ui.tree_list.pager'; import './ui.tree_list.columns_resizing_reordering'; import './ui.tree_list.column_fixing'; import './ui.tree_list.adaptivity'; import './ui.tree_list.selection'; import './ui.tree_list.search'; import './ui.tree_list.keyboard_navigation'; import './ui.tree_list.virtual_columns'; import './ui.tree_list.focus'; import './ui.tree_list.row_dragging';
import React from 'react'; import { useRecoilValue } from 'recoil'; import { totalsState } from './state'; function Totals() { const totals = useRecoilValue(totalsState); return ( <div className="container"> <h2 className="title">Totals</h2> <p>Subtotal: ${totals.subtotal.toFixed(2)}</p> <p>Shipping: ${totals.shipping.toFixed(2)}</p> <p><strong>Total: ${totals.total}</strong></p> </div> ) } export default Totals
import compose from 'koa-compose'; import postsRouter from './posts'; export default function router() { return compose([ postsRouter.middleware(), ]); }
function areaOfTriangle(sideOne ,sideTwo, sideThree){ semiperimeter = 0.5*(sideOne + sideTwo + sideThree); area = Math.sqrt(semiperimeter * (semiperimeter-sideOne) * (semiperimeter-sideTwo) * (semiperimeter-sideThree)); return area; }
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var point_1 = require("./point"); var like_button_1 = require("./like-button"); //catch compile time errors //======== function ======== function log(message) { console.log(message); } var message = 'Hello World'; log(message); //======== var vs let variable declaration ======== function doSomething() { for (var i = 0; i < 5; i++) { console.log(i); } console.log("finally " + i); //you can catch error at compile-time } doSomething(); //======== data type ======== var a; var b; var c; var d; var e = [1, 2, 3]; var f = [1, true, 'a', false]; //======== any data type usage ======== var count; count = 'a'; //compilation error count = 5; //======== enum ================ var Color; (function (Color) { Color[Color["Red"] = 0] = "Red"; Color[Color["Green"] = 1] = "Green"; Color[Color["Yellow"] = 2] = "Yellow"; })(Color || (Color = {})); ; // explicit define the value for each colour so when you need to add more value, you know where to add var backgroundColor = Color.Green; //======== type assertion, casting ======== var message1; message1 = "abc"; //let endWithC = (<string> message1).endsWith('c'); //let endWithA = (message1 as string).endsWith('a'); //console.log(endWithC); //console.log(endWithA); //======== arrow function ======== var log1 = function (message) { console.log(message); }; var log2 = function (message) { return console.log(message); }; var log3 = function () { return console.log(message); }; ////======== object ======== var point1 = new point_1.Point(); point1.X = 50; point1.Y = 100; point1.draw(); function drawPoint(point) { console.log(point.X); console.log(point.Y); } var point = { "x": 4, "y": 5 }; //========implement a like button ====== var likeButton = new like_button_1.LikeButton(); while (1) { likeButton.onClick(); console.log(likeButton.LikeCount); console.log(likeButton.IsSelected); }
// @tag full-page // @require C:\webapps\dlmsprint2a\app.js
$(function () { initPostTable(); initSelTable(); $("#selPostModel .btn-close").click(function () { closeModal(); }); $("#selSaveBtn").click(function(){ var ids = $("#selTable").bootstrapTable("getSelections"); var ids_arr = ""; if (!ids.length) { $Jtk.n_warning("请勾选需要关联的关联关系!"); return; } for (var i = 0; i < ids.length; i++) { ids_arr += ids[i].id; if (i !== (ids.length - 1)) ids_arr += ","; } $Jtk.confirm({ text: "确定选中关联?", confirmButtonText: "确定" }, function () { $.post('/system/cms/post/saveRelation', {"postIds": ids_arr,"termId":termId}, function (r) { if (r.code === 200) { $Jtk.n_success(r.msg); refresh(); } else { $Jtk.n_danger(r.msg); } }); }); }) }); function initPostTable() { var setting = { idField: 'id', uniqueId: 'id', toolbar:'#toolbar', sidePagination: 'server', showColumns: true, pagination:true, pageSize:10, url: '/system/cms/post/sellist?postType='+postType+'&termId='+termId, columns: [ { field: 'selectItem', checkbox: true }, { title: '编号', field: 'id', width: '50px' }, { title: '标题', field: 'postTitle' }, { title: '评论数', field: 'commentCount' }, { title: '创建时间', field: 'createTime' }, { field: 'operate', title: '操作', align: 'center', events : { 'click .post-delete': function (e, value, row, index) { delPost(row.id); } }, formatter: operateFormatter } ] }; $Jtk.initTable('postTable', setting); } function initSelTable() { var setting = { idField: 'id', uniqueId: 'id', sidePagination: 'server', showColumns: true, pagination:true, pageSize:10, url: '/system/cms/post/sellist?postType='+postType, columns: [ { field: 'selSelectItem', checkbox: true }, { title: '编号', field: 'id', width: '50px' }, { title: '标题', field: 'postTitle' }, { title: '评论数', field: 'commentCount' }, { title: '创建时间', field: 'createTime' } ] }; $Jtk.initTable('selTable', setting); } function refresh() { $Jtk.refreshTable("postTable"); } function closeModal() { var $modal = $("#selPostModel"); $modal.find("button.btn-hide").attr("data-dismiss", "modal").trigger('click'); } // 操作按钮 function operateFormatter(value, row, index) { return [ '<a type="button" class="post-delete btn btn-xs btn-default" title="取消" data-toggle="tooltip"><i class="mdi mdi-delete"></i></a>' ].join(''); } function delPost(id){ $Jtk.confirm({ text:" 确定要删除关联?", confirmButtonText:"确定" },function(){ $.post('/system/cms/post/delRelation', {"postIds": id,"termId":termId}, function (r) { if (r.code === 200) { $Jtk.n_success(r.msg); refresh(); } else { $Jtk.n_danger(r.msg); } }); }) } function cancelRelation() { var ids = $("#postTable").bootstrapTable("getSelections"); var ids_arr = ""; if (!ids.length) { $Jtk.n_warning("请勾选需要删除的关联关系!"); return; } for (var i = 0; i < ids.length; i++) { ids_arr += ids[i].id; if (i !== (ids.length - 1)) ids_arr += ","; } $Jtk.confirm({ text: "确定删除选中关联?", confirmButtonText: "确定删除" }, function () { $.post('/system/cms/post/delRelation', {"postIds": ids_arr,"termId":termId}, function (r) { if (r.code === 200) { $Jtk.n_success(r.msg); refresh(); } else { $Jtk.n_danger(r.msg); } }); }); }
// A port of the Firefox extension // https://github.com/palant/searchlinkfix/blob/master/data/content.js var actualCode = '(' + function() { 'use strict'; var found = null; var restore = function() { try { if (found && ('getAttribute' in found.element) && found.element.getAttribute('href') !== found.href) { found.element.href = found.href; } } catch(e) { // ignored } }; // Fix the links by adding a pair of mousedown handlers window.addEventListener('mousedown', function(e) { // Find the <a> tag var curr = null; for (curr = e.target; curr && curr.localName && curr.localName.toLowerCase() !== 'a'; curr = curr.parentNode) { } // Verify it is in the search container, break out if the encrypted.google iframe if necessary var checked = false; if (curr) { var par = curr.parentNode; if (window.frameElement) { par = window.frameElement.parentNode; } for (; par && par.parentNode; par = par.parentNode) { if (('getAttribute' in par) && par.getAttribute('id') === 'search') { checked = true; break; } } } if (!checked) { curr = null; } // Didn't find it if (!curr) { found = null; return; } // Save the link location found = { 'href': curr.href, 'element': curr }; // Restore even if event was cancelled setTimeout(restore, 0); }, true); window.addEventListener('mousedown', restore, false); } + ')();'; // Inject code into the page to access the underlying JavaScript objects // https://stackoverflow.com/questions/9515704/building-a-chrome-extension-inject-code-in-a-page-using-a-content-script var script = document.createElement('script'); script.textContent = actualCode; (document.head || document.documentElement).appendChild(script); script.parentNode.removeChild(script);
var width = 600, height = 600, blockSize = 20, widthInBlocks = width / blockSize, heightInBlocks = height / blockSize; var game = (function () { var canvas, ctx, frameLength, score, timeout; var init = function () { var $canvas = $('#jsSnake'); if ($canvas.length === 0) { $('body').append('<canvas id="jsSnake">'); } $canvas = $('#jsSnake'); $canvas.attr('width', width); $canvas.attr('height', height); canvas = $canvas[0]; ctx = canvas.getContext('2d'); score = 0; frameLength = 200; bindEvents(); gameLoop(); } var increaseScore = function () { score++; frameLength *= 0.9; } function gameLoop() { ctx.clearRect(0, 0, width, height); snake.advance(apple); draw(); if (snake.checkCollision()) { snake.retreat(); snake.draw(ctx); gameOver(); } else { timeout = setTimeout(gameLoop, frameLength); } } function draw() { snake.draw(ctx); drawBorder(); apple.draw(ctx); drawScore(); } function drawScore() { ctx.save(); ctx.font = 'bold 102px sans-serif'; ctx.fillStyle = 'rgba(0, 0, 0, 0.3)'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; var centreX = width / 2; var centreY = width / 2; ctx.fillText(score.toString(), centreX, centreY); ctx.restore(); } function gameOver() { ctx.save(); ctx.font = 'bold 30px sans-serif'; ctx.fillStyle = '#000'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; ctx.strokeStyle = 'white'; ctx.lineWidth = 2; var centreX = width / 2, centreY = width / 2; ctx.strokeText('Game Over', centreX, centreY - 10); ctx.fillText('Game Over', centreX, centreY - 10); ctx.restore(); } function drawBorder() { ctx.save(); ctx.strokeStyle = 'gray'; ctx.lineWidth = blockSize / 2; ctx.lineCap = 'square'; var offset = ctx.lineWidth / 2, corners = [ [offset, offset], [width - offset, offset], [width - offset, height - offset], [offset, height - offset] ]; ctx.beginPath(); ctx.moveTo(corners[3][0], corners[3][1]); $.each(corners, function (index, corner) { ctx.lineTo(corner[0], corner[1]); }); ctx.stroke(); ctx.restore(); } function bindEvents() { var keysToDirections = { 37: 'left', 38: 'up', 39: 'right', 40: 'down' }; $(document).keydown(function (event) { var key = event.which; var direction = keysToDirections[key]; if (direction) { snake.setDirection(direction); event.preventDefault(); } }); } return { init: init, increaseScore : increaseScore }; })(); $(document).ready(function () { game.init(); });
'use strict'; /* Services */ // Demonstrate how to register services // In this case it is a simple value service. angular.module('scrobbleAlong.services', []). factory('baseApi', ['$http', '$log', function($http, $log) { var apiServiceInstance = { getApiUrl: function(page, params, callback) { $http({ method: 'GET', url: '/api/' + page, params: params || {} }). success(function(data) { //$log.log("Success getting page " + page + ":", data); callback(data); }). error(function(data) { //$log.log("Error getting page " + page + ":", data); callback(null); }); }, postApiUrl: function(page, data, callback) { $http({ method: 'POST', url: '/api/' + page, data: data || {} }). success(function(response) { //$log.log("Success posting to page " + page + ":", data); callback(null, response); }). error(function(error) { //$log.log("Error posting to page " + page + ":", data); callback(error, null); }); } }; return apiServiceInstance; }]). factory('userDetails', ['baseApi', function(baseApi) { var apiServiceInstance = { getUserDbInfo: function(callback) { baseApi.getApiUrl('user-details', null, function(data) { if (data && data.username) { callback({ lastfmUsername: data.username, listeningTo: data.listening, userScrobbles: data.scrobbles, scrobbleTimeoutTime: data.scrobbleTimeoutTime, scrobbleTimeoutEnabled: data.scrobbleTimeoutEnabled }); } else { callback({ lastfmUsername: null, listeningTo: null, userScrobbles: {}, scrobbleTimeoutTime: null, scrobbleTimeoutEnabled: false }); } }); }, getUserLfmInfo: function(username, nocache, callback) { var params = { user: username }; if (nocache) { params['nocache'] = true; } baseApi.getApiUrl('user-lastfm-info', params, function(data) { if (data) { callback(data); } else { callback(null); } }); } }; return apiServiceInstance; }]). factory('stationDetails', ['baseApi', function(baseApi) { // Updates the stations details in batches, callback is called when everything is done var getApiBatch = function(batchSize, url, stationNames, username, stations, nocache, callback) { if (stationNames.length == 0) { if (callback) callback(); return; } stationNames = stationNames.slice(0); // Clone array so we can splice it safely var batch = stationNames.splice(0, batchSize); var params = { stations: batch.join(",") }; if (username) { params['user'] = username; } if (nocache) { params['nocache'] = true; } baseApi.getApiUrl(url, params, function(data) { angular.forEach(stations, function(station) { if (station.lastfmUsername in data) { angular.extend(station, data[station.lastfmUsername]); } }); getApiBatch(batchSize, url, stationNames, username, stations, nocache, callback); }); }; var apiServiceInstance = { // Returns an array of station details in the callback getAllStationsDbInfo: function(nocache, callback) { var params = { }; if (nocache) { params['nocache'] = true; } baseApi.getApiUrl('stations', params, function(data) { if (callback) callback(data || []); }); }, // Returns a map of station name to last.fm details (profile pic) in the callback getStationsLfmInfo: function(stationNames, results, nocache, callback) { if (!stationNames || stationNames.length == 0) { if (callback) callback(); return; } getApiBatch(10, 'station-lastfm-info', stationNames, null, results, nocache, callback); }, // Returns a map of station name to tasteometer scores in the callback getStationsTasteometer: function(stationNames, username, results, nocache, callback) { if (!stationNames || stationNames.length == 0 || !username) { if (callback) callback(); return; } getApiBatch(10, 'station-lastfm-tasteometer', stationNames, username, results, nocache, callback); }, getStationsRecentTracks: function(stationNames, results, nocache, callback) { if (!stationNames || stationNames.length == 0) { if (callback) callback(); return; } getApiBatch(5, 'station-lastfm-recenttracks', stationNames, null, results, nocache, callback); } }; return apiServiceInstance; }]). factory('userManagement', ['baseApi', function(baseApi) { var apiServiceInstance = { getLoginUrl: function(callback) { baseApi.getApiUrl('login-url', null, function(data) { if (data && data.loginUrl) { callback(data.loginUrl); } else { callback('#'); } }); }, stopScrobbling: function(stationUsername, callback) { baseApi.postApiUrl('stop-scrobbling', {}, function(error, userDetails) { if (error) { callback(error, null); } else { callback(null, { listeningTo: userDetails.listening, scrobbleTimeoutTime: userDetails.scrobbleTimeoutTime, scrobbleTimeoutEnabled: userDetails.scrobbleTimeoutEnabled }); } }); }, scrobbleAlong: function(stationUsername, callback) { baseApi.postApiUrl('scrobble-along', { username: stationUsername }, function(error, userDetails) { if (error) { callback(error, null); } else { callback(null, { listeningTo: userDetails.listening, scrobbleTimeoutTime: userDetails.scrobbleTimeoutTime, scrobbleTimeoutEnabled: userDetails.scrobbleTimeoutEnabled }); } }); }, setScrobbleTimeoutEnabled: function(enabled, callback) { baseApi.postApiUrl('scrobble-timeout-enable', { enabled: enabled }, function(error, userDetails) { if (error) { callback(error, null); } else { callback(null, { listeningTo: userDetails.listening, scrobbleTimeoutTime: userDetails.scrobbleTimeoutTime, scrobbleTimeoutEnabled: userDetails.scrobbleTimeoutEnabled }); } }); }, changeScrobbleTimeout: function(numMinutes, callback) { baseApi.postApiUrl('scrobble-timeout-change', { minutes: numMinutes }, function(error, userDetails) { if (error) { callback(error, null); } else { callback(null, { listeningTo: userDetails.listening, scrobbleTimeoutTime: userDetails.scrobbleTimeoutTime, scrobbleTimeoutEnabled: userDetails.scrobbleTimeoutEnabled }); } }); } }; return apiServiceInstance; }]). factory('adminInfo', ['baseApi', function(baseApi) { var apiServiceInstance = { getAllUsers: function(callback) { baseApi.getApiUrl('admin/users', {}, callback); }, getAllStations: function(callback) { baseApi.getApiUrl('admin/stations', {}, callback); }, addStation: function(station, callback) { baseApi.postApiUrl('admin/add-station', { station: station }, callback); }, updateStation: function(station, callback) { baseApi.postApiUrl('admin/update-station', { station: station }, callback); }, clearUserListening: function(username, callback) { baseApi.postApiUrl('admin/clear-listening', { username: username }, callback); }, clearUserSession: function(username, callback) { baseApi.postApiUrl('admin/clear-session', { username: username }, callback); } }; return apiServiceInstance; }]);
/** * @author Ignacio González Bullón - <nacho.gonzalez.bullon@gmail.com> * @since 22/11/15. */ (function () { 'use strict'; angular.module('corestudioApp.admin') .factory('Holiday', Holiday); Holiday.$inject = ['$resource', 'HOLIDAYS_ENDPOINT']; function Holiday ($resource, HOLIDAYS_ENDPOINT) { return $resource(HOLIDAYS_ENDPOINT, {}, { 'query': { method: 'GET', url: 'api/admin/holidays/getByYear/:year', isArray: true, cache: true }, 'get': { method: 'GET', cache: true, transformResponse: function (data) { data = angular.fromJson(data); return data; } }, 'update': {method: 'PUT'}, 'save': {method: 'POST'}, 'delete': {method: 'DELETE'} }); } })();
import React from "react" import { connect } from "react-redux" import {HashRouter as Router, Route, Link, Redirect} from 'react-router-dom' import styled from "styled-components" import $ from "jquery" import Footer from './footer.jsx' class Cperson extends React.Component { constructor(props){ super(props); } render(){ var Cper = styled.div` .header{ top: 0; padding: 0; font-size: 2.0em; width:100%; height:78px; background-color: #474a4f; color: #fff; line-height:78px } .header span:nth-of-type(1){ margin-left:46px; } .header span:nth-of-type(2){ text-align: center; width: 88%; height: 50px; display: inline-block; } .glyphicon{color:#fff} .section .ctag{ background-color: #474a4f; height:30px; width:100%; color:#fff; } .cTop{border-bottom:1px solid gray;margin:15px auto;box-shadow:1px 1px 1px 1px gray;width:80%} .ctImg{width:50px;height:50px;border-radius:50px;float:left} .ctSap{color:black;margin-left:20px;} .ctSap span:nth-of-type(1){display:block;font-size:1.3em;} .ctSap span:nth-of-type(2){display:block;font-size:1em;} .cbtm{flex:1;color:black} .cbtm span{width:30%;text-align:center;font-size:1em;line-height:30px;height:30px;display:inline-block;margin:5px 10px;border:1px solid gray} .cMid{border-bottom:1px solid gray;margin:25px auto;box-shadow:1px 1px 1px 1px gray;width:80%} .cMid p{flex:1;height:30px;padding:5px;} .cMid p span{width:33%;text-align:center;display:inline-block;height:30px;line-height:30px;color:black} .cBtm{border-bottom:1px solid gray;margin:25px auto;box-shadow:1px 1px 1px 1px gray;width:80%} .ht{color:black; border-bottom:1px solid gray;height:40px;line-height:40px;text-align:center;width:100%;font-size:1.1em} .cjmsec{border-bottom:1px solid #999;width:100%;padding-top:20px;color:black} .cjmsec p {margin-left:25px;} ` return (<Cper> <div> <div className="header"><Link to="/more/fx"><span className="glyphicon glyphicon-chevron-left"></span></Link><span>详细资料</span> </div> <div className="section"> </div> <Footer /> </div> </Cper>) } componentDidMount(){ var targetHeight = ($(window).height()+72) $('.section').css('height',targetHeight) $.ajax({ url:'https://www.easy-mock.com/mock/5993f32f059b9c566dbf4430/frent/others/index?name='+this.props.state.ajName, type:'get', success:function(res){ var reg = (res.data.recently).map((data)=>{ return` <div> <div class="cjmsec"> <p>${data.title}</p> <p>#${data.label} &nbsp;&nbsp;${data.time}</p> </div> </div> ` }).join('') var arr = []; arr.push(res.data) console.log(arr) $('.section').html(arr.map(function(attr){ return` <div class="cTop"> <div> <p class="ctImg"><img src=${attr.icon}${attr.id} alx="xx"/></p> <p class="ctSap"><span>${attr.name}</span><span>${attr.profile}</span></p> </div> <div class="cbtm"> <span><buttom>取消关注</buttom></span><span><buttom>话题</buttom></span> </div> </div> <div class="cMid"> <p><span>性别</span><span>${attr.gender}</span><span>&nbsp;</span></p> <p><span>正在找</span><span>${attr.label}</span><span>&nbsp;</span></p> </div> <div class="cBtm"> <p class="ht">最近发布的话题</p> <div> ${reg} </div> </div> ` })) } }) } } export default connect((state)=>{ return {state} },(dispatch)=>{ return { } })(Cperson)
import React from 'react'; import { Form, Button, DatePicker, Typography, message, Statistic, Row, Col } from 'antd'; import { useMutation } from 'react-query'; import MainLayout from '../../Layouts/MainLayout'; import api from '../../Utils/api'; const { Text } = Typography; const fetchStatistics = async ({ dateFrom, dateTo }) => { if (!dateFrom) { return; } const { data } = await api.get(`/issues/statistics?dateFrom=${dateFrom}&dateTo=${dateTo}`); return data; }; const Keys = () => { const [form] = Form.useForm(); const [mutate, { isLoading, data, error }] = useMutation(fetchStatistics); const onFinish = (values) => { mutate({ dateFrom: values.dateFrom, dateTo: values.dateTo }); }; const onReset = () => { form.resetFields(); }; const renderForm = () => ( <div> <Form layout="inline" name="statistics" onFinish={onFinish} form={form}> <Form.Item label="Date from" name="dateFrom" rules={[{ required: true, message: 'Please enter a starting date!' }]} > <DatePicker /> </Form.Item> <Form.Item label="Date To" name="dateTo" rules={[{ required: true, message: 'Please enter the end date!' }]} > <DatePicker /> </Form.Item> <Form.Item> <Button type="primary" htmlType="submit" loading={isLoading}> Search statistics </Button> <Button htmlType="button" onClick={onReset}> Reset </Button> </Form.Item> </Form> </div> ); const renderStatistics = () => { const { total, resolved, severities } = data; return ( <> <Row gutter={16}> <Col span={12}> <Statistic title="Total Issues" value={total} /> </Col> <Col span={12}> <Statistic title="Resolved" value={resolved} /> </Col> <Col span={24}> <Text style={{ marginTop: 32, fontWeight: 600 }}>By severity</Text> </Col> {severities.map(({ _id, count }) => { return ( <Col span={6}> <Statistic title={_id} value={count} /> </Col> ); })} </Row> </> ); }; const renderError = () => { const { response: { data }, } = error; return message.error(data.message); }; return ( <MainLayout> {renderForm()} {error && renderError()} {data && renderStatistics()} </MainLayout> ); }; export default Keys;
import React from "react"; import RegisterProvider from "./RegisterProvider"; import RegisterPage from "./RegisterPage"; const Register = () => { return ( <RegisterProvider> <RegisterPage /> </RegisterProvider> ); }; export default Register;
'use strict'; const {CheckSettings, Region} = require('@applitools/eyes-sdk-core'); function createCheckSettings({ignore, floating}) { const checkSettings = new CheckSettings(0); if (ignore) { ignore = [].concat(ignore); for (const region of ignore) { checkSettings.ignoreRegions(new Region(region)); } } if (floating) { floating = [].concat(floating); for (const region of floating) { checkSettings.floatingRegion( new Region(region), region.maxUpOffset, region.maxDownOffset, region.maxLeftOffset, region.maxRightOffset, ); } } return checkSettings; } module.exports = createCheckSettings;
export const decrement = () => { return { type: "DECREMENT" }; }; export const increment = () => { return { type: "INCREMENT" }; }; export const onChange = value => { return { type: "CHANGE", value }; }; export const onSubmit = e => { return { type: "SUBMIT", e }; }; export const toggle = text => { return { type: "TOGGLE", text }; }; export const allItems = () => { return { type: "ALL_ITEMS" }; }; export const checkedItems = () => { console.log(`action checkedItems`); return { type: "CHECKED_ITEMS" }; }; export const UnCheckedItems = () => { return { type: "UNCHECKED_ITEMS" }; };
var dialogsModule = require("ui/dialogs"); var observableModule = require("data/observable"); var ObservableArray = require("data/observable-array").ObservableArray; var page; var pageData = new observableModule.fromObject({ groceryList: new ObservableArray([ { name: "eggs" }, { name: "bread" }, { name: "cereal" } ]) }); exports.loaded = function(args) { page = args.object; page.bindingContext = pageData; };
"use strict" window.onload = init; var id = 1; var canvas; var width; var height; var cx; var cy; var socket = null; var connected = false; var connectionInterval = 60000; var trackerData = {}; var targets = {}; var paths = {}; var trackerHistory = []; var trail = null; var link = null; var distThresh = 10000; var screensaver = false; var screensaver_timeout = 20000; function init() { console.log('init!'); canvas = Raphael($('#svgDiv')[0], '100%', '100%'); width = ($('#svgDiv')[0]).offsetWidth; height = ($('#svgDiv')[0]).offsetHeight; console.log('window dimensions: '+width+'x'+height); cx = width * 0.5; cy = height * 0.5; // identify(); if (navigator.onLine) { console.log("You are Online"); } else { console.log("You are Offline"); } function openWebSocket() { console.log(" Trying to connect..."); // Create a new WebSocket. //socket = new WebSocket('ws://192.168.1.120/Dal200'); socket = new WebSocket('ws://134.190.133.142/Dal200'); socket.onopen = function(event) { console.log("Connection established"); socket.send("SVG renderer "+id+" connected."); connected = true; } socket.onclose = function(event) { console.log("Connection dropped, will try to reconnect in", connectionInterval/1000, "seconds"); connected = false; for (var i in targets) { targets[i].label.remove(); targets[i].remove(); targets[i] = null; } targets = {}; } socket.onmessage = function(event) { let data = null; if (event.data) data = JSON.parse(event.data); if (!data) return; if (data.trackerData) { for (var i in data.trackerData) { updateTrackerData(data.trackerData[i].id, convertCoords(data.trackerData[i].position)); } if (screensaver == true) { screensaver = false; // animate targets back to their proper positions for (var i in targets) { //Stop the current animations first targets[i].stop(); let pos = targets[i].data('pos') targets[i].stop() .animate({'cx': pos.x, 'cy': pos.y, 'opacity': 1}, 1000, 'linear', function() { this.label.stop() .animate({'opacity': 1}, 500, 'linear'); }); } } } else if (data.targets) { for (var i in data.targets) { updateTarget(data.targets[i].UUID, convertCoords(data.targets[i].Position), data.targets[i].Label, data.targets[i].Type, data.targets[i].Page); } } else if (data.paths) { for (var i in data.paths) { updatePath(data.paths[i].UUID, data.paths[i].source, data.paths[i].destination); } } else if (data.command) { switch (data.command) { case 'identify': identify(); break; } } else if (data.dwellIndex != null) { // console.log('dwellIndex:', data.dwellIndex); // find target with dwell index for (var i in targets) { if (targets[i].dwellIndex == data.dwellIndex) { targets[i].attr({'stroke': 'red'}) .animate({'stroke': 'white'}, 2000, 'linear'); break; } } } else if(data.screenSaver) { function a(o) { o.animate({'cx': Math.random() * 800, 'cy': Math.random() * 600, 'opacity': 0.8}, Math.random() * 10000 + 10000, 'linear', function() { b(this); }); } function b(o) { o.animate({'cx': Math.random() * 800, 'cy': Math.random() * 600, 'opacity': 0.8}, Math.random() * 10000 + 10000, 'linear', function() { a(this); }); } for (var i in targets) { targets[i].label .animate({'opacity': 0}, 500, 'linear'); a(targets[i]); } } } } // open webSocket openWebSocket(); // check the websocket periodically setInterval(function() { console.log("checking websocket..."); if (connected == true) { console.log(" Socket ok."); return; } openWebSocket(); }, connectionInterval); // activate the screensaver if necessary setInterval(function() { console.log("checking for activity..."); if (screensaver == true) { console.log("animating!"); for (var i in targets) { targets[i].label.stop() .animate({'opacity': 0}, 500, 'linear'); targets[i].stop() .animate({'cx': Math.random() * 800, 'cy': Math.random() * 600, 'opacity': 0.8}, screensaver_timeout, 'linear'); } } screensaver = true; }, screensaver_timeout); // open webSocket openWebSocket(); // check the websocket periodically setInterval(function() { console.log("checking websocket..."); if (connected == true) { console.log(" Socket ok."); return; } openWebSocket(); }, connectionInterval); // activate the screensaver if necessary // not used anymore, wait for command from manager // setInterval(function() { // console.log("checking for activity..."); // if (screensaver == true) { // for (var i in targets) { // targets[i].label.stop() // .animate({'opacity': 0}, 500, 'linear'); // targets[i].stop() // .animate({'cx': Math.random() * 800, // 'cy': Math.random() * 600, // 'opacity': 0.8}, screensaver_timeout, 'linear'); // } // } // screensaver = true; // }, screensaver_timeout); $('body').on('keydown.list', function(e) { switch (e.which) { case 32: socket.close(); break; /* space */ for (var i in trackerData) { updateTrackerData(i, randomCoord()); } for (var i in targets) { updateTarget(i, randomCoord()); } break; } }) // debugging: add a couple of targets // updateTarget(0, randomCoord(), "category 1", 1); // updateTarget(1, randomCoord(), "category 2", 0); // // updatePath(3, 0, 1); // function makeSteps(num) { // let steps = []; // for (var i = 0; i < num; i++) { // let path = canvas.path([['M', 0, 0], // ['l', 0, 500]]) // .attr({'stroke-width': 30, // 'stroke': 'white'}) // .rotate(-5) // .translate(220 + i * 40, 165); // steps.push(path); // } // } // // makeSteps(9); // // step 1 // canvas.path([['M', 0, 0], // ['l', 0, 500]]) // .attr({'stroke-width': 30, // 'stroke': Raphael.getColor()}) // .rotate(-5) // .translate(220, 165); // // canvas.circle(300, 500, 40).attr({'fill': 'white', // 'fill-opacity': 1, // 'stroke-width': 10, // 'opacity': 1}); } function convertCoords(pos) { let offset = {'x': 10, 'y': -250}; let scale = {'x': 2.25, 'y': 2.5}; // let offset = {'x': 400, 'y': -320}; // let scale = {'x': 2.4, 'y': 2.5}; // let offset = {'x': -1110, 'y': -340}; // let scale = {'x': 1.68, 'y': 2.9}; let x = pos.x * scale.x + offset.x; let y = pos.y * scale.y + offset.y; x = 512 - x + 750; // if (pos.x > 465) // x -= 45; // added y-offset to compensate for projector clamp slipping x -= 60; y -= 45; return {'x': x, 'y': y}; } function identify() { let test = canvas.text(cx, cy, 'Dal200 SVG Renderer #'+id) .attr({'opacity': 1, 'font-size': 36, 'fill': 'white'}) .animate({'opacity': 0}, 10000, 'linear', function() { this.remove(); }); } function randomCoord() { return {'x': Math.random() * width, 'y': Math.random() * height}; } function circlePath(pos, r1, r2, a) { if (!r2) r2 = r1; if (!a) a = 0; return [['M', pos.x + r1 * 0.65, pos.y - r2 * 0.65], ['a', r1, r2, a, 1, 0, 0.001, 0.001], ['z']]; } function distSquared(pos1, pos2) { let distX = pos1.x - pos2.x; let distY = pos1.y - pos2.y; return distX * distX + distY * distY; } function updateTrackerData(id, pos) { // pos.x = 512 - pos.x + 750; if (!trackerData[id]) { trackerData[id] = canvas.circle(pos.x, pos.y, 40) .attr({'stroke': 'white', 'fill-opacity': 0, 'stroke-width': 10, 'opacity': 0}) .data({'id': id}); trackerData[id].animationFrame = 0; } trackerData[id].stop().toFront(); // console.log('placing tracker', id, 'at', pos); trackerData[id].animate({'cx': pos.x, 'cy': pos.y, 'r': trackerData[id].animationFrame, 'opacity': 1}, 300, 'linear', function() { this.animate({'opacity': 0}, 10000, '>', function() { trackerData[this.data('id')] = null; this.remove(); }); }); trackerData[id].animationFrame += 0.5; if (trackerData[id].animationFrame > 40) trackerData[id].animationFrame = 20; // check if we are close to any targets for (var i in targets) { let dist = distSquared(pos, targets[i].data('pos')); // console.log(id, i, dist); targets[i].attr({'stroke-opacity': dist < distThresh ? 1 : 0, 'stroke-width': dist < distThresh ? (distThresh - dist) * 0.001 : 0 }); // if (dist < distThresh) { //// console.log('tracker', id, 'proximate to target', i); // targets[i].attr({'stroke-opacity': 1}); // if (targets[i].sel < 255) // targets[i].sel++; // } // else if (targets[i].sel > 0) // targets[i].sel--; // let opacity = targets[i].sel / 255; // targets[i].attr({'stroke-opacity': opacity}); } // draw a trail trackerHistory.push(pos); while (trackerHistory.length > 30) trackerHistory.shift(); if (trackerHistory.length > 1) { let path = []; path.push(['M', trackerHistory[0].x, trackerHistory[0].y]); for (var i = 0; i < trackerHistory.length; i++) path.push(['T', trackerHistory[i].x, trackerHistory[i].y]); if (!trail) trail = canvas.path().attr({'stroke': 'white', 'stroke-width': 25, 'opacity': 0, 'stroke-linecap': 'round'}); trail.stop().animate({'path': path, 'opacity': 0.7}, 100, 'linear', function() { this.animate({'opacity': 0}, 2000, 'linear', function() { while (trackerHistory.length) trackerHistory.shift(); }); }).toBack(); } } function updateTarget(id, pos, label, type, dwellIndex) { if (!targets[id]) { targets[id] = canvas.circle(0, 0, 30 + (pos.x) * 0.04); targets[id].label = canvas.text(pos.x, pos.y, label) .rotate(90); targets[id].sel = 0; targets[id].dwellIndex = dwellIndex; } // console.log('placing target', id, 'at', pos); targets[id].attr({'cx': pos.x, 'cy': pos.y}); targets[id].data({'pos': pos}); let color; switch (type) { case 0: color = '#FFBBBB'; break; case 1: color = '#BBFFBB'; break; case 2: color = '#BBBBFF'; break; default: color = '#FFFFFF'; break; } targets[id].animate({'fill': color, 'stroke': 'white', 'stroke-opacity': 0, 'stroke-width': 10}).toBack(); targets[id].label.animate({'x': pos.x, 'y': pos.y, 'stroke': 'black', 'font-size': 16}); // console.log(targets); } function updatePath(id, src, dst) { src = targets[src]; dst = targets[dst]; if (!src) { console.log('missing src target for path', id); return; } if (!dst) { console.log('missing dst target for path', id); return; } if (!paths[id]) { console.log('adding path'); paths[id] = canvas.path([['M', src.pos.x, src.pos.y]]) .attr({'stroke-dasharray': '.'}) .toBack(); } paths[id].animate({'path': [['M', src.pos.x, src.pos.y], ['S', src.pos.x, dst.pos.y, dst.pos.x, dst.pos.y]], // ['L', dst.pos.x, dst.pos.y]], 'stroke': 'white', 'stroke-width': 10 }); }
/** * Copyright (C) 2009 eXo Platform SAS. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ function UIWorkspace(id) { this.id = id ; this.isFirstTime = true ; }; eXo.portal.UIWorkspace = new UIWorkspace("UIWorkspace") ; /*#############################-Working Workspace-##############################*/ if(eXo.portal.UIWorkingWorkspace == undefined) { eXo.portal.UIWorkingWorkspace = new UIWorkspace("UIWorkingWorkspace") ; }; /** * Resize UIControlWorkspace document object to fit on the screen */ eXo.portal.UIWorkingWorkspace.onResize = function() { var uiWorkspace = document.getElementById(eXo.portal.UIWorkingWorkspace.id) ; if(eXo.core.Browser.isIE6()) { var tabs = eXo.core.DOMUtil.findFirstDescendantByClass(uiWorkspace, "div", "UIHorizontalTabs") ; if(tabs) tabs.style.left = 0; } };
'use strict'; const Q = require('@nmq/q/client'); setInterval( () => { Q.publish('database', 'create', {id:10}); Q.publish('database', 'udpate', {id:10, name:'Domboo'}); Q.publish('database', 'delete', {id:10, name:'Howdiest'}); Q.publish('network', 'attack', {id:10, name:'Domboo'}); Q.publish('network', 'no-service', {id:10, name:'Howdiest'}); }, 3000);
'use strict'; /** * @ngdoc directive * @name seedApp.directive:shopfront * @description * # shopfront */ angular.module('seedApp') .directive('shopfront', function (previewService) { return { scope: true, templateUrl: 'views/shopfront.dir.html', restrict: 'E', link: function postLink(scope) { scope.name = 'The Co-operative Food - Strand'; scope.addr = 'Golden Cross House, 456-459 Strand, London WC2R 0RG, United Kingdom'; scope.tagsOptions = { colorClass: 'light-grey3', icon: 'local_offer', numberString: '356', size: '27', }; scope.favouriteOptions = { colorClass: 'light-grey3', icon: 'favorite', numberString: 27, size: '27', }; scope.directionsOptions = { colorClass: 'business-blue', icon: 'directions_walk', numberString: '1,26 Km', size: '27', }; scope.editTags = function(ev) { var parent = '#searchbar'; var text = 'This will bring up the edit tags modal for this shopfront'; previewService.preview(ev, parent, text); }; var favourited = false; scope.favouriteShopfront = function(ev) { var parent = '#searchbar'; var text = 'This will favourite this shopfront'; previewService.preview(ev, parent, text).then(function(){ if (favourited){ scope.favouriteOptions.numberString --; scope.favouriteOptions.colorClass = 'light-grey3'; }else{ scope.favouriteOptions.numberString ++; scope.favouriteOptions.colorClass = 'favourited'; } favourited = !favourited; }); }; scope.showDirections = function(ev) { var parent = '#searchbar'; var text = 'This will bring up the directions modal for this business'; previewService.preview(ev, parent, text); }; scope.gotoEntity = function(ev) { var parent = '#searchbar'; var text = 'This will take you to the entity\'s profile page'; previewService.preview(ev, parent, text); }; } }; });
const path = require('path'); const webpack = require('webpack'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const MiniCssExtractPlugin = require('mini-css-extract-plugin'); const isProd = process.env.NODE_ENV === 'prod'; const resolve = (dir) => { return path.join(__dirname, '..', dir) }; module.exports = { entry: resolve('src/main.js'), output: { path: resolve('dist'), filename: "js/[name].js", publicPath: "/" }, module: { rules: [ { test: /\.(sa|sc|c)ss$/, // 正则匹配sass/scss/css use: [ { loader: isProd ? MiniCssExtractPlugin.loader : 'style-loader' }, { loader: 'css-loader' }, { loader: 'sass-loader' }, { loader: 'postcss-loader' } ] }, { test: /(\.jsx|\.js)$/, //jsx 解析 loader: 'babel-loader', exclude: /node_modules/, }, { test: /\.(png|jpg|svg|gif)$/, use: [ { loader: 'url-loader', options: { limit: 1000, // 限制只有小于1kb的图片才转为base64,例子图片为1.47kb,所以不会被转化 outputPath: 'images' // 设置打包后图片存放的文件夹名称 } } ] } ] }, plugins: [ new webpack.BannerPlugin('版权所有,翻版必究'), new HtmlWebpackPlugin({ template: resolve('src/index.html'), title: 'react-mobx', minify: { removeComments: true, // 删除注释 collapseWhitespace: true, // 压缩成一行 removeAttributeQuotes: false, // 删除引号 } }), ], resolve: { extensions: ['.ts', '.tsx', '.js', '.jsx', '.scss', '.css'], // 可以省略的后缀名 }, };
import gql from "graphql-tag"; const ABOUT_QUERY = gql` query About { about { title { en hun } subtitle { en hun } } } `; export default ABOUT_QUERY;