text
stringlengths 7
3.69M
|
|---|
import Detial from './Detial'
export default Detial;
|
var searchData=
[
['v_5fcycle_97',['v_cycle',['../v__cycle_8h.html#ac02ac948524a2ec22da26b88ba062378',1,'v_cycle.h']]],
['vec1_98',['vec1',['../functions_8h.html#afb2569f43ba282c49ec37dc69c4be077',1,'functions.h']]],
['vec2_99',['vec2',['../functions_8h.html#ac65eeff05a547f39022de2f560a1ba34',1,'functions.h']]],
['vec3_100',['vec3',['../functions_8h.html#a2e62c650b3b0e661bf37b78ee33249cb',1,'functions.h']]]
];
|
import React from 'react';
import { FaInstagram, FaTwitterSquare, FaLinkedin, FaReact, FaPhp, FaHtml5, FaCss3, FaGithubAlt } from 'react-icons/fa';
import { DiJavascript1 } from "react-icons/di";
import styled from 'styled-components';
const QueHagoContainer = styled.div`
margin-top: 70px;
display: grid;
@media(min-width: 20em) {
grid-template-columns: 100%;
width: 100%;
}
@media(min-width: 57em) {
grid-template-columns: repeat(2, 65% 35%);
max-width: 55em;
}
grid-gap: 20px;
height: 100vh;
`;
const LeftColumn = styled.div`
${'' /* background-color: #26283B; */}
padding: 20px;
border-right: 1px solid #6A6B7B;
.cab{
margin-bottom: 2em;
border-bottom: 1px solid #191A28;
min-height: 9em;
}
.nombre{
position: relative;
font-size: 2rem;
text-transform: uppercase;
font-weight: 700;
.profesion{
font-size: .3em;
margin-top: 10px;
position: absolute;
right: 7px;
bottom: -6px;
}
}
.description{
margin-top: 1.5em;
font-size: .8em;
line-height: 1.3em;
}
.expe__title{
font-size: 1.5em;
font-weight: 700;
margin-bottom: .4em
}
.expe__case-unit{
display: grid;
grid-template-columns: repeat(2, 1fr);
margin-bottom: 2em;
}
.expe__case-place{
font-size: .7em;
margin-top: -3px;
}
.skills{
display: grid;
justify-content: center;
align-items: center;
grid-template-columns: repeat(5, 1fr);
font-size: 1.8em;
margin-bottom: 1em;
}
`;
const RightColumn = styled.div`
padding: 20px;
.contacto{
min-height: 9em;
border-bottom: 1px solid #191A28;
margin-bottom: 2em;
}
.contacto__title{
font-size: 2rem;
text-transform: uppercase;
font-weight: 800;
line-height: 1em;
}
.title{
font-size: 1.5em;
}
.box{
margin-bottom: 1.5em;
}
.social__box{
display: grid;
grid-template-columns: repeat(3, 10%);
grid-gap: 1em;
.title{
margin-bottom: 1.5em;
}
.icons{
font-size: 1.5em;
transition: color .4s ease-in-out;
&:hover{
color: #98A6B6;
}
}
}
`;
const QueHago = () => {
return (
<QueHagoContainer className="que-hago container font-culum">
<LeftColumn className="">
<div className="cab">
<p className="nombre inline"> Manuell Villagordo Vera <small className="profesion">Desarrollador web</small></p>
<p className="description"> Con mas de 10 años de experiencia en tecnologías web relizando proyectos ecommerce en las plataformas mas conocidas (Magento, Prestashop y Woocomerce) con PHP. Ahora, aprendiendo y desarrolando proyectos en Javascript con React, Vue y Node.</p>
</div>
<div className="expe">
<h2 className="expe__title"> Experiencia </h2>
<div className="expe__case">
<div className="expe__case-unit">
<div className="expe__case-date">
Junio 2009 - Marzo 2015
<div className="expe__case-place ">
Orihuela, España
</div>
</div>
<div className="expe__case-work">
Wordpress, Prestashop
</div>
</div>
<div className="expe__case-unit">
<div className="expe__case-date">
Junio 2015 - Mayo 2017
<div className="expe__case-place ">
Barcelona, España
</div>
</div>
<div className="expe__case-work">
Ecommerce Magento 1.9
</div>
</div>
<div className="expe__case-unit">
<div className="expe__case-date">
Junio 2017 - Mayo 2018
<div className="expe__case-place ">
Madrid, España
</div>
</div>
<div className="expe__case-work">
Ecommerce Magento 2.0
</div>
</div>
<div className="expe__case-unit">
<div className="expe__case-date">
Diciembre 2018 - Julio 2019
<div className="expe__case-place ">
Alicante, España
</div>
</div>
<div className="expe__case-work">
Web php Symfony
</div>
</div>
<div className="expe__case-unit">
<div className="expe__case-date">
Diciembre 2018 - actualidad
<div className="expe__case-place ">
Catral, España
</div>
</div>
<div className="expe__case-work">
ISP con PHP
</div>
</div>
<div className="expe__case-unit">
<div className="expe__case-date">
Diciembre 2020 - actualidad
<div className="expe__case-place ">
Catral, España
</div>
</div>
<div className="expe__case-work">
<p>Proyecto personal, Laravel y Vue. Reserva clases Crossfit </p>
</div>
</div>
</div>
</div>
<div className="expe">
<h2 className="expe__title"> Skills </h2>
<div className="expe__case-unit skills">
<a href="#p" title="React"><FaReact /></a>
<a href="#p" title="PHP"><FaPhp /></a>
<a href="#p" title="HTML"><FaHtml5 /></a>
<a href="#p" title="CSS3"><FaCss3 /></a>
<a href="#p" title="Javascript"><DiJavascript1 /></a>
</div>
<h2 className="expe__title"> Cuenta Github </h2>
<div className="expe__case-unit skills">
<a href="https://github.com/mnuhell" title="Github"><FaGithubAlt /></a>
</div>
</div>
</LeftColumn>
<RightColumn className="">
<div className="contacto">
<h2 className="contacto__title"> Información de contácto</h2>
</div>
<div className="nacimiento box">
<h2 className="title nacimiento__title font-bold">Fecha de nacimiento</h2>
<p className="nacimiento__content"> 30-01-1978</p>
</div>
<div className="nacionalidad box">
<h2 className="title nacionalidad__title font-bold">Nacionalidad</h2>
<p className="nacionalidad__content"> Española</p>
</div>
<div className="email box">
<h2 className="title email__title font-bold">Email</h2>
<p className="email__content"> m.villagordovera[at]gmail.com</p>
</div>
<div className="social box">
<h2 className="title direccion__title font-bold">Redes sociales</h2>
<div className="social__box">
<a href="https://www.instagram.com/manuffit78/" className="icons instagram" title="instagram"><FaInstagram /></a>
<a href="https://twitter.com/mnuhell" className="icons twitter" title="twitter"><FaTwitterSquare /></a>
<a href="https://www.linkedin.com/in/manuelvillagordo/" className="icons linkedin" title="LinkedIn"><FaLinkedin /></a>
</div>
</div>
</RightColumn>
</QueHagoContainer>
)
}
export default QueHago;
|
let minute =20;
let seconds =minute*60 ;
console.log(`${minute} minute is ${seconds}seconds`);
|
//StateStartingGame
StateStartingGame.prototype = Object.create(State.prototype);
StateStartingGame.prototype.constructor = StateStartingGame;
StateStartingGame.animState = {
STARTING: 0,
IDLE: 1,
ENDING: 2,
ENDED: 3
}
function StateStartingGame(modx) {
this.init(modx);
this.anim_state = StateStartingGame.animState.STARTING;
this.hudPlane = new Plane(this.modx.scene, 10);
this.hudAppearance = new CGFappearance(modx.scene);
this.hudAppearance.setAmbient(1, 1, 1, 1);
this.hudAppearance.setDiffuse(1, 1, 1, 1);
this.hudAppearance.setSpecular(0.3, 0.3, 0.3, 1);
this.hudAppearance.setShininess(120);
this.hudAppearance.setTexture(new CGFtexture(modx.scene, "game/resources/start_menu.png"));
this.animTime = -1;
this.animDuration = 2;
this.animEndDuration = 1;
this.endAnimTime = -1;
this.modx.scene.lights[5].setPosition(2, 2, 1, 0);
this.modx.scene.lights[5].setAmbient(1, 1, 1, 1);
this.modx.scene.lights[5].setDiffuse(1, 1, 1, 1);
this.modx.scene.lights[5].setSpecular(1, 1, 1, 1);
this.modx.scene.lights[5].setVisible(false);
}
StateStartingGame.prototype.displayHUD = function(t) {
if(this.anim_state != StateStartingGame.animState.ENDING) {
this.modx.scene.lights[5].enable();
this.modx.scene.lights[5].update();
if(this.animTime == -1 || t < this.animTime) {
this.animTime = t;
return;
}
this.modx.scene.pushMatrix();
this.hudAppearance.apply();
this.modx.scene.translate(1.3, -2.3, 0);
if(t > this.animTime + this.animDuration) {
this.anim_state = StateStartingGame.animState.IDLE;
this.modx.scene.scale(4, 2.5, 1);
} else {
anim_prop = (t-this.animTime)/this.animDuration;
this.modx.scene.scale(4*anim_prop, 2.5*anim_prop,1);
}
this.modx.scene.translate(0.5, 0.5, 0);
this.hudPlane.display();
this.modx.scene.popMatrix();
} else {
this.modx.scene.lights[5].enable();
this.modx.scene.lights[5].update();
if(this.animTime == -1 || t < this.animTime) {
this.animTime = t;
return;
}
this.modx.scene.pushMatrix();
this.hudAppearance.apply();
this.modx.scene.translate(1.3, -2.3, 0);
if(t > this.animTime + this.animEndDuration) {
this.anim_state = StateStartingGame.animState.ENDED;
this.modx.scene.scale(0, 0, 1);
this.modx.start(new Game(this.newGame));
this.modx.scene.lights[5].disable();
this.modx.scene.lights[5].update();
} else {
anim_prop = (t-this.animTime)/this.animEndDuration;
this.modx.scene.scale(4*(1 - anim_prop), 2.5*(1 - anim_prop),1);
}
this.modx.scene.translate(0.5, 0.5, 0);
this.hudPlane.display();
this.modx.scene.popMatrix();
}
}
StateStartingGame.prototype.display = function(t) {}
StateStartingGame.prototype.isFinished = function(t) {
return this.anim_state == StateStartingGame.animState.ENDED;
}
StateStartingGame.prototype.terminate = function(newGame) {
this.anim_state = StateStartingGame.animState.ENDING;
this.animTime = -1;
this.newGame = newGame;
}
|
function getPeaks(data) {
// console.log(data[0]);
// console.log(d3.values(data[0]));
// console.log(+d3.values(data[0])[1]);
// array (time) of array (# of peaks) of objects (index & value)
var peaksoverTime = [];
// d3.values(data[i]) get the ith row: 0 ~ data.length
// d3.values(data[i])[j] get the element at the jth column & the ith row (columns: Timesteps)
// +d3.values(data[i])[j] convert string to number
for (var j=0; j<TimeSteps; j++) {
var peaks = [];
if (+d3.values(data[0])[j+1] >= +d3.values(data[1])[j+1] && +d3.values(data[0])[j+1] > 1e-12) {
peaks.push({index: 0, value: +d3.values(data[0])[j+1]});
}
for (var i=1; i<data.length-1; i++) {
if ( +d3.values(data[i])[j+1] >= +d3.values(data[i-1])[j+1]
&& +d3.values(data[i])[j+1] >= +d3.values(data[i+1])[j+1]
&& +d3.values(data[i])[j+1] > 1e-12) {
peaks.push({index: i, value: +d3.values(data[i])[j+1]});
}
}
if (+d3.values(data[data.length-1])[j+1] >= +d3.values(data[data.length-2])[j+1] && +d3.values(data[data.length-1])[j+1] > 1e-12) {
peaks.push({index: data.length-1, value: +d3.values(data[data.length-1])[j+1]});
}
peaksoverTime.push(peaks);
}
// console.log(peaks);
return peaksoverTime;
}
function findMax(data, dimension) {
var max = 0;
for (var i=0; i<TimeSteps; i++) {
for (var j=0; j<data.length; j++) {
if ( +d3.values(data[j])[i+dimension] > max) {
max = +d3.values(data[j])[i+dimension];
}
}
}
return max;
}
|
// test_displayDeviceList.js
// 2017.08.17
// Test: global deviceListの列挙
let deviceList = global.get("deviceList");
for (let deviceName in deviceList) {
console.log(deviceName);
console.log(deviceList[deviceName]);
console.log(deviceList[deviceName].ip);
console.log(deviceList[deviceName].manufacturerNameJa);
console.log(deviceList[deviceName].manufacturerNameEn);
}
msg.payload = deviceList;
return msg;
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Message } from "react-bulma-components";
const error = (props) => (
<Message color="danger">
<Message.Header>
Title
</Message.Header>
<Message.Body>
{props.errorMessage}
</Message.Body>
</Message>
)
error.propTypes = {
errorMessage : PropTypes.string.isRequired
}
export default error;
|
import React, { Component } from 'react';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faSpinner, faSync } from '@fortawesome/free-solid-svg-icons';
import * as apiNotes from './../../api/notes';
import NotesAddForm from './NotesAddForm';
import NotesList from './NotesList';
import './Notes.css';
class Notes extends Component {
state = {
deletingIds: [],
isAdding: false,
isDeleting: false,
isFetching: false,
notes: []
}
componentDidMount() {
this.fetchNotes();
}
addNote(content) {
this.setState({
isAdding: true
});
apiNotes.addNote(content)
.then(() => {
this.setState({
isAdding: false
});
this.fetchNotes();
})
.catch(() => {
this.setState({
isAdding: false
});
});
}
deleteNote(id) {
const { deletingIds } = this.state;
this.setState({
deletingIds: [
...deletingIds,
id
],
isDeleting: true
});
apiNotes.deleteNote(id)
.then(() => {
this.setState(prevState => {
return {
...prevState,
deletingIds: prevState.deletingIds.filter(deletingId => deletingId !== id),
isDeleting: false
}});
this.fetchNotes();
})
.catch(() => {
this.setState(prevState => ({
...prevState,
deletingIds: prevState.deletingIds.filter(deletingId => deletingId !== id),
isDeleting: false
}));
});
}
fetchNotes() {
const { isFetching } = this.state;
if (isFetching) {
return;
}
this.setState({
isFetching: true
});
apiNotes.fetchNotes()
.then(notes => {
this.setState({
notes,
isFetching: false
});
})
.catch(() => {
this.setState({
isFetching: false
});
});
}
handleAddFormSubmit = noteContent => {
this.addNote(noteContent);
}
handleNoteDelete = id => {
this.deleteNote(id);
}
handleUpdateClick = () => {
this.fetchNotes();
}
render() {
const {
deletingIds,
isAdding,
isDeleting,
isFetching,
notes
} = this.state;
return (
<div className="Notes">
<h1>
Notes
{' '}
<button
className="Notes-updateButton"
disabled={isAdding || isDeleting || isFetching}
type="button"
onClick={this.handleUpdateClick}
>
{isFetching ? (
<FontAwesomeIcon
icon={faSpinner}
size="lg"
spin
/>
) : (
<FontAwesomeIcon
icon={faSync}
size="lg"
/>
)}
</button>
</h1>
<NotesList
deletingIds={deletingIds}
items={notes}
onNoteDelete={this.handleNoteDelete}
/>
<NotesAddForm
isLoading={isAdding}
onSubmit={this.handleAddFormSubmit}
/>
</div>
);
}
}
export default Notes;
|
// 查看、测试webpack的hook执行流程
const webpack = require('webpack')
const config = require('./webpack.config')
const compiler = webpack(config)
Object.keys(compiler.hooks).forEach(h=>{
compiler.hooks[h].tap('xxx',(compilation)=>{
console.log(`run----------------->${h}`)
})
})
compiler.run()
|
import React from 'react';
import PropTypes from 'prop-types';
import css from './cardSnippet.css';
const makeTagToElement = tagSet =>
tagSet.map((data, index) => (
<div key={index} className={css.tagInstance}>{data}</div>
));
const CardSnippet = ({ title, preview, tag }) => (
<div className={css.container}>
<div className={css.head}>
<div className={css.title}>
<div className={css.block} />
<div className={css.text}>{title}</div>
</div>
</div>
<div className={css.footer}>
<p className={css.preview}>{preview}</p>
<div className={css.tag}>
<img
className={css.tagImg}
src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACQAAAAkCAYAAADhAJiYAAAABGdBTUEAALGPC/xhBQAAA85JREFUWAnFmGuITVEUx9fa905DSRp55JGUD4QyM8ZMwjQZjyRFPilRCgmhKOKjkFeUmjxCvvognzC43fKaB5mQL8pIxAdKjME95yz/vc89d+bee2bOOfeeYde5e5+11t7rd9de+3EvU0xF7nXMI8fegOGaSWQK6srAoZm/kVA7JRIHeXFdu7bnwE4BBvKwayz97L0AiFUBpoOpbVKJldw871ZyMKsgnaQ6p1NPbyuRTDK2zBl84xQp6SRRn4L6o99Y2O9EPZLEvigik0uOkIGxrBQiMz7r+Cpm6QAvrfkYDNJnIa1tu0mcU0ZSUTGjpAgVwbDax0vqj/e5idBieY8oucWWSZGBimF4L2BO+CFIqmsWkbUdUzIXeosUd5CjTnJTdXfOXnI4RqRyihANf5gGf5j0081EmU4iZwuAavHUk+NsJ7ZfSKpj7UDuQgNFg3lejbw4Bwgsff6AyACaz2BNf0XOjSDmy5LumuoHFWrKosAYJ2IdwERgbH5HlcNreP7Mr1ou6RcniX49B1QVsbUHoh3Gvt9HYIQiw+jBheqyPlo8GP3OjbORwHzN6BzxbLKmbjUoUEkw7rhu5BVl8rzpF0/GVFGkM2o/KWRlwOgRkcwoQpvk0fvhpq1fH72qgmyd+47N06f45lCZMEQJdRorahVyZQb9+fxU0p2XyEFEfvduBdYETN5vSibP+vAggAWlbBiMx4tq0sRyCKsJuwygHMEqkyN4pkCWwarbyQvmvDKu86bOtvOA4oDxvh831h3WaYylfhP1B4B047mOEDRwY+15zw7A03JtlfiYO8vihMk5CNGQ1sfPkFfVgP1CzfXjTIT+G8y9ttUGRoMLXWdmW5nMtzJ3ETr31GZ9NvkfByG+cGgTHB+zyHYumg46ryr5mG4r6vl+FHQTs4p/B5Ox7sNnlfErtJ8b69/qdhIwy42QOfXPIuPCjHH9Ugv84khxi8IqyG5c0uMJh6o201QAQ80N2/r700n9wAiEV8idJ+v7K+NsDwSDRPauZ8adomTFXuwTP5HmGu7KUECFhdFEiptq32APWIOp+zUUUFFgNFDfxtjatgy3uxtI8mEQO9Bt5KUN7lVBW5ZQosJoFzkg/YJfALFBlQJTBBQXVKkwvkDlQpUDMyBQqVDlwgwKFBUqDphAoLBQccGEAgqCihMmNJAvFBOuDvhdTrwLV5fR2gabSIs+mwqPA6ML+ZG3DwX1yd+nCqxjgNEj5t2pC1wUveJPhds48hZC8TKnZPpBrHaUGxlvvEgR8jrpWtLtk+mPGkXJ2tfcxFZ/XTntv1uaNyKE8HLcAAAAAElFTkSuQmCC" />
{makeTagToElement(tag)}
</div>
</div>
</div>
);
CardSnippet.propTypes = {
title: PropTypes.string.isRequired,
tag: PropTypes.array.isRequired,
preview: PropTypes.string.isRequired,
};
CardSnippet.defaultProps = {
title: '',
tag: [],
preview: '',
};
export default CardSnippet;
|
function login(){
var xhr=createXhr();
xhr.onreadystatechange=function(){
if(xhr.readyState==4&&xhr.status==200){
var res=xhr.responseText;
console.log(res);
}
}
xhr.open("post","mypro/login",true);
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
var uname=$("uname").value;
var upwd=$("upwd").value;
var formData="uname="+uname+"&upwd="+upwd;
xhr.send(formData);
}
|
var WebSocket = require('ws').Server;
var wss = new WebSocket({port:8080});
wss.on('connection', function (ws) {
console.log('client connected');
ws.on('message', function (message) {
console.log(message);
wss.clients.forEach(function each(client) {
client.send('你说:' + message);
});
});
});
|
/* begin copyright text
*
* Copyright © 2016 PTC Inc., Its Subsidiary Companies, and /or its Partners. All Rights Reserved.
*
* end copyright text
*/
/* jshint node: true */
/* jshint strict: global */
/* jshint eqnull:true */
/* jshint esversion: 6 */
'use strict';
var ms = require('ms');
var os = require('os');
var ESAPI = require('node-esapi');
var url = require('url');
var lodash = require('lodash');
var path = require('path');
var fs = require('fs');
var cryptoConstants = require('crypto').constants;
var moment = require('moment');
var maxMaxAge = 60 * 60 * 24 * 365 * 1000; // 1 year
var minAuthorizationRefreshRate = ms('30 seconds');
var defaultAuthorizationRefreshRate = ms('5 minutes');
var cryptoHelper = require('./cryptoHelper');
exports.debugCallback = function(debug, msg) {
return function() {debug(msg, JSON.stringify(arguments.length === 1 ? arguments[0] : arguments)); };
};
exports.quoteString = function(thisString) {
return "'" + (thisString ? thisString.replace(/'/g,"''") : thisString ) + "'";
};
exports.removeElementFromArray = function(thisArray, thisElement, debug) {
if (thisArray && thisArray.length > 0) {
var index = thisArray.indexOf(thisElement);
if (index > -1) {
if (debug) {
debug("Element " + thisElement + " found at index: " + index);
}
thisArray.splice(index, 1);
return true;
} else {
if (debug) {
debug("Element " + thisElement + " not found in array: " + JSON.stringify(thisArray));
}
}
}
return false;
};
exports.printErrorOnConsole = function(error, filename, debug, debugMessage) {
if (debug) {
debug((debugMessage || "") + (error.stack || error));
}
console.error(filename, (error.stack || error));
};
/**
* Validates and returns the validated port
*/
exports.validatePort = function(port) {
if (typeof port === "string") {
if (/^\d+?$/.test(port)) {
port = parseInt(port, 10);
}
}
if (isNaN(port) || typeof port !== 'number' || port%1 !== 0) {
throw new Error("Invalid port [requires an integer between 1 and 65535]:" + JSON.stringify(port));
}
if (port < 1 || port > 65535) {
throw new Error("Invalid port [requires an integer between 1 and 65535]: " + port);
}
return port;
};
/**
* Returns the max age in seconds based on the maxAge property set in opts
*/
exports.getMaxAgeInSeconds = function(opts) {
return Math.floor(this.getMaxAge(opts)/1000);
};
exports.getMaxAge = function(opts) {
// To be exactly as the maxAge configuration property of static
// serve (or serve static) in express, the below code is a copy from their
// implementation. Sepcifically from the below two files:
// 1) send/index.js - version 0.13.1
// https://github.com/pillarjs/send/blob/master/index.js#L125
// 2) expressjs/serve-favicon/index.js - version 2.3.0
// https://github.com/expressjs/serve-favicon/blob/master/index.js#L125
var maxage = opts ? (opts.maxAge || opts.maxage) : null;
maxage = typeof maxage === 'string' ? ms(maxage) : Number(maxage);
maxage = !isNaN(maxage) ? Math.min(Math.max(0, maxage), maxMaxAge) : 0;
return maxage;
};
/**
* Validates the defaultDomainName and returns:
* a) An overwritten domain (hostname.local) if --nodn command-line option
* was specified
* b) The trimmed value of defaultDomainName property
* If NULL/Undefined/EPMTY after trimming, exits the process with code 1
* while printing an error on the console.
*/
exports.validateDefaultDomainName = function(defaultDomainName, nodn) {
if (nodn) {
defaultDomainName = this.getSimpleHostname() + ".local";
} else {
var isValid = false;
if (defaultDomainName && typeof defaultDomainName === 'string') {
defaultDomainName = defaultDomainName.trim();
if (defaultDomainName) {
isValid = true;
}
}
if (!isValid) {
defaultDomainName = {error: [
"ERROR >>> ExperienceService's 'defaultDomainName' property is invalid.",
"You can set the 'defaultDomainName' property to a valid",
"domain name string in one of three ways:",
" 1) Using the ExperienceService's configuration file OR",
" 2) Using the '--defaultDomainName' command-line option OR",
" 3) Using the '--nodn' command-line option",
" (use only when running ExperienceService in developer mode)",
"Option 3 overrides the 'defaultDomainName' property to",
"use '<hostname>.local' which renders the data unfit for",
"migration and replication.",
"Please refer to the ExperienceService documentation for more information about",
"the 'defaultDomainName' property and how to set it."]};
}
}
return defaultDomainName;
};
/**
* Returns the simple hostname or localhost if no hostname
* was returned by the native API
*/
exports.getSimpleHostname = function() {
var name = os.hostname();
var pi = name.indexOf('.'); // extract the simple hostname
if (pi > 0) {
name = name.substr(0, pi);
}
return name;
};
/**
* Translates the command-line options to configuration properties
*/
exports.translateCommandLineOptsToConfigProperties = function(config) {
if (config && typeof config === 'object') {
if (process.argv.indexOf('-dev') > 0 || config.dev != null) {
// Dev mode defaults
config.nossl = true;
config.nodn = true;
} else {
if (process.argv.indexOf('-nossl') > 0) { config.nossl = true; }
if (process.argv.indexOf('-nodn') > 0) { config.nodn = true; }
}
} else {
throw new Error("Cannot translate to properties on an invalid object: " + config);
}
};
exports.getAuthorizationRefreshRate = function(opts) {
var refreshRate = opts && opts.authorization ? opts.authorization.refreshRate : defaultAuthorizationRefreshRate;
refreshRate = typeof refreshRate === 'string' ? ms(refreshRate) : Number(refreshRate);
refreshRate = isNaN(refreshRate) ? defaultAuthorizationRefreshRate : Math.max(refreshRate, minAuthorizationRefreshRate);
return refreshRate;
};
exports.encodeForJavaScript = function(value) {
if (value) {
return ESAPI.encoder().encodeForJavaScript(value === 'object' ? JSON.stringify(value) : String(value));
} else {
return value;
}
};
exports.intersectArrays = function(a, b) {
if ( !a || !b) {
return [];
}
var t;
if (b.length > a.length) {// to loop over shorter
t = b; b = a; a = t;
}
return a.filter(function(e) {
return (b.indexOf(e) !== -1);
});
};
//recursively removes null and empty string properties
exports.cleanConfig = function(config){
for (var key in config) {
var value = config[key];
if (value == null || value === '') {
delete config[key];
}
else if (typeof value === 'object') {
this.cleanConfig(value);
}
}
return config;
};
exports.getTrustProxy = function getTrustProxy(trustProxy) {
if (lodash.isString(trustProxy)) {
var stringValue = String(trustProxy).toLowerCase();
if (stringValue === 'true' || stringValue === 'false') {
return (stringValue === 'true');
}
}
return trustProxy;
};
//format timestamp as YYYY-MM-DDTHH:MM:SS.sssTZ (full ISO-8601 format)
exports.formatTimestamp = function(ts){
if ( ts != null && (typeof ts === 'string' || typeof ts === 'number')){
var mo = new moment.utc(ts);
if (mo.isValid()) {
return mo.toISOString();
} else {
console.warn("Invalid timestamp format", ts );
}
}
return ts;
};
exports.setAuthenticationConfiguration = function setAuthenticationConfiguration(authConfig) {
// WARNING !!! This function is also called from the installer.
// Please ensure compatibility when making changes.
if (lodash.isPlainObject(authConfig)) {
if (authConfig.baseUrl) {
var parsedBaseUrl = url.parse(authConfig.baseUrl);
authConfig.protocol = parsedBaseUrl.protocol;
authConfig.port = parsedBaseUrl.port;
authConfig.hostname = parsedBaseUrl.hostname;
} else if (authConfig.protocol && !authConfig.protocol.endsWith(":")) {
authConfig.protocol = authConfig.protocol + ":";
}
}
return authConfig;
};
/**
* Load HTTPS certificates.
*/
exports.loadHTTPSOptions = function loadHTTPSOptions(settings) {
var options = {};
if (settings.httpsPfxPath && (settings.httpsKeyPath ||
settings.httpsCrtPath || settings.httpsCaPath)){
throw new Error("Invalid configuration: httpsPfxPath and any of httpsKeyPath/httpsCrtPath/httpsCaPath cannot be specified together");
}
if (settings.httpsCertPassphrase) {
if (typeof(settings.httpsCertPassphrase) !== "string") {
throw new Error("Invalid configuration: httpsCertPassphrase has to be a string");
}
options.passphrase = cryptoHelper.getProperty(settings.httpsCertPassphrase);
}
if (settings.httpsPfxPath) {
options.pfx = fs.readFileSync(settings.httpsPfxPath);
} else if (settings.httpsKeyPath && settings.httpsCrtPath) {
options.key = fs.readFileSync(settings.httpsKeyPath);
options.cert = fs.readFileSync(settings.httpsCrtPath);
if (settings.httpsCaPath) {
options.ca = fs.readFileSync(settings.httpsCaPath);
}
} else {
throw new Error("Invalid configuration: Either httpsPfxPath or httpsKeyPath/httpsCrtPath have to be specified");
}
/*jshint camelcase: false */
/*jshint bitwise: false */
options.secureOptions = cryptoConstants.SSL_OP_NO_SSLv2
| cryptoConstants.SSL_OP_NO_SSLv3 | cryptoConstants.SSL_OP_NO_TLSv1;
return options;
};
const mapDeepValue = (json, cb) =>
lodash.mapValues(json, (v, k) =>
lodash.isPlainObject(v) ? mapDeepValue(v, cb) : cb(v, k, json)
);
exports.mapDeepValue = mapDeepValue;
/**
* Normalizes the path
*/
exports.normalizePath = function normalizePath(pathToNormalize) {
if (!lodash.isString(pathToNormalize) || pathToNormalize.length === 0) {
return pathToNormalize;
} else if (path.isAbsolute(pathToNormalize)) {
return path.normalize(pathToNormalize);
} else {
return path.resolve(__dirname, pathToNormalize);
}
};
exports.throwError = function throwError(error, status) {
var err = null;
if (typeof error === 'string') { err = new Error(error); }
else { err = error || new Error(); }
if (!err.status) {err.status = status || 400; }
throw err;
};
exports.wrapIfPassphraseError = function(err){
if (err && err.message && (err.message.includes("mac verify failure") ||
err.message.includes("bad decrypt") || err.message.includes("bad password read"))){
err.message = "Invalid configuration: httpsCertPassphrase may not contain correct passphrase for certificate. " +
"Original error: " + err.message;
}
return err;
};
exports.removeURLParameter = function(url, parameter) {
if (!url || !parameter) {
return url;
}
//prefer to use l.search if you have a location/link object
var urlparts= url.split('?');
if (urlparts.length>=2) {
var prefix= encodeURIComponent(parameter)+'=';
var pars= urlparts[1].split(/[&;]/g).filter(part => part.length > 0);
//reverse iteration as may be destructive
for (var i= pars.length; i-- > 0;) {
//idiom for string.startsWith
if (pars[i].lastIndexOf(prefix, 0) !== -1) {
pars.splice(i, 1);
}
}
return urlparts[0] + (pars.length > 0 ? '?' + pars.join('&') : '');
}
return url;
};
/**
* Parse JSON ignoring parsing error
* @param text Input test to be parsed
* @param defaultObject Default object returned in case of parsing error.
* `undefined` returned when parameter is not specified
* @returns Parsed javascript value
*/
exports.safeJsonParse = function safeJsonParse(text, defaultObject) {
try {
return JSON.parse(text);
} catch(e) {} // eslint-disable-line no-empty
return defaultObject;
};
|
/**
* Created by juancarlosnavarrete on 4/16/17.
*/
var myChoices = [ 'Views Products for Sale', 'View Low Inventory', 'Add to Inventory', 'Add new Product', 'exit'];
var lowInventory = 'SELECT * FROM products WHERE stock_quantity < 5';
var selectAll = 'SELECT * FROM products';
var addInventory = 'UPDATE products SET stock_quantity=? where id = ?';
var addItem = 'INSERT INTO products (product_name, department_name, price, stock_quantity) VALUES (?,?,?,?)';
var invalidInput = '\n\tInvalid input(s), please Try again.\n';
exports.myChoices = myChoices;
exports.lowQuantityItems = lowInventory;
exports.selecAll = selectAll;
exports.addInventory = addInventory;
exports.addItem = addItem;
exports.invalidInput = invalidInput;
|
import React, {Component} from 'react';
import classnames from 'classnames';
import PropTypes from 'prop-types';
import { toggleDropdown } from 'Utils/toggle';
/**
* @description Returns a Custom list
* @class {CustomList}
* @param {Object} props- component props
* @param {string} props.identifier - id for the <ul> tag
* @param {string} props.listContent - Items to appear on list
* @param {string} props.listDirection - Direction of list to be display , with triangle inclusive
* @param {Object} [...rest] - Any class props to be added to <ul>
* @returns {JSX} - JSX Component
*/
const propTypes = {
identifier: PropTypes.string.isRequired,
listDirection: PropTypes.string,
listContent:PropTypes.array.isRequired,
rest: PropTypes.obejct,
children: PropTypes.node,
dropdownInitiator: PropTypes.string.isRequired
}
class CustomList extends Component{
componentDidMount(){
const {
dropdownInitiator,
identifier
} = this.props
toggleDropdown(`.${dropdownInitiator}`,`#${identifier}`);
}
render(){
const {
listContent,
listDirection,
identifier,
...rest
} = this.props;
{/**Switch Lists attached arrow position based on usual choice*/}
let pos
switch (listDirection){
case 'up':
pos='u';
break;
case 'right':
pos='r';
break;
case 'left':
pos='l';
break;
default:
pos='d'
}
const listItems = listContent.map((item, index)=>
<li key={index}
role={item.role?item.role:''}
onClick = {item.onClick ? item.onClick: null }
className = {classnames(item.role=='seperator'?'divider':'list-item',
item.role=='header'?'dropdown-header':'')}
style = {{...item['role'] === 'header' ? {fontSize:'17px'}:{fontSize:'16px'}}}>
{(!item.role || item['role']!=='seperator') &&
<a href={item.href}>{item.name}</a>
}
</li>
);
return(
<ul id = {identifier}
className={classnames(
`dropdown-menu dropdown-menu-triangle-b-${pos}`
)}
{...rest}>
{this.props.children &&
<li>{this.props.children}</li>
}
{listItems}
</ul>
);
}
}
CustomList.propTypes = propTypes;
export default CustomList
|
import React from 'react';
import Barrels from './Components/barrels.jpg';
import Budweiser from './logos/Budweiser.jpg'
import Busch from './logos/Busch.gif';
import Corona from './logos/Corona.jpg';
import Michelob from './logos/Michelob.jpg';
import Natural from './logos/Natural.jpg';
import ShockTop from './logos/ShockTop.jpg';
function Home() {
return (
<div className='text-center'>
<div>
<h1 className='pt-3'>Welcome to Cerveza Heaven</h1>
<h5>The land of all beers</h5>
<img src={Barrels} style={{width: '500px'}} className='mt-2 mb-2 img-thumbnail' alt='Barrels of Beer'></img>
</div>
<div>
<h2>Our Story</h2>
<p className='p-5 ml-5 mr-5'>
Cerveza Heaven was started by a pair of young entrepreneurs that had a love for beer.
It did not matter whether the beer came from a local gas station, their uncle's garage brewery,
or the cooler section of a Walmart. One day, Bill and Ted decided to switch it up from their long time
favorite beer, Busch Lite, and try a beer so magnificent that a virus was named after it. That's right,
Bill and Ted tried the one and only Corona. They soon found out that Mexican beer can be just as good, if
not better than the classNamey Busch Lite. After having a few sips of Corona, Ted had an epiphany. He told Bill
that they should open a liquor store and sell only Anheuser-Busch and Corona products. Bill was ecstatic
about the idea and agreed to join Ted in the business. Bill and Ted needed an investor in their business, and this
is where I came into the picture. I decided to help fund Bill and Ted's idea, and we came to an agreement that I would get
69% of the business. Unfortunately, both of them have left me stranded with the business. You see,
Bill and Ted went on a haitus, an excellent adventure if you will. I have not heard from them in years, however I bring you
<strong> Cerveza Heaven</strong>, the heaven for Corona and Busch fans alike.
</p>
</div>
<div className='container pt-3'>
<p><strong>Proud Supplier of</strong></p>
<div className='row pt-3'>
<a className='col-sm-4' href='/shop/#budweiser' title='Budwesier'>
<img src={Budweiser}
className='p-2'
width='100%'
alt='Budweiser Logo'
></img>
</a>
<a className='col-sm-4' href='/shop/#busch' title='Buschhhhhhh'>
<img src={Busch}
className='p-2'
width='100%'
alt='Busch Lite Logo'
></img>
</a>
<a className='col-sm-4' href='/shop/#corona' title='Corona Extra'>
<img src={Corona}
className='p-2'
width='100%'
alt='Corona Logo'
></img>
</a>
</div>
<div className='row pt-3 pb-3'>
<a className='col-sm-4' href='/shop/#michelob' title='Michelob Ultra'>
<img src={Michelob}
className='p-2'
width='100%'
alt='Michelob Ultra Logo'
></img>
</a>
<a className='col-sm-4' href='/shop/#natural' title='Natty Light'>
<img src={Natural}
className='p-2'
width='100%'
alt='Natural Light Logo'
></img>
</a>
<a className='col-sm-4' href='/shop/#shocktop' title='Shock Top'>
<img src={ShockTop}
className='p-2'
width='85%'
alt='Shock Top Logo'
></img>
</a>
</div>
</div>
</div>
);
}
export default Home;
|
import { Routes } from "./Routes";
import { BrowserRouter as Router } from "react-router-dom";
import { Container, Divider } from "@mui/material";
import { GolbalProvider } from "./context/GlobalState";
import { Header } from "./components/header/Header";
import NotificationAlert from "./components/notificationAlert/NotificationAlert";
function App() {
return (
<GolbalProvider>
<Header />
<Divider />
<Container maxWidth="md">
<Router>
<Routes />
</Router>
</Container>
<NotificationAlert />
</GolbalProvider>
);
}
export default App;
|
/**
* Created by linxin on 2017/1/11.
*/
export const addevent = ({ commit }, param) =>{
commit('ADDEVENT',{items: param});
}
export const eventdone = ({ commit }, param) =>{
commit('EVENTDONE',{id: param});
}
export const eventtodo = ({ commit }, param) =>{
commit('EVENTTODO',{id: param});
}
export const eventcancel = ({ commit }, param) =>{
commit('EVENTCANCEL',{id: param});
}
export const clearevent = ({ commit }) =>{
commit('CLEAREVENT');
}
export const delevent = ({ commit }, param) =>{
commit('DELEVENT', param);
}
export const editevent = ({ commit }, param) =>{
commit('EDITEVENT', param);
}
|
/* eslint-disable max-len */
// // the passed array gets sorted by attr. attr needs to be a String.
// /**
// *
// * @param {Array} arr
// * @param {string} attr
// */
// function sortWrapper(arr, attr) {
// // just for testing
// let nullCounter = 0;
// // just for testing
// arr.forEach((lib) => {
// if (lib[attr] == null) {
// nullCounter += 1;
// }
// });
// // just for testing
// console.log('nullCounter');
// console.log(nullCounter);
// // descending order.
// arr.sort((a, b) => b[attr] - a[attr]);
// }
// /**
// * atrOnePath and atrTwoPath contain the path to the elements of interest.
// * i.e. the path [user, adress, city] would give us THIS VALUE
// * {
// * id:
// * user: {
// * name:
// * tele:
// * adress: {
// * city: THIS VALUE!
// * ...
// *
// * @param {Object[]} data
// * @param {Array.<string>} atrOnePath
// * @param {Array.<string>} atrTwoPath
// */
// function getTwoAttributesNested(data, atrOnePath, atrTwoPath, objId) {
// const ret = [];
// data.forEach((d) => {
// const xVal = atrOnePath.reduce((obj, key) => ((obj && obj[key] !== 'undefined') ? obj[key] : undefined), d);
// const yVal = atrTwoPath.reduce((obj, key) => ((obj && obj[key] !== 'undefined') ? obj[key] : undefined), d);
// const iD = objId.reduce((obj, key) => ((obj && obj[key] !== 'undefined') ? obj[key] : undefined), d);
// ret.push({ x: xVal, y: yVal, id: iD });
// });
// return ret;
// }
const sizeOfCircle = 8;
/**
* Calculates the max edgeLengt for artifact
* such that all artifacts fit into the screenspace for the given svgDim.
* @param {Number} numberOfArtifact - number of datapoints we want to display.
* @param {Object} svgDim - width: and height:
* @returns {Number} - max edge length.
*/
function calcEdgeLen(numberOfArtifact, svgDim) {
const { width } = svgDim;
const { height } = svgDim;
const pixelTotal = width * height;
const pixelPerArtifact = pixelTotal / numberOfArtifact;
const edgeLength = Math.floor(Math.sqrt(pixelPerArtifact));
return edgeLength;
}
function getUniquePart(id) {
// elem ids have the form app-view-svg or app-view. We are interested in the first part.
return id.split('-')[0];
}
function createTooltip() {
d3.select('#viscontainer')
.insert('div')
.attr('id', 'tooltip')
.style('opacity', 0);
}
const colorscales = {
cve: d3.scaleThreshold() /// / original nist color
.domain([0.1, 4.0, 7.0, 9.0])
.range(['darkgrey', '#ffe358', '#edb15c', '#d9534f', 'black']), // original nist color: f2cc0c
goodall: d3.scaleThreshold() // paper goodall et al.
.domain([1, 2, 3, 4, 5, 6, 7, 8, 9])
.range(['darkgrey', '#ffffd9', '#edf8b1', '#c7e9b4', '#7fcdbb', '#41b6c4', '#1d91c0', '#225ea8', '#253494', '#081d58']),
epss: d3.interpolateOrRd,
cluster: d3.scaleOrdinal()
.domain([-1, 6])
.range(['darkgrey', '#fff1f1', '#6fdc8c', '#ff7eb6', '#e6ab02', '#bae6ff', '#ffff99', '#d4bbff']),
linear: d3.scaleLinear()
.domain([1, 739])
.range(['#deebf7', '#3182bd']),
log: d3.scaleLog()
.domain([1, 739]) // domain cannot start at 0!! log.
.range(['#deebf7', '#3182bd']),
circleScale: d3.scaleSqrt()
.domain([1, 739])
.range([sizeOfCircle, sizeOfCircle]),
};
export {
// eslint-disable-next-line max-len
calcEdgeLen, getUniquePart, createTooltip, colorscales, sizeOfCircle,
};
|
// @flow
export * from './core/Core.js';
export { default as GameObject } from './scene/GameObject.js';
export { default as Scene } from './scene/Scene.js';
export * from './utils/Utils.js';
|
const { stdin } = process
stdin.setEncoding('utf8')
const readLine = () =>
new Promise((resolve, reject) => {
stdin.once('data', resolve)
stdin.once('error', reject)
})
/**
* @deprecated Use readInputFiles() instead
* @see ./readInputFiles.js
* Reads input from a file, line by line. The first line is always the number of lines that follow (this format is given in the problems)
* @param {function} parseLine A callback to use for processing each line except the first
* @returns {Array}
*/
async function parseInputLineByLine(parseLine = null) {
try {
let input = []
if (stdin.end) {
const numberOfCases = await readLine()
// stdin was not redirected to a file (it's keyboard)
for (let i = 0; i < numberOfCases; i++) {
const rawLine = (await readLine()).split('\n')[0]
input.push(parseLine ? parseLine(rawLine) : rawLine)
}
stdin.end()
} else {
const fileContent = await readLine()
const allLines = fileContent.split('\n')
input = allLines
.slice(1) // skip the 1st line, it's the number of cases
.map(parseLine ? parseLine : x => x)
}
return input
} catch (e) {
console.error(e)
}
}
module.exports = { parseInputLineByLine }
|
import styled from 'styled-components';
const DateField = styled.input`
font-size: 20px;
display: inline-block;
/* float: left; */
width: 144px;
height: 34px;
padding: 1px;
`;
export default DateField
//position: absolute; to go overtop existing components
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var stores = {};
var storage = {
setItem: function setItem(k, v) {
stores[k] = v;
}, getItem: function getItem(k) {
return stores[k];
}, removeItem: function removeItem(k) {
delete stores[k];
}
};
exports.default = storage;
module.exports = exports["default"];
|
const chai = require('chai');
const expect = chai.expect;
const BufferController = require('../src/buffer-controller');
const { testConfig } = require('../src/config');
const { convertSizeStringToByteNumber } = require('../src/utils');
describe('BufferController class', () => {
let bufferController;
let dummyData = 'dummyData';
let bufferNameSnapshot;
let maxSize;
beforeEach(() => {
bufferController = new BufferController();
bufferNameSnapshot = bufferController.activeBuffer.name;
maxSize = convertSizeStringToByteNumber(testConfig.activeBufferMaxSize);
});
it('should create instance of BufferController', () => {
expect(bufferController).to.be.instanceOf(BufferController);
});
it('should write data to buffer', () => {
bufferController.write(dummyData);
expect(bufferController.activeBuffer.size).to.equal(dummyData.length);
});
it('should rollover buffer when overloaded', (done) => {
let byte = 'd';
var data = new Array(maxSize + 1).join(byte);
bufferController.write(data);
expect(bufferController.activeBuffer.size).to.equal(maxSize);
bufferController.write('should cause rollover event');
setTimeout(() => {
expect(bufferController.activeBuffer.size).to.equal(0);
expect(bufferController.activeBuffer.name).to.not.equal(bufferNameSnapshot);
done();
}, 5);
});
it('should rollover buffer when max age exceeded & size > 0', (done) => {
bufferController.write(dummyData);
expect(bufferController.activeBuffer.size).to.equal(dummyData.length);
setTimeout(() => {
expect(bufferController.activeBuffer.size).to.equal(0);
expect(bufferController.activeBuffer.name).to.not.equal(bufferNameSnapshot);
done();
}, testConfig.activeBufferMaxAge * 1000 + 10);
});
it('should not rollover buffer when max age exceeded & size > 0 but allowTimeRollover=false', (done) => {
testConfig.allowTimeRollover = false;
bufferController = new BufferController();
bufferNameSnapshot = bufferController.activeBuffer.name;
bufferController.write(dummyData);
expect(bufferController.activeBuffer.size).to.equal(dummyData.length);
setTimeout(() => {
expect(bufferController.activeBuffer.size).to.equal(dummyData.length);
expect(bufferController.activeBuffer.name).to.equal(bufferNameSnapshot);
done();
}, testConfig.activeBufferMaxAge * 1000 + 10);
});
it('should not rollover buffer when max age exceeded & size == 0', (done) => {
expect(bufferController.activeBuffer.size).to.equal(0);
setTimeout(() => {
expect(bufferController.activeBuffer.size).to.equal(0);
expect(bufferController.activeBuffer.name).to.equal(bufferNameSnapshot);
done();
}, testConfig.activeBufferMaxAge * 1000 + 10);
});
it('should emit event when buffer has exchanged', (done) => {
let byte = 'd';
var data = new Array(maxSize + 1).join(byte);
bufferController.on('bufferExchange', (e) => {
let bufferNameSnapshotStored = bufferNameSnapshot.replace(testConfig.activeBufferFileExtension, testConfig.inactiveBufferFileExtension);
expect(bufferController.activeBuffer.name).to.not.equal(bufferNameSnapshot);
expect(e.fileName).to.equal(bufferNameSnapshotStored);
done();
});
bufferController.write(data);
bufferController.write('should cause rollover event');
});
});
|
/**
* Created by ShriRam on 2/17/2017.
*/
import React from 'react';
import {Link} from 'react-router';
const Main = React.createClass ({
render(){
return(
<div>
<h1> <Link to="/"> Reductageam</Link> </h1>
{React.cloneElement(this.props.children,this.props)}
</div>
)
}
})
export default Main;
|
import config from './config'
import {map, omit, filter} from 'lodash'
import { createBaseSelectors, buildSortedOptionList } from '../common/selectors'
import FormTemplateSelectors from '../form-templates/selectors'
import {createSelector} from 'reselect'
const Selectors = createBaseSelectors(config.entityName)
Selectors.buildNewEntity = () => {
let newEntity = {
labels: {
fr: 'Nouveau raccourci',
en: 'New shortcut'
},
isArchived: false
}
return newEntity
}
Selectors.getFormTemplateOptions = createSelector(
[FormTemplateSelectors.getEntities, Selectors.getEntities, Selectors.getEditedEntity],
(formTemplates, formShortcuts, editedShortcut) => {
const currentId = editedShortcut ? editedShortcut.id : null
const usedShortcuts = omit(formShortcuts, currentId)
const formIds = new Set(map(usedShortcuts, 'formTemplateId'))
const validFormTemplates = filter(formTemplates, template => {
return !formIds.has(template.id) && !template.preventShortcut
})
return buildSortedOptionList(validFormTemplates, 'name')
}
)
export default Selectors
|
/*global describe: true, expect: true, it: true, xdescribe: true, xit: true */
xdescribe('jsdoc/template', function() {
// TODO
});
|
const tools = require('./tools');
//const strToManipulate = "Lorem ipsum dolor sit amet, consectetur adipiscing elit";
const strToManipulate = process.argv[2];
const capital = tools.capitalizeEach(strToManipulate);
const reversing = tools.reverseStr(capital);
console.log(capital);
console.log(reversing);
|
const express = require('express')
// 创建应用对象
const app = express()
//禁止服务器返回powered-by,意思是说明搭建服务器的工具,服务器是基于什么搭建起来的,安全性
app.disable('X-Powered-By');
// 暴露静态资源,使用户直接在地址栏输入地址也可以看得见
app.use(express.static('public'))
// 声明使用解析post请求的中间件
app.use(express.urlencoded({extended: true})) // 请求体参数是: name=tom&pwd=123
// 声明使用路由器中间件
const indexRouter = require('./router')
app.use(indexRouter)
//测试接口
app.get('/',(req,res)=>{
res.setHeader('Access-Control-Allow-Origin','*') // 设置响应头解决跨域
res.send('我是主页')
})
app.post('/test',(req,res)=>{
res.send(req.body)
})
// 首页的10个图标处
app.get('/iconList',(req,res)=>{
res.setHeader('Access-Control-Allow-Origin','*')
res.send('')
})
//给服务器指定端口
app.listen(3000,function (err) {
if (!err){
console.log('服务器连接成功')
console.log('服务器地址:http://localhost:3000')
} else {
console.log('服务器连接失败')
}
})
|
import { connect } from 'react-redux';
import Admin from 'components/admin/admin';
const mapStateToProps = state => ({
roles: state.keycloak.roles,
});
export default connect(mapStateToProps)(Admin);
|
import test from "tape"
import { escapeRegExp } from "./escape-reg-exp"
test("escapeRegExp", t => {
const actualT1 = escapeRegExp("lorem. ipsum [dolor] (sit amet)?")
const expectedT1 = "lorem\\. ipsum \\[dolor\\] \\(sit amet\\)\\?"
t.equal(actualT1, expectedT1, "Chars: (, ), [, ], ?, . should be escaped")
const actualT2 = escapeRegExp("Alice + Bob = $orry | A < B | f* => {}")
const expectedT2 = "Alice \\+ Bob = \\$orry \\| A \\< B \\| f\\* =\\> \\{\\}"
t.equal(
actualT2,
expectedT2,
"Chars: +, $, |, <, >, *, {, } should be escaped"
)
t.end()
})
|
import React, { Component } from 'react';
import {StyleSheet, Text, View} from 'react-native';
export class Gauge extends Component {
constructor() {
super();
this.state = {
value: null
}
}
componentWillMount() {
setInterval(() => {
this.setState({
value: this.state.value + 1
})
},1000)
}
render() {
return (
<View>
<Text style={styles.meter}>{this.state.value}</Text>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
meter: {
textAlign: 'center',
color: '#333333',
fontSize: 45,
fontWeight: 'bold',
color: 'teal',
marginBottom: 5,
},
});
export default Gauge
|
module.exports = function(sequelize, DataTypes) {
return sequelize.define("Municipality", {
name: DataTypes.STRING,
internet1: DataTypes.FLOAT,
internet3: DataTypes.FLOAT,
internet10: DataTypes.FLOAT,
internet30: DataTypes.FLOAT,
internet100: DataTypes.FLOAT
})
}
|
import React from 'react';
import { Row, Col,Card, Button, Icon, Modal, Message} from 'antd';
import BasicTable from './Table'
import {fetch} from '../../api/tools'
import { receiveData, fetchData } from '@/action';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as config from '../../api/config';
class Home extends React.Component {
state = {
visible: false,
newsInfo:[],
userInfo:{},
modalContent: {},
usersWallet:{}
};
showModal = (item) => {
this.setState({
visible: true,
modalContent: item
});
let params = {
id: item.id,
status: 1,
}
// fetch('put','/usercenter/messages/update',params).then(res=>{
// if(res.code == 0){
// this.fetchNews()
// this.props.fetchData({funcName:'unreadNews',stateName: 'unreadNewsNum'})
// }else{
// Message.error(res.msg)
// }
// })
};
handleCancel = (e) => {
this.setState({
visible: false,
});
};
goDetail = (record) =>{
// let detailName = record.serviceName + record.accessType
let detailName = record.serviceName
localStorage.setItem('serviceName', detailName)
this.props.history.push(`/app/service/detail/${record.appKey}`)
}
componentDidMount(){
// this.fetchNews()
// let userInfo = this.props.userInfo && this.props.userInfo.data && this.props.userInfo.data.data
// if(userInfo){
// this.setState({userInfo: userInfo})
// }else{
// this.props.fetchData({funcName:'userInfo',stateName: 'userInfo'})
// }
// let usersWallet = this.props.usersWallet && this.props.usersWallet.data && this.props.usersWallet.data.data
// if(usersWallet){
// this.setState({usersWallet: usersWallet})
// } else{
// this.props.fetchData({funcName:'usersWallet',stateName: 'usersWallet'})
// }
}
fetchNews = () => {
// fetch('get','/usercenter/messages/list?current=1&size=2').then(res=>{
// if(res.code == 0){
// this.setState({newsInfo: res.data.records,})
// }else{
// Message.error(res.msg)
// }
// })
}
componentWillReceiveProps(nextProps) {
let usersWallet = nextProps.usersWallet && nextProps.usersWallet.data && nextProps.usersWallet.data.data || {}
let userInfo = nextProps.userInfo && nextProps.userInfo.data && nextProps.userInfo.data.data||{}
this.setState({usersWallet: usersWallet, userInfo: userInfo})
}
toNewService(){
window.location.href = `${config.BASE_PATH}serviceList`
}
render() {
let { newsInfo, modalContent, userInfo, usersWallet } = this.state
return (
<div className="gutter-example">
<Row type="flex" justify="start">
<Card style={{ width: 420 ,marginRight: 20}}>
<p>{userInfo.accountLevel}</p>
<p>欢迎,{userInfo.nickName || userInfo.username} <a onClick={()=>this.props.history.push('/app/system/authentication')}>{userInfo.certifiedStatus}</a></p>
<p>上次登录时间:{userInfo.lastLoginTime}</p>
<Button type='primary' onClick={()=>this.props.history.push('/app/system/setAccount')}>账号设置</Button>
</Card>
<Card style={{ width: 420 }}>
<p>账户余额</p>
<p className="f18">¥<span className="f36">{usersWallet.balance}</span></p>
<Button type='primary' onClick={()=>this.props.history.push('/app/account/balance')}>去充值</Button>
</Card>
</Row>
{newsInfo.length>0 && <div style={{background:'white', width:'100%',marginTop: 15, marginBottom: 15, padding: 10}}>
<Row type="flex" justify="space-between" align='middle'>
<div>
{newsInfo.map((item,index)=>
<p className={'y-center'} onClick={()=>this.showModal(item)} key={index}>
{item.type == 1 && '【系统消息】'}
{item.type == 0 && '【后台消息】'}
<span className={item.status==0?'c-blue col-content':'col-content'}>{item.content}</span> {item.createTime}
</p>
)}
</div>
<Button type='primary' onClick={()=>this.props.history.push('/app/system/news')}>查看全部</Button>
</Row>
</div>}
<Row gutter={16}>
<Col className="gutter-row" md={24}>
<div className="gutter-box">
<Card title="我的数据" bordered={false}>
<BasicTable type={1} goDetail={this.goDetail}/>
</Card>
</div>
</Col>
</Row>
<Button type='primary' style={{marginTop: 15,width: '100%', height: 42}} onClick={this.toNewService}>
<Icon type='plus' style={{fontSize: 13}} />申请数据服务
</Button>
<Modal title="消息详情"
visible={this.state.visible}
onCancel={this.handleCancel}
footer={false}
>
<p style={{fontSize: '13px',marginLeft:'-5'}}>{modalContent.type == 1 &&'【系统消息】'}{modalContent.type == 0 &&'【后台消息】'} {modalContent.createTime}</p>
<p style={{color: '#ababab'}}>{modalContent.content}</p>
<div className="modal-footer-btn">
<Button type='primary' onClick={this.handleCancel}>我知道了</Button>
</div>
</Modal>
</div>
);
}
}
const mapStateToProps = state => {
const { usersWallet = {data: {}} , userInfo = {data: {}} } = state.httpData;
return {usersWallet, userInfo};
};
const mapDispatchToProps = dispatch => ({
fetchData: bindActionCreators(fetchData, dispatch),
});
export default connect(mapStateToProps, mapDispatchToProps)(Home)
|
import {inject, bindable, bindingMode} from 'aurelia-framework';
import {Router, Redirect} from 'aurelia-router';
import * as palette from 'google-palette';
import {ApiInterface} from '../services/api-interface';
import {state} from '../services/state';
import {destroyCharts, generateCharts} from '../services/draw-charts';
@inject(Router, ApiInterface)
export class User {
@bindable({ defaultBindingMode: bindingMode.twoWay }) state = state;
constructor(Router, ApiInterface) {
this.router = Router;
this.api = ApiInterface;
this.pagination = { perPage: 10, created: 0, participated: 0 };
this.charts = { created: [], participated: [] };
this.user = { created: [], participated: [] };
}
canActivate() {
if(this.state.user.username === null) {
if(this.router.history.previousLocation === '/home' || this.router.history.previousLocation === '/polls') {
return(false);
}
else {
return(new Redirect('home'));
}
}
}
async activate(params, routeConfig, navigationInstruction) {
if(!this.state.polls.length || (this.state.toUpdatePolls.now !== null && (Date.now() - this.state.toUpdatePolls.now) > 60000)) {
let response = await this.api.getPolls();
this.state.polls = response.map((v, i, a) => v);
this.state.toUpdatePolls.now = Date.now();
this.state.toUpdatePolls.updated = true;
}
this.user.created = this.state.polls.filter((v, i, a) => v.owner === this.state.user.username);
this.user.participated = this.state.polls.filter((v, i, a) => v.voters[this.state.user.username] !== undefined && v.voters[this.state.user.username] !== null);
}
attached() {
let canvas = [
['created', document.getElementById('created').getElementsByTagName('canvas')],
['participated', document.getElementById('participated').getElementsByTagName('canvas')]
];
generateCharts(palette, canvas, this.charts, this.state);
}
detached() {
destroyCharts(this.charts);
this.charts = null;
this.user = {};
this.pagination = {};
}
setPaginationAmount(amount) {
destroyCharts(this.charts);
this.pagination.perPage = Number(amount);
setTimeout(() => {
let canvas = [
['created', document.getElementById('created').getElementsByTagName('canvas')],
['participated', document.getElementById('participated').getElementsByTagName('canvas')]
];
generateCharts(palette, canvas, this.charts, this.state);
}, 0);
}
changePage(direction, poll) {
destroyCharts(this.charts[poll], 'array');
if(direction === 'prev') {
this.pagination[poll] = (this.pagination[poll] - this.pagination.perPage) < 0
? 0
: this.pagination[poll] - this.pagination.perPage;
}
else {
this.pagination[poll] = (this.pagination[poll] + this.pagination.perPage) > this.state.polls.length
? this.state.polls.length - this.pagination.perPage
: this.pagination[poll] + this.pagination.perPage;
}
setTimeout(() => {
let canvas = [[poll, document.getElementById(poll).getElementsByTagName('canvas')]];
generateCharts(palette, canvas, this.charts, this.state);
}, 0);
}
async createPoll() {
let id = await this.api.getPollID();
if(id) {
this.router.navigateToRoute('poll', { id: id, new: true });
}
else {
this.router.navigateToRoute('home');
}
}
}
|
const THREE = require('three');
const fs = require('fs');
const util = require('./util.js');
let camera, renderer, scene, car;
const initialCameraPosition = new THREE.Vector3(-100, 100, -100);
function initAnimation() {
renderer = new THREE.WebGLRenderer({antialias: true});
renderer.setClearColor(0xA0D9FE);
renderer.setSize(window.innerWidth, window.innerHeight, true);
renderer.setPixelRatio(window.devicePixelRatio || 1);
const ratio = renderer.getContext().drawingBufferWidth / renderer.getContext().drawingBufferHeight;
scene = new THREE.Scene();
const height = 50;
const width = ratio*height;
camera = new THREE.OrthographicCamera(width/-2, width/2, height/2, height/-2, 0.1, 1000);
camera.position.copy(initialCameraPosition);
camera.lookAt(new THREE.Vector3(0, 0, 0))
document.body.appendChild(renderer.domElement);
car = makeCar();
scene.add(car);
const light = new THREE.DirectionalLight(0xffffff, 1.0);
light.position.set(-1, 2.5, -2);
scene.add(light);
}
function makeCar() {
const car = new THREE.Mesh(
new THREE.BoxGeometry(2, 2, 4),
new THREE.MeshLambertMaterial({color: 0xd1d1d1})
)
return car;
}
function moveCar() {
}
function moveCamera() {
}
function checkIntersections() {
}
function animate() {
requestAnimationFrame(animate);
moveCar();
moveCamera();
checkIntersections();
renderer.render(scene, camera);
}
initAnimation();
animate();
|
var express = require('express');
const bodyParser = require('body-parser');
var User = require('../models/user');
var passport = require('passport');
var send_mail = require('./mail');
var authenticate = require('../authenticate');
const nodemailer = require("nodemailer");
var multer = require('multer');
var router = express.Router();
router.use(bodyParser.json());
var userPicStorage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'public/images/userpic')
},
filename: function (req, file, cb) {
cb(null, 'anything_for_now' )
}
});
var userPicUpload = multer({ storage: userPicStorage }).single('userPic');
/* GET users listing. */
router.post('/signup', (req, res, next) => {
User.register({
username: req.body.username,
name: req.body.name,
companyname: req.body.companyname,
usertype: req.body.usertype,
typeofdatabase: req.body.typeofdatabase,
userpic: req.body.userpic,
parentid: req.body.parentid
},
req.body.password, (err,user) => {
console.log('ran');
if(err){
console.log("I say : " + err.message);
res.status(401).send(err);
}
else{
passport.authenticate('local')(req, res, () => {
send_mail.send_mail(req.user.username,"Signed Up!","You have been succesfully signed up");
res.statusCode = 200;
console.log("req.user.userpic");
console.log(req.user.userpic);
res.setHeader('Content-Type','application/json');
res.json({message : 'signup succesful', userpic:"req.user.userpic"});
});
}
});
});
router.post('/login',(req, res, next) => {
passport.authenticate('local', function(err, user, info) {
res.setHeader('Content-Type','application/json');
if (err) {
res.status(401).send(err);
return;
}
if (!user) {
error = {message: 'invalid user'};
res.status(401).send(error);
return;
}
req.logIn(user, function(err) {
if (err) {
res.status(401).send(err);
return;
}
var token = authenticate.getToken({_id: req.user._id});
console.log("logged in with token : " + token);
res.statusCode = 200;
res.json({
token : token,
message: "logged in succesfully!"
});
});
})(req, res, next);
});
router.post('/upload_report',authenticate.verifyUser,(req,res)=>{
User.upload(req,res,async (err)=>{
if(err)
{
console.log('multer error');
return res.json({error:`an error occured ${err}`});
}
let userid=req.user._id;
let path=User.Path+req.file.filename;
let user=await User.findById(userid);
await user.reports.push({name:req.body.name,path});
await user.save();
return res.status(200).json({"message":"Report Uploaded succesfully"});
})
})
router.get('/get_patients',authenticate.verifyUser,async (req,res)=>{
const Patients=await User.find({parentid:req.user._id});
return res.status(200).json({Patients});
})
router.get('/detail',authenticate.verifyUser, (req,res,next) => {
res.setHeader('Content-Type','application/json');
res.statusCode = 200;
res.json({
name: req.user.name,
companyname: req.user.companyname,
usertype: req.user.usertype,
typeofdatabase: req.user.typeofdatabase,
userpic: req.user.userpic,
companylogo: req.user.companylogo,
parentid: req.user.parentid,
reports:req.user.reports
});
});
router.get('/user_info/:id',authenticate.verifyUser,async (req,res)=>{
console.log("here-------"+req.params.id);
let user=await User.findById(req.params.id);
return res.status(200).json(user);
})
router.post('/localuser/signup',authenticate.verifyUser, (req,res,next) => {
User.register({
username: req.body.username,
name: req.body.name,
companyname: req.user.companyname,
usertype: req.body.usertype,
typeofdatabase: req.user.typeofdatabase,
userpic: req.body.userpic,
companylogo: req.user.companylogo,
parentid: req.user._id
},
req.body.password, (err,user) => {
console.log('ran');
if(err){
res.status(401).send(err);
}
else{
passport.authenticate('local')(req, res, () => {
send_mail.send_mail(req.user.username,"Signed Up!","You have been succesfully signed up");
res.statusCode = 200;
res.setHeader('Content-Type','application/json');
res.json({message : 'Signup Succesful'});
});
}
});
});
module.exports = router;
// var express = require('express');
// const bodyParser = require('body-parser');
// var User = require('../models/user');
// var passport = require('passport');
// var send_mail = require('./mail');
// var authenticate = require('../authenticate');
// const nodemailer = require("nodemailer");
// var multer = require('multer');
// var router = express.Router();
// router.use(bodyParser.json());
// var companylogoStorage = multer.diskStorage({
// destination: function (req, file, cb) {
// cb(null, 'public/images/companylogo')
// },
// filename: function (req, file, cb) {
// cb(null, 'anything_for_now' )
// }
// });
// var companylogoUpload = multer({ storage: companylogoStorage }).single('companylogo');
// /* GET users listing. */
// router.post('/signup', (req, res, next) => {
// companylogoUpload(req, res, function (err) {
// if (err instanceof multer.MulterError) {
// return res.status(500).json(err)
// } else if (err) {
// return res.status(500).json(err)
// }
// console.log("3 : reached");
// return res.status(200).send(req.companylogo)
// })
// console.log("req.body");
// console.log(req.body.data);
// User.register({
// username: req.body.username,
// name: req.body.name,
// companyname: req.body.companyname,
// usertype: req.body.usertype,
// typeofdatabase: req.body.typeofdatabase,
// userpic: req.body.userpic,
// parentid: req.body.parentid
// },
// req.body.password, (err,user) => {
// console.log('ran');
// if(err){
// console.log("I say : " + err.message);
// res.status(401).send(err);
// }
// else{
// passport.authenticate('local')(req, res, () => {
// send_mail.send_mail(req.user.username,"Signed Up!","You have been succesfully signed up");
// //shit starts here :
// // console.log("1 : id=> ");
// // console.log(req.user._id);
// // console.log("2 : companylogo=> ");
// // console.log(req.body.companylogo);
// // req.companylogo = req.body.companylogo;
// // companylogoUpload(req, res, function (err) {
// // if (err instanceof multer.MulterError) {
// // return res.status(500).json(err)
// // } else if (err) {
// // return res.status(500).json(err)
// // }
// // console.log("3 : reached");
// // return res.status(200).send(req.companylogo)
// // })
// // shit ends here
// res.statusCode = 200;
// res.setHeader('Content-Type','application/json');
// res.json({message : 'signup succesful'});
// });
// }
// });
// });
// router.post('/login',(req, res, next) => {
// passport.authenticate('local', function(err, user, info) {
// res.setHeader('Content-Type','application/json');
// if (err) {
// res.status(401).send(err);
// return;
// }
// if (!user) {
// error = {message: 'invalid user'};
// res.status(401).send(error);
// return;
// }
// req.logIn(user, function(err) {
// if (err) {
// res.status(401).send(err);
// return;
// }
// var token = authenticate.getToken({_id: req.user._id});
// console.log("logged in with token : " + token);
// res.statusCode = 200;
// res.json({
// token : token,
// message: "logged in succesfully!"
// });
// });
// })(req, res, next);
// });
// router.get('/detail',authenticate.verifyUser, (req,res,next) => {
// res.setHeader('Content-Type','application/json');
// res.statusCode = 200;
// res.json({
// name: req.user.name,
// companyname: req.user.companyname,
// usertype: req.user.usertype,
// typeofdatabase: req.user.typeofdatabase,
// userpic: req.user.userpic,
// companylogo: req.user.companylogo,
// parentid: req.user.parentid
// });
// });
// router.post('/localuser/signup',authenticate.verifyUser, (req,res,next) => {
// User.register({
// username: req.body.username,
// name: req.body.name,
// companyname: req.user.companyname,
// usertype: req.body.usertype,
// typeofdatabase: req.user.typeofdatabase,
// userpic: req.body.userpic,
// companylogo: req.user.companylogo,
// parentid: req.user._id
// },
// req.body.password, (err,user) => {
// console.log('ran');
// if(err){
// res.status(401).send(err);
// }
// else{
// passport.authenticate('local')(req, res, () => {
// send_mail.send_mail(req.user.username,"Signed Up!","You have been succesfully signed up");
// res.statusCode = 200;
// res.setHeader('Content-Type','application/json');
// res.json({message : 'Signup Succesful'});
// });
// }
// });
// });
// module.exports = router;
|
/* String Declaration */
// Single Quote
var a = 'Hunny Coders'
console.log(a)
// Double Quote
var b = "Learn Something new course"
console.log(b)
// new String
var c = new String('New String')
console.log(c)
// Template Literal
var line = `Bangladesh is our homeland and
It is wonderful country`
console.log(line)
// Escape notation
// console.log('We are "Hunny Coders" Group')
// console.log("We are 'Hunny Coders' Group")
// console.log("We are \"Hunny Coders\" Group")
console.log('We are \nHunny Coders\tGroup')
// String Concatanation
console.log('Hunny' + ' Best ' + 'Codders')
// String Variable Embadding
var name = "Abdur Rahman"
var title = 'content creator'
console.log('Hello ' + '\'' + name + '\'')
var newLine = `Hello ${name} - who is a ${title}`
console.log(newLine)
console.log(data.name);
|
print = (something) => {
console.log(something);
}
class Perceptron {
constructor(){
this.weigths = [1,0,0];
this.inputs = [
[1,0,0],
[1,1,0],
[1,0,1],
[1,1,1]
];
this.desired = [0,0,0,1];
this.learningRate = 1;
this.epochs = 100;
}
weightSum(input){
let sum = 0;
for(let j = 0; j < this.weigths.length; j++){
sum+= input[j] * this.weigths[j];
}
return sum;
}
doActivation(z){
return z >= 0 ? 1 : 0;
}
calculateError(currentResult, desiredResult){
return desiredResult - currentResult;
}
tweakWeights(inputIndex, error){
let currentInput = this.inputs[inputIndex];
for(let k = 0; k < this.weigths.length; k++){
this.weigths[k] += this.learningRate * error * currentInput[k];
}
}
train(){
for(let i = 0; i < this.epochs; i++){
for(let j = 0; j < this.inputs.length; j++){
let z = this.weightSum(this.inputs[j]);
let y = this.doActivation(z);
let error = this.calculateError(y, this.desired[j]);
console.log("Input index: " + j);
console.log("Error: " + error);
console.log("Weights before: " + this.weigths);
this.tweakWeights(j, error);
console.log("Weights after: " + this.weigths + "\n" + "------------------------------------");
}
}
}
insertBiasX(input){
let vector = [];
vector.push(1);
for(let i = 0; i < input.length; i++){
vector.push(input[i]);
}
return vector;
}
predict(input){
let vec = this.insertBiasX(input);
let z = this.weightSum(vec);
let y = this.doActivation(z);
console.log("Input: [ " + input + " ] Result: " + y);
}
}
var perceptron = new Perceptron();
perceptron.train();
perceptron.predict([0,0])
|
/**
* Created by Terris
* https://github.com/qinglingzhiyu
*
* @date: 2019-01-09
* @flow
*
* description: circle-introduce 逻辑
*
*/
import {
circleDetailWithToken,
getCircleInfoWithoutToken,
isJoinCircle
} from '../../api/request.js'
import regeneratorRuntime, {
async
} from '../../api/regeneratorRuntime.js'
import {
jumpToPromisify,
showModalPromisify,
showToastPromisify,
setStoragePromisify,
getStorageInfoPromisify,
} from '../../api/promisify.js'
import {
isAuthor,
QiniuToken,
} from '../../common/common.js'
import {
isTestEnvironment
} from '../../api/config';
const app = getApp()
Page({
/**
* 页面的初始数据
*/
data: {},
/**
* 生命周期函数--监听页面加载
*/
onLoad: async function (options) {
let {
circleId,
comeFrom
} = options;
try {
if (circleId) this.setData({
circleId: circleId
})
else throw new Error(`circleId:${circleId}`)
} catch (error) {
isTestEnvironment && await showModalPromisify({
title: '错误提示',
content: String(error)
})
}
comeFrom && this.setData({
comeFrom
})
wx.hideShareMenu(); //取消顶部分享
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: async function () {
let {
circleId
} = this.data;
let storageInfo = await getStorageInfoPromisify();
if (storageInfo.keys.includes('Token')) {
try {
let circleDetailData = await circleDetailWithToken(circleId);
if (typeof circleDetailData === 'undefined' || !circleDetailData) throw new Error(`circleDetailWithToken api is ${circleDetailWithToken}`)
if (circleDetailData.statusCode === 200) {
circleDetailData.data['brief'] = circleDetailData.data.brief.split(',')
circleDetailData.data['descr'] = circleDetailData.data.descr.split('\r\n')
circleDetailData.data['welfare'] = circleDetailData.data.welfare.split('\r\n')
this.setData({
circleIntroduceData: circleDetailData.data
}) //获取页面数据
} else throw new Error(`statusCode of circleDetailWithToken is ${circleDetailData.statusCode}`)
} catch (error) {
isTestEnvironment && await showModalPromisify({
title: '错误提示',
content: String(error)
})
}
} else {
try {
let circle = circleId && await getCircleInfoWithoutToken({
circle_id: circleId
});
if (typeof circle === 'undefined') throw new Error(`getCircleInfoWithoutToken api is ${circle}`)
if (circle.statusCode === 200) {
circle.data['brief'] = circle.data.brief.split(',')
circle.data['descr'] = circle.data.descr.split('\r\n')
circle.data['welfare'] = circle.data.welfare.split('\r\n')
this.setData({
circleIntroduceData: circle.data
})
} else throw new Error(`statusCode of getCircleInfoWithoutToken is ${circle.statusCode}`)
} catch (error) {
isTestEnvironment && await showModalPromisify({
title: '错误提示',
content: String(error)
})
}
}
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function (e) {
let circleName = e.target.dataset.circlename; //当前圈子名称
let circleId = this.data.circleId; //当前圈子id
return {
title: `请符合条件的您,加入${circleName},找到结婚对象!`,
path: '/pages/circle-introduce/circle-introduce?circleId=' + circleId,
imageUrl: '/images/share-bg.png'
}
},
/**
* 跳转越早越优惠页面
*/
userInfo: async function (info) {
if (info.detail.errMsg === 'getUserInfo:fail auth deny') return
let {
nickName
} = info.detail.userInfo;
setStoragePromisify({
'NICKNAME': nickName
})
let {
circleid,
name
} = info.currentTarget.dataset;
if (typeof circleid === 'undefined' || !circleid) throw new Error(`circleid is ${circleid}`);
if (typeof name === 'undefined' || !name) throw new Error(`circleName is ${name}`);
let authorStatus = await isAuthor({
encryptedData: info.detail.encryptedData,
iv: info.detail.iv
})
if (authorStatus.statusCode === 'isOk' || authorStatus.statusCode === 200) {
let result = await isJoinCircle({
circle_id: circleid
});
if (!result) throw new Error('isJoinCircle api is undefined')
if (result.statusCode === 200) {
if (result.data.joined) jumpToPromisify('circle-dynamic', 'redirect', {
circleId: circleid,
navTitle: name
});
else jumpToPromisify('sale', 'redirect', {
circleId: circleid
})
} else throw new Error(`isJoinCircle api is statusCode: ${result.statusCode}`), showToastPromisify({
title: '网络错误'
})
} else throw new Error(`isAuthor api statusCode: ${authorStatus.statusCode}`), showToastPromisify({
title: '网络错误'
})
if (authorStatus.statusCode === 200) QiniuToken();
},
/**
* 保存formid
*/
bindSubmit: async function (e) {
let {
formId
} = e.detail;
formId && app.data.formID.push(formId);
},
/**
* 跳转圈子首页
*/
goPageWithCircle: function () {
jumpToPromisify('circle', 'reLaunch');
}
})
|
//轮播图片
var arr=Array();
arr[0]="images/bg1.jpg";
arr[1]="images/bg2.jpg";
arr[2]="images/bg3.jpg";
arr[3]="images/bg4.jpg";
arr[4]="images/bg5.jpg";
var n=0;
var a=setInterval(lunbo1,2000);
function lunbo1(){
if (n==arr.length-1) {
n=0;
}
else{
n++;
}
document.getElementById("bg").src=arr[n];
document.getElementById("lunbo").src=arr[n];
}
function stop1(){
clearInterval(a);
}
function start1(){
a=setInterval(lunbo1,2000);
}
function lunbo2(id){
clearInterval(a);
n=document.getElementById(id).value;
document.getElementById("bg").src=arr[n];
document.getElementById("lunbo").src=arr[n];
}
//导航栏和具体分类 二级菜单
function show(id1,id2) {
document.getElementById(id2).style.display = "block";
old=document.getElementById(id1).style.backgroundColor;
document.getElementById(id1).style.backgroundColor = "white";
}
function hide(id1,id2) {
document.getElementById(id2).style.display = "none";
document.getElementById(id1).style.backgroundColor = old;
}
//顶部搜索栏随滚动条出现/消失
onscroll= function(){
if (document.getElementById("showSearch").getBoundingClientRect().top<=0) {
document.getElementById("search-fixed").style.display="block";
}
if (document.getElementById("showSearch").getBoundingClientRect().top>0) {
document.getElementById("search-fixed").style.display="none";
}
}
//品牌上关注的显示和隐藏
function showguanzhu(id0){
document.getElementById(id0).style.display="block";
}
function hideguanzhu(id0){
document.getElementById(id0).style.display="none";
}
//左侧图片切换
function change(id1,id2){
document.getElementById(id1).src=document.getElementById(id2).src;
}
//点击登录(注册)
function login(){
document.getElementById("z-top").style.display="block";
document.getElementById("login1").style.display="block";
}
function hidelogin(){
document.getElementById("z-top").style.display="none";
document.getElementById("login1").style.display="none";
}
function denglu1(id1,id2,id3){
if (document.getElementById(id1).value=="") {
alert("请输入用户名");
document.getElementById(id1).focus();
return;
}
if (document.getElementById(id2).value=="") {
alert("请输入密码");
document.getElementById(id2).focus();
return;
}
document.getElementById(id3).submit();
}
function long(){
if (document.getElementById("username2").value.length>10) {
alert("用户名不能超过10个字符");
setTimeout(function(){document.getElementById("username2").focus();},100);
}
}
//图片改变大小
function imgBig(id){
document.getElementById(id).style.width="140px";
document.getElementById(id).style.height="140px";
}
function imgSmall(id){
document.getElementById(id).style.width="133px";
document.getElementById(id).style.height="133px";
}
|
atom.declare("Game.PlayerController",
{
initialize: function()
{
this.isPlayer = true;
this.ghostSpeed = 0.3;
this.position = new Point(0, 0);
this.thrustOn = false;
var keyboard = Controller.keyboard;
keyboard.events.add( 'aup', function ()
{
if (Controller.PlayerController.ship == null)
return;
Controller.PlayerController.thrustOn = !Controller.PlayerController.thrustOn;
if (Controller.PlayerController.thrustOn) Controller.updateEngineOnStatus("on");
else Controller.updateEngineOnStatus("off");
});
},
controllShip: function(time)
{
this.position = this.ship.shape.center;
if (Controller.cruiseControll_left && Controller.cruiseControll_right)
{
this.ship.thrust(time);
return;
}
if (Controller.cruiseControll_left)
{
this.ship.thrust(time);
this.ship.rotate(time, false);
return;
}
if (Controller.cruiseControll_right)
{
this.ship.thrust(time);
this.ship.rotate(time, true);
return;
}
var keyboard = Controller.keyboard;
if (keyboard.key("aleft")) this.ship.rotate(time, true);
if (keyboard.key("aright")) this.ship.rotate(time, false);
if (this.thrustOn)
this.ship.thrust(time);
},
controllGhost: function(time)
{
var keyboard = Controller.keyboard;
var dx = 0;
var dy = 0;
var speed = this.ghostSpeed * time;
if (keyboard.key("aup")) dy -= speed;
if (keyboard.key("adown")) dy += speed;
if (keyboard.key("aleft")) dx -= speed;
if (keyboard.key("aright")) dx += speed;
var movePoint = new Point(dx, dy);
Controller.addLayersTranslate(movePoint);
this.position = new Point(this.position.x + dx, this.position.y + dy);
},
onUpdate: function(time)
{
if (this.ship != null)
this.controllShip(time);
else
this.controllGhost(time);
}
});
|
import React from 'react';
import PropTypes from 'prop-types';
import { Panel } from '../Panel';
import { Box } from '../Box';
import { Inline } from '../Inline';
const buttonProps = {
0: {
color: 'blue',
key: 'modal-primary',
},
1: {
color: 'blue',
variant: 'outline',
key: 'modal-secondary',
},
2: {
color: 'blue',
variant: 'text',
key: 'modal-tertiary',
},
};
function getButtonProps(index, element) {
return {
...buttonProps[index],
...element.props,
};
}
const Footer = React.forwardRef(function Footer({ children }, ref) {
const buttons = React.Children.toArray(children);
return (
<Panel borderLeft="none" borderRight="none" borderBottom="none" ref={ref}>
<Panel.Section>
{buttons && (
<Box display="flex" justifyContent="space-between">
<Inline space="300">
{buttons[0] && React.cloneElement(buttons[0], getButtonProps(0, buttons[0]))}
{buttons[1] && React.cloneElement(buttons[1], getButtonProps(1, buttons[1]))}
</Inline>
{buttons[2] && (
<Box>
{buttons[2] && React.cloneElement(buttons[2], getButtonProps(2, buttons[2]))}
</Box>
)}
</Box>
)}
</Panel.Section>
</Panel>
);
});
Footer.displayName = 'Modal.Footer';
Footer.propTypes = {
children: PropTypes.node,
};
export default Footer;
|
/*!
betajs-media-components - v0.0.40 - 2016-11-21
Copyright (c) Ziggeo,Oliver Friedmann
Apache-2.0 Software License.
*/
(function () {
var Scoped = this.subScope();
Scoped.binding("browser", "global:BetaJS.Browser");
Scoped.binding("module", "global:BetaJS.MediaComponents");
Scoped.extend("module:Assets.playerthemes", [
"module:Templates",
"browser:Info"
], function (Templates, Info) {
var ie8 = Info.isInternetExplorer() && Info.internetExplorerVersion() <= 8;
return {
"theatre": {
css: "ba-videoplayer-theatre-theme",
csstheme: "ba-videoplayer-theatre-theme",
tmplcontrolbar: Templates["theatre-video_player_controlbar"],
cssloader: ie8 ? "ba-videoplayer" : "",
cssmessage: "ba-videoplayer",
cssplaybutton: ie8 ? "ba-videoplayer" : ""
}
};
});
Scoped.extend("module:Assets.recorderthemes", [
"module:Templates",
"browser:Info"
], function (Templates, Info) {
var ie8 = Info.isInternetExplorer() && Info.internetExplorerVersion() <= 8;
return {
"space": {
css: "ba-videorecorder-space-theme",
cssmessage: "ba-videorecorder",
cssloader: "ba-videorecorder",
tmplchooser: Templates["space-video_recorder_chooser"]
}
};
});
}).call(Scoped);
|
import React from 'react';
import styles from './LoadElement.module.css';
const LoadElement = () => (
<div className={styles.imageLoadingBackground}>
<h1 className={styles.text}>Image Loading ...</h1>
</div>
);
export default LoadElement;
|
var currentPage = 1;
var pathname = window.location.pathname;
function checkScroll(pathname) {
currentPage++;
$.ajax({
type : "GET",
url : pathname + '?page=' + currentPage,
dataType: "jsonp"
});
}
$(window).scroll(function(){
if ($(window).scrollTop() == $(document).height() - $(window).height()){
if ( currentPage < $('.pagination .page').length ) { $("#loading").show(); checkScroll(pathname); }
}
});
$(document).ready( function () {
$("#loading").hide();
$(".pagination").hide();
});
|
import { Router } from "express";
import {Vote, Candidate, Election} from "../models/Vote"
import { auth } from "../utils/auth";
const router = Router();
// Create Candidate
router.post("/candidate/create", auth, async (req, res) => {
const { election } = req.body;
try {
const candidate = await Candidate.create(req.body);
await Election.findByIdAndUpdate(
election,
{ $addToSet: { candidates: candidate.id } },
{new:true}
)
return res.send(candidate);
} catch (error) {
res.send(error);
}
})
// Get Candidates
router.get("/candidate", async (req, res) => {
try {
const candidates = await Candidate.find();
res.send(candidates);
} catch (error) {
res.send(error);
}
})
router.delete("/candidate/:id", auth, async (req, res) => {
try {
const candidate = await Candidate.findByIdAndDelete(req.params.id);
return res.send(candidate);
} catch (error) {
res.send(error);
}
})
//election
router.post("/election/create", auth, async (req, res) => {
try {
const election = await Election.create(req.body);
res.send(election);
} catch (error) {
res.send(error)
}
})
router.get("/election", async (req, res) => {
try {
const elections = await Election.find();
res.send(elections)
} catch (error) {
res.send(error);
}
})
router.get("/election/:id", async (req, res) => {
try {
const election = await Election.findById(req.params.id);
res.send(election)
} catch (error) {
res.send(error);
}
})
router.post("/create", auth, async (req, res) => {
const { election, voter, candidate } = req.body;
if (!election || !voter || !candidate) return res.status(500).send("Include an election, voter or candidate");
try {
// create vote
const vote = await Vote.create(req.body);
// add the vote to a candidate
await Candidate.findByIdAndUpdate(
candidate,
{$addToSet:{votes:vote.id}}
).catch((err) => {
return res.status(500).send(err);
})
// add the voter to Election;
await Election.findByIdAndUpdate(election, { $addToSet: { voters: voter } });
res.send(vote);
} catch (error) {
res.send(error);
}
})
// Get votes
// Get vote
// Update vote
// Delete vote
export {router as voteRoutes}
|
var express = require( "express" )
var bodyParser = require( "body-parser" )
var app = express()
app.use( bodyParser.json() )
// Including js files.
var ut = require( './UtilityFunctions.js')
var db = require( './DatabaseActions.js' )
var ev = require( './Evaluations.js' )
var validate = require( './Validation.js' )
var HTTP = ut.http_codes()
/**
* Handles get requests, takes key and attempts to read it from database.
* @params { STRING } pathname - forms the url address
* @params { FUNCTION } takes incoming request object and returning response object.
*/
app.get( "/websheet/:key/:type", function (reqt, resp) {
// Construct a valid key with key and type.
var keyValue = reqt.params.key + "_" + reqt.params.type
if ( validate.Key( keyValue ) ) {
if( reqt.params.type == 'value' ){
ut.logger( "Recieved Request: READ VALUE OF - " + reqt.params.key )
alternativeKey = reqt.params.key + "_formula"
db.read( alternativeKey, function ( read_code, read_response ) {
if ( read_code == HTTP.OK ){
// Formula exists therefore evaluate and return
ev.evaluateExpression( alternativeKey, function ( resolve_Code, resolve_value ) {
resp.status( resolve_Code )
resp.json( { key: reqt.params.key, value: resolve_value } )
// After update we will ensure value is correct by storing the evaluated code.
// if the resolve Expression returned successfully.
if( resolve_Code == HTTP.OK ){
// We don't want to do anything with response, and failure to insert wouldn't be an issue.
db.insert( {key: keyValue, value: resolve_value }, function ( c, o) {})
}
})
} else {
// Error on read or there is no value for Formula, either way we want to be helpful
// and return something of use
db.read( keyValue, function ( value_code, value_output ) {
resp.status( value_code )
if ( value_code == HTTP.OK ){
// eval response to ensure floating point number.
value_output = { key: reqt.params.key, value: eval(value_output.value) }
}
resp.json( value_output )
})
}
})
} else if ( reqt.params.type == 'formula' ) {
ut.logger( "Recieved Request: READ FORMULA OF - " + reqt.params.key )
db.read( keyValue, function ( http_status, output) {
resp.status( http_status )
if( http_status == HTTP.OK ){
resp.json( { key: reqt.params.key, value: output.value } )
} else {
resp.json( output )
}
})
} else {
// Address incorrect
resp.status( HTTP.NOT_FOUND )
resp.json( "ERROR: Not serving at the address." )
}
} else {
// Key is invalid
resp.status( HTTP.BAD_REQUEST )
resp.json( "ERROR: Malformed Request." )
}
})
/**
* Handles post requests, extracts key and value and attempts to create it in the database.
* @params { STRING } pathname - forms the url address
* @params { FUNCTION } takes incoming request object and returning response object.
*/
app.post( "/websheet/:type/", function (reqt, resp) {
if( reqt.params.type == 'formula' || reqt.params.type == 'value' ){
ut.logger( "Recieved Request: CREATE " + reqt.params.type.toUpperCase() + " FOR - " + reqt.body.key )
//Extract data
var keyValue = reqt.body.key + "_" + reqt.params.type
var datapoint = { key: keyValue, value: reqt.body.value }
if ( validate.Datapoint( reqt.params.type, datapoint ) ){
//For value ensure number.
if ( reqt.params.type == 'value' ) datapoint.value = eval( reqt.body.value )
db.insert( datapoint, function ( http_status, output ) {
resp.status( http_status )
resp.json( {key: reqt.body.key, value: output.value} )
})
} else {
resp.status( HTTP.BAD_REQUEST )
resp.json( "ERROR: Malformed Request data.")
}
} else {
resp.status( HTTP.NOT_FOUND )
resp.json( "ERROR: Not serving at the address.")
}
})
/**
* Handles put requests, extracts key and value and attempts to update entry in the database.
* @params { STRING } pathname - forms the url address
* @params { FUNCTION } takes incoming request object and returning response object.
*/
app.put( "/websheet/:key/:type", function ( reqt, resp ){
if( reqt.params.type == 'formula' || reqt.params.type == 'value' ){
ut.logger( "Recieved Request: UPDATE - " + reqt.params.type.toUpperCase() + " FOR - " + reqt.params.key )
//Extract data
var keyValue = reqt.params.key + "_" + reqt.params.type
var datapoint = { key: keyValue, value: reqt.body.value }
if ( validate.Datapoint( reqt.params.type, datapoint ) ){
//For value ensure number.
if ( reqt.params.type == 'value' ) datapoint.value = eval( reqt.body.value )
db.insert( datapoint, function ( http_status, output ) {
resp.status( http_status )
resp.json( {key: reqt.body.key, value: output.value} )
})
} else {
resp.status( HTTP.BAD_REQUEST )
resp.json( "ERROR: Malformed Request data.")
}
} else {
resp.status( HTTP.NOT_FOUND )
resp.json( "ERROR: Not serving at the address.")
}
})
/**
* Handles delete requests, extracts key and attempts to deletes entry in the database.
* @params { STRING } pathname - forms the url address
* @params { FUNCTION } takes incoming request object and returning response object.
*/
app.delete( "/websheet/:key/:type", function ( reqt, resp ) {
ut.logger( "Recieved Request: DELETE " + reqt.params.type.toUpperCase() + " FOR - " + reqt.params.key )
if( reqt.params.type == 'formula' || reqt.params.type == 'value' ){
var keyValue = reqt.params.key + "_" + reqt.params.type
if ( validate.Key( keyValue ) ){
db.delete( keyValue, function ( http_status, output){
resp.status( http_status )
resp.json( output )
})
} else {
resp.status( HTTP.BAD_REQUEST )
resp.json( "ERROR: Malformed Request data.")
}
} else {
resp.status( HTTP.NOT_FOUND )
resp.json( "ERROR: Not serving at the address.")
}
})
/**
* Starts node server listening on port
* @params { NUMBER } port number
* @params { FUNCTION } defines parts 1 depandancies
*/
app.listen( 3000, function () {
ut.logger( "Starting..." )
var loc = "mongodb://localhost/Websheet"
var coll = "kfv"
var dbSelect = "./DatabaseActions.js"
ut.logger( "Setting local database..." )
ev.toggleDBActions( dbSelect )
ut.logger( "Setting Database location as: " + loc )
db.SetLocation( loc )
ut.logger( "Setting collection name as: " + coll )
db.SetCollection( coll )
ut.logger( "Server Started on port 3000." )
console.log("-------------------------------------------------")
})
|
$(document).ready(function(){
var password = localStorage.getItem('TempPasswordIT');
if( password === "IRISTECH"){
$('.BtnDonePage').show();
//$('.BtnEditPage').hide();
$('.ChangeContent').on('click');
$('.ChangeContent').on('click');
$('.IndexServiceImg').on('click');
$('.IndexSliderItemFile').on('click');
$('.ChangeContentURL').on('click');
$('.ChangeContentAndURL').on('click');
$('#map').on('click');
$('.IndexFunFactImg').on('click');
}else{
$('.BtnDonePage').hide();
//$('.BtnEditPage').show();
$('.IndexSliderItemFile').hide();
$('.IframeMapChange').hide();
$('.IndexServiceImg').hide();
$('.IndexFunFactImg').hide();
$('.ChangeContent').off('click');
$('.IndexServiceImg').off('click');
$('.IndexSliderItemFile').off('click');
$('.ChangeContentURL').off('click');
$('.ChangeContentAndURL').off('click');
$('#map').off('click');
$('.IndexFunFactImg').off('click');
}
$(".BtnDonePage").click(function(){
Swal.fire({
title: 'Are you sure?',
text: "Your DONE editing!",
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, DONE!'
}).then((result) => {
if (result.isConfirmed) {
localStorage.removeItem('TempPasswordIT');
location.reload();
}
})
});///clsoe for BtnEditPage
$(".BtnEditPage").dblclick(function(){
const { value: text } = Swal.fire({
title: 'CONFIRMED ?',
text: "Pls. Input Assigned Password",
icon: 'info',
input: 'password',
inputPlaceholder: 'Enter Password ...',
inputAttributes: {
'aria-label': 'Password Code'
},
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes!',
}).then(result => {
if (result.value) {
if( result.value === "IRISTECH"){
localStorage.setItem('TempPasswordIT', 'IRISTECH');
$('.ChangeContent').on('click');
$('.BtnDonePage').show();
$('.BtnEditPage').hide();
}else{
Swal.fire({
icon: 'error',
title: 'Oops...',
text: 'PASSWORD invalid, Pls. Check the Docs.',
})
// $('.ChangeContent').off('click');
}
}
});
});///clsoe for BtnEditPage
$(".ChangeContent").click(function(){
var password = localStorage.getItem('TempPasswordIT');
if( password === "IRISTECH"){
const { value: text } = Swal.fire({
title: 'CONFIRMED ?',
text: "Pls. New WORDS to DISPLAY",
icon: 'info',
input: 'textarea',
inputPlaceholder: 'Enter New WORDS ...',
inputAttributes: {
'aria-label': 'Password Code'
},
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes!',
}).then(result => {
if (result.value) {
$("#" + this.id ).html(result.value);
}
});
}
// else{
// Swal.fire({
// icon: 'error',
// title: 'Oops...',
// text: 'EDITING not ALLOWED',
// })
// }
});///clsoe for FooterMenu
$(".IndexServiceImg").on('change', function () {
if (typeof (FileReader) != "undefined") {
// var image_holder = $("#"+this.id );
var GetIDsData = $(this).attr('data-id');
var image_holder = $("#"+GetIDsData);
//alert(image_holder);
image_holder.empty();
var reader = new FileReader();
reader.onload = function (e) {
$("<img />", {
"src": e.target.result,
"class": "thumb-image"
}).appendTo(image_holder);
}
image_holder.show();
reader.readAsDataURL($(this)[0].files[0]);
} else {
alert("This browser does not support FileReader.");
}
});
$(".IndexFunFactImg").on('change', function (event) {
var GetIDsData = $(this).attr('data-id');
var file = document.getElementById('IndexFunFactImg').files[0];
var reader = new FileReader();
reader.onloadend = function(){
document.getElementById(GetIDsData).style.backgroundImage = "url(" + reader.result + ")";
}
if(file){
reader.readAsDataURL(file);
}else{
}
});
$(".IndexSliderItemFile").on('change', function (event) {
var GetIDsData = $(this).attr('data-id'); //for img
var GetIDsURL = $(this).attr('data-value'); //for img url
var file = document.getElementById(GetIDsURL).files[0];
var reader = new FileReader();
reader.onloadend = function(){
document.getElementById(GetIDsData).style.backgroundImage = "url(" + reader.result + ")";
}
if(file){
reader.readAsDataURL(file);
}else{
}
});
$(".ChangeContentURL").click(function(){
var password = localStorage.getItem('TempPasswordIT');
if( password === "IRISTECH"){
const { value: text } = Swal.fire({
title: 'CONFIRMED ?',
text: "Pls. New URL to DISPLAY",
icon: 'info',
input: 'textarea',
inputPlaceholder: 'Enter New WHOLE URL ...',
inputAttributes: {
'aria-label': 'Password Code'
},
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes!',
}).then(result => {
if (result.value) {
$("a#"+ this.id).prop("href", result.value)
}
});
}
// else{
// Swal.fire({
// icon: 'error',
// title: 'Oops...',
// text: 'EDITING not ALLOWED',
// })
// }
});///clsoe for FooterMenu
$(".ChangeContentAndURL").click(function(){
var password = localStorage.getItem('TempPasswordIT');
if( password === "IRISTECH"){
const { value: text } = Swal.fire({
title: 'CONFIRMED ?',
text: "Pls. New WORDS to DISPLAY",
icon: 'info',
input: 'textarea',
inputPlaceholder: 'Enter New WORDS ...',
inputAttributes: {
'aria-label': 'Password Code'
},
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes!',
}).then(result => {
if (result.value) {
$("#" + this.id ).html(result.value); //content
//
const { value: text } = Swal.fire({ //url
title: 'CONFIRMED ?',
text: "Pls. New URL to DISPLAY",
icon: 'info',
input: 'textarea',
inputPlaceholder: 'Enter New WHOLE URL ...',
inputAttributes: {
'aria-label': 'Password Code'
},
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes!',
}).then(result1 => {
if (result1.value) {
var GetIDsURL = $(this).attr('data-target');
$("a#"+ GetIDsURL).prop("href", result1.value)
}
});
}
});
}
// else{
// Swal.fire({
// icon: 'error',
// title: 'Oops...',
// text: 'EDITING not ALLOWED',
// })
// }
});///clsoe for FooterMenu
$("#map").click(function(){
var password = localStorage.getItem('TempPasswordIT');
if( password === "IRISTECH"){
const { value: text } = Swal.fire({
title: 'CONFIRMED ?',
text: "Pls. New URL to DISPLAY",
icon: 'info',
input: 'textarea',
inputPlaceholder: 'Enter New WHOLE URL ...',
inputAttributes: {
'aria-label': 'Password Code'
},
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes!',
}).then(result => {
if (result.value) {
var $iframe = $('#IframeMap');
if ($iframe.length) {
$iframe.attr('src',result.value);
return false;
}
return true;
}
});
}
// else{
// Swal.fire({
// icon: 'error',
// title: 'Oops...',
// text: 'EDITING not ALLOWED',
// })
// }
});///clsoe for fuction
}); //close Jquery
|
import User from "../entity/User";
class ParserJSONToUser {
parse(json) {
return new User(json.id, json.name, json.email, new Date(json.dateRegistration), new Date(json.dateLogin), json.userStatus);
}
}
export default new ParserJSONToUser();
|
/**
* @module config-controller
*/
const config = require( '../models/config-model' );
const express = require( 'express' );
const router = express.Router();
// var debug = require( 'debug' )( 'config-controller' );
module.exports = app => {
app.use( `${config.server[ 'base path' ]}/client-config.json`, router );
};
router
.get( '/', ( req, res ) => {
res.json( config.client );
} );
|
const form = document.getElementById('addNewBook');
console.log("start event")
if (form)
form.addEventListener("submit", async(e) => {
e.preventDefault();
console.log("event initialized")
let bookA = document.getElementById('ttl').value;
let bookP = document.getElementById('atr').value;
let bookR = document.getElementById('prc').value;
const book = {
title: bookA,
author: bookP,
cost: bookR,
}
console.log(book);
await fetch('http://localhost:3000/books', {
method: 'POST',
body: JSON.stringify(book),
headers: { 'Content-Type': 'application/json' }
});
// window.location.replace('/book=bookList.html');
})
|
const { AbstractIndexCreationTask } = require("ravendb");
class Game_ForSearch extends AbstractIndexCreationTask {
constructor() {
super();
this.map = "docs.Games.Select(Games => new {" +
" id = Games.id," +
" name = Games.name," +
" userId = Games.userId," +
" isPublic = Games.isPublic," +
"})";
}
}
module.exports = Game_ForSearch;
|
const expressErrorHandler = (err, req, res, next) => {
console.log('Response error handler:');
console.log(err);
const { msgFa = "خطایی رخ داده است!", msgEn = "Something went wrong!", status = 500, detail } = err
res.status(status).json({
success: false,
error: {
msgFa,
msgEn,
detail
},
});
};
module.exports = expressErrorHandler;
|
var _slice = Array.prototype.slice;
module.exports = function(args, start) {
return _slice.call(args, start || 0);
};
|
const homeArr = ["a mansion", "an apartment", "a castle", "a house", "a world far beyond our own", "a trash can", "the hood"];
const transportArr = ["a supercar", "a horse-drawn carriage", "a Honda Civic", "teleportation", "walking", "a wheelchair","a nintendo labo motorcycle","a Charizard","a sparrow"];
const powerArr = ["mindbending", "remote teleportation", "telekinesis", "telepathy", "being good at fortnite", "mindreading", "being an adept coder", "godhood", "invincibility",
];
if(process.argv[2] != undefined){
homeArr[homeArr.length] = process.argv[2];
}
if(process.argv[4] != undefined){
powerArr[powerArr.length] = process.argv[4];
}
function mach(){
return "You shall live in " + dwelling() + " with your " + offspring() + " offspring. Your transport will be " + transport() + " and you have been given the power of " + power() + ".";
}
function random (number){
return Math.floor(Math.random()*number);
}
function dwelling(){
return homeArr[random(homeArr.length)];
}
function fifty50(){
return random(51);
}
function offspring(){
if(fifty50() == 1){
return process.argv[3];
}
else{
if(process.argv[3] != undefined){
return random(50);
}
}
}
function power(){
return powerArr[random(powerArr.length)];
}
function transport(){
return transportArr[random(transportArr.length)];
}
console.log(mach());
|
// Copyright 2018 Google LLC
//
// 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.
/** @typedef {Omit<ClientRect, 'x'|'y'|'toJSON'>} Rect */
/**
* @param {Rect} clientRect
* @param {LH.Artifacts.ViewportDimensions} viewport
* @return {boolean}
*/
function isBoxInViewport(clientRect, viewport) {
const {innerWidth, innerHeight} = viewport;
const {left, top, right, bottom} = clientRect;
return left < right && top < bottom && // Non-zero area
left < innerWidth && top < innerHeight && 0 < right && 0 < bottom;
}
/**
* @param {Rect} clientRect
* @param {LH.Artifacts.ViewportDimensions} viewport
* @return {number}
*/
function boxViewableArea(clientRect, viewport) {
if (!isBoxInViewport(clientRect, viewport)) return 0;
const {innerWidth, innerHeight} = viewport;
const {left, top, right, bottom} = clientRect;
return (Math.min(right, innerWidth) - Math.max(left, 0)) *
(Math.min(bottom, innerHeight) - Math.max(top, 0));
}
/**
* Converts points (from a TraceEvent) to a Rect.
* @param {number[]} points
* @return {Rect}
*/
function toClientRect([left, top, width, height]) {
return {
left,
top,
width,
height,
right: left + width,
bottom: top + height,
};
}
/**
* Checks Rect a overlaps Rect b. Note that this returns true for
* overlapping perimeters.
* @param {Rect} a
* @param {Rect} b
* @return {boolean}
*/
function overlaps(a, b) {
const overlapX = !(a.right < b.left || b.right < a.left);
const overlapY = !(a.bottom < b.top || b.bottom < a.top);
return overlapX && overlapY;
}
export {
boxViewableArea,
isBoxInViewport,
overlaps,
toClientRect,
};
|
var testid = "37", testname = casper.cli.get("testname") + testid;
casper.test.begin(testname, 2, function suite(test) {
casper.start(casper.cli.get("url") + '/' + casper.cli.get("page"), function() {
var file = '.\\' + casper.cli.get("testdata") + '\\' + testname + '.rdf';
this.page.uploadFile('input[type="file"]', file);
this.click('div.more');
this.wait(300, function() {
this.sendKeys('input#tab1endpoint', casper.cli.get("url") + '/' + casper.cli.get("endpoint"), {reset: true});
//if (casper.cli.has("output")) {this.capture(casper.cli.get("output") + '/' + testname + '-0.png'); }
this.click('button[id="tab1validate"]');
});
});
casper.then(function() {
this.waitForResource(casper.cli.get("url") + '/sparql', function() {
//if (casper.cli.has("output")) {this.capture(casper.cli.get("output") + '/' + testname + '-1.png'); }
this.page.injectJs('.\\' + casper.cli.get("testdata") + '\\jquery.js');
var results, violationid;
var results= this.evaluate(function () {
return $("#results tbody tr").length; // jquery here
});
//this.echo(results);
test.assertEquals(results, 1);
var violationid= this.evaluate(function () {
return $("#results tbody tr:nth-child(1) td:nth-child(2) a").text(); // jquery here
});
//this.echo(violationid);
test.assertEquals(violationid, testid);
}, 3000);
});
casper.run(function() {
test.done();
});
});
|
app.factory('DataService', [function () {
//getEmployee
var getEmployee = function (id) {
if (id == 123) {
return {
id: 123,
fullName: 'nguyen van nam',
notes: 'laptrinhvien',
department: 'ngnam',
dateHired: '2/3/2015',
mytime: '2/3/2015 9:45 AM',
rate: 5,
isUnderNonComplete: false,
perkCard: true,
perkStock: false,
perkSixWeek: true,
payrollType: "none"
};
}
return console.log('no data');
};
//insertEmployee
var insertEmployee = function (newEmployee) {
return true;
};
//updateEmployee
var updateEmployee = function (employee) {
return true;
};
return {
insertEmployee: insertEmployee,
updateEmployee: updateEmployee,
getEmployee: getEmployee
};
}])
|
let Dog = function(color, hungry) {
this.status = "normal",
this.color = "black"
if (hungry !== undefined) {
this.hungry = hungry;
} else {
this.hungry = false;
}
}
// var sadie = new Dog()
// var moonshine = new Dog()
export
default Dog;
|
import React from 'react'
import Style from './Dialogs.module.css'
class Dialogs extends React.Component {
constructor() {
super()
}
render () {
return (
<div>
Dialog
</div>
)
}
}
export default Dialogs
|
var bf = new Buffer("Hello");
console.log(bf.toString());
console.log(bf.toString('base64'));
console.log(bf.toString('utf-8', 0, 2));
|
import renderer from 'react-test-renderer';
import Input from '../components/Input';
import React from 'react';
import { mount, shallow } from 'enzyme';
import enzymeConfig from '../../enzymeConfig';
import * as mock_dummyData from './dummy/data';
jest.mock('react-redux', () => ({
useDispatch: ()=> { },
useSelector: () => ({
OrganizationReducer: {
isError: true,
error: mock_dummyData.error
},
RepoReducer: {
isError: true,
error: mock_dummyData.error
}
})
}));
describe('<Input/>', function() {
it('Should render correctly', function(){
const component = renderer.create(<Input />);
const tree = component.toJSON();
expect(tree).toMatchSnapshot();
});
it('Should have correct label and input type', function(){
const component = shallow(<Input label={'Number'} type={'number'}/>);
expect(component.find('span').at(0).text()).toEqual('Number');
expect(component.find('input.form-control[type="number"]')).toHaveLength(1);
});
it('Text input should be correct', function() {
const component = mount(<Input label={'Test'} type={'text'}/>);
const input = component.find('input.form-control');
input.simulate('change', {target: {value: 'someth ing'}});
expect(input.instance().value).toEqual('something');
})
it('Error messages should be correct', function() {
const component = shallow(<Input/>);
component.find('button').simulate('click');
const errorMessage = component.find('span.text-danger');
expect(errorMessage.text()).toEqual('*You need to enter a username to search')
})
//TODO: Add more tests related to error display & data fetching test using nock and async-wait-until
})
|
import { css } from 'styled-components';
import { COLORS, OTHER, SPACE_SIZE } from '@/utils/styleConstants';
const TextAreaStyles = css`
display: block;
width: 100%;
min-height: 95px;
padding: ${SPACE_SIZE.XXS} ${SPACE_SIZE.XS};
color: ${COLORS.INPUT.TEXT};
font: 14px/16px var(--ff);
border: 1px solid ${COLORS.INPUT.BORDER};
${OTHER.BORDER_RADIUS};
overflow: auto;
resize: none;
&:hover,
&:focus {
border-color: ${COLORS.INPUT.TEXT};
}
&::placeholder {
color: ${COLORS.TEXT.PLACE_HOLDER};
}
`;
export default TextAreaStyles;
|
document.querySelector("#login").addEventListener("click", login);
function login(){
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
let existingMessage = document.getElementById("statusMessage");
if(existingMessage){
existingMessage.remove()
}
let username = document.getElementById("username").value
let password = document.getElementById("password").value
async function sendDataToServer(){
const config = {
method: "POST",
headers: {"Content-Type": "application/json"},
body: JSON.stringify({username:username, password:password})}
const response = await fetch("http://127.0.0.1:5000/api/popup/login", config);
const data = await response.json();
let newParagraph = document.createElement('p');
newParagraph.setAttribute("id", "statusMessage");
let cardBody = document.getElementsByClassName("card-body")[0];
if(data.status === "success"){
chrome.storage.sync.set({session_id:data.session_id}, function(){
console.log('Value is set to ' + data.session_id);
});
var text = document.createTextNode("Login Successful")
chrome.browserAction.setPopup({popup: "popup.html"});
newParagraph.appendChild(text);
cardBody.appendChild(newParagraph);
setTimeout(()=>{
window.close()
},1200)
}else{
var text = document.createTextNode("Login Failed")
chrome.browserAction.setPopup({popup: "login.html"});
newParagraph.appendChild(text);
cardBody.appendChild(newParagraph);
}
chrome.tabs.sendMessage(tabs[0].id, {status:data.status, username:data.username, session_id:data.session_id}); //send message to content.js to display in the console
}
sendDataToServer()
})
}
|
import React, { Component } from 'react'
import ArticleList from './ArticleList'
import { Link } from '@reach/router'
import * as api from "../../api"
import Konami from 'react-konami-code'
export default class ArticlePage extends Component {
state = {
sort_by: "created_at",
topic: null,
author: null,
order: "desc",
topics: [],
konami: false
}
render() {
return (
<div className="articlePageWrapper">
<div className={this.state.konami? "bgimg-doggo" : "bgimg-1"} >
<Konami action={this.easterEgg}></Konami>
<div className="caption1">
<span className="border">↓ARTICLES↓</span>
</div>
</div>
<div className="articlePageFlex">
<div className="h3Box">
<h3 className="h3Border">Here are all of our articles. Use the buttons below to see articles relating to specific topics.
</h3>
</div>
<div className="sortByWrapper">
<label>Sort by:
<select name="sort_by" id="sort_by_Select" value={this.state.sort_by} onChange={this.handleChange} className="select-css">
<option value="created_at">Date posted</option>
<option value="votes">Votes</option>
<option value="comment_count">Number of comments</option>
<option value="author">Author</option>
<option value="topic">Topic</option>
</select>
</label>
</div>
<ul className="listOfTopics">
<li key="allTopics" className="topics"><Link to={`/articles/`} className="topics">{"<"} all topics {'/>'}</ Link></li>
{this.state.topics.map(topic => {
return <li key={`${topic.slug}`} className="topics"><Link to={`/articles/topics/${topic.slug}`} className="topics">{`< ${topic.slug} />`}</Link></li>
})}
</ul>
<ArticleList className="ArticleListWrapper" topic={this.state.topic} sort_by={this.state.sort_by} author={this.state.author} />
</div>
</div>
)
}
componentDidMount() {
this.fetchTopics();
}
handleChange = (event) => {
const { value } = event.target
this.setState(currentState => {
return { articles: currentState.articles, sort_by: `${value}` }
});
}
fetchTopics = () => {
return api.getTopics().then(topics => {
this.setState({ topics: topics })
})
}
easterEgg = () => {
const selected = window.confirm("Get ready for cuteness")
if (selected) {
this.setState({ konami: true })
}
}
}
|
importScripts('/_nuxt/workbox.3de3418b.js')
const workboxSW = new self.WorkboxSW({
"cacheId": "master",
"clientsClaim": true,
"directoryIndex": "/"
})
workboxSW.precache([
{
"url": "/_nuxt/app.8195eebbc24851e37706.js",
"revision": "77b0f31ef8e66f0118708ab326d4ee62"
},
{
"url": "/_nuxt/layouts/default.8b71241a806b4a658afb.js",
"revision": "ced48dc14c901f466932ff228e272049"
},
{
"url": "/_nuxt/manifest.0a9bc55d1f596cbfe0f7.js",
"revision": "784c1722cffcd386d4475dd56eb3a6a5"
},
{
"url": "/_nuxt/pages/index.483d9e58ab87d303b154.js",
"revision": "2e65c8aedb34fbf8727098eac4822049"
},
{
"url": "/_nuxt/pages/login.fad26d49934049b83934.js",
"revision": "04880bc8baeb4195e8c9e9b701035e43"
},
{
"url": "/_nuxt/vendor.d3668abf8668933cad18.js",
"revision": "f67c9eb8b7ad910cfcb496b210b4ddfb"
}
])
workboxSW.router.registerRoute(new RegExp('/_nuxt/.*'), workboxSW.strategies.cacheFirst({}), 'GET')
workboxSW.router.registerRoute(new RegExp('/.*'), workboxSW.strategies.networkFirst({}), 'GET')
|
import React from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import { colors } from '../utils';
import { Icon } from '.';
const Select = ({ children }) => (
<SelectContainer>
<p>{children}</p>
<Icon name="carrot" />
</SelectContainer>
);
Select.propTypes = {
children: PropTypes.string.isRequired,
};
const SelectContainer = styled.div`
display: flex;
height: 36px;
border-radius: 4px;
border: 1px solid ${colors.lightGrey};
background-color: ${colors.almostWhite};
padding: 0 8px 0 12px;
align-items: center;
${({ margin }) =>
margin &&
`
margin-right: 16px;
`};
> p {
font-family: GTAmericaMedium;
color: ${colors.darkGrey};
margin-right: 6px;
padding-bottom: 4px;
}
`;
export default Select;
|
import Vue from 'vue'
import VueRouter from 'vue-router'
import Feed from '../views/Feed.vue'
import { ToastProgrammatic as Toast } from 'buefy'
import store from '../store/index'
Vue.use(VueRouter)
const routes = [
// Feed
{
path: '/',
redirect: '/discover'
},
{
path: '/discover',
name: 'Discover',
component: Feed
},
// Guest Login
{
path: '/login',
name: 'Login',
meta: { guest: true },
component: () => import('../views/Login.vue')
},
// Recipe
{
path: '/recipe/:id',
component: () => import('../views/Recipe.vue')
},
// Recipe add/update
{
path: '/recipe/:id/update',
meta: { requiresAuth: true },
component: () => import('../views/UpdateRecipe.vue')
},
{
path: '/add/recipe',
meta: { requiresAuth: true },
component: () => import('../views/AddRecipe.vue')
},
// User Profile
{
path: '/user/:id',
component: () => import('../views/UserProfile.vue')
},
// Settings
{
path: '/user/:id/settings',
name: 'Settings',
meta: { requiresAuth: true },
component: () => import('../views/Settings.vue'),
children: [
{
path: 'account',
component: () => import('../views/settings/Account.vue')
},
{
path: 'favorites',
component: () => import('../views/settings/Favorites.vue')
},
{
path: 'manage_users',
meta: { isAdmin: true },
component: () => import('../views/admin/Users.vue')
},
{
path: 'manage_recipes',
meta: { isAdmin: true },
component: () => import('../views/admin/Recipes.vue')
}
]
},
// About
{
path: '/about',
name: 'About',
component: () => import('../views/About.vue')
}
]
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes,
scrollBehavior(...args) {
if (args[2]) {
return args[2]
} else {
return { x: 0, y: 0 }
}
}
})
//
router.beforeEach((to, from, next) => {
// Checks if route is requies user to be authenticated
if (to.matched.some(record => record.meta.requiresAuth)) {
if (store.state.loggedIn !== null) {
// Checks if user is authenticated
if (localStorage.getItem('jwt') === store.state.loggedIn.authToken) {
// Checks if route is requies user to be admi
if (to.matched.some(record => record.meta.isAdmin)) {
// Checks if user is admin
if (store.state.loggedIn.meta.isAdmin) {
next()
} else {
next({ path: '/' })
}
} else {
next()
}
}
} else {
Toast.open({
message: `Need to be logged in to proceed to this page!`,
type: 'is-warning'
})
next({
path: '/login',
params: { nextUrl: to.fullPath }
})
}
// Checks if route is requies user not to be authenticated
} else if (to.matched.some(record => record.meta.guest)) {
if (localStorage.getItem('jwt') === null) {
next()
}
else {
next({ name: 'Discover' })
}
} else {
next()
}
})
export default router
|
function access1(){
$( "#block-access1" ).show( "slow" );
$( "#block-access2" ).hide();
$( "#block-access3" ).hide();
$( "#block-access4" ).hide();
}
function access2(){
$( "#block-access2" ).show( "slow" );
$( "#block-access1" ).hide();
$( "#block-access3" ).hide();
$( "#block-access4" ).hide();
}
function access3(){
$( "#block-access3" ).show( "slow" );
$( "#block-access1" ).hide();
$( "#block-access2" ).hide();
$( "#block-access4" ).hide();
}
function access4(){
$( "#block-access4" ).show( "slow" );
$( "#block-access1" ).hide();
$( "#block-access2" ).hide();
$( "#block-access3" ).hide();
}
|
'use strict';
function QueueCtrl($scope, $rootScope, $state, $ionicModal, $cordovaKeyboard, $ionicPopup, lodash, Queue) {
var vm = this;
$rootScope.votes = {};
$rootScope.$watch('user.connected', function(conn) {
if (conn) {
Queue.get().$loaded().then(function(queue) {
$rootScope.queueList = queue;
});
}
});
$ionicModal.fromTemplateUrl('templates/modal/queue.tmpl.html', {
scope: $scope,
controller: 'QueueCtrl',
controllerAs: 'queue',
animation: 'slide-in-up'
}).then(function(modal) {
vm.modal = modal;
});
vm.goto = function(id) {
vm.close();
$state.transitionTo('app.artist', { action: 'slug', artistId: id });
};
vm.close = function() {
vm.modal.hide().then(function() {
if (window.cordova && window.cordova.plugins.Keyboard) {
$cordovaKeyboard.disableScroll(false);
}
});
};
vm.open = function() {
if (window.cordova && window.cordova.plugins.Keyboard) {
$cordovaKeyboard.disableScroll(true);
}
vm.modal.show();
};
vm.remove = function(track) {
$ionicPopup.confirm({
template: 'Are you sure you want to delete this video from the queue?',
title: 'Alma',
cancelText: 'Cancel',
okText: 'Delete'
}).then(function(res) {
if (res) {
Queue.remove(track).then(function() {
$ionicPopup.alert({
template: 'Your video has successfully been removed from the queue',
title: 'Alma'
});
});
}
});
};
vm.vote = function(track, vote) {
Queue.vote(track.$id, vote);
};
vm.status = function(vote) {
return (!angular.isDefined(vote)) ? false : !vote;
};
}
angular.module('arcanine.controllers').controller('QueueCtrl', QueueCtrl);
|
module.exports = {
siteUrl: process.env.SITE_URL || "https://estrilda.damonge.com",
generateRobotsTxt: true,
outDir: "./out",
};
|
/* eslint-disable react-hooks/exhaustive-deps */
import React, { useEffect } from 'react';
import { useDispatch } from 'react-redux';
import { useSelector } from 'react-redux';
import { useLocation } from 'react-router';
import { addToRecentlyViewed } from '../../redux/booksSlice';
import Footer from '../HomePage/Footer';
import BookDetails from './BookDetails';
import BooksSidebar from './BooksSidebar';
const BookDetailsPage = () => {
const { book } = useLocation().state
const { recentlyViewed } = useSelector(state => state.books)
const dispatch = useDispatch()
useEffect(() => {
if (recentlyViewed.indexOf(book) === -1) {
dispatch(addToRecentlyViewed(book))
}
}, [book]);
return (
<>
<div className="container-fluid">
<div className="row">
{/* Main Content */}
<div className="col-xl-8 col-lg-7 mt-4 mb-5 ps-5">
<BookDetails book={book} />
</div>
{/* Suggested books Sidebar */}
<div className="col-xl-3 col-lg-4">
<BooksSidebar recentlyViewed={recentlyViewed} />
</div>
</div>
</div>
{/* Footer */}
<Footer />
</>
);
}
export default BookDetailsPage;
|
var _Component;
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
Component((_Component = {
properties: {},
options: {
multipleSlots: true
},
data: {
flag: false,
wrapAnimate: "",
bgOpacity: 0,
frameAnimate: ""
}
}, _defineProperty(_Component, "properties", {
frameTitle: {
type: String,
value: "标题"
},
custom: {
type: Boolean,
value: false
}
}), _defineProperty(_Component, "methods", {
catchMove: function catchMove() {},
showFrame: function showFrame() {
this.setData({
flag: true,
wrapAnimate: "wrapAnimate",
frameAnimate: "frameAnimate"
});
},
hideFrame: function hideFrame() {
var that = this;
that.setData({
wrapAnimate: "wrapAnimateOut",
frameAnimate: "frameAnimateOut"
});
setTimeout(function() {
that.setData({
flag: false
});
}, 200);
},
catchNone: function catchNone() {
//阻止冒泡
},
_showEvent: function _showEvent() {
this.triggerEvent("showEvent");
},
_hideEvent: function _hideEvent() {
this.triggerEvent("hideEvent");
}
}), _Component));
|
// Creare un oggetto che descriva uno studente con le seguenti proprietà: nome, cognome e età. Stampare a schermo attraverso il for in tutte le proprietà.
// var utente = {
// 'nome': 'Federico',
// 'cognome': 'Caiello',
// 'eta\'': 25,
// };
// for (var caratteristiche in utente) {
// console.log(utente[caratteristiche]);
// }
// Creare un array di oggetti di studenti. Ciclare su tutti gli studenti e stampare per ognuno nome e cognome
// var studenti = [
// {
// 'nome': 'Federico',
// 'cognome': 'Caiello',
// 'cose': 'macchina'
// },
// {
// 'nome': 'Marco',
// 'cognome': 'Stefanini',
// 'cose': 'macchina'
// },
// {
// 'nome': 'Lorenzo',
// 'cognome': 'Petrollini',
// 'cose': 'chiavi'
// }
// ];
// console.log(studenti);
//
// for (var i=0; i < studenti.length; i++){
// console.log(studenti[i].nome + studenti[i].cognome);
// }
// Dare la possibilità all’utente attraverso 3 prompt di aggiungere un nuovo oggetto studente inserendo nell’ordine: nome, cognome e età.
var array = [{
'nome': 'Federico',
'cognome': 'Caiello',
'eta\'': 25
},{
'nome': prompt('inserisci il tuo nome'),
'cognome': prompt('inserisci il tuo cognome'),
'eta': parseInt(prompt('inserisci la tua eta'))
}];
for (var chiave in array) {
console.log(chiave, array[chiave]);
for (var i=0; i<array[chiave].length; i++) {
console.log('posizione' + i + ' ' + array[chiave][i]);
}
}
|
/**
* 操作title(标题名称) 和 content(需要推送的消息内容) (创建时间 显示) logic(作为消息是否发送的逻辑处理字段 0默认未发送 1 已经发送)
*
*/
var msgPush = AV.Object.extend("msgPush");
function GetRequest() {
var url = location.search;
var theRequest = new Object();
if (url.indexOf("?") != -1) {
var str = url.substr(1);
strs = str.split("&");
for(var i = 0; i < strs.length; i ++) {
theRequest[strs[i].split("=")[0]]=(strs[i].split("=")[1]);
}
}
return theRequest;
}
function getTime(){
var Request = GetRequest();
var username=Request["username"];
var cql="select * from _User where username='"+username+"'";
AV.Query.doCloudQuery(cql, {
success: function(result){
//加载消息列表数据
var time = JSON.stringify(result.results[0]._serverData.readTime);
console.log(time);
loadData(time,0);
},
error: function(error){
}
});
}
var pageNo=1;
var count=0;
var pageSize=10;
function loadData(loginTime,page){
var whereMsg="sendTime>=date("+loginTime+")";
if(loginTime==undefined||loginTime.length==0){
whereMsg="sendTime<>null";
}
cql="select count(*),* from msgPush where "+whereMsg+" order by sendTime desc";
if(page!=0){
cql+=" limit "+(page-1)*pageSize+","+pageSize;
}
console.log(cql);
AV.Query.doCloudQuery(cql, {
success: function(result){
console.log(result);
//results 是查询返回的结果,AV.Object 列表
var obj = result.results;
count = result.count;
myCount = count%pageSize== 0?(count/pageSize==0?1:count/pageSize):parseInt(count/pageSize)+1;
if (page==myCount) {
$("#btn1").attr("disabled","disabled");
document.getElementById("btn1").style.visibility="hidden";
}
//alert(obj.length);
// $("#dataMsg").html("");
//清空选择数据
for (var i = 0; i < obj.length; i++) {
var productionObj = obj[i];
addTableRow(productionObj);
}
},
error: function(error){
console.log(error);
//查询失败,查看 error
if(whichHint == 3){
$("#hintinfo3").html("<font color='red'>"+error.message+"</font>");
}
if(whichHint == 1){
$("#hintinfo").html("<font color='red'>"+error.message+"</font>");
}
}
});
}
//展现列表数据
function addTableRow(productionObj) {
var fields = ["get('title')"];
var htmlString = "<tr style='height:50px;' id=\"ul_"+productionObj.id+"\" onclick=\"artdel('"+productionObj.id+"')\">";
for (var i = 0; i < fields.length; i++) {
htmlString += "<td><font>" + eval("productionObj." + fields[i]) + "</font></td>";
}
htmlString += "</tr>";
$("#dataMsg").html($("#dataMsg").html() + htmlString);
}
function artdel(did){
window.location="msgdetail.html?msgid="+did;
}
function goPage(type) {
if (type == -1) {
$("#btn1").removeAttr("disabled");
if (pageNo == 1) {
$("#btn2").attr("disabled","disabled");
return;
}
pageNo = pageNo - 1;
if (pageNo==1) {
$("#btn2").attr("disabled","disabled");
}
}
if (type == 1) {
$("#btn2").removeAttr("disabled");
var myCount = count%pageSize== 0?(count/pageSize==0?1:count/pageSize):parseInt(count/pageSize)+1;
if (pageNo==myCount) {
$("#btn1").attr("disabled","disabled");
document.getElementById("btn1").style.visibility="hidden";
return;
}
pageNo = pageNo + 1;
if (pageNo==myCount) {
$("#btn1").attr("disabled","disabled");
document.getElementById("btn1").style.visibility="hidden";
}
}
loadData("",pageNo);
}
|
const { baseResolver } = require('../../../libaries/apollo-resolver-creator')
const properties = baseResolver.createResolver(
async (subCategory, args, context) => {
return context.models.subCategoryProp.getBySubCategoryId(subCategory._id)
}
)
const category = baseResolver.createResolver(
async (subCategory, args, context) => {
return context.models.category.getOne({ _id: subCategory.categoryId })
}
)
module.exports = {
SubCategory: {
category,
properties,
},
}
|
// ==UserScript==
// @name reddit-open
// @namespace test
// @description open each link to comments in a new tab
// @include *reddit.com*
// @version 1
// @grant none
// ==/UserScript==
function getElementsByClassName(oElm, strTagName, strClassName){
var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
var arrReturnElements = new Array();
strClassName = strClassName.replace(/\-/g, "\\-");
var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
var oElement;
for (var i=0; i<arrElements.length; i++) {
oElement = arrElements[i];
if (oRegExp.test(oElement.className)) {
arrReturnElements.push(oElement);
}
}
return (arrReturnElements)
}
function OpenInNewTab(url) {
var win = window.open(url, '_blank');
win.focus();
}
var all = getElementsByClassName(document, 'a', 'comments');
for (var i = 0; i < all.length; i++) {
//console.log( i + " ---- " + all[i].href)
OpenInNewTab(all[i].href);
}
|
function HomeController($scope, $location) {
$scope.go = function(path) {
$location.path(path);
};
};
HomeController.$inject = ['$scope', '$location'];
angular
.module('uponnyc')
.controller('HomeController', HomeController)
|
import React from 'react';
import { List, Datagrid, TextField, ReferenceManyField, SingleFieldList, ChipField } from 'admin-on-rest';
import { Create, SimpleForm, TextInput, SelectInput, LongTextInput, ReferenceInput } from 'admin-on-rest';
import { Edit, DisabledInput, EditButton } from 'admin-on-rest';
import { Filter, } from 'admin-on-rest';
//import { TabbedForm, FormTab } from 'admin-on-rest';
export const AddressesFilter = (props) => (
<Filter {...props}>
<TextInput label="Title RegEx" source="title[$search]" alwaysOn />
<TextInput label="SEARCH FULL TEXT" source="$text[$search]" alwaysOn />
<ReferenceInput label="Team" source="_id" reference="teams" allowEmpty>
<SelectInput optionText="name" />
</ReferenceInput>
</Filter>
);
export const AddressesList = (props) => (
<List {...props} filters={<AddressesFilter />}>
<Datagrid>
<TextField label= "ID" source="_id"/>
<TextField label= "title" source="title" style={{textAlign: ""}}/>
<TextField label= "Street" source="streetAddress" />
<TextField label= "city" source="city" />
<TextField label= "Zip" source="postalCode" />
<TextField label= "Country" source="addressCountry" />
<TextField label= "Complement" source="addressExtra" />
<EditButton />
</Datagrid>
</List>
);
export const AddressesCreate = (props) => (
<Create {...props}>
<SimpleForm>
<TextInput label="Address Title" source="title"/>
<LongTextInput label= "Street" source="streetAddress" style={{ maxWidth: 544 }} />
<TextInput label= "Zip" source="postalCode" style={{ display: 'inline-block' }} />
<TextInput label= "city" source="city" style={{ display: 'inline-block', marginLeft: 32 }} />
<TextInput label= "Country" source="addressCountry" />
<TextInput label= "Complement" source="addressExtra" />
</SimpleForm>
</Create>
);
export const AddressesEdit = (props) => (
<Edit {...props}>
<SimpleForm>
<TextInput label= "title" source="title"/>
<LongTextInput label= "Street" source="streetAddress" style={{ maxWidth: 544 }} />
<TextInput label= "Zip" source="postalCode" style={{ display: 'inline-block' }} />
<TextInput label= "city" source="city" style={{ display: 'inline-block', marginLeft: 32 }} />
<TextInput label= "Country" source="addressCountry" />
<TextInput label= "Complement" source="addressExtra" />
</SimpleForm>
</Edit>
);
/*
export const EntitiesCreate = (props) => (
<Create {...props}>
<TabbedForm>
<FormTab label="identity">
<SelectInput source="type" choices={choices} optionText="label" optionValue="_id" />
<TextInput label= "Name" source="name" style={{ display: 'inline-block' }} />
<TextInput label= "Firstname" source="firstname" style={{ display: 'inline-block' , marginLeft: 32}} />
<TextInput label= "SIRET" source="siret" />
<TextInput label= "E-mail" source="email" />
<TextInput label= "Phone" source="phone" />
<TextInput label= "Addresses" source="addresses" />
</FormTab>
<FormTab label="Addresses">
</FormTab>
<FormTab label="Bank">
<TextInput label= "IBAN" source="bankAccounts" style={{ display: 'inline-block' }} />
<TextInput label= "BIC/SWIFT" source="swift" style={{ display: 'inline-block' , marginLeft: 32}} />
</FormTab>
</TabbedForm>
</Create>
);*/
|
angular.module('adCreativeService', [])
.factory('AdCreative', function($http) {
return {
get : function() {
return $http.get('/Api/wz-adcreative');
},
save : function(adCreativeData) {
return $http({
method: 'POST',
url: '/Api/wz-adcreative',
headers: { 'Content-Type' : 'application/x-www-form-urlencoded' },
data: $.param(adCreativeData)
});
},
savePageLinkAd:function(adCreativeData){
return $http({
method: 'POST',
url: '/Api/wz-adcreative-page-link-ad',
headers: { 'Content-Type' : 'application/x-www-form-urlencoded' },
data: $.param(adCreativeData)
});
},
saveCallToActionAd:function(adCreativeData){
return $http({
method: 'POST',
url: '/Api/wz-adcreative-callto-action-ad',
headers: { 'Content-Type' : 'application/x-www-form-urlencoded' },
data: $.param(adCreativeData)
});
},
saveVideoPageLikeAd:function(adCreativeData){
return $http({
method: 'POST',
url: '/Api/wz-adcreative-video-pagelike-ad',
headers: { 'Content-Type' : 'application/x-www-form-urlencoded' },
data: $.param(adCreativeData)
});
},
fetchVideoThumbImages:function(adCreativeData){
return $http.get('video-thumb-url?video_id='+adCreativeData.video_id);
},
savePagePostAd:function(adCreativeData){
return $http({
method: 'POST',
url: '/Api/wz-adcreative-page-post-ad',
headers: { 'Content-Type' : 'application/x-www-form-urlencoded' },
data: $.param(adCreativeData)
});
},
fetchPagePosts:function(adCreativeData){
return $http.get('list-page-posts?page_id='+adCreativeData.page_id);
},
saveProductsAd:function(adCreativeData){
return $http({
method: 'POST',
url: '/Api/wz-adcreative-carousal-ad',
headers: { 'Content-Type' : 'application/x-www-form-urlencoded' },
data: $.param(adCreativeData)
});
}
}
});
|
import dependencyInjector from '../core/utils/dependency_injector';
import parentLocales from './cldr-data/parent_locales';
import getParentLocale from './parentLocale';
var DEFAULT_LOCALE = 'en';
export default dependencyInjector({
locale: (() => {
var currentLocale = DEFAULT_LOCALE;
return locale => {
if (!locale) {
return currentLocale;
}
currentLocale = locale;
};
})(),
getValueByClosestLocale: function getValueByClosestLocale(getter) {
var locale = this.locale();
var value = getter(locale);
var isRootLocale;
while (!value && !isRootLocale) {
locale = getParentLocale(parentLocales, locale);
if (locale) {
value = getter(locale);
} else {
isRootLocale = true;
}
}
if (value === undefined && locale !== DEFAULT_LOCALE) {
return getter(DEFAULT_LOCALE);
}
return value;
}
});
|
export class myClass {
constructor() {
}
}
|
/**
* Created by KyoheiMorimoto on 2014/04/28.
*/
TodoAppManager.module("TodoApp.List",function(List,TodoAppManager,Backbone,Marionette,$,_){
List.Controller = {
listTodos : function(){
var todos = TodoAppManager.request("todo:TodoModel");
var todosView = new List.TodosView({
collection:todos
});
todosView.on("itemview:todo:delete", function(childView,model){
todos.remove(model);
});
TodoAppManager.mainRegion.show(todosView);
}
}
});
|
const Promise = require('bluebird');
const _ = require('lodash/fp');
const c = require('chalk');
const executeScript = require('../core/script');
const __listDependencies = (isDev, pkg, requestedDependencies) => {
const depsKey = isDev ? 'devDependencies' : 'dependencies';
return _.intersection(requestedDependencies, Object.keys(pkg[depsKey] || {}));
};
const install = isDev => (pkg, requestedDependencies) => {
const dependencies = __listDependencies(isDev, pkg, requestedDependencies);
if (_.isEmpty(dependencies)) {
return Promise.resolve([]);
}
const mode = isDev ? '--dev' : '';
return executeScript([
`yarn add ${dependencies.join(' ')} --exact --ignore-engines --ignore-scripts ${mode}`
]).then(() => {
process.stdout.write(`+ ${dependencies.map(d => c.bold.dim(d)).join(', ')} installed\n`);
return dependencies;
});
};
module.exports = {
install: install(''),
installDev: install('--dev'),
__listDependencies
};
|
import configManager from './config';
class Boot {
init() {
this.config = configManager.getConfig();
this.game.stage.backgroundColor = "#FFFFFF";
}
preload() {
this.game.loadAssets('boot');
}
startPreloadScene() {
this.game.state.start("Preload");
}
create() {
this.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
setTimeout(this.startPreloadScene.bind(this), 500);
}
}
export default Boot;
|
import React, { Component } from 'react';
import { Tabs, Tab, Paper } from 'material-ui';
import Signups from './signups';
import { SIGNUPS, GROUP_STAGE, PLAYOFFS, COMPLETED } from '../../constants/tournament-phases';
const renderStandings = function(tournament) {
if (tournament.phase === SIGNUPS) {
return;
}
return (
<Tab label="Standings" value="standings" key="standings">
</Tab>
);
};
const renderIntake = function(tournament) {
return (
<Tab label="Signups" value="signups" key="signups">
<Signups tournament={tournament} />
</Tab>
);
};
const renderTabs = function(tournament) {
return [
renderStandings(tournament),
renderIntake(tournament)
].filter(tab => !!tab);
};
export default function TournamentTabs(props) {
const { tournament, selected } = props;
return (
<Paper zDepth={1}>
<Tabs
value={selected}
onChange={tab => props.doSelectTab(tournament, tab)}
key={tournament.id}>
{renderTabs(tournament)}
</Tabs>
</Paper>
);
}
|
define({
debug: false,
frame: "jquery",
main: "app",
charset: "utf-8",
base: "http://10.228.132.171:8070/easyjs/",
alias: {
jquery: "jquery/jquery.1.10.2.js",
app: "./demo/app.js",
usetest: "./demo/test.js",
test: "10.228.132.171:8070/easyjs/demo/exports.js",
testa: "./demo/exports.js",
testb: "./demo/testb.js",
testc: "./demo/testc.js",
jqcookie: "./demo/plugs/jq.cookie/jq.cookie.js",
jqcontextmenu: "./demo/plugs/jq.contextmenu/jq.contextmenu.js",
jqlocalstorage: "./demo/plugs/jq.localstorage/jq.localstorage.js",
html5video_pc: "./demo/plugs/html5video.pc/jq.html5video.js",
html5video_tracksdemo: "./demo/plugs/html5video.pc/jq.html5video.tracksdemo.js",
html5video_pc_css: "./demo/plugs/html5video.pc/jq.html5video.css"
},
paths: {
demo: "demo",
module: "demo",
jquery: "demo"
},
preload: ["http://10.228.132.171:8070/easyjs/demo/easyjs.dom.js", "module/easyjs.style.js"]
});
|
import AppError from '../errors/AppError';
class SessionController {
constructor(user) {
this.User = user;
}
async show(id) {
const user = await this.User.findById(id);
if (!user) {
throw new AppError(400, 'User does not exist.');
}
return user;
}
}
export default SessionController;
|
const puppeteer = require('puppeteer');
var USER = {login:"",password:""}
async function main() {
const browser = await puppeteer.launch({headless:false});
const page = await browser.newPage();
await page.goto('https://sigaa.ufpi.br/sigaa/verTelaLogin.do');
// Fill username field
await page.$eval('input[name="user.login"]', (el, user) => el.value = user, USER.login);
// Fill password field
await page.$eval('input[name="user.senha"]', (el, user) => el.value = user, USER.password);
// Click login and wait for loading
await Promise.all([
page.click("input[type=submit]"),
page.waitForNavigation({ waitUntil: 'networkidle0' }),
]);
var [button] = await page.$x("//span[contains(., 'Ensino')]");
if (button)
await button.click();
var [button] = await page.$x("//td[contains(., 'Minhas Notas')]")
if (button)
await button.click();
}
main()
|
import { createSlice } from "@reduxjs/toolkit";
const initialState = {
isBooting: false,
};
export const slice = createSlice({
name: "app",
initialState,
reducers: {
startBoot: (state) => {
state.isBooting = true;
},
completeBoot: (state) => {
state.isBooting = false;
},
},
});
export const { startBoot, completeBoot } = slice.actions;
export const selectIsBooting = (state) => state.app.isBooting;
export default slice.reducer;
|
import React from 'react';
import {BrowserRouter as Router, Route, Redirect, Switch, Link} from 'react-router-dom';
import createBrowserHistory from 'history/createBrowserHistory';
import Home from '../views/home';
import WrappedNormalLoginForm from '../views/login';
const customHistory = createBrowserHistory();
const RootRoute = () => {
/*const routes = createRootRoutes();
console.log('routes:', routes);
const generateRoutes = () => {
return routes.map(route => {
if (route.component) {
if (route.exact) {
return <Route key={route.key} exact path={route.path} component={route.component}/>
} else {
return <Route key={route.key} path={route.path} component={route.component}/>
}
} else if (route.render) {
if (route.exact) {
return <Route key={route.key} exact path={route.path} render={route.render}/>
} else {
return <Route key={route.key} path={route.path} render={route.render}/>
}
}
});
};
const rootRoute = generateRoutes();
console.log('rootRoute:', rootRoute);
let routeComponent = React.createElement(Switch, null, ...rootRoute);*/
return (
<Router basename='/'>
<Switch>
<Route exact path="/" component={WrappedNormalLoginForm}/>
<Route path="/home" component={Home}/>
<Redirect from='*' to='/'/>
</Switch>
</Router>
)
};
export default RootRoute;
|
import React from 'react'
import { Option, Select } from 'muicss/react'
const SelectDefault = ({ state, value, handle, title, divClass, status }) => (
<div className={`search-form__${divClass}`}>
<Select name='input' label={title} value={value} disabled={status} onChange={handle}>
<Option value='0' label='Todas' />
{state.map(data =>
<Option key={data.ID} value={data.ID} label={data.Name} />
)}
</Select>
</div>
)
export default SelectDefault
|
const path = require("path");
const express = require("express");
const app = express();
const port = proccess.env.PORT || 3000;
const users = [];
app.use(express.urlencoded({ extended: false })); //for html form
app.use(express.json()); //for json
app.route("/").get((req, res) => {
res.sendFile(path.join(__dirname, "form.html"));
});
app
.route("./users")
.get((req, res) => {
res.setHeader("Content-Type", "text/html");
res.send(`
<html>
<body>
<ul>
${users.map((item) => `<li>${item}</li>`).join("")}
</ul>
</body>
</html
`);
})
.post((req, res) => {
const { name } = req.body;
users.push(name);
res.sendStatus(200);
});
app.listen(port, () => console.log(`Server Listening on port${port}`));
|
function setup() {
createCanvas(400, 400);
}
function draw() {
fill(mouseX + 50);
ellipse(mouseX, mouseY, 50, 200);
}
|
/**
* Created by Eric on 1/1/2016.
*/
var http = 'http://'
var domain = '10.0.0.45';
function url(path) {
return http + domain + path;
}
module.exports = {
baseTreatmentCost: 10.0,
leaflet: {
apiUrl: function () {
return 'https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}';
},
apiId: function () {
return 'jeffglc.of7g059c';
},
apiKey: function () {
return 'pk.eyJ1IjoiamVmZmdsYyIsImEiOiJjaWlic2V2ZWgwMWtkd2VsemxnNjU0amplIn0.4_KiKQDyeSB5BroosNCdAA';
}
},
api: {
getStreams: function () {
return url('/ajax/getStreams.php?');
},
getStreamPaths: function (id) {
return url('/ajax/getStreamPath.php?id=' + id);
},
}
};
|
/**
* Created by jonas on 14.03.17.
*/
import React from 'react';
import {Button, Platform, StyleSheet, Text, View, ScrollView} from 'react-native';
export default function Overview({openAnyline, checkCameraPermissionAndOpen, disabled}) {
const platformPermissionCheck = (Platform.OS === 'android') ? checkCameraPermissionAndOpen : openAnyline;
return (
<ScrollView style={styles.container}>
<Text style={styles.text}>OTHER</Text>
<View style={styles.buttons}>
<Button style={styles.buttons} title={' MRZ Scanner'} color="#0099FF"
disabled={disabled}
onPress={() => {
platformPermissionCheck('MRZ')
}}/>
</View>
</ScrollView>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
// justifyContent: 'space-between',
backgroundColor: '#303030',
marginTop: '40%',
marginBottom: '20%'
},
buttons: {
margin: 5
},
text: {
color: 'white',
textAlign: 'center',
fontSize: 20,
marginTop: 25
}
});
|
import React from 'react'
import { TouchableOpacity } from 'react-native'
import EvilIcons from 'react-native-vector-icons/EvilIcons'
const IconButton = ({ onPress }) => {
return (
<TouchableOpacity onPress={ onPress } >
<EvilIcons
name="trash"
color="#FF0000"
size={40}
/>
</TouchableOpacity>
)
}
export default IconButton
|
import React, {Component} from 'react';
import './css/dashboard.css';
import AllOrders from './all-orders';
import OrderSummary from './order-summary';
import OrderContents from './order-contents';
import { withRouter } from 'react-router-dom';
import { socket } from '../app';
class DashBoard extends Component {
componentDidMount() {
document.title="Home";
if(!this.props.globalUserLoginStatus) {
this.props.history.push('/login');
}
else {
if(new Date().toLocaleDateString().slice(0,2) === localStorage.getItem('crDate')) {
this.props.reloadPrevState();
socket.on('new order', (orderDetails) => {
this.props.addOrder(orderDetails);
this.props.showNewNotification(orderDetails.orderNumber);
})
let svgHolder = document.querySelector('.svg-holder');
if(svgHolder) {
svgHolder.style.opacity = '0';
}
}
else {
localStorage.removeItem('reactState');
localStorage.setItem('crDate',new Date().toLocaleDateString().slice(0,2));
}
}
console.log('State after updating total order served from DASHBOARD:',this.props.orderSummary);
}
render() {
return (
<React.Fragment>
{/* <HomeNavBar /> */}
<div className="dashboard m-t-50">
<OrderSummary orderSummary={this.props.orderSummary}
updateTotalOrderCount={this.props.updateTotalOrderCount} />
<AllOrders allOrders={this.props.allOrders}
setCurrentlySelectedOrder={this.props.setCurrentlySelectedOrder} />
<OrderContents selectedOrder={this.props.selectedOrder}
orderContents={this.props.orderContents}
userId={this.props.userId} updateOrderStatus={this.props.updateOrderStatus}
orderAccepted={this.props.orderAccepted} orderDeclined={this.props.orderDeclined}/>
</div>
</React.Fragment>
)
}
}
export default withRouter(DashBoard);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.