text stringlengths 7 3.69M |
|---|
import { login, logout, getInfo, signup} from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
const user = {
state: {
token: getToken(),
name: '',
avatar: '',
roles: []
},
mutations: {
SET_TOKEN: (state, data) => {
state.token = data.token;
state.UserName = data.UserName;
},
SET_NAME: (state, name) => {
state.name = name
},
SET_AVATAR: (state, avatar) => {
state.avatar = avatar
},
SET_ROLES: (state, roles) => {
state.roles = roles
}
},
actions: {
// 登录
Login({ commit }, userInfo) {
const username = userInfo.username.trim()
return new Promise((resolve, reject) => {
login(username, userInfo.password).then(data => {
console.log(data);
setToken(data.token)
commit('SET_TOKEN', data)
resolve()
}).catch(error => {
reject(error)
})
})
},
// 获取用户信息
GetInfo({ commit, state }) {
return new Promise((resolve, reject) => {
getInfo(state).then(data => {
let userObj = data.rows[0];
commit('SET_ROLES', [ userObj.permission ])
commit('SET_NAME', userObj.user_name)
commit('SET_AVATAR', '')
resolve(userObj)
}).catch(error => {
reject(error)
})
})
},
// 登出
LogOut({ commit, state }) {
return new Promise((resolve, reject) => {
logout(state).then((data) => {
commit('SET_TOKEN', '')
commit('SET_ROLES', [])
removeToken()
resolve(data)
}).catch(error => {
reject(error)
})
})
},
// 前端 登出
FedLogOut({ commit }) {
return new Promise(resolve => {
commit('SET_TOKEN', '')
removeToken()
resolve()
})
},
//注册
SignUp({ commit }, userInfo) {
const username = userInfo.username.trim()
return new Promise((resolve, reject) => {
signup(username, userInfo.password).then(data => {
resolve(data)
}).catch(error => {
reject(error)
})
})
}
}
}
export default user
|
/*
* All Rights Reserved
* Author: Ashok Kumar Shah
* https://shahnashok.com
*/
if(window.location.hash)
{
var hash = window.location.hash.substring(1);
if(hash == "debug")
document.getElementById('debug').style.display = "block";
}
var shah = new Object();
shah.log = function(msg) {
if(shah.debug)
{
console.log(msg);
document.getElementById('loganswer').textContent = msg;
}
}
shah.table = function(msg) {
if(shah.debug)
console.table(msg);
}
var sl = TAFFY(config);
var packageMCQ = {};
shah.debug = true;
shah.prompt = [4,7,13,20,27,29,35,36,37,40,42,52,63,64,75,82,84,88,92,96];
shah.struct = [ {point: 4, snake: 0, ladder: 46},
{point: 7, snake: 0, ladder: 26},
{point: 13, snake: 0, ladder: 33},
{point: 20, snake: 0, ladder: 39},
{point: 27, snake: 6, ladder: 0},
{point: 29, snake: 0, ladder: 70},
{point: 35, snake: 0, ladder: 53},
{point: 36, snake: 18, ladder: 0},
{point: 37, snake: 0, ladder: 58},
{point: 40, snake: 19, ladder: 0},
{point: 42, snake: 0, ladder: 62},
{point: 52, snake: 0, ladder: 94},
{point: 63, snake: 19, ladder: 0},
{point: 64, snake: 0, ladder: 83},
{point: 75, snake: 54, ladder: 0},
{point: 82, snake: 41, ladder: 0},
{point: 84, snake: 45, ladder: 0},
{point: 88, snake: 67, ladder: 0},
{point: 92, snake: 51, ladder: 0},
{point: 96, snake: 3, ladder: 0}];
shah.questionAttempt = 0;
shah.currentpos;
shah.filtered = [];
shah.lastrolled = 0;
shah.filteredIndex = 0;
shah.setpos = function(curpos) {
shah.currentpos = curpos;
console.log(curpos);
var cellProp = $('td').filter(function(i,e){ return this.textContent.trim() == curpos }).get(0);
var paddingX = 20;
var paddingY = 20;
var pX = ((54 * parseInt(cellProp.cellIndex)) );
var pY = ((53.5 * parseInt(cellProp.parentNode.rowIndex)));
$('#player').animate({top: pY + 'px', left: pX + 'px'});
//document.getElementsByClassName('dice')[0].className = "dice";
if(curpos == "Stop")
{
shah.gameover();
} else if(shah.lastrolled == 6)
{
setTimeout(function()
{
$('.overlay, .sixDigitMsg').show();
setTimeout (function(){
$('.overlay, .sixDigitMsg').hide();
document.getElementById('rolldicebtn').onclick = rolldice;
document.getElementById('reddice').onclick = rolldice;
}, 1500);
}, 1000);
} else if(shah.prompt.indexOf(shah.currentpos) == -1)
{
document.getElementById('rolldicebtn').onclick = rolldice;
document.getElementById('reddice').onclick = rolldice;
} else {
setTimeout(setQuestion(curpos), 1000);
}
}
shah.gameover = function()
{
//alert('game over');
$('#replay').show();
$('#msgComplete').show();
setTimeout(function()
{
//playSound('well done');
$('#msgComplete').addClass('open');
setTimeout(function()
{
$('#msgComplete span img').each(function(i, e)
{
$(this).show().addClass('textEffect' + (i+1));
});
}, 300);
}, 10);
}
var slLevels = new Array();
sl().each(function (r) {
if(slLevels.indexOf(r.level) == -1)
slLevels.push(r.level);
});
var nextscreen = function(oldscreen, newscreen) {
document.getElementById(oldscreen).style.display = "none";
document.getElementById(newscreen).style.display = "block";
}
var selectlevel = function(level) {
nextscreen('screen3', 'screen4');
packageMCQ.level = level;
var slThemes = [];
sl({level: level}).each(function (r) {
if(slThemes.indexOf(r.theme) == -1)
slThemes.push(r.theme);
});
shah.log(slThemes);
var themeHTML = "";
for(var i=0; i<slThemes.length; i++)
themeHTML += '<li onclick="selecttheme(\'' + slThemes[i] + '\')">' + slThemes[i] + '</li>';
document.getElementById('selectTheme').innerHTML = themeHTML;
}
var selecttheme = function(theme) {
nextscreen("screen4", "screen5");
packageMCQ.theme = theme;
shah.filtered = new Array();
sl({level: packageMCQ.level, theme: packageMCQ.theme}).each(function(r)
{
shah.filtered.push(r);
});
shah.table(shah.filtered);
//shuffle(shah.filtered);
shah.setpos("Start");
}
function shuffle(o){
for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
}
var rolldice = function()
{
document.getElementById('rolldicebtn').onclick = ""; //remove click from the roll btn
document.getElementById('reddice').onclick = ""; //remove click from the roll btn
var randomNum;
randomNum = Math.floor(Math.random() * 6) + 1;
if(shah.questionAttempt < 10)
{
parentloop: for(var i=0; i<shah.prompt.length; i++)
{
for(var j=1; j<6; j++)
{
//console.log('current pos: ' + (shah.currentpos+j) + '; prompt: ' + shah.prompt[i]);
if((shah.currentpos+j) == shah.prompt[i])
{
console.log('captured at ' + j);
randomNum = j;
break parentloop;
}
}
}
}
if(window.toroll)
{
randomNum = parseInt(window.toroll);
}
shah.log('dice rolled: ' + randomNum);
document.getElementsByClassName('dice')[0].className = "dice digit" + randomNum;
setTimeout(function()
{
document.getElementsByClassName('dice')[0].className += "static";
if(shah.currentpos == "Start") shah.currentpos = 1;
if(shah.currentpos == "Stop") shah.currentpos = 100;
shah.currentpos += randomNum;
shah.lastrolled = randomNum;
var tempholder;
if(shah.currentpos == 0) tempholder = "Start";
else if(shah.currentpos >= 100) tempholder = "Stop";
else tempholder = shah.currentpos;
shah.setpos(tempholder);
}, 1200);
}
var levelHTML = "";
for(var i=0; i<slLevels.length; i++)
levelHTML += '<li onclick="selectlevel(\'' + (i+1) + '\')">Level ' + slLevels[i] + '</li>';
document.getElementById('selectLevel').innerHTML = levelHTML;
var setQuestion = function(curpos)
{
pos_img = curpos;
curpos = curpos - 1;
//shah.questionAttempt++;
//reshuffle filtered questions before the question repeats
//if(shah.filteredIndex >= shah.filtered.length)
//{
// shuffle(shah.filtered);
// shah.filteredIndex = 0;
// shah.table(shah.filtered);
//}
//insert information for q/a
document.getElementById('questionImg').style.backgroundImage = "url('img/"+ pos_img +".png')";
document.getElementById('questionTitleTxt').textContent = shah.filtered[curpos].question;
for(var i=0; i<4; i++)
{
document.querySelectorAll('#userAnswer ul li')[i].textContent = shah.filtered[curpos].answers[i];
if(i == (parseInt(shah.filtered[curpos].correct) - 1))
{
document.querySelectorAll('#userAnswer ul li')[i].id = "correctans";
shah.log('Ans: ' + shah.filtered[curpos].answers[i]);
}
}
//show question viewer
document.getElementById('questionViewer').style.bottom = "0px";
//shah.filteredIndex++;
}
var submitAnswer = function()
{
//need to update a popup here -- validation for not selecting an answer
if(document.getElementsByClassName('active').length < 1)
{
$('.overlay, .errorMsg').show();
setTimeout (function(){
$('.overlay, .errorMsg').hide();
}, 3500);
//alert("Please select an answer.");
return false;
}
var newpos;
for(var i=0; i<shah.struct.length; i++)
{
if(shah.currentpos == shah.struct[i].point)
{
newpos = shah.struct[i];
break;
}
}
var attempt = (document.getElementsByClassName('active')[0].id == "correctans") ? true : false;
//hide question viewer
document.getElementById('questionViewer').style.bottom = "";
setTimeout(function()
{
if (newpos.ladder != 0 && attempt == true){//is a lader
shah.setpos(newpos.ladder);
document.getElementById((attempt == true) ? "correctsound" : "incorrectsound").play();
document.getElementsByClassName('active')[0].className = "";
}else{
document.getElementById('rolldicebtn').onclick = rolldice;
document.getElementById('reddice').onclick = rolldice;
}
if (newpos.snake != 0 && attempt == false){//is a snake
shah.setpos(newpos.snake);
document.getElementById((attempt == true) ? "correctsound" : "incorrectsound").play();
document.getElementsByClassName('active')[0].className = "";
}else{
document.getElementById('rolldicebtn').onclick = rolldice;
document.getElementById('reddice').onclick = rolldice;
}
}, 1000);
}
var setactiveans = function(ele)
{
if(document.querySelector('.active'))
document.querySelector('.active').className = "";
ele.className = "active";
}
function playagain() {
location.href = document.URL;
}
var setfixroll = function(toroll)
{
window.toroll = toroll;
}
var clearfixroll = function()
{
window.toroll = "";
}
var preload = ["img/digit1.png",
"img/digit2.png",
"img/digit3.png",
"img/digit4.png",
"img/digit5.png",
"img/digit6.png",
"img/grass.png",
"img/snake1.png",
"img/snake2.png",
"img/snakes/ludoSnake1.png",
"img/snakes/ludoSnake2.png",
"img/snakes/ludoSnake3.png",
"img/snakes/ludoSnake4.png",
"img/snakes/ludoSnake5.png",
"img/snakes/ludoSnake6.png",
"img/snakes/ludoSnake7.png",
"img/snakes/ludoSnake8.png",
"img/snakes/ludoSnake8.png",
"img/snakes/ludoSnake9.png",
"img/snakes/ludoSnake10.png",
"img/snakes/ludoSnake11.png",
"img/snakes/ludoSnake12.png",
"img/snakes/ludoSnake13.png",
"img/snakes/ludoSnake14.png",
"img/snakes/ludoSnake15.png",
"img/snakes/ludoSnake16.png"];
var promises = [];
for (var i = 0; i < preload.length; i++) {
(function(url, promise) {
var img = new Image();
img.onload = function() {
promise.resolve();
};
img.src = url;
})(preload[i], promises[i] = $.Deferred());
}
$(document).ready(function() {
$.when.apply($, promises).done(function() {
$('body').addClass('done');
});
}); |
var path = require('path');
var webpack = require('webpack');
var env = process.env.NODE_ENV;
var config = {
entry: [
'./src/oms.coffee'
],
plugins: [
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(env)
})
],
output: {
path: path.join(__dirname, 'dist'),
publicPath: '/dist/',
filename: 'oms.js',
library: 'OverlappingMarkerSpiderfier',
libraryTarget: 'umd',
},
module: {
loaders: [
{
test: /\.coffee$/,
loader: 'coffee',
exclude: /node_modules/,
include: __dirname,
}
]
}
};
if (env === 'production') {
config.plugins.push(
new webpack.optimize.UglifyJsPlugin({
compressor: {
pure_getters: true,
screw_ie8: true,
warnings: false,
}
})
);
config.output.filename = 'oms.min.js';
} else {
config.plugins.push(
new webpack.HotModuleReplacementPlugin()
);
config.entry.unshift(
'webpack-dev-server/client?http://localhost:3000',
'webpack/hot/dev-server'
);
}
module.exports = config;
|
import React from "react";
import styled, { css } from "styled-components";
import { Menu } from "antd";
function Header(props) {
return (
<HeaderContainer HeaderPosition={props.HeaderPosition}>
<div style={{ width: "80%", height: "100%", margin: "0 auto" }}>
<Menu
selectedKeys={props.ScrollPosition}
mode="horizontal"
theme={props.HeaderPosition ? "light" : "dark"}
>
<Menu.Item key="home" onClick={() => props.onClickMenu("Home")}>
Home
</Menu.Item>
<Menu.Item
key="aboutMe"
onClick={() => props.onClickMenu("About Me")}
>
About Me
</Menu.Item>
<Menu.Item key="skills" onClick={() => props.onClickMenu("Skills")}>
Skills
</Menu.Item>
<Menu.Item
key="projects"
onClick={() => props.onClickMenu("Projects")}
>
Projects
</Menu.Item>
</Menu>
</div>
</HeaderContainer>
);
}
const HeaderContainer = styled.div`
width: 100%;
margin-bottom: 0px;
z-index: 1;
background-color: rgb(0, 21, 41);
transition: background-color 200ms;
${(props) =>
props.HeaderPosition
? css`
position: fixed;
top: 0;
background-color: #ffffff;
`
: css`
position: absolute;
bottom: 0;
background-color: rgb(0, 21, 41);
`}
`;
export default Header;
|
const db = require('../db/dbhelper')
const ObjectID = require('mongodb').ObjectID;
module.exports = {
reg(app){
app.get('/stores',async (req,res) => {
let result = await db.select('goodslist');
res.send(result)
}),
app.post('/delPro',async (req,res) => {
let proId = req.body.pId*1
console.log('pId:',proId)
let result = await db.remove('goodslist',{'id':proId});
res.send(result)
}),
app.post('/updatePro',async (req,res) => {
let proId = req.body.id*1
let data = {
id:proId,
name:req.body.name,
price:req.body.price*1,
sell:req.body.sell*1,
classify:req.body.classify,
brand:req.body.brand,
type:req.body.type,
img:req.body.img
}
console.log(data)
let result = await db.update('goodslist',{'id':proId},{$set:data});
res.send(result)
}),
app.post('/insertPro',async (req,res) => {
let proId = req.body.id*1
let data = {
id:proId,
name:req.body.name,
price:req.body.price*1,
sell:req.body.sell*1,
classify:req.body.classify,
brand:req.body.brand,
type:req.body.type,
img:req.body.img
}
console.log(data)
let result = await db.insert('goodslist',data);
res.send(result)
})
}
}
|
import {isoDateFormat} from '../utils';
const craetePathPointContainerElement = (pathPoint, dayCounter) => {
const {pathPointStartDateTime} = pathPoint;
return (`
<li class="trip-days__item day">
<div class="day__info">
<span class="day__counter">${dayCounter}</span>
<time class="day__date" datetime=${isoDateFormat(pathPointStartDateTime)}>${pathPointStartDateTime.toLocaleString(`en-US`, {month: `short`})} ${pathPointStartDateTime.getDate()}</time>
</div>
<ul class="trip-events__list">
</ul>
</li>
`);
};
const createPathPointContainerTemplate = () => {
return (
`<ul class="trip-days">
</ul>`
);
};
export {createPathPointContainerTemplate, craetePathPointContainerElement};
|
// write a function, that given a list of fodmaps and a string containing a list of ingredients seperated by a comma, determines whether the recipe has any high fodmap ingredients
const sampleRecipe = "garlic, potatoes, cherries, butter"
const sampleFodmaps = ["garlic", "onion", "milk"]
function recipeChecker(recipe, fodmaps) {
// convert our recipe to a list of words
// Check each ingredient in our recipe to see if it's a fodmap
const recipeArr = recipe.split(',');
for (let i = 0; i < recipeArr.length; i++) {
if (fodmaps.includes(recipeArr[i])) {
console.log(recipeArr[i]);
}
}
}
function checkTextBoxRecipe() {
const recipeInput = document.getElementById('recipeInput').value;
recipeChecker(recipeInput, sampleFodmaps)
}
const submitButton = document.getElementById("submit").onclick = checkTextBoxRecipe
|
const passport = require('passport');
const local_strategy = require('passport-local').Strategy;
const bcrypt = require('bcrypt');
const User = require('../models/user');
module.exports = () => {
passport.use(new local_strategy({
usernameField: 'id',
passwordField: 'passwd',
}, async(id, passwd, done) => {
try{
const ex_user = await User.findOne({
where: {name: id},
});
if(ex_user){
const result = await bcrypt.compare(passwd, ex_user.passwd);
result ? done(null, ex_user) : done(null, false, {message: 'wrong password'});
}
else{
done(null, false, {message: 'Did not signup yet'});
}
}
catch(err){
console.error(err);
done(err);
}
}));
}; |
let questionContainer = document.querySelector('.question');
let answerContainers = document.querySelectorAll('.answer');
let questionNumberContainer = document.querySelector('.questionNumber');
const time = 32000;
const category = 0;
let questionNumber = 0;
let questionsNumbers = new Array(5);
let questionTimeout;
let questionInterval;
let points = 0;
var asking = false;
window.onload = function() {
fadeIn("#quizContainer");
document.querySelector('.mitologia').addEventListener('click', function() {
display('.gameContainer');
randomQuestions(data[category].questions.length);
setEvents();
setQuestion(questionsNumbers[questionNumber]);
});
document.querySelector('.dodaj').addEventListener('click', function() {
display(".addContainer");
});
document.getElementById('add').addEventListener('click', add);
}
function setQuestion(id) {
asking = true;
var date = new Date();
var bar = document.querySelector('.bar');
var left = 30;
questionInterval = setInterval(function() {
document.querySelector('.timeLeft').innerHTML = left-- + "s";
var newDate = new Date();
bar.style.width = 100 - (newDate.getTime() - date.getTime())/300 + "%";
}, 1000);
document.querySelector('.photoContainer').style.backgroundImage = "url(" + data[category].questions[id].image + ")";
document.querySelector('.backgroundPhoto').style.backgroundImage = "url(" + data[category].questions[id].image + ")";
questionNumberContainer.innerHTML = questionNumber + 1;
questionContainer.innerHTML = data[category].questions[id].question + ":";
document.querySelector('.category').querySelector('span').innerHTML = data[category].category;
let index = 0;
answerContainers.forEach(answerContainer => {
answerContainer.innerHTML = data[category].questions[id].answers[index++];
});
questionTimeout = setTimeout(function() {
clearInterval(questionInterval);
checkAnswer(1);
}, time);
}
function setEvents() {
answerContainers.forEach(answer => answer.addEventListener('click', function() {
if(asking) {
clearTimeout(questionTimeout);
clearInterval(questionInterval);
checkAnswer(answer.dataset.number, this);
}
}));
}
function checkAnswer(answer, element = null) {
asking = false;
if(element) {
if(answer == data[category].questions[questionsNumbers[questionNumber]].correct) {
element.classList.add('right');
points++;
} else {
element.classList.add('wrong');
}
}
setTimeout(function() {
if(element) {
element.classList.remove('wrong');
element.classList.remove('right');
}
if(questionNumber<4) {
setQuestion(questionsNumbers[++questionNumber]);
} else {
setResults();
}
}, 1000);
}
function setResults() {
document.querySelector('.photoContainer').style.backgroundImage = "url(" + data[category].image + ")";
document.querySelector('.backgroundPhoto').style.backgroundImage = "url(" + data[category].image + ")";
document.querySelector('.bigText').innerHTML = "Wyniki!";
questionContainer.innerHTML = "Zdobyłeś " + points + "/5 punktów!";
let index = 0;
answerContainers.forEach(answerContainer => {
if(index == 0)
answerContainer.innerHTML = "Gratulujemy i życzymy powodzenia w dalszych grach!";
else
answerContainer.innerHTML = "";
index++;
});
}
function randomQuestions(maxNumber) {
for(let i=0;i<5;++i) {
var is = false;
while(!is) {
var od = true;
var number = parseInt(Math.random()*maxNumber);
for(var j=0; j<i; ++j) {
if(number === questionsNumbers[j]) {
od = false;
}
}
if(od) {
is = true;
}
}
questionsNumbers[i] = number;
}
}
function fadeIn(element) {
document.querySelector(element).style.top = "50vh";
setTimeout(function() {
document.querySelector(element).style.opacity = "1";
}, 600);
}
function add() {
let src = document.querySelector('.photoSrc').value;
let categories = document.getElementById("categories");
var selectedCategory = categories.options[categories.selectedIndex].value;
let newAnswers = document.querySelectorAll('.newAnswer');
console.log(newAnswers);
let newQuestion;
if(!src) src = data[selectedCategory].image;
newQuestion = {
"image":src,
"question":document.querySelector('.newQuestion').querySelector('input').value,
"answers":[
newAnswers[0].querySelector('input').value,
newAnswers[1].querySelector('input').value,
newAnswers[2].querySelector('input').value,
newAnswers[3].querySelector('input').value
],
};
console.log(newQuestion);
data[selectedCategory].questions.push(newQuestion);
console.log(JSON.stringify(data));
display(".menuContainer");
}
function display(container) {
document.querySelector('.addContainer').style.display = "none";
document.querySelector('.menuContainer').style.display = "none";
document.querySelector('.gameContainer').style.display = "none";
document.querySelector(container).style.display = "block";
}
const data = [
{
"id":"0",
"category":"Mitologia",
"image":"./images/mithology.jpg",
"questions":[
{
"image":"./images/wings.jpg",
"question":"Bóg uważany za boga nieba i boga wszystkich bogów to",
"answers":[
"Afrodyta",
"Posejdon",
"Zeus",
"Hades"
],
"correct":"2",
"added":"09.06.2018",
"author":"Eryk Sikora"
},
{
"image":"http://st3.ancientfacts.net/wp-content/uploads/2016/01/greek-gods-e1453392568100.jpg",
"question":"Rodzeństwo Zeusa to",
"answers":[
"Apollo, Gaja, Demeter",
"Posejdon, Hera, Demeter, Atena",
"Posejdon, Demeter, Hades, Apollo",
"Posejdon, Hera, Demeter, Hades"
],
"correct":"3",
"added":"09.06.2018",
"author":"Eryk Sikora"
},
{
"image":"./images/heaven.jpg",
"question":"Jak powstał świat wg mitów greckich",
"answers":[
"Na początku był chaos, a z chaosu wyłoniła się Gaja i Uranos",
"Na początku było niebo, a z nieba wyłoniła się Gaja, a niebem był Uranos",
"Powstał z potęgi Zeusa",
"Brak informacji"
],
"correct":"0",
"added":"09.06.2018",
"author":"Eryk Sikora"
},
{
"image":"./images/afrodyta.png",
"question":"Jak nazywał się bóg/bogini sztuki i piękna",
"answers":[
"Afrodyta",
"Hermes",
"Apollo",
"Hades"
],
"correct":"2",
"added":"09.06.2018",
"author":"Eryk Sikora"
},
{
"image":"./images/hercules.jpg",
"question":"Najtrudniejsze zadanie Herkulesa to",
"answers":[
"Stajnia Augiasza",
"Wielogłowa Hydra",
"Złote jabłka z ogrodu",
"..."
],
"correct":"1",
"added":"09.06.2018",
"author":"Eryk Sikora"
},
{
"image":"./images/nymphes.jpg",
"question":"Jak nazywał się młodzieniec, który zmarł z tęsknoty za własnym odbiciem",
"answers":[
"Bratek",
"Hermes",
"Narcyz",
"Augiasz"
],
"correct":"2",
"added":"09.06.2018",
"author":"Eryk Sikora"
},
{
"image":"http://4.bp.blogspot.com/-KIZj764TnWM/VVCcjlOPaoI/AAAAAAAACt0/sECmu9DJDwc/s1600/Hand%2Bpainted%2B01grreek.jpg",
"question":"Widniejąca na zdjęciu królewna kreteńska, córka króla Katreusa to",
"answers":[
"Aerope",
"Afrodyta",
"Gaja",
"Agamemnon"
],
"correct":"0",
"added":"09.06.2018",
"author":"Eryk Sikora"
},
{
"image":"https://www.ancient.eu/uploads/images/4130.jpg?v=1485681486",
"question":"Zeus, by zostać królem greckich bogów, musiał zabić swojego tatę",
"answers":[
"Uranosa",
"Kronosa",
"Promoeteusza",
"Atlasa"
],
"correct":"1",
"added":"05.07.2018",
"author":"Eryk Sikora"
},
{
"image":"http://static.t13.cl/images/sizes/1200x675/1467786289-90301721carracci-jupiteretjunon.jpg",
"question":"Jaki ptak kojarzony jest z Herą",
"answers":[
"Sokół",
"Sikorka",
"Słowik",
"Paw"
],
"correct":"3",
"added":"06.07.2018",
"author":"Eryk Sikora"
},
{
"image":"http://www.4enoch.org/wiki4/images/3/37/Muses.jpg",
"question":"Czyimi córkami były muzy Apollina",
"answers":[
"Posejdona i Meduzy",
"Apollina i Tyche",
"Dzeusa i Mnemosyne",
"Apollinai Dafne"
],
"correct":"2",
"added":"06.07.2018",
"author":"Eryk Sikora"
}
]
}
] |
/**
*
*/
function insereForm(controller){
var control = 'controller/'+controller+'Controller.php';
var dados = $('#formRsenha').serialize();
$.post(control, dados, function(response){
var result = response
if (result.match(/Enviado.*/)) {
//limpar os campos
$('#formRsenha input').each(function(){
$(this).val('');
});
//limpando a mensagem anterior
$("#mensagemok").empty();
//exibe alert
$("#mensagemok").css("display","block");
//exibe mensaagem
$("#mensagemok").append(result);
//oculta alert erro
$("#mensagemerror").css("display","none");
}else{
//oculta a mensagem de ok
$("#mensagemok").css("display","none");
//limpando a mensagem anterior
$("#mensagemerror").empty();
//carrega informações na tela
$("#mensagemerror").append(result);
//exibe alert
$("#mensagemerror").css("display","block");
//apos 3 segundos oculta alerta
setTimeout(function(){$("#mensagemerror").css("display","none");}, 5000);
}
});
};
|
import React, { useState, useEffect } from 'react';
import { Container, Button, Jumbotron, Form, FormGroup, FormControl, FormLabel } from 'react-bootstrap';
function WhatsNext({ updateStep, two, updateTwo}) {
useEffect(() => {
updateStep(2);
})
function changeTwo(newTwo) {
var str = newTwo.toString();
window.localStorage.setItem("two", str);
updateTwo(str)
}
return (
<div className="Progress">
<Container>
<Jumbotron>
<h1 className="question">What are you going to work on next?</h1>
<br className="my-3" />
<form>
<Form.Control size="lg" type="text" placeholder={two} onChange={(e) => changeTwo(e.target.value)}/>
</form>
<br className="my-3" />
<p>
{/* <Button variant="primary" size="lg" href="/help" id="submit">Next -></Button> */}
<a href="/help"><div className="button_1 button_2">Next</div></a>
</p>
</Jumbotron>
</Container>
</div>
);
}
export default WhatsNext; |
/**
* @Copyright (c) 2019-present, Zabo & Modular, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* @description: Zabo account-related functions
*/
'use strict'
const { SDKError } = require('../err')
/**
* @typedef {{
* data?: [import('./users').Balance]
* request_id?: String
* }} GetAccountBalancesResp
*/
/**
* Accounts API.
*/
class Accounts {
constructor (api) {
/** @private */
this.api = api
this.id = null
this.data = null
}
/**
* @private
*/
_setAccount (account) {
this.id = account.id
this.data = account
}
async get () {
try {
const response = await this.api.request('GET', '/sessions')
this._setAccount(response)
return this.data
} catch (err) {
throw new SDKError(err.error_type, err.message, err.request_id)
}
}
async create ({ clientId, credentials, provider, origin } = {}) {
if (!clientId) {
throw new SDKError(
400,
`[Zabo] Unable to connect with the Zabo API. Make sure you have registered your app at https://zabo.com and that you entered a valid 'clientId' value.
More details at: https://zabo.com/docs`
)
}
const data = {
client_id: clientId,
provider_name: provider,
credentials,
origin
}
try {
const account = await this.api.request('POST', '/accounts', data)
this._setAccount(account)
return account
} catch (err) {
throw new SDKError(err.error_type, err.message, err.request_id)
}
}
/**
* Returns the user balances for the requested currencies. When requesting balances from the client,
* the request should be made in the context of the connected account. When requesting from an
* application server, requests should be made in the context of a user. See documentation about
* users. Cryptocurrencies available to your app can be queried. If no currencies are specified,
* then all available currencies will be returned.
* @param {{
* tickers?: [String]
* }} param0 Request parameters.
* @returns {Promise<GetAccountBalancesResp>} API response.
*/
async getBalances ({ tickers } = {}) {
if (!this.id) {
throw new SDKError(401, '[Zabo] Account not yet connected. See: https://zabo.com/docs#connecting-a-user')
}
let url = `/accounts/${this.id}/balances`
if (tickers) {
if (Array.isArray(tickers)) {
tickers = tickers.join(',')
}
url = `${url}?tickers=${tickers}`
}
try {
return this.api.request('GET', url)
} catch (err) {
throw new SDKError(err.error_type, err.message, err.request_id)
}
}
/**
* This endpoint will create and return a deposit address for the specified account.
* If the currency is not supported by the connected provider, you will receive an 'unsupported' error.
* See Unsupported Functions for more information.
* @param {String} ticker Three-letter identifier for the currency this deposit address should be used for.
* @returns {Promise<import('./users').CreateDepositAddressResp>} API response.
*/
async createDepositAddress (ticker) {
if (!this.id) {
throw new SDKError(401, '[Zabo] Account not yet connected. See: https://zabo.com/docs#connecting-a-user')
} else if (!ticker || typeof ticker !== 'string') {
throw new SDKError(400, '[Zabo] Missing or invalid `ticker` parameter. See: https://zabo.com/docs#create-a-deposit-address')
}
const providersWithStaticDepositAddresses = [
'metamask',
'ledger',
'hedera',
'address-only',
'binance'
]
for (const provider of providersWithStaticDepositAddresses) {
if (provider === this.data.provider.name) {
console.warn(`[Zabo] Provider '${provider}' does not support dynamic address generation. Fallbacking to accounts.getDepositAddresses()... More details: https://zabo.com/docs#get-deposit-addresses`)
return this.getDepositAddresses(ticker)
}
}
try {
return this.api.request('POST', `/accounts/${this.id}/deposit-addresses?ticker=${ticker}`)
} catch (err) {
throw new SDKError(err.error_type, err.message, err.request_id)
}
}
/**
* This endpoint will retrieve all deposit addresses for the specified account.
* If the currency is not supported by the connected provider, you will receive
* an 'unsupported' error. See Unsupported Functions for more information.
* @param {String} ticker Three-letter identifier for the currency this deposit address should be used for.
* @returns {Promise<import('./users').GetDepositAddressesResp>}
*/
async getDepositAddresses (ticker) {
if (!this.id) {
throw new SDKError(401, '[Zabo] Account not yet connected. See: https://zabo.com/docs#connecting-a-user')
} else if (!ticker || typeof ticker !== 'string') {
throw new SDKError(400, '[Zabo] Invalid `ticker` parameter. See: https://zabo.com/docs#get-deposit-addresses')
}
try {
return this.api.request('GET', `/accounts/${this.id}/deposit-addresses?ticker=${ticker}`)
} catch (err) {
throw new SDKError(err.error_type, err.message, err.request_id)
}
}
}
/**
* @typedef {Accounts} AccountsAPI
* @type {(api) => AccountsAPI}
*/
module.exports = (api) => {
return new Accounts(api)
}
|
function makeSteps(count)
{
const steps = [];
steps.push(new BenchmarkTestStep('Adding classes', (bench, contentWindow, contentDocument) => {
bench.addClasses(100);
}));
steps.push(new BenchmarkTestStep('Removing classes', (bench, contentWindow, contentDocument) => {
bench.removeClasses(100);
}));
steps.push(new BenchmarkTestStep('Adding leaf elements', (bench, contentWindow, contentDocument) => {
bench.addLeafElements(100);
}));
steps.push(new BenchmarkTestStep('Removing leaf elements', (bench, contentWindow, contentDocument) => {
bench.removeLeafElements(100);
}));
return steps;
}
function makeSuite(configuration)
{
return {
name: configuration.name,
url: 'style-bench.html',
prepare: (runner, contentWindow, contentDocument) => {
return runner.waitForElement('#testroot').then((element) => {
return contentWindow.createBenchmark(configuration);
});
},
tests: makeSteps(),
};
}
var Suites = [];
for (const configuration of StyleBench.predefinedConfigurations())
Suites.push(makeSuite(configuration));
|
// import FaviconsWebpackPlugin from 'favicons-webpack-plugin';
const webpack = require('webpack');
const path = require('path');
// import StyleLintPlugin from 'stylelint-webpack-plugin';
module.exports = {
context: path.join(__dirname, '/src'),
devtool: 'source-map',
entry: {
app: ['./scripts/main.js']
},
output: {
// publicPath: '',
filename: 'assets/scripts/[name].bundle.js',
path: path.join(__dirname, './build')
},
plugins: [
// new webpack.optimize.CommonsChunkPlugin({
// name: 'common',
// filename: 'assets/scripts/common.js',
// minChunks: 2
// }),
// new webpack.ProvidePlugin({
// $: 'jquery',
// jQuery: 'jquery',
// 'window.jQuery': 'jquery'
// }),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
},
sourceMap: true
}),
new webpack.DefinePlugin({
//CDN: JSON.stringify('https://ad.csdnevnik.ru/special/staging/riff/assets/')
//https://ad.csdnevnik.ru/special/staging/panini/assets/
CDN: JSON.stringify('http://localhost:300/assets/')
})
// new StyleLintPlugin({
// configFile: './.stylelintrc',
// })
// new FaviconsWebpackPlugin('./favicon.png')
],
module: {
rules: [
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: ['babel-loader']
},
// {
// test: /\.js$/,
// enforce: "pre",
// exclude: /(node_modules|bower_components)/,
// loader: "eslint-loader",
// options: {
// fix: true
// }
// },
]
}
};
|
import React, { Component } from 'react';
import scss from './TrafficTable.module.scss';
import classNames from 'classnames';
import update from 'immutability-helper';
import TrafficHeader from './TableHeader/TableHeader';
import TableBody from './TableBody/TableBody';
import ErrorBoundary from '../../../components/ErrorBoundary/ErrorBoundary';
class TrafficTable extends Component {
state = {
headers: this.props.headers,
rows: this.props.rows,
totalColumns: this.props.headers.length,
prevX: 0,
tableContainerWidth: 0,
ttlPub: 0,
ttlPla: 0,
ttlCre: 0
};
componentDidMount() {
let ttlWidth = 0;
this.state.headers.forEach(header => {
ttlWidth = ttlWidth + header.width + 2;
});
let tblWinWidth = document.getElementById('tableWindow').offsetWidth;
if(tblWinWidth - 36 < ttlWidth) {
this.setState({tableContainerWidth:ttlWidth});
}
// update container width based on headers
}
handleHeaderDragStart = (event, col, index) => {
this.setState({prevX:event.pageX});
}
handleHeaderDragStop = (event, col, index) => {
let width = event.pageX - this.state.prevX;
let updatedHeaders = [...this.state.headers];
width = updatedHeaders[index].width + width;
updatedHeaders[index].width = width <= 20 ? 20 : width;
let ttlWidth = 0;
this.state.headers.forEach(header => {
ttlWidth = ttlWidth + header.width + 2;
});
this.setState({headers:updatedHeaders, tableContainerWidth: ttlWidth});
}
handleLevel1Click = (lvl1Index) => {
let ttlPub = this.state.ttlPub;
let ttlPla = this.state.ttlPla;
let ttlCre = this.state.ttlCre;
let maxPub = document.getElementsByClassName('column0').length;
let maxPla = document.getElementsByClassName('column1').length;
let maxCre = document.getElementsByClassName('column4').length;
let onePlacementIsSelected = this.state.rows[lvl1Index].placements.some(obj => {
return obj.selected === true;
});
let oneGenericIsSelected = false;
for(let i=0; i<this.state.rows[lvl1Index].placements.length; i++) {
if (
this.state.rows[lvl1Index].placements[i].generics.some(obj => {
return obj.selected === true;
})
) {
oneGenericIsSelected = true;
break;
}
};
let newRows = [];
if(this.state.rows[lvl1Index].selected) {
//Unselect placements and generics, and self
if(oneGenericIsSelected) {
newRows = update(this.state.rows,{
[lvl1Index]: oneDeep => update(oneDeep, {
placements: {$apply: placements => { return placements.map(pla => {
let newPla = {...pla};
newPla.generics = newPla.generics.map(cre => {let newCre = {...cre}; newCre.selected = false; if(cre.selected)ttlCre = ttlCre - 1; return newCre;});
return newPla;
});} }
})
});
} else if(onePlacementIsSelected) {
newRows = update(this.state.rows,{
[lvl1Index]: oneDeep => update(oneDeep, {
placements: {$apply: placements => { return placements.map(pla => {let newPla = {...pla}; newPla.selected = false; if(pla.selected)ttlPla = ttlPla - 1; return newPla;});} }
})
});
} else {
newRows = update(this.state.rows,{
[lvl1Index]: oneDeep => update(oneDeep, {
selected: {$set: false}
})
});
ttlPub = ttlPub - 1;
}
} else {
newRows = update(this.state.rows,{
[lvl1Index]: oneDeep => update(oneDeep, {
selected: {$set: true},
placements: {$apply: placements => { return placements.map(pla => {
let newPla = {...pla};
newPla.generics = newPla.generics.map(cre => {let newCre = {...cre}; newCre.selected = true; if(ttlCre < maxCre && !cre.selected)ttlCre = ttlCre + 1; return newCre;});
newPla.selected = true;
if(ttlPla < maxPla && !pla.selected)ttlPla = ttlPla + 1;
return newPla;
});} }
})
});
if(ttlPub < maxPub)ttlPub = ttlPub + 1;
}
this.setState({rows:newRows, ttlPub, ttlPla, ttlCre});
};
handleLevel2Click = (lvl1Index, lvl2Index) => {
let ttlPla = this.state.ttlPla;
let ttlCre = this.state.ttlCre;
let maxPla = document.getElementsByClassName('column1').length;
let maxCre = document.getElementsByClassName('column4').length;
let oneGenericIsSelected = this.state.rows[lvl1Index].placements[lvl2Index].generics.some(obj => {
return obj.selected === true;
});
let newRows = [];
if(this.state.rows[lvl1Index].placements[lvl2Index].selected) {
//Unselect placements and generics
if(oneGenericIsSelected) {
newRows = update(this.state.rows,{
[lvl1Index]: oneDeep => update(oneDeep, {
placements: placements => update(placements,{
[lvl2Index]: twoDeep => update(twoDeep, {
generics: {$apply: generics => { return generics.map(cre => {let newCre = {...cre}; newCre.selected = false; if(cre.selected)ttlCre = ttlCre - 1; return newCre;});} }
})
})
})
});
} else {
newRows = update(this.state.rows,{
[lvl1Index]: oneDeep => update(oneDeep, {
placements: placements => update(placements,{
[lvl2Index]: twoDeep => update(twoDeep, {
selected: {$set: false}
})
})
})
});
ttlPla = ttlPla - 1;
}
} else {
newRows = update(this.state.rows,{
[lvl1Index]: oneDeep => update(oneDeep, {
placements: placements => update(placements,{
[lvl2Index]: twoDeep => update(twoDeep, {
selected: {$set: true},
generics: {$apply: generics => { return generics.map(cre => {let newCre = {...cre}; newCre.selected = true; if(ttlCre < maxCre && !cre.selected) ttlCre = ttlCre + 1; return newCre;});} }
})
})
})
});
if(ttlPla < maxPla) ttlPla = ttlPla + 1;
}
this.setState({rows:newRows, ttlPla, ttlCre});
};
handleLevel3Click = (lvl1Index, lvl2Index, lvl3Index) => {
let ttlCre = this.state.ttlCre;
let maxCre = document.getElementsByClassName('column4').length;
let newRows = update(this.state.rows,{
[lvl1Index]: oneDeep => update(oneDeep, {
placements: placements => update(placements,{
[lvl2Index]: twoDeep => update(twoDeep, {
generics: generics=> update(generics,{
[lvl3Index]: threeDeep => update(threeDeep,{
selected: {$apply: orig => {return !orig;}}
})
})
})
})
})
});
let isSelected = newRows[lvl1Index].placements[lvl2Index].generics[lvl3Index].selected;
if(isSelected && this.state.ttlCre < maxCre)
ttlCre = ttlCre + 1;
else if(!isSelected) ttlCre = ttlCre - 1;
this.setState({rows:newRows, ttlCre});
};
level1HeaderClick = () => {
let ttlPub = 0;
let ttlPla = 0;
let ttlCre = 0;
let maxPub = document.getElementsByClassName('column0').length;
let maxPla = document.getElementsByClassName('column1').length;
let maxCre = document.getElementsByClassName('column4').length;
let newRows;
if(this.state.ttlPub === maxPub) {
//remove all
newRows= update(this.state.rows,{
$apply: products => {
return products.map(pub => {
let newPub = {...pub};
newPub.selected = false;
newPub.placements = newPub.placements.map(pla => {
let newPla = {...pla};
newPla.generics = newPla.generics.map(cre => {let newCre = {...cre}; newCre.selected = false; return newCre;});
newPla.selected = false;
return newPla;
});
return newPub;
});
}
});
} else {
//add all
newRows= update(this.state.rows,{
$apply: products => {
return products.map(pub => {
let newPub = {...pub};
newPub.selected = true;
newPub.placements = newPub.placements.map(pla => {
let newPla = {...pla};
newPla.generics = newPla.generics.map(cre => {let newCre = {...cre}; newCre.selected = true; ttlCre = ttlCre + 1; return newCre;});
newPla.selected = true;
ttlPla = ttlPla + 1;
return newPla;
});
ttlPub = ttlPub + 1;
return newPub;
});
}
});
}
this.setState({rows:newRows, ttlPub,ttlPla,ttlCre});
}
level2HeaderClick = () => {
let ttlPub = 0;
let ttlPla = 0;
let ttlCre = 0;
let maxCre = document.getElementsByClassName('column4').length;
let maxPla = document.getElementsByClassName('column1').length;
let newRows;
if(this.state.ttlPub <= 0 && this.state.ttlPla === maxPla && this.state.ttlCre === maxCre) {
// remove generics
newRows = update(this.state.rows,{
$apply: products => {
return products.map(pub => {
let newPub = {...pub};
newPub.selected = false;
newPub.placements = newPub.placements.map(pla => {
let newPla = {...pla};
newPla.generics = newPla.generics.map(cre => {let newCre = {...cre}; newCre.selected = false; return newCre;});
newPla.selected = true;
ttlPla = ttlPla + 1;
return newPla;
});
return newPub;
});
}
});
} else if (this.state.ttlPub <= 0 && this.state.ttlPla === maxPla && this.state.ttlCre <= 0) {
//remove placements
newRows = update(this.state.rows,{
$apply: products => {
return products.map(pub => {
let newPub = {...pub};
newPub.selected = false;
newPub.placements = newPub.placements.map(pla => {
let newPla = {...pla};
newPla.generics = newPla.generics.map(cre => {let newCre = {...cre}; newCre.selected = false; return newCre;});
newPla.selected = false;
return newPla;
});
return newPub;
});
}
});
} else {
//remove Products and add all placements and generics
newRows = update(this.state.rows,{
$apply: products => {
return products.map(pub => {
let newPub = {...pub};
newPub.selected = false;
newPub.placements = newPub.placements.map(pla => {
let newPla = {...pla};
newPla.generics = newPla.generics.map(cre => {let newCre = {...cre}; newCre.selected = true; ttlCre = ttlCre + 1; return newCre;});
newPla.selected = true;
ttlPla = ttlPla + 1;
return newPla;
});
return newPub;
});
}
});
}
this.setState({rows:newRows, ttlPub,ttlPla,ttlCre});
}
level3HeaderClick = () => {
let ttlPub = 0;
let ttlPla = 0;
let ttlCre = 0;
let maxCre = document.getElementsByClassName('column4').length;
let newRows;
if(this.state.ttlPub <= 0 && this.state.ttlPla <= 0 && this.state.ttlCre === maxCre) {
//remove generics
newRows = update(this.state.rows,{
$apply: products => {
return products.map(pub => {
let newPub = {...pub};
newPub.selected = false;
newPub.placements = newPub.placements.map(pla => {
let newPla = {...pla};
newPla.generics = newPla.generics.map(cre => {let newCre = {...cre}; newCre.selected = false; return newCre;});
newPla.selected = false;
return newPla;
});
return newPub;
});
}
});
} else {
// set all generics, rest remove
newRows = update(this.state.rows,{
$apply: products => {
return products.map(pub => {
let newPub = {...pub};
newPub.selected = false;
newPub.placements = newPub.placements.map(pla => {
let newPla = {...pla};
newPla.generics = newPla.generics.map(cre => {let newCre = {...cre}; newCre.selected = true; ttlCre = ttlCre + 1; return newCre;});
newPla.selected = false;
return newPla;
});
return newPub;
});
}
});
}
this.setState({rows:newRows, ttlPub,ttlPla,ttlCre});
}
render () {
return (
<React.Fragment>
<p className={scss.title}>CUSTOM TABLE</p>
<div id='tableWindow' className={classNames(scss.trafficTableWindow)}>
<ErrorBoundary>
<div id='TrafficTableContainer' className={scss.TrafficTableContainer} style={this.state.tableContainerWidth > 0 ? {width:this.state.tableContainerWidth}:null}>
<TrafficHeader
headers={this.state.headers}
totalColumns={this.state.totalColumns}
handleHeaderDragStart = {this.handleHeaderDragStart}
handleHeaderDragStop = {this.handleHeaderDragStop}
level1HeaderClick = {this.level1HeaderClick}
level2HeaderClick = {this.level2HeaderClick}
level3HeaderClick = {this.level3HeaderClick}
ttlPub = {this.state.ttlPub}
ttlPla = {this.state.ttlPla}
ttlCre = {this.state.ttlCre}
/>
<TableBody
headers={this.state.headers}
rows={this.state.rows}
handleLevel3Click = {this.handleLevel3Click}
handleLevel2Click = {this.handleLevel2Click}
handleLevel1Click = {this.handleLevel1Click}
/>
</div>
</ErrorBoundary>
</div>
</React.Fragment>
)
}
}
export default TrafficTable; |
import React from "react";
import { Route } from "react-router-dom";
import App from "./components/App";
import About from "./components/About";
import Sq from "./components/Sq";
import ProPage from "./components/pro/ProPage";
export default [
<Route key="app" exact path="/" component={App} />,
<Route key="sq" exact path="/sq" component={Sq} />,
<Route key="sqpro" path="/sq/pro" component={ProPage} />,
<Route key="about" exact path="/about" component={About} />
];
|
import omit from "lodash.omit";
import omitBy from "lodash.omitby";
import traverse from "./traverse";
import print from "./printers";
function getType({ type }) {
if (type instanceof Function) {
return type.name.toLowerCase();
}
if (typeof type === "string") {
return type.toLowerCase();
}
return typeof type;
}
function cleanSvgProps(node, props) {
const type = getType(node);
return type === "path" || type === "polygon" || type === "svg"
? omit(props, ["d", "path", "points", "viewBox"])
: props;
}
export const minimaliseTransform = excludeProps => (
accum,
node,
props,
children
) => {
const { ...other } = props;
return {
accum,
node,
props: omitBy(
{
...cleanSvgProps(node, other)
},
excludeProps
),
children
};
};
export default excludeProps =>
traverse(print, minimaliseTransform(excludeProps));
const isEmptyObject = obj =>
obj && typeof obj === "object" && Object.keys(obj).length === 0;
export const minimalWebTransform = minimaliseTransform(
(value, key) =>
value === undefined ||
typeof value === "function" ||
isEmptyObject(value) ||
key === "dir"
);
export const minimalWeb = traverse(print, minimalWebTransform);
const redundantNativeKeys = new Set([
"accessible",
"allowFontScaling",
"className",
"ellipsizeMode",
"href"
]);
export const minimalNativeTransform = minimaliseTransform(
(value, key) =>
value === undefined ||
typeof value === "function" ||
isEmptyObject(value) ||
redundantNativeKeys.has(key)
);
export const minimalNative = traverse(print, minimalNativeTransform);
|
/*global PIFRAMES */
/* Written by Mostafa Mohammed and Cliff Shaffer */
$(document).ready(function() {
"use strict";
var av_name = "SetNotationFS";
var av = new JSAV(av_name);
var Frames = PIFRAMES.init(av_name);
// Frame 1
av.umsg("Let's review some of this notation.");
av.displayInit();
// Frame 2
av.umsg(Frames.addQuestion("braces"));
av.step();
// Frame 3
av.umsg(Frames.addQuestion("former"));
av.step();
// Frame 4
av.umsg(Frames.addQuestion("members"));
av.step();
// Frame 5
av.umsg(Frames.addQuestion("null"));
av.step();
// Frame 6
av.umsg(Frames.addQuestion("size"));
av.step();
// Frame 7
av.umsg(Frames.addQuestion("size2"));
av.step();
// Frame 8
av.umsg(Frames.addQuestion("subset"));
av.step();
// Frame 9
av.umsg(Frames.addQuestion("union"));
av.step();
// Frame 10
av.umsg(Frames.addQuestion("emptyunion"));
av.step();
// Frame 11
av.umsg(Frames.addQuestion("commute"));
av.step();
// Frame 12
av.umsg(Frames.addQuestion("intersect"));
av.step();
// Frame 13
av.umsg(Frames.addQuestion("emptyintersect"));
av.step();
// Frame 14
av.umsg(Frames.addQuestion("commuteI"));
av.step();
// Frame 15
av.umsg(Frames.addQuestion("setdiff"));
av.step();
// Frame 16
av.umsg(Frames.addQuestion("setdiff2"));
av.step();
// Frame 17
av.umsg(Frames.addQuestion("setdiffcomm"));
av.step();
// Frame 18
av.umsg(Frames.addQuestion("product"));
av.step();
// Frame 19
av.umsg(Frames.addQuestion("productsize"));
av.step();
// Frame 20
av.umsg(Frames.addQuestion("powerset"));
av.step();
// Frame 21
av.umsg(Frames.addQuestion("powersize"));
av.step();
// Frame 22
av.umsg("Congratulations! Frameset completed.");
av.recorded();
});
|
const reporteFinal = (ids) => async (dispatch) => {
const BASE_API = 'https://api.nal.usda.gov/fdc/v1/';
const API_KEY = 'api_key=xegkBOn6pSqBMY3HdPnjahRLFpJDwr48P8094pnM';
const myHeaders = new Headers();
myHeaders.append('Content-Type', 'application/json');
const requestOptions = {
method: 'GET',
headers: myHeaders,
redirect: 'follow',
};
const URLArray = ids.map((id) => (fetch(`${BASE_API}${id}?${API_KEY}`, requestOptions).then((response) => response.json())));
Promise.all(URLArray)
.then(async (data) => {
dispatch({
type: 'FINAL_REPORT',
payload: data,
});
})
.catch((error) => console.error(error.message));
};
export default reporteFinal;
|
var cantClusters = null;
var nombreClusters = ["Platos / Agudos", "Bombos / Graves", "Redoblantes / Congas / Medios altos", "Toms bajos / Medios graves", "Campanas"];
// setup fill color
var cValue = function(d) { return d.cluster;},
color = d3.scale.category10();
var tooltip;
var mostrarEspectrograma = false;
var cantPerCluster;
function doViz() {
var margin = {top: 0, right: 0, bottom: 0, left: 0},
width = $(window).width() * 0.99 - margin.left - margin.right,
// height = $(window).height() * 0.5 - margin.top - margin.bottom;
height = $("#viz").height() - $("#divMostrarEspectrograma").height() - $("#viz h1").height() * 2;
// width = 500,
// height = 300
;
// Audio
var audio = $("#audio")[0];
var DOT_SIZE = 4;
var shiftPressed = false;
$("#mostrarEspectrograma").click( function() {
mostrarEspectrograma = $(this).is(":checked");
});
//zoom
// var zoom = d3.behavior.zoom()
// .scaleExtent([1,10])
// .on("zoom", function() {
// svg.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
// })
// ;
// var drag = d3.behavior.drag()
// .origin(function(d) { return d; })
// .on("dragstart", function(d) {
// d3.event.sourceEvent.stopPropagation();
// d3.select(this).classed("dragging", true);
// })
// .on("drag", function(d) {
// d3.select(this).attr("cx", d.x = d3.event.x).attr("cy", d.y = d3.event.y);
// })
// .on("dragend", function(d) {
// d3.select(this).classed("dragging", false);
// });
/*
* value accessor - returns the value to encode for a given data object.
* scale - maps value to a visual display encoding, such as a pixel position.
* map function - maps from data value to display value
* axis - sets up axis
*/
// setup x
var xValue = function(d) { return d.x;}, // data -> value
xScale = d3.scale.linear().range([0, width]), // value -> display
xMap = function(d) { return xScale(xValue(d));}, // data -> display
xAxis = d3.svg.axis().scale(xScale).orient("bottom");
// setup y
var yValue = function(d) { return d.y;}, // data -> value
yScale = d3.scale.linear().range([height, 0]), // value -> display
yMap = function(d) { return yScale(yValue(d));}, // data -> display
yAxis = d3.svg.axis().scale(yScale).orient("left");
// add the graph canvas to the body of the webpage
var svg = d3.select("#viz .fp-tableCell").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
// .call(zoom)
;
svg.append("rect")
.attr("width", width)
.attr("height", height)
.style("fill", "none")
.style("pointer-events", "all")
;
// add the tooltip area to the webpage
tooltip = d3.select("#viz .fp-tableCell").append("div")
.attr("class", "tooltip")
.style("opacity", 0);
d3.tsv("audioClusteringResult.tsv", function(error, data) {
// change string (from CSV) into number format
var maxCluster = 0;
cantPerCluster = [];
data.forEach(function(d) {
d.x = +d.x;
d.y = +d.y;
d.cluster = +d.cluster;
if ( !cantPerCluster[d.cluster] ) {
cantPerCluster[d.cluster] = 1;
} else {
cantPerCluster[d.cluster]++;
}
if ( d.cluster > maxCluster ) {
maxCluster = d.cluster;
}
d.file = d.file.replace(".wav", ".mp3");
});
cantClusters = maxCluster;
renderClustersItems();
// don't want dots overlapping axis, so add in buffer to data domain
xScale.domain([d3.min(data, xValue)-1, d3.max(data, xValue)+1]);
yScale.domain([d3.min(data, yValue)-1, d3.max(data, yValue)+1]);
// draw dots
svg.selectAll(".dot")
.data(data)
.enter().append("circle")
.attr("class", "dot")
.attr("r", DOT_SIZE)
.attr("cx", xMap)
.attr("cy", yMap)
.attr("data-cluster", function(d) { return d.cluster })
.style("fill", function(d) { return color(cValue(d));})
.on("click", function(d) {
if ( !d3.select(this).classed("filtered") ) {
audio.src = "sounds.mp3/" + d.file;
audio.play();
d3.select(this).attr("r", DOT_SIZE * 3).transition().attr("r", DOT_SIZE);
}
})
.on("mouseover", function(d) {
d3.select(this).style("stroke", "black");
if ( mostrarEspectrograma && !d3.select(this).classed("filtered") ) {
tooltip.transition()
.duration(200)
.style("opacity", 1);
// tooltip.html("Filename:" + d.file)
tooltip.html("<div>" + d.file + "</div><img src='espectrogramas/" + data.indexOf(d) + ".png' />")
// .style("left", (d3.event.pageX + 5) + "px")
// .style("top", (d3.event.pageY - 28) + "px");
;
}
})
.on("mouseout", function(d) {
d3.select(this).style("stroke", "");
if ( mostrarEspectrograma ) {
tooltip.transition()
.duration(500)
.style("opacity", 0)
;
}
});
});
}
function filterCluster(cluster) {
$dots = $(".dot[data-cluster='" + cluster + "']");
if ( $dots.eq(0).hasClass("filtered") ) {
$dots.removeClass("filtered");
} else {
$dots.addClass("filtered");
}
}
function renderClustersItems() {
// $("body").mousedown(function(e) {
// shiftPressed = e.shiftKey;
// })
for( var i = 0 ; i <= cantClusters ; i++ ) {
var $container = $("<div class='cluster'>");
var $check = $("<input type='checkbox' />").val(i).attr("id", "chkCluster" + i).attr("checked", true);
// var $item = $("<label for='" + "chkCluster" + i + "'>").text( nombreClusters[i] + " (" + i + ")").attr("data-cluster", i);
var $item = $("<label for='" + "chkCluster" + i + "'>").text( nombreClusters[i] + " (" + cantPerCluster[i] + ")" ).attr("data-cluster", i);
$item.css("background-color", color(i));
$container.css("border-color", color(i));
$container.append($check).append($item);
$("#clusterItems").append($container);
$check.change(function() {
filterCluster ( $(this).val() );
// if ( shiftPressed ) {
// console.log("asd");
// }
});
$item.mouseover( function() {
if ( mostrarEspectrograma ) {
tooltip.transition().duration(200)
.style("opacity", 1);
tooltip.html("<img src='espectrogramasCluster/" + $(this).attr("data-cluster") + ".png' />")
}
});
$item.mouseleave( function() {
if ( mostrarEspectrograma ) {
tooltip
.transition()
.duration(500)
.style("opacity", 0)
;
}
});
}
}
|
const BaseDao = require("./base.dao");
const UserModel = require("../models/user.model");
const userDao = new BaseDao(UserModel);
async function createUser(data) {
let {_id, ...payload} = data;
let query = {};
if(_id){
query = { _id }
}
let options = {new: true, upsert: true};
const userData = await userDao.findOneAndUpdate(query, payload, options).exec();
return userData;
}
async function addUser(payload){
userData= new UserModel(payload);
return await userData.save();
}
async function getUserData(query){
const projection = {};
const userData = await userDao.findOne(query, projection).lean().exec();
return userData;
}
async function getUsersData(query){
const projection = {};
return await userDao.findMany(query, projection).lean().exec();
}
async function deleteEmployee(query){
const userData = await userDao.removeOne(query).lean().exec();
return userData;
}
module.exports = {
createUser,
getUserData,
deleteEmployee,
getUsersData,
addUser
}; |
import React, { Component, PropTypes } from 'react';
import {
View,
StyleSheet,
StatusBar,
TouchableOpacity,
Text,
} from 'react-native';
import { NavigationStyles } from '@expo/ex-navigation';
import colors from 'kolors';
import { Components, Location } from 'expo';
import ElevatedView from 'react-native-elevated-view';
import { maybeOpenURL } from 'react-native-app-link';
import connectDropdownAlert from '../utils/connectDropdownAlert';
import { phonecall } from 'react-native-communications';
import { observer } from 'mobx-react/native';
import { observable } from 'mobx';
@connectDropdownAlert
@observer
export default class MeetRiderScreen extends Component {
static route = {
navigationBar: {
visible: false,
},
styles: {
...NavigationStyles.SlideHorizontal,
},
};
static propTypes = {
navigator: PropTypes.object.isRequired,
navigation: PropTypes.object.isRequired,
pickupLocation: PropTypes.object.isRequired,
rider: PropTypes.object.isRequired,
alertWithType: PropTypes.func.isRequired,
};
@observable region;
@observable location;
componentWillMount() {
Location.watchPositionAsync(
{
enableHighAccuracy: true,
timeInterval: 1000,
distanceInterval: 1,
},
data => {
this.location = {
latitude: data.coords.latitude,
longitude: data.coords.longitude,
};
}
).then(locationSub => {
this.locationSub = locationSub;
});
}
componentWillUnmount() {
this.locationSub.remove();
}
onRegionChange = region => this.region = region;
render() {
return (
<View style={styles.container}>
<Components.MapView
ref={c => {
this.map = c;
}}
style={StyleSheet.absoluteFillObject}
initialRegion={{
latitude: this.props.pickupLocation.lat,
longitude: this.props.pickupLocation.lon,
latitudeDelta: 0.0922,
longitudeDelta: 0.0421,
}}
showsUserLocation
followsUserLocation
toolbarEnabled={false}
loadingEnabled
region={this.region}
onRegionChange={this.onRegionChange}
>
<StatusBar hidden />
<Components.MapView.Marker
title={this.props.pickupLocation.name}
coordinate={{
latitude: this.props.pickupLocation.lat,
longitude: this.props.pickupLocation.lon,
}}
onCalloutPress={() => {
const wazeUrl = `waze://?ll=${this.props.pickupLocation.lat},` +
`${this.props.pickupLocation.lon}&z=10&navigate=yes`;
maybeOpenURL(wazeUrl, {
appName: 'Waze',
appStoreId: 'id323229106',
playStoreId: 'com.waze',
}).catch(err => {
this.props.alertWithType('error', 'Error', err.toString());
});
}}
>
<ElevatedView style={styles.marker} elevation={6}>
<View style={styles.markerInner} />
</ElevatedView>
</Components.MapView.Marker>
<If condition={this.location}>
<Components.MapView.Polyline
strokeWidth={2}
strokeColor={colors.black}
geodesic
lineDashPattern={[4, 8, 4, 8]}
coordinates={[
{
latitude: this.props.pickupLocation.lat,
longitude: this.props.pickupLocation.lon,
},
this.location,
]}
/>
</If>
</Components.MapView>
<TouchableOpacity
onPress={() => this.map.animateToCoordinate({
latitude: this.props.pickupLocation.lat,
longitude: this.props.pickupLocation.lon,
})}
>
<ElevatedView style={styles.infoBox} elevation={4}>
<Text style={styles.infoBoxText}>
Pickup at the
{' '}
{this.props.pickupLocation.name.toLowerCase().trim()}
.
</Text>
</ElevatedView>
</TouchableOpacity>
<View style={styles.actionContainer}>
<View>
<Text style={styles.driverName}>
{this.props.rider.displayName.toUpperCase()}
</Text>
</View>
<View style={styles.buttonRow}>
<TouchableOpacity onPress={() => this.props.navigator.pop()}>
<View style={[styles.button, styles.cancelButton]}>
<Text style={styles.cancel}>CLOSE</Text>
</View>
</TouchableOpacity>
<TouchableOpacity
onPress={() => {
phonecall(this.props.rider.phoneNumber, true);
}}
>
<View style={styles.button}>
<Text style={styles.contact}>CONTACT</Text>
</View>
</TouchableOpacity>
</View>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'space-between',
},
infoBox: {
backgroundColor: colors.black,
paddingVertical: 8,
paddingHorizontal: 16,
marginTop: 64,
borderRadius: 4,
justifyContent: 'center',
alignItems: 'center',
},
infoBoxText: {
fontFamily: 'open-sans',
fontSize: 16,
color: 'white',
},
marker: {
height: 24,
width: 24,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: colors.black,
borderRadius: 12,
},
markerInner: {
backgroundColor: 'white',
height: 8,
width: 8,
borderRadius: 4,
},
actionContainer: {
paddingVertical: 8,
backgroundColor: 'white',
justifyContent: 'center',
alignItems: 'center',
},
driverName: {
fontFamily: 'open-sans-bold',
color: colors.black,
fontSize: 14,
paddingBottom: 8,
},
buttonRow: {
paddingTop: 8,
borderTopWidth: StyleSheet.hairlineWidth,
borderColor: colors.lightGrey,
alignItems: 'center',
justifyContent: 'space-around',
flexDirection: 'row',
},
button: {
paddingHorizontal: 16,
alignItems: 'center',
},
cancelButton: {
borderRightWidth: StyleSheet.hairlineWidth,
borderColor: colors.lightGrey,
},
cancel: {
fontFamily: 'open-sans-bold',
color: colors.hotPink,
fontSize: 14,
},
contact: {
fontFamily: 'open-sans-bold',
color: colors.blue,
fontSize: 14,
},
});
|
import React from 'react'
import './List.css'
import PropTypes from 'prop-types'
import { withRouter, Link } from 'react-router-dom'
import { Header } from './Header/Header'
export const List = (props) => {
const { id, name, description, type } = props
return (
<div className="list">
<Link
to={{
pathname: id ? type + id : type,
search: !id && name && name,
state: {
name: name,
},
}}
style={{
textDecoration: 'none',
textAlign: 'left',
width: '100%',
color: 'white',
}}
>
<Header title={`${name} ${description || ''}`} />
</Link>
</div>
)
}
List.propTypes = {
name: PropTypes.string.isRequired,
type: PropTypes.string.isRequired,
}
export default withRouter(List)
|
import React, { Component } from 'react';
// import styled from 'styled-components';
import { graphql } from "react-apollo";
import { Button, Input, Field, Label, styled, Backdrop, Overlay } from 'reakit';
import { Link } from 'react-router-dom';
import { palette as p } from 'styled-tools';
import Cookie from 'js-cookie';
// import Button from '../../components/common/Button';
import { appConsumerWrapper } from '../../wrappers/AppStore';
import { SIGN_IN } from '../../graphql/mutations';
import { GET_ME } from '../../graphql/queries';
import SidebarMenu from '../../components/SidebarMenu';
import ContentLayout from '../../components/Layouts/ContentLayout';
class SignIn extends Component {
state = {
username: '',
password: '',
}
handleOnChange = type => e => {
this.setState({ [type]: e.target.value });
}
handleOnSignIn = () => {
const { mutate } = this.props;
const { username, password } = this.state;
mutate({
variables: {
username,
password,
},
update: (cache, result) => {
const { data: { signIn: { me } } } = result;
// const data = { me };
console.log('>>> sign in update: ', { me });
cache.writeQuery({
query: GET_ME,
data: { me },
});
}
}).then(result => {
const { data: { signIn: { token, me } } } = result;
Cookie.set('token', token)
this.props.history.push('/games');
}).catch(error => {
console.log('>>>> mutate error: ', { error });
});
}
render() {
const { username, password } = this.state;
return (
<ContentLayout>
<Overlay.Container>
{overlay => (
<Container>
<MyBackdrop visible={true} />
<MyOverlay fade slide {...overlay} visible={true}>
<h3>Sign In</h3>
<Field marginBottom="1rem">
<Input
id="username"
placeholder="email or username"
value={username}
onChange={this.handleOnChange('username')}
/>
</Field>
<Field marginBottom="1rem">
<Input
id="password"
placeholder="password"
type="password"
value={password}
onChange={this.handleOnChange('password')}
/>
</Field>
<Button onClick={this.handleOnSignIn} primary>Sign In</Button>
<MyLink to="/">go to home page</MyLink>
</MyOverlay>
</Container>
)}
</Overlay.Container>
</ContentLayout>
);
}
}
export default graphql(SIGN_IN)(appConsumerWrapper(SignIn));
const MyLink = styled(Link)`
float: right;
`;
const Container = styled.div`
padding: 1rem;
background-color: ${p('grayscale', -2)};
`;
const MyOverlay = styled(Overlay)`
min-width: 300px;
background-color: ${p('grayscale', -2)};
`;
const MyBackdrop = styled(Backdrop)`
background-color: white;
`;
|
const initSwiperSlider = () => {
const slider = document.querySelector('.proorb-slider');
if (slider) {
slider.classList.remove('slider--no-js');
const swiper = new Swiper('.proorb-slider', {
slidesPerView: 1,
spaceBetween: 130,
slidesPerGroup: 1,
loop: false,
autoHeight: true,
pagination: {
el: '.swiper-pagination',
type: 'bullets',
clickable: true,
renderBullet: function (index, className) {
return `<span class="${className}">${index + 1}</span>`;
},
},
breakpoints: {
1024: {
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev',
},
// slidesPerView: 3,
// slidesPerGroup: 3,
// pagination: {
// el: '.swiper-pagination',
// type: 'bullets',
// renderBullet: function (index, className) {
// return `<span class="${className}">${index + 1}</span>`;
// },
// },
},
},
});
}
};
document.addEventListener('DOMContentLoaded', () => {
initSwiperSlider();
});
|
// Write a function that counts how many different ways you can make change for an amount of money, given an array of coin denominations. For example, there are 3 ways to give change for 4 if you have coins with denomination 1 and 2:
// 1+1+1+1, 1+1+2, 2+2.
// The order of coins does not matter:
// 1+1+2 == 2+1+1
// Also, assume that you have an infinite ammount of coins.
// Your function should take an amount to change and an array of unique denominations for the coins:
// countChange(4, [1,2]) // => 3
// countChange(10, [5,2,3]) // => 4
// countChange(11, [5,7]) // => 0
// Specifications
// countChange(money, coins)
// Parameters
// money: Number - Number to make change for
// coins: Array<Number> - Array of denominations
// Return Value
// Number - Number of ways change can be made
// Examples
// money coins Return Value
// 10 [5,2,3] 4
let countChange = function(money, coins) {
return findComboCount(money, coins, 0);
}
function findComboCount(money, coin, index) {
if(money === 0){
return 1;
}
else if (money < 0 || coin.length == index) {
return 0;
}
else {
let withFirstCoin = findComboCount(money - coin[index], coin, index);
let withoutFirstCoin = findComboCount(money, coin, index + 1);
return withFirstCoin + withoutFirstCoin;
}
}
|
import React, { useContext } from 'react';
import cn from 'classnames';
import { StateContext } from '../../../../app/App';
import { setSearchingPanelOpened } from '../../../../state/actions';
import { Button } from '../../../Button';
import { Toggle } from '../../../Toggle';
import style from './style.module.css';
export const Header = () => {
const {
dispatch,
} = useContext(StateContext);
const onOpen = () => dispatch(setSearchingPanelOpened(true));
return (
<header className={style.widget__header}>
<Button
title='Поиск города'
className={cn(style.button, style["widget__serching-open"])}
onClick={onOpen}/>
<Toggle />
</header>
)
};
|
/**
* Created by az on 2017/7/17.
*/
import React, {Component} from 'react';
/*eslint-disable*/
class QbDropDownItem extends Component {
constructor(props) {
super(props);
this.state= {
label: props.label,
value: props.value,
}
}
clickHandler() {
const {onClick} = this.props;
return onClick(this.state);
}
render() {
const {className, style, href, label} = this.props;
let c = className?className: '';
let itemClass = "dropdown-item " + c;
return (
<a className={itemClass} href={href} style={style} onClick={this.clickHandler.bind(this)}>{label}</a>
)
}
}
export default QbDropDownItem;
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Field, reduxForm } from 'redux-form';
import TextField from '../../../form-fields/text';
import SelectInput from '../../../form-fields/select';
import {maskCurrency} from '../../../../utils/normalizations';
import Typography from 'material-ui/Typography';
import Button from 'material-ui/Button';
import Grid from 'material-ui/Grid';
class FlightsFourthStep extends Component {
render() {
const { previousPage, invalid, pristine, submitting, handleSubmit } = this.props;
const options = [
{ value: 'manha', text: 'Das 06:00 às 11:59'},
{ value: 'tarde', text: 'Das 12:00 às 17:59'},
{ value: 'noite', text: 'Das 18:00 às 23:59'},
{ value: 'madrugada', text: 'Das 00:00 às 05:59'},
];
const options2 = [
{ value: 0, text: 'Somente voos diretos'},
{ value: 1, text: 'Voos com até 1 parada'},
{ value: 2, text: 'Voos com 2 paradas ou mais'},
]
return (
<form onSubmit={handleSubmit} className="quotation-form">
<Grid container gutter={24}>
<Grid item xs={12}>
<Typography type="title" color="inherit" style={{ marginBottom: 20 }}>
Transporte Aéreo
</Typography>
</Grid>
<Grid item xs={12} >
<Field
name="periodo_voo_ida"
component={SelectInput}
options={options}
label="Ida"
/>
</Grid>
<Grid item xs={12} >
<Field
name="periodo_voo_volta"
component={SelectInput}
options={options}
label="Volta"
/>
</Grid>
<Grid item xs={12}>
<Typography type="title" color="inherit" style={{ marginTop: 50, marginBottom: 20 }}>
Opções Avançadas
</Typography>
</Grid>
<Grid item xs={12}>
<Field
type="text"
name="companias_aereas_preferenciais"
component={TextField}
label="Companhias Aéreas de Preferência"
/>
</Grid>
<Grid item xs={12}>
<Field
name="numero_paradas"
component={SelectInput}
options={options2}
label="Número de Paradas"
/>
</Grid>
<Grid item xs={12}>
<Field
type="number"
name="tempo_voo"
component={TextField}
label="Tempo de Voo em Horas"
/>
</Grid>
<Grid item xs={12}>
<Field
type="tel"
name="aereo_preco_desejado"
component={TextField}
label="Preço Máximo"
normalize={maskCurrency}
/>
</Grid>
<Grid gutter={0} container item xs={12} style={{ marginTop: 30}}>
<Grid gutter={0} container item xs={6} justify="flex-start">
<Button raised color="primary" type="button" onClick={previousPage}>
Anterior
</Button>
</Grid>
<Grid gutter={0} container item xs={6} justify="flex-end">
<Button raised color="primary" type="submit" disabled={invalid || pristine || submitting}>
Próximo
</Button>
</Grid>
</Grid>
</Grid>
</form>
);
}
}
FlightsFourthStep.propTypes = {
handleSubmit: PropTypes.func.isRequired
};
export default reduxForm({
form: 'flightsForm',
destroyOnUnmount: false,
forceUnregisterOnUnmount: true,
})(FlightsFourthStep) |
import {
GET_MESSAGES_SUCCSESS,
GET_MESSAGES_FAILURE,
SEND_MESSAGES_SUCCESS,
SEND_MESSAGES_FAILURE,
CLOSE_MODAL,
OPEN_EMOJI,
GET_MESSAGE_BY_ID_SUCCSESS,
GET_MESSAGE_BY_ID_FAILURE
} from "../store/actions";
const initialState = {
messages: [],
datetime: "",
loading: true,
error: "",
show: false,
open: false,
message: {},
imageViewer: false
};
const reducer = (state = initialState, action) => {
switch (action.type) {
case OPEN_EMOJI:
return { ...state, open: !state.open };
case CLOSE_MODAL:
return {
...state,
show: false,
loading: false,
error: "",
imageViewer: false
};
case GET_MESSAGES_SUCCSESS:
return {
...state,
messages: action.data,
datetime: action.datetime,
loading: false
};
case GET_MESSAGES_FAILURE:
return { ...state, error: action.error, show: true, loading: false };
case GET_MESSAGE_BY_ID_SUCCSESS:
return {
...state,
message: action.data,
imageViewer: true
};
case GET_MESSAGE_BY_ID_FAILURE:
return { ...state, error: action.error, show: true };
case SEND_MESSAGES_SUCCESS:
return { ...state, open: false };
case SEND_MESSAGES_FAILURE:
return { ...state, error: action.error, show: true };
default:
return state;
}
};
export default reducer;
|
/* eslint-disable no-sequences */
import React, { useEffect, useState } from 'react';
import { render, fireEvent } from 'react-testing-library';
import roger from '../index';
describe('Given the Jolly Roger library', () => {
beforeEach(() => {
roger.flush();
});
describe('when we use the Roger\'s useContext/context', () => {
it('should allow us to define methods in the context which accept an action', () => {
roger.context({
multiply(data) {
return data.number * 2;
}
})
const A = function () {
const { multiply } = roger.useContext();
const [ foo, setFoo ] = useState(0);
return (
<button data-testid='button' onClick={ () => setFoo(multiply({ number: 12 })) }>
{ foo }
</button>
);
};
const { container, getByTestId } = render(<A />);
expect(container.textContent).toEqual('0');
fireEvent.click(getByTestId('button'));
expect(container.textContent).toEqual('24');
});
it(`should allow us to update roger's state`, () => {
roger.context({
multiply(data, { setNumber }) {
setNumber(data.number * 2);
}
});
roger.useReducer('foo', {
setNumber(oldValue, newValue) {
return newValue;
}
});
const B = function () {
const { multiply } = roger.useContext();
const [ foo ] = roger.useState('foo', 13);
return (
<button data-testid='button2' onClick={ () => multiply({ number: 33 }) }>
{ foo }
</button>
);
};
const { container, getByTestId } = render(<B />);
expect(container.textContent).toEqual('13');
fireEvent.click(getByTestId('button2'));
expect(container.textContent).toEqual('66');
});
});
});
|
// The GameSetup object defines all the optional parameters around an instance of the
// Memory Match game.
MemoryMatch.GameSetup = {
clientId: "bravotv",
gameName: "RealHousewivesMemoryChallenge",
gameTitle: "The Real Housewives Memory Challenge",
gameSubTitle: "A true Housewife never forgets, so test your recall skills with a ‘Real’ challenge. You might even earn the most sought after Bravo accessory, your very own ‘Real Housewives’ Award!",
gameShortSubTitle: "A Real Housewife never forgets, so test your skills in the ultimate memory challenge.",
gameId: 1084,
siteId: 108,
gameLink: 'http://www.bravotv.com/the-real-housewives-memory-challenge',
gameShortLink: 'http://bravo.ly/XWN3ty',
gameIcon: 'http://www.bravotv.com/media/games/real-housewives-memory-challenge/assets/icon.png',
enginesisStage: '',
developerKey: 'deaddaeddeaddaed',
gameKey: 'e86cf3754cbd83700639e16eee0583c4',
siteDomain: 'bravotv.com',
twitterId: '@bravotv',
socialHashTag: '#rhmc',
facebookAppId: '477181735758491',
googlePlusClientId: '972925239064-mgco9a8lvqu00tuf9pv3q9c385834h66.apps.googleusercontent.com',
googleAnalyticsAccountId: 'UA-13133265-1',
promoImage: 'http://www.bravotv.com/media/games/real-housewives-memory-challenge/assets/1200x900.png',
orientation: "landscape",
assetsFolder: "assets",
backgroundImage: "background.jpg",
popupBackground: "gamePopup.png",
orientationIcon: "rotate-device.png",
guiSprites: ["guiSpriteSheet1.png", "guiSpriteSheet2.png", "mapSpriteSheet.png", "shareicons.png"],
particleSprite: "sparkle_21x23.png",
guiBoldFontName: "SohoStd-BoldItalic",
guiMediumFontName: "open_sanscondensed_light",
guiFontColor: "#FFFFFF",
guiFontColorBonus: "#2393a7",
guiFontColorAchievement: "#2393a7",
guiInfoColor: "#FFFFFF",
guiAlertFontColor: "#FFFFFF",
guiHUDMatchCountHeight: 0.7,
guiHUDMatchCountOffset: 0.12,
guiHUDMatchCountTopMargin: 0.5,
adMinDisplaySeconds: 15,
adShowPreroll: 1,
adInterstitalGameCounter: 3,
adInterstitalLevelCounter: 0,
achievementBorderColor: '#58ddf5',
achievementBackgroundColor: '#3bc7e4',
achievementFontColorEarned: '#FFFFFF',
achievementFontColorUnearned: '#606060',
cardWidth: 384,
cardHeight: 512,
cardMatchCounterPosition: 4,
cardMatchCounterFont: "SohoStd-BoldItalic",
cardMatchCounterColor: "#0000CC",
cardMatchCounterSize: 60,
numberOfStars: 3,
unlockAllFirstLevels: true,
levelButtonAlign: "vertical",
levels: [
{gameId: 4,
title: "Wife Pairing",
gameCount: 6,
challengeGameId: 3,
challengeAdvanceStreak: 3,
iconHUD: "iconHudLand1",
iconPopup: "gameOverLand1",
mapImage: "land1",
mapPosition: {x: 300, y: 738},
gemPosition: {x: 6, y: 380},
tipId: 1,
primaryColor: "#3bc7e4",
secondaryColor: "#2393a7",
liteColor: "#58ddf5"},
{gameId: 5,
title: "A Housewife Never Forgets",
gameCount: 6,
challengeGameId: 6,
challengeAdvanceStreak: 5,
iconHUD: "iconHudLand2",
iconPopup: "gameOverLand2",
mapImage: "land2",
mapPosition: {x: 880, y: 1160},
gemPosition: {x: 116, y: 380},
tipId: 2,
primaryColor: "#f27015",
secondaryColor: "#ce5f12",
liteColor: "#ff9b55"},
{gameId: 2,
title: "Housewives in a Haystack",
gameCount: 6,
challengeGameId: 8,
challengeAdvanceStreak: 3,
iconHUD: "iconHudLand3",
iconPopup: "gameOverLand3",
mapImage: "land3",
mapPosition: {x: 1480, y: 1060},
gemPosition: {x: 226, y: 380},
tipId: 4,
primaryColor: "#8e5fa5",
secondaryColor: "#6b437f",
liteColor: "#be81dc"},
{gameId: 7,
title: "A Race Against Wine",
gameCount: 6,
challengeGameId: 1,
challengeAdvanceStreak: 5,
iconHUD: "iconHudLand4",
iconPopup: "gameOverLand4",
mapImage: "land4",
mapPosition: {x: 1580, y: 404},
gemPosition: {x: 336, y: 380},
tipId: 3,
primaryColor: "#d2428d",
secondaryColor: "#a93370",
liteColor: "#f850a7"}],
games: [
{gameId: 1, gameType: 2, games:30, tolerance: 0, columns:2, rows:2,
cardSprites: ["NY1.png", "NY2.png"],
cardWidth: 384,
cardHeight: 512,
numCards: 19,
levelName:"Repeat After Me",
levelIntro: "Repeat After Me: I will play a pattern, when I am done you must repeat that pattern. Each turn one more is added. You need at least a streak of 5 to advance."
},
{gameId: 2, gameType: 4, games:6, tolerance: 3, columns:3, rows:3,
cardSprites: ["NJ1.png", "NJ2.png"],
cardWidth: 384,
cardHeight: 512,
numCards: 19,
levelName:"Housewives in a Haystack",
levelIntro: "Remember the cards and when it is your turn you are showed a card and you must remember where it was. You have a limited number of moves to find all the cards.",
startMatchCount: 2,
removeMatches: 1,
cardShowTime: 5000,
progression: [{tolerance: 2, matchCount: 3, columns:2, rows:2}, {tolerance: 2, matchCount: 3, columns:2, rows:2}, {tolerance: 4, matchCount: 5, columns:2, rows:3}, {tolerance: 3, matchCount: 5, columns:3, rows:2}, {tolerance: 3, matchCount: 5, columns:3, rows:2}, {tolerance: 4, matchCount: 8, columns:3, rows:3}]
},
{gameId: 3, gameType: 3, games:20, tolerance: 1, columns:7, rows:4,
cardSprites: ["OC1.png", "OC2.png", "BH1.png", "BH2.png"],
cardWidth: 384,
cardHeight: 512,
numCards: 19,
levelName:"Pattern",
levelIntro: "You are shown a pattern, you must select the cards in that pattern. You need at least a streak of 3 to advance.",
startMatchCount: 4,
cardShowTime: 1000,
progression: [{tolerance: 1, columns:5, rows:3}, {tolerance: 1, columns:5, rows:3}, {tolerance: 1, columns:5, rows:4}, {tolerance: 1, columns:5, rows:4}, {tolerance: 1, columns:6, rows:4}, {tolerance: 1, columns:6, rows:4}, {tolerance: 1, columns:7, rows:4}]
},
{gameId: 4, gameType: 1, games:6, tolerance: 6, columns:4, rows:3,
cardSprites: ["OC1.png", "OC2.png", "BH1.png", "BH2.png"],
cardWidth: 384,
cardHeight: 512,
numCards: 19,
levelName:"Wife Pairing ",
levelIntro: "Classic memory match game. Each card has one match. Clear the board before you run out of moves.",
progression: [{tolerance: 10, columns:4, rows:3}, {tolerance: 9, columns:4, rows:3}, {tolerance: 15, columns:4, rows:4}, {tolerance: 13, columns:4, rows:4}, {tolerance: 20, columns:5, rows:4}, {tolerance: 18, columns:5, rows:4}]
},
{gameId: 5, gameType: 5, games:6, tolerance: 3, columns:4, rows:2,
cardSprites: ["ATL1.png", "ATL2.png"],
cardWidth: 384,
cardHeight: 512,
numCards: 19,
levelName:"A Housewife Never Forgets",
levelIntro: "A twist on memory, you must pair all the cards in as few moves as you can. You only get a limited number of moves to pair all the cards.",
progression: [{tolerance: 2, columns:4, rows:2}, {tolerance: 2, columns:4, rows:2}, {tolerance: 3, columns:5, rows:2}, {tolerance: 3, columns:5, rows:2}, {tolerance: 3, columns:4, rows:3}, {tolerance: 3, columns:4, rows:3}],
cardShowTime: 5000
},
{gameId: 6, gameType: 6, games:20, tolerance: 1, columns:3, rows:1,
cardSprites: ["ATL1.png", "ATL2.png"],
cardWidth: 384,
cardHeight: 512,
numCards: 19,
levelName:"Follow Your Card",
levelIntro: "A shell game: you are shown a card, follow the cards as they are moved and when they stop, pick only that card. You must complete at least 5 to advance.",
cardShowTime: 1000,
shuffleCount: 4,
cardAdvance: 5,
advanceToColumns: 5
},
{gameId: 7, gameType: 7, games:6, tolerance: 5, columns:4, rows:2,
cardSprites: ["NY1.png", "NY2.png"],
cardWidth: 384,
cardHeight: 512,
numCards: 19,
levelName:"A Race Against Wine",
levelIntro: "Make matches to stop your nemesis from drinking all your wine! You miss, she drinks your wine. You match, you keep your wine. Now match!",
progression: [{tolerance: 5, columns:4, rows:2}, {tolerance: 5, columns:4, rows:2}, {tolerance: 9, columns:4, rows:3}, {tolerance: 9, columns:4, rows:3}, {tolerance: 8, columns:4, rows:3}, {tolerance: 8, columns:4, rows:3}]
},
{gameId: 8, gameType: 8, games:15, tolerance: 1, columns:5, rows:1,
levelName:"Parts vs. Whole",
levelIntro: "You are shown a set of cards, only one is part of the target card. Pick the correct card to advance. You must complete 3 boards to advance.",
cardSprites: ["NJ3.png"],
cardWidth: 384,
cardHeight: 512,
cardShowTime: 1250,
imageGroups:[
{sprites: 0, difficulty: 1, targetCard: 1, matchCard: 7, badCardCount: 2, badCards: [11,12,13,14,17,18,19]},
{sprites: 0, difficulty: 1, targetCard: 5, matchCard: 10, badCardCount: 2, badCards: [9,12,13,14,15]},
{sprites: 0, difficulty: 1, targetCard: 5, matchCard: 16, badCardCount: 2, badCards: [9,12,13,14,15]},
{sprites: 0, difficulty: 2, targetCard: 6, matchCard: 12, badCardCount: 2, badCards: [9,10,11,14,16,19]},
{sprites: 0, difficulty: 2, targetCard: 1, matchCard: 16, badCardCount: 2, badCards: [11,12,13,14,17,18,19]},
{sprites: 0, difficulty: 2, targetCard: 5, matchCard: 11, badCardCount: 2, badCards: [9,12,13,14,15]},
{sprites: 0, difficulty: 3, targetCard: 2, matchCard: 8, badCardCount: 3, badCards: [7,11,14,15,16,19]},
{sprites: 0, difficulty: 3, targetCard: 4, matchCard: 10, badCardCount: 3, badCards: [8,11,13,14,15,16,19]},
{sprites: 0, difficulty: 3, targetCard: 2, matchCard: 9, badCardCount: 3, badCards: [7,11,14,15,16,19]},
{sprites: 0, difficulty: 3, targetCard: 4, matchCard: 12, badCardCount: 3, badCards: [8,11,13,14,15,16,19]},
{sprites: 0, difficulty: 3, targetCard: 4, matchCard: 9, badCardCount: 3, badCards: [8,11,13,14,15,16,19]},
{sprites: 0, difficulty: 4, targetCard: 6, matchCard: 12, badCardCount: 4, badCards: [9,10,11,14,16,19]},
{sprites: 0, difficulty: 4, targetCard: 4, matchCard: 7, badCardCount: 4, badCards: [8,11,13,14,15,16,19]},
{sprites: 0, difficulty: 4, targetCard: 3, matchCard: 9, badCardCount: 4, badCards: [7,11,12,13,14,15,16,18]},
{sprites: 0, difficulty: 4, targetCard: 3, matchCard: 10, badCardCount: 4, badCards: [7,11,12,13,14,15,16,18]},
{sprites: 0, difficulty: 4, targetCard: 4, matchCard: 10, badCardCount: 4, badCards: [8,11,13,14,15,16,19]},
{sprites: 0, difficulty: 4, targetCard: 2, matchCard: 9, badCardCount: 4, badCards: [7,11,13,14,15,16,19]}
]
}
],
Sounds: {
soundCardDeal: "card-deal.ogg",
soundCardFlip: "cardflip.ogg",
soundCorrect: "correct.ogg",
soundCorrectLess: "correct2.ogg",
soundAchievement: "achievement.ogg",
soundMiss: "miss.ogg",
soundMissLess: "miss2.ogg",
soundTap: "button-tap.ogg",
soundIntro: "intro2.ogg",
soundChallenge: "challenge.ogg",
soundWin: "win.ogg",
soundLose: "lose.ogg",
soundBump: "bump.ogg",
soundBonus: "bonus.ogg",
soundMovesLow: "UhOh-2.ogg",
soundMovesLast: "UhOh-4.ogg",
soundShuffling: "MonteShuffle-3.ogg",
note1: "note1.ogg",
note2: "note2.ogg",
note3: "note3.ogg",
note4: "note4.ogg",
note5: "note5.ogg",
note6: "note6.ogg",
note7: "note7.ogg",
note8: "note8.ogg"
},
guiSpritesheet1Frames: null,
guiSpritesheet2Frames: null,
mapSpritesheetFrames: null,
shareIconsFrames: null,
particleFrames: {width:21, height:23, regX:10, regY:11},
achievements: [
{id: 1, name: "Fast Match", value: 50, icon: "fastmatch", description: "Make a match in less than 1 second."},
{id: 2, name: "Fast Combo", value: 50, icon: "fastcombo", description: "Make a combo in less than 2 seconds."},
{id: 3, name: "Triple Combo", value: 150, icon: "triplecombo", description: "Make three combos without a miss."},
{id: 4, name: "Quad-bo", value: 250, icon: "quadbo", description: "Make four combos without a miss."},
{id: 5, name: "Five Combos", value: 100, icon: "5combo", description: "Make five combos in one game."},
{id: 6, name: "Fifty Combos", value: 250, icon: "50combo", description: "Make fifty combos."},
{id: 7, name: "25 Combos", value: 100, icon: "25combo", description: "Make twenty five combos."},
{id: 8, name: "50 Matches", value: 50, icon: "50match", description: "Make 50 matches."},
{id: 9, name: "100 Matches", value: 150, icon: "100match", description: "Make 100 matches."},
{id: 10, name: "250 Matches", value: 250, icon: "250match", description: "Make 250 matches."},
{id: 11, name: "Lucky Guess", value: 50, icon: "luckyguess", description: "Make a match without seeing the second card."},
{id: 12, name: "Clairvoyant", value: 250, icon: "clairvoyant", description: "Make a match without seeing either card."},
{id: 13, name: "Chain Gang", value: 100, icon: "chaingang", description: "Complete three chain boards without a miss."},
{id: 14, name: "Chaintastic", value: 250, icon: "chaintastic", description: "Complete last chain board without a miss."},
{id: 15, name: "A Contender", value: 250, icon: "acontender", description: "Beat all 4 challenges."},
{id: 16, name: "3-Star", value: 500, icon: "3star", description: "Earn 3 stars on all levels."},
{id: 17, name: "Quick Draw", value: 100, icon: "quickdraw", description: "Complete a game in less than 5 seconds."},
{id: 18, name: "Mozart", value: 275, icon: "mozart", description: "Score over 15 in simon game."},
{id: 19, name: "Monte", value: 275, icon: "monte", description: "Beat 10 monte boards."},
{id: 20, name: "Picasso", value: 275, icon: "picasso", description: "Beat 10 pattern boards."},
{id: 21, name: "Eagle Eye", value: 275, icon: "eagleeye", description: "Beat 15 eyespy boards."}
],
winState: {
title: "Congratulations! You Win!",
subtitle: "You completed the Real Housewives Memory Challenge! You\'re the hottest gamer in the country!",
info: "Now try to go back and improve your scores, earn all the achievements, and earn 3 stars in every game! You can do it!"},
tips: [[
{id: 1, category: 'win', text: 'When the going gets tough, you just get stronger and stronger!'},
{id: 2, category: 'win', text: 'You\'re the hottest gamer in the O.C.!'},
{id: 3, category: 'win', text: 'You like to have fun, and you do play games (pretty well we might add)!'},
{id: 17, category: 'tip', text: 'Life isn\'t always diamonds and roses, so don\'t give up!'},
{id: 18, category: 'tip', text: 'In Beverly Hills, the higher you climb, the farther you fall. You\'ll get it next time!'},
{id: 22, category: 'tip', text: 'Everyone loves a comeback story, especially starring you!'}
],
[
{id: 5, category: 'win', text: 'You know how to work it, and win games!'},
{id: 6, category: 'win', text: 'You have arrived, and the spotlight is on you, honey!'},
{id: 7, category: 'win', text: 'People are intimidated by your success.'},
{id: 8, category: 'tip', text: 'Don\'t worry success is in your DNA. When one door closes, another one opens, so try again!'},
{id: 20, category: 'tip', text: 'A true Southern belle knows her worth, and you\'re priceless, so give it another shot!'},
{id: 26, category: 'tip', text: 'Don\'t worry so much about keeping up with the Joneses and give it another try!'}
],
[
{id: 13, category: 'win', text: 'You\'re a Jersey girl, no one can knock you down!'},
{id: 14, category: 'win', text: 'Haters are gonna hate, but you just win, win, win!'},
{id: 15, category: 'win', text: 'Life is short, you have no time for losing!'},
{id: 21, category: 'tip', text: 'Life is about change, sometimes you just have to roll with the punches. Give it another shot!'},
{id: 21, category: 'tip', text: 'When times get tough, you learn who your real friends are. Don\'t give up!'},
{id: 22, category: 'tip', text: 'You\'ve faced your share of challenges, but you\'re tougher than you look, so try again!'}
],
[
{id: 9, category: 'win', text: 'Get the pinot ready, because it\'s turtle time! Congrats!'},
{id: 10, category: 'win', text: 'You have a taste for winning, and winning has a taste for you!'},
{id: 11, category: 'win', text: 'To some people, winning elegantly just comes naturally.'},
{id: 12, category: 'tip', text: 'A true New Yorker never backs down, and you\'re no exception. Holla!'},
{id: 24, category: 'tip', text: 'You may not be the sharpest tool in the shed, but you\'re pretty, so don\'t give up!'},
{id: 25, category: 'tip', text: 'You\'re living the American dream, one mistake at a time... Try again!'}
]],
mapImages: [],
mapLevelPositions: [
[{x:166, y:140}, {x:236, y:340}, {x:110, y:510}, {x:230, y:650}, {x:90, y:804}, {x:300, y:840}, {x:370, y:1020}],
[{x:730, y:1280}, {x:854, y:1164}, {x:684, y:1032}, {x:572, y:836}, {x:756, y:840}, {x:892, y:964}, {x:1072, y:1048}],
[{x:1280, y:1198}, {x:1418, y:1248}, {x:1428, y:1036}, {x:1544, y:928}, {x:1388, y:838}, {x:1388, y:628}, {x:1516, y:644}],
[{x:1746, y:498}, {x:1720, y:270}, {x:1718, y:48}, {x:1548, y:114}, {x:1498, y:304}, {x:1328, y:316}, {x:1140, y:228}]
],
mapLevelColor: "#FFFFFF",
mapPathColor: 'rgba(102,102,102,0.5)',
mapLogoPosition: {x: 1024, y:144},
mapAwardPosition: {x: 1024, y:540},
mapSpecialMarkers: [{x: 650, y: 1306, icon: 'planeRouteCa'}, {x: 1270, y: 1190, icon: 'planeRouteGa'}, {x: 1712, y: 662, icon: 'bridge'}],
GUIStrings: {
loadingMessages: ["We're loading...", "It's getting amazing!...", "Oh! This is looking good...", "Ready to play!"],
wordsOfEncouragement: ['Amazing', 'Spectacular', 'Awesome', 'Sensational', 'Impressive', 'Inspiring', 'Magnificent', 'Wonderful'],
bookmarkTitle: 'Did you know?',
bookmarkMessage: 'For a better playing experience you can bookmark this app by tapping the Share icon then select Add to Home Screen.',
shareEmailMessage: 'Matching game with something extra - come play %gamename%. I really enjoy this game, you will too!',
shareStatusMessage: 'Matching game with something extra - Come play %gamename%. I really enjoy this game, you will too!',
shareStatusShortMessage: 'Come play %gamename%. I really enjoy this game, you will too!',
shareGameOverMessage: 'Oh yes! I just completed %gamename% with a score of %score%. Can you beat me?',
shareGameOverShortMessage: 'I just completed %gamename% with a score of %score%. Can you beat me?',
orientationMessage: 'This game is best played in landscape orientation.',
creditsInfo: 'This game was made by JumpyDot using the EaselJS HTML5 framework.',
creditsCredit: 'Dan Hart: Game Design & Product Management\n\nJohn Foster: Programming & Audio\n\nJulia Deter-Keren: Game Design & Art Direction\n\nRobert Prescott: Quality Assurance',
demoTextMatchLikeCards: 'Match like cards.',
demoTextClearBoard: 'Clear the board before you run out of misses.',
demoTextPlayQuick: 'Play quickly for extra points.',
demoTextStudyBoard: 'Study the board to remember where all the pairs are located.',
demoTextOnlyAFewSeconds: 'You have only a few seconds to study the board.',
demoTextFindPairs: 'Find the pairs but you have only a few misses!',
demoTextNemesisGoal: 'Each time you miss your Nemesis advances. Don\'t lose your cupcake!',
demoTextRememberLocation: 'Remember the locations of the cards.',
demoTextHaystackGoal: 'Locate the target card before you run out of misses.',
sharePopupTitle: "Share %gamename% with your favorite social network:",
emailErrorSender: 'Please provide your email address as the sender.',
emailErrorTo: 'Please provide the email address of a recipient.',
emailErrorFrom: 'Please provide a valid sender email address.',
emailErrorToEmail: 'Please provide a valid email address of a recipient.',
allLevelsUnlocked: 'You have unlocked all levels.',
allLevelsLocked: 'You have reset all levels.'
}
}; |
import React from 'react';
import { Card } from 'semantic-ui-react'
import { auth, db } from '../services/firebase';
import Medication from './Medication';
import NewMedication from './NewMedication';
export default class MedList extends React.Component {
constructor(props) {
super(props);
this.state = {
user: auth().currentUser,
meds: [],
readError: null,
writeError: null
};
this.path = `users/${auth().currentUser.uid}/${this.props.person.key}/meds/`;
}
async componentDidMount() {
this.setState( { readError: null } );
try {
db.ref(this.path).on('value', snapshot => {
let meds = [];
snapshot.forEach( snap => {
const theMed = { key: snap.ref.path.pieces_[snap.ref.path.pieces_.length -1 ], ...snap.val() }
meds.push(theMed);
});
this.setState({ meds });
});
} catch(error) {
this.setState({readError: error.message});
}
}
render() {
return (
<Card.Group>
{ this.state.meds.map( med => {
return <Card key={med.key} className="med-card"><Medication med={med} person={this.props.person} /></Card>
})}
<Card key="newMed" className="med-card new-med-card"><NewMedication person={this.props.person} /></Card>
</Card.Group>
);
}
} |
var $layer;
var layerTemplate;
var scrollPosition = 0;
var $window = $(window);
$(document).ready(init);
function init() {
$layer = $('._layer').css({
position: 'absolute',
opacity: 0.9,
zIndex: 1000
});
$layer.on('click', function (e) {
if ($(e.target).closest('.__close').length > 0) {
$layer.hide();
unfreezeBackground();
e.preventDefault();
}
});
layerTemplate = Handlebars.compile($('._layerTemplate').html());
}
function getHtml(data) {
return layerTemplate({
heading: data.subtitle,
url: data.url,
starredCharacters: data.characters,
allCharacters: data.allCharacters
});
}
function parseData(data) {
var characters = [];
var allCharacters = [];
_.each(data.characters.split(','), function (character) {
if (character.length < 1) {
return;
}
characters.push({
name: $.trim(character)
});
});
_.each(data.allCharacters.split(','), function (character) {
if (character.length < 1) {
return;
}
allCharacters.push({
name: $.trim(character)
});
});
data.characters = characters;
data.allCharacters = allCharacters;
return data;
}
function drawLayer(result) {
var height = 0;
if ($layer.is(':visible')) {
result = parseData(result);
$layer.html(getHtml(result));
height = $layer.find('.__heading').outerHeight();
$layer.find('.__toonContainer').css({
height: $window.height() - (height + 30 + 2) // padding + border
});
presetCharacters();
addEventHandlersOnChar();
}
}
function presetCharacters() {
var onList = [];
var notOnList = [];
$layer.find('.__charOnList').each(function (index, elem) {
onList.push($(this).attr('data-name'));
});
$layer.find('.__charNotOnList').each(function (index, elem) {
notOnList.push($(this).attr('data-name'));
});
_.each(onList, function (name) {
setOnList(name);
});
}
function setOnList(name) {
$layer.find('.__charNotOnList[data-name="' + name + '"]')
.removeClass('btn-primary')
.addClass('btn-default')
.prop('disabled', 'disabled');
}
function setNotOnList(name) {
$layer.find('.__charNotOnList[data-name="' + name + '"]')
.removeClass('btn-default')
.addClass('btn-primary')
.prop('disabled', '');
}
function addEventHandlersOnChar() {
$layer.find('.__charOnList').on('click', function (e) {
e.preventDefault();
var $target = $(e.target);
console.log($target.attr('data-name'));
});
$layer.find('.__charNotOnList').on('click', function (e) {
e.preventDefault();
var $target = $(e.target);
console.log($target.attr('data-name'));
});
}
function freezeBackground() {
scrollPosition = $window.scrollTop();
$('.__wrap').css({
position: 'fixed',
left: '0px',
right: '0px',
top: '0px',
bottom: '0px',
overflow: 'hidden',
height: $window.height(),
}).scrollTop(scrollPosition);
$window.scrollTop(0);
}
function unfreezeBackground() {
$('.__wrap').css({
position: '',
overflow: 'visible',
height: 'auto'
});
$window.scrollTop(scrollPosition);
}
function showLoading() {
var $output = $(layerTemplate({
heading: '정보를 불러오고 있습니다.'
}));
$output.find('.__body').hide();
freezeBackground();
$layer.html($output.html()).css({
left: 0,
top: 0,
width: '100%',
height: '100%'
}).show();
} |
// SET CALENDER SPAN
export const setStartDate = (startDate = null) => ({
type: 'SET_START_DATE',
startDate
})
export const setEndDate = (endDate = null) => ({
type: 'SET_END_DATE',
endDate
})
export const searchByMarket = (searchText = '') => ({
type: 'SEARCH_BY_MARKET',
searchText
})
export const sortByMarket = () => ({
type: 'SORT_BY_MARKET',
})
export const sortByDirection = () => ({
type: 'SORT_BY_DIRECTION'
})
export const sortBySetup = () => ({
type: 'SORT_BY_SETUP'
})
export const sortByR = () => ({
type: 'SORT_BY_R'
})
export const sortByOutcome = () => ({
type: 'SORT_BY_OUTCOME'
})
export const sortByOpened = () => ({
type: 'SORT_BY_OPENED'
})
export const sortByClosed = () => ({
type: 'SORT_BY_CLOSED'
})
export const sortByPeriod = () => ({
type: 'SORT_BY_PERIOD'
})
export const sortByExecution = () => ({
type: 'SORT_BY_EXECUTION'
})
export const sortByManagement = () => ({
type: 'SORT_BY_MANAGEMENT'
})
|
var mongoose = require('mongoose');
var User = module.exports = {};
// BRICE GITHUB ID : 18247624 && LOGIN : BumbleBrice
User.init = function (app) {
const userSchema = new mongoose.Schema({
githubId: {
type: Number,
unique: true,
required: true
},
accessToken: {
type: String,
required: true
},
refreshToken: {
type: String,
required: false
},
username: {
type: String,
required: true
},
displayName: {
type: String,
required: false
},
emails: [
{
value: String,
_id: false // To prevent mongoose from creating unwanted _id property
}
],
avatarUrl: {
type: String,
require: false
},
});
this.model = mongoose.model('User', userSchema)
app.get('/user', (req, res) => {
this.model.find({}, function (err, users) {
if (err) res.send(err);
res.send(users);
})
});
app.delete('/user/:id', (req, res) => {
this.delete(req.params.id);
});
}
User.onConnection = function (profile, accessToken, refreshToken, done) {
this.model.findOne({githubId: profile.id}, (err, userFound) => {
if (userFound) {
// Update user and save it
userFound.displayName = profile.displayName;
userFound.username = profile.username;
userFound.accessToken = accessToken;
userFound.refreshToken = refreshToken;
userFound.emails = profile.emails;
userFound.avatarUrl = profile._json.avatar_url
userFound.save((err) => {
console.log(err);
});
userFound.admin = true;
done(null, userFound); // CALLBACK FOR AUTHENTICATION
} else {
// Create user
let userTemp = {
githubId: profile.id,
accessToken,
username: profile.username,
displayName: profile.displayName,
emails: profile.emails,
avatarUrl: profile._json.avatar_url
}
this.model.create(userTemp, (err, userResponse) => {
if (err) console.log(err);
userResponse.admin = true;
done(null, userResponse); // CALLBACK FOR AUTHENTICATION
})
}
})
}
User.delete = function (_id) {
this.model.remove({_id: _id}, function(err) {
if (err) return console.log(err);
})
} |
import React, { Fragment } from "react";
import SelectedOne from "../elements/selectedOne";
import NextStep from "../elements/nextbutton";
import CopyInput from "../elements/copyinput";
import Total from "../elements/total";
import { FaBitcoin, FaCheckCircle } from "react-icons/fa";
import { useHistory } from "react-router-dom";
import { useSelector, useDispatch } from "react-redux";
import { setPromo, setCC } from "../../../store/actions/bitpayActions";
const StepThree = ({ data }) => {
const selectedCC = useSelector(state => state.bitpayReducer.cryptoCurrency);
const selectedPromo = useSelector(state => state.bitpayReducer.promo);
const iconBit = <FaBitcoin className="icon-first" />;
const textBit = "Crypto currency";
const iconSelICON = <FaCheckCircle className="icon-first" />;
const textICON = selectedCC ? selectedCC.name : "";
const textTwoICON = selectedPromo ? selectedPromo.name : "";
const history = useHistory();
const dispatch = useDispatch();
const ChangeURL = () => {
history.push("/");
};
const ChangeURLTwo = () => {
history.push("/steptwo");
};
const ChangeAll = () => {
history.push("/");
dispatch(setPromo(null));
dispatch(setCC(null));
};
const SetURL = () => {
if (selectedCC === null || selectedPromo === null) {
alert(
"you have not selected a promotion or currency, your transaction cannot be processed!"
);
} else {
history.push("/stepfour");
}
};
const generateS4 = () =>
(((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
const idPayment =
generateS4() +
generateS4() +
"-" +
generateS4() +
"-" +
generateS4() +
"-" +
generateS4() +
"-" +
generateS4() +
generateS4() +
generateS4();
return (
<Fragment>
<SelectedOne icon={iconBit} text={textBit} ChangeURL={ChangeAll} />
<SelectedOne icon={iconSelICON} text={textICON} ChangeURL={ChangeURL} />
<SelectedOne
icon={iconSelICON}
text={textTwoICON}
ChangeURL={ChangeURLTwo}
/>
<h5 className="header-el">
<b>Total</b>
</h5>
<Total selectedCC={selectedCC} />
<h5 className="header-el" style={{ marginTop: "60px" }}>
<b>Send your payment to</b>
</h5>
<CopyInput CopyValue={idPayment} />
<NextStep SetURL={SetURL} />
</Fragment>
);
};
export default StepThree;
|
(function() {
// 这些变量和函数的说明,请参考 rdk/app/example/web/scripts/main.js 的注释
var imports = [
'rd.controls.Table','css!base/css/simple_tab2','css!rd.styles.IconFonts'
];
var extraModules = [ ];
var controllerDefination = ['$scope', main];
function main(scope) {
scope.setting = {
"columnDefs" :[
{
title : "操作",
targets:6,
render : '<i class="iconfont iconfont-e8b7"></i> <i class="iconfont iconfont-e8c8"></i>' }
]
}
function imagePosition(){
var width = parseFloat($('.main2').css('width'));
var height = parseFloat($('.main2').css('height'));//恨据外围 div的长宽给图标自动定位
$('button.images_right').css({
'left':(width-1)+"px",
'top':(height/2-32)+"px"
});
}
imagePosition();
//左右拉的点击动漫效果
scope.iconCondition = true;
scope.images = function(){
scope.iconCondition = !scope.iconCondition;
if($('.main2').hasClass('images_down')){
$('.main2').removeClass('images_down').addClass('images_up');
}else{
$('.main2').removeClass('images_up').addClass('images_down')
}
}
}
var controllerName = 'DemoController';
//==========================================================================
// 从这里开始的代码、注释请不要随意修改
//==========================================================================
define(/*fix-from*/application.import(imports)/*fix-to*/, start);
function start() {
application.initImports(imports, arguments);
rdk.$injectDependency(application.getComponents(extraModules, imports));
rdk.$ngModule.controller(controllerName, controllerDefination);
}
})(); |
import React from 'react'
import { Container, Row, Col } from 'react-bootstrap'
const Category = () => {
return (
<Container className='category-parent'>
<h4>Category</h4>
<Row className='mt-4'>
{/* boxes */}
<Col md='1' xs='4' className='px-3'>
<div className='category-box inactive'>
<i className='fas fa-mitten text-secondary'></i>
</div>
</Col>
<Col md='1' xs='4' className='px-3'>
<div className='category-box active'>
<i className='fas fa-tshirt text-white'></i>
</div>
</Col>
{/* Dummy Buttons */}
<Col md='1' xs='4' className='px-3'>
<div className='category-box inactive'></div>
</Col>
</Row>
</Container>
)
}
export default Category
|
(function () {
// Shorthard for utilities
var Dom = YAHOO.util.Dom,
Event = YAHOO.util.Event,
Lang = YAHOO.lang,
Button = YAHOO.widget.Button,
// Private collection of radio buttons
m_oButtons = {};
/**
* The ButtonGroup class creates a set of buttons that are mutually
* exclusive; checking one button in the set will uncheck all others in the
* button group.
* @param {String} p_oElement String specifying the id attribute of the
* <code><div></code> element of the button group.
* @param {<a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/
* level-one-html.html#ID-22445964">HTMLDivElement</a>} p_oElement Object
* specifying the <code><div></code> element of the button group.
* @param {Object} p_oElement Object literal specifying a set of
* configuration attributes used to create the button group.
* @param {Object} p_oAttributes Optional. Object literal specifying a set
* of configuration attributes used to create the button group.
* @namespace YAHOO.widget
* @class ButtonGroup
* @constructor
* @extends YAHOO.util.Element
*/
YAHOO.widget.ButtonGroup = function (p_oElement, p_oAttributes) {
var fnSuperClass = YAHOO.widget.ButtonGroup.superclass.constructor,
sNodeName,
oElement,
sId;
if (arguments.length == 1 && !Lang.isString(p_oElement) &&
!p_oElement.nodeName) {
if (!p_oElement.id) {
sId = Dom.generateId();
p_oElement.id = sId;
YAHOO.log("No value specified for the button group's \"id\"" +
" attribute. Setting button group id to \"" + sId + "\".",
"info");
}
this.logger = new YAHOO.widget.LogWriter("ButtonGroup " + sId);
this.logger.log("No source HTML element. Building the button " +
"group using the set of configuration attributes.");
fnSuperClass.call(this, (this._createGroupElement()), p_oElement);
}
else if (Lang.isString(p_oElement)) {
oElement = Dom.get(p_oElement);
if (oElement) {
if (oElement.nodeName.toUpperCase() == this.NODE_NAME) {
this.logger =
new YAHOO.widget.LogWriter("ButtonGroup " + p_oElement);
fnSuperClass.call(this, oElement, p_oAttributes);
}
}
}
else {
sNodeName = p_oElement.nodeName.toUpperCase();
if (sNodeName && sNodeName == this.NODE_NAME) {
if (!p_oElement.id) {
p_oElement.id = Dom.generateId();
YAHOO.log("No value specified for the button group's" +
" \"id\" attribute. Setting button group id " +
"to \"" + p_oElement.id + "\".", "warn");
}
this.logger =
new YAHOO.widget.LogWriter("ButtonGroup " + p_oElement.id);
fnSuperClass.call(this, p_oElement, p_oAttributes);
}
}
};
YAHOO.extend(YAHOO.widget.ButtonGroup, YAHOO.util.Element, {
// Protected properties
/**
* @property _buttons
* @description Array of buttons in the button group.
* @default null
* @protected
* @type Array
*/
_buttons: null,
// Constants
/**
* @property NODE_NAME
* @description The name of the tag to be used for the button
* group's element.
* @default "DIV"
* @final
* @type String
*/
NODE_NAME: "DIV",
/**
* @property CSS_CLASS_NAME
* @description String representing the CSS class(es) to be applied
* to the button group's element.
* @default "yui-buttongroup"
* @final
* @type String
*/
CSS_CLASS_NAME: "yui-buttongroup",
// Protected methods
/**
* @method _createGroupElement
* @description Creates the button group's element.
* @protected
* @return {<a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/
* level-one-html.html#ID-22445964">HTMLDivElement</a>}
*/
_createGroupElement: function () {
var oElement = document.createElement(this.NODE_NAME);
return oElement;
},
// Protected attribute setter methods
/**
* @method _setDisabled
* @description Sets the value of the button groups's
* "disabled" attribute.
* @protected
* @param {Boolean} p_bDisabled Boolean indicating the value for
* the button group's "disabled" attribute.
*/
_setDisabled: function (p_bDisabled) {
var nButtons = this.getCount(),
i;
if (nButtons > 0) {
i = nButtons - 1;
do {
this._buttons[i].set("disabled", p_bDisabled);
}
while (i--);
}
},
// Protected event handlers
/**
* @method _onKeyDown
* @description "keydown" event handler for the button group.
* @protected
* @param {Event} p_oEvent Object representing the DOM event object
* passed back by the event utility (YAHOO.util.Event).
*/
_onKeyDown: function (p_oEvent) {
var oTarget = Event.getTarget(p_oEvent),
nCharCode = Event.getCharCode(p_oEvent),
sId = oTarget.parentNode.parentNode.id,
oButton = m_oButtons[sId],
nIndex = -1;
if (nCharCode == 37 || nCharCode == 38) {
nIndex = (oButton.index === 0) ?
(this._buttons.length - 1) : (oButton.index - 1);
}
else if (nCharCode == 39 || nCharCode == 40) {
nIndex = (oButton.index === (this._buttons.length - 1)) ?
0 : (oButton.index + 1);
}
if (nIndex > -1) {
this.check(nIndex);
this.getButton(nIndex).focus();
}
},
/**
* @method _onAppendTo
* @description "appendTo" event handler for the button group.
* @protected
* @param {Event} p_oEvent Object representing the event that was fired.
*/
_onAppendTo: function (p_oEvent) {
var aButtons = this._buttons,
nButtons = aButtons.length,
i;
for (i = 0; i < nButtons; i++) {
aButtons[i].appendTo(this.get("element"));
}
},
/**
* @method _onButtonCheckedChange
* @description "checkedChange" event handler for each button in the
* button group.
* @protected
* @param {Event} p_oEvent Object representing the event that was fired.
* @param {<a href="YAHOO.widget.Button.html">YAHOO.widget.Button</a>}
* p_oButton Object representing the button that fired the event.
*/
_onButtonCheckedChange: function (p_oEvent, p_oButton) {
var bChecked = p_oEvent.newValue,
oCheckedButton = this.get("checkedButton");
if (bChecked && oCheckedButton != p_oButton) {
if (oCheckedButton) {
oCheckedButton.set("checked", false, true);
}
this.set("checkedButton", p_oButton);
this.set("value", p_oButton.get("value"));
}
else if (oCheckedButton && !oCheckedButton.set("checked")) {
oCheckedButton.set("checked", true, true);
}
},
// Public methods
/**
* @method init
* @description The ButtonGroup class's initialization method.
* @param {String} p_oElement String specifying the id attribute of the
* <code><div></code> element of the button group.
* @param {<a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/
* level-one-html.html#ID-22445964">HTMLDivElement</a>} p_oElement Object
* specifying the <code><div></code> element of the button group.
* @param {Object} p_oElement Object literal specifying a set of
* configuration attributes used to create the button group.
* @param {Object} p_oAttributes Optional. Object literal specifying a
* set of configuration attributes used to create the button group.
*/
init: function (p_oElement, p_oAttributes) {
this._buttons = [];
YAHOO.widget.ButtonGroup.superclass.init.call(this, p_oElement,
p_oAttributes);
this.addClass(this.CSS_CLASS_NAME);
this.logger.log("Searching for child nodes with the class name " +
"\"yui-radio-button\" to add to the button group.");
var aButtons = this.getElementsByClassName("yui-radio-button");
if (aButtons.length > 0) {
this.logger.log("Found " + aButtons.length +
" child nodes with the class name \"yui-radio-button.\"" +
" Attempting to add to button group.");
this.addButtons(aButtons);
}
this.logger.log("Searching for child nodes with the type of " +
" \"radio\" to add to the button group.");
function isRadioButton(p_oElement) {
return (p_oElement.type == "radio");
}
aButtons =
Dom.getElementsBy(isRadioButton, "input", this.get("element"));
if (aButtons.length > 0) {
this.logger.log("Found " + aButtons.length + " child nodes" +
" with the type of \"radio.\" Attempting to add to" +
" button group.");
this.addButtons(aButtons);
}
this.on("keydown", this._onKeyDown);
this.on("appendTo", this._onAppendTo);
var oContainer = this.get("container");
if (oContainer) {
if (Lang.isString(oContainer)) {
Event.onContentReady(oContainer, function () {
this.appendTo(oContainer);
}, null, this);
}
else {
this.appendTo(oContainer);
}
}
this.logger.log("Initialization completed.");
},
/**
* @method initAttributes
* @description Initializes all of the configuration attributes used to
* create the button group.
* @param {Object} p_oAttributes Object literal specifying a set of
* configuration attributes used to create the button group.
*/
initAttributes: function (p_oAttributes) {
var oAttributes = p_oAttributes || {};
YAHOO.widget.ButtonGroup.superclass.initAttributes.call(
this, oAttributes);
/**
* @attribute name
* @description String specifying the name for the button group.
* This name will be applied to each button in the button group.
* @default null
* @type String
*/
this.setAttributeConfig("name", {
value: oAttributes.name,
validator: Lang.isString
});
/**
* @attribute disabled
* @description Boolean indicating if the button group should be
* disabled. Disabling the button group will disable each button
* in the button group. Disabled buttons are dimmed and will not
* respond to user input or fire events.
* @default false
* @type Boolean
*/
this.setAttributeConfig("disabled", {
value: (oAttributes.disabled || false),
validator: Lang.isBoolean,
method: this._setDisabled
});
/**
* @attribute value
* @description Object specifying the value for the button group.
* @default null
* @type Object
*/
this.setAttributeConfig("value", {
value: oAttributes.value
});
/**
* @attribute container
* @description HTML element reference or string specifying the id
* attribute of the HTML element that the button group's markup
* should be rendered into.
* @type <a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/
* level-one-html.html#ID-58190037">HTMLElement</a>|String
* @default null
* @writeonce
*/
this.setAttributeConfig("container", {
value: oAttributes.container,
writeOnce: true
});
/**
* @attribute checkedButton
* @description Reference for the button in the button group that
* is checked.
* @type {<a href="YAHOO.widget.Button.html">YAHOO.widget.Button</a>}
* @default null
*/
this.setAttributeConfig("checkedButton", {
value: null
});
},
/**
* @method addButton
* @description Adds the button to the button group.
* @param {<a href="YAHOO.widget.Button.html">YAHOO.widget.Button</a>}
* p_oButton Object reference for the <a href="YAHOO.widget.Button.html">
* YAHOO.widget.Button</a> instance to be added to the button group.
* @param {String} p_oButton String specifying the id attribute of the
* <code><input></code> or <code><span></code> element
* to be used to create the button to be added to the button group.
* @param {<a href="http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/
* level-one-html.html#ID-6043025">HTMLInputElement</a>|<a href="
* http://www.w3.org/TR/2000/WD-DOM-Level-1-20000929/level-one-html.html#
* ID-33759296">HTMLElement</a>} p_oButton Object reference for the
* <code><input></code> or <code><span></code> element
* to be used to create the button to be added to the button group.
* @param {Object} p_oButton Object literal specifying a set of
* <a href="YAHOO.widget.Button.html">YAHOO.widget.Button</a>
* configuration attributes used to configure the button to be added to
* the button group.
* @return {<a href="YAHOO.widget.Button.html">YAHOO.widget.Button</a>}
*/
addButton: function (p_oButton) {
var oButton,
oButtonElement,
oGroupElement,
nIndex,
sButtonName,
sGroupName;
if (p_oButton instanceof Button &&
p_oButton.get("type") == "radio") {
oButton = p_oButton;
}
else if (!Lang.isString(p_oButton) && !p_oButton.nodeName) {
p_oButton.type = "radio";
oButton = new Button(p_oButton);
}
else {
oButton = new Button(p_oButton, { type: "radio" });
}
if (oButton) {
nIndex = this._buttons.length;
sButtonName = oButton.get("name");
sGroupName = this.get("name");
oButton.index = nIndex;
this._buttons[nIndex] = oButton;
m_oButtons[oButton.get("id")] = oButton;
if (sButtonName != sGroupName) {
oButton.set("name", sGroupName);
}
if (this.get("disabled")) {
oButton.set("disabled", true);
}
if (oButton.get("checked")) {
this.set("checkedButton", oButton);
}
oButtonElement = oButton.get("element");
oGroupElement = this.get("element");
if (oButtonElement.parentNode != oGroupElement) {
oGroupElement.appendChild(oButtonElement);
}
oButton.on("checkedChange",
this._onButtonCheckedChange, oButton, this);
this.logger.log("Button " + oButton.get("id") + " added.");
}
return oButton;
},
/**
* @method addButtons
* @description Adds the array of buttons to the button group.
* @param {Array} p_aButtons Array of <a href="YAHOO.widget.Button.html">
* YAHOO.widget.Button</a> instances to be added
* to the button group.
* @param {Array} p_aButtons Array of strings specifying the id
* attribute of the <code><input></code> or <code><span>
* </code> elements to be used to create the buttons to be added to the
* button group.
* @param {Array} p_aButtons Array of object references for the
* <code><input></code> or <code><span></code> elements
* to be used to create the buttons to be added to the button group.
* @param {Array} p_aButtons Array of object literals, each containing
* a set of <a href="YAHOO.widget.Button.html">YAHOO.widget.Button</a>
* configuration attributes used to configure each button to be added
* to the button group.
* @return {Array}
*/
addButtons: function (p_aButtons) {
var nButtons,
oButton,
aButtons,
i;
if (Lang.isArray(p_aButtons)) {
nButtons = p_aButtons.length;
aButtons = [];
if (nButtons > 0) {
for (i = 0; i < nButtons; i++) {
oButton = this.addButton(p_aButtons[i]);
if (oButton) {
aButtons[aButtons.length] = oButton;
}
}
}
}
return aButtons;
},
/**
* @method removeButton
* @description Removes the button at the specified index from the
* button group.
* @param {Number} p_nIndex Number specifying the index of the button
* to be removed from the button group.
*/
removeButton: function (p_nIndex) {
var oButton = this.getButton(p_nIndex),
nButtons,
i;
if (oButton) {
this.logger.log("Removing button " + oButton.get("id") + ".");
this._buttons.splice(p_nIndex, 1);
delete m_oButtons[oButton.get("id")];
oButton.removeListener("checkedChange",
this._onButtonCheckedChange);
oButton.destroy();
nButtons = this._buttons.length;
if (nButtons > 0) {
i = this._buttons.length - 1;
do {
this._buttons[i].index = i;
}
while (i--);
}
this.logger.log("Button " + oButton.get("id") + " removed.");
}
},
/**
* @method getButton
* @description Returns the button at the specified index.
* @param {Number} p_nIndex The index of the button to retrieve from the
* button group.
* @return {<a href="YAHOO.widget.Button.html">YAHOO.widget.Button</a>}
*/
getButton: function (p_nIndex) {
return this._buttons[p_nIndex];
},
/**
* @method getButtons
* @description Returns an array of the buttons in the button group.
* @return {Array}
*/
getButtons: function () {
return this._buttons;
},
/**
* @method getCount
* @description Returns the number of buttons in the button group.
* @return {Number}
*/
getCount: function () {
return this._buttons.length;
},
/**
* @method focus
* @description Sets focus to the button at the specified index.
* @param {Number} p_nIndex Number indicating the index of the button
* to focus.
*/
focus: function (p_nIndex) {
var oButton,
nButtons,
i;
if (Lang.isNumber(p_nIndex)) {
oButton = this._buttons[p_nIndex];
if (oButton) {
oButton.focus();
}
}
else {
nButtons = this.getCount();
for (i = 0; i < nButtons; i++) {
oButton = this._buttons[i];
if (!oButton.get("disabled")) {
oButton.focus();
break;
}
}
}
},
/**
* @method check
* @description Checks the button at the specified index.
* @param {Number} p_nIndex Number indicating the index of the button
* to check.
*/
check: function (p_nIndex) {
var oButton = this.getButton(p_nIndex);
if (oButton) {
oButton.set("checked", true);
}
},
/**
* @method destroy
* @description Removes the button group's element from its parent
* element and removes all event handlers.
*/
destroy: function () {
this.logger.log("Destroying...");
var nButtons = this._buttons.length,
oElement = this.get("element"),
oParentNode = oElement.parentNode,
i;
if (nButtons > 0) {
i = this._buttons.length - 1;
do {
this._buttons[i].destroy();
}
while (i--);
}
this.logger.log("Removing DOM event handlers.");
Event.purgeElement(oElement);
this.logger.log("Removing from document.");
oParentNode.removeChild(oElement);
},
/**
* @method toString
* @description Returns a string representing the button group.
* @return {String}
*/
toString: function () {
return ("ButtonGroup " + this.get("id"));
}
});
})(); |
const sqlite3 = require('sqlite3').verbose();
/**
* Get all projects of one user, which is not in waiting status. Async mode.
* @param {number} uid - User ID
* @param {function} callback - Callback function that handles query results
* @returns {function} Callback function
* @async
*/
function getProjects(uid,callback) {
let db = new sqlite3.Database("./db/projectDB.db", (err) => {
if (err) {
console.error(err.message);
}
// console.log('Connected to the result database.');
});
let sql = `SELECT ProjectName AS projectName, ProjectCode AS projectCode, FileName AS fileName, ProjectStatus AS projectStatus, EnvelopeStatus AS envStatus, FeatureStatus AS featureStatus, SequenceStatus AS seqStatus, Description AS description, datetime(Date, 'localtime') AS uploadTime, MS1_envelope_file AS envelopeFile
FROM Projects
WHERE (ProjectStatus = 1 OR ProjectStatus = 0 OR ProjectStatus = 2) AND uid = ?;`;
db.all(sql,[uid], (err, rows) => {
if(err) {
return callback(err);
}else {
return callback(rows);
}
});
db.close();
}
module.exports = getProjects; |
import React, { PropTypes } from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './TenantAuthorityDistribution.less';
import Search from '../../../components/Search';
import SuperTree from './components/SuperTree';
import {Icon} from 'antd';
class TenantAuthorityDistribution extends React.Component {
static propTypes = {
filters: PropTypes.array,
searchConfig: PropTypes.object,
searchDataChange: PropTypes.func,
getTenantAuthority: PropTypes.func,
cleanSearchData: PropTypes.func,
notDistributionOnExpand: PropTypes.func,
notDistributionOnChecked: PropTypes.func,
distributionOnChecked: PropTypes.func,
distributionOnExpand: PropTypes.func,
searchData: PropTypes.object,
notDistributionExpand: PropTypes.object,
notDistributionChecked: PropTypes.object,
distributionExpand: PropTypes.object,
distributionChecked: PropTypes.object,
authorityMove: PropTypes.func,
};
onClick = (key) => {
switch (key) {
case 'search':
this.props.getTenantAuthority();
break;
case 'reset':
this.props.cleanSearchData();
break;
default:
break;
}
};
renderSearch() {
const props = {
config: this.props.searchConfig,
filters: this.props.filters,
onSearch: this.props.searchDataChange,
onChange: this.props.onChange,
data: this.props.searchData,
onClick: this.onClick,
};
return (<Search {...props}/>)
}
renderPublicSuperTree() {
const defaultTree = {
root: 'top',
top: {key: 'top', children: ['notDistributionTree']},
notDistributionTree: {key: 'notDistributionTree', title: '可分配权限', children: []},
};
const props = {
tree: this.props.notDistributionTree.root ? this.props.notDistributionTree : defaultTree,
expand: this.props.notDistributionExpand,
onExpand: this.props.notDistributionOnExpand,
checked: this.props.notDistributionChecked,
onCheck: this.props.notDistributionOnChecked,
};
return (<SuperTree {...props}/>);
}
renderTenantSuperTree() {
const defaultTree = {
root: 'top',
top: {key: 'top', children: ['distributionTree']},
distributionTree: {key: 'distributionTree', title: '已分配权限', children: []},
};
const props = {
tree: this.props.distributionTree.root ? this.props.distributionTree : defaultTree,
expand: this.props.distributionExpand,
onExpand: this.props.distributionOnExpand,
checked: this.props.distributionChecked,
onCheck: this.props.distributionOnChecked,
};
return (<SuperTree {...props}/>)
}
renderPage = () => {
return (
<div className={s.root}>
<div className={s.searchWrap}>
{this.renderSearch()}
</div>
<div className={s.workplace}>
<div className={s.publicAuthority}>
{this.renderPublicSuperTree()}
</div>
<div className={s.buttons}>
<Icon type="right-square" onClick={() => {this.props.authorityMove('moveIn')}} style={{fontSize:28,color:'#01a4ff'}}/>
<Icon type="left-square" onClick={() => {this.props.authorityMove('moveOut')}}style={{fontSize:28,color:'#01a4ff'}}/>
</div>
<div className={s.tenantAuthority}>
{this.renderTenantSuperTree()}
</div>
</div>
</div>
);
};
render() {
return this.renderPage();
}
}
export default withStyles(s)(TenantAuthorityDistribution);
|
const fs = require("fs");
const $elasticsearch = require('elasticsearch');
const $promise = require("bluebird");
const $elastic = function(){
let self = this;
this.client = null;
this.dbConfig = null;
this.initialized = false;
this.init = (dbConfig) => {
if(!dbConfig) dbConfig = self.dbConfig;
if(dbConfig!==null){
self.dbConfig = dbConfig;
self.client = new $elasticsearch.Client(self.dbConfig);
self.initialized = true;
self.client.ping({
requestTimeout: 30000,
}, (err) => {
if (err) {
console.error('elasticsearch cluster is down!');
}
});
}
};
this.search = (obj) => {
return new $promise((resolve, reject) => {
self.client.search(obj).then(resolve, (err) => reject(self.$$formatError(err)));
});
};
this.bulk = (obj) => {
return new $promise((resolve, reject) => {
self.client.bulk(obj).then(resolve, (err) => reject(self.$$formatError(err)));
});
};
this.buildQuery = (obj) => {
let objSearch = {
"index": `enspire.${obj.table}`,
"type" : "index",
"from" : obj.offset,
"size" : obj.limit,
"body" : {}
};
if(obj.sorts.length>0){
objSearch.body.sort=[];
obj.sorts.forEach((sort) => {
let objSort = {};
let arySortName = sort.name.split('.');
let sortName = arySortName[1];
if(typeof sort.keyName !== 'undefined'){
objSort[`${sortName}.${sort.keyName.replace(/\,/gi,'.')}`] = {"order":sort.dir.toLowerCase()}
}else{
objSort[`${sortName}`] = {"order":sort.dir.toLowerCase()}
}
objSearch.body.sort.push(objSort);
});
}
if(obj.fields.length>0){
objSearch.body._source = [];
obj.fields.forEach(field => objSearch.body._source.push(field.field.replace(obj.namespace+'.','')))
}
if(obj.groups.length>0){
let group = obj.groups[0];
let fieldName = '';
if(typeof group.keyName !== 'undefined'){
fieldName = `${group.name.replace(obj.namespace+'.','')}.${group.keyName.replace(/\,/gi,'.')}`
}else{
fieldName = group.name.replace(obj.namespace+'.','')
}
objSearch.body.collapse = {
"field" : fieldName
}
objSearch.body.aggs = {
"restfulize_group_total": {
"cardinality": {
"field": fieldName
}
}
}
}
if(obj.aggregates.length>0){
if(typeof objSearch.body.aggs === 'undefined'){
objSearch.body.aggs = {};
}
obj.aggregates.forEach((aggregate) => {
let fieldName = '';
if(typeof aggregate.keyName !== 'undefined'){
fieldName = `${aggregate.name.replace(obj.namespace+'.','')}.${aggregate.keyName.replace(/\,/gi,'.')}`
}else{
fieldName = aggregate.name.replace(obj.namespace+'.','')
}
objSearch.body.aggs[aggregate.as] = {};
objSearch.body.aggs[aggregate.as][aggregate.aggregate] = {
field: fieldName
}
});
}
let objQuery = self.$filter(obj);
if(Object.keys(objQuery.query).length>0){
objSearch.body.query = objQuery.query;
}
return objSearch;
};
this.sourcesFromHits = (resp) => {
let ary = [];
let lngHits = resp.hits.hits.length;
for(let i=0;i<lngHits;i++){
ary.push(resp.hits.hits[i]._source)
}
return ary;
};
this.$filter = (obj) => {
let objQuery = {
"query":{}
};
let search = self.$$combineAndPrepFilters(obj);
let lngStructure = search.structure.length;
let cntArg = 0;
if(lngStructure>0){
const boolFilter = (ary=[]) => {
let obj = {
"bool" : {}
};
let aryFilter = [];
let lngAry = ary.length;
for(let i=0;i<lngAry;i++) {
let filter = ary[i];
if (Array.isArray(filter)) {
aryFilter.push(boolFilter(filter));
} else {
if(filter==="arg"){
let objArg = search.fields[cntArg],
aryArgName = objArg.name.split('.'),
objArgName = aryArgName[aryArgName.length-1],
objArgValue = objArg.value,
bolIsJsonbSearch = false,
objArgument = {};
if(typeof objArg.keyName !== 'undefined'){
objArgName += `.${objArg.keyName}`;
}
objArgName = objArgName.replace(/\,/gi,'.');
/** THIS IS A NO-NO BUT WAS A QUCIK SEV 1 FIX */
if (objArgName === 'sku.code') {
aryArgValue = [objArgValue];
} else {
aryArgValue = objArgValue.split(' ')
}
switch(objArg.sep){
case '??':
strArg = objArgName+" ? '"+objArgValue+"' ";
break;
case '=#':
strArg = objArgName+"="+objArgValue+" ";
break;
case '>>':
if(aryArgValue.length>1){
objArgument = {"bool":{"must":[]}};
aryArgValue.forEach((argValue) => {
let objStatement = {"range" : {}};
objStatement.range[objArgName] = {
"gt": argValue
};
objArgument.bool.must.push(objStatement)
})
}else{
objArgument = {"range" : {}};
objArgument.range[objArgName] = {
"gt": objArgValue
};;
}
aryFilter.push(objArgument);
break;
case '<<':
if(aryArgValue.length>1){
objArgument = {"bool":{"must":[]}};
aryArgValue.forEach((argValue) => {
let objStatement = {"range" : {}};
objStatement.range[objArgName] = {
"lt": argValue
};
objArgument.bool.must.push(objStatement)
})
}else{
objArgument = {"range" : {}};
objArgument.range[objArgName] = {
"lt": objArgValue
};;
}
aryFilter.push(objArgument);
break;
case '>=':
if(aryArgValue.length>1){
objArgument = {"bool":{"must":[]}};
aryArgValue.forEach((argValue) => {
let objStatement = {"range" : {}};
objStatement.range[objArgName] = {
"gte": argValue
};
objArgument.bool.must.push(objStatement)
})
}else{
objArgument = {"range" : {}};
objArgument.range[objArgName] = {
"gte": objArgValue
};;
}
aryFilter.push(objArgument);
break;
case '<=':
if(aryArgValue.length>1){
objArgument = {"bool":{"must":[]}};
aryArgValue.forEach((argValue) => {
let objStatement = {"range" : {}};
objStatement.range[objArgName] = {
"lte": argValue
};
objArgument.bool.must.push(objStatement)
})
}else{
objArgument = {"range" : {}};
objArgument.range[objArgName] = {
"lte": objArgValue
};;
}
aryFilter.push(objArgument);
break;
case '==':
if(aryArgValue.length>1){
objArgument = {"bool":{"must":[]}};
aryArgValue.forEach((argValue) => {
let objStatement = {"term" : {}};
objStatement.term[objArgName] = objArg.caseInsensitive ? argValue.toLowerCase() : argValue;
objArgument.bool.must.push(objStatement)
})
}else{
objArgument = {"term" : {}};
objArgument.term[objArgName] = objArg.caseInsensitive ? objArgValue.toLowerCase() : objArgValue;
}
aryFilter.push(objArgument);
break;
case '@>':
strArg = objArgName+"@>'"+objArgValue+"' ";
break;
case '!=':
objArgument = {"bool":{"must_not":[]}};
if(aryArgValue.length>1){
aryArgValue.forEach((argValue) => {
let objStatement = {"term" : {}};
objStatement.term[objArgName] = objArg.caseInsensitive ? argValue.toLowerCase() : argValue;
objArgument.bool.must_not.push(objStatement)
})
}else{
let objStatement = {"term" : {}};
objStatement.term[objArgName] = objArg.caseInsensitive ? objArgValue.toLowerCase() : objArgValue;
objArgument.bool.must_not.push(objStatement)
}
aryFilter.push(objArgument);
break;
case '!^':
strArg = objArgName+" IS NOT NULL ";
break;
case '^^':
strArg = objArgName+" IS NULL ";
break;
case '%%':
if(aryArgValue.length>1){
objArgument = {"bool":{"must":[]}};
aryArgValue.forEach((argValue) => {
let objStatement = {"wildcard" : {}};
objStatement.wildcard[objArgName] = objArg.caseInsensitive ? `*${argValue.toLowerCase()}*` : `*${argValue}*`;
objArgument.bool.must.push(objStatement)
})
}else{
objArgument = {"wildcard" : {}};
objArgument.wildcard[objArgName] = objArg.caseInsensitive ? `*${objArgValue.toLowerCase()}*` : `*${objArgValue}*`;
}
aryFilter.push(objArgument);
break;
case '%a':
if(aryArgValue.length>1){
objArgument = {"bool":{"must":[]}};
aryArgValue.forEach((argValue) => {
let objStatement = {"wildcard" : {}};
objStatement.wildcard[objArgName] = objArg.caseInsensitive ? `*${argValue.toLowerCase()}` : `*${argValue}`;
objArgument.bool.must.push(objStatement)
})
}else{
objArgument = {"wildcard" : {}};
objArgument.wildcard[objArgName] = objArg.caseInsensitive ? `*${objArgValue.toLowerCase()}` : `*${objArgValue}`;
}
aryFilter.push(objArgument);
break;
case 'a%':
if(aryArgValue.length>1){
objArgument = {"bool":{"must":[]}};
aryArgValue.forEach((argValue) => {
let objStatement = {"wildcard" : {}};
objStatement.wildcard[objArgName] = objArg.caseInsensitive ? `${argValue.toLowerCase()}*` : `${argValue}*`;
objArgument.bool.must.push(objStatement)
})
}else{
objArgument = {"wildcard" : {}};
objArgument.wildcard[objArgName] = objArg.caseInsensitive ? `${objArgValue.toLowerCase()}*` : `${objArgValue}*`;
}
aryFilter.push(objArgument);
break;
}
cntArg++;
}
}
}
if(lngAry>1){
switch(ary[1]){
case '&&':
obj.bool.must = aryFilter;
break;
case '||':
obj.bool.should = aryFilter;
break;
}
}else{
obj.bool.must = aryFilter;
}
return obj;
};
objQuery.query = {
"constant_score": {
"filter": boolFilter(search.structure)
}
};
}
console.log(JSON.stringify(objQuery));
return objQuery;
};
this.$$combineAndPrepFilters = (obj) => {
const wrapFilter = (ary = [], structure = []) => {
if (structure.length > 1) {
if (structure[0] !== "(") {
structure.unshift("(");
}
if (structure[structure.length - 1] !== ")") {
structure.push(")");
}
}
if (ary.length > 0 && structure.length>0) {
ary.push('&&');
}
ary = ary.concat(structure);
return ary;
};
let structure = wrapFilter([],obj.filters.structure);
structure = wrapFilter(structure,obj._filters.structure);
structure = wrapFilter(structure,obj._auth.structure);
let fields = obj.filters.fields;
if (obj._filters.fields.length > 0) {
fields = fields.concat(obj._filters.fields);
}
if (obj._auth.fields.length > 0) {
fields = fields.concat(obj._auth.fields);
}
const parseIntoArrays = (ary=[]) => {
let structure = [],
lngAry = ary.length,
x=0;
for(x=0;x<lngAry;x++){
let item = ary[x];
if(item === ')'){
break;
}else if(item === '('){
let obj = parseIntoArrays(ary.slice(x+1));
x = x+(obj.x+1);
structure.push(obj.structure);
}else{
structure.push(item)
}
}
return {structure,x}
};
let objStructure = parseIntoArrays(structure);
structure = objStructure.structure;
console.log(structure);
return {structure,fields}
};
this.$$formatError = (err) => {
console.log(err)
return [500,{errors:[{code:3425+"",message:`Elastic Search Exception: ${err.message})`}]}];
};
this.init();
};
module.exports = new $elastic(); |
import firebase from 'firebase';
var firebaseConfig = {
/* enter your keys here */
};
// Initialize Firebase
const fire= firebase.initializeApp(firebaseConfig);
export default fire
|
export {Dashboard} from './Dashboard';
export {Profile} from './Profile';
export {Home} from './Home';
export {Services} from './Services';
|
import React from 'react';
import styled from 'styled-components';
import Card from './Card';
import { Wrapper as FormWrapper } from '../Form';
import brandRecognition from '../../../assets/icons/brand-recognition.svg';
import detailedRecords from '../../../assets/icons/detailed-records.svg';
import fullyCustomizable from '../../../assets/icons/fully-customizable.svg';
import { desktop } from '../../../styles/responsive';
import { colors } from '../../../styles/colors';
const Features = () => {
return (
<Wrapper>
<Container>
<Heading>Advanced Statistics</Heading>
<Paragraph>Track how your links are performing across the web with our
advanced statistics dashboard.</Paragraph>
<CardsContainer id="cards-container">
{data.map((el, i) => (
<CardWrapper key={i}>
<Card
id={`card-${i}`}
icon={el.icon}
heading={el.heading}
text={el.text}
/>
</CardWrapper>
))}
</CardsContainer>
</Container>
</Wrapper>
);
}
export default Features;
const Wrapper = styled(FormWrapper)`
padding: 5rem 0;
margin: 0;
&::after {
top: 0;
}
`;
const Container = styled.section`
text-align: center;
width: 86%;
max-width: 30rem;
margin: 0 auto;
@media ${desktop} {
width: 80%;
max-width: 64rem;
}
`;
const CardsContainer = styled.div`
@media ${desktop} {
display: flex;
margin-top: 4rem;
}
`;
const CardWrapper = styled.div`
&:not(:last-child) > div > div::after {
content: "";
display: block;
width: 0.5rem;
height: 3rem;
background-color: ${colors['button-bg']};
position: absolute;
left: calc(50% - 0.25rem);
bottom: -3rem;
}
@media ${desktop} {
&:first-child > div > div::after {
width: 1.75rem;
height: 0.5rem;
left: 100%;
top: 50%;
}
&:nth-child(2) {
padding-top: 2rem;
> div > div::after {
width: 1.75rem;
height: 0.5rem;
left: 100%;
top: calc(50% - 2rem);
}
}
&:last-child {
padding-top: 4rem;
}
}
`;
const Heading = styled.h2`
margin-bottom: 0.75rem;
`;
const Paragraph = styled.p`
@media ${desktop} {
max-width: 25rem;
margin: 0 auto;
line-height: 1.5rem;
}
`;
const data = [
{
icon: brandRecognition,
heading: 'Brand Recognition',
text: 'Boost your brand recognition with each click. Generic links don’t mean a thing. Branded links help instil confidence in your content.'
},
{
icon: detailedRecords,
heading: 'Detailed Records',
text: 'Gain insights into who is clicking your links. Knowing when and where people engage with your content helps inform better decisions.'
},
{
icon: fullyCustomizable,
heading: 'Fully Customizable',
text: 'Improve brand awareness and content discoverability through customizable links, supercharging audience engagement.'
}
];
|
var config = {
apiKey: "AIzaSyCCCnCJ6aApLdTJ925Sv7cxU4ov0i-ZUPg",
authDomain: "test-5e880.firebaseapp.com",
databaseURL: "https://test-5e880.firebaseio.com",
projectId: "test-5e880",
storageBucket: "test-5e880.appspot.com",
messagingSenderId: "899929819636"
};
firebase.initializeApp(config);
// Create a variable to reference the database
var database = firebase.database();
var trainDatabase = database.ref("trainDatabase");
var trainName = "";
var destination = "";
var firstTrainTime = "00:00";
var frequency = 0;
// var minutes="";
//setting variables for moment.js time manipulation
// var tFrequency = 3;
// // Time is 3:30 AM
// var firstTime = "03:30";
// First Time (pushed back 1 year to make sure it comes before current time)
var firstTimeConverted = moment(firstTrainTime, "HH:mm").subtract(1, "years");
console.log(firstTimeConverted);
// Current Time
var currentTime = moment();
console.log("CURRENT TIME: " + moment(currentTime).format("hh:mm"));
// Difference between the times
var diffTime = moment().diff(moment(firstTimeConverted), "minutes");
console.log("DIFFERENCE IN TIME: " + diffTime);
// Time apart (remainder)
console.log(typeof frequency);
console.log('freq ', frequency);
//click function that adds trains to list and adds info to Firebase
$("#add-train").on("click", function(event){
event.preventDefault();
trainName = $("#train").val().trim();
destination = $("#destination").val().trim();
firstTrainTime = $("#firstTT").val().trim();
frequency = $("#frequency").val().trim();
frequency = parseInt(frequency, 10);
// console.log(frequency);
var tRemainder = diffTime % frequency;
console.log(tRemainder);
// Minute Until Train
var tMinutesTillTrain = frequency - tRemainder;
console.log("MINUTES TILL TRAIN: " + tMinutesTillTrain);
// Next Train
var nextTrain = moment().add(tMinutesTillTrain, "minutes");
console.log("ARRIVAL TIME: " + moment(nextTrain).format("hh:mm"));
trainDatabase.push({
trainName: trainName,
destination: destination,
firstTrainTime: firstTrainTime,
frequency: frequency,
tMinutesTillTrain: tMinutesTillTrain
});
$("#train").val("");
$("#destination").val("");
$("#firstTT").val("");
$("#frequency").val(null);
});
//concatenates information into table
trainDatabase.on("child_added", function(childSnapshot){
$("tBody").append("<tr class='well'><td class='train-name'> " + childSnapshot.val().trainName +
" </td><td class='train-destination'> " + childSnapshot.val().destination +
" </td><td class='train-frequency'> " + childSnapshot.val().frequency +
" </td><td class='first-train-time'> " + childSnapshot.val().firstTrainTime +
" </td><td class='train-minutes'> " + childSnapshot.val().tMinutesTillTrain + " </td></tr>");
});
// function (errorObjects) {
// console.log("Errors handled: " + errorObject.code);
// }
//adds new listing to table
trainDatabase.orderByChild("dataAdded").limitToLast(1).on("child_added", function(snapshot) {
});
|
import { CITATION_DATA, MAP, HANDLE_SIDEBAR, START_DATE, END_DATE, ACTIVE_RANGE, DRAWING_PRESENT, POLYGON_DATA, ACTIVE_DARK } from "../constants/action-types";
const INITIAL_STATE = {
citation: null,
mapRef: null,
isSidebarOpen: false,
startDate: new Date(),
endDate: new Date(),
activateDateRange: false,
drawingPresent: false,
polygonData: null,
darkMode: window.matchMedia('(prefers-color-scheme: dark)').matches,
};
function rootReducer(state = INITIAL_STATE, action) {
switch (action.type) {
case CITATION_DATA:
return {
...state,
citation: action.payload,
};
case MAP:
return {
...state,
mapRef: action.payload,
};
case HANDLE_SIDEBAR:
return {
...state,
isSidebarOpen: action.payload,
};
case START_DATE:
return {
...state,
startDate: action.payload,
};
case END_DATE:
return {
...state,
endDate: action.payload,
};
case ACTIVE_RANGE:
return {
...state,
activateDateRange: action.payload,
};
case DRAWING_PRESENT:
return {
...state,
drawingPresent: action.payload,
};
case POLYGON_DATA:
return {
...state,
polygonData: action.payload,
};
case ACTIVE_DARK:
return {
...state,
darkMode: action.payload,
};
default:
return state;
}
}
export default rootReducer;
|
var fs = require('fs');
var path = require('path');
var EventSocket = require('/event-socket/event-socket');
var es = new EventSocket('ws://event-socket:8080/');
es.bind('open', function() {
console.log('OPENED');
var count = 0;
es.bind('pong', function(resp) {
console.log('PONG: ', resp);
setTimeout(function() {
es.send('ping', resp+=1);
}, 3000);
});
es.send('ping', count);
var testfile = "test.js";
var filestream = fs.createReadStream(testfile);
es.pipe(filestream, { filename: path.basename(testfile) });
});
|
import React from 'react';
import {ROLE} from "../common/constants";
import {connect} from "react-redux";
import {fetchEmployee} from "../actions/EmployeeAction";
const mapDispatchToProps = dispatch => {
return {
fetchEmployee: id => dispatch(fetchEmployee(id))
};
};
const mapStateToProps = (state) => {
return {employee : state.employeeReducer.employee};
};
class HomeComponent extends React.Component{
constructor(props)
{
super(props);
this.props.fetchEmployee("admin");
}
setRole(){
switch( this.props.employee.role ){
case ROLE.ADMIN :
this.props.history.push("/admin");
break;
case ROLE.TRAINER :
this.props.history.push("/trainer");
break;
default :
this.props.history.push("/participant");
break;
}
}
render() {
if(this.props.employee.role) {
this.setRole();
return(
<div></div>
);
}
return(
<div>Loading...</div>
);
}
}
const RoutingComponent = connect(mapStateToProps, mapDispatchToProps)(HomeComponent);
export default RoutingComponent;
|
angular.module("TeacherController", [])
.controller("teacherController", function ($scope, UserService, $log, $window) { }); |
import StyledDocument from '../components/StyledDocument';
export default class Document extends StyledDocument {}
|
import React from "react"
import styled from "styled-components"
import { navigate } from "gatsby"
import Headline3 from "../../Headlines/Headline3"
import BaseButton from "../../Shared/Buttons/BaseButton"
import IgniteOneTwoCards from "./IgniteOneTwoCards"
import IgniteThreeFourCards from "./IgniteThreeFourCards"
import { above } from "../../../styles/Theme"
const BenefitSection = () => {
const handlePageScroll = () => navigate("/ignite-form")
return (
<BenefitContainer>
<HeadlineWrapper>
<BaseButton handleClick={handlePageScroll}>
Lock In Your Spot Today!
</BaseButton>
<Headline3>As an Ignite Member You Get:</Headline3>
</HeadlineWrapper>
<IgniteOneTwoCards />
<IgniteThreeFourCards />
</BenefitContainer>
)
}
export default BenefitSection
const BenefitContainer = styled.div`
margin: 60px 0 0 0;
padding: 0 12px;
display: flex;
flex-direction: column;
align-items: center;
${above.tablet`
padding: 0;
`}
`
const HeadlineWrapper = styled.div`
display: grid;
grid-template-columns: 1fr;
gap: 60px;
width: 100%;
`
|
import React, { useState } from 'react';
import Header from '../Header-Footer/Header';
import { searchByNumber } from '../../utils/api';
import Reservation from '../dashboard/Reservation.js'
import ErrorAlert from '../main/ErrorAlert';
export default function Search() {
const [reservations, setReservations] = useState([])
async function searchHandler() {
const searchValue = document.querySelector("input").value
setReservations(await searchByNumber(searchValue))
}
reservations.forEach((res) => res.reservation_date = res.reservation_date.substring(0, 10))
return (
<div>
<Header page="Search" />
<div className='d-flex justify-content-center my-5'>
<label className='text-white mx-2' htmlFor='phone-number'>Phone Number</label>
<input
required
className='w-25 text-center'
type='text'
id='phone-number'
placeholder="Enter a customer's phone number"
/>
<button className='mx-4' onClick={searchHandler}>Search</button>
</div>
<div className='text-center d-flex flex-column justify-content-center'>
{reservations.length === 0 && <ErrorAlert error={{message: 'No reservations found'}} />}
{(reservations.map((reservation) => <Reservation reservation={reservation} />))}
</div>
</div>
)
} |
const express=require("express")
const mysql=require("mysql")
const DATA_BASE=require("../CONFIG/DATA_BASE.js")
const link=mysql.createPool(DATA_BASE)
module.exports=function(){
const server=express.Router()
server.use("/",function(request,response){
const {cid,company,contact,Email,address}=request.body;
const {userMSG}=Object.assign({},request.session);
const sql=`
UPDATE customer SET
company='${company}',
contact='${contact}',
Email='${Email}',
address='${address}'
WHERE uid='${userMSG.uid}'
AND time='${cid}'
`;
new Promise(function(resolve,reject){
link.query(sql,function(err){
if(!err){resolve()}else{reject(err)}
})
}).then(function(){
response.send({result:true})
}).catch(function(err){
console.log(err)
response.send({result:false,error:err})
})
})
return server
} |
import React from "react";
import { makeStyles, useTheme } from '@material-ui/core/styles';
import Grid from '@material-ui/core/Grid';
import Typography from '@material-ui/core/Typography';
import WP from 'utils/wordpress';
import CardActionArea from "@material-ui/core/CardActionArea";
import dynamic from 'next/dynamic';
import { format, parse } from 'date-fns';
const Item = dynamic(() => import('components/home/newsfeed-item'));
import Button from 'components/Button';
import { cdnURL } from 'utils/constants';
const useStyles = makeStyles((theme) => ({
contentContainer: {
width: '80%',
margin: 'auto'
},
rootContainer: {
width: '100%',
margin: 0
},
footerContainer: {
width: '100%',
paddingTop: 100,
paddingBottom: 100,
backgroundImage: 'linear-gradient(to right, #1637BC, #2D8AEA)',
color: theme.palette.secondary.main
},
bannerContainer: {
minHeight: '30vh',
backgroundPosition: 'center bottom',
backgroundSize: 'cover',
backgroundImage: 'url(https://samahan.stdcdn.com/21-22/landing.png), linear-gradient(to right, #1637BC, #2D8AEA)',
paddingLeft: 'clamp(50px, 10vw, 100px)',
paddingRight: 'clamp(50px, 10vw, 100px)',
color: 'white'
},
rootContainer: {
width: '100%',
marginBottom: 0
},
checkOutContainer: {
marginLeft: '20vw'
},
pictureContainer: {
display: 'none',
[theme.breakpoints.up('sm')]: {
display: 'block',
},
},
link: {
textDecoration: 'none'
}
}));
const Page = ({ archives }) => {
// Get the data of the current list.
const classes = useStyles();
const theme = useTheme();
return (
<div className={classes.rootContainer}>
<Grid container direction="column" spacing={3} alignItems="center" justify="center" className={classes.bannerContainer}>
<Grid item style={{ textAlign: 'center' }}>
<Typography variant="h2" style={{ lineHeight: '0.8em' }}>
STUDENT ASSEMBLY
</Typography>
<Typography variant="h3">
ARCHIVES
</Typography>
</Grid>
</Grid>
<div style={{ height: 50 }} />
{/* Insert header here! */}
<div className={classes.contentContainer} style={{ marginBottom: 100, paddingTop: '4rem', paddingBottom: '4rem' }}>
<Grid container direction="column" spacing={3} alignItems="stretch">
{archives.map((archive, i) => {
// Render one Item component for each one.
return (
<Grid item style={{ backgroundColor: i % 2 === 1 ? 'rgb(242, 242, 242)' : 'white', padding: 0, borderRadius: 20 }} key={archive.id}>
<CardActionArea onClick={() => window.open(archive.acf.document_file, '_blank')} style={{ borderRadius: 20 }}>
<Grid container direction="column" style={{ padding: theme.spacing(2) }} spacing={1}>
<Grid item>
<Typography variant="h5" className={classes.link} style={{ color: theme.palette.primary.main }}>{archive.title.rendered}</Typography>
</Grid>
<Grid item>
<Typography className={classes.link}>{format(parse(archive.acf.date, 'dd/MM/yyyy', new Date()), 'MMMM d, yyyy')}</Typography>
</Grid>
</Grid>
</CardActionArea>
</Grid>
);
})}
</Grid>
</div>
</div>
);
};
export async function getStaticProps(ctx) {
try {
const res = await WP.archives().perPage(100);
if (res) {
return { props: { archives: res }, revalidate: 10 };
} else {
return { props: { archives: [] }, revalidate: 10 };
}
} catch (err) {
return { props: { archives: [] }, revalidate: 10 };
}
}
export default Page; |
var express = require('express');
var router = express.Router();
router.use(express.json());
const mongodbModel = require("../models/mongodb.js");
mongodbModel.get
router.post("/rest/input/ai/", (req,res,next) => {
});
router.post("/email", async (req,res) => {
try {
mongodbModel.postemaildata(req.body);
res.sendStatus(200)
} catch (err) {
res.status(500).json({message: err.message})
}
});
router.post("/rest/input/sensors/", (req,res,next) => {
if (typeof req.body.token == 'undefined') {
res.sendStatus(401)
} else {
if (req.body.token == process.env['dbpass']) {
mongodbModel.postsensordata(req.body);
res.sendStatus(200)
} else {
res.sendStatus(401)
}
}
});
router.post("/rest/input/articles/", (req,res,next) => {
if (typeof req.body.token == 'undefined') {
res.sendStatus(401)
} else {
if (req.body.token == process.env['dbpass']) {
mongodbModel.postarticledata(req.body);
res.sendStatus(200)
} else {
res.sendStatus(401)
}
}
});
router.post("/rest/input/alerts/", (req,res,next) => {
if (typeof req.body.token == 'undefined') {
res.sendStatus(401)
} else {
if (req.body.token == process.env['dbpass']) {
mongodbModel.postalertdata(req.body);
res.sendStatus(200)
} else {
res.sendStatus(401)
}
}
});
router.get("/rest/output/sensors", async (req,res, next) => {
const data = await mongodbModel.getsensordata()
res.send(data)
});
router.get("/rest/output/formnumberofresponses", async (req,res, next) => {
const data = await mongodbModel.countformdata()
res.send(data)
});
router.get("/rest/output/queriedsensors", async (req,res, next) => {
const data = await mongodbModel.querysensordata(req.body.minutesago)
res.send(data)
});
router.get("/rest/output/articles", async (req,res, next) => {
const data = await mongodbModel.getarticlesdata()
res.send(data)
});
router.get("/rest/output/article", async (req,res, next) => {
const data = await mongodbModel.getarticledata(req.headers.title)
res.send(data[0])
});
router.get("/rest/output/alerts", async (req,res, next) => {
const data = await mongodbModel.getalertsdata()
res.send(data)
});
router.get("/rest/output/forms", async (req,res, next) => {
const data = await mongodbModel.getformsdata()
res.send(data)
});
router.get("/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret", async (req,res, next) => {
res.send({"Somehow wrapping this message in JSON makes it display better on mobile": "🤫 The existence of this page is a massive secret.\nWant more secrets?\nTry Caesar shifting an all-lowercase version of our team name (without space or puncatuations). There is a page at one of these locations.\n(also try appending team member names at the end of this api call path)"})
});
router.get("/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/david", async (req,res, next) => {
res.send({"github": "null / unknown / boring", "message": "🤫 Shhhh David is ANGRY!", "biggest_comtribution": "The boss and bogeyman."})
});
/*
https://dev-test.projecteco.ml/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/david
*/
router.get("/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/dylan", async (req,res, next) => {
res.send({"github": "normal / boring", "message": "🤫 Shhhh Dylan raving about Drehmal!", "biggest_comtribution": "The worldwide web."})
});
router.get("/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/george", async (req,res, next) => {
res.send({"github": "filamity", "message": "🤫 Shhhh Geroge is working!", "biggest_comtribution": "The walrus / https://youtu.be/k7YVxLLIuGM"})
});
router.get("/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/vincent", async (req,res, next) => {
res.send({"github": "null / unknown / boring", "message": "🤫 Shhhh What a G!", "biggest_comtribution": "You reading this rn."})
});
router.get("/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret/secret", async (req,res, next) => {
res.send({"Somehow wrapping this message in JSON makes it display better on mobile": "🤷 Are you bored yet?"})
});
module.exports = router;
|
import React from 'react';
import styled from 'styled-components';
import { addQuote } from '../actions/quotes';
function loadQuote(){
return <div>
<button onClick={addQuote}>LOAD QUOTE</button>
</div>
}
export default loadQuote; |
// OLD -- (function() {
/*global ODSA */
"use strict";
$(document).ready(function () {
var av_name = "BetaAppCON";
var interpret = ODSA.UTILS.loadConfig({"av_name": av_name}).interpreter;
var av = new JSAV(av_name);
var x = 0; var y = 0;
// var av = new JSAV("av");
var stepOne = ["(", "λx.", "(", "x", "x", ")", "(", "λy.", "y", "z", ")", ")"];
var stepTwo = ["(", "λx.", "(", "x", "x", ")", "z", ")"];
var stepThree = ["(", "z", "z", ")"];
// av.label("β-Reduction Matrix");
av.label("$\\beta$-Reduction");
var m1 = av.ds.matrix([stepOne, stepTwo, stepThree], {style: "plain"});
for(y = 0; y < 12; y++)
{
m1.css(x, y, {"background-color": "#eed"});
}
x = 1;
for(y = 0; y < 8; y++)
{
m1.css(x, y, {"background-color": "#eed", "color": "#eed"});
}
x = 2;
for(y = 0; y < 4; y++)
{
m1.css(x, y, {"background-color": "#eed", "color": "#eed"});
}
m1.css(0, 8, {"text-align": "left"});
m1.layout();
av.umsg("This slideshow will go through the process of reducing a lambda calculus expression using applicative-order β-reduction.");
av.displayInit();
m1.css(0, 7, {"background-color": "aqua", "color": "rgb(0,0,0)"});
av.umsg("First, we need to identify the first lambda variable. Since we are doing applicative-order reduction, this is the innermost variable.");
av.step();
m1.css(0, 9, {"background-color": "pink", "color": "rgb(0,0,0)"});
av.umsg("Next, we need to identify the argument being passed into the variable.");
av.step();
m1.css(0, 8, {"background-color": "lightgreen", "color": "rgb(0,0,0)"});
av.umsg("Then we look at the body of the function that we are passing the argument to...");
av.step();
av.umsg("...and we go through the body and make note of each instance of the variable inside the body (which is easy in this case because the body is only one variable)...");
av.step();
x = 1;
for(y = 0; y < 8; y++)
{
m1.css(x, y, {"background-color": "#eed", "color": "rgb(0,0,0)"});
}
m1.css(1, 6, {"background-color": "lightgreen", "color": "rgb(0,0,0)"});
av.umsg("...which we replace with the argument.");
av.step();
m1.css(1, 6, {"background-color": "#eed", "color": "rgb(0,0,0)"});
av.umsg("Since there are no more instances of the lambda variable within the body, we have completed one β-reduction!");
av.step();
m1.css(0, 7, {"background-color": "#eed", "color": "rgb(0,0,0)"});
m1.css(0, 8, {"background-color": "#eed", "color": "rgb(0,0,0)"});
m1.css(0, 9, {"background-color": "#eed", "color": "rgb(0,0,0)"});
av.umsg("However, there are still more reductions to be done...");
av.step();
m1.css(1, 1, {"background-color": "aqua", "color": "rgb(0,0,0)"});
av.umsg("So we must identify the next lambda variable...");
av.step();
m1.css(1, 6, {"background-color": "pink", "color": "rgb(0,0,0)"});
av.umsg("...and the argument that will be passed into it.");
av.step();
m1.css(1, 2, {"background-color": "lightgreen", "color": "rgb(0,0,0)"});
m1.css(1, 3, {"background-color": "lightgreen", "color": "rgb(0,0,0)"});
m1.css(1, 4, {"background-color": "lightgreen", "color": "rgb(0,0,0)"});
m1.css(1, 5, {"background-color": "lightgreen", "color": "rgb(0,0,0)"});
av.umsg("Then we look at the body of the function...");
av.step();
m1.css(1, 2, {"background-color": "#eed", "color": "rgb(0,0,0)"});
m1.css(1, 5, {"background-color": "#eed", "color": "rgb(0,0,0)"});
av.umsg("...and we make note of each instance of the variable inside of the body of the function...");
av.step();
x = 2;
for(y = 0; y < 4; y++)
{
m1.css(x, y, {"background-color": "#eed", "color": "rgb(0,0,0)"});
}
m1.css(2, 1, {"background-color": "lightgreen", "color": "rgb(0,0,0)"});
m1.css(2, 2, {"background-color": "lightgreen", "color": "rgb(0,0,0)"});
av.umsg("...and we replace them with the argument!");
av.step();
x = 1;
for(y = 0; y < 8; y++)
{
m1.css(x, y, {"background-color": "#eed", "color": "#eed"});
}
m1.css(2, 1, {"background-color": "#eed", "color": "rgb(0,0,0)"});
m1.css(2, 2, {"background-color": "#eed", "color": "rgb(0,0,0)"});
av.umsg("And with that we have completed a full β-reduction and we have a simplified expression!");
av.recorded();
});
// OLD -- }()); |
var besgamApp = angular
/************************************************************************/
/* Aplicación */
/************************************************************************/
/* Modulo */
.module( "besgam", ["wp.api", "infinite-scroll", "pascalprecht.translate", "tmh.dynamicLocale", "ngSanitize", "vcRecaptcha", "ngAnimate", "ui.bootstrap", "ui.bootstrap.tpls", "ngTagsInput", "angularRangeSlider", "nvd3", "angulartics", "angulartics.google.tagmanager", "angular-flexslider", "slick", "visibilityChange", "duScroll", "ngImgCrop"], function( $httpProvider )
{
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
})
/* Configuración */
.config( ["$translateProvider", "tmhDynamicLocaleProvider", "pathProvider", function( $translateProvider, tmhDynamicLocaleProvider, pathProvider )
{
pathProvider.set("http://www.besgam.com/blog/wp-json/wp/v2");
$translateProvider
.useLoader( "angularTranslateAsyncLoader" )
.useSanitizeValueStrategy('escaped')
.usePostCompiling(true);
tmhDynamicLocaleProvider.localeLocationPattern( "/src/lib/locale/angular-locale_{{ locale }}.js" );
//tmhDynamicLocaleProvider.localeLocationPattern( "https://code.angularjs.org./1.5.0/i18n/angular-locale_{{ locale }}.js");
}])
/* Inicio */
.run(["$templateCache", "$rootScope", "$filter", "uibPaginationConfig", "uibPagerConfig", "VisibilityChange", function( $templateCache, $rootScope, $filter, uibPaginationConfig, uibPagerConfig, VisibilityChange )
{
VisibilityChange.configure({broadcast: true});
$templateCache.put("uib/template/rating/rating.html", '<span ng-mouseleave="reset()" ng-keydown="onKeydown($event)" tabindex="0" role="slider" aria-valuemin="0" aria-valuemax="{{range.length}}" aria-valuenow="{{value}}">\n <span ng-repeat-start="r in range track by $index" class="sr-only">({{ $index < value ? \'*\' : \' \' }})</span>\n <i ng-repeat-end ng-mouseenter="enter($index + 1)" ng-click="rate($index + 1)" class="star-rating" ng-class="$index < value && (r.stateOn || \'fa-star\') || (r.stateOff || \'fa-star-o\')" ng-attr-title="{{r.title}}" aria-valuetext="{{r.title}}"></i>\n</span>\n');
// $rootScope.$on("$routeChangeStart", function()
// {
// window.scrollTo(0,0);
// });
$rootScope.$on('$translateChangeSuccess', function()
{
uibPaginationConfig.previousText = $filter('translate')('pagination.previous');
uibPaginationConfig.nextText = $filter('translate')('pagination.next');
uibPagerConfig.previousText = $filter('translate')('pagination.previous');
uibPagerConfig.nextText = $filter('translate')('pagination.next');
});
FastClick.attach(document.body);
}])
/************************************************************************/
/* TIPSTER */
/************************************************************************/
// .controller('tipsterGraphic', function( $scope )
// {
// $scope.options = {
// chart: {
// type: 'pieChart',
// height: 450,
// donut: true,
// x: function(d)
// {
// return d.key;
// },
// y: function(d)
// {
// return d.y;
// },
// showLabels: true,
// pie:
// {
// startAngle: function(d)
// {
// return d.startAngle/2 -Math.PI/2
// },
// endAngle: function(d)
// {
// return d.endAngle/2 -Math.PI/2
// }
// },
// duration: 500,
// color: ['#179ab5','#6bbbbc'],
// showLegend: false,
// }
// };
// $scope.data = [
// {
// key: "Acumulado",
// y: 5
// },
// {
// key: "Falta",
// y: 2
// }
// ];
// $scope.Rssoptions = {
// chart: {
// type: 'pieChart',
// height: 450,
// x: function(d){return d.key;},
// y: function(d){return d.y;},
// showLabels: true,
// duration: 500,
// labelThreshold: 0.01,
// labelSunbeamLayout: true,
// showLegend: false,
// color: ['#e59c46','#09789d','#ff6364','#32bca7']
// }
// };
// $scope.Rssdata = [
// {
// key: "Facebook",
// y: 2
// },
// {
// key: "Twitter",
// y: 2
// },
// {
// key: "Besgam",
// y: 9
// },
// {
// key: "Seguidores",
// y: 7
// }
// ];
// $scope.earnOptions = {
// chart: {
// type: 'cumulativeLineChart',
// height: 250,
// margin : {
// top: 20,
// right: 20,
// bottom: 60,
// left: 65
// },
// x: function(d){ return d[0]; },
// y: function(d){ return d[1]/100; },
// average: function(d) { return d.mean/100; },
// color: d3.scale.category10().range(),
// duration: 300,
// useInteractiveGuideline: true,
// clipVoronoi: false,
// xAxis: {
// axisLabel: 'X Axis',
// tickFormat: function(d) {
// return d3.time.format('%m/%d/%y')(new Date(d))
// },
// showMaxMin: false,
// staggerLabels: true
// },
// yAxis: {
// axisLabel: 'Y Axis',
// tickFormat: function(d){
// return d3.format(',.1%')(d);
// },
// axisLabelDistance: 20
// },
// showLegend: false,
// showYAxis: false,
// showXAxis: false
// }
// };
// $scope.earndata = [
// {
// key: "Seguidores",
// values: [
// [ 1083297600000 , 0] ,
// [ 1085976000000 , 10] ,
// [ 1088568000000 , 30] ,
// [ 1091246400000 , 50] ,
// [ 1093924800000 , 63] ,
// [ 1096516800000 , 64] ,
// [ 1099195200000 , 64] ,
// [ 1101790800000 , 64] ,
// [ 1104469200000 , 64] ,
// [ 1107147600000 , 70] ,
// [ 1109566800000 , 71] ,
// [ 1112245200000 , 72] ,
// [ 1114833600000 , 72] ,
// [ 1117512000000 , 74] ,
// [ 1120104000000 , 75] ,
// [ 1122782400000 , 78] ,
// [ 1125460800000 , 78] ,
// [ 1128052800000 , 90] ,
// [ 1130734800000 , 91] ,
// [ 1133326800000 , 95] ,
// [ 1136005200000 , 97] ,
// [ 1138683600000 , 127] ,
// [ 1141102800000 , 128] ,
// [ 1143781200000 , 130] ,
// [ 1146369600000 , 140] ,
// [ 1149048000000 , 156] ,
// [ 1151640000000 , 179] ,
// [ 1154318400000 , 190] ,
// [ 1156996800000 , 210] ,
// ],
// mean: 250
// },
// {
// key: "Facebook",
// values: [
// [ 1083297600000 , 0] ,
// [ 1085976000000 , 1] ,
// [ 1088568000000 , 3] ,
// [ 1091246400000 , 5] ,
// [ 1093924800000 , 10] ,
// [ 1096516800000 , 20] ,
// [ 1099195200000 , 21] ,
// [ 1101790800000 , 40] ,
// [ 1104469200000 , 50] ,
// [ 1107147600000 , 50] ,
// [ 1109566800000 , 53] ,
// [ 1112245200000 , 59] ,
// [ 1114833600000 , 63] ,
// [ 1117512000000 , 64] ,
// [ 1120104000000 , 66] ,
// [ 1122782400000 , 73] ,
// [ 1125460800000 , 71] ,
// [ 1128052800000 , 71] ,
// [ 1130734800000 , 77] ,
// [ 1133326800000 , 95] ,
// [ 1136005200000 , 107] ,
// [ 1138683600000 , 127] ,
// [ 1141102800000 , 122] ,
// [ 1143781200000 , 126] ,
// [ 1146369600000 , 132] ,
// [ 1149048000000 , 133] ,
// [ 1151640000000 , 133] ,
// [ 1154318400000 , 133] ,
// [ 1156996800000 , 133] ,
// ],
// mean: -60
// },
// {
// key: "Twitter",
// mean: 125,
// values: [
// [ 1083297600000 , 0] ,
// [ 1085976000000 , 85] ,
// [ 1088568000000 , 86] ,
// [ 1091246400000 , 86] ,
// [ 1093924800000 , 86] ,
// [ 1096516800000 , 86] ,
// [ 1099195200000 , 99] ,
// [ 1101790800000 , 99] ,
// [ 1104469200000 , 99] ,
// [ 1107147600000 , 99] ,
// [ 1109566800000 , 122] ,
// [ 1112245200000 , 122] ,
// [ 1114833600000 , 123] ,
// [ 1117512000000 , 125] ,
// [ 1120104000000 , 130] ,
// [ 1122782400000 , 130] ,
// [ 1125460800000 , 130] ,
// [ 1128052800000 , 130] ,
// [ 1130734800000 , 142] ,
// [ 1133326800000 , 143] ,
// [ 1136005200000 , 143] ,
// [ 1138683600000 , 243] ,
// [ 1141102800000 , 243] ,
// [ 1143781200000 , 245] ,
// [ 1146369600000 , 245] ,
// [ 1149048000000 , 245] ,
// [ 1151640000000 , 246] ,
// [ 1154318400000 , 350] ,
// [ 1156996800000 , 363] ,
// ]
// },
// {
// key: "Besgam",
// values: [
// [ 1083297600000 , 60] ,
// [ 1085976000000 , 65] ,
// [ 1088568000000 , 65] ,
// [ 1091246400000 , 65] ,
// [ 1093924800000 , 66] ,
// [ 1096516800000 , 67] ,
// [ 1099195200000 , 68] ,
// [ 1101790800000 , 68] ,
// [ 1104469200000 , 68] ,
// [ 1107147600000 , 68] ,
// [ 1109566800000 , 72] ,
// [ 1112245200000 , 89] ,
// [ 1114833600000 , 89] ,
// [ 1117512000000 , 89] ,
// [ 1120104000000 , 89] ,
// [ 1122782400000 , 89] ,
// [ 1125460800000 , 92] ,
// [ 1128052800000 , 92] ,
// [ 1130734800000 , 95] ,
// [ 1133326800000 , 96] ,
// [ 1136005200000 , 97] ,
// [ 1138683600000 , 105] ,
// [ 1141102800000 , 125] ,
// [ 1143781200000 , 125] ,
// [ 1146369600000 , 125] ,
// [ 1149048000000 , 139] ,
// [ 1151640000000 , 147] ,
// [ 1154318400000 , 148] ,
// [ 1156996800000 , 180] ,
// ],
// mean: 250
// }
// ];
// })
// .controller('tipsterGallery', function( $scope, $translate )
// {
// $scope.tipGallery = [
// {
// image: '/img/besgam-icons/icons/gallery-tipster-1.jpg',
// title: "tipster.howWork.gallery.title1",
// text: "tipster.howWork.gallery.text1"
// },
// {
// image: '/img/besgam-icons/icons/gallery-tipster-2.jpg',
// title: "tipster.howWork.gallery.title2",
// text: "tipster.howWork.gallery.text2"
// },
// {
// image: '/img/besgam-icons/icons/gallery-tipster-3.jpg',
// title: "tipster.howWork.gallery.title3",
// text: "tipster.howWork.gallery.text3"
// }
// ];
// // $translate('tipster.howWork.gallery.text3').then(function (translation) // "Deporte";
// // {
// // $scope.titleSport = translation;
// // });
// $scope.aBefore = function()
// {
// $scope.varPrueba=true;
// }
// $scope.aAfter = function()
// {
// $scope.varPrueba = false;
// }
// })
// .controller('tipsterFile', function( $scope, dataFactory, $route, tipster, tipsterOdds )
// {
// /* Instanciamos */
// $scope.aOdds = [];
// dataFactory.getDataFeed().then( function(res)
// {
// $scope.feed = res.data;
// /* Param identificador del tipster relacionado con el param del app.es */
// var nick = $route.current.params.nick;
// /* llamada al servicio */
// tipster.data($route.current.params.nick)
// .then(function(res)
// {
// $scope.tipster = {};
// if( typeof res != 'undefined' )
// {
// var cTips,
// hTips,
// data = res[0];
// tipster.gTips(data.tipster, 'C')
// .then(function(res)
// {
// cTips = res;
// tipster.gTips(data.tipster, 'H')
// .then(function(res)
// {
// hTips = res;
// $scope.tipster = {
// data: data,
// cTips: cTips,
// hTips: hTips
// };
// });
// });
// }
// });
// $scope.getOdds = function( index, value )
// {
// /* llamamos al servicio */
// tipsterOdds.tipBets( value, $scope.feed )
// .then(function(res)
// {
// $scope.aOdds[index] = res;
// });
// }
// var statisticData = function( obj )
// {
// var arr = [];
// angular.forEach(obj, function(value, key)
// {
// this.push({
// key: key,
// value: value
// });
// }, arr);
// return arr;
// };
// });
// })
// .controller('tipster', function($scope, dataFactory, $route, tipsterOdds, tipster)
// {
// $scope.aOdds = [];
// $scope.events = [];
// $scope.filterEvent = [];
// $scope.selectedInput = {};
// $scope.$on( 'LOAD', function(){ $scope.loading = true } );
// $scope.$on( 'UNLOAD', function(){ $scope.loading = false } );
// $scope.$emit('LOAD');
// $scope.rangeOdd = [
// { odd: 1.1 },
// { odd: 1.2 },
// { odd: 1.4 },
// { odd: 1.6 },
// { odd: 1.8 },
// { odd: 2.0 },
// { odd: 2.2 },
// { odd: 2.5 },
// { odd: 3.0 },
// { odd: 3.5 },
// { odd: 4.0 },
// { odd: 4.5 },
// { odd: 5.0 },
// { odd: 6.0 },
// { odd: 7.0 },
// { odd: 8.0 },
// { odd: 9.0 },
// { odd: 10.0 },
// { odd: 15.0 },
// { odd: 20.0 },
// { odd: 100}
// ];
// $scope.item = [{
// name : 'RangeOddLow',
// value : 0
// },
// {
// name : 'rangeOddHigh',
// value : 20
// }];
// $scope.getOdds = function( id )
// {
// var itemData = $scope.items[id],
// // declaramos la variable aSendData como un array
// aSendData = [];
// // recorremos el array
// for( var nCont = 0, len = itemData.bet.length;
// nCont < len;
// nCont++)
// {
// // cortamos la cadena por los " | "
// var aTokens = itemData.bet[nCont];
// // formamos un objeto y le hacemos un push de los cortes de aTokens para poderlos usar
// aSendData.push( aTokens );
// }
// // llamamos al servicio
// tipsterOdds.tipBets( aSendData, $scope.feed )
// .then(function(res)
// {
// $scope.aOdds[id] = res;
// },
// function(err)
// {
// $scope.aOdds[id].push(res);
// });
// };
// dataFactory.getDataFeed().then( function(res)
// {
// $scope.feed = res.data;
// dataFactory.getDataJson().then( function(res)
// {
// /* Paginación */
// $scope.currentPage = 1;
// $scope.numPerPage = 10;
// $scope.maxSize = 5;
// $scope.setPage = function (pageNo)
// {
// window.scrollTo(0,0);
// $scope.currentPage = pageNo;
// };
// $scope.events = res.data; //todos los eventos
// $scope.filterEvent = res.data; //todos los eventos que ya están filtrados
// $scope.events.map(function(it)
// {
// if( it.markets != null )
// it.tips = parseInt(it.markets.str_bet['1'][0].n_odd);
// else
// it.tips = 0;
// });
// /* Ordenación */
// var orderObj = ['-tips','orderTime'];
// $scope.setOrdered = function( obj )
// {
// orderObj = obj;
// };
// $scope.ordered = function()
// {
// return orderObj;
// };
// $scope.changeOrder = function()
// {
// if( $scope.selectedInput.date == 1 && $scope.selectedInput.tips == 1 )
// {
// $scope.setOrdered(['tips','-orderTime']);
// }
// else if( $scope.selectedInput.date == 1 && $scope.selectedInput.tips != 1 )
// {
// $scope.setOrdered(['-tips','-orderTime']);
// }
// else if( $scope.selectedInput.date != 1 && $scope.selectedInput.tips != 1 )
// {
// $scope.setOrdered(['-tips','orderTime']);
// }
// else
// {
// $scope.setOrdered(['tips','orderTime']);
// }
// };
// /* Ordenación top tipsters acierto, deporte, beneficio, seguidores */
// var orderTip = ['ranking', '-tips.ok', '!-sport[1]', '-sport[1]', '-benefit','-followers'];
// $scope.setOrderedTip = function( obj )
// {
// orderTip = obj;
// };
// $scope.orderedTip = function()
// {
// return orderTip;
// };
// $scope.changeTipster = function( filter )
// {
// if( filter.substring(0, 7) == '-sport[' ) //cogemos los caracateres del string entre las posiciones 0 y 5 y comprobamos que sea igual a sport[
// {
// orderTip.map( function ( value, index ) //VALUE es el elemento actual del array que se está procesando // INDEX posición actual del value
// {
// if( value.substring(0, 7) == '-sport[' || value.substring(0, 8) == '!-sport[' )
// orderTip.splice( index, 1 ); //Slice() elimina elementos del array, tanto como hayas indicado en los parámetros
// });
// orderTip.unshift( filter ); //unshift añade elementos al principio del array
// orderTip.unshift( '!'+filter ); //unshift añade elementos al principio del array
// }
// else
// {
// var filterAux;
// //buscamos el caracter '_' Si no lo tiene, lo añade y viceversa
// if( filter.charAt(0) != '-' )
// filterAux = '-'+filter;
// else
// filterAux = filter.substr(1);
// //Recorremos el array orderTip
// orderTip.map( function ( value, index ) //VALUE es el elemento actual del array que se está procesando // INDEX posición actual del value
// {
// if( filter == value || filterAux == value )
// {
// orderTip.splice( index, 1 ); //Slice() elimina elementos del array, tanto como hayas indicado en los parámetros
// orderTip.unshift( filter ); //unshift añade elementos al principio del array
// }
// });
// }
// };
// /* Deportes */
// $scope.prematchSports = $scope.events.reduce(function(sum, place)
// {
// if(sum.indexOf( place.sportID ) < 0) sum.push( place.sportID );
// return sum;
// }, []);
// /* Lista de ligas */
// listPrematchLeagues();
// $scope.$emit('UNLOAD');
// });
// });
// var listPrematchDataFilter = function( data )
// {
// var dataFilter = [];
// if( $scope.selectedInput.league != "" )
// {
// angular.forEach(data, function(value, key)
// {
// if( value.league == $scope.selectedInput.league )
// dataFilter.push(value);
// });
// }
// else if( $scope.selectedInput.sport != "" )
// {
// angular.forEach(data, function(value, key)
// {
// if( value.sportID == $scope.selectedInput.sport )
// dataFilter.push(value);
// });
// }
// else
// {
// dataFilter = data;
// }
// return changeRange(dataFilter);
// };
// var listPrematchLeagues = function()
// {
// $scope.prematchLeagues = $scope.events.reduce(function(sum, place)
// {
// if( place.league != null )
// {
// if( $scope.selectedInput.sport && $scope.selectedInput.sport != "" )
// {
// if (sum.indexOf( place.league ) < 0 && $scope.selectedInput.sport == place.sportID )
// sum.push( place.league );
// }
// else
// {
// if (sum.indexOf( place.league ) < 0)
// sum.push( place.league );
// }
// }
// return sum;
// }, []);
// };
// var changeRange = function( data )
// {
// var dataFilter = [];
// angular.forEach( data, function(value, key)
// {
// var fInsert = false;
// if( value.markets )
// {
// angular.forEach( value.markets.str_bet, function( bet, keyBet)
// {
// if( bet[0].n_odd <= parseFloat($scope.rangeOdd[$scope.item[1].value].odd) && bet[0].n_odd >= parseFloat($scope.rangeOdd[$scope.item[0].value].odd) ) fInsert = true;
// });
// }
// else
// fInsert = true
// if( fInsert ) dataFilter.push( value );
// });
// return dataFilter;
// };
// $scope.changeListPrematch = function()
// {
// /* Lista de ligas */
// listPrematchLeagues();
// $scope.filterEvent = listPrematchDataFilter($scope.events );
// };
// tipster.data()
// .then(function(res)
// {
// $scope.tipster = res;
// /* Paginación */
// $scope.currentTipsterPage = 1;
// $scope.numTipPerPage = 8;
// $scope.maxSize = 5;
// $scope.setTipPage = function (pageNo)
// {
// window.scrollTo(0,0);
// $scope.currentTipsterPage = pageNo;
// };
// });
// $scope.viewPredictions = function(index, eventID)
// {
// $scope.items = [];
// if( $scope.tipsDrp != index )
// {
// $scope.tipsDrp = index;
// //predicciones
// tipster.eTips( eventID )
// .then(function(res)
// {
// res.map(function(it)
// {
// tipster.data( it.tipster )
// .then(function(resT)
// {
// $scope.items.push({
// ranking: resT[0].ranking,
// nick: resT[0].nick,
// mail: resT[0].mail,
// img: resT[0].img,
// tipBenefit: resT[0].benefit,
// tipYield: resT[0].yield,
// tipStake: resT[0].stake,
// tips: resT[0].tips,
// sport: resT[0].sport,
// comment: it.comment,
// tipster: it.tipster,
// stake: it.stake,
// cuote: it.cuote,
// bet: it.bet
// });
// })
// .catch(function( e )
// {
// console.log("ocurrio un error %s en tipster.data", e );
// });
// });
// })
// .catch(function( e )
// {
// console.log("ocurrio un error %s en tipster.eTips", e );
// });
// }
// else
// $scope.tipsDrp = -1;
// };
// })
/************************************************************************/
/* LIVE */
/************************************************************************/
// .controller('realTimeCard', function($scope, $http, $route, $filter, $timeout, $translate, socket, dataFactory, $route, VisibilityChange)
// {
// /* Instanciamos */
// var host = 'http://des.besgam.com:8080',
// livevent = $route.current.params.livevent,
// fileChartData = host + "/file/" + livevent + ".txt",
// chartData = [];
// /* Reinicializamos */
// $scope.item = null;
// $scope.payout = 0;
// $scope.chartData = null;
// $scope.active = {
// marketID: null
// };
// $scope.$on( 'LOAD' , function(){ $scope.loading = true } );
// $scope.$on( 'UNLOAD', function(){ $scope.loading = false } );
// $scope.$on( 'PING' , function(){ $scope.close = false } );
// $scope.$on( 'LEAVE' , function(){ $scope.close = true } );
// $scope.$emit('LOAD');
// VisibilityChange.onVisible(function()
// {
// $route.reload();
// //$scope.$emit('LOAD');
// //socket.emit("subscribe", livevent);
// //console.log("onVisible...");
// });
// VisibilityChange.onHidden(function()
// {
// socket.emit('unsubscribe', livevent);
// //console.log("onHidden...");
// });
// /* Carga de datos de feeds */
// dataFactory.getDataFeed().then( function( afeed )
// {
// $scope.feed = afeed.data;
// /* Nos suscribimos al live */
// socket.emit("subscribe", livevent);
// });
// $scope.$on('$destroy', function()
// {
// //$scope = $scope.$new(true);
// socket.emit('unsubscribe', livevent);
// });
// socket.on('leave-room', function()
// {
// if( $scope.loading )
// document.location.href = "./#!/live-list-search";
// //$scope.active.marketID = -1;
// $scope.$emit('LEAVE');
// });
// socket.on('reconnect', function(err)
// {
// console.log("reconnect: %s", err);
// $scope.$emit('LOAD');
// socket.emit('subscribe', livevent);
// });
// socket.on('reconnecting', function(err)
// {
// console.log("reconnecting: %s", err);
// $route.reload();
// });
// socket.on('message', function (data)
// {
// //console.log(data);
// $scope.$emit('PING');
// if( typeof(data.markets) == 'undefined' )
// return data;
// /*******************************************/
// /* Quitamos las casas que no sean del pais */
// /*******************************************/
// for( var nCont = 0, len = data.markets.length;
// nCont < len;
// nCont++ )
// {
// for( var nContBet = 0, lenBet = data.markets[ nCont ].bets.length;
// nContBet < lenBet;
// nContBet++ )
// {
// for( var nContData = data.markets[ nCont ].bets[nContBet].data.length-1;
// nContData >= 0;
// nContData-- )
// {
// if( !$scope.feed[data.markets[ nCont ].bets[nContBet].data[nContData].id_feed] )
// {
// data.markets[ nCont ].bets[nContBet].data.splice(nContData, 1);
// }
// }
// }
// }
// if( $scope.item == null )
// {
// $scope.chartData = null;
// $scope.chartOptions = {
// chart: {
// type: 'lineChart',
// height: 205,
// margin : {
// top: 10,
// right: 0,
// bottom: 50,
// left: 33
// },
// color: ['#69c198','#ff6868','#757575'],
// showLegend: true,
// showYAxis: true,
// showXAxis: true,
// useInteractiveGuideline: true,
// xAxis: {
// axisLabel: '',
// tickFormat: function(d)
// {
// var score = null;
// angular.forEach( $scope.chartData[ $scope.active.marketID ], function( value, key )
// {
// angular.forEach( value.values, function( data, key )
// {
// if( data.x == d )
// score = data.score;
// });
// });
// return d3.time.format('%H:%M:%S')(new Date(d)) + " - " + score;
// },
// ticks: 15,
// },
// yAxis: {
// //showMaxMin: false,
// tickFormat: function(d)
// {
// //return parseFloat(d).toFixed(2);
// return $filter("oddsConverter")(d,2);
// },
// ticks: 5,
// },
// tooltip: {
// gravity: 'n'
// },
// // legend: {
// // vers: 'furious'
// // },
// legendPosition: 'right'
// }
// };
// $scope.getMinMax = function( name )
// {
// if( $scope.chartData == null || $scope.active.marketID == null )
// return {
// min: 0,
// max: 0
// };
// var maxVal = null,
// minVal = null;
// if( name == 'Draw' ) name = $translate.instant('graphicMarket.draw');
// angular.forEach( $scope.chartData[ $scope.active.marketID ], function( bet )
// {
// if( bet.key == name )
// {
// angular.forEach( bet.values, function( value )
// {
// minVal = (!minVal || value.y < minVal) ? value.y : minVal;
// maxVal = (!maxVal || value.y > maxVal) ? value.y : maxVal;
// });
// }
// });
// return {
// min: minVal,
// max: maxVal
// }
// };
// $http.get(fileChartData)
// .then( function processFile(response)
// {
// var fileList = response.data.split('\n');
// for( var nCont = 0, len = fileList.length;
// nCont < len;
// nCont++ )
// {
// var tokens = fileList[nCont].split('|');
// for( var nToken = 2, lenToken = tokens.length-1;
// nToken < lenToken;
// nToken++ )
// {
// var aux = tokens[ nToken ].split('$'),
// idMarket = parseInt(aux[0]),
// datas = aux[1].split(',');
// if( !chartData[ idMarket ] )
// {
// chartData[ idMarket ] = [];
// if( datas.length-1 == 2 )
// {
// chartData[ idMarket ].push({ values: [], key: data.participants[0].name });
// chartData[ idMarket ].push({ values: [], key: data.participants[1].name });
// }
// else
// {
// chartData[ idMarket ].push({ values: [], key: data.participants[0].name });
// chartData[ idMarket ].push({ values: [], key: $translate.instant('graphicMarket.draw') });
// chartData[ idMarket ].push({ values: [], key: data.participants[1].name });
// }
// }
// if(idMarket == 1 || idMarket == 4 || idMarket == 5 || idMarket == 7 )
// {
// for( var nValues = 0, lenValues = datas.length-1;
// nValues < lenValues;
// nValues++ )
// {
// if( chartData[ idMarket ][nValues] )
// chartData[ idMarket ][nValues].values.push({x: parseInt(tokens[0]), y: $filter("setDecimal")( parseFloat(datas[nValues]), 2 ), score: tokens[1] });
// }
// }
// }
// }
// if( typeof($scope.active) != 'undefined' )
// {
// /* Grafica por defecto */
// switch( data.sportID )
// {
// case 1:
// $scope.active.marketID = 1;
// break;
// case 2:
// $scope.active.marketID = 7;
// break;
// case 3:
// $scope.active.marketID = 7;
// break;
// }
// }
// $scope.chartData = chartData;
// });
// /* Carga de datos de feeds */
// dataFactory.getDataFeed().then( function( afeed )
// {
// $scope.feed = afeed.data;
// dataFactory.getDataMarkets().then( function( amarket )
// {
// $scope.marketsData = amarket.data.markets;
// $scope.filterList = (function( filters, markets, data )
// {
// var aFilters = [];
// angular.forEach( filters.filters, function(filter, key)
// {
// if( filter.name != 'Favoritos' )
// {
// var aMarkets = [],
// fFind = false;
// angular.forEach( filter.list, function( market, key )
// {
// angular.forEach( data.markets, function( dMarket, key )
// {
// if( market == dMarket.id )
// {
// aMarkets.push( markets[ market ] );
// fFind = true;
// }
// });
// });
// if( fFind )
// {
// aFilters.push({
// id: filter.idFilter,
// name: filter.name,
// markets: aMarkets
// });
// }
// }
// });
// return aFilters;
// })( amarket.data.filters[ data.sportID ], amarket.data.markets, data );
// });
// });
// }
// else
// {
// if( $scope.chartData )
// {
// var dd = angular.copy($scope.chartData);
// // for( var nCont = 0, len = $scope.item.markets.length;
// // nCont < len;
// // nCont++ )
// // {
// // for( var nContBet = 0, lenBet = $scope.item.markets[ nCont ].bets.length;
// // nContBet < lenBet;
// // nContBet++ )
// // {
// // dd[nCont].values.push({x: parseInt(Date.now()), y: parseFloat($scope.item.markets[nCont].bets[nCont].data[0].n_odd) });
// // }
// // }
// angular.forEach( $scope.item.markets, function(market, marketKey)
// {
// if(market.id == 1 || market.id == 4 || market.id == 5 || market.id == 7 )
// {
// angular.forEach( market.bets, function(bet, betKey)
// {
// var score = null;
// if( $scope.item.info.score == null )
// score = '';
// else
// {
// if( $scope.item.sportID != 3 )
// score = $scope.item.info.score.replace(/ /g, '');
// else
// {
// var set = $scope.item.info.set != null ? " ( " + $scope.item.info.set + " )" : '';
// score = $scope.item.info.score.replace(/ /g, '') + set;
// }
// }
// if( typeof(dd[market.id]) != 'undefined')
// dd[ market.id ][betKey].values.push({x: parseInt(Date.now()), y: $filter("setDecimal")( parseFloat(bet.data[0].n_odd), 2 ), score: score });
// //$scope.chartData[ market.id ][betKey].values.push({x: parseInt(Date.now()), y: parseFloat(bet.data[0].n_odd), score: score });
// });
// }
// });
// $scope.chartData = angular.copy(dd);
// }
// }
// $scope.item = getData( data );
// $scope.log = $filter('orderBy')( $scope.item.log, 'id', true ) || null;
// $scope.titleLog = ($scope.log != null && $scope.log.length > 0) ? $scope.log[0].message : null;
// function getData( data )
// {
// if( typeof($scope.marketsTabs) == 'undefined' )
// {
// $scope.marketsTabs = [];
// $scope.marketsPayOut = [];
// for( var nMarkets = 0, lenMarkets = data.markets.length;
// nMarkets < lenMarkets;
// nMarkets++)
// {
// $scope.marketsTabs.push([]);
// $scope.marketsPayOut.push([]);
// for( var nBets = 0, lenBets = data.markets[nMarkets].bets.length;
// nBets < lenBets;
// nBets++)
// {
// $scope.marketsTabs[ nMarkets ].push(false);
// $scope.marketsPayOut[ nMarkets ].push(false);
// }
// }
// }
// else if( $scope.marketsTabs.length < data.markets.length )
// {
// for( var nMarkets = $scope.marketsTabs.length, lenMarkets = data.markets.length;
// nMarkets < lenMarkets;
// nMarkets++)
// {
// $scope.marketsTabs.push([]);
// $scope.marketsPayOut.push([]);
// for( var nBets = 0, lenBets = data.markets[nMarkets].bets.length;
// nBets < lenBets;
// nBets++)
// {
// $scope.marketsTabs[ nMarkets ].push(false);
// $scope.marketsPayOut[ nMarkets ].push(false);
// }
// }
// }
// angular.forEach( data.markets, function( market, mkey )
// {
// var prob = null;
// angular.forEach( market.bets, function( bet, bkey)
// {
// prob += 1/bet.data[0].n_odd;
// });
// var payout = (1/prob)*100;
// angular.forEach( market.bets, function( bet, bkey)
// {
// bet.prob = parseInt( (1/bet.data[0].n_odd)*payout );
// });
// market.payout = parseInt(payout);
// });
// //var data = [];
// if( $scope.auxData != null )
// {
// for( var nCont = 0, len = data.markets.length;
// nCont < len;
// nCont++ )
// {
// for( var nSubCont = 0, lenSub = $scope.auxData.markets.length, fFind = false;
// nSubCont < lenSub && fFind == false;
// nSubCont++ )
// {
// if( data.markets[nCont].id == $scope.auxData.markets[nSubCont].id )
// {
// for( var nBetCont = 0, lenBet = data.markets[nCont].bets.length;
// nBetCont < lenBet;
// nBetCont++ )
// {
// for( var nBetSubCont = 0, lenSubBet = $scope.auxData.markets[nSubCont].bets.length;
// nBetSubCont < lenSubBet;
// nBetSubCont++ )
// {
// if( data.markets[nCont].bets[nBetCont].name == $scope.auxData.markets[nSubCont].bets[nBetSubCont].name)
// {
// if( data.markets[nCont].bets[nBetCont].data[0].n_odd < $scope.auxData.markets[nSubCont].bets[nBetSubCont].data[0].n_odd )
// data.markets[nCont].bets[nBetCont].data[0].diff = 'down';
// else if( data.markets[nCont].bets[nBetCont].data[0].n_odd > $scope.auxData.markets[nSubCont].bets[nBetSubCont].data[0].n_odd )
// data.markets[nCont].bets[nBetCont].data[0].diff = 'high';
// else
// data.markets[nCont].bets[nBetCont].data[0].diff = 'equal';
// // for( var nBetDataCont = 0, lenBetData = data.markets[nCont].bets[nBetCont].data.length;
// // nBetDataCont < lenBetData;
// // nBetDataCont++ )
// // {
// // if( data.markets[nCont].bets[nBetCont].data[nBetDataCont].n_odd < $scope.auxData.markets[nSubCont].bets[nBetSubCont].data[nBetDataCont].n_odd )
// // data.markets[nCont].bets[nBetCont].data[nBetDataCont].diff = 'down';
// // else if( data.markets[nCont].bets[nBetCont].data[nBetDataCont].n_odd > $scope.auxData.markets[nSubCont].bets[nBetSubCont].data[nBetDataCont].n_odd )
// // data.markets[nCont].bets[nBetCont].data[nBetDataCont].diff = 'high';
// // else
// // data.markets[nCont].bets[nBetCont].data[nBetDataCont].diff = 'equal';
// // }
// }
// }
// }
// fFind = true;
// }
// }
// }
// }
// $scope.$emit('UNLOAD');
// return data;
// };
// /* Reemplezamos los datos */
// $scope.auxData = $scope.item;
// });
// $scope.mActive = function( active )
// {
// if( !active ) return true;
// var fFind = false;
// for( nCont = 0, len = $scope.item.markets.length;
// nCont < len && fFind == false;
// nCont++ )
// {
// if( $scope.item.markets[nCont].id == active )
// fFind = true;
// }
// return fFind;
// };
// $scope.getLiveDrop = function( parent, id )
// {
// return $scope.marketsTabs[parent][id] =! $scope.marketsTabs[parent][id];
// }
// $scope.getLivePayOut = function( parent, id)
// {
// return $scope.marketsPayOut[parent][id] =! $scope.marketsPayOut[parent][id];
// }
// })
// .controller('realTimeList', function( $scope, $window, $translate, dataFactory, socket, $route, VisibilityChange )
// {
// $scope.data = null;
// $scope.auxData = null;
// $scope.dataFilter = null;
// $scope.selectedInput = [];
// $scope.$on( 'LOAD', function(){ $scope.loading = true } );
// $scope.$on( 'UNLOAD', function(){ $scope.loading = false } );
// /* Paginación */
// $scope.totalData = 0;
// $scope.currentPage = 1;
// $scope.numPerPage = 10;
// $scope.maxSize = 5;
// $scope.setPage = function (pageNo)
// {
// window.scrollTo(0,0);
// $scope.currentPage = pageNo;
// };
// //$scope.setPage($scope.currentPage);
// var nameSport = [
// "",
// "futbol",
// "baloncesto",
// "tenis"
// ];
// $scope.$emit('LOAD');
// VisibilityChange.onVisible(function()
// {
// //$window.location.reload();
// $route.reload();
// //$scope.$emit('LOAD');
// //socket.emit("subscribe", 'list-data-live');
// //console.log("onVisible...");
// });
// VisibilityChange.onHidden(function()
// {
// socket.emit('unsubscribe', 'list-data-live');
// //console.log("onHidden...");
// });
// $scope.$on('$destroy', function()
// {
// //$scope = $scope.$new(true);
// socket.emit('unsubscribe', 'list-data-live');
// });
// /* Carga de datos de feeds */
// dataFactory.getDataFeed().then( function( afeed )
// {
// $scope.feed = afeed.data;
// /* Nos suscribimos al live */
// socket.emit('subscribe', 'list-data-live');
// });
// // socket.on('connect', function()
// // {
// // socket.emit('subscribe', 'list-data-live');
// // });
// socket.on('disconnect', function(err)
// {
// console.log("disconnect: %s", err);
// });
// socket.on('reconnect', function(err)
// {
// console.log("reconnect: %s", err);
// $scope.$emit('LOAD');
// socket.emit('subscribe', 'list-data-live');
// });
// socket.on('reconnecting', function(err)
// {
// console.log("reconnecting: %s", err);
// $route.reload();
// });
// socket.on('leave-room', function()
// {
// //document.location.href = "./#!";
// });
// socket.on('message', function (data)
// {
// //console.log( data );
// $scope.data = [];
// for( var nCont = 0, len = data.length;
// nCont < len;
// nCont++ )
// {
// var info = data[nCont].info;
// for( var nContBet = 0, lenBet = data[nCont].markets.length;
// nContBet < lenBet;
// nContBet++ )
// {
// if( data[nCont].markets[nContBet].id == 1 ||
// data[nCont].markets[nContBet].id == 7 )
// {
// /*******************************************/
// /* Quitamos las casas que no sean del pais */
// /*******************************************/
// for( var nContData = 0, lenData = data[nCont].markets[nContBet].bets.length;
// nContData < lenData;
// nContData++ )
// {
// for( var nContOdd = data[nCont].markets[nContBet].bets[nContData].data.length-1;
// nContOdd >= 0;
// nContOdd-- )
// {
// if( !$scope.feed[data[nCont].markets[nContBet].bets[nContData].data[nContOdd].id_feed] )
// {
// data[nCont].markets[nContBet].bets[nContData].data.splice(nContOdd, 1);
// }
// }
// }
// if( data[nCont].markets[nContBet].bets[0].data.length > 0 )
// {
// $scope.data.push({
// idSport: data[nCont].sportID,
// sportType: data[nCont].sport,
// info: info,
// league: data[ nCont ].league,
// event: data[ nCont].event,
// bets: data[nCont].markets[nContBet].bets
// });
// }
// }
// }
// }
// if( $scope.auxData != null )
// {
// for( var nCont = 0, len = $scope.data.length;
// nCont < len;
// nCont++ )
// {
// for( var nSubCont = 0, lenSub = $scope.auxData.length, fFind = false;
// nSubCont < lenSub && fFind == false;
// nSubCont++ )
// {
// if( $scope.data[nCont].event == $scope.auxData[nSubCont].event )
// {
// for( var nBetCont = 0, lenBet = $scope.data[nCont].bets.length;
// nBetCont < lenBet;
// nBetCont++ )
// {
// for( var nBetSubCont = 0, lenSubBet = $scope.auxData[nSubCont].bets.length;
// nBetSubCont < lenSubBet;
// nBetSubCont++ )
// {
// if( $scope.data[nCont].bets[nBetCont].name == $scope.auxData[nSubCont].bets[nBetSubCont].name)
// {
// if( $scope.data[nCont].bets[nBetCont].data[0].n_odd < $scope.auxData[nSubCont].bets[nBetSubCont].data[0].n_odd )
// $scope.data[nCont].bets[nBetCont].data[0].diff = 'down';
// else if( $scope.data[nCont].bets[nBetCont].data[0].n_odd > $scope.auxData[nSubCont].bets[nBetSubCont].data[0].n_odd )
// $scope.data[nCont].bets[nBetCont].data[0].diff = 'high';
// else
// $scope.data[nCont].bets[nBetCont].data[0].diff = 'equal';
// }
// }
// }
// }
// }
// }
// }
// /* Reemplezamos los datos */
// $scope.auxData = $scope.data;
// $scope.dataFilter = listLiveDataFilter( $scope.auxData );
// $scope.totalData = ($scope.dataFilter.length-10);
// $scope.liveSports = $scope.data.reduce(function(sum, place)
// {
// if(sum.indexOf( place.idSport ) < 0) sum.push( place.idSport );
// return sum;
// }, []);
// /* Lista de ligas */
// listLiveLeagues();
// });
// $scope.getSport = function( id )
// {
// return nameSport[ id ];
// };
// var listLiveDataFilter = function( data )
// {
// var dataFilter = [];
// if( $scope.selectedInput.league != "" )
// {
// angular.forEach(data, function(value, key)
// {
// if( value.league == $scope.selectedInput.league )
// dataFilter.push(value);
// });
// }
// else if( $scope.selectedInput.sport != "" )
// {
// angular.forEach(data, function(value, key)
// {
// if( value.idSport == $scope.selectedInput.sport )
// dataFilter.push(value);
// });
// }
// else
// {
// angular.forEach(data, function(value, key)
// {
// dataFilter.push(value);
// });
// }
// // if( $scope.selectedInput.sport != "" && $scope.selectedInput.league != "" )
// // {
// // angular.forEach(data, function(value, key)
// // {
// // if(value.sport == $scope.selectedInput.sport && value.league == $scope.selectedInput.league )
// // dataFilter.push(value);
// // });
// // }
// // else if( $scope.selectedInput.sport != "" )
// // {
// // angular.forEach(data, function(value, key)
// // {
// // if( value.sport == $scope.selectedInput.sport )
// // dataFilter.push(value);
// // });
// // }
// // else if( $scope.selectedInput.sport == "" )
// // {
// // angular.forEach(data, function(value, key)
// // {
// // dataFilter.push(value);
// // });
// // }
// if( data.length == 0 && dataFilter.length == 0 )
// $scope.$emit('UNLOAD');
// else if( data.length > 0 && dataFilter.length > 0 )
// $scope.$emit('UNLOAD');
// return dataFilter;
// };
// var listLiveLeagues = function()
// {
// $scope.liveLeagues = $scope.data.reduce(function(sum, place)
// {
// if( place.league != null )
// {
// if( $scope.selectedInput.sport && $scope.selectedInput.sport != "" )
// {
// if (sum.indexOf( place.league ) < 0 && $scope.selectedInput.sport == place.idSport )
// sum.push( place.league );
// }
// else
// {
// if (sum.indexOf( place.league ) < 0) sum.push( place.league );
// }
// }
// return sum;
// }, []);
// };
// $scope.changeListLive = function()
// {
// /* Lista de ligas */
// listLiveLeagues();
// /* Lista de Eventos */
// $scope.dataFilter = listLiveDataFilter( $scope.auxData );
// };
// /* Cargamos los datos de las feed */
// dataFactory.getDataFeed().then( function(response)
// {
// $scope.feed = response.data;
// });
// })
// .controller("redirect-live", function( $scope, $route, $http, $interpolate, $sessionStorage, eventTrack )
// {
// var id_feed = $route.current.params.id_feed,
// id_bet = $route.current.params.id_bet,
// id_bid = $route.current.params.id_bid,
// url = null,
// confFeed = {
// method: 'GET',
// url: 'json/feeds.json',
// headers: {
// 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
// }
// };
// /* Traqueamos el evento */
// eventTrack.new({
// name: "redirect",
// category: "live",
// label: id_feed+"-"+id_bet
// });
// /* Carga de datos de feeds */
// $http(confFeed).
// success(function(dataFeed, status, headers, config)
// {
// $scope.img_feed = dataFeed[ id_feed ].str_image;
// id_bid = dataFeed[ id_feed ].str_bid;
// var getBetSlip = {
// method: 'POST',
// url: 'php/redirect-live.php',
// headers: {
// 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
// },
// data: "id_feed=" + id_feed + "&id_bet=" + id_bet + "&id_bid=" + id_bid + "&id_user=" + $sessionStorage.iduser
// }
// /* Recuperamos datos del evento */
// $http(getBetSlip).
// success(function(dataBet, status, headers, config)
// {
// /* Componemos la url */
// url = $interpolate( dataBet.url )($scope);
// document.location.href = url;
// });
// });
// })
/************************************************************************/
/* Includes */
/************************************************************************/
// .controller("header", function( $scope, $localStorage, $sessionStorage, $location, $http )
// {
// $scope.$lStorage = $localStorage;
// $scope.$storage = $sessionStorage;
// var url = $location.url(),
// endUrl = url.split("?");
// $scope.isNotHome = function()
// {
// if( ( endUrl[0] == "/search" || endUrl[0] == "/home" || endUrl[0] == "/" ) && !$scope.fScrollData )
// return false;
// else
// return true;
// };
// $scope.$storage = $sessionStorage;
// /* Cerrar la sesion del usuario */
// $scope.closeSession= function()
// {
// Si todo ha ido bien, se redirecciona al index y se borra el localStorage
// $sessionStorage.iduser = null;
// $sessionStorage.expired = 0;
// $sessionStorage.favorites = null;
// $sessionStorage.str_name = null;
// $sessionStorage.str_email = null;
// $sessionStorage.a_sports = null;
// $sessionStorage.other_sport = null;
// $sessionStorage.nameuser = null;
// $sessionStorage.sessionid = null;
// $sessionStorage.$save();
// $sessionStorage.$reset();
// document.location.href = "./#!";
// }
// })
// .controller('checkCookie', function( $scope, $http, $window )
// {
// /* Ocular capa */
// $scope.layerCookie = false;
// /* Comprobar si el usuario tiene la cookie */
// if( getCookie("besgamCookies") == "" )
// {
// /* Mostar capa */
// $scope.layerCookie = true;
// angular.element($window).bind("scroll", function()
// {
// cookieSave();
// });
// angular.element($window).bind("click", function()
// {
// cookieSave();
// });
// function cookieSave()
// {
// /* Grabar cookie */
// setCookie("besgamCookies","cookePolitic", 3650);
// /* Ocular capa */
// $scope.layerCookie = false;
// $scope.$apply();
// }
// }
// /* Damos valor a la cookie */
// function setCookie( cname, cvalue, exdays )
// {
// var d = new Date();
// d.setTime(d.getTime() + (exdays*24*60*60*1000));
// var expires = "{expires:"+d.toUTCString()+"}";
// document.cookie = cname + "=" + escape(cvalue) + ";expires=" + expires;
// }
// /* Con esta función obtenemos la cookie */
// function getCookie( besgamCookies )
// {
// var name = besgamCookies + "=";
// var ca = document.cookie.split(';');
// for(var i=0; i<ca.length; i++) {
// var c = ca[i];
// while (c.charAt(0)==' ') c = c.substring(1);
// if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
// }
// return "";
// }
// })
// .controller('tweets', function( $scope, dataFactory )
// {
// var now = new Date();
// $scope.offsetutc = now.getTimezoneOffset();
// dataFactory.getDataTwitter().then( function(response)
// {
// $scope.tweets = response.data;
// });
// $scope.submit = function(form)
// {
// var href = "./#!newsletter/" + $scope.email;
// document.location.href = href;
// //document.forms[form].submit();
// };
// })
// .controller('flexslider', function( $scope, dataFactory )
// {
// $scope.slides = [];
// dataFactory.getDataFeed().then( function( response )
// {
// angular.forEach( response.data, function( value, key )
// {
// $scope.slides.push( value );
// });
// });
// })
// .controller('tweets-slick', function( $scope, dataFactory)
// {
// dataFactory.getDataTwitter().then( function(response)
// {
// $scope.tweets = response.data;
// });
// })
/************************************************************************/
/* Servicios */
/************************************************************************/
// .service('tipster', function( $localStorage, $q, dateTime )
// {
// var tipsterData = [
// {
// tipster : 1,
// nick: 'Anton_Siruelas',
// mail: 'asiruela@besgam.com',
// img: 'fer.jpg',
// ranking: 8,
// benefit: 121.73,
// yield: 8.50,
// stake: 1.55,
// followers: 105,
// tips: {
// total: 18,
// ok: 5,
// cancel: 3,
// ko: 10
// },
// sport: [{
// type: 'Fútbol',
// percent: 70
// },
// {
// type: 'Baloncesto',
// percent: 30
// }],
// betHouse:[{
// id_feed: 7,
// percent: 80
// },
// {
// id_feed: 2,
// percent: 10
// },
// {
// id_feed: 4,
// percent: 10
// }]
// },
// {
// tipster : 2,
// nick: 'Marcel_Duchamp',
// mail: 'asiruela@besgam.com',
// img: 'fer.jpg',
// ranking: 5,
// benefit: 12.73,
// yield: 28.50,
// stake: 16.55,
// followers: 207,
// tips: {
// total: 45,
// ok: 20,
// cancel: 0,
// ko: 25
// },
// sport: [{
// type: 'Fútbol',
// percent: 20
// },
// {
// type: 'Baloncesto',
// percent: 50
// },
// {
// type: 'Tenis',
// percent: 6
// }],
// betHouse:[{
// id_feed: 13,
// percent: 80
// },
// {
// id_feed: 2,
// percent: 10
// },
// {
// id_feed: 6,
// percent: 10
// }]
// },
// {
// tipster : 3,
// nick: 'patricio',
// mail: 'patricio@besgam.com',
// img: 'fer.jpg',
// ranking: 4,
// benefit: 1.73,
// yield: 28.50,
// stake: 16.55,
// followers: 207,
// tips: {
// total: 45,
// ok: 20,
// cancel: 0,
// ko: 25
// },
// sport: [{
// type: 'Boxeo',
// percent: 100
// }],
// betHouse:[{
// id_feed: 2,
// percent: 80
// },
// {
// id_feed: 10,
// percent: 10
// },
// {
// id_feed: 4,
// percent: 10
// }]
// },
// {
// tipster : 4,
// nick: 'Lucas',
// mail: 'lucas@besgam.com',
// img: 'fer.jpg',
// ranking: 2,
// benefit: 1.73,
// yield: 28.50,
// stake: 16.55,
// followers: 207,
// tips: {
// total: 45,
// ok: 20,
// cancel: 0,
// ko: 25
// },
// sport: [{
// type: 'Boxeo',
// percent: 100
// }],
// betHouse:[{
// id_feed: 2,
// percent: 80
// },
// {
// id_feed: 10,
// percent: 10
// },
// {
// id_feed: 4,
// percent: 10
// }]
// },
// {
// tipster : 5,
// nick: 'Marcos',
// mail: 'patricio@besgam.com',
// img: 'fer.jpg',
// ranking: 5,
// benefit: 1.73,
// yield: 28.50,
// stake: 16.55,
// followers: 207,
// tips: {
// total: 45,
// ok: 20,
// cancel: 0,
// ko: 25
// },
// sport: [{
// type: 'Boxeo',
// percent: 100
// }],
// betHouse:[{
// id_feed: 2,
// percent: 80
// },
// {
// id_feed: 10,
// percent: 10
// },
// {
// id_feed: 4,
// percent: 10
// }]
// },
// {
// tipster : 6,
// nick: 'Lorena Garcís',
// mail: 'patricio@besgam.com',
// img: 'fer.jpg',
// ranking: 10,
// benefit: 1.73,
// yield: 28.50,
// stake: 16.55,
// followers: 207,
// tips: {
// total: 45,
// ok: 20,
// cancel: 0,
// ko: 25
// },
// sport: [{
// type: 'Boxeo',
// percent: 100
// }],
// betHouse:[{
// id_feed: 2,
// percent: 80
// },
// {
// id_feed: 10,
// percent: 10
// },
// {
// id_feed: 4,
// percent: 10
// }]
// },
// {
// tipster : 7,
// nick: 'Alfonso',
// mail: 'patricio@besgam.com',
// img: 'fer.jpg',
// ranking: 10,
// benefit: 1.73,
// yield: 28.50,
// stake: 16.55,
// followers: 207,
// tips: {
// total: 45,
// ok: 20,
// cancel: 0,
// ko: 25
// },
// sport: [{
// type: 'Boxeo',
// percent: 100
// }],
// betHouse:[{
// id_feed: 2,
// percent: 80
// },
// {
// id_feed: 10,
// percent: 10
// },
// {
// id_feed: 4,
// percent: 10
// }]
// },
// {
// tipster : 8,
// nick: 'Rocío',
// mail: 'patricio@besgam.com',
// img: 'fer.jpg',
// ranking: 14,
// benefit: 1.73,
// yield: 28.50,
// stake: 16.55,
// followers: 207,
// tips: {
// total: 45,
// ok: 20,
// cancel: 0,
// ko: 25
// },
// sport: [{
// type: 'Boxeo',
// percent: 100
// }],
// betHouse:[{
// id_feed: 2,
// percent: 80
// },
// {
// id_feed: 10,
// percent: 10
// },
// {
// id_feed: 4,
// percent: 10
// }]
// },
// {
// tipster : 9,
// nick: 'Aarón Sánchez',
// mail: 'patricio@besgam.com',
// img: 'fer.jpg',
// ranking: 7,
// benefit: 1.73,
// yield: 28.50,
// stake: 16.55,
// followers: 207,
// tips: {
// total: 45,
// ok: 20,
// cancel: 0,
// ko: 25
// },
// sport: [{
// type: 'Boxeo',
// percent: 100
// }],
// betHouse:[{
// id_feed: 2,
// percent: 80
// },
// {
// id_feed: 10,
// percent: 10
// },
// {
// id_feed: 4,
// percent: 10
// }]
// },
// {
// tipster : 10,
// nick: 'Leonor',
// mail: 'patricio@besgam.com',
// img: 'fer.jpg',
// ranking: 3,
// benefit: 1.73,
// yield: 28.50,
// stake: 16.55,
// followers: 207,
// tips: {
// total: 45,
// ok: 20,
// cancel: 0,
// ko: 25
// },
// sport: [{
// type: 'Boxeo',
// percent: 100
// }],
// betHouse:[{
// id_feed: 2,
// percent: 80
// },
// {
// id_feed: 10,
// percent: 10
// },
// {
// id_feed: 4,
// percent: 10
// }]
// },
// {
// tipster : 11,
// nick: 'Bob Esponja',
// mail: 'patricio@besgam.com',
// img: 'fer.jpg',
// ranking: 5,
// benefit: 1.73,
// yield: 28.50,
// stake: 16.55,
// followers: 207,
// tips: {
// total: 45,
// ok: 20,
// cancel: 0,
// ko: 25
// },
// sport: [{
// type: 'Boxeo',
// percent: 100
// }],
// betHouse:[{
// id_feed: 2,
// percent: 80
// },
// {
// id_feed: 10,
// percent: 10
// },
// {
// id_feed: 4,
// percent: 10
// }]
// },
// {
// tipster : 12,
// nick: 'Tipster 1',
// mail: 'patricio@besgam.com',
// img: 'fer.jpg',
// ranking: 15,
// benefit: 1.73,
// yield: 28.50,
// stake: 16.55,
// followers: 207,
// tips: {
// total: 45,
// ok: 20,
// cancel: 0,
// ko: 25
// },
// sport: [{
// type: 'Boxeo',
// percent: 100
// }],
// betHouse:[{
// id_feed: 2,
// percent: 80
// },
// {
// id_feed: 10,
// percent: 10
// },
// {
// id_feed: 4,
// percent: 10
// }]
// },
// {
// tipster : 13,
// nick: 'Tipster 2',
// mail: 'patricio@besgam.com',
// img: 'fer.jpg',
// ranking: 16,
// benefit: 1.73,
// yield: 28.50,
// stake: 16.55,
// followers: 207,
// tips: {
// total: 45,
// ok: 20,
// cancel: 0,
// ko: 25
// },
// sport: [{
// type: 'Boxeo',
// percent: 100
// }],
// betHouse:[{
// id_feed: 2,
// percent: 80
// },
// {
// id_feed: 10,
// percent: 10
// },
// {
// id_feed: 4,
// percent: 10
// }]
// }
// ]
// var tipsPrediction = [
// {
// eventID: [21394],
// tipster: 1,
// comment: [
// {
// text: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed eiusmod incidunt ut dolore setibus sum loquid et magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut nulis quod.',
// time: 'Sat Oct 29 2016 20:00:00',
// min_cuote: 2
// }],
// stake: 5,
// cuote: 2.5,
// bet: [{
// id_league: 67,
// id_event: 21394,
// str_event: 'Tyson Fury vs Wladimir Klitschko',
// id_market: 22,
// str_market: 'Ganador',
// str_bet: '1',
// str_bet_feed: 'Tyson Fury',
// time: 'Sat Oct 29 2016 20:00:00',
// sportID: 7,
// sport: 'Boxeo',
// cuote: 2.5,
// },
// {
// id_league: 67,
// id_event: 21394,
// str_event: 'Tyson Fury2 vs Wladimir Klitschko',
// id_market: 22,
// str_market: 'Ganador',
// str_bet: '1',
// str_bet_feed: 'Wladimir Klitschko',
// time: 'Sat Oct 30 2016 20:00:00',
// sportID: 7,
// sport: 'Boxeo',
// cuote: 2.5,
// }]
// },
// {
// eventID: [21394],
// tipster: 1,
// comment: [
// {
// text: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed eiusmod incidunt ut dolore setibus sum loquid et magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut nulis quod.',
// time: 'Sat Oct 29 2016 20:00:00',
// min_cuote: 2
// },
// {
// text: ' Otro ng repeat Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed eiusmod incidunt ut dolore setibus sum loquid et magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut nulis quod.',
// time: 'Fri Oct 28 2016 19:00:00',
// min_cuote: 1
// }],
// stake: 5,
// cuote: 2.5,
// bet: [{
// id_league: 67,
// id_event: 21394,
// str_event: 'Tyson Fury vs Wladimir Klitschko',
// id_market: 22,
// str_market: 'Ganador',
// str_bet: '1',
// str_bet_feed: 'NO Tyson Fury',
// time: 'Thu Aug 25 2016 17:00:00',
// sportID: 7,
// sport: 'Boxeo',
// cuote: 2.5,
// }]
// },
// {
// eventID: [21394, 27092, 27093],
// tipster: 1,
// comment: [{
// text: '2º Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed eiusmod incidunt ut dolore setibus sum loquid et magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut nulis quod.',
// time: 'Sat Oct 29 2016 20:00:00',
// min_cuote: 2
// }],
// stake: 7,
// cuote: 3.5,
// bet: [
// {
// id_league: 67,
// id_event: 21394,
// str_event: 'Tyson Fury vs Wladimir Klitschko',
// id_market: 22,
// str_market: 'Ganador',
// str_bet: '1',
// str_bet_feed: 'Tyson Fury',
// time: 'Sat Oct 29 2016 20:00:00',
// sportID: 7,
// sport: 'Boxeo',
// cuote: 2.5
// },
// {
// id_league: 67,
// id_event: 27092,
// str_event: 'Tyson Fury vs Wladimir Klitschko',
// id_market: 22,
// str_market: 'Ganador',
// str_bet: '1',
// str_bet_feed: 'Tyson Fury',
// time: 'Thu Aug 25 2016 17:00:00',
// sportID: 7,
// sport: 'Boxeo',
// cuote: 2.5
// },
// {
// id_league: 21,
// id_event: 27093,
// str_event: 'Ganador de la competición',
// id_market: 8,
// str_market: 'Ganador',
// str_bet: 'Mercedes',
// str_bet_feed: 'Mercedes',
// time: 'Sun Nov 20 2016 13:00:00',
// sportID: 5,
// sport: 'Formula 1',
// cuote: 2.5
// }]
// }
// ]
// /* -- datos de los tipster -- */
// this.data = function( id ) // String -> Nick || Numerico -> id
// {
// var defered = $q.defer();
// try
// {
// var data;
// if( typeof id == 'undefined' )
// data = tipsterData;
// else
// {
// // filter recorre un array como map pero adems filtra
// data = tipsterData.filter( function(it)
// {
// if( it.nick === id || it.tipster === id )
// return it;
// });
// }
// defered.resolve( data );
// }
// catch( e )
// {
// defered.reject( e.message );
// }
// return defered.promise;
// };
// /* -- predicciones de un determinado evento -- */
// this.eTips = function( id_event )
// {
// var defered = $q.defer();
// try
// {
// var data = tipsPrediction.filter( function( it )
// {
// var fFind = false;
// it.eventID.map( function( value )
// {
// if( value == id_event ) fFind = true;
// });
// if( fFind ) return it;
// });
// defered.resolve( data );
// }
// catch( e )
// {
// defered.reject( e.message );
// }
// return defered.promise;
// }
// /* H || A */
// this.gTips = function( id_tipster, type )
// {
// var defered = $q.defer();
// try
// {
// var data = tipsPrediction.filter( function( it )
// {
// if( it.tipster == id_tipster)
// {
// var fFind = false;
// it.bet.filter(function( date )
// {
// if( dateTime.fExpiration(date.time) ) fFind = true;
// });
// /* Expirado -> True && type == H (historicas) */
// if( fFind && type == 'H' )
// return it; // Añadir
// /* Expirado -> False && type == C (Curren --> actuales) */
// else if (!fFind && type == 'C')
// return it; // Añadir
// }
// });
// defered.resolve( data );
// }
// catch( e )
// {
// defered.reject( e.message );
// }
// // function fExpiration( strTime )
// // {
// // if( !strTime ) return; // Control para evitar vacios
// // var targetTime = new Date( strTime ),
// // offsetTime = new Date( targetTime.getTime() + $localStorage.timeZoneOffset ),
// // today = new Date();
// // return (offsetTime > today ) ? 0 : 1;
// // };
// return defered.promise;
// }
// })
// .service('dateTime', function( $localStorage )
// {
// this.fExpiration = function( strTime )
// {
// if( !strTime ) return; // Control para evitar vacios
// /* Hora del evento + UTC */
// var targetTime = new Date( strTime ),
// offsetTime = new Date( targetTime.getTime() + $localStorage.timeZoneOffset );
// /* NOW + UTC */
// var now = new Date(),
// nowUTC = new Date( now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds() ),
// today = new Date( nowUTC.getTime() + $localStorage.timeZoneOffset );
// return (offsetTime > today ) ? 0 : 1;
// };
// })
// .service('eventTrack', function( $analytics )
// {
// this.new = function( obj )
// {
// $analytics.eventTrack( obj.name,
// {
// category: obj.category,
// label: obj.label
// });
// }
// })
// .service('tipsterOdds', function( $http, $q )
// {
// this.tipBets = function( params, feeds )
// {
// var deferred = $q.defer(),
// objParams = new Object(params);
// $http({
// method : 'POST',
// url : '/php/getOddsTips.php',
// headers: {'Content-Type': 'application/x-www-form-urlencoded'},
// data : $.param(objParams)
// }).then(
// function success(res)
// {
// var data = res.data,
// exit = [];
// data.map(function(items)
// {
// items.map( function(item)
// {
// if( data.length == 1 )
// {
// exit.push({
// "id_bet": [item.id_bet],
// "id_feed": item.id_feed,
// "n_odd": item.n_odd
// });
// }
// else
// {
// var fFind = false;
// exit.map( function(exitItem )
// {
// if( exitItem.id_feed == item.id_feed )
// {
// exitItem.id_bet.push( item.id_bet );
// exitItem.n_odd = exitItem.n_odd * item.n_odd;
// fFind = true;
// }
// });
// /* Si no encontramos */
// if( !fFind )
// {
// exit.push({
// "id_bet": [item.id_bet],
// "id_feed": item.id_feed,
// "n_odd": item.n_odd
// });
// }
// }
// });
// });
// /*******************************************/
// /* Quitamos las casas que no sean del pais */
// /*******************************************/
// exit = exit.filter(function( it, id )
// {
// if( feeds[ it.id_feed ] ) return it;
// });
// /*******************************************/
// /* Ordenamos por la cuota descendente */
// /*******************************************/
// exit.sort( function(a, b)
// {
// var _a = a.n_odd,
// _b = b.n_odd;
// return _a > _b ? -1 : _a < _b ? 1 : 0;
// });
// deferred.resolve( exit );
// },
// function error(res)
// {
// console.log('¡¡¡error!!!');
// deferred.reject( 'hay un error' );
// });
// return deferred.promise;
// }
// // this.tipBets = function( patricio1 )
// // {
// // $http({
// // method : 'POST',
// // url : 'patricia.php',
// // data : {
// // param1 : patricio1
// // }
// // }).then(
// // function success(res)
// // {
// // return [
// // {
// // "id_bet": [6058363, 6058363],
// // "id_feed": 4,
// // "n_odd": 2.35
// // },
// // {
// // "id_bet": [6059778, 6058363],
// // "id_feed": 3,
// // "n_odd": 2.2
// // }
// // ];
// // },
// // function error(res)
// // {
// // console.log('¡¡¡error!!!');
// // });
// // }
// })
// //[{"id_bet":6058363,"id_feed":4,"n_odd":2.35},{"id_bet":6059778,"id_feed":3,"n_odd":2.2}]
/************************************************************************/
/* Factorias */
/************************************************************************/
// .factory('socket', function ($rootScope)
// {
// var socket = io.connect('http://des.besgam.com:8080');
// return {
// on: function (eventName, callback)
// {
// socket.on(eventName, function ()
// {
// var args = arguments;
// $rootScope.$apply(function ()
// {
// callback.apply(socket, args);
// });
// });
// },
// emit: function (eventName, data, callback)
// {
// socket.emit(eventName, data, function ()
// {
// var args = arguments;
// $rootScope.$apply(function ()
// {
// if (callback)
// {
// callback.apply(socket, args);
// }
// });
// })
// },
// destroy: function()
// {
// socket.disconnet();
// }
// };
// })
// .factory('metas', function( $location )
// {
// var title = '',
// description = '',
// keywords = '',
// base = '';
// return {
// title: function()
// {
// return title;
// },
// description: function()
// {
// return description;
// },
// keywords: function() { return keywords; },
// robots: function()
// {
// if( $location.host() == 'www.besgam.com' )
// return 'index, follow';
// else
// return 'noindex, nofollow';
// },
// reset: function()
// {
// title = '';
// description = '';
// keywords = '';
// base = '';
// },
// setTitle: function( newTitle )
// {
// title = newTitle;
// },
// setMetaDescription: function(newMetaDescription)
// {
// description = newMetaDescription;
// },
// setKeywords: function(newKeywords)
// {
// keywords = newKeywords;
// }
// };
// })
// .factory('dataFactory', function( $http )
// {
// var dataJson = $http({
// method: 'GET',
// url: './json/data.json',
// params: {'_':new Date().getTime()},
// headers: {
// 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
// }
// }).success(function (data) { return data; }),
// dataBanner = $http({
// method: 'GET',
// url: './json/dataBanner.json',
// params: {'_':new Date().getTime()},
// headers: {
// 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
// }
// }).success(function (data) { return data; }),
// dataFeed = $http.get('./json/feeds.json').success(function (data)
// {
// return data;
// }),
// dataTwitter = $http.get('./php/twitter.php').success(function (data)
// {
// return data;
// }),
// dataBonos = $http.get('./json/dataBono.json').success(function (data)
// {
// return data;
// }),
// dataMarkets = $http.get('./json/markets.json').success(function (data)
// {
// return data;
// });
// return {
// getDataJson: function() { return dataJson ; },
// getDataBanner: function() { return dataBanner ; },
// getDataFeed: function() { return dataFeed ; },
// getDataTwitter: function() { return dataTwitter ; },
// getDataBonos: function() { return dataBonos ; },
// getDataMarkets: function() { return dataMarkets ; }
// }
// })
// .factory( "angularTranslateAsyncLoader", function( $q, $http )
// {
// return function( options )
// {
// var deferred = $q.defer();
// $http
// .get( "/src/lang/" + options.key + ".json" )
// .success( function( data )
// {
// deferred.resolve( data );
// })
// .error( function()
// {
// deferred.reject( options.key );
// });
// return deferred.promise;
// }
// })
// .factory ('timeOut', function($location, $sessionStorage)
// {
// /* Comprobar el timepo de session y echarte si se ha cumplido */
// return {
// timeOut:function()
// {
// if(angular.isUndefined($sessionStorage.expired) || $sessionStorage.expired == 0 ||
// angular.isUndefined($sessionStorage.iduser) || $sessionStorage.iduser == 0 ||
// angular.isUndefined($sessionStorage.sessionid) || $sessionStorage.sessionid == 0)
// {
// $location.path('register').replace();
// }
// else
// {
// var now = new Date();
// var time_now = now.getTime();
// var expired = $sessionStorage.expired;
// var longSession = 1440*60000 // 60.000 seg que es 1 minuto * 3 minutos
// var time_session = expired + longSession ;
// if(time_session < time_now)
// {
// /* La sesion ha caducado */
// $sessionStorage.iduser = null;
// $sessionStorage.expired = 0;
// $sessionStorage.favorites = null;
// $sessionStorage.str_name = null;
// $sessionStorage.str_email = null;
// $sessionStorage.a_sports = null;
// $sessionStorage.other_sport = null;
// $sessionStorage.nameuser = null;
// $sessionStorage.sessionid = null;
// $sessionStorage.$save();
// $sessionStorage.$reset();
// $location.path('register').replace();
// }
// else
// return true;
// }
// }
// }
// })
// .factory ('device', function( $window )
// {
// var userAgent = $window.navigator.userAgent,
// browsers = ["Mobile","iPhone","iPod","BlackBerry","Opera Mini","Sony","MOT","Nokia","samsung"],
// typeMobile = false;
// for(var key in browsers)
// {
// if( userAgent.indexOf(browsers[key]) != -1 )
// {
// typeMobile = true;
// }
// break;
// };
// return {
// is: function()
// {
// return typeMobile;
// }
// }
// })
/************************************************************************/
/* Directivas */
/************************************************************************/
// .directive("focusMe", function ( $timeout, $parse, $rootScope )
// {
// return {
// // scope: '=focusMe',
// // link: function (scope, element, attrs)
// // {
// // var model = $parse(attrs.focusMe);
// // scope.$watch(model, function (value)
// // {
// // console.log('value=', value);
// // if (value === true)
// // {
// // $timeout(function ()
// // {
// // element[0].focus();
// // scope.$apply(model.assign(scope, true));
// // }, 250);
// // }
// // });
// // element.bind('blur', function ()
// // {
// // console.log('blur');
// // scope.$apply(model.assign(scope, false));
// // });
// // }
// // scope: { trigger: '=focusMe' },
// // link: function(scope, element)
// // {
// // scope.$watch('trigger', function(value)
// // {
// // if(value === true)
// // {
// // console.log('trigger',value);
// // $timeout(function() {
// // element[0].focus();
// // //scope.trigger = false;
// // });
// // }
// // });
// // }
// // link: function( scope, element, attr )
// // {
// // element.on("touchstart", function(event)
// // {
// // event.preventDefault();
// // event.stopPropagation();
// // $rootScope.showSearchMobile = true;
// // scope.$apply();
// // var el = document.getElementById("target");
// // el.focus();
// // });
// // element.on("touchend", function(event)
// // {
// // //return false;
// // // event.preventDefault();
// // // event.stopPropagation();
// // });
// // }
// };
// })
// .directive("headerScroll", function ($window)
// {
// return function(scope, element, attrs)
// {
// angular.element($window).bind("scroll", function()
// {
// if (this.pageYOffset > 273)
// scope.headerFixedChangeClass = true;
// else
// scope.headerFixedChangeClass = false;
// scope.$apply();
// });
// };
// })
// .directive('totalShopBetsIn', function( $window, $document, $rootScope )
// {
// return function( scope, element, attrs )
// {
// var w = angular.element($window),
// body = angular.element( $document[0].body );
// // scope.getWindowDimensions = function ()
// // {
// // return {
// // 'h': w.height(),
// // 'w': w.width()
// // };
// // };
// // scope.$watch(scope.getWindowDimensions, function (newValue, oldValue)
// // {
// // scope.windowHeight = newValue.h;
// // scope.windowWidth = newValue.w;
// // scope.style = function () {
// // return {
// // 'height': (newValue.h - 100) + 'px',
// // 'width': (newValue.w - 100) + 'px'
// // };
// // };
// // }, true);
// w.bind('resize', function( scope )
// {
// if( $window.innerWidth <= 680 && $rootScope.showBag )
// element.attr( 'style', 'max-height: ' + ($window.innerHeight - getHeightBag() ) + 'px' );
// else
// element.attr( 'style', 'max-height: 450px' );
// });
// scope.$watch('showBag', function()
// {
// if( $window.innerWidth <= 680 && $rootScope.showBag )
// {
// body.addClass('overflow-hidden-bag');
// element.attr( 'style', 'max-height: ' + ($window.innerHeight - getHeightBag() ) + 'px' );
// }
// else
// body.removeClass('overflow-hidden-bag');
// });
// scope.$watch('changeView', function()
// {
// if( $window.innerWidth <= 680 && $rootScope.showBag )
// element.attr( 'style', 'max-height: ' + ($window.innerHeight - getHeightBag() ) + 'px' );
// });
// getHeightBag = function()
// {
// return $rootScope.changeView == 'simple' ? 135 : 112;
// };
// };
// })
// .directive('bodyOverflow', function( $document, $rootScope )
// {
// return function( scope, element, attrs )
// {
// var body = angular.element( $document[0].body );
// scope.$watch('showSearchMobile', function()
// {
// if( $rootScope.showSearchMobile )
// body.addClass('overflow-hidden-search');
// else
// body.removeClass('overflow-hidden-search');
// });
// };
// })
// .directive("hideClickOutside", function( $document )
// {
// return {
// link: function (scope, element, attrs)
// {
// $document.on('click', function (e)
// {
// if( !element[0].contains(e.target) )
// {
// scope.$apply(function ()
// {
// scope.search.tags = '';
// });
// }
// });
// }
// }
// })
// .directive('hideFilterOutside', function( $document, $parse )
// {
// return {
// link: function postLink(scope, element, attrs)
// {
// var first = true; // Primer click
// /* Observadores */
// scope.$watch( attrs.hideFilterOutside, function( newValue, oldValue)
// {
// if (newValue !== oldValue && newValue == true)
// $document.bind('click', onClick); // Creamos evento
// else if (newValue !== oldValue && newValue == false)
// {
// /* Inicializamos */
// first = true;
// $document.unbind('click', onClick); // Drestruimos evento
// }
// });
// /* Se utiliza SOLO cuando se selecciona un filtro */
// scope.$watch( 'filter.selected', function( newValue, oldValue)
// {
// if (newValue !== oldValue && oldValue !== undefined )
// {
// /* Inicializamos */
// first = true;
// $document.unbind('click', onClick); // Drestruimos evento
// scope.$parent.prematchMarketFilter = false;
// }
// });
// /* Evento on click */
// var onClick = function (event)
// {
// /* Instanciamos */
// var isChild = $(element).has(event.target).length > 0,
// isSelf = element[0] == event.target,
// isInside = isChild || isSelf;
// if( !isInside && !first )
// {
// switch( attrs.hideFilterOutside )
// {
// case '$parent.liveListFilter':
// scope.$parent.liveListFilter = false;
// break;
// case '$parent.liveMarketFilter':
// scope.$parent.liveMarketFilter = false;
// break;
// case 'menuFilter':
// scope.menuFilter = false;
// break;
// case '$parent.prematchListFilter':
// scope.$parent.prematchListFilter = false;
// break;
// case '$parent.prematchMarketFilter':
// scope.$parent.prematchMarketFilter = false;
// break;
// case '$parent.tipsterFilter':
// scope.$parent.tipsterFilter = false;
// break;
// case '$parent.tipsterTopFilter':
// scope.$parent.tipsterTopFilter = false;
// break;
// case 'predictiveSearch':
// scope.search.tags = '';
// scope.predictiveSearch = false;
// break;
// case 'predictiveCentralSearch':
// scope.search.tags = '';
// scope.predictiveCentralSearch = false;
// break;
// }
// /* Inicializamos */
// first = true;
// /* Aplicamos scope */
// scope.$apply();
// }
// else
// /* No es la primera vez */
// first = false;
// }
// }
// };
// })
// .directive("tooltipTouchChart", function( $document )
// {
// return {
// link: function (scope, element, attrs)
// {
// element.on('touchstart', function (e)
// {
// angular.element(element).find('.nvtooltip').css("display", "block");
// });
// element.on('touchend', function (e)
// {
// angular.element(element).find('.nvtooltip').css("display", "none");
// });
// }
// }
// })
// .directive("hideFilterOutside", function( $document )
// {
// return {
// link: function (scope, element, attrs)
// {
// $document.on('click', function (e)
// {
// scope.$apply(function ()
// {
// if( !element[0].contains(e.target) )
// {
// switch( e.target.lang )
// {
// case 'live-list-filter':
// scope.$parent.liveListFilter = true;
// break;
// case 'live-market-filter':
// scope.$parent.liveMarketFilter = true;
// break;
// case 'menu-filter':
// scope.menuFilter = true;
// break;
// case 'prematch-list-filter':
// scope.$parent.prematchListFilter = true;
// break;
// case 'prematch-market-filter':
// scope.$parent.prematchMarketFilter = true;
// break;
// case 'tipster-filter':
// scope.$parent.tipsterFilter = true;
// break;
// case 'tipster-top-filter':
// scope.$parent.$parent.tipsterTopFilter = true;
// break;
// default:
// /* Control de submenus */
// if( scope.menuFilter == true && scope.mblInter == true )
// scope.mblInter = false;
// /* Ocultamos */
// scope.$parent.liveListFilter = false;
// scope.$parent.liveMarketFilter = false;
// scope.menuFilter = false;
// scope.$parent.prematchListFilter = false;
// scope.$parent.prematchMarketFilter = false;
// scope.$parent.tipsterFilter = false;
// scope.$parent.tipsterTopFilter = false;
// break;
// }
// }
// });
// });
// }
// }
// })
// .directive("scroll", function($window, $rootScope)
// {
// return function(scope, element, attrs)
// {
// // var userAgent = $window.navigator.userAgent,
// // browsers = ["Mobile","iPhone","iPod","BlackBerry","Opera Mini","Sony","MOT","Nokia","samsung"],
// // typeMobile = false;
// // for(var key in browsers)
// // {
// // if( userAgent.indexOf(browsers[key]) != -1 )
// // {
// // typeMobile = true;
// // }
// // break;
// // };
// angular.element($window).bind("scroll", function()
// {
// if (this.pageYOffset > 273)
// $rootScope.fScrollData = true;
// else
// $rootScope.fScrollData = false;
// scope.$apply();
// });
// };
// })
// .directive("inputHeaderSearch", function($window, $location, $anchorScroll)
// {
// return function( scope, element, attrs)
// {
// var userAgent = $window.navigator.userAgent,
// browsers = ["Mobile","iPhone","iPod","BlackBerry","Opera Mini","Sony","MOT","Nokia","samsung"];
// for(var key in browsers)
// {
// if( userAgent.indexOf(browsers[key]) != -1 )
// {
// element.attr("disabled", "disabled");
// }
// break;
// };
// element.bind("touchend", function()
// {
// document.location.href = "search.html";
// });
// };
// })
// .directive('activeBet', function( $localStorage )
// {
// return {
// restrict: 'A',
// link: function (scope, element, attrs)
// {
// var id = attrs['id'],
// el = element;
// angular.forEach($localStorage.simple, function(value, key)
// {
// if( id == value.id_element )
// {
// el.toggleClass('betslip-active', true );
// }
// });
// /* Cuando se fuerza el evento con $scope.broadcast lanza esta función */
// scope.$on('del-active-betslip', function( event, id )
// {
// if( el[0].id == id )
// {
// el.toggleClass('betslip-active', false );
// }
// });
// /* Cuando se fuerza el evento con $scope.broadcast lanza esta función */
// scope.$on('add-active-betslip', function( event, id )
// {
// if( el[0].id == id )
// {
// el.toggleClass('betslip-active', true );
// }
// });
// }
// };
// })
// .directive('betinput', function( $window )
// {
// return {
// template: '<input type="tel" ng-model="bet" ng-init="bet=0" maxlength="9">',
// restrict: 'E', //<betinput></betinput> hace referencia a un elemento/etiqueta html
// require: 'ngModel',
// replace: true,
// link: function( scope, element, attrs, modelCtrl )
// {
// modelCtrl.$parsers.push(function (inputValue)
// {
// var transformedInput = inputValue ? inputValue.replace(/[^\d.-]/g,'') : null;
// if (transformedInput!=inputValue) {
// modelCtrl.$setViewValue(transformedInput);
// modelCtrl.$render();
// }
// return transformedInput;
// });
// // element.bind("focus", function()
// // {
// // if (!$window.getSelection().toString())
// // this.setSelectionRange(0, 9)
// // });
// element.bind("click", function()
// {
// if (!$window.getSelection().toString())
// this.setSelectionRange(0, this.value.length)
// });
// }
// };
// })
// .directive('validatiOn', function ()
// {
// return {
// restrict: 'A',
// require: '^form', /* */
// link: function (scope, el, attrs, form)
// {
// /* Cogemos el elemento input dentro de 'el', que es el contenedor (coge el que tiene el atributo 'name')... */
// var inputEl = el[0].querySelector('[name]'),
// /* lo convertimos en elemento de angular */
// inputNgEl = angular.element(inputEl),
// /* Cogemos el atributo 'name' para validar en el formulario más abajo */
// inputName = inputNgEl.attr('name');
// /* Cuando el usuario sale del elemento, aplica la clase .has-error a la capa que contiene el input */
// inputNgEl.bind('blur', function ()
// {
// el.toggleClass('has-error', form[inputName].$invalid);
// });
// /* Cuando se fuerza el evento con $scope.broadcast lanza esta función */
// scope.$on('validate-form', function( event, formName )
// {
// if( form.$name == formName )
// el.toggleClass('has-error', form[inputName].$invalid);
// });
// }
// };
// })
// /************************************************************************/
// /* Filtros */
// /************************************************************************/
// .filter('trim', function ()
// {
// return function(value)
// {
// if(!angular.isString(value))
// return value;
// return value.replace(/^\s+|\s+$/g, ''); // no utilizamos trim()
// };
// })
// .filter('replaceName', function()
// {
// return function (input) {
// if(!input) return;
// return input.toLowerCase()
// .replace(/[áàäâå]/g, 'a')
// .replace(/[éèëê]/g, 'e')
// .replace(/[íìïî]/g, 'i')
// .replace(/[óòöô]/g, 'o')
// .replace(/[úùüû]/g, 'u')
// .replace(/[ýÿ]/g, 'y')
// .replace(/[ñ]/g, 'n')
// .replace(/[ç]/g, 'c')
// .replace(/['"]/g, '')
// .replace(/\//g, "")
// .replace(/ /g, '-');
// };
// })
// .filter('cutTwoPoints', function()
// {
// return function( input, position ) {
// if( !input || !position ) return;
// var info = input.split(" : ");
// if( info.length == 1 )
// info = input.split(":");
// if( info.length == 1 ) return;
// if( position == 'left' )
// return info[0] == '' ? '-' : info[0];
// else if( position == 'right' )
// return info[1] == '' ? '-' : info[1];
// else
// return;
// }
// })
// .filter('infoSets', function()
// {
// return function (input) {
// if(!input) return;
// var exit = "";
// for( var nCont = 0, len = input.length;
// nCont < len;
// nCont++ )
// {
// exit += input[nCont].replace(/ /g, '') + " ";
// }
// return exit;
// }
// })
// .filter('timeZoneOffset', function( $localStorage )
// {
// return function( input )
// {
// if( !input ) return; // Control para evitar vacios
// var targetTime = new Date( input ),
// timeZoneOffset = $localStorage.timeZoneOffset || 0,
// offsetTime = new Date( targetTime.getTime() + timeZoneOffset );
// //format = format || "dd/mm HH:MM";
// //return offsetTime.format( format );
// return offsetTime;
// }
// })
// .filter('oddsConverter', function( $localStorage )
// {
// function reduce(a,b)
// {
// var n = new Array(2);
// var f = GCD(a,b);
// n[0] = a/f;
// n[1] = b/f;
// return n;
// }
// function GCD(num1,num2)
// {
// var a; var b;
// if (num1 < num2) {a = num2; b = num1;}
// else if (num1 > num2) {a = num1; b = num2;}
// else if (num1 == num2) {return num1;}
// while(1)
// {
// if (b == 0)
// return a;
// else
// {
// var temp = b;
// b = a % b;
// a = temp;
// }
// }
// }
// return function( input, places )
// {
// if( angular.isUndefined(input) || input == null )
// return;
// var type = $localStorage.oddsType || "decimal",
// places = angular.isUndefined(places) ? 2 : places;
// switch( type )
// {
// case "us":
// input-=1;
// if(input < 1)
// return('-'+(100/input).toFixed(2));
// else
// return('+'+(input*100).toFixed(2));
// break;
// case "fraction":
// input = parseFloat(input).toFixed(2);
// var num = (input-1) * 10000;
// var dom = 10000;
// num = Math.round(num);
// dom = Math.round(dom);
// var a = reduce(num,dom);
// num = a[0];
// dom = a[1];
// return(num+'/'+dom);
// break;
// default:
// return parseFloat(input.toFixed( places ))+' ';
// break;
// }
// };
// })
// .filter('setBetSlipDecimal', function ($filter)
// {
// return function( input, places )
// {
// if(isNaN(input) || input === null ) return input;
// return input.toFixed( places );
// };
// })
// .filter('isArray', function()
// {
// return function (input) {
// return angular.isArray(input);
// };
// })
// .filter('startFrom', function()
// {
// return function(input, start)
// {
// if( !input ) return; // Control para evitar vacios
// start = +start; //parse to int
// return input.slice(start);
// }
// })
// .filter('toArray', function ()
// {
// 'use strict';
// return function (obj)
// {
// if (!(obj instanceof Object))
// return obj;
// return Object.keys(obj).map(function (key)
// {
// return Object.defineProperty(obj[key], '$key', {__proto__: null, value: key});
// });
// }
// })
// .filter('orderObjectBy', function()
// {
// return function(items, field, reverse)
// {
// var filtered = [];
// angular.forEach(items, function(item)
// {
// filtered.push(item);
// });
// filtered.sort(function (a, b)
// {
// return (a[field] > b[field]) ? 1 : ((a[field] < b[field]) ? -1 : 0);
// });
// if(reverse) filtered.reverse();
// return filtered;
// };
// })
// .filter('range', function()
// {
// return function(input, total)
// {
// total = parseInt(total);
// for (var i=0; i<total; i++)
// input.push(i);
// return input;
// };
// })
// .filter('reverse', function()
// {
// return function(items)
// {
// return items.slice().reverse();
// };
// })
// .filter('setTextual', function ($filter)
// {
// return function ( input, nChar )
// {
// if( !input ) return input;
// var text,
// nch = nChar-3;
// if( input.length > nch )
// return input.substr(0, nch) + "...";
// else
// return input;
// };
// })
// .filter('setDecimal', function ($filter)
// {
// return function (input, places)
// {
// if (isNaN(input)) return input;
// var factor = "1" + Array(+(places > 0 && places + 1)).join("0");
// return Math.round(input * factor) / factor;
// };
// })
// .filter('nospace', function ()
// {
// return function (value)
// {
// return (!value) ? '' : value.replace(/ /g, '');
// };
// })
// .filter('startFromMarket', [function()
// {
// return function(obj, limit)
// {
// var keys = Object.keys(obj);
// if(keys.length < 1)
// return [];
// var ret = new Object,
// count = 0;
// angular.forEach(keys, function(key, arrayIndex)
// {
// if(count < limit)
// count++;
// else
// {
// ret[key] = obj[key];
// count++;
// }
// });
// return ret;
// };
// }])
// .filter('myLimitTo', [function()
// {
// return function(obj, limit)
// {
// var keys = Object.keys(obj);
// if(keys.length < 1){
// return [];
// }
// var ret = new Object,
// count = 0;
// angular.forEach(keys, function(key, arrayIndex)
// {
// if(count >= limit)
// return false;
// ret[key] = obj[key];
// count++;
// });
// return ret;
// };
// }])
// .filter('reverseAnything', function()
// {
// return function(items)
// {
// if(typeof items === 'undefined') { return; }
// return angular.isArray(items) ?
// items.slice().reverse() : // If it is an array, split and reverse it
// (items + '').split('').reverse().join(''); // else make it a string (if it isn't already), and reverse it
// };
// })
// .filter('limitText', function ()
// {
// return function (value)
// {
// value = String(value).replace(/<[^>]+>/gm, '');
// var limit = 210;
// if(value.length > limit)
// return value.substr(0,limit) + " ...";
// else
// {
// var diff = limit - parseInt(value.length);
// var white ="";
// for(var index = 0; index < diff; index++)
// {
// white += "  ";
// }
// return value + white ;
// }
// };
// })
// .filter('filterMarkets', function ()
// {
// return function (items, group)
// {
// var filtered = [];
// angular.forEach(items, function(value, key)
// {
// angular.forEach(group, function(valueGroup, keyGroup)
// {
// if(value.id_market == valueGroup)
// filtered.push(value);
// });
// });
// return filtered;
// };
// })
// .filter( 'shortName', function()
// {
// var limitChar = 10;
// function cutName( str, limit )
// {
// str = str.substr(0, limit-3 );
// str += "...";
// return str;
// };
// return function( input, order )
// {
// var player = input.split(" vs "),
// plus0 = 0,
// plus1 = 0;
// if( player[0].length < limitChar )
// plus1 = limitChar - player[0].length;
// if( player[1].length < limitChar )
// plus0 = limitChar - player[1].length;
// if( player[0].length > limitChar )
// player[0] = cutName( player[0], limitChar+plus0 );
// if( player[1].length > limitChar )
// player[1] = cutName( player[1], limitChar+plus1 );
// if( order == 1 )
// return player[0];
// return player[1];
// };
// })
// /* Para pormociones. Sustituye el tag <strong> por <span> con negrita */
// .filter('replaceTagHTML', function()
// {
// return function(textHTML)
// {
// var begin = textHTML.replace(/<strong>/gi, "<span class='strong'>");
// return begin.replace(/<\/strong>/gi, "</span>");
// }
// })
/************************************************************************/
/* Controladores */
/************************************************************************/
// .controller('metaTags', function( $scope, $location, $rootElement , $http, $rootScope)
// {
// /* Realizar base name */
// var metaFragment = document.getElementsByTagName('meta')[1],
// el = document.createElement("base");
// if( $location.host() == "des.besgam.com" )
// el.setAttribute("href", "//des.besgam.com/");
// else
// el.setAttribute("href", "//www.besgam.com/");
// metaFragment.parentNode.insertBefore(el, metaFragment.nextSibling);
// if($location.host() == "des.besgam.com")
// $scope.metadata = {
// 'content' : 'noindex, nofollow'
// };
// else
// $scope.metadata = {
// 'content' : 'index, follow'
// };
// /* SEO PARA LA FICHA DEL EVENTO */
// $scope.capitalize = function(dataString)
// {
// var all = dataString.split(" ");
// var result = "";
// angular.forEach(all, function(value, key) {
// all[key] = value.substr(0,1).toUpperCase()+value.substr(1,value.length) + " ";
// });
// all = all.join(" ");
// all = all.substr(0, all.length - 1);
// return all;
// }
// /* Titulo de la ficha */
// var url_event = $location.url();
// url_event = url_event.split('/');
// if(url_event[1]=="apuestas" && url_event.length > 6)
// {
// /* Obtener datos de los equipos, deportes y ligas */
// var league_card = url_event[2].replace(/-/g," ");
// var event_card = url_event[3].replace(/-/g," ");
// var event_card = event_card.split('vs');
// var team1 = "";
// var team2 = "";
// if(event_card.length >1){
// team2 = event_card[1].replace(/(^\s*)|(\s*$)/g,"");
// }
// team1 = event_card[0].replace(/(^\s*)|(\s*$)/g,"");
// var idsport_card = parseInt(url_event[5],10) - 1;
// var dataSport = {
// method: 'GET',
// url: 'json/sports.json',
// cache: true,
// headers: {
// 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
// }
// };
// /* Segun el deporte se añaden los meta y los keywords*/
// $http(dataSport).
// success(function(data, status, headers, config)
// {
// sport_card = data[idsport_card].sportName ;
// document.querySelector('title').innerHTML = "Apuesta al "+ $scope.capitalize(team1) + " " + $scope.capitalize(team2) + " "+ sport_card + " " + $scope.capitalize(league_card) +
// " tras conocer con Besgam las mejores cuotas";
// var description = document.querySelector("meta[name=description]");
// var txt_team2 = (team2!="") ? $scope.capitalize(team2) + " " : "";
// var txt_description = "Busca en Besgam las mejores cuotas del mercado para "+ $scope.capitalize(team1) +" "
// + txt_team2 + sport_card + " " + $scope.capitalize(league_card) +
// ". Compara y consigue el mayor rendimiento en tus apuestas deportivas";
// description.setAttribute('content', txt_description);
// var keywords = document.querySelector("meta[name=keywords]");
// var txt_team2 = (team2!="") ? $scope.capitalize(team2) + ", " : "";
// keywords.setAttribute('content',
// $scope.capitalize(team1) + ", " +
// txt_team2 +
// sport_card + ", " +
// $scope.capitalize(league_card) +
// ", besgam, apuestas, rendimiento, comparador de cuotas, casas apuestas, comparador apuestas, apuestas deportivas");
// }).
// error(function(data, status, headers, config)
// {
// });
// }
// })
// .controller("besgamSearch", function( $rootScope, $scope, $http, $location, $translate, $route, dataFactory )
// {
// var now = new Date(),
// url = $location.url(),
// endUrl = url.split("?");
// $scope.placeholder = $route.current.params.target;
// $scope.isNotHome = function()
// {
// if( ( endUrl[0] == "/search" || endUrl[0] == "/home" || endUrl[0] == "/" ) && !$scope.fScrollData )
// return false;
// else
// return true;
// };
// $translate('controller.search.param1').then(function (translation)
// {
// $scope.placeholder = ($route.current.params.target == translation || angular.isUndefined($route.current.params.target)) ? 'header.betFinderM.search' : $route.current.params.target;
// });
// $translate('centralFinder.filter.sport').then(function (translation) // "Deporte";
// {
// $scope.titleSport = translation;
// });
// $translate('centralFinder.filter.competition').then(function (translation) // "Competición";
// {
// $scope.titleLeague = translation;
// });
// $scope.search = [];
// $scope.submit = function(form)
// {
// if( typeof($scope.search.tags) == 'undefined' || $scope.search.tags == '' ) $scope.search.tags = $translate.instant('controller.search.param1');
// if( typeof($scope.search.sport) == 'undefined' || $scope.search.sport == '' ) $scope.search.sport = $translate.instant('controller.search.param2');
// if( typeof($scope.search.league) == 'undefined' || $scope.search.league == '' ) $scope.search.league = $translate.instant('controller.search.param3');
// var href = "./#!search";
// if( $scope.search.tags != "" )
// href += "/" + $scope.search.tags;
// if( $scope.search.sport != "" )
// href += "/" + $scope.search.sport;
// if( $scope.search.league != "" )
// href += "/" + $scope.search.league;
// document.location.href = href;
// //document.forms[form].submit();
// };
// dataFactory.getDataJson().then( function(response)
// {
// $scope.dataJson = response.data;
// $scope.sports = $scope.dataJson.reduce(function(sum, place)
// {
// if (sum.indexOf( place.sport ) < 0) sum.push( place.sport );
// return sum;
// }, []);
// $scope.createLeagues();
// });
// $scope.createLeagues = function()
// {
// if( typeof $scope.search != 'undefined' )
// $scope.titleSport = ( $scope.search.sport == "" ) ? $translate.instant('centralFinder.filter.sport') : $scope.search.sport;
// $scope.leagues = $scope.dataJson.reduce(function(sum, place)
// {
// if( typeof $scope.search.sport != 'undefined' && $scope.search.sport != "" )
// {
// if (sum.indexOf( place.league ) < 0 && $scope.search.sport == place.sport )
// sum.push( place.league );
// }
// else
// {
// if (sum.indexOf( place.league ) < 0) sum.push( place.league );
// }
// return sum;
// }, []);
// $scope.search.league = "";
// };
// $scope.selectLeagues = function()
// {
// $scope.titleLeague = ($scope.search.league == "") ? $translate.instant('centralFinder.filter.competition') : $scope.search.league;
// };
// })
// .controller("betslip", function( $scope, $rootScope, $http, $window, $localStorage, $location, $timeout, $translate, dataFactory, dateTime, device )
// {
// $scope.$lStorage = $localStorage;
// $scope.isArray = angular.isArray;
// $scope.tabActive = 0;
// $scope.resetData = function()
// {
// $scope.$lStorage.simple = [];
// $scope.$lStorage.combined = [
// {"bets": -1, "betSlip": [], "totalCombined": {} },
// {"bets": -1, "betSlip": [], "totalCombined": {} },
// {"bets": -1, "betSlip": [], "totalCombined": {} },
// {"bets": -1, "betSlip": [], "totalCombined": {} }
// ];
// $scope.$lStorage.tabActive = 0;
// };
// /* Definimos el localStorage */
// if( angular.isUndefined( $scope.$lStorage.simple ) ||
// angular.isUndefined( $scope.$lStorage.combined ) )
// {
// $scope.resetData();
// }
// /* Control de eventos caducados */
// else
// {
// if( $scope.$lStorage.simple.length > 0 )
// {
// var expirationSimple = false;
// /* Comprobamos si ya existe */
// angular.forEach( $scope.$lStorage.simple, function(value, key)
// {
// var isExpiration = dateTime.fExpiration( value.expiration );
// if( isExpiration )
// {
// value.is_expiration = isExpiration;
// expirationSimple = true;
// }
// });
// /* Solo buscamos eventos caducados en las cestas combinadas */
// /* si hemos encontrado algun evento caducado en las simples */
// if( expirationSimple )
// {
// /* Buscamos en las apuestas de combinadas */
// angular.forEach( $scope.$lStorage.combined, function(value, key)
// {
// angular.forEach( value.bets, function(bet, betKey)
// {
// bet.is_expiration = dateTime.fExpiration( bet.expiration );
// });
// });
// }
// }
// }
// /* Cargamos los datos de las feed */
// dataFactory.getDataFeed().then( function(response)
// {
// $scope.feed = response.data;
// });
// $rootScope.getIdName = function( id_event, id_market, str_bet )
// {
// return id_event+"|"+id_market+"|"+str_bet;
// };
// $rootScope.addLocal = function( id_element, id_sport, id_league, str_league, id_event, str_event, str_market, str_bet, bet, dt_expiration, default_feed )
// {
// var addSimple = true, // Inicializamos a TRUE para insertar en simple
// addCombined = true;
// if( $scope.$lStorage.simple.length > 0 )
// {
// /* Comprobamos si ya existe */
// angular.forEach( $scope.$lStorage.simple, function(value, key)
// {
// if( value.id_element == id_element )
// {
// addSimple = false;
// addCombined = false;
// $scope.delSimple( key );
// // if( $scope.$lStorage.combined[ $scope.$lStorage.tabActive ].bets != -1 )
// // {
// // angular.forEach( $scope.$lStorage.combined[ $scope.$lStorage.tabActive ].bets, function( bet, key )
// // {
// // if( bet.id_element == id_element )
// // {
// // addCombined = false;
// // }
// // });
// // }
// }
// });
// }
// if( addSimple || addCombined )
// {
// var bets = {
// "id_element": id_element,
// "id_sport": id_sport,
// "id_league": id_league,
// "str_league": str_league,
// "id_event": id_event,
// "str_event": str_event,
// "str_market": str_market,
// "str_bet": str_bet,
// "expiration": dt_expiration,
// "is_expiration": 0,
// "focus_bet": {
// "id_feed": bet[0].id_feed,
// "n_odd": bet[0].n_odd,
// "id_bet": bet[0].id_bet,
// "is": 1
// },
// "simple_bet": bet[default_feed],
// "bet": bet,
// "duplicate": 0
// };
// /* Comprobamos si tenemos otro apuesta del mismo evento */
// bets.duplicate = $scope.duplicate( id_event, $scope.$lStorage.tabActive, 'add' );
// bets.is_expiration = dateTime.fExpiration( dt_expiration );
// /* Se guarda en el localStorage */
// if( addSimple ) // Simple
// $scope.$lStorage.simple.push(bets);
// if( addCombined )
// {
// /* Comprobamos que sea array */
// if( $scope.$lStorage.combined[ $scope.$lStorage.tabActive ].bets == -1 )
// $scope.$lStorage.combined[ $scope.$lStorage.tabActive ].bets = [];
// $scope.$lStorage.combined[ $scope.$lStorage.tabActive ].bets.push(bets);
// $scope.addBetSlip( bets.bet );
// }
// /* Salvamos el localStorage */
// $scope.$lStorage.$save();
// /* Visualizamos la cesta por primera vez */
// /* Y que no sea un dispositivo */
// if( $scope.$lStorage.simple.length == 1 && !device.is() )
// $rootScope.showBag = 1;
// /* Eliminamos de la directiva */
// $rootScope.$broadcast('add-active-betslip', bets.id_element );
// }
// };
// // function fExpiration( strTime )
// // {
// // if( !strTime ) return; // Control para evitar vacios
// // /* Hora del evento + UTC */
// // var targetTime = new Date( strTime ),
// // offsetTime = new Date( targetTime.getTime() + $localStorage.timeZoneOffset );
// // /* NOW + UTC */
// // var now = new Date(),
// // nowUTC = new Date( now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds() ),
// // today = new Date( nowUTC.getTime() + $localStorage.timeZoneOffset );
// // return (offsetTime > today ) ? 0 : 1;
// // };
// $scope.duplicate = function( id_event, tabActive, action )
// {
// var duplicate = 0,
// duplicates = [];
// /* Comprobamos si ya tenemos el evento de otra apuesta */
// angular.forEach( $scope.$lStorage.combined[ tabActive ].bets, function(value, key)
// {
// if( value.id_event == id_event )
// {
// if( action == 'add' )
// {
// value.duplicate = 1;
// duplicate = 1;
// }
// else if( action == 'delete' )
// {
// duplicates.push( key );
// }
// }
// });
// if( duplicates.length < 3 )
// {
// for( var nCont = 0, len = duplicates.length;
// nCont < len;
// nCont++ )
// {
// $scope.$lStorage.combined[ tabActive ].bets[ duplicates[nCont] ].duplicate = 0;
// }
// }
// return duplicate;
// };
// $scope.getMsg = function( focus_bet, duplicate, expiration, feed, str_event )
// {
// if( expiration )
// {
// return $translate.instant('controller.msg-betslip.msg1');
// }
// else if( focus_bet )
// {
// return $translate.instant('controller.msg-betslip.msg2') + feed;
// }
// else
// {
// return $translate.instant('controller.msg-betslip.msg3') + str_event;
// }
// };
// $scope.delSimple = function( id )
// {
// $timeout(function()
// {
// /* Eliminamos de la directiva */
// $rootScope.$broadcast('del-active-betslip', $scope.$lStorage.simple[ id ].id_element );
// /* Buscamos en las apuestas de combinadas */
// angular.forEach( $scope.$lStorage.combined, function(value, key)
// {
// angular.forEach( value.bets, function(bet, betKey)
// {
// /* Si encontramos la apuesta */
// if( bet.id_element == $scope.$lStorage.simple[ id ].id_element )
// {
// /* Comprobamos eventos duplicados de un mismo evento */
// $scope.duplicate( $scope.$lStorage.combined[ key ].bets[betKey].id_event, key, 'delete' );
// $scope.delBetSlip( $scope.$lStorage.combined[ key ].bets[betKey].bet, key );
// /* Eliminamos la apuesta de la combinada */
// $scope.$lStorage.combined[ key ].bets.splice( betKey, 1);
// }
// });
// });
// /* Eliminamos del array simple */
// $scope.$lStorage.simple.splice(id, 1);
// if( $scope.$lStorage.simple.length == 0 )
// $scope.resetData();
// $scope.$lStorage.$save();
// },400);
// };
// $scope.delSimpleCombined = function( id, tabActive )
// {
// var fSearch = false;
// /* Buscamos en las apuestas de combinadas */
// angular.forEach( $scope.$lStorage.combined, function(value, key)
// {
// angular.forEach( value.bets, function(bet, betKey)
// {
// /* Si encontramos la apuesta */
// if( bet.id_element == $scope.$lStorage.combined[ tabActive ].bets[id].id_element && key != tabActive )
// fSearch = true;
// });
// });
// /* Si no encontramos la apuesta en otra vista borramos de la simple */
// if( !fSearch )
// {
// angular.forEach( $scope.$lStorage.simple, function(value, key)
// {
// /* Si encontramos la apuesta */
// if( value.id_element == $scope.$lStorage.combined[ tabActive ].bets[id].id_element )
// {
// /* Eliminamos de la directiva */
// $rootScope.$broadcast('del-active-betslip', $scope.$lStorage.simple[ key ].id_element );
// /* Eliminamos la apuesta de la simple */
// $scope.$lStorage.simple.splice(key, 1);
// }
// });
// }
// };
// $scope.delCombined = function( id, tabActive )
// {
// $timeout(function()
// {
// /* Comprobamos eventos duplicados de un mismo evento */
// $scope.duplicate( $scope.$lStorage.combined[ tabActive ].bets[id].id_event, tabActive, 'delete' );
// $scope.delSimpleCombined( id, tabActive );
// if( $scope.$lStorage.simple.length == 0 )
// $scope.resetData();
// else
// {
// $scope.delBetSlip( $scope.$lStorage.combined[ tabActive ].bets[id].bet, tabActive );
// $scope.$lStorage.combined[ tabActive ].bets.splice(id, 1);
// if( $scope.$lStorage.combined[ tabActive ].bets.length == 0 )
// $scope.$lStorage.combined[ tabActive ] = {"bets": -1, "betSlip": [], "totalCombined": {} };
// }
// $localStorage.$save();
// },400);
// };
// $scope.delTab = function( id )
// {
// angular.forEach( $scope.$lStorage.combined[ id ].bets, function(bet, bKey)
// {
// $scope.delSimpleCombined( bKey, id);
// });
// $scope.$lStorage.combined[ id ] = {"bets": -1, "betSlip": [], "totalCombined": {} };
// $scope.$lStorage.$save();
// };
// $scope.copyTab = function( active, id )
// {
// if( angular.isArray( $scope.$lStorage.combined[ id ].bets ) )
// {
// $scope.$lStorage.combined[ active ] = angular.copy( $scope.$lStorage.combined[ id ] );
// $scope.$lStorage.$save();
// }
// };
// $scope.changeSimple = function( idBet, id )
// {
// $scope.$lStorage.simple[ idBet ].simple_bet = $scope.$lStorage.simple[ idBet ].bet[ id ];
// $scope.$lStorage.$save();
// };
// $scope.totalCombined = function( odd, feed, tabActive )
// {
// var total = 0,
// exit = false;
// if( angular.isUndefined( tabActive) )
// tabActive = $scope.$lStorage.tabActive;
// if( angular.isUndefined( feed ) && angular.isUndefined( odd ) )
// {
// angular.forEach( $scope.$lStorage.combined[ tabActive ].betSlip, function(value, key)
// {
// if( value.n_odd > total )
// {
// total = value.n_odd;
// $scope.$lStorage.combined[ tabActive ].totalCombined = {
// "value": value.n_odd,
// "feed": value.id_feed
// };
// }
// });
// }
// else
// {
// $scope.$lStorage.combined[ tabActive ].totalCombined = {
// "value": odd,
// "feed": feed
// };
// }
// /* Modificamos el foco */
// angular.forEach( $scope.$lStorage.combined[ tabActive ].bets, function(value, key)
// {
// for( var nCont = 0, len = value.bet.length;
// nCont < len && !exit; nCont++ )
// {
// if( value.bet[nCont].id_feed == $scope.$lStorage.combined[ tabActive ].totalCombined.feed )
// {
// value.focus_bet.id_feed = value.bet[nCont].id_feed;
// value.focus_bet.n_odd = value.bet[nCont].n_odd;
// value.focus_bet.id_bet = value.bet[nCont].id_bet;
// value.focus_bet.is = 1;
// exit = true;
// }
// }
// /* No existe la apuesta para la casa seleccionada */
// if( !exit ) value.focus_bet.is = 0;
// /* Volvemos a iniciar la salida */
// exit = false;
// });
// $scope.$lStorage.$save();
// };
// $scope.addBetSlip = function( bets )
// {
// var obj = {}, // Obj para insertar en nuestro boleto
// fSearch = false; // Comprobar si ya tenemos ese feed
// angular.forEach(bets, function(bet, bKey)
// {
// angular.forEach( $scope.$lStorage.combined[ $scope.$lStorage.tabActive ].betSlip, function( value, key )
// {
// if( bet.id_feed == value.id_feed )
// {
// value.n_odd = value.n_odd * bet.n_odd;
// fSearch = true;
// }
// });
// /* Si no lo encontramos lo insertamos */
// if( !fSearch )
// $scope.$lStorage.combined[ $scope.$lStorage.tabActive ].betSlip.push({
// "id_feed": bet.id_feed,
// "n_odd": bet.n_odd
// });
// fSearch = false;
// });
// $scope.totalCombined();
// };
// $scope.delBetSlip = function( bets, tabActive )
// {
// angular.forEach(bets, function(bet, bKey)
// {
// angular.forEach( $scope.$lStorage.combined[ tabActive ].betSlip, function( value, key )
// {
// if( bet.id_feed == value.id_feed )
// {
// value.n_odd = value.n_odd / bet.n_odd;
// if( value.n_odd <= 1 )
// $scope.$lStorage.combined[ tabActive ].betSlip.splice(key, 1);
// }
// });
// });
// $scope.totalCombined( undefined, undefined, tabActive );
// };
// $scope.locationTo = function( str_league, str_event, id_event, id_sport )
// {
// str_league = str_league.replace(/\//g,"-");
// str_league = str_league.replace(/ /g,"-");
// str_event = str_event.replace(/\//g,"-");
// str_event = str_event.replace(/ /g,"-");
// window.location = "./#!apuestas/" + angular.lowercase(str_league) + "/" + angular.lowercase(str_event) + "/" + id_event + "/" + id_sport + "/"
// };
// $scope.submit = function( type )
// {
// var url = "",
// host = $location.$$absUrl.split("#");
// if( type == 'simple')
// {
// url = "./#!redirect/" +
// this.simple.simple_bet.id_feed + "/" +
// this.simple.id_league + "/" +
// this.simple.id_event + "/" +
// this.simple.simple_bet.id_bet + "/" +
// "0/";
// }
// else if( type == 'combined' )
// {
// var bets = [];
// for( var nCont = 0, len = this.bagCombined.bets.length;
// nCont < len;
// nCont++ )
// {
// if( this.bagCombined.bets[nCont].focus_bet.is )
// bets.push( this.bagCombined.bets[nCont].focus_bet.id_bet );
// }
// url = "./#!redirect/" +
// this.bagCombined.totalCombined.feed + "/" +
// this.bagCombined.bets[0].id_league + "/" +
// this.bagCombined.bets[0].id_event + "/" +
// bets.join() + "/" +
// "0/";
// }
// $window.open( host[0]+url, '_blank' );
// };
// })
// .controller("redirect", function( $scope, $http, $route, $interpolate, $sessionStorage, $filter, eventTrack, dataFactory )
// {
// var id_feed = $route.current.params.id_feed,
// id_league = $route.current.params.id_league,
// id_event = $route.current.params.id_event,
// id_bet = $route.current.params.id_bet,
// id_bid = $route.current.params.id_bid,
// url = null,
// getDataEvent = {
// method: 'POST',
// url: 'php/redirect.php',
// headers: {
// 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
// },
// data: 'id_feed=' + id_feed + '&id_league=' + id_league + "&id_event=" + id_event
// },
// getBetSlip = {
// method: 'POST',
// url: 'php/betSlip.php',
// headers: {
// 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
// },
// data: 'id_feed=' + id_feed + "&id_bet=" + id_bet + "&id_event=" + id_event + "&id_bid=" + id_bid + "&id_user=" + $sessionStorage.iduser
// }
// /* Traqueamos el evento */
// eventTrack.new({
// name: "redirect",
// category: "prematch",
// label: id_feed+"-"+id_league+"-"+id_event+"-"+id_bet+"-"+id_bid
// });
// /* Carga de datos de feeds */
// dataFactory.getDataFeed().then( function(response)
// {
// var dataFeed = response.data;
// $scope.img_feed = dataFeed[ id_feed ].str_image;
// if( dataFeed[ id_feed ].str_link_bag != "" )
// {
// url = dataFeed[ id_feed ].str_link_bag;
// /* Recuperamos datos del evento */
// $http(getBetSlip).
// success(function(dataBet, status, headers, config)
// {
// $scope.id_event = $filter('trim')(id_event);
// $scope.id_bet = $filter('trim')(dataBet.id_bet);
// $scope.id_market = $filter('trim')(dataBet.id_market);
// $scope.str_bid = $filter('trim')(dataBet.str_bid) || $filter('trim')(dataFeed[ id_feed ].str_bid);
// switch( parseInt(id_feed) )
// {
// /* INTERWETTEN */
// case 5:
// /* Recuperamos datos del evento */
// $http(getDataEvent).
// success(function(dataEvent, status, headers, config)
// {
// /* Control para eventos caducados */
// if( dataEvent.length == 0)
// {
// dataEvent[0] = {
// "id_league": 0,
// "id_event": 0,
// "link_event": ''
// };
// }
// $scope.id_feed = id_feed;
// $scope.id_league = dataEvent[0]['id_league'];
// $scope.id_event = dataEvent[0]['id_event'];
// /* Componemos la url */
// url = $interpolate(url)($scope);
// document.location.href = url;
// });
// break;
// default:
// /* Componemos la url */
// url = $interpolate(url)($scope);
// document.location.href = url;
// break
// }
// });
// }
// else if( dataFeed[ id_feed ].str_link_event != "" )
// {
// url = dataFeed[ id_feed ].str_link_event;
// /* Recuperamos datos del evento */
// $http(getDataEvent).
// success(function(dataEvent, status, headers, config)
// {
// /* Control para eventos caducados */
// if( dataEvent.length == 0)
// {
// dataEvent[0] = {
// "id_league": 0,
// "id_event": 0,
// "link_event": ''
// };
// }
// $scope.id_feed = id_feed;
// $scope.id_league = dataEvent[0]['id_league'];
// $scope.id_event = dataEvent[0]['id_event'];
// switch( parseInt(id_feed) )
// {
// /* William Hill */
// case 3:
// if( dataEvent[0]['link_event'] != "" )
// {
// // http://sports.williamhill.com/bet/en-gb/betting/e/8153439/Lee%2dSelby%2dv%2dFernando%2dMontiel
// var strFrag = dataEvent[0]['link_event'].split(/\/e\//),
// strLink = strFrag[1].split('/');
// $scope.id_event = strLink[0];
// }
// break;
// }
// /* Componemos la url */
// url = $interpolate(url)($scope);
// document.location.href = url;
// });
// }
// else
// {
// //url = dataFeed[ id_feed ].str_link;
// url = dataFeed[ id_feed ].str_link_bonus;
// document.location.href = url;
// }
// });
// })
// .controller("changeType", function( $scope, $localStorage, $filter, $translate, $route )
// {
// // var filter = $filter('oddsConverter');
// $scope.updateOdd = function( type )
// {
// $localStorage.oddsType = type;
// $localStorage.$save();
// //$scope.$digest();
// // $scope.model = $filter('oddsConverter')($scope.model);
// // $scope.$apply();
// //filter();
// //$route.reload();
// };
// $scope.optionOdd = function( type )
// {
// if( type == $localStorage.oddsType )
// return true;
// };
// $scope.updateLocale = function( type )
// {
// // $scope.$apply =
// $localStorage.language = type;
// $localStorage.locale = type;
// $localStorage.$save();
// $translate.use( $localStorage.language );
// };
// $scope.optionLocale = function( type )
// {
// if( type == $localStorage.language )
// return true;
// };
// $scope.changeTimeOffset = function( offset )
// {
// $localStorage.timeZoneOffset = offset;
// $localStorage.$save();
// };
// $scope.timeZoneOffset = function( offset )
// {
// if( offset == $localStorage.timeZoneOffset )
// return true;
// }
// })
// .controller("bonusController", function( $scope, $http, $location)
// {
// var confBono = {
// method: 'GET',
// url: 'json/dataBono.json',
// params: {'_':new Date().getTime()},
// headers: {
// 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
// }
// };
// $http(confBono).
// success(function(data, status, headers, config)
// {
// for ( var index = 0; index < data.length; index ++)
// {
// if(data[index].id_bono == id_bono)
// {
// $scope.bonus = data[index];
// $scope.id_feed = $scope.bonus.id_feed;
// break;
// document.querySelector('title').innerHTML = $scope.bonus.str_title_web ;
// var description = document.querySelector("meta[name=description]");
// description.setAttribute('content', $scope.bonus.str_description );
// if($scope.bonus.str_keywords)
// {
// var keywords = document.querySelector("meta[name=keywords]");
// keywords.setAttribute('content', "apuestas deportivas, bonos bienvenida, regalos, casas apuestas, promociones, apuestas en directo, ofertas, juego online, " +
// $scope.bonus.str_feed.toLowerCase() + ", " + $scope.bonus.str_keywords);
// }
// }
// }
// }).
// error(function(data, status, headers, config)
// {
// });
// })
// .controller('dataBanner', function( $scope, $http, dataFactory )
// {
// dataFactory.getDataBanner().then( function(response)
// {
// $scope.data = response.data;
// });
// })
// .controller("besgamSearchList", function( $rootScope, $scope, $http, $route, $translate, dataFactory )
// {
// var now = new Date(),
// target = '',
// sportGo = '',
// leagueGo = '';
// $scope.$on( 'LOAD', function(){ $scope.loading = true } );
// $scope.$on( 'UNLOAD', function(){ $scope.loading = false } );
// $scope.$emit('LOAD');
// $scope.rangeOdd = [
// { odd: 1.1 },
// { odd: 1.2 },
// { odd: 1.4 },
// { odd: 1.6 },
// { odd: 1.8 },
// { odd: 2.0 },
// { odd: 2.2 },
// { odd: 2.5 },
// { odd: 3.0 },
// { odd: 3.5 },
// { odd: 4.0 },
// { odd: 4.5 },
// { odd: 5.0 },
// { odd: 6.0 },
// { odd: 7.0 },
// { odd: 8.0 },
// { odd: 9.0 },
// { odd: 10.0 },
// { odd: 15.0 },
// { odd: 20.0 },
// { odd: 100}
// ];
// $scope.item = [{
// name : 'RangeOddLow',
// value : 0
// },
// {
// name : 'rangeOddHigh',
// value : 20
// }];
// dataFactory.getDataJson().then( function(response)
// {
// $translate('controller.search.param1').then(function (translation)
// {
// target = ($route.current.params.target == translation || angular.isUndefined($route.current.params.target)) ? '' : $route.current.params.target;
// $translate('controller.search.param2').then(function (translation)
// {
// sportGo = ($route.current.params.sport == translation || angular.isUndefined($route.current.params.sport)) ? '' : $route.current.params.sport;
// $translate('controller.search.param3').then(function (translation)
// {
// leagueGo = ($route.current.params.league == translation || angular.isUndefined($route.current.params.league)) ? '' : $route.current.params.league;
// /* Instanciamos */
// $scope.search = {"league":leagueGo,"sport":sportGo,"tags":target};
// $scope.data = response.data;
// $scope.aux = $scope.$eval("filtered = (data | filter:search:strict)");
// $scope.selectedInput = {};
// $scope.totalData = ($scope.aux.length-10);
// $scope.currentPage = 1;
// $scope.numPerPage = 10;
// $scope.maxSize = 5;
// $scope.setPage = function (pageNo)
// {
// window.scrollTo(0,0);
// $scope.currentPage = pageNo;
// };
// $scope.setPage($scope.currentPage);
// /* Ordenación */
// var orderObj = ['orderTime','event'];
// $scope.setOrdered = function( obj )
// {
// orderObj = obj;
// };
// $scope.ordered = function()
// {
// return orderObj;
// };
// $scope.chageOrder = function()
// {
// if( $scope.selectedInput.date == '1' )
// $scope.setOrdered(['-orderTime','event']);
// else
// $scope.setOrdered(['orderTime','event']);
// };
// /* Deportes */
// $scope.prematchSports = $scope.aux.reduce(function(sum, place)
// {
// if(sum.indexOf( place.sportID ) < 0) sum.push( place.sportID );
// return sum;
// }, []);
// /* Lista de ligas */
// listPrematchLeagues();
// $scope.$emit('UNLOAD');
// });
// });
// });
// });
// var listPrematchDataFilter = function( data )
// {
// var dataFilter = [];
// if( $scope.selectedInput.league != "" )
// {
// angular.forEach(data, function(value, key)
// {
// if( value.league == $scope.selectedInput.league )
// if( $scope.selectedInput.promo && value.promo ) dataFilter.push(value);
// else if( !$scope.selectedInput.promo ) dataFilter.push(value);
// });
// }
// else if( $scope.selectedInput.sport != "" )
// {
// angular.forEach(data, function(value, key)
// {
// if( value.sportID == $scope.selectedInput.sport )
// if( $scope.selectedInput.promo && value.promo ) dataFilter.push(value);
// else if( !$scope.selectedInput.promo ) dataFilter.push(value);
// });
// }
// else
// {
// angular.forEach(data, function(value, key)
// {
// if( $scope.selectedInput.promo && value.promo ) dataFilter.push(value);
// else if( !$scope.selectedInput.promo ) dataFilter.push(value);
// });
// }
// return changeRange(dataFilter);
// };
// var listPrematchLeagues = function()
// {
// $scope.prematchLeagues = $scope.aux.reduce(function(sum, place)
// {
// if( place.league != null )
// {
// if( $scope.selectedInput.sport && $scope.selectedInput.sport != "" )
// {
// if (sum.indexOf( place.league ) < 0 && $scope.selectedInput.sport == place.sportID )
// {
// if( $scope.selectedInput.promo && place.promo ) sum.push( place.league );
// else if( !$scope.selectedInput.promo ) sum.push( place.league );
// }
// }
// else
// {
// if (sum.indexOf( place.league ) < 0)
// if( $scope.selectedInput.promo && place.promo ) sum.push( place.league );
// else if( !$scope.selectedInput.promo ) sum.push( place.league );
// }
// }
// return sum;
// }, []);
// };
// var changeRange = function( data )
// {
// var dataFilter = [];
// angular.forEach( data, function(value, key)
// {
// var fInsert = false;
// if( value.markets )
// {
// angular.forEach( value.markets.str_bet, function( bet, keyBet)
// {
// if( bet[0].n_odd <= parseFloat($scope.rangeOdd[$scope.item[1].value].odd) && bet[0].n_odd >= parseFloat($scope.rangeOdd[$scope.item[0].value].odd) ) fInsert = true;
// });
// }
// else
// fInsert = true
// if( fInsert ) dataFilter.push( value );
// });
// return dataFilter;
// };
// $scope.changeListPrematch = function()
// {
// /* Lista de ligas */
// listPrematchLeagues();
// $scope.filtered = listPrematchDataFilter($scope.aux );
// };
// $scope.reset = function()
// {
// $scope.selectedInput = {
// sport: "",
// league: "",
// date: "",
// promo: false
// };
// $scope.changeListPrematch();
// };
// })
// .controller("surebet", function( $scope, $http, $location ,$localStorage, $filter, dataFactory )
// {
// $scope.surebets = [];
// $scope.imgLoad = 0;
// $scope.$on( 'LOAD', function(){ $scope.loading = true } );
// $scope.$on( 'UNLOAD', function(){ $scope.loading = false } );
// $scope.$emit('LOAD');
// /* Cargamos los datos de las feed */
// dataFactory.getDataFeed().then( function(response)
// {
// $scope.feed = response.data;
// /* Cargamos los datos de las feed */
// dataFactory.getDataFeed().then( function(response)
// {
// $scope.feed = response.data;
// dataFactory.getDataJson().then( function(response)
// {
// var data = response.data,
// aData = [];
// for( var nCont = 0, len = data.length;
// nCont < len;
// nCont++ )
// {
// if( data[nCont].markets )
// {
// var uno = 0,
// pro = 0,
// cuota = 0;
// for(var index in data[nCont].markets.str_bet)
// {
// uno += 1/data[nCont].markets.str_bet[index][0].n_odd;
// prob = 1/data[nCont].markets.str_bet[index][0].n_odd;
// cuota = data[nCont].markets.str_bet[index][0].n_odd;
// }
// if( uno < 1 )
// {
// var str_bet = {},
// auxBet = {},
// keys = [],
// name = null;
// for(var index in data[nCont].markets.str_bet)
// {
// name = (index == "1") ? "011" : (index == "X") ? "02X" : "032";
// prob = 1/data[nCont].markets.str_bet[index][0].n_odd;
// resProb = (prob*100)/uno;
// data[nCont].markets.str_bet[index][0]["prob"] = $filter("setDecimal")( resProb, 2 );
// str_bet[ name ] = data[nCont].markets.str_bet[index];
// keys.push( name );
// }
// keys.sort();
// for( var nSubContKeys = 0, lenKeys = keys.length;
// nSubContKeys < lenKeys;
// nSubContKeys++ )
// {
// auxBet[ keys[nSubContKeys] ] = str_bet[ keys[nSubContKeys] ];
// }
// var prob = (prob*100)/uno,
// profit = (prob*cuota)-100;
// aData.push({
// "n_id_sport": data[nCont].sportID,
// "str_sport": data[nCont].sport,
// "id_league": data[nCont].leagueID,
// "str_league": data[nCont].league,
// "n_id_event": data[nCont].id,
// "str_name_event": data[nCont].event,
// "str_time_event": data[nCont].orderTime,
// "profit": $filter("setDecimal")(profit, 2),
// "str_market_name": data[nCont].markets.str_market,
// "str_market_short": data[nCont].markets.str_market_short,
// "n_result_market": data[nCont].markets.str_bet.length,
// "a_markets": {
// "id_market": data[nCont].markets.id_market,
// "str_market": data[nCont].markets.str_market,
// "str_market_short": data[nCont].markets.str_market_short,
// "str_description": data[nCont].markets.str_description,
// "id_market_group": data[nCont].markets.id_market_group,
// "n_order": data[nCont].markets.n_order,
// "char_order": data[nCont].markets.char_order,
// "str_bet": auxBet
// }
// });
// }
// }
// }
// $scope.imgLoad = (aData.length == 0) ? 1 : 0;
// $scope.surebets = aData;
// $scope.totalData = (aData.length-5);
// $scope.currentPage = 1;
// $scope.numPerPage = 6;
// $scope.maxSize = 5;
// $scope.setPage = function (pageNo)
// {
// window.scrollTo(0,0);
// //console.log('setpage:' + pageNo);
// $scope.currentPage = pageNo;
// };
// $scope.setPage($scope.currentPage);
// $scope.$emit('UNLOAD');
// });
// });
// });
// /* Quita caracteres de una cadena */
// $scope.cutChar = function( str, nChar )
// {
// return str.substr( nChar );
// }
// $scope.getIdName = function( id_event, id_market, str_bet )
// {
// return id_event+"|"+id_market+"|"+str_bet;
// };
// })
// .controller("promotions", function( $scope, $http, $route, $translate, dataFactory )
// {
// var id_event = $route.current.params.record;
// $scope.data = [];
// $translate('controller.text-result').then(function (translation) // "Cargando datos...";
// {
// $scope.textInfo = translation;
// });
// /* Datos de las promociones */
// var confPromo = {
// method: 'GET',
// url: 'json/dataPromo.json',
// params: {'_':new Date().getTime()},
// headers: {
// 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
// }
// };
// /* Cargamos los datos de las feed */
// dataFactory.getDataFeed().then( function(response)
// {
// $scope.feed = response.data;
// $http(confPromo).
// success(function(data, status, headers, config)
// {
// /* Los datos son diferentes si se llega desde el menu o desde el buscador/ficha */
// /* Se llega desde el buscador o desde la ficha */
// if(typeof(id_event) != "undefined")
// {
// var data_event = new Array();
// angular.forEach(data, function(value, key) {
// if(value.id_event==id_event)
// {
// value.is_important = 1;
// data_event.push(value);
// }
// });
// $scope.data = data_event;
// }
// else
// $scope.data = data;
// Expirar las promociones desde el cliente
// var today = new Date();
// angular.forEach($scope.data, function(value, key) {
// if(new Date(value.date_end) < today)
// {
// value.is_expired = 1;
// }
// });
// $scope.currentPage = 1;
// $scope.numPerPage = 10;
// $scope.maxSize = 5;
// $scope.setPage = function (pageNo)
// {
// window.scrollTo(0,0);
// //console.log('setpage:' + pageNo);
// $scope.currentPage = pageNo;
// };
// $scope.setPage($scope.currentPage);
// $translate('promotions.noPromo').then(function (translation) //"Actualmente no tenemos promociones disponibles";
// {
// $scope.textInfo = translation;
// });
// }).
// error(function(data, status, headers, config)
// {
// });
// });
// $scope.changeClassGround = function(is_important,is_registered, is_expired)
// {
// if(is_important==1)
// return 'promo-dest';
// else
// if(is_registered=='1' && is_expired==0)
// return 'user-promo-favorite';
// else
// return 'promo';
// }
// $scope.changeClassPromo = function(is_important)
// {
// if(is_important==1)
// return 'imagen-casa';
// else if(is_important==0)
// return 'imagen-casa-promo';
// }
// })
// .controller("bonosController", function( $scope, $http, $location, dataFactory )
// {
// $scope.data = [];
// /* Datos de los bonos */
// var confBono = {
// method: 'GET',
// url: 'json/dataBono.json',
// params: {'_':new Date().getTime()},
// headers: {
// 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
// }
// };
// /* Se hace la llamada para obtener la info */
// dataFactory.getDataFeed().then( function(response)
// {
// $scope.feed = response.data;
// $http(confBono).
// success(function(data, status, headers, config)
// {
// $scope.besgamSize = 10;
// $scope.data = data;
// $scope.currentPage = 1;
// /*if($scope.besgamSize >= $scope.data.length)
// $scope.numPerPage = $scope.data.length - 1;
// else*/
// $scope.numPerPage = $scope.besgamSize;
// $scope.maxSize = 5;
// $scope.setPage = function (pageNo)
// {
// window.scrollTo(0,0);
// //console.log('setpage:' + pageNo);
// $scope.currentPage = pageNo;
// };
// $scope.setPage($scope.currentPage);
// }).
// error(function(data, status, headers, config)
// {
// });
// });
// })
// .controller("bonusControllerFeed", function( $scope, $http, $sce, $sessionStorage, $route, dataFactory)
// {
// $scope.bonus = {};
// dataFactory.getDataBonos().then(function(response)
// {
// for ( var index = 0; index < response.data.length; index ++)
// {
// if(response.data[index].id_bono == $route.current.params.record )
// {
// return $scope.bonus = response.data[index];
// }
// }
// });
// })
// .controller('ratingCtrl', function( $scope, $http, $sce, $sessionStorage, $location, $translate )
// {
// var params = $location.search();
// var id_feed = params['feed'];
// /* Ponemos el ratin a solo letura y comprobamos el usuario */
// $scope.isReadonly = true;
// $scope.tooltipText = $sce.trustAsHtml('Inicia sesión<br>para poder votar');
// /* Recogemos los varlos de inicio */
// var loadDataFeed = {
// method: 'POST',
// url: 'php/loadDataRating.php',
// headers: {
// 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
// },
// data: 'id_feed=' + id_feed
// };
// $http(loadDataFeed).
// success(function(data, status, headers, config)
// {
// $scope.rate = data.rate;
// });
// $scope.max = 5;
// $scope.id_feed = id_feed;
// /* Si es un usuario registrado, le permitimos votar */
// if( $sessionStorage.sessionid )
// {
// $scope.isReadonly = false;
// $translate('bonus.score').then(function (translation) // 'Haz click para puntuar'
// {
// $scope.tooltipText = $sce.trustAsHtml( translation );
// });
// }
// $scope.ratingClick = function( value )
// {
// /* Si es un usuario registrado, le permitimos votar */
// if( $sessionStorage.sessionid )
// {
// var setDataFeed = {
// method: 'POST',
// url: 'php/setDataRating.php',
// headers: {
// 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
// },
// data: 'n_rate=' + value + '&id_feed=' + $scope.id_feed
// };
// $http(setDataFeed).
// success(function(data, status, headers, config)
// {
// $scope.rate = data.rate;
// });
// $translate('bonus.vote').then(function (translation) //'Voto emitido<br>Sólo puedes votar una vez cada casa.');
// {
// $scope.tooltipText = $sce.trustAsHtml( translation );
// });
// }
// };
// $scope.hoveringOver = function(value)
// {
// $scope.overStar = value;
// $scope.percent = 100 * (value / $scope.max);
// };
// $scope.ratingStates = [
// {stateOn: 'glyphicon-ok-sign', stateOff: 'glyphicon-ok-circle'},
// {stateOn: 'glyphicon-star', stateOff: 'glyphicon-star-empty'},
// {stateOn: 'glyphicon-heart', stateOff: 'glyphicon-ban-circle'},
// {stateOn: 'glyphicon-heart'},
// {stateOff: 'glyphicon-off'}
// ];
// })
// .controller("metaController", function( $scope, DataOne )
// {
// $scope.bonus = {};
// // DataOne.one_bonus().then(function(response)
// // {
// // $scope.bonus = response;
// // /* Añadimos el title, la descripcion y los keywords */
// // document.querySelector('title').innerHTML = $scope.bonus.str_title_web ;
// // var description = document.querySelector("meta[name=description]");
// // description.setAttribute('content', $scope.bonus.str_description );
// // if($scope.bonus.str_keywords)
// // {
// // var keywords = document.querySelector("meta[name=keywords]");
// // keywords.setAttribute('content', "apuestas deportivas, bonos bienvenida, regalos, casas apuestas, promociones, apuestas en directo, ofertas, juego online, " +
// // $scope.bonus.str_feed.toLowerCase() + ", " + $scope.bonus.str_keywords);
// // }
// // });
// })
// .controller("marketCard", function( $scope, $http, $location, $rootScope, $sessionStorage, dataFactory )
// {
// $scope.$storage = $sessionStorage;
// $scope.$on( 'LOAD', function(){ $scope.loading = true } );
// $scope.$on( 'UNLOAD', function(){ $scope.loading = false } );
// $scope.$emit('LOAD');
// //$localStorage.$reset();
// var expreg = new RegExp("^/apuestas/([^/]*)/([^/]*)/([^/]*)/([^/]*)/$"),
// excrt = new RegExp("com/(.*?)/#!"),
// getCtr = excrt.exec($location.$$absUrl),
// country = getCtr == null ? 'com' : getCtr[1],
// param = expreg.exec($location.url()),
// id = param[3],
// sportID = param[4],
// confEvent = {
// method: 'GET',
// url: 'json/events/'+id+'.json',
// params: {'_':new Date().getTime()},
// headers: {
// 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
// }
// },
// confUser = {
// method: 'POST',
// url: 'php/getFavorites.php',
// headers: {
// 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
// },
// data :'iduser ='+ $scope.$storage.iduser
// },
// confGetEvent = {
// method: 'POST',
// url: 'php/getEvent.php',
// headers: {
// 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
// },
// data: 'id=' + id + '&sportID=' + sportID + "&country=" + country + "&markets[]"
// };
// /* Variables globales */
// $scope.id = id;
// $scope.sportID = sportID;
// $rootScope = new Array();
// $scope.selected = 0;
// $scope.is_favorite = 0; // si es el filtro de favoritos
// $scope.exist_favorite = 0; // si existen cuotas en los mercados favoritos
// $scope.draw_filter = new Array(); // filtros con cuotas
// $scope.is_promo = 0; // saber si el evento tiene o no promos
// /* Comprobar si el evento esta caducado */
// dataFactory.getDataJson().then( function( response )
// {
// var dataPortrait = response.data;
// var date_event_update = null;
// var exist_event = false;
// for(var i=0;i< dataPortrait.length; i++)
// {
// if(dataPortrait[i]['id'] == $scope.id)
// {
// date_event_update = dataPortrait[i]['update'];
// exist_event = true;
// $scope.is_promo = dataPortrait[i]['promo'];
// break;
// }
// }
// if(!exist_event)
// /* Evento caducado */
// document.location.href = "./#!/expired-event";
// //$location.path("expired-event");
// /* Carga de datos de feeds */
// dataFactory.getDataFeed().then( function(response)
// {
// $scope.feed = response.data;
// /* Carga de datos de filtros */
// dataFactory.getDataMarkets().then( function(response)
// {
// $scope.filter = response.data.filters[$scope.sportID].filters;
// $scope.filter.selected = 0;
// /* Carga evento */
// $http(confEvent).
// success(function(dataOneEvent, statusEvent, headers, config)
// {
// /* status 200 o 302 */
// var date_event_file = headers()['last-modified'],
// dateJS = new Date(date_event_file),
// yearJS = dateJS.getUTCFullYear(),
// monthJS = dateJS.getUTCMonth(),
// dayJS = dateJS.getUTCDate(),
// hourJS = dateJS.getUTCHours(),
// minuteJS = dateJS.getUTCMinutes(),
// secondJS = dateJS.getUTCSeconds();
// /* Fecha UTC del json de la ficha */
// var date_event_file = new Date( yearJS, monthJS,dayJS, hourJS, minuteJS, secondJS );
// if(exist_event) date_event_update = new Date (date_event_update);
// if(!exist_event || date_event_file < date_event_update)
// {
// /* Generar evento */
// $http(confGetEvent).
// success(function(dataTwoEvent, status, headers, config)
// {
// $scope.getFavorites(dataTwoEvent);
// }).
// error(function(data, status, headers, config)
// {
// });
// }
// else
// $scope.getFavorites(dataOneEvent);
// $scope.$emit('UNLOAD');
// }).
// error(function(data, status, headers, config)
// {
// /* NO EXISTE JSON */
// /* Generar evento */
// $http(confGetEvent).
// success(function(dataTwoEvent, status, headers, config)
// {
// $scope.getFavorites(dataTwoEvent);
// $scope.$emit('UNLOAD');
// }).
// error(function(data, status, headers, config)
// {
// $scope.$emit('UNLOAD');
// });
// });
// });
// });
// });
// $scope.getFavorites = function(dataEvent)
// {
// /* Buscar los favoritos del usuario */
// /* Primero se buscan en el localStorage. Si no estan, entonces se va al servidor */
// if($sessionStorage == null)
// {
// $http(confUser).
// success(function(dataUser, status, headers, config)
// {
// /* Se guardan los datos de los favoritos y del usuario en el localStorage */
// $sessionStorage.favorites = dataUser.list;
// $sessionStorage.$save();
// /* Se gestionan los favoritos de la ficha */
// $scope.assignFavorites(dataEvent, dataUser.list);
// }).
// error(function(data, status, headers, config)
// {
// });
// }
// else
// {
// $scope.assignFavorites(dataEvent, $sessionStorage.favorites);
// }
// };
// $scope.assignFavorites = function (dataEvent, dataFavorites)
// {
// /* Se guardan los datos del evento y del usuario para la ficha */
// $scope.data = dataEvent;
// $scope.data.favorites = dataFavorites;
// /* Mercados favoritos global para acceder desde cualquier scope */
// $scope.fav_filter_show = dataFavorites;
// /* Index del mercado 'favoritos' */
// $scope.index_favorite = $scope.filter.length -1;
// /* Si hay favoritos, se activa su filtro */
// if($scope.data.favorites!= "" && $scope.data.favorites!= null)
// {
// $scope.filter.selected = $scope.index_favorite;
// $scope.filter_show = $scope.data.favorites;
// $scope.selected = $scope.index_favorite;
// $scope.is_favorite = 1;
// $scope.exist_favorite = 0;
// /* Comprobar si hay cuotas de los mercados favoritos */
// angular.forEach($scope.data.markets, function(value, key)
// {
// if($scope.data.favorites.indexOf(value.id_market) > -1)
// $scope.exist_favorite = 1;
// });
// }
// else
// {
// /* Mercados del primer filtro */
// $scope.filter_show = $scope.filter[0].list;
// $scope.is_favorite = 0;
// $scope.selected = 0;
// }
// /* Se recorren los datos de los mercados para pintar o no los filtros */
// angular.forEach($scope.filter, function(valueF, keyF)
// {
// angular.forEach($scope.data.markets, function(valueM, keyM)
// {
// if(valueF.list.indexOf(valueM.id_market) > -1)
// $scope.draw_filter.push(keyF);
// });
// });
// };
// /* Filtros de mercados */
// $scope.showFilter = function (nIndex)
// {
// if(nIndex < $scope.index_favorite)
// {
// /* Filtro de un mercado cualquiera */
// $scope.filter_show = $scope.filter[nIndex].list;
// $scope.is_favorite = 0;
// /* comprobar que hay datos de los mercados del filtro */
// $scope.exist_favorite = 0;
// angular.forEach($scope.data.markets, function(value, key)
// {
// if($scope.filter_show.indexOf(value.id_market) > -1)
// $scope.exist_favorite = 1;
// });
// }
// else
// {
// /* Es el filtro de los mercados favoritos */
// $scope.filter_show = $scope.fav_filter_show;
// $scope.is_favorite = 1;
// /* comprobar que hay datos de los mercados del filtro */
// $scope.exist_favorite = 0;
// if($scope.filter_show!= null)
// {
// angular.forEach($scope.data.markets, function(value, key)
// {
// if($scope.filter_show.indexOf(value.id_market) > -1)
// $scope.exist_favorite = 1;
// });
// }
// else
// $scope.exist_favorite = 1;
// }
// };
// // /* Indicar si el filtro esta seleccionado */
// // $scope.isSelected = function(nSelection)
// // {
// // return $scope.selected === nSelection;
// // };
// // /* Selecciona el filtro */
// // $scope.setSelection = function(nSelection)
// // {
// // $scope.selected = nSelection;
// // };
// /* Añadir/eliminar favorito */
// $scope.checkFavorite = function( nMarket , nType)
// {
// /* Convertir el valor booleano a uno numerico */
// var option= (nType) ? 1 : 0;
// /* Eliminar/añadir el mercado favorito */
// var confMarketFavorite = {
// method: 'POST',
// url: 'php/getFavorites.php',
// headers: {
// 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
// },
// data: 'id_market='+nMarket+'&option='+option + '&iduser='+$scope.$storage.iduser
// };
// $http(confMarketFavorite).
// success(function(data, status, headers, config)
// {
// /* Se actualiza la lista de favoritos */
// $scope.fav_filter_show = data.list;
// /* Se guarda en el localStorage */
// $sessionStorage.favorites = data.list;
// $sessionStorage.$save();
// $scope.$storage.favorites = data.list;
// /* comprobar que hay datos de los mercados del filtro */
// $scope.exist_favorite = 0;
// if($scope.fav_filter_show != null){
// // Hay mercados favoritos
// angular.forEach($scope.data.markets, function(value, key) {
// if($scope.fav_filter_show.indexOf(value.id_market) > -1)
// $scope.exist_favorite = 1;
// });
// }
// else
// $scope.exist_favorite = 1;
// }).
// error(function(data, status, headers, config)
// {
// // called asynchronously if an error occurs
// // or server returns response with an error status.
// });
// };
// $scope.getFavoriteContent = function()
// {
// $scope.favText =! $scope.favText;
// };
// $scope.trimChar = function( str, len )
// {
// var subStr;
// if( screen.width < 400 )
// {
// var subStr = str.substr( 0, len );
// if( str.length > len )
// subStr += "...";
// }
// else
// subStr = str;
// return subStr;
// };
// /* Quita caracteres de una cadena */
// $scope.cutChar = function( str, nChar )
// {
// var temp = str.substr( nChar );
// if( temp.indexOf('|') == -1 )
// return temp;
// else
// {
// var strName = temp.split('|');
// return strName[1];
// }
// };
// $scope.cutIdName = function( str )
// {
// var temp = str.split('|');
// return temp[0].substr(2);
// };
// /* Añade caracteres a una cadena */
// $scope.addChar = function( str, strAdd )
// {
// if( str )
// {
// var str = str.split(".");
// return str[0]+"_on."+str[1];
// }
// };
// $scope.displayRow = function ( position )
// {
// /* Visualizar las filas de 3 columnas en el ganador de la competicion */
// if(position%3==0)
// return true;
// else
// return false;
// };
// // $scope.displayCell = function ( positionRow, index )
// // {
// // /* Visulaizar las columnas de las filas de 3 en el ganador de la competicion */
// // if(index >= positionRow && index <= ( positionRow + 2 ) )
// // return true;
// // else
// // return false;
// // };
// // $scope.emptyCells = function ( position )
// // {
// // if( !$scope.data) return;
// // /* Calcula el numero de celdas vacias para completar una fila */
// // var length_data = Object.keys($scope.data.markets[position].str_bet).length;
// // return ( 3 - length_data % 3 ) ;
// // };
// // $scope.numberRow = function ( position )
// // {
// // /* Calcula el index de la fila donde añadir las celdas vacias*/
// // var length_data = Object.keys($scope.data.markets[position].str_bet).length;
// // return ( Math.floor(length_data / 3 ) * 3);
// // };
// // $scope.getInfo = function ( index )
// // {
// // /* Retorna el texto de info del mercado por su identificador */
// // return $scope.infoMarket[index];
// // };
// })
// .controller("load", function( $scope, $http)
// {
// $scope.showMessageLoading=true;
// $scope.isLoading = function ()
// {
// return $http.pendingRequests.length > 0;
// };
// $scope.$watch($scope.isLoading, function (v)
// {
// $scope.showMessageLoading=v;
// })
// })
// .controller('newsletter', function( $scope, $http, $route, $log, vcRecaptchaService )
// {
// $scope.email = $route.current.params.email;
// $scope.response = null;
// $scope.widgetId = null;
// $scope.model = {
// key: '6LfuiAgTAAAAABTVAVcs1h1SEtBNTnhAT1gHi3uv'
// };
// $scope.setResponse = function (response) {
// console.info('Response available');
// $scope.response = response;
// };
// $scope.setWidgetId = function (widgetId) {
// console.info('Created widget ID: %s', widgetId);
// $scope.widgetId = widgetId;
// };
// $scope.submit = function(form)
// {
// /* Inicializamos valores del formulario */
// form.captcha.$setValidity('recaptcha', true);
// form.email.$setValidity('recurrent', true);
// form.email.$setValidity('unexpected', true);
// form.email.$setValidity('sessionko', true);
// /* Controlamos el CaptCha */
// if( !$scope.response || form.$error.recaptcha )
// form.captcha.$setValidity('recaptcha', false);
// /* Comprobamos errores */
// $scope.$broadcast('validate-form', form.$name );
// /* Controlamos la validación del formulario */
// if (form.$invalid)
// return;
// /* Configuración del envío */
// var params = {
// method: 'POST',
// url: 'php/newsletter.php',
// headers: {
// 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
// },
// data: 'email='+this.email+'&resp='+$scope.response
// }
// /* Llamada al modelo */
// $http( params )
// .success(function(data, status, headers, params)
// {
// /* Si nos devuelve un error */
// if( data.error || !angular.isDefined( data.error ) )
// {
// Dependiendo de la respuesta damos el error
// switch(data.type)
// {
// case 'ALREADY-EXISTS': // El email ya ha sido registrado
// form.email.$setValidity('recurrent', false);
// break;
// case 'CAPTCHA-KO': // La respuesta del Captcha no es correcta.
// form.captcha.$setValidity('recaptcha', false);
// break;
// case 'SESSION-KO': // Solo se permite 1 inscripción por sesión
// form.email.$setValidity('sessionko', false);
// break;
// default: // Error por defecto
// form.email.$setValidity('unexpected', false);
// }
// /* Reiniciamos el captCha */
// $scope.response = null;
// vcRecaptchaService.reload(0);
// /* Creamos los mensajes de error */
// $scope.$broadcast('validate-form', form.$name );
// }
// else
// $scope.respOK = true;
// /* Recogamos el error, si el estatus no es OK */
// if (status != 200)
// $log.error(data);
// })
// .error(function(data, status, headers, config)
// {
// $log.error(data);
// });
// };
// $scope.back = function()
// {
// $scope.send = 0;
// };
// /* Envio de parametros en un formulario */
// var param = function(data)
// {
// var returnString = '';
// for (d in data)
// {
// if (data.hasOwnProperty(d))
// returnString += d + '=' + data[d] + '&';
// }
// // Remove last ampersand and return
// return returnString.slice( 0, returnString.length - 1 );
// };
// })
/********************************** PANEL DE USUARIO **********************************************/
// .controller('loginController', function( $scope, $localStorage, $location, $http, $sessionStorage, vcRecaptchaService, $translate, $route)
// {
// /* Controlar el pais */
// /* La forma de saber el pais es con el primer parametro de la url */
// var absUrl = $location.absUrl().replace("http://",'').split('/');
// $scope.country = absUrl[1];
// /* Links de facebook y twitter */
// $scope.linkFacebook = function()
// {
// document.location.href="php/connectFacebook.php?locale=" + $scope.country;
// }
// $scope.linkTwitter= function()
// {
// document.location.href="php/connectTwitter.php?locale=" + $scope.country;
// }
// /* Controlar los errores de login con facebook o twitter */
// if(angular.isDefined($route.current.params.exit))
// {
// switch($route.current.params.exit)
// {
// case "1":
// $translate('register.errorLoginExternal.bbdd').then(function (translation)
// {
// $scope.errorExternal = translation;
// });
// break;
// case "2":
// $translate('register.errorLoginExternal.facebookConnect').then(function (translation)
// {
// $scope.errorExternal = translation;
// });
// break;
// case "3":
// $translate('register.errorLoginExternal.facebookData').then(function (translation)
// {
// $scope.errorExternal = translation;
// });
// break;
// case "4":
// $translate('register.errorLoginExternal.userPass').then(function (translation)
// {
// $scope.errorExternal = translation;
// });
// break;
// case "6":
// $translate('register.errorLoginExternal.twitterConnect').then(function (translation)
// {
// $scope.errorExternal = translation;
// });
// break;
// case "7":
// $translate('register.errorLoginExternal.twitterData').then(function (translation)
// {
// $scope.errorExternal = translation;
// });
// break;
// default:
// $scope.errorExternal = "";
// }
// $scope.errorLoginExternal = true;
// }
// $scope.response = null;
// $scope.widgetId = null;
// $sessionStorage.$reset();
// $scope.model = {
// key: '6LfuiAgTAAAAABTVAVcs1h1SEtBNTnhAT1gHi3uv'
// };
// $scope.setResponse = function (response) {
// //console.info('Response available');
// $scope.response = response;
// };
// $scope.setWidgetId = function (widgetId) {
// //console.info('Created widget ID: %s', widgetId);
// $scope.widgetId = widgetId;
// };
// $scope.submit = function(form)
// {
// switch (form.$name)
// {
// case "loginForm":
// /* Inicializamos valores del formulario */
// form.passLogin.$setValidity('sqlEmpty', true);
// form.passLogin.$setValidity('unexpected', true);
// var method = "POST",
// url = "php/login.php",
// data = "user="+this.userLogin+"&pass="+this.passLogin + "&locale=" + $scope.country;
// break;
// case "recoverForm":
// /* Inicializamos valores del formulario */
// form.hRecover.$setValidity('recaptcha', true);
// form.userRecover.$setValidity('sqlEmpty', true);
// form.userRecover.$setValidity('unexpected', true);
// $scope.send = false;
// var method = "POST",
// url = "php/recover.php",
// data = "user="+this.userRecover+"&resp="+$scope.response;
// /* Controlamos el CaptCha */
// if( !$scope.response || form.$error.recaptcha )
// form.hRecover.$setValidity('recaptcha', false);
// break;
// case "createForm":
// /* Inicializamos valores del formulario */
// form.hCreate.$setValidity('recaptcha', true);
// form.createRePass.$setValidity('equal', true);
// form.createUser.$setValidity('recurrent', true);
// form.createUser.$setValidity('unexpected', true);
// var method = "POST",
// url = "php/register.php",
// data = "user="+this.createUser+"&pass="+this.createPass+"&newsletter="+this.newsletter+
// "&robinson="+this.robinson+"&resp="+$scope.response +"&locale=" + $scope.country;
// /* Controlamos el CaptCha */
// if( !$scope.response || form.$error.recaptcha )
// form.hCreate.$setValidity('recaptcha', false);
// /* Controlamos que las contraseñas coincidan */
// if( this.createPass != this.createRePass )
// form.createRePass.$setValidity('equal', false);
// break;
// }
// /* Comprobamos errores */
// $scope.$broadcast('validate-form', form.$name );
// /* Control de formulario */
// if( form.$invalid )
// return false;
// /* Instanciamos datos de la llamada */
// var params = {
// method: method,
// url: url,
// data: data
// };
// /* Llamada al modelo */
// $http( params )
// .success(function(data, status, headers, params)
// {
// switch( form.$name )
// {
// case "loginForm":
// /* Si nos devuelve un error */
// if( data.error || !angular.isDefined( data.error ) )
// {
// Dependiendo de la respuesta damos el error
// switch(data.type)
// {
// case 'EMPTY_ERROR': // El usuario o la clave no son correctos.
// form.passLogin.$setValidity('sqlEmpty', false);
// break;
// default: // Error por defecto
// form.passLogin.$setValidity('unexpected', false);
// }
// }
// /* Si todo ha ido bien */
// else
// {
// $translate('dashboard.header.count').then(function (translation)
// {
// /* Borramos el local storage */
// $sessionStorage.$reset();
// /* Aplicamos el localStorage de favoritos , deportes, y demas datos del iduser */
// $sessionStorage.favorites = data.markets;
// $sessionStorage.iduser = data.iduser;
// $sessionStorage.str_name = data.str_name;
// $sessionStorage.str_email = data.str_email;
// $sessionStorage.a_sports = data.a_sports;
// $sessionStorage.other_sport = data.other_sport;
// $sessionStorage.nameuser = !(data.str_name) ? translation : data.str_name.substr(0,6) + "...";
// $sessionStorage.sessionid = data.iduser;
// /* Controlar el tiempo de sesion */
// var time_in = new Date();
// $sessionStorage.expired = time_in.getTime();
// /* Guardamos los valores */
// $sessionStorage.$save();
// /* Redirigimos a la home */
// $location.path('userHome').replace();
// });
// }
// break;
// case "recoverForm":
// /* Si nos devuelve un error */
// if( data.error || !angular.isDefined( data.error ) )
// {
// /* Dependiendo de la respuesta damos el error */
// switch(data.type)
// {
// case 'EMPTY_ERROR': // El usuario o la clave no son correctos.
// form.userRecover.$setValidity('sqlEmpty', false);
// break;
// case 'CAPTCHA_KO': // La respuesta del Captcha no es correcta.
// form.hRecover.$setValidity('recaptcha', false);
// break;
// default: // Error por defecto
// form.userRecover.$setValidity('unexpected', false);
// }
// }
// /* Si todo ha ido bien */
// else
// {
// $scope.send = true;
// }
// /* Reiniciamos el captCha */
// $scope.response = null;
// vcRecaptchaService.reload(0);
// break;
// case "createForm":
// /* Si nos devuelve un error */
// if( data.error || !angular.isDefined( data.error ) )
// {
// /* Dependiendo de la respuesta damos el error */
// switch(data.type)
// {
// case 'EMAIL_RECURRENT': // La dirección de correo ya existe.
// form.createUser.$setValidity('recurrent', false);
// break;
// case 'CAPTCHA_KO': // La respuesta del Captcha no es correcta.
// form.hCreate.$setValidity('recaptcha', false);
// break;
// default: // Error por defecto
// form.createUser.$setValidity('unexpected', false);
// }
// /* Reiniciamos el captCha */
// $scope.response = null;
// vcRecaptchaService.reload(1);
// }
// /* Si todo ha ido bien */
// else
// {
// $translate('dashboard.header.count').then(function (translation) // "Evento no disponible en "+feed;
// {
// /* Borramos el local storage */
// $sessionStorage.$reset();
// /* Aplicamos el localStorage de favoritos y iduser y demas datos*/
// $sessionStorage.favorites = data.markets;
// $sessionStorage.iduser = data.iduser;
// $sessionStorage.nameuser = translation;
// $sessionStorage.sessionid = data.iduser;
// $sessionStorage.str_email = data.str_email;
// $sessionStorage.str_name = "";
// /* Controlar el tiempo de sesion */
// var time_in = new Date();
// $sessionStorage.expired = time_in.getTime();
// /* Guardamos los valores */
// $sessionStorage.$save();
// /* Redirigimos a la home */
// $location.path('showElection').replace();
// });
// }
// break;
// }
// $scope.$broadcast('validate-form', form.$name );
// })
// .error(function(data, status, headers, config)
// {
// //$scope.dataReg = data;
// });
// };
// })
// .controller('recoveryController', function( $scope, $http, $route )
// {
// /* Inicializamos variables */
// $scope.showLogin = false;
// /* Recuperamos los parametros */
// var token = $route.current.params.token;
// $scope.submit = function(form)
// {
// /* Inicializamos el formulario */
// form.rePass.$setValidity('equal', true);
// form.pass.$setValidity('unexpected', true);
// form.pass.$setValidity('tokenOut', true);
// var method = "POST",
// url = "php/recovery.php",
// data = "pass="+this.pass+"&token="+token;
// /* Controlamos que las contraseñas coincidan */
// if( this.pass != this.rePass )
// form.rePass.$setValidity('equal', false);
// /* Comprobamos errores */
// $scope.$broadcast('validate-form', form.$name );
// /* Control de formulario */
// if( form.$invalid )
// return false;
// /* Instanciamos datos de la llamada */
// var params = {
// method: method,
// url: url,
// data: data
// };
// Llamada al modelo
// $http( params )
// .success( function(data, status, headers, params )
// {
// /* Si nos devuelve un error */
// if( data.error || !angular.isDefined( data.error ) )
// {
// /* Dependiendo de la respuesta damos el error */
// switch(data.type)
// {
// case 'TOKEN_ERROR': // El token no es correcto o ha caducado.
// form.pass.$setValidity('tokenOut', false);
// break;
// default: // Error por defecto
// form.pass.$setValidity('unexpected', false);
// }
// /* Comprobamos errores */
// $scope.$broadcast('validate-form', form.$name );
// }
// /* Si todo ha ido bien */
// else
// {
// /* Enseñamos el texto de correcto */
// $scope.showLogin = true;
// }
// });
// };
// $scope.iniLogin = function()
// {
// /* Redirigimos al login */
// document.location.href = "./#!register";
// };
// })
// .controller('electionUser', function($scope, $location, $http, $sessionStorage, $filter, timeOut, dataFactory)
// {
// /* Controlar que se esta en sesion */
// var session = timeOut.timeOut();
// $scope.user_sports = [];
// $scope.user_feeds = [];
// $scope.dataSettings = {};
// var confSport = {
// method: 'POST',
// url: 'php/dashboard/getDataUserSettings.php',
// data: 'iduser='+ $sessionStorage.iduser ,
// headers: {
// 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
// }
// };
// $http(confSport).
// success(function(data, status, headers, config)
// {
// $scope.dataSettings.sport = data.sport;
// }).
// error(function(data, status, headers, config)
// {
// });
// dataFactory.getDataFeed().then( function( listFeed )
// {
// $scope.dataSettings.feed = listFeed.data;
// });
// /* Modificar el src de la img de los deportes */
// $scope.selectUrl = function (item,sport)
// {
// if($scope.user_sports.indexOf(item) !== -1 )
// return '/img/besgam-icons/sport-icons/sport-icons-register/icon-'+$filter('replaceName')(sport)+'-on.svg';
// else
// return '/img/besgam-icons/sport-icons/sport-icons-register/icon-'+$filter('replaceName')(sport)+'-off.svg';
// };
// /* Actualizar el array de deportes */
// $scope.updateValue = function (structure,valueAdd,strData)
// {
// var index = structure.indexOf(valueAdd);
// if( index === -1 )
// {
// structure.push(valueAdd);
// if( strData != "" )
// return '/img/besgam-icons/sport-icons/sport-icons-register/icon-'+$filter('replaceName')(strData)+'-on.svg';
// else
// return 1;
// }
// else if( index !== -1 )
// {
// structure.splice(index, 1);
// if(strData!="")
// return '/img/besgam-icons/sport-icons/sport-icons-register/icon-'+$filter('replaceName')(strData)+'-off.svg';
// else
// return 1;
// }
// };
// $scope.submit = function(form)
// {
// /* Recoger los datos de los otros deportes */
// var str_others = "";
// angular.forEach(this.others, function(value, key) {
// if(str_others=="")
// str_others = str_others + value.text ;
// else
// str_others = str_others + "," +value.text;
// });
// var params = {
// method: "POST",
// url: "php/election.php",
// data: "&user_sports=" + $scope.user_sports + "&user_feeds=" + $scope.user_feeds
// + "&others="+ str_others +"&iduser="+ $sessionStorage.iduser
// };
// $http( params )
// .success(function(data, status, headers, params)
// {
// if(data.error)
// {
// /* Error al registrar las casas y deportes */
// }
// else
// {
// /* Guardar la info del usuario en la sesion */
// $sessionStorage.str_name = data.dataUser.str_name;
// $sessionStorage.str_email = data.dataUser.str_email;
// $sessionStorage.a_sports = data.dataUser.a_sports;
// $sessionStorage.$save();
// $location.path('userHome').replace();
// }
// }).
// error(function(data, status, headers, config)
// {
// });
// };
// })
/************************************************* PANEL DE USUARIO ***********************************/
// .controller('userHome', function( $scope, $http, $location, dataFactory, $sessionStorage, $route, timeOut, $translate)
// {
// $scope.dataWordpress = [];
// $scope.user_sports = "";
// /* Se viene de facebook o de twitter */
// if(angular.isDefined($route.current.params.iduser))
// {
// /* Obtener los datos del usuario */
// var confUser = {
// method: 'POST',
// url: 'php/dashboard/getDataUser.php',
// data: 'iduser=' + $route.current.params.iduser,
// headers: {
// 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
// }
// }
// $http(confUser).
// success(function(data, status, headers, config)
// {
// $translate('dashboard.header.count').then(function (translation) // "Evento no disponible en "+feed;
// {
// /* Borramos el local storage */
// $sessionStorage.$reset();
// /* Aplicamos el localStorage de favoritos , deportes, y demas datos del iduser */
// $sessionStorage.favorites = data.a_markets;
// $sessionStorage.iduser = data.iduser;
// $sessionStorage.str_name = data.str_name;
// $sessionStorage.str_email = data.str_email;
// $sessionStorage.a_sports = data.a_sport;
// $sessionStorage.other_sport = data.str_other_sport;
// $sessionStorage.nameuser = !(data.str_name) ? translation : data.str_name.substr(0,6) + "...";
// $sessionStorage.sessionid = data.iduser;
// $sessionStorage.login_external = 1;
// /* Controlar el tiempo de sesion */
// var time_in = new Date();
// $sessionStorage.expired = time_in.getTime();
// /* Guardamos los valores */
// $sessionStorage.$save();
// $scope.$storage = $sessionStorage;
// /* Datos del usuario y de sus deportes */
// $scope.user_sports = (!$scope.$storage.a_sports) ? [] : $scope.$storage.a_sports.replace('[','').replace(']','').split(',');
// });
// })
// .
// error(function(data, status, headers, config)
// {
// });
// }
// else
// {
// /* Controlar que se esta en sesion */
// var session = timeOut.timeOut();
// $scope.$storage = $sessionStorage;
// /* Datos del usuario y de sus deportes */
// $scope.user_sports = (!$scope.$storage.a_sports) ? [] : $scope.$storage.a_sports.replace('[','').replace(']','').split(',');
// }
// var confWordpress = {
// method: 'POST',
// url: 'php/dashboard/getBlogPostHome.php',
// headers: {
// 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
// }
// },
// confPromo = {
// method: 'GET',
// url: 'json/dataPromo.json',
// params: {'_':new Date().getTime()},
// headers: {
// 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
// }
// };
// /* Promociones */
// dataFactory.getDataFeed().then( function(response)
// {
// /* Datos de las casas */
// $scope.feed = response.data;
// $http(confPromo).
// success(function(data, status, headers, config)
// {
// /* Se guardan los datos .Primero las que son para usuarios registrados, luego las destacadas y luego las demas */
// $scope.promos = [];
// var not_two = !($scope.promos.length == 2);
// var no_more = true;
// var promos_add = [];
// var limit = 2;
// var index_register = 0;
// var index_imp = 0;
// var index = 0;
// while(not_two)
// {
// /* Usuarios registrados */
// index_register = 0;
// while(index_register < data.length && not_two)
// {
// /* No esta añadida */
// if(data[index_register]['user_registered'] == 1 && promos_add.indexOf(data[index_register]['id_promo'])== -1)
// {
// $scope.promos.push(data[index_register]);
// promos_add.push(data[index_register]['id_promo']);
// }
// not_two = !($scope.promos.length == limit);
// index_register++;
// }
// /* Destacadas */
// index_imp = 0;
// while(index_imp < data.length && not_two)
// {
// if(data[index_imp]['is_important'] == 1 && promos_add.indexOf(data[index_imp]['id_promo'])== -1)
// {
// $scope.promos.push(data[index_imp]);
// promos_add.push(data[index_imp]['id_promo']);
// }
// not_two = !($scope.promos.length == limit);
// index_imp++;
// }
// /* Resto por si no hay */
// index = 0;
// while(index < data.length && not_two)
// {
// if(promos_add.indexOf(data[index]['id_promo']) == -1)
// {
// $scope.promos.push(data[index]);
// promos_add.push(data[index]['id_promo']);
// }
// not_two = !($scope.promos.length == limit);
// index++;
// }
// }
// }).
// error(function(data, status, headers, config)
// {
// });
// });
// /* Post de la zona tipster */
// $http(confWordpress).
// success(function(data, status, headers, config)
// {
// /* Se guardan los datos */
// $scope.dataWordpress = data;
// }).
// error(function(data, status, headers, config)
// {
// });
// $scope.$watch('user_sport', function()
// {
// if($scope.user_sport != "")
// {
// dataFactory.getDataJson().then( function(response)
// {
// /* Si el usuario tiene deportes, los proximos eventos de esos deportes */
// /* Si no, los proximos eventos como en la portada */
// /* Primero hay que ordenar los eventos del json por fecha */
// var dataEventOrder = response.data;
// var limit = 13;
// dataEventOrder.sort(function (a, b) {
// return (a['orderTime'] > b['orderTime']) ? 1 : ((a['orderTime'] < b['orderTime']) ? -1 : 0);
// });
// $scope.events = [];
// if($scope.user_sports.length == 0)
// {
// /* Los 10 primeros */
// for(var index = 0; index < limit; index++)
// {
// $scope.events.push(dataEventOrder[index]);
// }
// }
// else
// {
// /* Lista de deporte y condicion de parada */
// var list_sports_stop = new Object();
// for(var index=0; index < $scope.user_sports.length; index++)
// {
// list_sports_stop[$scope.user_sports[index]] = false;
// }
// var not_ten = true; //condicion de parada por tamaño
// var exist_more = false; //condicion de parada por deporte
// var list_id_add = new Array();//lista de eventos añadidos
// /* Mientras no haya 10 eventos y existan eventos para los deportes del usuario */
// while (not_ten && !exist_more)
// {
// /* Para cada deporte */
// angular.forEach(list_sports_stop, function(value, key)
// {
// /* Para cada evento del portal */
// if(!value)
// {
// var find_event = value;
// for(var id_event = 0; id_event < dataEventOrder.length ; id_event++)
// {
// /* Evento del deporte y aun no añadido */
// if(dataEventOrder[id_event]['sportID'] == key &&
// list_id_add.indexOf(dataEventOrder[id_event]['id']) == -1 &&
// $scope.events.length < limit)
// {
// $scope.events.push(dataEventOrder[id_event]);
// list_id_add.push(dataEventOrder[id_event]['id']);
// find_event = true;
// break;
// }
// }
// list_sports_stop[key] = !find_event;
// }
// });
// /* Comprobar parada por deporte */
// var continue_sport = false;
// angular.forEach(list_sports_stop, function(value, key)
// {
// continue_sport = continue_sport || !value;
// });
// exist_more = !continue_sport;
// /* Comprobar parada por eventos */
// if($scope.events.length >= limit)
// not_ten = false;
// }
// if($scope.events.length <= parseInt(limit,10) -1)
// {
// /* Rellenamos por si no tenemos 10 eventos*/
// var not_enough = true;
// var index = 0;
// while(not_enough && index < dataEventOrder.length)
// {
// if(list_id_add.indexOf(dataEventOrder[index]['id']) == -1)
// {
// $scope.events.push(dataEventOrder[index]);
// }
// index++;
// not_enough = !($scope.events.length == limit);
// }
// }
// }
// });
// }
// });
// $scope.selectTitle = function(id, titleFeed, titlePersonal)
// {
// if (parseInt(id,10) > 0)
// return $translate.instant('bonus.generalPage.homeBonus.title'); //"Consigue tu bono de "+ titleFeed + " apuestas";
// else if(parseInt(id,10)== 0)
// return $translate.instant('promotions.linkTitle'); //"Promoción de Besgam";
// else
// return titlePersonal;
// };
// })
// .controller('userSettings', function( $scope, $http, $location, $sessionStorage, vcRecaptchaService, timeOut, $filter, $translate, dataFactory)
// {
// /* Controlar que se esta en sesion */
// var session = timeOut.timeOut();
// /* Si se ha entrado por facebook o twitter no se puede cambiar la contraseña */
// $scope.showPassBlock = angular.isDefined($sessionStorage.login_external) && $sessionStorage.login_external == 1 ? false : true;
// /* Datos del captcha */
// $scope.response = null;
// $scope.widgetId = null;
// /* Datos de los mercados y filtros */
// $scope.selected_sport = 0;
// $scope.selected_filter = 1;
// $scope.selected_market = 1;
// /* Variables para la visualizacion de mensajes */
// $scope.update_favorites = false;
// $scope.error_update_favorites = true;
// $scope.update_settings = false;
// $scope.error_update_settings = true;
// $scope.update_user = false;
// $scope.error_delete = true;
// $scope.delete_user = false;
// $scope.$storage = $sessionStorage;
// /* Primer elto del acordeon abierto*/
// $scope.status = {
// isFirstOpen: true
// };
// $scope.model = {
// key: '6LfuiAgTAAAAABTVAVcs1h1SEtBNTnhAT1gHi3uv'
// };
// var confUser = {
// method: 'POST',
// url: 'php/dashboard/getDataUser.php',
// data:'iduser='+ $scope.$storage.iduser,
// headers: {
// 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
// }
// };
// var confSport = {
// method: 'POST',
// url: 'php/dashboard/getDataUserSettings.php',
// headers: {
// 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
// }
// };
// // var confMarkets = {
// // method: 'GET',
// // url: 'json/markets.json',
// // headers: {
// // 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
// // }
// // }
// $scope.setResponse = function (response) {
// //console.info('Response available');
// $scope.response = response;
// };
// $scope.setWidgetId = function (widgetId) {
// //console.info('Created widget ID: %s', widgetId);
// $scope.widgetId = widgetId;
// };
// /* Modificar el src de la img de los deportes */
// $scope.selectUrl = function (item,sport){
// if($scope.user_sports.indexOf(item) !== -1 )
// return '/img/besgam-icons/sport-icons/sport-icons-register/icon-'+$filter('replaceName')(sport)+'-on.svg';
// else
// return '/img/besgam-icons/sport-icons/sport-icons-register/icon-'+$filter('replaceName')(sport)+'-off.svg';
// };
// /* Hacemos las llamadas para obtener los datos del usuario */
// $http(confUser).
// success(function(data, status, headers, config)
// {
// $translate('dashboard.header.count').then(function (translation) // "Evento no disponible en "+feed;
// {
// $sessionStorage.nameuser = ! (data.str_name) ? translation : data.str_name.substr(0,6) +"...";
// $sessionStorage.$save();
// });
// $scope.str_name = (!data.str_name) ? "" : data.str_name;
// $scope.str_email = data.str_email;
// $scope.iduser = data.iduser;
// /*$scope.str_pass = data.str_pass;
// $scope.str_pass_two = data.str_pass;*/
// $scope.str_pass = "";
// $scope.str_pass_two = "";
// $scope.actualpass="00000000";
// $scope.robinson = (data.robinson == "0") ? 0: 1;
// $scope.newsletter = data.newsletter;
// $scope.user_favorites = (!data.a_markets) ? [] : data.a_markets.replace('[','').replace(']','').split(',');
// for (elem_market in $scope.user_favorites ) {
// $scope.user_favorites[elem_market] = parseInt($scope.user_favorites[elem_market], 10);
// }
// $scope.user_feeds = (!data.a_feed) ? [] : data.a_feed.replace('[','').replace(']','').split(',');
// $scope.user_sports = (!data.a_sport) ? [] : data.a_sport.replace('[','').replace(']','').split(',');
// if(!data.str_other_sport)
// $scope.user_others = [];
// else
// $scope.user_others = data.str_other_sport.split(',');
// /* Datos de las casas, deportes y los filtros de mercados */
// $http(confSport).
// success(function(data, status, headers, config)
// {
// $scope.dataSettings = data;
// //console.log($scope.dataSettings);
// dataFactory.getDataFeed().then( function( listFeed )
// {
// $scope.dataSettings.feed = listFeed.data;
// });
// dataFactory.getDataMarkets().then( function( dataMarketsJSON )
// {
// $scope.dataFilters = dataMarketsJSON.data.filters;
// $scope.dataMarkets = dataMarketsJSON.data.markets;
// //console.log($scope.dataFilters) ;
// //console.log($scope.dataMarkets) ;
// });
// }).
// error(function(data, status, headers, config)
// {
// });
// }).
// error(function(data, status, headers, config)
// {
// });
// /* Actualizar el array de deportes */
// $scope.updateValue = function (structure,valueAdd,strData)
// {
// var index = structure.indexOf(valueAdd);
// if(index === -1){
// structure.push(valueAdd);
// if(strData!=""){
// return '/img/besgam-icons/sport-icons/sport-icons-register/icon-'+$filter('replaceName')(strData)+'-on.svg';
// }
// else{
// return 1;
// }
// }
// else if (index !== -1)
// {
// structure.splice(index, 1);
// if(strData!="")
// {
// return '/img/besgam-icons/sport-icons/sport-icons-register/icon-'+$filter('replaceName')(strData)+'-off.svg';
// }
// else{
// return 1;
// }
// }
// //console.log(structure);
// };
// /*Seleccion de deportes */
// $scope.isSportSelected = function(nSelection)
// {
// return $scope.selected_sport == nSelection;
// };
// $scope.setSportSelected = function(nSelection)
// {
// /*$scope.selected_sport = nSelection;
// $scope.selected_filter = 1;
// $scope.selected_market = 1;*/
// $scope.selected_sport = nSelection;
// $scope.selected_filter = 1;
// $scope.selected_market = 1;
// };
// /* Seleccion de filtros */
// $scope.isFilterSelected = function(nFilter,nSport)
// {
// return $scope.selected_sport == nSport && $scope.selected_filter == nFilter;
// };
// $scope.setFilterSelected = function(nFilter,nSport)
// {
// $scope.selected_sport = nSport;
// $scope.selected_filter = nFilter;
// };
// /* Indicar si el mercado esta seleccionado */
// $scope.isMarketSelected = function(nFilter,nSport)
// {
// return $scope.selected_sport == nSport && $scope.selected_filter == nFilter;
// };
// /* Actualizar el array de deportes */
// $scope.updateFavorites = function(nMarket)
// {
// //console.log($scope.user_favorites);
// var index = $scope.user_favorites.indexOf(nMarket);
// if(index === -1)
// $scope.user_favorites.push(nMarket);
// else
// $scope.user_favorites.splice(index, 1);
// //console.log($scope.user_favorites);
// };
// /* Envio de los 3 posibles formularios */
// $scope.submit = function(form)
// {
// switch (form.$name)
// {
// case 'editForm':
// /* Se envian los datos para actualizar al usuario */
// var change_pass = 1;
// var reload = 0;
// form.editCaptcha.$setValidity('recaptcha', true);
// form.str_pass_two.$setValidity('equal', true);
// form.str_pass_two.$setValidity('unexpected', true);
// /* Comprobar si se ha modificado la password*/
// /*if($scope.str_pass == this.str_pass)
// change_pass = 0;*/
// if(this.str_pass=="" && this.str_pass_two=="")
// change_pass = 0;
// Comprobar si se ha modificado el nombre o correo para recargar o no la pagina
// if($scope.str_name != this.str_name || $scope.str_email != this.str_email)
// reload = 1;
// /* Validar captcha e igualdad de passwords */
// if( !$scope.response || form.$error.recaptcha )
// form.editCaptcha.$setValidity('recaptcha', false);
// if( this.str_pass != this.str_pass_two )
// form.str_pass_two.$setValidity('equal', false);
// $scope.$broadcast('validate-form', form.$name );
// if( form.$invalid )
// return false;
// var params = {
// method: "POST",
// url: "php/dashboard/updateUser.php",
// data: "iduser="+this.iduser+"&str_name="+this.str_name+"&str_email="+this.str_email+"&str_pass="+this.str_pass+
// "&robinson="+this.robinson+"&newsletter="+this.newsletter+"&change="+change_pass+"&resp="+$scope.response
// };
// $http( params )
// .success(function(data, status, headers, params)
// {
// /* Si nos devuelve un error */
// if( data.error )
// {
// /* Dependiendo de la respuesta damos el error */
// switch(data.type)
// {
// case 'EMPTY_ERROR':
// form.name.$setValidity("unexpected", false);
// break;
// case 'CAPTCHA_KO': // La respuesta del Captcha no es correcta.
// form.editCaptcha.$setValidity('recaptcha', false);
// break;
// default: // Error por defecto
// form.str_pass_two.$setValidity('unexpected', false);
// }
// }
// else
// {
// $translate('dashboard.header.count').then(function (translation) // "Evento no disponible en "+feed;
// {
// $sessionStorage.nameuser = !(data.str_name) ? translation : data.str_name.substr(0,6)+"...";
// $sessionStorage.$save();
// $scope.$storage = $sessionStorage;
// });
// $scope.update_user = true;
// }
// $scope.response = null;
// vcRecaptchaService.reload(0);
// $scope.$broadcast('validate-form', form.$name );
// })
// .error(function(data, status, headers, config)
// {
// $scope.response = null;
// vcRecaptchaService.reload(0);
// form.name.$setValidity("unexpected", false);
// $scope.$broadcast('validate-form', form.$name );
// });
// break;
// case 'settingsForm':
// /* Enviamos los datos para actualizar las casas y deportes del usuario */
// /* Creamos la lista de deportes textuales */
// var str_others = "";
// angular.forEach(this.user_others, function(value, key) {
// if(str_others=="")
// str_others = str_others + value.text ;
// else
// str_others = str_others + "," +value.text;
// });
// var params = {
// method: "POST",
// url: "php/dashboard/updateUserSettings.php",
// data:"iduser="+this.iduser+"&user_sports="+$scope.user_sports+"&user_feeds="+ $scope.user_feeds
// + "&user_others="+ str_others
// };
// $http( params )
// .success(function(data, status, headers, params)
// {
// /* Activamos la visualizacion de mensajes de respuesta segun el resultado de la llamada */
// if( data.msg == "KAO")
// $scope.error_update_settings = true;
// else
// {
// $scope.error_update_settings = false;
// $sessionStorage.a_sports = "[" + $scope.user_sports + "]";
// $sessionStorage.$save();
// }
// $scope.update_settings = true;
// }).error(function(data, status, headers, config)
// {
// $scope.error_update_settings = true;
// $scope.update_settings = true;
// });
// break;
// case 'favoritesForm':
// /* Enviamos los datos para actualizar los favoritos */
// var params = {
// method: "POST",
// url: "php/dashboard/updateUserFavorites.php",
// data: "iduser="+this.iduser+"&user_markets="+$scope.user_favorites
// };
// $http( params )
// .success(function(data, status, headers, params)
// {
// /* Activamos la visualizacion de los mensajes de respuesta segun se hayan podido o no
// actualizar los favoritos */
// if( data.msg == "KAO" )
// $scope.error_update_favorites = true;
// else
// {
// $scope.error_update_favorites = false;
// $sessionStorage.favorites = $scope.user_favorites;
// $sessionStorage.$save();
// }
// $scope.update_favorites = true;
// }).error(function(data, status, headers, config)
// {
// $scope.error_update_favorites = true;
// $scope.update_favorites = true;
// });
// break;
// case 'deleteForm':
// form.deleteCaptcha.$setValidity('recaptcha', true);
// /* Validar captcha */
// if( !$scope.response || form.$error.recaptcha )
// form.deleteCaptcha.$setValidity('recaptcha', false);
// $scope.$broadcast('validate-form', form.$name );
// if( form.$invalid )
// return false;
// /*Enviamos los datos para borrar el usuario */
// var params = {
// method: "POST",
// url: "php/dashboard/deleteUser.php",
// data: "iduser="+this.iduser+"&resp="+$scope.response
// };
// $http( params )
// .success(function(data, status, headers, params)
// {
// /* Activamos la visualizacion de los mensajes de respuesta segun se haya podido o no dar de baja */
// if( data.msg == "KAO-BBDD" )
// $scope.error_delete = true;
// else if(data.msg == "KAO-CAPTCHA")
// form.deleteCaptcha.$setValidity('recaptcha', false);
// else
// {
// /* Borrar la sesion del navegador */
// $sessionStorage.favorites = null;
// $sessionStorage.iduser = null;
// $sessionStorage.nameuser = null;
// $sessionStorage.str_name = null;
// $sessionStorage.str_email = null;
// $sessionStorage.a_sports = null;
// $sessionStorage.sessionid = null;
// $sessionStorage.other_sport = null;
// $sessionStorage.expired = 0;
// $sessionStorage.$save();
// $sessionStorage.$reset();
// $location.path('deleteUser').replace();
// }
// $scope.response = null;
// vcRecaptchaService.reload(1);
// $scope.$broadcast('validate-form', form.$name );
// }).error(function(data, status, headers, config)
// {
// $scope.delete_user= true;
// $scope.error_delete = true;
// $scope.response = null;
// vcRecaptchaService.reload(1);
// });
// break;
// }
// };
// })
// .controller("userPromotions", function( $scope, $http, $location, dataFactory, $sessionStorage, $translate, timeOut)
// {
// /* Controlar que se esta en sesion */
// var session = timeOut.timeOut();
// $scope.dataPromo = [];
// $scope.textInfo ="Cargando datos...";
// $scope.$storage = $sessionStorage;
// var confPromo = {
// /* Datos de las promociones */
// method: 'GET',
// url: 'json/dataPromo.json',
// params: {'_':new Date().getTime()},
// headers: {
// 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
// }
// };
// /* Se hace la llamada para obtener la info de las casas y de las promos*/
// dataFactory.getDataFeed().then( function(response)
// {
// /* Datos de las casas */
// $scope.feed = response.data;
// $http(confPromo).
// success(function(data, status, headers, config)
// {
// /* Guardar las promos */
// $scope.dataPromo = data;
// /* Expirar las promociones desde el cliente */
// var today = new Date();
// angular.forEach($scope.dataPromo, function(value, key) {
// if(new Date(value.date_end) < today)
// {
// value.is_expired = 1;
// }
// });
// Paginacion
// $scope.totalData = ($scope.dataPromo.length-10);
// $scope.currentPage = 1;
// $scope.numPerPage = 10;
// $scope.maxSize = 5;
// $scope.setPage = function (pageNo)
// {
// window.scrollTo(0,0);
// $scope.currentPage = pageNo;
// };
// $scope.setPage($scope.currentPage);
// $translate('promotions.noPromo').then(function (translation) //"Actualmente no tenemos promociones disponibles.";
// {
// $scope.textInfo = translation;
// });
// }).
// error(function(data, status, headers, config)
// {
// });
// });
// /* Cambiar los estilos d elas promo segun su tipo */
// $scope.changeClassGround = function(is_important,is_registered, is_expired)
// {
// if(is_important==1)
// return 'user-promo-dest';
// else
// if(is_registered=='1' && is_expired==0)
// return 'user-promo-favorite';
// else
// return 'user-promo';
// }
// $scope.changeClassPromo = function(is_important)
// {
// if(is_important==1)
// return 'imagen-casa';
// else if(is_important==0)
// return 'user-imagen-casa-promo';
// }
// })
// .controller('userAcademy', function( $scope, $http, $location, $sessionStorage, timeOut)
// {
// /* Controlar que se esta en sesion */
// var session = timeOut.timeOut();
// $scope.data = [];
// $scope.$storage = $sessionStorage;
// /* Obtenemos los post de worpress */
// var confWordpress = {
// method: 'POST',
// url: 'php/dashboard/getBlogPost.php',
// headers: {
// 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
// }
// };
// $http(confWordpress).
// success(function(data, status, headers, config)
// {
// /* Se guardan los datos */
// $scope.data = data;
// /* Paginacion */
// $scope.totalData = ($scope.data.length-9);
// $scope.currentPage = 1;
// $scope.numPerPage = 9;
// $scope.maxSize = 5;
// $scope.setPage = function (pageNo)
// {
// window.scrollTo(0,0);
// $scope.currentPage = pageNo;
// };
// $scope.setPage($scope.currentPage);
// }).
// error(function(data, status, headers, config)
// {
// });
// })
// .controller('nivelesCtrl', function($scope, $window, dataFactory)
// {
// /* Instanciamos variables */
// $scope.dataJson = [];
// $scope.limit = 3;
// $scope.maxLimit = 8;
// $scope.eventBlock = [];
// $scope.eventData = [];
// $scope.betSlip = [];
// $scope.totalCombined = [];
// $scope.msgActive = false;
// $scope.sportSelect = 0;
// $scope.items = [{
// name : 'RangeTime',
// value : 3
// },
// {
// name : 'RangeOddLow',
// value : 4
// },
// {
// name : 'rangeOddHigh',
// value : 11
// }];
// $scope.rangeTime = [
// { diff: 3600, range: 1, srange: "hora" },
// { diff: 3600*6, range: 6, srange: "horas" },
// { diff: 3600*24, range: 24, srange: "horas" },
// { diff: 3600*48, range: 48, srange: "horas" },
// { diff: 3600*72, range: 72, srange: "horas" },
// { diff: 3600*24*7, range: 7, srange: "días" }
// ];
// $scope.rangeOdd = [
// { odd: 1.2 },
// { odd: 1.4 },
// { odd: 1.6 },
// { odd: 1.8 },
// { odd: 2.0 },
// { odd: 2.2 },
// { odd: 2.5 },
// { odd: 3.0 },
// { odd: 3.5 },
// { odd: 4.0 },
// { odd: 4.5 },
// { odd: 5.0 },
// { odd: 6.0 },
// { odd: 7.0 },
// { odd: 8.0 },
// { odd: 9.0 },
// { odd: 10.0 }
// ];
// /* Cargamos los datos de las feed */
// dataFactory.getDataFeed().then( function(response)
// {
// $scope.feed = response.data;
// /* Cargamos las apuestas */
// dataFactory.getDataJson().then( function(response)
// {
// $scope.dataJson = response.data;
// $scope.sports = $scope.dataJson.reduce(function(sum, place)
// {
// if( sum.indexOf( place.sport ) < 0 ) sum.push(place.sport);
// return sum;
// }, []);
// $scope.getData = function()
// {
// $scope.list = $scope.dataJson.reduce(function(sum, place)
// {
// if( !place.markets || ($scope.sportSelect != 0 && $scope.sportSelect != place.sport ) ) return sum;
// if( fInTime( place.time, $scope.rangeTime[$scope.items[0].value].diff ) )
// {
// var addBet = [],
// objAux = {};
// if( place.markets.str_bet[1][0].n_odd >= $scope.rangeOdd[$scope.items[1].value].odd &&
// place.markets.str_bet[1][0].n_odd <= $scope.rangeOdd[$scope.items[2].value].odd )
// {
// addBet.push({
// betName: '1',
// bet: place.markets.str_bet[1]
// });
// }
// if( place.markets.str_bet[2][0].n_odd >= $scope.rangeOdd[$scope.items[1].value].odd &&
// place.markets.str_bet[2][0].n_odd <= $scope.rangeOdd[$scope.items[2].value].odd )
// {
// addBet.push({
// betName: '2',
// bet: place.markets.str_bet[2]
// });
// }
// if( place.markets.str_bet['X'] &&
// place.markets.str_bet['X'][0].n_odd >= $scope.rangeOdd[$scope.items[1].value].odd &&
// place.markets.str_bet['X'][0].n_odd <= $scope.rangeOdd[$scope.items[2].value].odd )
// {
// addBet.push({
// betName: 'X',
// bet: place.markets.str_bet['X']
// });
// }
// if( addBet.length > 0 )
// {
// objAux = {
// sport: place.sport,
// sportID: place.sportID,
// leagueID: place.leagueID,
// league: place.league,
// id: place.id,
// eventN: place.event,
// market: place.markets.str_market_short,
// is_available: 1
// };
// shuffleArray(addBet);
// objAux.betName = addBet[0].betName;
// objAux.bet = addBet[0].bet;
// objAux.focus_bet = {
// id_feed: addBet[0].bet[0].id_feed,
// n_odd: addBet[0].bet[0].n_odd,
// id_bet: addBet[0].bet[0].id_bet
// }
// sum.push( objAux );
// }
// }
// return sum;
// }, []);
// shuffleArray($scope.list);
// $scope.list.sort( function( a, b)
// {
// if( a["bet"].length > b["bet"].length ) return -1;
// if( a["bet"].length < b["bet"].length ) return 1;
// return 0;
// });
// if( $scope.list.length >= $scope.limit )
// {
// for( var nCont = 0, len = $scope.limit;
// nCont < len;
// nCont++ )
// {
// if( !$scope.eventBlock[ nCont ] )
// {
// $scope.eventData[ nCont ] = $scope.list[ nCont ];
// }
// }
// $scope.betSlip = [];
// for( var nCont = 0, len = $scope.eventData.length;
// nCont < len;
// nCont++ )
// {
// $scope.addBetSlip( $scope.eventData[nCont].bet );
// }
// return $scope.eventData;
// }
// else
// $scope.msgActive = true;
// }
// $scope.getData();
// });
// $scope.addEvent = function()
// {
// if( $scope.list[ $scope.limit ] && $scope.limit < $scope.maxLimit )
// {
// $scope.eventData.push( $scope.list[ $scope.limit ] );
// $scope.addBetSlip( $scope.list[ $scope.limit ].bet );
// $scope.limit++;
// }
// else
// $scope.msgActive = true;
// }
// $scope.delEvent = function( id )
// {
// $scope.delBetSlip( $scope.eventData[id].bet );
// $scope.eventData.splice(id, 1);
// $scope.eventBlock.splice(id, 1);
// $scope.list.splice(id, 1);
// $scope.limit--;
// };
// var fInTime = function( strTime, rangeTime )
// {
// if( !strTime ) return; // Control para evitar vacios
// var targetTime = new Date( strTime ),
// offsetTime = new Date(targetTime.getTime() + (targetTime.getTimezoneOffset() * 60 * 1000) * -1 ),
// today = new Date(),
// diffTime = new Date(today.getTime() + (rangeTime * 1000) );
// return (offsetTime > today && offsetTime < diffTime ) ? 1 : 0;
// };
// var shuffleArray = function(array)
// {
// var m = array.length, t, i;
// while (m)
// {
// i = Math.floor(Math.random() * m--);
// t = array[m];
// array[m] = array[i];
// array[i] = t;
// }
// return array;
// };
// $scope.totalCombinedData = function( odd, feed )
// {
// var total = 0,
// exit = false;
// if( angular.isUndefined( feed ) && angular.isUndefined( odd ) )
// {
// angular.forEach($scope.betSlip, function(value, key)
// {
// if( value.n_odd > total )
// {
// total = value.n_odd;
// $scope.totalCombined = {
// "value": value.n_odd,
// "feed": value.id_feed
// };
// }
// });
// }
// else
// {
// $scope.totalCombined = {
// "value": odd,
// "feed": feed
// };
// }
// /* Modificamos el foco */
// angular.forEach($scope.eventData, function(value, key)
// {
// for( var nCont = 0, len = value.bet.length;
// nCont < len && !exit; nCont++ )
// {
// if( value.bet[nCont].id_feed == $scope.totalCombined.feed )
// {
// value.focus_bet.id_feed = value.bet[nCont].id_feed;
// value.focus_bet.n_odd = value.bet[nCont].n_odd;
// value.focus_bet.id_bet = value.bet[nCont].id_bet;
// value.is_available = 1;
// exit = true;
// }
// }
// /* No existe la apuesta para la casa seleccionada */
// if( !exit ) value.is_available = 0;
// /* Volvemos a iniciar la salida */
// exit = false;
// });
// };
// $scope.addBetSlip = function( bets )
// {
// var obj = {}, // Obj para insertar en nuestro boleto
// fSearch = false; // Comprobar si ya tenemos ese feed
// angular.forEach(bets, function(bet, bKey)
// {
// angular.forEach( $scope.betSlip, function( value, key )
// {
// if( bet.id_feed == value.id_feed )
// {
// value.n_odd = value.n_odd * bet.n_odd;
// fSearch = true;
// }
// });
// /* Si no lo encontramos lo insertamos */
// if( !fSearch )
// $scope.betSlip.push({
// "id_feed": bet.id_feed,
// "n_odd": bet.n_odd
// });
// fSearch = false;
// });
// $scope.totalCombinedData();
// };
// $scope.delBetSlip = function( bets )
// {
// angular.forEach(bets, function(bet, bKey)
// {
// angular.forEach( $scope.betSlip, function( value, key )
// {
// if( bet.id_feed == value.id_feed )
// {
// value.n_odd = value.n_odd / bet.n_odd;
// if( value.n_odd <= 1 )
// $scope.betSlip.splice(key, 1);
// }
// });
// });
// $scope.totalCombinedData();
// };
// $scope.locationTo = function( str_league, str_event, id_event, id_sport )
// {
// str_league = str_league.replace(/\//g,"-");
// str_league = str_league.replace(/ /g,"-");
// str_event = str_event.replace(/\//g,"-");
// window.open( './#!apuestas/' + angular.lowercase(str_league) + '/' + angular.lowercase(str_event) + '/' + id_event + '/' + id_sport + '/', '_blank');
// };
// $scope.submit = function(form)
// {
// var id_feed = this.id_feed,
// id_league = this.id_league,
// id_event = this.id_event,
// id_bet = [];
// for( var nCont = 0, len = $scope.eventData.length;
// nCont < len;
// nCont++ )
// {
// id_bet.push( $scope.eventData[nCont].focus_bet.id_bet );
// }
// url = "./#!redirect/" +
// id_feed + "/" +
// id_league + "/" +
// id_event + "/" +
// id_bet.join() + "/" +
// "0/";
// $window.open( url, '_blank' );
// };
// });
// })
; |
import userQueries from '../DB/queries/user-queries.js';
import jwtFunctions from '../auth/jwt.js';
import encrypt from '../auth/encrypt.js';
import db from '../models/index.js';
const { User, FanPage } = db;
//import user queries functions
const { verifyUser, usernameEmailExist, updateUser, verifyUsername } = userQueries;
//import jwt functions
const { createToken } = jwtFunctions;
// import encrypt functions
const { hashPassword } = encrypt;
// register new user
const register = async (req, res) => {
try {
const { firstName, lastName, email, password, verifiedPassword } = req.body;
//make username lowercase
const username = req.body.username.toLowerCase();
// check if user exists already based on username or email
const exists = await usernameEmailExist(username, email);
// throw error if email or username exists
if (exists) throw exists;
if (exists === 'serverError') throw exists;
// make user password and verify password matches just to be safe
if (password !== verifiedPassword) throw 'passwordMismatch';
// hash the password
const hashedPassword = hashPassword(verifiedPassword);
// create the user in DB
const newUser = {
firstName,
lastName,
email,
username,
password: hashedPassword
};
// send user to db for creation
await User.create(newUser);
return res.status(201).json({
status: 201,
message: 'User was created successfully',
requestedAt: new Date().toLocaleString(),
});
} catch (error) {
console.log(error); //keep just incase if db error
//user already exists error
if (error === "emailExists" || error === "usernameExists") {
return res.status(409).json({
status: 409,
message: error,
requestAt: new Date().toLocaleString()
});
}
// password does not match error
if (error === "passwordMismatch") {
return res.status(401).json({
status: 401,
message: error,
requestAt: new Date().toLocaleString()
});
}
// all other errors
return res.status(500).json({
status: 500,
message: "Server error",
requestAt: new Date().toLocaleString()
});
}
}
// login user
const login = async (req, res) => {
try {
// grab data from body
const { password } = req.body;
const username = req.body.username.toLowerCase();
// check if credentials are empty
if (!username || !password) throw 'Invalid Credentials';
// Verify if user credentials matches
const verifiedUser = await verifyUser(username, password);
if (verifiedUser !== false) {
// create the json web token
const userJWT = createToken(verifiedUser);
return res.status(200).json({
status: 200,
message: 'Success',
userJWT,
requestAt: new Date().toLocaleString()
});
} else {
throw 'Invalid Credentials';
}
} catch (error) {
// if invalid credentials then let user know
if (error === 'Invalid Credentials') {
return res.status(401).json({
status: 401,
message: 'Invalid Credentials',
requestAt: new Date().toLocaleString()
});
}
return res.status(500).json({
status: 500,
message: 'Server error',
requestAt: new Date().toLocaleString()
});
}
};
// send user data
const getUserData = async (req, res) => {
try {
//get user data minus the password
const foundUser = await User.findById(req.user._id).select('-password').lean();
//grab users top 4 most recent pages
const recentPages = await FanPage.find({
author: req.user._id
}).sort('-createdAt').limit(4);
foundUser.recentPages = recentPages;
return res.status(200).json({
status: 200,
message: 'Success',
foundUser,
requestAt: new Date().toLocaleString()
});
} catch (error) {
return res.status(500).json({
status: 500,
message: 'Server error',
requestAt: new Date().toLocaleString()
});
}
};
// update the user data
const updateUserData = async (req, res) => {
try {
//make username lowercase
req.body.username = req.body.username.toLowerCase();
//grab userID
const userID = req.params.userID;
//username from React front end
const username = req.body.username;
//grab username from MongoDB
const foundUser = await User.findById(userID).select('-password');
//if front end username is not equal to Database stored username...
if (username !== foundUser.username) {
const userExists = await verifyUsername(username);
if (userExists) throw 'userExists';
}
const updatedUser = await updateUser(userID, req.body);
if (updateUser === false) throw 'updatedUserFailed';
//create a new jwt to be returned
const userJWT = createToken(updatedUser);
return res.status(200).json({
status: 200,
message: 'Success',
updatedUser,
userJWT,
requestAt: new Date().toLocaleString()
});
} catch (error) {
console.log(error)
// DB failed to update user
if (error === "updateUserFailed") {
return res.status(400).json({
status: 400,
message: 'Failed to update user',
requestAt: new Date().toLocaleString()
});
}
// send message if username already exists
if (error === "userExists") {
return res.status(400).json({
status: 400,
message: 'Username already exists',
requestAt: new Date().toLocaleString()
});
}
return res.status(500).json({
status: 500,
message: 'Server error',
requestAt: new Date().toLocaleString()
});
}
};
const authCtrls = {
login,
register,
getUserData,
updateUserData,
}
export default authCtrls; |
'use strict';
function addColumn (ev) {
ev.preventDefault();
let array = [];
this.state.table.forEach(function(arr,i){
arr.push('');
array.push(arr);
});
this.setState({table:array});
}
function addRow (ev) {
ev.preventDefault();
let array = this.state.table;
array.push(['','']);
this.setState({table:array});
}
function changeCell (rowIndex, columnIndex, ev) {
let array = this.state.table;
array[rowIndex][columnIndex] = ev.target.value;
this.setState({table:array});
}
function focusCell (rowIndex, columnIndex) {
this.setState({focused:[rowIndex,columnIndex]});
}
function blurCell () {
this.setState({focused:null});
}
function removeRow (ev) {
ev.preventDefault();
if (this.state.table.length > 1) {
let array = this.state.table;
array.pop();
this.setState({table:array});
}
}
function removeColumn (ev) {
ev.preventDefault();
let array = this.state.table;
let removed = false;
array.forEach(function(arr,i){
if(arr.length > 1){
removed = true;
arr.pop();
}
});
if (removed) {
this.setState({table:array});
}
}
export default {
addColumn,
addRow,
changeCell,
focusCell,
blurCell,
removeRow,
removeColumn
};
|
import { useState, useEffect } from "react";
import ListItem from "./todoListItem";
let taskData = JSON.parse(localStorage.getItem("taskData")) || [];
const App = (props) => {
const [tasks, setTasks] = useState(taskData);
const makeId = () => {
let abc = "abcdefghijklmnopqrstuvwxyz";
let id = "";
while (tasks.map((e) => e.id).includes(id) || id === "") {
for (let i = 0; i < 5; i++) {
id += abc[Math.floor(Math.random() * 26)];
}
}
return id;
};
const toggleTheme = () => {
let currentTheme = document.body.classList[0];
if (currentTheme === "darkTheme")
document.body.classList.replace("darkTheme", "lightTheme");
if (currentTheme === "lightTheme")
document.body.classList.replace("lightTheme", "darkTheme");
};
const dltTask = (id) => {
let parent = document.querySelector("#" + id + "").parentElement
.parentElement;
if (parent.nodeName === "LI") {
setTasks(tasks.filter((e) => e.id !== id));
}
};
const handleNewData = (e, id) => {
if ((e?.type === "keyup" && e?.key === "Enter") || e?.type === "blur") {
e.preventDefault();
if (e.target.value === "") return;
setTasks([
...tasks,
{ id: makeId(), content: e.target.value, state: false },
]);
e.target.value = "";
}
};
const changeTaskType = (e) => {
let id = e.target.id;
let state = e.target.checked;
tasks.find((e) => e.id === id).state = state;
setTasks([...tasks]);
};
useEffect(() => {
localStorage.setItem("taskData", JSON.stringify(tasks));
});
const clearCompleted = () => {
setTasks([...tasks.filter((e) => !e.state)]);
};
const showBy = (type) => {
switch (type) {
case "active":
document
.querySelectorAll(
"#root > div > div.TODOList > div > div > button"
)
.forEach((e) => {
if (e.classList.contains("activeBtn"))
e.classList.remove("activeBtn");
});
document
.querySelector(
"#root > div > div.TODOList > div > div > button:nth-child(2)"
)
.classList.add("activeBtn");
document
.querySelectorAll(
"#root > div > div.TODOList > ul li >div> input"
)
.forEach((i) => {
i.parentElement.parentElement.style.display = "block";
if (i.checked) {
i.parentElement.parentElement.style.display =
"none";
}
});
break;
case "completed":
document
.querySelectorAll(
"#root > div > div.TODOList > div > div > button"
)
.forEach((e) => {
if (e.classList.contains("activeBtn"))
e.classList.remove("activeBtn");
});
document
.querySelector(
"#root > div > div.TODOList > div > div > button:nth-child(3)"
)
.classList.add("activeBtn");
document
.querySelectorAll(
"#root > div > div.TODOList > ul li >div> input"
)
.forEach((i) => {
i.parentElement.parentElement.style.display = "block";
if (!i.checked) {
i.parentElement.parentElement.style.display =
"none";
}
});
break;
case "all":
document
.querySelectorAll(
"#root > div > div.TODOList > div > div > button"
)
.forEach((e) => {
if (e.classList.contains("activeBtn"))
e.classList.remove("activeBtn");
});
document
.querySelector(
"#root > div > div.TODOList > div > div > button:nth-child(1)"
)
.classList.add("activeBtn");
document
.querySelectorAll(
"#root > div > div.TODOList > ul li >div> input"
)
.forEach((i) => {
i.parentElement.parentElement.style.display = "block";
});
break;
default:
document.querySelectorAll(
"#root > div > div.TODOList > ul li"
).style.display = "block";
break;
}
};
return (
<div className="app">
<div className="topBar">
<h1 className="appName">TODO</h1>
<button className="themeBtn" onClick={toggleTheme}></button>
</div>
<div className="newTODO">
{(() => {
let id = makeId();
return (
<ListItem
handleNewData={handleNewData}
checkBoxId={id}
isChecked={false}
listItemText="Type new task"
type={"input"}
/>
);
})()}
</div>
<div className="TODOList">
<ul>
{tasks.map((data) => {
return (
<li key={data.id}>
<ListItem
key={data.id}
dltTask={dltTask}
changeTaskType={changeTaskType}
checkBoxId={data.id}
isChecked={data.state}
listItemText={data.content}
type={"display"}
/>
</li>
);
})}
</ul>
<div className="listInfo">
<span className="itemLength">
{tasks.length} items left
</span>
<div className="filterItems">
<button
className="activeBtn"
onClick={() => showBy("all")}
>
All
</button>
<button onClick={() => showBy("active")}>Active</button>
<button onClick={() => showBy("completed")}>
Completed
</button>
</div>
<button className="clearComplete" onClick={clearCompleted}>
Clear Complete
</button>
</div>
</div>
</div>
);
};
export default App;
|
/*
* ProGade API
* http://api.progade.de/
*
* Copyright 2012, Hans-Peter Wandura (ProGade)
* You can find the Licenses, Terms and Conditions under: http://api.progade.de/api_terms.php
*
* Last changes of this file: Aug 23 2012
*/
/*
@start class
@param extends classPG_ClassBasics
*/
function classPG_DropArea()
{
// Declarations...
this.iDefaultGridX = 0;
this.iDefaultGridY = 0;
this.iDefaultType = PG_DROPAREA_TYPE_SIMPLE;
this.sDefaultGroupID = PG_DRAGANDDROP_GROUP_ALL;
this.iDefaultMaxElements = 0;
this.sDefaultCssStyle = '';
this.sDefaultCssClass = '';
// this.iDefaultGrabMoveDistX = -1;
// this.iDefaultGrabMoveDistY = -1;
// Construct...
this.setID({'sID': 'PGDropArea'});
this.initClassBasics();
// Methods...
/*
@start method
@param iType [needed][type]int[/type]
[en]...[/en]
*/
this.setDefaultType = function(_iType)
{
_iType = this.getRealParameter({'oParameters': _iType, 'sName': 'iType', 'xParameter': _iType});
this.iDefaultType = _iType;
}
/* @end method */
/*
@start method
@return iType [type]int[/type]
[en]...[/en]
*/
this.getDefaultType = function() {return this.iDefaultType;}
/* @end method */
/*
@start method
@param iGroupID [needed][type]int[/type]
[en]...[/en]
*/
this.setDefaultGroupID = function(_iGroupID)
{
_iGroupID = this.getRealParameter({'oParameters': _iGroupID, 'sName': 'iGroupID', 'xParameter': _iGroupID});
this.sDefaultGroupID = _iGroupID;
}
/* @end method */
/*
@start method
@return sGroupID [type]string[/type]
[en]...[/en]
*/
this.getDefaultGroupID = function() {return this.sDefaultGroupID;}
/* @end method */
/*
@start method
@param sStyle [needed][type]string[/type]
[en]...[/en]
*/
this.setDefaultCssStyle = function(_sStyle)
{
_sStyle = this.getRealParameter({'oParameters': _sStyle, 'sName': 'sStyle', 'xParameter': _sStyle});
this.sDefaultCssStyle = _sStyle;
}
/* @end method */
/*
@start method
@return sCssStyle [type]string[/type]
[en]...[/en]
*/
this.getDefaultCssStyle = function() {return this.sDefaultCssStyle;}
/* @end method */
/*
@start method
@param sClass [needed][type]string[/type]
[en]...[/en]
*/
this.setDefaultCssClass = function(_sClass)
{
_sClass = this.getRealParameter({'oParameters': _sClass, 'sName': 'sClass', 'xParameter': _sClass});
this.sDefaultCssClass = _sClass;
}
/* @end method */
/*
@start method
@return sCssClass [type]string[/type]
[en]...[/en]
*/
this.getDefaultCssClass = function() {return this.sDefaultCssClass;}
/* @end method */
/*
@start method
@param iGridX [needed][type]int[/type]
[en]...[/en]
*/
this.setDefaultGridX = function(_iGridX)
{
_iGridX = this.getRealParameter({'oParameters': _iGridX, 'sName': 'iGridX', 'xParameter': _iGridX});
this.iDefaultGridX = _iGridX;
}
/* @end method */
/*
@start method
@return iGridX [type]int[/type]
[en]...[/en]
*/
this.getDefaultGridX = function() {return this.iDefaultGridX;}
/* @end method */
/*
@start method
@param iGridY [needed][type]int[/type]
[en]...[/en]
*/
this.setDefaultGridY = function(_iGridY)
{
_iGridY = this.getRealParameter({'oParameters': _iGridY, 'sName': 'iGridY', 'xParameter': _iGridY});
this.iDefaultGridY = _iGridY;
}
/* @end method */
/*
@start method
@return iGridY [type]int[/type]
[en]...[/en]
*/
this.getDefaultGridY = function() {return this.iDefaultGridY;}
/* @end method */
/*
@start method
@param iGridX [type]int[/type]
[en]...[/en]
@param iGridY [type]int[/type]
[en]...[/en]
*/
this.setDefaultGrid = function(_iGridX, _iGridY)
{
if (typeof(_iGridY) == 'undefined') {var _iGridY = null;}
_iGridY = this.getRealParameter({'oParameters': _iGridX, 'sName': 'iGridY', 'xParameter': _iGridY});
_iGridX = this.getRealParameter({'oParameters': _iGridX, 'sName': 'iGridX', 'xParameter': _iGridX});
this.iDefaultGridX = _iGridX;
this.iDefaultGridY = _iGridY;
}
/* @end method */
/*
@start method
@param sContainerID [needed][type]string[/type]
[en]...[/en]
@param sDropAreaID [type]string[/type]
[en]...[/en]
@param sSizeX [type]string[/type]
[en]...[/en]
@param sSizeY [type]string[/type]
[en]...[/en]
@param iGridX [type]int[/type]
[en]...[/en]
@param iGridY [type]int[/type]
[en]...[/en]
@param iDropAreaType [type]int[/type]
[en]...[/en]
@param iGroupID [type]int[/type]
[en]...[/en]
@param sContent [type]string[/type]
[en]...[/en]
@param sOnDrop [type]string[/type]
[en]...[/en]
@param axData [type]mixed[][/type]
[en]...[/en]
@param iMaxDragElements [type]int[/type]
[en]...[/en]
@param sCssStyle [type]string[/type]
[en]...[/en]
@param sCssClass [type]string[/type]
[en]...[/en]
*/
this.buildInto = function(
_sContainerID,
_sDropAreaID,
_sSizeX,
_sSizeY,
_iGridX,
_iGridY,
_iDropAreaType,
_iGroupID,
_sContent,
_sOnDrop,
_axData,
_iMaxDragElements,
_sCssStyle,
_sCssClass
)
{
if (typeof(_sDropAreaID) == 'undefined') {var _sDropAreaID = null;}
if (typeof(_sSizeX) == 'undefined') {var _sSizeX = null;}
if (typeof(_sSizeY) == 'undefined') {var _sSizeY = null;}
if (typeof(_iGridX) == 'undefined') {var _iGridX = null;}
if (typeof(_iGridY) == 'undefined') {var _iGridY = null;}
if (typeof(_iDropAreaType) == 'undefined') {var _iDropAreaType = null;}
if (typeof(_iGroupID) == 'undefined') {var _iGroupID = null;}
if (typeof(_sContent) == 'undefined') {var _sContent = null;}
if (typeof(_sOnDrop) == 'undefined') {var _sOnDrop = null;}
if (typeof(_axData) == 'undefined') {var _axData = null;}
if (typeof(_iMaxDragElements) == 'undefined') {var _iMaxDragElements = null;}
if (typeof(_sCssStyle) == 'undefined') {var _sCssStyle = null;}
if (typeof(_sCssClass) == 'undefined') {var _sCssClass = null;}
_sDropAreaID = this.getRealParameter({'oParameters': _sContainerID, 'sName': 'sDropAreaID', 'xParameter': _sDropAreaID});
_sSizeX = this.getRealParameter({'oParameters': _sContainerID, 'sName': 'sSizeX', 'xParameter': _sSizeX});
_sSizeY = this.getRealParameter({'oParameters': _sContainerID, 'sName': 'sSizeY', 'xParameter': _sSizeY});
_iGridX = this.getRealParameter({'oParameters': _sContainerID, 'sName': 'iGridX', 'xParameter': _iGridX});
_iGridY = this.getRealParameter({'oParameters': _sContainerID, 'sName': 'iGridY', 'xParameter': _iGridY});
_iDropAreaType = this.getRealParameter({'oParameters': _sContainerID, 'sName': 'iDropAreaType', 'xParameter': _iDropAreaType});
_iGroupID = this.getRealParameter({'oParameters': _sContainerID, 'sName': 'iGroupID', 'xParameter': _iGroupID});
_sContent = this.getRealParameter({'oParameters': _sContainerID, 'sName': 'sContent', 'xParameter': _sContent});
_sOnDrop = this.getRealParameter({'oParameters': _sContainerID, 'sName': 'sOnDrop', 'xParameter': _sOnDrop});
_axData = this.getRealParameter({'oParameters': _sContainerID, 'sName': 'axData', 'xParameter': _axData});
_iMaxDragElements = this.getRealParameter({'oParameters': _sContainerID, 'sName': 'iMaxDragElements', 'xParameter': _iMaxDragElements});
_sCssStyle = this.getRealParameter({'oParameters': _sContainerID, 'sName': 'sCssStyle', 'xParameter': _sCssStyle});
_sCssClass = this.getRealParameter({'oParameters': _sContainerID, 'sName': 'sCssClass', 'xParameter': _sCssClass});
_sContainerID = this.getRealParameter({'oParameters': _sContainerID, 'sName': 'sContainerID', 'xParameter': _sContainerID});
var _sHtml = this.build(
{
'sDropAreaID': _sDropAreaID,
'sSizeX': _sSizeX, 'sSizeY': _sSizeY,
'iGridX': _iGridX, 'iGridY': _iGridY,
'iDropAreaType': _iDropAreaType,
'iGroupID': _iGroupID,
'sContent': _sContent,
'sOnDrop': _sOnDrop,
'axData': _axData,
'iMaxDragElements': _iMaxDragElements,
'sCssStyle': _sCssStyle, 'sCssClass': _sCssClass
}
);
if (_sContainerID != null)
{
var _oContainer = this.oDocument.getElementById(_sContainerID);
if (_oContainer) {_oContainer.innerHTML += _sHtml;}
}
}
/* @end method */
/*
@start method
@return sDropAreaHtml [type]string[/type]
[en]...[/en]
@param sDropAreaID [type]string[/type]
[en]...[/en]
@param sSizeX [type]string[/type]
[en]...[/en]
@param sSizeY [type]string[/type]
[en]...[/en]
@param iGridX [type]int[/type]
[en]...[/en]
@param iGridY [type]int[/type]
[en]...[/en]
@param iDropAreaType [type]int[/type]
[en]...[/en]
@param iGroupID [type]int[/type]
[en]...[/en]
@param sContent [type]string[/type]
[en]...[/en]
@param sOnDrop [type]string[/type]
[en]...[/en]
@param axData [type]mixed[][/type]
[en]...[/en]
@param iMaxDragElements [type]int[/type]
[en]...[/en]
@param sCssStyle [type]string[/type]
[en]...[/en]
@param sCssClass [type]string[/type]
[en]...[/en]
*/
this.build = function(
_sDropAreaID,
_sSizeX,
_sSizeY,
_iGridX,
_iGridY,
_iDropAreaType,
_iGroupID,
_sContent,
_sOnDrop,
_axData,
_iMaxDragElements,
_sCssStyle,
_sCssClass
)
{
if (typeof(_sSizeX) == 'undefined') {var _sSizeX = null;}
if (typeof(_sSizeY) == 'undefined') {var _sSizeY = null;}
if (typeof(_iGridX) == 'undefined') {var _iGridX = null;}
if (typeof(_iGridY) == 'undefined') {var _iGridY = null;}
if (typeof(_iDropAreaType) == 'undefined') {var _iDropAreaType = null;}
if (typeof(_iGroupID) == 'undefined') {var _iGroupID = null;}
if (typeof(_sContent) == 'undefined') {var _sContent = null;}
if (typeof(_sOnDrop) == 'undefined') {var _sOnDrop = null;}
if (typeof(_axData) == 'undefined') {var _axData = null;}
if (typeof(_iMaxDragElements) == 'undefined') {var _iMaxDragElements = null;}
if (typeof(_sCssStyle) == 'undefined') {var _sCssStyle = null;}
if (typeof(_sCssClass) == 'undefined') {var _sCssClass = null;}
_sSizeX = this.getRealParameter({'oParameters': _sDropAreaID, 'sName': 'sSizeX', 'xParameter': _sSizeX});
_sSizeY = this.getRealParameter({'oParameters': _sDropAreaID, 'sName': 'sSizeY', 'xParameter': _sSizeY});
_iGridX = this.getRealParameter({'oParameters': _sDropAreaID, 'sName': 'iGridX', 'xParameter': _iGridX});
_iGridY = this.getRealParameter({'oParameters': _sDropAreaID, 'sName': 'iGridY', 'xParameter': _iGridY});
_iDropAreaType = this.getRealParameter({'oParameters': _sDropAreaID, 'sName': 'iDropAreaType', 'xParameter': _iDropAreaType});
_iGroupID = this.getRealParameter({'oParameters': _sDropAreaID, 'sName': 'iGroupID', 'xParameter': _iGroupID});
_sContent = this.getRealParameter({'oParameters': _sDropAreaID, 'sName': 'sContent', 'xParameter': _sContent});
_sOnDrop = this.getRealParameter({'oParameters': _sDropAreaID, 'sName': 'sOnDrop', 'xParameter': _sOnDrop});
_axData = this.getRealParameter({'oParameters': _sDropAreaID, 'sName': 'axData', 'xParameter': _axData});
_iMaxDragElements = this.getRealParameter({'oParameters': _sDropAreaID, 'sName': 'iMaxDragElements', 'xParameter': _iMaxDragElements});
_sCssStyle = this.getRealParameter({'oParameters': _sDropAreaID, 'sName': 'sCssStyle', 'xParameter': _sCssStyle});
_sCssClass = this.getRealParameter({'oParameters': _sDropAreaID, 'sName': 'sCssClass', 'xParameter': _sCssClass});
_sDropAreaID = this.getRealParameter({'oParameters': _sDropAreaID, 'sName': 'sDropAreaID', 'xParameter': _sDropAreaID});
if (_iGridX == null) {_iGridX = this.iDefaultGridX;}
if (_iGridY == null) {_iGridY = this.iDefaultGridY;}
if (_iGroupID == null) {_iGroupID = this.sDefaultGroupID;}
if (_iDropAreaType == null) {_iDropAreaType = this.iDefaultType;}
if (_iMaxDragElements == null) {_iMaxDragElements = this.iDefaultMaxElements;}
if (_sCssStyle == null) {_sCssStyle = this.sDefaultCssStyle;}
if (_sCssClass == null) {_sCssClass = this.sDefaultCssClass;}
var _sHtml = '';
/*
_sHtml += '<div id="'+_sDropAreaID+'" style="position:relative; width:'+_sSizeX+'; height:'+_sSizeY+'; overflow:hidden; top:0px; left:0px; ';
if (this.isDebugMode(PG_DEBUG_HIGH)) {_sHtml += 'border:solid 1px #ff0000; ';}
if ((_sCssStyle != null) && (_sCssStyle != '')) {_sHtml += _sCssStyle+' ';}
_sHtml += '" ';
if ((_sCssClass != null) && (_sCssClass != '')) {_sHtml += 'class="'+_sCssClass+'" ';}
_sHtml += '>';
if (_sContent != null) {_sHtml += _sContent;}
_sHtml += '</div>';
*/
if (this.isDebugMode(PG_DEBUG_HIGH)) {_sCssStyle += ' border:solid 1px red;';}
_sHtml += oPGDivs.build(
{
'sDivID': _sDropAreaID,
'sContent': _sContent,
'xSizeX': _sSizeX,
'xSizeY': _sSizeY,
'sOverflow': 'hidden',
'xPosX': '0px',
'xPosY': '0px',
'sPosition': 'relative',
'sCssClass': _sCssClass,
'sCssStyle': _sCssStyle,
'bReturnHtml': true
}
);
oPGDragAndDrop.registerDropArea(
{
'sDropAreaID': _sDropAreaID,
'iGridX': _iGridX, 'iGridY': _iGridY,
'iDropAreaType': _iDropAreaType,
'iGroupID': _iGroupID,
'sOnDrop': _sOnDrop,
'axData': _axData,
'iMaxDragElements': _iMaxDragElements
}
);
return _sHtml;
}
/* @end method */
/*
@start method
@param sDropAreaID [needed][type]string[/type]
[en]...[/en]
@param sContent [needed][type]string[/type]
[en]...[/en]
*/
this.addContent = function(_sDropAreaID, _sContent)
{
if (typeof(_sContent) == 'undefined') {var _sContent = null;}
_sContent = this.getRealParameter({'oParameters': _sDropAreaID, 'sName': 'sContent', 'xParameter': _sContent});
_sDropAreaID = this.getRealParameter({'oParameters': _sDropAreaID, 'sName': 'sDropAreaID', 'xParameter': _sDropAreaID});
var _oDropArea = this.oDocument.getElementById(_sDropAreaID);
if (_oDropArea) {_oDropArea.innerHTML += _sContent;}
}
/* @end method */
/*
@start method
@param sDropAreaID [needed][type]string[/type]
[en]...[/en]
@param sContent [needed][type]string[/type]
[en]...[/en]
*/
this.setContent = function(_sDropAreaID, _sContent)
{
if (typeof(_sContent) == 'undefined') {var _sContent = null;}
_sContent = this.getRealParameter({'oParameters': _sDropAreaID, 'sName': 'sContent', 'xParameter': _sContent});
_sDropAreaID = this.getRealParameter({'oParameters': _sDropAreaID, 'sName': 'sDropAreaID', 'xParameter': _sDropAreaID});
var _oDropArea = this.oDocument.getElementById(_sDropAreaID);
if (_oDropArea) {_oDropArea.innerHTML = _sContent;}
}
/* @end method */
}
/* @end class */
classPG_DropArea.prototype = new classPG_ClassBasics();
var oPGDropArea = new classPG_DropArea();
|
'use strict';
angular.module('tutorialize')
.component('tutorial', {
templateUrl: '/components/tutorial/tutorial.html',
controller: Tutorial,
bindings: {
tutorial: '<',
onTutorialClick: '=',
index: '<',
focusedTuto: '@'
}
})
function Tutorial() {
// Controller
} |
import { combineReducers } from 'redux'
import dashboard from './dashboard'
import database from './database'
const rootReducer = combineReducers({ dashboard, database })
export default rootReducer
|
import { List } from 'react-content-loader';
const ListLoader = () => (
<List
width={850}
height={130}
animaye={true}
preserveAspectRatio={'meet'}
style={{ width: '100%', height: '220px' }}
/>
);
export default ListLoader;
|
import React from 'react';
import Wrapper from './Wrapper'
import TidbitTitle from './TidbitTitle'
export default class FeatureTidbit extends React.Component {
static propTypes = {
feature: React.PropTypes.object
};
render() {
return (
<Wrapper>
<TidbitTitle>{this.props.feature.title}</TidbitTitle>
</Wrapper>
);
}
}
|
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var passportLocalMongoose = require('passport-local-mongoose');
var portfolioSchema = new Schema({
referenceContact: {
type: String
},
description: {
type: String,
required: true
},
duration : {
type: Number,
required: true
},
reference: {
type: String
},
referenceContact: {
type: String
},
address: {
type: String
},
photos: [{
type: String
}]
}, {
timestamps: true
});
var User = new Schema({
username: String,
password: String,
dateofbirth: {
type: Date
},
firstname: {
type: String,
default: ''
},
nationality : {
type: String,
default: ''
},
lastname: {
type: String,
default: ''
},
occupation: {
type: String,
default: ''
},
image: {
type: String
},
applications: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Opportunity'
}],
admin: {
type: Boolean,
default: false
},
portifolio: [portfolioSchema],
interviewRequests: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Interview'
},
projectsGranted: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Opportunity'
}]
});
User.methods.getName = function() {
return (this.firstname + ' ' + this.lastname);
};
User.plugin(passportLocalMongoose);
module.exports = mongoose.model('User', User); |
export {_register_} from './RegisterStore';
|
/**
* Copyright (c) Benjamin Ansbach - all rights reserved.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
const AbstractInt = require('./AbstractInt');
const Endian = require('./../../Endian');
const BC = require('./../../BC');
/**
* Fields type for an 8Bit int value.
*/
class Int8 extends AbstractInt {
/**
* Constructor.
*
* @param {String} id
* @param {Boolean} unsigned
*/
constructor(id, unsigned) {
super(id || 'int8', unsigned, Endian.LITTLE_ENDIAN);
this.description('1byte 8bit int value');
}
/**
* @inheritDoc AbstractType#encodedSize
*/
get encodedSize() {
return 1;
}
/**
* Reads the int8 value from the given bytes.
*
* @param {BC|Buffer|Uint8Array|String} bc
* @param {Object} options
* @param {*} all
* @returns {Number|*}
*/
decodeFromBytes(bc, options = {}, all = null) {
return BC.from(bc).readInt8(0, this.unsigned);
}
/**
* Encodes the given int8 value.
*
* @param {Number} value
* @returns {BC}
*/
encodeToBytes(value) {
return BC.fromInt8(value, this.unsigned);
}
}
module.exports = Int8;
|
'use strict'
angular.module('main')
.controller('UsersDeleteController', ['$scope', '$location', '$routeParams', 'User',
function ($scope, $location, $routeParams, User) {
$scope.user = User.get({id: $routeParams.id});
$scope.delete = function () {
$scope.user.$delete().then(function () {
$location.path('/users');
}, function (resp) {
$scope.alert.add('Erro!', 'Ocorreu uma falha ao tentar realizar o exclus�o.');
});
};
}]); |
import React, { useState, useEffect } from "react";
import "antd/dist/antd.css";
import { Form, Input, Button, Checkbox, message } from "antd";
import { Redirect } from "react-router-dom";
import { useDispatch, useSelector } from "react-redux";
import { userActions } from "../actions/userActions";
const layout = {
labelCol: {
span: 8,
},
wrapperCol: {
span: 16,
},
};
const Auth = () => {
const [formData, setFormData] = React.useState({
username: "",
password: "",
});
const { username, password } = formData;
const [isAuthenticated, setIsAuthenticated] = useState(false);
const users = useSelector((state) => state.userReducer);
const dispatch = useDispatch();
useEffect(() => {
if (users.isAuthenticated === true) setIsAuthenticated(true);
}, [users.isAuthenticated]);
const handleOnChange = (e) => {
setFormData({ ...formData, [e.target.name]: e.target.value });
};
useEffect(() => {
if (users && users.error && typeof users.error === "string") {
message.error(users.error);
}
}, [users]);
const handleOnSubmit = () => {
dispatch(userActions.login(formData));
};
const handleOnSubmitFailed = (errorInfo) => {
message.error("Please fill out all required field!", errorInfo);
};
if (isAuthenticated === true) {
return <Redirect to="/"></Redirect>;
} else {
return (
<div className="login">
<div className="login-form">
<Form
{...layout}
name="basic"
initialValues={{
remember: true,
}}
onFinish={handleOnSubmit}
onFinishFailed={handleOnSubmitFailed}
>
<h2 className="text-center">Login</h2>
<Form.Item
name="username"
rules={[
{
required: true,
message: "Please input your username!",
},
]}
>
<Input
placeholder="username"
className="input"
name="username"
id="username"
value={username}
onChange={(e) => handleOnChange(e)}
/>
</Form.Item>
<Form.Item
name="password"
rules={[
{
required: true,
message: "Please input your password!",
},
]}
>
<Input.Password
placeholder="password"
className="input"
name="password"
id="password"
onChange={(e) => handleOnChange(e)}
/>
</Form.Item>
<Form.Item name="remember" valuePropName="checked">
<Checkbox>Remember me</Checkbox>
</Form.Item>
<Form.Item>
<Button type="primary" htmlType="submit" className="input">
Login
</Button>
</Form.Item>
</Form>
</div>
</div>
);
}
};
export default Auth;
|
import React, { useState, useEffect } from "react";
import Axios from "axios";
export default function AddingAxios() {
var [employeeList, setEmployeeList] = useState([]);
var [counter, setCounter] = useState(0);
useEffect(() => {
getEmployeeList();
}, [])
useEffect(() => {
debugger;
})
useEffect(() => {
debugger;
}, [counter])
useEffect(() => {
debugger;
}, [counter, employeeList])
function addEmployee() {
var newEmployee = {
"id":"900",
"createdAt":"2018-12-03T00:28:30.136Z",
"name":"Maynard Hilll",
"avatar":"https://s3.amazonaws.com/uifaces/faces/twitter/danro/128.jpg"
}
var newArray = [newEmployee, ...JSON.parse(JSON.stringify(employeeList))];
setEmployeeList(newArray);
}
function getEmployeeList() {
Axios.get("https://5c055de56b84ee00137d25a0.mockapi.io/api/v1/employees").then((response) => {
setEmployeeList(response.data);
})
}
function addCounter() {
setCounter(counter + 1)
}
debugger;
return (
<div>
<h1>Current Counter is: {counter}</h1>
<input type="button" onClick={addCounter} value="Add To the Counter" /><hr/><br/>
<input type="button" onClick={addEmployee} value="Add Employee" />
<h1>Employee List is Givebn Below....</h1>
{employeeList.map((emp) => {
return (
<div>
<h1>Employee Name: {emp.name}</h1>
<h1>Employee Id: {emp.id}</h1>
<h1>Employee CreatedAt: {emp.createdAt}</h1>
<hr/>
</div>
)
})}
<input type="button" value="Get Employees" onClick={getEmployeeList} />
</div>
)
} |
import ExpoPixi, { PIXI } from 'expo-pixi';
export default async context => {
// Custom Expo loading spine
const dragon = await ExpoPixi.spineAsync({
json: require('../../assets/pixi/dragon.json'),
atlas: require('../../assets/pixi/dragon.atlas'),
assetProvider: {
'dragon.png': require('../../assets/pixi/dragon.png'),
'dragon2.png': require('../../assets/pixi/dragon2.png'),
},
});
const app = ExpoPixi.application({
context,
});
app.stop();
dragon.skeleton.setToSetupPose();
dragon.update(0);
dragon.autoUpdate = false;
// create a container for the spine animation and add the animation to it
var dragonCage = new PIXI.Container();
dragonCage.addChild(dragon);
// measure the spine animation and position it inside its container to align it to the origin
var localRect = dragon.getLocalBounds();
dragon.position.set(-localRect.x, -localRect.y);
// now we can scale, position and rotate the container as any other display object
var scale = Math.min(
app.renderer.width * 0.7 / dragonCage.width,
app.renderer.height * 0.7 / dragonCage.height
);
dragonCage.scale.set(scale, scale);
dragonCage.position.set(
(app.renderer.width - dragonCage.width) * 0.5,
(app.renderer.height - dragonCage.height) * 0.5
);
// add the container to the stage
app.stage.addChild(dragonCage);
// once position and scaled, set the animation to play
dragon.state.setAnimation(0, 'flying', true);
app.start();
app.ticker.add(function() {
// update the spine animation, only needed if dragon.autoupdate is set to false
dragon.update(0.01666666666667); // HARDCODED FRAMERATE!
});
};
|
'use strict';
const colors = require('colors');
const types = {
'write': {
'tag': 'info',
'color': 'green'
},
'warn': {
'tag': 'warning',
'color': 'yellow'
},
'error': {
'tag': 'error',
'color': 'red'
}
}
const getDate = () => {
const d = new Date();
const boundGetInfo = getInfo.bind(d);
return `${Number(boundGetInfo('Month')) + 1}/${boundGetInfo('Date')}/${boundGetInfo('FullYear')} ${boundGetInfo('Hours')}:${boundGetInfo('Minutes')}:${boundGetInfo('Seconds')}`;
}
const createLevel = i => {
module.exports[i] = data => {
const obj = types[i];
const date = getDate();
console.log(`[${obj.tag.toUpperCase()}][${date}] > ${data}`[obj.color]);
}
}
const getInfo = function(type) {
return this['get' + type]() < 10 ? '0' + this['get' + type]() : this['get' + type]();
}
for (let i in types)
createLevel(i)
|
function deleteEntry(name, id){
if(window.confirm("Are you sure you want to delete this entry?")){
var form = document.createElement("form");
form.setAttribute("method", "post");
form.setAttribute("action", "");
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", name);
hiddenField.setAttribute("value", id);
form.appendChild(hiddenField);
document.body.appendChild(form);
form.submit();
}
}
|
// import Mock from 'mockjs'
// import { param2Obj } from '@/utils'
const xxList = [
{
'xxid': 1,
// 学校类型,幼儿园,小学,初中,高中
'xxlx': 3,
'xxmc': '莲都区碧湖中学',
'njlist': [
{
'njid': 1,
// 编号和名称从字典获取 小学1-6,初中7-9
'njbh': '7',
'njmc': '初一',
'bjlist': [
{
'bjid': 1,
'bjmc': '初中一年级(01)班',
'bjbh': '1'
},
{
'bjid': 2,
'bjmc': '初中一年级(02)班',
'bjbh': '2'
}
]
},
{
'njid': 2,
// 编号和名称从字典获取 小学1-6,初中7-9
'njbh': '8',
'njmc': '初二',
'bjlist': [
{
'bjid': 3,
'bjmc': '初中一年级(01)班',
'bjbh': '1'
},
{
'bjid': 4,
'bjmc': '初中一年级(02)班',
'bjbh': '2'
}
]
}
]
},
{
'xxid': 2,
'xxlx': 3,
'xxmc': '莲都区花园中学',
'njlist': [
{
'njid': 3,
// 编号和名称从字典获取 小学1-6,初中7-9
'njbh': '7',
'njmc': '初一',
'bjlist': [
{
'bjid': 5,
'bjmc': '初中一年级(01)班',
'bjbh': '1'
},
{
'bjid': 6,
'bjmc': '初中一年级(02)班',
'bjbh': '2'
}
]
},
{
'njid': 4,
// 编号和名称从字典获取 小学1-6,初中7-9
'njbh': '8',
'njmc': '初二',
'bjlist': [
{
'bjid': 7,
'bjmc': '初中一年级(01)班',
'bjbh': '1'
},
{
'bjid': 8,
'bjmc': '初中一年级(02)班',
'bjbh': '2'
}
]
}
]
},
{
'xxid': 3,
'xxlx': 2,
'xxmc': '莲都区实验小学',
'njlist': [
{
'njid': 5,
// 编号和名称从字典获取 小学1-6,初中7-9
'njbh': '1',
'njmc': '一年级',
'bjlist': [
{
'bjid': 9,
'bjmc': '小学一年级(01)班',
'bjbh': '1'
},
{
'bjid': 10,
'bjmc': '小学一年级(02)班',
'bjbh': '2'
}
]
},
{
'njid': 6,
// 编号和名称从字典获取 小学1-6,初中7-9
'njbh': '2',
'njmc': '二年级',
'bjlist': [
{
'bjid': 11,
'bjmc': '小学一年级(01)班',
'bjbh': '1'
},
{
'bjid': 12,
'bjmc': '小学一年级(02)班',
'bjbh': '2'
}
]
}
]
}
]
export default [
{
url: '/xxglapi/allxxnjbytree',
type: 'get',
response: config => {
// const { ty } = param2Obj(config.url)
const mockList = []
let tempObj = {}
let tempObj2 = {}
let tempObj3 = {}
xxList.forEach((key, index) => {
tempObj = {}
tempObj.xxid = key.xxid
tempObj.label = key.xxmc
tempObj.xxlx = key.xxlx
tempObj.children = []
key.njlist.forEach((key2, index2) => {
tempObj2 = {}
tempObj2.xxid = key.xxid
tempObj2.label = key2.njmc
tempObj2.njbh = key2.njbh
tempObj2.children = []
key2.bjlist.forEach((key3, index3) => {
tempObj3 = {}
tempObj3.xxid = key.xxid
tempObj3.njbh = key2.njbh
tempObj3.bjid = key3.bjid
tempObj3.label = key3.bjmc
tempObj3.bjbh = key3.bjbh
tempObj2.children.push(tempObj3)
})
tempObj.children.push(tempObj2)
})
mockList.push(tempObj)
})
return {
code: 20000,
items: mockList
}
}
},
{
url: '/xxglapi/xxnjlist',
type: 'get',
response: config => {
// const { ty } = param2Obj(config.url)
const mockList = []
let tempObj = {}
let tempObj2 = {}
let tempObj3 = {}
xxList.forEach((key, index) => {
tempObj = {}
tempObj.xxid = key.xxid
tempObj.label = key.xxmc
tempObj.xxlx = key.xxlx
tempObj.children = []
key.njlist.forEach((key2, index2) => {
tempObj2 = {}
tempObj2.njid = key2.njid
tempObj2.label = key2.njmc
tempObj2.njbh = key2.njbh
tempObj2.children = []
key2.bjlist.forEach((key3, index3) => {
tempObj3 = {}
tempObj3.bjid = key3.bjid
tempObj3.label = key3.bjmc
tempObj3.bjbh = key3.bjbh
tempObj2.children.push(tempObj3)
})
tempObj.children.push(tempObj2)
})
mockList.push(tempObj)
})
return {
code: 20000,
items: mockList
}
}
}
]
|
/*
* @Description: In User Settings Edit
* @Author: mengjl
* @Date: 2019-07-17 16:12:48
* @LastEditors: mengjl
* @LastEditTime: 2019-07-30 17:01:09
*/
cc.Class({
name : 'ResMgr',
properties: {
m_loadResQueue : new Array(), // 要加载的文件列表
m_loadAmount : 0,
m_completeFunc : null,
m_progressFunc : null,
},
init()
{
setInterval(() => {
this.gc();
}, 10000);
},
clearQueue()
{
this.m_loadResQueue.length = 0;
},
loadRes(completeFunc, progressFunc)
{
// this.printResCount();
this.m_completeFunc = completeFunc;
this.m_progressFunc = progressFunc;
if (this.m_loadResQueue.length <= 0) {
if (this.m_progressFunc) {
this.m_progressFunc(1);
}
if (this.m_completeFunc) {
this.m_completeFunc();
}
return;
}
this.m_loadAmount = 0;
this._load();
},
addRes(url, type = cc.Asset)
{
if (url == undefined || url == null ) {
console.error('load resource url is null')
return;
}
this.m_loadResQueue.push({url : url, type : type, });
},
getRes(url, type = cc.Asset)
{
return cc.loader.getRes(url, type);
},
getConfig(filename)
{
var res = this.getRes(filename);
if (res) {
return res.json;
}
return null;
},
getSkelData(filename)
{
return this.getRes(filename, sp.SkeletonData);
},
getAtlas(filename)
{
return this.getRes(filename, cc.SpriteAtlas);
},
getAtlasFrame(atlasName, frameName)
{
var atlas = this.getAtlas(atlasName);
if (atlas) {
return atlas.getSpriteFrame(frameName);
}
return null;
},
getFont(filename)
{
return this.getRes(filename, cc.Font);
},
//获取图集资源
getSpriteByAtlas(atlas, name)
{
return this.getAtlasFrame(atlas, name);
},
_checkComplete()
{
if (this.m_progressFunc) {
this.m_progressFunc(this.m_loadAmount / this.m_loadResQueue.length);
}
if (this.m_loadAmount >= this.m_loadResQueue.length) {
if (this.m_completeFunc) {
this.m_completeFunc();
}
// this.printResCount();
}
else
{
this._load();
}
},
gc()
{
// console.log('gc');
cc.sys.garbageCollect();
},
removeAssetArr(urlarr)
{
if (Array.isArray(urlarr)) {
for (let index = 0; index < urlarr.length; index++) {
const url = urlarr[index];
this.removeAsset(url);
}
}
else if (urlarr)
{
for (const url in urlarr) {
this.removeAsset(url, urlarr[url]);
}
}
},
removeSpriteAtlasArr(urlarr)
{
if (Array.isArray(urlarr)) {
for (let index = 0; index < urlarr.length; index++) {
const url = urlarr[index];
this.removeAsset(url, cc.SpriteAtlas);
}
}
else if (urlarr)
{
for (const url in urlarr) {
if (urlarr[url] == cc.SpriteAtlas) {
this.removeAsset(url, cc.SpriteAtlas);
}
}
}
},
removeAsset(url, type = cc.Asset)
{
this._removeItem(url);
var item = cc.loader.getRes(url);
if (item) {
cc.loader.release(item.url);
}
cc.loader.releaseRes(url, type);
},
_removeItem(url)
{
var deps = cc.loader.getDependsRecursively(url);
// console.log(deps);
var caches = cc.loader['_cache'];
for (const id in caches) {
const item = caches[id];
if (item == null) {
continue;
}
if (item.dependKeys == null) {
continue;
}
for (let index = 0; index < item.dependKeys.length; index++) {
const dependKey = item.dependKeys[index];
// console.log(deps.indexOf(dependKey))
if (deps.indexOf(dependKey) != -1) {
cc.loader.release(item.url);
break;
}
}
}
},
printResCount()
{
console.log('getResCount', cc.loader.getResCount());
// console.log(cc.loader._cache);
},
_load()
{
const resInfo = this.m_loadResQueue[this.m_loadAmount];
var url = resInfo.url;
var type = resInfo.type;
// console.log(cc.loader.getRes(url, type))
var res = cc.loader.getRes(url, type);
if (res) {
this.m_loadAmount++;
this._checkComplete();
return;
}
cc.loader.loadRes(url, type, (err, obj) => {
if(err){
console.error("load " + url + "--->", err);
}
else{
this.m_loadAmount++;
this._checkComplete();
}
});
},
haveQuote(url)
{
var deps = cc.loader.getDependsRecursively(url);
// console.log(deps);
var caches = cc.loader['_cache'];
for (const id in caches) {
const item = caches[id];
if (item == null) {
continue;
}
if (item.dependKeys == null) {
continue;
}
for (let index = 0; index < item.dependKeys.length; index++) {
const dependKey = item.dependKeys[index];
// console.log(deps.indexOf(dependKey))
if (deps.indexOf(dependKey) != -1) {
return true;
}
}
}
return false;
},
findAllRes()
{
var results = [];
var caches = cc.loader['_cache'];
for (const id in caches) {
const item = caches[id];
if (item) {
if (item.type == 'png' || item.type == 'webp' || item.type == 'jpg') {
results.push(item);
}
}
}
if (this.m_lastfind == null) {
this.m_lastfind = results;
}
else
{
var diff = [];
for (let index = 0; index < results.length; index++) {
const element = results[index];
if (this.m_lastfind.indexOf(element) == -1) {
diff.push(element)
}
}
this.m_lastfind = results;
console.error(diff);
}
return results;
},
findUnsedRes()
{
var results = [];
var caches = cc.loader['_cache'];
for (const id in caches) {
const item = caches[id];
if (item == null) {
continue;
}
// console.log(item)
if (this.haveQuote(item.url) == false) {
if (item.type == 'png' || item.type == 'webp' || item.type == 'jpg') {
results.push(item.url);
}
// console.log(item)
}
}
return results;
},
}); |
const ResponseError = require('../../../Enterprise_business_rules/Manage_error/ResponseError');
const { TYPES_ERROR } = require('../../../Enterprise_business_rules/Manage_error/codeError');
const { ROLES } = require('../../../Enterprise_business_rules/constant');
module.exports = async (examData, repositories) => {
const { idAdmin, idExam } = examData;
const { examRepositoryMySQL, userRepositoryMySQL } = repositories;
// Se comprueba que se reciben el idAdmin y el idUser
if (!idAdmin || !idExam) {
throw new ResponseError(TYPES_ERROR.FATAL, 'Los IDs son necesarios para realizar la consulta', 'id_empty');
}
// Se comprueba que los ids recibidos son números
if (Number.isNaN(Number(idAdmin)) || Number.isNaN(Number(idExam))) {
throw new ResponseError(TYPES_ERROR.FATAL, 'Los ids deben ser números', 'id_format_error');
}
// Se comprueba que el usuario con idAdmin existe
const existAdmin = await userRepositoryMySQL.getUser(idAdmin);
if (!existAdmin) {
throw new ResponseError(TYPES_ERROR.FATAL, 'El administrador no existe', 'user_not_exist');
}
// Se comprueba que el idAdmin tiene rol de administrador de exámenes
const isRoleAdmin = await userRepositoryMySQL.getRole({ userRoleData: { UserId: idAdmin, role: ROLES.ADMIN_EXAM } });
if (!isRoleAdmin) {
throw new ResponseError(TYPES_ERROR.ERROR, 'El usuario actual necesita rol de Administrador de exámenes para solicitar información de un examen', 'role_not_assigned');
}
const exam = await examRepositoryMySQL.getExam(idExam);
if (!exam) {
throw new ResponseError(TYPES_ERROR.ERROR, 'El examen no existe', 'exam_not_exist');
}
return exam;
};
|
/* eslint-disable no-useless-escape */
import validator from 'validator';
import owasp from 'owasp-password-strength-test';
import joi from 'joi';
import { parsePhoneNumberFromString } from 'libphonenumber-js';
import { errors as errorList } from './constants/messages';
// TODO: find a better place for maxBTCPerTrade
const maxBTCPerTrade = 2;
export const validateOrder = (order, orderPair) => {
const schema = joi.object().keys({
pairId: joi
.number()
.integer()
.min(1)
.required(),
price: joi
.number()
.min(Number((Number(orderPair.lastPrice) * 0.8).toFixed(6)))
.max(Number((Number(orderPair.lastPrice) * 1.2).toFixed(6)))
.required()
.precision(Number(orderPair.priceDecimals))
.strict(),
amount: joi
.number()
.greater(0)
.max(Number((maxBTCPerTrade / Number(orderPair.lastPrice)).toFixed(6)))
.required()
.min(Number(orderPair.minTradeAmount))
.precision(Number(orderPair.tradeAmountDecimals))
.strict(),
sideId: joi.number().valid(1, 2),
typeId: joi.number().valid(1, 2),
});
const result1 = joi.validate(order, schema, { presence: 'required' });
const result2 = joi.validate(
{ orderValue: order.price * order.amount },
joi.object().keys({
orderValue: joi.number().min(Number(orderPair.minOrderValue)),
}),
{ presence: 'required' },
);
const result = result1.error ? result1 : result2;
return result.error ? result.error.details[0].message : '';
};
export const validateTransaction = (transaction, token) => {
const schema = joi.object().keys({
walletId: joi
.number()
.integer()
.min(1)
.required(),
destination: joi
.string()
.token()
.max(256)
.required(),
amount: joi
.number()
.min(Number(token.minimumWithdrawalAmount))
.max(Number(token.tokenCap))
.precision(Number(token.decimalPrecision))
.greater(0)
.required(),
tokenId: joi
.number()
.integer()
.min(1),
typeId: joi.number().valid(1, 2),
});
const result = joi.validate(transaction, schema, { presence: 'required' });
return result.error ? result.error.details[0].message : '';
};
export const validateArrayOfEmails = array => {
const schema = joi.array().items(joi.string().email());
const result = joi.validate(array, schema, { presence: 'required' });
return result.error ? result.error.details[0].message : '';
};
export const validatePhoneNumber = phoneNumber => {
const number = parsePhoneNumberFromString(phoneNumber);
let error = '';
if (number) {
if (!number.isValid()) {
error = errorList.PHONE_NUMBER_IS_INCORRECT;
}
} else {
error = errorList.PHONE_NUMBER_NOT_PROVIDED;
}
return error;
};
export const validateName = name => {
const schema = joi
.string()
.max(128)
.min(1);
const result = joi.validate(name, schema, { presence: 'required' });
return result.error ? result.error.details[0].message : '';
};
export const validateId = id => {
const schema = joi
.number()
.integer()
.min(1);
const result = joi.validate(id, schema, { presence: 'required' });
return result.error ? result.error.details[0].message : '';
};
export const validateToken = token => {
let error = '';
if (token.length === 0) {
error = errorList.TOKEN_FIELD_IS_EMPTY;
} else if (!validator.isLength(token, { min: 0, max: 256 })) {
error = errorList.TOKEN_IS_TOO_LONG;
}
return error;
};
export const validateFirstName = name => {
let error = '';
if (name.length === 0) {
error = errorList.FIRST_NAME_FIELD_IS_EMPTY;
} else if (!validator.isLength(name, { min: 0, max: 128 })) {
error = errorList.NAME_IS_TOO_LONG;
}
return error;
};
export const validateLastName = name => {
let error = '';
if (name.length === 0) {
error = errorList.LAST_NAME_FIELD_IS_EMPTY;
} else if (!validator.isLength(name, { min: 0, max: 128 })) {
error = errorList.NAME_IS_TOO_LONG;
}
return error;
};
export const validateEmail = email => {
let error = '';
if (email.length === 0) {
error = errorList.EMAIL_FIELD_IS_EMPTY;
} else if (!validator.isEmail(email)) {
error = errorList.EMAIL_FORMAT_IS_INCORRECT;
} else if (!validator.isLength(email, { min: 0, max: 128 })) {
error = errorList.EMAIL_IS_TOO_LONG;
}
return error;
};
export const validatePassword = (password, isRegister) => {
let error = '';
const strength = owasp.test(password);
if (password.length === 0) {
error = errorList.PASSWORD_FIELD_IS_EMPTY;
} else if (password.length === 0) {
error = errorList.PASSWORD_FIELD_IS_EMPTY;
} else if (isRegister && strength.errors.length > 0) {
error = strength.errors[0];
} else if (!validator.isLength(password, { min: 0, max: 128 })) {
error = errorList.PASSWORD_IS_TOO_LONG;
}
return error;
};
export const validatePasswordConfirm = (password, passwordConfirm) => {
let error = '';
if (password !== passwordConfirm) {
error = errorList.PASSWORD_CONFIRMATION_FAILED;
}
return error;
};
export const validateAmount = amount => {
const schema = joi.number().min(0.000000001);
const result = joi.validate(amount, schema, { presence: 'required' });
return result.error ? result.error.details[0].message : '';
};
|
import React, { useEffect, useState } from 'react';
import MainGrid from '../components/MainGrid';
import Box from '../components/Box';
import { AlurakutMenu, AlurakutProfileSidebarMenuDefault, OrkutNostalgicIconSet } from '../lib/AlurakutCommons';
import { ProfileRelationsBoxWrapper } from '../components/ProfileRelations';
import BoxWrapper from '../components/BoxWrapper';
import nookies from 'nookies';
import jwt from 'jsonwebtoken';
function ProfileSidebar(props){
return (
<Box as="aside">
<img src={`https://github.com/${props.githubUser}.png`} style={{ borderRadius: '8px' }}/>
<hr />
<p className="boxLink">
<a className="" href={`https://github.com/${props.githubUser}`}>
@{props.githubUser}
</a>
</p>
<hr />
<AlurakutProfileSidebarMenuDefault />
</Box>
)
}
function ProfileRelationsBox(props){
return (
<ProfileRelationsBoxWrapper>
<h2 className="smallTitle">
{props.title} ({props.items?.length})
</h2>
<ul>
{props.items.slice(0, 6).map((item, index) => {
return (
<li key={index}>
<a>
<img src={item?.html_url+".png"} style={{ borderRadius: '8px' }}/>
<span>{item.login}</span>
</a>
</li>
)
})
}
</ul>
</ProfileRelationsBoxWrapper>
)
}
export default function Home(props) {
const usuarioAleatorio = props.githubUser;
const [seguidores, setSeguidores] = useState([]);
const pessoasFavoritas = [
{id: 1, name: 'juunegreiros', image: 'https://github.com/juunegreiros.png'},
{id: 2, name: 'omariosouto', image: 'https://github.com/omariosouto.png'},
{id: 3, name: 'peas', image: 'https://github.com/peas.png'},
{id: 4, name: 'rafaballerini', image: 'https://github.com/rafaballerini.png'},
{id: 5, name: 'marcobrunodev', image: 'https://github.com/marcobrunodev.png'},
{id: 6, name: 'felipefialho', image: 'https://github.com/felipefialho.png'}
];
/* const [comunidades, setComunidades] = React.useState([{
id: '12802378123789378912789789123896123',
name: 'Eu odeio acordar cedo',
image: 'https://alurakut.vercel.app/capa-comunidade-01.jpg'
}]); */
const [comunidades, setComunidades] = React.useState([]);
useEffect(function(){
fetch('https://api.github.com/users/peas/followers')
.then(function (respostaDoServidor) {
return respostaDoServidor.json();
})
.then(function(respostaDoServidor){
setSeguidores(respostaDoServidor)
})
console.log("process ", process);
//API GRAPH
fetch('https://graphql.datocms.com/', {
method: 'POST',
headers: {
'Authorization': '07b3c0ca056fe3269b196458de55b7',
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify({"query": `query {
allCommunities {
id
title
image
creatorSlug
}
}` })
})
.then(response => response.json())
.then((responseCompleta) => {
console.log("reresponseCompleta ", responseCompleta);
setComunidades(responseCompleta.data.allCommunities)
})
},[]);
return (
<>
<AlurakutMenu />
<MainGrid>
<div className="profileArea" style={{ gridArea: 'profileArea' }}>
<ProfileSidebar githubUser={usuarioAleatorio}/>
</div>
<div className="welcomeArea" style={{ gridArea: 'welcomeArea' }}>
<Box className="title">
<h1>Bem vindo (a)</h1>
<OrkutNostalgicIconSet />
</Box>
<Box>
<h2 className="subTitle">O que você deseja fazer?</h2>
<form onSubmit={function handleSubmit(event){
event.preventDefault();
const dadosForm = new FormData(event.target);
const comunidade = {
title: dadosForm.get('title'),
image: dadosForm.get('image'),
creatorSlug: usuarioAleatorio
}
fetch('/api/comunidades', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(comunidade)
})
.then(async (response) => {
const data = await response.json();
const comunidadeAtualizada = [...comunidades, data.registroCriado];
setComunidades(comunidadeAtualizada)
})
}}>
<div>
<input
placeholder="Qual vai ser o nome da sua comunidade?"
name="title"
aria-label="Qual vai ser o nome da sua comunidade?"
type="text"
/>
</div>
<div>
<input
placeholder="Coloque uma URL para usarmos de capa"
name="image"
aria-label="Coloque uma URL para usarmos de capa"
/>
</div>
<button>
Criar comunidade
</button>
</form>
</Box>
</div>
<div className="profileRelationsArea" style={{ gridArea: 'profileRelationsArea' }}>
<ProfileRelationsBox title="Seguidores" items={seguidores}/>
<BoxWrapper title="Meus amigos" item={pessoasFavoritas}/>
<BoxWrapper title="Minhas comunidades" item={comunidades}/>
</div>
</MainGrid>
</>
)
}
export async function getServerSideProps(context){
const cookies = nookies.get(context);
const token = cookies.USER_TOKEN;
const { githubUser } = jwt.decode(token);
const { isAuthenticated } = await fetch('https://alurakut.vercel.app/api/auth', {
headers: {
'Authorization': token,
},
})
.then((response) => response.json())
console.log("isAutenticated ", isAuthenticated);
if(!isAuthenticated) {
return {
redirect: {
destination: '/login',
permanent: false
}
}
}
return {
props: {
githubUser
}
}
} |
const db = require("./utils/db");
//Sử dụng Promise
// const promise = db.load("SELECT * FROM categories");
// promise
// .then((data) => {
// console.log(data);
// })
// .catch((error) => {
// console.log(error);
// })
// .finally(() => {
// console.log("done");
// });
//Sử dụng async await
const main = async () => {
const rows = await db.load("SELECT * FROM categories");
console.log(rows);
}
main();
|
import React from 'react';
import {connect} from "react-redux";
import {bindActionCreators} from "redux";
import * as basketActions from '../../Actions/BasketAC'
import {uniqBy} from "lodash";
import {BasketComponent, MenuGoods} from "./MenuGoods";
const mapStateToProps = ({basket}) => ({
totalPrice: basket.items.reduce((total,product)=> total + product.price, 0),
count: basket.items.length,
items: uniqBy(basket.items, n => n.id),
})
const mapDispatchToProps = (dispatch) => ({
...bindActionCreators(basketActions, dispatch)
})
export default connect(mapStateToProps, mapDispatchToProps)(MenuGoods); |
import { createTheme } from '@material-ui/core';
const lightTheme = createTheme({
palette: {
primary: {
light: '#b71c1c',
main: '#1b5e20',
dark: '#0d47a1',
contrastText: '#fff',
},
secondary: {
light: '#ef9a9a',
main: '#f44336',
dark: '#c62828',
},
action: {
disabledBackground: 'orange',
disabled: 'white',
},
},
});
export default lightTheme;
|
var React = require("react");
require("../css/<%= filename %>.scss");
var Application = React.createClass({
render: function() {
return (
<div>
<h1>Hello! Rakuten!</h1>
<p>Build front end with SPEED SPEED SPEED</p>
</div>);
}
});
React.render(<Application/>, document.getElementById('<%= filename %>_content'));
|
import { tag, WeElement } from 'omi'
@tag('input-list', true)
export class List extends WeElement {
css () {
return `
.input-list {
box-sizing: border-box;
width: 50%;
font-size: 130%;
border: 1px solid #ddd;
border-radius: 4px;
color: #777;
}
.input-list {
margin: 5px auto;
padding: 0;
text-align: left;
background: #fff;
list-style: none inside;
}
li {
padding: 3px 10px;
}
li:hover {
background: rgba(200, 200, 200, 0.3);
}`
}
itemClicked = event => {
this.props.onItemClick({ itemText: event.target.textContent })
}
render(props) {
return (
<ul className='input-list'>
{ props.text.map(item => <li key={item} onClick={this.itemClicked}>{item}</li>) }
</ul>
)
}
}
|
//05.Write a function that finds the youngest male person in a given array of people and prints his full name
//Use only array methods and no regular loops (for, while)
//Use Array#find
'use strict';
if (!Array.prototype.find) {
Array.prototype.find = function(predicate) {
if (this == null) {
throw new TypeError('Array.prototype.find called on null or undefined');
}
if (typeof predicate !== 'function') {
throw new TypeError('predicate must be a function');
}
var list = Object(this);
var length = list.length >>> 0;
var thisArg = arguments[1];
var value;
for (var i = 0; i < length; i++) {
value = list[i];
if (predicate.call(thisArg, value, i, list)) {
return value;
}
}
return undefined;
};
}
var people = createPeople();
getYoungestMalePerson(people);
function getYoungestMalePerson(people){
var males = people.filter(function(person){
return !person.gender;
}).sort(function(item, nextItem){
return item.age > nextItem.age;
});
var youngest = males.find(function(male){
return male;
});
console.log(youngest.firstName + ' ' + youngest.lastName + '\nAge ' + youngest.age);
}
function createPeople(){
var people = [];
people.push(makePerson('Pesho', 'Goshov', 25, false));
people.push(makePerson('Pesho', 'Mitkov', 11, false));
people.push(makePerson('Peshka', 'Asparuhov', 35, true));
people.push(makePerson('Pesho', 'Dimitrov', 42, false));
people.push(makePerson('Goshka', 'Peev', 15, true));
people.push(makePerson('Gosho', 'Grishov', 28, false));
people.push(makePerson('Stamat', 'Stamatov', 14, false));
people.push(makePerson('Nekva', 'Pichova', 55, true));
people.push(makePerson('Spas', 'Grigorov', 80, false));
people.push(makePerson('Grishata', 'Pichev', 75, false));
function makePerson(firstName, lastName, age, gender){
return {
firstName: firstName,
lastName: lastName,
age: age,
gender: gender
};
}
return people;
}
|
function apiCall(path, success_handler, failure_handler) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState === 4) {
// console.log(path + ": " + this.statusText);
if (this.status === 200) {
success_handler(JSON.parse(this.responseText), this.getResponseHeader("Last-Modified"));
} else {
failure_handler(path);
}
}
};
xhttp.open("GET", path, true);
xhttp.send();
}
function lostConnection(path, elementId) {
console.log("There was an error retrieving data from " + path);
if (elementId !== undefined) {
var currentValue = document.getElementById(elementId).textContent;
document.getElementById(elementId).textContent = currentValue + " (lost connection to: " + path + ")"
}
var td = document.getElementsByTagName("td");
for (var i = 0; i < td.length; i++) {
td[i].classList.remove('pulsing');
}
}
function fetchEtlId() {
apiCall("/api/etl-id", function (obj, ignored) {
document.getElementById("etl-id").textContent = obj.id
}, function (path) {
lostConnection(path)
});
}
function fetchEtlCommandLine() {
apiCall("/api/command-line", function (obj, ignored) {
document.getElementById("command-line").textContent = obj.args
}, function (path) {
lostConnection(path)
});
}
function fetchEtlIndices() {
apiCall("/api/indices", updateEtlIndices, function (path) {
lostConnection(path, "indices-table-last-modified")
})
}
function fetchEtlEvents() {
apiCall("/api/events", updateEtlEvents, function (path) {
lostConnection(path, "events-table-last-modified")
});
}
function updateEtlIndices(etlIndices, lastModified) {
// Update table with the current progress meter (200px * percentage = 2 * percentage points)
var table = "<tr><th>Name</th><th>Current Index</th><th>Final Index</th><th colspan='2'>Complete</th></tr>";
var len = etlIndices.length;
if (len === 0) {
table += "<tr><td colspan='5'>(waiting...)</td></tr>";
}
/* else */
for (var i = 0; i < len; i++) {
var e = etlIndices[i];
var percentage = (100.0 * e.counter) / e.final;
var percentageLabel = (percentage >= 10.0 || percentage < 0.1) ? percentage.toFixed(0) : percentage.toFixed(1);
var indexClass;
if (e.current === e.final) {
indexClass = "progress complete";
} else {
indexClass = "progress pulsing";
}
table += "<tr>" +
"<td>" + e.name + "</td>" +
"<td>" + e.current + "</td>" +
"<td>" + e.final + "</td>" +
"<td>" + percentageLabel + "% </td>" +
"<td class='" + indexClass + "'><div style='width:" + (2 * percentage).toFixed(2) + "px'></div></td>" +
"</tr>";
}
document.getElementById("indices-table").innerHTML = table;
document.getElementById("indices-table-last-modified").textContent = lastModified;
setTimeout(fetchEtlIndices, 1000);
}
function updateEtlEvents(etlEvents, lastModified) {
var table = "<tr>" +
"<th>Index</th><th>Step</th><th>Target Relation</th>" +
"<th title='Latest event received'>Last Event</th><th>Timestamp</th><th>Elapsed</th>" +
"</tr>";
var len = etlEvents.length;
if (len === 0) {
table += "<tr><td colspan='6'>(waiting...)</td></tr>";
}
/* else */
var now = (new Date()).valueOf();
var i;
var e;
for (i = 0; i < len; i++) {
e = etlEvents[i];
var name = e.extra.index.name || "";
var current = e.extra.index.current || "?";
var timestamp = new Date(e.timestamp.replace(' ', 'T')); /* official ISO8601 */
var elapsed = e.elapsed;
var elapsedLabel;
if (elapsed === undefined) {
elapsed = (now - timestamp) / 1000.0;
}
elapsedLabel = elapsed.toFixed(1);
var eventLabel = e.event;
var eventClass = "event-" + eventLabel;
if (eventLabel === "start") {
eventLabel += " <div style='width: 1em'></div>";
eventClass += " progress pulsing";
}
table += "<tr>" +
"<td><a href='/api/events/" + e.monitor_id + "'>" + name + " #" + current + "</a></td>" +
"<td>" + e.step + "</td>" +
"<td class='" + eventClass + "' id='event-" + e.target + "'>" + e.target + "</td>" +
"<td class='" + eventClass + "'>" + eventLabel + "</td>" +
"<td>" + timestamp.toISOString() + " </td>" +
"<td class='right-aligned'> " + elapsedLabel + "s </td>" +
"</tr>";
}
document.getElementById("events-table").innerHTML = table;
document.getElementById("events-table-last-modified").textContent = lastModified;
for (i = 0; i < len; i++) {
e = etlEvents[i];
if (e.event === "fail") {
document.getElementById("event-" + e.target).setAttribute("title", e.errors[0].message);
}
}
setTimeout(fetchEtlEvents, 1000);
}
window.onload = function () {
fetchEtlId();
fetchEtlCommandLine();
fetchEtlIndices();
fetchEtlEvents();
};
|
//主题
var cgi = require('../common/cgi').subject,
subjectList = require('./list'),
subjectInfo = require('./info'),
subjectCreate = require('./create');
var striker = $(window.striker);
//模板引用
var tmpl = {
area : require('../../tpl/subject/size.ejs'),
manage : require('../../tpl/user/manage.ejs'), //管理员
list : require('../../tpl/subject/list.ejs'), //主题列表
head : require('../../tpl/subject/head.ejs'), //主题详情头部
onemanage : require('../../tpl/user/onemanage.ejs'), //单个管理员
aside : require('../../tpl/subject/aside.ejs'), //主题详情右边资源列表
rlist : require('../../tpl/resource/list.ejs') //资源列表
};
var proMap = {
mySubject : '我创建的',
myFollow : '我关注的',
myInvited : '邀请我的',
open : '公开主题',
myArchived : '归档主题'
}
var Subject = {};
module.exports = Subject;
/*定义通用参数*/
var start = 0,
limit = 20;
Subject.search = subjectList.search;
Subject.create = subjectCreate.create;
Subject.info = subjectInfo.info;
Subject.area = function(domname){
var proName = domname,
dom = $('#'+domname+'Block');
this.proName = domname;
this.dom = dom;
this.page = 0; //开始页码
this.allPage = 0;
this.limit = 5; //一页的条数
this.order = 'createTime';//0 按时间排序,1 按更新时间排序
this.listDom; //列表的位置
this.key;
var html = tmpl.area({
proText : proMap[domname],
proName : domname
});
dom.html(html);
this.listDom = $('#'+domname);
this.numDom = $("#"+domname+'Num');
this.prePage = dom.find('.pre-page');
this.nextPage = dom.find('.next-page');
this.timeDom = dom.find('.time');
this.updateDom = dom.find('.update');
this.allNum = 0;
this.loading = false;
this.getDate({
start : this.page*this.limit,
limit : this.limit,
orderby : this.order
});
this.bindAction();
}
//下一页
Subject.area.prototype.next = function(){
if(this.page < this.allPage-1){
this.page++;
this.getDate({
start : this.page*this.limit,
limit : this.limit,
orderby : this.order
});
}
}
//上一页
Subject.area.prototype.pre = function(){
if(this.page > 0){
this.page--;
this.getDate({
start : this.page*this.limit,
limit : this.limit,
orderby : this.order
});
}
}
//打开收起
Subject.area.prototype.close = function(e){
var target = $(e.target);
if(this.listDom.hasClass('hide')){
this.listDom.removeClass('hide');
target.attr('class','arrow-down');
}else{
this.listDom.addClass('hide');
target.attr('class','arrow-up');
}
}
//按发表时间排序
Subject.area.prototype.orderbytime = function(){
// orderby: updateTime / createTime
this.order = 'createTime';
this.timeDom.addClass('active');
this.updateDom.removeClass('active');
this.getDate({
start : this.page*this.limit,
limit : this.limit,
orderby : this.order
});
}
//按更新时间排序
Subject.area.prototype.orderbyupdate = function(){
this.order = 'updateTime';
this.updateDom.addClass('active');
this.timeDom.removeClass('active');
this.getDate({
start : this.page*this.limit,
limit : this.limit,
orderby : this.order
});
}
//新建主题
Subject.area.prototype.create = function(){
if(!this.createSubject){
this.createSubject = window.striker.createSubject;
}
if(!this.label){
this.label = window.striker.label;
}
this.createSubject.changeType(this.proName);
//this.label.init();
}
//判断翻页是否可以点击
Subject.area.prototype.checkPage = function(){
if(this.page <= 1){
this.prePage.addClass('disabled');
if(this.allPage === 1){
this.nextPage.prop({disabled:true}).addClass('disabled');
}else{
this.nextPage.prop({disabled:false}).removeClass('disabled');
}
}else if(this.page >= this.allPage-1){
this.nextPage.prop({disabled:true}).addClass('disabled');
if(this.allPage === 1){
this.prePage.prop({disabled:true}).addClass('disabled');
}else{
this.prePage.prop({disabled:false}).removeClass('disabled');
}
}
}
//修改总数
Subject.area.prototype.changeNum = function(num){
this.allPage = Math.ceil(num/this.limit);
this.allNum = num;
this.numDom.text(num);
}
Subject.area.prototype.getDate = function(param){
if(this.loading){
return;
}
var _this = this;
this.loading = true;
var funname = 'search';
if(this.proName === 'myFollow'){
funname = 'following';
}else if (this.proName === 'myInvited'){
funname = 'invited';
}else if (this.proName === 'myArchived'){
funname = 'archived';
}else if (this.proName === 'open'){
param.private = 1;
}else if(this.proName === 'mySubject'){
funname = 'list';
}
cgi[funname](param,function(res){
_this.loading = false;
if(res.code === 0){
var html = tmpl.list(res.data);
console.log(html);
_this.listDom.html(html);
_this.changeNum(res.data.total);
_this.checkPage();
}
});
}
/*
考虑到首页结构的特殊性,这里分块绑定事件
*/
Subject.area.prototype.bindAction = function(){
var _this = this;
this.dom.bind('click',function(e){
var target = $(e.target),
action = target.data('action');
if(_this[action]){
_this[action](e);
}
});
striker.bind('subjectCreated',function(){
if('mySubject' === _this.proName){
_this.allNum++;
_this.changeNum(_this.allNum);
}
});
striker.bind('startSearch',function(e,d){
_this.key = d;
_this.page = 0;
if(_this.proName === 'mySubject'){
_this.getDate({
start : _this.page*_this.limit,
limit : _this.limit,
orderby : _this.order,
keyword : _this.key
});
}
});
}
Subject.init = function(type){
subjectList.init(type,cgi,tmpl);
subjectInfo.init(type,cgi,tmpl);
subjectCreate.init(type,cgi,tmpl);
} |
const Chance = require('chance');
const chance = new Chance();
module.exports = chance;
|
import React from 'react';
import R from '../../js/Requisition.js';
const parseToTime = time => {
const minutes = Math.floor(time % 3600 / 60);
const seconds = Math.floor(time % 3600 % 60);
return `${minutes}:${seconds < 10 ? "0" + seconds : seconds}`
};
const favorite = musicID => {
R.addFavorite(musicID, () => {
console.log('Successfully added');
//DOES NOTHING
}, statusCode => {
});
};
const handleFavorite = props => {
if (props.music.favorited === false) {
favorite(props.music.id);
props.changeFavorite(props.music, true);
} else if (props.music.favorited === true) {
unfavorite(props.music.id);
props.changeFavorite(props.music, false);
} else
$('#myModal').modal('show');
};
const MusicItemWeekly = props => {
return(
<div className="col-lg-4 col-md-12 padding_right40">
<div className="ms_weekly_box">
<div className="weekly_left">
<span className="w_top_no">
{props.count < 10 ? `0${props.count}` : props.count}
</span>
<div className="w_top_song">
<div className="w_tp_song_img">
<img src={props.music.posterURL ? props.music.posterURL : './images/weekly/song1.jpg'}
alt="" className="img-fluid"/>
<div className="ms_song_overlay">
</div>
<div className="ms_play_icon" onClick={() => props.onPlayPause(props.music)}>
<img src={`./images/svg/${props.paused ? 'play.svg' : 'pause.svg'}`} alt=""/>
</div>
</div>
<div className="w_tp_song_name">
<h3><a href="#">{props.music.name}</a></h3>
<p>{
props.music.authors ? props.music.authors[0].name : 'No authors'}
</p>
</div>
</div>
</div>
<div className="weekly_right">
<span className="w_song_time">{parseToTime(props.music.duration)}</span>
<span className="ms_more_icon" data-other="1">
<img src="./images/svg/more.svg" alt=""/>
</span>
</div>
<ul className="more_option">
<li><a href="javascript:;" onClick={() => handleFavorite(props)}><span className="opt_icon"><span
className="icon icon_fav"/></span>{props.music.favorited ? 'Remove Favourite' : 'Add To Favourites'}</a></li>
</ul>
</div>
</div>
);
};
export default MusicItemWeekly;
|
import { arrayRemoveItem } from '../../utils'
const initialState = {
map: {},
idsMap: {
all: [],
waitPay: [],
waitDelivery: [],
waitReceive: [],
waitEvaluate: [],
saleSupport: []
},
pagingMap: {
all: { page: 1, limit: 10, finished: false },
waitPay: { page: 1, limit: 10, finished: false },
waitDelivery: { page: 1, limit: 10, finished: false },
waitReceive: { page: 1, limit: 10, finished: false },
waitEvaluate: { page: 1, limit: 10, finished: false },
saleSupport: { page: 1, limit: 10, finished: false }
},
orderType: null
}
let id
const mine = function (state = initialState, action) {
switch (action.type) {
case 'SET_MINE_ORDER_TYPE':
const { orderType } = action.payload
return { ...state, orderType }
case 'SET_MINE_ORDERS':
const { orderType: _orderType, pagingMap } = state
const { orders, paging } = action.payload
pagingMap[_orderType] = paging
orders.map(order => {
const { orderId: id } = order
state.idsMap[_orderType].push(id)
state.map[id] = order
})
return { ...state, pagingMap }
case 'SET_MINE_ORDER_DETAIL':
id = action.payload.id
const { order } = action.payload
state.map[id] = { ...state.map[id], ...order }
return { ...state }
case 'UPDATE_ORDER_SHARE_STATUS':
case 'CLEAER_ORDERS':
const { orderId, expressId, merchId } = action.payload
// @TODO: update => instead of simple clear
state.map = {}
Object.keys(state.idsMap).map(key => state.idsMap[key] = [])
Object.keys(state.pagingMap).map(key => state.pagingMap[key] = { page: 1, limit: 10, finished: false })
return { ...state }
case 'DELETE_ORDER':
id = action.payload.id
state.idsMap.waitPay = arrayRemoveItem(state.idsMap.waitPay, id)
state.idsMap.all = arrayRemoveItem(state.idsMap.all, id)
delete state.map[id]
return { ...state }
default:
return state
}
}
export default mine
|
// Compiled by ClojureScript 0.0-3211 {:optimize-constants true, :static-fns true}
goog.provide('reagent.impl.util');
goog.require('cljs.core');
goog.require('clojure.string');
goog.require('reagent.interop');
goog.require('reagent.debug');
reagent.impl.util.is_client = (typeof window !== 'undefined') && (!(((window["document"]) == null)));
reagent.impl.util.extract_props = (function reagent$impl$util$extract_props(v){
var p = cljs.core.nth.cljs$core$IFn$_invoke$arity$3(v,(1),null);
if(cljs.core.map_QMARK_(p)){
return p;
} else {
return null;
}
});
reagent.impl.util.extract_children = (function reagent$impl$util$extract_children(v){
var p = cljs.core.nth.cljs$core$IFn$_invoke$arity$3(v,(1),null);
var first_child = ((((p == null)) || (cljs.core.map_QMARK_(p)))?(2):(1));
if((cljs.core.count(v) > first_child)){
return cljs.core.subvec.cljs$core$IFn$_invoke$arity$2(v,first_child);
} else {
return null;
}
});
reagent.impl.util.get_argv = (function reagent$impl$util$get_argv(c){
return (c["props"]["argv"]);
});
reagent.impl.util.get_props = (function reagent$impl$util$get_props(c){
return reagent.impl.util.extract_props((c["props"]["argv"]));
});
reagent.impl.util.get_children = (function reagent$impl$util$get_children(c){
return reagent.impl.util.extract_children((c["props"]["argv"]));
});
reagent.impl.util.reagent_component_QMARK_ = (function reagent$impl$util$reagent_component_QMARK_(c){
return !(((c["props"]["argv"]) == null));
});
reagent.impl.util.cached_react_class = (function reagent$impl$util$cached_react_class(c){
return (c["cljsReactClass"]);
});
reagent.impl.util.cache_react_class = (function reagent$impl$util$cache_react_class(c,constructor){
return (c["cljsReactClass"] = constructor);
});
reagent.impl.util.memoize_1 = (function reagent$impl$util$memoize_1(f){
var mem = (function (){var G__10859 = cljs.core.PersistentArrayMap.EMPTY;
return (cljs.core.atom.cljs$core$IFn$_invoke$arity$1 ? cljs.core.atom.cljs$core$IFn$_invoke$arity$1(G__10859) : cljs.core.atom.call(null,G__10859));
})();
return ((function (mem){
return (function (arg){
var v = cljs.core.get.cljs$core$IFn$_invoke$arity$2((function (){var G__10860 = mem;
return (cljs.core.deref.cljs$core$IFn$_invoke$arity$1 ? cljs.core.deref.cljs$core$IFn$_invoke$arity$1(G__10860) : cljs.core.deref.call(null,G__10860));
})(),arg);
if(!((v == null))){
return v;
} else {
var ret = (function (){var G__10861 = arg;
return (f.cljs$core$IFn$_invoke$arity$1 ? f.cljs$core$IFn$_invoke$arity$1(G__10861) : f.call(null,G__10861));
})();
cljs.core.swap_BANG_.cljs$core$IFn$_invoke$arity$4(mem,cljs.core.assoc,arg,ret);
return ret;
}
});
;})(mem))
});
reagent.impl.util.dont_camel_case = new cljs.core.PersistentHashSet(null, new cljs.core.PersistentArrayMap(null, 2, ["aria",null,"data",null], null), null);
reagent.impl.util.capitalize = (function reagent$impl$util$capitalize(s){
if((cljs.core.count(s) < (2))){
return clojure.string.upper_case(s);
} else {
return [cljs.core.str(clojure.string.upper_case(cljs.core.subs.cljs$core$IFn$_invoke$arity$3(s,(0),(1)))),cljs.core.str(cljs.core.subs.cljs$core$IFn$_invoke$arity$2(s,(1)))].join('');
}
});
reagent.impl.util.dash_to_camel = (function reagent$impl$util$dash_to_camel(dashed){
if(typeof dashed === 'string'){
return dashed;
} else {
var name_str = cljs.core.name(dashed);
var vec__10864 = clojure.string.split.cljs$core$IFn$_invoke$arity$2(name_str,/-/);
var start = cljs.core.nth.cljs$core$IFn$_invoke$arity$3(vec__10864,(0),null);
var parts = cljs.core.nthnext(vec__10864,(1));
if(cljs.core.truth_((function (){var G__10865 = start;
return (reagent.impl.util.dont_camel_case.cljs$core$IFn$_invoke$arity$1 ? reagent.impl.util.dont_camel_case.cljs$core$IFn$_invoke$arity$1(G__10865) : reagent.impl.util.dont_camel_case.call(null,G__10865));
})())){
return name_str;
} else {
return cljs.core.apply.cljs$core$IFn$_invoke$arity$3(cljs.core.str,start,cljs.core.map.cljs$core$IFn$_invoke$arity$2(reagent.impl.util.capitalize,parts));
}
}
});
/**
* @constructor
*/
reagent.impl.util.partial_ifn = (function (f,args,p){
this.f = f;
this.args = args;
this.p = p;
this.cljs$lang$protocol_mask$partition1$ = 0;
this.cljs$lang$protocol_mask$partition0$ = 6291457;
})
reagent.impl.util.partial_ifn.prototype.cljs$core$IHash$_hash$arity$1 = (function (_){
var self__ = this;
var ___$1 = this;
return cljs.core.hash(new cljs.core.PersistentVector(null, 2, 5, cljs.core.PersistentVector.EMPTY_NODE, [self__.f,self__.args], null));
});
reagent.impl.util.partial_ifn.prototype.cljs$core$IEquiv$_equiv$arity$2 = (function (_,other){
var self__ = this;
var ___$1 = this;
return (cljs.core._EQ_.cljs$core$IFn$_invoke$arity$2(self__.f,other.f)) && (cljs.core._EQ_.cljs$core$IFn$_invoke$arity$2(self__.args,other.args));
});
reagent.impl.util.partial_ifn.prototype.call = (function() {
var G__10867__delegate = function (self__,a){
var self____$1 = this;
var _ = self____$1;
var or__4335__auto___10868 = self__.p;
if(cljs.core.truth_(or__4335__auto___10868)){
} else {
self__.p = cljs.core.apply.cljs$core$IFn$_invoke$arity$3(cljs.core.partial,self__.f,self__.args);
}
return cljs.core.apply.cljs$core$IFn$_invoke$arity$2(self__.p,a);
};
var G__10867 = function (self__,var_args){
var self__ = this;
var a = null;
if (arguments.length > 1) {
var G__10869__i = 0, G__10869__a = new Array(arguments.length - 1);
while (G__10869__i < G__10869__a.length) {G__10869__a[G__10869__i] = arguments[G__10869__i + 1]; ++G__10869__i;}
a = new cljs.core.IndexedSeq(G__10869__a,0);
}
return G__10867__delegate.call(this,self__,a);};
G__10867.cljs$lang$maxFixedArity = 1;
G__10867.cljs$lang$applyTo = (function (arglist__10870){
var self__ = cljs.core.first(arglist__10870);
var a = cljs.core.rest(arglist__10870);
return G__10867__delegate(self__,a);
});
G__10867.cljs$core$IFn$_invoke$arity$variadic = G__10867__delegate;
return G__10867;
})()
;
reagent.impl.util.partial_ifn.prototype.apply = (function (self__,args10866){
var self__ = this;
var self____$1 = this;
return self____$1.call.apply(self____$1,[self____$1].concat(cljs.core.aclone(args10866)));
});
reagent.impl.util.partial_ifn.prototype.cljs$core$IFn$_invoke$arity$2 = (function() {
var G__10871__delegate = function (a){
var _ = this;
var or__4335__auto___10872 = self__.p;
if(cljs.core.truth_(or__4335__auto___10872)){
} else {
self__.p = cljs.core.apply.cljs$core$IFn$_invoke$arity$3(cljs.core.partial,self__.f,self__.args);
}
return cljs.core.apply.cljs$core$IFn$_invoke$arity$2(self__.p,a);
};
var G__10871 = function (var_args){
var self__ = this;
var a = null;
if (arguments.length > 0) {
var G__10873__i = 0, G__10873__a = new Array(arguments.length - 0);
while (G__10873__i < G__10873__a.length) {G__10873__a[G__10873__i] = arguments[G__10873__i + 0]; ++G__10873__i;}
a = new cljs.core.IndexedSeq(G__10873__a,0);
}
return G__10871__delegate.call(this,a);};
G__10871.cljs$lang$maxFixedArity = 0;
G__10871.cljs$lang$applyTo = (function (arglist__10874){
var a = cljs.core.seq(arglist__10874);
return G__10871__delegate(a);
});
G__10871.cljs$core$IFn$_invoke$arity$variadic = G__10871__delegate;
return G__10871;
})()
;
reagent.impl.util.partial_ifn.cljs$lang$type = true;
reagent.impl.util.partial_ifn.cljs$lang$ctorStr = "reagent.impl.util/partial-ifn";
reagent.impl.util.partial_ifn.cljs$lang$ctorPrWriter = (function (this__4914__auto__,writer__4915__auto__,opt__4916__auto__){
return cljs.core._write(writer__4915__auto__,"reagent.impl.util/partial-ifn");
});
reagent.impl.util.__GT_partial_ifn = (function reagent$impl$util$__GT_partial_ifn(f,args,p){
return (new reagent.impl.util.partial_ifn(f,args,p));
});
reagent.impl.util.merge_class = (function reagent$impl$util$merge_class(p1,p2){
var class$ = (function (){var temp__4126__auto__ = cljs.core.constant$keyword$class.cljs$core$IFn$_invoke$arity$1(p1);
if(cljs.core.truth_(temp__4126__auto__)){
var c1 = temp__4126__auto__;
var temp__4126__auto____$1 = cljs.core.constant$keyword$class.cljs$core$IFn$_invoke$arity$1(p2);
if(cljs.core.truth_(temp__4126__auto____$1)){
var c2 = temp__4126__auto____$1;
return [cljs.core.str(c1),cljs.core.str(" "),cljs.core.str(c2)].join('');
} else {
return null;
}
} else {
return null;
}
})();
if((class$ == null)){
return p2;
} else {
return cljs.core.assoc.cljs$core$IFn$_invoke$arity$3(p2,cljs.core.constant$keyword$class,class$);
}
});
reagent.impl.util.merge_style = (function reagent$impl$util$merge_style(p1,p2){
var style = (function (){var temp__4126__auto__ = cljs.core.constant$keyword$style.cljs$core$IFn$_invoke$arity$1(p1);
if(cljs.core.truth_(temp__4126__auto__)){
var s1 = temp__4126__auto__;
var temp__4126__auto____$1 = cljs.core.constant$keyword$style.cljs$core$IFn$_invoke$arity$1(p2);
if(cljs.core.truth_(temp__4126__auto____$1)){
var s2 = temp__4126__auto____$1;
return cljs.core.merge.cljs$core$IFn$_invoke$arity$variadic(cljs.core.array_seq([s1,s2], 0));
} else {
return null;
}
} else {
return null;
}
})();
if((style == null)){
return p2;
} else {
return cljs.core.assoc.cljs$core$IFn$_invoke$arity$3(p2,cljs.core.constant$keyword$style,style);
}
});
reagent.impl.util.merge_props = (function reagent$impl$util$merge_props(p1,p2){
if((p1 == null)){
return p2;
} else {
if(cljs.core.map_QMARK_(p1)){
} else {
throw (new Error([cljs.core.str("Assert failed: "),cljs.core.str(cljs.core.pr_str.cljs$core$IFn$_invoke$arity$variadic(cljs.core.array_seq([cljs.core.list(new cljs.core.Symbol(null,"map?","map?",-1780568534,null),new cljs.core.Symbol(null,"p1","p1",703771573,null))], 0)))].join('')));
}
return reagent.impl.util.merge_style(p1,reagent.impl.util.merge_class(p1,cljs.core.merge.cljs$core$IFn$_invoke$arity$variadic(cljs.core.array_seq([p1,p2], 0))));
}
});
reagent.impl.util._STAR_always_update_STAR_ = false;
if(typeof reagent.impl.util.roots !== 'undefined'){
} else {
reagent.impl.util.roots = (function (){var G__10875 = cljs.core.PersistentArrayMap.EMPTY;
return (cljs.core.atom.cljs$core$IFn$_invoke$arity$1 ? cljs.core.atom.cljs$core$IFn$_invoke$arity$1(G__10875) : cljs.core.atom.call(null,G__10875));
})();
}
reagent.impl.util.clear_container = (function reagent$impl$util$clear_container(node){
try{return (React["unmountComponentAtNode"])(node);
}catch (e10877){if((e10877 instanceof Object)){
var e = e10877;
if(typeof console !== 'undefined'){
console.warn([cljs.core.str("Warning: "),cljs.core.str("Error unmounting:")].join(''));
} else {
}
if(typeof console !== 'undefined'){
return console.log(e);
} else {
return null;
}
} else {
throw e10877;
}
}});
reagent.impl.util.render_component = (function reagent$impl$util$render_component(comp,container,callback){
try{var _STAR_always_update_STAR_10882 = reagent.impl.util._STAR_always_update_STAR_;
reagent.impl.util._STAR_always_update_STAR_ = true;
try{return (React["render"])((function (){return (comp.cljs$core$IFn$_invoke$arity$0 ? comp.cljs$core$IFn$_invoke$arity$0() : comp.call(null));
})(),container,((function (_STAR_always_update_STAR_10882){
return (function (){
var _STAR_always_update_STAR_10883 = reagent.impl.util._STAR_always_update_STAR_;
reagent.impl.util._STAR_always_update_STAR_ = false;
try{cljs.core.swap_BANG_.cljs$core$IFn$_invoke$arity$4(reagent.impl.util.roots,cljs.core.assoc,container,new cljs.core.PersistentVector(null, 2, 5, cljs.core.PersistentVector.EMPTY_NODE, [comp,container], null));
if(cljs.core.some_QMARK_(callback)){
return (callback.cljs$core$IFn$_invoke$arity$0 ? callback.cljs$core$IFn$_invoke$arity$0() : callback.call(null));
} else {
return null;
}
}finally {reagent.impl.util._STAR_always_update_STAR_ = _STAR_always_update_STAR_10883;
}});})(_STAR_always_update_STAR_10882))
);
}finally {reagent.impl.util._STAR_always_update_STAR_ = _STAR_always_update_STAR_10882;
}}catch (e10881){if((e10881 instanceof Object)){
var e = e10881;
reagent.impl.util.clear_container(container);
throw e;
} else {
throw e10881;
}
}});
reagent.impl.util.re_render_component = (function reagent$impl$util$re_render_component(comp,container){
return reagent.impl.util.render_component(comp,container,null);
});
reagent.impl.util.unmount_component_at_node = (function reagent$impl$util$unmount_component_at_node(container){
cljs.core.swap_BANG_.cljs$core$IFn$_invoke$arity$3(reagent.impl.util.roots,cljs.core.dissoc,container);
return (React["unmountComponentAtNode"])(container);
});
reagent.impl.util.force_update_all = (function reagent$impl$util$force_update_all(){
var seq__10889_10894 = cljs.core.seq(cljs.core.vals((function (){var G__10893 = reagent.impl.util.roots;
return (cljs.core.deref.cljs$core$IFn$_invoke$arity$1 ? cljs.core.deref.cljs$core$IFn$_invoke$arity$1(G__10893) : cljs.core.deref.call(null,G__10893));
})()));
var chunk__10890_10895 = null;
var count__10891_10896 = (0);
var i__10892_10897 = (0);
while(true){
if((i__10892_10897 < count__10891_10896)){
var v_10898 = chunk__10890_10895.cljs$core$IIndexed$_nth$arity$2(null,i__10892_10897);
cljs.core.apply.cljs$core$IFn$_invoke$arity$2(reagent.impl.util.re_render_component,v_10898);
var G__10899 = seq__10889_10894;
var G__10900 = chunk__10890_10895;
var G__10901 = count__10891_10896;
var G__10902 = (i__10892_10897 + (1));
seq__10889_10894 = G__10899;
chunk__10890_10895 = G__10900;
count__10891_10896 = G__10901;
i__10892_10897 = G__10902;
continue;
} else {
var temp__4126__auto___10903 = cljs.core.seq(seq__10889_10894);
if(temp__4126__auto___10903){
var seq__10889_10904__$1 = temp__4126__auto___10903;
if(cljs.core.chunked_seq_QMARK_(seq__10889_10904__$1)){
var c__5120__auto___10905 = cljs.core.chunk_first(seq__10889_10904__$1);
var G__10906 = cljs.core.chunk_rest(seq__10889_10904__$1);
var G__10907 = c__5120__auto___10905;
var G__10908 = cljs.core.count(c__5120__auto___10905);
var G__10909 = (0);
seq__10889_10894 = G__10906;
chunk__10890_10895 = G__10907;
count__10891_10896 = G__10908;
i__10892_10897 = G__10909;
continue;
} else {
var v_10910 = cljs.core.first(seq__10889_10904__$1);
cljs.core.apply.cljs$core$IFn$_invoke$arity$2(reagent.impl.util.re_render_component,v_10910);
var G__10911 = cljs.core.next(seq__10889_10904__$1);
var G__10912 = null;
var G__10913 = (0);
var G__10914 = (0);
seq__10889_10894 = G__10911;
chunk__10890_10895 = G__10912;
count__10891_10896 = G__10913;
i__10892_10897 = G__10914;
continue;
}
} else {
}
}
break;
}
return "Updated";
});
|
import React, { useRef, useState, useEffect } from "react";
import "./QuestionsContainer.css";
import QuestionsTitle from "./QuestionsTitle";
import InputAnswer from "./InputAnswer";
// import getQuestionsData from "../dumData.json";
import InputSubmit from "../componant/InputSubmit";
import ScoreBord from "./ScoreBord";
import useFetch from "../utilities/useFetch";
import right from "../img/right.gif";
import losGif from "../img/wrongAnswer.gif";
import winPhoto from "../img/win.gif";
import wrongAnswerPhoto from "../img/wrong.gif";
const QuestionsContainer = () => {
const [getQuestionsData, setQuestionsData] = useState({});
const [questionIndex, setQuestionIndex] = useState(0);
const [answer, setAnswer] = useState();
const [gameOver, setGameOver] = useState(false);
const [correct, setCorrect] = useState(0);
const [wrong, setWrong] = useState(0);
const [win, setWin] = useState("");
const [los, setLos] = useState("");
const [gifCorrect, setGifCorrect] = useState(false);
const [gifWrong, setGifWrong] = useState(false);
const input = useRef();
const { isLoading, error, clearError, sendRequest } = useFetch();
const fetchQuestion = async (url) => {
const data = await sendRequest(url);
setQuestionsData(data);
};
const postQuestion = async () => {
const url = "http://localhost:5000/api/get-answer";
const body = {
_id: getQuestionsData[questionIndex]._id,
num: getQuestionsData[questionIndex].Number,
answer,
};
const request = {
method: "POST",
body: JSON.stringify(body),
headers: { "Content-Type": "application/json" },
};
let getAnswer;
try {
getAnswer = await sendRequest(
url,
request.method,
request.body,
request.headers
);
} catch (err) {
console.log("request not send", err);
}
if (getAnswer.answer === true) {
setCorrect(correct + 1);
setGifCorrect(true);
} else {
setWrong(wrong + 1);
setGifWrong(true);
}
};
useEffect(() => {
fetchQuestion("http://localhost:5000/api/questions");
}, [questionIndex]);
useEffect(() => {
setTimeout(() => {
setGifCorrect(false);
setGifWrong(false);
}, 1300);
}, [correct, wrong]);
const score = (num) => {
if (parseInt(answer) === getQuestionsData[num].answer) {
setCorrect(correct.scor + 1);
setGifCorrect(true);
} else {
setWrong(wrong + 1);
setLos(true);
}
};
const changeHandler = (e) => {
setAnswer(e.target.value);
};
const submitHandler = (e) => {
e.preventDefault();
postQuestion();
if (questionIndex === getQuestionsData.length - 1) {
setGameOver(true);
} else {
setQuestionIndex(questionIndex + 1);
}
score(questionIndex);
addScore();
setAnswer("");
input.current.focus();
};
const restartHnadler = () => {
setQuestionIndex(0);
setGameOver(false);
setCorrect(0);
setWrong(0);
};
const addScore = () => {
if (correct > wrong) {
setWin("You Win");
} else {
setWin("You Lose");
}
};
return (
<div className="main">
<div className="container">
{isLoading && <div>LOADING ... </div>}
{error && <div>SORRY SOMETHING WENT WRONG ... </div>}
{gifCorrect && <img src={right} alt="correct" />}
{gifWrong && <img src={wrongAnswerPhoto} alt="wrong" />}
{!gifCorrect && !gifWrong && gameOver ? (
<ScoreBord
onclick={restartHnadler}
scor={win}
correct={correct}
wrong={wrong}
/>
) : (
getQuestionsData.length &&
!gifCorrect &&
!gifWrong && (
<>
<h1>Question{getQuestionsData[questionIndex].Number}</h1>
<p>What is the result :</p>
<div className="questions_container">
<QuestionsTitle
questionText={getQuestionsData[questionIndex].question}
/>
{/* <InputAnswer onChange={changeHandler} value={answer} ref={input} /> */}
<input
className="answer"
type="text"
onChange={changeHandler}
value={answer}
autoFocus
ref={input}
/>
</div>
<InputSubmit onclick={submitHandler} />
</>
)
)}
</div>
<div className="gif_container">
{correct > wrong && gameOver && !gifWrong && !gifWrong && (
<img src={winPhoto} alt="win" />
)}
{correct < wrong && gameOver && !gifWrong && !gifCorrect && (
<img src={losGif} alt="win" />
)}
</div>
</div>
);
};
export default QuestionsContainer;
|
// 函数作用域和块级作用域
function foo(a) {
var b = 2
function bar() {
}
var c = 3
}
// a, b, c bar 仅仅在foo 内部可以使用
// 最小授权原则
(function () {
function doSomething(a) {
b = a + doSomethingElse(a * 2)
console.log(b * 3)
}
function doSomethingElse(a) {
return a - 1
}
var b
doSomething(3)
})()
// 上述可能导致doSomethingElse被异常使用
// 更“合理” 的设计会将这些私有的具体内容隐藏在 doSomething(..) 内部, 例如:
;(function () {
function doSomething(a) {
function doSomethingElse(a) {
return a - 1
}
var b
b = a + doSomethingElse(a * 2)
console.log(b * 3)
}
doSomething(3)
})()
try {
console.log(a)
} catch (e) {
console.log(e)
}
// 我们习惯将 var a = 2; 看作一个声明,而实际上 JavaScript 引擎并不这么认为。它将 var a
// 和 a = 2 当作两个单独的声明,第一个是编译阶段的任务,而第二个则是执行阶段的任务。
// 这意味着无论作用域中的声明出现在什么地方,都将在代码本身被执行前首先进行处理。
// 可以将这个过程形象地想象成所有的声明(变量和函数)都会被“移动”到各自作用域的
// 最顶端,这个过程被称为提升。
// 声明本身会被提升,而包括函数表达式的赋值在内的赋值操作并不会提升。
//
|
import { observable } from 'mobx'
import { AuthStore } from './authStore'
import { UiStore } from './uiStore'
import { ProductsStore } from './productsStore'
import { ListsStore } from './listsStore'
import { PurchasesStore } from './purchasesStore'
import { SearchStore } from './searchStore'
import { KeyChainStore } from './KeyChainStore'
import { BuyForMe } from '../../Services/BuyForMe/BuyForMe'
export default new class {
@observable authStore
@observable uiStore
@observable productsStore
@observable listsStore
@observable purchasesStore
@observable searchStore
@observable keyChainStore
@observable buyForMeStore
constructor() {
this.authStore = new AuthStore()
this.uiStore = new UiStore()
this.productsStore = new ProductsStore()
this.listsStore = new ListsStore(this)
this.purchasesStore = new PurchasesStore(this)
this.searchStore = new SearchStore()
this.keyChainStore = new KeyChainStore()
this.buyForMeStore = new BuyForMe()
}
}()
|
import { useState } from 'react';
function useModal(initialMode = false) {
const [isModalOpen, setModalOpen] = useState(initialMode);
function toggleModal() {
setModalOpen((prev) => !prev);
}
return {
isModalOpen,
toggleModal,
setModalOpen,
};
}
export default useModal;
|
import { useStore } from 'vuex'
export function getLogin() {
const store = useStore();
if(sessionStorage)
if(sessionStorage.getItem('informationUser') != undefined && sessionStorage.getItem('loggedIn') != undefined && sessionStorage.getItem('informationUser') != undefined){
store.state.informationLogin = JSON.parse(sessionStorage.getItem('informationLogin'));
store.state.loggedIn = JSON.parse(sessionStorage.getItem('loggedIn'));
store.state.informationUser = JSON.parse(sessionStorage.getItem('informationUser'));
}
} |
define(
[
'require',
'jquery',
'underscore',
'backbone',
'marionette',
'js/login',
'js/routers/loginrouter',
'js/controllers/logincontroller',
'js/models/error',
'js/layouts/login/loginLayout'
],
function(
require,
$,
_,
Backbone,
Marionette,
Login,
Router,
Controller,
Error,
LoginLayout
) {
return function(error) {
console.log("Wavity login starting initialization ...");
if ( (typeof(error) !== "undefined") && (error !== null) && (error.length > 0) && (error !== "null") ) {
Login.Error = new Error({code: error, context: 'authentication'});
}
Login.Controller = new Controller();
Login.Router = new Router({ controller: Login.Controller });
Login.Layout = new LoginLayout();
Login.start();
console.log("... finished Wavity login initialization.");
}
});
// EOF
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.