text
stringlengths 7
3.69M
|
|---|
/* jshint node: true, -W030 */
/* globals Phoenix, Window, Modal, Screen, _ */
'use strict';
var keys = [];
var cmd = ['cmd'];
var cmdAlt = ['cmd', 'alt'];
var grids = {
'1 Up': {rows: 1, cols: 1},
'2 Up': {rows: 1, cols: 2},
'3 Up': {rows: 1, cols: 3},
'4 Up': {rows: 2, cols: 2},
'6 Up': {rows: 2, cols: 3},
'9 Up': {rows: 3, cols: 3},
};
function grid(name) {
var rows = grids[name].rows;
var cols = grids[name].cols;
return function applyGrid() {
var windows = Window.visibleWindowsInOrder();
windows.splice(Math.min(windows.length, cols*rows));
var pre = windows.length;
var sFrame = Screen.mainScreen().visibleFrameInRectangle();
var width = Math.round(sFrame.width / cols);
var height = Math.round(sFrame.height / rows);
var x = sFrame.x;
var y = sFrame.y;
_.times(cols, function(col) {
_.times(rows, function(row) {
var n = col + (row*cols);
var rect = {x: x + (col*width), y: y + (row*height), width: width, height: height};
if (windows.length > n) {
windows[n].setFrame(rect);
}
});
});
};
}
keys.push(Phoenix.bind('1', cmd, grid('1 Up')));
keys.push(Phoenix.bind('2', cmd, grid('2 Up')));
keys.push(Phoenix.bind('3', cmd, grid('3 Up')));
keys.push(Phoenix.bind('4', cmd, grid('4 Up')));
keys.push(Phoenix.bind('6', cmd, grid('6 Up')));
keys.push(Phoenix.bind('9', cmd, grid('9 Up')));
function moveFocusFn(dir) {
return function moveFocus() {
var fnNames = {
h: 'focusClosestWindowInWest',
j: 'focusClosestWindowInSouth',
k: 'focusClosestWindowInNorth',
l: 'focusClosestWindowInEast'
};
Window.focusedWindow()[fnNames[dir]]();
};
}
keys.push(Phoenix.bind('h', cmdAlt, moveFocusFn('h')));
keys.push(Phoenix.bind('j', cmdAlt, moveFocusFn('j')));
keys.push(Phoenix.bind('k', cmdAlt, moveFocusFn('k')));
keys.push(Phoenix.bind('l', cmdAlt, moveFocusFn('l')));
function showCenteredModal(message, offset) {
var m = new Modal();
m.duration = 0.5;
m.message = message;
var sFrame = Screen.mainScreen().visibleFrameInRectangle();
var mFrame = m.frame();
var mX = Math.round((sFrame.width / 2) - (mFrame.width / 2));
var mY = Math.round((sFrame.height / 2) - (mFrame.height / 2));
if (!offset) {
offset = {x: 0, y: 0};
}
m.origin = {x: sFrame.x + mX + offset.x, y: sFrame.y + mY + offset.y};
m.show();
}
|
"use strict";
var models = require('../models');
var shortid = require('shortid');
var fs = require('fs');
var path = require('path');
var resource_dir = path.resolve(__dirname + '/../resource/');
exports.addClass = function(req, res) {
if (req.body.className.split(' ').join('').length === 0) return res.redirect('/dashboard');
models.User.findOne({
where: {
username: req.session.user.username
}
}).then(function(user) {
if (user.type === 'student') return res.status(403).sendFile(path.resolve(__dirname + '/../public/html/403.html'));
else {
models.Class.create({
className: req.body.className,
classCode: shortid.generate()
}).then(function(Class) {
user.addClass(Class).then(function(data) {
addClassFolder(Class.dataValues.classCode, function(err) {
return res.redirect('/class/' + Class.classCode);
});
});
});
}
});
}
var addClassFolder = function(classCode, cb) {
fs.mkdir(resource_dir + '/' + String(classCode) + '/', function(err) {
return cb(err);
});
}
exports.joinClass = function(req, res) {
if (req.session.user.type === 'teacher') return res.status(403).sendFile(path.resolve(__dirname + '/../public/html/403.html'));
models.Class.findOne({
where: {
classCode: req.body.classCode
}
}).then(function(Class) {
if (Class === null) return res.redirect('/dashboard');
models.User.findOne({
where: {
username: req.session.user.username
}
}).then(function(user) {
user.addClass(Class).then(function(data) {
return res.redirect('/class/' + Class.classCode);
});
});
});
};
exports.updateClass = function(req, res) {
var classCode = req.params.classCode;
models.Class.findOne({
where: {
classCode: classCode
}
}).then(function(Class) {
});
}
exports.classPage = function(req, res) {
models.Class.findOne({
where: {
classCode: req.params.classCode
}
}).then(function(Class) {
Class.getPosts().then(function(posts) {
(function recursePosts(i) {
if (i === posts.length) {
return res.render(__dirname + '/../views/class', {
user: req.session.user,
Class: Class,
posts: posts
});
}
models.User.findOne({
where: {
id: posts[i].dataValues.UserId
}
}).then(function(user) {
posts[i].dataValues.User = user;
models.Post.findOne({
where: {
id: posts[i].dataValues.id
}
}).then(function(post) {
post.getComments().then(function(comments) {
posts[i].dataValues.Comments = comments;
(function recurseComments(j) {
if (j === posts[i].dataValues.Comments.length) {
return recursePosts(i+1);
}
models.User.findOne({
where: {
id: posts[i].dataValues.Comments[j].dataValues.UserId
}
}).then(function(commentor) {
posts[i].dataValues.Comments[j].dataValues.User = commentor;
recurseComments(j+1);
})
})(0);
});
});
});
})(0);
});
});
}
|
import React from 'react';
const getName = name =>
name
.split('-')
.map(n => n.substr(0, 1).toUpperCase() + n.substr(1))
.join('');
export default ({ baseUrl, components }) => {
const Items = components.map(item => {
const name = getName(item);
return <li key={name} className="sg-nav__component-item">
<a href={`${baseUrl}/${item}.html`}>{name}</a>
</li>
});
return <ul className="sg-nav__component-list">
{Items}
</ul>
}
|
import React from 'react'
import '../styles/main.scss'
export default class TeamName extends React.Component {
render () {
return (
<h1 className="title">{this.props.name}</h1>
)
}
}
|
import React, {useEffect, useRef, useContext} from 'react';
import classes from './Cockpit.css';
import AuthContext from '../../context/auth-context';
//props.showPersons is this.state.showPersons
//props.persons is this.state.persons
const cockpit = (props) => {
const toggleButtonRef = useRef(null);
const authContext = useContext(AuthContext);
console.log(authContext.authenticated);
//useEffect runs after every render cycle!!
//useEffect is a React Hook that takes a default function that
//will run for every render cycle ofthe Cockpit.js
//hence, useEffect basically functions as componentDidMount
//and componentDidUpdate together
//we only want to run useEffect here when our persons changed
//for that we add a second argument [props.persons].
useEffect(() => {
console.log('[Cockpit.js] useEffect');
//HTTP request...
setTimeout(() => {
console.log('Saved data to cloud!');
}, 1000);
}, [props.persons]);
//you can use useEffect more if you want different effects on different
//data change
//useEffect executes only when the component renders the first time
//to do that pass an empty array.
//This tell React, this useEffect method has no dependencies and it
//should re-run whenever one of the dependencies changes.
//Now, since we have no dependencies, then, they can never change.
//and therefore useEffect can never re-run. It will therefore only run for
//the first time. That is the default. But it will never run again.
useEffect(() => {
console.log('[Cockpit.js], useEffect');
setTimeout(() => {
console.log('Saved data to cloud and run only the first time!');
}, 1000);
}, []);
//useEffect for clean-up like componentWillUnmount()}{}
//we return an anonymous function which will run BEFORE the main
//useEffect function runs, but AFTER the first render cycle!
useEffect(() => {
setTimeout(() => {
console.log('[Cockpit.js], for clean-up');
}, 1000);
return () => {
console.log("[Cockpit.js], clean-up work using useEffect()");
}
}, []);
//the below useEffect is useful if you want to cancel whenever the component
//is re-rendered or updated
useEffect(() => {
console.log('[Cockpit.js] 2nd useEffect');
return () => {
console.log("[Cockpit.js], clean-up work using 2nd useEffect()");
};
});
useEffect(() => {
toggleButtonRef.current.click();
return () => {
console.log('[Cockpit.js] toggleButtonRef');
}
}, []);
const assignedClasses = [];
let btnClass = "";
if(props.showPersons) {
btnClass = classes.Red;
}
if(props.personsLength <= 2){
assignedClasses.push(classes.red);
}
if(props.personsLength <= 1){
assignedClasses.push(classes.bold);
}
return(
<div className={classes.Cockpit}>
<h1> Hi! I'm a React App for {props.title}</h1>
<p className={assignedClasses.join(' ')}>
This is really working!!!
</p>
<button
className={btnClass}
onClick={props.clicked}
ref={toggleButtonRef}>
Toggle Persons
</button>
<button onClick={authContext.login}>
Log in
</button>
</div>
);
}
export default React.memo(cockpit);
|
require('@code-fellows/supergoose');
require('../jest.config');
const NotesCRUD = require('../libs/model/note-collection');
beforeEach(NotesCRUD.clear);
describe('Note collection', () => {
it('can create a new note', async () => {
const note = { category: 'test', payload: 'test message' };
const createdNote = await NotesCRUD.create(note);
expect(createdNote._id).toBeDefined();
expect(createdNote.category).toBe('test');
expect(createdNote.text).toBe('test message');
});
it('can get all notes', async () => {
const note = { category: 'test', payload: 'test message' };
const note1 = { category: 'test1', payload: 'test message' };
const testNote = { category: 'test', text: 'test message' };
const testNote1 = { category: 'test1', text: 'test message' };
await NotesCRUD.create(note);
await NotesCRUD.create(note1);
const notes = await NotesCRUD.get();
expect(notes.length).toBe(2);
compareProps(testNote, notes[0]);
compareProps(testNote1, notes[1]);
});
it('can get one note', async () => {
const note = { category: 'test', payload: 'test message' };
const note1 = { category: 'test1', payload: 'test message' };
const testNote = { category: 'test', text: 'test message' };
await NotesCRUD.create(note);
await NotesCRUD.create(note1);
const notes = await NotesCRUD.get('test');
expect(notes.length).toBe(1);
compareProps(testNote, notes[0]);
});
it('can delete a new note', async () => {
const note = { category: 'test', payload: 'test message' };
const createdNote = await NotesCRUD.create(note);
await NotesCRUD.delete(createdNote._id);
const notes = await NotesCRUD.get();
expect(notes.length).toBe(0);
});
function compareProps(a, b) {
for (const key in a) {
expect(a[key]).toBe(b[key]);
}
}
});
|
const nodemailer = require('nodemailer');
const transporter = nodemailer.createTransport({
host: "smtp.gmail.com",
port: 465,
secure: true,
auth: {
user: "ezequielromerobertani@gmail.com",
pass: "ktgchrwctkwxcgor"
}
});
// verify connection configuration
transporter.verify().then(()=>{
console.log("ready for send emails")
})
module.exports = transporter
|
(function(_) {
// 2 param es el arreglo de las dependencias
angular.module('kingGrafic.controllers', []) //sin ; al final para tener chainmethods
.controller('ProductsController', ['$scope', 'kinggraficService', function ($scope, kinggraficService){
kinggraficService.all().then(function (data){
$scope.products = data;
$scope.groupped = partition(data, 4);
});
function partition(data, n) {
return _.chain(data).groupBy(function (element, index) {
return Math.floor(index / n);
}).toArray().value();
}
}])
.controller('ProductController', ['$scope', '$routeParams', 'kinggraficService', function ($scope, $routeParams, kinggraficService) {
var name = $routeParams.name;
kinggraficService.byName(name)
.then(function (data){
$scope.product = data;
})
}])
.controller('TabsController', ['$scope', function ($scope) {
$scope.tab = 1;
$scope.selectTab = function (tab) {
$scope.tab = tab;
};
$scope.isActive = function (tab) {
return tab === $scope.tab;
}
}]);
})(_);
|
import Pair from "crocks/Pair";
import State from "crocks/State";
import type from "crocks/core/type";
import isFunction from "crocks/predicates/isFunction";
import { matcherHint } from "jest-matcher-utils";
import { isObjValueSameType, slice, popLastSlide } from "./helpers";
const sampleArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
expect.extend({
toReturnType(received, typeToMatch) {
if (!isFunction(received))
throw new Error(
`expect(Function).toReturnType(Type)\n\nReceived value must be a function but ${type(
received
)} was given.`
);
const result = received();
const message =
matcherHint(".toReturnType") +
"\n\n" +
`Expected returned type to be: \n"${type(typeToMatch)}"\n` +
`Received type: \n"${type(result)}"`;
return {
message,
pass: type(result) === type(typeToMatch)
};
}
});
describe("isObjValueSameType()", () => {
const sampleObj = {
val1: 1,
val2: "Hello",
val3: () => "Wazup",
val4: Pair(1, 2),
val5: true
};
const curried = isObjValueSameType(sampleObj);
test("Must return false when the value is not of the same type", () => {
expect(curried("val1", "World")).toBe(false);
expect(curried("val2", () => "nothing")).toBe(false);
expect(curried("val3", 2)).toBe(false);
expect(curried("val4", {})).toBe(false);
expect(curried("val4", 300)).toBe(false);
});
test("Must return true when the values are the same type", () => {
expect(curried("val1", 2)).toBe(true);
expect(curried("val2", "World")).toBe(true);
expect(
curried("val3", function() {
return null;
})
).toBe(true);
expect(curried("val4", Pair("Hello", 2))).toBe(true);
expect(curried("val5", false)).toBe(true);
});
test("Must return false when the key doesn't exist in the object", () => {
expect(curried("noKey", 10)).toBe(false);
expect(curried("noKey", undefined)).toBe(false);
expect(curried("noKey", null)).toBe(false);
});
});
describe("slice()", () => {
test("It should be a curried function", () => {
expect(slice()).toBeInstanceOf(Function);
expect(slice(0)).toBeInstanceOf(Function);
expect(slice(0, 2)).toBeInstanceOf(Function);
expect(slice(0, 2, sampleArray)).toHaveLength(2);
});
test("It should throw a TypeError when starting index is not a number", () => {
const sliceTest = x => () => slice(x, 2, []);
const errorMsg = "slice(): The first argument must be a Number";
expect(sliceTest({})).toThrowError(errorMsg);
expect(sliceTest(null)).toThrowError(errorMsg);
expect(sliceTest(undefined)).toThrowError(errorMsg);
expect(sliceTest([1, 2, 3])).toThrowError(errorMsg);
expect(sliceTest(() => null)).toThrowError(errorMsg);
expect(sliceTest(1)).not.toThrow();
});
test("It should throw a TypeError when ending index is not a number", () => {
const sliceTest = x => () => slice(0, x, []);
const errorMsg = "slice(): The second argument must be a Number";
expect(sliceTest({})).toThrowError(errorMsg);
expect(sliceTest(null)).toThrowError(errorMsg);
expect(sliceTest(undefined)).toThrowError(errorMsg);
expect(sliceTest([1, 2, 3])).toThrowError(errorMsg);
expect(sliceTest(() => null)).toThrowError(errorMsg);
expect(sliceTest(1)).not.toThrow();
});
test("It should throw a TypeError when provided list is not an array", () => {
const sliceTest = x => () => slice(0, 2, x);
const errorMsg = "slice(): The third argument must be an Array";
expect(sliceTest({})).toThrowError(errorMsg);
expect(sliceTest(null)).toThrowError(errorMsg);
expect(sliceTest(undefined)).toThrowError(errorMsg);
expect(sliceTest(123)).toThrowError(errorMsg);
expect(sliceTest(() => null)).toThrowError(errorMsg);
expect(sliceTest([])).not.toThrow();
});
test("It should take the first 2 items in the array", () => {
expect(slice(0, 2, sampleArray)).toHaveLength(2);
});
});
describe("popLastSlide()", () => {
test("It should return a State ADT", () => {
expect(popLastSlide).toReturnType(State);
});
test("It should place the last item from the slides array into the resultant and remove it from the state portion", () => {
const sampleState = { slides: [{}, {}, {}, { name: "LastSlide" }] };
const result = popLastSlide().runWith(sampleState);
expect(result.fst()).toHaveProperty("name", "LastSlide");
expect(result.snd().slides).toHaveLength(3);
});
test("It should have an empty object in the resultant when there is no slides in the state", () => {
const result = popLastSlide().runWith({});
expect(result.fst()).toEqual({});
});
test("It should not set a slides property in the state when there is no slides to begin with", () => {
const result = popLastSlide().runWith({});
expect(result.snd()).not.toHaveProperty("slides");
});
});
|
Write a function that returns the total surface area and volume of a box as an array: [area, volume]
function getSize(width, height, depth)
//surface area (SA)=2lw+2lh+2hw
//volume = w * L * h
const getSize = (width, height, depth) => {
let sArea, volume;
let ansArr = [];
sArea = 2*width*depth + 2*depth*height + 2*height*width;
volume = width*depth*height
ansArr.push(sArea);
ansArr.push(volume);
return ansArr
}
//codewars answer that I would like to refactor and look into. Has to do with breaking down functions into their smallest part and calling upon them.
|
///TODO:REVIEW
/**
* @param {number} N
* @return {number}
*/
var countArrangement = function(N) {
var visited = [];
for(var i = 0; i<=N; i++) {
visited[i] = false;
}
var count = {val: 0}
calculate(N, 1, visited, count);
return count.val;
};
function calculate(N, pos, visited, count) {
if(pos>N) {
count.val++;
}
for(var i = 1; i<=N; i++) {
if(!visited[i] && (pos %i ===0 || i % pos ===0)) {
visited[i] = true;
calculate(N, pos+1, visited, count);
visited[i] = false;
}
}
}
console.log(countArrangement(2));
|
'use strict';
const configFetchHandler = require('handler/config/userhandler');
//const all = [].concat(configFetchHandler);
const all = [].concat(require('handler/config/userhandler'),require('handler/config/authhandler'));
module.exports = all;
|
$(document).on('ready', function() {
var userId = null;
getUserInfo();
var timer = setInterval(getUserInfo, 2000);
// 签名
$('.canvas').jqSignature();
// 保存签名
$('.submit').on('click', function () {
console.log('提交')
var dataUrl = $('.canvas').jqSignature('getDataURL');
var data = new FormData();
data.append('userId', userId);
data.append('file', dataUrl);
$.ajax({
url: 'https://wx.sagacn.com/siemens/completeSignature',
type: 'post',
processData: false, // 告诉jQuery不要去处理发送的数据
contentType: false, // 告诉jQuery不要去设置Content-Type请求头
data: data,
dataType: 'json',
success: function (res) {
$('.canvas').jqSignature('clearCanvas');
$('.signature').hide().prev().show();
window.location.reload();
},
error: function () {
$('.canvas').jqSignature('clearCanvas');
$('.signature').hide().prev().show();
}
})
})
// 清除画布
$('.clear').click(function () {
$('.canvas').jqSignature('clearCanvas');
})
// 获取用户信息
function getUserInfo() {
// clearInterval(timer);
$.ajax({
url: 'https://wx.sagacn.com/siemens/prepareToSign',
type: 'get',
dataType: 'json',
success: function (res) {
if(res.meta.code !== 0){
return;
}
let data = res.data;
if(data && !data.signatureLink){
$('.agent').html('欢迎'+ data.agentName);
userId = res.data.id;
$('.signature').show().prev().hide();
return;
}
$('.signature').hide().prev().show();
// timer = setInterval(getUserInfo, 2000);
}
})
}
});
|
const Engine = Matter.Engine;
const World = Matter.World;
const Bodies = Matter.Bodies;
const Body = Matter.Body;
const Render = Matter.Render;
var ground1, ground2;
var stick1, stick2, stick3, stick4, stick5, stick6;
var ball1, ball2;
function preload(){
}
function setup(){
createCanvas(1270, 750);
engine = Engine.create();
world = engine.world;
ground1 = new Ground(700, 365, 1500, 20);
ground2 = new Ground(700, 740, 1500, 20);
ground3 = new Ground(1265, 230, 15, 1500);
ground4 = new Ground(515, 4, 1505, 15);
ground5 = new Ground(5, 230, 15, 1500);
dustbin1 = new Dustbin(1000, 255, 150, 200);
// dustbin2 = new Dustbin(1000, 630, 150, 200);
ball1 = new Paperball(400, 290, 90);
// ball2 = new Paperball(400, 670, 90);
var render = Render.create({
element: document.body,
engine: engine,
options: {
width: 1600,
height: 700,
wireframes: false
}
});
Render.run(render);
}
function draw(){
background("lightblue");
Engine.update(engine);
fill("maroon");
textSize(20);
text("Use all the 4 arrow keys to move the balls", 470, 50);
//to display the grounds
ground1.display();
ground2.display();
ground3.display();
ground4.display();
ground5.display();
//to display the dustbins
dustbin1.display();
// dustbin2.display();
//to display the paperballs
ball1.display();
// ball2.display();
}
function keyPressed(){
//up arrow
if(keyCode===38){
Matter.Body.applyForce(ball1.body, ball1.body.position, {x:150, y:-105})
//Matter.Body.applyForce(ball2.body, ball2.body.position, {x:150, y:-75})
}
//left arrow
//if(keyCode===37){
// Matter.Body.applyForce(ball1.body, ball1.body.position, {x:-105, y:-65})
//Matter.Body.applyForce(ball2.body, ball2.body.position, {x:-75, y:-65})
// }
//right arrow
// if(keyCode===39){
// Matter.Body.applyForce(ball1.body, ball1.body.position, {x:105, y:-65})
// Matter.Body.applyForce(ball2.body, ball2.body.position, {x:75, y:-65})
// }
//down arrow
//if(keyCode===40){
//Matter.Body.applyForce(ball1.body, ball1.body.position, {x:105, y:105})
// Matter.Body.applyForce(ball2.body, ball2.body.position, {x:75, y:105})
//}
}
|
class MyElement extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
const changeNameButton = document.createElement('button');
changeNameButton.textContent = 'changeName()';
changeNameButton.addEventListener('click', () => {
this.changeName();
});
this.shadowRoot.appendChild(changeNameButton);
}
changeName() {
this.name = Math.random()
.toString(36)
.slice(-6);
}
get name() {
return this.getAttribute('name');
}
set name(value) {
this.setAttribute('name', value);
}
connectedCallback() {
const element = document.createElement('p');
element.textContent = `connectedCallback`;
this.shadowRoot.appendChild(element);
}
adoptedCallback() {
const element = document.createElement('p');
element.textContent = `adoptedCallback`;
this.shadowRoot.appendChild(element);
}
attributeChangedCallback(name, oldValue, newValue) {
const element = document.createElement('p');
element.textContent = `attributeChanged: name ${name}; oldValue ${oldValue}; newValue ${newValue}`;
this.shadowRoot.appendChild(element);
}
static get observedAttributes() {
return ['name'];
}
}
if (!customElements.get('my-element')) {
customElements.define('my-element', MyElement);
}
|
module.exports = {
port : process.env.PORT || 8080,
web : '/public'
}
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.App = App;
exports.Page = Page;
function App(opts) {
var err = {
err: 'xxx',
message: '错误消息'
};
opts.onError(err);
opts.onLaunch(); // opts.data;
opts.onShow();
}
function Page(opts) {
opts.onLoad({}); // opts.data;
opts.onShow();
}
|
import React, { useEffect } from "react";
import {
Row,
Col,
Card,
CardBody,
CardHeader,
CardTitle,
CardText,
Container,
Jumbotron
} from "reactstrap";
import { connect } from "react-redux";
import { Redirect } from "react-router-dom";
import { fetch_history } from "../../store/actions/cartAction";
import Loader from "../loading/spinner";
/*global localStorage */
const DashBoard = props => {
useEffect(() => {
props.fetchHistory(localStorage.token);
}, []);
let content;
if (!props.auth) {
content = <Redirect to="/login" />;
} else {
content = (
<Container className="page" style={{ marginTop: "2rem" }}>
{props.loadingStatus ? (
<Loader />
) : (
<Row>
<Col>
<div>
<Jumbotron>
<h1>Welcome {props.user} </h1>
</Jumbotron>
</div>
<div style={{ marginTop: "2rem" }}>
{props.orderedItems.map(item => {
return (
<Card style={{ marginTop: "1rem" }} key={item._d}>
<CardHeader>
Ordered on{" "}
<span style={{ color: "red" }}>{item.date}</span>
<span style={{ color: "green", marginLeft: "1rem" }}>
$ {item.total_amount}
</span>
</CardHeader>
<CardBody>
{item.orders.map(order => {
return (
<CardTitle key>
{order.title} x{order.quantity}
</CardTitle>
);
})}
</CardBody>
</Card>
);
})}
</div>
</Col>
</Row>
)}
</Container>
);
}
return content;
};
const mapStateToProps = state => {
return {
user: state.auth.userInfo.name,
orderedItems: state.cart.orderHistory,
loadingStatus: state.cart.loading,
auth: state.auth.isAuth
};
};
const mapDispatchToProps = dispatch => {
return {
fetchHistory: token => dispatch(fetch_history(token))
};
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(DashBoard);
|
import React, { Component } from 'react';
import {getParse, parseString} from './parser'
import Formula from './Formula'
import ReactJson from 'react-json-view'
import Tree from './Tree'
import Message from './Message'
import {getRandomArray} from './helpers'
// import eqs from './data/all_equations.json'
const FinishedEl = ({formulas}) => {
console.log("initializing")
if (formulas.length > 0) {
return formulas.map( (el, i)=> (
<div>
<div className={"katex"} style={{display: "block"}}><Formula key={i} id={i} el={el}/><Tree formula={el}/></div>
</div>
)
)
}
else {
return <div> none yet </div>
}
}
class Tester extends Component {
constructor(props) {
super(props)
this.state = { formulas: [], renderFormulas: false}
this.test = this.test.bind(this)
this.getJson = this.getJson.bind(this)
this.gotFormulas = this.gotFormulas.bind(this)
this.renderFormulas = this.renderFormulas.bind(this)
}
gotFormulas(formulas) {
this.setState({formulas: formulas})
}
gotResult(result, formulas) {
const error_ct = formulas? formulas.filter(el=> !el.children ).length : null
this.setState({testResults: result, error_ct: error_ct, renderFormulas: false})
}
renderFormulas() {
this.setState({renderFormulas: true})
}
componentDidMount() {
this.getJson()
}
async getJson() {
const json = await fetch(`https://raw.githubusercontent.com/samghelms/katex-parsing-eval/master/src/data/all_equations.json`)
.then(response => response.json())
.then(json => json)
this.setState({raw_formulas: json})
}
test(e) {
if (!this.state.raw_formulas)
return
const keys = Object.keys(this.state.raw_formulas)
const random_arr = getRandomArray(keys, e.target.id)
var i = 0;
const t0 = performance.now();
var formulas = []
var random_idx
while (i < e.target.id) {
random_idx = random_arr[i]
formulas.push(getParse(this.state.raw_formulas[random_idx]))
i++
}
const t1 = performance.now();
const result = (t1 - t0)
this.gotResult(result, formulas)
this.gotFormulas(formulas)
}
render() {
console.log(this.state)
const formulas = this.state.formulas? this.state.formulas.map(el=> el && el.children? el.children[1]: {"failText": el}) : null
return (
<div className="App">
<button id = {10} onClick={this.test}> 10 formulas </button>
<button id = {100} onClick={this.test}> 100 formulas </button>
<button id = {1000} onClick={this.test}> 1000 formulas </button>
<button id = {10000} onClick={this.test}> 10000 formulas </button>
{this.state.testResults? <Message renderFlag = {this.state.renderFormulas} renderedFlag={this.renderFormulas} style={{padding: 10}} testResults={this.state.testResults} error_ct={this.state.error_ct}/>: <div style={{padding: 10}}> Select a test above </div>}
{this.state.renderFormulas ? <FinishedEl formulas={formulas}/> : <div> waiting on you to select a test... </div> }
</div>
);
}
}
// <FinishedEl formulas={formulas}/>
export default Tester;
|
var nodemailer = require('nodemailer');
var credentials = require('../credentials');
module.exports = (function() {
let mailTransport = nodemailer.createTransport({
service: '163',
port: '465',
secureConnection: true,
auth: {
user: credentials.mail.user,
pass: credentials.mail.password
}
});
let from = '"JavaScript之禅" <zhoutf1995@163.com>';
let errorRecipient = 'do123dixia@163.com';
return {
send: function (mail) {
mail = mail || {};
let to = mail.to;
let subject = mail.subject;
let text = mail.text;
mailTransport.sendMail({
from: from,
to: to,
subject: subject,
text: text
}, function (err, info) {
if (err) return console.error('Unable to send mail: ' + err);
console.log('Message sent: %s', info.messageId);
})
},
sendError: function (mail) {
let message = mail.message;
let exception = mail.exception;
let filename = mail.filename;
let body = '<h1>Meadowlark Travel Site Error</h1>' +
'message:<br><pre>' + message + '</pre><br>';
if(exception) body += 'exception:<br><pre>' + exception + '</pre><br>';
if(filename) body += 'filename:<br><pre>' + filename + '</pre><br>';
mailTransport.sendMail({
from: from,
to: errorRecipient,
subject: 'Meadowlark Travel Site Error',
html: body,
generateTextFromHtml: true
}, function(err){
if(err) console.error('Unable to send email: ' + err);
});
}
}
})();
|
/**
* @author Hank
*
*
*/
const express = require('express');
const app = express();
const Stream = require('stream');
app.use(express.static('./dist'));
app.use(async (req, res) => {
// 或者从 CDN 上下载到 server 端
// const serverPath = await downloadServerBundle('http://cdn.com/bar/umi.server.js');
const render = require('./dist/umi.server');
res.setHeader('Content-Type', 'text/html');
const context = {};
const { html, error, rootContainer, ssrHtml } = await render({
// 有需要可带上 query
path: req.url,
context,
// 可自定义 html 模板
// htmlTemplate: defaultHtml,
// 启用流式渲染
mode: 'stream',
// html 片段静态标记(适用于静态站点生成)
// staticMarkup: false,
// 扩展 getInitialProps 在服务端渲染中的参数
// getInitialPropsCtx: {},
// manifest,正常情况下不需要
});
// support stream content
// res.send(html)
if (html instanceof Stream) {
html.pipe(res);
html.on('end', function() {
res.end();
});
} else {
res.send(html);
}
});
app.listen(3000, () => {
console.log('app is run port 3000');
});
|
var controllers = require('../controllers'),
api = require('../controllers/api');
module.exports = function(app) {
app.get('/', controllers.index);
app.get('/login', controllers.login);
// API
app.get('/api/home', api.home);
app.get('/api/reward', api.reward);
app.get('/api/behavior', api.behavior);
app.get('/api/student', api.student);
};
|
function isAlpha(word) {
return (
word
.toLowerCase()
.match(/\w/g)
.map((x) => x.charCodeAt(word) - 96)
.reduce((a, b) => a + b) %
2 ===
0
);
}
const result = isAlpha('True');
console.log(result);
// function isAlpha(word) {
// return word.match(/[a-z]/g).reduce((a, b) => a + b.charCodeAt() - 96, 0)%2 === 0;
// }
// const isAlpha = str => {
// const aCharCode = 'a'.charCodeAt(0);
// const letters = str.toLowerCase().replace(/[^a-z]/g, '');
// const sum = Array.from(letters).reduce(
// (total, char) => total + (char.charCodeAt(0) - aCharCode + 1),
// 0,
// );
// return sum % 2 === 0;
// };
// Test.assertEquals(isAlpha("i'am king"), true)
// Test.assertEquals(isAlpha("True"), true)
// Test.assertEquals(isAlpha("alexa"), false)
|
import React, {useCallback, useContext} from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import {deleteRequestFromList} from "../../api/api";
import style from './RequestItem.module.css';
import DeleteIcon from "../DeleteIcon/DeleteIcon";
import {ContextApp} from "../../reducers/reducer";
import {resetResponse, setRequestList, setRequestToForm, setResponseError} from "../../reducers/actions";
const RequestItem = props => {
const {state: {list,}, dispatch} = useContext(ContextApp);
const setList = useCallback((list) => dispatch(setRequestList(list)), [dispatch]);
const setRequest = useCallback((data) => dispatch(setRequestToForm(data)), [dispatch]);
const resetResp = useCallback(() => dispatch(resetResponse()), [dispatch]);
const handleClickDelete = async() => {
const res = await deleteRequestFromList({deleteIndex: props.index});
setList(res);
};
const handleClickItem = () =>{
resetResp();
setRequest(props);
};
return (
<div className={style.wrapper} onClick={handleClickItem}>
<div
className={classNames(style.method,
props.method.toLowerCase() === 'post' ? style.post : style.get)}
>
{props.method}
</div>
<div className={style.url}>{props.url}</div>
<div className={style.iconWrapper}>
<DeleteIcon onClick = {handleClickDelete} className = {style.icon}/>
</div>
</div>
);
};
RequestItem.propTypes = {
};
export default RequestItem;
|
import { LightningElement } from 'lwc';
export default class ComponentLifecycleParent extends LightningElement {
constructor() {
super();
// eslint-disable-next-line no-console
console.log('Parent - Constructor');
}
connectedCallback() {
// eslint-disable-next-line no-console
console.log('Parent - Connected Callback');
}
renderedCallback() {
// eslint-disable-next-line no-console
console.log('Parent - Rendered Callback');
}
disconnectedCallback() {
// eslint-disable-next-line no-console
console.log('Parent - Disconnected Callback');
}
}
|
import React, { Component } from 'react';
import './UnanswerTableView.css';
import { Dropdown, Icon, Label, Table, Checkbox } from 'semantic-ui-react'
// import SortableTree, { changeNodeAtPath, addNodeUnderParent, removeNodeAtPath } from 'react-sortable-tree';
// import { searchedListData, NERTagging } from '../../MLAdmin'
import { Link } from 'react-router-dom';
import moment from 'moment';
export default class UnanswerTableView extends Component{
state = {
unanswerList: [],
unanswerListPage: '',
unanswerListCount: '',
searchedStr: '',
searchedListData: [],
searchedListPage: '',
searchedListCount: '',
selectAll: false,
selectedID: [],
selectedData: [],
searched: false
};
componentWillReceiveProps = (nextProps) => {
if(nextProps.unanswerList !== this.state.unanswerList){
this.setState({
unanswerList: nextProps.unanswerList
})
}
if(nextProps.unanswerListPage !== this.state.unanswerListPage){
this.setState({
unanswerListPage: nextProps.unanswerListPage
})
}
if(nextProps.unanswerListCount !== this.state.unanswerListCount){
this.setState({
unanswerListCount: nextProps.unanswerListCount
})
}
if(nextProps.searchedListData !== this.state.searchedListData){
this.setState({
searchedListData: nextProps.searchedListData
})
}
if(nextProps.searchedListPage !== this.state.searchedListPage){
this.setState({
searchedListPage: nextProps.searchedListPage
})
}
if(nextProps.searchedListCount !== this.state.searchedListCount){
this.setState({
searchedListCount: nextProps.searchedListCount
})
}
if(nextProps.searched !== this.state.searched){
this.setState({
searched: nextProps.searched
})
}
}
render() {
const { unanswerList, unanswerListPage, unanswerListCount, searched, searchedListCount, searchedListData, searchedListPage } = this.state;
var array = [];
var first=0;
var last=0;
var i;
if(searched){
first =( Math.floor(searchedListPage/10))*10 + 0;
if((searchedListCount/10 - searchedListPage) < 9){
last = Math.ceil(searchedListCount/10)-1
}else{
last = (Math.floor(searchedListPage/10))*10 + 9;
}
for(i = first; i<(last+1); i++){
array.push(i);
}
}else{
first =( Math.floor(unanswerListPage/10))*10 + 0;
if((unanswerListCount/10 - unanswerListPage) < 9){
last = Math.ceil(unanswerListCount/10)-1
}else{
last = (Math.floor(unanswerListPage/10))*10 + 9;
}
for(i = first; i<(last+1); i++){
array.push(i);
}
}
return (
<div className='UnanswerTableView'>
<div className='outsideTable'>
<div className='ui search searchBox'>
<div className='ui icon input'>
<i className='search link icon' />
<Icon
inverted
size='mini'
className='removeSearchBtn link'
circular
name='delete'
onClick={() => {
this.props.searchUnanswerDataList('');
}}
/>
<input
className='prompt'
type='text'
placeholder='Search...'
onKeyPress={(e)=>{
if(e.key === 'Enter'){
this.props.searchUnanswerDataList(e.target.value)
}
}}
onChange={(e)=>{
this.props.searchUnanswerDataList(e.target.value)
}}
value={this.state.searchWord}
/>
</div>
</div>
</div>
<Table size='small' basic='very' className='faqTable'>
<Table.Header>
<Table.Row>
<Table.HeaderCell textAlign={'center'} width={1}>
<Checkbox checked={this.state.selectAll} onChange={(e, {checked}) => this.handleSelectAll(checked)}/>
</Table.HeaderCell>
<Table.HeaderCell textAlign={'center'} width={2}>날짜</Table.HeaderCell>
<Table.HeaderCell textAlign={'center'} width={9}>질문</Table.HeaderCell>
<Table.HeaderCell textAlign={'center'} width={2}>플랫폼</Table.HeaderCell>
<Table.HeaderCell textAlign={'center'} width={1}>보기</Table.HeaderCell>
<Table.HeaderCell textAlign={'center'} width={1}>삭제</Table.HeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
{!searched && unanswerList.length > 0 && unanswerList.map(this.makeRow)}
{searched && searchedListData.length > 0 && searchedListData.map(this.makeRow)}
</Table.Body>
</Table>
{/* {this.modalRenderer()} */}
{/* <div className='tableBtn'>선택 다운로드</div> */}
<div className='tableBtn' onClick={this.multipleDeleteData}>삭제</div>
<div className='pagebox'>
{!searched && unanswerListPage > 9 && <div className='pagebtn' onClick={this.props.handlePage.bind(this, 'prev')}>{'<'}</div>}
{searched && searchedListPage > 9 && <div className='pagebtn' onClick={this.props.handlePage.bind(this, 'prev')}>{'<'}</div>}
{array.map((j, i) => {
if(searched){
return (
<div key={j} className={searchedListPage === j ? 'pagebtn active' : 'pagebtn'} onClick={this.props.handlePage.bind(this, j)}>{j+1}</div>
)
}else{
return (
<div key={j} className={unanswerListPage === j ? 'pagebtn active' : 'pagebtn'} onClick={this.props.handlePage.bind(this, j)}>{j+1}</div>
)
}
}) }
{array.length === 10 && <div className='pagebtn' onClick={this.props.handlePage.bind(this, 'next')}>{'>'}</div>}
</div>
</div>
);
}
// fileUpload = (e) => {
// e.stopPropagation();
// e.preventDefault();
// var file = e.target.files[0];
// this.setState({
// file: file
// })
// var form = new FormData();
// form.append('file', file);
// this.props.uploadData(form)
// }
makeRow = ({platform, client_id, answers, create_date, id, memo, question, topics}, idx) => {
return (
<Table.Row key={idx}>
<Table.Cell textAlign={'center'}>
<Checkbox checked={this.state[idx]} onChange={(e, {checked}) => this.handleCheckBox(e, id, idx, checked)}/>
</Table.Cell>
<Table.Cell textAlign={'center'}>{create_date !== null && create_date !== undefined && moment(create_date).format('YY/MM/DD HH:ss')}</Table.Cell>
<Table.Cell textAlign={'left'}>
<Link to={`/ResponseSetting/Unanswer/id=${id}`}>{question !== undefined && question}</Link>
</Table.Cell>
<Table.Cell textAlign={'center'}>{platform !== null && platform !== undefined && platform}</Table.Cell>
<Table.Cell textAlign={'center'}>
<Link to={`/ResponseSetting/Unanswer/id=${id}`}><span className='iconBtn changeBtn'><Icon name='edit' /></span></Link>
</Table.Cell>
<Table.Cell textAlign={'center'}><span className='iconBtn deleteBtn' onClick={this.deleteUnanswerData.bind(this, id)}><Icon name='delete'/></span></Table.Cell>
</Table.Row>
)
}
multipleDeleteData = () => {
this.props.multipleDeleteUnanswerData(this.state.selectedID)
}
deleteUnanswerData = (id) => {
this.props.deleteUnanswerData(id)
}
setSelect = (obj) => {
var stateObj = [];
for(var i = 0; i < 10; i++){
stateObj.push(obj)
}
this.setState(stateObj)
}
handleCheckBox = (e, id, i, checked) => {
var selectedID = this.state.selectedID;
var selectedData = this.state.selectedData;
if(checked === true) {
selectedID.push(id);
selectedData.push(this.state.unanswerList[i]);
}else{
for(var n = 0; n < selectedID.length; n++){
if(selectedID[n] === id){
selectedID.splice(n, 1);
}
if(selectedData[n] === this.state.unanswerList[i]){
selectedData.splice(n, 1);
}
}
this.setState({
selectAll: false
})
}
this.setState({
selectedID: selectedID,
selectedData: selectedData,
[i]: !this.state[i]
})
}
handleSelectAll = (checked) => {
var selectedID = [];
var selectedData = [];
var i;
this.setState({
selectAll: !this.state.selectAll
})
if(checked === true){
for(i = 0; i < this.state.unanswerList.length; i++){
selectedData.push(this.state.unanswerList[i]);
selectedID.push(this.state.unanswerList[i].id);
}
this.setSelect(true)
}else{
this.setSelect(false)
}
this.setState({
selectedID: selectedID,
selectedData: selectedData
})
}
setSelect = (obj) => {
var stateObj = [];
for(var i = 0; i < 10; i++){
stateObj.push(obj)
}
this.setState(stateObj)
}
resetSelect = () => {
this.setState({
selectedID: [],
selectedData: [],
selectAll: false,
})
this.setSelect(false)
}
}
|
var thumbs = document.getElementsByClassName("imageThumbs");
var images = [];
var modal = document.getElementById("modal");
var modalOverlay = document.getElementById("modalOverlay");
var j, i;
function cacheImages() {
for (j = 0; j < cacheImages.arguments.length; j++) {
images[j] = new Image;
images[j].src = cacheImages.arguments[j];
}
}
cacheImages(
"images/field.jpg",
"images/tree.jpg",
"images/stone.jpg"
)
window.onload = function () {
for (i = 0; i < thumbs.length; i++) {
thumbs[i].src = images[i].src;
thumbs[i].addEventListener("click", showHiRes, false);
}
}
function showHiRes() {
modal.style.visibility = "visible";
modalOverlay.style.visibility = "visible";
modalOverlay.addEventListener("click", closeAll, false);
modal.innerHTML = "<img class='imagesHiRes' src='" + this.src + "'><button class='close' id='close'>x</button>";
var closeButton = document.getElementById("close");
closeButton.addEventListener("click", closeAll, false);
}
function closeAll() {
modal.style.visibility = "hidden";
modalOverlay.style.visibility = "hidden";
}
|
import movieService from "../services/movie.js";
export default class MoviePage {
constructor() {
this.template();
}
template() {
document.getElementById('content').innerHTML += /*html*/ `
<section id="movies" class="page">
<header class="topbar">
<h2>Movies</h2>
<a class="right" href="#favorites">Favorites</a>
</header>
<section id="movie-container" class="grid-container"></section>
</section>
`;
}
addToFavourites(movieId) {
movieService.addToFavourites(movieId);
}
removeFromFavourites(movieId) {
movieService.removeFromFavourites(movieId);
}
}
|
import { AppColors, MaterialColors } from './Colors'
import * as Themes from './themes'
import {
FontWeights,
FontSizes,
BorderWidths,
BorderRadius,
} from './Typography'
export {
AppColors,
MaterialColors,
FontWeights,
FontSizes,
BorderWidths,
BorderRadius,
Themes,
}
|
const argon2 = require('argon2')
const faker = require('faker')
const { range } = require('lodash')
const { USERS_MAX } = require('../length')
faker.locale = 'pt_BR'
const firstEmail = 'user@test.com'
const basePassword = '12345678'
const modelUser = async email => {
const firstName = faker.name.firstName()
const lastName = faker.name.lastName()
return {
id: faker.datatype.uuid(),
first_name: firstName,
last_name: lastName,
email: email || faker.internet.email(firstName, lastName),
password: await argon2.hash(basePassword),
created_at: faker.date.recent(30),
updated_at: faker.date.recent(30),
deleted_at: faker.datatype.boolean() ? faker.date.recent(30) : null
}
}
const makeUsers = async () => {
const firstUser = await modelUser(firstEmail)
const users = await Promise.all(range(USERS_MAX)
.map(() => modelUser()))
return [firstUser, ...users]
}
exports.seed = async knex => {
await knex('users').del()
const users = await makeUsers(knex)
await knex('users').insert(users)
}
|
import ListCommerces from './ListRestaurants';
import CommerceSettings from './CreateCommerce';
export { ListCommerces, CommerceSettings };
|
define(['apps/system2/docquery/docquery', 'apps/system2/docquery/docquery.service'], function (app) {
app.module.controller("docquery.controller.search", function ($scope,$rootScope, $uibModal, $filter, docqueryService, stdApiUrl, stdApiVersion) {
$scope.downloadUrl = stdApiUrl + stdApiVersion;
$scope.fonds = docqueryService.getArchiveList().$object;
$scope.search = function () {
$scope.listResult = true;
var archives = $scope.fonds[0].Archives.where(function (a) { return a.choose; });
var fields = [];
var fieldsMap = {};
angular.forEach(archives, function (a) {
if (a.HasVolume) {
var vFields = a.VolumeFields.where(function (f) { return f.ForSearch; });
var fs = vFields.map(function (f) { var fid = "_f" + f.ID + "_v"; fieldsMap[fid] = f.Name; return fid; })
fields = fields.concat(fs);
} else {
var bField = a.BoxFields.where(function (f) { return f.ForSearch; }).map(function (f) { return "_f" + f.ID + "_b" });
var fs = bField.map(function (f) { var fid = "_f" + f.ID + "_b"; fieldsMap[fid] = f.Name; return fid; })
fields = fields.concat(fs);
}
if (a.HasProject) {
var pField = a.ProjectFields.where(function (f) { return f.ForSearch; });
var fs = pField.map(function (f) { var fid = "_f" + f.ID + "_p"; fieldsMap[fid] = f.Name; return fid; });
fields = fields.concat(fs);
}
});
$scope.fields = fields;
$scope.fieldsMap = fieldsMap;
docqueryService.searchArchive($scope.searchKey, fields.join(',')).then(function (result) {
$scope.searchResult = result;
});
}
$scope.getMainInfo = function (datas) {
for (var i = 0; i < $scope.fields.length; i++) {
var f = $scope.fields[i];
if (datas[f] && datas[f].indexOf('<font') >= 0) {
return datas[f];
}
}
return datas[0];
}
$scope.getMainInfoField = function (datas) {
for (var i = 0; i < $scope.fields.length; i++) {
var f = $scope.fields[i];
if (datas[f] && datas[f].indexOf('<font') >= 0) {
return $scope.fieldsMap[f];
}
}
}
$scope.setCurrentItem = function (item) {
$scope.currentItem = item;
}
$scope.$watch("currentItem", function (newval,oldval) {
if (newval) {
loadArchiveInfo(newval.Datas.ArchiveType, newval.Datas.FondsNumber, newval.ID);
}
})
$scope.getMainArchiveName = function (item) {
var archives = $scope.fonds[0].Archives.where(a => a.Key == item.Datas.ArchiveType);
var files = archives[0].VolumeFields.where(f => f.Main);
if (files.length > 0) {
return files.map(f => item.Datas["_f" + f.ID + "_v"]).join('-');
} else {
return item.Datas._f1_v;
}
}
var loadArchiveInfo = function (type, fonds,id ) {
var archives = $scope.fonds[0].Archives.where(a => a.Key == type);
$scope.archiveFields = archives[0].VolumeFields;
$scope.boxFields = archives[0].BoxFields;
$scope.archiveFileFileds = archives[0].FileFields;
$scope.projectFields = archives[0].ProjectFields;
docqueryService.getArchiveVolumeData({
ids: id,
fonds: fonds,
archive: type
}).then(function (result) {
if (result.Source && result.Source.length > 0) {
$scope.volumeInfo = result.Source[0];
if ($scope.volumeInfo.ProjectID > 0) {
docqueryService.getProjInfo($scope.volumeInfo.ProjectID).then(function (projInfo) {
$scope.projInfo = projInfo;
});
}
}
});
docqueryService.getArchiveFileData({
volume: id,
fonds: fonds,
archive: type
}).then(function (result) {
$scope.archiveFiles = result.Source;
});
docqueryService.getArchiveLog(fonds, type, id).then(function (datas) {
$scope.currentArchiveLogs = datas;
});
}
$scope.getFiledValue = function (source, field) {
if (source) {
switch (field.DataType) {
case 3: return $filter('TDate')(source["_f" + field.ID]);
case 4: return $filter('enumMap')(source["_f" + field.ID], field.BaseData);
default: return source["_f" + field.ID];
}
}
}
$scope.getMainFileName = function (item) {
var files = $scope.archiveFileFileds.where(f => f.Main);
if (files.length > 0) {
return files.map(f => item["_f" + f.ID]).join('-');
} else {
return item._f1;
}
}
$scope.getMainArchiveName2 = function (archiveType, source) {
var archives = $scope.fonds[0].Archives.where(a => a.Key == archiveType);
var files = archives[0].VolumeFields.where(f => f.Main);
if (files.length > 0) {
return files.map(f => source["_f" + f.ID]).join('-');
} else {
return source._f1_v;
}
}
$scope.addToBorrowList = function () {
if ($rootScope.archiveBorrowList == undefined) {
$rootScope.archiveBorrowList = [];
}
var id = $scope.currentItem.Datas.ArchiveType + "_" + $scope.volumeInfo.ID;
if ($rootScope.archiveBorrowList.contains(a => a.id == id)) {
bootbox.alert("该档案已在我的借阅列表中!");
} else {
var mainName = $scope.getMainArchiveName2($scope.currentItem.Datas.ArchiveType, $scope.volumeInfo);
$rootScope.archiveBorrowList.push({
id: id,
archiveID : $scope.volumeInfo.ID,
fonds: $scope.volumeInfo.FondsNumber,
type : $scope.currentItem.Datas.ArchiveType,
typeName: $scope.currentItem.Datas.ArchiveTypeName,
name: mainName,
copies: $scope.volumeInfo.Copies
});
}
}
});
});
|
import React, { useEffect, useState } from 'react';
import Container from 'react-bootstrap/Container';
import Row from 'react-bootstrap/Row';
import Col from 'react-bootstrap/Col';
import InputGroup from 'react-bootstrap/InputGroup';
import FormControl from 'react-bootstrap/FormControl';
import Accordion from 'react-bootstrap/Accordion';
import Card from 'react-bootstrap/Card';
import Image from 'react-bootstrap/Image';
import Media from 'react-bootstrap/Media';
import { AiOutlineSearch } from 'react-icons/ai';
import './mainStyles.css';
import { useSelector } from 'react-redux';
import { AiOutlineStar, AiFillStar } from 'react-icons/ai';
import firebase from '../../../firebase';
const MessageHeader = ({handleSearchChange}) => {
const [isFavorited, setFavorited] = useState(false);
const chatRoom = useSelector(state => state.chatRoom.currentChatRoom);
const user = useSelector(state => state.user.currentUser);
const isPravateRoom = useSelector(state => state.chatRoom.isPravateRoom);
const userPosts = useSelector(state => state.chatRoom.userPosts);
const userRef = firebase.database().ref("users");
useEffect(() => {
if(chatRoom && user) {
addFavoriteListener(chatRoom.id, user.uid);
}
}, []);
const addFavoriteListener = (chatRoomId, userId) => {
userRef
.child(userId)
.child("favorited")
.once("value")
.then(data => {
if(data.val() !== null) {
const chatRoomIds = Object.keys(data.val());
const isAlreadyFavorited = chatRoomIds.includes(chatRoomId);
setFavorited(isAlreadyFavorited);
}
})
};
const handleFavorite = () => {
if(isFavorited) {
userRef.child(`${user.uid}/favorited`)
.child(chatRoom.id)
.remove(err => {
console.log(err);
});
setFavorited(isFavorited => !isFavorited);
} else {
userRef.child(`${user.uid}/favorited`).update({
[chatRoom.id] : {
name: chatRoom.name,
description: chatRoom.description,
createdBy: {
name: chatRoom.createdBy.name,
image: chatRoom.createdBy.image
}
}
});
setFavorited(isFavorited => !isFavorited);
}
}
const renderUserPosts = (userPosts) =>
Object.entries(userPosts)
.sort((a,b) => b[1].count - a[1].count)
.map(([key,val], i) => (
<li key={isFavorited}
style={{listStyle: 'none', padding: '0.5em 0'}}>
<Media>
<img
width={40}
height={40}
className="mr-3"
src={val.image}
alt={val.name}
/>
<Media.Body style={{ fontSize: '0.8rem'}}>
<h6>{key}</h6>
<span>
{val.count}개
</span>
</Media.Body>
</Media>
</li>
))
return (
<div className="messageHeader">
<Container
style={{
height: '10em',
padding: '1em 2em 0 2em'
}}>
<Row style={{marginBottom: '1em' }}>
<Col sm={8} style={{ fontSize: '2rem'}}>
{chatRoom && chatRoom.name}
{!isPravateRoom &&
<span onClick={handleFavorite} style={{cursor:'pointer', marginLeft: '1.1em'}}>
{!isFavorited ? <AiOutlineStar /> : <AiFillStar />}
</span>
}
</Col>
<Col sm={4} style={{ display: 'flex', alignItems: 'center', justifyContent:'center'}}>
<InputGroup.Prepend style={{
alignSelf: 'stretch',
margin: '0.3em 0'}}>
<InputGroup.Text id="basic-addon1">
<AiOutlineSearch />
</InputGroup.Text>
</InputGroup.Prepend>
<FormControl
onChange={handleSearchChange}
placeholder="search"
aria-label="search"
aria-describedby="basic-addon1"
/>
</Col>
</Row>
<Row>
<Col sm>
<Accordion>
<Card>
<Accordion.Toggle as={Card.Header} eventKey="0">
Description
</Accordion.Toggle>
<Accordion.Collapse eventKey="0">
<Card.Body>{chatRoom && chatRoom.description}</Card.Body>
</Accordion.Collapse>
</Card>
</Accordion>
</Col>
<Col sm>
<Accordion>
<Card>
<Accordion.Toggle as={Card.Header} eventKey="0">
User Message
</Accordion.Toggle>
<Accordion.Collapse eventKey="0">
<Card.Body>
<ul
style={{padding: '0'}}
>{userPosts && renderUserPosts(userPosts)}</ul>
</Card.Body>
</Accordion.Collapse>
</Card>
</Accordion>
</Col>
<Col sm style={{paddingTop: '0.5rem'}}>
<span>방장</span>
</Col>
</Row>
</Container>
</div>
);
};
export default MessageHeader;
|
import './App.css';
import NetworkComponent from "./Components/NetworkComponent";
function App() {
return (
<div className="App">
<NetworkComponent/>
</div>
);
}
export default App;
|
/**
* Created by Des on 15/11/29.
*/
blog.run( ['$rootScope', function($rootScope) {
}] );
|
/**
* 备注:
* slug 对应配置中心名称
*/
module.exports = {
1001: {
slug: 'hotsites',
name: '热门网站',
tpl: 'card/hotsite',
method: 'getSiteList'
},
1002: {
slug: 'site_navi',
name: '网址导航',
tpl: 'card/navigation',
method: 'getData'
},
1004: {
slug: 'video',
name: '热门视频',
tpl: 'card/video'
},
1005: {
slug: 'life',
name: '生活助手',
tpl: 'card/life'
},
1007: {
slug: 'game',
name: '热门游戏',
tpl: 'card/game'
},
1008: {
slug: 'news',
name: '新闻资讯',
tpl: 'card/news'
},
1009: {
slug: 'novel',
name: '小说书架',
tpl: 'card/novel'
},
1010: {
slug: 'hotword',
name: '实时热点',
tpl: 'card/top'
},
1011: {
slug: 'astrology',
name: '星座运势',
tpl: 'card/sign',
method: 'getAllData'
},
1012: {
slug: 'joke',
name: '趣闻',
tpl: 'card/fun'
},
1013: {
slug: 'grab',
name: '欧洲杯',
tpl: 'card/euroCup',
method: 'UEFAEuro2016'
},
1014: {
slug: 'software',
name: '软件应用',
tpl: 'card/soft'
},
1016: {
slug: 'opponews',
name: 'OPPO资讯',
tpl: 'card/oppo'
},
1017: {
name: '新春',
tpl: 'card/spring'
},
1018: {
name: '招聘',
tpl: 'card/joinUs'
},
1019: {
slug: 'tuniu',
name: '途牛暑假出行季',
tpl: 'card/tuniu'
},
3001: {
slug: 'topic',
name: '热点话题',
tpl: 'card/topic'
}
};
|
const CheckoutSystem = require('../src/checkout-system');
describe('example scenarios', () => {
const checkoutSystem = new CheckoutSystem();
it('calculates total for default customer', async () => {
const checkout = await checkoutSystem.createCheckout('default');
await checkout.add('classic');
await checkout.add('standout');
await checkout.add('premium');
const total = await checkout.total();
expect(total).to.equal(98797);
});
it('calculates total for UNILEVER customer', async () => {
const checkout = await checkoutSystem.createCheckout('UNILEVER');
await checkout.add('classic');
await checkout.add('classic');
await checkout.add('classic');
await checkout.add('premium');
const total = await checkout.total();
expect(total).to.equal(93497);
});
it('calculates total for APPLE customer', async () => {
const checkout = await checkoutSystem.createCheckout('APPLE');
await checkout.add('standout');
await checkout.add('standout');
await checkout.add('standout');
await checkout.add('premium');
const total = await checkout.total();
expect(total).to.equal(129496);
});
it('calculates total for NIKE customer', async () => {
const checkout = await checkoutSystem.createCheckout('NIKE');
await checkout.add('premium');
await checkout.add('premium');
await checkout.add('premium');
await checkout.add('premium');
const total = await checkout.total();
expect(total).to.equal(151996);
});
it('calculates total for FORD customer', async () => {
const checkout = await checkoutSystem.createCheckout('FORD');
await checkout.add('classic');
await checkout.add('classic');
await checkout.add('classic');
await checkout.add('classic');
await checkout.add('classic');
await checkout.add('standout');
await checkout.add('standout');
await checkout.add('premium');
await checkout.add('premium');
await checkout.add('premium');
const total = await checkout.total();
expect(total).to.equal(286991);
});
});
|
// import { get, isUndefined, once, remove } from 'lodash'
// import Promise from 'bluebird'
// import memoize from 'utils/memoize'
// import uasParser from 'ua-parser-js'
// import loggerFactory from 'utils/logger'
// import {
// actions as gamestateActions,
// selectors as gamestateSelectors,
// isActive,
// } from 'morpheus/gamestate'
// import {
// selectors as gameSelectors,
// actions as gameActions,
// } from 'morpheus/game'
// import { selectors as castSelectors } from 'morpheus/casts'
// import { actions as sceneActions } from 'morpheus/scene'
// import { sceneLoadQueue } from 'morpheus/scene/actions'
// import {
// special as inputHandlerFactory,
// eventInterface,
// } from 'morpheus/hotspot'
// import { getAssetUrl } from 'service/gamedb'
// import { loadAsImage } from 'service/image'
// import { createVideo } from 'utils/video'
// import { resizeToScreen, generateMovieTransform } from 'utils/resize'
// import linkPreload from 'utils/linkPreload'
// import renderEvents from 'utils/render'
// import { GESTURES } from 'morpheus/constants'
// import { and, or, not } from 'utils/matchers'
// import { forMorpheusType, isMovie, isAudio, isHotspot } from '../matchers'
// const logger = loggerFactory('cast:special')
// const selectSpecialCastDataFromSceneAndType = (scene, sceneType) => {
// if (sceneType === 3) {
// return get(scene, 'casts', []).find(c => c.__t === 'MovieSpecialCast')
// }
// return null
// }
// const userAgentString = (global.navigator && global.navigator.userAgent) || ''
// const uas = uasParser(userAgentString)
// const movExt = uas.browser.name.indexOf('Safari') !== -1 ? 'mp4' : 'webm'
// function startRenderLoop({ update }) {
// renderEvents.onRender(update)
// }
// export const delegate = memoize(scene => {
// function applies() {
// return selectSpecialCastDataFromSceneAndType(scene, get(scene, 'sceneType'))
// }
// function updateAssets({
// getState,
// autoplay,
// assets,
// loadingAssets,
// movieCasts,
// dispatch,
// }) {
// const loadedData = [
// ...assets.map(({ data }) => data),
// ...loadingAssets.map(({ data }) => data),
// ]
// function existsInAssets(cast) {
// return loadedData.find(data => data === cast)
// }
// return Promise.all(
// movieCasts
// .filter(
// cast =>
// !existsInAssets(cast) &&
// isActive({
// cast,
// gamestates: gamestateSelectors.forState(getState()),
// }),
// )
// .map(movieCast => {
// return new Promise((resolve, reject) => {
// console.log(`-----------------> Loading ${movieCast.fileName}`)
// loadingAssets.push({
// data: movieCast,
// })
// const video = createVideo(getAssetUrl(movieCast.fileName), {
// loop: movieCast.looping,
// autoplay,
// onerror: reject,
// })
// video.volume = gameSelectors.htmlVolume(getState())
// video.classList.add('MovieSpecialCast')
// function onVideoEnded() {
// let startAngle
// const { nextSceneId, angleAtEnd, dissolveToNextScene } = movieCast
// if (
// nextSceneId &&
// nextSceneId !== 0x3fffffff &&
// nextSceneId !== scene.sceneId
// ) {
// if (
// !isUndefined(angleAtEnd) &&
// angleAtEnd !== -1 &&
// !onVideoEnded.__aborted
// ) {
// startAngle = (angleAtEnd * Math.PI) / 1800
// startAngle -= Math.PI - Math.PI / 6
// }
// logger.info(
// `End of movie transition from ${scene.sceneId} to ${nextSceneId}`,
// )
// dispatch(
// sceneActions.goToScene(nextSceneId, dissolveToNextScene),
// ).catch(() =>
// console.error('Failed to load scene', nextSceneId),
// )
// dispatch(sceneActions.setNextStartAngle(startAngle))
// }
// }
// function onCanPlayThrough() {
// video.removeEventListener('canplaythrough', onCanPlayThrough)
// resolve({
// el: video,
// listeners: {
// ended: onVideoEnded,
// canplaythrough: onCanPlayThrough,
// },
// })
// }
// video.addEventListener('ended', onVideoEnded)
// video.addEventListener('canplaythrough', onCanPlayThrough)
// }).then(({ el, listeners }) => ({
// el,
// listeners,
// data: movieCast,
// }))
// }),
// ).then(videos => {
// // Check is there is already a parent... we will immediately add there.
// const findParent = once(() => videos.find(v => v.parentElement))
// videos.forEach(video => {
// const { el, data, listeners } = video
// applyTransformToVideo({
// transform: generateMovieTransform({
// dimensions: gameSelectors.dimensions(getState()),
// cast: data,
// }),
// video: el,
// })
// assets.push({
// el,
// data,
// listeners,
// })
// remove(loadingAssets, ({ data: lData }) => data === lData)
// const parent = findParent()
// if (parent) {
// parent.parentElement.appendChild(el)
// }
// })
// return videos
// })
// }
// function doLoad({ setState, isLoaded, isLoading }) {
// return (dispatch, getState) => {
// if (isLoaded) {
// return Promise.resolve({})
// }
// if (isLoading) {
// return isLoading
// }
// const assets = []
// const videos = []
// const loadingAssets = []
// const controlledCastsData = scene.casts.filter(
// and(forMorpheusType('ControlledMovieCast'), not(isAudio)),
// )
// const movieCasts = scene.casts.filter(isMovie)
// const imageCasts = scene.casts.filter(c => c.image)
// const gamestates = gamestateSelectors.forState(getState())
// const loadImages = Promise.all(
// imageCasts.map(imageCast => {
// const { fileName, startFrame } = imageCast
// return loadAsImage(getAssetUrl(fileName, `${startFrame}.png`)).then(
// img => ({
// el: img,
// data: imageCast,
// }),
// )
// }),
// )
// // let loadMovies = updateAssets({
// // dispatch,
// // setState,
// // getState,
// // movieCasts,
// // assets,
// // loadingAssets,
// // autoplay: false,
// // });
// const loadMovies = movieCasts
// .filter(cast =>
// isActive({
// cast,
// gamestates,
// }),
// )
// .map(cast => ({ cast }))
// const activeMovieCasts = movieCasts
// .filter(cast =>
// isActive({
// cast,
// gamestates,
// }),
// )
// .map(movieCast => ({
// movieCast,
// autoplay: false,
// }))
// const loadControlledMovies = Promise.all(
// controlledCastsData
// .filter(cast => !cast.audioOnly)
// .map(cast =>
// loadAsImage(getAssetUrl(cast.fileName, 'png')).then(img => ({
// el: img,
// data: cast,
// })),
// ),
// )
// function onVideoEnded(e, movieCast) {
// let startAngle
// const { nextSceneId, angleAtEnd, dissolveToNextScene } = movieCast
// if (
// nextSceneId &&
// nextSceneId !== 0x3fffffff &&
// nextSceneId !== scene.sceneId
// ) {
// if (
// !isUndefined(angleAtEnd) &&
// angleAtEnd !== -1 &&
// !onVideoEnded.__aborted
// ) {
// startAngle = (angleAtEnd * Math.PI) / 1800
// startAngle -= Math.PI - Math.PI / 6
// }
// logger.info(
// `End of movie transition from ${scene.sceneId} to ${nextSceneId}`,
// )
// dispatch(
// sceneActions.goToScene(nextSceneId, dissolveToNextScene),
// ).catch(() => console.error('Failed to load scene', nextSceneId))
// dispatch(sceneActions.setNextStartAngle(startAngle))
// }
// }
// function onCanPlayThrough(e, movieCast) {
// if (
// activeMovieCasts.find(
// ({ movieCast: a, autoplay }) => !autoplay && a === movieCast,
// )
// ) {
// e.currentTarget.play()
// }
// }
// const specialHandler = eventInterface.touchDisablesMouse(
// inputHandlerFactory({
// dispatch,
// scene,
// }),
// )
// const promise = Promise.all([
// loadImages,
// loadMovies,
// loadControlledMovies,
// ]).then(([images, movies, controlledCasts]) => ({
// images,
// controlledCasts,
// isLoaded: true,
// assets,
// movieCasts,
// movies,
// loadingAssets,
// activeMovieCasts,
// onCanPlayThrough,
// specialHandler,
// onVideoEnded,
// videoPreloads: [],
// }))
// setState({
// isLoading: promise,
// })
// return promise
// }
// }
// function doEnter() {
// return (dispatch, getState) => {
// dispatch(gameActions.setCursor(null))
// }
// }
// function onStage({ images, activeMovieCasts }) {
// return (dispatch, getState) => {
// const hotspotData = scene.casts.filter(isHotspot)
// const gamestates = gamestateSelectors.forState(getState())
// activeMovieCasts.forEach(({ videoEl, autoplay }) => {
// if (!autoplay) {
// // videoEl.play()
// }
// })
// hotspotData
// .filter(cast => isActive({ cast, gamestates }))
// .forEach(hotspot => {
// const { gesture } = hotspot
// if (
// GESTURES[gesture] === 'Always' ||
// GESTURES[gesture] === 'SceneEnter'
// ) {
// dispatch(gamestateActions.handleHotspot({ hotspot }))
// }
// })
// images.some(({ data: cast }) => {
// if (cast.actionAtEnd > 0) {
// // FIXME this is a disconnected promise chain because trying to sychronize
// // on the new action while within the scene pipeline did not work
// function tryToTransition() {
// if (!sceneLoadQueue.isPending(scene.sceneId)) {
// logger.info(
// `Image transition from ${scene.sceneId} to ${cast.actionAtEnd}`,
// )
// dispatch(
// sceneActions.goToScene(
// cast.actionAtEnd,
// cast.dissolveToNextScene,
// ),
// )
// } else {
// setTimeout(tryToTransition, 500)
// }
// }
// setTimeout(tryToTransition, 500)
// }
// return null
// })
// return Promise.resolve()
// }
// }
// function doExit({ controlledCasts }) {
// return (dispatch, getState) => {
// // // FIXME: Clean this up!!
// // // const videos = specialSelectors.videos(getState());
// //
// // const everything = sounds;
// // const v = {
// // volume: 1,
// // };
// // const tween = new Tween(v)
// // .to({
// // volume: 0,
// // }, 1000);
// // tween.onUpdate(() => {
// // everything.forEach(({ el, listeners }) => {
// // if (!listeners.ended) {
// // // Only fade out sounds that do not need to finish
// // el.volume = v.volume;
// // }
// // });
// // });
// // tween.start();
// //
// // everything.forEach(({ el, listeners }) => {
// // Object.keys(listeners).forEach((eventName) => {
// // const handler = listeners[eventName];
// // if (eventName === 'ended') {
// // // Used to keep handler from doing things it shouldn't
// // handler.__aborted = true;
// // }
// // });
// // });
// // Reset animated controlledMovieCallbacks
// controlledCasts
// .map(ref => ref.data)
// .filter(
// cast =>
// cast.controlledMovieCallbacks &&
// cast.controlledMovieCallbacks.length,
// )
// .forEach(({ controlledMovieCallbacks }) =>
// controlledMovieCallbacks.forEach(controlledMovieCallback => {
// delete controlledMovieCallback.currentValue
// delete controlledMovieCallback.tick
// }),
// )
// return Promise.resolve({
// exited: true,
// })
// }
// }
// function doUnload({ assets, loadingAssets, videoPreloads }) {
// return () => {
// return Promise.resolve({
// images: [],
// assets: [],
// videoPreloads: [],
// canvas: null,
// isLoaded: false,
// exited: null,
// })
// }
// }
// function doPause({ assets }) {
// return () => {
// assets.forEach(({ el }) => {
// if (el && el.paused) {
// el.__mWasPaused = true
// } else if (el && el.pause) {
// el.pause()
// el.__mWasPaused = false
// }
// })
// }
// }
// function doResume({ assets }) {
// return () => {
// assets.forEach(({ el }) => {
// if (el && !el.__mWasPaused) {
// el.play()
// }
// })
// }
// }
// return {
// applies,
// doLoad,
// doPreload: doLoad,
// doEnter,
// onStage,
// doExit,
// doUnload,
// doPreunload: doUnload,
// doPause,
// doResume,
// }
// })
|
lolDmgApp.controller('DamageSimulationController', function($scope, RiotApi) {
//$scope.currentchampion = {};
RiotApi.getChampionList().then( function(response) {
$scope.champions = response.data.data;
// console.log($scope.champions);
});
RiotApi.getItemList().then( function(response) {
$scope.items = response.data;
$scope.displayitems = $scope.items;
console.log($scope.items);
});
});
lolDmgApp.controller('CurrentChampionController', function($scope) {
$scope.currentchampion = {};
});
lolDmgApp.controller('ChampionStatusController', function($scope){
$scope.currentchampion.displaystats1 = [{}, {}, {}, {}, {}, {}, {}, {}];
$scope.currentchampion.displaystats2 = [{}, {}, {}, {}, {}, {}, {}, {}];
$scope.currentchampion.items = [{}, {}, {}, {}, {}, {}];
$scope.mouseoverStat = {};
$scope.currentitemstats = {};
$scope.DisplayStatus = function() {
console.log($scope.champions);
console.log($scope.currentchampion);
//console.log($scope.champions[$scope.currentchampion.key].stats);
};
// show stat detail in tooltip when mouseover stat
$scope.mouseoverStatDetail = function(stat) {
//console.log(stat);
$scope.mouseoverStat = stat;
};
});
lolDmgApp.controller('ChampionCollectionController', function($scope, $filter, $sce, RiotApi, ngDialog) {
$scope.category = "";
$scope.currentitem = {};
$scope.view = "1";
$scope.buildfromitemtree = [];
$scope.selectedItemIndex = "";
$scope.baseItemImageUrl = "https://ddragon.leagueoflegends.com/cdn/6.24.1/img/item/"
// switch view for Item/Rune/Mastery
$scope.selectView = function(viewValue) {
$scope.view = viewValue;
//console.log($scope.view);
};
// Show item details in display Item List Page
$scope.showItemDetail = function (item) {
if($scope.currentitem !== item) {
$scope.buildfromitemtree = getBuildFromItems(item, $scope.items);
$scope.currentitem = item;
//console.log(item);
}
};
//change current item with selected item from "Build into panel"
$scope.showItemDetailWithID = function(item_id) {
//console.log($scope.items.data[item_id]);
if($scope.currentitem.id !== item_id) {
$scope.currentitem = $scope.items.data[item_id];
$scope.buildfromitemtree = getBuildFromItems($scope.currentitem, $scope.items);
}
};
// buy item from Items List
$scope.buyItem = function(item) {
var itemCapacity = 6;
var itemAdded = false;
for( var i = 0; i < itemCapacity && itemAdded === false; i++) {
if(angular.equals({}, $scope.currentchampion.items[i])) {
$scope.currentchampion.items[i] = item;
itemAdded = true;
}
}
if (itemAdded === false)
$scope.buyitemerror = "Items are full";
//console.log($scope.currentchampion);
// update items stats (stats bonus)
getCurrentItemsStats($scope.currentchampion.items, $scope.currentchampion.displaystats1.concat($scope.currentchampion.displaystats2));
};
// select item from champion itemset.
$scope.selectChampionItem = function( item_index, item) {
$scope.selectedItemIndex = item_index;
$scope.currentitem = item;
$scope.buildfromitemtree = getBuildFromItems($scope.currentitem, $scope.items);
console.log(item);
};
// show item popup info when mouseover
$scope.setCurrentMouseoverItem = function(item) {
$scope.currentmouseoveritem = item;
};
// sell an item
$scope.sellItem = function(item_index, item) {
$scope.selectedItemIndex = "";
$scope.currentitem = {};
$scope.buildfromitemtree = {};
$scope.currentchampion.items[item_index] = {};
$scope.buyitemerror = "";
// update current items stats
getCurrentItemsStats($scope.currentchampion.items, $scope.currentchampion.displaystats1.concat($scope.currentchampion.displaystats2));
};
// get build-from-items tree for selected item
// the output tree will looks like:
// [[{item: item, colspan: colspan}],[],[]...]
// with td colspan attribute, it will format like a hierarchy tree in the view
getBuildFromItems = function(item, items) {
$scope.currentitem.buildFromItems = [];
var itemStructure = [];
var itemFromOutput = [];
var itemFromStack = [];
var maxspan = 1;
var currentLevelItemStructure = [];
// Initial item from array
itemFromOutput.push([item.id.toString()]);
itemStructure.push([{"item": item, "colspan": 1}]);
if(item.from){
itemFromOutput.push(item.from);
itemFromStack.push(item.from);
// $scope.currentitem.buildFromItems.push(item.from);
}
var itemsFromSameLevel = [];
while(itemFromStack.length > 0) {
var itemFrom = itemFromStack[0];
var currentlevelspan = 0;
itemFromStack.splice(0, 1);
//console.log(itemFrom);
itemsFromSameLevel = [];
currentLevelItemStructure = [];
for(var i = 0; i < itemFrom.length; i++) {
//console.log(itemFrom[i]);
//console.log(items.data[itemFrom[i]]);
if(itemFrom[i].length > 0 && items.data[itemFrom[i]].from) {
currentLevelItemStructure.push({"item": items.data[itemFrom[i]], "colspan": items.data[itemFrom[i]].from.length});
currentlevelspan += items.data[itemFrom[i]].from.length;
itemsFromSameLevel.push(items.data[itemFrom[i]].from);
// $scope.currentitem.buildFromItems.push(items.data[itemFrom[i]].from);
}else {
currentLevelItemStructure.push({"item": items.data[itemFrom[i]], "colspan": 1});
currentlevelspan += 1;
itemsFromSameLevel.push([]);
}
}
itemStructure.push(currentLevelItemStructure);
if(itemsFromSameLevel.join('') != '') {
itemFromStack.push(itemsFromSameLevel.join().split(','));
}
if(currentlevelspan > maxspan)
maxspan = currentlevelspan;
}
//console.log(itemFromOutput);
itemStructure[0][0].colspan = maxspan;
//console.log(itemStructure);
//console.log($scope.currentitem.buildFromItems);
return itemStructure;
};
getCurrentItemsStats = function(items, championstats) {
//console.log(championstats);
// initialize item stats to empty array
$scope.currentitemstats = {};
//console.log($scope.currentitemstats);
var itemCapacity = 6;
// loop through current items to get the stats array
for(var i = 0; i < itemCapacity; i++) {
var hiddenitemstats = {};
var itemstats = items[i].stats;
if(!angular.equals({}, items[i])) {
// find hidden stats
hiddenitemstats = parseItemDescription(items[i].sanitizedDescription);
console.log(hiddenitemstats);
}
// if hidden stats found, add to itemstats
if( !angular.equals({}, hiddenitemstats) ) {
angular.extend(itemstats, hiddenitemstats);
console.log(itemstats);
}
if(itemstats) {
// loop through each stats to update champion stats bonus
angular.forEach(itemstats, function(value, key) {
var statName, championstat;
//console.log(key + ":" + value);
// if stat contain "Flat", add the value to the stats bonus
if(key.indexOf("Flat") !== -1) {
// get the name of stat from key, key will have the format of Flat{statname}Mod
statName = key.substring(key.indexOf("Flat") + ("Flat").length, key.length - 3);
championstat = $filter("filter")(championstats, {bonusStat: statName}, true)[0];
if($scope.currentitemstats[statName])
$scope.currentitemstats[statName] += value;
else
$scope.currentitemstats[statName] = value;
}
if(key.indexOf("Percent") !== -1) {
// get the name of stat from key, key will have the format of Percent{statname}Mod
statName = key.substring(key.indexOf("Percent") + ("Percent").length, key.length - 3);
// get champion stat using bonus statName
championstat = $filter("filter")(championstats, {bonusStat: statName}, true)[0];
if($scope.currentitemstats[statName]) {
//console.log();
// if base is equal to 0, use 1 instead, apply for lifesteal, spell vamp
if(championstat.base === 0)
$scope.currentitemstats[statName] += 1 * value;
else
$scope.currentitemstats[statName] += championstat.base * value;
}
else {
// if base is equal to 0, use 1 instead, apply for lifesteal, spell vamp
if(championstat.base === 0) {
$scope.currentitemstats[statName] = 1 * value;
}
else{
$scope.currentitemstats[statName] = championstat.base * value;
}
}
}
// update champion bonus stat and total stat (totalstat = base + bonus)
// attack speed will need growthAsBonus because attack speed grow is bonus(not base)
if(championstat) {
championstat.bonus = $scope.currentitemstats[statName].toFixed(3);
championstat.content = (parseFloat(championstat.base) + parseFloat(championstat.bonus) + (parseFloat(championstat.growthAsBonus || 0) )).toFixed(3);
if(championstat.max && championstat.content > championstat.max) {
championstat.content = championstat.max;
championstat.bonus = championstat.max;
}
}
});
}
console.log(items[i].sanitizedDescription);
}
console.log($scope.currentitemstats);
};
// Parse item description to item stats
parseItemDescription = function(itemDescription) {
description = itemDescription.split(' ').join('');
itemstats = {};
// get the value of life steal if exists
// ex: +20%LifeSteall
if(description.indexOf("LifeSteal") !== -1) {
value = parseFloat(description.substring(description.indexOf("LifeSteal")-3, description.indexOf("LifeSteal")-1))/100;
angular.extend(itemstats, {"FlatLifeStealMod": value});
}
console.log(itemstats);
return itemstats;
};
// change display item base on item's category
$scope.changeDisplayItems = function(category) {
$scope.category = category;
$scope.currentitem = {};
};
// check if this item available if Summoner's Rift
$scope.summonerRiftItem = function( item ) {
return item.gold.purchasable && item.tags != null; //item.maps["11"] &&
};
$scope.getItemList = function() {
ngDialog.open({
template: '/templates/pages/dmgSimulation/partial/championStatus/itemListPopup.html',
className: 'ngdialog-theme-default',
scope: $scope,
width: 950
});
};
});
lolDmgApp.controller('ChampionSelectedController', function($scope, ngDialog, RiotApi){
$scope.message = "this is champion selected controller.";
//console.log($scope.currentchampion);
$scope.resetLevel = function() {
if($scope.currentchampion.level) {
$scope.currentchampion.level = 1;
updateStatsWithLevel($scope.currentchampion.displaystats1.concat($scope.currentchampion.displaystats2));
}
};
$scope.maxLevel = function() {
if($scope.currentchampion.level) {
$scope.currentchampion.level = 18;
updateStatsWithLevel($scope.currentchampion.displaystats1.concat($scope.currentchampion.displaystats2));
}
};
$scope.upLevel = function() {
if($scope.currentchampion.level < 18) {
$scope.currentchampion.level += 1;
updateStatsWithLevel($scope.currentchampion.displaystats1.concat($scope.currentchampion.displaystats2));
}
};
$scope.downLevel = function() {
if($scope.currentchampion.level > 1) {
$scope.currentchampion.level -= 1;
updateStatsWithLevel($scope.currentchampion.displaystats1.concat($scope.currentchampion.displaystats2));
}
};
// calculate new stats when champion level changes
function updateStatsWithLevel(stats) {
for(var i = 0; i < stats.length; i++) {
stat = stats[i].name;
statperlevel = stat + "perlevel";
// console.log(statperlevel);
if($scope.champions[$scope.currentchampion.key].stats[statperlevel]){
level = $scope.currentchampion.level;
if(statperlevel === 'attackspeedperlevel') {
base = 0.625/(1+$scope.champions[$scope.currentchampion.key].stats["attackspeedoffset"]);
growth = base * $scope.champions[$scope.currentchampion.key].stats[statperlevel]/100;
// the grow of attack speed only apply to bonus, not base
stats[i].growthAsBonus = (growth * (level - 1) * (0.685 + 0.0175 * level)).toFixed(3);
// attck speed stat will base on outside item bonus + inside level up bonus
stats[i].content = (parseFloat(base + parseFloat(stats[i].bonus)) + parseFloat(stats[i].growthAsBonus)).toFixed(3);
}
else {
base = $scope.champions[$scope.currentchampion.key].stats[stat];
growth = $scope.champions[$scope.currentchampion.key].stats[statperlevel];
//calculate new stats base on formula
//newStatistic = b + g * (n - 1) * (0.685 + 0.0175 * n)
//where b is base, g is growth, n is current level
stats[i].base = (base + growth * (level - 1) * (0.685 + 0.0175 * level)).toFixed(3);
stats[i].content = (parseFloat(stats[i].base) + parseFloat(stats[i].bonus)).toFixed(3);
}
//console.log(stats[i]);
}
}
};
$scope.DisplayCurrentChampion = function() {
console.log($scope.something);
console.log($scope.currentchampion);
console.log($scope.champions);
};
$scope.DisplayChampion = function() {
//$scope.champions = $scope.championList.data;
console.log($scope.message);
ngDialog.open({
template: '/templates/pages/dmgSimulation/partial/championSelected/championListPopup.html',
className: 'ngdialog-theme-default',
//controller: ['$scope', function($scope) {
//RiotApi.getChampionList().then(function(response){
//console.log(response);
// $scope.champions = response.data.data;
// });
//}],
scope: $scope,
width: 850
});
};
});
lolDmgApp.controller('ChampionListController', function($scope) {
$scope.baseImageUrl = "https://ddragon.leagueoflegends.com/cdn/6.24.1/img/champion/";
$scope.currentchampion.loadingImage = "https://dummyimage.com/160x240/000/fff";
$scope.baseLoadingImageUrl = "https://ddragon.leagueoflegends.com/cdn/img/champion/loading/";
//console.log($scope);
// select champion from popup window, and set currentchampion stats(name, images, stats)
$scope.selectChampion = function(champion_name, champion_key) {
//console.log($scope.champions)
//console.log($scope.champions);
//console.log(champion_name);
// console.log($scope.champions[champion_name]);
//$scope.currentChampion = $scope.champions[champion_name];
$scope.currentchampion.name = champion_name;
$scope.currentchampion.key = champion_key;
$scope.currentchampion.level = 1;
$scope.currentchampion.loadingImage = $scope.baseLoadingImageUrl + champion_key + "_1.jpg";
$scope.currentchampion.thumbnail = $scope.baseImageUrl + $scope.champions[champion_key].image.full;
//console.log("current champion: " + $scope.currentChampion.name);
formattedCurrentChampionStats($scope.champions[$scope.currentchampion.key].stats);
$scope.closeThisDialog("closing champion selection");
};
// private function to initialize current champion stats
function formattedCurrentChampionStats(stats) {
var statsiconlocation = "/images/stats_icons/";
$scope.currentchampion.displaystats1 = [];
$scope.currentchampion.displaystats1.push({name: "hpregen", content: stats.hpregen, icon: statsiconlocation + "hpregen.png", base: stats.hpregen, bonus: 0, bonusStat: "HPRegen"});
$scope.currentchampion.displaystats1.push({name: "mpregen", content: stats.mpregen, icon: statsiconlocation + "mpregen.png", base: stats.mpregen, bonus: 0, bonusStat: "MPRegen"});
$scope.currentchampion.displaystats1.push({name: "armorpen", content: "0 | 0%", icon: statsiconlocation + "armorpen.png", bonus: 0, bonusStat: "ArmorPenetration"});
$scope.currentchampion.displaystats1.push({name: "magicpen", content: "0 | 0%", icon: statsiconlocation + "magicpen.png", bonus: 0, bonusStat: "MagicPenetration"});
$scope.currentchampion.displaystats1.push({name: "lifesteal", content: "0", icon: statsiconlocation + "lifesteal.png", base: 0, bonus: 0, bonusStat: "LifeSteal", max: 1});
$scope.currentchampion.displaystats1.push({name: "spellsteal", content: "0", icon: statsiconlocation + "spellsteal.png", base: 0, bonus: 0, bonusStat: "SepllVamp", max: 1});
$scope.currentchampion.displaystats1.push({name: "attackrange", content: stats.attackrange, icon: statsiconlocation + "attackrange.png", base: stats.attackrange, bonus: 0});
$scope.currentchampion.displaystats1.push({name: "tenacity", content: "0", icon: statsiconlocation + "tenacity.png", bonus: 0});
$scope.currentchampion.displaystats2 = [];
$scope.currentchampion.displaystats2.push({name: "attackdamage", content: stats.attackdamage, icon: statsiconlocation + "attackdamage.png", base: stats.attackdamage, bonus: 0, bonusStat: "PhysicalDamage"});
$scope.currentchampion.displaystats2.push({name: "spelldamage", content: "0", icon: statsiconlocation + "spelldamage.png", base: 0, bonus: 0, bonusStat: "MagicDamage"});
$scope.currentchampion.displaystats2.push({name: "armor", content: stats.armor, icon: statsiconlocation + "armor.png", base: stats.armor, bonus: 0, bonusStat: "Armor"});
$scope.currentchampion.displaystats2.push({name: "spellblock", content: stats.spellblock, icon: statsiconlocation + "spellblock.png", base: stats.spellblock, bonus: 0, bonusStat: "SpellBlock"});
$scope.currentchampion.displaystats2.push({name: "attackspeed", content: (0.625/(1+stats.attackspeedoffset)).toFixed(3), icon: statsiconlocation + "attackspeed.png", base: (0.625/(1+stats.attackspeedoffset)).toFixed(3), bonus: 0, bonusStat: "AttackSpeed", growthAsBonus: 0, max: 2.5});
$scope.currentchampion.displaystats2.push({name: "cooldown", content: 0, icon: statsiconlocation + "cooldown.png", bonus: 0});
$scope.currentchampion.displaystats2.push({name: "crit", content: stats.crit, icon: statsiconlocation + "crit.png", base: 0, bonus: 0, bonusStat: "CritChance", max: 1});
$scope.currentchampion.displaystats2.push({name: "movespeed", content: stats.movespeed, icon: statsiconlocation + "movespeed.png", base: stats.movespeed, bonus: 0, bonusStat: "MovementSpeed"});
}
});
lolDmgApp.controller('ChampionSkillSetController', function($scope) {
$scope.skillSet = [
{icon: 'https://dummyimage.com/30x30/000/fff', identify: 'Q'},
{icon: 'https://dummyimage.com/30x30/000/fff', identify: 'W'},
{icon: 'https://dummyimage.com/30x30/000/fff', identify: 'E'},
{icon: 'https://dummyimage.com/30x30/000/fff', identify: 'R'}
];
});
lolDmgApp.controller('DamgePanelController', function($scope) {
});
|
(function() {
'use strict';
var userServices = function($q, $http, $cookies, $window) {
var deferred = $q.defer();
// Function to login a user
this.login = function(user, remember) {
return $http.post('/api/login', user)
.success(function(res) {
var now = new Date(),
exp;
if (remember) {
exp = new Date(now.getFullYear() + 1, now.getMonth(), now.getDate());
} else {
exp = null;
}
$cookies.put('session', res.token, {
path: '/',
expires: exp
});
//$window.location.href = '/home';
deferred.resolve('Success');
})
.error(function(err) {
deferred.reject(err);
});
};
this.register = function(user) {
return $http.post('/api/register', user)
.success(function(res) {
//$window.location.href = '/home';
deferred.resolve('Success');
})
.error(function(err) {
deferred.reject(err);
});
};
this.logged = function() {
return $http.get('/api/verifysession')
.success(function(res) {
deferred.resolve(res.data);
})
.error(function(err) {
deferred.reject(err);
});
};
// Function to logout a user
this.logout = function() {
$cookies.remove('session', {
path: '/'
});
$window.location.href = '/';
};
this.getAllUsers = function() {
return $http.get('/api/get_all_users')
.success(function(res) {
deferred.resolve('Success');
})
.error(function(err) {
deferred.reject(err);
});
};
this.getIdeasByAuthor = function(userid) {
var config = {
headers: {
'authorid': userid
}
};
return $http.get('/api/ideasbyauthor', config)
.success(function(res) {
deferred.resolve('Success');
})
.error(function(err) {
deferred.reject(err);
});
};
this.getAllIdeas = function(userid) {
var config = {
headers: {
'authorid': userid
}
};
return $http.get('/api/get_all_ideas', config)
.success(function(res) {
deferred.resolve('Success');
})
.error(function(err) {
deferred.reject(err);
});
};
this.getIdeas = function() {
return $http.get('/api/ideas')
.success(function(res) {
deferred.resolve('Success');
})
.error(function(err) {
console.log(err);
deferred.reject(err);
});
};
this.createIdea = function(idea) {
return $http.post('/api/createidea', idea)
.success(function(res) {
deferred.resolve("Success");
})
.error(function(err) {
deferred.reject(err);
});
};
this.deleteIdea = function(idea) {
return $http.post('/api/deleteidea', idea)
.success(function(res) {
deferred.resolve(res.insertId);
})
.error(function(err) {
deferred.reject(err);
});
};
this.updateIdea = function(idea) {
return $http.post('/api/updateidea', idea)
.success(function(res) {
deferred.resolve("Success");
})
.error(function(err) {
deferred.reject(err);
});
};
this.addcomment = function(idea) {
return $http.post('/api/addcomment', idea)
.success(function(res) {
deferred.resolve("Success");
})
.error(function(err) {
deferred.reject(err);
});
};
this.getcomments = function(idea) {
var config = {
headers: {
'idideas': idea
}
};
return $http.get('/api/getcomments', config)
.success(function(res) {
deferred.resolve("Success");
})
.error(function(err) {
deferred.reject(err);
});
};
this.deletecomment = function(idea) {
return $http.post('/api/deletecomment', idea)
.success(function(res) {
deferred.resolve("Success");
})
.error(function(err) {
deferred.reject(err);
});
};
this.deletevote = function(idea) {
return $http.post('/api/deletevote', idea)
.success(function(res) {
deferred.resolve("Success");
})
.error(function(err) {
deferred.reject(err);
});
};
this.checkvote = function(idea) {
var config = {
headers: {
'idi': idea.idi,
'idu': idea.idu
}
};
return $http.get('/api/checkvote', config)
.success(function(res) {
deferred.resolve(res);
})
.error(function(err) {
deferred.reject(err);
});
};
this.getvotes = function(idea) {
var config = {
headers: {
'idideas': idea
}
};
return $http.get('/api/getvotes', config)
.success(function(res) {
deferred.resolve("Success");
})
.error(function(err) {
deferred.reject(err);
});
};
this.upvote = function(idea) {
return $http.post('/api/upvote', idea)
.success(function(res) {
deferred.resolve("Success");
})
.error(function(err) {
deferred.reject(err);
});
};
this.downvote = function(idea) {
return $http.post('/api/downvote', idea)
.success(function(res) {
deferred.resolve("Success");
})
.error(function(err) {
deferred.reject(err);
});
};
};
// Injecting modules used for better minifing later on
userServices.$inject = ['$q', '$http', '$cookies', '$window'];
// Enabling the service in the app
angular.module('ideasmanagement').service('userServices', userServices);
}());
|
// designer_details.css
const d = document.querySelector('.d');
const info = document.querySelector('.info');
const pic_all = document.querySelector('.pic_all');
const profile_content = document.querySelector('.profile_content');
d.addEventListener("click",function(){
pic_all.style.display = 'flex';
profile_content.style.display = 'none';
d.classList.add("d");
info.classList.remove("d");
});
info.addEventListener("click",function(){
pic_all.style.display = 'none';
profile_content.style.display = 'flex';
info.classList.add("d");
d.classList.remove("d");
})
|
class Slingshot{
constructor(bodyA , bodyB){
var options ={
bodyA:bodyA ,
bodyB:bodyB ,
stiffness:.04 , length:10}
this.slingshot = Constraint.create(options)
World.add(world,this.slingshot)
}
display(){
strokeWeight(4)
line(this.slingshot.bodyA.position.x , this.slingshot.bodyA.position.y , this.slingshot.bodyB.position.x , this.slingshot.bodyB.position.y,)
}
}
|
// Global Variables
var errorColor = "#777777";
var u_minL = 2;
var u_maxL = 32;
var e_minL = 6;
var e_maxL = 64;
var p_minL = 8;
var p_maxL = 64;
var fn_minL = 0;
var fn_maxL = 64;
/* ==============================
General Field Validations
============================== */
// Check if field is empty
function isEmpty(field) {
"use strict";
if (field.value === "") {
return true;
}
return false;
}
// Check if length of field is within a given range
function insideRange(field, min, max) {
"use strict";
if (field.value.length <= max && field.value.length >= min) {
return true;
}
return false;
}
// Check if field contains only alphabetic characters
function isAlphabetic(field) {
"use strict";
if ((/^[0-9a-zA-Z\-'_]+$/.test(field.value))) {
return true;
}
return false;
}
/* ==============================
Specific Field Validations
============================== */
// Validate a username field
function validateUsername(usernameField) {
"use strict";
if (isEmpty(usernameField) || !insideRange(usernameField, u_minL, u_maxL) || !isAlphabetic(usernameField)) {
usernameField.style.borderColor = errorColor;
return false;
}
usernameField.removeAttribute("style");
return true;
}
|
import React from 'react';
export default class ResultComponent extends React.Component{
// TODO: change style
constructor(props){
super(props)
this.state = { data: this.props.data }
this.componentWillReceiveProps = this.componentWillReceiveProps.bind(this)
}
componentWillReceiveProps(newProps) {
this.setState({data: newProps.data})
}
render(){
return (
<div>
<h3 className="text-left ml-3">Result</h3>
{
this.state.data.map((value, index) => {
let doc = value._source
return (
<div key={index} className={"ml-5"}>
{doc.ArticleTitle} <br/>
{doc.Title} <br/>
{doc.Author.map((value) => {
return value.ForeName + " " + value.LastName
}).join(", ")} <br/>
{doc.PubDate} <br/>
<br/>
</div>
)
})
}
</div>
);
}
}
|
wms.controller('ShipmentEditCtrl', function ($scope, $filter, $http, $location, $q, $stateParams, UserService, Auth) {
var baseUrl = '/shipment_maintenance'
var shipment_header_id = $stateParams.header_id
var shipment_detail_id = $stateParams.detail_id
var app_parameters = Auth.getAppParameters()
var client = app_parameters.client
var warehouse = app_parameters.warehouse
if (shipment_header_id != null) {
var url = baseUrl + '/'+ shipment_header_id + '.json?client=' + client + '&warehouse='+ warehouse + '&expand=true';
$http.get(url).success(function (data) {
$scope.shipment_header = data.shipment_header
$scope.shipment_details = data.shipment_detail
console.log($scope.shipment_details)
$scope.shipment_detail = $filter('search')(data.shipment_detail, shipment_detail_id, 'id');
}).error(function(){
console.log('failed call');
});
};
$scope.YesorNo = [
{value: 'Y', text: 'Yes'},
{value: 'N', text: 'No'},
];
$scope.header_template = {
name: 'header_template',
url: '/templates/shipment_maintenance/shipment_header.html'
};
$scope.detail_template = {
name: 'detail_template',
url: '/templates/shipment_maintenance/shipment_detail.html'
};
$scope.statuses = [
{value: 'Created', text: 'Created'},
{value: 'Initiated', text: 'Initiated'},
{value: 'In Fullfilment', text: 'In Fullfilment'},
{value: 'Verified', text: 'Verified'},
{value: 'Cancelled', text: 'Cancelled'}
];
$scope.updateHeader = function(data, el, id) {
var url = baseUrl + '/' + id + '/update_header' ;
var d = $q.defer();
d = UserService.updateResource(data, el, id, url, $scope, d)
return d.promise;
};
$scope.updateDetail = function(data, el, id) {
var url = baseUrl + '/' + id + '/update_detail';
var d = $q.defer();
d= UserService.updateResource(data, el, id, url, $scope, d)
return d.promise;
};
$scope.ok = function () {
$location.path(baseUrl);
};
});
|
/**
* Created by patrick conroy on 2/7/18.
*/
import Link from 'next/link'
import moment from 'moment'
const formatArticleDate=(articleDate) =>{
return moment(articleDate).format('MMMM Do YYYY')
}
const ArticleListItem= ({article, id}) => (
<li>
<a onClick={()=>{window.location.href=window.location.origin+"/article?id=0"}}>
<h2>
{article.title}
</h2>
</a>
<p>{(article.username) ? "Posted by "+article.username + " on ": "" }
{(article.datetime)? formatArticleDate(article.datetime):""}</p>
<hr />
<style jsx>{`
hr
{
margin-top: 20px;
margin-bottom: 20px;
border: 0;
border-top: 1px solid #eee;
display: block;
unicode-bidi: isolate;
-webkit-margin-before: 0.5em;
-webkit-margin-after: 0.5em;
-webkit-margin-start: auto;
-webkit-margin-end: auto;
overflow: hidden;
}
h2
{
margin-top: 30px;
margin-bottom: 10px;
font-size: 36px;
font-weight:800;
font-family: 'Open Sans', 'Helvetica Neue', Helvetica, Arial, sans-serif;;
}
p
{
font-family: 'Lora', 'Times New Roman', serif;
color: #808080;
font-size: 18px;
font-style: italic;
margin-top: 0;
line-height: 1.5;
margin: 30px 0;
}
`}</style>
</li>
)
export default ArticleListItem;
|
import React, { useContext } from "react";
import styled from "styled-components";
import "@styles/fontello/css/fontello.css";
import { SpeedSlider } from "@home/SpeedSlider";
import { WrapperButton, SvgIcon } from "@common/Generic";
import { ThemeContext } from "@common/Layout";
import { SlideFromLeft } from "@styles/animations";
import { DispatchContext, StateContext } from "@home/Game";
import { Settings, Play, Pause, Note, Random, Clear } from "@styles/svg/Buttons";
import {
TOGGLE_PLAY,
CLEAR_BOARD,
RANDOM_BOARD,
MUTE_SOUND,
TOGGLE_SETTINGS,
} from "@reducer/action-types";
const ButtonWrapper = styled.div`
border-width: 1px 0 0 1px;
border-style: solid;
border-color: ${({ colors }) => colors.brblack};
box-shadow: 2px 2px 0px black;
display: flex;
flex-direction: row;
justify-content: center;
@media screen and (orientation: landscape) {
flex-direction: column;
margin-right: 10px;
}
`;
const Container = styled.div`
display: flex;
flex-direction: column;
align-items: center;
@media screen and (orientation: landscape) {
flex-direction: row;
}
animation: 0.5s ease 1 both ${SlideFromLeft};
}
`;
const StyledSvg = styled(SvgIcon)`
width: 4vh;
height: 4vh;
margin: 1vh;
${({ muted }) => muted && `opacity: 0.3`}
`;
const Buttons = () => {
const colors = useContext(ThemeContext);
const dispatch = useContext(DispatchContext);
const { mute, isPlaying } = useContext(StateContext);
return (
<Container>
<ButtonWrapper colors={colors}>
<WrapperButton title={TOGGLE_PLAY} onClick={() => dispatch({ type: TOGGLE_PLAY })}>
<StyledSvg color={colors.green} svg={isPlaying ? Pause : Play} />
</WrapperButton>
<WrapperButton title={RANDOM_BOARD} onClick={() => dispatch({ type: RANDOM_BOARD })}>
<StyledSvg color={colors.border} svg={Random} />
</WrapperButton>
<WrapperButton title={CLEAR_BOARD} onClick={() => dispatch({ type: CLEAR_BOARD })}>
<StyledSvg color={colors.red} svg={Clear} />
</WrapperButton>
<WrapperButton title={MUTE_SOUND} onClick={() => dispatch({ type: MUTE_SOUND })}>
<StyledSvg color={colors.blue} muted={mute} svg={Note} />
</WrapperButton>
<WrapperButton title={TOGGLE_SETTINGS} onClick={() => dispatch({ type: TOGGLE_SETTINGS })}>
<StyledSvg color={colors.grey} svg={Settings} />
</WrapperButton>
</ButtonWrapper>
<SpeedSlider dark responsive boxShadows />
</Container>
);
};
export default Buttons;
|
const GameObject = require('./GameObject')
class Engine{
let canvas
const obj = []
let update
constructor(id) {
getCanvas(id)
isRunning = true
}
start() {
obj.forEach(element => {
element.OnInit()
})array
this.update = setInterval(obj.forEach(element => {
element.OnUpdate()
}),200)
}
stop() {
clearInterval(this.update)
}
getCanvas(id) {
this.canvas = document.getElementById(id);
}
render() {
}
draw(GameObject) {
}
}
module.exports = Engine
|
import React, { useState, useEffect, useRef } from 'react';
import { Button, Row, Col, Form, Input, notification, Select } from "antd";
import { updateComesApi } from "../../Api/Sistema/comestibles";
import { UserOutlined, NumberOutlined } from '@ant-design/icons';
export default function EditComesForm(props) {
const { comes, setIsVisibleModal, setReloadComes } = props;
const [ComesData, setComesData] = useState({
nombre: comes.nombre,
cantidad: comes.cantidad,
tipo: comes.tipo,
marca: comes.marca,
clase: comes.clase,
linea: comes.lineas
})
const updateComes = e => {
e.preventDefault();
let ComesUpdate = ComesData;
if (!ComesUpdate.nombre || !ComesUpdate.cantidad || !ComesUpdate.tipo || !ComesUpdate.marca || !ComesUpdate.clase || !ComesUpdate.linea) {
openNotification('bottomRight', "Por favor rellene todos los espacios", "error")
return;
}
updateComesApi(ComesUpdate, comes._id).then(result => {
openNotification('bottomRight', result.message, "success")
setIsVisibleModal(false)
setReloadComes(true);
});
}
const openNotification = (placement, message, type) => {
notification[type]({
message: message,
placement,
});
};
return (
<div>
<h1>Formulario de Edición</h1>
<EditForm
ComesData={ComesData}
setComesData={setComesData}
updateComes={updateComes}
/>
</div>
)
}
function EditForm(props) {
const { ComesData, setComesData, updateComes } = props;
const { Option } = Select
return (
<Form className="form-edit">
<Row gutter={24}>
<Col span={12}>
<Form.Item>
<Input
prefix={<UserOutlined />}
placeholder="Nombre"
onChange={e => setComesData({ ...ComesData, nombre: e.target.value })}
/>
</Form.Item>
</Col>
<Col span={12}>
<Form.Item>
<Input
prefix={<NumberOutlined />}
placeholder="Cantidad"
onChange={e => setComesData({ ...ComesData, cantidad: e.target.value })}
/>
</Form.Item>
</Col>
</Row>
<Row gutter={24}>
<Col span={12}>
<Form.Item>
<Select
placeholder="Seleccione un Tipo"
onChange={e => setComesData({ ...ComesData, tipo: e })}
>
<Option value="Frutas">Frutas</Option>
<Option value="Cacao">Cacao</Option>
<Option value="Carnes">Carnes</Option>
<Option value="Aceites">Aceites</Option>
<Option value="Cereales">Cereales</Option>
<Option value="Vegetales">Vegetales</Option>
<Option value="Legumbres">Legumbres</Option>
<Option value="Frutos Secos">Frutos Secos</Option>
</Select>
</Form.Item>
</Col>
<Col span={12}>
<Form.Item>
<Select
placeholder="Seleccione una Clase"
onChange={e => setComesData({ ...ComesData, clase: e })}
>
<Option value="Fibra">Fibra</Option>
<Option value="Grasas">Grasas</Option>
<Option value="Proteínas">Proteínas</Option>
<Option value="Vitaminas">Vitaminas</Option>
<Option value="Minerales">Minerales</Option>
<Option value="Carbohidratos">Carbohidratos</Option>
</Select>
</Form.Item>
</Col>
</Row>
<Row gutter={24}>
<Col span={12}>
<Form.Item>
<Select
placeholder="Seleccione una Linea"
onChange={e => setComesData({ ...ComesData, linea: e })}
>
<Option value="Secos">Secos</Option>
<Option value="Congelados">Congelados</Option>
<Option value="Refrigerados">Refrigerados</Option>
</Select>
</Form.Item>
</Col>
</Row>
<Form.Item>
<Button type="primary" htmlType="submit" className="btn-submit" onClick={updateComes}>
Actualizar Comestible
</Button>
</Form.Item>
</Form>
)
}
|
import { ADD_TODO,
TOGGLE_TODO_STATUS,
UPDATE_TODO,
DELETE_TODO,
TODO_ITEMS_HYDRATE
} from 'Actions/actionTypes';
const deleteTodo = (state, id) => {
const index = state.findIndex((todo) => {
return todo.id === parseInt(id);
});
return [
...state.slice(0, index),
...state.slice(index + 1)
];
}
const updateTodoItem = (state, action) => {
console.log(action);
const index = state.findIndex((todo) => {
return todo.id === parseInt(action.id);
});
const todo = state[index];
const modifiedTodo = {
...todo,
text: action.text
};
return [
...state.slice(0, index),
modifiedTodo,
...state.slice(index + 1)
]
};
const toggleTodoItem = (state, id) => {
console.log(state, id);
const index = state.findIndex((todo) => {
return todo.id === parseInt(id);
});
const todo = state[index];
const modifiedTodo = {
...todo,
done: !todo.done
};
return [
...state.slice(0, index),
modifiedTodo,
...state.slice(index + 1)
]
}
const todos = (state = [], action) => {
switch(action.type) {
case TODO_ITEMS_HYDRATE:
return [
...action.todos
]
case ADD_TODO:
return [
...state,
{
id: action.id,
text: action.text,
done: false
}
]
case TOGGLE_TODO_STATUS:
return toggleTodoItem(state, action.id);
case UPDATE_TODO:
return updateTodoItem(state, action)
case DELETE_TODO:
return deleteTodo(state, action.id)
default:
return state
}
}
export default todos;
|
/**
* Created by OXOYO on 2019/8/29.
*
* 节点基础方法
*/
import utils from '../utils'
export default {
setState (name, value, item) {
// 设置锚点状态
utils.anchor.setState(name, value, item)
// 设置shapeControl状态
utils.shapeControl.setState(name, value, item)
},
// 绘制后附加锚点
afterDraw (cfg, group) {
// 绘制锚点
utils.anchor.draw(cfg, group)
// 绘制shapeControl
utils.shapeControl.draw(cfg, group)
}
}
|
const Pokemon = require('../Pokemon.js')
const Attack = require('../Attack.js')
const Weakness = require('../Weakness.js')
const Resistance = require('../Resistance.js')
class Pikachu extends Pokemon {
constructor() {
super(
'Pikachu',
60,
60,
'Lightning',
[
new Attack('Electric Ring', 50),
new Attack('Pika Punch', 20)
],
[
new Weakness('Fire', 1.5),
new Resistance('Fighting', 20)
]
)
}
}
module.exports = Pikachu
|
import {
BackgroundImage,
Paper,
Player,
Bot,
Scissor,
Rock,
} from '../../../../../assets';
import {PLAYER_SELECT, PLAY, RESET, RESULT} from '../actions/gameAction';
const initialState = {
arrayGame: [
{
id: 'scissor',
image: Scissor,
status: true,
},
{
id: 'rock',
image: Rock,
status: false,
},
{
id: 'paper',
image: Paper,
status: false,
},
],
playerSelect: {
id: 'scissor',
image: Scissor,
status: true,
},
botSelect: {
id: 'rock',
image: Rock,
status: false,
},
score: 0,
times: 9,
};
const gameReducer = (state = {...initialState}, action) => {
switch (action.type) {
case PLAYER_SELECT:
let newArrGame = [...state.arrayGame];
const selectItem = state.arrayGame.find(
item => item.id === action.payload.id,
);
if (!selectItem.status) {
const previoursSelect = newArrGame.find(item => item.status);
selectItem.status = true;
previoursSelect.status = false;
state.arrayGame = newArrGame;
}
state.playerSelect = selectItem;
return state;
case PLAY:
state.botSelect = state.arrayGame[action.payload];
return state;
case RESULT:
switch (state.playerSelect.id) {
case 'paper':
if (state.botSelect.id === 'paper') {
state.times--;
} else if (state.botSelect.id === 'rock') {
state.score++;
} else {
if (state.score > 0) {
state.score--;
}
state.times--;
}
break;
case 'scissor':
if (state.botSelect.id === 'scissor') {
state.times--;
} else if (state.botSelect.id === 'paper') {
state.score++;
} else {
if (state.score > 0) {
state.score--;
}
state.times--;
}
break;
case 'rock':
if (state.botSelect.id === 'rock') {
state.times--;
} else if (state.botSelect.id === 'scissor') {
state.score++;
} else {
if (state.score > 0) {
state.score--;
}
state.times--;
}
break;
}
return state;
case RESET:
const arrayGame = [
{
id: 'scissor',
image: Scissor,
status: true,
},
{
id: 'rock',
image: Rock,
status: false,
},
{
id: 'paper',
image: Paper,
status: false,
},
];
return {...state, ...initialState, arrayGame};
default:
return state;
}
};
export default gameReducer;
|
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, or any plugin's
// vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file. JavaScript code in this file should be added after the last require_* statement.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require rails-ujs
//= require activestorage
//= require turbolinks
//= require jquery
//= require rails-ujs
//= require_tree .
document.addEventListener("turbolinks:load", function() {
// hoverでparent_categoryを開くーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーー
const category_btn = document.querySelector('#category_button')
const categoryList_container = document.querySelector('.category-list__container')
category_btn.addEventListener('mouseenter', () => {
categoryList_container.classList.add('open_category-list')
});
category_btn.addEventListener('mouseleave', () => {
categoryList_container.classList.remove('open_category-list')
});
categoryList_container.addEventListener('mouseenter', () => {
categoryList_container.classList.add('open_category-list')
});
categoryList_container.addEventListener('mouseleave', () => {
categoryList_container.classList.remove('open_category-list')
});
$('.category-list__container').hover(function(){},function(){
$(this).removeClass('open_category-list');
})
// 動的なカテゴリリストの追加・削除ーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーー
// parent_catogoryをhoverしたとき
$('.parent_category__li').hover(function(){
// hoverしてないときに使う要素
$('#category_button')
$('.category-list__container')
$(this).find('a').css('backgroundColor','rgb(233, 232, 232)');
var parent_category_number = $(this).data('parent') //hoverした<li>のdata-parent属性を取得
$(this).css('backGroundColor','rgb(233, 232, 232)');
var child_lists = '';
// 取得したidをもとに、child-categories[i]を指定して、.each do |child| で<li>を作成する
gon.child_categories[parent_category_number].forEach(function(child, i){
// parentをもとに、取り出したchild配列からhashを取り出し、一つずつに対し、<li>を作成
var child__li = `<li class="child-category__li" data-child="${i}">
<a href="/categories/${child.id}">${child.name}</a>
</li>`;
// <li>を一つにまとめる
child_lists += child__li;
});
// <ul>に入れるための関数
var child_category_ul = `<ul class='child-category__ul'>
${child_lists}
</ul>`;
$(this).append(child_category_ul);
// child_categoryをhoverしたときーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーーー
$('.child-category__li').hover(function(){
$(this).find('a').css('backgroundColor','rgb(233, 232, 232)')
var child_category_number = $(this).data('child') //hoverした<li>のdata-parent属性を取得
var grand_child_lists = '';
// 取得したidをもとに、child-categories[i]を指定して、.each do |child| で<li>を作成する
gon.parent_array[parent_category_number][child_category_number].forEach(function(grand_child){
// parentをもとに、取り出したgrandchild配列からhashを取り出し、一つずつに対し、<li>を作成
var grand_child__li = `<li class="grand_child-category__li">
<a href="/categories/${grand_child.id}">${grand_child.name}</a>
</li>`;
// <li>を一つにまとめる
grand_child_lists += grand_child__li;
});
// <ul>に入れるための関数
var grand_child_category__ul = `<ul class='grand_child-category__ul'>
${grand_child_lists}
</ul>`;
$(this).append(grand_child_category__ul);
},function(){
$(this).find('a').css('backgroundColor','#ffffff');
$('.grand_child-category__ul').remove();
});
},function(){
$(this).find('a').css('backgroundColor','#ffffff');
$('.child-category__ul').remove();
});
});
|
import knex from '../config/db';
class Colaborador {
constructor(nome, bi, photoBi, idCoordenador, photoAvatar, idCurso) {
this.nome = nome;
this.bi = bi;
this.idCurso = idCurso;
this.idCoordenador = idCoordenador;
this.photoAvatar = photoAvatar;
this.photoBi = photoBi;
this.nivelSession = 2;
this.palavraPasse = bi;
}
async save() {
this.palavraPasse = await this.criptPassword();
let dados = await knex.insert(this).into('colaborador');
return dados;
}
criptPassword () {
if(this.palavraPasse){
console.log(this.palavraPasse);
return hash(this.palavraPasse, 8);
}
}
static async show(id) {
let dado = await knex.select().into('colaborador').whereRaw(`id = "${id}"`);
return dado;
}
static async showDate() {
let dados = await knex.select().into('colaborador');
return dados;
}
static async update(id, dado) {
if(dado.palavraPasse){
dado.palavraPasse = await hash(dado.palavraPasse, 8);
}
return knex.whereRaw(`id = "${id}"`).update(dado).table('colaborador');
}
static colaboradorCurso(id) {
return knex.table('colaborador').whereRaw(`idCurso = "${id}"`).count();
}
}
export default Colaborador;
|
var Member = require('../models/member')
var _ = require('underscore')
exports.fetch = function (req, res) {
Member.fetch(function (err, members) {
if (err) {
res.send({
success: false,
reason: err
})
} else {
res.send({
success: true,
classInfoList: members
})
}
})
}
exports.save = function (req, res) {
var memberObj = req.body
var _member
if (memberObj._id) {
Member.findById(memberObj._id, function (err, member) {
if (err) {
res.send({
success: false,
reason: err
})
}
_member = _.extend(member, memberObj)
_member.save(function (err, member) {
if (err) {
res.send({
success: false,
reason: err
})
} else {
res.send({
success: true
})
}
})
})
} else {
_member = new Member(memberObj)
_member.save(function (err, member) {
if (err) {
res.send({
success: false,
reason: err
})
} else {
res.send({
success: true
})
}
})
}
}
exports.del = function (req, res) {
var filterCondition = req.body
Member.remove(filterCondition, function (err) {
if (err) {
res.send({
success: false,
reason: err
})
} else {
res.send({
success: true
})
}
})
}
|
import jwt from 'jsonwebtoken'
import { secret } from '../config'
export default async (ctx, next) => {
const XToken = ctx.get('X-Token');
// console.log(XToken)
if (XToken === '') {
// ctx.throw(401, "no token detected in http header 'X-Token'");
ctx.body = {
code: 40001,
message: '请求头里面没有对应的token信息'
}
}
let tokenContent;
try {
tokenContent = await jwt.verify(XToken, secret);//如果token过期或验证失败,将抛出错误
// console.log(tokenContent)
await next();
} catch (err) {
// ctx.throw(401, 'invalid token');
console.log(err);
if(err.message == 'jwt expired'){
ctx.body = {
code: 40001,
message: 'token已过期,请重新登录'
}
}else{
ctx.throw(500)//在所有加上checkToken的文件只要有错误都会抛出这个
// 抛给了前端的request拦截器了
}
}
}
|
$('.number').keypress(function (event) {
if ((event.which != 46 || $(this).val().indexOf('.') != -1) &&
(event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});
$(document).on("input", '.number', function (event) {
$(this).val(fixDecimalIn($(this).val()));
//alert("Sim");
});
$(document).ready(function () {
changeOperation(".operation-type");
});
function changeOperation(obj) {
var value = $(obj).val();
$(".sell-field").prop("disabled", false);
$(".sell-field-select").prop("disabled", false);
$(".buy-field").prop("disabled", false);
$(".buy-field-select").prop("disabled", false);
$(".btn-insert-trade").prop("disabled", false);
$(".rate-field-select").val("default").change().prop("disabled", false);
$(".rate-field").val("").prop("disabled", false);
switch (value) {
case "1"://TROCA
break;
case "2"://ENTRADA
$(".sell-field").val("").prop("disabled", true);
$(".sell-field-select").val("default").change().prop("disabled", true);
break;
case "3"://SAÍDA
$(".buy-field").val("").prop("disabled", true);
$(".buy-field-select").val("default").change().prop("disabled", true);
break;
default:
$(".btn-insert-trade").prop("disabled", true);
$(".sell-field").prop("disabled", true);
$(".sell-field-select").prop("disabled", true);
$(".buy-field").prop("disabled", true);
$(".buy-field-select").prop("disabled", true);
$(".btn-insert-trade").prop("disabled", true);
$(".rate-field-select").val("default").change().prop("disabled", true);
$(".rate-field").val("").prop("disabled", true);
break;
}
}
$(".operation-type").change(function () {
changeOperation($(this));
})
$(document).on("click", ".btn-insert-trade", function (e) {
$(this).prop("disabled", true);
e.preventDefault();
var operation_value = $(".operation-type").val();
switch (operation_value) {
case "1":
tradeValuesConfirm();
break;
case "2":
if (ValuesConfirm(".buy-field-select", ".buy-field")) {
var selected_buy = $(".buy-field-select").val();
var buy = $(".buy-field").val();
var rate = $(".rate-field").val() != "" ? $(".rate-field").val() : " ";
var selected_rate = $(".rate-field-selected").val() != "default" ? $(".rate-field-selected").val() : " ";
createTrade(buy, selected_buy, " ", " ", rate, selected_rate);
}
break;
case "3":
if (ValuesConfirm(".sell-field-select", ".sell-field")) {
var selected_sell = $(".sell-field-select").val();
var sell = $(".sell-field").val();
var rate = $(".rate-field").val() != "" ? $(".rate-field").val() : " ";
var selected_rate = $(".rate-field-selected").val() != "default" ? $(".rate-field-selected").val() : " ";
createTrade(" ", " ", sell, selected_sell, rate, selected_rate);
}
break;
default:
break;
}
$(this).prop("disabled", false);
});
function ValuesConfirm(select, field, sellorbuy) {
var selected = $(select).val();
var field_set = $(field).val();
var rate = $(".rate-field").val();
var selected_rate = $(".rate-field-select").val();
if (isValidDate($(".date-change").val())) {
if (selected !== "default") {
if (field_set != null && field_set != undefined && field_set != "") {
if (rate != null && rate != undefined && rate != "") {
if (selected_rate === "default") {
alert("Selecione a moeda utilizada para a Taxa.");
}
else {
if (isDecimal(field_set) && isDecimal(rate)) {
return true;
}
else {
alert("Os campos devem estar no formato monetário (####.####).");
}
}
}
else {
//alert("tudo ok sem taxa");
if (isDecimal(field_set)) {
//console.log(fixDecimal(field_set));
return true;
}
else {
alert("Os campos devem estar no formato monetário (####.####).");
}
}
}
else {
alert("Preencha o valor do campo de " + sellorbuy + ".");
}
}
else {
alert("Selecione o Tipo de moeda.");
}
}
else {
alert("A data digitada não é válida.")
$(".data-change").val("");
}
return false;
}
function tradeValuesConfirm() {
var selected_buy = $(".buy-field-select").val();
var selected_sell = $(".sell-field-select").val();
var buy = $(".buy-field").val();
var sell = $(".sell-field").val();
var rate = $(".rate-field").val();
var selected_rate = $(".rate-field-select").val();
if (isValidDate($(".date-change").val())) {
if (selected_buy !== "default" && selected_sell !== "default") {
if (buy != null && buy != undefined && buy != "") {
if (sell != null && sell != undefined && sell != "") {
if (rate != null && rate != undefined && rate != "") {
if (selected_rate === "default") {
alert("Selecione a moeda utilizada para a Taxa.");
}
else {
if (isDecimal(buy) && isDecimal(sell) && isDecimal(rate)) {
createTrade(buy, selected_buy, sell, selected_sell, rate, selected_rate);
}
else {
alert("Os campos devem estar no formato monetário (####.####).");
}
}
}
else {
//alert("tudo ok sem taxa");
if (isDecimal(buy) && isDecimal(sell)) {
createTrade(buy, selected_buy, sell, selected_sell, "", "");
}
else {
alert("Os campos devem estar no formato monetário (####.####).");
}
}
}
else {
alert("Preencha o valor do campo de Venda.");
}
}
else {
alert("Preencha o valor do campo de Compra.");
}
}
else {
alert("Selecione o Tipo de moeda de Venda e Compra.");
}
} else {
alert("A data digitada não é válida");
$(".date-change").val("");
}
}
function isDecimal(text) {
var checkVal = text;
if (checkVal.match("^[0-9]{0,7}((\.|,)[0-9]{1,8}|[0-9]{0,8})$")) {
return true;
} else {
return false;
}
}
function createTrade(buy, coin_buy, sell, coin_sell, rate, coin_rate) {
var TradeTemp = {
trade: {
Tipo: $(".operation-type").val(),
ValorCompra: fixDecimal(buy),
MoedaCompra: coin_buy,
ValorVenda: fixDecimal(sell),
MoedaVenda: coin_sell,
ValorTaxa: fixDecimal(rate),
MoedaTaxa: coin_rate,
Comentario: $(".text-commentary").val() != "" ? $(".text-commentary").val() : " ",
DataTroca: $(".date-change").val()
}
};
var url = "";
$.ajax({
url: "CreateTrade",
data: JSON.stringify(TradeTemp),
method: "POST",
dataType: "JSON",
contentType: "application/json",
success: function (data) {
url = data.url;
window.location.href = url;
}, error: function () {
alert("Ocorreu um erro ao tentar cadastrar uma nova Troca.");
window.location.reload = true;
}
});
}
function isValidDate(s) {
if (s.length > 0) {
var bits = s.split('/');
var d = new Date(bits[2] + '/' + bits[1] + '/' + bits[0]);
return !!(d && (d.getMonth() + 1) == bits[1] && d.getDate() == Number(bits[0]));
} else return false;
}
function fixDecimalIn(text) {
var $this = text,
dot = $this.indexOf('.'),
before, after;
if (dot >= 1) {
before = $this.substr(0, dot).slice(0, 6);
after = $this.substr(dot, $this.lenght).slice(1, 8);
console.log(`${before}.${after}`);
$this = `${before}.${after}`;
}
else {
if (dot == 0) {
$this = $this.slice(0, 9);
}
else
$this = $this.slice(0, 8);
}
return $this;
}
function fixDecimal(text) {
var $this = text;
if ($this.length > 0 && $this != " ") {
var dot = $this.indexOf('.');
switch (dot) {
case 0:
$this = `00${$this}`;
break;
case -1:
$this = `${$this}.00`;
break;
}
} else $this = " ";
return $this;
}
|
console.log(soma(3,4))
// console.log(sub(3,4)) Aqui gera erro pois não está declarado
//Function Declaration (funções declaradas desta forma são carregadas primeiro pelo interpretador)
function soma(x, y){
return x + y
}
//Function expression
const sub = function(x, y){
return x - y
}
//Named function expression
const mult = function mult(x, y){
return x * y
}
|
function isMobile() {
return window.innerHeight > window.innerWidth;
}
const fetchData = async (url) => {
const response = await fetch(url);
return response.json();
};
export { isMobile, fetchData };
|
//handles the creating, and deletion of assets
auraCreate.assetManagement = function($scope, $http){
//adds an asset to a obect
$scope.addAssets = function(){
$http({
method: 'PUT',
url: $scope.queryObjects,
data: {
name: $scope.curObj.name,
desc: $scope.curObj.description,
beacon_id: $scope.curObj.beacon_id,
arobj_id: $scope.curObj.arobj_id,
organization_id: $scope.curObj.organization_id,
altitude: $scope.curObj.altitude,
latitude: $scope.curObj.latitude,
longitude: $scope.curObj.longitude,
thumbnail: $scope.curObj.thumbnail,
contents: $scope.updatedAssets
},
headers: {
"X-Aura-API-Key": $scope.auraAPIKey
}
}).then(function mySuccess(response){
alertSuccess("SUCCESS: " + $scope.uploadCount + " assets have been successfully added to " + $scope.curObj.name + "!");
$scope.displayObject($scope.curObj);
}, function myError(response) {
alertFailure("ERROR: failed to create the asset/s for " + $scope.curObj.name + ".");
});
}
//deletes an asset from an objects assets and from firebase
$scope.removeAsset = function(asset){
bootbox.confirm({
title: "Delete " + asset.name + "?",
message: "Are you sure you want to permanently delete " + asset.name + "?",
buttons: {
cancel: {
label: '<i class="fa fa-times"></i> Cancel',
className: 'btn-danger'
},
confirm: {
label: '<i class="fa fa-check"></i> Confirm',
className: 'btn-success'
}
},
callback: function (result) {
if(result){
//remove the asset thumbnail from firebase
//remove the asset url from firebase
//Delete the asset by updating the object its associated with
$http({
method: 'Delete',
url: $scope.queryObjects + "/" + $scope.curObj.arobj_id + "/contents/" + asset.content_id,
headers: {
"X-Aura-API-Key": $scope.auraAPIKey
}
}).then(function mySuccess(response) {
alertSuccess("SUCCESS: " + asset.name + " has been successfully deleted!");
}, function myError(response) {
alertFailure("ERROR: failed to delete " + asset.name + ".");
});
}
}
});
}
//adds the asset to the scope in preparation to be added to the server
$scope.updateAssets = function(assetName, assetID, assetURL, thumbnailURL, type){
switch(type){
case "image":
break;
case "audio":
//no thumbnail for audio, use default Aura Headphone image in view
thumbnailURL = "";
break;
case "video":
break;
case "3d":
break;
}
var newAsset = {
name: assetName,
value: assetURL,
content_type: type,
arobj_id: $scope.curObj.arobj_id,
content_id: assetID,
thumbnail: thumbnailURL
}
$scope.updatedAssets = $scope.curObj.assets;
$scope.updatedAssets[$scope.updatedAssets.length] = newAsset;
$scope.uploadCount ++;
if($scope.uploadCount == $scope.files.length){
$scope.addAssets();
}
}
//helper function to scopify assets for deletion purposes
$scope.setAssets = function(){
$scope.curAssets = $scope.curObj.assets;
}
}
|
/**
* Created by kdehbi on 21/04/2016.
*/
'use strict';
eventsApp.controller('CompileSampleController',
function CompileSampleController($scope, $compile, $parse) {
//function will be called by button on our page
//takes in markup
$scope.appendDivToElement = function(markup) {
//calling $compile service & passing in markup
//so we compile this markup in the context of the scope
//which is passed in the compile also
//(the compile service returns a linking function so it returns a function in which the $scope is passed)
return $compile(markup)($scope).
//than this markup is appended to the appendHere div we created in the CompileCache.html
appendTo(angular.element('#appendHere'));
//angular.element similar to jQuery
}
//we create a variable that is set to $parse()
//so the var represents a function that takes in an expression
//however, this function also returns a function (linkedfunction)
var fn = $parse('1+2');
//so if we run this function, it will evaluate the expression and return a value
console.log(fn());
//here $parse, will parse the expression 'event.name'
var getter = $parse('event.name');
//getter is set to a function, but this function also returns a function
var context1 = {event : {name:'AngularJS Boot Camp'}};
var context2 = {event: {name:'Code Camp'}}
console.log(getter(context1));
console.log(getter(context2));
//the function returned by $parse can take in a couple of parameters
//for example a context (here context2) and a local context (here context1)
//anything in context1 will take precedence over context2 in case of overlap
console.log(getter(context2,context1));//will return AngularJS Boot Camp
//you can also assign variables to contexts
//getter here (before) was the function returned by $parse
var setter = getter.assign;
setter(context2, 'Code Retreat');
})
|
import React, {Component} from 'react';
import {connect} from 'react-redux';
import {NavigationContainer} from '@react-navigation/native';
import {createStackNavigator} from '@react-navigation/stack';
import {createDrawerNavigator} from '@react-navigation/drawer';
import Home from '../screen/Home';
import Load from '../screen/load/Load';
import Login from '../screen/user/Login';
import DrawerCustom from '../component/menu/DrawerCustom';
const Stack = createStackNavigator();
const Drawer = createDrawerNavigator();
const Navigation = class extends Component {
constructor(props){
super(props);
}
homeScreen = (props) => {
return(
<Drawer.Navigator drawerContent={() => <DrawerCustom { ... props}/>} initialRouteName='VisitSearch'>
<Drawer.Screen name='Principal' component={Home} />
</Drawer.Navigator>
)
}
render(){
return(
<NavigationContainer>
<Stack.Navigator initialRouteName='Load' >
<Stack.Screen name='Load' component={Load} options={{ headerShown: false}}/>
<Stack.Screen name='Login' component={Login} options={{ headerShown: false}}/>
<Stack.Screen name='Main' component={this.homeScreen} options={{ headerShown: false}}/>
</Stack.Navigator>
</NavigationContainer>
)
}
}
const mapStateToProps = ({ load }) => {
return {
orientation: load.orientation
}
}
export default connect(mapStateToProps,null)(Navigation);
|
import React, { Component } from 'react';
import {
Jumbotron,
Row,
Col,
Button
} from 'reactstrap';
import CardComponent from '../../components/Card/card';
import PropTypes from 'prop-types';
import styles from './jumbotron.scss';
import TalkToWeddingPlanner from '../../components/TalkToWeddingPlanner/talkToWeddingPlanner';
class JumbotronComponent extends Component {
constructor(props) {
super(props);
}
renderButton = (buttonText) => {
if (!buttonText) {
return <div></div>;
}
return (
<div className="mt-5 text-center">
{
this.props.isTalkToAhwanam === true ? <TalkToWeddingPlanner buttonText={buttonText}/> : <Button className="primary-button" onClick={this.props.buttonAction}>{buttonText}</Button>
}
</div>
);
}
renderSubtitle = (subtitle) => {
if (!subtitle) {
return <div></div>;
}
if (this.props.cardType) {
return (
<p className={`w-75 mb-4 text-center ${styles.center} ${styles.pSmall}`}>
{subtitle}
</p>
);
} else {
return (
<p className={`${styles.pLarge} ${styles.center} text-center mb-4`}>
{subtitle}
</p>
)
}
}
renderCards = (cardType) => {
if (!cardType || !this.props.items) {
return <div></div>;
}
const cards = this.props.items.map((item, index) => {
return <Col xs="12" sm="4" className="d-none d-sm-block" key={index}>
<CardComponent cardDetails={item} cardType={cardType} category={this.props.category}/>
</Col>
});
return <Row>{cards}</Row>;
}
render() {
return (
<div>
<Jumbotron style={{ backgroundColor: this.props.bgcolor }} className="mb-0">
<div className={this.props.containerStyle != 'packageWrap' ? (this.props.containerStyle != 'carouselWrap' ? (this.props.containerStyle === 'otherWrap' ? styles.otherWrap : 'container') : styles.carouselWrap) : styles.packageWrap}>
<h2 className="text-center">{this.props.data.title}</h2>
{/* <hr className="mt-3 mb-5" /> */}
{this.renderSubtitle(this.props.data.subtitle)}
{this.props.insideContainer ? this.props.children : ''}
{this.renderCards(this.props.cardType)}
{this.renderButton(this.props.data.buttonText)}
</div>
{!this.props.insideContainer ? this.props.children : ''}
</Jumbotron>
</div>
);
}
}
JumbotronComponent.propTypes = {
data: PropTypes.object,
bgcolor: PropTypes.string,
cardType: PropTypes.string,
buttonAction: PropTypes.func,
items: PropTypes.array,
children: PropTypes.node,
isTalkToAhwanam: PropTypes.bool,
category: PropTypes.string,
insideContainer: PropTypes.bool,
containerStyle: PropTypes.string
};
JumbotronComponent.defaultProps = {
insideContainer: true
}
export default JumbotronComponent;
|
module.exports = {
createOrder: (req,res) => {
const db = req.app.get('db');
const {shipping_address, user_id} = req.body;
db.order_create([shipping_address, user_id]).then(order => {
res.status(200).json(order)
})
},
createLine: (req,res) => {
const db = req.app.get('db');
const {order_id, product_id} = req.body;
db.order_line([order_id, product_id]).then(order => {
res.status(200).json(order)
})
req.session.cart = [];
},
orderHistory: (req, res) => {
const db = req.app.get('db');
const {id} = req.params;
db.order_history_get([id]).then(history => {
res.status(200).send(history)
})
}
}
|
import React, {Component} from 'react'
import {connect} from 'react-redux'
import {checkout} from '../store/currentCart'
import {StripeProvider} from 'react-stripe-elements'
import {Elements} from 'react-stripe-elements'
import Stripe from './Stripe'
class Checkout extends Component {
constructor() {
super()
this.state = {}
this.handleSubmit = this.handleSubmit.bind(this)
}
async handleSubmit() {
event.preventDefault()
await this.props.checkout()
this.props.history.push('/products')
}
render() {
const currentCart = this.props.cart.products
const {isLoggedIn} = this.props
if (isLoggedIn) {
if (!currentCart) {
return <h1>Loading!</h1>
} else {
return (
<div>
<h1>Order Summary</h1>
<table>
<tr>
<th>Items</th>
<th>Quantity</th>
<th>Price</th>
</tr>
{currentCart.map(product => {
return (
<tr>
<td>{product.title}</td>
<td>{product.cartItem.quantity}</td>
<td>${product.price / 100}</td>
</tr>
)
})}
<tr>
<th>Total:</th>
<th />
<th>
${currentCart.reduce((accumulator, product) => {
return (
accumulator + product.cartItem.quantity * product.price
)
}, 0) / 100}
</th>
</tr>
</table>
{/* <h1>Billing and Payment Information</h1> */}
<Stripe
name="Payment Information"
description="Please fill the fields below"
amount={currentCart.reduce((accumulator, product) => {
return accumulator + product.cartItem.quantity * product.price
}, 0)}
/>
</div>
)
}
} else if (!this.props.cart.length) {
return <h1>Loading!</h1>
} else {
return (
<div>
<h1>Order Summary</h1>
<table>
<tr>
<th>Items</th>
<th>Quantity</th>
<th>Price</th>
</tr>
{this.props.cart.map(product => {
return (
<tr>
<td>{product.title}</td>
<td>{product.quantity}</td>
<td>${product.price / 100}</td>
</tr>
)
})}
<tr>
<th>Total:</th>
<th />
<th>
${this.props.cart.reduce((accumulator, product) => {
return accumulator + product.quantity * product.price
}, 0) / 100}
</th>
</tr>
</table>
{/* <h1>Billing and Payment Information</h1> */}
<Stripe
name="Payment Information"
description="Please fill the fields below"
amount={this.props.cart.reduce((accumulator, product) => {
return accumulator + product.quantity * product.price
}, 0)}
/>
</div>
)
}
}
}
const mapStateToProps = state => ({
cart: state.currentCart,
isLoggedIn: !!state.user.id
})
const mapDispatchToProps = dispatch => ({
checkout: () => {
dispatch(checkout())
}
})
export default connect(mapStateToProps, mapDispatchToProps)(Checkout)
|
import React from 'react';
import PropTypes from 'prop-types';
import {Link} from 'react-router-dom';
import {MDBIcon} from 'mdbreact';
import classes from './index.module.css';
const Title = (props) => (
<div className={classes.wrapper}>
<Link to={{
pathname:`/question/${props.questionId}/answer/${props.answerId}`,
}}>
<strong className={classes.title}>{props.title}</strong>
</Link>
<MDBIcon className={classes.iconStyle} icon="ellipsis-h"/>
</div>
);
Title.propTypes = {
// self
title: PropTypes.string.isRequired,
questionId: PropTypes.number.isRequired,
answerId: PropTypes.number.isRequired,
};
export default Title;
|
/**
* Sample React Native App
* https://github.com/facebook/react-native
*
* @format
* @flow
*/
import React from 'react';
import {SafeAreaView} from 'react-native';
import Container from './src/components/container';
import {Provider} from 'react-redux';
import configureStore from './src/store';
const App = () => {
const store = configureStore();
return (
<Provider store={store}>
<SafeAreaView>
<Container />
</SafeAreaView>
</Provider>
);
};
export default App;
|
var leftArray=0
var rightArray=0
var numParts=0;
var secondWord = '';
function functionInit() {
return new Promise(function(resolve, reject) {
getConfig('6').then(function() {
return getConfigByElement("act6","act",1,null);
}).then(function(c){
return functionCallback(c);
}).then(function() {
removeLoading();
playTutorial(actNum);
resolve();
});
});
}
function functionsDD(context,currElem){
isCorrect=checkCorrect(currElem);
if (isCorrect==true) { sessionCounter(); }
}
function functionCallback(conf){
return new Promise(function(resolve, reject) {
conf = conf[0];
var wordToChange = conf["target"] - 1;
var values = conf["values"];
// Choose firstone, they are disordered.
left=values[0].join('').replace(/,/g, ""); //no se van a mover
right=values[1].join('').replace(/,/g, "");
// wordToChange=group["wordToChange"];
functInitWords(left,right,wordToChange); //muestra una palabra y oculta la otra
secondWord = right;
getConfigByElementWithOne("distractors","words",2,functInitImages,right)
.then(function() {
resolve();
});
});
}
function moveToTarget(elem) {
$('#target').append(elem);
functionsDD($('#target'),elem);
}
function changeColor(cont,words,wordToChange){
parts=words.split("");
elements=[];
$(parts).each(function(ind,elem){
d=document.createElement('div');
elem = elem.toUpperCase();
$(d).html(elem);
a=$(d).addClass('inline');
elements.push(a);
});
wordToChange = $(elements[wordToChange]);
$(wordToChange).addClass('wordSelected');
$(wordToChange).mouseover(function(){
playSound(words);
});
$(wordToChange).click(function(){
// $('.firstWord').fadeOut();
// $('.secondWord').removeAttr('hidden');
var left1 = $("#left1 .wordSelected").removeAttr('hidden');
$("#left0 .wordSelected").replaceWith(left1);
$(left1).addClass("animated flash");
// $(left1).appendTo($(elements[wordToChange]));
$('#target').removeAttr('hidden');
$('#rightContainer').removeAttr('hidden');
$('#firstImage').remove();
// $('#left1').removeClass('secondWordHidden');
playSound( $(this).html() );
});
return elements;
}
//sin desordenar
function functInitWords(first,second,wordToChange){
//palabra inicial con letra llamativa------------------------
t=$('#leftboxTemp').clone();
$(t).attr('id','left0');
name=first;
addSound(name);
$(t).attr('name',name);
$(t).attr('alt', name);
$(t).addClass('firstWord');
$(t).addClass('textBackground');
$(t).removeAttr('hidden');
$(t).hover(function() {
playSound(this.name);
});
changed=changeColor($(t),name,wordToChange);
$(t).html(changed);
$('#leftContainer').append(t);
t='';
//----------------------------------------------------------------------
//palabra oculta -----------------------------------------------
t=$('#leftboxTemp').clone();
$(t).attr('id','left1');
name=second;
addSound(name);
$(t).attr('name',name);
$(t).attr('alt', name);
$(t).removeAttr('hidden');
$(t).addClass('secondWordHidden');
$(t).addClass('textBackground');
$(t).mousedown(function() {
playSound(this.name);
});
changed=changeColor($(t),name,wordToChange);
$(t).html(changed);
$('#leftContainer').append(t);
//-------------------------------------------------------
//---------------initial Image
firstImg(left);
}
function functInitImages(conf,x){
//-------------second stage images
imgs=[];
$(conf).each(function(index,e){
//t=$('#'+rightArray[index]);
t=$('#rightboxTemp').clone();
$(t).attr('id','right'+index);
$(t).removeAttr('hidden');
name=conf[index];
addSound(name);
$(t).attr('name',name);
$(t).attr('alt', name);
$(t).prop('num',index);
//$(t).css({backgroundImage : 'url(images/imgOculta/' + $(t).attr("name") + '.jpg)'});
$(t).attr('src','images/activities/' + name + '.jpg');
$(t).hover(function(){
var elem = this;
$.data(this, "timer", setTimeout($.proxy(function() {
playSound($(elem).attr("name"));
}, this), 300));
}, function() { clearTimeout($.data(this, "timer")); }
);
imgs.push(t);
});
disorder(imgs);
$("#rightContainer").append(imgs);
contRight=$('#rightContainer').children();
idObj=$('#target');
dragAndDrop(contRight,idObj,functionsDD,moveToTarget);
}
function firstImg(conf){
//-------------------------show image
t1=$('#rightboxTemp').clone();
$(t1).attr('id','firstImage');
$(t1).addClass('firstImage');
$(t1).attr('src','images/activities/' + conf + '.jpg');
$(t1).removeAttr('hidden');
$("#leftContainer").append(t1);
}
function checkCorrect(part) {
var name = $(part).attr("name");
$(part).removeClass('img-rigth');
if(name.valueOf() == secondWord.valueOf()) {
window.setTimeout(function(){$(part).addClass("animateToFront");},0);
return true;
}
else {
wrong(part,"#rightContainer");
window.setTimeout(function(){
$(part).addClass('img-rigth');
}, 1000);
return false;
}
}
function checkReplace(box,newDiv){
if( $(box).has('img') ){
prevDiv=$(box).children();
$(prevDiv).removeClass('wrong');
$(prevDiv).addClass('normal');
$('#rightContainer').append(prevDiv);
$(box).append(newDiv);
}
}
|
import React, {Component} from 'react'
import Panel from './Panel'
class Staff extends Component {
render(){
return(
<div className="staffView">{this.props.position + ' ' + this.props.name + ' ' + this.props.family}</div>
)
}
}
export default Staff;
|
// eslint-disable-next-line
import React, { Component } from 'react';
import TextField from 'material-ui/TextField';
import Divider from 'material-ui/Divider';
import DatePicker from 'material-ui/DatePicker';
class DeniedForm extends Component {
// constructor(props) {
// super(props);
// this.state = {
// value: ''
// };
//
// this.handleSubmit = this.handleSubmit.bind(this);
// }
handleSubmit(e) {
console.log("FORM SUBMITTED", this.state.value);
}
render() {
return (
<div>
<h1>Denied</h1>
<form onSubmit={this.handleSubmit}>
<TextField hintText="Company" underlineShow={false}/>
<Divider />
<DatePicker hintText="Date" mode="landscape" underlineShow={false} />
</form>
</div>
)
}
}
export default DeniedForm;
|
/**
* This file is part of Sesatheque.
* Copyright 2014-2015, Association Sésamath
*
* Sesatheque is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License version 3
* as published by the Free Software Foundation.
*
* Sesatheque is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Sesatheque (LICENCE.txt).
* @see http://www.gnu.org/licenses/agpl.txt
*
*
* Ce fichier fait partie de l'application Sésathèque, créée par l'association Sésamath.
*
* Sésathèque est un logiciel libre ; vous pouvez le redistribuer ou le modifier suivant
* les termes de la GNU Affero General Public License version 3 telle que publiée par la
* Free Software Foundation.
* Sésathèque est distribué dans l'espoir qu'il sera utile, mais SANS AUCUNE GARANTIE,
* sans même la garantie tacite de QUALITÉ MARCHANDE ou d'ADÉQUATION à UN BUT PARTICULIER.
* Consultez la GNU Affero General Public License pour plus de détails.
* Vous devez avoir reçu une copie de la GNU General Public License en même temps que Sésathèque
* (cf LICENCE.txt et http://vvlibri.org/fr/Analyse/gnu-affero-general-public-license-v3-analyse
* pour une explication en français)
*/
'use strict'
/**
* Un groupe d'utilisateurs
* @constructor
* @private
* @param {Object} initObj Un objet ayant des propriétés d'un groupe
*/
function Groupe (initObj) {
if (!initObj || typeof initObj !== 'object') initObj = {}
/**
* L'identifiant interne à la sésathèque
* @type {Integer}
* @default undefined
*/
this.oid = initObj.oid || undefined
/**
* Nom
* @type {string}
* @default ''
*/
this.nom = typeof initObj.nom === 'string' ? initObj.nom.trim() : ''
/**
* Description
* @type {string}
* @default ''
*/
this.description = typeof initObj.description === 'string' ? initObj.description : ''
/**
* Tout le monde peut s'y inscrire
* @type {boolean}
* @default false
*/
this.ouvert = !!initObj.ouvert
/**
* Visible dans la liste générale des groupes, tout le monde peut suivre ses publications
* @type {boolean}
*/
this.public = !!initObj.public
/**
* liste de pid de ceux qui peuvent gérer le groupe (le créateur et ceux à qui il a délégué la gestion)
* @type {string[]}
*/
this.gestionnaires = initObj.gestionnaires || []
/**
* @name dateCreation
* @type {Date}
* @default undefined
*/
if (initObj.dateCreation) {
if (typeof initObj.dateCreation === 'string') this.dateCreation = new Date(initObj.dateCreation)
else if (initObj.dateCreation instanceof Date) this.dateCreation = initObj.dateCreation
} // sinon, sera ajouté à l'écriture en Bdd
}
module.exports = Groupe
|
export { default } from './component'
export { default as Label } from './label'
export { default as Supporting } from './supporting'
|
angular.module('manager')
.controller('NotesController', [
'$scope', '$filter', '$http', '$modal', 'settingsService', 'Str',
function ($scope, $filter, $http, $modal, $db, str) {
var api = $db.getApi("Notes");
$scope.current = {
user: 0,
category: 0,
search: ""
};
$scope.notesGridData = [];
$scope.selectednotes = [];
api.getCategories().success(function (data) {
$scope.categories = data;
});
var linkTemplate = '<div class="ngCellText" ng-class="col.colIndex()">' +
'<a href="public/note/?id={{row.getProperty(\'PublicId\')}}">' +
'{{row.getProperty(col.field)}}' +
'</a></div>';
$scope.notesGrid = {
data: 'notesGridData',
multiSelect: false,
selectedItems: $scope.selectednotes,
enableColumnResize: true,
enableCellSelection: false,
enableRowSelection: true,
enableCellEdit: false,
enableRowEdit: false,
columnDefs: [
{
field: 'Date',
displayName: str.grid_Date,
cellFilter: 'date:\'yyyy-MM-dd\'',
width: '100px'
},
{ field: 'Category.Name', displayName: str.grid_Category },
{
field: 'Name',
displayName: str.grid_Name,
cellTemplate: linkTemplate
},
{
field: 'Description',
displayName: str.grid_Description,
enableCellEdit: true
},
{ field: 'Owner.UserName', displayName: str.grid_Owner, width: '80px' },
{
displayName: str.grid_Actions,
cellTemplate: '<div style="text-align:center;">' +
'<button class="btn btn-warning btn-xs" ng-click="addNote(true,$index)" title="' + str.action_Edit + '">' +
'<span class="glyphicon glyphicon-pencil"></span>' +
'</button>' +
'<button class="btn btn-danger btn-xs" type="button" ng-click="deleteNotes($index)" title="' + str.action_Remove + '">' +
'<span class="glyphicon glyphicon-remove"></span>' +
'</button>' +
'</div>',
width: '80px',
enableCellEdit: false
}
],
};
$scope.update = function () {
api.getItems($scope.current.user, $scope.current.category, $scope.current.search)
.success(function (data) { $scope.notesGridData = data; });
};
$scope.update();
$scope.addNote = function (editable) {
var note = {};
var category = {};
var title;
if (editable) {
angular.copy(this.row.entity, note);
category = note.Category == null ? null :
_.find($scope.categories,
function (c) { return c.Id == note.Category.Id; }
);
title = str.ttl_EditNotes;
} else {
title = str.ttl_AddNotes;
}
$modal.open({
templateUrl: 'addNote.html',
controller: [
'$scope', '$modalInstance', function ($mscope, $modalInstance) {
$mscope.Title = title;
$mscope.c = note;
$mscope.originalContent = note.Content;
$mscope.c.Category = category;
$mscope.categories = $scope.categories;
$mscope.IsNoteChanged = function (content) {
return (typeof $mscope.c == "undefined") ? false : $mscope.originalContent != content;
}
$mscope.save = function () {
api.updateItem($mscope.c).success(function (data) {
$mscope.originalContent = $mscope.c.Content;
});
};
$mscope.ok = function () { $modalInstance.close($mscope.c); };
$mscope.cancel = function () { $modalInstance.dismiss('cancel'); };
}
],
size: 'lg' // lg-900, sm - 300, default - 600
}).result.then(function(item) { api.updateItem(item).then($scope.update); });
};
$scope.deleteNotes = function () {
var exp = this.row.entity;
$modal.open({
templateUrl: 'deleteNote.html',
controller: [
'$scope', '$modalInstance', function ($mscope, $modalInstance) {
$mscope.Title = str.ttl_DeleteNotes;
$mscope.c = exp;
$mscope.ok = function () { $modalInstance.close(); };
$mscope.cancel = function () { $modalInstance.dismiss('cancel'); };
}
]
}).result.then(function() { api.deleteItem(exp).then($scope.update); });
};
}
]);
|
// @flow
import * as React from 'react';
import classNames from 'classnames';
import _ from 'lodash';
import { getUnhandledProps, prefix, defaultProps } from '../utils';
type Props = {
classPrefix?: string,
value?: string,
className?: string,
children?: React.Node,
style?: Object,
onChange?: (value: string, event: SyntheticEvent<*>) => void,
inputRef?: React.ElementRef<*>,
componentClass: React.ElementType
};
class InputSearch extends React.Component<Props> {
handleChange = (event: SyntheticEvent<*>) => {
const { onChange } = this.props;
onChange && onChange(_.get(event, 'target.value'), event);
};
render() {
const {
value,
componentClass: Component,
children,
className,
classPrefix,
inputRef,
style,
...rest
} = this.props;
const addPrefix = prefix(classPrefix);
const unhandled = getUnhandledProps(InputSearch, rest);
return (
<div className={classNames(classPrefix, className)} style={style}>
<Component
{...unhandled}
ref={inputRef}
className={addPrefix('input')}
value={value}
onChange={this.handleChange}
/>
{children}
</div>
);
}
}
const enhance = defaultProps({
classPrefix: 'picker-search',
componentClass: 'input'
});
export default enhance(InputSearch);
|
var chart = Highcharts.chart('container', {
chart: {
type: 'line'
},
title: {
text: '三种算法归一化折损累计增益对比'
},
subtitle: {
text: 'gowalla'
},
xAxis: {
categories: [1, 101, 201, 301, 401, 501, 601, 701, 801, 901, 1001]
},
yAxis: {
title: {
text: 'ndcg rate'
}
},
plotOptions: {
line: {
dataLabels: {
// 开启数据标签
enabled: false
},
// 关闭鼠标跟踪,对应的提示框、点击事件会失效
enableMouseTracking: false
}
},
series: [{
name: 'ngcf_gowalla_ndcg TOP10',
data: [0.016744558, 0.10119898, 0.102479935, 0.104211055, 0.10665003, 0.10621135, 0.10654442, 0.106958985, 0.10698137, 0.10785606, 0.10778848]},{
name: 'lightgcn_gowalla_ndcg TOP10',
data: [0.05366331, 0.10844049, 0.1149618, 0.114172556, 0.11396899, 0.112997256, 0.111715406, 0.11209896, 0.11181076, 0.11143555, 0.11156893]}, {
name: 'bprmf_gowalla_ndcg TOP10',
data: [0.044266034, 0.092652254, 0.09788345, 0.098033175, 0.09854762, 0.10036265, 0.09841372, 0.098666094, 0.09867458, 0.09914931, 0.10041072]}]
});
|
import React, { PropTypes, Component } from 'react';
import {GridList, GridTile} from 'material-ui/GridList';
import IconButton from 'material-ui/IconButton';
import Subheader from 'material-ui/Subheader';
import StarBorder from 'material-ui/svg-icons/toggle/star-border';
//config
import config from '../../configuration/configuration.js';
//dialog with description
import DescriptionDialog from './DescriptionDialog/DescriptionDialog.jsx';
const styles = {
root: {
display: 'flex',
flexWrap: 'wrap',
justifyContent: 'space-around',
height: window.innerHeight - 64 + 'px',
},
gridList: {
width: '100%',
overflowY: 'auto',
},
};
const tilesData = [
{
img: config.img_url() + 'grid-list/00-52-29-429_640.jpg',
title: 'Breakfast',
author: 'John Snow www',
},
{
img: config.img_url() + 'grid-list/burger-827309_640.jpg',
title: 'Tasty burger 1',
author: 'pashminu',
},
{
img: config.img_url() + 'grid-list/00-52-29-429_640.jpg',
title: 'Breakfast',
author: 'Lorem ipsum',
},
{
img: config.img_url() + 'grid-list/burger-827309_640.jpg',
title: 'Tasty burger',
author: 'pashminu',
},
{
img: config.img_url() + 'grid-list/camera-813814_640.jpg',
title: 'Camera',
author: 'Danson67',
},
{
img: config.img_url() + 'grid-list/morning-819362_640.jpg',
title: 'Morning',
author: 'fancycrave1',
},
{
img: config.img_url() + 'grid-list/hats-829509_640.jpg',
title: 'Hats',
author: 'Hans',
},
{
img: config.img_url() + 'grid-list/honey-823614_640.jpg',
title: 'Honey',
author: 'fancycravel',
},
{
img: config.img_url() + 'grid-list/vegetables-790022_640.jpg',
title: 'Vegetables',
author: 'DaDaDaDa',
},
{
img: config.img_url() + 'grid-list/water-plant-821293_640.jpg',
title: 'Water plant',
author: 'John Lennon',
},
{
img: config.img_url() + 'grid-list/vegetables-790022_640.jpg',
title: 'Vegetables',
author: 'ABCD',
},
{
img: config.img_url() + 'grid-list/water-plant-821293_640.jpg',
title: 'Water plant',
author: 'Baran Karki',
},
{
img: config.img_url() + 'grid-list/vegetables-790022_640.jpg',
title: 'Vegetables',
author: 'AilAAl111',
},
{
img: config.img_url() + 'grid-list/water-plant-821293_640.jpg',
title: 'Water plant',
author: 'BkrmadtyaKarki',
},
];
class GridListExampleSimple extends React.Component {
constructor(props) {
super(props);
//set state
this.state = {}
}
render() {
//alert('ionic.Platform.isWebView(): ', ionic.Platform.isAndroid() );
return(
<div style={styles.root}>
<GridList
cellHeight={200}
style={styles.gridList}
>
<Subheader>Grid List Example <DescriptionDialog></DescriptionDialog></Subheader>
{tilesData.map((tile) => (
<GridTile
key={tile.img + tile.author + tile.title}
title={tile.title}
subtitle={<span>by <b>{tile.author}</b></span>}
actionIcon={<IconButton><StarBorder color="white" /></IconButton>}
>
<img src={tile.img} />
</GridTile>
))}
</GridList>
</div>
);
}
}
export default GridListExampleSimple;
|
(function(){
return function(request,script){
return [
{ "coord":[122.841114,45.619026],"value" : 87,"name":"白城市"},
{"coord":[124.823608,45.118243],"value":80,"name":"松原市"},
{"coord":[126.55302,43.843577],"value":43,"name":"吉林市"},
{"coord":[125.3245,43.886841],"value":87,"name":"长春市"}
];
}
})();
|
import Vue from 'vue';
import 'document-register-element/build/document-register-element';
// include vue-custom-element plugin to Vue
import VueCustomElement from 'vue-custom-element'
Vue.use(VueCustomElement)
// include vue-touch plugin to Vue
import VueTouch from 'vue-touch'
Vue.use(VueTouch, {name: 'v-touch'})
// import and register your component(s)
import SpinItemComponent from './components/SpinItemComponent.vue'
Vue.customElement('spin-item', SpinItemComponent)
|
function runTest()
{
FBTest.openNewTab(basePath + "firebug/4153/issue4153.html", function (win)
{
detachFirebug(function (win)
{
FBTest.ok(FBTest.isDetached(), "Firebug must be detached now.");
deactiveFirebug(function ()
{
FBTest.ok(isDeactive(), "Firebug must be deactivated now.");
toggleDetachBar(function ()
{
FBTest.ok(!(FBTest.isDetached() && isDeactive()),
"Firebug must be activated and also attached to the main window now.");
FBTest.testDone();
});
});
});
});
}
function detachFirebug(callback)
{
FBTest.detachFirebug(function(detachedWindow)
{
if (FBTest.ok(detachedWindow, "Firebug is detaching ....."))
{
FBTest.OneShotHandler(detachedWindow, "load", function (event)
{
FBTest.progress("Firebug detached in a new window.");
setTimeout(function ()
{
callback(detachedWindow);
});
});
}
});
}
function toggleDetachBar(callback)
{
FW.Firebug.toggleDetachBar(false, true);
if (FBTest.ok(!FBTest.isDetached(), "Firebug is attached to the main window."))
{
setTimeout(function ()
{
callback();
});
}
else
{
FBTest.testDone();
return;
}
}
function deactiveFirebug(callback)
{
FW.Firebug.closeFirebug(true);
if (FBTest.ok(isDeactive(), "Firebug is deactivated now."))
{
setTimeout(function ()
{
callback();
});
}
else
{
FBTest.testDone();
return;
}
}
function isDeactive()
{
return !FW.Firebug.currentContext;
}
|
import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import _defineProperty from "@babel/runtime/helpers/defineProperty";
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
import React, { useReducer, createContext } from 'react';
import { UUID } from '@ctkit/commons';
import * as store from '@ctkit/local-storage';
var initialState = {
user: null,
authenticated: false,
appId: null
};
var Session = createContext(initialState);
var reducer = function reducer(state, action) {
var sessionId = null;
var prefix = function prefix(id) {
return "".concat(state.appId || action.appId, "-").concat(id);
};
switch (action.type) {
case 'LOGOUT':
store.reset();
return {
appId: state.appId,
user: null,
authenticated: false
};
case 'LOGIN':
if (!action.payload) throw new Error('INVALID_LOGIN_PAYLOAD');
sessionId = UUID.create(); //store.set('user.access_token', action.payload.access_token);
store.set(prefix('session_user'), JSON.stringify(action.payload), sessionId);
store.set(prefix('session_id'), Buffer.from(sessionId).toString('base64'));
return _objectSpread({}, state, {
authenticated: true,
user: action.payload
});
}
return state;
};
function SessionProvider(_ref) {
var children = _ref.children,
appId = _ref.appId;
var sessionId = store.get("".concat(appId, "-session_id"));
var user = null;
if (sessionId) {
try {
var secret = Buffer.from(sessionId, 'base64').toString('utf8');
var userCached = store.get("".concat(appId, "-session_user"), secret);
user = JSON.parse(userCached);
} catch (e) {
console.warn(e.message);
}
}
var _initialState = {
appId: appId,
user: user,
authenticated: user != null
};
var _useReducer = useReducer(reducer, _initialState),
_useReducer2 = _slicedToArray(_useReducer, 2),
state = _useReducer2[0],
dispatch = _useReducer2[1];
var value = {
state: state,
dispatch: dispatch
};
return React.createElement(Session.Provider, {
value: value
}, children);
}
var SessionConsumer = Session.Consumer;
export { Session, SessionProvider, SessionConsumer };
|
$(document).ready(function(){
var default_value = 'find replacer...';
$('.default-value').each(function() {
$(this).focus(function() {
if(this.value == default_value) {
this.value = '';
}
});
$(this).blur(function() {
if(this.value == '') {
this.value = default_value;
}
});
});
$(window).keydown(function(event){
if(event.keyCode == 13) {
event.preventDefault();
return false;
}
});
$("#findreplacer").keypress(function(event) {
if ( event.which == 13 ) {
var value = $('#findreplacer').val();
if (value==''){
return false;
}else{
$("#button-search").click();
}
}
});
$("#button-search").click(function() {
var value = $('#findreplacer').val();
var searchmode= $("input:radio:checked").val();
if (value==default_value){
return false;
}
//window.location="http://linux:8000/man/"+searchmode+"/"+value;
});
$("#findreplacer").keyup(function(){
var str = $('#findreplacer').val();
var searchmode= $("input:radio:checked").val();
if (str.length==0)
{
document.getElementById("livesearch").innerHTML="";
document.getElementById("livesearch").style.display="none";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("livesearch").innerHTML=xmlhttp.responseText;
document.getElementById("livesearch").style.display="block";
}
}
xmlhttp.open("GET","http://linux:8000/man/"+searchmode+"AjaxSearch/"+str,true);
xmlhttp.send();
});
});
function ClearTextSearch(){
document.getElementById("findreplacer").value="find replacer...";
document.getElementById("livesearch").innerHTML="";
document.getElementById("livesearch").style.display="none";
}
|
#!/usr/bin/env node
'use strict';
// check update first
require('update-notifier')({
pkg: require('../package.json')
}).notify({
defer: false
})
var chalk = require('chalk')
var commander = require('commander')
process.on('exit', function() {
if (process.argv.length === 2) {
console.log(chalk.cyan(' ___ '))
console.log(chalk.cyan(' ____/ /___ ____ ____ '))
console.log(chalk.cyan(' / __ / __ \\/ __ \\/ __ \\ '))
console.log(chalk.cyan(' / /_/ / /_/ / / / / /_/ / '))
console.log(chalk.cyan(' \\____/\\____/_/ /_/\\__, / '))
console.log(chalk.cyan(' /____/ '))
console.log('')
console.log(' Version: ' + commander.version())
commander.help()
}
})
commander
// version
.version(require('../package').version, '-v, --version')
// usage
.usage('<command> [options]')
// init
commander
.command('init')
.description('初始化项目文件')
.allowUnknownOption(true)
.option('-f, --force', '直接覆盖,不做目录非空校验')
.action(function(type, options) {
if (!options) {
options = type
type = undefined
}
require('dong-init')({
type: type || 'spa',
force: options.force
})
})
.on('--help', function(){
console.log(' Examples:')
console.log('')
console.log(chalk.gray(' $ ') +
chalk.magenta('dong init spa') +
chalk.gray(' ....... Single Page Application'))
console.log(chalk.gray(' $ ') +
chalk.magenta('dong init web') +
chalk.gray(' ....... General Web Project'))
console.log('')
})
// patch
commander
.command('patch')
.description('给 SPM 打补丁')
.allowUnknownOption(true)
.option('-r, --registry <registry>', '自定义 NPM 源,如 `https://registry.npm.taobao.org`')
.option('-f, --force', '直接打补丁,不校验是否已打补丁')
.action(function(type, options) {
if (!options) {
options = type
type = undefined
}
require('dong-patch')({
type: type || 'manual',
registry: options.registry,
force: options.force
})
})
// build
commander
.command('build')
.description('静态文件构建,包括资源哈希值生成')
.allowUnknownOption(true)
.option('-r, --root <root>', 'Web 服务根目录,默认 `.`')
.option('-v, --views <views>', '视图文件,默认服务根目录下的 `*.html`')
.option('-i, --i18n <i18n>', '需要构建的语言版本,默认不区分语言')
.option('-f, --force', '先清空输出目录')
.option('-d, --debug', 'DEBUG, 仅生成 `seajs, config.js`')
.action(function(type, options) {
if (!options) {
options = type
type = undefined
}
require('dong-build')({
type: type || 'spa',
root: options.root,
views: options.views,
i18n: options.i18n,
force: options.force,
debug: options.debug
})
})
.on('--help', function(){
console.log(' Examples:')
console.log('')
console.log(chalk.gray(' $ ') +
chalk.magenta('dong build spa') +
chalk.gray(' ....... Single Page Application'))
console.log(chalk.gray(' $ ') +
chalk.magenta('dong build web') +
chalk.gray(' ....... General Web Project'))
console.log('')
})
// i18n
commander
.command('i18n')
.description('语言包(待翻译)生成工具')
.allowUnknownOption(true)
.action(function() {
require('dong-i18n')()
})
// serve
commander
.command('serve')
.description('启动 Web 服务')
.allowUnknownOption(true)
.option('-r, --root <root>', 'Web 服务根目录,默认 `.`')
.option('-H, --host <host>', '服务域名,默认 `127.0.0.1`')
.option('-p, --port <port>', '监听端口,默认 `9527`')
.option('-m, --mock <mock>', '接口模拟数据路径,默认 `api`')
.option('-o, --open', '自动在浏览器打开,默认 `false`')
.option('-d, --debug', '显示 DEBUG 信息,默认 `false`')
.action(function() {
require('dong-serve')({
root: this.root,
host: this.host,
port: this.port,
mock: this.mock,
open: this.open,
debug: this.debug
})
})
commander.parse(process.argv)
|
import React from 'react';
import { connect } from 'react-redux';
import { Form, Row, Col, Container } from 'react-bootstrap';
// Helper Components
import StyledButton from '../common/Button/StyledButton';
import BaseDropDown from '../CreatePizza/BaseDropDown';
// Actions
import { setBase, clearPizza, setQuantity } from '../../actions/pizza';
import { addPizza, updatePizzaInPizzas } from '../../actions/pizzas';
import { setMenu } from '../../actions/menu';
import './SizeQuantityPrompt.css'
class SizeQuantityPrompt extends React.Component {
constructor(props) {
super(props);
this.state = {
quantity: this.props.pizza.quantity,
size: this.props.size.type,
};
}
MAX_PIZZA_QUANTITY = 100;
MIN_PIZZA_QUANTITY = 1;
handleSizeChange = (type, item) => {
this.setState({ size: item });
this.props.setBase('size', item);
};
// handler for user-inputted quantities between [1 ... 100]
handleQuantityChange = (e) => {
e.preventDefault();
let value = parseInt(e.target.value);
this.setState({ quantity: value });
this.props.setQuantity(value);
};
// Calculates total price of pizza (quantity * base price)
calcTotalPrice = (basePrice) => {
let totalPrice = basePrice;
// state.quantity has been changed from default to a new number
if (Number.isInteger(this.state.quantity))
this.props.pizza.quantity = this.state.quantity;
totalPrice *= this.props.pizza.quantity;
return totalPrice.toFixed(2);
};
handleSubmit = (e) => {
e.preventDefault();
const currentPizza = { ...this.props.pizza };
// // trying to implement editing a pizza at its real-time index in pizzas
if (currentPizza.editPizzaFlag) {
this.props.setQuantity(this.state.quantity);
this.props.setBase('size', this.state.size);
// update the whatever has changed in the pizza here
// this.props.updatePizzaInPizzas(currentPizza.index, currentPizza)
}
const basePrice = (
Number(currentPizza.basePrice) + currentPizza.size.price
).toFixed(2);
const totalPrice = this.calcTotalPrice(basePrice);
this.props.addPizza({
...currentPizza,
basePrice,
totalPrice,
editPizzaFlag: false,
});
this.props.clearPizza();
this.props.setMenu(4);
};
render() {
return (
<Container fluid className='sizeContainer'>
<Col md={{ span: 2, offset: 5 }}>
<Form onSubmit={this.handleSubmit}>
<Form.Group as={Row}>
<BaseDropDown
value={this.props.size.type || 'Choose Size'}
type={'Size'}
options={this.props.sizes}
handleChange={this.handleSizeChange}
/>
<div className="quantityForm">
<Form.Label>Quantity: </Form.Label>
<Form.Control
name="quantity"
type="number"
min={this.MIN_PIZZA_QUANTITY}
max={this.MAX_PIZZA_QUANTITY}
placeholder={String(this.state.quantity)}
value={String(this.state.quantity)}
onChange={this.handleQuantityChange}
/>
</div>
</Form.Group>
<StyledButton
variant="basicButton"
disabled={
this.props.size.type === null || isNaN(this.state.quantity)
}
text="Add to Cart"
type="submit"
/>
</Form>
</Col>
</Container>
);
}
}
const mapStateToProps = (state) => ({
size: state.pizza.size,
sizes: state.database.sizes,
pizza: state.pizza,
});
export default connect(mapStateToProps, {
setBase,
setQuantity,
clearPizza,
addPizza,
updatePizzaInPizzas,
setMenu,
})(SizeQuantityPrompt);
|
(function(){
"use strict";
function Tivo(imagePath){
//call to super
createjs.BitmapAnimation.call(this);
//var
var _this = this;
_this.life = 100;
_this.leftPress = false;
_this.rightPress = false;
_this.walkingLeft = false;
_this.walkingRight = false;
//set sprite data
_this.spriteData = new createjs.SpriteSheet({
images:[imagePath],
frames:{width:85,height:85},
animations:{idle:[0],walkRight:[1,13],walkLeft:[14,26]}
});
//initializiation
_this.initialize(_this.spriteData);
_this.gotoAndPlay("idle");
//add event listeners
_this.addEventListener('tick',handleTick.bind(_this));
document.addEventListener('keydown',handleKeyDown.bind(_this));
document.addEventListener('keyup',handleKeyUp.bind(_this));
}
/*prototype behaviors*/
Tivo.prototype.constructor = "Tivo";
Tivo.prototype = Object.create(createjs.BitmapAnimation.prototype);
Tivo.prototype.walkLeft = function(){
if(!this.isWalkingLeft){
this.gotoAndPlay("walkLeft");
this.isWalkingLeft= true;
}else{
null;
}
}
Tivo.prototype.walkRight = function(){
if(!this.isWalkingRight){
this.gotoAndPlay("walkRight");
this.isWalkingRight= true;
}else{
null;
}
}
Tivo.prototype.removeLife = function(item){
this.life -= item.damage;
}
Tivo.prototype.getLife = function(){
return this.life;
}
/*Event Handlers*/
function handleTick(e){
var _this = this;
////////////////////////////////control tivo sprite
if(_this.leftPress == true && _this.rightPress == false){
if(_this.x < 0){
null;
}else{
_this.x -= 5;
_this.walkLeft();
}
//console.log('left');
}else if(_this.rightPress == true && _this.leftPress == false){
if(_this.x > 939){
null;
}else{
_this.x += 5;
_this.walkRight();
}
}
}
function handleKeyDown(e){
var _this = this;
switch(e.keyCode){
case 37: _this.leftPress = true;
break;
case 39: _this.rightPress = true;
break;
}
}//end of keydown
function handleKeyUp(e){
var _this = this;
switch(e.keyCode){
case 37: _this.leftPress = false;_this.isWalkingLeft = false;
break;
case 39: _this.rightPress = false;_this.isWalkingRight = false;
break;
}
if(_this.leftPress == false && _this.rightPress == false){_this.gotoAndPlay("idle");}
}//end of keyUp
//expose to global scope
window.Tivo = Tivo;
}());
|
// Task 1
const name = 'Gil';
const age = 28;
const isCool = true;
const friends = ['liat', 'dana', 'efrat', 'oded', 'amos', 'nimrod'];
console.log(`Name: ${name}\nAge: ${age}\nIs cool: ${isCool}\nFriends: ${friends}`);
// Task 2
const person = {
name,
age,
isCool,
friends
}
for (const value of Object.values(person)) {
console.log(value)
}
for (const friend of person.friends) {
console.log(friend);
}
// Task 3
const pFriends = person.friends;
for (let i = 0; i < pFriends.length; i++) {
if (pFriends[i].toLowerCase().startsWith('a')) {
console.log(pFriends[i]);
} else {
continue;
}
}
for (let i = 0; i < pFriends.length; i++) {
pFriends[i].toLowerCase().startsWith('a') && console.log(pFriends[i]);
}
// Task 4
for (const fr of pFriends) {
fr === 'liat' ? console.log('hi liat') :
fr === 'dana' ? console.log('hi dana') :
fr === 'efrat' ? console.log('hi efrat') :
fr === 'oded' ? console.log('bye oded') :
fr === 'amos' ? console.log('hi amos') :
fr === 'nimrod' ? console.log('hi nimrod') :
console.log(`whor are you ${fr}??`);
}
for (const fr of pFriends) {
switch (fr) {
case 'liat':
console.log('hi liat');
break;
case 'nimrod':
case 'efrat':
console.log('So cool...');
break
case 'oded':
console.log('why oded?');
default:
console.log(`${fr} not familiar...`)
}
}
|
// Node.js fiddle
var http = require('http');
var fs = require('fs');
http.createServer((rq,wr)=>{
if(rq.url=='/client.js'){
wr.writeHead(200,{"Content-Type":"text/javascript"});
fs.readFile('client.js',
(e,data)=>{
if(!e)wr.write(data)
else wr.write(e.message)
wr.end();
});
return
}
console.log(rq.headers);
wr.writeHead(200,{'Content-type':'text/html'});
wr.write(`
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="client.js" type="application/javascript" async defer></script>
<link rel="stylesheet" href="">
</head>
<body onload="connect()">
<h3>Running on node server.</h3>
<input type="text" id="nickname" placeholder="enter a nickname">
<div id="render" style="width:19em;height:9em;border:solid grey 1px;background-color:black;color:green;padding:3em;">
</div>
<input id="msg" type="text">
<button onclick="sendMsg()">Send</button>
</body>
</html>`);
wr.end();
}).listen(80,'localhost');
|
import React, { Component } from "react";
import { connect } from "react-redux";
import Grid from "@material-ui/core/Grid";
import Table from "@material-ui/core/Table";
import TableCell from "@material-ui/core/TableCell";
import TableRow from "@material-ui/core/TableRow";
import TableBody from "@material-ui/core/TableBody";
import withWidth from "@material-ui/core/withWidth";
import { isWidthDown } from "@material-ui/core/withWidth";
let id = 0;
function createData(firstCol, secondCol) {
id += firstCol + 1;
return { id, firstCol, secondCol };
}
class HistoryExpansionTable extends Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
const width = this.props.width;
const bookingData = this.props.expansionData;
let ReservationRows;
let PoliciesRows;
let BillRows;
if (bookingData) {
ReservationRows = [
createData("Confirmation Number", bookingData.bookingId),
createData("Guest Name", bookingData.name),
createData("Arrival Date", bookingData.checkIn.toDateString()),
createData("Departure Date", bookingData.checkOut.toDateString()),
createData("Room Type", bookingData.roomType)
];
PoliciesRows = [
createData("Check-In Time", "3:00 PM"),
createData("Check-Out Time", "12:00 noon"),
createData(
"Cancellation Policy",
"Cancellations must be received 48 hours before check-in date for full refund"
)
];
if (this.props.isAuthenticatedNotLoggedIn) {
BillRows = [
createData("Nightly Rate", "$" + bookingData.nightlyRate),
createData("Number of Rooms", bookingData.numRooms),
createData("Number of Nights", bookingData.numberOfNights),
createData("Subtotal", "$" + bookingData.subtotal),
createData(
"Discounts",
bookingData.discounts
? "$" + bookingData.discounts
: bookingData.discounts
),
createData(
"Rewards Discount",
bookingData.rewardsDiscount
? "$" + bookingData.rewardsDiscount
: null
),
createData("Taxes and Fees", "$" + bookingData.taxesAndFees),
createData("Total", "$" + bookingData.total)
];
} else {
BillRows = [
createData("Nightly Rate", "$" + bookingData.nightlyRate),
createData("Number of Rooms", bookingData.numRooms),
createData("Number of Nights", bookingData.numberOfNights),
createData("Subtotal", "$" + bookingData.subtotal),
createData(
"Discounts",
bookingData.discounts
? "$" + bookingData.discounts
: bookingData.discounts
),
createData(
"Rewards Discount",
bookingData.rewardsDiscount
? "$" + bookingData.rewardsDiscount
: null
),
createData("Taxes and Fees", "$" + bookingData.taxesAndFees),
createData("Total", "$" + bookingData.total),
createData("Reward Points Used", bookingData.rewardPointsUsed),
createData(
"Reward Points Earned (*added after check-in)",
bookingData.rewardPointsEarned
)
];
}
return (
<Grid
xs={isWidthDown("xs", width) ? 11 : 12}
container
spacing={isWidthDown("xs", width) ? 0 : 8}
justify="center"
style={{ margin: isWidthDown("xs", width) ? 10 : -8 }}
>
<Grid item xs={isWidthDown("xs", width) ? 11 : 4}>
<div
style={{
color: "white",
paddingLeft: 10,
background:
"linear-gradient(to right, #0c4b78, #3d4e96, #2c76a9)"
}}
>
RESERVATION DETAILS
</div>
<Table>
<TableBody>
{ReservationRows.map(row => (
<TableRow
key={row.id}
style={{
padding: 0
}}
>
<TableCell
align="left"
style={{ paddingLeft: 5, paddingRight: 5, width: 150 }}
>
{row.firstCol}
</TableCell>
<TableCell align="left" style={{ padding: 0 }}>
{row.secondCol}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
<div
style={{
color: "white",
paddingLeft: 10,
background:
"linear-gradient(to right, #0c4b78, #3d4e96, #2c76a9)"
}}
>
POLICIES
</div>
<Table>
<TableBody>
{PoliciesRows.map(row => (
<TableRow key={row.id} style={{ padding: 0 }}>
<TableCell
align="left"
style={{ paddingLeft: 5, paddingRight: 5, width: 150 }}
>
{row.firstCol}
</TableCell>
<TableCell align="left" style={{ padding: 0 }}>
{row.secondCol}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</Grid>
<Grid item xs={isWidthDown("xs", width) ? 11 : 4}>
<div
style={{
color: "white",
paddingLeft: 10,
background:
"linear-gradient(to right, #0c4b78, #3d4e96, #2c76a9)"
}}
>
FINAL BILL
</div>
<Table>
<TableBody>
{BillRows.map(row => {
if (row.secondCol === null) {
// if no discounts, dont render the row
return;
} else {
return (
<TableRow key={row.id} style={{ padding: 0 }}>
<TableCell
align="left"
style={{
paddingLeft: 5,
paddingRight: 5,
width: 150
}}
>
{row.firstCol}
</TableCell>
<TableCell align="right">{row.secondCol}</TableCell>
</TableRow>
);
}
})}
</TableBody>
</Table>
</Grid>
</Grid>
);
} else {
return null;
}
}
}
const mapStateToProps = state => ({
bookingData: state.bookingData,
query: state.query
});
export default connect(mapStateToProps)(withWidth()(HistoryExpansionTable));
|
import React from 'react';
import { graphql } from 'gatsby';
import Layout from '../components/layout.js';
import { Link } from "gatsby";
import BlockContent from '@sanity/block-content-to-react';
import Image from 'gatsby-image'
export const query = graphql`
query($slug: String) {
sanityProject(slug: { current: {eq: $slug} }) {
title
_rawProjectBody
categories {
title
}
projGallery {
asset {
fluid {
...GatsbySanityImageFluid
}
}
}
}
}
`;
export default ({ data }) => (
<Layout>
<div class="project-container">
<div className="intro">
<h1>{ data.sanityProject.title }</h1>
<ul className="categories" style={{ listStyle: 'none' }}>
{ data.sanityProject.categories.map((category) => (
<li> { category.title } </li>
))}
</ul>
</div>
<div className="project-body">
<BlockContent blocks={ data.sanityProject._rawProjectBody } />
{ data.sanityProject.projGallery.map((gallery) => (
<Image fluid={gallery.asset.fluid } />
))}
</div>
</div>
<div className="back-to-home"><Link to="/">Back to home</Link></div>
</Layout>
)
|
var baseUrl = "http://127.0.0.1:8080";
var d = new DimensionsHelper();
function log(i){
console.log(i);
}
function male_vs_female_corr(){
var name = "Personality Correlation";
var sH = new ScatterPlotHelper();
var g = new Graph(d.height, d.width, name, {x:"Male", y:"Female"}, {x:[-1, 17], y:[-1, 17]});
g.value.x = sH.value.x;
g.value.y = sH.value.y;
d3.json(baseUrl+"/couple/codes", function(error, data){
if (error){
console.warn(error)
}
else {
var attr = sH.attr;
attr.cx = g.map.x;
attr.cy = g.map.y;
attr.class = "dot";
var style = sH.style;
var s = new Scatter(g, data.c_data, attr, style);
s.draw()
}
});
}
male_vs_female_corr()
function male_vs_female_sphere(name){
var sH = new ScatterPlotHelper();
var g = new Graph(d.height, d.width, name, {x:"Male", y:"Female"}, {x:[-10, 101], y:[-10, 101]});
g.value.x = sH.value.x;
g.value.y = sH.value.y;
d3.json(baseUrl+"/couple/personality?sphere="+name, function(error, data){
if (error){
console.warn(error)
}
else {
var attr = sH.attr;
attr.cx = g.map.x;
attr.cy = g.map.y;
attr.class = "dot supplement "+name;
var style = sH.style;
var sSupplement = new Scatter(g, data.s_data, attr, style);
sSupplement.draw()
var suppRegLine = new SlopeInterceptLine(g, data.regression.supplement, {}, style);
suppRegLine.draw();
attr.class = "dot compliment "+name;
style.fill = "#EB485A";
style.stroke = "#f28591";
attr.cy = function (d){
return g.scale.y(100-g.value.y(d));
}
var sCompliment = new Scatter(g, data.s_data, attr, style);
sCompliment.draw()
var compRegLine = new SlopeInterceptLine(g, data.regression.compliment, {}, style);
compRegLine.draw();
}
});
}
male_vs_female_sphere("extrovert")
male_vs_female_sphere("intuition")
male_vs_female_sphere("feeling")
male_vs_female_sphere("perceiving")
|
// これは検証用です
// // export文を使ってhello関数を定義する。
// export function hello() {
// alert('Bootstrap');
// }
|
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';
export const getSeason = createAsyncThunk(
'getSeason',
async () => {
const res = await fetch('https://api.jikan.moe/v4/seasons/2021/fall')
if(res.ok) {
const seasonList = await res.json()
return { seasonList }
}
}
)
export const AnimeSeasonSlice = createSlice({
name: "seasonList",
initialState: [],
reducers: {
// setWatch: (state, action) => {
// const showExists = (state.filter(item => state.mal_id === item.mal_id).length > 0)
// if(showExists) {
// state = [...state]
// } else {
// state = [...state, state]
// }
// return { ...state, watchList: [action.payload, ...state.watchList]}
// }
},
extraReducers: {
[getSeason.fulfilled]: (state, action) => {
return action.payload.seasonList;
}
}
})
export const { } = AnimeSeasonSlice.actions
export default AnimeSeasonSlice.reducer
|
$(function () {
$('.glyphicon-remove').on('click', function (event) {
var id = $(event.currentTarget).attr('data-id');
$('#deletingModal').attr('data-id', id);
$('#deletingModal').modal();
});
$('#yes').on('click', function () {
var id = $('#deletingModal').attr('data-id'),
userId = $('.self-container').attr('id');
$.post('../../Album/Delete', {id:id, userId:userId});
$('#'+id).remove();
$('#deletingModal').modal('hide');
})
});
|
const aws = require('aws-sdk');
exports.send = function(sessionParams){
var emailParams = {
Destination:{
ToAddresses:[]
},
Message:{
Subject:{
Charset:'UTF-8',
Data:''
},
Body:{
Html:{
Charset:'UTF-8',
Data:''
},
Text:{
Charset:'UTF-8',
Data:''
}
}
},
Source:"alexa@hopefulloser.io",
};
emailParams.Destination.ToAddresses.push(sessionParams.toAddress);
emailParams.Message.Subject.Data = sessionParams.subject;
emailParams.Message.Body.Html.Data = sessionParams.message;
const ses = new aws.SES({
region:'us-west-2'
});
var email = ses.sendEmail(emailParams,function(err,data){
if(err){
console.log(err,err.stack);
}
else{
console.log(data);
}
});
}
|
const editAbwesenheit = require('./editAbwesenheit')
const putAbwesenheit = (req, res) => {
const updateAbwesenheit = {
from: req.query.from,
until: req.query.until,
title: req.query.title,
description: req.query.description
}
editAbwesenheit(req, res, updateAbwesenheit)
}
module.exports = putAbwesenheit
|
import { createOptionParser, OPTION_CONFIG_PRESET } from 'dr-js/module/common/module/OptionParser'
import { parseOptionMap, createOptionGetter } from 'dr-js/module/node/module/ParseOption'
const { SingleString, SingleInteger } = OPTION_CONFIG_PRESET
const SingleStringPath = { ...SingleString, isPath: true }
const OPTION_CONFIG = {
prefixENV: 'dr-city',
formatList: [
{
...SingleString,
optional: true,
name: 'config',
shortName: 'c',
description: `# from JSON: set to 'path/to/config.json'\n# from ENV: set to 'env'`
},
{ ...SingleString, name: 'hostname', shortName: 'h' },
{ ...SingleInteger, name: 'port', shortName: 'p' },
{
optional: true,
name: 'https',
shortName: 's',
argumentCount: '0+',
extendFormatList: [
{ ...SingleStringPath, name: 'file-SSL-key' },
{ ...SingleStringPath, name: 'file-SSL-cert' },
{ ...SingleStringPath, name: 'file-SSL-chain' },
{ ...SingleStringPath, name: 'file-SSL-dhparam' }
]
},
{ ...SingleStringPath, name: 'path-share' },
{ ...SingleStringPath, name: 'path-user' },
{ ...SingleStringPath, name: 'file-firebase-admin-token' },
{ ...SingleStringPath, optional: true, name: 'path-log', extendFormatList: [ { ...SingleString, optional: true, name: 'prefix-log-file' } ] },
{ ...SingleStringPath, optional: true, name: 'file-pid' }
]
}
const { parseCLI, parseENV, parseJSON, processOptionMap, formatUsage } = createOptionParser(OPTION_CONFIG)
const parseOption = async () => createOptionGetter(await parseOptionMap({ parseCLI, parseENV, parseJSON, processOptionMap }))
const exitWithError = (error) => {
__DEV__ && console.warn(error)
!__DEV__ && console.warn(formatUsage(error.message || error.toString()))
process.exit(1)
}
export { parseOption, exitWithError }
|
import React, {Component} from 'react';
import FacebookLoginButton from 'react-facebook-login/dist/facebook-login-render-props';
import {connect} from "react-redux";
import Facebook from 'react-icons/lib/fa/facebook-square';
import IconButton from '@material-ui/core/IconButton';
import config from "../../../config";
import {facebookLogin} from "../../../store/actions/userActions";
import withStyles from "@material-ui/core/styles/withStyles";
const styles = theme => ({
button: {
marginLeft: '15px',
marginRight: "15px",
background: '#fff'
},
registerBtn: {
background: '#5282b8',
color: '#fff',
fontSize: '12px'
}
});
class FacebookLogin extends Component {
facebookResponse = response => {
if (response.id) {
this.props.facebookLogin(response);
}
};
render() {
const { classes } = this.props;
return <FacebookLoginButton
appId={config.facebookAppId}
fields="name,email,picture"
render={renderProps => (
<IconButton className={classes.button} onClick={renderProps.onClick} variant="fab" color="secondary" aria-label="add">
<Facebook style={{fontSize: '30px'}} />
</IconButton>
)}
callback={this.facebookResponse}
/>
}
}
const mapDispatchToProps = dispatch => ({
facebookLogin: data => dispatch(facebookLogin(data))
});
export default connect(null, mapDispatchToProps)(withStyles(styles)(FacebookLogin));
|
"use strict";
class App {
map;
constructor(artist) {
this.artist = artist;
this.upcomingShows = [];
this._getClientPostion();
}
_getClientPostion() {
navigator.geolocation.getCurrentPosition(this._renderMap.bind(this));
artistForm.classList.add("invisible");
document.getElementById("mapid").classList.remove("hidden");
}
_renderMap(pos) {
const { latitude, longitude } = pos.coords;
this.map = L.map("mapid").setView([latitude, longitude], 9);
L.tileLayer("https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png", {
attribution:
'© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors',
}).addTo(this.map);
this._getTourDates();
}
_getTourDates() {
// ENTER YOUR OWN API KEY AND REMOVE OTHER URL DECLARATION
// const apiKey = "yOUrSuP3r3ven7aPp-id";
// const url = `https://rest.bandsintown.com/v4/artists/${this.artist}/events/?app_id=${apiKey}`;
const url = `https://wesleytheobald.com:3000/bands/${this.artist}`;
fetch(url)
.then((response) => response.json())
.then((data) => {
for (let concert of data) {
this.upcomingShows.push(concert);
this._renderMarker(concert);
}
});
}
_renderMarker(data) {
const coords = [data.venue.latitude, data.venue.longitude];
const date = new Date(data.datetime);
const month = date.toLocaleString("default", { month: "long" });
const marker = L.marker(coords).addTo(this.map).bindPopup(
`${data.lineup[0]} at ${data.venue.name}<br>
${month} ${date.getDate()}, ${date.getFullYear()} - <a href="${
data.url
}">Get Tickets</a>`
);
marker.on("click", (e) =>
this.map.setView([e.latlng.lat, e.latlng.lng], 15)
);
}
}
const artistForm = document.getElementById("artist__form");
artistForm.addEventListener("submit", function (e) {
e.preventDefault();
let artist = document.getElementById("artist").value;
const app = new App(artist);
});
|
var portaApp = angular.module('portaApp', ['ngRoute']);
portaApp.config(function ($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider
.when('/booking', {
templateUrl: 'wp-content/themes/stlportawash/pages/begin.html',
controller: 'mainController',
activePage: 'begin'
})
.when('/location', {
templateUrl: 'wp-content/themes/stlportawash/pages/location.html',
controller: 'locationController',
activePage: 'location'
})
.when('/house', {
templateUrl: 'wp-content/themes/stlportawash/pages/house.html',
controller: 'houseController',
activePage: 'house'
})
.when('/services', {
templateUrl: 'wp-content/themes/stlportawash/pages/services.html',
controller: 'servicesController',
activePage: 'services'
})
.when('/quote', {
templateUrl: 'wp-content/themes/stlportawash/pages/quote.html',
controller: 'quoteController',
activePage: 'quote'
})
.when('/schedule', {
templateUrl: 'wp-content/themes/stlportawash/pages/schedule.html',
controller: 'scheduleController',
activePage: 'schedule'
})
.when('/end', {
templateUrl: 'wp-content/themes/stlportawash/pages/end.html'
})
.when('/commercial', {
templateUrl: 'wp-content/themes/stlportawash/pages/commercial.html'
})
.otherwise({
redirectTo: "/"
});
});
function navController($scope, $route) {
$scope.$route = $route;
}
portaApp.controller('mainController', function ($scope) {
});
portaApp.controller('locationController', function ($scope) {
$scope.Good = false;
$scope.Bad = false;
var mapOptions = {
center: { lat: 38.68, lng: -90.46 },
zoom: 8
};
var image = {
url: 'wp-content/themes/stlportawash/assets/img/marker.png'
}
var map = new google.maps.Map(document.getElementById('map'),
mapOptions);
$scope.Search = function () {
$scope.Good = false;
$scope.Bad = false;
var address = $scope.address;
var radius = parseInt(50, 10) * 1000;
var marker_start = new google.maps.Marker({
position: { lat: 38.688757, lng: -90.464391 },
map: map,
icon: image,
title: "STL PortaWash"
});
var populationOptions = {
strokeColor: '#66FF99',
strokeOpacity: 0.2,
strokeWeight: 2,
fillColor: '#66FF99',
fillOpacity: 0.35,
map: map,
center: new google.maps.LatLng(38.68, -90.46),
radius: 80000
};
var cityCircle = new google.maps.Circle(populationOptions);
var lat = '';
var lng = '';
var geocoder = new google.maps.Geocoder();
var marker_user = null;
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
lat = results[0].geometry.location.lat();
lng = results[0].geometry.location.lng();
marker_user = new google.maps.Marker({
position: { lat: lat, lng: lng },
map: map,
animation: google.maps.Animation.DROP,
title: "Your Location"
});
if (google.maps.geometry.spherical.computeDistanceBetween(marker_user.getPosition(), marker_start.getPosition()) < 80000)
$scope.$apply(function () { $scope.Good = true; });
else
$scope.$apply(function () { $scope.Bad = true; });
}
});
};
});
portaApp.controller('houseController', function ($scope) {
});
portaApp.controller('servicesController', function ($scope) {
this.service = serviceTypes;
this.calculateHours = function () {
var totalHours = 0;
for (var i = 0; i < this.service.length; i++) {
if (this.service[i].selected == true)
totalHours += this.service[i].hours;
};
return totalHours;
};
});
portaApp.controller('quoteController', function ($scope) {
this.service = serviceTypes;
this.customer = customerData;
});
portaApp.controller('scheduleController', function ($scope) {
});
portaApp.controller('finalController', function ($scope) {
});
portaApp.controller('focusController', function ($scope) {
$scope.$watch('focus', function (v) {
$scope.chosenPlace = v;
});
});
portaApp.directive('googleplace', function () {
return {
require: 'ngModel',
scope: {
ngModel: '=',
details: '=?'
},
link: function (scope, element, attrs, model) {
var options = {
types: [],
componentRestrictions: {}
};
scope.gPlace = new google.maps.places.Autocomplete(element[0], options);
google.maps.event.addListener(scope.gPlace, 'place_changed', function () {
scope.$apply(function () {
scope.details = scope.gPlace.getPlace();
model.$setViewValue(element.val());
});
});
}
};
});
portaApp.controller('focusController', function ($scope, $http) {
$scope.customerInput = customerData;
$scope.$watch("focus", function (newVal) {
$scope.formData.search = $scope.chosenPlaceDetails.address_components[0].long_name + ' ' + $scope.chosenPlaceDetails.address_components[1].long_name;
});
$scope.formData = {};
$scope.submission = false;
var param = function (data) {
var returnString = '';
for (d in data) {
if (data.hasOwnProperty(d))
returnString += d + '=' + data[d] + '&';
}
return returnString.slice(0, returnString.length - 1);
};
$scope.submitForm = function () {
$scope.customerInput.totalSqFt = null;
$http({
method: 'POST',
url: 'wp-content/themes/stlportawash/php/zillow.php',
data: param($scope.formData),
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
})
.success(function (data) {
$scope.formData = {};
$scope.submission = true;
$scope.customerInput.totalSqFt = data.messageSuccess;
var numCheck = Number($scope.customerInput.totalSqFt);
if (isNaN(numCheck)) {
$scope.customerInput.errorMessage = "No square footage could be found for this address. Please enter it below.";
$scope.customerInput.successMessage = "";
} else {
$scope.customerInput.successMessage = "Success!";
$scope.customerInput.errorMessage = "";
}
});
};
});
var customerData = {
name: undefined,
phone: undefined,
email: undefined,
address: undefined,
totalSqFt: undefined,
errorMessage: undefined
};
var serviceTypes = [
{
name: "Vinyl Siding",
idName: "vinyl",
hours: 1,
icon: "fa-home",
},
{
name: "Patio",
idName: "patio",
hours: 1,
icon: "fa-leaf"
},
{
name: "Sidewalk",
idName: "sidwalk",
hours: 1,
icon: "fa-chain"
},
{
name: "Deck",
idName: "deck",
hours: 1,
icon: "fa-pagelines"
},
{
name: "Driveway",
idName: "driveway",
hours: 1,
icon: "fa-car"
},
{
name: "Gutters",
idName: "gutters",
hours: 1,
icon: "fa-umbrella"
},
{
name: "Pool",
idName: "pool",
hours: 1,
icon: "fa-tint"
},
{
name: "Garage",
idName: "garage",
hours: 1,
icon: "fa-wrench"
},
{
name: "Concrete",
idName: "concrete",
hours: 1,
icon: "fa-align-justify"
}
];
portaApp.controller('dateController', [
'$scope', '$http', function ($scope, $http) {
this.weekday = weekdays;
this.customerInput = customerData;
this.selectDate = function (startTime, endTime) {
customerData.startTime = startTime;
customerData.endTime = endTime;
}
$http.get('wp-content/themes/stlportawash/php/calendar.php')
.success(function (data) {
JSON.stringify(data);
weekdays[0].date = data.monday;
weekdays[1].date = data.tuesday;
weekdays[2].date = data.wednesday;
weekdays[3].date = data.thursday;
weekdays[4].date = data.friday;
weekdays[0].start8 = data.monstart8;
weekdays[0].start11 = data.monstart11;
weekdays[0].start2 = data.monstart2;
weekdays[0].end11 = data.monend11;
weekdays[0].end2 = data.monend2;
weekdays[0].end5 = data.monend5;
weekdays[1].start8 = data.tuestart8;
weekdays[1].start11 = data.tuestart11;
weekdays[1].start2 = data.tuestart2;
weekdays[1].end11 = data.tueend11;
weekdays[1].end2 = data.tueend2;
weekdays[1].end5 = data.tueend5;
weekdays[2].start8 = data.wedstart8;
weekdays[2].start11 = data.wedstart11;
weekdays[2].start2 = data.wedstart2;
weekdays[2].end11 = data.wedend11;
weekdays[2].end2 = data.wedend2;
weekdays[2].end5 = data.wedend5;
weekdays[3].start8 = data.thustart8;
weekdays[3].start11 = data.thustart11;
weekdays[3].start2 = data.thustart2;
weekdays[3].end11 = data.thuend11;
weekdays[3].end2 = data.thuend2;
weekdays[3].end5 = data.thuend5;
weekdays[4].start8 = data.fristart8;
weekdays[4].start11 = data.fristart11;
weekdays[4].start2 = data.fristart2;
weekdays[4].end11 = data.friend11;
weekdays[4].end2 = data.friend2;
weekdays[4].end5 = data.friend5;
});
}
]);
var weekdays = [
{
dayName: "Monday",
dayId: "mon",
date: null,
start8: null,
end11: null,
start11: null,
end2: null,
start2: null,
end5: null
},
{
dayName: "Tuesday",
dayId: "tue",
date: undefined,
start8: undefined,
end11: undefined,
start11: undefined,
end2: undefined,
start2: undefined,
end5: undefined
},
{
dayName: "Wednesday",
dayId: "wed",
date: undefined,
start8: undefined,
end11: undefined,
start11: undefined,
end2: undefined,
start2: undefined,
end5: undefined
},
{
dayName: "Thursday",
dayId: "thu",
date: undefined,
start8: undefined,
end11: undefined,
start11: undefined,
end2: undefined,
start2: undefined,
end5: undefined
},
{
dayName: "Friday",
dayId: "fri",
date: undefined,
start8: undefined,
end11: undefined,
start11: undefined,
end2: undefined,
start2: undefined,
end5: undefined
}
];
var customerData = {
name: undefined,
phone: undefined,
email: undefined,
address: undefined,
totalSqFt: undefined,
startTime: undefined,
endTime: undefined,
errorMessage: undefined
};
var serviceTypes = [
{
name: "Vinyl Siding",
idName: "vinyl",
hours: 1,
icon: "fa-home",
},
{
name: "Patio",
idName: "patio",
hours: 1,
icon: "fa-leaf"
},
{
name: "Sidewalk",
idName: "sidwalk",
hours: 1,
icon: "fa-chain"
},
{
name: "Deck",
idName: "deck",
hours: 1,
icon: "fa-pagelines"
},
{
name: "Driveway",
idName: "driveway",
hours: 1,
icon: "fa-car"
},
{
name: "Gutters",
idName: "gutters",
hours: 1,
icon: "fa-umbrella"
},
{
name: "Pool",
idName: "pool",
hours: 1,
icon: "fa-tint"
},
{
name: "Garage",
idName: "garage",
hours: 1,
icon: "fa-wrench"
},
{
name: "Concrete",
idName: "concrete",
hours: 1,
icon: "fa-align-justify"
}
];
|
const jwtSecret = process.env.JWT_SECRET || 'foofdytdyd';
module.exports = {
jwtSecret
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.