text stringlengths 7 3.69M |
|---|
import mongoose from "mongoose";
const userSchema = mongoose.Schema(
{
name: {
type: String,
required: true,
},
email: {
type: String,
required: [true, "Please add an email"],
unique: true,
match: [
/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/,
"Please add a valid email",
],
},
password: {
type: String,
required: [true, "Please add a password"],
minlength: 6,
// when u return a user on api, we dont wanna see password so select:false
select: false,
},
isAdmin: {
type: Boolean,
required: true,
default: false,
},
resetPasswordToken: String,
resetPasswordExpire: Date,
shippingAddress: {
address: { type: String },
city: { type: String },
postalCode: { type: String },
},
},
{
timestamps: true,
}
);
const User = mongoose.model("User", userSchema);
export default User;
|
const { ValidationError } = require('./ValidationError');
const ok = function ok(value, message) {
if (!value) {
throw new ValidationError(message);
}
return value;
};
const notNull = function notNull(value, message) {
if (value === null) {
throw new ValidationError(message);
}
return value;
};
module.exports = ok;
module.exports.ok = ok;
module.exports.notNull = notNull;
|
import React from 'react';
import '../styles/styles.css'
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import { Link } from 'react-router-dom';
export default function Nav(props) {
return (
<div>
<nav className="nav">
<Link style={{ color: "black", textDecoration: 'none' }} to='/'>
<h3>Home</h3>
</Link>
<ul className='nav-links'>
<Link style={{ color: "black", textDecoration: 'none' }} to='/cart'>
<li>Cart</li>
</Link>
<Link style={{ color: "black", textDecoration: 'none' }} to='/wishlist'>
<li>Wishlist</li>
</Link>
</ul>
</nav>
</div>
)
} |
export default (meth, url)=>{
return new Promise((resolve, reject)=>{
let xhr = new XMLHttpRequest();
xhr.open(meth,url);
xhr.addEventListener('load',()=>{
resolve(xhr.responseText);
});
xhr.addEventListener('error',()=>{
reject(xhr.statusText);
})
xhr.send();
});
}
|
/*
var years = [1990,1986, 1993,2007,1967];
function arrayCalc(arr,fn){
var arrRes =[];
for(var i =0; i<arr.length; i++){
arrRes.push(fn(arr[i]));
}
return arrRes;
}
function calculateAge(el){
return 2021-el;
}
function isFullAge(el){
return el >= 18;
}
function maxHeartRate(el){
return Math.round(206.9 -(.67 * el));
}
var ages = arrayCalc(years, calculateAge);
var fullAge = arrayCalc(ages,isFullAge);
var heartRate = arrayCalc(ages,maxHeartRate);
console.log(ages);
console.log(fullAge);
console.log(heartRate)
*/
/*
function interviewQuestion(job){
if(job ==="designer"){
return function(name){
console.log(name + ', do you explaing the UI design ?');
}
}else if( job ==='teacher'){
return function(name){
console.log('what do you want to teach students,' + name);
}
}else{
return function(name){
console.log("hello" + name+ ' what do you do');
}
}
}
var designerQuestion = interviewQuestion('designer');
var teacherQuestion = interviewQuestion('teacher');
var doctorQuestion = interviewQuestion('doctor');
designerQuestion('john');
teacherQuestion('smith');
teacherQuestion('roy');
teacherQuestion('jonson');
doctorQuestion('mark');
interviewQuestion('designer')('hossain');
// function game(){
// var score = Math.random() * 10;
// console.log(score >= 5);
// }
// game();
(function(){
var score = Math.random()*10;
console.log(score >= 5);
})();
//console.log(score);
(function(goodluck){
var score = Math.random()*10;
console.log(score >= 5 - goodluck);
})(5);
*/
function retirement(retirementAge){
return function(yearOfBirth){
var a = 'years left until retirement';
var age = 2021-yearOfBirth;
console.log((retirementAge-age) +a );
}
}
var retirementUs = retirement(66);
var retirementGer = retirement(65);
retirement(60)(1970);
retirementUs(1990);
retirementGer(1987);
//closures
function interviewQuestion(job){
return function(name){
if(job=='teacher'){
console.log(name + ' can you please teach me ?');
}else if(job == 'designer'){
console.log(name + ' can you please explain ui design');
}else{
console.log(name + ' what can you please explain ui design');
}
}
}
interviewQuestion('teacher')("john");
var john = {
name:'john',
age:27,
job:'teacher',
presentation:function(style,timeOfDay){
if(style == 'formal'){
console.log('good '+ timeOfDay + ' ladies and gentlemen! I \' am ' + this.name +
', I \' m a ' + this.job + ' and I am '+ this.age + ' years old.');
}else if(style =='friendly'){
console.log('Hi what\'s up I \'m '+ this.name +
', I \' m a ' + this.job + ' and I am '+ this.age + ' years old. Have a nice day '+ timeOfDay+'.');
}
}
};
john.presentation('formal', 'morning');
|
/* global describe, it */
require('simple-mocha');
var models = require('models');
var User = models.User;
var authCtrl = require('controllers/auth');
var _ = require('lodash');
var assert = require('assert');
describe( 'Auth controller', function(){
describe('should register a new user', function( ){
var testData = {
email: 'testuser@test.com',
password: 'secret',
name: 'Test User'
};
it( 'should save new user', function( done ){
return authCtrl.postRegister( testData )
.then(function( result ){
assert( result );
var testData = _.pick( result, 'name', 'email', 'username' );
var expectedData = _.omit( testData, 'password' );
expectedData.username = testData.email;
assert.deepEqual( testData, expectedData );
return User.findById( result.id );
})
.then(function( user ){
assert( user );
})
.asCallback(done);
});
it('should send verification Email', function(){
var globalMailBox = global._mailBox;
assert( globalMailBox );
var userMailBox = globalMailBox[testData.email];
assert( userMailBox && userMailBox.length );
var mail = userMailBox[0];
assert( mail.html );
var emailToken = mail.html.match(/href=\".*emailToken=(.*)\">Verification Link<\/a>/);
assert( emailToken && emailToken[1] )
})
})
})
|
// Assignment Code
// Array of special characters to be included in password
var specialCharacters = [
"@",
"%",
"+",
"\\",
"/",
"'",
"!",
"#",
"$",
"^",
"?",
":",
",",
")",
"(",
"}",
"{",
"]",
"[",
"~",
"-",
"_",
".",
];
// Array of numeric characters to be included in password
var numericCharacters = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
// Array of lowercase characters to be included in password
var lowerCasedCharacters = [
"a",
"b",
"c",
"d",
"e",
"f",
"g",
"h",
"i",
"j",
"k",
"l",
"m",
"n",
"o",
"p",
"q",
"r",
"s",
"t",
"u",
"v",
"w",
"x",
"y",
"z",
];
// Array of uppercase characters to be included in password
var upperCasedCharacters = [
"A",
"B",
"C",
"D",
"E",
"F",
"G",
"H",
"I",
"J",
"K",
"L",
"M",
"N",
"O",
"P",
"Q",
"R",
"S",
"T",
"U",
"V",
"W",
"X",
"Y",
"Z",
];
//Creates blank variable for the user prompt to feed the desired characters into
var PasswordCharacters = "";
//Creates our blank password to build off of
var passwordtext = '' ;
//Retrieves reference to to the button with the generate ID
var generateBtn = document.querySelector("#generate");
function generatePassword() {
//Prompt User for Password length
var PasswordLength = prompt(
"Please select a password length between 8 and 128 characters."
);
//make sure length is between 8 and 128
if (PasswordLength < 8 || PasswordLength > 128) {
alert("Invalid length; please input a number between 8 and 128");
return "invalid length; please input a number btween 8 and 128";
}
//Confirm prompt user if they want Special Characters
var UseSpecial = confirm("Do you want Special Characters? (!,#,?, etc)");
//Adds Special characters to password generation
if (UseSpecial) {
PasswordCharacters = [...PasswordCharacters, ...specialCharacters]
}
//Confirm prompt user if they want Numeric Characters
var UseNumeric = confirm("Do you want Numeric Characters? (0-9)");
//Adds Numeric characters to password generation
if (UseNumeric) {
PasswordCharacters = [...PasswordCharacters, ...numericCharacters];
// PasswordCharacters += numericCharacters;
}
//Confirm prompt user if they want uppercase Characters
var UseUppercase = confirm("Do you want Uppercase Characters? (A-Z)");
//Adds Upper Case characters to password generation array
if (UseUppercase) {
PasswordCharacters = [...PasswordCharacters, ...upperCasedCharacters];
}
//Confirm prompt user if they want lowercase Characters
var UseLowercase = confirm("Do you want Lowercase Characters? (a-z)");
//Adds Lower Case characters to password generation
if (UseLowercase) {
PasswordCharacters = [...PasswordCharacters, ...lowerCasedCharacters];
}
//Checks to make sure one of the character sets is used.
if (!UseLowercase && !UseNumeric && !UseSpecial && !UseUppercase) {
return alert("At least one character type must be selected");
}
//Function to pull a random index from a specified array
function random(Array) {
var randomeIndex = Math.floor(Math.random() * Array.length);
var item = Array[randomeIndex];
return item;
}
//For loops iterates based on Password length specified by user. Uses math.random to randomly select an index from our generated PasswordCharacters array, and continues until we reach desired password length
for (var i = 0; i < PasswordLength; i++) {
passwordtext += random(PasswordCharacters);
}
return passwordtext;
}
//Write password to the #password input
function writePassword() {
var password = generatePassword();
var passwordText = document.querySelector("#password");
passwordText.value = password;
}
// Add event listener to generate button
generateBtn.addEventListener("click", writePassword);
|
import React, { useEffect, useState, useCallback } from 'react'
import Link from 'next/link'
// This is an Isomorphic link
// The server-side rendered mark-up will include an `href` attribute
const IsomorphicLink = props => {
const [hasMounted, setHasMounted] = useState(false)
// This is effectively `componentDidMount`
useEffect(() => setHasMounted(true), [])
// Trigger the `onClick()` of the Link when hitting the space or enter key
const clickOnEnterOrSpaceKey = useCallback(ev => {
if (props.onKeyDown) props.onKeyDown(ev)
if (ev.key === 'Enter' || ev.key === ' ') {
ev.preventDefault()
ev.target.click()
}
})
// Add the `href` attribute when not mounted to enable navigation
if (!hasMounted) {
return (
<Link href={props.href}>
{React.cloneElement(props.children, {
href: props.href,
})}
</Link>
)
}
// Remove the `href` attribute when mounted to enable client-side routing
return (
<Link href={props.href}>
{React.cloneElement(props.children, {
onKeyDown: clickOnEnterOrSpaceKey,
tabIndex: 0,
})}
</Link>
)
}
export default IsomorphicLink
|
/**
* images-task.js
* ==============
* Optimize images.
*
*/
module.exports = (gulp, plugins, config) => {
gulp.task('images', () => {
const options = {
imagemin: {
progressive: true,
interlaced: true
}
};
return gulp.src(config.globs.img.src)
.pipe(plugins.newer(config.globs.img.dest))
.pipe(!config.debug ? plugins.imagemin(options.imagemin) : plugins.util.noop())
.pipe(gulp.dest(config.globs.img.dest));
});
};
|
P.views.workouts.priv.Program = P.views.workouts.priv.Abstract.extend({
onRender: function() {
P.views.workouts.priv.Abstract.prototype.onRender.call(this);
this.rProgram.show(new P.views.workouts.view.ProgramLink({
program: this.model.get('program_id')
}));
},
onDelete: function() {
P.common.PubSub.navigate('/programs/view/' + this.model.get('program_id'));
}
}); |
const FtpSrv = require('ftp-srv');
const fs = require('fs');
const ftpServer = new FtpSrv({
username: "111",
password: "111",
root: "./",
port: 21,
greeting: ["Hello ", "Looking of somthing ?",]
});
ftpServer.on('login', (data, resolve, reject) => {
if (data.password === '111') {
if (!fs.existsSync(`d:/Projects/Node/FTP Server/public/${data.username}`)){
fs.mkdirSync(`d:/Projects/Node/FTP Server/public/${data.username}`)
}
resolve({ root: `d:/Projects/Node/FTP Server/public/${data.username}/` });
}
else {
reject('wrong password');
}
});
ftpServer.listen()
.then(() => {
console.log('run');
}); |
let assert = require('chai').assert
let request = require('supertest-as-promised')
let app = require('../../app')
let db = require("../../app/models")
let userName = "aaaaaa"
let body = "1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111"
describe('messages', () => {
it('should post message', () => {
return request(app)
.post('/api')
.send({ userName, body })
.expect(201)
.then((data) => {
assert.ok(data);
});
});
it('should return 400 if message body less then 200', () => {
let body = "123123"
return request(app)
.post('/api')
.send({ userName, body })
.expect(400)
.then((data) => {
assert.ok(data);
});
});
it('should return 400 if userName has invalid symbols', () => {
let userName = "1@"
return request(app)
.post('/api')
.send({ userName, body })
.expect(400)
.then((data) => {
assert.ok(data);
});
});
it('should return 200 on getting array of messages', () => {
return request(app)
.get('/api')
.expect(200)
.then((data) => {
assert.ok(data);
});
});
it('should return 400 if userName has 0 length', () => {
let userName=""
return request(app)
.post('/api')
.send({userName, body})
.expect(400)
.then((data) => {
assert.ok(data);
});
});
});
|
var HomePage = require ('../Pages/HomePage.page.js');
describe ('Home', ()=> {
beforeEach(function(){
browser.waitForAngularEnabled(false);
browser.get('https://www.ssa.gov/');
});
it('should have correct page title', ()=> {
expect(browser.getTitle()).toEqual('The United States Social Security Administration');
});
it('should have correct url of the page', ()=> {
browser.getCurrentUrl().then(function(url){
console.log(url);
});
});
it('should display the navigation bar', ()=> {
expect(HomePage.navigationBar.isDisplayed()).toBeTruthy();
});
it('sign up button should be clickable', ()=> {
HomePage.signUpButton.isDisplayed().then(function(isVisible){
if(isVisible){
console.log("sign up button is displayed");
}else{
console.log("sign up button is NOT displayed");
}
})
});
}); |
import React from 'react';
import PropTypes from 'prop-types';
import Card from './Card';
import Slider from 'react-slick';
import sliderOptions from './sliderOptions';
import dataCleaner from '../helpers/dataCleaner';
const Favorites = ({ favoriteItems, userFavArray, userId, removeFavorite }) => {
return (
<div>
<div className="favorites-div">
<Slider {...sliderOptions}>
{favoriteItems.map((item, index) => {
return (<Card
movieData={Object.assign({},
dataCleaner(item),
{ poster_path: item.poster_path })}
userFavArray={userFavArray}
removeFav={removeFavorite}
userId={userId}
type="favs"
key={index}
/>);
})}
</Slider>
</div>
{ favoriteItems.length &&
<div className="card-list-div">
{favoriteItems.map((item, index) => {
return (<Card
movieData={Object.assign({},
dataCleaner(item),
{ poster_path: item.poster_path })}
userFavArray={userFavArray}
removeFav={removeFavorite}
userId={userId}
type="favs"
key={index}
/>);
})}
</div>
}
</div>
);
};
Favorites.propTypes = {
fetchData: PropTypes.func,
addToFavorites: PropTypes.func,
removeFavorite: PropTypes.func,
userId: PropTypes.number,
favoriteItems: PropTypes.array,
userFavArray: PropTypes.array,
items: PropTypes.objectOf(PropTypes.object)
};
export default Favorites;
|
let str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
export function generateHash(len = 16) {
let result = ''
for (let i = 0; i < len; i++) {
let random = parseInt(Math.random() * 62)
let letter = str.charAt(random)
result += letter
}
return result
} |
const e = require("express");
const Especiali = require("../../Models/Especiales/Especialidades");
function guardarEsp(req, res) {
console.log('Endpoint de guardar especiales ejecutado');
const newEsp = new Especiali();
const { codigo, nombre, ingrediente, precio, detalle, foto } = req.body;
newEsp.codigo = codigo;
newEsp.nombre = nombre;
newEsp.ingrediente = ingrediente;
newEsp.precio = precio;
newEsp.detalle = detalle;
newEsp.foto = foto;
if (codigo === '') {
res.status(404).send({ message: 'Codigo requerido' })
} else {
if (nombre === '') {
res.status(404).send({ message: 'Nombre requerido' })
} else {
if (ingredientes === '') {
res.status(404).send({ message: 'Ingredientes requeridos' })
} else {
if (precio === '') {
res.status(404).send({ message: 'Precio requerido' })
} else {
if (detalle === '') {
res.status(404).send({ message: 'Detalle requerido' })
} else {
newEsp.save((err, EspStored) => {
if (err) {
res.status(500).send({ message: "Error del servidor" })
} else {
if (!EspStored) {
res.status(404).send({ message: "Error al guardar especial" });
} else {
console.log('Especialidad guardada con exito');
res.status(200).send({ Especialidades: EspStored });
}
}
});
}
}
}
}
}
}
function getEspecialidades(req, res) {
Especiali.find().then(especialidades => {
if (!especialidades) {
res.status(404).send({ message: "No se ha encontrado ninguna especialidad" });
} else {
res.status(200).send({ especialidades });
}
})
}
function getEspecialNames(req, res) {
Especiali.find({}, { nombre: 1, precio: 1, _id: 0 }).then(especialidades => {
if (!especialidades) {
res.status(404).send({ message: "No se ha encontrado ninguna especialidad" });
} else {
res.status(200).send({ especialidades });
}
})
}
function updateEspecialidades(req, res) {
const especiData = req.body;
const params = req.params;
Especiali.findByIdAndUpdate({ _id: params.id }, especiData, (err, espUpdate) => {
if (err) {
res.status(500).send({ code: 500, message: "Error del servidor" });
} else {
if (!espUpdate) {
res.status(404).send({ code: 404, message: "No se ha encontrado el Especialidades" });
} else {
res.status(200).send({ code: 200, message: "Especialidad actualizada correctamente" });
}
}
})
}
function deleteEspecialidades(req, res) {
const { id } = req.params;
Especiali.findByIdAndRemove(id, (err, espeDeleted) => {
if (err) {
res.status(500).send({ cod: 500, message: "Error del servidor" });
} else {
if (!espeDeleted) {
res.status(404).send({ code: 404, message: "No se ha encontrado el Especialidades" });
} else {
res.status(200).send({ code: 200, message: "Especialidad eliminada correctamente" });
}
}
})
}
module.exports = {
guardarEsp,
getEspecialidades,
getEspecialNames,
updateEspecialidades,
deleteEspecialidades
}; |
var AUTH0_CLIENT_ID='YGfHgtkVCYNqK1mr2MiOlhjezWnHldzU';
var AUTH0_DOMAIN='amliuyong.auth0.com';
var AUTH0_CALLBACK_URL=location.href;
var API_BASE_URL = "https://i56bou5pk9.execute-api.us-east-1.amazonaws.com/dev";
var global_config = {
AUTH0_CLIENT_ID,
AUTH0_DOMAIN,
AUTH0_CALLBACK_URL,
API_BASE_URL
};
|
/* eslint-disable @typescript-eslint/no-var-requires */
const defaultTheme = require('tailwindcss/defaultTheme');
module.exports = {
purge: ['./pages/**/*.{js,ts,jsx,tsx}', './components/**/*.{js,ts,jsx,tsx}'],
darkMode: false, // or 'media' or 'class'
theme: {
extend: {
fontFamily: {
sans: ['PT Sans', ...defaultTheme.fontFamily.sans],
mono: ['JetBrains Mono', ...defaultTheme.fontFamily.mono],
},
maxWidth: {
30: '30ch',
},
boxShadow: {
th: '0 1px 0 0 rgba(229, 231, 235, 1)',
},
colors: {
link: '#0070f3',
'link-hover': '#3291ff',
},
},
},
variants: {
extend: {
opacity: ['disabled'],
cursor: ['disabled'],
pointerEvents: ['disabled'],
},
},
plugins: [require('@tailwindcss/forms')],
};
|
// return 1 if string s is properly bracketed, 0 otherwise
const brackets = s => {
const left = {'(':')', '[':']', '{':'}'};
const right = {')':'(', ']':'[', '}':'{'};
const stack = [];
const chars = s.split('');
for(let c of chars) {
if(left[c]) stack.push(left[c]);
if(right[c] && stack.pop() != c) return 0;
};
if(stack.length > 0) return 0;
return 1;
};
module.exports = brackets; |
import React from 'react'
import { View, StyleSheet , Text } from 'react-native'
import AppColors from '../Colors/AppColors'
import { widthPercentageToDP as wp, heightPercentageToDP as hp } from 'react-native-responsive-screen';
import Paddings from '../Enums/Paddings';
import Title from '../Components/Title'
import TitleType from '../Enums/TitleType'
import Icon from 'react-native-vector-icons/MaterialIcons';
export default CompanyHeader = props => {
return (
<View style={styles.container}>
<View style={styles.leftSqure}>
<Icon name='engineering' size={wp('7%%')} color={AppColors.mainIconColor} />
</View>
<View style={styles.textContainer}>
<Text style={styles.description} >
We found <Text style = {{fontWeight : 'bold'}}>{props.count} certified companies</Text> in your Selected Location
</Text>
</View>
</View>
)
}
const styles = StyleSheet.create({
container: {
backgroundColor: AppColors.mainButtonColor,
flexDirection: 'row',
padding: wp(Paddings.normal),
alignItems: 'center',
alignContent : 'flex-start',
justifyContent: 'flex-start'
},
leftSqure: {
width: wp(Paddings.large),
height: wp(Paddings.large),
borderRadius: 10,
borderColor: AppColors.textColor,
borderWidth: 1,
alignItems : 'center',
justifyContent : 'center',
backgroundColor : AppColors.buttonDisabledColor
},
description: {
fontWeight: 'normal',
color: AppColors.mainBackground,
textAlign: 'left',
flexWrap : 'wrap',
fontSize : wp('4%')
},
textContainer: {
padding : wp(Paddings.small),
flex : 1
}
}) |
const Car = require('mongoose').model('Car')
module.exports = {
addCarView: (req, res) => {
res.render('adminPanel/createCarView');
},
createCar: (req, res, next) => {
let carData = req.body
let objForCreation = {
brand: carData.brand,
model: carData.model,
image: carData.image,
year: carData.year,
creationDate: Date.now(),
pricePerDay: carData.pricePerDay
}
Car.create(objForCreation).then(() => {
res.redirect('/')
});
}
}; |
var React = require('react');
exports.collect = function collect(node, predicate, options) {
options = options || {};
var blackboxComponents = Boolean(options.blackboxComponents);
var found = [];
if (node === false || node == undefined || node === null) {
return found;
}
if (predicate(node)) {
found.push(node);
}
if (node.props && !shouldBlackbox(node, blackboxComponents)) {
var children = childrenArray(node.props);
var recursed = children.map(function(child) {
return collect(child, predicate, options);
});
found = [].concat.apply(found, recursed);
}
return found;
};
function shouldBlackbox(node, flag) {
if (!flag) return false;
return typeof node.type === 'function';
}
function childrenArray(props) {
var array = [];
React.Children.forEach(props.children, function(child) {
array.push(child);
});
return array;
}
|
var entry = require('./common/entry')
var publicKey = require('./common/public-key')
var strict = require('./strict')
module.exports = strict({
type: 'object',
properties: {
type: {const: 'confirm'},
publicKey,
entry
}
})
|
// Write your code in this file!
function scuberGreetingForFeet(tripDistance) {
if (tripDistance <= 400) {
return 'This one is on me!';}
else if (tripDistance > 2500) {
return 'No can do.';}
else if (tripDistance >2000) {
return 'I will gladly take your thirty bucks.' ;}
else {
return 'The trip will cost ${(2000/30) * tripDistance} !' ;
}
}
function ternaryCheckCity (destinationCity) {
return destinationCity === 'NYC' ? "Ok, sounds good." : "No go." ;
}
function switchOnCharmFromTip(tip) {
switch(tip) {
case 'generous':
return 'Thank you so much.';
case 'not as generous':
return 'Thank you.' ;
case 'thanks for everything':
return 'Bye.' ;
}
}
|
var searchData=
[
['searchchar',['searchChar',['../shell_8c.html#adc513a5c9f6df8f1a54c83193a362499',1,'shell.c']]],
['sh_5fcd',['sh_cd',['../sh__command_8c.html#a9aa0f977496ed2eb3dcef2c34f088009',1,'sh_command.c']]],
['sh_5fcommand_2ec',['sh_command.c',['../sh__command_8c.html',1,'']]],
['sh_5fecho',['sh_echo',['../sh__command_8c.html#a80a1e5f75df008cd7984d0b884875303',1,'sh_command.c']]],
['sh_5fexit',['sh_exit',['../sh__command_8c.html#a4e41dc224bf68fa133b07bc26231b5f9',1,'sh_command.c']]],
['sh_5fhelp',['sh_help',['../sh__command_8c.html#a0bace0a3c9c18f008a62e5fea1db47d1',1,'sh_command.c']]],
['sh_5fpwd',['sh_pwd',['../sh__command_8c.html#abc711a50a61b3f1c861c19d49e258819',1,'sh_command.c']]],
['shell_2ec',['shell.c',['../shell_8c.html',1,'']]]
];
|
import React from 'react';
import ReactDOM from 'react-dom';
import Main from './pages/main';
import About from './pages/About';
import Where from './pages/Where';
import Contact from './pages/Contact';
import Home from './pages/Home';
import Portfolio from './pages/Portfolio';
import NavBar from './components/NavBar';
/**
* yellow color initial gradient: #D8A72C;
* yellow color end gradient: #f4e6c2;
*
* blue color initial gradient: #2d3a6a;
* blue color end gradient: #3b57c2;
*/
import './styles/global.css';
import { Provider } from 'react-redux';
import { PersistGate } from 'redux-persist/integration/react';
import { store, persistor } from './configReducers/configStore';
ReactDOM.render(
<Provider store={store}>
<PersistGate loading={true} persistor={persistor}>
<NavBar
linksNav={
[
{
component: Home,
nome: 'Início',
id: 'home'
},
{
component: About,
nome: 'Sobre nós',
id: 'about'
},
{
component: Portfolio,
nome: 'Portfólio',
id: 'portfolio'
},
{
component: Where,
nome:'Onde estamos',
id: 'where'
},
{
component: Contact,
nome:'Contato',
id: 'contact'
}
]
}
/>
<Main />
</PersistGate>
</Provider>
,
document.getElementById('root')
);
|
import React from 'react';
export default class Item extends React.Component {
static propTypes = {
idx: React.PropTypes.number.isRequired,
name: React.PropTypes.any.isRequired
};
constructor() {
super();
this.state = {
checked: false
};
}
checkElement() {
this.setState({
checked: !this.state.checked
});
}
render() {
return (
<li key={this.props.idx} onClick={() => this.checkElement()} className={this.state.checked ? 'check' : 'uncheck'}>
{this.props.name}
</li>
);
}
} |
import React, { Component } from 'react'
import styled from 'styled-components'
import Layout from './Layout'
import Icon from '../../assets/images/notice/construct.png'
const Image = styled.img`
width: 150px;
height: 150px;
`
class ComingSoon extends Component {
render() {
return (
<Layout
title="COMING SOON"
titleStyle={{
animation: 'changeColor 3s linear infinite',
}}
description="This page is under construction. We are working to bring you new best experience. Stay tured for something amazing"
icon={<Image src={Icon} />}
/>
)
}
}
export default ComingSoon
|
import { extendObservable } from "mobx";
class ListaData {
constructor() {
extendObservable(this, { tareas: [] });
this.agregarTarea = this.agregarTarea.bind(this);
this.eliminarTarea = this.eliminarTarea.bind(this);
}
agregarTarea(tarea) {
console.log(tarea);
this.tareas.push(tarea);
}
eliminarTarea(indice) {
console.log(indice);
this.tareas.splice(indice, 1);
}
}
let ListData = new ListaData();
export default ListData;
|
import AbstractView from "./AbstractView.js";
export default class extends AbstractView {
constructor(params) {
super(params);
}
async getHtml(isLoggedIn, role) {
return `
<!--Navbar-->
<nav class="navbar navbar-expand-md navbar-light">
<!-- Left / Navbar brand -->
<div class="navbar-nav">
<a href="/" class="navbar-brand mx-auto" data-link>Home</a>
</div>
<!-- Collapse button -->
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<!-- Collapsible content -->
<div class="collapse navbar-collapse w-100" id="navbarSupportedContent">
<!-- Center -->
<div class="mx-auto">
<ul class="navbar-nav">
<li class="nav-item">
<a href="/about" class="nav-link" data-link>About</a>
</li>
<li class="nav-item">
<a href="/teachers" class="nav-link" data-link>Teachers</a>
</li>
<li class="nav-item">
<a href="/classes" class="nav-link" data-link>Classes</a>
</li>
<li class="nav-item">
<a href="/schedule" class="nav-link" data-link>Schedule</a>
</li>
<li class="nav-item">
<a href="/matchme" class="nav-link" data-link>MatchMe</a>
</li>
<li class="nav-item">
<a href="/map" class="nav-link" data-link>Map</a>
</li>
${isLoggedIn ?
`<li class="nav-item">
<a href="/dashboard" class="nav-link" data-link>
${role === 'user' ? "My Account" : "Dashboard"}
</a>
</li>`
: ``}
</ul>
</div>
</div>
</nav>
<div class="header-forms">
${isLoggedIn ?
`<a href="/logout" class="btn btn-sm btn-outline-info" id="logout-user" data-link>Logout</a>`
:
`<a href="/login" class="btn btn-sm btn-outline-info" data-link>Login</a>
<a href="/signup" class="btn btn-sm btn-outline-info" data-link>Signup</a>`
}
</div>
`;
}
}
|
(function($) {
/*
Name: jq Placeholder For IE;
Author:Kingwell Leng;
Date:2015-09-25;
Version:1.0;
*/
function log(msg, type) {
var t = type || 'log';
try {
console[t](msg);
} catch (ev) {}
}
window.log = log;
//存放绑定元素,用于重置显示状态;
$.placeholder = {
input: [],
resetStatus: function() {
var len = this.input.length;
$.each(this.input, function(i, ele) {
$(ele).blur();
});
return len ? '\u91cd\u7f6e\u6210\u529f' + len + '\u4e2a' : '\u60a8\u6ca1\u6709\u7ed1\u5b9a\u4efb\u4f55\u5143\u7d20';
}
};
$.fn.placeholder = function(options) {
var style = '';
var ops = $.fn.extend({
left: 0,
top: 0,
extendStyle: '',
blankCharacter: true,
color: '',
lineHeight: '',
wrapTagName: 'span'
}, options);
if (!$('#placeholder__').length) {
//$.fn.placeholder.lock = true;
//http://img.huizecdn.com/com/opacity_0.gif;;
style = '.placeholder-wrap{position: relative;display: inline-block;}.placeholder-text{position: absolute; }.placeholder-input{position: relative;background-color: transparent; z-index: 1;}';
$('head').append('<style id="placeholder__">' + ops.extendStyle + style + '</style>');
}
function returnValue(_this, property) {
return parseInt($(_this).attr(property), 10) || 0;
}
return this.each(function() {
var _this = this;
//避免多次绑定
if ($(_this).data('status')) {
return;
}
$(_this).data('status', true);
if ($(_this).is(':hidden')) {
log('\u8fd9\u662f\u4e00\u4e2a\u9690\u85cf\u5143\u7d20\uff0c\u65e0\u6cd5\u51c6\u786e\u5b9a\u4f4d', 'info');
}
if ($(_this).css('backgroundImage') === 'none') {
$(_this).css('backgroundImage', '//img.huizecdn.com/com/opacity_0.gif');
}
$.placeholder.input.push(_this);
var text = ops.text || $(_this).attr('placeholder-text') || '',
$text,
$input,
timeout,
color = ops.color || $(_this).attr('placeholder-color') || '#999',
left = ops.left !== 0 ? ops.left : returnValue(_this, 'placeholder-left'),
top = ops.top || returnValue(_this, 'placeholder-top'),
width = ops.width || (returnValue(_this, 'placeholder-width') || 'auto'),
height = ops.height || returnValue(_this, 'placeholder-height'),
fontSize = ops.fontSize || parseInt($(_this).attr('placeholder-size'), 10),
pos,
zIndex = parseInt($('body').css('z-index')) || 1,
isBody = $(_this).parent()[0].tagName.toLowerCase() === 'body',
box = {
width: $(_this).outerWidth(),
height: $(_this).outerHeight(),
size: fontSize || parseInt($(_this).css('fontSize'), 10)
},
tagName = document.createElement($(_this).attr('placeholder-tag') || (ops.wrapTagName || 'span'));
$(tagName).addClass('placeholder-wrap');
$(_this).addClass('placeholder-input');
if (ops.wrapTagName === false) {
if (isBody) {
}
$(_this).parent().css({
position: 'relative'
});
} else {
$(_this).wrap(tagName);
}
$(_this).before('<span class="placeholder-text">' + text + '</span>');
$text = $(_this).prev('.placeholder-text');
pos = $(_this).position();
left += pos.left + parseInt($(_this).css('padding-left'), 10) || 0;
top += pos.top;
if (isBody) {
left = left - parseInt($('body').css('margin-left'), 10) || 0;
top = top - parseInt($('body').css('margin-top'), 10) || 0;
}
//console.log(pos);
$text.css({
width: width || box.width,
height: box.height,
left: left,
top: top,
zIndex: zIndex,
fontSize: box.size,
lineHeight: (ops.lineHeight ? ops.lineHeight : box.height) + 'px',
color: ops.color || color
});
$(_this).css({
zIndex: zIndex + 1
});
//Set Status show Or hide;
function _set() {
var val = $(_this).val(),
_val = $.trim(val);
if (ops.blankCharacter) {
if (val.length) {
$text.hide();
} else {
$text.show();
}
} else {
if (_val.length) {
$text.hide();
} else {
$text.show();
}
}
}
//Bind Events;
//Bind Events;
var isIE = !!window.ActiveXObject;
if (isIE) {
$(_this).parent()
.on('click', 'span.placeholder-text', function() {
$(_this).parent().find('input').focus();
});
}
$(_this)
.on('keydown', _set)
.on('blur', _set)
.on('paste', function() {
clearTimeout(timeout);
_set();
})
.on('keyup', _set)
.on('change', _set)
.on('click', _set)
.on('change', _set);
$(function() {
_set();
});
});
};
})(jQuery); |
$(document).ready(function() {var formatter = new CucumberHTML.DOMFormatter($('.cucumber-report'));formatter.uri("src/test/resources/agileProject.feature");
formatter.feature({
"name": "Agile project sign in",
"description": "",
"keyword": "Feature",
"tags": [
{
"name": "@AgileProject"
}
]
});
formatter.scenario({
"name": "Login as a authenticated user",
"description": "",
"keyword": "Scenario",
"tags": [
{
"name": "@AgileProject"
}
]
});
formatter.step({
"name": "user is on home page",
"keyword": "Given "
});
formatter.match({
"location": "AgileProjectSteps.userIsOnHomePage()"
});
formatter.result({
"status": "passed"
});
formatter.step({
"name": "user navigates to agile page",
"keyword": "When "
});
formatter.match({
"location": "AgileProjectSteps.userNavigatesToAgilePage()"
});
formatter.result({
"status": "passed"
});
formatter.step({
"name": "user enters username \"1303\" and password \"Guru99\"",
"keyword": "And "
});
formatter.match({
"location": "AgileProjectSteps.userEntersUsernameAndPassword(String,String)"
});
formatter.result({
"status": "passed"
});
formatter.step({
"name": "click login button",
"keyword": "And "
});
formatter.match({
"location": "AgileProjectSteps.clickLoginButton()"
});
formatter.result({
"status": "passed"
});
formatter.step({
"name": "welcome message is correct",
"keyword": "Then "
});
formatter.match({
"location": "AgileProjectSteps.welcomeMessageIsCorrect()"
});
formatter.result({
"status": "passed"
});
formatter.scenario({
"name": "Unhappy login",
"description": "",
"keyword": "Scenario",
"tags": [
{
"name": "@AgileProject"
}
]
});
formatter.step({
"name": "user is on home page",
"keyword": "Given "
});
formatter.match({
"location": "AgileProjectSteps.userIsOnHomePage()"
});
formatter.result({
"status": "passed"
});
formatter.step({
"name": "user navigates to agile page",
"keyword": "When "
});
formatter.match({
"location": "AgileProjectSteps.userNavigatesToAgilePage()"
});
formatter.result({
"status": "passed"
});
formatter.step({
"name": "user enters username \"111\" and password \"xyz\"",
"keyword": "And "
});
formatter.match({
"location": "AgileProjectSteps.userEntersUsernameAndPassword(String,String)"
});
formatter.result({
"status": "passed"
});
formatter.step({
"name": "click login button",
"keyword": "And "
});
formatter.match({
"location": "AgileProjectSteps.clickLoginButton()"
});
formatter.result({
"status": "passed"
});
formatter.step({
"name": "unvalid credentials message is shown",
"keyword": "Then "
});
formatter.match({
"location": "AgileProjectSteps.unvalidCredentialsMessageIsShown()"
});
formatter.result({
"status": "passed"
});
formatter.uri("src/test/resources/dragAndDrop.feature");
formatter.feature({
"name": "Drag and drop is working",
"description": "",
"keyword": "Feature",
"tags": [
{
"name": "@DragAndDrop"
}
]
});
formatter.scenario({
"name": "Put bank details into drag and drop form",
"description": "",
"keyword": "Scenario",
"tags": [
{
"name": "@DragAndDrop"
}
]
});
formatter.step({
"name": "user is on dragAndDrop page",
"keyword": "Given "
});
formatter.match({
"location": "DragAndDropSteps.userIsOnDragAndDropPage()"
});
formatter.result({
"status": "passed"
});
formatter.step({
"name": "success message is not shown",
"keyword": "And "
});
formatter.match({
"location": "DragAndDropSteps.successMessageIsNotShown()"
});
formatter.result({
"status": "passed"
});
formatter.step({
"name": "user drop debit account \"BANK\"",
"keyword": "When "
});
formatter.match({
"location": "DragAndDropSteps.userDropDebitAccount(String)"
});
formatter.result({
"status": "passed"
});
formatter.step({
"name": "user drop debit amount \"5000\"",
"keyword": "And "
});
formatter.match({
"location": "DragAndDropSteps.userDropDebitAmount(String)"
});
formatter.result({
"status": "passed"
});
formatter.step({
"name": "user drop credit account \"SALES\"",
"keyword": "And "
});
formatter.match({
"location": "DragAndDropSteps.userDropCreditAccount(String)"
});
formatter.result({
"status": "passed"
});
formatter.step({
"name": "user drop credit amount \"5000\"",
"keyword": "And "
});
formatter.match({
"location": "DragAndDropSteps.userDropCreditAmount(String)"
});
formatter.result({
"status": "passed"
});
formatter.step({
"name": "success message is shown drag",
"keyword": "Then "
});
formatter.match({
"location": "DragAndDropSteps.successMessageIsShownDrag()"
});
formatter.result({
"status": "passed"
});
formatter.uri("src/test/resources/fileUpload.feature");
formatter.feature({
"name": "File upload is working",
"description": "",
"keyword": "Feature",
"tags": [
{
"name": "@Smoke"
}
]
});
formatter.scenario({
"name": "User can upload file on uploadFilePage",
"description": "",
"keyword": "Scenario",
"tags": [
{
"name": "@Smoke"
}
]
});
formatter.step({
"name": "user is on uploadFilePage",
"keyword": "Given "
});
formatter.match({
"location": "FileUploadSteps.userIsOnUploadFilePage()"
});
formatter.result({
"status": "passed"
});
formatter.step({
"name": "title of page is \"File Upload Demo\"",
"keyword": "And "
});
formatter.match({
"location": "FileUploadSteps.titleOfPageIs(String)"
});
formatter.result({
"status": "passed"
});
formatter.step({
"name": "user click \"Choose File\" button",
"keyword": "When "
});
formatter.match({
"location": "FileUploadSteps.userClickButton(String)"
});
formatter.result({
"status": "passed"
});
formatter.step({
"name": "add file path",
"keyword": "And "
});
formatter.match({
"location": "AgileProjectSteps.addFilePath()"
});
formatter.result({
"status": "passed"
});
formatter.step({
"name": "click \"Submit File\" button",
"keyword": "And "
});
formatter.match({
"location": "FileUploadSteps.clickButton(String)"
});
formatter.result({
"status": "passed"
});
formatter.step({
"name": "success message is shown",
"keyword": "Then "
});
formatter.match({
"location": "FileUploadSteps.successMessageIsShown()"
});
formatter.result({
"status": "passed"
});
formatter.uri("src/test/resources/smokeNavigation.feature");
formatter.feature({
"name": "Navigation to few pages is working",
"description": "",
"keyword": "Feature",
"tags": [
{
"name": "@Smoke"
}
]
});
formatter.scenario({
"name": "User can navigate to homePage",
"description": "",
"keyword": "Scenario",
"tags": [
{
"name": "@Smoke"
}
]
});
formatter.step({
"name": "user navigate to homePage",
"keyword": "When "
});
formatter.match({
"location": "NavigationSteps.userNavigateToHomePage()"
});
formatter.result({
"status": "passed"
});
formatter.step({
"name": "title of homePage is \"Guru99 Bank Home Page\"",
"keyword": "Then "
});
formatter.match({
"location": "NavigationSteps.titleOfHomePageIs(String)"
});
formatter.result({
"status": "passed"
});
formatter.step({
"name": "login form is present",
"keyword": "And "
});
formatter.match({
"location": "NavigationSteps.loginFormIsPresent()"
});
formatter.result({
"status": "passed"
});
formatter.scenario({
"name": "User can navigate to newToursPage",
"description": "",
"keyword": "Scenario",
"tags": [
{
"name": "@Smoke"
}
]
});
formatter.step({
"name": "user is on homePage",
"keyword": "Given "
});
formatter.match({
"location": "NavigationSteps.userIsOnHomePage()"
});
formatter.result({
"status": "passed"
});
formatter.step({
"name": "user click on newToursButton",
"keyword": "When "
});
formatter.match({
"location": "NavigationSteps.userClickOnNewToursButton()"
});
formatter.result({
"status": "passed"
});
formatter.step({
"name": "title of newToursPage is \"Welcome: Mercury Tours\"",
"keyword": "Then "
});
formatter.match({
"location": "NavigationSteps.titleOfNewToursPageIs(String)"
});
formatter.result({
"status": "passed"
});
formatter.step({
"name": "main fragment is present",
"keyword": "And "
});
formatter.match({
"location": "NavigationSteps.mainFragmentIsPresent()"
});
formatter.result({
"status": "passed"
});
formatter.scenario({
"name": "User can navigate to tablePage",
"description": "",
"keyword": "Scenario",
"tags": [
{
"name": "@Smoke"
}
]
});
formatter.step({
"name": "user is on homePage",
"keyword": "Given "
});
formatter.match({
"location": "NavigationSteps.userIsOnHomePage()"
});
formatter.result({
"status": "passed"
});
formatter.step({
"name": "user click on tableDemoLink",
"keyword": "When "
});
formatter.match({
"location": "NavigationSteps.userClickOnTableDemoLink()"
});
formatter.result({
"status": "passed"
});
formatter.step({
"name": "title of tablePage is correct",
"keyword": "Then "
});
formatter.match({
"location": "NavigationSteps.titleOfTablePageIsCorrect()"
});
formatter.result({
"status": "passed"
});
formatter.step({
"name": "table is present",
"keyword": "And "
});
formatter.match({
"location": "NavigationSteps.tableIsPresent()"
});
formatter.result({
"status": "passed"
});
}); |
function show(id) {
document.getElementById('sky').setAttribute('src', '#' + id);
}
|
import React from 'react'
import { Container, Row} from 'react-bootstrap'
import FullName from './profile/FullName'
import Adress from './profile/Adress'
import ProfilePhoto from './profile/ProfilePhoto'
const Main = () => {
return (
<Container>
<Row className= "mt-3">
<ProfilePhoto/>
<FullName/>
<Adress/>
</Row>
</Container>
)
}
export default Main
|
const path = require("path");
const fs = require("fs");
const sass = require("sass");
function debounce(fn, wait) {
let timer = 0;
return () => {
if (!!timer) clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, arguments), wait);
};
}
const input = path.join(__dirname, "src", "scss", "apollo.scss");
const output = path.join(__dirname, "source", "style", "apollo.css");
function build() {
sass.render({ file: input, outputStyle: "compressed" }, (error, result) => {
if (error) throw error;
fs.writeFile(output, result.css, error => {
if (error) throw error;
});
});
console.log("build done");
}
function watch() {
console.log("start watch");
const debounceBuild = debounce(build, 5000);
fs.watch("./src", { recursive: true }, (event, file) => {
debounceBuild();
});
}
const operate = {
"--build": build,
"--watch": watch
};
for (const key of process.argv) {
if (key in operate) operate[key].call();
}
|
const Data={
products: [
{
id: '1',
name: "Nike Shirt",
image: "https://static.nike.com/a/images/c_limit,w_592,f_auto/t_product_v1/152648de-6352-4aff-a8d5-b72ac8868200/sportswear-mens-t-shirt-MK2TR1.png",
price: 10,
brand: "Nike",
rating: 4.5,
numReviews: 15,
description: "high quality product"
},
{
id: '2',
name: "Nike Shirt",
image: "https://static.nike.com/a/images/c_limit,w_592,f_auto/t_product_v1/152648de-6352-4aff-a8d5-b72ac8868200/sportswear-mens-t-shirt-MK2TR1.png",
price: 10,
brand: "Nike",
rating: 4.5,
numReviews: 10,
description: "high quality product"
},
{
id: '3',
name: "Nike Shirt",
image: "https://static.nike.com/a/images/c_limit,w_592,f_auto/t_product_v1/152648de-6352-4aff-a8d5-b72ac8868200/sportswear-mens-t-shirt-MK2TR1.png",
price: 10,
brand: "Nike",
rating: 4.5,
numReviews: 10,
description: "high quality product"
},
{
id: '4',
name: "Nike Shirt",
image: "https://static.nike.com/a/images/c_limit,w_592,f_auto/t_product_v1/152648de-6352-4aff-a8d5-b72ac8868200/sportswear-mens-t-shirt-MK2TR1.png",
price: 10,
brand: "Nike",
rating: 4.5,
numReviews: 10,
description: "high quality product"
},
{
id: '5',
name: "Nike Shirt",
image: "https://static.nike.com/a/images/c_limit,w_592,f_auto/t_product_v1/152648de-6352-4aff-a8d5-b72ac8868200/sportswear-mens-t-shirt-MK2TR1.png",
price: 10,
brand: "Nike",
rating: 4.5,
numReviews: 10,
description: "high quality product"
},
{
id: '6',
name: "Nike Shirt",
image: "https://static.nike.com/a/images/c_limit,w_592,f_auto/t_product_v1/152648de-6352-4aff-a8d5-b72ac8868200/sportswear-mens-t-shirt-MK2TR1.png",
price: 10,
brand: "Nike",
rating: 4.5,
numReviews: 10,
description: "high quality product"
}
]
};
export default Data; |
const Web3 = require('./web3/web3');
const EthereumTx = require('ethereumjs-tx')
const keythereum = require('keythereum');
const readlineSync = require('readline-sync');
const os = require('os');
const path = require('path');
const fs = require('fs');
const autoBind = require('auto-bind');
const url = require('url');
const XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;
const rlp = require('./rlp');
const ieleTranslator = require('./ieleTranslator');
const typeChk = require('./typeChk');
const IeleCompiler = require('./ieleCompiler');
const winston = require('winston');
const DailyRotateFile = require('winston-daily-rotate-file');
const uuidv4 = require('uuid/v4');
function thr0w(e) {
throw e;
}
function readSecret(prompt) {
const input = readlineSync.question(prompt, {
hideEchoBack: true,
mask: ' '
});
process.stdin.resume();
process.stdin.setRawMode(true)
return input;
}
function readPasswordOnce() {
return readSecret('Enter password: ');
}
function readPasswordTwice() {
const pass1 = readSecret('Enter password: ');
const pass2 = readSecret('Repeat password: ');
if (pass1 === pass2) {
return pass1;
} else {
throw 'Passwords did not match';
}
}
function encodeNumber(number) {
const bi = BigInt(number);
// how many bytes required to store the number (without sign)
const dim = function(n, l = 1n, r = 0n) {
if (n < 128n || n == 128n && r == 0n)
return l;
else {
return dim(n >> 8n, l + 1n, n & 255n);
}
}
const complement = bi >= 0 ? bi : (1n << (8n * dim(-bi))) + bi;
const reprStr = complement.toString(16);
const paddedStr = reprStr.length % 2 ? '0' + reprStr : reprStr;
const buf = Buffer.from(paddedStr, 'hex');
const signedBuf = buf[0] > 127 && bi > 0 ? Buffer.concat([Buffer.from([0]), buf]) : buf;
return signedBuf;
}
function decodeNumber(buffer) {
if (buffer.length == 0)
throw('decodeNumber: empty buffer');
else {
const makePositive = function(buf, pos = 0n) {
if (buf.length == 0)
return pos;
else {
const p = (pos << 8n) + BigInt(buf[0]);
return makePositive(buf.slice(1), p);
}
}
const isPositive = buffer[0] < 128;
const positive = makePositive(buffer);
if (isPositive)
return positive;
else {
const dim = 1n << BigInt(buffer.length * 8);
return positive - dim;
}
}
}
const testnets = {
evm: {
rpc: 'https://rpc-evm.portal.dev.cardano.org/',
faucet: 'https://faucet-evm.portal.dev.cardano.org/'
},
kevm: {
rpc: 'https://rpc-kevm.portal.dev.cardano.org/',
faucet: 'https://faucet-kevm.portal.dev.cardano.org/'
},
iele: {
rpc: 'https://iele-testnet.iohkdev.io:8546',
faucet: 'https://iele-testnet.iohkdev.io:8099/faucet',
compiler: 'https://remix-testnet.iele.mantis.iohkdev.io/remix/api'
}
}
function getUrls(base) {
const testnet = testnets[base]
if (testnet !== undefined) {
return testnet;
} else {
const custom = url.parse(base)
custom.port = 8099;
custom.host = null;
const faucet = url.resolve(url.format(custom), '/faucet');
return {rpc: base, faucet};
}
}
function createRequestLogger(logdir) {
const {combine, timestamp, label, prettyPrint} = winston.format;
const format = combine(label({ label: 'JSON-RPC' }), timestamp(), prettyPrint());
return winston.createLogger({
format: format,
transports: [
new DailyRotateFile({
filename: path.join(logdir, 'requests_%DATE%.log')
})
]
});
}
class Iele {
constructor(mallet) {
this._mallet = mallet;
this._compiler = new IeleCompiler(testnets.iele.compiler);
}
simpleTransfer(tx, password) {
if (!tx.to)
throw "'to' property must be defined (target address)"
tx.data = `0xc9876465706f736974c0` // RLP-encoded 'deposit' function with no args
return this._mallet.sendTransaction(tx, password)
}
callContract(tx, password) {
if (!tx.to)
throw "'to' property must be defined (target address)"
const func = tx.func !== undefined ? tx.func : thr0w("'func' property must be defined (contract function to be called)");
const args = (tx.args || []).map(n => encodeNumber(n));
tx.data = '0x' + rlp.encode([func, args]).toString('hex');
return this._mallet.sendTransaction(tx, password);
}
constantCall(tx) {
if (!tx.to)
throw "'to' property must be defined (target address)"
const func = tx.func !== undefined ? tx.func : thr0w("'func' property must be defined (contract function to be called)");
const args = (tx.args || []).map(n => encodeNumber(n));
tx.data = '0x' + rlp.encode([func, args]).toString('hex');
tx.func = undefined; // no idea why this is needed
tx.args = undefined;
const returnData = this._mallet.web3.eth.call(tx);
return rlp.decode(returnData).map(b => decodeNumber(b));
}
deployContract(tx, password) {
if (tx.code === undefined)
throw("'code' property must be defined (new contract's code)");
const code =
tx.code instanceof Buffer
? tx.code
: tx.code.startsWith('0x')
? Buffer.from(tx.code.substring(2), 'hex')
: Buffer.from(tx.code, 'hex')
const args = (tx.args || []).map(n => encodeNumber(n));
tx.data = '0x' + rlp.encode([code, args]).toString('hex');
return this._mallet.sendTransaction(tx, password);
}
enc(value, type) {
return BigInt(ieleTranslator.encode(value, {type: type}));
}
dec(value, type) {
const s = value.toString(16);
const v = s.length % 2 == 0 ? s : '0' + s;
const r = ieleTranslator.decode(v, {type: type});
if (r.rest.length > 0)
throw 'Unexpected conversion remainder: ' + JSON.stringify(r);
else
return r.result;
}
compile(mainSourcePath) {
return this._compiler.compile(mainSourcePath);
}
}
class Mallet {
constructor(url, datadir) {
this.datadir = datadir;
this.keystore = path.join(this.datadir, 'keystore');
this.logdir = path.join(this.datadir, 'logs');
[this.datadir, this.logdir, this.keystore].forEach(d => {
if (!fs.existsSync(d))
fs.mkdirSync(d);
});
const {rpc, faucet} = getUrls(url);
this.web3 = new Web3(new Web3.providers.HttpProvider(rpc), createRequestLogger(this.logdir));
this.faucetUrl = faucet;
this.selectedAccount = null;
this.lastTx = null;
this.iele = new Iele(this);
autoBind(this);
}
getBalance(addr) {
return this.web3.eth.getBalance(this.resolveAddress(addr)).toString();
}
newAccount(pass) {
const password = pass !== undefined ? pass : readPasswordTwice();
const dk = keythereum.create();
const keyObject = keythereum.dump(password, dk.privateKey, dk.salt, dk.iv);
keythereum.exportToFile(keyObject, this.keystore);
return keythereum.privateKeyToAddress(dk.privateKey);
}
listAccounts() {
const files = fs.readdirSync(this.keystore);
const pattern = /^UTC--.*--([0-9a-fA-F]{40})$/;
const accounts = files.filter(f => f.match(pattern)).map(f => '0x' + f.replace(pattern, '$1'));
return accounts;
}
importPrivateKey(keyHex, pass) {
const input = keyHex !== undefined ? keyHex : readSecret('Enter private key: ');
const prvKeyHex = input.startsWith('0x') ? input.substring(2) : input;
if (!keythereum.isHex(prvKeyHex) && !keythereum.isBase64(prvKeyHex)) {
throw 'Invalid key format';
} else {
const password = pass !== undefined ? pass : readPasswordTwice();
const randomBytes = keythereum.crypto.randomBytes(keythereum.constants.ivBytes + keythereum.constants.keyBytes);
const privateKey = keythereum.str2buf(prvKeyHex);
const iv = randomBytes.slice(0, keythereum.constants.ivBytes);
const salt = randomBytes.slice(keythereum.constants.ivBytes);
const keyObject = keythereum.dump(password, privateKey, salt, iv);
keythereum.exportToFile(keyObject, this.keystore);
return keythereum.privateKeyToAddress(privateKey);
}
}
selectAccount(addr) {
if (!this.listAccounts().includes(addr)) {
throw `No account with address ${addr} in keystore`;
} else {
this.selectedAccount = addr;
return addr;
}
}
currentAccount() {
return this.selectedAccount;
}
getNonce(addr) {
return this.web3.eth.getTransactionCount(this.resolveAddress(addr));
}
sendTransaction(tx, password) {
const from = this.resolveAddress(null);
const privateKey = this.recoverPrivateKey(from, password);
tx.gasPrice = tx.gasPrice || 5000000000;
tx.gasLimit = tx.gasLimit || tx.gas || thr0w('gas must be explicitly provided');
//Set default chainId if EIP-155 is used
//tx.chainId = tx.chainId === undefined ? 61 : tx.chainId;
tx.nonce = tx.nonce === undefined ? this.getNonce(from) : tx.nonce;
const ethTx = new EthereumTx(tx);
ethTx.sign(privateKey);
const serializedTx = ethTx.serialize();
const hash = this.web3.eth.sendRawTransaction('0x' + serializedTx.toString('hex'));
this.lastTx = tx;
this.lastTx.from = from;
this.lastTx.hash = hash;
return hash;
}
lastTransaction() {
return this.lastTx;
}
getReceipt(hash) {
const resolvedHash = hash || this.lastTx.hash || thr0w('No TX recorded');
const receipt = this.web3.eth.getTransactionReceipt(resolvedHash);
if (receipt && receipt.statusCode !== undefined) {
try {
const rawReturnData = receipt.returnData;
receipt.returnData = rlp.decode(rawReturnData).map(b => decodeNumber(b));
receipt.rawReturnData = rawReturnData;
} catch (e) {}
}
return receipt;
}
resolveAddress(addr) {
return addr || this.selectedAccount || thr0w('No account selected');
}
recoverPrivateKey(addr, pass) {
const keyObject = keythereum.importFromFile(addr, this.datadir);
const password = pass !== undefined ? pass : readPasswordOnce();
const key = keythereum.recover(password, keyObject);
return key.slice(Math.max(0, key.length - keythereum.constants.keyBytes));
}
requestFunds(addr) {
const address = this.resolveAddress(addr);
const queryUrl = this.faucetUrl;
const req_uuid = 'mallet_' + uuidv4();
const requestBody_ = {
jsonrpc: "2.0",
method: "faucet_sendFunds",
params: [ address ],
id: req_uuid
};
const requestBody = JSON.stringify(requestBody_);
const request = new XMLHttpRequest();
request.open('POST', queryUrl, false);
request.setRequestHeader("Content-Type","application/json");
request.send(requestBody);
if (request.status == 200) {
return request.responseText;
} else {
throw "Faucet error: " + request.responseText;
}
}
}
module.exports = Mallet;
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by an Apache-style license that can be
// found in the LICENSE file.
"use strict";
// FIXME(slightlyoff): Fetch the default policy from storage/preferences.
// chrome.storage.sync.set({defaultPolicy: defaultPolicy}, function() {});
// chrome.storage.sync.get(["defaultPolicy"], function(items) {});
var HEADER_NAME = "X-WebKit-CSP";
// FIXME(slighltyoff): stub for now!
var policyTypes = {
promsicuious:
"default-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; img-src 'self' data:;",
ssl:
"default-src https:; script-src https: 'unsafe-inline'; style-src https: 'unsafe-inline'",
};
var defaultPolicy = new csp.SecurityPolicy(policyTypes.promsicuious);
chrome.webRequest.onHeadersReceived.addListener(
function(details) {
// Parse whatever policy has been sent, merge it with our preferred policy,
// and set the union as the new CSP
// FIXME: should we try to be case-insenstitive here?
var cspHeaders = [];
var headers = [];
details.responseHeaders.forEach(function(h) {
((csp.SecurityPolicy.headerList.indexOf(h.name) != -1)
? cspHeaders : headers).push(h);
});
if (cspHeaders.length) {
var policies = cspHeaders.map(function(h) { return h.value; });
policies.unshift(defaultPolicy.policy);
var merged = csp.SecurityPolicy.merge.apply(null, policies);
// console.log("enforcing merged policy:", merged.policy);
headers.push({
// FIXME: should this be unprefixed now?
name: HEADER_NAME,
value: merged.policy,
});
} else {
// console.log("enforcing default policy:", defaultPolicy.policy);
headers.push({
// FIXME: should this be unprefixed now?
// name: "X-Content-Security-Policy",
name: HEADER_NAME,
value: defaultPolicy.policy,
});
}
return { responseHeaders: headers };
},
// filters
{
urls: ["<all_urls>"],
// May be:
// ["main_frame", "sub_frame", "stylesheet",
// "script", "image", "object",
// "xmlhttprequest", "other"]
//
// We only want to advertise CSP policy for the top-level and iframe
// navigations.
types: ["main_frame", "sub_frame"]
},
// extraInfoSpec
[ "responseHeaders", "blocking"]
);
// onBeforeRequest:
// We add a header to denote the CSP policy we'll enforce based on
// the user's preferences unless the site sends one.
chrome.webRequest.onBeforeSendHeaders.addListener(
function(info) {
info.requestHeaders.push({
name: "X-CriSP-Enforced-Policy",
value: defaultPolicy.toString()
})
},
// filters
{
urls: ["<all_urls>"],
// May be:
// ["main_frame", "sub_frame", "stylesheet",
// "script", "image", "object",
// "xmlhttprequest", "other"]
//
// We only want to advertise CSP policy for the top-level and iframe
// navigations.
types: ["main_frame", "sub_frame"]
},
// extraInfoSpec
[ "requestHeaders", "blocking" ]
);
/*
chrome.webRequest.onCompleted.addListener(function(object details) {...});
Fired when a request is completed.
Listener Parameters
details ( object )
tabId ( integer )
The ID of the tab in which the request takes place. Set to -1 if the request
isn't related to a tab.
parentFrameId ( integer )
ID of frame that wraps the frame which sent the request. Set to -1 if no
parent frame exists.
fromCache ( boolean )
Indicates if this response was fetched from disk cache.
url ( string )
ip ( optional string )
The server IP address that the request was actually sent to. Note that it may
be a literal IPv6 address.
statusLine ( optional string )
HTTP status line of the response.
frameId ( integer )
The value 0 indicates that the request happens in the main frame; a positive
value indicates the ID of a subframe in which the request happens. If the
document of a (sub-)frame is loaded (type is main_frame or sub_frame), frameId
indicates the ID of this frame, not the ID of the outer frame. Frame IDs are
unique within a tab.
requestId ( string )
The ID of the request. Request IDs are unique within a browser session. As a
result, they could be used to relate different events of the same request.
timeStamp ( double )
The time when this signal is triggered, in milliseconds since the epoch.
responseHeaders ( optional HttpHeaders )
The HTTP response headers that were received along with this response.
type ( enumerated string ["main_frame", "sub_frame", "stylesheet", "script",
"image", "object", "xmlhttprequest", "other"] )
How the requested resource will be used.
method ( string )
Standard HTTP method.
statusCode ( integer )
Standard HTTP status code returned by the server.
*/
/*
chrome.webRequest.onHeadersReceived.addListener(function(object deails) {...});
Fired when HTTP response headers of a request have been received.
Listener Parameters
deails ( object )
tabId ( integer )
The ID of the tab in which the request takes place. Set to -1 if the request
isn't related to a tab.
parentFrameId ( integer )
ID of frame that wraps the frame which sent the request. Set to -1 if no
parent frame exists.
url ( string )
timeStamp ( double )
The time when this signal is triggered, in milliseconds since the epoch.
statusLine ( optional string )
HTTP status line of the response.
frameId ( integer )
The value 0 indicates that the request happens in the main frame; a positive
value indicates the ID of a subframe in which the request happens. If the
document of a (sub-)frame is loaded (type is main_frame or sub_frame), frameId
indicates the ID of this frame, not the ID of the outer frame. Frame IDs are
unique within a tab.
requestId ( string )
The ID of the request. Request IDs are unique within a browser session. As a
result, they could be used to relate different events of the same request.
responseHeaders ( optional HttpHeaders )
The HTTP response headers that have been received with this response.
type (
enumerated string ["main_frame", "sub_frame", "stylesheet", "script", "image",
"object", "xmlhttprequest", "other"] )
How the requested resource will be used.
method ( string )
Standard HTTP method.
*/ |
import httpStatus from 'http-status';
import validation from 'express-validation';
import mongoose from 'mongoose';
import { ValidationError, APIError } from '../../helpers/errors';
export default (err, req, res, next) => {
let message;
if (err instanceof ValidationError) {
return next(err.toAPIError());
} else if (err instanceof mongoose.Error.ValidationError) {
message = Object.keys(err.errors).map(key => err.errors[key].message).join(' and ');
return next(new APIError(message, httpStatus.BAD_REQUEST));
} else if (err instanceof validation.ValidationError) {
message = err.errors.map(error => error.messages.join('. ')).join(' and ');
return next(new APIError(message, err.status));
} else if (!(err instanceof APIError)) {
return next(new APIError(err.message, err.status, err.isPublic));
}
return next(err);
};
|
"use strict";
const express = require("express");
const checkAccountSession = require("../controllers/account/check-account-session");
const createAccount = require("../controllers/account/create-account-controller");
const login = require("../controllers/account/login-controller");
const activate = require("../controllers/account/activate-account-controller")
const passwordRecovery = require("../controllers/account/password-recovery-controller");
const changePassword = require("../controllers/account/change-password-controllers");
const newActivationEmail = require("../controllers/account/new-activation-email-controller");
const logoutUser = require("../controllers/account/logout-account-controller");
const router = express.Router();
router.post("/v1/accounts", createAccount);
router.post("/v1/accounts/login", login);
router.put("/v1/accounts/activate/:verification_code", activate);
router.post("/v1/accounts/password/recovery", passwordRecovery);
router.post("/v1/accounts/password/change", checkAccountSession, changePassword);
router.post("/v1/accounts/email/activation/recovery", newActivationEmail);
router.post("/v1/accounts/logout", checkAccountSession, logoutUser);
module.exports = router; |
import Vue from 'vue'
import App from './App.vue'
Vue.config.productionTip = false
import './assets/iconfont/iconfont.css'
import './assets/scss/style.scss';
import router from './router'
import VueAwesomeSwiper from 'vue-awesome-swiper'
import 'swiper/dist/css/swiper.css'
Vue.use(VueAwesomeSwiper, /* { default global options } */)
import Card from './components/Card.vue';
Vue.component('m-card', Card)
import ListCard from './components/ListCard.vue';
Vue.component('m-list-card', ListCard)
import TopAd from './components/TopAd.vue';
Vue.component('Top-Ad', TopAd)
import Nav from './components/Nav.vue';
Vue.component('N-av', Nav)
//vant
import 'vant/lib/index.css';
import { Popup } from 'vant';
Vue.use(Popup);
import { Tab, Tabs, Toast } from 'vant';
Vue.use(Tab).use(Tabs).use(Toast);
import { Form, FormItem, Button, Input , InputNumber } from 'element-ui';
Vue.use(Form).use(FormItem).use(Button).use(Input).use(InputNumber);
import axios from 'axios'
Vue.prototype.$http = axios.create({
baseURL: process.env.VUE_APP_API_URL || '/web/api',
// baseURL: 'http://localhost:3000/web/api'
})
import VueWechatTitle from 'vue-wechat-title'
Vue.use(VueWechatTitle)
// 根据路由设置标题
router.beforeEach((to, from, next) => {
/*路由发生改变修改页面的title */
if(to.meta.title) {
document.title = to.meta.title
}
next();
})
new Vue({
router,
render: h => h(App)
}).$mount('#app') |
// 异常!!!
// 输出全局可用变量_dirname的值
console.log('文件的目录是:' + _dirname);
console.log('文件的绝对路径是:' + _filename);
|
import React from "react";
import { Link, Router } from "react-router-dom";
import { createBrowserHistory } from "history";
import "./App.css";
const defaultHistory = createBrowserHistory();
function App({ history }) {
console.log(window);
return (
<Router history={history || defaultHistory}>
<div className="App">
<header className="App-header">
<h1>App Two</h1>
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<Link to="/app-one">App One</Link>
<br />
<Link to="/app-one/view">App View</Link>
</header>
</div>
</Router>
);
}
export default App;
|
var isPwValid = false;
$(document).ready(function() {
$("#form_signup").submit(function(){
alert("hello");
});
$("#input_re_pw").change(function() {
if ($("#input_pw").val() == "") {
isPwValid = false;
return;
}
if ($("#input_pw").val() != $("#input_re_pw").val()) {
isPwValid = false;
$("#input_re_pw").css("border-color", "#91000e");
$("#input_re_pw").focus();
} else {
isPwValid = true;
$("#input_re_pw").css("border-color", "#cccccc");
}
});
$("#input_pw").change(function() {
if ($("#input_re_pw").val() == "") {
isPwValid = false;
return;
}
if ($("#input_pw").val() == $("#input_re_pw").val()) {
isPwValid = true;
$("#input_re_pw").css("border-color", "#cccccc");
} else {
isPwValid = false;
$("#input_re_pw").css("border-color", "#91000e");
$("#input_re_pw").focus();
}
});
}); |
export default class CurrencyUtil {
/**
* matchs a curancey code to a currancy symbol ex: usd->$
* @param {string} currency
* @returns string
*/
static getSymbol = (currency) => {
return currancy_symbols[currency.toLowerCase()] || '$'
}
/**
* converts cents to dollars
* @param {int} cents
* @returns int as dollars
*/
static convertCentToDollar = cents => cents / 100
}
const currancy_symbols = {
'usd': '$'
} |
const Recipe = require('../models/recipe');
// const { deleteOne } = require('../models/user');
module.exports = {
index,
create,
show,
update,
delete: deleteOne,
userRecipes
};
async function userRecipes(req, res) {
console.log('text', req.params.id);
const recipes = await Recipe.find({ 'user': req.params.id})
res.status(200).json(recipes);
}
async function index(req, res) {
const recipes = await Recipe.find({});
res.status(200).json(recipes);
}
async function create (req, res) {
const recipe = await Recipe.create(req.body);
res.status(201).json(recipe);
}
async function show (req, res) {
const recipe = await Recipe.findById(req.params.id);
res.status(200).json(recipe);
}
async function update(req, res) {
const updatedRecipe = await Recipe.findByIdAndUpdate(req.params.id, req.body, {new: true});
res.status(200).json(updatedRecipe);
}
async function deleteOne (req, res) {
console.log('hitting here')
const deletedRecipe = await Recipe.findByIdAndRemove(req.params.id);
res.status(200).json(deletedRecipe);
}
|
require('dotenv').config();
const express = require('express'),
session = require('express-session'),
massive = require('massive'),
bodyParser = require('body-parser'),
auth = require('./authentication')
prod = require('./productFunctions'),
orders = require('./orders');
const {
SERVER_PORT,
CONNECTION_STRING,
SESSION_SECRET
} = process.env
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.json());
massive(CONNECTION_STRING).then(db => {
app.set('db', db)
});
app.use(session({
secret: SESSION_SECRET,
resave: false,
saveUninitialized: true
}));
//Check if session exists
app.get('/auth/user', (req, res) => {
console.log(req.session.user)
req.session.user
? res.status(200).send(req.session.user)
: res.status(401).send('Not signed in')
})
//Authentication endpoints
app.post('/auth/addUser', auth.register);
app.post('/auth/login', auth.login);
app.post('/auth/logout', auth.logout);
app.get('/auth/getUsers', auth.getUsers)
//Product Management Endpoints
app.post('/api/addProduct', prod.addProduct)
app.get('/api/getProducts', prod.getProducts)
app.get('/api/product/:id', prod.getProduct)
app.delete('/api/product/:id', prod.deleteProduct)
//Shipping
app.get('/api/getOrders', orders.getOrders)
app.put('/api/fulfill/:id', orders.fulfill)
app.get('/api/orderItems/:id', orders.getOrderItems)
app.listen(SERVER_PORT, () => {
console.log('Running on: ', SERVER_PORT)
}) |
var mongoose = require('mongoose')
var orderItems = new mongoose.Schema({
orderCompany : { type: String, default: '' },
projectName : { type: String, default: '' },
items : [{
itemNumber : { type: String, default: '' },
standard : { type: String, default: '' },
cadNumber : { type: String, default: '' },
size : { type: String, default: '' },
itemName : { type: String, default: '' },
totalQuantity : { type: Number, default: '' },
requestingWork : [],
companyinfo : {
productionCompany : { type: String, default: '' },
releaseCompany : { type: String, default: '' }
},
price: {
SBB : Number,
EP : Number,
PC : Number,
CP : Number,
BI : Number,
tangse : Number,
backing : Number,
pv : Number,
acidCleaning : Number,
},
record : [{
recordNo : {type: Number, default: 0 },
chackInTime : Date,
chackOutTime : Date,
quantity : {type: Number, default: 0 } ,
recordStats : {type: String, default: ''}
}],
shippingFee : Number,
itemsStats : { type: Number, default: 0 }, //0 등록안됨 1 입고됨 2 출고됨 3 마감완료 4반송
exprectedChackInTime : Date,
exprectedChackOutTime : Date,
memo : { type: String, default: '' },
deadline : {type: String, default: ''}
}]
})
orderItems = mongoose.model('orderItems', orderItems);
module.exports = orderItems; |
//tabs.js
import React from 'react';
import {
View, Text,
TouchableOpacity
} from 'react-native';
import s from './style'
const tw = (imanagerTab,tab)=>imanagerTab===tab?[s.bfwTap,s.bfw]:s.bfw
const bf = (imanagerTab,tab)=>imanagerTab===tab?[s.bf,s.bfTap]:s.bf
const Tabs = ({imanagerTab,switchImanagerTab}) => (
<View style={s.ctnr}>
<View><TouchableOpacity onPress={()=>switchImanagerTab(1)} style={s.btn}>
<View style={tw(imanagerTab,1)}>
<Text style={bf(imanagerTab,1)} allowFontScaling={false}>已上架</Text>
</View></TouchableOpacity></View>
<View><TouchableOpacity onPress={()=>switchImanagerTab(2)} style={s.btn}>
<View style={tw(imanagerTab,2)}>
<Text style={bf(imanagerTab,2)} allowFontScaling={false}>未上架</Text>
</View></TouchableOpacity></View>
<View><TouchableOpacity onPress={()=>switchImanagerTab(3)} style={s.btn}>
<View style={tw(imanagerTab,3)}>
<Text style={bf(imanagerTab,3)} allowFontScaling={false}>已告罄</Text>
</View></TouchableOpacity></View>
<View><TouchableOpacity onPress={()=>switchImanagerTab(4)} style={s.btn}>
<View style={tw(imanagerTab,4)}>
<Text style={bf(imanagerTab,4)} allowFontScaling={false}>仓库中</Text>
</View></TouchableOpacity></View>
</View>
);
export default Tabs
|
// Code Challenge #1
// If I give you a string of repeating characters, return a string each character following by the number of times it occurs.
// Example: “aabbbc” => “a2b3c1”
const defaultString = 'abccggddauuj'
let reduceObj = defaultString.split('').reduce((acc, value)=>{
return {
...acc,
[value]: acc[value]? acc[value]+1 : 1
}
},{})
console.log(reduceObj)
const output = Object.entries(reduceObj).flat().join('')
console.log('entries-ouput',Object.entries(reduceObj))
console.log('entries-flat-ouput',Object.entries(reduceObj).flat())
console.log(output)
const defaultString2 = 'hhhhkddkkkfhiiz'
const obJStore = {};
const anotherWay = defaultString2.split("").forEach((value) => {
obJStore[value] = obJStore[value] ? obJStore[value] + 1 : 1;
});
const output2 = Object.entries(obJStore).flat().join("");
console.log(output2); |
const express = require('express');
const router = express.Router();
const path = require('path');
const async = require('async');
const category = require('../proxy/category');
const tool = require('../utility/tool');
router.get('/', (req, res, next) => {
async.parallel([
// 获取配置
function (cb) {
tool.getConfig(path.join(__dirname, '../config/settings.json'), (err, settings) => {
if (err) {
cb(err);
} else {
cb(null, settings);
}
});
},
// 获取分类
function (cb) {
category.getAll((err, categories) => {
if (err) {
cb(err);
} else {
cb(null, categories);
}
});
}
], (err, results) => {
let settings,
categories;
if (err) {
next(err);
} else {
settings = results[0];
categories = results[1];
res.render('blog/index', {
cateData: categories,
settings,
title: settings.SiteName,
currentCate: '',
isRoot: true
});
}
});
});
module.exports = router;
|
import React from 'react';
import styled from 'styled-components';
import PropTypes from 'prop-types';
import EyeHideSVG from '../../svg/eye-hide.svg';
import EyeShowSVG from '../../svg/eye-show.svg';
const FilterMinMaxContainer = styled.section`
width: 100%;
display: grid;
grid-template-columns: 20% 30% 20% 30%;
grid-template-rows: 20px 26px 20px;
row-gap: 2px;
grid-template-areas:
'. . . m-show-hide-icon'
'm-title m-min-input m-to m-max-input'
'. m-min-value-info . m-max-value-info';
label {
font-family: 'HelveticaNeue-Thin';
color: #000;
}
* {
justify-self: center;
align-self: center;
}
input {
height: 26px;
width: 80%;
background: white;
border: 1px solid black;
font-family: 'HelveticaNeue-Thin';
color: #000;
font-size: 14px;
justify-self: end;
padding-left: 10px;
}
`;
const Title = styled.label`
grid-area: m-title;
font-size: 14px;
justify-self: start;
`;
const MinInput = styled.input`
grid-area: m-min-input;
`;
const MinValueInfo = styled.label`
grid-area: m-min-value-info;
font-size: 10px;
justify-self: end;
align-self: start;
`;
const To = styled.label`
grid-area: m-to;
font-size: 14px;
`;
const MaxInput = styled.input`
grid-area: m-max-input;
`;
const MaxValueInfo = styled.label`
grid-area: m-max-value-info;
font-size: 10px;
justify-self: end;
align-self: start;
`;
const ShowHideButton = styled.button`
grid-area: m-show-hide-icon;
display: flex;
justify-content: center;
align-items: center;
`;
const FilterMinMax = ({
title,
minLimit,
maxLimit,
minInputValue,
maxInputValue,
showTo,
minChanged,
maxChanged,
showToChanged,
}) => {
const handleMinInputChange = (event) => {
if (event.target.value.match(/^[0-9]*$/g)) {
minChanged(event.target.value);
}
};
const handleMaxInputChange = (event) => {
if (event.target.value.match(/^[0-9]*$/g)) {
maxChanged(event.target.value);
}
};
const handleShowTo = () => {
showToChanged(!showTo);
};
return (
<FilterMinMaxContainer>
<Title>{title}:</Title>
<MinInput
value={minInputValue}
onChange={handleMinInputChange}
data-testid={`${title}-filterminmax-min-input`}
/>
{showTo && <MinValueInfo>min: {Math.floor(minLimit)}</MinValueInfo>}
{showTo && <To>to</To>}
{showTo && (
<MaxInput
value={maxInputValue}
onChange={handleMaxInputChange}
data-testid={`${title}-filterminmax-max-input`}
/>
)}
{showTo && <MaxValueInfo>max: {Math.ceil(maxLimit)}</MaxValueInfo>}
<ShowHideButton
onClick={handleShowTo}
data-testid={`${title}-filterminmax-show-hide-button`}
>
{!showTo && <EyeShowSVG width={11.43}></EyeShowSVG>}
{showTo && <EyeHideSVG width={11.43}></EyeHideSVG>}
</ShowHideButton>
</FilterMinMaxContainer>
);
};
FilterMinMax.propTypes = {
title: PropTypes.string.isRequired,
minLimit: PropTypes.number.isRequired,
maxLimit: PropTypes.number.isRequired,
minInputValue: PropTypes.string.isRequired,
maxInputValue: PropTypes.string.isRequired,
showTo: PropTypes.bool,
minChanged: PropTypes.func.isRequired,
maxChanged: PropTypes.func.isRequired,
showToChanged: PropTypes.func.isRequired,
};
FilterMinMax.defaultProps = {
showTo: true,
};
export default FilterMinMax;
|
import React from 'react';
const DisplayBox = ({ selectedProduct }) => {
return (
<div id="displayBox">
<img className="displayImg" src={selectedProduct.image} />
<div className="displayDetails">
<h4>{selectedProduct.name} <span>({selectedProduct.year})</span></h4>
<div className="scrollBox">
<p>{selectedProduct.description}</p>
</div>
<div className="footer">
<p>Rating: {selectedProduct.rating} / 10 stars</p>
</div>
<div className="footer">
<p>Price: ${selectedProduct.price.toFixed(2)}</p>
</div>
<div className="footer">
<p>Runtime: {selectedProduct.runtime} minutes</p>
</div>
<div className="footer">
<button className="add-to-cart" data-id={selectedProduct.id}>Add To Cart</button>
</div>
</div>
</div>
);
}
export default DisplayBox; |
import * as React from 'react';
import {NavigationContainer} from '@react-navigation/native';
import {createNativeStackNavigator} from '@react-navigation/native-stack';
import {AppBottomTab} from './src/navigation';
const Stack = createNativeStackNavigator();
export default function App() {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen
options={{
headerShown: false,
}}
name="AppBottomTab"
component={AppBottomTab}
/>
</Stack.Navigator>
</NavigationContainer>
);
}
|
const LocalStrategy = require("passport-local").Strategy;
const uniqid = require('uniqid');
const db = require('../db');
const bcrypt = require('bcrypt');
const invalid = function(input) {
if(input === null || input === undefined || input === '')
{
return true;
}
return false;
}
module.exports = function(passport) {
passport.serializeUser(function(_ID, callback) {
return callback(null, _ID);
});
passport.deserializeUser(function(_ID, callback) {
db.query('SELECT * FROM users WHERE _ID = ?', [_ID]).then((rows) => {
if (rows.length) {
return callback(null, rows[0]._ID);
} else {
return callback(null, false);
}
}).catch(function(err) {
console.log(err);
return callback(null, false);
})
});
passport.use(
"local-signup",
new LocalStrategy({
usernameField : "username",
passwordField : "password",
passReqToCallback : true
},
function(req, username, password, callback) {
if(invalid(username) || invalid(password))
{
return callback('Missing credentials', false, null);
}
if(!/^[a-z0-9]+$/i.test(username))
{
return callback('Name must contain only alphanumeric values', false, null);
}
if(username.length < 8)
{
return callback('Username must contain at least 8 characters', false, null);
}
if(password.length < 8)
{
return callback('Password must contain at least 8 characters', false, null);
}
let _ID = uniqid();
let hashedPassword = bcrypt.hashSync(password, '$2b$10$cKG.wf1rAo3qVV3o6uBkSO');
db.query('SELECT * FROM users WHERE username = ?', [username]).then((rows) => {
if(rows.length)
{
return callback('Name is already taken.', false, null);
}
db.query('INSERT INTO users (_ID, username, password) VALUES (?, ?, ?)', [_ID, username, hashedPassword]).then(() => {
return callback(null, {username});
}).catch((err) => {
return callback('Something went wrong.', false, null);
})
}).catch((err) => {
return callback('Something went wrong.', false, null);
})
})
);
passport.use(
"local-signin",
new LocalStrategy({
usernameField : "username",
passwordField : "password",
passReqToCallback : true
},
function(req, username, password, callback) {
if(invalid(username) || invalid(password))
{
return callback('Missing credentials', false, null);
}
db.query('SELECT * FROM users WHERE username = ?', [username]).then((rows) => {
if(!rows.length)
{
return callback('User not found.', false, null);
}
if(!bcrypt.compareSync(password, rows[0].password))
{
return callback('Invalid password.', false, null);
}
return callback(null, rows[0]._ID);
}).catch((err) => {
return callback('Something went wrong.', false, null);
})
})
);
};
|
var orderItemMapping = {
"Items": {
key: function(item) {
return ko.utils.unwrapObservable(item.Id);
},
create: function(options) {
return new ItemViewModel(options.data);
}
}
};
ItemViewModel = function (data) {
var self = this;
ko.mapping.fromJS(data, orderItemMapping, self);
self.ExtPrice = ko.computed(function () {
return (self.Quantity()*self.Price()).toFixed(2);
});
};
OrderViewModel = function (data) {
var self = this;
//self.Id = ko.observable(data.id);
//self.CustomerName = ko.observable(data.CustomerName);
//self.PONumber = ko.observable(data.PONumber);
//self.MessageToClient = ko.observable(data.MessageToClient);
ko.mapping.fromJS(data, orderItemMapping, self);
self.save = function () {
$.ajax({
url: '/Orders/Save/',
type: 'POST',
data: ko.toJSON(self),
contentType: 'application/json'
}).done(function(data) {
ko.mapping.fromJS(data, {}, self);
})
.fail(function () {
alert("error while saving");
});
};
self.remove = function () {
$.ajax({
url: '/Orders/Delete/',
type: 'POST',
data: ko.toJSON(self),
contentType: 'application/json'
}).done(function(data) {
if (data.newLocation != null) {
window.location = data.newLocation;
}
})
.fail(function() {
alert("error while deleting");
});
};
self.addItem = function() {
var item = new ItemViewModel({
Code: "",
Quantity: 1,
Price: 0
});
self.Items.push(item);
};
self.deleteItem = function () {
self.Items.remove(this);
};
self.Total = ko.computed(function () {
var total = 0;
ko.utils.arrayForEach(self.Items(), function(item) {
total += parseFloat(item.ExtPrice());
});
return total.toFixed(2);
});
self.TotalCount = ko.computed(function () {
var count = 0;
ko.utils.arrayForEach(self.Items(), function(item) {
count += item.Quantity();
});
return count;
});
self.AvgItemPrice = ko.computed(function() {
var avg = self.Total() / self.TotalCount();
return avg.toFixed(2);
});
}; |
var xmlHttp;
var inc_Q_id_Answer;
var Answer_chooz="O";
var answer_found_to_mark;
var quest_details="";
var time_remain_alert = 0;
function openloader(){
document.getElementById("error").innerHTML ='<img src="Server_Pictures_Print/images/loader.gif" class="img-responsive" alt="Uploading...."/>';
document.getElementById("error1").innerHTML ='<img src="Server_Pictures_Print/images/loader.gif" class="img-responsive" alt="Uploading...."/>';
}
function closeloader(){
document.getElementById("error").innerHTML ='';
document.getElementById("error1").innerHTML ='';
}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
function validate_questions()
{
question_remain_message="";
quest_details="";
var last_question = document.getElementById('Q_id_total').innerHTML;
last_question = new Number(last_question);
var Question_not_ansa = 0;
for (var i=1; i<=last_question; i++)
{
var p_ansa_id_2 = i + "A";
if (document.getElementById(p_ansa_id_2).innerHTML=="O")
{
Question_not_ansa = Question_not_ansa + 1;
quest_details = quest_details + i + ", ";
}
}
//alert ("you have not answer = " + Question_not_ansa);
if (Question_not_ansa > 0){
question_remain_message ="And You Have Not ANSWER " + Question_not_ansa + " Question's - which are \n Question : " + quest_details;
}else{
question_remain_message="";
}
var r=confirm("Are You sure You want to Submit the Exam ... \nYou still have Some Time Left " + question_remain_message+ "\n\nClick OK to Submit \nor \nClick CANCEL to Continue with the Exam");
if (r==true)
{
document.forms["quizform"].submit();
}
else
{
return false;
}
}
function Previous()
{
var q_id_no = document.getElementById("Q_id").innerHTML;
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
alert ("Your browser does not support AJAX!");
return;
}
/*&"?status="+kkk*/
var url="Question_Ajax_Script.php";
url=url+"?Q_id="+inc_Q_id_Answer+"&answer_chooz="+Answer_chooz+"¤t_id="+q_id_no;
xmlHttp.onreadystatechange=QuestionChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
//########################################### by question navigator ########################################
function Mark_choice_question(question_id_chooz)
{
openloader();
inc_Q_id_Answer = question_id_chooz;
var new_id = document.getElementById("Q_id").innerHTML;
var p_ansa_id = new_id + "A";
if (document.getElementById("A").checked==true){
Answer_chooz = "A";
}else if (document.getElementById("B").checked==true){
Answer_chooz = "B";
}
else if (document.getElementById("C").checked==true){
Answer_chooz = "C";
}else if(document.getElementById("D").checked==true){
Answer_chooz = "D";
}
else{
Answer_chooz = "O";
}
document.getElementById(p_ansa_id).innerHTML = Answer_chooz;
Previous();
}
//########################################### MARK WHEN AT THE LAST QUESTION - TO TICK AGAINST THE DIALOG BOX MSG ########################################
function Mark_choice_current_question()
{
var new_id = document.getElementById("Q_id").innerHTML;
var p_ansa_id = new_id + "A";
if (document.getElementById("A").checked==true){
Answer_chooz = "A";
}else if (document.getElementById("B").checked==true){
Answer_chooz = "B";
}
else if (document.getElementById("C").checked==true){
Answer_chooz = "C";
}else if(document.getElementById("D").checked==true){
Answer_chooz = "D";
}
else{
Answer_chooz = "O";
}
document.getElementById(p_ansa_id).innerHTML = Answer_chooz;
}
//########################################### by next and previous ########################################
function Mark_choice(determine_n_p)
{
openloader();
var new_id = document.getElementById("Q_id").innerHTML;
var p_ansa_id = new_id + "A";
if (document.getElementById("A").checked==true){
Answer_chooz = "A";
}else if (document.getElementById("B").checked==true){
Answer_chooz = "B";
}
else if (document.getElementById("C").checked==true){
Answer_chooz = "C";
}else if(document.getElementById("D").checked==true){
Answer_chooz = "D";
}
else{
Answer_chooz = "O";
}
document.getElementById(p_ansa_id).innerHTML = Answer_chooz;
var Q_id_total = document.getElementById('Q_id_total').innerHTML;
Q_id_total = new Number(Q_id_total);
//alert(Q_id_total);
inc_Q_id_Answer = 0;
if (determine_n_p =="previous")
{
if (new_id <= 1)
{
//highest number of question is Q_id_total
inc_Q_id_Answer = Q_id_total;
}
else
{
inc_Q_id_Answer = new Number(new_id) - 1;
}
}
//next
if (determine_n_p =="next")
{
if (new_id == Q_id_total)
{
//lowest number of question is 1
inc_Q_id_Answer = 1;
}
else
{
inc_Q_id_Answer = new Number(new_id) + 1;
}
}
Previous();
}
//###################################################################################
/* when Question is change*/
function QuestionChanged()
{
if (xmlHttp.readyState==4)
{
document.getElementById("Question_Container").innerHTML="";
document.getElementById("Question_Container").innerHTML=xmlHttp.responseText;
document.getElementById("Q_id").innerHTML = inc_Q_id_Answer;
document.getElementById("Q_id2").innerHTML = inc_Q_id_Answer;
//change the color of the question in navigation
document.getElementById(inc_Q_id_Answer).style.color="black";
inc_Q_id_Answer3 = inc_Q_id_Answer + "A";
answer_found_to_mark = document.getElementById(inc_Q_id_Answer3).innerHTML;
//alert(answer_found_to_mark);
closeloader();
if(answer_found_to_mark =="A")
{
document.getElementById("A").checked=true;
}
else if(answer_found_to_mark =="B")
{
document.getElementById("B").checked=true;
}
else if(answer_found_to_mark =="C")
{
document.getElementById("C").checked=true;
}
else if(answer_found_to_mark =="D")
{
document.getElementById("D").checked=true;
}
else
{
document.getElementById("O").checked=true;
}
}
}
v |
'use strict';
angular.module('myApp.dashboard', ['ngRoute','ui.bootstrap','myApp.data-access','ui.filters'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/dashboard', {
templateUrl: 'dashboard/dashboard.html',
controller: 'DashboardCtrl'
});
}])
.controller('DashboardCtrl', function($scope,trafficMeister) {
var data = {};
$scope.isBrandSelected = false;
$scope.isTypeSelected = false;
trafficMeister.fetchData()
.success(function(dataSuccess){
$scope.vehicleInformation = dataSuccess;
data = dataSuccess;
})
.error(function(){
console.log("Error Occured");
});
$scope.showVehicleInformation = function (vehicleInfo){
$scope.brandOptions = [];
for (var i = 0; i < data.length; i++) {
if(vehicleInfo.type == data[i].type){
$scope.brandOptions.push(data[i].brand)
}
}
$scope.isTypeSelected = true;
}
$scope.showVehicleInformationBrand = function(vehicleInfo){
$scope.colorOptions = [];
var colors = [];
for (var i = 0; i < data.length; i++) {
if(vehicleInfo == data[i].brand){
for (var j = 0; j < data[i].colors.length; j++) {
console.log(data[i].colors[j]);
$scope.colorOptions.push(data[i].colors[j])
}
$scope.vehicleImg = data[i].img;
}
}
$scope.isBrandSelected = true;
}
});
|
import axios from 'axios'
const VueAxios = {
install: function(Vue){
if (this.installed) return;
this.installed = true;
Vue.axios = axios;
Object.defineProperty(Vue.prototype, "$http",{
get() {
return axios
}
})
}
}
export default VueAxios |
import { Alert } from "bootstrap";
import React, { Component } from "react"
import { Link } from "react-router-dom";
export default class Login extends Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.handleFormSubmit = this.handleFormSubmit.bind(this);
this.state = {
UserName1: '',
}
}
handleChange= (e)=> {
this.setState({[e.target.name]:e.target.value});
}
// on form submit...
handleFormSubmit(e) {
e.preventDefault()
localStorage.setItem('document',JSON.stringify(this.state));
}
// React Life Cycle
componentDidMount() {
this.documentData = JSON.parse(localStorage.getItem('document'));
if (localStorage.getItem('document')) {
this.setState({
UserName1: this.documentData.UserName1,
})
} else {
this.setState({
UserName1: '',
})
}
}
login() {
//alert("Login Called");
//console.warn(this.state)
fetch('https://userapiforltiproject.azurewebsites.net/api/Token/Authenticate',
{
method: "POST",
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(this.state)
}).then((result) => {
result.json().then((resp) => {
var token = JSON.parse(resp).access_token
var role = JSON.parse(resp).Role
var User_Validity = JSON.parse(resp).Error
if (User_Validity == "unauthorized") {
alert("Invalid Username and Password")
}
else if (User_Validity === "None") {
//localStorage.setItem(this.state.UserName1, JSON.stringify(token))
localStorage.setItem("Token", JSON.stringify(token))
//console.warn(this.state.UserName1, JSON.stringify(resp));
if (role == "Admin") {
window.location = "/Details"
//alert("This is admin")
}
else if (role == "User") {
window.location = "/Hosttimer"
//alert("This is usser")
}
}
})
})
}
render() {
return (
<form className="form" onSubmit = {this.handleFormSubmit}>
<h1>Login Form</h1>
<br />
<div>
<label><b>UserName</b></label>
<input type="text" ref="UserName1" placeholder="Username" name = "UserName1" Value={this.state.UserName1} onChange= {this.handleChange}></input>
</div>
<br />
<div>
<label><b>Password</b></label>
<input type="password" ref="password" placeholder="Password" onChange={(e) => { this.setState({ UserPassword: e.target.value }) }}></input>
</div>
<br />
<div>
<button onClick={() => this.login()} className= "btn btn-secondary" >Login</button>
</div>
<br />
<div>
<Link to = "/CNA">
<p>Create New Account</p>
</Link>
</div>
</form>
);
}
}
|
import React from "react";
import ComingSoon from "./ComingSoon";
function Help() {
return (
<>
<ComingSoon />
</>
);
}
export default Help;
|
import configuration from "../../lib/configuration";
import profile from "../../lib/profile";
import chai from "chai";
import chaiAsPromise from "chai-as-promised";
import _ from "lodash";
chai.use(chaiAsPromise);
const expect = chai.expect;
const assert = chai.assert;
describe("Profile", () => {
it("getNightwatchConfig", () => {
const argv = {
seleniumgrid_host: "FAKE_HOST",
seleniumgrid_port: "4444"
};
configuration.validateConfig({}, argv);
const config = profile.getNightwatchConfig({ desiredCapabilities: { browser: "chrome" } });
expect(config.selenium_host).to.equal(argv.seleniumgrid_host);
expect(config.selenium_port).to.equal(argv.seleniumgrid_port);
expect(config.desiredCapabilities.browser).to.equal("chrome");
});
describe("getProfiles", () => {
it("with seleniumgrid_browser", () => {
const argvMock = {
seleniumgrid_browser: "chrome"
};
const opts = {
settings: {
testFramework: {
profile: {
getProfiles: (browsers) => {
return [{
desiredCapabilities: { browserName: 'chrome' },
executor: 'seleniumgrid',
id: 'chrome'
}];
}
}
}
}
};
return profile
.getProfiles(opts, argvMock)
.then((p) => {
expect(p.length).to.equal(1);
expect(p[0].desiredCapabilities.browserName).to.equal("chrome");
expect(p[0].executor).to.equal("seleniumgrid");
expect(p[0].id).to.equal("chrome");
})
.catch(err => assert(false, "getProfile isn't functional" + err));
});
it("with seleniumgrid_browsers", () => {
const argvMock = {
seleniumgrid_browsers: "chrome,safari"
};
const opts = {
settings: {
testFramework: {
profile: {
getProfiles: (browsers) => {
return [{
desiredCapabilities: { browserName: 'chrome' },
executor: 'seleniumgrid',
id: 'chrome'
}, {
desiredCapabilities: { browserName: 'safari' },
executor: 'seleniumgrid',
id: 'safari'
}];
}
}
}
}
};
return profile
.getProfiles(opts, argvMock)
.then((p) => {
expect(p.length).to.equal(2);
expect(p[0].desiredCapabilities.browserName).to.equal("chrome");
expect(p[0].executor).to.equal("seleniumgrid");
expect(p[0].id).to.equal("chrome");
expect(p[1].desiredCapabilities.browserName).to.equal("safari");
expect(p[1].executor).to.equal("seleniumgrid");
expect(p[1].id).to.equal("safari");
})
.catch(err => assert(false, "getProfile isn't functional" + err));
});
it("without seleniumgrid_browsers or seleniumgrid_browser", () => {
let argvMock = {};
const opts = {
settings: {
testFramework: {
}
}
};
return profile
.getProfiles(opts, argvMock)
.then((p) => {
expect(p.length).to.equal(1);
expect(p[0].executor).to.equal("seleniumgrid");
expect(p[0].id).to.equal("mocha");
})
.catch(err => assert(false, "getProfile isn't functional" + err));
});
});
describe("getCapabilities", () => {
it("succeed", () => {
const argvMock = {
seleniumgrid_browsers: "chrome,safari"
};
const opts = {
settings: {
testFramework: {
profile: {
getCapabilities: (profile) => {
return {
desiredCapabilities: { browserName: 'chrome' },
executor: 'seleniumgrid',
id: 'chrome'
};
}
}
}
}
};
return profile
.getCapabilities(null, opts)
.then((p) => {
expect(p.executor).to.equal("seleniumgrid");
expect(p.id).to.equal("chrome");
})
.catch(err => assert(false, "getProfile isn't functional" + err));
});
it("default", () => {
let opts = {
settings: {
testFramework: {
}
}
};
return profile
.getCapabilities("chrome", opts)
.then((p) => {
expect(p.executor).to.equal("seleniumgrid");
expect(p.id).to.equal("mocha");
})
.catch(err => assert(false, "getCapabilities isn't functional" + err));
});
it("listBrowsers", (done) => {
let opts = {
settings: {
testFramework: {
profile: {
listBrowsers: () => { return ["chrome"]; }
}
}
}
};
return profile
.listBrowsers(opts, () => {
done();
});
});
it("mocha listBrowsers", (done) => {
let opts = {
settings: {
testFramework: {
}
}
};
return profile
.listBrowsers(opts, () => {
done();
});
});
});
}); |
$(document).ready(function(){
getLocation();
// Button swaps units between C and F when clicked
$('#button').click(function(){
var currTemp = $('#temp').html();
var tempNum = parseInt(currTemp);
var tempUnits;
if (currTemp.indexOf("F") >= 0){
tempUnits = "C";
tempNum = Math.round((tempNum -32) * (5/9));
}
else if (currTemp.indexOf("C") >= 0){
tempUnits = "F";
tempNum = Math.round((tempNum * 1.8) + 32);
}
$('#temp').html(tempNum + " °" + tempUnits); // Reset #temp with converted data
}); // End button
})
/** Get user location data **/
function getLocation() {
$.ajax({
url: "https://www.googleapis.com/geolocation/v1/geolocate?key=AIzaSyBJCvxEmi2PsLS9HTTnwkw07UyTsLO-WB0",
type: "POST",
success: function (response) {
getLocalWeather(response);
},
error: function () {
alert("Error: Unable to retrieve data from remote server");
}
});
}
/** Get localized weather data **/
function getLocalWeather(response) {
var apiURL = "http://api.openweathermap.org/data/2.5/weather?";
var lat = "lat=" + response.location.lat + "&";
var lng = "lon=" + response.location.lng + "&";
var appID = "appid=8a755c3903379d7e690ec63d41cb5528&units=imperial";
var fullURL = apiURL + lat + lng + appID;
$.ajax({
url: fullURL,
type: "POST",
dataType: "jsonp",
success: function(response) {
updatePage(response);
},
error: function (){
alert("Error: Unable to retrieve data from remote server");
}
});
}
/** Update page with current local weather data **/
function updatePage (weatherData) {
var userCity = weatherData.name;
var currentTemp = Math.round(weatherData.main.temp) + " °F";
var currentWeather = weatherData.weather[0].main;
// Update elements with current weatherData
$('#location').html(userCity);
$('#temp').html(currentTemp);
$('#weather').html(currentWeather);
// Retrieve icon for current weatherData and update element
var apiURL = "http://openweathermap.org/img/w/";
var iconID = weatherData.weather[0].icon;
var fileType = ".png";
var fullURL = apiURL + iconID + fileType;
$('#icon').attr("src", fullURL);
var bgCondition;
// Use the weather icon ID numbers to match general weather condition categories to bg images
var weatherID = parseInt(iconID); // strip everything but the number value from iconID
if (weatherID == 1)
bgCondition = "clear";
else if (weatherID >= 2 && weatherID<= 4)
bgCondition = "cloudy";
else if (weatherID >= 9 && weatherID<= 10)
bgCondition = "rain";
else if (weatherID == 13)
bgCondition = "snow";
else if (weatherID == 50)
bgCondition = "fog";
else if (weatherID == 11)
bgCondition = "storm";
$("body").css("background-image","url('images/" + bgCondition + ".jpg')");
};
|
import React from 'react'
import TodoListItem from './todo-list-item'
const TodoList = ({ todos, trigger, deleteItem }) => {
const items = todos.map(t => (
<TodoListItem {...t}
deleteItem={() => deleteItem(t.key)}
triggerImportant={() => trigger('important', t.key)}
triggerDone={() => trigger('done', t.key)} />
))
return (
<ul className="list-group">
{items}
</ul>
)
}
export default TodoList;
|
const Appacitive = require('appacitive');
const promise = Appacitive.initialize({
apikey: "MEk6aMTDtliwwwQvQgT7GXNS+Ak8P7FI6Q/pqYTpgVY=",
env: "sandbox",
appId: "168002687610258053"
});
function contractUserObject(userData) {
let user = {};
user.username = userData.username;
user.password = userData.password;
user.firstname = userData.firstname;
return user
}
async function getUserLists(user) {
var list = [];
var query = user.getConnectedObjects({
relation: 'owns', //mandatory
returnEdge: false,
label: 'lists', //mandatory
});
let queryResult = await query.fetch()
for (let i = 0; i < queryResult.length; i++) {
list[i] = queryResult[i].get("name")
}
return list
}
module.exports = {
createUser: async function (userData) {
var userObject = contractUserObject(userData)
try {
let addResult = await Appacitive.Users.createUser(userObject)
let userID = addResult.get('__id')
return userID
} catch (err) {
console.log(err.message)
}
},
loginUser: async function (loginData) {
try {
console.log(loginData.username, loginData.password)
let loginResult = await Appacitive.Users.login(loginData.username, loginData.password)
let userToken = loginResult.token
let userLists = await getUserLists(loginResult.user)
console.log(userLists)
return (userToken +" User Lists: " + userLists)
} catch (err) {
console.log(err.message)
}
}
} |
// export const test = 'http://127.0.0.1:8000';
export const test = 'http://192.168.193.128:8000';
// export const test = 'http://120.79.232.23:8000';
/**
* 真正的请求
* @param url 请求地址
* @param options 请求参数
* @param method 请求方式
* @param header 头文件
*/
function commonFetcdh(url, options, header='', method = 'GET') {
let initObj = {};
if (method === 'GET') { // 如果是GET请求,拼接url
url += '?' + searchStr;
initObj = {
method: method,
}
} else {
initObj = {
method: method,
headers: header,
body: options
}
}
fetch(url, initObj).then((res) => {
return res.json()
}).then((res) => {
return res
})
}
/**
* GET请求
* @param url 请求地址
* @param options 请求参数
*/
function GET(url, options) {
return commonFetcdh(url, options, 'GET')
}
/**
* POST请求
* @param url 请求地址
* @param options 请求参数
* @param header 头文件
*/
function POST(url, options, header) {
return commonFetcdh(url, options, header,'POST')
}
export { //很关键
POST,GET
} |
// var clarg = process.argv.slice(2);
// console.log(clarg);
// function revString(clarg) {
// for (var i = 0; i < clarg.length; i++) {
// var arg = clarg[i];
// for (var j = arg.length - 1; j >= 0; j--) {
// var revString = "";
// revString += arg[i];
// }
// }
// return clarg;
// }
// console.log(revString(clarg));
var allArguments = process.argv.slice(2);
var revArguments = [];
var string = "";
function reverse(allArguments) {
for (var i = 0; i <= allArguments.length - 1; i++) {
string = allArguments[i];
var stringRev = "";
for (var j = string.length - 1; j >= 0 ; j--) {
stringRev += string[j];
}
revArguments.push(stringRev);
}
return revArguments;
}
console.log(reverse(allArguments));
// function revString(clarg) {
// var argument;
// for(var i = 0; i < clarg.length - 1; i++) {
// var stringRev = "";
// argument = clarg[i];
// for (var j = argument.length - 1; j >= 0; j--) {
// stringRev += argument[i];
// }
// console.log(stringRev);
// }
// }
// revString(clarg);
// // function rS (string) {
// var revString = ""
// var string = "hello"
// for (var i = string.length - 1; i >= 0; i--) {
// revString += string[i];
// }
// console.log("hello");
// console.log(revString);
// console.log(rS("hello")); |
/*global PIFRAMES */
// Initial draft by John Taylor, Rewritten by Cliff Shaffer, November 2020
$(document).ready(function() {
"use strict";
var av_name = "NFAFS";
var av = new JSAV(av_name);
var Frames = PIFRAMES.init(av_name);
// Frame 1
av.umsg("Here we give a formal definition for Nondeterministic Finite Automata (NFA), and seek to gain some understanding about their limitations.");
av.displayInit();
// Frame 2
av.umsg(Frames.addQuestion("nfadfa"));
av.step();
// Frame 3
av.umsg(Frames.addQuestion("def"));
av.step();
// Frame 4
av.umsg(Frames.addQuestion("multi"));
av.step();
// Frame 5
av.umsg(Frames.addQuestion("moretrans"));
av.step();
// Frame 6
av.umsg(Frames.addQuestion("choices"));
av.step();
// Frame 7
//NFA with multi transition
var urllinkNFA = "../../../AV/OpenFLAP/machines/FA/NFAexample1.jff";
var linkNFA = new av.ds.FA({center: true, url: urllinkNFA, top: 50});
av.umsg(Frames.addQuestion("nfaexamp"));
av.step();
// Frame 8
av.umsg(Frames.addQuestion("badb"));
av.step();
// Frame 9
av.umsg("The NFA accepts a string if <b>any</b> of the paths that it might take when processing that string ends in a final state. It does not matter that there are paths where the machine goes wrong (that is, ends up in a non-final state). What matters is that there is at least one way for the NFA to go right.");
av.step();
// Frame 10
av.umsg("Nondeterminism gives us is a simple way to express the concept of 'or'. In this example, the machine effectively gives us the union of two languages: $L = \\{ab^n \\mid n > 0\\} \\cup \\{aa\\}$. In other words, the machine can accept strings that start with 'a' and follow the path to q1 (which then accepts one or more 'b'), or strings that start with 'a' and follow the path to q2 (which then accepts another 'a').");
av.step();
//Frame 11
linkNFA.hide();
//NFA with lambda
var urllinkNFAlambda = "../../../AV/OpenFLAP/machines/FA/NFAexample2.jff";
var linkNFAlambda = new av.ds.FA({center: true, url: urllinkNFAlambda, top: 30});
av.umsg("If you read carefully, you might have noticed that there is another difference in how the $\\delta$ function is defined for the NFA. In addition to the symbols of the alphabet, a transition is also permitted on the $\\lambda$ symbol. This is called a \"lambda transition\". Of course, in the input string there is no actual $\\lambda$ symbol.");
av.step();
// Frame 12
av.umsg(Frames.addQuestion("lambda"));
av.step();
// Frame 13
av.umsg(Frames.addQuestion("multilambda"));
av.step();
// Frame 14
av.umsg(Frames.addQuestion("starting"));
av.step();
// Frame 15
av.umsg(Frames.addQuestion("firstletter"));
av.step();
// Frame 16
av.umsg(Frames.addQuestion("walk"));
av.step();
// Frame 17
av.umsg(Frames.addQuestion("formalaccept"));
av.step();
// Frame 18
av.umsg(Frames.addQuestion("acceptreject"));
av.step();
// Frame 19
av.umsg("Why use NFAs? One reason is that they can be easier to create or understand. For example, hopefully it is easy to see that this one accepts the union of two pretty simple languages. So, $L = \\{(ab)^n \\mid n>0\\} \\cup \\{a^nb \\mid n>0\\}$. While this language can also be accepted by a DFA, it might not be as simple to come up with the answer.");
av.step();
// Frame 20
av.umsg("Another reason could be that NFAs allow us to define some languages that cannot be defined by any DFA. After all, nondeterminism and $\\lambda$ transitions seem like pretty powerful constructs. However, we are about to see that there is an algorithm that can convert any NFA into an equivalent DFA. Therefore, since any language that can be accepted by an NFA can also be accepted by a corresponding DFA, the set of languages accepted by NFAs cannot be greater than the set accepted by DFAs.");
av.step();
// Frame 21
linkNFAlambda.hide();
var urlnfa = "../../../AV/OpenFLAP/machines/FA/NFA2DFAexample1.jff";
var nfa = new av.ds.FA({center: true, url: urlnfa, left: 0});
av.umsg(Frames.addQuestion("nfaex"));
av.step();
// Frame 22
var urldfa = "../../../AV/OpenFLAP/machines/FA/NFA2DFAexample2.jff";
var dfa = new av.ds.FA({center: true, url: urldfa, left: 250});
av.umsg("Hopefully it is not too hard to convince yourself that the DFA on the right accepts the same language as the NFA. Note that the names of the states are chosen to help you to see their relationships to the original NFA. In fact, there was a procedure followed to generate this DFA, which also produced these node labels.");
av.step();
// Frame 23
av.umsg("Congratulations! Frameset completed.");
av.recorded();
});
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* admin.js :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mdalil <mdalil@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/08/06 00:15:35 by mayday #+# #+# */
/* Updated: 2019/08/08 22:56:55 by mdalil ### ########.fr */
/* */
/* ************************************************************************** */
function getValuesFromDB()
{
return promisedRequest
.get("../model/process.php", { action: 'get_admin' })
.then((response) => {
document.getElementById("mail").value = response.user_mail;
document.getElementById("username").value = response.user_name;
document.getElementById("send_notification").value = `${response.notification == 1 ? `disable` : `enable`} notification`;
})
.catch((response) => createAlert(response, "ok", () => location.href = "?view=login"));
}
function createAdminView()
{
if (!getToken())
return ;
const feed = document.getElementById("feed");
const element = document.createElement("div");
const commentbox = document.createElement("div");
getValuesFromDB();
const form = {
'mail': generateForm([
{id: "mail", type: "text", text: "Mail"},
{id: "send_mail", type: "button", value: "send", onclick: "accountAction('change_mail', this.form)"}
]),
'username': generateForm([
{id: "username", type: "text", text: "Username"},
{id: "send_username", type: "button", value: "send", onclick: "accountAction('change_username', this.form)"}
]),
'password': generateForm([
{id: "password", type: "password", text: "Password"},
{id: "password_confirm", type: "password", text: "Password Confirm"},
{id: "send_password", type: "button", value: "send", onclick: "accountAction('change_password', this.form)"}
]),
'notification': generateForm([
{id: "send_notification", type: "button", onclick: "accountAction('change_notification', this.form, () => location.reload(true), () => location.href = '?view=login')"}
])
};
element.id = "element";
commentbox.id = "commentbox";
Object.keys(form).forEach((form_elem) => commentbox.appendChild(form[form_elem]));
element.appendChild(commentbox);
feed.appendChild(element);
} |
import React, { Component } from "react";
import { StyleSheet, Text, View, Dimensions, Image, ImageBackground} from 'react-native';
import { VictoryChart, VictoryLegend, VictoryAxis, VictoryBar, VictoryTheme } from "victory-native";
import wasteImg from '../../assets/triangle_small.png';
import moneyImg from '../../assets/money_small.png';
import carbonImg from '../../assets/carbon_small.png';
import topBackground from '../../assets/dashboardBackground.png';
import * as firebase from 'firebase';
import 'firebase/firestore';
import { AppContext } from '../../AppContextProvider';
//Components
class Dashboard extends Component {
static navigationOptions = {
};
state = {
loaded: 0, // triggers a reload
data: {
totalWeight: 0,
foodTotalWeight: 0,
dataWeekly: [],
}
}
// Set the context to be used
// Refer to React Context API: https://reactjs.org/docs/context.html#contextprovider
// use the experimental public class fields syntax
// Refer to example: https://www.taniarascia.com/using-context-api-in-react/
static contextType = AppContext;
// Get log data
// fetch all logs of the user and get the aggregated data
getLog = async (userId) => {
const dbh = firebase.firestore();
console.log(`get getLog of ${userId}...`);
const userLogRef = dbh.collection('logs').doc(userId);
const jsonata = require("jsonata");
var total = 0;
userLogRef.get()
.then((docSnapshot) => {
console.log(`fetched log succcessfuly`);
if (docSnapshot.exists) {
const data = docSnapshot.data();
// refer to https://docs.jsonata.org/overview for details of how to do filtering/aggregations
// https://docs.jsonata.org/predicate
// aggregate and get all the data
// sum of total
//console.log('data:' + JSON.stringify(data,null,4));
var totalWeightEpression = jsonata("$sum(log.weight)");
var totalWeight = totalWeightEpression.evaluate(data);
// Food waste
var foodTotalWeightExpression = jsonata("$sum(log[waste='fw'].weight)");
var foodTotalWeight = foodTotalWeightExpression.evaluate(data);
console.log(`totalWeight:${totalWeight} foodTotalWeight:${foodTotalWeight}`);
var weeklyData = [];
var arrayLength = data.log.length;
var log = data.log;
for (var i = 0; i < arrayLength; i++) {
var date1 = new Date(log[i].date.seconds * 1000);
var dateStr = (date1.getMonth() + 1) + '/' + date1.getDate();
var dayOrderStr = date1.getMonth()*30 + date1.getDate();
log[i].day=dateStr;
log[i].dayOrder = dayOrderStr;
}
var weightByDayExpression = jsonata("log{day: $sum(weight)}^(dayOrder)");
var groupResult = weightByDayExpression.evaluate(data);
console.log(`groupResult:` + JSON.stringify(groupResult,null,4));
var dataWeekly=[];
var count=1;
for (const [key, value] of Object.entries(groupResult)) {
//Do stuff where key would be 0 and value would be the object
//console.log(`key:${key} value:${value}`);
var entry = {
day: count,
label: key,
amount: value
};
dataWeekly.push(entry);
count = count + 1;
}
if (dataWeekly.length>7) {
dataWeekly=dataWeekly.slice(-7);
}
//console.log('dataWeekly: ' + JSON.stringify(dataWeekly,null,4));
var compostData = {
totalWeight: totalWeight,
foodTotalWeight: foodTotalWeight,
dataWeekly: dataWeekly
}
this.setState({data: compostData});
} else { // new user with no data
console.log(`log does not exist for ${userId}`);
}
});
}
// set a loop to check the user.timestamp every 30 seconds
// if flag changed, then reload data
// it will trigger the page to render again
componentDidMount() {
setInterval(() => {
//console.log('check if data refreshed');
let { user, setUser } = this.context;
// console.log('user data refreshed in dashboard: ');
if (user.timestamp !== "") {
let userId = user.loggedIn ? user.userInfo.user_id : 'GuestUser';
this.getLog(userId);
user.timestamp = ""; // reset timestamp back to empty
setUser(user);
this.setState({loaded:1}); // need to rewind this value to one so the bar chart can be loaded
}
}, 10000); // check if dashboard need refresh every 10 seconds
}
componentWillUnmount() {
console.log('dashboard component will unmount.')
}
render() {
//console.log('dashboard data never loaded, load it. context:' + JSON.stringify(this.context,null,4) );
console.log('dashboard data never loaded, load it');
const user = this.context.user;
let userId = user.loggedIn ? user.userInfo.user_id : 'GuestUser';
//console.log(`in DashboardScreen, userId(${userId}) context data: ` + JSON.stringify(this.context,null,4));
let loadCount = this.state.loaded;
if (loadCount<3) {
loadCount = loadCount + 1;
this.setState({userId: userId});
this.getLog(userId);
this.setState({loaded: loadCount});
} else {
console.log('already loaded. loadCount:' + loadCount);
//this.getLog(userId);
}
console.log('render data:' + JSON.stringify(this.state.data));
var dataWeekly = this.state.data.dataWeekly;
// calculate data
const pricePerTon = 55;
var totalWeight = this.state.data.totalWeight;
var totalFoodWasteWeight = this.state.data.foodTotalWeight;
var dollar = Number.parseFloat(pricePerTon * totalWeight/2000).toFixed(2);
// using only food waste for emission and miles
var emission = Number.parseFloat(totalFoodWasteWeight * 0.8).toFixed(1);
var miles = Number.parseFloat(emission * 1.126).toFixed(1);
const DeviceWidth = Dimensions.get('window').width;
const marginBottom = 10;
const marginLeft = 10;
let nickname = "";
if (user.loggedIn) {
if (user.userInfo.name.indexOf('@') != -1) {
nickname = user.userInfo.name.substring(0,user.userInfo.name.indexOf('@')); // strip @ from email
} else {
nickname = user.userInfo.name;
}
} else {
nickname = userId;
}
return (
<View style={styles.container}>
<ImageBackground source={topBackground} style={styles.backgroundImage}>
<Text style={{ textAlign:'center', fontWeight: 'bold', fontSize:22, alignContent:"center"}}>Hello {nickname}</Text>
<View styles={styles.container}>
<Text style={{textAlign:'center', alignContent:"center"}}>You have diverted to date</Text>
<Text style={{ textAlign:'center', fontWeight: 'bold', fontSize:24, alignContent:"center"}}>{parseFloat(totalWeight.toFixed(1))} lbs</Text>
<Text style={{ textAlign:'center' }}>organic waste from landfills by composting.</Text>
{userId==='GuestUser' ? (
<Text style={{color:"red"}} > This is DEMO account showing combined inputs of all guests.</Text>
): totalWeight===0 ? (
<Text style={{ textAlign:'center', color:"black", fontSize:20, alignContent:"center"}}>Time to start!</Text>
):
<Text style={{ textAlign:'center', color:"black", fontSize:20, alignContent:"center"}}>Way to go!</Text>
}
<Text></Text>
<Text></Text>
</View>
</ImageBackground>
<View style={styles.container3}>
<Text style={{fontSize:18, width:"100%", alignContent:"center", marginBottom: 10}}>TOTAL LOGGED IMPACT</Text>
<View style={{
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
}}>
<View>
<View style={{justifyContent: 'center',alignItems:'center', width: DeviceWidth*0.33, height: DeviceWidth*0.18, marginBottom:0, marginLeft:0}}>
<Image resizeMode="contain" source={wasteImg}></Image>
</View>
<View style={{justifyContent: 'center',alignItems:'center', width: DeviceWidth*0.3, height: DeviceWidth*0.10, marginBottom:0, marginLeft:0}} >
<Text style={{fontSize:22, fontWeight:'bold'}}> {parseFloat(totalWeight.toFixed(1))} </Text>
<Text> lbs </Text>
</View>
</View>
<View>
<View style={{justifyContent: 'center', alignItems:'center', width: DeviceWidth*0.34, height: DeviceWidth*0.18, marginBottom:0, marginLeft:0 }} >
<Image resizeMode="contain" source={moneyImg}></Image>
</View>
<View style={{justifyContent: 'center',alignItems:'center', width: DeviceWidth*0.3, height: DeviceWidth*0.10, marginBottom:0, marginLeft:0 }} >
<Text style={{fontSize:22, fontWeight:'bold'}}> {dollar} </Text>
<Text> USD</Text>
</View>
</View>
<View>
<View style={{justifyContent: 'center', alignItems:'center', width: DeviceWidth*0.33, height: DeviceWidth*0.18, marginTop:0, marginBottom:0, marginLeft:0 }} >
<Image resizeMode="contain" source={carbonImg}></Image>
</View>
<View style={{justifyContent: 'center', alignItems:'center', width: DeviceWidth*0.3, height: DeviceWidth*0.10, marginBottom:0, marginLeft:0}} >
<Text style={{fontSize:22, fontWeight:'bold'}}> {Number.parseFloat(emission).toFixed(1)} </Text>
<Text> lbs CO2e</Text>
</View>
</View>
</View>
</View>
<View style={{flex: 1, justifyContent: 'center', alignItems:'center', alignContent:"center", backgroundColor:'#F5F3F4', width:'100%'}}>
<Text /><Text />
<Text style={{ fontSize:18, alignContent:"center", marginTop: 0, marginBottom: 0}}>RECENT PROGRESS</Text>
<VictoryChart
// domainPadding will add space to each side of VictoryBar to
// prevent it from overlapping the axis
theme={VictoryTheme.material}
domainPadding={0}
color="gray"
width={360}
height={180}
>
<VictoryAxis
// tickValues specifies both the number of ticks and where
// they are placed on the axis
tickValues={this.state.data.dataWeekly.map(item=>{return item.day})}
tickFormat={this.state.data.dataWeekly.map(item=>{return item.label})}
/>
<VictoryAxis
dependentAxis
// tickFormat specifies how ticks should be displayed
tickFormat={(x) => (`${x} lbs`)}
/>
<VictoryBar
data={this.state.data.dataWeekly.map(item=>{return {month:item.day, amount:item.amount}})}
x="month"
y="amount"
/>
</VictoryChart>
</View>
</View>
)
};
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
container2: {
flex: 1,
backgroundColor: '#e3e8e5',
alignItems: 'center',
justifyContent: 'center',
width:"100%"
},
container3: {
flex: 1,
//backgroundColor: '#C5DAB2',
backgroundColor: '#dbe3d1',
alignItems: 'center',
justifyContent: 'center',
},
backgroundImage: {
flex: 1,
resizeMode: 'center', // or 'stretch',
//justifyContent: 'center',
width: '100%',
height: '100%',
alignContent:"stretch",
justifyContent: 'center',
},
text: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
}
});
export default Dashboard;
|
import React from 'react';
import {Link, Redirect} from 'react-router-dom';
import AccountService from '../services/AccountService.js';
import NavBar from './NavBar';
import HomePage from './HomePage';
class Account extends HomePage {
constructor(props) {
super(props);
this.state = {
initialDeposit: null,
success: "",
error: ""
}
}
handleSubmit = (e) => {
e.preventDefault();
AccountService.createAccount(this.props.location.state.activeUser.id, this.state.initialDeposit).then(() => {
this.setState(() => ({
success: "Account created sucessfully"
}));
})
.catch((error) =>{
console.log(error);
this.setState(() => ({
error: "Unable to create account"
}));
});
}
render() {
// checks if user is logged in
if (!this.props.location.state || this.state.isLoggedIn===false){
return <Redirect to="/login" />
}
const sucessStyle = {
color: 'blue'
}
const errorStyle = {
color: 'red'
}
return(
<div>
<NavBar activeUser={this.state.user} isLoggedIn={this.state.isLoggedIn}/>
<h3>Create Account</h3>
<p style={sucessStyle}>{this.state.success}</p>
<p style={errorStyle} >{this.state.error} </p>
<form onSubmit={this.handleSubmit}>
<label>Initial Deposit</label><br/>
<input type="number" value={this.state.initialDeposit}
onChange={evt => this.setState({initialDeposit : evt.target.value, error:"", success: ""})}
min="0.00" step="0.01" placeholder="$0.00" required
/><br/><br/>
<input type="submit" />
</form>
<br></br>
<Link to={{
pathname: "/home",
state: {
activeUser: this.props.activeUser,
isLoggedIn: this.props.isLoggedIn
}
}}>
<li className="nav-items">Home</li>
</Link>
</div>
);
}
}
export default Account; |
function verification(contrat)
{
var bool = false
if(!contrat.civilite)
{
console.log("Veuillez saisir une civilité");
bool = true;
}
if(!contrat.nom)
{
console.log("Veuillez saisir un nom");
bool = true;
}
if (!contrat.prenom)
{
console.log("Veuillez saisir un prenom")
bool = true;
}
if (!contrat.lieu_de_naissance)
{
console.log("Veuillez saisir un lieu de naissance")
bool = true;
}
if(!contrat.nationalite)
{
console.log("Veuillez saisir une nationalité");
bool = true;
}
if (!contrat.address)
{
console.log("Veuillez saisir une address")
bool = true;
}
if (!contrat.secu)
{
console.log("Veuillez saisir un n° de sécurité sociale")
bool = true;
}
if (contrat.secu.length !=13)
{
console.log("Veuillez saisir un n° de sécurité sociale à 13 chiffres")
bool = true;
}
if (!contrat.date_de_debut)
{
console.log("Veuillez saisir une date début")
bool = true;
}
if (!contrat.statut)
{
console.log("Veuillez saisir un statut")
bool = true;
}
if (!contrat.salaire_brut)
{
console.log("Veuillez saisir un salaire brut")
bool = true;
}
if (!contrat.position)
{
console.log("Veuillez saisir une position")
bool = true;
}
if (!contrat.coefficient)
{
console.log("Veuillez saisir un coefficient")
bool = true;
}
if(contrat.civilite && contrat.nom && contrat.prenom && contrat.lieu_de_naissance && contrat.address && contrat.secu && contrat.secu.length==13 && contrat.date_de_debut && contrat.nationalite && contrat.statut && contrat.salaire_brut && contrat.coefficient&& contrat.position)
{
console.log("L'insertion à la base à été un succes")
return false;
}
}
module.exports = verification; |
// INSTANTIATION
var APP = require("/core");
var DB = require("/db");
var Utils = require("/utils");
var args = arguments[0] || {};
var familyListController = this;
var user_token = Ti.App.Properties.getString("user_token",false);
var action = DB.INSERT;
var actual_page = 1;
var total_paginado = 10;
var descargando = false;
DB.init(function(){});
var dataInmuebles = args && args.params && args.params.data ? args.params.data : null;
var isFromBusqueda = args && args.params && args.params.from ? true:false;
if(dataInmuebles && dataInmuebles.length > 0){
showRows(dataInmuebles);
}
// ADDITIONS
// FUNCTIONS
function loadInmuebles(pagina){
}
function loadUsers(){
APP.showActivityindicator();
descargando = true;
var dataTemp = {
url : L("url_inmuebles_paginados") + actual_page + "/" + total_paginado,
type : 'GET',
format : 'JSON',
data : {
}
};
APP.http.request(dataTemp,function(_result){
//Ti.API.info("-->"+JSON.stringify(_result));
if(_result._result == 1){
var longitud = _result._data.length ? _result._data.length : 0;
var data = _result._data ? _result._data : 0;
Ti.API.info('LONGITUD-----'+longitud);
if(longitud > 0){
showRows(data);
descargando = false;
APP.hideActivityindicator();
}else{
//alert(_result._data.message);
APP.hideActivityindicator();
alert("No messages were found.");
}
}else{
APP.hideActivityindicator();
alert("Internet connection error, please try again.");
}
});
}
function showRows(data){
for(var i=0; i < data.length; i++ ){
var element = data[i];
var row = Alloy.createController('FamilyWallet/RowFamily',{element:element}).getView();
$.wrapper.add(row);
}
}
function initializeView(){
user_token = Ti.App.Properties.getString("user_token",false);
loadUsers();
}
function updateView(){
APP.headerbar.removeAllCustomViews();
APP.headerbar.setLeftButton(0,false);
APP.headerbar.setRightButton(0,false);
APP.headerbar.setLeftButton(APP.OPENMENU,true);
APP.headerbar.setTitle("Inmuebles");
user_token = Ti.App.Properties.getString("user_token",false);
loadUsers();
}
function showProfile(e){
//Ti.API.info('Console-------->'+JSON.stringify(e.source));
APP.openWindow({controller:"FamilyWallet/ProfileFamily",
controllerParams:e.source.elemento});
/*
var id = "";
var member = null;
if(e.source && e.source.id_profile){
id = e.source.id_profile;
member = DB.getMember(id,function(){});
if(member){
member = member[0];
}
action = DB.UPDATE;
var params = {id_profile:id,
familyListController:familyListController,
member:member};
openDetailView((member.type == APP.USER_MEMBER) ?
"FamilyWallet/ProfileFamily":
"FamilyWallet/PetFamily",
params);
}else if(e.source.id == "plusBtn"){
action = DB.INSERT;
var dialog = Titanium.UI.createOptionDialog({
options: ['Member','Pet','Cancel'],
cancel:2
});
dialog.show();
dialog.addEventListener('click',function(e){
APP.getToken({
openLogin : true,
callback : function(_token) {
if (e.index == 0) {
openDetailView("FamilyWallet/ProfileFamily", {
id_profile : id,
familyListController : familyListController,
member : member
});
} else if (e.index == 1) {
openDetailView("FamilyWallet/PetFamily", {
id_profile : id,
familyListController : familyListController,
member : member
});
} else {
}
return true;
}
});
});
}else{
}
*/
}
// CODEº
// LSITENERS
$.scrollFamily.addEventListener('scroll', function (e) {
Ti.API.info('RECT:'+ ($.wrapper.rect.height - e.y));
Ti.API.info('SIZEHE:'+ $.scrollFamily.getRect().height);
//Ti.API.info('SIZEHE:'+ e.contentSize.height);
var tolerancia = 100;
if(( ($.wrapper.rect.height - e.y) <= ($.scrollFamily.getRect().height + tolerancia)) && !descargando ){
actual_page += 1;
!isFromBusqueda && loadUsers();
}
});
// EXPORTS
exports.loadUsers = loadUsers;
exports.updateView = updateView;
exports.initializeView = initializeView; |
import React, { Component, Fragment } from 'react'
import { connect } from 'react-redux'
import Nav from '../Nav'
import SearchBar from '../SearchBar'
import Gifs from '../Gifs'
import * as actionTypes from '../../actions'
class Favorites extends Component {
constructor(props) {
super(props)
this.state = {
query: '',
loading: false,
title: 'Favorites',
}
}
componentDidMount() {
this.props.onFavoriteGifsInit()
}
updateQuery(e) {
this.setState({
query: e.target.value
})
}
handleSearch = () => {
const { query } = this.state
const { onFetchData } = this.props
onFetchData(query)
const newTitle = !!query ? query : 'Trending Now'
this.setState({
title: newTitle
})
}
render() {
const { query, loading, title } = this.state
const { favoriteGifs } = this.props
return (
<Fragment>
<Nav />
<SearchBar
value={query}
updateQuery={(e) => this.updateQuery(e)}
handleSearch={this.handleSearch}
/>
{
loading
? 'Cargando ...'
: <Gifs
gifs={favoriteGifs}
title={title}
/>
}
</Fragment>
)
}
}
const mapStateToProps = state => {
return {
favoriteGifs: state.gifs
}
}
const mapDispatchToProps = dispatch => {
return {
onFavoriteGifsInit: () => dispatch(actionTypes.favoriteGifsInit()),
onFetchData: (query) => dispatch(actionTypes.fetchDataRequest(query))
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Favorites) |
import React, { Component } from 'react';
import { connect } from 'react-redux';
import Button from 'components/Button';
import MeetingsListItem from './components/MeetingsListItem';
import './style.css';
import future from 'images/future.png';
import past from 'images/past.png';
class MeetingsList extends Component {
constructor(props) {
super(props);
this.ALL = 'ALL';
this.meetingListItems = this.meetingListItems.bind(this);
this.openMeeting = this.openMeeting.bind(this);
this.byType = this.byType.bind(this);
this.upcoming = this.upcoming.bind(this);
this.completed = this.completed.bind(this);
this.typeDropDownOptions = this.typeDropDownOptions.bind(this);
this.setFilter = this.setFilter.bind(this);
this.setCompleted = this.setCompleted.bind(this);
this.unsetCompleted = this.unsetCompleted.bind(this);
this.state = {
openMeeting: null,
filter: this.ALL,
completed: false
};
}
byType(meetings, type) {
if (type !== this.ALL) return meetings.filter(m => m.meeting_type === type);
return meetings;
}
upcoming(meetings) {
return meetings.filter(m => Date.parse(m.date_time) > Date.now());
}
completed(meetings) {
return meetings.filter(m => Date.parse(m.date_time) < Date.now());
}
openMeeting(id) {
return () => {
this.setState({ openMeeting: id });
};
}
meetingListItems(meetings, meetingTypes, openMeeting, openFunc) {
return meetings.map(meeting => (
<MeetingsListItem
key={meeting.id}
meeting={meeting}
opened={openMeeting === null ? false : openMeeting === meeting.id}
open={this.openMeeting(meeting.id)}
meetingType={
meetingTypes.find(
meetingType => meetingType.id === meeting.meeting_type
) || {}
}
/>
));
}
setFilter(e) {
if (e.target.value === this.ALL) this.setState({ filter: e.target.value });
else this.setState({ filter: parseInt(e.target.value, 10) });
}
setCompleted() {
this.setState({ completed: true });
}
unsetCompleted() {
this.setState({ completed: false });
}
typeDropDownOptions(meetingTypes) {
return meetingTypes.map(type => (
<option key={type.id} value={type.id}>
{type.meeting_title}
</option>
));
}
render() {
let meetingsList = this.props.meetings;
if (this.state.completed) meetingsList = this.completed(meetingsList);
else meetingsList = this.upcoming(meetingsList);
meetingsList = this.byType(meetingsList, this.state.filter);
return (
<div>
<h3 className="text-center">Meetings & Huddles</h3>
<div className="filters">
<select onChange={this.setFilter}>
<option value={this.ALL} default>
Show all types
</option>
{this.typeDropDownOptions(this.props.meetingTypes)}
</select>
<div className="buttons">
<Button
click={this.unsetCompleted}
className={this.state.completed ? '' : 'active'}
>
<img src={future} alt="" /> Upcoming
</Button>
<Button
click={this.setCompleted}
className={this.state.completed ? 'active' : ''}
>
<img src={past} alt="" /> Completed
</Button>
</div>
<div className="clearfix" />
</div>
<ul className="meetings-list">
{this.meetingListItems(
meetingsList,
this.props.meetingTypes,
this.state.openMeeting,
this.openMeeting
)}
</ul>
</div>
);
}
}
const mapStateToProps = state => {
let meetings = state.meetings.items;
if (state.me.user.is_staff && state.defaultCompany)
meetings = state.meetings.items.filter(
meeting => meeting.company === state.defaultCompany
);
return {
meetings,
meetingTypes: state.meetingTypes.items
};
};
export default connect(mapStateToProps)(MeetingsList);
|
var mailHelper = require('sendgrid').mail;
var mailer = {
content: new mailHelper.Content("text/plain", "Welcome to Chinmaya Vrindavan Events. \n " +
"\n " +
"Have a great day! \n " +
"Chinmaya Vrindavan Events Team"),
sendMail: function (fromMail, toMail, subject, customContent) {
var from_email = new mailHelper.Email(fromMail);
var to_email = new mailHelper.Email(toMail);
var mail = new mailHelper.Mail(from_email, subject, to_email, customContent || this.content);
var sg = require('sendgrid')(process.env.SENDGRID_API_KEY);
var request = sg.emptyRequest({
method: 'POST',
path: '/v3/mail/send',
body: mail.toJSON()
});
sg.API(request, function(error, response) {
});
}
};
module.exports = mailer;
|
import React from 'react'
import Form from 'react-bootstrap/Form'
import { Button, Container, Col, Row } from 'react-bootstrap'
import { createGame, getAllPlayers } from '../../lib/api'
import { useForm } from 'react-hook-form'
import { useHistory } from 'react-router-dom'
import { getPayLoad } from '../../lib/auth'
function GameAdd() {
const { register, handleSubmit } = useForm()
const [payoutsKnown, setPayoutsKnown] = React.useState(false)
const [playerNumKnown, setPlayerNumKnown] = React.useState(false)
const [buyinKnown, setBuyinKnown] = React.useState(false)
const [formData, setFormData] = React.useState({
prizeForFirst: 0,
prizeForSecond: 0,
prizeForThird: 0,
buyIn: '',
numberOfPlayers: 3,
userId: '',
firstPlace: '',
secondPlace: '',
thirdPlace: '',
fourthPlace: '',
fifthPlace: '',
sixthPlace: '',
seventhPlace: '',
eighthPlace: '',
ninthPlace: '',
})
const [formErrors, setFormErrors] = React.useState({
firstPlace: '',
secondPlace: '',
thirdPlace: '',
fourthPlace: '',
fifthPlace: '',
sixthPlace: '',
seventhPlace: '',
eighthPlace: '',
ninthPlace: '',
name: '',
date: '',
})
const [isError, setIsError] = React.useState(false)
const [playerList, setPlayerList] = React.useState(null)
const history = useHistory()
const [totalPotDifference, setTotalPotDifference] = React.useState(null)
const [userId, setUserId] = React.useState(null)
React.useEffect(() => {
const getData = async () => {
const playerData = await getAllPlayers()
const payLoad = getPayLoad()
const user = payLoad.sub
setUserId(user)
setPlayerList(playerData.data)
console.log(playerData.data)
}
getData()
}, [])
const handleSub = (event) => {
setIsError(false)
event.preventDefault()
const name = event.target.name
if (name === 'numberOfPlayers' && formData[name]) {
setPlayerNumKnown(true)
}
if (name === 'buyIn' && formData[name] > 0) {
setBuyinKnown(true)
} else if (name === 'buyIn'){
setIsError(true)
}
if (name === 'winnings') {
if (parseInt(formData['prizeForFirst']) + parseInt(formData['prizeForSecond']) + parseInt(formData['prizeForThird'])
=== (parseInt(formData['buyIn']) * parseInt(formData['numberOfPlayers']))) {
setPayoutsKnown(true)
} else {
setTotalPotDifference((parseInt(formData['prizeForFirst']) + parseInt(formData['prizeForSecond']) + parseInt(formData['prizeForThird']))
- ((parseInt(formData['buyIn']) * parseInt(formData['numberOfPlayers']))))
setIsError(true)
}
}
}
const handleChange = (event) => {
const value = event.target.value
setFormData({ ...formData, [event.target.name]: value })
console.log(formData)
}
const mergeThenSend = async (rankingsData) => {
rankingsData = { ...rankingsData, ...formData, userId: userId }
console.log(rankingsData)
try {
await createGame(rankingsData)
history.push('/dashboard')
} catch (err) {
setFormErrors(err.response.data)
}
}
return (
<Container className="login" fluid>
<Row>
<Col className="outer-col"></Col>
<Col xs={4} className="form-vertical-align">
<div className='log-game-form-wrap'>
<h2>Add New Game</h2>
{!playerNumKnown &&
<Form name="numberOfPlayers" onSubmit={handleSub}>
<Form.Group className="mb-3">
<Form.Label>How many players in your game?</Form.Label>
<Form.Control
as="select"
name="numberOfPlayers"
onChange={handleChange}>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
</Form.Control>
</Form.Group>
<Button variant="none" className="btn-default" type="submit">
Next
</Button>
</Form>
}
{!buyinKnown && playerNumKnown &&
<Form name="buyIn" onSubmit={handleSub}>
<Form.Group className="mb-3">
<Form.Label>What is the buy-in?</Form.Label>
<Form.Control
type="number"
className={isError ? 'is-invalid' : ''}
placeholder="Buy-in amount"
name="buyIn"
onChange={handleChange}/>
{isError && (
<Form.Text className="text-muted">
Please enter a valid buy-in
</Form.Text>
)}
</Form.Group>
<Button
variant="none"
className="btn-default"
type="submit"
>
Next
</Button>
</Form>
}
{playerNumKnown && buyinKnown && !payoutsKnown &&
<Form name="winnings" onSubmit={handleSub}>
<Form.Group className="mb-3">
<Form.Label>Prize for First</Form.Label>
<Form.Control
type="text"
className={isError ? 'is-invalid' : ''}
placeholder="Prize for First"
name="prizeForFirst"
onChange={handleChange}/>
</Form.Group>
<Form.Group className="mb-3">
<Form.Label>Prize for Second</Form.Label>
<Form.Control
type="text"
className={isError ? 'is-invalid' : ''}
placeholder="Prize for Second"
name="prizeForSecond"
onChange={handleChange}/>
</Form.Group>
<Form.Group className="mb-3">
<Form.Label>Prize for Third</Form.Label>
<Form.Control
type="text"
className={isError ? 'is-invalid' : ''}
placeholder="Prize for Third"
name="prizeForThird"
onChange={handleChange}/>
{isError && (
<Form.Text className="text-muted">
{totalPotDifference > 0 ? `Your payouts are £${totalPotDifference} bigger than the prize pool`
: `Your payouts are £${totalPotDifference * -1} smaller than the prize pool` }
</Form.Text>
)}
</Form.Group>
<Button
variant="none"
className="btn-default"
type="submit"
>
Next
</Button>
</Form>
}
{playerNumKnown && buyinKnown && payoutsKnown &&
<Form name="players" onSubmit={handleSubmit(mergeThenSend)}>
<Form.Group className="mb-3">
<Form.Label>First Place</Form.Label>
<Form.Control
as="select"
className={`${formErrors['firstPlace'] ? 'is-invalid' : ''}`}
{...register('firstPlace', { required: true })}
name="firstPlace"
defaultValue="def"
onChange={handleChange}>
<option value="def" disabled hidden>Select player</option>
{playerList.filter(player => player.userId === userId)
.filter(player => player.id !== parseInt(formData.secondPlace) && player.id !== parseInt(formData.thirdPlace) &&
player.id !== parseInt(formData.fourthPlace) && player.id !== parseInt(formData.fifthPlace) && player.id !== parseInt(formData.sixthPlace) &&
player.id !== parseInt(formData.seventhPlace) && player.id !== parseInt(formData.eighthPlace) && player.id !== parseInt(formData.ninthPlace))
.map(player => (
<option key={player.id} value={player.id}>{player.name}</option>
))}
</Form.Control>
{formErrors['firstPlace'] && (
<Form.Text
className="text-muted">A player is required
</Form.Text>
)}
</Form.Group>
<Form.Group className="mb-3">
<Form.Label>Second Place</Form.Label>
<Form.Control
as="select"
className={`${formErrors['secondPlace'] ? 'is-invalid' : ''}`}
defaultValue="def"
{...register('secondPlace', { required: true })}
name="secondPlace"
onChange={handleChange}>
<option value="def" disabled hidden>Select player</option>
{playerList.filter(player => player.userId === userId)
.filter(player => player.id !== parseInt(formData.firstPlace) && player.id !== parseInt(formData.thirdPlace) &&
player.id !== parseInt(formData.fourthPlace) && player.id !== parseInt(formData.fifthPlace) && player.id !== parseInt(formData.sixthPlace) &&
player.id !== parseInt(formData.seventhPlace) && player.id !== parseInt(formData.eighthPlace) && player.id !== parseInt(formData.ninthPlace))
.map(player => (
<option key={player.id} value={player.id}>{player.name}</option>
))}
</Form.Control>
{formErrors['secondPlace'] && (
<Form.Text
className="text-muted">A player is required
</Form.Text>
)}
</Form.Group>
<Form.Group className="mb-3">
<Form.Label>Third Place</Form.Label>
<Form.Control
as="select"
className={`${formErrors['thirdPlace'] ? 'is-invalid' : ''}`}
defaultValue="def"
name="thirdPlace"
{...register('thirdPlace', { required: true })}
onChange={handleChange}>
<option value="def" disabled hidden>Select player</option>
{playerList.filter(player => player.userId === userId)
.filter(player => player.id !== parseInt(formData.firstPlace) && player.id !== parseInt(formData.secondPlace) &&
player.id !== parseInt(formData.fourthPlace) && player.id !== parseInt(formData.fifthPlace) && player.id !== parseInt(formData.sixthPlace) &&
player.id !== parseInt(formData.seventhPlace) && player.id !== parseInt(formData.eighthPlace) && player.id !== parseInt(formData.ninthPlace))
.map(player => (
<option key={player.id} value={player.id}>{player.name}</option>
))}
</Form.Control>
{formErrors['thirdPlace'] && (
<Form.Text
className="text-muted">A player is required
</Form.Text>
)}
</Form.Group>
{formData.numberOfPlayers > 3 &&
<Form.Group className="mb-3">
<Form.Label>Fourth Place</Form.Label>
<Form.Control
as="select"
className={`${formErrors['fourthPlace'] ? 'is-invalid' : ''}`}
defaultValue="def"
name="fourthPlace"
{...register('fourthPlace', { required: true })}
onChange={handleChange}>
<option value="def" disabled hidden>Select player</option>
{playerList.filter(player => player.userId === userId)
.filter(player => player.id !== parseInt(formData.firstPlace) && player.id !== parseInt(formData.secondPlace) && player.id !== parseInt(formData.thirdPlace) &&
player.id !== parseInt(formData.fifthPlace) && player.id !== parseInt(formData.sixthPlace) &&
player.id !== parseInt(formData.seventhPlace) && player.id !== parseInt(formData.eighthPlace) && player.id !== parseInt(formData.ninthPlace))
.map(player => (
<option key={player.id} value={player.id}>{player.name}</option>
))}
</Form.Control>
{formErrors['fourthPlace'] && (
<Form.Text
className="text-muted">A player is required
</Form.Text>
)}
</Form.Group>
}
{formData.numberOfPlayers > 4 &&
<Form.Group className="mb-3">
<Form.Label>Fifth Place</Form.Label>
<Form.Control
as="select"
name="fifthPlace"
className={`${formErrors['fifthPlace'] ? 'is-invalid' : ''}`}
defaultValue="def"
{...register('fifthPlace', { required: true })}
onChange={handleChange}>
<option value="def" disabled hidden>Select player</option>
{playerList.filter(player => player.userId === userId)
.filter(player => player.id !== parseInt(formData.firstPlace) && player.id !== parseInt(formData.secondPlace) && player.id !== parseInt(formData.thirdPlace) &&
player.id !== parseInt(formData.fourthPlace) && player.id !== parseInt(formData.sixthPlace) &&
player.id !== parseInt(formData.seventhPlace) && player.id !== parseInt(formData.eighthPlace) && player.id !== parseInt(formData.ninthPlace))
.map(player => (
<option key={player.id} value={player.id}>{player.name}</option>
))}
</Form.Control>
{formErrors['fifthPlace'] && (
<Form.Text
className="text-muted">A player is required
</Form.Text>
)}
</Form.Group>
}
{formData.numberOfPlayers > 5 &&
<Form.Group className="mb-3">
<Form.Label>Sixth Place</Form.Label>
<Form.Control
as="select"
defaultValue="def"
name="sixthPlace"
className={`${formErrors['sixthPlace'] ? 'is-invalid' : ''}`}
{...register('sixthPlace', { required: true })}
onChange={handleChange}>
<option value="def" disabled hidden>Select player</option>
{playerList.filter(player => player.userId === userId)
.filter(player => player.id !== parseInt(formData.firstPlace) && player.id !== parseInt(formData.secondPlace) &&
player.id !== parseInt(formData.fourthPlace) && player.id !== parseInt(formData.fifthPlace && player.id !== parseInt(formData.thirdPlace) &&
player.id !== parseInt(formData.seventhPlace) && player.id !== parseInt(formData.eighthPlace) && player.id !== parseInt(formData.ninthPlace)))
.map(player => (
<option key={player.id} value={player.id}>{player.name}</option>
))}
</Form.Control>
{formErrors['sixthPlace'] && (
<Form.Text
className="text-muted">A player is required
</Form.Text>
)}
</Form.Group>
}
{formData.numberOfPlayers > 6 &&
<Form.Group className="mb-3">
<Form.Label>Seventh Place</Form.Label>
<Form.Control
as="select"
defaultValue="def"
className={`${formErrors['seventhPlace'] ? 'is-invalid' : ''}`}
name="seventhPlace"
{...register('seventhPlace', { required: true })}
onChange={handleChange}>
<option value="def" disabled hidden>Select player</option>
{playerList.filter(player => player.userId === userId)
.filter(player => player.id !== parseInt(formData.firstPlace) && player.id !== parseInt(formData.secondPlace) &&
player.id !== parseInt(formData.fourthPlace) && player.id !== parseInt(formData.fifthPlace) && player.id !== parseInt(formData.sixthPlace) &&
player.id !== parseInt(formData.thirdPlace) && player.id !== parseInt(formData.eighthPlace) && player.id !== parseInt(formData.ninthPlace))
.map(player => (
<option key={player.id} value={player.id}>{player.name}</option>
))}
</Form.Control>
{formErrors['seventhPlace'] && (
<Form.Text
className="text-muted">A player is required
</Form.Text>
)}
</Form.Group>
}
{formData.numberOfPlayers > 7 &&
<Form.Group className="mb-3">
<Form.Label>Eighth Place</Form.Label>
<Form.Control
as="select"
className={`${formErrors['eighthPlace'] ? 'is-invalid' : ''}`}
defaultValue="def"
name="eighthPlace"
{...register('eighthPlace', { required: true })}
onChange={handleChange}>
<option value="def" disabled hidden>Select player</option>
{playerList.filter(player => player.userId === userId)
.filter(player => player.id !== parseInt(formData.firstPlace) && player.id !== parseInt(formData.secondPlace) &&
player.id !== parseInt(formData.fourthPlace) && player.id !== parseInt(formData.fifthPlace) && player.id !== parseInt(formData.sixthPlace) &&
player.id !== parseInt(formData.seventhPlace) && player.id !== parseInt(formData.thirdPlace) && player.id !== parseInt(formData.ninthPlace))
.map(player => (
<option key={player.id} value={player.id}>{player.name}</option>
))}
</Form.Control>
{formErrors['eighthPlace'] && (
<Form.Text className="text-muted">A player is required</Form.Text>
)}
</Form.Group>
}
{formData.numberOfPlayers > 8 &&
<Form.Group className="mb-3">
<Form.Label>Ninth Place</Form.Label>
<Form.Control
as="select"
className={`${formErrors['ninthPlace'] ? 'is-invalid' : ''}`}
name="ninthPlace"
defaultValue="def"
{...register('ninthPlace', { required: true })}
onChange={handleChange}>
<option value="def" disabled hidden>Select player</option>
{playerList.filter(player => player.userId === userId)
.filter(player => player.id !== parseInt(formData.firstPlace) && player.id !== parseInt(formData.secondPlace) &&
player.id !== parseInt(formData.fourthPlace) && player.id !== parseInt(formData.fifthPlace) && player.id !== parseInt(formData.sixthPlace) &&
player.id !== parseInt(formData.seventhPlace) && player.id !== parseInt(formData.eighthPlace) && player.id !== parseInt(formData.thirdPlace))
.map(player => (
<option key={player.id} value={player.id}>{player.name}</option>
))}
</Form.Control>
{formErrors['ninthPlace'] && (
<Form.Text className="text-muted">A player is required</Form.Text>
)}
</Form.Group>
}
<Form.Group className="mb-3">
<Form.Label>Date</Form.Label>
<Form.Control
type="text"
className={`${formErrors['date'] ? 'is-invalid' : ''}`}
placeholder="Date"
name="date"
{...register('date')}
/>
{formErrors['date'] && (
<Form.Text
className="text-muted">A valid date is required
</Form.Text>
)}
</Form.Group>
<Form.Group className="mb-3">
<Form.Label>Game name</Form.Label>
<Form.Control
type="text"
className={`${formErrors['name'] ? 'is-invalid' : ''}`}
placeholder="Game name"
name="name"
{...register('name')}
/>
{formErrors['name'] && (
<Form.Text
className="text-muted">A name is required for the game
</Form.Text>
)}
</Form.Group>
<Button
variant="none"
className="btn-default"
type="submit">
Add Game
</Button>
</Form>
}
</div>
</Col>
<Col className="outer-col"></Col>
</Row>
</Container>
)
}
export default GameAdd |
class Measurer {
constructor(fontFamily) {
const dom = document.createElement('canvas');
this.ctx = dom.getContext('2d');
this.fontFamily = fontFamily;
this.cache = {};
}
text(text, fontSize = 16) {
const key = `${text}${fontSize}`;
if (this.cache[key]) {
return this.cache[key];
}
this.ctx.font = `${fontSize}px ${this.fontFamily}`;
this.ctx.textBaseline = 'top';
const measure = this.ctx.measureText(text);
const result = {
width: measure.width,
height: measure.actualBoundingBoxDescent
};
this.cache[key] = result;
return result;
}
}
class Loader {
constructor() {
this.imageCache = {};
}
async loadImage(src) {
if (this.imageCache[src]) {
this.imageCache[src];
}
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => {
this.imageCache[src] = img;
resolve(img);
};
img.onerror = e => {
reject(e);
};
img.src = src;
});
}
}
const STAFF_LEVEL_BOX_COLOR_MAP = {
1: '#343a40',
2: '#f8f9fa',
3: '#28a745',
4: '#17a2b8',
5: '#ffc107',
6: '#dc3545'
};
const TEXT_COLOR = {
WHITE: 'white',
BLACK: '#212529'
};
const STAFF_LEVEL_FONT_COLOR_MAP = {
1: TEXT_COLOR.WHITE,
2: TEXT_COLOR.BLACK,
3: TEXT_COLOR.WHITE,
4: TEXT_COLOR.WHITE,
5: TEXT_COLOR.BLACK,
6: TEXT_COLOR.WHITE
};
class AkhrDrawer {
/**
*
* @param {HR_RESULT} hrList
* @param {number} width
* @param {number} padding
*/
constructor(hrList, width, padding, withStaffImage) {
this.hrList = hrList;
this.width = width;
this.padding = padding;
this.height = 0;
this.paths = [];
this.withStaffImage = withStaffImage;
this.measurer = new Measurer();
this.loader = new Loader();
}
async addImagePath(pointer, src, width, height, errorBackGround, borderRadius) {
let image = null;
try {
image = await this.loader.loadImage(src);
} catch (e) {
console.log('load image error, use default error color ');
}
this.paths.push({
type: 'image',
x: pointer.x,
y: pointer.y,
width,
height,
image,
bgColor: errorBackGround,
borderRadius
});
}
addPureBoxPath(pointer, width, height, backgroundColor) {
this.paths.push({
type: 'rect',
x: pointer.x,
y: pointer.y,
width,
height,
color: backgroundColor
});
}
addPureTextBoxPath(
pointer,
text,
fontSize,
paddingHorizontal,
boxHeight,
boxColor,
color,
borderRadius = 0,
doNotDraw
) {
const { width, height } = this.measurer.text(text, fontSize);
const boxWidth = width + paddingHorizontal * 2;
const rectPath = {
type: 'rect',
x: pointer.x,
y: pointer.y,
height: boxHeight,
width: boxWidth,
color: boxColor,
borderRadius
};
const textPath = {
type: 'text',
x: pointer.x + paddingHorizontal,
y: pointer.y + (boxHeight - height) / 2,
fontSize,
color,
content: text
};
if (!doNotDraw) {
this.paths.push(rectPath);
this.paths.push(textPath);
}
const resetXY = p => {
rectPath.x = p.x;
rectPath.y = p.y;
textPath.x = p.x + paddingHorizontal;
textPath.y = p.y + (boxHeight - height) / 2;
};
if (doNotDraw) {
return { boxWidth, resetXY, rectPath, textPath };
}
return { boxWidth, resetXY };
}
async addImageTextBoxPath(
pointer,
imageSrc,
imageMarginVertical,
imageMarginRight,
text,
fontSize,
paddingHorizontal,
boxHeight,
boxColor,
imageErrorColor,
color,
imageBorderRadius,
borderRadius = 0,
doNotDraw
) {
const { width, height } = this.measurer.text(text, fontSize);
let image = null;
try {
image = await this.loader.loadImage(imageSrc);
} catch (e) {
console.log(e);
console.log('image load error, use default error color');
}
const imageHeight = boxHeight - imageMarginVertical * 2;
const imageWidth = image ? imageHeight * (image.width / image.height) : imageHeight;
const boxWidth = imageWidth + imageMarginRight + width + paddingHorizontal * 2;
const rectPath = {
type: 'rect',
x: pointer.x,
y: pointer.y,
height: boxHeight,
width: boxWidth,
color: boxColor,
borderRadius
};
const imagePath = {
type: 'image',
x: pointer.x + paddingHorizontal,
y: pointer.y + imageMarginVertical,
height: imageHeight,
width: imageWidth,
bgColor: imageErrorColor,
image,
borderRadius: imageBorderRadius
};
const textPath = {
type: 'text',
x: pointer.x + paddingHorizontal + imageWidth + imageMarginRight,
y: pointer.y + (boxHeight - height) / 2,
fontSize,
color,
content: text
};
const resetXY = p => {
rectPath.x = p.x;
rectPath.y = p.y;
imagePath.x = p.x + paddingHorizontal;
imagePath.y = p.y + imageMarginVertical;
textPath.x = p.x + paddingHorizontal + imageWidth + imageMarginRight;
textPath.y = p.y + (boxHeight - height) / 2;
};
if (doNotDraw) {
return { boxWidth, resetXY, rectPath, imagePath, textPath };
}
return { boxWidth, resetXY };
}
addTagTextBox(pointer, tag, boxHeight) {
return this.addPureTextBoxPath(pointer, tag, 14, 10, boxHeight, '#6c757d', TEXT_COLOR.WHITE, 3);
}
getTagTextBox(pointer, tag, boxHeight) {
return this.addPureTextBoxPath(pointer, tag, 14, 10, boxHeight, '#6c757d', TEXT_COLOR.WHITE, 3, true);
}
getStaffTextBox(pointer, staff, boxHeight, level) {
return this.addPureTextBoxPath(
pointer,
staff.name,
14,
10,
boxHeight,
STAFF_LEVEL_BOX_COLOR_MAP[staff.level],
STAFF_LEVEL_FONT_COLOR_MAP[staff.level],
3,
true
);
}
getStaffImageTextBox(pointer, staff, boxHeight) {
return this.addImageTextBoxPath(
pointer,
`./res/akhr-chara/${staff.enName}.png`,
3,
5,
staff.name,
14,
10,
boxHeight,
STAFF_LEVEL_BOX_COLOR_MAP[staff.level],
'white',
STAFF_LEVEL_FONT_COLOR_MAP[staff.level],
3,
3,
true
);
}
addTitlePath() {
const content = '识别词条:';
const titleHeight = 20;
this.paths.push({ type: 'text', x: 0, y: 0, fontSize: titleHeight, content, color: TEXT_COLOR.BLACK });
this.height += this.measurer.text(content, titleHeight).height;
this.height += 10; // marginTop
const boxHeight = 35;
const pointer = { x: 0, y: this.height };
this.hrList.words.forEach(word => {
const { boxWidth, resetXY } = this.addTagTextBox(pointer, word, boxHeight);
if (pointer.x + boxWidth > this.width) {
// 一行放不下, 自动换行
pointer.x = 0;
pointer.y += boxHeight;
pointer.y += 10; // marginBottom
this.height = pointer.y;
resetXY(pointer);
}
pointer.x += boxWidth;
pointer.x += 10; // marginRight
});
if (this.hrList.words.length) {
this.height += boxHeight;
}
}
getCombineTagsPath(startPointer, tags) {
const tagsHeight = 35;
return tags.reduce(
(result, tag, index) => {
const { rectPath, textPath } = this.getTagTextBox(startPointer, tag, tagsHeight);
startPointer.y += tagsHeight;
result.height += tagsHeight;
startPointer.y += 10; // marginBottom
if (index < tags.length - 1) {
result.height += 10;
}
result.paths.push(rectPath);
result.paths.push(textPath);
return result;
},
{ height: 0, paths: [] }
);
}
async getStaffsPath(startPointer, maxWidth, staffs) {
const boxHeight = this.withStaffImage ? 40 : 35;
const paddingBottom = 10;
let lineCount = 1;
let width = 0;
const startX = startPointer.x;
const paths = await staffs.reduce(async (result, staff) => {
result = await result;
const getPathFunc = this[this.withStaffImage ? 'getStaffImageTextBox' : 'getStaffTextBox'];
const { boxWidth, resetXY, rectPath, textPath, imagePath } = await getPathFunc.call(
this,
startPointer,
staff,
boxHeight
);
if (width + boxWidth > maxWidth) {
// 一行放不下, 自动换行
startPointer.x = startX;
width = 0;
startPointer.y += boxHeight;
startPointer.y += paddingBottom; // marginBottom
lineCount += 1; // 记录新的一行
resetXY(startPointer);
}
startPointer.x += boxWidth;
startPointer.x += 10; // marginRight
width += boxWidth;
width += 10;
result.push(rectPath);
if (this.withStaffImage) {
result.push(imagePath);
}
result.push(textPath);
return result;
}, Promise.resolve([]));
return {
height: boxHeight * lineCount + paddingBottom * (lineCount - 1),
paths
};
}
async addRowPath({ tags, staffs }, index) {
const rowPadding = 8;
const tagsContainerMaxWidth = 120;
const staffsMaxWidth = this.width - tagsContainerMaxWidth;
const tagsStartPointer = { x: rowPadding, y: this.height + rowPadding };
const staffsStartPointer = { x: tagsContainerMaxWidth, y: this.height + rowPadding };
const { height: tagsHeight, paths: tagPaths } = this.getCombineTagsPath(tagsStartPointer, tags);
const { height: staffsHeight, paths: staffPaths } = await this.getStaffsPath(
staffsStartPointer,
staffsMaxWidth,
staffs,
true
);
const maxHeight = Math.max(tagsHeight, staffsHeight) + rowPadding * 2;
this.addPureBoxPath(
{ x: 0, y: this.height },
this.width,
maxHeight,
index % 2 ? 'transparent' : 'rgba(0,0,0,.1)'
);
this.paths = this.paths.concat(tagPaths, staffPaths);
this.height += maxHeight;
}
async addContentPath() {
this.height += 10; // marginTop
const { combined } = this.hrList;
for (let index in combined) {
await this.addRowPath(combined[index], index);
}
}
async getPath() {
this.addTitlePath();
await this.addContentPath();
}
drawRadiusRect(x, y, width, height, borderRadius) {
const r = borderRadius;
this.ctx.beginPath();
this.ctx.moveTo(x + r, y);
this.ctx.lineTo(x + width - r, y);
this.ctx.quadraticCurveTo(x + width, y, x + width, y + r);
this.ctx.lineTo(x + width, y + height - r);
this.ctx.quadraticCurveTo(x + width, y + height, x + width - r, y + height);
this.ctx.lineTo(x + r, y + height);
this.ctx.quadraticCurveTo(x, y + height, x, y + height - r);
this.ctx.lineTo(x, y + r);
this.ctx.quadraticCurveTo(x, y, x + r, y);
this.ctx.closePath();
}
drawRect({ color, x, y, width, height, borderRadius }) {
this.ctx.fillStyle = color;
if (!borderRadius) {
this.ctx.fillRect(x, y, width, height);
return;
}
this.drawRadiusRect(x, y, width, height, borderRadius);
this.ctx.fill();
}
drawImage({ x, y, width, height, image, bgColor = 'white', borderRadius }) {
if (!image && bgColor) {
this.drawRect({ color: bgColor, x, y, width, height, borderRadius });
return;
}
if (borderRadius) {
this.ctx.save();
this.drawRadiusRect(x, y, width, height, borderRadius);
this.ctx.clip();
this.ctx.drawImage(image, x, y, width, height);
this.ctx.restore();
} else {
this.ctx.drawImage(image, x, y, width, height);
}
}
drawText(path) {
this.ctx.fillStyle = path.color;
this.ctx.textBaseline = 'top';
this.ctx.font = `${path.fontSize}px sans-serif`;
this.ctx.fillText(path.content, path.x, path.y);
}
async draw() {
await this.getPath();
const dom = document.createElement('canvas');
this.ctx = dom.getContext('2d');
const domWidth = this.width + this.padding * 2;
const domHeight = this.height + this.padding * 2;
dom.style.width = domWidth;
dom.style.height = domHeight;
dom.width = domWidth;
dom.height = domHeight;
document.body.append(dom);
this.ctx.fillStyle = '#ECEFF1';
this.ctx.fillRect(0, 0, domWidth, domHeight);
this.ctx.fill();
const bgImage = await this.loader.loadImage(`./res/akhr-bg/${Math.floor(Math.random() * 70)}.png`);
const imgWidth = Math.min(this.width, this.height) * 0.7;
const imgHeigh = imgWidth * (bgImage.height / bgImage.width);
this.drawImage({
x: domWidth - imgWidth,
y: domHeight - imgHeigh,
width: imgWidth,
height: imgHeigh,
image: bgImage,
bgColor: '#ECEFF1'
});
this.ctx.fillStyle = 'rgba(255, 255, 255, 0.4)';
this.ctx.fillRect(0, 0, domWidth, domHeight);
this.ctx.fill();
this.ctx.translate(this.padding, this.padding);
this.paths.forEach(p => {
switch (p.type) {
case 'text':
this.drawText(p);
break;
case 'rect':
this.drawRect(p);
break;
case 'image':
this.drawImage(p);
break;
default:
}
});
}
}
const drawer = new AkhrDrawer(window.HR_RESULT, 1000, 10, true);
drawer.draw();
|
// pages/total/total.js
import * as echarts from '../../ec-canvas/echarts';
const app = getApp()
let interval = null
let interval1 = null
function initChart(canvas, width, height, dpr) {
const chart = echarts.init(canvas, null, {
width: width,
height: height,
devicePixelRatio: dpr // new
});
canvas.setChart(chart);
var option = {
backgroundColor: "#ffffff",
tooltip: {
trigger: 'item'
},
series: [{
label: {
normal: {
fontSize: 14
}
},
type: 'pie',
center: ['50%', '50%'],
radius: ['20%', '40%'],
data: [{
value: null,
name: '收入'
}, {
value: null,
name: '支出'
}]
}]
};
option.series[0].data[0].value = app.globalData.totalByMonth.incomeByMonth;
option.series[0].data[1].value = app.globalData.totalByMonth.expendByMonth;
chart.setOption(option, true);
interval = setInterval(function () {
option.series[0].data[0].value = app.globalData.totalByMonth.incomeByMonth;
option.series[0].data[1].value = app.globalData.totalByMonth.expendByMonth;
chart.setOption(option, true);
}, 3000)
return chart;
}
function lineInit(canvas, width, height, dpr) {
const chart = echarts.init(canvas, null, {
width: width,
height: height,
devicePixelRatio: dpr // new
});
canvas.setChart(chart);
var option = {
legend: {
data: ['收入', '支出'],
top: 50,
left: 'center',
z: 100
},
grid: {
containLabel: true
},
tooltip: {
show: true,
trigger: 'axis'
},
xAxis: {
type: 'category',
boundaryGap: false,
data: [],
// show: false
},
yAxis: {
x: 'center',
type: 'value',
splitLine: {
lineStyle: {
type: 'dashed'
}
}
},
series: [{
name: '收入',
type: 'line',
smooth: true,
data: []
}, {
name: '支出',
type: 'line',
smooth: true,
data: []
}]
};
option.xAxis.data = app.globalData.dateList
option.series[0].data = app.globalData.incomeByDay;
option.series[1].data = app.globalData.expendByDay;
chart.setOption(option, true);
interval1 = setInterval(function () {
option.xAxis.data = app.globalData.dateList
option.series[0].data = app.globalData.incomeByDay;
option.series[1].data = app.globalData.expendByDay;
chart.setOption(option, true);
}, 3000)
return chart;
}
Page({
/**
* 页面的初始数据
*/
data: {
ecpie: {
onInit: initChart
},
ecline: {
onInit: lineInit
},
expendByMonth: 0,
incomeByMonth: 0,
isShow: false,
optionPie: {},
optionLine: {}
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
if (app.globalData.items.length>0) {
this.setData({ isShow: true })
}
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
clearInterval(interval)
clearInterval(interval1)
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
}) |
import Vue from 'vue'
import Router from 'vue-router'
import welcome from '@/components/welcome'
import choose from '@/components/choose'
import choose2 from '@/components/choose2'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'welcome',
component: welcome
},
{
path:'/choose',
name:'choose',
component:choose
},
{
path:'/choose2',
name:'choose2',
component:choose2
},
{
path:'/',
redirect:'/'
}
]
})
|
const User = require('../Model/UserModel')
exports.bindwithUser =async(req,res,next)=>{
if (!req.session.isLoggIn) {
return next()
}
try{
let user = await User.findById(req.session.user._id)
req.user = user
next()
}
catch(err){
next(err)
}
}
exports.dashboardAthenticate =async(req,res,next)=>{
if (!req.session.isLoggIn) {
return res.redirect('/login')
}
return next()
}
exports.pollcreateAthenticate=(req,res,next)=>{
if(!req.session.isLoggIn){
return res.redirect("/")
}
return next()
}
exports.LOgInAndSingUpAthentication=async(req,res,next)=>{
if(req.session.isLoggIn){
return res.redirect('/school')
}
return next()
} |
'use strict';
/**
* This module provides the proxy configuration for the dev server.
*/
module.exports = function (grunt) {
var getProxyConfig = function () {
var backend = grunt.option('backend') || 'local';
if (backend === 'local') {
return [
{
context: ['/rest'],
host: 'localhost',
port: 8080
}
];
} else {
// server proxy config
return [
{
context: ['/rest'],
host: '??some-host.com??',
port: 443,
https: true,
changeOrigin: true,
rewrite: {
'^/rest': '/server-context/rest'
}
}
];
}
};
var configureMiddlewares = function (connect, options) {
if (!Array.isArray(options.base)) {
options.base = [options.base];
}
var middlewares = [];
middlewares.push(require('grunt-connect-proxy/lib/utils').proxyRequest);
middlewares.push(require('grunt-connect-rewrite/lib/utils').rewriteRequest);
// Serve static files.
options.base.forEach(function (base) {
middlewares.push(connect.static(base));
});
// Make directory browse-able.
var directory = options.directory || options.base[options.base.length - 1];
middlewares.push(connect.directory(directory));
return middlewares;
};
return {
middlewares: configureMiddlewares,
proxies: getProxyConfig()
};
}; |
import React, {Component} from 'react';
import {View,Text,StyleSheet,FlatList,TouchableHighlight,ActivityIndicator} from 'react-native';
import { connect } from 'react-redux';
import ContatoItem from '../components/ContatoList/ContatoItem';
import { getContactList ,createChat} from '../actions/ChatActions';
export class ContatoList extends Component{
static navigationOptions = {
title:'',
tabBarLabel:'Contatos',
header:null
}
constructor(props){
super(props);
this.state = {
loading:true
};
console.disableYellowBox = true;
this.contatoClick = this.contatoClick.bind(this);
this.props.getContactList(this.props.uid, ()=>{
this.setState({loading:false});
}); //passando o usuário logado como parâmetro para filtrar a lista
}
contatoClick(item){
//alert('Chamando: '+item.name+' Key:'+item.key);
let found = false;
for(var i in this.props.chats){
if(this.props.chats[i].other==item.key){
found=true;
}
}
if(found==false){
this.props.createChat(this.props.uid,item.key);
this.props.navigation.navigate('ConversasStack'); //mandar para a stacknavigator
}else{
alert('já existe conversa');
}
}
render(){
return(
<View style={styles.container}>
{this.state.loading && <ActivityIndicator size='large'/> /*CONDIÇÃO TERNÁRIA PARA APARECER O LOADING*/}
<FlatList
data ={this.props.contacts}
renderItem = {({item}) => (
<TouchableHighlight
underlayColor="#DDDDDD"
style={styles.buttonArea} onPress={() => this.contatoClick(item)}>
<View >
<Text>{item.name}</Text>
</View>
</TouchableHighlight>
)}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
margin:10
},
buttonArea:{
height:40,
flex:1,
justifyContent:'center',
paddingLeft:10,
borderBottomWidth:1,
borderBottomColor:'#CCCCCC'
}
});
//retorna user e senha por exemplo
const mapStateToProps = (state)=>{
return {
uid:state.auth.uid,
contacts:state.chat.contacts,
chats:state.chat.chats
};
};
//checklogin são as ações que podem ser executadas nessa tela, final a tela que vai abrir
const ContatoListConnect = connect(mapStateToProps,{getContactList,createChat })(ContatoList);
export default ContatoListConnect; |
/*
*
* More info at https://github.com/JawaJava/Jakarta-Cute-Dropdown/blob/master/LICENSE
*
* Copyright (c) 2015, Jawa Java, Rudy Hermawan
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
;(function($, window, document, undefined){
if(typeof undefined !== "undefined") {
undefined = void 0;
}
var n = 5000;
$.fn.jktCD = function(options){
var s = $.extend({
cssName : 'jktCD',
partClick : '.jktCD-click',
partMain : '.jktCD-style-one',
typeCursor : 'hover', // click | hover | both,
triActive : true,
mainLeft : 0,
triLeft : 10
}, options);
//main name plugin
var cssName_ = s.cssName;
//temp data for replace data in style
var temp_loop = '.data-loop-'+cssName_+'{}';
//base in array data each declarate
var base = $(this);
var nameLeft;
//n number of length, z_i for handle z-index per loop
n -= base.length;
var z_i = n--;
//adding style area for plugin use
if($('#hidden-part_'+cssName_).length == 0){
$('body').append('<div id="hidden-part_'+cssName_+'" style="display:none"><style>'+temp_loop+'</style></div>');
}
//to add new element css for plugin usage
function changeCss(css){
var tg = $('#hidden-part_'+cssName_);
var template = tg.html();
//check exist of class
var y = new RegExp(css);
if( ! y.test(template)){
template = template.replace(temp_loop, css+' '+temp_loop);
tg.html(template);
}
}
return this.each(function(e, y){
var this_click = $(this);
//part element per loop
var main_part = this_click.find('.'+cssName_+'-main');
z_i--;
if(e == 0) {
nameLeft = cssName_+'-left-after-'+s.triLeft;
//adding new css class element spesific of triangle on top of main box
changeCss('.'+cssName_+'-main.'+nameLeft+':after{left:'+s.triLeft+'px !important;}');
}
//handle main box position
if(s.mainLeft != 0) main_part.css({'left':s.mainLeft+'px'});
//adding with change display of triangle on main box
if(s.triActive == false) main_part.toggleClass(cssName_+'-hide-after');
//adding class on var nameLeft in main box for handle left from them
if(s.triLeft != 10 && s.triLeft > 0) main_part.toggleClass(nameLeft);
this_click.css({'position':'relative','z-index':z_i});
var y = 'mouseenter click';
//made change if desktop, option of click or mouseenter
if( ! /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
y = ((s.typeCursor == 'hover') ? 'mouseenter' : ((s.typeCursor == 'both') ? 'mouseenter click' : 'click'));
}
this_click.find(s.partClick).unbind(y);
this_click.find(s.partClick).bind(y, function(e){
e.stopPropagation();
base.find('.'+cssName_+'-main').hide();
var t = $(this).parent().find('.'+cssName_+'-main');
t.toggle();
});
$(document).unbind('click');
$(document).bind('click', function(e){
$(this).find('.'+cssName_+'-main').hide();
});
});
};
})(jQuery, this, document); |
;
'use strict';
import '../styles/app.scss';
import frontReducer from './reducers/front-reducer';
import rightReducer from './reducers/right-reducer';
import topReducer from './reducers/top-reducer';
import leftReducer from './reducers/left-reducer';
import backReducer from './reducers/back-reducer';
import downReducer from './reducers/down-reducer';
import { CUBE, ACTION, STATES } from './constants';
import { log } from './logger';
import { qs, qsa, byId } from './query';
import { dictStateRotate, dictTransform } from './dictionaries/dictionary';
import { cloneObject, transformsApply } from './cube-util';
log('App running');
const Hammer = window.Hammer;
const hammerOptions = {
preventDefault: true
};
let _state = {};
function getState() {
return _state;
}
function initState() {
_state = {
value: 'tf', // top front
stateHistory: ['tf'],
actionHistory: [],
transforms: [],
};
}
function formatDate(date) {
return `${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`;
}
function setState(newState) {
_state = newState;
return this;
}
function updateUiByState(state) {
if (state.transforms && state.transforms.length) {
const transforms = state.transforms.map(t => `rotate${t.key}(${t.val}deg)`);
cubeElement.style.transform = transforms.join(' ');
}
return this;
}
function truncateTransforms(state) {
if (state.transforms.length >= 4) {
// todo
}
return this;
}
function getDebugData(face, eventtype) {
return `
<div class='event'>${face} ${eventtype}</div>
<div class='state'> ${JSON.stringify(getState())}</div>
<div class='transform'> ${cubeElement.style.transform}</div>
<div class='time'> ${(formatDate(new Date()))}</div>
`;
}
const debug = qs('.debug'),
cubeElement = byId('cube-1x1'),
frontElement = byId('front'),
topElement = byId('top'),
rightElement = byId('right'),
leftElement = byId('left'),
backElement = byId('back'),
downElement = byId('down');
cubeElement.addEventListener('transitionend', (ev) => {
let state = getState();
if (state.transforms && state.transforms.length >= 4) {
// cubeElement.classList.add('u-no-transition-important');
// cubeElement.offsetHeight;
//cubeElement.classList.remove('u-no-transition-important');
}
});
/* Init */
const hammerFront = new Hammer(frontElement, hammerOptions);
hammerFront.get('swipe').set({
direction: Hammer.DIRECTION_ALL
});
const hammerTop = new Hammer(topElement, hammerOptions);
hammerTop.get('swipe').set({
direction: Hammer.DIRECTION_ALL
});
const hammerRight = new Hammer(rightElement, hammerOptions);
hammerRight.get('swipe').set({
direction: Hammer.DIRECTION_ALL
});
const hammerBack = new Hammer(backElement, hammerOptions);
hammerBack.get('swipe').set({
direction: Hammer.DIRECTION_ALL
});
const hammerDown = new Hammer(downElement, hammerOptions);
hammerDown.get('swipe').set({
direction: Hammer.DIRECTION_ALL
});
const hammerLeft = new Hammer(leftElement, hammerOptions);
hammerLeft.get('swipe').set({
direction: Hammer.DIRECTION_ALL
});
//-----------
/* Setup */
const hammerEvents = 'swipeleft swiperight swipeup swipedown';
hammerFront.on(hammerEvents, (ev) => {
const action = { type: ev.type },
newState = frontReducer(getState(), action);
truncateTransforms(newState);
setState(newState);
updateUiByState(newState);
debug.innerHTML = getDebugData('front', ev.type);
log(ev.type);
});
hammerRight.on(hammerEvents, (ev) => {
const action = { type: ev.type };
const newState = rightReducer(getState(), action);
truncateTransforms(newState);
setState(newState);
updateUiByState(newState);
debug.innerHTML = getDebugData('right', ev.type);
log(ev.type);
});
hammerLeft.on(hammerEvents, (ev) => {
const action = { type: ev.type };
const newState = leftReducer(getState(), action);
truncateTransforms(newState);
setState(newState);
updateUiByState(newState);
debug.innerHTML = getDebugData('left', ev.type);
log(ev.type);
});
hammerBack.on(hammerEvents, (ev) => {
const action = { type: ev.type };
const newState = backReducer(getState(), action);
truncateTransforms(newState);
setState(newState);
updateUiByState(newState);
debug.innerHTML = getDebugData('back', ev.type);
log(ev.type);
});
hammerTop.on(hammerEvents, (ev) => {
const action = { type: ev.type };
const newState = topReducer(getState(), action);
truncateTransforms(newState);
setState(newState);
updateUiByState(newState);
debug.innerHTML = getDebugData('top', ev.type);
log(ev.type);
});
hammerDown.on(hammerEvents, (ev) => {
const action = { type: ev.type },
newState = downReducer(getState(), action);
truncateTransforms(newState);
setState(newState);
updateUiByState(newState);
debug.innerHTML = getDebugData('down', ev.type);
log(ev.type);
});
function rotateTo(stateCode) {
let transformCodes = dictStateRotate[stateCode];
if (transformCodes && transformCodes.length) {
let transformKeyVals = transformCodes.map(t => dictTransform[t]),
transforms = transformKeyVals.map(t => `rotate${t.key}(${t.val}deg)`),
nextState = Object.assign({}, getState());
nextState.value = stateCode;
nextState.stateHistory.push(stateCode);
nextState.actionHistory.push(`rotateTo: ${stateCode}`);
nextState.transforms = transformKeyVals;
setState(nextState);
updateUiByState(nextState);
return getState();
}
}
function x() {
const newState = frontReducer(getState(), { type: 'swipeup' });
truncateTransforms(newState);
setState(newState);
updateUiByState(newState);
debug.innerHTML = getDebugData('front', 'swipeup');
}
function _x() {
const newState = frontReducer(getState(), { type: 'swipedown' });
truncateTransforms(newState);
setState(newState);
updateUiByState(newState);
debug.innerHTML = getDebugData('front', 'swipedown');
}
function y() {
const newState = frontReducer(getState(), { type: 'swiperight' });
truncateTransforms(newState);
setState(newState);
updateUiByState(newState);
debug.innerHTML = getDebugData('front', 'swiperight');
}
function _y() {
const newState = frontReducer(getState(), { type: 'swipeleft' });
truncateTransforms(newState);
setState(newState);
updateUiByState(newState);
debug.innerHTML = getDebugData('front', 'swipeleft');
}
function z() {
const newState = topReducer(getState(), { type: 'swiperight' });
truncateTransforms(newState);
setState(newState);
updateUiByState(newState);
debug.innerHTML = getDebugData('top', 'swiperight');
}
function _z() {
const newState = topReducer(getState(), { type: 'swipeleft' });
truncateTransforms(newState);
setState(newState);
updateUiByState(newState);
debug.innerHTML = getDebugData('top', 'swipeleft');
}
function uix() {
ui({ key: 'x', val: 90 });
debug.innerHTML = getDebugData('ui', 'x');
}
function ui_x() {
ui({ key: 'x', val: -90 });
debug.innerHTML = getDebugData('ui', '-x');
}
function uiy() {
ui({ key: 'y', val: 90 });
debug.innerHTML = getDebugData('ui', 'y');
}
function ui_y() {
ui({ key: 'y', val: -90 });
debug.innerHTML = getDebugData('ui', '-y');
}
function uiz() {
ui({ key: 'z', val: 90 });
debug.innerHTML = getDebugData('ui', 'z');
}
function ui_z() {
ui({ key: 'z', val: -90 });
debug.innerHTML = getDebugData('ui', '-z');
}
function ui(transformKeyVal) {
let newState = cloneObject(getState());
transformsApply(transformKeyVal, newState);
truncateTransforms(newState);
setState(newState);
updateUiByState(newState);
}
function uiRotateTo(event) {
let component = document.getElementById('cube-rotate-to');
let value = component.querySelector('input').value;
if (value) {
rotateTo(value);
}
}
initState();
const inputPlaceholder = Object.keys(STATES).join(' ');
const rotateToEl = document.getElementById('cube-rotate-to');
rotateToEl.querySelector('input').setAttribute('placeholder', inputPlaceholder);
rotateToEl.addEventListener('keypress', ev => {
const key = ev.which || ev.keyCode;
const ENTER = 13;
if (key === ENTER) {
uiRotateTo(event);
}
});
window.app = window.cube = {
rotateTo,
uiRotateTo,
x,
_x,
y,
_y,
z,
_z,
uix,
ui_x,
uiy,
ui_y,
uiz,
ui_z,
debug: {
cubeEl: cubeElement,
getState,
STATES,
}
};
export class App {
constructor() {}
} |
// Finish the solution so that it sorts the passed in array of numbers. If the function passes in an empty array or null/nil value then it should return an empty array.
// For example:
// solution([1, 2, 10, 50, 5]); // should return [1,2,5,10,50]
// solution(null); // should return []
// function solution(nums){
// }
//parameters
//an array of numbers
//return
//sorted array of numbers
//examples
//console.log(solution([1, 2, 10, 50, 5])) //[1,2,5,10,50]
//PSEUDOCODE
//need to use sort and make sure that an eempty or "null" will return []
// const solution = nums => [...new Float64Array(nums).sort()];
// if (nums && nums !== []) {
// return nums.sort((a,b) => {
// if (a < b) {
// return -1;
// }
// if ( a > b) {
// return 1;
// }
// return 0
// });
// }
// else {
// return []
// }
// }
let solution = nums => [...nums].sort((a, b) => a - b);
console.log([1, 2, 10, 50, 5]) |
import React from "react"
import { Provider } from "react-redux"
// import createStore from "./src/store/createStore"
import { createStore as reduxCreateStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk'
import reducer from './src/store/reducer'
// import rootReducer from '.';
const windowGlobal = typeof window !== 'undefined' && window;
const devtools =
process.env.NODE_ENV === 'development' && windowGlobal.devToolsExtension
? window.__REDUX_DEVTOOLS_EXTENSION__ &&
window.__REDUX_DEVTOOLS_EXTENSION__()
: f => f;
// const createStore = () => reduxCreateStore(reducer, applyMiddleware(thunk));
const createStore = () => reduxCreateStore(reducer, compose(applyMiddleware(thunk), devtools));
// export default ({ element }) => (
// <Provider store={createStore()}>{element}</Provider>
// );
// eslint-disable-next-line react/display-name,react/prop-types
function wrapWithProvider({ element }) {
const store = createStore()
return <Provider store={store}>{element}</Provider>
}
export default wrapWithProvider |
import mongoose from 'mongoose';
const companySchema = new mongoose.Schema({
name: { type: String, trim: true },
description: { type: String, trim: true },
punchcard_lifetime: { type: Number, min: 0 }
});
if (!companySchema.options.toJSON) { companySchema.options.toJSON = {}; }
if (!companySchema.options.toObject) { companySchema.options.toObject = {}; }
companySchema.options.toJSON.transform = companySchema.options.toObject.transform = (doc, ret) => {
delete ret.__v;
};
const Company = mongoose.model('Company', companySchema);
export default Company;
|
const DATE = new Date();
const YEAR = DATE.getFullYear();
const MONTH = DATE.getMonth() + 1;
const DAY = DATE.getDate();
const WEEKTABLE = {
common: {
cn: ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'],
cns: ['日', '一', '二', '三', '四', '五', '六'],
en: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
},
intl: {
cn: ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日'],
cns: ['一', '二', '三', '四', '五', '六', '日'],
en: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
}
};
//修正年月
function fixedYM(year , month ) {
if (+month === 0) {
year = +year - 1;
month = 12;
};
if (+month === 13) {
year = +year + 1;
month = 1;
};
return [year, month];
};
//获取某年某月有多少天
function getMonthDays(year, month) {
const YM = this.fixedYM(year, month);
return new Date(YM[0], YM[1], 0).getDate();
};
//返回某年某月某日是星期几
function getWeekday(year, month, day) {
const YM = this.fixedYM(year, month);
return new Date(YM[0], YM[1] - 1, day).getDay();
};
//获取某年某月的具体天数的排列顺序
function getMonthDaysArray(year , month , day) {
if (typeof day === 'undefined' && year === YEAR && month === MONTH) day = DAY;
let dayArrays = [];
const days = this.getMonthDays(year, month), preDays = this.getMonthDays(year, month - 1);
const thisMonthFirstDayInWeek = this.getWeekday(year, month, 1), thisMonthLastDayInWeek = this.getWeekday(year, month, days);
const thisMonthAllDays = thisMonthFirstDayInWeek + days + 6 - thisMonthLastDayInWeek;
//上月在当月日历面板中的排列
for (let i = 0; i < thisMonthFirstDayInWeek; i++) {
dayArrays.push({
dayNum: (preDays - thisMonthFirstDayInWeek + i + 1),
weekDay: WEEKTABLE.common.cn[i]
})
}
//当月日历面板中的排列
for (let i = 1; i <= days; i++) {
const weekDayFlag = (thisMonthFirstDayInWeek + i - 1) % 7
dayArrays.push({
dayNum: i,
weekDay: WEEKTABLE.common.cn[weekDayFlag],
selected: i === +day,
isThisMonth: true
})
};
//下月在当月日历面板中的排列
for (let i = 1; i <= (6 - thisMonthLastDayInWeek); i++) {
const weekDayFlag = (thisMonthFirstDayInWeek + days + i - 1) % 7
dayArrays.push({
dayNum: i,
weekDay: WEEKTABLE.common.cn[weekDayFlag]
})
};
return dayArrays;
}
var dArrays=getMonthDaysArray(YEAR,MONTH,DAY);
console.log(dArrays);
function getStr(dArrays) {
var str="";
for (var i=0;i<dArrays.length/7;i++){
str+="<tr>";
for (var j=i*7;j<(i*7+7);j++) {
str+="<td>"+dArrays[j].dayNum+"</td>";
}
str+="</tr>";
}
return str;
}
$(function () {
$("li:nth-of-type(2)").html(YEAR);
$("li:nth-of-type(3)").html(MONTH);
var sid=$("#attence_aid").html();
var str=getStr(dArrays);
$("#calendar_body").html(str);
console.log(YEAR);
console.log(MONTH);
var attenceTime=new Date(YEAR,MONTH-1,1);
var data={
sId:sid,
attenceTime:attenceTime
}
$.ajax({
type:'POST',
url:'attence/getAttence',
data:JSON.stringify(data),
cache: false, // 是否缓存
async: true, // 是否异步执行
processData: false, // 是否处理发送的数据 (必须false才会避开jQuery对 formdata 的默认处理)
contentType: 'application/json;charset=UTF-8', // 设置Content-Type请求头
success:function (resultData) {
console.log(resultData);
for (var i = 0; i < resultData.length; i++){
var attenceTime = resultData[i];
console.log(attenceTime);
for (var j=0;j<dArrays.length;j++){
if (dArrays[j].isThisMonth) {
if (attenceTime===dArrays[j].dayNum){
var ctd = document.getElementsByTagName("td")[j];
ctd.style.backgroundColor="orange";
ctd.style.borderRadius="50%";
console.log(j);
}
}
}
}
}
});
$("#clock_in").click(function () {
var data1={
sId:sid
}
$.ajax({
type:'POST',
url:'attence/insert',
data:JSON.stringify(data1),
cache: false, // 是否缓存
async: true, // 是否异步执行
processData: false, // 是否处理发送的数据 (必须false才会避开jQuery对 formdata 的默认处理)
contentType: 'application/json;charset=UTF-8', // 设置Content-Type请求头
success:function (data) {
if (data=="success") {
alert("打卡成功!");
}else if (data=="no") {
alert("您今日已打卡,不能重复打卡!")
}else if (data=="later") {
alert("您已迟到!");
}
window.location.reload();
},
error:function (resultData) {
alert("打卡失败!");
}
});
});
var yea=parseInt($("#calender_header li:nth-of-type(2)").html());
var mon=parseInt($("#calender_header li:nth-of-type(3)").html());
console.log(yea);
console.log(mon);
$("#calender_header li:nth-of-type(1)").click(function () {
if (mon == 1) {
mon=12;
yea-=1;
}else {
mon-=1;
}
data.attenceTime=new Date(yea,mon-1);
$("#calender_header li:nth-of-type(2)").html(yea);
$("#calender_header li:nth-of-type(3)").html(mon);
var das=getMonthDaysArray(yea,mon,DAY);
var str=getStr(das);
$("#calendar_body").html(str);
$("#calendar_day td").removeClass("calendar_attence");
$.ajax({
type:'POST',
url:'attence/getAttence',
data:JSON.stringify(data),
cache: false, // 是否缓存
async: true, // 是否异步执行
processData: false, // 是否处理发送的数据 (必须false才会避开jQuery对 formdata 的默认处理)
contentType: 'application/json;charset=UTF-8', // 设置Content-Type请求头
success:function (resultData) {
for (var i = 0; i < resultData.length; i++){
var attenceTime = resultData[i];
for (var j=0;j<dArrays.length;j++){
if (dArrays[j].isThisMonth) {
if (attenceTime===dArrays[j].dayNum){
var ctd = document.getElementsByTagName("td")[j];
ctd.style.backgroundColor="orange";
ctd.style.borderRadius="50%";
console.log(j);
}
}
}
}
}
});
});
$("#calender_header li:nth-of-type(4)").click(function () {
if (mon == 12) {
mon=1;
yea+=1;
}else {
mon+=1;
}
data.attenceTime=new Date(yea,mon-1);
$("#calender_header li:nth-of-type(2)").html(yea);
$("#calender_header li:nth-of-type(3)").html(mon);
var das=getMonthDaysArray(yea,mon,DAY);
var str=getStr(das);
$("#calendar_body").html(str);
$("#calendar_day td").removeClass("calendar_attence");
$.ajax({
type:'POST',
url:'attence/getAttence',
data:JSON.stringify(data),
cache: false, // 是否缓存
async: true, // 是否异步执行
processData: false, // 是否处理发送的数据 (必须false才会避开jQuery对 formdata 的默认处理)
contentType: 'application/json;charset=UTF-8', // 设置Content-Type请求头
success:function (resultData) {
for (var i = 0; i < resultData.length; i++){
var attenceTime = resultData[i];
for (var j=0;j<dArrays.length;j++){
if (dArrays[j].isThisMonth) {
if (attenceTime===dArrays[j].dayNum){
var ctd = document.getElementsByTagName("td")[j];
ctd.style.backgroundColor="orange";
ctd.style.borderRadius="50%";
console.log(j);
}
}
}
}
}
});
});
}); |
import React, { Component } from 'react'
export default class Counter extends Component {
increment = () => {
const { select_number } = this.refs
this.props.increment(select_number.value * 1)
}
decrement = () => {
const { select_number } = this.refs
this.props.decrement(select_number.value * 1)
}
incrementIfOdd = () => {
const { select_number } = this.refs
const {count} = this.props
if (count % 2 === 1) {
this.props.increment(select_number.value * 1)
}
}
incrementAsync = () => {
const { select_number } = this.refs
setTimeout(() => {
this.props.increment(select_number.value * 1)
}, 500)
}
render() {
return (
<div>
<span>count is {this.props.count}</span><br />
<select ref='select_number'>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
</select>
<button onClick={this.increment}>+</button>
<button onClick={this.decrement}>-</button>
<button onClick={this.incrementIfOdd}>increment if odd</button>
<button onClick={this.incrementAsync}>increment async</button>
</div>
)
}
}
|
const { searchHotActivityList, searchProductId } = require('../Model/search');
const getHotActivity = (req, res) => {
searchHotActivityList()
.then((activityList) => {
res.json(activityList);
})
.catch((err) => {
throw err;
});
};
const getProductInfo = (req, res) => {
searchProductId()
.then((productBriefInfo) => {
res.json(productBriefInfo);
})
.catch((err) => {
throw err;
});
};
module.exports = {
getHotActivity,
getProductInfo,
};
|
var variables________________________________8________________8js________8js____8js__8js_8js =
[
[ "variables________________8________8js____8js__8js_8js", "variables________________________________8________________8js________8js____8js__8js_8js.html#aa20e08551125f5d35a89f1acae12b279", null ]
]; |
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import InputBar from './components/input_bar';
import TaskList from './components/task_list';
//const App = () => <h1>Hello World</h1>;
class App extends Component {
constructor(props) {
super(props);
this.state = {
task: []
};
this.getInput = this.getInput.bind(this);
this.deleteInput = this.deleteInput.bind(this);
}
getInput(event) {
event.preventDefault();
this.setState({ task: [...this.state.task, event.target.task.value] });
event.target.task.value = '';
}
deleteInput(index) {
const newTaskList = this.state.task.filter((a, i) => {
return index !== i;
});
this.setState({ task: newTaskList });
}
render() {
return (
<div>
<h1>To-Do App</h1>
<InputBar handler={this.getInput} />
<TaskList delete={this.deleteInput} task={this.state.task} />
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
|
/**
* performance.now cross-browser
* @author Colin Mutter <colin.mutter@gmail.com>
*/
/**
* Deps
*/
var bind = require('./bind');
/**
* Determine nav start offset w/o global polyfill for unsupprted clients
*/
var nowOffset;
if (typeof window.performance === 'undefined' || !window.performance.timing) {
nowOffset = +new Date();
}
else {
nowOffset = window.performance.timing.navigationStart || +new Date();
}
/**
* performance.now cross-browser
* @return {Number}
*/
module.exports = function now() {
var perf;
if (typeof window.performance === 'undefined' || !window.performance.now) {
perf = {};
}
else {
perf = window.performance;
}
/**
* Return a cross-browser performance.now result
*/
var val = bind(perf, (perf.now ||
perf.mozNow ||
perf.msNow ||
perf.oNow ||
perf.webkitNow ||
function () {
return (+new Date() - nowOffset);
}))();
console.log(+new Date(), nowOffset, parseFloat(val));
} |
'use strict';
window.app = (function (angular) {
var appVersion = 1;
var app = angular.module('app', ['ngMaterial']);
app.controller('mainController', ['$scope', function ($scope) {
$scope.btnClick = function (e) {
$scope.result = 'Clicked: ' + new Date().toLocaleString();
};
}]);
return app;
})(angular, undefined); |
var mostrarSite = true
const site = 'www.augustoludovice.com'
console.log('Hello Word!')
console.log('Meu nome é Augusto!')
console.log('E eu estou aprendendo Node.js com o Guia do programador')
if(mostrarSite){
console.log(site)
} |
import inView from "in-view";
require('../menu');
inView.threshold(0.6);
inView('.service')
.on('enter', (el) => {
document.body.setAttribute(`class`, el.getAttribute(`data-section`));
})
.on('exit', (el) => {
// document.body.setAttribute(`class`, ``);
}); |
var searchData=
[
['reorder_5fgraphs',['reorder_graphs',['../main_8cpp.html#a6ab5cc576d7a5d4a62cbac77ef88c364',1,'main.cpp']]],
['reorder_5fmatrix',['reorder_matrix',['../main_8cpp.html#a89793f8c7939fe2032afeb0295764fb6',1,'main.cpp']]]
];
|
import actionTypes from 'constants/action-types';
export default {
open: () => ({
type: actionTypes.uploadModalState.OPEN
}),
close: () => ({
type: actionTypes.uploadModalState.CLOSE
})
};
|
const fs = require('fs');
const http = require('http');
const PORT = process.env.PORT || 3050;
const server = http.createServer();
// var movies = { success: null, movies: [] };
// var names = ['Interstaller', 'Anatolia', 'MUSTAFA KEMAL ATATURK'];
// const success = 1;
// movies.success = success;
// names.forEach(name => {
// const index = movies.movies.indexOf(name);
// if (index == -1) {
// movies.movies.push({name:name});
// }
// });
// let jsonFormat = JSON.stringify(movies);
// console.log(jsonFormat);
// fs.appendFile('test.json',jsonFormat.toString(), (err) => {
// if (err) throw err;
// console.log('Append or Create Success');
// });
// const file = 'test.json';
// const readStream = fs.createReadStream(file);
// let len = 0;
// fs.stat(file, (err, data) => {
// console.log(data.size);
// readStream.on('data', (chunk) => {
// len += chunk.length;
// console.log(len);
// });
// });
// // fs.stat(file,(err,data)=>{
// // console.log(data.size);
// // readStream.on('data',(chunk)=>{
// // len += chunk.length;
// // console.log(len);
// // console.log(chunk.toString());
// // });
// // });
// const readJson = fs.readFileSync(file);
// // console.log(JSON.parse(readJson));
// readStream.on('end', () => {
// console.log('Finished');
// });
// readStream.on('data', (chunk) => {
// len += chunk.length;
// console.log(len);
// console.log(chunk.toString());
// server.on('request', (req, res) => {
// res.writeHead(200, { 'Content-Type': 'application/json; charset = utf-8' });
// res.end(chunk.toString());
// }).listen(PORT);
// });
/// Emitter & event
// const events = require('events');
// const eventEmitter = new events.EventEmitter();
// eventEmitter.on('hey', (object) => {
// console.log('Sey Hello' + object.name + object.lastname);
// });
// eventEmitter.emit('hey', { name: 'Taylan', lastname: 'YILDIZ' });
// eventEmitter.once('ok', () => {
// console.log('Just Run Once');
// });
// eventEmitter.emit('ok');
// eventEmitter.emit('ok');
// eventEmitter.emit('ok');
const events = require('events');
const eventEmitter = new events.EventEmitter();
// eventEmitter.on('connection', (port) => {
// console.log('Connection : '+port);
// });
// eventEmitter.emit('connection',1883);
const _server = {
host: 'http://255.234.23.1',
port: 1883
};
eventEmitter.once('connected', (url) => {
console.log(`${url.host} : ${url.port}`);
});
eventEmitter.emit('connected',_server); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.