text
stringlengths 7
3.69M
|
|---|
import React from "react";
import IconButton from "@material-ui/core/IconButton";
import ExitToAppIcon from "@material-ui/icons/ExitToApp";
import LoginAppIcon from "@material-ui/icons/LockOpen";
import "./styles.css";
export const AuthButton = (props) => {
const { isLogged, onClick } = props;
const Icon = isLogged ? ExitToAppIcon : LoginAppIcon;
return (
<IconButton className="auth-logout-button" onClick={onClick}>
<Icon className="auth-logout-button-icon" />
</IconButton>
);
};
|
$(document).ready(function() {
$('body').show();
$(document).trigger('getPhoneCodes');
var anchors = ('home, ' + $('.page_data').data('anchors')).split(", ");
$('#fullpage').fullpage({
afterLoad: function(anchorLink, index) {
if (index != 1) {
$('.navbar-brand').removeClass('text-transparent');
$('.navbar-toggler svg')
.removeClass('text-white')
.addClass('text-galaxy');
} else {
$('#fp-nav ul li a span').addClass('bg-white');
}
$('.navbar-collapse').collapse('hide');
},
anchors: anchors,
loopHorizontal: false,
menu: '.navbar-nav',
navigation: true,
navigationPosition: 'right',
onLeave: function(index, nextIndex, direction) {
var leavingSection = $(this);
//after leaving section 2
if (nextIndex == 1) {
$('.navbar-brand').addClass('text-transparent');
$('.navbar-toggler svg')
.removeClass('text-galaxy')
.addClass('text-white');
} else {
$('#fp-nav ul li a span').removeClass('bg-white');
}
},
onSlideLeave: function(
anchorLink, index, slideIndex, direction, nextSlideIndex) {
var slideNum = nextSlideIndex + 1
$('.nav .nav-link').removeClass('active');
$('#' + anchorLink + '-slide' + slideNum).addClass('active');
},
scrollHorizontally: true,
slidesNavPosition: 'bottom',
verticalCentered: false,
});
$('.fp-next').html('<i class="fas fa-chevron-circle-right fa-2x"></i>')
$('.fp-prev').html('<i class="fas fa-chevron-circle-left fa-2x"></i>')
$('#fp-nav ul li a span').addClass('bg-white');
// Show slide navigation on smaller viewports...
$('.fp-slidesNav').addClass('d-lg-none');
// Hide slide arrows on smaller viewports...
// $('.fp-controlArrow').addClass('d-none d-lg-block');
});
$(document).on('click', '.dismiss_nav', function(event) {
$('.navbar-collapse').collapse('hide');
});
$('.navbar-collapse').on('show.bs.collapse', function(event) {
$(this).fadeIn('fast');
});
$('.navbar-collapse').on('hide.bs.collapse', function(event) {
$(this).fadeOut();
});
/*=================================================
= SET COUNTRY DIALLING CODE =
=================================================*/
function getPhoneCode() {
var countryCode = $('#id_country', '#demo_request_form')
.countrySelect("getSelectedCountryData")
.iso2
.toUpperCase();
// Look up code... (note: phoneCodes is assigned in separate .js file)
return phoneCodes[countryCode]
}
$(document).on('input change', '#id_country', function(event) {
var phc = getPhoneCode()
// Update phone field prepend...
$('.input-group-text', '#div_id_phone').text('+' + phc);
// Update value of form phone code field...
$('#id_phone_code', '#demo_request_form').val(phc);
});
/*=================================================
= GET CLIENT INQUIRY FORM =
=================================================*/
$(document).on('click', '.demo_request_get_button', function(event) {
event.preventDefault();
$.ajax({
url: '/clients/demo-request-create/',
type: 'GET',
})
.done(function(data) {
// Load data to DOM...
$('.modal-body').html(data);
// Display submit button...
$('.demo_request_post_btn').removeClass('d-none');
// Launch modal...
$('#homeModalCenter').modal({
keyboard: false,
backdrop: 'static'
});
// Prevent fullpage.js from scrolling...
$.fn.fullpage.setAllowScrolling(false);
// Set pretty country-select field...
$('#id_country', '.modal-body').countrySelect();
var phc = getPhoneCode()
// Update phone field prepend...
$('.input-group-text', '#div_id_phone').text('+' + phc);
// Set value for phone code...
$('#id_phone_code').val(phc)
})
});
$(document).on('hide.bs.modal', function(event) {
// Re-enable fullpage.js scrolling...
$.fn.fullpage.setAllowScrolling(true);
});
/*=================================================
= POST CLIENT INQUIRY FORM =
=================================================*/
$(document).on('click', '.demo_request_post_btn', function(event) {
event.preventDefault();
$.ajax({
url: '/clients/demo-request-create/',
type: 'POST',
data: $('#demo_request_form').serialize()
})
.done(function(data) {
// $('#id_country', '#modal-body').countrySelect('destroy');
// Display data...
$('.modal-body').html(data);
// If no form is valid...
if (!$(data).find('.is-invalid').length) {
console.log('no errors found');
// Hide post button...
$('.demo_request_post_btn').addClass('d-none');
}
// If form is invalid...
else {
// Store value of the country field and clear. This is
// needed to avoid errors when initialising
// countrySelect...
var selCountry = $('#id_country').val();
$('#id_country').val('');
// Setup country-select field with country flags...
$('#id_country').countrySelect();
// Select instance value...
$('#id_country').countrySelect('setCountry', selCountry);
// Insert phone code into phone field input prepend...
$('.input-group-text', '#div_id_phone')
.text('+' + getPhoneCode());
}
})
});
|
export { default as History } from "./history";
export { default as Wishlist } from "./wishlist";
export { default as Password } from "./password";
|
import {string, isEqualToField, required, Schema, validate} from 'sapin'
export const changePasswordSchema = new Schema({
oldPassword: string(required),
newPassword: string(required),
confirmPassword: string([required, isEqualToField('newPassword')])
})
export const validateChangePassword = (entity) => {
return validate(entity, changePasswordSchema)
}
|
let superiorOculta,superiorLateral= false;
function cambioSongSpoti(uri,imagen,index){
if(sound) sound.setPath(uri,soundLoaded,soundError);
else sound = new p5.SoundFile(uri,soundLoaded,soundError);
arteAlbum = loadImage(imagen,i=>i.resize(width/2,0));
$('#tagCancion').html(`${retornoSpotify[index].Titulo} - ${retornoSpotify[index].Artista}`);
}
var retornoSpotify = [];
function buscar(){
retornoSpotify = [];
//document.getElementById('r').innerHTML = "";
const uri = 'https://api.spotify.com/v1';
const consulta = '/search?q=' + document.getElementById('inEscanor').value + '&type=track&limit=50';
fetch(uri+consulta, {
method : 'GET',
headers : {'Authorization' : token.token_type + ' ' + token.access_token}
}).then(r=>r.json()).catch(e=>console.error(e)).then(r=>{
let d = document.getElementById('r');
if(r.error) {
console.error(r.error);
alert(r.error.message);
if(r.error.status===401) window.location.replace('http://localhost:8000');
} else {
console.log(r.tracks.items.length);
if(r.tracks.items.length == 0) retornoSpotify.push({
'Titulo' : 'N/A',
'Artista' : 'N/A',
'Album' : 'N/A',
'PlayIt' : 'N/A',
});
else r.tracks.items.forEach(lk=>{
let imagen = lk.album.images[0].url; //filtrar imagen a una de tamaño aceptable
let prevurl = lk.preview_url;
let spobutton = prevurl?'<button onclick="cambioSongSpoti(\''+prevurl+"','"+imagen+'\','+retornoSpotify.length+')">Play It</button>':'<label>N/A</label>'
let cancion = {
'Titulo' : lk.name,
'Artista' : lk.artists[0].name,
'Album' : lk.album.name,
'PlayIt' : spobutton,
'_id' : retornoSpotify.length,
'_prev' : prevurl,
'_cover' : imagen,
}
retornoSpotify.push(cancion);
});
creadorTabla(retornoSpotify);
}
let gruped = agrupar(retornoSpotify);
sunburst_raiz = jerarquicar(gruped,document.getElementById('inEscanor').value);
cluster_raiz = sunburst_raiz.copy();
cluster_raiz.eachAfter(d=>{d._children=d.children;d.children=null;})
cluster_raiz.children = cluster_raiz._children;
sunburst(sunburst_raiz);
});
}
function ocultarSuperior(){
var componente = document.getElementById("divisionControles");
if(superiorOculta){
miBtn=document.getElementById("buttonSuperior");
miBtn.style.backgroundImage = "url('assets/images/buttons/Up.png')";
miBtn.onmouseover = function(){miBtn.style.backgroundImage = "url('assets/images/buttons/Up-Hover.png')";};
miBtn.onmouseout = function(){miBtn.style.backgroundImage = "url('assets/images/buttons/Up.png')";};
// Cambiar a visible
componente.style.visibility='visible';
// Cambiar tamaño para tomar espacio
document.getElementById("divisionOcultarLateral").style.top = "120px";
document.getElementById("divisionBuscador").style.top = "120px";
// Eliminar altura requerida por componente
document.getElementById("divisionOcultarLateral").style.height = "calc(100% - 120px)";
document.getElementById("divisionBuscador").style.height = "calc(100% - 120px)";
}
else{
// Cambiar a oculto
miBtn=document.getElementById("buttonSuperior");
miBtn.style.backgroundImage = "url('assets/images/buttons/Down.png')";
miBtn.onmouseover = function(){miBtn.style.backgroundImage = "url('assets/images/buttons/Down-Hover.png')";};
miBtn.onmouseout = function(){miBtn.style.backgroundImage = "url('assets/images/buttons/Down.png')";};
componente.style.visibility='hidden';
// Eliminar espacio por ocultar el componente
document.getElementById("divisionOcultarLateral").style.top = "45px";
document.getElementById("divisionBuscador").style.top = "45px";
// Agregar altura extra ya no requerida por componente
document.getElementById("divisionOcultarLateral").style.height = "calc(100% - 45px)";
document.getElementById("divisionBuscador").style.height = "calc(100% - 45px)";
}
superiorOculta=!superiorOculta;
}
function ocultarLateral(){
var componente = document.getElementById("divisionBuscador");
if(superiorLateral){
miBtn2=document.getElementById("buttonLateral");
miBtn2.style.backgroundImage = "url('assets/images/buttons/Der.png')";
miBtn2.onmouseover = function(){miBtn2.style.backgroundImage = "url('assets/images/buttons/Der-Hover.png')";};
miBtn2.onmouseout = function(){miBtn2.style.backgroundImage = "url('assets/images/buttons/Der.png')";};
componente.style.visibility='visible';
}
else{
miBtn2=document.getElementById("buttonLateral");
miBtn2.style.backgroundImage = "url('assets/images/buttons/Izq.png')";
miBtn2.onmouseover = function(){miBtn2.style.backgroundImage = "url('assets/images/buttons/Izq-Hover.png')";};
miBtn2.onmouseout = function(){miBtn2.style.backgroundImage = "url('assets/images/buttons/Izq.png')";};
componente.style.visibility='hidden';
}
superiorLateral=!superiorLateral;
}
/* ================================================================== *
* Aqui van a ir todas aquellas funciones que se encargen de responder
* directamente a eventos de la UI
* ================================================================== */
/*funcion encargada de activar y desactivar el loop de la cancion*/
function buttonLoopMetodo(){
//si la cacion no se esta ejecunatdo no se realiza el reto de la funcion
if(!soundMode) return;
/* Mas o menos, obentgo el estado actual del loop, y lo invierto */
if(!sound.isPlaying()){
loopActivo = !loopActivo;
} else {
loopActivo = !sound.isLooping();
}
sound.setLoop(loopActivo);
}
function toggleSound(){
if(!soundMode) return;
if(sound.isPlaying()){
barraDuracionActiva = false;
sound.pause();
} else {
barraDuracionActiva = true;
sound.play();
}
}
function clearGrid(){
const tw = (width/2)/32;
const th = height/32;
for(let i=0;i<32;++i){
mpoints[i]=[];
for(let j=0;j<32;++j){
mpoints[i][j]={x:i*tw,y:j*th};
}
}
}
/*Funcion encargada de detener la reproduccion de la cancion que se esta ejecutando*/
function buttonStop(){
//si la cacion no se esta ejecunatdo no se realiza el reto de la funcion
if(!soundMode) return;
//Se detiene la reproduccion de la cancion
sound.stop();
}
function keyPressed(){
if(key=='p' || key == ' ') toggleSound();
}
function fileHandle(file){
console.log(file);
if(file.type=="audio"){
window.jsmediatags.read(file.file, {
onSuccess: (data)=>{
let tags = data.tags;
/*Example
album: "Relaxer"
artist: "alt-J"
picture: Object { format: "image/jpeg", type: "Cover (front)", description: "", data:[...], ... }<=Esta picture.data es la imagen del cover, util a futuro
title: "Adeline"
track: "6/8"
year: "2017"
*/
console.log(tags.title,tags.artist,tags.album, tags);
},
onError: (error)=>{console.error(error);}
});
textCanvas.background(15);
textCanvas.text('Archivo no cargado\nEspera unos minutos\nO prueba con otro',200,200);
sound.stop();
sound = loadSound(file,soundLoaded,soundError);
} else {
soundError();
}
}
/*Funcion encargada de actualizar el aspecto de los botones dependiendo de los
valores en el que se encuentren en ejecucion*/
function actualizarBotones(){
/* ================================================================== *
* No seria mejor actualizar los botones solamente cuando han *
* Cambiado, como por ejemplo, en la funcion que los modifica *
* ================================================================== */
var miBtn;
//si la cacion no se esta ejecunatdo no se realiza el reto de la funcion
if(!soundMode) return;
//if encargado de recizar si la cancion se esta ejecutando para actualizar el btnPausa
if(sound.isPlaying()){
//Se actualiza el la palabra dentro del boton a Play
miBtn=document.getElementById("buttonPausa");
if(validadorHover(miBtn)){
miBtn.style.backgroundImage = "url('assets/images/buttons/pause-Hover.png')";
}
else{
miBtn.style.backgroundImage = "url('assets/images/buttons/pause.png')";
}
}
//else encargado de actualizar el btnPausa
else {
miBtn=document.getElementById("buttonPausa");
if(validadorHover(miBtn)){
miBtn.style.backgroundImage = "url('assets/images/buttons/play-Hover.png')";
}
else{
miBtn.style.backgroundImage = "url('assets/images/buttons/play.png')";
}
}
//if encargado de recizar si la cancion se esta ejecutando en loop para actualizar el btnLoop
if(loopActivo){
//Se actualiza el color del boton con relacion al valor
miBtn=document.getElementById("buttonLoop");
if(validadorHover(miBtn)){
miBtn.style.backgroundImage = "url('assets/images/buttons/replay ON-Hover.png')";
}
else{
miBtn.style.backgroundImage = "url('assets/images/buttons/replay ON.png')";
}
}
//else encargado de actualizar el btnLoop
else {
miBtn=document.getElementById("buttonLoop");
if(validadorHover(miBtn)){
miBtn.style.backgroundImage = "url('assets/images/buttons/replay-Hover.png')";
}
else{
miBtn.style.backgroundImage = "url('assets/images/buttons/replay.png')";
}
}
//if encargado de recizar si la cancion se esta ejecutando en loop para actualizar el btnReversa
if(invertidor){
//Se actualiza el color del boton con relacion al valor
miBtn=document.getElementById("buttonReversa");
if(validadorHover(miBtn)){
miBtn.style.backgroundImage = "url('assets/images/buttons/rewind ON-Hover.png')";
}
else{
miBtn.style.backgroundImage = "url('assets/images/buttons/rewind ON.png')";
}
}
//else encargado de actualizar el btnReversa
else {
//Se actualiza el color del boton con relacion al valor
miBtn=document.getElementById("buttonReversa");
if(validadorHover(miBtn)){
miBtn.style.backgroundImage = "url('assets/images/buttons/rewind-Hover.png')";
}
else{
miBtn.style.backgroundImage = "url('assets/images/buttons/rewind.png')";
}
}
if(fastForward){
miBtn=document.getElementById("buttonSpeed");
if(validadorHover(miBtn)){
miBtn.style.backgroundImage = "url('assets/images/buttons/fast-forward ON-Hover.png')";
}
else{
miBtn.style.backgroundImage = "url('assets/images/buttons/fast-forward ON.png')";
}
}
else{
miBtn=document.getElementById("buttonSpeed");
if(validadorHover(miBtn)){
miBtn.style.backgroundImage = "url('assets/images/buttons/fast-forward-Hover.png')";
}
else{
miBtn.style.backgroundImage = "url('assets/images/buttons/fast-forward.png')";
}
}
}
/*funcion encargada de hacer un salto en la cancion a los segundos que el usuario
quiere hacer*/
function tiempoBarraMusica(self){
//si la cacion no se esta ejecunatdo no se realiza el reto de la funcion
if(!soundMode) return;
//Detiene la ejecucion atual de la cancion
sound.stop();
//se activa la actualizacion del slider
barraDuracionActiva = true;
//Variable encargada de conseguir el valor del tiempo al cual el Usuario quiere
//hacer para la reproduccion de la cancion
let tiempo=parseInt(self.value);
//Salta al tiempo deseado despues de 50ms, para asegurar que no haya errores por asincrono
//Si se hace inmediato, primero salta y luego la cancion se detiene o no.
setTimeout(function(){sound.jump(tiempo);},50);
}
/*Funcion encargada padar los segundos dados en eun patron de MM:SS*/
function tiempoMusica(valor){
//si la cacion no se esta ejecunatdo no se realiza el reto de la funcion
if(!soundMode) return;
//Variable encargada de obtener los Minutos de la cancion
var minutos = parseInt(valor/60);
//Variable encargada de obtener los Segundos de la cancion
var segundos = parseInt(valor%60);
//If encargado de revizar si el numero es menor a 10 para colocar un cero para que se vea mas estetico
//la representacion de los Minutos
if(minutos<=9){
minutos="0"+ minutos;
}
//If encargado de revizar si el numero es menor a 10 para colocar un cero para que se vea mas estetico
//la representacion de los Segundos
if(segundos<=9){
segundos="0"+ segundos;
}
//Retorna un String con los minutos y segundos acomodados de manera estetica
return minutos +":"+ segundos;
}
/*Funcion encargada de Actualizar el Slider seekTime del UI con el valor actual de en
cual segundo se encuentra la ejecucion de la cancion*/
function valorTiempoBarraMusica(valor){
//If encargado de revisar que si se pueda actualizar el valor y que este no
//interfiera cuando el usuario intente cambiar el tiempo de ejecucion de la cancion
if(barraDuracionActiva){
$("#Duracion1").html(tiempoMusica(sound.currentTime()));
$("#Duracion2").html(tiempoMusica(sound.duration()));
//se asigna el valor al Slider con los segundos actuales de la cancion
document.getElementById("seekTime").value = parseInt(valor);
}
}
/*Funcion a encargada de asignar la velociada a la cacion ya sea en funcion normal o en reversa*/
function Velocidad(){
console.log("test");
//si la cacion no se esta ejecunatdo no se realiza el reto de la funcion
if(!soundMode) return;
if(invertidor) inversorMusical();
//si la funcion de reversa esta activa el valor del Slider se hara negativo
if(fastForward){
//Se le asigna la velocidad a la cancion
sound.rate(1);
document.getElementById("buttonSpeed").style.backgroundImage = "url('assets/images/buttons/fast-forward.png')";
}
else{
//Se le asigna la velocidad a la cancion
sound.rate(2);
document.getElementById("buttonSpeed").style.backgroundImage = "url('assets/images/buttons/fast-forward ON.png')";
}
fastForward = !fastForward;
}
/*Funcion encargado de actualizar el volumen de la cancion utlizando un slider del UI*/
function volumenMusica(self){
//si la cacion no se esta ejecunatdo no se realiza el reto de la funcion
if(!soundMode) return;
//Obtiene el valor del Slider de volumen del UI y pasa el valor a un numero
let entrada = parseInt(self.value);
//Asigna el valor del volumen a la cancion pero lo divide entre 10 porque el radio de valor 0.0 a 1.0
sound.setVolume(entrada/10);
//Se refresca el valor del lbl que despliega el valor del volumen en el UI
$("#valorVolumenMusica").html(entrada);
}
/*Funcion encargada de reproducir en reversa la cancion o rever*/
function inversorMusical(){
//si la cacion no se esta ejecunatdo no se realiza el reto de la funcion
if(!soundMode) return;
if(fastForward) Velocidad();
//if encargo de revisar si la variable de invertido esta en un valor de true y si este
//es el caso colocar la cancion a velocidad de 1 a sonar normal
if(invertidor){
//se asigna el valor de velocidad 1 a la cancion
sound.rate(1);
//se actualiza el valor la variable invertidor
invertidor=false;
}
//else que se ejecutara si el if anterior no cumple con la condicion, si
//es el caso colocar la cancion a velocidad de -1 a sonar en reversa
else{
/*Por un error de la libreria se hace un juego con la velocidad negativa para que esta
pueda ser ejecutada*/
//se asigna el valor de velocidad -1 a la cancion
sound.rate(-1);
//se asigna el valor de velocidad 0 a la cancion
sound.rate(0);
//se asigna el valor de velocidad -1 a la cancion
sound.rate(-1);
//se actualiza el valor la variable invertidor
invertidor=true;
}
}
function validadorHover(element){
var rect = element.getBoundingClientRect();
var minX = rect.x;
var maxX = minX + 35;
var minY = rect.y;
var maxY = minY + 35;
if((minX < mouseX && mouseX < maxX) && (minY < mouseY && mouseY < maxY)){
return true;
}
return false;
}
function select_svg(){
let value = document.getElementById('svg_selected');
value = value.options[value.selectedIndex].value;
$('div.tooltip').remove();
if(value==='solar'){
sunburst(nodo_selecto);
} else if(value==='cluster'){
cluster();
} else {
heapmap();
}
}
|
import React from "react";
import {
makeStyles,
Card,
Typography,
CardActionArea
} from "@material-ui/core";
import CardContent from "@material-ui/core/CardContent";
const useStyles = makeStyles({
root: {
maxWidth: 345,
backgroundColor: "#fff",
width: "100%",
boxShadow: "0 8px 40px -12px rgba(0,0,0,0.3)",
"&:hover": {
boxShadow: "0 16px 70px -12.125px rgba(0,0,0,0.3)"
}
},
actionArea: {
height: "100%"
}
});
const SmallCard = ({ title }) => {
const classes = useStyles();
return (
<Card className={classes.root}>
<CardActionArea className={classes.actionArea}>
<CardContent>
<Typography gutterBottom variant="h5" component="h2">
{title}
</Typography>
</CardContent>
</CardActionArea>
</Card>
);
};
export default SmallCard;
|
// The following is from: http://shebang.brandonmintern.com/foolproof-html-escaping-in-javascript/
// Use the browser's built-in functionality to quickly and safely escape the string
function escapeHtml(str) {
var div = document.createElement('div');
div.appendChild(document.createTextNode(str));
return div.innerHTML;
}
//var saveOriginal = document.getElementById("thelinks").innerHTML;
var saveOriginal = document.body.innerHTML;
var links = document.getElementsByTagName('a');
var i;
var txt = "";
for (i = 0; i < links.length; ++i) {
if (i == 0) {
txt += "<ol>";
}
// Do something with links[i].href
txt += '<li>';
txt += '<a href="' + links[i].href +
'" target="' + links[i].href + '">' + links[i].href + '</a><br />';
if (links[i].innerHTML) {
txt += '<a href="' + links[i].href + '" target="' + links[i].href + '">' + links[i].innerHTML + '</a><br />';
}
txt += '<br />'
txt += '</li>';
}
if (links.length > 0){
txt += "</ol>";
}
document.body.innerHTML = txt;
//document.innerHTML += '<div style="position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000;"></div>';
document.body.innerHTML += '<div><h1>--- original text (unchanged) ---</h1>';
document.body.innerHTML += '<pre>' + escapeHtml(saveOriginal) + '</pre>';
document.body.innerHTML += '<div><h1>--- original text (rendered) ---</h1>';
document.body.innerHTML += '<pre>' + saveOriginal + '</pre>';
|
const Entity = require('./entity');
const EntityInterface = require('./interface');
const EntityFactoryInterface = require('./factory-interface');
module.exports = {
Entity,
EntityInterface,
EntityFactoryInterface,
}
|
var Profile = require('./profile.js'),
renderer = require('./renderer.js'),
querystring = require('querystring'),
fs = require('fs');
var commonHeaders = {'Content-Type': 'text/html'};
//Handle HTTP route GET / and POST / i.e. Home
function home(request, response) {
if (request.url === '/') {
if (request.method.toLowerCase() === 'get') {
response.writeHead(200, commonHeaders );
renderer.view('header', {}, response);
renderer.view('search', {}, response);
renderer.view('footer', {}, response);
response.end();
} else {
// get the post data from body, extract the username,
request.on('data', function(postBody) {
console.log(postBody.toString());
var query = querystring.parse(postBody.toString());
response.writeHead(303, {"location": "/" + query.username});
response.end();
});
}
}
}
//3. Handle HTTP route GET /:username i.e. /chalkers
function user(request, response) {
var username = request.url.replace('/', '');
if (username.length > 0) {
response.writeHead(200, commonHeaders);
renderer.view('header', {}, response);
var studentProfile = new Profile(username);
studentProfile.on('end', function(profileJSON) {
var values = {
avatarUrl : profileJSON.gravatar_url,
username : profileJSON.profile_name,
badges : profileJSON.badges.length,
javascriptPoints: profileJSON.points.JavaScript
};
console.log(values);
//response.write(values.username + ' has ' + values.badges + ' badges.' + "\n");
renderer.view('profile', values, response);
renderer.view('footer', {}, response);
response.end();
});
studentProfile.on('error', function(error) {
renderer.view('search', {}, response);
renderer.view('error', {errorMessage: error.message}, response);
renderer.view('footer', {}, response);
response.end();
});
}
}
function css(request, response) {
var cssData = fs.readFileSync(__dirname + request.url, {encoding: 'utf8'});
response.writeHead(200, {'Content-Type': 'text/css'});
response.write(cssData);
response.end();
}
module.exports.home = home;
module.exports.user = user;
module.exports.css = css;
|
"use strict"
module.exports = angular.module("products.controller", [])
.controller("ProductsController", ['$scope', '$ionicSideMenuDelegate', 'ProductService', 'ControlModalService', 'WishlistService','CartService',
function ($scope, $ionicSideMenuDelegate, ProductService, ControlModalService, WishlistService, CartService) {
$scope.products = ProductService.productCurrent;
$scope.page = ProductService.page;
$scope.openMenu = function () {
$ionicSideMenuDelegate.toggleLeft();
};
$scope.loadMoreData = function () {
var type = $scope.currentcheckCtrl;
var temppage = $scope.page.number;
temppage++;
ProductService.filterProduct(type, 1, temppage).then(
function (data) {
var temp = $scope.products;
temp = temp.concat(data);
angular.copy(temp, $scope.products);//must use angular.copy
$scope.$broadcast('scroll.infiniteScrollComplete');
angular.copy({
number: temppage
}, $scope.page);
}
);
};
$scope.add_to_cart = function (item) {
CartService.addCart(item);
}
$scope.addToWishlist = function (item) {
WishlistService.addWishlist(item);
}
}
]);
|
class Player {
static getSettings () {
return {
auras: auras,
items: selectedItems,
sets: JSON.parse(localStorage.setBonuses),
enchants: selectedEnchants,
gems: selectedGems,
talents: talents,
stats: characterStats,
simSettings: settings,
enemy: {
level: parseInt($("input[name='target-level']").val()),
natureResist: parseInt($("input[name='target-nature-resistance']").val()),
fireResist: parseInt($("input[name='target-fire-resistance']").val()),
armor: parseInt($("input[name='enemyArmor']").val())
},
rotation: rotation,
selectedItemSlot: $("#item-slot-selection-list li[data-selected='true']").attr('data-slot')
}
}
constructor (settings, customItemSlot, customItemSubSlot, customItemId, customStat, customStatValue) {
this.stats = JSON.parse(JSON.stringify(settings.stats)) // Create a deep-copy of the character's stats since we need to modify the values.
this.stats.hastePercent += 1
this.items = JSON.parse(JSON.stringify(settings.items))
this.enemy = settings.enemy
this.rotation = settings.rotation
this.talents = settings.talents
this.simSettings = settings.simSettings
this.level = 70
this.gcdValue = 1.5
this.shattrathFaction = settings.simSettings.shattrathFaction // Aldor or Scryers
this.exaltedWithShattrathFaction = settings.simSettings.shattrathFactionReputation == 'yes'
this.itemId = customItemId || settings.items[settings.selectedItemSlot] || 0
this.sets = JSON.parse(JSON.stringify(settings.sets))
this.selectedAuras = settings.auras
this.minimumGcdValue = 1
// I don't know if this formula only works for bosses or not, so for the moment I'm only using it for lvl >=73 targets.
const enemyBaseResistance = settings.enemy.level >= 73 ? (6 * this.level * 5) / 75 : 0
this.enemy.natureResist = Math.max(this.enemy.natureResist, enemyBaseResistance, 0)
this.enemy.fireResist = Math.max(this.enemy.fireResist, enemyBaseResistance, 0)
this.enemy.natureResist = Math.max(enemyBaseResistance, 0)
this.enemy.arcaneResist = Math.max(enemyBaseResistance, 0)
this.enemy.frostResist = Math.max(enemyBaseResistance, 0)
this.combatlog = []
this.critMultiplier = 1.5
this.importantAuraCounter = 0 // counts the amount of active "important" auras such as trinket procs, on-use trinket uses, power infusion etc.
this.totalManaRegenerated = 0
this.simChoosingRotation = settings.simSettings.rotationOption == 'simChooses'
// The amount to increase spell cast times by.
// This will not have any actual effect on the dps result because of how small the value is, but it will make things a lot more realistic
// because cast times, dot ticks, and such will fall out of sync with each other (which is what happens when a real player is playing)
// and it will make it easier to, for example, pre-cast Immolate to reapply it right after it expires.
// If Immolate has 1.5 seconds remaining, the sim won't start casting immolate because it would refresh before it expires
// so Immolate would need to have ~1.49999s left of its duration for it to start casting.
// But with this delay, Immolate's cast time would be ~1.500001 which would allow it to reapply Immolate when it has 1.5 seconds left
// This should solve that problem if I'm thinking through this correctly.
this.spellDelay = 0.0001
this.customStat = {
stat: customStat,
value: customStatValue
}
// Check if we're finding stat weights
if (this.customStat.stat && this.stats.hasOwnProperty(this.customStat.stat)) {
this.stats[this.customStat.stat] += this.customStat.value
}
this.metaGemIds = []
// Get the meta gem ID
if (settings.gems && settings.gems.head && settings.items.head) {
for (const gemSocket in settings.gems.head[settings.items.head]) {
if (settings.gems.head[settings.items.head][gemSocket]) {
const gemId = settings.gems.head[settings.items.head][gemSocket][1]
if (gems.meta[gemId]) {
this.metaGemIds.push(gemId)
}
}
}
}
// If the player is equipped with a custom item then remove the stats from the currently equipped item and add stats from the custom item
if (customItemSlot && customItemId && customItemId !== settings.items[customItemSlot + customItemSubSlot]) {
// Loop through all items in the custom item slot
for (const item in items[customItemSlot]) {
// Check if this is the currently equipped item
if (items[customItemSlot][item].id == settings.items[customItemSlot + customItemSubSlot]) {
// Remove stats from currently equipped item
for (const stat in items[customItemSlot][item]) {
if (this.stats.hasOwnProperty(stat)) {
this.stats[stat] -= items[customItemSlot][item][stat]
}
}
// Decrement the counter for the set id if it is part of a set
if (items[customItemSlot][item].hasOwnProperty('setId')) {
this.sets[items[customItemSlot][item].setId]--
}
// Remove stats from gems in the equipped item if there are any
// Also check if the item's socket bonus is active and remove the stats from it if so
if (settings.gems[customItemSlot] && settings.gems[customItemSlot][settings.items[customItemSlot + customItemSubSlot]]) {
let socketBonusActive = true
// Loop through each socket in the equipped item
for (const socket in settings.gems[customItemSlot][settings.items[customItemSlot + customItemSubSlot]]) {
if (settings.gems[customItemSlot][settings.items[customItemSlot + customItemSubSlot]][socket]) {
const socketColor = settings.gems[customItemSlot][settings.items[customItemSlot + customItemSubSlot]][socket][0]
const gemId = settings.gems[customItemSlot][settings.items[customItemSlot + customItemSubSlot]][socket][1]
// Find the gem's color since the socket and gem colors might not match
for (const gemColor in gems) {
if (gems[gemColor][gemId]) {
// Check whether the gem color is in the array of gem colors that are valid for this socket color (e.g. checks whether a 'purple' gem is valid for a 'blue' socket)
if (!socketInfo[socketColor].gems.includes(gemColor)) {
socketBonusActive = false
}
if (gemColor == 'meta') {
if (this.metaGemIds.includes(gemId)) {
this.metaGemIds.splice(this.metaGemIds.indexOf(gemId), 1)
}
}
// Loop through the gem's stats and remove them from the player
for (const stat in gems[gemColor][gemId]) {
if (this.stats.hasOwnProperty(stat)) {
this.stats[stat] -= gems[gemColor][gemId][stat]
}
}
}
}
} else { // No gem in this socket
socketBonusActive = false
}
}
// If the socket bonus is active then remove the socket bonus stats
if (socketBonusActive && items[customItemSlot][item].socketBonus) {
for (const stat in items[customItemSlot][item].socketBonus) {
if (this.stats.hasOwnProperty(stat)) {
this.stats[stat] -= items[customItemSlot][item].socketBonus[stat]
} else {
console.log("Can't remove stat '" + stat + "' from player (trying to remove socket bonus)")
}
}
}
}
}
// Check if this is the custom item
else if (items[customItemSlot][item].id == customItemId) {
// Add stats from the item
for (const stat in items[customItemSlot][item]) {
if (this.stats.hasOwnProperty(stat)) {
this.stats[stat] += items[customItemSlot][item][stat]
}
}
// Increment the counter for the set id if it is part of a set
if (items[customItemSlot][item].hasOwnProperty('setId')) {
this.sets[items[customItemSlot][item].setId] = this.sets[items[customItemSlot][item].setId] + 1 || 1 // Have a default value of '1' in case the set id is undefined in the sets array
}
// Add the item's id to its slot in this.items
// This is required for items that are on-use or have a proc such as Band of the Eternal Sage since they check if the item's ID is equipped.
this.items[customItemSlot + customItemSubSlot] = customItemId
// Add stats from any gems equipped in the custom item
if (settings.gems[customItemSlot] && settings.gems[customItemSlot][customItemId]) {
// Boolean to keep track of whether the item's socket bonus is active or not
let socketBonusActive = true
for (const socket in settings.gems[customItemSlot][customItemId]) {
if (settings.gems[customItemSlot][customItemId][socket]) {
const socketColor = settings.gems[customItemSlot][customItemId][socket][0]
const gemId = settings.gems[customItemSlot][customItemId][socket][1]
// Check for meta gem
if (customItemSlot == 'head' && gems.meta[gemId]) {
this.metaGemIds.push(gemId)
}
// Find the gem's color since it might not match the socket color
for (const gemColor in gems) {
if (gems[gemColor][gemId]) {
// Check whether the gem color is in the array of gem colors that are valid for this socket color (e.g. checks whether a 'purple' gem is valid for a 'blue' socket)
if (!socketInfo[socketColor].gems.includes(gemColor)) {
socketBonusActive = false
}
// Add stats from the gem equipped in this socket
for (const stat in gems[gemColor][gemId]) {
if (this.stats.hasOwnProperty(stat)) {
this.stats[stat] += gems[gemColor][gemId][stat]
}
}
}
}
} else { // No gem equipped in this socket
socketBonusActive = false
}
}
// If the socket bonus is active then remove the socket bonus stats
if (socketBonusActive && items[customItemSlot][item].socketBonus) {
for (const stat in items[customItemSlot][item].socketBonus) {
if (this.stats.hasOwnProperty(stat)) {
this.stats[stat] += items[customItemSlot][item].socketBonus[stat]
} else {
console.log("Can't add stat '" + stat + "' to player (trying to add socket bonus)")
}
}
}
}
}
}
if (this.metaGemIds.length > 1) {
console.log(this.metaGemIds.length + ' meta gems equipped, somehow.')
}
}
// this.stats.shadowModifier *= (1 + (0.02 * settings.talents.shadowMastery))
this.spellTravelTime = 1
// The Twin Stars 2-set bonus
if (this.sets['667'] == 2) this.stats.spellPower += 15
// Crit chance
this.stats.critChanceMultiplier = 1000
if (settings.auras.powerOfTheGuardianMage) this.stats.critRating += 28 * this.simSettings.mageAtieshAmount
this.stats.critChance = baseCritChancePercent + (this.stats.critRating / critRatingPerPercent)
if (settings.auras.moonkinAura) this.stats.critChance += 5
if (settings.auras.judgementOfTheCrusader) this.stats.critChance += 3
if (settings.auras.totemOfWrath) this.stats.critChance += (3 * settings.simSettings.totemOfWrathAmount)
if (settings.auras.chainOfTheTwilightOwl) this.stats.critChance += 2
// Hit chance
this.stats.hitChanceMultiplier = 1000
if (settings.sets['658'] >= 2) this.stats.hitRating += 35 // Mana-Etched Regalia 2-set bonus (35 hit rating)
if ( settings.talents.elementalPrecision) this.stats.hitRating += (settings.talents.elementalPrecision * (hitRatingPerPercent * 2))
if ( settings.talents.naturesGuidance) this.stats.hitRating += (settings.talents.naturesGuidance * (hitRatingPerPercent * 1))
this.stats.extraHitChance = this.stats.hitRating / hitRatingPerPercent // hit percent from hit rating
if (settings.auras.totemOfWrath) this.stats.extraHitChance += (3 * settings.simSettings.totemOfWrathAmount)
if (settings.auras.inspiringPresence === true) this.stats.extraHitChance += 1
this.stats.hitChance = Math.round(getBaseHitChance(this.level, parseInt(this.enemy.level))) // The player's chance of hitting the enemy, usually between 83% and 99%
// Ferocious Inspiration
if (settings.auras.ferociousInspiration) {
this.stats.natureModifier *= Math.pow(1.03, settings.simSettings.ferociousInspirationAmount)
this.stats.fireModifier *= Math.pow(1.03, settings.simSettings.ferociousInspirationAmount)
}
// Add % dmg modifiers from Curse of the Elements + Malediction
if (settings.auras.curseOfTheElements) {
this.stats.shadowModifier *= 1.1 + (0.01 * (settings.simSettings.improvedCurseOfTheElements || 0))
this.stats.fireModifier *= 1.1 + (0.01 * (settings.simSettings.improvedCurseOfTheElements || 0))
}
// Add spell power from Fel Armor
if (settings.auras.felArmor) {
this.stats.spellPower += 100
}
// Add spell power from Improved Divine Spirit
this.stats.spiritModifier = 1
if (settings.auras.prayerOfSpirit && settings.simSettings.improvedDivineSpirit) {
this.stats.spellPower += (this.stats.spirit * this.stats.spiritModifier * (0 + (settings.simSettings.improvedDivineSpirit / 20)))
}
// Elemental Shaman T4 2pc bonus
if (settings.auras.wrathOfAirTotem && settings.simSettings.improvedWrathOfAirTotem == "yes") this.stats.spellPower += 20
// Add stamina from Demonic Embrace
this.stats.staminaModifier = 1
// Add mp5 from Vampiric Touch (add 25% instead of 5% since we're adding it to the mana per 5 seconds variable)
if (settings.auras.vampiricTouch) {
this.stats.mp5 += settings.simSettings.shadowPriestDps * 0.25
}
if (settings.auras.powerOfTheGuardianWarlock) {
this.stats.spellPower += 33 * settings.simSettings.warlockAtieshAmount
}
// Enemy Armor Reduction
if (settings.auras.faerieFire) this.enemy.armor -= 610
if ((settings.auras.sunderArmor && settings.auras.exposeArmor && settings.simSettings.improvedExposeArmor == 2) || (settings.auras.exposeArmor && !settings.auras.sunderArmor)) this.enemy.armor -= 2050 * (1 + 0.25 * settings.simSettings.improvedExposeArmor)
else if (settings.auras.sunderArmor) this.enemy.armor -= 520 * 5
if (settings.auras.curseOfRecklessness) this.enemy.armor -= 800
if (settings.auras.annihilator) this.enemy.armor -= 600
this.enemy.armor = Math.max(0, this.enemy.armor)
this.stats.health = (this.stats.health + (this.stats.stamina * this.stats.staminaModifier) * healthPerStamina)
this.stats.maxMana = (this.stats.mana + (this.stats.intellect * this.stats.intellectModifier) * manaPerInt)
// Assign the filler spell.
this.filler = null
for (const spell in settings.rotation.filler) {
if (settings.rotation.filler[spell]) {
this.filler = spell
break
}
}
if (this.filler == null) {
this.filler = 'lightningBolt'
}
// Assign the curse (if selected)
this.curse = null
for (const spell in settings.rotation.curse) {
if (settings.rotation.curse[spell]) {
this.curse = spell
break
}
}
// Records all information about damage done for each spell such as crit %, miss %, average damage per cast etc.
this.damageBreakdown = {}
// Records all information about auras such as how often it was applied and the uptime %.
this.auraBreakdown = {}
// Records all information about mana gain abilities like Life Tap, Mana Pots, and Demonic Runes
this.manaGainBreakdown = { mp5: { name: 'Mp5' } }
if (this.selectedAuras.judgementOfWisdom) this.manaGainBreakdown.judgementOfWisdom = { name: 'Judgement of Wisdom' }
// Pet
this.demonicKnowledgeSp = 0 // Spell Power from the Demonic Knowledge talent
this.combatlog.push('---------------- Player stats ----------------')
this.combatlog.push('Health: ' + Math.round(this.stats.health))
this.combatlog.push('Mana: ' + Math.round(this.stats.maxMana))
this.combatlog.push('Stamina: ' + Math.round(this.stats.stamina * this.stats.staminaModifier))
this.combatlog.push('Intellect: ' + Math.round(this.stats.intellect * this.stats.intellectModifier))
this.combatlog.push('Spell Power: ' + this.getSpellPower())
this.combatlog.push('Nature Power: ' + this.stats.naturePower)
this.combatlog.push('Fire Power: ' + this.stats.firePower)
// this.combatlog.push('Crit Chance: ' + Math.round(this.getCritChance('destruction') * 100) / 100 + '%')
this.combatlog.push('Hit Chance: ' + Math.min(16, Math.round((this.stats.extraHitChance) * 100) / 100) + '%')
this.combatlog.push('Haste: ' + Math.round((this.stats.hasteRating / hasteRatingPerPercent) * 100) / 100 + '%')
this.combatlog.push('Nature Modifier: ' + Math.round(this.stats.natureModifier * 100) + '%')
this.combatlog.push('Fire Modifier: ' + Math.round(this.stats.fireModifier * 100) + '%')
this.combatlog.push('MP5: ' + this.stats.mp5)
this.combatlog.push('Spell Penetration: ' + this.stats.spellPen)
if (this.pet) {
let petAp = this.pet.stats.ap * this.pet.stats.apModifier
// Divide away the hidden 10% Felguard attack power bonus for the combat log to avoid confusion
if (this.pet.pet == PetName.FELGUARD) {
petAp /= 1.1
} else if (this.pet.pet == PetName.SUCCUBUS) {
petAp /= 1.05
}
this.combatlog.push('---------------- Pet stats ----------------')
this.combatlog.push('Stamina: ' + Math.round(this.pet.stats.stamina * this.pet.stats.staminaModifier))
this.combatlog.push('Intellect: ' + Math.round(this.pet.stats.intellect * this.pet.stats.intellectModifier))
this.combatlog.push('Strength: ' + Math.round((this.pet.stats.baseStats.strength + this.pet.stats.buffs.strength) * this.pet.stats.strengthModifier))
this.combatlog.push('Agility: ' + Math.round(this.pet.stats.agility * this.pet.stats.agilityModifier))
this.combatlog.push('Spirit: ' + Math.round((this.pet.stats.baseStats.spirit + this.pet.stats.spirit) * this.pet.stats.spiritModifier))
this.combatlog.push('Attack Power: ' + Math.round(petAp))
this.combatlog.push('Spell Power: ' + Math.round(this.pet.stats.spellPower))
this.combatlog.push('Mana: ' + Math.round(this.pet.stats.maxMana))
this.combatlog.push('MP5: ' + Math.round(this.pet.stats.mp5))
if (this.pet.pet !== PetName.IMP) {
this.combatlog.push('Physical Hit Chance: ' + Math.round(this.pet.getMeleeHitChance() * 100) / 100 + '%')
this.combatlog.push('Physical Crit Chance: ' + Math.round(this.pet.getMeleeCritChance() * 100) / 100 + '% (' + this.pet.critSuppression + '% Crit Suppression Applied)')
this.combatlog.push('Glancing Blow Chance: ' + Math.round(this.pet.glancingBlowChance * 100) / 100 + '%')
}
if (this.pet.pet === PetName.IMP || this.pet.pet === PetName.SUCCUBUS) {
this.combatlog.push('Spell Hit Chance: ' + Math.round(this.pet.getSpellHitChance() * 100) / 100 + '%')
this.combatlog.push('Spell Crit Chance: ' + Math.round(this.pet.getSpellCritChance() * 100) / 100 + '%')
}
this.combatlog.push('Damage Modifier: ' + Math.round(this.pet.stats.damageModifier * 100) + '%')
}
this.combatlog.push('---------------- Enemy stats ----------------')
this.combatlog.push('Level: ' + this.enemy.level)
this.combatlog.push('Nature Resistance: ' + this.enemy.natureResist)
this.combatlog.push('Fire Resistance: ' + this.enemy.fireResist)
if (this.pet && this.pet.pet != PetName.IMP) {
this.combatlog.push('Dodge Chance: ' + this.pet.enemyDodgeChance + '%')
this.combatlog.push('Armor: ' + this.enemy.armor)
this.combatlog.push('Damage Reduction From Armor: ' + Math.round((1 - this.pet.armorMultiplier) * 10000) / 100 + '%')
}
this.combatlog.push('---------------------------------------------')
}
initialize () {
// Trinkets
this.trinkets = []
this.trinketIds = [this.items.trinket1, this.items.trinket2]
if (this.trinketIds.includes(32483)) this.trinkets.push(new SkullOfGuldan(this))
if (this.trinketIds.includes(34429)) this.trinkets.push(new ShiftingNaaruSliver(this))
if (this.trinketIds.includes(33829)) this.trinkets.push(new HexShrunkenHead(this))
if (this.trinketIds.includes(29370)) this.trinkets.push(new IconOfTheSilverCrescent(this))
if (this.trinketIds.includes(29132)) this.trinkets.push(new ScryersBloodgem(this))
if (this.trinketIds.includes(23046)) this.trinkets.push(new RestrainedEssenceOfSapphiron(this))
if (this.trinketIds.includes(29179)) this.trinkets.push(new XirisGift(this))
if (this.trinketIds.includes(25620)) this.trinkets.push(new AncientCrystalTalisman(this))
if (this.trinketIds.includes(28223)) this.trinkets.push(new ArcanistsStone(this))
if (this.trinketIds.includes(25936)) this.trinkets.push(new TerokkarTabletOfVim(this))
if (this.trinketIds.includes(28040)) this.trinkets.push(new VengeanceOfTheIllidari(this))
if (this.trinketIds.includes(24126)) this.trinkets.push(new FigurineLivingRubySerpent(this))
if (this.trinketIds.includes(29376)) this.trinkets.push(new EssenceOfTheMartyr(this))
if (this.trinketIds.includes(30340)) this.trinkets.push(new StarkillersBauble(this))
if (this.trinketIds.includes(38290)) this.trinkets.push(new DarkIronSmokingPipe(this))
// Spells
this.spells = {
lifeTap: new LifeTap(this)
}
if (this.simSettings.fightType == "aoe") {
} else {
if (this.rotation.filler.lightningBolt || this.filler == 'lightningBolt' || this.simChoosingRotation) this.spells.lightningBolt = new LightningBolt(this)
if (this.rotation.dot.corruption || this.simChoosingRotation) this.spells.corruption = new Corruption(this)
if (this.talents.siphonLife && (this.rotation.dot.siphonLife || this.simChoosingRotation)) this.spells.siphonLife = new SiphonLife(this)
if (this.rotation.dot.flameshock || this.simChoosingRotation) this.spells.flameshock = new FlameShock(this)
if (this.rotation.curse.curseOfAgony) this.spells.curseOfAgony = new CurseOfAgony(this)
if (this.rotation.curse.curseOfTheElements) this.spells.curseOfTheElements = new CurseOfTheElements(this)
if (this.rotation.curse.curseOfRecklessness) this.spells.curseOfRecklessness = new CurseOfRecklessness(this)
}
if (this.selectedAuras.destructionPotion) this.spells.destructionPotion = new DestructionPotion(this)
if (this.selectedAuras.superManaPotion) this.spells.superManaPotion = new SuperManaPotion(this)
if (this.selectedAuras.demonicRune) this.spells.demonicRune = new DemonicRune(this)
if (this.selectedAuras.flameCap) this.spells.flameCap = new FlameCap(this)
if (this.simSettings.race == 'orc') this.spells.bloodFury = new BloodFury(this)
if (this.selectedAuras.drumsOfBattle) this.spells.drumsOfBattle = new DrumsOfBattle(this)
else if (this.selectedAuras.drumsOfWar) this.spells.drumsOfWar = new DrumsOfWar(this)
else if (this.selectedAuras.drumsOfRestoration) this.spells.drumsOfRestoration = new DrumsOfRestoration(this)
if (this.items.mainhand == 31336) this.spells.bladeOfWizardry = new BladeOfWizardry(this)
if (this.items.neck == 34678) this.spells.shatteredSunPendantOfAcumen = new ShatteredSunPendantOfAcumen(this)
if (this.items.chest == 28602) this.spells.robeOfTheElderScribes = new RobeOfTheElderScribes(this)
if (this.metaGemIds.includes(25893)) this.spells.mysticalSkyfireDiamond = new MysticalSkyfireDiamond(this)
if (this.metaGemIds.includes(25901)) this.spells.insightfulEarthstormDiamond = new InsightfulEarthstormDiamond(this)
if (this.trinketIds.includes(34470)) this.spells.timbalsFocusingCrystal = new TimbalsFocusingCrystal(this)
if (this.trinketIds.includes(27922)) this.spells.markOfDefiance = new MarkOfDefiance(this)
if (this.talents.lightningOverload > 0) this.spells.lightningOverload = new LightningOverload(this)
if (this.talents.elementalMastery > 0) this.spells.elementalMastery = new ElementalMastery(this)
if (this.trinketIds.includes(28785)) this.spells.theLightningCapacitor = new TheLightningCapacitor(this)
if (this.trinketIds.includes(27683)) this.spells.quagmirransEye = new QuagmirransEye(this)
if (this.trinketIds.includes(28418)) this.spells.shiffarsNexusHorn = new ShiffarsNexusHorn(this)
if (this.trinketIds.includes(30626)) this.spells.sextantOfUnstableCurrents = new SextantOfUnstableCurrents(this)
if ([this.items.ring1, this.items.ring2].includes(29305)) this.spells.bandOfTheEternalSage = new BandOfTheEternalSage(this)
if (this.selectedAuras.powerInfusion) {
this.spells.powerInfusion = []
for (let i = 0; i < this.simSettings.powerInfusionAmount; i++) {
this.spells.powerInfusion.push(new PowerInfusion(this))
}
}
if (this.selectedAuras.bloodlust) {
this.spells.bloodlust = []
for (let i = 0; i < this.simSettings.bloodlustAmount; i++) {
this.spells.bloodlust.push(new Bloodlust(this))
}
}
if (this.selectedAuras.innervate) {
this.spells.innervate = []
for (let i = 0; i < this.simSettings.innervateAmount; i++) {
this.spells.innervate.push(new Innervate(this))
}
}
// Auras
this.auras = {}
if (this.simSettings.fightType == "singleTarget") {
if (this.spells.corruption) this.auras.corruption = new CorruptionDot(this)
if (this.spells.siphonLife) this.auras.siphonLife = new SiphonLifeDot(this)
if (this.spells.flameshock) this.auras.flameshock = new FlameShockDot(this)
if (this.spells.curseOfAgony) this.auras.curseOfAgony = new CurseOfAgonyDot(this)
if (this.rotation.curse.curseOfTheElements) this.auras.curseOfTheElements = new CurseOfTheElementsAura(this)
if (this.rotation.curse.curseOfRecklessness) this.auras.curseOfRecklessness = new CurseOfRecklessnessAura(this)
}
if (this.selectedAuras.powerInfusion) this.auras.powerInfusion = new PowerInfusionAura(this)
if (this.selectedAuras.innervate) this.auras.innervate = new InnervateAura(this)
if (this.simSettings.race == 'orc') this.auras.bloodFury = new BloodFuryAura(this)
if (this.selectedAuras.destructionPotion) this.auras.destructionPotion = new DestructionPotionAura(this)
if (this.selectedAuras.flameCap) this.auras.flameCap = new FlameCapAura(this)
if (this.selectedAuras.bloodlust) this.auras.bloodlust = new BloodlustAura(this)
if (this.selectedAuras.drumsOfBattle) this.auras.drumsOfBattle = new DrumsOfBattleAura(this)
else if (this.selectedAuras.drumsOfWar) this.auras.drumsOfWar = new DrumsOfWarAura(this)
else if (this.selectedAuras.drumsOfRestoration) this.auras.drumsOfRestoration = new DrumsOfRestorationAura(this)
if ([this.items.ring1, this.items.ring2].includes(29305)) this.auras.bandOfTheEternalSage = new BandOfTheEternalSageAura(this)
if ([this.items.ring1, this.items.ring2].includes(21190)) this.auras.wrathOfCenarius = new WrathOfScenarius(this)
if (this.items.mainhand == 31336) this.auras.bladeOfWizardry = new BladeOfWizardryAura(this)
if (this.items.neck == 34678 && this.shattrathFaction == 'Aldor') this.auras.shatteredSunPendantOfAcumen = new ShatteredSunPendantOfAcumenAura(this)
if (this.items.chest == 28602) this.auras.robeOfTheElderScribes = new RobeOfTheElderScribesAura(this)
if (this.metaGemIds.includes(25893)) this.auras.mysticalSkyfireDiamond = new MysticalSkyfireDiamondAura(this)
if (this.trinketIds.includes(28789)) this.auras.eyeOfMagtheridon = new EyeOfMagtheridon(this)
if (this.trinketIds.includes(30626)) this.auras.sextantOfUnstableCurrents = new SextantOfUnstableCurrentsAura(this)
if (this.trinketIds.includes(27683)) this.auras.quagmirransEye = new QuagmirransEyeAura(this)
if (this.trinketIds.includes(28418)) this.auras.shiffarsNexusHorn = new ShiffarsNexusHornAura(this)
if (this.trinketIds.includes(32493)) this.auras.ashtongueTalismanOfShadows = new AshtongueTalismanOfShadows(this)
if (this.trinketIds.includes(31856)) this.auras.darkmoonCardCrusade = new DarkmoonCardCrusadeAura(this)
if (this.trinketIds.includes(28785)) this.auras.theLightningCapacitor = new TheLightningCapacitorAura(this)
if (this.talents.elementalMastery > 0) this.auras.elementalMastery = new ElementalMasteryAura(this)
if (this.talents.elementalFocus > 0) this.auras.clearcasting = new ClearcastingAura(this)
if (this.sets['559'] == 2) this.auras.spellstrikeProc = new SpellstrikeProc(this)
if (this.sets['658'] >= 4) this.auras.manaEtched4Set = new ManaEtched4Set(this)
}
reset () {
this.castTimeRemaining = 0
this.gcdRemaining = 0
this.mana = this.stats.maxMana
this.mp5Timer = 5
this.fiveSecondRuleTimer = 5
this.importantAuraCounter = 0
}
cast (spell, predictedDamage = 0) {
if (this.gcdRemaining > 0 && this.spells[spell].onGcd) {
throw 'Attempting to cast a spell (' + spell + ') on GCD with ' + this.gcdRemaining + ' cooldown remaining.'
}
this.spells[spell].startCast(predictedDamage)
}
areAnyCooldownsReady () {
if (this.spells.bloodlust && !this.auras.bloodlust.active) {
for (let i = 0; i < this.spells.bloodlust.length; i++) {
if (this.spells.bloodlust[i].ready()) {
return true
}
}
}
if (this.auras.powerInfusion && !this.auras.powerInfusion.active) {
for (let i = 0; i < this.spells.powerInfusion.length; i++) {
if (this.spells.powerInfusion[i].ready()) {
return true
}
}
}
if (this.auras.innervate && !this.auras.innervate.active) {
for (let i = 0; i < this.spells.innervate.length; i++) {
if (this.spells.innervate[i].ready()) {
return true
}
}
}
if (this.spells.destructionPotion && this.spells.destructionPotion.ready()) return true
for (let i = 0; i < this.trinkets.length; i++) {
if (this.trinkets[i].ready()) return true
}
if (this.spells.bloodFury && this.spells.bloodFury.ready()) return true
return false
}
useCooldowns () {
if (this.spells.bloodlust && !this.auras.bloodlust.active) {
for (let i = 0; i < this.spells.bloodlust.length; i++) {
if (this.spells.bloodlust[i].ready()) {
this.spells.bloodlust[i].startCast()
break
}
}
}
// Only use Power Infusion if Bloodlust wasn't chosen or if Bloodlust isn't active since they don't stack together
if (this.spells.powerInfusion && !this.auras.powerInfusion.active && (!this.auras.bloodlust || !this.auras.bloodlust.active)) {
for (let i = 0; i < this.spells.powerInfusion.length; i++) {
if (this.spells.powerInfusion[i].ready()) {
this.spells.powerInfusion[i].startCast()
break
}
}
}
if (this.spells.innervate && !this.auras.innervate.active) {
for (let i = 0; i < this.spells.innervate.length; i++) {
if (this.spells.innervate[i].ready()) {
this.spells.innervate[i].startCast()
break
}
}
}
if (this.spells.destructionPotion && this.spells.destructionPotion.ready()) {
this.cast('destructionPotion')
}
if (this.spells.elementalMastery && this.spells.elementalMastery.ready()){
this.cast('elementalMastery')
}
if (this.spells.flameCap && this.spells.flameCap.ready()) {
this.cast('flameCap')
}
if (this.spells.bloodFury && this.spells.bloodFury.ready()) {
this.cast('bloodFury')
}
for (let i = 0; i < this.trinkets.length; i++) {
if (this.trinkets[i] && this.trinkets[i].ready()) {
this.trinkets[i].use()
// Set the other on-use trinket (if another is equipped) on cooldown for the duration of the trinket just used if the trinkets share cooldown
const otherTrinketSlot = i == 1 ? 2 : 1
if (this.trinkets[otherTrinketSlot] && this.trinkets[otherTrinketSlot].sharesCooldown && this.trinkets[i].sharesCooldown) {
this.trinkets[otherTrinketSlot].cooldownRemaining = Math.max(this.trinkets[otherTrinketSlot].cooldownRemaining, this.trinkets[i].duration)
}
}
}
}
castLifeTapOrDarkPact() {
this.cast('lifeTap')
}
getGcdValue(spellVarName = '') {
let hastePercent = this.stats.hastePercent
// If both Bloodlust and Power Infusion are active then remove the 20% bonus from Power Infusion since they don't stack
if (this.auras.powerInfusion && this.auras.bloodlust && this.auras.powerInfusion.active && this.auras.bloodlust.active) {
hastePercent /= 1.2
}
return Math.max(this.minimumGcdValue, Math.round(this.gcdValue / ((1 + (this.stats.hasteRating / hasteRatingPerPercent / 100)) * hastePercent) * 10000) / 10000)
}
getHitChance(isAfflictionSpell) {
let hitChance = this.stats.hitChance + this.stats.extraHitChance
if (isAfflictionSpell) {
hitChance += this.talents.convection * 2
}
return Math.min(99, hitChance)
}
isHit (isAfflictionSpell) {
const hit = (random(1, 100 * this.stats.hitChanceMultiplier) <= this.getHitChance(isAfflictionSpell) * this.stats.hitChanceMultiplier)
// Eye of Magtheridon
if (!hit && this.trinketIds.includes(28789)) {
this.auras.eyeOfMagtheridon.apply()
}
return hit
}
getSpellPower() {
let spellPower = this.stats.spellPower + this.demonicKnowledgeSp
// Spellfire 3-set bonus
if (this.sets['552'] == 3) {
spellPower += this.stats.intellect * this.stats.intellectModifier * 0.07
}
return Math.round(spellPower)
}
// Returns the crit percentage of the player.
// Since crit gains a bonus from intellect, and intellect could fluctuate during the fight (through procs and such), it's better to calculate it by calling a function like this.
getCritChance (spell) {
let critChance = this.stats.critChance + ((this.stats.intellect * this.stats.intellectModifier) * critPerInt)
if( (spell.name == "Lightning Bolt" || spell.name == "Chain Lightning"))
{
critChance += this.talents.callOfThunder
critChance += this.talents.tidalMastery
}
return critChance
}
isCrit (spell, extraCrit = 0) {
return (random(1, (100 * this.stats.critChanceMultiplier)) <= ((this.getCritChance(spell) + extraCrit) * this.stats.critChanceMultiplier))
}
// The formula is (75 * resistance) / (playerLevel * 5) which gives the number to multiply the damage with (between 0 and 1) to simulate the average partial resist mitigation.
getPartialResistMultiplier (resist) {
return 1 - ((75 * resist) / (this.level * 5)) / 100
}
combatLog (info) {
if (this.iteration == 2) {
this.combatlog.push('|' + (Math.round(this.fightTime * 10000) / 10000).toFixed(4) + '| ' + info)
}
}
}
|
// inputs
const submitBtn = document.getElementById("submit-btn");
const nameInput = document.getElementById("name");
const DOBInput = document.getElementById("DOB");
const emailInput = document.getElementById("email");
const ContactNumberInput = document.getElementById("Contact-number");
const hobbiesInput = document.getElementById("hobbies");
submitBtn.addEventListener('click',(e)=>{
validateInputs();
})
// validate on length
const validateInputs =()=>{
if(nameInput.value.length===0)
{
alert('Name field is required');
return;
}
else if(DOBInput.value.length===0)
{
alert('Date of Birth field is required');
return;
}
else if(emailInput.value.length===0)
{
alert('Email field is required');
return;
}
else if(ContactNumberInput.value.length===0)
{
alert('Contact Numer is required');
return;
}
else if(hobbiesInput.value.length===0)
{
alert('Hobbies field is required');
return;
}
if(!validateEmail(emailInput.value))
{
alert('Email is invalid');
return;
}
if(!validateContactNum(ContactNumberInput.value))
{
alert('Contact number is invalid');
return;
}
alert('Form submitted successfully!');
clearInputs();
}
// validation for email
const validateEmail=(email)=>{
const re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(String(email).toLowerCase());
}
// validation for contact number
const validateContactNum =(num)=>{
const number = parseInt(num);
console.log(number);
if(number < 1000000000 && number > 9999999999)
{
return false;
}
return true;
}
// after submitted, clear form
const clearInputs=()=>{
nameInput.value='';
DOBInput.value='';
emailInput.value='';
ContactNumberInput.value='';
hobbiesInput.value='';
}
|
import React from 'react'
import { connect } from 'react-redux'
import LoginForm from 'app/components/forms/login'
import { loginUser } from 'app/actions/session'
export default connect((state) => state)(({ dispatch }) => (
<LoginForm onSubmit={({ email, password }) => dispatch(loginUser(email, password))} />
))
|
var mongoose = require('mongoose'); // mongo db
// define model =================
var Miracle = mongoose.model('Miracles', {
name: String,
date: String,
location: String,
title: String,
category: String,
desc: String,
username: String
});
module.exports = Miracle;
|
module.exports = {
port: 8080,
projectRoot: "/build",
database: {
engine: "postgres",
host: "TFB-database",
user: "benchmarkdbuser",
password: "benchmarkdbpass",
database: "hello_world",
port: 5432,
// Will check models against current scheme and perform migrations
migrations: false
}
};
|
var isBgEffectActive = true;
var timer;
var timerInterval = 500;
var opacity = 0;
var timerStep = 0.05;
var IsMenuActivate = false;
function Init() {
document.getElementById("topBar").innerHTML = '<h2 id="title">' + document.title.split(' - ')[1].split(' ')[0] + '</h2>' + document.getElementById("topBar").innerHTML;
document.getElementById("title").style.margin = "0 0 0 65px";
var column = document.getElementById("center_column");
column.style.maxWidth = "100%";
column.style.marginLeft = "0";
column.style.left = "0";
CloseMenu();
Resize();
if (window.addEventListener)
window.addEventListener('click', Click);
else {
document.attachEvent("onclick", Click);
}
isBgEffectActive = !checkCookie("backGround");
if (isBgEffectActive) {
timer = window.setTimeout("Timer();", timerInterval);
} else {
UpdateBackground();
}
}
function UpdateBackground() {
isBgEffectActive = !checkCookie("backGround");
if (isBgEffectActive) {
//var tmp = GetCookie("_bg_opacity");
//opacity = tmp == undefined ? 0 : parseInt(tmp);
//window.addEventListener('beforeunload', SaveOpacity);
var back = document.getElementById("firstBack");
back.style.background = "url('images/background.png')";
document.getElementById('secondBack').style.left = "0";
//timer = window.setTimeout("Timer();", timerInterval);
} else {
var src = GetCookie("backGround");
var back = document.getElementById("firstBack");
back.style.background = "url('" + src + "')";
document.getElementById('secondBack').style.opacity = "0";
document.getElementById('secondBack').style.left = "-100%";
}
}
//function SaveOpacity() {
// //alert("---- "+opacity);
// if (opacity > 1)
// opacity = 1;
// if (opacity < 0)
// opacity = 0;
// SetCookie("_bg_opacity", opacity);
// window.onbeforeunload = undefined;
//}
//TIMER
function Timer() {
if (!isBgEffectActive) return;
if (opacity >= 1.1 || opacity < -0.1) {
timerStep *= -1;
}
opacity += timerStep;
document.getElementById('secondBack').style.opacity = "" + opacity;
timer = window.setTimeout("Timer();", timerInterval);
}
var IsMenuOpend = false;
//RESIZE
function Resize() {
var w = window,
d = document,
e = d.documentElement,
g = d.getElementsByTagName('body')[0],
widthWindow = w.innerWidth || e.clientWidth || g.clientWidth,
heightWindow = w.innerHeight || e.clientHeight || g.clientHeight;
var width = widthWindow;
var column = d.getElementById("center_column");
document.getElementById('leftMenu').style.width = 200 + "px";
document.getElementById('leftMenu').style.height = (heightWindow - 45) + "px";
var left;
if (widthWindow < 1000) {
width = widthWindow * 0.98;
if (width > 800)
width = 800;
left = (widthWindow - width) / 2;
document.getElementById('topBar').style.left = '0';
document.getElementById('leftMenu').style.top = '45px';
if (widthWindow < 400)
document.getElementById('leftMenu').style.width = (widthWindow * 0.8) + "px";
MenuClosed();
} else {
width = widthWindow * 0.6;
if (width < 800)
width = 800;
left = 200 + (widthWindow - 200 - width) / 2;
document.getElementById('topBar').style.left = '200px';
document.getElementById('leftMenu').style.top = '0';
document.getElementById('leftMenu').style.left = '0';
document.getElementById('leftMenu').style.height = heightWindow + 'px';
MenuOpend();
}
column.style.width = width + "px";
column.style.left = left + "px";
}
function MenuOpend() {
if (IsMenuOpend) return;
IsMenuOpend = true;
document.getElementById('menuButton').style.left = "-100%";
document.getElementById('title').style.margin = "0 0 0 20px";
ActivateMenu();
}
function MenuClosed() {
if (!IsMenuOpend) return;
IsMenuOpend = false;
document.getElementById('menuButton').style.left = "0";
document.getElementById('title').style.margin = "0 0 0 65px";
CloseMenu();
IsMenuActivate = false;
}
//MENU
function Click(event) {
event = event || window.event;
if (IsMenuOpend) return;
if (IsMenuActivate) {
CloseMenu();
} else {
if (event.target) {
if (event.target.id == 'menuButton')
ActivateMenu();
} else {
if (event.srcElement.id == 'menuButton')
ActivateMenu();
}
}
}
function ActivateMenu() {
if (IsMenuOpend) return;
document.getElementById('leftMenu').style.left = '0px';
IsMenuActivate = true;
}
function CloseMenu() {
document.getElementById('leftMenu').style.left = '-100%';
IsMenuActivate = false;
}
|
$(document).ready(function(){
$("#agregar").click(function(){
var item = $("#lista").children().last().clone();
item.text(parseInt(item.text())+1);
$("#lista").append(item);
})
$("#quitar").click(function(){
$("#lista").children().first().remove();
})
});
|
import './modal.scss';
import JSXComponent from 'metal-jsx';
class Modal extends JSXComponent {
/**
* Renders the component's content. Note that data can be accessed via the
* `props` property.
*/
render() {
return <div class="modal show">
<div class="modal-dialog">
<div class="modal-content">
<header class="modal-header">
<button type="button" class="close">
<span>×</span>
</button>
<h4>{this.props.header}</h4>
</header>
<section class="modal-body">
{this.props.body}
</section>
<footer class="modal-footer">
<button type="button" class="btn btn-primary">OK</button>
</footer>
</div>
</div>
</div>;
}
}
export default Modal;
|
module.exports = function(grunt) {
'use strict';
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
meta: {
banner: {
dist: '/*!\n'+
' * <%= pkg.name %> v<%= pkg.version %> - <%= pkg.description %>\n'+
' */\n'
},
outputDir: 'js/dist',
output : '<%= meta.outputDir %>/<%= pkg.main %>',
outputMin : '<%= meta.outputDir %>/<%= pkg.main.replace("js", "min.js") %>'
},
concat: {
options: {
separator: ''
},
dist: {
src: [
'js/vendor/underscore-min.js',
'js/vendor/eveline.js',
'js/vendor/canvasquery.js',
'js/vendor/dat-gui.js',
'js/engine/engine.js',
'js/engine/loader.js',
'js/engine/assets.js',
'js/engine/application.js',
'js/engine/scene.js',
'js/engine/collection.js',
'js/engine/utils.js',
'js/main.js',
'js/entity/*.js',
'js/game.js',
],
dest: '<%= meta.output %>.js'
}
},
uglify: {
dist: {
options: {
banner: '<%= meta.banner.dist %>'
},
files: {
'<%= meta.outputDir %>/<%= pkg.main %>.min.js': ['<%= concat.dist.dest %>']
}
},
},
// jshint: {
// files: ['Gruntfile.js', 'js/']
// },
});
// Load the plugin that provides the "uglify" task.
grunt.loadNpmTasks('grunt-contrib-uglify');
//grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-concat');
// Default task(s).
grunt.registerTask('test', [/*'jshint'*/]);
grunt.registerTask('default', ['test','concat','uglify']);
};
|
//终端中要输入:npx webpack ./src/main.js ./dist/bundle.js
//1.commonjs模块化规范
const {add,mul}=require('./js/math.js'); //打包的时候打包该入口文件就可,会自动识别有没有其他依赖文件
console.log(add(20,30));
console.log(mul(20,30));
//2.ES6模块化规范
import {name,height} from "./js/info.js";
console.log(name);
console.log(height);
//3.依赖css文件,还必须有两个loader
require('./css/normal.css');
//4.依赖less文件
require('./css/special.less');
document.writeln('<h2>这个与write的区别是可以换行</h2>');
//5.使用vue进行开发
import Vue from 'vue';
//import App from './vue/app.js';
import App from './vue/app.vue'; //同样需要相应的loader
//以下内容可以打包到另外的js文件或者vue文件
// const App={ //定义一个组件
// //以下会自动替换到html结构中,不用在html中写出并反复修改
// //切记template中必须有一个根标签!!!!!!!极易忘!!!!!!!!
// template:`
// <div>
// <h2>{{message}} {{name}}</h2>
// <button @click="btn">按钮</button>
// </div>
// `,
// data(){
// return {
// message:'hello webpack',
// name:"cyj"
// }
// },
// methods:{
// btn(){
// }
// }
// }
const app=new Vue({
el:'#app',
template:'<App></App>',
components:{
App //注册组件,ES6增强语法
}
});
document.writeln("<h1>本地服务器可以实时更新</h1>"); //在预格式标签<pre>中会换行
|
import $ from '../../core/renderer';
import Button from '../button';
import { move, locate } from '../../animation/translator';
import messageLocalization from '../../localization/message';
import { FunctionTemplate } from '../../core/templates/function_template';
import { when } from '../../core/utils/deferred';
import { extendFromObject } from '../../core/utils/extend';
import { getBoundingRect } from '../../core/utils/position';
import { AppointmentTooltipInfo } from './dataStructures';
import { LIST_ITEM_DATA_KEY, LIST_ITEM_CLASS } from './constants';
var APPOINTMENT_COLLECTOR_CLASS = 'dx-scheduler-appointment-collector';
var COMPACT_APPOINTMENT_COLLECTOR_CLASS = APPOINTMENT_COLLECTOR_CLASS + '-compact';
var APPOINTMENT_COLLECTOR_CONTENT_CLASS = APPOINTMENT_COLLECTOR_CLASS + '-content';
var WEEK_VIEW_COLLECTOR_OFFSET = 5;
var COMPACT_THEME_WEEK_VIEW_COLLECTOR_OFFSET = 1;
export class CompactAppointmentsHelper {
constructor(instance) {
this.instance = instance;
this.elements = [];
}
render(options) {
var {
isCompact,
items,
buttonColor
} = options;
var template = this._createTemplate(items.data.length, isCompact);
var button = this._createCompactButton(template, options);
var $button = button.$element();
this._makeBackgroundColor($button, items.colors, buttonColor);
this._makeBackgroundDarker($button);
this.elements.push($button);
$button.data('items', this._createTooltipInfos(items));
return $button;
}
clear() {
this.elements.forEach(button => {
button.detach();
button.remove();
});
this.elements = [];
}
_createTooltipInfos(items) {
return items.data.map((appointment, index) => {
var _items$settings;
var targetedAdapter = this.instance.createAppointmentAdapter(appointment).clone();
if (((_items$settings = items.settings) === null || _items$settings === void 0 ? void 0 : _items$settings.length) > 0) {
var {
info
} = items.settings[index];
targetedAdapter.startDate = info.sourceAppointment.startDate;
targetedAdapter.endDate = info.sourceAppointment.endDate;
}
return new AppointmentTooltipInfo(appointment, targetedAdapter.source(), items.colors[index], items.settings[index]);
});
}
_onButtonClick(e, options) {
var $button = $(e.element);
this.instance.showAppointmentTooltipCore($button, $button.data('items'), this._getExtraOptionsForTooltip(options, $button));
}
_getExtraOptionsForTooltip(options, $appointmentCollector) {
return {
clickEvent: this._clickEvent(options.onAppointmentClick).bind(this),
dragBehavior: options.allowDrag && this._createTooltipDragBehavior($appointmentCollector).bind(this),
dropDownAppointmentTemplate: this.instance.option().dropDownAppointmentTemplate,
// deprecated option
isButtonClick: true
};
}
_clickEvent(onAppointmentClick) {
return e => {
var config = {
itemData: e.itemData.appointment,
itemElement: e.itemElement,
targetedAppointment: e.itemData.targetedAppointment
};
var createClickEvent = extendFromObject(this.instance.fire('mapAppointmentFields', config), e, false);
delete createClickEvent.itemData;
delete createClickEvent.itemIndex;
delete createClickEvent.itemElement;
onAppointmentClick(createClickEvent);
};
}
_createTooltipDragBehavior($appointmentCollector) {
return e => {
var $element = $(e.element);
var workSpace = this.instance.getWorkSpace();
var getItemData = itemElement => {
var _$$data;
return (_$$data = $(itemElement).data(LIST_ITEM_DATA_KEY)) === null || _$$data === void 0 ? void 0 : _$$data.appointment;
};
var getItemSettings = (_, event) => {
return event.itemSettings;
};
var initialPosition = locate($appointmentCollector);
var options = {
filter: ".".concat(LIST_ITEM_CLASS),
isSetCursorOffset: true,
initialPosition,
getItemData,
getItemSettings
};
workSpace._createDragBehaviorBase($element, options);
};
}
_getCollectorOffset(width, cellWidth) {
return cellWidth - width - this._getCollectorRightOffset();
}
_getCollectorRightOffset() {
return this.instance.getRenderingStrategyInstance()._isCompactTheme() ? COMPACT_THEME_WEEK_VIEW_COLLECTOR_OFFSET : WEEK_VIEW_COLLECTOR_OFFSET;
}
_makeBackgroundDarker(button) {
button.css('boxShadow', "inset ".concat(getBoundingRect(button.get(0)).width, "px 0 0 0 rgba(0, 0, 0, 0.3)"));
}
_makeBackgroundColor($button, colors, color) {
when.apply(null, colors).done(function () {
this._makeBackgroundColorCore($button, color, arguments);
}.bind(this));
}
_makeBackgroundColorCore($button, color, itemsColors) {
var paintButton = true;
var currentItemColor;
color && color.done(function (color) {
if (itemsColors.length) {
currentItemColor = itemsColors[0];
for (var i = 1; i < itemsColors.length; i++) {
if (currentItemColor !== itemsColors[i]) {
paintButton = false;
break;
}
currentItemColor = color;
}
}
color && paintButton && $button.css('backgroundColor', color);
}.bind(this));
}
_setPosition(element, position) {
move(element, {
top: position.top,
left: position.left
});
}
_createCompactButton(template, options) {
var $button = this._createCompactButtonElement(options);
return this.instance._createComponent($button, Button, {
type: 'default',
width: options.width,
height: options.height,
onClick: e => this._onButtonClick(e, options),
template: this._renderTemplate(template, options.items, options.isCompact)
});
}
_createCompactButtonElement(_ref) {
var {
isCompact,
$container,
width,
coordinates,
applyOffset,
cellWidth
} = _ref;
var result = $('<div>').addClass(APPOINTMENT_COLLECTOR_CLASS).toggleClass(COMPACT_APPOINTMENT_COLLECTOR_CLASS, isCompact).appendTo($container);
var offset = applyOffset ? this._getCollectorOffset(width, cellWidth) : 0;
this._setPosition(result, {
top: coordinates.top,
left: coordinates.left + offset
});
return result;
}
_renderTemplate(template, items, isCompact) {
return new FunctionTemplate(options => {
return template.render({
model: {
appointmentCount: items.data.length,
isCompact: isCompact
},
container: options.container
});
});
}
_createTemplate(count, isCompact) {
this._initButtonTemplate(count, isCompact);
return this.instance._getAppointmentTemplate('appointmentCollectorTemplate');
}
_initButtonTemplate(count, isCompact) {
this.instance._templateManager.addDefaultTemplates({
appointmentCollector: new FunctionTemplate(options => this._createButtonTemplate(count, $(options.container), isCompact))
});
}
_createButtonTemplate(appointmentCount, element, isCompact) {
var text = isCompact ? appointmentCount : messageLocalization.getFormatter('dxScheduler-moreAppointments')(appointmentCount);
return element.append($('<span>').text(text)).addClass(APPOINTMENT_COLLECTOR_CONTENT_CLASS);
}
}
|
//Get the Medooze Media Server interface
const MediaServer = require("medooze-media-server");
//Get Semantic SDP objects
const SemanticSDP = require("semantic-sdp");
const SDPInfo = SemanticSDP.SDPInfo;
const MediaInfo = SemanticSDP.MediaInfo;
const CandidateInfo = SemanticSDP.CandidateInfo;
const DTLSInfo = SemanticSDP.DTLSInfo;
const ICEInfo = SemanticSDP.ICEInfo;
const StreamInfo = SemanticSDP.StreamInfo;
const TrackInfo = SemanticSDP.TrackInfo;
const Direction = SemanticSDP.Direction;
const CodecInfo = SemanticSDP.CodecInfo;
module.exports = function(request,protocol,endpoint)
{
const connection = request.accept(protocol);
connection.on('message', (frame) =>
{
//Get cmd
var msg = JSON.parse(frame.utf8Data);
//Get cmd
if (msg.cmd==="OFFER")
{
//Process the sdp
var offer = SDPInfo.process(msg.offer);
//Create an DTLS ICE transport in that enpoint
const transport = endpoint.createTransport(offer);
//Set RTP remote properties
transport.setRemoteProperties(offer);
//Get local DTLS and ICE info
const dtls = transport.getLocalDTLSInfo();
const ice = transport.getLocalICEInfo();
//Get local candidates
const candidates = endpoint.getLocalCandidates();
//Create local SDP info
let answer = new SDPInfo();
//Add ice and dtls info
answer.setDTLS(dtls);
answer.setICE(ice);
//For each local candidate
for (let i=0;i<candidates.length;++i)
//Add candidate to media info
answer.addCandidate(candidates[i]);
//Get remote video m-line info
let videoOffer = offer.getMedia("video");
//If offer had video
if (videoOffer)
{
//Create video answer
const video = videoOffer.answer({
codecs: CodecInfo.MapFromNames(["VP8"], true),
extensions: new Set([
"urn:ietf:params:rtp-hdrext:toffset",
"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",
//"urn:3gpp:video-orientation",
"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",
"http://www.webrtc.org/experiments/rtp-hdrext/playout-delay",
"urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id",
"urn:ietf:params:rtp-hdrext:sdes:repair-rtp-stream-id",
"urn:ietf:params:rtp-hdrext:sdes:mid",
]),
simulcast: true
});
//Limit incoming bitrate
video.setBitrate(4096);
//Add it to answer
answer.addMedia(video);
}
//Set RTP local properties
transport.setLocalProperties({
video : answer.getMedia("video")
});
const ts = Date.now();
//Dump contents
//transport.dump("/tmp/"+ts+".pcap");
//Create recoreder
const recorder = MediaServer.createRecorder ("/tmp/"+ts +".mp4");
//For each stream offered
for (let offered of offer.getStreams().values())
{
//Create the remote stream into the transport
const incomingStream = transport.createIncomingStream(offered);
//Create new local stream
const outgoingStream = transport.createOutgoingStream({
audio: false,
video: true
});
//Get local stream info
const info = outgoingStream.getStreamInfo();
//Copy incoming data from the remote stream to the local one
connection.transporder = outgoingStream.attachTo(incomingStream)[0];
//Add local stream info it to the answer
answer.addStream(info);
//Record it
recorder.record(incomingStream);
}
//Send response
connection.sendUTF(JSON.stringify({
answer : answer.toString()
}));
//Close on disconnect
connection.on("close",() => {
//Stop transport an recorded
transport.stop();
recorder.stop();
});
} else {
connection.transporder.selectEncoding(msg.rid);
//Select layer
connection.transporder.selectLayer(parseInt(msg.spatialLayerId),parseInt(msg.temporalLayerId));
}
});
};
|
$(".show-menu").click(function() {
$(".main-nav").slideToggle("slow");
});
|
import React, {Fragment} from 'react'
import Container from "@material-ui/core/Container";
import Button from "@material-ui/core/Button";
import Grid from "@material-ui/core/Grid";
import Paper from "@material-ui/core/Paper";
import makeStyles from "@material-ui/core/styles/makeStyles";
import MapContainer from '../components/MapContainer'
import withStyles from "@material-ui/core/styles/withStyles";
import Box from "@material-ui/core/Box";
import AppBar from "../components/NavBar";
import BuildingList from "../components/BuildingList";
import BuildingCard from "../components/BuildingCard";
import Typography from "@material-ui/core/Typography";
import {
BrowserRouter as Router,
Switch,
Route,
Link, withRouter
} from "react-router-dom";
import MainView from "./MainView";
import ProfileView from "./ProfileView";
import IconButton from "@material-ui/core/IconButton";
import CloseIcon from '@material-ui/icons/Close';
import TextField from "@material-ui/core/TextField";
const useStyles = theme => ({
paper: {
marginTop: theme.spacing(3)
},
title: {
marginTop: theme.spacing(1),
marginBottom: theme.spacing(1),
marginLeft: theme.spacing(1),
marginRight: theme.spacing(1)
},
closeButton:{
alignItems:'flex-end',
},
textBox:{
marginTop: theme.spacing(1),
marginBottom: theme.spacing(1),
marginLeft: theme.spacing(1),
marginRight: theme.spacing(1)
},
sendButton:{
marginTop: theme.spacing(1),
marginBottom: theme.spacing(1),
marginLeft: theme.spacing(1),
marginRight: theme.spacing(1),
alignContent: 'right'
}
});
class LoginView extends React.Component {
constructor(props) {
super(props);
this.state = {}
}
componentDidMount() {
}
render() {
const {classes} = this.props;
return (
<Container maxWidth="100%" justify="center">
<Grid direction="row">
<Typography variant={'h4'}
className={classes.title}>Login</Typography>
</Grid>
<Grid direction="row">
<TextField
id="filled-required"
label="Username"
variant="filled"
/>
</Grid>
<Grid direction="row">
<TextField
id="filled-password-input"
label="Password"
type="password"
autoComplete="current-password"
variant="filled"
/>
</Grid>
<Grid direction="row">
<Button variant="contained" color="primary" href={'/'}>
Log in
</Button>
</Grid>
</Container>
)
}
}
export default (withStyles(useStyles)(LoginView))
|
export { default as Profile } from './profile';
export { default as Industry } from './industry';
export { default as Problem } from './problem';
export { default as Category } from './category';
export { default as Technology } from './technology';
export { default as Advantage } from './advantage';
|
import React from 'react';
import { Button } from 'react-native';
import { createStackNavigator, createAppContainer } from 'react-navigation';
import { useCavy } from 'cavy';
import scenarios from './scenarios';
// Create our HomeScreen which contains a button to each of our test scenarios.
const HomeScreen = ({ navigation }) => {
const generateTestHook = useCavy();
return (
<>
{scenarios.map(scenario => (
<Button
key={scenario.key}
ref={generateTestHook(scenario.key)}
title={scenario.label}
onPress={() => navigation.navigate(scenario.key)}
/>
))}
</>
);
};
// Create a navigation route to each of our test scenarios.
const scenarioRoutes = scenarios.reduce((acc, scenario) => {
acc[scenario.key] = {
screen: scenario.Screen,
navigationOptions: { title: scenario.label },
};
return acc;
}, {});
// Our app navigator, containing the navigation to each of our test scenarios.
const MainNavigator = createStackNavigator({
Home: { screen: HomeScreen },
...scenarioRoutes,
});
const AppContainer = createAppContainer(MainNavigator);
// Wrap our app in the Tester component, containing all our test scenarios.
export default App = () => <AppContainer />;
|
import React,{useEffect,useContext} from 'react';
import ListDetails from './ListDetails'
import {hideProductDetailsPage
} from './../../redux/actions'
import {ProductContext} from '../../ProductContext';
import {initMaterialbox} from './../../utilities/form'
function ProductDetails(props){
useEffect(()=>{
initMaterialbox()
});
const {productDetailsDisplay,dispatch} = useContext(ProductContext)
const display = productDetailsDisplay.display;
useEffect(()=>{
console.log('productDetailsDisplayStatus',productDetailsDisplay)
})
return(
<div className='navbar-fixed '>
<nav>
<div className="nav-wrapper white ">
<ul className={`collection product-details col s4 m6 lighten-3 fixed scale-transition ${display}`}>
<ListDetails onClick={()=>{dispatch(hideProductDetailsPage())}} />
</ul>
</div>
</nav>
</div>
)
}
export default ProductDetails
|
'use strict';
import React, { Component,PropTypes } from 'react';
import {
View,
ToastAndroid,
StyleSheet,
Platform,
NativeModules
} from 'react-native';
const toastModule = NativeModules.RNModule;
module.exports = {
//安卓情况下,
// msg:提示信息
// duration:提示信息持续显示的时间 默认SHORT , 传值“long(转小写)”为LONG
//ios,
// msg:提示信息
//duration:(单位秒数) 提示信息持续显示的时间,默认1.5s
ToastShow(msg,duration){
if (Platform.OS === 'android') {
return ToastAndroid.show(msg,
duration ?
(duration.toLowerCase() === "long" ? ToastAndroid.LONG : ToastAndroid.SHORT)
: ToastAndroid.SHORT);
}else{
// var showTime = !isNaN(duration) ? duration : 1.5;
toastModule.hideHUD();
toastModule.showMessage(msg);
// toastModule.showMessageWithTime(msg,showTime);
}
}
}
|
(function() {
'use strict';
angular.module('core')
.factory('Feed', ['common', 'DS',
function(common, DS) {
var Model = DS.defineResource('feed');
var service = {
data: [],
list: list,
fetching: false,
model: Model
};
return service;
/////////////////////
function list($page) {
return getList($page);
}
function getList($page) {
$page = ($page == 'undefined') ? 1 : $page;
return Model.findAll({'page': $page})
.then(function(data) {
service.fetching = false;
return data;
})
.catch(function(error) {
common.logger.error('Error retrieving data for ' + Model.name, error);
});
}
}]);
}());
|
var forbidden = [''];
$('#vendoritemcapacityexception-exception_date').datepicker({
startDate: 'today',
autoclose: true,
format: 'dd-mm-yyyy',
beforeShowDay:function(Date){
//
var curr_day = Date.getDate();
var curr_month = Date.getMonth()+1;
var curr_year = Date.getFullYear();
var curr_date = curr_month+'/'+curr_day+'/'+curr_year;
if (forbidden.indexOf(curr_date)>-1) return false;
}
});
|
import {PolymerElement, html} from '@polymer/polymer';
class Form2Demo extends PolymerElement {
static get template() {
return html`
<style include="iron-flex iron-flex-alignment iron-flex-factors">
</style>
<div class="layout horizontal">
<div class="leftmainbox">
</div>
<div class="flex-9 rightmainbox">
<page-toolbar>
<div maintitle>My Form</div>
</page-toolbar>
<div class="layout horizontal">
<vertical-tabs class="flex-1">
<vertical-tab>Inbox</vertical-tab>
<vertical-tab>Starred</vertical-tab>
<vertical-tab>Sent Items</vertical-tab>
<vertical-tab>Official</vertical-tab>
</vertical-tabs>
<div class="flex-7 form-container">
</div>
</div>
</div>
</div>
`;
}
constructor() {
super();
}
}
customElements.define('form2-demo', Form2Demo);
|
// https://github.com/OvellesNegres/solution-lab-chronometer-js/blob/main/javascript/chronometer.js
class Chronometer {
constructor() {
this.currentTime = 0;
this.intervalId = null;
this.currentMilliseconds = 0;
}
start(callback) {
//!! Remember to save the interval execution in the intervalId property
this.intervalId = setInterval(() => {
//!!If there is a callback, execute it, it it isn't the code will ignore the execution
if (callback) callback();
this.currentTime += 1;
//this.currentTime++
}, 10);
}
getMinutes() {
let minutes = Math.floor(this.currentTime / 100 / 60);
return minutes;
// ... your code goes here
}
getSeconds() {
let minutes = this.currentTime / 100 / 60;
let seconds = Math.floor((minutes - Math.floor(minutes)) * 60);
return seconds;
// ... your code goes here
}
getMilliseconds() {
return this.currentTime % 100;
}
computeTwoDigitNumber(value) {
return String(value).padStart(2, 0);
// (OR) return ('0' + value).slice(-2);
// ... your code goes here
}
stop() {
clearInterval(this.intervalId);
}
reset() {
this.currentTime = 0;
// ... your code goes here
}
split() {
//Remember you can use a function within a function and pass the return as an argument for another function
const minutes = this.computeTwoDigitNumber(this.getMinutes());
const seconds = this.computeTwoDigitNumber(this.getSeconds());
const milliseconds = this.computeTwoDigitNumber(this.getMilliseconds());
return `${minutes}:${seconds}: ${milliseconds}`;
}
}
// The following is required to make unit tests work.
/* Environment setup. Do not modify the below code. */
if (typeof module !== 'undefined') {
module.exports = Chronometer;
}
|
import React from 'react'
import styles from './../../styles/colorMaster.module.scss'
function ColorMaster(){
return(
<section className={styles.colorMaster}>
<div className={styles.colorMaster__container}>
<div className={styles.colorMaster__content}>
<h2 className={styles.colorMaster__title}>Re-Engineered by Cooler Master</h2>
<p className={styles.colorMaster__text}>CMODX is the personalized & performance division of Cooler Master, where you will find premium made, custom-like PC builds that are designed and curated by the industry’s most innovative & creative designers AKMod, Inony, Timpelay, and we collaborate with KFC Gaming, Atari, PC Master Race to keep things fresh.</p>
</div>
</div>
</section>
)
}
export default ColorMaster
|
var config = {
velocity: 0.15,
sunRotation: 0,
sunScale: 1,
sunFill: "#333",
sunStroke: "#dd9363",
sunDirection: true,
oceanLightness: 37,
nightMode: false,
};
$(document).ready(() => {
// Add Scroll listener
$(window).scroll(function(){
let yScroll = $(this).scrollTop();
if(yScroll > 20) {
if (!$('.site-header').hasClass("fixed")) {
$('.site-header').addClass("fixed");
}
} else {
if ($('.site-header').hasClass("fixed")) {
$('.site-header').removeClass("fixed");
}
}
});
// Enable Navigation dropdown on small screens
$('#site-nav .nav-toggler').click(() => {
if(!$('.site-header').hasClass("toggled")) {
$("#site-nav .nav-bar").animate({ height: "100%" }, "fast", () =>
$('.site-header').addClass("toggled")
);
} else {
$("#site-nav .nav-bar").animate({ height: "0%" }, "fast", () =>
$('.site-header').removeClass("toggled")
);
}
})
// Enable Documention section
$('#documentation .section-title').click(() => {
if(!$('#documentation').closest('.section').hasClass("toggled")) {
$("#documentation ul").toggle("slow", () =>
$('#documentation').closest('.section').addClass("toggled")
);
} else {''
$("#documentation ul").hide('fast', () => {
$('#documentation').closest('.section').removeClass("toggled")
});
}
})
$("#banner .section-inner").animate({ left: "50%" }, "slow", () => {
$("#banner .border-gradient").animate({ width: "100%" }, "fast", () =>
$("#banner").setDone()
);
});
window.requestAnimationFrame(loadCanvasArt);
$(window).on("resize scroll", () => {
// Animate About-section
if ($("#about").shouldAnimate()) {
$("#about .section-inner").animate({ left: "0%" }, "slow", () => {
$("#about .border-gradient").animate({ width: "100%" }, "fast", () =>
$("#about").setDone()
);
});
}
// Animate Artwork-section
if ($("#artwork").shouldAnimate()) {
$("#artwork .section-inner").animate({ right: "0%" }, "slow", () => {
$("#artwork .border-gradient-reverse").animate({ width: "100%" }, "fast", () =>
$("#artwork").setDone()
);
});
}
// Animate Documentation-section
if ($("#documentation").shouldAnimate()) {
$("#documentation .section-inner").animate(
{ left: "0%" },
"slow",
() => {
$("#documentation .border-gradient").animate(
{ width: "100%" },
"fast",
() => $("#documentation").setDone()
);
}
);
}
});
});
const loadCanvasArt = () => {
let canvas = document.getElementById("canvas-art");
let ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
canvas.addEventListener("mouseenter", (e) => {
config.nightMode = true;
config.sunFill = "hsl(57, 64%, 22%)";
config.sunStroke = "#f3f1c9";
// Draw dark background on hover
ctx.fillStyle = "#222";
ctx.fillRect(0, 0, canvas.width, canvas.height);
});
canvas.addEventListener("mouseleave", (e) => {
config.sunFill = "#333";
config.sunStroke = "#dd9363";
config.nightMode = false;
});
// Calculate animation variables
if (config.sunDirection) {
config.sunRotation += config.velocity;
config.sunScale += config.velocity / 200;
config.oceanLightness -= 8 / 200;
} else {
config.sunRotation -= config.velocity;
config.sunScale -= config.velocity / 200;
config.oceanLightness += 8 / 200;
}
if (config.sunRotation > 30) {
config.sunDirection = false;
} else if (config.sunRotation <= 0) {
config.sunDirection = true;
}
// Draw dark background on nightmode
if (config.nightMode) {
ctx.fillStyle = "#222";
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
// Animate and draw the sun
ctx.rotate((config.sunRotation * Math.PI) / 180);
ctx.scale(config.sunScale, config.sunScale);
drawPolygon(
ctx,
[
[200, 20],
[225, 37],
[225, 63],
[200, 80],
[175, 63],
[175, 37],
],
{ fillColor: config.sunFill, stroke: true, strokeColor: config.sunStroke, strokeWidth: 15 }
);
ctx.restore();
// Reset identity matrix
ctx.setTransform(1, 0, 0, 1, 0, 0);
// Mountains
drawPolygon(
ctx,
[
[158, 250],
[188, 175],
[218, 250],
],
{ fillColor: "rgba(207, 106, 63, 1)" }
);
drawPolygon(
ctx,
[
[113, 250],
[148, 135],
[183, 250],
],
{ fillColor: "rgba(232, 206, 171, 1)" }
);
drawPolygon(
ctx,
[
[38, 250],
[88, 75],
[138, 250],
],
{ fillColor: "rgba(143, 51, 21, 1)" }
);
drawPolygon(
ctx,
[
[203, 250],
[233, 105],
[262, 250],
],
{ fillColor: "rgba(221, 147, 99, 0.8)" }
);
// Draw Ocean
let ocean = new Path2D("M35 260 A20 17.5 0 0 0 265 260");
ctx.fillStyle = `hsl(197, 100%, ${config.oceanLightness}%)`;
ctx.fill(ocean);
// Mountain Reflections
drawPolygon(
ctx,
[
[158, 260],
[188, 300],
[218, 260],
],
{ fillColor: "rgba(207, 106, 63, 0.4)" }
);
drawPolygon(
ctx,
[
[113, 260],
[148, 320],
[183, 260],
],
{ fillColor: "rgba(232, 206, 171, 0.4)" }
);
drawPolygon(
ctx,
[
[38, 260],
[88, 330],
[138, 260],
],
{ fillColor: "rgba(143, 51, 21, 0.4)" }
);
drawPolygon(
ctx,
[
[203, 260],
[233, 325],
[262, 260],
],
{ fillColor: "rgba(221, 147, 99, 0.4)" }
);
// Draw dark overlay on nightmode
if (config.nightMode) {
ctx.fillStyle = "rgba(34, 34, 34, 0.25)";
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
window.requestAnimationFrame(loadCanvasArt);
};
const drawPolygon = (ctx, path, options) => {
let started = false;
ctx.fillStyle = options.fillColor;
ctx.strokeStyle = options.strokeColor;
ctx.lineWidth = options.strokeWidth;
for (const point of path) {
if (!started) {
ctx.beginPath();
ctx.moveTo(point[0], point[1]);
started = true;
continue;
}
ctx.lineTo(point[0], point[1]);
}
ctx.closePath();
ctx.fill();
if (options.stroke) ctx.stroke();
};
$.fn.setDone = function () {
if (!$(this).hasClass("done")) {
$(this).addClass("done");
}
};
$.fn.shouldAnimate = function () {
if (!$(this).hasClass("done")) {
let top = $(this).offset().top;
let bottom = top + $(this).outerHeight();
let vTop = $(window).scrollTop();
let vBottom = vTop + $(window).height();
return bottom > vTop && top < vBottom;
}
return false;
};
|
!
function(a) {
"use strict";
var b = {
initialised: !1,
container: a("#portfolio-item-container"),
init: function() {
if (!this.initialised) {
this.initialised = !0;
var b = this;
a.fn.imagesLoaded && imagesLoaded(b.container,
function() {
b.calculateWidth(),
b.isotopeActivate(),
b.isotopeFilter(),
b.hoverAnimation(),
b.prettyPhoto(),
b.infinitescroll(),
b.openProject(),
b.closeProject()
})
}
},
calculateWidth: function() {
var b, c = a(window).width(),
d = this.container.width(),
e = this.container.data("maxcolumn");
b = c > 1600 ? 5 : c > 1170 ? 4 : c > 768 ? 3 : c > 540 ? 2 : 1;
this.container.find(".pic-frame").css("width", Math.floor((d-10*b) / b))/* 10为外边距的两倍*/
},
isotopeActivate: function() {
{
var a = this.container,
b = a.data("layoutmode");
a.isotope({
itemSelector: ".pic-frame",
layoutMode: b ? b: "masonry"
}).data("isotope")
}
},
isotopeReinit: function() {
this.container.isotope("destroy"),
this.isotopeActivate()
},
isotopeFilter: function() {
var b = this,
c = a("#portfolio-filter");
c.find("a").on("click",
function(d) {
var e = a(this),
f = e.attr("data-filter"),
g = b.container.data("animationclass"),
h = g ? g: "fadeInUp";
c.find(".active").removeClass("active"),
b.container.find(".pic-frame").removeClass("animate-item " + h),
b.container.isotope({
filter: f
}),
e.addClass("active"),
d.preventDefault()
})
},
elementsAnimate: function() {
var b = this.container.data("animationclass"),
c = b ? b: "fadeInUp";
this.container.find(".animate-item").each(function() {
var b = a(this),
d = b.data("animate-time");
setTimeout(function() {
b.addClass("animated " + c)
},
d)
}),
this.container.isotope("layout")
},
hoverAnimation: function() {
var b = this.container.data("rotateanimation"),
c = b ? b: !1;
a.fn.hoverdir && this.container.find("li").each(function() {
a(this).hoverdir({
speed: 400,
hoverDelay: 0,
hoverElem: ".portfolio-overlay",/**#####**/
rotate3d: c
})
})
},
prettyPhoto: function() {
a.fn.prettyPhoto && a("a[data-rel^='prettyPhoto']").prettyPhoto({
hook: "data-rel",
animation_speed: "fast",
slideshow: 6e3,
autoplay_slideshow: !0,
show_title: !1,
deeplinking: !1,
social_tools: "",
overlay_gallery: !0,
opacity: .85
})
},
infinitescroll: function() {
var b = this;
a.fn.infinitescroll && this.container.infinitescroll({
navSelector: "#page-nav",
nextSelector: "#page-nav a",
itemSelector: ".pic-frame",
loading: {
finishedMsg: "没有更多的结果了."
/*,img:"//eonythemes.com/themes/t/images/load.GIF"*/
}
},
function(c) {
b.container.isotope("appended", a(c)),
b.calculateWidth(),
b.elementsAnimate(),
b.container.isotope("layout"),
b.hoverAnimation(),
b.prettyPhoto()
})
},
openProject: function() {
var b = a("#portfolio-single-content"),
c = b.find(".single-portfolio");
a(".open-btn").on("click",
function(d) {
if (b.hasClass("onepage-portfolio-single")) {
var e = b.offset().top - 80;
a("html, body").animate({
scrollTop: e
},
800),
a(c).fadeIn(1e3)
} else a(b).fadeIn(1e3);
d.preventDefault()
})
},
closeProject: function() {
var b = a("#portfolio-single-content"),
c = b.find(".single-portfolio");
a(".portfolio-close").on("click",
function(d) {
b.hasClass("onepage-portfolio-single") ? a(c).fadeOut(600) : a(b).fadeOut(600),
d.preventDefault()
})
}
};
b.init(),
a.event.special.debouncedresize ? a(window).on("debouncedresize",
function() {
b.calculateWidth(),
b.isotopeReinit()
}) : a(window).on("resize",
function() {
b.calculateWidth(),
b.isotopeReinit()
}),
"undefined" != typeof Pace ? Pace.on("done",
function() {
b.elementsAnimate()
}) : a(window).on("load",
function() {
b.elementsAnimate()
})
} (jQuery);
|
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var jsonParser = bodyParser.json();
var request = require('request');
var Recipe = require('./models/recipe.js');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/recipes');
app.use(bodyParser.json());
app.use(jsonParser);
var NutritionixClient = require('nutritionix');
var nutritionix = new NutritionixClient({
appId: 'a120429b',
appKey: '3e1551bafdb518dba63b0555ac4f1482'
});
//request to get nutrition information based on ingredients list.
function getIngredientNutrients(joinedIng, recipeId) {
// for each ingredient in an array
for (var i = 0; i < joinedIng.length; i++) {
var ingBody = joinedIng[i];
// var ingBody = joinedIng.join("\n");
// console.log("joined ingredients sent for query are %j", ingBody)
request({
method: 'POST',
headers: {
'Content-Type': 'text/plain',
'X-APP-ID': 'a120429b',
'X-APP-KEY': '3e1551bafdb518dba63b0555ac4f1482'
},
uri: {
protocol: 'https:',
slashes: true,
auth: null,
host: 'api.nutritionix.com',
port: 443,
hostname: 'api.nutritionix.com',
hash: null,
search: null,
query: null,
pathname: '/v2/natural',
path: '/v2/natural',
href: 'https://api.nutritionix.com/v2/natural'
},
body: ingBody
}, function(error, response, body) {
if (error) {
console.log(" ERROR = " + error);
} else {
///response is an object with results as a key and value as nutrition details
console.log("nutrition status = " + response.statusCode);
// console.log("nutrition: body = " + response.body);
var res = response.body;
res = JSON.parse(res);
var result = res.results;
//if ingredient format is not correct
if (response.statusCode === 400) {
} else if (response.statusCode === 200) {
result.forEach(function(ingredient) {
var nutrient = ingredient.nutrients;
console.log("nutrient length is: " + nutrient.length);
if (nutrient.length > 0) {
//define variable and assign them values in the for -loop below
var proteinValue;
var proteinUnit;
var carbohydratesValue;
var carbohydratesUnit;
var lipidValue;
var lipidUnit;
var polyUnsatValue;
var polyUnsatUnit;
var monoUnsatValue;
var monoUnsatUnit;
var satValue;
var satUnit;
var cholesterolValue;
var cholesterolUnit;
var ironValue;
var ironUnit;
var vitaminCValue;
var vitaminCUnit;
var vitaminAValue;
var vitaminAUnit;
var vitaminB6Value;
var vitaminB6Unit;
var vitaminB12Value;
var vitaminB12Unit;
//go through each nutrient in the array and look for the nutrients- carbs,lipids,etc
for (var i = 0; i < nutrient.length; i++) {
if (nutrient[i].name === "Protein") {
proteinValue = nutrient[i].value;
proteinUnit = nutrient[i].unit;
console.log("this is nutrient info for protein: %j%j ", proteinValue, proteinUnit);
} else if (nutrient[i].name === "Carbohydrate, by difference") {
carbohydratesValue = nutrient[i].value;
carbohydratesUnit = nutrient[i].unit;
console.log("this is nutrient info for carbs: %j%j ", carbohydratesValue, carbohydratesUnit);
} else if (nutrient[i].name === "Total lipid (fat)") {
lipidValue = nutrient[i].value;
lipidUnit = nutrient[i].unit;
console.log("this is nutrient info for lipid: %j%j ", lipidValue, lipidUnit);
} else if (nutrient[i].name === "Fatty acids, total polyunsaturated") {
polyUnsatValue = nutrient[i].value;
polyUnsatUnit = nutrient[i].unit;
console.log("this is nutrient info for polyUnsat: %j%j ", polyUnsatValue, polyUnsatUnit);
} else if (nutrient[i].name === "Fatty acids, total monounsaturated") {
monoUnsatValue = nutrient[i].value;
monoUnsatUnit = nutrient[i].unit;
console.log("this is nutrient info for monoUnsat: %j%j ", monoUnsatValue, monoUnsatUnit);
} else if (nutrient[i].name === "Fatty acids, total monounsaturated") {
satValue = nutrient[i].value;
satUnit = nutrient[i].unit;
console.log("this is nutrient info for satValue: %j%j ", monoUnsatValue, monoUnsatUnit);
} else if (nutrient[i].name === "Iron,FE") {
ironValue = nutrient[i].value;
ironUnit = nutrient[i].unit;
console.log("this is nutrient info for iron: %j%j ", monoUnsatValue, monoUnsatUnit);
} else if (nutrient[i].name === "Vitamin C, total ascorbic acid") {
vitaminCValue = nutrient[i].value;
vitaminCUnit = nutrient[i].unit;
console.log("this is nutrient info for monoUnsat: %j%j ", vitaminCValue, vitaminCUnit);
} else if (nutrient[i].name === "Vitamin B-6") {
vitaminB6Value = nutrient[i].value;
vitaminB6Unit = nutrient[i].unit;
console.log("this is nutrient info for B6: %j%j ", vitaminB6Value, vitaminB6Unit);
} else if (nutrient[i].name === "Vitamin B-6") {
vitaminB6Value = nutrient[i].value;
vitaminB6Unit = nutrient[i].unit;
console.log("this is nutrient info for B6: %j%j ", vitaminB6Value, vitaminB6Unit);
} else if (nutrient[i].name === "Vitamin B-12") {
vitaminB12Value = nutrient[i].value;
vitaminB12Unit = nutrient[i].unit;
console.log("this is nutrient info for B12: %j%j ", vitaminB12Value, vitaminB12Unit);
} else if (nutrient[i].name === "Vitamin A, RAE") {
vitaminAValue = nutrient[i].value;
vitaminAUnit = nutrient[i].unit;
console.log("this is nutrient info for vitA: %j%j ", vitaminAValue, vitaminAUnit);
}
}
var ingredientsInsert = {
name: ingBody,
protein: {
value: proteinValue,
unit: proteinUnit
},
carbohydrates: {
value: carbohydratesValue,
unit: carbohydratesUnit
},
fat: {
value: lipidValue,
unit: lipidUnit
},
monoUnsaturatedFat: {
value: monoUnsatValue,
unit: monoUnsatUnit
},
polyUnsaturatedFat: {
value: polyUnsatValue,
unit: polyUnsatUnit
},
saturatedFat: {
value: satValue,
unit: satUnit
},
cholesterol: {
value: cholesterolValue,
unit: cholesterolUnit
},
iron: {
value: ironValue,
unit: ironUnit
},
vitaminC: {
value: vitaminCValue,
unit: vitaminCUnit
},
vitaminA: {
value: vitaminAValue,
unit: vitaminAUnit
},
vitaminB6: {
value: vitaminB6Value,
unit: vitaminB6Unit
},
vitaminB12: {
value: vitaminB12Value,
unit: vitaminB12Unit
}
}
// var ingredientInsert = {
// name: ingBody,
// }
Recipe.update({
recipe_name: recipeId
}, {
$push: {
ingredients: ingredientsInsert
}
}, function(err, ingredients) {
if (err) {
console.error(err);
} else {
console.log("success!");
}
});
}
})
}
}
});
};
};
//callback function from individual recipes.THIS IS THE RESPONSE WITH INDIVIDUAL RECIPE. From the response, it gets an array of ingredients which will be used to make an http request.
function processRemoteRecipe(error, response, body) {
if (error) {
console.log("processRemoteRecipes: ERROR = " + error);
} else {
// console.log("processRemoteRecipes: status = " + response.statusCode);
// console.log("processRemoteRecipes: body = " + response.body);
var body = JSON.parse(response.body);
var recipe = body.recipe;
var recipePublisher = recipe.publisher;
var recipeIngredients = recipe.ingredients;
//filtering recipes according to publishes so that it will easy to scrape methods from the same site.
if (recipePublisher === "All Recipes") {
console.log("processRemoteRecipes: publisher recipes = " + recipeIngredients);
console.log("processRemoteRecipes: publisher recipes = " + recipePublisher);
var recipe_id = recipe.recipe_id;
var rec = Recipe.create({
title: recipe.title,
// ingredients: recipe.ingredients,
source_url: recipe.source_url,
image_url: recipe.image_url,
recipe_id: recipe_id,
method: "Whatever"
});
console.log("create recipe: %j", rec);
// calls getIngredientNutrients to make a http request to get nutrition details
getIngredientNutrients(recipeIngredients, recipe_id);
}
}
}
//make http request to api to get individual revipe details
function getRemoteRecipe(recipe) {
//stores the recipe id for each recipe and then uses it to make individual http calls
var recipeId = recipe.recipe_id;
var recipeUrl = "http://food2fork.com/api/get?key=ef82898c8dec1bd923cf8abcec885398&rId=";
recipeUrl += recipeId;
request({
url: recipeUrl,
method: 'GET'
}, processRemoteRecipe)
}
//call back function after list of recipes. Use the recipe id for each recipe in the list to make individual http requests to get recipe details.
function handleListRecipes(error, response, body) {
if (error) {
} else {
var body = JSON.parse(response.body);
var count = body.count;
var recipes = body.recipes;
// console.log("handleListRecipes: count = " + count);
// console.log("handleListRecipes: recipes = " + recipes);
//make a request to get each recipe detail
recipes.forEach(getRemoteRecipe);
//for trial calling remoterecipes only for one recipe
// getRemoteRecipe(recipes[2]);
}
};
//Gets a list of recipes from api which will give recipe id and some other info for each recipe.
function listRecipes() {
request_params = {
url: 'http://food2fork.com/api/search?key=ef82898c8dec1bd923cf8abcec885398&page=1',
// key: 'ef82898c8dec1bd923cf8abcec885398',
// page: 1, //Query string data
method: 'GET' //Specify the method
};
//make request to api to get list of recipes. handleListRecipes is the callback function
request(request_params, handleListRecipes);
};
app.get('/me', function(req, res) {
//invokes listRecipes
listRecipes();
});
var server = app.listen(3000, function() {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
// ef82898c8dec1bd923cf8abcec885398
|
import { ACTION_RETRIEVE_USER, ACTION_CLEAR_USER } from '../actions/userActions';
export const STATE_LOGGED_OUT = 'LOGGED_OUT';
export const STATE_LOGGED_IN = 'LOGGED_IN';
const initialState = {
gotUser: false,
currentUser: null,
loginState: STATE_LOGGED_OUT,
};
const reducer = (state = initialState, { type, payload }) => {
switch (type) {
case ACTION_RETRIEVE_USER:
return {
...state,
gotUser: true,
currentUser: payload.partial ? { ...state.currentUser, ...payload.user } : payload.user,
loginState: STATE_LOGGED_IN,
};
case ACTION_CLEAR_USER:
return {
...state,
gotUser: false,
currentUser: null,
loginState: STATE_LOGGED_OUT,
};
default:
return state;
}
};
export default reducer;
|
/**
* 1.理解 window 对象和全局作用域
* 2.将 window 相对屏幕居中
* 3.调整 window 大小为 1280 * 720 (长 * 高)
* 4.新标签页打开一个百度网站,并在 5s 后关闭
* 5.设置一个 3s 延时,时间到后打印 glj
* 6.取消刚刚设置的延时
* 7.设置一个轮询(间歇调用),第一次打印 1,第二次打印 2,每次增加 1,以此类推
* 8.5s 后取消轮询
*/
console.log(window.screenTop, window.screenLeft, window.innerHeight, window.innerWidth, window.outerHeight, window.outerWidth);
/** 必须由此页面打开的窗口才能控制 */
// const Baidu = window.open('http://127.0.0.1:5500/8%E3%80%81BOM', 'BaiDu', "resizable,scrollbars,status");
// Baidu.resizeTo(1280, 720);
// const x = (screen.width - Baidu.outerWidth) / 2;
// const y = (screen.height - Baidu.outerHeight) / 2;
// Baidu.moveTo(x, y);
// setTimeout(() => {
// Baidu.close();
// }, 5000);
/**
* 1.获取当前网页地址
* 2.获取当前网页域名
* 3.修改当前网页地址,在地址后面加上查询字符串 '?glj=1&learn=2'
* 4.获取当前网页查询字符串,并转换为 { glj: 1, learn: 2 } 的形式
* 5.获取当前网页哈希(hash)
*/
console.log('地址', window.location.href, '域名', window.location.host);
if (!location.search) {
location.search = '?glj=1&learn=2';
}
function getQueryStringArgs() {
/** 此处 location.search 如果不存在会返回空字符串,因此不用担心报错 */
const qs = location.search.substring(1);
const args = {};
const items = qs.length ? qs.split('&') : [];
console.log('items:', items);
let len = items.length;
for (let i = 0; i < len; i++) {
const item = items[i].split('=');
const name = decodeURIComponent(item[0]);
const value = decodeURIComponent(item[1]);
args[name] = value;
}
console.log('reduce', items.reduce((qsObject, current) => {
const item = current.split('=');
const name = decodeURIComponent(item[0]);
const value = decodeURIComponent(item[1]);
qsObject[name] = value;
return qsObject;
}, {}));
return args;
}
console.log(getQueryStringArgs());
console.log(location.hash);
/**
* 1.后退网页一次
* 2.前进网页一次
* 3.跳转到百度
*/
// history.go(-1);
// /** history.back() */
// history.go(1);
// /** history.forward() */
// history.go('www.baidu.com');
|
import React from "react";
import { View, Text, TouchableOpacity } from "react-native";
import { createStackNavigator } from "@react-navigation/stack";
import { useFonts, Amarante_400Regular } from "@expo-google-fonts/amarante";
import MaterialCommunityIcons from "react-native-vector-icons/MaterialCommunityIcons";
import Color from "../styles/Color";
import CommunityFeedScreen from "../screens/CommunityFeedScreen";
import PostDetail from "../screens/PostDetailScreen";
import PostDetailScreen from "../screens/PostDetailScreen";
const Stack = createStackNavigator();
function CommunityScreen(props) {
return (
<Stack.Navigator
initialRouteName="communityFeed"
headerMode="float"
headerTitleStyle={{ alignSelf: "center" }}
screenOptions={({ navigation }) => ({
headerStyle: {
backgroundColor: Color.themeColor,
},
headerTitle: () => <CommunityHeader navigation={navigation} />,
headerLeft: false,
})}
>
<Stack.Screen name="communityFeed" component={CommunityFeedScreen} />
<Stack.Screen name="PostDetail" component={PostDetailScreen} />
</Stack.Navigator>
);
}
function CommunityHeader(props) {
let [fontsLoaded] = useFonts({
Amarante_400Regular,
});
if (!fontsLoaded) {
return (
<View>
<Text>Loading</Text>
</View>
);
} else {
return (
<View
style={{
flex: 1,
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
}}
>
<Text style={{ color: "#fff", fontFamily: "Amarante_400Regular" }}>
ThePingPong
</Text>
<View style={{ flexDirection: "row" }}>
<TouchableOpacity style={{ padding: 5 }}>
<MaterialCommunityIcons
name="heart-outline"
size={30}
color={"#fff"}
/>
</TouchableOpacity>
<TouchableOpacity style={{ paddingTop: 5 }}>
<MaterialCommunityIcons name="plus" size={30} color={"#fff"} />
</TouchableOpacity>
</View>
</View>
);
}
}
export default CommunityScreen;
|
// 08-dom/03-select-three/script.js - 8.3: select multiple elements by css selector
(() => {
// your code here
document.getElementsByClassName("target")[0].innerHTML = "Owned";
document.getElementsByClassName("target")[1].innerHTML = "Owned";
document.getElementsByClassName("target")[2].innerHTML = "Owned";
document.getElementsByClassName("target")[3].innerHTML = "Owned";
document.getElementsByClassName("target")[4].innerHTML = "Owned";
})();
|
// @ts-check
import ReactDOM from 'react-dom';
export function render(app, element) {
return new Promise(resolve => ReactDOM.render(app, element, resolve));
}
|
const webpack = require('webpack');
const style_config = {
'test': /\.less$/,
'use': [{
'loader': 'style-loader'
}, {
'loader': 'css-loader'
}, {
'loader': 'postcss-loader',
'options': {
'plugins': () => [require('autoprefixer')]
}
}, {
'loader': 'less-loader'
}]
}
module.exports = style_config;
|
var last_product_id = 0;
$(function() {
$('#productModal').on('hide.bs.modal', function (e) {
if (typeof countdown != 'undefined') clearInterval(countdown);
});
});
function refresh_products(page) {
var search = $('#filters input[name=filter-search]').val();
var domain = $('#filters select[name=filter-domain]').val();
var product_group = $('#filters select[name=filter-product-group]').val();
var sort = $('#filters select[name=filter-sort]').val();
if (page == -1) page = $('#product-grid-page').val();
$('#box-container .box').remove();
$('#box-container').html("<div style='text-align: center; font-size: 18px; font-weight: bold; text-shadow: 0 0 10px #fff; padding: 50px 0;'><i class='fa fa-spin fa-spinner'></i> Please Wait...</div>");
$.ajax({
url: "product_grid.php",
method: 'POST',
cache: false,
data: { domain: domain, product_group: product_group, page: page, sort: sort, search: search },
success: function(data) {
$('#box-container').html(data);
refresh_layout();
$('#filters input[name=filter-search]').focus().select().on("keyup", function(e) {
if (e.which == 13) refresh_products(-1);
});
$('#box-container .has-tooltip').tooltip({html: true});
}
});
}
$(window).resize(function() {
refresh_layout();
});
function refresh_layout() {
$('#wait').hide();
var box_height = Array();
var final_y = Array();
var final_x = Array();
$('.box').each(function(e) {
box_height.push($(this).height());
});
var width = $('#box-container').width();
var cols = Math.floor(width / 250);
var start = Math.round((width - cols * 250) / 2);
var container_height = 0;
jQuery.each(box_height, function(index) {
var x = start + (index % cols) * 250;
var row = Math.floor(index / cols);
var y = 0;
for (i = 0; i < row; i++) {
y += box_height[i * cols + (index % cols)] + 14;
}
final_y.push(y);
final_x.push(x);
container_height = y + 150;
});
$('.box').each(function(index) {
$(this).css({ top: final_y[index], left: final_x[index] });
});
$('#box-container').height(container_height + 700);
$('#box-container-inner').height(container_height + 450);
}
function show_product(product_id) {
$('#productModal .modal-body').html('<div style="padding: 20px 20px 0 20px;"><i class="fa fa-spin fa-spinner"></i> Please Wait...</div>');
$('#productModal').modal('show');
$.ajax({
url: "product.php",
method: 'POST',
cache: false,
data: { product_id: product_id },
success: function(data) {
$('#productModal .modal-body').html(data);
$('#productModal .has-tooltip').tooltip({html: true});
}
});
}
function show_last_product() {
$('.modal').modal('hide');
if (last_product_id > 0) {
show_product(last_product_id);
}
}
function account(id) {
$('.modal').modal('hide');
$('#accountModal .modal-body').html('<i class="fa fa-spin fa-spinner"></i> Please Wait...');
$('#accountModal').modal('show');
$.ajax({
url: "account.php",
method: 'POST',
cache: false,
data: { id: id },
success: function(data) {
$('#accountModal .modal-body').html(data);
}
});
}
function sign_in() {
$('#sign-in-form .btn-primary').attr('disabled', 'disabled').html('<i class="fa fa-spin fa-spinner"></i> Please Wait');
$.ajax({
url: "sign_in.php",
method: 'POST',
cache: false,
data: $('#sign-in-form form').serialize(),
success: function(data) {
console.log(data);
if (data == "error") {
$('#sign-in-form .btn-primary').removeAttr('disabled', 'disabled').html('Sign In');
$('#sign-in-form .error').html('The email or password you entered was incorrect. Please try again.').show();
}
else if (data == "signed in") {
refresh_menu();
$('.modal').modal('hide');
$('#postSignInModal').modal('show');
}
else if (data == "reset password") {
window.location.replace("reset_password.php");
}
else {
$('#sign-in-form .btn-primary').removeAttr('disabled', 'disabled').html('Sign In');
$('#sign-in-form .error').html('The email address needs verification. <span onclick="resend_confirmation(' + data + ')" style="text-decoration: underline; cursor: pointer;">Click here</span> to resend verification email.').show();
}
}
});
}
function sign_out() {
$('#accountModal .btn').attr('disabled', 'disabled');
$('#accountModal .btn-sign-out').html('<i class="fa fa-spin fa-spinner"></i> Please Wait');
$.ajax({
url: "sign_out.php",
cache: false,
success: function(data) {
$('.modal').modal('hide');
refresh_menu();
}
});
}
function create_account() {
$('#create-account-form .btn-primary').attr('disabled', 'disabled').html('<i class="fa fa-spin fa-spinner"></i> Please Wait');
$.ajax({
url: "create_account.php",
method: 'POST',
cache: false,
data: $('#create-account-form form').serialize(),
success: function(data) {
console.log(data);
$('#create-account-form .btn-primary').removeAttr('disabled', 'disabled').html('Create Account');
if (data == "error") {
$('#create-account-form .error').html('The email is invalid or password is less than 8 characters.').show();
}
else if (data == "email exists") {
$('#sign-in-form .error').html('The email you used is already in our system. Please use it to sign in.').show();
$('.sign-groups').hide();
$('#sign-in-form').show();
}
else if (data == "confirmation sent") {
$('#sign-in-form .error').html('A confirmation email has been sent to you. Click the link in that email to verify this account before signing in.').show();
$('.sign-groups').hide();
$('#sign-in-form').show();
}
else if (data == "signed in") {
refresh_menu();
$('.modal').modal('hide');
$('#postSignUpModal').modal('show');
}
}
});
}
function forgot_password() {
$('#forgot-password-form .btn-primary').attr('disabled', 'disabled').html('<i class="fa fa-spin fa-spinner"></i> Please Wait');
$.ajax({
url: "forgot_password.php",
method: 'POST',
cache: false,
data: $('#forgot-password-form form').serialize(),
success: function(data) {
console.log(data);
$('#forgot-password-form .btn-primary').removeAttr('disabled', 'disabled').html('Reset Password');
if (data == "error") {
$('#forgot-password-form .error').html('The email entered is invalid.').show();
}
else if (data == "password reset") {
$('#sign-in-form .error').html('A new password has been emailed to you. Please use it to sign in.').show();
$('.sign-groups').hide();
$('#sign-in-form').show();
}
else {
$('#forgot-password-form .error').html(data).show();
}
}
});
}
function refresh_menu() {
$.ajax({
url: "menu.php",
method: 'GET',
cache: false,
data: { ajax: 1 },
success: function(data) {
$('.nav.nav-main .menu-top').html(data);
}
});
}
function account_update() {
$('#account-form .btn-primary').attr('disabled', 'disabled').html('<i class="fa fa-spin fa-spinner"></i> Please Wait');
$.ajax({
url: "account_update_check.php",
method: 'POST',
cache: false,
data: $('#account-form form').serialize(),
success: function(data) {
$('#account-form .btn-primary').removeAttr('disabled', 'disabled').html('Update Details');
if (data != "") {
alert(data);
return;
}
$.ajax({
url: "account_update.php",
method: 'POST',
cache: false,
data: $('#account-form form').serialize(),
success: function(data) {
$('#account-form .btn-primary').removeAttr('disabled', 'disabled').html('Update Details');
if (data != "") {
modal_message("Invalid Profile URL", data, '');
}
else {
show_last_product();
}
}
});
}
});
}
function check_profile_url() {
var profile_url = $('#sign_profile').val().trim();
$('#sign_profile').val(profile_url);
if (profile_url.indexOf("http") != 0) profile_url = "http://" + profile_url;
window.open(profile_url);
}
function review_now(product_id) {
if ($('.review_now_' + product_id).hasClass('disabled')) return;
$('.review_now_' + product_id).addClass('disabled').html('<i class="fa fa-spin fa-spinner"></i> Please Wait');
$.ajax({
url: "request.php",
method: 'POST',
cache: false,
data: { product_id: product_id },
success: function(data) {
console.log(data);
if (data == "error") {
$('.review_now_' + product_id).addClass('danger').html('There was a error!');
$('.product-message').html('Something went wrong... refresh your browser and try again.').show();
return;
}
if (data == "success") {
$('.review_now_' + product_id).addClass('success').removeClass('disabled').html('Review Requested');
$('.product-message').html('Your request has been sent to the seller. If you are chosen to review this product you will receive an email with further instructions. <br><br><a href="review-requests.php">Click here</a> to manage your review requests.').show();
$('#product_' + product_id + ' .btn-review').addClass('success').html("<span class='glyphicon glyphicon-ok'></span>");
return;
}
if (data == "removed") {
$('.review_now_' + product_id).removeClass('success disabled').html('Request Removed');
$('.product-message').html('Your request to review this product has been removed. If this was a mistake just click the button above again.').show();
$('#product_' + product_id + ' .btn-review').removeClass('success').html("Review Now");
return;
}
if (data == "over limit") {
$('.review_now_' + product_id).addClass('danger').removeClass('disabled').html('There was a problem!');
$('.product-message').html('You are over your request limit! You need to review a product to request more vouchers. <br><br><a href="review-requests.php">Click here</a> to manage your review requests.').show();
$('#product_' + product_id + ' .btn-review').removeClass('success').html("Review Now");
}
}
});
}
function mc_subscribe(cl) {
var email = $('.' + cl + ' input[name=email]').val();
$('.' + cl + ' button').html('<i class="fa fa-spin fa-spinner"></i> Please Wait').attr('disabled', 'disabled');
$.ajax({
url: "mc_subscribe.php",
method: 'POST',
cache: false,
data: { email: email },
success: function(data) {
$('.' + cl).html(data);
}
});
}
function modal_message(title, message, button) {
$('.modal').modal('hide');
$('#messageModal .modalName').html(title);
$('#messageModal .modal-body').html(message);
if (button == '') $('#messageModal .modal-footer').hide();
else {
$('#messageModal .modal-footer').show();
$('#messageModal .modal-footer .btn').html(button).show();
}
$('#messageModal').modal('show');
}
function resend_confirmation(reviewer_id) {
$('#accountModal .modal-body').html('<i class="fa fa-spin fa-spinner"></i> Please Wait...');
$('#accountModal').modal('show');
$.ajax({
url: "resend_confirmation.php",
method: 'POST',
cache: false,
data: { reviewer_id: reviewer_id },
success: function(data) {
$.ajax({
url: "account.php",
method: 'POST',
cache: false,
data: { id: 'sign-in' },
success: function(data) {
$('#accountModal .modal-body').html(data);
$('#accountModal .modal-body .error').html('A verification email has been sent to you. Click the link in that email to verify your account before signing in.').show();
}
});
}
});
}
|
import axios from "axios";
import { GET_TV_SHOW_GENRES } from "../types";
export const getTvShowGenres = () => dispatch => {
axios.get("/.netlify/functions/getTvShowGenres")
.then(res =>
dispatch({
type: GET_TV_SHOW_GENRES,
payload: res.data
})
)
}
|
import React from 'react';
import { Home } from './views/Home';
import { Contact } from './views/Contact';
import { ProjectList } from './views/ProjectList';
import { Navbar } from './components/Navbar';
import { Footer } from './components/Footer';
import { About } from './views/About';
import { Route, Switch } from 'react-router-dom';
import Project from './views/Project/Project';
import ScrollToTop from './ScrollToTop';
export const Routes = () => {
return (
<div className="content">
<Navbar />
<ScrollToTop>
<Switch>
<Route exact path="/Projects/:id" component={Project}/>
<Route exact path="/" component={Home} />
<Route exact path="/Projects" component={ProjectList} />
<Route exact path="/Contact" component={Contact} />
<Route exact path="/About" component={About} />
</Switch>
</ScrollToTop>
<Footer />
</div>
);
};
|
/*
--- Day 3: Crossed Wires ---
The gravity assist was successful, and you're well on your way to the Venus refuelling station. During the rush back on Earth, the fuel management system wasn't completely installed, so that's next on the priority list.
Opening the front panel reveals a jumble of wires. Specifically, two wires are connected to a central port and extend outward on a grid. You trace the path each wire takes as it leaves the central port, one wire per line of text (your puzzle input).
The wires twist and turn, but the two wires occasionally cross paths. To fix the circuit, you need to find the intersection point closest to the central port. Because the wires are on a grid, use the Manhattan distance for this measurement. While the wires do technically cross right at the central port where they both start, this point does not count, nor does a wire count as crossing with itself.
For example, if the first wire's path is R8,U5,L5,D3, then starting from the central port (o), it goes right 8, up 5, left 5, and finally down 3:
...........
...........
...........
....+----+.
....|....|.
....|....|.
....|....|.
.........|.
.o-------+.
...........
Then, if the second wire's path is U7,R6,D4,L4, it goes up 7, right 6, down 4, and left 4:
...........
.+-----+...
.|.....|...
.|..+--X-+.
.|..|..|.|.
.|.-X--+.|.
.|..|....|.
.|.......|.
.o-------+.
...........
These wires cross at two locations (marked X), but the lower-left one is closer to the central port: its distance is 3 + 3 = 6.
Here are a few more examples:
R75,D30,R83,U83,L12,D49,R71,U7,L72
U62,R66,U55,R34,D71,R55,D58,R83 = distance 159
R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51
U98,R91,D20,R16,D67,R40,U7,R15,U6,R7 = distance 135
What is the Manhattan distance from the central port to the closest intersection?
Your puzzle answer was 870.
The first half of this puzzle is complete! It provides one gold star: *
--- Part Two ---
It turns out that this circuit is very timing-sensitive; you actually need to minimize the signal delay.
To do this, calculate the number of steps each wire takes to reach each intersection; choose the intersection where the sum of both wires' steps is lowest. If a wire visits a position on the grid multiple times, use the steps value from the first time it visits that position when calculating the total value of a specific intersection.
The number of steps a wire takes is the total number of grid squares the wire has entered to get to that location, including the intersection being considered. Again consider the example from above:
...........
.+-----+...
.|.....|...
.|..+--X-+.
.|..|..|.|.
.|.-X--+.|.
.|..|....|.
.|.......|.
.o-------+.
...........
In the above example, the intersection closest to the central port is reached after 8+5+5+2 = 20 steps by the first wire and 7+6+4+3 = 20 steps by the second wire for a total of 20+20 = 40 steps.
However, the top-right intersection is better: the first wire takes only 8+5+2 = 15 and the second wire takes only 7+6+2 = 15, a total of 15+15 = 30 steps.
Here are the best steps for the extra examples from above:
R75,D30,R83,U83,L12,D49,R71,U7,L72
U62,R66,U55,R34,D71,R55,D58,R83 = 610 steps
R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51
U98,R91,D20,R16,D67,R40,U7,R15,U6,R7 = 410 steps
What is the fewest combined steps the wires must take to reach an intersection?
*/
const fs = require('fs');
const path = require('path');
const txt = fs.readFileSync(path.resolve(__dirname, 'data.txt'), 'utf-8');
const directions = txt.split('\n');
const firstCableInstructions = directions[0].split(',');
const secondCableInstructions = directions[1].split(',');
let x = 0;
let y = 0;
let totalFirstSteps = 0;
let totalSecondSteps = 0;
const matrix = { 0: { 0: { val: 0, steps: 0 } } };
for (let i = 0; i < firstCableInstructions.length; i++) {
const instruction = firstCableInstructions[i];
const steps = parseInt(instruction.substring(1, instruction.length));
switch (instruction[0]) {
case 'R':
for (let j = 0; j < steps; j++) {
x++;
totalFirstSteps++;
if (!matrix[x]) matrix[x] = {};
if (!matrix[x][y]) matrix[x][y] = { val: 0, steps: totalFirstSteps };
}
break;
case 'L':
for (let j = 0; j < steps; j++) {
x--;
totalFirstSteps++;
if (!matrix[x]) matrix[x] = {};
if (!matrix[x][y]) matrix[x][y] = { val: 0, steps: totalFirstSteps };
}
break;
case 'U':
for (let j = 0; j < steps; j++) {
y++;
totalFirstSteps++;
if (!matrix[x]) matrix[x] = {};
if (!matrix[x][y]) matrix[x][y] = { val: 0, steps: totalFirstSteps };
}
break;
case 'D':
for (let j = 0; j < steps; j++) {
y--;
totalFirstSteps++;
if (!matrix[x]) matrix[x] = {};
if (!matrix[x][y]) matrix[x][y] = { val: 0, steps: totalFirstSteps };
}
break;
}
}
x = 0;
y = 0;
let closerDistance = Number.POSITIVE_INFINITY;
let fewerSteps = Number.POSITIVE_INFINITY;
for (let i = 0; i < secondCableInstructions.length; i++) {
const instruction = secondCableInstructions[i];
const steps = parseInt(instruction.substring(1, instruction.length));
switch (instruction[0]) {
case 'R':
for (let j = 0; j < steps; j++) {
x++;
totalSecondSteps++;
if (matrix[x] && matrix[x][y] && matrix[x][y].val === 0) {
matrix[x][y].val = 1;
const distance = Math.abs(x) + Math.abs(y);
if (distance < closerDistance) closerDistance = distance;
const totalSteps = matrix[x][y].steps + totalSecondSteps;
if (totalSteps < fewerSteps) fewerSteps = totalSteps;
}
}
break;
case 'L':
for (let j = 0; j < steps; j++) {
x--;
totalSecondSteps++;
if (matrix[x] && matrix[x][y] && matrix[x][y].val === 0) {
matrix[x][y].val = 1;
const distance = Math.abs(x) + Math.abs(y);
if (distance < closerDistance) closerDistance = distance;
const totalSteps = matrix[x][y].steps + totalSecondSteps;
if (totalSteps < fewerSteps) fewerSteps = totalSteps;
}
}
break;
case 'U':
for (let j = 0; j < steps; j++) {
y++;
totalSecondSteps++;
if (matrix[x] && matrix[x][y] && matrix[x][y].val === 0) {
matrix[x][y].val = 1;
const distance = Math.abs(x) + Math.abs(y);
if (distance < closerDistance) closerDistance = distance;
const totalSteps = matrix[x][y].steps + totalSecondSteps;
if (totalSteps < fewerSteps) fewerSteps = totalSteps;
}
}
break;
case 'D':
for (let j = 0; j < steps; j++) {
y--;
totalSecondSteps++;
if (matrix[x] && matrix[x][y] && matrix[x][y].val === 0) {
matrix[x][y].val = 1;
const distance = Math.abs(x) + Math.abs(y);
if (distance < closerDistance) closerDistance = distance;
const totalSteps = matrix[x][y].steps + totalSecondSteps;
if (totalSteps < fewerSteps) fewerSteps = totalSteps;
}
}
break;
}
}
console.log(closerDistance);
console.log(fewerSteps);
|
$(document).ready(() => {
$(".save-btn").on("click", function() {
var patternId = $(this).attr("data-id");
var idValue = $(this).attr("id");
var numberValue = idValue.substring(11);
var nameValue = $("#patternName" + numberValue).text();
var urlValue = $("#patternLink" + numberValue).attr("href");
var imageLink = $("#patternImage" + numberValue).attr("src");
var authorName = $("#patternAuthor" + numberValue).text();
$.ajax({
url: "/api/patterns",
method: "POST",
async: true,
data: {
id: patternId,
name: nameValue,
url: urlValue,
image: imageLink,
author: authorName
},
dataType: "json",
error: function(jqXHR, textStatus, errorThrown) {
alert("Error saving. Error code: " + errorThrown);
}
}).then(function(data) {
if (data.saved === "done") {
alert(`Saved ${nameValue} by ${authorName}.`);
} else if (data.saved === "already") {
alert(`You have already saved ${nameValue} by ${authorName}.`);
} else if (data.saved === "error") {
alert("Error saving the pattern to your profile");
}
});
});
//Generate next 6 patterns
$("#next").on("click", function() {
console.log("made it");
if ($("#patternsContainer").hasClass("d-block")) {
$("#patternsContainer")
.removeClass("d-block")
.addClass("d-none");
}
if ($("#spinnerDiv").hasClass("d-none")) {
$("#spinnerDiv")
.removeClass("d-none")
.addClass("d-block");
}
});
$("#generatePatterns").on("click", function(event) {
event.preventDefault();
if ($("#patternsContainer").hasClass("d-block")) {
$("#patternsContainer")
.removeClass("d-block")
.addClass("d-none");
}
if ($("#spinnerDiv").hasClass("d-none")) {
$("#spinnerDiv")
.removeClass("d-none")
.addClass("d-block");
}
let knitOrCrochet = $("#knit-or-crochet").val();
let yarnWeight = $("#yarnWeight").val();
let articleOfClothing = $("#articleOfClothing").val();
$.ajax({
url: "/api/patterns",
method: "GET",
async: true,
data: {
knitOrCrochet: knitOrCrochet,
yarnWeight: yarnWeight,
articleOfClothing: articleOfClothing
},
dataType: "json",
error: function(errorThrown) {
alert(
"Error code: " + errorThrown + "\n Please refresh and try again."
);
//Remove spinner if error occurs
if (
$("#patternsContainer").hasClass("d-none") &&
$("#spinnerDiv").hasClass("d-block")
) {
$("#spinnerDiv")
.removeClass("d-block")
.addClass("d-none");
$("#patternsContainer")
.removeClass("d-none")
.addClass("d-block");
}
}
}).then(data => {
for (let i = 0; i < data.length; i++) {
$("#patternImage" + (i + 1)).attr("src", data[i].image);
$("#patternName" + (i + 1)).text(data[i].name);
$("#patternAuthor" + (i + 1)).text(data[i].author);
$("#patternLink" + (i + 1)).attr("href", data[i].link);
$("#patternSave" + (i + 1)).attr("data-id", data[i].id);
}
if (
$("#patternsContainer").hasClass("d-none") &&
$("#spinnerDiv").hasClass("d-block")
) {
$("#spinnerDiv")
.removeClass("d-block")
.addClass("d-none");
$("#patternsContainer")
.removeClass("d-none")
.addClass("d-block");
}
});
});
});
|
import AsyncStorage from "@react-native-async-storage/async-storage";
import React, { useEffect, useState } from "react";
import { CommonActions } from "@react-navigation/native";
import {
StyleSheet,
Text,
View,
Image,
TouchableOpacity,
StatusBar,
} from "react-native";
import { Feather } from "@expo/vector-icons";
import firebase from "../Firebase";
function ProfileScreen(props) {
const signout = async () => {
AsyncStorage.setItem("isLoggedIn", "0");
AsyncStorage.setItem("UID", "");
await props.navigation.dispatch(
CommonActions.reset({
index: 0,
key: "null",
routes: [{ name: "Auth" }],
})
);
firebase.auth().signOut();
};
const [userdata, setUserdata] = useState("");
const fetchData = () => {
const uid = global.UID;
const db = firebase.firestore();
db.collection("users")
.doc(uid)
.get()
.then((snapshot) => {
setUserdata(snapshot.data());
})
.catch((err) => console.log(err));
};
useEffect(() => {
fetchData();
const willFocusSubscription = props.navigation.addListener("focus", () => {
fetchData();
});
return willFocusSubscription;
}, []);
return (
<View style={styles.container}>
<View
style={{
marginTop: StatusBar.currentHeight,
padding: 15,
backgroundColor: "white",
borderWidth: 1,
borderColor: "#E5E5E5",
}}
>
<Text style={{ fontSize: 18, fontWeight: "bold" }}>Profile</Text>
</View>
<View
style={{
marginTop: 10,
paddingVertical: 30,
paddingHorizontal: 20,
backgroundColor: "white",
flexDirection: "row",
borderWidth: 1,
borderColor: "#E5E5E5",
}}
>
<TouchableOpacity>
<Image
source={{
uri: userdata.picture,
}}
style={{
height: 60,
width: 60,
borderRadius: 60,
resizeMode: "center",
}}
/>
</TouchableOpacity>
<View style={{ marginLeft: 30, flex: 1 }}>
<Text style={{ fontSize: 16, fontWeight: "bold" }}>
{userdata.name}
</Text>
<Text style={{ fontSize: 12, color: "grey" }}>{userdata.uid}</Text>
<Text style={{ fontSize: 12, color: "grey" }}>{userdata.number}</Text>
<TouchableOpacity
style={{ position: "absolute", right: 5 }}
onPress={() =>
props.navigation.navigate("EditProfile", {
uid: userdata.uid,
name: userdata.name,
picture: userdata.picture,
})
}
>
<Feather name="edit" size={25} color="black" />
</TouchableOpacity>
</View>
</View>
<TouchableOpacity
style={{
width: "40%",
backgroundColor: "white",
alignSelf: "center",
marginTop: 10,
padding: 10,
justifyContent: "center",
alignItems: "center",
flexDirection: "row",
borderRadius: 20,
borderWidth: 1,
borderColor: "#E5E5E5",
}}
onPress={() => props.navigation.navigate("Saved")}
>
<Image
source={require("../assets/icons/saved.png")}
style={{ height: 30, width: 30, resizeMode: "center" }}
/>
<Text style={{ fontSize: 18, marginLeft: 10 }}>Saved</Text>
</TouchableOpacity>
<TouchableOpacity
style={{
backgroundColor: "white",
padding: 15,
marginTop: 15,
borderBottomWidth: 1,
borderColor: "#E5E5E5",
justifyContent: "center",
}}
onPress={() => props.navigation.navigate("Adress")}
>
<Text style={{ fontSize: 16 }}>Address</Text>
<Image
source={require("../assets/icons/stroke.png")}
style={{
height: 20,
width: 20,
resizeMode: "center",
position: "absolute",
right: 20,
}}
/>
</TouchableOpacity>
<TouchableOpacity
style={{
backgroundColor: "white",
padding: 15,
borderBottomWidth: 1,
borderColor: "#E5E5E5",
justifyContent: "center",
}}
onPress={() => props.navigation.navigate("Myorders")}
>
<Text style={{ fontSize: 16 }}>My Orders</Text>
<Image
source={require("../assets/icons/stroke.png")}
style={{
height: 20,
width: 20,
resizeMode: "center",
position: "absolute",
right: 20,
}}
/>
</TouchableOpacity>
<TouchableOpacity
style={{
backgroundColor: "white",
padding: 15,
justifyContent: "center",
}}
onPress={() => props.navigation.navigate("ContactUs")}
>
<Text style={{ fontSize: 16 }}>Contact Us</Text>
<Image
source={require("../assets/icons/stroke.png")}
style={{
height: 20,
width: 20,
resizeMode: "center",
position: "absolute",
right: 20,
}}
/>
</TouchableOpacity>
<TouchableOpacity
style={{
backgroundColor: "white",
padding: 15,
justifyContent: "center",
}}
onPress={() => signout()}
>
<Text style={{ fontSize: 16 }}>Sign Out</Text>
<Image
source={require("../assets/icons/stroke.png")}
style={{
height: 20,
width: 20,
resizeMode: "center",
position: "absolute",
right: 20,
}}
/>
</TouchableOpacity>
<View
style={{
position: "absolute",
backgroundColor: "white",
bottom: 0,
paddingVertical: 50,
width: "100%",
justifyContent: "center",
alignItems: "center",
}}
>
<Text style={{ fontSize: 30 }}>Instyl</Text>
<Text style={{ color: "grey" }}>Version 1</Text>
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
});
export default ProfileScreen;
|
//const router = require('./../../utils/router')
var express = require('express')
var router = express.Router()
const { handleResponse } = require('./../../utils/responseHanlder')
const UserModel = require('./../../models/users.model')
router.post('/', async (req, res) => {
console.log('signup post route was hit')
let { fName, lName, address1, address2, city, state, zip, aptNo, email, phone, password, subscribed_to_mails, accepted_tnc } = req.body
if (!fName || !address1 || !email || !password || !phone) {
return handleResponse(res, 400, 'Missing params')
}
if(!accepted_tnc) {
return handleResponse(res, 400, 'Terms and conditions must be accepted')
}
let existingUser = await UserModel.findOne({ $or: [{email}, {phone}] })
if(existingUser) {
return handleResponse(res, 400, 'User with given mail/phone already exists')
}
let initials = getInitials(fName, lName)
await new UserModel({
fName, lName, address1, address2, city, state, zip, aptNo, email, phone, password, initials, subscribed_to_mails, accepted_tnc
}).save()
return handleResponse(res,201, 'Signup successful')
})
const getInitials = (fName, lName) => {
let initials = fName[0]
if(lName) initials += lName[0]
else if(fName.length>1) initials += fName[1]
return initials
}
module.exports = router
|
(function($){
$.fn.scrollingTo = function( opts ) {
var defaults = {
animationTime : 1000,
easing : '',
callbackBeforeTransition : function(){},
callbackAfterTransition : function(){}
};
var config = $.extend( {}, defaults, opts );
$(this).click(function(e){
var eventVal = e;
e.preventDefault();
var $section = $(document).find( $(this).data('section') );
if ( $section.length < 1 ) {
return false;
};
if ( $('html, body').is(':animated') ) {
$('html, body').stop( true, true );
};
var scrollPos = $section.offset().top;
if ( $(window).scrollTop() == scrollPos ) {
return false;
};
config.callbackBeforeTransition(eventVal, $section);
$('html, body').animate({
'scrollTop' : (scrollPos+'px' )
}, config.animationTime, config.easing, function(){
config.callbackAfterTransition(eventVal, $section);
});
});
};
/* ========================================================================= */
/* Contact Form Validating
/* ========================================================================= */
$('#contact-form').validate({
rules: {
name: {
required: true,
}
, email: {
required: true, email: true,
}
,phonenumber:{
required: true , minlength:10,
}
, aqa: {
required: false,
}
, message: {
required: true,minlength:10,
}
,
}
, messages: {
user_name: {
required: "الرجاء إدخال الاسم ",
}
, email: {
required: "الرجاء إضافة عنوان الإيميل ",
}
, message: {
required: "الرجاء إضافة محتوى الرسالة ", minlength: "يجب ألا يقل المحتوى عن 10 حروف",
}
,phonenumber:{
required:"الرجاء إضافة رقم التواصل " , minlength:"يجب ألا يقل الرقم عن 10 أرقام ",
}
}
, submitHandler: function(form) {
$(form).ajaxSubmit( {
type:"POST", data: $(form).serialize(), url:"sendmail.php", success: function() {
$('#contact-form #success').fadeIn();
}
, error: function() {
$('#contact-form #error').fadeIn();
}
}
);
}
});
}(jQuery));
jQuery(document).ready(function(){
"use strict";
new WOW().init();
(function(){
jQuery('.smooth-scroll').scrollingTo();
}());
});
$(document).ready(function(){
$(window).scroll(function () {
if ($(window).scrollTop() > 50) {
$(".navbar-brand a").css("color","#fff");
$("#top-bar").removeClass("animated-header");
} else {
$(".navbar-brand a").css("color","inherit");
$("#top-bar").addClass("animated-header");
}
});
$("#clients-logo").owlCarousel({
itemsCustom : false,
pagination : false,
items : 5,
autoplay: true,
});
});
// fancybox
$(".fancybox").fancybox({
padding: 0,
openEffect : 'elastic',
openSpeed : 450,
closeEffect : 'elastic',
closeSpeed : 350,
closeClick : true,
helpers : {
title : {
type: 'inside'
},
overlay : {
css : {
'background' : 'rgba(0,0,0,0.8)'
}
}
}
});
|
import React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { searchProducts } from '../actions/index';
class Pagination extends React.Component {
constructor(props) {
super(props);
this.renderPaginationItems = this.renderPaginationItems.bind(this);
this.checkCurrentPage = this.checkCurrentPage.bind(this);
}
componentDidMount() {
}
checkCurrentPage(page){ return page === this.props.currentPage ? 'disabled' : ''};
renderPaginationItems(pageArray) {
return (
pageArray.map(page => {
return(
<li
className="page-item"
key={page}
onClick={e => {
this.props.searchProducts({
query: this.props.currentSearch,
category: this.props.currentCategory,
page
})
}}
>
<span className="page-link">
{page}
</span>
</li>
)
})
);
}
render() {
if(this.props.pages === undefined){
return (<div className=''></div>)
}
return (
<div className=''>
<nav aria-label="Page navigation example">
<ul className="pagination pagination-lg justify-content-center">
{this.renderPaginationItems(this.props.pages)}
</ul>
</nav>
</div>
);
}
}
function mapStateToProps(state) {
return {
pages: state.products.pages,
currentSearch: state.products.currentSearch,
currentCategory: state.products.currentCategory,
currentPage: state.products.currentPage
};
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({ searchProducts }, dispatch);
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(Pagination);
|
var express = require("express");
var router = express.Router();
var teamController = require("../src/teams/teamController");
/* CREATE team */
router.post("/", teamController.createTeam);
/* GET team listing. */
router.get("/", teamController.listTeam);
router.get("/:id", teamController.showTeam);
/* UPDATE team */
router.put("/:id", teamController.updateTeam);
/* DELETE team */
router.delete("/:id", teamController.deleteTeam);
module.exports = router;
|
(function(){
angular.module('app.data').service('commonService',commonService);
commonService.$inject=['$http', '$q', '$filter', '$stateParams', 'dataService','$anchorScroll','$location'];
function commonService($http, $q, $filter, $stateParams, dataService,$anchorScroll,$location){
this.dublicateData=dublicateData;
var deferred=$q.defer();
function dublicateData(url,name){
$http({
method:"GET",
url:url +'/'+name,
}).then(function(result){
console.log(result)
deferred.resolve(result.data)
},function(error){
deferred.error(error)
})
}
}
}())
|
// 二个4x4矩阵相乘
// 或矩阵和齐次坐标相乘
let _multiply = function (matrix4, param) {
let newParam = [];
for (let i = 0; i < 4; i++)
for (let j = 0; j < param.length / 4; j++)
newParam[j * 4 + i] =
matrix4[i] * param[j * 4] +
matrix4[i + 4] * param[j * 4 + 1] +
matrix4[i + 8] * param[j * 4 + 2] +
matrix4[i + 12] * param[j * 4 + 3];
return newParam;
};
import _move from './.inside/move';
import _rotate from './.inside/rotate';
import _scale from './.inside/scale';
import _transform from './.inside/transform';
/**
* 4x4矩阵
* 列主序存储
* @since V0.2.0
* @public
*/
export default function (initMatrix4) {
let matrix4 = initMatrix4 || [
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1
];
let matrix4Obj = {
// 移动
"move": function (dis, a, b, c) {
matrix4 = _multiply(_move(dis, a, b, c), matrix4);
return matrix4Obj;
},
// 旋转
"rotate": function (deg, a1, b1, c1, a2, b2, c2) {
var matrix4s = _transform(a1, b1, c1, a2, b2, c2);
matrix4 = _multiply(_multiply(_multiply(matrix4s[1], _rotate(deg)), matrix4s[0]), matrix4);
return matrix4Obj;
},
// 缩放
"scale": function (xTimes, yTimes, zTimes, cx, cy, cz) {
matrix4 = _multiply(_scale(xTimes, yTimes, zTimes, cx, cy, cz), matrix4);
return matrix4Obj;
},
// 乘法
// 可以传入一个矩阵(matrix4,flag)
"multiply": function (newMatrix4, flag) {
matrix4 = flag ? _multiply(matrix4, newMatrix4) : _multiply(newMatrix4, matrix4);
return matrix4Obj;
},
// 对一个坐标应用变换
// 齐次坐标(x,y,z,w)
"use": function (x, y, z, w) {
// w为0表示点位于无穷远处,忽略
z = z || 0; w = w || 1;
var temp = _multiply(matrix4, [x, y, z, w]);
temp[0] = +temp[0].toFixed(7);
temp[1] = +temp[1].toFixed(7);
temp[2] = +temp[2].toFixed(7);
temp[3] = +temp[3].toFixed(7);
return temp;
},
// 矩阵的值
"value": function () {
return matrix4;
}
};
return matrix4Obj;
};
|
var User = require("../models/user");
var Class = require("../models/class");
var Complaint = require("../models/complaint");
var middlewareObj = {};
middlewareObj.isAdmin = function (req,res,next){
if( req.isAuthenticated() ){
if(req.user.isrole==="admin"){
next();
}
else{
req.logout();
res.redirect("back");
}
}else{
res.redirect("back");
}
};
middlewareObj.isProfessor = function (req,res,next){
if( req.isAuthenticated() ){
if(req.user.isrole==="professor"){
next();
}
else{
req.logout();
res.redirect("back");
}
}else{
res.redirect("back");
}
};
middlewareObj.classOwnership = function (req,res,next){
if(req.isAuthenticated() && req.user.isrole==="professor"){
Class.findById(req.params.id,function(err,foundclass){
if(err){
console.log(err);
res.redirect("back");
}
else{
if(req.user._id.equals(foundclass.author.id)){
next();
}
else{
console.log(err);
res.redirect("back");
}
}
});
}
else{
console.log(err);
res.redirect("back");
}
};
middlewareObj.isStudent = function (req,res,next){
if( req.isAuthenticated() ){
if(req.user.isrole==="student"){
next();
}
else{
req.logout();
res.redirect("back");
}
}else{
res.redirect("back");
}
};
module.exports = middlewareObj;
|
angular.module('ddysys.services')
.factory('Appointments', function(PostData, $http) {
return {
all: function(type) {
var postData = new PostData('apphosAddresList');
postData.limit = 30; //后续可能要加分页
if(type != '') postData.pStatus = type; //如要取所有的预约,需将该参数留空
return $http.post('api', postData);
},
get: function(id) {
var postData = new PostData('apphosAddresInfo');
postData.plusId = id;
return $http.post('api', postData);
},
handle: function(id, pStatus, reason){
var postData = new PostData('appupdateHosAddres');
postData.plusId = id;
postData.pStatus = pStatus;
postData.reason = reason;
return $http.post('api', postData);
},
formatDate: function(date){
if(date) return date.replace(/(\d{4})(\d{2})(\d{2})/, '$1-$2-$3') //要加条件,否则会不停报date undefined错误
},
formatPStatus: function(pStatus){
switch(pStatus){
case "Y":
return {class:"balanced", text: "已同意"};
break;
case "N":
return {class:"assertive", text: "已拒绝"};
break;
case "W":
return {class:"positive", text: "待处理", todo: true};
break;
}
}
}
})
|
const User = require('../../../models/user');
const { TransformObject } = require('../users/merge');
const { createToken } = require("../global/createToken");
exports.recordExercisePlayed = async (args, req) => {
try {
const user = await User.findById(req.userId);
let courseProgress = [{ courseId: args.courseId, exercisesPlayed: {} }];
if (user.courseProgress && user.courseProgress.length > 0) courseProgress = user.courseProgress;
let courseProgressIndex = courseProgress
.findIndex(course => course.courseId === args.courseId );
if (courseProgressIndex === -1) {
courseProgress.push({ courseId: args.courseId, exercisesPlayed: {} });
courseProgressIndex = courseProgress.length - 1;
}
const newCourseObject = courseProgress[courseProgressIndex].exercisesPlayed
[`${ args.sectionIndex }-${ args.videoIndex }-${ args.exercise }`];
if (newCourseObject) {
JSON.parse(newCourseObject)[args.exercise] = args.score;
} else {
let tmpPlayedExercise = null;
const exercisePlayed = courseProgress[courseProgressIndex].exercisesPlayed;
if (typeof exercisePlayed === "string") {
tmpPlayedExercise = JSON.parse(exercisePlayed);
} else {
courseProgress[courseProgressIndex].exercisesPlayed = {};
tmpPlayedExercise = courseProgress[courseProgressIndex].exercisesPlayed;
}
tmpPlayedExercise[`${ args.sectionIndex }-${ args.videoIndex }-${ args.exercise }`] = args.score;
courseProgress[courseProgressIndex].exercisesPlayed = JSON.stringify(tmpPlayedExercise);
}
user.courseProgress = courseProgress;
user.markModified('courseProgress');
user.save();
const token = createToken(user);
return { token, ...TransformObject(user) }
} catch (e) {
throw e;
}
};
|
class Renderer {
render(a, b, c) {
document.getElementById("box").style.bottom = String(a) + "px";
b.forEach((o, i) => {
document.getElementsByClassName("object")[i].setAttribute("style", "right: " + o.right + "px");
});
document.getElementById("score").innerHTML = c;
}
reset() {
//for(let i = 0; i < document.getElementsByClassName("object").length; i++){
$(".object").remove(); /*[i]*/
//}
}
}
class Game {
constructor() {
this.Render = new Renderer();
this.Player = new Box();
this.Obsticals = [];
this.isnewObjectvar = 0;
this.highscore = 0;
this.score = 0;
this.Gameloop();
}
restart() {
clearInterval(this.loopofGame);
if (this.score > this.highscore) {
this.highscore = this.score;
document.getElementById("highscore").innerHTML = "High Score: " + this.highscore;
}
this.Player.reset();
this.Render.reset();
this.Obsticals = [];
this.isnewObjectvar = 0;
this.score = 0;
this.Gameloop();
}
start() {
document.body.onkeyup = (e) => {
if (e.keyCode == 32) {
this.Player.jump();
}
};
document.body.addEventListener("click", () => {
this.Player.jump();
});
}
update() {
this.Render.render(this.Player.height, this.Obsticals, this.score);
this.Player.Fall();
this.Obsticals.forEach((o) => {
o.move();
});
if (this.isnewObject()) {
this.Obsticals.push(new Obsical(1));
this.Obsticals.forEach((o, i) => {
if (o.right > 2000) {
this.Obsticals.shift();
document.getElementsByClassName("object")[0].remove();
}
});
}
if (this.IsGameOver()) {
this.restart();
}
}
Gameloop() {
this.start();
this.loopofGame = setInterval(() => {
this.update();
}, 10);
}
isnewObject() {
this.isnewObjectvar += 1;
if (this.isnewObjectvar == 200) {
this.isnewObjectvar = 0;
this.score += 1;
return true;
} else {
return false;
}
}
IsGameOver() {
let Temp = false;
let Box = document.getElementById("box");
let style = window.getComputedStyle(Box).right;
style = parseInt(style);
this.Obsticals.forEach((o) => {
if ((o.right - 40 < style && o.right > style) || (o.right - 40 < style + 20 && o.right > style + 20)) {
if (this.Player.height > o.bottom && this.Player.height + 20 < o.top) {
Temp = false;
} else {
Temp = true;
}
}
});
if (this.Player.height < 0) {
this.Player.height = 200;
this.Player.speed = 0;
Temp = true;
}
if (this.Player.height > 500) {
this.Player.height = 200;
this.Player.speed = 0;
Temp = true;
}
return Temp;
}
}
class Box {
constructor() {
this.height = 200;
this.speed = 0;
}
reset() {
this.height = 200;
this.speed = 0;
}
Fall() {
this.height -= this.speed;
this.getFaster();
}
getFaster() {
this.speed += 0.05;
}
jump() {
this.speed = -3;
}
}
class Obsical {
constructor(a) {
let Temp = Math.floor(Math.random() * 350 + 1);
let object = document.createElement("div");
object.setAttribute("class", "object");
let top = document.createElement("div");
top.setAttribute("class", "top");
top.setAttribute("style", "height: " + String(Temp) + "px");
let bottom = document.createElement("div");
bottom.setAttribute("class", "bottom");
bottom.setAttribute("style", "height: " + String(500 - Temp - 150) + "px");
object.appendChild(top);
object.appendChild(bottom);
document.getElementById("container").appendChild(object);
this.top = 500 - Temp;
this.bottom = 500 - Temp - 150;
this.right = 0;
this.speed = a;
}
move() {
this.right = this.right + this.speed;
}
}
let Game1 = new Game();
|
module.exports = {
name: 'stockhelp',
description: 'help function',
execute(message, args, Discord, client) {
const symbol = '⏹️';
let embed = new Discord.MessageEmbed()
.setColor("#1a73e8")
.setTitle("Command List:")
.setAuthor('StockBot' + symbol)
.setDescription("A list of useful commands.")
.addFields(
{name:'\u200b', value:'\u200b'},
{name:"`-get [SYM]`", value:"Get the current stock information for a symbol."},
{name:"`-makeportfolio`", value:"Initializes a users portfolio."},
{name:"`-portfolio` / `-p`", value:"View your portfolio."},
{name:"`-buy [AMOUNT] [SYM]`", value:"Buy an amount of stock of the symbol entered."},
{name:"`-sell [AMOUNT] [SYM]`", value:"Sell an amount of stock of the symbol entered."},
{name:"`-view`", value:"See the symbols of some potential stocks to buy."},
{name:"`-stockhelp`", value:"You are here."},
{name:'\u200b', value:'\u200b'},
)
message.channel.send(embed);
}
}
|
import omit from 'lodash/omit';
import { types } from '../constants';
const initialState = { boards: {}, loading: false, isBoardDeleting: false };
export default (state = initialState, action) => {
switch (action.type) {
case types.GET_BOARDS_START:
return { ...state, loading: true };
case types.GET_BOARDS_SUCCESS:
return { ...state, boards: action.payload, loading: false };
case types.CREATE_BOARD:
return {
...state,
boards: { ...state.boards, [action.payload.id]: action.payload }
};
case types.UPDATE_BOARD:
const { id, params } = action.payload;
return {
...state,
boards: { ...state.boards, [id]: { ...state.boards[id], ...params } }
};
case types.DELETE_BOARD_START:
return { ...state, isBoardDeleting: true };
case types.DELETE_BOARD_SUCCESS:
return { ...state, boards: omit(state.boards, action.payload), isBoardDeleting: false };
case types.AUTH_SIGN_OUT:
return initialState;
default:
return state;
}
};
|
let arr = [
{ id: 1, src: 'https://placebear.com/50/50', title: 'Some Title', desc: 'The description', favorite: false },
{ id: 2, src: 'https://placebear.com/50/50', title: 'Some Title', desc: 'The description', favorite: false },
{ id: 3, src: 'https://placebear.com/50/50', title: 'Some Title', desc: 'The description', favorite: false },
];
function buildList() {
const main = document.getElementById('main');
arr.forEach(item => {
const wrapper = document.createElement('div');
const left = document.createElement('div');
const right = document.createElement('div');
const image = document.createElement('img');
const title = document.createElement('h2');
const lineBreak = document.createElement('br');
const desc = document.createElement('p');
const favorite = document.createElement('span');
wrapper.className = 'wrapper';
left.className = 'left';
right.className = 'right';
favorite.className = 'favorite';
favorite.setAttribute('data-id', item.id);
favorite.onclick = handleFavClick;
title.innerText = item.title;
title.className = 'title';
desc.className = 'description';
desc.innerText = item.desc;
image.src = item.src;
main.appendChild(wrapper);
wrapper.appendChild(favorite);
wrapper.appendChild(image);
wrapper.appendChild(right);
right.appendChild(title);
right.appendChild(lineBreak);
right.appendChild(desc);
});
}
function handleFavClick(e) {
const id = e.target.dataset.id;
e.target.className = e.target.className === 'favorite checked' ? 'favorite' : 'favorite checked';
// Using this method of updating the array because I will not be mutating the array, but replacing it with a new array
arr = arr.map(item => {
if (item.id === Number(id)) {
return Object.assign({}, item, {favorite: true})
} else {
return item;
}
});
}
|
Vue.component('calendar', {
template: `<div id="calendar" style="display: flex; flex-direction: column; height: 100%;">
<div :style="{background: '#2d8cf0',
'display': 'flex', 'flex-direction': 'row', 'justify-content': 'flex-start',
'align-items': 'center', color: 'white' }"
>
<div style="flex: 1;"></div>
<Icon type="ios-arrow-back" size="28" @click.native="onClickIcon(-1)"
style="cursor: pointer; margin-right: 10px;"/>
<div style="font-size: 30px;">{{month.toString("yyyy-mm")}}</div>
<Icon type="ios-arrow-forward" size="28" @click.native="onClickIcon(1)"
style="cursor: pointer; margin-left: 10px;" />
<div style="flex: 1; text-align: right;">
<Icon type="md-more" size="28" @click.native="onClickIconMore"
style="cursor: pointer; margin-right: 10px;" />
</div>
</div>
<div style="display: flex; flex-direction: row; background-color: #e5e5e5">
<div v-for="(item, index) in weekday" style="flex: 1; padding: 5px 0 ">
<div :style="{'text-align': 'center', color: index >= 5 ? '#FF8C00' : ''}">
{{'星期' + item}}
</div>
</div>
</div>
<div style="flex: 1; display: flex; flex-direction: column;">
<div class="row" v-for="(weeks, index1) in schedule" style="flex: 1; display: flex; flex-direction: row;">
<div class="col" v-for="(day, index2) in weeks"
:style="{flex: '1', height: '100%', padding: '5px',
backgroundColor: day.available ? (day.workday == 2 ? 'rgba(45, 140, 250, 0.2)' : 'white') : '#F8F8F8',
}">
<!-- 非當月 -->
<div v-if="day.available == false" style="height: 100%; display: flex; flex-direction: column;">
<div style="text-align: center; color: #D3D3D3;">{{day.day}}</div>
<div v-if="typeof day.holiday == 'string'"
style="text-align: center; color: rgba(0,0,0, 0.3); background-color: rgba(0, 255, 0, 0.2);">
{{day.holiday}}
</div>
</div>
<!-- 國定假日 -->
<div v-else-if="typeof day.holiday == 'string'" style="height: 100%;">
<div style="text-align: center;">{{day.day}}</div>
<div style="text-align: center; background-color: green; color: white;">
{{day.holiday}}
</div>
</div>
<!-- 工作日 workday: 1 今天以前,2 今天,3 今天以後 -->
<div v-else-if="day.workday > 0" style="height: 100%; display: flex; flex-direction: column;">
<div style="text-align: center;">{{day.day}}</div>
<record :workday="day.workday"
:preload="preload[day.date]"
:datas="recorder"
:date="day.date"
:alarm="alarm"
@onAlarmSet="onAlarmSet"
></record>
</div>
<!-- 周末,周日 -->
<div v-else :style="{height: '100%'}">
<div :style="{'text-align': 'center', color: '#FF8C00'}">{{day.day}}</div>
</div>
</div>
</div>
</div>
<i-button v-if="btn.length > 0" type="primary" shape="circle" size="large"
@click.native="onAdd" id="btnAdd"
style="position: absolute; bottom: 10px; right: 10px;">
{{btn}}
</i-button>
<datePick ref="datePick" :date="alarm" @onChangeAlarm="onChangeAlarm" />
<setting ref="setting" :date="alarm" @onChangeSetting="onChangeSetting" @onChangePreload="onChangePreload" />
</div>`,
props: {
},
data() {
return {
schedule: [],
preload: {},
recorder: null,
weekday: ["一", "二", "三", "四", "五", "六", "日"],
today: new Date(),
month: new Date(),
btn: "上",
alarm: "",
visible: false
};
},
created(){
window.onmessage = function(e){
// this.console.log(e.data)
if(typeof e.data.from == "string" && e.data.from == "background"){
// if(e.origin.indexOf('://localhost:') == -1 && e.origin.indexOf('://jimc052.github.io/') == -1){
console.log(e.data)
}
};
},
async mounted () {
// delete window.localStorage["schedule=2020-02"]
// delete window.localStorage["alarm"];
window.postMessage({cmd: 'getAlarms'}, "*");
let s = window.localStorage["schedule=proload"];
if(typeof s == "string" && s.length > 0) {
this.preload = JSON.parse(s);
}
if(this.$isDebug()){
// this.today = new Date(2022, 4, 1, 8, 52)
// this.preload = {
// "2022-08-12":{"上班":"08:00","下班":"19:00"},
// "2021-12-21":{"上班":"11:00","下班":"19:00"},
// };
}
let arr = [];
let today = this.today.toString("yyyy-mm-dd");
for(let key in this.preload) {
if(key < today) {
arr.push(key)
}
}
if(typeof this.preload[today] == "object") {
let now = (new Date()).toString("hh:MM");
for(let key in this.preload[today]) {
if(now >= this.preload[today][key]) {
delete this.preload[today][key];
window.localStorage["schedule=proload"] = JSON.stringify(this.preload);
}
}
}
if(arr.length > 0) {
arr.forEach(item =>{
delete this.preload[item]
})
window.localStorage["schedule=proload"] = JSON.stringify(this.preload);
}
console.log(JSON.stringify(this.preload))
this.alarm = this.$storage("alarm");
this.retrieve();
},
destroyed() {
},
methods: {
onClickIconMore(){
this.$refs["setting"].visible = true;
},
onChangeSetting(value){
console.log("onChangeSetting: " + value)
this.setAlarm(this.alarm)
},
onChangePreload(value){
this.preload = value;
this.retrieve();
},
onAlarmSet(){
this.$refs["datePick"].visible = true;
},
onChangeAlarm(d){
console.log(d)
this.setAlarm(d)
},
isToday(today){
if(this.$isDebug()) return true;
if(typeof today == "undefined") today = this.today;
return today.toString("yyyy-mm-dd") == (new Date()).toString("yyyy-mm-dd");
},
onAdd() {
if(this.isToday() == false) {
alert("日期逾時,請更新網頁")
} else {
let url = 'https://bccjd.jabezpos.com/main?designer=BCC_EIP';
// 'https://jd.jabezpos.com/?designer=BCC_EIP&database=ERPS&solution=SOLUTION1';
// let url = 'https://bccjd.jabezpos.com/main?designer=BCC_EIP';
if(this.$isDebug() == false){
window.open(url, "",
"resizable=yes,toolbar=no,status=no,location=no,menubar=no,scrollbars=yes"
);
}
let month = this.today.toString("yyyy-mm");
let dd = this.today.toString("dd");
if(this.recorder == null || typeof this.recorder == "undefined") {
this.recorder = {};
}
if(typeof this.recorder[dd] == "undefined") {
this.recorder[dd] = {};
}
this.recorder[dd][this.btn] = (new Date()).toString("hh:MM");
this.$set(this.recorder, dd, this.recorder[dd])
// this.recorder[dd].push(obj);
this.$storage("schedule=" + month, this.recorder);
let d1 = this.today;
if(this.btn == "下班") {
let d1 = this.today.addDays(1);
let s1 = d1.toString("yyyy-mm-dd");
while(typeof holiday[s1] == "string") {
d1 = this.today.addDays(1);
s1 = d1.toString("yyyy-mm-dd");
}
}
let y = d1.getFullYear(), m = d1.getMonth();
let {schedule, recorder} = this.parseSchedule(y, m);
if(recorder == null) recorder = {};
let {time, btn} = this.arrangeAlarm(d1, schedule, recorder);
if(time.length == 0) {
if(m == 11) {
y++; m = 0;
} else {
m++;
}
let d1 = new Date(y, m, 1)
let {schedule, recorder} = this.parseSchedule(y, m);
if(recorder == null) recorder = {};
let {time} = this.arrangeAlarm(d1, schedule, recorder);
this.setAlarm(time);
this.btn = "";
} else {
this.setAlarm(time);
this.btn = (this.btn == "上班") ? "下班" : "";
}
}
},
setAlarm(date){
// if(date.length < 10) return;
this.alarm = date;
this.$storage("alarm", date);
let periodInMinutes = this.$storage("periodInMinutes");
let d = new Date(date);
window.postMessage({cmd: 'setAlarm', name: date,
when: d.getTime(),
periodInMinutes: parseInt(periodInMinutes, 10)
}, "*");
},
onClickIcon(index) {
this.today = new Date();
let y = this.month.getFullYear()
let m = this.month.getMonth() + index;
if(m <= -1) {
m = 11;
y--;
} else if(m >= 12) {
m = 0;
y++;
}
this.month = new Date(y, m, 1);
this.retrieve()
},
retrieve() {
this.btn = "";
// this.schedule = []; this.schedule = [];
let y = this.month.getFullYear(), m = this.month.getMonth();
let {schedule, recorder} = this.parseSchedule(y, m);
this.recorder = recorder;
this.schedule = schedule;
// && this.alarm.length == 0
if(this.month.toString("yyyy-mm") == this.today.toString("yyyy-mm")) {
let {time, btn, isPreload} = this.arrangeAlarm(this.today, schedule, recorder);
// console.log(time, btn)
if(time.length == 0) {
if(m == 11) {
y++; m = 0;
} else {
m++;
}
let d1 = new Date(y, m, 1)
let {schedule, recorder} = this.parseSchedule(y, m);
if(recorder == null) recorder = {};
let {time} = this.arrangeAlarm(d1, schedule, recorder);
this.setAlarm(time);
} else {
if(this.alarm.length == 0 || this.alarm.substr(0, 10) < this.today.toString("yyyy-mm-dd"))
this.setAlarm(time);
else if(isPreload == true && time >= this.today.toString("yyyy-mm-ddThh:MM") )
this.setAlarm(time);
if(time.substr(0, 10) == this.today.toString("yyyy-mm-dd")) // isPreload
this.btn = btn;
}
}
},
parseSchedule(y, m) {
let d1 = new Date(y, m, 1);
let month = d1.toString("yyyy-mm");
let days = d1.getDay() * -1;
let myRecords = this.$storage("schedule=" + month);
let mySchedule = [];
d1.addDays(days + (days == 0 ? -6 : 1));
let today = this.today.toString("yyyy-mm-dd");
for(let i = 0; i <= 5; i++) {
let arr = [];
for(let j = 0; j <= 6; j++) {
let s1 = d1.toString("yyyy-mm-dd");
// console.log(s1 + ": " + d1.getDay())
let obj = {
date: s1,
day: d1.toString("d"),
available: s1.substr(0, 7) == month,
holiday: typeof holiday[s1] == "string" ? holiday[s1] : undefined,
workday: 0,
};
if((d1.getDay() > 0 && d1.getDay() < 6) || workday.indexOf(s1) > -1) {
obj.workday = s1 == today ? 2 : (s1 > today ? 3 : 1)
}
obj.editable = s1 >= this.today.toString("yyyy-mm-dd");
arr.push(obj);
d1.addDays(1);
}
mySchedule.push(arr)
if(d1.toString("yyyy-mm") > month) break;
}
return {schedule: mySchedule, recorder: myRecords};
},
arrangeAlarm(date, schedule, records){
let s1 = date.toString("yyyy-mm-dd");
let morning = this.$storage("morning");
let preload = typeof this.preload[s1] == "undefined" ? {} : this.preload[s1];
for(let i = 0; i < schedule.length; i++) {
let week = schedule[i];
for(let j = 0; j < week.length; j++) {
let row = week[j];
if(row.date >= s1 && row.workday == 2) { // 工作日
let dd = row.date.substr(8);
let state = "";
if(records) {
if(typeof records[dd] == "undefined") records[dd] = {};
if(typeof records[dd]["下班"] == "string")
continue;
else if(typeof records[dd]["上班"] == "string")
state = "下班";
else
state = "上班";
} else {
if(row.date > s1 || (new Date()).getHours() > 12)
state = "下班";
else
state = "上班";
}
if(state.length > 0) {
if(typeof preload[state] == "string") {
return {time: row.date + "T" + preload[state], btn: state, isPreload: true};
} else
return {time: row.date + "T" + (state == "上班" ? morning : "18:00"), btn: state};
}
} else if(row.date >= s1 && row.workday == 3) { //今天以後
preload = typeof this.preload[row.date] == "undefined" ? {} : this.preload[row.date]
if(typeof preload["上班"] == "string") {
return {time: row.date + "T" + preload["上班"], btn: "上班", isPreload: true};
} else
return {time: row.date + "T" + morning, btn: "上班"};
}
}
}
return {time: "", btn: ""};
},
onClickDay(day) {
if(this.isToday() == false) {
alert("日期逾時,請更新網頁")
}
},
},
watch: {
}
});
// OK 的 function
// window.postMessage({cmd: 'clearAlarms'}, "*");
// window.postMessage({cmd: 'getAlarms'}, "*");
// window.postMessage({cmd: 'setAlarm', name: "測試 alarm",
// when: Date.now() + (1000 * 60) ,
// periodInMinutes: 3
// }, "*");
|
/**
* Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH
* under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership.
*
* Camunda licenses this file to you under the MIT; you may not use this file
* except in compliance with the MIT License.
*/
import {
bootstrapModeler,
inject
} from 'bpmn-js/test/helper';
import TestContainer from 'mocha-test-container-support';
import propertiesPanelModule from 'bpmn-js-properties-panel';
import {
query as domQuery,
classes as domClasses
} from 'min-dom';
import coreModule from 'bpmn-js/lib/core';
import selectionModule from 'diagram-js/lib/features/selection';
import modelingModule from 'bpmn-js/lib/features/modeling';
import propertiesProviderModule from '..';
import zeebeModdleExtensions from 'zeebe-bpmn-moddle/resources/zeebe';
describe('zeebe-properties-provider', function() {
const diagramXML = require('./ParticipantProcess.bpmn');
const modules = [
coreModule,
selectionModule,
modelingModule,
propertiesPanelModule,
propertiesProviderModule
];
const moddleExtensions = {
zeebe: zeebeModdleExtensions
};
let container;
beforeEach(function() {
container = TestContainer.get(this);
});
beforeEach(bootstrapModeler(diagramXML, {
modules,
moddleExtensions
}));
beforeEach(inject(function(propertiesPanel) {
propertiesPanel.attachTo(container);
}));
describe('general tab', function() {
it('should show general group', inject(function(selection, elementRegistry) {
// given
const pool = elementRegistry.get('Participant_1');
// when
selection.select(pool);
// then
shouldHaveGroup(container, 'general', 'general');
}));
it('should have pool id and name inputs', inject(function(selection, elementRegistry) {
// given
const pool = elementRegistry.get('Participant_1');
// when
selection.select(pool);
// then
shouldHaveInput(container, 'general', 'participant-id');
shouldHaveInput(container, 'general', 'participant-name');
}));
it('should have pool process id and process name inputs', inject(function(selection, elementRegistry) {
// given
const pool = elementRegistry.get('Participant_1');
// when
selection.select(pool);
// then
shouldHaveInput(container, 'general', 'process-id');
shouldHaveInput(container, 'general', 'process-name');
}));
});
});
// helper /////////
function getTab(container, tabName) {
return domQuery(`div[data-tab="${tabName}"]`, container);
}
function getGroup(container, tabName, groupName) {
const tab = getTab(container, tabName);
return domQuery(`div[data-group="${groupName}"]`, tab);
}
function getInput(container, tabName, inputName) {
const tab = getTab(container, tabName);
return domQuery(`div[data-entry="${inputName}"]`, tab);
}
const shouldHaveGroup = (container, tabName, groupName) => {
const group = getGroup(container, tabName, groupName);
expect(group).to.exist;
expect(domClasses(group).has('bpp-hidden')).to.be.false;
};
const shouldHaveInput = (container, tabName, inputName) => {
const input = getInput(container, tabName, inputName);
expect(input).to.exist;
};
|
const express = require ('express');
const router = express.Router();
//tutaj dodajecie swoje routes
router.use('/',require('./books'))
router.use('/',require('./authors'))
router.use('/',require('./users'))
router.use('/',require('./orders'))
//wyrzuca stronę
router.get('/',(req,res,next)=>{
res.sendFile('index.html')
})
module.exports = router
|
/**
* Copyright 2016 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
goog.provide('audioCat.ui.tracks.widget.CreateEmptyTrackWidget');
goog.require('audioCat.ui.tracks.widget.TrackLeftBottomWidget');
/**
* A widget for creating new empty tracks.
* @param {!audioCat.utility.DomHelper} domHelper Facilitates DOM interactions.
* @param {!audioCat.action.track.CreateEmptyTrackAction} createEmptyTrackAction
* An action for creating empty tracks.
* @constructor
* @extends {audioCat.ui.tracks.widget.TrackLeftBottomWidget}
*/
audioCat.ui.tracks.widget.CreateEmptyTrackWidget = function(
domHelper,
createEmptyTrackAction) {
/**
* @private
*/
this.createEmptyTrackAction_ = createEmptyTrackAction;
goog.base(this, domHelper, '+ Empty', 'Add empty track.');
};
goog.inherits(audioCat.ui.tracks.widget.CreateEmptyTrackWidget,
audioCat.ui.tracks.widget.TrackLeftBottomWidget);
/** @override */
audioCat.ui.tracks.widget.CreateEmptyTrackWidget.prototype.handleUpPress =
function() {
this.createEmptyTrackAction_.doAction();
};
|
const { paginationResolvers } = require('@limit0/mongoose-graphql-pagination');
const moment = require('moment');
const userAttributionFields = require('./user-attribution');
const Advertiser = require('../../models/advertiser');
const Campaign = require('../../models/campaign');
const Publisher = require('../../models/publisher');
const Story = require('../../models/story');
const Image = require('../../models/image');
const ga = require('../../services/google-analytics');
const storySearchFilter = [
{
bool: {
must: [
{ term: { deleted: false } },
{ term: { placeholder: false } },
],
},
},
];
const getMetricStartDate = (publishedAt, startDate) => (startDate.valueOf() < publishedAt.valueOf()
? publishedAt
: startDate
);
const quotaUser = ({ auth, ip }) => {
const { sessionId } = auth;
if (sessionId) return sessionId;
return ip;
};
module.exports = {
/**
*
*/
StoryReports: {
byDay: (story, { startDate, endDate }, ctx) => {
const { publishedAt, status } = story;
if (status !== 'Published') {
return [];
}
return ga.storyReportByDay(story.id, {
quotaUser: quotaUser(ctx),
endDate,
startDate: getMetricStartDate(publishedAt, startDate),
});
},
acquisition: (story, args, ctx) => {
const { publishedAt, status } = story;
if (status !== 'Published') {
return [];
}
return ga.storyAcquisitionReport(story.id, {
quotaUser: quotaUser(ctx),
startDate: publishedAt,
endDate: new Date(),
});
},
devices: (story, args, ctx) => {
const { publishedAt, status } = story;
if (status !== 'Published') {
return [];
}
return ga.storyDeviceReport(story.id, {
quotaUser: quotaUser(ctx),
startDate: publishedAt,
endDate: new Date(),
});
},
},
/**
*
*/
StoryReportByDay: {
date: ({ date }, { format }) => moment(date).format(format),
},
/**
*
*/
Story: {
// @todo Determine if this should run a strict/active find.
// Ultimately, deleting an advertiser should delete it's stories?
advertiser: story => Advertiser.findById(story.advertiserId),
publisher: (story, { contextId }) => {
const publisherId = contextId || story.publisherId;
return Publisher.findById(publisherId);
},
primaryImage: story => Image.findById(story.primaryImageId),
images: story => Image.find({ _id: { $in: story.imageIds } }),
campaigns: (story, { pagination, sort }) => {
const criteria = { storyId: story.id, deleted: false };
return Campaign.paginate({ pagination, criteria, sort });
},
previewUrl: story => story.getUrl({ preview: true }),
url: story => story.getUrl(),
hash: story => story.pushId,
path: story => story.getPath(),
metrics: async (story, args, ctx) => {
const { publishedAt, status } = story;
if (status !== 'Published') {
return ga.getDefaultMetricValues();
}
const report = await ga.storyReport(story.id, {
startDate: publishedAt,
endDate: new Date(),
quotaUser: quotaUser(ctx),
});
return report.metrics;
},
reports: story => story,
...userAttributionFields,
},
StorySitemapItem: {
loc: async (story) => {
const url = await story.getUrl();
/**
* Per the sitemap entity escaping section
* @see https://www.sitemaps.org/protocol.html#escaping
*/
return url
.replace('&', '&')
.replace('\'', ''')
.replace('"', '"')
.replace('>', '>')
.replace('<', '<');
},
lastmod: ({ updatedAt }) => (updatedAt ? moment(updatedAt).toISOString() : null),
changefreq: () => 'monthly',
priority: () => 0.5,
image: ({ primaryImageId }) => {
if (!primaryImageId) return null;
return Image.findById(primaryImageId);
},
},
StorySitemapImage: {
loc: image => image.getSrc(),
caption: () => null,
},
/**
*
*/
StoryConnection: paginationResolvers.connection,
/**
*
*/
Query: {
/**
*
*/
story: (root, { input }) => {
const { id } = input;
return Story.strictFindActiveById(id);
},
/**
*
*/
publishedStory: async (root, { input }) => {
const { id, preview } = input;
const story = await Story.strictFindActiveById(id);
if (preview) return story;
const { status } = story;
if (status !== 'Published') {
throw new Error(`No story found for ID '${id}'`);
}
return story;
},
/**
*
*/
storyHash: (root, { input }) => {
const { advertiserId, hash } = input;
return Story.strictFindActiveOne({ advertiserId, pushId: hash });
},
/**
*
*/
allStories: (root, { pagination, sort }) => {
const criteria = {
deleted: false,
placeholder: false,
};
return Story.paginate({ criteria, pagination, sort });
},
/**
*
*/
publishedStories: (root, { pagination, sort }) => {
const criteria = {
deleted: false,
placeholder: false,
publishedAt: { $lte: new Date() },
};
return Story.paginate({ criteria, pagination, sort });
},
storySitemap: () => {
const criteria = {
deleted: false,
placeholder: false,
publishedAt: { $lte: new Date() },
};
return Story.find(criteria).sort({ publishedAt: -1 });
},
/**
*
*/
searchStories: (root, { pagination, phrase }) => Story
.search(phrase, { pagination, filter: storySearchFilter }),
/**
*
*/
autocompleteStories: async (root, { pagination, phrase }) => Story
.autocomplete(phrase, { pagination, filter: storySearchFilter }),
},
/**
*
*/
Mutation: {
/**
* Clones a story
*/
cloneStory: async (root, { input }, { auth }) => {
auth.check();
const { id } = input;
const doc = await Story.strictFindActiveById(id);
return doc.clone(auth.user);
},
/**
*
*/
createStory: (root, { input }, { auth }) => {
auth.check();
const { payload } = input;
const {
title,
advertiserId,
publisherId,
publishedAt,
} = payload;
const story = new Story({
title,
advertiserId,
publisherId,
publishedAt,
});
story.setUserContext(auth.user);
return story.save();
},
/**
*
*/
deleteStory: async (root, { input }, { auth }) => {
auth.check();
const { id } = input;
const story = await Story.strictFindActiveById(id);
story.setUserContext(auth.user);
return story.softDelete();
},
/**
*
*/
updateStory: async (root, { input }, { auth }) => {
auth.check();
const { id, payload } = input;
const {
title,
teaser,
body,
advertiserId,
publisherId,
publishedAt,
} = payload;
const story = await Story.strictFindActiveById(id);
story.setUserContext(auth.user);
story.set({
title,
teaser,
body,
advertiserId,
publisherId,
publishedAt,
});
return story.save();
},
/**
*
*/
removeStoryImage: async (root, { storyId, imageId }, { auth }) => {
const story = await Story.strictFindActiveById(storyId);
auth.checkAdvertiserAccess(story.advertiserId);
if (auth.user) {
story.setUserContext(auth.user);
}
story.removeImageId(imageId);
return story.save();
},
/**
*
*/
addStoryImage: async (root, { storyId, imageId }, { auth }) => {
const story = await Story.strictFindActiveById(storyId);
auth.checkAdvertiserAccess(story.advertiserId);
if (auth.user) {
story.setUserContext(auth.user);
}
story.addImageId(imageId);
return story.save();
},
/**
*
*/
storyPrimaryImage: async (root, { storyId, imageId }, { auth }) => {
const story = await Story.strictFindActiveById(storyId);
auth.checkAdvertiserAccess(story.advertiserId);
story.primaryImageId = imageId || undefined;
if (auth.user) {
story.setUserContext(auth.user);
}
return story.save();
},
/**
*
*/
storyTitle: async (root, { id, value }, { auth }) => {
const story = await Story.strictFindActiveById(id);
auth.checkAdvertiserAccess(story.advertiserId);
if (auth.user) {
story.setUserContext(auth.user);
}
if (story.placeholder === true) {
story.placeholder = false;
}
story.title = value;
return story.save();
},
/**
*
*/
storyTeaser: async (root, { id, value }, { auth }) => {
const story = await Story.strictFindActiveById(id);
auth.checkAdvertiserAccess(story.advertiserId);
if (auth.user) {
story.setUserContext(auth.user);
}
story.teaser = value;
return story.save();
},
/**
*
*/
storyBody: async (root, { id, value }, { auth }) => {
const story = await Story.strictFindActiveById(id);
auth.checkAdvertiserAccess(story.advertiserId);
if (auth.user) {
story.setUserContext(auth.user);
}
story.body = value;
return story.save();
},
/**
*
*/
storyPublishedAt: async (root, { id, value }, { auth }) => {
const story = await Story.strictFindActiveById(id);
auth.checkAdvertiserAccess(story.advertiserId);
if (value) {
['title', 'body', 'primaryImageId'].forEach((key) => {
if (!story.get(key)) {
throw new Error(`You must set the story's ${key} before publishing.`);
}
});
}
if (auth.user) {
story.setUserContext(auth.user);
}
story.publishedAt = value;
return story.save();
},
},
};
|
import {useRouter} from "next/router";
import { getAllFilesData, getAllFilesId } from "../lib/folder";
import { getFile } from "../lib/file";
import Layout from "../components/layout";
import Hero from "../components/hero";
import PostList from "../components/post-list";
import ServiceList from "../components/service-list" ;
import ProjectList from "../components/project-list" ;
export default function Home({ allPostsData, pageData, allProjectsData, filesID }) {
const {locale} = useRouter();
console.log(filesID);
return (
<Layout url="/" title={pageData.title}>
<div>
<Hero image={pageData.image}>
<h1 className="mb-2">{pageData.heading}</h1>
<p className="text-lg">{pageData.subheading}</p>
</Hero>
<ServiceList
items={pageData.services}
>
<h2>Services</h2>
</ServiceList>
<PostList
items={allPostsData}
limit={2}
>
<h2>
{locale == "fr" ? "Derniers articles" : "Latest posts"}
</h2>
</PostList>
<ProjectList
items={allProjectsData}
limit={4}
>
<h2>
{locale == "fr" ? "Derniers projets" : "Latest projects"}
</h2>
</ProjectList>
</div>
</Layout>
);
}
export async function getStaticProps({ locale }) {
const allPostsData = await getAllFilesData("posts", locale);
const allProjectsData = await getAllFilesData("projects", locale);
const pageData = await getFile("pages", "home", locale);
const filesID = await getAllFilesId("posts", locale);
return {
props: {
allPostsData,
pageData,
allProjectsData,
filesID
},
};
}
|
function search(arr,low,high) {
if (low > high)
return;
if (low==high)
{
console.log("The required element is %d ", arr[low]);
return;
}
// Find the middle point
let mid = (low + high) / 2;
if (mid%2 == 0) {
if (arr[mid] == arr[mid+1])
search(arr, mid+2, high);
else
search(arr, low, mid);
} else {
if (arr[mid] == arr[mid-1])
search(arr, mid+1, high);
else
search(arr, low, mid-1);
}
}
Input: search([1,1,2,2,6,8,8,99,99,100,100],0,10)
Output: 6
2.
Object.values(data.reduce((acc, obj)=>{
let key1 = obj.name.toString();
acc[key1] = acc[key1] || { name: key1, value : []};
acc[key1].value.push(obj.value);
return acc;
},{})).each(obj => obj.value = obj.value.join(',') );
Input = [
{name: "tracker_id", value: "16"},
{name: "tracker_view_id", value: "9"},
{name: "data[322][]", value: "Choice1"},
{name: "data[322][]", value: "Choice2"},
{name: "data[326]", value: "03/09/2019"},
{name: "data[335]", value: "Choice2"},
{name: "data[335]", value: "Choice3"},
{name: "data[335]", value: "5555553"},
{name: "data[444]", value: "25540:Ruby"},
{name: "data[330]", value: "Choice4"},
{name: "data[331]", value: "2000"},
{name: "data[327]", value: "48:First last,57:Manthan K Patel1"},
{name: "data[320]", value: "126:Idea Management Team"},
{name: "data[441]", value: "18/09/2019"},
{name: "data[441]", value: ""},
{name: "data[441]", value: "Testing Title"},
{name: "data[96]", value: "tetw"},
]
Output = [
{name: "tracker_id", value: "16"}
{name: "tracker_view_id", value: "9"}
{name: "data[322][]", value: "Choice1,Choice2"}
{name: "data[326]", value: "03/09/2019"}
{name: "data[335]", value: "Choice2,Choice3,5555553"}
{name: "data[444]", value: "25540:Ruby"}
{name: "data[330]", value: "Choice4"}
{name: "data[331]", value: "2000"}
{name: "data[327]", value: "48:First last,57:Manthan K Patel1"}
{name: "data[320]", value: "126:Idea Management Team"}
{name: "data[441]", value: "18/09/2019,,Testing Title"}
{name: "data[96]", value: "tetw"}
]
/**
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
**/
var twoSum = function(nums, target) {
let hashMap = {};
for(let index=0; index < nums; index++) {
if(hashMap[nums[index]] !== undefined) return (hashMap[nums[index]], index);
hashMap[target - nums[index]] = index; // store index as value. and target - current number as a key.
}
};
|
import configureStore from './';
describe('Store Valid Test', () => {
const store = configureStore;
test('Store should be a valid object', () => {
expect(typeof store).toBe('object');
});
test('Store must have a dispatch function', () => {
expect(typeof store.dispatch).toBe('function');
});
test('Store must have a subscribe function', () => {
expect(typeof store.subscribe).toBe('function');
});
});
|
import { createStore, applyMiddleware, combineReducers } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension/developmentOnly';
import thunk from 'redux-thunk';
import logger from 'redux-logger';
import createSagaMiddleware from 'redux-saga';
import rootSaga from '../sagas/index';
import { registerReducer } from './reducers/registerReducer';
import { loginReducer } from './reducers/loginReducer';
import { createProjectReducer, deleteProjectReducer, fetchProjectsReducer, getSingleProjectReducer, updateProjectReducer } from './reducers/projectReducer';
import { getAllUsersReducer, getOneUserReducer } from './reducers/users';
import { createTaskReducer, getTaskReducer } from './reducers/task';
export default function configureStore() {
const sagaMiddleware = createSagaMiddleware();
const store = createStore(
combineReducers({
taskcreate: createTaskReducer,
tasks: getTaskReducer,
reg: registerReducer,
log: loginReducer,
users: getAllUsersReducer,
user: getOneUserReducer,
create: createProjectReducer,
projects: fetchProjectsReducer,
update: updateProjectReducer,
delete: deleteProjectReducer,
oneProj: getSingleProjectReducer
}),
composeWithDevTools(applyMiddleware(sagaMiddleware, thunk, logger))
);
console.log('single user');
sagaMiddleware.run(rootSaga);
return store;
}
|
const { remote, ipcRenderer } = require('electron')
const menuArrow = document.getElementById('menu-arrow')
, menuShield = document.getElementById('menu-shield')
, menuShieldDiv = menuShield.querySelector('div')
, body = document.body
ipcRenderer.on('menu-focused', e =>
{
document.addEventListener('keydown', handleKeyNav, false)
body.classList.remove('blurred')
body.classList.add('focused')
})
ipcRenderer.on('menu-blurred', e =>
{
document.removeEventListener('keydown', handleKeyNav, false)
body.classList.remove('focused')
body.classList.add('blurred')
})
ipcRenderer.on('menu-showlayer', ( e, showBkgd ) =>
{
if( showBkgd )
body.classList.add('show-bkgd')
else
body.classList.remove('show-bkgd')
})
ipcRenderer.on('menu-setup', ( e, props ) =>
{
body.classList.add('menu-ready')
body.classList.remove('reversed')
if( props.direction === 'down' )
body.classList.add('reversed')
menuArrow.removeAttribute('style')
menuArrow.style.left = props.arrow + 'px'
menuShield.removeAttribute('style')
menuShield.style.cssText = 'flex: 0 0 '+props.shieldHeight+'px'
menuShieldDiv.removeAttribute('style')
menuShieldDiv.style.cssText = 'width: '+props.shieldWidth+'px; height: '+props.shieldHeight+'px; left: '+props.shieldLeft+'px'
var createNode = html => new DOMParser().parseFromString(html, 'text/html').body.firstChild
, listElm = document.querySelector('.menu__list__inner ul')
, list = document.createDocumentFragment()
, rand = (max, min) => Math.random() * (max - min) + min
, i = 0
, item = null
for ( i; i < rand(2, 9); i++ ) {
item = createNode(`
<li class="menu__list__item">
<div>
<span class="menu__list__label">label ${i+1}</span>
</div>
</li>
`)
list.appendChild(item)
}
listElm.innerHTML = ''
listElm.appendChild(list)
})
menuShieldDiv.addEventListener('click', e =>
{
console.log('click shield')
ipcRenderer.send('menu-close')
})
const handleKeyNav = e =>
{
// e.preventDefault()
// e.stopPropagation()
// tab
if( e.keyCode === 9 )
return ipcRenderer.send('menu-close', 'tab')
// esc
if( e.keyCode === 27 )
{
// H-CASE
e.preventDefault()
e.stopPropagation()
return ipcRenderer.send('menu-close', 'esc')
}
}
// based on 'Electron click through transparency example'
// https://gist.github.com/StickyCube/ed79421bc53cba38f5b74b060d3f15fa
const getEventModifiers = evt => [
{ field: 'ctrlKey', name: 'control' }
, { field: 'shiftKey', name: 'shift' }
, { field: 'altKey', name: 'alt' }
, { field: 'metaKey', name: 'meta' }
].filter(elm => evt[elm.field]).map(elm => elm.name)
const getEventButton = evt =>
{
switch( evt.button )
{
case 2: return 'right'
case 1: return 'middle'
case 0:
default: return 'left'
}
}
window.onEvent = function (type, e)
{
var target = e.target
if( !target.dataset || !target.dataset.clickable )
return
var _event = {
type
, modifiers: getEventModifiers(e)
, button: getEventButton(e)
, x: e.clientX
, y: e.clientY
, globalX: e.screenX
, globalY: e.screenY
, movementX: e.movementX
, movementY: e.movementY
, clickCount: e.detail
}
if( type === 'mouseWheel' )
_event = Object.assign( _event, {
deltaX: e.deltaX
, deltaY: e.deltaY
})
return ipcRenderer.send('ClickableRegion::mouse-event', _event )
}
body.addEventListener('mouseup', e => onEvent('mouseUp', e), false )
body.addEventListener('mousedown', e => onEvent('mouseDown', e), false )
body.addEventListener('mouseenter', e => onEvent('mouseEnter', e), false )
body.addEventListener('mouseleave', e => onEvent('mouseLeave', e), false )
body.addEventListener('mousemove', e => onEvent('mouseMove', e), false )
body.addEventListener('mousewheel', e => onEvent('mouseWheel', e), false )
|
'use strict';
import {menuIsOpen} from "../header-nav/header-nav";
const EVENTS = require('./../../common/scripts/constants/EVENTS');
const block = 'login-button';
$(document).ready(function () {
const $block = $('.' + block);
$block.on(EVENTS.ELEMENT.CLICK, function () {
if(menuIsOpen()){
$(document).trigger(EVENTS.CUSTOM.POPUP_MENU.CLOSED);
}
$(document).trigger(EVENTS.CUSTOM.LOGIN_POPUP.OPENED)
});
});
|
import React, { useState, useEffect, useContext, createContext } from 'react'
import { gql, useMutation, useQuery } from '@apollo/client'
import PropTypes from 'prop-types'
import { useRouter } from 'next/router'
const GET_CURRENT_USER = gql`
query getCurrentUser {
getCurrentUser {
id
username
role
firstName
lastName
imageUrl
}
}
`
const LOGOUT = gql`
mutation logout {
logout {
message
}
}
`
const authContext = createContext()
// Provider hook that creates auth object and handles state
function useProvideAuth() {
const [user, setUser] = useState(null)
const [sendLogout] = useMutation(LOGOUT)
const router = useRouter()
const {
data,
loading,
error,
refetch,
networkStatus
} = useQuery(GET_CURRENT_USER, { notifyOnNetworkStatusChange: true })
useEffect(() => {
if (!loading && data && data.getCurrentUser) {
setUser(data.getCurrentUser)
}
}, [data, loading, error, networkStatus])
function fetchUser() {
refetch()
}
function logout() {
sendLogout()
localStorage.removeItem('clientToken')
setUser(null)
router.push('/login')
}
function checkUserIsLoggedIn() {
return localStorage.getItem('clientToken') !== null
}
// Return the user object and auth methods
return {
user,
checkUserIsLoggedIn,
fetchUser,
logout
}
}
// Provider component that wraps your app and makes auth object ...
// ... available to any child component that calls useAuth().
export function ProvideAuth({ children }) {
const auth = useProvideAuth()
return <authContext.Provider value={auth}>{children}</authContext.Provider>
}
// Hook for child components to get the auth object ...
// ... and re-render when it changes.
export const useAuth = () => useContext(authContext)
ProvideAuth.propTypes = {
children: PropTypes.node.isRequired
}
|
import * as qz from 'qz-tray';
import { sha256 } from 'js-sha256';
////// Qz-tray --> used for printing to any type of printer.
////// ----------> https://qz.io/wiki/2.0-getting-started
qz.api.setSha256Type(data => sha256(data));
qz.api.setPromiseType(resolver => new Promise(resolver));
qz.websocket.connect().then(function() {
return qz.printers.find("PDFwriter"); // Pass the printer name into the next Promise
}).then(function(printer) {
let config = qz.configs.create(printer); // Create a default config for the found printer
let data = [
'Grozeries Delivery\n',
'Persons Name\n',
'Redacted 34\n',
'Postcode Cityname\n'
]
return qz.print(config, data);
}).catch(function(e) { console.error(e); });
|
let readlinesync= require("readline-sync");
let chalk= require('chalk');
const userName = readlinesync.question("May I know your name? ");
const cl = console.log;
cl(`Hey ${userName}, let's find out if you know Aditya or not.`)
let score = 0;
const questions = [
{
question: "Aditya's favourite netflix show?",
options: `\n 1. Master of None \n 2. Chernobyl \n 3. Rick and Morty`,
answer: "Master of None"
},
{
question: "Dogs, cats or babies?",
options: `\n 1. Babies \n 2. Cat \n 3. Dogs`,
answer: "Dogs"
},
{
question: "The video game he plays the most: ",
options: `\n 1. PUBG \n 2. NFS Most Wanted \n 3. Valorant`,
answer: "Valorant"
},
{
question: "Does Aditya share food?",
options: `\n 1. Yep \n 2. Nope \n 3. Big No`,
answer: "Big No"
},
{
question: "His favourite book?",
options: `\n 1. Rich Dad Poor Dad \n 2. Subtle art of not giving a fuck \n 3. Tools of Titans`,
answer: "Subtle art of not giving a fuck"
},
{
question: "Did he ever tried to skateboard and failed? ",
options: `\n 1. Nope \n 2. Yep \n 3. He didn't fail`,
answer: "He didn't fail"
},
{
question: "That one hill station he went multiple times in college:",
options: `\n 1. Shimla \n 2. Mussoorie \n 3. Kodaikenal`,
answer: "Mussoorie"
},
{
question: "Where is he currently working at?",
options: `\n 1. Zeda.io \n 2. Niyo Solutions \n 3. VibeCheck`,
answer: "Zeda.io"
},
{
question: "How much does he wants to get into NeogCamp?",
options: `\n 1. Okaishly \n 2. Pretty much \n 3. Dinosaur big`,
answer: "Dinosaur big"
},
{
question: "Is he a frontend or a backend heavy dev?",
options: `\n 1. Frontend \n 2. Backend \n 3. Android`,
answer: "Frontend"
}
]
//Level 0 will have 5 questions, if score is greater than 1, pass on to next Level
let level= 1;
// game loop
for(let i = 0; i< questions.length; i++){
if(i === 5){
cl(chalk`\n{yellow ------------------------------------}\n`);
cl(chalk`{yellow ------------------------------------}\n`);
cl(`\nLevel 1 Score: ${score} correct out of 5`);
if(score < 1){
cl(chalk`Your score is not enough to qualify to the next level\n\n TRY AGAIN 😉 .`);
cl(chalk`\n{yellow ------------------------------------}\n`);
cl(chalk`{yellow ------------------------------------}\n`);
break;
}
cl(chalk`\nYay! You made it to level 2`);
level++;
cl(chalk`\n{bold {underline LEVEL ${level}}}`);
}
cl(chalk`\n {yellow ------------------------------------} \n`);
cl(chalk`{bgWhite {black Question ${i+1}}}. ${questions[i].question}`);
cl(questions[i].options + '\n');
const answer= readlinesync.question("Your Answer: ");
if(answer.toLowerCase() === questions[i].answer.toLowerCase()){
cl("TRUE THAT");
score++;
} else{
cl("NOPE");
}
cl(`Current Score: ${score}`)
}
cl(chalk`\n{yellow ------------------------------------} \n`);
cl(chalk`{yellow ------------------------------------} \n`);
cl(chalk`{bold Quiz over}, your final score: ${score}`);
|
let box = document.getElementById('box');
box.style.backgroundColor = 'yellow'
|
'use strict'
const vbTemplate = require('claudia-bot-builder').viberTemplate
module.exports = function startMenu(text) {
return new vbTemplate.Text(text || `Hello this is Space Explorer, what would you like me to do:`)
.addReplyKeyboard(true)
.addKeyboardButton(`<font color="#FFFFFF"><b>Astronomy Picture of the Day</b></font>`, 'APOD', 3, 2, {
TextSize: 'large',
BgColor: '#000000',
BgMediaType: 'picture',
BgMedia: 'https://raw.githubusercontent.com/stojanovic/space-explorer-bot-viber/master/images/galaxy.jpeg'
})
.addKeyboardButton(`<font color="#FFFFFF"><b>Photos from Rovers on Mars</b></font>`, 'Mars Rovers', 3, 2, {
TextSize: 'large',
BgColor: '#000000',
BgMediaType: 'picture',
BgMedia: 'https://raw.githubusercontent.com/stojanovic/space-explorer-bot-viber/master/images/curiosity.jpg'
})
.addKeyboardButton(`<font color="#FFFFFF"><b>Where is the ISS now?</b></font>`, 'ISS', 3, 2, {
TextSize: 'large',
BgColor: '#000000',
BgMediaType: 'picture',
BgMedia: 'https://raw.githubusercontent.com/stojanovic/space-explorer-bot-viber/master/images/iss.jpg'
})
.addKeyboardButton(`<font color="#FFFFFF"><b>How many people are in space right now?</b></font>`, 'People in Space', 3, 2, {
TextSize: 'large',
BgColor: '#000000',
BgMediaType: 'picture',
BgMedia: 'https://raw.githubusercontent.com/stojanovic/space-explorer-bot-viber/master/images/space-people.jpg'
})
.addKeyboardButton(`<font color="#FFFFFF"><b>What about me, your space bot?</b></font>`, 'About', 6, 1, {
TextSize: 'large',
BgColor: '#000000',
BgMediaType: 'picture'
//BgMedia: 'https://raw.githubusercontent.com/stojanovic/space-explorer-bot-viber/master/images/claudia-chatbot.png'
})
.get()
}
|
import React from "react";
import Card from "@material-ui/core/Card";
import CardContent from "@material-ui/core/CardContent";
import CardActions from "@material-ui/core/CardActions";
import Button from "@material-ui/core/Button";
const ApprovalCard = props => {
const handleApprove = () => {
alert("Accepted");
};
const handleReject = () => {
alert("Rejected");
};
return (
<div>
<Card className="mt-1">
<CardContent>{props.children}</CardContent>
<CardActions>
<Button onClick={handleApprove} size="small" color="primary">
Approve
</Button>
<Button onClick={handleReject} size="small" color="secondary">
Reject
</Button>
</CardActions>
</Card>
</div>
);
};
export default ApprovalCard;
|
import React from "react";
// props.children refers to <Container> this stuff here </Container> between the tags
export default (props) => (
<div style={{margin: "3em auto", maxWidth: 600}}>
{ props.children }
</div>
);
|
import React, { Component } from "react";
const PlayerHand = ({ cards }) => {
let handCards = cards.map((card, index) => (
<div key={index} className="card">
{card}
</div>
));
return <div className="player-hand">{handCards}</div>;
};
export default class UI extends Component {
render() {
return (
<div className="game-wrapper">
<div className="lp-wrapper">
<span>
{this.props.G.players[0].hp} LP / {this.props.G.players[0].mana} MP
</span>
<span>
{this.props.G.players[1].hp} LP / {this.props.G.players[1].mana} MP
</span>
</div>
<div>Player 1 Hand</div>
<div className="zones">
<div className="decks">
<div>Player 1 ExtraDeck</div>
<div>Player 0 ExtraDeck</div>
</div>
<div className="field">
<div>Player 1 Board</div>
<div>Phases</div>
<div>Player 0 Board</div>
</div>
<div className="decks">
<div>Player 1 Deck</div>
<div onClick={() => this.props.moves.drawCard(0)} className="card">
{this.props.G.players[0].deck.length}
</div>
</div>
</div>
<PlayerHand cards={this.props.G.players[0].hand} />
</div>
);
}
}
|
/**
* Created by bqthong on 8/2/2016.
*/
(function () {
'use strict';
angular.module('mod.table',[])
.directive('tableDirective', function () {
return {
restrict: 'AE',
scope: {
data: '=',
columns: '=?',
columnsTable: '=?',
selectedList: '=?',
tplDetail: '=?'
},
templateUrl: 'component/table/template/table.template.html',
link: function (scope, element, attrs) {
scope.detailTemplateBody = scope.tplDetail;
var bodyView = element.find('.body-view');
var detailView = element.find('.detail-view');
scope.detailTemplate = 'component/table/template/table-detail.template.html';
// Show detail view
function showDetailView() {
scope.hideDetail = false;
bodyView.addClass('col-md-6');
detailView.addClass('col-md-6');
}
// Hide detail view
scope.hideDetailView = function() {
scope.hideDetail = true;
bodyView.removeClass('col-md-6');
detailView.removeClass('col-md-6');
};
// Check single select to show detail view
scope.checkSingleSelect = function () {
return scope.selectedList.length === 1;
};
// Select check box
scope.selectCheckbox = function (item) {
for(var i=0;i<scope.selectedList.length;i++){
if(scope.selectedList[i].id === item.id) {
return true;
}
}
};
// Select all check box
scope.selectAllCheckbox = function () {
if(scope.data.length === scope.selectedList.length){
return true;
}
};
// Check all check box
scope.checkAll = function () {
if(scope.selectAllCheckbox()){
scope.hideDetailView();
scope.selectedList.splice(0, scope.selectedList.length);
}
else {
scope.hideDetailView();
scope.selectedList.splice(0, scope.selectedList.length);
for(var i = 0; i < scope.data.length; i++){
scope.data[i].selected = true;
scope.selectedList.push( scope.data[i]);
}
}
};
// Click on row to select single item
scope.clickItem = function (item) {
item.selected = true;
scope.selectedList.splice(0, scope.selectedList.length);
scope.selectedList.push(item);
showDetailView();
};
// Click on check box to select multiple item
scope.clickMultipleItem = function (item) {
var index = -1;
for(var i = 0;i < scope.selectedList.length;i++){
if(angular.equals(scope.selectedList[i],item)){
index = i;
break;
}
}
if(index < 0){
scope.hideDetailView();
item.selected = true;
scope.selectedList.push(item);
}
else {
scope.hideDetailView();
scope.selectedList.splice(index,1);
}
if(scope.checkSingleSelect()){
showDetailView();
}
};
// Sort by column
scope.sortType = function (valueSort) {
if (scope.valueSort === valueSort) {
scope.sortReverse = !scope.sortReverse;
} else {
scope.sortReverse = false;
}
scope.valueSort = valueSort;
};
scope.$on('hideDetailView',function(event, data){
scope.hideDetailView();
});
}
}
})
})();
|
import React, { useEffect } from "react";
import { connect } from "react-redux";
import { push } from "connected-react-router";
export default function(ComposedComponent) {
const Authenticate = props => {
const _isAuthenticated = () => {
const token = localStorage.getItem("token");
return Boolean(token);
// TODO: we need to verify the token
};
useEffect(() => {
const _checkAndRedirect = () => {
const { redirect } = props;
const isAuthenticated = _isAuthenticated();
if (!isAuthenticated) {
redirect();
}
};
_checkAndRedirect();
}, [props]);
const isAuthenticated = _isAuthenticated();
return (
<div>{isAuthenticated ? <ComposedComponent {...props} /> : null}</div>
);
};
const mapDispatchToProps = dispatch => {
return {
redirect: () => dispatch(push("/auth/login"))
};
};
return connect(
null,
mapDispatchToProps
)(Authenticate);
}
|
import createReducer from '../utils/createReducer'
import { BooksEndpoints } from '../../api'
// Types
export const GET_BOOKS_REQUEST = '[books] GET_BOOKS / REQUEST'
export const GET_BOOKS_SUCCESS = '[books] GET_BOOKS / SUCCESS'
// Initial State
const initialState = {
items: []
}
// Reducer
export default createReducer(initialState)({
[GET_BOOKS_SUCCESS]: (state, action) => ({
...state,
items: action.payload.books
})
})
// Actions
export const getBooks = () => async dispatch => {
try {
dispatch(getBooksRequest())
const response = await BooksEndpoints.getBooks()
dispatch(getBooksSuccess(response.data))
} catch (error) {
console.log(`Error occured on ${getBooksRequest().type}`)
}
}
export const getBooksRequest = () => ({ type: GET_BOOKS_REQUEST })
export const getBooksSuccess = books => ({
type: GET_BOOKS_SUCCESS,
payload: { books }
})
|
const getDataBase = require('../database.js');
const db = getDataBase();
const express = require('express');
const router = express.Router();
// GET /hamsters
router.get('/', async (req, res) => {
try {
const hamstersRef = db.collection('hamsters');
const snapshot = await hamstersRef.get();
if(snapshot.empty) {
res.send(404).send('Oh no! No hamsters to be found.');
return;
}
hamsterList = []
snapshot.forEach(doc => {
const data = doc.data()
data.id = doc.id
hamsterList.push(data)
})
res.status(200).send(hamsterList);
} catch(error) {
res.status(500).send('Oops! Something went wrong... ' + error.message);
}
});
// GET /hamsters/random
router.get('/random', async (req, res) => {
try {
const hamstersRef = db.collection('hamsters');
const snapshot = await hamstersRef.get();
if(snapshot.empty) {
res.send(404).send('Oh no! No hamsters to be found.');
return;
}
hamsterList = []
snapshot.forEach(doc => {
const data = doc.data();
data.id = doc.id;
hamsterList.push(data);
})
res.status(200).send(hamsterList[Math.floor(Math.random()*hamsterList.length)]);
} catch(error) {
res.status(500).send('Oops! Something went wrong... ' + error.message);
}
});
// GET /hamsters/:id
router.get('/:id', async (req, res) => {
try {
const id = req.params.id;
const hamsterRef = await db.collection('hamsters').doc(id).get();
if(!hamsterRef.exists) {
res.status(404).send(`Oh no! Hamster with id:${id} does not exist.`);
return;
}
const data = hamsterRef.data();
res.status(200).send(data);
} catch(error) {
res.status(500).send('Oops! Something went wrong... ' + error.message);
}
});
// POST /hamsters
router.post('/', async (req, res) => {
try {
const newHamsterObject = req.body;
if(!isObject(newHamsterObject)) {
res.sendStatus(400);
return
}
const docRef = await db.collection('hamsters').add(newHamsterObject);
const newHamsterObjId = { id: docRef.id };
res.status(200).send(newHamsterObjId);
} catch(error) {
res.status(500).send('Oops! Something went wrong... ' + error.message);
}
});
function isObject(hamsterObject) {
if(hamsterObject && ['name', 'age', 'favFood', 'loves', 'imgName', 'wins', 'defeats', 'games'].every(p => hamsterObject.hasOwnProperty(p))) {
if(!Number.isInteger(hamsterObject.age) || hamsterObject.age < 0) return false;
if(!Number.isInteger(hamsterObject.wins) || hamsterObject.wins < 0) return false;
if(!Number.isInteger(hamsterObject.defeats) || hamsterObject.defeats < 0) return false;
if(!Number.isInteger(hamsterObject.games) || hamsterObject.games < 0) return false;
return true;
}
return false;
};
// PUT /hamsters/:id
router.put('/:id', async (req, res) => {
try {
const hamsterObject = req.body;
const id = req.params.id;
const hamsterRef = await db.collection('hamsters').doc(id).get();
if(!hamsterObject || !id) {
res.sendStatus(400);
return;
}
if(!hamsterRef.exists) {
res.status(404).send('Oh no! Hamster does not exist.');
return;
}
const docRef = db.collection('hamsters').doc(id);
await docRef.set(hamsterObject, { merge: true });
if(Object.keys(hamsterObject).length === 0) {
res.sendStatus(400);
return;
}
res.sendStatus(200);
} catch(error) {
res.status(500).send('Oops! Something went wrong... ' + error.message);
}
});
// DELETE /hamsters/:id
router.delete('/:id', async (req, res) => {
try {
const id = req.params.id;
const hamsterRef = await db.collection('hamsters').doc(id).get();
if(!id) {
res.sendStatus(400);
return;
}
if(!hamsterRef.exists) {
res.status(404).send('Oh no! Hamster does not exist.');
return;
}
await db.collection('hamsters').doc(id).delete();
res.sendStatus(200);
} catch(error) {
res.status(500).send('Oops! Something went wrong... ' + error.message);
}
});
module.exports = router;
|
export default {
uid: "",
firstName: "",
lastName: "",
email: "",
loggedIn: false
};
|
var terrain = ( function () {
'use strict';
var u = {
size : 100,
height : 20,
resolution : 256,
complexity : 2,
type : 1,
fog: 1,
fogStart : 0.5,
};
var maxspeed = 1;
var acc = 0.01;
var dec = 0.01;
var pos, ease;
var material = null;
var mesh = null;
var compute = null;
var uniforms_terrain = null;
var uniforms_height = null;
var heightmapVariable;
var heightTexture = null;
terrain = {
getData : function () {
return u;
},
init : function ( o ) {
pos = new THREE.Vector3();
ease = new THREE.Vector2();
pool.load( ['glsl/terrain_la_vs.glsl', 'glsl/terrain_la_fs.glsl', 'glsl/noiseMap.glsl'], terrain.create );
},
create : function () {
terrain.makeHeightTexture();
//var tx = new THREE.Texture( pool.get( 'diffuse1' ) );
//tx.wrapS = tx.wrapT = THREE.RepeatWrapping;
//tx.repeat.set( 100, 100 );
//tx.anisotropy = 4;
//tx.needsUpdate = true;
var uniformPlus = {
size: { value: u.size },
height: { value: u.height },
resolution: { value: u.resolution },
heightmap: { value: null },
enableFog: { value: null },
fogColor: { value: null },
fogStart: { value: null },
grass: { value: null },
};
material = new THREE.ShaderMaterial( {
uniforms: THREE.UniformsUtils.merge( [ THREE.ShaderLib[ 'lambert' ].uniforms, uniformPlus ] ),
vertexShader: pool.get( 'terrain_la_vs' ),
fragmentShader: pool.get( 'terrain_la_fs' ),
});
material.lights = true;
material.map = null;
uniforms_terrain = material.uniforms;
//uniforms_terrain.grass.value = tx;
uniforms_terrain.heightmap.value = heightTexture.texture;
uniforms_terrain.enableFog.value = u.fog;
uniforms_terrain.fogStart.value = u.fogStart;
uniforms_terrain.fogColor.value = new THREE.Color(0x2c2c26);
var geometry = new THREE.PlaneBufferGeometry( u.size, u.size, u.resolution - 1, u.resolution -1 );
geometry.rotateX( -Math.PI / 2 );
mesh = new THREE.Mesh( geometry, material );
mesh.matrixAutoUpdate = false;
//mesh.castShadow = true;
//mesh.receiveShadow = true;
//mesh.updateMatrix();
view.add( mesh );
view.addUpdate( terrain.easing );
},
makeHeightTexture : function(){
compute = new GPUComputationRenderer( u.resolution, u.resolution, view.getRenderer() );
heightmapVariable = compute.addVariable( "heightmap", pool.get( 'noiseMap' ), compute.createTexture() );
compute.init();
uniforms_height = heightmapVariable.material.uniforms;
uniforms_height.pos = { value: 0 };;
uniforms_height.size = { value: 0 };
uniforms_height.resolution = { value: 0 };
uniforms_height.type = { value: 0 };
uniforms_height.complexity = { value: 0 };
uniforms_height.pos.value = pos;
uniforms_height.size.value = u.size;
uniforms_height.resolution.value = u.resolution;
uniforms_height.type.value = u.type;
uniforms_height.complexity.value = 1 / ( u.complexity * 100 );
compute.compute();
heightTexture = compute.getCurrentRenderTarget( heightmapVariable );
},
update: function () {
uniforms_height.pos.value = pos;
uniforms_height.type.value = u.type;
uniforms_height.size.value = u.size;
uniforms_height.resolution.value = u.resolution;
uniforms_height.complexity.value = 1 / ( u.complexity * 100 );
uniforms_terrain.size.value = u.size;
uniforms_terrain.resolution.value = u.resolution;
uniforms_terrain.height.value = u.height;
uniforms_terrain.enableFog.value = u.fog;
uniforms_terrain.fogStart.value = u.fogStart;
compute.compute();
},
getHeight: function ( x, y ) {
if(!heightTexture) return 0;
var r = view.getPixel( heightTexture, x || u.resolution*0.5, y || u.resolution*0.5 );
return r[ 0 ] * u.height;
},
easing: function () {
var key = user.getKey();
var r = -view.getControls().getAzimuthalAngle();
if(key[7]) maxspeed = 1.5;
else maxspeed = 0.25;
//acceleration
ease.y += key[1] * acc; // up down
ease.x += key[0] * acc; // left right
//speed limite
ease.x = ease.x > maxspeed ? maxspeed : ease.x;
ease.x = ease.x < -maxspeed ? -maxspeed : ease.x;
ease.y = ease.y > maxspeed ? maxspeed : ease.y;
ease.y = ease.y < -maxspeed ? -maxspeed : ease.y;
//break
if (!key[1]) {
if (ease.y > dec) ease.y -= dec;
else if (ease.y < -dec) ease.y += dec;
else ease.y = 0;
}
if (!key[0]) {
if (ease.x > dec) ease.x -= dec;
else if (ease.x < -dec) ease.x += dec;
else ease.x = 0;
}
//debug(Math.floor(r*57.295779513082320876) + '__x:' + pos.x + '__z:'+pos.z)
if ( !ease.x && !ease.y ) return;
pos.z += Math.sin(r) * ease.x + Math.cos(r) * ease.y;
pos.x += Math.cos(r) * ease.x - Math.sin(r) * ease.y;
terrain.update();
},
}
return terrain;
})();
|
export function getEmployeesById(db, id, cb) {
const Employees = new db.models.Employees();
return Employees.query({where: {'user_id': id}})
.fetch()
.then(function (collection) {
return cb(null, collection.toJSON());
})
.otherwise(function (err) {
return cb(err, null);
});
}
export function addEmployeeToUser(db, payload, cb) {
const Employee = db.models.Employee;
Employee.forge({
name: payload.employee.name,
user_id: payload.user.id
}).save()
.then(function (employee) {
cb(null, employee);
})
.otherwise(function (err) {
cb(err, null);
});
}
export function deleteEmployee(db, id, cb) {
const Employee = db.models.Employee;
Employee.forge({id: id})
.fetch({require: true})
.then(function (employee) {
employee.destroy().then(function () {
cb(null);
});
})
.otherwise(function (err) {
cb(err);
});
}
export function updateEmployee(db, payload, cb) {
const Employee = db.models.Employee;
Employee.forge({id: payload.employeeId})
.fetch({require: true})
.then(function (employee) {
employee.set({name: payload.employee.name}).save()
.then(function (savedEmployee) {
cb(null, savedEmployee);
})
.otherwise(function (err) {
cb(err, null);
});
});
}
|
define(['angular'], function(angular){
var module = angular.module('Avatar', [])
.directive('avatar', avatarDirective);
avatarDirective.$inject = [];
function avatarDirective() {
var colorMapping = {};
return {
restrict: "E",
replace: true,
scope: {
user: "="
},
templateUrl: 'assets/javascripts/chat/avatar/avatarTpl.html',
link: function($scope) {
// http://stackoverflow.com/questions/1484506/random-color-generator-in-javascript
function randomColor() {
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
var unwatch = $scope.$watch("user", function(user) {
console.log("user", user);
if (user != null && typeof (user.name) != 'undefined' ) {
$scope.initials = (user.name[0] || "A");
if (!colorMapping[user.id]) colorMapping[user.id] = randomColor();
$scope.color = colorMapping[user.id];
unwatch();
}
});
}
};
}
return module;
});
|
'use strict'
var _ = require('./util')
/**
* API返回结果的固定格式和默认值
* @type {{success: boolean, message: string, count: number, data: Array}}
* success 返回结果
* message 消息
* count 纪录总数,仅在分页查询时使用,不表示data的长度
* data 返回的结果集
*/
var result_default = {
success: false,
message: null,
count: 0,
data: []
}
/**
* 返回成功的RESULT
* @param params string|array|object
* @returns {*}
*/
var success = function (params) {
if (_.isString(params))
return _.extend({}, result_default, {success: true, message: params})
if (_.isArray(params))
return _.extend({}, result_default, {success: true, data: params})
return _.extend({}, result_default, params, {success: true}).pick('success', 'message', 'count', 'data')
}
/**
* 返回失败的RESULT
* @param params string|object
* @returns {*}
*/
var failure = function (params) {
if (_.isString(params))
return _.extend({}, result_default, {message: params})
return _.extend({}, result_default, params, {success: false}).pick('success', 'message', 'count', 'data')
}
module.exports = {
success: success,
failure: failure,
/**
* 保存成功
*/
SUCCESS_SAVE: success('保存成功'),
/**
* 删除成功
*/
SUCCESS_DELETE: success('删除成功'),
/**
* 保存失败
*/
FAILURE_SAVE: failure('保存失败'),
/**
* 查询失败
*/
FAILURE_QUERY: failure('查询失败'),
/**
* 删除失败
*/
FAILURE_DELETE: failure('删除失败')
}
|
var sample = {"type":"cpu","time":"123","re":"1"}
console.log(sample)
delete sample["type"];
console.log(sample);
var s = "1bcdE"
var re = s.indexOf('bc');
console.log(re);
//for key in keys:
// console.log(key)
|
let submitButtonClick = document.getElementById("submitButton");
let clearButtonClick = document.getElementById("clearButton");
console.log('TEST');
/*let formName = document.getElementById("name").value;
let formEmail = document.getElementById("email").value;
let formTel = document.getElementById("phone").value;
let formMessage = document.getElementById("messageText").value;
let formDataContent = [];*/
// console.log(submitButtonClick);
let formDataContent = [];
let submittedData = [];
const formData = function () {
let formName = document.getElementById("name").value;
let formEmail = document.getElementById("email").value;
let formTel = document.getElementById("phone").value;
let formMessage = document.getElementById("messageText").value;
if (formName != "") {
formDataContent.push("\n\tName: " + formName)
};
if (formEmail != "") {
formDataContent.push("\n\tEmail: " + formEmail)
};
if (formTel != "") {
formDataContent.push("\n\tPhone Number: " + formTel)
};
if (formMessage != "") {
formDataContent.push("\n\tYour message: " + formMessage)
};
alert("Your message has been submitted. Here's what you've submitted: \n" + formDataContent + "\nThis message is actually going somewhere. I promise.");
submittedData = formDataContent;
formDataContent = [];
};
const clearData = function() {formDataContent = [];};
submitButtonClick.addEventListener('click', formData, false);
clearButtonClick.addEventListener('click', clearData, false);
|
//jshint esversion:6
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
//console.log(req);
res.send("<h2 style = 'color: green'>Hello World!!!</h2>");
});
// app.get('/test', (req, res) => res.send('Hello World prime test'));
app.get('/contact', (req, res) => {
res.send("My contact:Sai@gmail.com");
});
app.get('/about', (req, res) => {
res.send("I am a java developer trying to become a fullstack developer and I am in to learning all the possible technologies for now. ⭐️");
});
app.get('/test', (req, res) => {
res.send("I am a java developer trying to become a fullstack developer and I am in to learning all the possible technologies for now. ⭐️");
});
// nodemod to observe change and restart server all time
app.get('/node1', (req, res) =>
res.send("I")
);
app.listen(port,() =>
console.log(`Example app listening on port ${port}!`));
|
(function($) {
$(document).ready(function() {
/***************************
* Variable
**************************/
var refreshInterval = 10;
var autoRefresh = true;
var inTransaction = false;
var toggle = false;
var autoRefreshLauncher;
/**************************************
* Preview and state
***************************************/
function getPreviewAndState(isLoader){
if(!inTransaction){
inTransaction = true;
if(isLoader){$('.preview-block').addClass("block-opt-refresh");}
$.ajax({
url: 'PreviewStateMachine',
type: 'POST',
dataType:'json',
data: $('.js-value-form').serialize(),
success: function (data) {
if(data.header.statut == "200"){
$("#vm-state-machine").empty();
$("#vm-state-machine").html("<i class=\"fa "+ data.data.state +" \" aria-hidden=\"true\"></i> "+ data.data.state );
if(data.data.preview == null){
$("#js-preview-img").attr("src","assets/img/photos/nosignal.jpg");
}else{
$("#js-preview-img").attr("src",data.data.preview);
}
$('.preview-block').removeClass("block-opt-refresh");
if(isLoader){notify("success","Preview updated!");}
inTransaction = false;
}else{
if(isLoader){notify('warning','Error ['+data.header.statut+'] getPreviewAndState');}
$('.preview-block').removeClass("block-opt-refresh");
inTransaction = false;
}
},
error: function (data) {
if(isLoader){notify('warning','Error ['+data.header.statut+'] getPreviewAndState');}
$('.preview-block').removeClass("block-opt-refresh");
inTransaction = false;
}
});
}
}
/**************************************
* Start and Stop
***************************************/
function startMachine(){
inTransaction = true;
$('.loader').show();
$.ajax({
url: 'StartMachine',
type: 'POST',
dataType:'json',
data: $('.js-value-form').serialize(),
success: function (data) {
inTransaction = false;
$('.loader').hide();
if(data.header.statut == "200"){
getPreviewAndState();
notify('success','Machine being started');
}else{
notify('danger','Error : ['+ data.header.statut +'] Machine not started !');
}
},
error: function (jqXHR, textStatus, errorThrown) {
inTransaction = false;
$('.loader').hide();
notify('danger','Error : '+ jqXHR.status+' ['+errorThrown+'] Machine not started !');
}
});
}
function stopMachine(){
inTransaction = true;
$('.loader').show();
$.ajax({
url: 'StopMachine',
type: 'POST',
dataType:'json',
data: $('#stop-machine-form').serialize(),
success: function (data) {
inTransaction = false;
jQuery('#stopMachine-modal').modal('hide');
$('.loader').hide();
if(data.header.statut == "200"){
getPreviewAndState();
notify('success','Machine being stopped');
}else{
notify('danger','Error : ['+ data.header.statut +'] Machine not started !');
}
},
error: function (jqXHR, textStatus, errorThrown) {
jQuery('#stopMachine-modal').modal('hide');
inTransaction = false;
$('.loader').hide();
notify('danger','Error : '+ jqXHR.status+' ['+errorThrown+'] Machine not stopped !');
}
});
}
/**************************************
* Delete and create
***************************************/
function deleteMachine(){
inTransaction = true;
$('.loader').show();
$.ajax({
url: 'DeleteMachine',
type: 'POST',
data: $('#delete-vm-form').serialize(),
success: function (data) {
inTransaction = false;
jQuery('#deleteMachine-modal').modal('hide');
notify('success','Machine deleted');
$('.loader').hide();
window.location.replace("index.jsp");
},
error: function (jqXHR, textStatus, errorThrown) {
inTransaction = false;
jQuery('#deleteMachine-modal').modal('hide');
notify('danger','Error : '+ jqXHR.status+' ['+errorThrown+'] Machine not deleted !');
$('.loader').hide();
}
});
}
/**************************************
* Configure
***************************************/
function configureMachine(){
inTransaction = true;
$('.loader').show();
$.ajax({
url: 'ConfigureMachine',
type: 'POST',
data: $('#cfg-vm-form').serialize(),
success: function (data) {
inTransaction = false;
$('.loader').hide();
jQuery('#configureMachine-modal').modal('hide');
notify('success','Settings saved !');
location.reload();
},
error: function (jqXHR, textStatus, errorThrown) {
inTransaction = false;
$('.loader').hide();
notify('danger','Error : '+ jqXHR.status+' ['+errorThrown+'] Settings not saved !');
}
});
}
/**************************************
* Storage
***************************************/
function showStorageTree(data){
$('.js-tree-storage').empty();
jQuery('.js-tree-storage').treeview({
data: data.data.storageTree,
color: '#555',
expandIcon: 'fa fa-plus',
collapseIcon: 'fa fa-minus',
nodeIcon: 'fa fa-hdd-o text-primary',
onhoverColor: '#f9f9f9',
selectedColor: '#555',
selectedBackColor: '#f1f1f1',
showBorder: false,
levels: 3,
onNodeSelected: function(event, data) {
showStorageInfos(data);
},
onNodeUnselected: function(event,data){
hideStorageInfos();
}
});
}
function getStorageTree(){
$('.loader-storage').show();
$.ajax({
url: 'ConfigureStorage',
type: 'POST',
dataType:'json',
data: $('.js-value-form').serialize()+"&fn=getStorageTree¶m=null",
success: function (data) {
$('.loader-storage').hide();
if(data.header.statut == "200"){
setControllerAvailable(data.data.controller);
showStorageTree(data);
}else{
notify('danger','Error : ['+ data.header.statut +'] getStorageTree');
}
},
error: function (jqXHR, textStatus, errorThrown) {
$('.loader-storage').hide();
notify('danger','Error : '+ jqXHR.status+' ['+errorThrown+'] getStorageTree');
}
});
}
function showStorageInfos(data){
var node = data.text.substring(0,3);
$('#storage-infos').empty();
if(node == "Con"){
$('#storage-infos').append("<h3 id=\"controllerName\">"+data.text.substring(13) +"<h3><br>");
$('#storage-infos').append("<button id=\"btn-add-opticalDisk\" class=\"btn btn-default\" type=\"button\"><i class=\"si si-disc\"></i></button>");
$('#storage-infos').append("<button data-toggle=\"modal\" data-target=\"#createHDD-modal\" id=\"btn-add-hardDisk\" class=\"btn btn-default\" type=\"button\"><i class=\"fa fa-hdd-o\"></i></button>");
$('#storage-infos').append("<button id=\"btn-delete-controller\" class=\"btn btn-danger\" type=\"button\" ><i class=\"fa fa-times\"></i></button>");
$('#btn-delete-controller').click(function(e){
e.preventDefault();
swal({
title: 'Are you sure?',
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!'
}).then(function () {
deleteController();
hideStorageInfos();
})
});
}else{
$('#storage-infos').html("drive : "+data.text+"<br>");
}
}
function hideStorageInfos(){
$('#storage-infos').empty();
}
function setControllerAvailable(data){
$.each(data,function(key,val){
switch(key){
case "IDE":
$('#new-controller-ide').addClass("disable-controller");
break;
case "SATA":
$('#new-controller-sata').addClass("disable-controller");
break;
case "USB":
$('#new-controller-usb').addClass("disable-controller");
break;
case "FLOPPY":
$('#new-controller-floppy').addClass("disable-controller");
break;
case "SAS":
$('#new-controller-sas').addClass("disable-controller");
break;
case "SCSI":
$('#new-controller-scsi').addClass("disable-controller");
break;
default:
break;
}
});
}
function createController(ctrl){
$('.loader-storage').show();
$.ajax({
url: 'ConfigureStorage',
type: 'POST',
dataType:'json',
data: $('.js-value-form').serialize() + "&fn=addCtrl¶m="+ctrl,
success: function (data) {
$('.loader-storage').hide();
if(data.header.statut == "200"){
setControllerAvailable(data.data.controller);
showStorageTree(data);
}else{
notify('danger','Error : ['+ data.header.statut +'] createController');
}
},
error: function (jqXHR, textStatus, errorThrown) {
$('.loader-storage').hide();
notify('danger','Error : '+ jqXHR.status+' ['+errorThrown+'] createController');
}
});
}
function deleteController(){
$('.loader-storage').show();
var ctrl = $('#controllerName').text();
$.ajax({
url: 'ConfigureStorage',
type: 'POST',
dataType:'json',
data: $('.js-value-form').serialize() + "&fn=removeCtrl¶m="+ctrl,
success: function (data) {
$('.loader-storage').hide();
if(data.header.statut == "200"){
setControllerAvailable(data.data.controller);
showStorageTree(data);
}else{
notify('danger','Error : ['+ data.header.statut +'] deleteController');
swal( 'Oops...', 'Something went wrong!', 'error' );
}
},
error: function (jqXHR, textStatus, errorThrown) {
$('.loader-storage').hide();
notify('danger','Error : '+ jqXHR.status+' ['+errorThrown+'] deleteController');
swal( 'Oops...', 'Something went wrong!', 'error' );
}
});
}
function createHDD(){
$('.loader-storage').show();
var ctrl = $('#controllerName').text();
$.ajax({
url: 'ConfigureStorage',
type: 'POST',
dataType:'json',
data: $('.js-value-form').serialize() +"&"+$('#js-form-createHDD').serialize()+ "&fn=addDrive¶m="+ctrl,
success: function (data) {
$('.loader-storage').hide();
if(data.header.statut == "200"){
jQuery('#createHDD-modal').modal('hide');
setControllerAvailable(data.data.controller);
showStorageTree(data);
}else{
notify('danger','Error : ['+ data.header.statut +'] createHDD' );
swal( 'Oops...', 'Something went wrong!', 'error' );
}
},
error: function (jqXHR, textStatus, errorThrown) {
$('.loader-storage').hide();
notify('danger','Error : '+ jqXHR.status+' ['+errorThrown+'] createHDD');
swal( 'Oops...', 'Something went wrong!', 'error' );
}
});
}
/**************************************
* Other function
***************************************/
function changeInterval(int){
clearInterval(autoRefreshLauncher);
if(int == 0){
autoRefresh = false;
}else{
autoRefresh = true;
autoRefreshLauncher = setInterval(function () { mainAPI(); },int*1000);
}
}
function notify(type, msg){
var ico = '';
if(type== 'danger'){
ico = 'fa fa-times';
}else if(type == 'success'){
ico = 'fa fa -check';
}else if( type== 'warning'){
ico = 'fa fa-warning';
}else{
ico = '';
}
jQuery.notify({
icon: ico,
message: msg
},
{
element: 'body',
type: type,
allow_dismiss: true,
newest_on_top: true,
showProgressbar: false,
placement: {
from: 'top',
align: 'right'
},
offset: 20,
spacing: 10,
z_index: 1033,
delay: 6000,
timer: 1000,
animate: {
enter: 'animated fadeIn',
exit: 'animated fadeOutDown'
}
});
}
/***************************
* On click event
**************************/
$('#detail-btn').click(function() {
$('#detail-btn').addClass('active-vm-tab');
$('#console-btn').removeClass('active-vm-tab');
$('#snapshot-btn').removeClass('active-vm-tab');
$('#details').show();
$('#console').hide();
$('#snapshot').hide();
});
$('#console-btn').click(function() {
$('#detail-btn').removeClass('active-vm-tab');
$('#console-btn').addClass('active-vm-tab');
$('#snapshot-btn').removeClass('active-vm-tab');
$('#details').hide();
$('#console').show();
$('#snapshot').hide();
});
$('#snapshot-btn').click(function() {
$('#detail-btn').removeClass('active-vm-tab');
$('#console-btn').removeClass('active-vm-tab');
$('#snapshot-btn').addClass('active-vm-tab');
$('#details').hide();
$('#console').hide();
$('#snapshot').show();
});
$('#btn-preview-refresh').click(function(e) {
e.preventDefault();
getPreviewAndState(true);
});
$('#btn-change-interval').click(function(e) {
e.preventDefault();
changeInterval($('#btn-change-interval').text());
});
$('#start-btn').click(function(e) {
e.preventDefault();
startMachine();
});
$('#btn-delete-machine').click(function(e) {
e.preventDefault();
deleteMachine();
});
$('#start-btn-dropdown').click(function(e) {
e.preventDefault();
startMachine();
});
$('#btn-stop-machine').click(function(e){
e.preventDefault();
stopMachine();
});
$('#btn-create-machine').click(function(e){
e.preventDefault();
createMachine();
});
$('#btn-save-cfg-vm').click(function(e){
e.preventDefault();
configureMachine();
});
$('#btn-createHDD').click(function(e){
e.preventDefault();
createHDD();
});
//Change interval
$('#btn-change-interval-0').click(function(e){
e.preventDefault();
$('#li-change-interval-5').removeClass("active-interval");
$('#li-change-interval-10').removeClass("active-interval");
$('#li-change-interval-20').removeClass("active-interval");
$('#li-change-interval-0').removeClass("active-interval");
$('#li-change-interval-0').addClass("active-interval");
changeInterval(0);
});
$('#btn-change-interval-5').click(function(e){
e.preventDefault();
$('#li-change-interval-5').removeClass("active-interval");
$('#li-change-interval-10').removeClass("active-interval");
$('#li-change-interval-20').removeClass("active-interval");
$('#li-change-interval-0').removeClass("active-interval");
changeInterval(5);
$('#li-change-interval-5').addClass("active-interval");
});
$('#btn-change-interval-10').click(function(e){
e.preventDefault();
$('#li-change-interval-5').removeClass("active-interval");
$('#li-change-interval-10').removeClass("active-interval");
$('#li-change-interval-20').removeClass("active-interval");
$('#li-change-interval-0').removeClass("active-interval");
changeInterval(10);
$('#li-change-interval-10').addClass("active-interval");
});
$('#btn-change-interval-20').click(function(e){
e.preventDefault();
$('#li-change-interval-5').removeClass("active-interval");
$('#li-change-interval-10').removeClass("active-interval");
$('#li-change-interval-20').removeClass("active-interval");
$('#li-change-interval-0').removeClass("active-interval");
changeInterval(20);
$('#li-change-interval-20').addClass("active-interval");
});
//add storage controller
$('#new-controller-ide').click(function(e){
e.preventDefault();
createController("IDE");
});
$('#new-controller-sata').click(function(e){
e.preventDefault();
createController("SATA");
});
$('#new-controller-usb').click(function(e){
e.preventDefault();
createController("USB");
});
$('#new-controller-floppy').click(function(e){
e.preventDefault();
createController("FLOPPY");
});
$('#new-controller-sas').click(function(e){
e.preventDefault();
createController("SAS");
});
$('#new-controller-scsi').click(function(e){
e.preventDefault();
createController("SCSI");
});
/***************************
* Main API
**************************/
function mainAPI(){
if(autoRefresh){
getPreviewAndState();
}
}
getPreviewAndState();
getStorageTree();
autoRefreshLauncher = setInterval(function () { mainAPI(); },refreshInterval*1000);
});
})(jQuery);
|
var SimplePromise = require('../simple'),
assert = require('assert');
describe('Value Promise', function () {
describe('fulfill', function () {
it('should at fulfilled state', function (done) {
var fulfilledState = null,
fulfilledStateChain = null,
fulfilledPromise = SimplePromise(function (resolve, reject) {
setTimeout(function () {
resolve();
}, 100);
});
fulfilledPromise.then(function () {
fulfilledState = true;
}, function () {
fulfilledState = false;
}).then(function () {
fulfilledStateChain = true;
}, function () {
fulfilledStateChain = false;
});
setTimeout(function () {
assert(fulfilledState && fulfilledStateChain, 'fulfilled promise failed');
done();
}, 200);
});
});
describe('reject', function () {
it('should at rejected state', function (done) {
var rejectedState = null,
rejectedStateChain = null,
rejectedPromise = SimplePromise(function (resolve, reject) {
setTimeout(function () {
reject();
}, 100);
});
rejectedPromise.then(function () {
rejectedState = true;
}, function () {
rejectedState = false;
}).then(function () {
rejectedStateChain = true;
}, function () {
rejectedStateChain = false;
});
setTimeout(function () {
assert(rejectedState === false && rejectedStateChain === false, 'rejected promise failed');
done();
}, 200);
});
});
});
|
var Blog = {
loading: false, // to prevent hitting the ajax function more than necessary
num_loaded: 0, // number of posts already shown
api_url: '',
init: function() {
// record # of posts we already have
Blog.num_loaded = $(".post").length;
// api endpoint for grabbing posts
Blog.api_url = location.pathname + '?offset=';
// hide the non-js pager. By keeping the pager with no JS, google can still index posts.
$('ul.pager').hide();
// set the trigger
$(window).scroll(function(e){
if (Blog.loading){
return false;
}
if (document.documentElement.clientHeight + $(document).scrollTop() >= document.body.offsetHeight) {
Blog.loading = true;
$('#loader').show(); // a way to show the user we're working
Blog.loadPosts();
}
});
},
loadPosts: function() {
// make request to backend for next batch of posts
$.get(Blog.api_url + Blog.num_loaded, function(data) {
if (data.indexOf("<div") >= 0) {
$('#loader').hide();
$( ".post:last" ).after(data);
Blog.num_loaded = $(".post").length;
// wait 1 sec before we allow loading posts again
setTimeout(function() {
Blog.loading = false;
},1000);
} else {
// there are no more posts, remove spinner, show end of paragraph marker
$("#loader img").remove();
$("#loader").css("background-image", "url(/static/images/paragraph.png)");
}
});
}
};
$(Blog.init);
|
import React from "react"
import PhotosList from "./PhotosList"
class PhotosListContainer extends React.Component {
constructor() {
super()
this.state = { photos: [] }
}
fetchAsync = async () => {
let data = await (await fetch('https://jsonplaceholder.typicode.com/photos', {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})).json()
return data
}
componentDidMount() {
this.fetchAsync()
.then(photos => this.setState({ photos }))
.catch(error => console.log(error.message))
}
render() {
return <PhotosList photos={this.state.photos} />
}
}
export default PhotosListContainer
|
import React, { useState, useEffect } from 'react';
import { connect } from 'dva';
import { Layout, Tag, Select, Button} from 'antd';
import { Link } from 'dva/router';
import styles from "./checkQuestions.scss"
const { CheckableTag } = Tag;
const { Option } = Select;
const { Content } = Layout;
function CheckQuestions(props) {
useEffect(() => {
props.checkQusetons()
props.getExamTypes()
props.getQuestionsTypes()
props.getSubjects()
}, [])
let { QuestionsType, examType, subjects } = props
let tagsFromServer = ['All'];
//所有的课程类型
tagsFromServer = tagsFromServer.concat(subjects && subjects.map(item => item.subject_text))
//选中的课程类型
const [checkedCon, setCheckedCon] = useState('')
//全选的状态
const [allChecked, setAllChecked] = useState(false)
//查询考试类型的ID
const [exam_id, setExamTypeId] = useState('')
//查询题目类型的ID
const [questions_type_id, setQuestionsTypeId] = useState('')
//查询课程类型的ID
const [subject_id, setSubjectId] = useState('')
let handleChange = (tag, checked) => {
console.log(tag, checked)
if (tag === "All") {
setAllChecked(!allChecked)
setCheckedCon('')
} else {
setCheckedCon(tag)
setSubjectId(subjects && subjects.filter(item => item.subject_text === tag)[0].subject_id)
}
}
let getExamTypeId = (e) => {
let id = examType && examType.filter(item => item.exam_name === e)[0].exam_id
setExamTypeId(id)
// console.log(id)
}
let getQuestionsTypeId = (e) => {
let id = QuestionsType && QuestionsType.filter(item => item.questions_type_text === e)[0].questions_type_id
setQuestionsTypeId(id)
}
let searchTest = () => {
props.searchTests({ exam_id, questions_type_id, subject_id })
}
return (
<Layout style={{ padding: '0 24px 24px' }}>
<h2 style={{ padding: '20px 0px', marginTop: '10px' }}>查看试题</h2>
<Content
style={{
background: '#fff',
padding: 24,
marginBottom: 24,
borderRadius: 10
}}
>
<div style={{ display: 'flex', marginBottom: 10, lineHeight: '40px' }}>
<h6 style={{ marginRight: 8, display: 'inline', fontSize: 14, width: '8%', textAlign: 'right' }}>课程类型:</h6>
<div style={{ flex: 1 }}>
{tagsFromServer.map((tag, index) => (
<CheckableTag
key={tag}
checked={checkedCon === tag}
className={allChecked ? styles['ant-tag-checkable-checked'] : ''}
onChange={checked => handleChange(tag, checked)}
>
{tag}
</CheckableTag>
))}
</div>
</div>
<div style={{ display: 'flex', marginBottom: 24, padding: '' }}>
<div style={{ display: 'flex', alignItems: "center", width: '25%' }}>
<label style={{ width: '35%', textAlign: 'right' }}>考试类型:</label>
<div style={{ width: '62.5%' }}>
<Select style={{ width: '100%' }} onChange={(e) => getExamTypeId(e)}>
{examType && examType.map((item, index) => <Option key={index} value={item.exam_name}>{item.exam_name}</Option>)}
</Select>
</div>
</div>
<div style={{ display: 'flex', alignItems: "center", width: '25%' }}>
<label style={{ width: '35%', textAlign: 'right' }}>题目类型:</label>
<div style={{ width: '62.5%' }}>
<Select defaultValue="" style={{ width: '100%' }} onChange={(e) => getQuestionsTypeId(e)}>
{QuestionsType && QuestionsType.map((item, index) => <Option key={index} value={item.questions_type_text}>{item.questions_type_text}</Option>)}
</Select>
</div>
</div>
<div style={{ width: '25%' }} className={styles.ant_submit}>
<Button type="primary" icon="search" onClick={searchTest}>查询</Button>
</div>
</div>
</Content>
<Content
style={{
background: '#fff',
padding: 24,
marginBottom: 24,
borderRadius: 10
}}
>
<div className={styles.ant_list}>
{props.qustions && props.qustions.map((item, index) => <div key={index} className={styles.ant_list_item}>
<Link to={"/main/questions/detail/" + item.questions_id}>
<div>
<h4>{item.title}</h4>
</div>
<div>
<div>
<Tag color="blue">{item.questions_type_text}</Tag>
<Tag color="geekblue">{item.subject_text}</Tag>
<Tag color="orange">{item.exam_name}</Tag>
</div>
<span>{item.user_name} 发布</span>
</div>
</Link>
<ul>
<li style={{ cursor: 'pointer' }}><Link to={"/main/questions/editQuestions/" + item.questions_id}>编辑</Link></li>
</ul>
</div>)}
</div>
</Content>
</Layout>
);
}
CheckQuestions.propTypes = {
};
const mapStateToProps = state => {
return {
...state.questions,
}
}
const mapDispatchToProps = dispatch => {
return {
checkQusetons: () => {
dispatch({
type: 'questions/questions',
})
},
getExamTypes: () => {
dispatch({
type: 'questions/examTypes'
})
},
getQuestionsTypes: () => {
dispatch({
type: 'questions/QuestionsTypes'
})
},
getSubjects: () => {
dispatch({
type: 'questions/Subject'
})
},
searchTests: payload => {
dispatch({
type: 'questions/searchTest',
payload
})
}
}
}
export default connect(mapStateToProps, mapDispatchToProps)(CheckQuestions);
|
// npm commands
/**
* Instructions:
* 1. npm init -y
* 2. npm install express
* 3. both both together with &&
*
*/
/**
* Instructions for template engine
* 1. npm i handlebars node-fetch express-handlebars hbs
* 2. update our app.get()
*
* 3.
*/
/**
* app.template
*/
const express = require('express');
const app = express();
var port = 3001;
const fetch = require('node-fetch');
/**
* Instructions for template engine
* 1. npm i handlebars node-fetch express-handlebars hbs
* 2. update our app.get()
*
* 3. Create template files
* a. views/index.hbs
* b. views/layouts/main.hbs
* c. views/partials/head.hbs
*/
const hbs = require('express-handlebars')({
extname: '.hbs',
});
app.engine('hbs', hbs);
app.set('view engine', 'hbs');
app.get('/',(req,res)=>{
res.render('index');
});
// res == response aka what we send to the client
// async tag on callback function allows us to use async/wait
app.get('/pokemon/:id', async (req, res) => {
try {
const URI = `https://pokeapi.co/api/v2/pokemon/${req.params.id}`;
const pokemonData = await fetch(URI);
const json = await pokemonData.json();
// console.log(json);
pokeName = await json.name;
pokeImg = await json.sprites.back_default;
// console.log(pokeImg);
await res.render('index', {
name: pokeName,
img: pokeImg
});
} catch (error) {
console.log(error);
}
});
app.listen(process.env.PORT || port, () => {
console.log(`Server started on ${port}`);
});
//npm start, open your browser and run localhost:port
|
module.exports = require('./questions.router.js');
|
function getRandomString() {
return Math.random().toString(36).substring(7)
}
class Utils {
static getRandomString = getRandomString
}
export { Utils }
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.