text
stringlengths 7
3.69M
|
|---|
let mass = [1, 3, 5, 6, 7];
for (let key in mass) {
console.log(key); //получаем ключи, т.е 0, 1, 2, 3, 4 - порядковые номера элементов
}
for (let key of mass) {
console.log(key); //получаем значения, т.е 1, 3, 5, 6, 7 - порядковые номера элементов
}
|
// JavaScript - Node v8.1.3
describe('Your refactored find() function', _ => {
it('should behave as expected', _ => {
var array = [2, 3, 5, 7, 11];
Test.assertEquals(find(array, 5), 2);
Test.assertEquals(find(array, 11), 4);
Test.assertEquals(find(array, 3), 1);
Test.assertEquals(find(array, 2), 0);
Test.assertEquals(find(array, 7), 3);
Test.assertEquals(find(array, 1), 'Not found');
Test.assertEquals(find(array, 8), 'Not found');
array = [true, 'Hello World', false, 'Lorem Ipsum', 6, Math.PI];
Test.assertEquals(find(array, 'Hello World'), 1);
Test.assertEquals(find(array, 'lorem ipsum'), 'Not found');
Test.assertEquals(find(array, 'Lorem Ipsum'), 3);
Test.assertEquals(find(array, false), 2);
Test.assertEquals(find(array, true), 0);
Test.assertEquals(find(array, Math.PI), 5);
Test.assertEquals(find(array, 3.14), 'Not found');
Test.assertEquals(find(array, 6), 4);
});
});
|
import { Activity, singleS3StreamInput } from 'aries-data';
import pkgJson from '../package.json';
import MySQLWriteStream from './MySQLWriteStream';
import inferSchema from './util/inferSchema';
import createReadStreamWithFilename from './util/file-read-stream';
import _ from 'highland';
export default class MySQLSink extends Activity {
static props = {
name: pkgJson.name,
version: pkgJson.version,
};
@singleS3StreamInput() // don't pass json param, inferSchema might be reading a csv file
async onTask(activityTask, config) {
const incomingSchema = await inferSchema(activityTask.input.file, config.schemaHint, config.json);
// createReadStreamWithFilename returns a Node Readable stream, we need to wrap it in highland and batch it at 1000 to make our inserts faster
const readStream = _(createReadStreamWithFilename(activityTask.input.key))
.split()
.errors(err => {});
return this.writeToMySQLWithStream(readStream, incomingSchema, config);
}
writeToMySQLWithStream(stream, schema, config) {
return new Promise((resolve, reject) => {
const writeStream = new MySQLWriteStream(schema, config);
const target = stream.pipe(writeStream);
target.on('close', () => {
this.log.info('Successfully stream records to MySQL');
resolve();
});
target.on('error', (err) => {
this.log.debug(`error on writeStream: ${err}`);
reject(err);
});
});
}
};
|
import React from "react";
import Header from "../../components/Header";
import "./style.css";
import profile from "./profile.png"
function AboutContainer() {
return (
// the uk-container class gives it a max width and wraps the main content of the website, also it will be centers and will have padding on the sides
<div className="uk-container uk-margin-right">
<div className="uk-text-center">
<div id="about-container">
<div id="about-me"><img src={profile} width="100" height="100" alt="profile picture"></img>
<Header title="About Me" />
<p className="uk-text-justify about-me">
Full-stack web developer with a background in immunology and preclinical research.
I began my journey into programming in order to create access to tech for young Armenian women,
who do not have the opportunity or tools to learn programming or computer science.
I now hope to work in the tech industry and along with working on new, exciting technology, gain knowledge and experience,
so I can better inform young Armenian women who are also interested in technology
</p>
</div>
</div>
</div>
</div>
)
};
export default AboutContainer;
|
var http = require ('http') ;
var server = http.createServer (function (req, res)
{
res.writeHead(200);
res.end ('Salut tout le monde ! ');
}) ;
server.listen(8080);
|
var $ = require('jquery');
$(document).ready(function() {
$('#button').click(function() { alert('it works!'); });
});
|
var n=1;
var m=2;
function move(x,y){
return x+y
}
export {n,m,add}
|
{
"name": "Rialto",
"stars": 3,
"price": 1461,
"detail":{
"address": "Carrer de Ferran, 40-42, Barcelona",
"images": ["https://images.almundo.com/201/1000000/50000/48900/48852/48852_56_b.jpg",
"https://images.almundo.com/201/1000000/50000/48900/48852/48852_47_b.jpg",
"https://images.almundo.com/201/1000000/50000/48900/48852/48852_50_b.jpg",
"https://images.almundo.com/201/1000000/50000/48900/48852/48852_52_b.jpg" ],
"coordinates":{
"latitude": "41.38195781399147",
"longitude": "2.1763343999999734"
},
"description": "Te sentirás como en tu propia casa en una de las 205 habitaciones con aire acondicionado y televisor de pantalla plana. Mantén el contacto con los tuyos gracias a la conexión a Internet wifi gratis. El baño privado con ducha y bañera combinadas está provisto de artículos de higiene personal gratuitos y secador de pelo. Las comodidades incluyen teléfono y escritorio, además de un servicio de limpieza disponible todos los días."
}
}
{
"name": "NH Collection Barcelona Gran Hotel Calderón",
"stars": 5,
"price": 3060,
"detail":{
"address": "Rambla de Catalunya, 26, Barcelona",
"images": ["https://images.almundo.com/201/1000000/530000/523300/523278/523278_267_b.jpg",
"https://images.almundo.com/201/1000000/530000/523300/523278/523278_357_b.jpg",
"https://images.almundo.com/201/1000000/530000/523300/523278/523278_204_b.jpg",
"https://images.almundo.com/201/1000000/530000/523300/523278/523278_162_b.jpg",
"https://images.almundo.com/201/1000000/530000/523300/523278/523278_264_b.jpg",
"https://images.almundo.com/201/1000000/530000/523300/523278/523278_282_b.jpg",
"https://images.almundo.com/201/1000000/530000/523300/523278/523278_275_b.jpg"],
"coordinates":{
"latitude": "41.38946541399519",
"longitude": "2.1662651000000324"
},
"description": "Te sentirás como en tu propia casa en una de las 255 habitaciones con aire acondicionado, minibar y televisor de plasma. La conexión a Internet wifi gratis te mantendrá en contacto con los tuyos; también podrás ver tu programa favorito en el televisor con canales por satélite. El baño privado con bañera o ducha está provisto de artículos de higiene personal gratuitos y secador de pelo. Las comodidades incluyen caja fuerte (cabe un portátil), escritorio y teléfono."
}
}
{
"name": "Hotel Viladomat by Silken",
"stars": 3,
"price": 1564,
"detail":{
"address": "Carrer de Viladomat, 197, Barcelona",
"images": ["https://images.almundo.com/201/1000000/670000/660200/660111/2b1d89a0_b.jpg",
"https://images.almundo.com/201/1000000/670000/660200/660111/660111_38_b.jpg",
"https://images.almundo.com/201/1000000/670000/660200/660111/68ce9d4c_b.jpg",
"https://images.almundo.com/201/1000000/670000/660200/660111/660111_54_b.jpg",
"https://images.almundo.com/201/1000000/670000/660200/660111/d78a62a8_b.jpg",
"https://images.almundo.com/201/1000000/670000/660200/660111/3fd5e4c3_b.jpg"],
"coordinates":{
"latitude": "41.384364646410795",
"longitude": "2.152564574343825"
},
"description": "Te sentirás como en tu propia casa en una de las 81 habitaciones con aire acondicionado y minibar. La conexión a Internet wifi gratis te mantendrá en contacto con los tuyos; también podrás ver tu programa favorito en el televisor con canales por satélite. El baño privado con ducha y bañera combinadas está provisto de artículos de higiene personal gratuitos y secador de pelo. Las comodidades incluyen caja fuerte y escritorio, además de un servicio de limpieza disponible todos los días."
}
}
{
"name": "Acta Splendid",
"stars": 3,
"price": 2065,
"detail":{
"address": "Muntaner 2 Barcelona Spain 08, Barcelona",
"images": ["https://images.almundo.com/201/1000000/670000/662900/662802/662802_77_b.jpg",
"https://images.almundo.com/201/1000000/670000/662900/662802/662802_74_b.jpg",
"https://images.almundo.com/201/1000000/670000/662900/662802/662802_75_b.jpg",
"https://images.almundo.com/201/1000000/670000/662900/662802/662802_79_b.jpg",
"https://images.almundo.com/201/1000000/670000/662900/662802/662802_80_b.jpg",
"https://images.almundo.com/201/1000000/670000/662900/662802/662802_81_b.jpg",
"https://images.almundo.com/201/1000000/670000/662900/662802/662802_82_b.jpg",
"https://images.almundo.com/201/1000000/670000/662900/662802/662802_88_b.jpg"],
"coordinates":{
"latitude": "41.38401551399249",
"longitude": "2.163140099999964"
},
"description": "Te sentirás como en tu propia casa en una de las 40 habitaciones con aire acondicionado, minibar y televisor de plasma. La conexión a Internet wifi gratis te mantendrá en contacto con los tuyos; también podrás ver tu programa favorito en el televisor con canales por satélite. El baño privado con bañera o ducha está provisto de artículos de higiene personal gratuitos y secador de pelo. Las comodidades incluyen caja fuerte y escritorio, además de un servicio de limpieza disponible todos los días.."
}
}
{
"name": "Grupotel Gran Vía 678",
"stars": 4,
"price": 2132,
"detail":{
"address": "Gran Via de les Corts Catalanes, 678, Barcelona",
"images": ["https://images.almundo.com/201/4000000/3050000/3045800/3045791/3045791_72_b.jpg",
"https://images.almundo.com/201/4000000/3050000/3045800/3045791/3045791_73_b.jpg",
"https://images.almundo.com/201/4000000/3050000/3045800/3045791/3045791_74_b.jpg",
"https://images.almundo.com/201/4000000/3050000/3045800/3045791/3045791_75_b.jpg"],
"coordinates":{
"latitude": "41.39234401399658",
"longitude": "2.1729157500000156"
},
"description": "Te sentirás como en tu propia casa en una de las 98 habitaciones con aire acondicionado y minibar. La conexión a Internet wifi gratis te mantendrá en contacto con los tuyos; también podrás ver tu programa favorito en el televisor con canales por satélite. Las comodidades incluyen caja fuerte y escritorio, además de un servicio de limpieza disponible todos los días."
}
}
{
"name": "Mayerling Abamita Apartments",
"stars": 3,
"price": 3701,
"detail":{
"address": "Calle Ausias March, 25, Barcelona",
"images": ["https://images.almundo.com/201/14000000/13230000/13227600/13227589/13227589_17_b.jpg",
"https://images.almundo.com/201/14000000/13230000/13227600/13227589/13227589_20_b.jpg",
"https://images.almundo.com/201/14000000/13230000/13227600/13227589/13227589_14_b.jpg"],
"coordinates":{
"latitude": "41.39117831399601",
"longitude": "2.1749489999999696"
},
"description": "Te sentirás como en tu propia casa en una de las 98 habitaciones con aire acondicionado y minibar. La conexión a Internet wifi gratis te mantendrá en contacto con los tuyos; también podrás ver tu programa favorito en el televisor con canales por satélite. Las comodidades incluyen caja fuerte y escritorio, además de un servicio de limpieza disponible todos los días."
}
}
{
"name": "Onix Rambla Hotel",
"stars": 3,
"price": 2782,
"detail":{
"address": "Rambla de Catalunya, 24, Barcelona",
"images": ["https://images.almundo.com/201/2000000/1110000/1105600/1105546/1105546_108_b.jpg",
"https://images.almundo.com/201/2000000/1110000/1105600/1105546/1105546_105_b.jpg",
"https://images.almundo.com/201/2000000/1110000/1105600/1105546/1105546_106_b.jpg"],
"coordinates":{
"latitude": "41.389209513995056",
"longitude": "2.166300299999989"
},
"description": "Te sentirás como en tu propia casa en una de las 98 habitaciones con aire acondicionado y minibar. La conexión a Internet wifi gratis te mantendrá en contacto con los tuyos; también podrás ver tu programa favorito en el televisor con canales por satélite. Las comodidades incluyen caja fuerte y escritorio, además de un servicio de limpieza disponible todos los días."
}
}
{
"name": "Feetup Garden House Hostel Barcelona",
"stars": 1,
"price": 1492,
"detail":{
"address": "Carrer d'Hedilla, 58, Barcelona",
"images": ["https://images.almundo.com/201/6000000/5440000/5436700/5436626/5436626_1_b.jpg",
"https://images.almundo.com/201/6000000/5440000/5436700/5436626/5436626_10_b.jpg",
"https://images.almundo.com/201/6000000/5440000/5436700/5436626/5436626_21_b.jpg"],
"coordinates":{
"latitude": "41.43603616401814",
"longitude": "2.161292450000019"
},
"description": "Te sentirás como en tu propia casa en una de las 98 habitaciones con aire acondicionado y minibar. La conexión a Internet wifi gratis te mantendrá en contacto con los tuyos; también podrás ver tu programa favorito en el televisor con canales por satélite. Las comodidades incluyen caja fuerte y escritorio, además de un servicio de limpieza disponible todos los días."
}
}
{
"name": "Lugaris Beach - Apartments",
"stars": 4,
"price": 4061,
"detail":{
"address": "Passeig Calvell 45, Barcelona",
"images": ["https://images.almundo.com/201/5000000/4100000/4099200/4099112/4099112_17_b.jpg",
"https://images.almundo.com/201/5000000/4100000/4099200/4099112/4099112_47_b.jpg",
"https://images.almundo.com/201/5000000/4100000/4099200/4099112/4099112_18_b.jpg"],
"coordinates":{
"latitude": "41.3990452139999",
"longitude": "2.2073447000000215"
},
"description": "Te sentirás como en tu propia casa en una de las 98 habitaciones con aire acondicionado y minibar. La conexión a Internet wifi gratis te mantendrá en contacto con los tuyos; también podrás ver tu programa favorito en el televisor con canales por satélite. Las comodidades incluyen caja fuerte y escritorio, además de un servicio de limpieza disponible todos los días."
}
}
{
"name": "Sunotel Aston",
"stars": 3,
"price": 1625,
"detail":{
"address": "Carrer de Paris 101, Barcelona",
"images": ["https://images.almundo.com/201/2000000/1180000/1170100/1170099/1170099_120_b.jpg",
"https://images.almundo.com/201/2000000/1180000/1170100/1170099/1170099_56_b.jpg",
"https://images.almundo.com/201/2000000/1180000/1170100/1170099/1170099_54_b.jpg"],
"coordinates":{
"latitude": "41.38938261399516",
"longitude": "2.1474199000000453"
},
"description": "Te sentirás como en tu propia casa en una de las 98 habitaciones con aire acondicionado y minibar. La conexión a Internet wifi gratis te mantendrá en contacto con los tuyos; también podrás ver tu programa favorito en el televisor con canales por satélite. Las comodidades incluyen caja fuerte y escritorio, además de un servicio de limpieza disponible todos los días."
}
}
--------------------------------------------------
{
"name": "Hotel onix liceo",
"stars": 4,
"price": 2025,
"detail":{
"address": "Carrer de Paris 101, Barcelona",
"images": ["https://images.almundo.com/201/2000000/1180000/1170100/1170099/1170099_56_b.jpg",
"https://images.almundo.com/201/2000000/1180000/1170100/1170099/1170099_120_b.jpg",
"https://images.almundo.com/201/2000000/1180000/1170100/1170099/1170099_54_b.jpg"],
"coordinates":{
"latitude": "41.38938261399516",
"longitude": "2.1474199000000453"
},
"description": "Te sentirás como en tu propia casa en una de las 98 habitaciones con aire acondicionado y minibar. La conexión a Internet wifi gratis te mantendrá en contacto con los tuyos; también podrás ver tu programa favorito en el televisor con canales por satélite. Las comodidades incluyen caja fuerte y escritorio, además de un servicio de limpieza disponible todos los días."
}
}
{
"name": "Hotel Ciutat Vella",
"stars": 3,
"price": 1825,
"detail":{
"address": "Carrer de Paris 101, Barcelona",
"images": ["https://images.almundo.com/201/2000000/1180000/1170100/1170099/1170099_54_b.jpg",
"https://images.almundo.com/201/2000000/1180000/1170100/1170099/1170099_120_b.jpg",
"https://images.almundo.com/201/2000000/1180000/1170100/1170099/1170099_56_b.jpg" ],
"coordinates":{
"latitude": "41.38938261399516",
"longitude": "2.1474199000000453"
},
"description": "Te sentirás como en tu propia casa en una de las 98 habitaciones con aire acondicionado y minibar. La conexión a Internet wifi gratis te mantendrá en contacto con los tuyos; también podrás ver tu programa favorito en el televisor con canales por satélite. Las comodidades incluyen caja fuerte y escritorio, además de un servicio de limpieza disponible todos los días."
}
}
{
"name": "Hotel Continental Barcelona",
"stars": 5,
"price": 1025,
"detail":{
"address": "Carrer de Paris 101, Barcelona",
"images": ["https://images.almundo.com/201/2000000/1180000/1170100/1170099/1170099_120_b.jpg",
"https://images.almundo.com/201/2000000/1180000/1170100/1170099/1170099_56_b.jpg",
"https://images.almundo.com/201/2000000/1180000/1170100/1170099/1170099_54_b.jpg"],
"coordinates":{
"latitude": "41.38938261399516",
"longitude": "2.1474199000000453"
},
"description": "Te sentirás como en tu propia casa en una de las 98 habitaciones con aire acondicionado y minibar. La conexión a Internet wifi gratis te mantendrá en contacto con los tuyos; también podrás ver tu programa favorito en el televisor con canales por satélite. Las comodidades incluyen caja fuerte y escritorio, además de un servicio de limpieza disponible todos los días."
}
}
{
"name": "Albergue Studio Hostel",
"stars": 2,
"price": 1234,
"detail":{
"address": "Carrer de Paris 101, Barcelona",
"images": ["https://images.almundo.com/201/2000000/1180000/1170100/1170099/1170099_56_b.jpg",
"https://images.almundo.com/201/2000000/1180000/1170100/1170099/1170099_120_b.jpg",
"https://images.almundo.com/201/2000000/1180000/1170100/1170099/1170099_54_b.jpg"],
"coordinates":{
"latitude": "41.38938261399516",
"longitude": "2.1474199000000453"
},
"description": "Te sentirás como en tu propia casa en una de las 98 habitaciones con aire acondicionado y minibar. La conexión a Internet wifi gratis te mantendrá en contacto con los tuyos; también podrás ver tu programa favorito en el televisor con canales por satélite. Las comodidades incluyen caja fuerte y escritorio, además de un servicio de limpieza disponible todos los días."
}
}
{
"name": "AinB Picasso Corders Apartments",
"stars": 2,
"price": 1625,
"detail":{
"address": "Carrer de Paris 101, Barcelona",
"images": ["https://images.almundo.com/201/2000000/1180000/1170100/1170099/1170099_54_b.jpg",
"https://images.almundo.com/201/2000000/1180000/1170100/1170099/1170099_120_b.jpg",
"https://images.almundo.com/201/2000000/1180000/1170100/1170099/1170099_56_b.jpg"],
"coordinates":{
"latitude": "41.38938261399516",
"longitude": "2.1474199000000453"
},
"description": "Te sentirás como en tu propia casa en una de las 98 habitaciones con aire acondicionado y minibar. La conexión a Internet wifi gratis te mantendrá en contacto con los tuyos; también podrás ver tu programa favorito en el televisor con canales por satélite. Las comodidades incluyen caja fuerte y escritorio, además de un servicio de limpieza disponible todos los días."
}
}
{
"name": "Catalonia Mikado",
"stars": 3,
"price": 4353,
"detail":{
"address": "Carrer de Paris 101, Barcelona",
"images": ["https://images.almundo.com/201/2000000/1180000/1170100/1170099/1170099_120_b.jpg",
"https://images.almundo.com/201/2000000/1180000/1170100/1170099/1170099_56_b.jpg",
"https://images.almundo.com/201/2000000/1180000/1170100/1170099/1170099_54_b.jpg"],
"coordinates":{
"latitude": "41.38938261399516",
"longitude": "2.1474199000000453"
},
"description": "Te sentirás como en tu propia casa en una de las 98 habitaciones con aire acondicionado y minibar. La conexión a Internet wifi gratis te mantendrá en contacto con los tuyos; también podrás ver tu programa favorito en el televisor con canales por satélite. Las comodidades incluyen caja fuerte y escritorio, además de un servicio de limpieza disponible todos los días."
}
}
{
"name": "Hotel Actual",
"stars": 3,
"price": 1625,
"detail":{
"address": "Carrer de Paris 101, Barcelona",
"images": ["https://images.almundo.com/201/2000000/1180000/1170100/1170099/1170099_54_b.jpg",
"https://images.almundo.com/201/2000000/1180000/1170100/1170099/1170099_120_b.jpg",
"https://images.almundo.com/201/2000000/1180000/1170100/1170099/1170099_56_b.jpg"],
"coordinates":{
"latitude": "41.38938261399516",
"longitude": "2.1474199000000453"
},
"description": "Te sentirás como en tu propia casa en una de las 98 habitaciones con aire acondicionado y minibar. La conexión a Internet wifi gratis te mantendrá en contacto con los tuyos; también podrás ver tu programa favorito en el televisor con canales por satélite. Las comodidades incluyen caja fuerte y escritorio, además de un servicio de limpieza disponible todos los días."
}
}
{
"name": "Gran Hotel La Florida",
"stars": 3,
"price": 1625,
"detail":{
"address": "Carrer de Paris 101, Barcelona",
"images": ["https://images.almundo.com/201/1000000/50000/48900/48852/48852_50_b.jpg",
"https://images.almundo.com/201/2000000/1180000/1170100/1170099/1170099_56_b.jpg",
"https://images.almundo.com/201/2000000/1180000/1170100/1170099/1170099_54_b.jpg"],
"coordinates":{
"latitude": "41.38938261399516",
"longitude": "2.1474199000000453"
},
"description": "Te sentirás como en tu propia casa en una de las 98 habitaciones con aire acondicionado y minibar. La conexión a Internet wifi gratis te mantendrá en contacto con los tuyos; también podrás ver tu programa favorito en el televisor con canales por satélite. Las comodidades incluyen caja fuerte y escritorio, además de un servicio de limpieza disponible todos los días."
}
}
{
"name": "Hotel EuroPark",
"stars": 3,
"price": 1625,
"detail":{
"address": "Carrer de Paris 101, Barcelona",
"images": ["https://images.almundo.com/201/1000000/920000/913800/913726/913726_208_b.jpg",
"https://images.almundo.com/201/2000000/1180000/1170100/1170099/1170099_56_b.jpg",
"https://images.almundo.com/201/2000000/1180000/1170100/1170099/1170099_54_b.jpg"],
"coordinates":{
"latitude": "41.38938261399516",
"longitude": "2.1474199000000453"
},
"description": "Te sentirás como en tu propia casa en una de las 98 habitaciones con aire acondicionado y minibar. La conexión a Internet wifi gratis te mantendrá en contacto con los tuyos; también podrás ver tu programa favorito en el televisor con canales por satélite. Las comodidades incluyen caja fuerte y escritorio, además de un servicio de limpieza disponible todos los días."
}
}
{
"name": "Gran Hotel La Florida",
"stars": 3,
"price": 1625,
"detail":{
"address": "Carrer de Paris 101, Barcelona",
"images": ["https://images.almundo.com/201/1000000/920000/913800/913726/913726_169_b.jpg",
"https://images.almundo.com/201/2000000/1180000/1170100/1170099/1170099_56_b.jpg",
"https://images.almundo.com/201/2000000/1180000/1170100/1170099/1170099_54_b.jpg"],
"coordinates":{
"latitude": "41.38938261399516",
"longitude": "2.1474199000000453"
},
"description": "Te sentirás como en tu propia casa en una de las 98 habitaciones con aire acondicionado y minibar. La conexión a Internet wifi gratis te mantendrá en contacto con los tuyos; también podrás ver tu programa favorito en el televisor con canales por satélite. Las comodidades incluyen caja fuerte y escritorio, además de un servicio de limpieza disponible todos los días."
}
}
{
"name": "Hotel Lleó",
"stars": 3,
"price": 1625,
"detail":{
"address": "Carrer de Paris 101, Barcelona",
"images": ["https://images.almundo.com/201/1000000/920000/913800/913726/913726_42_b.jpg",
"https://images.almundo.com/201/2000000/1180000/1170100/1170099/1170099_56_b.jpg",
"https://images.almundo.com/201/2000000/1180000/1170100/1170099/1170099_54_b.jpg"],
"coordinates":{
"latitude": "41.38938261399516",
"longitude": "2.1474199000000453"
},
"description": "Te sentirás como en tu propia casa en una de las 98 habitaciones con aire acondicionado y minibar. La conexión a Internet wifi gratis te mantendrá en contacto con los tuyos; también podrás ver tu programa favorito en el televisor con canales por satélite. Las comodidades incluyen caja fuerte y escritorio, además de un servicio de limpieza disponible todos los días."
}
}
{
"name": "Hotel Grums Barcelona",
"stars": 3,
"price": 1625,
"detail":{
"address": "Carrer de Paris 101, Barcelona",
"images": ["https://images.almundo.com/201/1000000/920000/913800/913726/913726_63_b.jpg",
"https://images.almundo.com/201/2000000/1180000/1170100/1170099/1170099_56_b.jpg",
"https://images.almundo.com/201/2000000/1180000/1170100/1170099/1170099_54_b.jpg"],
"coordinates":{
"latitude": "41.38938261399516",
"longitude": "2.1474199000000453"
},
"description": "Te sentirás como en tu propia casa en una de las 98 habitaciones con aire acondicionado y minibar. La conexión a Internet wifi gratis te mantendrá en contacto con los tuyos; también podrás ver tu programa favorito en el televisor con canales por satélite. Las comodidades incluyen caja fuerte y escritorio, además de un servicio de limpieza disponible todos los días."
}
}
{
"name": "Cram Hotel",
"stars": 3,
"price": 1625,
"detail":{
"address": "Carrer de Paris 101, Barcelona",
"images": ["https://images.almundo.com/201/1000000/920000/913800/913726/913726_76_b.jpg",
"https://images.almundo.com/201/2000000/1180000/1170100/1170099/1170099_56_b.jpg",
"https://images.almundo.com/201/2000000/1180000/1170100/1170099/1170099_54_b.jpg"],
"coordinates":{
"latitude": "41.38938261399516",
"longitude": "2.1474199000000453"
},
"description": "Te sentirás como en tu propia casa en una de las 98 habitaciones con aire acondicionado y minibar. La conexión a Internet wifi gratis te mantendrá en contacto con los tuyos; también podrás ver tu programa favorito en el televisor con canales por satélite. Las comodidades incluyen caja fuerte y escritorio, además de un servicio de limpieza disponible todos los días."
}
}
{
"name": "B-Hotel",
"stars": 3,
"price": 1625,
"detail":{
"address": "Carrer de Paris 101, Barcelona",
"images": ["https://images.almundo.com/201/1000000/920000/913800/913726/913726_85_b.jpg",
"https://images.almundo.com/201/2000000/1180000/1170100/1170099/1170099_56_b.jpg",
"https://images.almundo.com/201/2000000/1180000/1170100/1170099/1170099_54_b.jpg"],
"coordinates":{
"latitude": "41.38938261399516",
"longitude": "2.1474199000000453"
},
"description": "Te sentirás como en tu propia casa en una de las 98 habitaciones con aire acondicionado y minibar. La conexión a Internet wifi gratis te mantendrá en contacto con los tuyos; también podrás ver tu programa favorito en el televisor con canales por satélite. Las comodidades incluyen caja fuerte y escritorio, además de un servicio de limpieza disponible todos los días."
}
}
{
"name": "Gran Derby Suite Hotel",
"stars": 3,
"price": 1625,
"detail":{
"address": "Carrer de Paris 101, Barcelona",
"images": ["https://images.almundo.com/201/1000000/920000/913800/913726/913726_97_b.jpg",
"https://images.almundo.com/201/2000000/1180000/1170100/1170099/1170099_56_b.jpg",
"https://images.almundo.com/201/2000000/1180000/1170100/1170099/1170099_54_b.jpg"],
"coordinates":{
"latitude": "41.38938261399516",
"longitude": "2.1474199000000453"
},
"description": "Te sentirás como en tu propia casa en una de las 98 habitaciones con aire acondicionado y minibar. La conexión a Internet wifi gratis te mantendrá en contacto con los tuyos; también podrás ver tu programa favorito en el televisor con canales por satélite. Las comodidades incluyen caja fuerte y escritorio, además de un servicio de limpieza disponible todos los días."
}
}
|
import React from "react";
import ToggleButton from "react-bootstrap/ToggleButton";
import ButtonGroup from "react-bootstrap/ButtonGroup";
import {Button} from 'react-bootstrap';
import "bootstrap/dist/css/bootstrap.min.css";
import './help.css'
function Help({ updateStep, three, updateThree }) {
function changeThree(newThree) {
updateThree(newThree);
window.localStorage.setItem("three", newThree);
}
return (
<div className="Help">
<br />
<h1>Are you stuck? Do you need help?</h1>
<br />
<h2>Remember to ask for help from a mentor or a Senior Engineer if you are blocked.</h2>
<br></br>
<Button variant="primary" onClick={() => changeThree(1)}>Yes</Button>
<Button variant="primary" onClick={() => changeThree(0)}>No</Button>
<br></br>
<br></br>
<a href="/done"><div className="button_1 button_2">Done </div></a>
</div>
);
}
export default Help;
|
/**
* Created by Hild Franck on 7/8/2015.
*/
const DIRX = 0;
const DIRY = 1;
Image.prototype.createTintCanvas = function(width, height){
var tintCanvas = document.createElement('canvas');
tintCanvas.width = width;
tintCanvas.height = height;
return tintCanvas;
};
Image.prototype.tintImg = function(color, xStart, yStart, width, height){
xStart = xStart || 0;
yStart = yStart || 0;
width = width || 32;
height = height || 32;
var colorRatio = 255/(color.red + color.green + color.blue);
var tintCanvas = this.createTintCanvas(width, height);
var tintContext = tintCanvas.getContext('2d');
tintContext.drawImage(this, xStart, yStart, width, height, 0, 0, width, height);
var pixelData = tintContext.getImageData(0, 0, width, height);
for(var j = 0; j < height*width*4; j+=width*4) {
for (var i = 0; i < width * 4; i += 4) {
pixelData.data[i+j] += colorRatio*color.red;
pixelData.data[i+j+1] += colorRatio*color.green;
pixelData.data[i+j+2] += colorRatio*color.blue;
}
}
tintContext.putImageData(pixelData,0,0);
return tintCanvas.toDataURL();
};
function Sprite(imgPath, _width, _height, _sprite, _nbrFrame, _xSpot, _ySpot){
this.image = new Image();
this.tintImage = new Image();
this.image.src = imgPath;
this.spriteInd = _sprite;
this.animInd = 0;
this.nbrFrame = _nbrFrame || this.image.width / 32;
this.frame = 0;
this.width = _width;
this.height = _height;
this.widthMod = 1;
this.xSpot = _xSpot || Math.floor(this.width/2);
this.ySpot = _ySpot || Math.floor(this.height/2);
this.isTint = false;
this.rotation = false;
}
function Entity(){}
Entity.prototype.draw = function(sprite, sprIndX, sprIndY){
game.context.drawImage(sprite.image, sprIndX * 32 , sprIndY * 32, 32, 32, this.x - sprite.xSpot + game.xOffSet, this.y - sprite.ySpot + game.yOffSet, 32, 32);
};
Entity.prototype.animate = function(sprite, animSpeed){
animSpeed = animSpeed || 1;
var x = this.x;
var y = this.y;
if(sprite.rotation){
game.context.translate(this.x+game.xOffSet, this.y+game.yOffSet);
game.context.rotate(sprite.angle);
this.x = -game.xOffSet;
this.y = -game.yOffSet;
}
if(!(sprite.isTint))
this.draw(sprite, sprite.frame + 3 * sprite.spriteInd, sprite.animInd, this.x, this.y);
else{
this.sprite.tintImage.src = this.sprite.image.tintImg(new ColorRGB(255, 0, 0), (sprite.frame + 3 * sprite.spriteInd)*32, sprite.animInd*32);
game.context.drawImage(sprite.tintImage, 0, 0, 32, 32, this.x - sprite.xSpot + game.xOffSet, this.y - sprite.ySpot + game.yOffSet, 32, 32);
}
if(sprite.rotation){
this.x = x;
this.y = y;
game.context.rotate(-sprite.angle);
game.context.translate(-(this.x+game.xOffSet), -(this.y+game.yOffSet));
sprite.rotation = false;
}
this.countDraw++;
if (this.countDraw >= Math.round((game.fps/sprite.nbrFrame)/animSpeed) * sprite.nbrFrame)
this.countDraw = 0;
if (this.countDraw % Math.round((game.fps/sprite.nbrFrame) / animSpeed) == 0)
sprite.frame++;
if (sprite.frame >= sprite.nbrFrame)
sprite.frame = 0;
};
Entity.prototype.rotate = function(angle){
this.sprite.rotation = true;
this.sprite.angle = angle;
};
Entity.prototype.death = function(){
this.sprite.widthMod -= 0.02;
this.sprite.tintImage.src = this.sprite.image.tintImg(new ColorRGB(255, 0, 0), (this.sprite.frame + 3 * this.sprite.spriteInd)*32, this.sprite.animInd*32);
game.context.drawImage(this.sprite.tintImage, 0, 0, 32, 32, this.x - this.sprite.xSpot * this.sprite.widthMod + game.xOffSet, this.y - this.sprite.ySpot* (1/this.sprite.widthMod) + game.yOffSet, 32 * this.sprite.widthMod, 32);
if(this.sprite.widthMod <= 0)
this.dead = true;
};
Entity.prototype.takeDmg = function(dmg){
game.createTxtFx(this, dmg, 15, false, false);
this.sprite.isTint = true;
};
Entity.prototype.setAnimInd = function(){
if (this.x < this.xPrev)
return 1;
if (this.x > this.xPrev)
return 2;
if (this.y > this.yPrev)
return 3;
if (this.y < this.yPrev)
return 0;
};
function Enemy(_x, _y, _speed, _dirX, _id){
this.type = 'enemy';
this.xPrev = _x;
this.yPrev = _y;
this.x = _x;
this.y = _y;
this.speed = _speed;
this.dirX = _dirX;
this.countDraw = 0;
this.sprite = new Sprite("resources/monster2.png", 32, 32, 0, 3);
this.dying = false;
this.dead = false;
this.id = _id;
this.countTint = 0;
this.display = function () {
if(!this.dying) {
var time = new Date();
this.x += (((game.fps / 1000) * this.speed) * (time.getTime() - game.objects.servTime)) * this.dirX;
this.sprite.animInd = this.setAnimInd();
this.animate(this.sprite, 1.5);
}
else
this.death();
this.xPrev = this.x;
if(this.sprite.isTint)
this.countTint++;
if(this.countTint == 6){
this.sprite.isTint = false;
this.countTint = 0;
}
return true;
};
}
Enemy.prototype = Object.create(Entity.prototype);
Enemy.prototype.constructor = Enemy;
function Player(_x, _y, _speed, _date, _key, sprite){
this.type = 'player';
this.xPrev = _x;
this.yPrev = _y;
this.x = _x;
this.y = _y;
this.speed = _speed;
this.countDraw = 0;
this.key = _key;
this.time = (new Date()).getTime();
this.lastTime = _date;
this.sprite = new Sprite("resources/Actor1.png", 32, 32, sprite, 3);
this.display = function () {
this.time = (new Date()).getTime();
if(this.key != -1) {
this.x += 0.06 * this.speed * player.dir[this.key][DIRX] * (this.time - this.lastTime);
this.y += 0.06 * this.speed * player.dir[this.key][DIRY] * (this.time - this.lastTime);
this.sprite.animInd = this.setAnimInd();
}
this.animate();
this.lastTime = this.time;
return true;
};
}
Player.prototype = Object.create(Entity.prototype);
Player.prototype.constructor = Player;
function SpriteFx(_x, _y,_sprite, _nbrFrame, _animSpeed, _loop, _linker, _isLinked){
this.x = _x;
this.y = _y;
this.rot = Math.random() * (Math.PI * 2);
this.animSpeed = _animSpeed || 1;
this.looped = _loop || false;
this.creator = _linker || undefined;
this.isLinked = _isLinked || false;
this.stop = false;
this.sprite = new Sprite("resources/graphics/fx/" + _sprite + ".png", 32, 32, 0, _nbrFrame);
this.countDraw = 0;
/**
* Dessine l'effet spécial
*/
this.display = function(){
if(this.isLinked && this.creator !== "undefined"){
this.x = this.creator.x;
this.y = this.creator.y + 4;
}
this.rotate(this.rot);
this.animate(this.sprite, this.animSpeed);
if((this.sprite.frame >= this.sprite.nbrFrame - 1 && this.countDraw == (game.fps/this.animSpeed) - 1) || this.stop ){
if(!this.looped || this.stop) {
game.objects.entities.splice(game.objects.entities.indexOf(this), 1);
return false;
}
else{
this.frame = 0;
this.sprInd = 0;
this.countDraw = 0;
return true;
}
}
else
return true;
}
}
SpriteFx.prototype = Object.create(Entity.prototype);
SpriteFx.prototype.constructor = SpriteFx;
function ColorRGB(_red, _green, _blue, _alpha){
this.red = _red;
this.green = _green;
this.blue = _blue;
this.alpha = _alpha || 1
}
ColorRGB.prototype.toHex = function(){
return new ColorHex(this.red.toString(16) + this.green.toString(16) + this.blue.toString(16), this.alpha);
};
function ColorHex(_hex, _alpha){
this.hex = _hex;
this.alpha = _alpha;
}
ColorHex.prototype.getColor = function(){
return this.hex;
};
ColorHex.prototype.toDec = function(){
return new ColorRGB(parseInt(this.hex.splice(0,3), 16), parseInt(this.hex.splice(3,6), 16), parseInt(this.hex.splice(6,9), 16), this.alpha);
};
/**
* L'objet du jeu
* @class
* @property {HTMLCanvasElement} canvas Le canvas dans lequel le jeu tourne
* @property {CanvasRenderingContext2D} context Spécification des méthodes et propriétés du canvas
* @property {Number} fps Nombre de frames par seconde
* @property {Number} xOffSet Nombre de pixel de décalage entre l'origine du dessin et l'origine du canvas sur l'axe x
* @property {Number} yOffSet Nombre de pixel de décalage entre l'origine du dessin et l'origine du canvas sur l'axe y
*/
var game = {
/** @lends game */
canvas: document.getElementById("canvas"),
context: canvas.getContext("2d"),
timeTest: (new Date()).getTime(),
lastTimeTest: 0,
lastUpdt: 0,
fps: 60,
xOffSet: 0,
yOffSet: 0,
/**
* Gère les objets dans le jeu
* @class
*/
objects:{
entities: [],
gui: [],
servTime: 0,
/**
* Fonction d'ajout d'un objet dans un tableau d'objets
* @param {Array} arr Le tableau dans lequel l'objet est placé
* @param {Object} obj L'objet à placer
*/
add: function(arr, obj){
arr.push(obj);
},
/**
* Fonction qui rafraichi une liste d'objets à afficher
* @param {Object} data Les données serveur à traiter
*/
refresh: function(data){
this.servTime = data.servData.date;
data.servData.fx.forEach(function(element){
game.createSpriteFx(element.x, element.y, element.graphic, 3, 5);
});
data.servData.enemies.forEach(function(element){
for (var i = 0; i < game.objects.entities.length; i++){
if (element.$loki === game.objects.entities[i].id && game.objects.entities[i].type === 'enemy'){
if (!(element.hit === null) && game.objects.entities[i].dying == false)
game.objects.entities[i].takeDmg(element.hit.damage);
if(!element.dead) {
game.objects.entities[i].y = element.y;
game.objects.entities[i].x = element.x;
game.objects.entities[i].dirX = element.dirX;
}
else {
game.objects.entities[i].dying = true;
if(game.objects.entities[i].dead) {
game.objects.entities.splice(i, 1);
i--;
}
}
break;
}
else if(element.$loki === undefined)
break;
}
if(i == game.objects.entities.length && !element.dead) {
game.objects.entities.push(new Enemy(element.x, element.y, element.speed, element.dirX, element.$loki));
}
});
data.servData.players.forEach(function(element){
for (var i = 0; i < game.objects.entities.length; i++) {
if (element.$loki === game.objects.entities[i].$loki && game.objects.entities[i].type === 'player' && element.$loki !== player.id) {
if(game.objects.entities[i].key == element.key)
break;
else{
game.objects.entities[i].key = element.key;
}
break;
}
}
if (i == game.objects.entities.length && element.$loki !== player.id) {
game.objects.entities.push(new Player(element.x, element.y, element.speed, element.date, element.key));
}
});
if(data.plyData.level.length != 0) {
game.createTxtFx({
x: game.canvas.width / 2,
y: game.canvas.height - 100
}, (data.plyData.level.length) + "Level up !", 30, true, true);
for(var i = 0; i < data.plyData.level.length; i++)
game.createTxtFx({
x: game.canvas.width / 2,
y: game.canvas.height - 75
}, data.plyData.level[i] + " gain !", 30, true, true);
}
if(player.currentHp < data.plyData.data.currHp)
game.createTxtFx(player, "+" + (data.plyData.data.currHp - player.currentHp), 30, true, true);
game.objects.arrange();
player.currentStm = data.plyData.data.currentStm;
player.currentHp = data.plyData.data.currHp;
player.currXp = data.plyData.data.currXp;
player.maxXp = data.plyData.data.maxXp;
},
/**
* Fonction qui tri les objets selon leur variable y
*/
arrange: function(){
game.objects.entities.sort(function(a, b){
if(a.y < b.y)
return -1;
if(a.y > b.y)
return 1;
return 0;
});
}
},
/**
* L'objet de la carte
* @class
* @property {Object} tileSheet Contient le fichier du layout de la map
* @property {Number} height Hauteur de la map (nombre de tiles)
* @property {Number} width Largeur de la map (nombre de tiles)
*/
map:{
tileSheet: new Image(),
height: 10,
width: 10,
/**
* Fonction qui initialise la map
* @param {Object} tileSheetFile Le fichier de tiles à utiliser
* @param {Number} [_width=10] Largeur de la map
* @param {Number} [_height=10] Hauteur de la map
*/
init: function(tileSheetFile, _width, _height){
this.tileSheet.src = "resources/graphics/" + tileSheetFile;
if(_width !== undefined)
this.width = _width;
if(_height !== undefined)
this.height = _height;
},
/**
* Fonction qui dessine une tile
* @param x Coordonnée x de la tile sur le tilesheet
* @param y Coordonnée y de la tile sur le tilesheet
*/
dispTile: function(x, y){
game.context.drawImage(this.tileSheet, 0, 0, 32, 32, x, y, 32, 32);
},
/**
* Fonction qui dessine la map
*/
drawMap: function(){
for (var i = 0; i < this.width; i++) {
for (var j = 0; j < this.height; j++) {
this.dispTile(32 * i + game.xOffSet, 32 * j + game.yOffSet);
}
}
}
},
/**
* Fonction qui initialise le jeu
*/
init: function(){
this.map.init("Outside_A2.png");
this.addListeners();
},
/**
* Fonction qui centre la caméra sur un objet
* @param obj L'objet sur lequel la caméra sera centrée
* @param pVwWdtOffset La largeur à partir de laquelle la caméra suit l'objet
* @param pVwHgtOffset La hauteur à partir de laquelle la caméra suit l'objet
*/
portview: function(obj, pVwWdtOffset, pVwHgtOffset){
if(obj.x + this.xOffSet > this.canvas.width - pVwWdtOffset)
this.xOffSet += (this.canvas.width - pVwWdtOffset) - (obj.x + this.xOffSet);
if(obj.x + this.xOffSet < 0 + pVwWdtOffset)
this.xOffSet += pVwWdtOffset - (obj.x + this.xOffSet);
if(obj.y + this.yOffSet > this.canvas.height - pVwHgtOffset)
this.yOffSet += (canvas.height - pVwHgtOffset) - (obj.y + this.yOffSet);
if(obj.y + this.yOffSet < 0 + pVwWdtOffset)
this.yOffSet += pVwHgtOffset - (obj.y + this.yOffSet);
},
/**
* Ajoute les gestionnaires d'évènement
*/
addListeners: function(){
addEventListener("keydown", function(event) {
if (event.keyCode == 68)
player.rightSwitch = true;
if(event.keyCode == 81)
player.leftSwitch = true;
if(event.keyCode == 90)
player.upSwitch = true;
if(event.keyCode == 83)
player.downSwitch = true;
if(event.keyCode == 100) {
if(!player.attackSwitch)
player.attackStart = (new Date()).getTime();
player.attackSwitch = true;
}
if(event.keyCode == 104)
player.concentrate();
}, true);
addEventListener("keyup", function(event){
if(event.keyCode == 68)
player.rightSwitch = false;
if(event.keyCode == 81)
player.leftSwitch = false;
if(event.keyCode == 90)
player.upSwitch = false;
if(event.keyCode == 83)
player.downSwitch = false;
if(event.keyCode == 100)
player.attack("attackOne");
if(event.keyCode == 104){
player.conc.stop = true;
player.conc = null;
}
}, true);
socket.on("message", function(message){
game.objects.refresh(message);
});
socket.on("servData", function(servData){
player.x = servData.xPlayer;
player.y = servData.yPlayer;
player.key.id = servData.dirPlayer;
player.currentHp = servData.hlthPlayer;
player.currentStm = servData.stmnPlayer;
player.currXp = servData.xpPlayer;
player.id = servData.idPlayer;
player.sprite = new Sprite("resources/graphics/Actor1.png", 32, 32, 1, 3);
player.chargedTime = servData.chrgdTmPlayer;
});
},
/**
* Dessine les objets listés
*/
drawObjects: function(){
for(var i = 0; i < game.objects.entities.length; i++){
if(!game.objects.entities[i].display())
i--;
}
for(i = 0; i < game.objects.gui.length; i++){
if(!game.objects.gui[i].display())
i--;
}
},
/**
* Fonction permettant d'écirire du texte à l'écran
* @param {String} text Le texte à afficher
* @param {Number} x La coordonnée x de l'affichage
* @param {Number} y La coordonnée x de l'affichage
* @param {String} [color="black"] La couleur du texte
* @param {Number} [opacity=1] La transparence du texte
* @param {Number} [size=10] La taille de la police
* @param {String} [align="left"] Le placement du texte
* @param {Boolean} [isStatic=false] Défini si le texte suis la est fixe sur l'affichage ou non
*/
writeText: function(text, x, y, color, opacity, size, align, isStatic){
this.context.font = typeof size !== "undefined" ? size.toString() + "px sans-serif" : "10px sans-serif";
this.context.textAlign = align || "left";
this.context.fillStyle = color || "white";
this.context.globalAlpha = opacity || 1;
isStatic = isStatic || false;
this.context.strokeStyle = "black";
this.context.lineWidth = 0.5;
if(isStatic) {
this.context.fillText(text, x, y);
this.context.strokeText(text, x, y);
}
else {
this.context.fillText(text, x + game.xOffSet, y + game.yOffSet);
this.context.strokeText(text, x + game.xOffSet, y + game.yOffSet);
}
this.context.globalAlpha = 1;
this.context.lineWidth = 2;
},
/**
* Constructeur d'un objet de texte spécial
* @param {Object} _creator L'objet à l'origine de la création du texte
* @param {String} _text Le texte à afficher
* @constructor
*/
TextFx: function(_creator, _text, size, _persistence, _isStatic){
this.creator = _creator;
this.text = _text;
this.persistence = _persistence || false;
this.isStatic = _isStatic || false;
this.yAnim = 0;
this.x = this.creator.x;
this.y = this.creator.y - 20;
this.opacity = 1;
this.persCnter = 0;
/**
* Dessine le texte
* @returns {Boolean} Si l'objet est encore dans le tableau
* @instance
*/
this.display = function(){
if(this.opacity > 0){
game.writeText(this.text,this.x,this.y - this.yAnim, "red", this.opacity, size, "center", this.isStatic);
if(!this.persistence)
this.opacity -= 0.03;
else
this.persCnter++;
if (this.persCnter < 20)
this.yAnim += 1;
if (this.persCnter == 80)
this.persistence = false;
return true;
}
else {
game.objects.gui.splice(game.objects.gui.indexOf(this), 1);
return false;
}
}
},
/**
* Fonction qui permet de créer un objet de texte spécial
* @param {Object} creator Le créateur du texte
* @param {String} text Le texte à afficher
*/
createTxtFx: function(creator, text,size, persistence, isStatic){
game.objects.gui.push(new this.TextFx(creator, text, size, persistence, isStatic));
},
createSpriteFx: function(x, y, sprite, nbrFrame, animSpeed, loop, linker, isLinked){
var ind = game.objects.entities.push(new SpriteFx(x, y, sprite, nbrFrame, animSpeed, loop, linker, isLinked));
return game.objects.entities[ind - 1];
},
/**
* Fonction lancée à chaque frame
*/
update: function(){
this.context.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.map.drawMap();
player.update();
socket.emit('message',{
x: player.x,
y: player.y,
dirX: player.dirX,
dirY: player.dirY,
concentrate: player.conc !== null
});
this.portview(player,100,100);
game.drawObjects();
player.drawLife();
if(!socket.connected){
this.context.font = "20px Arial";
this.context.fillStyle = "red";
this.context.textAlign = "center";
this.context.fillText("Connexion en cours...", this.canvas.width/2, this.canvas.height/2)
}
}
};
/**
* L'objet du joueur
* @class
* @property {Object} spriteSheet Contient le fichier de sprites du personnage
* @property {Number} countDraw Compte le nombre de frame
* @property {Number} frame Frame de l'animation rn cours
* @property {Number} nbrFrame Nombre de frame dans une animation
* @property {Number} sprite Origine du spriteSheet du personnage
* @property {Number} sprInd Contient le fichier de sprites du personnage
* @property {Number} heigth Hauteur d'un sprite en pixel
* @property {Number} width Largeur d'un sprite en pixel
* @property {Number} x La coordonnée x du personnage
* @property {Number} y La coordonnée y du personnage
* @property {Number} xPrev La coordonnée y du personnage à la frame précédente
* @property {Number} yPrev La coordonnée y du personnage à la frame précédente
* @property {Number} xSpot La coordonnée x de l'origine du dessin
* @property {Number} ySpot La coordonnée y de l'origine du dessin
* @property {Number} speed La vitesse du personnage en pixel
* @property {Number} maxHp Le nombre de point de vie maximum pour le personnage
* @property {Number} currentHp Le nombre de points de vie actuel du personnage
*/
var player = {
spriteSheet: new Image(),
sprite: null,
countDraw: 0,
dirX: 0,
dirY: 1,
dir: [
[0,1],
[-1,0],
[1,0],
[0,-1]
],
key: {id: -1, date: 0},
prevKey: {id: -1, date: 0},
x: 150,
y: 150,
xPrev: 0,
yPrev: 0,
speed: 4,
maxHp: 10,
currentHp: 10,
maxStm: 10,
currentStm: 10,
maxXp: 20,
currXp: 0,
conc: null,
attackStart: 0,
keys: 0,
attackSwitch: false,
rightSwitch: false,
leftSwitch: false,
upSwitch: false,
downSwitch: false,
arrTest: [],
arrTestTwo: [],
lastKey: 0,
testKey: 0,
sumX :0,
loop: 0,
chargedTime: 350,
charge: 0,
/**
* Fonction d'initialisation du personnage
* @param {Number} [_sprite=1] Sprite du personnage
* @param {Number} [xStart=10] Coordonnée x de départ du personnage
* @param {Number} [yStart=10] Coordonnée y de départ du personnage
*/
init: function(_sprite, xStart, yStart){
this.x = xStart || this.x;
this.y = yStart || this.y;
this.sprite = new Sprite("resources/graphics/Actor1.png", 32, 32, _sprite, 3);
game.objects.add(game.objects.entities, this);
},
/**
* Gère l'attaque du personnage
*/
attack: function(){
this.attackSwitch = false;
console.log((new Date()).getTime() - this.attackStart);
socket.emit('attack', (new Date()).getTime() - this.attackStart);
this.attackStart = 0;
this.charge = 0;
},
concentrate: function(){
if(this.conc === null)
this.conc = game.createSpriteFx(player.x, player.y, "Special10", 7, 1, true, player, true);
},
draw: Entity.prototype.draw,
animate: Entity.prototype.animate,
setKey: function(){
if(this.rightSwitch)
return 2;
if(this.leftSwitch)
return 1;
if(this.upSwitch)
return 3;
if(this.downSwitch)
return 0;
return -1;
},
drawBar: function(color, value, text, x, y){
game.context.strokeRect(x, y, 101, 21);
game.context.fillStyle = color.getColor();
game.context.fillRect(x+1, y+1, value * 99, 19);
game.writeText(text, x + 110, y + 15, color.getColor(), 1, 12, "left", true);
},
display: function(){
this.animate(this.sprite, 2);
return true;
},
/**
* Dessine la vie du joueur
*/
drawLife: function(){
this.drawBar((new ColorHex("#2ecc71", 1)), this.currentHp / this.maxHp, "HP", 5, 5);
this.drawBar((new ColorHex("#e74c3c", 1)), this.currentStm / this.maxStm, "Stamina", 5, 31);
this.drawBar((new ColorHex("#3498db", 1)), this.charge / this.chargedTime, "Charge", 5, 57);
game.context.strokeRect(20,game.canvas.height - 20,game.canvas.width - 40,16);
game.context.fillStyle = "#CC9900";
game.context.fillRect(21,game.canvas.height - 19,this.currXp / this.maxXp * (game.canvas.width - 42), 14);
game.writeText("XP",game.canvas.width/2,game.canvas.height - 25,"CC9900",1, 15,"center", true);
},
/**
* Fonction de mise à jour du personnage à chaque frame
*/
update: function(){
this.prevKey.id = this.key.id;
this.xPrev = this.x;
this.yPrev = this.y;
this.key.id = this.setKey();
if(this.attackStart != 0)
this.charge = (this.charge >= this.chargedTime) ? this.chargedTime : ((new Date()).getTime() - this.attackStart);
game.timeTest = (new Date()).getTime();
if((this.rightSwitch || this.leftSwitch || this.upSwitch || this.downSwitch)){
game.lastTimeTest = game.lastUpdt;
this.x += 0.06 * this.speed * this.dir[this.key.id][DIRX] * (game.timeTest - game.lastTimeTest);
this.y += 0.06 * this.speed * this.dir[this.key.id][DIRY] * (game.timeTest - game.lastTimeTest);
this.x = Math.round(this.x);
this.y = Math.round(this.y);
this.sprite.animInd = this.key.id;
}
this.key.date = game.lastUpdt;
if(this.key.id != this.prevKey.id)
socket.emit("movement", this.key);
this.dirX = this.dir[this.sprite.animInd][DIRX];
this.dirY = this.dir[this.sprite.animInd][DIRY];
game.lastUpdt = game.timeTest;
if(this.x == this.xPrev && this.y == this.yPrev){
this.sprite.frame = 1;
this.countDraw = 0;
}
}
};
//--- Initialisation ---
game.init();
player.init(1);
//--- Game loop ---
setInterval(function(){
debug.clear();
game.update();
debug.monitor("x: ", player.x);
debug.monitor("y: ", player.y);
debug.monitor("dirX: ", player.dirX);
debug.monitor("dirY: ", player.dirY);
debug.show();
}, 1000/game.fps);
|
class CreditCardService {
charge() {}
}
const chargeOrder = (orderId, creditCardToken) => {
const creditCardCompanyResponse = new CreditCardService().charge(orderId, creditCardToken);
if (!creditCardCompanyResponse) {
throw {message: 'Invalid response from credit card company'};
}
};
chargeOrder(1, 'dsfsd0');
|
'use strict';
/**
* Ressources partagées disponibles dans chaque contrôleur
*/
app.service('FrontSession', function () {
// private
var operation = {};
// public
return {
'getOperation': function () {
return operation;
},
'setOperation': function(value) {
operation = value;
}
}
});
|
// Function 1
function doubleNumbers(arr) {
return arr.map( x => x * 2);
}
console.log(doubleNumbers([2, 5, 100]));
//Function 2
function stringItUp(arr) {
return arr.map( x => x.toString())
}
console.log(stringItUp([2, 5, 100]));
//Function 3
function capitalizeNames(arr) {
return arr = arr.map(x => x.toLowerCase().replace(/\D/, c => c.toUpperCase()));
}
console.log(capitalizeNames(["john", "JACOB", "jinGleHeimer", "schmidt"]));
//Fucntion 4
function namesOnly(arr){
return arr.map(x => x.name)
}
console.log(namesOnly([
{
name: "Angelina Jolie",
age: 80
},
{
name: "Eric Jones",
age: 2
},
{
name: "Paris Hilton",
age: 5
},
{
name: "Kayne West",
age: 16
},
{
name: "Bob Ziroll",
age: 100
}
]) )
//Function 5
function makeStrings(arr){
return arr.map(function(x) {
if (x.age < 18) {
return x.name + " is under age!!"
} else {
return x.name + " can go to The Matrix"
}
})
}
console.log(makeStrings([
{
name: "Angelina Jolie",
age: 80
},
{
name: "Eric Jones",
age: 2
},
{
name: "Paris Hilton",
age: 5
},
{
name: "Kayne West",
age: 16
},
{
name: "Bob Ziroll",
age: 100
}
]));
//FUNCTION 6
function readyToPutInTheDOM(arr){
return arr.map(x => "<h1>" + x.name + "</h1><h2>" + x.age + "</h2>")
}
console.log(readyToPutInTheDOM([
{
name: "Angelina Jolie",
age: 80
},
{
name: "Eric Jones",
age: 2
},
{
name: "Paris Hilton",
age: 5
},
{
name: "Kayne West",
age: 16
},
{
name: "Bob Ziroll",
age: 100
}
]) )
|
import React, { Component } from 'react';
import { Form, Icon, Button } from 'antd';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { createForm, formShape, createFormField } from 'rc-form';
import * as CounterActions from '../actions';
import MiniForm from './Form';
// จงประยุก Form_ ให้เข้ากับ Redux form
// import MiniForm from './Form_';
const FormItem = Form.Item;
class DynamicFieldSet extends Component {
static propTypes = {
form: formShape,
}
handleSubmit = (e) => {
e.preventDefault();
this.props.form.validateFieldsAndScroll((err, values) => {
if (!err) {
console.log('Received values of form: ', values);
}
});
}
render() {
const { forms } = this.props.multiForm
const formItemLayout = {
labelCol: {
xs: { span: 24 },
sm: { span: 4 },
},
wrapperCol: {
xs: { span: 24 },
sm: { span: 20 },
},
};
const formItemLayoutWithOutLabel = {
wrapperCol: {
xs: { span: 24, offset: 0 },
sm: { span: 20, offset: 4 },
},
};
return (
<Form onSubmit={this.handleSubmit}>
{ forms.map(
(item, index) => <MiniForm key={index} index={item.key} formItemLayout={formItemLayout} formItemLayoutWithOutLabel={formItemLayoutWithOutLabel}/>
) }
<FormItem {...formItemLayoutWithOutLabel}>
<Button type="dashed" onClick={this.props.addForm} style={{ width: '60%' }}>
<Icon type="plus" /> Add field
</Button>
</FormItem>
<FormItem {...formItemLayoutWithOutLabel}>
<Button type="primary" htmlType="submit">Submit</Button>
</FormItem>
</Form>
);
}
}
const mapStateToProps = state => {
return {
multiForm: state.multiForm
}
}
const mapDispatchToProps = (dispatch) => {
return bindActionCreators(CounterActions, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(createForm({
mapPropsToFields(props) {
return {
multiForm: createFormField(props.multiForm)
};
},
})(DynamicFieldSet));
|
var multiples = function() {
var sum = 0;
var maxNumber = document.getElementById("input1").value;
for (var i = 1; i < maxNumber; i++) {
if ((i % 3 === 0) || (i % 5 === 0)) {
sum += i;
}
}
document.getElementById("output1").innerHTML = "Result: " + sum;
};
|
import {react, useState, useEffect} from 'react'
function header() {
return (
<div>This is header</div>
)
}
export default header;
|
const URI = "https://donotpanic.cc/cedict/MatchOnly/";
export const searchDic = async list => {
try {
if (!navigator.onLine) {
alert(`Unable to search dictionary,\nas You appear to be OFFLINE!`);
throw "User Offline!";
}
const raw = await fetch(URI, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(list)
});
const result = await raw.json();
return result;
} catch (error) {
console.warn("API Error:", error);
return list.map(e => {
return { match: { simp: e, trad: "", pinyin: "", eng: "" } };
});
}
};
|
"use strict";
var dbConfig = require('../config/dbConfig');
var constants = require('../config/constants');
var dbUtility = require('../utility/dbConnection');
var emailUtility = require('../utility/email');
var encryptUtility = require('../utility/encryption');
var mysql = require('mysql');
var shortid = require('shortid');
var date = require('moment');
var User = {
useHello: function (demodata, callback) {
var response;
var encrypt_data;
encryptUtility.encrypt(demodata, function (err, data) {
if(data)
{response = {
"error": false,
"message": data
};
encrypt_data=data;
callback(null,response);
}
else
{response = {
"error": true,
"message": err
};
callback(response);
}
});
encryptUtility.decrypt("0c8bd89c2e", function (err, data) {
if(data)
{response = {
"error": false,
"message": data
};
callback(null,response);
}
else
{response = {
"error": true,
"message": err
};
callback(response);
}
});
},
// getting user list details
getUser: function (callback) {
dbUtility.query('select * from ' + dbConfig.table1, function(err, rows, fields) {
console.log("select * from " + dbConfig.table1);
if(rows)
{
callback(null,rows);
}
else {
callback(err);
console.log(JSON.stringify(err));
}
});
},
// getting user by id
getUserById: function (id , callback) {
dbUtility.query('select * from ' + dbConfig.table1+'where id='+id, function(err, rows, fields) {
console.log("select * from " + dbConfig.table1+'where id='+id);
if(rows)
{
callback(null,rows);
}
else {
callback(err);
console.log(JSON.stringify(err));
}
});
},
// getting user by Email
getUserByEmail: function (email , callback) {
dbUtility.query('select * from ' + dbConfig.table1+'where email='+email, function(err, rows, fields) {
console.log("select * from " + dbConfig.table1+'where email='+email);
if(rows)
{
callback(null,rows);
}
else {
callback(err);
console.log(JSON.stringify(err));
}
});
},
//set password
setPassword: function (data, callback) {
encryptUtility.encrypt(data.password, function (err, result) {
if(result)
{data.password=result;
}
else
{
console.log("password could not encrypt ........."+JSON.stringify(err));
}
});
var response;
var query= dbUtility.query("select id from " + dbConfig.table1 + " where email='"+data.email+"'",function(err,rows)
{
console.log(rows[0]);
if(err)
{ response = {
"error": true,
"message": err
};
callback(response);
}
if(rows[0] !== undefined) {
var query1= dbUtility.query("UPDATE " + dbConfig.table1 + " SET password='"+data.password+"' where id='"+rows[0].id+"'",function(err,rows)
{
if(err)
{
response = {
"error": true,
"message": err
};
callback(response);
}
else {
response = {
"error": false,
"message": "Password successfully set"
};
callback(null,response);
}
});
console.log(query1.sql);
}
else
{ response = {
"error": true,
"message": "no data found"
};
callback(response);
}
});
console.log(query.sql);
},
//creating users
createUser: function (data, callback) {
data.id = shortid.generate().substring(0, 8);
var createdDate = new Date().toISOString().slice(0, 19).replace('T', ' ');
data.createdon=createdDate;
data.lastupdated=createdDate;
data.isadmin=constants.invited;
data.userstatus="I";
var response;
var query = dbUtility.query("INSERT INTO " + dbConfig.table1 + " SET ?", data, function(err, rows) {
if (err) {
response = {
"error": true,
"message": err
};
callback(null,response);
} else {
response = {
"error": false,
"message1": "Data Inserted successfully"
};
emailUtility.sendEmail(data.email, function (err, data) {
if (err) {
// res.send({
// 'status': 500,
// 'cause': err
// });
callback(err);
} else {
// res.send({
// 'status': 200,
// 'data': data
// });
response.message2="Mail has been sent successfully";
}
callback(null,response);
});
}
});
console.log(query.sql);
},
};
module.exports = User;
|
const data = {
"returnCode": 0,
"errorCode": "0",
"returnMsg": "操作成功",
"result": [
{
"title": "resourceName1223",
"data": {
"id": "5941eaaa2878480d9a643df8fee0f92f",
"insertUser": "111",
"insertTime": "2017-08-07 17:53:28",
"updateUser": null,
"updateTime": null,
"tenantId": "111",
"pid": "root",
"resourceKey": "resourceKey1223",
"resourceName": "resourceName1223",
"resourceEnName": "resourceEnName",
"resourceType": 1
},
"children": null
},
{
"title": "resourceName",
"data": {
"id": "6b4c28b62e994710bab3b10e6aad88cb",
"insertUser": "111",
"insertTime": "2017-08-07 17:52:20",
"updateUser": null,
"updateTime": null,
"tenantId": "111",
"pid": "root",
"resourceKey": "resourceKey11",
"resourceName": "resourceName",
"resourceEnName": "resourceEnName",
"resourceType": 1
},
"children": null
},
{
"title": "resourceName",
"data": {
"id": "8237a9c4cf0c465abdf21bc8d95aa325",
"insertUser": "111",
"insertTime": "2017-08-07 17:51:58",
"updateUser": null,
"updateTime": null,
"tenantId": "111",
"pid": "root",
"resourceKey": "resourceKey10",
"resourceName": "resourceName",
"resourceEnName": "resourceEnName",
"resourceType": 1
},
"children": null
},
{
"title": "resourceName",
"data": {
"id": "8d86c4b775df431d99265eb0a1ac2faf",
"insertUser": "111",
"insertTime": "2017-08-07 17:51:20",
"updateUser": null,
"updateTime": null,
"tenantId": "111",
"pid": "root",
"resourceKey": "resourceKey9",
"resourceName": "resourceName",
"resourceEnName": "resourceEnName",
"resourceType": 1
},
"children": null
},
{
"title": "1111",
"data": {
"id": "5972648a23ee48a6a7c575ad25f805a7",
"insertUser": "111",
"insertTime": "2017-08-07 10:49:21",
"updateUser": null,
"updateTime": null,
"tenantId": "111",
"pid": "root",
"resourceKey": "resourceKey8",
"resourceName": "1111",
"resourceEnName": "111",
"resourceType": 1
},
"children": [
{
"title": "公共字典",
"data": {
"id": "6b6ec525aab4442fa59f1af9043ed76e",
"insertUser": "111",
"insertTime": "2017-08-07 10:31:31",
"updateUser": null,
"updateTime": null,
"tenantId": "111",
"pid": "5972648a23ee48a6a7c575ad25f805a7",
"resourceKey": "resourceKey7",
"resourceName": "公共字典",
"resourceEnName": "111",
"resourceType": 0
},
"children": [
{
"title": "fasdfas",
"data": {
"id": "863e3578f9024288b16fc7c715371c72",
"insertUser": "111",
"insertTime": "2017-08-07 11:11:37",
"updateUser": null,
"updateTime": null,
"tenantId": "111",
"pid": "6b6ec525aab4442fa59f1af9043ed76e",
"resourceKey": "resourceKey6",
"resourceName": "fasdfas",
"resourceEnName": "dddddd",
"resourceType": 1
},
"children": [
{
"title": "resourceName",
"data": {
"id": "a9c2e8d4f102451384d4ccd5bcc3da99",
"insertUser": "111",
"insertTime": "2017-08-07 10:46:39",
"updateUser": "111",
"updateTime": "2017-08-07 10:54:33",
"tenantId": "111",
"pid": "863e3578f9024288b16fc7c715371c72",
"resourceKey": "resourceKey5",
"resourceName": "resourceName",
"resourceEnName": "resourceEnName111",
"resourceType": 1
},
"children": null
}
]
}
]
}
]
},
{
"title": "resourceName",
"data": {
"id": "73fc8ea01ab64ef5bfb2dc39f20c3222",
"insertUser": "111",
"insertTime": "2017-08-07 10:33:18",
"updateUser": null,
"updateTime": null,
"tenantId": "111",
"pid": "root",
"resourceKey": "resourceKey4",
"resourceName": "resourceName",
"resourceEnName": "resourceEnName",
"resourceType": 1
},
"children": null
},
{
"title": "resourceName",
"data": {
"id": "42977f4e42194408b56999cb0493eda9",
"insertUser": "111",
"insertTime": "2017-08-07 09:57:40",
"updateUser": null,
"updateTime": null,
"tenantId": "111",
"pid": "root",
"resourceKey": "resourceKey3",
"resourceName": "resourceName",
"resourceEnName": "resourceEnName",
"resourceType": 1
},
"children": null
},
{
"title": "resourceName",
"data": {
"id": "26f52ccd61b34796a61705968efe7b03",
"insertUser": "111",
"insertTime": "2017-08-07 09:53:22",
"updateUser": null,
"updateTime": null,
"tenantId": "111",
"pid": "root",
"resourceKey": "resourceKey2",
"resourceName": "resourceName",
"resourceEnName": "resourceEnName",
"resourceType": 1
},
"children": null
},
{
"title": "resourceName",
"data": {
"id": "73fc8ea01ab64ef5bfb2dc39f20c5094",
"insertUser": "111",
"insertTime": "2017-08-07 09:52:43",
"updateUser": null,
"updateTime": null,
"tenantId": "111",
"pid": "root",
"resourceKey": "resourceKey1",
"resourceName": "resourceName",
"resourceEnName": "resourceEnName",
"resourceType": 1
},
"children": null
}
],
"stackTrace": null
}
export default data;
|
const Weapon = require('../Weapon');
const FiredAmmo = require('./FiredAmmo');
function Range(typeId, name, itemId, durability, damage, distance, fireRate, accuracy, ammoId, reloadTime, magazineSize, currentMagazine) {
Weapon.apply(this, arguments);
this.accuracy = accuracy;
this.ammoId = ammoId;
this.reloadTime = reloadTime;
this.magazineSize = magazineSize;
this.currentMagazine = currentMagazine;
this.isReloaded = true;
this.isFireRateReady = true;
}
Range.prototype = Object.create(Weapon.prototype);
Range.prototype.shot = function (firedAmmos, personId, initialX, initialY, toX, toY) {
let result=null;
if (this.isReloaded&&this.isFireRateReady&&this.currentMagazine>0) {
this.currentMagazine--;
//this.damage--;
for (let i = 0; i<firedAmmos.length; i++){
if (!firedAmmos[i].active){
firedAmmos[i].charge(personId, this.damage, initialX, initialY, toX, toY, this.accuracy, this.distance)
result = firedAmmos[i];
break;
}
if (i===firedAmmos.length-1){
firedAmmos.push(firedAmmos[0].newCharge(personId, this.damage, initialX, initialY, toX, toY, this.accuracy, this.distance));
result = firedAmmos[firedAmmos.length-1];
break;
}
}
if (this.fireRate!==null){
this.isFireRateReady = false;
setTimeout(function (){
this.isFireRateReady = true;
}.bind(this), this.fireRate);
}
return result;
}
return result;
};
Range.prototype.reloadWeapon = function (size) {
this.isReloaded = false;
setTimeout(function () {
this.isReloaded = true;
this.currentMagazine=size;
}.bind(this), this.reloadTime);
}
// Range.prototype.setReloaded = function () {
// this.isReloaded = true;
// this.currentMagazine=1;
// }
module.exports = Range;
|
import { observable, computed } from 'mobx';
class Todo {
id = Math.random();
@observable title;
@observable finished = false;
constructor(title) {
this.title = title;
}
}
class TodoList {
@observable todos = [];
@computed get unfinishedTodoCount() {
return this.todos.filter(todo => !todo.finished).length;
}
}
class AppState {
@observable todoList = null;
constructor() {
this.todoList = new TodoList();
this.seekDummyData()
}
seekDummyData() {
this.todoList.todos.push(
new Todo("Get Coffee"),
new Todo("Write simpler code")
);
this.todoList.todos[0].finished = true;
}
}
export default AppState;
|
import {
Vector3,
Raycaster
} from 'three'
import {
Vec3
} from 'oimo'
export default class Controls {
constructor(game) {
this.game = game
this.keysDown = {}
this.frontSpeed = 0
this.sideSpeed = 0
this.acceleration = 1
this.setupMouse()
this.setupKeyboard()
}
setupMouse(){
this.game.camera.rotation.order = "YXZ"
this.game.canvas.addEventListener('click', (event) => this.game.canvas.requestPointerLock())
this.game.canvas.addEventListener('mousemove', (event) => {
this.game.camera.rotation.x -= event.movementY * 0.002
this.game.camera.rotation.y -= event.movementX * 0.002
})
}
setupKeyboard(){
document.addEventListener('keydown', (event) => {
this.keysDown[event.keyCode] = true
})
document.addEventListener('keyup', (event) => {
this.keysDown[event.keyCode] = false
})
}
update() {
this.front = 0
this.side = 0
this.jump = false
if(this.keysDown[38]) this.front = 1
if(this.keysDown[40]) this.front = -1
if(this.keysDown[39]) this.side = 1
if(this.keysDown[37]) this.side = -1
if(this.keysDown[96]) {
if(this.game.player.isOnFloor()) {
this.jump = true
}
}
var dir = Controls.getDirectionVector(this.game.player.camera, this.front, this.side)
this.game.player.body.body.linearVelocity.add(this.game.player.body.body.linearVelocity, dir)
if(this.jump) this.game.player.body.body.linearVelocity.y = 10
this.game.player.body.body.linearVelocity.x *= 0.90
this.game.player.body.body.linearVelocity.y
this.game.player.body.body.linearVelocity.z *= 0.90
}
static getDirectionVector(camera, frontSpeed, sideSpeed) {
var direction = new Vector3(0, 0, -1).applyQuaternion(camera.quaternion).normalize()
var strafe = direction.clone().cross(new Vector3(0, 1, 0)).multiplyScalar(sideSpeed)
var face = direction.clone().multiply(new Vector3(1, 0, 1)).multiplyScalar(frontSpeed)
return face.add(strafe)
}
}
|
import React, {
Component
} from "react";
import axios from "axios";
import PodContent from "../PodComponents/PodContent";
import {
connect
} from "react-redux";
import {
saveEngineering
} from '../../actions/engineeringAction';
import { NavLink } from 'react-router-dom';
import '../../style/metricsapp.css';
import '../../style/engg.css';
import swal from 'sweetalert';
import { ON_EXPORT_URL, LOAD_POD_URL } from '../Constants/constants';
import {getMonthName} from "../CommonFunctions/CommonFunctions"
class Engineering extends React.Component {
constructor(props) {
super(props);
let currentDate = new Date();
let currentYear = currentDate.getFullYear();
let currentMonth = currentDate.getMonth()+1;
this.state = {
engg:[{
periodMonth: currentMonth,
periodYear: currentYear,
codeQualityCyclometric: "",
codeQualityTechnical: "",
codeQualityMaintainability: "",
securityDefects: "",
comments: ""
}],
podDetailList: [],
periodMonthList: [{
periodMonthId: "1",
periodMonthName: "January"
},
{
periodMonthId: "2",
periodMonthName: "February"
},
{
periodMonthId: "3",
periodMonthName: "March"
},
{
periodMonthId: "4",
periodMonthName: "April"
},
{
periodMonthId: "5",
periodMonthName: "May"
},
{
periodMonthId: "6",
periodMonthName: "June"
},
{
periodMonthId: "7",
periodMonthName: "July"
},
{
periodMonthId: "8",
periodMonthName: "August"
},
{
periodMonthId: "9",
periodMonthName: "September"
},
{
periodMonthId: "10",
periodMonthName: "October"
},
{
periodMonthId: "11",
periodMonthName: "November"
},
{
periodMonthId: "12",
periodMonthName: "December"
}
],
periodYearList: [{
periodYearId: "1",
periodYearName: "2015"
},
{
periodYearId: "2",
periodYearName: "2016"
},
{
periodYearId: "3",
periodYearName: "2017"
},
{
periodYearId: "4",
periodYearName: "2018"
},
{
periodYearId: "5",
periodYearName: "2019"
},
{
periodYearId: "6",
periodYearName: "2020"
},
{
periodYearId: "7",
periodYearName: "2021"
},
{
periodYearId: "8",
periodYearName: "2022"
},
{
periodYearId: "9",
periodYearName: "2023"
},
{
periodYearId: "10",
periodYearName: "2024"
},
{
periodYearId: "11",
periodYearName: "2025"
},
{
periodYearId: "12",
periodYearName: "2025"
}
]
};
this.saveData = this.saveData.bind(this);
}
sweetAlert() {
// e.preventDefault();
swal("Successfully Saved!", "Successfully Saved", "success")
// window.location.reload()
}
saveData(e) {
e.preventDefault();
const engineeringData = {
podId: this.props.podContent.podId,
podName: this.props.podContent.podName,
engg: this.state.engg
};
console.log(engineeringData)
this.props.dispatch(saveEngineering(engineeringData));
this.sweetAlert();
this.props.history.push('/ListItems');
}
addClick(){
let currentDate = new Date();
let currentYear = currentDate.getFullYear();
let currentMonth = currentDate.getMonth()+1;
this.setState(prevState => ({
engg: [...prevState.engg,{
periodMonth: currentMonth,
periodYear: currentYear,
codeQualityCyclometric: "",
codeQualityTechnical: "",
codeQualityMaintainability: "",
securityDefects: "",
comments: ""
}]
}))
}
removeClick(i){
let engg = [...this.state.engg];
if(i>=1){
engg.splice(i, 1);
this.setState({ engg });
}
}
handleChange(i,e) {
const { name, value } = e.target;
let engg = [...this.state.engg];
engg[i] = {...engg[i], [name]: value};
this.setState({ engg });
};
addPeriodMonth(i,e) {
let periodMonthList = this.state.periodMonthList;
const { name, value } = e.target;
let engg = [...this.state.engg]
console.log("<<<selected= ",value)
let index = periodMonthList.findIndex(x => x.periodMonthName === value);
engg[i] = {...engg[i], [name]: periodMonthList[index].periodMonthId};
this.setState({ engg });
};
onExport() {
const FileDownload = require('js-file-download');
axios.get(ON_EXPORT_URL + "Engineering" , {
responseType: 'arraybuffer'
}).
then(res => {
var blob = new Blob([res.data], { 'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=Cp1252' });
FileDownload(blob, 'report.xls');
})
}
createUI(){
let currentDate = new Date();
let currentYear = currentDate.getFullYear();
let currentMonth = currentDate.getMonth()+1;
let periodMonthList = this.state.periodMonthList.map(data => {
return <option key={
data.periodMonthId
} > {
data.periodMonthName
} </option>;
});
let periodYearList = this.state.periodYearList.map(data => {
return <option key={
data.periodYearId
}> {
data.periodYearName
} </option>;
});
return this.state.engg.map((el, i) => (
<tbody>
<tr>
<td>
<select ref="periodMonthList" id="periodMonth" value={getMonthName(el.periodMonth)} className="form-control" name="periodMonth" onChange={this.addPeriodMonth.bind(this,i)} >
{periodMonthList}
</select>
</td>
<td>
<select ref="periodYearList" id="periodYear" value={el.periodYear} className="form-control" name="periodYear" onChange={this.handleChange.bind(this,i)} >
{periodYearList}
</select>
</td>
<td>
<input className="form-control" type="number" pattern="[0-3]" name="codeQualityCyclometric" value={el.codeQualityCyclometric ||''} onChange={this.handleChange.bind(this,i)}
required/>
</td>
<td>
<input className="form-control" type="number" name="codeQualityTechnical" value={el.codeQualityTechnical ||''} onChange={this.handleChange.bind(this,i)}
required/>
</td>
<td>
<input className="form-control" type="text" pattern="[A-Z]" name="codeQualityMaintainability" value={el.codeQualityMaintainability ||''} onChange={this.handleChange.bind(this,i)}
maxLength="2" required/>
</td>
<td>
<input className="form-control" type="number" name="securityDefects" value={el.securityDefects ||''} onChange={this.handleChange.bind(this,i)}
required/>
</td>
<td>
<input className="form-control" type="text" id="comments" name="comments" value={el.comments ||''} onChange={this.handleChange.bind(this,i)}
required/>
</td>
<td>
<input id="remove" className="btn btn-info btn-sm" type ="button" value="remove" onClick={this.removeClick.bind(this, i)}
required/>
</td>
</tr>
</tbody>
))
}
onInputChange = e => {
let lastString = e.target.value[e.target.value.length - 1];
if (lastString.match("[+-]?[0-9]") == null) {
e.target.value = e.target.value.substring(0, e.target.value.length - 1);
}
};
render() {
const positionAbsolute = {
position: `absolute`,
right: `16px`
};
let periodMonthList = this.state.periodMonthList.map(data => {
return <option key={
data.periodMonthId
} > {
data.periodMonthName
} </option>;
});
let periodYearList = this.state.periodYearList.map(data => {
return <option key={
data.periodYearId
} > {
data.periodYearName
} </option>;
});
return (
<div className="container sidebarspace">
<NavLink to='/ListItems'><button className="goback ">Go Back</button></NavLink>
<h1> Engineering </h1>
<form onSubmit={this.saveData}>
<div className="form-group">
<PodContent />
<br />
<div className="scrollmenu">
<table className="table-hover">
<thead id ="enggtable">
<th className="text-center">Month</th>
<th className="text-center">Year</th>
<th className="text-center">Code Quality - Cyclomatic complexity/ function</th>
<th className="text-center">Code Quality - Technical Debt (in Days)</th>
<th className="text-center">Code Quality - Maintainability Index Index (A,B,C, D, E)</th>
<th className="text-center">Number of security defects identified after code checkin (Number)</th>
<th className="text-center">Comments</th>
<th className="text-center">Action</th>
</thead>
{this.createUI()}
</table>
</div>
<br />
<div className = "wrapper">
<td>
<input id ="add_button" className ="btn btn-primary" type='button' value='Add' onClick={this.addClick.bind(this)}/>
</td>
<td>
<input id ="submit_button" type="submit" className ="btn btn-primary" value="Submit" />
</td>
<td>
<input type="button" className ="btn btn-primary" value="Export" onClick={this.onExport.bind(this)}/>
</td>
</div>
</div>
</form>
</div>
)
}
}
const mapPropsToState = (state) => {
return {
podContent: state.podContent
}
}
export default connect(mapPropsToState)(Engineering);
|
import fetch from 'isomorphic-fetch';
import Promise from 'promise';
const API_KEY = '29675a4401a78f0c624db3bcde9a48c7';
const API_URL = 'http://api.openweathermap.org/data/2.5';
const API_URL_FLICKR = ' https://api.flickr.com/services/rest/';
const API_FLICKR_KEY = '43222c6296f7465a62aca5020ef7267d';
const FLICKR_SECRET = 'c9fb46989ce3422c';
// http://api.openweathermap.org/data/2.5/forecast/daily?id=524901&cnt=5&appid=5a043a1bd95bf3ee500eb89de107b41e
const kelvinToCelsius = (kelvin) => kelvin - 273.15;
const round = (value, decimals = 1) => {
const x = Math.pow(10, decimals);
return Math.round(x * value) / x;
};
const apiCall = (url) => {
return fetch(url)
.then(response => {
if (response.status >= 400) {
return Promise.reject('Invalid response');
}
return response.json();
})
.then(json => {
if (url.indexOf('flickr') !== -1 && json.stat != 'ok') {
return Promise.reject('Cant find place');
} else if (url.indexOf('flickr') == -1 && parseInt(json.cod) !== 200) {
return Promise.reject('Invalid response');
}
return json;
});
};
export const queryWeather = (city) => {
let data;
return apiCall(`${API_URL}/weather?q=${city.trim()}&appid=${API_KEY}`)
.then(json => {
data = {
temperature: round(kelvinToCelsius(json.main.temp), 0),
humidity: json.main.humidity,
icon: json.weather[0].id,
name: json.name,
country: json.sys.country.toLowerCase()
};
return apiCall(`${API_URL}/forecast/daily?id=${json.id}&cnt=5&appid=${API_KEY}`);
})
.then(json => {
data = {
...data,
forecast: json.list.map((d) => ({
weekday: (new Date(d.dt * 1000)).getDay(),
icon: d.weather[0].id,
maxTemp: round(kelvinToCelsius(d.temp.max), 0),
minTemp: round(kelvinToCelsius(d.temp.min), 0)
}))
};
return apiCall(`${API_URL_FLICKR}?method=flickr.places.find&api_key=${API_FLICKR_KEY}&query=${city}&format=json&nojsoncallback=1`);
})
.then(json => {
data = {
...data,
placeId: json.places.place[0].place_id,
lat: json.places.place[0].latitude,
lon: json.places.place[0].longitude
}
return apiCall(`${API_URL_FLICKR}?method=flickr.photos.search&api_key=${API_FLICKR_KEY}&per_page=5&page=1&safe_search=true&place_id=${data.placeId}&format=json&nojsoncallback=1`);
}).then(json => {
let photos = [];
for (let i = 0; i < json.photos.photo.length; i++) {
let item = json.photos.photo[i];
photos.push(`https://farm${item.farm}.staticflickr.com/${item.server}/${item.id}_${item.secret}.jpg`);
}
return {
...data,
photos: photos
}
});
};
|
$(function(e) {
$('input[name="fecha"]').datetimepicker({
format: "YYYY-MM-DD"
});
$('input[name="archivo"]').on('change',function(e){
if ($(this).val() != '')
$('input[name="nombre_archivo"]').val($(this).val());
else
$('input[name="nombre_archivo"]').val('');
});
$('.carousel').slick({
autoplay: "true",
autoplaySpeed: 1000
});
$('#fullpage').fullpage({
menu: '#menu',
anchors: ['inicio', 'como_funciona', 'conocenos', 'preguntas_frecuentes', 'contacto'],
navigation: true,
navigationPosition: 'right',
navigationTooltips: ['Inicio', '¿Cómo funciona?', 'Preguntas Frecuentes', 'Conocénos', 'Contacto'],
responsiveWidth: 900,
responsiveHeigth: 900
});
});
|
import React from "react";
import styled from "styled-components/native";
import { MaterialCommunityIcons } from "@expo/vector-icons";
import AsyncStorage from "@react-native-async-storage/async-storage";
import {
View,
Text,
Pressable,
Image,
TouchableHighlight,
Modal,
nickName,
} from "react-native";
import { useState } from "react";
const MyScreenUserInfo = ({ navigation, nickName }) => {
const [modalVisible, setModalVisible] = useState(false);
const Logout = () => {
AsyncStorage.clear();
navigation.navigate("SignUp");
};
return (
<>
<UserInfoView>
<Modal animationType="slide" transparent={true} visible={modalVisible}>
<CenteredView>
<ModalView>
<ModalAlertView>
<ModalText>로그아웃하시겠습니까?</ModalText>
</ModalAlertView>
<ModalTextView>
<SubmitBtn
onPress={() => {
setModalVisible(!modalVisible);
Logout();
}}
>
<SubmitText>네</SubmitText>
</SubmitBtn>
<CancelBtn
onPress={() => {
setModalVisible(!modalVisible);
}}
>
<CancelText>아니요</CancelText>
</CancelBtn>
</ModalTextView>
</ModalView>
</CenteredView>
</Modal>
<UserInfo>
<UserNickName>{nickName}</UserNickName>
<LogoutBtn
onPress={() => {
setModalVisible(true);
}}
>
<MaterialCommunityIcons
name="logout-variant"
size={21}
color="black"
/>
<Text> 로그아웃</Text>
</LogoutBtn>
</UserInfo>
<UserImgView>
<UserImg
source={{
uri:
"https://images.unsplash.com/photo-1596815064285-45ed8a9c0463?ixid=MXwxMjA3fDB8MHxzZWFyY2h8Mjl8fGdpcmx8ZW58MHx8MHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=800&q=60",
}}
/>
</UserImgView>
</UserInfoView>
</>
);
};
export default MyScreenUserInfo;
const UserInfoView = styled.View`
margin-top: 40px;
flex-direction: row;
align-items: center;
justify-content: space-between;
padding: 0 20px;
`;
// 모달관련
const CenteredView = styled.View`
flex: 1;
justify-content: center;
align-items: center;
margin-top: 22px;
background-color: rgba(0, 0, 0, 0.6);
`;
const ModalView = styled.View`
width: 250px;
height: 200px;
margin: 20px;
background-color: white;
border-radius: 20;
align-items: center;
justify-content: center;
`;
const ModalText = styled.Text`
text-align: center;
font-size: 20px;
`;
const ModalAlertView = styled.View`
width: 200px;
height: 60px;
justify-content: center;
border-bottom-color: #0d7dd0;
border-bottom-width: 1px;
`;
const ModalTextView = styled.View`
flex-direction: row;
width: 200px;
height: 60px;
align-items: center;
`;
const SubmitBtn = styled.Pressable`
width: 100px;
height: 50px;
justify-content: center;
`;
const SubmitText = styled.Text`
font-weight: bold;
text-align: center;
font-size: 16px;
`;
const CancelBtn = styled.Pressable`
width: 100px;
height: 50px;
justify-content: center;
border-left-color: #0d7dd0;
border-left-width: 1px;
`;
const CancelText = styled.Text`
font-weight: bold;
text-align: center;
font-size: 16px;
`;
const UserInfo = styled.View`
flex-direction: row;
`;
const UserNickName = styled.Text`
font-size: 20px;
font-weight: 600;
margin-right: 10px;
`;
const LogoutBtn = styled.Pressable`
width: 90px;
height: 30px;
flex-direction: row;
justify-content: center;
align-items: center;
border-radius: 20;
border: 1px solid black;
`;
const UserImgView = styled.View`
width: 60px;
height: 60px;
`;
const UserImg = styled.Image`
width: 100%;
height: 100%;
border-radius: 50;
`;
|
var mongoose = require('mongoose');
var themeSchema = new mongoose.Schema({
theme: { type: String, required: true}
});
var Theme = mongoose.model('Theme', themeSchema);
// Make this available to our other files
module.exports = Theme;
|
const path = require('path')
const args = require('./args')
const { DEFAULT_FILE_EXT } = require('./constants')
module.exports = {
get dir() {
return path.resolve(args.current.dir)
},
get target() {
return this.forTarget(args.current.target)
},
get output() {
return path.resolve(args.current.output)
},
forTarget(target) {
return path.resolve(this.dir, `${target}${DEFAULT_FILE_EXT}`)
}
}
|
$(document).ready(function(){
// Menu Bar Functions Start //
$(".nav-head").mouseover(function(){
$(this).css("color","rgba(239, 154, 154, 0.59)");
})
$(".nav-head").mouseout(function(){
$(this).css("color","white");
})
$(window).scroll(function(){
var height = $(window).scrollTop();
if (height > 575) {
$(".navbar-container").addClass("section2-active");
}
else {
$(".navbar-container").removeClass("section2-active");
}
});
$("#menu-bar-container").click(function(){
$(".navbar-container").addClass("navbar-deactive");
$("body").addClass("no-scroll");
setTimeout(function(){
$(".body-container").addClass("section-active");
$(".side-navbar-container").addClass("sidebar-active");
},100);
});
$(".home-button").click(function(){
setTimeout(function(){
$(".navbar-container").addClass("navbar-deactive");
$("body").addClass("no-scroll");
},150);
setTimeout(function(){
$(".body-container").addClass("section-active");
$(".side-navbar-container").addClass("sidebar-active");
},200);
});
$("#menu-bar-container").mouseover(function(){
$("#menu-bar-container").css("transform","rotate(180deg)");
$("#menu-bar-container").css("-webkit-transform","rotate(180deg)");
$("#menu-bar-container").css("-moz-transform","rotate(180deg)");
$("#menu-bar-container").css("-o-transform","rotate(180deg)");
})
$(this).mouseout(function(){
$("#menu-bar-container").css("transform","rotate(0deg)");
$("#menu-bar-container").css("-webkit-transform","rotate(0deg)");
$("#menu-bar-container").css("-moz-transform","rotate(0deg)");
$("#menu-bar-container").css("-o-transform","rotate(0deg)");
})
$("#side-menu-bar-container").click(function(){
$(".side-navbar-container").removeClass("sidebar-active");
$(".body-container").removeClass("section-active");
$(".sub-categories").removeClass("active-sub");
$(".arrow-container").removeClass("arrow-active");
setTimeout(function(){
$(".category-head").removeClass("debump");
},600);
setTimeout(function(){
$(".navbar-container").removeClass("navbar-deactive");
$("body").removeClass("no-scroll");
},100);
});
$(".body-container").click(function(){
$(".side-navbar-container").removeClass("sidebar-active");
$(".body-container").removeClass("section-active");
$(".sub-categories").removeClass("active-sub");
$(".arrow-container").removeClass("arrow-active");
setTimeout(function(){
$(".category-head").removeClass("debump");
},600);
setTimeout(function(){
$(".navbar-container").removeClass("navbar-deactive");
$("body").removeClass("no-scroll");
},100);
});
$("#side-menu-bar-container").mouseover(function(){
$("#side-menu-bar-container").css("transform","rotate(180deg)");
$("#side-menu-bar-container").css("-webkit-transform","rotate(180deg)");
$("#side-menu-bar-container").css("-moz-transform","rotate(180deg)");
$("#side-menu-bar-container").css("-o-transform","rotate(180deg)");
})
$(this).mouseout(function(){
$("#side-menu-bar-container").css("transform","rotate(0deg)")
$("#side-menu-bar-container").css("-webkit-transform","rotate(0deg)");
$("#side-menu-bar-container").css("-moz-transform","rotate(0deg)");
$("#side-menu-bar-container").css("-o-transform","rotate(0deg)");
})
// Menu Bar Functions End //
// Side Bar Functions Start //
$(".practice-tests").click(function(){
if ($(".practice-tests").hasClass("debump"))
{ $(".sub-practice-tests").removeClass("active-sub");
$(".a1").removeClass("arrow-active");
setTimeout(function(){
$(".practice-tests").removeClass("debump");
},600);
}
else { $(this).addClass("debump");
$(".a1").addClass("arrow-active");
setTimeout(function(){
$(".sub-practice-tests").addClass("active-sub");
},500); }
});
$(".drug-lists").click(function(){
if ($(".drug-lists").hasClass("debump"))
{ $(".sub-drug-lists").removeClass("active-sub");
$(".a2").removeClass("arrow-active");
setTimeout(function(){
$(".drug-lists").removeClass("debump");
},600);
}
else { $(this).addClass("debump");
$(".a2").addClass("arrow-active");
setTimeout(function(){
$(".sub-drug-lists").addClass("active-sub");
},500); }
});
$(".study-notes").click(function(){
if ($(".study-notes").hasClass("debump"))
{ $(".sub-study-notes").removeClass("active-sub");
$(".a3").removeClass("arrow-active");
setTimeout(function(){
$(".study-notes").removeClass("debump");
},600);
}
else { $(this).addClass("debump");
$(".a3").addClass("arrow-active");
setTimeout(function(){
$(".sub-study-notes").addClass("active-sub");
},500); }
});
$(".math").click(function(){
if ($(".math").hasClass("debump"))
{ $(".sub-math").removeClass("active-sub");
$(".a4").removeClass("arrow-active");
setTimeout(function(){
$(".math").removeClass("debump");
},600);
}
else { $(this).addClass("debump");
$(".a4").addClass("arrow-active");
setTimeout(function(){
$(".sub-math").addClass("active-sub");
},500); }
});
$(".forums").click(function(){
if ($(".forums").hasClass("debump"))
{ $(".sub-forums").removeClass("active-sub");
$(".a5").removeClass("arrow-active");
setTimeout(function(){
$(".forums").removeClass("debump");
},600);
}
else { $(this).addClass("debump");
$(".a5").addClass("arrow-active");
setTimeout(function(){
$(".sub-forums").addClass("active-sub");
},500); }
});
// Side Bar Functions End //
$(".home-head").mouseover(function(){
$(".home-border").css("width","50%");
});
$(".home-head").mouseout(function(){
$(".home-border").css("width","20%");
});
$(".home-button").mouseover(function(){
$(".home-button").addClass("button-active");
});
$(".home-button").mouseout(function(){
$(".home-button").removeClass("button-active");
});
// Carousel Function //
$(".rts-arrow").click(function(){
var carousel = parseInt($('.carousel').css('margin-left').replace("px", ""));
if (carousel == -1300){
return false;
}
else{
$(".carousel").css("margin-left","+=-650px");
}
});
$(".lts-arrow").click(function(){
var carousel = parseInt($('.carousel').css('margin-left').replace("px", ""));
if (carousel == 0){
return false;
}
else{
$(".carousel").css("margin-left","+=650px");
}
});
$(".rts-arrow").click(function(){
if($(".b1").hasClass("bubble-active")){
$(".b1").removeClass("bubble-active");
$(".b2").addClass("bubble-active");
}
else if($(".b2").hasClass("bubble-active")){
$(".b2").removeClass("bubble-active");
$(".b3").addClass("bubble-active");
}
else{
return false;
}
});
$(".lts-arrow").click(function(){
if($(".b2").hasClass("bubble-active")){
$(".b2").removeClass("bubble-active");
$(".b1").addClass("bubble-active");
}
else if($(".b3").hasClass("bubble-active")){
$(".b3").removeClass("bubble-active");
$(".b2").addClass("bubble-active");
}
else{
return false;
}
});
$(".b1").click(function(){
$(this).addClass("bubble-active");
$(".b2").removeClass("bubble-active");
$(".b3").removeClass("bubble-active");
$(".carousel").css("margin-left","0");
});
$(".b2").click(function(){
$(this).addClass("bubble-active");
$(".b1").removeClass("bubble-active");
$(".b3").removeClass("bubble-active");
$(".carousel").css("margin-left","-650");
});
$(".b3").click(function(){
$(this).addClass("bubble-active");
$(".b1").removeClass("bubble-active");
$(".b2").removeClass("bubble-active");
$(".carousel").css("margin-left","-1300");
});
$(".search-box").click(function(){
$(".search").show();
$("body").addClass("no-scroll");
$(window).scrollTop(0);
});
$(".search-overlay").click(function(){
$(".search").hide();
$("body").removeClass("no-scroll");
});
$(".submit-search").click(function(){
$(".search").hide();
$("body").removeClass("no-scroll");
});
});
|
var StudentsView = Backbone.View.extend({
initialize: function() {
//this.render();
this.collection.on('update', this.render, this);
},
render: function() {
var me = this;
this.$el.html('');
var $html = this.collection.map(function (s) {
return new StudentEntryView({model: s}).render();
})
this.$el.append($html);
return this.$el;
}
});
|
const express = require('express');
const router = express.Router();
const filmsController = require('../../controllers/films');
// El post para crear una pelicula por json
router.post('/', async (req, res) => {
const film = {
release_date: req.body.release_date,
title: req.body.title,
};
let result = await filmsController.addFilm(film);
res.send(result);
});
module.exports = router;
|
var Foam = require('foam-gl'),
MouseEvent = Foam.MouseEvent,
Mouse = Foam.Mouse,
KeyEvent = Foam.KeyEvent,
Keyboard = Foam.Keyboard;
Foam.App.newOnLoad({
setup : function(){
Mouse.getInstance().addEventListener(MouseEvent.MOUSE_DOWN,this.onMouseDown.bind(this));
Keyboard.getInstance().addEventListener(KeyEvent.KEY_DOWN, this.onKeyDown.bind(this));
Keyboard.getInstance().addEventListener(KeyEvent.KEY_PRESS, this.onKeyPress.bind(this));
},
update : function(){
/*
var mouse = Mouse.getInstance();
console.log('Mouse down: ' + mouse.isDown() + '\n' +
' pressed: ' + mouse.isPressed() + '\n' +
' moved: ' + mouse.didMove() + '\n' +
' dragged: ' + mouse.isDragged() + '\n' +
' positionLast: ' + 'x: ' + mouse.getXLast() + ', y:' + mouse.getYLast() + '\n' +
' position: ' + 'x: ' + mouse.getX() + ', y: ' + mouse.getY() + '\n' +
' didEnter: ' + mouse.didEnter() + '\n' +
' didLeave: ' + mouse.didLeave());
*/
},
onMouseDown : function(event) {
console.log(event);
},
onKeyDown : function(event){
console.log(event);
},
onKeyUp : function(event){
console.log(event);
},
onKeyPress : function(event){
console.log(event.type);
}
});
|
$(function () {
var NotificationsViewModel = function () {
var self = this;
self.notifications = ko.observableArray();
self.following = ko.observable(false);
self.notFollowing = ko.observable(true);
self.update = function () {
$.getJSON("/api/notifications", function (data) {
self.notifications(data);
if(WallName)
self.updateState();
});
};
self.markAsRead = function () {
$.ajax({
url: "/api/notifications",
method: "PUT",
success: function (data) {
self.notifications(data);
}
});
};
self.updateState = function () {
if (WallName)
$.get("/api/walls?WallName=" + WallName, function (data) {
self.following(data.state);
self.notFollowing(!data.state);
});
};
self.follow = function () {
if (WallName)
$.post("/api/walls?WallName=" + WallName, function (data) {
self.updateState();
});
};
self.unfollow = function () {
if (WallName)
$.ajax({
url: "/api/walls?WallName=" + WallName,
method: "DELETE",
success: function () {
self.updateState();
}
});
};
};
var notificationsViewModel = new NotificationsViewModel();
ko.applyBindings(notificationsViewModel, document.getElementById("navbar"));
notificationsViewModel.update();
if(WallName)
{
notificationsViewModel.updateState();
}
});
|
import React, { Component } from 'react';
import firebase from 'firebase';
import StyledFirebaseAuth from 'react-firebaseui/StyledFirebaseAuth';
import {Container} from 'reactstrap';
firebase.initializeApp({
apiKey:"AIzaSyBNwp4IUDZODI87R9JS6I1qe1fQzBEHngw",
authDomain:"barcamp-management.firebaseapp.com"
});
const Lstyles = {
textAlign: 'center',
color : 'white'
};
const load = {
textAlign : 'center',
padding : '50px',
fontSize : "20px"
};
const welcome = {
fontSize : '70px'
};
const page = {
backgroundColor : "#09090A"
}
const page2 = {
height : "980px",
}
class Login extends Component{
constructor(props) {
super(props);
this.toggle = this.toggle.bind(this);
this.changePage =this.changePage.bind(this);
this.state = {
isSignedIn:false,
dropdownOpen: false
}
}
uiConfig = {
signInFlow : "popup",
signInOptions: [
firebase.auth.GoogleAuthProvider.PROVIDER_ID,
firebase.auth.GithubAuthProvider.PROVIDER_ID
],
callbacks : {
singInSuccess : () => false
}
}
toggle() {
this.setState({
dropdownOpen: !this.state.dropdownOpen
});
}
changePage(){
setTimeout(() => {
this.props.history.push('/attendee');
}, 2000);
}
componentDidMount = () => {
firebase.auth().onAuthStateChanged(user => {
this.setState({ isSignedIn: !!user })
console.log("user", user)
})
}
render() {
return (
<div style={page}>
<Container style={page2}>
<div style={Lstyles}>
<font size="90">Barcamp Login</font>
{this.state.isSignedIn ? (
<span>
<h1 style={welcome}>Welcome</h1>
<h4 style={load}>loading...</h4>
{this.changePage()}
</span>
) : (
<StyledFirebaseAuth
uiConfig={this.uiConfig}
firebaseAuth={firebase.auth()}
/>
)}
</div>
</Container>
</div>
)
}
}
export default Login;
|
function calcScore(code, guess) {
let answer = { correctPos: 0, incorrectPos: 0 };
findCorrectPos(code, guess, answer);
findIncorrectPos(code, guess, answer);
return answer;
}
function findIncorrectPos(code, guess, answer) {
for (let i = 0; i < guess.length; i++) {
if (guess[i] === undefined) continue;
let index = code.indexOf(guess[i]);
if (index != -1) {
answer["incorrectPos"]++;
guess[i] = undefined;
code[index] = undefined;
}
}
}
function findCorrectPos(code, guess, answer) {
for (let i = 0; i < guess.length; i++) {
if (guess[i] == code[i]) {
answer["correctPos"]++;
code[i] = undefined;
guess[i] = undefined;
}
}
}
module.exports = calcScore
|
import {compose, withPropsOnChange, onlyUpdateForKeys} from 'recompose'
// local libs
import {
plainProvedGet as g,
immutableProvedGet as ig,
setPropTypes,
PropTypes,
ImmutablePropTypes,
getRandomWidthList,
} from 'src/App/helpers'
// this HOC getting 'randomWidthListSize', 'randomWidthList', 'setRandomWidthList' from props,
// so your wrapped component should provide these props:
// compose(
// connect(
// state => ({
// randomWidthList: ig(state, 'app', 'home', 'randomWidthList'),
// }),
// {
// setRandomWidthList: g(actions, 'setRandomWidthList'),
// }
// ),
// withPropsOnChange(['data'], {
// randomWidthListSize: g(ig(props.data, 'nichesListWithThumb'), 'size')),
// }),
// imagesRandomWidth,
// )
// we can't get 'setRandomWidthList' inside this HOC because we need specific actions for each page
// we can't get 'randomWidthList', because 'currentSections' becomes available after page loads,
// we can't get 'randomWidthListSize', because this HOC is used by the plugs and for each page
// we have different key names (for example: 'nichesListWithThumb', 'videoList', etc)
export default compose(
onlyUpdateForKeys(['randomWidthListSize', 'randomWidthList']),
withPropsOnChange(['randomWidthListSize', 'randomWidthList'], props => {
if ( ! g(props, 'randomWidthListSize'))
return { styledBounds: null }
const // getting without 'g' because we don't have 'data' in plugs
isLoaded = props.data ? ig(props.data, 'isLoaded') : null
if (
g(props, 'randomWidthList') &&
g(props, 'randomWidthList', 'size') === g(props, 'randomWidthListSize')
)
return {
styledBounds: g(props, 'randomWidthList').map(x => Object.freeze({
width: `${x}px`
})),
}
const
randomWidthList = getRandomWidthList(
g(props, 'randomWidthListSize'),
g(props, 'randomWidthList'),
)
if ( ! isLoaded)
props.setRandomWidthList({randomWidthList})
return {
styledBounds: randomWidthList.map(x => Object.freeze({width: `${x}px`})),
}
}),
setPropTypes(process.env.NODE_ENV === 'production' ? null : {
randomWidthListSize: PropTypes.number,
randomWidthList: PropTypes.nullable(ImmutablePropTypes.listOf(PropTypes.number)),
styledBounds: PropTypes.nullable(ImmutablePropTypes.listOf(PropTypes.exact({
width: PropTypes.string,
}))),
setRandomWidthList: PropTypes.func,
})
)
|
import './HelloWorld.scss';
const { registerBlockType } = wp.blocks;
const { __ } = wp.i18n;
const heartIcon = (
<svg
xmlns='http://www.w3.org/2000/svg'
height='24px'
viewBox='0 0 24 24'
width='24px'
fill='#000000'>
<path d='M0 0h24v24H0z' fill='none' />
<path d='M16.5 3c-1.74 0-3.41.81-4.5 2.09C10.91 3.81 9.24 3 7.5 3 4.42 3 2 5.42 2 8.5c0 3.78 3.4 6.86 8.55 11.54L12 21.35l1.45-1.32C18.6 15.36 22 12.28 22 8.5 22 5.42 19.58 3 16.5 3zm-4.4 15.55l-.1.1-.1-.1C7.14 14.24 4 11.39 4 8.5 4 6.5 5.5 5 7.5 5c1.54 0 3.04.99 3.57 2.36h1.87C13.46 5.99 14.96 5 16.5 5c2 0 3.5 1.5 3.5 3.5 0 2.89-3.14 5.74-7.9 10.05z' />
</svg>
);
registerBlockType('themename-block/hello-world', {
title: __('Hello World', 'themename-hello-world'),
description: __('Our first block', 'themename-hello-world'),
category: 'layout',
icon: {
background: '#f03',
foreground: '#fff',
src: heartIcon,
},
keywords: [__('photo', 'themename-block'), __('image', 'themename-hello-world')],
edit: (props) => {
const { className } = props;
return (
<div className={className}>
<h1 className='title-color'>Hello World</h1>
<p className='text-color'>👋 Lorem Ipsum</p>
</div>
);
},
save: ({ className }) => {
return (
<div className={className}>
<h1 className='title-color'>Hello World</h1>
<p className='text-color'>👋 Lorem Ipsum</p>
</div>
);
},
});
|
var ipc = require('electron').ipcRenderer;
const fixedCourse = 3
let wsWidth = $id('workspace').offsetWidth
let psWidth = $id('paramsSetting').offsetWidth
let wsHeight = "100%"
let canResize = false
let drag = false
let editHeight = 230
let changedPsWidth = 300//do not delete this varable,use in other js file!!!!
let onfocus = true
let timeTicker
window.onresize = function () {
AutoSetWindowSize()
}
//windows max min hide func
if (!$isNull($id('closeBtn'))) {
$id('closeBtn').onclick = function () {
ipc.send('window-close');
}
}
if (!$isNull($id('maxBtn'))) {
$id('maxBtn').onclick = function () {
ipc.send('window-max');
}
}
if (!$isNull($id('hideBtn'))) {
$id('hideBtn').onclick = function () {
ipc.send('window-hide');
}
}
//Windows drag handler
$id('workspace').onmousemove = function () {
if (event.clientX - 60 - psWidth >= -fixedCourse &&
event.clientX - 60 - psWidth <= fixedCourse) {
this.style.cursor = 'ew-resize'
canResize = true
} else {
this.style.cursor = 'default'
}
if (drag && canResize && onfocus) {
psWidth = event.clientX - 60;
changedPsWidth = psWidth
AutoSetWindowSize();
}
}
$id('workspace').onmousedown = function () {
if (canResize && onfocus)
drag = true
this.onmouseup = function () {
if (canResize) {
drag = false;
canResize = false;
}
}
}
$id('tab').onwheel = function (event) {
event.preventDefault();
//设置鼠标滚轮滚动时屏幕滚动条的移动步长
var step = 50;
if (event.deltaY < 0) {
//向上滚动鼠标滚轮,屏幕滚动条左移
this.scrollLeft -= step;
} else {
//向下滚动鼠标滚轮,屏幕滚动条右移
this.scrollLeft += step;
}
}
//bottom bar
$id('showInputSend').onclick = function () {
if ($id('output').style.display == 'block') {
$id('output').style.display = 'none'
editHeight = 0
AutoSetWindowSize()
$id('showInputSend').innerText = 'ShowInput'
} else {
$id('output').style.display = 'block'
editHeight = 230
AutoSetWindowSize()
$id('showInputSend').innerText = 'HideInput'
}
}
//当前窗口得到焦点
window.onfocus = function () {
setTimeout(function () {
onfocus = true
}, 200)
canResize = false
drag = false
return
};
//当前窗口失去焦点
window.onblur = function () {
onfocus = false
};
//bottom button
//Function area
function init() {
psWidth = $id('paramsSetting').offsetWidth
AutoSetWindowSize()
}
function AutoSetWindowSize() {
wsWidth = $id('root').offsetWidth - 60
wsHeight = $tag('body')[0].offsetHeight - 50
$id('workspace').style.width = wsWidth + 'px'
if (psWidth < 236 && psWidth != 0)
psWidth = 236
if(psWidth > 350 && psWidth != 0)
psWidth = 350
$id('box').style.height = wsHeight - 45 - editHeight + 'px'
$id('topContainer').style.height = wsHeight + 'px'
$id('mainDisplay').style.width = wsWidth - psWidth + 'px'
$id('paramsSetting').style.width = psWidth + 'px'
}
function headerSizeChange(){
headerSize = parseInt($id('headerSize').options[$id('headerSize').selectedIndex].value)
}
function logItemSizeChange(){
logItemSize = parseInt($id('logItemSize').options[$id('logItemSize').selectedIndex].value)
}
function encodingChange(){
hexType = $id('encoding').options[$id('encoding').selectedIndex].value == 'true' ? true : false
}
function timeIntervalChange(){
timeInterval = parseInt($id('timeInterval').options[$id('timeInterval').selectedIndex].value)
window.clearInterval(timeTicker)
timeTicker = setInterval(function(){if(!autoSend){return} sendMessage()},timeInterval)
}
function autoSendChange(){
autoSend = $id('autoSend').options[$id('autoSend').selectedIndex].value == 'true' ? true : false
}
timeTicker = setInterval(function () {if(!autoSend){return} sendMessage()}, timeInterval)
|
import riot from 'riot'
import {notificationManager} from 'utils'
const inList = function (list, elem) {
for (const val of list) {
if (val.id === elem.id) {
return true
}
}
return false
}
riot.mixin('load-entities', {
init: function () {
this.mixin('loading')
},
mergeLists: function (dest, newElems) {
for (const newElem of newElems) {
if (!inList(dest, newElem)) {
dest.push(newElem)
}
}
},
loadEntities: function (service, options = {}) {
const key = options.key || 'entities'
const entitiesName = options.entitiesName || key || 'entities'
this.startLoading()
return service.list(options.query)
.then((res) => {
this.mergeLists(this[key], res)
return res
})
.catch(_e => {
notificationManager.notify(`Failed to load the ${entitiesName}`, 'danger')
})
.finally(() => this.endLoading({update: true}))
}
})
|
var DEFAULT_PAGE_SIZE = 20;
var RESOURCE_CACHES = {};
$('a[data-resources-container]').on('click', function (){
var layoutid = $(this).attr('data-resources-container');
var html = '';
var category = resource_category[layoutid];
if( category ){
$.each( category, function(id, alias){
html += '<li onClick="removeLayoutResource(this)" class="list-group-item" data-category=1 name="' + id + '" > ' + alias + '</li>';
})
}
var resource = resources[layoutid];
if( resource ){
$.each( resource, function(id, alias){
html += '<li onClick="removeLayoutResource(this)" class="list-group-item" data-category=0 name="' + id + '" > ' + alias + '</li>';
})
}
if( html ) {
$('#layout_resources ul').html(html);
$('#layout_resources span').addClass('hidden');
} else {
$('#layout_resources ul').empty();
$('#layout_resources span').removeClass('hidden');
}
$('#resourcesModal').find('input[name="layoutid"]:first').val(layoutid);
var first_tab = $('#resources a:first');
if( first_tab.parent().hasClass('active') ){
var category = first_tab.attr('href') == '#resource-category-set';
reloadLayouerUI(category, 1, DEFAULT_PAGE_SIZE);
}else{
first_tab.tab('show');
}
$('#resourcesModal').modal('show');
});
$('a[data-toggle="tab"]', '#resources').on('shown.bs.tab', function (e) {
var category = $(e.target).attr('href') == '#resource-category-set';
reloadLayouerUI(category, 1, DEFAULT_PAGE_SIZE);
})
function addLayoutResource(elm){
self = $(elm);
if( self.hasClass('disabled') ) return;
$('#layout_resources span').addClass('hidden');
self.addClass('disabled');
var layoutid = $('#resourcesModal').find('input[name="layoutid"]:first').val();
var id = self.attr('name');
var category = self.attr('data-category') == 1;
var alias = self.text();
if( category ){
$('#layout_resources ul').append('<li onClick="removeLayoutResource(this)" class="list-group-item" data-category=1 name="' + id + '"> ' + alias + '</li>');
resource_category[layoutid][id] = alias;
}else{
$('#layout_resources ul').append('<li onClick="removeLayoutResource(this)" class="list-group-item" data-category=0 name="' + id + '"> ' + alias + '</li>');
resources[layoutid][id] = alias;
}
}
function removeLayoutResource(elm){
self = $(elm);
var layoutid = $('#resourcesModal').find('input[name="layoutid"]:first').val();
var id = self.attr('name');
var category = self.attr('data-category') == 1;
if( category ){
$('li.disabled[name="' + id + '"]', '#resource-category-set').removeClass('disabled');
delete resource_category[layoutid][id];
}else{
$('li.disabled[name="' + id + '"]', '#resource-set').removeClass('disabled');
delete resources[layoutid][id];
}
if( self.parent().children().length == 1) $('#layout_resources span').removeClass('hidden');
self.remove();
}
$('#save-resource', '#resourcesModal').on('click', function(){
showLoading();
var layoutid = $('#resourcesModal').find('input[name="layoutid"]:first').val();
$.ajax({
type: 'post',
url: '/resources/' + resource_db_name + '/' + layoutid + '/get',
dataType: 'json',
timeout: 5000,
cache: false,
data: {'resources': $.toJSON(resources[layoutid]), 'resource_category': $.toJSON(resource_category[layoutid])},
success: function (data) {
hideLoading();
$('#resourcesModal').modal('hide');
$('#result-modal').modal('show');
},
});
})
function autoPagination(count, pagesize){
var num = count / pagesize;
self = $('.pagination', '#resourcesModal');
if( num > 1 ){
var pagenum = self.children().length - 2;
if( pagenum > num ){
$('li.hidden', self).removeClass('hidden');
$('li:gt(' + num + '):lt(-1)', self).addClass('hidden');
} else if ( pagenum < num ) {
$('li.hidden', self).removeClass('hidden');
var last = $('li:last', self);
for(var i=pagenum; i < parseInt(num)+1; i++){
last.before('<li><a onClick="gotoPage(this)" name="' + i + '" href="#">' + i + '</a></li>');
}
} else {
$('li.hidden', self).removeClass('hidden');
}
}else{
self.children().addClass('hidden');
}
}
function gotoPage(elm){
var pagenum = $(elm).attr('name');
if( pagenum == 'first' ){
pagenum = '1';
}else if(pagenum == 'last'){
pagenum = $('.pagination li:not(.hidden):eq(-2)>a').attr('name')
}
var category = $('#resources li.active>a').attr('href') == '#resource-category-set';
reloadLayouerUI(category, pagenum, DEFAULT_PAGE_SIZE);
}
function reloadLayouerUI(category, pagenum, pagesize) {
var categoryValue = '';
var hasResource = null;
var container = null;
var layoutid = $('#resourcesModal').find('input[name="layoutid"]:first').val();
if( category ){
categoryValue = '1';
hasResource = resource_category;
container = $('#resource-category-set ul');
}else{
categoryValue = '0';
hasResource = resources;
container = $('#resource-set ul');
}
showLoading();
$.ajax({
type: 'get',
url: '/resources/get?category=' + categoryValue + '&pagenum=' + pagenum + '&pagesize=' + pagesize,
dataType: 'json',
cache: false,
timeout: 5000,
success: function (datas) {
var html = '';
$.each(datas.results, function(i, response){
if( response._id in hasResource[layoutid] ){
html += '<li onClick="addLayoutResource(this)" class="list-group-item disabled" data-category=' + categoryValue + ' name="' + response._id + '"> ' + response.alias + '</li>';
}else{
html += '<li onClick="addLayoutResource(this)" class="list-group-item" data-category=' + categoryValue + ' name="' + response._id + '"> ' + response.alias + '</li>';
}
});
container.html( html );
autoPagination( datas.count, pagesize );
hideLoading();
},
});
}
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import './css/MetamaskDisplay.css';
import Web3 from 'web3'
const web3 = new Web3(global.web3.currentProvider);
const mapStateToProps = (state) => ({
web3Enable: state.metamask.web3Enable,
networkID: state.metamask.networkID,
currentAccount: state.metamask.currentAccount,
addresses: state.addresses.addresses
});
const MapDispatchToProps = (dispatch) => ({
checkWeb3: (payload) => {
dispatch({ type: 'CHECK_WEB3', payload });
},
accountUpdate: (payload) => {
dispatch({ type: 'ACCOUNT_UPDATE', payload });
},
networkUpdate: (payload) => {
dispatch({ type: 'NETWORK_UPDATE', payload });
},
addAddress: (addr) => {
const payload = {
name: 'metamask account',
address: addr
}
dispatch({ type: 'ADD_ADDR', payload });
}
});
class MetamaskDisplay extends Component {
constructor(props) {
super(props);
this.checkWeb3Status = this.checkWeb3Status.bind(this);
this.getCurrentAccount = this.getCurrentAccount.bind(this);
this.getNetwork = this.getNetwork.bind(this);
}
componentDidMount() {
this.checkWeb3Status();
this.getCurrentAccount();
this.getNetwork();
}
checkWeb3Status() {
if (typeof global.web3 !== 'undefined') {
this.props.checkWeb3(true);
} else {
this.props.checkWeb3(false);
}
}
getCurrentAccount() {
// if (!this.props.web3Enable) {
// console.log('web3 object not defined');
// return;
// }
// Get the current account from metamask
web3.eth.getAccounts().then( (accounts) => {
if (accounts[0] !== this.props.currentAccount)
this.props.accountUpdate(accounts[0]);
if(!this.props.addresses.includes(accounts[0])) {
this.props.addAddress(accounts[0]);
}
});
}
getNetwork() {
// if (!this.props.web3Enable) {
// console.log('web3 object not defined');
// return;
// }
// Get the network
web3.eth.net.getId( (err,res) => {
this.props.networkUpdate(res);
});
}
render() {
var network_description = '';
if (this.props.networkID) {
switch (this.props.networkID.toString()) {
case "1":
network_description = 'This is mainnet';
break;
case "2":
network_description = 'This is the deprecated Morden test network';
break;
case "3":
network_description = 'This is the ropsten test network';
break;
case "4":
network_description = 'This is the Rinkeby test network';
break;
case "42":
network_description = 'This is the Kovan test network';
break;
default:
network_description = 'This is an unknown network';
}
}
return (
<div className="MetamaskDisplay">
<div>
<button onClick={this.checkWeb3Status}>
Check Web3
</button>
Metamask status:
{this.props.web3Enable.toString()}
</div>
<div>
<button onClick={this.getCurrentAccount}>
Get Account
</button>
Account:
<span>{this.props.currentAccount}</span>
</div>
<div>
Network ID:
{ this.props.networkID }
<br/>
<button onClick={this.getNetwork}>
Get Network
</button>
Description:
{ network_description }
</div>
</div>
);
}
}
export default connect(
mapStateToProps,
MapDispatchToProps
)(MetamaskDisplay);
|
import styled from "@emotion/styled";
const PopoverContentButton = styled.button`
background: ${(props) => (props.color ? props.color : "#eee")};
padding: 2px 4px;
border-radius: 7px;
opacity: 0.7;
color: white;
text-align: left;
outline: none;
margin: 1px 0;
font-size: 14px;
border: none;
&:hover {
background: ${(props) => (props.hoverColor ? props.hoverColor : "#ddd")};
}
`;
export default PopoverContentButton;
|
import React, {Component} from "react";
import {Field, Form, Formik} from 'formik';
import ProjectDataService from "../../service/ProjectDataService";
import * as Yup from "yup";
class ProjectForm extends Component {
constructor(props) {
super(props)
this.state = {
id: this.props.match.params.id,
name: '',
cost: '',
department: '',
dateBegin: '',
dateEnd: '',
dateEndReal: '',
message: ''
}
this.onSubmit = this.onSubmit.bind(this)
}
componentDidMount() {
if (this.state.id === "new") {
} else {
ProjectDataService.retrieveProject(this.state.id)
.then(response => this.setState({
name: response.data.name,
cost: response.data.cost,
department: response.data.department,
dateBegin: response.data.dateBegin,
dateEnd: response.data.dateEnd,
dateEndReal: response.data.dateEndReal
}))
}
}
onSubmit(values) {
this.setState({message: ''})
let project = {
name: values.name,
cost: values.cost,
department: values.department,
dateBegin: values.dateBegin,
dateEnd: values.dateEnd,
dateEndReal: values.dateEndReal
}
if (this.state.id === "new") {
ProjectDataService.createProject(project)
.then(() => this.props.history.push('/projects'),
error => {
const resMessage =
(error.response &&
error.response.data &&
error.response.data.message) ||
error.message ||
error.toString();
this.setState({
message: resMessage
});
})
} else {
ProjectDataService.updateProject(this.state.id, project)
.then(() => this.props.history.push('/projects'),
error => {
const resMessage =
(error.response &&
error.response.data &&
error.response.data.message) ||
error.message ||
error.toString();
this.setState({
message: resMessage
});
})
}
}
validate(values) {
function process(date) {
var parts = date.split("/");
return new Date(parts[2], parts[1] - 1, parts[0]);
}
let errors = {}
const dateBegin = process(values.dateBegin)
const dateEnd = process(values.dateEnd)
const dateEndReal = process(values.dateEndReal)
if (dateBegin > dateEnd) {
errors.dateEnd = 'Date begin cannot be greater than date end'
} else if (dateBegin > dateEndReal) {
errors.dateEndReal = 'Date begin cannot be greater than date end'
}
return errors
}
dateRegex = /^([0-2][0-9]|(3)[0-1])(\/)(((0)[0-9])|((1)[0-2]))(\/)\d{4}$/
projectSchema = Yup.object().shape({
name: Yup.string()
.min(2, 'Too Short!')
.max(15, 'Too Long!')
.required('Required'),
cost: Yup.number()
.min(1, 'Too Small!')
.max(99999999, 'Too Big!')
.required('Required'),
department: Yup.string()
.min(1, 'Too Short!')
.max(15, 'Too Long...!'),
dateBegin: Yup.string()
.matches(this.dateRegex, "Date must be valid DD/MM/YYYY!"),
dateEnd: Yup.string()
.matches(this.dateRegex, "Date must be valid DD/MM/YYYY!"),
dateEndReal: Yup.string()
.matches(this.dateRegex, "Date must be valid DD/MM/YYYY!"),
})
render() {
let {message, id, name, cost, department, dateBegin, dateEnd, dateEndReal} = this.state
return (
<div className="form">
<h3>Project details</h3>
<div className="formik">
<Formik
initialValues={{id, name, cost, department, dateBegin, dateEnd, dateEndReal}}
onSubmit={this.onSubmit}
validateOnChange={false}
validateOnBlur={false}
validate={this.validate}
validationSchema={this.projectSchema}
enableReinitialize={true}>
{
({errors}) => (
<Form>
{this.state.message && (
<div className="form-group">
<div className="alert alert-danger" role="alert">
{message}
</div>
</div>
)}
<fieldset className="form-group">
<label>Name</label>
<Field className="form-control" type="text" name="name"/>
</fieldset>
{errors.name && (
<div className="alert alert-danger" role="alert">
{errors.name}
</div>)}
<fieldset className="form-group">
<label>Cost</label>
<Field className="form-control" type="text" name="cost"/>
</fieldset>
{errors.cost && (
<div className="alert alert-danger" role="alert">
{errors.cost}
</div>)}
<fieldset className="form-group">
<label>Department</label>
<Field className="form-control" type="text" name="department.name"/>
</fieldset>
{errors.department && (
<div className="alert alert-danger" role="alert">
{errors.department}
</div>)}
<fieldset className="form-group">
<label>Date begin</label>
<Field className="form-control" type="text" name="dateBegin"/>
</fieldset>
{errors.dateBegin && (
<div className="alert alert-danger" role="alert">
{errors.dateBegin}
</div>)}
<fieldset className="form-group">
<label>Date end</label>
<Field className="form-control" type="text" name="dateEnd"/>
</fieldset>
{errors.dateEnd && (
<div className="alert alert-danger" role="alert">
{errors.dateEnd}
</div>)}
<fieldset className="form-group">
<label>Real end date</label>
<Field className="form-control" type="text" name="dateEndReal"/>
</fieldset>
{errors.dateEndReal && (
<div className="alert alert-danger" role="alert">
{errors.dateEndReal}
</div>)}
<button className="btn btn-outline-light" type="submit">Save</button>
</Form>
)
}
</Formik>
</div>
</div>
)
}
}
export default ProjectForm
|
var a = [];
$(window).load(function() {
$('#calc').css("opacity", '0');
$('#calc').animate({
opacity: '1'
}, 300, function() {
a.push(0);
$("span").text(a.join(""));
});
});
$(".bttn").click(function(e) {
$(this).animate({
opacity: 0.8
}, 60);
$(this).animate({
opacity: 1
});
e.preventDefault();
});
document.getElementById("ce").disabled = true;
$(".numb").click(function() {
if (a[0] == 0 && a.length == 1) {
a.pop(0);
$("span").text(a.join(""));
}
$("span").append($(this).text());
a.push($(this).text());
if (a.length > 1) {
var x = $("span").css('left');
x = x.replace("px", "");
parseInt(x);
$("span").css('left', (x - 30) + 'px');
}
});
$("#ac").click(function() {
$("span").animate({
bottom: '20px',
opacity: '0'
}, 300, function() {
$("span").empty();
$("span").attr('style', '');
a.splice(0, a.length);
a.push(0);
$("span").text(a.join(""));
});
//Bhargav was stuck a day in here removing bugs
});
$("#del").click(function() {
if (a.length > 1) {
a.pop();
} else if (typeof a[0] == 'number' && a[0] % 1 == 0) {
a[0] = Math.floor(a[0] / 10);
} else {
a.pop();
a.push(0);
}
$("span").text(a.join(""));
var y = Math.max(a.length, a[0].toString().length);
$("span").css('left', (280 - (29 * (y - 1))) + 'px');
});
$("#equ").click(function() {
$("span").animate({
bottom: '20px',
opacity: '0'
}, 300, function() {
$("span").empty();
$("span").attr('style', '');
var k = a.join("");
var p;
//var p = parseFloat(eval(k));
try {
p = parseFloat(eval(k));
p = p.toFixed(5);
// console.log(p);
p = parseFloat(p);
// console.log(p);
var b = p.toString();
$("span").append(p);
a.splice(0, a.length);
a.push(p);
$("span").css('left', (280 - (29 * (b.length - 1))) + 'px');
} catch (e) {
if (e instanceof SyntaxError) {
console.log(e.message);
a = [0];
$("span").empty();
$("span").text(a.join(""));
}
}
});
});
|
/**
* Created by wuyin on 2016/5/18.
*/
var http = require('http');
var qs = require('querystring');
/**
* 控制路由的功能
* @param path
*/
function rotuteHandle(request) {
if (request.url == '/login' && request.method.toLowerCase() == 'post') {
console.log('获取login的post请求');
return 'post method';
}
return 'get method';
}
/**
* 处理请求的方法
* @param req
* @param resp
*/
function onRequest(req, resp) {
resp.writeHead(200, {
'Content-Type': 'text/plain'
});
var postData = '';
if (req.url == '/login' && req.method.toLowerCase() == 'post') {
/**
* 在Node.js中处理Post请求与Get请求的方式不同,需要单独的处理不像Get可以直接获取
* 需要注册两个listener来实现,分别是data和end的两个listener
* ```
request.addListener('data',function);
request.addListener('end',function);
```
*/
req.addListener('data', function (data) {
postData += data;
console.log('获取post请求参数中。。。。')
});
req.addListener('end', function () {
console.log(postData);
console.log('获取post参数成功');
var content = qs.parse(postData).text;
resp.write(content);
resp.end();
})
} else {
resp.write('other method');
resp.end();
}
}
var server = http.createServer(onRequest);
server.listen(3000);
|
/*
Third party
*/
//= ../../bower_components/jquery/dist/jquery.min.js
//= ../../bower_components/materialize/dist/js/materialize.min.js
/*
Custom
*/
//= partials/common.js
|
const ul = document.querySelector("ul");
ul.addEventListener("click", event => {
// console.log("event----:", event.currentTarget);
// console.log("event----:", event.target);
// event.target.classList.toggle("hightlight");
event.target.closest("li").classList.toggle("hightlight");
});
|
import React from "react";
import { useQuery } from "react-apollo-hooks";
import GET_POSTS from "../../graphql/post/queries/posts";
import Posts from "../Posts";
import Loading from "../Loading";
import PostsContainer from "../styled/PostsContainer";
const Home = () => {
const { data, error, loading } = useQuery(GET_POSTS);
if (loading) return <Loading />;
if (error) return <div>Error! {error.message}</div>;
return (
<PostsContainer>
<Posts posts={data.posts.edges} />
</PostsContainer>
);
};
export default Home;
|
var express = require("express");
var app = express();
var path = require('path');
var mongodb = require('mongodb');
var crypto = require('crypto');
var algorithm = 'aes-256-ctr';
var secret = 'M1lGr4u'
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/baseNodinho';
var bodyparser = require('body-parser');
app.use(bodyparser.json());
function encrypt(v){
var cipher = crypto.createCipher(algorithm,password)
var crypted = cipher.update(v,'utf8','hex')
crypted += cipher.final('hex');
return crypted;
}
app.get("/",function (req, res){
res.status(200).json({message: "Funcionando"});
})
app.post("/autorize",function (req, res){
res.setHeader('Access-Control-Allow-Origin','*');
usuario = req.body.params.usuario;
console.log(usuario);
if(usuario.email == null){
console.error("Ocorreu algum problema");
res.status(500).send('Acontenceu algum problema!');
}else{
MongoClient.connect(url, function (err, db) {
if (err){
console.error(err.stack);
res.status(500).send('Acontenceu algum problema!');
}else {
var collection = db.collection('usuarios');
collection.findOne({email: usuario.email}, function(err, document) {
if (err){
console.error("Ocorreu algum problema");
res.status(500).send('Acontenceu algum problema!');
}else{
v = id + nome;
} res.status(200).json({token: encrypt(v) });
});
//Fecha a conexão
db.close();
}
});
}
})
app.listen(process.env.PORT || 8010, function () {
console.log('Listening on http://localhost:' + (process.env.PORT || 8010));
});
|
import Vue from 'vue'
import App from './App.vue'
import router from './router'
Vue.config.productionTip = false
new Vue({
router,
render: h => h(App),
}).$mount('#app')
// 配置全局自定义设置
import settings from '@/assets/js/settings'
Vue.prototype.$settings = settings;
// axios配置:cnpm install axios
import axios from 'axios'
Vue.prototype.$axios = axios;
|
const props = require('./../resources/application.json');
const zoteroClient = require('zotero-api-client')(props.zotero.apiKey);
function callZoteroApi(){
const myapi = zoteroClient.library(props.zotero.entityType, props.zotero.humanitrackGroupId);
const itemsResponse = myapi.items().get();
return new Promise(resolve => {
resolve(itemsResponse);
});
}
exports.getAndFormatZoteroData = async function(callback) {
const result = await callZoteroApi();
const allResults = [];
const creators = [];
const tags = [];
for(var i = 0; i < result.raw.length; i++){
var data = result.raw[i].data;
if(data["abstractNote"]){
allResults.push([data["key"], data["version"], data["itemType"], data["title"], data["abstractNote"], data["publicationTitle"], data["volume"], data["issue"], data["pages"], data["date"], data["DOI"], data["ISSN"]])
const creatorsData = data["creators"];
const tagsData = data["tags"];
for(var j = 0; j < creatorsData.length; j++){
let creator = [];
creator.push(data["key"]);
creator.push(creatorsData[j].creatorType);
creator.push(creatorsData[j].firstName + " " + creatorsData[j].lastName);
creators.push(creator);
}
for(var j = 0; j < tagsData.length; j++){
let tag = [];
tag.push(data["key"]);
tag.push(tagsData[j].tag);
tags.push(tag);
}
}
}
callback({allResults: allResults, creators: creators, tags: tags});
}
|
function solve(args) {
var nums = args[0].split(' ').map(function(el){
return parseInt(el);
});
var result = 0, currentResult = 0, firstPeak, secondPeak, valley;
for(var i = 0, len = nums.length; i < len; i++){
if(firstPeak) {
currentResult++;
}
// get first peak
if(!firstPeak) {
firstPeak = nums[i];
}
// get the valley
else if(!valley || valley > nums[i]) {
valley = nums[i];
}
// get the second peak
else if(!secondPeak || secondPeak < nums[i]) {
secondPeak = nums[i];
}
// get result
if(secondPeak > nums[i] || i == nums.length - 1) {
if(i < nums.length - 1) {
currentResult--;
}
if(result < currentResult) {
result = currentResult;
}
if(i == nums.length - 1) {
break;
}
currentResult = 0;
firstPeak = secondPeak;
secondPeak = null;
valley = null;
i--;
}
}
return result;
}
var tests = [
["5 1 7 6 3 6 4 2 3 8"]
,
["5 1 7 4 8"],
["10 1 2 3 4 5 4 3 2 1 10"]
];
for(var i = 0, len = tests.length; i < len; i++){
console.log(solve(tests[i]));
}
|
import React, { Component } from 'react';
import './StatusCircle.css';
class StatusCircle extends Component {
state = {
modalOpen: false,
userDetails: ''
};
componentWillMount = () => {
this.setState({
userDetails: JSON.parse(localStorage.getItem('userProfile'))
});
};
render() {
const {
backgroundColor,
foregroundColor,
height,
width,
payload
} = this.props;
return (
<div
className="status-container"
style={{
background: backgroundColor,
color: foregroundColor,
height: height,
width: width
}}
>
<span>{payload}</span>
</div>
);
}
}
export default StatusCircle;
|
import React, {Component} from 'react';
import { Table, Icon, Divider, message, Modal, Form, Input } from 'antd';
import { Link } from 'react-router';
const FormItem = Form.Item;
const formItemLayout = {
labelCol: { span: 4 },
wrapperCol: { span: 16 },
};
class Manage_cont extends Component{
constructor(props){
super(props);
this.state={
visible: false,
confirmLoading: false,//编辑弹窗中 保存按钮loading
editData:{}
};
this.columns = [{
title: '待协同供应商',
dataIndex: 'COMPANY_NAME',
key: 'COMPANY_NAME',
width:250
}, {
title: '主数据编码',
dataIndex: 'MDM_CODE',
key: 'MDM_CODE',
}, {
title: '联系人',
dataIndex: 'CONTACT',
key: 'CONTACT',
}, {
title: '手机',
dataIndex: 'CONTACT_PHONE',
key: 'CONTACT_PHONE',
},{
title: '电子邮箱',
dataIndex: 'EMAIL',
key: 'EMAIL',
},{
title: '调查表状态',
dataIndex: 'QUESTIONNAIRE_STATE',
key: 'QUESTIONNAIRE_STATE',
render: (text, record) => {
let tex = "";
switch (record.QUESTIONNAIRE_STATE) {
case "0":
tex = "未发送";
break;
case "1":
tex = "已发送";
break;
case "2":
tex = "待审核";
break;
case "3":
tex = "未通过";
break;
case "4":
tex = "已通过";
break;
}
return <span>{tex}</span>;
}
},{
title: '供应商状态',
dataIndex: 'DEV_STATE',
key: 'DEV_STATE',
render: (text, record) => {
let tex = "";
switch (record.DEV_STATE) {
case "0":
tex = "待考察";
break;
case "1":
tex = "潜在";
break;
case "2":
tex = "注册";
break;
}
return <span>{tex}</span>;
}
},{
title: '操作',
key: 'action',
width:130,
// “QUESTIONNAIRE_STATE”:(0:未发送,1:已发送,2:未审核,3:未通过,4:已通过) 调查表状态
// "DEV_STATE": "1",(0:待考察;1:潜在;2:注册)供应商状态;
render: (text, record,index) => {
let status = record.QUESTIONNAIRE_STATE+record.DEV_STATE;
let str = null;
// 审核的URL
let url = postName+"/portal/ssoIndex#supplierToviewLook?status=1&option=hideMenu&id="+record.QUESTIONNAIRE_ID;
//查看-已通过:2
let url2 = postName+"/portal/ssoIndex#supplierToviewLook?status=2&option=hideMenu&id="+record.QUESTIONNAIRE_ID;
//查看-未通过:3
let url3 = postName+"/portal/ssoIndex#supplierToviewLook?status=3&option=hideMenu&id="+record.QUESTIONNAIRE_ID;
switch(status){
case "41":
str = <span>
<a href='javascript:void(0)' onClick={()=>this.editContact(record)}>编辑 </a>
<a href={url2}>查看 </a>
<a href="javascript:void(0);" onClick={()=>this.reviewClick(record)}> 重审 </a>
</span>;
break;
case "31":
str = <span>
<a href='javascript:void(0)' onClick={()=>this.editContact(record)}>编辑 </a>
<a href={url3}>查看 </a>
<a href="javascript:void(0);" onClick={()=>this.reviewClick(record)}> 重审 </a>
</span>;
break;
case "21":
str = <span>
<a href='javascript:void(0)' onClick={()=>this.editContact(record)}>编辑 </a>
<a href={url}>审核</a>
</span>;
break;
case "42":
str = <span>
<a href='javascript:void(0)' onClick={()=>this.editContact(record)}>编辑 </a>
<a href={url2}>查看 </a>
<a href="javascript:void(0);" onClick={()=>this.reviewClick(record)}> 重审 </a>
</span>;
break;
case "32":
str = <span>
<a href='javascript:void(0)' onClick={()=>this.editContact(record)}>编辑 </a>
<a href={url3}>查看 </a>
<a href="javascript:void(0);" onClick={()=>this.reviewClick(record)}> 重审 </a>
</span>;
break;
case "22":
str = <span>
<a href='javascript:void(0)' onClick={()=>this.editContact(record)}>编辑 </a>
<a href={url}>审核 </a>
</span>;
break;
case "40":
str = <span>
<a href='javascript:void(0)' onClick={()=>this.editContact(record)}>编辑 </a>
<a href={url2}>查看 </a>
<a href="javascript:void(0);" onClick={()=>this.reviewClick(record)}> 重审 </a>
</span>;
break;
case "30":
str= <span>
<a href='javascript:void(0)' onClick={()=>this.editContact(record)}>编辑 </a>
<a href={url3}>查看 </a>
<a href="javascript:void(0);" onClick={()=>this.reviewClick(record)}> 重审 </a>
</span>;
break;
case "20":
str = <span>
<a href='javascript:void(0) onClick={()=>this.editContact(record)}'>编辑 </a>
<a href={url}>审核 </a>
</span>
break;
case "00":
str = <span>
<a href='javascript:void(0)' onClick={()=>this.editContact(record)}>编辑 </a>
<a href="javascript:void(0);" onClick={()=>this.sendClick(record)}>发送调查表 </a>
</span>
break;
case "10":
str = <span>
<a href='javascript:void(0)' onClick={()=>this.editContact(record)}>编辑 </a>
</span>;
break;
}
return str;
},
}];
}
//编辑
editContact = (record) =>{
this.setState({visible:true,editData:{
contact:record.CONTACT?record.CONTACT:'',
tel:record.CONTACT_PHONE?record.CONTACT_PHONE:'',
email:record.EMAIL?record.EMAIL:'',
EAF_ID:record.EAF_ID
}});
}
//关闭编辑弹窗
handleCancel = () => {
this.setState({ visible: false,confirmLoading: false });
}
//编辑弹窗 保存
handleOk = () =>{
const _this = this;
this.props.form.validateFields((err, values) =>{
console.log(err);
console.log(values);
if(!err){
this.setState({ confirmLoading: true });
ajax({
url: "/txieasyui?taskFramePN=UpdateSupplierPhoneDao&command=UpdateSupplierPhoneDao.UpdateSupplierPhone&colname=json_ajax&colname1={%27dataform%27:%27eui_form_data%27}",
dataType: "json",
type: "GET",
data: {MOBILE:values.TEL,CONTACT_NAME:values.CONTACT,EMAIL:values.EMAIL,EAF_ID:values.EAF_ID},
success: function (result) {
if(result.EAF_ERROR) {
message.error(result.EAF_ERROR);
return;
}
//发送成功后关闭弹窗
_this.setState({ visible: false });
_this.setState({ confirmLoading: false });
//刷新企业供应商列表
_this.props.handleSearch("",2);
},
error: function (res) {
message.error(res.EAF_ERROR);
}
});
}
});
}
// 重审 点击事件
reviewClick = (record) => {
const _this = this;
ajax({
url: "/txieasyui?taskFramePN=AlternativeSupplierDao&command=AlternativeSupplierDao.auditCrCheck&colname=json&refresh=0.9673956279036522&colname1={%27dataform%27:%27eui_form_data%27,%27tablename%27:%27detail0%27}",
dataType: "json",
type: "GET",
data: {"eafId":record.EAF_ID,"supplierId":record.SUPPLIER_ID,"purId":record.PUR_ID},
success: function (result) {
if(result.EAF_ERROR) {
message.error(result.EAF_ERROR);
return;
}
if(result.success=="true"){
//刷新企业供应商列表
_this.props.handleSearch("",2);
}
Modal.info({
title: '提示',
content: (
<div>
<p style={{visibility:"hidden"}}>111 </p>
<p>{result.msg}</p>
</div>
),
onOk() {},
});
},
error: function (res) {
message.error(res.EAF_ERROR);
}
});
}
// 发送调查表 点击事件
sendClick = (record) =>{
const _this = this;
ajax({
url: "/txieasyui?taskFramePN=AlternativeSupplierDao&command=AlternativeSupplierDao.sendQusetionnaire&colname=json&refresh=0.9673956279036522&colname1={%27dataform%27:%27eui_form_data%27,%27tablename%27:%27detail0%27}",
dataType: "json",
type: "GET",
data: {"eafId":record.EAF_ID,"supplierId":record.SUPPLIER_ID,"purId":record.PUR_ID},
success: function (result) {
if(result.EAF_ERROR) {
message.error(result.EAF_ERROR);
return;
}
console.log(result)
if(result.success=="true"){
//刷新企业供应商列表
_this.props.handleSearch("",2);
Modal.info({
title: '提示',
content: (
<div>
<p style={{visibility:"hidden"}}>111 </p>
<p>发送调查表成功。</p>
</div>
),
onOk() {},
});
}else{
Modal.info({
title: '提示',
content: (
<div>
<p style={{visibility:"hidden"}}>111 </p>
<p>发送调查表失败。</p>
</div>
),
onOk() {},
});
}
},
error: function (res) {
message.error(res.EAF_ERROR);
}
});
}
// 分页器初始化
handlePage = () => {
const total = this.props.manageData && this.props.manageData.total * 1;
return (
{
current: this.props.managePage,
defaultCurrent: 1,
defaultPageSize: 10,
showQuickJumper: true,
onChange: (pageNumber) => this.onChangePage(pageNumber),
total: total
}
)
}
//分页发起ajax请求
onChangePage = (page) => {
this.props.hanlePageSearch(page);
}
render(){
const loading = this.props.manageData&&this.props.manageData.rows;
const manageData = this.props.manageData&&this.props.manageData.rows;
const { visible, confirmLoading,editData} = this.state;
const { getFieldDecorator } = this.props.form;
return (
<div>
<Table rowKey={record => record.SUPPLIER_ID} pagination={this.handlePage()} loading={!loading} columns={this.columns} dataSource={manageData} />
<Modal
visible={visible}
title="编辑信息"
onOk={this.handleOk}
onCancel={this.handleCancel}
maskClosable={false}
destroyOnClose={true}
confirmLoading={confirmLoading}
okText="保存"
cancelText="关闭"
>
<div>
<FormItem {...formItemLayout} label="EAF_ID" style={{display:"none"}}>
{getFieldDecorator('EAF_ID', {
initialValue:editData.EAF_ID?editData.EAF_ID:'',
rules: [{
required: false,
message: '联系人不能为空',
}],
})(
<Input />
)}
</FormItem>
<FormItem {...formItemLayout} label="联系人">
{getFieldDecorator('CONTACT', {
initialValue:editData.contact?editData.contact:'',
rules: [{
required: true,
message: '联系人不能为空',
}],
})(
<Input />
)}
</FormItem>
<FormItem {...formItemLayout} label="手机">
{getFieldDecorator('TEL', {
initialValue:editData.tel?editData.tel:'',
rules: [{
required: true,
message: '手机不能为空',
},{
pattern: /(^0{0,1}1[3|4|5|6|7|8|9][0-9]{9}$)/,
message: '手机格式不正确',
}],
})(
<Input />
)}
</FormItem>
<FormItem {...formItemLayout} label="电子邮箱">
{getFieldDecorator('EMAIL', {
initialValue:editData.email?editData.email:'',
rules: [{
required: true,
message: '邮件内容不能为空',
},{
pattern: /(^\s*)\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*(\s*$)/,
message: '邮箱格式不正确',
}],
})(
<Input />
)}
</FormItem>
</div>
</Modal>
</div>
)
}
}
export default Form.create()(Manage_cont);
|
var http = require('http');
var os = require('os');
var servers = [];
var s;
function reqHandler(req, res) {
var clientIP = getLocalIP();
var response = 'Client IP:' + clientIP + '\n' + 'Port: ' + req.socket.remoteAddress + '\n';
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end(response);
console.log({
remoteAddress: req.socket.remoteAddress,
remotePort: req.socket.remotePort,
localAddress: req.socket.localAddress,
localPort: req.socket.localPort,
});
}
for (let port = 8000; port < 8050; port++) {
s = http.createServer(reqHandler);
s.listen(port);
servers.push(s);
}
function getClientIP(req) {
//var strAry = req.connection.remoteAddress.split(':');
//return strAry[strAry.length -1];
//return req.connection.remoteAddress;
console.log("x-forwarded-for %s", req.headers['x-forwarded-for']);
console.log("Remote IP %s", req.connection.remoteAddress);
console.log("IPs %s", req.ips);
return (req.headers['x-forwarded-for'] || '').split(',')[0]
|| req.connection.remoteAddress;
}
function getLocalIP() {
var interfaces = os.networkInterfaces();
var IPv4;
for (var devName in interfaces) {
var iface = interfaces[devName];
for (var i = 0; i < iface.length; i++) {
var alias = iface[i];
if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
IPv4 = alias.address;
}
}
}
return IPv4;
}
|
{
"portfolio":[
{
"title": "Last Botanica in East Harlem",
"type": "Print story",
"pubdate": "October 2013"
},
{
"title": "Food and Poverty",
"type": "Print story",
"pubdate": "November 2013"
},
{
"title": "Co-location",
"type": "Print story",
"pubdate": "December 2013"
}
]
}
|
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
export const Counter = {
template: `<div>{{ count }}</div>`,
computed: {
count() {
return this.$store.state.count;
}
}
};
|
import styled from "styled-components";
const AboutTitle = styled.h1`
text-align: center;
font-size: ${props => props.theme.fontSizes.sizeFive};
color: ${props => props.theme.colors.black.quaternaryBlack};
margin-bottom: 20px;
`;
const AboutText = styled.p`
text-align: center;
font-size: ${props => props.theme.fontSizes.sizeThree};
color: ${props => props.theme.colors.black.quaternaryBlack};
margin-bottom: 20px;
line-height: 140%;
`;
const LabelLink = styled.p`
color: ${props => props.theme.colors.black.quaternaryBlack};
text-align: center;
margin-bottom: 6px;
@media (max-width: 770px) {
display: flex;
flex-direction: column;
margin-bottom: 10px;
&:last-child {
margin-bottom: 0px;
}
};
`;
const StyledLink = styled.a`
color: ${props => props.theme.colors.purple.primaryPurple};
&:hover {
color: ${props => props.theme.colors.purple.tertiaryPurple};
}
transition: color .2s linear;
`;
export { AboutTitle, AboutText, LabelLink, StyledLink }
|
// eslint-disable-next-line import/prefer-default-export
export const store = {
stories: [
{
plot: 'Моя лошадь потрясающая.',
writer: 'Мистер Уибл',
upvotes: 28,
voted: false,
},
{
plot: 'Нарвалы изобрели шашлык.',
writer: 'Мистер Уибл',
upvotes: 8,
voted: false,
},
{
plot: 'Тёмная сторона Силы сильнее',
writer: 'Дарт Вейдер',
upvotes: 52,
voted: false,
},
{
plot: 'Просто так в Мордор не попадёшь',
writer: 'Боромир',
upvotes: 74,
voted: false,
},
],
};
|
//Project 9: Gallery Component
import React from 'react';
import GalleryItem from './GalleryItem';
function Gallery(props) {
return (
<div className="photo-container">
<h2>Images: {props.result} </h2>
<ul>
{props.urls.map((url, index) => <GalleryItem key={index} url={url} />)}
</ul>
</div>
)
}
/*Purpose: h2 tag is programmatically updated with props based on the Search input that updates the photoTheme state in the App component.
Map() is used to iteratively create GalleryItem components with unique key props and urls aside to a url prop from the relevant url state in App. */
export default Gallery;
|
$(document).ready(function(){
Oeasymain2dmap.init();
});
var Oeasymain2dmap = {
caranddoorcount:null,
quxian:function(){
var code = Oeasymain2dmap.GetQueryString('zone');
var quxianmap = null;
var jsonData = null;
$.ajax({
url:oeasymapconfig.echartjson ,
dataType: "json",
async:false,
type: "GET"
}).done(function(_dt){
jsonData=_dt;
});
if(!Oeasymain2dmap.checkcode(code)){
var tempArr=jsonData.features.filter(c=>c.id==code)
jsonData.features.length=1;
jsonData.features[0]=tempArr[0];
}
quxianmap = jsonData;
return quxianmap;
},
GetQueryString:function(name)
{
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
var r = window.location.search.substr(1).match(reg);
if (r != null) return unescape(r[2]); return null;
},
geoCoord : {},
quxianunit:[],
checkcode:function(code){
if(code == oeasymapconfig.city_code){
return true;
}else{
return false;
}
},
init:function(){
//根据参数获取对应的区县数据
var quxiancode = Oeasymain2dmap.GetQueryString('zone');
if(Oeasymain2dmap.checkcode(quxiancode) == true){
$.ajax({
url:oeasymapconfig.unitInfo+"/unit/unitInfo.do" ,
dataType: "json",
type: "POST",
data: {
"province_code":oeasymapconfig.province_code,
"city_code":quxiancode
},
xhrFields: {
withCredentials: true
}
}).done(function(msg){
var data = msg.data;
if(data != null){
if(data.length >0){
for (var i = 0; i < data.length; i++) {
var lng = data[i].lng;
var lat = data[i].lat;
var unitid = data[i].unit_id;
Oeasymain2dmap.geoCoord[unitid] = [lng,lat];
Oeasymain2dmap.quxianunit.push({"unit_id":unitid,"lng":lng,"lat":lat});
}
setTimeout(function(){
var chartOptioncity = Oeasymain2dmap.chartOptionfun();
var myChartcity = echarts.init(document.getElementById('main2dmap'));
myChartcity.setOption(chartOptioncity, true);
},300);
}else{
var chartOptioncity = Oeasymain2dmap.chartOptionfun();
var myChartcity = echarts.init(document.getElementById('main2dmap'));
myChartcity.setOption(chartOptioncity, true);
}
}else{
//chartnounitdata
var chartOptioncitynounit = Oeasymain2dmap.chartnounitdata();
var myChartcitynounit = echarts.init(document.getElementById('main2dmap'));
myChartcitynounit.setOption(chartOptioncitynounit, true);
}
}) .fail(function(jqXHR, textStatus) {
var chartOptioncityerror = Oeasymain2dmap.chartnounitdata();
var myChartcityerror = echarts.init(document.getElementById('main2dmap'));
myChartcityerror.setOption(chartOptioncityerror, true);
});
}else{
$.ajax({
url:oeasymapconfig.unitInfo+"/unit/unitInfo.do" ,
dataType: "json",
type: "POST",
data: {
"province_code":oeasymapconfig.province_code,
"town_code":quxiancode
},
xhrFields: {
withCredentials: true
}
}).done(function(msg){
var data = msg.data;
if(data !=null){
if(data.length >0){
for (var j = 0; j < data.length; j++) {
var lng = data[j].lng;
var lat = data[j].lat;
var unitid = data[j].unit_id;
Oeasymain2dmap.geoCoord[unitid] = [lng,lat];
Oeasymain2dmap.quxianunit.push({"unit_id":unitid,"lng":lng,"lat":lat});
}
setTimeout(function(){
var chartOption = Oeasymain2dmap.chartOptionfun();
var myChart = echarts.init(document.getElementById('main2dmap'));
myChart.setOption(chartOption, true);
},300);
}else{
var chartOption = Oeasymain2dmap.chartOptionfun();
var myChart = echarts.init(document.getElementById('main2dmap'));
myChart.setOption(chartOption, true);
}
}else{
//chartnounitdata
var chartOptiontownnounit = Oeasymain2dmap.chartnounitdata();
var myCharttownnounit = echarts.init(document.getElementById('main2dmap'));
myCharttownnounit.setOption(chartOptiontownnounit, true);
}
}) .fail(function(jqXHR, textStatus) {
var chartOptiontownerror = Oeasymain2dmap.chartnounitdata();
var myCharttownerror = echarts.init(document.getElementById('main2dmap'));
myCharttownerror.setOption(chartOptiontownerror, true);
});
}
//初始化人流车流数据,写入内存
$.ajax({
url:oeasymapconfig.unitCount+"/unit/unitCount.do" ,
dataType: "json",
type: "POST",
data: {
"province_code":oeasymapconfig.province_code,
"city_code":oeasymapconfig.city_code
},
xhrFields: {
withCredentials: true
}
}).done(function(data){
Oeasymain2dmap.caranddoorcount = data;
}).fail(function(jqXHR, textStatus) {
Oeasymain2dmap.caranddoorcount = null;
});
},
chartOptionfun:function(){
var quxiancode = Oeasymain2dmap.GetQueryString('zone');
var series = [ {
name : '昆明市',
type : 'map',
roam : 'move',
hoverable : true,
mapType : '云南',
itemStyle : {
normal : {
borderColor : 'rgba(14,73,117,1)',
borderWidth : 2,
areaStyle : {
color : 'rgba(0,83, 153,1)'
},
label:{
show:true,
textStyle: {
color: "rgb(249, 249, 249)"
}
},
shadowColor: 'rgba(0, 0, 0, 0.5)',
shadowBlur: 10,
shadowOffsetX:50,
shadowOffsetY:-50
},
},
data : [],
markLine : {
smooth : true,
symbol : [ 'none', 'circle' ],
symbolSize : 1,
itemStyle : {
normal : {
color : '#fff',
borderWidth : 1,
borderColor : 'rgba(30,144,255,0.5)'
}
},
data : [
], //无用的轨迹线,暂时去掉
},
geoCoord : Oeasymain2dmap.geoCoord
}];
for (var i=0;i<Oeasymain2dmap.quxianunit.length;i++){
var lng = Oeasymain2dmap.quxianunit[i].lng;
var lat = Oeasymain2dmap.quxianunit[i].lat;
var unitid = Oeasymain2dmap.quxianunit[i].unit_id;
var tt = i+1;
if (tt <Oeasymain2dmap.quxianunit.length){
var unitid1 = Oeasymain2dmap.quxianunit[tt].unit_id;
var num = parseInt(Math.random()*100);
var route1 = [
[{name:unitid}, {name:unitid1,value:num}]
];
var routenames1 = [
{name:unitid,value:num}
];
var routepoint = {
name : '小区',
type : 'map',
mapType : '云南',
data : [],
markPoint : {
symbol : 'emptyCircle',
symbolSize : function(v) {
return 10 + v / 10
},
effect : {
show : true,
shadowBlur : 0
},
itemStyle : {
normal : {
label : {
show : false
}
},
emphasis : {
label : {
position : 'top',
show:false
}
}
},
data : routenames1
}
};
series.push(routepoint);
}
}
var option = {
backgroundColor : 'rgba(6, 24, 64,0.9)',
color : [ 'gold', 'aqua', 'lime' ],
title : {
text : '',
subtext : '',
x : 'center',
textStyle : {
color : '#fff'
}
},
tooltip : {
trigger : 'item',
backgroundColor:'rgba(49,206,199,0.7)',
formatter : function (params) {
var unitid = '';
unitid = params.name.toString();
var str = '';
if(unitid != '' && unitid !=null){
//根据小区的经度和纬度,调用小区的当日人流和车流数据
if(unitid.indexOf(">") == -1){
if(/^[\u3220-\uFA29]+$/.test(unitid)){
//如果是中文,则是区县提示文字
str = unitid;
}else{
//小区点上的提示,人流量和车流量
if(Oeasymain2dmap.caranddoorcount){
for(k=0;k<Oeasymain2dmap.caranddoorcount.length;k++){
if(unitid == Oeasymain2dmap.caranddoorcount[k].unit_id){
str += Oeasymain2dmap.caranddoorcount[k].name+'<br/>';
str += '今日人流:'+Oeasymain2dmap.caranddoorcount[k].doorCount+'<br/>';
str += '今日车流:'+Oeasymain2dmap.caranddoorcount[k].carCount+'<br/>';
}
}
}else{
str += unitid+'<br/>';
str += '今日人流:0'+'<br/>';
str += '今日车流:0'+'<br/>';
}
}
}
}
return str;
}
},
dataRange : {
show : false,
min : 0,
max : 100,
calculable : true,
color : [ '#ff3333', 'orange', 'yellow', 'lime', 'aqua' ],
textStyle : {
color : '#fff'
}
},
series : series
};
return option
},
chartnounitdata:function(){
var quxiancode = Oeasymain2dmap.GetQueryString('zone');
var series = [ {
name : '昆明市',
type : 'map',
roam : 'move',
hoverable : true,
mapType : '云南',
itemStyle : {
normal : {
borderColor : 'rgba(14,73,117,1)',
borderWidth : 2,
areaStyle : {
color : 'rgba(0,83, 153,1)'
},
label:{
show:true,
textStyle: {
color: "rgb(249, 249, 249)"
}
},
shadowColor: 'rgba(0, 0, 0, 0.5)',
shadowBlur: 10,
shadowOffsetX:50,
shadowOffsetY:-50
},
},
data : [],
markLine : {
smooth : true,
symbol : [ 'none', 'circle' ],
symbolSize : 1,
itemStyle : {
normal : {
color : '#fff',
borderWidth : 1,
borderColor : 'rgba(30,144,255,0.5)'
}
},
data : [
], //无用的轨迹线,暂时去掉
},
geoCoord : []
}];
var option = {
backgroundColor : 'rgba(6, 24, 64,0.9)',
color : [ 'gold', 'aqua', 'lime' ],
title : {
text : '',
subtext : '',
x : 'center',
textStyle : {
color : '#fff'
}
},
tooltip : {
trigger : 'item',
backgroundColor:'rgba(49,206,199,0.7)',
formatter : '{b}'
},
dataRange : {
show : false,
min : 0,
max : 100,
calculable : true,
color : [ '#ff3333', 'orange', 'yellow', 'lime', 'aqua' ],
textStyle : {
color : '#fff'
}
},
series : series
};
return option
},
return3dgispage:function(){
top.location.href = oeasymapconfig.return3dgispage ;
},
};
|
//1是post请求,2是put请求,3是get请求
import { post, put, get, del } from './request';
//登录
export function toLogin(user) {
return post({
url: '/login',
params: user,
});
}
//获取菜单列表
export function getMenuList() {
return post({
url: '/menus',
});
}
//用户列表
export function getUserList(queryInfo) {
return get({
url: '/users',
method: 'get',
params: queryInfo,
});
}
//修改用户状态
export function changeUserState(uId, type) {
return put({
url: '/users/' + uId + '/state/' + type,
});
}
//添加用户
export function addUsers(queryInfo) {
return post({
url: '/users',
method: 'post',
data: queryInfo,
});
}
//查询用户
export function searchUsers(id) {
return get({
url: '/users/' + id,
});
}
//编辑用户信息并提交
export function submitUsers(id, queryInfo) {
return put({
url: '/users/' + id,
data: queryInfo,
});
}
export function deleteUsers(id) {
return del({
url: '/users/' + id,
});
}
|
import React from 'react'
export default props => (
<h1>1 - {props.value}</h1>
)
export const Segundo = props => (
<h1>2 - {props.value}</h1>
)
// export { Primeiro, Segundo }
|
OperacionesManager.module("ContratoApp.Disolucion", function(Disolucion, OperacionesManager, Backbone, Marionette, $, _){
Disolucion.Layout = Marionette.LayoutView.extend({
template: "#tpl-detalle",
regions: {
lateral: "#lateral",
principal: "#principal",
},
});
Disolucion.Principal = Marionette.ItemView.extend({
template: "#tpl-disolucion-crear",
className: "principal-container",
events: {
"keyup #inputDescuentoCrear": "mostrarResultado",
"click #buttonDisolucionCrear": "guardarDisolucion",
},
onRender: function(){
$('.points').each(function(){
var v_pound = $(this).html();
v_pound = numberWithCommas(v_pound);
$(this).html(v_pound);
});
},
mostrarResultado: function(){
var descuento = this.$el.find('#inputDescuentoCrear').val();
var resultado = descuento
this.$el.find('#resultadoDisolucionCrear').html(resultado);
$('.points').each(function(){
var v_pound = $(this).html();
v_pound = numberWithCommas(v_pound);
$(this).html(v_pound);
});
},
guardarDisolucion: function(e){
e.preventDefault();
var motivo = this.$el.find('#inputMotivoCrear').val();
var descuento = this.$el.find('#inputDescuentoCrear').val();
var valor = this.model.get('valor') - descuento;
var codigo = this.model.get('codigo').toString();
var _ = this;
$.ajax({
data: {
descuento: descuento,
valor: valor,
motivo: motivo,
contrato:codigo,
},
url: '/ajax/disoluciones/guardar-disolucion/',
type: 'POST',
success: function(data) {
_.limpiar();
console.log("Disolucion guardado");
Backbone.history.navigate("contratos/" + codigo + "/disoluciones", {trigger: true});
}
});
},
limpiar: function(){
this.$el.find('#inputDescuentoCrear').val("");
this.$el.find('#inputMotivoCrear').val("");
}
});
Disolucion.Contrato = Marionette.ItemView.extend({
template: "#tpl-detalle-contrato",
});
Disolucion.Disolucion = Marionette.ItemView.extend({
template: "#tpl-disolucion-item",
className: "principal-container",
events: {
'click .item-boton': 'reversarDisolucion',
},
reversarDisolucion: function(e) {
e.preventDefault();
var pk_disolucion = e.currentTarget.dataset.pk;
$.ajax({
data: {pk_disolucion: pk_disolucion, pk_contrato: this.model.get("id")},
type: "POST",
url: "/ajax/disoluciones/reversar/",
success: function(data) {
console.log(data);
}
});
},
onRender: function(){
$('.points').each(function(){
var v_pound = $(this).html();
v_pound = numberWithCommas(v_pound);
$(this).html(v_pound);
});
},
});
});
|
const checkboxStyle = {
margin: '7px 5px'
}
export {
checkboxStyle
}
|
const express = require('express')
const app = express()
const api = require('./routes/api')
const bodyParser = require('body-parser')
const path=require('path')
app.use(express.static(path.join(__dirname,'..','node_modules')))
app.use(express.static(path.join(__dirname,'..','dist')))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
app.use( '/', api )
// Mongoose setup
const mongoose = require('mongoose')
mongoose.connect(process.env.MONGODB_URI||'mongodb://localhost/weatherapp', { useNewUrlParser: true })
const port = 3000
app.listen(process.env.port || port, function () {
console.log(`Running on port ${port}`)
})
|
//@flow
import React, {Component} from 'react';
import autobind from 'class-autobind';
import {FlatList} from 'react-native';
import {List, ListItem, Avatar} from 'react-native-elements';
import {DismissKeyboardView} from '../../../components/core';
import {NoItemFound} from '../../../components';
import styles, {AVATAR_SIZE} from './ListView-style';
import type {Presenter} from '../../../data/presenter/Presenter-type';
import type {NavigationScreenProp} from 'react-navigation';
import DEFAULT_AVATAR from '../../../assets/images/default-profile-pic.png';
type Props = {
navigation: NavigationScreenProp<*>,
presenterList: Map<string, Presenter>,
searchValue: string,
};
type PresenterListItem = {
item: Presenter,
index: number,
};
export default class PresenterListView extends Component<Props, void> {
props: Props;
constructor() {
super(...arguments);
autobind(this);
}
render() {
let {presenterList, searchValue} = this.props;
let data = this._getFilteredData(presenterList, searchValue);
return (
<List containerStyle={styles.listContainer}>
<FlatList
ListEmptyComponent={() => {
return (
<DismissKeyboardView
style={[styles.listContainer, styles.noItemFound]}
>
<NoItemFound text="No Presenters Found" />
</DismissKeyboardView>
);
}}
data={data}
renderItem={this._renderItem}
keyExtractor={(item) => item.id}
/>
</List>
);
}
_getFilteredData(data: Map<string, Presenter>, filterValue: string) {
return Array.from(data.values()).filter((presenter: Presenter) => {
return presenter.name.toLowerCase().includes(filterValue.toLowerCase());
});
}
_renderItem({item: presenter}: PresenterListItem) {
let {navigate} = this.props.navigation;
let avatarProps = presenter.profilePictureUri || DEFAULT_AVATAR;
return (
<ListItem
key={presenter.id}
roundAvatar
hideChevron
title={presenter.name}
subtitle={`${presenter.jobTitle}, ${presenter.companyName}`}
avatar={
<Avatar
rounded
source={avatarProps}
width={AVATAR_SIZE}
height={AVATAR_SIZE}
avatarStyle={styles.avatarContainer}
/>
}
containerStyle={styles.itemContainer}
onPress={() => navigate('PresenterDetailScene', {presenter})}
/>
);
}
}
|
import React, { useContext } from 'react';
import AudioPlayer from './AudioPlayer';
import ProfileContext from '../../context/profile/profileContext';
const AudioContainer = () => {
const profileContext = useContext(ProfileContext);
const { isMusic, toggleMusic } = profileContext;
return (
<div className="audio-container">
<div className="audio-command">
<i className={`fas ${isMusic ? 'fa-stop' : 'fa-play'}`} onClick={toggleMusic}></i>
</div>
{
isMusic &&
<AudioPlayer />
}
</div>
);
}
export default AudioContainer;
|
import React, { useState, useEffect } from "react";
import axios from "axios";
import Folder from './Folder'
import Content from './Content';
import FolderIcon from '@material-ui/icons/Folder';
import ExpandMoreIcon from '@material-ui/icons/ExpandMore';
import { makeStyles } from '@material-ui/core/styles';
import { Grid, Card, CardActions, CardContent, Button, Paper, Accordion, AccordionDetails, AccordionSummary, Typography } from '@material-ui/core/';
import {
BrowserRouter as Router,
Switch,
Route,
Link,
useHistory,
useLocation,
useParams,
} from "react-router-dom";
import { Redirect } from 'react-router'
import Menu from '@material-ui/core/Menu';
import MenuItem from '@material-ui/core/MenuItem';
import Dialog from '@material-ui/core/Dialog';
import DialogActions from '@material-ui/core/DialogActions';
import DialogContent from '@material-ui/core/DialogContent';
import DialogContentText from '@material-ui/core/DialogContentText';
import DialogTitle from '@material-ui/core/DialogTitle';
import TextField from '@material-ui/core/TextField';
import UploadContent from "../components/staff/UploadContent"
import Snackbar from '@material-ui/core/Snackbar';
import MuiAlert from '@material-ui/lab/Alert';
import CircularProgress from '@material-ui/core/CircularProgress';
import NavFolder from "./NavFolder"
function Alert(props) {
return <MuiAlert elevation={6} variant="filled" {...props} />;
}
const useStyles = makeStyles((theme) => ({
rootAccordion: {
width: '100%',
// marginBottom : "15px"
},
heading: {
fontSize: theme.typography.pxToRem(15),
flexBasis: '33.33%',
flexShrink: 0,
},
secondaryHeading: {
fontSize: theme.typography.pxToRem(15),
color: theme.palette.text.secondary,
},
progress: {
display: 'flex',
margin: "0% auto",
alignItems: "center",
position: "absolute",
top: "50%",
bottom: "50%",
right: "50%",
'& > * + *': {
marginLeft: theme.spacing(2),
}
},
// rootPaper: {
// display: "flex",
// flexWrap: "wrap",
// width: "250px",
// height: "20%",
// cursor: "pointer",
// margin: "0px 0px 30px 30px",
// padding: "10px 0",
// position: "relative",
// },
// rootFolderIcon: {
// display: "inline",
// // alignItems: "center",
// width: "2.3em",
// height: "3em",
// padding: "3px",
// margin: "auto 5px",
// // float: "left",
// },
// rootFolderName: {
// // display: "inline",
// display: "flex",
// alignItems: "center",
// fontSize: "1em",
// // fontSize: "1.2vw",
// // fontWeight: "600",
// margin: "auto 5px",
// width: "150px",
// height: "50px",
// // textAlign: "left",
// position: "absolute",
// top: "20%",
// left: "25%",
// // float: "left",
// },
root: {
flexGrow: 1,
},
}));
const Dashboard = () => {
const classes = useStyles();
const [anchorEl, setAnchorEl] = React.useState(null);
const handleClose = () => {
setAnchorEl(null);
setAddNewFolderName("")
};
const handleClick = (event, isOneClick) => {
if (isOneClick)
setAnchorEl(event.currentTarget);
};
const handleCloseMessage = (event, reason) => {
if (reason === 'clickaway') {
return;
}
setOpenMessage(false);
};
const [subFolders, setSubFolders] = useState();
const [contents, setContents] = useState();
const [loadingSubFolders, setLoadingSubFolders] = useState(true);
const [threeDots, setThreeDots] = useState(false);
const [foldersChanged, setFoldersChanged] = useState(true);
const [isExpand, setIsExpand] = useState(false);
const [navs, setNavs] = useState([{ _id: "", folderName: "Dashboard" }]);
const [courseID, setCourseID] = useState()
const [openAdd, setOpenAdd] = useState(false);
const [addNewFolderName, setAddNewFolderName] = useState("");
const [openMessage, setOpenMessage] = useState(false);
const [MessageText, setMessageText] = useState();
const [openUpload, setOpenUpload] = useState(false);
let history = useHistory()
let rootFolder = useParams().folderID
const token = localStorage.getItem('token')
const userID = localStorage.getItem('userID')
const role = localStorage.getItem('role')
const auth = {
headers: { token }
}
useEffect(() => {
if (!rootFolder) {
axios.get(`http://localhost:8080/courses/${userID}`, auth)
.then(res => {
setSubFolders(res.data)
setLoadingSubFolders(true)
setThreeDots(false)
})
.catch(err => console.log(err))
}
else {
axios.get(`http://localhost:8080/courses/folder/${rootFolder}`, auth)
.then(res => {
setSubFolders(res.data.subFolders)
setLoadingSubFolders(false)
setThreeDots(true)
setNavsPro(res.data.folderName)
setContents(res.data.contents.reverse())
setFoldersChanged(false)
})
.catch(err => console.log(err))
}
}, [rootFolder, foldersChanged])
const handleDoubleClickFn = (rootFolderParam, isThreeDotsClicked) => {
if (!isThreeDotsClicked)
history.push(`${rootFolderParam}`)
}
const setNavsPro = async (folderName) => {
const dashboard = { _id: "", folderName: "Dashboard" }
const last = { _id: rootFolder, folderName: folderName }
let navArr = []
let changingRootFolder = rootFolder;
try {
while (changingRootFolder != null) {
let res = await axios.get(`http://localhost:8080/courses/rootFolder/${changingRootFolder}`, auth)
if (!res.data)
break
navArr.push(res.data)
changingRootFolder = res.data._id
}
navArr.push(dashboard)
const result = navArr.reverse()
result.push(last)
// console.log("navs from setNavs pro =>>>> ", result)
setNavs(result)
if (result[1] && result[1].folderName) {
const start = result[1].folderName.lastIndexOf("(") + 1
const end = result[1].folderName.lastIndexOf(")")
const code = result[1].folderName.substring(start, end)
let codeResult = await axios.get(`http://localhost:8080/courses/code/${code}`)
setCourseID(codeResult.data._id)
}
} catch (error) {
console.log(error)
}
}
const addFolder = async () => {
console.log(addNewFolderName)
try {
const res = await axios.post(`http://localhost:8080/courses/createFolder/${rootFolder}`, { folderName: addNewFolderName })
setOpenAdd(false)
setOpenMessage(true)
setMessageText(`${addNewFolderName} folder added successfully !`)
setAddNewFolderName("")
setAnchorEl(null);
setFoldersChanged(true);
// setTimeout(() => {
// window.location.reload()
// }, 2400)
} catch (error) {
console.log(error.response.data)
}
}
const setFoldersChangedFN = (bool) => {
setFoldersChanged(bool)
}
const closeDialogContent = () => {
setOpenUpload(false)
}
return (
<div className="container-fluid">
{!subFolders ? <CircularProgress color="secondary" className={classes.progress} /> :
<div className={classes.rootAccordion}>
{navs.length !== 0 && <NavFolder
isExpand={isExpand}
navs={navs}
// setNewNavs={setNavsPro}
/>}
<Accordion defaultExpanded={true}>
<AccordionSummary expandIcon={<ExpandMoreIcon />}>
<Typography className={classes.heading}>Folders ({subFolders.length})</Typography>
</AccordionSummary>
<AccordionDetails>
<div className={classes.root}>
<div className="container-fluid">
<div className="row gx-4">
{
subFolders.map(item => {
return (
<Folder
add={handleClick}
folderClicked={handleDoubleClickFn}
isOneClick={false}
// threeDotsClicked={isThreeDotsClicked}
// setThreeDotsClicked={setThreeDotsClicked}
rootFolder={item._id}
folderName={item.folderName}
role={role}
threeDots={threeDots}
folderChanged={setFoldersChangedFN}
key={item._id}
/>
)
})
}
{
!loadingSubFolders && role === "staff" &&
<>
<Folder
add={handleClick}
// folderClicked={handleAddSubFolderOrContentFn}
isOneClick={true}
// threeDotsClicked={isThreeDotsClicked}
rootFolder={rootFolder}
folderName="Add Folder/Content"
role={role}
/>
<Menu
id="simple-menu"
anchorEl={anchorEl}
keepMounted
open={Boolean(anchorEl)}
onClose={handleClose}
>
<MenuItem onClick={() => setOpenAdd(true)}>Add Folder</MenuItem>
<MenuItem onClick={() => setOpenUpload(true)}>Upload Content</MenuItem>
</Menu>
{/* Dialog to add new folder */}
{
openAdd &&
<>
<Dialog open={openAdd} onClose={() => setOpenAdd(false)} aria-labelledby="form-dialog-title">
<DialogTitle id="form-dialog-title">Add New Folder</DialogTitle>
<DialogContent>
<DialogContentText>
To add a new folder, please enter folder name here.
</DialogContentText>
<TextField
autoFocus
// defaultValue={discussionData.text}
value={addNewFolderName}
onChange={(e) => setAddNewFolderName(e.target.value)}
margin="dense"
id="name"
label="New Text"
type="text"
fullWidth
/>
</DialogContent>
<DialogActions>
<Button onClick={() => { setOpenAdd(false); setAddNewFolderName("") }} color="primary">
Cancel
</Button>
<Button onClick={addFolder} color="primary">
Add
</Button>
</DialogActions>
</Dialog>
</>
}
{
openMessage &&
<Snackbar open={openMessage} autoHideDuration={2500} onClose={handleCloseMessage}>
<Alert onClose={handleCloseMessage} severity="success">
{MessageText}
</Alert>
</Snackbar>
}
{
openUpload ? <UploadContent isOpen={true} isClosed={closeDialogContent} folderChanged={setFoldersChangedFN} courseID={courseID} />
:
<UploadContent isOpen={false} isClosed={closeDialogContent} folderChanged={setFoldersChangedFN} courseID={courseID} />
}
</>
}
</div>
</div>
</div>
</AccordionDetails>
</Accordion>
</div>
}
{
contents &&
<div className={classes.rootAccordion}>
<Accordion defaultExpanded={true}>
<AccordionSummary expandIcon={<ExpandMoreIcon />}>
<Typography className={classes.heading}>Contents ({contents.length})</Typography>
</AccordionSummary>
<AccordionDetails>
<div className="container">
<div className="row gx-4">
{
contents.map(content => {
return <Content
key={content}
contentID={content}
token={token}
folderChanged={setFoldersChangedFN}
/>
})
}
</div>
</div>
</AccordionDetails>
</Accordion>
</div>
}
</div >
)
}
export default Dashboard
|
const lista = () => {
return `
`
}
exports.lista = lista
|
const postfix = "_content_li";
const goTo = function(seqno) {
window.open("https://cafe.naver.com/destinychild/" + seqno);
}
let sheet = null;
const head = document.head || document.getElementsByTagName('head')[0];
const contentsBody = document.getElementById("contentsBody");
const writeData = function(contents) {
if (sheet != null) head.removeChild(sheet);
sheet = document.createElement('style');
const classified = Object.keys(contents);
const contentsBodyElements = [];
for (let i in classified) {
const keyword = classified[i];
if (keyword == 'isFirst') continue;
const sheet_str = "h2." + keyword + " { background: url('images/" + keyword + ".png') no-repeat;" +
" background-size: contain;" +
" padding-left: 40px; }";
sheet.type='text/css';
sheet.appendChild(document.createTextNode(sheet_str));
head.appendChild(sheet);
contentsBodyElements.push("<section class='section_", keyword, "'>");
contentsBodyElements.push("<div class='title'>");
contentsBodyElements.push("<h2 class='", keyword, "'> ", contents[keyword].label, "</h2>");
contentsBodyElements.push("</div>");
contentsBodyElements.push("<div class='content'>");
contentsBodyElements.push("<ul id='", keyword, postfix, "'>");
const elements = contents[keyword].contents;
for (let i in elements) {
const element = elements[i];
// liElements.push("<li onclick='goTo(" + element.seqno + ")'>[" + element.category + "] " + element.summary + "(" + element.title + " by." + element.author+ ") - " + element.registered + "</li>")
contentsBodyElements.push("<li><span onclick='goTo(" + element.seqno + ")'>[" + categories[element.category].label + "] " + element.title + " - by." + element.author+ " - " + element.registered + "</span></li>")
}
contentsBodyElements.push("</ul>");
contentsBodyElements.push("</div>");
contentsBodyElements.push("</section>");
}
contentsBody.innerHTML = contentsBodyElements.join('');
};
const writeDataByLevel = function() {
if (levels.isFirst === true) {
levels.isFirst = false;
for (let i in contents) {
const content = contents[i];
levels[content.level].contents.push(content);
}
}
writeData(levels);
};
writeDataByLevel();
const writeDataByCategory = function() {
if (categories.isFirst === true) {
categories.isFirst = false;
for (let i in contents) {
const content = contents[i];
categories[content.category].contents.push(content);
}
}
writeData(categories);
};
|
sap.ui.jsview("enterFioriConfiguration", {
getControllerName: function() {
return null;
},
/**
*
* @param oController may be null
* @returns {sap.ui.cre.Control}
*/
createContent: function(oController) {
var jsView = this;
var data = window.iab.context;
if (data.fioriConfiguration == null) {
data.fioriConfiguration = "";
}
// create JSON model instance
var oModel = new sap.ui.model.json.JSONModel();
// set the data for the model
oModel.setData(data);
// set the model to the core
sap.ui.getCore().setModel(oModel);
// This function calculates how wide the vbox containing all the controls should be.
var calculateDisplayWidth = function(totalWidth) {
var displayWidth = 0;
if (totalWidth <= 360) {
displayWidth = totalWidth*0.9;
} else {
// On a wide screen, use a little more space
displayWidth = 324 + ((totalWidth - 360)*0.1);
}
return Math.round(displayWidth);
}
var vbox = new sap.m.VBox('EnterFioriConfiguration');
var inputConfiguration = new sap.m.Input( 'configuration_input', {
value:"{/fioriConfiguration}",
placeholder:"Enter Fiori URL or Work Email",
liveChange:function(){
inputConfiguration.setValueState(sap.ui.core.ValueState.None);
valueStateErrorControl = null;
}
});
var valueStateErrorControl = null;
if (data.valueStateText != null) {
inputConfiguration.setValueStateText(data.valueStateText);
inputConfiguration.setValueState(sap.ui.core.ValueState.Error);
valueStateErrorControl = inputConfiguration;
}
var helpText = new sap.m.Text( 'configuration_text', {
text:"Enter the Fiori URL or your Work Email address, as indicated in the instructions from your IT Administrator."
});
var panel = new sap.m.Panel( 'configuration_text_panel', {
content: [helpText]
});
var buttonOKPress = function() {
buttonOK.setEnabled(false);
if (inputConfiguration.getValue()) {
inputConfiguration.setValue(inputConfiguration.getValue().trim());
}
setTimeout(function(){
// fix bcp issue: error message shows up and then disappear in ios by moving validation to here
// we would need to refactor or clean up later
function isEmail(emailAddress) {
if (typeof(emailAddress) !== 'string') {
return false;
}
var regexp = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/;
var result = regexp.test(emailAddress);
console.log("check email format: " + result);
return result;
};
function isUrl(url) {
if (typeof(url) !== 'string') {
return false;
}
var regexp = /^(http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
var result = regexp.test(url);
console.log("check URL format: " + result);
return result;
};
if (!(isUrl(inputConfiguration.getValue()) || isEmail(inputConfiguration.getValue()))) {
inputConfiguration.setValueStateText("Invalid Fiori URL. Please enter the SAP Fiori configuration again");
inputConfiguration.setValueState(sap.ui.core.ValueState.Error);
inputConfiguration.focus();
buttonOK.setEnabled(true);
return ;
}
data.fioriConfiguration = inputConfiguration.getValue();
window.iab.triggerEvent("SUBMIT", JSON.stringify(data));
buttonOK.setEnabled(true);
}, 500);
}
var buttonOK = new sap.m.Button( 'button_ok', {
type:sap.m.ButtonType.Emphasized,
text:"OK",
width:"100%",
press : buttonOKPress
});
var vboxPlaceholder1 = new sap.m.HBox( 'vbox_placeholder1', {
height:"75px"
});
var vboxPlaceholder2 = new sap.m.HBox( 'vbox_placeholder2', {
height:"25px"
});
var vboxPlaceholder3 = new sap.m.HBox( 'vbox_placeholder3', {
height:"25px"
});
vbox.addItem(vboxPlaceholder1);
vbox.addItem(inputConfiguration);
vbox.addItem(vboxPlaceholder2);
vbox.addItem(panel);
vbox.addItem(vboxPlaceholder3);
vbox.addItem(buttonOK);
vboxPageContent = new sap.m.VBox('vbox_content', {
alignItems:sap.m.FlexAlignItems.Center,
justifyContent:sap.m.FlexJustifyContent.Start,
items:[vbox]
});
var sapLogo = new sap.m.Image( 'sap_logo', {
src:"img/sapLogo.png",
height:"40px"
});
var copyright = new sap.m.Text( 'copyright', {
text:"Copyright \u00A9 2014 SAP SE. All rights reserved."
});
var footerHBox = new sap.m.HBox('panel_hbox', {
justifyContent:sap.m.FlexJustifyContent.SpaceBetween,
alignItems:sap.m.FlexAlignItems.Start,
width: "90%",
items: [sapLogo, copyright]
});
vboxOuter = new sap.m.FlexBox('vbox_outer', {
direction:sap.m.FlexDirection.Column,
justifyContent:sap.m.FlexJustifyContent.SpaceBetween,
alignItems:sap.m.FlexAlignItems.Center,
items:[vboxPageContent, footerHBox],
fitContainer: true
});
// If the screen width is available, pre-calculate how wide the vbox should be
// so that the user can't see it draw as the wrong size then quickly redraw as
// the correct size.
if ($(window).width()) {
vbox.setWidth(calculateDisplayWidth($(window).width()) + "px");
copyright.setWidth(Math.round($(window).width()/2) + "px");
}
sap.ui.core.ResizeHandler.register(vboxOuter, function(e){
vbox.setWidth(calculateDisplayWidth(e.size.width) + "px");
copyright.setWidth(Math.round(e.size.width/2) + "px");
var domRef = jsView.getDomRef();
if( $(window).height() && $(window).height() > domRef.offsetHeight) {
// The view is not taking up the whole screen height, force it.
jsView.setHeight($(window).height() + "px");
}
});
vboxPageContent.onAfterRendering = function() {
var inputs = this.$().find(':input');
inputs.attr('autocapitalize', 'off');
inputs.attr('autocorrect', 'off');
inputs.attr('autocomplete', 'off');
if (valueStateErrorControl != null) {
// Do the work in a setTimeout because otherwise the focus gets stolen
// away (and if the focus is not on the input control then the value
// state text is not visible).
setTimeout(function(){
valueStateErrorControl.focus();
},400);
}
sap.m.FlexBox.prototype.onAfterRendering.apply(this, arguments);
}
window.iab.page.setShowHeader(false);
window.iab.heightWithoutKeyboard = null;
this.onAfterRendering = function() {
var domRef = this.getDomRef();
if( $(window).height() && $(window).height() > domRef.offsetHeight) {
// The view is not taking up the whole screen height, force it.
this.setHeight($(window).height() + "px");
window.iab.heightWithoutKeyboard = $(window).height();
}
}
window.onkeyup = function(e) {
var key = e.keyCode ? e.keyCode : e.which;
if (key == 13) {
// GO button pressed on Android keyboard
buttonOKPress();
}
}
return vboxOuter;
}
});
|
import express from 'express';
import http from 'http';
import socketIo from 'socket.io';
import fetch from 'node-fetch';
const port = process.env.PORT || 4000;
const index = require('./routes/index');
const app = express();
app.use(index);
const server = http.createServer(app);
const io = socketIo(server);
io.on('connection', socket => {
console.log('New client connected'), setInterval(
() => getApiAndEmit(socket),
10000
);
socket.on('disconnect', () => console.log('Client disconnected'));
});
const getApiAndEmit = async socket => {
const url =
'http://api.openweathermap.org/data/2.5/weather?q=Berlin,de&&appid=<the api key>';
try {
const response = await fetch(url).then(res => res.json()).then(res => res);
socket.emit('FromAPI', response);
} catch (error) {
console.error(`Error: ${error}`);
}
};
server.listen(port, () => console.log(`Listening on port ${port}`));
|
module.exports = {
threadBombandoK: 5,
threadBombando: 5000,
};
|
// Diffuse
// https://learnopengl.com/Lighting/Basic-Lighting
const vs_diffuse = `#version 300 es
precision mediump float;
in vec3 position;
in vec3 normal;
out vec4 worldNormal;
out vec3 toLightVector;
uniform mat4 projectionMatrix;
uniform mat4 transformationMatrix;
uniform mat4 normalMatrix;
uniform mat4 viewMatrix;
uniform vec3 lightPosition;
void main ( void )
{
// Because position can change direction when model is translated/scaled/rotated
vec4 worldPosition = transformationMatrix * vec4( position, 1.0 );
// Because normal can change direction when model is rotated
worldNormal = normalMatrix * vec4( normal, 0.0 );
// Vector pointing from vertex to light
toLightVector = lightPosition - worldPosition.xyz;
//
gl_Position = projectionMatrix * viewMatrix * worldPosition;
}
`;
|
import React from "react";
import PropTypes from "prop-types";
const Btn = (props) => {
const styles = [ "btn", props.styles ].join(" ");
return (
<button className={styles} onClick={props.click}>
{props.children}
</button>
);
};
Btn.propTypes = {
click: PropTypes.func.isRequired,
styles: PropTypes.string
};
export default Btn;
|
module.exports = {
fxb: {
'secret': '2FAsecret',
'username': 'email',
'password': 'pass',
'accountID': 'account id you get calling GetUserInfo function',
'OMSId': 'OMSId you get calling GetUserInfo function'
},
mbtc: {
'name': 'Botv3',
'id': 'id',
'secret': 'secret',
'pin': 'pin'
},
btd: 'ApiToken xxx',
bzx: {
key: 'key',
secret: 'secret'
}
}
|
import React from 'react';
const NewList = () => {
return (
<div>
NewList
</div>
);
};
export default NewList;
|
var db = require ('./mysql.js');
exports.getHomePage = function(req,res){
res.sendFile(path.join(__dirname+ '/index.html'));
}
exports.getChatHistory = function(req,res){
var data = req.body;
var chathistory = db.getAllMsgforRoom(data.id);
console.log(chathistory)
res.send(chathistory);
}
exports.addMsgToRoom = function(id,msg){
db.addMsgToRoom(id,msg);
}
exports.createRoom = function(req,res){
// var data = req.body;
// var chathistory = db.getAllMsgforRoom(data.id);
// console.log(chathistory)
// res.send(chathistory);
}
|
$(document).ready(function () {
initpersonal();
});
var url = window.location.href;
var userId = url.substring(url.lastIndexOf('=') + 1);
function getSecurityClearanceLookup() {
var apiUrlSecurityCleareance = GetWebAPIURL() + '/api/Lookup/?name=SecurityClearance';
var dataSecurityCleareanceObj;
//To get details of security cleareance lookup
$.ajax({
url: apiUrlSecurityCleareance,
type: 'GET',
async: false,
headers: app.securityHeaders(),
contentType: "application/json; charset=utf-8",
success: function (data) {
dataSecurityCleareanceObj = data;
},
error: function (xhr, status, error) {
alert('Error :' + status);
}
});
return dataSecurityCleareanceObj;
}
function getWillingToRelocateLookup() {
var apiUrlWillingToRelocate = GetWebAPIURL() + '/api/Lookup/?name=WillingToRelocate';
var dataWillingToRelocate;
//TO get details of willing to relocate lookup details
$.ajax({
url: apiUrlWillingToRelocate,
type: 'GET',
async: false,
headers: app.securityHeaders(),
contentType: "application/json; charset=utf-8",
success: function (data) {
dataWillingToRelocate = data;
},
error: function (xhr, status, error) {
alert('Error :' + status);
}
});
return dataWillingToRelocate;
}
var selectedPersonalObj;
function getJobseekerPersonalInfo() {
var apiUrlOverview = GetWebAPIURL() + 'api/Overview/'; // + userId;
var dataObjOverview;
//To get overview details
$.ajax({
url: apiUrlOverview,
type: 'GET',
async: false,
headers: app.securityHeaders(),
contentType: "application/json; charset=utf-8",
success: function (data) {
dataObjOverview = data;
},
error: function (xhr, status, error) {
alert('Eroooror :' + status);
}
});
selectedPersonalObj = dataObjOverview;
return dataObjOverview;
}
function initpersonal() {
viewModel.errorCheckSecurity = ko.observable('0');
viewModel.errorCheckRelocate = ko.observable('0');
viewModel.errorCheckIndustry = ko.observable('0');
viewModel.myinfoid = ko.observable();
viewModel.personalCheck = ko.observable('0');
viewModel.jobseekerId = ko.observable();
viewModel.isEditablePersonal = ko.observable(false);
viewModel.btnPersonal = ko.observable("Edit");
// viewModel.industriesTextbox = ko.observable().extend({ required: { message: "Industry required" } });
viewModel.specialityTextbox = ko.observable().extend({ required: { message: "Speciality required" } });
viewModel.industryTypeId = ko.observableArray();
viewModel.industryType = ko.observableArray();
viewModel.IndustryName = ko.observableArray();
var dataIndustryTypeObj = getIndustryTypeLookup();
for (da in dataIndustryTypeObj) {
viewModel.industryType.push({ name: dataIndustryTypeObj[da].Name, id: dataIndustryTypeObj[da].Id });
}
viewModel.selectedIndexSecurity = ko.observable(0);
viewModel.dataSecurity = ko.observable(createListSecurity());
viewModel.selectedIndexRelocate = ko.observable(0).extend({ required: { message: "Select Willing to relocate" } });
viewModel.dataRelocate = ko.observable(createListRelocate());
var dataSecurityCleareanceObj = getSecurityClearanceLookup();
var dataWillingToRelocate = getWillingToRelocateLookup();
var dataObjOverview = getJobseekerPersonalInfo();
if (dataObjOverview) {
viewModel.myinfoid(dataObjOverview.Id);
viewModel.jobseekerId(dataObjOverview.JobSeekerId);
if (dataObjOverview.Speciality) {
//viewModel.industriesTextbox(dataObjOverview.Industry);
viewModel.specialityTextbox(dataObjOverview.Speciality);
//viewModel.industryTypeId(dataObjOverview.Industry);
viewModel.personalCheck('1');
if (dataObjOverview.SecurityClearanceId) {
for (da in dataSecurityCleareanceObj) {
if (dataObjOverview.SecurityClearanceId == dataSecurityCleareanceObj[da].Id) {
viewModel.selectedIndexSecurity((parseInt(da) + 1));
}
}
}
if (dataObjOverview.WillingToRelocateId) {
for (da in dataWillingToRelocate) {
if (dataObjOverview.WillingToRelocateId == dataWillingToRelocate[da].Id) {
viewModel.selectedIndexRelocate((parseInt(da) + 1));
}
}
}
if (dataObjOverview.Industry) {
var getIndustryType = dataObjOverview.Industry;
var getIndustryId = getIndustryType.split(',');
for (var index = 0; index < getIndustryId.length; index++) {
viewModel.industryTypeId.push(getIndustryId[index]);
}
//viewModel.accountStatusCheck('1');
getIndustryName(dataObjOverview.Industry);
}
}
}
viewModel.SecurityCleareanceLabel = ko.computed(function () {
return viewModel.dataSecurity()[viewModel.selectedIndexSecurity()].label;
}, this);
viewModel.WillingToRelocateLabel = ko.computed(function () {
return viewModel.dataRelocate()[viewModel.selectedIndexRelocate()].label;
}, this);
/* viewModel.industriesTextbox = ko.computed(function () {
for (var j = 0; j < viewModel.industryType().length; j++) {
if (viewModel.industryTypeId() == viewModel.industryType()[j].id)
return viewModel.industryType()[j].name;
}
}, viewModel);*/
viewModel.displayErrorsPersonal = ko.observable(false);
viewModel.errorPersonalInformation = ko.validation.group({ p2: viewModel.specialityTextbox });
}
function getIndustryName(Industry) {
viewModel.IndustryName.removeAll();
//var dataObjOverview = getJobseekerPersonalInfo();
//var getIndustryType = Industry;
var getIndustryId = Industry.split(',');
for (var j = 0; j < viewModel.industryType().length; j++) {
for (var index = 0; index < getIndustryId.length; index++) {
if (viewModel.industryType()[j].id == getIndustryId[index]) {
viewModel.IndustryName.push(viewModel.industryType()[j].name);
}
}
}
return viewModel.IndustryName();
}
function createListSecurity() {
var dataSecurityCleareanceObj = getSecurityClearanceLookup();
var list = [];
list.push({ label: "Select", value: "" });
for (da in dataSecurityCleareanceObj) {
list.push({
label: dataSecurityCleareanceObj[da].Name,
value: dataSecurityCleareanceObj[da].Id
});
}
return list;
}
function createListRelocate() {
var dataWillingToRelocate = getWillingToRelocateLookup();
var list = [];
list.push({ label: "Select", value: "" });
for (da in dataWillingToRelocate) {
list.push({
label: dataWillingToRelocate[da].Name,
value: dataWillingToRelocate[da].Id
});
}
return list;
}
viewModel.whichTemplateToUsePersonal = function () {
return viewModel.isEditablePersonal() ? "EditPersonalInformation" : "ViewPersonalInformation";
}
viewModel.savePersonal = function () {
if (viewModel.industryTypeId()!="" && viewModel.specialityTextbox.isValid() && viewModel.selectedIndexSecurity() > 0 && viewModel.selectedIndexRelocate() > 0) {
var dataObjOverview = getJobseekerPersonalInfo();
var dataObjMyInfo;
var jobSeekerMyInfoObj = {}
var jsonObject = ko.toJS(viewModel);
if (dataObjOverview) {
jobSeekerMyInfoObj.JobSeekerId = userId;
jobSeekerMyInfoObj.Summary = dataObjOverview.Summary;
jobSeekerMyInfoObj.CurrentStatus = dataObjOverview.CurrentStatus;
jobSeekerMyInfoObj.Industry = jsonObject.industryTypeId.toString();
jobSeekerMyInfoObj.Speciality = jsonObject.specialityTextbox;
jobSeekerMyInfoObj.SecurityClearanceId = viewModel.dataSecurity()[viewModel.selectedIndexSecurity()].value;
jobSeekerMyInfoObj.WillingToRelocateId = viewModel.dataRelocate()[viewModel.selectedIndexRelocate()].value;
dataObjMyInfo = JSON.stringify(jobSeekerMyInfoObj);
}
else {
jobSeekerMyInfoObj.JobSeekerId = userId;
jobSeekerMyInfoObj.Industry = jsonObject.industryTypeId.toString();
jobSeekerMyInfoObj.Speciality = jsonObject.specialityTextbox;
jobSeekerMyInfoObj.SecurityClearanceId = viewModel.dataSecurity()[viewModel.selectedIndexSecurity()].value;
jobSeekerMyInfoObj.WillingToRelocateId = viewModel.dataRelocate()[viewModel.selectedIndexRelocate()].value;
dataObjMyInfo = JSON.stringify(jobSeekerMyInfoObj);
}
if (jsonObject.myinfoid) {
var apiUrlMyInfoUpdate = GetWebAPIURL() + 'api/Overview/' + jsonObject.myinfoid;
//To update overview table
$.ajax({
url: apiUrlMyInfoUpdate,
type: "PUT",
data: dataObjMyInfo,
headers: app.securityHeaders(),
contentType: "application/json; charset=utf-8",
async: false,
success: function (data) {
viewModel.btnPersonal("Edit");
viewModel.isEditablePersonal(false);
getIndustryName(jobSeekerMyInfoObj.Industry);
},
error: function (xhr, error) {
alert('Error :' + error);
}
});
}
else {
var apiUrlMyInfoUpdate = GetWebAPIURL() + '/api/Overview/';
//To insert details into Overview table
$.ajax({
url: apiUrlMyInfoUpdate,
type: "POST",
data: dataObjMyInfo,
headers: app.securityHeaders(),
contentType: "application/json; charset=utf-8",
async: false,
success: function (data) {
viewModel.myinfoid(data);
viewModel.btnPersonal("Edit");
viewModel.isEditablePersonal(false);
getIndustryName(jobSeekerMyInfoObj.Industry);
},
error: function (xhr, error) {
alert('Error :' + error);
}
});
}
viewModel.errorCheckSecurity('0');
viewModel.errorCheckRelocate('0');
viewModel.errorCheckIndustry('0');
}
else {
viewModel.errorPersonalInformation.showAllMessages();
viewModel.displayErrorsPersonal(true);
if (viewModel.selectedIndexRelocate() <= 0) {
viewModel.errorCheckRelocate('1');
}
else { viewModel.errorCheckRelocate('0'); }
if (viewModel.selectedIndexSecurity() <= 0) {
viewModel.errorCheckSecurity('1');
}
else { viewModel.errorCheckSecurity('0'); }
if (viewModel.industryTypeId() == "") {
viewModel.errorCheckIndustry('1');
}
else { viewModel.errorCheckIndustry('0'); }
}
}
viewModel.cancelPersonal = function () {
personalObj = ko.toJS(viewModel);
if (personalObj.myinfoid) {
// viewModel.industriesTextbox(selectedPersonalObj.Industry);
viewModel.specialityTextbox(selectedPersonalObj.Speciality);
viewModel.selectedIndexSecurity(selectedSecurity);
viewModel.selectedIndexRelocate(selectedRelocate);
viewModel.btnPersonal("Edit");
}
viewModel.isEditablePersonal(false);
viewModel.errorCheckSecurity('0');
viewModel.errorCheckRelocate('0');
}
var selectedSecurity;
var selectedRelocate;
viewModel.clickButtonPersonal = function () {
selectedSecurity = viewModel.selectedIndexSecurity();
selectedRelocate = viewModel.selectedIndexRelocate();
viewModel.btnPersonal("Submit");
viewModel.isEditablePersonal(true);
}
viewModel.addFirstPersonalInformation = function () {
viewModel.btnPersonal("Submit");
viewModel.isEditablePersonal(true);
viewModel.personalCheck('1');
this.jobseekerId(userId);
}
ko.validation.init({
registerExtenders: true,
messagesOnModified: true,
insertMessages: true
});
|
var supertest = require("supertest");
var should = require("should");
var mode = process.env.NODE_TLS_REJECT_UNAUTHORIZED=0;
// This agent refers to PORT where program is runninng.
var server = supertest.agent("https://localhost:8000");
// UNIT test begin
describe("Results testing",function(){
// #1 should return contacts representation in j son
it("should return all results",function(done){
// calling home page api
server
.get("/memberarea/fixtures")
.expect("Content-type",/json/)
.expect(200) // THis is HTTP response
.end(function(err,res){
// HTTP status should be 200
res.status.should.equal(200);
done();
});
});
it("should add a new result",function(done){
// post to /memberarea/fixtures
server.post('/memberarea/fixtures')
.send({HomeTeam:'1g7700uh', AwayTeam:"r1g7u70011ls", referee:"1lgug77100"})
.expect("Content-type", /json/)
.expect(201)
.end(function(err,res){
//console.log(res)
if (err) {
throw err
};
console.log(res.status);
res.status.should.equal(201);
done();
});
});
/*it("should delete a fixture",function(done){
// calling home page api
server
.get("/memberarea/fixtures")
.expect("Content-type", /json/) // Get fixtures working but cannot read property of expect undefined
.expect(200) // THis is HTTP response
.end(function(err,res){
console.log(err)
console.log(res)
const id = res.body[0]._id;
console.log(res)
server
.delete("/memberarea/fixtures/:id"+id)
console.log(res)
.expect("Content-type",/json/)
.expect(200) // THis is HTTP response
.end(function(err,res){
console.log(res)
res.body._id.should.equal(id);
//res.body.should.have.property("HomeTeam");
done();
});
});
});
*/
});
|
{ { { {var sera = 'Será?'} } } }
console.log(sera)
function teste(){
var local = 123
}
teste()
//console.log(local) //caso a variável seja declarado dentro de uma funçaõ o seu escopo de acesso se limita a mesma.
|
var scrollTransition_elemList = [];
document.addEventListener('DOMContentLoaded', scrollTransition_getElements);
function scrollTransition_getElements() {
var bufferArray = [];
bufferArray = document.getElementsByClassName('intro__content');
addBufferedItems();
bufferArray = document.getElementsByClassName('skills__content');
addBufferedItems();
bufferArray = document.getElementsByClassName('projects__content');
addBufferedItems();
bufferArray = document.getElementsByClassName('experience__content');
addBufferedItems();
bufferArray = document.getElementsByClassName('fun__content');
addBufferedItems();
bufferArray = document.getElementsByClassName('contact__content');
addBufferedItems();
function addBufferedItems() {
var i = 0;
while (i < bufferArray.length) {
scrollTransition_elemList[scrollTransition_elemList.length] = bufferArray[i];
i++;
}
bufferArray = [];
}
// console.log(scrollTransition_elemList);
}
function scrollTransition_toggle() {
var distanceToTop = [];
var i = 0;
while (i < scrollTransition_elemList.length) {
distanceToTop[i] = scrollTransition_elemList[i].getBoundingClientRect().top - (document.documentElement.clientHeight * 0.8);
if (distanceToTop[i] < 0) {
scrollTransition_elemList[i].classList.remove('content-hidden');
}
else {
scrollTransition_elemList[i].classList.add('content-hidden');
}
i++;
}
// console.log(distanceToTop[1]);
// console.log(scrollTransition_elemList[1]);
}
setInterval(scrollTransition_toggle, 250);
|
import React, {useState, useEffect, useContext } from 'react'
import { auth } from '../firebase/firebaseConfig'
const AuthContext = React.createContext()
//hook(a) para acceder al contexto
const useAuth = () =>{
return useContext(AuthContext)
}
const AuthProvider = ({children}) => {
const [usuario,cambiarUsuario] = useState()
// estado para chequear cuando cargue el usuario
const [cargando,cambiarCargando] = useState(true)
// efecto para ejecutar si hay usuario, solo se comprueba una vez
useEffect(()=>{
const cancelarSuscripcion = auth.onAuthStateChanged((user)=>{
cambiarUsuario(user)
cambiarCargando(false)
})
// para cuando cerremos sesion
return cancelarSuscripcion
},[])
return (
<AuthContext.Provider value={{usuario:usuario}}>
{/* solamente retornamos los hijos cuando no este cargando
ya cuando cargue retornar los children*/}
{!cargando && children}
</AuthContext.Provider>
);
}
export {AuthProvider, AuthContext, useAuth};
|
function setup() {
oma10930;
}
function draw() {
}
|
odoo.define('avd_pos.pos_customer_required', function (require) {
"use strict";
var screens = require('point_of_sale.screens');
var gui = require('point_of_sale.gui');
var core = require('web.core');
var _t = core._t;
var models = require('point_of_sale.models');
models.load_models({
model: 'province',
fields: ['name', 'code'],
loaded: function(self,province){
// self.product_loc_qty = qty;
},
});
models.load_models({
model: 'canton',
fields: ['name', 'code', 'province_id'],
loaded: function(self,canton){
// self.product_loc_qty = qty;
},
});
models.load_models({
model: 'district',
fields: ['name', 'code', 'canton_id'],
loaded: function(self,district){
// self.product_loc_qty = qty;
},
});
models.load_models({
model: 'locality',
fields: ['name', 'code', 'district_id'],
loaded: function(self,locality){
// self.product_loc_qty = qty;
},
});
screens.PaymentScreenWidget.include({
validate_order: function(options) {
if(!this.pos.get('selectedOrder').get_client()){
this.gui.show_popup('error',{
'title': _t('Order cannot be confirmed'),
'body': _t('Please select a customer for this order.'),
});
return;
}
return this._super(options);
}
});
var _show_screen_ = gui.Gui.prototype.show_screen;
gui.Gui.prototype.show_screen = function(screen_name, params, refresh){
if(this.pos.config.require_customer == 'order'
&& !this.pos.get('selectedOrder').get_client()
&& screen_name != 'clientlist'){
_show_screen_.call(this, screen_name, params, refresh);
screen_name = 'clientlist';
}
_show_screen_.call(this, screen_name, params, refresh);
};
var _super_posmodel = models.PosModel.prototype;
models.PosModel = models.PosModel.extend({
initialize: function (session, attributes) {
var partner_model = _.find(this.models, function(model){
return model.model === 'res.partner';
});
partner_model.fields.push('fax_no');
partner_model.fields.push('province_id');
partner_model.fields.push('canton_id');
partner_model.fields.push('district_id');
partner_model.fields.push('locality_id');
partner_model.fields.push('phone');
return _super_posmodel.initialize.call(this, session, attributes);
},
});
});
|
import { run } from '@ember/runloop';
import { defer, reject, resolve } from 'rsvp';
import { module, skip } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { find, render, click, settled, waitUntil } from '@ember/test-helpers';
import { test, testBS4, defaultButtonClass } from '../../helpers/bootstrap-test';
import { gte } from 'ember-compatibility-helpers';
import hbs from 'htmlbars-inline-precompile';
import setupNoDeprecations from '../../helpers/setup-no-deprecations';
import a11yAudit from 'ember-a11y-testing/test-support/audit'
module('Integration | Component | bs-button', function(hooks) {
setupRenderingTest(hooks);
setupNoDeprecations(hooks);
hooks.beforeEach(function() {
this.actions = {};
this.send = (actionName, ...args) => this.actions[actionName].apply(this, args);
});
test('button has correct default markup', async function(assert) {
await render(hbs`{{#bs-button}}Test{{/bs-button}}`);
assert.dom('button').hasClass('btn', 'button has btn class');
assert.dom('button').hasClass(defaultButtonClass(), 'button has type class');
});
test('button has correct size', async function(assert) {
await render(hbs`{{#bs-button size="lg"}}Test{{/bs-button}}`);
assert.dom('button').hasClass('btn-lg', 'button has size class');
});
test('button has correct type', async function(assert) {
await render(hbs`{{#bs-button type="primary"}}Test{{/bs-button}}`);
assert.dom('button').hasClass('btn', 'button has btn class');
assert.dom('button').hasClass('btn-primary', 'button has type class');
assert.dom('button').doesNotHaveClass('btn-outline-primary', 'button does not have outline class');
});
test('button can be active', async function(assert) {
await render(hbs`{{#bs-button active=true}}Test{{/bs-button}}`);
assert.dom('button').hasClass('active', 'button has active class');
});
test('button can be block', async function(assert) {
await render(hbs`{{#bs-button block=true}}Test{{/bs-button}}`);
assert.dom('button').hasClass('btn-block', 'button has block class');
});
test('button has HTML attributes', async function(assert) {
await render(hbs`{{#bs-button id="test" disabled=true title="title"}}Test{{/bs-button}}`);
assert.equal(this.element.querySelector('button').getAttribute('id'), 'test');
assert.equal(this.element.querySelector('button').getAttribute('disabled'), '');
assert.equal(this.element.querySelector('button').getAttribute('title'), 'title');
assert.deprecationsInclude('Argument disabled of <BsButton> component is deprecated.');
assert.deprecationsInclude('Argument title of <BsButton> component is deprecated.');
});
test('button has default label', async function(assert) {
await render(hbs`{{bs-button defaultText="test"}}`);
assert.dom('button').hasText('test');
});
test('button has default type "button"', async function(assert) {
await render(hbs`{{bs-button}}`);
assert.equal(this.element.querySelector('button').type, 'button');
});
test('buttonType property allows changing button type', async function(assert) {
await render(hbs`{{bs-button buttonType="submit"}}`);
assert.dom('button').hasAttribute('type', 'submit');
assert.deprecationsInclude('Argument buttonType of <BsButton> component is deprecated.');
});
test('button with icon property shows icon', async function(assert) {
await render(hbs`{{bs-button icon="fas fa-check"}}`);
assert.dom('button i').hasClass('fas');
assert.dom('button i').hasClass('fa-check');
});
testBS4('button with outline property shows as outline', async function(assert) {
await render(hbs`{{bs-button type="primary" outline=true}}`);
assert.dom('button').hasClass('btn-outline-primary');
assert.dom('button').doesNotHaveClass('btn-primary');
});
test('button with iconActive and iconInactive properties shows icon depending on active state', async function(assert) {
this.set('active', false);
await render(hbs`{{bs-button active=active iconInactive="fas fa-plus" iconActive="fas fa-minus"}}`);
assert.dom('button i').hasClass('fas');
assert.dom('button i').hasClass('fa-plus');
this.set('active', true);
assert.dom('button i').hasClass('fas');
assert.dom('button i').hasClass('fa-minus');
this.set('active', false);
assert.dom('button i').hasClass('fas');
assert.dom('button i').hasClass('fa-plus');
});
test('clicking a button sends onClick action with "value" property as a parameter', async function(assert) {
let action = this.spy();
this.actions.testAction = action;
await render(hbs`{{bs-button onClick=(action "testAction") value="dummy"}}`);
await click('button');
assert.ok(action.calledWith('dummy'), 'onClick action has been called with button value');
});
test('button text is changed according to button state', async function(assert) {
let deferredClickAction = defer();
this.set('clickAction', () => {
return deferredClickAction.promise;
});
await render(
hbs`{{bs-button
defaultText="default text"
pendingText="text for pending state"
fulfilledText="text for fulfilled state"
rejectedText="text for rejected state"
onClick=clickAction
}}`);
assert.dom('button').hasText('default text');
click('button');
await waitUntil(() => {
return find('button').textContent.trim() === 'text for pending state';
});
deferredClickAction.resolve();
await settled();
assert.dom('button').hasText('text for fulfilled state');
deferredClickAction = defer();
click('button');
await waitUntil(() => {
return find('button').textContent.trim() === 'text for pending state';
});
deferredClickAction.reject();
await settled();
assert.dom('button').hasText('text for rejected state');
});
test('button text remains to default if no state text wasn\'t set', async function (assert) {
let deferredClickAction = defer();
this.set('clickAction', () => {
return deferredClickAction.promise;
});
await render(
hbs`{{bs-button
defaultText="default text"
onClick=clickAction
}}`);
assert.dom('button').hasText('default text');
click('button');
await waitUntil(() => {
return find('button').textContent.trim() === 'default text';
});
deferredClickAction.resolve();
await settled();
assert.dom('button').hasText('default text');
deferredClickAction = defer();
click('button');
await waitUntil(() => {
return find('button').textContent.trim() === 'default text';
});
deferredClickAction.reject();
await settled();
assert.dom('button').hasText('default text');
});
test('setting reset to true resets button text', async function(assert) {
this.set('clickAction', () => {
return resolve();
});
await render(hbs`
{{bs-button defaultText="default text" fulfilledText="text for fulfilled state" reset=reset onClick=clickAction}}
`);
assert.dom('button').hasText('default text');
await click('button');
assert.dom('button').hasText('text for fulfilled state');
run(() => this.set('reset', true));
assert.dom('button').hasText('default text');
});
test('button is disabled while in pending state', async function(assert) {
let deferredClickAction = defer();
this.set('clickAction', () => {
return deferredClickAction.promise;
});
await render(hbs`{{bs-button onClick=clickAction}}`);
assert.dom('button').isNotDisabled();
await click('button');
assert.dom('button').isDisabled();
deferredClickAction.resolve();
await settled();
assert.dom('button').isNotDisabled();
});
test('button is not disabled while in pending state if preventConcurrency is false', async function(assert) {
let deferredClickAction = defer();
this.set('clickAction', () => {
return deferredClickAction.promise;
});
await render(hbs`<BsButton @onClick={{clickAction}} @preventConcurrency={{false}} />`);
await click('button');
assert.dom('button').isNotDisabled();
deferredClickAction.resolve();
await settled();
});
test('setting @disabled property to false prevents button from being disabled while in pending state', async function(assert) {
let deferredClickAction = defer();
this.set('clickAction', () => {
return deferredClickAction.promise;
});
await render(hbs`<BsButton @disabled={{false}} @onClick={{clickAction}} />`);
await click('button');
assert.dom('button').isNotDisabled();
assert.deprecationsInclude('Argument disabled of <BsButton> component is deprecated.');
deferredClickAction.resolve();
await settled();
});
(gte('3.4.0') ? test : skip)('setting disabled HTML attribute to false prevents button from being disabled while in pending state', async function(assert) {
let deferredClickAction = defer();
this.set('clickAction', () => {
return deferredClickAction.promise;
});
await render(hbs`<BsButton @onClick={{clickAction}} disabled={{false}} />`);
await click('button');
assert.dom('button').isNotDisabled();
deferredClickAction.resolve();
await settled();
});
test('isPending, isFulfilled and isRejected properties are yielded', async function (assert) {
let deferredClickAction = defer();
this.set('clickAction', () => {
return deferredClickAction.promise;
});
await render(hbs`{{#bs-button reset=reset onClick=clickAction as |button|}}
{{#if button.isPending}}isPending{{/if}}
{{#if button.isFulfilled}}isFulfilled{{/if}}
{{#if button.isRejected}}isRejected{{/if}}
{{/bs-button}}`);
assert.dom('button').hasText('');
click('button');
await waitUntil(() => {
return find('button').textContent.trim() === 'isPending';
});
deferredClickAction.resolve();
await settled();
assert.dom('button').hasText('isFulfilled');
deferredClickAction = defer();
click('button');
await waitUntil(() => {
return find('button').textContent.trim() === 'isPending';
});
deferredClickAction.reject();
await settled();
assert.dom('button').hasText('isRejected');
run(() => this.set('reset', true));
assert.dom('button').hasText('');
});
test('isSettled shorthand is yielded', async function (assert) {
this.set('clickAction', () => {
return resolve();
});
await render(hbs`{{#bs-button reset=reset onClick=clickAction as |button|}}
{{#if button.isSettled}}isSettled{{/if}}
{{/bs-button}}`);
assert.dom('button').hasText('');
await click('button');
assert.dom('button').hasText('isSettled');
run(() => this.set('reset', true));
assert.dom('button').hasText('');
this.set('clickAction', () => {
return reject();
});
await click('button');
assert.dom('button').hasText('isSettled');
});
test('clicking a button with onClick action will prevent event to bubble up', async function(assert) {
let buttonClick = this.spy();
this.actions.buttonClick = buttonClick;
let parentClick = this.spy();
this.actions.parentClick = parentClick;
await render(
hbs`<div {{action "parentClick"}}>{{#bs-button onClick=(action "buttonClick")}}Button{{/bs-button}}</div>`
);
await click('button');
assert.ok(buttonClick.called);
assert.notOk(parentClick.called);
});
test('clicking a button without onClick action will cause event to bubble up', async function(assert) {
let parentClick = this.spy();
this.actions.parentClick = parentClick;
await render(hbs`<div {{action "parentClick"}}>{{#bs-button}}Button{{/bs-button}}</div>`);
await click('button');
assert.ok(parentClick.called);
});
test('clicking a button with onClick action and bubble=true will cause event to bubble up', async function(assert) {
let buttonClick = this.spy();
this.actions.buttonClick = buttonClick;
let parentClick = this.spy();
this.actions.parentClick = parentClick;
await render(
hbs`<div {{action "parentClick"}}>{{#bs-button bubble=true onClick=(action "buttonClick")}}Button{{/bs-button}}</div>`
);
await click('button');
assert.ok(buttonClick.called);
assert.ok(parentClick.called);
});
test('prevents onClick action to be fired concurrently', async function(assert) {
let deferredClickAction = defer();
let clickActionHasBeenExecuted = false;
this.set('clickAction', () => {
clickActionHasBeenExecuted = true;
return deferredClickAction.promise;
});
await render(hbs`{{bs-button onClick=clickAction}}`);
click('button');
await waitUntil(() => clickActionHasBeenExecuted);
this.set('clickAction', () => {
assert.ok(false, 'onClick action is not executed concurrently');
});
await click('button');
deferredClickAction.resolve();
await settled();
this.set('clickAction', () => {
assert.step('onClick action');
});
await click('button');
assert.verifySteps(['onClick action'], 'onClick action is fired again after pending click action is settled');
});
test('preventConcurrency=false allows onClick action to be fired concurrently', async function(assert) {
let deferredClickAction = defer();
let clickActionExecutionCount = 0;
this.set('clickAction', () => {
clickActionExecutionCount++;
return deferredClickAction.promise;
});
await render(hbs`{{bs-button onClick=clickAction preventConcurrency=false}}`);
await click('button');
assert.equal(clickActionExecutionCount, 1);
await click('button');
assert.equal(clickActionExecutionCount, 2);
deferredClickAction.resolve();
});
test('it passes accessibility checks', async function (assert) {
await render(hbs`{{#bs-button}}Test{{/bs-button}}`);
await a11yAudit();
assert.ok(true, 'A11y audit passed');
});
});
|
var moment = require('moment');
var Scheduler = function () {
this.schedule = function(job) {
for (var i = 0; i < job.count; i++) {
var time = this.pluckBetween(job.start, job.end);
var delta = time - parseInt(moment().format('x'));
setTimeout(function() {
job.f.apply(global, job.args);
}, delta);
var timeString = this.formatUnixTime(time);
var fName = job.f.name;
console.log("Scheduled job `%s` for %s", fName, timeString);
}
},
this.pluckBetween = function(start, end) {
return Math.floor(Math.random() * (end - start)) + start;
},
this.formatUnixTime = function(time) {
return moment(time).format("ddd MMMM Do YYYY HH:mm:ss");
}
};
module.exports = new Scheduler();
|
const api = new Promise((resolve, reject) => {
if (Math.random() > 0.5) resolve("Sucesso");
resolve("Falha");
});
api
.then((res) => {
console.log(res);
log();
})
.catch((rej) => {
log();
});
api
.then((res) => {
console.log(res);
log();
})
.catch((rej) => {
log();
})
.finally(log());
function log() {
console.log("Chamada concluída");
}
|
jQuery(function($){
var team = {
"list": [
{
"name": "Claire Shi",
"program": "Math",
"description": "<p>爱音乐爱健身爱做饭</p>",
"department": "pr",
"social": {
"envelope": "shichang0421@gmail.com",
"wechat": "shichang0421"
}
},
{
"name": "Jingyi Guo",
"program": "Civil Eng",
"description": "<p>除了学习啥都干</p>",
"department": "editorial",
"social": {
"instagram": "http://instagram.com/avant_leo",
"wechat": "hypnos_akaneko"
}
},
{
"name": "Autumn Xu",
"program": "Math",
"description": "<p>数学系的文科生,</p><p>鹅大爷的好闺蜜。</p>",
"department": "editorial",
"social": {
"facebook": "https://www.facebook.com/autumn.xu.52",
"wechat": "autumnxjingjing"
}
},
{
"name": "Wendy Lin",
"program": "Actuarial Science",
"description": "<p>每天莫名其妙的乐呵</p>",
"department": "event",
"social": {
"envelope": "wandi0118@gmail.com",
"wechat": "wandi0118",
"facebook": "https://www.facebook.com/wandi.lin1"
}
},
{
"name": "Michael Chi",
"program": "Computer Eng",
"description": "<p>喜欢一切跟吃有关的东西</p>",
"department": "tech",
"social": {
"envelope": "michael.chi1997@gmail.com",
"wechat": "michael1997725",
"facebook": "https://www.facebook.com/michael.chi.9"
}
},
{
"name": "Spencer Tao",
"program": "Economics",
"description": "<p>Try to be an Explorer.</p>",
"department": "pr",
"social": {
"envelope": "spencerts@outlook.com",
"wechat": "speocean",
"instagram": "speocean"
}
},
{
"name": "Sandy Xu",
"program": "AFM",
"description": "<p>做喜欢做的事儿~</p>",
"department": "design",
"social": {
"envelope": "sandyxu0927@gmail.com",
"wechat": "onenonly0927",
"facebook": "https://www.facebook.com/sandy0927"
}
},
{
"name": "Sylvia Zhang",
"program": "AFM",
"description": "<p>虽然一把年纪了,但还是很想成为被选召的孩子啊</p>",
"department": "design",
"social": {
"envelope": "zzhangshuyan@gmail.com",
"wechat": "sylviaokita"
}
},
{
"name": "Nicole Sheng",
"program": "Actuarial Science",
"description": "<p>吃面不吃米的南方人,心有文科的理科生</p>",
"department": "editorial",
"social": {
"envelope": "nicoleshengsal@gmail.com",
"wechat": "372233161",
"instagram": "ithought_nicolllle",
"facebook": "https://www.facebook.com/nicole.sheng.5"
}
},
{
"name": "Cici Wu",
"program": "GBDA",
"description": "<p>标准吃货一枚</p>",
"department": "design",
"social": {
"envelope": "cicimengxiw847@gmail.com",
"wechat": "wumengxi980817",
"instagram": "ciciwumengxi"
}
},
{
"name": "Ariel Ji",
"program": "Computer Science",
"description": "<p>喝最烈的酒</p> <p>做最野的汪</p>",
"department": "design",
"social": {
"envelope": "ariel.jsy@gmail.com",
"wechat": "16479889796",
"instagram": "stupidariel"
}
},
{
"name": "Alicia Gu",
"program": "",
"description": "<p>彪悍勇敢,乐观温暖</p>",
"department": "event",
"social": {
"wechat": "tarotapioca"
}
},
{
"name": "Angela Fan",
"program": "",
"description": "<p>话唠~ 活泼 喜欢吃</p>",
"department": "event",
"social": {
"wechat": "fansijia0731"
}
},
{
"name": "Chandler Yan",
"program": "Computer Science",
"description": "<p>我就是我,做最不一样的水(cheng)果(zi)</p>",
"department": "exec",
"social": {
"wechat": "as574601359"
}
},
{
"name": "Claudia Ying",
"program": "",
"description": "<p>只想暴瘦</p><p>只想暴富</p>",
"department": "event",
"social": {
"wechat": "xin600025",
"instagram": "ccclaudia.y"
}
},
{
"name": "Echo Qiu",
"program": "",
"description": "<p>长期来面临的主要矛盾:美食与减肥</p>",
"department": "event",
"social": {
"wechat": "13601563031"
}
},
{
"name": "Joyce Luo",
"program": "Biology & Psychology",
"description": "<p>怀着改变世界的英雄梦,祈求安稳的平凡人生</p>",
"department": "pr",
"social": {
"wechat": "joyceee96"
}
},
{
"name": "Leon Ma",
"program": "Computer Engineering",
"description": "<p>Work Hard Play Hard</p>",
"department": "pr",
"social": {
"wechat": "leonma333"
}
},
{
"name": "Rachel Ni",
"program": "",
"description": "<p>实在没有才艺了 给大家翻个白眼吧</p>",
"department": "editorial",
"social": {
"wechat": "yunakim2014",
}
},
{
"name": "Timmy Zhu",
"program": "",
"description": "<p>想当歌手和电竞选手的程序员</p>",
"department": "event",
"social": {
"wechat": "hualuozuihuanshang",
}
},
{
"name": "Violet",
"program": "",
"description": "<p>最大的爱好就是吃饭</p><p>爱吃午饭 晚饭 夜宵</p><p>如果早上起得来</p><p>也爱吃早饭</p>",
"department": "event",
"social": {
"wechat": "934644451",
}
},
{
"name": "Vivi Cao",
"program": "",
"description": "<p>近期目标:和男票养三只猫,两只狗,一只蜥蜴。已达成:½</p>",
"department": "editorial",
"social": {
"wechat": "lilyice19980226",
}
},
{
"name": "Vivian Bai",
"program": "Science and Business",
"description": "<p>声优都是怪物,惹不起惹不起</p>",
"department": "pr",
"social": {
"wechat": "x_1970-2000",
}
},
{
"name": "Yichen Wang",
"program": "",
"description": "<p>想要一夜暴富。钱啊 快来吧</p>",
"department": "editorial",
"social": {
"wechat": "bujianbusan778629",
}
},
{
"name": "Zoey Yang",
"program": "FARM",
"description": "<p>谁动了本宝的蛋黄酥?</p>",
"department": "event",
"social": {
"wechat": "y199701142199",
}
},
{
"name": "Selina Xie",
"program": "Math",
"description": "<p>想要个暑假</p>",
"department": "pr",
"social": {
"wechat": "Xie222x",
}
},
{
"name": "V",
"program": "",
"description": "<p>一句话也没有</p>",
"department": "pr",
"social": {
"wechat": "VANniah",
}
},
{
"name": "Fiona Luo",
"program": "",
"description": "<p>想暴富的胖胖</p>",
"department": "event",
"social": {
},
"style": "object-position: right;"
},
{
"name": "Grace Chu",
"program": "AFM",
"description": "<p>be my own cheerleader</p>",
"department": "design",
"social": {
"wechat": "DrewRace1219",
}
},
{
"name": "Lucia Liu",
"program": "Computer Science",
"description": "<p>能吃能喝就是福,胖要胖的理直气壮</p>",
"department": "pr",
"social": {
"wechat": "Luck-Lucia",
}
},
{
"name": "Nina Ren",
"program": "精算统计",
"description": "<p>每天开心快乐傻笑,真好</p>",
"department": "pr",
"social":{}
}
],
"html": "",
"template": "<div class=\"col-lg-3 col-md-3 col-sm-4\" data-department=\"%s\"> <div class=\"single_team wow fadeInUp\"> <div class=\"team_img\"> <img src=\"img/team/%s.jpg\" style=\"%s\" onerror=\"this.src='img/team/placeholder-user-photo.png';\"> </div> <h5>%s</h5> <span>%s</span> <div class=\"description\">%s</div> <div class=\"team_social\">%s</div> </div> </div>",
"social": "<a href=\"%s\" target=\"blank\"><i class=\"fa fa-%s\"></i></a>",
"wechat": "<a class=\"wechat-button\" data-toggle=\"tooltip\" title=\"复制粘贴 ID: %s 到微信加入好友\" data-trigger=\"click focus\"><i class=\"fa fa-wechat\"></i></a>",
"prepare": function () {
var self = this;
this.list.map(function(member) {
var social_list = "";
Object.keys(member.social).forEach(function (site) {
if (site == "wechat") {
social_list += sprintf(team.wechat, member.social[site]);
} else {
social_list += sprintf(team.social, member.social[site], site);
}
});
self.html += sprintf(self.template,
member["department"],
member["name"].replace(/ /g,'').toLowerCase(),
member["style"] ? member["style"] : "",
member["name"],
member["program"],
member["description"],
social_list);
});
},
"load": function () {
$("#load_team").append(this.html);
$('.team_slider').slick({
dots: false,
infinite: true,
speed: 300,
slidesToShow: 4,
slidesToScroll: 4,
responsive: [
{
breakpoint: 1024,
settings: {slidesToShow: 3, slidesToScroll: 3, infinite: true, dots: true }
},
{
breakpoint: 600,
settings: {slidesToShow: 2, slidesToScroll: 2 }
},
{
breakpoint: 480,
settings: {slidesToShow: 1, slidesToScroll: 1 }
}
]
});
// initialize tooltip
$('[data-toggle="tooltip"]').tooltip();
}
};
team.prepare();
jQuery(window).load(function() {
team.load();
});
var team_filters = $("#team-filter").find("a"),
is_filtering = false;
team_filters.on("click", function (e) {
e.preventDefault();
if (is_filtering) return ;
is_filtering = true;
if ($(this).parent().hasClass("active")) {
return;
}
team_filters.parent().removeClass("active");
$(this).parent().addClass("active");
var selection = $(this).attr("href").substring(1);
$("#filter-dropdown span:first-child").html($(this).text());
$('.team_slider').animate({
opacity: "0"
}, 500, function() {
$('.team_slider').slick('slickUnfilter');
if (selection) {
$('.team_slider').slick('slickFilter', 'div[data-department~="' + selection + '"]');
}
}).animate({
opacity: "1"
}, 500, function() {
is_filtering = false;
});
});
$('.team_slider').on('setPosition', function(slick) {
$("#filter-dropdown").width(slick.currentTarget.clientWidth - 56);
});
});
|
import React, { Component } from 'react';
import { Container, Row, Col } from 'reactstrap';
class CoreValue extends Component {
render() {
return (
<div className="coreValue">
<Container>
<Row>
<Col>
<h2 className="h2Quote">
"Integrasi Investasi, Beasiswa & Ikatan Dinas Teknologi Informasi Berdampak Sosial."
</h2>
</Col>
</Row>
</Container>
</div>
);
}
}
export default CoreValue;
|
var todoapp = angular.module('todoApp', ['ui.router']);
todoapp.config(function($stateProvider, $urlRouterProvider) {
//
// For any unmatched url, redirect to /state1
$urlRouterProvider.otherwise("/");
//
// Now set up the states
$stateProvider
.state('index', {
url: "/",
templateUrl: "/templates/index.html",
controller: function($scope) {
console.log($scope)
}
})
.state('list', {
url: "/list",
templateUrl: "/templates/list.html",
controller: function($scope, $http) {
// console.log($scope)
$scope.items = ["A", "List", "Of", "Items"];
$http.get('/api/list').then(
function(res){
console.log(res)
$scope.tareas = res.data
}
,
function(error){
console.log(error)
}
)
},
})
// .state('ficha', {
// url: "/state2",
// templateUrl: "partials/state2.html"
// })
// .state('state2.list', {
// url: "/list",
// templateUrl: "partials/state2.list.html",
// controller: function($scope) {
// $scope.things = ["A", "Set", "Of", "Things"];
// }
// });
});
|
import React from 'react'
const RecipeCard=(props)=>{
console.log(props.recipe)
return (
<div className="col-sm-4 mt-3">
<div className="card" style={{maxWidth:"450px",minWeight:"200px"}} key={props.recipe.recipe.label} >
<img className="card-img-top img-thumbnail" src={props.recipe.recipe.image} alt="Card image"/>
<div className="card-body">
<h4 className="card-title">{props.recipe.recipe.label}</h4>
<p><strong>Calories</strong> {props.recipe.recipe.calories} KCal.</p>
<span className="card-text float-start">Desh Type -- {props.recipe.recipe.dishType}</span>
<span className="card-text float-end">Meal Type -- {props.recipe.recipe.mealType}</span>
</div>
</div>
</div>
)
}
export default RecipeCard
|
import React, { useState, useEffect } from "react";
import { Grid, Card, Icon, Fab } from "@material-ui/core";
import { fireDb } from "../../../services/firebase/firebaseConfig";
const StatCards2 = () => {
const [patients, setPatients] = useState([]);
const [user, setUser] = useState("");
let docPatients = [];
useEffect(() => {
async function loadPatients() {
//fetch the patient list
const request = await fetch(
"https://healthymind.herokuapp.com/api/getPatients",
{}
);
const allPatients = await request.json();
//set the patient list on state
setPatients(allPatients.patients);
// console.log(allPatients.patients.length)
}
//invoke the function
loadPatients();
}, []);
const authListener = () => {
fireDb.auth().onAuthStateChanged((user) => {
// clearInputs();
if (user) {
setUser(user);
} else {
setUser("");
}
});
};
useEffect(() => {
authListener();
}, []);
patients &&
Object.keys(patients).forEach(function (key) {
const data = patients[key];
if (data.docId === user.email) {
// console.log(data);
docPatients.push(data);
}
});
let total_patients = docPatients.length;
let perc_increase = (
((total_patients - (total_patients - 1)) / (total_patients - 1)) *
100
).toFixed(2);
return (
<Grid container spacing={3} className="mb-24">
<Grid item xs={12} md={6}>
<Card elevation={3} className="p-16">
<div className="flex flex-middle">
<Fab
size="medium"
className="bg-light-green circle-44 box-shadow-none"
>
<Icon
className="IconTrending"
style={{ color: "#fff !important;" }}
>
trending_up
</Icon>
</Fab>
<h5 className="font-weight-500 text-green m-0 ml-12">
Active Patients
</h5>
</div>
<div className="pt-16 flex flex-middle">
<h2 className="m-0 text-muted flex-grow-1">
{total_patients === 0 ? (
<h6>No patients available</h6>
) : (
total_patients
)}
</h2>
<div className="ml-12 small-circle bg-green text-white">
<Icon className="small-icon">expand_less</Icon>
</div>
<span className="font-size-13 text-green ml-4">
{" "}
(+{perc_increase}%)
</span>
</div>
</Card>
</Grid>
<Grid item xs={12} md={6}></Grid>
</Grid>
);
};
export default StatCards2;
|
import React from 'react'
import AppBar from '@material-ui/core/AppBar';
const appBarLight = {
background: "#fafafa",
boxShadow: "none",
}
const appBarDark = {
background: "#1e2023",
boxShadow: "none",
}
class Nav extends React.Component {
constructor(props) {
super(props);
this.state = {
darkModeToggle: false,
}
};
handleClick = () => {
this.setState(state => ({
darkModeToggle: !state.darkModeToggle
}))
// if (localStorage.getItem('mode') == "light") {
// localStorage.setItem('mode', 'dark')
// }
// else {
// localStorage.setItem('mode', 'light')
// }
// console.log(localStorage.getItem('mode'))
}
componentDidMount = () =>{
// localStorage.setItem('mode','light')
// if(localStorage.getItem('mode') == 'light'){
// this.setState(state =>({
// darkModeToggle : !state.darkModeToggle
// }))
// }
// else{
// this.setState(state =>({
// darkModeToggle : !state.darkModeToggle
// }))
// }
}
render() {
return (
<AppBar position="sticky" style={ this.state.darkModeToggle ? appBarDark : appBarLight}>
<ul>
<li className="logo">
{
this.state.darkModeToggle ? <a href="/"><img src={require('../images/whitetrans2x.png')} width="60" height="40" alt="Logo" /></a> :
<a href="/homepage"><img src={require('../images/blacktrans4x.png')} width="60" height="40" alt="Logo" /></a>
}
</li>
<li>
<a href="/create">Make a Post</a>
</li>
<li>
<a href="/about">About Me</a>
</li>
{/* <li>
<a href="/profile" disabled>Profile</a>
</li> */}
<li>
<a href="/login">Login</a>
</li>
<li className="darkModeStyle">
<button onClick={this.handleClick} className="darkModeBtn">Dark Mode</button>
</li>
</ul>
<style jsx>{`
:global(body) {
margin: 0;
background: ${this.state.darkModeToggle ? '#1e2023' : '#fafafa'};
color: ${this.state.darkModeToggle ? 'white' : 'black'};
font-family: -apple-system, BlinkMacSystemFont, Avenir Next, Avenir,Helvetica, sans-serif;
}
.logo{
margin : 0px !important;
}
nav {
text-align: center;
display:relative;
}
ul {
}
nav > ul {
padding: 4px 16px;
}
li {
padding: 6px 8px;
margin: 12px;
float:left;
list-style-type: none;
}
li:last-child{
float:right;
}
a {
color: #0582C6;
text-decoration: none;
font-size: 16px;
font-weight:bold;
}
.main-logo{
font-weight:bold;
padding: 4px 16px;
}
button{
width : 100px;
height : 25px;
color : ${this.state.darkModeToggle ? 'white' : 'black'};
border: ${this.state.darkModeToggle ? '1px solid white' : '1px solid black'};
border-radius : 10px ;
background : none ;
}
button:hover{
cursor : pointer;
}
.darkModeBtn:focus {
outline: none;
}
`}</style>
</AppBar>
)
}
}
export default Nav
|
const init = () => {
angular.module('med-edu').controller('ClinicController', ['$scope', 'StateManagerAgent',
($scope, stateManagerAgent) => {
const maxLevel = stateManagerAgent.getMaxLevel() - 1;
$scope.rewardImage = `level${maxLevel}.jpg`;
$scope.toNavigate = () => stateManagerAgent.toNavigate()
}]);
}
export default init;
|
import {ConnectAccount} from "./connectAccount.js";
import Http from "./http.js";
import {DataStorage} from "./lib.js";
import {LocalStorage} from "./storage.js";
import {ServerLink} from "./serverLink.js";
import RenderQuestionList from "./renderQuestionList.js";
export function help() {
const serverLink = new ServerLink();
const http = new Http(serverLink.link);
const usernameBarEl = document.querySelector('#usernameBar');
const connectAccount = new ConnectAccount();
const storage = new DataStorage(new LocalStorage());
const renderQuestionList = new RenderQuestionList();
let user;
(async function updateUser() {
if (storage.getUserData === null) {
document.location.href = 'index.html'
} else {
await connectAccount.getData();
user = await connectAccount.user;
renderQuestionList.renderQuestionList(user);
usernameBarEl.textContent = user.username;
}
})();
const exitButtonEl = document.querySelector('#exitButton');
exitButtonEl.addEventListener('click', (evt) => {
storage.unlogin();
document.location.href = 'index.html'
});
const questionFormEl = document.querySelector('#questionForm');
const questionFormListener = async (evt) => {
evt.preventDefault();
const inputThemeEl = document.querySelector('#inputTheme');
const inputTextEl = document.querySelector('#inputText');
if (inputThemeEl.value.length < 6) {
inputThemeEl.className = 'form-control is-invalid';
return;
}
if (inputTextEl.value.length < 30) {
inputTextEl.className = 'form-control is-invalid';
return;
}
let questionObject = {
theme: inputThemeEl.value,
question: inputTextEl.value,
status: 'false'
};
inputThemeEl.className = 'form-control';
inputTextEl.className = 'form-control';
user.support.push(questionObject);
let timetableUpdate = await http.timetableUpdate(user);
let _resultUpdateFlag = '';
await timetableUpdate.json().then(async (data) => {
_resultUpdateFlag = data;
await console.log(data);
renderQuestionList.renderQuestionList(user);
});
inputTextEl.value = '';
inputThemeEl.value = '';
};
questionFormEl.addEventListener('submit', questionFormListener);
}
|
'use strict';
// Libs
const tuyaPlug = require('../libs/tuya-plug');
class TuyaController {
static async indexHandler(req, res, next) {
let devices = await tuyaPlug.getDevices();
res.json({
devices
});
return next();
}
static async switchHandler(req, res, next) {
const name = req.params.name;
const enable = !!parseInt(req.params.enable);
const plug = await tuyaPlug.switchPlug(name, enable);
res.json({
plug
});
return next();
}
}
module.exports = TuyaController;
|
import asyncHandler from 'express-async-handler'
import Order from '/orderModel.js';
const addOrderItems= asyncHandler(async (req,res)=>{
const {side ,price}=req.body;
const order = new Order({
side:side,
price:price
})
const createdOrder = await order.save();
res.status(201).json(createdOrder);
class Node
{
constructor(data)
{
this.data = data;
this.left = null;
this.right = null;
}
}
const isTreeSymmetric = tree =>isTreeEqual(tree.left, tree.right)
const Node = (value, left, right) => ({value, left, right})
const tree1 =
Node(1,
Node(2,
Node(3, Node(4), Node(5)),
Node(3, Node(4), Node(5))),
Node(2,
Node(3, Node(4), Node(5)),
Node(3, Node(4), Node(5))))
console.log(isTreeSymmetric(tree1)) // true
if(left == right){ //checking variable values
if(isTreeSymmetric(tree1) == false)
let result = Order.remove({_id: req.query._id}) //assuming we get an id in query
this.removeNode(node, this.data)
}
const isTreeEqual = (x, y) => {
if (x === undefined && y === undefined)
return true
else if (x === undefined || y === undefined)
return false
else if (x.value === y.value)
return isTreeEqual(x.left, y.left) && isTreeEqual(x.right, y.right)
else
return false
}
removeNode(node, key)
{
// if the root is null then tree is
// empty
if(node === null)
return null;
// if data to be delete is less than
// roots data then move to left subtree
else if(key < node.data)
{
node.left = this.removeNode(node.left, key);
return node;
}
// if data to be delete is greater than
// roots data then move to right subtree
else if(key > node.data)
{
node.right = this.removeNode(node.right, key);
return node;
}
// if data is similar to the root's data
// then delete this node
else
{
// deleting node with no children
if(node.left === null && node.right === null)
{
node = null;
return node;
}
// deleting node with one children
if(node.left === null)
{
node = node.right;
return node;
}
else if(node.right === null)
{
node = node.left;
return node;
}
// Deleting node with two children
// minumum node of the rigt subtree
// is stored in aux
var aux = this.findMinNode(node.right);
node.data = aux.data;
node.right = this.removeNode(node.right, aux.data);
return node;
}
}
})
|
let mongoose = require('mongoose');
let Schema = mongoose.Schema;
const ROLE_TYPES = ['user', 'admin'];
let UserSchema = new Schema({
name:{
type: String,
required: 'Your name is required'
},
email: {
type: String,
required: 'Your email address is required'
},
Created_date: {
type: Date,
default: Date.now()
},
role: {
type: String,
enum: ROLE_TYPES,
default: ['user']
}
});
module.exports = mongoose.model('Users', UserSchema);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.